xref: /linux/tools/lib/bpf/libbpf.c (revision 1cec0b70fdc678d6c0252f3f25e23df0b5a5e49c)
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 	size_t fd_array_cnt;
798 
799 	struct usdt_manager *usdt_man;
800 
801 	int arena_map_idx;
802 	void *arena_data;
803 	size_t arena_data_sz;
804 	size_t arena_data_off;
805 	bool data_in_arena;
806 	bool arena_mapped;
807 	/* pointers to data in the data of internal maps, when data is in arena */
808 	struct data_ptr {
809 		int sec_idx;
810 		size_t sec_off;
811 		int targ_sec_idx;
812 		size_t targ_off;
813 		char *sym_name;
814 	} *data_ptrs;
815 	size_t data_ptr_cnt;
816 
817 	void *jumptables_data;
818 	size_t jumptables_data_sz;
819 
820 	struct {
821 		struct bpf_program *prog;
822 		unsigned int sym_off;
823 		int fd;
824 	} *jumptable_maps;
825 	size_t jumptable_map_cnt;
826 
827 	/*
828 	 * Pointers to functions found in read-only data sections: tables of
829 	 * functions, structures of operations, vtables. Sorted by section
830 	 * and offset.
831 	 */
832 	struct func_ptr {
833 		int sec_idx;		/* ELF section that contains the pointer */
834 		size_t sec_off;		/* offset of the pointer in the section */
835 		size_t text_off;	/* offset of the function in .text section */
836 	} *func_ptrs;
837 	size_t func_ptr_cnt;
838 
839 	/*
840 	 * Read-only data with pointers to functions is different for every
841 	 * program that uses it, because so are the offsets of the functions.
842 	 */
843 	struct {
844 		struct bpf_program *prog;
845 		int map_idx;
846 		int fd;
847 	} *func_ptr_maps;
848 	size_t func_ptr_map_cnt;
849 
850 	struct kern_feature_cache *feat_cache;
851 	char *token_path;
852 	int token_fd;
853 
854 	char path[];
855 };
856 
857 static const char *elf_sym_str(const struct bpf_object *obj, size_t off);
858 static const char *elf_sec_str(const struct bpf_object *obj, size_t off);
859 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx);
860 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name);
861 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn);
862 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn);
863 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn);
864 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx);
865 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx);
866 
867 void bpf_program__unload(struct bpf_program *prog)
868 {
869 	if (!prog)
870 		return;
871 
872 	zclose(prog->fd);
873 
874 	zfree(&prog->func_info);
875 	zfree(&prog->line_info);
876 	zfree(&prog->subprogs);
877 }
878 
879 static void bpf_program__exit(struct bpf_program *prog)
880 {
881 	if (!prog)
882 		return;
883 
884 	bpf_program__unload(prog);
885 	zfree(&prog->name);
886 	zfree(&prog->sec_name);
887 	zfree(&prog->insns);
888 	zfree(&prog->reloc_desc);
889 
890 	prog->nr_reloc = 0;
891 	prog->insns_cnt = 0;
892 	prog->sec_idx = -1;
893 }
894 
895 static bool insn_is_subprog_call(const struct bpf_insn *insn)
896 {
897 	return BPF_CLASS(insn->code) == BPF_JMP &&
898 	       BPF_OP(insn->code) == BPF_CALL &&
899 	       BPF_SRC(insn->code) == BPF_K &&
900 	       insn->src_reg == BPF_PSEUDO_CALL &&
901 	       insn->dst_reg == 0 &&
902 	       insn->off == 0;
903 }
904 
905 static bool is_call_insn(const struct bpf_insn *insn)
906 {
907 	return insn->code == (BPF_JMP | BPF_CALL);
908 }
909 
910 static bool insn_is_pseudo_func(struct bpf_insn *insn)
911 {
912 	return is_ldimm64_insn(insn) && insn->src_reg == BPF_PSEUDO_FUNC;
913 }
914 
915 static bool prog_has_callx(const struct bpf_program *prog)
916 {
917 	size_t i;
918 
919 	for (i = 0; i < prog->insns_cnt; i++)
920 		if (prog->insns[i].code == (BPF_JMP | BPF_CALL | BPF_X))
921 			return true;
922 	return false;
923 }
924 
925 static int
926 bpf_object__init_prog(struct bpf_object *obj, struct bpf_program *prog,
927 		      const char *name, size_t sec_idx, const char *sec_name,
928 		      size_t sec_off, void *insn_data, size_t insn_data_sz)
929 {
930 	if (insn_data_sz == 0 || insn_data_sz % BPF_INSN_SZ || sec_off % BPF_INSN_SZ) {
931 		pr_warn("sec '%s': corrupted program '%s', offset %zu, size %zu\n",
932 			sec_name, name, sec_off, insn_data_sz);
933 		return -EINVAL;
934 	}
935 
936 	memset(prog, 0, sizeof(*prog));
937 	prog->obj = obj;
938 
939 	prog->sec_idx = sec_idx;
940 	prog->sec_insn_off = sec_off / BPF_INSN_SZ;
941 	prog->sec_insn_cnt = insn_data_sz / BPF_INSN_SZ;
942 	/* insns_cnt can later be increased by appending used subprograms */
943 	prog->insns_cnt = prog->sec_insn_cnt;
944 
945 	prog->type = BPF_PROG_TYPE_UNSPEC;
946 	prog->fd = -1;
947 	prog->exception_cb_idx = -1;
948 
949 	/* libbpf's convention for SEC("?abc...") is that it's just like
950 	 * SEC("abc...") but the corresponding bpf_program starts out with
951 	 * autoload set to false.
952 	 */
953 	if (sec_name[0] == '?') {
954 		prog->autoload = false;
955 		/* from now on forget there was ? in section name */
956 		sec_name++;
957 	} else {
958 		prog->autoload = true;
959 	}
960 
961 	prog->autoattach = true;
962 
963 	/* inherit object's log_level */
964 	prog->log_level = obj->log_level;
965 
966 	prog->sec_name = strdup(sec_name);
967 	if (!prog->sec_name)
968 		goto errout;
969 
970 	prog->name = strdup(name);
971 	if (!prog->name)
972 		goto errout;
973 
974 	prog->insns = malloc(insn_data_sz);
975 	if (!prog->insns)
976 		goto errout;
977 	memcpy(prog->insns, insn_data, insn_data_sz);
978 
979 	return 0;
980 errout:
981 	pr_warn("sec '%s': failed to allocate memory for prog '%s'\n", sec_name, name);
982 	bpf_program__exit(prog);
983 	return -ENOMEM;
984 }
985 
986 static int
987 bpf_object__add_programs(struct bpf_object *obj, Elf_Data *sec_data,
988 			 const char *sec_name, int sec_idx)
989 {
990 	Elf_Data *symbols = obj->efile.symbols;
991 	struct bpf_program *prog, *progs;
992 	void *data = sec_data->d_buf;
993 	size_t sec_sz = sec_data->d_size, sec_off, prog_sz, nr_syms;
994 	int nr_progs, err, i;
995 	const char *name;
996 	Elf64_Sym *sym;
997 
998 	progs = obj->programs;
999 	nr_progs = obj->nr_programs;
1000 	nr_syms = symbols->d_size / sizeof(Elf64_Sym);
1001 
1002 	for (i = 0; i < nr_syms; i++) {
1003 		sym = elf_sym_by_idx(obj, i);
1004 
1005 		if (sym->st_shndx != sec_idx)
1006 			continue;
1007 		if (ELF64_ST_TYPE(sym->st_info) != STT_FUNC)
1008 			continue;
1009 
1010 		prog_sz = sym->st_size;
1011 		sec_off = sym->st_value;
1012 
1013 		name = elf_sym_str(obj, sym->st_name);
1014 		if (!name) {
1015 			pr_warn("sec '%s': failed to get symbol name for offset %zu\n",
1016 				sec_name, sec_off);
1017 			return -LIBBPF_ERRNO__FORMAT;
1018 		}
1019 
1020 		if (sec_off + prog_sz > sec_sz || sec_off + prog_sz < sec_off) {
1021 			pr_warn("sec '%s': program at offset %zu crosses section boundary\n",
1022 				sec_name, sec_off);
1023 			return -LIBBPF_ERRNO__FORMAT;
1024 		}
1025 
1026 		if (sec_idx != obj->efile.text_shndx && ELF64_ST_BIND(sym->st_info) == STB_LOCAL) {
1027 			pr_warn("sec '%s': program '%s' is static and not supported\n", sec_name, name);
1028 			return -ENOTSUP;
1029 		}
1030 
1031 		pr_debug("sec '%s': found program '%s' at insn offset %zu (%zu bytes), code size %zu insns (%zu bytes)\n",
1032 			 sec_name, name, sec_off / BPF_INSN_SZ, sec_off, prog_sz / BPF_INSN_SZ, prog_sz);
1033 
1034 		progs = libbpf_reallocarray(progs, nr_progs + 1, sizeof(*progs));
1035 		if (!progs) {
1036 			/*
1037 			 * In this case the original obj->programs
1038 			 * is still valid, so don't need special treat for
1039 			 * bpf_close_object().
1040 			 */
1041 			pr_warn("sec '%s': failed to alloc memory for new program '%s'\n",
1042 				sec_name, name);
1043 			return -ENOMEM;
1044 		}
1045 		obj->programs = progs;
1046 
1047 		prog = &progs[nr_progs];
1048 
1049 		err = bpf_object__init_prog(obj, prog, name, sec_idx, sec_name,
1050 					    sec_off, data + sec_off, prog_sz);
1051 		if (err)
1052 			return err;
1053 
1054 		if (ELF64_ST_BIND(sym->st_info) != STB_LOCAL)
1055 			prog->sym_global = true;
1056 
1057 		/* if function is a global/weak symbol, but has restricted
1058 		 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF FUNC
1059 		 * as static to enable more permissive BPF verification mode
1060 		 * with more outside context available to BPF verifier
1061 		 */
1062 		if (prog->sym_global && (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
1063 		    || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL))
1064 			prog->mark_btf_static = true;
1065 
1066 		nr_progs++;
1067 		obj->nr_programs = nr_progs;
1068 	}
1069 
1070 	return 0;
1071 }
1072 
1073 static void bpf_object_bswap_progs(struct bpf_object *obj)
1074 {
1075 	struct bpf_program *prog = obj->programs;
1076 	struct bpf_insn *insn;
1077 	int p, i;
1078 
1079 	for (p = 0; p < obj->nr_programs; p++, prog++) {
1080 		insn = prog->insns;
1081 		for (i = 0; i < prog->insns_cnt; i++, insn++)
1082 			bpf_insn_bswap(insn);
1083 	}
1084 	pr_debug("converted %zu BPF programs to native byte order\n", obj->nr_programs);
1085 }
1086 
1087 static const struct btf_member *
1088 find_member_by_offset(const struct btf_type *t, __u32 bit_offset)
1089 {
1090 	struct btf_member *m;
1091 	int i;
1092 
1093 	for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
1094 		if (btf_member_bit_offset(t, i) == bit_offset)
1095 			return m;
1096 	}
1097 
1098 	return NULL;
1099 }
1100 
1101 static const struct btf_member *
1102 find_member_by_name(const struct btf *btf, const struct btf_type *t,
1103 		    const char *name)
1104 {
1105 	struct btf_member *m;
1106 	int i;
1107 
1108 	for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
1109 		if (!strcmp(btf__name_by_offset(btf, m->name_off), name))
1110 			return m;
1111 	}
1112 
1113 	return NULL;
1114 }
1115 
1116 static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
1117 			    __u16 kind, struct btf **res_btf,
1118 			    struct module_btf **res_mod_btf);
1119 
1120 #define STRUCT_OPS_VALUE_PREFIX "bpf_struct_ops_"
1121 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
1122 				   const char *name, __u32 kind);
1123 
1124 static int
1125 find_struct_ops_kern_types(struct bpf_object *obj, const char *tname_raw,
1126 			   struct module_btf **mod_btf,
1127 			   const struct btf_type **type, __u32 *type_id,
1128 			   const struct btf_type **vtype, __u32 *vtype_id,
1129 			   const struct btf_member **data_member)
1130 {
1131 	const struct btf_type *kern_type, *kern_vtype;
1132 	const struct btf_member *kern_data_member;
1133 	struct btf *btf = NULL;
1134 	__s32 kern_vtype_id, kern_type_id;
1135 	char tname[192], stname[256];
1136 	__u32 i;
1137 
1138 	snprintf(tname, sizeof(tname), "%.*s",
1139 		 (int)bpf_core_essential_name_len(tname_raw), tname_raw);
1140 
1141 	snprintf(stname, sizeof(stname), "%s%s", STRUCT_OPS_VALUE_PREFIX, tname);
1142 
1143 	/* Look for the corresponding "map_value" type that will be used
1144 	 * in map_update(BPF_MAP_TYPE_STRUCT_OPS) first, figure out the btf
1145 	 * and the mod_btf.
1146 	 * For example, find "struct bpf_struct_ops_tcp_congestion_ops".
1147 	 */
1148 	kern_vtype_id = find_ksym_btf_id(obj, stname, BTF_KIND_STRUCT, &btf, mod_btf);
1149 	if (kern_vtype_id < 0) {
1150 		pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n", stname);
1151 		return kern_vtype_id;
1152 	}
1153 	kern_vtype = btf__type_by_id(btf, kern_vtype_id);
1154 
1155 	kern_type_id = btf__find_by_name_kind(btf, tname, BTF_KIND_STRUCT);
1156 	if (kern_type_id < 0) {
1157 		pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n", tname);
1158 		return kern_type_id;
1159 	}
1160 	kern_type = btf__type_by_id(btf, kern_type_id);
1161 
1162 	/* Find "struct tcp_congestion_ops" from
1163 	 * struct bpf_struct_ops_tcp_congestion_ops {
1164 	 *	[ ... ]
1165 	 *	struct tcp_congestion_ops data;
1166 	 * }
1167 	 */
1168 	kern_data_member = btf_members(kern_vtype);
1169 	for (i = 0; i < btf_vlen(kern_vtype); i++, kern_data_member++) {
1170 		if (kern_data_member->type == kern_type_id)
1171 			break;
1172 	}
1173 	if (i == btf_vlen(kern_vtype)) {
1174 		pr_warn("struct_ops init_kern: struct %s data is not found in struct %s\n",
1175 			tname, stname);
1176 		return -EINVAL;
1177 	}
1178 
1179 	*type = kern_type;
1180 	*type_id = kern_type_id;
1181 	*vtype = kern_vtype;
1182 	*vtype_id = kern_vtype_id;
1183 	*data_member = kern_data_member;
1184 
1185 	return 0;
1186 }
1187 
1188 static bool bpf_map__is_struct_ops(const struct bpf_map *map)
1189 {
1190 	return map->def.type == BPF_MAP_TYPE_STRUCT_OPS;
1191 }
1192 
1193 static bool is_valid_st_ops_program(struct bpf_object *obj,
1194 				    const struct bpf_program *prog)
1195 {
1196 	int i;
1197 
1198 	for (i = 0; i < obj->nr_programs; i++) {
1199 		if (&obj->programs[i] == prog)
1200 			return prog->type == BPF_PROG_TYPE_STRUCT_OPS;
1201 	}
1202 
1203 	return false;
1204 }
1205 
1206 /* For each struct_ops program P, referenced from some struct_ops map M,
1207  * enable P.autoload if there are Ms for which M.autocreate is true,
1208  * disable P.autoload if for all Ms M.autocreate is false.
1209  * Don't change P.autoload for programs that are not referenced from any maps.
1210  */
1211 static int bpf_object_adjust_struct_ops_autoload(struct bpf_object *obj)
1212 {
1213 	struct bpf_program *prog, *slot_prog;
1214 	struct bpf_map *map;
1215 	int i, j, k, vlen;
1216 
1217 	for (i = 0; i < obj->nr_programs; ++i) {
1218 		int should_load = false;
1219 		int use_cnt = 0;
1220 
1221 		prog = &obj->programs[i];
1222 		if (prog->type != BPF_PROG_TYPE_STRUCT_OPS)
1223 			continue;
1224 
1225 		for (j = 0; j < obj->nr_maps; ++j) {
1226 			const struct btf_type *type;
1227 
1228 			map = &obj->maps[j];
1229 			if (!bpf_map__is_struct_ops(map))
1230 				continue;
1231 
1232 			type = btf__type_by_id(obj->btf, map->st_ops->type_id);
1233 			vlen = btf_vlen(type);
1234 			for (k = 0; k < vlen; ++k) {
1235 				slot_prog = map->st_ops->progs[k];
1236 				if (prog != slot_prog)
1237 					continue;
1238 
1239 				use_cnt++;
1240 				if (map->autocreate)
1241 					should_load = true;
1242 			}
1243 		}
1244 		if (use_cnt)
1245 			prog->autoload = should_load;
1246 	}
1247 
1248 	return 0;
1249 }
1250 
1251 /* Init the map's fields that depend on kern_btf */
1252 static int bpf_map__init_kern_struct_ops(struct bpf_map *map)
1253 {
1254 	const struct btf_member *member, *kern_member, *kern_data_member;
1255 	const struct btf_type *type, *kern_type, *kern_vtype;
1256 	__u32 i, kern_type_id, kern_vtype_id, kern_data_off;
1257 	struct bpf_object *obj = map->obj;
1258 	const struct btf *btf = obj->btf;
1259 	struct bpf_struct_ops *st_ops;
1260 	const struct btf *kern_btf;
1261 	struct module_btf *mod_btf = NULL;
1262 	void *data, *kern_data;
1263 	const char *tname;
1264 	int err;
1265 
1266 	st_ops = map->st_ops;
1267 	type = btf__type_by_id(btf, st_ops->type_id);
1268 	tname = btf__name_by_offset(btf, type->name_off);
1269 	err = find_struct_ops_kern_types(obj, tname, &mod_btf,
1270 					 &kern_type, &kern_type_id,
1271 					 &kern_vtype, &kern_vtype_id,
1272 					 &kern_data_member);
1273 	if (err)
1274 		return err;
1275 
1276 	kern_btf = mod_btf ? mod_btf->btf : obj->btf_vmlinux;
1277 
1278 	pr_debug("struct_ops init_kern %s: type_id:%u kern_type_id:%u kern_vtype_id:%u\n",
1279 		 map->name, st_ops->type_id, kern_type_id, kern_vtype_id);
1280 
1281 	map->mod_btf_fd = mod_btf ? mod_btf->fd : -1;
1282 	map->def.value_size = kern_vtype->size;
1283 	map->btf_vmlinux_value_type_id = kern_vtype_id;
1284 
1285 	st_ops->kern_vdata = calloc(1, kern_vtype->size);
1286 	if (!st_ops->kern_vdata)
1287 		return -ENOMEM;
1288 
1289 	data = st_ops->data;
1290 	kern_data_off = kern_data_member->offset / 8;
1291 	kern_data = st_ops->kern_vdata + kern_data_off;
1292 
1293 	member = btf_members(type);
1294 	for (i = 0; i < btf_vlen(type); i++, member++) {
1295 		const struct btf_type *mtype, *kern_mtype;
1296 		__u32 mtype_id, kern_mtype_id;
1297 		void *mdata, *kern_mdata;
1298 		struct bpf_program *prog;
1299 		__s64 msize, kern_msize;
1300 		__u32 moff, kern_moff;
1301 		__u32 kern_member_idx;
1302 		const char *mname;
1303 
1304 		mname = btf__name_by_offset(btf, member->name_off);
1305 		if (btf_member_bitfield_size(type, i)) {
1306 			pr_warn("struct_ops init_kern %s: local bitfield %s is not supported\n",
1307 				map->name, mname);
1308 			return -ENOTSUP;
1309 		}
1310 
1311 		moff = member->offset / 8;
1312 		mdata = data + moff;
1313 		msize = btf__resolve_size(btf, member->type);
1314 		if (msize < 0) {
1315 			pr_warn("struct_ops init_kern %s: failed to resolve the size of member %s\n",
1316 				map->name, mname);
1317 			return msize;
1318 		}
1319 
1320 		kern_member = find_member_by_name(kern_btf, kern_type, mname);
1321 		if (!kern_member) {
1322 			if (!libbpf_is_mem_zeroed(mdata, msize)) {
1323 				pr_warn("struct_ops init_kern %s: Cannot find member %s in kernel BTF\n",
1324 					map->name, mname);
1325 				return -ENOTSUP;
1326 			}
1327 
1328 			if (st_ops->progs[i]) {
1329 				/* If we had declaratively set struct_ops callback, we need to
1330 				 * force its autoload to false, because it doesn't have
1331 				 * a chance of succeeding from POV of the current struct_ops map.
1332 				 * If this program is still referenced somewhere else, though,
1333 				 * then bpf_object_adjust_struct_ops_autoload() will update its
1334 				 * autoload accordingly.
1335 				 */
1336 				st_ops->progs[i]->autoload = false;
1337 				st_ops->progs[i] = NULL;
1338 			}
1339 
1340 			/* Skip all-zero/NULL fields if they are not present in the kernel BTF */
1341 			pr_info("struct_ops %s: member %s not found in kernel, skipping it as it's set to zero\n",
1342 				map->name, mname);
1343 			continue;
1344 		}
1345 
1346 		kern_member_idx = kern_member - btf_members(kern_type);
1347 		if (btf_member_bitfield_size(kern_type, kern_member_idx)) {
1348 			pr_warn("struct_ops init_kern %s: bitfield %s is not supported\n",
1349 				map->name, mname);
1350 			return -ENOTSUP;
1351 		}
1352 
1353 		kern_moff = kern_member->offset / 8;
1354 		kern_mdata = kern_data + kern_moff;
1355 
1356 		mtype = skip_mods_and_typedefs(btf, member->type, &mtype_id);
1357 		kern_mtype = skip_mods_and_typedefs(kern_btf, kern_member->type,
1358 						    &kern_mtype_id);
1359 		if (BTF_INFO_KIND(mtype->info) !=
1360 		    BTF_INFO_KIND(kern_mtype->info)) {
1361 			pr_warn("struct_ops init_kern %s: Unmatched member type %s %u != %u(kernel)\n",
1362 				map->name, mname, BTF_INFO_KIND(mtype->info),
1363 				BTF_INFO_KIND(kern_mtype->info));
1364 			return -ENOTSUP;
1365 		}
1366 
1367 		if (btf_is_ptr(mtype)) {
1368 			prog = *(void **)mdata;
1369 			/* just like for !kern_member case above, reset declaratively
1370 			 * set (at compile time) program's autload to false,
1371 			 * if user replaced it with another program or NULL
1372 			 */
1373 			if (st_ops->progs[i] && st_ops->progs[i] != prog)
1374 				st_ops->progs[i]->autoload = false;
1375 
1376 			/* Update the value from the shadow type */
1377 			st_ops->progs[i] = prog;
1378 			if (!prog)
1379 				continue;
1380 
1381 			if (!is_valid_st_ops_program(obj, prog)) {
1382 				pr_warn("struct_ops init_kern %s: member %s is not a struct_ops program\n",
1383 					map->name, mname);
1384 				return -ENOTSUP;
1385 			}
1386 
1387 			kern_mtype = skip_mods_and_typedefs(kern_btf,
1388 							    kern_mtype->type,
1389 							    &kern_mtype_id);
1390 
1391 			/* mtype->type must be a func_proto which was
1392 			 * guaranteed in bpf_object__collect_st_ops_relos(),
1393 			 * so only check kern_mtype for func_proto here.
1394 			 */
1395 			if (!btf_is_func_proto(kern_mtype)) {
1396 				pr_warn("struct_ops init_kern %s: kernel member %s is not a func ptr\n",
1397 					map->name, mname);
1398 				return -ENOTSUP;
1399 			}
1400 
1401 			if (mod_btf)
1402 				prog->attach_btf_obj_fd = mod_btf->fd;
1403 
1404 			/* if we haven't yet processed this BPF program, record proper
1405 			 * attach_btf_id and member_idx
1406 			 */
1407 			if (!prog->attach_btf_id) {
1408 				prog->attach_btf_id = kern_type_id;
1409 				prog->expected_attach_type = kern_member_idx;
1410 			}
1411 
1412 			/* struct_ops BPF prog can be re-used between multiple
1413 			 * .struct_ops & .struct_ops.link as long as it's the
1414 			 * same struct_ops struct definition and the same
1415 			 * function pointer field
1416 			 */
1417 			if (prog->attach_btf_id != kern_type_id) {
1418 				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",
1419 					map->name, mname, prog->name, prog->sec_name, prog->type,
1420 					prog->attach_btf_id, kern_type_id);
1421 				return -EINVAL;
1422 			}
1423 			if (prog->expected_attach_type != kern_member_idx) {
1424 				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",
1425 					map->name, mname, prog->name, prog->sec_name, prog->type,
1426 					prog->expected_attach_type, kern_member_idx);
1427 				return -EINVAL;
1428 			}
1429 
1430 			st_ops->kern_func_off[i] = kern_data_off + kern_moff;
1431 
1432 			pr_debug("struct_ops init_kern %s: func ptr %s is set to prog %s from data(+%u) to kern_data(+%u)\n",
1433 				 map->name, mname, prog->name, moff,
1434 				 kern_moff);
1435 
1436 			continue;
1437 		}
1438 
1439 		kern_msize = btf__resolve_size(kern_btf, kern_mtype_id);
1440 		if (kern_msize < 0 || msize != kern_msize) {
1441 			pr_warn("struct_ops init_kern %s: Error in size of member %s: %zd != %zd(kernel)\n",
1442 				map->name, mname, (ssize_t)msize,
1443 				(ssize_t)kern_msize);
1444 			return -ENOTSUP;
1445 		}
1446 
1447 		pr_debug("struct_ops init_kern %s: copy %s %u bytes from data(+%u) to kern_data(+%u)\n",
1448 			 map->name, mname, (unsigned int)msize,
1449 			 moff, kern_moff);
1450 		memcpy(kern_mdata, mdata, msize);
1451 	}
1452 
1453 	return 0;
1454 }
1455 
1456 static int bpf_object__init_kern_struct_ops_maps(struct bpf_object *obj)
1457 {
1458 	struct bpf_map *map;
1459 	size_t i;
1460 	int err;
1461 
1462 	for (i = 0; i < obj->nr_maps; i++) {
1463 		map = &obj->maps[i];
1464 
1465 		if (!bpf_map__is_struct_ops(map))
1466 			continue;
1467 
1468 		if (!map->autocreate)
1469 			continue;
1470 
1471 		err = bpf_map__init_kern_struct_ops(map);
1472 		if (err)
1473 			return err;
1474 	}
1475 
1476 	return 0;
1477 }
1478 
1479 static int init_struct_ops_maps(struct bpf_object *obj, const char *sec_name,
1480 				int shndx, Elf_Data *data)
1481 {
1482 	const struct btf_type *type, *datasec;
1483 	const struct btf_var_secinfo *vsi;
1484 	struct bpf_struct_ops *st_ops;
1485 	const char *tname, *var_name;
1486 	__s32 type_id, datasec_id;
1487 	const struct btf *btf;
1488 	struct bpf_map *map;
1489 	__u32 i;
1490 
1491 	if (shndx == -1)
1492 		return 0;
1493 
1494 	btf = obj->btf;
1495 	datasec_id = btf__find_by_name_kind(btf, sec_name,
1496 					    BTF_KIND_DATASEC);
1497 	if (datasec_id < 0) {
1498 		pr_warn("struct_ops init: DATASEC %s not found\n",
1499 			sec_name);
1500 		return -EINVAL;
1501 	}
1502 
1503 	datasec = btf__type_by_id(btf, datasec_id);
1504 	vsi = btf_var_secinfos(datasec);
1505 	for (i = 0; i < btf_vlen(datasec); i++, vsi++) {
1506 		type = btf__type_by_id(obj->btf, vsi->type);
1507 		var_name = btf__name_by_offset(obj->btf, type->name_off);
1508 
1509 		type_id = btf__resolve_type(obj->btf, vsi->type);
1510 		if (type_id < 0) {
1511 			pr_warn("struct_ops init: Cannot resolve var type_id %u in DATASEC %s\n",
1512 				vsi->type, sec_name);
1513 			return -EINVAL;
1514 		}
1515 
1516 		type = btf__type_by_id(obj->btf, type_id);
1517 		tname = btf__name_by_offset(obj->btf, type->name_off);
1518 		if (!tname[0]) {
1519 			pr_warn("struct_ops init: anonymous type is not supported\n");
1520 			return -ENOTSUP;
1521 		}
1522 		if (!btf_is_struct(type)) {
1523 			pr_warn("struct_ops init: %s is not a struct\n", tname);
1524 			return -EINVAL;
1525 		}
1526 
1527 		map = bpf_object__add_map(obj);
1528 		if (IS_ERR(map))
1529 			return PTR_ERR(map);
1530 
1531 		map->sec_idx = shndx;
1532 		map->sec_offset = vsi->offset;
1533 		map->name = strdup(var_name);
1534 		if (!map->name)
1535 			return -ENOMEM;
1536 		map->btf_value_type_id = type_id;
1537 
1538 		/* Follow same convention as for programs autoload:
1539 		 * SEC("?.struct_ops") means map is not created by default.
1540 		 */
1541 		if (sec_name[0] == '?') {
1542 			map->autocreate = false;
1543 			/* from now on forget there was ? in section name */
1544 			sec_name++;
1545 		}
1546 
1547 		map->def.type = BPF_MAP_TYPE_STRUCT_OPS;
1548 		map->def.key_size = sizeof(int);
1549 		map->def.value_size = type->size;
1550 		map->def.max_entries = 1;
1551 		map->def.map_flags = strcmp(sec_name, STRUCT_OPS_LINK_SEC) == 0 ? BPF_F_LINK : 0;
1552 		map->autoattach = true;
1553 
1554 		map->st_ops = calloc(1, sizeof(*map->st_ops));
1555 		if (!map->st_ops)
1556 			return -ENOMEM;
1557 		st_ops = map->st_ops;
1558 		st_ops->data = malloc(type->size);
1559 		st_ops->progs = calloc(btf_vlen(type), sizeof(*st_ops->progs));
1560 		st_ops->kern_func_off = malloc(btf_vlen(type) *
1561 					       sizeof(*st_ops->kern_func_off));
1562 		if (!st_ops->data || !st_ops->progs || !st_ops->kern_func_off)
1563 			return -ENOMEM;
1564 
1565 		if (vsi->offset + type->size > data->d_size) {
1566 			pr_warn("struct_ops init: var %s is beyond the end of DATASEC %s\n",
1567 				var_name, sec_name);
1568 			return -EINVAL;
1569 		}
1570 
1571 		memcpy(st_ops->data,
1572 		       data->d_buf + vsi->offset,
1573 		       type->size);
1574 		st_ops->type_id = type_id;
1575 
1576 		pr_debug("struct_ops init: struct %s(type_id=%d) %s found at offset %u\n",
1577 			 tname, type_id, var_name, vsi->offset);
1578 	}
1579 
1580 	return 0;
1581 }
1582 
1583 static int bpf_object_init_struct_ops(struct bpf_object *obj)
1584 {
1585 	const char *sec_name;
1586 	int sec_idx, err;
1587 
1588 	for (sec_idx = 0; sec_idx < obj->efile.sec_cnt; ++sec_idx) {
1589 		struct elf_sec_desc *desc = &obj->efile.secs[sec_idx];
1590 
1591 		if (desc->sec_type != SEC_ST_OPS)
1592 			continue;
1593 
1594 		sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1595 		if (!sec_name)
1596 			return -LIBBPF_ERRNO__FORMAT;
1597 
1598 		err = init_struct_ops_maps(obj, sec_name, sec_idx, desc->data);
1599 		if (err)
1600 			return err;
1601 	}
1602 
1603 	return 0;
1604 }
1605 
1606 static struct bpf_object *bpf_object__new(const char *path,
1607 					  const void *obj_buf,
1608 					  size_t obj_buf_sz,
1609 					  const char *obj_name)
1610 {
1611 	struct bpf_object *obj;
1612 	char *end;
1613 
1614 	obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
1615 	if (!obj) {
1616 		pr_warn("alloc memory failed for %s\n", path);
1617 		return ERR_PTR(-ENOMEM);
1618 	}
1619 
1620 	strcpy(obj->path, path);
1621 	if (obj_name) {
1622 		libbpf_strlcpy(obj->name, obj_name, sizeof(obj->name));
1623 	} else {
1624 		/* Using basename() GNU version which doesn't modify arg. */
1625 		libbpf_strlcpy(obj->name, basename((void *)path), sizeof(obj->name));
1626 		end = strchr(obj->name, '.');
1627 		if (end)
1628 			*end = 0;
1629 	}
1630 
1631 	obj->efile.fd = -1;
1632 	/*
1633 	 * Caller of this function should also call
1634 	 * bpf_object__elf_finish() after data collection to return
1635 	 * obj_buf to user. If not, we should duplicate the buffer to
1636 	 * avoid user freeing them before elf finish.
1637 	 */
1638 	obj->efile.obj_buf = obj_buf;
1639 	obj->efile.obj_buf_sz = obj_buf_sz;
1640 	obj->efile.btf_maps_shndx = -1;
1641 	obj->efile.arena_data_shndx = -1;
1642 	obj->kconfig_map_idx = -1;
1643 	obj->arena_map_idx = -1;
1644 
1645 	obj->kern_version = get_kernel_version();
1646 	obj->state  = OBJ_OPEN;
1647 
1648 	return obj;
1649 }
1650 
1651 static void bpf_object__elf_finish(struct bpf_object *obj)
1652 {
1653 	if (!obj->efile.elf)
1654 		return;
1655 
1656 	elf_end(obj->efile.elf);
1657 	obj->efile.elf = NULL;
1658 	obj->efile.ehdr = NULL;
1659 	obj->efile.symbols = NULL;
1660 	obj->efile.arena_data = NULL;
1661 
1662 	zfree(&obj->efile.secs);
1663 	obj->efile.sec_cnt = 0;
1664 	zclose(obj->efile.fd);
1665 	obj->efile.obj_buf = NULL;
1666 	obj->efile.obj_buf_sz = 0;
1667 }
1668 
1669 static int bpf_object__elf_init(struct bpf_object *obj)
1670 {
1671 	Elf64_Ehdr *ehdr;
1672 	int err = 0;
1673 	Elf *elf;
1674 
1675 	if (obj->efile.elf) {
1676 		pr_warn("elf: init internal error\n");
1677 		return -LIBBPF_ERRNO__LIBELF;
1678 	}
1679 
1680 	if (obj->efile.obj_buf_sz > 0) {
1681 		/* obj_buf should have been validated by bpf_object__open_mem(). */
1682 		elf = elf_memory((char *)obj->efile.obj_buf, obj->efile.obj_buf_sz);
1683 	} else {
1684 		obj->efile.fd = open(obj->path, O_RDONLY | O_CLOEXEC);
1685 		if (obj->efile.fd < 0) {
1686 			err = -errno;
1687 			pr_warn("elf: failed to open %s: %s\n", obj->path, errstr(err));
1688 			return err;
1689 		}
1690 
1691 		elf = elf_begin(obj->efile.fd, ELF_C_READ_MMAP, NULL);
1692 	}
1693 
1694 	if (!elf) {
1695 		pr_warn("elf: failed to open %s as ELF file: %s\n", obj->path, elf_errmsg(-1));
1696 		err = -LIBBPF_ERRNO__LIBELF;
1697 		goto errout;
1698 	}
1699 
1700 	obj->efile.elf = elf;
1701 
1702 	if (elf_kind(elf) != ELF_K_ELF) {
1703 		err = -LIBBPF_ERRNO__FORMAT;
1704 		pr_warn("elf: '%s' is not a proper ELF object\n", obj->path);
1705 		goto errout;
1706 	}
1707 
1708 	if (gelf_getclass(elf) != ELFCLASS64) {
1709 		err = -LIBBPF_ERRNO__FORMAT;
1710 		pr_warn("elf: '%s' is not a 64-bit ELF object\n", obj->path);
1711 		goto errout;
1712 	}
1713 
1714 	obj->efile.ehdr = ehdr = elf64_getehdr(elf);
1715 	if (!obj->efile.ehdr) {
1716 		pr_warn("elf: failed to get ELF header from %s: %s\n", obj->path, elf_errmsg(-1));
1717 		err = -LIBBPF_ERRNO__FORMAT;
1718 		goto errout;
1719 	}
1720 
1721 	/* Validate ELF object endianness... */
1722 	if (ehdr->e_ident[EI_DATA] != ELFDATA2LSB &&
1723 	    ehdr->e_ident[EI_DATA] != ELFDATA2MSB) {
1724 		err = -LIBBPF_ERRNO__ENDIAN;
1725 		pr_warn("elf: '%s' has unknown byte order\n", obj->path);
1726 		goto errout;
1727 	}
1728 	/* and save after bpf_object_open() frees ELF data */
1729 	obj->byteorder = ehdr->e_ident[EI_DATA];
1730 
1731 	if (elf_getshdrstrndx(elf, &obj->efile.shstrndx)) {
1732 		pr_warn("elf: failed to get section names section index for %s: %s\n",
1733 			obj->path, elf_errmsg(-1));
1734 		err = -LIBBPF_ERRNO__FORMAT;
1735 		goto errout;
1736 	}
1737 
1738 	/* ELF is corrupted/truncated, avoid calling elf_strptr. */
1739 	if (!elf_rawdata(elf_getscn(elf, obj->efile.shstrndx), NULL)) {
1740 		pr_warn("elf: failed to get section names strings from %s: %s\n",
1741 			obj->path, elf_errmsg(-1));
1742 		err = -LIBBPF_ERRNO__FORMAT;
1743 		goto errout;
1744 	}
1745 
1746 	/* Old LLVM set e_machine to EM_NONE */
1747 	if (ehdr->e_type != ET_REL || (ehdr->e_machine && ehdr->e_machine != EM_BPF)) {
1748 		pr_warn("elf: %s is not a valid eBPF object file\n", obj->path);
1749 		err = -LIBBPF_ERRNO__FORMAT;
1750 		goto errout;
1751 	}
1752 
1753 	return 0;
1754 errout:
1755 	bpf_object__elf_finish(obj);
1756 	return err;
1757 }
1758 
1759 static bool is_native_endianness(struct bpf_object *obj)
1760 {
1761 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1762 	return obj->byteorder == ELFDATA2LSB;
1763 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
1764 	return obj->byteorder == ELFDATA2MSB;
1765 #else
1766 # error "Unrecognized __BYTE_ORDER__"
1767 #endif
1768 }
1769 
1770 static int
1771 bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
1772 {
1773 	if (!data) {
1774 		pr_warn("invalid license section in %s\n", obj->path);
1775 		return -LIBBPF_ERRNO__FORMAT;
1776 	}
1777 	/* libbpf_strlcpy() only copies first N - 1 bytes, so size + 1 won't
1778 	 * go over allowed ELF data section buffer
1779 	 */
1780 	libbpf_strlcpy(obj->license, data, min(size + 1, sizeof(obj->license)));
1781 	pr_debug("license of %s is %s\n", obj->path, obj->license);
1782 	return 0;
1783 }
1784 
1785 static int
1786 bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
1787 {
1788 	__u32 kver;
1789 
1790 	if (!data || size != sizeof(kver)) {
1791 		pr_warn("invalid kver section in %s\n", obj->path);
1792 		return -LIBBPF_ERRNO__FORMAT;
1793 	}
1794 	memcpy(&kver, data, sizeof(kver));
1795 	obj->kern_version = kver;
1796 	pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
1797 	return 0;
1798 }
1799 
1800 static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
1801 {
1802 	if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
1803 	    type == BPF_MAP_TYPE_HASH_OF_MAPS)
1804 		return true;
1805 	return false;
1806 }
1807 
1808 static int find_elf_sec_sz(const struct bpf_object *obj, const char *name, __u32 *size)
1809 {
1810 	Elf_Data *data;
1811 	Elf_Scn *scn;
1812 
1813 	if (!name)
1814 		return -EINVAL;
1815 
1816 	scn = elf_sec_by_name(obj, name);
1817 	data = elf_sec_data(obj, scn);
1818 	if (data) {
1819 		*size = data->d_size;
1820 		return 0; /* found it */
1821 	}
1822 
1823 	return -ENOENT;
1824 }
1825 
1826 static Elf64_Sym *find_elf_var_sym(const struct bpf_object *obj, const char *name)
1827 {
1828 	Elf_Data *symbols = obj->efile.symbols;
1829 	const char *sname;
1830 	size_t si;
1831 
1832 	for (si = 0; si < symbols->d_size / sizeof(Elf64_Sym); si++) {
1833 		Elf64_Sym *sym = elf_sym_by_idx(obj, si);
1834 
1835 		if (ELF64_ST_TYPE(sym->st_info) != STT_OBJECT)
1836 			continue;
1837 
1838 		if (ELF64_ST_BIND(sym->st_info) != STB_GLOBAL &&
1839 		    ELF64_ST_BIND(sym->st_info) != STB_WEAK)
1840 			continue;
1841 
1842 		sname = elf_sym_str(obj, sym->st_name);
1843 		if (!sname) {
1844 			pr_warn("failed to get sym name string for var %s\n", name);
1845 			return ERR_PTR(-EIO);
1846 		}
1847 		if (strcmp(name, sname) == 0)
1848 			return sym;
1849 	}
1850 
1851 	return ERR_PTR(-ENOENT);
1852 }
1853 
1854 #ifndef MFD_CLOEXEC
1855 #define MFD_CLOEXEC 0x0001U
1856 #endif
1857 #ifndef MFD_NOEXEC_SEAL
1858 #define MFD_NOEXEC_SEAL 0x0008U
1859 #endif
1860 
1861 static int create_placeholder_fd(void)
1862 {
1863 	unsigned int flags = MFD_CLOEXEC | MFD_NOEXEC_SEAL;
1864 	const char *name = "libbpf-placeholder-fd";
1865 	int fd;
1866 
1867 	fd = ensure_good_fd(sys_memfd_create(name, flags));
1868 	if (fd >= 0)
1869 		return fd;
1870 	else if (errno != EINVAL)
1871 		return -errno;
1872 
1873 	/* Possibly running on kernel without MFD_NOEXEC_SEAL */
1874 	fd = ensure_good_fd(sys_memfd_create(name, flags & ~MFD_NOEXEC_SEAL));
1875 	if (fd < 0)
1876 		return -errno;
1877 	return fd;
1878 }
1879 
1880 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
1881 {
1882 	struct bpf_map *map;
1883 	int err;
1884 
1885 	err = libbpf_ensure_mem((void **)&obj->maps, &obj->maps_cap,
1886 				sizeof(*obj->maps), obj->nr_maps + 1);
1887 	if (err)
1888 		return ERR_PTR(err);
1889 
1890 	map = &obj->maps[obj->nr_maps++];
1891 	map->obj = obj;
1892 	/* Preallocate map FD without actually creating BPF map just yet.
1893 	 * These map FD "placeholders" will be reused later without changing
1894 	 * FD value when map is actually created in the kernel.
1895 	 *
1896 	 * This is useful to be able to perform BPF program relocations
1897 	 * without having to create BPF maps before that step. This allows us
1898 	 * to finalize and load BTF very late in BPF object's loading phase,
1899 	 * right before BPF maps have to be created and BPF programs have to
1900 	 * be loaded. By having these map FD placeholders we can perform all
1901 	 * the sanitizations, relocations, and any other adjustments before we
1902 	 * start creating actual BPF kernel objects (BTF, maps, progs).
1903 	 */
1904 	map->fd = create_placeholder_fd();
1905 	if (map->fd < 0)
1906 		return ERR_PTR(map->fd);
1907 	map->inner_map_fd = -1;
1908 	map->autocreate = true;
1909 
1910 	return map;
1911 }
1912 
1913 static size_t array_map_mmap_sz(unsigned int value_sz, unsigned int max_entries)
1914 {
1915 	const long page_sz = sysconf(_SC_PAGE_SIZE);
1916 	size_t map_sz;
1917 
1918 	map_sz = (size_t)roundup(value_sz, 8) * max_entries;
1919 	map_sz = roundup(map_sz, page_sz);
1920 	return map_sz;
1921 }
1922 
1923 static size_t bpf_map_mmap_sz(const struct bpf_map *map)
1924 {
1925 	const long page_sz = sysconf(_SC_PAGE_SIZE);
1926 
1927 	switch (map->def.type) {
1928 	case BPF_MAP_TYPE_ARRAY:
1929 	case BPF_MAP_TYPE_PERCPU_ARRAY:
1930 		return array_map_mmap_sz(map->def.value_size, map->def.max_entries);
1931 	case BPF_MAP_TYPE_ARENA:
1932 		return page_sz * map->def.max_entries;
1933 	default:
1934 		return 0; /* not supported */
1935 	}
1936 }
1937 
1938 static int bpf_map_mmap_resize(struct bpf_map *map, size_t old_sz, size_t new_sz)
1939 {
1940 	void *mmaped;
1941 
1942 	if (!map->mmaped)
1943 		return -EINVAL;
1944 
1945 	if (old_sz == new_sz)
1946 		return 0;
1947 
1948 	mmaped = mmap(NULL, new_sz, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1949 	if (mmaped == MAP_FAILED)
1950 		return -errno;
1951 
1952 	memcpy(mmaped, map->mmaped, min(old_sz, new_sz));
1953 	munmap(map->mmaped, old_sz);
1954 	map->mmaped = mmaped;
1955 	return 0;
1956 }
1957 
1958 static char *internal_map_name(struct bpf_object *obj, const char *real_name,
1959 			       enum libbpf_map_type type)
1960 {
1961 	char map_name[BPF_OBJ_NAME_LEN], *p;
1962 	int pfx_len, sfx_len = max((size_t)7, strlen(real_name));
1963 
1964 	/* This is one of the more confusing parts of libbpf for various
1965 	 * reasons, some of which are historical. The original idea for naming
1966 	 * internal names was to include as much of BPF object name prefix as
1967 	 * possible, so that it can be distinguished from similar internal
1968 	 * maps of a different BPF object.
1969 	 * As an example, let's say we have bpf_object named 'my_object_name'
1970 	 * and internal map corresponding to '.rodata' ELF section. The final
1971 	 * map name advertised to user and to the kernel will be
1972 	 * 'my_objec.rodata', taking first 8 characters of object name and
1973 	 * entire 7 characters of '.rodata'.
1974 	 * Somewhat confusingly, if internal map ELF section name is shorter
1975 	 * than 7 characters, e.g., '.bss', we still reserve 7 characters
1976 	 * for the suffix, even though we only have 4 actual characters, and
1977 	 * resulting map will be called 'my_objec.bss', not even using all 15
1978 	 * characters allowed by the kernel. Oh well, at least the truncated
1979 	 * object name is somewhat consistent in this case. But if the map
1980 	 * name is '.kconfig', we'll still have entirety of '.kconfig' added
1981 	 * (8 chars) and thus will be left with only first 7 characters of the
1982 	 * object name ('my_obje'). Happy guessing, user, that the final map
1983 	 * name will be "my_obje.kconfig".
1984 	 * Now, with libbpf starting to support arbitrarily named .rodata.*
1985 	 * and .data.* data sections, it's possible that ELF section name is
1986 	 * longer than allowed 15 chars, so we now need to be careful to take
1987 	 * only up to 15 first characters of ELF name, taking no BPF object
1988 	 * name characters at all. So '.rodata.abracadabra' will result in
1989 	 * '.rodata.abracad' kernel and user-visible name.
1990 	 * We need to keep this convoluted logic intact for .data, .bss and
1991 	 * .rodata maps, but for new custom .data.custom and .rodata.custom
1992 	 * maps we use their ELF names as is, not prepending bpf_object name
1993 	 * in front. We still need to truncate them to 15 characters for the
1994 	 * kernel. Full name can be recovered for such maps by using DATASEC
1995 	 * BTF type associated with such map's value type, though.
1996 	 */
1997 	if (sfx_len >= BPF_OBJ_NAME_LEN)
1998 		sfx_len = BPF_OBJ_NAME_LEN - 1;
1999 
2000 	/*
2001 	 * Don't prefix the bpf_object name if this is a custom dot map
2002 	 * (containing two or more dots) or a percpu data map.
2003 	 */
2004 	if (strchr(real_name + 1, '.') != NULL || type == LIBBPF_MAP_PERCPU)
2005 		pfx_len = 0;
2006 	else
2007 		pfx_len = min((size_t)BPF_OBJ_NAME_LEN - sfx_len - 1, strlen(obj->name));
2008 
2009 	snprintf(map_name, sizeof(map_name), "%.*s%.*s", pfx_len, obj->name,
2010 		 sfx_len, real_name);
2011 
2012 	/* sanities map name to characters allowed by kernel */
2013 	for (p = map_name; *p && p < map_name + sizeof(map_name); p++)
2014 		if (!isalnum(*p) && *p != '_' && *p != '.')
2015 			*p = '_';
2016 
2017 	return strdup(map_name);
2018 }
2019 
2020 static int
2021 map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map);
2022 
2023 /* Internal BPF map is mmap()'able only if at least one of corresponding
2024  * DATASEC's VARs are to be exposed through BPF skeleton. I.e., it's a GLOBAL
2025  * variable and it's not marked as __hidden (which turns it into, effectively,
2026  * a STATIC variable).
2027  */
2028 static bool map_is_mmapable(struct bpf_object *obj, struct bpf_map *map)
2029 {
2030 	const struct btf_type *t, *vt;
2031 	struct btf_var_secinfo *vsi;
2032 	int i, n;
2033 
2034 	if (!map->btf_value_type_id)
2035 		return false;
2036 
2037 	/*
2038 	 * The internal PERCPU maps are not mmapable because the underlying
2039 	 * percpu_array maps do not have mmap support.
2040 	 */
2041 	if (map->libbpf_type == LIBBPF_MAP_PERCPU)
2042 		return false;
2043 
2044 	t = btf__type_by_id(obj->btf, map->btf_value_type_id);
2045 	if (!btf_is_datasec(t))
2046 		return false;
2047 
2048 	vsi = btf_var_secinfos(t);
2049 	for (i = 0, n = btf_vlen(t); i < n; i++, vsi++) {
2050 		vt = btf__type_by_id(obj->btf, vsi->type);
2051 		if (!btf_is_var(vt))
2052 			continue;
2053 
2054 		if (btf_var(vt)->linkage != BTF_VAR_STATIC)
2055 			return true;
2056 	}
2057 
2058 	return false;
2059 }
2060 
2061 static int
2062 bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
2063 			      const char *real_name, int sec_idx, void *data, size_t data_sz)
2064 {
2065 	bool is_percpu = type == LIBBPF_MAP_PERCPU;
2066 	struct bpf_map_def *def;
2067 	struct bpf_map *map;
2068 	size_t mmap_sz;
2069 	int err;
2070 
2071 	map = bpf_object__add_map(obj);
2072 	if (IS_ERR(map))
2073 		return PTR_ERR(map);
2074 
2075 	map->libbpf_type = type;
2076 	map->sec_idx = sec_idx;
2077 	map->sec_offset = 0;
2078 	map->real_name = strdup(real_name);
2079 	map->name = internal_map_name(obj, real_name, type);
2080 	if (!map->real_name || !map->name) {
2081 		zfree(&map->real_name);
2082 		zfree(&map->name);
2083 		return -ENOMEM;
2084 	}
2085 
2086 	def = &map->def;
2087 	def->type = is_percpu ? BPF_MAP_TYPE_PERCPU_ARRAY : BPF_MAP_TYPE_ARRAY;
2088 	def->key_size = sizeof(int);
2089 	def->value_size = data_sz;
2090 	def->max_entries = 1;
2091 	def->map_flags = type == LIBBPF_MAP_RODATA || type == LIBBPF_MAP_KCONFIG
2092 		? BPF_F_RDONLY_PROG : 0;
2093 
2094 	/* failures are fine because of maps like .rodata.str1.1 */
2095 	(void) map_fill_btf_type_info(obj, map);
2096 
2097 	if (map_is_mmapable(obj, map))
2098 		def->map_flags |= BPF_F_MMAPABLE;
2099 
2100 	pr_debug("map '%s' (global %sdata): at sec_idx %d, offset %zu, flags %x.\n",
2101 		 map->name, is_percpu ? "percpu " : "", map->sec_idx,
2102 		 map->sec_offset, def->map_flags);
2103 
2104 	mmap_sz = bpf_map_mmap_sz(map);
2105 	map->mmaped = mmap(NULL, mmap_sz, PROT_READ | PROT_WRITE,
2106 			   MAP_SHARED | MAP_ANONYMOUS, -1, 0);
2107 	if (map->mmaped == MAP_FAILED) {
2108 		err = -errno;
2109 		map->mmaped = NULL;
2110 		pr_warn("failed to alloc map '%s' content buffer: %s\n", map->name, errstr(err));
2111 		zfree(&map->real_name);
2112 		zfree(&map->name);
2113 		return err;
2114 	}
2115 
2116 	if (data)
2117 		memcpy(map->mmaped, data, data_sz);
2118 
2119 	pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
2120 	return 0;
2121 }
2122 
2123 static int bpf_object__init_global_data_maps(struct bpf_object *obj)
2124 {
2125 	struct elf_sec_desc *sec_desc;
2126 	const char *sec_name;
2127 	int err = 0, sec_idx;
2128 
2129 	/*
2130 	 * Populate obj->maps with libbpf internal maps.
2131 	 */
2132 	for (sec_idx = 1; sec_idx < obj->efile.sec_cnt; sec_idx++) {
2133 		sec_desc = &obj->efile.secs[sec_idx];
2134 
2135 		/* Skip recognized sections with size 0. */
2136 		if (!sec_desc->data || sec_desc->data->d_size == 0)
2137 			continue;
2138 
2139 		switch (sec_desc->sec_type) {
2140 		case SEC_DATA:
2141 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
2142 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
2143 							    sec_name, sec_idx,
2144 							    sec_desc->data->d_buf,
2145 							    sec_desc->data->d_size);
2146 			break;
2147 		case SEC_RODATA:
2148 			obj->has_rodata = true;
2149 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
2150 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
2151 							    sec_name, sec_idx,
2152 							    sec_desc->data->d_buf,
2153 							    sec_desc->data->d_size);
2154 			break;
2155 		case SEC_BSS:
2156 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
2157 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
2158 							    sec_name, sec_idx,
2159 							    NULL,
2160 							    sec_desc->data->d_size);
2161 			break;
2162 		case SEC_PERCPU:
2163 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
2164 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_PERCPU,
2165 							    sec_name, sec_idx,
2166 							    sec_desc->data->d_buf,
2167 							    sec_desc->data->d_size);
2168 			break;
2169 		default:
2170 			/* skip */
2171 			break;
2172 		}
2173 		if (err)
2174 			return err;
2175 	}
2176 	return 0;
2177 }
2178 
2179 
2180 static struct extern_desc *find_extern_by_name(const struct bpf_object *obj,
2181 					       const void *name)
2182 {
2183 	int i;
2184 
2185 	for (i = 0; i < obj->nr_extern; i++) {
2186 		if (strcmp(obj->externs[i].name, name) == 0)
2187 			return &obj->externs[i];
2188 	}
2189 	return NULL;
2190 }
2191 
2192 static struct extern_desc *find_extern_by_name_with_len(const struct bpf_object *obj,
2193 							const void *name, int len)
2194 {
2195 	const char *ext_name;
2196 	int i;
2197 
2198 	for (i = 0; i < obj->nr_extern; i++) {
2199 		ext_name = obj->externs[i].name;
2200 		if (strlen(ext_name) == len && strncmp(ext_name, name, len) == 0)
2201 			return &obj->externs[i];
2202 	}
2203 	return NULL;
2204 }
2205 
2206 static int set_kcfg_value_tri(struct extern_desc *ext, void *ext_val,
2207 			      char value)
2208 {
2209 	switch (ext->kcfg.type) {
2210 	case KCFG_BOOL:
2211 		if (value == 'm') {
2212 			pr_warn("extern (kcfg) '%s': value '%c' implies tristate or char type\n",
2213 				ext->name, value);
2214 			return -EINVAL;
2215 		}
2216 		*(bool *)ext_val = value == 'y' ? true : false;
2217 		break;
2218 	case KCFG_TRISTATE:
2219 		if (value == 'y')
2220 			*(enum libbpf_tristate *)ext_val = TRI_YES;
2221 		else if (value == 'm')
2222 			*(enum libbpf_tristate *)ext_val = TRI_MODULE;
2223 		else /* value == 'n' */
2224 			*(enum libbpf_tristate *)ext_val = TRI_NO;
2225 		break;
2226 	case KCFG_CHAR:
2227 		*(char *)ext_val = value;
2228 		break;
2229 	case KCFG_UNKNOWN:
2230 	case KCFG_INT:
2231 	case KCFG_CHAR_ARR:
2232 	default:
2233 		pr_warn("extern (kcfg) '%s': value '%c' implies bool, tristate, or char type\n",
2234 			ext->name, value);
2235 		return -EINVAL;
2236 	}
2237 	ext->is_set = true;
2238 	return 0;
2239 }
2240 
2241 static int set_kcfg_value_str(struct extern_desc *ext, char *ext_val,
2242 			      const char *value)
2243 {
2244 	size_t len;
2245 
2246 	if (ext->kcfg.type != KCFG_CHAR_ARR) {
2247 		pr_warn("extern (kcfg) '%s': value '%s' implies char array type\n",
2248 			ext->name, value);
2249 		return -EINVAL;
2250 	}
2251 
2252 	len = strlen(value);
2253 	if (len < 2 || value[len - 1] != '"') {
2254 		pr_warn("extern (kcfg) '%s': invalid string config '%s'\n",
2255 			ext->name, value);
2256 		return -EINVAL;
2257 	}
2258 
2259 	/* strip quotes */
2260 	len -= 2;
2261 	if (len >= ext->kcfg.sz) {
2262 		pr_warn("extern (kcfg) '%s': long string '%s' of (%zu bytes) truncated to %d bytes\n",
2263 			ext->name, value, len, ext->kcfg.sz - 1);
2264 		len = ext->kcfg.sz - 1;
2265 	}
2266 	memcpy(ext_val, value + 1, len);
2267 	ext_val[len] = '\0';
2268 	ext->is_set = true;
2269 	return 0;
2270 }
2271 
2272 static int parse_u64(const char *value, __u64 *res)
2273 {
2274 	char *value_end;
2275 	int err;
2276 
2277 	errno = 0;
2278 	*res = strtoull(value, &value_end, 0);
2279 	if (errno) {
2280 		err = -errno;
2281 		pr_warn("failed to parse '%s': %s\n", value, errstr(err));
2282 		return err;
2283 	}
2284 	if (*value_end) {
2285 		pr_warn("failed to parse '%s' as integer completely\n", value);
2286 		return -EINVAL;
2287 	}
2288 	return 0;
2289 }
2290 
2291 static bool is_kcfg_value_in_range(const struct extern_desc *ext, __u64 v)
2292 {
2293 	int bit_sz = ext->kcfg.sz * 8;
2294 
2295 	if (ext->kcfg.sz == 8)
2296 		return true;
2297 
2298 	/* Validate that value stored in u64 fits in integer of `ext->sz`
2299 	 * bytes size without any loss of information. If the target integer
2300 	 * is signed, we rely on the following limits of integer type of
2301 	 * Y bits and subsequent transformation:
2302 	 *
2303 	 *     -2^(Y-1) <= X           <= 2^(Y-1) - 1
2304 	 *            0 <= X + 2^(Y-1) <= 2^Y - 1
2305 	 *            0 <= X + 2^(Y-1) <  2^Y
2306 	 *
2307 	 *  For unsigned target integer, check that all the (64 - Y) bits are
2308 	 *  zero.
2309 	 */
2310 	if (ext->kcfg.is_signed)
2311 		return v + (1ULL << (bit_sz - 1)) < (1ULL << bit_sz);
2312 	else
2313 		return (v >> bit_sz) == 0;
2314 }
2315 
2316 static int set_kcfg_value_num(struct extern_desc *ext, void *ext_val,
2317 			      __u64 value)
2318 {
2319 	if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR &&
2320 	    ext->kcfg.type != KCFG_BOOL) {
2321 		pr_warn("extern (kcfg) '%s': value '%llu' implies integer, char, or boolean type\n",
2322 			ext->name, (unsigned long long)value);
2323 		return -EINVAL;
2324 	}
2325 	if (ext->kcfg.type == KCFG_BOOL && value > 1) {
2326 		pr_warn("extern (kcfg) '%s': value '%llu' isn't boolean compatible\n",
2327 			ext->name, (unsigned long long)value);
2328 		return -EINVAL;
2329 
2330 	}
2331 	if (!is_kcfg_value_in_range(ext, value)) {
2332 		pr_warn("extern (kcfg) '%s': value '%llu' doesn't fit in %d bytes\n",
2333 			ext->name, (unsigned long long)value, ext->kcfg.sz);
2334 		return -ERANGE;
2335 	}
2336 	switch (ext->kcfg.sz) {
2337 	case 1:
2338 		*(__u8 *)ext_val = value;
2339 		break;
2340 	case 2:
2341 		*(__u16 *)ext_val = value;
2342 		break;
2343 	case 4:
2344 		*(__u32 *)ext_val = value;
2345 		break;
2346 	case 8:
2347 		*(__u64 *)ext_val = value;
2348 		break;
2349 	default:
2350 		return -EINVAL;
2351 	}
2352 	ext->is_set = true;
2353 	return 0;
2354 }
2355 
2356 static int bpf_object__process_kconfig_line(struct bpf_object *obj,
2357 					    char *buf, void *data)
2358 {
2359 	struct extern_desc *ext;
2360 	char *sep, *value;
2361 	int len, err = 0;
2362 	void *ext_val;
2363 	__u64 num;
2364 
2365 	if (!str_has_pfx(buf, "CONFIG_"))
2366 		return 0;
2367 
2368 	sep = strchr(buf, '=');
2369 	if (!sep) {
2370 		pr_warn("failed to parse '%s': no separator\n", buf);
2371 		return -EINVAL;
2372 	}
2373 
2374 	/* Trim ending '\n' */
2375 	len = strlen(buf);
2376 	if (buf[len - 1] == '\n')
2377 		buf[len - 1] = '\0';
2378 	/* Split on '=' and ensure that a value is present. */
2379 	*sep = '\0';
2380 	if (!sep[1]) {
2381 		*sep = '=';
2382 		pr_warn("failed to parse '%s': no value\n", buf);
2383 		return -EINVAL;
2384 	}
2385 
2386 	ext = find_extern_by_name(obj, buf);
2387 	if (!ext || ext->is_set)
2388 		return 0;
2389 
2390 	ext_val = data + ext->kcfg.data_off;
2391 	value = sep + 1;
2392 
2393 	switch (*value) {
2394 	case 'y': case 'n': case 'm':
2395 		err = set_kcfg_value_tri(ext, ext_val, *value);
2396 		break;
2397 	case '"':
2398 		err = set_kcfg_value_str(ext, ext_val, value);
2399 		break;
2400 	default:
2401 		/* assume integer */
2402 		err = parse_u64(value, &num);
2403 		if (err) {
2404 			pr_warn("extern (kcfg) '%s': value '%s' isn't a valid integer\n", ext->name, value);
2405 			return err;
2406 		}
2407 		if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR) {
2408 			pr_warn("extern (kcfg) '%s': value '%s' implies integer type\n", ext->name, value);
2409 			return -EINVAL;
2410 		}
2411 		err = set_kcfg_value_num(ext, ext_val, num);
2412 		break;
2413 	}
2414 	if (err)
2415 		return err;
2416 	pr_debug("extern (kcfg) '%s': set to %s\n", ext->name, value);
2417 	return 0;
2418 }
2419 
2420 static int bpf_object__read_kconfig_file(struct bpf_object *obj, void *data)
2421 {
2422 	char buf[PATH_MAX];
2423 	struct utsname uts;
2424 	int len, err = 0;
2425 	gzFile file;
2426 
2427 	uname(&uts);
2428 	len = snprintf(buf, PATH_MAX, "/boot/config-%s", uts.release);
2429 	if (len < 0)
2430 		return -EINVAL;
2431 	else if (len >= PATH_MAX)
2432 		return -ENAMETOOLONG;
2433 
2434 	/* gzopen also accepts uncompressed files. */
2435 	file = gzopen(buf, "re");
2436 	if (!file)
2437 		file = gzopen("/proc/config.gz", "re");
2438 
2439 	if (!file) {
2440 		pr_warn("failed to open system Kconfig\n");
2441 		return -ENOENT;
2442 	}
2443 
2444 	while (gzgets(file, buf, sizeof(buf))) {
2445 		err = bpf_object__process_kconfig_line(obj, buf, data);
2446 		if (err) {
2447 			pr_warn("error parsing system Kconfig line '%s': %s\n",
2448 				buf, errstr(err));
2449 			goto out;
2450 		}
2451 	}
2452 
2453 out:
2454 	gzclose(file);
2455 	return err;
2456 }
2457 
2458 static int bpf_object__read_kconfig_mem(struct bpf_object *obj,
2459 					const char *config, void *data)
2460 {
2461 	char buf[PATH_MAX];
2462 	int err = 0;
2463 	FILE *file;
2464 
2465 	file = fmemopen((void *)config, strlen(config), "r");
2466 	if (!file) {
2467 		err = -errno;
2468 		pr_warn("failed to open in-memory Kconfig: %s\n", errstr(err));
2469 		return err;
2470 	}
2471 
2472 	while (fgets(buf, sizeof(buf), file)) {
2473 		err = bpf_object__process_kconfig_line(obj, buf, data);
2474 		if (err) {
2475 			pr_warn("error parsing in-memory Kconfig line '%s': %s\n",
2476 				buf, errstr(err));
2477 			break;
2478 		}
2479 	}
2480 
2481 	fclose(file);
2482 	return err;
2483 }
2484 
2485 static int bpf_object__init_kconfig_map(struct bpf_object *obj)
2486 {
2487 	struct extern_desc *last_ext = NULL, *ext;
2488 	size_t map_sz;
2489 	int i, err;
2490 
2491 	for (i = 0; i < obj->nr_extern; i++) {
2492 		ext = &obj->externs[i];
2493 		if (ext->type == EXT_KCFG)
2494 			last_ext = ext;
2495 	}
2496 
2497 	if (!last_ext)
2498 		return 0;
2499 
2500 	map_sz = last_ext->kcfg.data_off + last_ext->kcfg.sz;
2501 	err = bpf_object__init_internal_map(obj, LIBBPF_MAP_KCONFIG,
2502 					    ".kconfig", obj->efile.symbols_shndx,
2503 					    NULL, map_sz);
2504 	if (err)
2505 		return err;
2506 
2507 	obj->kconfig_map_idx = obj->nr_maps - 1;
2508 
2509 	return 0;
2510 }
2511 
2512 const struct btf_type *
2513 skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id)
2514 {
2515 	const struct btf_type *t = btf__type_by_id(btf, id);
2516 
2517 	if (res_id)
2518 		*res_id = id;
2519 
2520 	while (btf_is_mod(t) || btf_is_typedef(t)) {
2521 		if (res_id)
2522 			*res_id = t->type;
2523 		t = btf__type_by_id(btf, t->type);
2524 	}
2525 
2526 	return t;
2527 }
2528 
2529 static const struct btf_type *
2530 resolve_func_ptr(const struct btf *btf, __u32 id, __u32 *res_id)
2531 {
2532 	const struct btf_type *t;
2533 
2534 	t = skip_mods_and_typedefs(btf, id, NULL);
2535 	if (!btf_is_ptr(t))
2536 		return NULL;
2537 
2538 	t = skip_mods_and_typedefs(btf, t->type, res_id);
2539 
2540 	return btf_is_func_proto(t) ? t : NULL;
2541 }
2542 
2543 static const char *__btf_kind_str(__u16 kind)
2544 {
2545 	switch (kind) {
2546 	case BTF_KIND_UNKN: return "void";
2547 	case BTF_KIND_INT: return "int";
2548 	case BTF_KIND_PTR: return "ptr";
2549 	case BTF_KIND_ARRAY: return "array";
2550 	case BTF_KIND_STRUCT: return "struct";
2551 	case BTF_KIND_UNION: return "union";
2552 	case BTF_KIND_ENUM: return "enum";
2553 	case BTF_KIND_FWD: return "fwd";
2554 	case BTF_KIND_TYPEDEF: return "typedef";
2555 	case BTF_KIND_VOLATILE: return "volatile";
2556 	case BTF_KIND_CONST: return "const";
2557 	case BTF_KIND_RESTRICT: return "restrict";
2558 	case BTF_KIND_FUNC: return "func";
2559 	case BTF_KIND_FUNC_PROTO: return "func_proto";
2560 	case BTF_KIND_VAR: return "var";
2561 	case BTF_KIND_DATASEC: return "datasec";
2562 	case BTF_KIND_FLOAT: return "float";
2563 	case BTF_KIND_DECL_TAG: return "decl_tag";
2564 	case BTF_KIND_TYPE_TAG: return "type_tag";
2565 	case BTF_KIND_ENUM64: return "enum64";
2566 	case BTF_KIND_LOC_PARAM: return "loc_param";
2567 	case BTF_KIND_LOC_PROTO: return "loc_proto";
2568 	case BTF_KIND_LOCSEC: return "locsec";
2569 	default: return "unknown";
2570 	}
2571 }
2572 
2573 const char *btf_kind_str(const struct btf_type *t)
2574 {
2575 	return __btf_kind_str(btf_kind(t));
2576 }
2577 
2578 /*
2579  * Fetch integer attribute of BTF map definition. Such attributes are
2580  * represented using a pointer to an array, in which dimensionality of array
2581  * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
2582  * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
2583  * type definition, while using only sizeof(void *) space in ELF data section.
2584  */
2585 static bool get_map_field_int(const char *map_name, const struct btf *btf,
2586 			      const struct btf_member *m, __u32 *res)
2587 {
2588 	const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
2589 	const char *name = btf__name_by_offset(btf, m->name_off);
2590 	const struct btf_array *arr_info;
2591 	const struct btf_type *arr_t;
2592 
2593 	if (!btf_is_ptr(t)) {
2594 		pr_warn("map '%s': attr '%s': expected PTR, got %s.\n",
2595 			map_name, name, btf_kind_str(t));
2596 		return false;
2597 	}
2598 
2599 	arr_t = btf__type_by_id(btf, t->type);
2600 	if (!arr_t) {
2601 		pr_warn("map '%s': attr '%s': type [%u] not found.\n",
2602 			map_name, name, t->type);
2603 		return false;
2604 	}
2605 	if (!btf_is_array(arr_t)) {
2606 		pr_warn("map '%s': attr '%s': expected ARRAY, got %s.\n",
2607 			map_name, name, btf_kind_str(arr_t));
2608 		return false;
2609 	}
2610 	arr_info = btf_array(arr_t);
2611 	*res = arr_info->nelems;
2612 	return true;
2613 }
2614 
2615 static bool get_map_field_long(const char *map_name, const struct btf *btf,
2616 			       const struct btf_member *m, __u64 *res)
2617 {
2618 	const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
2619 	const char *name = btf__name_by_offset(btf, m->name_off);
2620 
2621 	if (btf_is_ptr(t)) {
2622 		__u32 res32;
2623 		bool ret;
2624 
2625 		ret = get_map_field_int(map_name, btf, m, &res32);
2626 		if (ret)
2627 			*res = (__u64)res32;
2628 		return ret;
2629 	}
2630 
2631 	if (!btf_is_enum(t) && !btf_is_enum64(t)) {
2632 		pr_warn("map '%s': attr '%s': expected ENUM or ENUM64, got %s.\n",
2633 			map_name, name, btf_kind_str(t));
2634 		return false;
2635 	}
2636 
2637 	if (btf_vlen(t) != 1) {
2638 		pr_warn("map '%s': attr '%s': invalid __ulong\n",
2639 			map_name, name);
2640 		return false;
2641 	}
2642 
2643 	if (btf_is_enum(t)) {
2644 		const struct btf_enum *e = btf_enum(t);
2645 
2646 		*res = e->val;
2647 	} else {
2648 		const struct btf_enum64 *e = btf_enum64(t);
2649 
2650 		*res = btf_enum64_value(e);
2651 	}
2652 	return true;
2653 }
2654 
2655 static int pathname_concat(char *buf, size_t buf_sz, const char *path, const char *name)
2656 {
2657 	int len;
2658 
2659 	len = snprintf(buf, buf_sz, "%s/%s", path, name);
2660 	if (len < 0)
2661 		return -EINVAL;
2662 	if (len >= buf_sz)
2663 		return -ENAMETOOLONG;
2664 
2665 	return 0;
2666 }
2667 
2668 static int build_map_pin_path(struct bpf_map *map, const char *path)
2669 {
2670 	char buf[PATH_MAX];
2671 	int err;
2672 
2673 	if (!path)
2674 		path = BPF_FS_DEFAULT_PATH;
2675 
2676 	err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
2677 	if (err)
2678 		return err;
2679 
2680 	return bpf_map__set_pin_path(map, buf);
2681 }
2682 
2683 /* should match definition in bpf_helpers.h */
2684 enum libbpf_pin_type {
2685 	LIBBPF_PIN_NONE,
2686 	/* PIN_BY_NAME: pin maps by name (in /sys/fs/bpf by default) */
2687 	LIBBPF_PIN_BY_NAME,
2688 };
2689 
2690 int parse_btf_map_def(const char *map_name, struct btf *btf,
2691 		      const struct btf_type *def_t, bool strict,
2692 		      struct btf_map_def *map_def, struct btf_map_def *inner_def)
2693 {
2694 	const struct btf_type *t;
2695 	const struct btf_member *m;
2696 	bool is_inner = inner_def == NULL;
2697 	int vlen, i;
2698 
2699 	vlen = btf_vlen(def_t);
2700 	m = btf_members(def_t);
2701 	for (i = 0; i < vlen; i++, m++) {
2702 		const char *name = btf__name_by_offset(btf, m->name_off);
2703 
2704 		if (!name) {
2705 			pr_warn("map '%s': invalid field #%d.\n", map_name, i);
2706 			return -EINVAL;
2707 		}
2708 		if (strcmp(name, "type") == 0) {
2709 			if (!get_map_field_int(map_name, btf, m, &map_def->map_type))
2710 				return -EINVAL;
2711 			map_def->parts |= MAP_DEF_MAP_TYPE;
2712 		} else if (strcmp(name, "max_entries") == 0) {
2713 			if (!get_map_field_int(map_name, btf, m, &map_def->max_entries))
2714 				return -EINVAL;
2715 			map_def->parts |= MAP_DEF_MAX_ENTRIES;
2716 		} else if (strcmp(name, "map_flags") == 0) {
2717 			if (!get_map_field_int(map_name, btf, m, &map_def->map_flags))
2718 				return -EINVAL;
2719 			map_def->parts |= MAP_DEF_MAP_FLAGS;
2720 		} else if (strcmp(name, "numa_node") == 0) {
2721 			if (!get_map_field_int(map_name, btf, m, &map_def->numa_node))
2722 				return -EINVAL;
2723 			map_def->parts |= MAP_DEF_NUMA_NODE;
2724 		} else if (strcmp(name, "key_size") == 0) {
2725 			__u32 sz;
2726 
2727 			if (!get_map_field_int(map_name, btf, m, &sz))
2728 				return -EINVAL;
2729 			if (map_def->key_size && map_def->key_size != sz) {
2730 				pr_warn("map '%s': conflicting key size %u != %u.\n",
2731 					map_name, map_def->key_size, sz);
2732 				return -EINVAL;
2733 			}
2734 			map_def->key_size = sz;
2735 			map_def->parts |= MAP_DEF_KEY_SIZE;
2736 		} else if (strcmp(name, "key") == 0) {
2737 			__s64 sz;
2738 
2739 			t = btf__type_by_id(btf, m->type);
2740 			if (!t) {
2741 				pr_warn("map '%s': key type [%u] not found.\n",
2742 					map_name, m->type);
2743 				return -EINVAL;
2744 			}
2745 			if (!btf_is_ptr(t)) {
2746 				pr_warn("map '%s': key spec is not PTR: %s.\n",
2747 					map_name, btf_kind_str(t));
2748 				return -EINVAL;
2749 			}
2750 			sz = btf__resolve_size(btf, t->type);
2751 			if (sz < 0) {
2752 				pr_warn("map '%s': can't determine key size for type [%u]: %zd.\n",
2753 					map_name, t->type, (ssize_t)sz);
2754 				return sz;
2755 			}
2756 			if (map_def->key_size && map_def->key_size != sz) {
2757 				pr_warn("map '%s': conflicting key size %u != %zd.\n",
2758 					map_name, map_def->key_size, (ssize_t)sz);
2759 				return -EINVAL;
2760 			}
2761 			map_def->key_size = sz;
2762 			map_def->key_type_id = t->type;
2763 			map_def->parts |= MAP_DEF_KEY_SIZE | MAP_DEF_KEY_TYPE;
2764 		} else if (strcmp(name, "value_size") == 0) {
2765 			__u32 sz;
2766 
2767 			if (!get_map_field_int(map_name, btf, m, &sz))
2768 				return -EINVAL;
2769 			if (map_def->value_size && map_def->value_size != sz) {
2770 				pr_warn("map '%s': conflicting value size %u != %u.\n",
2771 					map_name, map_def->value_size, sz);
2772 				return -EINVAL;
2773 			}
2774 			map_def->value_size = sz;
2775 			map_def->parts |= MAP_DEF_VALUE_SIZE;
2776 		} else if (strcmp(name, "value") == 0) {
2777 			__s64 sz;
2778 
2779 			t = btf__type_by_id(btf, m->type);
2780 			if (!t) {
2781 				pr_warn("map '%s': value type [%u] not found.\n",
2782 					map_name, m->type);
2783 				return -EINVAL;
2784 			}
2785 			if (!btf_is_ptr(t)) {
2786 				pr_warn("map '%s': value spec is not PTR: %s.\n",
2787 					map_name, btf_kind_str(t));
2788 				return -EINVAL;
2789 			}
2790 			sz = btf__resolve_size(btf, t->type);
2791 			if (sz < 0) {
2792 				pr_warn("map '%s': can't determine value size for type [%u]: %zd.\n",
2793 					map_name, t->type, (ssize_t)sz);
2794 				return sz;
2795 			}
2796 			if (map_def->value_size && map_def->value_size != sz) {
2797 				pr_warn("map '%s': conflicting value size %u != %zd.\n",
2798 					map_name, map_def->value_size, (ssize_t)sz);
2799 				return -EINVAL;
2800 			}
2801 			map_def->value_size = sz;
2802 			map_def->value_type_id = t->type;
2803 			map_def->parts |= MAP_DEF_VALUE_SIZE | MAP_DEF_VALUE_TYPE;
2804 		}
2805 		else if (strcmp(name, "values") == 0) {
2806 			bool is_map_in_map = bpf_map_type__is_map_in_map(map_def->map_type);
2807 			bool is_prog_array = map_def->map_type == BPF_MAP_TYPE_PROG_ARRAY;
2808 			const char *desc = is_map_in_map ? "map-in-map inner" : "prog-array value";
2809 			char inner_map_name[128];
2810 			int err;
2811 
2812 			if (is_inner) {
2813 				pr_warn("map '%s': multi-level inner maps not supported.\n",
2814 					map_name);
2815 				return -ENOTSUP;
2816 			}
2817 			if (i != vlen - 1) {
2818 				pr_warn("map '%s': '%s' member should be last.\n",
2819 					map_name, name);
2820 				return -EINVAL;
2821 			}
2822 			if (!is_map_in_map && !is_prog_array) {
2823 				pr_warn("map '%s': should be map-in-map or prog-array.\n",
2824 					map_name);
2825 				return -ENOTSUP;
2826 			}
2827 			if (map_def->value_size && map_def->value_size != 4) {
2828 				pr_warn("map '%s': conflicting value size %u != 4.\n",
2829 					map_name, map_def->value_size);
2830 				return -EINVAL;
2831 			}
2832 			map_def->value_size = 4;
2833 			t = btf__type_by_id(btf, m->type);
2834 			if (!t) {
2835 				pr_warn("map '%s': %s type [%u] not found.\n",
2836 					map_name, desc, m->type);
2837 				return -EINVAL;
2838 			}
2839 			if (!btf_is_array(t) || btf_array(t)->nelems) {
2840 				pr_warn("map '%s': %s spec is not a zero-sized array.\n",
2841 					map_name, desc);
2842 				return -EINVAL;
2843 			}
2844 			t = skip_mods_and_typedefs(btf, btf_array(t)->type, NULL);
2845 			if (!btf_is_ptr(t)) {
2846 				pr_warn("map '%s': %s def is of unexpected kind %s.\n",
2847 					map_name, desc, btf_kind_str(t));
2848 				return -EINVAL;
2849 			}
2850 			t = skip_mods_and_typedefs(btf, t->type, NULL);
2851 			if (is_prog_array) {
2852 				if (!btf_is_func_proto(t)) {
2853 					pr_warn("map '%s': prog-array value def is of unexpected kind %s.\n",
2854 						map_name, btf_kind_str(t));
2855 					return -EINVAL;
2856 				}
2857 				continue;
2858 			}
2859 			if (!btf_is_struct(t)) {
2860 				pr_warn("map '%s': map-in-map inner def is of unexpected kind %s.\n",
2861 					map_name, btf_kind_str(t));
2862 				return -EINVAL;
2863 			}
2864 
2865 			snprintf(inner_map_name, sizeof(inner_map_name), "%s.inner", map_name);
2866 			err = parse_btf_map_def(inner_map_name, btf, t, strict, inner_def, NULL);
2867 			if (err)
2868 				return err;
2869 
2870 			map_def->parts |= MAP_DEF_INNER_MAP;
2871 		} else if (strcmp(name, "pinning") == 0) {
2872 			__u32 val;
2873 
2874 			if (is_inner) {
2875 				pr_warn("map '%s': inner def can't be pinned.\n", map_name);
2876 				return -EINVAL;
2877 			}
2878 			if (!get_map_field_int(map_name, btf, m, &val))
2879 				return -EINVAL;
2880 			if (val != LIBBPF_PIN_NONE && val != LIBBPF_PIN_BY_NAME) {
2881 				pr_warn("map '%s': invalid pinning value %u.\n",
2882 					map_name, val);
2883 				return -EINVAL;
2884 			}
2885 			map_def->pinning = val;
2886 			map_def->parts |= MAP_DEF_PINNING;
2887 		} else if (strcmp(name, "map_extra") == 0) {
2888 			__u64 map_extra;
2889 
2890 			if (!get_map_field_long(map_name, btf, m, &map_extra))
2891 				return -EINVAL;
2892 			map_def->map_extra = map_extra;
2893 			map_def->parts |= MAP_DEF_MAP_EXTRA;
2894 		} else {
2895 			if (strict) {
2896 				pr_warn("map '%s': unknown field '%s'.\n", map_name, name);
2897 				return -ENOTSUP;
2898 			}
2899 			pr_debug("map '%s': ignoring unknown field '%s'.\n", map_name, name);
2900 		}
2901 	}
2902 
2903 	if (map_def->map_type == BPF_MAP_TYPE_UNSPEC) {
2904 		pr_warn("map '%s': map type isn't specified.\n", map_name);
2905 		return -EINVAL;
2906 	}
2907 
2908 	return 0;
2909 }
2910 
2911 static size_t adjust_ringbuf_sz(size_t sz)
2912 {
2913 	__u32 page_sz = sysconf(_SC_PAGE_SIZE);
2914 	__u32 mul;
2915 
2916 	/* if user forgot to set any size, make sure they see error */
2917 	if (sz == 0)
2918 		return 0;
2919 	/* Kernel expects BPF_MAP_TYPE_RINGBUF's max_entries to be
2920 	 * a power-of-2 multiple of kernel's page size. If user diligently
2921 	 * satisfied these conditions, pass the size through.
2922 	 */
2923 	if ((sz % page_sz) == 0 && is_pow_of_2(sz / page_sz))
2924 		return sz;
2925 
2926 	/* Otherwise find closest (page_sz * power_of_2) product bigger than
2927 	 * user-set size to satisfy both user size request and kernel
2928 	 * requirements and substitute correct max_entries for map creation.
2929 	 */
2930 	for (mul = 1; mul <= UINT_MAX / page_sz; mul <<= 1) {
2931 		if (mul * page_sz > sz)
2932 			return mul * page_sz;
2933 	}
2934 
2935 	/* if it's impossible to satisfy the conditions (i.e., user size is
2936 	 * very close to UINT_MAX but is not a power-of-2 multiple of
2937 	 * page_size) then just return original size and let kernel reject it
2938 	 */
2939 	return sz;
2940 }
2941 
2942 static bool map_is_ringbuf(const struct bpf_map *map)
2943 {
2944 	return map->def.type == BPF_MAP_TYPE_RINGBUF ||
2945 	       map->def.type == BPF_MAP_TYPE_USER_RINGBUF;
2946 }
2947 
2948 static void fill_map_from_def(struct bpf_map *map, const struct btf_map_def *def)
2949 {
2950 	map->def.type = def->map_type;
2951 	map->def.key_size = def->key_size;
2952 	map->def.value_size = def->value_size;
2953 	map->def.max_entries = def->max_entries;
2954 	map->def.map_flags = def->map_flags;
2955 	map->map_extra = def->map_extra;
2956 
2957 	map->numa_node = def->numa_node;
2958 	map->btf_key_type_id = def->key_type_id;
2959 	map->btf_value_type_id = def->value_type_id;
2960 
2961 	/* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
2962 	if (map_is_ringbuf(map))
2963 		map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
2964 
2965 	if (def->parts & MAP_DEF_MAP_TYPE)
2966 		pr_debug("map '%s': found type = %u.\n", map->name, def->map_type);
2967 
2968 	if (def->parts & MAP_DEF_KEY_TYPE)
2969 		pr_debug("map '%s': found key [%u], sz = %u.\n",
2970 			 map->name, def->key_type_id, def->key_size);
2971 	else if (def->parts & MAP_DEF_KEY_SIZE)
2972 		pr_debug("map '%s': found key_size = %u.\n", map->name, def->key_size);
2973 
2974 	if (def->parts & MAP_DEF_VALUE_TYPE)
2975 		pr_debug("map '%s': found value [%u], sz = %u.\n",
2976 			 map->name, def->value_type_id, def->value_size);
2977 	else if (def->parts & MAP_DEF_VALUE_SIZE)
2978 		pr_debug("map '%s': found value_size = %u.\n", map->name, def->value_size);
2979 
2980 	if (def->parts & MAP_DEF_MAX_ENTRIES)
2981 		pr_debug("map '%s': found max_entries = %u.\n", map->name, def->max_entries);
2982 	if (def->parts & MAP_DEF_MAP_FLAGS)
2983 		pr_debug("map '%s': found map_flags = 0x%x.\n", map->name, def->map_flags);
2984 	if (def->parts & MAP_DEF_MAP_EXTRA)
2985 		pr_debug("map '%s': found map_extra = 0x%llx.\n", map->name,
2986 			 (unsigned long long)def->map_extra);
2987 	if (def->parts & MAP_DEF_PINNING)
2988 		pr_debug("map '%s': found pinning = %u.\n", map->name, def->pinning);
2989 	if (def->parts & MAP_DEF_NUMA_NODE)
2990 		pr_debug("map '%s': found numa_node = %u.\n", map->name, def->numa_node);
2991 
2992 	if (def->parts & MAP_DEF_INNER_MAP)
2993 		pr_debug("map '%s': found inner map definition.\n", map->name);
2994 }
2995 
2996 static const char *btf_var_linkage_str(__u32 linkage)
2997 {
2998 	switch (linkage) {
2999 	case BTF_VAR_STATIC: return "static";
3000 	case BTF_VAR_GLOBAL_ALLOCATED: return "global";
3001 	case BTF_VAR_GLOBAL_EXTERN: return "extern";
3002 	default: return "unknown";
3003 	}
3004 }
3005 
3006 static int bpf_object__init_user_btf_map(struct bpf_object *obj,
3007 					 const struct btf_type *sec,
3008 					 int var_idx, int sec_idx,
3009 					 const Elf_Data *data, bool strict,
3010 					 const char *pin_root_path)
3011 {
3012 	struct btf_map_def map_def = {}, inner_def = {};
3013 	const struct btf_type *var, *def;
3014 	const struct btf_var_secinfo *vi;
3015 	const struct btf_var *var_extra;
3016 	const char *map_name;
3017 	struct bpf_map *map;
3018 	int err;
3019 
3020 	vi = btf_var_secinfos(sec) + var_idx;
3021 	var = btf__type_by_id(obj->btf, vi->type);
3022 	var_extra = btf_var(var);
3023 	map_name = btf__name_by_offset(obj->btf, var->name_off);
3024 
3025 	if (str_is_empty(map_name)) {
3026 		pr_warn("map #%d: empty name.\n", var_idx);
3027 		return -EINVAL;
3028 	}
3029 	if ((__u64)vi->offset + vi->size > data->d_size) {
3030 		pr_warn("map '%s' BTF data is corrupted.\n", map_name);
3031 		return -EINVAL;
3032 	}
3033 	if (!btf_is_var(var)) {
3034 		pr_warn("map '%s': unexpected var kind %s.\n",
3035 			map_name, btf_kind_str(var));
3036 		return -EINVAL;
3037 	}
3038 	if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED) {
3039 		pr_warn("map '%s': unsupported map linkage %s.\n",
3040 			map_name, btf_var_linkage_str(var_extra->linkage));
3041 		return -EOPNOTSUPP;
3042 	}
3043 
3044 	def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
3045 	if (!btf_is_struct(def)) {
3046 		pr_warn("map '%s': unexpected def kind %s.\n",
3047 			map_name, btf_kind_str(var));
3048 		return -EINVAL;
3049 	}
3050 	if (def->size > vi->size) {
3051 		pr_warn("map '%s': invalid def size.\n", map_name);
3052 		return -EINVAL;
3053 	}
3054 
3055 	map = bpf_object__add_map(obj);
3056 	if (IS_ERR(map))
3057 		return PTR_ERR(map);
3058 	map->name = strdup(map_name);
3059 	if (!map->name) {
3060 		pr_warn("map '%s': failed to alloc map name.\n", map_name);
3061 		return -ENOMEM;
3062 	}
3063 	map->libbpf_type = LIBBPF_MAP_UNSPEC;
3064 	map->def.type = BPF_MAP_TYPE_UNSPEC;
3065 	map->sec_idx = sec_idx;
3066 	map->sec_offset = vi->offset;
3067 	map->btf_var_idx = var_idx;
3068 	pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
3069 		 map_name, map->sec_idx, map->sec_offset);
3070 
3071 	err = parse_btf_map_def(map->name, obj->btf, def, strict, &map_def, &inner_def);
3072 	if (err)
3073 		return err;
3074 
3075 	fill_map_from_def(map, &map_def);
3076 
3077 	if (map_def.pinning == LIBBPF_PIN_BY_NAME) {
3078 		err = build_map_pin_path(map, pin_root_path);
3079 		if (err) {
3080 			pr_warn("map '%s': couldn't build pin path.\n", map->name);
3081 			return err;
3082 		}
3083 	}
3084 
3085 	if (map_def.parts & MAP_DEF_INNER_MAP) {
3086 		map->inner_map = calloc(1, sizeof(*map->inner_map));
3087 		if (!map->inner_map)
3088 			return -ENOMEM;
3089 		map->inner_map->fd = create_placeholder_fd();
3090 		if (map->inner_map->fd < 0)
3091 			return map->inner_map->fd;
3092 		map->inner_map->sec_idx = sec_idx;
3093 		map->inner_map->name = malloc(strlen(map_name) + sizeof(".inner") + 1);
3094 		if (!map->inner_map->name)
3095 			return -ENOMEM;
3096 		sprintf(map->inner_map->name, "%s.inner", map_name);
3097 
3098 		fill_map_from_def(map->inner_map, &inner_def);
3099 	}
3100 
3101 	err = map_fill_btf_type_info(obj, map);
3102 	if (err)
3103 		return err;
3104 
3105 	return 0;
3106 }
3107 
3108 static int init_arena_map_data(struct bpf_object *obj, struct bpf_map *map,
3109 			       void *data, size_t data_sz)
3110 {
3111 	obj->arena_data = malloc(data_sz);
3112 	if (!obj->arena_data)
3113 		return -ENOMEM;
3114 	memcpy(obj->arena_data, data, data_sz);
3115 	obj->arena_data_sz = data_sz;
3116 
3117 	/* make bpf_map__init_value() work for ARENA maps */
3118 	map->mmaped = obj->arena_data;
3119 
3120 	return 0;
3121 }
3122 
3123 static bool map_is_const_str(const struct bpf_map *map)
3124 {
3125 	return map->libbpf_type == LIBBPF_MAP_RODATA &&
3126 	       str_has_pfx(map->real_name, RODATA_SEC ".str");
3127 }
3128 
3129 static bool map_data_goes_to_arena(const struct bpf_object *obj, const struct bpf_map *map)
3130 {
3131 	int i;
3132 
3133 	switch (map->libbpf_type) {
3134 	case LIBBPF_MAP_DATA:
3135 	case LIBBPF_MAP_BSS:
3136 		return true;
3137 	case LIBBPF_MAP_RODATA:
3138 		break;
3139 	default:
3140 		return false;
3141 	}
3142 
3143 	/*
3144 	 * Const strings that kfuncs and helpers take have to be in a frozen
3145 	 * map. Pointers to them that are stored in data point to a copy of
3146 	 * the strings that is in arena.
3147 	 */
3148 	if (map_is_const_str(map))
3149 		return true;
3150 	/*
3151 	 * Read-only data with pointers stays a frozen map: the kernel
3152 	 * recognizes pointers to functions in it.
3153 	 */
3154 	if (str_has_pfx(map->real_name, DATA_REL_RO_SEC))
3155 		return false;
3156 	for (i = 0; i < obj->efile.sec_cnt; i++) {
3157 		const struct elf_sec_desc *sec = &obj->efile.secs[i];
3158 
3159 		if (sec->sec_type == SEC_RELO && sec->shdr->sh_info == map->sec_idx)
3160 			return false;
3161 	}
3162 	return true;
3163 }
3164 
3165 /* Returns the offset of the data of the map in arena data that is sz bytes so far */
3166 static size_t map_arena_off(const struct bpf_object *obj, const struct bpf_map *map, size_t sz)
3167 {
3168 	size_t align = obj->efile.secs[map->sec_idx].shdr->sh_addralign;
3169 
3170 	return roundup(sz, max(align, sizeof(__u64)));
3171 }
3172 
3173 /*
3174  * Make .data, .bss and .rodata a part of arena data. They follow __arena
3175  * variables of the object, if there are any.
3176  */
3177 static int bpf_object__init_arena_data(struct bpf_object *obj)
3178 {
3179 	const size_t page_sz = sysconf(_SC_PAGE_SIZE);
3180 	size_t sz = obj->arena_data_sz;
3181 	struct bpf_map *map;
3182 	void *data;
3183 	int i;
3184 
3185 	if (!obj->data_in_arena)
3186 		return 0;
3187 
3188 	for (i = 0; i < obj->nr_maps; i++) {
3189 		map = &obj->maps[i];
3190 		if (map_data_goes_to_arena(obj, map))
3191 			sz = map_arena_off(obj, map, sz) + map->def.value_size;
3192 	}
3193 	if (sz == obj->arena_data_sz)
3194 		return 0;
3195 
3196 	if (obj->arena_map_idx < 0) {
3197 		/* bpf_object__init_user_btf_maps() didn't look: there is no .maps section */
3198 		if (obj->efile.arena_data) {
3199 			pr_warn("elf: sec '%s': to use global __arena variables the ARENA map should be explicitly declared in SEC(\".maps\")\n",
3200 				ARENA_SEC);
3201 			return -ENOENT;
3202 		}
3203 
3204 		map = bpf_object__add_map(obj);
3205 		if (IS_ERR(map))
3206 			return PTR_ERR(map);
3207 
3208 		map->real_name = strdup("arena");
3209 		map->name = strdup("arena");
3210 		if (!map->real_name || !map->name) {
3211 			zfree(&map->real_name);
3212 			zfree(&map->name);
3213 			return -ENOMEM;
3214 		}
3215 		map->sec_idx = -1;
3216 		map->def.type = BPF_MAP_TYPE_ARENA;
3217 		map->def.max_entries = roundup(sz, page_sz) / page_sz;
3218 		map->def.map_flags = BPF_F_MMAPABLE;
3219 		obj->arena_map_idx = map - obj->maps;
3220 	}
3221 
3222 	data = realloc(obj->arena_data, sz);
3223 	if (!data)
3224 		return -ENOMEM;
3225 	memset(data + obj->arena_data_sz, 0, sz - obj->arena_data_sz);
3226 	sz = obj->arena_data_sz;
3227 	obj->arena_data = data;
3228 	obj->maps[obj->arena_map_idx].mmaped = data;
3229 
3230 	for (i = 0; i < obj->nr_maps; i++) {
3231 		map = &obj->maps[i];
3232 		if (!map_data_goes_to_arena(obj, map))
3233 			continue;
3234 		sz = map_arena_off(obj, map, sz);
3235 		map->arena_off = sz;
3236 		memcpy(data + sz, map->mmaped, map->def.value_size);
3237 		sz += map->def.value_size;
3238 		pr_debug("map '%s': data is in arena at offset %zu\n", map->name, map->arena_off);
3239 		if (map_is_const_str(map)) {
3240 			map->arena_copy = true;
3241 			continue;
3242 		}
3243 		munmap(map->mmaped, bpf_map_mmap_sz(map));
3244 		/* make bpf_map__initial_value() and bpf_map__set_initial_value() work */
3245 		map->mmaped = data + map->arena_off;
3246 		map->autocreate = false;
3247 		map->in_arena = true;
3248 	}
3249 	obj->arena_data_sz = sz;
3250 	return 0;
3251 }
3252 
3253 static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict,
3254 					  const char *pin_root_path)
3255 {
3256 	const struct btf_type *sec = NULL;
3257 	int nr_types, i, vlen, err;
3258 	const struct btf_type *t;
3259 	const char *name;
3260 	Elf_Data *data;
3261 	Elf_Scn *scn;
3262 
3263 	if (obj->efile.btf_maps_shndx < 0)
3264 		return 0;
3265 
3266 	scn = elf_sec_by_idx(obj, obj->efile.btf_maps_shndx);
3267 	data = elf_sec_data(obj, scn);
3268 	if (!data) {
3269 		pr_warn("elf: failed to get %s map definitions for %s\n",
3270 			MAPS_ELF_SEC, obj->path);
3271 		return -EINVAL;
3272 	}
3273 
3274 	nr_types = btf__type_cnt(obj->btf);
3275 	for (i = 1; i < nr_types; i++) {
3276 		t = btf__type_by_id(obj->btf, i);
3277 		if (!btf_is_datasec(t))
3278 			continue;
3279 		name = btf__name_by_offset(obj->btf, t->name_off);
3280 		if (strcmp(name, MAPS_ELF_SEC) == 0) {
3281 			sec = t;
3282 			obj->efile.btf_maps_sec_btf_id = i;
3283 			break;
3284 		}
3285 	}
3286 
3287 	if (!sec) {
3288 		pr_warn("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
3289 		return -ENOENT;
3290 	}
3291 
3292 	vlen = btf_vlen(sec);
3293 	for (i = 0; i < vlen; i++) {
3294 		err = bpf_object__init_user_btf_map(obj, sec, i,
3295 						    obj->efile.btf_maps_shndx,
3296 						    data, strict,
3297 						    pin_root_path);
3298 		if (err)
3299 			return err;
3300 	}
3301 
3302 	for (i = 0; i < obj->nr_maps; i++) {
3303 		struct bpf_map *map = &obj->maps[i];
3304 
3305 		if (map->def.type != BPF_MAP_TYPE_ARENA)
3306 			continue;
3307 
3308 		if (obj->arena_map_idx >= 0) {
3309 			pr_warn("map '%s': only single ARENA map is supported (map '%s' is also ARENA)\n",
3310 				map->name, obj->maps[obj->arena_map_idx].name);
3311 			return -EINVAL;
3312 		}
3313 		obj->arena_map_idx = i;
3314 
3315 		if (obj->efile.arena_data) {
3316 			err = init_arena_map_data(obj, map, obj->efile.arena_data->d_buf,
3317 						  obj->efile.arena_data->d_size);
3318 			if (err)
3319 				return err;
3320 		}
3321 	}
3322 	if (obj->efile.arena_data && obj->arena_map_idx < 0) {
3323 		pr_warn("elf: sec '%s': to use global __arena variables the ARENA map should be explicitly declared in SEC(\".maps\")\n",
3324 			ARENA_SEC);
3325 		return -ENOENT;
3326 	}
3327 
3328 	return 0;
3329 }
3330 
3331 static int bpf_object__init_maps(struct bpf_object *obj,
3332 				 const struct bpf_object_open_opts *opts)
3333 {
3334 	const char *pin_root_path;
3335 	bool strict;
3336 	int err = 0;
3337 
3338 	strict = !OPTS_GET(opts, relaxed_maps, false);
3339 	pin_root_path = OPTS_GET(opts, pin_root_path, NULL);
3340 
3341 	err = bpf_object__init_user_btf_maps(obj, strict, pin_root_path);
3342 	err = err ?: bpf_object__init_global_data_maps(obj);
3343 	err = err ?: bpf_object__init_kconfig_map(obj);
3344 	err = err ?: bpf_object_init_struct_ops(obj);
3345 	err = err ?: bpf_object__init_arena_data(obj);
3346 
3347 	return err;
3348 }
3349 
3350 static bool section_have_execinstr(struct bpf_object *obj, int idx)
3351 {
3352 	Elf64_Shdr *sh;
3353 
3354 	sh = elf_sec_hdr(obj, elf_sec_by_idx(obj, idx));
3355 	if (!sh)
3356 		return false;
3357 
3358 	return sh->sh_flags & SHF_EXECINSTR;
3359 }
3360 
3361 static bool starts_with_qmark(const char *s)
3362 {
3363 	return s && s[0] == '?';
3364 }
3365 
3366 static bool btf_needs_sanitization(struct bpf_object *obj)
3367 {
3368 	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
3369 	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
3370 	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
3371 	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
3372 	bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
3373 	bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
3374 	bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
3375 	bool has_qmark_datasec = kernel_supports(obj, FEAT_BTF_QMARK_DATASEC);
3376 	bool has_layout = kernel_supports(obj, FEAT_BTF_LAYOUT);
3377 
3378 	return !has_func || !has_datasec || !has_func_global || !has_float ||
3379 	       !has_decl_tag || !has_type_tag || !has_enum64 || !has_qmark_datasec ||
3380 	       !has_layout;
3381 }
3382 
3383 struct btf *bpf_object__sanitize_btf(struct bpf_object *obj, struct btf *orig_btf)
3384 {
3385 	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
3386 	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
3387 	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
3388 	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
3389 	bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
3390 	bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
3391 	bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
3392 	bool has_qmark_datasec = kernel_supports(obj, FEAT_BTF_QMARK_DATASEC);
3393 	bool has_layout = kernel_supports(obj, FEAT_BTF_LAYOUT);
3394 	int enum64_placeholder_id = 0;
3395 	const struct btf_header *hdr;
3396 	struct btf *btf = NULL;
3397 	const void *raw_data;
3398 	struct btf_type *t;
3399 	int i, j, vlen;
3400 	__u32 sz;
3401 	int err;
3402 
3403 	/* clone BTF to sanitize a copy and leave the original intact */
3404 	raw_data = btf__raw_data(orig_btf, &sz);
3405 	if (!raw_data)
3406 		return ERR_PTR(-ENOMEM);
3407 	/* btf_header() gives us endian-safe header info */
3408 	hdr = btf_header(orig_btf);
3409 
3410 	if (!has_layout && hdr->hdr_len >= sizeof(struct btf_header) &&
3411 	    (hdr->layout_len != 0 || hdr->layout_off != 0)) {
3412 		const struct btf_header *old_hdr = raw_data;
3413 		struct btf_header *new_hdr;
3414 		void *new_raw_data;
3415 		__u32 new_str_off;
3416 
3417 		/*
3418 		 * Need to rewrite BTF to exclude layout information and
3419 		 * move string section to immediately after types.
3420 		 */
3421 		new_raw_data = malloc(sz);
3422 		if (!new_raw_data)
3423 			return ERR_PTR(-ENOMEM);
3424 
3425 		memcpy(new_raw_data, raw_data, sz);
3426 		new_hdr = new_raw_data;
3427 		new_hdr->layout_off = 0;
3428 		new_hdr->layout_len = 0;
3429 		new_str_off = hdr->type_off + hdr->type_len;
3430 		/* Handle swapped endian case */
3431 		if (old_hdr->magic != hdr->magic)
3432 			new_hdr->str_off = bswap_32(new_str_off);
3433 		else
3434 			new_hdr->str_off = new_str_off;
3435 
3436 		memmove(new_raw_data + hdr->hdr_len + new_str_off,
3437 			new_raw_data + hdr->hdr_len + hdr->str_off,
3438 			hdr->str_len);
3439 		sz = hdr->hdr_len + hdr->type_off + hdr->type_len + hdr->str_len;
3440 		btf = btf__new(new_raw_data, sz);
3441 		free(new_raw_data);
3442 	} else {
3443 		btf = btf__new(raw_data, sz);
3444 	}
3445 	err = libbpf_get_error(btf);
3446 	if (err)
3447 		return ERR_PTR(err);
3448 
3449 	/* enforce 8-byte pointers for BPF-targeted BTFs */
3450 	btf__set_pointer_size(btf, 8);
3451 
3452 	for (i = 1; i < btf__type_cnt(btf); i++) {
3453 		t = (struct btf_type *)btf__type_by_id(btf, i);
3454 
3455 		if ((!has_datasec && btf_is_var(t)) || (!has_decl_tag && btf_is_decl_tag(t))) {
3456 			/* replace VAR/DECL_TAG with INT */
3457 			t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
3458 			/*
3459 			 * using size = 1 is the safest choice, 4 will be too
3460 			 * big and cause kernel BTF validation failure if
3461 			 * original variable took less than 4 bytes
3462 			 */
3463 			t->size = 1;
3464 			*(int *)(t + 1) = BTF_INT_ENC(0, 0, 8);
3465 		} else if (!has_datasec && btf_is_datasec(t)) {
3466 			/* replace DATASEC with STRUCT */
3467 			const struct btf_var_secinfo *v = btf_var_secinfos(t);
3468 			struct btf_member *m = btf_members(t);
3469 			struct btf_type *vt;
3470 			char *name;
3471 
3472 			name = (char *)btf__name_by_offset(btf, t->name_off);
3473 			while (*name) {
3474 				if (*name == '.' || *name == '?')
3475 					*name = '_';
3476 				name++;
3477 			}
3478 
3479 			vlen = btf_vlen(t);
3480 			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
3481 			for (j = 0; j < vlen; j++, v++, m++) {
3482 				/* order of field assignments is important */
3483 				m->offset = v->offset * 8;
3484 				m->type = v->type;
3485 				/* preserve variable name as member name */
3486 				vt = (void *)btf__type_by_id(btf, v->type);
3487 				m->name_off = vt->name_off;
3488 			}
3489 		} else if (!has_qmark_datasec && btf_is_datasec(t) &&
3490 			   starts_with_qmark(btf__name_by_offset(btf, t->name_off))) {
3491 			/* replace '?' prefix with '_' for DATASEC names */
3492 			char *name;
3493 
3494 			name = (char *)btf__name_by_offset(btf, t->name_off);
3495 			if (name[0] == '?')
3496 				name[0] = '_';
3497 		} else if (!has_func && btf_is_func_proto(t)) {
3498 			/* replace FUNC_PROTO with ENUM */
3499 			vlen = btf_vlen(t);
3500 			t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
3501 			t->size = sizeof(__u32); /* kernel enforced */
3502 		} else if (!has_func && btf_is_func(t)) {
3503 			/* replace FUNC with TYPEDEF */
3504 			t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
3505 		} else if (!has_func_global && btf_is_func(t)) {
3506 			/* replace BTF_FUNC_GLOBAL with BTF_FUNC_STATIC */
3507 			t->info = BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0);
3508 		} else if (!has_float && btf_is_float(t)) {
3509 			/* replace FLOAT with an equally-sized empty STRUCT;
3510 			 * since C compilers do not accept e.g. "float" as a
3511 			 * valid struct name, make it anonymous
3512 			 */
3513 			t->name_off = 0;
3514 			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, 0);
3515 		} else if (!has_type_tag && btf_is_type_tag(t)) {
3516 			/* replace TYPE_TAG with a CONST */
3517 			t->name_off = 0;
3518 			t->info = BTF_INFO_ENC(BTF_KIND_CONST, 0, 0);
3519 		} else if (!has_enum64 && btf_is_enum(t)) {
3520 			/* clear the kflag */
3521 			t->info = btf_type_info(btf_kind(t), btf_vlen(t), false);
3522 		} else if (!has_enum64 && btf_is_enum64(t)) {
3523 			/* replace ENUM64 with a union */
3524 			struct btf_member *m;
3525 
3526 			if (enum64_placeholder_id == 0) {
3527 				enum64_placeholder_id = btf__add_int(btf, "enum64_placeholder", 1, 0);
3528 				if (enum64_placeholder_id < 0) {
3529 					btf__free(btf);
3530 					return ERR_PTR(enum64_placeholder_id);
3531 				}
3532 				t = (struct btf_type *)btf__type_by_id(btf, i);
3533 			}
3534 
3535 			m = btf_members(t);
3536 			vlen = btf_vlen(t);
3537 			t->info = BTF_INFO_ENC(BTF_KIND_UNION, 0, vlen);
3538 			for (j = 0; j < vlen; j++, m++) {
3539 				m->type = enum64_placeholder_id;
3540 				m->offset = 0;
3541 			}
3542 		}
3543 	}
3544 
3545 	return btf;
3546 }
3547 
3548 static bool libbpf_needs_btf(const struct bpf_object *obj)
3549 {
3550 	return obj->efile.btf_maps_shndx >= 0 ||
3551 	       obj->efile.has_st_ops ||
3552 	       obj->nr_extern > 0;
3553 }
3554 
3555 static bool kernel_needs_btf(const struct bpf_object *obj)
3556 {
3557 	return obj->efile.has_st_ops;
3558 }
3559 
3560 static int bpf_object__init_btf(struct bpf_object *obj,
3561 				Elf_Data *btf_data,
3562 				Elf_Data *btf_ext_data)
3563 {
3564 	int err = -ENOENT;
3565 
3566 	if (btf_data) {
3567 		obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
3568 		err = libbpf_get_error(obj->btf);
3569 		if (err) {
3570 			obj->btf = NULL;
3571 			pr_warn("Error loading ELF section %s: %s.\n", BTF_ELF_SEC, errstr(err));
3572 			goto out;
3573 		}
3574 		/* enforce 8-byte pointers for BPF-targeted BTFs */
3575 		btf__set_pointer_size(obj->btf, 8);
3576 	}
3577 	if (btf_ext_data) {
3578 		struct btf_ext_info *ext_segs[3];
3579 		int seg_num, sec_num;
3580 
3581 		if (!obj->btf) {
3582 			pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
3583 				 BTF_EXT_ELF_SEC, BTF_ELF_SEC);
3584 			goto out;
3585 		}
3586 		obj->btf_ext = btf_ext__new(btf_ext_data->d_buf, btf_ext_data->d_size);
3587 		err = libbpf_get_error(obj->btf_ext);
3588 		if (err) {
3589 			pr_warn("Error loading ELF section %s: %s. Ignored and continue.\n",
3590 				BTF_EXT_ELF_SEC, errstr(err));
3591 			obj->btf_ext = NULL;
3592 			goto out;
3593 		}
3594 
3595 		/* setup .BTF.ext to ELF section mapping */
3596 		ext_segs[0] = &obj->btf_ext->func_info;
3597 		ext_segs[1] = &obj->btf_ext->line_info;
3598 		ext_segs[2] = &obj->btf_ext->core_relo_info;
3599 		for (seg_num = 0; seg_num < ARRAY_SIZE(ext_segs); seg_num++) {
3600 			struct btf_ext_info *seg = ext_segs[seg_num];
3601 			const struct btf_ext_info_sec *sec;
3602 			const char *sec_name;
3603 			Elf_Scn *scn;
3604 
3605 			if (seg->sec_cnt == 0)
3606 				continue;
3607 
3608 			seg->sec_idxs = calloc(seg->sec_cnt, sizeof(*seg->sec_idxs));
3609 			if (!seg->sec_idxs) {
3610 				err = -ENOMEM;
3611 				goto out;
3612 			}
3613 
3614 			sec_num = 0;
3615 			for_each_btf_ext_sec(seg, sec) {
3616 				/* preventively increment index to avoid doing
3617 				 * this before every continue below
3618 				 */
3619 				sec_num++;
3620 
3621 				sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
3622 				if (str_is_empty(sec_name))
3623 					continue;
3624 				scn = elf_sec_by_name(obj, sec_name);
3625 				if (!scn)
3626 					continue;
3627 
3628 				seg->sec_idxs[sec_num - 1] = elf_ndxscn(scn);
3629 			}
3630 		}
3631 	}
3632 out:
3633 	if (err && libbpf_needs_btf(obj)) {
3634 		pr_warn("BTF is required, but is missing or corrupted.\n");
3635 		return err;
3636 	}
3637 	return 0;
3638 }
3639 
3640 static int compare_vsi_off(const void *_a, const void *_b)
3641 {
3642 	const struct btf_var_secinfo *a = _a;
3643 	const struct btf_var_secinfo *b = _b;
3644 
3645 	return a->offset - b->offset;
3646 }
3647 
3648 static int btf_fixup_datasec(struct bpf_object *obj, struct btf *btf,
3649 			     struct btf_type *t)
3650 {
3651 	__u32 size = 0, i, vars = btf_vlen(t);
3652 	const char *sec_name = btf__name_by_offset(btf, t->name_off);
3653 	struct btf_var_secinfo *vsi;
3654 	bool fixup_offsets = false;
3655 	int err;
3656 
3657 	if (!sec_name) {
3658 		pr_debug("No name found in string section for DATASEC kind.\n");
3659 		return -ENOENT;
3660 	}
3661 
3662 	/* Extern-backing datasecs (.ksyms, .kconfig) have their size and
3663 	 * variable offsets set at the previous step. Further, not every
3664 	 * extern BTF VAR has corresponding ELF symbol preserved, so we skip
3665 	 * all fixups altogether for such sections and go straight to sorting
3666 	 * VARs within their DATASEC.
3667 	 */
3668 	if (strcmp(sec_name, KCONFIG_SEC) == 0 || strcmp(sec_name, KSYMS_SEC) == 0)
3669 		goto sort_vars;
3670 
3671 	/* Clang leaves DATASEC size and VAR offsets as zeroes, so we need to
3672 	 * fix this up. But BPF static linker already fixes this up and fills
3673 	 * all the sizes and offsets during static linking. So this step has
3674 	 * to be optional. But the STV_HIDDEN handling is non-optional for any
3675 	 * non-extern DATASEC, so the variable fixup loop below handles both
3676 	 * functions at the same time, paying the cost of BTF VAR <-> ELF
3677 	 * symbol matching just once.
3678 	 */
3679 	if (t->size == 0) {
3680 		err = find_elf_sec_sz(obj, sec_name, &size);
3681 		if (err || !size) {
3682 			pr_debug("sec '%s': failed to determine size from ELF: size %u, err %s\n",
3683 				 sec_name, size, errstr(err));
3684 			return -ENOENT;
3685 		}
3686 
3687 		t->size = size;
3688 		fixup_offsets = true;
3689 	}
3690 
3691 	for (i = 0, vsi = btf_var_secinfos(t); i < vars; i++, vsi++) {
3692 		const struct btf_type *t_var;
3693 		struct btf_var *var;
3694 		const char *var_name;
3695 		Elf64_Sym *sym;
3696 
3697 		t_var = btf__type_by_id(btf, vsi->type);
3698 		if (!t_var || !btf_is_var(t_var)) {
3699 			pr_debug("sec '%s': unexpected non-VAR type found\n", sec_name);
3700 			return -EINVAL;
3701 		}
3702 
3703 		var = btf_var(t_var);
3704 		if (var->linkage == BTF_VAR_STATIC || var->linkage == BTF_VAR_GLOBAL_EXTERN)
3705 			continue;
3706 
3707 		var_name = btf__name_by_offset(btf, t_var->name_off);
3708 		if (!var_name) {
3709 			pr_debug("sec '%s': failed to find name of DATASEC's member #%u\n",
3710 				 sec_name, i);
3711 			return -ENOENT;
3712 		}
3713 
3714 		sym = find_elf_var_sym(obj, var_name);
3715 		if (IS_ERR(sym)) {
3716 			pr_debug("sec '%s': failed to find ELF symbol for VAR '%s'\n",
3717 				 sec_name, var_name);
3718 			return -ENOENT;
3719 		}
3720 
3721 		if (fixup_offsets)
3722 			vsi->offset = sym->st_value;
3723 
3724 		/* if variable is a global/weak symbol, but has restricted
3725 		 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF VAR
3726 		 * as static. This follows similar logic for functions (BPF
3727 		 * subprogs) and influences libbpf's further decisions about
3728 		 * whether to make global data BPF array maps as
3729 		 * BPF_F_MMAPABLE.
3730 		 */
3731 		if (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
3732 		    || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL)
3733 			var->linkage = BTF_VAR_STATIC;
3734 	}
3735 
3736 sort_vars:
3737 	qsort(btf_var_secinfos(t), vars, sizeof(*vsi), compare_vsi_off);
3738 	return 0;
3739 }
3740 
3741 static int bpf_object_fixup_btf(struct bpf_object *obj)
3742 {
3743 	int i, n, err = 0;
3744 
3745 	if (!obj->btf)
3746 		return 0;
3747 
3748 	n = btf__type_cnt(obj->btf);
3749 	for (i = 1; i < n; i++) {
3750 		struct btf_type *t = btf_type_by_id(obj->btf, i);
3751 
3752 		/* Loader needs to fix up some of the things compiler
3753 		 * couldn't get its hands on while emitting BTF. This
3754 		 * is section size and global variable offset. We use
3755 		 * the info from the ELF itself for this purpose.
3756 		 */
3757 		if (btf_is_datasec(t)) {
3758 			err = btf_fixup_datasec(obj, obj->btf, t);
3759 			if (err)
3760 				return err;
3761 		}
3762 	}
3763 
3764 	return 0;
3765 }
3766 
3767 static bool prog_needs_vmlinux_btf(struct bpf_program *prog)
3768 {
3769 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
3770 	    prog->type == BPF_PROG_TYPE_LSM)
3771 		return true;
3772 
3773 	/* BPF_PROG_TYPE_TRACING programs which do not attach to other programs
3774 	 * also need vmlinux BTF
3775 	 */
3776 	if (prog->type == BPF_PROG_TYPE_TRACING && !prog->attach_prog_fd)
3777 		return true;
3778 
3779 	return false;
3780 }
3781 
3782 static bool map_needs_vmlinux_btf(struct bpf_map *map)
3783 {
3784 	return bpf_map__is_struct_ops(map);
3785 }
3786 
3787 static bool obj_needs_vmlinux_btf(const struct bpf_object *obj)
3788 {
3789 	struct bpf_program *prog;
3790 	struct bpf_map *map;
3791 	int i;
3792 
3793 	/* CO-RE relocations need kernel BTF, only when btf_custom_path
3794 	 * is not specified
3795 	 */
3796 	if (obj->btf_ext && obj->btf_ext->core_relo_info.len && !obj->btf_custom_path)
3797 		return true;
3798 
3799 	/* Support for typed ksyms needs kernel BTF */
3800 	for (i = 0; i < obj->nr_extern; i++) {
3801 		const struct extern_desc *ext;
3802 
3803 		ext = &obj->externs[i];
3804 		if (ext->type == EXT_KSYM && ext->ksym.type_id)
3805 			return true;
3806 	}
3807 
3808 	bpf_object__for_each_program(prog, obj) {
3809 		if (!prog->autoload)
3810 			continue;
3811 		if (prog_needs_vmlinux_btf(prog))
3812 			return true;
3813 	}
3814 
3815 	bpf_object__for_each_map(map, obj) {
3816 		if (map_needs_vmlinux_btf(map))
3817 			return true;
3818 	}
3819 
3820 	return false;
3821 }
3822 
3823 static int bpf_object__load_vmlinux_btf(struct bpf_object *obj, bool force)
3824 {
3825 	int err;
3826 
3827 	/* btf_vmlinux could be loaded earlier */
3828 	if (obj->btf_vmlinux || obj->gen_loader)
3829 		return 0;
3830 
3831 	if (!force && !obj_needs_vmlinux_btf(obj))
3832 		return 0;
3833 
3834 	obj->btf_vmlinux = btf__load_vmlinux_btf();
3835 	err = libbpf_get_error(obj->btf_vmlinux);
3836 	if (err) {
3837 		pr_warn("Error loading vmlinux BTF: %s\n", errstr(err));
3838 		obj->btf_vmlinux = NULL;
3839 		return err;
3840 	}
3841 	return 0;
3842 }
3843 
3844 static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
3845 {
3846 	struct btf *kern_btf = obj->btf;
3847 	bool btf_mandatory, sanitize;
3848 	int i, err = 0;
3849 
3850 	if (!obj->btf)
3851 		return 0;
3852 
3853 	if (!kernel_supports(obj, FEAT_BTF)) {
3854 		if (kernel_needs_btf(obj)) {
3855 			err = -EOPNOTSUPP;
3856 			goto report;
3857 		}
3858 		pr_debug("Kernel doesn't support BTF, skipping uploading it.\n");
3859 		return 0;
3860 	}
3861 
3862 	/* Even though some subprogs are global/weak, user might prefer more
3863 	 * permissive BPF verification process that BPF verifier performs for
3864 	 * static functions, taking into account more context from the caller
3865 	 * functions. In such case, they need to mark such subprogs with
3866 	 * __attribute__((visibility("hidden"))) and libbpf will adjust
3867 	 * corresponding FUNC BTF type to be marked as static and trigger more
3868 	 * involved BPF verification process.
3869 	 */
3870 	for (i = 0; i < obj->nr_programs; i++) {
3871 		struct bpf_program *prog = &obj->programs[i];
3872 		struct btf_type *t;
3873 		const char *name;
3874 		int j, n;
3875 
3876 		if (!prog->mark_btf_static || !prog_is_subprog(obj, prog))
3877 			continue;
3878 
3879 		n = btf__type_cnt(obj->btf);
3880 		for (j = 1; j < n; j++) {
3881 			t = btf_type_by_id(obj->btf, j);
3882 			if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL)
3883 				continue;
3884 
3885 			name = btf__str_by_offset(obj->btf, t->name_off);
3886 			if (strcmp(name, prog->name) != 0)
3887 				continue;
3888 
3889 			t->info = btf_type_info(BTF_KIND_FUNC, BTF_FUNC_STATIC, 0);
3890 			break;
3891 		}
3892 	}
3893 
3894 	sanitize = btf_needs_sanitization(obj);
3895 	if (sanitize) {
3896 		kern_btf = bpf_object__sanitize_btf(obj, obj->btf);
3897 		if (IS_ERR(kern_btf))
3898 			return PTR_ERR(kern_btf);
3899 	}
3900 
3901 	if (obj->gen_loader) {
3902 		__u32 raw_size = 0;
3903 		const void *raw_data = btf__raw_data(kern_btf, &raw_size);
3904 
3905 		if (!raw_data)
3906 			return -ENOMEM;
3907 		bpf_gen__load_btf(obj->gen_loader, raw_data, raw_size);
3908 		/* Pretend to have valid FD to pass various fd >= 0 checks.
3909 		 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
3910 		 */
3911 		btf__set_fd(kern_btf, 0);
3912 	} else {
3913 		/* currently BPF_BTF_LOAD only supports log_level 1 */
3914 		err = btf_load_into_kernel(kern_btf, obj->log_buf, obj->log_size,
3915 					   obj->log_level ? 1 : 0, obj->token_fd);
3916 	}
3917 	if (sanitize) {
3918 		if (!err) {
3919 			/* move fd to libbpf's BTF */
3920 			btf__set_fd(obj->btf, btf__fd(kern_btf));
3921 			btf__set_fd(kern_btf, -1);
3922 		}
3923 		btf__free(kern_btf);
3924 	}
3925 report:
3926 	if (err) {
3927 		btf_mandatory = kernel_needs_btf(obj);
3928 		if (btf_mandatory) {
3929 			pr_warn("Error loading .BTF into kernel: %s. BTF is mandatory, can't proceed.\n",
3930 				errstr(err));
3931 		} else {
3932 			pr_info("Error loading .BTF into kernel: %s. BTF is optional, ignoring.\n",
3933 				errstr(err));
3934 			err = 0;
3935 		}
3936 	}
3937 	return err;
3938 }
3939 
3940 static const char *elf_sym_str(const struct bpf_object *obj, size_t off)
3941 {
3942 	const char *name;
3943 
3944 	name = elf_strptr(obj->efile.elf, obj->efile.strtabidx, off);
3945 	if (!name) {
3946 		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3947 			off, obj->path, elf_errmsg(-1));
3948 		return NULL;
3949 	}
3950 
3951 	return name;
3952 }
3953 
3954 static const char *elf_sec_str(const struct bpf_object *obj, size_t off)
3955 {
3956 	const char *name;
3957 
3958 	name = elf_strptr(obj->efile.elf, obj->efile.shstrndx, off);
3959 	if (!name) {
3960 		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3961 			off, obj->path, elf_errmsg(-1));
3962 		return NULL;
3963 	}
3964 
3965 	return name;
3966 }
3967 
3968 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx)
3969 {
3970 	Elf_Scn *scn;
3971 
3972 	scn = elf_getscn(obj->efile.elf, idx);
3973 	if (!scn) {
3974 		pr_warn("elf: failed to get section(%zu) from %s: %s\n",
3975 			idx, obj->path, elf_errmsg(-1));
3976 		return NULL;
3977 	}
3978 	return scn;
3979 }
3980 
3981 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name)
3982 {
3983 	Elf_Scn *scn = NULL;
3984 	Elf *elf = obj->efile.elf;
3985 	const char *sec_name;
3986 
3987 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3988 		sec_name = elf_sec_name(obj, scn);
3989 		if (!sec_name)
3990 			return NULL;
3991 
3992 		if (strcmp(sec_name, name) != 0)
3993 			continue;
3994 
3995 		return scn;
3996 	}
3997 	return NULL;
3998 }
3999 
4000 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn)
4001 {
4002 	Elf64_Shdr *shdr;
4003 
4004 	if (!scn)
4005 		return NULL;
4006 
4007 	shdr = elf64_getshdr(scn);
4008 	if (!shdr) {
4009 		pr_warn("elf: failed to get section(%zu) header from %s: %s\n",
4010 			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
4011 		return NULL;
4012 	}
4013 
4014 	return shdr;
4015 }
4016 
4017 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn)
4018 {
4019 	const char *name;
4020 	Elf64_Shdr *sh;
4021 
4022 	if (!scn)
4023 		return NULL;
4024 
4025 	sh = elf_sec_hdr(obj, scn);
4026 	if (!sh)
4027 		return NULL;
4028 
4029 	name = elf_sec_str(obj, sh->sh_name);
4030 	if (!name) {
4031 		pr_warn("elf: failed to get section(%zu) name from %s: %s\n",
4032 			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
4033 		return NULL;
4034 	}
4035 
4036 	return name;
4037 }
4038 
4039 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn)
4040 {
4041 	Elf_Data *data;
4042 
4043 	if (!scn)
4044 		return NULL;
4045 
4046 	data = elf_getdata(scn, 0);
4047 	if (!data) {
4048 		pr_warn("elf: failed to get section(%zu) %s data from %s: %s\n",
4049 			elf_ndxscn(scn), elf_sec_name(obj, scn) ?: "<?>",
4050 			obj->path, elf_errmsg(-1));
4051 		return NULL;
4052 	}
4053 
4054 	return data;
4055 }
4056 
4057 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx)
4058 {
4059 	if (idx >= obj->efile.symbols->d_size / sizeof(Elf64_Sym))
4060 		return NULL;
4061 
4062 	return (Elf64_Sym *)obj->efile.symbols->d_buf + idx;
4063 }
4064 
4065 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx)
4066 {
4067 	if (idx >= data->d_size / sizeof(Elf64_Rel))
4068 		return NULL;
4069 
4070 	return (Elf64_Rel *)data->d_buf + idx;
4071 }
4072 
4073 static bool is_sec_name_dwarf(const char *name)
4074 {
4075 	/* approximation, but the actual list is too long */
4076 	return str_has_pfx(name, ".debug_");
4077 }
4078 
4079 static bool ignore_elf_section(Elf64_Shdr *hdr, const char *name)
4080 {
4081 	/* no special handling of .strtab */
4082 	if (hdr->sh_type == SHT_STRTAB)
4083 		return true;
4084 
4085 	/* ignore .llvm_addrsig section as well */
4086 	if (hdr->sh_type == SHT_LLVM_ADDRSIG)
4087 		return true;
4088 
4089 	/* no subprograms will lead to an empty .text section, ignore it */
4090 	if (hdr->sh_type == SHT_PROGBITS && hdr->sh_size == 0 &&
4091 	    strcmp(name, ".text") == 0)
4092 		return true;
4093 
4094 	/* DWARF sections */
4095 	if (is_sec_name_dwarf(name))
4096 		return true;
4097 
4098 	if (str_has_pfx(name, ".rel")) {
4099 		name += sizeof(".rel") - 1;
4100 		/* DWARF section relocations */
4101 		if (is_sec_name_dwarf(name))
4102 			return true;
4103 
4104 		/* .BTF and .BTF.ext don't need relocations */
4105 		if (strcmp(name, BTF_ELF_SEC) == 0 ||
4106 		    strcmp(name, BTF_EXT_ELF_SEC) == 0)
4107 			return true;
4108 	}
4109 
4110 	return false;
4111 }
4112 
4113 static int cmp_progs(const void *_a, const void *_b)
4114 {
4115 	const struct bpf_program *a = _a;
4116 	const struct bpf_program *b = _b;
4117 
4118 	if (a->sec_idx != b->sec_idx)
4119 		return a->sec_idx < b->sec_idx ? -1 : 1;
4120 
4121 	/* sec_insn_off can't be the same within the section */
4122 	return a->sec_insn_off < b->sec_insn_off ? -1 : 1;
4123 }
4124 
4125 static int bpf_object__elf_collect(struct bpf_object *obj)
4126 {
4127 	struct elf_sec_desc *sec_desc;
4128 	Elf *elf = obj->efile.elf;
4129 	Elf_Data *btf_ext_data = NULL;
4130 	Elf_Data *btf_data = NULL;
4131 	int idx = 0, err = 0;
4132 	const char *name;
4133 	Elf_Data *data;
4134 	Elf_Scn *scn;
4135 	Elf64_Shdr *sh;
4136 
4137 	/* ELF section indices are 0-based, but sec #0 is special "invalid"
4138 	 * section. Since section count retrieved by elf_getshdrnum() does
4139 	 * include sec #0, it is already the necessary size of an array to keep
4140 	 * all the sections.
4141 	 */
4142 	if (elf_getshdrnum(obj->efile.elf, &obj->efile.sec_cnt)) {
4143 		pr_warn("elf: failed to get the number of sections for %s: %s\n",
4144 			obj->path, elf_errmsg(-1));
4145 		return -LIBBPF_ERRNO__FORMAT;
4146 	}
4147 	obj->efile.secs = calloc(obj->efile.sec_cnt, sizeof(*obj->efile.secs));
4148 	if (!obj->efile.secs)
4149 		return -ENOMEM;
4150 
4151 	/* a bunch of ELF parsing functionality depends on processing symbols,
4152 	 * so do the first pass and find the symbol table
4153 	 */
4154 	scn = NULL;
4155 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
4156 		sh = elf_sec_hdr(obj, scn);
4157 		if (!sh)
4158 			return -LIBBPF_ERRNO__FORMAT;
4159 
4160 		/* the second pass has to know it when it sees relocations of data */
4161 		name = elf_sec_str(obj, sh->sh_name);
4162 		if (name && strcmp(name, ARENA_DATA_SEC) == 0)
4163 			obj->data_in_arena = true;
4164 
4165 		if (sh->sh_type == SHT_SYMTAB) {
4166 			if (obj->efile.symbols) {
4167 				pr_warn("elf: multiple symbol tables in %s\n", obj->path);
4168 				return -LIBBPF_ERRNO__FORMAT;
4169 			}
4170 
4171 			data = elf_sec_data(obj, scn);
4172 			if (!data)
4173 				return -LIBBPF_ERRNO__FORMAT;
4174 
4175 			idx = elf_ndxscn(scn);
4176 
4177 			obj->efile.symbols = data;
4178 			obj->efile.symbols_shndx = idx;
4179 			obj->efile.strtabidx = sh->sh_link;
4180 		}
4181 	}
4182 
4183 	if (!obj->efile.symbols) {
4184 		pr_warn("elf: couldn't find symbol table in %s, stripped object file?\n",
4185 			obj->path);
4186 		return -ENOENT;
4187 	}
4188 
4189 	scn = NULL;
4190 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
4191 		idx = elf_ndxscn(scn);
4192 		sec_desc = &obj->efile.secs[idx];
4193 
4194 		sh = elf_sec_hdr(obj, scn);
4195 		if (!sh)
4196 			return -LIBBPF_ERRNO__FORMAT;
4197 
4198 		name = elf_sec_str(obj, sh->sh_name);
4199 		if (!name)
4200 			return -LIBBPF_ERRNO__FORMAT;
4201 
4202 		if (ignore_elf_section(sh, name))
4203 			continue;
4204 
4205 		data = elf_sec_data(obj, scn);
4206 		if (!data)
4207 			return -LIBBPF_ERRNO__FORMAT;
4208 
4209 		pr_debug("elf: section(%d) %s, size %lu, link %d, flags %lx, type=%d\n",
4210 			 idx, name, (unsigned long)data->d_size,
4211 			 (int)sh->sh_link, (unsigned long)sh->sh_flags,
4212 			 (int)sh->sh_type);
4213 
4214 		if (strcmp(name, "license") == 0) {
4215 			err = bpf_object__init_license(obj, data->d_buf, data->d_size);
4216 			if (err)
4217 				return err;
4218 		} else if (strcmp(name, "version") == 0) {
4219 			err = bpf_object__init_kversion(obj, data->d_buf, data->d_size);
4220 			if (err)
4221 				return err;
4222 		} else if (strcmp(name, "maps") == 0) {
4223 			pr_warn("elf: legacy map definitions in 'maps' section are not supported by libbpf v1.0+\n");
4224 			return -ENOTSUP;
4225 		} else if (strcmp(name, MAPS_ELF_SEC) == 0) {
4226 			obj->efile.btf_maps_shndx = idx;
4227 		} else if (strcmp(name, BTF_ELF_SEC) == 0) {
4228 			if (sh->sh_type != SHT_PROGBITS)
4229 				return -LIBBPF_ERRNO__FORMAT;
4230 			btf_data = data;
4231 		} else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
4232 			if (sh->sh_type != SHT_PROGBITS)
4233 				return -LIBBPF_ERRNO__FORMAT;
4234 			btf_ext_data = data;
4235 		} else if (sh->sh_type == SHT_SYMTAB) {
4236 			/* already processed during the first pass above */
4237 		} else if (sh->sh_type == SHT_PROGBITS && data->d_size > 0) {
4238 			if (sh->sh_flags & SHF_EXECINSTR) {
4239 				if (strcmp(name, ".text") == 0)
4240 					obj->efile.text_shndx = idx;
4241 				err = bpf_object__add_programs(obj, data, name, idx);
4242 				if (err)
4243 					return err;
4244 			} else if (strcmp(name, DATA_REL_RO_SEC) == 0 ||
4245 				   str_has_pfx(name, DATA_REL_RO_SEC ".")) {
4246 				/*
4247 				 * Constants with pointers in them, e.g. vtables,
4248 				 * that position independent code keeps here to
4249 				 * have them relocated. There is nothing that
4250 				 * writes to it after that.
4251 				 */
4252 				sec_desc->sec_type = SEC_RODATA;
4253 				sec_desc->shdr = sh;
4254 				sec_desc->data = data;
4255 			} else if (strcmp(name, DATA_SEC) == 0 ||
4256 				   str_has_pfx(name, DATA_SEC ".")) {
4257 				sec_desc->sec_type = SEC_DATA;
4258 				sec_desc->shdr = sh;
4259 				sec_desc->data = data;
4260 			} else if (strcmp(name, RODATA_SEC) == 0 ||
4261 				   str_has_pfx(name, RODATA_SEC ".")) {
4262 				sec_desc->sec_type = SEC_RODATA;
4263 				sec_desc->shdr = sh;
4264 				sec_desc->data = data;
4265 			} else if (strcmp(name, PERCPU_SEC) == 0 ||
4266 				   str_has_pfx(name, PERCPU_SEC ".")) {
4267 				sec_desc->sec_type = SEC_PERCPU;
4268 				sec_desc->shdr = sh;
4269 				sec_desc->data = data;
4270 			} else if (strcmp(name, STRUCT_OPS_SEC) == 0 ||
4271 				   strcmp(name, STRUCT_OPS_LINK_SEC) == 0 ||
4272 				   strcmp(name, "?" STRUCT_OPS_SEC) == 0 ||
4273 				   strcmp(name, "?" STRUCT_OPS_LINK_SEC) == 0) {
4274 				sec_desc->sec_type = SEC_ST_OPS;
4275 				sec_desc->shdr = sh;
4276 				sec_desc->data = data;
4277 				obj->efile.has_st_ops = true;
4278 			} else if (strcmp(name, ARENA_SEC) == 0) {
4279 				obj->efile.arena_data = data;
4280 				obj->efile.arena_data_shndx = idx;
4281 			} else if (strcmp(name, ARENA_DATA_SEC) == 0) {
4282 				/* the marker, see the first pass */
4283 			} else if (strcmp(name, JUMPTABLES_SEC) == 0) {
4284 				obj->jumptables_data = malloc(data->d_size);
4285 				if (!obj->jumptables_data)
4286 					return -ENOMEM;
4287 				memcpy(obj->jumptables_data, data->d_buf, data->d_size);
4288 				obj->jumptables_data_sz = data->d_size;
4289 				obj->efile.jumptables_data_shndx = idx;
4290 			} else {
4291 				pr_info("elf: skipping unrecognized data section(%d) %s\n",
4292 					idx, name);
4293 			}
4294 		} else if (sh->sh_type == SHT_REL) {
4295 			int targ_sec_idx = sh->sh_info; /* points to other section */
4296 
4297 			if (sh->sh_entsize != sizeof(Elf64_Rel) ||
4298 			    targ_sec_idx >= obj->efile.sec_cnt)
4299 				return -LIBBPF_ERRNO__FORMAT;
4300 
4301 			/*
4302 			 * Only do relo for section with exec instructions,
4303 			 * struct_ops, maps, and read-only data that might
4304 			 * have pointers to functions.
4305 			 */
4306 			if (!section_have_execinstr(obj, targ_sec_idx) &&
4307 			    !(obj->data_in_arena &&
4308 			      (!strcmp(name, ".rel" DATA_SEC) ||
4309 			       str_has_pfx(name, ".rel" DATA_SEC "."))) &&
4310 			    strcmp(name, ".rel" RODATA_SEC) &&
4311 			    !str_has_pfx(name, ".rel" RODATA_SEC ".") &&
4312 			    strcmp(name, ".rel" DATA_REL_RO_SEC) &&
4313 			    !str_has_pfx(name, ".rel" DATA_REL_RO_SEC ".") &&
4314 			    strcmp(name, ".rel" STRUCT_OPS_SEC) &&
4315 			    strcmp(name, ".rel" STRUCT_OPS_LINK_SEC) &&
4316 			    strcmp(name, ".rel?" STRUCT_OPS_SEC) &&
4317 			    strcmp(name, ".rel?" STRUCT_OPS_LINK_SEC) &&
4318 			    strcmp(name, ".rel" MAPS_ELF_SEC)) {
4319 				pr_info("elf: skipping relo section(%d) %s for section(%d) %s\n",
4320 					idx, name, targ_sec_idx,
4321 					elf_sec_name(obj, elf_sec_by_idx(obj, targ_sec_idx)) ?: "<?>");
4322 				continue;
4323 			}
4324 
4325 			sec_desc->sec_type = SEC_RELO;
4326 			sec_desc->shdr = sh;
4327 			sec_desc->data = data;
4328 		} else if (sh->sh_type == SHT_NOBITS && (strcmp(name, BSS_SEC) == 0 ||
4329 							 str_has_pfx(name, BSS_SEC "."))) {
4330 			sec_desc->sec_type = SEC_BSS;
4331 			sec_desc->shdr = sh;
4332 			sec_desc->data = data;
4333 		} else {
4334 			pr_info("elf: skipping section(%d) %s (size %zu)\n", idx, name,
4335 				(size_t)sh->sh_size);
4336 		}
4337 	}
4338 
4339 	if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) {
4340 		pr_warn("elf: symbol strings section missing or invalid in %s\n", obj->path);
4341 		return -LIBBPF_ERRNO__FORMAT;
4342 	}
4343 
4344 	/* change BPF program insns to native endianness for introspection */
4345 	if (!is_native_endianness(obj))
4346 		bpf_object_bswap_progs(obj);
4347 
4348 	/* sort BPF programs by section name and in-section instruction offset
4349 	 * for faster search
4350 	 */
4351 	if (obj->nr_programs)
4352 		qsort(obj->programs, obj->nr_programs, sizeof(*obj->programs), cmp_progs);
4353 
4354 	return bpf_object__init_btf(obj, btf_data, btf_ext_data);
4355 }
4356 
4357 static bool sym_is_extern(const Elf64_Sym *sym)
4358 {
4359 	int bind = ELF64_ST_BIND(sym->st_info);
4360 	/* externs are symbols w/ type=NOTYPE, bind=GLOBAL|WEAK, section=UND */
4361 	return sym->st_shndx == SHN_UNDEF &&
4362 	       (bind == STB_GLOBAL || bind == STB_WEAK) &&
4363 	       ELF64_ST_TYPE(sym->st_info) == STT_NOTYPE;
4364 }
4365 
4366 static bool sym_is_subprog(const Elf64_Sym *sym, int text_shndx)
4367 {
4368 	int bind = ELF64_ST_BIND(sym->st_info);
4369 	int type = ELF64_ST_TYPE(sym->st_info);
4370 
4371 	/* in .text section */
4372 	if (sym->st_shndx != text_shndx)
4373 		return false;
4374 
4375 	/* local function */
4376 	if (bind == STB_LOCAL && type == STT_SECTION)
4377 		return true;
4378 
4379 	/* global function */
4380 	return (bind == STB_GLOBAL || bind == STB_WEAK) && type == STT_FUNC;
4381 }
4382 
4383 static int find_extern_btf_id(const struct btf *btf, const char *ext_name)
4384 {
4385 	const struct btf_type *t;
4386 	const char *tname;
4387 	int i, n;
4388 
4389 	if (!btf)
4390 		return -ESRCH;
4391 
4392 	n = btf__type_cnt(btf);
4393 	for (i = 1; i < n; i++) {
4394 		t = btf__type_by_id(btf, i);
4395 
4396 		if (!btf_is_var(t) && !btf_is_func(t))
4397 			continue;
4398 
4399 		tname = btf__name_by_offset(btf, t->name_off);
4400 		if (strcmp(tname, ext_name))
4401 			continue;
4402 
4403 		if (btf_is_var(t) &&
4404 		    btf_var(t)->linkage != BTF_VAR_GLOBAL_EXTERN)
4405 			return -EINVAL;
4406 
4407 		if (btf_is_func(t) && btf_func_linkage(t) != BTF_FUNC_EXTERN)
4408 			return -EINVAL;
4409 
4410 		return i;
4411 	}
4412 
4413 	return -ENOENT;
4414 }
4415 
4416 static int find_extern_sec_btf_id(struct btf *btf, int ext_btf_id) {
4417 	const struct btf_var_secinfo *vs;
4418 	const struct btf_type *t;
4419 	int i, j, n;
4420 
4421 	if (!btf)
4422 		return -ESRCH;
4423 
4424 	n = btf__type_cnt(btf);
4425 	for (i = 1; i < n; i++) {
4426 		t = btf__type_by_id(btf, i);
4427 
4428 		if (!btf_is_datasec(t))
4429 			continue;
4430 
4431 		vs = btf_var_secinfos(t);
4432 		for (j = 0; j < btf_vlen(t); j++, vs++) {
4433 			if (vs->type == ext_btf_id)
4434 				return i;
4435 		}
4436 	}
4437 
4438 	return -ENOENT;
4439 }
4440 
4441 static enum kcfg_type find_kcfg_type(const struct btf *btf, int id,
4442 				     bool *is_signed)
4443 {
4444 	const struct btf_type *t;
4445 	const char *name;
4446 
4447 	t = skip_mods_and_typedefs(btf, id, NULL);
4448 	name = btf__name_by_offset(btf, t->name_off);
4449 
4450 	if (is_signed)
4451 		*is_signed = false;
4452 	switch (btf_kind(t)) {
4453 	case BTF_KIND_INT: {
4454 		int enc = btf_int_encoding(t);
4455 
4456 		if (enc & BTF_INT_BOOL)
4457 			return t->size == 1 ? KCFG_BOOL : KCFG_UNKNOWN;
4458 		if (is_signed)
4459 			*is_signed = enc & BTF_INT_SIGNED;
4460 		if (t->size == 1)
4461 			return KCFG_CHAR;
4462 		if (t->size < 1 || t->size > 8 || (t->size & (t->size - 1)))
4463 			return KCFG_UNKNOWN;
4464 		return KCFG_INT;
4465 	}
4466 	case BTF_KIND_ENUM:
4467 		if (t->size != 4)
4468 			return KCFG_UNKNOWN;
4469 		if (strcmp(name, "libbpf_tristate"))
4470 			return KCFG_UNKNOWN;
4471 		return KCFG_TRISTATE;
4472 	case BTF_KIND_ENUM64:
4473 		if (strcmp(name, "libbpf_tristate"))
4474 			return KCFG_UNKNOWN;
4475 		return KCFG_TRISTATE;
4476 	case BTF_KIND_ARRAY:
4477 		if (btf_array(t)->nelems == 0)
4478 			return KCFG_UNKNOWN;
4479 		if (find_kcfg_type(btf, btf_array(t)->type, NULL) != KCFG_CHAR)
4480 			return KCFG_UNKNOWN;
4481 		return KCFG_CHAR_ARR;
4482 	default:
4483 		return KCFG_UNKNOWN;
4484 	}
4485 }
4486 
4487 static int cmp_externs(const void *_a, const void *_b)
4488 {
4489 	const struct extern_desc *a = _a;
4490 	const struct extern_desc *b = _b;
4491 
4492 	if (a->type != b->type)
4493 		return a->type < b->type ? -1 : 1;
4494 
4495 	if (a->type == EXT_KCFG) {
4496 		/* descending order by alignment requirements */
4497 		if (a->kcfg.align != b->kcfg.align)
4498 			return a->kcfg.align > b->kcfg.align ? -1 : 1;
4499 		/* ascending order by size, within same alignment class */
4500 		if (a->kcfg.sz != b->kcfg.sz)
4501 			return a->kcfg.sz < b->kcfg.sz ? -1 : 1;
4502 	}
4503 
4504 	/* resolve ties by name */
4505 	return strcmp(a->name, b->name);
4506 }
4507 
4508 static int find_int_btf_id(const struct btf *btf)
4509 {
4510 	const struct btf_type *t;
4511 	int i, n;
4512 
4513 	n = btf__type_cnt(btf);
4514 	for (i = 1; i < n; i++) {
4515 		t = btf__type_by_id(btf, i);
4516 
4517 		if (btf_is_int(t) && btf_int_bits(t) == 32)
4518 			return i;
4519 	}
4520 
4521 	return 0;
4522 }
4523 
4524 static int add_dummy_ksym_var(struct btf *btf)
4525 {
4526 	int i, int_btf_id, sec_btf_id, dummy_var_btf_id;
4527 	const struct btf_var_secinfo *vs;
4528 	const struct btf_type *sec;
4529 
4530 	if (!btf)
4531 		return 0;
4532 
4533 	sec_btf_id = btf__find_by_name_kind(btf, KSYMS_SEC,
4534 					    BTF_KIND_DATASEC);
4535 	if (sec_btf_id < 0)
4536 		return 0;
4537 
4538 	sec = btf__type_by_id(btf, sec_btf_id);
4539 	vs = btf_var_secinfos(sec);
4540 	for (i = 0; i < btf_vlen(sec); i++, vs++) {
4541 		const struct btf_type *vt;
4542 
4543 		vt = btf__type_by_id(btf, vs->type);
4544 		if (btf_is_func(vt))
4545 			break;
4546 	}
4547 
4548 	/* No func in ksyms sec.  No need to add dummy var. */
4549 	if (i == btf_vlen(sec))
4550 		return 0;
4551 
4552 	int_btf_id = find_int_btf_id(btf);
4553 	dummy_var_btf_id = btf__add_var(btf,
4554 					"dummy_ksym",
4555 					BTF_VAR_GLOBAL_ALLOCATED,
4556 					int_btf_id);
4557 	if (dummy_var_btf_id < 0)
4558 		pr_warn("cannot create a dummy_ksym var\n");
4559 
4560 	return dummy_var_btf_id;
4561 }
4562 
4563 static int bpf_object__collect_externs(struct bpf_object *obj)
4564 {
4565 	struct btf_type *sec, *kcfg_sec = NULL, *ksym_sec = NULL;
4566 	const struct btf_type *t;
4567 	struct extern_desc *ext;
4568 	int i, n, off, dummy_var_btf_id;
4569 	const char *ext_name, *sec_name;
4570 	size_t ext_essent_len;
4571 	Elf_Scn *scn;
4572 	Elf64_Shdr *sh;
4573 
4574 	if (!obj->efile.symbols)
4575 		return 0;
4576 
4577 	scn = elf_sec_by_idx(obj, obj->efile.symbols_shndx);
4578 	sh = elf_sec_hdr(obj, scn);
4579 	if (!sh || sh->sh_entsize != sizeof(Elf64_Sym))
4580 		return -LIBBPF_ERRNO__FORMAT;
4581 
4582 	dummy_var_btf_id = add_dummy_ksym_var(obj->btf);
4583 	if (dummy_var_btf_id < 0)
4584 		return dummy_var_btf_id;
4585 
4586 	n = sh->sh_size / sh->sh_entsize;
4587 	pr_debug("looking for externs among %d symbols...\n", n);
4588 
4589 	for (i = 0; i < n; i++) {
4590 		Elf64_Sym *sym = elf_sym_by_idx(obj, i);
4591 
4592 		if (!sym)
4593 			return -LIBBPF_ERRNO__FORMAT;
4594 		if (!sym_is_extern(sym))
4595 			continue;
4596 		ext_name = elf_sym_str(obj, sym->st_name);
4597 		if (str_is_empty(ext_name))
4598 			continue;
4599 
4600 		ext = obj->externs;
4601 		ext = libbpf_reallocarray(ext, obj->nr_extern + 1, sizeof(*ext));
4602 		if (!ext)
4603 			return -ENOMEM;
4604 		obj->externs = ext;
4605 		ext = &ext[obj->nr_extern];
4606 		memset(ext, 0, sizeof(*ext));
4607 		obj->nr_extern++;
4608 
4609 		ext->btf_id = find_extern_btf_id(obj->btf, ext_name);
4610 		if (ext->btf_id <= 0) {
4611 			pr_warn("failed to find BTF for extern '%s': %d\n",
4612 				ext_name, ext->btf_id);
4613 			return ext->btf_id;
4614 		}
4615 		t = btf__type_by_id(obj->btf, ext->btf_id);
4616 		ext->name = strdup(btf__name_by_offset(obj->btf, t->name_off));
4617 		if (!ext->name)
4618 			return -ENOMEM;
4619 		ext->sym_idx = i;
4620 		ext->is_weak = ELF64_ST_BIND(sym->st_info) == STB_WEAK;
4621 
4622 		ext_essent_len = bpf_core_essential_name_len(ext->name);
4623 		ext->essent_name = NULL;
4624 		if (ext_essent_len != strlen(ext->name)) {
4625 			ext->essent_name = strndup(ext->name, ext_essent_len);
4626 			if (!ext->essent_name)
4627 				return -ENOMEM;
4628 		}
4629 
4630 		ext->sec_btf_id = find_extern_sec_btf_id(obj->btf, ext->btf_id);
4631 		if (ext->sec_btf_id <= 0) {
4632 			pr_warn("failed to find BTF for extern '%s' [%d] section: %d\n",
4633 				ext_name, ext->btf_id, ext->sec_btf_id);
4634 			return ext->sec_btf_id;
4635 		}
4636 		sec = (void *)btf__type_by_id(obj->btf, ext->sec_btf_id);
4637 		sec_name = btf__name_by_offset(obj->btf, sec->name_off);
4638 
4639 		if (strcmp(sec_name, KCONFIG_SEC) == 0) {
4640 			if (btf_is_func(t)) {
4641 				pr_warn("extern function %s is unsupported under %s section\n",
4642 					ext->name, KCONFIG_SEC);
4643 				return -ENOTSUP;
4644 			}
4645 			kcfg_sec = sec;
4646 			ext->type = EXT_KCFG;
4647 			ext->kcfg.sz = btf__resolve_size(obj->btf, t->type);
4648 			if (ext->kcfg.sz <= 0) {
4649 				pr_warn("failed to resolve size of extern (kcfg) '%s': %d\n",
4650 					ext_name, ext->kcfg.sz);
4651 				return ext->kcfg.sz;
4652 			}
4653 			ext->kcfg.align = btf__align_of(obj->btf, t->type);
4654 			if (ext->kcfg.align <= 0) {
4655 				pr_warn("failed to determine alignment of extern (kcfg) '%s': %d\n",
4656 					ext_name, ext->kcfg.align);
4657 				return -EINVAL;
4658 			}
4659 			ext->kcfg.type = find_kcfg_type(obj->btf, t->type,
4660 							&ext->kcfg.is_signed);
4661 			if (ext->kcfg.type == KCFG_UNKNOWN) {
4662 				pr_warn("extern (kcfg) '%s': type is unsupported\n", ext_name);
4663 				return -ENOTSUP;
4664 			}
4665 		} else if (strcmp(sec_name, KSYMS_SEC) == 0) {
4666 			ksym_sec = sec;
4667 			ext->type = EXT_KSYM;
4668 			skip_mods_and_typedefs(obj->btf, t->type,
4669 					       &ext->ksym.type_id);
4670 		} else {
4671 			pr_warn("unrecognized extern section '%s'\n", sec_name);
4672 			return -ENOTSUP;
4673 		}
4674 	}
4675 	pr_debug("collected %d externs total\n", obj->nr_extern);
4676 
4677 	if (!obj->nr_extern)
4678 		return 0;
4679 
4680 	/* sort externs by type, for kcfg ones also by (align, size, name) */
4681 	qsort(obj->externs, obj->nr_extern, sizeof(*ext), cmp_externs);
4682 
4683 	/* for .ksyms section, we need to turn all externs into allocated
4684 	 * variables in BTF to pass kernel verification; we do this by
4685 	 * pretending that each extern is a 8-byte variable
4686 	 */
4687 	if (ksym_sec) {
4688 		/* find existing 4-byte integer type in BTF to use for fake
4689 		 * extern variables in DATASEC
4690 		 */
4691 		int int_btf_id = find_int_btf_id(obj->btf);
4692 		/* For extern function, a dummy_var added earlier
4693 		 * will be used to replace the vs->type and
4694 		 * its name string will be used to refill
4695 		 * the missing param's name.
4696 		 */
4697 		const struct btf_type *dummy_var;
4698 
4699 		dummy_var = btf__type_by_id(obj->btf, dummy_var_btf_id);
4700 		for (i = 0; i < obj->nr_extern; i++) {
4701 			ext = &obj->externs[i];
4702 			if (ext->type != EXT_KSYM)
4703 				continue;
4704 			pr_debug("extern (ksym) #%d: symbol %d, name %s\n",
4705 				 i, ext->sym_idx, ext->name);
4706 		}
4707 
4708 		sec = ksym_sec;
4709 		n = btf_vlen(sec);
4710 		for (i = 0, off = 0; i < n; i++, off += sizeof(int)) {
4711 			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
4712 			struct btf_type *vt;
4713 
4714 			vt = (void *)btf__type_by_id(obj->btf, vs->type);
4715 			ext_name = btf__name_by_offset(obj->btf, vt->name_off);
4716 			ext = find_extern_by_name(obj, ext_name);
4717 			if (!ext) {
4718 				pr_warn("failed to find extern definition for BTF %s '%s'\n",
4719 					btf_kind_str(vt), ext_name);
4720 				return -ESRCH;
4721 			}
4722 			if (btf_is_func(vt)) {
4723 				const struct btf_type *func_proto;
4724 				struct btf_param *param;
4725 				int j;
4726 
4727 				func_proto = btf__type_by_id(obj->btf,
4728 							     vt->type);
4729 				param = btf_params(func_proto);
4730 				/* Reuse the dummy_var string if the
4731 				 * func proto does not have param name.
4732 				 */
4733 				for (j = 0; j < btf_vlen(func_proto); j++)
4734 					if (param[j].type && !param[j].name_off)
4735 						param[j].name_off =
4736 							dummy_var->name_off;
4737 				vs->type = dummy_var_btf_id;
4738 				vt->info &= ~0xffff;
4739 				vt->info |= BTF_FUNC_GLOBAL;
4740 			} else {
4741 				btf_var(vt)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
4742 				vt->type = int_btf_id;
4743 			}
4744 			vs->offset = off;
4745 			vs->size = sizeof(int);
4746 		}
4747 		sec->size = off;
4748 	}
4749 
4750 	if (kcfg_sec) {
4751 		sec = kcfg_sec;
4752 		/* for kcfg externs calculate their offsets within a .kconfig map */
4753 		off = 0;
4754 		for (i = 0; i < obj->nr_extern; i++) {
4755 			ext = &obj->externs[i];
4756 			if (ext->type != EXT_KCFG)
4757 				continue;
4758 
4759 			ext->kcfg.data_off = roundup(off, ext->kcfg.align);
4760 			off = ext->kcfg.data_off + ext->kcfg.sz;
4761 			pr_debug("extern (kcfg) #%d: symbol %d, off %d, name %s\n",
4762 				 i, ext->sym_idx, ext->kcfg.data_off, ext->name);
4763 		}
4764 		sec->size = off;
4765 		n = btf_vlen(sec);
4766 		for (i = 0; i < n; i++) {
4767 			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
4768 
4769 			t = btf__type_by_id(obj->btf, vs->type);
4770 			ext_name = btf__name_by_offset(obj->btf, t->name_off);
4771 			ext = find_extern_by_name(obj, ext_name);
4772 			if (!ext) {
4773 				pr_warn("failed to find extern definition for BTF var '%s'\n",
4774 					ext_name);
4775 				return -ESRCH;
4776 			}
4777 			btf_var(t)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
4778 			vs->offset = ext->kcfg.data_off;
4779 		}
4780 	}
4781 	return 0;
4782 }
4783 
4784 static bool prog_is_subprog(const struct bpf_object *obj, const struct bpf_program *prog)
4785 {
4786 	return prog->sec_idx == obj->efile.text_shndx;
4787 }
4788 
4789 struct bpf_program *
4790 bpf_object__find_program_by_name(const struct bpf_object *obj,
4791 				 const char *name)
4792 {
4793 	struct bpf_program *prog;
4794 
4795 	bpf_object__for_each_program(prog, obj) {
4796 		if (prog_is_subprog(obj, prog))
4797 			continue;
4798 		if (!strcmp(prog->name, name))
4799 			return prog;
4800 	}
4801 	return errno = ENOENT, NULL;
4802 }
4803 
4804 static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
4805 				      int shndx)
4806 {
4807 	switch (obj->efile.secs[shndx].sec_type) {
4808 	case SEC_BSS:
4809 	case SEC_DATA:
4810 	case SEC_RODATA:
4811 	case SEC_PERCPU:
4812 		return true;
4813 	default:
4814 		return false;
4815 	}
4816 }
4817 
4818 static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
4819 				      int shndx)
4820 {
4821 	return shndx == obj->efile.btf_maps_shndx;
4822 }
4823 
4824 static enum libbpf_map_type
4825 bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
4826 {
4827 	if (shndx == obj->efile.symbols_shndx)
4828 		return LIBBPF_MAP_KCONFIG;
4829 
4830 	switch (obj->efile.secs[shndx].sec_type) {
4831 	case SEC_BSS:
4832 		return LIBBPF_MAP_BSS;
4833 	case SEC_DATA:
4834 		return LIBBPF_MAP_DATA;
4835 	case SEC_RODATA:
4836 		return LIBBPF_MAP_RODATA;
4837 	case SEC_PERCPU:
4838 		return LIBBPF_MAP_PERCPU;
4839 	default:
4840 		return LIBBPF_MAP_UNSPEC;
4841 	}
4842 }
4843 
4844 static int bpf_prog_compute_hash(struct bpf_program *prog)
4845 {
4846 	struct bpf_insn *purged;
4847 	int i, err = 0;
4848 
4849 	purged = calloc(prog->insns_cnt, BPF_INSN_SZ);
4850 	if (!purged)
4851 		return -ENOMEM;
4852 
4853 	/* If relocations have been done, the map_fd needs to be
4854 	 * discarded for the digest calculation.
4855 	 */
4856 	for (i = 0; i < prog->insns_cnt; i++) {
4857 		purged[i] = prog->insns[i];
4858 		if (purged[i].code == (BPF_LD | BPF_IMM | BPF_DW) &&
4859 		    (purged[i].src_reg == BPF_PSEUDO_MAP_FD ||
4860 		     purged[i].src_reg == BPF_PSEUDO_MAP_VALUE)) {
4861 			purged[i].imm = 0;
4862 			i++;
4863 			if (i >= prog->insns_cnt ||
4864 			    prog->insns[i].code != 0 ||
4865 			    prog->insns[i].dst_reg != 0 ||
4866 			    prog->insns[i].src_reg != 0 ||
4867 			    prog->insns[i].off != 0) {
4868 				err = -EINVAL;
4869 				goto out;
4870 			}
4871 			purged[i] = prog->insns[i];
4872 			purged[i].imm = 0;
4873 		}
4874 	}
4875 	libbpf_sha256(purged, prog->insns_cnt * sizeof(struct bpf_insn),
4876 		      prog->hash);
4877 out:
4878 	free(purged);
4879 	return err;
4880 }
4881 
4882 static int bpf_program__record_reloc(struct bpf_program *prog,
4883 				     struct reloc_desc *reloc_desc,
4884 				     __u32 insn_idx, const char *sym_name,
4885 				     const Elf64_Sym *sym, const Elf64_Rel *rel)
4886 {
4887 	struct bpf_insn *insn = &prog->insns[insn_idx];
4888 	size_t map_idx, nr_maps = prog->obj->nr_maps;
4889 	struct bpf_object *obj = prog->obj;
4890 	__u32 shdr_idx = sym->st_shndx;
4891 	enum libbpf_map_type type;
4892 	const char *sym_sec_name;
4893 	struct bpf_map *map;
4894 
4895 	if (!is_call_insn(insn) && !is_ldimm64_insn(insn)) {
4896 		pr_warn("prog '%s': invalid relo against '%s' for insns[%u].code 0x%x\n",
4897 			prog->name, sym_name, insn_idx, insn->code);
4898 		return -LIBBPF_ERRNO__RELOC;
4899 	}
4900 
4901 	if (sym_is_extern(sym)) {
4902 		int sym_idx = ELF64_R_SYM(rel->r_info);
4903 		int i, n = obj->nr_extern;
4904 		struct extern_desc *ext;
4905 
4906 		for (i = 0; i < n; i++) {
4907 			ext = &obj->externs[i];
4908 			if (ext->sym_idx == sym_idx)
4909 				break;
4910 		}
4911 		if (i >= n) {
4912 			pr_warn("prog '%s': extern relo failed to find extern for '%s' (%d)\n",
4913 				prog->name, sym_name, sym_idx);
4914 			return -LIBBPF_ERRNO__RELOC;
4915 		}
4916 		pr_debug("prog '%s': found extern #%d '%s' (sym %d) for insn #%u\n",
4917 			 prog->name, i, ext->name, ext->sym_idx, insn_idx);
4918 		if (insn->code == (BPF_JMP | BPF_CALL))
4919 			reloc_desc->type = RELO_EXTERN_CALL;
4920 		else
4921 			reloc_desc->type = RELO_EXTERN_LD64;
4922 		reloc_desc->insn_idx = insn_idx;
4923 		reloc_desc->ext_idx = i;
4924 		return 0;
4925 	}
4926 
4927 	/* sub-program call relocation */
4928 	if (is_call_insn(insn)) {
4929 		if (insn->src_reg != BPF_PSEUDO_CALL) {
4930 			pr_warn("prog '%s': incorrect bpf_call opcode\n", prog->name);
4931 			return -LIBBPF_ERRNO__RELOC;
4932 		}
4933 		/* text_shndx can be 0, if no default "main" program exists */
4934 		if (!shdr_idx || shdr_idx != obj->efile.text_shndx) {
4935 			sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4936 			pr_warn("prog '%s': bad call relo against '%s' in section '%s'\n",
4937 				prog->name, sym_name, sym_sec_name);
4938 			return -LIBBPF_ERRNO__RELOC;
4939 		}
4940 		if (sym->st_value % BPF_INSN_SZ) {
4941 			pr_warn("prog '%s': bad call relo against '%s' at offset %zu\n",
4942 				prog->name, sym_name, (size_t)sym->st_value);
4943 			return -LIBBPF_ERRNO__RELOC;
4944 		}
4945 		reloc_desc->type = RELO_CALL;
4946 		reloc_desc->insn_idx = insn_idx;
4947 		reloc_desc->sym_off = sym->st_value;
4948 		return 0;
4949 	}
4950 
4951 	if (!shdr_idx || shdr_idx >= SHN_LORESERVE) {
4952 		pr_warn("prog '%s': invalid relo against '%s' in special section 0x%x; forgot to initialize global var?..\n",
4953 			prog->name, sym_name, shdr_idx);
4954 		return -LIBBPF_ERRNO__RELOC;
4955 	}
4956 
4957 	/* loading subprog addresses */
4958 	if (sym_is_subprog(sym, obj->efile.text_shndx)) {
4959 		/* global_func: sym->st_value = offset in the section, insn->imm = 0.
4960 		 * local_func: sym->st_value = 0, insn->imm = offset in the section.
4961 		 */
4962 		if ((sym->st_value % BPF_INSN_SZ) || (insn->imm % BPF_INSN_SZ)) {
4963 			pr_warn("prog '%s': bad subprog addr relo against '%s' at offset %zu+%d\n",
4964 				prog->name, sym_name, (size_t)sym->st_value, insn->imm);
4965 			return -LIBBPF_ERRNO__RELOC;
4966 		}
4967 
4968 		reloc_desc->type = RELO_SUBPROG_ADDR;
4969 		reloc_desc->insn_idx = insn_idx;
4970 		reloc_desc->sym_off = sym->st_value;
4971 		return 0;
4972 	}
4973 
4974 	type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
4975 	sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4976 
4977 	/* arena data relocation */
4978 	if (shdr_idx == obj->efile.arena_data_shndx) {
4979 		if (obj->arena_map_idx < 0) {
4980 			pr_warn("prog '%s': bad arena data relocation at insn %u, no arena maps defined\n",
4981 				prog->name, insn_idx);
4982 			return -LIBBPF_ERRNO__RELOC;
4983 		}
4984 		reloc_desc->type = RELO_DATA;
4985 		reloc_desc->insn_idx = insn_idx;
4986 		reloc_desc->map_idx = obj->arena_map_idx;
4987 		reloc_desc->sym_off = sym->st_value;
4988 
4989 		map = &obj->maps[obj->arena_map_idx];
4990 		pr_debug("prog '%s': found arena map %d (%s, sec %d, off %zu) for insn %u\n",
4991 			 prog->name, obj->arena_map_idx, map->name, map->sec_idx,
4992 			 map->sec_offset, insn_idx);
4993 		return 0;
4994 	}
4995 
4996 	/* jump table data relocation */
4997 	if (shdr_idx == obj->efile.jumptables_data_shndx) {
4998 		reloc_desc->type = RELO_INSN_ARRAY;
4999 		reloc_desc->insn_idx = insn_idx;
5000 		reloc_desc->map_idx = -1;
5001 		reloc_desc->sym_off = sym->st_value;
5002 		reloc_desc->sym_size = sym->st_size;
5003 		return 0;
5004 	}
5005 
5006 	/* generic map reference relocation */
5007 	if (type == LIBBPF_MAP_UNSPEC) {
5008 		if (!bpf_object__shndx_is_maps(obj, shdr_idx)) {
5009 			pr_warn("prog '%s': bad map relo against '%s' in section '%s'\n",
5010 				prog->name, sym_name, sym_sec_name);
5011 			return -LIBBPF_ERRNO__RELOC;
5012 		}
5013 		for (map_idx = 0; map_idx < nr_maps; map_idx++) {
5014 			map = &obj->maps[map_idx];
5015 			if (map->libbpf_type != type ||
5016 			    map->sec_idx != sym->st_shndx ||
5017 			    map->sec_offset != sym->st_value)
5018 				continue;
5019 			pr_debug("prog '%s': found map %zu (%s, sec %d, off %zu) for insn #%u\n",
5020 				 prog->name, map_idx, map->name, map->sec_idx,
5021 				 map->sec_offset, insn_idx);
5022 			break;
5023 		}
5024 		if (map_idx >= nr_maps) {
5025 			pr_warn("prog '%s': map relo failed to find map for section '%s', off %zu\n",
5026 				prog->name, sym_sec_name, (size_t)sym->st_value);
5027 			return -LIBBPF_ERRNO__RELOC;
5028 		}
5029 		reloc_desc->type = RELO_LD64;
5030 		reloc_desc->insn_idx = insn_idx;
5031 		reloc_desc->map_idx = map_idx;
5032 		reloc_desc->sym_off = 0; /* sym->st_value determines map_idx */
5033 		return 0;
5034 	}
5035 
5036 	/* global data map relocation */
5037 	if (!bpf_object__shndx_is_data(obj, shdr_idx)) {
5038 		pr_warn("prog '%s': bad data relo against section '%s'\n",
5039 			prog->name, sym_sec_name);
5040 		return -LIBBPF_ERRNO__RELOC;
5041 	}
5042 	for (map_idx = 0; map_idx < nr_maps; map_idx++) {
5043 		map = &obj->maps[map_idx];
5044 		if (map->libbpf_type != type || map->sec_idx != sym->st_shndx)
5045 			continue;
5046 		pr_debug("prog '%s': found data map %zu (%s, sec %d, off %zu) for insn %u\n",
5047 			 prog->name, map_idx, map->name, map->sec_idx,
5048 			 map->sec_offset, insn_idx);
5049 		break;
5050 	}
5051 	if (map_idx >= nr_maps) {
5052 		pr_warn("prog '%s': data relo failed to find map for section '%s'\n",
5053 			prog->name, sym_sec_name);
5054 		return -LIBBPF_ERRNO__RELOC;
5055 	}
5056 
5057 	reloc_desc->type = RELO_DATA;
5058 	reloc_desc->insn_idx = insn_idx;
5059 	reloc_desc->map_idx = map_idx;
5060 	reloc_desc->sym_off = sym->st_value;
5061 	if (map->in_arena) {
5062 		reloc_desc->map_idx = obj->arena_map_idx;
5063 		reloc_desc->sym_off += map->arena_off;
5064 	}
5065 	return 0;
5066 }
5067 
5068 static bool prog_contains_insn(const struct bpf_program *prog, size_t insn_idx)
5069 {
5070 	return insn_idx >= prog->sec_insn_off &&
5071 	       insn_idx < prog->sec_insn_off + prog->sec_insn_cnt;
5072 }
5073 
5074 static struct bpf_program *find_prog_by_sec_insn(const struct bpf_object *obj,
5075 						 size_t sec_idx, size_t insn_idx)
5076 {
5077 	int l = 0, r = obj->nr_programs - 1, m;
5078 	struct bpf_program *prog;
5079 
5080 	if (!obj->nr_programs)
5081 		return NULL;
5082 
5083 	while (l < r) {
5084 		m = l + (r - l + 1) / 2;
5085 		prog = &obj->programs[m];
5086 
5087 		if (prog->sec_idx < sec_idx ||
5088 		    (prog->sec_idx == sec_idx && prog->sec_insn_off <= insn_idx))
5089 			l = m;
5090 		else
5091 			r = m - 1;
5092 	}
5093 	/* matching program could be at index l, but it still might be the
5094 	 * wrong one, so we need to double check conditions for the last time
5095 	 */
5096 	prog = &obj->programs[l];
5097 	if (prog->sec_idx == sec_idx && prog_contains_insn(prog, insn_idx))
5098 		return prog;
5099 	return NULL;
5100 }
5101 
5102 static int
5103 bpf_object__collect_prog_relos(struct bpf_object *obj, Elf64_Shdr *shdr, Elf_Data *data)
5104 {
5105 	const char *relo_sec_name, *sec_name;
5106 	size_t sec_idx = shdr->sh_info, sym_idx;
5107 	struct bpf_program *prog;
5108 	struct reloc_desc *relos;
5109 	int err, i, nrels;
5110 	const char *sym_name;
5111 	__u32 insn_idx;
5112 	Elf_Scn *scn;
5113 	Elf_Data *scn_data;
5114 	Elf64_Sym *sym;
5115 	Elf64_Rel *rel;
5116 
5117 	if (sec_idx >= obj->efile.sec_cnt)
5118 		return -EINVAL;
5119 
5120 	scn = elf_sec_by_idx(obj, sec_idx);
5121 	scn_data = elf_sec_data(obj, scn);
5122 	if (!scn_data)
5123 		return -LIBBPF_ERRNO__FORMAT;
5124 
5125 	relo_sec_name = elf_sec_str(obj, shdr->sh_name);
5126 	sec_name = elf_sec_name(obj, scn);
5127 	if (!relo_sec_name || !sec_name)
5128 		return -EINVAL;
5129 
5130 	pr_debug("sec '%s': collecting relocation for section(%zu) '%s'\n",
5131 		 relo_sec_name, sec_idx, sec_name);
5132 	nrels = shdr->sh_size / shdr->sh_entsize;
5133 
5134 	for (i = 0; i < nrels; i++) {
5135 		rel = elf_rel_by_idx(data, i);
5136 		if (!rel) {
5137 			pr_warn("sec '%s': failed to get relo #%d\n", relo_sec_name, i);
5138 			return -LIBBPF_ERRNO__FORMAT;
5139 		}
5140 
5141 		sym_idx = ELF64_R_SYM(rel->r_info);
5142 		sym = elf_sym_by_idx(obj, sym_idx);
5143 		if (!sym) {
5144 			pr_warn("sec '%s': symbol #%zu not found for relo #%d\n",
5145 				relo_sec_name, sym_idx, i);
5146 			return -LIBBPF_ERRNO__FORMAT;
5147 		}
5148 
5149 		if (sym->st_shndx >= obj->efile.sec_cnt) {
5150 			pr_warn("sec '%s': corrupted symbol #%zu pointing to invalid section #%zu for relo #%d\n",
5151 				relo_sec_name, sym_idx, (size_t)sym->st_shndx, i);
5152 			return -LIBBPF_ERRNO__FORMAT;
5153 		}
5154 
5155 		if (rel->r_offset % BPF_INSN_SZ || rel->r_offset >= scn_data->d_size) {
5156 			pr_warn("sec '%s': invalid offset 0x%zx for relo #%d\n",
5157 				relo_sec_name, (size_t)rel->r_offset, i);
5158 			return -LIBBPF_ERRNO__FORMAT;
5159 		}
5160 
5161 		insn_idx = rel->r_offset / BPF_INSN_SZ;
5162 		/* relocations against static functions are recorded as
5163 		 * relocations against the section that contains a function;
5164 		 * in such case, symbol will be STT_SECTION and sym.st_name
5165 		 * will point to empty string (0), so fetch section name
5166 		 * instead
5167 		 */
5168 		if (ELF64_ST_TYPE(sym->st_info) == STT_SECTION && sym->st_name == 0)
5169 			sym_name = elf_sec_name(obj, elf_sec_by_idx(obj, sym->st_shndx));
5170 		else
5171 			sym_name = elf_sym_str(obj, sym->st_name);
5172 		sym_name = sym_name ?: "<?";
5173 
5174 		pr_debug("sec '%s': relo #%d: insn #%u against '%s'\n",
5175 			 relo_sec_name, i, insn_idx, sym_name);
5176 
5177 		prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
5178 		if (!prog) {
5179 			pr_debug("sec '%s': relo #%d: couldn't find program in section '%s' for insn #%u, probably overridden weak function, skipping...\n",
5180 				relo_sec_name, i, sec_name, insn_idx);
5181 			continue;
5182 		}
5183 
5184 		relos = libbpf_reallocarray(prog->reloc_desc,
5185 					    prog->nr_reloc + 1, sizeof(*relos));
5186 		if (!relos)
5187 			return -ENOMEM;
5188 		prog->reloc_desc = relos;
5189 
5190 		/* adjust insn_idx to local BPF program frame of reference */
5191 		insn_idx -= prog->sec_insn_off;
5192 		err = bpf_program__record_reloc(prog, &relos[prog->nr_reloc],
5193 						insn_idx, sym_name, sym, rel);
5194 		if (err)
5195 			return err;
5196 
5197 		prog->nr_reloc++;
5198 	}
5199 	return 0;
5200 }
5201 
5202 static int map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map)
5203 {
5204 	int id;
5205 
5206 	if (!obj->btf)
5207 		return -ENOENT;
5208 
5209 	/* if it's BTF-defined map, we don't need to search for type IDs.
5210 	 * For struct_ops map, it does not need btf_key_type_id and
5211 	 * btf_value_type_id.
5212 	 */
5213 	if (map->sec_idx == obj->efile.btf_maps_shndx || bpf_map__is_struct_ops(map))
5214 		return 0;
5215 
5216 	/*
5217 	 * LLVM annotates global data differently in BTF, that is,
5218 	 * only as '.data', '.bss', '.percpu' or '.rodata'.
5219 	 */
5220 	if (!bpf_map__is_internal(map))
5221 		return -ENOENT;
5222 
5223 	id = btf__find_by_name(obj->btf, map->real_name);
5224 	if (id < 0)
5225 		return id;
5226 
5227 	map->btf_key_type_id = 0;
5228 	map->btf_value_type_id = id;
5229 	return 0;
5230 }
5231 
5232 static int bpf_get_map_info_from_fdinfo(int fd, struct bpf_map_info *info)
5233 {
5234 	char file[PATH_MAX], buff[4096];
5235 	FILE *fp;
5236 	__u32 val;
5237 	int err;
5238 
5239 	snprintf(file, sizeof(file), "/proc/%d/fdinfo/%d", getpid(), fd);
5240 	memset(info, 0, sizeof(*info));
5241 
5242 	fp = fopen(file, "re");
5243 	if (!fp) {
5244 		err = -errno;
5245 		pr_warn("failed to open %s: %s. No procfs support?\n", file,
5246 			errstr(err));
5247 		return err;
5248 	}
5249 
5250 	while (fgets(buff, sizeof(buff), fp)) {
5251 		if (sscanf(buff, "map_type:\t%u", &val) == 1)
5252 			info->type = val;
5253 		else if (sscanf(buff, "key_size:\t%u", &val) == 1)
5254 			info->key_size = val;
5255 		else if (sscanf(buff, "value_size:\t%u", &val) == 1)
5256 			info->value_size = val;
5257 		else if (sscanf(buff, "max_entries:\t%u", &val) == 1)
5258 			info->max_entries = val;
5259 		else if (sscanf(buff, "map_flags:\t%x", &val) == 1)
5260 			info->map_flags = val;
5261 	}
5262 
5263 	fclose(fp);
5264 
5265 	return 0;
5266 }
5267 
5268 static bool map_is_created(const struct bpf_map *map)
5269 {
5270 	return map->obj->state >= OBJ_PREPARED || map->reused;
5271 }
5272 
5273 bool bpf_map__autocreate(const struct bpf_map *map)
5274 {
5275 	return map->autocreate;
5276 }
5277 
5278 int bpf_map__set_autocreate(struct bpf_map *map, bool autocreate)
5279 {
5280 	if (map_is_created(map))
5281 		return libbpf_err(-EBUSY);
5282 
5283 	if (map->in_arena)
5284 		return libbpf_err(-EOPNOTSUPP);
5285 
5286 	map->autocreate = autocreate;
5287 	return 0;
5288 }
5289 
5290 int bpf_map__set_autoattach(struct bpf_map *map, bool autoattach)
5291 {
5292 	if (!bpf_map__is_struct_ops(map))
5293 		return libbpf_err(-EINVAL);
5294 
5295 	map->autoattach = autoattach;
5296 	return 0;
5297 }
5298 
5299 bool bpf_map__autoattach(const struct bpf_map *map)
5300 {
5301 	return map->autoattach;
5302 }
5303 
5304 int bpf_map__reuse_fd(struct bpf_map *map, int fd)
5305 {
5306 	struct bpf_map_info info;
5307 	__u32 len = sizeof(info), name_len;
5308 	int new_fd, err;
5309 	char *new_name;
5310 
5311 	memset(&info, 0, len);
5312 	err = bpf_map_get_info_by_fd(fd, &info, &len);
5313 	if (err && errno == EINVAL)
5314 		err = bpf_get_map_info_from_fdinfo(fd, &info);
5315 	if (err)
5316 		return libbpf_err(err);
5317 
5318 	name_len = strlen(info.name);
5319 	if (name_len == BPF_OBJ_NAME_LEN - 1 && strncmp(map->name, info.name, name_len) == 0)
5320 		new_name = strdup(map->name);
5321 	else
5322 		new_name = strdup(info.name);
5323 
5324 	if (!new_name)
5325 		return libbpf_err(-errno);
5326 
5327 	/*
5328 	 * Like dup(), but make sure new FD is >= 3 and has O_CLOEXEC set.
5329 	 * This is similar to what we do in ensure_good_fd(), but without
5330 	 * closing original FD.
5331 	 */
5332 	new_fd = fcntl(fd, F_DUPFD_CLOEXEC, 3);
5333 	if (new_fd < 0) {
5334 		err = -errno;
5335 		goto err_free_new_name;
5336 	}
5337 
5338 	err = reuse_fd(map->fd, new_fd);
5339 	if (err)
5340 		goto err_free_new_name;
5341 
5342 	free(map->name);
5343 
5344 	map->name = new_name;
5345 	map->def.type = info.type;
5346 	map->def.key_size = info.key_size;
5347 	map->def.value_size = info.value_size;
5348 	map->def.max_entries = info.max_entries;
5349 	map->def.map_flags = info.map_flags;
5350 	map->btf_key_type_id = info.btf_key_type_id;
5351 	map->btf_value_type_id = info.btf_value_type_id;
5352 	map->reused = true;
5353 	map->map_extra = info.map_extra;
5354 
5355 	return 0;
5356 
5357 err_free_new_name:
5358 	free(new_name);
5359 	return libbpf_err(err);
5360 }
5361 
5362 __u32 bpf_map__max_entries(const struct bpf_map *map)
5363 {
5364 	return map->def.max_entries;
5365 }
5366 
5367 struct bpf_map *bpf_map__inner_map(struct bpf_map *map)
5368 {
5369 	if (!bpf_map_type__is_map_in_map(map->def.type))
5370 		return errno = EINVAL, NULL;
5371 
5372 	return map->inner_map;
5373 }
5374 
5375 int bpf_map__set_max_entries(struct bpf_map *map, __u32 max_entries)
5376 {
5377 	if (map_is_created(map))
5378 		return libbpf_err(-EBUSY);
5379 
5380 	map->def.max_entries = max_entries;
5381 
5382 	/* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
5383 	if (map_is_ringbuf(map))
5384 		map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
5385 
5386 	return 0;
5387 }
5388 
5389 static int bpf_object_prepare_token(struct bpf_object *obj)
5390 {
5391 	const char *bpffs_path;
5392 	int bpffs_fd = -1, token_fd, err;
5393 	bool mandatory;
5394 	enum libbpf_print_level level;
5395 
5396 	/* token is explicitly prevented */
5397 	if (obj->token_path && obj->token_path[0] == '\0') {
5398 		pr_debug("object '%s': token is prevented, skipping...\n", obj->name);
5399 		return 0;
5400 	}
5401 
5402 	mandatory = obj->token_path != NULL;
5403 	level = mandatory ? LIBBPF_WARN : LIBBPF_DEBUG;
5404 
5405 	bpffs_path = obj->token_path ?: BPF_FS_DEFAULT_PATH;
5406 	bpffs_fd = open(bpffs_path, O_DIRECTORY, O_RDWR);
5407 	if (bpffs_fd < 0) {
5408 		err = -errno;
5409 		__pr(level, "object '%s': failed (%s) to open BPF FS mount at '%s'%s\n",
5410 		     obj->name, errstr(err), bpffs_path,
5411 		     mandatory ? "" : ", skipping optional step...");
5412 		return mandatory ? err : 0;
5413 	}
5414 
5415 	token_fd = bpf_token_create(bpffs_fd, 0);
5416 	close(bpffs_fd);
5417 	if (token_fd < 0) {
5418 		if (!mandatory && token_fd == -ENOENT) {
5419 			pr_debug("object '%s': BPF FS at '%s' doesn't have BPF token delegation set up, skipping...\n",
5420 				 obj->name, bpffs_path);
5421 			return 0;
5422 		}
5423 		__pr(level, "object '%s': failed (%d) to create BPF token from '%s'%s\n",
5424 		     obj->name, token_fd, bpffs_path,
5425 		     mandatory ? "" : ", skipping optional step...");
5426 		return mandatory ? token_fd : 0;
5427 	}
5428 
5429 	obj->feat_cache = calloc(1, sizeof(*obj->feat_cache));
5430 	if (!obj->feat_cache) {
5431 		close(token_fd);
5432 		return -ENOMEM;
5433 	}
5434 
5435 	obj->token_fd = token_fd;
5436 	obj->feat_cache->token_fd = token_fd;
5437 
5438 	return 0;
5439 }
5440 
5441 static int
5442 bpf_object__probe_loading(struct bpf_object *obj)
5443 {
5444 	struct bpf_insn insns[] = {
5445 		BPF_MOV64_IMM(BPF_REG_0, 0),
5446 		BPF_EXIT_INSN(),
5447 	};
5448 	int ret, insn_cnt = ARRAY_SIZE(insns);
5449 
5450 	if (obj->gen_loader || obj->token_fd)
5451 		return 0;
5452 
5453 	ret = bump_rlimit_memlock();
5454 	if (ret)
5455 		pr_warn("Failed to bump RLIMIT_MEMLOCK (err = %s), you might need to do it explicitly!\n",
5456 			errstr(ret));
5457 
5458 	/* make sure basic loading works */
5459 	ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
5460 	if (ret < 0)
5461 		ret = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, NULL);
5462 	if (ret < 0) {
5463 		ret = errno;
5464 		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",
5465 			__func__, errstr(ret));
5466 		return -ret;
5467 	}
5468 	close(ret);
5469 
5470 	return 0;
5471 }
5472 
5473 bool kernel_supports(const struct bpf_object *obj, enum kern_feature_id feat_id)
5474 {
5475 	if (obj->gen_loader)
5476 		/* To generate loader program assume the latest kernel
5477 		 * to avoid doing extra prog_load, map_create syscalls.
5478 		 */
5479 		return true;
5480 
5481 	if (obj->feat_cache)
5482 		return feat_supported(obj->feat_cache, feat_id);
5483 
5484 	return feat_supported(NULL, feat_id);
5485 }
5486 
5487 /* Used in testing to simulate missing features. */
5488 void bpf_object_set_feat_cache(struct bpf_object *obj, struct kern_feature_cache *cache)
5489 {
5490 	if (obj->feat_cache)
5491 		free(obj->feat_cache);
5492 	obj->feat_cache = cache;
5493 }
5494 
5495 static bool map_is_reuse_compat(const struct bpf_map *map, int map_fd)
5496 {
5497 	struct bpf_map_info map_info;
5498 	__u32 map_info_len = sizeof(map_info);
5499 	int err;
5500 
5501 	memset(&map_info, 0, map_info_len);
5502 	err = bpf_map_get_info_by_fd(map_fd, &map_info, &map_info_len);
5503 	if (err && errno == EINVAL)
5504 		err = bpf_get_map_info_from_fdinfo(map_fd, &map_info);
5505 	if (err) {
5506 		pr_warn("failed to get map info for map FD %d: %s\n", map_fd,
5507 			errstr(err));
5508 		return false;
5509 	}
5510 
5511 	/*
5512 	 * bpf_get_map_info_by_fd() for DEVMAP will always return flags with
5513 	 * BPF_F_RDONLY_PROG set, but it generally is not set at map creation time.
5514 	 * Thus, ignore the BPF_F_RDONLY_PROG flag in the flags returned from
5515 	 * bpf_get_map_info_by_fd() when checking for compatibility with an
5516 	 * existing DEVMAP.
5517 	 */
5518 	if (map->def.type == BPF_MAP_TYPE_DEVMAP || map->def.type == BPF_MAP_TYPE_DEVMAP_HASH)
5519 		map_info.map_flags &= ~BPF_F_RDONLY_PROG;
5520 
5521 	return (map_info.type == map->def.type &&
5522 		map_info.key_size == map->def.key_size &&
5523 		map_info.value_size == map->def.value_size &&
5524 		map_info.max_entries == map->def.max_entries &&
5525 		map_info.map_flags == map->def.map_flags &&
5526 		map_info.map_extra == map->map_extra);
5527 }
5528 
5529 static int
5530 bpf_object__reuse_map(struct bpf_map *map)
5531 {
5532 	int err, pin_fd;
5533 
5534 	pin_fd = bpf_obj_get(map->pin_path);
5535 	if (pin_fd < 0) {
5536 		err = -errno;
5537 		if (err == -ENOENT) {
5538 			pr_debug("found no pinned map to reuse at '%s'\n",
5539 				 map->pin_path);
5540 			return 0;
5541 		}
5542 
5543 		pr_warn("couldn't retrieve pinned map '%s': %s\n",
5544 			map->pin_path, errstr(err));
5545 		return err;
5546 	}
5547 
5548 	if (!map_is_reuse_compat(map, pin_fd)) {
5549 		pr_warn("couldn't reuse pinned map at '%s': parameter mismatch\n",
5550 			map->pin_path);
5551 		close(pin_fd);
5552 		return -EINVAL;
5553 	}
5554 
5555 	err = bpf_map__reuse_fd(map, pin_fd);
5556 	close(pin_fd);
5557 	if (err)
5558 		return err;
5559 
5560 	map->pinned = true;
5561 	pr_debug("reused pinned map at '%s'\n", map->pin_path);
5562 
5563 	return 0;
5564 }
5565 
5566 static struct bpf_map *bpf_object__sec_map(struct bpf_object *obj, int sec_idx)
5567 {
5568 	int i;
5569 
5570 	for (i = 0; i < obj->nr_maps; i++)
5571 		if (bpf_map__is_internal(&obj->maps[i]) && obj->maps[i].sec_idx == sec_idx)
5572 			return &obj->maps[i];
5573 	return NULL;
5574 }
5575 
5576 static int bpf_object__mmap_arena(struct bpf_object *obj, struct bpf_map *map)
5577 {
5578 	int i, err;
5579 
5580 	map->mmaped = mmap((void *)(long)map->map_extra,
5581 			   bpf_map_mmap_sz(map), PROT_READ | PROT_WRITE,
5582 			   map->map_extra ? MAP_SHARED | MAP_FIXED : MAP_SHARED,
5583 			   map->fd, 0);
5584 	if (map->mmaped == MAP_FAILED) {
5585 		err = -errno;
5586 		map->mmaped = NULL;
5587 		pr_warn("map '%s': failed to mmap arena: %s\n",
5588 			map->name, errstr(err));
5589 		return err;
5590 	}
5591 	if (obj->arena_data) {
5592 		memcpy(map->mmaped + obj->arena_data_off, obj->arena_data,
5593 			obj->arena_data_sz);
5594 		zfree(&obj->arena_data);
5595 	}
5596 	for (i = 0; i < obj->nr_maps; i++) {
5597 		struct bpf_map *m = &obj->maps[i];
5598 
5599 		if (m->in_arena)
5600 			m->mmaped = map->mmaped + obj->arena_data_off + m->arena_off;
5601 	}
5602 	return 0;
5603 }
5604 
5605 static int
5606 bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
5607 {
5608 	enum libbpf_map_type map_type = map->libbpf_type;
5609 	bool is_percpu = map_type == LIBBPF_MAP_PERCPU;
5610 	const __u64 update_flags = is_percpu ? BPF_F_ALL_CPUS : 0;
5611 	int err, zero = 0;
5612 	size_t mmap_sz;
5613 
5614 	if (obj->gen_loader) {
5615 		bpf_gen__map_update_elem(obj->gen_loader, map - obj->maps,
5616 					 map->mmaped, map->def.value_size, update_flags);
5617 		if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG)
5618 			bpf_gen__map_freeze(obj->gen_loader, map - obj->maps);
5619 		return 0;
5620 	}
5621 
5622 	err = bpf_map_update_elem(map->fd, &zero, map->mmaped, update_flags);
5623 	if (err) {
5624 		err = -errno;
5625 		pr_warn("map '%s': failed to set initial contents: %s\n",
5626 			bpf_map__name(map), errstr(err));
5627 		return err;
5628 	}
5629 
5630 	/* Freeze .rodata and .kconfig map as read-only from syscall side. */
5631 	if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG) {
5632 		err = bpf_map_freeze(map->fd);
5633 		if (err) {
5634 			err = -errno;
5635 			pr_warn("map '%s': failed to freeze as read-only: %s\n",
5636 				bpf_map__name(map), errstr(err));
5637 			return err;
5638 		}
5639 	}
5640 
5641 	/* Remap anonymous mmap()-ed "map initialization image" as
5642 	 * a BPF map-backed mmap()-ed memory, but preserving the same
5643 	 * memory address. This will cause kernel to change process'
5644 	 * page table to point to a different piece of kernel memory,
5645 	 * but from userspace point of view memory address (and its
5646 	 * contents, being identical at this point) will stay the
5647 	 * same. This mapping will be released by bpf_object__close()
5648 	 * as per normal clean up procedure.
5649 	 */
5650 	mmap_sz = bpf_map_mmap_sz(map);
5651 	if (map->def.map_flags & BPF_F_MMAPABLE) {
5652 		void *mmaped;
5653 		int prot;
5654 
5655 		if (map->def.map_flags & BPF_F_RDONLY_PROG)
5656 			prot = PROT_READ;
5657 		else
5658 			prot = PROT_READ | PROT_WRITE;
5659 		mmaped = mmap(map->mmaped, mmap_sz, prot, MAP_SHARED | MAP_FIXED, map->fd, 0);
5660 		if (mmaped == MAP_FAILED) {
5661 			err = -errno;
5662 			pr_warn("map '%s': failed to re-mmap() contents: %s\n",
5663 				bpf_map__name(map), errstr(err));
5664 			return err;
5665 		}
5666 		map->mmaped = mmaped;
5667 	} else if (is_percpu) {
5668 		if (mprotect(map->mmaped, mmap_sz, PROT_READ)) {
5669 			err = -errno;
5670 			pr_warn("map '%s': failed to mprotect() contents: %s\n",
5671 				bpf_map__name(map), errstr(err));
5672 			return err;
5673 		}
5674 	} else if (map->mmaped) {
5675 		munmap(map->mmaped, mmap_sz);
5676 		map->mmaped = NULL;
5677 	}
5678 
5679 	return 0;
5680 }
5681 
5682 static void bpf_map__destroy(struct bpf_map *map);
5683 
5684 static int bpf_object__create_map(struct bpf_object *obj, struct bpf_map *map, bool is_inner)
5685 {
5686 	LIBBPF_OPTS(bpf_map_create_opts, create_attr);
5687 	struct bpf_map_def *def = &map->def;
5688 	const char *map_name = NULL;
5689 	int err = 0, map_fd;
5690 
5691 	if (kernel_supports(obj, FEAT_PROG_NAME))
5692 		map_name = map->name;
5693 	create_attr.map_ifindex = map->map_ifindex;
5694 	create_attr.map_flags = def->map_flags;
5695 	create_attr.numa_node = map->numa_node;
5696 	create_attr.map_extra = map->map_extra;
5697 	create_attr.token_fd = obj->token_fd;
5698 	if (obj->token_fd)
5699 		create_attr.map_flags |= BPF_F_TOKEN_FD;
5700 	if (map->excl_prog) {
5701 		err = bpf_prog_compute_hash(map->excl_prog);
5702 		if (err)
5703 			return err;
5704 
5705 		create_attr.excl_prog_hash = map->excl_prog->hash;
5706 		create_attr.excl_prog_hash_size = SHA256_DIGEST_LENGTH;
5707 	}
5708 
5709 	if (bpf_map__is_struct_ops(map)) {
5710 		create_attr.btf_vmlinux_value_type_id = map->btf_vmlinux_value_type_id;
5711 		if (map->mod_btf_fd >= 0) {
5712 			create_attr.value_type_btf_obj_fd = map->mod_btf_fd;
5713 			create_attr.map_flags |= BPF_F_VTYPE_BTF_OBJ_FD;
5714 		}
5715 	}
5716 
5717 	if (obj->btf && btf__fd(obj->btf) >= 0) {
5718 		create_attr.btf_fd = btf__fd(obj->btf);
5719 		create_attr.btf_key_type_id = map->btf_key_type_id;
5720 		create_attr.btf_value_type_id = map->btf_value_type_id;
5721 	}
5722 
5723 	if (bpf_map_type__is_map_in_map(def->type)) {
5724 		if (map->inner_map) {
5725 			err = map_set_def_max_entries(map->inner_map);
5726 			if (err)
5727 				return err;
5728 			err = bpf_object__create_map(obj, map->inner_map, true);
5729 			if (err) {
5730 				pr_warn("map '%s': failed to create inner map: %s\n",
5731 					map->name, errstr(err));
5732 				return err;
5733 			}
5734 			map->inner_map_fd = map->inner_map->fd;
5735 		}
5736 		if (map->inner_map_fd >= 0)
5737 			create_attr.inner_map_fd = map->inner_map_fd;
5738 	}
5739 
5740 	switch (def->type) {
5741 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
5742 	case BPF_MAP_TYPE_CGROUP_ARRAY:
5743 	case BPF_MAP_TYPE_STACK_TRACE:
5744 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
5745 	case BPF_MAP_TYPE_HASH_OF_MAPS:
5746 	case BPF_MAP_TYPE_DEVMAP:
5747 	case BPF_MAP_TYPE_DEVMAP_HASH:
5748 	case BPF_MAP_TYPE_CPUMAP:
5749 	case BPF_MAP_TYPE_XSKMAP:
5750 	case BPF_MAP_TYPE_SOCKMAP:
5751 	case BPF_MAP_TYPE_SOCKHASH:
5752 	case BPF_MAP_TYPE_QUEUE:
5753 	case BPF_MAP_TYPE_STACK:
5754 	case BPF_MAP_TYPE_ARENA:
5755 		create_attr.btf_fd = 0;
5756 		create_attr.btf_key_type_id = 0;
5757 		create_attr.btf_value_type_id = 0;
5758 		map->btf_key_type_id = 0;
5759 		map->btf_value_type_id = 0;
5760 		break;
5761 	case BPF_MAP_TYPE_STRUCT_OPS:
5762 		create_attr.btf_value_type_id = 0;
5763 		break;
5764 	default:
5765 		break;
5766 	}
5767 
5768 	if (obj->gen_loader) {
5769 		bpf_gen__map_create(obj->gen_loader, def->type, map_name,
5770 				    def->key_size, def->value_size, def->max_entries,
5771 				    &create_attr, is_inner ? -1 : map - obj->maps);
5772 		/* We keep pretenting we have valid FD to pass various fd >= 0
5773 		 * checks by just keeping original placeholder FDs in place.
5774 		 * See bpf_object__add_map() comment.
5775 		 * This placeholder fd will not be used with any syscall and
5776 		 * will be reset to -1 eventually.
5777 		 */
5778 		map_fd = map->fd;
5779 	} else {
5780 		map_fd = bpf_map_create(def->type, map_name,
5781 					def->key_size, def->value_size,
5782 					def->max_entries, &create_attr);
5783 	}
5784 	if (map_fd < 0 && (create_attr.btf_key_type_id || create_attr.btf_value_type_id)) {
5785 		err = -errno;
5786 		pr_warn("Error in bpf_create_map_xattr(%s): %s. Retrying without BTF.\n",
5787 			map->name, errstr(err));
5788 		create_attr.btf_fd = 0;
5789 		create_attr.btf_key_type_id = 0;
5790 		create_attr.btf_value_type_id = 0;
5791 		map->btf_key_type_id = 0;
5792 		map->btf_value_type_id = 0;
5793 		map_fd = bpf_map_create(def->type, map_name,
5794 					def->key_size, def->value_size,
5795 					def->max_entries, &create_attr);
5796 	}
5797 
5798 	if (bpf_map_type__is_map_in_map(def->type) && map->inner_map) {
5799 		if (obj->gen_loader)
5800 			map->inner_map->fd = -1;
5801 		bpf_map__destroy(map->inner_map);
5802 		zfree(&map->inner_map);
5803 	}
5804 
5805 	if (map_fd < 0)
5806 		return map_fd;
5807 
5808 	/* obj->gen_loader case, prevent reuse_fd() from closing map_fd */
5809 	if (map->fd == map_fd)
5810 		return 0;
5811 
5812 	/* Keep placeholder FD value but now point it to the BPF map object.
5813 	 * This way everything that relied on this map's FD (e.g., relocated
5814 	 * ldimm64 instructions) will stay valid and won't need adjustments.
5815 	 * map->fd stays valid but now point to what map_fd points to.
5816 	 */
5817 	return reuse_fd(map->fd, map_fd);
5818 }
5819 
5820 static int init_map_in_map_slots(struct bpf_object *obj, struct bpf_map *map)
5821 {
5822 	const struct bpf_map *targ_map;
5823 	unsigned int i;
5824 	int fd, err = 0;
5825 
5826 	for (i = 0; i < map->init_slots_sz; i++) {
5827 		if (!map->init_slots[i])
5828 			continue;
5829 
5830 		targ_map = map->init_slots[i];
5831 		fd = targ_map->fd;
5832 
5833 		if (obj->gen_loader) {
5834 			bpf_gen__populate_outer_map(obj->gen_loader,
5835 						    map - obj->maps, i,
5836 						    targ_map - obj->maps);
5837 		} else {
5838 			err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5839 		}
5840 		if (err) {
5841 			err = -errno;
5842 			pr_warn("map '%s': failed to initialize slot [%u] to map '%s' fd=%d: %s\n",
5843 				map->name, i, targ_map->name, fd, errstr(err));
5844 			return err;
5845 		}
5846 		pr_debug("map '%s': slot [%u] set to map '%s' fd=%d\n",
5847 			 map->name, i, targ_map->name, fd);
5848 	}
5849 
5850 	zfree(&map->init_slots);
5851 	map->init_slots_sz = 0;
5852 
5853 	return 0;
5854 }
5855 
5856 static int init_prog_array_slots(struct bpf_object *obj, struct bpf_map *map)
5857 {
5858 	const struct bpf_program *targ_prog;
5859 	unsigned int i;
5860 	int fd, err;
5861 
5862 	if (obj->gen_loader)
5863 		return -ENOTSUP;
5864 
5865 	for (i = 0; i < map->init_slots_sz; i++) {
5866 		if (!map->init_slots[i])
5867 			continue;
5868 
5869 		targ_prog = map->init_slots[i];
5870 		fd = bpf_program__fd(targ_prog);
5871 
5872 		err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5873 		if (err) {
5874 			err = -errno;
5875 			pr_warn("map '%s': failed to initialize slot [%u] to prog '%s' fd=%d: %s\n",
5876 				map->name, i, targ_prog->name, fd, errstr(err));
5877 			return err;
5878 		}
5879 		pr_debug("map '%s': slot [%u] set to prog '%s' fd=%d\n",
5880 			 map->name, i, targ_prog->name, fd);
5881 	}
5882 
5883 	zfree(&map->init_slots);
5884 	map->init_slots_sz = 0;
5885 
5886 	return 0;
5887 }
5888 
5889 static int bpf_object_init_prog_arrays(struct bpf_object *obj)
5890 {
5891 	struct bpf_map *map;
5892 	int i, err;
5893 
5894 	for (i = 0; i < obj->nr_maps; i++) {
5895 		map = &obj->maps[i];
5896 
5897 		if (!map->init_slots_sz || map->def.type != BPF_MAP_TYPE_PROG_ARRAY)
5898 			continue;
5899 
5900 		err = init_prog_array_slots(obj, map);
5901 		if (err < 0)
5902 			return err;
5903 	}
5904 	return 0;
5905 }
5906 
5907 static int map_set_def_max_entries(struct bpf_map *map)
5908 {
5909 	if (map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY && !map->def.max_entries) {
5910 		int nr_cpus;
5911 
5912 		nr_cpus = libbpf_num_possible_cpus();
5913 		if (nr_cpus < 0) {
5914 			pr_warn("map '%s': failed to determine number of system CPUs: %d\n",
5915 				map->name, nr_cpus);
5916 			return nr_cpus;
5917 		}
5918 		pr_debug("map '%s': setting size to %d\n", map->name, nr_cpus);
5919 		map->def.max_entries = nr_cpus;
5920 	}
5921 
5922 	return 0;
5923 }
5924 
5925 static int
5926 bpf_object__create_maps(struct bpf_object *obj)
5927 {
5928 	struct bpf_map *map;
5929 	unsigned int i, j;
5930 	int err;
5931 	bool retried;
5932 
5933 	for (i = 0; i < obj->nr_maps; i++) {
5934 		map = &obj->maps[i];
5935 
5936 		/* To support old kernels, we skip creating global data maps
5937 		 * (.rodata, .data, .kconfig, etc); later on, during program
5938 		 * loading, if we detect that at least one of the to-be-loaded
5939 		 * programs is referencing any global data map, we'll error
5940 		 * out with program name and relocation index logged.
5941 		 * This approach allows to accommodate Clang emitting
5942 		 * unnecessary .rodata.str1.1 sections for string literals,
5943 		 * but also it allows to have CO-RE applications that use
5944 		 * global variables in some of BPF programs, but not others.
5945 		 * If those global variable-using programs are not loaded at
5946 		 * runtime due to bpf_program__set_autoload(prog, false),
5947 		 * bpf_object loading will succeed just fine even on old
5948 		 * kernels.
5949 		 * Same skipping applies to percpu data.
5950 		 */
5951 		if (bpf_map__is_internal(map)) {
5952 			bool is_percpu = map->libbpf_type == LIBBPF_MAP_PERCPU;
5953 			enum kern_feature_id feat_id;
5954 
5955 			feat_id = is_percpu ? FEAT_PERCPU_DATA : FEAT_GLOBAL_DATA;
5956 			if (!kernel_supports(obj, feat_id))
5957 				map->autocreate = false;
5958 		}
5959 
5960 		if (!map->autocreate) {
5961 			pr_debug("map '%s': skipped auto-creating...\n", map->name);
5962 			continue;
5963 		}
5964 
5965 		/* see bpf_object__relocate_data_ptrs() */
5966 		if (map->def.type == BPF_MAP_TYPE_ARENA && obj->arena_mapped)
5967 			continue;
5968 
5969 		err = map_set_def_max_entries(map);
5970 		if (err)
5971 			goto err_out;
5972 
5973 		retried = false;
5974 retry:
5975 		if (map->pin_path) {
5976 			err = bpf_object__reuse_map(map);
5977 			if (err) {
5978 				pr_warn("map '%s': error reusing pinned map\n",
5979 					map->name);
5980 				goto err_out;
5981 			}
5982 			if (retried && map->fd < 0) {
5983 				pr_warn("map '%s': cannot find pinned map\n",
5984 					map->name);
5985 				err = -ENOENT;
5986 				goto err_out;
5987 			}
5988 		}
5989 
5990 		if (map->reused) {
5991 			pr_debug("map '%s': skipping creation (preset fd=%d)\n",
5992 				 map->name, map->fd);
5993 		} else {
5994 			err = bpf_object__create_map(obj, map, false);
5995 			if (err)
5996 				goto err_out;
5997 
5998 			pr_debug("map '%s': created successfully, fd=%d\n",
5999 				 map->name, map->fd);
6000 
6001 			if (bpf_map__is_internal(map)) {
6002 				err = bpf_object__populate_internal_map(obj, map);
6003 				if (err < 0)
6004 					goto err_out;
6005 			} else if (map->def.type == BPF_MAP_TYPE_ARENA) {
6006 				err = bpf_object__mmap_arena(obj, map);
6007 				if (err)
6008 					return err;
6009 			}
6010 			if (map->init_slots_sz && map->def.type != BPF_MAP_TYPE_PROG_ARRAY) {
6011 				err = init_map_in_map_slots(obj, map);
6012 				if (err < 0)
6013 					goto err_out;
6014 			}
6015 		}
6016 
6017 		if (map->pin_path && !map->pinned) {
6018 			err = bpf_map__pin(map, NULL);
6019 			if (err) {
6020 				if (!retried && err == -EEXIST) {
6021 					retried = true;
6022 					goto retry;
6023 				}
6024 				pr_warn("map '%s': failed to auto-pin at '%s': %s\n",
6025 					map->name, map->pin_path, errstr(err));
6026 				goto err_out;
6027 			}
6028 		}
6029 	}
6030 
6031 	return 0;
6032 
6033 err_out:
6034 	pr_warn("map '%s': failed to create: %s\n", map->name, errstr(err));
6035 	pr_perm_msg(err);
6036 	for (j = 0; j < i; j++)
6037 		zclose(obj->maps[j].fd);
6038 	return err;
6039 }
6040 
6041 static bool bpf_core_is_flavor_sep(const char *s)
6042 {
6043 	/* check X___Y name pattern, where X and Y are not underscores */
6044 	return s[0] != '_' &&				      /* X */
6045 	       s[1] == '_' && s[2] == '_' && s[3] == '_' &&   /* ___ */
6046 	       s[4] != '_';				      /* Y */
6047 }
6048 
6049 /* Given 'some_struct_name___with_flavor' return the length of a name prefix
6050  * before last triple underscore. Struct name part after last triple
6051  * underscore is ignored by BPF CO-RE relocation during relocation matching.
6052  */
6053 size_t bpf_core_essential_name_len(const char *name)
6054 {
6055 	size_t n = strlen(name);
6056 	int i;
6057 
6058 	for (i = n - 5; i >= 0; i--) {
6059 		if (bpf_core_is_flavor_sep(name + i))
6060 			return i + 1;
6061 	}
6062 	return n;
6063 }
6064 
6065 void bpf_core_free_cands(struct bpf_core_cand_list *cands)
6066 {
6067 	if (!cands)
6068 		return;
6069 
6070 	free(cands->cands);
6071 	free(cands);
6072 }
6073 
6074 int bpf_core_add_cands(struct bpf_core_cand *local_cand,
6075 		       size_t local_essent_len,
6076 		       const struct btf *targ_btf,
6077 		       const char *targ_btf_name,
6078 		       int targ_start_id,
6079 		       struct bpf_core_cand_list *cands)
6080 {
6081 	struct bpf_core_cand *new_cands, *cand;
6082 	const struct btf_type *t, *local_t;
6083 	const char *targ_name, *local_name;
6084 	size_t targ_essent_len;
6085 	int n, i;
6086 
6087 	local_t = btf__type_by_id(local_cand->btf, local_cand->id);
6088 	local_name = btf__str_by_offset(local_cand->btf, local_t->name_off);
6089 
6090 	n = btf__type_cnt(targ_btf);
6091 	for (i = targ_start_id; i < n; i++) {
6092 		t = btf__type_by_id(targ_btf, i);
6093 		if (!btf_kind_core_compat(t, local_t))
6094 			continue;
6095 
6096 		targ_name = btf__name_by_offset(targ_btf, t->name_off);
6097 		if (str_is_empty(targ_name))
6098 			continue;
6099 
6100 		targ_essent_len = bpf_core_essential_name_len(targ_name);
6101 		if (targ_essent_len != local_essent_len)
6102 			continue;
6103 
6104 		if (strncmp(local_name, targ_name, local_essent_len) != 0)
6105 			continue;
6106 
6107 		pr_debug("CO-RE relocating [%u] %s %s: found target candidate [%d] %s %s in [%s]\n",
6108 			 local_cand->id, btf_kind_str(local_t),
6109 			 local_name, i, btf_kind_str(t), targ_name,
6110 			 targ_btf_name);
6111 		new_cands = libbpf_reallocarray(cands->cands, cands->len + 1,
6112 					      sizeof(*cands->cands));
6113 		if (!new_cands)
6114 			return -ENOMEM;
6115 
6116 		cand = &new_cands[cands->len];
6117 		cand->btf = targ_btf;
6118 		cand->id = i;
6119 
6120 		cands->cands = new_cands;
6121 		cands->len++;
6122 	}
6123 	return 0;
6124 }
6125 
6126 static bool is_btf_mod_allowed(const struct bpf_object *obj, const char *name)
6127 {
6128 	ssize_t i;
6129 
6130 	if (obj->btf_module_allowlist_cnt < 0)
6131 		return true;
6132 
6133 	for (i = 0; i < obj->btf_module_allowlist_cnt; i++) {
6134 		if (strcmp(obj->btf_module_allowlist[i], name) == 0)
6135 			return true;
6136 	}
6137 
6138 	return false;
6139 }
6140 
6141 static int load_module_btfs(struct bpf_object *obj)
6142 {
6143 	struct bpf_btf_info info;
6144 	struct module_btf *mod_btf;
6145 	struct btf *btf;
6146 	char name[64];
6147 	__u32 id = 0, len;
6148 	int err, fd;
6149 
6150 	if (obj->btf_modules_loaded)
6151 		return 0;
6152 
6153 	if (obj->gen_loader)
6154 		return 0;
6155 
6156 	/* don't do this again, even if we find no module BTFs */
6157 	obj->btf_modules_loaded = true;
6158 
6159 	/* kernel too old to support module BTFs */
6160 	if (!kernel_supports(obj, FEAT_MODULE_BTF))
6161 		return 0;
6162 
6163 	if (obj->btf_module_allowlist_cnt == 0)
6164 		return 0;
6165 
6166 	while (true) {
6167 		err = bpf_btf_get_next_id(id, &id);
6168 		if (err && errno == ENOENT)
6169 			return 0;
6170 		if (err && errno == EPERM) {
6171 			pr_debug("skipping module BTFs loading, missing privileges\n");
6172 			return 0;
6173 		}
6174 		if (err) {
6175 			err = -errno;
6176 			pr_warn("failed to iterate BTF objects: %s\n", errstr(err));
6177 			return err;
6178 		}
6179 
6180 		fd = bpf_btf_get_fd_by_id(id);
6181 		if (fd < 0) {
6182 			if (errno == ENOENT)
6183 				continue; /* expected race: BTF was unloaded */
6184 			err = -errno;
6185 			pr_warn("failed to get BTF object #%u FD: %s\n", id, errstr(err));
6186 			return err;
6187 		}
6188 
6189 		len = sizeof(info);
6190 		memset(&info, 0, sizeof(info));
6191 		info.name = ptr_to_u64(name);
6192 		info.name_len = sizeof(name);
6193 
6194 		btf = NULL;
6195 		err = bpf_btf_get_info_by_fd(fd, &info, &len);
6196 		if (err) {
6197 			err = -errno;
6198 			pr_warn("failed to get BTF object #%u info: %s\n", id, errstr(err));
6199 			break;
6200 		}
6201 
6202 		/* ignore non-module BTFs */
6203 		if (!info.kernel_btf || strcmp(name, "vmlinux") == 0) {
6204 			close(fd);
6205 			continue;
6206 		}
6207 
6208 		if (!is_btf_mod_allowed(obj, name)) {
6209 			close(fd);
6210 			continue;
6211 		}
6212 
6213 		btf = btf_get_from_fd(fd, obj->btf_vmlinux);
6214 		err = libbpf_get_error(btf);
6215 		if (err) {
6216 			pr_warn("failed to load module [%s]'s BTF object #%u: %s\n",
6217 				name, id, errstr(err));
6218 			break;
6219 		}
6220 
6221 		err = libbpf_ensure_mem((void **)&obj->btf_modules, &obj->btf_module_cap,
6222 					sizeof(*obj->btf_modules), obj->btf_module_cnt + 1);
6223 		if (err)
6224 			break;
6225 
6226 		mod_btf = &obj->btf_modules[obj->btf_module_cnt];
6227 
6228 		mod_btf->btf = btf;
6229 		mod_btf->id = id;
6230 		mod_btf->fd = fd;
6231 		mod_btf->name = strdup(name);
6232 		if (!mod_btf->name) {
6233 			err = -ENOMEM;
6234 			break;
6235 		}
6236 		obj->btf_module_cnt++;
6237 
6238 		if (obj->btf_module_allowlist_cnt == obj->btf_module_cnt)
6239 			break;
6240 	}
6241 
6242 	if (err) {
6243 		btf__free(btf);
6244 		close(fd);
6245 	}
6246 	return err;
6247 }
6248 
6249 static struct bpf_core_cand_list *
6250 bpf_core_find_cands(struct bpf_object *obj, const struct btf *local_btf, __u32 local_type_id)
6251 {
6252 	struct bpf_core_cand local_cand = {};
6253 	struct bpf_core_cand_list *cands;
6254 	const struct btf *main_btf;
6255 	const struct btf_type *local_t;
6256 	const char *local_name;
6257 	size_t local_essent_len;
6258 	int err, i;
6259 
6260 	local_cand.btf = local_btf;
6261 	local_cand.id = local_type_id;
6262 	local_t = btf__type_by_id(local_btf, local_type_id);
6263 	if (!local_t)
6264 		return ERR_PTR(-EINVAL);
6265 
6266 	local_name = btf__name_by_offset(local_btf, local_t->name_off);
6267 	if (str_is_empty(local_name))
6268 		return ERR_PTR(-EINVAL);
6269 	local_essent_len = bpf_core_essential_name_len(local_name);
6270 
6271 	cands = calloc(1, sizeof(*cands));
6272 	if (!cands)
6273 		return ERR_PTR(-ENOMEM);
6274 
6275 	/* Attempt to find target candidates in vmlinux BTF first */
6276 	main_btf = obj->btf_vmlinux_override ?: obj->btf_vmlinux;
6277 	err = bpf_core_add_cands(&local_cand, local_essent_len, main_btf, "vmlinux", 1, cands);
6278 	if (err)
6279 		goto err_out;
6280 
6281 	/* if vmlinux BTF has any candidate, don't got for module BTFs */
6282 	if (cands->len)
6283 		return cands;
6284 
6285 	/* if vmlinux BTF was overridden, don't attempt to load module BTFs */
6286 	if (obj->btf_vmlinux_override)
6287 		return cands;
6288 
6289 	/* now look through module BTFs, trying to still find candidates */
6290 	err = load_module_btfs(obj);
6291 	if (err)
6292 		goto err_out;
6293 
6294 	for (i = 0; i < obj->btf_module_cnt; i++) {
6295 		err = bpf_core_add_cands(&local_cand, local_essent_len,
6296 					 obj->btf_modules[i].btf,
6297 					 obj->btf_modules[i].name,
6298 					 btf__type_cnt(obj->btf_vmlinux),
6299 					 cands);
6300 		if (err)
6301 			goto err_out;
6302 	}
6303 
6304 	return cands;
6305 err_out:
6306 	bpf_core_free_cands(cands);
6307 	return ERR_PTR(err);
6308 }
6309 
6310 /* Check local and target types for compatibility. This check is used for
6311  * type-based CO-RE relocations and follow slightly different rules than
6312  * field-based relocations. This function assumes that root types were already
6313  * checked for name match. Beyond that initial root-level name check, names
6314  * are completely ignored. Compatibility rules are as follows:
6315  *   - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs are considered compatible, but
6316  *     kind should match for local and target types (i.e., STRUCT is not
6317  *     compatible with UNION);
6318  *   - for ENUMs, the size is ignored;
6319  *   - for INT, size and signedness are ignored;
6320  *   - for ARRAY, dimensionality is ignored, element types are checked for
6321  *     compatibility recursively;
6322  *   - CONST/VOLATILE/RESTRICT modifiers are ignored;
6323  *   - TYPEDEFs/PTRs are compatible if types they pointing to are compatible;
6324  *   - FUNC_PROTOs are compatible if they have compatible signature: same
6325  *     number of input args and compatible return and argument types.
6326  * These rules are not set in stone and probably will be adjusted as we get
6327  * more experience with using BPF CO-RE relocations.
6328  */
6329 int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
6330 			      const struct btf *targ_btf, __u32 targ_id)
6331 {
6332 	return __bpf_core_types_are_compat(local_btf, local_id, targ_btf, targ_id, 32);
6333 }
6334 
6335 int bpf_core_types_match(const struct btf *local_btf, __u32 local_id,
6336 			 const struct btf *targ_btf, __u32 targ_id)
6337 {
6338 	return __bpf_core_types_match(local_btf, local_id, targ_btf, targ_id, false, 32);
6339 }
6340 
6341 static size_t bpf_core_hash_fn(const long key, void *ctx)
6342 {
6343 	return key;
6344 }
6345 
6346 static bool bpf_core_equal_fn(const long k1, const long k2, void *ctx)
6347 {
6348 	return k1 == k2;
6349 }
6350 
6351 static int record_relo_core(struct bpf_program *prog,
6352 			    const struct bpf_core_relo *core_relo, int insn_idx)
6353 {
6354 	struct reloc_desc *relos, *relo;
6355 
6356 	relos = libbpf_reallocarray(prog->reloc_desc,
6357 				    prog->nr_reloc + 1, sizeof(*relos));
6358 	if (!relos)
6359 		return -ENOMEM;
6360 	relo = &relos[prog->nr_reloc];
6361 	relo->type = RELO_CORE;
6362 	relo->insn_idx = insn_idx;
6363 	relo->core_relo = core_relo;
6364 	prog->reloc_desc = relos;
6365 	prog->nr_reloc++;
6366 	return 0;
6367 }
6368 
6369 static const struct bpf_core_relo *find_relo_core(struct bpf_program *prog, int insn_idx)
6370 {
6371 	struct reloc_desc *relo;
6372 	int i;
6373 
6374 	for (i = 0; i < prog->nr_reloc; i++) {
6375 		relo = &prog->reloc_desc[i];
6376 		if (relo->type != RELO_CORE || relo->insn_idx != insn_idx)
6377 			continue;
6378 
6379 		return relo->core_relo;
6380 	}
6381 
6382 	return NULL;
6383 }
6384 
6385 static int bpf_core_resolve_relo(struct bpf_program *prog,
6386 				 const struct bpf_core_relo *relo,
6387 				 int relo_idx,
6388 				 const struct btf *local_btf,
6389 				 struct hashmap *cand_cache,
6390 				 struct bpf_core_relo_res *targ_res)
6391 {
6392 	struct bpf_core_spec specs_scratch[3] = {};
6393 	struct bpf_core_cand_list *cands = NULL;
6394 	const char *prog_name = prog->name;
6395 	const struct btf_type *local_type;
6396 	const char *local_name;
6397 	__u32 local_id = relo->type_id;
6398 	int err;
6399 
6400 	local_type = btf__type_by_id(local_btf, local_id);
6401 	if (!local_type)
6402 		return -EINVAL;
6403 
6404 	local_name = btf__name_by_offset(local_btf, local_type->name_off);
6405 	if (!local_name)
6406 		return -EINVAL;
6407 
6408 	if (relo->kind != BPF_CORE_TYPE_ID_LOCAL &&
6409 	    !hashmap__find(cand_cache, local_id, &cands)) {
6410 		cands = bpf_core_find_cands(prog->obj, local_btf, local_id);
6411 		if (IS_ERR(cands)) {
6412 			pr_warn("prog '%s': relo #%d: target candidate search failed for [%u] %s %s: %ld\n",
6413 				prog_name, relo_idx, local_id, btf_kind_str(local_type),
6414 				local_name, PTR_ERR(cands));
6415 			return PTR_ERR(cands);
6416 		}
6417 		err = hashmap__set(cand_cache, local_id, cands, NULL, NULL);
6418 		if (err) {
6419 			bpf_core_free_cands(cands);
6420 			return err;
6421 		}
6422 	}
6423 
6424 	return bpf_core_calc_relo_insn(prog_name, relo, relo_idx, local_btf, cands, specs_scratch,
6425 				       targ_res);
6426 }
6427 
6428 static int
6429 bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
6430 {
6431 	const struct btf_ext_info_sec *sec;
6432 	struct bpf_core_relo_res targ_res;
6433 	const struct bpf_core_relo *rec;
6434 	const struct btf_ext_info *seg;
6435 	struct hashmap_entry *entry;
6436 	struct hashmap *cand_cache = NULL;
6437 	struct bpf_program *prog;
6438 	struct bpf_insn *insn;
6439 	const char *sec_name;
6440 	int i, err = 0, insn_idx, sec_idx, sec_num;
6441 
6442 	if (obj->btf_ext->core_relo_info.len == 0)
6443 		return 0;
6444 
6445 	if (targ_btf_path) {
6446 		obj->btf_vmlinux_override = btf__parse(targ_btf_path, NULL);
6447 		err = libbpf_get_error(obj->btf_vmlinux_override);
6448 		if (err) {
6449 			pr_warn("failed to parse target BTF: %s\n", errstr(err));
6450 			return err;
6451 		}
6452 	}
6453 
6454 	cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
6455 	if (IS_ERR(cand_cache)) {
6456 		err = PTR_ERR(cand_cache);
6457 		goto out;
6458 	}
6459 
6460 	seg = &obj->btf_ext->core_relo_info;
6461 	sec_num = 0;
6462 	for_each_btf_ext_sec(seg, sec) {
6463 		sec_idx = seg->sec_idxs[sec_num];
6464 		sec_num++;
6465 
6466 		sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
6467 		if (str_is_empty(sec_name)) {
6468 			err = -EINVAL;
6469 			goto out;
6470 		}
6471 
6472 		pr_debug("sec '%s': found %u CO-RE relocations\n", sec_name, sec->num_info);
6473 
6474 		for_each_btf_ext_rec(seg, sec, i, rec) {
6475 			if (rec->insn_off % BPF_INSN_SZ) {
6476 				err = -EINVAL;
6477 				goto out;
6478 			}
6479 
6480 			insn_idx = rec->insn_off / BPF_INSN_SZ;
6481 			prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
6482 			if (!prog) {
6483 				/* When __weak subprog is "overridden" by another instance
6484 				 * of the subprog from a different object file, linker still
6485 				 * appends all the .BTF.ext info that used to belong to that
6486 				 * eliminated subprogram.
6487 				 * This is similar to what x86-64 linker does for relocations.
6488 				 * So just ignore such relocations just like we ignore
6489 				 * subprog instructions when discovering subprograms.
6490 				 */
6491 				pr_debug("sec '%s': skipping CO-RE relocation #%d for insn #%d belonging to eliminated weak subprogram\n",
6492 					 sec_name, i, insn_idx);
6493 				continue;
6494 			}
6495 			/* no need to apply CO-RE relocation if the program is
6496 			 * not going to be loaded
6497 			 */
6498 			if (!prog->autoload)
6499 				continue;
6500 
6501 			/* adjust insn_idx from section frame of reference to the local
6502 			 * program's frame of reference; (sub-)program code is not yet
6503 			 * relocated, so it's enough to just subtract in-section offset
6504 			 */
6505 			insn_idx = insn_idx - prog->sec_insn_off;
6506 			if (insn_idx >= prog->insns_cnt) {
6507 				err = -EINVAL;
6508 				goto out;
6509 			}
6510 			insn = &prog->insns[insn_idx];
6511 
6512 			if (is_ldimm64_insn(insn) && (size_t)insn_idx + 1 >= prog->insns_cnt) {
6513 				pr_warn("prog '%s': relo #%d: insn #%d (LDIMM64) is truncated\n",
6514 					prog->name, i, insn_idx);
6515 				err = -EINVAL;
6516 				goto out;
6517 			}
6518 
6519 			err = record_relo_core(prog, rec, insn_idx);
6520 			if (err) {
6521 				pr_warn("prog '%s': relo #%d: failed to record relocation: %s\n",
6522 					prog->name, i, errstr(err));
6523 				goto out;
6524 			}
6525 
6526 			if (prog->obj->gen_loader)
6527 				continue;
6528 
6529 			err = bpf_core_resolve_relo(prog, rec, i, obj->btf, cand_cache, &targ_res);
6530 			if (err) {
6531 				pr_warn("prog '%s': relo #%d: failed to relocate: %s\n",
6532 					prog->name, i, errstr(err));
6533 				goto out;
6534 			}
6535 
6536 			err = bpf_core_patch_insn(prog->name, insn, insn_idx, rec, i, &targ_res);
6537 			if (err) {
6538 				pr_warn("prog '%s': relo #%d: failed to patch insn #%d: %s\n",
6539 					prog->name, i, insn_idx, errstr(err));
6540 				goto out;
6541 			}
6542 		}
6543 	}
6544 
6545 out:
6546 	/* obj->btf_vmlinux and module BTFs are freed after object load */
6547 	btf__free(obj->btf_vmlinux_override);
6548 	obj->btf_vmlinux_override = NULL;
6549 
6550 	if (!IS_ERR_OR_NULL(cand_cache)) {
6551 		hashmap__for_each_entry(cand_cache, entry, i) {
6552 			bpf_core_free_cands(entry->pvalue);
6553 		}
6554 		hashmap__free(cand_cache);
6555 	}
6556 	return err;
6557 }
6558 
6559 /* base map load ldimm64 special constant, used also for log fixup logic */
6560 #define POISON_LDIMM64_MAP_BASE 2001000000
6561 #define POISON_LDIMM64_MAP_PFX "200100"
6562 
6563 static void poison_map_ldimm64(struct bpf_program *prog, int relo_idx,
6564 			       int insn_idx, struct bpf_insn *insn,
6565 			       int map_idx, const struct bpf_map *map)
6566 {
6567 	int i;
6568 
6569 	pr_debug("prog '%s': relo #%d: poisoning insn #%d that loads map #%d '%s'\n",
6570 		 prog->name, relo_idx, insn_idx, map_idx, map->name);
6571 
6572 	/* we turn single ldimm64 into two identical invalid calls */
6573 	for (i = 0; i < 2; i++) {
6574 		insn->code = BPF_JMP | BPF_CALL;
6575 		insn->dst_reg = 0;
6576 		insn->src_reg = 0;
6577 		insn->off = 0;
6578 		/* if this instruction is reachable (not a dead code),
6579 		 * verifier will complain with something like:
6580 		 * invalid func unknown#2001000123
6581 		 * where lower 123 is map index into obj->maps[] array
6582 		 */
6583 		insn->imm = POISON_LDIMM64_MAP_BASE + map_idx;
6584 
6585 		insn++;
6586 	}
6587 }
6588 
6589 /* unresolved kfunc call special constant, used also for log fixup logic */
6590 #define POISON_CALL_KFUNC_BASE 2002000000
6591 #define POISON_CALL_KFUNC_PFX "2002"
6592 
6593 static void poison_kfunc_call(struct bpf_program *prog, int relo_idx,
6594 			      int insn_idx, struct bpf_insn *insn,
6595 			      int ext_idx, const struct extern_desc *ext)
6596 {
6597 	pr_debug("prog '%s': relo #%d: poisoning insn #%d that calls kfunc '%s'\n",
6598 		 prog->name, relo_idx, insn_idx, ext->name);
6599 
6600 	/* we turn kfunc call into invalid helper call with identifiable constant */
6601 	insn->code = BPF_JMP | BPF_CALL;
6602 	insn->dst_reg = 0;
6603 	insn->src_reg = 0;
6604 	insn->off = 0;
6605 	/* if this instruction is reachable (not a dead code),
6606 	 * verifier will complain with something like:
6607 	 * invalid func unknown#2001000123
6608 	 * where lower 123 is extern index into obj->externs[] array
6609 	 */
6610 	insn->imm = POISON_CALL_KFUNC_BASE + ext_idx;
6611 }
6612 
6613 static int find_jt_map(struct bpf_object *obj, struct bpf_program *prog, unsigned int sym_off)
6614 {
6615 	size_t i;
6616 
6617 	for (i = 0; i < obj->jumptable_map_cnt; i++) {
6618 		/*
6619 		 * This might happen that same offset is used for two different
6620 		 * programs (as jump tables can be the same). However, for
6621 		 * different programs different maps should be created.
6622 		 */
6623 		if (obj->jumptable_maps[i].sym_off == sym_off &&
6624 		    obj->jumptable_maps[i].prog == prog)
6625 			return obj->jumptable_maps[i].fd;
6626 	}
6627 
6628 	return -ENOENT;
6629 }
6630 
6631 static int add_jt_map(struct bpf_object *obj, struct bpf_program *prog, unsigned int sym_off, int map_fd)
6632 {
6633 	size_t cnt = obj->jumptable_map_cnt;
6634 	size_t size = sizeof(obj->jumptable_maps[0]);
6635 	void *tmp;
6636 
6637 	tmp = libbpf_reallocarray(obj->jumptable_maps, cnt + 1, size);
6638 	if (!tmp)
6639 		return -ENOMEM;
6640 
6641 	obj->jumptable_maps = tmp;
6642 	obj->jumptable_maps[cnt].prog = prog;
6643 	obj->jumptable_maps[cnt].sym_off = sym_off;
6644 	obj->jumptable_maps[cnt].fd = map_fd;
6645 	obj->jumptable_map_cnt++;
6646 
6647 	return 0;
6648 }
6649 
6650 static int find_subprog_idx(struct bpf_program *prog, int insn_idx)
6651 {
6652 	int i;
6653 
6654 	for (i = prog->subprog_cnt - 1; i >= 0; i--) {
6655 		if (insn_idx >= prog->subprogs[i].sub_insn_off)
6656 			return i;
6657 	}
6658 
6659 	return -1;
6660 }
6661 
6662 static int create_jt_map(struct bpf_object *obj, struct bpf_program *prog, struct reloc_desc *relo)
6663 {
6664 	const __u32 jt_entry_size = 8;
6665 	unsigned int sym_off = relo->sym_off;
6666 	int jt_size = relo->sym_size;
6667 	__u32 max_entries = jt_size / jt_entry_size;
6668 	__u32 value_size = sizeof(struct bpf_insn_array_value);
6669 	struct bpf_insn_array_value val = {};
6670 	int subprog_idx;
6671 	int map_fd, err;
6672 	__u64 insn_off;
6673 	__u64 *jt;
6674 	__u32 i;
6675 
6676 	map_fd = find_jt_map(obj, prog, sym_off);
6677 	if (map_fd >= 0)
6678 		return map_fd;
6679 
6680 	if (sym_off % jt_entry_size) {
6681 		pr_warn("map '.jumptables': jumptable start %u should be multiple of %u\n",
6682 			sym_off, jt_entry_size);
6683 		return -EINVAL;
6684 	}
6685 
6686 	if (jt_size % jt_entry_size) {
6687 		pr_warn("map '.jumptables': jumptable size %d should be multiple of %u\n",
6688 			jt_size, jt_entry_size);
6689 		return -EINVAL;
6690 	}
6691 
6692 	map_fd = bpf_map_create(BPF_MAP_TYPE_INSN_ARRAY, ".jumptables",
6693 				4, value_size, max_entries, NULL);
6694 	if (map_fd < 0)
6695 		return map_fd;
6696 
6697 	if (!obj->jumptables_data) {
6698 		pr_warn("map '.jumptables': ELF file is missing jump table data\n");
6699 		err = -EINVAL;
6700 		goto err_close;
6701 	}
6702 	if (sym_off + jt_size > obj->jumptables_data_sz) {
6703 		pr_warn("map '.jumptables': jumptables_data size is %zu, trying to access %u\n",
6704 			obj->jumptables_data_sz, sym_off + jt_size);
6705 		err = -EINVAL;
6706 		goto err_close;
6707 	}
6708 
6709 	subprog_idx = -1; /* main program */
6710 	if (relo->insn_idx < 0 || relo->insn_idx >= prog->insns_cnt) {
6711 		pr_warn("map '.jumptables': invalid instruction index %d\n", relo->insn_idx);
6712 		err = -EINVAL;
6713 		goto err_close;
6714 	}
6715 	if (prog->subprogs)
6716 		subprog_idx = find_subprog_idx(prog, relo->insn_idx);
6717 
6718 	jt = (__u64 *)(obj->jumptables_data + sym_off);
6719 	for (i = 0; i < max_entries; i++) {
6720 		/*
6721 		 * The offset should be made to be relative to the beginning of
6722 		 * the main function, not the subfunction.
6723 		 */
6724 		insn_off = jt[i]/sizeof(struct bpf_insn);
6725 		if (subprog_idx >= 0) {
6726 			insn_off -= prog->subprogs[subprog_idx].sec_insn_off;
6727 			insn_off += prog->subprogs[subprog_idx].sub_insn_off;
6728 		} else {
6729 			insn_off -= prog->sec_insn_off;
6730 		}
6731 
6732 		/*
6733 		 * LLVM-generated jump tables contain u64 records, however
6734 		 * should contain values that fit in u32.
6735 		 */
6736 		if (insn_off > UINT32_MAX) {
6737 			pr_warn("map '.jumptables': invalid jump table value 0x%llx at offset %u\n",
6738 				(unsigned long long)jt[i], sym_off + i * jt_entry_size);
6739 			err = -EINVAL;
6740 			goto err_close;
6741 		}
6742 
6743 		val.orig_off = insn_off;
6744 		err = bpf_map_update_elem(map_fd, &i, &val, 0);
6745 		if (err)
6746 			goto err_close;
6747 	}
6748 
6749 	err = bpf_map_freeze(map_fd);
6750 	if (err)
6751 		goto err_close;
6752 
6753 	err = add_jt_map(obj, prog, sym_off, map_fd);
6754 	if (err)
6755 		goto err_close;
6756 
6757 	return map_fd;
6758 
6759 err_close:
6760 	close(map_fd);
6761 	return err;
6762 }
6763 
6764 /*
6765  * The kernel recognizes a pointer to a function in a frozen read-only map by
6766  * its value: the offset in bytes of the function in the program. It makes
6767  * callx work for tables of functions, structures of operations and vtables,
6768  * where pointers are mixed with other data. Functions have different offsets
6769  * in different programs, so create a copy of the map for the program.
6770  * The kernel replaces the offsets with the addresses of the functions when it
6771  * loads the program, which has to be the only user of the map.
6772  */
6773 static int create_func_ptr_map(struct bpf_object *obj, struct bpf_program *prog, int map_idx)
6774 {
6775 	LIBBPF_OPTS(bpf_map_create_opts, opts, .map_flags = BPF_F_RDONLY_PROG);
6776 	struct bpf_map *map = &obj->maps[map_idx];
6777 	__u32 value_size = map->def.value_size;
6778 	size_t i, j, cnt, sec_insn_off;
6779 	struct func_ptr *ptrs;
6780 	int map_fd, err, zero = 0;
6781 	__u64 val;
6782 	void *data, *tmp;
6783 
6784 	for (i = 0; i < obj->func_ptr_map_cnt; i++)
6785 		if (obj->func_ptr_maps[i].prog == prog &&
6786 		    obj->func_ptr_maps[i].map_idx == map_idx)
6787 			return obj->func_ptr_maps[i].fd;
6788 
6789 	/* the map is not created yet, what it's going to have is in mmaped */
6790 	if (!map->mmaped)
6791 		return -EINVAL;
6792 
6793 	data = malloc(value_size);
6794 	if (!data)
6795 		return -ENOMEM;
6796 	memcpy(data, map->mmaped, value_size);
6797 
6798 	ptrs = map->func_ptrs;
6799 	cnt = map->func_ptr_cnt;
6800 	for (i = 0; i < cnt; i++) {
6801 		if (ptrs[i].sec_off + sizeof(val) > value_size) {
6802 			err = -LIBBPF_ERRNO__FORMAT;
6803 			goto err_free;
6804 		}
6805 		/*
6806 		 * Static functions were appended by bpf_object__append_func_ptrs_code().
6807 		 * A global function is in the program only if the code refers to it.
6808 		 */
6809 		sec_insn_off = ptrs[i].text_off / BPF_INSN_SZ;
6810 		for (j = 0; j < prog->subprog_cnt; j++)
6811 			if (prog->subprogs[j].sec_insn_off == sec_insn_off)
6812 				break;
6813 		if (j == prog->subprog_cnt) {
6814 			pr_debug("prog '%s': map '%s': no function for the pointer at offset %zu, it's NULL\n",
6815 				 prog->name, map->name, ptrs[i].sec_off);
6816 			val = 0;
6817 		} else {
6818 			val = (__u64)prog->subprogs[j].sub_insn_off * BPF_INSN_SZ;
6819 		}
6820 		/* light skeleton can be generated for a target of another endianness */
6821 		if (!is_native_endianness(obj))
6822 			val = bswap_64(val);
6823 		memcpy(data + ptrs[i].sec_off, &val, sizeof(val));
6824 	}
6825 
6826 	/*
6827 	 * The kernel takes any aligned 64-bit value that is equal to the offset
6828 	 * of a function for a pointer. Tell when it's going to get it wrong.
6829 	 */
6830 	for (i = 0, j = 0; i + sizeof(val) <= value_size; i += sizeof(val)) {
6831 		__u32 k;
6832 
6833 		while (j < cnt && ptrs[j].sec_off < i)
6834 			j++;
6835 		if (j < cnt && ptrs[j].sec_off == i)
6836 			continue;
6837 		memcpy(&val, data + i, sizeof(val));
6838 		if (!is_native_endianness(obj))
6839 			val = bswap_64(val);
6840 		if (!val || val % BPF_INSN_SZ)
6841 			continue;
6842 		for (k = 0; k < prog->subprog_cnt; k++) {
6843 			if ((__u64)prog->subprogs[k].sub_insn_off * BPF_INSN_SZ != val)
6844 				continue;
6845 			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",
6846 				prog->name, map->name, (unsigned long long)val, i);
6847 			break;
6848 		}
6849 	}
6850 
6851 	if (obj->gen_loader) {
6852 		__u32 *ptr_offs = calloc(cnt, sizeof(*ptr_offs));
6853 		__u64 *ptr_vals = calloc(cnt, sizeof(*ptr_vals));
6854 
6855 		if (!ptr_offs || !ptr_vals) {
6856 			free(ptr_offs);
6857 			free(ptr_vals);
6858 			err = -ENOMEM;
6859 			goto err_free;
6860 		}
6861 		for (i = 0; i < cnt; i++) {
6862 			ptr_offs[i] = ptrs[i].sec_off;
6863 			memcpy(&ptr_vals[i], data + ptrs[i].sec_off, sizeof(val));
6864 			if (!is_native_endianness(obj))
6865 				ptr_vals[i] = bswap_64(ptr_vals[i]);
6866 		}
6867 		/* it's an index in fd_array of the loader, not an fd */
6868 		map_fd = bpf_gen__func_ptr_map_create(obj->gen_loader, map->name, map_idx, data,
6869 						      value_size, ptr_offs, ptr_vals, cnt);
6870 		free(ptr_offs);
6871 		free(ptr_vals);
6872 		goto done;
6873 	}
6874 
6875 	opts.token_fd = obj->token_fd;
6876 	if (obj->token_fd)
6877 		opts.map_flags |= BPF_F_TOKEN_FD;
6878 
6879 	map_fd = bpf_map_create(BPF_MAP_TYPE_ARRAY, map->name, sizeof(int), value_size, 1, &opts);
6880 	if (map_fd < 0) {
6881 		err = map_fd;
6882 		goto err_free;
6883 	}
6884 
6885 	err = bpf_map_update_elem(map_fd, &zero, data, 0);
6886 	if (!err)
6887 		err = bpf_map_freeze(map_fd);
6888 	if (err) {
6889 		err = -errno;
6890 		goto err_close;
6891 	}
6892 done:
6893 
6894 	tmp = libbpf_reallocarray(obj->func_ptr_maps, obj->func_ptr_map_cnt + 1,
6895 				  sizeof(*obj->func_ptr_maps));
6896 	if (!tmp) {
6897 		err = -ENOMEM;
6898 		goto err_close;
6899 	}
6900 	obj->func_ptr_maps = tmp;
6901 	obj->func_ptr_maps[obj->func_ptr_map_cnt].prog = prog;
6902 	obj->func_ptr_maps[obj->func_ptr_map_cnt].map_idx = map_idx;
6903 	obj->func_ptr_maps[obj->func_ptr_map_cnt].fd = map_fd;
6904 	obj->func_ptr_map_cnt++;
6905 
6906 	pr_debug("prog '%s': created a copy of map '%s' with %zu pointers to functions\n",
6907 		 prog->name, map->name, cnt);
6908 	free(data);
6909 	return map_fd;
6910 
6911 err_close:
6912 	if (!obj->gen_loader)
6913 		close(map_fd);
6914 err_free:
6915 	free(data);
6916 	return err;
6917 }
6918 
6919 /* Relocate data references within program code:
6920  *  - map references;
6921  *  - global variable references;
6922  *  - extern references.
6923  */
6924 static int
6925 bpf_object__relocate_data(struct bpf_object *obj, struct bpf_program *prog)
6926 {
6927 	int i;
6928 
6929 	for (i = 0; i < prog->nr_reloc; i++) {
6930 		struct reloc_desc *relo = &prog->reloc_desc[i];
6931 		struct bpf_insn *insn = &prog->insns[relo->insn_idx];
6932 		const struct bpf_map *map;
6933 		struct extern_desc *ext;
6934 
6935 		switch (relo->type) {
6936 		case RELO_LD64:
6937 			map = &obj->maps[relo->map_idx];
6938 			if (obj->gen_loader) {
6939 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX;
6940 				insn[0].imm = relo->map_idx;
6941 			} else if (map->autocreate) {
6942 				insn[0].src_reg = BPF_PSEUDO_MAP_FD;
6943 				insn[0].imm = map->fd;
6944 			} else {
6945 				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
6946 						   relo->map_idx, map);
6947 			}
6948 			break;
6949 		case RELO_DATA:
6950 			map = &obj->maps[relo->map_idx];
6951 			insn[1].imm = insn[0].imm + relo->sym_off;
6952 
6953 			if (relo->map_idx == obj->arena_map_idx)
6954 				insn[1].imm += obj->arena_data_off;
6955 
6956 			if (map->autocreate && map->func_ptr_cnt && prog->has_callx) {
6957 				int map_fd;
6958 
6959 				/* the program gets its own map with pointers to its functions */
6960 				map_fd = create_func_ptr_map(obj, prog, relo->map_idx);
6961 				if (map_fd < 0) {
6962 					pr_warn("prog '%s': relo #%d: can't create a copy of map '%s' with pointers to functions\n",
6963 						prog->name, i, map->name);
6964 					return map_fd;
6965 				}
6966 				insn[0].src_reg = obj->gen_loader ? BPF_PSEUDO_MAP_IDX_VALUE :
6967 								    BPF_PSEUDO_MAP_VALUE;
6968 				insn[0].imm = map_fd;
6969 			} else if (obj->gen_loader) {
6970 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
6971 				insn[0].imm = relo->map_idx;
6972 			} else if (map->autocreate) {
6973 				insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6974 				insn[0].imm = map->fd;
6975 			} else {
6976 				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
6977 						   relo->map_idx, map);
6978 			}
6979 			break;
6980 		case RELO_EXTERN_LD64:
6981 			ext = &obj->externs[relo->ext_idx];
6982 			if (ext->type == EXT_KCFG) {
6983 				if (obj->gen_loader) {
6984 					insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
6985 					insn[0].imm = obj->kconfig_map_idx;
6986 				} else {
6987 					insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6988 					insn[0].imm = obj->maps[obj->kconfig_map_idx].fd;
6989 				}
6990 				insn[1].imm = ext->kcfg.data_off;
6991 			} else /* EXT_KSYM */ {
6992 				if (ext->ksym.type_id && ext->is_set) { /* typed ksyms */
6993 					insn[0].src_reg = BPF_PSEUDO_BTF_ID;
6994 					insn[0].imm = ext->ksym.kernel_btf_id;
6995 					insn[1].imm = ext->ksym.kernel_btf_obj_fd;
6996 				} else { /* typeless ksyms or unresolved typed ksyms */
6997 					insn[0].imm = (__u32)ext->ksym.addr;
6998 					insn[1].imm = ext->ksym.addr >> 32;
6999 				}
7000 			}
7001 			break;
7002 		case RELO_EXTERN_CALL:
7003 			ext = &obj->externs[relo->ext_idx];
7004 			insn[0].src_reg = BPF_PSEUDO_KFUNC_CALL;
7005 			if (ext->is_set) {
7006 				insn[0].imm = ext->ksym.kernel_btf_id;
7007 				insn[0].off = ext->ksym.btf_fd_idx;
7008 			} else { /* unresolved weak kfunc call */
7009 				poison_kfunc_call(prog, i, relo->insn_idx, insn,
7010 						  relo->ext_idx, ext);
7011 			}
7012 			break;
7013 		case RELO_SUBPROG_ADDR:
7014 			if (insn[0].src_reg != BPF_PSEUDO_FUNC) {
7015 				pr_warn("prog '%s': relo #%d: bad insn\n",
7016 					prog->name, i);
7017 				return -EINVAL;
7018 			}
7019 			/* handled already */
7020 			break;
7021 		case RELO_CALL:
7022 			/* handled already */
7023 			break;
7024 		case RELO_CORE:
7025 			/* will be handled by bpf_program_record_relos() */
7026 			break;
7027 		case RELO_INSN_ARRAY: {
7028 			int map_fd;
7029 
7030 			map_fd = create_jt_map(obj, prog, relo);
7031 			if (map_fd < 0) {
7032 				pr_warn("prog '%s': relo #%d: can't create jump table: sym_off %u\n",
7033 					prog->name, i, relo->sym_off);
7034 				return map_fd;
7035 			}
7036 			insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
7037 			insn->imm = map_fd;
7038 			insn->off = 0;
7039 		}
7040 			break;
7041 		default:
7042 			pr_warn("prog '%s': relo #%d: bad relo type %u\n",
7043 				prog->name, i, relo->type);
7044 			return -EINVAL;
7045 		}
7046 	}
7047 
7048 	return 0;
7049 }
7050 
7051 static int adjust_prog_btf_ext_info(const struct bpf_object *obj,
7052 				    const struct bpf_program *prog,
7053 				    const struct btf_ext_info *ext_info,
7054 				    void **prog_info, __u32 *prog_rec_cnt,
7055 				    __u32 *prog_rec_sz)
7056 {
7057 	void *copy_start = NULL, *copy_end = NULL;
7058 	void *rec, *rec_end, *new_prog_info;
7059 	const struct btf_ext_info_sec *sec;
7060 	size_t old_sz, new_sz;
7061 	int i, sec_num, sec_idx, off_adj;
7062 
7063 	sec_num = 0;
7064 	for_each_btf_ext_sec(ext_info, sec) {
7065 		sec_idx = ext_info->sec_idxs[sec_num];
7066 		sec_num++;
7067 		if (prog->sec_idx != sec_idx)
7068 			continue;
7069 
7070 		for_each_btf_ext_rec(ext_info, sec, i, rec) {
7071 			__u32 insn_off = *(__u32 *)rec / BPF_INSN_SZ;
7072 
7073 			if (insn_off < prog->sec_insn_off)
7074 				continue;
7075 			if (insn_off >= prog->sec_insn_off + prog->sec_insn_cnt)
7076 				break;
7077 
7078 			if (!copy_start)
7079 				copy_start = rec;
7080 			copy_end = rec + ext_info->rec_size;
7081 		}
7082 
7083 		if (!copy_start)
7084 			return -ENOENT;
7085 
7086 		/* append func/line info of a given (sub-)program to the main
7087 		 * program func/line info
7088 		 */
7089 		old_sz = (size_t)(*prog_rec_cnt) * ext_info->rec_size;
7090 		new_sz = old_sz + (copy_end - copy_start);
7091 		new_prog_info = realloc(*prog_info, new_sz);
7092 		if (!new_prog_info)
7093 			return -ENOMEM;
7094 		*prog_info = new_prog_info;
7095 		*prog_rec_cnt = new_sz / ext_info->rec_size;
7096 		memcpy(new_prog_info + old_sz, copy_start, copy_end - copy_start);
7097 
7098 		/* Kernel instruction offsets are in units of 8-byte
7099 		 * instructions, while .BTF.ext instruction offsets generated
7100 		 * by Clang are in units of bytes. So convert Clang offsets
7101 		 * into kernel offsets and adjust offset according to program
7102 		 * relocated position.
7103 		 */
7104 		off_adj = prog->sub_insn_off - prog->sec_insn_off;
7105 		rec = new_prog_info + old_sz;
7106 		rec_end = new_prog_info + new_sz;
7107 		for (; rec < rec_end; rec += ext_info->rec_size) {
7108 			__u32 *insn_off = rec;
7109 
7110 			*insn_off = *insn_off / BPF_INSN_SZ + off_adj;
7111 		}
7112 		*prog_rec_sz = ext_info->rec_size;
7113 		return 0;
7114 	}
7115 
7116 	return -ENOENT;
7117 }
7118 
7119 static int
7120 reloc_prog_func_and_line_info(const struct bpf_object *obj,
7121 			      struct bpf_program *main_prog,
7122 			      const struct bpf_program *prog)
7123 {
7124 	int err;
7125 
7126 	/* no .BTF.ext relocation if .BTF.ext is missing or kernel doesn't
7127 	 * support func/line info
7128 	 */
7129 	if (!obj->btf_ext || !kernel_supports(obj, FEAT_BTF_FUNC))
7130 		return 0;
7131 
7132 	/* only attempt func info relocation if main program's func_info
7133 	 * relocation was successful
7134 	 */
7135 	if (main_prog != prog && !main_prog->func_info)
7136 		goto line_info;
7137 
7138 	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->func_info,
7139 				       &main_prog->func_info,
7140 				       &main_prog->func_info_cnt,
7141 				       &main_prog->func_info_rec_size);
7142 	if (err) {
7143 		if (err != -ENOENT) {
7144 			pr_warn("prog '%s': error relocating .BTF.ext function info: %s\n",
7145 				prog->name, errstr(err));
7146 			return err;
7147 		}
7148 		if (main_prog->func_info) {
7149 			/*
7150 			 * Some info has already been found but has problem
7151 			 * in the last btf_ext reloc. Must have to error out.
7152 			 */
7153 			pr_warn("prog '%s': missing .BTF.ext function info.\n", prog->name);
7154 			return err;
7155 		}
7156 		/* Have problem loading the very first info. Ignore the rest. */
7157 		pr_warn("prog '%s': missing .BTF.ext function info for the main program, skipping all of .BTF.ext func info.\n",
7158 			prog->name);
7159 	}
7160 
7161 line_info:
7162 	/* don't relocate line info if main program's relocation failed */
7163 	if (main_prog != prog && !main_prog->line_info)
7164 		return 0;
7165 
7166 	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->line_info,
7167 				       &main_prog->line_info,
7168 				       &main_prog->line_info_cnt,
7169 				       &main_prog->line_info_rec_size);
7170 	if (err) {
7171 		if (err != -ENOENT) {
7172 			pr_warn("prog '%s': error relocating .BTF.ext line info: %s\n",
7173 				prog->name, errstr(err));
7174 			return err;
7175 		}
7176 		if (main_prog->line_info) {
7177 			/*
7178 			 * Some info has already been found but has problem
7179 			 * in the last btf_ext reloc. Must have to error out.
7180 			 */
7181 			pr_warn("prog '%s': missing .BTF.ext line info.\n", prog->name);
7182 			return err;
7183 		}
7184 		/* Have problem loading the very first info. Ignore the rest. */
7185 		pr_warn("prog '%s': missing .BTF.ext line info for the main program, skipping all of .BTF.ext line info.\n",
7186 			prog->name);
7187 	}
7188 	return 0;
7189 }
7190 
7191 static int cmp_relo_by_insn_idx(const void *key, const void *elem)
7192 {
7193 	size_t insn_idx = *(const size_t *)key;
7194 	const struct reloc_desc *relo = elem;
7195 
7196 	if (insn_idx == relo->insn_idx)
7197 		return 0;
7198 	return insn_idx < relo->insn_idx ? -1 : 1;
7199 }
7200 
7201 static struct reloc_desc *find_prog_insn_relo(const struct bpf_program *prog, size_t insn_idx)
7202 {
7203 	if (!prog->nr_reloc)
7204 		return NULL;
7205 	return bsearch(&insn_idx, prog->reloc_desc, prog->nr_reloc,
7206 		       sizeof(*prog->reloc_desc), cmp_relo_by_insn_idx);
7207 }
7208 
7209 static int append_subprog_relos(struct bpf_program *main_prog, struct bpf_program *subprog)
7210 {
7211 	int new_cnt = main_prog->nr_reloc + subprog->nr_reloc;
7212 	struct reloc_desc *relos;
7213 	int i;
7214 
7215 	if (main_prog == subprog)
7216 		return 0;
7217 	relos = libbpf_reallocarray(main_prog->reloc_desc, new_cnt, sizeof(*relos));
7218 	/* if new count is zero, reallocarray can return a valid NULL result;
7219 	 * in this case the previous pointer will be freed, so we *have to*
7220 	 * reassign old pointer to the new value (even if it's NULL)
7221 	 */
7222 	if (!relos && new_cnt)
7223 		return -ENOMEM;
7224 	if (subprog->nr_reloc)
7225 		memcpy(relos + main_prog->nr_reloc, subprog->reloc_desc,
7226 		       sizeof(*relos) * subprog->nr_reloc);
7227 
7228 	for (i = main_prog->nr_reloc; i < new_cnt; i++)
7229 		relos[i].insn_idx += subprog->sub_insn_off;
7230 	/* After insn_idx adjustment the 'relos' array is still sorted
7231 	 * by insn_idx and doesn't break bsearch.
7232 	 */
7233 	main_prog->reloc_desc = relos;
7234 	main_prog->nr_reloc = new_cnt;
7235 	return 0;
7236 }
7237 
7238 static int save_subprog_offsets(struct bpf_program *main_prog, struct bpf_program *subprog)
7239 {
7240 	size_t size = sizeof(main_prog->subprogs[0]);
7241 	int cnt = main_prog->subprog_cnt;
7242 	void *tmp;
7243 
7244 	tmp = libbpf_reallocarray(main_prog->subprogs, cnt + 1, size);
7245 	if (!tmp)
7246 		return -ENOMEM;
7247 
7248 	main_prog->subprogs = tmp;
7249 	main_prog->subprogs[cnt].sec_insn_off = subprog->sec_insn_off;
7250 	main_prog->subprogs[cnt].sub_insn_off = subprog->sub_insn_off;
7251 	main_prog->subprog_cnt++;
7252 
7253 	return 0;
7254 }
7255 
7256 static int
7257 bpf_object__append_subprog_code(struct bpf_object *obj, struct bpf_program *main_prog,
7258 				struct bpf_program *subprog)
7259 {
7260 	struct bpf_insn *insns;
7261 	size_t new_cnt;
7262 	int err;
7263 
7264 	subprog->sub_insn_off = main_prog->insns_cnt;
7265 
7266 	new_cnt = main_prog->insns_cnt + subprog->insns_cnt;
7267 	insns = libbpf_reallocarray(main_prog->insns, new_cnt, sizeof(*insns));
7268 	if (!insns) {
7269 		pr_warn("prog '%s': failed to realloc prog code\n", main_prog->name);
7270 		return -ENOMEM;
7271 	}
7272 	main_prog->insns = insns;
7273 	main_prog->insns_cnt = new_cnt;
7274 
7275 	memcpy(main_prog->insns + subprog->sub_insn_off, subprog->insns,
7276 	       subprog->insns_cnt * sizeof(*insns));
7277 
7278 	pr_debug("prog '%s': added %zu insns from sub-prog '%s'\n",
7279 		 main_prog->name, subprog->insns_cnt, subprog->name);
7280 
7281 	/* The subprog insns are now appended. Append its relos too. */
7282 	err = append_subprog_relos(main_prog, subprog);
7283 	if (err)
7284 		return err;
7285 
7286 	err = save_subprog_offsets(main_prog, subprog);
7287 	if (err) {
7288 		pr_warn("prog '%s': failed to add subprog offsets: %s\n",
7289 			main_prog->name, errstr(err));
7290 		return err;
7291 	}
7292 
7293 	return 0;
7294 }
7295 
7296 static int
7297 bpf_object__reloc_code(struct bpf_object *obj, struct bpf_program *main_prog,
7298 		       struct bpf_program *prog)
7299 {
7300 	size_t sub_insn_idx, insn_idx;
7301 	struct bpf_program *subprog;
7302 	struct reloc_desc *relo;
7303 	struct bpf_insn *insn;
7304 	int err;
7305 
7306 	err = reloc_prog_func_and_line_info(obj, main_prog, prog);
7307 	if (err)
7308 		return err;
7309 
7310 	for (insn_idx = 0; insn_idx < prog->sec_insn_cnt; insn_idx++) {
7311 		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
7312 		if (!insn_is_subprog_call(insn) && !insn_is_pseudo_func(insn))
7313 			continue;
7314 
7315 		relo = find_prog_insn_relo(prog, insn_idx);
7316 		if (relo && relo->type == RELO_EXTERN_CALL)
7317 			/* kfunc relocations will be handled later
7318 			 * in bpf_object__relocate_data()
7319 			 */
7320 			continue;
7321 		if (relo && relo->type != RELO_CALL && relo->type != RELO_SUBPROG_ADDR) {
7322 			pr_warn("prog '%s': unexpected relo for insn #%zu, type %u\n",
7323 				prog->name, insn_idx, relo->type);
7324 			return -LIBBPF_ERRNO__RELOC;
7325 		}
7326 		if (relo) {
7327 			/* sub-program instruction index is a combination of
7328 			 * an offset of a symbol pointed to by relocation and
7329 			 * call instruction's imm field; for global functions,
7330 			 * call always has imm = -1, but for static functions
7331 			 * relocation is against STT_SECTION and insn->imm
7332 			 * points to a start of a static function
7333 			 *
7334 			 * for subprog addr relocation, the relo->sym_off + insn->imm is
7335 			 * the byte offset in the corresponding section.
7336 			 */
7337 			if (relo->type == RELO_CALL)
7338 				sub_insn_idx = relo->sym_off / BPF_INSN_SZ + insn->imm + 1;
7339 			else
7340 				sub_insn_idx = (relo->sym_off + insn->imm) / BPF_INSN_SZ;
7341 		} else if (insn_is_pseudo_func(insn)) {
7342 			/*
7343 			 * RELO_SUBPROG_ADDR relo is always emitted even if both
7344 			 * functions are in the same section, so it shouldn't reach here.
7345 			 */
7346 			pr_warn("prog '%s': missing subprog addr relo for insn #%zu\n",
7347 				prog->name, insn_idx);
7348 			return -LIBBPF_ERRNO__RELOC;
7349 		} else {
7350 			/* if subprogram call is to a static function within
7351 			 * the same ELF section, there won't be any relocation
7352 			 * emitted, but it also means there is no additional
7353 			 * offset necessary, insns->imm is relative to
7354 			 * instruction's original position within the section
7355 			 */
7356 			sub_insn_idx = prog->sec_insn_off + insn_idx + insn->imm + 1;
7357 		}
7358 
7359 		/* we enforce that sub-programs should be in .text section */
7360 		subprog = find_prog_by_sec_insn(obj, obj->efile.text_shndx, sub_insn_idx);
7361 		if (!subprog) {
7362 			pr_warn("prog '%s': no .text section found yet sub-program call exists\n",
7363 				prog->name);
7364 			return -LIBBPF_ERRNO__RELOC;
7365 		}
7366 
7367 		/* if it's the first call instruction calling into this
7368 		 * subprogram (meaning this subprog hasn't been processed
7369 		 * yet) within the context of current main program:
7370 		 *   - append it at the end of main program's instructions blog;
7371 		 *   - process is recursively, while current program is put on hold;
7372 		 *   - if that subprogram calls some other not yet processes
7373 		 *   subprogram, same thing will happen recursively until
7374 		 *   there are no more unprocesses subprograms left to append
7375 		 *   and relocate.
7376 		 */
7377 		if (subprog->sub_insn_off == 0) {
7378 			err = bpf_object__append_subprog_code(obj, main_prog, subprog);
7379 			if (err)
7380 				return err;
7381 			err = bpf_object__reloc_code(obj, main_prog, subprog);
7382 			if (err)
7383 				return err;
7384 		}
7385 
7386 		/* main_prog->insns memory could have been re-allocated, so
7387 		 * calculate pointer again
7388 		 */
7389 		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
7390 		/* calculate correct instruction position within current main
7391 		 * prog; each main prog can have a different set of
7392 		 * subprograms appended (potentially in different order as
7393 		 * well), so position of any subprog can be different for
7394 		 * different main programs
7395 		 */
7396 		insn->imm = subprog->sub_insn_off - (prog->sub_insn_off + insn_idx) - 1;
7397 
7398 		pr_debug("prog '%s': insn #%zu relocated, imm %d points to subprog '%s' (now at %zu offset)\n",
7399 			 prog->name, insn_idx, insn->imm, subprog->name, subprog->sub_insn_off);
7400 	}
7401 
7402 	return 0;
7403 }
7404 
7405 /* Append to the main program all functions that the data of the map points to */
7406 static int
7407 bpf_object__append_func_ptrs_code(struct bpf_object *obj, struct bpf_program *main_prog,
7408 				  const struct bpf_map *map)
7409 {
7410 	struct bpf_program *subprog;
7411 	size_t i, cnt, sec_insn_off;
7412 	struct func_ptr *ptrs;
7413 	int err;
7414 
7415 	ptrs = map->func_ptrs;
7416 	cnt = map->func_ptr_cnt;
7417 	for (i = 0; i < cnt; i++) {
7418 		sec_insn_off = ptrs[i].text_off / BPF_INSN_SZ;
7419 		subprog = find_prog_by_sec_insn(obj, obj->efile.text_shndx, sec_insn_off);
7420 		if (!subprog || subprog->sec_insn_off != sec_insn_off) {
7421 			pr_warn("prog '%s': map '%s': no function at .text+%zu for the pointer at offset %zu\n",
7422 				main_prog->name, map->name, ptrs[i].text_off, ptrs[i].sec_off);
7423 			return -LIBBPF_ERRNO__RELOC;
7424 		}
7425 
7426 		/*
7427 		 * callx can't call global functions. Don't add one to the
7428 		 * program only because the data points to it.
7429 		 */
7430 		if (subprog->sym_global)
7431 			continue;
7432 
7433 		/* see the comment in bpf_object__reloc_code() */
7434 		if (subprog->sub_insn_off == 0) {
7435 			err = bpf_object__append_subprog_code(obj, main_prog, subprog);
7436 			if (err)
7437 				return err;
7438 			err = bpf_object__reloc_code(obj, main_prog, subprog);
7439 			if (err)
7440 				return err;
7441 		}
7442 	}
7443 	return 0;
7444 }
7445 
7446 /*
7447  * The program that has callx might call any function that the data it refers
7448  * to points to. Append them. Programs that don't have callx can't call them
7449  * and the kernel doesn't look for pointers to functions in their data.
7450  */
7451 static int
7452 bpf_object__append_func_ptrs(struct bpf_object *obj, struct bpf_program *prog)
7453 {
7454 	size_t i;
7455 	int err;
7456 
7457 	prog->has_callx = prog_has_callx(prog);
7458 	if (!prog->has_callx)
7459 		return 0;
7460 
7461 	/* relocations of the functions that are appended are appended too */
7462 	for (i = 0; i < prog->nr_reloc; i++) {
7463 		struct reloc_desc *relo = &prog->reloc_desc[i];
7464 
7465 		if (relo->type != RELO_DATA || !obj->maps[relo->map_idx].func_ptr_cnt)
7466 			continue;
7467 		err = bpf_object__append_func_ptrs_code(obj, prog, &obj->maps[relo->map_idx]);
7468 		if (err)
7469 			return err;
7470 	}
7471 	return 0;
7472 }
7473 
7474 /*
7475  * Relocate sub-program calls.
7476  *
7477  * Algorithm operates as follows. Each entry-point BPF program (referred to as
7478  * main prog) is processed separately. For each subprog (non-entry functions,
7479  * that can be called from either entry progs or other subprogs) gets their
7480  * sub_insn_off reset to zero. This serves as indicator that this subprogram
7481  * hasn't been yet appended and relocated within current main prog. Once its
7482  * relocated, sub_insn_off will point at the position within current main prog
7483  * where given subprog was appended. This will further be used to relocate all
7484  * the call instructions jumping into this subprog.
7485  *
7486  * We start with main program and process all call instructions. If the call
7487  * is into a subprog that hasn't been processed (i.e., subprog->sub_insn_off
7488  * is zero), subprog instructions are appended at the end of main program's
7489  * instruction array. Then main program is "put on hold" while we recursively
7490  * process newly appended subprogram. If that subprogram calls into another
7491  * subprogram that hasn't been appended, new subprogram is appended again to
7492  * the *main* prog's instructions (subprog's instructions are always left
7493  * untouched, as they need to be in unmodified state for subsequent main progs
7494  * and subprog instructions are always sent only as part of a main prog) and
7495  * the process continues recursively. Once all the subprogs called from a main
7496  * prog or any of its subprogs are appended (and relocated), all their
7497  * positions within finalized instructions array are known, so it's easy to
7498  * rewrite call instructions with correct relative offsets, corresponding to
7499  * desired target subprog.
7500  *
7501  * Its important to realize that some subprogs might not be called from some
7502  * main prog and any of its called/used subprogs. Those will keep their
7503  * subprog->sub_insn_off as zero at all times and won't be appended to current
7504  * main prog and won't be relocated within the context of current main prog.
7505  * They might still be used from other main progs later.
7506  *
7507  * Visually this process can be shown as below. Suppose we have two main
7508  * programs mainA and mainB and BPF object contains three subprogs: subA,
7509  * subB, and subC. mainA calls only subA, mainB calls only subC, but subA and
7510  * subC both call subB:
7511  *
7512  *        +--------+ +-------+
7513  *        |        v v       |
7514  *     +--+---+ +--+-+-+ +---+--+
7515  *     | subA | | subB | | subC |
7516  *     +--+---+ +------+ +---+--+
7517  *        ^                  ^
7518  *        |                  |
7519  *    +---+-------+   +------+----+
7520  *    |   mainA   |   |   mainB   |
7521  *    +-----------+   +-----------+
7522  *
7523  * We'll start relocating mainA, will find subA, append it and start
7524  * processing sub A recursively:
7525  *
7526  *    +-----------+------+
7527  *    |   mainA   | subA |
7528  *    +-----------+------+
7529  *
7530  * At this point we notice that subB is used from subA, so we append it and
7531  * relocate (there are no further subcalls from subB):
7532  *
7533  *    +-----------+------+------+
7534  *    |   mainA   | subA | subB |
7535  *    +-----------+------+------+
7536  *
7537  * At this point, we relocate subA calls, then go one level up and finish with
7538  * relocation mainA calls. mainA is done.
7539  *
7540  * For mainB process is similar but results in different order. We start with
7541  * mainB and skip subA and subB, as mainB never calls them (at least
7542  * directly), but we see subC is needed, so we append and start processing it:
7543  *
7544  *    +-----------+------+
7545  *    |   mainB   | subC |
7546  *    +-----------+------+
7547  * Now we see subC needs subB, so we go back to it, append and relocate it:
7548  *
7549  *    +-----------+------+------+
7550  *    |   mainB   | subC | subB |
7551  *    +-----------+------+------+
7552  *
7553  * At this point we unwind recursion, relocate calls in subC, then in mainB.
7554  */
7555 static int
7556 bpf_object__relocate_calls(struct bpf_object *obj, struct bpf_program *prog)
7557 {
7558 	struct bpf_program *subprog;
7559 	int i, err;
7560 
7561 	/* mark all subprogs as not relocated (yet) within the context of
7562 	 * current main program
7563 	 */
7564 	for (i = 0; i < obj->nr_programs; i++) {
7565 		subprog = &obj->programs[i];
7566 		if (!prog_is_subprog(obj, subprog))
7567 			continue;
7568 
7569 		subprog->sub_insn_off = 0;
7570 	}
7571 
7572 	err = bpf_object__reloc_code(obj, prog, prog);
7573 	if (err)
7574 		return err;
7575 
7576 	return bpf_object__append_func_ptrs(obj, prog);
7577 }
7578 
7579 static void
7580 bpf_object__free_relocs(struct bpf_object *obj)
7581 {
7582 	struct bpf_program *prog;
7583 	int i;
7584 
7585 	/* free up relocation descriptors */
7586 	for (i = 0; i < obj->nr_programs; i++) {
7587 		prog = &obj->programs[i];
7588 		zfree(&prog->reloc_desc);
7589 		prog->nr_reloc = 0;
7590 	}
7591 }
7592 
7593 static int cmp_relocs(const void *_a, const void *_b)
7594 {
7595 	const struct reloc_desc *a = _a;
7596 	const struct reloc_desc *b = _b;
7597 
7598 	if (a->insn_idx != b->insn_idx)
7599 		return a->insn_idx < b->insn_idx ? -1 : 1;
7600 
7601 	/* no two relocations should have the same insn_idx, but ... */
7602 	if (a->type != b->type)
7603 		return a->type < b->type ? -1 : 1;
7604 
7605 	return 0;
7606 }
7607 
7608 static void bpf_object__sort_relos(struct bpf_object *obj)
7609 {
7610 	int i;
7611 
7612 	for (i = 0; i < obj->nr_programs; i++) {
7613 		struct bpf_program *p = &obj->programs[i];
7614 
7615 		if (!p->nr_reloc)
7616 			continue;
7617 
7618 		qsort(p->reloc_desc, p->nr_reloc, sizeof(*p->reloc_desc), cmp_relocs);
7619 	}
7620 }
7621 
7622 static int bpf_prog_assign_exc_cb(struct bpf_object *obj, struct bpf_program *prog)
7623 {
7624 	const char *str = "exception_callback:";
7625 	size_t pfx_len = strlen(str);
7626 	int i, j, n;
7627 
7628 	if (!obj->btf || !kernel_supports(obj, FEAT_BTF_DECL_TAG))
7629 		return 0;
7630 
7631 	n = btf__type_cnt(obj->btf);
7632 	for (i = 1; i < n; i++) {
7633 		const char *name;
7634 		struct btf_type *t;
7635 
7636 		t = btf_type_by_id(obj->btf, i);
7637 		if (!btf_is_decl_tag(t) || btf_decl_tag(t)->component_idx != -1)
7638 			continue;
7639 
7640 		name = btf__str_by_offset(obj->btf, t->name_off);
7641 		if (strncmp(name, str, pfx_len) != 0)
7642 			continue;
7643 
7644 		t = btf_type_by_id(obj->btf, t->type);
7645 		if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL) {
7646 			pr_warn("prog '%s': exception_callback:<value> decl tag not applied to the main program\n",
7647 				prog->name);
7648 			return -EINVAL;
7649 		}
7650 		if (strcmp(prog->name, btf__str_by_offset(obj->btf, t->name_off)) != 0)
7651 			continue;
7652 		/* Multiple callbacks are specified for the same prog,
7653 		 * the verifier will eventually return an error for this
7654 		 * case, hence simply skip appending a subprog.
7655 		 */
7656 		if (prog->exception_cb_idx >= 0) {
7657 			prog->exception_cb_idx = -1;
7658 			break;
7659 		}
7660 
7661 		name += pfx_len;
7662 		if (str_is_empty(name)) {
7663 			pr_warn("prog '%s': exception_callback:<value> decl tag contains empty value\n",
7664 				prog->name);
7665 			return -EINVAL;
7666 		}
7667 
7668 		for (j = 0; j < obj->nr_programs; j++) {
7669 			struct bpf_program *subprog = &obj->programs[j];
7670 
7671 			if (!prog_is_subprog(obj, subprog))
7672 				continue;
7673 			if (strcmp(name, subprog->name) != 0)
7674 				continue;
7675 			/* Enforce non-hidden, as from verifier point of
7676 			 * view it expects global functions, whereas the
7677 			 * mark_btf_static fixes up linkage as static.
7678 			 */
7679 			if (!subprog->sym_global || subprog->mark_btf_static) {
7680 				pr_warn("prog '%s': exception callback %s must be a global non-hidden function\n",
7681 					prog->name, subprog->name);
7682 				return -EINVAL;
7683 			}
7684 			/* Let's see if we already saw a static exception callback with the same name */
7685 			if (prog->exception_cb_idx >= 0) {
7686 				pr_warn("prog '%s': multiple subprogs with same name as exception callback '%s'\n",
7687 					prog->name, subprog->name);
7688 				return -EINVAL;
7689 			}
7690 			prog->exception_cb_idx = j;
7691 			break;
7692 		}
7693 
7694 		if (prog->exception_cb_idx >= 0)
7695 			continue;
7696 
7697 		pr_warn("prog '%s': cannot find exception callback '%s'\n", prog->name, name);
7698 		return -ENOENT;
7699 	}
7700 
7701 	return 0;
7702 }
7703 
7704 static struct {
7705 	enum bpf_prog_type prog_type;
7706 	const char *ctx_name;
7707 } global_ctx_map[] = {
7708 	{ BPF_PROG_TYPE_CGROUP_DEVICE,           "bpf_cgroup_dev_ctx" },
7709 	{ BPF_PROG_TYPE_CGROUP_SKB,              "__sk_buff" },
7710 	{ BPF_PROG_TYPE_CGROUP_SOCK,             "bpf_sock" },
7711 	{ BPF_PROG_TYPE_CGROUP_SOCK_ADDR,        "bpf_sock_addr" },
7712 	{ BPF_PROG_TYPE_CGROUP_SOCKOPT,          "bpf_sockopt" },
7713 	{ BPF_PROG_TYPE_CGROUP_SYSCTL,           "bpf_sysctl" },
7714 	{ BPF_PROG_TYPE_FLOW_DISSECTOR,          "__sk_buff" },
7715 	{ BPF_PROG_TYPE_KPROBE,                  "bpf_user_pt_regs_t" },
7716 	{ BPF_PROG_TYPE_LWT_IN,                  "__sk_buff" },
7717 	{ BPF_PROG_TYPE_LWT_OUT,                 "__sk_buff" },
7718 	{ BPF_PROG_TYPE_LWT_SEG6LOCAL,           "__sk_buff" },
7719 	{ BPF_PROG_TYPE_LWT_XMIT,                "__sk_buff" },
7720 	{ BPF_PROG_TYPE_NETFILTER,               "bpf_nf_ctx" },
7721 	{ BPF_PROG_TYPE_PERF_EVENT,              "bpf_perf_event_data" },
7722 	{ BPF_PROG_TYPE_RAW_TRACEPOINT,          "bpf_raw_tracepoint_args" },
7723 	{ BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE, "bpf_raw_tracepoint_args" },
7724 	{ BPF_PROG_TYPE_SCHED_ACT,               "__sk_buff" },
7725 	{ BPF_PROG_TYPE_SCHED_CLS,               "__sk_buff" },
7726 	{ BPF_PROG_TYPE_SK_LOOKUP,               "bpf_sk_lookup" },
7727 	{ BPF_PROG_TYPE_SK_MSG,                  "sk_msg_md" },
7728 	{ BPF_PROG_TYPE_SK_REUSEPORT,            "sk_reuseport_md" },
7729 	{ BPF_PROG_TYPE_SK_SKB,                  "__sk_buff" },
7730 	{ BPF_PROG_TYPE_SOCK_OPS,                "bpf_sock_ops" },
7731 	{ BPF_PROG_TYPE_SOCKET_FILTER,           "__sk_buff" },
7732 	{ BPF_PROG_TYPE_XDP,                     "xdp_md" },
7733 	/* all other program types don't have "named" context structs */
7734 };
7735 
7736 /* forward declarations for arch-specific underlying types of bpf_user_pt_regs_t typedef,
7737  * for below __builtin_types_compatible_p() checks;
7738  * with this approach we don't need any extra arch-specific #ifdef guards
7739  */
7740 struct pt_regs;
7741 struct user_pt_regs;
7742 struct user_regs_struct;
7743 
7744 static bool need_func_arg_type_fixup(const struct btf *btf, const struct bpf_program *prog,
7745 				     const char *subprog_name, int arg_idx,
7746 				     int arg_type_id, const char *ctx_name)
7747 {
7748 	const struct btf_type *t;
7749 	const char *tname;
7750 
7751 	/* check if existing parameter already matches verifier expectations */
7752 	t = skip_mods_and_typedefs(btf, arg_type_id, NULL);
7753 	if (!btf_is_ptr(t))
7754 		goto out_warn;
7755 
7756 	/* typedef bpf_user_pt_regs_t is a special PITA case, valid for kprobe
7757 	 * and perf_event programs, so check this case early on and forget
7758 	 * about it for subsequent checks
7759 	 */
7760 	while (btf_is_mod(t))
7761 		t = btf__type_by_id(btf, t->type);
7762 	if (btf_is_typedef(t) &&
7763 	    (prog->type == BPF_PROG_TYPE_KPROBE || prog->type == BPF_PROG_TYPE_PERF_EVENT)) {
7764 		tname = btf__str_by_offset(btf, t->name_off) ?: "<anon>";
7765 		if (strcmp(tname, "bpf_user_pt_regs_t") == 0)
7766 			return false; /* canonical type for kprobe/perf_event */
7767 	}
7768 
7769 	/* now we can ignore typedefs moving forward */
7770 	t = skip_mods_and_typedefs(btf, t->type, NULL);
7771 
7772 	/* if it's `void *`, definitely fix up BTF info */
7773 	if (btf_is_void(t))
7774 		return true;
7775 
7776 	/* if it's already proper canonical type, no need to fix up */
7777 	tname = btf__str_by_offset(btf, t->name_off) ?: "<anon>";
7778 	if (btf_is_struct(t) && strcmp(tname, ctx_name) == 0)
7779 		return false;
7780 
7781 	/* special cases */
7782 	switch (prog->type) {
7783 	case BPF_PROG_TYPE_KPROBE:
7784 		/* `struct pt_regs *` is expected, but we need to fix up */
7785 		if (btf_is_struct(t) && strcmp(tname, "pt_regs") == 0)
7786 			return true;
7787 		break;
7788 	case BPF_PROG_TYPE_PERF_EVENT:
7789 		if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct pt_regs) &&
7790 		    btf_is_struct(t) && strcmp(tname, "pt_regs") == 0)
7791 			return true;
7792 		if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct user_pt_regs) &&
7793 		    btf_is_struct(t) && strcmp(tname, "user_pt_regs") == 0)
7794 			return true;
7795 		if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct user_regs_struct) &&
7796 		    btf_is_struct(t) && strcmp(tname, "user_regs_struct") == 0)
7797 			return true;
7798 		break;
7799 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
7800 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
7801 		/* allow u64* as ctx */
7802 		if (btf_is_int(t) && t->size == 8)
7803 			return true;
7804 		break;
7805 	default:
7806 		break;
7807 	}
7808 
7809 out_warn:
7810 	pr_warn("prog '%s': subprog '%s' arg#%d is expected to be of `struct %s *` type\n",
7811 		prog->name, subprog_name, arg_idx, ctx_name);
7812 	return false;
7813 }
7814 
7815 static int clone_func_btf_info(struct btf *btf, int orig_fn_id, struct bpf_program *prog)
7816 {
7817 	int fn_id, fn_proto_id, ret_type_id, orig_proto_id;
7818 	int i, err, arg_cnt, fn_name_off, linkage;
7819 	struct btf_type *fn_t, *fn_proto_t, *t;
7820 	struct btf_param *p;
7821 
7822 	/* caller already validated FUNC -> FUNC_PROTO validity */
7823 	fn_t = btf_type_by_id(btf, orig_fn_id);
7824 	fn_proto_t = btf_type_by_id(btf, fn_t->type);
7825 
7826 	/* Note that each btf__add_xxx() operation invalidates
7827 	 * all btf_type and string pointers, so we need to be
7828 	 * very careful when cloning BTF types. BTF type
7829 	 * pointers have to be always refetched. And to avoid
7830 	 * problems with invalidated string pointers, we
7831 	 * add empty strings initially, then just fix up
7832 	 * name_off offsets in place. Offsets are stable for
7833 	 * existing strings, so that works out.
7834 	 */
7835 	fn_name_off = fn_t->name_off; /* we are about to invalidate fn_t */
7836 	linkage = btf_func_linkage(fn_t);
7837 	orig_proto_id = fn_t->type; /* original FUNC_PROTO ID */
7838 	ret_type_id = fn_proto_t->type; /* fn_proto_t will be invalidated */
7839 	arg_cnt = btf_vlen(fn_proto_t);
7840 
7841 	/* clone FUNC_PROTO and its params */
7842 	fn_proto_id = btf__add_func_proto(btf, ret_type_id);
7843 	if (fn_proto_id < 0)
7844 		return -EINVAL;
7845 
7846 	for (i = 0; i < arg_cnt; i++) {
7847 		int name_off;
7848 
7849 		/* copy original parameter data */
7850 		t = btf_type_by_id(btf, orig_proto_id);
7851 		p = &btf_params(t)[i];
7852 		name_off = p->name_off;
7853 
7854 		err = btf__add_func_param(btf, "", p->type);
7855 		if (err)
7856 			return err;
7857 
7858 		fn_proto_t = btf_type_by_id(btf, fn_proto_id);
7859 		p = &btf_params(fn_proto_t)[i];
7860 		p->name_off = name_off; /* use remembered str offset */
7861 	}
7862 
7863 	/* clone FUNC now, btf__add_func() enforces non-empty name, so use
7864 	 * entry program's name as a placeholder, which we replace immediately
7865 	 * with original name_off
7866 	 */
7867 	fn_id = btf__add_func(btf, prog->name, linkage, fn_proto_id);
7868 	if (fn_id < 0)
7869 		return -EINVAL;
7870 
7871 	fn_t = btf_type_by_id(btf, fn_id);
7872 	fn_t->name_off = fn_name_off; /* reuse original string */
7873 
7874 	return fn_id;
7875 }
7876 
7877 /* Check if main program or global subprog's function prototype has `arg:ctx`
7878  * argument tags, and, if necessary, substitute correct type to match what BPF
7879  * verifier would expect, taking into account specific program type. This
7880  * allows to support __arg_ctx tag transparently on old kernels that don't yet
7881  * have a native support for it in the verifier, making user's life much
7882  * easier.
7883  */
7884 static int bpf_program_fixup_func_info(struct bpf_object *obj, struct bpf_program *prog)
7885 {
7886 	const char *ctx_name = NULL, *ctx_tag = "arg:ctx", *fn_name;
7887 	struct bpf_func_info_min *func_rec;
7888 	struct btf_type *fn_t, *fn_proto_t;
7889 	struct btf *btf = obj->btf;
7890 	const struct btf_type *t;
7891 	struct btf_param *p;
7892 	int ptr_id = 0, struct_id, tag_id, orig_fn_id;
7893 	int i, n, arg_idx, arg_cnt, err, rec_idx;
7894 	int *orig_ids;
7895 
7896 	/* no .BTF.ext, no problem */
7897 	if (!obj->btf_ext || !prog->func_info)
7898 		return 0;
7899 
7900 	/* don't do any fix ups if kernel natively supports __arg_ctx */
7901 	if (kernel_supports(obj, FEAT_ARG_CTX_TAG))
7902 		return 0;
7903 
7904 	/* some BPF program types just don't have named context structs, so
7905 	 * this fallback mechanism doesn't work for them
7906 	 */
7907 	for (i = 0; i < ARRAY_SIZE(global_ctx_map); i++) {
7908 		if (global_ctx_map[i].prog_type != prog->type)
7909 			continue;
7910 		ctx_name = global_ctx_map[i].ctx_name;
7911 		break;
7912 	}
7913 	if (!ctx_name)
7914 		return 0;
7915 
7916 	/* remember original func BTF IDs to detect if we already cloned them */
7917 	orig_ids = calloc(prog->func_info_cnt, sizeof(*orig_ids));
7918 	if (!orig_ids)
7919 		return -ENOMEM;
7920 	for (i = 0; i < prog->func_info_cnt; i++) {
7921 		func_rec = prog->func_info + prog->func_info_rec_size * i;
7922 		orig_ids[i] = func_rec->type_id;
7923 	}
7924 
7925 	/* go through each DECL_TAG with "arg:ctx" and see if it points to one
7926 	 * of our subprogs; if yes and subprog is global and needs adjustment,
7927 	 * clone and adjust FUNC -> FUNC_PROTO combo
7928 	 */
7929 	for (i = 1, n = btf__type_cnt(btf); i < n; i++) {
7930 		/* only DECL_TAG with "arg:ctx" value are interesting */
7931 		t = btf__type_by_id(btf, i);
7932 		if (!btf_is_decl_tag(t))
7933 			continue;
7934 		if (strcmp(btf__str_by_offset(btf, t->name_off), ctx_tag) != 0)
7935 			continue;
7936 
7937 		/* only global funcs need adjustment, if at all */
7938 		orig_fn_id = t->type;
7939 		fn_t = btf_type_by_id(btf, orig_fn_id);
7940 		if (!btf_is_func(fn_t) || btf_func_linkage(fn_t) != BTF_FUNC_GLOBAL)
7941 			continue;
7942 
7943 		/* sanity check FUNC -> FUNC_PROTO chain, just in case */
7944 		fn_proto_t = btf_type_by_id(btf, fn_t->type);
7945 		if (!fn_proto_t || !btf_is_func_proto(fn_proto_t))
7946 			continue;
7947 
7948 		/* find corresponding func_info record */
7949 		func_rec = NULL;
7950 		for (rec_idx = 0; rec_idx < prog->func_info_cnt; rec_idx++) {
7951 			if (orig_ids[rec_idx] == t->type) {
7952 				func_rec = prog->func_info + prog->func_info_rec_size * rec_idx;
7953 				break;
7954 			}
7955 		}
7956 		/* current main program doesn't call into this subprog */
7957 		if (!func_rec)
7958 			continue;
7959 
7960 		/* some more sanity checking of DECL_TAG */
7961 		arg_cnt = btf_vlen(fn_proto_t);
7962 		arg_idx = btf_decl_tag(t)->component_idx;
7963 		if (arg_idx < 0 || arg_idx >= arg_cnt)
7964 			continue;
7965 
7966 		/* check if we should fix up argument type */
7967 		p = &btf_params(fn_proto_t)[arg_idx];
7968 		fn_name = btf__str_by_offset(btf, fn_t->name_off) ?: "<anon>";
7969 		if (!need_func_arg_type_fixup(btf, prog, fn_name, arg_idx, p->type, ctx_name))
7970 			continue;
7971 
7972 		/* clone fn/fn_proto, unless we already did it for another arg */
7973 		if (func_rec->type_id == orig_fn_id) {
7974 			int fn_id;
7975 
7976 			fn_id = clone_func_btf_info(btf, orig_fn_id, prog);
7977 			if (fn_id < 0) {
7978 				err = fn_id;
7979 				goto err_out;
7980 			}
7981 
7982 			/* point func_info record to a cloned FUNC type */
7983 			func_rec->type_id = fn_id;
7984 		}
7985 
7986 		/* create PTR -> STRUCT type chain to mark PTR_TO_CTX argument;
7987 		 * we do it just once per main BPF program, as all global
7988 		 * funcs share the same program type, so need only PTR ->
7989 		 * STRUCT type chain
7990 		 */
7991 		if (ptr_id == 0) {
7992 			struct_id = btf__add_struct(btf, ctx_name, 0);
7993 			ptr_id = btf__add_ptr(btf, struct_id);
7994 			if (ptr_id < 0 || struct_id < 0) {
7995 				err = -EINVAL;
7996 				goto err_out;
7997 			}
7998 		}
7999 
8000 		/* for completeness, clone DECL_TAG and point it to cloned param */
8001 		tag_id = btf__add_decl_tag(btf, ctx_tag, func_rec->type_id, arg_idx);
8002 		if (tag_id < 0) {
8003 			err = -EINVAL;
8004 			goto err_out;
8005 		}
8006 
8007 		/* all the BTF manipulations invalidated pointers, refetch them */
8008 		fn_t = btf_type_by_id(btf, func_rec->type_id);
8009 		fn_proto_t = btf_type_by_id(btf, fn_t->type);
8010 
8011 		/* fix up type ID pointed to by param */
8012 		p = &btf_params(fn_proto_t)[arg_idx];
8013 		p->type = ptr_id;
8014 	}
8015 
8016 	free(orig_ids);
8017 	return 0;
8018 err_out:
8019 	free(orig_ids);
8020 	return err;
8021 }
8022 
8023 /*
8024  * Turn pointers to data that are stored in data into addresses of arena.
8025  * The arena is created here, ahead of the other maps: the address has to be
8026  * known before the maps that hold the pointers are created.
8027  */
8028 static int bpf_object__relocate_data_ptrs(struct bpf_object *obj)
8029 {
8030 	struct bpf_map *arena, *map, *targ;
8031 	__u64 addr, val;
8032 	size_t i;
8033 	int err;
8034 
8035 	if (!obj->data_ptr_cnt)
8036 		return 0;
8037 
8038 	for (i = 0; i < obj->data_ptr_cnt; i++) {
8039 		struct data_ptr *p = &obj->data_ptrs[i];
8040 
8041 		if (p->targ_sec_idx < 0)
8042 			continue;
8043 		map = bpf_object__sec_map(obj, p->sec_idx);
8044 		targ = bpf_object__sec_map(obj, p->targ_sec_idx);
8045 		if (map && (map->in_arena || map->autocreate) &&
8046 		    (!targ || (!targ->in_arena && !targ->arena_copy))) {
8047 			pr_warn("sec '%s': pointer to '%s' at offset %zu can't be resolved: sec '%s' is not in arena\n",
8048 				map->real_name, p->sym_name, p->sec_off,
8049 				targ ? targ->real_name : "<?>");
8050 			return -LIBBPF_ERRNO__RELOC;
8051 		}
8052 	}
8053 
8054 	if (obj->gen_loader) {
8055 		pr_warn("pointers to data in data are not supported by light skeleton\n");
8056 		return -ENOTSUP;
8057 	}
8058 
8059 	if (obj->arena_map_idx < 0)
8060 		return 0;
8061 
8062 	arena = &obj->maps[obj->arena_map_idx];
8063 	if (!arena->autocreate)
8064 		return 0;
8065 	/* libbpf doesn't mmap an arena that it didn't create, so the address is not known */
8066 	if (arena->reused || arena->pin_path) {
8067 		pr_warn("map '%s': pointers to data in data are not supported with pinned or reused arena\n",
8068 			arena->name);
8069 		return -ENOTSUP;
8070 	}
8071 
8072 	err = bpf_object__create_map(obj, arena, false);
8073 	err = err ?: bpf_object__mmap_arena(obj, arena);
8074 	if (err) {
8075 		pr_warn("map '%s': failed to create: %s\n", arena->name, errstr(err));
8076 		return err;
8077 	}
8078 	obj->arena_mapped = true;
8079 
8080 	for (i = 0; i < obj->data_ptr_cnt; i++) {
8081 		struct data_ptr *p = &obj->data_ptrs[i];
8082 
8083 		map = bpf_object__sec_map(obj, p->sec_idx);
8084 		if (!map || (!map->in_arena && !map->autocreate))
8085 			continue;
8086 
8087 		addr = (__u64)(unsigned long)arena->mmaped + obj->arena_data_off + p->targ_off;
8088 		if (p->targ_sec_idx >= 0)
8089 			addr += bpf_object__sec_map(obj, p->targ_sec_idx)->arena_off;
8090 
8091 		memcpy(&val, map->mmaped + p->sec_off, sizeof(val));
8092 		val += addr;
8093 		memcpy(map->mmaped + p->sec_off, &val, sizeof(val));
8094 	}
8095 	return 0;
8096 }
8097 
8098 static int bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
8099 {
8100 	struct bpf_program *prog;
8101 	size_t i, j;
8102 	int err;
8103 
8104 	if (obj->btf_ext) {
8105 		err = bpf_object__relocate_core(obj, targ_btf_path);
8106 		if (err) {
8107 			pr_warn("failed to perform CO-RE relocations: %s\n",
8108 				errstr(err));
8109 			return err;
8110 		}
8111 		bpf_object__sort_relos(obj);
8112 	}
8113 
8114 	if (obj->arena_map_idx >= 0) {
8115 		struct bpf_map *arena_map = &obj->maps[obj->arena_map_idx];
8116 		size_t data_sz = roundup(obj->arena_data_sz, sysconf(_SC_PAGE_SIZE));
8117 		size_t mmap_sz = bpf_map_mmap_sz(arena_map);
8118 
8119 		if (data_sz > mmap_sz) {
8120 			pr_warn("map '%s': declared ARENA map size (%zu) is too small to hold global %s of size %zu\n",
8121 				arena_map->name, mmap_sz,
8122 				obj->data_in_arena ? "data" : "__arena variables",
8123 				obj->arena_data_sz);
8124 			return -E2BIG;
8125 		}
8126 
8127 		/* place globals at the end of the arena (if supported) */
8128 		if (kernel_supports(obj, FEAT_LDIMM64_FULL_RANGE_OFF))
8129 			obj->arena_data_off = mmap_sz - data_sz;
8130 	}
8131 
8132 	err = bpf_object__relocate_data_ptrs(obj);
8133 	if (err)
8134 		return err;
8135 
8136 	/* Before relocating calls pre-process relocations and mark
8137 	 * few ld_imm64 instructions that points to subprogs.
8138 	 * Otherwise bpf_object__reloc_code() later would have to consider
8139 	 * all ld_imm64 insns as relocation candidates. That would
8140 	 * reduce relocation speed, since amount of find_prog_insn_relo()
8141 	 * would increase and most of them will fail to find a relo.
8142 	 */
8143 	for (i = 0; i < obj->nr_programs; i++) {
8144 		prog = &obj->programs[i];
8145 		for (j = 0; j < prog->nr_reloc; j++) {
8146 			struct reloc_desc *relo = &prog->reloc_desc[j];
8147 			struct bpf_insn *insn = &prog->insns[relo->insn_idx];
8148 
8149 			/* mark the insn, so it's recognized by insn_is_pseudo_func() */
8150 			if (relo->type == RELO_SUBPROG_ADDR)
8151 				insn[0].src_reg = BPF_PSEUDO_FUNC;
8152 		}
8153 	}
8154 
8155 	/* relocate subprogram calls and append used subprograms to main
8156 	 * programs; each copy of subprogram code needs to be relocated
8157 	 * differently for each main program, because its code location might
8158 	 * have changed.
8159 	 * Append subprog relos to main programs to allow data relos to be
8160 	 * processed after text is completely relocated.
8161 	 */
8162 	for (i = 0; i < obj->nr_programs; i++) {
8163 		prog = &obj->programs[i];
8164 		/* sub-program's sub-calls are relocated within the context of
8165 		 * its main program only
8166 		 */
8167 		if (prog_is_subprog(obj, prog))
8168 			continue;
8169 		if (!prog->autoload)
8170 			continue;
8171 
8172 		err = bpf_object__relocate_calls(obj, prog);
8173 		if (err) {
8174 			pr_warn("prog '%s': failed to relocate calls: %s\n",
8175 				prog->name, errstr(err));
8176 			return err;
8177 		}
8178 
8179 		err = bpf_prog_assign_exc_cb(obj, prog);
8180 		if (err)
8181 			return err;
8182 		/* Now, also append exception callback if it has not been done already. */
8183 		if (prog->exception_cb_idx >= 0) {
8184 			struct bpf_program *subprog = &obj->programs[prog->exception_cb_idx];
8185 
8186 			/* Calling exception callback directly is disallowed, which the
8187 			 * verifier will reject later. In case it was processed already,
8188 			 * we can skip this step, otherwise for all other valid cases we
8189 			 * have to append exception callback now.
8190 			 */
8191 			if (subprog->sub_insn_off == 0) {
8192 				err = bpf_object__append_subprog_code(obj, prog, subprog);
8193 				if (err)
8194 					return err;
8195 				err = bpf_object__reloc_code(obj, prog, subprog);
8196 				if (err)
8197 					return err;
8198 			}
8199 		}
8200 	}
8201 	for (i = 0; i < obj->nr_programs; i++) {
8202 		prog = &obj->programs[i];
8203 		if (prog_is_subprog(obj, prog))
8204 			continue;
8205 		if (!prog->autoload)
8206 			continue;
8207 
8208 		/* Process data relos for main programs */
8209 		err = bpf_object__relocate_data(obj, prog);
8210 		if (err) {
8211 			pr_warn("prog '%s': failed to relocate data references: %s\n",
8212 				prog->name, errstr(err));
8213 			return err;
8214 		}
8215 
8216 		/* Fix up .BTF.ext information, if necessary */
8217 		err = bpf_program_fixup_func_info(obj, prog);
8218 		if (err) {
8219 			pr_warn("prog '%s': failed to perform .BTF.ext fix ups: %s\n",
8220 				prog->name, errstr(err));
8221 			return err;
8222 		}
8223 	}
8224 
8225 	return 0;
8226 }
8227 
8228 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
8229 					    Elf64_Shdr *shdr, Elf_Data *data);
8230 
8231 static int bpf_object__collect_map_relos(struct bpf_object *obj,
8232 					 Elf64_Shdr *shdr, Elf_Data *data)
8233 {
8234 	const int bpf_ptr_sz = 8, host_ptr_sz = sizeof(void *);
8235 	int i, j, nrels, new_sz;
8236 	const struct btf_var_secinfo *vi = NULL;
8237 	const struct btf_type *sec, *var, *def;
8238 	struct bpf_map *map = NULL, *targ_map = NULL;
8239 	struct bpf_program *targ_prog = NULL;
8240 	bool is_prog_array, is_map_in_map;
8241 	const struct btf_member *member;
8242 	const char *name, *mname, *type;
8243 	unsigned int moff;
8244 	Elf64_Sym *sym;
8245 	Elf64_Rel *rel;
8246 	void *tmp;
8247 
8248 	if (!obj->efile.btf_maps_sec_btf_id || !obj->btf)
8249 		return -EINVAL;
8250 	sec = btf__type_by_id(obj->btf, obj->efile.btf_maps_sec_btf_id);
8251 	if (!sec)
8252 		return -EINVAL;
8253 
8254 	nrels = shdr->sh_size / shdr->sh_entsize;
8255 	for (i = 0; i < nrels; i++) {
8256 		rel = elf_rel_by_idx(data, i);
8257 		if (!rel) {
8258 			pr_warn(".maps relo #%d: failed to get ELF relo\n", i);
8259 			return -LIBBPF_ERRNO__FORMAT;
8260 		}
8261 
8262 		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
8263 		if (!sym) {
8264 			pr_warn(".maps relo #%d: symbol %zx not found\n",
8265 				i, (size_t)ELF64_R_SYM(rel->r_info));
8266 			return -LIBBPF_ERRNO__FORMAT;
8267 		}
8268 		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
8269 
8270 		pr_debug(".maps relo #%d: for %zd value %zu rel->r_offset %zu name %u ('%s')\n",
8271 			 i, (ssize_t)(rel->r_info >> 32), (size_t)sym->st_value,
8272 			 (size_t)rel->r_offset, sym->st_name, name);
8273 
8274 		for (j = 0; j < obj->nr_maps; j++) {
8275 			map = &obj->maps[j];
8276 			if (map->sec_idx != obj->efile.btf_maps_shndx)
8277 				continue;
8278 
8279 			vi = btf_var_secinfos(sec) + map->btf_var_idx;
8280 			if (vi->offset <= rel->r_offset &&
8281 			    rel->r_offset + bpf_ptr_sz <= vi->offset + vi->size)
8282 				break;
8283 		}
8284 		if (j == obj->nr_maps) {
8285 			pr_warn(".maps relo #%d: cannot find map '%s' at rel->r_offset %zu\n",
8286 				i, name, (size_t)rel->r_offset);
8287 			return -EINVAL;
8288 		}
8289 
8290 		is_map_in_map = bpf_map_type__is_map_in_map(map->def.type);
8291 		is_prog_array = map->def.type == BPF_MAP_TYPE_PROG_ARRAY;
8292 		type = is_map_in_map ? "map" : "prog";
8293 		if (is_map_in_map) {
8294 			if (sym->st_shndx != obj->efile.btf_maps_shndx) {
8295 				pr_warn(".maps relo #%d: '%s' isn't a BTF-defined map\n",
8296 					i, name);
8297 				return -LIBBPF_ERRNO__RELOC;
8298 			}
8299 			if (map->def.type == BPF_MAP_TYPE_HASH_OF_MAPS &&
8300 			    map->def.key_size != sizeof(int)) {
8301 				pr_warn(".maps relo #%d: hash-of-maps '%s' should have key size %zu.\n",
8302 					i, map->name, sizeof(int));
8303 				return -EINVAL;
8304 			}
8305 			targ_map = bpf_object__find_map_by_name(obj, name);
8306 			if (!targ_map) {
8307 				pr_warn(".maps relo #%d: '%s' isn't a valid map reference\n",
8308 					i, name);
8309 				return -ESRCH;
8310 			}
8311 		} else if (is_prog_array) {
8312 			targ_prog = bpf_object__find_program_by_name(obj, name);
8313 			if (!targ_prog) {
8314 				pr_warn(".maps relo #%d: '%s' isn't a valid program reference\n",
8315 					i, name);
8316 				return -ESRCH;
8317 			}
8318 			if (targ_prog->sec_idx != sym->st_shndx ||
8319 			    targ_prog->sec_insn_off * 8 != sym->st_value ||
8320 			    prog_is_subprog(obj, targ_prog)) {
8321 				pr_warn(".maps relo #%d: '%s' isn't an entry-point program\n",
8322 					i, name);
8323 				return -LIBBPF_ERRNO__RELOC;
8324 			}
8325 		} else {
8326 			return -EINVAL;
8327 		}
8328 
8329 		var = btf__type_by_id(obj->btf, vi->type);
8330 		def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
8331 		if (btf_vlen(def) == 0)
8332 			return -EINVAL;
8333 		member = btf_members(def) + btf_vlen(def) - 1;
8334 		mname = btf__name_by_offset(obj->btf, member->name_off);
8335 		if (strcmp(mname, "values"))
8336 			return -EINVAL;
8337 
8338 		moff = btf_member_bit_offset(def, btf_vlen(def) - 1) / 8;
8339 		if (rel->r_offset - vi->offset < moff)
8340 			return -EINVAL;
8341 
8342 		moff = rel->r_offset - vi->offset - moff;
8343 		/* here we use BPF pointer size, which is always 64 bit, as we
8344 		 * are parsing ELF that was built for BPF target
8345 		 */
8346 		if (moff % bpf_ptr_sz)
8347 			return -EINVAL;
8348 		moff /= bpf_ptr_sz;
8349 		if (moff >= map->init_slots_sz) {
8350 			new_sz = moff + 1;
8351 			tmp = libbpf_reallocarray(map->init_slots, new_sz, host_ptr_sz);
8352 			if (!tmp)
8353 				return -ENOMEM;
8354 			map->init_slots = tmp;
8355 			memset(map->init_slots + map->init_slots_sz, 0,
8356 			       (new_sz - map->init_slots_sz) * host_ptr_sz);
8357 			map->init_slots_sz = new_sz;
8358 		}
8359 		map->init_slots[moff] = is_map_in_map ? (void *)targ_map : (void *)targ_prog;
8360 
8361 		pr_debug(".maps relo #%d: map '%s' slot [%u] points to %s '%s'\n",
8362 			 i, map->name, moff, type, name);
8363 	}
8364 
8365 	return 0;
8366 }
8367 
8368 /*
8369  * A pointer to data that is stored in data. When data is in arena
8370  * the program dereferences what it loads from data, so the pointer has
8371  * to be the address of the target in arena.
8372  */
8373 static int bpf_object__collect_data_ptr(struct bpf_object *obj, const char *relo_sec_name,
8374 					int relo_idx, size_t sec_idx, const Elf64_Rel *rel,
8375 					const Elf64_Sym *sym)
8376 {
8377 	Elf_Data *scn_data = obj->efile.secs[sec_idx].data;
8378 	const char *sym_name = elf_sym_str(obj, sym->st_name) ?: "<?>";
8379 	struct data_ptr *ptrs;
8380 
8381 	if (ELF64_ST_TYPE(sym->st_info) == STT_SECTION && sym->st_shndx < obj->efile.sec_cnt)
8382 		sym_name = elf_sec_name(obj, elf_sec_by_idx(obj, sym->st_shndx)) ?: "<?>";
8383 
8384 	if (ELF64_R_TYPE(rel->r_info) != R_BPF_64_ABS64 ||
8385 	    sym->st_shndx >= obj->efile.sec_cnt ||
8386 	    (sym->st_shndx != obj->efile.arena_data_shndx &&
8387 	     !bpf_object__shndx_is_data(obj, sym->st_shndx)) ||
8388 	    rel->r_offset >= scn_data->d_size ||
8389 	    scn_data->d_size - rel->r_offset < sizeof(__u64)) {
8390 		pr_warn("sec '%s': relo #%d: can't resolve pointer to '%s' at offset %zu when data is in arena\n",
8391 			relo_sec_name, relo_idx, sym_name, (size_t)rel->r_offset);
8392 		return -LIBBPF_ERRNO__RELOC;
8393 	}
8394 
8395 	ptrs = libbpf_reallocarray(obj->data_ptrs, obj->data_ptr_cnt + 1, sizeof(*ptrs));
8396 	if (!ptrs)
8397 		return -ENOMEM;
8398 	obj->data_ptrs = ptrs;
8399 
8400 	ptrs[obj->data_ptr_cnt].sec_idx = sec_idx;
8401 	ptrs[obj->data_ptr_cnt].sec_off = rel->r_offset;
8402 	/* __arena variables are at the start of arena data */
8403 	ptrs[obj->data_ptr_cnt].targ_sec_idx =
8404 		sym->st_shndx == obj->efile.arena_data_shndx ? -1 : sym->st_shndx;
8405 	ptrs[obj->data_ptr_cnt].targ_off = sym->st_value;
8406 	ptrs[obj->data_ptr_cnt].sym_name = strdup(sym_name);
8407 	if (!ptrs[obj->data_ptr_cnt].sym_name)
8408 		return -ENOMEM;
8409 	obj->data_ptr_cnt++;
8410 
8411 	pr_debug("sec '%s': relo #%d: pointer at offset %zu to '%s'\n",
8412 		 relo_sec_name, relo_idx, (size_t)rel->r_offset, sym_name);
8413 	return 0;
8414 }
8415 
8416 /* Collect pointers in a data section that went to arena */
8417 static int bpf_object__collect_data_relos(struct bpf_object *obj,
8418 					  Elf64_Shdr *shdr, Elf_Data *data)
8419 {
8420 	int i, err, nrels = shdr->sh_size / shdr->sh_entsize;
8421 	const char *relo_sec_name;
8422 	Elf64_Sym *sym;
8423 	Elf64_Rel *rel;
8424 
8425 	relo_sec_name = elf_sec_str(obj, shdr->sh_name) ?: "<?>";
8426 	for (i = 0; i < nrels; i++) {
8427 		rel = elf_rel_by_idx(data, i);
8428 		sym = rel ? elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info)) : NULL;
8429 		if (!sym) {
8430 			pr_warn("sec '%s': failed to get relo #%d\n", relo_sec_name, i);
8431 			return -LIBBPF_ERRNO__FORMAT;
8432 		}
8433 		err = bpf_object__collect_data_ptr(obj, relo_sec_name, i, shdr->sh_info, rel, sym);
8434 		if (err)
8435 			return err;
8436 	}
8437 	return 0;
8438 }
8439 
8440 /*
8441  * Collect pointers to functions in a read-only data section. They are
8442  * R_BPF_64_ABS64 relocations against .text section, where the offset of
8443  * a static function in the section is stored in place. Relocations in data
8444  * sections were ignored before pointers to functions were supported. Those
8445  * that are something else, e.g. pointers to data, still are, unless data
8446  * is in arena.
8447  */
8448 static int bpf_object__collect_rodata_relos(struct bpf_object *obj,
8449 					    Elf64_Shdr *shdr, Elf_Data *data)
8450 {
8451 	size_t sec_idx = shdr->sh_info, sym_idx;
8452 	int i, nrels = shdr->sh_size / shdr->sh_entsize;
8453 	const char *relo_sec_name;
8454 	struct func_ptr *ptrs;
8455 	Elf_Data *scn_data;
8456 	Elf64_Sym *sym;
8457 	Elf64_Rel *rel;
8458 	__u64 addend;
8459 
8460 	relo_sec_name = elf_sec_str(obj, shdr->sh_name) ?: "<?>";
8461 	scn_data = obj->efile.secs[sec_idx].data;
8462 	if (!scn_data)
8463 		return -LIBBPF_ERRNO__FORMAT;
8464 
8465 	for (i = 0; i < nrels; i++) {
8466 		rel = elf_rel_by_idx(data, i);
8467 		if (!rel) {
8468 			pr_warn("sec '%s': failed to get relo #%d\n", relo_sec_name, i);
8469 			return -LIBBPF_ERRNO__FORMAT;
8470 		}
8471 
8472 		sym_idx = ELF64_R_SYM(rel->r_info);
8473 		sym = elf_sym_by_idx(obj, sym_idx);
8474 		if (!sym) {
8475 			pr_warn("sec '%s': symbol #%zu not found for relo #%d\n",
8476 				relo_sec_name, sym_idx, i);
8477 			return -LIBBPF_ERRNO__FORMAT;
8478 		}
8479 
8480 		if (ELF64_R_TYPE(rel->r_info) != R_BPF_64_ABS64 ||
8481 		    !sym_is_subprog(sym, obj->efile.text_shndx)) {
8482 			int err;
8483 
8484 			if (obj->data_in_arena) {
8485 				err = bpf_object__collect_data_ptr(obj, relo_sec_name, i,
8486 								   sec_idx, rel, sym);
8487 				if (err)
8488 					return err;
8489 				continue;
8490 			}
8491 			pr_debug("sec '%s': relo #%d: not a pointer to a function, skipping...\n",
8492 				 relo_sec_name, i);
8493 			continue;
8494 		}
8495 
8496 		/* the kernel finds aligned pointers only */
8497 		if (rel->r_offset % sizeof(__u64) || rel->r_offset >= scn_data->d_size ||
8498 		    scn_data->d_size - rel->r_offset < sizeof(__u64)) {
8499 			pr_debug("sec '%s': relo #%d: unsupported offset 0x%zx, skipping...\n",
8500 				 relo_sec_name, i, (size_t)rel->r_offset);
8501 			continue;
8502 		}
8503 
8504 		memcpy(&addend, scn_data->d_buf + rel->r_offset, sizeof(addend));
8505 		if (!is_native_endianness(obj))
8506 			addend = bswap_64(addend);
8507 		if ((sym->st_value + addend) % BPF_INSN_SZ) {
8508 			pr_debug("sec '%s': relo #%d: bad pointer to a function at offset %zu+%llu, skipping...\n",
8509 				 relo_sec_name, i, (size_t)sym->st_value,
8510 				 (unsigned long long)addend);
8511 			continue;
8512 		}
8513 
8514 		ptrs = libbpf_reallocarray(obj->func_ptrs, obj->func_ptr_cnt + 1, sizeof(*ptrs));
8515 		if (!ptrs)
8516 			return -ENOMEM;
8517 		obj->func_ptrs = ptrs;
8518 
8519 		ptrs[obj->func_ptr_cnt].sec_idx = sec_idx;
8520 		ptrs[obj->func_ptr_cnt].sec_off = rel->r_offset;
8521 		ptrs[obj->func_ptr_cnt].text_off = sym->st_value + addend;
8522 		obj->func_ptr_cnt++;
8523 
8524 		pr_debug("sec '%s': relo #%d: pointer at offset %zu to a function at .text+%zu\n",
8525 			 relo_sec_name, i, (size_t)rel->r_offset, (size_t)(sym->st_value + addend));
8526 	}
8527 	return 0;
8528 }
8529 
8530 static int cmp_func_ptrs(const void *_a, const void *_b)
8531 {
8532 	const struct func_ptr *a = _a;
8533 	const struct func_ptr *b = _b;
8534 
8535 	if (a->sec_idx != b->sec_idx)
8536 		return a->sec_idx < b->sec_idx ? -1 : 1;
8537 	if (a->sec_off != b->sec_off)
8538 		return a->sec_off < b->sec_off ? -1 : 1;
8539 	return 0;
8540 }
8541 
8542 static int bpf_object__collect_relos(struct bpf_object *obj)
8543 {
8544 	int i, err;
8545 
8546 	for (i = 0; i < obj->efile.sec_cnt; i++) {
8547 		struct elf_sec_desc *sec_desc = &obj->efile.secs[i];
8548 		Elf64_Shdr *shdr;
8549 		Elf_Data *data;
8550 		int idx;
8551 
8552 		if (sec_desc->sec_type != SEC_RELO)
8553 			continue;
8554 
8555 		shdr = sec_desc->shdr;
8556 		data = sec_desc->data;
8557 		idx = shdr->sh_info;
8558 
8559 		if (shdr->sh_type != SHT_REL || idx < 0 || idx >= obj->efile.sec_cnt) {
8560 			pr_warn("internal error at %d\n", __LINE__);
8561 			return -LIBBPF_ERRNO__INTERNAL;
8562 		}
8563 
8564 		if (obj->efile.secs[idx].sec_type == SEC_RODATA)
8565 			err = bpf_object__collect_rodata_relos(obj, shdr, data);
8566 		else if (obj->efile.secs[idx].sec_type == SEC_DATA)
8567 			err = bpf_object__collect_data_relos(obj, shdr, data);
8568 		else if (obj->efile.secs[idx].sec_type == SEC_ST_OPS)
8569 			err = bpf_object__collect_st_ops_relos(obj, shdr, data);
8570 		else if (idx == obj->efile.btf_maps_shndx)
8571 			err = bpf_object__collect_map_relos(obj, shdr, data);
8572 		else
8573 			err = bpf_object__collect_prog_relos(obj, shdr, data);
8574 		if (err)
8575 			return err;
8576 	}
8577 
8578 	/* sort by section, so that pointers in the data of a map are next to each other */
8579 	if (obj->func_ptr_cnt)
8580 		qsort(obj->func_ptrs, obj->func_ptr_cnt, sizeof(*obj->func_ptrs), cmp_func_ptrs);
8581 
8582 	for (i = 0; i < obj->nr_maps; i++) {
8583 		struct bpf_map *map = &obj->maps[i];
8584 		size_t j;
8585 
8586 		if (map->libbpf_type != LIBBPF_MAP_RODATA)
8587 			continue;
8588 		for (j = 0; j < obj->func_ptr_cnt; j++) {
8589 			if (obj->func_ptrs[j].sec_idx != map->sec_idx)
8590 				continue;
8591 			if (!map->func_ptr_cnt)
8592 				map->func_ptrs = &obj->func_ptrs[j];
8593 			map->func_ptr_cnt++;
8594 		}
8595 	}
8596 
8597 	bpf_object__sort_relos(obj);
8598 	return 0;
8599 }
8600 
8601 static bool insn_is_helper_call(struct bpf_insn *insn, enum bpf_func_id *func_id)
8602 {
8603 	if (BPF_CLASS(insn->code) == BPF_JMP &&
8604 	    BPF_OP(insn->code) == BPF_CALL &&
8605 	    BPF_SRC(insn->code) == BPF_K &&
8606 	    insn->src_reg == 0 &&
8607 	    insn->dst_reg == 0) {
8608 		    *func_id = insn->imm;
8609 		    return true;
8610 	}
8611 	return false;
8612 }
8613 
8614 static int bpf_object__sanitize_prog(struct bpf_object *obj, struct bpf_program *prog)
8615 {
8616 	struct bpf_insn *insn = prog->insns;
8617 	enum bpf_func_id func_id;
8618 	int i;
8619 
8620 	if (obj->gen_loader)
8621 		return 0;
8622 
8623 	for (i = 0; i < prog->insns_cnt; i++, insn++) {
8624 		if (!insn_is_helper_call(insn, &func_id))
8625 			continue;
8626 
8627 		/* on kernels that don't yet support
8628 		 * bpf_probe_read_{kernel,user}[_str] helpers, fall back
8629 		 * to bpf_probe_read() which works well for old kernels
8630 		 */
8631 		switch (func_id) {
8632 		case BPF_FUNC_probe_read_kernel:
8633 		case BPF_FUNC_probe_read_user:
8634 			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
8635 				insn->imm = BPF_FUNC_probe_read;
8636 			break;
8637 		case BPF_FUNC_probe_read_kernel_str:
8638 		case BPF_FUNC_probe_read_user_str:
8639 			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
8640 				insn->imm = BPF_FUNC_probe_read_str;
8641 			break;
8642 		default:
8643 			break;
8644 		}
8645 	}
8646 	return 0;
8647 }
8648 
8649 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
8650 				     int *btf_obj_fd, int *btf_type_id);
8651 
8652 static inline bool is_tracing_multi(enum bpf_attach_type type)
8653 {
8654 	return type == BPF_TRACE_FENTRY_MULTI || type == BPF_TRACE_FEXIT_MULTI ||
8655 	       type == BPF_TRACE_FSESSION_MULTI;
8656 }
8657 
8658 static const struct module_btf *find_attach_module(struct bpf_object *obj, const char *attach)
8659 {
8660 	const char *sep, *mod_name = NULL;
8661 	int i, mod_len, err;
8662 
8663 	/*
8664 	 * We expect attach string in the form of either
8665 	 * - function_pattern or
8666 	 * - <module>:function_pattern
8667 	 */
8668 	sep = strchr(attach, ':');
8669 	if (sep) {
8670 		mod_name = attach;
8671 		mod_len = sep - mod_name;
8672 	}
8673 	if (!mod_name)
8674 		return NULL;
8675 
8676 	err = load_module_btfs(obj);
8677 	if (err)
8678 		return NULL;
8679 
8680 	for (i = 0; i < obj->btf_module_cnt; i++) {
8681 		const struct module_btf *mod = &obj->btf_modules[i];
8682 
8683 		if (strncmp(mod->name, mod_name, mod_len) == 0 && mod->name[mod_len] == '\0')
8684 			return mod;
8685 	}
8686 	return NULL;
8687 }
8688 
8689 static int tracing_multi_mod_fd(struct bpf_program *prog, int *btf_obj_fd)
8690 {
8691 	const char *attach_name, *sep;
8692 	const struct module_btf *mod;
8693 
8694 	*btf_obj_fd = 0;
8695 	attach_name = strchr(prog->sec_name, '/');
8696 
8697 	/* Program with no details in spec, using kernel btf. */
8698 	if (!attach_name)
8699 		return 0;
8700 
8701 	/* Program with no module section, using kernel btf. */
8702 	sep = strchr(++attach_name, ':');
8703 	if (!sep)
8704 		return 0;
8705 
8706 	/* Program with module specified, get its btf fd. */
8707 	mod = find_attach_module(prog->obj, attach_name);
8708 	if (!mod)
8709 		return -EINVAL;
8710 
8711 	*btf_obj_fd = mod->fd;
8712 	return 0;
8713 }
8714 
8715 static int libbpf_setup_prog_flags(struct bpf_program *prog, long cookie)
8716 {
8717 	enum sec_def_flags def = cookie;
8718 
8719 	if (def & SEC_SLEEPABLE)
8720 		prog->prog_flags |= BPF_F_SLEEPABLE;
8721 
8722 	if (def & SEC_XDP_FRAGS)
8723 		prog->prog_flags |= BPF_F_XDP_HAS_FRAGS;
8724 
8725 	return 0;
8726 }
8727 
8728 /* this is called as prog->sec_def->prog_prepare_load_fn for libbpf-supported sec_defs */
8729 static int libbpf_prepare_prog_load(struct bpf_program *prog,
8730 				    struct bpf_prog_load_opts *opts, long cookie)
8731 {
8732 	enum sec_def_flags def = cookie;
8733 
8734 	/* old kernels might not support specifying expected_attach_type */
8735 	if ((def & SEC_EXP_ATTACH_OPT) && !kernel_supports(prog->obj, FEAT_EXP_ATTACH_TYPE))
8736 		opts->expected_attach_type = 0;
8737 
8738 	/* special check for usdt to use uprobe_multi link */
8739 	if ((def & SEC_USDT) && kernel_supports(prog->obj, FEAT_UPROBE_MULTI_LINK)) {
8740 		/* for BPF_TRACE_UPROBE_MULTI, user might want to query expected_attach_type
8741 		 * in prog, and expected_attach_type we set in kernel is from opts, so we
8742 		 * update both.
8743 		 */
8744 		prog->expected_attach_type = BPF_TRACE_UPROBE_MULTI;
8745 		opts->expected_attach_type = BPF_TRACE_UPROBE_MULTI;
8746 	}
8747 
8748 	if ((def & SEC_ATTACH_BTF) && !prog->attach_btf_id) {
8749 		int btf_obj_fd = 0, btf_type_id = 0, err;
8750 		const char *attach_name;
8751 
8752 		attach_name = strchr(prog->sec_name, '/');
8753 		if (!attach_name) {
8754 			/* if BPF program is annotated with just SEC("fentry")
8755 			 * (or similar) without declaratively specifying
8756 			 * target, then it is expected that target will be
8757 			 * specified with bpf_program__set_attach_target() at
8758 			 * runtime before BPF object load step. If not, then
8759 			 * there is nothing to load into the kernel as BPF
8760 			 * verifier won't be able to validate BPF program
8761 			 * correctness anyways.
8762 			 */
8763 			pr_warn("prog '%s': no BTF-based attach target is specified, use bpf_program__set_attach_target()\n",
8764 				prog->name);
8765 			return -EINVAL;
8766 		}
8767 		attach_name++; /* skip over / */
8768 
8769 		err = libbpf_find_attach_btf_id(prog, attach_name, &btf_obj_fd, &btf_type_id);
8770 		if (err)
8771 			return err;
8772 
8773 		/* cache resolved BTF FD and BTF type ID in the prog */
8774 		prog->attach_btf_obj_fd = btf_obj_fd;
8775 		prog->attach_btf_id = btf_type_id;
8776 
8777 		/* but by now libbpf common logic is not utilizing
8778 		 * prog->attach_btf_obj_fd/prog->attach_btf_id anymore because
8779 		 * this callback is called after opts were populated by
8780 		 * libbpf, so this callback has to update opts explicitly here
8781 		 */
8782 		opts->attach_btf_obj_fd = btf_obj_fd;
8783 		opts->attach_btf_id = btf_type_id;
8784 	}
8785 
8786 	if (is_tracing_multi(prog->expected_attach_type)) {
8787 		int err, btf_obj_fd = 0;
8788 
8789 		err = tracing_multi_mod_fd(prog, &btf_obj_fd);
8790 		if (err < 0)
8791 			return err;
8792 
8793 		prog->attach_btf_obj_fd = btf_obj_fd;
8794 		opts->attach_btf_obj_fd = btf_obj_fd;
8795 	}
8796 
8797 	return 0;
8798 }
8799 
8800 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz);
8801 
8802 static int bpf_object_load_prog(struct bpf_object *obj, struct bpf_program *prog,
8803 				struct bpf_insn *insns, int insns_cnt,
8804 				const char *license, __u32 kern_version, int *prog_fd)
8805 {
8806 	LIBBPF_OPTS(bpf_prog_load_opts, load_attr);
8807 	const char *prog_name = NULL;
8808 	size_t log_buf_size = 0;
8809 	char *log_buf = NULL, *tmp;
8810 	bool own_log_buf = true;
8811 	__u32 log_level = prog->log_level;
8812 	int ret, err;
8813 
8814 	/* Be more helpful by rejecting programs that can't be validated early
8815 	 * with more meaningful and actionable error message.
8816 	 */
8817 	switch (prog->type) {
8818 	case BPF_PROG_TYPE_UNSPEC:
8819 		/*
8820 		 * The program type must be set.  Most likely we couldn't find a proper
8821 		 * section definition at load time, and thus we didn't infer the type.
8822 		 */
8823 		pr_warn("prog '%s': missing BPF prog type, check ELF section name '%s'\n",
8824 			prog->name, prog->sec_name);
8825 		return -EINVAL;
8826 	case BPF_PROG_TYPE_STRUCT_OPS:
8827 		if (prog->attach_btf_id == 0) {
8828 			pr_warn("prog '%s': SEC(\"struct_ops\") program isn't referenced anywhere, did you forget to use it?\n",
8829 				prog->name);
8830 			return -EINVAL;
8831 		}
8832 		break;
8833 	default:
8834 		break;
8835 	}
8836 
8837 	if (!insns || !insns_cnt)
8838 		return -EINVAL;
8839 
8840 	if (kernel_supports(obj, FEAT_PROG_NAME))
8841 		prog_name = prog->name;
8842 	load_attr.attach_prog_fd = prog->attach_prog_fd;
8843 	load_attr.attach_btf_obj_fd = prog->attach_btf_obj_fd;
8844 	load_attr.attach_btf_id = prog->attach_btf_id;
8845 	load_attr.kern_version = kern_version;
8846 	load_attr.prog_ifindex = prog->prog_ifindex;
8847 	load_attr.expected_attach_type = prog->expected_attach_type;
8848 
8849 	/* specify func_info/line_info only if kernel supports them */
8850 	if (obj->btf && btf__fd(obj->btf) >= 0 && kernel_supports(obj, FEAT_BTF_FUNC)) {
8851 		load_attr.prog_btf_fd = btf__fd(obj->btf);
8852 		load_attr.func_info = prog->func_info;
8853 		load_attr.func_info_rec_size = prog->func_info_rec_size;
8854 		load_attr.func_info_cnt = prog->func_info_cnt;
8855 		load_attr.line_info = prog->line_info;
8856 		load_attr.line_info_rec_size = prog->line_info_rec_size;
8857 		load_attr.line_info_cnt = prog->line_info_cnt;
8858 	}
8859 	load_attr.log_level = log_level;
8860 	load_attr.prog_flags = prog->prog_flags;
8861 	/* the program accesses its data in arena through plain numbers */
8862 	if (obj->data_in_arena)
8863 		load_attr.prog_flags |= BPF_F_ARENA_SCALAR;
8864 	load_attr.fd_array = obj->fd_array;
8865 
8866 	load_attr.token_fd = obj->token_fd;
8867 	if (obj->token_fd)
8868 		load_attr.prog_flags |= BPF_F_TOKEN_FD;
8869 
8870 	/* adjust load_attr if sec_def provides custom preload callback */
8871 	if (prog->sec_def && prog->sec_def->prog_prepare_load_fn) {
8872 		err = prog->sec_def->prog_prepare_load_fn(prog, &load_attr, prog->sec_def->cookie);
8873 		if (err < 0) {
8874 			pr_warn("prog '%s': failed to prepare load attributes: %s\n",
8875 				prog->name, errstr(err));
8876 			return err;
8877 		}
8878 		insns = prog->insns;
8879 		insns_cnt = prog->insns_cnt;
8880 	}
8881 
8882 	if (obj->gen_loader) {
8883 		bpf_gen__prog_load(obj->gen_loader, prog->type, prog->name,
8884 				   license, insns, insns_cnt, &load_attr,
8885 				   prog - obj->programs);
8886 		*prog_fd = -1;
8887 		return 0;
8888 	}
8889 
8890 retry_load:
8891 	/* if log_level is zero, we don't request logs initially even if
8892 	 * custom log_buf is specified; if the program load fails, then we'll
8893 	 * bump log_level to 1 and use either custom log_buf or we'll allocate
8894 	 * our own and retry the load to get details on what failed
8895 	 */
8896 	if (log_level) {
8897 		if (prog->log_buf) {
8898 			log_buf = prog->log_buf;
8899 			log_buf_size = prog->log_size;
8900 			own_log_buf = false;
8901 		} else if (obj->log_buf) {
8902 			log_buf = obj->log_buf;
8903 			log_buf_size = obj->log_size;
8904 			own_log_buf = false;
8905 		} else {
8906 			log_buf_size = max((size_t)BPF_LOG_BUF_SIZE, log_buf_size * 2);
8907 			tmp = realloc(log_buf, log_buf_size);
8908 			if (!tmp) {
8909 				ret = -ENOMEM;
8910 				goto out;
8911 			}
8912 			log_buf = tmp;
8913 			log_buf[0] = '\0';
8914 			own_log_buf = true;
8915 		}
8916 	}
8917 
8918 	load_attr.log_buf = log_buf;
8919 	load_attr.log_size = log_buf_size;
8920 	load_attr.log_level = log_level;
8921 
8922 	ret = bpf_prog_load(prog->type, prog_name, license, insns, insns_cnt, &load_attr);
8923 	if (ret >= 0) {
8924 		if (log_level && own_log_buf) {
8925 			pr_debug("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
8926 				 prog->name, log_buf);
8927 		}
8928 
8929 		if (obj->has_rodata && kernel_supports(obj, FEAT_PROG_BIND_MAP)) {
8930 			struct bpf_map *map;
8931 			int i;
8932 
8933 			for (i = 0; i < obj->nr_maps; i++) {
8934 				map = &prog->obj->maps[i];
8935 				if (map->libbpf_type != LIBBPF_MAP_RODATA || map->in_arena)
8936 					continue;
8937 
8938 				if (bpf_prog_bind_map(ret, map->fd, NULL)) {
8939 					pr_warn("prog '%s': failed to bind map '%s': %s\n",
8940 						prog->name, map->real_name, errstr(errno));
8941 					/* Don't fail hard if can't bind rodata. */
8942 				}
8943 			}
8944 		}
8945 
8946 		*prog_fd = ret;
8947 		ret = 0;
8948 		goto out;
8949 	}
8950 
8951 	if (log_level == 0) {
8952 		log_level = 1;
8953 		goto retry_load;
8954 	}
8955 	/* On ENOSPC, increase log buffer size and retry, unless custom
8956 	 * log_buf is specified.
8957 	 * Be careful to not overflow u32, though. Kernel's log buf size limit
8958 	 * isn't part of UAPI so it can always be bumped to full 4GB. So don't
8959 	 * multiply by 2 unless we are sure we'll fit within 32 bits.
8960 	 * Currently, we'll get -EINVAL when we reach (UINT_MAX >> 2).
8961 	 */
8962 	if (own_log_buf && errno == ENOSPC && log_buf_size <= UINT_MAX / 2)
8963 		goto retry_load;
8964 
8965 	ret = -errno;
8966 
8967 	/* post-process verifier log to improve error descriptions */
8968 	fixup_verifier_log(prog, log_buf, log_buf_size);
8969 
8970 	pr_warn("prog '%s': BPF program load failed: %s\n", prog->name, errstr(errno));
8971 	pr_perm_msg(ret);
8972 
8973 	if (own_log_buf && log_buf && log_buf[0] != '\0') {
8974 		pr_warn("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
8975 			prog->name, log_buf);
8976 	}
8977 
8978 out:
8979 	if (own_log_buf)
8980 		free(log_buf);
8981 	return ret;
8982 }
8983 
8984 static char *find_prev_line(char *buf, char *cur)
8985 {
8986 	char *p;
8987 
8988 	if (cur == buf) /* end of a log buf */
8989 		return NULL;
8990 
8991 	p = cur - 1;
8992 	while (p - 1 >= buf && *(p - 1) != '\n')
8993 		p--;
8994 
8995 	return p;
8996 }
8997 
8998 static void patch_log(char *buf, size_t buf_sz, size_t log_sz,
8999 		      char *orig, size_t orig_sz, const char *patch)
9000 {
9001 	/* size of the remaining log content to the right from the to-be-replaced part */
9002 	size_t rem_sz = (buf + log_sz) - (orig + orig_sz);
9003 	size_t patch_sz = strlen(patch);
9004 
9005 	if (patch_sz != orig_sz) {
9006 		/* If patch line(s) are longer than original piece of verifier log,
9007 		 * shift log contents by (patch_sz - orig_sz) bytes to the right
9008 		 * starting from after to-be-replaced part of the log.
9009 		 *
9010 		 * If patch line(s) are shorter than original piece of verifier log,
9011 		 * shift log contents by (orig_sz - patch_sz) bytes to the left
9012 		 * starting from after to-be-replaced part of the log
9013 		 *
9014 		 * We need to be careful about not overflowing available
9015 		 * buf_sz capacity. If that's the case, we'll truncate the end
9016 		 * of the original log, as necessary.
9017 		 */
9018 		if (patch_sz > orig_sz) {
9019 			if (orig + patch_sz >= buf + buf_sz) {
9020 				/* patch is big enough to cover remaining space completely */
9021 				patch_sz -= (orig + patch_sz) - (buf + buf_sz) + 1;
9022 				rem_sz = 0;
9023 			} else if (patch_sz - orig_sz > buf_sz - log_sz) {
9024 				/* patch causes part of remaining log to be truncated */
9025 				rem_sz -= (patch_sz - orig_sz) - (buf_sz - log_sz);
9026 			}
9027 		}
9028 		/* shift remaining log to the right by calculated amount */
9029 		memmove(orig + patch_sz, orig + orig_sz, rem_sz);
9030 	}
9031 
9032 	memcpy(orig, patch, patch_sz);
9033 }
9034 
9035 static void fixup_log_failed_core_relo(struct bpf_program *prog,
9036 				       char *buf, size_t buf_sz, size_t log_sz,
9037 				       char *line1, char *line2, char *line3)
9038 {
9039 	/* Expected log for failed and not properly guarded CO-RE relocation:
9040 	 * line1 -> 123: (85) call unknown#195896080
9041 	 * line2 -> invalid func unknown#195896080
9042 	 * line3 -> <anything else or end of buffer>
9043 	 *
9044 	 * "123" is the index of the instruction that was poisoned. We extract
9045 	 * instruction index to find corresponding CO-RE relocation and
9046 	 * replace this part of the log with more relevant information about
9047 	 * failed CO-RE relocation.
9048 	 */
9049 	const struct bpf_core_relo *relo;
9050 	struct bpf_core_spec spec;
9051 	char patch[512], spec_buf[256];
9052 	int insn_idx, err, spec_len;
9053 
9054 	if (sscanf(line1, "%d: (%*d) call unknown#195896080\n", &insn_idx) != 1)
9055 		return;
9056 
9057 	relo = find_relo_core(prog, insn_idx);
9058 	if (!relo)
9059 		return;
9060 
9061 	err = bpf_core_parse_spec(prog->name, prog->obj->btf, relo, &spec);
9062 	if (err)
9063 		return;
9064 
9065 	spec_len = bpf_core_format_spec(spec_buf, sizeof(spec_buf), &spec);
9066 	snprintf(patch, sizeof(patch),
9067 		 "%d: <invalid CO-RE relocation>\n"
9068 		 "failed to resolve CO-RE relocation %s%s\n",
9069 		 insn_idx, spec_buf, spec_len >= sizeof(spec_buf) ? "..." : "");
9070 
9071 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
9072 }
9073 
9074 static void fixup_log_missing_map_load(struct bpf_program *prog,
9075 				       char *buf, size_t buf_sz, size_t log_sz,
9076 				       char *line1, char *line2, char *line3)
9077 {
9078 	/* Expected log for failed and not properly guarded map reference:
9079 	 * line1 -> 123: (85) call unknown#2001000345
9080 	 * line2 -> invalid func unknown#2001000345
9081 	 * line3 -> <anything else or end of buffer>
9082 	 *
9083 	 * "123" is the index of the instruction that was poisoned.
9084 	 * "345" in "2001000345" is a map index in obj->maps to fetch map name.
9085 	 */
9086 	struct bpf_object *obj = prog->obj;
9087 	const struct bpf_map *map;
9088 	int insn_idx, map_idx;
9089 	char patch[128];
9090 
9091 	if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &map_idx) != 2)
9092 		return;
9093 
9094 	map_idx -= POISON_LDIMM64_MAP_BASE;
9095 	if (map_idx < 0 || map_idx >= obj->nr_maps)
9096 		return;
9097 	map = &obj->maps[map_idx];
9098 
9099 	snprintf(patch, sizeof(patch),
9100 		 "%d: <invalid BPF map reference>\n"
9101 		 "BPF map '%s' is referenced but wasn't created\n",
9102 		 insn_idx, map->name);
9103 
9104 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
9105 }
9106 
9107 static void fixup_log_missing_kfunc_call(struct bpf_program *prog,
9108 					 char *buf, size_t buf_sz, size_t log_sz,
9109 					 char *line1, char *line2, char *line3)
9110 {
9111 	/* Expected log for failed and not properly guarded kfunc call:
9112 	 * line1 -> 123: (85) call unknown#2002000345
9113 	 * line2 -> invalid func unknown#2002000345
9114 	 * line3 -> <anything else or end of buffer>
9115 	 *
9116 	 * "123" is the index of the instruction that was poisoned.
9117 	 * "345" in "2002000345" is an extern index in obj->externs to fetch kfunc name.
9118 	 */
9119 	struct bpf_object *obj = prog->obj;
9120 	const struct extern_desc *ext;
9121 	int insn_idx, ext_idx;
9122 	char patch[128];
9123 
9124 	if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &ext_idx) != 2)
9125 		return;
9126 
9127 	ext_idx -= POISON_CALL_KFUNC_BASE;
9128 	if (ext_idx < 0 || ext_idx >= obj->nr_extern)
9129 		return;
9130 	ext = &obj->externs[ext_idx];
9131 
9132 	snprintf(patch, sizeof(patch),
9133 		 "%d: <invalid kfunc call>\n"
9134 		 "kfunc '%s' is referenced but wasn't resolved\n",
9135 		 insn_idx, ext->name);
9136 
9137 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
9138 }
9139 
9140 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz)
9141 {
9142 	/* look for familiar error patterns in last N lines of the log */
9143 	const size_t max_last_line_cnt = 10;
9144 	char *prev_line, *cur_line, *next_line;
9145 	size_t log_sz;
9146 	int i;
9147 
9148 	if (!buf)
9149 		return;
9150 
9151 	log_sz = strlen(buf) + 1;
9152 	next_line = buf + log_sz - 1;
9153 
9154 	for (i = 0; i < max_last_line_cnt; i++, next_line = cur_line) {
9155 		cur_line = find_prev_line(buf, next_line);
9156 		if (!cur_line)
9157 			return;
9158 
9159 		if (str_has_pfx(cur_line, "invalid func unknown#195896080\n")) {
9160 			prev_line = find_prev_line(buf, cur_line);
9161 			if (!prev_line)
9162 				continue;
9163 
9164 			/* failed CO-RE relocation case */
9165 			fixup_log_failed_core_relo(prog, buf, buf_sz, log_sz,
9166 						   prev_line, cur_line, next_line);
9167 			return;
9168 		} else if (str_has_pfx(cur_line, "invalid func unknown#"POISON_LDIMM64_MAP_PFX)) {
9169 			prev_line = find_prev_line(buf, cur_line);
9170 			if (!prev_line)
9171 				continue;
9172 
9173 			/* reference to uncreated BPF map */
9174 			fixup_log_missing_map_load(prog, buf, buf_sz, log_sz,
9175 						   prev_line, cur_line, next_line);
9176 			return;
9177 		} else if (str_has_pfx(cur_line, "invalid func unknown#"POISON_CALL_KFUNC_PFX)) {
9178 			prev_line = find_prev_line(buf, cur_line);
9179 			if (!prev_line)
9180 				continue;
9181 
9182 			/* reference to unresolved kfunc */
9183 			fixup_log_missing_kfunc_call(prog, buf, buf_sz, log_sz,
9184 						     prev_line, cur_line, next_line);
9185 			return;
9186 		}
9187 	}
9188 }
9189 
9190 static int bpf_program_record_relos(struct bpf_program *prog)
9191 {
9192 	struct bpf_object *obj = prog->obj;
9193 	int i;
9194 
9195 	for (i = 0; i < prog->nr_reloc; i++) {
9196 		struct reloc_desc *relo = &prog->reloc_desc[i];
9197 		struct extern_desc *ext = &obj->externs[relo->ext_idx];
9198 		int kind;
9199 
9200 		switch (relo->type) {
9201 		case RELO_EXTERN_LD64:
9202 			if (ext->type != EXT_KSYM)
9203 				continue;
9204 			kind = btf_is_var(btf__type_by_id(obj->btf, ext->btf_id)) ?
9205 				BTF_KIND_VAR : BTF_KIND_FUNC;
9206 			bpf_gen__record_extern(obj->gen_loader, ext->name,
9207 					       ext->is_weak, !ext->ksym.type_id,
9208 					       true, kind, relo->insn_idx);
9209 			break;
9210 		case RELO_EXTERN_CALL:
9211 			bpf_gen__record_extern(obj->gen_loader, ext->name,
9212 					       ext->is_weak, false, false, BTF_KIND_FUNC,
9213 					       relo->insn_idx);
9214 			break;
9215 		case RELO_CORE: {
9216 			struct bpf_core_relo cr = {
9217 				.insn_off = relo->insn_idx * 8,
9218 				.type_id = relo->core_relo->type_id,
9219 				.access_str_off = relo->core_relo->access_str_off,
9220 				.kind = relo->core_relo->kind,
9221 			};
9222 
9223 			bpf_gen__record_relo_core(obj->gen_loader, &cr);
9224 			break;
9225 		}
9226 		default:
9227 			continue;
9228 		}
9229 	}
9230 	return 0;
9231 }
9232 
9233 static int
9234 bpf_object__load_progs(struct bpf_object *obj, int log_level)
9235 {
9236 	struct bpf_program *prog;
9237 	size_t i;
9238 	int err;
9239 
9240 	for (i = 0; i < obj->nr_programs; i++) {
9241 		prog = &obj->programs[i];
9242 		if (prog_is_subprog(obj, prog))
9243 			continue;
9244 		if (!prog->autoload) {
9245 			pr_debug("prog '%s': skipped loading\n", prog->name);
9246 			continue;
9247 		}
9248 		prog->log_level |= log_level;
9249 
9250 		if (obj->gen_loader)
9251 			bpf_program_record_relos(prog);
9252 
9253 		err = bpf_object_load_prog(obj, prog, prog->insns, prog->insns_cnt,
9254 					   obj->license, obj->kern_version, &prog->fd);
9255 		if (err) {
9256 			pr_warn("prog '%s': failed to load: %s\n", prog->name, errstr(err));
9257 			return err;
9258 		}
9259 	}
9260 
9261 	bpf_object__free_relocs(obj);
9262 	return 0;
9263 }
9264 
9265 static int bpf_object_prepare_progs(struct bpf_object *obj)
9266 {
9267 	struct bpf_program *prog;
9268 	size_t i;
9269 	int err;
9270 
9271 	for (i = 0; i < obj->nr_programs; i++) {
9272 		prog = &obj->programs[i];
9273 		err = bpf_object__sanitize_prog(obj, prog);
9274 		if (err)
9275 			return err;
9276 	}
9277 	return 0;
9278 }
9279 
9280 static const struct bpf_sec_def *find_sec_def(const char *sec_name);
9281 
9282 static int bpf_object_init_progs(struct bpf_object *obj, const struct bpf_object_open_opts *opts)
9283 {
9284 	struct bpf_program *prog;
9285 	int err;
9286 
9287 	bpf_object__for_each_program(prog, obj) {
9288 		prog->sec_def = find_sec_def(prog->sec_name);
9289 		if (!prog->sec_def) {
9290 			/* couldn't guess, but user might manually specify */
9291 			pr_debug("prog '%s': unrecognized ELF section name '%s'\n",
9292 				prog->name, prog->sec_name);
9293 			continue;
9294 		}
9295 
9296 		prog->type = prog->sec_def->prog_type;
9297 		prog->expected_attach_type = prog->sec_def->expected_attach_type;
9298 
9299 		/* sec_def can have custom callback which should be called
9300 		 * after bpf_program is initialized to adjust its properties
9301 		 */
9302 		if (prog->sec_def->prog_setup_fn) {
9303 			err = prog->sec_def->prog_setup_fn(prog, prog->sec_def->cookie);
9304 			if (err < 0) {
9305 				pr_warn("prog '%s': failed to initialize: %s\n",
9306 					prog->name, errstr(err));
9307 				return err;
9308 			}
9309 		}
9310 	}
9311 
9312 	return 0;
9313 }
9314 
9315 static struct bpf_object *bpf_object_open(const char *path, const void *obj_buf, size_t obj_buf_sz,
9316 					  const char *obj_name,
9317 					  const struct bpf_object_open_opts *opts)
9318 {
9319 	const char *kconfig, *btf_tmp_path, *token_path;
9320 	size_t mod_allow_cnt, i, j;
9321 	const char **mod_allow;
9322 	struct bpf_object *obj;
9323 	int err;
9324 	char *log_buf;
9325 	size_t log_size;
9326 	__u32 log_level;
9327 
9328 	if (obj_buf && !obj_name)
9329 		return ERR_PTR(-EINVAL);
9330 
9331 	if (elf_version(EV_CURRENT) == EV_NONE) {
9332 		pr_warn("failed to init libelf for %s\n",
9333 			path ? : "(mem buf)");
9334 		return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
9335 	}
9336 
9337 	if (!OPTS_VALID(opts, bpf_object_open_opts))
9338 		return ERR_PTR(-EINVAL);
9339 
9340 	obj_name = OPTS_GET(opts, object_name, NULL) ?: obj_name;
9341 	if (obj_buf) {
9342 		path = obj_name;
9343 		pr_debug("loading object '%s' from buffer\n", obj_name);
9344 	} else {
9345 		pr_debug("loading object from %s\n", path);
9346 	}
9347 
9348 	log_buf = OPTS_GET(opts, kernel_log_buf, NULL);
9349 	log_size = OPTS_GET(opts, kernel_log_size, 0);
9350 	log_level = OPTS_GET(opts, kernel_log_level, 0);
9351 	if (log_size > UINT_MAX)
9352 		return ERR_PTR(-EINVAL);
9353 	if (log_size && !log_buf)
9354 		return ERR_PTR(-EINVAL);
9355 
9356 	token_path = OPTS_GET(opts, bpf_token_path, NULL);
9357 	/* if user didn't specify bpf_token_path explicitly, check if
9358 	 * LIBBPF_BPF_TOKEN_PATH envvar was set and treat it as bpf_token_path
9359 	 * option
9360 	 */
9361 	if (!token_path)
9362 		token_path = getenv("LIBBPF_BPF_TOKEN_PATH");
9363 	if (token_path && strlen(token_path) >= PATH_MAX)
9364 		return ERR_PTR(-ENAMETOOLONG);
9365 
9366 	mod_allow = OPTS_GET(opts, btf_module_allowlist, NULL);
9367 	mod_allow_cnt = OPTS_GET(opts, btf_module_allowlist_cnt, 0);
9368 
9369 	if (mod_allow_cnt > SSIZE_MAX || (!mod_allow && mod_allow_cnt > 0))
9370 		return ERR_PTR(-EINVAL);
9371 
9372 	for (i = 0; i < mod_allow_cnt; i++) {
9373 		if (!mod_allow[i] || !mod_allow[i][0])
9374 			return ERR_PTR(-EINVAL);
9375 
9376 		for (j = 0; j < i; j++) {
9377 			if (strcmp(mod_allow[i], mod_allow[j]) == 0)
9378 				return ERR_PTR(-EINVAL);
9379 		}
9380 	}
9381 
9382 	obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
9383 	if (IS_ERR(obj))
9384 		return obj;
9385 
9386 	obj->log_buf = log_buf;
9387 	obj->log_size = log_size;
9388 	obj->log_level = log_level;
9389 
9390 	if (token_path) {
9391 		obj->token_path = strdup(token_path);
9392 		if (!obj->token_path) {
9393 			err = -ENOMEM;
9394 			goto out;
9395 		}
9396 	}
9397 
9398 	btf_tmp_path = OPTS_GET(opts, btf_custom_path, NULL);
9399 	if (btf_tmp_path) {
9400 		if (strlen(btf_tmp_path) >= PATH_MAX) {
9401 			err = -ENAMETOOLONG;
9402 			goto out;
9403 		}
9404 		obj->btf_custom_path = strdup(btf_tmp_path);
9405 		if (!obj->btf_custom_path) {
9406 			err = -ENOMEM;
9407 			goto out;
9408 		}
9409 	}
9410 
9411 	kconfig = OPTS_GET(opts, kconfig, NULL);
9412 	if (kconfig) {
9413 		obj->kconfig = strdup(kconfig);
9414 		if (!obj->kconfig) {
9415 			err = -ENOMEM;
9416 			goto out;
9417 		}
9418 	}
9419 
9420 	obj->btf_module_allowlist_cnt = mod_allow ? mod_allow_cnt : -1;
9421 	if (mod_allow_cnt > 0) {
9422 		obj->btf_module_allowlist =
9423 			calloc(mod_allow_cnt, sizeof(*obj->btf_module_allowlist));
9424 		if (!obj->btf_module_allowlist) {
9425 			err = -ENOMEM;
9426 			goto out;
9427 		}
9428 
9429 		for (i = 0; i < mod_allow_cnt; i++) {
9430 			obj->btf_module_allowlist[i] = strdup(mod_allow[i]);
9431 			if (!obj->btf_module_allowlist[i]) {
9432 				err = -ENOMEM;
9433 				goto out;
9434 			}
9435 		}
9436 	}
9437 
9438 	err = bpf_object__elf_init(obj);
9439 	err = err ? : bpf_object__elf_collect(obj);
9440 	err = err ? : bpf_object__collect_externs(obj);
9441 	err = err ? : bpf_object_fixup_btf(obj);
9442 	err = err ? : bpf_object__init_maps(obj, opts);
9443 	err = err ? : bpf_object_init_progs(obj, opts);
9444 	err = err ? : bpf_object__collect_relos(obj);
9445 	if (err)
9446 		goto out;
9447 
9448 	bpf_object__elf_finish(obj);
9449 
9450 	return obj;
9451 out:
9452 	bpf_object__close(obj);
9453 	return ERR_PTR(err);
9454 }
9455 
9456 struct bpf_object *
9457 bpf_object__open_file(const char *path, const struct bpf_object_open_opts *opts)
9458 {
9459 	if (!path)
9460 		return libbpf_err_ptr(-EINVAL);
9461 
9462 	return libbpf_ptr(bpf_object_open(path, NULL, 0, NULL, opts));
9463 }
9464 
9465 struct bpf_object *bpf_object__open(const char *path)
9466 {
9467 	return bpf_object__open_file(path, NULL);
9468 }
9469 
9470 struct bpf_object *
9471 bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
9472 		     const struct bpf_object_open_opts *opts)
9473 {
9474 	char tmp_name[64];
9475 
9476 	if (!obj_buf || obj_buf_sz == 0)
9477 		return libbpf_err_ptr(-EINVAL);
9478 
9479 	/* create a (quite useless) default "name" for this memory buffer object */
9480 	snprintf(tmp_name, sizeof(tmp_name), "%lx-%zx", (unsigned long)obj_buf, obj_buf_sz);
9481 
9482 	return libbpf_ptr(bpf_object_open(NULL, obj_buf, obj_buf_sz, tmp_name, opts));
9483 }
9484 
9485 static int bpf_object_unload(struct bpf_object *obj)
9486 {
9487 	size_t i;
9488 
9489 	if (!obj)
9490 		return libbpf_err(-EINVAL);
9491 
9492 	for (i = 0; i < obj->nr_maps; i++) {
9493 		zclose(obj->maps[i].fd);
9494 		if (obj->maps[i].st_ops)
9495 			zfree(&obj->maps[i].st_ops->kern_vdata);
9496 	}
9497 
9498 	for (i = 0; i < obj->nr_programs; i++)
9499 		bpf_program__unload(&obj->programs[i]);
9500 
9501 	return 0;
9502 }
9503 
9504 static int bpf_object__sanitize_maps(struct bpf_object *obj)
9505 {
9506 	struct bpf_map *m;
9507 
9508 	bpf_object__for_each_map(m, obj) {
9509 		if (!bpf_map__is_internal(m))
9510 			continue;
9511 		if (!kernel_supports(obj, FEAT_ARRAY_MMAP))
9512 			m->def.map_flags &= ~BPF_F_MMAPABLE;
9513 	}
9514 
9515 	return 0;
9516 }
9517 
9518 typedef int (*kallsyms_cb_t)(unsigned long long sym_addr, char sym_type,
9519 			     const char *sym_name, void *ctx);
9520 
9521 static int libbpf_kallsyms_parse(kallsyms_cb_t cb, void *ctx)
9522 {
9523 	char sym_type, sym_name[500];
9524 	unsigned long long sym_addr;
9525 	int ret, err = 0;
9526 	FILE *f;
9527 
9528 	f = fopen("/proc/kallsyms", "re");
9529 	if (!f) {
9530 		err = -errno;
9531 		pr_warn("failed to open /proc/kallsyms: %s\n", errstr(err));
9532 		return err;
9533 	}
9534 
9535 	while (true) {
9536 		ret = fscanf(f, "%llx %c %499s%*[^\n]\n",
9537 			     &sym_addr, &sym_type, sym_name);
9538 		if (ret == EOF && feof(f))
9539 			break;
9540 		if (ret != 3) {
9541 			pr_warn("failed to read kallsyms entry: %d\n", ret);
9542 			err = -EINVAL;
9543 			break;
9544 		}
9545 
9546 		err = cb(sym_addr, sym_type, sym_name, ctx);
9547 		if (err)
9548 			break;
9549 	}
9550 
9551 	fclose(f);
9552 	return err;
9553 }
9554 
9555 static int kallsyms_cb(unsigned long long sym_addr, char sym_type,
9556 		       const char *sym_name, void *ctx)
9557 {
9558 	struct bpf_object *obj = ctx;
9559 	const struct btf_type *t;
9560 	struct extern_desc *ext;
9561 	const char *res;
9562 
9563 	res = strstr(sym_name, ".llvm.");
9564 	if (sym_type == 'd' && res)
9565 		ext = find_extern_by_name_with_len(obj, sym_name, res - sym_name);
9566 	else
9567 		ext = find_extern_by_name(obj, sym_name);
9568 	if (!ext || ext->type != EXT_KSYM)
9569 		return 0;
9570 
9571 	t = btf__type_by_id(obj->btf, ext->btf_id);
9572 	if (!btf_is_var(t))
9573 		return 0;
9574 
9575 	if (ext->is_set && ext->ksym.addr != sym_addr) {
9576 		pr_warn("extern (ksym) '%s': resolution is ambiguous: 0x%llx or 0x%llx\n",
9577 			sym_name, ext->ksym.addr, sym_addr);
9578 		return -EINVAL;
9579 	}
9580 	if (!ext->is_set) {
9581 		ext->is_set = true;
9582 		ext->ksym.addr = sym_addr;
9583 		pr_debug("extern (ksym) '%s': set to 0x%llx\n", sym_name, sym_addr);
9584 	}
9585 	return 0;
9586 }
9587 
9588 static int bpf_object__read_kallsyms_file(struct bpf_object *obj)
9589 {
9590 	return libbpf_kallsyms_parse(kallsyms_cb, obj);
9591 }
9592 
9593 static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
9594 			    __u16 kind, struct btf **res_btf,
9595 			    struct module_btf **res_mod_btf)
9596 {
9597 	struct module_btf *mod_btf;
9598 	struct btf *btf;
9599 	int i, id, err;
9600 
9601 	btf = obj->btf_vmlinux;
9602 	mod_btf = NULL;
9603 	id = btf__find_by_name_kind(btf, ksym_name, kind);
9604 
9605 	if (id == -ENOENT) {
9606 		err = load_module_btfs(obj);
9607 		if (err)
9608 			return err;
9609 
9610 		for (i = 0; i < obj->btf_module_cnt; i++) {
9611 			/* we assume module_btf's BTF FD is always >0 */
9612 			mod_btf = &obj->btf_modules[i];
9613 			btf = mod_btf->btf;
9614 			id = btf__find_by_name_kind_own(btf, ksym_name, kind);
9615 			if (id != -ENOENT)
9616 				break;
9617 		}
9618 	}
9619 	if (id <= 0)
9620 		return -ESRCH;
9621 
9622 	*res_btf = btf;
9623 	*res_mod_btf = mod_btf;
9624 	return id;
9625 }
9626 
9627 static int bpf_object__resolve_ksym_var_btf_id(struct bpf_object *obj,
9628 					       struct extern_desc *ext)
9629 {
9630 	const struct btf_type *targ_var, *targ_type;
9631 	__u32 targ_type_id, local_type_id;
9632 	struct module_btf *mod_btf = NULL;
9633 	const char *targ_var_name;
9634 	struct btf *btf = NULL;
9635 	int id, err;
9636 
9637 	id = find_ksym_btf_id(obj, ext->name, BTF_KIND_VAR, &btf, &mod_btf);
9638 	if (id < 0) {
9639 		if (id == -ESRCH && ext->is_weak)
9640 			return 0;
9641 		pr_warn("extern (var ksym) '%s': not found in kernel BTF\n",
9642 			ext->name);
9643 		return id;
9644 	}
9645 
9646 	/* find local type_id */
9647 	local_type_id = ext->ksym.type_id;
9648 
9649 	/* find target type_id */
9650 	targ_var = btf__type_by_id(btf, id);
9651 	targ_var_name = btf__name_by_offset(btf, targ_var->name_off);
9652 	targ_type = skip_mods_and_typedefs(btf, targ_var->type, &targ_type_id);
9653 
9654 	err = bpf_core_types_are_compat(obj->btf, local_type_id,
9655 					btf, targ_type_id);
9656 	if (err <= 0) {
9657 		const struct btf_type *local_type;
9658 		const char *targ_name, *local_name;
9659 
9660 		local_type = btf__type_by_id(obj->btf, local_type_id);
9661 		local_name = btf__name_by_offset(obj->btf, local_type->name_off);
9662 		targ_name = btf__name_by_offset(btf, targ_type->name_off);
9663 
9664 		pr_warn("extern (var ksym) '%s': incompatible types, expected [%u] %s %s, but kernel has [%u] %s %s\n",
9665 			ext->name, local_type_id,
9666 			btf_kind_str(local_type), local_name, targ_type_id,
9667 			btf_kind_str(targ_type), targ_name);
9668 		return -EINVAL;
9669 	}
9670 
9671 	ext->is_set = true;
9672 	ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
9673 	ext->ksym.kernel_btf_id = id;
9674 	pr_debug("extern (var ksym) '%s': resolved to [%d] %s %s\n",
9675 		 ext->name, id, btf_kind_str(targ_var), targ_var_name);
9676 
9677 	return 0;
9678 }
9679 
9680 static int bpf_object__resolve_ksym_func_btf_id(struct bpf_object *obj,
9681 						struct extern_desc *ext)
9682 {
9683 	int local_func_proto_id, kfunc_proto_id, kfunc_id;
9684 	struct module_btf *mod_btf = NULL;
9685 	const struct btf_type *kern_func;
9686 	struct btf *kern_btf = NULL;
9687 	int ret;
9688 
9689 	local_func_proto_id = ext->ksym.type_id;
9690 
9691 	kfunc_id = find_ksym_btf_id(obj, ext->essent_name ?: ext->name, BTF_KIND_FUNC, &kern_btf,
9692 				    &mod_btf);
9693 	if (kfunc_id < 0) {
9694 		if (kfunc_id == -ESRCH && ext->is_weak)
9695 			return 0;
9696 		pr_warn("extern (func ksym) '%s': not found in kernel or module BTFs\n",
9697 			ext->name);
9698 		return kfunc_id;
9699 	}
9700 
9701 	kern_func = btf__type_by_id(kern_btf, kfunc_id);
9702 	kfunc_proto_id = kern_func->type;
9703 
9704 	ret = bpf_core_types_are_compat(obj->btf, local_func_proto_id,
9705 					kern_btf, kfunc_proto_id);
9706 	if (ret <= 0) {
9707 		if (ext->is_weak)
9708 			return 0;
9709 
9710 		pr_warn("extern (func ksym) '%s': func_proto [%d] incompatible with %s [%d]\n",
9711 			ext->name, local_func_proto_id,
9712 			mod_btf ? mod_btf->name : "vmlinux", kfunc_proto_id);
9713 		return -EINVAL;
9714 	}
9715 
9716 	/* set index for module BTF fd in fd_array, if unset */
9717 	if (mod_btf && !mod_btf->fd_array_idx) {
9718 		/* insn->off is s16 */
9719 		if (obj->fd_array_cnt == INT16_MAX) {
9720 			pr_warn("extern (func ksym) '%s': module BTF fd index %d too big to fit in bpf_insn offset\n",
9721 				ext->name, mod_btf->fd_array_idx);
9722 			return -E2BIG;
9723 		}
9724 		/* Cannot use index 0 for module BTF fd */
9725 		if (!obj->fd_array_cnt)
9726 			obj->fd_array_cnt = 1;
9727 
9728 		ret = libbpf_ensure_mem((void **)&obj->fd_array, &obj->fd_array_cap, sizeof(int),
9729 					obj->fd_array_cnt + 1);
9730 		if (ret)
9731 			return ret;
9732 		mod_btf->fd_array_idx = obj->fd_array_cnt;
9733 		/* we assume module BTF FD is always >0 */
9734 		obj->fd_array[obj->fd_array_cnt++] = mod_btf->fd;
9735 	}
9736 
9737 	ext->is_set = true;
9738 	ext->ksym.kernel_btf_id = kfunc_id;
9739 	ext->ksym.btf_fd_idx = mod_btf ? mod_btf->fd_array_idx : 0;
9740 	/* Also set kernel_btf_obj_fd to make sure that bpf_object__relocate_data()
9741 	 * populates FD into ld_imm64 insn when it's used to point to kfunc.
9742 	 * {kernel_btf_id, btf_fd_idx} -> fixup bpf_call.
9743 	 * {kernel_btf_id, kernel_btf_obj_fd} -> fixup ld_imm64.
9744 	 */
9745 	ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
9746 	pr_debug("extern (func ksym) '%s': resolved to %s [%d]\n",
9747 		 ext->name, mod_btf ? mod_btf->name : "vmlinux", kfunc_id);
9748 
9749 	return 0;
9750 }
9751 
9752 static int bpf_object__resolve_ksyms_btf_id(struct bpf_object *obj)
9753 {
9754 	const struct btf_type *t;
9755 	struct extern_desc *ext;
9756 	int i, err;
9757 
9758 	for (i = 0; i < obj->nr_extern; i++) {
9759 		ext = &obj->externs[i];
9760 		if (ext->type != EXT_KSYM || !ext->ksym.type_id)
9761 			continue;
9762 
9763 		if (obj->gen_loader) {
9764 			ext->is_set = true;
9765 			ext->ksym.kernel_btf_obj_fd = 0;
9766 			ext->ksym.kernel_btf_id = 0;
9767 			continue;
9768 		}
9769 		t = btf__type_by_id(obj->btf, ext->btf_id);
9770 		if (btf_is_var(t))
9771 			err = bpf_object__resolve_ksym_var_btf_id(obj, ext);
9772 		else
9773 			err = bpf_object__resolve_ksym_func_btf_id(obj, ext);
9774 		if (err)
9775 			return err;
9776 	}
9777 	return 0;
9778 }
9779 
9780 static int bpf_object__resolve_externs(struct bpf_object *obj,
9781 				       const char *extra_kconfig)
9782 {
9783 	bool need_config = false, need_kallsyms = false;
9784 	bool need_vmlinux_btf = false;
9785 	struct extern_desc *ext;
9786 	void *kcfg_data = NULL;
9787 	int err, i;
9788 
9789 	if (obj->nr_extern == 0)
9790 		return 0;
9791 
9792 	if (obj->kconfig_map_idx >= 0)
9793 		kcfg_data = obj->maps[obj->kconfig_map_idx].mmaped;
9794 
9795 	for (i = 0; i < obj->nr_extern; i++) {
9796 		ext = &obj->externs[i];
9797 
9798 		if (ext->type == EXT_KSYM) {
9799 			if (ext->ksym.type_id)
9800 				need_vmlinux_btf = true;
9801 			else
9802 				need_kallsyms = true;
9803 			continue;
9804 		} else if (ext->type == EXT_KCFG) {
9805 			void *ext_ptr = kcfg_data + ext->kcfg.data_off;
9806 			__u64 value = 0;
9807 
9808 			/* Kconfig externs need actual /proc/config.gz */
9809 			if (str_has_pfx(ext->name, "CONFIG_")) {
9810 				need_config = true;
9811 				continue;
9812 			}
9813 
9814 			/* Virtual kcfg externs are customly handled by libbpf */
9815 			if (strcmp(ext->name, "LINUX_KERNEL_VERSION") == 0) {
9816 				value = get_kernel_version();
9817 				if (!value) {
9818 					pr_warn("extern (kcfg) '%s': failed to get kernel version\n", ext->name);
9819 					return -EINVAL;
9820 				}
9821 			} else if (strcmp(ext->name, "LINUX_HAS_BPF_COOKIE") == 0) {
9822 				value = kernel_supports(obj, FEAT_BPF_COOKIE);
9823 			} else if (strcmp(ext->name, "LINUX_HAS_SYSCALL_WRAPPER") == 0) {
9824 				value = kernel_supports(obj, FEAT_SYSCALL_WRAPPER);
9825 			} else if (!str_has_pfx(ext->name, "LINUX_") || !ext->is_weak) {
9826 				/* Currently libbpf supports only CONFIG_ and LINUX_ prefixed
9827 				 * __kconfig externs, where LINUX_ ones are virtual and filled out
9828 				 * customly by libbpf (their values don't come from Kconfig).
9829 				 * If LINUX_xxx variable is not recognized by libbpf, but is marked
9830 				 * __weak, it defaults to zero value, just like for CONFIG_xxx
9831 				 * externs.
9832 				 */
9833 				pr_warn("extern (kcfg) '%s': unrecognized virtual extern\n", ext->name);
9834 				return -EINVAL;
9835 			}
9836 
9837 			err = set_kcfg_value_num(ext, ext_ptr, value);
9838 			if (err)
9839 				return err;
9840 			pr_debug("extern (kcfg) '%s': set to 0x%llx\n",
9841 				 ext->name, (unsigned long long)value);
9842 		} else {
9843 			pr_warn("extern '%s': unrecognized extern kind\n", ext->name);
9844 			return -EINVAL;
9845 		}
9846 	}
9847 	if (need_config && extra_kconfig) {
9848 		err = bpf_object__read_kconfig_mem(obj, extra_kconfig, kcfg_data);
9849 		if (err)
9850 			return -EINVAL;
9851 		need_config = false;
9852 		for (i = 0; i < obj->nr_extern; i++) {
9853 			ext = &obj->externs[i];
9854 			if (ext->type == EXT_KCFG && !ext->is_set) {
9855 				need_config = true;
9856 				break;
9857 			}
9858 		}
9859 	}
9860 	if (need_config) {
9861 		err = bpf_object__read_kconfig_file(obj, kcfg_data);
9862 		if (err)
9863 			return -EINVAL;
9864 	}
9865 	if (need_kallsyms) {
9866 		err = bpf_object__read_kallsyms_file(obj);
9867 		if (err)
9868 			return -EINVAL;
9869 	}
9870 	if (need_vmlinux_btf) {
9871 		err = bpf_object__resolve_ksyms_btf_id(obj);
9872 		if (err)
9873 			return -EINVAL;
9874 	}
9875 	for (i = 0; i < obj->nr_extern; i++) {
9876 		ext = &obj->externs[i];
9877 
9878 		if (!ext->is_set && !ext->is_weak) {
9879 			pr_warn("extern '%s' (strong): not resolved\n", ext->name);
9880 			return -ESRCH;
9881 		} else if (!ext->is_set) {
9882 			pr_debug("extern '%s' (weak): not resolved, defaulting to zero\n",
9883 				 ext->name);
9884 		}
9885 	}
9886 
9887 	return 0;
9888 }
9889 
9890 static void bpf_map_prepare_vdata(const struct bpf_map *map)
9891 {
9892 	const struct btf_type *type;
9893 	struct bpf_struct_ops *st_ops;
9894 	__u32 i;
9895 
9896 	st_ops = map->st_ops;
9897 	type = btf__type_by_id(map->obj->btf, st_ops->type_id);
9898 	for (i = 0; i < btf_vlen(type); i++) {
9899 		struct bpf_program *prog = st_ops->progs[i];
9900 		void *kern_data;
9901 		int prog_fd;
9902 
9903 		if (!prog)
9904 			continue;
9905 
9906 		prog_fd = bpf_program__fd(prog);
9907 		kern_data = st_ops->kern_vdata + st_ops->kern_func_off[i];
9908 		*(unsigned long *)kern_data = prog_fd;
9909 	}
9910 }
9911 
9912 static int bpf_object_prepare_struct_ops(struct bpf_object *obj)
9913 {
9914 	struct bpf_map *map;
9915 	int i;
9916 
9917 	for (i = 0; i < obj->nr_maps; i++) {
9918 		map = &obj->maps[i];
9919 
9920 		if (!bpf_map__is_struct_ops(map))
9921 			continue;
9922 
9923 		if (!map->autocreate)
9924 			continue;
9925 
9926 		bpf_map_prepare_vdata(map);
9927 	}
9928 
9929 	return 0;
9930 }
9931 
9932 static void bpf_object_unpin(struct bpf_object *obj)
9933 {
9934 	int i;
9935 
9936 	/* unpin any maps that were auto-pinned during load */
9937 	for (i = 0; i < obj->nr_maps; i++)
9938 		if (obj->maps[i].pinned && !obj->maps[i].reused)
9939 			bpf_map__unpin(&obj->maps[i], NULL);
9940 }
9941 
9942 static void bpf_object_cleanup_btf(struct bpf_object *obj)
9943 {
9944 	int i;
9945 
9946 	/* clean up module BTFs */
9947 	for (i = 0; i < obj->btf_module_cnt; i++) {
9948 		close(obj->btf_modules[i].fd);
9949 		btf__free(obj->btf_modules[i].btf);
9950 		free(obj->btf_modules[i].name);
9951 	}
9952 	obj->btf_module_cnt = 0;
9953 	obj->btf_module_cap = 0;
9954 	obj->btf_modules_loaded = false;
9955 	zfree(&obj->btf_modules);
9956 
9957 	/* clean up vmlinux BTF */
9958 	btf__free(obj->btf_vmlinux);
9959 	obj->btf_vmlinux = NULL;
9960 }
9961 
9962 static void bpf_object_post_load_cleanup(struct bpf_object *obj)
9963 {
9964 	/* clean up fd_array */
9965 	zfree(&obj->fd_array);
9966 
9967 	/* clean up BTF */
9968 	bpf_object_cleanup_btf(obj);
9969 }
9970 
9971 static int bpf_object_prepare(struct bpf_object *obj, const char *target_btf_path)
9972 {
9973 	int err;
9974 
9975 	if (obj->state >= OBJ_PREPARED) {
9976 		pr_warn("object '%s': prepare loading can't be attempted twice\n", obj->name);
9977 		return -EINVAL;
9978 	}
9979 
9980 	err = bpf_object_prepare_token(obj);
9981 	err = err ? : bpf_object__probe_loading(obj);
9982 	err = err ? : bpf_object__load_vmlinux_btf(obj, false);
9983 	err = err ? : bpf_object__resolve_externs(obj, obj->kconfig);
9984 	err = err ? : bpf_object__sanitize_maps(obj);
9985 	err = err ? : bpf_object__init_kern_struct_ops_maps(obj);
9986 	err = err ? : bpf_object_adjust_struct_ops_autoload(obj);
9987 	err = err ? : bpf_object__relocate(obj, obj->btf_custom_path ? : target_btf_path);
9988 	err = err ? : bpf_object__sanitize_and_load_btf(obj);
9989 	err = err ? : bpf_object__create_maps(obj);
9990 	err = err ? : bpf_object_prepare_progs(obj);
9991 
9992 	if (err) {
9993 		bpf_object_unpin(obj);
9994 		bpf_object_unload(obj);
9995 		obj->state = OBJ_LOADED;
9996 		return err;
9997 	}
9998 
9999 	obj->state = OBJ_PREPARED;
10000 	return 0;
10001 }
10002 
10003 static int bpf_object_load(struct bpf_object *obj, int extra_log_level, const char *target_btf_path)
10004 {
10005 	int err;
10006 
10007 	if (!obj)
10008 		return libbpf_err(-EINVAL);
10009 
10010 	if (obj->state >= OBJ_LOADED) {
10011 		pr_warn("object '%s': load can't be attempted twice\n", obj->name);
10012 		return libbpf_err(-EINVAL);
10013 	}
10014 
10015 	/* Disallow kernel loading programs of non-native endianness but
10016 	 * permit cross-endian creation of "light skeleton".
10017 	 */
10018 	if (obj->gen_loader) {
10019 		int nr_func_ptr_maps = 0, nr_progs = 0, i;
10020 		bool text_has_callx = false;
10021 
10022 		/*
10023 		 * Every program that has callx may get a copy of every map with
10024 		 * pointers to functions. Which functions a program calls is not
10025 		 * known yet. Any of them may call the ones that have callx.
10026 		 */
10027 		for (i = 0; i < obj->nr_maps; i++)
10028 			if (obj->maps[i].autocreate && obj->maps[i].func_ptr_cnt)
10029 				nr_func_ptr_maps++;
10030 		for (i = 0; i < obj->nr_programs; i++)
10031 			if (prog_is_subprog(obj, &obj->programs[i]) &&
10032 			    prog_has_callx(&obj->programs[i]))
10033 				text_has_callx = true;
10034 		for (i = 0; i < obj->nr_programs; i++)
10035 			if (obj->programs[i].autoload && !prog_is_subprog(obj, &obj->programs[i]) &&
10036 			    (text_has_callx || prog_has_callx(&obj->programs[i])))
10037 				nr_progs++;
10038 		bpf_gen__init(obj->gen_loader, obj->log_level | extra_log_level,
10039 			      obj->nr_programs, obj->nr_maps, nr_func_ptr_maps * nr_progs);
10040 	} else if (!is_native_endianness(obj)) {
10041 		pr_warn("object '%s': loading non-native endianness is unsupported\n", obj->name);
10042 		return libbpf_err(-LIBBPF_ERRNO__ENDIAN);
10043 	}
10044 
10045 	if (obj->state < OBJ_PREPARED) {
10046 		err = bpf_object_prepare(obj, target_btf_path);
10047 		if (err)
10048 			return libbpf_err(err);
10049 	}
10050 	err = bpf_object__load_progs(obj, extra_log_level);
10051 	err = err ? : bpf_object_init_prog_arrays(obj);
10052 	err = err ? : bpf_object_prepare_struct_ops(obj);
10053 
10054 	if (obj->gen_loader) {
10055 		/* reset FDs */
10056 		if (obj->btf)
10057 			btf__set_fd(obj->btf, -1);
10058 		if (!err)
10059 			err = bpf_gen__finish(obj->gen_loader, obj->nr_programs, obj->nr_maps);
10060 	}
10061 
10062 	bpf_object_post_load_cleanup(obj);
10063 	obj->state = OBJ_LOADED; /* doesn't matter if successfully or not */
10064 
10065 	if (err) {
10066 		bpf_object_unpin(obj);
10067 		bpf_object_unload(obj);
10068 		pr_warn("failed to load object '%s'\n", obj->path);
10069 		return libbpf_err(err);
10070 	}
10071 
10072 	return 0;
10073 }
10074 
10075 int bpf_object__prepare(struct bpf_object *obj)
10076 {
10077 	return libbpf_err(bpf_object_prepare(obj, NULL));
10078 }
10079 
10080 int bpf_object__load(struct bpf_object *obj)
10081 {
10082 	return bpf_object_load(obj, 0, NULL);
10083 }
10084 
10085 static int make_parent_dir(const char *path)
10086 {
10087 	char *dname, *dir;
10088 	int err = 0;
10089 
10090 	dname = strdup(path);
10091 	if (dname == NULL)
10092 		return -ENOMEM;
10093 
10094 	dir = dirname(dname);
10095 	if (mkdir(dir, 0700) && errno != EEXIST)
10096 		err = -errno;
10097 
10098 	free(dname);
10099 	if (err) {
10100 		pr_warn("failed to mkdir %s: %s\n", path, errstr(err));
10101 	}
10102 	return err;
10103 }
10104 
10105 static int check_path(const char *path)
10106 {
10107 	struct statfs st_fs;
10108 	char *dname, *dir;
10109 	int err = 0;
10110 
10111 	if (path == NULL)
10112 		return -EINVAL;
10113 
10114 	dname = strdup(path);
10115 	if (dname == NULL)
10116 		return -ENOMEM;
10117 
10118 	dir = dirname(dname);
10119 	if (statfs(dir, &st_fs)) {
10120 		pr_warn("failed to statfs %s: %s\n", dir, errstr(errno));
10121 		err = -errno;
10122 	}
10123 	free(dname);
10124 
10125 	if (!err && st_fs.f_type != BPF_FS_MAGIC) {
10126 		pr_warn("specified path %s is not on BPF FS\n", path);
10127 		err = -EINVAL;
10128 	}
10129 
10130 	return err;
10131 }
10132 
10133 int bpf_program__pin(struct bpf_program *prog, const char *path)
10134 {
10135 	int err;
10136 
10137 	if (prog->fd < 0) {
10138 		pr_warn("prog '%s': can't pin program that wasn't loaded\n", prog->name);
10139 		return libbpf_err(-EINVAL);
10140 	}
10141 
10142 	err = make_parent_dir(path);
10143 	if (err)
10144 		return libbpf_err(err);
10145 
10146 	err = check_path(path);
10147 	if (err)
10148 		return libbpf_err(err);
10149 
10150 	if (bpf_obj_pin(prog->fd, path)) {
10151 		err = -errno;
10152 		pr_warn("prog '%s': failed to pin at '%s': %s\n", prog->name, path, errstr(err));
10153 		return libbpf_err(err);
10154 	}
10155 
10156 	pr_debug("prog '%s': pinned at '%s'\n", prog->name, path);
10157 	return 0;
10158 }
10159 
10160 int bpf_program__unpin(struct bpf_program *prog, const char *path)
10161 {
10162 	int err;
10163 
10164 	if (prog->fd < 0) {
10165 		pr_warn("prog '%s': can't unpin program that wasn't loaded\n", prog->name);
10166 		return libbpf_err(-EINVAL);
10167 	}
10168 
10169 	err = check_path(path);
10170 	if (err)
10171 		return libbpf_err(err);
10172 
10173 	err = unlink(path);
10174 	if (err)
10175 		return libbpf_err(-errno);
10176 
10177 	pr_debug("prog '%s': unpinned from '%s'\n", prog->name, path);
10178 	return 0;
10179 }
10180 
10181 int bpf_map__pin(struct bpf_map *map, const char *path)
10182 {
10183 	int err;
10184 
10185 	if (map == NULL) {
10186 		pr_warn("invalid map pointer\n");
10187 		return libbpf_err(-EINVAL);
10188 	}
10189 
10190 	if (map->fd < 0) {
10191 		pr_warn("map '%s': can't pin BPF map without FD (was it created?)\n", map->name);
10192 		return libbpf_err(-EINVAL);
10193 	}
10194 
10195 	if (map->pin_path) {
10196 		if (path && strcmp(path, map->pin_path)) {
10197 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
10198 				bpf_map__name(map), map->pin_path, path);
10199 			return libbpf_err(-EINVAL);
10200 		} else if (map->pinned) {
10201 			pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
10202 				 bpf_map__name(map), map->pin_path);
10203 			return 0;
10204 		}
10205 	} else {
10206 		if (!path) {
10207 			pr_warn("missing a path to pin map '%s' at\n",
10208 				bpf_map__name(map));
10209 			return libbpf_err(-EINVAL);
10210 		} else if (map->pinned) {
10211 			pr_warn("map '%s' already pinned\n", bpf_map__name(map));
10212 			return libbpf_err(-EEXIST);
10213 		}
10214 
10215 		map->pin_path = strdup(path);
10216 		if (!map->pin_path) {
10217 			err = -errno;
10218 			goto out_err;
10219 		}
10220 	}
10221 
10222 	err = make_parent_dir(map->pin_path);
10223 	if (err)
10224 		return libbpf_err(err);
10225 
10226 	err = check_path(map->pin_path);
10227 	if (err)
10228 		return libbpf_err(err);
10229 
10230 	if (bpf_obj_pin(map->fd, map->pin_path)) {
10231 		err = -errno;
10232 		goto out_err;
10233 	}
10234 
10235 	map->pinned = true;
10236 	pr_debug("pinned map '%s'\n", map->pin_path);
10237 
10238 	return 0;
10239 
10240 out_err:
10241 	pr_warn("failed to pin map: %s\n", errstr(err));
10242 	return libbpf_err(err);
10243 }
10244 
10245 int bpf_map__unpin(struct bpf_map *map, const char *path)
10246 {
10247 	int err;
10248 
10249 	if (map == NULL) {
10250 		pr_warn("invalid map pointer\n");
10251 		return libbpf_err(-EINVAL);
10252 	}
10253 
10254 	if (map->pin_path) {
10255 		if (path && strcmp(path, map->pin_path)) {
10256 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
10257 				bpf_map__name(map), map->pin_path, path);
10258 			return libbpf_err(-EINVAL);
10259 		}
10260 		path = map->pin_path;
10261 	} else if (!path) {
10262 		pr_warn("no path to unpin map '%s' from\n",
10263 			bpf_map__name(map));
10264 		return libbpf_err(-EINVAL);
10265 	}
10266 
10267 	err = check_path(path);
10268 	if (err)
10269 		return libbpf_err(err);
10270 
10271 	err = unlink(path);
10272 	if (err != 0)
10273 		return libbpf_err(-errno);
10274 
10275 	map->pinned = false;
10276 	pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path);
10277 
10278 	return 0;
10279 }
10280 
10281 int bpf_map__set_pin_path(struct bpf_map *map, const char *path)
10282 {
10283 	char *new = NULL;
10284 
10285 	if (path) {
10286 		new = strdup(path);
10287 		if (!new)
10288 			return libbpf_err(-errno);
10289 	}
10290 
10291 	free(map->pin_path);
10292 	map->pin_path = new;
10293 	return 0;
10294 }
10295 
10296 __alias(bpf_map__pin_path)
10297 const char *bpf_map__get_pin_path(const struct bpf_map *map);
10298 
10299 const char *bpf_map__pin_path(const struct bpf_map *map)
10300 {
10301 	return map->pin_path;
10302 }
10303 
10304 bool bpf_map__is_pinned(const struct bpf_map *map)
10305 {
10306 	return map->pinned;
10307 }
10308 
10309 static void sanitize_pin_path(char *s)
10310 {
10311 	/* bpffs disallows periods in path names */
10312 	while (*s) {
10313 		if (*s == '.')
10314 			*s = '_';
10315 		s++;
10316 	}
10317 }
10318 
10319 int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
10320 {
10321 	struct bpf_map *map;
10322 	int err;
10323 
10324 	if (!obj)
10325 		return libbpf_err(-ENOENT);
10326 
10327 	if (obj->state < OBJ_PREPARED) {
10328 		pr_warn("object not yet loaded; load it first\n");
10329 		return libbpf_err(-ENOENT);
10330 	}
10331 
10332 	bpf_object__for_each_map(map, obj) {
10333 		char *pin_path = NULL;
10334 		char buf[PATH_MAX];
10335 
10336 		if (!map->autocreate)
10337 			continue;
10338 
10339 		if (path) {
10340 			err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
10341 			if (err)
10342 				goto err_unpin_maps;
10343 			sanitize_pin_path(buf);
10344 			pin_path = buf;
10345 		} else if (!map->pin_path) {
10346 			continue;
10347 		}
10348 
10349 		err = bpf_map__pin(map, pin_path);
10350 		if (err)
10351 			goto err_unpin_maps;
10352 	}
10353 
10354 	return 0;
10355 
10356 err_unpin_maps:
10357 	while ((map = bpf_object__prev_map(obj, map))) {
10358 		if (!map->pin_path)
10359 			continue;
10360 
10361 		bpf_map__unpin(map, NULL);
10362 	}
10363 
10364 	return libbpf_err(err);
10365 }
10366 
10367 int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
10368 {
10369 	struct bpf_map *map;
10370 	int err;
10371 
10372 	if (!obj)
10373 		return libbpf_err(-ENOENT);
10374 
10375 	bpf_object__for_each_map(map, obj) {
10376 		char *pin_path = NULL;
10377 		char buf[PATH_MAX];
10378 
10379 		if (path) {
10380 			err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
10381 			if (err)
10382 				return libbpf_err(err);
10383 			sanitize_pin_path(buf);
10384 			pin_path = buf;
10385 		} else if (!map->pin_path) {
10386 			continue;
10387 		}
10388 
10389 		err = bpf_map__unpin(map, pin_path);
10390 		if (err)
10391 			return libbpf_err(err);
10392 	}
10393 
10394 	return 0;
10395 }
10396 
10397 int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
10398 {
10399 	struct bpf_program *prog;
10400 	char buf[PATH_MAX];
10401 	int err;
10402 
10403 	if (!obj)
10404 		return libbpf_err(-ENOENT);
10405 
10406 	if (obj->state < OBJ_LOADED) {
10407 		pr_warn("object not yet loaded; load it first\n");
10408 		return libbpf_err(-ENOENT);
10409 	}
10410 
10411 	bpf_object__for_each_program(prog, obj) {
10412 		err = pathname_concat(buf, sizeof(buf), path, prog->name);
10413 		if (err)
10414 			goto err_unpin_programs;
10415 
10416 		err = bpf_program__pin(prog, buf);
10417 		if (err)
10418 			goto err_unpin_programs;
10419 	}
10420 
10421 	return 0;
10422 
10423 err_unpin_programs:
10424 	while ((prog = bpf_object__prev_program(obj, prog))) {
10425 		if (pathname_concat(buf, sizeof(buf), path, prog->name))
10426 			continue;
10427 
10428 		bpf_program__unpin(prog, buf);
10429 	}
10430 
10431 	return libbpf_err(err);
10432 }
10433 
10434 int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
10435 {
10436 	struct bpf_program *prog;
10437 	int err;
10438 
10439 	if (!obj)
10440 		return libbpf_err(-ENOENT);
10441 
10442 	bpf_object__for_each_program(prog, obj) {
10443 		char buf[PATH_MAX];
10444 
10445 		err = pathname_concat(buf, sizeof(buf), path, prog->name);
10446 		if (err)
10447 			return libbpf_err(err);
10448 
10449 		err = bpf_program__unpin(prog, buf);
10450 		if (err)
10451 			return libbpf_err(err);
10452 	}
10453 
10454 	return 0;
10455 }
10456 
10457 int bpf_object__pin(struct bpf_object *obj, const char *path)
10458 {
10459 	int err;
10460 
10461 	err = bpf_object__pin_maps(obj, path);
10462 	if (err)
10463 		return libbpf_err(err);
10464 
10465 	err = bpf_object__pin_programs(obj, path);
10466 	if (err) {
10467 		bpf_object__unpin_maps(obj, path);
10468 		return libbpf_err(err);
10469 	}
10470 
10471 	return 0;
10472 }
10473 
10474 int bpf_object__unpin(struct bpf_object *obj, const char *path)
10475 {
10476 	int err;
10477 
10478 	err = bpf_object__unpin_programs(obj, path);
10479 	if (err)
10480 		return libbpf_err(err);
10481 
10482 	err = bpf_object__unpin_maps(obj, path);
10483 	if (err)
10484 		return libbpf_err(err);
10485 
10486 	return 0;
10487 }
10488 
10489 static void bpf_map__destroy(struct bpf_map *map)
10490 {
10491 	if (map->inner_map) {
10492 		bpf_map__destroy(map->inner_map);
10493 		zfree(&map->inner_map);
10494 	}
10495 
10496 	zfree(&map->init_slots);
10497 	map->init_slots_sz = 0;
10498 
10499 	if (map->mmaped && map->mmaped != map->obj->arena_data && !map->in_arena)
10500 		munmap(map->mmaped, bpf_map_mmap_sz(map));
10501 	map->mmaped = NULL;
10502 
10503 	if (map->st_ops) {
10504 		zfree(&map->st_ops->data);
10505 		zfree(&map->st_ops->progs);
10506 		zfree(&map->st_ops->kern_func_off);
10507 		zfree(&map->st_ops);
10508 	}
10509 
10510 	zfree(&map->name);
10511 	zfree(&map->real_name);
10512 	zfree(&map->pin_path);
10513 
10514 	if (map->fd >= 0)
10515 		zclose(map->fd);
10516 }
10517 
10518 void bpf_object__close(struct bpf_object *obj)
10519 {
10520 	size_t i;
10521 
10522 	if (IS_ERR_OR_NULL(obj))
10523 		return;
10524 
10525 	/*
10526 	 * if user called bpf_object__prepare() without ever getting to
10527 	 * bpf_object__load(), we need to clean up stuff that is normally
10528 	 * cleaned up at the end of loading step
10529 	 */
10530 	bpf_object_post_load_cleanup(obj);
10531 
10532 	usdt_manager_free(obj->usdt_man);
10533 	obj->usdt_man = NULL;
10534 
10535 	bpf_gen__free(obj->gen_loader);
10536 	bpf_object__elf_finish(obj);
10537 	bpf_object_unload(obj);
10538 	btf__free(obj->btf);
10539 	btf__free(obj->btf_vmlinux);
10540 	btf_ext__free(obj->btf_ext);
10541 
10542 	for (i = 0; i < obj->nr_maps; i++)
10543 		bpf_map__destroy(&obj->maps[i]);
10544 
10545 	zfree(&obj->btf_custom_path);
10546 	zfree(&obj->kconfig);
10547 
10548 	for (i = 0; i < obj->nr_extern; i++) {
10549 		zfree(&obj->externs[i].name);
10550 		zfree(&obj->externs[i].essent_name);
10551 	}
10552 
10553 	zfree(&obj->externs);
10554 	obj->nr_extern = 0;
10555 
10556 	zfree(&obj->maps);
10557 	obj->nr_maps = 0;
10558 
10559 	if (obj->programs && obj->nr_programs) {
10560 		for (i = 0; i < obj->nr_programs; i++)
10561 			bpf_program__exit(&obj->programs[i]);
10562 	}
10563 	zfree(&obj->programs);
10564 
10565 	zfree(&obj->feat_cache);
10566 	zfree(&obj->token_path);
10567 	if (obj->token_fd > 0)
10568 		close(obj->token_fd);
10569 
10570 	zfree(&obj->arena_data);
10571 
10572 	zfree(&obj->jumptables_data);
10573 	obj->jumptables_data_sz = 0;
10574 
10575 	for (i = 0; i < obj->jumptable_map_cnt; i++)
10576 		close(obj->jumptable_maps[i].fd);
10577 	zfree(&obj->jumptable_maps);
10578 
10579 	for (i = 0; i < obj->func_ptr_map_cnt; i++)
10580 		if (!obj->gen_loader)
10581 			close(obj->func_ptr_maps[i].fd);
10582 	zfree(&obj->func_ptr_maps);
10583 	zfree(&obj->func_ptrs);
10584 	for (i = 0; i < obj->data_ptr_cnt; i++)
10585 		zfree(&obj->data_ptrs[i].sym_name);
10586 	zfree(&obj->data_ptrs);
10587 
10588 	if (obj->btf_module_allowlist) {
10589 		for (i = 0; i < obj->btf_module_allowlist_cnt; i++)
10590 			zfree(&obj->btf_module_allowlist[i]);
10591 		zfree(&obj->btf_module_allowlist);
10592 	}
10593 
10594 	free(obj);
10595 }
10596 
10597 const char *bpf_object__name(const struct bpf_object *obj)
10598 {
10599 	return obj ? obj->name : libbpf_err_ptr(-EINVAL);
10600 }
10601 
10602 unsigned int bpf_object__kversion(const struct bpf_object *obj)
10603 {
10604 	return obj ? obj->kern_version : 0;
10605 }
10606 
10607 int bpf_object__token_fd(const struct bpf_object *obj)
10608 {
10609 	return obj->token_fd ?: -1;
10610 }
10611 
10612 struct btf *bpf_object__btf(const struct bpf_object *obj)
10613 {
10614 	return obj ? obj->btf : NULL;
10615 }
10616 
10617 int bpf_object__btf_fd(const struct bpf_object *obj)
10618 {
10619 	return obj->btf ? btf__fd(obj->btf) : -1;
10620 }
10621 
10622 int bpf_object__set_kversion(struct bpf_object *obj, __u32 kern_version)
10623 {
10624 	if (obj->state >= OBJ_LOADED)
10625 		return libbpf_err(-EINVAL);
10626 
10627 	obj->kern_version = kern_version;
10628 
10629 	return 0;
10630 }
10631 
10632 int bpf_object__gen_loader(struct bpf_object *obj, struct gen_loader_opts *opts)
10633 {
10634 	struct bpf_gen *gen;
10635 
10636 	if (!opts)
10637 		return libbpf_err(-EFAULT);
10638 	if (!OPTS_VALID(opts, gen_loader_opts))
10639 		return libbpf_err(-EINVAL);
10640 	gen = calloc(1, sizeof(*gen));
10641 	if (!gen)
10642 		return libbpf_err(-ENOMEM);
10643 	gen->opts = opts;
10644 	gen->swapped_endian = !is_native_endianness(obj);
10645 	obj->gen_loader = gen;
10646 	return 0;
10647 }
10648 
10649 static struct bpf_program *
10650 __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
10651 		    bool forward)
10652 {
10653 	size_t nr_programs = obj->nr_programs;
10654 	ssize_t idx;
10655 
10656 	if (!nr_programs)
10657 		return NULL;
10658 
10659 	if (!p)
10660 		/* Iter from the beginning */
10661 		return forward ? &obj->programs[0] :
10662 			&obj->programs[nr_programs - 1];
10663 
10664 	if (p->obj != obj) {
10665 		pr_warn("error: program handler doesn't match object\n");
10666 		return errno = EINVAL, NULL;
10667 	}
10668 
10669 	idx = (p - obj->programs) + (forward ? 1 : -1);
10670 	if (idx >= obj->nr_programs || idx < 0)
10671 		return NULL;
10672 	return &obj->programs[idx];
10673 }
10674 
10675 struct bpf_program *
10676 bpf_object__next_program(const struct bpf_object *obj, struct bpf_program *prev)
10677 {
10678 	struct bpf_program *prog = prev;
10679 
10680 	do {
10681 		prog = __bpf_program__iter(prog, obj, true);
10682 	} while (prog && prog_is_subprog(obj, prog));
10683 
10684 	return prog;
10685 }
10686 
10687 struct bpf_program *
10688 bpf_object__prev_program(const struct bpf_object *obj, struct bpf_program *next)
10689 {
10690 	struct bpf_program *prog = next;
10691 
10692 	do {
10693 		prog = __bpf_program__iter(prog, obj, false);
10694 	} while (prog && prog_is_subprog(obj, prog));
10695 
10696 	return prog;
10697 }
10698 
10699 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
10700 {
10701 	prog->prog_ifindex = ifindex;
10702 }
10703 
10704 const char *bpf_program__name(const struct bpf_program *prog)
10705 {
10706 	return prog->name;
10707 }
10708 
10709 const char *bpf_program__section_name(const struct bpf_program *prog)
10710 {
10711 	return prog->sec_name;
10712 }
10713 
10714 bool bpf_program__autoload(const struct bpf_program *prog)
10715 {
10716 	return prog->autoload;
10717 }
10718 
10719 int bpf_program__set_autoload(struct bpf_program *prog, bool autoload)
10720 {
10721 	if (prog->obj->state >= OBJ_LOADED)
10722 		return libbpf_err(-EINVAL);
10723 
10724 	prog->autoload = autoload;
10725 	return 0;
10726 }
10727 
10728 bool bpf_program__autoattach(const struct bpf_program *prog)
10729 {
10730 	return prog->autoattach;
10731 }
10732 
10733 void bpf_program__set_autoattach(struct bpf_program *prog, bool autoattach)
10734 {
10735 	prog->autoattach = autoattach;
10736 }
10737 
10738 const struct bpf_insn *bpf_program__insns(const struct bpf_program *prog)
10739 {
10740 	return prog->insns;
10741 }
10742 
10743 size_t bpf_program__insn_cnt(const struct bpf_program *prog)
10744 {
10745 	return prog->insns_cnt;
10746 }
10747 
10748 int bpf_program__set_insns(struct bpf_program *prog,
10749 			   struct bpf_insn *new_insns, size_t new_insn_cnt)
10750 {
10751 	struct bpf_insn *insns;
10752 
10753 	if (prog->obj->state >= OBJ_LOADED)
10754 		return libbpf_err(-EBUSY);
10755 
10756 	insns = libbpf_reallocarray(prog->insns, new_insn_cnt, sizeof(*insns));
10757 	/* NULL is a valid return from reallocarray if the new count is zero */
10758 	if (!insns && new_insn_cnt) {
10759 		pr_warn("prog '%s': failed to realloc prog code\n", prog->name);
10760 		return libbpf_err(-ENOMEM);
10761 	}
10762 	memcpy(insns, new_insns, new_insn_cnt * sizeof(*insns));
10763 
10764 	prog->insns = insns;
10765 	prog->insns_cnt = new_insn_cnt;
10766 	return 0;
10767 }
10768 
10769 int bpf_program__fd(const struct bpf_program *prog)
10770 {
10771 	if (!prog)
10772 		return libbpf_err(-EINVAL);
10773 
10774 	if (prog->fd < 0)
10775 		return libbpf_err(-ENOENT);
10776 
10777 	return prog->fd;
10778 }
10779 
10780 __alias(bpf_program__type)
10781 enum bpf_prog_type bpf_program__get_type(const struct bpf_program *prog);
10782 
10783 enum bpf_prog_type bpf_program__type(const struct bpf_program *prog)
10784 {
10785 	return prog->type;
10786 }
10787 
10788 static size_t custom_sec_def_cnt;
10789 static struct bpf_sec_def *custom_sec_defs;
10790 static struct bpf_sec_def custom_fallback_def;
10791 static bool has_custom_fallback_def;
10792 static int last_custom_sec_def_handler_id;
10793 
10794 int bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
10795 {
10796 	if (prog->obj->state >= OBJ_LOADED)
10797 		return libbpf_err(-EBUSY);
10798 
10799 	/* if type is not changed, do nothing */
10800 	if (prog->type == type)
10801 		return 0;
10802 
10803 	prog->type = type;
10804 
10805 	/* If a program type was changed, we need to reset associated SEC()
10806 	 * handler, as it will be invalid now. The only exception is a generic
10807 	 * fallback handler, which by definition is program type-agnostic and
10808 	 * is a catch-all custom handler, optionally set by the application,
10809 	 * so should be able to handle any type of BPF program.
10810 	 */
10811 	if (prog->sec_def != &custom_fallback_def)
10812 		prog->sec_def = NULL;
10813 	return 0;
10814 }
10815 
10816 __alias(bpf_program__expected_attach_type)
10817 enum bpf_attach_type bpf_program__get_expected_attach_type(const struct bpf_program *prog);
10818 
10819 enum bpf_attach_type bpf_program__expected_attach_type(const struct bpf_program *prog)
10820 {
10821 	return prog->expected_attach_type;
10822 }
10823 
10824 int bpf_program__set_expected_attach_type(struct bpf_program *prog,
10825 					   enum bpf_attach_type type)
10826 {
10827 	if (prog->obj->state >= OBJ_LOADED)
10828 		return libbpf_err(-EBUSY);
10829 
10830 	prog->expected_attach_type = type;
10831 	return 0;
10832 }
10833 
10834 __u32 bpf_program__flags(const struct bpf_program *prog)
10835 {
10836 	return prog->prog_flags;
10837 }
10838 
10839 int bpf_program__set_flags(struct bpf_program *prog, __u32 flags)
10840 {
10841 	if (prog->obj->state >= OBJ_LOADED)
10842 		return libbpf_err(-EBUSY);
10843 
10844 	prog->prog_flags = flags;
10845 	return 0;
10846 }
10847 
10848 int bpf_program__add_flags(struct bpf_program *prog, __u32 flags)
10849 {
10850 	return bpf_program__set_flags(prog, prog->prog_flags | flags);
10851 }
10852 
10853 int bpf_program__clear_flags(struct bpf_program *prog, __u32 flags)
10854 {
10855 	return bpf_program__set_flags(prog, prog->prog_flags & ~flags);
10856 }
10857 
10858 __u32 bpf_program__log_level(const struct bpf_program *prog)
10859 {
10860 	return prog->log_level;
10861 }
10862 
10863 int bpf_program__set_log_level(struct bpf_program *prog, __u32 log_level)
10864 {
10865 	if (prog->obj->state >= OBJ_LOADED)
10866 		return libbpf_err(-EBUSY);
10867 
10868 	prog->log_level = log_level;
10869 	return 0;
10870 }
10871 
10872 const char *bpf_program__log_buf(const struct bpf_program *prog, size_t *log_size)
10873 {
10874 	*log_size = prog->log_size;
10875 	return prog->log_buf;
10876 }
10877 
10878 int bpf_program__set_log_buf(struct bpf_program *prog, char *log_buf, size_t log_size)
10879 {
10880 	if (!!log_buf != !!log_size)
10881 		return libbpf_err(-EINVAL);
10882 	if (log_size > UINT_MAX)
10883 		return libbpf_err(-EINVAL);
10884 	if (prog->obj->state >= OBJ_LOADED)
10885 		return libbpf_err(-EBUSY);
10886 
10887 	prog->log_buf = log_buf;
10888 	prog->log_size = log_size;
10889 	return 0;
10890 }
10891 
10892 struct bpf_func_info *bpf_program__func_info(const struct bpf_program *prog)
10893 {
10894 	if (prog->func_info_rec_size != sizeof(struct bpf_func_info))
10895 		return libbpf_err_ptr(-EOPNOTSUPP);
10896 	return prog->func_info;
10897 }
10898 
10899 __u32 bpf_program__func_info_cnt(const struct bpf_program *prog)
10900 {
10901 	return prog->func_info_cnt;
10902 }
10903 
10904 struct bpf_line_info *bpf_program__line_info(const struct bpf_program *prog)
10905 {
10906 	if (prog->line_info_rec_size != sizeof(struct bpf_line_info))
10907 		return libbpf_err_ptr(-EOPNOTSUPP);
10908 	return prog->line_info;
10909 }
10910 
10911 __u32 bpf_program__line_info_cnt(const struct bpf_program *prog)
10912 {
10913 	return prog->line_info_cnt;
10914 }
10915 
10916 int bpf_program__clone(struct bpf_program *prog, const struct bpf_prog_load_opts *opts)
10917 {
10918 	LIBBPF_OPTS(bpf_prog_load_opts, attr);
10919 	struct bpf_object *obj;
10920 	const void *info;
10921 	__u32 info_cnt, info_rec_size;
10922 	int err, fd, prog_btf_fd;
10923 
10924 	if (!prog)
10925 		return libbpf_err(-EINVAL);
10926 
10927 	if (!OPTS_VALID(opts, bpf_prog_load_opts))
10928 		return libbpf_err(-EINVAL);
10929 
10930 	obj = prog->obj;
10931 	if (obj->state < OBJ_PREPARED)
10932 		return libbpf_err(-EINVAL);
10933 
10934 	/*
10935 	 * Caller-provided opts take priority; fall back to
10936 	 * prog/object defaults when the caller leaves them zero.
10937 	 */
10938 	attr.attach_prog_fd = OPTS_GET(opts, attach_prog_fd, 0) ?: prog->attach_prog_fd;
10939 	attr.prog_flags = OPTS_GET(opts, prog_flags, 0) ?: prog->prog_flags;
10940 	attr.prog_ifindex = OPTS_GET(opts, prog_ifindex, 0) ?: prog->prog_ifindex;
10941 	attr.kern_version = OPTS_GET(opts, kern_version, 0) ?: obj->kern_version;
10942 	attr.fd_array = OPTS_GET(opts, fd_array, NULL) ?: obj->fd_array;
10943 	attr.fd_array_cnt = OPTS_GET(opts, fd_array_cnt, 0) ?: obj->fd_array_cnt;
10944 	attr.token_fd = OPTS_GET(opts, token_fd, 0) ?: obj->token_fd;
10945 	if (attr.token_fd)
10946 		attr.prog_flags |= BPF_F_TOKEN_FD;
10947 	if (obj->data_in_arena)
10948 		attr.prog_flags |= BPF_F_ARENA_SCALAR;
10949 
10950 	prog_btf_fd = OPTS_GET(opts, prog_btf_fd, 0);
10951 	if (!prog_btf_fd && obj->btf)
10952 		prog_btf_fd = btf__fd(obj->btf);
10953 
10954 	/* BTF func/line info: only pass if kernel supports it */
10955 	if (kernel_supports(obj, FEAT_BTF_FUNC) && prog_btf_fd > 0) {
10956 		attr.prog_btf_fd = prog_btf_fd;
10957 
10958 		/* func_info/line_info triples: all-or-nothing from caller */
10959 		info = OPTS_GET(opts, func_info, NULL);
10960 		info_cnt = OPTS_GET(opts, func_info_cnt, 0);
10961 		info_rec_size = OPTS_GET(opts, func_info_rec_size, 0);
10962 		if (!!info != !!info_cnt || !!info != !!info_rec_size) {
10963 			pr_warn("prog '%s': func_info, func_info_cnt, and func_info_rec_size must all be specified or all omitted\n",
10964 				prog->name);
10965 			return libbpf_err(-EINVAL);
10966 		}
10967 		attr.func_info = info ?: prog->func_info;
10968 		attr.func_info_cnt = info ? info_cnt : prog->func_info_cnt;
10969 		attr.func_info_rec_size = info ? info_rec_size : prog->func_info_rec_size;
10970 
10971 		info = OPTS_GET(opts, line_info, NULL);
10972 		info_cnt = OPTS_GET(opts, line_info_cnt, 0);
10973 		info_rec_size = OPTS_GET(opts, line_info_rec_size, 0);
10974 		if (!!info != !!info_cnt || !!info != !!info_rec_size) {
10975 			pr_warn("prog '%s': line_info, line_info_cnt, and line_info_rec_size must all be specified or all omitted\n",
10976 				prog->name);
10977 			return libbpf_err(-EINVAL);
10978 		}
10979 		attr.line_info = info ?: prog->line_info;
10980 		attr.line_info_cnt = info ? info_cnt : prog->line_info_cnt;
10981 		attr.line_info_rec_size = info ? info_rec_size : prog->line_info_rec_size;
10982 	}
10983 
10984 	/* Logging is caller-controlled; no fallback to prog/obj log settings */
10985 	attr.log_buf = OPTS_GET(opts, log_buf, NULL);
10986 	attr.log_size = OPTS_GET(opts, log_size, 0);
10987 	attr.log_level = OPTS_GET(opts, log_level, 0);
10988 
10989 	/*
10990 	 * Fields below may be mutated by prog_prepare_load_fn:
10991 	 * Seed them from prog/obj defaults here;
10992 	 * Later override with caller-provided opts.
10993 	 */
10994 	attr.expected_attach_type = prog->expected_attach_type;
10995 	attr.attach_btf_id = prog->attach_btf_id;
10996 	attr.attach_btf_obj_fd = prog->attach_btf_obj_fd;
10997 
10998 	if (prog->sec_def && prog->sec_def->prog_prepare_load_fn) {
10999 		err = prog->sec_def->prog_prepare_load_fn(prog, &attr, prog->sec_def->cookie);
11000 		if (err)
11001 			return libbpf_err(err);
11002 	}
11003 
11004 	/* Re-apply caller overrides for output fields */
11005 	if (OPTS_GET(opts, expected_attach_type, 0))
11006 		attr.expected_attach_type = OPTS_GET(opts, expected_attach_type, 0);
11007 	if (OPTS_GET(opts, attach_btf_id, 0))
11008 		attr.attach_btf_id = OPTS_GET(opts, attach_btf_id, 0);
11009 	if (OPTS_GET(opts, attach_btf_obj_fd, 0))
11010 		attr.attach_btf_obj_fd = OPTS_GET(opts, attach_btf_obj_fd, 0);
11011 
11012 	/*
11013 	 * Unlike bpf_object_load_prog(), we intentionally do not call bpf_prog_bind_map()
11014 	 * for RODATA maps here to avoid mutating the object's state. Callers can bind the
11015 	 * required maps themselves using bpf_prog_bind_map().
11016 	 */
11017 	fd = bpf_prog_load(prog->type, prog->name, obj->license, prog->insns, prog->insns_cnt,
11018 			   &attr);
11019 
11020 	return libbpf_err(fd);
11021 }
11022 
11023 #define SEC_DEF(sec_pfx, ptype, atype, flags, ...) {			    \
11024 	.sec = (char *)sec_pfx,						    \
11025 	.prog_type = BPF_PROG_TYPE_##ptype,				    \
11026 	.expected_attach_type = atype,					    \
11027 	.cookie = (long)(flags),					    \
11028 	.prog_setup_fn = libbpf_setup_prog_flags,			    \
11029 	.prog_prepare_load_fn = libbpf_prepare_prog_load,		    \
11030 	__VA_ARGS__							    \
11031 }
11032 
11033 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
11034 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
11035 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link);
11036 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link);
11037 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
11038 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
11039 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link);
11040 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
11041 static int attach_kprobe_session(const struct bpf_program *prog, long cookie, struct bpf_link **link);
11042 static int attach_uprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
11043 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link);
11044 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link);
11045 static int attach_tracing_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
11046 
11047 static const struct bpf_sec_def section_defs[] = {
11048 	SEC_DEF("socket",		SOCKET_FILTER, 0, SEC_NONE),
11049 	SEC_DEF("sk_reuseport/migrate",	SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT_OR_MIGRATE, SEC_ATTACHABLE),
11050 	SEC_DEF("sk_reuseport",		SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT, SEC_ATTACHABLE),
11051 	SEC_DEF("kprobe+",		KPROBE,	0, SEC_NONE, attach_kprobe),
11052 	SEC_DEF("uprobe+",		KPROBE,	0, SEC_NONE, attach_uprobe),
11053 	SEC_DEF("uprobe.s+",		KPROBE,	0, SEC_SLEEPABLE, attach_uprobe),
11054 	SEC_DEF("kretprobe+",		KPROBE, 0, SEC_NONE, attach_kprobe),
11055 	SEC_DEF("uretprobe+",		KPROBE, 0, SEC_NONE, attach_uprobe),
11056 	SEC_DEF("uretprobe.s+",		KPROBE, 0, SEC_SLEEPABLE, attach_uprobe),
11057 	SEC_DEF("kprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
11058 	SEC_DEF("kretprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
11059 	SEC_DEF("kprobe.session+",	KPROBE,	BPF_TRACE_KPROBE_SESSION, SEC_NONE, attach_kprobe_session),
11060 	SEC_DEF("uprobe.multi+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_NONE, attach_uprobe_multi),
11061 	SEC_DEF("uretprobe.multi+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_NONE, attach_uprobe_multi),
11062 	SEC_DEF("uprobe.session+",	KPROBE,	BPF_TRACE_UPROBE_SESSION, SEC_NONE, attach_uprobe_multi),
11063 	SEC_DEF("uprobe.multi.s+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_SLEEPABLE, attach_uprobe_multi),
11064 	SEC_DEF("uretprobe.multi.s+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_SLEEPABLE, attach_uprobe_multi),
11065 	SEC_DEF("uprobe.session.s+",	KPROBE,	BPF_TRACE_UPROBE_SESSION, SEC_SLEEPABLE, attach_uprobe_multi),
11066 	SEC_DEF("ksyscall+",		KPROBE,	0, SEC_NONE, attach_ksyscall),
11067 	SEC_DEF("kretsyscall+",		KPROBE, 0, SEC_NONE, attach_ksyscall),
11068 	SEC_DEF("usdt+",		KPROBE,	0, SEC_USDT, attach_usdt),
11069 	SEC_DEF("usdt.s+",		KPROBE,	0, SEC_USDT | SEC_SLEEPABLE, attach_usdt),
11070 	SEC_DEF("tc/ingress",		SCHED_CLS, BPF_TCX_INGRESS, SEC_NONE), /* alias for tcx */
11071 	SEC_DEF("tc/egress",		SCHED_CLS, BPF_TCX_EGRESS, SEC_NONE),  /* alias for tcx */
11072 	SEC_DEF("tcx/ingress",		SCHED_CLS, BPF_TCX_INGRESS, SEC_NONE),
11073 	SEC_DEF("tcx/egress",		SCHED_CLS, BPF_TCX_EGRESS, SEC_NONE),
11074 	SEC_DEF("tc",			SCHED_CLS, 0, SEC_NONE), /* deprecated / legacy, use tcx */
11075 	SEC_DEF("classifier",		SCHED_CLS, 0, SEC_NONE), /* deprecated / legacy, use tcx */
11076 	SEC_DEF("action",		SCHED_ACT, 0, SEC_NONE), /* deprecated / legacy, use tcx */
11077 	SEC_DEF("netkit/primary",	SCHED_CLS, BPF_NETKIT_PRIMARY, SEC_NONE),
11078 	SEC_DEF("netkit/peer",		SCHED_CLS, BPF_NETKIT_PEER, SEC_NONE),
11079 	SEC_DEF("tracepoint+",		TRACEPOINT, 0, SEC_NONE, attach_tp),
11080 	SEC_DEF("tp+",			TRACEPOINT, 0, SEC_NONE, attach_tp),
11081 	SEC_DEF("tracepoint.s+",	TRACEPOINT, 0, SEC_SLEEPABLE, attach_tp),
11082 	SEC_DEF("tp.s+",		TRACEPOINT, 0, SEC_SLEEPABLE, attach_tp),
11083 	SEC_DEF("raw_tracepoint+",	RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
11084 	SEC_DEF("raw_tp+",		RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
11085 	SEC_DEF("raw_tracepoint.s+",	RAW_TRACEPOINT, 0, SEC_SLEEPABLE, attach_raw_tp),
11086 	SEC_DEF("raw_tp.s+",		RAW_TRACEPOINT, 0, SEC_SLEEPABLE, attach_raw_tp),
11087 	SEC_DEF("raw_tracepoint.w+",	RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
11088 	SEC_DEF("raw_tp.w+",		RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
11089 	SEC_DEF("tp_btf+",		TRACING, BPF_TRACE_RAW_TP, SEC_ATTACH_BTF, attach_trace),
11090 	SEC_DEF("tp_btf.s+",		TRACING, BPF_TRACE_RAW_TP, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
11091 	SEC_DEF("fentry+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF, attach_trace),
11092 	SEC_DEF("fmod_ret+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF, attach_trace),
11093 	SEC_DEF("fexit+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF, attach_trace),
11094 	SEC_DEF("fentry.s+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
11095 	SEC_DEF("fmod_ret.s+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
11096 	SEC_DEF("fexit.s+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
11097 	SEC_DEF("fsession+",		TRACING, BPF_TRACE_FSESSION, SEC_ATTACH_BTF, attach_trace),
11098 	SEC_DEF("fsession.s+",		TRACING, BPF_TRACE_FSESSION, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
11099 	SEC_DEF("fsession.multi+",	TRACING, BPF_TRACE_FSESSION_MULTI, 0, attach_tracing_multi),
11100 	SEC_DEF("fsession.multi.s+",	TRACING, BPF_TRACE_FSESSION_MULTI, SEC_SLEEPABLE, attach_tracing_multi),
11101 	SEC_DEF("fentry.multi+",	TRACING, BPF_TRACE_FENTRY_MULTI, 0, attach_tracing_multi),
11102 	SEC_DEF("fexit.multi+",		TRACING, BPF_TRACE_FEXIT_MULTI, 0, attach_tracing_multi),
11103 	SEC_DEF("fentry.multi.s+",	TRACING, BPF_TRACE_FENTRY_MULTI, SEC_SLEEPABLE, attach_tracing_multi),
11104 	SEC_DEF("fexit.multi.s+",	TRACING, BPF_TRACE_FEXIT_MULTI, SEC_SLEEPABLE, attach_tracing_multi),
11105 	SEC_DEF("freplace+",		EXT, 0, SEC_ATTACH_BTF, attach_trace),
11106 	SEC_DEF("lsm+",			LSM, BPF_LSM_MAC, SEC_ATTACH_BTF, attach_lsm),
11107 	SEC_DEF("lsm.s+",		LSM, BPF_LSM_MAC, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_lsm),
11108 	SEC_DEF("lsm_cgroup+",		LSM, BPF_LSM_CGROUP, SEC_ATTACH_BTF),
11109 	SEC_DEF("iter+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF, attach_iter),
11110 	SEC_DEF("iter.s+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_iter),
11111 	SEC_DEF("syscall",		SYSCALL, 0, SEC_SLEEPABLE),
11112 	SEC_DEF("xdp.frags/devmap",	XDP, BPF_XDP_DEVMAP, SEC_XDP_FRAGS),
11113 	SEC_DEF("xdp/devmap",		XDP, BPF_XDP_DEVMAP, SEC_ATTACHABLE),
11114 	SEC_DEF("xdp.frags/cpumap",	XDP, BPF_XDP_CPUMAP, SEC_XDP_FRAGS),
11115 	SEC_DEF("xdp/cpumap",		XDP, BPF_XDP_CPUMAP, SEC_ATTACHABLE),
11116 	SEC_DEF("xdp.frags",		XDP, BPF_XDP, SEC_XDP_FRAGS),
11117 	SEC_DEF("xdp",			XDP, BPF_XDP, SEC_ATTACHABLE_OPT),
11118 	SEC_DEF("perf_event",		PERF_EVENT, 0, SEC_NONE),
11119 	SEC_DEF("lwt_in",		LWT_IN, 0, SEC_NONE),
11120 	SEC_DEF("lwt_out",		LWT_OUT, 0, SEC_NONE),
11121 	SEC_DEF("lwt_xmit",		LWT_XMIT, 0, SEC_NONE),
11122 	SEC_DEF("lwt_seg6local",	LWT_SEG6LOCAL, 0, SEC_NONE),
11123 	SEC_DEF("sockops",		SOCK_OPS, BPF_CGROUP_SOCK_OPS, SEC_ATTACHABLE_OPT),
11124 	SEC_DEF("sk_skb/stream_parser",	SK_SKB, BPF_SK_SKB_STREAM_PARSER, SEC_ATTACHABLE_OPT),
11125 	SEC_DEF("sk_skb/stream_verdict",SK_SKB, BPF_SK_SKB_STREAM_VERDICT, SEC_ATTACHABLE_OPT),
11126 	SEC_DEF("sk_skb/verdict",	SK_SKB, BPF_SK_SKB_VERDICT, SEC_ATTACHABLE_OPT),
11127 	SEC_DEF("sk_skb",		SK_SKB, 0, SEC_NONE),
11128 	SEC_DEF("sk_msg",		SK_MSG, BPF_SK_MSG_VERDICT, SEC_ATTACHABLE_OPT),
11129 	SEC_DEF("lirc_mode2",		LIRC_MODE2, BPF_LIRC_MODE2, SEC_ATTACHABLE_OPT),
11130 	SEC_DEF("flow_dissector",	FLOW_DISSECTOR, BPF_FLOW_DISSECTOR, SEC_ATTACHABLE_OPT),
11131 	SEC_DEF("cgroup_skb/ingress",	CGROUP_SKB, BPF_CGROUP_INET_INGRESS, SEC_ATTACHABLE_OPT),
11132 	SEC_DEF("cgroup_skb/egress",	CGROUP_SKB, BPF_CGROUP_INET_EGRESS, SEC_ATTACHABLE_OPT),
11133 	SEC_DEF("cgroup/skb",		CGROUP_SKB, 0, SEC_NONE),
11134 	SEC_DEF("cgroup/sock_create",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE),
11135 	SEC_DEF("cgroup/sock_release",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_RELEASE, SEC_ATTACHABLE),
11136 	SEC_DEF("cgroup/sock",		CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE_OPT),
11137 	SEC_DEF("cgroup/post_bind4",	CGROUP_SOCK, BPF_CGROUP_INET4_POST_BIND, SEC_ATTACHABLE),
11138 	SEC_DEF("cgroup/post_bind6",	CGROUP_SOCK, BPF_CGROUP_INET6_POST_BIND, SEC_ATTACHABLE),
11139 	SEC_DEF("cgroup/bind4",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND, SEC_ATTACHABLE),
11140 	SEC_DEF("cgroup/bind6",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND, SEC_ATTACHABLE),
11141 	SEC_DEF("cgroup/connect4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT, SEC_ATTACHABLE),
11142 	SEC_DEF("cgroup/connect6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT, SEC_ATTACHABLE),
11143 	SEC_DEF("cgroup/connect_unix",	CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_CONNECT, SEC_ATTACHABLE),
11144 	SEC_DEF("cgroup/sendmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG, SEC_ATTACHABLE),
11145 	SEC_DEF("cgroup/sendmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG, SEC_ATTACHABLE),
11146 	SEC_DEF("cgroup/sendmsg_unix",	CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_SENDMSG, SEC_ATTACHABLE),
11147 	SEC_DEF("cgroup/recvmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_RECVMSG, SEC_ATTACHABLE),
11148 	SEC_DEF("cgroup/recvmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_RECVMSG, SEC_ATTACHABLE),
11149 	SEC_DEF("cgroup/recvmsg_unix",	CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_RECVMSG, SEC_ATTACHABLE),
11150 	SEC_DEF("cgroup/getpeername4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETPEERNAME, SEC_ATTACHABLE),
11151 	SEC_DEF("cgroup/getpeername6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETPEERNAME, SEC_ATTACHABLE),
11152 	SEC_DEF("cgroup/getpeername_unix", CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_GETPEERNAME, SEC_ATTACHABLE),
11153 	SEC_DEF("cgroup/getsockname4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETSOCKNAME, SEC_ATTACHABLE),
11154 	SEC_DEF("cgroup/getsockname6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETSOCKNAME, SEC_ATTACHABLE),
11155 	SEC_DEF("cgroup/getsockname_unix", CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_GETSOCKNAME, SEC_ATTACHABLE),
11156 	SEC_DEF("cgroup/sysctl",	CGROUP_SYSCTL, BPF_CGROUP_SYSCTL, SEC_ATTACHABLE),
11157 	SEC_DEF("cgroup/getsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_GETSOCKOPT, SEC_ATTACHABLE),
11158 	SEC_DEF("cgroup/setsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_SETSOCKOPT, SEC_ATTACHABLE),
11159 	SEC_DEF("cgroup/dev",		CGROUP_DEVICE, BPF_CGROUP_DEVICE, SEC_ATTACHABLE_OPT),
11160 	SEC_DEF("struct_ops+",		STRUCT_OPS, 0, SEC_NONE),
11161 	SEC_DEF("struct_ops.s+",	STRUCT_OPS, 0, SEC_SLEEPABLE),
11162 	SEC_DEF("sk_lookup",		SK_LOOKUP, BPF_SK_LOOKUP, SEC_ATTACHABLE),
11163 	SEC_DEF("netfilter",		NETFILTER, BPF_NETFILTER, SEC_NONE),
11164 };
11165 
11166 int libbpf_register_prog_handler(const char *sec,
11167 				 enum bpf_prog_type prog_type,
11168 				 enum bpf_attach_type exp_attach_type,
11169 				 const struct libbpf_prog_handler_opts *opts)
11170 {
11171 	struct bpf_sec_def *sec_def;
11172 
11173 	if (!OPTS_VALID(opts, libbpf_prog_handler_opts))
11174 		return libbpf_err(-EINVAL);
11175 
11176 	if (last_custom_sec_def_handler_id == INT_MAX) /* prevent overflow */
11177 		return libbpf_err(-E2BIG);
11178 
11179 	if (sec) {
11180 		sec_def = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt + 1,
11181 					      sizeof(*sec_def));
11182 		if (!sec_def)
11183 			return libbpf_err(-ENOMEM);
11184 
11185 		custom_sec_defs = sec_def;
11186 		sec_def = &custom_sec_defs[custom_sec_def_cnt];
11187 	} else {
11188 		if (has_custom_fallback_def)
11189 			return libbpf_err(-EBUSY);
11190 
11191 		sec_def = &custom_fallback_def;
11192 	}
11193 
11194 	sec_def->sec = sec ? strdup(sec) : NULL;
11195 	if (sec && !sec_def->sec)
11196 		return libbpf_err(-ENOMEM);
11197 
11198 	sec_def->prog_type = prog_type;
11199 	sec_def->expected_attach_type = exp_attach_type;
11200 	sec_def->cookie = OPTS_GET(opts, cookie, 0);
11201 
11202 	sec_def->prog_setup_fn = OPTS_GET(opts, prog_setup_fn, NULL);
11203 	sec_def->prog_prepare_load_fn = OPTS_GET(opts, prog_prepare_load_fn, NULL);
11204 	sec_def->prog_attach_fn = OPTS_GET(opts, prog_attach_fn, NULL);
11205 
11206 	sec_def->handler_id = ++last_custom_sec_def_handler_id;
11207 
11208 	if (sec)
11209 		custom_sec_def_cnt++;
11210 	else
11211 		has_custom_fallback_def = true;
11212 
11213 	return sec_def->handler_id;
11214 }
11215 
11216 int libbpf_unregister_prog_handler(int handler_id)
11217 {
11218 	struct bpf_sec_def *sec_defs;
11219 	int i;
11220 
11221 	if (handler_id <= 0)
11222 		return libbpf_err(-EINVAL);
11223 
11224 	if (has_custom_fallback_def && custom_fallback_def.handler_id == handler_id) {
11225 		memset(&custom_fallback_def, 0, sizeof(custom_fallback_def));
11226 		has_custom_fallback_def = false;
11227 		return 0;
11228 	}
11229 
11230 	for (i = 0; i < custom_sec_def_cnt; i++) {
11231 		if (custom_sec_defs[i].handler_id == handler_id)
11232 			break;
11233 	}
11234 
11235 	if (i == custom_sec_def_cnt)
11236 		return libbpf_err(-ENOENT);
11237 
11238 	free(custom_sec_defs[i].sec);
11239 	for (i = i + 1; i < custom_sec_def_cnt; i++)
11240 		custom_sec_defs[i - 1] = custom_sec_defs[i];
11241 	custom_sec_def_cnt--;
11242 
11243 	/* try to shrink the array, but it's ok if we couldn't */
11244 	sec_defs = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt, sizeof(*sec_defs));
11245 	/* if new count is zero, reallocarray can return a valid NULL result;
11246 	 * in this case the previous pointer will be freed, so we *have to*
11247 	 * reassign old pointer to the new value (even if it's NULL)
11248 	 */
11249 	if (sec_defs || custom_sec_def_cnt == 0)
11250 		custom_sec_defs = sec_defs;
11251 
11252 	return 0;
11253 }
11254 
11255 static bool sec_def_matches(const struct bpf_sec_def *sec_def, const char *sec_name)
11256 {
11257 	size_t len = strlen(sec_def->sec);
11258 
11259 	/* "type/" always has to have proper SEC("type/extras") form */
11260 	if (sec_def->sec[len - 1] == '/') {
11261 		if (str_has_pfx(sec_name, sec_def->sec))
11262 			return true;
11263 		return false;
11264 	}
11265 
11266 	/* "type+" means it can be either exact SEC("type") or
11267 	 * well-formed SEC("type/extras") with proper '/' separator
11268 	 */
11269 	if (sec_def->sec[len - 1] == '+') {
11270 		len--;
11271 		/* not even a prefix */
11272 		if (strncmp(sec_name, sec_def->sec, len) != 0)
11273 			return false;
11274 		/* exact match or has '/' separator */
11275 		if (sec_name[len] == '\0' || sec_name[len] == '/')
11276 			return true;
11277 		return false;
11278 	}
11279 
11280 	return strcmp(sec_name, sec_def->sec) == 0;
11281 }
11282 
11283 static const struct bpf_sec_def *find_sec_def(const char *sec_name)
11284 {
11285 	const struct bpf_sec_def *sec_def;
11286 	int i, n;
11287 
11288 	n = custom_sec_def_cnt;
11289 	for (i = 0; i < n; i++) {
11290 		sec_def = &custom_sec_defs[i];
11291 		if (sec_def_matches(sec_def, sec_name))
11292 			return sec_def;
11293 	}
11294 
11295 	n = ARRAY_SIZE(section_defs);
11296 	for (i = 0; i < n; i++) {
11297 		sec_def = &section_defs[i];
11298 		if (sec_def_matches(sec_def, sec_name))
11299 			return sec_def;
11300 	}
11301 
11302 	if (has_custom_fallback_def)
11303 		return &custom_fallback_def;
11304 
11305 	return NULL;
11306 }
11307 
11308 #define MAX_TYPE_NAME_SIZE 32
11309 
11310 static char *libbpf_get_type_names(bool attach_type)
11311 {
11312 	int i, len = ARRAY_SIZE(section_defs) * MAX_TYPE_NAME_SIZE;
11313 	char *buf;
11314 
11315 	buf = malloc(len);
11316 	if (!buf)
11317 		return NULL;
11318 
11319 	buf[0] = '\0';
11320 	/* Forge string buf with all available names */
11321 	for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
11322 		const struct bpf_sec_def *sec_def = &section_defs[i];
11323 
11324 		if (attach_type) {
11325 			if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
11326 				continue;
11327 
11328 			if (!(sec_def->cookie & SEC_ATTACHABLE))
11329 				continue;
11330 		}
11331 
11332 		if (strlen(buf) + strlen(section_defs[i].sec) + 2 > len) {
11333 			free(buf);
11334 			return NULL;
11335 		}
11336 		strcat(buf, " ");
11337 		strcat(buf, section_defs[i].sec);
11338 	}
11339 
11340 	return buf;
11341 }
11342 
11343 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
11344 			     enum bpf_attach_type *expected_attach_type)
11345 {
11346 	const struct bpf_sec_def *sec_def;
11347 	char *type_names;
11348 
11349 	if (!name)
11350 		return libbpf_err(-EINVAL);
11351 
11352 	sec_def = find_sec_def(name);
11353 	if (sec_def) {
11354 		*prog_type = sec_def->prog_type;
11355 		*expected_attach_type = sec_def->expected_attach_type;
11356 		return 0;
11357 	}
11358 
11359 	pr_debug("failed to guess program type from ELF section '%s'\n", name);
11360 	type_names = libbpf_get_type_names(false);
11361 	if (type_names != NULL) {
11362 		pr_debug("supported section(type) names are:%s\n", type_names);
11363 		free(type_names);
11364 	}
11365 
11366 	return libbpf_err(-ESRCH);
11367 }
11368 
11369 const char *libbpf_bpf_attach_type_str(enum bpf_attach_type t)
11370 {
11371 	if (t < 0 || t >= ARRAY_SIZE(attach_type_name))
11372 		return NULL;
11373 
11374 	return attach_type_name[t];
11375 }
11376 
11377 const char *libbpf_bpf_link_type_str(enum bpf_link_type t)
11378 {
11379 	if (t < 0 || t >= ARRAY_SIZE(link_type_name))
11380 		return NULL;
11381 
11382 	return link_type_name[t];
11383 }
11384 
11385 const char *libbpf_bpf_map_type_str(enum bpf_map_type t)
11386 {
11387 	if (t < 0 || t >= ARRAY_SIZE(map_type_name))
11388 		return NULL;
11389 
11390 	return map_type_name[t];
11391 }
11392 
11393 const char *libbpf_bpf_prog_type_str(enum bpf_prog_type t)
11394 {
11395 	if (t < 0 || t >= ARRAY_SIZE(prog_type_name))
11396 		return NULL;
11397 
11398 	return prog_type_name[t];
11399 }
11400 
11401 static struct bpf_map *find_struct_ops_map_by_offset(struct bpf_object *obj,
11402 						     int sec_idx,
11403 						     size_t offset)
11404 {
11405 	struct bpf_map *map;
11406 	size_t i;
11407 
11408 	for (i = 0; i < obj->nr_maps; i++) {
11409 		map = &obj->maps[i];
11410 		if (!bpf_map__is_struct_ops(map))
11411 			continue;
11412 		if (map->sec_idx == sec_idx &&
11413 		    map->sec_offset <= offset &&
11414 		    offset - map->sec_offset < map->def.value_size)
11415 			return map;
11416 	}
11417 
11418 	return NULL;
11419 }
11420 
11421 /* Collect the reloc from ELF, populate the st_ops->progs[], and update
11422  * st_ops->data for shadow type.
11423  */
11424 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
11425 					    Elf64_Shdr *shdr, Elf_Data *data)
11426 {
11427 	const struct btf_type *type;
11428 	const struct btf_member *member;
11429 	struct bpf_struct_ops *st_ops;
11430 	struct bpf_program *prog;
11431 	unsigned int shdr_idx;
11432 	const struct btf *btf;
11433 	struct bpf_map *map;
11434 	unsigned int moff, insn_idx;
11435 	const char *name;
11436 	__u32 member_idx;
11437 	Elf64_Sym *sym;
11438 	Elf64_Rel *rel;
11439 	int i, nrels;
11440 
11441 	btf = obj->btf;
11442 	nrels = shdr->sh_size / shdr->sh_entsize;
11443 	for (i = 0; i < nrels; i++) {
11444 		rel = elf_rel_by_idx(data, i);
11445 		if (!rel) {
11446 			pr_warn("struct_ops reloc: failed to get %d reloc\n", i);
11447 			return -LIBBPF_ERRNO__FORMAT;
11448 		}
11449 
11450 		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
11451 		if (!sym) {
11452 			pr_warn("struct_ops reloc: symbol %zx not found\n",
11453 				(size_t)ELF64_R_SYM(rel->r_info));
11454 			return -LIBBPF_ERRNO__FORMAT;
11455 		}
11456 
11457 		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
11458 		map = find_struct_ops_map_by_offset(obj, shdr->sh_info, rel->r_offset);
11459 		if (!map) {
11460 			pr_warn("struct_ops reloc: cannot find map at rel->r_offset %zu\n",
11461 				(size_t)rel->r_offset);
11462 			return -EINVAL;
11463 		}
11464 
11465 		moff = rel->r_offset - map->sec_offset;
11466 		shdr_idx = sym->st_shndx;
11467 		st_ops = map->st_ops;
11468 		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",
11469 			 map->name,
11470 			 (long long)(rel->r_info >> 32),
11471 			 (long long)sym->st_value,
11472 			 shdr_idx, (size_t)rel->r_offset,
11473 			 map->sec_offset, sym->st_name, name);
11474 
11475 		if (shdr_idx >= SHN_LORESERVE) {
11476 			pr_warn("struct_ops reloc %s: rel->r_offset %zu shdr_idx %u unsupported non-static function\n",
11477 				map->name, (size_t)rel->r_offset, shdr_idx);
11478 			return -LIBBPF_ERRNO__RELOC;
11479 		}
11480 		if (sym->st_value % BPF_INSN_SZ) {
11481 			pr_warn("struct_ops reloc %s: invalid target program offset %llu\n",
11482 				map->name, (unsigned long long)sym->st_value);
11483 			return -LIBBPF_ERRNO__FORMAT;
11484 		}
11485 		insn_idx = sym->st_value / BPF_INSN_SZ;
11486 
11487 		type = btf__type_by_id(btf, st_ops->type_id);
11488 		member = find_member_by_offset(type, moff * 8);
11489 		if (!member) {
11490 			pr_warn("struct_ops reloc %s: cannot find member at moff %u\n",
11491 				map->name, moff);
11492 			return -EINVAL;
11493 		}
11494 		member_idx = member - btf_members(type);
11495 		name = btf__name_by_offset(btf, member->name_off);
11496 
11497 		if (!resolve_func_ptr(btf, member->type, NULL)) {
11498 			pr_warn("struct_ops reloc %s: cannot relocate non func ptr %s\n",
11499 				map->name, name);
11500 			return -EINVAL;
11501 		}
11502 
11503 		prog = find_prog_by_sec_insn(obj, shdr_idx, insn_idx);
11504 		if (!prog) {
11505 			pr_warn("struct_ops reloc %s: cannot find prog at shdr_idx %u to relocate func ptr %s\n",
11506 				map->name, shdr_idx, name);
11507 			return -EINVAL;
11508 		}
11509 
11510 		/* prevent the use of BPF prog with invalid type */
11511 		if (prog->type != BPF_PROG_TYPE_STRUCT_OPS) {
11512 			pr_warn("struct_ops reloc %s: prog %s is not struct_ops BPF program\n",
11513 				map->name, prog->name);
11514 			return -EINVAL;
11515 		}
11516 
11517 		st_ops->progs[member_idx] = prog;
11518 
11519 		/* st_ops->data will be exposed to users, being returned by
11520 		 * bpf_map__initial_value() as a pointer to the shadow
11521 		 * type. All function pointers in the original struct type
11522 		 * should be converted to a pointer to struct bpf_program
11523 		 * in the shadow type.
11524 		 */
11525 		*((struct bpf_program **)(st_ops->data + moff)) = prog;
11526 	}
11527 
11528 	return 0;
11529 }
11530 
11531 #define BTF_TRACE_PREFIX "btf_trace_"
11532 #define BTF_LSM_PREFIX "bpf_lsm_"
11533 #define BTF_ITER_PREFIX "bpf_iter_"
11534 #define BTF_MAX_NAME_SIZE 128
11535 
11536 void btf_get_kernel_prefix_kind(enum bpf_attach_type attach_type,
11537 				const char **prefix, int *kind)
11538 {
11539 	switch (attach_type) {
11540 	case BPF_TRACE_RAW_TP:
11541 		*prefix = BTF_TRACE_PREFIX;
11542 		*kind = BTF_KIND_TYPEDEF;
11543 		break;
11544 	case BPF_LSM_MAC:
11545 	case BPF_LSM_CGROUP:
11546 		*prefix = BTF_LSM_PREFIX;
11547 		*kind = BTF_KIND_FUNC;
11548 		break;
11549 	case BPF_TRACE_ITER:
11550 		*prefix = BTF_ITER_PREFIX;
11551 		*kind = BTF_KIND_FUNC;
11552 		break;
11553 	default:
11554 		*prefix = "";
11555 		*kind = BTF_KIND_FUNC;
11556 	}
11557 }
11558 
11559 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
11560 				   const char *name, __u32 kind)
11561 {
11562 	char btf_type_name[BTF_MAX_NAME_SIZE];
11563 	int ret;
11564 
11565 	ret = snprintf(btf_type_name, sizeof(btf_type_name),
11566 		       "%s%s", prefix, name);
11567 	/* snprintf returns the number of characters written excluding the
11568 	 * terminating null. So, if >= BTF_MAX_NAME_SIZE are written, it
11569 	 * indicates truncation.
11570 	 */
11571 	if (ret < 0 || ret >= sizeof(btf_type_name))
11572 		return -ENAMETOOLONG;
11573 	return btf__find_by_name_kind(btf, btf_type_name, kind);
11574 }
11575 
11576 static inline int find_attach_btf_id(struct btf *btf, const char *name,
11577 				     enum bpf_attach_type attach_type)
11578 {
11579 	const char *prefix;
11580 	int kind;
11581 
11582 	btf_get_kernel_prefix_kind(attach_type, &prefix, &kind);
11583 	return find_btf_by_prefix_kind(btf, prefix, name, kind);
11584 }
11585 
11586 int libbpf_find_vmlinux_btf_id(const char *name,
11587 			       enum bpf_attach_type attach_type)
11588 {
11589 	struct btf *btf;
11590 	int err;
11591 
11592 	btf = btf__load_vmlinux_btf();
11593 	err = libbpf_get_error(btf);
11594 	if (err) {
11595 		pr_warn("vmlinux BTF is not found\n");
11596 		return libbpf_err(err);
11597 	}
11598 
11599 	err = find_attach_btf_id(btf, name, attach_type);
11600 	if (err <= 0)
11601 		pr_warn("%s is not found in vmlinux BTF\n", name);
11602 
11603 	btf__free(btf);
11604 	return libbpf_err(err);
11605 }
11606 
11607 static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd, int token_fd)
11608 {
11609 	struct bpf_prog_info info;
11610 	__u32 info_len = sizeof(info);
11611 	struct btf *btf;
11612 	int err;
11613 
11614 	memset(&info, 0, info_len);
11615 	err = bpf_prog_get_info_by_fd(attach_prog_fd, &info, &info_len);
11616 	if (err) {
11617 		pr_warn("failed bpf_prog_get_info_by_fd for FD %u: %s\n",
11618 			attach_prog_fd, errstr(err));
11619 		return err;
11620 	}
11621 
11622 	err = -EINVAL;
11623 	if (!info.btf_id) {
11624 		pr_warn("The target program doesn't have BTF\n");
11625 		goto out;
11626 	}
11627 	btf = btf_load_from_kernel(info.btf_id, NULL, token_fd);
11628 	err = libbpf_get_error(btf);
11629 	if (err) {
11630 		pr_warn("Failed to get BTF %u of the program: %s\n", info.btf_id, errstr(err));
11631 		goto out;
11632 	}
11633 	err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
11634 	btf__free(btf);
11635 	if (err <= 0) {
11636 		pr_warn("%s is not found in prog's BTF\n", name);
11637 		goto out;
11638 	}
11639 out:
11640 	return err;
11641 }
11642 
11643 static int find_kernel_btf_id(struct bpf_object *obj, const char *attach_name,
11644 			      enum bpf_attach_type attach_type,
11645 			      int *btf_obj_fd, int *btf_type_id)
11646 {
11647 	int ret, i, mod_len = 0;
11648 	const char *fn_name, *mod_name = NULL;
11649 
11650 	fn_name = strchr(attach_name, ':');
11651 	if (fn_name) {
11652 		mod_name = attach_name;
11653 		mod_len = fn_name - mod_name;
11654 		fn_name++;
11655 	}
11656 
11657 	if (!mod_name || strncmp(mod_name, "vmlinux", mod_len) == 0) {
11658 		ret = find_attach_btf_id(obj->btf_vmlinux,
11659 					 mod_name ? fn_name : attach_name,
11660 					 attach_type);
11661 		if (ret > 0) {
11662 			*btf_obj_fd = 0; /* vmlinux BTF */
11663 			*btf_type_id = ret;
11664 			return 0;
11665 		}
11666 		if (ret != -ENOENT)
11667 			return ret;
11668 	}
11669 
11670 	ret = load_module_btfs(obj);
11671 	if (ret)
11672 		return ret;
11673 
11674 	for (i = 0; i < obj->btf_module_cnt; i++) {
11675 		const struct module_btf *mod = &obj->btf_modules[i];
11676 
11677 		if (mod_name && strncmp(mod->name, mod_name, mod_len) != 0)
11678 			continue;
11679 
11680 		ret = find_attach_btf_id(mod->btf,
11681 					 mod_name ? fn_name : attach_name,
11682 					 attach_type);
11683 		if (ret > 0) {
11684 			*btf_obj_fd = mod->fd;
11685 			*btf_type_id = ret;
11686 			return 0;
11687 		}
11688 		if (ret == -ENOENT)
11689 			continue;
11690 
11691 		return ret;
11692 	}
11693 
11694 	return -ESRCH;
11695 }
11696 
11697 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
11698 				     int *btf_obj_fd, int *btf_type_id)
11699 {
11700 	enum bpf_attach_type attach_type = prog->expected_attach_type;
11701 	__u32 attach_prog_fd = prog->attach_prog_fd;
11702 	int err = 0;
11703 
11704 	/* BPF program's BTF ID */
11705 	if (prog->type == BPF_PROG_TYPE_EXT || attach_prog_fd) {
11706 		if (!attach_prog_fd) {
11707 			pr_warn("prog '%s': attach program FD is not set\n", prog->name);
11708 			return -EINVAL;
11709 		}
11710 		err = libbpf_find_prog_btf_id(attach_name, attach_prog_fd, prog->obj->token_fd);
11711 		if (err < 0) {
11712 			pr_warn("prog '%s': failed to find BPF program (FD %u) BTF ID for '%s': %s\n",
11713 				prog->name, attach_prog_fd, attach_name, errstr(err));
11714 			return err;
11715 		}
11716 		*btf_obj_fd = 0;
11717 		*btf_type_id = err;
11718 		return 0;
11719 	}
11720 
11721 	/* kernel/module BTF ID */
11722 	if (prog->obj->gen_loader) {
11723 		bpf_gen__record_attach_target(prog->obj->gen_loader, attach_name, attach_type);
11724 		*btf_obj_fd = 0;
11725 		*btf_type_id = 1;
11726 	} else {
11727 		err = find_kernel_btf_id(prog->obj, attach_name,
11728 					 attach_type, btf_obj_fd,
11729 					 btf_type_id);
11730 	}
11731 	if (err) {
11732 		pr_warn("prog '%s': failed to find kernel BTF type ID of '%s': %s\n",
11733 			prog->name, attach_name, errstr(err));
11734 		return err;
11735 	}
11736 	return 0;
11737 }
11738 
11739 int libbpf_attach_type_by_name(const char *name,
11740 			       enum bpf_attach_type *attach_type)
11741 {
11742 	char *type_names;
11743 	const struct bpf_sec_def *sec_def;
11744 
11745 	if (!name)
11746 		return libbpf_err(-EINVAL);
11747 
11748 	sec_def = find_sec_def(name);
11749 	if (!sec_def) {
11750 		pr_debug("failed to guess attach type based on ELF section name '%s'\n", name);
11751 		type_names = libbpf_get_type_names(true);
11752 		if (type_names != NULL) {
11753 			pr_debug("attachable section(type) names are:%s\n", type_names);
11754 			free(type_names);
11755 		}
11756 
11757 		return libbpf_err(-EINVAL);
11758 	}
11759 
11760 	if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
11761 		return libbpf_err(-EINVAL);
11762 	if (!(sec_def->cookie & SEC_ATTACHABLE))
11763 		return libbpf_err(-EINVAL);
11764 
11765 	*attach_type = sec_def->expected_attach_type;
11766 	return 0;
11767 }
11768 
11769 int bpf_map__fd(const struct bpf_map *map)
11770 {
11771 	if (!map)
11772 		return libbpf_err(-EINVAL);
11773 	if (!map_is_created(map))
11774 		return -1;
11775 	return map->fd;
11776 }
11777 
11778 static bool map_uses_real_name(const struct bpf_map *map)
11779 {
11780 	/* Since libbpf started to support custom .data.* and .rodata.* maps,
11781 	 * their user-visible name differs from kernel-visible name. Users see
11782 	 * such map's corresponding ELF section name as a map name.
11783 	 * This check distinguishes .data/.rodata from .data.* and .rodata.*
11784 	 * maps to know which name has to be returned to the user.
11785 	 * Map name of the custom .percpu.* maps might be truncated to
11786 	 * BPF_OBJ_NAME_LEN-1 chars in internal_map_name(). Hence, percpu data
11787 	 * maps must use real name for their user-visible name.
11788 	 */
11789 	if (map->libbpf_type == LIBBPF_MAP_DATA && strcmp(map->real_name, DATA_SEC) != 0)
11790 		return true;
11791 	if (map->libbpf_type == LIBBPF_MAP_RODATA && strcmp(map->real_name, RODATA_SEC) != 0)
11792 		return true;
11793 	if (map->libbpf_type == LIBBPF_MAP_PERCPU)
11794 		return true;
11795 	return false;
11796 }
11797 
11798 const char *bpf_map__name(const struct bpf_map *map)
11799 {
11800 	if (!map)
11801 		return NULL;
11802 
11803 	if (map_uses_real_name(map))
11804 		return map->real_name;
11805 
11806 	return map->name;
11807 }
11808 
11809 enum bpf_map_type bpf_map__type(const struct bpf_map *map)
11810 {
11811 	return map->def.type;
11812 }
11813 
11814 int bpf_map__set_type(struct bpf_map *map, enum bpf_map_type type)
11815 {
11816 	if (map_is_created(map))
11817 		return libbpf_err(-EBUSY);
11818 	map->def.type = type;
11819 	return 0;
11820 }
11821 
11822 __u32 bpf_map__map_flags(const struct bpf_map *map)
11823 {
11824 	return map->def.map_flags;
11825 }
11826 
11827 int bpf_map__set_map_flags(struct bpf_map *map, __u32 flags)
11828 {
11829 	if (map_is_created(map))
11830 		return libbpf_err(-EBUSY);
11831 	map->def.map_flags = flags;
11832 	return 0;
11833 }
11834 
11835 __u64 bpf_map__map_extra(const struct bpf_map *map)
11836 {
11837 	return map->map_extra;
11838 }
11839 
11840 int bpf_map__set_map_extra(struct bpf_map *map, __u64 map_extra)
11841 {
11842 	if (map_is_created(map))
11843 		return libbpf_err(-EBUSY);
11844 	map->map_extra = map_extra;
11845 	return 0;
11846 }
11847 
11848 __u32 bpf_map__numa_node(const struct bpf_map *map)
11849 {
11850 	return map->numa_node;
11851 }
11852 
11853 int bpf_map__set_numa_node(struct bpf_map *map, __u32 numa_node)
11854 {
11855 	if (map_is_created(map))
11856 		return libbpf_err(-EBUSY);
11857 	map->numa_node = numa_node;
11858 	return 0;
11859 }
11860 
11861 __u32 bpf_map__key_size(const struct bpf_map *map)
11862 {
11863 	return map->def.key_size;
11864 }
11865 
11866 int bpf_map__set_key_size(struct bpf_map *map, __u32 size)
11867 {
11868 	if (map_is_created(map))
11869 		return libbpf_err(-EBUSY);
11870 	map->def.key_size = size;
11871 	return 0;
11872 }
11873 
11874 __u32 bpf_map__value_size(const struct bpf_map *map)
11875 {
11876 	return map->def.value_size;
11877 }
11878 
11879 static int map_btf_datasec_resize(struct bpf_map *map, __u32 size)
11880 {
11881 	struct btf *btf;
11882 	struct btf_type *datasec_type, *var_type;
11883 	struct btf_var_secinfo *var;
11884 	const struct btf_type *array_type;
11885 	const struct btf_array *array;
11886 	int vlen, element_sz, new_array_id;
11887 	__u32 nr_elements;
11888 
11889 	/* check btf existence */
11890 	btf = bpf_object__btf(map->obj);
11891 	if (!btf)
11892 		return -ENOENT;
11893 
11894 	/* verify map is datasec */
11895 	datasec_type = btf_type_by_id(btf, bpf_map__btf_value_type_id(map));
11896 	if (!btf_is_datasec(datasec_type)) {
11897 		pr_warn("map '%s': cannot be resized, map value type is not a datasec\n",
11898 			bpf_map__name(map));
11899 		return -EINVAL;
11900 	}
11901 
11902 	/* verify datasec has at least one var */
11903 	vlen = btf_vlen(datasec_type);
11904 	if (vlen == 0) {
11905 		pr_warn("map '%s': cannot be resized, map value datasec is empty\n",
11906 			bpf_map__name(map));
11907 		return -EINVAL;
11908 	}
11909 
11910 	/* verify last var in the datasec is an array */
11911 	var = &btf_var_secinfos(datasec_type)[vlen - 1];
11912 	var_type = btf_type_by_id(btf, var->type);
11913 	array_type = skip_mods_and_typedefs(btf, var_type->type, NULL);
11914 	if (!btf_is_array(array_type)) {
11915 		pr_warn("map '%s': cannot be resized, last var must be an array\n",
11916 			bpf_map__name(map));
11917 		return -EINVAL;
11918 	}
11919 
11920 	/* verify request size aligns with array */
11921 	array = btf_array(array_type);
11922 	element_sz = btf__resolve_size(btf, array->type);
11923 	if (element_sz <= 0 || (size - var->offset) % element_sz != 0) {
11924 		pr_warn("map '%s': cannot be resized, element size (%d) doesn't align with new total size (%u)\n",
11925 			bpf_map__name(map), element_sz, size);
11926 		return -EINVAL;
11927 	}
11928 
11929 	/* create a new array based on the existing array, but with new length */
11930 	nr_elements = (size - var->offset) / element_sz;
11931 	new_array_id = btf__add_array(btf, array->index_type, array->type, nr_elements);
11932 	if (new_array_id < 0)
11933 		return new_array_id;
11934 
11935 	/* adding a new btf type invalidates existing pointers to btf objects,
11936 	 * so refresh pointers before proceeding
11937 	 */
11938 	datasec_type = btf_type_by_id(btf, map->btf_value_type_id);
11939 	var = &btf_var_secinfos(datasec_type)[vlen - 1];
11940 	var_type = btf_type_by_id(btf, var->type);
11941 
11942 	/* finally update btf info */
11943 	datasec_type->size = size;
11944 	var->size = size - var->offset;
11945 	var_type->type = new_array_id;
11946 
11947 	return 0;
11948 }
11949 
11950 int bpf_map__set_value_size(struct bpf_map *map, __u32 size)
11951 {
11952 	if (map_is_created(map))
11953 		return libbpf_err(-EBUSY);
11954 
11955 	if (map->in_arena)
11956 		return libbpf_err(-EOPNOTSUPP);
11957 
11958 	if (map->mmaped) {
11959 		size_t mmap_old_sz, mmap_new_sz;
11960 		int err;
11961 
11962 		if (map->def.type != BPF_MAP_TYPE_ARRAY &&
11963 		    map->def.type != BPF_MAP_TYPE_PERCPU_ARRAY)
11964 			return libbpf_err(-EOPNOTSUPP);
11965 
11966 		mmap_old_sz = bpf_map_mmap_sz(map);
11967 		mmap_new_sz = array_map_mmap_sz(size, map->def.max_entries);
11968 		err = bpf_map_mmap_resize(map, mmap_old_sz, mmap_new_sz);
11969 		if (err) {
11970 			pr_warn("map '%s': failed to resize memory-mapped region: %s\n",
11971 				bpf_map__name(map), errstr(err));
11972 			return libbpf_err(err);
11973 		}
11974 		err = map_btf_datasec_resize(map, size);
11975 		if (err && err != -ENOENT) {
11976 			pr_warn("map '%s': failed to adjust resized BTF, clearing BTF key/value info: %s\n",
11977 				bpf_map__name(map), errstr(err));
11978 			map->btf_value_type_id = 0;
11979 			map->btf_key_type_id = 0;
11980 		}
11981 	}
11982 
11983 	map->def.value_size = size;
11984 	return 0;
11985 }
11986 
11987 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
11988 {
11989 	return map ? map->btf_key_type_id : 0;
11990 }
11991 
11992 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
11993 {
11994 	return map ? map->btf_value_type_id : 0;
11995 }
11996 
11997 int bpf_map__set_initial_value(struct bpf_map *map,
11998 			       const void *data, size_t size)
11999 {
12000 	size_t actual_sz;
12001 
12002 	if (map_is_created(map))
12003 		return libbpf_err(-EBUSY);
12004 
12005 	if (!map->mmaped || map->libbpf_type == LIBBPF_MAP_KCONFIG)
12006 		return libbpf_err(-EINVAL);
12007 
12008 	if (map->def.type == BPF_MAP_TYPE_ARENA)
12009 		actual_sz = map->obj->arena_data_sz;
12010 	else
12011 		actual_sz = map->def.value_size;
12012 	if (size != actual_sz)
12013 		return libbpf_err(-EINVAL);
12014 
12015 	memcpy(map->mmaped, data, size);
12016 	return 0;
12017 }
12018 
12019 void *bpf_map__initial_value(const struct bpf_map *map, size_t *psize)
12020 {
12021 	if (bpf_map__is_struct_ops(map)) {
12022 		if (psize)
12023 			*psize = map->def.value_size;
12024 		return map->st_ops->data;
12025 	}
12026 
12027 	if (!map->mmaped)
12028 		return NULL;
12029 
12030 	if (map->def.type == BPF_MAP_TYPE_ARENA)
12031 		*psize = map->obj->arena_data_sz;
12032 	else
12033 		*psize = map->def.value_size;
12034 
12035 	return map->mmaped;
12036 }
12037 
12038 bool bpf_map__is_internal(const struct bpf_map *map)
12039 {
12040 	return map->libbpf_type != LIBBPF_MAP_UNSPEC;
12041 }
12042 
12043 __u32 bpf_map__ifindex(const struct bpf_map *map)
12044 {
12045 	return map->map_ifindex;
12046 }
12047 
12048 int bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
12049 {
12050 	if (map_is_created(map))
12051 		return libbpf_err(-EBUSY);
12052 	map->map_ifindex = ifindex;
12053 	return 0;
12054 }
12055 
12056 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
12057 {
12058 	if (!bpf_map_type__is_map_in_map(map->def.type)) {
12059 		pr_warn("error: unsupported map type\n");
12060 		return libbpf_err(-EINVAL);
12061 	}
12062 	if (map->inner_map_fd != -1) {
12063 		pr_warn("error: inner_map_fd already specified\n");
12064 		return libbpf_err(-EINVAL);
12065 	}
12066 	if (map->inner_map) {
12067 		bpf_map__destroy(map->inner_map);
12068 		zfree(&map->inner_map);
12069 	}
12070 	map->inner_map_fd = fd;
12071 	return 0;
12072 }
12073 
12074 int bpf_map__set_exclusive_program(struct bpf_map *map, struct bpf_program *prog)
12075 {
12076 	if (map_is_created(map)) {
12077 		pr_warn("exclusive programs must be set before map creation\n");
12078 		return libbpf_err(-EINVAL);
12079 	}
12080 
12081 	if (map->obj != prog->obj) {
12082 		pr_warn("excl_prog and map must be from the same bpf object\n");
12083 		return libbpf_err(-EINVAL);
12084 	}
12085 
12086 	map->excl_prog = prog;
12087 	return 0;
12088 }
12089 
12090 struct bpf_program *bpf_map__exclusive_program(struct bpf_map *map)
12091 {
12092 	return map->excl_prog;
12093 }
12094 
12095 static struct bpf_map *
12096 __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
12097 {
12098 	ssize_t idx;
12099 	struct bpf_map *s, *e;
12100 
12101 	if (!obj || !obj->maps)
12102 		return errno = EINVAL, NULL;
12103 
12104 	s = obj->maps;
12105 	e = obj->maps + obj->nr_maps;
12106 
12107 	if ((m < s) || (m >= e)) {
12108 		pr_warn("error in %s: map handler doesn't belong to object\n",
12109 			 __func__);
12110 		return errno = EINVAL, NULL;
12111 	}
12112 
12113 	idx = (m - obj->maps) + i;
12114 	if (idx >= obj->nr_maps || idx < 0)
12115 		return NULL;
12116 	return &obj->maps[idx];
12117 }
12118 
12119 struct bpf_map *
12120 bpf_object__next_map(const struct bpf_object *obj, const struct bpf_map *prev)
12121 {
12122 	if (prev == NULL && obj != NULL)
12123 		return obj->maps;
12124 
12125 	return __bpf_map__iter(prev, obj, 1);
12126 }
12127 
12128 struct bpf_map *
12129 bpf_object__prev_map(const struct bpf_object *obj, const struct bpf_map *next)
12130 {
12131 	if (next == NULL && obj != NULL) {
12132 		if (!obj->nr_maps)
12133 			return NULL;
12134 		return obj->maps + obj->nr_maps - 1;
12135 	}
12136 
12137 	return __bpf_map__iter(next, obj, -1);
12138 }
12139 
12140 struct bpf_map *
12141 bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
12142 {
12143 	struct bpf_map *pos;
12144 
12145 	bpf_object__for_each_map(pos, obj) {
12146 		/* if it's a special internal map name (which always starts
12147 		 * with dot) then check if that special name matches the
12148 		 * real map name (ELF section name)
12149 		 */
12150 		if (name[0] == '.') {
12151 			if (pos->real_name && strcmp(pos->real_name, name) == 0)
12152 				return pos;
12153 			continue;
12154 		}
12155 		/* otherwise map name has to be an exact match */
12156 		if (map_uses_real_name(pos)) {
12157 			if (strcmp(pos->real_name, name) == 0)
12158 				return pos;
12159 			continue;
12160 		}
12161 		if (strcmp(pos->name, name) == 0)
12162 			return pos;
12163 	}
12164 	return errno = ENOENT, NULL;
12165 }
12166 
12167 int
12168 bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
12169 {
12170 	return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
12171 }
12172 
12173 static int validate_map_op(const struct bpf_map *map, size_t key_sz,
12174 			   size_t value_sz, bool check_value_sz, __u64 flags)
12175 {
12176 	if (!map_is_created(map)) /* map is not yet created */
12177 		return -ENOENT;
12178 
12179 	if (map->def.key_size != key_sz) {
12180 		pr_warn("map '%s': unexpected key size %zu provided, expected %u\n",
12181 			map->name, key_sz, map->def.key_size);
12182 		return -EINVAL;
12183 	}
12184 
12185 	if (map->fd < 0) {
12186 		pr_warn("map '%s': can't use BPF map without FD (was it created?)\n", map->name);
12187 		return -EINVAL;
12188 	}
12189 
12190 	if (!check_value_sz)
12191 		return 0;
12192 
12193 	switch (map->def.type) {
12194 	case BPF_MAP_TYPE_PERCPU_ARRAY:
12195 	case BPF_MAP_TYPE_PERCPU_HASH:
12196 	case BPF_MAP_TYPE_LRU_PERCPU_HASH:
12197 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: {
12198 		int num_cpu = libbpf_num_possible_cpus();
12199 		size_t elem_sz = roundup(map->def.value_size, 8);
12200 
12201 		if (flags & (BPF_F_CPU | BPF_F_ALL_CPUS)) {
12202 			if ((flags & BPF_F_CPU) && (flags & BPF_F_ALL_CPUS)) {
12203 				pr_warn("map '%s': BPF_F_CPU and BPF_F_ALL_CPUS are mutually exclusive\n",
12204 					map->name);
12205 				return -EINVAL;
12206 			}
12207 			if (map->def.value_size != value_sz) {
12208 				pr_warn("map '%s': unexpected value size %zu provided for either BPF_F_CPU or BPF_F_ALL_CPUS, expected %u\n",
12209 					map->name, value_sz, map->def.value_size);
12210 				return -EINVAL;
12211 			}
12212 			break;
12213 		}
12214 
12215 		if (value_sz != num_cpu * elem_sz) {
12216 			pr_warn("map '%s': unexpected value size %zu provided for per-CPU map, expected %d * %zu = %zu\n",
12217 				map->name, value_sz, num_cpu, elem_sz, num_cpu * elem_sz);
12218 			return -EINVAL;
12219 		}
12220 		break;
12221 	}
12222 	default:
12223 		if (map->def.value_size != value_sz) {
12224 			pr_warn("map '%s': unexpected value size %zu provided, expected %u\n",
12225 				map->name, value_sz, map->def.value_size);
12226 			return -EINVAL;
12227 		}
12228 		break;
12229 	}
12230 	return 0;
12231 }
12232 
12233 int bpf_map__lookup_elem(const struct bpf_map *map,
12234 			 const void *key, size_t key_sz,
12235 			 void *value, size_t value_sz, __u64 flags)
12236 {
12237 	int err;
12238 
12239 	err = validate_map_op(map, key_sz, value_sz, true, flags);
12240 	if (err)
12241 		return libbpf_err(err);
12242 
12243 	return bpf_map_lookup_elem_flags(map->fd, key, value, flags);
12244 }
12245 
12246 int bpf_map__update_elem(const struct bpf_map *map,
12247 			 const void *key, size_t key_sz,
12248 			 const void *value, size_t value_sz, __u64 flags)
12249 {
12250 	int err;
12251 
12252 	err = validate_map_op(map, key_sz, value_sz, true, flags);
12253 	if (err)
12254 		return libbpf_err(err);
12255 
12256 	return bpf_map_update_elem(map->fd, key, value, flags);
12257 }
12258 
12259 int bpf_map__delete_elem(const struct bpf_map *map,
12260 			 const void *key, size_t key_sz, __u64 flags)
12261 {
12262 	int err;
12263 
12264 	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */, flags);
12265 	if (err)
12266 		return libbpf_err(err);
12267 
12268 	return bpf_map_delete_elem_flags(map->fd, key, flags);
12269 }
12270 
12271 int bpf_map__lookup_and_delete_elem(const struct bpf_map *map,
12272 				    const void *key, size_t key_sz,
12273 				    void *value, size_t value_sz, __u64 flags)
12274 {
12275 	int err;
12276 
12277 	err = validate_map_op(map, key_sz, value_sz, true, flags);
12278 	if (err)
12279 		return libbpf_err(err);
12280 
12281 	return bpf_map_lookup_and_delete_elem_flags(map->fd, key, value, flags);
12282 }
12283 
12284 int bpf_map__get_next_key(const struct bpf_map *map,
12285 			  const void *cur_key, void *next_key, size_t key_sz)
12286 {
12287 	int err;
12288 
12289 	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */, 0);
12290 	if (err)
12291 		return libbpf_err(err);
12292 
12293 	return bpf_map_get_next_key(map->fd, cur_key, next_key);
12294 }
12295 
12296 long libbpf_get_error(const void *ptr)
12297 {
12298 	if (!IS_ERR_OR_NULL(ptr))
12299 		return 0;
12300 
12301 	if (IS_ERR(ptr))
12302 		errno = -PTR_ERR(ptr);
12303 
12304 	/* If ptr == NULL, then errno should be already set by the failing
12305 	 * API, because libbpf never returns NULL on success and it now always
12306 	 * sets errno on error. So no extra errno handling for ptr == NULL
12307 	 * case.
12308 	 */
12309 	return -errno;
12310 }
12311 
12312 /* Replace link's underlying BPF program with the new one */
12313 int bpf_link__update_program(struct bpf_link *link, struct bpf_program *prog)
12314 {
12315 	int ret;
12316 	int prog_fd = bpf_program__fd(prog);
12317 
12318 	if (prog_fd < 0) {
12319 		pr_warn("prog '%s': can't use BPF program without FD (was it loaded?)\n",
12320 			prog->name);
12321 		return libbpf_err(-EINVAL);
12322 	}
12323 
12324 	ret = bpf_link_update(bpf_link__fd(link), prog_fd, NULL);
12325 	return libbpf_err_errno(ret);
12326 }
12327 
12328 /* Release "ownership" of underlying BPF resource (typically, BPF program
12329  * attached to some BPF hook, e.g., tracepoint, kprobe, etc). Disconnected
12330  * link, when destructed through bpf_link__destroy() call won't attempt to
12331  * detach/unregisted that BPF resource. This is useful in situations where,
12332  * say, attached BPF program has to outlive userspace program that attached it
12333  * in the system. Depending on type of BPF program, though, there might be
12334  * additional steps (like pinning BPF program in BPF FS) necessary to ensure
12335  * exit of userspace program doesn't trigger automatic detachment and clean up
12336  * inside the kernel.
12337  */
12338 void bpf_link__disconnect(struct bpf_link *link)
12339 {
12340 	link->disconnected = true;
12341 }
12342 
12343 int bpf_link__destroy(struct bpf_link *link)
12344 {
12345 	int err = 0;
12346 
12347 	if (IS_ERR_OR_NULL(link))
12348 		return 0;
12349 
12350 	if (!link->disconnected && link->detach)
12351 		err = link->detach(link);
12352 	if (link->pin_path)
12353 		free(link->pin_path);
12354 	if (link->dealloc)
12355 		link->dealloc(link);
12356 	else
12357 		free(link);
12358 
12359 	return libbpf_err(err);
12360 }
12361 
12362 int bpf_link__fd(const struct bpf_link *link)
12363 {
12364 	return link->fd;
12365 }
12366 
12367 const char *bpf_link__pin_path(const struct bpf_link *link)
12368 {
12369 	return link->pin_path;
12370 }
12371 
12372 static int bpf_link__detach_fd(struct bpf_link *link)
12373 {
12374 	return libbpf_err_errno(close(link->fd));
12375 }
12376 
12377 struct bpf_link *bpf_link__open(const char *path)
12378 {
12379 	struct bpf_link *link;
12380 	int fd;
12381 
12382 	fd = bpf_obj_get(path);
12383 	if (fd < 0) {
12384 		fd = -errno;
12385 		pr_warn("failed to open link at %s: %d\n", path, fd);
12386 		return libbpf_err_ptr(fd);
12387 	}
12388 
12389 	link = calloc(1, sizeof(*link));
12390 	if (!link) {
12391 		close(fd);
12392 		return libbpf_err_ptr(-ENOMEM);
12393 	}
12394 	link->detach = &bpf_link__detach_fd;
12395 	link->fd = fd;
12396 
12397 	link->pin_path = strdup(path);
12398 	if (!link->pin_path) {
12399 		bpf_link__destroy(link);
12400 		return libbpf_err_ptr(-ENOMEM);
12401 	}
12402 
12403 	return link;
12404 }
12405 
12406 int bpf_link__detach(struct bpf_link *link)
12407 {
12408 	return bpf_link_detach(link->fd) ? -errno : 0;
12409 }
12410 
12411 int bpf_link__pin(struct bpf_link *link, const char *path)
12412 {
12413 	int err;
12414 
12415 	if (link->pin_path)
12416 		return libbpf_err(-EBUSY);
12417 	err = make_parent_dir(path);
12418 	if (err)
12419 		return libbpf_err(err);
12420 	err = check_path(path);
12421 	if (err)
12422 		return libbpf_err(err);
12423 
12424 	link->pin_path = strdup(path);
12425 	if (!link->pin_path)
12426 		return libbpf_err(-ENOMEM);
12427 
12428 	if (bpf_obj_pin(link->fd, link->pin_path)) {
12429 		err = -errno;
12430 		zfree(&link->pin_path);
12431 		return libbpf_err(err);
12432 	}
12433 
12434 	pr_debug("link fd=%d: pinned at %s\n", link->fd, link->pin_path);
12435 	return 0;
12436 }
12437 
12438 int bpf_link__unpin(struct bpf_link *link)
12439 {
12440 	int err;
12441 
12442 	if (!link->pin_path)
12443 		return libbpf_err(-EINVAL);
12444 
12445 	err = unlink(link->pin_path);
12446 	if (err != 0)
12447 		return -errno;
12448 
12449 	pr_debug("link fd=%d: unpinned from %s\n", link->fd, link->pin_path);
12450 	zfree(&link->pin_path);
12451 	return 0;
12452 }
12453 
12454 struct bpf_link_perf {
12455 	struct bpf_link link;
12456 	int perf_event_fd;
12457 	/* legacy kprobe support: keep track of probe identifier and type */
12458 	char *legacy_probe_name;
12459 	bool legacy_is_kprobe;
12460 	bool legacy_is_retprobe;
12461 };
12462 
12463 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe);
12464 static int remove_uprobe_event_legacy(const char *probe_name, bool retprobe);
12465 
12466 static int bpf_link_perf_detach(struct bpf_link *link)
12467 {
12468 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
12469 	int err = 0;
12470 
12471 	if (ioctl(perf_link->perf_event_fd, PERF_EVENT_IOC_DISABLE, 0) < 0)
12472 		err = -errno;
12473 
12474 	if (perf_link->perf_event_fd != link->fd)
12475 		close(perf_link->perf_event_fd);
12476 	close(link->fd);
12477 
12478 	/* legacy uprobe/kprobe needs to be removed after perf event fd closure */
12479 	if (perf_link->legacy_probe_name) {
12480 		if (perf_link->legacy_is_kprobe) {
12481 			err = remove_kprobe_event_legacy(perf_link->legacy_probe_name,
12482 							 perf_link->legacy_is_retprobe);
12483 		} else {
12484 			err = remove_uprobe_event_legacy(perf_link->legacy_probe_name,
12485 							 perf_link->legacy_is_retprobe);
12486 		}
12487 	}
12488 
12489 	return err;
12490 }
12491 
12492 static void bpf_link_perf_dealloc(struct bpf_link *link)
12493 {
12494 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
12495 
12496 	free(perf_link->legacy_probe_name);
12497 	free(perf_link);
12498 }
12499 
12500 struct bpf_link *bpf_program__attach_perf_event_opts(const struct bpf_program *prog, int pfd,
12501 						     const struct bpf_perf_event_opts *opts)
12502 {
12503 	struct bpf_link_perf *link;
12504 	int prog_fd, link_fd = -1, err;
12505 	bool force_ioctl_attach;
12506 
12507 	if (!OPTS_VALID(opts, bpf_perf_event_opts))
12508 		return libbpf_err_ptr(-EINVAL);
12509 
12510 	if (pfd < 0) {
12511 		pr_warn("prog '%s': invalid perf event FD %d\n",
12512 			prog->name, pfd);
12513 		return libbpf_err_ptr(-EINVAL);
12514 	}
12515 	prog_fd = bpf_program__fd(prog);
12516 	if (prog_fd < 0) {
12517 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
12518 			prog->name);
12519 		return libbpf_err_ptr(-EINVAL);
12520 	}
12521 
12522 	link = calloc(1, sizeof(*link));
12523 	if (!link)
12524 		return libbpf_err_ptr(-ENOMEM);
12525 	link->link.detach = &bpf_link_perf_detach;
12526 	link->link.dealloc = &bpf_link_perf_dealloc;
12527 	link->perf_event_fd = pfd;
12528 
12529 	force_ioctl_attach = OPTS_GET(opts, force_ioctl_attach, false);
12530 	if (kernel_supports(prog->obj, FEAT_PERF_LINK) && !force_ioctl_attach) {
12531 		DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_opts,
12532 			.perf_event.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0));
12533 
12534 		link_fd = bpf_link_create(prog_fd, pfd, BPF_PERF_EVENT, &link_opts);
12535 		if (link_fd < 0) {
12536 			err = -errno;
12537 			pr_warn("prog '%s': failed to create BPF link for perf_event FD %d: %s\n",
12538 				prog->name, pfd, errstr(err));
12539 			goto err_out;
12540 		}
12541 		link->link.fd = link_fd;
12542 	} else {
12543 		if (OPTS_GET(opts, bpf_cookie, 0)) {
12544 			pr_warn("prog '%s': user context value is not supported\n", prog->name);
12545 			err = -EOPNOTSUPP;
12546 			goto err_out;
12547 		}
12548 
12549 		if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
12550 			err = -errno;
12551 			pr_warn("prog '%s': failed to attach to perf_event FD %d: %s\n",
12552 				prog->name, pfd, errstr(err));
12553 			if (err == -EPROTO)
12554 				pr_warn("prog '%s': try add PERF_SAMPLE_CALLCHAIN to or remove exclude_callchain_[kernel|user] from pfd %d\n",
12555 					prog->name, pfd);
12556 			goto err_out;
12557 		}
12558 		link->link.fd = pfd;
12559 	}
12560 
12561 	if (!OPTS_GET(opts, dont_enable, false)) {
12562 		if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
12563 			err = -errno;
12564 			pr_warn("prog '%s': failed to enable perf_event FD %d: %s\n",
12565 				prog->name, pfd, errstr(err));
12566 			goto err_out;
12567 		}
12568 	}
12569 
12570 	return &link->link;
12571 err_out:
12572 	if (link_fd >= 0)
12573 		close(link_fd);
12574 	free(link);
12575 	return libbpf_err_ptr(err);
12576 }
12577 
12578 struct bpf_link *bpf_program__attach_perf_event(const struct bpf_program *prog, int pfd)
12579 {
12580 	return bpf_program__attach_perf_event_opts(prog, pfd, NULL);
12581 }
12582 
12583 /*
12584  * this function is expected to parse integer in the range of [0, 2^31-1] from
12585  * given file using scanf format string fmt. If actual parsed value is
12586  * negative, the result might be indistinguishable from error
12587  */
12588 static int parse_uint_from_file(const char *file, const char *fmt)
12589 {
12590 	int err, ret;
12591 	FILE *f;
12592 
12593 	f = fopen(file, "re");
12594 	if (!f) {
12595 		err = -errno;
12596 		pr_debug("failed to open '%s': %s\n", file, errstr(err));
12597 		return err;
12598 	}
12599 	err = fscanf(f, fmt, &ret);
12600 	if (err != 1) {
12601 		err = err == EOF ? -EIO : -errno;
12602 		pr_debug("failed to parse '%s': %s\n", file, errstr(err));
12603 		fclose(f);
12604 		return err;
12605 	}
12606 	fclose(f);
12607 	return ret;
12608 }
12609 
12610 static int determine_kprobe_perf_type(void)
12611 {
12612 	const char *file = "/sys/bus/event_source/devices/kprobe/type";
12613 
12614 	return parse_uint_from_file(file, "%d\n");
12615 }
12616 
12617 static int determine_uprobe_perf_type(void)
12618 {
12619 	const char *file = "/sys/bus/event_source/devices/uprobe/type";
12620 
12621 	return parse_uint_from_file(file, "%d\n");
12622 }
12623 
12624 static int determine_kprobe_retprobe_bit(void)
12625 {
12626 	const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
12627 
12628 	return parse_uint_from_file(file, "config:%d\n");
12629 }
12630 
12631 static int determine_uprobe_retprobe_bit(void)
12632 {
12633 	const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
12634 
12635 	return parse_uint_from_file(file, "config:%d\n");
12636 }
12637 
12638 #define PERF_UPROBE_REF_CTR_OFFSET_BITS 32
12639 #define PERF_UPROBE_REF_CTR_OFFSET_SHIFT 32
12640 
12641 static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
12642 				 uint64_t offset, int pid, size_t ref_ctr_off)
12643 {
12644 	const size_t attr_sz = sizeof(struct perf_event_attr);
12645 	struct perf_event_attr attr;
12646 	int type, pfd;
12647 
12648 	if ((__u64)ref_ctr_off >= (1ULL << PERF_UPROBE_REF_CTR_OFFSET_BITS))
12649 		return -EINVAL;
12650 
12651 	memset(&attr, 0, attr_sz);
12652 
12653 	type = uprobe ? determine_uprobe_perf_type()
12654 		      : determine_kprobe_perf_type();
12655 	if (type < 0) {
12656 		pr_warn("failed to determine %s perf type: %s\n",
12657 			uprobe ? "uprobe" : "kprobe",
12658 			errstr(type));
12659 		return type;
12660 	}
12661 	if (retprobe) {
12662 		int bit = uprobe ? determine_uprobe_retprobe_bit()
12663 				 : determine_kprobe_retprobe_bit();
12664 
12665 		if (bit < 0) {
12666 			pr_warn("failed to determine %s retprobe bit: %s\n",
12667 				uprobe ? "uprobe" : "kprobe",
12668 				errstr(bit));
12669 			return bit;
12670 		}
12671 		attr.config |= 1ULL << bit;
12672 	}
12673 	attr.size = attr_sz;
12674 	attr.type = type;
12675 	attr.config |= (__u64)ref_ctr_off << PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
12676 	attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
12677 	attr.config2 = offset;		 /* kprobe_addr or probe_offset */
12678 
12679 	/* pid filter is meaningful only for uprobes */
12680 	pfd = syscall(__NR_perf_event_open, &attr,
12681 		      pid < 0 ? -1 : pid /* pid */,
12682 		      pid == -1 ? 0 : -1 /* cpu */,
12683 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
12684 	return pfd >= 0 ? pfd : -errno;
12685 }
12686 
12687 static int append_to_file(const char *file, const char *fmt, ...)
12688 {
12689 	int fd, n, err = 0;
12690 	va_list ap;
12691 	char buf[1024];
12692 
12693 	va_start(ap, fmt);
12694 	n = vsnprintf(buf, sizeof(buf), fmt, ap);
12695 	va_end(ap);
12696 
12697 	if (n < 0 || n >= sizeof(buf))
12698 		return -EINVAL;
12699 
12700 	fd = open(file, O_WRONLY | O_APPEND | O_CLOEXEC, 0);
12701 	if (fd < 0)
12702 		return -errno;
12703 
12704 	if (write(fd, buf, n) < 0)
12705 		err = -errno;
12706 
12707 	close(fd);
12708 	return err;
12709 }
12710 
12711 #define DEBUGFS "/sys/kernel/debug/tracing"
12712 #define TRACEFS "/sys/kernel/tracing"
12713 
12714 static bool use_debugfs(void)
12715 {
12716 	static int has_debugfs = -1;
12717 
12718 	if (has_debugfs < 0)
12719 		has_debugfs = faccessat(AT_FDCWD, DEBUGFS, F_OK, AT_EACCESS) == 0;
12720 
12721 	return has_debugfs == 1;
12722 }
12723 
12724 static const char *tracefs_path(void)
12725 {
12726 	return use_debugfs() ? DEBUGFS : TRACEFS;
12727 }
12728 
12729 static const char *tracefs_kprobe_events(void)
12730 {
12731 	return use_debugfs() ? DEBUGFS"/kprobe_events" : TRACEFS"/kprobe_events";
12732 }
12733 
12734 static const char *tracefs_uprobe_events(void)
12735 {
12736 	return use_debugfs() ? DEBUGFS"/uprobe_events" : TRACEFS"/uprobe_events";
12737 }
12738 
12739 static const char *tracefs_available_filter_functions(void)
12740 {
12741 	return use_debugfs() ? DEBUGFS"/available_filter_functions"
12742 			     : TRACEFS"/available_filter_functions";
12743 }
12744 
12745 static const char *tracefs_available_filter_functions_addrs(void)
12746 {
12747 	return use_debugfs() ? DEBUGFS"/available_filter_functions_addrs"
12748 			     : TRACEFS"/available_filter_functions_addrs";
12749 }
12750 
12751 static void gen_probe_legacy_event_name(char *buf, size_t buf_sz,
12752 					const char *name, size_t offset)
12753 {
12754 	static int index = 0;
12755 	int i;
12756 
12757 	snprintf(buf, buf_sz, "libbpf_%d_%d_%s_0x%zx", getpid(),
12758 		 __sync_fetch_and_add(&index, 1), name, offset);
12759 
12760 	/* sanitize name in the probe name */
12761 	for (i = 0; buf[i]; i++) {
12762 		if (!isalnum(buf[i]))
12763 			buf[i] = '_';
12764 	}
12765 }
12766 
12767 static int add_kprobe_event_legacy(const char *probe_name, bool retprobe,
12768 				   const char *kfunc_name, size_t offset)
12769 {
12770 	return append_to_file(tracefs_kprobe_events(), "%c:%s/%s %s+0x%zx",
12771 			      retprobe ? 'r' : 'p',
12772 			      retprobe ? "kretprobes" : "kprobes",
12773 			      probe_name, kfunc_name, offset);
12774 }
12775 
12776 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe)
12777 {
12778 	return append_to_file(tracefs_kprobe_events(), "-:%s/%s",
12779 			      retprobe ? "kretprobes" : "kprobes", probe_name);
12780 }
12781 
12782 static int determine_kprobe_perf_type_legacy(const char *probe_name, bool retprobe)
12783 {
12784 	char file[256];
12785 
12786 	snprintf(file, sizeof(file), "%s/events/%s/%s/id",
12787 		 tracefs_path(), retprobe ? "kretprobes" : "kprobes", probe_name);
12788 
12789 	return parse_uint_from_file(file, "%d\n");
12790 }
12791 
12792 static int perf_event_kprobe_open_legacy(const char *probe_name, bool retprobe,
12793 					 const char *kfunc_name, size_t offset, int pid)
12794 {
12795 	const size_t attr_sz = sizeof(struct perf_event_attr);
12796 	struct perf_event_attr attr;
12797 	int type, pfd, err;
12798 
12799 	err = add_kprobe_event_legacy(probe_name, retprobe, kfunc_name, offset);
12800 	if (err < 0) {
12801 		pr_warn("failed to add legacy kprobe event for '%s+0x%zx': %s\n",
12802 			kfunc_name, offset,
12803 			errstr(err));
12804 		return err;
12805 	}
12806 	type = determine_kprobe_perf_type_legacy(probe_name, retprobe);
12807 	if (type < 0) {
12808 		err = type;
12809 		pr_warn("failed to determine legacy kprobe event id for '%s+0x%zx': %s\n",
12810 			kfunc_name, offset,
12811 			errstr(err));
12812 		goto err_clean_legacy;
12813 	}
12814 
12815 	memset(&attr, 0, attr_sz);
12816 	attr.size = attr_sz;
12817 	attr.config = type;
12818 	attr.type = PERF_TYPE_TRACEPOINT;
12819 
12820 	pfd = syscall(__NR_perf_event_open, &attr,
12821 		      pid < 0 ? -1 : pid, /* pid */
12822 		      pid == -1 ? 0 : -1, /* cpu */
12823 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
12824 	if (pfd < 0) {
12825 		err = -errno;
12826 		pr_warn("legacy kprobe perf_event_open() failed: %s\n",
12827 			errstr(err));
12828 		goto err_clean_legacy;
12829 	}
12830 	return pfd;
12831 
12832 err_clean_legacy:
12833 	/* Clear the newly added legacy kprobe_event */
12834 	remove_kprobe_event_legacy(probe_name, retprobe);
12835 	return err;
12836 }
12837 
12838 static const char *arch_specific_syscall_pfx(void)
12839 {
12840 #if defined(__x86_64__)
12841 	return "x64";
12842 #elif defined(__i386__)
12843 	return "ia32";
12844 #elif defined(__s390x__)
12845 	return "s390x";
12846 #elif defined(__arm__)
12847 	return "arm";
12848 #elif defined(__aarch64__)
12849 	return "arm64";
12850 #elif defined(__mips__)
12851 	return "mips";
12852 #elif defined(__riscv)
12853 	return "riscv";
12854 #elif defined(__powerpc__)
12855 	return "powerpc";
12856 #elif defined(__powerpc64__)
12857 	return "powerpc64";
12858 #else
12859 	return NULL;
12860 #endif
12861 }
12862 
12863 int probe_kern_syscall_wrapper(int token_fd)
12864 {
12865 	char syscall_name[64];
12866 	const char *ksys_pfx;
12867 
12868 	ksys_pfx = arch_specific_syscall_pfx();
12869 	if (!ksys_pfx)
12870 		return 0;
12871 
12872 	snprintf(syscall_name, sizeof(syscall_name), "__%s_sys_bpf", ksys_pfx);
12873 
12874 	if (determine_kprobe_perf_type() >= 0) {
12875 		int pfd;
12876 
12877 		pfd = perf_event_open_probe(false, false, syscall_name, 0, getpid(), 0);
12878 		if (pfd >= 0)
12879 			close(pfd);
12880 
12881 		return pfd >= 0 ? 1 : 0;
12882 	} else { /* legacy mode */
12883 		char probe_name[MAX_EVENT_NAME_LEN];
12884 
12885 		gen_probe_legacy_event_name(probe_name, sizeof(probe_name), syscall_name, 0);
12886 		if (add_kprobe_event_legacy(probe_name, false, syscall_name, 0) < 0)
12887 			return 0;
12888 
12889 		(void)remove_kprobe_event_legacy(probe_name, false);
12890 		return 1;
12891 	}
12892 }
12893 
12894 struct bpf_link *
12895 bpf_program__attach_kprobe_opts(const struct bpf_program *prog,
12896 				const char *func_name,
12897 				const struct bpf_kprobe_opts *opts)
12898 {
12899 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
12900 	enum probe_attach_mode attach_mode;
12901 	char *legacy_probe = NULL;
12902 	struct bpf_link *link;
12903 	size_t offset;
12904 	bool retprobe, legacy;
12905 	int pfd, err;
12906 
12907 	if (!OPTS_VALID(opts, bpf_kprobe_opts))
12908 		return libbpf_err_ptr(-EINVAL);
12909 
12910 	attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
12911 	retprobe = OPTS_GET(opts, retprobe, false);
12912 	offset = OPTS_GET(opts, offset, 0);
12913 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
12914 
12915 	legacy = determine_kprobe_perf_type() < 0;
12916 	switch (attach_mode) {
12917 	case PROBE_ATTACH_MODE_LEGACY:
12918 		legacy = true;
12919 		pe_opts.force_ioctl_attach = true;
12920 		break;
12921 	case PROBE_ATTACH_MODE_PERF:
12922 		if (legacy)
12923 			return libbpf_err_ptr(-ENOTSUP);
12924 		pe_opts.force_ioctl_attach = true;
12925 		break;
12926 	case PROBE_ATTACH_MODE_LINK:
12927 		if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
12928 			return libbpf_err_ptr(-ENOTSUP);
12929 		break;
12930 	case PROBE_ATTACH_MODE_DEFAULT:
12931 		break;
12932 	default:
12933 		return libbpf_err_ptr(-EINVAL);
12934 	}
12935 	if (!func_name && legacy)
12936 		return libbpf_err_ptr(-EOPNOTSUPP);
12937 
12938 	if (!legacy) {
12939 		pfd = perf_event_open_probe(false /* uprobe */, retprobe,
12940 					    func_name, offset,
12941 					    -1 /* pid */, 0 /* ref_ctr_off */);
12942 	} else {
12943 		char probe_name[MAX_EVENT_NAME_LEN];
12944 
12945 		gen_probe_legacy_event_name(probe_name, sizeof(probe_name),
12946 					    func_name, offset);
12947 
12948 		legacy_probe = strdup(probe_name);
12949 		if (!legacy_probe)
12950 			return libbpf_err_ptr(-ENOMEM);
12951 
12952 		pfd = perf_event_kprobe_open_legacy(legacy_probe, retprobe, func_name,
12953 						    offset, -1 /* pid */);
12954 	}
12955 	if (pfd < 0) {
12956 		err = pfd;
12957 		pr_warn("prog '%s': failed to create %s '%s%s0x%zx' perf event: %s\n",
12958 			prog->name, retprobe ? "kretprobe" : "kprobe",
12959 			func_name ?: "", func_name ? "+" : "",
12960 			offset, errstr(err));
12961 		goto err_out;
12962 	}
12963 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
12964 	err = libbpf_get_error(link);
12965 	if (err) {
12966 		close(pfd);
12967 		pr_warn("prog '%s': failed to attach to %s '%s%s0x%zx': %s\n",
12968 			prog->name, retprobe ? "kretprobe" : "kprobe",
12969 			func_name ?: "", func_name ? "+" : "",
12970 			offset, errstr(err));
12971 		goto err_clean_legacy;
12972 	}
12973 	if (legacy) {
12974 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
12975 
12976 		perf_link->legacy_probe_name = legacy_probe;
12977 		perf_link->legacy_is_kprobe = true;
12978 		perf_link->legacy_is_retprobe = retprobe;
12979 	}
12980 
12981 	return link;
12982 
12983 err_clean_legacy:
12984 	if (legacy)
12985 		remove_kprobe_event_legacy(legacy_probe, retprobe);
12986 err_out:
12987 	free(legacy_probe);
12988 	return libbpf_err_ptr(err);
12989 }
12990 
12991 struct bpf_link *bpf_program__attach_kprobe(const struct bpf_program *prog,
12992 					    bool retprobe,
12993 					    const char *func_name)
12994 {
12995 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts,
12996 		.retprobe = retprobe,
12997 	);
12998 
12999 	return bpf_program__attach_kprobe_opts(prog, func_name, &opts);
13000 }
13001 
13002 struct bpf_link *bpf_program__attach_ksyscall(const struct bpf_program *prog,
13003 					      const char *syscall_name,
13004 					      const struct bpf_ksyscall_opts *opts)
13005 {
13006 	LIBBPF_OPTS(bpf_kprobe_opts, kprobe_opts);
13007 	char func_name[128];
13008 
13009 	if (!OPTS_VALID(opts, bpf_ksyscall_opts))
13010 		return libbpf_err_ptr(-EINVAL);
13011 
13012 	if (kernel_supports(prog->obj, FEAT_SYSCALL_WRAPPER)) {
13013 		/* arch_specific_syscall_pfx() should never return NULL here
13014 		 * because it is guarded by kernel_supports(). However, since
13015 		 * compiler does not know that we have an explicit conditional
13016 		 * as well.
13017 		 */
13018 		snprintf(func_name, sizeof(func_name), "__%s_sys_%s",
13019 			 arch_specific_syscall_pfx() ? : "", syscall_name);
13020 	} else {
13021 		snprintf(func_name, sizeof(func_name), "__se_sys_%s", syscall_name);
13022 	}
13023 
13024 	kprobe_opts.retprobe = OPTS_GET(opts, retprobe, false);
13025 	kprobe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
13026 
13027 	return bpf_program__attach_kprobe_opts(prog, func_name, &kprobe_opts);
13028 }
13029 
13030 /* Adapted from perf/util/string.c */
13031 bool glob_match(const char *str, const char *pat)
13032 {
13033 	while (*str && *pat && *pat != '*') {
13034 		if (*pat == '?') {      /* Matches any single character */
13035 			str++;
13036 			pat++;
13037 			continue;
13038 		}
13039 		if (*str != *pat)
13040 			return false;
13041 		str++;
13042 		pat++;
13043 	}
13044 	/* Check wild card */
13045 	if (*pat == '*') {
13046 		while (*pat == '*')
13047 			pat++;
13048 		if (!*pat) /* Tail wild card matches all */
13049 			return true;
13050 		while (*str)
13051 			if (glob_match(str++, pat))
13052 				return true;
13053 	}
13054 	return !*str && !*pat;
13055 }
13056 
13057 struct kprobe_multi_resolve {
13058 	const char *pattern;
13059 	unsigned long *addrs;
13060 	size_t cap;
13061 	size_t cnt;
13062 };
13063 
13064 struct avail_kallsyms_data {
13065 	char **syms;
13066 	size_t cnt;
13067 	struct kprobe_multi_resolve *res;
13068 };
13069 
13070 static int avail_func_cmp(const void *a, const void *b)
13071 {
13072 	return strcmp(*(const char **)a, *(const char **)b);
13073 }
13074 
13075 static int avail_kallsyms_cb(unsigned long long sym_addr, char sym_type,
13076 			     const char *sym_name, void *ctx)
13077 {
13078 	struct avail_kallsyms_data *data = ctx;
13079 	struct kprobe_multi_resolve *res = data->res;
13080 	int err;
13081 
13082 	if (!glob_match(sym_name, res->pattern))
13083 		return 0;
13084 
13085 	if (!bsearch(&sym_name, data->syms, data->cnt, sizeof(*data->syms), avail_func_cmp)) {
13086 		/* Some versions of kernel strip out .llvm.<hash> suffix from
13087 		 * function names reported in available_filter_functions, but
13088 		 * don't do so for kallsyms. While this is clearly a kernel
13089 		 * bug (fixed by [0]) we try to accommodate that in libbpf to
13090 		 * make multi-kprobe usability a bit better: if no match is
13091 		 * found, we will strip .llvm. suffix and try one more time.
13092 		 *
13093 		 *   [0] fb6a421fb615 ("kallsyms: Match symbols exactly with CONFIG_LTO_CLANG")
13094 		 */
13095 		char sym_trim[256], *psym_trim = sym_trim;
13096 		const char *sym_sfx;
13097 
13098 		if (!(sym_sfx = strstr(sym_name, ".llvm.")))
13099 			return 0;
13100 
13101 		/* psym_trim vs sym_trim dance is done to avoid pointer vs array
13102 		 * coercion differences and get proper `const char **` pointer
13103 		 * which avail_func_cmp() expects
13104 		 */
13105 		snprintf(sym_trim, sizeof(sym_trim), "%.*s", (int)(sym_sfx - sym_name), sym_name);
13106 		if (!bsearch(&psym_trim, data->syms, data->cnt, sizeof(*data->syms), avail_func_cmp))
13107 			return 0;
13108 	}
13109 
13110 	err = libbpf_ensure_mem((void **)&res->addrs, &res->cap, sizeof(*res->addrs), res->cnt + 1);
13111 	if (err)
13112 		return err;
13113 
13114 	res->addrs[res->cnt++] = (unsigned long)sym_addr;
13115 	return 0;
13116 }
13117 
13118 static int libbpf_available_kallsyms_parse(struct kprobe_multi_resolve *res)
13119 {
13120 	const char *available_functions_file = tracefs_available_filter_functions();
13121 	struct avail_kallsyms_data data;
13122 	char sym_name[500];
13123 	FILE *f;
13124 	int err = 0, ret, i;
13125 	char **syms = NULL;
13126 	size_t cap = 0, cnt = 0;
13127 
13128 	f = fopen(available_functions_file, "re");
13129 	if (!f) {
13130 		err = -errno;
13131 		pr_warn("failed to open %s: %s\n", available_functions_file, errstr(err));
13132 		return err;
13133 	}
13134 
13135 	while (true) {
13136 		char *name;
13137 
13138 		ret = fscanf(f, "%499s%*[^\n]\n", sym_name);
13139 		if (ret == EOF && feof(f))
13140 			break;
13141 
13142 		if (ret != 1) {
13143 			pr_warn("failed to parse available_filter_functions entry: %d\n", ret);
13144 			err = -EINVAL;
13145 			goto cleanup;
13146 		}
13147 
13148 		if (!glob_match(sym_name, res->pattern))
13149 			continue;
13150 
13151 		err = libbpf_ensure_mem((void **)&syms, &cap, sizeof(*syms), cnt + 1);
13152 		if (err)
13153 			goto cleanup;
13154 
13155 		name = strdup(sym_name);
13156 		if (!name) {
13157 			err = -errno;
13158 			goto cleanup;
13159 		}
13160 
13161 		syms[cnt++] = name;
13162 	}
13163 
13164 	/* no entries found, bail out */
13165 	if (cnt == 0) {
13166 		err = -ENOENT;
13167 		goto cleanup;
13168 	}
13169 
13170 	/* sort available functions */
13171 	qsort(syms, cnt, sizeof(*syms), avail_func_cmp);
13172 
13173 	data.syms = syms;
13174 	data.res = res;
13175 	data.cnt = cnt;
13176 	libbpf_kallsyms_parse(avail_kallsyms_cb, &data);
13177 
13178 	if (res->cnt == 0)
13179 		err = -ENOENT;
13180 
13181 cleanup:
13182 	for (i = 0; i < cnt; i++)
13183 		free((char *)syms[i]);
13184 	free(syms);
13185 
13186 	fclose(f);
13187 	return err;
13188 }
13189 
13190 static bool has_available_filter_functions_addrs(void)
13191 {
13192 	return access(tracefs_available_filter_functions_addrs(), R_OK) != -1;
13193 }
13194 
13195 static int libbpf_available_kprobes_parse(struct kprobe_multi_resolve *res)
13196 {
13197 	const char *available_path = tracefs_available_filter_functions_addrs();
13198 	char sym_name[500];
13199 	FILE *f;
13200 	int ret, err = 0;
13201 	unsigned long long sym_addr;
13202 
13203 	f = fopen(available_path, "re");
13204 	if (!f) {
13205 		err = -errno;
13206 		pr_warn("failed to open %s: %s\n", available_path, errstr(err));
13207 		return err;
13208 	}
13209 
13210 	while (true) {
13211 		ret = fscanf(f, "%llx %499s%*[^\n]\n", &sym_addr, sym_name);
13212 		if (ret == EOF && feof(f))
13213 			break;
13214 
13215 		if (ret != 2) {
13216 			pr_warn("failed to parse available_filter_functions_addrs entry: %d\n",
13217 				ret);
13218 			err = -EINVAL;
13219 			goto cleanup;
13220 		}
13221 
13222 		if (!glob_match(sym_name, res->pattern))
13223 			continue;
13224 
13225 		err = libbpf_ensure_mem((void **)&res->addrs, &res->cap,
13226 					sizeof(*res->addrs), res->cnt + 1);
13227 		if (err)
13228 			goto cleanup;
13229 
13230 		res->addrs[res->cnt++] = (unsigned long)sym_addr;
13231 	}
13232 
13233 	if (res->cnt == 0)
13234 		err = -ENOENT;
13235 
13236 cleanup:
13237 	fclose(f);
13238 	return err;
13239 }
13240 
13241 struct bpf_link *
13242 bpf_program__attach_kprobe_multi_opts(const struct bpf_program *prog,
13243 				      const char *pattern,
13244 				      const struct bpf_kprobe_multi_opts *opts)
13245 {
13246 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
13247 	struct kprobe_multi_resolve res = {
13248 		.pattern = pattern,
13249 	};
13250 	enum bpf_attach_type attach_type;
13251 	struct bpf_link *link = NULL;
13252 	const unsigned long *addrs;
13253 	int err, link_fd, prog_fd;
13254 	bool retprobe, session, unique_match;
13255 	const __u64 *cookies;
13256 	const char **syms;
13257 	size_t cnt;
13258 
13259 	if (!OPTS_VALID(opts, bpf_kprobe_multi_opts))
13260 		return libbpf_err_ptr(-EINVAL);
13261 
13262 	prog_fd = bpf_program__fd(prog);
13263 	if (prog_fd < 0) {
13264 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
13265 			prog->name);
13266 		return libbpf_err_ptr(-EINVAL);
13267 	}
13268 
13269 	syms    = OPTS_GET(opts, syms, false);
13270 	addrs   = OPTS_GET(opts, addrs, false);
13271 	cnt     = OPTS_GET(opts, cnt, false);
13272 	cookies = OPTS_GET(opts, cookies, false);
13273 	unique_match = OPTS_GET(opts, unique_match, false);
13274 
13275 	if (!pattern && !addrs && !syms)
13276 		return libbpf_err_ptr(-EINVAL);
13277 	if (pattern && (addrs || syms || cookies || cnt))
13278 		return libbpf_err_ptr(-EINVAL);
13279 	if (!pattern && !cnt)
13280 		return libbpf_err_ptr(-EINVAL);
13281 	if (!pattern && unique_match)
13282 		return libbpf_err_ptr(-EINVAL);
13283 	if (addrs && syms)
13284 		return libbpf_err_ptr(-EINVAL);
13285 
13286 	/*
13287 	 * Exact function name (no wildcards) without unique_match:
13288 	 * bypass kallsyms parsing and pass the symbol directly to the
13289 	 * kernel via syms[] array.  When unique_match is set, fall
13290 	 * through to the slow path which detects duplicate symbols.
13291 	 */
13292 	if (pattern && !strpbrk(pattern, "*?") && !unique_match) {
13293 		syms = &pattern;
13294 		cnt = 1;
13295 	} else if (pattern) {
13296 		if (has_available_filter_functions_addrs())
13297 			err = libbpf_available_kprobes_parse(&res);
13298 		else
13299 			err = libbpf_available_kallsyms_parse(&res);
13300 		if (err)
13301 			goto error;
13302 
13303 		if (unique_match && res.cnt != 1) {
13304 			pr_warn("prog '%s': failed to find a unique match for '%s' (%zu matches)\n",
13305 				prog->name, pattern, res.cnt);
13306 			err = -EINVAL;
13307 			goto error;
13308 		}
13309 
13310 		addrs = res.addrs;
13311 		cnt = res.cnt;
13312 	}
13313 
13314 	retprobe = OPTS_GET(opts, retprobe, false);
13315 	session  = OPTS_GET(opts, session, false);
13316 
13317 	if (retprobe && session)
13318 		return libbpf_err_ptr(-EINVAL);
13319 
13320 	attach_type = session ? BPF_TRACE_KPROBE_SESSION : BPF_TRACE_KPROBE_MULTI;
13321 
13322 	lopts.kprobe_multi.syms = syms;
13323 	lopts.kprobe_multi.addrs = addrs;
13324 	lopts.kprobe_multi.cookies = cookies;
13325 	lopts.kprobe_multi.cnt = cnt;
13326 	lopts.kprobe_multi.flags = retprobe ? BPF_F_KPROBE_MULTI_RETURN : 0;
13327 
13328 	link = calloc(1, sizeof(*link));
13329 	if (!link) {
13330 		err = -ENOMEM;
13331 		goto error;
13332 	}
13333 	link->detach = &bpf_link__detach_fd;
13334 
13335 	link_fd = bpf_link_create(prog_fd, 0, attach_type, &lopts);
13336 	if (link_fd < 0) {
13337 		err = -errno;
13338 		/*
13339 		 * Normalize error code: when exact name bypasses kallsyms
13340 		 * parsing, kernel returns ESRCH from ftrace_lookup_symbols().
13341 		 * Convert to ENOENT for API consistency with the pattern
13342 		 * matching path which returns ENOENT from userspace.
13343 		 */
13344 		if (err == -ESRCH)
13345 			err = -ENOENT;
13346 		pr_warn("prog '%s': failed to attach: %s\n",
13347 			prog->name, errstr(err));
13348 		goto error;
13349 	}
13350 	link->fd = link_fd;
13351 	free(res.addrs);
13352 	return link;
13353 
13354 error:
13355 	free(link);
13356 	free(res.addrs);
13357 	return libbpf_err_ptr(err);
13358 }
13359 
13360 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
13361 {
13362 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts);
13363 	long offset = 0;
13364 	const char *func_name;
13365 	char *func;
13366 	int n;
13367 
13368 	*link = NULL;
13369 
13370 	/* no auto-attach for SEC("kprobe") and SEC("kretprobe") */
13371 	if (strcmp(prog->sec_name, "kprobe") == 0 || strcmp(prog->sec_name, "kretprobe") == 0)
13372 		return 0;
13373 
13374 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe/");
13375 	if (opts.retprobe)
13376 		func_name = prog->sec_name + sizeof("kretprobe/") - 1;
13377 	else
13378 		func_name = prog->sec_name + sizeof("kprobe/") - 1;
13379 
13380 	n = sscanf(func_name, "%m[a-zA-Z0-9_.]+%li", &func, &offset);
13381 	if (n < 1) {
13382 		pr_warn("kprobe name is invalid: %s\n", func_name);
13383 		return -EINVAL;
13384 	}
13385 
13386 	if (offset < 0) {
13387 		free(func);
13388 		pr_warn("kprobe offset must be a non-negative integer: %li\n", offset);
13389 		return -EINVAL;
13390 	}
13391 
13392 	if (opts.retprobe && offset != 0) {
13393 		free(func);
13394 		pr_warn("kretprobes do not support offset specification\n");
13395 		return -EINVAL;
13396 	}
13397 
13398 	opts.offset = offset;
13399 	*link = bpf_program__attach_kprobe_opts(prog, func, &opts);
13400 	free(func);
13401 	return libbpf_get_error(*link);
13402 }
13403 
13404 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link)
13405 {
13406 	LIBBPF_OPTS(bpf_ksyscall_opts, opts);
13407 	const char *syscall_name;
13408 
13409 	*link = NULL;
13410 
13411 	/* no auto-attach for SEC("ksyscall") and SEC("kretsyscall") */
13412 	if (strcmp(prog->sec_name, "ksyscall") == 0 || strcmp(prog->sec_name, "kretsyscall") == 0)
13413 		return 0;
13414 
13415 	opts.retprobe = str_has_pfx(prog->sec_name, "kretsyscall/");
13416 	if (opts.retprobe)
13417 		syscall_name = prog->sec_name + sizeof("kretsyscall/") - 1;
13418 	else
13419 		syscall_name = prog->sec_name + sizeof("ksyscall/") - 1;
13420 
13421 	*link = bpf_program__attach_ksyscall(prog, syscall_name, &opts);
13422 	return *link ? 0 : -errno;
13423 }
13424 
13425 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
13426 {
13427 	LIBBPF_OPTS(bpf_kprobe_multi_opts, opts);
13428 	const char *spec;
13429 	char *pattern;
13430 	int n;
13431 
13432 	*link = NULL;
13433 
13434 	/* no auto-attach for SEC("kprobe.multi") and SEC("kretprobe.multi") */
13435 	if (strcmp(prog->sec_name, "kprobe.multi") == 0 ||
13436 	    strcmp(prog->sec_name, "kretprobe.multi") == 0)
13437 		return 0;
13438 
13439 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe.multi/");
13440 	if (opts.retprobe)
13441 		spec = prog->sec_name + sizeof("kretprobe.multi/") - 1;
13442 	else
13443 		spec = prog->sec_name + sizeof("kprobe.multi/") - 1;
13444 
13445 	n = sscanf(spec, "%m[a-zA-Z0-9_.*?]", &pattern);
13446 	if (n < 1) {
13447 		pr_warn("kprobe multi pattern is invalid: %s\n", spec);
13448 		return -EINVAL;
13449 	}
13450 
13451 	*link = bpf_program__attach_kprobe_multi_opts(prog, pattern, &opts);
13452 	free(pattern);
13453 	return libbpf_get_error(*link);
13454 }
13455 
13456 static int attach_kprobe_session(const struct bpf_program *prog, long cookie,
13457 				 struct bpf_link **link)
13458 {
13459 	LIBBPF_OPTS(bpf_kprobe_multi_opts, opts, .session = true);
13460 	const char *spec;
13461 	char *pattern;
13462 	int n;
13463 
13464 	*link = NULL;
13465 
13466 	/* no auto-attach for SEC("kprobe.session") */
13467 	if (strcmp(prog->sec_name, "kprobe.session") == 0)
13468 		return 0;
13469 
13470 	spec = prog->sec_name + sizeof("kprobe.session/") - 1;
13471 	n = sscanf(spec, "%m[a-zA-Z0-9_.*?]", &pattern);
13472 	if (n < 1) {
13473 		pr_warn("kprobe session pattern is invalid: %s\n", spec);
13474 		return -EINVAL;
13475 	}
13476 
13477 	*link = bpf_program__attach_kprobe_multi_opts(prog, pattern, &opts);
13478 	free(pattern);
13479 	return *link ? 0 : -errno;
13480 }
13481 
13482 static int attach_uprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
13483 {
13484 	char *probe_type = NULL, *binary_path = NULL, *func_name = NULL;
13485 	LIBBPF_OPTS(bpf_uprobe_multi_opts, opts);
13486 	int n, ret = -EINVAL;
13487 
13488 	*link = NULL;
13489 
13490 	n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[^\n]",
13491 		   &probe_type, &binary_path, &func_name);
13492 	switch (n) {
13493 	case 1:
13494 		/* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
13495 		ret = 0;
13496 		break;
13497 	case 3:
13498 		opts.session = str_has_pfx(probe_type, "uprobe.session");
13499 		opts.retprobe = str_has_pfx(probe_type, "uretprobe.multi");
13500 
13501 		*link = bpf_program__attach_uprobe_multi(prog, -1, binary_path, func_name, &opts);
13502 		ret = libbpf_get_error(*link);
13503 		break;
13504 	default:
13505 		pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
13506 			prog->sec_name);
13507 		break;
13508 	}
13509 	free(probe_type);
13510 	free(binary_path);
13511 	free(func_name);
13512 	return ret;
13513 }
13514 
13515 #define MAX_BPF_FUNC_ARGS 12
13516 
13517 static bool btf_type_is_modifier(const struct btf_type *t)
13518 {
13519 	switch (BTF_INFO_KIND(t->info)) {
13520 	case BTF_KIND_TYPEDEF:
13521 	case BTF_KIND_VOLATILE:
13522 	case BTF_KIND_CONST:
13523 	case BTF_KIND_RESTRICT:
13524 	case BTF_KIND_TYPE_TAG:
13525 		return true;
13526 	default:
13527 		return false;
13528 	}
13529 }
13530 
13531 #define MAX_RESOLVE_DEPTH 32
13532 
13533 static int btf_get_type_size(const struct btf *btf, __u32 type_id,
13534 			     const struct btf_type **ret_type)
13535 {
13536 	const struct btf_type *t;
13537 	int i;
13538 
13539 	*ret_type = btf__type_by_id(btf, 0);
13540 	if (!type_id)
13541 		return 0;
13542 	t = btf__type_by_id(btf, type_id);
13543 	for (i = 0; i < MAX_RESOLVE_DEPTH && t && btf_type_is_modifier(t); i++)
13544 		t = btf__type_by_id(btf, t->type);
13545 	if (!t || i == MAX_RESOLVE_DEPTH)
13546 		return -EINVAL;
13547 	*ret_type = t;
13548 	if (btf_is_ptr(t))
13549 		return btf__pointer_size(btf);
13550 	if (btf_is_int(t) || btf_is_any_enum(t) || btf_is_struct(t) || btf_is_union(t))
13551 		return t->size;
13552 	return -EINVAL;
13553 }
13554 
13555 bool btf_type_is_traceable_func(const struct btf *btf, const struct btf_type *t)
13556 {
13557 	const struct btf_param *args;
13558 	const struct btf_type *proto;
13559 	__u32 i, nargs;
13560 	int ret;
13561 
13562 	if (!btf_is_func(t))
13563 		return false;
13564 	proto = btf__type_by_id(btf, t->type);
13565 	if (!proto || !btf_is_func_proto(proto))
13566 		return false;
13567 
13568 	args = (const struct btf_param *)(proto + 1);
13569 	nargs = btf_vlen(proto);
13570 	if (nargs > MAX_BPF_FUNC_ARGS)
13571 		return false;
13572 
13573 	/* No support for struct return type. */
13574 	ret = btf_get_type_size(btf, proto->type, &t);
13575 	if (ret < 0 || btf_is_struct(t) || btf_is_union(t))
13576 		return false;
13577 
13578 	for (i = 0; i < nargs; i++) {
13579 		/* No support for variable args. */
13580 		if (i == nargs - 1 && args[i].type == 0)
13581 			return false;
13582 		ret = btf_get_type_size(btf, args[i].type, &t);
13583 		/* No support of struct argument size greater than 16 bytes. */
13584 		if (ret < 0 || ret > 16)
13585 			return false;
13586 		/* No support for void argument. */
13587 		if (ret == 0)
13588 			return false;
13589 	}
13590 
13591 	return true;
13592 }
13593 
13594 static int
13595 collect_btf_func_ids_by_glob(const struct btf *btf, const char *pattern, __u32 **ids)
13596 {
13597 	__u32 type_id, nr_types = btf__type_cnt(btf);
13598 	size_t cap = 0, cnt = 0;
13599 
13600 	if (!pattern)
13601 		return -EINVAL;
13602 
13603 	for (type_id = 1; type_id < nr_types; type_id++) {
13604 		const struct btf_type *t = btf__type_by_id(btf, type_id);
13605 		const char *name;
13606 		int err;
13607 
13608 		if (btf_kind(t) != BTF_KIND_FUNC)
13609 			continue;
13610 		name = btf__name_by_offset(btf, t->name_off);
13611 		if (!name)
13612 			continue;
13613 
13614 		if (!glob_match(name, pattern))
13615 			continue;
13616 		if (!btf_type_is_traceable_func(btf, t))
13617 			continue;
13618 
13619 		err = libbpf_ensure_mem((void **) ids, &cap, sizeof(**ids), cnt + 1);
13620 		if (err) {
13621 			free(*ids);
13622 			return -ENOMEM;
13623 		}
13624 		(*ids)[cnt++] = type_id;
13625 	}
13626 
13627 	return cnt;
13628 }
13629 
13630 static int collect_func_ids_by_glob(const struct bpf_program *prog, const char *pattern, __u32 **ids)
13631 {
13632 	struct bpf_object *obj = prog->obj;
13633 	const struct module_btf *mod;
13634 	struct btf *btf = NULL;
13635 	const char *sep;
13636 	int err;
13637 
13638 	err = bpf_object__load_vmlinux_btf(obj, true);
13639 	if (err)
13640 		return err;
13641 
13642 	/* In case we have module specified, we will find its btf and use that. */
13643 	sep = strchr(pattern, ':');
13644 	if (sep) {
13645 		mod = find_attach_module(obj, pattern);
13646 		if (!mod) {
13647 			err = -EINVAL;
13648 			goto cleanup;
13649 		}
13650 		btf = mod->btf;
13651 		pattern = sep + 1;
13652 	} else {
13653 		/* Program is loaded for kernel module. */
13654 		if (prog->attach_btf_obj_fd) {
13655 			err = -EINVAL;
13656 			goto cleanup;
13657 		}
13658 		btf = obj->btf_vmlinux;
13659 	}
13660 
13661 	err = collect_btf_func_ids_by_glob(btf, pattern, ids);
13662 
13663 cleanup:
13664 	bpf_object_cleanup_btf(obj);
13665 	return err;
13666 }
13667 
13668 struct bpf_link *
13669 bpf_program__attach_tracing_multi(const struct bpf_program *prog, const char *pattern,
13670 				  const struct bpf_tracing_multi_opts *opts)
13671 {
13672 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
13673 	int prog_fd, link_fd, err, cnt;
13674 	__u32 *free_ids = NULL;
13675 	struct bpf_link *link;
13676 	const __u64 *cookies;
13677 	const __u32 *ids;
13678 
13679 	if (!OPTS_VALID(opts, bpf_tracing_multi_opts))
13680 		return libbpf_err_ptr(-EINVAL);
13681 
13682 	prog_fd = bpf_program__fd(prog);
13683 	if (prog_fd < 0) {
13684 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
13685 			prog->name);
13686 		return libbpf_err_ptr(-EINVAL);
13687 	}
13688 
13689 	cnt = OPTS_GET(opts, cnt, 0);
13690 	ids = OPTS_GET(opts, ids, NULL);
13691 	cookies = OPTS_GET(opts, cookies, NULL);
13692 
13693 	if (!!ids != !!cnt)
13694 		return libbpf_err_ptr(-EINVAL);
13695 	if (pattern && (ids || cookies))
13696 		return libbpf_err_ptr(-EINVAL);
13697 	if (!pattern && !ids)
13698 		return libbpf_err_ptr(-EINVAL);
13699 
13700 	if (pattern) {
13701 		cnt = collect_func_ids_by_glob(prog, pattern, &free_ids);
13702 		if (cnt < 0)
13703 			return libbpf_err_ptr(cnt);
13704 		if (cnt == 0)
13705 			return libbpf_err_ptr(-EINVAL);
13706 		ids = (const __u32 *) free_ids;
13707 	}
13708 
13709 	lopts.tracing_multi.ids = ids;
13710 	lopts.tracing_multi.cookies = cookies;
13711 	lopts.tracing_multi.cnt = cnt;
13712 
13713 	link = calloc(1, sizeof(*link));
13714 	if (!link) {
13715 		err = -ENOMEM;
13716 		goto error;
13717 	}
13718 	link->detach = &bpf_link__detach_fd;
13719 
13720 	link_fd = bpf_link_create(prog_fd, 0, prog->expected_attach_type, &lopts);
13721 	if (link_fd < 0) {
13722 		err = -errno;
13723 		pr_warn("prog '%s': failed to attach: %s\n", prog->name, errstr(err));
13724 		goto error;
13725 	}
13726 	link->fd = link_fd;
13727 	free(free_ids);
13728 	return link;
13729 
13730 error:
13731 	free(link);
13732 	free(free_ids);
13733 	return libbpf_err_ptr(err);
13734 }
13735 
13736 static int attach_tracing_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
13737 {
13738 	static const char *const prefixes[] = {
13739 		"fentry.multi",
13740 		"fexit.multi",
13741 		"fsession.multi",
13742 		"fentry.multi.s",
13743 		"fexit.multi.s",
13744 		"fsession.multi.s",
13745 	};
13746 	const char *spec = NULL;
13747 	char *pattern;
13748 	size_t i;
13749 	int n;
13750 
13751 	*link = NULL;
13752 
13753 	for (i = 0; i < ARRAY_SIZE(prefixes); i++) {
13754 		size_t pfx_len;
13755 
13756 		if (!str_has_pfx(prog->sec_name, prefixes[i]))
13757 			continue;
13758 
13759 		pfx_len = strlen(prefixes[i]);
13760 		/* no auto-attach case of, e.g., SEC("fentry.multi") */
13761 		if (prog->sec_name[pfx_len] == '\0')
13762 			return 0;
13763 
13764 		if (prog->sec_name[pfx_len] != '/')
13765 			continue;
13766 
13767 		spec = prog->sec_name + pfx_len + 1;
13768 		break;
13769 	}
13770 
13771 	if (!spec) {
13772 		pr_warn("prog '%s': invalid section name '%s'\n",
13773 			prog->name, prog->sec_name);
13774 		return -EINVAL;
13775 	}
13776 
13777 	n = sscanf(spec, "%m[a-zA-Z0-9_.*?:]", &pattern);
13778 	if (n < 1) {
13779 		pr_warn("tracing multi pattern is invalid: %s\n", spec);
13780 		return -EINVAL;
13781 	}
13782 
13783 	*link = bpf_program__attach_tracing_multi(prog, pattern, NULL);
13784 	free(pattern);
13785 	return libbpf_get_error(*link);
13786 }
13787 
13788 static inline int add_uprobe_event_legacy(const char *probe_name, bool retprobe,
13789 					  const char *binary_path, size_t offset)
13790 {
13791 	return append_to_file(tracefs_uprobe_events(), "%c:%s/%s %s:0x%zx",
13792 			      retprobe ? 'r' : 'p',
13793 			      retprobe ? "uretprobes" : "uprobes",
13794 			      probe_name, binary_path, offset);
13795 }
13796 
13797 static inline int remove_uprobe_event_legacy(const char *probe_name, bool retprobe)
13798 {
13799 	return append_to_file(tracefs_uprobe_events(), "-:%s/%s",
13800 			      retprobe ? "uretprobes" : "uprobes", probe_name);
13801 }
13802 
13803 static int determine_uprobe_perf_type_legacy(const char *probe_name, bool retprobe)
13804 {
13805 	char file[512];
13806 
13807 	snprintf(file, sizeof(file), "%s/events/%s/%s/id",
13808 		 tracefs_path(), retprobe ? "uretprobes" : "uprobes", probe_name);
13809 
13810 	return parse_uint_from_file(file, "%d\n");
13811 }
13812 
13813 static int perf_event_uprobe_open_legacy(const char *probe_name, bool retprobe,
13814 					 const char *binary_path, size_t offset, int pid)
13815 {
13816 	const size_t attr_sz = sizeof(struct perf_event_attr);
13817 	struct perf_event_attr attr;
13818 	int type, pfd, err;
13819 
13820 	err = add_uprobe_event_legacy(probe_name, retprobe, binary_path, offset);
13821 	if (err < 0) {
13822 		pr_warn("failed to add legacy uprobe event for %s:0x%zx: %s\n",
13823 			binary_path, (size_t)offset, errstr(err));
13824 		return err;
13825 	}
13826 	type = determine_uprobe_perf_type_legacy(probe_name, retprobe);
13827 	if (type < 0) {
13828 		err = type;
13829 		pr_warn("failed to determine legacy uprobe event id for %s:0x%zx: %s\n",
13830 			binary_path, offset, errstr(err));
13831 		goto err_clean_legacy;
13832 	}
13833 
13834 	memset(&attr, 0, attr_sz);
13835 	attr.size = attr_sz;
13836 	attr.config = type;
13837 	attr.type = PERF_TYPE_TRACEPOINT;
13838 
13839 	pfd = syscall(__NR_perf_event_open, &attr,
13840 		      pid < 0 ? -1 : pid, /* pid */
13841 		      pid == -1 ? 0 : -1, /* cpu */
13842 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
13843 	if (pfd < 0) {
13844 		err = -errno;
13845 		pr_warn("legacy uprobe perf_event_open() failed: %s\n", errstr(err));
13846 		goto err_clean_legacy;
13847 	}
13848 	return pfd;
13849 
13850 err_clean_legacy:
13851 	/* Clear the newly added legacy uprobe_event */
13852 	remove_uprobe_event_legacy(probe_name, retprobe);
13853 	return err;
13854 }
13855 
13856 /* Find offset of function name in archive specified by path. Currently
13857  * supported are .zip files that do not compress their contents, as used on
13858  * Android in the form of APKs, for example. "file_name" is the name of the ELF
13859  * file inside the archive. "func_name" matches symbol name or name@@LIB for
13860  * library functions.
13861  *
13862  * An overview of the APK format specifically provided here:
13863  * https://en.wikipedia.org/w/index.php?title=Apk_(file_format)&oldid=1139099120#Package_contents
13864  */
13865 static long elf_find_func_offset_from_archive(const char *archive_path, const char *file_name,
13866 					      const char *func_name)
13867 {
13868 	struct zip_archive *archive;
13869 	struct zip_entry entry;
13870 	long ret;
13871 	Elf *elf;
13872 
13873 	archive = zip_archive_open(archive_path);
13874 	if (IS_ERR(archive)) {
13875 		ret = PTR_ERR(archive);
13876 		pr_warn("zip: failed to open %s: %ld\n", archive_path, ret);
13877 		return ret;
13878 	}
13879 
13880 	ret = zip_archive_find_entry(archive, file_name, &entry);
13881 	if (ret) {
13882 		pr_warn("zip: could not find archive member %s in %s: %ld\n", file_name,
13883 			archive_path, ret);
13884 		goto out;
13885 	}
13886 	pr_debug("zip: found entry for %s in %s at 0x%lx\n", file_name, archive_path,
13887 		 (unsigned long)entry.data_offset);
13888 
13889 	if (entry.compression) {
13890 		pr_warn("zip: entry %s of %s is compressed and cannot be handled\n", file_name,
13891 			archive_path);
13892 		ret = -LIBBPF_ERRNO__FORMAT;
13893 		goto out;
13894 	}
13895 
13896 	elf = elf_memory((void *)entry.data, entry.data_length);
13897 	if (!elf) {
13898 		pr_warn("elf: could not read elf file %s from %s: %s\n", file_name, archive_path,
13899 			elf_errmsg(-1));
13900 		ret = -LIBBPF_ERRNO__LIBELF;
13901 		goto out;
13902 	}
13903 
13904 	ret = elf_find_func_offset(elf, file_name, func_name);
13905 	if (ret > 0) {
13906 		pr_debug("elf: symbol address match for %s of %s in %s: 0x%x + 0x%lx = 0x%lx\n",
13907 			 func_name, file_name, archive_path, entry.data_offset, (unsigned long)ret,
13908 			 (unsigned long)(ret + entry.data_offset));
13909 		ret += entry.data_offset;
13910 	}
13911 	elf_end(elf);
13912 
13913 out:
13914 	zip_archive_close(archive);
13915 	return ret;
13916 }
13917 
13918 static const char *arch_specific_lib_paths(void)
13919 {
13920 	/*
13921 	 * Based on https://packages.debian.org/sid/libc6.
13922 	 *
13923 	 * Assume that the traced program is built for the same architecture
13924 	 * as libbpf, which should cover the vast majority of cases.
13925 	 */
13926 #if defined(__x86_64__)
13927 	return "/lib/x86_64-linux-gnu";
13928 #elif defined(__i386__)
13929 	return "/lib/i386-linux-gnu";
13930 #elif defined(__s390x__)
13931 	return "/lib/s390x-linux-gnu";
13932 #elif defined(__arm__) && defined(__SOFTFP__)
13933 	return "/lib/arm-linux-gnueabi";
13934 #elif defined(__arm__) && !defined(__SOFTFP__)
13935 	return "/lib/arm-linux-gnueabihf";
13936 #elif defined(__aarch64__)
13937 	return "/lib/aarch64-linux-gnu";
13938 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 64
13939 	return "/lib/mips64el-linux-gnuabi64";
13940 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 32
13941 	return "/lib/mipsel-linux-gnu";
13942 #elif defined(__powerpc64__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
13943 	return "/lib/powerpc64le-linux-gnu";
13944 #elif defined(__sparc__) && defined(__arch64__)
13945 	return "/lib/sparc64-linux-gnu";
13946 #elif defined(__riscv) && __riscv_xlen == 64
13947 	return "/lib/riscv64-linux-gnu";
13948 #else
13949 	return NULL;
13950 #endif
13951 }
13952 
13953 /* Get full path to program/shared library. */
13954 static int resolve_full_path(const char *file, char *result, size_t result_sz)
13955 {
13956 	const char *search_paths[4] = {};
13957 	int i, perm;
13958 
13959 	if (str_has_sfx(file, ".so") || strstr(file, ".so.")) {
13960 		search_paths[0] = getenv("LD_LIBRARY_PATH");
13961 		search_paths[1] = "/usr/lib64:/usr/lib";
13962 		search_paths[2] = arch_specific_lib_paths();
13963 		search_paths[3] = "/lib64:/lib";
13964 		perm = R_OK;
13965 	} else {
13966 		search_paths[0] = getenv("PATH");
13967 		search_paths[1] = "/usr/bin:/usr/sbin";
13968 		perm = R_OK | X_OK;
13969 	}
13970 
13971 	for (i = 0; i < ARRAY_SIZE(search_paths); i++) {
13972 		const char *s;
13973 
13974 		if (!search_paths[i])
13975 			continue;
13976 		for (s = search_paths[i]; s != NULL; s = strchr(s, ':')) {
13977 			const char *next_path;
13978 			int seg_len;
13979 
13980 			if (s[0] == ':')
13981 				s++;
13982 			next_path = strchr(s, ':');
13983 			seg_len = next_path ? next_path - s : strlen(s);
13984 			if (!seg_len)
13985 				continue;
13986 			snprintf(result, result_sz, "%.*s/%s", seg_len, s, file);
13987 			/* ensure it has required permissions */
13988 			if (faccessat(AT_FDCWD, result, perm, AT_EACCESS) < 0)
13989 				continue;
13990 			pr_debug("resolved '%s' to '%s'\n", file, result);
13991 			return 0;
13992 		}
13993 	}
13994 	return -ENOENT;
13995 }
13996 
13997 struct bpf_link *
13998 bpf_program__attach_uprobe_multi(const struct bpf_program *prog,
13999 				 pid_t pid,
14000 				 const char *path,
14001 				 const char *func_pattern,
14002 				 const struct bpf_uprobe_multi_opts *opts)
14003 {
14004 	const unsigned long *ref_ctr_offsets = NULL, *offsets = NULL;
14005 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
14006 	unsigned long *resolved_offsets = NULL;
14007 	enum bpf_attach_type attach_type;
14008 	int err = 0, link_fd, prog_fd;
14009 	struct bpf_link *link = NULL;
14010 	char full_path[PATH_MAX];
14011 	bool retprobe, session;
14012 	const __u64 *cookies;
14013 	const char **syms;
14014 	size_t cnt;
14015 
14016 	if (!OPTS_VALID(opts, bpf_uprobe_multi_opts))
14017 		return libbpf_err_ptr(-EINVAL);
14018 
14019 	prog_fd = bpf_program__fd(prog);
14020 	if (prog_fd < 0) {
14021 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
14022 			prog->name);
14023 		return libbpf_err_ptr(-EINVAL);
14024 	}
14025 
14026 	syms = OPTS_GET(opts, syms, NULL);
14027 	offsets = OPTS_GET(opts, offsets, NULL);
14028 	ref_ctr_offsets = OPTS_GET(opts, ref_ctr_offsets, NULL);
14029 	cookies = OPTS_GET(opts, cookies, NULL);
14030 	cnt = OPTS_GET(opts, cnt, 0);
14031 	retprobe = OPTS_GET(opts, retprobe, false);
14032 	session  = OPTS_GET(opts, session, false);
14033 
14034 	/*
14035 	 * User can specify 2 mutually exclusive set of inputs:
14036 	 *
14037 	 * 1) use only path/func_pattern/pid arguments
14038 	 *
14039 	 * 2) use path/pid with allowed combinations of:
14040 	 *    syms/offsets/ref_ctr_offsets/cookies/cnt
14041 	 *
14042 	 *    - syms and offsets are mutually exclusive
14043 	 *    - ref_ctr_offsets and cookies are optional
14044 	 *
14045 	 * Any other usage results in error.
14046 	 */
14047 
14048 	if (!path)
14049 		return libbpf_err_ptr(-EINVAL);
14050 	if (!func_pattern && cnt == 0)
14051 		return libbpf_err_ptr(-EINVAL);
14052 
14053 	if (func_pattern) {
14054 		if (syms || offsets || ref_ctr_offsets || cookies || cnt)
14055 			return libbpf_err_ptr(-EINVAL);
14056 	} else {
14057 		if (!!syms == !!offsets)
14058 			return libbpf_err_ptr(-EINVAL);
14059 	}
14060 
14061 	if (retprobe && session)
14062 		return libbpf_err_ptr(-EINVAL);
14063 
14064 	if (func_pattern) {
14065 		if (!strchr(path, '/')) {
14066 			err = resolve_full_path(path, full_path, sizeof(full_path));
14067 			if (err) {
14068 				pr_warn("prog '%s': failed to resolve full path for '%s': %s\n",
14069 					prog->name, path, errstr(err));
14070 				return libbpf_err_ptr(err);
14071 			}
14072 			path = full_path;
14073 		}
14074 
14075 		err = elf_resolve_pattern_offsets(path, func_pattern,
14076 						  &resolved_offsets, &cnt);
14077 		if (err < 0)
14078 			return libbpf_err_ptr(err);
14079 		offsets = resolved_offsets;
14080 	} else if (syms) {
14081 		err = elf_resolve_syms_offsets(path, cnt, syms, &resolved_offsets, STT_FUNC);
14082 		if (err < 0)
14083 			return libbpf_err_ptr(err);
14084 		offsets = resolved_offsets;
14085 	}
14086 
14087 	attach_type = session ? BPF_TRACE_UPROBE_SESSION : BPF_TRACE_UPROBE_MULTI;
14088 
14089 	lopts.uprobe_multi.path = path;
14090 	lopts.uprobe_multi.offsets = offsets;
14091 	lopts.uprobe_multi.ref_ctr_offsets = ref_ctr_offsets;
14092 	lopts.uprobe_multi.cookies = cookies;
14093 	lopts.uprobe_multi.cnt = cnt;
14094 	lopts.uprobe_multi.flags = retprobe ? BPF_F_UPROBE_MULTI_RETURN : 0;
14095 
14096 	if (pid == 0)
14097 		pid = getpid();
14098 	if (pid > 0)
14099 		lopts.uprobe_multi.pid = pid;
14100 
14101 	link = calloc(1, sizeof(*link));
14102 	if (!link) {
14103 		err = -ENOMEM;
14104 		goto error;
14105 	}
14106 	link->detach = &bpf_link__detach_fd;
14107 
14108 	link_fd = bpf_link_create(prog_fd, 0, attach_type, &lopts);
14109 	if (link_fd < 0) {
14110 		err = -errno;
14111 		pr_warn("prog '%s': failed to attach multi-uprobe: %s\n",
14112 			prog->name, errstr(err));
14113 		goto error;
14114 	}
14115 	link->fd = link_fd;
14116 	free(resolved_offsets);
14117 	return link;
14118 
14119 error:
14120 	free(resolved_offsets);
14121 	free(link);
14122 	return libbpf_err_ptr(err);
14123 }
14124 
14125 LIBBPF_API struct bpf_link *
14126 bpf_program__attach_uprobe_opts(const struct bpf_program *prog, pid_t pid,
14127 				const char *binary_path, size_t func_offset,
14128 				const struct bpf_uprobe_opts *opts)
14129 {
14130 	const char *archive_path = NULL, *archive_sep = NULL;
14131 	char *legacy_probe = NULL;
14132 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
14133 	enum probe_attach_mode attach_mode;
14134 	char full_path[PATH_MAX];
14135 	struct bpf_link *link;
14136 	size_t ref_ctr_off;
14137 	int pfd, err;
14138 	bool retprobe, legacy;
14139 	const char *func_name;
14140 
14141 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
14142 		return libbpf_err_ptr(-EINVAL);
14143 
14144 	attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
14145 	retprobe = OPTS_GET(opts, retprobe, false);
14146 	ref_ctr_off = OPTS_GET(opts, ref_ctr_offset, 0);
14147 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
14148 
14149 	if (!binary_path)
14150 		return libbpf_err_ptr(-EINVAL);
14151 
14152 	/* Check if "binary_path" refers to an archive. */
14153 	archive_sep = strstr(binary_path, "!/");
14154 	if (archive_sep) {
14155 		full_path[0] = '\0';
14156 		libbpf_strlcpy(full_path, binary_path,
14157 			       min(sizeof(full_path), (size_t)(archive_sep - binary_path + 1)));
14158 		archive_path = full_path;
14159 		binary_path = archive_sep + 2;
14160 	} else if (!strchr(binary_path, '/')) {
14161 		err = resolve_full_path(binary_path, full_path, sizeof(full_path));
14162 		if (err) {
14163 			pr_warn("prog '%s': failed to resolve full path for '%s': %s\n",
14164 				prog->name, binary_path, errstr(err));
14165 			return libbpf_err_ptr(err);
14166 		}
14167 		binary_path = full_path;
14168 	}
14169 	func_name = OPTS_GET(opts, func_name, NULL);
14170 	if (func_name) {
14171 		long sym_off;
14172 
14173 		if (archive_path) {
14174 			sym_off = elf_find_func_offset_from_archive(archive_path, binary_path,
14175 								    func_name);
14176 			binary_path = archive_path;
14177 		} else {
14178 			sym_off = elf_find_func_offset_from_file(binary_path, func_name);
14179 		}
14180 		if (sym_off < 0)
14181 			return libbpf_err_ptr(sym_off);
14182 		func_offset += sym_off;
14183 	}
14184 
14185 	legacy = determine_uprobe_perf_type() < 0;
14186 	switch (attach_mode) {
14187 	case PROBE_ATTACH_MODE_LEGACY:
14188 		legacy = true;
14189 		pe_opts.force_ioctl_attach = true;
14190 		break;
14191 	case PROBE_ATTACH_MODE_PERF:
14192 		if (legacy)
14193 			return libbpf_err_ptr(-ENOTSUP);
14194 		pe_opts.force_ioctl_attach = true;
14195 		break;
14196 	case PROBE_ATTACH_MODE_LINK:
14197 		if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
14198 			return libbpf_err_ptr(-ENOTSUP);
14199 		break;
14200 	case PROBE_ATTACH_MODE_DEFAULT:
14201 		break;
14202 	default:
14203 		return libbpf_err_ptr(-EINVAL);
14204 	}
14205 
14206 	if (!legacy) {
14207 		pfd = perf_event_open_probe(true /* uprobe */, retprobe, binary_path,
14208 					    func_offset, pid, ref_ctr_off);
14209 	} else {
14210 		char probe_name[MAX_EVENT_NAME_LEN];
14211 
14212 		if (ref_ctr_off)
14213 			return libbpf_err_ptr(-EINVAL);
14214 
14215 		gen_probe_legacy_event_name(probe_name, sizeof(probe_name),
14216 					    strrchr(binary_path, '/') ? : binary_path,
14217 					    func_offset);
14218 
14219 		legacy_probe = strdup(probe_name);
14220 		if (!legacy_probe)
14221 			return libbpf_err_ptr(-ENOMEM);
14222 
14223 		pfd = perf_event_uprobe_open_legacy(legacy_probe, retprobe,
14224 						    binary_path, func_offset, pid);
14225 	}
14226 	if (pfd < 0) {
14227 		err = pfd;
14228 		pr_warn("prog '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
14229 			prog->name, retprobe ? "uretprobe" : "uprobe",
14230 			binary_path, func_offset,
14231 			errstr(err));
14232 		goto err_out;
14233 	}
14234 
14235 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
14236 	err = libbpf_get_error(link);
14237 	if (err) {
14238 		close(pfd);
14239 		pr_warn("prog '%s': failed to attach to %s '%s:0x%zx': %s\n",
14240 			prog->name, retprobe ? "uretprobe" : "uprobe",
14241 			binary_path, func_offset,
14242 			errstr(err));
14243 		goto err_clean_legacy;
14244 	}
14245 	if (legacy) {
14246 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
14247 
14248 		perf_link->legacy_probe_name = legacy_probe;
14249 		perf_link->legacy_is_kprobe = false;
14250 		perf_link->legacy_is_retprobe = retprobe;
14251 	}
14252 	return link;
14253 
14254 err_clean_legacy:
14255 	if (legacy)
14256 		remove_uprobe_event_legacy(legacy_probe, retprobe);
14257 err_out:
14258 	free(legacy_probe);
14259 	return libbpf_err_ptr(err);
14260 }
14261 
14262 /* Format of u[ret]probe section definition supporting auto-attach:
14263  * u[ret]probe/binary:function[+offset]
14264  *
14265  * binary can be an absolute/relative path or a filename; the latter is resolved to a
14266  * full binary path via bpf_program__attach_uprobe_opts.
14267  *
14268  * Specifying uprobe+ ensures we carry out strict matching; either "uprobe" must be
14269  * specified (and auto-attach is not possible) or the above format is specified for
14270  * auto-attach.
14271  */
14272 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
14273 {
14274 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts);
14275 	char *probe_type = NULL, *binary_path = NULL, *func_name = NULL, *func_off;
14276 	int n, c, ret = -EINVAL;
14277 	long offset = 0;
14278 
14279 	*link = NULL;
14280 
14281 	n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[^\n]",
14282 		   &probe_type, &binary_path, &func_name);
14283 	switch (n) {
14284 	case 1:
14285 		/* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
14286 		ret = 0;
14287 		break;
14288 	case 2:
14289 		pr_warn("prog '%s': section '%s' missing ':function[+offset]' specification\n",
14290 			prog->name, prog->sec_name);
14291 		break;
14292 	case 3:
14293 		/* check if user specifies `+offset`, if yes, this should be
14294 		 * the last part of the string, make sure sscanf read to EOL
14295 		 */
14296 		func_off = strrchr(func_name, '+');
14297 		if (func_off) {
14298 			n = sscanf(func_off, "+%li%n", &offset, &c);
14299 			if (n == 1 && *(func_off + c) == '\0')
14300 				func_off[0] = '\0';
14301 			else
14302 				offset = 0;
14303 		}
14304 		opts.retprobe = strcmp(probe_type, "uretprobe") == 0 ||
14305 				strcmp(probe_type, "uretprobe.s") == 0;
14306 		if (opts.retprobe && offset != 0) {
14307 			pr_warn("prog '%s': uretprobes do not support offset specification\n",
14308 				prog->name);
14309 			break;
14310 		}
14311 		opts.func_name = func_name;
14312 		*link = bpf_program__attach_uprobe_opts(prog, -1, binary_path, offset, &opts);
14313 		ret = libbpf_get_error(*link);
14314 		break;
14315 	default:
14316 		pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
14317 			prog->sec_name);
14318 		break;
14319 	}
14320 	free(probe_type);
14321 	free(binary_path);
14322 	free(func_name);
14323 
14324 	return ret;
14325 }
14326 
14327 struct bpf_link *bpf_program__attach_uprobe(const struct bpf_program *prog,
14328 					    bool retprobe, pid_t pid,
14329 					    const char *binary_path,
14330 					    size_t func_offset)
14331 {
14332 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts, .retprobe = retprobe);
14333 
14334 	return bpf_program__attach_uprobe_opts(prog, pid, binary_path, func_offset, &opts);
14335 }
14336 
14337 struct bpf_link *bpf_program__attach_usdt(const struct bpf_program *prog,
14338 					  pid_t pid, const char *binary_path,
14339 					  const char *usdt_provider, const char *usdt_name,
14340 					  const struct bpf_usdt_opts *opts)
14341 {
14342 	char resolved_path[512];
14343 	struct bpf_object *obj = prog->obj;
14344 	struct bpf_link *link;
14345 	__u64 usdt_cookie;
14346 	int err;
14347 
14348 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
14349 		return libbpf_err_ptr(-EINVAL);
14350 
14351 	if (bpf_program__fd(prog) < 0) {
14352 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
14353 			prog->name);
14354 		return libbpf_err_ptr(-EINVAL);
14355 	}
14356 
14357 	if (!binary_path)
14358 		return libbpf_err_ptr(-EINVAL);
14359 
14360 	if (!strchr(binary_path, '/')) {
14361 		err = resolve_full_path(binary_path, resolved_path, sizeof(resolved_path));
14362 		if (err) {
14363 			pr_warn("prog '%s': failed to resolve full path for '%s': %s\n",
14364 				prog->name, binary_path, errstr(err));
14365 			return libbpf_err_ptr(err);
14366 		}
14367 		binary_path = resolved_path;
14368 	}
14369 
14370 	/* USDT manager is instantiated lazily on first USDT attach. It will
14371 	 * be destroyed together with BPF object in bpf_object__close().
14372 	 */
14373 	if (IS_ERR(obj->usdt_man))
14374 		return libbpf_ptr(obj->usdt_man);
14375 	if (!obj->usdt_man) {
14376 		obj->usdt_man = usdt_manager_new(obj);
14377 		if (IS_ERR(obj->usdt_man))
14378 			return libbpf_ptr(obj->usdt_man);
14379 	}
14380 
14381 	usdt_cookie = OPTS_GET(opts, usdt_cookie, 0);
14382 	link = usdt_manager_attach_usdt(obj->usdt_man, prog, pid, binary_path,
14383 					usdt_provider, usdt_name, usdt_cookie);
14384 	err = libbpf_get_error(link);
14385 	if (err)
14386 		return libbpf_err_ptr(err);
14387 	return link;
14388 }
14389 
14390 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link)
14391 {
14392 	char *path = NULL, *provider = NULL, *name = NULL;
14393 	const char *sec_name;
14394 	int n, err;
14395 
14396 	sec_name = bpf_program__section_name(prog);
14397 	if (strcmp(sec_name, "usdt") == 0) {
14398 		/* no auto-attach for just SEC("usdt") */
14399 		*link = NULL;
14400 		return 0;
14401 	}
14402 
14403 	n = sscanf(sec_name, "usdt/%m[^:]:%m[^:]:%m[^:]", &path, &provider, &name);
14404 	if (n != 3) {
14405 		pr_warn("invalid section '%s', expected SEC(\"usdt/<path>:<provider>:<name>\")\n",
14406 			sec_name);
14407 		err = -EINVAL;
14408 	} else {
14409 		*link = bpf_program__attach_usdt(prog, -1 /* any process */, path,
14410 						 provider, name, NULL);
14411 		err = libbpf_get_error(*link);
14412 	}
14413 	free(path);
14414 	free(provider);
14415 	free(name);
14416 	return err;
14417 }
14418 
14419 static int determine_tracepoint_id(const char *tp_category,
14420 				   const char *tp_name)
14421 {
14422 	char file[PATH_MAX];
14423 	int ret;
14424 
14425 	ret = snprintf(file, sizeof(file), "%s/events/%s/%s/id",
14426 		       tracefs_path(), tp_category, tp_name);
14427 	if (ret < 0)
14428 		return -errno;
14429 	if (ret >= sizeof(file)) {
14430 		pr_debug("tracepoint %s/%s path is too long\n",
14431 			 tp_category, tp_name);
14432 		return -E2BIG;
14433 	}
14434 	return parse_uint_from_file(file, "%d\n");
14435 }
14436 
14437 static int perf_event_open_tracepoint(const char *tp_category,
14438 				      const char *tp_name)
14439 {
14440 	const size_t attr_sz = sizeof(struct perf_event_attr);
14441 	struct perf_event_attr attr;
14442 	int tp_id, pfd, err;
14443 
14444 	tp_id = determine_tracepoint_id(tp_category, tp_name);
14445 	if (tp_id < 0) {
14446 		pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
14447 			tp_category, tp_name,
14448 			errstr(tp_id));
14449 		return tp_id;
14450 	}
14451 
14452 	memset(&attr, 0, attr_sz);
14453 	attr.type = PERF_TYPE_TRACEPOINT;
14454 	attr.size = attr_sz;
14455 	attr.config = tp_id;
14456 
14457 	pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
14458 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
14459 	if (pfd < 0) {
14460 		err = -errno;
14461 		pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
14462 			tp_category, tp_name,
14463 			errstr(err));
14464 		return err;
14465 	}
14466 	return pfd;
14467 }
14468 
14469 struct bpf_link *bpf_program__attach_tracepoint_opts(const struct bpf_program *prog,
14470 						     const char *tp_category,
14471 						     const char *tp_name,
14472 						     const struct bpf_tracepoint_opts *opts)
14473 {
14474 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
14475 	struct bpf_link *link;
14476 	int pfd, err;
14477 
14478 	if (!OPTS_VALID(opts, bpf_tracepoint_opts))
14479 		return libbpf_err_ptr(-EINVAL);
14480 
14481 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
14482 
14483 	pfd = perf_event_open_tracepoint(tp_category, tp_name);
14484 	if (pfd < 0) {
14485 		pr_warn("prog '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
14486 			prog->name, tp_category, tp_name,
14487 			errstr(pfd));
14488 		return libbpf_err_ptr(pfd);
14489 	}
14490 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
14491 	err = libbpf_get_error(link);
14492 	if (err) {
14493 		close(pfd);
14494 		pr_warn("prog '%s': failed to attach to tracepoint '%s/%s': %s\n",
14495 			prog->name, tp_category, tp_name,
14496 			errstr(err));
14497 		return libbpf_err_ptr(err);
14498 	}
14499 	return link;
14500 }
14501 
14502 struct bpf_link *bpf_program__attach_tracepoint(const struct bpf_program *prog,
14503 						const char *tp_category,
14504 						const char *tp_name)
14505 {
14506 	return bpf_program__attach_tracepoint_opts(prog, tp_category, tp_name, NULL);
14507 }
14508 
14509 /*
14510  * Match section name against a prefix array. Returns pointer past
14511  * "prefix/" on match, empty string for bare sections (exact prefix
14512  * match), or NULL if no prefix matches.
14513  */
14514 static const char *sec_name_match_prefix(const char *sec_name,
14515 					 const char *const *prefixes,
14516 					 size_t n)
14517 {
14518 	size_t i;
14519 
14520 	for (i = 0; i < n; i++) {
14521 		size_t pfx_len;
14522 
14523 		if (!str_has_pfx(sec_name, prefixes[i]))
14524 			continue;
14525 
14526 		pfx_len = strlen(prefixes[i]);
14527 		if (sec_name[pfx_len] == '\0')
14528 			return sec_name + pfx_len;
14529 
14530 		if (sec_name[pfx_len] != '/' || sec_name[pfx_len + 1] == '\0')
14531 			continue;
14532 
14533 		return sec_name + pfx_len + 1;
14534 	}
14535 	return NULL;
14536 }
14537 
14538 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
14539 {
14540 	static const char *const prefixes[] = {
14541 		"tp.s",
14542 		"tp",
14543 		"tracepoint.s",
14544 		"tracepoint",
14545 	};
14546 	char *sec_name, *tp_cat, *tp_name;
14547 	const char *match;
14548 
14549 	*link = NULL;
14550 
14551 	match = sec_name_match_prefix(prog->sec_name, prefixes, ARRAY_SIZE(prefixes));
14552 	if (!match) {
14553 		pr_warn("prog '%s': invalid section name '%s'\n", prog->name, prog->sec_name);
14554 		return -EINVAL;
14555 	}
14556 	if (!match[0]) /* bare section name no autoattach */
14557 		return 0;
14558 
14559 	sec_name = strdup(prog->sec_name);
14560 	if (!sec_name)
14561 		return -ENOMEM;
14562 
14563 	tp_cat = sec_name + (match - prog->sec_name);
14564 	tp_name = strchr(tp_cat, '/');
14565 	if (!tp_name) {
14566 		free(sec_name);
14567 		return -EINVAL;
14568 	}
14569 	*tp_name = '\0';
14570 	tp_name++;
14571 
14572 	*link = bpf_program__attach_tracepoint(prog, tp_cat, tp_name);
14573 	free(sec_name);
14574 	return libbpf_get_error(*link);
14575 }
14576 
14577 struct bpf_link *
14578 bpf_program__attach_raw_tracepoint_opts(const struct bpf_program *prog,
14579 					const char *tp_name,
14580 					struct bpf_raw_tracepoint_opts *opts)
14581 {
14582 	LIBBPF_OPTS(bpf_raw_tp_opts, raw_opts);
14583 	struct bpf_link *link;
14584 	int prog_fd, pfd;
14585 
14586 	if (!OPTS_VALID(opts, bpf_raw_tracepoint_opts))
14587 		return libbpf_err_ptr(-EINVAL);
14588 
14589 	prog_fd = bpf_program__fd(prog);
14590 	if (prog_fd < 0) {
14591 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
14592 		return libbpf_err_ptr(-EINVAL);
14593 	}
14594 
14595 	link = calloc(1, sizeof(*link));
14596 	if (!link)
14597 		return libbpf_err_ptr(-ENOMEM);
14598 	link->detach = &bpf_link__detach_fd;
14599 
14600 	raw_opts.tp_name = tp_name;
14601 	raw_opts.cookie = OPTS_GET(opts, cookie, 0);
14602 	pfd = bpf_raw_tracepoint_open_opts(prog_fd, &raw_opts);
14603 	if (pfd < 0) {
14604 		pfd = -errno;
14605 		free(link);
14606 		pr_warn("prog '%s': failed to attach to raw tracepoint '%s': %s\n",
14607 			prog->name, tp_name, errstr(pfd));
14608 		return libbpf_err_ptr(pfd);
14609 	}
14610 	link->fd = pfd;
14611 	return link;
14612 }
14613 
14614 struct bpf_link *bpf_program__attach_raw_tracepoint(const struct bpf_program *prog,
14615 						    const char *tp_name)
14616 {
14617 	return bpf_program__attach_raw_tracepoint_opts(prog, tp_name, NULL);
14618 }
14619 
14620 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
14621 {
14622 	static const char *const prefixes[] = {
14623 		"raw_tp",
14624 		"raw_tracepoint",
14625 		"raw_tp.w",
14626 		"raw_tracepoint.w",
14627 		"raw_tp.s",
14628 		"raw_tracepoint.s",
14629 	};
14630 	const char *match;
14631 
14632 	*link = NULL;
14633 
14634 	match = sec_name_match_prefix(prog->sec_name, prefixes, ARRAY_SIZE(prefixes));
14635 	if (!match) {
14636 		pr_warn("prog '%s': invalid section name '%s'\n", prog->name, prog->sec_name);
14637 		return -EINVAL;
14638 	}
14639 	if (!match[0])
14640 		return 0;
14641 
14642 	*link = bpf_program__attach_raw_tracepoint(prog, match);
14643 	return libbpf_get_error(*link);
14644 }
14645 
14646 /* Common logic for all BPF program types that attach to a btf_id */
14647 static struct bpf_link *bpf_program__attach_btf_id(const struct bpf_program *prog,
14648 						   const struct bpf_trace_opts *opts)
14649 {
14650 	LIBBPF_OPTS(bpf_link_create_opts, link_opts);
14651 	struct bpf_link *link;
14652 	int prog_fd, pfd;
14653 
14654 	if (!OPTS_VALID(opts, bpf_trace_opts))
14655 		return libbpf_err_ptr(-EINVAL);
14656 
14657 	prog_fd = bpf_program__fd(prog);
14658 	if (prog_fd < 0) {
14659 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
14660 		return libbpf_err_ptr(-EINVAL);
14661 	}
14662 
14663 	link = calloc(1, sizeof(*link));
14664 	if (!link)
14665 		return libbpf_err_ptr(-ENOMEM);
14666 	link->detach = &bpf_link__detach_fd;
14667 
14668 	/* libbpf is smart enough to redirect to BPF_RAW_TRACEPOINT_OPEN on old kernels */
14669 	link_opts.tracing.cookie = OPTS_GET(opts, cookie, 0);
14670 	pfd = bpf_link_create(prog_fd, 0, bpf_program__expected_attach_type(prog), &link_opts);
14671 	if (pfd < 0) {
14672 		pfd = -errno;
14673 		free(link);
14674 		pr_warn("prog '%s': failed to attach: %s\n",
14675 			prog->name, errstr(pfd));
14676 		return libbpf_err_ptr(pfd);
14677 	}
14678 	link->fd = pfd;
14679 	return link;
14680 }
14681 
14682 struct bpf_link *bpf_program__attach_trace(const struct bpf_program *prog)
14683 {
14684 	return bpf_program__attach_btf_id(prog, NULL);
14685 }
14686 
14687 struct bpf_link *bpf_program__attach_trace_opts(const struct bpf_program *prog,
14688 						const struct bpf_trace_opts *opts)
14689 {
14690 	return bpf_program__attach_btf_id(prog, opts);
14691 }
14692 
14693 struct bpf_link *bpf_program__attach_lsm(const struct bpf_program *prog)
14694 {
14695 	return bpf_program__attach_btf_id(prog, NULL);
14696 }
14697 
14698 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link)
14699 {
14700 	*link = bpf_program__attach_trace(prog);
14701 	return libbpf_get_error(*link);
14702 }
14703 
14704 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link)
14705 {
14706 	*link = bpf_program__attach_lsm(prog);
14707 	return libbpf_get_error(*link);
14708 }
14709 
14710 static struct bpf_link *
14711 bpf_program_attach_fd(const struct bpf_program *prog,
14712 		      int target_fd, const char *target_name,
14713 		      const struct bpf_link_create_opts *opts)
14714 {
14715 	enum bpf_attach_type attach_type;
14716 	struct bpf_link *link;
14717 	int prog_fd, link_fd;
14718 
14719 	prog_fd = bpf_program__fd(prog);
14720 	if (prog_fd < 0) {
14721 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
14722 		return libbpf_err_ptr(-EINVAL);
14723 	}
14724 
14725 	link = calloc(1, sizeof(*link));
14726 	if (!link)
14727 		return libbpf_err_ptr(-ENOMEM);
14728 	link->detach = &bpf_link__detach_fd;
14729 
14730 	attach_type = bpf_program__expected_attach_type(prog);
14731 	link_fd = bpf_link_create(prog_fd, target_fd, attach_type, opts);
14732 	if (link_fd < 0) {
14733 		link_fd = -errno;
14734 		free(link);
14735 		pr_warn("prog '%s': failed to attach to %s: %s\n",
14736 			prog->name, target_name,
14737 			errstr(link_fd));
14738 		return libbpf_err_ptr(link_fd);
14739 	}
14740 	link->fd = link_fd;
14741 	return link;
14742 }
14743 
14744 struct bpf_link *
14745 bpf_program__attach_cgroup(const struct bpf_program *prog, int cgroup_fd)
14746 {
14747 	return bpf_program_attach_fd(prog, cgroup_fd, "cgroup", NULL);
14748 }
14749 
14750 struct bpf_link *
14751 bpf_program__attach_netns(const struct bpf_program *prog, int netns_fd)
14752 {
14753 	return bpf_program_attach_fd(prog, netns_fd, "netns", NULL);
14754 }
14755 
14756 struct bpf_link *
14757 bpf_program__attach_sockmap(const struct bpf_program *prog, int map_fd)
14758 {
14759 	return bpf_program_attach_fd(prog, map_fd, "sockmap", NULL);
14760 }
14761 
14762 struct bpf_link *bpf_program__attach_xdp(const struct bpf_program *prog, int ifindex)
14763 {
14764 	/* target_fd/target_ifindex use the same field in LINK_CREATE */
14765 	return bpf_program_attach_fd(prog, ifindex, "xdp", NULL);
14766 }
14767 
14768 struct bpf_link *
14769 bpf_program__attach_cgroup_opts(const struct bpf_program *prog, int cgroup_fd,
14770 				const struct bpf_cgroup_opts *opts)
14771 {
14772 	LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
14773 	__u32 relative_id;
14774 	int relative_fd;
14775 
14776 	if (!OPTS_VALID(opts, bpf_cgroup_opts))
14777 		return libbpf_err_ptr(-EINVAL);
14778 
14779 	relative_id = OPTS_GET(opts, relative_id, 0);
14780 	relative_fd = OPTS_GET(opts, relative_fd, 0);
14781 
14782 	if (relative_fd && relative_id) {
14783 		pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
14784 			prog->name);
14785 		return libbpf_err_ptr(-EINVAL);
14786 	}
14787 
14788 	link_create_opts.cgroup.expected_revision = OPTS_GET(opts, expected_revision, 0);
14789 	link_create_opts.cgroup.relative_fd = relative_fd;
14790 	link_create_opts.cgroup.relative_id = relative_id;
14791 	link_create_opts.flags = OPTS_GET(opts, flags, 0);
14792 
14793 	return bpf_program_attach_fd(prog, cgroup_fd, "cgroup", &link_create_opts);
14794 }
14795 
14796 struct bpf_link *
14797 bpf_program__attach_tcx(const struct bpf_program *prog, int ifindex,
14798 			const struct bpf_tcx_opts *opts)
14799 {
14800 	LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
14801 	__u32 relative_id;
14802 	int relative_fd;
14803 
14804 	if (!OPTS_VALID(opts, bpf_tcx_opts))
14805 		return libbpf_err_ptr(-EINVAL);
14806 
14807 	relative_id = OPTS_GET(opts, relative_id, 0);
14808 	relative_fd = OPTS_GET(opts, relative_fd, 0);
14809 
14810 	/* validate we don't have unexpected combinations of non-zero fields */
14811 	if (!ifindex) {
14812 		pr_warn("prog '%s': target netdevice ifindex cannot be zero\n",
14813 			prog->name);
14814 		return libbpf_err_ptr(-EINVAL);
14815 	}
14816 	if (relative_fd && relative_id) {
14817 		pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
14818 			prog->name);
14819 		return libbpf_err_ptr(-EINVAL);
14820 	}
14821 
14822 	link_create_opts.tcx.expected_revision = OPTS_GET(opts, expected_revision, 0);
14823 	link_create_opts.tcx.relative_fd = relative_fd;
14824 	link_create_opts.tcx.relative_id = relative_id;
14825 	link_create_opts.flags = OPTS_GET(opts, flags, 0);
14826 
14827 	/* target_fd/target_ifindex use the same field in LINK_CREATE */
14828 	return bpf_program_attach_fd(prog, ifindex, "tcx", &link_create_opts);
14829 }
14830 
14831 struct bpf_link *
14832 bpf_program__attach_netkit(const struct bpf_program *prog, int ifindex,
14833 			   const struct bpf_netkit_opts *opts)
14834 {
14835 	LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
14836 	__u32 relative_id;
14837 	int relative_fd;
14838 
14839 	if (!OPTS_VALID(opts, bpf_netkit_opts))
14840 		return libbpf_err_ptr(-EINVAL);
14841 
14842 	relative_id = OPTS_GET(opts, relative_id, 0);
14843 	relative_fd = OPTS_GET(opts, relative_fd, 0);
14844 
14845 	/* validate we don't have unexpected combinations of non-zero fields */
14846 	if (!ifindex) {
14847 		pr_warn("prog '%s': target netdevice ifindex cannot be zero\n",
14848 			prog->name);
14849 		return libbpf_err_ptr(-EINVAL);
14850 	}
14851 	if (relative_fd && relative_id) {
14852 		pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
14853 			prog->name);
14854 		return libbpf_err_ptr(-EINVAL);
14855 	}
14856 
14857 	link_create_opts.netkit.expected_revision = OPTS_GET(opts, expected_revision, 0);
14858 	link_create_opts.netkit.relative_fd = relative_fd;
14859 	link_create_opts.netkit.relative_id = relative_id;
14860 	link_create_opts.flags = OPTS_GET(opts, flags, 0);
14861 
14862 	return bpf_program_attach_fd(prog, ifindex, "netkit", &link_create_opts);
14863 }
14864 
14865 struct bpf_link *bpf_program__attach_freplace(const struct bpf_program *prog,
14866 					      int target_fd,
14867 					      const char *attach_func_name)
14868 {
14869 	int btf_id;
14870 
14871 	if (!!target_fd != !!attach_func_name) {
14872 		pr_warn("prog '%s': supply none or both of target_fd and attach_func_name\n",
14873 			prog->name);
14874 		return libbpf_err_ptr(-EINVAL);
14875 	}
14876 
14877 	if (prog->type != BPF_PROG_TYPE_EXT) {
14878 		pr_warn("prog '%s': only BPF_PROG_TYPE_EXT can attach as freplace\n",
14879 			prog->name);
14880 		return libbpf_err_ptr(-EINVAL);
14881 	}
14882 
14883 	if (target_fd) {
14884 		LIBBPF_OPTS(bpf_link_create_opts, target_opts);
14885 
14886 		btf_id = libbpf_find_prog_btf_id(attach_func_name, target_fd, prog->obj->token_fd);
14887 		if (btf_id < 0)
14888 			return libbpf_err_ptr(btf_id);
14889 
14890 		target_opts.target_btf_id = btf_id;
14891 
14892 		return bpf_program_attach_fd(prog, target_fd, "freplace",
14893 					     &target_opts);
14894 	} else {
14895 		/* no target, so use raw_tracepoint_open for compatibility
14896 		 * with old kernels
14897 		 */
14898 		return bpf_program__attach_trace(prog);
14899 	}
14900 }
14901 
14902 struct bpf_link *
14903 bpf_program__attach_iter(const struct bpf_program *prog,
14904 			 const struct bpf_iter_attach_opts *opts)
14905 {
14906 	DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
14907 	struct bpf_link *link;
14908 	int prog_fd, link_fd;
14909 	__u32 target_fd = 0;
14910 
14911 	if (!OPTS_VALID(opts, bpf_iter_attach_opts))
14912 		return libbpf_err_ptr(-EINVAL);
14913 
14914 	link_create_opts.iter_info = OPTS_GET(opts, link_info, (void *)0);
14915 	link_create_opts.iter_info_len = OPTS_GET(opts, link_info_len, 0);
14916 
14917 	prog_fd = bpf_program__fd(prog);
14918 	if (prog_fd < 0) {
14919 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
14920 		return libbpf_err_ptr(-EINVAL);
14921 	}
14922 
14923 	link = calloc(1, sizeof(*link));
14924 	if (!link)
14925 		return libbpf_err_ptr(-ENOMEM);
14926 	link->detach = &bpf_link__detach_fd;
14927 
14928 	link_fd = bpf_link_create(prog_fd, target_fd, BPF_TRACE_ITER,
14929 				  &link_create_opts);
14930 	if (link_fd < 0) {
14931 		link_fd = -errno;
14932 		free(link);
14933 		pr_warn("prog '%s': failed to attach to iterator: %s\n",
14934 			prog->name, errstr(link_fd));
14935 		return libbpf_err_ptr(link_fd);
14936 	}
14937 	link->fd = link_fd;
14938 	return link;
14939 }
14940 
14941 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link)
14942 {
14943 	*link = bpf_program__attach_iter(prog, NULL);
14944 	return libbpf_get_error(*link);
14945 }
14946 
14947 struct bpf_link *bpf_program__attach_netfilter(const struct bpf_program *prog,
14948 					       const struct bpf_netfilter_opts *opts)
14949 {
14950 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
14951 	struct bpf_link *link;
14952 	int prog_fd, link_fd;
14953 
14954 	if (!OPTS_VALID(opts, bpf_netfilter_opts))
14955 		return libbpf_err_ptr(-EINVAL);
14956 
14957 	prog_fd = bpf_program__fd(prog);
14958 	if (prog_fd < 0) {
14959 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
14960 		return libbpf_err_ptr(-EINVAL);
14961 	}
14962 
14963 	link = calloc(1, sizeof(*link));
14964 	if (!link)
14965 		return libbpf_err_ptr(-ENOMEM);
14966 
14967 	link->detach = &bpf_link__detach_fd;
14968 
14969 	lopts.netfilter.pf = OPTS_GET(opts, pf, 0);
14970 	lopts.netfilter.hooknum = OPTS_GET(opts, hooknum, 0);
14971 	lopts.netfilter.priority = OPTS_GET(opts, priority, 0);
14972 	lopts.netfilter.flags = OPTS_GET(opts, flags, 0);
14973 
14974 	link_fd = bpf_link_create(prog_fd, 0, BPF_NETFILTER, &lopts);
14975 	if (link_fd < 0) {
14976 		link_fd = -errno;
14977 		free(link);
14978 		pr_warn("prog '%s': failed to attach to netfilter: %s\n",
14979 			prog->name, errstr(link_fd));
14980 		return libbpf_err_ptr(link_fd);
14981 	}
14982 	link->fd = link_fd;
14983 
14984 	return link;
14985 }
14986 
14987 struct bpf_link *bpf_program__attach(const struct bpf_program *prog)
14988 {
14989 	struct bpf_link *link = NULL;
14990 	int err;
14991 
14992 	if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
14993 		return libbpf_err_ptr(-EOPNOTSUPP);
14994 
14995 	if (bpf_program__fd(prog) < 0) {
14996 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
14997 			prog->name);
14998 		return libbpf_err_ptr(-EINVAL);
14999 	}
15000 
15001 	err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, &link);
15002 	if (err)
15003 		return libbpf_err_ptr(err);
15004 
15005 	/* When calling bpf_program__attach() explicitly, auto-attach support
15006 	 * is expected to work, so NULL returned link is considered an error.
15007 	 * This is different for skeleton's attach, see comment in
15008 	 * bpf_object__attach_skeleton().
15009 	 */
15010 	if (!link)
15011 		return libbpf_err_ptr(-EOPNOTSUPP);
15012 
15013 	return link;
15014 }
15015 
15016 struct bpf_link_struct_ops {
15017 	struct bpf_link link;
15018 	int map_fd;
15019 };
15020 
15021 static int bpf_link__detach_struct_ops(struct bpf_link *link)
15022 {
15023 	struct bpf_link_struct_ops *st_link;
15024 	__u32 zero = 0;
15025 
15026 	st_link = container_of(link, struct bpf_link_struct_ops, link);
15027 
15028 	if (st_link->map_fd < 0)
15029 		/* w/o a real link */
15030 		return bpf_map_delete_elem(link->fd, &zero);
15031 
15032 	return close(link->fd);
15033 }
15034 
15035 struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map)
15036 {
15037 	struct bpf_link_struct_ops *link;
15038 	__u32 zero = 0;
15039 	int err, fd;
15040 
15041 	if (!bpf_map__is_struct_ops(map)) {
15042 		pr_warn("map '%s': can't attach non-struct_ops map\n", map->name);
15043 		return libbpf_err_ptr(-EINVAL);
15044 	}
15045 
15046 	if (map->fd < 0) {
15047 		pr_warn("map '%s': can't attach BPF map without FD (was it created?)\n", map->name);
15048 		return libbpf_err_ptr(-EINVAL);
15049 	}
15050 
15051 	link = calloc(1, sizeof(*link));
15052 	if (!link)
15053 		return libbpf_err_ptr(-EINVAL);
15054 
15055 	/* kern_vdata should be prepared during the loading phase. */
15056 	err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
15057 	/* It can be EBUSY if the map has been used to create or
15058 	 * update a link before.  We don't allow updating the value of
15059 	 * a struct_ops once it is set.  That ensures that the value
15060 	 * never changed.  So, it is safe to skip EBUSY.
15061 	 */
15062 	if (err && (!(map->def.map_flags & BPF_F_LINK) || err != -EBUSY)) {
15063 		free(link);
15064 		return libbpf_err_ptr(err);
15065 	}
15066 
15067 	link->link.detach = bpf_link__detach_struct_ops;
15068 
15069 	if (!(map->def.map_flags & BPF_F_LINK)) {
15070 		/* w/o a real link */
15071 		link->link.fd = map->fd;
15072 		link->map_fd = -1;
15073 		return &link->link;
15074 	}
15075 
15076 	fd = bpf_link_create(map->fd, 0, BPF_STRUCT_OPS, NULL);
15077 	if (fd < 0) {
15078 		free(link);
15079 		return libbpf_err_ptr(fd);
15080 	}
15081 
15082 	link->link.fd = fd;
15083 	link->map_fd = map->fd;
15084 
15085 	return &link->link;
15086 }
15087 
15088 struct bpf_link *bpf_map__attach_cgroup_opts(const struct bpf_map *map, int cgroup_fd,
15089 					     const struct bpf_cgroup_opts *opts)
15090 {
15091 	LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
15092 	struct bpf_link_struct_ops *link;
15093 	__u32 relative_id, zero = 0;
15094 	int err, fd, relative_fd;
15095 
15096 	if (!OPTS_VALID(opts, bpf_cgroup_opts))
15097 		return libbpf_err_ptr(-EINVAL);
15098 
15099 	if (!bpf_map__is_struct_ops(map)) {
15100 		pr_warn("map '%s': can't attach non-struct_ops map\n", map->name);
15101 		return libbpf_err_ptr(-EINVAL);
15102 	}
15103 
15104 	if (map->fd < 0) {
15105 		pr_warn("map '%s': can't attach BPF map without FD (was it created?)\n", map->name);
15106 		return libbpf_err_ptr(-EINVAL);
15107 	}
15108 
15109 	if (!(map->def.map_flags & BPF_F_LINK)) {
15110 		pr_warn("map '%s': can't attach to cgroup without BPF_F_LINK\n", map->name);
15111 		return libbpf_err_ptr(-EINVAL);
15112 	}
15113 
15114 	relative_id = OPTS_GET(opts, relative_id, 0);
15115 	relative_fd = OPTS_GET(opts, relative_fd, 0);
15116 
15117 	if (relative_fd && relative_id) {
15118 		pr_warn("map '%s': relative_fd and relative_id cannot be set at the same time\n",
15119 			map->name);
15120 		return libbpf_err_ptr(-EINVAL);
15121 	}
15122 
15123 	link_create_opts.cgroup.expected_revision = OPTS_GET(opts, expected_revision, 0);
15124 	link_create_opts.cgroup.relative_fd = relative_fd;
15125 	link_create_opts.cgroup.relative_id = relative_id;
15126 	link_create_opts.flags = OPTS_GET(opts, flags, 0);
15127 
15128 	link = calloc(1, sizeof(*link));
15129 	if (!link)
15130 		return libbpf_err_ptr(-ENOMEM);
15131 
15132 	err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
15133 	if (err && err != -EBUSY) {
15134 		free(link);
15135 		return libbpf_err_ptr(err);
15136 	}
15137 
15138 	link->link.detach = bpf_link__detach_struct_ops;
15139 
15140 	fd = bpf_link_create(map->fd, cgroup_fd, BPF_STRUCT_OPS, &link_create_opts);
15141 	if (fd < 0) {
15142 		free(link);
15143 		return libbpf_err_ptr(fd);
15144 	}
15145 
15146 	link->link.fd = fd;
15147 	link->map_fd = map->fd;
15148 
15149 	return &link->link;
15150 }
15151 
15152 /*
15153  * Swap the back struct_ops of a link with a new struct_ops map.
15154  */
15155 int bpf_link__update_map(struct bpf_link *link, const struct bpf_map *map)
15156 {
15157 	struct bpf_link_struct_ops *st_ops_link;
15158 	__u32 zero = 0;
15159 	int err;
15160 
15161 	if (!bpf_map__is_struct_ops(map))
15162 		return libbpf_err(-EINVAL);
15163 
15164 	if (map->fd < 0) {
15165 		pr_warn("map '%s': can't use BPF map without FD (was it created?)\n", map->name);
15166 		return libbpf_err(-EINVAL);
15167 	}
15168 
15169 	st_ops_link = container_of(link, struct bpf_link_struct_ops, link);
15170 	/* Ensure the type of a link is correct */
15171 	if (st_ops_link->map_fd < 0)
15172 		return libbpf_err(-EINVAL);
15173 
15174 	err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
15175 	/* It can be EBUSY if the map has been used to create or
15176 	 * update a link before.  We don't allow updating the value of
15177 	 * a struct_ops once it is set.  That ensures that the value
15178 	 * never changed.  So, it is safe to skip EBUSY.
15179 	 */
15180 	if (err && err != -EBUSY)
15181 		return err;
15182 
15183 	err = bpf_link_update(link->fd, map->fd, NULL);
15184 	if (err < 0)
15185 		return err;
15186 
15187 	st_ops_link->map_fd = map->fd;
15188 
15189 	return 0;
15190 }
15191 
15192 typedef enum bpf_perf_event_ret (*bpf_perf_event_print_t)(struct perf_event_header *hdr,
15193 							  void *private_data);
15194 
15195 static enum bpf_perf_event_ret
15196 perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
15197 		       void **copy_mem, size_t *copy_size,
15198 		       bpf_perf_event_print_t fn, void *private_data)
15199 {
15200 	struct perf_event_mmap_page *header = mmap_mem;
15201 	__u64 data_head = ring_buffer_read_head(header);
15202 	__u64 data_tail = header->data_tail;
15203 	void *base = ((__u8 *)header) + page_size;
15204 	int ret = LIBBPF_PERF_EVENT_CONT;
15205 	struct perf_event_header *ehdr;
15206 	size_t ehdr_size;
15207 
15208 	while (data_head != data_tail) {
15209 		ehdr = base + (data_tail & (mmap_size - 1));
15210 		ehdr_size = ehdr->size;
15211 
15212 		if (((void *)ehdr) + ehdr_size > base + mmap_size) {
15213 			void *copy_start = ehdr;
15214 			size_t len_first = base + mmap_size - copy_start;
15215 			size_t len_second = ehdr_size - len_first;
15216 
15217 			if (*copy_size < ehdr_size) {
15218 				free(*copy_mem);
15219 				*copy_mem = malloc(ehdr_size);
15220 				if (!*copy_mem) {
15221 					*copy_size = 0;
15222 					ret = LIBBPF_PERF_EVENT_ERROR;
15223 					break;
15224 				}
15225 				*copy_size = ehdr_size;
15226 			}
15227 
15228 			memcpy(*copy_mem, copy_start, len_first);
15229 			memcpy(*copy_mem + len_first, base, len_second);
15230 			ehdr = *copy_mem;
15231 		}
15232 
15233 		ret = fn(ehdr, private_data);
15234 		data_tail += ehdr_size;
15235 		if (ret != LIBBPF_PERF_EVENT_CONT)
15236 			break;
15237 	}
15238 
15239 	ring_buffer_write_tail(header, data_tail);
15240 	return libbpf_err(ret);
15241 }
15242 
15243 struct perf_buffer;
15244 
15245 struct perf_buffer_params {
15246 	struct perf_event_attr *attr;
15247 	/* if event_cb is specified, it takes precedence */
15248 	perf_buffer_event_fn event_cb;
15249 	/* sample_cb and lost_cb are higher-level common-case callbacks */
15250 	perf_buffer_sample_fn sample_cb;
15251 	perf_buffer_lost_fn lost_cb;
15252 	void *ctx;
15253 	int cpu_cnt;
15254 	int *cpus;
15255 	int *map_keys;
15256 };
15257 
15258 struct perf_cpu_buf {
15259 	struct perf_buffer *pb;
15260 	void *base; /* mmap()'ed memory */
15261 	void *buf; /* for reconstructing segmented data */
15262 	size_t buf_size;
15263 	int fd;
15264 	int cpu;
15265 	int map_key;
15266 };
15267 
15268 struct perf_buffer {
15269 	perf_buffer_event_fn event_cb;
15270 	perf_buffer_sample_fn sample_cb;
15271 	perf_buffer_lost_fn lost_cb;
15272 	void *ctx; /* passed into callbacks */
15273 
15274 	size_t page_size;
15275 	size_t mmap_size;
15276 	struct perf_cpu_buf **cpu_bufs;
15277 	struct epoll_event *events;
15278 	int cpu_cnt; /* number of allocated CPU buffers */
15279 	int epoll_fd; /* perf event FD */
15280 	int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
15281 };
15282 
15283 static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
15284 				      struct perf_cpu_buf *cpu_buf)
15285 {
15286 	if (!cpu_buf)
15287 		return;
15288 	if (cpu_buf->base &&
15289 	    munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
15290 		pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
15291 	if (cpu_buf->fd >= 0) {
15292 		ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
15293 		close(cpu_buf->fd);
15294 	}
15295 	free(cpu_buf->buf);
15296 	free(cpu_buf);
15297 }
15298 
15299 void perf_buffer__free(struct perf_buffer *pb)
15300 {
15301 	int i;
15302 
15303 	if (IS_ERR_OR_NULL(pb))
15304 		return;
15305 	if (pb->cpu_bufs) {
15306 		for (i = 0; i < pb->cpu_cnt; i++) {
15307 			struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
15308 
15309 			if (!cpu_buf)
15310 				continue;
15311 
15312 			bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
15313 			perf_buffer__free_cpu_buf(pb, cpu_buf);
15314 		}
15315 		free(pb->cpu_bufs);
15316 	}
15317 	if (pb->epoll_fd >= 0)
15318 		close(pb->epoll_fd);
15319 	free(pb->events);
15320 	free(pb);
15321 }
15322 
15323 static struct perf_cpu_buf *
15324 perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
15325 			  int cpu, int map_key)
15326 {
15327 	struct perf_cpu_buf *cpu_buf;
15328 	int err;
15329 
15330 	cpu_buf = calloc(1, sizeof(*cpu_buf));
15331 	if (!cpu_buf)
15332 		return ERR_PTR(-ENOMEM);
15333 
15334 	cpu_buf->pb = pb;
15335 	cpu_buf->cpu = cpu;
15336 	cpu_buf->map_key = map_key;
15337 
15338 	cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
15339 			      -1, PERF_FLAG_FD_CLOEXEC);
15340 	if (cpu_buf->fd < 0) {
15341 		err = -errno;
15342 		pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
15343 			cpu, errstr(err));
15344 		goto error;
15345 	}
15346 
15347 	cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
15348 			     PROT_READ | PROT_WRITE, MAP_SHARED,
15349 			     cpu_buf->fd, 0);
15350 	if (cpu_buf->base == MAP_FAILED) {
15351 		cpu_buf->base = NULL;
15352 		err = -errno;
15353 		pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
15354 			cpu, errstr(err));
15355 		goto error;
15356 	}
15357 
15358 	if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
15359 		err = -errno;
15360 		pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
15361 			cpu, errstr(err));
15362 		goto error;
15363 	}
15364 
15365 	return cpu_buf;
15366 
15367 error:
15368 	perf_buffer__free_cpu_buf(pb, cpu_buf);
15369 	return (struct perf_cpu_buf *)ERR_PTR(err);
15370 }
15371 
15372 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
15373 					      struct perf_buffer_params *p);
15374 
15375 struct perf_buffer *perf_buffer__new(int map_fd, size_t page_cnt,
15376 				     perf_buffer_sample_fn sample_cb,
15377 				     perf_buffer_lost_fn lost_cb,
15378 				     void *ctx,
15379 				     const struct perf_buffer_opts *opts)
15380 {
15381 	const size_t attr_sz = sizeof(struct perf_event_attr);
15382 	struct perf_buffer_params p = {};
15383 	struct perf_event_attr attr;
15384 	__u32 sample_period;
15385 
15386 	if (!OPTS_VALID(opts, perf_buffer_opts))
15387 		return libbpf_err_ptr(-EINVAL);
15388 
15389 	sample_period = OPTS_GET(opts, sample_period, 1);
15390 	if (!sample_period)
15391 		sample_period = 1;
15392 
15393 	memset(&attr, 0, attr_sz);
15394 	attr.size = attr_sz;
15395 	attr.config = PERF_COUNT_SW_BPF_OUTPUT;
15396 	attr.type = PERF_TYPE_SOFTWARE;
15397 	attr.sample_type = PERF_SAMPLE_RAW;
15398 	attr.wakeup_events = sample_period;
15399 
15400 	p.attr = &attr;
15401 	p.sample_cb = sample_cb;
15402 	p.lost_cb = lost_cb;
15403 	p.ctx = ctx;
15404 
15405 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
15406 }
15407 
15408 struct perf_buffer *perf_buffer__new_raw(int map_fd, size_t page_cnt,
15409 					 struct perf_event_attr *attr,
15410 					 perf_buffer_event_fn event_cb, void *ctx,
15411 					 const struct perf_buffer_raw_opts *opts)
15412 {
15413 	struct perf_buffer_params p = {};
15414 
15415 	if (!attr)
15416 		return libbpf_err_ptr(-EINVAL);
15417 
15418 	if (!OPTS_VALID(opts, perf_buffer_raw_opts))
15419 		return libbpf_err_ptr(-EINVAL);
15420 
15421 	p.attr = attr;
15422 	p.event_cb = event_cb;
15423 	p.ctx = ctx;
15424 	p.cpu_cnt = OPTS_GET(opts, cpu_cnt, 0);
15425 	p.cpus = OPTS_GET(opts, cpus, NULL);
15426 	p.map_keys = OPTS_GET(opts, map_keys, NULL);
15427 
15428 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
15429 }
15430 
15431 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
15432 					      struct perf_buffer_params *p)
15433 {
15434 	const char *online_cpus_file = "/sys/devices/system/cpu/online";
15435 	struct bpf_map_info map;
15436 	struct perf_buffer *pb;
15437 	bool *online = NULL;
15438 	__u32 map_info_len;
15439 	int err, i, j, n;
15440 
15441 	if (page_cnt == 0 || (page_cnt & (page_cnt - 1))) {
15442 		pr_warn("page count should be power of two, but is %zu\n",
15443 			page_cnt);
15444 		return ERR_PTR(-EINVAL);
15445 	}
15446 
15447 	/* best-effort sanity checks */
15448 	memset(&map, 0, sizeof(map));
15449 	map_info_len = sizeof(map);
15450 	err = bpf_map_get_info_by_fd(map_fd, &map, &map_info_len);
15451 	if (err) {
15452 		err = -errno;
15453 		/* if BPF_OBJ_GET_INFO_BY_FD is supported, will return
15454 		 * -EBADFD, -EFAULT, or -E2BIG on real error
15455 		 */
15456 		if (err != -EINVAL) {
15457 			pr_warn("failed to get map info for map FD %d: %s\n",
15458 				map_fd, errstr(err));
15459 			return ERR_PTR(err);
15460 		}
15461 		pr_debug("failed to get map info for FD %d; API not supported? Ignoring...\n",
15462 			 map_fd);
15463 	} else {
15464 		if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
15465 			pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
15466 				map.name);
15467 			return ERR_PTR(-EINVAL);
15468 		}
15469 	}
15470 
15471 	pb = calloc(1, sizeof(*pb));
15472 	if (!pb)
15473 		return ERR_PTR(-ENOMEM);
15474 
15475 	pb->event_cb = p->event_cb;
15476 	pb->sample_cb = p->sample_cb;
15477 	pb->lost_cb = p->lost_cb;
15478 	pb->ctx = p->ctx;
15479 
15480 	pb->page_size = getpagesize();
15481 	pb->mmap_size = pb->page_size * page_cnt;
15482 	pb->map_fd = map_fd;
15483 
15484 	pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
15485 	if (pb->epoll_fd < 0) {
15486 		err = -errno;
15487 		pr_warn("failed to create epoll instance: %s\n",
15488 			errstr(err));
15489 		goto error;
15490 	}
15491 
15492 	if (p->cpu_cnt > 0) {
15493 		pb->cpu_cnt = p->cpu_cnt;
15494 	} else {
15495 		pb->cpu_cnt = libbpf_num_possible_cpus();
15496 		if (pb->cpu_cnt < 0) {
15497 			err = pb->cpu_cnt;
15498 			goto error;
15499 		}
15500 		if (map.max_entries && map.max_entries < pb->cpu_cnt)
15501 			pb->cpu_cnt = map.max_entries;
15502 	}
15503 
15504 	pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
15505 	if (!pb->events) {
15506 		err = -ENOMEM;
15507 		pr_warn("failed to allocate events: out of memory\n");
15508 		goto error;
15509 	}
15510 	pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
15511 	if (!pb->cpu_bufs) {
15512 		err = -ENOMEM;
15513 		pr_warn("failed to allocate buffers: out of memory\n");
15514 		goto error;
15515 	}
15516 
15517 	err = parse_cpu_mask_file(online_cpus_file, &online, &n);
15518 	if (err) {
15519 		pr_warn("failed to get online CPU mask: %s\n", errstr(err));
15520 		goto error;
15521 	}
15522 
15523 	for (i = 0, j = 0; i < pb->cpu_cnt; i++) {
15524 		struct perf_cpu_buf *cpu_buf;
15525 		int cpu, map_key;
15526 
15527 		cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
15528 		map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
15529 
15530 		/* in case user didn't explicitly requested particular CPUs to
15531 		 * be attached to, skip offline/not present CPUs
15532 		 */
15533 		if (p->cpu_cnt <= 0 && (cpu >= n || !online[cpu]))
15534 			continue;
15535 
15536 		cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
15537 		if (IS_ERR(cpu_buf)) {
15538 			err = PTR_ERR(cpu_buf);
15539 			goto error;
15540 		}
15541 
15542 		pb->cpu_bufs[j] = cpu_buf;
15543 
15544 		err = bpf_map_update_elem(pb->map_fd, &map_key,
15545 					  &cpu_buf->fd, 0);
15546 		if (err) {
15547 			err = -errno;
15548 			pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
15549 				cpu, map_key, cpu_buf->fd,
15550 				errstr(err));
15551 			goto error;
15552 		}
15553 
15554 		pb->events[j].events = EPOLLIN;
15555 		pb->events[j].data.ptr = cpu_buf;
15556 		if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
15557 			      &pb->events[j]) < 0) {
15558 			err = -errno;
15559 			pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
15560 				cpu, cpu_buf->fd,
15561 				errstr(err));
15562 			goto error;
15563 		}
15564 		j++;
15565 	}
15566 	pb->cpu_cnt = j;
15567 	free(online);
15568 
15569 	return pb;
15570 
15571 error:
15572 	free(online);
15573 	if (pb)
15574 		perf_buffer__free(pb);
15575 	return ERR_PTR(err);
15576 }
15577 
15578 struct perf_sample_raw {
15579 	struct perf_event_header header;
15580 	uint32_t size;
15581 	char data[];
15582 };
15583 
15584 struct perf_sample_lost {
15585 	struct perf_event_header header;
15586 	uint64_t id;
15587 	uint64_t lost;
15588 	uint64_t sample_id;
15589 };
15590 
15591 static enum bpf_perf_event_ret
15592 perf_buffer__process_record(struct perf_event_header *e, void *ctx)
15593 {
15594 	struct perf_cpu_buf *cpu_buf = ctx;
15595 	struct perf_buffer *pb = cpu_buf->pb;
15596 	void *data = e;
15597 
15598 	/* user wants full control over parsing perf event */
15599 	if (pb->event_cb)
15600 		return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
15601 
15602 	switch (e->type) {
15603 	case PERF_RECORD_SAMPLE: {
15604 		struct perf_sample_raw *s = data;
15605 
15606 		if (pb->sample_cb)
15607 			pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
15608 		break;
15609 	}
15610 	case PERF_RECORD_LOST: {
15611 		struct perf_sample_lost *s = data;
15612 
15613 		if (pb->lost_cb)
15614 			pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
15615 		break;
15616 	}
15617 	default:
15618 		pr_warn("unknown perf sample type %u\n", e->type);
15619 		return LIBBPF_PERF_EVENT_ERROR;
15620 	}
15621 	return LIBBPF_PERF_EVENT_CONT;
15622 }
15623 
15624 static int perf_buffer__process_records(struct perf_buffer *pb,
15625 					struct perf_cpu_buf *cpu_buf)
15626 {
15627 	enum bpf_perf_event_ret ret;
15628 
15629 	ret = perf_event_read_simple(cpu_buf->base, pb->mmap_size,
15630 				     pb->page_size, &cpu_buf->buf,
15631 				     &cpu_buf->buf_size,
15632 				     perf_buffer__process_record, cpu_buf);
15633 	if (ret != LIBBPF_PERF_EVENT_CONT)
15634 		return ret;
15635 	return 0;
15636 }
15637 
15638 int perf_buffer__epoll_fd(const struct perf_buffer *pb)
15639 {
15640 	return pb->epoll_fd;
15641 }
15642 
15643 int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
15644 {
15645 	int i, cnt, err;
15646 
15647 	cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
15648 	if (cnt < 0)
15649 		return -errno;
15650 
15651 	for (i = 0; i < cnt; i++) {
15652 		struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
15653 
15654 		err = perf_buffer__process_records(pb, cpu_buf);
15655 		if (err) {
15656 			pr_warn("error while processing records: %s\n", errstr(err));
15657 			return libbpf_err(err);
15658 		}
15659 	}
15660 	return cnt;
15661 }
15662 
15663 /* Return number of PERF_EVENT_ARRAY map slots set up by this perf_buffer
15664  * manager.
15665  */
15666 size_t perf_buffer__buffer_cnt(const struct perf_buffer *pb)
15667 {
15668 	return pb->cpu_cnt;
15669 }
15670 
15671 /*
15672  * Return perf_event FD of a ring buffer in *buf_idx* slot of
15673  * PERF_EVENT_ARRAY BPF map. This FD can be polled for new data using
15674  * select()/poll()/epoll() Linux syscalls.
15675  */
15676 int perf_buffer__buffer_fd(const struct perf_buffer *pb, size_t buf_idx)
15677 {
15678 	struct perf_cpu_buf *cpu_buf;
15679 
15680 	if (buf_idx >= pb->cpu_cnt)
15681 		return libbpf_err(-EINVAL);
15682 
15683 	cpu_buf = pb->cpu_bufs[buf_idx];
15684 	if (!cpu_buf)
15685 		return libbpf_err(-ENOENT);
15686 
15687 	return cpu_buf->fd;
15688 }
15689 
15690 int perf_buffer__buffer(struct perf_buffer *pb, int buf_idx, void **buf, size_t *buf_size)
15691 {
15692 	struct perf_cpu_buf *cpu_buf;
15693 
15694 	if (buf_idx >= pb->cpu_cnt)
15695 		return libbpf_err(-EINVAL);
15696 
15697 	cpu_buf = pb->cpu_bufs[buf_idx];
15698 	if (!cpu_buf)
15699 		return libbpf_err(-ENOENT);
15700 
15701 	*buf = cpu_buf->base;
15702 	*buf_size = pb->mmap_size;
15703 	return 0;
15704 }
15705 
15706 /*
15707  * Consume data from perf ring buffer corresponding to slot *buf_idx* in
15708  * PERF_EVENT_ARRAY BPF map without waiting/polling. If there is no data to
15709  * consume, do nothing and return success.
15710  * Returns:
15711  *   - 0 on success;
15712  *   - <0 on failure.
15713  */
15714 int perf_buffer__consume_buffer(struct perf_buffer *pb, size_t buf_idx)
15715 {
15716 	struct perf_cpu_buf *cpu_buf;
15717 
15718 	if (buf_idx >= pb->cpu_cnt)
15719 		return libbpf_err(-EINVAL);
15720 
15721 	cpu_buf = pb->cpu_bufs[buf_idx];
15722 	if (!cpu_buf)
15723 		return libbpf_err(-ENOENT);
15724 
15725 	return perf_buffer__process_records(pb, cpu_buf);
15726 }
15727 
15728 int perf_buffer__consume(struct perf_buffer *pb)
15729 {
15730 	int i, err;
15731 
15732 	for (i = 0; i < pb->cpu_cnt; i++) {
15733 		struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
15734 
15735 		if (!cpu_buf)
15736 			continue;
15737 
15738 		err = perf_buffer__process_records(pb, cpu_buf);
15739 		if (err) {
15740 			pr_warn("perf_buffer: failed to process records in buffer #%d: %s\n",
15741 				i, errstr(err));
15742 			return libbpf_err(err);
15743 		}
15744 	}
15745 	return 0;
15746 }
15747 
15748 int bpf_program__set_attach_target(struct bpf_program *prog,
15749 				   int attach_prog_fd,
15750 				   const char *attach_func_name)
15751 {
15752 	int btf_obj_fd = 0, btf_id = 0, err;
15753 
15754 	if (!prog || attach_prog_fd < 0)
15755 		return libbpf_err(-EINVAL);
15756 
15757 	if (prog->obj->state >= OBJ_LOADED)
15758 		return libbpf_err(-EINVAL);
15759 
15760 	if (attach_prog_fd && !attach_func_name) {
15761 		/* Store attach_prog_fd. The BTF ID will be resolved later during
15762 		 * the normal object/program load phase.
15763 		 */
15764 		prog->attach_prog_fd = attach_prog_fd;
15765 		return 0;
15766 	}
15767 
15768 	if (attach_prog_fd) {
15769 		btf_id = libbpf_find_prog_btf_id(attach_func_name,
15770 						 attach_prog_fd, prog->obj->token_fd);
15771 		if (btf_id < 0)
15772 			return libbpf_err(btf_id);
15773 	} else {
15774 		if (!attach_func_name)
15775 			return libbpf_err(-EINVAL);
15776 
15777 		/* load btf_vmlinux, if not yet */
15778 		err = bpf_object__load_vmlinux_btf(prog->obj, true);
15779 		if (err)
15780 			return libbpf_err(err);
15781 		err = find_kernel_btf_id(prog->obj, attach_func_name,
15782 					 prog->expected_attach_type,
15783 					 &btf_obj_fd, &btf_id);
15784 		if (err)
15785 			return libbpf_err(err);
15786 	}
15787 
15788 	prog->attach_btf_id = btf_id;
15789 	prog->attach_btf_obj_fd = btf_obj_fd;
15790 	prog->attach_prog_fd = attach_prog_fd;
15791 	return 0;
15792 }
15793 
15794 int bpf_program__assoc_struct_ops(struct bpf_program *prog, struct bpf_map *map,
15795 				  struct bpf_prog_assoc_struct_ops_opts *opts)
15796 {
15797 	int prog_fd, map_fd;
15798 
15799 	prog_fd = bpf_program__fd(prog);
15800 	if (prog_fd < 0) {
15801 		pr_warn("prog '%s': can't associate BPF program without FD (was it loaded?)\n",
15802 			prog->name);
15803 		return libbpf_err(-EINVAL);
15804 	}
15805 
15806 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS) {
15807 		pr_warn("prog '%s': can't associate struct_ops program\n", prog->name);
15808 		return libbpf_err(-EINVAL);
15809 	}
15810 
15811 	map_fd = bpf_map__fd(map);
15812 	if (map_fd < 0) {
15813 		pr_warn("map '%s': can't associate BPF map without FD (was it created?)\n", map->name);
15814 		return libbpf_err(-EINVAL);
15815 	}
15816 
15817 	if (!bpf_map__is_struct_ops(map)) {
15818 		pr_warn("map '%s': can't associate non-struct_ops map\n", map->name);
15819 		return libbpf_err(-EINVAL);
15820 	}
15821 
15822 	return bpf_prog_assoc_struct_ops(prog_fd, map_fd, opts);
15823 }
15824 
15825 int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz)
15826 {
15827 	int err = 0, n, len, start, end = -1;
15828 	bool *tmp;
15829 
15830 	*mask = NULL;
15831 	*mask_sz = 0;
15832 
15833 	/* Each sub string separated by ',' has format \d+-\d+ or \d+ */
15834 	while (*s) {
15835 		if (*s == ',' || *s == '\n') {
15836 			s++;
15837 			continue;
15838 		}
15839 		n = sscanf(s, "%d%n-%d%n", &start, &len, &end, &len);
15840 		if (n <= 0 || n > 2) {
15841 			pr_warn("Failed to get CPU range %s: %d\n", s, n);
15842 			err = -EINVAL;
15843 			goto cleanup;
15844 		} else if (n == 1) {
15845 			end = start;
15846 		}
15847 		if (start < 0 || start > end) {
15848 			pr_warn("Invalid CPU range [%d,%d] in %s\n",
15849 				start, end, s);
15850 			err = -EINVAL;
15851 			goto cleanup;
15852 		}
15853 		tmp = realloc(*mask, end + 1);
15854 		if (!tmp) {
15855 			err = -ENOMEM;
15856 			goto cleanup;
15857 		}
15858 		*mask = tmp;
15859 		memset(tmp + *mask_sz, 0, start - *mask_sz);
15860 		memset(tmp + start, 1, end - start + 1);
15861 		*mask_sz = end + 1;
15862 		s += len;
15863 	}
15864 	if (!*mask_sz) {
15865 		pr_warn("Empty CPU range\n");
15866 		return -EINVAL;
15867 	}
15868 	return 0;
15869 cleanup:
15870 	free(*mask);
15871 	*mask = NULL;
15872 	return err;
15873 }
15874 
15875 int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz)
15876 {
15877 	int fd, err = 0, len;
15878 	char buf[128];
15879 
15880 	fd = open(fcpu, O_RDONLY | O_CLOEXEC);
15881 	if (fd < 0) {
15882 		err = -errno;
15883 		pr_warn("Failed to open cpu mask file %s: %s\n", fcpu, errstr(err));
15884 		return err;
15885 	}
15886 	len = read(fd, buf, sizeof(buf));
15887 	close(fd);
15888 	if (len <= 0) {
15889 		err = len ? -errno : -EINVAL;
15890 		pr_warn("Failed to read cpu mask from %s: %s\n", fcpu, errstr(err));
15891 		return err;
15892 	}
15893 	if (len >= sizeof(buf)) {
15894 		pr_warn("CPU mask is too big in file %s\n", fcpu);
15895 		return -E2BIG;
15896 	}
15897 	buf[len] = '\0';
15898 
15899 	return parse_cpu_mask_str(buf, mask, mask_sz);
15900 }
15901 
15902 int libbpf_num_possible_cpus(void)
15903 {
15904 	static const char *fcpu = "/sys/devices/system/cpu/possible";
15905 	static int cpus;
15906 	int err, n, i, tmp_cpus;
15907 	bool *mask;
15908 
15909 	tmp_cpus = READ_ONCE(cpus);
15910 	if (tmp_cpus > 0)
15911 		return tmp_cpus;
15912 
15913 	err = parse_cpu_mask_file(fcpu, &mask, &n);
15914 	if (err)
15915 		return libbpf_err(err);
15916 
15917 	tmp_cpus = 0;
15918 	for (i = 0; i < n; i++) {
15919 		if (mask[i])
15920 			tmp_cpus++;
15921 	}
15922 	free(mask);
15923 
15924 	WRITE_ONCE(cpus, tmp_cpus);
15925 	return tmp_cpus;
15926 }
15927 
15928 static int populate_skeleton_maps(const struct bpf_object *obj,
15929 				  struct bpf_map_skeleton *maps,
15930 				  size_t map_cnt, size_t map_skel_sz)
15931 {
15932 	int i;
15933 
15934 	for (i = 0; i < map_cnt; i++) {
15935 		struct bpf_map_skeleton *map_skel = (void *)maps + i * map_skel_sz;
15936 		struct bpf_map **map = map_skel->map;
15937 		const char *name = map_skel->name;
15938 		void **mmaped = map_skel->mmaped;
15939 
15940 		*map = bpf_object__find_map_by_name(obj, name);
15941 		if (!*map) {
15942 			pr_warn("failed to find skeleton map '%s'\n", name);
15943 			return -ESRCH;
15944 		}
15945 
15946 		/* externs shouldn't be pre-setup from user code */
15947 		if (mmaped && (*map)->libbpf_type != LIBBPF_MAP_KCONFIG)
15948 			*mmaped = (*map)->mmaped;
15949 	}
15950 	return 0;
15951 }
15952 
15953 static int populate_skeleton_progs(const struct bpf_object *obj,
15954 				   struct bpf_prog_skeleton *progs,
15955 				   size_t prog_cnt, size_t prog_skel_sz)
15956 {
15957 	int i;
15958 
15959 	for (i = 0; i < prog_cnt; i++) {
15960 		struct bpf_prog_skeleton *prog_skel = (void *)progs + i * prog_skel_sz;
15961 		struct bpf_program **prog = prog_skel->prog;
15962 		const char *name = prog_skel->name;
15963 
15964 		*prog = bpf_object__find_program_by_name(obj, name);
15965 		if (!*prog) {
15966 			pr_warn("failed to find skeleton program '%s'\n", name);
15967 			return -ESRCH;
15968 		}
15969 	}
15970 	return 0;
15971 }
15972 
15973 int bpf_object__open_skeleton(struct bpf_object_skeleton *s,
15974 			      const struct bpf_object_open_opts *opts)
15975 {
15976 	struct bpf_object *obj;
15977 	int err;
15978 
15979 	obj = bpf_object_open(NULL, s->data, s->data_sz, s->name, opts);
15980 	if (IS_ERR(obj)) {
15981 		err = PTR_ERR(obj);
15982 		pr_warn("failed to initialize skeleton BPF object '%s': %s\n",
15983 			s->name, errstr(err));
15984 		return libbpf_err(err);
15985 	}
15986 
15987 	*s->obj = obj;
15988 	err = populate_skeleton_maps(obj, s->maps, s->map_cnt, s->map_skel_sz);
15989 	if (err) {
15990 		pr_warn("failed to populate skeleton maps for '%s': %s\n", s->name, errstr(err));
15991 		return libbpf_err(err);
15992 	}
15993 
15994 	err = populate_skeleton_progs(obj, s->progs, s->prog_cnt, s->prog_skel_sz);
15995 	if (err) {
15996 		pr_warn("failed to populate skeleton progs for '%s': %s\n", s->name, errstr(err));
15997 		return libbpf_err(err);
15998 	}
15999 
16000 	return 0;
16001 }
16002 
16003 int bpf_object__open_subskeleton(struct bpf_object_subskeleton *s)
16004 {
16005 	int err, len, var_idx, i;
16006 	const char *var_name;
16007 	const struct bpf_map *map;
16008 	struct btf *btf;
16009 	__u32 map_type_id;
16010 	const struct btf_type *map_type, *var_type;
16011 	const struct bpf_var_skeleton *var_skel;
16012 	struct btf_var_secinfo *var;
16013 
16014 	if (!s->obj)
16015 		return libbpf_err(-EINVAL);
16016 
16017 	btf = bpf_object__btf(s->obj);
16018 	if (!btf) {
16019 		pr_warn("subskeletons require BTF at runtime (object %s)\n",
16020 			bpf_object__name(s->obj));
16021 		return libbpf_err(-errno);
16022 	}
16023 
16024 	err = populate_skeleton_maps(s->obj, s->maps, s->map_cnt, s->map_skel_sz);
16025 	if (err) {
16026 		pr_warn("failed to populate subskeleton maps: %s\n", errstr(err));
16027 		return libbpf_err(err);
16028 	}
16029 
16030 	err = populate_skeleton_progs(s->obj, s->progs, s->prog_cnt, s->prog_skel_sz);
16031 	if (err) {
16032 		pr_warn("failed to populate subskeleton maps: %s\n", errstr(err));
16033 		return libbpf_err(err);
16034 	}
16035 
16036 	for (var_idx = 0; var_idx < s->var_cnt; var_idx++) {
16037 		var_skel = (void *)s->vars + var_idx * s->var_skel_sz;
16038 		map = *var_skel->map;
16039 		map_type_id = bpf_map__btf_value_type_id(map);
16040 		map_type = btf__type_by_id(btf, map_type_id);
16041 
16042 		if (!btf_is_datasec(map_type)) {
16043 			pr_warn("type for map '%1$s' is not a datasec: %2$s\n",
16044 				bpf_map__name(map),
16045 				__btf_kind_str(btf_kind(map_type)));
16046 			return libbpf_err(-EINVAL);
16047 		}
16048 
16049 		len = btf_vlen(map_type);
16050 		var = btf_var_secinfos(map_type);
16051 		for (i = 0; i < len; i++, var++) {
16052 			var_type = btf__type_by_id(btf, var->type);
16053 			var_name = btf__name_by_offset(btf, var_type->name_off);
16054 			if (strcmp(var_name, var_skel->name) == 0) {
16055 				*var_skel->addr = map->mmaped + var->offset;
16056 				break;
16057 			}
16058 		}
16059 	}
16060 	return 0;
16061 }
16062 
16063 void bpf_object__destroy_subskeleton(struct bpf_object_subskeleton *s)
16064 {
16065 	if (!s)
16066 		return;
16067 	free(s->maps);
16068 	free(s->progs);
16069 	free(s->vars);
16070 	free(s);
16071 }
16072 
16073 int bpf_object__load_skeleton(struct bpf_object_skeleton *s)
16074 {
16075 	int i, err;
16076 
16077 	err = bpf_object__load(*s->obj);
16078 	if (err) {
16079 		pr_warn("failed to load BPF skeleton '%s': %s\n", s->name, errstr(err));
16080 		return libbpf_err(err);
16081 	}
16082 
16083 	for (i = 0; i < s->map_cnt; i++) {
16084 		struct bpf_map_skeleton *map_skel = (void *)s->maps + i * s->map_skel_sz;
16085 		struct bpf_map *map = *map_skel->map;
16086 
16087 		if (!map_skel->mmaped)
16088 			continue;
16089 
16090 		if (map->def.type == BPF_MAP_TYPE_ARENA)
16091 			*map_skel->mmaped = map->mmaped + map->obj->arena_data_off;
16092 		else
16093 			*map_skel->mmaped = map->mmaped;
16094 	}
16095 
16096 	return 0;
16097 }
16098 
16099 int bpf_object__attach_skeleton(struct bpf_object_skeleton *s)
16100 {
16101 	int i, err;
16102 
16103 	for (i = 0; i < s->prog_cnt; i++) {
16104 		struct bpf_prog_skeleton *prog_skel = (void *)s->progs + i * s->prog_skel_sz;
16105 		struct bpf_program *prog = *prog_skel->prog;
16106 		struct bpf_link **link = prog_skel->link;
16107 
16108 		if (!prog->autoload || !prog->autoattach)
16109 			continue;
16110 
16111 		/* auto-attaching not supported for this program */
16112 		if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
16113 			continue;
16114 
16115 		/* if user already set the link manually, don't attempt auto-attach */
16116 		if (*link)
16117 			continue;
16118 
16119 		err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, link);
16120 		if (err) {
16121 			pr_warn("prog '%s': failed to auto-attach: %s\n",
16122 				bpf_program__name(prog), errstr(err));
16123 			return libbpf_err(err);
16124 		}
16125 
16126 		/* It's possible that for some SEC() definitions auto-attach
16127 		 * is supported in some cases (e.g., if definition completely
16128 		 * specifies target information), but is not in other cases.
16129 		 * SEC("uprobe") is one such case. If user specified target
16130 		 * binary and function name, such BPF program can be
16131 		 * auto-attached. But if not, it shouldn't trigger skeleton's
16132 		 * attach to fail. It should just be skipped.
16133 		 * attach_fn signals such case with returning 0 (no error) and
16134 		 * setting link to NULL.
16135 		 */
16136 	}
16137 
16138 
16139 	for (i = 0; i < s->map_cnt; i++) {
16140 		struct bpf_map_skeleton *map_skel = (void *)s->maps + i * s->map_skel_sz;
16141 		struct bpf_map *map = *map_skel->map;
16142 		struct bpf_link **link;
16143 
16144 		if (!map->autocreate || !map->autoattach)
16145 			continue;
16146 
16147 		/* only struct_ops maps can be attached */
16148 		if (!bpf_map__is_struct_ops(map))
16149 			continue;
16150 
16151 		/* skeleton is created with earlier version of bpftool, notify user */
16152 		if (s->map_skel_sz < offsetofend(struct bpf_map_skeleton, link)) {
16153 			pr_warn("map '%s': BPF skeleton version is old, skipping map auto-attachment...\n",
16154 				bpf_map__name(map));
16155 			continue;
16156 		}
16157 
16158 		link = map_skel->link;
16159 		if (!link) {
16160 			pr_warn("map '%s': BPF map skeleton link is uninitialized\n",
16161 				bpf_map__name(map));
16162 			continue;
16163 		}
16164 
16165 		if (*link)
16166 			continue;
16167 
16168 		*link = bpf_map__attach_struct_ops(map);
16169 		if (!*link) {
16170 			err = -errno;
16171 			pr_warn("map '%s': failed to auto-attach: %s\n",
16172 				bpf_map__name(map), errstr(err));
16173 			return libbpf_err(err);
16174 		}
16175 	}
16176 
16177 	return 0;
16178 }
16179 
16180 void bpf_object__detach_skeleton(struct bpf_object_skeleton *s)
16181 {
16182 	int i;
16183 
16184 	for (i = 0; i < s->prog_cnt; i++) {
16185 		struct bpf_prog_skeleton *prog_skel = (void *)s->progs + i * s->prog_skel_sz;
16186 		struct bpf_link **link = prog_skel->link;
16187 
16188 		bpf_link__destroy(*link);
16189 		*link = NULL;
16190 	}
16191 
16192 	if (s->map_skel_sz < sizeof(struct bpf_map_skeleton))
16193 		return;
16194 
16195 	for (i = 0; i < s->map_cnt; i++) {
16196 		struct bpf_map_skeleton *map_skel = (void *)s->maps + i * s->map_skel_sz;
16197 		struct bpf_link **link = map_skel->link;
16198 
16199 		if (link) {
16200 			bpf_link__destroy(*link);
16201 			*link = NULL;
16202 		}
16203 	}
16204 }
16205 
16206 void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s)
16207 {
16208 	if (!s)
16209 		return;
16210 
16211 	bpf_object__detach_skeleton(s);
16212 	if (s->obj)
16213 		bpf_object__close(*s->obj);
16214 	free(s->maps);
16215 	free(s->progs);
16216 	free(s);
16217 }
16218