xref: /linux/tools/lib/bpf/libbpf.c (revision cd7a395838cbf76f5162fa48ff4a531be518fc43)
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 	/* the program or a function that it calls has callx */
501 	bool has_callx;
502 	bool mark_btf_static;
503 	enum bpf_prog_type type;
504 	enum bpf_attach_type expected_attach_type;
505 	int exception_cb_idx;
506 
507 	int prog_ifindex;
508 	__u32 attach_btf_obj_fd;
509 	__u32 attach_btf_id;
510 	__u32 attach_prog_fd;
511 
512 	void *func_info;
513 	__u32 func_info_rec_size;
514 	__u32 func_info_cnt;
515 
516 	void *line_info;
517 	__u32 line_info_rec_size;
518 	__u32 line_info_cnt;
519 	__u32 prog_flags;
520 	__u8  hash[SHA256_DIGEST_LENGTH];
521 
522 	struct bpf_light_subprog *subprogs;
523 	__u32 subprog_cnt;
524 };
525 
526 struct bpf_struct_ops {
527 	struct bpf_program **progs;
528 	__u32 *kern_func_off;
529 	/* e.g. struct tcp_congestion_ops in bpf_prog's btf format */
530 	void *data;
531 	/* e.g. struct bpf_struct_ops_tcp_congestion_ops in
532 	 *      btf_vmlinux's format.
533 	 * struct bpf_struct_ops_tcp_congestion_ops {
534 	 *	[... some other kernel fields ...]
535 	 *	struct tcp_congestion_ops data;
536 	 * }
537 	 * kern_vdata-size == sizeof(struct bpf_struct_ops_tcp_congestion_ops)
538 	 * bpf_map__init_kern_struct_ops() will populate the "kern_vdata"
539 	 * from "data".
540 	 */
541 	void *kern_vdata;
542 	__u32 type_id;
543 };
544 
545 #define DATA_SEC ".data"
546 #define PERCPU_SEC ".percpu"
547 #define BSS_SEC ".bss"
548 #define RODATA_SEC ".rodata"
549 #define DATA_REL_RO_SEC ".data.rel.ro"
550 #define KCONFIG_SEC ".kconfig"
551 #define KSYMS_SEC ".ksyms"
552 #define STRUCT_OPS_SEC ".struct_ops"
553 #define STRUCT_OPS_LINK_SEC ".struct_ops.link"
554 #define ARENA_SEC ".addr_space.1"
555 /*
556  * An object with this section keeps its global data in arena instead of
557  * array maps. What is in the section doesn't matter. .data, .bss and .rodata
558  * sections become a part of the arena map of the object, like __arena global
559  * variables are. If the object doesn't declare an arena map libbpf creates
560  * one that is just large enough for the data. bpf_object__find_map_by_name()
561  * finds it by the name "arena" and bpf_map__set_max_entries() changes its
562  * size before the object is loaded.
563  * Read-only sections with pointers to functions and sections with constant
564  * strings stay frozen array maps. A constant that a helper or a kfunc takes
565  * by pointer has to be in such section.
566  * Pointers to data that are stored in data become addresses of arena.
567  * The load fails if such pointer points to a section that is not in arena,
568  * or if the arena is pinned or reused.
569  *
570  * It's for programs written in Rust. There are no address spaces in Rust,
571  * the program accesses arena through plain numbers, so programs of the object
572  * are loaded with BPF_F_ARENA_SCALAR.
573  */
574 #define ARENA_DATA_SEC ".arena.data"
575 
576 enum libbpf_map_type {
577 	LIBBPF_MAP_UNSPEC,
578 	LIBBPF_MAP_DATA,
579 	LIBBPF_MAP_BSS,
580 	LIBBPF_MAP_RODATA,
581 	LIBBPF_MAP_KCONFIG,
582 	LIBBPF_MAP_PERCPU,
583 };
584 
585 struct bpf_map_def {
586 	unsigned int type;
587 	unsigned int key_size;
588 	unsigned int value_size;
589 	unsigned int max_entries;
590 	unsigned int map_flags;
591 };
592 
593 struct bpf_map {
594 	struct bpf_object *obj;
595 	char *name;
596 	/* real_name is defined for special internal maps (.rodata*,
597 	 * .data*, .bss, .kconfig) and preserves their original ELF section
598 	 * name. This is important to be able to find corresponding BTF
599 	 * DATASEC information.
600 	 */
601 	char *real_name;
602 	int fd;
603 	int sec_idx;
604 	size_t sec_offset;
605 	int map_ifindex;
606 	int inner_map_fd;
607 	struct bpf_map_def def;
608 	__u32 numa_node;
609 	__u32 btf_var_idx;
610 	int mod_btf_fd;
611 	__u32 btf_key_type_id;
612 	__u32 btf_value_type_id;
613 	__u32 btf_vmlinux_value_type_id;
614 	enum libbpf_map_type libbpf_type;
615 	void *mmaped;
616 	struct bpf_struct_ops *st_ops;
617 	struct bpf_map *inner_map;
618 	void **init_slots;
619 	int init_slots_sz;
620 	char *pin_path;
621 	bool pinned;
622 	bool reused;
623 	bool autocreate;
624 	bool autoattach;
625 	__u64 map_extra;
626 	struct bpf_program *excl_prog;
627 	/* pointers to functions in the data of an internal map, see obj->func_ptrs */
628 	struct func_ptr *func_ptrs;
629 	size_t func_ptr_cnt;
630 	/*
631 	 * Data of the internal map is a part of arena data at arena_off.
632 	 * The map is not created, unless it's a copy that is in arena.
633 	 */
634 	bool in_arena;
635 	bool arena_copy;
636 	size_t arena_off;
637 };
638 
639 enum extern_type {
640 	EXT_UNKNOWN,
641 	EXT_KCFG,
642 	EXT_KSYM,
643 };
644 
645 enum kcfg_type {
646 	KCFG_UNKNOWN,
647 	KCFG_CHAR,
648 	KCFG_BOOL,
649 	KCFG_INT,
650 	KCFG_TRISTATE,
651 	KCFG_CHAR_ARR,
652 };
653 
654 struct extern_desc {
655 	enum extern_type type;
656 	int sym_idx;
657 	int btf_id;
658 	int sec_btf_id;
659 	char *name;
660 	char *essent_name;
661 	bool is_set;
662 	bool is_weak;
663 	union {
664 		struct {
665 			enum kcfg_type type;
666 			int sz;
667 			int align;
668 			int data_off;
669 			bool is_signed;
670 		} kcfg;
671 		struct {
672 			unsigned long long addr;
673 
674 			/* target btf_id of the corresponding kernel var. */
675 			int kernel_btf_obj_fd;
676 			int kernel_btf_id;
677 
678 			/* local btf_id of the ksym extern's type. */
679 			__u32 type_id;
680 			/* BTF fd index to be patched in for insn->off, this is
681 			 * 0 for vmlinux BTF, index in obj->fd_array for module
682 			 * BTF
683 			 */
684 			__s16 btf_fd_idx;
685 		} ksym;
686 	};
687 };
688 
689 struct module_btf {
690 	struct btf *btf;
691 	char *name;
692 	__u32 id;
693 	int fd;
694 	int fd_array_idx;
695 };
696 
697 enum sec_type {
698 	SEC_UNUSED = 0,
699 	SEC_RELO,
700 	SEC_BSS,
701 	SEC_DATA,
702 	SEC_RODATA,
703 	SEC_ST_OPS,
704 	SEC_PERCPU,
705 };
706 
707 struct elf_sec_desc {
708 	enum sec_type sec_type;
709 	Elf64_Shdr *shdr;
710 	Elf_Data *data;
711 };
712 
713 struct elf_state {
714 	int fd;
715 	const void *obj_buf;
716 	size_t obj_buf_sz;
717 	Elf *elf;
718 	Elf64_Ehdr *ehdr;
719 	Elf_Data *symbols;
720 	Elf_Data *arena_data;
721 	size_t shstrndx; /* section index for section name strings */
722 	size_t strtabidx;
723 	struct elf_sec_desc *secs;
724 	size_t sec_cnt;
725 	int btf_maps_shndx;
726 	__u32 btf_maps_sec_btf_id;
727 	int text_shndx;
728 	int symbols_shndx;
729 	bool has_st_ops;
730 	int arena_data_shndx;
731 	int jumptables_data_shndx;
732 };
733 
734 struct usdt_manager;
735 
736 enum bpf_object_state {
737 	OBJ_OPEN,
738 	OBJ_PREPARED,
739 	OBJ_LOADED,
740 };
741 
742 struct bpf_object {
743 	char name[BPF_OBJ_NAME_LEN];
744 	char license[64];
745 	__u32 kern_version;
746 
747 	enum bpf_object_state state;
748 	struct bpf_program *programs;
749 	size_t nr_programs;
750 	struct bpf_map *maps;
751 	size_t nr_maps;
752 	size_t maps_cap;
753 
754 	char *kconfig;
755 	struct extern_desc *externs;
756 	int nr_extern;
757 	int kconfig_map_idx;
758 
759 	bool has_subcalls;
760 	bool has_rodata;
761 
762 	struct bpf_gen *gen_loader;
763 
764 	/* Information when doing ELF related work. Only valid if efile.elf is not NULL */
765 	struct elf_state efile;
766 
767 	unsigned char byteorder;
768 
769 	struct btf *btf;
770 	struct btf_ext *btf_ext;
771 
772 	/* Parse and load BTF vmlinux if any of the programs in the object need
773 	 * it at load time.
774 	 */
775 	struct btf *btf_vmlinux;
776 	/* Path to the custom BTF to be used for BPF CO-RE relocations as an
777 	 * override for vmlinux BTF.
778 	 */
779 	char *btf_custom_path;
780 	/* vmlinux BTF override for CO-RE relocations */
781 	struct btf *btf_vmlinux_override;
782 	/* Lazily initialized kernel module BTFs */
783 	struct module_btf *btf_modules;
784 	bool btf_modules_loaded;
785 	size_t btf_module_cnt;
786 	size_t btf_module_cap;
787 	char **btf_module_allowlist;
788 	ssize_t btf_module_allowlist_cnt;
789 
790 	/* optional log settings passed to BPF_BTF_LOAD and BPF_PROG_LOAD commands */
791 	char *log_buf;
792 	size_t log_size;
793 	__u32 log_level;
794 
795 	int *fd_array;
796 	size_t fd_array_cap;
797 	/*
798 	 * Slots handed out so far, slot 0 included. A kfunc insn names a module
799 	 * BTF slot through its offset, slot 0 stands for vmlinux BTF and stays
800 	 * empty, so the array goes to the kernel without a count, unless
801 	 * bpf_object__bind_arena() puts the arena of the object there.
802 	 */
803 	size_t fd_array_used;
804 
805 	struct usdt_manager *usdt_man;
806 
807 	int arena_map_idx;
808 	void *arena_data;
809 	size_t arena_data_sz;
810 	size_t arena_data_off;
811 	bool data_in_arena;
812 	bool arena_mapped;
813 	/* pointers to data in the data of internal maps, when data is in arena */
814 	struct data_ptr {
815 		int sec_idx;
816 		size_t sec_off;
817 		int targ_sec_idx;
818 		size_t targ_off;
819 		char *sym_name;
820 	} *data_ptrs;
821 	size_t data_ptr_cnt;
822 
823 	void *jumptables_data;
824 	size_t jumptables_data_sz;
825 
826 	struct {
827 		struct bpf_program *prog;
828 		unsigned int sym_off;
829 		int fd;
830 	} *jumptable_maps;
831 	size_t jumptable_map_cnt;
832 
833 	/*
834 	 * Pointers to functions found in read-only data sections: tables of
835 	 * functions, structures of operations, vtables. Sorted by section
836 	 * and offset.
837 	 */
838 	struct func_ptr {
839 		int sec_idx;		/* ELF section that contains the pointer */
840 		size_t sec_off;		/* offset of the pointer in the section */
841 		size_t text_off;	/* offset of the function in .text section */
842 	} *func_ptrs;
843 	size_t func_ptr_cnt;
844 
845 	/*
846 	 * Read-only data with pointers to functions is different for every
847 	 * program that uses it, because so are the offsets of the functions.
848 	 */
849 	struct {
850 		struct bpf_program *prog;
851 		int map_idx;
852 		int fd;
853 	} *func_ptr_maps;
854 	size_t func_ptr_map_cnt;
855 
856 	struct kern_feature_cache *feat_cache;
857 	char *token_path;
858 	int token_fd;
859 
860 	char path[];
861 };
862 
863 static const char *elf_sym_str(const struct bpf_object *obj, size_t off);
864 static const char *elf_sec_str(const struct bpf_object *obj, size_t off);
865 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx);
866 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name);
867 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn);
868 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn);
869 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn);
870 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx);
871 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx);
872 
873 void bpf_program__unload(struct bpf_program *prog)
874 {
875 	if (!prog)
876 		return;
877 
878 	zclose(prog->fd);
879 
880 	zfree(&prog->func_info);
881 	zfree(&prog->line_info);
882 	zfree(&prog->subprogs);
883 }
884 
885 static void bpf_program__exit(struct bpf_program *prog)
886 {
887 	if (!prog)
888 		return;
889 
890 	bpf_program__unload(prog);
891 	zfree(&prog->name);
892 	zfree(&prog->sec_name);
893 	zfree(&prog->insns);
894 	zfree(&prog->reloc_desc);
895 
896 	prog->nr_reloc = 0;
897 	prog->insns_cnt = 0;
898 	prog->sec_idx = -1;
899 }
900 
901 static bool insn_is_subprog_call(const struct bpf_insn *insn)
902 {
903 	return BPF_CLASS(insn->code) == BPF_JMP &&
904 	       BPF_OP(insn->code) == BPF_CALL &&
905 	       BPF_SRC(insn->code) == BPF_K &&
906 	       insn->src_reg == BPF_PSEUDO_CALL &&
907 	       insn->dst_reg == 0 &&
908 	       insn->off == 0;
909 }
910 
911 static bool is_call_insn(const struct bpf_insn *insn)
912 {
913 	return insn->code == (BPF_JMP | BPF_CALL);
914 }
915 
916 static bool insn_is_pseudo_func(struct bpf_insn *insn)
917 {
918 	return is_ldimm64_insn(insn) && insn->src_reg == BPF_PSEUDO_FUNC;
919 }
920 
921 static bool prog_has_callx(const struct bpf_program *prog)
922 {
923 	size_t i;
924 
925 	for (i = 0; i < prog->insns_cnt; i++)
926 		if (prog->insns[i].code == (BPF_JMP | BPF_CALL | BPF_X))
927 			return true;
928 	return false;
929 }
930 
931 static int
932 bpf_object__init_prog(struct bpf_object *obj, struct bpf_program *prog,
933 		      const char *name, size_t sec_idx, const char *sec_name,
934 		      size_t sec_off, void *insn_data, size_t insn_data_sz)
935 {
936 	if (insn_data_sz == 0 || insn_data_sz % BPF_INSN_SZ || sec_off % BPF_INSN_SZ) {
937 		pr_warn("sec '%s': corrupted program '%s', offset %zu, size %zu\n",
938 			sec_name, name, sec_off, insn_data_sz);
939 		return -EINVAL;
940 	}
941 
942 	memset(prog, 0, sizeof(*prog));
943 	prog->obj = obj;
944 
945 	prog->sec_idx = sec_idx;
946 	prog->sec_insn_off = sec_off / BPF_INSN_SZ;
947 	prog->sec_insn_cnt = insn_data_sz / BPF_INSN_SZ;
948 	/* insns_cnt can later be increased by appending used subprograms */
949 	prog->insns_cnt = prog->sec_insn_cnt;
950 
951 	prog->type = BPF_PROG_TYPE_UNSPEC;
952 	prog->fd = -1;
953 	prog->exception_cb_idx = -1;
954 
955 	/* libbpf's convention for SEC("?abc...") is that it's just like
956 	 * SEC("abc...") but the corresponding bpf_program starts out with
957 	 * autoload set to false.
958 	 */
959 	if (sec_name[0] == '?') {
960 		prog->autoload = false;
961 		/* from now on forget there was ? in section name */
962 		sec_name++;
963 	} else {
964 		prog->autoload = true;
965 	}
966 
967 	prog->autoattach = true;
968 
969 	/* inherit object's log_level */
970 	prog->log_level = obj->log_level;
971 
972 	prog->sec_name = strdup(sec_name);
973 	if (!prog->sec_name)
974 		goto errout;
975 
976 	prog->name = strdup(name);
977 	if (!prog->name)
978 		goto errout;
979 
980 	prog->insns = malloc(insn_data_sz);
981 	if (!prog->insns)
982 		goto errout;
983 	memcpy(prog->insns, insn_data, insn_data_sz);
984 
985 	return 0;
986 errout:
987 	pr_warn("sec '%s': failed to allocate memory for prog '%s'\n", sec_name, name);
988 	bpf_program__exit(prog);
989 	return -ENOMEM;
990 }
991 
992 static int
993 bpf_object__add_programs(struct bpf_object *obj, Elf_Data *sec_data,
994 			 const char *sec_name, int sec_idx)
995 {
996 	Elf_Data *symbols = obj->efile.symbols;
997 	struct bpf_program *prog, *progs;
998 	void *data = sec_data->d_buf;
999 	size_t sec_sz = sec_data->d_size, sec_off, prog_sz, nr_syms;
1000 	int nr_progs, err, i;
1001 	const char *name;
1002 	Elf64_Sym *sym;
1003 
1004 	progs = obj->programs;
1005 	nr_progs = obj->nr_programs;
1006 	nr_syms = symbols->d_size / sizeof(Elf64_Sym);
1007 
1008 	for (i = 0; i < nr_syms; i++) {
1009 		sym = elf_sym_by_idx(obj, i);
1010 
1011 		if (sym->st_shndx != sec_idx)
1012 			continue;
1013 		if (ELF64_ST_TYPE(sym->st_info) != STT_FUNC)
1014 			continue;
1015 
1016 		prog_sz = sym->st_size;
1017 		sec_off = sym->st_value;
1018 
1019 		name = elf_sym_str(obj, sym->st_name);
1020 		if (!name) {
1021 			pr_warn("sec '%s': failed to get symbol name for offset %zu\n",
1022 				sec_name, sec_off);
1023 			return -LIBBPF_ERRNO__FORMAT;
1024 		}
1025 
1026 		if (sec_off + prog_sz > sec_sz || sec_off + prog_sz < sec_off) {
1027 			pr_warn("sec '%s': program at offset %zu crosses section boundary\n",
1028 				sec_name, sec_off);
1029 			return -LIBBPF_ERRNO__FORMAT;
1030 		}
1031 
1032 		if (sec_idx != obj->efile.text_shndx && ELF64_ST_BIND(sym->st_info) == STB_LOCAL) {
1033 			pr_warn("sec '%s': program '%s' is static and not supported\n", sec_name, name);
1034 			return -ENOTSUP;
1035 		}
1036 
1037 		pr_debug("sec '%s': found program '%s' at insn offset %zu (%zu bytes), code size %zu insns (%zu bytes)\n",
1038 			 sec_name, name, sec_off / BPF_INSN_SZ, sec_off, prog_sz / BPF_INSN_SZ, prog_sz);
1039 
1040 		progs = libbpf_reallocarray(progs, nr_progs + 1, sizeof(*progs));
1041 		if (!progs) {
1042 			/*
1043 			 * In this case the original obj->programs
1044 			 * is still valid, so don't need special treat for
1045 			 * bpf_close_object().
1046 			 */
1047 			pr_warn("sec '%s': failed to alloc memory for new program '%s'\n",
1048 				sec_name, name);
1049 			return -ENOMEM;
1050 		}
1051 		obj->programs = progs;
1052 
1053 		prog = &progs[nr_progs];
1054 
1055 		err = bpf_object__init_prog(obj, prog, name, sec_idx, sec_name,
1056 					    sec_off, data + sec_off, prog_sz);
1057 		if (err)
1058 			return err;
1059 
1060 		if (ELF64_ST_BIND(sym->st_info) != STB_LOCAL)
1061 			prog->sym_global = true;
1062 
1063 		/* if function is a global/weak symbol, but has restricted
1064 		 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF FUNC
1065 		 * as static to enable more permissive BPF verification mode
1066 		 * with more outside context available to BPF verifier
1067 		 */
1068 		if (prog->sym_global && (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
1069 		    || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL))
1070 			prog->mark_btf_static = true;
1071 
1072 		nr_progs++;
1073 		obj->nr_programs = nr_progs;
1074 	}
1075 
1076 	return 0;
1077 }
1078 
1079 static void bpf_object_bswap_progs(struct bpf_object *obj)
1080 {
1081 	struct bpf_program *prog = obj->programs;
1082 	struct bpf_insn *insn;
1083 	int p, i;
1084 
1085 	for (p = 0; p < obj->nr_programs; p++, prog++) {
1086 		insn = prog->insns;
1087 		for (i = 0; i < prog->insns_cnt; i++, insn++)
1088 			bpf_insn_bswap(insn);
1089 	}
1090 	pr_debug("converted %zu BPF programs to native byte order\n", obj->nr_programs);
1091 }
1092 
1093 static const struct btf_member *
1094 find_member_by_offset(const struct btf_type *t, __u32 bit_offset)
1095 {
1096 	struct btf_member *m;
1097 	int i;
1098 
1099 	for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
1100 		if (btf_member_bit_offset(t, i) == bit_offset)
1101 			return m;
1102 	}
1103 
1104 	return NULL;
1105 }
1106 
1107 static const struct btf_member *
1108 find_member_by_name(const struct btf *btf, const struct btf_type *t,
1109 		    const char *name)
1110 {
1111 	struct btf_member *m;
1112 	int i;
1113 
1114 	for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
1115 		if (!strcmp(btf__name_by_offset(btf, m->name_off), name))
1116 			return m;
1117 	}
1118 
1119 	return NULL;
1120 }
1121 
1122 static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
1123 			    __u16 kind, struct btf **res_btf,
1124 			    struct module_btf **res_mod_btf);
1125 
1126 #define STRUCT_OPS_VALUE_PREFIX "bpf_struct_ops_"
1127 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
1128 				   const char *name, __u32 kind);
1129 
1130 static int
1131 find_struct_ops_kern_types(struct bpf_object *obj, const char *tname_raw,
1132 			   struct module_btf **mod_btf,
1133 			   const struct btf_type **type, __u32 *type_id,
1134 			   const struct btf_type **vtype, __u32 *vtype_id,
1135 			   const struct btf_member **data_member)
1136 {
1137 	const struct btf_type *kern_type, *kern_vtype;
1138 	const struct btf_member *kern_data_member;
1139 	struct btf *btf = NULL;
1140 	__s32 kern_vtype_id, kern_type_id;
1141 	char tname[192], stname[256];
1142 	__u32 i;
1143 
1144 	snprintf(tname, sizeof(tname), "%.*s",
1145 		 (int)bpf_core_essential_name_len(tname_raw), tname_raw);
1146 
1147 	snprintf(stname, sizeof(stname), "%s%s", STRUCT_OPS_VALUE_PREFIX, tname);
1148 
1149 	/* Look for the corresponding "map_value" type that will be used
1150 	 * in map_update(BPF_MAP_TYPE_STRUCT_OPS) first, figure out the btf
1151 	 * and the mod_btf.
1152 	 * For example, find "struct bpf_struct_ops_tcp_congestion_ops".
1153 	 */
1154 	kern_vtype_id = find_ksym_btf_id(obj, stname, BTF_KIND_STRUCT, &btf, mod_btf);
1155 	if (kern_vtype_id < 0) {
1156 		pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n", stname);
1157 		return kern_vtype_id;
1158 	}
1159 	kern_vtype = btf__type_by_id(btf, kern_vtype_id);
1160 
1161 	kern_type_id = btf__find_by_name_kind(btf, tname, BTF_KIND_STRUCT);
1162 	if (kern_type_id < 0) {
1163 		pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n", tname);
1164 		return kern_type_id;
1165 	}
1166 	kern_type = btf__type_by_id(btf, kern_type_id);
1167 
1168 	/* Find "struct tcp_congestion_ops" from
1169 	 * struct bpf_struct_ops_tcp_congestion_ops {
1170 	 *	[ ... ]
1171 	 *	struct tcp_congestion_ops data;
1172 	 * }
1173 	 */
1174 	kern_data_member = btf_members(kern_vtype);
1175 	for (i = 0; i < btf_vlen(kern_vtype); i++, kern_data_member++) {
1176 		if (kern_data_member->type == kern_type_id)
1177 			break;
1178 	}
1179 	if (i == btf_vlen(kern_vtype)) {
1180 		pr_warn("struct_ops init_kern: struct %s data is not found in struct %s\n",
1181 			tname, stname);
1182 		return -EINVAL;
1183 	}
1184 
1185 	*type = kern_type;
1186 	*type_id = kern_type_id;
1187 	*vtype = kern_vtype;
1188 	*vtype_id = kern_vtype_id;
1189 	*data_member = kern_data_member;
1190 
1191 	return 0;
1192 }
1193 
1194 static bool bpf_map__is_struct_ops(const struct bpf_map *map)
1195 {
1196 	return map->def.type == BPF_MAP_TYPE_STRUCT_OPS;
1197 }
1198 
1199 static bool is_valid_st_ops_program(struct bpf_object *obj,
1200 				    const struct bpf_program *prog)
1201 {
1202 	int i;
1203 
1204 	for (i = 0; i < obj->nr_programs; i++) {
1205 		if (&obj->programs[i] == prog)
1206 			return prog->type == BPF_PROG_TYPE_STRUCT_OPS;
1207 	}
1208 
1209 	return false;
1210 }
1211 
1212 /* For each struct_ops program P, referenced from some struct_ops map M,
1213  * enable P.autoload if there are Ms for which M.autocreate is true,
1214  * disable P.autoload if for all Ms M.autocreate is false.
1215  * Don't change P.autoload for programs that are not referenced from any maps.
1216  */
1217 static int bpf_object_adjust_struct_ops_autoload(struct bpf_object *obj)
1218 {
1219 	struct bpf_program *prog, *slot_prog;
1220 	struct bpf_map *map;
1221 	int i, j, k, vlen;
1222 
1223 	for (i = 0; i < obj->nr_programs; ++i) {
1224 		int should_load = false;
1225 		int use_cnt = 0;
1226 
1227 		prog = &obj->programs[i];
1228 		if (prog->type != BPF_PROG_TYPE_STRUCT_OPS)
1229 			continue;
1230 
1231 		for (j = 0; j < obj->nr_maps; ++j) {
1232 			const struct btf_type *type;
1233 
1234 			map = &obj->maps[j];
1235 			if (!bpf_map__is_struct_ops(map))
1236 				continue;
1237 
1238 			type = btf__type_by_id(obj->btf, map->st_ops->type_id);
1239 			vlen = btf_vlen(type);
1240 			for (k = 0; k < vlen; ++k) {
1241 				slot_prog = map->st_ops->progs[k];
1242 				if (prog != slot_prog)
1243 					continue;
1244 
1245 				use_cnt++;
1246 				if (map->autocreate)
1247 					should_load = true;
1248 			}
1249 		}
1250 		if (use_cnt)
1251 			prog->autoload = should_load;
1252 	}
1253 
1254 	return 0;
1255 }
1256 
1257 /* Init the map's fields that depend on kern_btf */
1258 static int bpf_map__init_kern_struct_ops(struct bpf_map *map)
1259 {
1260 	const struct btf_member *member, *kern_member, *kern_data_member;
1261 	const struct btf_type *type, *kern_type, *kern_vtype;
1262 	__u32 i, kern_type_id, kern_vtype_id, kern_data_off;
1263 	struct bpf_object *obj = map->obj;
1264 	const struct btf *btf = obj->btf;
1265 	struct bpf_struct_ops *st_ops;
1266 	const struct btf *kern_btf;
1267 	struct module_btf *mod_btf = NULL;
1268 	void *data, *kern_data;
1269 	const char *tname;
1270 	int err;
1271 
1272 	st_ops = map->st_ops;
1273 	type = btf__type_by_id(btf, st_ops->type_id);
1274 	tname = btf__name_by_offset(btf, type->name_off);
1275 	err = find_struct_ops_kern_types(obj, tname, &mod_btf,
1276 					 &kern_type, &kern_type_id,
1277 					 &kern_vtype, &kern_vtype_id,
1278 					 &kern_data_member);
1279 	if (err)
1280 		return err;
1281 
1282 	kern_btf = mod_btf ? mod_btf->btf : obj->btf_vmlinux;
1283 
1284 	pr_debug("struct_ops init_kern %s: type_id:%u kern_type_id:%u kern_vtype_id:%u\n",
1285 		 map->name, st_ops->type_id, kern_type_id, kern_vtype_id);
1286 
1287 	map->mod_btf_fd = mod_btf ? mod_btf->fd : -1;
1288 	map->def.value_size = kern_vtype->size;
1289 	map->btf_vmlinux_value_type_id = kern_vtype_id;
1290 
1291 	st_ops->kern_vdata = calloc(1, kern_vtype->size);
1292 	if (!st_ops->kern_vdata)
1293 		return -ENOMEM;
1294 
1295 	data = st_ops->data;
1296 	kern_data_off = kern_data_member->offset / 8;
1297 	kern_data = st_ops->kern_vdata + kern_data_off;
1298 
1299 	member = btf_members(type);
1300 	for (i = 0; i < btf_vlen(type); i++, member++) {
1301 		const struct btf_type *mtype, *kern_mtype;
1302 		__u32 mtype_id, kern_mtype_id;
1303 		void *mdata, *kern_mdata;
1304 		struct bpf_program *prog;
1305 		__s64 msize, kern_msize;
1306 		__u32 moff, kern_moff;
1307 		__u32 kern_member_idx;
1308 		const char *mname;
1309 
1310 		mname = btf__name_by_offset(btf, member->name_off);
1311 		if (btf_member_bitfield_size(type, i)) {
1312 			pr_warn("struct_ops init_kern %s: local bitfield %s is not supported\n",
1313 				map->name, mname);
1314 			return -ENOTSUP;
1315 		}
1316 
1317 		moff = member->offset / 8;
1318 		mdata = data + moff;
1319 		msize = btf__resolve_size(btf, member->type);
1320 		if (msize < 0) {
1321 			pr_warn("struct_ops init_kern %s: failed to resolve the size of member %s\n",
1322 				map->name, mname);
1323 			return msize;
1324 		}
1325 
1326 		kern_member = find_member_by_name(kern_btf, kern_type, mname);
1327 		if (!kern_member) {
1328 			if (!libbpf_is_mem_zeroed(mdata, msize)) {
1329 				pr_warn("struct_ops init_kern %s: Cannot find member %s in kernel BTF\n",
1330 					map->name, mname);
1331 				return -ENOTSUP;
1332 			}
1333 
1334 			if (st_ops->progs[i]) {
1335 				/* If we had declaratively set struct_ops callback, we need to
1336 				 * force its autoload to false, because it doesn't have
1337 				 * a chance of succeeding from POV of the current struct_ops map.
1338 				 * If this program is still referenced somewhere else, though,
1339 				 * then bpf_object_adjust_struct_ops_autoload() will update its
1340 				 * autoload accordingly.
1341 				 */
1342 				st_ops->progs[i]->autoload = false;
1343 				st_ops->progs[i] = NULL;
1344 			}
1345 
1346 			/* Skip all-zero/NULL fields if they are not present in the kernel BTF */
1347 			pr_info("struct_ops %s: member %s not found in kernel, skipping it as it's set to zero\n",
1348 				map->name, mname);
1349 			continue;
1350 		}
1351 
1352 		kern_member_idx = kern_member - btf_members(kern_type);
1353 		if (btf_member_bitfield_size(kern_type, kern_member_idx)) {
1354 			pr_warn("struct_ops init_kern %s: bitfield %s is not supported\n",
1355 				map->name, mname);
1356 			return -ENOTSUP;
1357 		}
1358 
1359 		kern_moff = kern_member->offset / 8;
1360 		kern_mdata = kern_data + kern_moff;
1361 
1362 		mtype = skip_mods_and_typedefs(btf, member->type, &mtype_id);
1363 		kern_mtype = skip_mods_and_typedefs(kern_btf, kern_member->type,
1364 						    &kern_mtype_id);
1365 		if (BTF_INFO_KIND(mtype->info) !=
1366 		    BTF_INFO_KIND(kern_mtype->info)) {
1367 			pr_warn("struct_ops init_kern %s: Unmatched member type %s %u != %u(kernel)\n",
1368 				map->name, mname, BTF_INFO_KIND(mtype->info),
1369 				BTF_INFO_KIND(kern_mtype->info));
1370 			return -ENOTSUP;
1371 		}
1372 
1373 		if (btf_is_ptr(mtype)) {
1374 			prog = *(void **)mdata;
1375 			/* just like for !kern_member case above, reset declaratively
1376 			 * set (at compile time) program's autload to false,
1377 			 * if user replaced it with another program or NULL
1378 			 */
1379 			if (st_ops->progs[i] && st_ops->progs[i] != prog)
1380 				st_ops->progs[i]->autoload = false;
1381 
1382 			/* Update the value from the shadow type */
1383 			st_ops->progs[i] = prog;
1384 			if (!prog)
1385 				continue;
1386 
1387 			if (!is_valid_st_ops_program(obj, prog)) {
1388 				pr_warn("struct_ops init_kern %s: member %s is not a struct_ops program\n",
1389 					map->name, mname);
1390 				return -ENOTSUP;
1391 			}
1392 
1393 			kern_mtype = skip_mods_and_typedefs(kern_btf,
1394 							    kern_mtype->type,
1395 							    &kern_mtype_id);
1396 
1397 			/* mtype->type must be a func_proto which was
1398 			 * guaranteed in bpf_object__collect_st_ops_relos(),
1399 			 * so only check kern_mtype for func_proto here.
1400 			 */
1401 			if (!btf_is_func_proto(kern_mtype)) {
1402 				pr_warn("struct_ops init_kern %s: kernel member %s is not a func ptr\n",
1403 					map->name, mname);
1404 				return -ENOTSUP;
1405 			}
1406 
1407 			if (mod_btf)
1408 				prog->attach_btf_obj_fd = mod_btf->fd;
1409 
1410 			/* if we haven't yet processed this BPF program, record proper
1411 			 * attach_btf_id and member_idx
1412 			 */
1413 			if (!prog->attach_btf_id) {
1414 				prog->attach_btf_id = kern_type_id;
1415 				prog->expected_attach_type = kern_member_idx;
1416 			}
1417 
1418 			/* struct_ops BPF prog can be re-used between multiple
1419 			 * .struct_ops & .struct_ops.link as long as it's the
1420 			 * same struct_ops struct definition and the same
1421 			 * function pointer field
1422 			 */
1423 			if (prog->attach_btf_id != kern_type_id) {
1424 				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",
1425 					map->name, mname, prog->name, prog->sec_name, prog->type,
1426 					prog->attach_btf_id, kern_type_id);
1427 				return -EINVAL;
1428 			}
1429 			if (prog->expected_attach_type != kern_member_idx) {
1430 				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",
1431 					map->name, mname, prog->name, prog->sec_name, prog->type,
1432 					prog->expected_attach_type, kern_member_idx);
1433 				return -EINVAL;
1434 			}
1435 
1436 			st_ops->kern_func_off[i] = kern_data_off + kern_moff;
1437 
1438 			pr_debug("struct_ops init_kern %s: func ptr %s is set to prog %s from data(+%u) to kern_data(+%u)\n",
1439 				 map->name, mname, prog->name, moff,
1440 				 kern_moff);
1441 
1442 			continue;
1443 		}
1444 
1445 		kern_msize = btf__resolve_size(kern_btf, kern_mtype_id);
1446 		if (kern_msize < 0 || msize != kern_msize) {
1447 			pr_warn("struct_ops init_kern %s: Error in size of member %s: %zd != %zd(kernel)\n",
1448 				map->name, mname, (ssize_t)msize,
1449 				(ssize_t)kern_msize);
1450 			return -ENOTSUP;
1451 		}
1452 
1453 		pr_debug("struct_ops init_kern %s: copy %s %u bytes from data(+%u) to kern_data(+%u)\n",
1454 			 map->name, mname, (unsigned int)msize,
1455 			 moff, kern_moff);
1456 		memcpy(kern_mdata, mdata, msize);
1457 	}
1458 
1459 	return 0;
1460 }
1461 
1462 static int bpf_object__init_kern_struct_ops_maps(struct bpf_object *obj)
1463 {
1464 	struct bpf_map *map;
1465 	size_t i;
1466 	int err;
1467 
1468 	for (i = 0; i < obj->nr_maps; i++) {
1469 		map = &obj->maps[i];
1470 
1471 		if (!bpf_map__is_struct_ops(map))
1472 			continue;
1473 
1474 		if (!map->autocreate)
1475 			continue;
1476 
1477 		err = bpf_map__init_kern_struct_ops(map);
1478 		if (err)
1479 			return err;
1480 	}
1481 
1482 	return 0;
1483 }
1484 
1485 static int init_struct_ops_maps(struct bpf_object *obj, const char *sec_name,
1486 				int shndx, Elf_Data *data)
1487 {
1488 	const struct btf_type *type, *datasec;
1489 	const struct btf_var_secinfo *vsi;
1490 	struct bpf_struct_ops *st_ops;
1491 	const char *tname, *var_name;
1492 	__s32 type_id, datasec_id;
1493 	const struct btf *btf;
1494 	struct bpf_map *map;
1495 	__u32 i;
1496 
1497 	if (shndx == -1)
1498 		return 0;
1499 
1500 	btf = obj->btf;
1501 	datasec_id = btf__find_by_name_kind(btf, sec_name,
1502 					    BTF_KIND_DATASEC);
1503 	if (datasec_id < 0) {
1504 		pr_warn("struct_ops init: DATASEC %s not found\n",
1505 			sec_name);
1506 		return -EINVAL;
1507 	}
1508 
1509 	datasec = btf__type_by_id(btf, datasec_id);
1510 	vsi = btf_var_secinfos(datasec);
1511 	for (i = 0; i < btf_vlen(datasec); i++, vsi++) {
1512 		type = btf__type_by_id(obj->btf, vsi->type);
1513 		var_name = btf__name_by_offset(obj->btf, type->name_off);
1514 
1515 		type_id = btf__resolve_type(obj->btf, vsi->type);
1516 		if (type_id < 0) {
1517 			pr_warn("struct_ops init: Cannot resolve var type_id %u in DATASEC %s\n",
1518 				vsi->type, sec_name);
1519 			return -EINVAL;
1520 		}
1521 
1522 		type = btf__type_by_id(obj->btf, type_id);
1523 		tname = btf__name_by_offset(obj->btf, type->name_off);
1524 		if (!tname[0]) {
1525 			pr_warn("struct_ops init: anonymous type is not supported\n");
1526 			return -ENOTSUP;
1527 		}
1528 		if (!btf_is_struct(type)) {
1529 			pr_warn("struct_ops init: %s is not a struct\n", tname);
1530 			return -EINVAL;
1531 		}
1532 
1533 		map = bpf_object__add_map(obj);
1534 		if (IS_ERR(map))
1535 			return PTR_ERR(map);
1536 
1537 		map->sec_idx = shndx;
1538 		map->sec_offset = vsi->offset;
1539 		map->name = strdup(var_name);
1540 		if (!map->name)
1541 			return -ENOMEM;
1542 		map->btf_value_type_id = type_id;
1543 
1544 		/* Follow same convention as for programs autoload:
1545 		 * SEC("?.struct_ops") means map is not created by default.
1546 		 */
1547 		if (sec_name[0] == '?') {
1548 			map->autocreate = false;
1549 			/* from now on forget there was ? in section name */
1550 			sec_name++;
1551 		}
1552 
1553 		map->def.type = BPF_MAP_TYPE_STRUCT_OPS;
1554 		map->def.key_size = sizeof(int);
1555 		map->def.value_size = type->size;
1556 		map->def.max_entries = 1;
1557 		map->def.map_flags = strcmp(sec_name, STRUCT_OPS_LINK_SEC) == 0 ? BPF_F_LINK : 0;
1558 		map->autoattach = true;
1559 
1560 		map->st_ops = calloc(1, sizeof(*map->st_ops));
1561 		if (!map->st_ops)
1562 			return -ENOMEM;
1563 		st_ops = map->st_ops;
1564 		st_ops->data = malloc(type->size);
1565 		st_ops->progs = calloc(btf_vlen(type), sizeof(*st_ops->progs));
1566 		st_ops->kern_func_off = malloc(btf_vlen(type) *
1567 					       sizeof(*st_ops->kern_func_off));
1568 		if (!st_ops->data || !st_ops->progs || !st_ops->kern_func_off)
1569 			return -ENOMEM;
1570 
1571 		if (vsi->offset + type->size > data->d_size) {
1572 			pr_warn("struct_ops init: var %s is beyond the end of DATASEC %s\n",
1573 				var_name, sec_name);
1574 			return -EINVAL;
1575 		}
1576 
1577 		memcpy(st_ops->data,
1578 		       data->d_buf + vsi->offset,
1579 		       type->size);
1580 		st_ops->type_id = type_id;
1581 
1582 		pr_debug("struct_ops init: struct %s(type_id=%d) %s found at offset %u\n",
1583 			 tname, type_id, var_name, vsi->offset);
1584 	}
1585 
1586 	return 0;
1587 }
1588 
1589 static int bpf_object_init_struct_ops(struct bpf_object *obj)
1590 {
1591 	const char *sec_name;
1592 	int sec_idx, err;
1593 
1594 	for (sec_idx = 0; sec_idx < obj->efile.sec_cnt; ++sec_idx) {
1595 		struct elf_sec_desc *desc = &obj->efile.secs[sec_idx];
1596 
1597 		if (desc->sec_type != SEC_ST_OPS)
1598 			continue;
1599 
1600 		sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1601 		if (!sec_name)
1602 			return -LIBBPF_ERRNO__FORMAT;
1603 
1604 		err = init_struct_ops_maps(obj, sec_name, sec_idx, desc->data);
1605 		if (err)
1606 			return err;
1607 	}
1608 
1609 	return 0;
1610 }
1611 
1612 static struct bpf_object *bpf_object__new(const char *path,
1613 					  const void *obj_buf,
1614 					  size_t obj_buf_sz,
1615 					  const char *obj_name)
1616 {
1617 	struct bpf_object *obj;
1618 	char *end;
1619 
1620 	obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
1621 	if (!obj) {
1622 		pr_warn("alloc memory failed for %s\n", path);
1623 		return ERR_PTR(-ENOMEM);
1624 	}
1625 
1626 	strcpy(obj->path, path);
1627 	if (obj_name) {
1628 		libbpf_strlcpy(obj->name, obj_name, sizeof(obj->name));
1629 	} else {
1630 		/* Using basename() GNU version which doesn't modify arg. */
1631 		libbpf_strlcpy(obj->name, basename((void *)path), sizeof(obj->name));
1632 		end = strchr(obj->name, '.');
1633 		if (end)
1634 			*end = 0;
1635 	}
1636 
1637 	obj->efile.fd = -1;
1638 	/*
1639 	 * Caller of this function should also call
1640 	 * bpf_object__elf_finish() after data collection to return
1641 	 * obj_buf to user. If not, we should duplicate the buffer to
1642 	 * avoid user freeing them before elf finish.
1643 	 */
1644 	obj->efile.obj_buf = obj_buf;
1645 	obj->efile.obj_buf_sz = obj_buf_sz;
1646 	obj->efile.btf_maps_shndx = -1;
1647 	obj->efile.arena_data_shndx = -1;
1648 	obj->kconfig_map_idx = -1;
1649 	obj->arena_map_idx = -1;
1650 
1651 	obj->kern_version = get_kernel_version();
1652 	obj->state  = OBJ_OPEN;
1653 
1654 	return obj;
1655 }
1656 
1657 static void bpf_object__elf_finish(struct bpf_object *obj)
1658 {
1659 	if (!obj->efile.elf)
1660 		return;
1661 
1662 	elf_end(obj->efile.elf);
1663 	obj->efile.elf = NULL;
1664 	obj->efile.ehdr = NULL;
1665 	obj->efile.symbols = NULL;
1666 	obj->efile.arena_data = NULL;
1667 
1668 	zfree(&obj->efile.secs);
1669 	obj->efile.sec_cnt = 0;
1670 	zclose(obj->efile.fd);
1671 	obj->efile.obj_buf = NULL;
1672 	obj->efile.obj_buf_sz = 0;
1673 }
1674 
1675 static int bpf_object__elf_init(struct bpf_object *obj)
1676 {
1677 	Elf64_Ehdr *ehdr;
1678 	int err = 0;
1679 	Elf *elf;
1680 
1681 	if (obj->efile.elf) {
1682 		pr_warn("elf: init internal error\n");
1683 		return -LIBBPF_ERRNO__LIBELF;
1684 	}
1685 
1686 	if (obj->efile.obj_buf_sz > 0) {
1687 		/* obj_buf should have been validated by bpf_object__open_mem(). */
1688 		elf = elf_memory((char *)obj->efile.obj_buf, obj->efile.obj_buf_sz);
1689 	} else {
1690 		obj->efile.fd = open(obj->path, O_RDONLY | O_CLOEXEC);
1691 		if (obj->efile.fd < 0) {
1692 			err = -errno;
1693 			pr_warn("elf: failed to open %s: %s\n", obj->path, errstr(err));
1694 			return err;
1695 		}
1696 
1697 		elf = elf_begin(obj->efile.fd, ELF_C_READ_MMAP, NULL);
1698 	}
1699 
1700 	if (!elf) {
1701 		pr_warn("elf: failed to open %s as ELF file: %s\n", obj->path, elf_errmsg(-1));
1702 		err = -LIBBPF_ERRNO__LIBELF;
1703 		goto errout;
1704 	}
1705 
1706 	obj->efile.elf = elf;
1707 
1708 	if (elf_kind(elf) != ELF_K_ELF) {
1709 		err = -LIBBPF_ERRNO__FORMAT;
1710 		pr_warn("elf: '%s' is not a proper ELF object\n", obj->path);
1711 		goto errout;
1712 	}
1713 
1714 	if (gelf_getclass(elf) != ELFCLASS64) {
1715 		err = -LIBBPF_ERRNO__FORMAT;
1716 		pr_warn("elf: '%s' is not a 64-bit ELF object\n", obj->path);
1717 		goto errout;
1718 	}
1719 
1720 	obj->efile.ehdr = ehdr = elf64_getehdr(elf);
1721 	if (!obj->efile.ehdr) {
1722 		pr_warn("elf: failed to get ELF header from %s: %s\n", obj->path, elf_errmsg(-1));
1723 		err = -LIBBPF_ERRNO__FORMAT;
1724 		goto errout;
1725 	}
1726 
1727 	/* Validate ELF object endianness... */
1728 	if (ehdr->e_ident[EI_DATA] != ELFDATA2LSB &&
1729 	    ehdr->e_ident[EI_DATA] != ELFDATA2MSB) {
1730 		err = -LIBBPF_ERRNO__ENDIAN;
1731 		pr_warn("elf: '%s' has unknown byte order\n", obj->path);
1732 		goto errout;
1733 	}
1734 	/* and save after bpf_object_open() frees ELF data */
1735 	obj->byteorder = ehdr->e_ident[EI_DATA];
1736 
1737 	if (elf_getshdrstrndx(elf, &obj->efile.shstrndx)) {
1738 		pr_warn("elf: failed to get section names section index for %s: %s\n",
1739 			obj->path, elf_errmsg(-1));
1740 		err = -LIBBPF_ERRNO__FORMAT;
1741 		goto errout;
1742 	}
1743 
1744 	/* ELF is corrupted/truncated, avoid calling elf_strptr. */
1745 	if (!elf_rawdata(elf_getscn(elf, obj->efile.shstrndx), NULL)) {
1746 		pr_warn("elf: failed to get section names strings from %s: %s\n",
1747 			obj->path, elf_errmsg(-1));
1748 		err = -LIBBPF_ERRNO__FORMAT;
1749 		goto errout;
1750 	}
1751 
1752 	/* Old LLVM set e_machine to EM_NONE */
1753 	if (ehdr->e_type != ET_REL || (ehdr->e_machine && ehdr->e_machine != EM_BPF)) {
1754 		pr_warn("elf: %s is not a valid eBPF object file\n", obj->path);
1755 		err = -LIBBPF_ERRNO__FORMAT;
1756 		goto errout;
1757 	}
1758 
1759 	return 0;
1760 errout:
1761 	bpf_object__elf_finish(obj);
1762 	return err;
1763 }
1764 
1765 static bool is_native_endianness(struct bpf_object *obj)
1766 {
1767 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1768 	return obj->byteorder == ELFDATA2LSB;
1769 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
1770 	return obj->byteorder == ELFDATA2MSB;
1771 #else
1772 # error "Unrecognized __BYTE_ORDER__"
1773 #endif
1774 }
1775 
1776 static int
1777 bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
1778 {
1779 	if (!data) {
1780 		pr_warn("invalid license section in %s\n", obj->path);
1781 		return -LIBBPF_ERRNO__FORMAT;
1782 	}
1783 	/* libbpf_strlcpy() only copies first N - 1 bytes, so size + 1 won't
1784 	 * go over allowed ELF data section buffer
1785 	 */
1786 	libbpf_strlcpy(obj->license, data, min(size + 1, sizeof(obj->license)));
1787 	pr_debug("license of %s is %s\n", obj->path, obj->license);
1788 	return 0;
1789 }
1790 
1791 static int
1792 bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
1793 {
1794 	__u32 kver;
1795 
1796 	if (!data || size != sizeof(kver)) {
1797 		pr_warn("invalid kver section in %s\n", obj->path);
1798 		return -LIBBPF_ERRNO__FORMAT;
1799 	}
1800 	memcpy(&kver, data, sizeof(kver));
1801 	obj->kern_version = kver;
1802 	pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
1803 	return 0;
1804 }
1805 
1806 static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
1807 {
1808 	if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
1809 	    type == BPF_MAP_TYPE_HASH_OF_MAPS)
1810 		return true;
1811 	return false;
1812 }
1813 
1814 static int find_elf_sec_sz(const struct bpf_object *obj, const char *name, __u32 *size)
1815 {
1816 	Elf_Data *data;
1817 	Elf_Scn *scn;
1818 
1819 	if (!name)
1820 		return -EINVAL;
1821 
1822 	scn = elf_sec_by_name(obj, name);
1823 	data = elf_sec_data(obj, scn);
1824 	if (data) {
1825 		*size = data->d_size;
1826 		return 0; /* found it */
1827 	}
1828 
1829 	return -ENOENT;
1830 }
1831 
1832 static Elf64_Sym *find_elf_var_sym(const struct bpf_object *obj, const char *name)
1833 {
1834 	Elf_Data *symbols = obj->efile.symbols;
1835 	const char *sname;
1836 	size_t si;
1837 
1838 	for (si = 0; si < symbols->d_size / sizeof(Elf64_Sym); si++) {
1839 		Elf64_Sym *sym = elf_sym_by_idx(obj, si);
1840 
1841 		if (ELF64_ST_TYPE(sym->st_info) != STT_OBJECT)
1842 			continue;
1843 
1844 		if (ELF64_ST_BIND(sym->st_info) != STB_GLOBAL &&
1845 		    ELF64_ST_BIND(sym->st_info) != STB_WEAK)
1846 			continue;
1847 
1848 		sname = elf_sym_str(obj, sym->st_name);
1849 		if (!sname) {
1850 			pr_warn("failed to get sym name string for var %s\n", name);
1851 			return ERR_PTR(-EIO);
1852 		}
1853 		if (strcmp(name, sname) == 0)
1854 			return sym;
1855 	}
1856 
1857 	return ERR_PTR(-ENOENT);
1858 }
1859 
1860 #ifndef MFD_CLOEXEC
1861 #define MFD_CLOEXEC 0x0001U
1862 #endif
1863 #ifndef MFD_NOEXEC_SEAL
1864 #define MFD_NOEXEC_SEAL 0x0008U
1865 #endif
1866 
1867 static int create_placeholder_fd(void)
1868 {
1869 	unsigned int flags = MFD_CLOEXEC | MFD_NOEXEC_SEAL;
1870 	const char *name = "libbpf-placeholder-fd";
1871 	int fd;
1872 
1873 	fd = ensure_good_fd(sys_memfd_create(name, flags));
1874 	if (fd >= 0)
1875 		return fd;
1876 	else if (errno != EINVAL)
1877 		return -errno;
1878 
1879 	/* Possibly running on kernel without MFD_NOEXEC_SEAL */
1880 	fd = ensure_good_fd(sys_memfd_create(name, flags & ~MFD_NOEXEC_SEAL));
1881 	if (fd < 0)
1882 		return -errno;
1883 	return fd;
1884 }
1885 
1886 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
1887 {
1888 	struct bpf_map *map;
1889 	int err;
1890 
1891 	err = libbpf_ensure_mem((void **)&obj->maps, &obj->maps_cap,
1892 				sizeof(*obj->maps), obj->nr_maps + 1);
1893 	if (err)
1894 		return ERR_PTR(err);
1895 
1896 	map = &obj->maps[obj->nr_maps++];
1897 	map->obj = obj;
1898 	/* Preallocate map FD without actually creating BPF map just yet.
1899 	 * These map FD "placeholders" will be reused later without changing
1900 	 * FD value when map is actually created in the kernel.
1901 	 *
1902 	 * This is useful to be able to perform BPF program relocations
1903 	 * without having to create BPF maps before that step. This allows us
1904 	 * to finalize and load BTF very late in BPF object's loading phase,
1905 	 * right before BPF maps have to be created and BPF programs have to
1906 	 * be loaded. By having these map FD placeholders we can perform all
1907 	 * the sanitizations, relocations, and any other adjustments before we
1908 	 * start creating actual BPF kernel objects (BTF, maps, progs).
1909 	 */
1910 	map->fd = create_placeholder_fd();
1911 	if (map->fd < 0)
1912 		return ERR_PTR(map->fd);
1913 	map->inner_map_fd = -1;
1914 	map->autocreate = true;
1915 
1916 	return map;
1917 }
1918 
1919 static size_t array_map_mmap_sz(unsigned int value_sz, unsigned int max_entries)
1920 {
1921 	const long page_sz = sysconf(_SC_PAGE_SIZE);
1922 	size_t map_sz;
1923 
1924 	map_sz = (size_t)roundup(value_sz, 8) * max_entries;
1925 	map_sz = roundup(map_sz, page_sz);
1926 	return map_sz;
1927 }
1928 
1929 static size_t bpf_map_mmap_sz(const struct bpf_map *map)
1930 {
1931 	const long page_sz = sysconf(_SC_PAGE_SIZE);
1932 
1933 	switch (map->def.type) {
1934 	case BPF_MAP_TYPE_ARRAY:
1935 	case BPF_MAP_TYPE_PERCPU_ARRAY:
1936 		return array_map_mmap_sz(map->def.value_size, map->def.max_entries);
1937 	case BPF_MAP_TYPE_ARENA:
1938 		return page_sz * map->def.max_entries;
1939 	default:
1940 		return 0; /* not supported */
1941 	}
1942 }
1943 
1944 static int bpf_map_mmap_resize(struct bpf_map *map, size_t old_sz, size_t new_sz)
1945 {
1946 	void *mmaped;
1947 
1948 	if (!map->mmaped)
1949 		return -EINVAL;
1950 
1951 	if (old_sz == new_sz)
1952 		return 0;
1953 
1954 	mmaped = mmap(NULL, new_sz, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1955 	if (mmaped == MAP_FAILED)
1956 		return -errno;
1957 
1958 	memcpy(mmaped, map->mmaped, min(old_sz, new_sz));
1959 	munmap(map->mmaped, old_sz);
1960 	map->mmaped = mmaped;
1961 	return 0;
1962 }
1963 
1964 static char *internal_map_name(struct bpf_object *obj, const char *real_name,
1965 			       enum libbpf_map_type type)
1966 {
1967 	char map_name[BPF_OBJ_NAME_LEN], *p;
1968 	int pfx_len, sfx_len = max((size_t)7, strlen(real_name));
1969 
1970 	/* This is one of the more confusing parts of libbpf for various
1971 	 * reasons, some of which are historical. The original idea for naming
1972 	 * internal names was to include as much of BPF object name prefix as
1973 	 * possible, so that it can be distinguished from similar internal
1974 	 * maps of a different BPF object.
1975 	 * As an example, let's say we have bpf_object named 'my_object_name'
1976 	 * and internal map corresponding to '.rodata' ELF section. The final
1977 	 * map name advertised to user and to the kernel will be
1978 	 * 'my_objec.rodata', taking first 8 characters of object name and
1979 	 * entire 7 characters of '.rodata'.
1980 	 * Somewhat confusingly, if internal map ELF section name is shorter
1981 	 * than 7 characters, e.g., '.bss', we still reserve 7 characters
1982 	 * for the suffix, even though we only have 4 actual characters, and
1983 	 * resulting map will be called 'my_objec.bss', not even using all 15
1984 	 * characters allowed by the kernel. Oh well, at least the truncated
1985 	 * object name is somewhat consistent in this case. But if the map
1986 	 * name is '.kconfig', we'll still have entirety of '.kconfig' added
1987 	 * (8 chars) and thus will be left with only first 7 characters of the
1988 	 * object name ('my_obje'). Happy guessing, user, that the final map
1989 	 * name will be "my_obje.kconfig".
1990 	 * Now, with libbpf starting to support arbitrarily named .rodata.*
1991 	 * and .data.* data sections, it's possible that ELF section name is
1992 	 * longer than allowed 15 chars, so we now need to be careful to take
1993 	 * only up to 15 first characters of ELF name, taking no BPF object
1994 	 * name characters at all. So '.rodata.abracadabra' will result in
1995 	 * '.rodata.abracad' kernel and user-visible name.
1996 	 * We need to keep this convoluted logic intact for .data, .bss and
1997 	 * .rodata maps, but for new custom .data.custom and .rodata.custom
1998 	 * maps we use their ELF names as is, not prepending bpf_object name
1999 	 * in front. We still need to truncate them to 15 characters for the
2000 	 * kernel. Full name can be recovered for such maps by using DATASEC
2001 	 * BTF type associated with such map's value type, though.
2002 	 */
2003 	if (sfx_len >= BPF_OBJ_NAME_LEN)
2004 		sfx_len = BPF_OBJ_NAME_LEN - 1;
2005 
2006 	/*
2007 	 * Don't prefix the bpf_object name if this is a custom dot map
2008 	 * (containing two or more dots) or a percpu data map.
2009 	 */
2010 	if (strchr(real_name + 1, '.') != NULL || type == LIBBPF_MAP_PERCPU)
2011 		pfx_len = 0;
2012 	else
2013 		pfx_len = min((size_t)BPF_OBJ_NAME_LEN - sfx_len - 1, strlen(obj->name));
2014 
2015 	snprintf(map_name, sizeof(map_name), "%.*s%.*s", pfx_len, obj->name,
2016 		 sfx_len, real_name);
2017 
2018 	/* sanities map name to characters allowed by kernel */
2019 	for (p = map_name; *p && p < map_name + sizeof(map_name); p++)
2020 		if (!isalnum(*p) && *p != '_' && *p != '.')
2021 			*p = '_';
2022 
2023 	return strdup(map_name);
2024 }
2025 
2026 static int
2027 map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map);
2028 
2029 /* Internal BPF map is mmap()'able only if at least one of corresponding
2030  * DATASEC's VARs are to be exposed through BPF skeleton. I.e., it's a GLOBAL
2031  * variable and it's not marked as __hidden (which turns it into, effectively,
2032  * a STATIC variable).
2033  */
2034 static bool map_is_mmapable(struct bpf_object *obj, struct bpf_map *map)
2035 {
2036 	const struct btf_type *t, *vt;
2037 	struct btf_var_secinfo *vsi;
2038 	int i, n;
2039 
2040 	if (!map->btf_value_type_id)
2041 		return false;
2042 
2043 	/*
2044 	 * The internal PERCPU maps are not mmapable because the underlying
2045 	 * percpu_array maps do not have mmap support.
2046 	 */
2047 	if (map->libbpf_type == LIBBPF_MAP_PERCPU)
2048 		return false;
2049 
2050 	t = btf__type_by_id(obj->btf, map->btf_value_type_id);
2051 	if (!btf_is_datasec(t))
2052 		return false;
2053 
2054 	vsi = btf_var_secinfos(t);
2055 	for (i = 0, n = btf_vlen(t); i < n; i++, vsi++) {
2056 		vt = btf__type_by_id(obj->btf, vsi->type);
2057 		if (!btf_is_var(vt))
2058 			continue;
2059 
2060 		if (btf_var(vt)->linkage != BTF_VAR_STATIC)
2061 			return true;
2062 	}
2063 
2064 	return false;
2065 }
2066 
2067 static int
2068 bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
2069 			      const char *real_name, int sec_idx, void *data, size_t data_sz)
2070 {
2071 	bool is_percpu = type == LIBBPF_MAP_PERCPU;
2072 	struct bpf_map_def *def;
2073 	struct bpf_map *map;
2074 	size_t mmap_sz;
2075 	int err;
2076 
2077 	map = bpf_object__add_map(obj);
2078 	if (IS_ERR(map))
2079 		return PTR_ERR(map);
2080 
2081 	map->libbpf_type = type;
2082 	map->sec_idx = sec_idx;
2083 	map->sec_offset = 0;
2084 	map->real_name = strdup(real_name);
2085 	map->name = internal_map_name(obj, real_name, type);
2086 	if (!map->real_name || !map->name) {
2087 		zfree(&map->real_name);
2088 		zfree(&map->name);
2089 		return -ENOMEM;
2090 	}
2091 
2092 	def = &map->def;
2093 	def->type = is_percpu ? BPF_MAP_TYPE_PERCPU_ARRAY : BPF_MAP_TYPE_ARRAY;
2094 	def->key_size = sizeof(int);
2095 	def->value_size = data_sz;
2096 	def->max_entries = 1;
2097 	def->map_flags = type == LIBBPF_MAP_RODATA || type == LIBBPF_MAP_KCONFIG
2098 		? BPF_F_RDONLY_PROG : 0;
2099 
2100 	/* failures are fine because of maps like .rodata.str1.1 */
2101 	(void) map_fill_btf_type_info(obj, map);
2102 
2103 	if (map_is_mmapable(obj, map))
2104 		def->map_flags |= BPF_F_MMAPABLE;
2105 
2106 	pr_debug("map '%s' (global %sdata): at sec_idx %d, offset %zu, flags %x.\n",
2107 		 map->name, is_percpu ? "percpu " : "", map->sec_idx,
2108 		 map->sec_offset, def->map_flags);
2109 
2110 	mmap_sz = bpf_map_mmap_sz(map);
2111 	map->mmaped = mmap(NULL, mmap_sz, PROT_READ | PROT_WRITE,
2112 			   MAP_SHARED | MAP_ANONYMOUS, -1, 0);
2113 	if (map->mmaped == MAP_FAILED) {
2114 		err = -errno;
2115 		map->mmaped = NULL;
2116 		pr_warn("failed to alloc map '%s' content buffer: %s\n", map->name, errstr(err));
2117 		zfree(&map->real_name);
2118 		zfree(&map->name);
2119 		return err;
2120 	}
2121 
2122 	if (data)
2123 		memcpy(map->mmaped, data, data_sz);
2124 
2125 	pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
2126 	return 0;
2127 }
2128 
2129 static int bpf_object__init_global_data_maps(struct bpf_object *obj)
2130 {
2131 	struct elf_sec_desc *sec_desc;
2132 	const char *sec_name;
2133 	int err = 0, sec_idx;
2134 
2135 	/*
2136 	 * Populate obj->maps with libbpf internal maps.
2137 	 */
2138 	for (sec_idx = 1; sec_idx < obj->efile.sec_cnt; sec_idx++) {
2139 		sec_desc = &obj->efile.secs[sec_idx];
2140 
2141 		/* Skip recognized sections with size 0. */
2142 		if (!sec_desc->data || sec_desc->data->d_size == 0)
2143 			continue;
2144 
2145 		switch (sec_desc->sec_type) {
2146 		case SEC_DATA:
2147 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
2148 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
2149 							    sec_name, sec_idx,
2150 							    sec_desc->data->d_buf,
2151 							    sec_desc->data->d_size);
2152 			break;
2153 		case SEC_RODATA:
2154 			obj->has_rodata = true;
2155 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
2156 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
2157 							    sec_name, sec_idx,
2158 							    sec_desc->data->d_buf,
2159 							    sec_desc->data->d_size);
2160 			break;
2161 		case SEC_BSS:
2162 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
2163 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
2164 							    sec_name, sec_idx,
2165 							    NULL,
2166 							    sec_desc->data->d_size);
2167 			break;
2168 		case SEC_PERCPU:
2169 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
2170 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_PERCPU,
2171 							    sec_name, sec_idx,
2172 							    sec_desc->data->d_buf,
2173 							    sec_desc->data->d_size);
2174 			break;
2175 		default:
2176 			/* skip */
2177 			break;
2178 		}
2179 		if (err)
2180 			return err;
2181 	}
2182 	return 0;
2183 }
2184 
2185 
2186 static struct extern_desc *find_extern_by_name(const struct bpf_object *obj,
2187 					       const void *name)
2188 {
2189 	int i;
2190 
2191 	for (i = 0; i < obj->nr_extern; i++) {
2192 		if (strcmp(obj->externs[i].name, name) == 0)
2193 			return &obj->externs[i];
2194 	}
2195 	return NULL;
2196 }
2197 
2198 static struct extern_desc *find_extern_by_name_with_len(const struct bpf_object *obj,
2199 							const void *name, int len)
2200 {
2201 	const char *ext_name;
2202 	int i;
2203 
2204 	for (i = 0; i < obj->nr_extern; i++) {
2205 		ext_name = obj->externs[i].name;
2206 		if (strlen(ext_name) == len && strncmp(ext_name, name, len) == 0)
2207 			return &obj->externs[i];
2208 	}
2209 	return NULL;
2210 }
2211 
2212 static int set_kcfg_value_tri(struct extern_desc *ext, void *ext_val,
2213 			      char value)
2214 {
2215 	switch (ext->kcfg.type) {
2216 	case KCFG_BOOL:
2217 		if (value == 'm') {
2218 			pr_warn("extern (kcfg) '%s': value '%c' implies tristate or char type\n",
2219 				ext->name, value);
2220 			return -EINVAL;
2221 		}
2222 		*(bool *)ext_val = value == 'y' ? true : false;
2223 		break;
2224 	case KCFG_TRISTATE:
2225 		if (value == 'y')
2226 			*(enum libbpf_tristate *)ext_val = TRI_YES;
2227 		else if (value == 'm')
2228 			*(enum libbpf_tristate *)ext_val = TRI_MODULE;
2229 		else /* value == 'n' */
2230 			*(enum libbpf_tristate *)ext_val = TRI_NO;
2231 		break;
2232 	case KCFG_CHAR:
2233 		*(char *)ext_val = value;
2234 		break;
2235 	case KCFG_UNKNOWN:
2236 	case KCFG_INT:
2237 	case KCFG_CHAR_ARR:
2238 	default:
2239 		pr_warn("extern (kcfg) '%s': value '%c' implies bool, tristate, or char type\n",
2240 			ext->name, value);
2241 		return -EINVAL;
2242 	}
2243 	ext->is_set = true;
2244 	return 0;
2245 }
2246 
2247 static int set_kcfg_value_str(struct extern_desc *ext, char *ext_val,
2248 			      const char *value)
2249 {
2250 	size_t len;
2251 
2252 	if (ext->kcfg.type != KCFG_CHAR_ARR) {
2253 		pr_warn("extern (kcfg) '%s': value '%s' implies char array type\n",
2254 			ext->name, value);
2255 		return -EINVAL;
2256 	}
2257 
2258 	len = strlen(value);
2259 	if (len < 2 || value[len - 1] != '"') {
2260 		pr_warn("extern (kcfg) '%s': invalid string config '%s'\n",
2261 			ext->name, value);
2262 		return -EINVAL;
2263 	}
2264 
2265 	/* strip quotes */
2266 	len -= 2;
2267 	if (len >= ext->kcfg.sz) {
2268 		pr_warn("extern (kcfg) '%s': long string '%s' of (%zu bytes) truncated to %d bytes\n",
2269 			ext->name, value, len, ext->kcfg.sz - 1);
2270 		len = ext->kcfg.sz - 1;
2271 	}
2272 	memcpy(ext_val, value + 1, len);
2273 	ext_val[len] = '\0';
2274 	ext->is_set = true;
2275 	return 0;
2276 }
2277 
2278 static int parse_u64(const char *value, __u64 *res)
2279 {
2280 	char *value_end;
2281 	int err;
2282 
2283 	errno = 0;
2284 	*res = strtoull(value, &value_end, 0);
2285 	if (errno) {
2286 		err = -errno;
2287 		pr_warn("failed to parse '%s': %s\n", value, errstr(err));
2288 		return err;
2289 	}
2290 	if (*value_end) {
2291 		pr_warn("failed to parse '%s' as integer completely\n", value);
2292 		return -EINVAL;
2293 	}
2294 	return 0;
2295 }
2296 
2297 static bool is_kcfg_value_in_range(const struct extern_desc *ext, __u64 v)
2298 {
2299 	int bit_sz = ext->kcfg.sz * 8;
2300 
2301 	if (ext->kcfg.sz == 8)
2302 		return true;
2303 
2304 	/* Validate that value stored in u64 fits in integer of `ext->sz`
2305 	 * bytes size without any loss of information. If the target integer
2306 	 * is signed, we rely on the following limits of integer type of
2307 	 * Y bits and subsequent transformation:
2308 	 *
2309 	 *     -2^(Y-1) <= X           <= 2^(Y-1) - 1
2310 	 *            0 <= X + 2^(Y-1) <= 2^Y - 1
2311 	 *            0 <= X + 2^(Y-1) <  2^Y
2312 	 *
2313 	 *  For unsigned target integer, check that all the (64 - Y) bits are
2314 	 *  zero.
2315 	 */
2316 	if (ext->kcfg.is_signed)
2317 		return v + (1ULL << (bit_sz - 1)) < (1ULL << bit_sz);
2318 	else
2319 		return (v >> bit_sz) == 0;
2320 }
2321 
2322 static int set_kcfg_value_num(struct extern_desc *ext, void *ext_val,
2323 			      __u64 value)
2324 {
2325 	if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR &&
2326 	    ext->kcfg.type != KCFG_BOOL) {
2327 		pr_warn("extern (kcfg) '%s': value '%llu' implies integer, char, or boolean type\n",
2328 			ext->name, (unsigned long long)value);
2329 		return -EINVAL;
2330 	}
2331 	if (ext->kcfg.type == KCFG_BOOL && value > 1) {
2332 		pr_warn("extern (kcfg) '%s': value '%llu' isn't boolean compatible\n",
2333 			ext->name, (unsigned long long)value);
2334 		return -EINVAL;
2335 
2336 	}
2337 	if (!is_kcfg_value_in_range(ext, value)) {
2338 		pr_warn("extern (kcfg) '%s': value '%llu' doesn't fit in %d bytes\n",
2339 			ext->name, (unsigned long long)value, ext->kcfg.sz);
2340 		return -ERANGE;
2341 	}
2342 	switch (ext->kcfg.sz) {
2343 	case 1:
2344 		*(__u8 *)ext_val = value;
2345 		break;
2346 	case 2:
2347 		*(__u16 *)ext_val = value;
2348 		break;
2349 	case 4:
2350 		*(__u32 *)ext_val = value;
2351 		break;
2352 	case 8:
2353 		*(__u64 *)ext_val = value;
2354 		break;
2355 	default:
2356 		return -EINVAL;
2357 	}
2358 	ext->is_set = true;
2359 	return 0;
2360 }
2361 
2362 static int bpf_object__process_kconfig_line(struct bpf_object *obj,
2363 					    char *buf, void *data)
2364 {
2365 	struct extern_desc *ext;
2366 	char *sep, *value;
2367 	int len, err = 0;
2368 	void *ext_val;
2369 	__u64 num;
2370 
2371 	if (!str_has_pfx(buf, "CONFIG_"))
2372 		return 0;
2373 
2374 	sep = strchr(buf, '=');
2375 	if (!sep) {
2376 		pr_warn("failed to parse '%s': no separator\n", buf);
2377 		return -EINVAL;
2378 	}
2379 
2380 	/* Trim ending '\n' */
2381 	len = strlen(buf);
2382 	if (buf[len - 1] == '\n')
2383 		buf[len - 1] = '\0';
2384 	/* Split on '=' and ensure that a value is present. */
2385 	*sep = '\0';
2386 	if (!sep[1]) {
2387 		*sep = '=';
2388 		pr_warn("failed to parse '%s': no value\n", buf);
2389 		return -EINVAL;
2390 	}
2391 
2392 	ext = find_extern_by_name(obj, buf);
2393 	if (!ext || ext->is_set)
2394 		return 0;
2395 
2396 	ext_val = data + ext->kcfg.data_off;
2397 	value = sep + 1;
2398 
2399 	switch (*value) {
2400 	case 'y': case 'n': case 'm':
2401 		err = set_kcfg_value_tri(ext, ext_val, *value);
2402 		break;
2403 	case '"':
2404 		err = set_kcfg_value_str(ext, ext_val, value);
2405 		break;
2406 	default:
2407 		/* assume integer */
2408 		err = parse_u64(value, &num);
2409 		if (err) {
2410 			pr_warn("extern (kcfg) '%s': value '%s' isn't a valid integer\n", ext->name, value);
2411 			return err;
2412 		}
2413 		if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR) {
2414 			pr_warn("extern (kcfg) '%s': value '%s' implies integer type\n", ext->name, value);
2415 			return -EINVAL;
2416 		}
2417 		err = set_kcfg_value_num(ext, ext_val, num);
2418 		break;
2419 	}
2420 	if (err)
2421 		return err;
2422 	pr_debug("extern (kcfg) '%s': set to %s\n", ext->name, value);
2423 	return 0;
2424 }
2425 
2426 static int bpf_object__read_kconfig_file(struct bpf_object *obj, void *data)
2427 {
2428 	char buf[PATH_MAX];
2429 	struct utsname uts;
2430 	int len, err = 0;
2431 	gzFile file;
2432 
2433 	uname(&uts);
2434 	len = snprintf(buf, PATH_MAX, "/boot/config-%s", uts.release);
2435 	if (len < 0)
2436 		return -EINVAL;
2437 	else if (len >= PATH_MAX)
2438 		return -ENAMETOOLONG;
2439 
2440 	/* gzopen also accepts uncompressed files. */
2441 	file = gzopen(buf, "re");
2442 	if (!file)
2443 		file = gzopen("/proc/config.gz", "re");
2444 
2445 	if (!file) {
2446 		pr_warn("failed to open system Kconfig\n");
2447 		return -ENOENT;
2448 	}
2449 
2450 	while (gzgets(file, buf, sizeof(buf))) {
2451 		err = bpf_object__process_kconfig_line(obj, buf, data);
2452 		if (err) {
2453 			pr_warn("error parsing system Kconfig line '%s': %s\n",
2454 				buf, errstr(err));
2455 			goto out;
2456 		}
2457 	}
2458 
2459 out:
2460 	gzclose(file);
2461 	return err;
2462 }
2463 
2464 static int bpf_object__read_kconfig_mem(struct bpf_object *obj,
2465 					const char *config, void *data)
2466 {
2467 	char buf[PATH_MAX];
2468 	int err = 0;
2469 	FILE *file;
2470 
2471 	file = fmemopen((void *)config, strlen(config), "r");
2472 	if (!file) {
2473 		err = -errno;
2474 		pr_warn("failed to open in-memory Kconfig: %s\n", errstr(err));
2475 		return err;
2476 	}
2477 
2478 	while (fgets(buf, sizeof(buf), file)) {
2479 		err = bpf_object__process_kconfig_line(obj, buf, data);
2480 		if (err) {
2481 			pr_warn("error parsing in-memory Kconfig line '%s': %s\n",
2482 				buf, errstr(err));
2483 			break;
2484 		}
2485 	}
2486 
2487 	fclose(file);
2488 	return err;
2489 }
2490 
2491 static int bpf_object__init_kconfig_map(struct bpf_object *obj)
2492 {
2493 	struct extern_desc *last_ext = NULL, *ext;
2494 	size_t map_sz;
2495 	int i, err;
2496 
2497 	for (i = 0; i < obj->nr_extern; i++) {
2498 		ext = &obj->externs[i];
2499 		if (ext->type == EXT_KCFG)
2500 			last_ext = ext;
2501 	}
2502 
2503 	if (!last_ext)
2504 		return 0;
2505 
2506 	map_sz = last_ext->kcfg.data_off + last_ext->kcfg.sz;
2507 	err = bpf_object__init_internal_map(obj, LIBBPF_MAP_KCONFIG,
2508 					    ".kconfig", obj->efile.symbols_shndx,
2509 					    NULL, map_sz);
2510 	if (err)
2511 		return err;
2512 
2513 	obj->kconfig_map_idx = obj->nr_maps - 1;
2514 
2515 	return 0;
2516 }
2517 
2518 const struct btf_type *
2519 skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id)
2520 {
2521 	const struct btf_type *t = btf__type_by_id(btf, id);
2522 
2523 	if (res_id)
2524 		*res_id = id;
2525 
2526 	while (btf_is_mod(t) || btf_is_typedef(t)) {
2527 		if (res_id)
2528 			*res_id = t->type;
2529 		t = btf__type_by_id(btf, t->type);
2530 	}
2531 
2532 	return t;
2533 }
2534 
2535 static const struct btf_type *
2536 resolve_func_ptr(const struct btf *btf, __u32 id, __u32 *res_id)
2537 {
2538 	const struct btf_type *t;
2539 
2540 	t = skip_mods_and_typedefs(btf, id, NULL);
2541 	if (!btf_is_ptr(t))
2542 		return NULL;
2543 
2544 	t = skip_mods_and_typedefs(btf, t->type, res_id);
2545 
2546 	return btf_is_func_proto(t) ? t : NULL;
2547 }
2548 
2549 static const char *__btf_kind_str(__u16 kind)
2550 {
2551 	switch (kind) {
2552 	case BTF_KIND_UNKN: return "void";
2553 	case BTF_KIND_INT: return "int";
2554 	case BTF_KIND_PTR: return "ptr";
2555 	case BTF_KIND_ARRAY: return "array";
2556 	case BTF_KIND_STRUCT: return "struct";
2557 	case BTF_KIND_UNION: return "union";
2558 	case BTF_KIND_ENUM: return "enum";
2559 	case BTF_KIND_FWD: return "fwd";
2560 	case BTF_KIND_TYPEDEF: return "typedef";
2561 	case BTF_KIND_VOLATILE: return "volatile";
2562 	case BTF_KIND_CONST: return "const";
2563 	case BTF_KIND_RESTRICT: return "restrict";
2564 	case BTF_KIND_FUNC: return "func";
2565 	case BTF_KIND_FUNC_PROTO: return "func_proto";
2566 	case BTF_KIND_VAR: return "var";
2567 	case BTF_KIND_DATASEC: return "datasec";
2568 	case BTF_KIND_FLOAT: return "float";
2569 	case BTF_KIND_DECL_TAG: return "decl_tag";
2570 	case BTF_KIND_TYPE_TAG: return "type_tag";
2571 	case BTF_KIND_ENUM64: return "enum64";
2572 	case BTF_KIND_LOC_PARAM: return "loc_param";
2573 	case BTF_KIND_LOC_PROTO: return "loc_proto";
2574 	case BTF_KIND_LOCSEC: return "locsec";
2575 	default: return "unknown";
2576 	}
2577 }
2578 
2579 const char *btf_kind_str(const struct btf_type *t)
2580 {
2581 	return __btf_kind_str(btf_kind(t));
2582 }
2583 
2584 /*
2585  * Fetch integer attribute of BTF map definition. Such attributes are
2586  * represented using a pointer to an array, in which dimensionality of array
2587  * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
2588  * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
2589  * type definition, while using only sizeof(void *) space in ELF data section.
2590  */
2591 static bool get_map_field_int(const char *map_name, const struct btf *btf,
2592 			      const struct btf_member *m, __u32 *res)
2593 {
2594 	const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
2595 	const char *name = btf__name_by_offset(btf, m->name_off);
2596 	const struct btf_array *arr_info;
2597 	const struct btf_type *arr_t;
2598 
2599 	if (!btf_is_ptr(t)) {
2600 		pr_warn("map '%s': attr '%s': expected PTR, got %s.\n",
2601 			map_name, name, btf_kind_str(t));
2602 		return false;
2603 	}
2604 
2605 	arr_t = btf__type_by_id(btf, t->type);
2606 	if (!arr_t) {
2607 		pr_warn("map '%s': attr '%s': type [%u] not found.\n",
2608 			map_name, name, t->type);
2609 		return false;
2610 	}
2611 	if (!btf_is_array(arr_t)) {
2612 		pr_warn("map '%s': attr '%s': expected ARRAY, got %s.\n",
2613 			map_name, name, btf_kind_str(arr_t));
2614 		return false;
2615 	}
2616 	arr_info = btf_array(arr_t);
2617 	*res = arr_info->nelems;
2618 	return true;
2619 }
2620 
2621 static bool get_map_field_long(const char *map_name, const struct btf *btf,
2622 			       const struct btf_member *m, __u64 *res)
2623 {
2624 	const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
2625 	const char *name = btf__name_by_offset(btf, m->name_off);
2626 
2627 	if (btf_is_ptr(t)) {
2628 		__u32 res32;
2629 		bool ret;
2630 
2631 		ret = get_map_field_int(map_name, btf, m, &res32);
2632 		if (ret)
2633 			*res = (__u64)res32;
2634 		return ret;
2635 	}
2636 
2637 	if (!btf_is_enum(t) && !btf_is_enum64(t)) {
2638 		pr_warn("map '%s': attr '%s': expected ENUM or ENUM64, got %s.\n",
2639 			map_name, name, btf_kind_str(t));
2640 		return false;
2641 	}
2642 
2643 	if (btf_vlen(t) != 1) {
2644 		pr_warn("map '%s': attr '%s': invalid __ulong\n",
2645 			map_name, name);
2646 		return false;
2647 	}
2648 
2649 	if (btf_is_enum(t)) {
2650 		const struct btf_enum *e = btf_enum(t);
2651 
2652 		*res = e->val;
2653 	} else {
2654 		const struct btf_enum64 *e = btf_enum64(t);
2655 
2656 		*res = btf_enum64_value(e);
2657 	}
2658 	return true;
2659 }
2660 
2661 static int pathname_concat(char *buf, size_t buf_sz, const char *path, const char *name)
2662 {
2663 	int len;
2664 
2665 	len = snprintf(buf, buf_sz, "%s/%s", path, name);
2666 	if (len < 0)
2667 		return -EINVAL;
2668 	if (len >= buf_sz)
2669 		return -ENAMETOOLONG;
2670 
2671 	return 0;
2672 }
2673 
2674 static int build_map_pin_path(struct bpf_map *map, const char *path)
2675 {
2676 	char buf[PATH_MAX];
2677 	int err;
2678 
2679 	if (!path)
2680 		path = BPF_FS_DEFAULT_PATH;
2681 
2682 	err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
2683 	if (err)
2684 		return err;
2685 
2686 	return bpf_map__set_pin_path(map, buf);
2687 }
2688 
2689 /* should match definition in bpf_helpers.h */
2690 enum libbpf_pin_type {
2691 	LIBBPF_PIN_NONE,
2692 	/* PIN_BY_NAME: pin maps by name (in /sys/fs/bpf by default) */
2693 	LIBBPF_PIN_BY_NAME,
2694 };
2695 
2696 int parse_btf_map_def(const char *map_name, struct btf *btf,
2697 		      const struct btf_type *def_t, bool strict,
2698 		      struct btf_map_def *map_def, struct btf_map_def *inner_def)
2699 {
2700 	const struct btf_type *t;
2701 	const struct btf_member *m;
2702 	bool is_inner = inner_def == NULL;
2703 	int vlen, i;
2704 
2705 	vlen = btf_vlen(def_t);
2706 	m = btf_members(def_t);
2707 	for (i = 0; i < vlen; i++, m++) {
2708 		const char *name = btf__name_by_offset(btf, m->name_off);
2709 
2710 		if (!name) {
2711 			pr_warn("map '%s': invalid field #%d.\n", map_name, i);
2712 			return -EINVAL;
2713 		}
2714 		if (strcmp(name, "type") == 0) {
2715 			if (!get_map_field_int(map_name, btf, m, &map_def->map_type))
2716 				return -EINVAL;
2717 			map_def->parts |= MAP_DEF_MAP_TYPE;
2718 		} else if (strcmp(name, "max_entries") == 0) {
2719 			if (!get_map_field_int(map_name, btf, m, &map_def->max_entries))
2720 				return -EINVAL;
2721 			map_def->parts |= MAP_DEF_MAX_ENTRIES;
2722 		} else if (strcmp(name, "map_flags") == 0) {
2723 			if (!get_map_field_int(map_name, btf, m, &map_def->map_flags))
2724 				return -EINVAL;
2725 			map_def->parts |= MAP_DEF_MAP_FLAGS;
2726 		} else if (strcmp(name, "numa_node") == 0) {
2727 			if (!get_map_field_int(map_name, btf, m, &map_def->numa_node))
2728 				return -EINVAL;
2729 			map_def->parts |= MAP_DEF_NUMA_NODE;
2730 		} else if (strcmp(name, "key_size") == 0) {
2731 			__u32 sz;
2732 
2733 			if (!get_map_field_int(map_name, btf, m, &sz))
2734 				return -EINVAL;
2735 			if (map_def->key_size && map_def->key_size != sz) {
2736 				pr_warn("map '%s': conflicting key size %u != %u.\n",
2737 					map_name, map_def->key_size, sz);
2738 				return -EINVAL;
2739 			}
2740 			map_def->key_size = sz;
2741 			map_def->parts |= MAP_DEF_KEY_SIZE;
2742 		} else if (strcmp(name, "key") == 0) {
2743 			__s64 sz;
2744 
2745 			t = btf__type_by_id(btf, m->type);
2746 			if (!t) {
2747 				pr_warn("map '%s': key type [%u] not found.\n",
2748 					map_name, m->type);
2749 				return -EINVAL;
2750 			}
2751 			if (!btf_is_ptr(t)) {
2752 				pr_warn("map '%s': key spec is not PTR: %s.\n",
2753 					map_name, btf_kind_str(t));
2754 				return -EINVAL;
2755 			}
2756 			sz = btf__resolve_size(btf, t->type);
2757 			if (sz < 0) {
2758 				pr_warn("map '%s': can't determine key size for type [%u]: %zd.\n",
2759 					map_name, t->type, (ssize_t)sz);
2760 				return sz;
2761 			}
2762 			if (map_def->key_size && map_def->key_size != sz) {
2763 				pr_warn("map '%s': conflicting key size %u != %zd.\n",
2764 					map_name, map_def->key_size, (ssize_t)sz);
2765 				return -EINVAL;
2766 			}
2767 			map_def->key_size = sz;
2768 			map_def->key_type_id = t->type;
2769 			map_def->parts |= MAP_DEF_KEY_SIZE | MAP_DEF_KEY_TYPE;
2770 		} else if (strcmp(name, "value_size") == 0) {
2771 			__u32 sz;
2772 
2773 			if (!get_map_field_int(map_name, btf, m, &sz))
2774 				return -EINVAL;
2775 			if (map_def->value_size && map_def->value_size != sz) {
2776 				pr_warn("map '%s': conflicting value size %u != %u.\n",
2777 					map_name, map_def->value_size, sz);
2778 				return -EINVAL;
2779 			}
2780 			map_def->value_size = sz;
2781 			map_def->parts |= MAP_DEF_VALUE_SIZE;
2782 		} else if (strcmp(name, "value") == 0) {
2783 			__s64 sz;
2784 
2785 			t = btf__type_by_id(btf, m->type);
2786 			if (!t) {
2787 				pr_warn("map '%s': value type [%u] not found.\n",
2788 					map_name, m->type);
2789 				return -EINVAL;
2790 			}
2791 			if (!btf_is_ptr(t)) {
2792 				pr_warn("map '%s': value spec is not PTR: %s.\n",
2793 					map_name, btf_kind_str(t));
2794 				return -EINVAL;
2795 			}
2796 			sz = btf__resolve_size(btf, t->type);
2797 			if (sz < 0) {
2798 				pr_warn("map '%s': can't determine value size for type [%u]: %zd.\n",
2799 					map_name, t->type, (ssize_t)sz);
2800 				return sz;
2801 			}
2802 			if (map_def->value_size && map_def->value_size != sz) {
2803 				pr_warn("map '%s': conflicting value size %u != %zd.\n",
2804 					map_name, map_def->value_size, (ssize_t)sz);
2805 				return -EINVAL;
2806 			}
2807 			map_def->value_size = sz;
2808 			map_def->value_type_id = t->type;
2809 			map_def->parts |= MAP_DEF_VALUE_SIZE | MAP_DEF_VALUE_TYPE;
2810 		}
2811 		else if (strcmp(name, "values") == 0) {
2812 			bool is_map_in_map = bpf_map_type__is_map_in_map(map_def->map_type);
2813 			bool is_prog_array = map_def->map_type == BPF_MAP_TYPE_PROG_ARRAY;
2814 			const char *desc = is_map_in_map ? "map-in-map inner" : "prog-array value";
2815 			char inner_map_name[128];
2816 			int err;
2817 
2818 			if (is_inner) {
2819 				pr_warn("map '%s': multi-level inner maps not supported.\n",
2820 					map_name);
2821 				return -ENOTSUP;
2822 			}
2823 			if (i != vlen - 1) {
2824 				pr_warn("map '%s': '%s' member should be last.\n",
2825 					map_name, name);
2826 				return -EINVAL;
2827 			}
2828 			if (!is_map_in_map && !is_prog_array) {
2829 				pr_warn("map '%s': should be map-in-map or prog-array.\n",
2830 					map_name);
2831 				return -ENOTSUP;
2832 			}
2833 			if (map_def->value_size && map_def->value_size != 4) {
2834 				pr_warn("map '%s': conflicting value size %u != 4.\n",
2835 					map_name, map_def->value_size);
2836 				return -EINVAL;
2837 			}
2838 			map_def->value_size = 4;
2839 			t = btf__type_by_id(btf, m->type);
2840 			if (!t) {
2841 				pr_warn("map '%s': %s type [%u] not found.\n",
2842 					map_name, desc, m->type);
2843 				return -EINVAL;
2844 			}
2845 			if (!btf_is_array(t) || btf_array(t)->nelems) {
2846 				pr_warn("map '%s': %s spec is not a zero-sized array.\n",
2847 					map_name, desc);
2848 				return -EINVAL;
2849 			}
2850 			t = skip_mods_and_typedefs(btf, btf_array(t)->type, NULL);
2851 			if (!btf_is_ptr(t)) {
2852 				pr_warn("map '%s': %s def is of unexpected kind %s.\n",
2853 					map_name, desc, btf_kind_str(t));
2854 				return -EINVAL;
2855 			}
2856 			t = skip_mods_and_typedefs(btf, t->type, NULL);
2857 			if (is_prog_array) {
2858 				if (!btf_is_func_proto(t)) {
2859 					pr_warn("map '%s': prog-array value def is of unexpected kind %s.\n",
2860 						map_name, btf_kind_str(t));
2861 					return -EINVAL;
2862 				}
2863 				continue;
2864 			}
2865 			if (!btf_is_struct(t)) {
2866 				pr_warn("map '%s': map-in-map inner def is of unexpected kind %s.\n",
2867 					map_name, btf_kind_str(t));
2868 				return -EINVAL;
2869 			}
2870 
2871 			snprintf(inner_map_name, sizeof(inner_map_name), "%s.inner", map_name);
2872 			err = parse_btf_map_def(inner_map_name, btf, t, strict, inner_def, NULL);
2873 			if (err)
2874 				return err;
2875 
2876 			map_def->parts |= MAP_DEF_INNER_MAP;
2877 		} else if (strcmp(name, "pinning") == 0) {
2878 			__u32 val;
2879 
2880 			if (is_inner) {
2881 				pr_warn("map '%s': inner def can't be pinned.\n", map_name);
2882 				return -EINVAL;
2883 			}
2884 			if (!get_map_field_int(map_name, btf, m, &val))
2885 				return -EINVAL;
2886 			if (val != LIBBPF_PIN_NONE && val != LIBBPF_PIN_BY_NAME) {
2887 				pr_warn("map '%s': invalid pinning value %u.\n",
2888 					map_name, val);
2889 				return -EINVAL;
2890 			}
2891 			map_def->pinning = val;
2892 			map_def->parts |= MAP_DEF_PINNING;
2893 		} else if (strcmp(name, "map_extra") == 0) {
2894 			__u64 map_extra;
2895 
2896 			if (!get_map_field_long(map_name, btf, m, &map_extra))
2897 				return -EINVAL;
2898 			map_def->map_extra = map_extra;
2899 			map_def->parts |= MAP_DEF_MAP_EXTRA;
2900 		} else {
2901 			if (strict) {
2902 				pr_warn("map '%s': unknown field '%s'.\n", map_name, name);
2903 				return -ENOTSUP;
2904 			}
2905 			pr_debug("map '%s': ignoring unknown field '%s'.\n", map_name, name);
2906 		}
2907 	}
2908 
2909 	if (map_def->map_type == BPF_MAP_TYPE_UNSPEC) {
2910 		pr_warn("map '%s': map type isn't specified.\n", map_name);
2911 		return -EINVAL;
2912 	}
2913 
2914 	return 0;
2915 }
2916 
2917 static size_t adjust_ringbuf_sz(size_t sz)
2918 {
2919 	__u32 page_sz = sysconf(_SC_PAGE_SIZE);
2920 	__u32 mul;
2921 
2922 	/* if user forgot to set any size, make sure they see error */
2923 	if (sz == 0)
2924 		return 0;
2925 	/* Kernel expects BPF_MAP_TYPE_RINGBUF's max_entries to be
2926 	 * a power-of-2 multiple of kernel's page size. If user diligently
2927 	 * satisfied these conditions, pass the size through.
2928 	 */
2929 	if ((sz % page_sz) == 0 && is_pow_of_2(sz / page_sz))
2930 		return sz;
2931 
2932 	/* Otherwise find closest (page_sz * power_of_2) product bigger than
2933 	 * user-set size to satisfy both user size request and kernel
2934 	 * requirements and substitute correct max_entries for map creation.
2935 	 */
2936 	for (mul = 1; mul <= UINT_MAX / page_sz; mul <<= 1) {
2937 		if (mul * page_sz > sz)
2938 			return mul * page_sz;
2939 	}
2940 
2941 	/* if it's impossible to satisfy the conditions (i.e., user size is
2942 	 * very close to UINT_MAX but is not a power-of-2 multiple of
2943 	 * page_size) then just return original size and let kernel reject it
2944 	 */
2945 	return sz;
2946 }
2947 
2948 static bool map_is_ringbuf(const struct bpf_map *map)
2949 {
2950 	return map->def.type == BPF_MAP_TYPE_RINGBUF ||
2951 	       map->def.type == BPF_MAP_TYPE_USER_RINGBUF;
2952 }
2953 
2954 static void fill_map_from_def(struct bpf_map *map, const struct btf_map_def *def)
2955 {
2956 	map->def.type = def->map_type;
2957 	map->def.key_size = def->key_size;
2958 	map->def.value_size = def->value_size;
2959 	map->def.max_entries = def->max_entries;
2960 	map->def.map_flags = def->map_flags;
2961 	map->map_extra = def->map_extra;
2962 
2963 	map->numa_node = def->numa_node;
2964 	map->btf_key_type_id = def->key_type_id;
2965 	map->btf_value_type_id = def->value_type_id;
2966 
2967 	/* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
2968 	if (map_is_ringbuf(map))
2969 		map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
2970 
2971 	if (def->parts & MAP_DEF_MAP_TYPE)
2972 		pr_debug("map '%s': found type = %u.\n", map->name, def->map_type);
2973 
2974 	if (def->parts & MAP_DEF_KEY_TYPE)
2975 		pr_debug("map '%s': found key [%u], sz = %u.\n",
2976 			 map->name, def->key_type_id, def->key_size);
2977 	else if (def->parts & MAP_DEF_KEY_SIZE)
2978 		pr_debug("map '%s': found key_size = %u.\n", map->name, def->key_size);
2979 
2980 	if (def->parts & MAP_DEF_VALUE_TYPE)
2981 		pr_debug("map '%s': found value [%u], sz = %u.\n",
2982 			 map->name, def->value_type_id, def->value_size);
2983 	else if (def->parts & MAP_DEF_VALUE_SIZE)
2984 		pr_debug("map '%s': found value_size = %u.\n", map->name, def->value_size);
2985 
2986 	if (def->parts & MAP_DEF_MAX_ENTRIES)
2987 		pr_debug("map '%s': found max_entries = %u.\n", map->name, def->max_entries);
2988 	if (def->parts & MAP_DEF_MAP_FLAGS)
2989 		pr_debug("map '%s': found map_flags = 0x%x.\n", map->name, def->map_flags);
2990 	if (def->parts & MAP_DEF_MAP_EXTRA)
2991 		pr_debug("map '%s': found map_extra = 0x%llx.\n", map->name,
2992 			 (unsigned long long)def->map_extra);
2993 	if (def->parts & MAP_DEF_PINNING)
2994 		pr_debug("map '%s': found pinning = %u.\n", map->name, def->pinning);
2995 	if (def->parts & MAP_DEF_NUMA_NODE)
2996 		pr_debug("map '%s': found numa_node = %u.\n", map->name, def->numa_node);
2997 
2998 	if (def->parts & MAP_DEF_INNER_MAP)
2999 		pr_debug("map '%s': found inner map definition.\n", map->name);
3000 }
3001 
3002 static const char *btf_var_linkage_str(__u32 linkage)
3003 {
3004 	switch (linkage) {
3005 	case BTF_VAR_STATIC: return "static";
3006 	case BTF_VAR_GLOBAL_ALLOCATED: return "global";
3007 	case BTF_VAR_GLOBAL_EXTERN: return "extern";
3008 	default: return "unknown";
3009 	}
3010 }
3011 
3012 static int bpf_object__init_user_btf_map(struct bpf_object *obj,
3013 					 const struct btf_type *sec,
3014 					 int var_idx, int sec_idx,
3015 					 const Elf_Data *data, bool strict,
3016 					 const char *pin_root_path)
3017 {
3018 	struct btf_map_def map_def = {}, inner_def = {};
3019 	const struct btf_type *var, *def;
3020 	const struct btf_var_secinfo *vi;
3021 	const struct btf_var *var_extra;
3022 	const char *map_name;
3023 	struct bpf_map *map;
3024 	int err;
3025 
3026 	vi = btf_var_secinfos(sec) + var_idx;
3027 	var = btf__type_by_id(obj->btf, vi->type);
3028 	var_extra = btf_var(var);
3029 	map_name = btf__name_by_offset(obj->btf, var->name_off);
3030 
3031 	if (str_is_empty(map_name)) {
3032 		pr_warn("map #%d: empty name.\n", var_idx);
3033 		return -EINVAL;
3034 	}
3035 	if ((__u64)vi->offset + vi->size > data->d_size) {
3036 		pr_warn("map '%s' BTF data is corrupted.\n", map_name);
3037 		return -EINVAL;
3038 	}
3039 	if (!btf_is_var(var)) {
3040 		pr_warn("map '%s': unexpected var kind %s.\n",
3041 			map_name, btf_kind_str(var));
3042 		return -EINVAL;
3043 	}
3044 	if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED) {
3045 		pr_warn("map '%s': unsupported map linkage %s.\n",
3046 			map_name, btf_var_linkage_str(var_extra->linkage));
3047 		return -EOPNOTSUPP;
3048 	}
3049 
3050 	def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
3051 	if (!btf_is_struct(def)) {
3052 		pr_warn("map '%s': unexpected def kind %s.\n",
3053 			map_name, btf_kind_str(var));
3054 		return -EINVAL;
3055 	}
3056 	if (def->size > vi->size) {
3057 		pr_warn("map '%s': invalid def size.\n", map_name);
3058 		return -EINVAL;
3059 	}
3060 
3061 	map = bpf_object__add_map(obj);
3062 	if (IS_ERR(map))
3063 		return PTR_ERR(map);
3064 	map->name = strdup(map_name);
3065 	if (!map->name) {
3066 		pr_warn("map '%s': failed to alloc map name.\n", map_name);
3067 		return -ENOMEM;
3068 	}
3069 	map->libbpf_type = LIBBPF_MAP_UNSPEC;
3070 	map->def.type = BPF_MAP_TYPE_UNSPEC;
3071 	map->sec_idx = sec_idx;
3072 	map->sec_offset = vi->offset;
3073 	map->btf_var_idx = var_idx;
3074 	pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
3075 		 map_name, map->sec_idx, map->sec_offset);
3076 
3077 	err = parse_btf_map_def(map->name, obj->btf, def, strict, &map_def, &inner_def);
3078 	if (err)
3079 		return err;
3080 
3081 	fill_map_from_def(map, &map_def);
3082 
3083 	if (map_def.pinning == LIBBPF_PIN_BY_NAME) {
3084 		err = build_map_pin_path(map, pin_root_path);
3085 		if (err) {
3086 			pr_warn("map '%s': couldn't build pin path.\n", map->name);
3087 			return err;
3088 		}
3089 	}
3090 
3091 	if (map_def.parts & MAP_DEF_INNER_MAP) {
3092 		map->inner_map = calloc(1, sizeof(*map->inner_map));
3093 		if (!map->inner_map)
3094 			return -ENOMEM;
3095 		map->inner_map->fd = create_placeholder_fd();
3096 		if (map->inner_map->fd < 0)
3097 			return map->inner_map->fd;
3098 		map->inner_map->sec_idx = sec_idx;
3099 		map->inner_map->name = malloc(strlen(map_name) + sizeof(".inner") + 1);
3100 		if (!map->inner_map->name)
3101 			return -ENOMEM;
3102 		sprintf(map->inner_map->name, "%s.inner", map_name);
3103 
3104 		fill_map_from_def(map->inner_map, &inner_def);
3105 	}
3106 
3107 	err = map_fill_btf_type_info(obj, map);
3108 	if (err)
3109 		return err;
3110 
3111 	return 0;
3112 }
3113 
3114 static int init_arena_map_data(struct bpf_object *obj, struct bpf_map *map,
3115 			       void *data, size_t data_sz)
3116 {
3117 	obj->arena_data = malloc(data_sz);
3118 	if (!obj->arena_data)
3119 		return -ENOMEM;
3120 	memcpy(obj->arena_data, data, data_sz);
3121 	obj->arena_data_sz = data_sz;
3122 
3123 	/* make bpf_map__init_value() work for ARENA maps */
3124 	map->mmaped = obj->arena_data;
3125 
3126 	return 0;
3127 }
3128 
3129 static bool map_is_const_str(const struct bpf_map *map)
3130 {
3131 	return map->libbpf_type == LIBBPF_MAP_RODATA &&
3132 	       str_has_pfx(map->real_name, RODATA_SEC ".str");
3133 }
3134 
3135 static bool map_data_goes_to_arena(const struct bpf_object *obj, const struct bpf_map *map)
3136 {
3137 	int i;
3138 
3139 	switch (map->libbpf_type) {
3140 	case LIBBPF_MAP_DATA:
3141 	case LIBBPF_MAP_BSS:
3142 		return true;
3143 	case LIBBPF_MAP_RODATA:
3144 		break;
3145 	default:
3146 		return false;
3147 	}
3148 
3149 	/*
3150 	 * Const strings that kfuncs and helpers take have to be in a frozen
3151 	 * map. Pointers to them that are stored in data point to a copy of
3152 	 * the strings that is in arena.
3153 	 */
3154 	if (map_is_const_str(map))
3155 		return true;
3156 	/*
3157 	 * Read-only data with pointers stays a frozen map: the kernel
3158 	 * recognizes pointers to functions in it.
3159 	 */
3160 	if (str_has_pfx(map->real_name, DATA_REL_RO_SEC))
3161 		return false;
3162 	for (i = 0; i < obj->efile.sec_cnt; i++) {
3163 		const struct elf_sec_desc *sec = &obj->efile.secs[i];
3164 
3165 		if (sec->sec_type == SEC_RELO && sec->shdr->sh_info == map->sec_idx)
3166 			return false;
3167 	}
3168 	return true;
3169 }
3170 
3171 /* Returns the offset of the data of the map in arena data that is sz bytes so far */
3172 static size_t map_arena_off(const struct bpf_object *obj, const struct bpf_map *map, size_t sz)
3173 {
3174 	size_t align = obj->efile.secs[map->sec_idx].shdr->sh_addralign;
3175 
3176 	return roundup(sz, max(align, sizeof(__u64)));
3177 }
3178 
3179 /*
3180  * Make .data, .bss and .rodata a part of arena data. They follow __arena
3181  * variables of the object, if there are any.
3182  */
3183 static int bpf_object__init_arena_data(struct bpf_object *obj)
3184 {
3185 	const size_t page_sz = sysconf(_SC_PAGE_SIZE);
3186 	size_t sz = obj->arena_data_sz;
3187 	struct bpf_map *map;
3188 	void *data;
3189 	int i;
3190 
3191 	if (!obj->data_in_arena)
3192 		return 0;
3193 
3194 	for (i = 0; i < obj->nr_maps; i++) {
3195 		map = &obj->maps[i];
3196 		if (map_data_goes_to_arena(obj, map))
3197 			sz = map_arena_off(obj, map, sz) + map->def.value_size;
3198 	}
3199 	if (sz == obj->arena_data_sz)
3200 		return 0;
3201 
3202 	if (obj->arena_map_idx < 0) {
3203 		/* bpf_object__init_user_btf_maps() didn't look: there is no .maps section */
3204 		if (obj->efile.arena_data) {
3205 			pr_warn("elf: sec '%s': to use global __arena variables the ARENA map should be explicitly declared in SEC(\".maps\")\n",
3206 				ARENA_SEC);
3207 			return -ENOENT;
3208 		}
3209 
3210 		map = bpf_object__add_map(obj);
3211 		if (IS_ERR(map))
3212 			return PTR_ERR(map);
3213 
3214 		map->real_name = strdup("arena");
3215 		map->name = strdup("arena");
3216 		if (!map->real_name || !map->name) {
3217 			zfree(&map->real_name);
3218 			zfree(&map->name);
3219 			return -ENOMEM;
3220 		}
3221 		map->sec_idx = -1;
3222 		map->def.type = BPF_MAP_TYPE_ARENA;
3223 		map->def.max_entries = roundup(sz, page_sz) / page_sz;
3224 		map->def.map_flags = BPF_F_MMAPABLE;
3225 		obj->arena_map_idx = map - obj->maps;
3226 	}
3227 
3228 	data = realloc(obj->arena_data, sz);
3229 	if (!data)
3230 		return -ENOMEM;
3231 	memset(data + obj->arena_data_sz, 0, sz - obj->arena_data_sz);
3232 	sz = obj->arena_data_sz;
3233 	obj->arena_data = data;
3234 	obj->maps[obj->arena_map_idx].mmaped = data;
3235 
3236 	for (i = 0; i < obj->nr_maps; i++) {
3237 		map = &obj->maps[i];
3238 		if (!map_data_goes_to_arena(obj, map))
3239 			continue;
3240 		sz = map_arena_off(obj, map, sz);
3241 		map->arena_off = sz;
3242 		memcpy(data + sz, map->mmaped, map->def.value_size);
3243 		sz += map->def.value_size;
3244 		pr_debug("map '%s': data is in arena at offset %zu\n", map->name, map->arena_off);
3245 		if (map_is_const_str(map)) {
3246 			map->arena_copy = true;
3247 			continue;
3248 		}
3249 		munmap(map->mmaped, bpf_map_mmap_sz(map));
3250 		/* make bpf_map__initial_value() and bpf_map__set_initial_value() work */
3251 		map->mmaped = data + map->arena_off;
3252 		map->autocreate = false;
3253 		map->in_arena = true;
3254 	}
3255 	obj->arena_data_sz = sz;
3256 	return 0;
3257 }
3258 
3259 static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict,
3260 					  const char *pin_root_path)
3261 {
3262 	const struct btf_type *sec = NULL;
3263 	int nr_types, i, vlen, err;
3264 	const struct btf_type *t;
3265 	const char *name;
3266 	Elf_Data *data;
3267 	Elf_Scn *scn;
3268 
3269 	if (obj->efile.btf_maps_shndx < 0)
3270 		return 0;
3271 
3272 	scn = elf_sec_by_idx(obj, obj->efile.btf_maps_shndx);
3273 	data = elf_sec_data(obj, scn);
3274 	if (!data) {
3275 		pr_warn("elf: failed to get %s map definitions for %s\n",
3276 			MAPS_ELF_SEC, obj->path);
3277 		return -EINVAL;
3278 	}
3279 
3280 	nr_types = btf__type_cnt(obj->btf);
3281 	for (i = 1; i < nr_types; i++) {
3282 		t = btf__type_by_id(obj->btf, i);
3283 		if (!btf_is_datasec(t))
3284 			continue;
3285 		name = btf__name_by_offset(obj->btf, t->name_off);
3286 		if (strcmp(name, MAPS_ELF_SEC) == 0) {
3287 			sec = t;
3288 			obj->efile.btf_maps_sec_btf_id = i;
3289 			break;
3290 		}
3291 	}
3292 
3293 	if (!sec) {
3294 		pr_warn("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
3295 		return -ENOENT;
3296 	}
3297 
3298 	vlen = btf_vlen(sec);
3299 	for (i = 0; i < vlen; i++) {
3300 		err = bpf_object__init_user_btf_map(obj, sec, i,
3301 						    obj->efile.btf_maps_shndx,
3302 						    data, strict,
3303 						    pin_root_path);
3304 		if (err)
3305 			return err;
3306 	}
3307 
3308 	for (i = 0; i < obj->nr_maps; i++) {
3309 		struct bpf_map *map = &obj->maps[i];
3310 
3311 		if (map->def.type != BPF_MAP_TYPE_ARENA)
3312 			continue;
3313 
3314 		if (obj->arena_map_idx >= 0) {
3315 			pr_warn("map '%s': only single ARENA map is supported (map '%s' is also ARENA)\n",
3316 				map->name, obj->maps[obj->arena_map_idx].name);
3317 			return -EINVAL;
3318 		}
3319 		obj->arena_map_idx = i;
3320 
3321 		if (obj->efile.arena_data) {
3322 			err = init_arena_map_data(obj, map, obj->efile.arena_data->d_buf,
3323 						  obj->efile.arena_data->d_size);
3324 			if (err)
3325 				return err;
3326 		}
3327 	}
3328 	if (obj->efile.arena_data && obj->arena_map_idx < 0) {
3329 		pr_warn("elf: sec '%s': to use global __arena variables the ARENA map should be explicitly declared in SEC(\".maps\")\n",
3330 			ARENA_SEC);
3331 		return -ENOENT;
3332 	}
3333 
3334 	return 0;
3335 }
3336 
3337 static int bpf_object__init_maps(struct bpf_object *obj,
3338 				 const struct bpf_object_open_opts *opts)
3339 {
3340 	const char *pin_root_path;
3341 	bool strict;
3342 	int err = 0;
3343 
3344 	strict = !OPTS_GET(opts, relaxed_maps, false);
3345 	pin_root_path = OPTS_GET(opts, pin_root_path, NULL);
3346 
3347 	err = bpf_object__init_user_btf_maps(obj, strict, pin_root_path);
3348 	err = err ?: bpf_object__init_global_data_maps(obj);
3349 	err = err ?: bpf_object__init_kconfig_map(obj);
3350 	err = err ?: bpf_object_init_struct_ops(obj);
3351 	err = err ?: bpf_object__init_arena_data(obj);
3352 
3353 	return err;
3354 }
3355 
3356 static bool section_have_execinstr(struct bpf_object *obj, int idx)
3357 {
3358 	Elf64_Shdr *sh;
3359 
3360 	sh = elf_sec_hdr(obj, elf_sec_by_idx(obj, idx));
3361 	if (!sh)
3362 		return false;
3363 
3364 	return sh->sh_flags & SHF_EXECINSTR;
3365 }
3366 
3367 static bool starts_with_qmark(const char *s)
3368 {
3369 	return s && s[0] == '?';
3370 }
3371 
3372 static bool btf_needs_sanitization(struct bpf_object *obj)
3373 {
3374 	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
3375 	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
3376 	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
3377 	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
3378 	bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
3379 	bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
3380 	bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
3381 	bool has_qmark_datasec = kernel_supports(obj, FEAT_BTF_QMARK_DATASEC);
3382 	bool has_layout = kernel_supports(obj, FEAT_BTF_LAYOUT);
3383 
3384 	return !has_func || !has_datasec || !has_func_global || !has_float ||
3385 	       !has_decl_tag || !has_type_tag || !has_enum64 || !has_qmark_datasec ||
3386 	       !has_layout;
3387 }
3388 
3389 struct btf *bpf_object__sanitize_btf(struct bpf_object *obj, struct btf *orig_btf)
3390 {
3391 	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
3392 	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
3393 	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
3394 	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
3395 	bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
3396 	bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
3397 	bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
3398 	bool has_qmark_datasec = kernel_supports(obj, FEAT_BTF_QMARK_DATASEC);
3399 	bool has_layout = kernel_supports(obj, FEAT_BTF_LAYOUT);
3400 	int enum64_placeholder_id = 0;
3401 	const struct btf_header *hdr;
3402 	struct btf *btf = NULL;
3403 	const void *raw_data;
3404 	struct btf_type *t;
3405 	int i, j, vlen;
3406 	__u32 sz;
3407 	int err;
3408 
3409 	/* clone BTF to sanitize a copy and leave the original intact */
3410 	raw_data = btf__raw_data(orig_btf, &sz);
3411 	if (!raw_data)
3412 		return ERR_PTR(-ENOMEM);
3413 	/* btf_header() gives us endian-safe header info */
3414 	hdr = btf_header(orig_btf);
3415 
3416 	if (!has_layout && hdr->hdr_len >= sizeof(struct btf_header) &&
3417 	    (hdr->layout_len != 0 || hdr->layout_off != 0)) {
3418 		const struct btf_header *old_hdr = raw_data;
3419 		struct btf_header *new_hdr;
3420 		void *new_raw_data;
3421 		__u32 new_str_off;
3422 
3423 		/*
3424 		 * Need to rewrite BTF to exclude layout information and
3425 		 * move string section to immediately after types.
3426 		 */
3427 		new_raw_data = malloc(sz);
3428 		if (!new_raw_data)
3429 			return ERR_PTR(-ENOMEM);
3430 
3431 		memcpy(new_raw_data, raw_data, sz);
3432 		new_hdr = new_raw_data;
3433 		new_hdr->layout_off = 0;
3434 		new_hdr->layout_len = 0;
3435 		new_str_off = hdr->type_off + hdr->type_len;
3436 		/* Handle swapped endian case */
3437 		if (old_hdr->magic != hdr->magic)
3438 			new_hdr->str_off = bswap_32(new_str_off);
3439 		else
3440 			new_hdr->str_off = new_str_off;
3441 
3442 		memmove(new_raw_data + hdr->hdr_len + new_str_off,
3443 			new_raw_data + hdr->hdr_len + hdr->str_off,
3444 			hdr->str_len);
3445 		sz = hdr->hdr_len + hdr->type_off + hdr->type_len + hdr->str_len;
3446 		btf = btf__new(new_raw_data, sz);
3447 		free(new_raw_data);
3448 	} else {
3449 		btf = btf__new(raw_data, sz);
3450 	}
3451 	err = libbpf_get_error(btf);
3452 	if (err)
3453 		return ERR_PTR(err);
3454 
3455 	/* enforce 8-byte pointers for BPF-targeted BTFs */
3456 	btf__set_pointer_size(btf, 8);
3457 
3458 	for (i = 1; i < btf__type_cnt(btf); i++) {
3459 		t = (struct btf_type *)btf__type_by_id(btf, i);
3460 
3461 		if ((!has_datasec && btf_is_var(t)) || (!has_decl_tag && btf_is_decl_tag(t))) {
3462 			/* replace VAR/DECL_TAG with INT */
3463 			t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
3464 			/*
3465 			 * using size = 1 is the safest choice, 4 will be too
3466 			 * big and cause kernel BTF validation failure if
3467 			 * original variable took less than 4 bytes
3468 			 */
3469 			t->size = 1;
3470 			*(int *)(t + 1) = BTF_INT_ENC(0, 0, 8);
3471 		} else if (!has_datasec && btf_is_datasec(t)) {
3472 			/* replace DATASEC with STRUCT */
3473 			const struct btf_var_secinfo *v = btf_var_secinfos(t);
3474 			struct btf_member *m = btf_members(t);
3475 			struct btf_type *vt;
3476 			char *name;
3477 
3478 			name = (char *)btf__name_by_offset(btf, t->name_off);
3479 			while (*name) {
3480 				if (*name == '.' || *name == '?')
3481 					*name = '_';
3482 				name++;
3483 			}
3484 
3485 			vlen = btf_vlen(t);
3486 			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
3487 			for (j = 0; j < vlen; j++, v++, m++) {
3488 				/* order of field assignments is important */
3489 				m->offset = v->offset * 8;
3490 				m->type = v->type;
3491 				/* preserve variable name as member name */
3492 				vt = (void *)btf__type_by_id(btf, v->type);
3493 				m->name_off = vt->name_off;
3494 			}
3495 		} else if (!has_qmark_datasec && btf_is_datasec(t) &&
3496 			   starts_with_qmark(btf__name_by_offset(btf, t->name_off))) {
3497 			/* replace '?' prefix with '_' for DATASEC names */
3498 			char *name;
3499 
3500 			name = (char *)btf__name_by_offset(btf, t->name_off);
3501 			if (name[0] == '?')
3502 				name[0] = '_';
3503 		} else if (!has_func && btf_is_func_proto(t)) {
3504 			/* replace FUNC_PROTO with ENUM */
3505 			vlen = btf_vlen(t);
3506 			t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
3507 			t->size = sizeof(__u32); /* kernel enforced */
3508 		} else if (!has_func && btf_is_func(t)) {
3509 			/* replace FUNC with TYPEDEF */
3510 			t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
3511 		} else if (!has_func_global && btf_is_func(t)) {
3512 			/* replace BTF_FUNC_GLOBAL with BTF_FUNC_STATIC */
3513 			t->info = BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0);
3514 		} else if (!has_float && btf_is_float(t)) {
3515 			/* replace FLOAT with an equally-sized empty STRUCT;
3516 			 * since C compilers do not accept e.g. "float" as a
3517 			 * valid struct name, make it anonymous
3518 			 */
3519 			t->name_off = 0;
3520 			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, 0);
3521 		} else if (!has_type_tag && btf_is_type_tag(t)) {
3522 			/* replace TYPE_TAG with a CONST */
3523 			t->name_off = 0;
3524 			t->info = BTF_INFO_ENC(BTF_KIND_CONST, 0, 0);
3525 		} else if (!has_enum64 && btf_is_enum(t)) {
3526 			/* clear the kflag */
3527 			t->info = btf_type_info(btf_kind(t), btf_vlen(t), false);
3528 		} else if (!has_enum64 && btf_is_enum64(t)) {
3529 			/* replace ENUM64 with a union */
3530 			struct btf_member *m;
3531 
3532 			if (enum64_placeholder_id == 0) {
3533 				enum64_placeholder_id = btf__add_int(btf, "enum64_placeholder", 1, 0);
3534 				if (enum64_placeholder_id < 0) {
3535 					btf__free(btf);
3536 					return ERR_PTR(enum64_placeholder_id);
3537 				}
3538 				t = (struct btf_type *)btf__type_by_id(btf, i);
3539 			}
3540 
3541 			m = btf_members(t);
3542 			vlen = btf_vlen(t);
3543 			t->info = BTF_INFO_ENC(BTF_KIND_UNION, 0, vlen);
3544 			for (j = 0; j < vlen; j++, m++) {
3545 				m->type = enum64_placeholder_id;
3546 				m->offset = 0;
3547 			}
3548 		}
3549 	}
3550 
3551 	return btf;
3552 }
3553 
3554 static bool libbpf_needs_btf(const struct bpf_object *obj)
3555 {
3556 	return obj->efile.btf_maps_shndx >= 0 ||
3557 	       obj->efile.has_st_ops ||
3558 	       obj->nr_extern > 0;
3559 }
3560 
3561 static bool kernel_needs_btf(const struct bpf_object *obj)
3562 {
3563 	return obj->efile.has_st_ops;
3564 }
3565 
3566 static int bpf_object__init_btf(struct bpf_object *obj,
3567 				Elf_Data *btf_data,
3568 				Elf_Data *btf_ext_data)
3569 {
3570 	int err = -ENOENT;
3571 
3572 	if (btf_data) {
3573 		obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
3574 		err = libbpf_get_error(obj->btf);
3575 		if (err) {
3576 			obj->btf = NULL;
3577 			pr_warn("Error loading ELF section %s: %s.\n", BTF_ELF_SEC, errstr(err));
3578 			goto out;
3579 		}
3580 		/* enforce 8-byte pointers for BPF-targeted BTFs */
3581 		btf__set_pointer_size(obj->btf, 8);
3582 	}
3583 	if (btf_ext_data) {
3584 		struct btf_ext_info *ext_segs[3];
3585 		int seg_num, sec_num;
3586 
3587 		if (!obj->btf) {
3588 			pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
3589 				 BTF_EXT_ELF_SEC, BTF_ELF_SEC);
3590 			goto out;
3591 		}
3592 		obj->btf_ext = btf_ext__new(btf_ext_data->d_buf, btf_ext_data->d_size);
3593 		err = libbpf_get_error(obj->btf_ext);
3594 		if (err) {
3595 			pr_warn("Error loading ELF section %s: %s. Ignored and continue.\n",
3596 				BTF_EXT_ELF_SEC, errstr(err));
3597 			obj->btf_ext = NULL;
3598 			goto out;
3599 		}
3600 
3601 		/* setup .BTF.ext to ELF section mapping */
3602 		ext_segs[0] = &obj->btf_ext->func_info;
3603 		ext_segs[1] = &obj->btf_ext->line_info;
3604 		ext_segs[2] = &obj->btf_ext->core_relo_info;
3605 		for (seg_num = 0; seg_num < ARRAY_SIZE(ext_segs); seg_num++) {
3606 			struct btf_ext_info *seg = ext_segs[seg_num];
3607 			const struct btf_ext_info_sec *sec;
3608 			const char *sec_name;
3609 			Elf_Scn *scn;
3610 
3611 			if (seg->sec_cnt == 0)
3612 				continue;
3613 
3614 			seg->sec_idxs = calloc(seg->sec_cnt, sizeof(*seg->sec_idxs));
3615 			if (!seg->sec_idxs) {
3616 				err = -ENOMEM;
3617 				goto out;
3618 			}
3619 
3620 			sec_num = 0;
3621 			for_each_btf_ext_sec(seg, sec) {
3622 				/* preventively increment index to avoid doing
3623 				 * this before every continue below
3624 				 */
3625 				sec_num++;
3626 
3627 				sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
3628 				if (str_is_empty(sec_name))
3629 					continue;
3630 				scn = elf_sec_by_name(obj, sec_name);
3631 				if (!scn)
3632 					continue;
3633 
3634 				seg->sec_idxs[sec_num - 1] = elf_ndxscn(scn);
3635 			}
3636 		}
3637 	}
3638 out:
3639 	if (err && libbpf_needs_btf(obj)) {
3640 		pr_warn("BTF is required, but is missing or corrupted.\n");
3641 		return err;
3642 	}
3643 	return 0;
3644 }
3645 
3646 static int compare_vsi_off(const void *_a, const void *_b)
3647 {
3648 	const struct btf_var_secinfo *a = _a;
3649 	const struct btf_var_secinfo *b = _b;
3650 
3651 	return a->offset - b->offset;
3652 }
3653 
3654 static int btf_fixup_datasec(struct bpf_object *obj, struct btf *btf,
3655 			     struct btf_type *t)
3656 {
3657 	__u32 size = 0, i, vars = btf_vlen(t);
3658 	const char *sec_name = btf__name_by_offset(btf, t->name_off);
3659 	struct btf_var_secinfo *vsi;
3660 	bool fixup_offsets = false;
3661 	int err;
3662 
3663 	if (!sec_name) {
3664 		pr_debug("No name found in string section for DATASEC kind.\n");
3665 		return -ENOENT;
3666 	}
3667 
3668 	/* Extern-backing datasecs (.ksyms, .kconfig) have their size and
3669 	 * variable offsets set at the previous step. Further, not every
3670 	 * extern BTF VAR has corresponding ELF symbol preserved, so we skip
3671 	 * all fixups altogether for such sections and go straight to sorting
3672 	 * VARs within their DATASEC.
3673 	 */
3674 	if (strcmp(sec_name, KCONFIG_SEC) == 0 || strcmp(sec_name, KSYMS_SEC) == 0)
3675 		goto sort_vars;
3676 
3677 	/* Clang leaves DATASEC size and VAR offsets as zeroes, so we need to
3678 	 * fix this up. But BPF static linker already fixes this up and fills
3679 	 * all the sizes and offsets during static linking. So this step has
3680 	 * to be optional. But the STV_HIDDEN handling is non-optional for any
3681 	 * non-extern DATASEC, so the variable fixup loop below handles both
3682 	 * functions at the same time, paying the cost of BTF VAR <-> ELF
3683 	 * symbol matching just once.
3684 	 */
3685 	if (t->size == 0) {
3686 		err = find_elf_sec_sz(obj, sec_name, &size);
3687 		if (err || !size) {
3688 			pr_debug("sec '%s': failed to determine size from ELF: size %u, err %s\n",
3689 				 sec_name, size, errstr(err));
3690 			return -ENOENT;
3691 		}
3692 
3693 		t->size = size;
3694 		fixup_offsets = true;
3695 	}
3696 
3697 	for (i = 0, vsi = btf_var_secinfos(t); i < vars; i++, vsi++) {
3698 		const struct btf_type *t_var;
3699 		struct btf_var *var;
3700 		const char *var_name;
3701 		Elf64_Sym *sym;
3702 
3703 		t_var = btf__type_by_id(btf, vsi->type);
3704 		if (!t_var || !btf_is_var(t_var)) {
3705 			pr_debug("sec '%s': unexpected non-VAR type found\n", sec_name);
3706 			return -EINVAL;
3707 		}
3708 
3709 		var = btf_var(t_var);
3710 		if (var->linkage == BTF_VAR_STATIC || var->linkage == BTF_VAR_GLOBAL_EXTERN)
3711 			continue;
3712 
3713 		var_name = btf__name_by_offset(btf, t_var->name_off);
3714 		if (!var_name) {
3715 			pr_debug("sec '%s': failed to find name of DATASEC's member #%u\n",
3716 				 sec_name, i);
3717 			return -ENOENT;
3718 		}
3719 
3720 		sym = find_elf_var_sym(obj, var_name);
3721 		if (IS_ERR(sym)) {
3722 			pr_debug("sec '%s': failed to find ELF symbol for VAR '%s'\n",
3723 				 sec_name, var_name);
3724 			return -ENOENT;
3725 		}
3726 
3727 		if (fixup_offsets)
3728 			vsi->offset = sym->st_value;
3729 
3730 		/* if variable is a global/weak symbol, but has restricted
3731 		 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF VAR
3732 		 * as static. This follows similar logic for functions (BPF
3733 		 * subprogs) and influences libbpf's further decisions about
3734 		 * whether to make global data BPF array maps as
3735 		 * BPF_F_MMAPABLE.
3736 		 */
3737 		if (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
3738 		    || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL)
3739 			var->linkage = BTF_VAR_STATIC;
3740 	}
3741 
3742 sort_vars:
3743 	qsort(btf_var_secinfos(t), vars, sizeof(*vsi), compare_vsi_off);
3744 	return 0;
3745 }
3746 
3747 static int bpf_object_fixup_btf(struct bpf_object *obj)
3748 {
3749 	int i, n, err = 0;
3750 
3751 	if (!obj->btf)
3752 		return 0;
3753 
3754 	n = btf__type_cnt(obj->btf);
3755 	for (i = 1; i < n; i++) {
3756 		struct btf_type *t = btf_type_by_id(obj->btf, i);
3757 
3758 		/* Loader needs to fix up some of the things compiler
3759 		 * couldn't get its hands on while emitting BTF. This
3760 		 * is section size and global variable offset. We use
3761 		 * the info from the ELF itself for this purpose.
3762 		 */
3763 		if (btf_is_datasec(t)) {
3764 			err = btf_fixup_datasec(obj, obj->btf, t);
3765 			if (err)
3766 				return err;
3767 		}
3768 	}
3769 
3770 	return 0;
3771 }
3772 
3773 static bool prog_needs_vmlinux_btf(struct bpf_program *prog)
3774 {
3775 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
3776 	    prog->type == BPF_PROG_TYPE_LSM)
3777 		return true;
3778 
3779 	/* BPF_PROG_TYPE_TRACING programs which do not attach to other programs
3780 	 * also need vmlinux BTF
3781 	 */
3782 	if (prog->type == BPF_PROG_TYPE_TRACING && !prog->attach_prog_fd)
3783 		return true;
3784 
3785 	return false;
3786 }
3787 
3788 static bool map_needs_vmlinux_btf(struct bpf_map *map)
3789 {
3790 	return bpf_map__is_struct_ops(map);
3791 }
3792 
3793 static bool obj_needs_vmlinux_btf(const struct bpf_object *obj)
3794 {
3795 	struct bpf_program *prog;
3796 	struct bpf_map *map;
3797 	int i;
3798 
3799 	/* CO-RE relocations need kernel BTF, only when btf_custom_path
3800 	 * is not specified
3801 	 */
3802 	if (obj->btf_ext && obj->btf_ext->core_relo_info.len && !obj->btf_custom_path)
3803 		return true;
3804 
3805 	/* Support for typed ksyms needs kernel BTF */
3806 	for (i = 0; i < obj->nr_extern; i++) {
3807 		const struct extern_desc *ext;
3808 
3809 		ext = &obj->externs[i];
3810 		if (ext->type == EXT_KSYM && ext->ksym.type_id)
3811 			return true;
3812 	}
3813 
3814 	bpf_object__for_each_program(prog, obj) {
3815 		if (!prog->autoload)
3816 			continue;
3817 		if (prog_needs_vmlinux_btf(prog))
3818 			return true;
3819 	}
3820 
3821 	bpf_object__for_each_map(map, obj) {
3822 		if (map_needs_vmlinux_btf(map))
3823 			return true;
3824 	}
3825 
3826 	return false;
3827 }
3828 
3829 static int bpf_object__load_vmlinux_btf(struct bpf_object *obj, bool force)
3830 {
3831 	int err;
3832 
3833 	/* btf_vmlinux could be loaded earlier */
3834 	if (obj->btf_vmlinux || obj->gen_loader)
3835 		return 0;
3836 
3837 	if (!force && !obj_needs_vmlinux_btf(obj))
3838 		return 0;
3839 
3840 	obj->btf_vmlinux = btf__load_vmlinux_btf();
3841 	err = libbpf_get_error(obj->btf_vmlinux);
3842 	if (err) {
3843 		pr_warn("Error loading vmlinux BTF: %s\n", errstr(err));
3844 		obj->btf_vmlinux = NULL;
3845 		return err;
3846 	}
3847 	return 0;
3848 }
3849 
3850 static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
3851 {
3852 	struct btf *kern_btf = obj->btf;
3853 	bool btf_mandatory, sanitize;
3854 	int i, err = 0;
3855 
3856 	if (!obj->btf)
3857 		return 0;
3858 
3859 	if (!kernel_supports(obj, FEAT_BTF)) {
3860 		if (kernel_needs_btf(obj)) {
3861 			err = -EOPNOTSUPP;
3862 			goto report;
3863 		}
3864 		pr_debug("Kernel doesn't support BTF, skipping uploading it.\n");
3865 		return 0;
3866 	}
3867 
3868 	/* Even though some subprogs are global/weak, user might prefer more
3869 	 * permissive BPF verification process that BPF verifier performs for
3870 	 * static functions, taking into account more context from the caller
3871 	 * functions. In such case, they need to mark such subprogs with
3872 	 * __attribute__((visibility("hidden"))) and libbpf will adjust
3873 	 * corresponding FUNC BTF type to be marked as static and trigger more
3874 	 * involved BPF verification process.
3875 	 */
3876 	for (i = 0; i < obj->nr_programs; i++) {
3877 		struct bpf_program *prog = &obj->programs[i];
3878 		struct btf_type *t;
3879 		const char *name;
3880 		int j, n;
3881 
3882 		if (!prog->mark_btf_static || !prog_is_subprog(obj, prog))
3883 			continue;
3884 
3885 		n = btf__type_cnt(obj->btf);
3886 		for (j = 1; j < n; j++) {
3887 			t = btf_type_by_id(obj->btf, j);
3888 			if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL)
3889 				continue;
3890 
3891 			name = btf__str_by_offset(obj->btf, t->name_off);
3892 			if (strcmp(name, prog->name) != 0)
3893 				continue;
3894 
3895 			t->info = btf_type_info(BTF_KIND_FUNC, BTF_FUNC_STATIC, 0);
3896 			break;
3897 		}
3898 	}
3899 
3900 	sanitize = btf_needs_sanitization(obj);
3901 	if (sanitize) {
3902 		kern_btf = bpf_object__sanitize_btf(obj, obj->btf);
3903 		if (IS_ERR(kern_btf))
3904 			return PTR_ERR(kern_btf);
3905 	}
3906 
3907 	if (obj->gen_loader) {
3908 		__u32 raw_size = 0;
3909 		const void *raw_data = btf__raw_data(kern_btf, &raw_size);
3910 
3911 		if (!raw_data)
3912 			return -ENOMEM;
3913 		bpf_gen__load_btf(obj->gen_loader, raw_data, raw_size);
3914 		/* Pretend to have valid FD to pass various fd >= 0 checks.
3915 		 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
3916 		 */
3917 		btf__set_fd(kern_btf, 0);
3918 	} else {
3919 		/* currently BPF_BTF_LOAD only supports log_level 1 */
3920 		err = btf_load_into_kernel(kern_btf, obj->log_buf, obj->log_size,
3921 					   obj->log_level ? 1 : 0, obj->token_fd);
3922 	}
3923 	if (sanitize) {
3924 		if (!err) {
3925 			/* move fd to libbpf's BTF */
3926 			btf__set_fd(obj->btf, btf__fd(kern_btf));
3927 			btf__set_fd(kern_btf, -1);
3928 		}
3929 		btf__free(kern_btf);
3930 	}
3931 report:
3932 	if (err) {
3933 		btf_mandatory = kernel_needs_btf(obj);
3934 		if (btf_mandatory) {
3935 			pr_warn("Error loading .BTF into kernel: %s. BTF is mandatory, can't proceed.\n",
3936 				errstr(err));
3937 		} else {
3938 			pr_info("Error loading .BTF into kernel: %s. BTF is optional, ignoring.\n",
3939 				errstr(err));
3940 			err = 0;
3941 		}
3942 	}
3943 	return err;
3944 }
3945 
3946 static const char *elf_sym_str(const struct bpf_object *obj, size_t off)
3947 {
3948 	const char *name;
3949 
3950 	name = elf_strptr(obj->efile.elf, obj->efile.strtabidx, off);
3951 	if (!name) {
3952 		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3953 			off, obj->path, elf_errmsg(-1));
3954 		return NULL;
3955 	}
3956 
3957 	return name;
3958 }
3959 
3960 static const char *elf_sec_str(const struct bpf_object *obj, size_t off)
3961 {
3962 	const char *name;
3963 
3964 	name = elf_strptr(obj->efile.elf, obj->efile.shstrndx, off);
3965 	if (!name) {
3966 		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3967 			off, obj->path, elf_errmsg(-1));
3968 		return NULL;
3969 	}
3970 
3971 	return name;
3972 }
3973 
3974 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx)
3975 {
3976 	Elf_Scn *scn;
3977 
3978 	scn = elf_getscn(obj->efile.elf, idx);
3979 	if (!scn) {
3980 		pr_warn("elf: failed to get section(%zu) from %s: %s\n",
3981 			idx, obj->path, elf_errmsg(-1));
3982 		return NULL;
3983 	}
3984 	return scn;
3985 }
3986 
3987 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name)
3988 {
3989 	Elf_Scn *scn = NULL;
3990 	Elf *elf = obj->efile.elf;
3991 	const char *sec_name;
3992 
3993 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3994 		sec_name = elf_sec_name(obj, scn);
3995 		if (!sec_name)
3996 			return NULL;
3997 
3998 		if (strcmp(sec_name, name) != 0)
3999 			continue;
4000 
4001 		return scn;
4002 	}
4003 	return NULL;
4004 }
4005 
4006 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn)
4007 {
4008 	Elf64_Shdr *shdr;
4009 
4010 	if (!scn)
4011 		return NULL;
4012 
4013 	shdr = elf64_getshdr(scn);
4014 	if (!shdr) {
4015 		pr_warn("elf: failed to get section(%zu) header from %s: %s\n",
4016 			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
4017 		return NULL;
4018 	}
4019 
4020 	return shdr;
4021 }
4022 
4023 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn)
4024 {
4025 	const char *name;
4026 	Elf64_Shdr *sh;
4027 
4028 	if (!scn)
4029 		return NULL;
4030 
4031 	sh = elf_sec_hdr(obj, scn);
4032 	if (!sh)
4033 		return NULL;
4034 
4035 	name = elf_sec_str(obj, sh->sh_name);
4036 	if (!name) {
4037 		pr_warn("elf: failed to get section(%zu) name from %s: %s\n",
4038 			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
4039 		return NULL;
4040 	}
4041 
4042 	return name;
4043 }
4044 
4045 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn)
4046 {
4047 	Elf_Data *data;
4048 
4049 	if (!scn)
4050 		return NULL;
4051 
4052 	data = elf_getdata(scn, 0);
4053 	if (!data) {
4054 		pr_warn("elf: failed to get section(%zu) %s data from %s: %s\n",
4055 			elf_ndxscn(scn), elf_sec_name(obj, scn) ?: "<?>",
4056 			obj->path, elf_errmsg(-1));
4057 		return NULL;
4058 	}
4059 
4060 	return data;
4061 }
4062 
4063 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx)
4064 {
4065 	if (idx >= obj->efile.symbols->d_size / sizeof(Elf64_Sym))
4066 		return NULL;
4067 
4068 	return (Elf64_Sym *)obj->efile.symbols->d_buf + idx;
4069 }
4070 
4071 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx)
4072 {
4073 	if (idx >= data->d_size / sizeof(Elf64_Rel))
4074 		return NULL;
4075 
4076 	return (Elf64_Rel *)data->d_buf + idx;
4077 }
4078 
4079 static bool is_sec_name_dwarf(const char *name)
4080 {
4081 	/* approximation, but the actual list is too long */
4082 	return str_has_pfx(name, ".debug_");
4083 }
4084 
4085 static bool ignore_elf_section(Elf64_Shdr *hdr, const char *name)
4086 {
4087 	/* no special handling of .strtab */
4088 	if (hdr->sh_type == SHT_STRTAB)
4089 		return true;
4090 
4091 	/* ignore .llvm_addrsig section as well */
4092 	if (hdr->sh_type == SHT_LLVM_ADDRSIG)
4093 		return true;
4094 
4095 	/* no subprograms will lead to an empty .text section, ignore it */
4096 	if (hdr->sh_type == SHT_PROGBITS && hdr->sh_size == 0 &&
4097 	    strcmp(name, ".text") == 0)
4098 		return true;
4099 
4100 	/* DWARF sections */
4101 	if (is_sec_name_dwarf(name))
4102 		return true;
4103 
4104 	if (str_has_pfx(name, ".rel")) {
4105 		name += sizeof(".rel") - 1;
4106 		/* DWARF section relocations */
4107 		if (is_sec_name_dwarf(name))
4108 			return true;
4109 
4110 		/* .BTF and .BTF.ext don't need relocations */
4111 		if (strcmp(name, BTF_ELF_SEC) == 0 ||
4112 		    strcmp(name, BTF_EXT_ELF_SEC) == 0)
4113 			return true;
4114 	}
4115 
4116 	return false;
4117 }
4118 
4119 static int cmp_progs(const void *_a, const void *_b)
4120 {
4121 	const struct bpf_program *a = _a;
4122 	const struct bpf_program *b = _b;
4123 
4124 	if (a->sec_idx != b->sec_idx)
4125 		return a->sec_idx < b->sec_idx ? -1 : 1;
4126 
4127 	/* sec_insn_off can't be the same within the section */
4128 	return a->sec_insn_off < b->sec_insn_off ? -1 : 1;
4129 }
4130 
4131 static int bpf_object__elf_collect(struct bpf_object *obj)
4132 {
4133 	struct elf_sec_desc *sec_desc;
4134 	Elf *elf = obj->efile.elf;
4135 	Elf_Data *btf_ext_data = NULL;
4136 	Elf_Data *btf_data = NULL;
4137 	int idx = 0, err = 0;
4138 	const char *name;
4139 	Elf_Data *data;
4140 	Elf_Scn *scn;
4141 	Elf64_Shdr *sh;
4142 
4143 	/* ELF section indices are 0-based, but sec #0 is special "invalid"
4144 	 * section. Since section count retrieved by elf_getshdrnum() does
4145 	 * include sec #0, it is already the necessary size of an array to keep
4146 	 * all the sections.
4147 	 */
4148 	if (elf_getshdrnum(obj->efile.elf, &obj->efile.sec_cnt)) {
4149 		pr_warn("elf: failed to get the number of sections for %s: %s\n",
4150 			obj->path, elf_errmsg(-1));
4151 		return -LIBBPF_ERRNO__FORMAT;
4152 	}
4153 	obj->efile.secs = calloc(obj->efile.sec_cnt, sizeof(*obj->efile.secs));
4154 	if (!obj->efile.secs)
4155 		return -ENOMEM;
4156 
4157 	/* a bunch of ELF parsing functionality depends on processing symbols,
4158 	 * so do the first pass and find the symbol table
4159 	 */
4160 	scn = NULL;
4161 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
4162 		sh = elf_sec_hdr(obj, scn);
4163 		if (!sh)
4164 			return -LIBBPF_ERRNO__FORMAT;
4165 
4166 		/* the second pass has to know it when it sees relocations of data */
4167 		name = elf_sec_str(obj, sh->sh_name);
4168 		if (name && strcmp(name, ARENA_DATA_SEC) == 0)
4169 			obj->data_in_arena = true;
4170 
4171 		if (sh->sh_type == SHT_SYMTAB) {
4172 			if (obj->efile.symbols) {
4173 				pr_warn("elf: multiple symbol tables in %s\n", obj->path);
4174 				return -LIBBPF_ERRNO__FORMAT;
4175 			}
4176 
4177 			data = elf_sec_data(obj, scn);
4178 			if (!data)
4179 				return -LIBBPF_ERRNO__FORMAT;
4180 
4181 			idx = elf_ndxscn(scn);
4182 
4183 			obj->efile.symbols = data;
4184 			obj->efile.symbols_shndx = idx;
4185 			obj->efile.strtabidx = sh->sh_link;
4186 		}
4187 	}
4188 
4189 	if (!obj->efile.symbols) {
4190 		pr_warn("elf: couldn't find symbol table in %s, stripped object file?\n",
4191 			obj->path);
4192 		return -ENOENT;
4193 	}
4194 
4195 	scn = NULL;
4196 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
4197 		idx = elf_ndxscn(scn);
4198 		sec_desc = &obj->efile.secs[idx];
4199 
4200 		sh = elf_sec_hdr(obj, scn);
4201 		if (!sh)
4202 			return -LIBBPF_ERRNO__FORMAT;
4203 
4204 		name = elf_sec_str(obj, sh->sh_name);
4205 		if (!name)
4206 			return -LIBBPF_ERRNO__FORMAT;
4207 
4208 		if (ignore_elf_section(sh, name))
4209 			continue;
4210 
4211 		data = elf_sec_data(obj, scn);
4212 		if (!data)
4213 			return -LIBBPF_ERRNO__FORMAT;
4214 
4215 		pr_debug("elf: section(%d) %s, size %lu, link %d, flags %lx, type=%d\n",
4216 			 idx, name, (unsigned long)data->d_size,
4217 			 (int)sh->sh_link, (unsigned long)sh->sh_flags,
4218 			 (int)sh->sh_type);
4219 
4220 		if (strcmp(name, "license") == 0) {
4221 			err = bpf_object__init_license(obj, data->d_buf, data->d_size);
4222 			if (err)
4223 				return err;
4224 		} else if (strcmp(name, "version") == 0) {
4225 			err = bpf_object__init_kversion(obj, data->d_buf, data->d_size);
4226 			if (err)
4227 				return err;
4228 		} else if (strcmp(name, "maps") == 0) {
4229 			pr_warn("elf: legacy map definitions in 'maps' section are not supported by libbpf v1.0+\n");
4230 			return -ENOTSUP;
4231 		} else if (strcmp(name, MAPS_ELF_SEC) == 0) {
4232 			obj->efile.btf_maps_shndx = idx;
4233 		} else if (strcmp(name, BTF_ELF_SEC) == 0) {
4234 			if (sh->sh_type != SHT_PROGBITS)
4235 				return -LIBBPF_ERRNO__FORMAT;
4236 			btf_data = data;
4237 		} else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
4238 			if (sh->sh_type != SHT_PROGBITS)
4239 				return -LIBBPF_ERRNO__FORMAT;
4240 			btf_ext_data = data;
4241 		} else if (sh->sh_type == SHT_SYMTAB) {
4242 			/* already processed during the first pass above */
4243 		} else if (sh->sh_type == SHT_PROGBITS && data->d_size > 0) {
4244 			if (sh->sh_flags & SHF_EXECINSTR) {
4245 				if (strcmp(name, ".text") == 0)
4246 					obj->efile.text_shndx = idx;
4247 				err = bpf_object__add_programs(obj, data, name, idx);
4248 				if (err)
4249 					return err;
4250 			} else if (strcmp(name, DATA_REL_RO_SEC) == 0 ||
4251 				   str_has_pfx(name, DATA_REL_RO_SEC ".")) {
4252 				/*
4253 				 * Constants with pointers in them, e.g. vtables,
4254 				 * that position independent code keeps here to
4255 				 * have them relocated. There is nothing that
4256 				 * writes to it after that.
4257 				 */
4258 				sec_desc->sec_type = SEC_RODATA;
4259 				sec_desc->shdr = sh;
4260 				sec_desc->data = data;
4261 			} else if (strcmp(name, DATA_SEC) == 0 ||
4262 				   str_has_pfx(name, DATA_SEC ".")) {
4263 				sec_desc->sec_type = SEC_DATA;
4264 				sec_desc->shdr = sh;
4265 				sec_desc->data = data;
4266 			} else if (strcmp(name, RODATA_SEC) == 0 ||
4267 				   str_has_pfx(name, RODATA_SEC ".")) {
4268 				sec_desc->sec_type = SEC_RODATA;
4269 				sec_desc->shdr = sh;
4270 				sec_desc->data = data;
4271 			} else if (strcmp(name, PERCPU_SEC) == 0 ||
4272 				   str_has_pfx(name, PERCPU_SEC ".")) {
4273 				sec_desc->sec_type = SEC_PERCPU;
4274 				sec_desc->shdr = sh;
4275 				sec_desc->data = data;
4276 			} else if (strcmp(name, STRUCT_OPS_SEC) == 0 ||
4277 				   strcmp(name, STRUCT_OPS_LINK_SEC) == 0 ||
4278 				   strcmp(name, "?" STRUCT_OPS_SEC) == 0 ||
4279 				   strcmp(name, "?" STRUCT_OPS_LINK_SEC) == 0) {
4280 				sec_desc->sec_type = SEC_ST_OPS;
4281 				sec_desc->shdr = sh;
4282 				sec_desc->data = data;
4283 				obj->efile.has_st_ops = true;
4284 			} else if (strcmp(name, ARENA_SEC) == 0) {
4285 				obj->efile.arena_data = data;
4286 				obj->efile.arena_data_shndx = idx;
4287 			} else if (strcmp(name, ARENA_DATA_SEC) == 0) {
4288 				/* the marker, see the first pass */
4289 			} else if (strcmp(name, JUMPTABLES_SEC) == 0) {
4290 				obj->jumptables_data = malloc(data->d_size);
4291 				if (!obj->jumptables_data)
4292 					return -ENOMEM;
4293 				memcpy(obj->jumptables_data, data->d_buf, data->d_size);
4294 				obj->jumptables_data_sz = data->d_size;
4295 				obj->efile.jumptables_data_shndx = idx;
4296 			} else {
4297 				pr_info("elf: skipping unrecognized data section(%d) %s\n",
4298 					idx, name);
4299 			}
4300 		} else if (sh->sh_type == SHT_REL) {
4301 			int targ_sec_idx = sh->sh_info; /* points to other section */
4302 
4303 			if (sh->sh_entsize != sizeof(Elf64_Rel) ||
4304 			    targ_sec_idx >= obj->efile.sec_cnt)
4305 				return -LIBBPF_ERRNO__FORMAT;
4306 
4307 			/*
4308 			 * Only do relo for section with exec instructions,
4309 			 * struct_ops, maps, and read-only data that might
4310 			 * have pointers to functions.
4311 			 */
4312 			if (!section_have_execinstr(obj, targ_sec_idx) &&
4313 			    !(obj->data_in_arena &&
4314 			      (!strcmp(name, ".rel" DATA_SEC) ||
4315 			       str_has_pfx(name, ".rel" DATA_SEC "."))) &&
4316 			    strcmp(name, ".rel" RODATA_SEC) &&
4317 			    !str_has_pfx(name, ".rel" RODATA_SEC ".") &&
4318 			    strcmp(name, ".rel" DATA_REL_RO_SEC) &&
4319 			    !str_has_pfx(name, ".rel" DATA_REL_RO_SEC ".") &&
4320 			    strcmp(name, ".rel" STRUCT_OPS_SEC) &&
4321 			    strcmp(name, ".rel" STRUCT_OPS_LINK_SEC) &&
4322 			    strcmp(name, ".rel?" STRUCT_OPS_SEC) &&
4323 			    strcmp(name, ".rel?" STRUCT_OPS_LINK_SEC) &&
4324 			    strcmp(name, ".rel" MAPS_ELF_SEC)) {
4325 				pr_info("elf: skipping relo section(%d) %s for section(%d) %s\n",
4326 					idx, name, targ_sec_idx,
4327 					elf_sec_name(obj, elf_sec_by_idx(obj, targ_sec_idx)) ?: "<?>");
4328 				continue;
4329 			}
4330 
4331 			sec_desc->sec_type = SEC_RELO;
4332 			sec_desc->shdr = sh;
4333 			sec_desc->data = data;
4334 		} else if (sh->sh_type == SHT_NOBITS && (strcmp(name, BSS_SEC) == 0 ||
4335 							 str_has_pfx(name, BSS_SEC "."))) {
4336 			sec_desc->sec_type = SEC_BSS;
4337 			sec_desc->shdr = sh;
4338 			sec_desc->data = data;
4339 		} else {
4340 			pr_info("elf: skipping section(%d) %s (size %zu)\n", idx, name,
4341 				(size_t)sh->sh_size);
4342 		}
4343 	}
4344 
4345 	if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) {
4346 		pr_warn("elf: symbol strings section missing or invalid in %s\n", obj->path);
4347 		return -LIBBPF_ERRNO__FORMAT;
4348 	}
4349 
4350 	/* change BPF program insns to native endianness for introspection */
4351 	if (!is_native_endianness(obj))
4352 		bpf_object_bswap_progs(obj);
4353 
4354 	/* sort BPF programs by section name and in-section instruction offset
4355 	 * for faster search
4356 	 */
4357 	if (obj->nr_programs)
4358 		qsort(obj->programs, obj->nr_programs, sizeof(*obj->programs), cmp_progs);
4359 
4360 	return bpf_object__init_btf(obj, btf_data, btf_ext_data);
4361 }
4362 
4363 static bool sym_is_extern(const Elf64_Sym *sym)
4364 {
4365 	int bind = ELF64_ST_BIND(sym->st_info);
4366 	/* externs are symbols w/ type=NOTYPE, bind=GLOBAL|WEAK, section=UND */
4367 	return sym->st_shndx == SHN_UNDEF &&
4368 	       (bind == STB_GLOBAL || bind == STB_WEAK) &&
4369 	       ELF64_ST_TYPE(sym->st_info) == STT_NOTYPE;
4370 }
4371 
4372 static bool sym_is_subprog(const Elf64_Sym *sym, int text_shndx)
4373 {
4374 	int bind = ELF64_ST_BIND(sym->st_info);
4375 	int type = ELF64_ST_TYPE(sym->st_info);
4376 
4377 	/* in .text section */
4378 	if (sym->st_shndx != text_shndx)
4379 		return false;
4380 
4381 	/* local function */
4382 	if (bind == STB_LOCAL && type == STT_SECTION)
4383 		return true;
4384 
4385 	/* global function */
4386 	return (bind == STB_GLOBAL || bind == STB_WEAK) && type == STT_FUNC;
4387 }
4388 
4389 static int find_extern_btf_id(const struct btf *btf, const char *ext_name)
4390 {
4391 	const struct btf_type *t;
4392 	const char *tname;
4393 	int i, n;
4394 
4395 	if (!btf)
4396 		return -ESRCH;
4397 
4398 	n = btf__type_cnt(btf);
4399 	for (i = 1; i < n; i++) {
4400 		t = btf__type_by_id(btf, i);
4401 
4402 		if (!btf_is_var(t) && !btf_is_func(t))
4403 			continue;
4404 
4405 		tname = btf__name_by_offset(btf, t->name_off);
4406 		if (strcmp(tname, ext_name))
4407 			continue;
4408 
4409 		if (btf_is_var(t) &&
4410 		    btf_var(t)->linkage != BTF_VAR_GLOBAL_EXTERN)
4411 			return -EINVAL;
4412 
4413 		if (btf_is_func(t) && btf_func_linkage(t) != BTF_FUNC_EXTERN)
4414 			return -EINVAL;
4415 
4416 		return i;
4417 	}
4418 
4419 	return -ENOENT;
4420 }
4421 
4422 static int find_extern_sec_btf_id(struct btf *btf, int ext_btf_id) {
4423 	const struct btf_var_secinfo *vs;
4424 	const struct btf_type *t;
4425 	int i, j, n;
4426 
4427 	if (!btf)
4428 		return -ESRCH;
4429 
4430 	n = btf__type_cnt(btf);
4431 	for (i = 1; i < n; i++) {
4432 		t = btf__type_by_id(btf, i);
4433 
4434 		if (!btf_is_datasec(t))
4435 			continue;
4436 
4437 		vs = btf_var_secinfos(t);
4438 		for (j = 0; j < btf_vlen(t); j++, vs++) {
4439 			if (vs->type == ext_btf_id)
4440 				return i;
4441 		}
4442 	}
4443 
4444 	return -ENOENT;
4445 }
4446 
4447 static enum kcfg_type find_kcfg_type(const struct btf *btf, int id,
4448 				     bool *is_signed)
4449 {
4450 	const struct btf_type *t;
4451 	const char *name;
4452 
4453 	t = skip_mods_and_typedefs(btf, id, NULL);
4454 	name = btf__name_by_offset(btf, t->name_off);
4455 
4456 	if (is_signed)
4457 		*is_signed = false;
4458 	switch (btf_kind(t)) {
4459 	case BTF_KIND_INT: {
4460 		int enc = btf_int_encoding(t);
4461 
4462 		if (enc & BTF_INT_BOOL)
4463 			return t->size == 1 ? KCFG_BOOL : KCFG_UNKNOWN;
4464 		if (is_signed)
4465 			*is_signed = enc & BTF_INT_SIGNED;
4466 		if (t->size == 1)
4467 			return KCFG_CHAR;
4468 		if (t->size < 1 || t->size > 8 || (t->size & (t->size - 1)))
4469 			return KCFG_UNKNOWN;
4470 		return KCFG_INT;
4471 	}
4472 	case BTF_KIND_ENUM:
4473 		if (t->size != 4)
4474 			return KCFG_UNKNOWN;
4475 		if (strcmp(name, "libbpf_tristate"))
4476 			return KCFG_UNKNOWN;
4477 		return KCFG_TRISTATE;
4478 	case BTF_KIND_ENUM64:
4479 		if (strcmp(name, "libbpf_tristate"))
4480 			return KCFG_UNKNOWN;
4481 		return KCFG_TRISTATE;
4482 	case BTF_KIND_ARRAY:
4483 		if (btf_array(t)->nelems == 0)
4484 			return KCFG_UNKNOWN;
4485 		if (find_kcfg_type(btf, btf_array(t)->type, NULL) != KCFG_CHAR)
4486 			return KCFG_UNKNOWN;
4487 		return KCFG_CHAR_ARR;
4488 	default:
4489 		return KCFG_UNKNOWN;
4490 	}
4491 }
4492 
4493 static int cmp_externs(const void *_a, const void *_b)
4494 {
4495 	const struct extern_desc *a = _a;
4496 	const struct extern_desc *b = _b;
4497 
4498 	if (a->type != b->type)
4499 		return a->type < b->type ? -1 : 1;
4500 
4501 	if (a->type == EXT_KCFG) {
4502 		/* descending order by alignment requirements */
4503 		if (a->kcfg.align != b->kcfg.align)
4504 			return a->kcfg.align > b->kcfg.align ? -1 : 1;
4505 		/* ascending order by size, within same alignment class */
4506 		if (a->kcfg.sz != b->kcfg.sz)
4507 			return a->kcfg.sz < b->kcfg.sz ? -1 : 1;
4508 	}
4509 
4510 	/* resolve ties by name */
4511 	return strcmp(a->name, b->name);
4512 }
4513 
4514 static int find_int_btf_id(const struct btf *btf)
4515 {
4516 	const struct btf_type *t;
4517 	int i, n;
4518 
4519 	n = btf__type_cnt(btf);
4520 	for (i = 1; i < n; i++) {
4521 		t = btf__type_by_id(btf, i);
4522 
4523 		if (btf_is_int(t) && btf_int_bits(t) == 32)
4524 			return i;
4525 	}
4526 
4527 	return 0;
4528 }
4529 
4530 static int add_dummy_ksym_var(struct btf *btf)
4531 {
4532 	int i, int_btf_id, sec_btf_id, dummy_var_btf_id;
4533 	const struct btf_var_secinfo *vs;
4534 	const struct btf_type *sec;
4535 
4536 	if (!btf)
4537 		return 0;
4538 
4539 	sec_btf_id = btf__find_by_name_kind(btf, KSYMS_SEC,
4540 					    BTF_KIND_DATASEC);
4541 	if (sec_btf_id < 0)
4542 		return 0;
4543 
4544 	sec = btf__type_by_id(btf, sec_btf_id);
4545 	vs = btf_var_secinfos(sec);
4546 	for (i = 0; i < btf_vlen(sec); i++, vs++) {
4547 		const struct btf_type *vt;
4548 
4549 		vt = btf__type_by_id(btf, vs->type);
4550 		if (btf_is_func(vt))
4551 			break;
4552 	}
4553 
4554 	/* No func in ksyms sec.  No need to add dummy var. */
4555 	if (i == btf_vlen(sec))
4556 		return 0;
4557 
4558 	int_btf_id = find_int_btf_id(btf);
4559 	dummy_var_btf_id = btf__add_var(btf,
4560 					"dummy_ksym",
4561 					BTF_VAR_GLOBAL_ALLOCATED,
4562 					int_btf_id);
4563 	if (dummy_var_btf_id < 0)
4564 		pr_warn("cannot create a dummy_ksym var\n");
4565 
4566 	return dummy_var_btf_id;
4567 }
4568 
4569 static int bpf_object__collect_externs(struct bpf_object *obj)
4570 {
4571 	struct btf_type *sec, *kcfg_sec = NULL, *ksym_sec = NULL;
4572 	const struct btf_type *t;
4573 	struct extern_desc *ext;
4574 	int i, n, off, dummy_var_btf_id;
4575 	const char *ext_name, *sec_name;
4576 	size_t ext_essent_len;
4577 	Elf_Scn *scn;
4578 	Elf64_Shdr *sh;
4579 
4580 	if (!obj->efile.symbols)
4581 		return 0;
4582 
4583 	scn = elf_sec_by_idx(obj, obj->efile.symbols_shndx);
4584 	sh = elf_sec_hdr(obj, scn);
4585 	if (!sh || sh->sh_entsize != sizeof(Elf64_Sym))
4586 		return -LIBBPF_ERRNO__FORMAT;
4587 
4588 	dummy_var_btf_id = add_dummy_ksym_var(obj->btf);
4589 	if (dummy_var_btf_id < 0)
4590 		return dummy_var_btf_id;
4591 
4592 	n = sh->sh_size / sh->sh_entsize;
4593 	pr_debug("looking for externs among %d symbols...\n", n);
4594 
4595 	for (i = 0; i < n; i++) {
4596 		Elf64_Sym *sym = elf_sym_by_idx(obj, i);
4597 
4598 		if (!sym)
4599 			return -LIBBPF_ERRNO__FORMAT;
4600 		if (!sym_is_extern(sym))
4601 			continue;
4602 		ext_name = elf_sym_str(obj, sym->st_name);
4603 		if (str_is_empty(ext_name))
4604 			continue;
4605 
4606 		ext = obj->externs;
4607 		ext = libbpf_reallocarray(ext, obj->nr_extern + 1, sizeof(*ext));
4608 		if (!ext)
4609 			return -ENOMEM;
4610 		obj->externs = ext;
4611 		ext = &ext[obj->nr_extern];
4612 		memset(ext, 0, sizeof(*ext));
4613 		obj->nr_extern++;
4614 
4615 		ext->btf_id = find_extern_btf_id(obj->btf, ext_name);
4616 		if (ext->btf_id <= 0) {
4617 			pr_warn("failed to find BTF for extern '%s': %d\n",
4618 				ext_name, ext->btf_id);
4619 			return ext->btf_id;
4620 		}
4621 		t = btf__type_by_id(obj->btf, ext->btf_id);
4622 		ext->name = strdup(btf__name_by_offset(obj->btf, t->name_off));
4623 		if (!ext->name)
4624 			return -ENOMEM;
4625 		ext->sym_idx = i;
4626 		ext->is_weak = ELF64_ST_BIND(sym->st_info) == STB_WEAK;
4627 
4628 		ext_essent_len = bpf_core_essential_name_len(ext->name);
4629 		ext->essent_name = NULL;
4630 		if (ext_essent_len != strlen(ext->name)) {
4631 			ext->essent_name = strndup(ext->name, ext_essent_len);
4632 			if (!ext->essent_name)
4633 				return -ENOMEM;
4634 		}
4635 
4636 		ext->sec_btf_id = find_extern_sec_btf_id(obj->btf, ext->btf_id);
4637 		if (ext->sec_btf_id <= 0) {
4638 			pr_warn("failed to find BTF for extern '%s' [%d] section: %d\n",
4639 				ext_name, ext->btf_id, ext->sec_btf_id);
4640 			return ext->sec_btf_id;
4641 		}
4642 		sec = (void *)btf__type_by_id(obj->btf, ext->sec_btf_id);
4643 		sec_name = btf__name_by_offset(obj->btf, sec->name_off);
4644 
4645 		if (strcmp(sec_name, KCONFIG_SEC) == 0) {
4646 			if (btf_is_func(t)) {
4647 				pr_warn("extern function %s is unsupported under %s section\n",
4648 					ext->name, KCONFIG_SEC);
4649 				return -ENOTSUP;
4650 			}
4651 			kcfg_sec = sec;
4652 			ext->type = EXT_KCFG;
4653 			ext->kcfg.sz = btf__resolve_size(obj->btf, t->type);
4654 			if (ext->kcfg.sz <= 0) {
4655 				pr_warn("failed to resolve size of extern (kcfg) '%s': %d\n",
4656 					ext_name, ext->kcfg.sz);
4657 				return ext->kcfg.sz;
4658 			}
4659 			ext->kcfg.align = btf__align_of(obj->btf, t->type);
4660 			if (ext->kcfg.align <= 0) {
4661 				pr_warn("failed to determine alignment of extern (kcfg) '%s': %d\n",
4662 					ext_name, ext->kcfg.align);
4663 				return -EINVAL;
4664 			}
4665 			ext->kcfg.type = find_kcfg_type(obj->btf, t->type,
4666 							&ext->kcfg.is_signed);
4667 			if (ext->kcfg.type == KCFG_UNKNOWN) {
4668 				pr_warn("extern (kcfg) '%s': type is unsupported\n", ext_name);
4669 				return -ENOTSUP;
4670 			}
4671 		} else if (strcmp(sec_name, KSYMS_SEC) == 0) {
4672 			ksym_sec = sec;
4673 			ext->type = EXT_KSYM;
4674 			skip_mods_and_typedefs(obj->btf, t->type,
4675 					       &ext->ksym.type_id);
4676 		} else {
4677 			pr_warn("unrecognized extern section '%s'\n", sec_name);
4678 			return -ENOTSUP;
4679 		}
4680 	}
4681 	pr_debug("collected %d externs total\n", obj->nr_extern);
4682 
4683 	if (!obj->nr_extern)
4684 		return 0;
4685 
4686 	/* sort externs by type, for kcfg ones also by (align, size, name) */
4687 	qsort(obj->externs, obj->nr_extern, sizeof(*ext), cmp_externs);
4688 
4689 	/* for .ksyms section, we need to turn all externs into allocated
4690 	 * variables in BTF to pass kernel verification; we do this by
4691 	 * pretending that each extern is a 8-byte variable
4692 	 */
4693 	if (ksym_sec) {
4694 		/* find existing 4-byte integer type in BTF to use for fake
4695 		 * extern variables in DATASEC
4696 		 */
4697 		int int_btf_id = find_int_btf_id(obj->btf);
4698 		/* For extern function, a dummy_var added earlier
4699 		 * will be used to replace the vs->type and
4700 		 * its name string will be used to refill
4701 		 * the missing param's name.
4702 		 */
4703 		const struct btf_type *dummy_var;
4704 
4705 		dummy_var = btf__type_by_id(obj->btf, dummy_var_btf_id);
4706 		for (i = 0; i < obj->nr_extern; i++) {
4707 			ext = &obj->externs[i];
4708 			if (ext->type != EXT_KSYM)
4709 				continue;
4710 			pr_debug("extern (ksym) #%d: symbol %d, name %s\n",
4711 				 i, ext->sym_idx, ext->name);
4712 		}
4713 
4714 		sec = ksym_sec;
4715 		n = btf_vlen(sec);
4716 		for (i = 0, off = 0; i < n; i++, off += sizeof(int)) {
4717 			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
4718 			struct btf_type *vt;
4719 
4720 			vt = (void *)btf__type_by_id(obj->btf, vs->type);
4721 			ext_name = btf__name_by_offset(obj->btf, vt->name_off);
4722 			ext = find_extern_by_name(obj, ext_name);
4723 			if (!ext) {
4724 				pr_warn("failed to find extern definition for BTF %s '%s'\n",
4725 					btf_kind_str(vt), ext_name);
4726 				return -ESRCH;
4727 			}
4728 			if (btf_is_func(vt)) {
4729 				const struct btf_type *func_proto;
4730 				struct btf_param *param;
4731 				int j;
4732 
4733 				func_proto = btf__type_by_id(obj->btf,
4734 							     vt->type);
4735 				param = btf_params(func_proto);
4736 				/* Reuse the dummy_var string if the
4737 				 * func proto does not have param name.
4738 				 */
4739 				for (j = 0; j < btf_vlen(func_proto); j++)
4740 					if (param[j].type && !param[j].name_off)
4741 						param[j].name_off =
4742 							dummy_var->name_off;
4743 				vs->type = dummy_var_btf_id;
4744 				vt->info &= ~0xffff;
4745 				vt->info |= BTF_FUNC_GLOBAL;
4746 			} else {
4747 				btf_var(vt)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
4748 				vt->type = int_btf_id;
4749 			}
4750 			vs->offset = off;
4751 			vs->size = sizeof(int);
4752 		}
4753 		sec->size = off;
4754 	}
4755 
4756 	if (kcfg_sec) {
4757 		sec = kcfg_sec;
4758 		/* for kcfg externs calculate their offsets within a .kconfig map */
4759 		off = 0;
4760 		for (i = 0; i < obj->nr_extern; i++) {
4761 			ext = &obj->externs[i];
4762 			if (ext->type != EXT_KCFG)
4763 				continue;
4764 
4765 			ext->kcfg.data_off = roundup(off, ext->kcfg.align);
4766 			off = ext->kcfg.data_off + ext->kcfg.sz;
4767 			pr_debug("extern (kcfg) #%d: symbol %d, off %d, name %s\n",
4768 				 i, ext->sym_idx, ext->kcfg.data_off, ext->name);
4769 		}
4770 		sec->size = off;
4771 		n = btf_vlen(sec);
4772 		for (i = 0; i < n; i++) {
4773 			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
4774 
4775 			t = btf__type_by_id(obj->btf, vs->type);
4776 			ext_name = btf__name_by_offset(obj->btf, t->name_off);
4777 			ext = find_extern_by_name(obj, ext_name);
4778 			if (!ext) {
4779 				pr_warn("failed to find extern definition for BTF var '%s'\n",
4780 					ext_name);
4781 				return -ESRCH;
4782 			}
4783 			btf_var(t)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
4784 			vs->offset = ext->kcfg.data_off;
4785 		}
4786 	}
4787 	return 0;
4788 }
4789 
4790 static bool prog_is_subprog(const struct bpf_object *obj, const struct bpf_program *prog)
4791 {
4792 	return prog->sec_idx == obj->efile.text_shndx;
4793 }
4794 
4795 struct bpf_program *
4796 bpf_object__find_program_by_name(const struct bpf_object *obj,
4797 				 const char *name)
4798 {
4799 	struct bpf_program *prog;
4800 
4801 	bpf_object__for_each_program(prog, obj) {
4802 		if (prog_is_subprog(obj, prog))
4803 			continue;
4804 		if (!strcmp(prog->name, name))
4805 			return prog;
4806 	}
4807 	return errno = ENOENT, NULL;
4808 }
4809 
4810 static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
4811 				      int shndx)
4812 {
4813 	switch (obj->efile.secs[shndx].sec_type) {
4814 	case SEC_BSS:
4815 	case SEC_DATA:
4816 	case SEC_RODATA:
4817 	case SEC_PERCPU:
4818 		return true;
4819 	default:
4820 		return false;
4821 	}
4822 }
4823 
4824 static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
4825 				      int shndx)
4826 {
4827 	return shndx == obj->efile.btf_maps_shndx;
4828 }
4829 
4830 static enum libbpf_map_type
4831 bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
4832 {
4833 	if (shndx == obj->efile.symbols_shndx)
4834 		return LIBBPF_MAP_KCONFIG;
4835 
4836 	switch (obj->efile.secs[shndx].sec_type) {
4837 	case SEC_BSS:
4838 		return LIBBPF_MAP_BSS;
4839 	case SEC_DATA:
4840 		return LIBBPF_MAP_DATA;
4841 	case SEC_RODATA:
4842 		return LIBBPF_MAP_RODATA;
4843 	case SEC_PERCPU:
4844 		return LIBBPF_MAP_PERCPU;
4845 	default:
4846 		return LIBBPF_MAP_UNSPEC;
4847 	}
4848 }
4849 
4850 static int bpf_prog_compute_hash(struct bpf_program *prog)
4851 {
4852 	struct bpf_insn *purged;
4853 	int i, err = 0;
4854 
4855 	purged = calloc(prog->insns_cnt, BPF_INSN_SZ);
4856 	if (!purged)
4857 		return -ENOMEM;
4858 
4859 	/* If relocations have been done, the map_fd needs to be
4860 	 * discarded for the digest calculation.
4861 	 */
4862 	for (i = 0; i < prog->insns_cnt; i++) {
4863 		purged[i] = prog->insns[i];
4864 		if (purged[i].code == (BPF_LD | BPF_IMM | BPF_DW) &&
4865 		    (purged[i].src_reg == BPF_PSEUDO_MAP_FD ||
4866 		     purged[i].src_reg == BPF_PSEUDO_MAP_VALUE)) {
4867 			purged[i].imm = 0;
4868 			i++;
4869 			if (i >= prog->insns_cnt ||
4870 			    prog->insns[i].code != 0 ||
4871 			    prog->insns[i].dst_reg != 0 ||
4872 			    prog->insns[i].src_reg != 0 ||
4873 			    prog->insns[i].off != 0) {
4874 				err = -EINVAL;
4875 				goto out;
4876 			}
4877 			purged[i] = prog->insns[i];
4878 			purged[i].imm = 0;
4879 		}
4880 	}
4881 	libbpf_sha256(purged, prog->insns_cnt * sizeof(struct bpf_insn),
4882 		      prog->hash);
4883 out:
4884 	free(purged);
4885 	return err;
4886 }
4887 
4888 static int bpf_program__record_reloc(struct bpf_program *prog,
4889 				     struct reloc_desc *reloc_desc,
4890 				     __u32 insn_idx, const char *sym_name,
4891 				     const Elf64_Sym *sym, const Elf64_Rel *rel)
4892 {
4893 	struct bpf_insn *insn = &prog->insns[insn_idx];
4894 	size_t map_idx, nr_maps = prog->obj->nr_maps;
4895 	struct bpf_object *obj = prog->obj;
4896 	__u32 shdr_idx = sym->st_shndx;
4897 	enum libbpf_map_type type;
4898 	const char *sym_sec_name;
4899 	struct bpf_map *map;
4900 
4901 	if (!is_call_insn(insn) && !is_ldimm64_insn(insn)) {
4902 		pr_warn("prog '%s': invalid relo against '%s' for insns[%u].code 0x%x\n",
4903 			prog->name, sym_name, insn_idx, insn->code);
4904 		return -LIBBPF_ERRNO__RELOC;
4905 	}
4906 
4907 	if (sym_is_extern(sym)) {
4908 		int sym_idx = ELF64_R_SYM(rel->r_info);
4909 		int i, n = obj->nr_extern;
4910 		struct extern_desc *ext;
4911 
4912 		for (i = 0; i < n; i++) {
4913 			ext = &obj->externs[i];
4914 			if (ext->sym_idx == sym_idx)
4915 				break;
4916 		}
4917 		if (i >= n) {
4918 			pr_warn("prog '%s': extern relo failed to find extern for '%s' (%d)\n",
4919 				prog->name, sym_name, sym_idx);
4920 			return -LIBBPF_ERRNO__RELOC;
4921 		}
4922 		pr_debug("prog '%s': found extern #%d '%s' (sym %d) for insn #%u\n",
4923 			 prog->name, i, ext->name, ext->sym_idx, insn_idx);
4924 		if (insn->code == (BPF_JMP | BPF_CALL))
4925 			reloc_desc->type = RELO_EXTERN_CALL;
4926 		else
4927 			reloc_desc->type = RELO_EXTERN_LD64;
4928 		reloc_desc->insn_idx = insn_idx;
4929 		reloc_desc->ext_idx = i;
4930 		return 0;
4931 	}
4932 
4933 	/* sub-program call relocation */
4934 	if (is_call_insn(insn)) {
4935 		if (insn->src_reg != BPF_PSEUDO_CALL) {
4936 			pr_warn("prog '%s': incorrect bpf_call opcode\n", prog->name);
4937 			return -LIBBPF_ERRNO__RELOC;
4938 		}
4939 		/* text_shndx can be 0, if no default "main" program exists */
4940 		if (!shdr_idx || shdr_idx != obj->efile.text_shndx) {
4941 			sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4942 			pr_warn("prog '%s': bad call relo against '%s' in section '%s'\n",
4943 				prog->name, sym_name, sym_sec_name);
4944 			return -LIBBPF_ERRNO__RELOC;
4945 		}
4946 		if (sym->st_value % BPF_INSN_SZ) {
4947 			pr_warn("prog '%s': bad call relo against '%s' at offset %zu\n",
4948 				prog->name, sym_name, (size_t)sym->st_value);
4949 			return -LIBBPF_ERRNO__RELOC;
4950 		}
4951 		reloc_desc->type = RELO_CALL;
4952 		reloc_desc->insn_idx = insn_idx;
4953 		reloc_desc->sym_off = sym->st_value;
4954 		return 0;
4955 	}
4956 
4957 	if (!shdr_idx || shdr_idx >= SHN_LORESERVE) {
4958 		pr_warn("prog '%s': invalid relo against '%s' in special section 0x%x; forgot to initialize global var?..\n",
4959 			prog->name, sym_name, shdr_idx);
4960 		return -LIBBPF_ERRNO__RELOC;
4961 	}
4962 
4963 	/* loading subprog addresses */
4964 	if (sym_is_subprog(sym, obj->efile.text_shndx)) {
4965 		/* global_func: sym->st_value = offset in the section, insn->imm = 0.
4966 		 * local_func: sym->st_value = 0, insn->imm = offset in the section.
4967 		 */
4968 		if ((sym->st_value % BPF_INSN_SZ) || (insn->imm % BPF_INSN_SZ)) {
4969 			pr_warn("prog '%s': bad subprog addr relo against '%s' at offset %zu+%d\n",
4970 				prog->name, sym_name, (size_t)sym->st_value, insn->imm);
4971 			return -LIBBPF_ERRNO__RELOC;
4972 		}
4973 
4974 		reloc_desc->type = RELO_SUBPROG_ADDR;
4975 		reloc_desc->insn_idx = insn_idx;
4976 		reloc_desc->sym_off = sym->st_value;
4977 		return 0;
4978 	}
4979 
4980 	type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
4981 	sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4982 
4983 	/* arena data relocation */
4984 	if (shdr_idx == obj->efile.arena_data_shndx) {
4985 		if (obj->arena_map_idx < 0) {
4986 			pr_warn("prog '%s': bad arena data relocation at insn %u, no arena maps defined\n",
4987 				prog->name, insn_idx);
4988 			return -LIBBPF_ERRNO__RELOC;
4989 		}
4990 		reloc_desc->type = RELO_DATA;
4991 		reloc_desc->insn_idx = insn_idx;
4992 		reloc_desc->map_idx = obj->arena_map_idx;
4993 		reloc_desc->sym_off = sym->st_value;
4994 
4995 		map = &obj->maps[obj->arena_map_idx];
4996 		pr_debug("prog '%s': found arena map %d (%s, sec %d, off %zu) for insn %u\n",
4997 			 prog->name, obj->arena_map_idx, map->name, map->sec_idx,
4998 			 map->sec_offset, insn_idx);
4999 		return 0;
5000 	}
5001 
5002 	/* jump table data relocation */
5003 	if (shdr_idx == obj->efile.jumptables_data_shndx) {
5004 		reloc_desc->type = RELO_INSN_ARRAY;
5005 		reloc_desc->insn_idx = insn_idx;
5006 		reloc_desc->map_idx = -1;
5007 		reloc_desc->sym_off = sym->st_value;
5008 		reloc_desc->sym_size = sym->st_size;
5009 		return 0;
5010 	}
5011 
5012 	/* generic map reference relocation */
5013 	if (type == LIBBPF_MAP_UNSPEC) {
5014 		if (!bpf_object__shndx_is_maps(obj, shdr_idx)) {
5015 			pr_warn("prog '%s': bad map relo against '%s' in section '%s'\n",
5016 				prog->name, sym_name, sym_sec_name);
5017 			return -LIBBPF_ERRNO__RELOC;
5018 		}
5019 		for (map_idx = 0; map_idx < nr_maps; map_idx++) {
5020 			map = &obj->maps[map_idx];
5021 			if (map->libbpf_type != type ||
5022 			    map->sec_idx != sym->st_shndx ||
5023 			    map->sec_offset != sym->st_value)
5024 				continue;
5025 			pr_debug("prog '%s': found map %zu (%s, sec %d, off %zu) for insn #%u\n",
5026 				 prog->name, map_idx, map->name, map->sec_idx,
5027 				 map->sec_offset, insn_idx);
5028 			break;
5029 		}
5030 		if (map_idx >= nr_maps) {
5031 			pr_warn("prog '%s': map relo failed to find map for section '%s', off %zu\n",
5032 				prog->name, sym_sec_name, (size_t)sym->st_value);
5033 			return -LIBBPF_ERRNO__RELOC;
5034 		}
5035 		reloc_desc->type = RELO_LD64;
5036 		reloc_desc->insn_idx = insn_idx;
5037 		reloc_desc->map_idx = map_idx;
5038 		reloc_desc->sym_off = 0; /* sym->st_value determines map_idx */
5039 		return 0;
5040 	}
5041 
5042 	/* global data map relocation */
5043 	if (!bpf_object__shndx_is_data(obj, shdr_idx)) {
5044 		pr_warn("prog '%s': bad data relo against section '%s'\n",
5045 			prog->name, sym_sec_name);
5046 		return -LIBBPF_ERRNO__RELOC;
5047 	}
5048 	for (map_idx = 0; map_idx < nr_maps; map_idx++) {
5049 		map = &obj->maps[map_idx];
5050 		if (map->libbpf_type != type || map->sec_idx != sym->st_shndx)
5051 			continue;
5052 		pr_debug("prog '%s': found data map %zu (%s, sec %d, off %zu) for insn %u\n",
5053 			 prog->name, map_idx, map->name, map->sec_idx,
5054 			 map->sec_offset, insn_idx);
5055 		break;
5056 	}
5057 	if (map_idx >= nr_maps) {
5058 		pr_warn("prog '%s': data relo failed to find map for section '%s'\n",
5059 			prog->name, sym_sec_name);
5060 		return -LIBBPF_ERRNO__RELOC;
5061 	}
5062 
5063 	reloc_desc->type = RELO_DATA;
5064 	reloc_desc->insn_idx = insn_idx;
5065 	reloc_desc->map_idx = map_idx;
5066 	reloc_desc->sym_off = sym->st_value;
5067 	if (map->in_arena) {
5068 		reloc_desc->map_idx = obj->arena_map_idx;
5069 		reloc_desc->sym_off += map->arena_off;
5070 	}
5071 	return 0;
5072 }
5073 
5074 static bool prog_contains_insn(const struct bpf_program *prog, size_t insn_idx)
5075 {
5076 	return insn_idx >= prog->sec_insn_off &&
5077 	       insn_idx < prog->sec_insn_off + prog->sec_insn_cnt;
5078 }
5079 
5080 static struct bpf_program *find_prog_by_sec_insn(const struct bpf_object *obj,
5081 						 size_t sec_idx, size_t insn_idx)
5082 {
5083 	int l = 0, r = obj->nr_programs - 1, m;
5084 	struct bpf_program *prog;
5085 
5086 	if (!obj->nr_programs)
5087 		return NULL;
5088 
5089 	while (l < r) {
5090 		m = l + (r - l + 1) / 2;
5091 		prog = &obj->programs[m];
5092 
5093 		if (prog->sec_idx < sec_idx ||
5094 		    (prog->sec_idx == sec_idx && prog->sec_insn_off <= insn_idx))
5095 			l = m;
5096 		else
5097 			r = m - 1;
5098 	}
5099 	/* matching program could be at index l, but it still might be the
5100 	 * wrong one, so we need to double check conditions for the last time
5101 	 */
5102 	prog = &obj->programs[l];
5103 	if (prog->sec_idx == sec_idx && prog_contains_insn(prog, insn_idx))
5104 		return prog;
5105 	return NULL;
5106 }
5107 
5108 static int
5109 bpf_object__collect_prog_relos(struct bpf_object *obj, Elf64_Shdr *shdr, Elf_Data *data)
5110 {
5111 	const char *relo_sec_name, *sec_name;
5112 	size_t sec_idx = shdr->sh_info, sym_idx;
5113 	struct bpf_program *prog;
5114 	struct reloc_desc *relos;
5115 	int err, i, nrels;
5116 	const char *sym_name;
5117 	__u32 insn_idx;
5118 	Elf_Scn *scn;
5119 	Elf_Data *scn_data;
5120 	Elf64_Sym *sym;
5121 	Elf64_Rel *rel;
5122 
5123 	if (sec_idx >= obj->efile.sec_cnt)
5124 		return -EINVAL;
5125 
5126 	scn = elf_sec_by_idx(obj, sec_idx);
5127 	scn_data = elf_sec_data(obj, scn);
5128 	if (!scn_data)
5129 		return -LIBBPF_ERRNO__FORMAT;
5130 
5131 	relo_sec_name = elf_sec_str(obj, shdr->sh_name);
5132 	sec_name = elf_sec_name(obj, scn);
5133 	if (!relo_sec_name || !sec_name)
5134 		return -EINVAL;
5135 
5136 	pr_debug("sec '%s': collecting relocation for section(%zu) '%s'\n",
5137 		 relo_sec_name, sec_idx, sec_name);
5138 	nrels = shdr->sh_size / shdr->sh_entsize;
5139 
5140 	for (i = 0; i < nrels; i++) {
5141 		rel = elf_rel_by_idx(data, i);
5142 		if (!rel) {
5143 			pr_warn("sec '%s': failed to get relo #%d\n", relo_sec_name, i);
5144 			return -LIBBPF_ERRNO__FORMAT;
5145 		}
5146 
5147 		sym_idx = ELF64_R_SYM(rel->r_info);
5148 		sym = elf_sym_by_idx(obj, sym_idx);
5149 		if (!sym) {
5150 			pr_warn("sec '%s': symbol #%zu not found for relo #%d\n",
5151 				relo_sec_name, sym_idx, i);
5152 			return -LIBBPF_ERRNO__FORMAT;
5153 		}
5154 
5155 		if (sym->st_shndx >= obj->efile.sec_cnt) {
5156 			pr_warn("sec '%s': corrupted symbol #%zu pointing to invalid section #%zu for relo #%d\n",
5157 				relo_sec_name, sym_idx, (size_t)sym->st_shndx, i);
5158 			return -LIBBPF_ERRNO__FORMAT;
5159 		}
5160 
5161 		if (rel->r_offset % BPF_INSN_SZ || rel->r_offset >= scn_data->d_size) {
5162 			pr_warn("sec '%s': invalid offset 0x%zx for relo #%d\n",
5163 				relo_sec_name, (size_t)rel->r_offset, i);
5164 			return -LIBBPF_ERRNO__FORMAT;
5165 		}
5166 
5167 		insn_idx = rel->r_offset / BPF_INSN_SZ;
5168 		/* relocations against static functions are recorded as
5169 		 * relocations against the section that contains a function;
5170 		 * in such case, symbol will be STT_SECTION and sym.st_name
5171 		 * will point to empty string (0), so fetch section name
5172 		 * instead
5173 		 */
5174 		if (ELF64_ST_TYPE(sym->st_info) == STT_SECTION && sym->st_name == 0)
5175 			sym_name = elf_sec_name(obj, elf_sec_by_idx(obj, sym->st_shndx));
5176 		else
5177 			sym_name = elf_sym_str(obj, sym->st_name);
5178 		sym_name = sym_name ?: "<?";
5179 
5180 		pr_debug("sec '%s': relo #%d: insn #%u against '%s'\n",
5181 			 relo_sec_name, i, insn_idx, sym_name);
5182 
5183 		prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
5184 		if (!prog) {
5185 			pr_debug("sec '%s': relo #%d: couldn't find program in section '%s' for insn #%u, probably overridden weak function, skipping...\n",
5186 				relo_sec_name, i, sec_name, insn_idx);
5187 			continue;
5188 		}
5189 
5190 		relos = libbpf_reallocarray(prog->reloc_desc,
5191 					    prog->nr_reloc + 1, sizeof(*relos));
5192 		if (!relos)
5193 			return -ENOMEM;
5194 		prog->reloc_desc = relos;
5195 
5196 		/* adjust insn_idx to local BPF program frame of reference */
5197 		insn_idx -= prog->sec_insn_off;
5198 		err = bpf_program__record_reloc(prog, &relos[prog->nr_reloc],
5199 						insn_idx, sym_name, sym, rel);
5200 		if (err)
5201 			return err;
5202 
5203 		prog->nr_reloc++;
5204 	}
5205 	return 0;
5206 }
5207 
5208 static int map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map)
5209 {
5210 	int id;
5211 
5212 	if (!obj->btf)
5213 		return -ENOENT;
5214 
5215 	/* if it's BTF-defined map, we don't need to search for type IDs.
5216 	 * For struct_ops map, it does not need btf_key_type_id and
5217 	 * btf_value_type_id.
5218 	 */
5219 	if (map->sec_idx == obj->efile.btf_maps_shndx || bpf_map__is_struct_ops(map))
5220 		return 0;
5221 
5222 	/*
5223 	 * LLVM annotates global data differently in BTF, that is,
5224 	 * only as '.data', '.bss', '.percpu' or '.rodata'.
5225 	 */
5226 	if (!bpf_map__is_internal(map))
5227 		return -ENOENT;
5228 
5229 	id = btf__find_by_name(obj->btf, map->real_name);
5230 	if (id < 0)
5231 		return id;
5232 
5233 	map->btf_key_type_id = 0;
5234 	map->btf_value_type_id = id;
5235 	return 0;
5236 }
5237 
5238 static int bpf_get_map_info_from_fdinfo(int fd, struct bpf_map_info *info)
5239 {
5240 	char file[PATH_MAX], buff[4096];
5241 	FILE *fp;
5242 	__u32 val;
5243 	int err;
5244 
5245 	snprintf(file, sizeof(file), "/proc/%d/fdinfo/%d", getpid(), fd);
5246 	memset(info, 0, sizeof(*info));
5247 
5248 	fp = fopen(file, "re");
5249 	if (!fp) {
5250 		err = -errno;
5251 		pr_warn("failed to open %s: %s. No procfs support?\n", file,
5252 			errstr(err));
5253 		return err;
5254 	}
5255 
5256 	while (fgets(buff, sizeof(buff), fp)) {
5257 		if (sscanf(buff, "map_type:\t%u", &val) == 1)
5258 			info->type = val;
5259 		else if (sscanf(buff, "key_size:\t%u", &val) == 1)
5260 			info->key_size = val;
5261 		else if (sscanf(buff, "value_size:\t%u", &val) == 1)
5262 			info->value_size = val;
5263 		else if (sscanf(buff, "max_entries:\t%u", &val) == 1)
5264 			info->max_entries = val;
5265 		else if (sscanf(buff, "map_flags:\t%x", &val) == 1)
5266 			info->map_flags = val;
5267 	}
5268 
5269 	fclose(fp);
5270 
5271 	return 0;
5272 }
5273 
5274 static bool map_is_created(const struct bpf_map *map)
5275 {
5276 	return map->obj->state >= OBJ_PREPARED || map->reused;
5277 }
5278 
5279 bool bpf_map__autocreate(const struct bpf_map *map)
5280 {
5281 	return map->autocreate;
5282 }
5283 
5284 int bpf_map__set_autocreate(struct bpf_map *map, bool autocreate)
5285 {
5286 	if (map_is_created(map))
5287 		return libbpf_err(-EBUSY);
5288 
5289 	if (map->in_arena)
5290 		return libbpf_err(-EOPNOTSUPP);
5291 
5292 	map->autocreate = autocreate;
5293 	return 0;
5294 }
5295 
5296 int bpf_map__set_autoattach(struct bpf_map *map, bool autoattach)
5297 {
5298 	if (!bpf_map__is_struct_ops(map))
5299 		return libbpf_err(-EINVAL);
5300 
5301 	map->autoattach = autoattach;
5302 	return 0;
5303 }
5304 
5305 bool bpf_map__autoattach(const struct bpf_map *map)
5306 {
5307 	return map->autoattach;
5308 }
5309 
5310 int bpf_map__reuse_fd(struct bpf_map *map, int fd)
5311 {
5312 	struct bpf_map_info info;
5313 	__u32 len = sizeof(info), name_len;
5314 	int new_fd, err;
5315 	char *new_name;
5316 
5317 	memset(&info, 0, len);
5318 	err = bpf_map_get_info_by_fd(fd, &info, &len);
5319 	if (err && errno == EINVAL)
5320 		err = bpf_get_map_info_from_fdinfo(fd, &info);
5321 	if (err)
5322 		return libbpf_err(err);
5323 
5324 	name_len = strlen(info.name);
5325 	if (name_len == BPF_OBJ_NAME_LEN - 1 && strncmp(map->name, info.name, name_len) == 0)
5326 		new_name = strdup(map->name);
5327 	else
5328 		new_name = strdup(info.name);
5329 
5330 	if (!new_name)
5331 		return libbpf_err(-errno);
5332 
5333 	/*
5334 	 * Like dup(), but make sure new FD is >= 3 and has O_CLOEXEC set.
5335 	 * This is similar to what we do in ensure_good_fd(), but without
5336 	 * closing original FD.
5337 	 */
5338 	new_fd = fcntl(fd, F_DUPFD_CLOEXEC, 3);
5339 	if (new_fd < 0) {
5340 		err = -errno;
5341 		goto err_free_new_name;
5342 	}
5343 
5344 	err = reuse_fd(map->fd, new_fd);
5345 	if (err)
5346 		goto err_free_new_name;
5347 
5348 	free(map->name);
5349 
5350 	map->name = new_name;
5351 	map->def.type = info.type;
5352 	map->def.key_size = info.key_size;
5353 	map->def.value_size = info.value_size;
5354 	map->def.max_entries = info.max_entries;
5355 	map->def.map_flags = info.map_flags;
5356 	map->btf_key_type_id = info.btf_key_type_id;
5357 	map->btf_value_type_id = info.btf_value_type_id;
5358 	map->reused = true;
5359 	map->map_extra = info.map_extra;
5360 
5361 	return 0;
5362 
5363 err_free_new_name:
5364 	free(new_name);
5365 	return libbpf_err(err);
5366 }
5367 
5368 __u32 bpf_map__max_entries(const struct bpf_map *map)
5369 {
5370 	return map->def.max_entries;
5371 }
5372 
5373 struct bpf_map *bpf_map__inner_map(struct bpf_map *map)
5374 {
5375 	if (!bpf_map_type__is_map_in_map(map->def.type))
5376 		return errno = EINVAL, NULL;
5377 
5378 	return map->inner_map;
5379 }
5380 
5381 int bpf_map__set_max_entries(struct bpf_map *map, __u32 max_entries)
5382 {
5383 	if (map_is_created(map))
5384 		return libbpf_err(-EBUSY);
5385 
5386 	map->def.max_entries = max_entries;
5387 
5388 	/* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
5389 	if (map_is_ringbuf(map))
5390 		map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
5391 
5392 	return 0;
5393 }
5394 
5395 static int bpf_object_prepare_token(struct bpf_object *obj)
5396 {
5397 	const char *bpffs_path;
5398 	int bpffs_fd = -1, token_fd, err;
5399 	bool mandatory;
5400 	enum libbpf_print_level level;
5401 
5402 	/* token is explicitly prevented */
5403 	if (obj->token_path && obj->token_path[0] == '\0') {
5404 		pr_debug("object '%s': token is prevented, skipping...\n", obj->name);
5405 		return 0;
5406 	}
5407 
5408 	mandatory = obj->token_path != NULL;
5409 	level = mandatory ? LIBBPF_WARN : LIBBPF_DEBUG;
5410 
5411 	bpffs_path = obj->token_path ?: BPF_FS_DEFAULT_PATH;
5412 	bpffs_fd = open(bpffs_path, O_DIRECTORY, O_RDWR);
5413 	if (bpffs_fd < 0) {
5414 		err = -errno;
5415 		__pr(level, "object '%s': failed (%s) to open BPF FS mount at '%s'%s\n",
5416 		     obj->name, errstr(err), bpffs_path,
5417 		     mandatory ? "" : ", skipping optional step...");
5418 		return mandatory ? err : 0;
5419 	}
5420 
5421 	token_fd = bpf_token_create(bpffs_fd, 0);
5422 	close(bpffs_fd);
5423 	if (token_fd < 0) {
5424 		if (!mandatory && token_fd == -ENOENT) {
5425 			pr_debug("object '%s': BPF FS at '%s' doesn't have BPF token delegation set up, skipping...\n",
5426 				 obj->name, bpffs_path);
5427 			return 0;
5428 		}
5429 		__pr(level, "object '%s': failed (%d) to create BPF token from '%s'%s\n",
5430 		     obj->name, token_fd, bpffs_path,
5431 		     mandatory ? "" : ", skipping optional step...");
5432 		return mandatory ? token_fd : 0;
5433 	}
5434 
5435 	obj->feat_cache = calloc(1, sizeof(*obj->feat_cache));
5436 	if (!obj->feat_cache) {
5437 		close(token_fd);
5438 		return -ENOMEM;
5439 	}
5440 
5441 	obj->token_fd = token_fd;
5442 	obj->feat_cache->token_fd = token_fd;
5443 
5444 	return 0;
5445 }
5446 
5447 static int
5448 bpf_object__probe_loading(struct bpf_object *obj)
5449 {
5450 	struct bpf_insn insns[] = {
5451 		BPF_MOV64_IMM(BPF_REG_0, 0),
5452 		BPF_EXIT_INSN(),
5453 	};
5454 	int ret, insn_cnt = ARRAY_SIZE(insns);
5455 
5456 	if (obj->gen_loader || obj->token_fd)
5457 		return 0;
5458 
5459 	ret = bump_rlimit_memlock();
5460 	if (ret)
5461 		pr_warn("Failed to bump RLIMIT_MEMLOCK (err = %s), you might need to do it explicitly!\n",
5462 			errstr(ret));
5463 
5464 	/* make sure basic loading works */
5465 	ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
5466 	if (ret < 0)
5467 		ret = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, NULL);
5468 	if (ret < 0) {
5469 		ret = errno;
5470 		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",
5471 			__func__, errstr(ret));
5472 		return -ret;
5473 	}
5474 	close(ret);
5475 
5476 	return 0;
5477 }
5478 
5479 bool kernel_supports(const struct bpf_object *obj, enum kern_feature_id feat_id)
5480 {
5481 	if (obj->gen_loader)
5482 		/* To generate loader program assume the latest kernel
5483 		 * to avoid doing extra prog_load, map_create syscalls.
5484 		 */
5485 		return true;
5486 
5487 	if (obj->feat_cache)
5488 		return feat_supported(obj->feat_cache, feat_id);
5489 
5490 	return feat_supported(NULL, feat_id);
5491 }
5492 
5493 /* Used in testing to simulate missing features. */
5494 void bpf_object_set_feat_cache(struct bpf_object *obj, struct kern_feature_cache *cache)
5495 {
5496 	if (obj->feat_cache)
5497 		free(obj->feat_cache);
5498 	obj->feat_cache = cache;
5499 }
5500 
5501 static bool map_is_reuse_compat(const struct bpf_map *map, int map_fd)
5502 {
5503 	struct bpf_map_info map_info;
5504 	__u32 map_info_len = sizeof(map_info);
5505 	int err;
5506 
5507 	memset(&map_info, 0, map_info_len);
5508 	err = bpf_map_get_info_by_fd(map_fd, &map_info, &map_info_len);
5509 	if (err && errno == EINVAL)
5510 		err = bpf_get_map_info_from_fdinfo(map_fd, &map_info);
5511 	if (err) {
5512 		pr_warn("failed to get map info for map FD %d: %s\n", map_fd,
5513 			errstr(err));
5514 		return false;
5515 	}
5516 
5517 	/*
5518 	 * bpf_get_map_info_by_fd() for DEVMAP will always return flags with
5519 	 * BPF_F_RDONLY_PROG set, but it generally is not set at map creation time.
5520 	 * Thus, ignore the BPF_F_RDONLY_PROG flag in the flags returned from
5521 	 * bpf_get_map_info_by_fd() when checking for compatibility with an
5522 	 * existing DEVMAP.
5523 	 */
5524 	if (map->def.type == BPF_MAP_TYPE_DEVMAP || map->def.type == BPF_MAP_TYPE_DEVMAP_HASH)
5525 		map_info.map_flags &= ~BPF_F_RDONLY_PROG;
5526 
5527 	return (map_info.type == map->def.type &&
5528 		map_info.key_size == map->def.key_size &&
5529 		map_info.value_size == map->def.value_size &&
5530 		map_info.max_entries == map->def.max_entries &&
5531 		map_info.map_flags == map->def.map_flags &&
5532 		map_info.map_extra == map->map_extra);
5533 }
5534 
5535 static int
5536 bpf_object__reuse_map(struct bpf_map *map)
5537 {
5538 	int err, pin_fd;
5539 
5540 	pin_fd = bpf_obj_get(map->pin_path);
5541 	if (pin_fd < 0) {
5542 		err = -errno;
5543 		if (err == -ENOENT) {
5544 			pr_debug("found no pinned map to reuse at '%s'\n",
5545 				 map->pin_path);
5546 			return 0;
5547 		}
5548 
5549 		pr_warn("couldn't retrieve pinned map '%s': %s\n",
5550 			map->pin_path, errstr(err));
5551 		return err;
5552 	}
5553 
5554 	if (!map_is_reuse_compat(map, pin_fd)) {
5555 		pr_warn("couldn't reuse pinned map at '%s': parameter mismatch\n",
5556 			map->pin_path);
5557 		close(pin_fd);
5558 		return -EINVAL;
5559 	}
5560 
5561 	err = bpf_map__reuse_fd(map, pin_fd);
5562 	close(pin_fd);
5563 	if (err)
5564 		return err;
5565 
5566 	map->pinned = true;
5567 	pr_debug("reused pinned map at '%s'\n", map->pin_path);
5568 
5569 	return 0;
5570 }
5571 
5572 static struct bpf_map *bpf_object__sec_map(struct bpf_object *obj, int sec_idx)
5573 {
5574 	int i;
5575 
5576 	for (i = 0; i < obj->nr_maps; i++)
5577 		if (bpf_map__is_internal(&obj->maps[i]) && obj->maps[i].sec_idx == sec_idx)
5578 			return &obj->maps[i];
5579 	return NULL;
5580 }
5581 
5582 static int bpf_object__mmap_arena(struct bpf_object *obj, struct bpf_map *map)
5583 {
5584 	int i, err;
5585 
5586 	map->mmaped = mmap((void *)(long)map->map_extra,
5587 			   bpf_map_mmap_sz(map), PROT_READ | PROT_WRITE,
5588 			   map->map_extra ? MAP_SHARED | MAP_FIXED : MAP_SHARED,
5589 			   map->fd, 0);
5590 	if (map->mmaped == MAP_FAILED) {
5591 		err = -errno;
5592 		map->mmaped = NULL;
5593 		pr_warn("map '%s': failed to mmap arena: %s\n",
5594 			map->name, errstr(err));
5595 		return err;
5596 	}
5597 	if (obj->arena_data) {
5598 		memcpy(map->mmaped + obj->arena_data_off, obj->arena_data,
5599 			obj->arena_data_sz);
5600 		zfree(&obj->arena_data);
5601 	}
5602 	for (i = 0; i < obj->nr_maps; i++) {
5603 		struct bpf_map *m = &obj->maps[i];
5604 
5605 		if (m->in_arena)
5606 			m->mmaped = map->mmaped + obj->arena_data_off + m->arena_off;
5607 	}
5608 	return 0;
5609 }
5610 
5611 static int
5612 bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
5613 {
5614 	enum libbpf_map_type map_type = map->libbpf_type;
5615 	bool is_percpu = map_type == LIBBPF_MAP_PERCPU;
5616 	const __u64 update_flags = is_percpu ? BPF_F_ALL_CPUS : 0;
5617 	int err, zero = 0;
5618 	size_t mmap_sz;
5619 
5620 	if (obj->gen_loader) {
5621 		bpf_gen__map_update_elem(obj->gen_loader, map - obj->maps,
5622 					 map->mmaped, map->def.value_size, update_flags);
5623 		if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG)
5624 			bpf_gen__map_freeze(obj->gen_loader, map - obj->maps);
5625 		return 0;
5626 	}
5627 
5628 	err = bpf_map_update_elem(map->fd, &zero, map->mmaped, update_flags);
5629 	if (err) {
5630 		err = -errno;
5631 		pr_warn("map '%s': failed to set initial contents: %s\n",
5632 			bpf_map__name(map), errstr(err));
5633 		return err;
5634 	}
5635 
5636 	/* Freeze .rodata and .kconfig map as read-only from syscall side. */
5637 	if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG) {
5638 		err = bpf_map_freeze(map->fd);
5639 		if (err) {
5640 			err = -errno;
5641 			pr_warn("map '%s': failed to freeze as read-only: %s\n",
5642 				bpf_map__name(map), errstr(err));
5643 			return err;
5644 		}
5645 	}
5646 
5647 	/* Remap anonymous mmap()-ed "map initialization image" as
5648 	 * a BPF map-backed mmap()-ed memory, but preserving the same
5649 	 * memory address. This will cause kernel to change process'
5650 	 * page table to point to a different piece of kernel memory,
5651 	 * but from userspace point of view memory address (and its
5652 	 * contents, being identical at this point) will stay the
5653 	 * same. This mapping will be released by bpf_object__close()
5654 	 * as per normal clean up procedure.
5655 	 */
5656 	mmap_sz = bpf_map_mmap_sz(map);
5657 	if (map->def.map_flags & BPF_F_MMAPABLE) {
5658 		void *mmaped;
5659 		int prot;
5660 
5661 		if (map->def.map_flags & BPF_F_RDONLY_PROG)
5662 			prot = PROT_READ;
5663 		else
5664 			prot = PROT_READ | PROT_WRITE;
5665 		mmaped = mmap(map->mmaped, mmap_sz, prot, MAP_SHARED | MAP_FIXED, map->fd, 0);
5666 		if (mmaped == MAP_FAILED) {
5667 			err = -errno;
5668 			pr_warn("map '%s': failed to re-mmap() contents: %s\n",
5669 				bpf_map__name(map), errstr(err));
5670 			return err;
5671 		}
5672 		map->mmaped = mmaped;
5673 	} else if (is_percpu) {
5674 		if (mprotect(map->mmaped, mmap_sz, PROT_READ)) {
5675 			err = -errno;
5676 			pr_warn("map '%s': failed to mprotect() contents: %s\n",
5677 				bpf_map__name(map), errstr(err));
5678 			return err;
5679 		}
5680 	} else if (map->mmaped) {
5681 		munmap(map->mmaped, mmap_sz);
5682 		map->mmaped = NULL;
5683 	}
5684 
5685 	return 0;
5686 }
5687 
5688 static void bpf_map__destroy(struct bpf_map *map);
5689 
5690 static int bpf_object__create_map(struct bpf_object *obj, struct bpf_map *map, bool is_inner)
5691 {
5692 	LIBBPF_OPTS(bpf_map_create_opts, create_attr);
5693 	struct bpf_map_def *def = &map->def;
5694 	const char *map_name = NULL;
5695 	int err = 0, map_fd;
5696 
5697 	if (kernel_supports(obj, FEAT_PROG_NAME))
5698 		map_name = map->name;
5699 	create_attr.map_ifindex = map->map_ifindex;
5700 	create_attr.map_flags = def->map_flags;
5701 	create_attr.numa_node = map->numa_node;
5702 	create_attr.map_extra = map->map_extra;
5703 	create_attr.token_fd = obj->token_fd;
5704 	if (obj->token_fd)
5705 		create_attr.map_flags |= BPF_F_TOKEN_FD;
5706 	if (map->excl_prog) {
5707 		err = bpf_prog_compute_hash(map->excl_prog);
5708 		if (err)
5709 			return err;
5710 
5711 		create_attr.excl_prog_hash = map->excl_prog->hash;
5712 		create_attr.excl_prog_hash_size = SHA256_DIGEST_LENGTH;
5713 	}
5714 
5715 	if (bpf_map__is_struct_ops(map)) {
5716 		create_attr.btf_vmlinux_value_type_id = map->btf_vmlinux_value_type_id;
5717 		if (map->mod_btf_fd >= 0) {
5718 			create_attr.value_type_btf_obj_fd = map->mod_btf_fd;
5719 			create_attr.map_flags |= BPF_F_VTYPE_BTF_OBJ_FD;
5720 		}
5721 	}
5722 
5723 	if (obj->btf && btf__fd(obj->btf) >= 0) {
5724 		create_attr.btf_fd = btf__fd(obj->btf);
5725 		create_attr.btf_key_type_id = map->btf_key_type_id;
5726 		create_attr.btf_value_type_id = map->btf_value_type_id;
5727 	}
5728 
5729 	if (bpf_map_type__is_map_in_map(def->type)) {
5730 		if (map->inner_map) {
5731 			err = map_set_def_max_entries(map->inner_map);
5732 			if (err)
5733 				return err;
5734 			err = bpf_object__create_map(obj, map->inner_map, true);
5735 			if (err) {
5736 				pr_warn("map '%s': failed to create inner map: %s\n",
5737 					map->name, errstr(err));
5738 				return err;
5739 			}
5740 			map->inner_map_fd = map->inner_map->fd;
5741 		}
5742 		if (map->inner_map_fd >= 0)
5743 			create_attr.inner_map_fd = map->inner_map_fd;
5744 	}
5745 
5746 	switch (def->type) {
5747 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
5748 	case BPF_MAP_TYPE_CGROUP_ARRAY:
5749 	case BPF_MAP_TYPE_STACK_TRACE:
5750 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
5751 	case BPF_MAP_TYPE_HASH_OF_MAPS:
5752 	case BPF_MAP_TYPE_DEVMAP:
5753 	case BPF_MAP_TYPE_DEVMAP_HASH:
5754 	case BPF_MAP_TYPE_CPUMAP:
5755 	case BPF_MAP_TYPE_XSKMAP:
5756 	case BPF_MAP_TYPE_SOCKMAP:
5757 	case BPF_MAP_TYPE_SOCKHASH:
5758 	case BPF_MAP_TYPE_QUEUE:
5759 	case BPF_MAP_TYPE_STACK:
5760 	case BPF_MAP_TYPE_ARENA:
5761 		create_attr.btf_fd = 0;
5762 		create_attr.btf_key_type_id = 0;
5763 		create_attr.btf_value_type_id = 0;
5764 		map->btf_key_type_id = 0;
5765 		map->btf_value_type_id = 0;
5766 		break;
5767 	case BPF_MAP_TYPE_STRUCT_OPS:
5768 		create_attr.btf_value_type_id = 0;
5769 		break;
5770 	default:
5771 		break;
5772 	}
5773 
5774 	if (obj->gen_loader) {
5775 		bpf_gen__map_create(obj->gen_loader, def->type, map_name,
5776 				    def->key_size, def->value_size, def->max_entries,
5777 				    &create_attr, is_inner ? -1 : map - obj->maps);
5778 		/* We keep pretenting we have valid FD to pass various fd >= 0
5779 		 * checks by just keeping original placeholder FDs in place.
5780 		 * See bpf_object__add_map() comment.
5781 		 * This placeholder fd will not be used with any syscall and
5782 		 * will be reset to -1 eventually.
5783 		 */
5784 		map_fd = map->fd;
5785 	} else {
5786 		map_fd = bpf_map_create(def->type, map_name,
5787 					def->key_size, def->value_size,
5788 					def->max_entries, &create_attr);
5789 	}
5790 	if (map_fd < 0 && (create_attr.btf_key_type_id || create_attr.btf_value_type_id)) {
5791 		err = -errno;
5792 		pr_warn("Error in bpf_create_map_xattr(%s): %s. Retrying without BTF.\n",
5793 			map->name, errstr(err));
5794 		create_attr.btf_fd = 0;
5795 		create_attr.btf_key_type_id = 0;
5796 		create_attr.btf_value_type_id = 0;
5797 		map->btf_key_type_id = 0;
5798 		map->btf_value_type_id = 0;
5799 		map_fd = bpf_map_create(def->type, map_name,
5800 					def->key_size, def->value_size,
5801 					def->max_entries, &create_attr);
5802 	}
5803 
5804 	if (bpf_map_type__is_map_in_map(def->type) && map->inner_map) {
5805 		if (obj->gen_loader)
5806 			map->inner_map->fd = -1;
5807 		bpf_map__destroy(map->inner_map);
5808 		zfree(&map->inner_map);
5809 	}
5810 
5811 	if (map_fd < 0)
5812 		return map_fd;
5813 
5814 	/* obj->gen_loader case, prevent reuse_fd() from closing map_fd */
5815 	if (map->fd == map_fd)
5816 		return 0;
5817 
5818 	/* Keep placeholder FD value but now point it to the BPF map object.
5819 	 * This way everything that relied on this map's FD (e.g., relocated
5820 	 * ldimm64 instructions) will stay valid and won't need adjustments.
5821 	 * map->fd stays valid but now point to what map_fd points to.
5822 	 */
5823 	return reuse_fd(map->fd, map_fd);
5824 }
5825 
5826 static int init_map_in_map_slots(struct bpf_object *obj, struct bpf_map *map)
5827 {
5828 	const struct bpf_map *targ_map;
5829 	unsigned int i;
5830 	int fd, err = 0;
5831 
5832 	for (i = 0; i < map->init_slots_sz; i++) {
5833 		if (!map->init_slots[i])
5834 			continue;
5835 
5836 		targ_map = map->init_slots[i];
5837 		fd = targ_map->fd;
5838 
5839 		if (obj->gen_loader) {
5840 			bpf_gen__populate_outer_map(obj->gen_loader,
5841 						    map - obj->maps, i,
5842 						    targ_map - obj->maps);
5843 		} else {
5844 			err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5845 		}
5846 		if (err) {
5847 			err = -errno;
5848 			pr_warn("map '%s': failed to initialize slot [%u] to map '%s' fd=%d: %s\n",
5849 				map->name, i, targ_map->name, fd, errstr(err));
5850 			return err;
5851 		}
5852 		pr_debug("map '%s': slot [%u] set to map '%s' fd=%d\n",
5853 			 map->name, i, targ_map->name, fd);
5854 	}
5855 
5856 	zfree(&map->init_slots);
5857 	map->init_slots_sz = 0;
5858 
5859 	return 0;
5860 }
5861 
5862 static int init_prog_array_slots(struct bpf_object *obj, struct bpf_map *map)
5863 {
5864 	const struct bpf_program *targ_prog;
5865 	unsigned int i;
5866 	int fd, err;
5867 
5868 	if (obj->gen_loader)
5869 		return -ENOTSUP;
5870 
5871 	for (i = 0; i < map->init_slots_sz; i++) {
5872 		if (!map->init_slots[i])
5873 			continue;
5874 
5875 		targ_prog = map->init_slots[i];
5876 		fd = bpf_program__fd(targ_prog);
5877 
5878 		err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5879 		if (err) {
5880 			err = -errno;
5881 			pr_warn("map '%s': failed to initialize slot [%u] to prog '%s' fd=%d: %s\n",
5882 				map->name, i, targ_prog->name, fd, errstr(err));
5883 			return err;
5884 		}
5885 		pr_debug("map '%s': slot [%u] set to prog '%s' fd=%d\n",
5886 			 map->name, i, targ_prog->name, fd);
5887 	}
5888 
5889 	zfree(&map->init_slots);
5890 	map->init_slots_sz = 0;
5891 
5892 	return 0;
5893 }
5894 
5895 static int bpf_object_init_prog_arrays(struct bpf_object *obj)
5896 {
5897 	struct bpf_map *map;
5898 	int i, err;
5899 
5900 	for (i = 0; i < obj->nr_maps; i++) {
5901 		map = &obj->maps[i];
5902 
5903 		if (!map->init_slots_sz || map->def.type != BPF_MAP_TYPE_PROG_ARRAY)
5904 			continue;
5905 
5906 		err = init_prog_array_slots(obj, map);
5907 		if (err < 0)
5908 			return err;
5909 	}
5910 	return 0;
5911 }
5912 
5913 static int map_set_def_max_entries(struct bpf_map *map)
5914 {
5915 	if (map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY && !map->def.max_entries) {
5916 		int nr_cpus;
5917 
5918 		nr_cpus = libbpf_num_possible_cpus();
5919 		if (nr_cpus < 0) {
5920 			pr_warn("map '%s': failed to determine number of system CPUs: %d\n",
5921 				map->name, nr_cpus);
5922 			return nr_cpus;
5923 		}
5924 		pr_debug("map '%s': setting size to %d\n", map->name, nr_cpus);
5925 		map->def.max_entries = nr_cpus;
5926 	}
5927 
5928 	return 0;
5929 }
5930 
5931 static int
5932 bpf_object__create_maps(struct bpf_object *obj)
5933 {
5934 	struct bpf_map *map;
5935 	unsigned int i, j;
5936 	int err;
5937 	bool retried;
5938 
5939 	for (i = 0; i < obj->nr_maps; i++) {
5940 		map = &obj->maps[i];
5941 
5942 		/* To support old kernels, we skip creating global data maps
5943 		 * (.rodata, .data, .kconfig, etc); later on, during program
5944 		 * loading, if we detect that at least one of the to-be-loaded
5945 		 * programs is referencing any global data map, we'll error
5946 		 * out with program name and relocation index logged.
5947 		 * This approach allows to accommodate Clang emitting
5948 		 * unnecessary .rodata.str1.1 sections for string literals,
5949 		 * but also it allows to have CO-RE applications that use
5950 		 * global variables in some of BPF programs, but not others.
5951 		 * If those global variable-using programs are not loaded at
5952 		 * runtime due to bpf_program__set_autoload(prog, false),
5953 		 * bpf_object loading will succeed just fine even on old
5954 		 * kernels.
5955 		 * Same skipping applies to percpu data.
5956 		 */
5957 		if (bpf_map__is_internal(map)) {
5958 			bool is_percpu = map->libbpf_type == LIBBPF_MAP_PERCPU;
5959 			enum kern_feature_id feat_id;
5960 
5961 			feat_id = is_percpu ? FEAT_PERCPU_DATA : FEAT_GLOBAL_DATA;
5962 			if (!kernel_supports(obj, feat_id))
5963 				map->autocreate = false;
5964 		}
5965 
5966 		if (!map->autocreate) {
5967 			pr_debug("map '%s': skipped auto-creating...\n", map->name);
5968 			continue;
5969 		}
5970 
5971 		/* see bpf_object__relocate_data_ptrs() */
5972 		if (map->def.type == BPF_MAP_TYPE_ARENA && obj->arena_mapped)
5973 			continue;
5974 
5975 		err = map_set_def_max_entries(map);
5976 		if (err)
5977 			goto err_out;
5978 
5979 		retried = false;
5980 retry:
5981 		if (map->pin_path) {
5982 			err = bpf_object__reuse_map(map);
5983 			if (err) {
5984 				pr_warn("map '%s': error reusing pinned map\n",
5985 					map->name);
5986 				goto err_out;
5987 			}
5988 			if (retried && map->fd < 0) {
5989 				pr_warn("map '%s': cannot find pinned map\n",
5990 					map->name);
5991 				err = -ENOENT;
5992 				goto err_out;
5993 			}
5994 		}
5995 
5996 		if (map->reused) {
5997 			pr_debug("map '%s': skipping creation (preset fd=%d)\n",
5998 				 map->name, map->fd);
5999 		} else {
6000 			err = bpf_object__create_map(obj, map, false);
6001 			if (err)
6002 				goto err_out;
6003 
6004 			pr_debug("map '%s': created successfully, fd=%d\n",
6005 				 map->name, map->fd);
6006 
6007 			if (bpf_map__is_internal(map)) {
6008 				err = bpf_object__populate_internal_map(obj, map);
6009 				if (err < 0)
6010 					goto err_out;
6011 			} else if (map->def.type == BPF_MAP_TYPE_ARENA) {
6012 				err = bpf_object__mmap_arena(obj, map);
6013 				if (err)
6014 					return err;
6015 			}
6016 			if (map->init_slots_sz && map->def.type != BPF_MAP_TYPE_PROG_ARRAY) {
6017 				err = init_map_in_map_slots(obj, map);
6018 				if (err < 0)
6019 					goto err_out;
6020 			}
6021 		}
6022 
6023 		if (map->pin_path && !map->pinned) {
6024 			err = bpf_map__pin(map, NULL);
6025 			if (err) {
6026 				if (!retried && err == -EEXIST) {
6027 					retried = true;
6028 					goto retry;
6029 				}
6030 				pr_warn("map '%s': failed to auto-pin at '%s': %s\n",
6031 					map->name, map->pin_path, errstr(err));
6032 				goto err_out;
6033 			}
6034 		}
6035 	}
6036 
6037 	return 0;
6038 
6039 err_out:
6040 	pr_warn("map '%s': failed to create: %s\n", map->name, errstr(err));
6041 	pr_perm_msg(err);
6042 	for (j = 0; j < i; j++)
6043 		zclose(obj->maps[j].fd);
6044 	return err;
6045 }
6046 
6047 static bool bpf_core_is_flavor_sep(const char *s)
6048 {
6049 	/* check X___Y name pattern, where X and Y are not underscores */
6050 	return s[0] != '_' &&				      /* X */
6051 	       s[1] == '_' && s[2] == '_' && s[3] == '_' &&   /* ___ */
6052 	       s[4] != '_';				      /* Y */
6053 }
6054 
6055 /* Given 'some_struct_name___with_flavor' return the length of a name prefix
6056  * before last triple underscore. Struct name part after last triple
6057  * underscore is ignored by BPF CO-RE relocation during relocation matching.
6058  */
6059 size_t bpf_core_essential_name_len(const char *name)
6060 {
6061 	size_t n = strlen(name);
6062 	int i;
6063 
6064 	for (i = n - 5; i >= 0; i--) {
6065 		if (bpf_core_is_flavor_sep(name + i))
6066 			return i + 1;
6067 	}
6068 	return n;
6069 }
6070 
6071 void bpf_core_free_cands(struct bpf_core_cand_list *cands)
6072 {
6073 	if (!cands)
6074 		return;
6075 
6076 	free(cands->cands);
6077 	free(cands);
6078 }
6079 
6080 int bpf_core_add_cands(struct bpf_core_cand *local_cand,
6081 		       size_t local_essent_len,
6082 		       const struct btf *targ_btf,
6083 		       const char *targ_btf_name,
6084 		       int targ_start_id,
6085 		       struct bpf_core_cand_list *cands)
6086 {
6087 	struct bpf_core_cand *new_cands, *cand;
6088 	const struct btf_type *t, *local_t;
6089 	const char *targ_name, *local_name;
6090 	size_t targ_essent_len;
6091 	int n, i;
6092 
6093 	local_t = btf__type_by_id(local_cand->btf, local_cand->id);
6094 	local_name = btf__str_by_offset(local_cand->btf, local_t->name_off);
6095 
6096 	n = btf__type_cnt(targ_btf);
6097 	for (i = targ_start_id; i < n; i++) {
6098 		t = btf__type_by_id(targ_btf, i);
6099 		if (!btf_kind_core_compat(t, local_t))
6100 			continue;
6101 
6102 		targ_name = btf__name_by_offset(targ_btf, t->name_off);
6103 		if (str_is_empty(targ_name))
6104 			continue;
6105 
6106 		targ_essent_len = bpf_core_essential_name_len(targ_name);
6107 		if (targ_essent_len != local_essent_len)
6108 			continue;
6109 
6110 		if (strncmp(local_name, targ_name, local_essent_len) != 0)
6111 			continue;
6112 
6113 		pr_debug("CO-RE relocating [%u] %s %s: found target candidate [%d] %s %s in [%s]\n",
6114 			 local_cand->id, btf_kind_str(local_t),
6115 			 local_name, i, btf_kind_str(t), targ_name,
6116 			 targ_btf_name);
6117 		new_cands = libbpf_reallocarray(cands->cands, cands->len + 1,
6118 					      sizeof(*cands->cands));
6119 		if (!new_cands)
6120 			return -ENOMEM;
6121 
6122 		cand = &new_cands[cands->len];
6123 		cand->btf = targ_btf;
6124 		cand->id = i;
6125 
6126 		cands->cands = new_cands;
6127 		cands->len++;
6128 	}
6129 	return 0;
6130 }
6131 
6132 static bool is_btf_mod_allowed(const struct bpf_object *obj, const char *name)
6133 {
6134 	ssize_t i;
6135 
6136 	if (obj->btf_module_allowlist_cnt < 0)
6137 		return true;
6138 
6139 	for (i = 0; i < obj->btf_module_allowlist_cnt; i++) {
6140 		if (strcmp(obj->btf_module_allowlist[i], name) == 0)
6141 			return true;
6142 	}
6143 
6144 	return false;
6145 }
6146 
6147 static int load_module_btfs(struct bpf_object *obj)
6148 {
6149 	struct bpf_btf_info info;
6150 	struct module_btf *mod_btf;
6151 	struct btf *btf;
6152 	char name[64];
6153 	__u32 id = 0, len;
6154 	int err, fd;
6155 
6156 	if (obj->btf_modules_loaded)
6157 		return 0;
6158 
6159 	if (obj->gen_loader)
6160 		return 0;
6161 
6162 	/* don't do this again, even if we find no module BTFs */
6163 	obj->btf_modules_loaded = true;
6164 
6165 	/* kernel too old to support module BTFs */
6166 	if (!kernel_supports(obj, FEAT_MODULE_BTF))
6167 		return 0;
6168 
6169 	if (obj->btf_module_allowlist_cnt == 0)
6170 		return 0;
6171 
6172 	while (true) {
6173 		err = bpf_btf_get_next_id(id, &id);
6174 		if (err && errno == ENOENT)
6175 			return 0;
6176 		if (err && errno == EPERM) {
6177 			pr_debug("skipping module BTFs loading, missing privileges\n");
6178 			return 0;
6179 		}
6180 		if (err) {
6181 			err = -errno;
6182 			pr_warn("failed to iterate BTF objects: %s\n", errstr(err));
6183 			return err;
6184 		}
6185 
6186 		fd = bpf_btf_get_fd_by_id(id);
6187 		if (fd < 0) {
6188 			if (errno == ENOENT)
6189 				continue; /* expected race: BTF was unloaded */
6190 			err = -errno;
6191 			pr_warn("failed to get BTF object #%u FD: %s\n", id, errstr(err));
6192 			return err;
6193 		}
6194 
6195 		len = sizeof(info);
6196 		memset(&info, 0, sizeof(info));
6197 		info.name = ptr_to_u64(name);
6198 		info.name_len = sizeof(name);
6199 
6200 		btf = NULL;
6201 		err = bpf_btf_get_info_by_fd(fd, &info, &len);
6202 		if (err) {
6203 			err = -errno;
6204 			pr_warn("failed to get BTF object #%u info: %s\n", id, errstr(err));
6205 			break;
6206 		}
6207 
6208 		/* ignore non-module BTFs */
6209 		if (!info.kernel_btf || strcmp(name, "vmlinux") == 0) {
6210 			close(fd);
6211 			continue;
6212 		}
6213 
6214 		if (!is_btf_mod_allowed(obj, name)) {
6215 			close(fd);
6216 			continue;
6217 		}
6218 
6219 		btf = btf_get_from_fd(fd, obj->btf_vmlinux);
6220 		err = libbpf_get_error(btf);
6221 		if (err) {
6222 			pr_warn("failed to load module [%s]'s BTF object #%u: %s\n",
6223 				name, id, errstr(err));
6224 			break;
6225 		}
6226 
6227 		err = libbpf_ensure_mem((void **)&obj->btf_modules, &obj->btf_module_cap,
6228 					sizeof(*obj->btf_modules), obj->btf_module_cnt + 1);
6229 		if (err)
6230 			break;
6231 
6232 		mod_btf = &obj->btf_modules[obj->btf_module_cnt];
6233 
6234 		mod_btf->btf = btf;
6235 		mod_btf->id = id;
6236 		mod_btf->fd = fd;
6237 		mod_btf->name = strdup(name);
6238 		if (!mod_btf->name) {
6239 			err = -ENOMEM;
6240 			break;
6241 		}
6242 		obj->btf_module_cnt++;
6243 
6244 		if (obj->btf_module_allowlist_cnt == obj->btf_module_cnt)
6245 			break;
6246 	}
6247 
6248 	if (err) {
6249 		btf__free(btf);
6250 		close(fd);
6251 	}
6252 	return err;
6253 }
6254 
6255 static struct bpf_core_cand_list *
6256 bpf_core_find_cands(struct bpf_object *obj, const struct btf *local_btf, __u32 local_type_id)
6257 {
6258 	struct bpf_core_cand local_cand = {};
6259 	struct bpf_core_cand_list *cands;
6260 	const struct btf *main_btf;
6261 	const struct btf_type *local_t;
6262 	const char *local_name;
6263 	size_t local_essent_len;
6264 	int err, i;
6265 
6266 	local_cand.btf = local_btf;
6267 	local_cand.id = local_type_id;
6268 	local_t = btf__type_by_id(local_btf, local_type_id);
6269 	if (!local_t)
6270 		return ERR_PTR(-EINVAL);
6271 
6272 	local_name = btf__name_by_offset(local_btf, local_t->name_off);
6273 	if (str_is_empty(local_name))
6274 		return ERR_PTR(-EINVAL);
6275 	local_essent_len = bpf_core_essential_name_len(local_name);
6276 
6277 	cands = calloc(1, sizeof(*cands));
6278 	if (!cands)
6279 		return ERR_PTR(-ENOMEM);
6280 
6281 	/* Attempt to find target candidates in vmlinux BTF first */
6282 	main_btf = obj->btf_vmlinux_override ?: obj->btf_vmlinux;
6283 	err = bpf_core_add_cands(&local_cand, local_essent_len, main_btf, "vmlinux", 1, cands);
6284 	if (err)
6285 		goto err_out;
6286 
6287 	/* if vmlinux BTF has any candidate, don't got for module BTFs */
6288 	if (cands->len)
6289 		return cands;
6290 
6291 	/* if vmlinux BTF was overridden, don't attempt to load module BTFs */
6292 	if (obj->btf_vmlinux_override)
6293 		return cands;
6294 
6295 	/* now look through module BTFs, trying to still find candidates */
6296 	err = load_module_btfs(obj);
6297 	if (err)
6298 		goto err_out;
6299 
6300 	for (i = 0; i < obj->btf_module_cnt; i++) {
6301 		err = bpf_core_add_cands(&local_cand, local_essent_len,
6302 					 obj->btf_modules[i].btf,
6303 					 obj->btf_modules[i].name,
6304 					 btf__type_cnt(obj->btf_vmlinux),
6305 					 cands);
6306 		if (err)
6307 			goto err_out;
6308 	}
6309 
6310 	return cands;
6311 err_out:
6312 	bpf_core_free_cands(cands);
6313 	return ERR_PTR(err);
6314 }
6315 
6316 /* Check local and target types for compatibility. This check is used for
6317  * type-based CO-RE relocations and follow slightly different rules than
6318  * field-based relocations. This function assumes that root types were already
6319  * checked for name match. Beyond that initial root-level name check, names
6320  * are completely ignored. Compatibility rules are as follows:
6321  *   - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs are considered compatible, but
6322  *     kind should match for local and target types (i.e., STRUCT is not
6323  *     compatible with UNION);
6324  *   - for ENUMs, the size is ignored;
6325  *   - for INT, size and signedness are ignored;
6326  *   - for ARRAY, dimensionality is ignored, element types are checked for
6327  *     compatibility recursively;
6328  *   - CONST/VOLATILE/RESTRICT modifiers are ignored;
6329  *   - TYPEDEFs/PTRs are compatible if types they pointing to are compatible;
6330  *   - FUNC_PROTOs are compatible if they have compatible signature: same
6331  *     number of input args and compatible return and argument types.
6332  * These rules are not set in stone and probably will be adjusted as we get
6333  * more experience with using BPF CO-RE relocations.
6334  */
6335 int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
6336 			      const struct btf *targ_btf, __u32 targ_id)
6337 {
6338 	return __bpf_core_types_are_compat(local_btf, local_id, targ_btf, targ_id, 32);
6339 }
6340 
6341 int bpf_core_types_match(const struct btf *local_btf, __u32 local_id,
6342 			 const struct btf *targ_btf, __u32 targ_id)
6343 {
6344 	return __bpf_core_types_match(local_btf, local_id, targ_btf, targ_id, false, 32);
6345 }
6346 
6347 static size_t bpf_core_hash_fn(const long key, void *ctx)
6348 {
6349 	return key;
6350 }
6351 
6352 static bool bpf_core_equal_fn(const long k1, const long k2, void *ctx)
6353 {
6354 	return k1 == k2;
6355 }
6356 
6357 static int record_relo_core(struct bpf_program *prog,
6358 			    const struct bpf_core_relo *core_relo, int insn_idx)
6359 {
6360 	struct reloc_desc *relos, *relo;
6361 
6362 	relos = libbpf_reallocarray(prog->reloc_desc,
6363 				    prog->nr_reloc + 1, sizeof(*relos));
6364 	if (!relos)
6365 		return -ENOMEM;
6366 	relo = &relos[prog->nr_reloc];
6367 	relo->type = RELO_CORE;
6368 	relo->insn_idx = insn_idx;
6369 	relo->core_relo = core_relo;
6370 	prog->reloc_desc = relos;
6371 	prog->nr_reloc++;
6372 	return 0;
6373 }
6374 
6375 static const struct bpf_core_relo *find_relo_core(struct bpf_program *prog, int insn_idx)
6376 {
6377 	struct reloc_desc *relo;
6378 	int i;
6379 
6380 	for (i = 0; i < prog->nr_reloc; i++) {
6381 		relo = &prog->reloc_desc[i];
6382 		if (relo->type != RELO_CORE || relo->insn_idx != insn_idx)
6383 			continue;
6384 
6385 		return relo->core_relo;
6386 	}
6387 
6388 	return NULL;
6389 }
6390 
6391 static int bpf_core_resolve_relo(struct bpf_program *prog,
6392 				 const struct bpf_core_relo *relo,
6393 				 int relo_idx,
6394 				 const struct btf *local_btf,
6395 				 struct hashmap *cand_cache,
6396 				 struct bpf_core_relo_res *targ_res)
6397 {
6398 	struct bpf_core_spec specs_scratch[3] = {};
6399 	struct bpf_core_cand_list *cands = NULL;
6400 	const char *prog_name = prog->name;
6401 	const struct btf_type *local_type;
6402 	const char *local_name;
6403 	__u32 local_id = relo->type_id;
6404 	int err;
6405 
6406 	local_type = btf__type_by_id(local_btf, local_id);
6407 	if (!local_type)
6408 		return -EINVAL;
6409 
6410 	local_name = btf__name_by_offset(local_btf, local_type->name_off);
6411 	if (!local_name)
6412 		return -EINVAL;
6413 
6414 	if (relo->kind != BPF_CORE_TYPE_ID_LOCAL &&
6415 	    !hashmap__find(cand_cache, local_id, &cands)) {
6416 		cands = bpf_core_find_cands(prog->obj, local_btf, local_id);
6417 		if (IS_ERR(cands)) {
6418 			pr_warn("prog '%s': relo #%d: target candidate search failed for [%u] %s %s: %ld\n",
6419 				prog_name, relo_idx, local_id, btf_kind_str(local_type),
6420 				local_name, PTR_ERR(cands));
6421 			return PTR_ERR(cands);
6422 		}
6423 		err = hashmap__set(cand_cache, local_id, cands, NULL, NULL);
6424 		if (err) {
6425 			bpf_core_free_cands(cands);
6426 			return err;
6427 		}
6428 	}
6429 
6430 	return bpf_core_calc_relo_insn(prog_name, relo, relo_idx, local_btf, cands, specs_scratch,
6431 				       targ_res);
6432 }
6433 
6434 static int
6435 bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
6436 {
6437 	const struct btf_ext_info_sec *sec;
6438 	struct bpf_core_relo_res targ_res;
6439 	const struct bpf_core_relo *rec;
6440 	const struct btf_ext_info *seg;
6441 	struct hashmap_entry *entry;
6442 	struct hashmap *cand_cache = NULL;
6443 	struct bpf_program *prog;
6444 	struct bpf_insn *insn;
6445 	const char *sec_name;
6446 	int i, err = 0, insn_idx, sec_idx, sec_num;
6447 
6448 	if (obj->btf_ext->core_relo_info.len == 0)
6449 		return 0;
6450 
6451 	if (targ_btf_path) {
6452 		obj->btf_vmlinux_override = btf__parse(targ_btf_path, NULL);
6453 		err = libbpf_get_error(obj->btf_vmlinux_override);
6454 		if (err) {
6455 			pr_warn("failed to parse target BTF: %s\n", errstr(err));
6456 			return err;
6457 		}
6458 	}
6459 
6460 	cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
6461 	if (IS_ERR(cand_cache)) {
6462 		err = PTR_ERR(cand_cache);
6463 		goto out;
6464 	}
6465 
6466 	seg = &obj->btf_ext->core_relo_info;
6467 	sec_num = 0;
6468 	for_each_btf_ext_sec(seg, sec) {
6469 		sec_idx = seg->sec_idxs[sec_num];
6470 		sec_num++;
6471 
6472 		sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
6473 		if (str_is_empty(sec_name)) {
6474 			err = -EINVAL;
6475 			goto out;
6476 		}
6477 
6478 		pr_debug("sec '%s': found %u CO-RE relocations\n", sec_name, sec->num_info);
6479 
6480 		for_each_btf_ext_rec(seg, sec, i, rec) {
6481 			if (rec->insn_off % BPF_INSN_SZ) {
6482 				err = -EINVAL;
6483 				goto out;
6484 			}
6485 
6486 			insn_idx = rec->insn_off / BPF_INSN_SZ;
6487 			prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
6488 			if (!prog) {
6489 				/* When __weak subprog is "overridden" by another instance
6490 				 * of the subprog from a different object file, linker still
6491 				 * appends all the .BTF.ext info that used to belong to that
6492 				 * eliminated subprogram.
6493 				 * This is similar to what x86-64 linker does for relocations.
6494 				 * So just ignore such relocations just like we ignore
6495 				 * subprog instructions when discovering subprograms.
6496 				 */
6497 				pr_debug("sec '%s': skipping CO-RE relocation #%d for insn #%d belonging to eliminated weak subprogram\n",
6498 					 sec_name, i, insn_idx);
6499 				continue;
6500 			}
6501 			/* no need to apply CO-RE relocation if the program is
6502 			 * not going to be loaded
6503 			 */
6504 			if (!prog->autoload)
6505 				continue;
6506 
6507 			/* adjust insn_idx from section frame of reference to the local
6508 			 * program's frame of reference; (sub-)program code is not yet
6509 			 * relocated, so it's enough to just subtract in-section offset
6510 			 */
6511 			insn_idx = insn_idx - prog->sec_insn_off;
6512 			if (insn_idx >= prog->insns_cnt) {
6513 				err = -EINVAL;
6514 				goto out;
6515 			}
6516 			insn = &prog->insns[insn_idx];
6517 
6518 			if (is_ldimm64_insn(insn) && (size_t)insn_idx + 1 >= prog->insns_cnt) {
6519 				pr_warn("prog '%s': relo #%d: insn #%d (LDIMM64) is truncated\n",
6520 					prog->name, i, insn_idx);
6521 				err = -EINVAL;
6522 				goto out;
6523 			}
6524 
6525 			err = record_relo_core(prog, rec, insn_idx);
6526 			if (err) {
6527 				pr_warn("prog '%s': relo #%d: failed to record relocation: %s\n",
6528 					prog->name, i, errstr(err));
6529 				goto out;
6530 			}
6531 
6532 			if (prog->obj->gen_loader)
6533 				continue;
6534 
6535 			err = bpf_core_resolve_relo(prog, rec, i, obj->btf, cand_cache, &targ_res);
6536 			if (err) {
6537 				pr_warn("prog '%s': relo #%d: failed to relocate: %s\n",
6538 					prog->name, i, errstr(err));
6539 				goto out;
6540 			}
6541 
6542 			err = bpf_core_patch_insn(prog->name, insn, insn_idx, rec, i, &targ_res);
6543 			if (err) {
6544 				pr_warn("prog '%s': relo #%d: failed to patch insn #%d: %s\n",
6545 					prog->name, i, insn_idx, errstr(err));
6546 				goto out;
6547 			}
6548 		}
6549 	}
6550 
6551 out:
6552 	/* obj->btf_vmlinux and module BTFs are freed after object load */
6553 	btf__free(obj->btf_vmlinux_override);
6554 	obj->btf_vmlinux_override = NULL;
6555 
6556 	if (!IS_ERR_OR_NULL(cand_cache)) {
6557 		hashmap__for_each_entry(cand_cache, entry, i) {
6558 			bpf_core_free_cands(entry->pvalue);
6559 		}
6560 		hashmap__free(cand_cache);
6561 	}
6562 	return err;
6563 }
6564 
6565 /* base map load ldimm64 special constant, used also for log fixup logic */
6566 #define POISON_LDIMM64_MAP_BASE 2001000000
6567 #define POISON_LDIMM64_MAP_PFX "200100"
6568 
6569 static void poison_map_ldimm64(struct bpf_program *prog, int relo_idx,
6570 			       int insn_idx, struct bpf_insn *insn,
6571 			       int map_idx, const struct bpf_map *map)
6572 {
6573 	int i;
6574 
6575 	pr_debug("prog '%s': relo #%d: poisoning insn #%d that loads map #%d '%s'\n",
6576 		 prog->name, relo_idx, insn_idx, map_idx, map->name);
6577 
6578 	/* we turn single ldimm64 into two identical invalid calls */
6579 	for (i = 0; i < 2; i++) {
6580 		insn->code = BPF_JMP | BPF_CALL;
6581 		insn->dst_reg = 0;
6582 		insn->src_reg = 0;
6583 		insn->off = 0;
6584 		/* if this instruction is reachable (not a dead code),
6585 		 * verifier will complain with something like:
6586 		 * invalid func unknown#2001000123
6587 		 * where lower 123 is map index into obj->maps[] array
6588 		 */
6589 		insn->imm = POISON_LDIMM64_MAP_BASE + map_idx;
6590 
6591 		insn++;
6592 	}
6593 }
6594 
6595 /* unresolved kfunc call special constant, used also for log fixup logic */
6596 #define POISON_CALL_KFUNC_BASE 2002000000
6597 #define POISON_CALL_KFUNC_PFX "2002"
6598 
6599 static void poison_kfunc_call(struct bpf_program *prog, int relo_idx,
6600 			      int insn_idx, struct bpf_insn *insn,
6601 			      int ext_idx, const struct extern_desc *ext)
6602 {
6603 	pr_debug("prog '%s': relo #%d: poisoning insn #%d that calls kfunc '%s'\n",
6604 		 prog->name, relo_idx, insn_idx, ext->name);
6605 
6606 	/* we turn kfunc call into invalid helper call with identifiable constant */
6607 	insn->code = BPF_JMP | BPF_CALL;
6608 	insn->dst_reg = 0;
6609 	insn->src_reg = 0;
6610 	insn->off = 0;
6611 	/* if this instruction is reachable (not a dead code),
6612 	 * verifier will complain with something like:
6613 	 * invalid func unknown#2001000123
6614 	 * where lower 123 is extern index into obj->externs[] array
6615 	 */
6616 	insn->imm = POISON_CALL_KFUNC_BASE + ext_idx;
6617 }
6618 
6619 static int find_jt_map(struct bpf_object *obj, struct bpf_program *prog, unsigned int sym_off)
6620 {
6621 	size_t i;
6622 
6623 	for (i = 0; i < obj->jumptable_map_cnt; i++) {
6624 		/*
6625 		 * This might happen that same offset is used for two different
6626 		 * programs (as jump tables can be the same). However, for
6627 		 * different programs different maps should be created.
6628 		 */
6629 		if (obj->jumptable_maps[i].sym_off == sym_off &&
6630 		    obj->jumptable_maps[i].prog == prog)
6631 			return obj->jumptable_maps[i].fd;
6632 	}
6633 
6634 	return -ENOENT;
6635 }
6636 
6637 static int add_jt_map(struct bpf_object *obj, struct bpf_program *prog, unsigned int sym_off, int map_fd)
6638 {
6639 	size_t cnt = obj->jumptable_map_cnt;
6640 	size_t size = sizeof(obj->jumptable_maps[0]);
6641 	void *tmp;
6642 
6643 	tmp = libbpf_reallocarray(obj->jumptable_maps, cnt + 1, size);
6644 	if (!tmp)
6645 		return -ENOMEM;
6646 
6647 	obj->jumptable_maps = tmp;
6648 	obj->jumptable_maps[cnt].prog = prog;
6649 	obj->jumptable_maps[cnt].sym_off = sym_off;
6650 	obj->jumptable_maps[cnt].fd = map_fd;
6651 	obj->jumptable_map_cnt++;
6652 
6653 	return 0;
6654 }
6655 
6656 static int find_subprog_idx(struct bpf_program *prog, int insn_idx)
6657 {
6658 	int i;
6659 
6660 	for (i = prog->subprog_cnt - 1; i >= 0; i--) {
6661 		if (insn_idx >= prog->subprogs[i].sub_insn_off)
6662 			return i;
6663 	}
6664 
6665 	return -1;
6666 }
6667 
6668 static int create_jt_map(struct bpf_object *obj, struct bpf_program *prog, struct reloc_desc *relo)
6669 {
6670 	const __u32 jt_entry_size = 8;
6671 	unsigned int sym_off = relo->sym_off;
6672 	int jt_size = relo->sym_size;
6673 	__u32 max_entries = jt_size / jt_entry_size;
6674 	__u32 value_size = sizeof(struct bpf_insn_array_value);
6675 	struct bpf_insn_array_value val = {};
6676 	int subprog_idx;
6677 	int map_fd, err;
6678 	__u64 insn_off;
6679 	__u64 *jt;
6680 	__u32 i;
6681 
6682 	map_fd = find_jt_map(obj, prog, sym_off);
6683 	if (map_fd >= 0)
6684 		return map_fd;
6685 
6686 	if (sym_off % jt_entry_size) {
6687 		pr_warn("map '.jumptables': jumptable start %u should be multiple of %u\n",
6688 			sym_off, jt_entry_size);
6689 		return -EINVAL;
6690 	}
6691 
6692 	if (jt_size % jt_entry_size) {
6693 		pr_warn("map '.jumptables': jumptable size %d should be multiple of %u\n",
6694 			jt_size, jt_entry_size);
6695 		return -EINVAL;
6696 	}
6697 
6698 	map_fd = bpf_map_create(BPF_MAP_TYPE_INSN_ARRAY, ".jumptables",
6699 				4, value_size, max_entries, NULL);
6700 	if (map_fd < 0)
6701 		return map_fd;
6702 
6703 	if (!obj->jumptables_data) {
6704 		pr_warn("map '.jumptables': ELF file is missing jump table data\n");
6705 		err = -EINVAL;
6706 		goto err_close;
6707 	}
6708 	if (sym_off + jt_size > obj->jumptables_data_sz) {
6709 		pr_warn("map '.jumptables': jumptables_data size is %zu, trying to access %u\n",
6710 			obj->jumptables_data_sz, sym_off + jt_size);
6711 		err = -EINVAL;
6712 		goto err_close;
6713 	}
6714 
6715 	subprog_idx = -1; /* main program */
6716 	if (relo->insn_idx < 0 || relo->insn_idx >= prog->insns_cnt) {
6717 		pr_warn("map '.jumptables': invalid instruction index %d\n", relo->insn_idx);
6718 		err = -EINVAL;
6719 		goto err_close;
6720 	}
6721 	if (prog->subprogs)
6722 		subprog_idx = find_subprog_idx(prog, relo->insn_idx);
6723 
6724 	jt = (__u64 *)(obj->jumptables_data + sym_off);
6725 	for (i = 0; i < max_entries; i++) {
6726 		/*
6727 		 * The offset should be made to be relative to the beginning of
6728 		 * the main function, not the subfunction.
6729 		 */
6730 		insn_off = jt[i]/sizeof(struct bpf_insn);
6731 		if (subprog_idx >= 0) {
6732 			insn_off -= prog->subprogs[subprog_idx].sec_insn_off;
6733 			insn_off += prog->subprogs[subprog_idx].sub_insn_off;
6734 		} else {
6735 			insn_off -= prog->sec_insn_off;
6736 		}
6737 
6738 		/*
6739 		 * LLVM-generated jump tables contain u64 records, however
6740 		 * should contain values that fit in u32.
6741 		 */
6742 		if (insn_off > UINT32_MAX) {
6743 			pr_warn("map '.jumptables': invalid jump table value 0x%llx at offset %u\n",
6744 				(unsigned long long)jt[i], sym_off + i * jt_entry_size);
6745 			err = -EINVAL;
6746 			goto err_close;
6747 		}
6748 
6749 		val.orig_off = insn_off;
6750 		err = bpf_map_update_elem(map_fd, &i, &val, 0);
6751 		if (err)
6752 			goto err_close;
6753 	}
6754 
6755 	err = bpf_map_freeze(map_fd);
6756 	if (err)
6757 		goto err_close;
6758 
6759 	err = add_jt_map(obj, prog, sym_off, map_fd);
6760 	if (err)
6761 		goto err_close;
6762 
6763 	return map_fd;
6764 
6765 err_close:
6766 	close(map_fd);
6767 	return err;
6768 }
6769 
6770 /*
6771  * The kernel recognizes a pointer to a function in a frozen read-only map by
6772  * its value: the offset in bytes of the function in the program. It makes
6773  * callx work for tables of functions, structures of operations and vtables,
6774  * where pointers are mixed with other data. Functions have different offsets
6775  * in different programs, so create a copy of the map for the program.
6776  * The kernel replaces the offsets with the addresses of the functions when it
6777  * loads the program, which has to be the only user of the map.
6778  */
6779 static int create_func_ptr_map(struct bpf_object *obj, struct bpf_program *prog, int map_idx)
6780 {
6781 	LIBBPF_OPTS(bpf_map_create_opts, opts, .map_flags = BPF_F_RDONLY_PROG);
6782 	struct bpf_map *map = &obj->maps[map_idx];
6783 	__u32 value_size = map->def.value_size;
6784 	size_t i, j, cnt, sec_insn_off;
6785 	struct func_ptr *ptrs;
6786 	int map_fd, err, zero = 0;
6787 	__u64 val;
6788 	void *data, *tmp;
6789 
6790 	for (i = 0; i < obj->func_ptr_map_cnt; i++)
6791 		if (obj->func_ptr_maps[i].prog == prog &&
6792 		    obj->func_ptr_maps[i].map_idx == map_idx)
6793 			return obj->func_ptr_maps[i].fd;
6794 
6795 	/* the map is not created yet, what it's going to have is in mmaped */
6796 	if (!map->mmaped)
6797 		return -EINVAL;
6798 
6799 	data = malloc(value_size);
6800 	if (!data)
6801 		return -ENOMEM;
6802 	memcpy(data, map->mmaped, value_size);
6803 
6804 	ptrs = map->func_ptrs;
6805 	cnt = map->func_ptr_cnt;
6806 	for (i = 0; i < cnt; i++) {
6807 		if (ptrs[i].sec_off + sizeof(val) > value_size) {
6808 			err = -LIBBPF_ERRNO__FORMAT;
6809 			goto err_free;
6810 		}
6811 		/*
6812 		 * Static functions were appended by bpf_object__append_func_ptrs_code().
6813 		 * A global function is in the program only if the code refers to it.
6814 		 */
6815 		sec_insn_off = ptrs[i].text_off / BPF_INSN_SZ;
6816 		for (j = 0; j < prog->subprog_cnt; j++)
6817 			if (prog->subprogs[j].sec_insn_off == sec_insn_off)
6818 				break;
6819 		if (j == prog->subprog_cnt) {
6820 			pr_debug("prog '%s': map '%s': no function for the pointer at offset %zu, it's NULL\n",
6821 				 prog->name, map->name, ptrs[i].sec_off);
6822 			val = 0;
6823 		} else {
6824 			val = (__u64)prog->subprogs[j].sub_insn_off * BPF_INSN_SZ;
6825 		}
6826 		/* light skeleton can be generated for a target of another endianness */
6827 		if (!is_native_endianness(obj))
6828 			val = bswap_64(val);
6829 		memcpy(data + ptrs[i].sec_off, &val, sizeof(val));
6830 	}
6831 
6832 	/*
6833 	 * The kernel takes any aligned 64-bit value that is equal to the offset
6834 	 * of a function for a pointer. Tell when it's going to get it wrong.
6835 	 */
6836 	for (i = 0, j = 0; i + sizeof(val) <= value_size; i += sizeof(val)) {
6837 		__u32 k;
6838 
6839 		while (j < cnt && ptrs[j].sec_off < i)
6840 			j++;
6841 		if (j < cnt && ptrs[j].sec_off == i)
6842 			continue;
6843 		memcpy(&val, data + i, sizeof(val));
6844 		if (!is_native_endianness(obj))
6845 			val = bswap_64(val);
6846 		if (!val || val % BPF_INSN_SZ)
6847 			continue;
6848 		for (k = 0; k < prog->subprog_cnt; k++) {
6849 			if ((__u64)prog->subprogs[k].sub_insn_off * BPF_INSN_SZ != val)
6850 				continue;
6851 			pr_warn("prog '%s': map '%s': value %llu at offset %zu is the offset of a function, the kernel will treat it as a pointer to it\n",
6852 				prog->name, map->name, (unsigned long long)val, i);
6853 			break;
6854 		}
6855 	}
6856 
6857 	if (obj->gen_loader) {
6858 		__u32 *ptr_offs = calloc(cnt, sizeof(*ptr_offs));
6859 		__u64 *ptr_vals = calloc(cnt, sizeof(*ptr_vals));
6860 
6861 		if (!ptr_offs || !ptr_vals) {
6862 			free(ptr_offs);
6863 			free(ptr_vals);
6864 			err = -ENOMEM;
6865 			goto err_free;
6866 		}
6867 		for (i = 0; i < cnt; i++) {
6868 			ptr_offs[i] = ptrs[i].sec_off;
6869 			memcpy(&ptr_vals[i], data + ptrs[i].sec_off, sizeof(val));
6870 			if (!is_native_endianness(obj))
6871 				ptr_vals[i] = bswap_64(ptr_vals[i]);
6872 		}
6873 		/* it's an index in fd_array of the loader, not an fd */
6874 		map_fd = bpf_gen__func_ptr_map_create(obj->gen_loader, map->name, map_idx, data,
6875 						      value_size, ptr_offs, ptr_vals, cnt);
6876 		free(ptr_offs);
6877 		free(ptr_vals);
6878 		goto done;
6879 	}
6880 
6881 	opts.token_fd = obj->token_fd;
6882 	if (obj->token_fd)
6883 		opts.map_flags |= BPF_F_TOKEN_FD;
6884 
6885 	map_fd = bpf_map_create(BPF_MAP_TYPE_ARRAY, map->name, sizeof(int), value_size, 1, &opts);
6886 	if (map_fd < 0) {
6887 		err = map_fd;
6888 		goto err_free;
6889 	}
6890 
6891 	err = bpf_map_update_elem(map_fd, &zero, data, 0);
6892 	if (!err)
6893 		err = bpf_map_freeze(map_fd);
6894 	if (err) {
6895 		err = -errno;
6896 		goto err_close;
6897 	}
6898 done:
6899 
6900 	tmp = libbpf_reallocarray(obj->func_ptr_maps, obj->func_ptr_map_cnt + 1,
6901 				  sizeof(*obj->func_ptr_maps));
6902 	if (!tmp) {
6903 		err = -ENOMEM;
6904 		goto err_close;
6905 	}
6906 	obj->func_ptr_maps = tmp;
6907 	obj->func_ptr_maps[obj->func_ptr_map_cnt].prog = prog;
6908 	obj->func_ptr_maps[obj->func_ptr_map_cnt].map_idx = map_idx;
6909 	obj->func_ptr_maps[obj->func_ptr_map_cnt].fd = map_fd;
6910 	obj->func_ptr_map_cnt++;
6911 
6912 	pr_debug("prog '%s': created a copy of map '%s' with %zu pointers to functions\n",
6913 		 prog->name, map->name, cnt);
6914 	free(data);
6915 	return map_fd;
6916 
6917 err_close:
6918 	if (!obj->gen_loader)
6919 		close(map_fd);
6920 err_free:
6921 	free(data);
6922 	return err;
6923 }
6924 
6925 /* Relocate data references within program code:
6926  *  - map references;
6927  *  - global variable references;
6928  *  - extern references.
6929  */
6930 static int
6931 bpf_object__relocate_data(struct bpf_object *obj, struct bpf_program *prog)
6932 {
6933 	int i;
6934 
6935 	for (i = 0; i < prog->nr_reloc; i++) {
6936 		struct reloc_desc *relo = &prog->reloc_desc[i];
6937 		struct bpf_insn *insn = &prog->insns[relo->insn_idx];
6938 		const struct bpf_map *map;
6939 		struct extern_desc *ext;
6940 
6941 		switch (relo->type) {
6942 		case RELO_LD64:
6943 			map = &obj->maps[relo->map_idx];
6944 			if (obj->gen_loader) {
6945 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX;
6946 				insn[0].imm = relo->map_idx;
6947 			} else if (map->autocreate) {
6948 				insn[0].src_reg = BPF_PSEUDO_MAP_FD;
6949 				insn[0].imm = map->fd;
6950 			} else {
6951 				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
6952 						   relo->map_idx, map);
6953 			}
6954 			break;
6955 		case RELO_DATA:
6956 			map = &obj->maps[relo->map_idx];
6957 			insn[1].imm = insn[0].imm + relo->sym_off;
6958 
6959 			if (relo->map_idx == obj->arena_map_idx)
6960 				insn[1].imm += obj->arena_data_off;
6961 
6962 			if (map->autocreate && map->func_ptr_cnt && prog->has_callx) {
6963 				int map_fd;
6964 
6965 				/* the program gets its own map with pointers to its functions */
6966 				map_fd = create_func_ptr_map(obj, prog, relo->map_idx);
6967 				if (map_fd < 0) {
6968 					pr_warn("prog '%s': relo #%d: can't create a copy of map '%s' with pointers to functions\n",
6969 						prog->name, i, map->name);
6970 					return map_fd;
6971 				}
6972 				insn[0].src_reg = obj->gen_loader ? BPF_PSEUDO_MAP_IDX_VALUE :
6973 								    BPF_PSEUDO_MAP_VALUE;
6974 				insn[0].imm = map_fd;
6975 			} else if (obj->gen_loader) {
6976 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
6977 				insn[0].imm = relo->map_idx;
6978 			} else if (map->autocreate) {
6979 				insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6980 				insn[0].imm = map->fd;
6981 			} else {
6982 				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
6983 						   relo->map_idx, map);
6984 			}
6985 			break;
6986 		case RELO_EXTERN_LD64:
6987 			ext = &obj->externs[relo->ext_idx];
6988 			if (ext->type == EXT_KCFG) {
6989 				if (obj->gen_loader) {
6990 					insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
6991 					insn[0].imm = obj->kconfig_map_idx;
6992 				} else {
6993 					insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6994 					insn[0].imm = obj->maps[obj->kconfig_map_idx].fd;
6995 				}
6996 				insn[1].imm = ext->kcfg.data_off;
6997 			} else /* EXT_KSYM */ {
6998 				if (ext->ksym.type_id && ext->is_set) { /* typed ksyms */
6999 					insn[0].src_reg = BPF_PSEUDO_BTF_ID;
7000 					insn[0].imm = ext->ksym.kernel_btf_id;
7001 					insn[1].imm = ext->ksym.kernel_btf_obj_fd;
7002 				} else { /* typeless ksyms or unresolved typed ksyms */
7003 					insn[0].imm = (__u32)ext->ksym.addr;
7004 					insn[1].imm = ext->ksym.addr >> 32;
7005 				}
7006 			}
7007 			break;
7008 		case RELO_EXTERN_CALL:
7009 			ext = &obj->externs[relo->ext_idx];
7010 			insn[0].src_reg = BPF_PSEUDO_KFUNC_CALL;
7011 			if (ext->is_set) {
7012 				insn[0].imm = ext->ksym.kernel_btf_id;
7013 				insn[0].off = ext->ksym.btf_fd_idx;
7014 			} else { /* unresolved weak kfunc call */
7015 				poison_kfunc_call(prog, i, relo->insn_idx, insn,
7016 						  relo->ext_idx, ext);
7017 			}
7018 			break;
7019 		case RELO_SUBPROG_ADDR:
7020 			if (insn[0].src_reg != BPF_PSEUDO_FUNC) {
7021 				pr_warn("prog '%s': relo #%d: bad insn\n",
7022 					prog->name, i);
7023 				return -EINVAL;
7024 			}
7025 			/* handled already */
7026 			break;
7027 		case RELO_CALL:
7028 			/* handled already */
7029 			break;
7030 		case RELO_CORE:
7031 			/* will be handled by bpf_program_record_relos() */
7032 			break;
7033 		case RELO_INSN_ARRAY: {
7034 			int map_fd;
7035 
7036 			map_fd = create_jt_map(obj, prog, relo);
7037 			if (map_fd < 0) {
7038 				pr_warn("prog '%s': relo #%d: can't create jump table: sym_off %u\n",
7039 					prog->name, i, relo->sym_off);
7040 				return map_fd;
7041 			}
7042 			insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
7043 			insn->imm = map_fd;
7044 			insn->off = 0;
7045 		}
7046 			break;
7047 		default:
7048 			pr_warn("prog '%s': relo #%d: bad relo type %u\n",
7049 				prog->name, i, relo->type);
7050 			return -EINVAL;
7051 		}
7052 	}
7053 
7054 	return 0;
7055 }
7056 
7057 static int adjust_prog_btf_ext_info(const struct bpf_object *obj,
7058 				    const struct bpf_program *prog,
7059 				    const struct btf_ext_info *ext_info,
7060 				    void **prog_info, __u32 *prog_rec_cnt,
7061 				    __u32 *prog_rec_sz)
7062 {
7063 	void *copy_start = NULL, *copy_end = NULL;
7064 	void *rec, *rec_end, *new_prog_info;
7065 	const struct btf_ext_info_sec *sec;
7066 	size_t old_sz, new_sz;
7067 	int i, sec_num, sec_idx, off_adj;
7068 
7069 	sec_num = 0;
7070 	for_each_btf_ext_sec(ext_info, sec) {
7071 		sec_idx = ext_info->sec_idxs[sec_num];
7072 		sec_num++;
7073 		if (prog->sec_idx != sec_idx)
7074 			continue;
7075 
7076 		for_each_btf_ext_rec(ext_info, sec, i, rec) {
7077 			__u32 insn_off = *(__u32 *)rec / BPF_INSN_SZ;
7078 
7079 			if (insn_off < prog->sec_insn_off)
7080 				continue;
7081 			if (insn_off >= prog->sec_insn_off + prog->sec_insn_cnt)
7082 				break;
7083 
7084 			if (!copy_start)
7085 				copy_start = rec;
7086 			copy_end = rec + ext_info->rec_size;
7087 		}
7088 
7089 		if (!copy_start)
7090 			return -ENOENT;
7091 
7092 		/* append func/line info of a given (sub-)program to the main
7093 		 * program func/line info
7094 		 */
7095 		old_sz = (size_t)(*prog_rec_cnt) * ext_info->rec_size;
7096 		new_sz = old_sz + (copy_end - copy_start);
7097 		new_prog_info = realloc(*prog_info, new_sz);
7098 		if (!new_prog_info)
7099 			return -ENOMEM;
7100 		*prog_info = new_prog_info;
7101 		*prog_rec_cnt = new_sz / ext_info->rec_size;
7102 		memcpy(new_prog_info + old_sz, copy_start, copy_end - copy_start);
7103 
7104 		/* Kernel instruction offsets are in units of 8-byte
7105 		 * instructions, while .BTF.ext instruction offsets generated
7106 		 * by Clang are in units of bytes. So convert Clang offsets
7107 		 * into kernel offsets and adjust offset according to program
7108 		 * relocated position.
7109 		 */
7110 		off_adj = prog->sub_insn_off - prog->sec_insn_off;
7111 		rec = new_prog_info + old_sz;
7112 		rec_end = new_prog_info + new_sz;
7113 		for (; rec < rec_end; rec += ext_info->rec_size) {
7114 			__u32 *insn_off = rec;
7115 
7116 			*insn_off = *insn_off / BPF_INSN_SZ + off_adj;
7117 		}
7118 		*prog_rec_sz = ext_info->rec_size;
7119 		return 0;
7120 	}
7121 
7122 	return -ENOENT;
7123 }
7124 
7125 static int
7126 reloc_prog_func_and_line_info(const struct bpf_object *obj,
7127 			      struct bpf_program *main_prog,
7128 			      const struct bpf_program *prog)
7129 {
7130 	int err;
7131 
7132 	/* no .BTF.ext relocation if .BTF.ext is missing or kernel doesn't
7133 	 * support func/line info
7134 	 */
7135 	if (!obj->btf_ext || !kernel_supports(obj, FEAT_BTF_FUNC))
7136 		return 0;
7137 
7138 	/* only attempt func info relocation if main program's func_info
7139 	 * relocation was successful
7140 	 */
7141 	if (main_prog != prog && !main_prog->func_info)
7142 		goto line_info;
7143 
7144 	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->func_info,
7145 				       &main_prog->func_info,
7146 				       &main_prog->func_info_cnt,
7147 				       &main_prog->func_info_rec_size);
7148 	if (err) {
7149 		if (err != -ENOENT) {
7150 			pr_warn("prog '%s': error relocating .BTF.ext function info: %s\n",
7151 				prog->name, errstr(err));
7152 			return err;
7153 		}
7154 		if (main_prog->func_info) {
7155 			/*
7156 			 * Some info has already been found but has problem
7157 			 * in the last btf_ext reloc. Must have to error out.
7158 			 */
7159 			pr_warn("prog '%s': missing .BTF.ext function info.\n", prog->name);
7160 			return err;
7161 		}
7162 		/* Have problem loading the very first info. Ignore the rest. */
7163 		pr_warn("prog '%s': missing .BTF.ext function info for the main program, skipping all of .BTF.ext func info.\n",
7164 			prog->name);
7165 	}
7166 
7167 line_info:
7168 	/* don't relocate line info if main program's relocation failed */
7169 	if (main_prog != prog && !main_prog->line_info)
7170 		return 0;
7171 
7172 	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->line_info,
7173 				       &main_prog->line_info,
7174 				       &main_prog->line_info_cnt,
7175 				       &main_prog->line_info_rec_size);
7176 	if (err) {
7177 		if (err != -ENOENT) {
7178 			pr_warn("prog '%s': error relocating .BTF.ext line info: %s\n",
7179 				prog->name, errstr(err));
7180 			return err;
7181 		}
7182 		if (main_prog->line_info) {
7183 			/*
7184 			 * Some info has already been found but has problem
7185 			 * in the last btf_ext reloc. Must have to error out.
7186 			 */
7187 			pr_warn("prog '%s': missing .BTF.ext line info.\n", prog->name);
7188 			return err;
7189 		}
7190 		/* Have problem loading the very first info. Ignore the rest. */
7191 		pr_warn("prog '%s': missing .BTF.ext line info for the main program, skipping all of .BTF.ext line info.\n",
7192 			prog->name);
7193 	}
7194 	return 0;
7195 }
7196 
7197 static int cmp_relo_by_insn_idx(const void *key, const void *elem)
7198 {
7199 	size_t insn_idx = *(const size_t *)key;
7200 	const struct reloc_desc *relo = elem;
7201 
7202 	if (insn_idx == relo->insn_idx)
7203 		return 0;
7204 	return insn_idx < relo->insn_idx ? -1 : 1;
7205 }
7206 
7207 static struct reloc_desc *find_prog_insn_relo(const struct bpf_program *prog, size_t insn_idx)
7208 {
7209 	if (!prog->nr_reloc)
7210 		return NULL;
7211 	return bsearch(&insn_idx, prog->reloc_desc, prog->nr_reloc,
7212 		       sizeof(*prog->reloc_desc), cmp_relo_by_insn_idx);
7213 }
7214 
7215 static int append_subprog_relos(struct bpf_program *main_prog, struct bpf_program *subprog)
7216 {
7217 	int new_cnt = main_prog->nr_reloc + subprog->nr_reloc;
7218 	struct reloc_desc *relos;
7219 	int i;
7220 
7221 	if (main_prog == subprog)
7222 		return 0;
7223 	relos = libbpf_reallocarray(main_prog->reloc_desc, new_cnt, sizeof(*relos));
7224 	/* if new count is zero, reallocarray can return a valid NULL result;
7225 	 * in this case the previous pointer will be freed, so we *have to*
7226 	 * reassign old pointer to the new value (even if it's NULL)
7227 	 */
7228 	if (!relos && new_cnt)
7229 		return -ENOMEM;
7230 	if (subprog->nr_reloc)
7231 		memcpy(relos + main_prog->nr_reloc, subprog->reloc_desc,
7232 		       sizeof(*relos) * subprog->nr_reloc);
7233 
7234 	for (i = main_prog->nr_reloc; i < new_cnt; i++)
7235 		relos[i].insn_idx += subprog->sub_insn_off;
7236 	/* After insn_idx adjustment the 'relos' array is still sorted
7237 	 * by insn_idx and doesn't break bsearch.
7238 	 */
7239 	main_prog->reloc_desc = relos;
7240 	main_prog->nr_reloc = new_cnt;
7241 	return 0;
7242 }
7243 
7244 static int save_subprog_offsets(struct bpf_program *main_prog, struct bpf_program *subprog)
7245 {
7246 	size_t size = sizeof(main_prog->subprogs[0]);
7247 	int cnt = main_prog->subprog_cnt;
7248 	void *tmp;
7249 
7250 	tmp = libbpf_reallocarray(main_prog->subprogs, cnt + 1, size);
7251 	if (!tmp)
7252 		return -ENOMEM;
7253 
7254 	main_prog->subprogs = tmp;
7255 	main_prog->subprogs[cnt].sec_insn_off = subprog->sec_insn_off;
7256 	main_prog->subprogs[cnt].sub_insn_off = subprog->sub_insn_off;
7257 	main_prog->subprog_cnt++;
7258 
7259 	return 0;
7260 }
7261 
7262 static int
7263 bpf_object__append_subprog_code(struct bpf_object *obj, struct bpf_program *main_prog,
7264 				struct bpf_program *subprog)
7265 {
7266 	struct bpf_insn *insns;
7267 	size_t new_cnt;
7268 	int err;
7269 
7270 	subprog->sub_insn_off = main_prog->insns_cnt;
7271 
7272 	new_cnt = main_prog->insns_cnt + subprog->insns_cnt;
7273 	insns = libbpf_reallocarray(main_prog->insns, new_cnt, sizeof(*insns));
7274 	if (!insns) {
7275 		pr_warn("prog '%s': failed to realloc prog code\n", main_prog->name);
7276 		return -ENOMEM;
7277 	}
7278 	main_prog->insns = insns;
7279 	main_prog->insns_cnt = new_cnt;
7280 
7281 	memcpy(main_prog->insns + subprog->sub_insn_off, subprog->insns,
7282 	       subprog->insns_cnt * sizeof(*insns));
7283 
7284 	pr_debug("prog '%s': added %zu insns from sub-prog '%s'\n",
7285 		 main_prog->name, subprog->insns_cnt, subprog->name);
7286 
7287 	/* The subprog insns are now appended. Append its relos too. */
7288 	err = append_subprog_relos(main_prog, subprog);
7289 	if (err)
7290 		return err;
7291 
7292 	err = save_subprog_offsets(main_prog, subprog);
7293 	if (err) {
7294 		pr_warn("prog '%s': failed to add subprog offsets: %s\n",
7295 			main_prog->name, errstr(err));
7296 		return err;
7297 	}
7298 
7299 	return 0;
7300 }
7301 
7302 static int
7303 bpf_object__reloc_code(struct bpf_object *obj, struct bpf_program *main_prog,
7304 		       struct bpf_program *prog)
7305 {
7306 	size_t sub_insn_idx, insn_idx;
7307 	struct bpf_program *subprog;
7308 	struct reloc_desc *relo;
7309 	struct bpf_insn *insn;
7310 	int err;
7311 
7312 	err = reloc_prog_func_and_line_info(obj, main_prog, prog);
7313 	if (err)
7314 		return err;
7315 
7316 	for (insn_idx = 0; insn_idx < prog->sec_insn_cnt; insn_idx++) {
7317 		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
7318 		if (!insn_is_subprog_call(insn) && !insn_is_pseudo_func(insn))
7319 			continue;
7320 
7321 		relo = find_prog_insn_relo(prog, insn_idx);
7322 		if (relo && relo->type == RELO_EXTERN_CALL)
7323 			/* kfunc relocations will be handled later
7324 			 * in bpf_object__relocate_data()
7325 			 */
7326 			continue;
7327 		if (relo && relo->type != RELO_CALL && relo->type != RELO_SUBPROG_ADDR) {
7328 			pr_warn("prog '%s': unexpected relo for insn #%zu, type %u\n",
7329 				prog->name, insn_idx, relo->type);
7330 			return -LIBBPF_ERRNO__RELOC;
7331 		}
7332 		if (relo) {
7333 			/* sub-program instruction index is a combination of
7334 			 * an offset of a symbol pointed to by relocation and
7335 			 * call instruction's imm field; for global functions,
7336 			 * call always has imm = -1, but for static functions
7337 			 * relocation is against STT_SECTION and insn->imm
7338 			 * points to a start of a static function
7339 			 *
7340 			 * for subprog addr relocation, the relo->sym_off + insn->imm is
7341 			 * the byte offset in the corresponding section.
7342 			 */
7343 			if (relo->type == RELO_CALL)
7344 				sub_insn_idx = relo->sym_off / BPF_INSN_SZ + insn->imm + 1;
7345 			else
7346 				sub_insn_idx = (relo->sym_off + insn->imm) / BPF_INSN_SZ;
7347 		} else if (insn_is_pseudo_func(insn)) {
7348 			/*
7349 			 * RELO_SUBPROG_ADDR relo is always emitted even if both
7350 			 * functions are in the same section, so it shouldn't reach here.
7351 			 */
7352 			pr_warn("prog '%s': missing subprog addr relo for insn #%zu\n",
7353 				prog->name, insn_idx);
7354 			return -LIBBPF_ERRNO__RELOC;
7355 		} else {
7356 			/* if subprogram call is to a static function within
7357 			 * the same ELF section, there won't be any relocation
7358 			 * emitted, but it also means there is no additional
7359 			 * offset necessary, insns->imm is relative to
7360 			 * instruction's original position within the section
7361 			 */
7362 			sub_insn_idx = prog->sec_insn_off + insn_idx + insn->imm + 1;
7363 		}
7364 
7365 		/* we enforce that sub-programs should be in .text section */
7366 		subprog = find_prog_by_sec_insn(obj, obj->efile.text_shndx, sub_insn_idx);
7367 		if (!subprog) {
7368 			pr_warn("prog '%s': no .text section found yet sub-program call exists\n",
7369 				prog->name);
7370 			return -LIBBPF_ERRNO__RELOC;
7371 		}
7372 
7373 		/* if it's the first call instruction calling into this
7374 		 * subprogram (meaning this subprog hasn't been processed
7375 		 * yet) within the context of current main program:
7376 		 *   - append it at the end of main program's instructions blog;
7377 		 *   - process is recursively, while current program is put on hold;
7378 		 *   - if that subprogram calls some other not yet processes
7379 		 *   subprogram, same thing will happen recursively until
7380 		 *   there are no more unprocesses subprograms left to append
7381 		 *   and relocate.
7382 		 */
7383 		if (subprog->sub_insn_off == 0) {
7384 			err = bpf_object__append_subprog_code(obj, main_prog, subprog);
7385 			if (err)
7386 				return err;
7387 			err = bpf_object__reloc_code(obj, main_prog, subprog);
7388 			if (err)
7389 				return err;
7390 		}
7391 
7392 		/* main_prog->insns memory could have been re-allocated, so
7393 		 * calculate pointer again
7394 		 */
7395 		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
7396 		/* calculate correct instruction position within current main
7397 		 * prog; each main prog can have a different set of
7398 		 * subprograms appended (potentially in different order as
7399 		 * well), so position of any subprog can be different for
7400 		 * different main programs
7401 		 */
7402 		insn->imm = subprog->sub_insn_off - (prog->sub_insn_off + insn_idx) - 1;
7403 
7404 		pr_debug("prog '%s': insn #%zu relocated, imm %d points to subprog '%s' (now at %zu offset)\n",
7405 			 prog->name, insn_idx, insn->imm, subprog->name, subprog->sub_insn_off);
7406 	}
7407 
7408 	return 0;
7409 }
7410 
7411 /* Append to the main program all functions that the data of the map points to */
7412 static int
7413 bpf_object__append_func_ptrs_code(struct bpf_object *obj, struct bpf_program *main_prog,
7414 				  const struct bpf_map *map)
7415 {
7416 	struct bpf_program *subprog;
7417 	size_t i, cnt, sec_insn_off;
7418 	struct func_ptr *ptrs;
7419 	int err;
7420 
7421 	ptrs = map->func_ptrs;
7422 	cnt = map->func_ptr_cnt;
7423 	for (i = 0; i < cnt; i++) {
7424 		sec_insn_off = ptrs[i].text_off / BPF_INSN_SZ;
7425 		subprog = find_prog_by_sec_insn(obj, obj->efile.text_shndx, sec_insn_off);
7426 		if (!subprog || subprog->sec_insn_off != sec_insn_off) {
7427 			pr_warn("prog '%s': map '%s': no function at .text+%zu for the pointer at offset %zu\n",
7428 				main_prog->name, map->name, ptrs[i].text_off, ptrs[i].sec_off);
7429 			return -LIBBPF_ERRNO__RELOC;
7430 		}
7431 
7432 		/*
7433 		 * callx can't call global functions. Don't add one to the
7434 		 * program only because the data points to it.
7435 		 */
7436 		if (subprog->sym_global)
7437 			continue;
7438 
7439 		/* see the comment in bpf_object__reloc_code() */
7440 		if (subprog->sub_insn_off == 0) {
7441 			err = bpf_object__append_subprog_code(obj, main_prog, subprog);
7442 			if (err)
7443 				return err;
7444 			err = bpf_object__reloc_code(obj, main_prog, subprog);
7445 			if (err)
7446 				return err;
7447 		}
7448 	}
7449 	return 0;
7450 }
7451 
7452 /*
7453  * The program that has callx might call any function that the data it refers
7454  * to points to. Append them. Programs that don't have callx can't call them
7455  * and the kernel doesn't look for pointers to functions in their data.
7456  */
7457 static int
7458 bpf_object__append_func_ptrs(struct bpf_object *obj, struct bpf_program *prog)
7459 {
7460 	size_t i;
7461 	int err;
7462 
7463 	prog->has_callx = prog_has_callx(prog);
7464 	if (!prog->has_callx)
7465 		return 0;
7466 
7467 	/* relocations of the functions that are appended are appended too */
7468 	for (i = 0; i < prog->nr_reloc; i++) {
7469 		struct reloc_desc *relo = &prog->reloc_desc[i];
7470 
7471 		if (relo->type != RELO_DATA || !obj->maps[relo->map_idx].func_ptr_cnt)
7472 			continue;
7473 		err = bpf_object__append_func_ptrs_code(obj, prog, &obj->maps[relo->map_idx]);
7474 		if (err)
7475 			return err;
7476 	}
7477 	return 0;
7478 }
7479 
7480 /*
7481  * Relocate sub-program calls.
7482  *
7483  * Algorithm operates as follows. Each entry-point BPF program (referred to as
7484  * main prog) is processed separately. For each subprog (non-entry functions,
7485  * that can be called from either entry progs or other subprogs) gets their
7486  * sub_insn_off reset to zero. This serves as indicator that this subprogram
7487  * hasn't been yet appended and relocated within current main prog. Once its
7488  * relocated, sub_insn_off will point at the position within current main prog
7489  * where given subprog was appended. This will further be used to relocate all
7490  * the call instructions jumping into this subprog.
7491  *
7492  * We start with main program and process all call instructions. If the call
7493  * is into a subprog that hasn't been processed (i.e., subprog->sub_insn_off
7494  * is zero), subprog instructions are appended at the end of main program's
7495  * instruction array. Then main program is "put on hold" while we recursively
7496  * process newly appended subprogram. If that subprogram calls into another
7497  * subprogram that hasn't been appended, new subprogram is appended again to
7498  * the *main* prog's instructions (subprog's instructions are always left
7499  * untouched, as they need to be in unmodified state for subsequent main progs
7500  * and subprog instructions are always sent only as part of a main prog) and
7501  * the process continues recursively. Once all the subprogs called from a main
7502  * prog or any of its subprogs are appended (and relocated), all their
7503  * positions within finalized instructions array are known, so it's easy to
7504  * rewrite call instructions with correct relative offsets, corresponding to
7505  * desired target subprog.
7506  *
7507  * Its important to realize that some subprogs might not be called from some
7508  * main prog and any of its called/used subprogs. Those will keep their
7509  * subprog->sub_insn_off as zero at all times and won't be appended to current
7510  * main prog and won't be relocated within the context of current main prog.
7511  * They might still be used from other main progs later.
7512  *
7513  * Visually this process can be shown as below. Suppose we have two main
7514  * programs mainA and mainB and BPF object contains three subprogs: subA,
7515  * subB, and subC. mainA calls only subA, mainB calls only subC, but subA and
7516  * subC both call subB:
7517  *
7518  *        +--------+ +-------+
7519  *        |        v v       |
7520  *     +--+---+ +--+-+-+ +---+--+
7521  *     | subA | | subB | | subC |
7522  *     +--+---+ +------+ +---+--+
7523  *        ^                  ^
7524  *        |                  |
7525  *    +---+-------+   +------+----+
7526  *    |   mainA   |   |   mainB   |
7527  *    +-----------+   +-----------+
7528  *
7529  * We'll start relocating mainA, will find subA, append it and start
7530  * processing sub A recursively:
7531  *
7532  *    +-----------+------+
7533  *    |   mainA   | subA |
7534  *    +-----------+------+
7535  *
7536  * At this point we notice that subB is used from subA, so we append it and
7537  * relocate (there are no further subcalls from subB):
7538  *
7539  *    +-----------+------+------+
7540  *    |   mainA   | subA | subB |
7541  *    +-----------+------+------+
7542  *
7543  * At this point, we relocate subA calls, then go one level up and finish with
7544  * relocation mainA calls. mainA is done.
7545  *
7546  * For mainB process is similar but results in different order. We start with
7547  * mainB and skip subA and subB, as mainB never calls them (at least
7548  * directly), but we see subC is needed, so we append and start processing it:
7549  *
7550  *    +-----------+------+
7551  *    |   mainB   | subC |
7552  *    +-----------+------+
7553  * Now we see subC needs subB, so we go back to it, append and relocate it:
7554  *
7555  *    +-----------+------+------+
7556  *    |   mainB   | subC | subB |
7557  *    +-----------+------+------+
7558  *
7559  * At this point we unwind recursion, relocate calls in subC, then in mainB.
7560  */
7561 static int
7562 bpf_object__relocate_calls(struct bpf_object *obj, struct bpf_program *prog)
7563 {
7564 	struct bpf_program *subprog;
7565 	int i, err;
7566 
7567 	/* mark all subprogs as not relocated (yet) within the context of
7568 	 * current main program
7569 	 */
7570 	for (i = 0; i < obj->nr_programs; i++) {
7571 		subprog = &obj->programs[i];
7572 		if (!prog_is_subprog(obj, subprog))
7573 			continue;
7574 
7575 		subprog->sub_insn_off = 0;
7576 	}
7577 
7578 	err = bpf_object__reloc_code(obj, prog, prog);
7579 	if (err)
7580 		return err;
7581 
7582 	return bpf_object__append_func_ptrs(obj, prog);
7583 }
7584 
7585 static void
7586 bpf_object__free_relocs(struct bpf_object *obj)
7587 {
7588 	struct bpf_program *prog;
7589 	int i;
7590 
7591 	/* free up relocation descriptors */
7592 	for (i = 0; i < obj->nr_programs; i++) {
7593 		prog = &obj->programs[i];
7594 		zfree(&prog->reloc_desc);
7595 		prog->nr_reloc = 0;
7596 	}
7597 }
7598 
7599 static int cmp_relocs(const void *_a, const void *_b)
7600 {
7601 	const struct reloc_desc *a = _a;
7602 	const struct reloc_desc *b = _b;
7603 
7604 	if (a->insn_idx != b->insn_idx)
7605 		return a->insn_idx < b->insn_idx ? -1 : 1;
7606 
7607 	/* no two relocations should have the same insn_idx, but ... */
7608 	if (a->type != b->type)
7609 		return a->type < b->type ? -1 : 1;
7610 
7611 	return 0;
7612 }
7613 
7614 static void bpf_object__sort_relos(struct bpf_object *obj)
7615 {
7616 	int i;
7617 
7618 	for (i = 0; i < obj->nr_programs; i++) {
7619 		struct bpf_program *p = &obj->programs[i];
7620 
7621 		if (!p->nr_reloc)
7622 			continue;
7623 
7624 		qsort(p->reloc_desc, p->nr_reloc, sizeof(*p->reloc_desc), cmp_relocs);
7625 	}
7626 }
7627 
7628 static int bpf_prog_assign_exc_cb(struct bpf_object *obj, struct bpf_program *prog)
7629 {
7630 	const char *str = "exception_callback:";
7631 	size_t pfx_len = strlen(str);
7632 	int i, j, n;
7633 
7634 	if (!obj->btf || !kernel_supports(obj, FEAT_BTF_DECL_TAG))
7635 		return 0;
7636 
7637 	n = btf__type_cnt(obj->btf);
7638 	for (i = 1; i < n; i++) {
7639 		const char *name;
7640 		struct btf_type *t;
7641 
7642 		t = btf_type_by_id(obj->btf, i);
7643 		if (!btf_is_decl_tag(t) || btf_decl_tag(t)->component_idx != -1)
7644 			continue;
7645 
7646 		name = btf__str_by_offset(obj->btf, t->name_off);
7647 		if (strncmp(name, str, pfx_len) != 0)
7648 			continue;
7649 
7650 		t = btf_type_by_id(obj->btf, t->type);
7651 		if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL) {
7652 			pr_warn("prog '%s': exception_callback:<value> decl tag not applied to the main program\n",
7653 				prog->name);
7654 			return -EINVAL;
7655 		}
7656 		if (strcmp(prog->name, btf__str_by_offset(obj->btf, t->name_off)) != 0)
7657 			continue;
7658 		/* Multiple callbacks are specified for the same prog,
7659 		 * the verifier will eventually return an error for this
7660 		 * case, hence simply skip appending a subprog.
7661 		 */
7662 		if (prog->exception_cb_idx >= 0) {
7663 			prog->exception_cb_idx = -1;
7664 			break;
7665 		}
7666 
7667 		name += pfx_len;
7668 		if (str_is_empty(name)) {
7669 			pr_warn("prog '%s': exception_callback:<value> decl tag contains empty value\n",
7670 				prog->name);
7671 			return -EINVAL;
7672 		}
7673 
7674 		for (j = 0; j < obj->nr_programs; j++) {
7675 			struct bpf_program *subprog = &obj->programs[j];
7676 
7677 			if (!prog_is_subprog(obj, subprog))
7678 				continue;
7679 			if (strcmp(name, subprog->name) != 0)
7680 				continue;
7681 			/* Enforce non-hidden, as from verifier point of
7682 			 * view it expects global functions, whereas the
7683 			 * mark_btf_static fixes up linkage as static.
7684 			 */
7685 			if (!subprog->sym_global || subprog->mark_btf_static) {
7686 				pr_warn("prog '%s': exception callback %s must be a global non-hidden function\n",
7687 					prog->name, subprog->name);
7688 				return -EINVAL;
7689 			}
7690 			/* Let's see if we already saw a static exception callback with the same name */
7691 			if (prog->exception_cb_idx >= 0) {
7692 				pr_warn("prog '%s': multiple subprogs with same name as exception callback '%s'\n",
7693 					prog->name, subprog->name);
7694 				return -EINVAL;
7695 			}
7696 			prog->exception_cb_idx = j;
7697 			break;
7698 		}
7699 
7700 		if (prog->exception_cb_idx >= 0)
7701 			continue;
7702 
7703 		pr_warn("prog '%s': cannot find exception callback '%s'\n", prog->name, name);
7704 		return -ENOENT;
7705 	}
7706 
7707 	return 0;
7708 }
7709 
7710 static struct {
7711 	enum bpf_prog_type prog_type;
7712 	const char *ctx_name;
7713 } global_ctx_map[] = {
7714 	{ BPF_PROG_TYPE_CGROUP_DEVICE,           "bpf_cgroup_dev_ctx" },
7715 	{ BPF_PROG_TYPE_CGROUP_SKB,              "__sk_buff" },
7716 	{ BPF_PROG_TYPE_CGROUP_SOCK,             "bpf_sock" },
7717 	{ BPF_PROG_TYPE_CGROUP_SOCK_ADDR,        "bpf_sock_addr" },
7718 	{ BPF_PROG_TYPE_CGROUP_SOCKOPT,          "bpf_sockopt" },
7719 	{ BPF_PROG_TYPE_CGROUP_SYSCTL,           "bpf_sysctl" },
7720 	{ BPF_PROG_TYPE_FLOW_DISSECTOR,          "__sk_buff" },
7721 	{ BPF_PROG_TYPE_KPROBE,                  "bpf_user_pt_regs_t" },
7722 	{ BPF_PROG_TYPE_LWT_IN,                  "__sk_buff" },
7723 	{ BPF_PROG_TYPE_LWT_OUT,                 "__sk_buff" },
7724 	{ BPF_PROG_TYPE_LWT_SEG6LOCAL,           "__sk_buff" },
7725 	{ BPF_PROG_TYPE_LWT_XMIT,                "__sk_buff" },
7726 	{ BPF_PROG_TYPE_NETFILTER,               "bpf_nf_ctx" },
7727 	{ BPF_PROG_TYPE_PERF_EVENT,              "bpf_perf_event_data" },
7728 	{ BPF_PROG_TYPE_RAW_TRACEPOINT,          "bpf_raw_tracepoint_args" },
7729 	{ BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE, "bpf_raw_tracepoint_args" },
7730 	{ BPF_PROG_TYPE_SCHED_ACT,               "__sk_buff" },
7731 	{ BPF_PROG_TYPE_SCHED_CLS,               "__sk_buff" },
7732 	{ BPF_PROG_TYPE_SK_LOOKUP,               "bpf_sk_lookup" },
7733 	{ BPF_PROG_TYPE_SK_MSG,                  "sk_msg_md" },
7734 	{ BPF_PROG_TYPE_SK_REUSEPORT,            "sk_reuseport_md" },
7735 	{ BPF_PROG_TYPE_SK_SKB,                  "__sk_buff" },
7736 	{ BPF_PROG_TYPE_SOCK_OPS,                "bpf_sock_ops" },
7737 	{ BPF_PROG_TYPE_SOCKET_FILTER,           "__sk_buff" },
7738 	{ BPF_PROG_TYPE_XDP,                     "xdp_md" },
7739 	/* all other program types don't have "named" context structs */
7740 };
7741 
7742 /* forward declarations for arch-specific underlying types of bpf_user_pt_regs_t typedef,
7743  * for below __builtin_types_compatible_p() checks;
7744  * with this approach we don't need any extra arch-specific #ifdef guards
7745  */
7746 struct pt_regs;
7747 struct user_pt_regs;
7748 struct user_regs_struct;
7749 
7750 static bool need_func_arg_type_fixup(const struct btf *btf, const struct bpf_program *prog,
7751 				     const char *subprog_name, int arg_idx,
7752 				     int arg_type_id, const char *ctx_name)
7753 {
7754 	const struct btf_type *t;
7755 	const char *tname;
7756 
7757 	/* check if existing parameter already matches verifier expectations */
7758 	t = skip_mods_and_typedefs(btf, arg_type_id, NULL);
7759 	if (!btf_is_ptr(t))
7760 		goto out_warn;
7761 
7762 	/* typedef bpf_user_pt_regs_t is a special PITA case, valid for kprobe
7763 	 * and perf_event programs, so check this case early on and forget
7764 	 * about it for subsequent checks
7765 	 */
7766 	while (btf_is_mod(t))
7767 		t = btf__type_by_id(btf, t->type);
7768 	if (btf_is_typedef(t) &&
7769 	    (prog->type == BPF_PROG_TYPE_KPROBE || prog->type == BPF_PROG_TYPE_PERF_EVENT)) {
7770 		tname = btf__str_by_offset(btf, t->name_off) ?: "<anon>";
7771 		if (strcmp(tname, "bpf_user_pt_regs_t") == 0)
7772 			return false; /* canonical type for kprobe/perf_event */
7773 	}
7774 
7775 	/* now we can ignore typedefs moving forward */
7776 	t = skip_mods_and_typedefs(btf, t->type, NULL);
7777 
7778 	/* if it's `void *`, definitely fix up BTF info */
7779 	if (btf_is_void(t))
7780 		return true;
7781 
7782 	/* if it's already proper canonical type, no need to fix up */
7783 	tname = btf__str_by_offset(btf, t->name_off) ?: "<anon>";
7784 	if (btf_is_struct(t) && strcmp(tname, ctx_name) == 0)
7785 		return false;
7786 
7787 	/* special cases */
7788 	switch (prog->type) {
7789 	case BPF_PROG_TYPE_KPROBE:
7790 		/* `struct pt_regs *` is expected, but we need to fix up */
7791 		if (btf_is_struct(t) && strcmp(tname, "pt_regs") == 0)
7792 			return true;
7793 		break;
7794 	case BPF_PROG_TYPE_PERF_EVENT:
7795 		if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct pt_regs) &&
7796 		    btf_is_struct(t) && strcmp(tname, "pt_regs") == 0)
7797 			return true;
7798 		if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct user_pt_regs) &&
7799 		    btf_is_struct(t) && strcmp(tname, "user_pt_regs") == 0)
7800 			return true;
7801 		if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct user_regs_struct) &&
7802 		    btf_is_struct(t) && strcmp(tname, "user_regs_struct") == 0)
7803 			return true;
7804 		break;
7805 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
7806 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
7807 		/* allow u64* as ctx */
7808 		if (btf_is_int(t) && t->size == 8)
7809 			return true;
7810 		break;
7811 	default:
7812 		break;
7813 	}
7814 
7815 out_warn:
7816 	pr_warn("prog '%s': subprog '%s' arg#%d is expected to be of `struct %s *` type\n",
7817 		prog->name, subprog_name, arg_idx, ctx_name);
7818 	return false;
7819 }
7820 
7821 static int clone_func_btf_info(struct btf *btf, int orig_fn_id, struct bpf_program *prog)
7822 {
7823 	int fn_id, fn_proto_id, ret_type_id, orig_proto_id;
7824 	int i, err, arg_cnt, fn_name_off, linkage;
7825 	struct btf_type *fn_t, *fn_proto_t, *t;
7826 	struct btf_param *p;
7827 
7828 	/* caller already validated FUNC -> FUNC_PROTO validity */
7829 	fn_t = btf_type_by_id(btf, orig_fn_id);
7830 	fn_proto_t = btf_type_by_id(btf, fn_t->type);
7831 
7832 	/* Note that each btf__add_xxx() operation invalidates
7833 	 * all btf_type and string pointers, so we need to be
7834 	 * very careful when cloning BTF types. BTF type
7835 	 * pointers have to be always refetched. And to avoid
7836 	 * problems with invalidated string pointers, we
7837 	 * add empty strings initially, then just fix up
7838 	 * name_off offsets in place. Offsets are stable for
7839 	 * existing strings, so that works out.
7840 	 */
7841 	fn_name_off = fn_t->name_off; /* we are about to invalidate fn_t */
7842 	linkage = btf_func_linkage(fn_t);
7843 	orig_proto_id = fn_t->type; /* original FUNC_PROTO ID */
7844 	ret_type_id = fn_proto_t->type; /* fn_proto_t will be invalidated */
7845 	arg_cnt = btf_vlen(fn_proto_t);
7846 
7847 	/* clone FUNC_PROTO and its params */
7848 	fn_proto_id = btf__add_func_proto(btf, ret_type_id);
7849 	if (fn_proto_id < 0)
7850 		return -EINVAL;
7851 
7852 	for (i = 0; i < arg_cnt; i++) {
7853 		int name_off;
7854 
7855 		/* copy original parameter data */
7856 		t = btf_type_by_id(btf, orig_proto_id);
7857 		p = &btf_params(t)[i];
7858 		name_off = p->name_off;
7859 
7860 		err = btf__add_func_param(btf, "", p->type);
7861 		if (err)
7862 			return err;
7863 
7864 		fn_proto_t = btf_type_by_id(btf, fn_proto_id);
7865 		p = &btf_params(fn_proto_t)[i];
7866 		p->name_off = name_off; /* use remembered str offset */
7867 	}
7868 
7869 	/* clone FUNC now, btf__add_func() enforces non-empty name, so use
7870 	 * entry program's name as a placeholder, which we replace immediately
7871 	 * with original name_off
7872 	 */
7873 	fn_id = btf__add_func(btf, prog->name, linkage, fn_proto_id);
7874 	if (fn_id < 0)
7875 		return -EINVAL;
7876 
7877 	fn_t = btf_type_by_id(btf, fn_id);
7878 	fn_t->name_off = fn_name_off; /* reuse original string */
7879 
7880 	return fn_id;
7881 }
7882 
7883 /* Check if main program or global subprog's function prototype has `arg:ctx`
7884  * argument tags, and, if necessary, substitute correct type to match what BPF
7885  * verifier would expect, taking into account specific program type. This
7886  * allows to support __arg_ctx tag transparently on old kernels that don't yet
7887  * have a native support for it in the verifier, making user's life much
7888  * easier.
7889  */
7890 static int bpf_program_fixup_func_info(struct bpf_object *obj, struct bpf_program *prog)
7891 {
7892 	const char *ctx_name = NULL, *ctx_tag = "arg:ctx", *fn_name;
7893 	struct bpf_func_info_min *func_rec;
7894 	struct btf_type *fn_t, *fn_proto_t;
7895 	struct btf *btf = obj->btf;
7896 	const struct btf_type *t;
7897 	struct btf_param *p;
7898 	int ptr_id = 0, struct_id, tag_id, orig_fn_id;
7899 	int i, n, arg_idx, arg_cnt, err, rec_idx;
7900 	int *orig_ids;
7901 
7902 	/* no .BTF.ext, no problem */
7903 	if (!obj->btf_ext || !prog->func_info)
7904 		return 0;
7905 
7906 	/* don't do any fix ups if kernel natively supports __arg_ctx */
7907 	if (kernel_supports(obj, FEAT_ARG_CTX_TAG))
7908 		return 0;
7909 
7910 	/* some BPF program types just don't have named context structs, so
7911 	 * this fallback mechanism doesn't work for them
7912 	 */
7913 	for (i = 0; i < ARRAY_SIZE(global_ctx_map); i++) {
7914 		if (global_ctx_map[i].prog_type != prog->type)
7915 			continue;
7916 		ctx_name = global_ctx_map[i].ctx_name;
7917 		break;
7918 	}
7919 	if (!ctx_name)
7920 		return 0;
7921 
7922 	/* remember original func BTF IDs to detect if we already cloned them */
7923 	orig_ids = calloc(prog->func_info_cnt, sizeof(*orig_ids));
7924 	if (!orig_ids)
7925 		return -ENOMEM;
7926 	for (i = 0; i < prog->func_info_cnt; i++) {
7927 		func_rec = prog->func_info + prog->func_info_rec_size * i;
7928 		orig_ids[i] = func_rec->type_id;
7929 	}
7930 
7931 	/* go through each DECL_TAG with "arg:ctx" and see if it points to one
7932 	 * of our subprogs; if yes and subprog is global and needs adjustment,
7933 	 * clone and adjust FUNC -> FUNC_PROTO combo
7934 	 */
7935 	for (i = 1, n = btf__type_cnt(btf); i < n; i++) {
7936 		/* only DECL_TAG with "arg:ctx" value are interesting */
7937 		t = btf__type_by_id(btf, i);
7938 		if (!btf_is_decl_tag(t))
7939 			continue;
7940 		if (strcmp(btf__str_by_offset(btf, t->name_off), ctx_tag) != 0)
7941 			continue;
7942 
7943 		/* only global funcs need adjustment, if at all */
7944 		orig_fn_id = t->type;
7945 		fn_t = btf_type_by_id(btf, orig_fn_id);
7946 		if (!btf_is_func(fn_t) || btf_func_linkage(fn_t) != BTF_FUNC_GLOBAL)
7947 			continue;
7948 
7949 		/* sanity check FUNC -> FUNC_PROTO chain, just in case */
7950 		fn_proto_t = btf_type_by_id(btf, fn_t->type);
7951 		if (!fn_proto_t || !btf_is_func_proto(fn_proto_t))
7952 			continue;
7953 
7954 		/* find corresponding func_info record */
7955 		func_rec = NULL;
7956 		for (rec_idx = 0; rec_idx < prog->func_info_cnt; rec_idx++) {
7957 			if (orig_ids[rec_idx] == t->type) {
7958 				func_rec = prog->func_info + prog->func_info_rec_size * rec_idx;
7959 				break;
7960 			}
7961 		}
7962 		/* current main program doesn't call into this subprog */
7963 		if (!func_rec)
7964 			continue;
7965 
7966 		/* some more sanity checking of DECL_TAG */
7967 		arg_cnt = btf_vlen(fn_proto_t);
7968 		arg_idx = btf_decl_tag(t)->component_idx;
7969 		if (arg_idx < 0 || arg_idx >= arg_cnt)
7970 			continue;
7971 
7972 		/* check if we should fix up argument type */
7973 		p = &btf_params(fn_proto_t)[arg_idx];
7974 		fn_name = btf__str_by_offset(btf, fn_t->name_off) ?: "<anon>";
7975 		if (!need_func_arg_type_fixup(btf, prog, fn_name, arg_idx, p->type, ctx_name))
7976 			continue;
7977 
7978 		/* clone fn/fn_proto, unless we already did it for another arg */
7979 		if (func_rec->type_id == orig_fn_id) {
7980 			int fn_id;
7981 
7982 			fn_id = clone_func_btf_info(btf, orig_fn_id, prog);
7983 			if (fn_id < 0) {
7984 				err = fn_id;
7985 				goto err_out;
7986 			}
7987 
7988 			/* point func_info record to a cloned FUNC type */
7989 			func_rec->type_id = fn_id;
7990 		}
7991 
7992 		/* create PTR -> STRUCT type chain to mark PTR_TO_CTX argument;
7993 		 * we do it just once per main BPF program, as all global
7994 		 * funcs share the same program type, so need only PTR ->
7995 		 * STRUCT type chain
7996 		 */
7997 		if (ptr_id == 0) {
7998 			struct_id = btf__add_struct(btf, ctx_name, 0);
7999 			ptr_id = btf__add_ptr(btf, struct_id);
8000 			if (ptr_id < 0 || struct_id < 0) {
8001 				err = -EINVAL;
8002 				goto err_out;
8003 			}
8004 		}
8005 
8006 		/* for completeness, clone DECL_TAG and point it to cloned param */
8007 		tag_id = btf__add_decl_tag(btf, ctx_tag, func_rec->type_id, arg_idx);
8008 		if (tag_id < 0) {
8009 			err = -EINVAL;
8010 			goto err_out;
8011 		}
8012 
8013 		/* all the BTF manipulations invalidated pointers, refetch them */
8014 		fn_t = btf_type_by_id(btf, func_rec->type_id);
8015 		fn_proto_t = btf_type_by_id(btf, fn_t->type);
8016 
8017 		/* fix up type ID pointed to by param */
8018 		p = &btf_params(fn_proto_t)[arg_idx];
8019 		p->type = ptr_id;
8020 	}
8021 
8022 	free(orig_ids);
8023 	return 0;
8024 err_out:
8025 	free(orig_ids);
8026 	return err;
8027 }
8028 
8029 /*
8030  * Turn pointers to data that are stored in data into addresses of arena.
8031  * The arena is created here, ahead of the other maps: the address has to be
8032  * known before the maps that hold the pointers are created.
8033  */
8034 static int bpf_object__relocate_data_ptrs(struct bpf_object *obj)
8035 {
8036 	struct bpf_map *arena, *map, *targ;
8037 	__u64 addr, val;
8038 	size_t i;
8039 	int err;
8040 
8041 	if (!obj->data_ptr_cnt)
8042 		return 0;
8043 
8044 	for (i = 0; i < obj->data_ptr_cnt; i++) {
8045 		struct data_ptr *p = &obj->data_ptrs[i];
8046 
8047 		if (p->targ_sec_idx < 0)
8048 			continue;
8049 		map = bpf_object__sec_map(obj, p->sec_idx);
8050 		targ = bpf_object__sec_map(obj, p->targ_sec_idx);
8051 		if (map && (map->in_arena || map->autocreate) &&
8052 		    (!targ || (!targ->in_arena && !targ->arena_copy))) {
8053 			pr_warn("sec '%s': pointer to '%s' at offset %zu can't be resolved: sec '%s' is not in arena\n",
8054 				map->real_name, p->sym_name, p->sec_off,
8055 				targ ? targ->real_name : "<?>");
8056 			return -LIBBPF_ERRNO__RELOC;
8057 		}
8058 	}
8059 
8060 	if (obj->gen_loader) {
8061 		pr_warn("pointers to data in data are not supported by light skeleton\n");
8062 		return -ENOTSUP;
8063 	}
8064 
8065 	if (obj->arena_map_idx < 0)
8066 		return 0;
8067 
8068 	arena = &obj->maps[obj->arena_map_idx];
8069 	if (!arena->autocreate)
8070 		return 0;
8071 	/* libbpf doesn't mmap an arena that it didn't create, so the address is not known */
8072 	if (arena->reused || arena->pin_path) {
8073 		pr_warn("map '%s': pointers to data in data are not supported with pinned or reused arena\n",
8074 			arena->name);
8075 		return -ENOTSUP;
8076 	}
8077 
8078 	err = bpf_object__create_map(obj, arena, false);
8079 	err = err ?: bpf_object__mmap_arena(obj, arena);
8080 	if (err) {
8081 		pr_warn("map '%s': failed to create: %s\n", arena->name, errstr(err));
8082 		return err;
8083 	}
8084 	obj->arena_mapped = true;
8085 
8086 	for (i = 0; i < obj->data_ptr_cnt; i++) {
8087 		struct data_ptr *p = &obj->data_ptrs[i];
8088 
8089 		map = bpf_object__sec_map(obj, p->sec_idx);
8090 		if (!map || (!map->in_arena && !map->autocreate))
8091 			continue;
8092 
8093 		addr = (__u64)(unsigned long)arena->mmaped + obj->arena_data_off + p->targ_off;
8094 		if (p->targ_sec_idx >= 0)
8095 			addr += bpf_object__sec_map(obj, p->targ_sec_idx)->arena_off;
8096 
8097 		memcpy(&val, map->mmaped + p->sec_off, sizeof(val));
8098 		val += addr;
8099 		memcpy(map->mmaped + p->sec_off, &val, sizeof(val));
8100 	}
8101 	return 0;
8102 }
8103 
8104 static int bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
8105 {
8106 	struct bpf_program *prog;
8107 	size_t i, j;
8108 	int err;
8109 
8110 	if (obj->btf_ext) {
8111 		err = bpf_object__relocate_core(obj, targ_btf_path);
8112 		if (err) {
8113 			pr_warn("failed to perform CO-RE relocations: %s\n",
8114 				errstr(err));
8115 			return err;
8116 		}
8117 		bpf_object__sort_relos(obj);
8118 	}
8119 
8120 	if (obj->arena_map_idx >= 0) {
8121 		struct bpf_map *arena_map = &obj->maps[obj->arena_map_idx];
8122 		size_t data_sz = roundup(obj->arena_data_sz, sysconf(_SC_PAGE_SIZE));
8123 		size_t mmap_sz = bpf_map_mmap_sz(arena_map);
8124 
8125 		if (data_sz > mmap_sz) {
8126 			pr_warn("map '%s': declared ARENA map size (%zu) is too small to hold global %s of size %zu\n",
8127 				arena_map->name, mmap_sz,
8128 				obj->data_in_arena ? "data" : "__arena variables",
8129 				obj->arena_data_sz);
8130 			return -E2BIG;
8131 		}
8132 
8133 		/* place globals at the end of the arena (if supported) */
8134 		if (kernel_supports(obj, FEAT_LDIMM64_FULL_RANGE_OFF))
8135 			obj->arena_data_off = mmap_sz - data_sz;
8136 	}
8137 
8138 	err = bpf_object__relocate_data_ptrs(obj);
8139 	if (err)
8140 		return err;
8141 
8142 	/* Before relocating calls pre-process relocations and mark
8143 	 * few ld_imm64 instructions that points to subprogs.
8144 	 * Otherwise bpf_object__reloc_code() later would have to consider
8145 	 * all ld_imm64 insns as relocation candidates. That would
8146 	 * reduce relocation speed, since amount of find_prog_insn_relo()
8147 	 * would increase and most of them will fail to find a relo.
8148 	 */
8149 	for (i = 0; i < obj->nr_programs; i++) {
8150 		prog = &obj->programs[i];
8151 		for (j = 0; j < prog->nr_reloc; j++) {
8152 			struct reloc_desc *relo = &prog->reloc_desc[j];
8153 			struct bpf_insn *insn = &prog->insns[relo->insn_idx];
8154 
8155 			/* mark the insn, so it's recognized by insn_is_pseudo_func() */
8156 			if (relo->type == RELO_SUBPROG_ADDR)
8157 				insn[0].src_reg = BPF_PSEUDO_FUNC;
8158 		}
8159 	}
8160 
8161 	/* relocate subprogram calls and append used subprograms to main
8162 	 * programs; each copy of subprogram code needs to be relocated
8163 	 * differently for each main program, because its code location might
8164 	 * have changed.
8165 	 * Append subprog relos to main programs to allow data relos to be
8166 	 * processed after text is completely relocated.
8167 	 */
8168 	for (i = 0; i < obj->nr_programs; i++) {
8169 		prog = &obj->programs[i];
8170 		/* sub-program's sub-calls are relocated within the context of
8171 		 * its main program only
8172 		 */
8173 		if (prog_is_subprog(obj, prog))
8174 			continue;
8175 		if (!prog->autoload)
8176 			continue;
8177 
8178 		err = bpf_object__relocate_calls(obj, prog);
8179 		if (err) {
8180 			pr_warn("prog '%s': failed to relocate calls: %s\n",
8181 				prog->name, errstr(err));
8182 			return err;
8183 		}
8184 
8185 		err = bpf_prog_assign_exc_cb(obj, prog);
8186 		if (err)
8187 			return err;
8188 		/* Now, also append exception callback if it has not been done already. */
8189 		if (prog->exception_cb_idx >= 0) {
8190 			struct bpf_program *subprog = &obj->programs[prog->exception_cb_idx];
8191 
8192 			/* Calling exception callback directly is disallowed, which the
8193 			 * verifier will reject later. In case it was processed already,
8194 			 * we can skip this step, otherwise for all other valid cases we
8195 			 * have to append exception callback now.
8196 			 */
8197 			if (subprog->sub_insn_off == 0) {
8198 				err = bpf_object__append_subprog_code(obj, prog, subprog);
8199 				if (err)
8200 					return err;
8201 				err = bpf_object__reloc_code(obj, prog, subprog);
8202 				if (err)
8203 					return err;
8204 			}
8205 		}
8206 	}
8207 	for (i = 0; i < obj->nr_programs; i++) {
8208 		prog = &obj->programs[i];
8209 		if (prog_is_subprog(obj, prog))
8210 			continue;
8211 		if (!prog->autoload)
8212 			continue;
8213 
8214 		/* Process data relos for main programs */
8215 		err = bpf_object__relocate_data(obj, prog);
8216 		if (err) {
8217 			pr_warn("prog '%s': failed to relocate data references: %s\n",
8218 				prog->name, errstr(err));
8219 			return err;
8220 		}
8221 
8222 		/* Fix up .BTF.ext information, if necessary */
8223 		err = bpf_program_fixup_func_info(obj, prog);
8224 		if (err) {
8225 			pr_warn("prog '%s': failed to perform .BTF.ext fix ups: %s\n",
8226 				prog->name, errstr(err));
8227 			return err;
8228 		}
8229 	}
8230 
8231 	return 0;
8232 }
8233 
8234 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
8235 					    Elf64_Shdr *shdr, Elf_Data *data);
8236 
8237 static int bpf_object__collect_map_relos(struct bpf_object *obj,
8238 					 Elf64_Shdr *shdr, Elf_Data *data)
8239 {
8240 	const int bpf_ptr_sz = 8, host_ptr_sz = sizeof(void *);
8241 	int i, j, nrels, new_sz;
8242 	const struct btf_var_secinfo *vi = NULL;
8243 	const struct btf_type *sec, *var, *def;
8244 	struct bpf_map *map = NULL, *targ_map = NULL;
8245 	struct bpf_program *targ_prog = NULL;
8246 	bool is_prog_array, is_map_in_map;
8247 	const struct btf_member *member;
8248 	const char *name, *mname, *type;
8249 	unsigned int moff;
8250 	Elf64_Sym *sym;
8251 	Elf64_Rel *rel;
8252 	void *tmp;
8253 
8254 	if (!obj->efile.btf_maps_sec_btf_id || !obj->btf)
8255 		return -EINVAL;
8256 	sec = btf__type_by_id(obj->btf, obj->efile.btf_maps_sec_btf_id);
8257 	if (!sec)
8258 		return -EINVAL;
8259 
8260 	nrels = shdr->sh_size / shdr->sh_entsize;
8261 	for (i = 0; i < nrels; i++) {
8262 		rel = elf_rel_by_idx(data, i);
8263 		if (!rel) {
8264 			pr_warn(".maps relo #%d: failed to get ELF relo\n", i);
8265 			return -LIBBPF_ERRNO__FORMAT;
8266 		}
8267 
8268 		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
8269 		if (!sym) {
8270 			pr_warn(".maps relo #%d: symbol %zx not found\n",
8271 				i, (size_t)ELF64_R_SYM(rel->r_info));
8272 			return -LIBBPF_ERRNO__FORMAT;
8273 		}
8274 		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
8275 
8276 		pr_debug(".maps relo #%d: for %zd value %zu rel->r_offset %zu name %u ('%s')\n",
8277 			 i, (ssize_t)(rel->r_info >> 32), (size_t)sym->st_value,
8278 			 (size_t)rel->r_offset, sym->st_name, name);
8279 
8280 		for (j = 0; j < obj->nr_maps; j++) {
8281 			map = &obj->maps[j];
8282 			if (map->sec_idx != obj->efile.btf_maps_shndx)
8283 				continue;
8284 
8285 			vi = btf_var_secinfos(sec) + map->btf_var_idx;
8286 			if (vi->offset <= rel->r_offset &&
8287 			    rel->r_offset + bpf_ptr_sz <= vi->offset + vi->size)
8288 				break;
8289 		}
8290 		if (j == obj->nr_maps) {
8291 			pr_warn(".maps relo #%d: cannot find map '%s' at rel->r_offset %zu\n",
8292 				i, name, (size_t)rel->r_offset);
8293 			return -EINVAL;
8294 		}
8295 
8296 		is_map_in_map = bpf_map_type__is_map_in_map(map->def.type);
8297 		is_prog_array = map->def.type == BPF_MAP_TYPE_PROG_ARRAY;
8298 		type = is_map_in_map ? "map" : "prog";
8299 		if (is_map_in_map) {
8300 			if (sym->st_shndx != obj->efile.btf_maps_shndx) {
8301 				pr_warn(".maps relo #%d: '%s' isn't a BTF-defined map\n",
8302 					i, name);
8303 				return -LIBBPF_ERRNO__RELOC;
8304 			}
8305 			if (map->def.type == BPF_MAP_TYPE_HASH_OF_MAPS &&
8306 			    map->def.key_size != sizeof(int)) {
8307 				pr_warn(".maps relo #%d: hash-of-maps '%s' should have key size %zu.\n",
8308 					i, map->name, sizeof(int));
8309 				return -EINVAL;
8310 			}
8311 			targ_map = bpf_object__find_map_by_name(obj, name);
8312 			if (!targ_map) {
8313 				pr_warn(".maps relo #%d: '%s' isn't a valid map reference\n",
8314 					i, name);
8315 				return -ESRCH;
8316 			}
8317 		} else if (is_prog_array) {
8318 			targ_prog = bpf_object__find_program_by_name(obj, name);
8319 			if (!targ_prog) {
8320 				pr_warn(".maps relo #%d: '%s' isn't a valid program reference\n",
8321 					i, name);
8322 				return -ESRCH;
8323 			}
8324 			if (targ_prog->sec_idx != sym->st_shndx ||
8325 			    targ_prog->sec_insn_off * 8 != sym->st_value ||
8326 			    prog_is_subprog(obj, targ_prog)) {
8327 				pr_warn(".maps relo #%d: '%s' isn't an entry-point program\n",
8328 					i, name);
8329 				return -LIBBPF_ERRNO__RELOC;
8330 			}
8331 		} else {
8332 			return -EINVAL;
8333 		}
8334 
8335 		var = btf__type_by_id(obj->btf, vi->type);
8336 		def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
8337 		if (btf_vlen(def) == 0)
8338 			return -EINVAL;
8339 		member = btf_members(def) + btf_vlen(def) - 1;
8340 		mname = btf__name_by_offset(obj->btf, member->name_off);
8341 		if (strcmp(mname, "values"))
8342 			return -EINVAL;
8343 
8344 		moff = btf_member_bit_offset(def, btf_vlen(def) - 1) / 8;
8345 		if (rel->r_offset - vi->offset < moff)
8346 			return -EINVAL;
8347 
8348 		moff = rel->r_offset - vi->offset - moff;
8349 		/* here we use BPF pointer size, which is always 64 bit, as we
8350 		 * are parsing ELF that was built for BPF target
8351 		 */
8352 		if (moff % bpf_ptr_sz)
8353 			return -EINVAL;
8354 		moff /= bpf_ptr_sz;
8355 		if (moff >= map->init_slots_sz) {
8356 			new_sz = moff + 1;
8357 			tmp = libbpf_reallocarray(map->init_slots, new_sz, host_ptr_sz);
8358 			if (!tmp)
8359 				return -ENOMEM;
8360 			map->init_slots = tmp;
8361 			memset(map->init_slots + map->init_slots_sz, 0,
8362 			       (new_sz - map->init_slots_sz) * host_ptr_sz);
8363 			map->init_slots_sz = new_sz;
8364 		}
8365 		map->init_slots[moff] = is_map_in_map ? (void *)targ_map : (void *)targ_prog;
8366 
8367 		pr_debug(".maps relo #%d: map '%s' slot [%u] points to %s '%s'\n",
8368 			 i, map->name, moff, type, name);
8369 	}
8370 
8371 	return 0;
8372 }
8373 
8374 /*
8375  * A pointer to data that is stored in data. When data is in arena
8376  * the program dereferences what it loads from data, so the pointer has
8377  * to be the address of the target in arena.
8378  */
8379 static int bpf_object__collect_data_ptr(struct bpf_object *obj, const char *relo_sec_name,
8380 					int relo_idx, size_t sec_idx, const Elf64_Rel *rel,
8381 					const Elf64_Sym *sym)
8382 {
8383 	Elf_Data *scn_data = obj->efile.secs[sec_idx].data;
8384 	const char *sym_name = elf_sym_str(obj, sym->st_name) ?: "<?>";
8385 	struct data_ptr *ptrs;
8386 
8387 	if (ELF64_ST_TYPE(sym->st_info) == STT_SECTION && sym->st_shndx < obj->efile.sec_cnt)
8388 		sym_name = elf_sec_name(obj, elf_sec_by_idx(obj, sym->st_shndx)) ?: "<?>";
8389 
8390 	if (ELF64_R_TYPE(rel->r_info) != R_BPF_64_ABS64 ||
8391 	    sym->st_shndx >= obj->efile.sec_cnt ||
8392 	    (sym->st_shndx != obj->efile.arena_data_shndx &&
8393 	     !bpf_object__shndx_is_data(obj, sym->st_shndx)) ||
8394 	    rel->r_offset >= scn_data->d_size ||
8395 	    scn_data->d_size - rel->r_offset < sizeof(__u64)) {
8396 		pr_warn("sec '%s': relo #%d: can't resolve pointer to '%s' at offset %zu when data is in arena\n",
8397 			relo_sec_name, relo_idx, sym_name, (size_t)rel->r_offset);
8398 		return -LIBBPF_ERRNO__RELOC;
8399 	}
8400 
8401 	ptrs = libbpf_reallocarray(obj->data_ptrs, obj->data_ptr_cnt + 1, sizeof(*ptrs));
8402 	if (!ptrs)
8403 		return -ENOMEM;
8404 	obj->data_ptrs = ptrs;
8405 
8406 	ptrs[obj->data_ptr_cnt].sec_idx = sec_idx;
8407 	ptrs[obj->data_ptr_cnt].sec_off = rel->r_offset;
8408 	/* __arena variables are at the start of arena data */
8409 	ptrs[obj->data_ptr_cnt].targ_sec_idx =
8410 		sym->st_shndx == obj->efile.arena_data_shndx ? -1 : sym->st_shndx;
8411 	ptrs[obj->data_ptr_cnt].targ_off = sym->st_value;
8412 	ptrs[obj->data_ptr_cnt].sym_name = strdup(sym_name);
8413 	if (!ptrs[obj->data_ptr_cnt].sym_name)
8414 		return -ENOMEM;
8415 	obj->data_ptr_cnt++;
8416 
8417 	pr_debug("sec '%s': relo #%d: pointer at offset %zu to '%s'\n",
8418 		 relo_sec_name, relo_idx, (size_t)rel->r_offset, sym_name);
8419 	return 0;
8420 }
8421 
8422 /* Collect pointers in a data section that went to arena */
8423 static int bpf_object__collect_data_relos(struct bpf_object *obj,
8424 					  Elf64_Shdr *shdr, Elf_Data *data)
8425 {
8426 	int i, err, nrels = shdr->sh_size / shdr->sh_entsize;
8427 	const char *relo_sec_name;
8428 	Elf64_Sym *sym;
8429 	Elf64_Rel *rel;
8430 
8431 	relo_sec_name = elf_sec_str(obj, shdr->sh_name) ?: "<?>";
8432 	for (i = 0; i < nrels; i++) {
8433 		rel = elf_rel_by_idx(data, i);
8434 		sym = rel ? elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info)) : NULL;
8435 		if (!sym) {
8436 			pr_warn("sec '%s': failed to get relo #%d\n", relo_sec_name, i);
8437 			return -LIBBPF_ERRNO__FORMAT;
8438 		}
8439 		err = bpf_object__collect_data_ptr(obj, relo_sec_name, i, shdr->sh_info, rel, sym);
8440 		if (err)
8441 			return err;
8442 	}
8443 	return 0;
8444 }
8445 
8446 /*
8447  * Collect pointers to functions in a read-only data section. They are
8448  * R_BPF_64_ABS64 relocations against .text section, where the offset of
8449  * a static function in the section is stored in place. Relocations in data
8450  * sections were ignored before pointers to functions were supported. Those
8451  * that are something else, e.g. pointers to data, still are, unless data
8452  * is in arena.
8453  */
8454 static int bpf_object__collect_rodata_relos(struct bpf_object *obj,
8455 					    Elf64_Shdr *shdr, Elf_Data *data)
8456 {
8457 	size_t sec_idx = shdr->sh_info, sym_idx;
8458 	int i, nrels = shdr->sh_size / shdr->sh_entsize;
8459 	const char *relo_sec_name;
8460 	struct func_ptr *ptrs;
8461 	Elf_Data *scn_data;
8462 	Elf64_Sym *sym;
8463 	Elf64_Rel *rel;
8464 	__u64 addend;
8465 
8466 	relo_sec_name = elf_sec_str(obj, shdr->sh_name) ?: "<?>";
8467 	scn_data = obj->efile.secs[sec_idx].data;
8468 	if (!scn_data)
8469 		return -LIBBPF_ERRNO__FORMAT;
8470 
8471 	for (i = 0; i < nrels; i++) {
8472 		rel = elf_rel_by_idx(data, i);
8473 		if (!rel) {
8474 			pr_warn("sec '%s': failed to get relo #%d\n", relo_sec_name, i);
8475 			return -LIBBPF_ERRNO__FORMAT;
8476 		}
8477 
8478 		sym_idx = ELF64_R_SYM(rel->r_info);
8479 		sym = elf_sym_by_idx(obj, sym_idx);
8480 		if (!sym) {
8481 			pr_warn("sec '%s': symbol #%zu not found for relo #%d\n",
8482 				relo_sec_name, sym_idx, i);
8483 			return -LIBBPF_ERRNO__FORMAT;
8484 		}
8485 
8486 		if (ELF64_R_TYPE(rel->r_info) != R_BPF_64_ABS64 ||
8487 		    !sym_is_subprog(sym, obj->efile.text_shndx)) {
8488 			int err;
8489 
8490 			if (obj->data_in_arena) {
8491 				err = bpf_object__collect_data_ptr(obj, relo_sec_name, i,
8492 								   sec_idx, rel, sym);
8493 				if (err)
8494 					return err;
8495 				continue;
8496 			}
8497 			pr_debug("sec '%s': relo #%d: not a pointer to a function, skipping...\n",
8498 				 relo_sec_name, i);
8499 			continue;
8500 		}
8501 
8502 		/* the kernel finds aligned pointers only */
8503 		if (rel->r_offset % sizeof(__u64) || rel->r_offset >= scn_data->d_size ||
8504 		    scn_data->d_size - rel->r_offset < sizeof(__u64)) {
8505 			pr_debug("sec '%s': relo #%d: unsupported offset 0x%zx, skipping...\n",
8506 				 relo_sec_name, i, (size_t)rel->r_offset);
8507 			continue;
8508 		}
8509 
8510 		memcpy(&addend, scn_data->d_buf + rel->r_offset, sizeof(addend));
8511 		if (!is_native_endianness(obj))
8512 			addend = bswap_64(addend);
8513 		if ((sym->st_value + addend) % BPF_INSN_SZ) {
8514 			pr_debug("sec '%s': relo #%d: bad pointer to a function at offset %zu+%llu, skipping...\n",
8515 				 relo_sec_name, i, (size_t)sym->st_value,
8516 				 (unsigned long long)addend);
8517 			continue;
8518 		}
8519 
8520 		ptrs = libbpf_reallocarray(obj->func_ptrs, obj->func_ptr_cnt + 1, sizeof(*ptrs));
8521 		if (!ptrs)
8522 			return -ENOMEM;
8523 		obj->func_ptrs = ptrs;
8524 
8525 		ptrs[obj->func_ptr_cnt].sec_idx = sec_idx;
8526 		ptrs[obj->func_ptr_cnt].sec_off = rel->r_offset;
8527 		ptrs[obj->func_ptr_cnt].text_off = sym->st_value + addend;
8528 		obj->func_ptr_cnt++;
8529 
8530 		pr_debug("sec '%s': relo #%d: pointer at offset %zu to a function at .text+%zu\n",
8531 			 relo_sec_name, i, (size_t)rel->r_offset, (size_t)(sym->st_value + addend));
8532 	}
8533 	return 0;
8534 }
8535 
8536 static int cmp_func_ptrs(const void *_a, const void *_b)
8537 {
8538 	const struct func_ptr *a = _a;
8539 	const struct func_ptr *b = _b;
8540 
8541 	if (a->sec_idx != b->sec_idx)
8542 		return a->sec_idx < b->sec_idx ? -1 : 1;
8543 	if (a->sec_off != b->sec_off)
8544 		return a->sec_off < b->sec_off ? -1 : 1;
8545 	return 0;
8546 }
8547 
8548 static int bpf_object__collect_relos(struct bpf_object *obj)
8549 {
8550 	int i, err;
8551 
8552 	for (i = 0; i < obj->efile.sec_cnt; i++) {
8553 		struct elf_sec_desc *sec_desc = &obj->efile.secs[i];
8554 		Elf64_Shdr *shdr;
8555 		Elf_Data *data;
8556 		int idx;
8557 
8558 		if (sec_desc->sec_type != SEC_RELO)
8559 			continue;
8560 
8561 		shdr = sec_desc->shdr;
8562 		data = sec_desc->data;
8563 		idx = shdr->sh_info;
8564 
8565 		if (shdr->sh_type != SHT_REL || idx < 0 || idx >= obj->efile.sec_cnt) {
8566 			pr_warn("internal error at %d\n", __LINE__);
8567 			return -LIBBPF_ERRNO__INTERNAL;
8568 		}
8569 
8570 		if (obj->efile.secs[idx].sec_type == SEC_RODATA)
8571 			err = bpf_object__collect_rodata_relos(obj, shdr, data);
8572 		else if (obj->efile.secs[idx].sec_type == SEC_DATA)
8573 			err = bpf_object__collect_data_relos(obj, shdr, data);
8574 		else if (obj->efile.secs[idx].sec_type == SEC_ST_OPS)
8575 			err = bpf_object__collect_st_ops_relos(obj, shdr, data);
8576 		else if (idx == obj->efile.btf_maps_shndx)
8577 			err = bpf_object__collect_map_relos(obj, shdr, data);
8578 		else
8579 			err = bpf_object__collect_prog_relos(obj, shdr, data);
8580 		if (err)
8581 			return err;
8582 	}
8583 
8584 	/* sort by section, so that pointers in the data of a map are next to each other */
8585 	if (obj->func_ptr_cnt)
8586 		qsort(obj->func_ptrs, obj->func_ptr_cnt, sizeof(*obj->func_ptrs), cmp_func_ptrs);
8587 
8588 	for (i = 0; i < obj->nr_maps; i++) {
8589 		struct bpf_map *map = &obj->maps[i];
8590 		size_t j;
8591 
8592 		if (map->libbpf_type != LIBBPF_MAP_RODATA)
8593 			continue;
8594 		for (j = 0; j < obj->func_ptr_cnt; j++) {
8595 			if (obj->func_ptrs[j].sec_idx != map->sec_idx)
8596 				continue;
8597 			if (!map->func_ptr_cnt)
8598 				map->func_ptrs = &obj->func_ptrs[j];
8599 			map->func_ptr_cnt++;
8600 		}
8601 	}
8602 
8603 	bpf_object__sort_relos(obj);
8604 	return 0;
8605 }
8606 
8607 static bool insn_is_helper_call(struct bpf_insn *insn, enum bpf_func_id *func_id)
8608 {
8609 	if (BPF_CLASS(insn->code) == BPF_JMP &&
8610 	    BPF_OP(insn->code) == BPF_CALL &&
8611 	    BPF_SRC(insn->code) == BPF_K &&
8612 	    insn->src_reg == 0 &&
8613 	    insn->dst_reg == 0) {
8614 		    *func_id = insn->imm;
8615 		    return true;
8616 	}
8617 	return false;
8618 }
8619 
8620 static int bpf_object__sanitize_prog(struct bpf_object *obj, struct bpf_program *prog)
8621 {
8622 	struct bpf_insn *insn = prog->insns;
8623 	enum bpf_func_id func_id;
8624 	int i;
8625 
8626 	if (obj->gen_loader)
8627 		return 0;
8628 
8629 	for (i = 0; i < prog->insns_cnt; i++, insn++) {
8630 		if (!insn_is_helper_call(insn, &func_id))
8631 			continue;
8632 
8633 		/* on kernels that don't yet support
8634 		 * bpf_probe_read_{kernel,user}[_str] helpers, fall back
8635 		 * to bpf_probe_read() which works well for old kernels
8636 		 */
8637 		switch (func_id) {
8638 		case BPF_FUNC_probe_read_kernel:
8639 		case BPF_FUNC_probe_read_user:
8640 			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
8641 				insn->imm = BPF_FUNC_probe_read;
8642 			break;
8643 		case BPF_FUNC_probe_read_kernel_str:
8644 		case BPF_FUNC_probe_read_user_str:
8645 			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
8646 				insn->imm = BPF_FUNC_probe_read_str;
8647 			break;
8648 		default:
8649 			break;
8650 		}
8651 	}
8652 	return 0;
8653 }
8654 
8655 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
8656 				     int *btf_obj_fd, int *btf_type_id);
8657 
8658 static inline bool is_tracing_multi(enum bpf_attach_type type)
8659 {
8660 	return type == BPF_TRACE_FENTRY_MULTI || type == BPF_TRACE_FEXIT_MULTI ||
8661 	       type == BPF_TRACE_FSESSION_MULTI;
8662 }
8663 
8664 static const struct module_btf *find_attach_module(struct bpf_object *obj, const char *attach)
8665 {
8666 	const char *sep, *mod_name = NULL;
8667 	int i, mod_len, err;
8668 
8669 	/*
8670 	 * We expect attach string in the form of either
8671 	 * - function_pattern or
8672 	 * - <module>:function_pattern
8673 	 */
8674 	sep = strchr(attach, ':');
8675 	if (sep) {
8676 		mod_name = attach;
8677 		mod_len = sep - mod_name;
8678 	}
8679 	if (!mod_name)
8680 		return NULL;
8681 
8682 	err = load_module_btfs(obj);
8683 	if (err)
8684 		return NULL;
8685 
8686 	for (i = 0; i < obj->btf_module_cnt; i++) {
8687 		const struct module_btf *mod = &obj->btf_modules[i];
8688 
8689 		if (strncmp(mod->name, mod_name, mod_len) == 0 && mod->name[mod_len] == '\0')
8690 			return mod;
8691 	}
8692 	return NULL;
8693 }
8694 
8695 static int tracing_multi_mod_fd(struct bpf_program *prog, int *btf_obj_fd)
8696 {
8697 	const char *attach_name, *sep;
8698 	const struct module_btf *mod;
8699 
8700 	*btf_obj_fd = 0;
8701 	attach_name = strchr(prog->sec_name, '/');
8702 
8703 	/* Program with no details in spec, using kernel btf. */
8704 	if (!attach_name)
8705 		return 0;
8706 
8707 	/* Program with no module section, using kernel btf. */
8708 	sep = strchr(++attach_name, ':');
8709 	if (!sep)
8710 		return 0;
8711 
8712 	/* Program with module specified, get its btf fd. */
8713 	mod = find_attach_module(prog->obj, attach_name);
8714 	if (!mod)
8715 		return -EINVAL;
8716 
8717 	*btf_obj_fd = mod->fd;
8718 	return 0;
8719 }
8720 
8721 static int libbpf_setup_prog_flags(struct bpf_program *prog, long cookie)
8722 {
8723 	enum sec_def_flags def = cookie;
8724 
8725 	if (def & SEC_SLEEPABLE)
8726 		prog->prog_flags |= BPF_F_SLEEPABLE;
8727 
8728 	if (def & SEC_XDP_FRAGS)
8729 		prog->prog_flags |= BPF_F_XDP_HAS_FRAGS;
8730 
8731 	return 0;
8732 }
8733 
8734 /* this is called as prog->sec_def->prog_prepare_load_fn for libbpf-supported sec_defs */
8735 static int libbpf_prepare_prog_load(struct bpf_program *prog,
8736 				    struct bpf_prog_load_opts *opts, long cookie)
8737 {
8738 	enum sec_def_flags def = cookie;
8739 
8740 	/* old kernels might not support specifying expected_attach_type */
8741 	if ((def & SEC_EXP_ATTACH_OPT) && !kernel_supports(prog->obj, FEAT_EXP_ATTACH_TYPE))
8742 		opts->expected_attach_type = 0;
8743 
8744 	/* special check for usdt to use uprobe_multi link */
8745 	if ((def & SEC_USDT) && kernel_supports(prog->obj, FEAT_UPROBE_MULTI_LINK)) {
8746 		/* for BPF_TRACE_UPROBE_MULTI, user might want to query expected_attach_type
8747 		 * in prog, and expected_attach_type we set in kernel is from opts, so we
8748 		 * update both.
8749 		 */
8750 		prog->expected_attach_type = BPF_TRACE_UPROBE_MULTI;
8751 		opts->expected_attach_type = BPF_TRACE_UPROBE_MULTI;
8752 	}
8753 
8754 	if ((def & SEC_ATTACH_BTF) && !prog->attach_btf_id) {
8755 		int btf_obj_fd = 0, btf_type_id = 0, err;
8756 		const char *attach_name;
8757 
8758 		attach_name = strchr(prog->sec_name, '/');
8759 		if (!attach_name) {
8760 			/* if BPF program is annotated with just SEC("fentry")
8761 			 * (or similar) without declaratively specifying
8762 			 * target, then it is expected that target will be
8763 			 * specified with bpf_program__set_attach_target() at
8764 			 * runtime before BPF object load step. If not, then
8765 			 * there is nothing to load into the kernel as BPF
8766 			 * verifier won't be able to validate BPF program
8767 			 * correctness anyways.
8768 			 */
8769 			pr_warn("prog '%s': no BTF-based attach target is specified, use bpf_program__set_attach_target()\n",
8770 				prog->name);
8771 			return -EINVAL;
8772 		}
8773 		attach_name++; /* skip over / */
8774 
8775 		err = libbpf_find_attach_btf_id(prog, attach_name, &btf_obj_fd, &btf_type_id);
8776 		if (err)
8777 			return err;
8778 
8779 		/* cache resolved BTF FD and BTF type ID in the prog */
8780 		prog->attach_btf_obj_fd = btf_obj_fd;
8781 		prog->attach_btf_id = btf_type_id;
8782 
8783 		/* but by now libbpf common logic is not utilizing
8784 		 * prog->attach_btf_obj_fd/prog->attach_btf_id anymore because
8785 		 * this callback is called after opts were populated by
8786 		 * libbpf, so this callback has to update opts explicitly here
8787 		 */
8788 		opts->attach_btf_obj_fd = btf_obj_fd;
8789 		opts->attach_btf_id = btf_type_id;
8790 	}
8791 
8792 	if (is_tracing_multi(prog->expected_attach_type)) {
8793 		int err, btf_obj_fd = 0;
8794 
8795 		err = tracing_multi_mod_fd(prog, &btf_obj_fd);
8796 		if (err < 0)
8797 			return err;
8798 
8799 		prog->attach_btf_obj_fd = btf_obj_fd;
8800 		opts->attach_btf_obj_fd = btf_obj_fd;
8801 	}
8802 
8803 	return 0;
8804 }
8805 
8806 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz);
8807 
8808 /*
8809  * Bind the arena of the object to the program about to be loaded. A program
8810  * has an arena only when an insn refers to the map, but the kernel can hand
8811  * it arena pointers all the same, as struct_ops arguments, through tagged
8812  * struct members or as kfunc return values, and the verifier rejects those
8813  * when the program has no arena to place them in. A continuous fd_array
8814  * binds every map in it, the arena takes slot 0, which is free: a kfunc insn
8815  * with offset 0 names vmlinux BTF rather than a slot.
8816  */
8817 static int bpf_object__bind_arena(struct bpf_object *obj, struct bpf_program *prog,
8818 				  struct bpf_prog_load_opts *load_attr)
8819 {
8820 	struct bpf_map *map;
8821 	int err;
8822 
8823 	if (obj->gen_loader || obj->arena_map_idx < 0 || !kernel_supports(obj, FEAT_FD_ARRAY_CNT))
8824 		return 0;
8825 	map = &obj->maps[obj->arena_map_idx];
8826 	/*
8827 	 * Nothing to bind when the arena is not created, or no longer is after
8828 	 * a failed load, when it is exclusive to another program, and nothing
8829 	 * for an offloaded program, which the kernel does not let near an
8830 	 * arena.
8831 	 */
8832 	if (!map->autocreate || map->fd < 0 || (map->excl_prog && map->excl_prog != prog) ||
8833 	    load_attr->prog_ifindex)
8834 		return 0;
8835 	/*
8836 	 * An arena exclusive to the program itself needs a kernel that checks
8837 	 * the map against the digest of the final program. Earlier kernels
8838 	 * compared a map bound through the fd_array against a digest they had
8839 	 * not computed yet and refused the load; there the program binds its
8840 	 * arena through its insns, as before.
8841 	 */
8842 	if (map->excl_prog && !kernel_supports(obj, FEAT_EXCL_MAP_FD_ARRAY_CNT))
8843 		return 0;
8844 
8845 	if (!obj->fd_array_used) {
8846 		err = libbpf_ensure_mem((void **)&obj->fd_array, &obj->fd_array_cap, sizeof(int), 1);
8847 		if (err)
8848 			return err;
8849 		obj->fd_array_used = 1;
8850 	}
8851 	obj->fd_array[0] = map->fd;
8852 	load_attr->fd_array = obj->fd_array;
8853 	/* with slot 0 filled every slot handed out is valid, so the array can go with a count */
8854 	load_attr->fd_array_cnt = obj->fd_array_used;
8855 	return 0;
8856 }
8857 
8858 static int bpf_object_load_prog(struct bpf_object *obj, struct bpf_program *prog,
8859 				struct bpf_insn *insns, int insns_cnt,
8860 				const char *license, __u32 kern_version, int *prog_fd)
8861 {
8862 	LIBBPF_OPTS(bpf_prog_load_opts, load_attr);
8863 	const char *prog_name = NULL;
8864 	size_t log_buf_size = 0;
8865 	char *log_buf = NULL, *tmp;
8866 	bool own_log_buf = true;
8867 	__u32 log_level = prog->log_level;
8868 	int ret, err;
8869 
8870 	/* Be more helpful by rejecting programs that can't be validated early
8871 	 * with more meaningful and actionable error message.
8872 	 */
8873 	switch (prog->type) {
8874 	case BPF_PROG_TYPE_UNSPEC:
8875 		/*
8876 		 * The program type must be set.  Most likely we couldn't find a proper
8877 		 * section definition at load time, and thus we didn't infer the type.
8878 		 */
8879 		pr_warn("prog '%s': missing BPF prog type, check ELF section name '%s'\n",
8880 			prog->name, prog->sec_name);
8881 		return -EINVAL;
8882 	case BPF_PROG_TYPE_STRUCT_OPS:
8883 		if (prog->attach_btf_id == 0) {
8884 			pr_warn("prog '%s': SEC(\"struct_ops\") program isn't referenced anywhere, did you forget to use it?\n",
8885 				prog->name);
8886 			return -EINVAL;
8887 		}
8888 		break;
8889 	default:
8890 		break;
8891 	}
8892 
8893 	if (!insns || !insns_cnt)
8894 		return -EINVAL;
8895 
8896 	if (kernel_supports(obj, FEAT_PROG_NAME))
8897 		prog_name = prog->name;
8898 	load_attr.attach_prog_fd = prog->attach_prog_fd;
8899 	load_attr.attach_btf_obj_fd = prog->attach_btf_obj_fd;
8900 	load_attr.attach_btf_id = prog->attach_btf_id;
8901 	load_attr.kern_version = kern_version;
8902 	load_attr.prog_ifindex = prog->prog_ifindex;
8903 	load_attr.expected_attach_type = prog->expected_attach_type;
8904 
8905 	/* specify func_info/line_info only if kernel supports them */
8906 	if (obj->btf && btf__fd(obj->btf) >= 0 && kernel_supports(obj, FEAT_BTF_FUNC)) {
8907 		load_attr.prog_btf_fd = btf__fd(obj->btf);
8908 		load_attr.func_info = prog->func_info;
8909 		load_attr.func_info_rec_size = prog->func_info_rec_size;
8910 		load_attr.func_info_cnt = prog->func_info_cnt;
8911 		load_attr.line_info = prog->line_info;
8912 		load_attr.line_info_rec_size = prog->line_info_rec_size;
8913 		load_attr.line_info_cnt = prog->line_info_cnt;
8914 	}
8915 	load_attr.log_level = log_level;
8916 	load_attr.prog_flags = prog->prog_flags;
8917 	/* the program accesses its data in arena through plain numbers */
8918 	if (obj->data_in_arena)
8919 		load_attr.prog_flags |= BPF_F_ARENA_SCALAR;
8920 	load_attr.fd_array = obj->fd_array;
8921 	err = bpf_object__bind_arena(obj, prog, &load_attr);
8922 	if (err)
8923 		return err;
8924 
8925 	load_attr.token_fd = obj->token_fd;
8926 	if (obj->token_fd)
8927 		load_attr.prog_flags |= BPF_F_TOKEN_FD;
8928 
8929 	/* adjust load_attr if sec_def provides custom preload callback */
8930 	if (prog->sec_def && prog->sec_def->prog_prepare_load_fn) {
8931 		err = prog->sec_def->prog_prepare_load_fn(prog, &load_attr, prog->sec_def->cookie);
8932 		if (err < 0) {
8933 			pr_warn("prog '%s': failed to prepare load attributes: %s\n",
8934 				prog->name, errstr(err));
8935 			return err;
8936 		}
8937 		insns = prog->insns;
8938 		insns_cnt = prog->insns_cnt;
8939 	}
8940 
8941 	if (obj->gen_loader) {
8942 		bpf_gen__prog_load(obj->gen_loader, prog->type, prog->name,
8943 				   license, insns, insns_cnt, &load_attr,
8944 				   prog - obj->programs);
8945 		*prog_fd = -1;
8946 		return 0;
8947 	}
8948 
8949 retry_load:
8950 	/* if log_level is zero, we don't request logs initially even if
8951 	 * custom log_buf is specified; if the program load fails, then we'll
8952 	 * bump log_level to 1 and use either custom log_buf or we'll allocate
8953 	 * our own and retry the load to get details on what failed
8954 	 */
8955 	if (log_level) {
8956 		if (prog->log_buf) {
8957 			log_buf = prog->log_buf;
8958 			log_buf_size = prog->log_size;
8959 			own_log_buf = false;
8960 		} else if (obj->log_buf) {
8961 			log_buf = obj->log_buf;
8962 			log_buf_size = obj->log_size;
8963 			own_log_buf = false;
8964 		} else {
8965 			log_buf_size = max((size_t)BPF_LOG_BUF_SIZE, log_buf_size * 2);
8966 			tmp = realloc(log_buf, log_buf_size);
8967 			if (!tmp) {
8968 				ret = -ENOMEM;
8969 				goto out;
8970 			}
8971 			log_buf = tmp;
8972 			log_buf[0] = '\0';
8973 			own_log_buf = true;
8974 		}
8975 	}
8976 
8977 	load_attr.log_buf = log_buf;
8978 	load_attr.log_size = log_buf_size;
8979 	load_attr.log_level = log_level;
8980 
8981 	ret = bpf_prog_load(prog->type, prog_name, license, insns, insns_cnt, &load_attr);
8982 	if (ret >= 0) {
8983 		if (log_level && own_log_buf) {
8984 			pr_debug("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
8985 				 prog->name, log_buf);
8986 		}
8987 
8988 		if (obj->has_rodata && kernel_supports(obj, FEAT_PROG_BIND_MAP)) {
8989 			struct bpf_map *map;
8990 			int i;
8991 
8992 			for (i = 0; i < obj->nr_maps; i++) {
8993 				map = &prog->obj->maps[i];
8994 				if (map->libbpf_type != LIBBPF_MAP_RODATA || map->in_arena)
8995 					continue;
8996 
8997 				if (bpf_prog_bind_map(ret, map->fd, NULL)) {
8998 					pr_warn("prog '%s': failed to bind map '%s': %s\n",
8999 						prog->name, map->real_name, errstr(errno));
9000 					/* Don't fail hard if can't bind rodata. */
9001 				}
9002 			}
9003 		}
9004 
9005 		*prog_fd = ret;
9006 		ret = 0;
9007 		goto out;
9008 	}
9009 
9010 	if (log_level == 0) {
9011 		log_level = 1;
9012 		goto retry_load;
9013 	}
9014 	/* On ENOSPC, increase log buffer size and retry, unless custom
9015 	 * log_buf is specified.
9016 	 * Be careful to not overflow u32, though. Kernel's log buf size limit
9017 	 * isn't part of UAPI so it can always be bumped to full 4GB. So don't
9018 	 * multiply by 2 unless we are sure we'll fit within 32 bits.
9019 	 * Currently, we'll get -EINVAL when we reach (UINT_MAX >> 2).
9020 	 */
9021 	if (own_log_buf && errno == ENOSPC && log_buf_size <= UINT_MAX / 2)
9022 		goto retry_load;
9023 
9024 	ret = -errno;
9025 
9026 	/* post-process verifier log to improve error descriptions */
9027 	fixup_verifier_log(prog, log_buf, log_buf_size);
9028 
9029 	pr_warn("prog '%s': BPF program load failed: %s\n", prog->name, errstr(errno));
9030 	pr_perm_msg(ret);
9031 
9032 	if (own_log_buf && log_buf && log_buf[0] != '\0') {
9033 		pr_warn("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
9034 			prog->name, log_buf);
9035 	}
9036 
9037 out:
9038 	if (own_log_buf)
9039 		free(log_buf);
9040 	return ret;
9041 }
9042 
9043 static char *find_prev_line(char *buf, char *cur)
9044 {
9045 	char *p;
9046 
9047 	if (cur == buf) /* end of a log buf */
9048 		return NULL;
9049 
9050 	p = cur - 1;
9051 	while (p - 1 >= buf && *(p - 1) != '\n')
9052 		p--;
9053 
9054 	return p;
9055 }
9056 
9057 static void patch_log(char *buf, size_t buf_sz, size_t log_sz,
9058 		      char *orig, size_t orig_sz, const char *patch)
9059 {
9060 	/* size of the remaining log content to the right from the to-be-replaced part */
9061 	size_t rem_sz = (buf + log_sz) - (orig + orig_sz);
9062 	size_t patch_sz = strlen(patch);
9063 
9064 	if (patch_sz != orig_sz) {
9065 		/* If patch line(s) are longer than original piece of verifier log,
9066 		 * shift log contents by (patch_sz - orig_sz) bytes to the right
9067 		 * starting from after to-be-replaced part of the log.
9068 		 *
9069 		 * If patch line(s) are shorter than original piece of verifier log,
9070 		 * shift log contents by (orig_sz - patch_sz) bytes to the left
9071 		 * starting from after to-be-replaced part of the log
9072 		 *
9073 		 * We need to be careful about not overflowing available
9074 		 * buf_sz capacity. If that's the case, we'll truncate the end
9075 		 * of the original log, as necessary.
9076 		 */
9077 		if (patch_sz > orig_sz) {
9078 			if (orig + patch_sz >= buf + buf_sz) {
9079 				/* patch is big enough to cover remaining space completely */
9080 				patch_sz -= (orig + patch_sz) - (buf + buf_sz) + 1;
9081 				rem_sz = 0;
9082 			} else if (patch_sz - orig_sz > buf_sz - log_sz) {
9083 				/* patch causes part of remaining log to be truncated */
9084 				rem_sz -= (patch_sz - orig_sz) - (buf_sz - log_sz);
9085 			}
9086 		}
9087 		/* shift remaining log to the right by calculated amount */
9088 		memmove(orig + patch_sz, orig + orig_sz, rem_sz);
9089 	}
9090 
9091 	memcpy(orig, patch, patch_sz);
9092 }
9093 
9094 static void fixup_log_failed_core_relo(struct bpf_program *prog,
9095 				       char *buf, size_t buf_sz, size_t log_sz,
9096 				       char *line1, char *line2, char *line3)
9097 {
9098 	/* Expected log for failed and not properly guarded CO-RE relocation:
9099 	 * line1 -> 123: (85) call unknown#195896080
9100 	 * line2 -> invalid func unknown#195896080
9101 	 * line3 -> <anything else or end of buffer>
9102 	 *
9103 	 * "123" is the index of the instruction that was poisoned. We extract
9104 	 * instruction index to find corresponding CO-RE relocation and
9105 	 * replace this part of the log with more relevant information about
9106 	 * failed CO-RE relocation.
9107 	 */
9108 	const struct bpf_core_relo *relo;
9109 	struct bpf_core_spec spec;
9110 	char patch[512], spec_buf[256];
9111 	int insn_idx, err, spec_len;
9112 
9113 	if (sscanf(line1, "%d: (%*d) call unknown#195896080\n", &insn_idx) != 1)
9114 		return;
9115 
9116 	relo = find_relo_core(prog, insn_idx);
9117 	if (!relo)
9118 		return;
9119 
9120 	err = bpf_core_parse_spec(prog->name, prog->obj->btf, relo, &spec);
9121 	if (err)
9122 		return;
9123 
9124 	spec_len = bpf_core_format_spec(spec_buf, sizeof(spec_buf), &spec);
9125 	snprintf(patch, sizeof(patch),
9126 		 "%d: <invalid CO-RE relocation>\n"
9127 		 "failed to resolve CO-RE relocation %s%s\n",
9128 		 insn_idx, spec_buf, spec_len >= sizeof(spec_buf) ? "..." : "");
9129 
9130 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
9131 }
9132 
9133 static void fixup_log_missing_map_load(struct bpf_program *prog,
9134 				       char *buf, size_t buf_sz, size_t log_sz,
9135 				       char *line1, char *line2, char *line3)
9136 {
9137 	/* Expected log for failed and not properly guarded map reference:
9138 	 * line1 -> 123: (85) call unknown#2001000345
9139 	 * line2 -> invalid func unknown#2001000345
9140 	 * line3 -> <anything else or end of buffer>
9141 	 *
9142 	 * "123" is the index of the instruction that was poisoned.
9143 	 * "345" in "2001000345" is a map index in obj->maps to fetch map name.
9144 	 */
9145 	struct bpf_object *obj = prog->obj;
9146 	const struct bpf_map *map;
9147 	int insn_idx, map_idx;
9148 	char patch[128];
9149 
9150 	if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &map_idx) != 2)
9151 		return;
9152 
9153 	map_idx -= POISON_LDIMM64_MAP_BASE;
9154 	if (map_idx < 0 || map_idx >= obj->nr_maps)
9155 		return;
9156 	map = &obj->maps[map_idx];
9157 
9158 	snprintf(patch, sizeof(patch),
9159 		 "%d: <invalid BPF map reference>\n"
9160 		 "BPF map '%s' is referenced but wasn't created\n",
9161 		 insn_idx, map->name);
9162 
9163 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
9164 }
9165 
9166 static void fixup_log_missing_kfunc_call(struct bpf_program *prog,
9167 					 char *buf, size_t buf_sz, size_t log_sz,
9168 					 char *line1, char *line2, char *line3)
9169 {
9170 	/* Expected log for failed and not properly guarded kfunc call:
9171 	 * line1 -> 123: (85) call unknown#2002000345
9172 	 * line2 -> invalid func unknown#2002000345
9173 	 * line3 -> <anything else or end of buffer>
9174 	 *
9175 	 * "123" is the index of the instruction that was poisoned.
9176 	 * "345" in "2002000345" is an extern index in obj->externs to fetch kfunc name.
9177 	 */
9178 	struct bpf_object *obj = prog->obj;
9179 	const struct extern_desc *ext;
9180 	int insn_idx, ext_idx;
9181 	char patch[128];
9182 
9183 	if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &ext_idx) != 2)
9184 		return;
9185 
9186 	ext_idx -= POISON_CALL_KFUNC_BASE;
9187 	if (ext_idx < 0 || ext_idx >= obj->nr_extern)
9188 		return;
9189 	ext = &obj->externs[ext_idx];
9190 
9191 	snprintf(patch, sizeof(patch),
9192 		 "%d: <invalid kfunc call>\n"
9193 		 "kfunc '%s' is referenced but wasn't resolved\n",
9194 		 insn_idx, ext->name);
9195 
9196 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
9197 }
9198 
9199 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz)
9200 {
9201 	/* look for familiar error patterns in last N lines of the log */
9202 	const size_t max_last_line_cnt = 10;
9203 	char *prev_line, *cur_line, *next_line;
9204 	size_t log_sz;
9205 	int i;
9206 
9207 	if (!buf)
9208 		return;
9209 
9210 	log_sz = strlen(buf) + 1;
9211 	next_line = buf + log_sz - 1;
9212 
9213 	for (i = 0; i < max_last_line_cnt; i++, next_line = cur_line) {
9214 		cur_line = find_prev_line(buf, next_line);
9215 		if (!cur_line)
9216 			return;
9217 
9218 		if (str_has_pfx(cur_line, "invalid func unknown#195896080\n")) {
9219 			prev_line = find_prev_line(buf, cur_line);
9220 			if (!prev_line)
9221 				continue;
9222 
9223 			/* failed CO-RE relocation case */
9224 			fixup_log_failed_core_relo(prog, buf, buf_sz, log_sz,
9225 						   prev_line, cur_line, next_line);
9226 			return;
9227 		} else if (str_has_pfx(cur_line, "invalid func unknown#"POISON_LDIMM64_MAP_PFX)) {
9228 			prev_line = find_prev_line(buf, cur_line);
9229 			if (!prev_line)
9230 				continue;
9231 
9232 			/* reference to uncreated BPF map */
9233 			fixup_log_missing_map_load(prog, buf, buf_sz, log_sz,
9234 						   prev_line, cur_line, next_line);
9235 			return;
9236 		} else if (str_has_pfx(cur_line, "invalid func unknown#"POISON_CALL_KFUNC_PFX)) {
9237 			prev_line = find_prev_line(buf, cur_line);
9238 			if (!prev_line)
9239 				continue;
9240 
9241 			/* reference to unresolved kfunc */
9242 			fixup_log_missing_kfunc_call(prog, buf, buf_sz, log_sz,
9243 						     prev_line, cur_line, next_line);
9244 			return;
9245 		}
9246 	}
9247 }
9248 
9249 static int bpf_program_record_relos(struct bpf_program *prog)
9250 {
9251 	struct bpf_object *obj = prog->obj;
9252 	int i;
9253 
9254 	for (i = 0; i < prog->nr_reloc; i++) {
9255 		struct reloc_desc *relo = &prog->reloc_desc[i];
9256 		struct extern_desc *ext = &obj->externs[relo->ext_idx];
9257 		int kind;
9258 
9259 		switch (relo->type) {
9260 		case RELO_EXTERN_LD64:
9261 			if (ext->type != EXT_KSYM)
9262 				continue;
9263 			kind = btf_is_var(btf__type_by_id(obj->btf, ext->btf_id)) ?
9264 				BTF_KIND_VAR : BTF_KIND_FUNC;
9265 			bpf_gen__record_extern(obj->gen_loader, ext->name,
9266 					       ext->is_weak, !ext->ksym.type_id,
9267 					       true, kind, relo->insn_idx);
9268 			break;
9269 		case RELO_EXTERN_CALL:
9270 			bpf_gen__record_extern(obj->gen_loader, ext->name,
9271 					       ext->is_weak, false, false, BTF_KIND_FUNC,
9272 					       relo->insn_idx);
9273 			break;
9274 		case RELO_CORE: {
9275 			struct bpf_core_relo cr = {
9276 				.insn_off = relo->insn_idx * 8,
9277 				.type_id = relo->core_relo->type_id,
9278 				.access_str_off = relo->core_relo->access_str_off,
9279 				.kind = relo->core_relo->kind,
9280 			};
9281 
9282 			bpf_gen__record_relo_core(obj->gen_loader, &cr);
9283 			break;
9284 		}
9285 		default:
9286 			continue;
9287 		}
9288 	}
9289 	return 0;
9290 }
9291 
9292 static int
9293 bpf_object__load_progs(struct bpf_object *obj, int log_level)
9294 {
9295 	struct bpf_program *prog;
9296 	size_t i;
9297 	int err;
9298 
9299 	for (i = 0; i < obj->nr_programs; i++) {
9300 		prog = &obj->programs[i];
9301 		if (prog_is_subprog(obj, prog))
9302 			continue;
9303 		if (!prog->autoload) {
9304 			pr_debug("prog '%s': skipped loading\n", prog->name);
9305 			continue;
9306 		}
9307 		prog->log_level |= log_level;
9308 
9309 		if (obj->gen_loader)
9310 			bpf_program_record_relos(prog);
9311 
9312 		err = bpf_object_load_prog(obj, prog, prog->insns, prog->insns_cnt,
9313 					   obj->license, obj->kern_version, &prog->fd);
9314 		if (err) {
9315 			pr_warn("prog '%s': failed to load: %s\n", prog->name, errstr(err));
9316 			return err;
9317 		}
9318 	}
9319 
9320 	bpf_object__free_relocs(obj);
9321 	return 0;
9322 }
9323 
9324 static int bpf_object_prepare_progs(struct bpf_object *obj)
9325 {
9326 	struct bpf_program *prog;
9327 	size_t i;
9328 	int err;
9329 
9330 	for (i = 0; i < obj->nr_programs; i++) {
9331 		prog = &obj->programs[i];
9332 		err = bpf_object__sanitize_prog(obj, prog);
9333 		if (err)
9334 			return err;
9335 	}
9336 	return 0;
9337 }
9338 
9339 static const struct bpf_sec_def *find_sec_def(const char *sec_name);
9340 
9341 static int bpf_object_init_progs(struct bpf_object *obj, const struct bpf_object_open_opts *opts)
9342 {
9343 	struct bpf_program *prog;
9344 	int err;
9345 
9346 	bpf_object__for_each_program(prog, obj) {
9347 		prog->sec_def = find_sec_def(prog->sec_name);
9348 		if (!prog->sec_def) {
9349 			/* couldn't guess, but user might manually specify */
9350 			pr_debug("prog '%s': unrecognized ELF section name '%s'\n",
9351 				prog->name, prog->sec_name);
9352 			continue;
9353 		}
9354 
9355 		prog->type = prog->sec_def->prog_type;
9356 		prog->expected_attach_type = prog->sec_def->expected_attach_type;
9357 
9358 		/* sec_def can have custom callback which should be called
9359 		 * after bpf_program is initialized to adjust its properties
9360 		 */
9361 		if (prog->sec_def->prog_setup_fn) {
9362 			err = prog->sec_def->prog_setup_fn(prog, prog->sec_def->cookie);
9363 			if (err < 0) {
9364 				pr_warn("prog '%s': failed to initialize: %s\n",
9365 					prog->name, errstr(err));
9366 				return err;
9367 			}
9368 		}
9369 	}
9370 
9371 	return 0;
9372 }
9373 
9374 static struct bpf_object *bpf_object_open(const char *path, const void *obj_buf, size_t obj_buf_sz,
9375 					  const char *obj_name,
9376 					  const struct bpf_object_open_opts *opts)
9377 {
9378 	const char *kconfig, *btf_tmp_path, *token_path;
9379 	size_t mod_allow_cnt, i, j;
9380 	const char **mod_allow;
9381 	struct bpf_object *obj;
9382 	int err;
9383 	char *log_buf;
9384 	size_t log_size;
9385 	__u32 log_level;
9386 
9387 	if (obj_buf && !obj_name)
9388 		return ERR_PTR(-EINVAL);
9389 
9390 	if (elf_version(EV_CURRENT) == EV_NONE) {
9391 		pr_warn("failed to init libelf for %s\n",
9392 			path ? : "(mem buf)");
9393 		return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
9394 	}
9395 
9396 	if (!OPTS_VALID(opts, bpf_object_open_opts))
9397 		return ERR_PTR(-EINVAL);
9398 
9399 	obj_name = OPTS_GET(opts, object_name, NULL) ?: obj_name;
9400 	if (obj_buf) {
9401 		path = obj_name;
9402 		pr_debug("loading object '%s' from buffer\n", obj_name);
9403 	} else {
9404 		pr_debug("loading object from %s\n", path);
9405 	}
9406 
9407 	log_buf = OPTS_GET(opts, kernel_log_buf, NULL);
9408 	log_size = OPTS_GET(opts, kernel_log_size, 0);
9409 	log_level = OPTS_GET(opts, kernel_log_level, 0);
9410 	if (log_size > UINT_MAX)
9411 		return ERR_PTR(-EINVAL);
9412 	if (log_size && !log_buf)
9413 		return ERR_PTR(-EINVAL);
9414 
9415 	token_path = OPTS_GET(opts, bpf_token_path, NULL);
9416 	/* if user didn't specify bpf_token_path explicitly, check if
9417 	 * LIBBPF_BPF_TOKEN_PATH envvar was set and treat it as bpf_token_path
9418 	 * option
9419 	 */
9420 	if (!token_path)
9421 		token_path = getenv("LIBBPF_BPF_TOKEN_PATH");
9422 	if (token_path && strlen(token_path) >= PATH_MAX)
9423 		return ERR_PTR(-ENAMETOOLONG);
9424 
9425 	mod_allow = OPTS_GET(opts, btf_module_allowlist, NULL);
9426 	mod_allow_cnt = OPTS_GET(opts, btf_module_allowlist_cnt, 0);
9427 
9428 	if (mod_allow_cnt > SSIZE_MAX || (!mod_allow && mod_allow_cnt > 0))
9429 		return ERR_PTR(-EINVAL);
9430 
9431 	for (i = 0; i < mod_allow_cnt; i++) {
9432 		if (!mod_allow[i] || !mod_allow[i][0])
9433 			return ERR_PTR(-EINVAL);
9434 
9435 		for (j = 0; j < i; j++) {
9436 			if (strcmp(mod_allow[i], mod_allow[j]) == 0)
9437 				return ERR_PTR(-EINVAL);
9438 		}
9439 	}
9440 
9441 	obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
9442 	if (IS_ERR(obj))
9443 		return obj;
9444 
9445 	obj->log_buf = log_buf;
9446 	obj->log_size = log_size;
9447 	obj->log_level = log_level;
9448 
9449 	if (token_path) {
9450 		obj->token_path = strdup(token_path);
9451 		if (!obj->token_path) {
9452 			err = -ENOMEM;
9453 			goto out;
9454 		}
9455 	}
9456 
9457 	btf_tmp_path = OPTS_GET(opts, btf_custom_path, NULL);
9458 	if (btf_tmp_path) {
9459 		if (strlen(btf_tmp_path) >= PATH_MAX) {
9460 			err = -ENAMETOOLONG;
9461 			goto out;
9462 		}
9463 		obj->btf_custom_path = strdup(btf_tmp_path);
9464 		if (!obj->btf_custom_path) {
9465 			err = -ENOMEM;
9466 			goto out;
9467 		}
9468 	}
9469 
9470 	kconfig = OPTS_GET(opts, kconfig, NULL);
9471 	if (kconfig) {
9472 		obj->kconfig = strdup(kconfig);
9473 		if (!obj->kconfig) {
9474 			err = -ENOMEM;
9475 			goto out;
9476 		}
9477 	}
9478 
9479 	obj->btf_module_allowlist_cnt = mod_allow ? mod_allow_cnt : -1;
9480 	if (mod_allow_cnt > 0) {
9481 		obj->btf_module_allowlist =
9482 			calloc(mod_allow_cnt, sizeof(*obj->btf_module_allowlist));
9483 		if (!obj->btf_module_allowlist) {
9484 			err = -ENOMEM;
9485 			goto out;
9486 		}
9487 
9488 		for (i = 0; i < mod_allow_cnt; i++) {
9489 			obj->btf_module_allowlist[i] = strdup(mod_allow[i]);
9490 			if (!obj->btf_module_allowlist[i]) {
9491 				err = -ENOMEM;
9492 				goto out;
9493 			}
9494 		}
9495 	}
9496 
9497 	err = bpf_object__elf_init(obj);
9498 	err = err ? : bpf_object__elf_collect(obj);
9499 	err = err ? : bpf_object__collect_externs(obj);
9500 	err = err ? : bpf_object_fixup_btf(obj);
9501 	err = err ? : bpf_object__init_maps(obj, opts);
9502 	err = err ? : bpf_object_init_progs(obj, opts);
9503 	err = err ? : bpf_object__collect_relos(obj);
9504 	if (err)
9505 		goto out;
9506 
9507 	bpf_object__elf_finish(obj);
9508 
9509 	return obj;
9510 out:
9511 	bpf_object__close(obj);
9512 	return ERR_PTR(err);
9513 }
9514 
9515 struct bpf_object *
9516 bpf_object__open_file(const char *path, const struct bpf_object_open_opts *opts)
9517 {
9518 	if (!path)
9519 		return libbpf_err_ptr(-EINVAL);
9520 
9521 	return libbpf_ptr(bpf_object_open(path, NULL, 0, NULL, opts));
9522 }
9523 
9524 struct bpf_object *bpf_object__open(const char *path)
9525 {
9526 	return bpf_object__open_file(path, NULL);
9527 }
9528 
9529 struct bpf_object *
9530 bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
9531 		     const struct bpf_object_open_opts *opts)
9532 {
9533 	char tmp_name[64];
9534 
9535 	if (!obj_buf || obj_buf_sz == 0)
9536 		return libbpf_err_ptr(-EINVAL);
9537 
9538 	/* create a (quite useless) default "name" for this memory buffer object */
9539 	snprintf(tmp_name, sizeof(tmp_name), "%lx-%zx", (unsigned long)obj_buf, obj_buf_sz);
9540 
9541 	return libbpf_ptr(bpf_object_open(NULL, obj_buf, obj_buf_sz, tmp_name, opts));
9542 }
9543 
9544 static int bpf_object_unload(struct bpf_object *obj)
9545 {
9546 	size_t i;
9547 
9548 	if (!obj)
9549 		return libbpf_err(-EINVAL);
9550 
9551 	for (i = 0; i < obj->nr_maps; i++) {
9552 		zclose(obj->maps[i].fd);
9553 		if (obj->maps[i].st_ops)
9554 			zfree(&obj->maps[i].st_ops->kern_vdata);
9555 	}
9556 
9557 	for (i = 0; i < obj->nr_programs; i++)
9558 		bpf_program__unload(&obj->programs[i]);
9559 
9560 	return 0;
9561 }
9562 
9563 static int bpf_object__sanitize_maps(struct bpf_object *obj)
9564 {
9565 	struct bpf_map *m;
9566 
9567 	bpf_object__for_each_map(m, obj) {
9568 		if (!bpf_map__is_internal(m))
9569 			continue;
9570 		if (!kernel_supports(obj, FEAT_ARRAY_MMAP))
9571 			m->def.map_flags &= ~BPF_F_MMAPABLE;
9572 	}
9573 
9574 	return 0;
9575 }
9576 
9577 typedef int (*kallsyms_cb_t)(unsigned long long sym_addr, char sym_type,
9578 			     const char *sym_name, void *ctx);
9579 
9580 static int libbpf_kallsyms_parse(kallsyms_cb_t cb, void *ctx)
9581 {
9582 	char sym_type, sym_name[500];
9583 	unsigned long long sym_addr;
9584 	int ret, err = 0;
9585 	FILE *f;
9586 
9587 	f = fopen("/proc/kallsyms", "re");
9588 	if (!f) {
9589 		err = -errno;
9590 		pr_warn("failed to open /proc/kallsyms: %s\n", errstr(err));
9591 		return err;
9592 	}
9593 
9594 	while (true) {
9595 		ret = fscanf(f, "%llx %c %499s%*[^\n]\n",
9596 			     &sym_addr, &sym_type, sym_name);
9597 		if (ret == EOF && feof(f))
9598 			break;
9599 		if (ret != 3) {
9600 			pr_warn("failed to read kallsyms entry: %d\n", ret);
9601 			err = -EINVAL;
9602 			break;
9603 		}
9604 
9605 		err = cb(sym_addr, sym_type, sym_name, ctx);
9606 		if (err)
9607 			break;
9608 	}
9609 
9610 	fclose(f);
9611 	return err;
9612 }
9613 
9614 static int kallsyms_cb(unsigned long long sym_addr, char sym_type,
9615 		       const char *sym_name, void *ctx)
9616 {
9617 	struct bpf_object *obj = ctx;
9618 	const struct btf_type *t;
9619 	struct extern_desc *ext;
9620 	const char *res;
9621 
9622 	res = strstr(sym_name, ".llvm.");
9623 	if (sym_type == 'd' && res)
9624 		ext = find_extern_by_name_with_len(obj, sym_name, res - sym_name);
9625 	else
9626 		ext = find_extern_by_name(obj, sym_name);
9627 	if (!ext || ext->type != EXT_KSYM)
9628 		return 0;
9629 
9630 	t = btf__type_by_id(obj->btf, ext->btf_id);
9631 	if (!btf_is_var(t))
9632 		return 0;
9633 
9634 	if (ext->is_set && ext->ksym.addr != sym_addr) {
9635 		pr_warn("extern (ksym) '%s': resolution is ambiguous: 0x%llx or 0x%llx\n",
9636 			sym_name, ext->ksym.addr, sym_addr);
9637 		return -EINVAL;
9638 	}
9639 	if (!ext->is_set) {
9640 		ext->is_set = true;
9641 		ext->ksym.addr = sym_addr;
9642 		pr_debug("extern (ksym) '%s': set to 0x%llx\n", sym_name, sym_addr);
9643 	}
9644 	return 0;
9645 }
9646 
9647 static int bpf_object__read_kallsyms_file(struct bpf_object *obj)
9648 {
9649 	return libbpf_kallsyms_parse(kallsyms_cb, obj);
9650 }
9651 
9652 static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
9653 			    __u16 kind, struct btf **res_btf,
9654 			    struct module_btf **res_mod_btf)
9655 {
9656 	struct module_btf *mod_btf;
9657 	struct btf *btf;
9658 	int i, id, err;
9659 
9660 	btf = obj->btf_vmlinux;
9661 	mod_btf = NULL;
9662 	id = btf__find_by_name_kind(btf, ksym_name, kind);
9663 
9664 	if (id == -ENOENT) {
9665 		err = load_module_btfs(obj);
9666 		if (err)
9667 			return err;
9668 
9669 		for (i = 0; i < obj->btf_module_cnt; i++) {
9670 			/* we assume module_btf's BTF FD is always >0 */
9671 			mod_btf = &obj->btf_modules[i];
9672 			btf = mod_btf->btf;
9673 			id = btf__find_by_name_kind_own(btf, ksym_name, kind);
9674 			if (id != -ENOENT)
9675 				break;
9676 		}
9677 	}
9678 	if (id <= 0)
9679 		return -ESRCH;
9680 
9681 	*res_btf = btf;
9682 	*res_mod_btf = mod_btf;
9683 	return id;
9684 }
9685 
9686 static int bpf_object__resolve_ksym_var_btf_id(struct bpf_object *obj,
9687 					       struct extern_desc *ext)
9688 {
9689 	const struct btf_type *targ_var, *targ_type;
9690 	__u32 targ_type_id, local_type_id;
9691 	struct module_btf *mod_btf = NULL;
9692 	const char *targ_var_name;
9693 	struct btf *btf = NULL;
9694 	int id, err;
9695 
9696 	id = find_ksym_btf_id(obj, ext->name, BTF_KIND_VAR, &btf, &mod_btf);
9697 	if (id < 0) {
9698 		if (id == -ESRCH && ext->is_weak)
9699 			return 0;
9700 		pr_warn("extern (var ksym) '%s': not found in kernel BTF\n",
9701 			ext->name);
9702 		return id;
9703 	}
9704 
9705 	/* find local type_id */
9706 	local_type_id = ext->ksym.type_id;
9707 
9708 	/* find target type_id */
9709 	targ_var = btf__type_by_id(btf, id);
9710 	targ_var_name = btf__name_by_offset(btf, targ_var->name_off);
9711 	targ_type = skip_mods_and_typedefs(btf, targ_var->type, &targ_type_id);
9712 
9713 	err = bpf_core_types_are_compat(obj->btf, local_type_id,
9714 					btf, targ_type_id);
9715 	if (err <= 0) {
9716 		const struct btf_type *local_type;
9717 		const char *targ_name, *local_name;
9718 
9719 		local_type = btf__type_by_id(obj->btf, local_type_id);
9720 		local_name = btf__name_by_offset(obj->btf, local_type->name_off);
9721 		targ_name = btf__name_by_offset(btf, targ_type->name_off);
9722 
9723 		pr_warn("extern (var ksym) '%s': incompatible types, expected [%u] %s %s, but kernel has [%u] %s %s\n",
9724 			ext->name, local_type_id,
9725 			btf_kind_str(local_type), local_name, targ_type_id,
9726 			btf_kind_str(targ_type), targ_name);
9727 		return -EINVAL;
9728 	}
9729 
9730 	ext->is_set = true;
9731 	ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
9732 	ext->ksym.kernel_btf_id = id;
9733 	pr_debug("extern (var ksym) '%s': resolved to [%d] %s %s\n",
9734 		 ext->name, id, btf_kind_str(targ_var), targ_var_name);
9735 
9736 	return 0;
9737 }
9738 
9739 static int bpf_object__resolve_ksym_func_btf_id(struct bpf_object *obj,
9740 						struct extern_desc *ext)
9741 {
9742 	int local_func_proto_id, kfunc_proto_id, kfunc_id;
9743 	struct module_btf *mod_btf = NULL;
9744 	const struct btf_type *kern_func;
9745 	struct btf *kern_btf = NULL;
9746 	int ret;
9747 
9748 	local_func_proto_id = ext->ksym.type_id;
9749 
9750 	kfunc_id = find_ksym_btf_id(obj, ext->essent_name ?: ext->name, BTF_KIND_FUNC, &kern_btf,
9751 				    &mod_btf);
9752 	if (kfunc_id < 0) {
9753 		if (kfunc_id == -ESRCH && ext->is_weak)
9754 			return 0;
9755 		pr_warn("extern (func ksym) '%s': not found in kernel or module BTFs\n",
9756 			ext->name);
9757 		return kfunc_id;
9758 	}
9759 
9760 	kern_func = btf__type_by_id(kern_btf, kfunc_id);
9761 	kfunc_proto_id = kern_func->type;
9762 
9763 	ret = bpf_core_types_are_compat(obj->btf, local_func_proto_id,
9764 					kern_btf, kfunc_proto_id);
9765 	if (ret <= 0) {
9766 		if (ext->is_weak)
9767 			return 0;
9768 
9769 		pr_warn("extern (func ksym) '%s': func_proto [%d] incompatible with %s [%d]\n",
9770 			ext->name, local_func_proto_id,
9771 			mod_btf ? mod_btf->name : "vmlinux", kfunc_proto_id);
9772 		return -EINVAL;
9773 	}
9774 
9775 	/* set index for module BTF fd in fd_array, if unset */
9776 	if (mod_btf && !mod_btf->fd_array_idx) {
9777 		/* insn->off is s16 */
9778 		if (obj->fd_array_used == INT16_MAX) {
9779 			pr_warn("extern (func ksym) '%s': module BTF fd index %d too big to fit in bpf_insn offset\n",
9780 				ext->name, mod_btf->fd_array_idx);
9781 			return -E2BIG;
9782 		}
9783 		/* Cannot use index 0 for module BTF fd */
9784 		if (!obj->fd_array_used)
9785 			obj->fd_array_used = 1;
9786 
9787 		ret = libbpf_ensure_mem((void **)&obj->fd_array, &obj->fd_array_cap, sizeof(int),
9788 					obj->fd_array_used + 1);
9789 		if (ret)
9790 			return ret;
9791 		mod_btf->fd_array_idx = obj->fd_array_used;
9792 		/* we assume module BTF FD is always >0 */
9793 		obj->fd_array[obj->fd_array_used++] = mod_btf->fd;
9794 	}
9795 
9796 	ext->is_set = true;
9797 	ext->ksym.kernel_btf_id = kfunc_id;
9798 	ext->ksym.btf_fd_idx = mod_btf ? mod_btf->fd_array_idx : 0;
9799 	/* Also set kernel_btf_obj_fd to make sure that bpf_object__relocate_data()
9800 	 * populates FD into ld_imm64 insn when it's used to point to kfunc.
9801 	 * {kernel_btf_id, btf_fd_idx} -> fixup bpf_call.
9802 	 * {kernel_btf_id, kernel_btf_obj_fd} -> fixup ld_imm64.
9803 	 */
9804 	ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
9805 	pr_debug("extern (func ksym) '%s': resolved to %s [%d]\n",
9806 		 ext->name, mod_btf ? mod_btf->name : "vmlinux", kfunc_id);
9807 
9808 	return 0;
9809 }
9810 
9811 static int bpf_object__resolve_ksyms_btf_id(struct bpf_object *obj)
9812 {
9813 	const struct btf_type *t;
9814 	struct extern_desc *ext;
9815 	int i, err;
9816 
9817 	for (i = 0; i < obj->nr_extern; i++) {
9818 		ext = &obj->externs[i];
9819 		if (ext->type != EXT_KSYM || !ext->ksym.type_id)
9820 			continue;
9821 
9822 		if (obj->gen_loader) {
9823 			ext->is_set = true;
9824 			ext->ksym.kernel_btf_obj_fd = 0;
9825 			ext->ksym.kernel_btf_id = 0;
9826 			continue;
9827 		}
9828 		t = btf__type_by_id(obj->btf, ext->btf_id);
9829 		if (btf_is_var(t))
9830 			err = bpf_object__resolve_ksym_var_btf_id(obj, ext);
9831 		else
9832 			err = bpf_object__resolve_ksym_func_btf_id(obj, ext);
9833 		if (err)
9834 			return err;
9835 	}
9836 	return 0;
9837 }
9838 
9839 static int bpf_object__resolve_externs(struct bpf_object *obj,
9840 				       const char *extra_kconfig)
9841 {
9842 	bool need_config = false, need_kallsyms = false;
9843 	bool need_vmlinux_btf = false;
9844 	struct extern_desc *ext;
9845 	void *kcfg_data = NULL;
9846 	int err, i;
9847 
9848 	if (obj->nr_extern == 0)
9849 		return 0;
9850 
9851 	if (obj->kconfig_map_idx >= 0)
9852 		kcfg_data = obj->maps[obj->kconfig_map_idx].mmaped;
9853 
9854 	for (i = 0; i < obj->nr_extern; i++) {
9855 		ext = &obj->externs[i];
9856 
9857 		if (ext->type == EXT_KSYM) {
9858 			if (ext->ksym.type_id)
9859 				need_vmlinux_btf = true;
9860 			else
9861 				need_kallsyms = true;
9862 			continue;
9863 		} else if (ext->type == EXT_KCFG) {
9864 			void *ext_ptr = kcfg_data + ext->kcfg.data_off;
9865 			__u64 value = 0;
9866 
9867 			/* Kconfig externs need actual /proc/config.gz */
9868 			if (str_has_pfx(ext->name, "CONFIG_")) {
9869 				need_config = true;
9870 				continue;
9871 			}
9872 
9873 			/* Virtual kcfg externs are customly handled by libbpf */
9874 			if (strcmp(ext->name, "LINUX_KERNEL_VERSION") == 0) {
9875 				value = get_kernel_version();
9876 				if (!value) {
9877 					pr_warn("extern (kcfg) '%s': failed to get kernel version\n", ext->name);
9878 					return -EINVAL;
9879 				}
9880 			} else if (strcmp(ext->name, "LINUX_HAS_BPF_COOKIE") == 0) {
9881 				value = kernel_supports(obj, FEAT_BPF_COOKIE);
9882 			} else if (strcmp(ext->name, "LINUX_HAS_SYSCALL_WRAPPER") == 0) {
9883 				value = kernel_supports(obj, FEAT_SYSCALL_WRAPPER);
9884 			} else if (!str_has_pfx(ext->name, "LINUX_") || !ext->is_weak) {
9885 				/* Currently libbpf supports only CONFIG_ and LINUX_ prefixed
9886 				 * __kconfig externs, where LINUX_ ones are virtual and filled out
9887 				 * customly by libbpf (their values don't come from Kconfig).
9888 				 * If LINUX_xxx variable is not recognized by libbpf, but is marked
9889 				 * __weak, it defaults to zero value, just like for CONFIG_xxx
9890 				 * externs.
9891 				 */
9892 				pr_warn("extern (kcfg) '%s': unrecognized virtual extern\n", ext->name);
9893 				return -EINVAL;
9894 			}
9895 
9896 			err = set_kcfg_value_num(ext, ext_ptr, value);
9897 			if (err)
9898 				return err;
9899 			pr_debug("extern (kcfg) '%s': set to 0x%llx\n",
9900 				 ext->name, (unsigned long long)value);
9901 		} else {
9902 			pr_warn("extern '%s': unrecognized extern kind\n", ext->name);
9903 			return -EINVAL;
9904 		}
9905 	}
9906 	if (need_config && extra_kconfig) {
9907 		err = bpf_object__read_kconfig_mem(obj, extra_kconfig, kcfg_data);
9908 		if (err)
9909 			return -EINVAL;
9910 		need_config = false;
9911 		for (i = 0; i < obj->nr_extern; i++) {
9912 			ext = &obj->externs[i];
9913 			if (ext->type == EXT_KCFG && !ext->is_set) {
9914 				need_config = true;
9915 				break;
9916 			}
9917 		}
9918 	}
9919 	if (need_config) {
9920 		err = bpf_object__read_kconfig_file(obj, kcfg_data);
9921 		if (err)
9922 			return -EINVAL;
9923 	}
9924 	if (need_kallsyms) {
9925 		err = bpf_object__read_kallsyms_file(obj);
9926 		if (err)
9927 			return -EINVAL;
9928 	}
9929 	if (need_vmlinux_btf) {
9930 		err = bpf_object__resolve_ksyms_btf_id(obj);
9931 		if (err)
9932 			return -EINVAL;
9933 	}
9934 	for (i = 0; i < obj->nr_extern; i++) {
9935 		ext = &obj->externs[i];
9936 
9937 		if (!ext->is_set && !ext->is_weak) {
9938 			pr_warn("extern '%s' (strong): not resolved\n", ext->name);
9939 			return -ESRCH;
9940 		} else if (!ext->is_set) {
9941 			pr_debug("extern '%s' (weak): not resolved, defaulting to zero\n",
9942 				 ext->name);
9943 		}
9944 	}
9945 
9946 	return 0;
9947 }
9948 
9949 static void bpf_map_prepare_vdata(const struct bpf_map *map)
9950 {
9951 	const struct btf_type *type;
9952 	struct bpf_struct_ops *st_ops;
9953 	__u32 i;
9954 
9955 	st_ops = map->st_ops;
9956 	type = btf__type_by_id(map->obj->btf, st_ops->type_id);
9957 	for (i = 0; i < btf_vlen(type); i++) {
9958 		struct bpf_program *prog = st_ops->progs[i];
9959 		void *kern_data;
9960 		int prog_fd;
9961 
9962 		if (!prog)
9963 			continue;
9964 
9965 		prog_fd = bpf_program__fd(prog);
9966 		kern_data = st_ops->kern_vdata + st_ops->kern_func_off[i];
9967 		*(unsigned long *)kern_data = prog_fd;
9968 	}
9969 }
9970 
9971 static int bpf_object_prepare_struct_ops(struct bpf_object *obj)
9972 {
9973 	struct bpf_map *map;
9974 	int i;
9975 
9976 	for (i = 0; i < obj->nr_maps; i++) {
9977 		map = &obj->maps[i];
9978 
9979 		if (!bpf_map__is_struct_ops(map))
9980 			continue;
9981 
9982 		if (!map->autocreate)
9983 			continue;
9984 
9985 		bpf_map_prepare_vdata(map);
9986 	}
9987 
9988 	return 0;
9989 }
9990 
9991 static void bpf_object_unpin(struct bpf_object *obj)
9992 {
9993 	int i;
9994 
9995 	/* unpin any maps that were auto-pinned during load */
9996 	for (i = 0; i < obj->nr_maps; i++)
9997 		if (obj->maps[i].pinned && !obj->maps[i].reused)
9998 			bpf_map__unpin(&obj->maps[i], NULL);
9999 }
10000 
10001 static void bpf_object_cleanup_btf(struct bpf_object *obj)
10002 {
10003 	int i;
10004 
10005 	/* clean up module BTFs */
10006 	for (i = 0; i < obj->btf_module_cnt; i++) {
10007 		close(obj->btf_modules[i].fd);
10008 		btf__free(obj->btf_modules[i].btf);
10009 		free(obj->btf_modules[i].name);
10010 	}
10011 	obj->btf_module_cnt = 0;
10012 	obj->btf_module_cap = 0;
10013 	obj->btf_modules_loaded = false;
10014 	zfree(&obj->btf_modules);
10015 
10016 	/* clean up vmlinux BTF */
10017 	btf__free(obj->btf_vmlinux);
10018 	obj->btf_vmlinux = NULL;
10019 }
10020 
10021 static void bpf_object_post_load_cleanup(struct bpf_object *obj)
10022 {
10023 	/* clean up fd_array, and the slots handed out with it */
10024 	zfree(&obj->fd_array);
10025 	obj->fd_array_cap = 0;
10026 	obj->fd_array_used = 0;
10027 
10028 	/* clean up BTF */
10029 	bpf_object_cleanup_btf(obj);
10030 }
10031 
10032 static int bpf_object_prepare(struct bpf_object *obj, const char *target_btf_path)
10033 {
10034 	int err;
10035 
10036 	if (obj->state >= OBJ_PREPARED) {
10037 		pr_warn("object '%s': prepare loading can't be attempted twice\n", obj->name);
10038 		return -EINVAL;
10039 	}
10040 
10041 	err = bpf_object_prepare_token(obj);
10042 	err = err ? : bpf_object__probe_loading(obj);
10043 	err = err ? : bpf_object__load_vmlinux_btf(obj, false);
10044 	err = err ? : bpf_object__resolve_externs(obj, obj->kconfig);
10045 	err = err ? : bpf_object__sanitize_maps(obj);
10046 	err = err ? : bpf_object__init_kern_struct_ops_maps(obj);
10047 	err = err ? : bpf_object_adjust_struct_ops_autoload(obj);
10048 	err = err ? : bpf_object__relocate(obj, obj->btf_custom_path ? : target_btf_path);
10049 	err = err ? : bpf_object__sanitize_and_load_btf(obj);
10050 	err = err ? : bpf_object__create_maps(obj);
10051 	err = err ? : bpf_object_prepare_progs(obj);
10052 
10053 	if (err) {
10054 		bpf_object_unpin(obj);
10055 		bpf_object_unload(obj);
10056 		obj->state = OBJ_LOADED;
10057 		return err;
10058 	}
10059 
10060 	obj->state = OBJ_PREPARED;
10061 	return 0;
10062 }
10063 
10064 static int bpf_object_load(struct bpf_object *obj, int extra_log_level, const char *target_btf_path)
10065 {
10066 	int err;
10067 
10068 	if (!obj)
10069 		return libbpf_err(-EINVAL);
10070 
10071 	if (obj->state >= OBJ_LOADED) {
10072 		pr_warn("object '%s': load can't be attempted twice\n", obj->name);
10073 		return libbpf_err(-EINVAL);
10074 	}
10075 
10076 	/* Disallow kernel loading programs of non-native endianness but
10077 	 * permit cross-endian creation of "light skeleton".
10078 	 */
10079 	if (obj->gen_loader) {
10080 		int nr_func_ptr_maps = 0, nr_progs = 0, i;
10081 		bool text_has_callx = false;
10082 
10083 		/*
10084 		 * Every program that has callx may get a copy of every map with
10085 		 * pointers to functions. Which functions a program calls is not
10086 		 * known yet. Any of them may call the ones that have callx.
10087 		 */
10088 		for (i = 0; i < obj->nr_maps; i++)
10089 			if (obj->maps[i].autocreate && obj->maps[i].func_ptr_cnt)
10090 				nr_func_ptr_maps++;
10091 		for (i = 0; i < obj->nr_programs; i++)
10092 			if (prog_is_subprog(obj, &obj->programs[i]) &&
10093 			    prog_has_callx(&obj->programs[i]))
10094 				text_has_callx = true;
10095 		for (i = 0; i < obj->nr_programs; i++)
10096 			if (obj->programs[i].autoload && !prog_is_subprog(obj, &obj->programs[i]) &&
10097 			    (text_has_callx || prog_has_callx(&obj->programs[i])))
10098 				nr_progs++;
10099 		bpf_gen__init(obj->gen_loader, obj->log_level | extra_log_level,
10100 			      obj->nr_programs, obj->nr_maps, nr_func_ptr_maps * nr_progs);
10101 	} else if (!is_native_endianness(obj)) {
10102 		pr_warn("object '%s': loading non-native endianness is unsupported\n", obj->name);
10103 		return libbpf_err(-LIBBPF_ERRNO__ENDIAN);
10104 	}
10105 
10106 	if (obj->state < OBJ_PREPARED) {
10107 		err = bpf_object_prepare(obj, target_btf_path);
10108 		if (err)
10109 			return libbpf_err(err);
10110 	}
10111 	err = bpf_object__load_progs(obj, extra_log_level);
10112 	err = err ? : bpf_object_init_prog_arrays(obj);
10113 	err = err ? : bpf_object_prepare_struct_ops(obj);
10114 
10115 	if (obj->gen_loader) {
10116 		/* reset FDs */
10117 		if (obj->btf)
10118 			btf__set_fd(obj->btf, -1);
10119 		if (!err)
10120 			err = bpf_gen__finish(obj->gen_loader, obj->nr_programs, obj->nr_maps);
10121 	}
10122 
10123 	bpf_object_post_load_cleanup(obj);
10124 	obj->state = OBJ_LOADED; /* doesn't matter if successfully or not */
10125 
10126 	if (err) {
10127 		bpf_object_unpin(obj);
10128 		bpf_object_unload(obj);
10129 		pr_warn("failed to load object '%s'\n", obj->path);
10130 		return libbpf_err(err);
10131 	}
10132 
10133 	return 0;
10134 }
10135 
10136 int bpf_object__prepare(struct bpf_object *obj)
10137 {
10138 	return libbpf_err(bpf_object_prepare(obj, NULL));
10139 }
10140 
10141 int bpf_object__load(struct bpf_object *obj)
10142 {
10143 	return bpf_object_load(obj, 0, NULL);
10144 }
10145 
10146 static int make_parent_dir(const char *path)
10147 {
10148 	char *dname, *dir;
10149 	int err = 0;
10150 
10151 	dname = strdup(path);
10152 	if (dname == NULL)
10153 		return -ENOMEM;
10154 
10155 	dir = dirname(dname);
10156 	if (mkdir(dir, 0700) && errno != EEXIST)
10157 		err = -errno;
10158 
10159 	free(dname);
10160 	if (err) {
10161 		pr_warn("failed to mkdir %s: %s\n", path, errstr(err));
10162 	}
10163 	return err;
10164 }
10165 
10166 static int check_path(const char *path)
10167 {
10168 	struct statfs st_fs;
10169 	char *dname, *dir;
10170 	int err = 0;
10171 
10172 	if (path == NULL)
10173 		return -EINVAL;
10174 
10175 	dname = strdup(path);
10176 	if (dname == NULL)
10177 		return -ENOMEM;
10178 
10179 	dir = dirname(dname);
10180 	if (statfs(dir, &st_fs)) {
10181 		pr_warn("failed to statfs %s: %s\n", dir, errstr(errno));
10182 		err = -errno;
10183 	}
10184 	free(dname);
10185 
10186 	if (!err && st_fs.f_type != BPF_FS_MAGIC) {
10187 		pr_warn("specified path %s is not on BPF FS\n", path);
10188 		err = -EINVAL;
10189 	}
10190 
10191 	return err;
10192 }
10193 
10194 int bpf_program__pin(struct bpf_program *prog, const char *path)
10195 {
10196 	int err;
10197 
10198 	if (prog->fd < 0) {
10199 		pr_warn("prog '%s': can't pin program that wasn't loaded\n", prog->name);
10200 		return libbpf_err(-EINVAL);
10201 	}
10202 
10203 	err = make_parent_dir(path);
10204 	if (err)
10205 		return libbpf_err(err);
10206 
10207 	err = check_path(path);
10208 	if (err)
10209 		return libbpf_err(err);
10210 
10211 	if (bpf_obj_pin(prog->fd, path)) {
10212 		err = -errno;
10213 		pr_warn("prog '%s': failed to pin at '%s': %s\n", prog->name, path, errstr(err));
10214 		return libbpf_err(err);
10215 	}
10216 
10217 	pr_debug("prog '%s': pinned at '%s'\n", prog->name, path);
10218 	return 0;
10219 }
10220 
10221 int bpf_program__unpin(struct bpf_program *prog, const char *path)
10222 {
10223 	int err;
10224 
10225 	if (prog->fd < 0) {
10226 		pr_warn("prog '%s': can't unpin program that wasn't loaded\n", prog->name);
10227 		return libbpf_err(-EINVAL);
10228 	}
10229 
10230 	err = check_path(path);
10231 	if (err)
10232 		return libbpf_err(err);
10233 
10234 	err = unlink(path);
10235 	if (err)
10236 		return libbpf_err(-errno);
10237 
10238 	pr_debug("prog '%s': unpinned from '%s'\n", prog->name, path);
10239 	return 0;
10240 }
10241 
10242 int bpf_map__pin(struct bpf_map *map, const char *path)
10243 {
10244 	int err;
10245 
10246 	if (map == NULL) {
10247 		pr_warn("invalid map pointer\n");
10248 		return libbpf_err(-EINVAL);
10249 	}
10250 
10251 	if (map->fd < 0) {
10252 		pr_warn("map '%s': can't pin BPF map without FD (was it created?)\n", map->name);
10253 		return libbpf_err(-EINVAL);
10254 	}
10255 
10256 	if (map->pin_path) {
10257 		if (path && strcmp(path, map->pin_path)) {
10258 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
10259 				bpf_map__name(map), map->pin_path, path);
10260 			return libbpf_err(-EINVAL);
10261 		} else if (map->pinned) {
10262 			pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
10263 				 bpf_map__name(map), map->pin_path);
10264 			return 0;
10265 		}
10266 	} else {
10267 		if (!path) {
10268 			pr_warn("missing a path to pin map '%s' at\n",
10269 				bpf_map__name(map));
10270 			return libbpf_err(-EINVAL);
10271 		} else if (map->pinned) {
10272 			pr_warn("map '%s' already pinned\n", bpf_map__name(map));
10273 			return libbpf_err(-EEXIST);
10274 		}
10275 
10276 		map->pin_path = strdup(path);
10277 		if (!map->pin_path) {
10278 			err = -errno;
10279 			goto out_err;
10280 		}
10281 	}
10282 
10283 	err = make_parent_dir(map->pin_path);
10284 	if (err)
10285 		return libbpf_err(err);
10286 
10287 	err = check_path(map->pin_path);
10288 	if (err)
10289 		return libbpf_err(err);
10290 
10291 	if (bpf_obj_pin(map->fd, map->pin_path)) {
10292 		err = -errno;
10293 		goto out_err;
10294 	}
10295 
10296 	map->pinned = true;
10297 	pr_debug("pinned map '%s'\n", map->pin_path);
10298 
10299 	return 0;
10300 
10301 out_err:
10302 	pr_warn("failed to pin map: %s\n", errstr(err));
10303 	return libbpf_err(err);
10304 }
10305 
10306 int bpf_map__unpin(struct bpf_map *map, const char *path)
10307 {
10308 	int err;
10309 
10310 	if (map == NULL) {
10311 		pr_warn("invalid map pointer\n");
10312 		return libbpf_err(-EINVAL);
10313 	}
10314 
10315 	if (map->pin_path) {
10316 		if (path && strcmp(path, map->pin_path)) {
10317 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
10318 				bpf_map__name(map), map->pin_path, path);
10319 			return libbpf_err(-EINVAL);
10320 		}
10321 		path = map->pin_path;
10322 	} else if (!path) {
10323 		pr_warn("no path to unpin map '%s' from\n",
10324 			bpf_map__name(map));
10325 		return libbpf_err(-EINVAL);
10326 	}
10327 
10328 	err = check_path(path);
10329 	if (err)
10330 		return libbpf_err(err);
10331 
10332 	err = unlink(path);
10333 	if (err != 0)
10334 		return libbpf_err(-errno);
10335 
10336 	map->pinned = false;
10337 	pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path);
10338 
10339 	return 0;
10340 }
10341 
10342 int bpf_map__set_pin_path(struct bpf_map *map, const char *path)
10343 {
10344 	char *new = NULL;
10345 
10346 	if (path) {
10347 		new = strdup(path);
10348 		if (!new)
10349 			return libbpf_err(-errno);
10350 	}
10351 
10352 	free(map->pin_path);
10353 	map->pin_path = new;
10354 	return 0;
10355 }
10356 
10357 __alias(bpf_map__pin_path)
10358 const char *bpf_map__get_pin_path(const struct bpf_map *map);
10359 
10360 const char *bpf_map__pin_path(const struct bpf_map *map)
10361 {
10362 	return map->pin_path;
10363 }
10364 
10365 bool bpf_map__is_pinned(const struct bpf_map *map)
10366 {
10367 	return map->pinned;
10368 }
10369 
10370 static void sanitize_pin_path(char *s)
10371 {
10372 	/* bpffs disallows periods in path names */
10373 	while (*s) {
10374 		if (*s == '.')
10375 			*s = '_';
10376 		s++;
10377 	}
10378 }
10379 
10380 int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
10381 {
10382 	struct bpf_map *map;
10383 	int err;
10384 
10385 	if (!obj)
10386 		return libbpf_err(-ENOENT);
10387 
10388 	if (obj->state < OBJ_PREPARED) {
10389 		pr_warn("object not yet loaded; load it first\n");
10390 		return libbpf_err(-ENOENT);
10391 	}
10392 
10393 	bpf_object__for_each_map(map, obj) {
10394 		char *pin_path = NULL;
10395 		char buf[PATH_MAX];
10396 
10397 		if (!map->autocreate)
10398 			continue;
10399 
10400 		if (path) {
10401 			err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
10402 			if (err)
10403 				goto err_unpin_maps;
10404 			sanitize_pin_path(buf);
10405 			pin_path = buf;
10406 		} else if (!map->pin_path) {
10407 			continue;
10408 		}
10409 
10410 		err = bpf_map__pin(map, pin_path);
10411 		if (err)
10412 			goto err_unpin_maps;
10413 	}
10414 
10415 	return 0;
10416 
10417 err_unpin_maps:
10418 	while ((map = bpf_object__prev_map(obj, map))) {
10419 		if (!map->pin_path)
10420 			continue;
10421 
10422 		bpf_map__unpin(map, NULL);
10423 	}
10424 
10425 	return libbpf_err(err);
10426 }
10427 
10428 int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
10429 {
10430 	struct bpf_map *map;
10431 	int err;
10432 
10433 	if (!obj)
10434 		return libbpf_err(-ENOENT);
10435 
10436 	bpf_object__for_each_map(map, obj) {
10437 		char *pin_path = NULL;
10438 		char buf[PATH_MAX];
10439 
10440 		if (path) {
10441 			err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
10442 			if (err)
10443 				return libbpf_err(err);
10444 			sanitize_pin_path(buf);
10445 			pin_path = buf;
10446 		} else if (!map->pin_path) {
10447 			continue;
10448 		}
10449 
10450 		err = bpf_map__unpin(map, pin_path);
10451 		if (err)
10452 			return libbpf_err(err);
10453 	}
10454 
10455 	return 0;
10456 }
10457 
10458 int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
10459 {
10460 	struct bpf_program *prog;
10461 	char buf[PATH_MAX];
10462 	int err;
10463 
10464 	if (!obj)
10465 		return libbpf_err(-ENOENT);
10466 
10467 	if (obj->state < OBJ_LOADED) {
10468 		pr_warn("object not yet loaded; load it first\n");
10469 		return libbpf_err(-ENOENT);
10470 	}
10471 
10472 	bpf_object__for_each_program(prog, obj) {
10473 		err = pathname_concat(buf, sizeof(buf), path, prog->name);
10474 		if (err)
10475 			goto err_unpin_programs;
10476 
10477 		err = bpf_program__pin(prog, buf);
10478 		if (err)
10479 			goto err_unpin_programs;
10480 	}
10481 
10482 	return 0;
10483 
10484 err_unpin_programs:
10485 	while ((prog = bpf_object__prev_program(obj, prog))) {
10486 		if (pathname_concat(buf, sizeof(buf), path, prog->name))
10487 			continue;
10488 
10489 		bpf_program__unpin(prog, buf);
10490 	}
10491 
10492 	return libbpf_err(err);
10493 }
10494 
10495 int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
10496 {
10497 	struct bpf_program *prog;
10498 	int err;
10499 
10500 	if (!obj)
10501 		return libbpf_err(-ENOENT);
10502 
10503 	bpf_object__for_each_program(prog, obj) {
10504 		char buf[PATH_MAX];
10505 
10506 		err = pathname_concat(buf, sizeof(buf), path, prog->name);
10507 		if (err)
10508 			return libbpf_err(err);
10509 
10510 		err = bpf_program__unpin(prog, buf);
10511 		if (err)
10512 			return libbpf_err(err);
10513 	}
10514 
10515 	return 0;
10516 }
10517 
10518 int bpf_object__pin(struct bpf_object *obj, const char *path)
10519 {
10520 	int err;
10521 
10522 	err = bpf_object__pin_maps(obj, path);
10523 	if (err)
10524 		return libbpf_err(err);
10525 
10526 	err = bpf_object__pin_programs(obj, path);
10527 	if (err) {
10528 		bpf_object__unpin_maps(obj, path);
10529 		return libbpf_err(err);
10530 	}
10531 
10532 	return 0;
10533 }
10534 
10535 int bpf_object__unpin(struct bpf_object *obj, const char *path)
10536 {
10537 	int err;
10538 
10539 	err = bpf_object__unpin_programs(obj, path);
10540 	if (err)
10541 		return libbpf_err(err);
10542 
10543 	err = bpf_object__unpin_maps(obj, path);
10544 	if (err)
10545 		return libbpf_err(err);
10546 
10547 	return 0;
10548 }
10549 
10550 static void bpf_map__destroy(struct bpf_map *map)
10551 {
10552 	if (map->inner_map) {
10553 		bpf_map__destroy(map->inner_map);
10554 		zfree(&map->inner_map);
10555 	}
10556 
10557 	zfree(&map->init_slots);
10558 	map->init_slots_sz = 0;
10559 
10560 	if (map->mmaped && map->mmaped != map->obj->arena_data && !map->in_arena)
10561 		munmap(map->mmaped, bpf_map_mmap_sz(map));
10562 	map->mmaped = NULL;
10563 
10564 	if (map->st_ops) {
10565 		zfree(&map->st_ops->data);
10566 		zfree(&map->st_ops->progs);
10567 		zfree(&map->st_ops->kern_func_off);
10568 		zfree(&map->st_ops);
10569 	}
10570 
10571 	zfree(&map->name);
10572 	zfree(&map->real_name);
10573 	zfree(&map->pin_path);
10574 
10575 	if (map->fd >= 0)
10576 		zclose(map->fd);
10577 }
10578 
10579 void bpf_object__close(struct bpf_object *obj)
10580 {
10581 	size_t i;
10582 
10583 	if (IS_ERR_OR_NULL(obj))
10584 		return;
10585 
10586 	/*
10587 	 * if user called bpf_object__prepare() without ever getting to
10588 	 * bpf_object__load(), we need to clean up stuff that is normally
10589 	 * cleaned up at the end of loading step
10590 	 */
10591 	bpf_object_post_load_cleanup(obj);
10592 
10593 	usdt_manager_free(obj->usdt_man);
10594 	obj->usdt_man = NULL;
10595 
10596 	bpf_gen__free(obj->gen_loader);
10597 	bpf_object__elf_finish(obj);
10598 	bpf_object_unload(obj);
10599 	btf__free(obj->btf);
10600 	btf__free(obj->btf_vmlinux);
10601 	btf_ext__free(obj->btf_ext);
10602 
10603 	for (i = 0; i < obj->nr_maps; i++)
10604 		bpf_map__destroy(&obj->maps[i]);
10605 
10606 	zfree(&obj->btf_custom_path);
10607 	zfree(&obj->kconfig);
10608 
10609 	for (i = 0; i < obj->nr_extern; i++) {
10610 		zfree(&obj->externs[i].name);
10611 		zfree(&obj->externs[i].essent_name);
10612 	}
10613 
10614 	zfree(&obj->externs);
10615 	obj->nr_extern = 0;
10616 
10617 	zfree(&obj->maps);
10618 	obj->nr_maps = 0;
10619 
10620 	if (obj->programs && obj->nr_programs) {
10621 		for (i = 0; i < obj->nr_programs; i++)
10622 			bpf_program__exit(&obj->programs[i]);
10623 	}
10624 	zfree(&obj->programs);
10625 
10626 	zfree(&obj->feat_cache);
10627 	zfree(&obj->token_path);
10628 	if (obj->token_fd > 0)
10629 		close(obj->token_fd);
10630 
10631 	zfree(&obj->arena_data);
10632 
10633 	zfree(&obj->jumptables_data);
10634 	obj->jumptables_data_sz = 0;
10635 
10636 	for (i = 0; i < obj->jumptable_map_cnt; i++)
10637 		close(obj->jumptable_maps[i].fd);
10638 	zfree(&obj->jumptable_maps);
10639 
10640 	for (i = 0; i < obj->func_ptr_map_cnt; i++)
10641 		if (!obj->gen_loader)
10642 			close(obj->func_ptr_maps[i].fd);
10643 	zfree(&obj->func_ptr_maps);
10644 	zfree(&obj->func_ptrs);
10645 	for (i = 0; i < obj->data_ptr_cnt; i++)
10646 		zfree(&obj->data_ptrs[i].sym_name);
10647 	zfree(&obj->data_ptrs);
10648 
10649 	if (obj->btf_module_allowlist) {
10650 		for (i = 0; i < obj->btf_module_allowlist_cnt; i++)
10651 			zfree(&obj->btf_module_allowlist[i]);
10652 		zfree(&obj->btf_module_allowlist);
10653 	}
10654 
10655 	free(obj);
10656 }
10657 
10658 const char *bpf_object__name(const struct bpf_object *obj)
10659 {
10660 	return obj ? obj->name : libbpf_err_ptr(-EINVAL);
10661 }
10662 
10663 unsigned int bpf_object__kversion(const struct bpf_object *obj)
10664 {
10665 	return obj ? obj->kern_version : 0;
10666 }
10667 
10668 int bpf_object__token_fd(const struct bpf_object *obj)
10669 {
10670 	return obj->token_fd ?: -1;
10671 }
10672 
10673 struct btf *bpf_object__btf(const struct bpf_object *obj)
10674 {
10675 	return obj ? obj->btf : NULL;
10676 }
10677 
10678 int bpf_object__btf_fd(const struct bpf_object *obj)
10679 {
10680 	return obj->btf ? btf__fd(obj->btf) : -1;
10681 }
10682 
10683 int bpf_object__set_kversion(struct bpf_object *obj, __u32 kern_version)
10684 {
10685 	if (obj->state >= OBJ_LOADED)
10686 		return libbpf_err(-EINVAL);
10687 
10688 	obj->kern_version = kern_version;
10689 
10690 	return 0;
10691 }
10692 
10693 int bpf_object__gen_loader(struct bpf_object *obj, struct gen_loader_opts *opts)
10694 {
10695 	struct bpf_gen *gen;
10696 
10697 	if (!opts)
10698 		return libbpf_err(-EFAULT);
10699 	if (!OPTS_VALID(opts, gen_loader_opts))
10700 		return libbpf_err(-EINVAL);
10701 	gen = calloc(1, sizeof(*gen));
10702 	if (!gen)
10703 		return libbpf_err(-ENOMEM);
10704 	gen->opts = opts;
10705 	gen->swapped_endian = !is_native_endianness(obj);
10706 	obj->gen_loader = gen;
10707 	return 0;
10708 }
10709 
10710 static struct bpf_program *
10711 __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
10712 		    bool forward)
10713 {
10714 	size_t nr_programs = obj->nr_programs;
10715 	ssize_t idx;
10716 
10717 	if (!nr_programs)
10718 		return NULL;
10719 
10720 	if (!p)
10721 		/* Iter from the beginning */
10722 		return forward ? &obj->programs[0] :
10723 			&obj->programs[nr_programs - 1];
10724 
10725 	if (p->obj != obj) {
10726 		pr_warn("error: program handler doesn't match object\n");
10727 		return errno = EINVAL, NULL;
10728 	}
10729 
10730 	idx = (p - obj->programs) + (forward ? 1 : -1);
10731 	if (idx >= obj->nr_programs || idx < 0)
10732 		return NULL;
10733 	return &obj->programs[idx];
10734 }
10735 
10736 struct bpf_program *
10737 bpf_object__next_program(const struct bpf_object *obj, struct bpf_program *prev)
10738 {
10739 	struct bpf_program *prog = prev;
10740 
10741 	do {
10742 		prog = __bpf_program__iter(prog, obj, true);
10743 	} while (prog && prog_is_subprog(obj, prog));
10744 
10745 	return prog;
10746 }
10747 
10748 struct bpf_program *
10749 bpf_object__prev_program(const struct bpf_object *obj, struct bpf_program *next)
10750 {
10751 	struct bpf_program *prog = next;
10752 
10753 	do {
10754 		prog = __bpf_program__iter(prog, obj, false);
10755 	} while (prog && prog_is_subprog(obj, prog));
10756 
10757 	return prog;
10758 }
10759 
10760 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
10761 {
10762 	prog->prog_ifindex = ifindex;
10763 }
10764 
10765 const char *bpf_program__name(const struct bpf_program *prog)
10766 {
10767 	return prog->name;
10768 }
10769 
10770 const char *bpf_program__section_name(const struct bpf_program *prog)
10771 {
10772 	return prog->sec_name;
10773 }
10774 
10775 bool bpf_program__autoload(const struct bpf_program *prog)
10776 {
10777 	return prog->autoload;
10778 }
10779 
10780 int bpf_program__set_autoload(struct bpf_program *prog, bool autoload)
10781 {
10782 	if (prog->obj->state >= OBJ_LOADED)
10783 		return libbpf_err(-EINVAL);
10784 
10785 	prog->autoload = autoload;
10786 	return 0;
10787 }
10788 
10789 bool bpf_program__autoattach(const struct bpf_program *prog)
10790 {
10791 	return prog->autoattach;
10792 }
10793 
10794 void bpf_program__set_autoattach(struct bpf_program *prog, bool autoattach)
10795 {
10796 	prog->autoattach = autoattach;
10797 }
10798 
10799 const struct bpf_insn *bpf_program__insns(const struct bpf_program *prog)
10800 {
10801 	return prog->insns;
10802 }
10803 
10804 size_t bpf_program__insn_cnt(const struct bpf_program *prog)
10805 {
10806 	return prog->insns_cnt;
10807 }
10808 
10809 int bpf_program__set_insns(struct bpf_program *prog,
10810 			   struct bpf_insn *new_insns, size_t new_insn_cnt)
10811 {
10812 	struct bpf_insn *insns;
10813 
10814 	if (prog->obj->state >= OBJ_LOADED)
10815 		return libbpf_err(-EBUSY);
10816 
10817 	insns = libbpf_reallocarray(prog->insns, new_insn_cnt, sizeof(*insns));
10818 	/* NULL is a valid return from reallocarray if the new count is zero */
10819 	if (!insns && new_insn_cnt) {
10820 		pr_warn("prog '%s': failed to realloc prog code\n", prog->name);
10821 		return libbpf_err(-ENOMEM);
10822 	}
10823 	memcpy(insns, new_insns, new_insn_cnt * sizeof(*insns));
10824 
10825 	prog->insns = insns;
10826 	prog->insns_cnt = new_insn_cnt;
10827 	return 0;
10828 }
10829 
10830 int bpf_program__fd(const struct bpf_program *prog)
10831 {
10832 	if (!prog)
10833 		return libbpf_err(-EINVAL);
10834 
10835 	if (prog->fd < 0)
10836 		return libbpf_err(-ENOENT);
10837 
10838 	return prog->fd;
10839 }
10840 
10841 __alias(bpf_program__type)
10842 enum bpf_prog_type bpf_program__get_type(const struct bpf_program *prog);
10843 
10844 enum bpf_prog_type bpf_program__type(const struct bpf_program *prog)
10845 {
10846 	return prog->type;
10847 }
10848 
10849 static size_t custom_sec_def_cnt;
10850 static struct bpf_sec_def *custom_sec_defs;
10851 static struct bpf_sec_def custom_fallback_def;
10852 static bool has_custom_fallback_def;
10853 static int last_custom_sec_def_handler_id;
10854 
10855 int bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
10856 {
10857 	if (prog->obj->state >= OBJ_LOADED)
10858 		return libbpf_err(-EBUSY);
10859 
10860 	/* if type is not changed, do nothing */
10861 	if (prog->type == type)
10862 		return 0;
10863 
10864 	prog->type = type;
10865 
10866 	/* If a program type was changed, we need to reset associated SEC()
10867 	 * handler, as it will be invalid now. The only exception is a generic
10868 	 * fallback handler, which by definition is program type-agnostic and
10869 	 * is a catch-all custom handler, optionally set by the application,
10870 	 * so should be able to handle any type of BPF program.
10871 	 */
10872 	if (prog->sec_def != &custom_fallback_def)
10873 		prog->sec_def = NULL;
10874 	return 0;
10875 }
10876 
10877 __alias(bpf_program__expected_attach_type)
10878 enum bpf_attach_type bpf_program__get_expected_attach_type(const struct bpf_program *prog);
10879 
10880 enum bpf_attach_type bpf_program__expected_attach_type(const struct bpf_program *prog)
10881 {
10882 	return prog->expected_attach_type;
10883 }
10884 
10885 int bpf_program__set_expected_attach_type(struct bpf_program *prog,
10886 					   enum bpf_attach_type type)
10887 {
10888 	if (prog->obj->state >= OBJ_LOADED)
10889 		return libbpf_err(-EBUSY);
10890 
10891 	prog->expected_attach_type = type;
10892 	return 0;
10893 }
10894 
10895 __u32 bpf_program__flags(const struct bpf_program *prog)
10896 {
10897 	return prog->prog_flags;
10898 }
10899 
10900 int bpf_program__set_flags(struct bpf_program *prog, __u32 flags)
10901 {
10902 	if (prog->obj->state >= OBJ_LOADED)
10903 		return libbpf_err(-EBUSY);
10904 
10905 	prog->prog_flags = flags;
10906 	return 0;
10907 }
10908 
10909 int bpf_program__add_flags(struct bpf_program *prog, __u32 flags)
10910 {
10911 	return bpf_program__set_flags(prog, prog->prog_flags | flags);
10912 }
10913 
10914 int bpf_program__clear_flags(struct bpf_program *prog, __u32 flags)
10915 {
10916 	return bpf_program__set_flags(prog, prog->prog_flags & ~flags);
10917 }
10918 
10919 __u32 bpf_program__log_level(const struct bpf_program *prog)
10920 {
10921 	return prog->log_level;
10922 }
10923 
10924 int bpf_program__set_log_level(struct bpf_program *prog, __u32 log_level)
10925 {
10926 	if (prog->obj->state >= OBJ_LOADED)
10927 		return libbpf_err(-EBUSY);
10928 
10929 	prog->log_level = log_level;
10930 	return 0;
10931 }
10932 
10933 const char *bpf_program__log_buf(const struct bpf_program *prog, size_t *log_size)
10934 {
10935 	*log_size = prog->log_size;
10936 	return prog->log_buf;
10937 }
10938 
10939 int bpf_program__set_log_buf(struct bpf_program *prog, char *log_buf, size_t log_size)
10940 {
10941 	if (!!log_buf != !!log_size)
10942 		return libbpf_err(-EINVAL);
10943 	if (log_size > UINT_MAX)
10944 		return libbpf_err(-EINVAL);
10945 	if (prog->obj->state >= OBJ_LOADED)
10946 		return libbpf_err(-EBUSY);
10947 
10948 	prog->log_buf = log_buf;
10949 	prog->log_size = log_size;
10950 	return 0;
10951 }
10952 
10953 struct bpf_func_info *bpf_program__func_info(const struct bpf_program *prog)
10954 {
10955 	if (prog->func_info_rec_size != sizeof(struct bpf_func_info))
10956 		return libbpf_err_ptr(-EOPNOTSUPP);
10957 	return prog->func_info;
10958 }
10959 
10960 __u32 bpf_program__func_info_cnt(const struct bpf_program *prog)
10961 {
10962 	return prog->func_info_cnt;
10963 }
10964 
10965 struct bpf_line_info *bpf_program__line_info(const struct bpf_program *prog)
10966 {
10967 	if (prog->line_info_rec_size != sizeof(struct bpf_line_info))
10968 		return libbpf_err_ptr(-EOPNOTSUPP);
10969 	return prog->line_info;
10970 }
10971 
10972 __u32 bpf_program__line_info_cnt(const struct bpf_program *prog)
10973 {
10974 	return prog->line_info_cnt;
10975 }
10976 
10977 int bpf_program__clone(struct bpf_program *prog, const struct bpf_prog_load_opts *opts)
10978 {
10979 	LIBBPF_OPTS(bpf_prog_load_opts, attr);
10980 	struct bpf_object *obj;
10981 	const void *info;
10982 	__u32 info_cnt, info_rec_size;
10983 	int err, fd, prog_btf_fd;
10984 
10985 	if (!prog)
10986 		return libbpf_err(-EINVAL);
10987 
10988 	if (!OPTS_VALID(opts, bpf_prog_load_opts))
10989 		return libbpf_err(-EINVAL);
10990 
10991 	obj = prog->obj;
10992 	if (obj->state < OBJ_PREPARED)
10993 		return libbpf_err(-EINVAL);
10994 
10995 	/*
10996 	 * Caller-provided opts take priority; fall back to
10997 	 * prog/object defaults when the caller leaves them zero.
10998 	 */
10999 	attr.attach_prog_fd = OPTS_GET(opts, attach_prog_fd, 0) ?: prog->attach_prog_fd;
11000 	attr.prog_flags = OPTS_GET(opts, prog_flags, 0) ?: prog->prog_flags;
11001 	attr.prog_ifindex = OPTS_GET(opts, prog_ifindex, 0) ?: prog->prog_ifindex;
11002 	attr.kern_version = OPTS_GET(opts, kern_version, 0) ?: obj->kern_version;
11003 	attr.fd_array = OPTS_GET(opts, fd_array, NULL) ?: obj->fd_array;
11004 	attr.fd_array_cnt = OPTS_GET(opts, fd_array_cnt, 0);
11005 	/* the arena of the object goes with the program, as in bpf_object__load() */
11006 	if (!OPTS_GET(opts, fd_array, NULL) && !OPTS_GET(opts, fd_array_cnt, 0)) {
11007 		err = bpf_object__bind_arena(obj, prog, &attr);
11008 		if (err)
11009 			return libbpf_err(err);
11010 	}
11011 	attr.token_fd = OPTS_GET(opts, token_fd, 0) ?: obj->token_fd;
11012 	if (attr.token_fd)
11013 		attr.prog_flags |= BPF_F_TOKEN_FD;
11014 	if (obj->data_in_arena)
11015 		attr.prog_flags |= BPF_F_ARENA_SCALAR;
11016 
11017 	prog_btf_fd = OPTS_GET(opts, prog_btf_fd, 0);
11018 	if (!prog_btf_fd && obj->btf)
11019 		prog_btf_fd = btf__fd(obj->btf);
11020 
11021 	/* BTF func/line info: only pass if kernel supports it */
11022 	if (kernel_supports(obj, FEAT_BTF_FUNC) && prog_btf_fd > 0) {
11023 		attr.prog_btf_fd = prog_btf_fd;
11024 
11025 		/* func_info/line_info triples: all-or-nothing from caller */
11026 		info = OPTS_GET(opts, func_info, NULL);
11027 		info_cnt = OPTS_GET(opts, func_info_cnt, 0);
11028 		info_rec_size = OPTS_GET(opts, func_info_rec_size, 0);
11029 		if (!!info != !!info_cnt || !!info != !!info_rec_size) {
11030 			pr_warn("prog '%s': func_info, func_info_cnt, and func_info_rec_size must all be specified or all omitted\n",
11031 				prog->name);
11032 			return libbpf_err(-EINVAL);
11033 		}
11034 		attr.func_info = info ?: prog->func_info;
11035 		attr.func_info_cnt = info ? info_cnt : prog->func_info_cnt;
11036 		attr.func_info_rec_size = info ? info_rec_size : prog->func_info_rec_size;
11037 
11038 		info = OPTS_GET(opts, line_info, NULL);
11039 		info_cnt = OPTS_GET(opts, line_info_cnt, 0);
11040 		info_rec_size = OPTS_GET(opts, line_info_rec_size, 0);
11041 		if (!!info != !!info_cnt || !!info != !!info_rec_size) {
11042 			pr_warn("prog '%s': line_info, line_info_cnt, and line_info_rec_size must all be specified or all omitted\n",
11043 				prog->name);
11044 			return libbpf_err(-EINVAL);
11045 		}
11046 		attr.line_info = info ?: prog->line_info;
11047 		attr.line_info_cnt = info ? info_cnt : prog->line_info_cnt;
11048 		attr.line_info_rec_size = info ? info_rec_size : prog->line_info_rec_size;
11049 	}
11050 
11051 	/* Logging is caller-controlled; no fallback to prog/obj log settings */
11052 	attr.log_buf = OPTS_GET(opts, log_buf, NULL);
11053 	attr.log_size = OPTS_GET(opts, log_size, 0);
11054 	attr.log_level = OPTS_GET(opts, log_level, 0);
11055 
11056 	/*
11057 	 * Fields below may be mutated by prog_prepare_load_fn:
11058 	 * Seed them from prog/obj defaults here;
11059 	 * Later override with caller-provided opts.
11060 	 */
11061 	attr.expected_attach_type = prog->expected_attach_type;
11062 	attr.attach_btf_id = prog->attach_btf_id;
11063 	attr.attach_btf_obj_fd = prog->attach_btf_obj_fd;
11064 
11065 	if (prog->sec_def && prog->sec_def->prog_prepare_load_fn) {
11066 		err = prog->sec_def->prog_prepare_load_fn(prog, &attr, prog->sec_def->cookie);
11067 		if (err)
11068 			return libbpf_err(err);
11069 	}
11070 
11071 	/* Re-apply caller overrides for output fields */
11072 	if (OPTS_GET(opts, expected_attach_type, 0))
11073 		attr.expected_attach_type = OPTS_GET(opts, expected_attach_type, 0);
11074 	if (OPTS_GET(opts, attach_btf_id, 0))
11075 		attr.attach_btf_id = OPTS_GET(opts, attach_btf_id, 0);
11076 	if (OPTS_GET(opts, attach_btf_obj_fd, 0))
11077 		attr.attach_btf_obj_fd = OPTS_GET(opts, attach_btf_obj_fd, 0);
11078 
11079 	/*
11080 	 * Unlike bpf_object_load_prog(), we intentionally do not call bpf_prog_bind_map()
11081 	 * for RODATA maps here to avoid mutating the object's state. Callers can bind the
11082 	 * required maps themselves using bpf_prog_bind_map().
11083 	 */
11084 	fd = bpf_prog_load(prog->type, prog->name, obj->license, prog->insns, prog->insns_cnt,
11085 			   &attr);
11086 
11087 	return libbpf_err(fd);
11088 }
11089 
11090 #define SEC_DEF(sec_pfx, ptype, atype, flags, ...) {			    \
11091 	.sec = (char *)sec_pfx,						    \
11092 	.prog_type = BPF_PROG_TYPE_##ptype,				    \
11093 	.expected_attach_type = atype,					    \
11094 	.cookie = (long)(flags),					    \
11095 	.prog_setup_fn = libbpf_setup_prog_flags,			    \
11096 	.prog_prepare_load_fn = libbpf_prepare_prog_load,		    \
11097 	__VA_ARGS__							    \
11098 }
11099 
11100 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
11101 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
11102 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link);
11103 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link);
11104 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
11105 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
11106 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link);
11107 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
11108 static int attach_kprobe_session(const struct bpf_program *prog, long cookie, struct bpf_link **link);
11109 static int attach_uprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
11110 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link);
11111 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link);
11112 static int attach_tracing_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
11113 
11114 static const struct bpf_sec_def section_defs[] = {
11115 	SEC_DEF("socket",		SOCKET_FILTER, 0, SEC_NONE),
11116 	SEC_DEF("sk_reuseport/migrate",	SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT_OR_MIGRATE, SEC_ATTACHABLE),
11117 	SEC_DEF("sk_reuseport",		SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT, SEC_ATTACHABLE),
11118 	SEC_DEF("kprobe+",		KPROBE,	0, SEC_NONE, attach_kprobe),
11119 	SEC_DEF("uprobe+",		KPROBE,	0, SEC_NONE, attach_uprobe),
11120 	SEC_DEF("uprobe.s+",		KPROBE,	0, SEC_SLEEPABLE, attach_uprobe),
11121 	SEC_DEF("kretprobe+",		KPROBE, 0, SEC_NONE, attach_kprobe),
11122 	SEC_DEF("uretprobe+",		KPROBE, 0, SEC_NONE, attach_uprobe),
11123 	SEC_DEF("uretprobe.s+",		KPROBE, 0, SEC_SLEEPABLE, attach_uprobe),
11124 	SEC_DEF("kprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
11125 	SEC_DEF("kretprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
11126 	SEC_DEF("kprobe.session+",	KPROBE,	BPF_TRACE_KPROBE_SESSION, SEC_NONE, attach_kprobe_session),
11127 	SEC_DEF("uprobe.multi+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_NONE, attach_uprobe_multi),
11128 	SEC_DEF("uretprobe.multi+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_NONE, attach_uprobe_multi),
11129 	SEC_DEF("uprobe.session+",	KPROBE,	BPF_TRACE_UPROBE_SESSION, SEC_NONE, attach_uprobe_multi),
11130 	SEC_DEF("uprobe.multi.s+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_SLEEPABLE, attach_uprobe_multi),
11131 	SEC_DEF("uretprobe.multi.s+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_SLEEPABLE, attach_uprobe_multi),
11132 	SEC_DEF("uprobe.session.s+",	KPROBE,	BPF_TRACE_UPROBE_SESSION, SEC_SLEEPABLE, attach_uprobe_multi),
11133 	SEC_DEF("ksyscall+",		KPROBE,	0, SEC_NONE, attach_ksyscall),
11134 	SEC_DEF("kretsyscall+",		KPROBE, 0, SEC_NONE, attach_ksyscall),
11135 	SEC_DEF("usdt+",		KPROBE,	0, SEC_USDT, attach_usdt),
11136 	SEC_DEF("usdt.s+",		KPROBE,	0, SEC_USDT | SEC_SLEEPABLE, attach_usdt),
11137 	SEC_DEF("tc/ingress",		SCHED_CLS, BPF_TCX_INGRESS, SEC_NONE), /* alias for tcx */
11138 	SEC_DEF("tc/egress",		SCHED_CLS, BPF_TCX_EGRESS, SEC_NONE),  /* alias for tcx */
11139 	SEC_DEF("tcx/ingress",		SCHED_CLS, BPF_TCX_INGRESS, SEC_NONE),
11140 	SEC_DEF("tcx/egress",		SCHED_CLS, BPF_TCX_EGRESS, SEC_NONE),
11141 	SEC_DEF("tc",			SCHED_CLS, 0, SEC_NONE), /* deprecated / legacy, use tcx */
11142 	SEC_DEF("classifier",		SCHED_CLS, 0, SEC_NONE), /* deprecated / legacy, use tcx */
11143 	SEC_DEF("action",		SCHED_ACT, 0, SEC_NONE), /* deprecated / legacy, use tcx */
11144 	SEC_DEF("netkit/primary",	SCHED_CLS, BPF_NETKIT_PRIMARY, SEC_NONE),
11145 	SEC_DEF("netkit/peer",		SCHED_CLS, BPF_NETKIT_PEER, SEC_NONE),
11146 	SEC_DEF("tracepoint+",		TRACEPOINT, 0, SEC_NONE, attach_tp),
11147 	SEC_DEF("tp+",			TRACEPOINT, 0, SEC_NONE, attach_tp),
11148 	SEC_DEF("tracepoint.s+",	TRACEPOINT, 0, SEC_SLEEPABLE, attach_tp),
11149 	SEC_DEF("tp.s+",		TRACEPOINT, 0, SEC_SLEEPABLE, attach_tp),
11150 	SEC_DEF("raw_tracepoint+",	RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
11151 	SEC_DEF("raw_tp+",		RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
11152 	SEC_DEF("raw_tracepoint.s+",	RAW_TRACEPOINT, 0, SEC_SLEEPABLE, attach_raw_tp),
11153 	SEC_DEF("raw_tp.s+",		RAW_TRACEPOINT, 0, SEC_SLEEPABLE, attach_raw_tp),
11154 	SEC_DEF("raw_tracepoint.w+",	RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
11155 	SEC_DEF("raw_tp.w+",		RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
11156 	SEC_DEF("tp_btf+",		TRACING, BPF_TRACE_RAW_TP, SEC_ATTACH_BTF, attach_trace),
11157 	SEC_DEF("tp_btf.s+",		TRACING, BPF_TRACE_RAW_TP, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
11158 	SEC_DEF("fentry+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF, attach_trace),
11159 	SEC_DEF("fmod_ret+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF, attach_trace),
11160 	SEC_DEF("fexit+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF, attach_trace),
11161 	SEC_DEF("fentry.s+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
11162 	SEC_DEF("fmod_ret.s+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
11163 	SEC_DEF("fexit.s+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
11164 	SEC_DEF("fsession+",		TRACING, BPF_TRACE_FSESSION, SEC_ATTACH_BTF, attach_trace),
11165 	SEC_DEF("fsession.s+",		TRACING, BPF_TRACE_FSESSION, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
11166 	SEC_DEF("fsession.multi+",	TRACING, BPF_TRACE_FSESSION_MULTI, 0, attach_tracing_multi),
11167 	SEC_DEF("fsession.multi.s+",	TRACING, BPF_TRACE_FSESSION_MULTI, SEC_SLEEPABLE, attach_tracing_multi),
11168 	SEC_DEF("fentry.multi+",	TRACING, BPF_TRACE_FENTRY_MULTI, 0, attach_tracing_multi),
11169 	SEC_DEF("fexit.multi+",		TRACING, BPF_TRACE_FEXIT_MULTI, 0, attach_tracing_multi),
11170 	SEC_DEF("fentry.multi.s+",	TRACING, BPF_TRACE_FENTRY_MULTI, SEC_SLEEPABLE, attach_tracing_multi),
11171 	SEC_DEF("fexit.multi.s+",	TRACING, BPF_TRACE_FEXIT_MULTI, SEC_SLEEPABLE, attach_tracing_multi),
11172 	SEC_DEF("freplace+",		EXT, 0, SEC_ATTACH_BTF, attach_trace),
11173 	SEC_DEF("lsm+",			LSM, BPF_LSM_MAC, SEC_ATTACH_BTF, attach_lsm),
11174 	SEC_DEF("lsm.s+",		LSM, BPF_LSM_MAC, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_lsm),
11175 	SEC_DEF("lsm_cgroup+",		LSM, BPF_LSM_CGROUP, SEC_ATTACH_BTF),
11176 	SEC_DEF("iter+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF, attach_iter),
11177 	SEC_DEF("iter.s+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_iter),
11178 	SEC_DEF("syscall",		SYSCALL, 0, SEC_SLEEPABLE),
11179 	SEC_DEF("xdp.frags/devmap",	XDP, BPF_XDP_DEVMAP, SEC_XDP_FRAGS),
11180 	SEC_DEF("xdp/devmap",		XDP, BPF_XDP_DEVMAP, SEC_ATTACHABLE),
11181 	SEC_DEF("xdp.frags/cpumap",	XDP, BPF_XDP_CPUMAP, SEC_XDP_FRAGS),
11182 	SEC_DEF("xdp/cpumap",		XDP, BPF_XDP_CPUMAP, SEC_ATTACHABLE),
11183 	SEC_DEF("xdp.frags",		XDP, BPF_XDP, SEC_XDP_FRAGS),
11184 	SEC_DEF("xdp",			XDP, BPF_XDP, SEC_ATTACHABLE_OPT),
11185 	SEC_DEF("perf_event",		PERF_EVENT, 0, SEC_NONE),
11186 	SEC_DEF("lwt_in",		LWT_IN, 0, SEC_NONE),
11187 	SEC_DEF("lwt_out",		LWT_OUT, 0, SEC_NONE),
11188 	SEC_DEF("lwt_xmit",		LWT_XMIT, 0, SEC_NONE),
11189 	SEC_DEF("lwt_seg6local",	LWT_SEG6LOCAL, 0, SEC_NONE),
11190 	SEC_DEF("sockops",		SOCK_OPS, BPF_CGROUP_SOCK_OPS, SEC_ATTACHABLE_OPT),
11191 	SEC_DEF("sk_skb/stream_parser",	SK_SKB, BPF_SK_SKB_STREAM_PARSER, SEC_ATTACHABLE_OPT),
11192 	SEC_DEF("sk_skb/stream_verdict",SK_SKB, BPF_SK_SKB_STREAM_VERDICT, SEC_ATTACHABLE_OPT),
11193 	SEC_DEF("sk_skb/verdict",	SK_SKB, BPF_SK_SKB_VERDICT, SEC_ATTACHABLE_OPT),
11194 	SEC_DEF("sk_skb",		SK_SKB, 0, SEC_NONE),
11195 	SEC_DEF("sk_msg",		SK_MSG, BPF_SK_MSG_VERDICT, SEC_ATTACHABLE_OPT),
11196 	SEC_DEF("lirc_mode2",		LIRC_MODE2, BPF_LIRC_MODE2, SEC_ATTACHABLE_OPT),
11197 	SEC_DEF("flow_dissector",	FLOW_DISSECTOR, BPF_FLOW_DISSECTOR, SEC_ATTACHABLE_OPT),
11198 	SEC_DEF("cgroup_skb/ingress",	CGROUP_SKB, BPF_CGROUP_INET_INGRESS, SEC_ATTACHABLE_OPT),
11199 	SEC_DEF("cgroup_skb/egress",	CGROUP_SKB, BPF_CGROUP_INET_EGRESS, SEC_ATTACHABLE_OPT),
11200 	SEC_DEF("cgroup/skb",		CGROUP_SKB, 0, SEC_NONE),
11201 	SEC_DEF("cgroup/sock_create",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE),
11202 	SEC_DEF("cgroup/sock_release",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_RELEASE, SEC_ATTACHABLE),
11203 	SEC_DEF("cgroup/sock",		CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE_OPT),
11204 	SEC_DEF("cgroup/post_bind4",	CGROUP_SOCK, BPF_CGROUP_INET4_POST_BIND, SEC_ATTACHABLE),
11205 	SEC_DEF("cgroup/post_bind6",	CGROUP_SOCK, BPF_CGROUP_INET6_POST_BIND, SEC_ATTACHABLE),
11206 	SEC_DEF("cgroup/bind4",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND, SEC_ATTACHABLE),
11207 	SEC_DEF("cgroup/bind6",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND, SEC_ATTACHABLE),
11208 	SEC_DEF("cgroup/connect4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT, SEC_ATTACHABLE),
11209 	SEC_DEF("cgroup/connect6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT, SEC_ATTACHABLE),
11210 	SEC_DEF("cgroup/connect_unix",	CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_CONNECT, SEC_ATTACHABLE),
11211 	SEC_DEF("cgroup/sendmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG, SEC_ATTACHABLE),
11212 	SEC_DEF("cgroup/sendmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG, SEC_ATTACHABLE),
11213 	SEC_DEF("cgroup/sendmsg_unix",	CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_SENDMSG, SEC_ATTACHABLE),
11214 	SEC_DEF("cgroup/recvmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_RECVMSG, SEC_ATTACHABLE),
11215 	SEC_DEF("cgroup/recvmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_RECVMSG, SEC_ATTACHABLE),
11216 	SEC_DEF("cgroup/recvmsg_unix",	CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_RECVMSG, SEC_ATTACHABLE),
11217 	SEC_DEF("cgroup/getpeername4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETPEERNAME, SEC_ATTACHABLE),
11218 	SEC_DEF("cgroup/getpeername6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETPEERNAME, SEC_ATTACHABLE),
11219 	SEC_DEF("cgroup/getpeername_unix", CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_GETPEERNAME, SEC_ATTACHABLE),
11220 	SEC_DEF("cgroup/getsockname4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETSOCKNAME, SEC_ATTACHABLE),
11221 	SEC_DEF("cgroup/getsockname6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETSOCKNAME, SEC_ATTACHABLE),
11222 	SEC_DEF("cgroup/getsockname_unix", CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_GETSOCKNAME, SEC_ATTACHABLE),
11223 	SEC_DEF("cgroup/sysctl",	CGROUP_SYSCTL, BPF_CGROUP_SYSCTL, SEC_ATTACHABLE),
11224 	SEC_DEF("cgroup/getsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_GETSOCKOPT, SEC_ATTACHABLE),
11225 	SEC_DEF("cgroup/setsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_SETSOCKOPT, SEC_ATTACHABLE),
11226 	SEC_DEF("cgroup/dev",		CGROUP_DEVICE, BPF_CGROUP_DEVICE, SEC_ATTACHABLE_OPT),
11227 	SEC_DEF("struct_ops+",		STRUCT_OPS, 0, SEC_NONE),
11228 	SEC_DEF("struct_ops.s+",	STRUCT_OPS, 0, SEC_SLEEPABLE),
11229 	SEC_DEF("sk_lookup",		SK_LOOKUP, BPF_SK_LOOKUP, SEC_ATTACHABLE),
11230 	SEC_DEF("netfilter",		NETFILTER, BPF_NETFILTER, SEC_NONE),
11231 };
11232 
11233 int libbpf_register_prog_handler(const char *sec,
11234 				 enum bpf_prog_type prog_type,
11235 				 enum bpf_attach_type exp_attach_type,
11236 				 const struct libbpf_prog_handler_opts *opts)
11237 {
11238 	struct bpf_sec_def *sec_def;
11239 
11240 	if (!OPTS_VALID(opts, libbpf_prog_handler_opts))
11241 		return libbpf_err(-EINVAL);
11242 
11243 	if (last_custom_sec_def_handler_id == INT_MAX) /* prevent overflow */
11244 		return libbpf_err(-E2BIG);
11245 
11246 	if (sec) {
11247 		sec_def = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt + 1,
11248 					      sizeof(*sec_def));
11249 		if (!sec_def)
11250 			return libbpf_err(-ENOMEM);
11251 
11252 		custom_sec_defs = sec_def;
11253 		sec_def = &custom_sec_defs[custom_sec_def_cnt];
11254 	} else {
11255 		if (has_custom_fallback_def)
11256 			return libbpf_err(-EBUSY);
11257 
11258 		sec_def = &custom_fallback_def;
11259 	}
11260 
11261 	sec_def->sec = sec ? strdup(sec) : NULL;
11262 	if (sec && !sec_def->sec)
11263 		return libbpf_err(-ENOMEM);
11264 
11265 	sec_def->prog_type = prog_type;
11266 	sec_def->expected_attach_type = exp_attach_type;
11267 	sec_def->cookie = OPTS_GET(opts, cookie, 0);
11268 
11269 	sec_def->prog_setup_fn = OPTS_GET(opts, prog_setup_fn, NULL);
11270 	sec_def->prog_prepare_load_fn = OPTS_GET(opts, prog_prepare_load_fn, NULL);
11271 	sec_def->prog_attach_fn = OPTS_GET(opts, prog_attach_fn, NULL);
11272 
11273 	sec_def->handler_id = ++last_custom_sec_def_handler_id;
11274 
11275 	if (sec)
11276 		custom_sec_def_cnt++;
11277 	else
11278 		has_custom_fallback_def = true;
11279 
11280 	return sec_def->handler_id;
11281 }
11282 
11283 int libbpf_unregister_prog_handler(int handler_id)
11284 {
11285 	struct bpf_sec_def *sec_defs;
11286 	int i;
11287 
11288 	if (handler_id <= 0)
11289 		return libbpf_err(-EINVAL);
11290 
11291 	if (has_custom_fallback_def && custom_fallback_def.handler_id == handler_id) {
11292 		memset(&custom_fallback_def, 0, sizeof(custom_fallback_def));
11293 		has_custom_fallback_def = false;
11294 		return 0;
11295 	}
11296 
11297 	for (i = 0; i < custom_sec_def_cnt; i++) {
11298 		if (custom_sec_defs[i].handler_id == handler_id)
11299 			break;
11300 	}
11301 
11302 	if (i == custom_sec_def_cnt)
11303 		return libbpf_err(-ENOENT);
11304 
11305 	free(custom_sec_defs[i].sec);
11306 	for (i = i + 1; i < custom_sec_def_cnt; i++)
11307 		custom_sec_defs[i - 1] = custom_sec_defs[i];
11308 	custom_sec_def_cnt--;
11309 
11310 	/* try to shrink the array, but it's ok if we couldn't */
11311 	sec_defs = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt, sizeof(*sec_defs));
11312 	/* if new count is zero, reallocarray can return a valid NULL result;
11313 	 * in this case the previous pointer will be freed, so we *have to*
11314 	 * reassign old pointer to the new value (even if it's NULL)
11315 	 */
11316 	if (sec_defs || custom_sec_def_cnt == 0)
11317 		custom_sec_defs = sec_defs;
11318 
11319 	return 0;
11320 }
11321 
11322 static bool sec_def_matches(const struct bpf_sec_def *sec_def, const char *sec_name)
11323 {
11324 	size_t len = strlen(sec_def->sec);
11325 
11326 	/* "type/" always has to have proper SEC("type/extras") form */
11327 	if (sec_def->sec[len - 1] == '/') {
11328 		if (str_has_pfx(sec_name, sec_def->sec))
11329 			return true;
11330 		return false;
11331 	}
11332 
11333 	/* "type+" means it can be either exact SEC("type") or
11334 	 * well-formed SEC("type/extras") with proper '/' separator
11335 	 */
11336 	if (sec_def->sec[len - 1] == '+') {
11337 		len--;
11338 		/* not even a prefix */
11339 		if (strncmp(sec_name, sec_def->sec, len) != 0)
11340 			return false;
11341 		/* exact match or has '/' separator */
11342 		if (sec_name[len] == '\0' || sec_name[len] == '/')
11343 			return true;
11344 		return false;
11345 	}
11346 
11347 	return strcmp(sec_name, sec_def->sec) == 0;
11348 }
11349 
11350 static const struct bpf_sec_def *find_sec_def(const char *sec_name)
11351 {
11352 	const struct bpf_sec_def *sec_def;
11353 	int i, n;
11354 
11355 	n = custom_sec_def_cnt;
11356 	for (i = 0; i < n; i++) {
11357 		sec_def = &custom_sec_defs[i];
11358 		if (sec_def_matches(sec_def, sec_name))
11359 			return sec_def;
11360 	}
11361 
11362 	n = ARRAY_SIZE(section_defs);
11363 	for (i = 0; i < n; i++) {
11364 		sec_def = &section_defs[i];
11365 		if (sec_def_matches(sec_def, sec_name))
11366 			return sec_def;
11367 	}
11368 
11369 	if (has_custom_fallback_def)
11370 		return &custom_fallback_def;
11371 
11372 	return NULL;
11373 }
11374 
11375 #define MAX_TYPE_NAME_SIZE 32
11376 
11377 static char *libbpf_get_type_names(bool attach_type)
11378 {
11379 	int i, len = ARRAY_SIZE(section_defs) * MAX_TYPE_NAME_SIZE;
11380 	char *buf;
11381 
11382 	buf = malloc(len);
11383 	if (!buf)
11384 		return NULL;
11385 
11386 	buf[0] = '\0';
11387 	/* Forge string buf with all available names */
11388 	for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
11389 		const struct bpf_sec_def *sec_def = &section_defs[i];
11390 
11391 		if (attach_type) {
11392 			if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
11393 				continue;
11394 
11395 			if (!(sec_def->cookie & SEC_ATTACHABLE))
11396 				continue;
11397 		}
11398 
11399 		if (strlen(buf) + strlen(section_defs[i].sec) + 2 > len) {
11400 			free(buf);
11401 			return NULL;
11402 		}
11403 		strcat(buf, " ");
11404 		strcat(buf, section_defs[i].sec);
11405 	}
11406 
11407 	return buf;
11408 }
11409 
11410 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
11411 			     enum bpf_attach_type *expected_attach_type)
11412 {
11413 	const struct bpf_sec_def *sec_def;
11414 	char *type_names;
11415 
11416 	if (!name)
11417 		return libbpf_err(-EINVAL);
11418 
11419 	sec_def = find_sec_def(name);
11420 	if (sec_def) {
11421 		*prog_type = sec_def->prog_type;
11422 		*expected_attach_type = sec_def->expected_attach_type;
11423 		return 0;
11424 	}
11425 
11426 	pr_debug("failed to guess program type from ELF section '%s'\n", name);
11427 	type_names = libbpf_get_type_names(false);
11428 	if (type_names != NULL) {
11429 		pr_debug("supported section(type) names are:%s\n", type_names);
11430 		free(type_names);
11431 	}
11432 
11433 	return libbpf_err(-ESRCH);
11434 }
11435 
11436 const char *libbpf_bpf_attach_type_str(enum bpf_attach_type t)
11437 {
11438 	if (t < 0 || t >= ARRAY_SIZE(attach_type_name))
11439 		return NULL;
11440 
11441 	return attach_type_name[t];
11442 }
11443 
11444 const char *libbpf_bpf_link_type_str(enum bpf_link_type t)
11445 {
11446 	if (t < 0 || t >= ARRAY_SIZE(link_type_name))
11447 		return NULL;
11448 
11449 	return link_type_name[t];
11450 }
11451 
11452 const char *libbpf_bpf_map_type_str(enum bpf_map_type t)
11453 {
11454 	if (t < 0 || t >= ARRAY_SIZE(map_type_name))
11455 		return NULL;
11456 
11457 	return map_type_name[t];
11458 }
11459 
11460 const char *libbpf_bpf_prog_type_str(enum bpf_prog_type t)
11461 {
11462 	if (t < 0 || t >= ARRAY_SIZE(prog_type_name))
11463 		return NULL;
11464 
11465 	return prog_type_name[t];
11466 }
11467 
11468 static struct bpf_map *find_struct_ops_map_by_offset(struct bpf_object *obj,
11469 						     int sec_idx,
11470 						     size_t offset)
11471 {
11472 	struct bpf_map *map;
11473 	size_t i;
11474 
11475 	for (i = 0; i < obj->nr_maps; i++) {
11476 		map = &obj->maps[i];
11477 		if (!bpf_map__is_struct_ops(map))
11478 			continue;
11479 		if (map->sec_idx == sec_idx &&
11480 		    map->sec_offset <= offset &&
11481 		    offset - map->sec_offset < map->def.value_size)
11482 			return map;
11483 	}
11484 
11485 	return NULL;
11486 }
11487 
11488 /* Collect the reloc from ELF, populate the st_ops->progs[], and update
11489  * st_ops->data for shadow type.
11490  */
11491 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
11492 					    Elf64_Shdr *shdr, Elf_Data *data)
11493 {
11494 	const struct btf_type *type;
11495 	const struct btf_member *member;
11496 	struct bpf_struct_ops *st_ops;
11497 	struct bpf_program *prog;
11498 	unsigned int shdr_idx;
11499 	const struct btf *btf;
11500 	struct bpf_map *map;
11501 	unsigned int moff, insn_idx;
11502 	const char *name;
11503 	__u32 member_idx;
11504 	Elf64_Sym *sym;
11505 	Elf64_Rel *rel;
11506 	int i, nrels;
11507 
11508 	btf = obj->btf;
11509 	nrels = shdr->sh_size / shdr->sh_entsize;
11510 	for (i = 0; i < nrels; i++) {
11511 		rel = elf_rel_by_idx(data, i);
11512 		if (!rel) {
11513 			pr_warn("struct_ops reloc: failed to get %d reloc\n", i);
11514 			return -LIBBPF_ERRNO__FORMAT;
11515 		}
11516 
11517 		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
11518 		if (!sym) {
11519 			pr_warn("struct_ops reloc: symbol %zx not found\n",
11520 				(size_t)ELF64_R_SYM(rel->r_info));
11521 			return -LIBBPF_ERRNO__FORMAT;
11522 		}
11523 
11524 		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
11525 		map = find_struct_ops_map_by_offset(obj, shdr->sh_info, rel->r_offset);
11526 		if (!map) {
11527 			pr_warn("struct_ops reloc: cannot find map at rel->r_offset %zu\n",
11528 				(size_t)rel->r_offset);
11529 			return -EINVAL;
11530 		}
11531 
11532 		moff = rel->r_offset - map->sec_offset;
11533 		shdr_idx = sym->st_shndx;
11534 		st_ops = map->st_ops;
11535 		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",
11536 			 map->name,
11537 			 (long long)(rel->r_info >> 32),
11538 			 (long long)sym->st_value,
11539 			 shdr_idx, (size_t)rel->r_offset,
11540 			 map->sec_offset, sym->st_name, name);
11541 
11542 		if (shdr_idx >= SHN_LORESERVE) {
11543 			pr_warn("struct_ops reloc %s: rel->r_offset %zu shdr_idx %u unsupported non-static function\n",
11544 				map->name, (size_t)rel->r_offset, shdr_idx);
11545 			return -LIBBPF_ERRNO__RELOC;
11546 		}
11547 		if (sym->st_value % BPF_INSN_SZ) {
11548 			pr_warn("struct_ops reloc %s: invalid target program offset %llu\n",
11549 				map->name, (unsigned long long)sym->st_value);
11550 			return -LIBBPF_ERRNO__FORMAT;
11551 		}
11552 		insn_idx = sym->st_value / BPF_INSN_SZ;
11553 
11554 		type = btf__type_by_id(btf, st_ops->type_id);
11555 		member = find_member_by_offset(type, moff * 8);
11556 		if (!member) {
11557 			pr_warn("struct_ops reloc %s: cannot find member at moff %u\n",
11558 				map->name, moff);
11559 			return -EINVAL;
11560 		}
11561 		member_idx = member - btf_members(type);
11562 		name = btf__name_by_offset(btf, member->name_off);
11563 
11564 		if (!resolve_func_ptr(btf, member->type, NULL)) {
11565 			pr_warn("struct_ops reloc %s: cannot relocate non func ptr %s\n",
11566 				map->name, name);
11567 			return -EINVAL;
11568 		}
11569 
11570 		prog = find_prog_by_sec_insn(obj, shdr_idx, insn_idx);
11571 		if (!prog) {
11572 			pr_warn("struct_ops reloc %s: cannot find prog at shdr_idx %u to relocate func ptr %s\n",
11573 				map->name, shdr_idx, name);
11574 			return -EINVAL;
11575 		}
11576 
11577 		/* prevent the use of BPF prog with invalid type */
11578 		if (prog->type != BPF_PROG_TYPE_STRUCT_OPS) {
11579 			pr_warn("struct_ops reloc %s: prog %s is not struct_ops BPF program\n",
11580 				map->name, prog->name);
11581 			return -EINVAL;
11582 		}
11583 
11584 		st_ops->progs[member_idx] = prog;
11585 
11586 		/* st_ops->data will be exposed to users, being returned by
11587 		 * bpf_map__initial_value() as a pointer to the shadow
11588 		 * type. All function pointers in the original struct type
11589 		 * should be converted to a pointer to struct bpf_program
11590 		 * in the shadow type.
11591 		 */
11592 		*((struct bpf_program **)(st_ops->data + moff)) = prog;
11593 	}
11594 
11595 	return 0;
11596 }
11597 
11598 #define BTF_TRACE_PREFIX "btf_trace_"
11599 #define BTF_LSM_PREFIX "bpf_lsm_"
11600 #define BTF_ITER_PREFIX "bpf_iter_"
11601 #define BTF_MAX_NAME_SIZE 128
11602 
11603 void btf_get_kernel_prefix_kind(enum bpf_attach_type attach_type,
11604 				const char **prefix, int *kind)
11605 {
11606 	switch (attach_type) {
11607 	case BPF_TRACE_RAW_TP:
11608 		*prefix = BTF_TRACE_PREFIX;
11609 		*kind = BTF_KIND_TYPEDEF;
11610 		break;
11611 	case BPF_LSM_MAC:
11612 	case BPF_LSM_CGROUP:
11613 		*prefix = BTF_LSM_PREFIX;
11614 		*kind = BTF_KIND_FUNC;
11615 		break;
11616 	case BPF_TRACE_ITER:
11617 		*prefix = BTF_ITER_PREFIX;
11618 		*kind = BTF_KIND_FUNC;
11619 		break;
11620 	default:
11621 		*prefix = "";
11622 		*kind = BTF_KIND_FUNC;
11623 	}
11624 }
11625 
11626 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
11627 				   const char *name, __u32 kind)
11628 {
11629 	char btf_type_name[BTF_MAX_NAME_SIZE];
11630 	int ret;
11631 
11632 	ret = snprintf(btf_type_name, sizeof(btf_type_name),
11633 		       "%s%s", prefix, name);
11634 	/* snprintf returns the number of characters written excluding the
11635 	 * terminating null. So, if >= BTF_MAX_NAME_SIZE are written, it
11636 	 * indicates truncation.
11637 	 */
11638 	if (ret < 0 || ret >= sizeof(btf_type_name))
11639 		return -ENAMETOOLONG;
11640 	return btf__find_by_name_kind(btf, btf_type_name, kind);
11641 }
11642 
11643 static inline int find_attach_btf_id(struct btf *btf, const char *name,
11644 				     enum bpf_attach_type attach_type)
11645 {
11646 	const char *prefix;
11647 	int kind;
11648 
11649 	btf_get_kernel_prefix_kind(attach_type, &prefix, &kind);
11650 	return find_btf_by_prefix_kind(btf, prefix, name, kind);
11651 }
11652 
11653 int libbpf_find_vmlinux_btf_id(const char *name,
11654 			       enum bpf_attach_type attach_type)
11655 {
11656 	struct btf *btf;
11657 	int err;
11658 
11659 	btf = btf__load_vmlinux_btf();
11660 	err = libbpf_get_error(btf);
11661 	if (err) {
11662 		pr_warn("vmlinux BTF is not found\n");
11663 		return libbpf_err(err);
11664 	}
11665 
11666 	err = find_attach_btf_id(btf, name, attach_type);
11667 	if (err <= 0)
11668 		pr_warn("%s is not found in vmlinux BTF\n", name);
11669 
11670 	btf__free(btf);
11671 	return libbpf_err(err);
11672 }
11673 
11674 static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd, int token_fd)
11675 {
11676 	struct bpf_prog_info info;
11677 	__u32 info_len = sizeof(info);
11678 	struct btf *btf;
11679 	int err;
11680 
11681 	memset(&info, 0, info_len);
11682 	err = bpf_prog_get_info_by_fd(attach_prog_fd, &info, &info_len);
11683 	if (err) {
11684 		pr_warn("failed bpf_prog_get_info_by_fd for FD %u: %s\n",
11685 			attach_prog_fd, errstr(err));
11686 		return err;
11687 	}
11688 
11689 	err = -EINVAL;
11690 	if (!info.btf_id) {
11691 		pr_warn("The target program doesn't have BTF\n");
11692 		goto out;
11693 	}
11694 	btf = btf_load_from_kernel(info.btf_id, NULL, token_fd);
11695 	err = libbpf_get_error(btf);
11696 	if (err) {
11697 		pr_warn("Failed to get BTF %u of the program: %s\n", info.btf_id, errstr(err));
11698 		goto out;
11699 	}
11700 	err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
11701 	btf__free(btf);
11702 	if (err <= 0) {
11703 		pr_warn("%s is not found in prog's BTF\n", name);
11704 		goto out;
11705 	}
11706 out:
11707 	return err;
11708 }
11709 
11710 static int find_kernel_btf_id(struct bpf_object *obj, const char *attach_name,
11711 			      enum bpf_attach_type attach_type,
11712 			      int *btf_obj_fd, int *btf_type_id)
11713 {
11714 	int ret, i, mod_len = 0;
11715 	const char *fn_name, *mod_name = NULL;
11716 
11717 	fn_name = strchr(attach_name, ':');
11718 	if (fn_name) {
11719 		mod_name = attach_name;
11720 		mod_len = fn_name - mod_name;
11721 		fn_name++;
11722 	}
11723 
11724 	if (!mod_name || strncmp(mod_name, "vmlinux", mod_len) == 0) {
11725 		ret = find_attach_btf_id(obj->btf_vmlinux,
11726 					 mod_name ? fn_name : attach_name,
11727 					 attach_type);
11728 		if (ret > 0) {
11729 			*btf_obj_fd = 0; /* vmlinux BTF */
11730 			*btf_type_id = ret;
11731 			return 0;
11732 		}
11733 		if (ret != -ENOENT)
11734 			return ret;
11735 	}
11736 
11737 	ret = load_module_btfs(obj);
11738 	if (ret)
11739 		return ret;
11740 
11741 	for (i = 0; i < obj->btf_module_cnt; i++) {
11742 		const struct module_btf *mod = &obj->btf_modules[i];
11743 
11744 		if (mod_name && strncmp(mod->name, mod_name, mod_len) != 0)
11745 			continue;
11746 
11747 		ret = find_attach_btf_id(mod->btf,
11748 					 mod_name ? fn_name : attach_name,
11749 					 attach_type);
11750 		if (ret > 0) {
11751 			*btf_obj_fd = mod->fd;
11752 			*btf_type_id = ret;
11753 			return 0;
11754 		}
11755 		if (ret == -ENOENT)
11756 			continue;
11757 
11758 		return ret;
11759 	}
11760 
11761 	return -ESRCH;
11762 }
11763 
11764 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
11765 				     int *btf_obj_fd, int *btf_type_id)
11766 {
11767 	enum bpf_attach_type attach_type = prog->expected_attach_type;
11768 	__u32 attach_prog_fd = prog->attach_prog_fd;
11769 	int err = 0;
11770 
11771 	/* BPF program's BTF ID */
11772 	if (prog->type == BPF_PROG_TYPE_EXT || attach_prog_fd) {
11773 		if (!attach_prog_fd) {
11774 			pr_warn("prog '%s': attach program FD is not set\n", prog->name);
11775 			return -EINVAL;
11776 		}
11777 		err = libbpf_find_prog_btf_id(attach_name, attach_prog_fd, prog->obj->token_fd);
11778 		if (err < 0) {
11779 			pr_warn("prog '%s': failed to find BPF program (FD %u) BTF ID for '%s': %s\n",
11780 				prog->name, attach_prog_fd, attach_name, errstr(err));
11781 			return err;
11782 		}
11783 		*btf_obj_fd = 0;
11784 		*btf_type_id = err;
11785 		return 0;
11786 	}
11787 
11788 	/* kernel/module BTF ID */
11789 	if (prog->obj->gen_loader) {
11790 		bpf_gen__record_attach_target(prog->obj->gen_loader, attach_name, attach_type);
11791 		*btf_obj_fd = 0;
11792 		*btf_type_id = 1;
11793 	} else {
11794 		err = find_kernel_btf_id(prog->obj, attach_name,
11795 					 attach_type, btf_obj_fd,
11796 					 btf_type_id);
11797 	}
11798 	if (err) {
11799 		pr_warn("prog '%s': failed to find kernel BTF type ID of '%s': %s\n",
11800 			prog->name, attach_name, errstr(err));
11801 		return err;
11802 	}
11803 	return 0;
11804 }
11805 
11806 int libbpf_attach_type_by_name(const char *name,
11807 			       enum bpf_attach_type *attach_type)
11808 {
11809 	char *type_names;
11810 	const struct bpf_sec_def *sec_def;
11811 
11812 	if (!name)
11813 		return libbpf_err(-EINVAL);
11814 
11815 	sec_def = find_sec_def(name);
11816 	if (!sec_def) {
11817 		pr_debug("failed to guess attach type based on ELF section name '%s'\n", name);
11818 		type_names = libbpf_get_type_names(true);
11819 		if (type_names != NULL) {
11820 			pr_debug("attachable section(type) names are:%s\n", type_names);
11821 			free(type_names);
11822 		}
11823 
11824 		return libbpf_err(-EINVAL);
11825 	}
11826 
11827 	if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
11828 		return libbpf_err(-EINVAL);
11829 	if (!(sec_def->cookie & SEC_ATTACHABLE))
11830 		return libbpf_err(-EINVAL);
11831 
11832 	*attach_type = sec_def->expected_attach_type;
11833 	return 0;
11834 }
11835 
11836 int bpf_map__fd(const struct bpf_map *map)
11837 {
11838 	if (!map)
11839 		return libbpf_err(-EINVAL);
11840 	if (!map_is_created(map))
11841 		return -1;
11842 	return map->fd;
11843 }
11844 
11845 static bool map_uses_real_name(const struct bpf_map *map)
11846 {
11847 	/* Since libbpf started to support custom .data.* and .rodata.* maps,
11848 	 * their user-visible name differs from kernel-visible name. Users see
11849 	 * such map's corresponding ELF section name as a map name.
11850 	 * This check distinguishes .data/.rodata from .data.* and .rodata.*
11851 	 * maps to know which name has to be returned to the user.
11852 	 * Map name of the custom .percpu.* maps might be truncated to
11853 	 * BPF_OBJ_NAME_LEN-1 chars in internal_map_name(). Hence, percpu data
11854 	 * maps must use real name for their user-visible name.
11855 	 */
11856 	if (map->libbpf_type == LIBBPF_MAP_DATA && strcmp(map->real_name, DATA_SEC) != 0)
11857 		return true;
11858 	if (map->libbpf_type == LIBBPF_MAP_RODATA && strcmp(map->real_name, RODATA_SEC) != 0)
11859 		return true;
11860 	if (map->libbpf_type == LIBBPF_MAP_PERCPU)
11861 		return true;
11862 	return false;
11863 }
11864 
11865 const char *bpf_map__name(const struct bpf_map *map)
11866 {
11867 	if (!map)
11868 		return NULL;
11869 
11870 	if (map_uses_real_name(map))
11871 		return map->real_name;
11872 
11873 	return map->name;
11874 }
11875 
11876 enum bpf_map_type bpf_map__type(const struct bpf_map *map)
11877 {
11878 	return map->def.type;
11879 }
11880 
11881 int bpf_map__set_type(struct bpf_map *map, enum bpf_map_type type)
11882 {
11883 	if (map_is_created(map))
11884 		return libbpf_err(-EBUSY);
11885 	map->def.type = type;
11886 	return 0;
11887 }
11888 
11889 __u32 bpf_map__map_flags(const struct bpf_map *map)
11890 {
11891 	return map->def.map_flags;
11892 }
11893 
11894 int bpf_map__set_map_flags(struct bpf_map *map, __u32 flags)
11895 {
11896 	if (map_is_created(map))
11897 		return libbpf_err(-EBUSY);
11898 	map->def.map_flags = flags;
11899 	return 0;
11900 }
11901 
11902 __u64 bpf_map__map_extra(const struct bpf_map *map)
11903 {
11904 	return map->map_extra;
11905 }
11906 
11907 int bpf_map__set_map_extra(struct bpf_map *map, __u64 map_extra)
11908 {
11909 	if (map_is_created(map))
11910 		return libbpf_err(-EBUSY);
11911 	map->map_extra = map_extra;
11912 	return 0;
11913 }
11914 
11915 __u32 bpf_map__numa_node(const struct bpf_map *map)
11916 {
11917 	return map->numa_node;
11918 }
11919 
11920 int bpf_map__set_numa_node(struct bpf_map *map, __u32 numa_node)
11921 {
11922 	if (map_is_created(map))
11923 		return libbpf_err(-EBUSY);
11924 	map->numa_node = numa_node;
11925 	return 0;
11926 }
11927 
11928 __u32 bpf_map__key_size(const struct bpf_map *map)
11929 {
11930 	return map->def.key_size;
11931 }
11932 
11933 int bpf_map__set_key_size(struct bpf_map *map, __u32 size)
11934 {
11935 	if (map_is_created(map))
11936 		return libbpf_err(-EBUSY);
11937 	map->def.key_size = size;
11938 	return 0;
11939 }
11940 
11941 __u32 bpf_map__value_size(const struct bpf_map *map)
11942 {
11943 	return map->def.value_size;
11944 }
11945 
11946 static int map_btf_datasec_resize(struct bpf_map *map, __u32 size)
11947 {
11948 	struct btf *btf;
11949 	struct btf_type *datasec_type, *var_type;
11950 	struct btf_var_secinfo *var;
11951 	const struct btf_type *array_type;
11952 	const struct btf_array *array;
11953 	int vlen, element_sz, new_array_id;
11954 	__u32 nr_elements;
11955 
11956 	/* check btf existence */
11957 	btf = bpf_object__btf(map->obj);
11958 	if (!btf)
11959 		return -ENOENT;
11960 
11961 	/* verify map is datasec */
11962 	datasec_type = btf_type_by_id(btf, bpf_map__btf_value_type_id(map));
11963 	if (!btf_is_datasec(datasec_type)) {
11964 		pr_warn("map '%s': cannot be resized, map value type is not a datasec\n",
11965 			bpf_map__name(map));
11966 		return -EINVAL;
11967 	}
11968 
11969 	/* verify datasec has at least one var */
11970 	vlen = btf_vlen(datasec_type);
11971 	if (vlen == 0) {
11972 		pr_warn("map '%s': cannot be resized, map value datasec is empty\n",
11973 			bpf_map__name(map));
11974 		return -EINVAL;
11975 	}
11976 
11977 	/* verify last var in the datasec is an array */
11978 	var = &btf_var_secinfos(datasec_type)[vlen - 1];
11979 	var_type = btf_type_by_id(btf, var->type);
11980 	array_type = skip_mods_and_typedefs(btf, var_type->type, NULL);
11981 	if (!btf_is_array(array_type)) {
11982 		pr_warn("map '%s': cannot be resized, last var must be an array\n",
11983 			bpf_map__name(map));
11984 		return -EINVAL;
11985 	}
11986 
11987 	/* verify request size aligns with array */
11988 	array = btf_array(array_type);
11989 	element_sz = btf__resolve_size(btf, array->type);
11990 	if (element_sz <= 0 || (size - var->offset) % element_sz != 0) {
11991 		pr_warn("map '%s': cannot be resized, element size (%d) doesn't align with new total size (%u)\n",
11992 			bpf_map__name(map), element_sz, size);
11993 		return -EINVAL;
11994 	}
11995 
11996 	/* create a new array based on the existing array, but with new length */
11997 	nr_elements = (size - var->offset) / element_sz;
11998 	new_array_id = btf__add_array(btf, array->index_type, array->type, nr_elements);
11999 	if (new_array_id < 0)
12000 		return new_array_id;
12001 
12002 	/* adding a new btf type invalidates existing pointers to btf objects,
12003 	 * so refresh pointers before proceeding
12004 	 */
12005 	datasec_type = btf_type_by_id(btf, map->btf_value_type_id);
12006 	var = &btf_var_secinfos(datasec_type)[vlen - 1];
12007 	var_type = btf_type_by_id(btf, var->type);
12008 
12009 	/* finally update btf info */
12010 	datasec_type->size = size;
12011 	var->size = size - var->offset;
12012 	var_type->type = new_array_id;
12013 
12014 	return 0;
12015 }
12016 
12017 int bpf_map__set_value_size(struct bpf_map *map, __u32 size)
12018 {
12019 	if (map_is_created(map))
12020 		return libbpf_err(-EBUSY);
12021 
12022 	if (map->in_arena)
12023 		return libbpf_err(-EOPNOTSUPP);
12024 
12025 	if (map->mmaped) {
12026 		size_t mmap_old_sz, mmap_new_sz;
12027 		int err;
12028 
12029 		if (map->def.type != BPF_MAP_TYPE_ARRAY &&
12030 		    map->def.type != BPF_MAP_TYPE_PERCPU_ARRAY)
12031 			return libbpf_err(-EOPNOTSUPP);
12032 
12033 		mmap_old_sz = bpf_map_mmap_sz(map);
12034 		mmap_new_sz = array_map_mmap_sz(size, map->def.max_entries);
12035 		err = bpf_map_mmap_resize(map, mmap_old_sz, mmap_new_sz);
12036 		if (err) {
12037 			pr_warn("map '%s': failed to resize memory-mapped region: %s\n",
12038 				bpf_map__name(map), errstr(err));
12039 			return libbpf_err(err);
12040 		}
12041 		err = map_btf_datasec_resize(map, size);
12042 		if (err && err != -ENOENT) {
12043 			pr_warn("map '%s': failed to adjust resized BTF, clearing BTF key/value info: %s\n",
12044 				bpf_map__name(map), errstr(err));
12045 			map->btf_value_type_id = 0;
12046 			map->btf_key_type_id = 0;
12047 		}
12048 	}
12049 
12050 	map->def.value_size = size;
12051 	return 0;
12052 }
12053 
12054 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
12055 {
12056 	return map ? map->btf_key_type_id : 0;
12057 }
12058 
12059 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
12060 {
12061 	return map ? map->btf_value_type_id : 0;
12062 }
12063 
12064 int bpf_map__set_initial_value(struct bpf_map *map,
12065 			       const void *data, size_t size)
12066 {
12067 	size_t actual_sz;
12068 
12069 	if (map_is_created(map))
12070 		return libbpf_err(-EBUSY);
12071 
12072 	if (!map->mmaped || map->libbpf_type == LIBBPF_MAP_KCONFIG)
12073 		return libbpf_err(-EINVAL);
12074 
12075 	if (map->def.type == BPF_MAP_TYPE_ARENA)
12076 		actual_sz = map->obj->arena_data_sz;
12077 	else
12078 		actual_sz = map->def.value_size;
12079 	if (size != actual_sz)
12080 		return libbpf_err(-EINVAL);
12081 
12082 	memcpy(map->mmaped, data, size);
12083 	return 0;
12084 }
12085 
12086 void *bpf_map__initial_value(const struct bpf_map *map, size_t *psize)
12087 {
12088 	if (bpf_map__is_struct_ops(map)) {
12089 		if (psize)
12090 			*psize = map->def.value_size;
12091 		return map->st_ops->data;
12092 	}
12093 
12094 	if (!map->mmaped)
12095 		return NULL;
12096 
12097 	if (map->def.type == BPF_MAP_TYPE_ARENA)
12098 		*psize = map->obj->arena_data_sz;
12099 	else
12100 		*psize = map->def.value_size;
12101 
12102 	return map->mmaped;
12103 }
12104 
12105 bool bpf_map__is_internal(const struct bpf_map *map)
12106 {
12107 	return map->libbpf_type != LIBBPF_MAP_UNSPEC;
12108 }
12109 
12110 __u32 bpf_map__ifindex(const struct bpf_map *map)
12111 {
12112 	return map->map_ifindex;
12113 }
12114 
12115 int bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
12116 {
12117 	if (map_is_created(map))
12118 		return libbpf_err(-EBUSY);
12119 	map->map_ifindex = ifindex;
12120 	return 0;
12121 }
12122 
12123 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
12124 {
12125 	if (!bpf_map_type__is_map_in_map(map->def.type)) {
12126 		pr_warn("error: unsupported map type\n");
12127 		return libbpf_err(-EINVAL);
12128 	}
12129 	if (map->inner_map_fd != -1) {
12130 		pr_warn("error: inner_map_fd already specified\n");
12131 		return libbpf_err(-EINVAL);
12132 	}
12133 	if (map->inner_map) {
12134 		bpf_map__destroy(map->inner_map);
12135 		zfree(&map->inner_map);
12136 	}
12137 	map->inner_map_fd = fd;
12138 	return 0;
12139 }
12140 
12141 int bpf_map__set_exclusive_program(struct bpf_map *map, struct bpf_program *prog)
12142 {
12143 	if (map_is_created(map)) {
12144 		pr_warn("exclusive programs must be set before map creation\n");
12145 		return libbpf_err(-EINVAL);
12146 	}
12147 
12148 	if (map->obj != prog->obj) {
12149 		pr_warn("excl_prog and map must be from the same bpf object\n");
12150 		return libbpf_err(-EINVAL);
12151 	}
12152 
12153 	map->excl_prog = prog;
12154 	return 0;
12155 }
12156 
12157 struct bpf_program *bpf_map__exclusive_program(struct bpf_map *map)
12158 {
12159 	return map->excl_prog;
12160 }
12161 
12162 static struct bpf_map *
12163 __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
12164 {
12165 	ssize_t idx;
12166 	struct bpf_map *s, *e;
12167 
12168 	if (!obj || !obj->maps)
12169 		return errno = EINVAL, NULL;
12170 
12171 	s = obj->maps;
12172 	e = obj->maps + obj->nr_maps;
12173 
12174 	if ((m < s) || (m >= e)) {
12175 		pr_warn("error in %s: map handler doesn't belong to object\n",
12176 			 __func__);
12177 		return errno = EINVAL, NULL;
12178 	}
12179 
12180 	idx = (m - obj->maps) + i;
12181 	if (idx >= obj->nr_maps || idx < 0)
12182 		return NULL;
12183 	return &obj->maps[idx];
12184 }
12185 
12186 struct bpf_map *
12187 bpf_object__next_map(const struct bpf_object *obj, const struct bpf_map *prev)
12188 {
12189 	if (prev == NULL && obj != NULL)
12190 		return obj->maps;
12191 
12192 	return __bpf_map__iter(prev, obj, 1);
12193 }
12194 
12195 struct bpf_map *
12196 bpf_object__prev_map(const struct bpf_object *obj, const struct bpf_map *next)
12197 {
12198 	if (next == NULL && obj != NULL) {
12199 		if (!obj->nr_maps)
12200 			return NULL;
12201 		return obj->maps + obj->nr_maps - 1;
12202 	}
12203 
12204 	return __bpf_map__iter(next, obj, -1);
12205 }
12206 
12207 struct bpf_map *
12208 bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
12209 {
12210 	struct bpf_map *pos;
12211 
12212 	bpf_object__for_each_map(pos, obj) {
12213 		/* if it's a special internal map name (which always starts
12214 		 * with dot) then check if that special name matches the
12215 		 * real map name (ELF section name)
12216 		 */
12217 		if (name[0] == '.') {
12218 			if (pos->real_name && strcmp(pos->real_name, name) == 0)
12219 				return pos;
12220 			continue;
12221 		}
12222 		/* otherwise map name has to be an exact match */
12223 		if (map_uses_real_name(pos)) {
12224 			if (strcmp(pos->real_name, name) == 0)
12225 				return pos;
12226 			continue;
12227 		}
12228 		if (strcmp(pos->name, name) == 0)
12229 			return pos;
12230 	}
12231 	return errno = ENOENT, NULL;
12232 }
12233 
12234 int
12235 bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
12236 {
12237 	return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
12238 }
12239 
12240 static int validate_map_op(const struct bpf_map *map, size_t key_sz,
12241 			   size_t value_sz, bool check_value_sz, __u64 flags)
12242 {
12243 	if (!map_is_created(map)) /* map is not yet created */
12244 		return -ENOENT;
12245 
12246 	if (map->def.key_size != key_sz) {
12247 		pr_warn("map '%s': unexpected key size %zu provided, expected %u\n",
12248 			map->name, key_sz, map->def.key_size);
12249 		return -EINVAL;
12250 	}
12251 
12252 	if (map->fd < 0) {
12253 		pr_warn("map '%s': can't use BPF map without FD (was it created?)\n", map->name);
12254 		return -EINVAL;
12255 	}
12256 
12257 	if (!check_value_sz)
12258 		return 0;
12259 
12260 	switch (map->def.type) {
12261 	case BPF_MAP_TYPE_PERCPU_ARRAY:
12262 	case BPF_MAP_TYPE_PERCPU_HASH:
12263 	case BPF_MAP_TYPE_LRU_PERCPU_HASH:
12264 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: {
12265 		int num_cpu = libbpf_num_possible_cpus();
12266 		size_t elem_sz = roundup(map->def.value_size, 8);
12267 
12268 		if (flags & (BPF_F_CPU | BPF_F_ALL_CPUS)) {
12269 			if ((flags & BPF_F_CPU) && (flags & BPF_F_ALL_CPUS)) {
12270 				pr_warn("map '%s': BPF_F_CPU and BPF_F_ALL_CPUS are mutually exclusive\n",
12271 					map->name);
12272 				return -EINVAL;
12273 			}
12274 			if (map->def.value_size != value_sz) {
12275 				pr_warn("map '%s': unexpected value size %zu provided for either BPF_F_CPU or BPF_F_ALL_CPUS, expected %u\n",
12276 					map->name, value_sz, map->def.value_size);
12277 				return -EINVAL;
12278 			}
12279 			break;
12280 		}
12281 
12282 		if (value_sz != num_cpu * elem_sz) {
12283 			pr_warn("map '%s': unexpected value size %zu provided for per-CPU map, expected %d * %zu = %zu\n",
12284 				map->name, value_sz, num_cpu, elem_sz, num_cpu * elem_sz);
12285 			return -EINVAL;
12286 		}
12287 		break;
12288 	}
12289 	default:
12290 		if (map->def.value_size != value_sz) {
12291 			pr_warn("map '%s': unexpected value size %zu provided, expected %u\n",
12292 				map->name, value_sz, map->def.value_size);
12293 			return -EINVAL;
12294 		}
12295 		break;
12296 	}
12297 	return 0;
12298 }
12299 
12300 int bpf_map__lookup_elem(const struct bpf_map *map,
12301 			 const void *key, size_t key_sz,
12302 			 void *value, size_t value_sz, __u64 flags)
12303 {
12304 	int err;
12305 
12306 	err = validate_map_op(map, key_sz, value_sz, true, flags);
12307 	if (err)
12308 		return libbpf_err(err);
12309 
12310 	return bpf_map_lookup_elem_flags(map->fd, key, value, flags);
12311 }
12312 
12313 int bpf_map__update_elem(const struct bpf_map *map,
12314 			 const void *key, size_t key_sz,
12315 			 const void *value, size_t value_sz, __u64 flags)
12316 {
12317 	int err;
12318 
12319 	err = validate_map_op(map, key_sz, value_sz, true, flags);
12320 	if (err)
12321 		return libbpf_err(err);
12322 
12323 	return bpf_map_update_elem(map->fd, key, value, flags);
12324 }
12325 
12326 int bpf_map__delete_elem(const struct bpf_map *map,
12327 			 const void *key, size_t key_sz, __u64 flags)
12328 {
12329 	int err;
12330 
12331 	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */, flags);
12332 	if (err)
12333 		return libbpf_err(err);
12334 
12335 	return bpf_map_delete_elem_flags(map->fd, key, flags);
12336 }
12337 
12338 int bpf_map__lookup_and_delete_elem(const struct bpf_map *map,
12339 				    const void *key, size_t key_sz,
12340 				    void *value, size_t value_sz, __u64 flags)
12341 {
12342 	int err;
12343 
12344 	err = validate_map_op(map, key_sz, value_sz, true, flags);
12345 	if (err)
12346 		return libbpf_err(err);
12347 
12348 	return bpf_map_lookup_and_delete_elem_flags(map->fd, key, value, flags);
12349 }
12350 
12351 int bpf_map__get_next_key(const struct bpf_map *map,
12352 			  const void *cur_key, void *next_key, size_t key_sz)
12353 {
12354 	int err;
12355 
12356 	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */, 0);
12357 	if (err)
12358 		return libbpf_err(err);
12359 
12360 	return bpf_map_get_next_key(map->fd, cur_key, next_key);
12361 }
12362 
12363 long libbpf_get_error(const void *ptr)
12364 {
12365 	if (!IS_ERR_OR_NULL(ptr))
12366 		return 0;
12367 
12368 	if (IS_ERR(ptr))
12369 		errno = -PTR_ERR(ptr);
12370 
12371 	/* If ptr == NULL, then errno should be already set by the failing
12372 	 * API, because libbpf never returns NULL on success and it now always
12373 	 * sets errno on error. So no extra errno handling for ptr == NULL
12374 	 * case.
12375 	 */
12376 	return -errno;
12377 }
12378 
12379 /* Replace link's underlying BPF program with the new one */
12380 int bpf_link__update_program(struct bpf_link *link, struct bpf_program *prog)
12381 {
12382 	int ret;
12383 	int prog_fd = bpf_program__fd(prog);
12384 
12385 	if (prog_fd < 0) {
12386 		pr_warn("prog '%s': can't use BPF program without FD (was it loaded?)\n",
12387 			prog->name);
12388 		return libbpf_err(-EINVAL);
12389 	}
12390 
12391 	ret = bpf_link_update(bpf_link__fd(link), prog_fd, NULL);
12392 	return libbpf_err_errno(ret);
12393 }
12394 
12395 /* Release "ownership" of underlying BPF resource (typically, BPF program
12396  * attached to some BPF hook, e.g., tracepoint, kprobe, etc). Disconnected
12397  * link, when destructed through bpf_link__destroy() call won't attempt to
12398  * detach/unregisted that BPF resource. This is useful in situations where,
12399  * say, attached BPF program has to outlive userspace program that attached it
12400  * in the system. Depending on type of BPF program, though, there might be
12401  * additional steps (like pinning BPF program in BPF FS) necessary to ensure
12402  * exit of userspace program doesn't trigger automatic detachment and clean up
12403  * inside the kernel.
12404  */
12405 void bpf_link__disconnect(struct bpf_link *link)
12406 {
12407 	link->disconnected = true;
12408 }
12409 
12410 int bpf_link__destroy(struct bpf_link *link)
12411 {
12412 	int err = 0;
12413 
12414 	if (IS_ERR_OR_NULL(link))
12415 		return 0;
12416 
12417 	if (!link->disconnected && link->detach)
12418 		err = link->detach(link);
12419 	if (link->pin_path)
12420 		free(link->pin_path);
12421 	if (link->dealloc)
12422 		link->dealloc(link);
12423 	else
12424 		free(link);
12425 
12426 	return libbpf_err(err);
12427 }
12428 
12429 int bpf_link__fd(const struct bpf_link *link)
12430 {
12431 	return link->fd;
12432 }
12433 
12434 const char *bpf_link__pin_path(const struct bpf_link *link)
12435 {
12436 	return link->pin_path;
12437 }
12438 
12439 static int bpf_link__detach_fd(struct bpf_link *link)
12440 {
12441 	return libbpf_err_errno(close(link->fd));
12442 }
12443 
12444 struct bpf_link *bpf_link__open(const char *path)
12445 {
12446 	struct bpf_link *link;
12447 	int fd;
12448 
12449 	fd = bpf_obj_get(path);
12450 	if (fd < 0) {
12451 		fd = -errno;
12452 		pr_warn("failed to open link at %s: %d\n", path, fd);
12453 		return libbpf_err_ptr(fd);
12454 	}
12455 
12456 	link = calloc(1, sizeof(*link));
12457 	if (!link) {
12458 		close(fd);
12459 		return libbpf_err_ptr(-ENOMEM);
12460 	}
12461 	link->detach = &bpf_link__detach_fd;
12462 	link->fd = fd;
12463 
12464 	link->pin_path = strdup(path);
12465 	if (!link->pin_path) {
12466 		bpf_link__destroy(link);
12467 		return libbpf_err_ptr(-ENOMEM);
12468 	}
12469 
12470 	return link;
12471 }
12472 
12473 int bpf_link__detach(struct bpf_link *link)
12474 {
12475 	return bpf_link_detach(link->fd) ? -errno : 0;
12476 }
12477 
12478 int bpf_link__pin(struct bpf_link *link, const char *path)
12479 {
12480 	int err;
12481 
12482 	if (link->pin_path)
12483 		return libbpf_err(-EBUSY);
12484 	err = make_parent_dir(path);
12485 	if (err)
12486 		return libbpf_err(err);
12487 	err = check_path(path);
12488 	if (err)
12489 		return libbpf_err(err);
12490 
12491 	link->pin_path = strdup(path);
12492 	if (!link->pin_path)
12493 		return libbpf_err(-ENOMEM);
12494 
12495 	if (bpf_obj_pin(link->fd, link->pin_path)) {
12496 		err = -errno;
12497 		zfree(&link->pin_path);
12498 		return libbpf_err(err);
12499 	}
12500 
12501 	pr_debug("link fd=%d: pinned at %s\n", link->fd, link->pin_path);
12502 	return 0;
12503 }
12504 
12505 int bpf_link__unpin(struct bpf_link *link)
12506 {
12507 	int err;
12508 
12509 	if (!link->pin_path)
12510 		return libbpf_err(-EINVAL);
12511 
12512 	err = unlink(link->pin_path);
12513 	if (err != 0)
12514 		return -errno;
12515 
12516 	pr_debug("link fd=%d: unpinned from %s\n", link->fd, link->pin_path);
12517 	zfree(&link->pin_path);
12518 	return 0;
12519 }
12520 
12521 struct bpf_link_perf {
12522 	struct bpf_link link;
12523 	int perf_event_fd;
12524 	/* legacy kprobe support: keep track of probe identifier and type */
12525 	char *legacy_probe_name;
12526 	bool legacy_is_kprobe;
12527 	bool legacy_is_retprobe;
12528 };
12529 
12530 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe);
12531 static int remove_uprobe_event_legacy(const char *probe_name, bool retprobe);
12532 
12533 static int bpf_link_perf_detach(struct bpf_link *link)
12534 {
12535 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
12536 	int err = 0;
12537 
12538 	if (ioctl(perf_link->perf_event_fd, PERF_EVENT_IOC_DISABLE, 0) < 0)
12539 		err = -errno;
12540 
12541 	if (perf_link->perf_event_fd != link->fd)
12542 		close(perf_link->perf_event_fd);
12543 	close(link->fd);
12544 
12545 	/* legacy uprobe/kprobe needs to be removed after perf event fd closure */
12546 	if (perf_link->legacy_probe_name) {
12547 		if (perf_link->legacy_is_kprobe) {
12548 			err = remove_kprobe_event_legacy(perf_link->legacy_probe_name,
12549 							 perf_link->legacy_is_retprobe);
12550 		} else {
12551 			err = remove_uprobe_event_legacy(perf_link->legacy_probe_name,
12552 							 perf_link->legacy_is_retprobe);
12553 		}
12554 	}
12555 
12556 	return err;
12557 }
12558 
12559 static void bpf_link_perf_dealloc(struct bpf_link *link)
12560 {
12561 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
12562 
12563 	free(perf_link->legacy_probe_name);
12564 	free(perf_link);
12565 }
12566 
12567 struct bpf_link *bpf_program__attach_perf_event_opts(const struct bpf_program *prog, int pfd,
12568 						     const struct bpf_perf_event_opts *opts)
12569 {
12570 	struct bpf_link_perf *link;
12571 	int prog_fd, link_fd = -1, err;
12572 	bool force_ioctl_attach;
12573 
12574 	if (!OPTS_VALID(opts, bpf_perf_event_opts))
12575 		return libbpf_err_ptr(-EINVAL);
12576 
12577 	if (pfd < 0) {
12578 		pr_warn("prog '%s': invalid perf event FD %d\n",
12579 			prog->name, pfd);
12580 		return libbpf_err_ptr(-EINVAL);
12581 	}
12582 	prog_fd = bpf_program__fd(prog);
12583 	if (prog_fd < 0) {
12584 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
12585 			prog->name);
12586 		return libbpf_err_ptr(-EINVAL);
12587 	}
12588 
12589 	link = calloc(1, sizeof(*link));
12590 	if (!link)
12591 		return libbpf_err_ptr(-ENOMEM);
12592 	link->link.detach = &bpf_link_perf_detach;
12593 	link->link.dealloc = &bpf_link_perf_dealloc;
12594 	link->perf_event_fd = pfd;
12595 
12596 	force_ioctl_attach = OPTS_GET(opts, force_ioctl_attach, false);
12597 	if (kernel_supports(prog->obj, FEAT_PERF_LINK) && !force_ioctl_attach) {
12598 		DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_opts,
12599 			.perf_event.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0));
12600 
12601 		link_fd = bpf_link_create(prog_fd, pfd, BPF_PERF_EVENT, &link_opts);
12602 		if (link_fd < 0) {
12603 			err = -errno;
12604 			pr_warn("prog '%s': failed to create BPF link for perf_event FD %d: %s\n",
12605 				prog->name, pfd, errstr(err));
12606 			goto err_out;
12607 		}
12608 		link->link.fd = link_fd;
12609 	} else {
12610 		if (OPTS_GET(opts, bpf_cookie, 0)) {
12611 			pr_warn("prog '%s': user context value is not supported\n", prog->name);
12612 			err = -EOPNOTSUPP;
12613 			goto err_out;
12614 		}
12615 
12616 		if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
12617 			err = -errno;
12618 			pr_warn("prog '%s': failed to attach to perf_event FD %d: %s\n",
12619 				prog->name, pfd, errstr(err));
12620 			if (err == -EPROTO)
12621 				pr_warn("prog '%s': try add PERF_SAMPLE_CALLCHAIN to or remove exclude_callchain_[kernel|user] from pfd %d\n",
12622 					prog->name, pfd);
12623 			goto err_out;
12624 		}
12625 		link->link.fd = pfd;
12626 	}
12627 
12628 	if (!OPTS_GET(opts, dont_enable, false)) {
12629 		if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
12630 			err = -errno;
12631 			pr_warn("prog '%s': failed to enable perf_event FD %d: %s\n",
12632 				prog->name, pfd, errstr(err));
12633 			goto err_out;
12634 		}
12635 	}
12636 
12637 	return &link->link;
12638 err_out:
12639 	if (link_fd >= 0)
12640 		close(link_fd);
12641 	free(link);
12642 	return libbpf_err_ptr(err);
12643 }
12644 
12645 struct bpf_link *bpf_program__attach_perf_event(const struct bpf_program *prog, int pfd)
12646 {
12647 	return bpf_program__attach_perf_event_opts(prog, pfd, NULL);
12648 }
12649 
12650 /*
12651  * this function is expected to parse integer in the range of [0, 2^31-1] from
12652  * given file using scanf format string fmt. If actual parsed value is
12653  * negative, the result might be indistinguishable from error
12654  */
12655 static int parse_uint_from_file(const char *file, const char *fmt)
12656 {
12657 	int err, ret;
12658 	FILE *f;
12659 
12660 	f = fopen(file, "re");
12661 	if (!f) {
12662 		err = -errno;
12663 		pr_debug("failed to open '%s': %s\n", file, errstr(err));
12664 		return err;
12665 	}
12666 	err = fscanf(f, fmt, &ret);
12667 	if (err != 1) {
12668 		err = err == EOF ? -EIO : -errno;
12669 		pr_debug("failed to parse '%s': %s\n", file, errstr(err));
12670 		fclose(f);
12671 		return err;
12672 	}
12673 	fclose(f);
12674 	return ret;
12675 }
12676 
12677 static int determine_kprobe_perf_type(void)
12678 {
12679 	const char *file = "/sys/bus/event_source/devices/kprobe/type";
12680 
12681 	return parse_uint_from_file(file, "%d\n");
12682 }
12683 
12684 static int determine_uprobe_perf_type(void)
12685 {
12686 	const char *file = "/sys/bus/event_source/devices/uprobe/type";
12687 
12688 	return parse_uint_from_file(file, "%d\n");
12689 }
12690 
12691 static int determine_kprobe_retprobe_bit(void)
12692 {
12693 	const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
12694 
12695 	return parse_uint_from_file(file, "config:%d\n");
12696 }
12697 
12698 static int determine_uprobe_retprobe_bit(void)
12699 {
12700 	const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
12701 
12702 	return parse_uint_from_file(file, "config:%d\n");
12703 }
12704 
12705 #define PERF_UPROBE_REF_CTR_OFFSET_BITS 32
12706 #define PERF_UPROBE_REF_CTR_OFFSET_SHIFT 32
12707 
12708 static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
12709 				 uint64_t offset, int pid, size_t ref_ctr_off)
12710 {
12711 	const size_t attr_sz = sizeof(struct perf_event_attr);
12712 	struct perf_event_attr attr;
12713 	int type, pfd;
12714 
12715 	if ((__u64)ref_ctr_off >= (1ULL << PERF_UPROBE_REF_CTR_OFFSET_BITS))
12716 		return -EINVAL;
12717 
12718 	memset(&attr, 0, attr_sz);
12719 
12720 	type = uprobe ? determine_uprobe_perf_type()
12721 		      : determine_kprobe_perf_type();
12722 	if (type < 0) {
12723 		pr_warn("failed to determine %s perf type: %s\n",
12724 			uprobe ? "uprobe" : "kprobe",
12725 			errstr(type));
12726 		return type;
12727 	}
12728 	if (retprobe) {
12729 		int bit = uprobe ? determine_uprobe_retprobe_bit()
12730 				 : determine_kprobe_retprobe_bit();
12731 
12732 		if (bit < 0) {
12733 			pr_warn("failed to determine %s retprobe bit: %s\n",
12734 				uprobe ? "uprobe" : "kprobe",
12735 				errstr(bit));
12736 			return bit;
12737 		}
12738 		attr.config |= 1ULL << bit;
12739 	}
12740 	attr.size = attr_sz;
12741 	attr.type = type;
12742 	attr.config |= (__u64)ref_ctr_off << PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
12743 	attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
12744 	attr.config2 = offset;		 /* kprobe_addr or probe_offset */
12745 
12746 	/* pid filter is meaningful only for uprobes */
12747 	pfd = syscall(__NR_perf_event_open, &attr,
12748 		      pid < 0 ? -1 : pid /* pid */,
12749 		      pid == -1 ? 0 : -1 /* cpu */,
12750 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
12751 	return pfd >= 0 ? pfd : -errno;
12752 }
12753 
12754 static int append_to_file(const char *file, const char *fmt, ...)
12755 {
12756 	int fd, n, err = 0;
12757 	va_list ap;
12758 	char buf[1024];
12759 
12760 	va_start(ap, fmt);
12761 	n = vsnprintf(buf, sizeof(buf), fmt, ap);
12762 	va_end(ap);
12763 
12764 	if (n < 0 || n >= sizeof(buf))
12765 		return -EINVAL;
12766 
12767 	fd = open(file, O_WRONLY | O_APPEND | O_CLOEXEC, 0);
12768 	if (fd < 0)
12769 		return -errno;
12770 
12771 	if (write(fd, buf, n) < 0)
12772 		err = -errno;
12773 
12774 	close(fd);
12775 	return err;
12776 }
12777 
12778 #define DEBUGFS "/sys/kernel/debug/tracing"
12779 #define TRACEFS "/sys/kernel/tracing"
12780 
12781 static bool use_debugfs(void)
12782 {
12783 	static int has_debugfs = -1;
12784 
12785 	if (has_debugfs < 0)
12786 		has_debugfs = faccessat(AT_FDCWD, DEBUGFS, F_OK, AT_EACCESS) == 0;
12787 
12788 	return has_debugfs == 1;
12789 }
12790 
12791 static const char *tracefs_path(void)
12792 {
12793 	return use_debugfs() ? DEBUGFS : TRACEFS;
12794 }
12795 
12796 static const char *tracefs_kprobe_events(void)
12797 {
12798 	return use_debugfs() ? DEBUGFS"/kprobe_events" : TRACEFS"/kprobe_events";
12799 }
12800 
12801 static const char *tracefs_uprobe_events(void)
12802 {
12803 	return use_debugfs() ? DEBUGFS"/uprobe_events" : TRACEFS"/uprobe_events";
12804 }
12805 
12806 static const char *tracefs_available_filter_functions(void)
12807 {
12808 	return use_debugfs() ? DEBUGFS"/available_filter_functions"
12809 			     : TRACEFS"/available_filter_functions";
12810 }
12811 
12812 static const char *tracefs_available_filter_functions_addrs(void)
12813 {
12814 	return use_debugfs() ? DEBUGFS"/available_filter_functions_addrs"
12815 			     : TRACEFS"/available_filter_functions_addrs";
12816 }
12817 
12818 static void gen_probe_legacy_event_name(char *buf, size_t buf_sz,
12819 					const char *name, size_t offset)
12820 {
12821 	static int index = 0;
12822 	int i;
12823 
12824 	snprintf(buf, buf_sz, "libbpf_%d_%d_%s_0x%zx", getpid(),
12825 		 __sync_fetch_and_add(&index, 1), name, offset);
12826 
12827 	/* sanitize name in the probe name */
12828 	for (i = 0; buf[i]; i++) {
12829 		if (!isalnum(buf[i]))
12830 			buf[i] = '_';
12831 	}
12832 }
12833 
12834 static int add_kprobe_event_legacy(const char *probe_name, bool retprobe,
12835 				   const char *kfunc_name, size_t offset)
12836 {
12837 	return append_to_file(tracefs_kprobe_events(), "%c:%s/%s %s+0x%zx",
12838 			      retprobe ? 'r' : 'p',
12839 			      retprobe ? "kretprobes" : "kprobes",
12840 			      probe_name, kfunc_name, offset);
12841 }
12842 
12843 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe)
12844 {
12845 	return append_to_file(tracefs_kprobe_events(), "-:%s/%s",
12846 			      retprobe ? "kretprobes" : "kprobes", probe_name);
12847 }
12848 
12849 static int determine_kprobe_perf_type_legacy(const char *probe_name, bool retprobe)
12850 {
12851 	char file[256];
12852 
12853 	snprintf(file, sizeof(file), "%s/events/%s/%s/id",
12854 		 tracefs_path(), retprobe ? "kretprobes" : "kprobes", probe_name);
12855 
12856 	return parse_uint_from_file(file, "%d\n");
12857 }
12858 
12859 static int perf_event_kprobe_open_legacy(const char *probe_name, bool retprobe,
12860 					 const char *kfunc_name, size_t offset, int pid)
12861 {
12862 	const size_t attr_sz = sizeof(struct perf_event_attr);
12863 	struct perf_event_attr attr;
12864 	int type, pfd, err;
12865 
12866 	err = add_kprobe_event_legacy(probe_name, retprobe, kfunc_name, offset);
12867 	if (err < 0) {
12868 		pr_warn("failed to add legacy kprobe event for '%s+0x%zx': %s\n",
12869 			kfunc_name, offset,
12870 			errstr(err));
12871 		return err;
12872 	}
12873 	type = determine_kprobe_perf_type_legacy(probe_name, retprobe);
12874 	if (type < 0) {
12875 		err = type;
12876 		pr_warn("failed to determine legacy kprobe event id for '%s+0x%zx': %s\n",
12877 			kfunc_name, offset,
12878 			errstr(err));
12879 		goto err_clean_legacy;
12880 	}
12881 
12882 	memset(&attr, 0, attr_sz);
12883 	attr.size = attr_sz;
12884 	attr.config = type;
12885 	attr.type = PERF_TYPE_TRACEPOINT;
12886 
12887 	pfd = syscall(__NR_perf_event_open, &attr,
12888 		      pid < 0 ? -1 : pid, /* pid */
12889 		      pid == -1 ? 0 : -1, /* cpu */
12890 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
12891 	if (pfd < 0) {
12892 		err = -errno;
12893 		pr_warn("legacy kprobe perf_event_open() failed: %s\n",
12894 			errstr(err));
12895 		goto err_clean_legacy;
12896 	}
12897 	return pfd;
12898 
12899 err_clean_legacy:
12900 	/* Clear the newly added legacy kprobe_event */
12901 	remove_kprobe_event_legacy(probe_name, retprobe);
12902 	return err;
12903 }
12904 
12905 static const char *arch_specific_syscall_pfx(void)
12906 {
12907 #if defined(__x86_64__)
12908 	return "x64";
12909 #elif defined(__i386__)
12910 	return "ia32";
12911 #elif defined(__s390x__)
12912 	return "s390x";
12913 #elif defined(__arm__)
12914 	return "arm";
12915 #elif defined(__aarch64__)
12916 	return "arm64";
12917 #elif defined(__mips__)
12918 	return "mips";
12919 #elif defined(__riscv)
12920 	return "riscv";
12921 #elif defined(__powerpc__)
12922 	return "powerpc";
12923 #elif defined(__powerpc64__)
12924 	return "powerpc64";
12925 #else
12926 	return NULL;
12927 #endif
12928 }
12929 
12930 int probe_kern_syscall_wrapper(int token_fd)
12931 {
12932 	char syscall_name[64];
12933 	const char *ksys_pfx;
12934 
12935 	ksys_pfx = arch_specific_syscall_pfx();
12936 	if (!ksys_pfx)
12937 		return 0;
12938 
12939 	snprintf(syscall_name, sizeof(syscall_name), "__%s_sys_bpf", ksys_pfx);
12940 
12941 	if (determine_kprobe_perf_type() >= 0) {
12942 		int pfd;
12943 
12944 		pfd = perf_event_open_probe(false, false, syscall_name, 0, getpid(), 0);
12945 		if (pfd >= 0)
12946 			close(pfd);
12947 
12948 		return pfd >= 0 ? 1 : 0;
12949 	} else { /* legacy mode */
12950 		char probe_name[MAX_EVENT_NAME_LEN];
12951 
12952 		gen_probe_legacy_event_name(probe_name, sizeof(probe_name), syscall_name, 0);
12953 		if (add_kprobe_event_legacy(probe_name, false, syscall_name, 0) < 0)
12954 			return 0;
12955 
12956 		(void)remove_kprobe_event_legacy(probe_name, false);
12957 		return 1;
12958 	}
12959 }
12960 
12961 struct bpf_link *
12962 bpf_program__attach_kprobe_opts(const struct bpf_program *prog,
12963 				const char *func_name,
12964 				const struct bpf_kprobe_opts *opts)
12965 {
12966 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
12967 	enum probe_attach_mode attach_mode;
12968 	char *legacy_probe = NULL;
12969 	struct bpf_link *link;
12970 	size_t offset;
12971 	bool retprobe, legacy;
12972 	int pfd, err;
12973 
12974 	if (!OPTS_VALID(opts, bpf_kprobe_opts))
12975 		return libbpf_err_ptr(-EINVAL);
12976 
12977 	attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
12978 	retprobe = OPTS_GET(opts, retprobe, false);
12979 	offset = OPTS_GET(opts, offset, 0);
12980 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
12981 
12982 	legacy = determine_kprobe_perf_type() < 0;
12983 	switch (attach_mode) {
12984 	case PROBE_ATTACH_MODE_LEGACY:
12985 		legacy = true;
12986 		pe_opts.force_ioctl_attach = true;
12987 		break;
12988 	case PROBE_ATTACH_MODE_PERF:
12989 		if (legacy)
12990 			return libbpf_err_ptr(-ENOTSUP);
12991 		pe_opts.force_ioctl_attach = true;
12992 		break;
12993 	case PROBE_ATTACH_MODE_LINK:
12994 		if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
12995 			return libbpf_err_ptr(-ENOTSUP);
12996 		break;
12997 	case PROBE_ATTACH_MODE_DEFAULT:
12998 		break;
12999 	default:
13000 		return libbpf_err_ptr(-EINVAL);
13001 	}
13002 	if (!func_name && legacy)
13003 		return libbpf_err_ptr(-EOPNOTSUPP);
13004 
13005 	if (!legacy) {
13006 		pfd = perf_event_open_probe(false /* uprobe */, retprobe,
13007 					    func_name, offset,
13008 					    -1 /* pid */, 0 /* ref_ctr_off */);
13009 	} else {
13010 		char probe_name[MAX_EVENT_NAME_LEN];
13011 
13012 		gen_probe_legacy_event_name(probe_name, sizeof(probe_name),
13013 					    func_name, offset);
13014 
13015 		legacy_probe = strdup(probe_name);
13016 		if (!legacy_probe)
13017 			return libbpf_err_ptr(-ENOMEM);
13018 
13019 		pfd = perf_event_kprobe_open_legacy(legacy_probe, retprobe, func_name,
13020 						    offset, -1 /* pid */);
13021 	}
13022 	if (pfd < 0) {
13023 		err = pfd;
13024 		pr_warn("prog '%s': failed to create %s '%s%s0x%zx' perf event: %s\n",
13025 			prog->name, retprobe ? "kretprobe" : "kprobe",
13026 			func_name ?: "", func_name ? "+" : "",
13027 			offset, errstr(err));
13028 		goto err_out;
13029 	}
13030 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
13031 	err = libbpf_get_error(link);
13032 	if (err) {
13033 		close(pfd);
13034 		pr_warn("prog '%s': failed to attach to %s '%s%s0x%zx': %s\n",
13035 			prog->name, retprobe ? "kretprobe" : "kprobe",
13036 			func_name ?: "", func_name ? "+" : "",
13037 			offset, errstr(err));
13038 		goto err_clean_legacy;
13039 	}
13040 	if (legacy) {
13041 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
13042 
13043 		perf_link->legacy_probe_name = legacy_probe;
13044 		perf_link->legacy_is_kprobe = true;
13045 		perf_link->legacy_is_retprobe = retprobe;
13046 	}
13047 
13048 	return link;
13049 
13050 err_clean_legacy:
13051 	if (legacy)
13052 		remove_kprobe_event_legacy(legacy_probe, retprobe);
13053 err_out:
13054 	free(legacy_probe);
13055 	return libbpf_err_ptr(err);
13056 }
13057 
13058 struct bpf_link *bpf_program__attach_kprobe(const struct bpf_program *prog,
13059 					    bool retprobe,
13060 					    const char *func_name)
13061 {
13062 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts,
13063 		.retprobe = retprobe,
13064 	);
13065 
13066 	return bpf_program__attach_kprobe_opts(prog, func_name, &opts);
13067 }
13068 
13069 struct bpf_link *bpf_program__attach_ksyscall(const struct bpf_program *prog,
13070 					      const char *syscall_name,
13071 					      const struct bpf_ksyscall_opts *opts)
13072 {
13073 	LIBBPF_OPTS(bpf_kprobe_opts, kprobe_opts);
13074 	char func_name[128];
13075 
13076 	if (!OPTS_VALID(opts, bpf_ksyscall_opts))
13077 		return libbpf_err_ptr(-EINVAL);
13078 
13079 	if (kernel_supports(prog->obj, FEAT_SYSCALL_WRAPPER)) {
13080 		/* arch_specific_syscall_pfx() should never return NULL here
13081 		 * because it is guarded by kernel_supports(). However, since
13082 		 * compiler does not know that we have an explicit conditional
13083 		 * as well.
13084 		 */
13085 		snprintf(func_name, sizeof(func_name), "__%s_sys_%s",
13086 			 arch_specific_syscall_pfx() ? : "", syscall_name);
13087 	} else {
13088 		snprintf(func_name, sizeof(func_name), "__se_sys_%s", syscall_name);
13089 	}
13090 
13091 	kprobe_opts.retprobe = OPTS_GET(opts, retprobe, false);
13092 	kprobe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
13093 
13094 	return bpf_program__attach_kprobe_opts(prog, func_name, &kprobe_opts);
13095 }
13096 
13097 /* Adapted from perf/util/string.c */
13098 bool glob_match(const char *str, const char *pat)
13099 {
13100 	while (*str && *pat && *pat != '*') {
13101 		if (*pat == '?') {      /* Matches any single character */
13102 			str++;
13103 			pat++;
13104 			continue;
13105 		}
13106 		if (*str != *pat)
13107 			return false;
13108 		str++;
13109 		pat++;
13110 	}
13111 	/* Check wild card */
13112 	if (*pat == '*') {
13113 		while (*pat == '*')
13114 			pat++;
13115 		if (!*pat) /* Tail wild card matches all */
13116 			return true;
13117 		while (*str)
13118 			if (glob_match(str++, pat))
13119 				return true;
13120 	}
13121 	return !*str && !*pat;
13122 }
13123 
13124 struct kprobe_multi_resolve {
13125 	const char *pattern;
13126 	unsigned long *addrs;
13127 	size_t cap;
13128 	size_t cnt;
13129 };
13130 
13131 struct avail_kallsyms_data {
13132 	char **syms;
13133 	size_t cnt;
13134 	struct kprobe_multi_resolve *res;
13135 };
13136 
13137 static int avail_func_cmp(const void *a, const void *b)
13138 {
13139 	return strcmp(*(const char **)a, *(const char **)b);
13140 }
13141 
13142 static int avail_kallsyms_cb(unsigned long long sym_addr, char sym_type,
13143 			     const char *sym_name, void *ctx)
13144 {
13145 	struct avail_kallsyms_data *data = ctx;
13146 	struct kprobe_multi_resolve *res = data->res;
13147 	int err;
13148 
13149 	if (!glob_match(sym_name, res->pattern))
13150 		return 0;
13151 
13152 	if (!bsearch(&sym_name, data->syms, data->cnt, sizeof(*data->syms), avail_func_cmp)) {
13153 		/* Some versions of kernel strip out .llvm.<hash> suffix from
13154 		 * function names reported in available_filter_functions, but
13155 		 * don't do so for kallsyms. While this is clearly a kernel
13156 		 * bug (fixed by [0]) we try to accommodate that in libbpf to
13157 		 * make multi-kprobe usability a bit better: if no match is
13158 		 * found, we will strip .llvm. suffix and try one more time.
13159 		 *
13160 		 *   [0] fb6a421fb615 ("kallsyms: Match symbols exactly with CONFIG_LTO_CLANG")
13161 		 */
13162 		char sym_trim[256], *psym_trim = sym_trim;
13163 		const char *sym_sfx;
13164 
13165 		if (!(sym_sfx = strstr(sym_name, ".llvm.")))
13166 			return 0;
13167 
13168 		/* psym_trim vs sym_trim dance is done to avoid pointer vs array
13169 		 * coercion differences and get proper `const char **` pointer
13170 		 * which avail_func_cmp() expects
13171 		 */
13172 		snprintf(sym_trim, sizeof(sym_trim), "%.*s", (int)(sym_sfx - sym_name), sym_name);
13173 		if (!bsearch(&psym_trim, data->syms, data->cnt, sizeof(*data->syms), avail_func_cmp))
13174 			return 0;
13175 	}
13176 
13177 	err = libbpf_ensure_mem((void **)&res->addrs, &res->cap, sizeof(*res->addrs), res->cnt + 1);
13178 	if (err)
13179 		return err;
13180 
13181 	res->addrs[res->cnt++] = (unsigned long)sym_addr;
13182 	return 0;
13183 }
13184 
13185 static int libbpf_available_kallsyms_parse(struct kprobe_multi_resolve *res)
13186 {
13187 	const char *available_functions_file = tracefs_available_filter_functions();
13188 	struct avail_kallsyms_data data;
13189 	char sym_name[500];
13190 	FILE *f;
13191 	int err = 0, ret, i;
13192 	char **syms = NULL;
13193 	size_t cap = 0, cnt = 0;
13194 
13195 	f = fopen(available_functions_file, "re");
13196 	if (!f) {
13197 		err = -errno;
13198 		pr_warn("failed to open %s: %s\n", available_functions_file, errstr(err));
13199 		return err;
13200 	}
13201 
13202 	while (true) {
13203 		char *name;
13204 
13205 		ret = fscanf(f, "%499s%*[^\n]\n", sym_name);
13206 		if (ret == EOF && feof(f))
13207 			break;
13208 
13209 		if (ret != 1) {
13210 			pr_warn("failed to parse available_filter_functions entry: %d\n", ret);
13211 			err = -EINVAL;
13212 			goto cleanup;
13213 		}
13214 
13215 		if (!glob_match(sym_name, res->pattern))
13216 			continue;
13217 
13218 		err = libbpf_ensure_mem((void **)&syms, &cap, sizeof(*syms), cnt + 1);
13219 		if (err)
13220 			goto cleanup;
13221 
13222 		name = strdup(sym_name);
13223 		if (!name) {
13224 			err = -errno;
13225 			goto cleanup;
13226 		}
13227 
13228 		syms[cnt++] = name;
13229 	}
13230 
13231 	/* no entries found, bail out */
13232 	if (cnt == 0) {
13233 		err = -ENOENT;
13234 		goto cleanup;
13235 	}
13236 
13237 	/* sort available functions */
13238 	qsort(syms, cnt, sizeof(*syms), avail_func_cmp);
13239 
13240 	data.syms = syms;
13241 	data.res = res;
13242 	data.cnt = cnt;
13243 	libbpf_kallsyms_parse(avail_kallsyms_cb, &data);
13244 
13245 	if (res->cnt == 0)
13246 		err = -ENOENT;
13247 
13248 cleanup:
13249 	for (i = 0; i < cnt; i++)
13250 		free((char *)syms[i]);
13251 	free(syms);
13252 
13253 	fclose(f);
13254 	return err;
13255 }
13256 
13257 static bool has_available_filter_functions_addrs(void)
13258 {
13259 	return access(tracefs_available_filter_functions_addrs(), R_OK) != -1;
13260 }
13261 
13262 static int libbpf_available_kprobes_parse(struct kprobe_multi_resolve *res)
13263 {
13264 	const char *available_path = tracefs_available_filter_functions_addrs();
13265 	char sym_name[500];
13266 	FILE *f;
13267 	int ret, err = 0;
13268 	unsigned long long sym_addr;
13269 
13270 	f = fopen(available_path, "re");
13271 	if (!f) {
13272 		err = -errno;
13273 		pr_warn("failed to open %s: %s\n", available_path, errstr(err));
13274 		return err;
13275 	}
13276 
13277 	while (true) {
13278 		ret = fscanf(f, "%llx %499s%*[^\n]\n", &sym_addr, sym_name);
13279 		if (ret == EOF && feof(f))
13280 			break;
13281 
13282 		if (ret != 2) {
13283 			pr_warn("failed to parse available_filter_functions_addrs entry: %d\n",
13284 				ret);
13285 			err = -EINVAL;
13286 			goto cleanup;
13287 		}
13288 
13289 		if (!glob_match(sym_name, res->pattern))
13290 			continue;
13291 
13292 		err = libbpf_ensure_mem((void **)&res->addrs, &res->cap,
13293 					sizeof(*res->addrs), res->cnt + 1);
13294 		if (err)
13295 			goto cleanup;
13296 
13297 		res->addrs[res->cnt++] = (unsigned long)sym_addr;
13298 	}
13299 
13300 	if (res->cnt == 0)
13301 		err = -ENOENT;
13302 
13303 cleanup:
13304 	fclose(f);
13305 	return err;
13306 }
13307 
13308 struct bpf_link *
13309 bpf_program__attach_kprobe_multi_opts(const struct bpf_program *prog,
13310 				      const char *pattern,
13311 				      const struct bpf_kprobe_multi_opts *opts)
13312 {
13313 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
13314 	struct kprobe_multi_resolve res = {
13315 		.pattern = pattern,
13316 	};
13317 	enum bpf_attach_type attach_type;
13318 	struct bpf_link *link = NULL;
13319 	const unsigned long *addrs;
13320 	int err, link_fd, prog_fd;
13321 	bool retprobe, session, unique_match;
13322 	const __u64 *cookies;
13323 	const char **syms;
13324 	size_t cnt;
13325 
13326 	if (!OPTS_VALID(opts, bpf_kprobe_multi_opts))
13327 		return libbpf_err_ptr(-EINVAL);
13328 
13329 	prog_fd = bpf_program__fd(prog);
13330 	if (prog_fd < 0) {
13331 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
13332 			prog->name);
13333 		return libbpf_err_ptr(-EINVAL);
13334 	}
13335 
13336 	syms    = OPTS_GET(opts, syms, false);
13337 	addrs   = OPTS_GET(opts, addrs, false);
13338 	cnt     = OPTS_GET(opts, cnt, false);
13339 	cookies = OPTS_GET(opts, cookies, false);
13340 	unique_match = OPTS_GET(opts, unique_match, false);
13341 
13342 	if (!pattern && !addrs && !syms)
13343 		return libbpf_err_ptr(-EINVAL);
13344 	if (pattern && (addrs || syms || cookies || cnt))
13345 		return libbpf_err_ptr(-EINVAL);
13346 	if (!pattern && !cnt)
13347 		return libbpf_err_ptr(-EINVAL);
13348 	if (!pattern && unique_match)
13349 		return libbpf_err_ptr(-EINVAL);
13350 	if (addrs && syms)
13351 		return libbpf_err_ptr(-EINVAL);
13352 
13353 	/*
13354 	 * Exact function name (no wildcards) without unique_match:
13355 	 * bypass kallsyms parsing and pass the symbol directly to the
13356 	 * kernel via syms[] array.  When unique_match is set, fall
13357 	 * through to the slow path which detects duplicate symbols.
13358 	 */
13359 	if (pattern && !strpbrk(pattern, "*?") && !unique_match) {
13360 		syms = &pattern;
13361 		cnt = 1;
13362 	} else if (pattern) {
13363 		if (has_available_filter_functions_addrs())
13364 			err = libbpf_available_kprobes_parse(&res);
13365 		else
13366 			err = libbpf_available_kallsyms_parse(&res);
13367 		if (err)
13368 			goto error;
13369 
13370 		if (unique_match && res.cnt != 1) {
13371 			pr_warn("prog '%s': failed to find a unique match for '%s' (%zu matches)\n",
13372 				prog->name, pattern, res.cnt);
13373 			err = -EINVAL;
13374 			goto error;
13375 		}
13376 
13377 		addrs = res.addrs;
13378 		cnt = res.cnt;
13379 	}
13380 
13381 	retprobe = OPTS_GET(opts, retprobe, false);
13382 	session  = OPTS_GET(opts, session, false);
13383 
13384 	if (retprobe && session)
13385 		return libbpf_err_ptr(-EINVAL);
13386 
13387 	attach_type = session ? BPF_TRACE_KPROBE_SESSION : BPF_TRACE_KPROBE_MULTI;
13388 
13389 	lopts.kprobe_multi.syms = syms;
13390 	lopts.kprobe_multi.addrs = addrs;
13391 	lopts.kprobe_multi.cookies = cookies;
13392 	lopts.kprobe_multi.cnt = cnt;
13393 	lopts.kprobe_multi.flags = retprobe ? BPF_F_KPROBE_MULTI_RETURN : 0;
13394 
13395 	link = calloc(1, sizeof(*link));
13396 	if (!link) {
13397 		err = -ENOMEM;
13398 		goto error;
13399 	}
13400 	link->detach = &bpf_link__detach_fd;
13401 
13402 	link_fd = bpf_link_create(prog_fd, 0, attach_type, &lopts);
13403 	if (link_fd < 0) {
13404 		err = -errno;
13405 		/*
13406 		 * Normalize error code: when exact name bypasses kallsyms
13407 		 * parsing, kernel returns ESRCH from ftrace_lookup_symbols().
13408 		 * Convert to ENOENT for API consistency with the pattern
13409 		 * matching path which returns ENOENT from userspace.
13410 		 */
13411 		if (err == -ESRCH)
13412 			err = -ENOENT;
13413 		pr_warn("prog '%s': failed to attach: %s\n",
13414 			prog->name, errstr(err));
13415 		goto error;
13416 	}
13417 	link->fd = link_fd;
13418 	free(res.addrs);
13419 	return link;
13420 
13421 error:
13422 	free(link);
13423 	free(res.addrs);
13424 	return libbpf_err_ptr(err);
13425 }
13426 
13427 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
13428 {
13429 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts);
13430 	long offset = 0;
13431 	const char *func_name;
13432 	char *func;
13433 	int n;
13434 
13435 	*link = NULL;
13436 
13437 	/* no auto-attach for SEC("kprobe") and SEC("kretprobe") */
13438 	if (strcmp(prog->sec_name, "kprobe") == 0 || strcmp(prog->sec_name, "kretprobe") == 0)
13439 		return 0;
13440 
13441 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe/");
13442 	if (opts.retprobe)
13443 		func_name = prog->sec_name + sizeof("kretprobe/") - 1;
13444 	else
13445 		func_name = prog->sec_name + sizeof("kprobe/") - 1;
13446 
13447 	n = sscanf(func_name, "%m[a-zA-Z0-9_.]+%li", &func, &offset);
13448 	if (n < 1) {
13449 		pr_warn("kprobe name is invalid: %s\n", func_name);
13450 		return -EINVAL;
13451 	}
13452 
13453 	if (offset < 0) {
13454 		free(func);
13455 		pr_warn("kprobe offset must be a non-negative integer: %li\n", offset);
13456 		return -EINVAL;
13457 	}
13458 
13459 	if (opts.retprobe && offset != 0) {
13460 		free(func);
13461 		pr_warn("kretprobes do not support offset specification\n");
13462 		return -EINVAL;
13463 	}
13464 
13465 	opts.offset = offset;
13466 	*link = bpf_program__attach_kprobe_opts(prog, func, &opts);
13467 	free(func);
13468 	return libbpf_get_error(*link);
13469 }
13470 
13471 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link)
13472 {
13473 	LIBBPF_OPTS(bpf_ksyscall_opts, opts);
13474 	const char *syscall_name;
13475 
13476 	*link = NULL;
13477 
13478 	/* no auto-attach for SEC("ksyscall") and SEC("kretsyscall") */
13479 	if (strcmp(prog->sec_name, "ksyscall") == 0 || strcmp(prog->sec_name, "kretsyscall") == 0)
13480 		return 0;
13481 
13482 	opts.retprobe = str_has_pfx(prog->sec_name, "kretsyscall/");
13483 	if (opts.retprobe)
13484 		syscall_name = prog->sec_name + sizeof("kretsyscall/") - 1;
13485 	else
13486 		syscall_name = prog->sec_name + sizeof("ksyscall/") - 1;
13487 
13488 	*link = bpf_program__attach_ksyscall(prog, syscall_name, &opts);
13489 	return *link ? 0 : -errno;
13490 }
13491 
13492 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
13493 {
13494 	LIBBPF_OPTS(bpf_kprobe_multi_opts, opts);
13495 	const char *spec;
13496 	char *pattern;
13497 	int n;
13498 
13499 	*link = NULL;
13500 
13501 	/* no auto-attach for SEC("kprobe.multi") and SEC("kretprobe.multi") */
13502 	if (strcmp(prog->sec_name, "kprobe.multi") == 0 ||
13503 	    strcmp(prog->sec_name, "kretprobe.multi") == 0)
13504 		return 0;
13505 
13506 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe.multi/");
13507 	if (opts.retprobe)
13508 		spec = prog->sec_name + sizeof("kretprobe.multi/") - 1;
13509 	else
13510 		spec = prog->sec_name + sizeof("kprobe.multi/") - 1;
13511 
13512 	n = sscanf(spec, "%m[a-zA-Z0-9_.*?]", &pattern);
13513 	if (n < 1) {
13514 		pr_warn("kprobe multi pattern is invalid: %s\n", spec);
13515 		return -EINVAL;
13516 	}
13517 
13518 	*link = bpf_program__attach_kprobe_multi_opts(prog, pattern, &opts);
13519 	free(pattern);
13520 	return libbpf_get_error(*link);
13521 }
13522 
13523 static int attach_kprobe_session(const struct bpf_program *prog, long cookie,
13524 				 struct bpf_link **link)
13525 {
13526 	LIBBPF_OPTS(bpf_kprobe_multi_opts, opts, .session = true);
13527 	const char *spec;
13528 	char *pattern;
13529 	int n;
13530 
13531 	*link = NULL;
13532 
13533 	/* no auto-attach for SEC("kprobe.session") */
13534 	if (strcmp(prog->sec_name, "kprobe.session") == 0)
13535 		return 0;
13536 
13537 	spec = prog->sec_name + sizeof("kprobe.session/") - 1;
13538 	n = sscanf(spec, "%m[a-zA-Z0-9_.*?]", &pattern);
13539 	if (n < 1) {
13540 		pr_warn("kprobe session pattern is invalid: %s\n", spec);
13541 		return -EINVAL;
13542 	}
13543 
13544 	*link = bpf_program__attach_kprobe_multi_opts(prog, pattern, &opts);
13545 	free(pattern);
13546 	return *link ? 0 : -errno;
13547 }
13548 
13549 static int attach_uprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
13550 {
13551 	char *probe_type = NULL, *binary_path = NULL, *func_name = NULL;
13552 	LIBBPF_OPTS(bpf_uprobe_multi_opts, opts);
13553 	int n, ret = -EINVAL;
13554 
13555 	*link = NULL;
13556 
13557 	n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[^\n]",
13558 		   &probe_type, &binary_path, &func_name);
13559 	switch (n) {
13560 	case 1:
13561 		/* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
13562 		ret = 0;
13563 		break;
13564 	case 3:
13565 		opts.session = str_has_pfx(probe_type, "uprobe.session");
13566 		opts.retprobe = str_has_pfx(probe_type, "uretprobe.multi");
13567 
13568 		*link = bpf_program__attach_uprobe_multi(prog, -1, binary_path, func_name, &opts);
13569 		ret = libbpf_get_error(*link);
13570 		break;
13571 	default:
13572 		pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
13573 			prog->sec_name);
13574 		break;
13575 	}
13576 	free(probe_type);
13577 	free(binary_path);
13578 	free(func_name);
13579 	return ret;
13580 }
13581 
13582 #define MAX_BPF_FUNC_ARGS 12
13583 
13584 static bool btf_type_is_modifier(const struct btf_type *t)
13585 {
13586 	switch (BTF_INFO_KIND(t->info)) {
13587 	case BTF_KIND_TYPEDEF:
13588 	case BTF_KIND_VOLATILE:
13589 	case BTF_KIND_CONST:
13590 	case BTF_KIND_RESTRICT:
13591 	case BTF_KIND_TYPE_TAG:
13592 		return true;
13593 	default:
13594 		return false;
13595 	}
13596 }
13597 
13598 #define MAX_RESOLVE_DEPTH 32
13599 
13600 static int btf_get_type_size(const struct btf *btf, __u32 type_id,
13601 			     const struct btf_type **ret_type)
13602 {
13603 	const struct btf_type *t;
13604 	int i;
13605 
13606 	*ret_type = btf__type_by_id(btf, 0);
13607 	if (!type_id)
13608 		return 0;
13609 	t = btf__type_by_id(btf, type_id);
13610 	for (i = 0; i < MAX_RESOLVE_DEPTH && t && btf_type_is_modifier(t); i++)
13611 		t = btf__type_by_id(btf, t->type);
13612 	if (!t || i == MAX_RESOLVE_DEPTH)
13613 		return -EINVAL;
13614 	*ret_type = t;
13615 	if (btf_is_ptr(t))
13616 		return btf__pointer_size(btf);
13617 	if (btf_is_int(t) || btf_is_any_enum(t) || btf_is_struct(t) || btf_is_union(t))
13618 		return t->size;
13619 	return -EINVAL;
13620 }
13621 
13622 bool btf_type_is_traceable_func(const struct btf *btf, const struct btf_type *t)
13623 {
13624 	const struct btf_param *args;
13625 	const struct btf_type *proto;
13626 	__u32 i, nargs;
13627 	int ret;
13628 
13629 	if (!btf_is_func(t))
13630 		return false;
13631 	proto = btf__type_by_id(btf, t->type);
13632 	if (!proto || !btf_is_func_proto(proto))
13633 		return false;
13634 
13635 	args = (const struct btf_param *)(proto + 1);
13636 	nargs = btf_vlen(proto);
13637 	if (nargs > MAX_BPF_FUNC_ARGS)
13638 		return false;
13639 
13640 	/* No support for struct return type. */
13641 	ret = btf_get_type_size(btf, proto->type, &t);
13642 	if (ret < 0 || btf_is_struct(t) || btf_is_union(t))
13643 		return false;
13644 
13645 	for (i = 0; i < nargs; i++) {
13646 		/* No support for variable args. */
13647 		if (i == nargs - 1 && args[i].type == 0)
13648 			return false;
13649 		ret = btf_get_type_size(btf, args[i].type, &t);
13650 		/* No support of struct argument size greater than 16 bytes. */
13651 		if (ret < 0 || ret > 16)
13652 			return false;
13653 		/* No support for void argument. */
13654 		if (ret == 0)
13655 			return false;
13656 	}
13657 
13658 	return true;
13659 }
13660 
13661 static int
13662 collect_btf_func_ids_by_glob(const struct btf *btf, const char *pattern, __u32 **ids)
13663 {
13664 	__u32 type_id, nr_types = btf__type_cnt(btf);
13665 	size_t cap = 0, cnt = 0;
13666 
13667 	if (!pattern)
13668 		return -EINVAL;
13669 
13670 	for (type_id = 1; type_id < nr_types; type_id++) {
13671 		const struct btf_type *t = btf__type_by_id(btf, type_id);
13672 		const char *name;
13673 		int err;
13674 
13675 		if (btf_kind(t) != BTF_KIND_FUNC)
13676 			continue;
13677 		name = btf__name_by_offset(btf, t->name_off);
13678 		if (!name)
13679 			continue;
13680 
13681 		if (!glob_match(name, pattern))
13682 			continue;
13683 		if (!btf_type_is_traceable_func(btf, t))
13684 			continue;
13685 
13686 		err = libbpf_ensure_mem((void **) ids, &cap, sizeof(**ids), cnt + 1);
13687 		if (err) {
13688 			free(*ids);
13689 			return -ENOMEM;
13690 		}
13691 		(*ids)[cnt++] = type_id;
13692 	}
13693 
13694 	return cnt;
13695 }
13696 
13697 static int collect_func_ids_by_glob(const struct bpf_program *prog, const char *pattern, __u32 **ids)
13698 {
13699 	struct bpf_object *obj = prog->obj;
13700 	const struct module_btf *mod;
13701 	struct btf *btf = NULL;
13702 	const char *sep;
13703 	int err;
13704 
13705 	err = bpf_object__load_vmlinux_btf(obj, true);
13706 	if (err)
13707 		return err;
13708 
13709 	/* In case we have module specified, we will find its btf and use that. */
13710 	sep = strchr(pattern, ':');
13711 	if (sep) {
13712 		mod = find_attach_module(obj, pattern);
13713 		if (!mod) {
13714 			err = -EINVAL;
13715 			goto cleanup;
13716 		}
13717 		btf = mod->btf;
13718 		pattern = sep + 1;
13719 	} else {
13720 		/* Program is loaded for kernel module. */
13721 		if (prog->attach_btf_obj_fd) {
13722 			err = -EINVAL;
13723 			goto cleanup;
13724 		}
13725 		btf = obj->btf_vmlinux;
13726 	}
13727 
13728 	err = collect_btf_func_ids_by_glob(btf, pattern, ids);
13729 
13730 cleanup:
13731 	bpf_object_cleanup_btf(obj);
13732 	return err;
13733 }
13734 
13735 struct bpf_link *
13736 bpf_program__attach_tracing_multi(const struct bpf_program *prog, const char *pattern,
13737 				  const struct bpf_tracing_multi_opts *opts)
13738 {
13739 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
13740 	int prog_fd, link_fd, err, cnt;
13741 	__u32 *free_ids = NULL;
13742 	struct bpf_link *link;
13743 	const __u64 *cookies;
13744 	const __u32 *ids;
13745 
13746 	if (!OPTS_VALID(opts, bpf_tracing_multi_opts))
13747 		return libbpf_err_ptr(-EINVAL);
13748 
13749 	prog_fd = bpf_program__fd(prog);
13750 	if (prog_fd < 0) {
13751 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
13752 			prog->name);
13753 		return libbpf_err_ptr(-EINVAL);
13754 	}
13755 
13756 	cnt = OPTS_GET(opts, cnt, 0);
13757 	ids = OPTS_GET(opts, ids, NULL);
13758 	cookies = OPTS_GET(opts, cookies, NULL);
13759 
13760 	if (!!ids != !!cnt)
13761 		return libbpf_err_ptr(-EINVAL);
13762 	if (pattern && (ids || cookies))
13763 		return libbpf_err_ptr(-EINVAL);
13764 	if (!pattern && !ids)
13765 		return libbpf_err_ptr(-EINVAL);
13766 
13767 	if (pattern) {
13768 		cnt = collect_func_ids_by_glob(prog, pattern, &free_ids);
13769 		if (cnt < 0)
13770 			return libbpf_err_ptr(cnt);
13771 		if (cnt == 0)
13772 			return libbpf_err_ptr(-EINVAL);
13773 		ids = (const __u32 *) free_ids;
13774 	}
13775 
13776 	lopts.tracing_multi.ids = ids;
13777 	lopts.tracing_multi.cookies = cookies;
13778 	lopts.tracing_multi.cnt = cnt;
13779 
13780 	link = calloc(1, sizeof(*link));
13781 	if (!link) {
13782 		err = -ENOMEM;
13783 		goto error;
13784 	}
13785 	link->detach = &bpf_link__detach_fd;
13786 
13787 	link_fd = bpf_link_create(prog_fd, 0, prog->expected_attach_type, &lopts);
13788 	if (link_fd < 0) {
13789 		err = -errno;
13790 		pr_warn("prog '%s': failed to attach: %s\n", prog->name, errstr(err));
13791 		goto error;
13792 	}
13793 	link->fd = link_fd;
13794 	free(free_ids);
13795 	return link;
13796 
13797 error:
13798 	free(link);
13799 	free(free_ids);
13800 	return libbpf_err_ptr(err);
13801 }
13802 
13803 static int attach_tracing_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
13804 {
13805 	static const char *const prefixes[] = {
13806 		"fentry.multi",
13807 		"fexit.multi",
13808 		"fsession.multi",
13809 		"fentry.multi.s",
13810 		"fexit.multi.s",
13811 		"fsession.multi.s",
13812 	};
13813 	const char *spec = NULL;
13814 	char *pattern;
13815 	size_t i;
13816 	int n;
13817 
13818 	*link = NULL;
13819 
13820 	for (i = 0; i < ARRAY_SIZE(prefixes); i++) {
13821 		size_t pfx_len;
13822 
13823 		if (!str_has_pfx(prog->sec_name, prefixes[i]))
13824 			continue;
13825 
13826 		pfx_len = strlen(prefixes[i]);
13827 		/* no auto-attach case of, e.g., SEC("fentry.multi") */
13828 		if (prog->sec_name[pfx_len] == '\0')
13829 			return 0;
13830 
13831 		if (prog->sec_name[pfx_len] != '/')
13832 			continue;
13833 
13834 		spec = prog->sec_name + pfx_len + 1;
13835 		break;
13836 	}
13837 
13838 	if (!spec) {
13839 		pr_warn("prog '%s': invalid section name '%s'\n",
13840 			prog->name, prog->sec_name);
13841 		return -EINVAL;
13842 	}
13843 
13844 	n = sscanf(spec, "%m[a-zA-Z0-9_.*?:]", &pattern);
13845 	if (n < 1) {
13846 		pr_warn("tracing multi pattern is invalid: %s\n", spec);
13847 		return -EINVAL;
13848 	}
13849 
13850 	*link = bpf_program__attach_tracing_multi(prog, pattern, NULL);
13851 	free(pattern);
13852 	return libbpf_get_error(*link);
13853 }
13854 
13855 static inline int add_uprobe_event_legacy(const char *probe_name, bool retprobe,
13856 					  const char *binary_path, size_t offset)
13857 {
13858 	return append_to_file(tracefs_uprobe_events(), "%c:%s/%s %s:0x%zx",
13859 			      retprobe ? 'r' : 'p',
13860 			      retprobe ? "uretprobes" : "uprobes",
13861 			      probe_name, binary_path, offset);
13862 }
13863 
13864 static inline int remove_uprobe_event_legacy(const char *probe_name, bool retprobe)
13865 {
13866 	return append_to_file(tracefs_uprobe_events(), "-:%s/%s",
13867 			      retprobe ? "uretprobes" : "uprobes", probe_name);
13868 }
13869 
13870 static int determine_uprobe_perf_type_legacy(const char *probe_name, bool retprobe)
13871 {
13872 	char file[512];
13873 
13874 	snprintf(file, sizeof(file), "%s/events/%s/%s/id",
13875 		 tracefs_path(), retprobe ? "uretprobes" : "uprobes", probe_name);
13876 
13877 	return parse_uint_from_file(file, "%d\n");
13878 }
13879 
13880 static int perf_event_uprobe_open_legacy(const char *probe_name, bool retprobe,
13881 					 const char *binary_path, size_t offset, int pid)
13882 {
13883 	const size_t attr_sz = sizeof(struct perf_event_attr);
13884 	struct perf_event_attr attr;
13885 	int type, pfd, err;
13886 
13887 	err = add_uprobe_event_legacy(probe_name, retprobe, binary_path, offset);
13888 	if (err < 0) {
13889 		pr_warn("failed to add legacy uprobe event for %s:0x%zx: %s\n",
13890 			binary_path, (size_t)offset, errstr(err));
13891 		return err;
13892 	}
13893 	type = determine_uprobe_perf_type_legacy(probe_name, retprobe);
13894 	if (type < 0) {
13895 		err = type;
13896 		pr_warn("failed to determine legacy uprobe event id for %s:0x%zx: %s\n",
13897 			binary_path, offset, errstr(err));
13898 		goto err_clean_legacy;
13899 	}
13900 
13901 	memset(&attr, 0, attr_sz);
13902 	attr.size = attr_sz;
13903 	attr.config = type;
13904 	attr.type = PERF_TYPE_TRACEPOINT;
13905 
13906 	pfd = syscall(__NR_perf_event_open, &attr,
13907 		      pid < 0 ? -1 : pid, /* pid */
13908 		      pid == -1 ? 0 : -1, /* cpu */
13909 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
13910 	if (pfd < 0) {
13911 		err = -errno;
13912 		pr_warn("legacy uprobe perf_event_open() failed: %s\n", errstr(err));
13913 		goto err_clean_legacy;
13914 	}
13915 	return pfd;
13916 
13917 err_clean_legacy:
13918 	/* Clear the newly added legacy uprobe_event */
13919 	remove_uprobe_event_legacy(probe_name, retprobe);
13920 	return err;
13921 }
13922 
13923 /* Find offset of function name in archive specified by path. Currently
13924  * supported are .zip files that do not compress their contents, as used on
13925  * Android in the form of APKs, for example. "file_name" is the name of the ELF
13926  * file inside the archive. "func_name" matches symbol name or name@@LIB for
13927  * library functions.
13928  *
13929  * An overview of the APK format specifically provided here:
13930  * https://en.wikipedia.org/w/index.php?title=Apk_(file_format)&oldid=1139099120#Package_contents
13931  */
13932 static long elf_find_func_offset_from_archive(const char *archive_path, const char *file_name,
13933 					      const char *func_name)
13934 {
13935 	struct zip_archive *archive;
13936 	struct zip_entry entry;
13937 	long ret;
13938 	Elf *elf;
13939 
13940 	archive = zip_archive_open(archive_path);
13941 	if (IS_ERR(archive)) {
13942 		ret = PTR_ERR(archive);
13943 		pr_warn("zip: failed to open %s: %ld\n", archive_path, ret);
13944 		return ret;
13945 	}
13946 
13947 	ret = zip_archive_find_entry(archive, file_name, &entry);
13948 	if (ret) {
13949 		pr_warn("zip: could not find archive member %s in %s: %ld\n", file_name,
13950 			archive_path, ret);
13951 		goto out;
13952 	}
13953 	pr_debug("zip: found entry for %s in %s at 0x%lx\n", file_name, archive_path,
13954 		 (unsigned long)entry.data_offset);
13955 
13956 	if (entry.compression) {
13957 		pr_warn("zip: entry %s of %s is compressed and cannot be handled\n", file_name,
13958 			archive_path);
13959 		ret = -LIBBPF_ERRNO__FORMAT;
13960 		goto out;
13961 	}
13962 
13963 	elf = elf_memory((void *)entry.data, entry.data_length);
13964 	if (!elf) {
13965 		pr_warn("elf: could not read elf file %s from %s: %s\n", file_name, archive_path,
13966 			elf_errmsg(-1));
13967 		ret = -LIBBPF_ERRNO__LIBELF;
13968 		goto out;
13969 	}
13970 
13971 	ret = elf_find_func_offset(elf, file_name, func_name);
13972 	if (ret > 0) {
13973 		pr_debug("elf: symbol address match for %s of %s in %s: 0x%x + 0x%lx = 0x%lx\n",
13974 			 func_name, file_name, archive_path, entry.data_offset, (unsigned long)ret,
13975 			 (unsigned long)(ret + entry.data_offset));
13976 		ret += entry.data_offset;
13977 	}
13978 	elf_end(elf);
13979 
13980 out:
13981 	zip_archive_close(archive);
13982 	return ret;
13983 }
13984 
13985 static const char *arch_specific_lib_paths(void)
13986 {
13987 	/*
13988 	 * Based on https://packages.debian.org/sid/libc6.
13989 	 *
13990 	 * Assume that the traced program is built for the same architecture
13991 	 * as libbpf, which should cover the vast majority of cases.
13992 	 */
13993 #if defined(__x86_64__)
13994 	return "/lib/x86_64-linux-gnu";
13995 #elif defined(__i386__)
13996 	return "/lib/i386-linux-gnu";
13997 #elif defined(__s390x__)
13998 	return "/lib/s390x-linux-gnu";
13999 #elif defined(__arm__) && defined(__SOFTFP__)
14000 	return "/lib/arm-linux-gnueabi";
14001 #elif defined(__arm__) && !defined(__SOFTFP__)
14002 	return "/lib/arm-linux-gnueabihf";
14003 #elif defined(__aarch64__)
14004 	return "/lib/aarch64-linux-gnu";
14005 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 64
14006 	return "/lib/mips64el-linux-gnuabi64";
14007 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 32
14008 	return "/lib/mipsel-linux-gnu";
14009 #elif defined(__powerpc64__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
14010 	return "/lib/powerpc64le-linux-gnu";
14011 #elif defined(__sparc__) && defined(__arch64__)
14012 	return "/lib/sparc64-linux-gnu";
14013 #elif defined(__riscv) && __riscv_xlen == 64
14014 	return "/lib/riscv64-linux-gnu";
14015 #else
14016 	return NULL;
14017 #endif
14018 }
14019 
14020 /* Get full path to program/shared library. */
14021 static int resolve_full_path(const char *file, char *result, size_t result_sz)
14022 {
14023 	const char *search_paths[4] = {};
14024 	int i, perm;
14025 
14026 	if (str_has_sfx(file, ".so") || strstr(file, ".so.")) {
14027 		search_paths[0] = getenv("LD_LIBRARY_PATH");
14028 		search_paths[1] = "/usr/lib64:/usr/lib";
14029 		search_paths[2] = arch_specific_lib_paths();
14030 		search_paths[3] = "/lib64:/lib";
14031 		perm = R_OK;
14032 	} else {
14033 		search_paths[0] = getenv("PATH");
14034 		search_paths[1] = "/usr/bin:/usr/sbin";
14035 		perm = R_OK | X_OK;
14036 	}
14037 
14038 	for (i = 0; i < ARRAY_SIZE(search_paths); i++) {
14039 		const char *s;
14040 
14041 		if (!search_paths[i])
14042 			continue;
14043 		for (s = search_paths[i]; s != NULL; s = strchr(s, ':')) {
14044 			const char *next_path;
14045 			int seg_len;
14046 
14047 			if (s[0] == ':')
14048 				s++;
14049 			next_path = strchr(s, ':');
14050 			seg_len = next_path ? next_path - s : strlen(s);
14051 			if (!seg_len)
14052 				continue;
14053 			snprintf(result, result_sz, "%.*s/%s", seg_len, s, file);
14054 			/* ensure it has required permissions */
14055 			if (faccessat(AT_FDCWD, result, perm, AT_EACCESS) < 0)
14056 				continue;
14057 			pr_debug("resolved '%s' to '%s'\n", file, result);
14058 			return 0;
14059 		}
14060 	}
14061 	return -ENOENT;
14062 }
14063 
14064 struct bpf_link *
14065 bpf_program__attach_uprobe_multi(const struct bpf_program *prog,
14066 				 pid_t pid,
14067 				 const char *path,
14068 				 const char *func_pattern,
14069 				 const struct bpf_uprobe_multi_opts *opts)
14070 {
14071 	const unsigned long *ref_ctr_offsets = NULL, *offsets = NULL;
14072 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
14073 	unsigned long *resolved_offsets = NULL;
14074 	enum bpf_attach_type attach_type;
14075 	int err = 0, link_fd, prog_fd;
14076 	struct bpf_link *link = NULL;
14077 	char full_path[PATH_MAX];
14078 	bool retprobe, session;
14079 	const __u64 *cookies;
14080 	const char **syms;
14081 	size_t cnt;
14082 
14083 	if (!OPTS_VALID(opts, bpf_uprobe_multi_opts))
14084 		return libbpf_err_ptr(-EINVAL);
14085 
14086 	prog_fd = bpf_program__fd(prog);
14087 	if (prog_fd < 0) {
14088 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
14089 			prog->name);
14090 		return libbpf_err_ptr(-EINVAL);
14091 	}
14092 
14093 	syms = OPTS_GET(opts, syms, NULL);
14094 	offsets = OPTS_GET(opts, offsets, NULL);
14095 	ref_ctr_offsets = OPTS_GET(opts, ref_ctr_offsets, NULL);
14096 	cookies = OPTS_GET(opts, cookies, NULL);
14097 	cnt = OPTS_GET(opts, cnt, 0);
14098 	retprobe = OPTS_GET(opts, retprobe, false);
14099 	session  = OPTS_GET(opts, session, false);
14100 
14101 	/*
14102 	 * User can specify 2 mutually exclusive set of inputs:
14103 	 *
14104 	 * 1) use only path/func_pattern/pid arguments
14105 	 *
14106 	 * 2) use path/pid with allowed combinations of:
14107 	 *    syms/offsets/ref_ctr_offsets/cookies/cnt
14108 	 *
14109 	 *    - syms and offsets are mutually exclusive
14110 	 *    - ref_ctr_offsets and cookies are optional
14111 	 *
14112 	 * Any other usage results in error.
14113 	 */
14114 
14115 	if (!path)
14116 		return libbpf_err_ptr(-EINVAL);
14117 	if (!func_pattern && cnt == 0)
14118 		return libbpf_err_ptr(-EINVAL);
14119 
14120 	if (func_pattern) {
14121 		if (syms || offsets || ref_ctr_offsets || cookies || cnt)
14122 			return libbpf_err_ptr(-EINVAL);
14123 	} else {
14124 		if (!!syms == !!offsets)
14125 			return libbpf_err_ptr(-EINVAL);
14126 	}
14127 
14128 	if (retprobe && session)
14129 		return libbpf_err_ptr(-EINVAL);
14130 
14131 	if (func_pattern) {
14132 		if (!strchr(path, '/')) {
14133 			err = resolve_full_path(path, full_path, sizeof(full_path));
14134 			if (err) {
14135 				pr_warn("prog '%s': failed to resolve full path for '%s': %s\n",
14136 					prog->name, path, errstr(err));
14137 				return libbpf_err_ptr(err);
14138 			}
14139 			path = full_path;
14140 		}
14141 
14142 		err = elf_resolve_pattern_offsets(path, func_pattern,
14143 						  &resolved_offsets, &cnt);
14144 		if (err < 0)
14145 			return libbpf_err_ptr(err);
14146 		offsets = resolved_offsets;
14147 	} else if (syms) {
14148 		err = elf_resolve_syms_offsets(path, cnt, syms, &resolved_offsets, STT_FUNC);
14149 		if (err < 0)
14150 			return libbpf_err_ptr(err);
14151 		offsets = resolved_offsets;
14152 	}
14153 
14154 	attach_type = session ? BPF_TRACE_UPROBE_SESSION : BPF_TRACE_UPROBE_MULTI;
14155 
14156 	lopts.uprobe_multi.path = path;
14157 	lopts.uprobe_multi.offsets = offsets;
14158 	lopts.uprobe_multi.ref_ctr_offsets = ref_ctr_offsets;
14159 	lopts.uprobe_multi.cookies = cookies;
14160 	lopts.uprobe_multi.cnt = cnt;
14161 	lopts.uprobe_multi.flags = retprobe ? BPF_F_UPROBE_MULTI_RETURN : 0;
14162 
14163 	if (pid == 0)
14164 		pid = getpid();
14165 	if (pid > 0)
14166 		lopts.uprobe_multi.pid = pid;
14167 
14168 	link = calloc(1, sizeof(*link));
14169 	if (!link) {
14170 		err = -ENOMEM;
14171 		goto error;
14172 	}
14173 	link->detach = &bpf_link__detach_fd;
14174 
14175 	link_fd = bpf_link_create(prog_fd, 0, attach_type, &lopts);
14176 	if (link_fd < 0) {
14177 		err = -errno;
14178 		pr_warn("prog '%s': failed to attach multi-uprobe: %s\n",
14179 			prog->name, errstr(err));
14180 		goto error;
14181 	}
14182 	link->fd = link_fd;
14183 	free(resolved_offsets);
14184 	return link;
14185 
14186 error:
14187 	free(resolved_offsets);
14188 	free(link);
14189 	return libbpf_err_ptr(err);
14190 }
14191 
14192 LIBBPF_API struct bpf_link *
14193 bpf_program__attach_uprobe_opts(const struct bpf_program *prog, pid_t pid,
14194 				const char *binary_path, size_t func_offset,
14195 				const struct bpf_uprobe_opts *opts)
14196 {
14197 	const char *archive_path = NULL, *archive_sep = NULL;
14198 	char *legacy_probe = NULL;
14199 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
14200 	enum probe_attach_mode attach_mode;
14201 	char full_path[PATH_MAX];
14202 	struct bpf_link *link;
14203 	size_t ref_ctr_off;
14204 	int pfd, err;
14205 	bool retprobe, legacy;
14206 	const char *func_name;
14207 
14208 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
14209 		return libbpf_err_ptr(-EINVAL);
14210 
14211 	attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
14212 	retprobe = OPTS_GET(opts, retprobe, false);
14213 	ref_ctr_off = OPTS_GET(opts, ref_ctr_offset, 0);
14214 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
14215 
14216 	if (!binary_path)
14217 		return libbpf_err_ptr(-EINVAL);
14218 
14219 	/* Check if "binary_path" refers to an archive. */
14220 	archive_sep = strstr(binary_path, "!/");
14221 	if (archive_sep) {
14222 		full_path[0] = '\0';
14223 		libbpf_strlcpy(full_path, binary_path,
14224 			       min(sizeof(full_path), (size_t)(archive_sep - binary_path + 1)));
14225 		archive_path = full_path;
14226 		binary_path = archive_sep + 2;
14227 	} else if (!strchr(binary_path, '/')) {
14228 		err = resolve_full_path(binary_path, full_path, sizeof(full_path));
14229 		if (err) {
14230 			pr_warn("prog '%s': failed to resolve full path for '%s': %s\n",
14231 				prog->name, binary_path, errstr(err));
14232 			return libbpf_err_ptr(err);
14233 		}
14234 		binary_path = full_path;
14235 	}
14236 	func_name = OPTS_GET(opts, func_name, NULL);
14237 	if (func_name) {
14238 		long sym_off;
14239 
14240 		if (archive_path) {
14241 			sym_off = elf_find_func_offset_from_archive(archive_path, binary_path,
14242 								    func_name);
14243 			binary_path = archive_path;
14244 		} else {
14245 			sym_off = elf_find_func_offset_from_file(binary_path, func_name);
14246 		}
14247 		if (sym_off < 0)
14248 			return libbpf_err_ptr(sym_off);
14249 		func_offset += sym_off;
14250 	}
14251 
14252 	legacy = determine_uprobe_perf_type() < 0;
14253 	switch (attach_mode) {
14254 	case PROBE_ATTACH_MODE_LEGACY:
14255 		legacy = true;
14256 		pe_opts.force_ioctl_attach = true;
14257 		break;
14258 	case PROBE_ATTACH_MODE_PERF:
14259 		if (legacy)
14260 			return libbpf_err_ptr(-ENOTSUP);
14261 		pe_opts.force_ioctl_attach = true;
14262 		break;
14263 	case PROBE_ATTACH_MODE_LINK:
14264 		if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
14265 			return libbpf_err_ptr(-ENOTSUP);
14266 		break;
14267 	case PROBE_ATTACH_MODE_DEFAULT:
14268 		break;
14269 	default:
14270 		return libbpf_err_ptr(-EINVAL);
14271 	}
14272 
14273 	if (!legacy) {
14274 		pfd = perf_event_open_probe(true /* uprobe */, retprobe, binary_path,
14275 					    func_offset, pid, ref_ctr_off);
14276 	} else {
14277 		char probe_name[MAX_EVENT_NAME_LEN];
14278 
14279 		if (ref_ctr_off)
14280 			return libbpf_err_ptr(-EINVAL);
14281 
14282 		gen_probe_legacy_event_name(probe_name, sizeof(probe_name),
14283 					    strrchr(binary_path, '/') ? : binary_path,
14284 					    func_offset);
14285 
14286 		legacy_probe = strdup(probe_name);
14287 		if (!legacy_probe)
14288 			return libbpf_err_ptr(-ENOMEM);
14289 
14290 		pfd = perf_event_uprobe_open_legacy(legacy_probe, retprobe,
14291 						    binary_path, func_offset, pid);
14292 	}
14293 	if (pfd < 0) {
14294 		err = pfd;
14295 		pr_warn("prog '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
14296 			prog->name, retprobe ? "uretprobe" : "uprobe",
14297 			binary_path, func_offset,
14298 			errstr(err));
14299 		goto err_out;
14300 	}
14301 
14302 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
14303 	err = libbpf_get_error(link);
14304 	if (err) {
14305 		close(pfd);
14306 		pr_warn("prog '%s': failed to attach to %s '%s:0x%zx': %s\n",
14307 			prog->name, retprobe ? "uretprobe" : "uprobe",
14308 			binary_path, func_offset,
14309 			errstr(err));
14310 		goto err_clean_legacy;
14311 	}
14312 	if (legacy) {
14313 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
14314 
14315 		perf_link->legacy_probe_name = legacy_probe;
14316 		perf_link->legacy_is_kprobe = false;
14317 		perf_link->legacy_is_retprobe = retprobe;
14318 	}
14319 	return link;
14320 
14321 err_clean_legacy:
14322 	if (legacy)
14323 		remove_uprobe_event_legacy(legacy_probe, retprobe);
14324 err_out:
14325 	free(legacy_probe);
14326 	return libbpf_err_ptr(err);
14327 }
14328 
14329 /* Format of u[ret]probe section definition supporting auto-attach:
14330  * u[ret]probe/binary:function[+offset]
14331  *
14332  * binary can be an absolute/relative path or a filename; the latter is resolved to a
14333  * full binary path via bpf_program__attach_uprobe_opts.
14334  *
14335  * Specifying uprobe+ ensures we carry out strict matching; either "uprobe" must be
14336  * specified (and auto-attach is not possible) or the above format is specified for
14337  * auto-attach.
14338  */
14339 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
14340 {
14341 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts);
14342 	char *probe_type = NULL, *binary_path = NULL, *func_name = NULL, *func_off;
14343 	int n, c, ret = -EINVAL;
14344 	long offset = 0;
14345 
14346 	*link = NULL;
14347 
14348 	n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[^\n]",
14349 		   &probe_type, &binary_path, &func_name);
14350 	switch (n) {
14351 	case 1:
14352 		/* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
14353 		ret = 0;
14354 		break;
14355 	case 2:
14356 		pr_warn("prog '%s': section '%s' missing ':function[+offset]' specification\n",
14357 			prog->name, prog->sec_name);
14358 		break;
14359 	case 3:
14360 		/* check if user specifies `+offset`, if yes, this should be
14361 		 * the last part of the string, make sure sscanf read to EOL
14362 		 */
14363 		func_off = strrchr(func_name, '+');
14364 		if (func_off) {
14365 			n = sscanf(func_off, "+%li%n", &offset, &c);
14366 			if (n == 1 && *(func_off + c) == '\0')
14367 				func_off[0] = '\0';
14368 			else
14369 				offset = 0;
14370 		}
14371 		opts.retprobe = strcmp(probe_type, "uretprobe") == 0 ||
14372 				strcmp(probe_type, "uretprobe.s") == 0;
14373 		if (opts.retprobe && offset != 0) {
14374 			pr_warn("prog '%s': uretprobes do not support offset specification\n",
14375 				prog->name);
14376 			break;
14377 		}
14378 		opts.func_name = func_name;
14379 		*link = bpf_program__attach_uprobe_opts(prog, -1, binary_path, offset, &opts);
14380 		ret = libbpf_get_error(*link);
14381 		break;
14382 	default:
14383 		pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
14384 			prog->sec_name);
14385 		break;
14386 	}
14387 	free(probe_type);
14388 	free(binary_path);
14389 	free(func_name);
14390 
14391 	return ret;
14392 }
14393 
14394 struct bpf_link *bpf_program__attach_uprobe(const struct bpf_program *prog,
14395 					    bool retprobe, pid_t pid,
14396 					    const char *binary_path,
14397 					    size_t func_offset)
14398 {
14399 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts, .retprobe = retprobe);
14400 
14401 	return bpf_program__attach_uprobe_opts(prog, pid, binary_path, func_offset, &opts);
14402 }
14403 
14404 struct bpf_link *bpf_program__attach_usdt(const struct bpf_program *prog,
14405 					  pid_t pid, const char *binary_path,
14406 					  const char *usdt_provider, const char *usdt_name,
14407 					  const struct bpf_usdt_opts *opts)
14408 {
14409 	char resolved_path[512];
14410 	struct bpf_object *obj = prog->obj;
14411 	struct bpf_link *link;
14412 	__u64 usdt_cookie;
14413 	int err;
14414 
14415 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
14416 		return libbpf_err_ptr(-EINVAL);
14417 
14418 	if (bpf_program__fd(prog) < 0) {
14419 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
14420 			prog->name);
14421 		return libbpf_err_ptr(-EINVAL);
14422 	}
14423 
14424 	if (!binary_path)
14425 		return libbpf_err_ptr(-EINVAL);
14426 
14427 	if (!strchr(binary_path, '/')) {
14428 		err = resolve_full_path(binary_path, resolved_path, sizeof(resolved_path));
14429 		if (err) {
14430 			pr_warn("prog '%s': failed to resolve full path for '%s': %s\n",
14431 				prog->name, binary_path, errstr(err));
14432 			return libbpf_err_ptr(err);
14433 		}
14434 		binary_path = resolved_path;
14435 	}
14436 
14437 	/* USDT manager is instantiated lazily on first USDT attach. It will
14438 	 * be destroyed together with BPF object in bpf_object__close().
14439 	 */
14440 	if (IS_ERR(obj->usdt_man))
14441 		return libbpf_ptr(obj->usdt_man);
14442 	if (!obj->usdt_man) {
14443 		obj->usdt_man = usdt_manager_new(obj);
14444 		if (IS_ERR(obj->usdt_man))
14445 			return libbpf_ptr(obj->usdt_man);
14446 	}
14447 
14448 	usdt_cookie = OPTS_GET(opts, usdt_cookie, 0);
14449 	link = usdt_manager_attach_usdt(obj->usdt_man, prog, pid, binary_path,
14450 					usdt_provider, usdt_name, usdt_cookie);
14451 	err = libbpf_get_error(link);
14452 	if (err)
14453 		return libbpf_err_ptr(err);
14454 	return link;
14455 }
14456 
14457 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link)
14458 {
14459 	char *path = NULL, *provider = NULL, *name = NULL;
14460 	const char *sec_name;
14461 	int n, err;
14462 
14463 	sec_name = bpf_program__section_name(prog);
14464 	if (strcmp(sec_name, "usdt") == 0) {
14465 		/* no auto-attach for just SEC("usdt") */
14466 		*link = NULL;
14467 		return 0;
14468 	}
14469 
14470 	n = sscanf(sec_name, "usdt/%m[^:]:%m[^:]:%m[^:]", &path, &provider, &name);
14471 	if (n != 3) {
14472 		pr_warn("invalid section '%s', expected SEC(\"usdt/<path>:<provider>:<name>\")\n",
14473 			sec_name);
14474 		err = -EINVAL;
14475 	} else {
14476 		*link = bpf_program__attach_usdt(prog, -1 /* any process */, path,
14477 						 provider, name, NULL);
14478 		err = libbpf_get_error(*link);
14479 	}
14480 	free(path);
14481 	free(provider);
14482 	free(name);
14483 	return err;
14484 }
14485 
14486 static int determine_tracepoint_id(const char *tp_category,
14487 				   const char *tp_name)
14488 {
14489 	char file[PATH_MAX];
14490 	int ret;
14491 
14492 	ret = snprintf(file, sizeof(file), "%s/events/%s/%s/id",
14493 		       tracefs_path(), tp_category, tp_name);
14494 	if (ret < 0)
14495 		return -errno;
14496 	if (ret >= sizeof(file)) {
14497 		pr_debug("tracepoint %s/%s path is too long\n",
14498 			 tp_category, tp_name);
14499 		return -E2BIG;
14500 	}
14501 	return parse_uint_from_file(file, "%d\n");
14502 }
14503 
14504 static int perf_event_open_tracepoint(const char *tp_category,
14505 				      const char *tp_name)
14506 {
14507 	const size_t attr_sz = sizeof(struct perf_event_attr);
14508 	struct perf_event_attr attr;
14509 	int tp_id, pfd, err;
14510 
14511 	tp_id = determine_tracepoint_id(tp_category, tp_name);
14512 	if (tp_id < 0) {
14513 		pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
14514 			tp_category, tp_name,
14515 			errstr(tp_id));
14516 		return tp_id;
14517 	}
14518 
14519 	memset(&attr, 0, attr_sz);
14520 	attr.type = PERF_TYPE_TRACEPOINT;
14521 	attr.size = attr_sz;
14522 	attr.config = tp_id;
14523 
14524 	pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
14525 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
14526 	if (pfd < 0) {
14527 		err = -errno;
14528 		pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
14529 			tp_category, tp_name,
14530 			errstr(err));
14531 		return err;
14532 	}
14533 	return pfd;
14534 }
14535 
14536 struct bpf_link *bpf_program__attach_tracepoint_opts(const struct bpf_program *prog,
14537 						     const char *tp_category,
14538 						     const char *tp_name,
14539 						     const struct bpf_tracepoint_opts *opts)
14540 {
14541 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
14542 	struct bpf_link *link;
14543 	int pfd, err;
14544 
14545 	if (!OPTS_VALID(opts, bpf_tracepoint_opts))
14546 		return libbpf_err_ptr(-EINVAL);
14547 
14548 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
14549 
14550 	pfd = perf_event_open_tracepoint(tp_category, tp_name);
14551 	if (pfd < 0) {
14552 		pr_warn("prog '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
14553 			prog->name, tp_category, tp_name,
14554 			errstr(pfd));
14555 		return libbpf_err_ptr(pfd);
14556 	}
14557 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
14558 	err = libbpf_get_error(link);
14559 	if (err) {
14560 		close(pfd);
14561 		pr_warn("prog '%s': failed to attach to tracepoint '%s/%s': %s\n",
14562 			prog->name, tp_category, tp_name,
14563 			errstr(err));
14564 		return libbpf_err_ptr(err);
14565 	}
14566 	return link;
14567 }
14568 
14569 struct bpf_link *bpf_program__attach_tracepoint(const struct bpf_program *prog,
14570 						const char *tp_category,
14571 						const char *tp_name)
14572 {
14573 	return bpf_program__attach_tracepoint_opts(prog, tp_category, tp_name, NULL);
14574 }
14575 
14576 /*
14577  * Match section name against a prefix array. Returns pointer past
14578  * "prefix/" on match, empty string for bare sections (exact prefix
14579  * match), or NULL if no prefix matches.
14580  */
14581 static const char *sec_name_match_prefix(const char *sec_name,
14582 					 const char *const *prefixes,
14583 					 size_t n)
14584 {
14585 	size_t i;
14586 
14587 	for (i = 0; i < n; i++) {
14588 		size_t pfx_len;
14589 
14590 		if (!str_has_pfx(sec_name, prefixes[i]))
14591 			continue;
14592 
14593 		pfx_len = strlen(prefixes[i]);
14594 		if (sec_name[pfx_len] == '\0')
14595 			return sec_name + pfx_len;
14596 
14597 		if (sec_name[pfx_len] != '/' || sec_name[pfx_len + 1] == '\0')
14598 			continue;
14599 
14600 		return sec_name + pfx_len + 1;
14601 	}
14602 	return NULL;
14603 }
14604 
14605 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
14606 {
14607 	static const char *const prefixes[] = {
14608 		"tp.s",
14609 		"tp",
14610 		"tracepoint.s",
14611 		"tracepoint",
14612 	};
14613 	char *sec_name, *tp_cat, *tp_name;
14614 	const char *match;
14615 
14616 	*link = NULL;
14617 
14618 	match = sec_name_match_prefix(prog->sec_name, prefixes, ARRAY_SIZE(prefixes));
14619 	if (!match) {
14620 		pr_warn("prog '%s': invalid section name '%s'\n", prog->name, prog->sec_name);
14621 		return -EINVAL;
14622 	}
14623 	if (!match[0]) /* bare section name no autoattach */
14624 		return 0;
14625 
14626 	sec_name = strdup(prog->sec_name);
14627 	if (!sec_name)
14628 		return -ENOMEM;
14629 
14630 	tp_cat = sec_name + (match - prog->sec_name);
14631 	tp_name = strchr(tp_cat, '/');
14632 	if (!tp_name) {
14633 		free(sec_name);
14634 		return -EINVAL;
14635 	}
14636 	*tp_name = '\0';
14637 	tp_name++;
14638 
14639 	*link = bpf_program__attach_tracepoint(prog, tp_cat, tp_name);
14640 	free(sec_name);
14641 	return libbpf_get_error(*link);
14642 }
14643 
14644 struct bpf_link *
14645 bpf_program__attach_raw_tracepoint_opts(const struct bpf_program *prog,
14646 					const char *tp_name,
14647 					struct bpf_raw_tracepoint_opts *opts)
14648 {
14649 	LIBBPF_OPTS(bpf_raw_tp_opts, raw_opts);
14650 	struct bpf_link *link;
14651 	int prog_fd, pfd;
14652 
14653 	if (!OPTS_VALID(opts, bpf_raw_tracepoint_opts))
14654 		return libbpf_err_ptr(-EINVAL);
14655 
14656 	prog_fd = bpf_program__fd(prog);
14657 	if (prog_fd < 0) {
14658 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
14659 		return libbpf_err_ptr(-EINVAL);
14660 	}
14661 
14662 	link = calloc(1, sizeof(*link));
14663 	if (!link)
14664 		return libbpf_err_ptr(-ENOMEM);
14665 	link->detach = &bpf_link__detach_fd;
14666 
14667 	raw_opts.tp_name = tp_name;
14668 	raw_opts.cookie = OPTS_GET(opts, cookie, 0);
14669 	pfd = bpf_raw_tracepoint_open_opts(prog_fd, &raw_opts);
14670 	if (pfd < 0) {
14671 		pfd = -errno;
14672 		free(link);
14673 		pr_warn("prog '%s': failed to attach to raw tracepoint '%s': %s\n",
14674 			prog->name, tp_name, errstr(pfd));
14675 		return libbpf_err_ptr(pfd);
14676 	}
14677 	link->fd = pfd;
14678 	return link;
14679 }
14680 
14681 struct bpf_link *bpf_program__attach_raw_tracepoint(const struct bpf_program *prog,
14682 						    const char *tp_name)
14683 {
14684 	return bpf_program__attach_raw_tracepoint_opts(prog, tp_name, NULL);
14685 }
14686 
14687 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
14688 {
14689 	static const char *const prefixes[] = {
14690 		"raw_tp",
14691 		"raw_tracepoint",
14692 		"raw_tp.w",
14693 		"raw_tracepoint.w",
14694 		"raw_tp.s",
14695 		"raw_tracepoint.s",
14696 	};
14697 	const char *match;
14698 
14699 	*link = NULL;
14700 
14701 	match = sec_name_match_prefix(prog->sec_name, prefixes, ARRAY_SIZE(prefixes));
14702 	if (!match) {
14703 		pr_warn("prog '%s': invalid section name '%s'\n", prog->name, prog->sec_name);
14704 		return -EINVAL;
14705 	}
14706 	if (!match[0])
14707 		return 0;
14708 
14709 	*link = bpf_program__attach_raw_tracepoint(prog, match);
14710 	return libbpf_get_error(*link);
14711 }
14712 
14713 /* Common logic for all BPF program types that attach to a btf_id */
14714 static struct bpf_link *bpf_program__attach_btf_id(const struct bpf_program *prog,
14715 						   const struct bpf_trace_opts *opts)
14716 {
14717 	LIBBPF_OPTS(bpf_link_create_opts, link_opts);
14718 	struct bpf_link *link;
14719 	int prog_fd, pfd;
14720 
14721 	if (!OPTS_VALID(opts, bpf_trace_opts))
14722 		return libbpf_err_ptr(-EINVAL);
14723 
14724 	prog_fd = bpf_program__fd(prog);
14725 	if (prog_fd < 0) {
14726 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
14727 		return libbpf_err_ptr(-EINVAL);
14728 	}
14729 
14730 	link = calloc(1, sizeof(*link));
14731 	if (!link)
14732 		return libbpf_err_ptr(-ENOMEM);
14733 	link->detach = &bpf_link__detach_fd;
14734 
14735 	/* libbpf is smart enough to redirect to BPF_RAW_TRACEPOINT_OPEN on old kernels */
14736 	link_opts.tracing.cookie = OPTS_GET(opts, cookie, 0);
14737 	pfd = bpf_link_create(prog_fd, 0, bpf_program__expected_attach_type(prog), &link_opts);
14738 	if (pfd < 0) {
14739 		pfd = -errno;
14740 		free(link);
14741 		pr_warn("prog '%s': failed to attach: %s\n",
14742 			prog->name, errstr(pfd));
14743 		return libbpf_err_ptr(pfd);
14744 	}
14745 	link->fd = pfd;
14746 	return link;
14747 }
14748 
14749 struct bpf_link *bpf_program__attach_trace(const struct bpf_program *prog)
14750 {
14751 	return bpf_program__attach_btf_id(prog, NULL);
14752 }
14753 
14754 struct bpf_link *bpf_program__attach_trace_opts(const struct bpf_program *prog,
14755 						const struct bpf_trace_opts *opts)
14756 {
14757 	return bpf_program__attach_btf_id(prog, opts);
14758 }
14759 
14760 struct bpf_link *bpf_program__attach_lsm(const struct bpf_program *prog)
14761 {
14762 	return bpf_program__attach_btf_id(prog, NULL);
14763 }
14764 
14765 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link)
14766 {
14767 	*link = bpf_program__attach_trace(prog);
14768 	return libbpf_get_error(*link);
14769 }
14770 
14771 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link)
14772 {
14773 	*link = bpf_program__attach_lsm(prog);
14774 	return libbpf_get_error(*link);
14775 }
14776 
14777 static struct bpf_link *
14778 bpf_program_attach_fd(const struct bpf_program *prog,
14779 		      int target_fd, const char *target_name,
14780 		      const struct bpf_link_create_opts *opts)
14781 {
14782 	enum bpf_attach_type attach_type;
14783 	struct bpf_link *link;
14784 	int prog_fd, link_fd;
14785 
14786 	prog_fd = bpf_program__fd(prog);
14787 	if (prog_fd < 0) {
14788 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
14789 		return libbpf_err_ptr(-EINVAL);
14790 	}
14791 
14792 	link = calloc(1, sizeof(*link));
14793 	if (!link)
14794 		return libbpf_err_ptr(-ENOMEM);
14795 	link->detach = &bpf_link__detach_fd;
14796 
14797 	attach_type = bpf_program__expected_attach_type(prog);
14798 	link_fd = bpf_link_create(prog_fd, target_fd, attach_type, opts);
14799 	if (link_fd < 0) {
14800 		link_fd = -errno;
14801 		free(link);
14802 		pr_warn("prog '%s': failed to attach to %s: %s\n",
14803 			prog->name, target_name,
14804 			errstr(link_fd));
14805 		return libbpf_err_ptr(link_fd);
14806 	}
14807 	link->fd = link_fd;
14808 	return link;
14809 }
14810 
14811 struct bpf_link *
14812 bpf_program__attach_cgroup(const struct bpf_program *prog, int cgroup_fd)
14813 {
14814 	return bpf_program_attach_fd(prog, cgroup_fd, "cgroup", NULL);
14815 }
14816 
14817 struct bpf_link *
14818 bpf_program__attach_netns(const struct bpf_program *prog, int netns_fd)
14819 {
14820 	return bpf_program_attach_fd(prog, netns_fd, "netns", NULL);
14821 }
14822 
14823 struct bpf_link *
14824 bpf_program__attach_sockmap(const struct bpf_program *prog, int map_fd)
14825 {
14826 	return bpf_program_attach_fd(prog, map_fd, "sockmap", NULL);
14827 }
14828 
14829 struct bpf_link *bpf_program__attach_xdp(const struct bpf_program *prog, int ifindex)
14830 {
14831 	/* target_fd/target_ifindex use the same field in LINK_CREATE */
14832 	return bpf_program_attach_fd(prog, ifindex, "xdp", NULL);
14833 }
14834 
14835 struct bpf_link *
14836 bpf_program__attach_cgroup_opts(const struct bpf_program *prog, int cgroup_fd,
14837 				const struct bpf_cgroup_opts *opts)
14838 {
14839 	LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
14840 	__u32 relative_id;
14841 	int relative_fd;
14842 
14843 	if (!OPTS_VALID(opts, bpf_cgroup_opts))
14844 		return libbpf_err_ptr(-EINVAL);
14845 
14846 	relative_id = OPTS_GET(opts, relative_id, 0);
14847 	relative_fd = OPTS_GET(opts, relative_fd, 0);
14848 
14849 	if (relative_fd && relative_id) {
14850 		pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
14851 			prog->name);
14852 		return libbpf_err_ptr(-EINVAL);
14853 	}
14854 
14855 	link_create_opts.cgroup.expected_revision = OPTS_GET(opts, expected_revision, 0);
14856 	link_create_opts.cgroup.relative_fd = relative_fd;
14857 	link_create_opts.cgroup.relative_id = relative_id;
14858 	link_create_opts.flags = OPTS_GET(opts, flags, 0);
14859 
14860 	return bpf_program_attach_fd(prog, cgroup_fd, "cgroup", &link_create_opts);
14861 }
14862 
14863 struct bpf_link *
14864 bpf_program__attach_tcx(const struct bpf_program *prog, int ifindex,
14865 			const struct bpf_tcx_opts *opts)
14866 {
14867 	LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
14868 	__u32 relative_id;
14869 	int relative_fd;
14870 
14871 	if (!OPTS_VALID(opts, bpf_tcx_opts))
14872 		return libbpf_err_ptr(-EINVAL);
14873 
14874 	relative_id = OPTS_GET(opts, relative_id, 0);
14875 	relative_fd = OPTS_GET(opts, relative_fd, 0);
14876 
14877 	/* validate we don't have unexpected combinations of non-zero fields */
14878 	if (!ifindex) {
14879 		pr_warn("prog '%s': target netdevice ifindex cannot be zero\n",
14880 			prog->name);
14881 		return libbpf_err_ptr(-EINVAL);
14882 	}
14883 	if (relative_fd && relative_id) {
14884 		pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
14885 			prog->name);
14886 		return libbpf_err_ptr(-EINVAL);
14887 	}
14888 
14889 	link_create_opts.tcx.expected_revision = OPTS_GET(opts, expected_revision, 0);
14890 	link_create_opts.tcx.relative_fd = relative_fd;
14891 	link_create_opts.tcx.relative_id = relative_id;
14892 	link_create_opts.flags = OPTS_GET(opts, flags, 0);
14893 
14894 	/* target_fd/target_ifindex use the same field in LINK_CREATE */
14895 	return bpf_program_attach_fd(prog, ifindex, "tcx", &link_create_opts);
14896 }
14897 
14898 struct bpf_link *
14899 bpf_program__attach_netkit(const struct bpf_program *prog, int ifindex,
14900 			   const struct bpf_netkit_opts *opts)
14901 {
14902 	LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
14903 	__u32 relative_id;
14904 	int relative_fd;
14905 
14906 	if (!OPTS_VALID(opts, bpf_netkit_opts))
14907 		return libbpf_err_ptr(-EINVAL);
14908 
14909 	relative_id = OPTS_GET(opts, relative_id, 0);
14910 	relative_fd = OPTS_GET(opts, relative_fd, 0);
14911 
14912 	/* validate we don't have unexpected combinations of non-zero fields */
14913 	if (!ifindex) {
14914 		pr_warn("prog '%s': target netdevice ifindex cannot be zero\n",
14915 			prog->name);
14916 		return libbpf_err_ptr(-EINVAL);
14917 	}
14918 	if (relative_fd && relative_id) {
14919 		pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
14920 			prog->name);
14921 		return libbpf_err_ptr(-EINVAL);
14922 	}
14923 
14924 	link_create_opts.netkit.expected_revision = OPTS_GET(opts, expected_revision, 0);
14925 	link_create_opts.netkit.relative_fd = relative_fd;
14926 	link_create_opts.netkit.relative_id = relative_id;
14927 	link_create_opts.flags = OPTS_GET(opts, flags, 0);
14928 
14929 	return bpf_program_attach_fd(prog, ifindex, "netkit", &link_create_opts);
14930 }
14931 
14932 struct bpf_link *bpf_program__attach_freplace(const struct bpf_program *prog,
14933 					      int target_fd,
14934 					      const char *attach_func_name)
14935 {
14936 	int btf_id;
14937 
14938 	if (!!target_fd != !!attach_func_name) {
14939 		pr_warn("prog '%s': supply none or both of target_fd and attach_func_name\n",
14940 			prog->name);
14941 		return libbpf_err_ptr(-EINVAL);
14942 	}
14943 
14944 	if (prog->type != BPF_PROG_TYPE_EXT) {
14945 		pr_warn("prog '%s': only BPF_PROG_TYPE_EXT can attach as freplace\n",
14946 			prog->name);
14947 		return libbpf_err_ptr(-EINVAL);
14948 	}
14949 
14950 	if (target_fd) {
14951 		LIBBPF_OPTS(bpf_link_create_opts, target_opts);
14952 
14953 		btf_id = libbpf_find_prog_btf_id(attach_func_name, target_fd, prog->obj->token_fd);
14954 		if (btf_id < 0)
14955 			return libbpf_err_ptr(btf_id);
14956 
14957 		target_opts.target_btf_id = btf_id;
14958 
14959 		return bpf_program_attach_fd(prog, target_fd, "freplace",
14960 					     &target_opts);
14961 	} else {
14962 		/* no target, so use raw_tracepoint_open for compatibility
14963 		 * with old kernels
14964 		 */
14965 		return bpf_program__attach_trace(prog);
14966 	}
14967 }
14968 
14969 struct bpf_link *
14970 bpf_program__attach_iter(const struct bpf_program *prog,
14971 			 const struct bpf_iter_attach_opts *opts)
14972 {
14973 	DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
14974 	struct bpf_link *link;
14975 	int prog_fd, link_fd;
14976 	__u32 target_fd = 0;
14977 
14978 	if (!OPTS_VALID(opts, bpf_iter_attach_opts))
14979 		return libbpf_err_ptr(-EINVAL);
14980 
14981 	link_create_opts.iter_info = OPTS_GET(opts, link_info, (void *)0);
14982 	link_create_opts.iter_info_len = OPTS_GET(opts, link_info_len, 0);
14983 
14984 	prog_fd = bpf_program__fd(prog);
14985 	if (prog_fd < 0) {
14986 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
14987 		return libbpf_err_ptr(-EINVAL);
14988 	}
14989 
14990 	link = calloc(1, sizeof(*link));
14991 	if (!link)
14992 		return libbpf_err_ptr(-ENOMEM);
14993 	link->detach = &bpf_link__detach_fd;
14994 
14995 	link_fd = bpf_link_create(prog_fd, target_fd, BPF_TRACE_ITER,
14996 				  &link_create_opts);
14997 	if (link_fd < 0) {
14998 		link_fd = -errno;
14999 		free(link);
15000 		pr_warn("prog '%s': failed to attach to iterator: %s\n",
15001 			prog->name, errstr(link_fd));
15002 		return libbpf_err_ptr(link_fd);
15003 	}
15004 	link->fd = link_fd;
15005 	return link;
15006 }
15007 
15008 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link)
15009 {
15010 	*link = bpf_program__attach_iter(prog, NULL);
15011 	return libbpf_get_error(*link);
15012 }
15013 
15014 struct bpf_link *bpf_program__attach_netfilter(const struct bpf_program *prog,
15015 					       const struct bpf_netfilter_opts *opts)
15016 {
15017 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
15018 	struct bpf_link *link;
15019 	int prog_fd, link_fd;
15020 
15021 	if (!OPTS_VALID(opts, bpf_netfilter_opts))
15022 		return libbpf_err_ptr(-EINVAL);
15023 
15024 	prog_fd = bpf_program__fd(prog);
15025 	if (prog_fd < 0) {
15026 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
15027 		return libbpf_err_ptr(-EINVAL);
15028 	}
15029 
15030 	link = calloc(1, sizeof(*link));
15031 	if (!link)
15032 		return libbpf_err_ptr(-ENOMEM);
15033 
15034 	link->detach = &bpf_link__detach_fd;
15035 
15036 	lopts.netfilter.pf = OPTS_GET(opts, pf, 0);
15037 	lopts.netfilter.hooknum = OPTS_GET(opts, hooknum, 0);
15038 	lopts.netfilter.priority = OPTS_GET(opts, priority, 0);
15039 	lopts.netfilter.flags = OPTS_GET(opts, flags, 0);
15040 
15041 	link_fd = bpf_link_create(prog_fd, 0, BPF_NETFILTER, &lopts);
15042 	if (link_fd < 0) {
15043 		link_fd = -errno;
15044 		free(link);
15045 		pr_warn("prog '%s': failed to attach to netfilter: %s\n",
15046 			prog->name, errstr(link_fd));
15047 		return libbpf_err_ptr(link_fd);
15048 	}
15049 	link->fd = link_fd;
15050 
15051 	return link;
15052 }
15053 
15054 struct bpf_link *bpf_program__attach(const struct bpf_program *prog)
15055 {
15056 	struct bpf_link *link = NULL;
15057 	int err;
15058 
15059 	if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
15060 		return libbpf_err_ptr(-EOPNOTSUPP);
15061 
15062 	if (bpf_program__fd(prog) < 0) {
15063 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
15064 			prog->name);
15065 		return libbpf_err_ptr(-EINVAL);
15066 	}
15067 
15068 	err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, &link);
15069 	if (err)
15070 		return libbpf_err_ptr(err);
15071 
15072 	/* When calling bpf_program__attach() explicitly, auto-attach support
15073 	 * is expected to work, so NULL returned link is considered an error.
15074 	 * This is different for skeleton's attach, see comment in
15075 	 * bpf_object__attach_skeleton().
15076 	 */
15077 	if (!link)
15078 		return libbpf_err_ptr(-EOPNOTSUPP);
15079 
15080 	return link;
15081 }
15082 
15083 struct bpf_link_struct_ops {
15084 	struct bpf_link link;
15085 	int map_fd;
15086 };
15087 
15088 static int bpf_link__detach_struct_ops(struct bpf_link *link)
15089 {
15090 	struct bpf_link_struct_ops *st_link;
15091 	__u32 zero = 0;
15092 
15093 	st_link = container_of(link, struct bpf_link_struct_ops, link);
15094 
15095 	if (st_link->map_fd < 0)
15096 		/* w/o a real link */
15097 		return bpf_map_delete_elem(link->fd, &zero);
15098 
15099 	return close(link->fd);
15100 }
15101 
15102 struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map)
15103 {
15104 	struct bpf_link_struct_ops *link;
15105 	__u32 zero = 0;
15106 	int err, fd;
15107 
15108 	if (!bpf_map__is_struct_ops(map)) {
15109 		pr_warn("map '%s': can't attach non-struct_ops map\n", map->name);
15110 		return libbpf_err_ptr(-EINVAL);
15111 	}
15112 
15113 	if (map->fd < 0) {
15114 		pr_warn("map '%s': can't attach BPF map without FD (was it created?)\n", map->name);
15115 		return libbpf_err_ptr(-EINVAL);
15116 	}
15117 
15118 	link = calloc(1, sizeof(*link));
15119 	if (!link)
15120 		return libbpf_err_ptr(-EINVAL);
15121 
15122 	/* kern_vdata should be prepared during the loading phase. */
15123 	err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
15124 	/* It can be EBUSY if the map has been used to create or
15125 	 * update a link before.  We don't allow updating the value of
15126 	 * a struct_ops once it is set.  That ensures that the value
15127 	 * never changed.  So, it is safe to skip EBUSY.
15128 	 */
15129 	if (err && (!(map->def.map_flags & BPF_F_LINK) || err != -EBUSY)) {
15130 		free(link);
15131 		return libbpf_err_ptr(err);
15132 	}
15133 
15134 	link->link.detach = bpf_link__detach_struct_ops;
15135 
15136 	if (!(map->def.map_flags & BPF_F_LINK)) {
15137 		/* w/o a real link */
15138 		link->link.fd = map->fd;
15139 		link->map_fd = -1;
15140 		return &link->link;
15141 	}
15142 
15143 	fd = bpf_link_create(map->fd, 0, BPF_STRUCT_OPS, NULL);
15144 	if (fd < 0) {
15145 		free(link);
15146 		return libbpf_err_ptr(fd);
15147 	}
15148 
15149 	link->link.fd = fd;
15150 	link->map_fd = map->fd;
15151 
15152 	return &link->link;
15153 }
15154 
15155 struct bpf_link *bpf_map__attach_cgroup_opts(const struct bpf_map *map, int cgroup_fd,
15156 					     const struct bpf_cgroup_opts *opts)
15157 {
15158 	LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
15159 	struct bpf_link_struct_ops *link;
15160 	__u32 relative_id, zero = 0;
15161 	int err, fd, relative_fd;
15162 
15163 	if (!OPTS_VALID(opts, bpf_cgroup_opts))
15164 		return libbpf_err_ptr(-EINVAL);
15165 
15166 	if (!bpf_map__is_struct_ops(map)) {
15167 		pr_warn("map '%s': can't attach non-struct_ops map\n", map->name);
15168 		return libbpf_err_ptr(-EINVAL);
15169 	}
15170 
15171 	if (map->fd < 0) {
15172 		pr_warn("map '%s': can't attach BPF map without FD (was it created?)\n", map->name);
15173 		return libbpf_err_ptr(-EINVAL);
15174 	}
15175 
15176 	if (!(map->def.map_flags & BPF_F_LINK)) {
15177 		pr_warn("map '%s': can't attach to cgroup without BPF_F_LINK\n", map->name);
15178 		return libbpf_err_ptr(-EINVAL);
15179 	}
15180 
15181 	relative_id = OPTS_GET(opts, relative_id, 0);
15182 	relative_fd = OPTS_GET(opts, relative_fd, 0);
15183 
15184 	if (relative_fd && relative_id) {
15185 		pr_warn("map '%s': relative_fd and relative_id cannot be set at the same time\n",
15186 			map->name);
15187 		return libbpf_err_ptr(-EINVAL);
15188 	}
15189 
15190 	link_create_opts.cgroup.expected_revision = OPTS_GET(opts, expected_revision, 0);
15191 	link_create_opts.cgroup.relative_fd = relative_fd;
15192 	link_create_opts.cgroup.relative_id = relative_id;
15193 	link_create_opts.flags = OPTS_GET(opts, flags, 0);
15194 
15195 	link = calloc(1, sizeof(*link));
15196 	if (!link)
15197 		return libbpf_err_ptr(-ENOMEM);
15198 
15199 	err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
15200 	if (err && err != -EBUSY) {
15201 		free(link);
15202 		return libbpf_err_ptr(err);
15203 	}
15204 
15205 	link->link.detach = bpf_link__detach_struct_ops;
15206 
15207 	fd = bpf_link_create(map->fd, cgroup_fd, BPF_STRUCT_OPS, &link_create_opts);
15208 	if (fd < 0) {
15209 		free(link);
15210 		return libbpf_err_ptr(fd);
15211 	}
15212 
15213 	link->link.fd = fd;
15214 	link->map_fd = map->fd;
15215 
15216 	return &link->link;
15217 }
15218 
15219 /*
15220  * Swap the back struct_ops of a link with a new struct_ops map.
15221  */
15222 int bpf_link__update_map(struct bpf_link *link, const struct bpf_map *map)
15223 {
15224 	struct bpf_link_struct_ops *st_ops_link;
15225 	__u32 zero = 0;
15226 	int err;
15227 
15228 	if (!bpf_map__is_struct_ops(map))
15229 		return libbpf_err(-EINVAL);
15230 
15231 	if (map->fd < 0) {
15232 		pr_warn("map '%s': can't use BPF map without FD (was it created?)\n", map->name);
15233 		return libbpf_err(-EINVAL);
15234 	}
15235 
15236 	st_ops_link = container_of(link, struct bpf_link_struct_ops, link);
15237 	/* Ensure the type of a link is correct */
15238 	if (st_ops_link->map_fd < 0)
15239 		return libbpf_err(-EINVAL);
15240 
15241 	err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
15242 	/* It can be EBUSY if the map has been used to create or
15243 	 * update a link before.  We don't allow updating the value of
15244 	 * a struct_ops once it is set.  That ensures that the value
15245 	 * never changed.  So, it is safe to skip EBUSY.
15246 	 */
15247 	if (err && err != -EBUSY)
15248 		return err;
15249 
15250 	err = bpf_link_update(link->fd, map->fd, NULL);
15251 	if (err < 0)
15252 		return err;
15253 
15254 	st_ops_link->map_fd = map->fd;
15255 
15256 	return 0;
15257 }
15258 
15259 typedef enum bpf_perf_event_ret (*bpf_perf_event_print_t)(struct perf_event_header *hdr,
15260 							  void *private_data);
15261 
15262 static enum bpf_perf_event_ret
15263 perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
15264 		       void **copy_mem, size_t *copy_size,
15265 		       bpf_perf_event_print_t fn, void *private_data)
15266 {
15267 	struct perf_event_mmap_page *header = mmap_mem;
15268 	__u64 data_head = ring_buffer_read_head(header);
15269 	__u64 data_tail = header->data_tail;
15270 	void *base = ((__u8 *)header) + page_size;
15271 	int ret = LIBBPF_PERF_EVENT_CONT;
15272 	struct perf_event_header *ehdr;
15273 	size_t ehdr_size;
15274 
15275 	while (data_head != data_tail) {
15276 		ehdr = base + (data_tail & (mmap_size - 1));
15277 		ehdr_size = ehdr->size;
15278 
15279 		if (((void *)ehdr) + ehdr_size > base + mmap_size) {
15280 			void *copy_start = ehdr;
15281 			size_t len_first = base + mmap_size - copy_start;
15282 			size_t len_second = ehdr_size - len_first;
15283 
15284 			if (*copy_size < ehdr_size) {
15285 				free(*copy_mem);
15286 				*copy_mem = malloc(ehdr_size);
15287 				if (!*copy_mem) {
15288 					*copy_size = 0;
15289 					ret = LIBBPF_PERF_EVENT_ERROR;
15290 					break;
15291 				}
15292 				*copy_size = ehdr_size;
15293 			}
15294 
15295 			memcpy(*copy_mem, copy_start, len_first);
15296 			memcpy(*copy_mem + len_first, base, len_second);
15297 			ehdr = *copy_mem;
15298 		}
15299 
15300 		ret = fn(ehdr, private_data);
15301 		data_tail += ehdr_size;
15302 		if (ret != LIBBPF_PERF_EVENT_CONT)
15303 			break;
15304 	}
15305 
15306 	ring_buffer_write_tail(header, data_tail);
15307 	return libbpf_err(ret);
15308 }
15309 
15310 struct perf_buffer;
15311 
15312 struct perf_buffer_params {
15313 	struct perf_event_attr *attr;
15314 	/* if event_cb is specified, it takes precedence */
15315 	perf_buffer_event_fn event_cb;
15316 	/* sample_cb and lost_cb are higher-level common-case callbacks */
15317 	perf_buffer_sample_fn sample_cb;
15318 	perf_buffer_lost_fn lost_cb;
15319 	void *ctx;
15320 	int cpu_cnt;
15321 	int *cpus;
15322 	int *map_keys;
15323 };
15324 
15325 struct perf_cpu_buf {
15326 	struct perf_buffer *pb;
15327 	void *base; /* mmap()'ed memory */
15328 	void *buf; /* for reconstructing segmented data */
15329 	size_t buf_size;
15330 	int fd;
15331 	int cpu;
15332 	int map_key;
15333 };
15334 
15335 struct perf_buffer {
15336 	perf_buffer_event_fn event_cb;
15337 	perf_buffer_sample_fn sample_cb;
15338 	perf_buffer_lost_fn lost_cb;
15339 	void *ctx; /* passed into callbacks */
15340 
15341 	size_t page_size;
15342 	size_t mmap_size;
15343 	struct perf_cpu_buf **cpu_bufs;
15344 	struct epoll_event *events;
15345 	int cpu_cnt; /* number of allocated CPU buffers */
15346 	int epoll_fd; /* perf event FD */
15347 	int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
15348 };
15349 
15350 static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
15351 				      struct perf_cpu_buf *cpu_buf)
15352 {
15353 	if (!cpu_buf)
15354 		return;
15355 	if (cpu_buf->base &&
15356 	    munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
15357 		pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
15358 	if (cpu_buf->fd >= 0) {
15359 		ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
15360 		close(cpu_buf->fd);
15361 	}
15362 	free(cpu_buf->buf);
15363 	free(cpu_buf);
15364 }
15365 
15366 void perf_buffer__free(struct perf_buffer *pb)
15367 {
15368 	int i;
15369 
15370 	if (IS_ERR_OR_NULL(pb))
15371 		return;
15372 	if (pb->cpu_bufs) {
15373 		for (i = 0; i < pb->cpu_cnt; i++) {
15374 			struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
15375 
15376 			if (!cpu_buf)
15377 				continue;
15378 
15379 			bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
15380 			perf_buffer__free_cpu_buf(pb, cpu_buf);
15381 		}
15382 		free(pb->cpu_bufs);
15383 	}
15384 	if (pb->epoll_fd >= 0)
15385 		close(pb->epoll_fd);
15386 	free(pb->events);
15387 	free(pb);
15388 }
15389 
15390 static struct perf_cpu_buf *
15391 perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
15392 			  int cpu, int map_key)
15393 {
15394 	struct perf_cpu_buf *cpu_buf;
15395 	int err;
15396 
15397 	cpu_buf = calloc(1, sizeof(*cpu_buf));
15398 	if (!cpu_buf)
15399 		return ERR_PTR(-ENOMEM);
15400 
15401 	cpu_buf->pb = pb;
15402 	cpu_buf->cpu = cpu;
15403 	cpu_buf->map_key = map_key;
15404 
15405 	cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
15406 			      -1, PERF_FLAG_FD_CLOEXEC);
15407 	if (cpu_buf->fd < 0) {
15408 		err = -errno;
15409 		pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
15410 			cpu, errstr(err));
15411 		goto error;
15412 	}
15413 
15414 	cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
15415 			     PROT_READ | PROT_WRITE, MAP_SHARED,
15416 			     cpu_buf->fd, 0);
15417 	if (cpu_buf->base == MAP_FAILED) {
15418 		cpu_buf->base = NULL;
15419 		err = -errno;
15420 		pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
15421 			cpu, errstr(err));
15422 		goto error;
15423 	}
15424 
15425 	if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
15426 		err = -errno;
15427 		pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
15428 			cpu, errstr(err));
15429 		goto error;
15430 	}
15431 
15432 	return cpu_buf;
15433 
15434 error:
15435 	perf_buffer__free_cpu_buf(pb, cpu_buf);
15436 	return (struct perf_cpu_buf *)ERR_PTR(err);
15437 }
15438 
15439 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
15440 					      struct perf_buffer_params *p);
15441 
15442 struct perf_buffer *perf_buffer__new(int map_fd, size_t page_cnt,
15443 				     perf_buffer_sample_fn sample_cb,
15444 				     perf_buffer_lost_fn lost_cb,
15445 				     void *ctx,
15446 				     const struct perf_buffer_opts *opts)
15447 {
15448 	const size_t attr_sz = sizeof(struct perf_event_attr);
15449 	struct perf_buffer_params p = {};
15450 	struct perf_event_attr attr;
15451 	__u32 sample_period;
15452 
15453 	if (!OPTS_VALID(opts, perf_buffer_opts))
15454 		return libbpf_err_ptr(-EINVAL);
15455 
15456 	sample_period = OPTS_GET(opts, sample_period, 1);
15457 	if (!sample_period)
15458 		sample_period = 1;
15459 
15460 	memset(&attr, 0, attr_sz);
15461 	attr.size = attr_sz;
15462 	attr.config = PERF_COUNT_SW_BPF_OUTPUT;
15463 	attr.type = PERF_TYPE_SOFTWARE;
15464 	attr.sample_type = PERF_SAMPLE_RAW;
15465 	attr.wakeup_events = sample_period;
15466 
15467 	p.attr = &attr;
15468 	p.sample_cb = sample_cb;
15469 	p.lost_cb = lost_cb;
15470 	p.ctx = ctx;
15471 
15472 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
15473 }
15474 
15475 struct perf_buffer *perf_buffer__new_raw(int map_fd, size_t page_cnt,
15476 					 struct perf_event_attr *attr,
15477 					 perf_buffer_event_fn event_cb, void *ctx,
15478 					 const struct perf_buffer_raw_opts *opts)
15479 {
15480 	struct perf_buffer_params p = {};
15481 
15482 	if (!attr)
15483 		return libbpf_err_ptr(-EINVAL);
15484 
15485 	if (!OPTS_VALID(opts, perf_buffer_raw_opts))
15486 		return libbpf_err_ptr(-EINVAL);
15487 
15488 	p.attr = attr;
15489 	p.event_cb = event_cb;
15490 	p.ctx = ctx;
15491 	p.cpu_cnt = OPTS_GET(opts, cpu_cnt, 0);
15492 	p.cpus = OPTS_GET(opts, cpus, NULL);
15493 	p.map_keys = OPTS_GET(opts, map_keys, NULL);
15494 
15495 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
15496 }
15497 
15498 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
15499 					      struct perf_buffer_params *p)
15500 {
15501 	const char *online_cpus_file = "/sys/devices/system/cpu/online";
15502 	struct bpf_map_info map;
15503 	struct perf_buffer *pb;
15504 	bool *online = NULL;
15505 	__u32 map_info_len;
15506 	int err, i, j, n;
15507 
15508 	if (page_cnt == 0 || (page_cnt & (page_cnt - 1))) {
15509 		pr_warn("page count should be power of two, but is %zu\n",
15510 			page_cnt);
15511 		return ERR_PTR(-EINVAL);
15512 	}
15513 
15514 	/* best-effort sanity checks */
15515 	memset(&map, 0, sizeof(map));
15516 	map_info_len = sizeof(map);
15517 	err = bpf_map_get_info_by_fd(map_fd, &map, &map_info_len);
15518 	if (err) {
15519 		err = -errno;
15520 		/* if BPF_OBJ_GET_INFO_BY_FD is supported, will return
15521 		 * -EBADFD, -EFAULT, or -E2BIG on real error
15522 		 */
15523 		if (err != -EINVAL) {
15524 			pr_warn("failed to get map info for map FD %d: %s\n",
15525 				map_fd, errstr(err));
15526 			return ERR_PTR(err);
15527 		}
15528 		pr_debug("failed to get map info for FD %d; API not supported? Ignoring...\n",
15529 			 map_fd);
15530 	} else {
15531 		if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
15532 			pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
15533 				map.name);
15534 			return ERR_PTR(-EINVAL);
15535 		}
15536 	}
15537 
15538 	pb = calloc(1, sizeof(*pb));
15539 	if (!pb)
15540 		return ERR_PTR(-ENOMEM);
15541 
15542 	pb->event_cb = p->event_cb;
15543 	pb->sample_cb = p->sample_cb;
15544 	pb->lost_cb = p->lost_cb;
15545 	pb->ctx = p->ctx;
15546 
15547 	pb->page_size = getpagesize();
15548 	pb->mmap_size = pb->page_size * page_cnt;
15549 	pb->map_fd = map_fd;
15550 
15551 	pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
15552 	if (pb->epoll_fd < 0) {
15553 		err = -errno;
15554 		pr_warn("failed to create epoll instance: %s\n",
15555 			errstr(err));
15556 		goto error;
15557 	}
15558 
15559 	if (p->cpu_cnt > 0) {
15560 		pb->cpu_cnt = p->cpu_cnt;
15561 	} else {
15562 		pb->cpu_cnt = libbpf_num_possible_cpus();
15563 		if (pb->cpu_cnt < 0) {
15564 			err = pb->cpu_cnt;
15565 			goto error;
15566 		}
15567 		if (map.max_entries && map.max_entries < pb->cpu_cnt)
15568 			pb->cpu_cnt = map.max_entries;
15569 	}
15570 
15571 	pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
15572 	if (!pb->events) {
15573 		err = -ENOMEM;
15574 		pr_warn("failed to allocate events: out of memory\n");
15575 		goto error;
15576 	}
15577 	pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
15578 	if (!pb->cpu_bufs) {
15579 		err = -ENOMEM;
15580 		pr_warn("failed to allocate buffers: out of memory\n");
15581 		goto error;
15582 	}
15583 
15584 	err = parse_cpu_mask_file(online_cpus_file, &online, &n);
15585 	if (err) {
15586 		pr_warn("failed to get online CPU mask: %s\n", errstr(err));
15587 		goto error;
15588 	}
15589 
15590 	for (i = 0, j = 0; i < pb->cpu_cnt; i++) {
15591 		struct perf_cpu_buf *cpu_buf;
15592 		int cpu, map_key;
15593 
15594 		cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
15595 		map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
15596 
15597 		/* in case user didn't explicitly requested particular CPUs to
15598 		 * be attached to, skip offline/not present CPUs
15599 		 */
15600 		if (p->cpu_cnt <= 0 && (cpu >= n || !online[cpu]))
15601 			continue;
15602 
15603 		cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
15604 		if (IS_ERR(cpu_buf)) {
15605 			err = PTR_ERR(cpu_buf);
15606 			goto error;
15607 		}
15608 
15609 		pb->cpu_bufs[j] = cpu_buf;
15610 
15611 		err = bpf_map_update_elem(pb->map_fd, &map_key,
15612 					  &cpu_buf->fd, 0);
15613 		if (err) {
15614 			err = -errno;
15615 			pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
15616 				cpu, map_key, cpu_buf->fd,
15617 				errstr(err));
15618 			goto error;
15619 		}
15620 
15621 		pb->events[j].events = EPOLLIN;
15622 		pb->events[j].data.ptr = cpu_buf;
15623 		if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
15624 			      &pb->events[j]) < 0) {
15625 			err = -errno;
15626 			pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
15627 				cpu, cpu_buf->fd,
15628 				errstr(err));
15629 			goto error;
15630 		}
15631 		j++;
15632 	}
15633 	pb->cpu_cnt = j;
15634 	free(online);
15635 
15636 	return pb;
15637 
15638 error:
15639 	free(online);
15640 	if (pb)
15641 		perf_buffer__free(pb);
15642 	return ERR_PTR(err);
15643 }
15644 
15645 struct perf_sample_raw {
15646 	struct perf_event_header header;
15647 	uint32_t size;
15648 	char data[];
15649 };
15650 
15651 struct perf_sample_lost {
15652 	struct perf_event_header header;
15653 	uint64_t id;
15654 	uint64_t lost;
15655 	uint64_t sample_id;
15656 };
15657 
15658 static enum bpf_perf_event_ret
15659 perf_buffer__process_record(struct perf_event_header *e, void *ctx)
15660 {
15661 	struct perf_cpu_buf *cpu_buf = ctx;
15662 	struct perf_buffer *pb = cpu_buf->pb;
15663 	void *data = e;
15664 
15665 	/* user wants full control over parsing perf event */
15666 	if (pb->event_cb)
15667 		return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
15668 
15669 	switch (e->type) {
15670 	case PERF_RECORD_SAMPLE: {
15671 		struct perf_sample_raw *s = data;
15672 
15673 		if (pb->sample_cb)
15674 			pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
15675 		break;
15676 	}
15677 	case PERF_RECORD_LOST: {
15678 		struct perf_sample_lost *s = data;
15679 
15680 		if (pb->lost_cb)
15681 			pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
15682 		break;
15683 	}
15684 	default:
15685 		pr_warn("unknown perf sample type %u\n", e->type);
15686 		return LIBBPF_PERF_EVENT_ERROR;
15687 	}
15688 	return LIBBPF_PERF_EVENT_CONT;
15689 }
15690 
15691 static int perf_buffer__process_records(struct perf_buffer *pb,
15692 					struct perf_cpu_buf *cpu_buf)
15693 {
15694 	enum bpf_perf_event_ret ret;
15695 
15696 	ret = perf_event_read_simple(cpu_buf->base, pb->mmap_size,
15697 				     pb->page_size, &cpu_buf->buf,
15698 				     &cpu_buf->buf_size,
15699 				     perf_buffer__process_record, cpu_buf);
15700 	if (ret != LIBBPF_PERF_EVENT_CONT)
15701 		return ret;
15702 	return 0;
15703 }
15704 
15705 int perf_buffer__epoll_fd(const struct perf_buffer *pb)
15706 {
15707 	return pb->epoll_fd;
15708 }
15709 
15710 int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
15711 {
15712 	int i, cnt, err;
15713 
15714 	cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
15715 	if (cnt < 0)
15716 		return -errno;
15717 
15718 	for (i = 0; i < cnt; i++) {
15719 		struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
15720 
15721 		err = perf_buffer__process_records(pb, cpu_buf);
15722 		if (err) {
15723 			pr_warn("error while processing records: %s\n", errstr(err));
15724 			return libbpf_err(err);
15725 		}
15726 	}
15727 	return cnt;
15728 }
15729 
15730 /* Return number of PERF_EVENT_ARRAY map slots set up by this perf_buffer
15731  * manager.
15732  */
15733 size_t perf_buffer__buffer_cnt(const struct perf_buffer *pb)
15734 {
15735 	return pb->cpu_cnt;
15736 }
15737 
15738 /*
15739  * Return perf_event FD of a ring buffer in *buf_idx* slot of
15740  * PERF_EVENT_ARRAY BPF map. This FD can be polled for new data using
15741  * select()/poll()/epoll() Linux syscalls.
15742  */
15743 int perf_buffer__buffer_fd(const struct perf_buffer *pb, size_t buf_idx)
15744 {
15745 	struct perf_cpu_buf *cpu_buf;
15746 
15747 	if (buf_idx >= pb->cpu_cnt)
15748 		return libbpf_err(-EINVAL);
15749 
15750 	cpu_buf = pb->cpu_bufs[buf_idx];
15751 	if (!cpu_buf)
15752 		return libbpf_err(-ENOENT);
15753 
15754 	return cpu_buf->fd;
15755 }
15756 
15757 int perf_buffer__buffer(struct perf_buffer *pb, int buf_idx, void **buf, size_t *buf_size)
15758 {
15759 	struct perf_cpu_buf *cpu_buf;
15760 
15761 	if (buf_idx >= pb->cpu_cnt)
15762 		return libbpf_err(-EINVAL);
15763 
15764 	cpu_buf = pb->cpu_bufs[buf_idx];
15765 	if (!cpu_buf)
15766 		return libbpf_err(-ENOENT);
15767 
15768 	*buf = cpu_buf->base;
15769 	*buf_size = pb->mmap_size;
15770 	return 0;
15771 }
15772 
15773 /*
15774  * Consume data from perf ring buffer corresponding to slot *buf_idx* in
15775  * PERF_EVENT_ARRAY BPF map without waiting/polling. If there is no data to
15776  * consume, do nothing and return success.
15777  * Returns:
15778  *   - 0 on success;
15779  *   - <0 on failure.
15780  */
15781 int perf_buffer__consume_buffer(struct perf_buffer *pb, size_t buf_idx)
15782 {
15783 	struct perf_cpu_buf *cpu_buf;
15784 
15785 	if (buf_idx >= pb->cpu_cnt)
15786 		return libbpf_err(-EINVAL);
15787 
15788 	cpu_buf = pb->cpu_bufs[buf_idx];
15789 	if (!cpu_buf)
15790 		return libbpf_err(-ENOENT);
15791 
15792 	return perf_buffer__process_records(pb, cpu_buf);
15793 }
15794 
15795 int perf_buffer__consume(struct perf_buffer *pb)
15796 {
15797 	int i, err;
15798 
15799 	for (i = 0; i < pb->cpu_cnt; i++) {
15800 		struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
15801 
15802 		if (!cpu_buf)
15803 			continue;
15804 
15805 		err = perf_buffer__process_records(pb, cpu_buf);
15806 		if (err) {
15807 			pr_warn("perf_buffer: failed to process records in buffer #%d: %s\n",
15808 				i, errstr(err));
15809 			return libbpf_err(err);
15810 		}
15811 	}
15812 	return 0;
15813 }
15814 
15815 int bpf_program__set_attach_target(struct bpf_program *prog,
15816 				   int attach_prog_fd,
15817 				   const char *attach_func_name)
15818 {
15819 	int btf_obj_fd = 0, btf_id = 0, err;
15820 
15821 	if (!prog || attach_prog_fd < 0)
15822 		return libbpf_err(-EINVAL);
15823 
15824 	if (prog->obj->state >= OBJ_LOADED)
15825 		return libbpf_err(-EINVAL);
15826 
15827 	if (attach_prog_fd && !attach_func_name) {
15828 		/* Store attach_prog_fd. The BTF ID will be resolved later during
15829 		 * the normal object/program load phase.
15830 		 */
15831 		prog->attach_prog_fd = attach_prog_fd;
15832 		return 0;
15833 	}
15834 
15835 	if (attach_prog_fd) {
15836 		btf_id = libbpf_find_prog_btf_id(attach_func_name,
15837 						 attach_prog_fd, prog->obj->token_fd);
15838 		if (btf_id < 0)
15839 			return libbpf_err(btf_id);
15840 	} else {
15841 		if (!attach_func_name)
15842 			return libbpf_err(-EINVAL);
15843 
15844 		/* load btf_vmlinux, if not yet */
15845 		err = bpf_object__load_vmlinux_btf(prog->obj, true);
15846 		if (err)
15847 			return libbpf_err(err);
15848 		err = find_kernel_btf_id(prog->obj, attach_func_name,
15849 					 prog->expected_attach_type,
15850 					 &btf_obj_fd, &btf_id);
15851 		if (err)
15852 			return libbpf_err(err);
15853 	}
15854 
15855 	prog->attach_btf_id = btf_id;
15856 	prog->attach_btf_obj_fd = btf_obj_fd;
15857 	prog->attach_prog_fd = attach_prog_fd;
15858 	return 0;
15859 }
15860 
15861 int bpf_program__assoc_struct_ops(struct bpf_program *prog, struct bpf_map *map,
15862 				  struct bpf_prog_assoc_struct_ops_opts *opts)
15863 {
15864 	int prog_fd, map_fd;
15865 
15866 	prog_fd = bpf_program__fd(prog);
15867 	if (prog_fd < 0) {
15868 		pr_warn("prog '%s': can't associate BPF program without FD (was it loaded?)\n",
15869 			prog->name);
15870 		return libbpf_err(-EINVAL);
15871 	}
15872 
15873 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS) {
15874 		pr_warn("prog '%s': can't associate struct_ops program\n", prog->name);
15875 		return libbpf_err(-EINVAL);
15876 	}
15877 
15878 	map_fd = bpf_map__fd(map);
15879 	if (map_fd < 0) {
15880 		pr_warn("map '%s': can't associate BPF map without FD (was it created?)\n", map->name);
15881 		return libbpf_err(-EINVAL);
15882 	}
15883 
15884 	if (!bpf_map__is_struct_ops(map)) {
15885 		pr_warn("map '%s': can't associate non-struct_ops map\n", map->name);
15886 		return libbpf_err(-EINVAL);
15887 	}
15888 
15889 	return bpf_prog_assoc_struct_ops(prog_fd, map_fd, opts);
15890 }
15891 
15892 int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz)
15893 {
15894 	int err = 0, n, len, start, end = -1;
15895 	bool *tmp;
15896 
15897 	*mask = NULL;
15898 	*mask_sz = 0;
15899 
15900 	/* Each sub string separated by ',' has format \d+-\d+ or \d+ */
15901 	while (*s) {
15902 		if (*s == ',' || *s == '\n') {
15903 			s++;
15904 			continue;
15905 		}
15906 		n = sscanf(s, "%d%n-%d%n", &start, &len, &end, &len);
15907 		if (n <= 0 || n > 2) {
15908 			pr_warn("Failed to get CPU range %s: %d\n", s, n);
15909 			err = -EINVAL;
15910 			goto cleanup;
15911 		} else if (n == 1) {
15912 			end = start;
15913 		}
15914 		if (start < 0 || start > end) {
15915 			pr_warn("Invalid CPU range [%d,%d] in %s\n",
15916 				start, end, s);
15917 			err = -EINVAL;
15918 			goto cleanup;
15919 		}
15920 		tmp = realloc(*mask, end + 1);
15921 		if (!tmp) {
15922 			err = -ENOMEM;
15923 			goto cleanup;
15924 		}
15925 		*mask = tmp;
15926 		memset(tmp + *mask_sz, 0, start - *mask_sz);
15927 		memset(tmp + start, 1, end - start + 1);
15928 		*mask_sz = end + 1;
15929 		s += len;
15930 	}
15931 	if (!*mask_sz) {
15932 		pr_warn("Empty CPU range\n");
15933 		return -EINVAL;
15934 	}
15935 	return 0;
15936 cleanup:
15937 	free(*mask);
15938 	*mask = NULL;
15939 	return err;
15940 }
15941 
15942 int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz)
15943 {
15944 	int fd, err = 0, len;
15945 	char buf[128];
15946 
15947 	fd = open(fcpu, O_RDONLY | O_CLOEXEC);
15948 	if (fd < 0) {
15949 		err = -errno;
15950 		pr_warn("Failed to open cpu mask file %s: %s\n", fcpu, errstr(err));
15951 		return err;
15952 	}
15953 	len = read(fd, buf, sizeof(buf));
15954 	close(fd);
15955 	if (len <= 0) {
15956 		err = len ? -errno : -EINVAL;
15957 		pr_warn("Failed to read cpu mask from %s: %s\n", fcpu, errstr(err));
15958 		return err;
15959 	}
15960 	if (len >= sizeof(buf)) {
15961 		pr_warn("CPU mask is too big in file %s\n", fcpu);
15962 		return -E2BIG;
15963 	}
15964 	buf[len] = '\0';
15965 
15966 	return parse_cpu_mask_str(buf, mask, mask_sz);
15967 }
15968 
15969 int libbpf_num_possible_cpus(void)
15970 {
15971 	static const char *fcpu = "/sys/devices/system/cpu/possible";
15972 	static int cpus;
15973 	int err, n, i, tmp_cpus;
15974 	bool *mask;
15975 
15976 	tmp_cpus = READ_ONCE(cpus);
15977 	if (tmp_cpus > 0)
15978 		return tmp_cpus;
15979 
15980 	err = parse_cpu_mask_file(fcpu, &mask, &n);
15981 	if (err)
15982 		return libbpf_err(err);
15983 
15984 	tmp_cpus = 0;
15985 	for (i = 0; i < n; i++) {
15986 		if (mask[i])
15987 			tmp_cpus++;
15988 	}
15989 	free(mask);
15990 
15991 	WRITE_ONCE(cpus, tmp_cpus);
15992 	return tmp_cpus;
15993 }
15994 
15995 static int populate_skeleton_maps(const struct bpf_object *obj,
15996 				  struct bpf_map_skeleton *maps,
15997 				  size_t map_cnt, size_t map_skel_sz)
15998 {
15999 	int i;
16000 
16001 	for (i = 0; i < map_cnt; i++) {
16002 		struct bpf_map_skeleton *map_skel = (void *)maps + i * map_skel_sz;
16003 		struct bpf_map **map = map_skel->map;
16004 		const char *name = map_skel->name;
16005 		void **mmaped = map_skel->mmaped;
16006 
16007 		*map = bpf_object__find_map_by_name(obj, name);
16008 		if (!*map) {
16009 			pr_warn("failed to find skeleton map '%s'\n", name);
16010 			return -ESRCH;
16011 		}
16012 
16013 		/* externs shouldn't be pre-setup from user code */
16014 		if (mmaped && (*map)->libbpf_type != LIBBPF_MAP_KCONFIG)
16015 			*mmaped = (*map)->mmaped;
16016 	}
16017 	return 0;
16018 }
16019 
16020 static int populate_skeleton_progs(const struct bpf_object *obj,
16021 				   struct bpf_prog_skeleton *progs,
16022 				   size_t prog_cnt, size_t prog_skel_sz)
16023 {
16024 	int i;
16025 
16026 	for (i = 0; i < prog_cnt; i++) {
16027 		struct bpf_prog_skeleton *prog_skel = (void *)progs + i * prog_skel_sz;
16028 		struct bpf_program **prog = prog_skel->prog;
16029 		const char *name = prog_skel->name;
16030 
16031 		*prog = bpf_object__find_program_by_name(obj, name);
16032 		if (!*prog) {
16033 			pr_warn("failed to find skeleton program '%s'\n", name);
16034 			return -ESRCH;
16035 		}
16036 	}
16037 	return 0;
16038 }
16039 
16040 int bpf_object__open_skeleton(struct bpf_object_skeleton *s,
16041 			      const struct bpf_object_open_opts *opts)
16042 {
16043 	struct bpf_object *obj;
16044 	int err;
16045 
16046 	obj = bpf_object_open(NULL, s->data, s->data_sz, s->name, opts);
16047 	if (IS_ERR(obj)) {
16048 		err = PTR_ERR(obj);
16049 		pr_warn("failed to initialize skeleton BPF object '%s': %s\n",
16050 			s->name, errstr(err));
16051 		return libbpf_err(err);
16052 	}
16053 
16054 	*s->obj = obj;
16055 	err = populate_skeleton_maps(obj, s->maps, s->map_cnt, s->map_skel_sz);
16056 	if (err) {
16057 		pr_warn("failed to populate skeleton maps for '%s': %s\n", s->name, errstr(err));
16058 		return libbpf_err(err);
16059 	}
16060 
16061 	err = populate_skeleton_progs(obj, s->progs, s->prog_cnt, s->prog_skel_sz);
16062 	if (err) {
16063 		pr_warn("failed to populate skeleton progs for '%s': %s\n", s->name, errstr(err));
16064 		return libbpf_err(err);
16065 	}
16066 
16067 	return 0;
16068 }
16069 
16070 int bpf_object__open_subskeleton(struct bpf_object_subskeleton *s)
16071 {
16072 	int err, len, var_idx, i;
16073 	const char *var_name;
16074 	const struct bpf_map *map;
16075 	struct btf *btf;
16076 	__u32 map_type_id;
16077 	const struct btf_type *map_type, *var_type;
16078 	const struct bpf_var_skeleton *var_skel;
16079 	struct btf_var_secinfo *var;
16080 
16081 	if (!s->obj)
16082 		return libbpf_err(-EINVAL);
16083 
16084 	btf = bpf_object__btf(s->obj);
16085 	if (!btf) {
16086 		pr_warn("subskeletons require BTF at runtime (object %s)\n",
16087 			bpf_object__name(s->obj));
16088 		return libbpf_err(-errno);
16089 	}
16090 
16091 	err = populate_skeleton_maps(s->obj, s->maps, s->map_cnt, s->map_skel_sz);
16092 	if (err) {
16093 		pr_warn("failed to populate subskeleton maps: %s\n", errstr(err));
16094 		return libbpf_err(err);
16095 	}
16096 
16097 	err = populate_skeleton_progs(s->obj, s->progs, s->prog_cnt, s->prog_skel_sz);
16098 	if (err) {
16099 		pr_warn("failed to populate subskeleton maps: %s\n", errstr(err));
16100 		return libbpf_err(err);
16101 	}
16102 
16103 	for (var_idx = 0; var_idx < s->var_cnt; var_idx++) {
16104 		var_skel = (void *)s->vars + var_idx * s->var_skel_sz;
16105 		map = *var_skel->map;
16106 		map_type_id = bpf_map__btf_value_type_id(map);
16107 		map_type = btf__type_by_id(btf, map_type_id);
16108 
16109 		if (!btf_is_datasec(map_type)) {
16110 			pr_warn("type for map '%1$s' is not a datasec: %2$s\n",
16111 				bpf_map__name(map),
16112 				__btf_kind_str(btf_kind(map_type)));
16113 			return libbpf_err(-EINVAL);
16114 		}
16115 
16116 		len = btf_vlen(map_type);
16117 		var = btf_var_secinfos(map_type);
16118 		for (i = 0; i < len; i++, var++) {
16119 			var_type = btf__type_by_id(btf, var->type);
16120 			var_name = btf__name_by_offset(btf, var_type->name_off);
16121 			if (strcmp(var_name, var_skel->name) == 0) {
16122 				*var_skel->addr = map->mmaped + var->offset;
16123 				break;
16124 			}
16125 		}
16126 	}
16127 	return 0;
16128 }
16129 
16130 void bpf_object__destroy_subskeleton(struct bpf_object_subskeleton *s)
16131 {
16132 	if (!s)
16133 		return;
16134 	free(s->maps);
16135 	free(s->progs);
16136 	free(s->vars);
16137 	free(s);
16138 }
16139 
16140 int bpf_object__load_skeleton(struct bpf_object_skeleton *s)
16141 {
16142 	int i, err;
16143 
16144 	err = bpf_object__load(*s->obj);
16145 	if (err) {
16146 		pr_warn("failed to load BPF skeleton '%s': %s\n", s->name, errstr(err));
16147 		return libbpf_err(err);
16148 	}
16149 
16150 	for (i = 0; i < s->map_cnt; i++) {
16151 		struct bpf_map_skeleton *map_skel = (void *)s->maps + i * s->map_skel_sz;
16152 		struct bpf_map *map = *map_skel->map;
16153 
16154 		if (!map_skel->mmaped)
16155 			continue;
16156 
16157 		if (map->def.type == BPF_MAP_TYPE_ARENA)
16158 			*map_skel->mmaped = map->mmaped + map->obj->arena_data_off;
16159 		else
16160 			*map_skel->mmaped = map->mmaped;
16161 	}
16162 
16163 	return 0;
16164 }
16165 
16166 int bpf_object__attach_skeleton(struct bpf_object_skeleton *s)
16167 {
16168 	int i, err;
16169 
16170 	for (i = 0; i < s->prog_cnt; i++) {
16171 		struct bpf_prog_skeleton *prog_skel = (void *)s->progs + i * s->prog_skel_sz;
16172 		struct bpf_program *prog = *prog_skel->prog;
16173 		struct bpf_link **link = prog_skel->link;
16174 
16175 		if (!prog->autoload || !prog->autoattach)
16176 			continue;
16177 
16178 		/* auto-attaching not supported for this program */
16179 		if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
16180 			continue;
16181 
16182 		/* if user already set the link manually, don't attempt auto-attach */
16183 		if (*link)
16184 			continue;
16185 
16186 		err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, link);
16187 		if (err) {
16188 			pr_warn("prog '%s': failed to auto-attach: %s\n",
16189 				bpf_program__name(prog), errstr(err));
16190 			return libbpf_err(err);
16191 		}
16192 
16193 		/* It's possible that for some SEC() definitions auto-attach
16194 		 * is supported in some cases (e.g., if definition completely
16195 		 * specifies target information), but is not in other cases.
16196 		 * SEC("uprobe") is one such case. If user specified target
16197 		 * binary and function name, such BPF program can be
16198 		 * auto-attached. But if not, it shouldn't trigger skeleton's
16199 		 * attach to fail. It should just be skipped.
16200 		 * attach_fn signals such case with returning 0 (no error) and
16201 		 * setting link to NULL.
16202 		 */
16203 	}
16204 
16205 
16206 	for (i = 0; i < s->map_cnt; i++) {
16207 		struct bpf_map_skeleton *map_skel = (void *)s->maps + i * s->map_skel_sz;
16208 		struct bpf_map *map = *map_skel->map;
16209 		struct bpf_link **link;
16210 
16211 		if (!map->autocreate || !map->autoattach)
16212 			continue;
16213 
16214 		/* only struct_ops maps can be attached */
16215 		if (!bpf_map__is_struct_ops(map))
16216 			continue;
16217 
16218 		/* skeleton is created with earlier version of bpftool, notify user */
16219 		if (s->map_skel_sz < offsetofend(struct bpf_map_skeleton, link)) {
16220 			pr_warn("map '%s': BPF skeleton version is old, skipping map auto-attachment...\n",
16221 				bpf_map__name(map));
16222 			continue;
16223 		}
16224 
16225 		link = map_skel->link;
16226 		if (!link) {
16227 			pr_warn("map '%s': BPF map skeleton link is uninitialized\n",
16228 				bpf_map__name(map));
16229 			continue;
16230 		}
16231 
16232 		if (*link)
16233 			continue;
16234 
16235 		*link = bpf_map__attach_struct_ops(map);
16236 		if (!*link) {
16237 			err = -errno;
16238 			pr_warn("map '%s': failed to auto-attach: %s\n",
16239 				bpf_map__name(map), errstr(err));
16240 			return libbpf_err(err);
16241 		}
16242 	}
16243 
16244 	return 0;
16245 }
16246 
16247 void bpf_object__detach_skeleton(struct bpf_object_skeleton *s)
16248 {
16249 	int i;
16250 
16251 	for (i = 0; i < s->prog_cnt; i++) {
16252 		struct bpf_prog_skeleton *prog_skel = (void *)s->progs + i * s->prog_skel_sz;
16253 		struct bpf_link **link = prog_skel->link;
16254 
16255 		bpf_link__destroy(*link);
16256 		*link = NULL;
16257 	}
16258 
16259 	if (s->map_skel_sz < sizeof(struct bpf_map_skeleton))
16260 		return;
16261 
16262 	for (i = 0; i < s->map_cnt; i++) {
16263 		struct bpf_map_skeleton *map_skel = (void *)s->maps + i * s->map_skel_sz;
16264 		struct bpf_link **link = map_skel->link;
16265 
16266 		if (link) {
16267 			bpf_link__destroy(*link);
16268 			*link = NULL;
16269 		}
16270 	}
16271 }
16272 
16273 void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s)
16274 {
16275 	if (!s)
16276 		return;
16277 
16278 	bpf_object__detach_skeleton(s);
16279 	if (s->obj)
16280 		bpf_object__close(*s->obj);
16281 	free(s->maps);
16282 	free(s->progs);
16283 	free(s);
16284 }
16285