xref: /linux/tools/lib/bpf/libbpf.c (revision e3d0dbb3b5e8983d3be780199af1e5134c8a9c17)
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_LSM_MAC]			= "lsm_mac",
119 	[BPF_LSM_CGROUP]		= "lsm_cgroup",
120 	[BPF_SK_LOOKUP]			= "sk_lookup",
121 	[BPF_TRACE_ITER]		= "trace_iter",
122 	[BPF_XDP_DEVMAP]		= "xdp_devmap",
123 	[BPF_XDP_CPUMAP]		= "xdp_cpumap",
124 	[BPF_XDP]			= "xdp",
125 	[BPF_SK_REUSEPORT_SELECT]	= "sk_reuseport_select",
126 	[BPF_SK_REUSEPORT_SELECT_OR_MIGRATE]	= "sk_reuseport_select_or_migrate",
127 	[BPF_PERF_EVENT]		= "perf_event",
128 	[BPF_TRACE_KPROBE_MULTI]	= "trace_kprobe_multi",
129 	[BPF_STRUCT_OPS]		= "struct_ops",
130 	[BPF_NETFILTER]			= "netfilter",
131 	[BPF_TCX_INGRESS]		= "tcx_ingress",
132 	[BPF_TCX_EGRESS]		= "tcx_egress",
133 	[BPF_TRACE_UPROBE_MULTI]	= "trace_uprobe_multi",
134 	[BPF_NETKIT_PRIMARY]		= "netkit_primary",
135 	[BPF_NETKIT_PEER]		= "netkit_peer",
136 	[BPF_TRACE_KPROBE_SESSION]	= "trace_kprobe_session",
137 	[BPF_TRACE_UPROBE_SESSION]	= "trace_uprobe_session",
138 };
139 
140 static const char * const link_type_name[] = {
141 	[BPF_LINK_TYPE_UNSPEC]			= "unspec",
142 	[BPF_LINK_TYPE_RAW_TRACEPOINT]		= "raw_tracepoint",
143 	[BPF_LINK_TYPE_TRACING]			= "tracing",
144 	[BPF_LINK_TYPE_CGROUP]			= "cgroup",
145 	[BPF_LINK_TYPE_ITER]			= "iter",
146 	[BPF_LINK_TYPE_NETNS]			= "netns",
147 	[BPF_LINK_TYPE_XDP]			= "xdp",
148 	[BPF_LINK_TYPE_PERF_EVENT]		= "perf_event",
149 	[BPF_LINK_TYPE_KPROBE_MULTI]		= "kprobe_multi",
150 	[BPF_LINK_TYPE_STRUCT_OPS]		= "struct_ops",
151 	[BPF_LINK_TYPE_NETFILTER]		= "netfilter",
152 	[BPF_LINK_TYPE_TCX]			= "tcx",
153 	[BPF_LINK_TYPE_UPROBE_MULTI]		= "uprobe_multi",
154 	[BPF_LINK_TYPE_NETKIT]			= "netkit",
155 	[BPF_LINK_TYPE_SOCKMAP]			= "sockmap",
156 };
157 
158 static const char * const map_type_name[] = {
159 	[BPF_MAP_TYPE_UNSPEC]			= "unspec",
160 	[BPF_MAP_TYPE_HASH]			= "hash",
161 	[BPF_MAP_TYPE_ARRAY]			= "array",
162 	[BPF_MAP_TYPE_PROG_ARRAY]		= "prog_array",
163 	[BPF_MAP_TYPE_PERF_EVENT_ARRAY]		= "perf_event_array",
164 	[BPF_MAP_TYPE_PERCPU_HASH]		= "percpu_hash",
165 	[BPF_MAP_TYPE_PERCPU_ARRAY]		= "percpu_array",
166 	[BPF_MAP_TYPE_STACK_TRACE]		= "stack_trace",
167 	[BPF_MAP_TYPE_CGROUP_ARRAY]		= "cgroup_array",
168 	[BPF_MAP_TYPE_LRU_HASH]			= "lru_hash",
169 	[BPF_MAP_TYPE_LRU_PERCPU_HASH]		= "lru_percpu_hash",
170 	[BPF_MAP_TYPE_LPM_TRIE]			= "lpm_trie",
171 	[BPF_MAP_TYPE_ARRAY_OF_MAPS]		= "array_of_maps",
172 	[BPF_MAP_TYPE_HASH_OF_MAPS]		= "hash_of_maps",
173 	[BPF_MAP_TYPE_DEVMAP]			= "devmap",
174 	[BPF_MAP_TYPE_DEVMAP_HASH]		= "devmap_hash",
175 	[BPF_MAP_TYPE_SOCKMAP]			= "sockmap",
176 	[BPF_MAP_TYPE_CPUMAP]			= "cpumap",
177 	[BPF_MAP_TYPE_XSKMAP]			= "xskmap",
178 	[BPF_MAP_TYPE_SOCKHASH]			= "sockhash",
179 	[BPF_MAP_TYPE_CGROUP_STORAGE]		= "cgroup_storage",
180 	[BPF_MAP_TYPE_REUSEPORT_SOCKARRAY]	= "reuseport_sockarray",
181 	[BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE]	= "percpu_cgroup_storage",
182 	[BPF_MAP_TYPE_QUEUE]			= "queue",
183 	[BPF_MAP_TYPE_STACK]			= "stack",
184 	[BPF_MAP_TYPE_SK_STORAGE]		= "sk_storage",
185 	[BPF_MAP_TYPE_STRUCT_OPS]		= "struct_ops",
186 	[BPF_MAP_TYPE_RINGBUF]			= "ringbuf",
187 	[BPF_MAP_TYPE_INODE_STORAGE]		= "inode_storage",
188 	[BPF_MAP_TYPE_TASK_STORAGE]		= "task_storage",
189 	[BPF_MAP_TYPE_BLOOM_FILTER]		= "bloom_filter",
190 	[BPF_MAP_TYPE_USER_RINGBUF]             = "user_ringbuf",
191 	[BPF_MAP_TYPE_CGRP_STORAGE]		= "cgrp_storage",
192 	[BPF_MAP_TYPE_ARENA]			= "arena",
193 	[BPF_MAP_TYPE_INSN_ARRAY]		= "insn_array",
194 };
195 
196 static const char * const prog_type_name[] = {
197 	[BPF_PROG_TYPE_UNSPEC]			= "unspec",
198 	[BPF_PROG_TYPE_SOCKET_FILTER]		= "socket_filter",
199 	[BPF_PROG_TYPE_KPROBE]			= "kprobe",
200 	[BPF_PROG_TYPE_SCHED_CLS]		= "sched_cls",
201 	[BPF_PROG_TYPE_SCHED_ACT]		= "sched_act",
202 	[BPF_PROG_TYPE_TRACEPOINT]		= "tracepoint",
203 	[BPF_PROG_TYPE_XDP]			= "xdp",
204 	[BPF_PROG_TYPE_PERF_EVENT]		= "perf_event",
205 	[BPF_PROG_TYPE_CGROUP_SKB]		= "cgroup_skb",
206 	[BPF_PROG_TYPE_CGROUP_SOCK]		= "cgroup_sock",
207 	[BPF_PROG_TYPE_LWT_IN]			= "lwt_in",
208 	[BPF_PROG_TYPE_LWT_OUT]			= "lwt_out",
209 	[BPF_PROG_TYPE_LWT_XMIT]		= "lwt_xmit",
210 	[BPF_PROG_TYPE_SOCK_OPS]		= "sock_ops",
211 	[BPF_PROG_TYPE_SK_SKB]			= "sk_skb",
212 	[BPF_PROG_TYPE_CGROUP_DEVICE]		= "cgroup_device",
213 	[BPF_PROG_TYPE_SK_MSG]			= "sk_msg",
214 	[BPF_PROG_TYPE_RAW_TRACEPOINT]		= "raw_tracepoint",
215 	[BPF_PROG_TYPE_CGROUP_SOCK_ADDR]	= "cgroup_sock_addr",
216 	[BPF_PROG_TYPE_LWT_SEG6LOCAL]		= "lwt_seg6local",
217 	[BPF_PROG_TYPE_LIRC_MODE2]		= "lirc_mode2",
218 	[BPF_PROG_TYPE_SK_REUSEPORT]		= "sk_reuseport",
219 	[BPF_PROG_TYPE_FLOW_DISSECTOR]		= "flow_dissector",
220 	[BPF_PROG_TYPE_CGROUP_SYSCTL]		= "cgroup_sysctl",
221 	[BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE]	= "raw_tracepoint_writable",
222 	[BPF_PROG_TYPE_CGROUP_SOCKOPT]		= "cgroup_sockopt",
223 	[BPF_PROG_TYPE_TRACING]			= "tracing",
224 	[BPF_PROG_TYPE_STRUCT_OPS]		= "struct_ops",
225 	[BPF_PROG_TYPE_EXT]			= "ext",
226 	[BPF_PROG_TYPE_LSM]			= "lsm",
227 	[BPF_PROG_TYPE_SK_LOOKUP]		= "sk_lookup",
228 	[BPF_PROG_TYPE_SYSCALL]			= "syscall",
229 	[BPF_PROG_TYPE_NETFILTER]		= "netfilter",
230 };
231 
232 static int __base_pr(enum libbpf_print_level level, const char *format,
233 		     va_list args)
234 {
235 	const char *env_var = "LIBBPF_LOG_LEVEL";
236 	static enum libbpf_print_level min_level = LIBBPF_INFO;
237 	static bool initialized;
238 
239 	if (!initialized) {
240 		char *verbosity;
241 
242 		initialized = true;
243 		verbosity = getenv(env_var);
244 		if (verbosity) {
245 			if (strcasecmp(verbosity, "warn") == 0)
246 				min_level = LIBBPF_WARN;
247 			else if (strcasecmp(verbosity, "debug") == 0)
248 				min_level = LIBBPF_DEBUG;
249 			else if (strcasecmp(verbosity, "info") == 0)
250 				min_level = LIBBPF_INFO;
251 			else
252 				fprintf(stderr, "libbpf: unrecognized '%s' envvar value: '%s', should be one of 'warn', 'debug', or 'info'.\n",
253 					env_var, verbosity);
254 		}
255 	}
256 
257 	/* if too verbose, skip logging  */
258 	if (level > min_level)
259 		return 0;
260 
261 	return vfprintf(stderr, format, args);
262 }
263 
264 static libbpf_print_fn_t __libbpf_pr = __base_pr;
265 
266 libbpf_print_fn_t libbpf_set_print(libbpf_print_fn_t fn)
267 {
268 	libbpf_print_fn_t old_print_fn;
269 
270 	old_print_fn = __atomic_exchange_n(&__libbpf_pr, fn, __ATOMIC_RELAXED);
271 
272 	return old_print_fn;
273 }
274 
275 __printf(2, 3)
276 void libbpf_print(enum libbpf_print_level level, const char *format, ...)
277 {
278 	va_list args;
279 	int old_errno;
280 	libbpf_print_fn_t print_fn;
281 
282 	print_fn = __atomic_load_n(&__libbpf_pr, __ATOMIC_RELAXED);
283 	if (!print_fn)
284 		return;
285 
286 	old_errno = errno;
287 
288 	va_start(args, format);
289 	print_fn(level, format, args);
290 	va_end(args);
291 
292 	errno = old_errno;
293 }
294 
295 static void pr_perm_msg(int err)
296 {
297 	struct rlimit limit;
298 	char buf[100];
299 
300 	if (err != -EPERM || geteuid() != 0)
301 		return;
302 
303 	err = getrlimit(RLIMIT_MEMLOCK, &limit);
304 	if (err)
305 		return;
306 
307 	if (limit.rlim_cur == RLIM_INFINITY)
308 		return;
309 
310 	if (limit.rlim_cur < 1024)
311 		snprintf(buf, sizeof(buf), "%zu bytes", (size_t)limit.rlim_cur);
312 	else if (limit.rlim_cur < 1024*1024)
313 		snprintf(buf, sizeof(buf), "%.1f KiB", (double)limit.rlim_cur / 1024);
314 	else
315 		snprintf(buf, sizeof(buf), "%.1f MiB", (double)limit.rlim_cur / (1024*1024));
316 
317 	pr_warn("permission error while running as root; try raising 'ulimit -l'? current value: %s\n",
318 		buf);
319 }
320 
321 /* Copied from tools/perf/util/util.h */
322 #ifndef zfree
323 # define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
324 #endif
325 
326 #ifndef zclose
327 # define zclose(fd) ({			\
328 	int ___err = 0;			\
329 	if ((fd) >= 0)			\
330 		___err = close((fd));	\
331 	fd = -1;			\
332 	___err; })
333 #endif
334 
335 static inline __u64 ptr_to_u64(const void *ptr)
336 {
337 	return (__u64) (unsigned long) ptr;
338 }
339 
340 int libbpf_set_strict_mode(enum libbpf_strict_mode mode)
341 {
342 	/* as of v1.0 libbpf_set_strict_mode() is a no-op */
343 	return 0;
344 }
345 
346 __u32 libbpf_major_version(void)
347 {
348 	return LIBBPF_MAJOR_VERSION;
349 }
350 
351 __u32 libbpf_minor_version(void)
352 {
353 	return LIBBPF_MINOR_VERSION;
354 }
355 
356 const char *libbpf_version_string(void)
357 {
358 #define __S(X) #X
359 #define _S(X) __S(X)
360 	return  "v" _S(LIBBPF_MAJOR_VERSION) "." _S(LIBBPF_MINOR_VERSION);
361 #undef _S
362 #undef __S
363 }
364 
365 enum reloc_type {
366 	RELO_LD64,
367 	RELO_CALL,
368 	RELO_DATA,
369 	RELO_EXTERN_LD64,
370 	RELO_EXTERN_CALL,
371 	RELO_SUBPROG_ADDR,
372 	RELO_CORE,
373 	RELO_INSN_ARRAY,
374 };
375 
376 struct reloc_desc {
377 	enum reloc_type type;
378 	int insn_idx;
379 	union {
380 		const struct bpf_core_relo *core_relo; /* used when type == RELO_CORE */
381 		struct {
382 			int map_idx;
383 			unsigned int sym_off;
384 			/*
385 			 * The following two fields can be unionized, as the
386 			 * ext_idx field is used for extern symbols, and the
387 			 * sym_size is used for jump tables, which are never
388 			 * extern
389 			 */
390 			union {
391 				int ext_idx;
392 				int sym_size;
393 			};
394 		};
395 	};
396 };
397 
398 /* stored as sec_def->cookie for all libbpf-supported SEC()s */
399 enum sec_def_flags {
400 	SEC_NONE = 0,
401 	/* expected_attach_type is optional, if kernel doesn't support that */
402 	SEC_EXP_ATTACH_OPT = 1,
403 	/* legacy, only used by libbpf_get_type_names() and
404 	 * libbpf_attach_type_by_name(), not used by libbpf itself at all.
405 	 * This used to be associated with cgroup (and few other) BPF programs
406 	 * that were attachable through BPF_PROG_ATTACH command. Pretty
407 	 * meaningless nowadays, though.
408 	 */
409 	SEC_ATTACHABLE = 2,
410 	SEC_ATTACHABLE_OPT = SEC_ATTACHABLE | SEC_EXP_ATTACH_OPT,
411 	/* attachment target is specified through BTF ID in either kernel or
412 	 * other BPF program's BTF object
413 	 */
414 	SEC_ATTACH_BTF = 4,
415 	/* BPF program type allows sleeping/blocking in kernel */
416 	SEC_SLEEPABLE = 8,
417 	/* BPF program support non-linear XDP buffer */
418 	SEC_XDP_FRAGS = 16,
419 	/* Setup proper attach type for usdt probes. */
420 	SEC_USDT = 32,
421 };
422 
423 struct bpf_sec_def {
424 	char *sec;
425 	enum bpf_prog_type prog_type;
426 	enum bpf_attach_type expected_attach_type;
427 	long cookie;
428 	int handler_id;
429 
430 	libbpf_prog_setup_fn_t prog_setup_fn;
431 	libbpf_prog_prepare_load_fn_t prog_prepare_load_fn;
432 	libbpf_prog_attach_fn_t prog_attach_fn;
433 };
434 
435 struct bpf_light_subprog {
436 	__u32 sec_insn_off;
437 	__u32 sub_insn_off;
438 };
439 
440 /*
441  * bpf_prog should be a better name but it has been used in
442  * linux/filter.h.
443  */
444 struct bpf_program {
445 	char *name;
446 	char *sec_name;
447 	size_t sec_idx;
448 	const struct bpf_sec_def *sec_def;
449 	/* this program's instruction offset (in number of instructions)
450 	 * within its containing ELF section
451 	 */
452 	size_t sec_insn_off;
453 	/* number of original instructions in ELF section belonging to this
454 	 * program, not taking into account subprogram instructions possible
455 	 * appended later during relocation
456 	 */
457 	size_t sec_insn_cnt;
458 	/* Offset (in number of instructions) of the start of instruction
459 	 * belonging to this BPF program  within its containing main BPF
460 	 * program. For the entry-point (main) BPF program, this is always
461 	 * zero. For a sub-program, this gets reset before each of main BPF
462 	 * programs are processed and relocated and is used to determined
463 	 * whether sub-program was already appended to the main program, and
464 	 * if yes, at which instruction offset.
465 	 */
466 	size_t sub_insn_off;
467 
468 	/* instructions that belong to BPF program; insns[0] is located at
469 	 * sec_insn_off instruction within its ELF section in ELF file, so
470 	 * when mapping ELF file instruction index to the local instruction,
471 	 * one needs to subtract sec_insn_off; and vice versa.
472 	 */
473 	struct bpf_insn *insns;
474 	/* actual number of instruction in this BPF program's image; for
475 	 * entry-point BPF programs this includes the size of main program
476 	 * itself plus all the used sub-programs, appended at the end
477 	 */
478 	size_t insns_cnt;
479 
480 	struct reloc_desc *reloc_desc;
481 	int nr_reloc;
482 
483 	/* BPF verifier log settings */
484 	char *log_buf;
485 	size_t log_size;
486 	__u32 log_level;
487 
488 	struct bpf_object *obj;
489 
490 	int fd;
491 	bool autoload;
492 	bool autoattach;
493 	bool sym_global;
494 	bool mark_btf_static;
495 	enum bpf_prog_type type;
496 	enum bpf_attach_type expected_attach_type;
497 	int exception_cb_idx;
498 
499 	int prog_ifindex;
500 	__u32 attach_btf_obj_fd;
501 	__u32 attach_btf_id;
502 	__u32 attach_prog_fd;
503 
504 	void *func_info;
505 	__u32 func_info_rec_size;
506 	__u32 func_info_cnt;
507 
508 	void *line_info;
509 	__u32 line_info_rec_size;
510 	__u32 line_info_cnt;
511 	__u32 prog_flags;
512 	__u8  hash[SHA256_DIGEST_LENGTH];
513 
514 	struct bpf_light_subprog *subprogs;
515 	__u32 subprog_cnt;
516 };
517 
518 struct bpf_struct_ops {
519 	struct bpf_program **progs;
520 	__u32 *kern_func_off;
521 	/* e.g. struct tcp_congestion_ops in bpf_prog's btf format */
522 	void *data;
523 	/* e.g. struct bpf_struct_ops_tcp_congestion_ops in
524 	 *      btf_vmlinux's format.
525 	 * struct bpf_struct_ops_tcp_congestion_ops {
526 	 *	[... some other kernel fields ...]
527 	 *	struct tcp_congestion_ops data;
528 	 * }
529 	 * kern_vdata-size == sizeof(struct bpf_struct_ops_tcp_congestion_ops)
530 	 * bpf_map__init_kern_struct_ops() will populate the "kern_vdata"
531 	 * from "data".
532 	 */
533 	void *kern_vdata;
534 	__u32 type_id;
535 };
536 
537 #define DATA_SEC ".data"
538 #define BSS_SEC ".bss"
539 #define RODATA_SEC ".rodata"
540 #define KCONFIG_SEC ".kconfig"
541 #define KSYMS_SEC ".ksyms"
542 #define STRUCT_OPS_SEC ".struct_ops"
543 #define STRUCT_OPS_LINK_SEC ".struct_ops.link"
544 #define ARENA_SEC ".addr_space.1"
545 
546 enum libbpf_map_type {
547 	LIBBPF_MAP_UNSPEC,
548 	LIBBPF_MAP_DATA,
549 	LIBBPF_MAP_BSS,
550 	LIBBPF_MAP_RODATA,
551 	LIBBPF_MAP_KCONFIG,
552 };
553 
554 struct bpf_map_def {
555 	unsigned int type;
556 	unsigned int key_size;
557 	unsigned int value_size;
558 	unsigned int max_entries;
559 	unsigned int map_flags;
560 };
561 
562 struct bpf_map {
563 	struct bpf_object *obj;
564 	char *name;
565 	/* real_name is defined for special internal maps (.rodata*,
566 	 * .data*, .bss, .kconfig) and preserves their original ELF section
567 	 * name. This is important to be able to find corresponding BTF
568 	 * DATASEC information.
569 	 */
570 	char *real_name;
571 	int fd;
572 	int sec_idx;
573 	size_t sec_offset;
574 	int map_ifindex;
575 	int inner_map_fd;
576 	struct bpf_map_def def;
577 	__u32 numa_node;
578 	__u32 btf_var_idx;
579 	int mod_btf_fd;
580 	__u32 btf_key_type_id;
581 	__u32 btf_value_type_id;
582 	__u32 btf_vmlinux_value_type_id;
583 	enum libbpf_map_type libbpf_type;
584 	void *mmaped;
585 	struct bpf_struct_ops *st_ops;
586 	struct bpf_map *inner_map;
587 	void **init_slots;
588 	int init_slots_sz;
589 	char *pin_path;
590 	bool pinned;
591 	bool reused;
592 	bool autocreate;
593 	bool autoattach;
594 	__u64 map_extra;
595 	struct bpf_program *excl_prog;
596 };
597 
598 enum extern_type {
599 	EXT_UNKNOWN,
600 	EXT_KCFG,
601 	EXT_KSYM,
602 };
603 
604 enum kcfg_type {
605 	KCFG_UNKNOWN,
606 	KCFG_CHAR,
607 	KCFG_BOOL,
608 	KCFG_INT,
609 	KCFG_TRISTATE,
610 	KCFG_CHAR_ARR,
611 };
612 
613 struct extern_desc {
614 	enum extern_type type;
615 	int sym_idx;
616 	int btf_id;
617 	int sec_btf_id;
618 	char *name;
619 	char *essent_name;
620 	bool is_set;
621 	bool is_weak;
622 	union {
623 		struct {
624 			enum kcfg_type type;
625 			int sz;
626 			int align;
627 			int data_off;
628 			bool is_signed;
629 		} kcfg;
630 		struct {
631 			unsigned long long addr;
632 
633 			/* target btf_id of the corresponding kernel var. */
634 			int kernel_btf_obj_fd;
635 			int kernel_btf_id;
636 
637 			/* local btf_id of the ksym extern's type. */
638 			__u32 type_id;
639 			/* BTF fd index to be patched in for insn->off, this is
640 			 * 0 for vmlinux BTF, index in obj->fd_array for module
641 			 * BTF
642 			 */
643 			__s16 btf_fd_idx;
644 		} ksym;
645 	};
646 };
647 
648 struct module_btf {
649 	struct btf *btf;
650 	char *name;
651 	__u32 id;
652 	int fd;
653 	int fd_array_idx;
654 };
655 
656 enum sec_type {
657 	SEC_UNUSED = 0,
658 	SEC_RELO,
659 	SEC_BSS,
660 	SEC_DATA,
661 	SEC_RODATA,
662 	SEC_ST_OPS,
663 };
664 
665 struct elf_sec_desc {
666 	enum sec_type sec_type;
667 	Elf64_Shdr *shdr;
668 	Elf_Data *data;
669 };
670 
671 struct elf_state {
672 	int fd;
673 	const void *obj_buf;
674 	size_t obj_buf_sz;
675 	Elf *elf;
676 	Elf64_Ehdr *ehdr;
677 	Elf_Data *symbols;
678 	Elf_Data *arena_data;
679 	size_t shstrndx; /* section index for section name strings */
680 	size_t strtabidx;
681 	struct elf_sec_desc *secs;
682 	size_t sec_cnt;
683 	int btf_maps_shndx;
684 	__u32 btf_maps_sec_btf_id;
685 	int text_shndx;
686 	int symbols_shndx;
687 	bool has_st_ops;
688 	int arena_data_shndx;
689 	int jumptables_data_shndx;
690 };
691 
692 struct usdt_manager;
693 
694 enum bpf_object_state {
695 	OBJ_OPEN,
696 	OBJ_PREPARED,
697 	OBJ_LOADED,
698 };
699 
700 struct bpf_object {
701 	char name[BPF_OBJ_NAME_LEN];
702 	char license[64];
703 	__u32 kern_version;
704 
705 	enum bpf_object_state state;
706 	struct bpf_program *programs;
707 	size_t nr_programs;
708 	struct bpf_map *maps;
709 	size_t nr_maps;
710 	size_t maps_cap;
711 
712 	char *kconfig;
713 	struct extern_desc *externs;
714 	int nr_extern;
715 	int kconfig_map_idx;
716 
717 	bool has_subcalls;
718 	bool has_rodata;
719 
720 	struct bpf_gen *gen_loader;
721 
722 	/* Information when doing ELF related work. Only valid if efile.elf is not NULL */
723 	struct elf_state efile;
724 
725 	unsigned char byteorder;
726 
727 	struct btf *btf;
728 	struct btf_ext *btf_ext;
729 
730 	/* Parse and load BTF vmlinux if any of the programs in the object need
731 	 * it at load time.
732 	 */
733 	struct btf *btf_vmlinux;
734 	/* Path to the custom BTF to be used for BPF CO-RE relocations as an
735 	 * override for vmlinux BTF.
736 	 */
737 	char *btf_custom_path;
738 	/* vmlinux BTF override for CO-RE relocations */
739 	struct btf *btf_vmlinux_override;
740 	/* Lazily initialized kernel module BTFs */
741 	struct module_btf *btf_modules;
742 	bool btf_modules_loaded;
743 	size_t btf_module_cnt;
744 	size_t btf_module_cap;
745 
746 	/* optional log settings passed to BPF_BTF_LOAD and BPF_PROG_LOAD commands */
747 	char *log_buf;
748 	size_t log_size;
749 	__u32 log_level;
750 
751 	int *fd_array;
752 	size_t fd_array_cap;
753 	size_t fd_array_cnt;
754 
755 	struct usdt_manager *usdt_man;
756 
757 	int arena_map_idx;
758 	void *arena_data;
759 	size_t arena_data_sz;
760 	size_t arena_data_off;
761 
762 	void *jumptables_data;
763 	size_t jumptables_data_sz;
764 
765 	struct {
766 		struct bpf_program *prog;
767 		unsigned int sym_off;
768 		int fd;
769 	} *jumptable_maps;
770 	size_t jumptable_map_cnt;
771 
772 	struct kern_feature_cache *feat_cache;
773 	char *token_path;
774 	int token_fd;
775 
776 	char path[];
777 };
778 
779 static const char *elf_sym_str(const struct bpf_object *obj, size_t off);
780 static const char *elf_sec_str(const struct bpf_object *obj, size_t off);
781 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx);
782 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name);
783 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn);
784 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn);
785 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn);
786 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx);
787 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx);
788 
789 void bpf_program__unload(struct bpf_program *prog)
790 {
791 	if (!prog)
792 		return;
793 
794 	zclose(prog->fd);
795 
796 	zfree(&prog->func_info);
797 	zfree(&prog->line_info);
798 	zfree(&prog->subprogs);
799 }
800 
801 static void bpf_program__exit(struct bpf_program *prog)
802 {
803 	if (!prog)
804 		return;
805 
806 	bpf_program__unload(prog);
807 	zfree(&prog->name);
808 	zfree(&prog->sec_name);
809 	zfree(&prog->insns);
810 	zfree(&prog->reloc_desc);
811 
812 	prog->nr_reloc = 0;
813 	prog->insns_cnt = 0;
814 	prog->sec_idx = -1;
815 }
816 
817 static bool insn_is_subprog_call(const struct bpf_insn *insn)
818 {
819 	return BPF_CLASS(insn->code) == BPF_JMP &&
820 	       BPF_OP(insn->code) == BPF_CALL &&
821 	       BPF_SRC(insn->code) == BPF_K &&
822 	       insn->src_reg == BPF_PSEUDO_CALL &&
823 	       insn->dst_reg == 0 &&
824 	       insn->off == 0;
825 }
826 
827 static bool is_call_insn(const struct bpf_insn *insn)
828 {
829 	return insn->code == (BPF_JMP | BPF_CALL);
830 }
831 
832 static bool insn_is_pseudo_func(struct bpf_insn *insn)
833 {
834 	return is_ldimm64_insn(insn) && insn->src_reg == BPF_PSEUDO_FUNC;
835 }
836 
837 static int
838 bpf_object__init_prog(struct bpf_object *obj, struct bpf_program *prog,
839 		      const char *name, size_t sec_idx, const char *sec_name,
840 		      size_t sec_off, void *insn_data, size_t insn_data_sz)
841 {
842 	if (insn_data_sz == 0 || insn_data_sz % BPF_INSN_SZ || sec_off % BPF_INSN_SZ) {
843 		pr_warn("sec '%s': corrupted program '%s', offset %zu, size %zu\n",
844 			sec_name, name, sec_off, insn_data_sz);
845 		return -EINVAL;
846 	}
847 
848 	memset(prog, 0, sizeof(*prog));
849 	prog->obj = obj;
850 
851 	prog->sec_idx = sec_idx;
852 	prog->sec_insn_off = sec_off / BPF_INSN_SZ;
853 	prog->sec_insn_cnt = insn_data_sz / BPF_INSN_SZ;
854 	/* insns_cnt can later be increased by appending used subprograms */
855 	prog->insns_cnt = prog->sec_insn_cnt;
856 
857 	prog->type = BPF_PROG_TYPE_UNSPEC;
858 	prog->fd = -1;
859 	prog->exception_cb_idx = -1;
860 
861 	/* libbpf's convention for SEC("?abc...") is that it's just like
862 	 * SEC("abc...") but the corresponding bpf_program starts out with
863 	 * autoload set to false.
864 	 */
865 	if (sec_name[0] == '?') {
866 		prog->autoload = false;
867 		/* from now on forget there was ? in section name */
868 		sec_name++;
869 	} else {
870 		prog->autoload = true;
871 	}
872 
873 	prog->autoattach = true;
874 
875 	/* inherit object's log_level */
876 	prog->log_level = obj->log_level;
877 
878 	prog->sec_name = strdup(sec_name);
879 	if (!prog->sec_name)
880 		goto errout;
881 
882 	prog->name = strdup(name);
883 	if (!prog->name)
884 		goto errout;
885 
886 	prog->insns = malloc(insn_data_sz);
887 	if (!prog->insns)
888 		goto errout;
889 	memcpy(prog->insns, insn_data, insn_data_sz);
890 
891 	return 0;
892 errout:
893 	pr_warn("sec '%s': failed to allocate memory for prog '%s'\n", sec_name, name);
894 	bpf_program__exit(prog);
895 	return -ENOMEM;
896 }
897 
898 static int
899 bpf_object__add_programs(struct bpf_object *obj, Elf_Data *sec_data,
900 			 const char *sec_name, int sec_idx)
901 {
902 	Elf_Data *symbols = obj->efile.symbols;
903 	struct bpf_program *prog, *progs;
904 	void *data = sec_data->d_buf;
905 	size_t sec_sz = sec_data->d_size, sec_off, prog_sz, nr_syms;
906 	int nr_progs, err, i;
907 	const char *name;
908 	Elf64_Sym *sym;
909 
910 	progs = obj->programs;
911 	nr_progs = obj->nr_programs;
912 	nr_syms = symbols->d_size / sizeof(Elf64_Sym);
913 
914 	for (i = 0; i < nr_syms; i++) {
915 		sym = elf_sym_by_idx(obj, i);
916 
917 		if (sym->st_shndx != sec_idx)
918 			continue;
919 		if (ELF64_ST_TYPE(sym->st_info) != STT_FUNC)
920 			continue;
921 
922 		prog_sz = sym->st_size;
923 		sec_off = sym->st_value;
924 
925 		name = elf_sym_str(obj, sym->st_name);
926 		if (!name) {
927 			pr_warn("sec '%s': failed to get symbol name for offset %zu\n",
928 				sec_name, sec_off);
929 			return -LIBBPF_ERRNO__FORMAT;
930 		}
931 
932 		if (sec_off + prog_sz > sec_sz || sec_off + prog_sz < sec_off) {
933 			pr_warn("sec '%s': program at offset %zu crosses section boundary\n",
934 				sec_name, sec_off);
935 			return -LIBBPF_ERRNO__FORMAT;
936 		}
937 
938 		if (sec_idx != obj->efile.text_shndx && ELF64_ST_BIND(sym->st_info) == STB_LOCAL) {
939 			pr_warn("sec '%s': program '%s' is static and not supported\n", sec_name, name);
940 			return -ENOTSUP;
941 		}
942 
943 		pr_debug("sec '%s': found program '%s' at insn offset %zu (%zu bytes), code size %zu insns (%zu bytes)\n",
944 			 sec_name, name, sec_off / BPF_INSN_SZ, sec_off, prog_sz / BPF_INSN_SZ, prog_sz);
945 
946 		progs = libbpf_reallocarray(progs, nr_progs + 1, sizeof(*progs));
947 		if (!progs) {
948 			/*
949 			 * In this case the original obj->programs
950 			 * is still valid, so don't need special treat for
951 			 * bpf_close_object().
952 			 */
953 			pr_warn("sec '%s': failed to alloc memory for new program '%s'\n",
954 				sec_name, name);
955 			return -ENOMEM;
956 		}
957 		obj->programs = progs;
958 
959 		prog = &progs[nr_progs];
960 
961 		err = bpf_object__init_prog(obj, prog, name, sec_idx, sec_name,
962 					    sec_off, data + sec_off, prog_sz);
963 		if (err)
964 			return err;
965 
966 		if (ELF64_ST_BIND(sym->st_info) != STB_LOCAL)
967 			prog->sym_global = true;
968 
969 		/* if function is a global/weak symbol, but has restricted
970 		 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF FUNC
971 		 * as static to enable more permissive BPF verification mode
972 		 * with more outside context available to BPF verifier
973 		 */
974 		if (prog->sym_global && (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
975 		    || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL))
976 			prog->mark_btf_static = true;
977 
978 		nr_progs++;
979 		obj->nr_programs = nr_progs;
980 	}
981 
982 	return 0;
983 }
984 
985 static void bpf_object_bswap_progs(struct bpf_object *obj)
986 {
987 	struct bpf_program *prog = obj->programs;
988 	struct bpf_insn *insn;
989 	int p, i;
990 
991 	for (p = 0; p < obj->nr_programs; p++, prog++) {
992 		insn = prog->insns;
993 		for (i = 0; i < prog->insns_cnt; i++, insn++)
994 			bpf_insn_bswap(insn);
995 	}
996 	pr_debug("converted %zu BPF programs to native byte order\n", obj->nr_programs);
997 }
998 
999 static const struct btf_member *
1000 find_member_by_offset(const struct btf_type *t, __u32 bit_offset)
1001 {
1002 	struct btf_member *m;
1003 	int i;
1004 
1005 	for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
1006 		if (btf_member_bit_offset(t, i) == bit_offset)
1007 			return m;
1008 	}
1009 
1010 	return NULL;
1011 }
1012 
1013 static const struct btf_member *
1014 find_member_by_name(const struct btf *btf, const struct btf_type *t,
1015 		    const char *name)
1016 {
1017 	struct btf_member *m;
1018 	int i;
1019 
1020 	for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
1021 		if (!strcmp(btf__name_by_offset(btf, m->name_off), name))
1022 			return m;
1023 	}
1024 
1025 	return NULL;
1026 }
1027 
1028 static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
1029 			    __u16 kind, struct btf **res_btf,
1030 			    struct module_btf **res_mod_btf);
1031 
1032 #define STRUCT_OPS_VALUE_PREFIX "bpf_struct_ops_"
1033 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
1034 				   const char *name, __u32 kind);
1035 
1036 static int
1037 find_struct_ops_kern_types(struct bpf_object *obj, const char *tname_raw,
1038 			   struct module_btf **mod_btf,
1039 			   const struct btf_type **type, __u32 *type_id,
1040 			   const struct btf_type **vtype, __u32 *vtype_id,
1041 			   const struct btf_member **data_member)
1042 {
1043 	const struct btf_type *kern_type, *kern_vtype;
1044 	const struct btf_member *kern_data_member;
1045 	struct btf *btf = NULL;
1046 	__s32 kern_vtype_id, kern_type_id;
1047 	char tname[192], stname[256];
1048 	__u32 i;
1049 
1050 	snprintf(tname, sizeof(tname), "%.*s",
1051 		 (int)bpf_core_essential_name_len(tname_raw), tname_raw);
1052 
1053 	snprintf(stname, sizeof(stname), "%s%s", STRUCT_OPS_VALUE_PREFIX, tname);
1054 
1055 	/* Look for the corresponding "map_value" type that will be used
1056 	 * in map_update(BPF_MAP_TYPE_STRUCT_OPS) first, figure out the btf
1057 	 * and the mod_btf.
1058 	 * For example, find "struct bpf_struct_ops_tcp_congestion_ops".
1059 	 */
1060 	kern_vtype_id = find_ksym_btf_id(obj, stname, BTF_KIND_STRUCT, &btf, mod_btf);
1061 	if (kern_vtype_id < 0) {
1062 		pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n", stname);
1063 		return kern_vtype_id;
1064 	}
1065 	kern_vtype = btf__type_by_id(btf, kern_vtype_id);
1066 
1067 	kern_type_id = btf__find_by_name_kind(btf, tname, BTF_KIND_STRUCT);
1068 	if (kern_type_id < 0) {
1069 		pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n", tname);
1070 		return kern_type_id;
1071 	}
1072 	kern_type = btf__type_by_id(btf, kern_type_id);
1073 
1074 	/* Find "struct tcp_congestion_ops" from
1075 	 * struct bpf_struct_ops_tcp_congestion_ops {
1076 	 *	[ ... ]
1077 	 *	struct tcp_congestion_ops data;
1078 	 * }
1079 	 */
1080 	kern_data_member = btf_members(kern_vtype);
1081 	for (i = 0; i < btf_vlen(kern_vtype); i++, kern_data_member++) {
1082 		if (kern_data_member->type == kern_type_id)
1083 			break;
1084 	}
1085 	if (i == btf_vlen(kern_vtype)) {
1086 		pr_warn("struct_ops init_kern: struct %s data is not found in struct %s\n",
1087 			tname, stname);
1088 		return -EINVAL;
1089 	}
1090 
1091 	*type = kern_type;
1092 	*type_id = kern_type_id;
1093 	*vtype = kern_vtype;
1094 	*vtype_id = kern_vtype_id;
1095 	*data_member = kern_data_member;
1096 
1097 	return 0;
1098 }
1099 
1100 static bool bpf_map__is_struct_ops(const struct bpf_map *map)
1101 {
1102 	return map->def.type == BPF_MAP_TYPE_STRUCT_OPS;
1103 }
1104 
1105 static bool is_valid_st_ops_program(struct bpf_object *obj,
1106 				    const struct bpf_program *prog)
1107 {
1108 	int i;
1109 
1110 	for (i = 0; i < obj->nr_programs; i++) {
1111 		if (&obj->programs[i] == prog)
1112 			return prog->type == BPF_PROG_TYPE_STRUCT_OPS;
1113 	}
1114 
1115 	return false;
1116 }
1117 
1118 /* For each struct_ops program P, referenced from some struct_ops map M,
1119  * enable P.autoload if there are Ms for which M.autocreate is true,
1120  * disable P.autoload if for all Ms M.autocreate is false.
1121  * Don't change P.autoload for programs that are not referenced from any maps.
1122  */
1123 static int bpf_object_adjust_struct_ops_autoload(struct bpf_object *obj)
1124 {
1125 	struct bpf_program *prog, *slot_prog;
1126 	struct bpf_map *map;
1127 	int i, j, k, vlen;
1128 
1129 	for (i = 0; i < obj->nr_programs; ++i) {
1130 		int should_load = false;
1131 		int use_cnt = 0;
1132 
1133 		prog = &obj->programs[i];
1134 		if (prog->type != BPF_PROG_TYPE_STRUCT_OPS)
1135 			continue;
1136 
1137 		for (j = 0; j < obj->nr_maps; ++j) {
1138 			const struct btf_type *type;
1139 
1140 			map = &obj->maps[j];
1141 			if (!bpf_map__is_struct_ops(map))
1142 				continue;
1143 
1144 			type = btf__type_by_id(obj->btf, map->st_ops->type_id);
1145 			vlen = btf_vlen(type);
1146 			for (k = 0; k < vlen; ++k) {
1147 				slot_prog = map->st_ops->progs[k];
1148 				if (prog != slot_prog)
1149 					continue;
1150 
1151 				use_cnt++;
1152 				if (map->autocreate)
1153 					should_load = true;
1154 			}
1155 		}
1156 		if (use_cnt)
1157 			prog->autoload = should_load;
1158 	}
1159 
1160 	return 0;
1161 }
1162 
1163 /* Init the map's fields that depend on kern_btf */
1164 static int bpf_map__init_kern_struct_ops(struct bpf_map *map)
1165 {
1166 	const struct btf_member *member, *kern_member, *kern_data_member;
1167 	const struct btf_type *type, *kern_type, *kern_vtype;
1168 	__u32 i, kern_type_id, kern_vtype_id, kern_data_off;
1169 	struct bpf_object *obj = map->obj;
1170 	const struct btf *btf = obj->btf;
1171 	struct bpf_struct_ops *st_ops;
1172 	const struct btf *kern_btf;
1173 	struct module_btf *mod_btf = NULL;
1174 	void *data, *kern_data;
1175 	const char *tname;
1176 	int err;
1177 
1178 	st_ops = map->st_ops;
1179 	type = btf__type_by_id(btf, st_ops->type_id);
1180 	tname = btf__name_by_offset(btf, type->name_off);
1181 	err = find_struct_ops_kern_types(obj, tname, &mod_btf,
1182 					 &kern_type, &kern_type_id,
1183 					 &kern_vtype, &kern_vtype_id,
1184 					 &kern_data_member);
1185 	if (err)
1186 		return err;
1187 
1188 	kern_btf = mod_btf ? mod_btf->btf : obj->btf_vmlinux;
1189 
1190 	pr_debug("struct_ops init_kern %s: type_id:%u kern_type_id:%u kern_vtype_id:%u\n",
1191 		 map->name, st_ops->type_id, kern_type_id, kern_vtype_id);
1192 
1193 	map->mod_btf_fd = mod_btf ? mod_btf->fd : -1;
1194 	map->def.value_size = kern_vtype->size;
1195 	map->btf_vmlinux_value_type_id = kern_vtype_id;
1196 
1197 	st_ops->kern_vdata = calloc(1, kern_vtype->size);
1198 	if (!st_ops->kern_vdata)
1199 		return -ENOMEM;
1200 
1201 	data = st_ops->data;
1202 	kern_data_off = kern_data_member->offset / 8;
1203 	kern_data = st_ops->kern_vdata + kern_data_off;
1204 
1205 	member = btf_members(type);
1206 	for (i = 0; i < btf_vlen(type); i++, member++) {
1207 		const struct btf_type *mtype, *kern_mtype;
1208 		__u32 mtype_id, kern_mtype_id;
1209 		void *mdata, *kern_mdata;
1210 		struct bpf_program *prog;
1211 		__s64 msize, kern_msize;
1212 		__u32 moff, kern_moff;
1213 		__u32 kern_member_idx;
1214 		const char *mname;
1215 
1216 		mname = btf__name_by_offset(btf, member->name_off);
1217 		moff = member->offset / 8;
1218 		mdata = data + moff;
1219 		msize = btf__resolve_size(btf, member->type);
1220 		if (msize < 0) {
1221 			pr_warn("struct_ops init_kern %s: failed to resolve the size of member %s\n",
1222 				map->name, mname);
1223 			return msize;
1224 		}
1225 
1226 		kern_member = find_member_by_name(kern_btf, kern_type, mname);
1227 		if (!kern_member) {
1228 			if (!libbpf_is_mem_zeroed(mdata, msize)) {
1229 				pr_warn("struct_ops init_kern %s: Cannot find member %s in kernel BTF\n",
1230 					map->name, mname);
1231 				return -ENOTSUP;
1232 			}
1233 
1234 			if (st_ops->progs[i]) {
1235 				/* If we had declaratively set struct_ops callback, we need to
1236 				 * force its autoload to false, because it doesn't have
1237 				 * a chance of succeeding from POV of the current struct_ops map.
1238 				 * If this program is still referenced somewhere else, though,
1239 				 * then bpf_object_adjust_struct_ops_autoload() will update its
1240 				 * autoload accordingly.
1241 				 */
1242 				st_ops->progs[i]->autoload = false;
1243 				st_ops->progs[i] = NULL;
1244 			}
1245 
1246 			/* Skip all-zero/NULL fields if they are not present in the kernel BTF */
1247 			pr_info("struct_ops %s: member %s not found in kernel, skipping it as it's set to zero\n",
1248 				map->name, mname);
1249 			continue;
1250 		}
1251 
1252 		kern_member_idx = kern_member - btf_members(kern_type);
1253 		if (btf_member_bitfield_size(type, i) ||
1254 		    btf_member_bitfield_size(kern_type, kern_member_idx)) {
1255 			pr_warn("struct_ops init_kern %s: bitfield %s is not supported\n",
1256 				map->name, mname);
1257 			return -ENOTSUP;
1258 		}
1259 
1260 		kern_moff = kern_member->offset / 8;
1261 		kern_mdata = kern_data + kern_moff;
1262 
1263 		mtype = skip_mods_and_typedefs(btf, member->type, &mtype_id);
1264 		kern_mtype = skip_mods_and_typedefs(kern_btf, kern_member->type,
1265 						    &kern_mtype_id);
1266 		if (BTF_INFO_KIND(mtype->info) !=
1267 		    BTF_INFO_KIND(kern_mtype->info)) {
1268 			pr_warn("struct_ops init_kern %s: Unmatched member type %s %u != %u(kernel)\n",
1269 				map->name, mname, BTF_INFO_KIND(mtype->info),
1270 				BTF_INFO_KIND(kern_mtype->info));
1271 			return -ENOTSUP;
1272 		}
1273 
1274 		if (btf_is_ptr(mtype)) {
1275 			prog = *(void **)mdata;
1276 			/* just like for !kern_member case above, reset declaratively
1277 			 * set (at compile time) program's autload to false,
1278 			 * if user replaced it with another program or NULL
1279 			 */
1280 			if (st_ops->progs[i] && st_ops->progs[i] != prog)
1281 				st_ops->progs[i]->autoload = false;
1282 
1283 			/* Update the value from the shadow type */
1284 			st_ops->progs[i] = prog;
1285 			if (!prog)
1286 				continue;
1287 
1288 			if (!is_valid_st_ops_program(obj, prog)) {
1289 				pr_warn("struct_ops init_kern %s: member %s is not a struct_ops program\n",
1290 					map->name, mname);
1291 				return -ENOTSUP;
1292 			}
1293 
1294 			kern_mtype = skip_mods_and_typedefs(kern_btf,
1295 							    kern_mtype->type,
1296 							    &kern_mtype_id);
1297 
1298 			/* mtype->type must be a func_proto which was
1299 			 * guaranteed in bpf_object__collect_st_ops_relos(),
1300 			 * so only check kern_mtype for func_proto here.
1301 			 */
1302 			if (!btf_is_func_proto(kern_mtype)) {
1303 				pr_warn("struct_ops init_kern %s: kernel member %s is not a func ptr\n",
1304 					map->name, mname);
1305 				return -ENOTSUP;
1306 			}
1307 
1308 			if (mod_btf)
1309 				prog->attach_btf_obj_fd = mod_btf->fd;
1310 
1311 			/* if we haven't yet processed this BPF program, record proper
1312 			 * attach_btf_id and member_idx
1313 			 */
1314 			if (!prog->attach_btf_id) {
1315 				prog->attach_btf_id = kern_type_id;
1316 				prog->expected_attach_type = kern_member_idx;
1317 			}
1318 
1319 			/* struct_ops BPF prog can be re-used between multiple
1320 			 * .struct_ops & .struct_ops.link as long as it's the
1321 			 * same struct_ops struct definition and the same
1322 			 * function pointer field
1323 			 */
1324 			if (prog->attach_btf_id != kern_type_id) {
1325 				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",
1326 					map->name, mname, prog->name, prog->sec_name, prog->type,
1327 					prog->attach_btf_id, kern_type_id);
1328 				return -EINVAL;
1329 			}
1330 			if (prog->expected_attach_type != kern_member_idx) {
1331 				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",
1332 					map->name, mname, prog->name, prog->sec_name, prog->type,
1333 					prog->expected_attach_type, kern_member_idx);
1334 				return -EINVAL;
1335 			}
1336 
1337 			st_ops->kern_func_off[i] = kern_data_off + kern_moff;
1338 
1339 			pr_debug("struct_ops init_kern %s: func ptr %s is set to prog %s from data(+%u) to kern_data(+%u)\n",
1340 				 map->name, mname, prog->name, moff,
1341 				 kern_moff);
1342 
1343 			continue;
1344 		}
1345 
1346 		kern_msize = btf__resolve_size(kern_btf, kern_mtype_id);
1347 		if (kern_msize < 0 || msize != kern_msize) {
1348 			pr_warn("struct_ops init_kern %s: Error in size of member %s: %zd != %zd(kernel)\n",
1349 				map->name, mname, (ssize_t)msize,
1350 				(ssize_t)kern_msize);
1351 			return -ENOTSUP;
1352 		}
1353 
1354 		pr_debug("struct_ops init_kern %s: copy %s %u bytes from data(+%u) to kern_data(+%u)\n",
1355 			 map->name, mname, (unsigned int)msize,
1356 			 moff, kern_moff);
1357 		memcpy(kern_mdata, mdata, msize);
1358 	}
1359 
1360 	return 0;
1361 }
1362 
1363 static int bpf_object__init_kern_struct_ops_maps(struct bpf_object *obj)
1364 {
1365 	struct bpf_map *map;
1366 	size_t i;
1367 	int err;
1368 
1369 	for (i = 0; i < obj->nr_maps; i++) {
1370 		map = &obj->maps[i];
1371 
1372 		if (!bpf_map__is_struct_ops(map))
1373 			continue;
1374 
1375 		if (!map->autocreate)
1376 			continue;
1377 
1378 		err = bpf_map__init_kern_struct_ops(map);
1379 		if (err)
1380 			return err;
1381 	}
1382 
1383 	return 0;
1384 }
1385 
1386 static int init_struct_ops_maps(struct bpf_object *obj, const char *sec_name,
1387 				int shndx, Elf_Data *data)
1388 {
1389 	const struct btf_type *type, *datasec;
1390 	const struct btf_var_secinfo *vsi;
1391 	struct bpf_struct_ops *st_ops;
1392 	const char *tname, *var_name;
1393 	__s32 type_id, datasec_id;
1394 	const struct btf *btf;
1395 	struct bpf_map *map;
1396 	__u32 i;
1397 
1398 	if (shndx == -1)
1399 		return 0;
1400 
1401 	btf = obj->btf;
1402 	datasec_id = btf__find_by_name_kind(btf, sec_name,
1403 					    BTF_KIND_DATASEC);
1404 	if (datasec_id < 0) {
1405 		pr_warn("struct_ops init: DATASEC %s not found\n",
1406 			sec_name);
1407 		return -EINVAL;
1408 	}
1409 
1410 	datasec = btf__type_by_id(btf, datasec_id);
1411 	vsi = btf_var_secinfos(datasec);
1412 	for (i = 0; i < btf_vlen(datasec); i++, vsi++) {
1413 		type = btf__type_by_id(obj->btf, vsi->type);
1414 		var_name = btf__name_by_offset(obj->btf, type->name_off);
1415 
1416 		type_id = btf__resolve_type(obj->btf, vsi->type);
1417 		if (type_id < 0) {
1418 			pr_warn("struct_ops init: Cannot resolve var type_id %u in DATASEC %s\n",
1419 				vsi->type, sec_name);
1420 			return -EINVAL;
1421 		}
1422 
1423 		type = btf__type_by_id(obj->btf, type_id);
1424 		tname = btf__name_by_offset(obj->btf, type->name_off);
1425 		if (!tname[0]) {
1426 			pr_warn("struct_ops init: anonymous type is not supported\n");
1427 			return -ENOTSUP;
1428 		}
1429 		if (!btf_is_struct(type)) {
1430 			pr_warn("struct_ops init: %s is not a struct\n", tname);
1431 			return -EINVAL;
1432 		}
1433 
1434 		map = bpf_object__add_map(obj);
1435 		if (IS_ERR(map))
1436 			return PTR_ERR(map);
1437 
1438 		map->sec_idx = shndx;
1439 		map->sec_offset = vsi->offset;
1440 		map->name = strdup(var_name);
1441 		if (!map->name)
1442 			return -ENOMEM;
1443 		map->btf_value_type_id = type_id;
1444 
1445 		/* Follow same convention as for programs autoload:
1446 		 * SEC("?.struct_ops") means map is not created by default.
1447 		 */
1448 		if (sec_name[0] == '?') {
1449 			map->autocreate = false;
1450 			/* from now on forget there was ? in section name */
1451 			sec_name++;
1452 		}
1453 
1454 		map->def.type = BPF_MAP_TYPE_STRUCT_OPS;
1455 		map->def.key_size = sizeof(int);
1456 		map->def.value_size = type->size;
1457 		map->def.max_entries = 1;
1458 		map->def.map_flags = strcmp(sec_name, STRUCT_OPS_LINK_SEC) == 0 ? BPF_F_LINK : 0;
1459 		map->autoattach = true;
1460 
1461 		map->st_ops = calloc(1, sizeof(*map->st_ops));
1462 		if (!map->st_ops)
1463 			return -ENOMEM;
1464 		st_ops = map->st_ops;
1465 		st_ops->data = malloc(type->size);
1466 		st_ops->progs = calloc(btf_vlen(type), sizeof(*st_ops->progs));
1467 		st_ops->kern_func_off = malloc(btf_vlen(type) *
1468 					       sizeof(*st_ops->kern_func_off));
1469 		if (!st_ops->data || !st_ops->progs || !st_ops->kern_func_off)
1470 			return -ENOMEM;
1471 
1472 		if (vsi->offset + type->size > data->d_size) {
1473 			pr_warn("struct_ops init: var %s is beyond the end of DATASEC %s\n",
1474 				var_name, sec_name);
1475 			return -EINVAL;
1476 		}
1477 
1478 		memcpy(st_ops->data,
1479 		       data->d_buf + vsi->offset,
1480 		       type->size);
1481 		st_ops->type_id = type_id;
1482 
1483 		pr_debug("struct_ops init: struct %s(type_id=%u) %s found at offset %u\n",
1484 			 tname, type_id, var_name, vsi->offset);
1485 	}
1486 
1487 	return 0;
1488 }
1489 
1490 static int bpf_object_init_struct_ops(struct bpf_object *obj)
1491 {
1492 	const char *sec_name;
1493 	int sec_idx, err;
1494 
1495 	for (sec_idx = 0; sec_idx < obj->efile.sec_cnt; ++sec_idx) {
1496 		struct elf_sec_desc *desc = &obj->efile.secs[sec_idx];
1497 
1498 		if (desc->sec_type != SEC_ST_OPS)
1499 			continue;
1500 
1501 		sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1502 		if (!sec_name)
1503 			return -LIBBPF_ERRNO__FORMAT;
1504 
1505 		err = init_struct_ops_maps(obj, sec_name, sec_idx, desc->data);
1506 		if (err)
1507 			return err;
1508 	}
1509 
1510 	return 0;
1511 }
1512 
1513 static struct bpf_object *bpf_object__new(const char *path,
1514 					  const void *obj_buf,
1515 					  size_t obj_buf_sz,
1516 					  const char *obj_name)
1517 {
1518 	struct bpf_object *obj;
1519 	char *end;
1520 
1521 	obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
1522 	if (!obj) {
1523 		pr_warn("alloc memory failed for %s\n", path);
1524 		return ERR_PTR(-ENOMEM);
1525 	}
1526 
1527 	strcpy(obj->path, path);
1528 	if (obj_name) {
1529 		libbpf_strlcpy(obj->name, obj_name, sizeof(obj->name));
1530 	} else {
1531 		/* Using basename() GNU version which doesn't modify arg. */
1532 		libbpf_strlcpy(obj->name, basename((void *)path), sizeof(obj->name));
1533 		end = strchr(obj->name, '.');
1534 		if (end)
1535 			*end = 0;
1536 	}
1537 
1538 	obj->efile.fd = -1;
1539 	/*
1540 	 * Caller of this function should also call
1541 	 * bpf_object__elf_finish() after data collection to return
1542 	 * obj_buf to user. If not, we should duplicate the buffer to
1543 	 * avoid user freeing them before elf finish.
1544 	 */
1545 	obj->efile.obj_buf = obj_buf;
1546 	obj->efile.obj_buf_sz = obj_buf_sz;
1547 	obj->efile.btf_maps_shndx = -1;
1548 	obj->kconfig_map_idx = -1;
1549 	obj->arena_map_idx = -1;
1550 
1551 	obj->kern_version = get_kernel_version();
1552 	obj->state  = OBJ_OPEN;
1553 
1554 	return obj;
1555 }
1556 
1557 static void bpf_object__elf_finish(struct bpf_object *obj)
1558 {
1559 	if (!obj->efile.elf)
1560 		return;
1561 
1562 	elf_end(obj->efile.elf);
1563 	obj->efile.elf = NULL;
1564 	obj->efile.ehdr = NULL;
1565 	obj->efile.symbols = NULL;
1566 	obj->efile.arena_data = NULL;
1567 
1568 	zfree(&obj->efile.secs);
1569 	obj->efile.sec_cnt = 0;
1570 	zclose(obj->efile.fd);
1571 	obj->efile.obj_buf = NULL;
1572 	obj->efile.obj_buf_sz = 0;
1573 }
1574 
1575 static int bpf_object__elf_init(struct bpf_object *obj)
1576 {
1577 	Elf64_Ehdr *ehdr;
1578 	int err = 0;
1579 	Elf *elf;
1580 
1581 	if (obj->efile.elf) {
1582 		pr_warn("elf: init internal error\n");
1583 		return -LIBBPF_ERRNO__LIBELF;
1584 	}
1585 
1586 	if (obj->efile.obj_buf_sz > 0) {
1587 		/* obj_buf should have been validated by bpf_object__open_mem(). */
1588 		elf = elf_memory((char *)obj->efile.obj_buf, obj->efile.obj_buf_sz);
1589 	} else {
1590 		obj->efile.fd = open(obj->path, O_RDONLY | O_CLOEXEC);
1591 		if (obj->efile.fd < 0) {
1592 			err = -errno;
1593 			pr_warn("elf: failed to open %s: %s\n", obj->path, errstr(err));
1594 			return err;
1595 		}
1596 
1597 		elf = elf_begin(obj->efile.fd, ELF_C_READ_MMAP, NULL);
1598 	}
1599 
1600 	if (!elf) {
1601 		pr_warn("elf: failed to open %s as ELF file: %s\n", obj->path, elf_errmsg(-1));
1602 		err = -LIBBPF_ERRNO__LIBELF;
1603 		goto errout;
1604 	}
1605 
1606 	obj->efile.elf = elf;
1607 
1608 	if (elf_kind(elf) != ELF_K_ELF) {
1609 		err = -LIBBPF_ERRNO__FORMAT;
1610 		pr_warn("elf: '%s' is not a proper ELF object\n", obj->path);
1611 		goto errout;
1612 	}
1613 
1614 	if (gelf_getclass(elf) != ELFCLASS64) {
1615 		err = -LIBBPF_ERRNO__FORMAT;
1616 		pr_warn("elf: '%s' is not a 64-bit ELF object\n", obj->path);
1617 		goto errout;
1618 	}
1619 
1620 	obj->efile.ehdr = ehdr = elf64_getehdr(elf);
1621 	if (!obj->efile.ehdr) {
1622 		pr_warn("elf: failed to get ELF header from %s: %s\n", obj->path, elf_errmsg(-1));
1623 		err = -LIBBPF_ERRNO__FORMAT;
1624 		goto errout;
1625 	}
1626 
1627 	/* Validate ELF object endianness... */
1628 	if (ehdr->e_ident[EI_DATA] != ELFDATA2LSB &&
1629 	    ehdr->e_ident[EI_DATA] != ELFDATA2MSB) {
1630 		err = -LIBBPF_ERRNO__ENDIAN;
1631 		pr_warn("elf: '%s' has unknown byte order\n", obj->path);
1632 		goto errout;
1633 	}
1634 	/* and save after bpf_object_open() frees ELF data */
1635 	obj->byteorder = ehdr->e_ident[EI_DATA];
1636 
1637 	if (elf_getshdrstrndx(elf, &obj->efile.shstrndx)) {
1638 		pr_warn("elf: failed to get section names section index for %s: %s\n",
1639 			obj->path, elf_errmsg(-1));
1640 		err = -LIBBPF_ERRNO__FORMAT;
1641 		goto errout;
1642 	}
1643 
1644 	/* ELF is corrupted/truncated, avoid calling elf_strptr. */
1645 	if (!elf_rawdata(elf_getscn(elf, obj->efile.shstrndx), NULL)) {
1646 		pr_warn("elf: failed to get section names strings from %s: %s\n",
1647 			obj->path, elf_errmsg(-1));
1648 		err = -LIBBPF_ERRNO__FORMAT;
1649 		goto errout;
1650 	}
1651 
1652 	/* Old LLVM set e_machine to EM_NONE */
1653 	if (ehdr->e_type != ET_REL || (ehdr->e_machine && ehdr->e_machine != EM_BPF)) {
1654 		pr_warn("elf: %s is not a valid eBPF object file\n", obj->path);
1655 		err = -LIBBPF_ERRNO__FORMAT;
1656 		goto errout;
1657 	}
1658 
1659 	return 0;
1660 errout:
1661 	bpf_object__elf_finish(obj);
1662 	return err;
1663 }
1664 
1665 static bool is_native_endianness(struct bpf_object *obj)
1666 {
1667 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1668 	return obj->byteorder == ELFDATA2LSB;
1669 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
1670 	return obj->byteorder == ELFDATA2MSB;
1671 #else
1672 # error "Unrecognized __BYTE_ORDER__"
1673 #endif
1674 }
1675 
1676 static int
1677 bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
1678 {
1679 	if (!data) {
1680 		pr_warn("invalid license section in %s\n", obj->path);
1681 		return -LIBBPF_ERRNO__FORMAT;
1682 	}
1683 	/* libbpf_strlcpy() only copies first N - 1 bytes, so size + 1 won't
1684 	 * go over allowed ELF data section buffer
1685 	 */
1686 	libbpf_strlcpy(obj->license, data, min(size + 1, sizeof(obj->license)));
1687 	pr_debug("license of %s is %s\n", obj->path, obj->license);
1688 	return 0;
1689 }
1690 
1691 static int
1692 bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
1693 {
1694 	__u32 kver;
1695 
1696 	if (!data || size != sizeof(kver)) {
1697 		pr_warn("invalid kver section in %s\n", obj->path);
1698 		return -LIBBPF_ERRNO__FORMAT;
1699 	}
1700 	memcpy(&kver, data, sizeof(kver));
1701 	obj->kern_version = kver;
1702 	pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
1703 	return 0;
1704 }
1705 
1706 static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
1707 {
1708 	if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
1709 	    type == BPF_MAP_TYPE_HASH_OF_MAPS)
1710 		return true;
1711 	return false;
1712 }
1713 
1714 static int find_elf_sec_sz(const struct bpf_object *obj, const char *name, __u32 *size)
1715 {
1716 	Elf_Data *data;
1717 	Elf_Scn *scn;
1718 
1719 	if (!name)
1720 		return -EINVAL;
1721 
1722 	scn = elf_sec_by_name(obj, name);
1723 	data = elf_sec_data(obj, scn);
1724 	if (data) {
1725 		*size = data->d_size;
1726 		return 0; /* found it */
1727 	}
1728 
1729 	return -ENOENT;
1730 }
1731 
1732 static Elf64_Sym *find_elf_var_sym(const struct bpf_object *obj, const char *name)
1733 {
1734 	Elf_Data *symbols = obj->efile.symbols;
1735 	const char *sname;
1736 	size_t si;
1737 
1738 	for (si = 0; si < symbols->d_size / sizeof(Elf64_Sym); si++) {
1739 		Elf64_Sym *sym = elf_sym_by_idx(obj, si);
1740 
1741 		if (ELF64_ST_TYPE(sym->st_info) != STT_OBJECT)
1742 			continue;
1743 
1744 		if (ELF64_ST_BIND(sym->st_info) != STB_GLOBAL &&
1745 		    ELF64_ST_BIND(sym->st_info) != STB_WEAK)
1746 			continue;
1747 
1748 		sname = elf_sym_str(obj, sym->st_name);
1749 		if (!sname) {
1750 			pr_warn("failed to get sym name string for var %s\n", name);
1751 			return ERR_PTR(-EIO);
1752 		}
1753 		if (strcmp(name, sname) == 0)
1754 			return sym;
1755 	}
1756 
1757 	return ERR_PTR(-ENOENT);
1758 }
1759 
1760 #ifndef MFD_CLOEXEC
1761 #define MFD_CLOEXEC 0x0001U
1762 #endif
1763 #ifndef MFD_NOEXEC_SEAL
1764 #define MFD_NOEXEC_SEAL 0x0008U
1765 #endif
1766 
1767 static int create_placeholder_fd(void)
1768 {
1769 	unsigned int flags = MFD_CLOEXEC | MFD_NOEXEC_SEAL;
1770 	const char *name = "libbpf-placeholder-fd";
1771 	int fd;
1772 
1773 	fd = ensure_good_fd(sys_memfd_create(name, flags));
1774 	if (fd >= 0)
1775 		return fd;
1776 	else if (errno != EINVAL)
1777 		return -errno;
1778 
1779 	/* Possibly running on kernel without MFD_NOEXEC_SEAL */
1780 	fd = ensure_good_fd(sys_memfd_create(name, flags & ~MFD_NOEXEC_SEAL));
1781 	if (fd < 0)
1782 		return -errno;
1783 	return fd;
1784 }
1785 
1786 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
1787 {
1788 	struct bpf_map *map;
1789 	int err;
1790 
1791 	err = libbpf_ensure_mem((void **)&obj->maps, &obj->maps_cap,
1792 				sizeof(*obj->maps), obj->nr_maps + 1);
1793 	if (err)
1794 		return ERR_PTR(err);
1795 
1796 	map = &obj->maps[obj->nr_maps++];
1797 	map->obj = obj;
1798 	/* Preallocate map FD without actually creating BPF map just yet.
1799 	 * These map FD "placeholders" will be reused later without changing
1800 	 * FD value when map is actually created in the kernel.
1801 	 *
1802 	 * This is useful to be able to perform BPF program relocations
1803 	 * without having to create BPF maps before that step. This allows us
1804 	 * to finalize and load BTF very late in BPF object's loading phase,
1805 	 * right before BPF maps have to be created and BPF programs have to
1806 	 * be loaded. By having these map FD placeholders we can perform all
1807 	 * the sanitizations, relocations, and any other adjustments before we
1808 	 * start creating actual BPF kernel objects (BTF, maps, progs).
1809 	 */
1810 	map->fd = create_placeholder_fd();
1811 	if (map->fd < 0)
1812 		return ERR_PTR(map->fd);
1813 	map->inner_map_fd = -1;
1814 	map->autocreate = true;
1815 
1816 	return map;
1817 }
1818 
1819 static size_t array_map_mmap_sz(unsigned int value_sz, unsigned int max_entries)
1820 {
1821 	const long page_sz = sysconf(_SC_PAGE_SIZE);
1822 	size_t map_sz;
1823 
1824 	map_sz = (size_t)roundup(value_sz, 8) * max_entries;
1825 	map_sz = roundup(map_sz, page_sz);
1826 	return map_sz;
1827 }
1828 
1829 static size_t bpf_map_mmap_sz(const struct bpf_map *map)
1830 {
1831 	const long page_sz = sysconf(_SC_PAGE_SIZE);
1832 
1833 	switch (map->def.type) {
1834 	case BPF_MAP_TYPE_ARRAY:
1835 		return array_map_mmap_sz(map->def.value_size, map->def.max_entries);
1836 	case BPF_MAP_TYPE_ARENA:
1837 		return page_sz * map->def.max_entries;
1838 	default:
1839 		return 0; /* not supported */
1840 	}
1841 }
1842 
1843 static int bpf_map_mmap_resize(struct bpf_map *map, size_t old_sz, size_t new_sz)
1844 {
1845 	void *mmaped;
1846 
1847 	if (!map->mmaped)
1848 		return -EINVAL;
1849 
1850 	if (old_sz == new_sz)
1851 		return 0;
1852 
1853 	mmaped = mmap(NULL, new_sz, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1854 	if (mmaped == MAP_FAILED)
1855 		return -errno;
1856 
1857 	memcpy(mmaped, map->mmaped, min(old_sz, new_sz));
1858 	munmap(map->mmaped, old_sz);
1859 	map->mmaped = mmaped;
1860 	return 0;
1861 }
1862 
1863 static char *internal_map_name(struct bpf_object *obj, const char *real_name)
1864 {
1865 	char map_name[BPF_OBJ_NAME_LEN], *p;
1866 	int pfx_len, sfx_len = max((size_t)7, strlen(real_name));
1867 
1868 	/* This is one of the more confusing parts of libbpf for various
1869 	 * reasons, some of which are historical. The original idea for naming
1870 	 * internal names was to include as much of BPF object name prefix as
1871 	 * possible, so that it can be distinguished from similar internal
1872 	 * maps of a different BPF object.
1873 	 * As an example, let's say we have bpf_object named 'my_object_name'
1874 	 * and internal map corresponding to '.rodata' ELF section. The final
1875 	 * map name advertised to user and to the kernel will be
1876 	 * 'my_objec.rodata', taking first 8 characters of object name and
1877 	 * entire 7 characters of '.rodata'.
1878 	 * Somewhat confusingly, if internal map ELF section name is shorter
1879 	 * than 7 characters, e.g., '.bss', we still reserve 7 characters
1880 	 * for the suffix, even though we only have 4 actual characters, and
1881 	 * resulting map will be called 'my_objec.bss', not even using all 15
1882 	 * characters allowed by the kernel. Oh well, at least the truncated
1883 	 * object name is somewhat consistent in this case. But if the map
1884 	 * name is '.kconfig', we'll still have entirety of '.kconfig' added
1885 	 * (8 chars) and thus will be left with only first 7 characters of the
1886 	 * object name ('my_obje'). Happy guessing, user, that the final map
1887 	 * name will be "my_obje.kconfig".
1888 	 * Now, with libbpf starting to support arbitrarily named .rodata.*
1889 	 * and .data.* data sections, it's possible that ELF section name is
1890 	 * longer than allowed 15 chars, so we now need to be careful to take
1891 	 * only up to 15 first characters of ELF name, taking no BPF object
1892 	 * name characters at all. So '.rodata.abracadabra' will result in
1893 	 * '.rodata.abracad' kernel and user-visible name.
1894 	 * We need to keep this convoluted logic intact for .data, .bss and
1895 	 * .rodata maps, but for new custom .data.custom and .rodata.custom
1896 	 * maps we use their ELF names as is, not prepending bpf_object name
1897 	 * in front. We still need to truncate them to 15 characters for the
1898 	 * kernel. Full name can be recovered for such maps by using DATASEC
1899 	 * BTF type associated with such map's value type, though.
1900 	 */
1901 	if (sfx_len >= BPF_OBJ_NAME_LEN)
1902 		sfx_len = BPF_OBJ_NAME_LEN - 1;
1903 
1904 	/* if there are two or more dots in map name, it's a custom dot map */
1905 	if (strchr(real_name + 1, '.') != NULL)
1906 		pfx_len = 0;
1907 	else
1908 		pfx_len = min((size_t)BPF_OBJ_NAME_LEN - sfx_len - 1, strlen(obj->name));
1909 
1910 	snprintf(map_name, sizeof(map_name), "%.*s%.*s", pfx_len, obj->name,
1911 		 sfx_len, real_name);
1912 
1913 	/* sanities map name to characters allowed by kernel */
1914 	for (p = map_name; *p && p < map_name + sizeof(map_name); p++)
1915 		if (!isalnum(*p) && *p != '_' && *p != '.')
1916 			*p = '_';
1917 
1918 	return strdup(map_name);
1919 }
1920 
1921 static int
1922 map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map);
1923 
1924 /* Internal BPF map is mmap()'able only if at least one of corresponding
1925  * DATASEC's VARs are to be exposed through BPF skeleton. I.e., it's a GLOBAL
1926  * variable and it's not marked as __hidden (which turns it into, effectively,
1927  * a STATIC variable).
1928  */
1929 static bool map_is_mmapable(struct bpf_object *obj, struct bpf_map *map)
1930 {
1931 	const struct btf_type *t, *vt;
1932 	struct btf_var_secinfo *vsi;
1933 	int i, n;
1934 
1935 	if (!map->btf_value_type_id)
1936 		return false;
1937 
1938 	t = btf__type_by_id(obj->btf, map->btf_value_type_id);
1939 	if (!btf_is_datasec(t))
1940 		return false;
1941 
1942 	vsi = btf_var_secinfos(t);
1943 	for (i = 0, n = btf_vlen(t); i < n; i++, vsi++) {
1944 		vt = btf__type_by_id(obj->btf, vsi->type);
1945 		if (!btf_is_var(vt))
1946 			continue;
1947 
1948 		if (btf_var(vt)->linkage != BTF_VAR_STATIC)
1949 			return true;
1950 	}
1951 
1952 	return false;
1953 }
1954 
1955 static int
1956 bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
1957 			      const char *real_name, int sec_idx, void *data, size_t data_sz)
1958 {
1959 	struct bpf_map_def *def;
1960 	struct bpf_map *map;
1961 	size_t mmap_sz;
1962 	int err;
1963 
1964 	map = bpf_object__add_map(obj);
1965 	if (IS_ERR(map))
1966 		return PTR_ERR(map);
1967 
1968 	map->libbpf_type = type;
1969 	map->sec_idx = sec_idx;
1970 	map->sec_offset = 0;
1971 	map->real_name = strdup(real_name);
1972 	map->name = internal_map_name(obj, real_name);
1973 	if (!map->real_name || !map->name) {
1974 		zfree(&map->real_name);
1975 		zfree(&map->name);
1976 		return -ENOMEM;
1977 	}
1978 
1979 	def = &map->def;
1980 	def->type = BPF_MAP_TYPE_ARRAY;
1981 	def->key_size = sizeof(int);
1982 	def->value_size = data_sz;
1983 	def->max_entries = 1;
1984 	def->map_flags = type == LIBBPF_MAP_RODATA || type == LIBBPF_MAP_KCONFIG
1985 		? BPF_F_RDONLY_PROG : 0;
1986 
1987 	/* failures are fine because of maps like .rodata.str1.1 */
1988 	(void) map_fill_btf_type_info(obj, map);
1989 
1990 	if (map_is_mmapable(obj, map))
1991 		def->map_flags |= BPF_F_MMAPABLE;
1992 
1993 	pr_debug("map '%s' (global data): at sec_idx %d, offset %zu, flags %x.\n",
1994 		 map->name, map->sec_idx, map->sec_offset, def->map_flags);
1995 
1996 	mmap_sz = bpf_map_mmap_sz(map);
1997 	map->mmaped = mmap(NULL, mmap_sz, PROT_READ | PROT_WRITE,
1998 			   MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1999 	if (map->mmaped == MAP_FAILED) {
2000 		err = -errno;
2001 		map->mmaped = NULL;
2002 		pr_warn("failed to alloc map '%s' content buffer: %s\n", map->name, errstr(err));
2003 		zfree(&map->real_name);
2004 		zfree(&map->name);
2005 		return err;
2006 	}
2007 
2008 	if (data)
2009 		memcpy(map->mmaped, data, data_sz);
2010 
2011 	pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
2012 	return 0;
2013 }
2014 
2015 static int bpf_object__init_global_data_maps(struct bpf_object *obj)
2016 {
2017 	struct elf_sec_desc *sec_desc;
2018 	const char *sec_name;
2019 	int err = 0, sec_idx;
2020 
2021 	/*
2022 	 * Populate obj->maps with libbpf internal maps.
2023 	 */
2024 	for (sec_idx = 1; sec_idx < obj->efile.sec_cnt; sec_idx++) {
2025 		sec_desc = &obj->efile.secs[sec_idx];
2026 
2027 		/* Skip recognized sections with size 0. */
2028 		if (!sec_desc->data || sec_desc->data->d_size == 0)
2029 			continue;
2030 
2031 		switch (sec_desc->sec_type) {
2032 		case SEC_DATA:
2033 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
2034 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
2035 							    sec_name, sec_idx,
2036 							    sec_desc->data->d_buf,
2037 							    sec_desc->data->d_size);
2038 			break;
2039 		case SEC_RODATA:
2040 			obj->has_rodata = true;
2041 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
2042 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
2043 							    sec_name, sec_idx,
2044 							    sec_desc->data->d_buf,
2045 							    sec_desc->data->d_size);
2046 			break;
2047 		case SEC_BSS:
2048 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
2049 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
2050 							    sec_name, sec_idx,
2051 							    NULL,
2052 							    sec_desc->data->d_size);
2053 			break;
2054 		default:
2055 			/* skip */
2056 			break;
2057 		}
2058 		if (err)
2059 			return err;
2060 	}
2061 	return 0;
2062 }
2063 
2064 
2065 static struct extern_desc *find_extern_by_name(const struct bpf_object *obj,
2066 					       const void *name)
2067 {
2068 	int i;
2069 
2070 	for (i = 0; i < obj->nr_extern; i++) {
2071 		if (strcmp(obj->externs[i].name, name) == 0)
2072 			return &obj->externs[i];
2073 	}
2074 	return NULL;
2075 }
2076 
2077 static struct extern_desc *find_extern_by_name_with_len(const struct bpf_object *obj,
2078 							const void *name, int len)
2079 {
2080 	const char *ext_name;
2081 	int i;
2082 
2083 	for (i = 0; i < obj->nr_extern; i++) {
2084 		ext_name = obj->externs[i].name;
2085 		if (strlen(ext_name) == len && strncmp(ext_name, name, len) == 0)
2086 			return &obj->externs[i];
2087 	}
2088 	return NULL;
2089 }
2090 
2091 static int set_kcfg_value_tri(struct extern_desc *ext, void *ext_val,
2092 			      char value)
2093 {
2094 	switch (ext->kcfg.type) {
2095 	case KCFG_BOOL:
2096 		if (value == 'm') {
2097 			pr_warn("extern (kcfg) '%s': value '%c' implies tristate or char type\n",
2098 				ext->name, value);
2099 			return -EINVAL;
2100 		}
2101 		*(bool *)ext_val = value == 'y' ? true : false;
2102 		break;
2103 	case KCFG_TRISTATE:
2104 		if (value == 'y')
2105 			*(enum libbpf_tristate *)ext_val = TRI_YES;
2106 		else if (value == 'm')
2107 			*(enum libbpf_tristate *)ext_val = TRI_MODULE;
2108 		else /* value == 'n' */
2109 			*(enum libbpf_tristate *)ext_val = TRI_NO;
2110 		break;
2111 	case KCFG_CHAR:
2112 		*(char *)ext_val = value;
2113 		break;
2114 	case KCFG_UNKNOWN:
2115 	case KCFG_INT:
2116 	case KCFG_CHAR_ARR:
2117 	default:
2118 		pr_warn("extern (kcfg) '%s': value '%c' implies bool, tristate, or char type\n",
2119 			ext->name, value);
2120 		return -EINVAL;
2121 	}
2122 	ext->is_set = true;
2123 	return 0;
2124 }
2125 
2126 static int set_kcfg_value_str(struct extern_desc *ext, char *ext_val,
2127 			      const char *value)
2128 {
2129 	size_t len;
2130 
2131 	if (ext->kcfg.type != KCFG_CHAR_ARR) {
2132 		pr_warn("extern (kcfg) '%s': value '%s' implies char array type\n",
2133 			ext->name, value);
2134 		return -EINVAL;
2135 	}
2136 
2137 	len = strlen(value);
2138 	if (len < 2 || value[len - 1] != '"') {
2139 		pr_warn("extern (kcfg) '%s': invalid string config '%s'\n",
2140 			ext->name, value);
2141 		return -EINVAL;
2142 	}
2143 
2144 	/* strip quotes */
2145 	len -= 2;
2146 	if (len >= ext->kcfg.sz) {
2147 		pr_warn("extern (kcfg) '%s': long string '%s' of (%zu bytes) truncated to %d bytes\n",
2148 			ext->name, value, len, ext->kcfg.sz - 1);
2149 		len = ext->kcfg.sz - 1;
2150 	}
2151 	memcpy(ext_val, value + 1, len);
2152 	ext_val[len] = '\0';
2153 	ext->is_set = true;
2154 	return 0;
2155 }
2156 
2157 static int parse_u64(const char *value, __u64 *res)
2158 {
2159 	char *value_end;
2160 	int err;
2161 
2162 	errno = 0;
2163 	*res = strtoull(value, &value_end, 0);
2164 	if (errno) {
2165 		err = -errno;
2166 		pr_warn("failed to parse '%s': %s\n", value, errstr(err));
2167 		return err;
2168 	}
2169 	if (*value_end) {
2170 		pr_warn("failed to parse '%s' as integer completely\n", value);
2171 		return -EINVAL;
2172 	}
2173 	return 0;
2174 }
2175 
2176 static bool is_kcfg_value_in_range(const struct extern_desc *ext, __u64 v)
2177 {
2178 	int bit_sz = ext->kcfg.sz * 8;
2179 
2180 	if (ext->kcfg.sz == 8)
2181 		return true;
2182 
2183 	/* Validate that value stored in u64 fits in integer of `ext->sz`
2184 	 * bytes size without any loss of information. If the target integer
2185 	 * is signed, we rely on the following limits of integer type of
2186 	 * Y bits and subsequent transformation:
2187 	 *
2188 	 *     -2^(Y-1) <= X           <= 2^(Y-1) - 1
2189 	 *            0 <= X + 2^(Y-1) <= 2^Y - 1
2190 	 *            0 <= X + 2^(Y-1) <  2^Y
2191 	 *
2192 	 *  For unsigned target integer, check that all the (64 - Y) bits are
2193 	 *  zero.
2194 	 */
2195 	if (ext->kcfg.is_signed)
2196 		return v + (1ULL << (bit_sz - 1)) < (1ULL << bit_sz);
2197 	else
2198 		return (v >> bit_sz) == 0;
2199 }
2200 
2201 static int set_kcfg_value_num(struct extern_desc *ext, void *ext_val,
2202 			      __u64 value)
2203 {
2204 	if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR &&
2205 	    ext->kcfg.type != KCFG_BOOL) {
2206 		pr_warn("extern (kcfg) '%s': value '%llu' implies integer, char, or boolean type\n",
2207 			ext->name, (unsigned long long)value);
2208 		return -EINVAL;
2209 	}
2210 	if (ext->kcfg.type == KCFG_BOOL && value > 1) {
2211 		pr_warn("extern (kcfg) '%s': value '%llu' isn't boolean compatible\n",
2212 			ext->name, (unsigned long long)value);
2213 		return -EINVAL;
2214 
2215 	}
2216 	if (!is_kcfg_value_in_range(ext, value)) {
2217 		pr_warn("extern (kcfg) '%s': value '%llu' doesn't fit in %d bytes\n",
2218 			ext->name, (unsigned long long)value, ext->kcfg.sz);
2219 		return -ERANGE;
2220 	}
2221 	switch (ext->kcfg.sz) {
2222 	case 1:
2223 		*(__u8 *)ext_val = value;
2224 		break;
2225 	case 2:
2226 		*(__u16 *)ext_val = value;
2227 		break;
2228 	case 4:
2229 		*(__u32 *)ext_val = value;
2230 		break;
2231 	case 8:
2232 		*(__u64 *)ext_val = value;
2233 		break;
2234 	default:
2235 		return -EINVAL;
2236 	}
2237 	ext->is_set = true;
2238 	return 0;
2239 }
2240 
2241 static int bpf_object__process_kconfig_line(struct bpf_object *obj,
2242 					    char *buf, void *data)
2243 {
2244 	struct extern_desc *ext;
2245 	char *sep, *value;
2246 	int len, err = 0;
2247 	void *ext_val;
2248 	__u64 num;
2249 
2250 	if (!str_has_pfx(buf, "CONFIG_"))
2251 		return 0;
2252 
2253 	sep = strchr(buf, '=');
2254 	if (!sep) {
2255 		pr_warn("failed to parse '%s': no separator\n", buf);
2256 		return -EINVAL;
2257 	}
2258 
2259 	/* Trim ending '\n' */
2260 	len = strlen(buf);
2261 	if (buf[len - 1] == '\n')
2262 		buf[len - 1] = '\0';
2263 	/* Split on '=' and ensure that a value is present. */
2264 	*sep = '\0';
2265 	if (!sep[1]) {
2266 		*sep = '=';
2267 		pr_warn("failed to parse '%s': no value\n", buf);
2268 		return -EINVAL;
2269 	}
2270 
2271 	ext = find_extern_by_name(obj, buf);
2272 	if (!ext || ext->is_set)
2273 		return 0;
2274 
2275 	ext_val = data + ext->kcfg.data_off;
2276 	value = sep + 1;
2277 
2278 	switch (*value) {
2279 	case 'y': case 'n': case 'm':
2280 		err = set_kcfg_value_tri(ext, ext_val, *value);
2281 		break;
2282 	case '"':
2283 		err = set_kcfg_value_str(ext, ext_val, value);
2284 		break;
2285 	default:
2286 		/* assume integer */
2287 		err = parse_u64(value, &num);
2288 		if (err) {
2289 			pr_warn("extern (kcfg) '%s': value '%s' isn't a valid integer\n", ext->name, value);
2290 			return err;
2291 		}
2292 		if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR) {
2293 			pr_warn("extern (kcfg) '%s': value '%s' implies integer type\n", ext->name, value);
2294 			return -EINVAL;
2295 		}
2296 		err = set_kcfg_value_num(ext, ext_val, num);
2297 		break;
2298 	}
2299 	if (err)
2300 		return err;
2301 	pr_debug("extern (kcfg) '%s': set to %s\n", ext->name, value);
2302 	return 0;
2303 }
2304 
2305 static int bpf_object__read_kconfig_file(struct bpf_object *obj, void *data)
2306 {
2307 	char buf[PATH_MAX];
2308 	struct utsname uts;
2309 	int len, err = 0;
2310 	gzFile file;
2311 
2312 	uname(&uts);
2313 	len = snprintf(buf, PATH_MAX, "/boot/config-%s", uts.release);
2314 	if (len < 0)
2315 		return -EINVAL;
2316 	else if (len >= PATH_MAX)
2317 		return -ENAMETOOLONG;
2318 
2319 	/* gzopen also accepts uncompressed files. */
2320 	file = gzopen(buf, "re");
2321 	if (!file)
2322 		file = gzopen("/proc/config.gz", "re");
2323 
2324 	if (!file) {
2325 		pr_warn("failed to open system Kconfig\n");
2326 		return -ENOENT;
2327 	}
2328 
2329 	while (gzgets(file, buf, sizeof(buf))) {
2330 		err = bpf_object__process_kconfig_line(obj, buf, data);
2331 		if (err) {
2332 			pr_warn("error parsing system Kconfig line '%s': %s\n",
2333 				buf, errstr(err));
2334 			goto out;
2335 		}
2336 	}
2337 
2338 out:
2339 	gzclose(file);
2340 	return err;
2341 }
2342 
2343 static int bpf_object__read_kconfig_mem(struct bpf_object *obj,
2344 					const char *config, void *data)
2345 {
2346 	char buf[PATH_MAX];
2347 	int err = 0;
2348 	FILE *file;
2349 
2350 	file = fmemopen((void *)config, strlen(config), "r");
2351 	if (!file) {
2352 		err = -errno;
2353 		pr_warn("failed to open in-memory Kconfig: %s\n", errstr(err));
2354 		return err;
2355 	}
2356 
2357 	while (fgets(buf, sizeof(buf), file)) {
2358 		err = bpf_object__process_kconfig_line(obj, buf, data);
2359 		if (err) {
2360 			pr_warn("error parsing in-memory Kconfig line '%s': %s\n",
2361 				buf, errstr(err));
2362 			break;
2363 		}
2364 	}
2365 
2366 	fclose(file);
2367 	return err;
2368 }
2369 
2370 static int bpf_object__init_kconfig_map(struct bpf_object *obj)
2371 {
2372 	struct extern_desc *last_ext = NULL, *ext;
2373 	size_t map_sz;
2374 	int i, err;
2375 
2376 	for (i = 0; i < obj->nr_extern; i++) {
2377 		ext = &obj->externs[i];
2378 		if (ext->type == EXT_KCFG)
2379 			last_ext = ext;
2380 	}
2381 
2382 	if (!last_ext)
2383 		return 0;
2384 
2385 	map_sz = last_ext->kcfg.data_off + last_ext->kcfg.sz;
2386 	err = bpf_object__init_internal_map(obj, LIBBPF_MAP_KCONFIG,
2387 					    ".kconfig", obj->efile.symbols_shndx,
2388 					    NULL, map_sz);
2389 	if (err)
2390 		return err;
2391 
2392 	obj->kconfig_map_idx = obj->nr_maps - 1;
2393 
2394 	return 0;
2395 }
2396 
2397 const struct btf_type *
2398 skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id)
2399 {
2400 	const struct btf_type *t = btf__type_by_id(btf, id);
2401 
2402 	if (res_id)
2403 		*res_id = id;
2404 
2405 	while (btf_is_mod(t) || btf_is_typedef(t)) {
2406 		if (res_id)
2407 			*res_id = t->type;
2408 		t = btf__type_by_id(btf, t->type);
2409 	}
2410 
2411 	return t;
2412 }
2413 
2414 static const struct btf_type *
2415 resolve_func_ptr(const struct btf *btf, __u32 id, __u32 *res_id)
2416 {
2417 	const struct btf_type *t;
2418 
2419 	t = skip_mods_and_typedefs(btf, id, NULL);
2420 	if (!btf_is_ptr(t))
2421 		return NULL;
2422 
2423 	t = skip_mods_and_typedefs(btf, t->type, res_id);
2424 
2425 	return btf_is_func_proto(t) ? t : NULL;
2426 }
2427 
2428 static const char *__btf_kind_str(__u16 kind)
2429 {
2430 	switch (kind) {
2431 	case BTF_KIND_UNKN: return "void";
2432 	case BTF_KIND_INT: return "int";
2433 	case BTF_KIND_PTR: return "ptr";
2434 	case BTF_KIND_ARRAY: return "array";
2435 	case BTF_KIND_STRUCT: return "struct";
2436 	case BTF_KIND_UNION: return "union";
2437 	case BTF_KIND_ENUM: return "enum";
2438 	case BTF_KIND_FWD: return "fwd";
2439 	case BTF_KIND_TYPEDEF: return "typedef";
2440 	case BTF_KIND_VOLATILE: return "volatile";
2441 	case BTF_KIND_CONST: return "const";
2442 	case BTF_KIND_RESTRICT: return "restrict";
2443 	case BTF_KIND_FUNC: return "func";
2444 	case BTF_KIND_FUNC_PROTO: return "func_proto";
2445 	case BTF_KIND_VAR: return "var";
2446 	case BTF_KIND_DATASEC: return "datasec";
2447 	case BTF_KIND_FLOAT: return "float";
2448 	case BTF_KIND_DECL_TAG: return "decl_tag";
2449 	case BTF_KIND_TYPE_TAG: return "type_tag";
2450 	case BTF_KIND_ENUM64: return "enum64";
2451 	default: return "unknown";
2452 	}
2453 }
2454 
2455 const char *btf_kind_str(const struct btf_type *t)
2456 {
2457 	return __btf_kind_str(btf_kind(t));
2458 }
2459 
2460 /*
2461  * Fetch integer attribute of BTF map definition. Such attributes are
2462  * represented using a pointer to an array, in which dimensionality of array
2463  * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
2464  * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
2465  * type definition, while using only sizeof(void *) space in ELF data section.
2466  */
2467 static bool get_map_field_int(const char *map_name, const struct btf *btf,
2468 			      const struct btf_member *m, __u32 *res)
2469 {
2470 	const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
2471 	const char *name = btf__name_by_offset(btf, m->name_off);
2472 	const struct btf_array *arr_info;
2473 	const struct btf_type *arr_t;
2474 
2475 	if (!btf_is_ptr(t)) {
2476 		pr_warn("map '%s': attr '%s': expected PTR, got %s.\n",
2477 			map_name, name, btf_kind_str(t));
2478 		return false;
2479 	}
2480 
2481 	arr_t = btf__type_by_id(btf, t->type);
2482 	if (!arr_t) {
2483 		pr_warn("map '%s': attr '%s': type [%u] not found.\n",
2484 			map_name, name, t->type);
2485 		return false;
2486 	}
2487 	if (!btf_is_array(arr_t)) {
2488 		pr_warn("map '%s': attr '%s': expected ARRAY, got %s.\n",
2489 			map_name, name, btf_kind_str(arr_t));
2490 		return false;
2491 	}
2492 	arr_info = btf_array(arr_t);
2493 	*res = arr_info->nelems;
2494 	return true;
2495 }
2496 
2497 static bool get_map_field_long(const char *map_name, const struct btf *btf,
2498 			       const struct btf_member *m, __u64 *res)
2499 {
2500 	const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
2501 	const char *name = btf__name_by_offset(btf, m->name_off);
2502 
2503 	if (btf_is_ptr(t)) {
2504 		__u32 res32;
2505 		bool ret;
2506 
2507 		ret = get_map_field_int(map_name, btf, m, &res32);
2508 		if (ret)
2509 			*res = (__u64)res32;
2510 		return ret;
2511 	}
2512 
2513 	if (!btf_is_enum(t) && !btf_is_enum64(t)) {
2514 		pr_warn("map '%s': attr '%s': expected ENUM or ENUM64, got %s.\n",
2515 			map_name, name, btf_kind_str(t));
2516 		return false;
2517 	}
2518 
2519 	if (btf_vlen(t) != 1) {
2520 		pr_warn("map '%s': attr '%s': invalid __ulong\n",
2521 			map_name, name);
2522 		return false;
2523 	}
2524 
2525 	if (btf_is_enum(t)) {
2526 		const struct btf_enum *e = btf_enum(t);
2527 
2528 		*res = e->val;
2529 	} else {
2530 		const struct btf_enum64 *e = btf_enum64(t);
2531 
2532 		*res = btf_enum64_value(e);
2533 	}
2534 	return true;
2535 }
2536 
2537 static int pathname_concat(char *buf, size_t buf_sz, const char *path, const char *name)
2538 {
2539 	int len;
2540 
2541 	len = snprintf(buf, buf_sz, "%s/%s", path, name);
2542 	if (len < 0)
2543 		return -EINVAL;
2544 	if (len >= buf_sz)
2545 		return -ENAMETOOLONG;
2546 
2547 	return 0;
2548 }
2549 
2550 static int build_map_pin_path(struct bpf_map *map, const char *path)
2551 {
2552 	char buf[PATH_MAX];
2553 	int err;
2554 
2555 	if (!path)
2556 		path = BPF_FS_DEFAULT_PATH;
2557 
2558 	err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
2559 	if (err)
2560 		return err;
2561 
2562 	return bpf_map__set_pin_path(map, buf);
2563 }
2564 
2565 /* should match definition in bpf_helpers.h */
2566 enum libbpf_pin_type {
2567 	LIBBPF_PIN_NONE,
2568 	/* PIN_BY_NAME: pin maps by name (in /sys/fs/bpf by default) */
2569 	LIBBPF_PIN_BY_NAME,
2570 };
2571 
2572 int parse_btf_map_def(const char *map_name, struct btf *btf,
2573 		      const struct btf_type *def_t, bool strict,
2574 		      struct btf_map_def *map_def, struct btf_map_def *inner_def)
2575 {
2576 	const struct btf_type *t;
2577 	const struct btf_member *m;
2578 	bool is_inner = inner_def == NULL;
2579 	int vlen, i;
2580 
2581 	vlen = btf_vlen(def_t);
2582 	m = btf_members(def_t);
2583 	for (i = 0; i < vlen; i++, m++) {
2584 		const char *name = btf__name_by_offset(btf, m->name_off);
2585 
2586 		if (!name) {
2587 			pr_warn("map '%s': invalid field #%d.\n", map_name, i);
2588 			return -EINVAL;
2589 		}
2590 		if (strcmp(name, "type") == 0) {
2591 			if (!get_map_field_int(map_name, btf, m, &map_def->map_type))
2592 				return -EINVAL;
2593 			map_def->parts |= MAP_DEF_MAP_TYPE;
2594 		} else if (strcmp(name, "max_entries") == 0) {
2595 			if (!get_map_field_int(map_name, btf, m, &map_def->max_entries))
2596 				return -EINVAL;
2597 			map_def->parts |= MAP_DEF_MAX_ENTRIES;
2598 		} else if (strcmp(name, "map_flags") == 0) {
2599 			if (!get_map_field_int(map_name, btf, m, &map_def->map_flags))
2600 				return -EINVAL;
2601 			map_def->parts |= MAP_DEF_MAP_FLAGS;
2602 		} else if (strcmp(name, "numa_node") == 0) {
2603 			if (!get_map_field_int(map_name, btf, m, &map_def->numa_node))
2604 				return -EINVAL;
2605 			map_def->parts |= MAP_DEF_NUMA_NODE;
2606 		} else if (strcmp(name, "key_size") == 0) {
2607 			__u32 sz;
2608 
2609 			if (!get_map_field_int(map_name, btf, m, &sz))
2610 				return -EINVAL;
2611 			if (map_def->key_size && map_def->key_size != sz) {
2612 				pr_warn("map '%s': conflicting key size %u != %u.\n",
2613 					map_name, map_def->key_size, sz);
2614 				return -EINVAL;
2615 			}
2616 			map_def->key_size = sz;
2617 			map_def->parts |= MAP_DEF_KEY_SIZE;
2618 		} else if (strcmp(name, "key") == 0) {
2619 			__s64 sz;
2620 
2621 			t = btf__type_by_id(btf, m->type);
2622 			if (!t) {
2623 				pr_warn("map '%s': key type [%d] not found.\n",
2624 					map_name, m->type);
2625 				return -EINVAL;
2626 			}
2627 			if (!btf_is_ptr(t)) {
2628 				pr_warn("map '%s': key spec is not PTR: %s.\n",
2629 					map_name, btf_kind_str(t));
2630 				return -EINVAL;
2631 			}
2632 			sz = btf__resolve_size(btf, t->type);
2633 			if (sz < 0) {
2634 				pr_warn("map '%s': can't determine key size for type [%u]: %zd.\n",
2635 					map_name, t->type, (ssize_t)sz);
2636 				return sz;
2637 			}
2638 			if (map_def->key_size && map_def->key_size != sz) {
2639 				pr_warn("map '%s': conflicting key size %u != %zd.\n",
2640 					map_name, map_def->key_size, (ssize_t)sz);
2641 				return -EINVAL;
2642 			}
2643 			map_def->key_size = sz;
2644 			map_def->key_type_id = t->type;
2645 			map_def->parts |= MAP_DEF_KEY_SIZE | MAP_DEF_KEY_TYPE;
2646 		} else if (strcmp(name, "value_size") == 0) {
2647 			__u32 sz;
2648 
2649 			if (!get_map_field_int(map_name, btf, m, &sz))
2650 				return -EINVAL;
2651 			if (map_def->value_size && map_def->value_size != sz) {
2652 				pr_warn("map '%s': conflicting value size %u != %u.\n",
2653 					map_name, map_def->value_size, sz);
2654 				return -EINVAL;
2655 			}
2656 			map_def->value_size = sz;
2657 			map_def->parts |= MAP_DEF_VALUE_SIZE;
2658 		} else if (strcmp(name, "value") == 0) {
2659 			__s64 sz;
2660 
2661 			t = btf__type_by_id(btf, m->type);
2662 			if (!t) {
2663 				pr_warn("map '%s': value type [%d] not found.\n",
2664 					map_name, m->type);
2665 				return -EINVAL;
2666 			}
2667 			if (!btf_is_ptr(t)) {
2668 				pr_warn("map '%s': value spec is not PTR: %s.\n",
2669 					map_name, btf_kind_str(t));
2670 				return -EINVAL;
2671 			}
2672 			sz = btf__resolve_size(btf, t->type);
2673 			if (sz < 0) {
2674 				pr_warn("map '%s': can't determine value size for type [%u]: %zd.\n",
2675 					map_name, t->type, (ssize_t)sz);
2676 				return sz;
2677 			}
2678 			if (map_def->value_size && map_def->value_size != sz) {
2679 				pr_warn("map '%s': conflicting value size %u != %zd.\n",
2680 					map_name, map_def->value_size, (ssize_t)sz);
2681 				return -EINVAL;
2682 			}
2683 			map_def->value_size = sz;
2684 			map_def->value_type_id = t->type;
2685 			map_def->parts |= MAP_DEF_VALUE_SIZE | MAP_DEF_VALUE_TYPE;
2686 		}
2687 		else if (strcmp(name, "values") == 0) {
2688 			bool is_map_in_map = bpf_map_type__is_map_in_map(map_def->map_type);
2689 			bool is_prog_array = map_def->map_type == BPF_MAP_TYPE_PROG_ARRAY;
2690 			const char *desc = is_map_in_map ? "map-in-map inner" : "prog-array value";
2691 			char inner_map_name[128];
2692 			int err;
2693 
2694 			if (is_inner) {
2695 				pr_warn("map '%s': multi-level inner maps not supported.\n",
2696 					map_name);
2697 				return -ENOTSUP;
2698 			}
2699 			if (i != vlen - 1) {
2700 				pr_warn("map '%s': '%s' member should be last.\n",
2701 					map_name, name);
2702 				return -EINVAL;
2703 			}
2704 			if (!is_map_in_map && !is_prog_array) {
2705 				pr_warn("map '%s': should be map-in-map or prog-array.\n",
2706 					map_name);
2707 				return -ENOTSUP;
2708 			}
2709 			if (map_def->value_size && map_def->value_size != 4) {
2710 				pr_warn("map '%s': conflicting value size %u != 4.\n",
2711 					map_name, map_def->value_size);
2712 				return -EINVAL;
2713 			}
2714 			map_def->value_size = 4;
2715 			t = btf__type_by_id(btf, m->type);
2716 			if (!t) {
2717 				pr_warn("map '%s': %s type [%d] not found.\n",
2718 					map_name, desc, m->type);
2719 				return -EINVAL;
2720 			}
2721 			if (!btf_is_array(t) || btf_array(t)->nelems) {
2722 				pr_warn("map '%s': %s spec is not a zero-sized array.\n",
2723 					map_name, desc);
2724 				return -EINVAL;
2725 			}
2726 			t = skip_mods_and_typedefs(btf, btf_array(t)->type, NULL);
2727 			if (!btf_is_ptr(t)) {
2728 				pr_warn("map '%s': %s def is of unexpected kind %s.\n",
2729 					map_name, desc, btf_kind_str(t));
2730 				return -EINVAL;
2731 			}
2732 			t = skip_mods_and_typedefs(btf, t->type, NULL);
2733 			if (is_prog_array) {
2734 				if (!btf_is_func_proto(t)) {
2735 					pr_warn("map '%s': prog-array value def is of unexpected kind %s.\n",
2736 						map_name, btf_kind_str(t));
2737 					return -EINVAL;
2738 				}
2739 				continue;
2740 			}
2741 			if (!btf_is_struct(t)) {
2742 				pr_warn("map '%s': map-in-map inner def is of unexpected kind %s.\n",
2743 					map_name, btf_kind_str(t));
2744 				return -EINVAL;
2745 			}
2746 
2747 			snprintf(inner_map_name, sizeof(inner_map_name), "%s.inner", map_name);
2748 			err = parse_btf_map_def(inner_map_name, btf, t, strict, inner_def, NULL);
2749 			if (err)
2750 				return err;
2751 
2752 			map_def->parts |= MAP_DEF_INNER_MAP;
2753 		} else if (strcmp(name, "pinning") == 0) {
2754 			__u32 val;
2755 
2756 			if (is_inner) {
2757 				pr_warn("map '%s': inner def can't be pinned.\n", map_name);
2758 				return -EINVAL;
2759 			}
2760 			if (!get_map_field_int(map_name, btf, m, &val))
2761 				return -EINVAL;
2762 			if (val != LIBBPF_PIN_NONE && val != LIBBPF_PIN_BY_NAME) {
2763 				pr_warn("map '%s': invalid pinning value %u.\n",
2764 					map_name, val);
2765 				return -EINVAL;
2766 			}
2767 			map_def->pinning = val;
2768 			map_def->parts |= MAP_DEF_PINNING;
2769 		} else if (strcmp(name, "map_extra") == 0) {
2770 			__u64 map_extra;
2771 
2772 			if (!get_map_field_long(map_name, btf, m, &map_extra))
2773 				return -EINVAL;
2774 			map_def->map_extra = map_extra;
2775 			map_def->parts |= MAP_DEF_MAP_EXTRA;
2776 		} else {
2777 			if (strict) {
2778 				pr_warn("map '%s': unknown field '%s'.\n", map_name, name);
2779 				return -ENOTSUP;
2780 			}
2781 			pr_debug("map '%s': ignoring unknown field '%s'.\n", map_name, name);
2782 		}
2783 	}
2784 
2785 	if (map_def->map_type == BPF_MAP_TYPE_UNSPEC) {
2786 		pr_warn("map '%s': map type isn't specified.\n", map_name);
2787 		return -EINVAL;
2788 	}
2789 
2790 	return 0;
2791 }
2792 
2793 static size_t adjust_ringbuf_sz(size_t sz)
2794 {
2795 	__u32 page_sz = sysconf(_SC_PAGE_SIZE);
2796 	__u32 mul;
2797 
2798 	/* if user forgot to set any size, make sure they see error */
2799 	if (sz == 0)
2800 		return 0;
2801 	/* Kernel expects BPF_MAP_TYPE_RINGBUF's max_entries to be
2802 	 * a power-of-2 multiple of kernel's page size. If user diligently
2803 	 * satisified these conditions, pass the size through.
2804 	 */
2805 	if ((sz % page_sz) == 0 && is_pow_of_2(sz / page_sz))
2806 		return sz;
2807 
2808 	/* Otherwise find closest (page_sz * power_of_2) product bigger than
2809 	 * user-set size to satisfy both user size request and kernel
2810 	 * requirements and substitute correct max_entries for map creation.
2811 	 */
2812 	for (mul = 1; mul <= UINT_MAX / page_sz; mul <<= 1) {
2813 		if (mul * page_sz > sz)
2814 			return mul * page_sz;
2815 	}
2816 
2817 	/* if it's impossible to satisfy the conditions (i.e., user size is
2818 	 * very close to UINT_MAX but is not a power-of-2 multiple of
2819 	 * page_size) then just return original size and let kernel reject it
2820 	 */
2821 	return sz;
2822 }
2823 
2824 static bool map_is_ringbuf(const struct bpf_map *map)
2825 {
2826 	return map->def.type == BPF_MAP_TYPE_RINGBUF ||
2827 	       map->def.type == BPF_MAP_TYPE_USER_RINGBUF;
2828 }
2829 
2830 static void fill_map_from_def(struct bpf_map *map, const struct btf_map_def *def)
2831 {
2832 	map->def.type = def->map_type;
2833 	map->def.key_size = def->key_size;
2834 	map->def.value_size = def->value_size;
2835 	map->def.max_entries = def->max_entries;
2836 	map->def.map_flags = def->map_flags;
2837 	map->map_extra = def->map_extra;
2838 
2839 	map->numa_node = def->numa_node;
2840 	map->btf_key_type_id = def->key_type_id;
2841 	map->btf_value_type_id = def->value_type_id;
2842 
2843 	/* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
2844 	if (map_is_ringbuf(map))
2845 		map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
2846 
2847 	if (def->parts & MAP_DEF_MAP_TYPE)
2848 		pr_debug("map '%s': found type = %u.\n", map->name, def->map_type);
2849 
2850 	if (def->parts & MAP_DEF_KEY_TYPE)
2851 		pr_debug("map '%s': found key [%u], sz = %u.\n",
2852 			 map->name, def->key_type_id, def->key_size);
2853 	else if (def->parts & MAP_DEF_KEY_SIZE)
2854 		pr_debug("map '%s': found key_size = %u.\n", map->name, def->key_size);
2855 
2856 	if (def->parts & MAP_DEF_VALUE_TYPE)
2857 		pr_debug("map '%s': found value [%u], sz = %u.\n",
2858 			 map->name, def->value_type_id, def->value_size);
2859 	else if (def->parts & MAP_DEF_VALUE_SIZE)
2860 		pr_debug("map '%s': found value_size = %u.\n", map->name, def->value_size);
2861 
2862 	if (def->parts & MAP_DEF_MAX_ENTRIES)
2863 		pr_debug("map '%s': found max_entries = %u.\n", map->name, def->max_entries);
2864 	if (def->parts & MAP_DEF_MAP_FLAGS)
2865 		pr_debug("map '%s': found map_flags = 0x%x.\n", map->name, def->map_flags);
2866 	if (def->parts & MAP_DEF_MAP_EXTRA)
2867 		pr_debug("map '%s': found map_extra = 0x%llx.\n", map->name,
2868 			 (unsigned long long)def->map_extra);
2869 	if (def->parts & MAP_DEF_PINNING)
2870 		pr_debug("map '%s': found pinning = %u.\n", map->name, def->pinning);
2871 	if (def->parts & MAP_DEF_NUMA_NODE)
2872 		pr_debug("map '%s': found numa_node = %u.\n", map->name, def->numa_node);
2873 
2874 	if (def->parts & MAP_DEF_INNER_MAP)
2875 		pr_debug("map '%s': found inner map definition.\n", map->name);
2876 }
2877 
2878 static const char *btf_var_linkage_str(__u32 linkage)
2879 {
2880 	switch (linkage) {
2881 	case BTF_VAR_STATIC: return "static";
2882 	case BTF_VAR_GLOBAL_ALLOCATED: return "global";
2883 	case BTF_VAR_GLOBAL_EXTERN: return "extern";
2884 	default: return "unknown";
2885 	}
2886 }
2887 
2888 static int bpf_object__init_user_btf_map(struct bpf_object *obj,
2889 					 const struct btf_type *sec,
2890 					 int var_idx, int sec_idx,
2891 					 const Elf_Data *data, bool strict,
2892 					 const char *pin_root_path)
2893 {
2894 	struct btf_map_def map_def = {}, inner_def = {};
2895 	const struct btf_type *var, *def;
2896 	const struct btf_var_secinfo *vi;
2897 	const struct btf_var *var_extra;
2898 	const char *map_name;
2899 	struct bpf_map *map;
2900 	int err;
2901 
2902 	vi = btf_var_secinfos(sec) + var_idx;
2903 	var = btf__type_by_id(obj->btf, vi->type);
2904 	var_extra = btf_var(var);
2905 	map_name = btf__name_by_offset(obj->btf, var->name_off);
2906 
2907 	if (str_is_empty(map_name)) {
2908 		pr_warn("map #%d: empty name.\n", var_idx);
2909 		return -EINVAL;
2910 	}
2911 	if ((__u64)vi->offset + vi->size > data->d_size) {
2912 		pr_warn("map '%s' BTF data is corrupted.\n", map_name);
2913 		return -EINVAL;
2914 	}
2915 	if (!btf_is_var(var)) {
2916 		pr_warn("map '%s': unexpected var kind %s.\n",
2917 			map_name, btf_kind_str(var));
2918 		return -EINVAL;
2919 	}
2920 	if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED) {
2921 		pr_warn("map '%s': unsupported map linkage %s.\n",
2922 			map_name, btf_var_linkage_str(var_extra->linkage));
2923 		return -EOPNOTSUPP;
2924 	}
2925 
2926 	def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
2927 	if (!btf_is_struct(def)) {
2928 		pr_warn("map '%s': unexpected def kind %s.\n",
2929 			map_name, btf_kind_str(var));
2930 		return -EINVAL;
2931 	}
2932 	if (def->size > vi->size) {
2933 		pr_warn("map '%s': invalid def size.\n", map_name);
2934 		return -EINVAL;
2935 	}
2936 
2937 	map = bpf_object__add_map(obj);
2938 	if (IS_ERR(map))
2939 		return PTR_ERR(map);
2940 	map->name = strdup(map_name);
2941 	if (!map->name) {
2942 		pr_warn("map '%s': failed to alloc map name.\n", map_name);
2943 		return -ENOMEM;
2944 	}
2945 	map->libbpf_type = LIBBPF_MAP_UNSPEC;
2946 	map->def.type = BPF_MAP_TYPE_UNSPEC;
2947 	map->sec_idx = sec_idx;
2948 	map->sec_offset = vi->offset;
2949 	map->btf_var_idx = var_idx;
2950 	pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
2951 		 map_name, map->sec_idx, map->sec_offset);
2952 
2953 	err = parse_btf_map_def(map->name, obj->btf, def, strict, &map_def, &inner_def);
2954 	if (err)
2955 		return err;
2956 
2957 	fill_map_from_def(map, &map_def);
2958 
2959 	if (map_def.pinning == LIBBPF_PIN_BY_NAME) {
2960 		err = build_map_pin_path(map, pin_root_path);
2961 		if (err) {
2962 			pr_warn("map '%s': couldn't build pin path.\n", map->name);
2963 			return err;
2964 		}
2965 	}
2966 
2967 	if (map_def.parts & MAP_DEF_INNER_MAP) {
2968 		map->inner_map = calloc(1, sizeof(*map->inner_map));
2969 		if (!map->inner_map)
2970 			return -ENOMEM;
2971 		map->inner_map->fd = create_placeholder_fd();
2972 		if (map->inner_map->fd < 0)
2973 			return map->inner_map->fd;
2974 		map->inner_map->sec_idx = sec_idx;
2975 		map->inner_map->name = malloc(strlen(map_name) + sizeof(".inner") + 1);
2976 		if (!map->inner_map->name)
2977 			return -ENOMEM;
2978 		sprintf(map->inner_map->name, "%s.inner", map_name);
2979 
2980 		fill_map_from_def(map->inner_map, &inner_def);
2981 	}
2982 
2983 	err = map_fill_btf_type_info(obj, map);
2984 	if (err)
2985 		return err;
2986 
2987 	return 0;
2988 }
2989 
2990 static int init_arena_map_data(struct bpf_object *obj, struct bpf_map *map,
2991 			       const char *sec_name, int sec_idx,
2992 			       void *data, size_t data_sz)
2993 {
2994 	const long page_sz = sysconf(_SC_PAGE_SIZE);
2995 	const size_t data_alloc_sz = roundup(data_sz, page_sz);
2996 	size_t mmap_sz;
2997 
2998 	mmap_sz = bpf_map_mmap_sz(map);
2999 	if (data_alloc_sz > mmap_sz) {
3000 		pr_warn("elf: sec '%s': declared ARENA map size (%zu) is too small to hold global __arena variables of size %zu\n",
3001 			sec_name, mmap_sz, data_sz);
3002 		return -E2BIG;
3003 	}
3004 
3005 	obj->arena_data = malloc(data_sz);
3006 	if (!obj->arena_data)
3007 		return -ENOMEM;
3008 	memcpy(obj->arena_data, data, data_sz);
3009 	obj->arena_data_sz = data_sz;
3010 
3011 	/* place globals at the end of the arena */
3012 	obj->arena_data_off = mmap_sz - data_alloc_sz;
3013 
3014 	/* make bpf_map__init_value() work for ARENA maps */
3015 	map->mmaped = obj->arena_data;
3016 
3017 	return 0;
3018 }
3019 
3020 static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict,
3021 					  const char *pin_root_path)
3022 {
3023 	const struct btf_type *sec = NULL;
3024 	int nr_types, i, vlen, err;
3025 	const struct btf_type *t;
3026 	const char *name;
3027 	Elf_Data *data;
3028 	Elf_Scn *scn;
3029 
3030 	if (obj->efile.btf_maps_shndx < 0)
3031 		return 0;
3032 
3033 	scn = elf_sec_by_idx(obj, obj->efile.btf_maps_shndx);
3034 	data = elf_sec_data(obj, scn);
3035 	if (!data) {
3036 		pr_warn("elf: failed to get %s map definitions for %s\n",
3037 			MAPS_ELF_SEC, obj->path);
3038 		return -EINVAL;
3039 	}
3040 
3041 	nr_types = btf__type_cnt(obj->btf);
3042 	for (i = 1; i < nr_types; i++) {
3043 		t = btf__type_by_id(obj->btf, i);
3044 		if (!btf_is_datasec(t))
3045 			continue;
3046 		name = btf__name_by_offset(obj->btf, t->name_off);
3047 		if (strcmp(name, MAPS_ELF_SEC) == 0) {
3048 			sec = t;
3049 			obj->efile.btf_maps_sec_btf_id = i;
3050 			break;
3051 		}
3052 	}
3053 
3054 	if (!sec) {
3055 		pr_warn("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
3056 		return -ENOENT;
3057 	}
3058 
3059 	vlen = btf_vlen(sec);
3060 	for (i = 0; i < vlen; i++) {
3061 		err = bpf_object__init_user_btf_map(obj, sec, i,
3062 						    obj->efile.btf_maps_shndx,
3063 						    data, strict,
3064 						    pin_root_path);
3065 		if (err)
3066 			return err;
3067 	}
3068 
3069 	for (i = 0; i < obj->nr_maps; i++) {
3070 		struct bpf_map *map = &obj->maps[i];
3071 
3072 		if (map->def.type != BPF_MAP_TYPE_ARENA)
3073 			continue;
3074 
3075 		if (obj->arena_map_idx >= 0) {
3076 			pr_warn("map '%s': only single ARENA map is supported (map '%s' is also ARENA)\n",
3077 				map->name, obj->maps[obj->arena_map_idx].name);
3078 			return -EINVAL;
3079 		}
3080 		obj->arena_map_idx = i;
3081 
3082 		if (obj->efile.arena_data) {
3083 			err = init_arena_map_data(obj, map, ARENA_SEC, obj->efile.arena_data_shndx,
3084 						  obj->efile.arena_data->d_buf,
3085 						  obj->efile.arena_data->d_size);
3086 			if (err)
3087 				return err;
3088 		}
3089 	}
3090 	if (obj->efile.arena_data && obj->arena_map_idx < 0) {
3091 		pr_warn("elf: sec '%s': to use global __arena variables the ARENA map should be explicitly declared in SEC(\".maps\")\n",
3092 			ARENA_SEC);
3093 		return -ENOENT;
3094 	}
3095 
3096 	return 0;
3097 }
3098 
3099 static int bpf_object__init_maps(struct bpf_object *obj,
3100 				 const struct bpf_object_open_opts *opts)
3101 {
3102 	const char *pin_root_path;
3103 	bool strict;
3104 	int err = 0;
3105 
3106 	strict = !OPTS_GET(opts, relaxed_maps, false);
3107 	pin_root_path = OPTS_GET(opts, pin_root_path, NULL);
3108 
3109 	err = bpf_object__init_user_btf_maps(obj, strict, pin_root_path);
3110 	err = err ?: bpf_object__init_global_data_maps(obj);
3111 	err = err ?: bpf_object__init_kconfig_map(obj);
3112 	err = err ?: bpf_object_init_struct_ops(obj);
3113 
3114 	return err;
3115 }
3116 
3117 static bool section_have_execinstr(struct bpf_object *obj, int idx)
3118 {
3119 	Elf64_Shdr *sh;
3120 
3121 	sh = elf_sec_hdr(obj, elf_sec_by_idx(obj, idx));
3122 	if (!sh)
3123 		return false;
3124 
3125 	return sh->sh_flags & SHF_EXECINSTR;
3126 }
3127 
3128 static bool starts_with_qmark(const char *s)
3129 {
3130 	return s && s[0] == '?';
3131 }
3132 
3133 static bool btf_needs_sanitization(struct bpf_object *obj)
3134 {
3135 	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
3136 	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
3137 	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
3138 	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
3139 	bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
3140 	bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
3141 	bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
3142 	bool has_qmark_datasec = kernel_supports(obj, FEAT_BTF_QMARK_DATASEC);
3143 
3144 	return !has_func || !has_datasec || !has_func_global || !has_float ||
3145 	       !has_decl_tag || !has_type_tag || !has_enum64 || !has_qmark_datasec;
3146 }
3147 
3148 static int bpf_object__sanitize_btf(struct bpf_object *obj, struct btf *btf)
3149 {
3150 	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
3151 	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
3152 	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
3153 	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
3154 	bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
3155 	bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
3156 	bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
3157 	bool has_qmark_datasec = kernel_supports(obj, FEAT_BTF_QMARK_DATASEC);
3158 	int enum64_placeholder_id = 0;
3159 	struct btf_type *t;
3160 	int i, j, vlen;
3161 
3162 	for (i = 1; i < btf__type_cnt(btf); i++) {
3163 		t = (struct btf_type *)btf__type_by_id(btf, i);
3164 
3165 		if ((!has_datasec && btf_is_var(t)) || (!has_decl_tag && btf_is_decl_tag(t))) {
3166 			/* replace VAR/DECL_TAG with INT */
3167 			t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
3168 			/*
3169 			 * using size = 1 is the safest choice, 4 will be too
3170 			 * big and cause kernel BTF validation failure if
3171 			 * original variable took less than 4 bytes
3172 			 */
3173 			t->size = 1;
3174 			*(int *)(t + 1) = BTF_INT_ENC(0, 0, 8);
3175 		} else if (!has_datasec && btf_is_datasec(t)) {
3176 			/* replace DATASEC with STRUCT */
3177 			const struct btf_var_secinfo *v = btf_var_secinfos(t);
3178 			struct btf_member *m = btf_members(t);
3179 			struct btf_type *vt;
3180 			char *name;
3181 
3182 			name = (char *)btf__name_by_offset(btf, t->name_off);
3183 			while (*name) {
3184 				if (*name == '.' || *name == '?')
3185 					*name = '_';
3186 				name++;
3187 			}
3188 
3189 			vlen = btf_vlen(t);
3190 			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
3191 			for (j = 0; j < vlen; j++, v++, m++) {
3192 				/* order of field assignments is important */
3193 				m->offset = v->offset * 8;
3194 				m->type = v->type;
3195 				/* preserve variable name as member name */
3196 				vt = (void *)btf__type_by_id(btf, v->type);
3197 				m->name_off = vt->name_off;
3198 			}
3199 		} else if (!has_qmark_datasec && btf_is_datasec(t) &&
3200 			   starts_with_qmark(btf__name_by_offset(btf, t->name_off))) {
3201 			/* replace '?' prefix with '_' for DATASEC names */
3202 			char *name;
3203 
3204 			name = (char *)btf__name_by_offset(btf, t->name_off);
3205 			if (name[0] == '?')
3206 				name[0] = '_';
3207 		} else if (!has_func && btf_is_func_proto(t)) {
3208 			/* replace FUNC_PROTO with ENUM */
3209 			vlen = btf_vlen(t);
3210 			t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
3211 			t->size = sizeof(__u32); /* kernel enforced */
3212 		} else if (!has_func && btf_is_func(t)) {
3213 			/* replace FUNC with TYPEDEF */
3214 			t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
3215 		} else if (!has_func_global && btf_is_func(t)) {
3216 			/* replace BTF_FUNC_GLOBAL with BTF_FUNC_STATIC */
3217 			t->info = BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0);
3218 		} else if (!has_float && btf_is_float(t)) {
3219 			/* replace FLOAT with an equally-sized empty STRUCT;
3220 			 * since C compilers do not accept e.g. "float" as a
3221 			 * valid struct name, make it anonymous
3222 			 */
3223 			t->name_off = 0;
3224 			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, 0);
3225 		} else if (!has_type_tag && btf_is_type_tag(t)) {
3226 			/* replace TYPE_TAG with a CONST */
3227 			t->name_off = 0;
3228 			t->info = BTF_INFO_ENC(BTF_KIND_CONST, 0, 0);
3229 		} else if (!has_enum64 && btf_is_enum(t)) {
3230 			/* clear the kflag */
3231 			t->info = btf_type_info(btf_kind(t), btf_vlen(t), false);
3232 		} else if (!has_enum64 && btf_is_enum64(t)) {
3233 			/* replace ENUM64 with a union */
3234 			struct btf_member *m;
3235 
3236 			if (enum64_placeholder_id == 0) {
3237 				enum64_placeholder_id = btf__add_int(btf, "enum64_placeholder", 1, 0);
3238 				if (enum64_placeholder_id < 0)
3239 					return enum64_placeholder_id;
3240 
3241 				t = (struct btf_type *)btf__type_by_id(btf, i);
3242 			}
3243 
3244 			m = btf_members(t);
3245 			vlen = btf_vlen(t);
3246 			t->info = BTF_INFO_ENC(BTF_KIND_UNION, 0, vlen);
3247 			for (j = 0; j < vlen; j++, m++) {
3248 				m->type = enum64_placeholder_id;
3249 				m->offset = 0;
3250 			}
3251 		}
3252 	}
3253 
3254 	return 0;
3255 }
3256 
3257 static bool libbpf_needs_btf(const struct bpf_object *obj)
3258 {
3259 	return obj->efile.btf_maps_shndx >= 0 ||
3260 	       obj->efile.has_st_ops ||
3261 	       obj->nr_extern > 0;
3262 }
3263 
3264 static bool kernel_needs_btf(const struct bpf_object *obj)
3265 {
3266 	return obj->efile.has_st_ops;
3267 }
3268 
3269 static int bpf_object__init_btf(struct bpf_object *obj,
3270 				Elf_Data *btf_data,
3271 				Elf_Data *btf_ext_data)
3272 {
3273 	int err = -ENOENT;
3274 
3275 	if (btf_data) {
3276 		obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
3277 		err = libbpf_get_error(obj->btf);
3278 		if (err) {
3279 			obj->btf = NULL;
3280 			pr_warn("Error loading ELF section %s: %s.\n", BTF_ELF_SEC, errstr(err));
3281 			goto out;
3282 		}
3283 		/* enforce 8-byte pointers for BPF-targeted BTFs */
3284 		btf__set_pointer_size(obj->btf, 8);
3285 	}
3286 	if (btf_ext_data) {
3287 		struct btf_ext_info *ext_segs[3];
3288 		int seg_num, sec_num;
3289 
3290 		if (!obj->btf) {
3291 			pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
3292 				 BTF_EXT_ELF_SEC, BTF_ELF_SEC);
3293 			goto out;
3294 		}
3295 		obj->btf_ext = btf_ext__new(btf_ext_data->d_buf, btf_ext_data->d_size);
3296 		err = libbpf_get_error(obj->btf_ext);
3297 		if (err) {
3298 			pr_warn("Error loading ELF section %s: %s. Ignored and continue.\n",
3299 				BTF_EXT_ELF_SEC, errstr(err));
3300 			obj->btf_ext = NULL;
3301 			goto out;
3302 		}
3303 
3304 		/* setup .BTF.ext to ELF section mapping */
3305 		ext_segs[0] = &obj->btf_ext->func_info;
3306 		ext_segs[1] = &obj->btf_ext->line_info;
3307 		ext_segs[2] = &obj->btf_ext->core_relo_info;
3308 		for (seg_num = 0; seg_num < ARRAY_SIZE(ext_segs); seg_num++) {
3309 			struct btf_ext_info *seg = ext_segs[seg_num];
3310 			const struct btf_ext_info_sec *sec;
3311 			const char *sec_name;
3312 			Elf_Scn *scn;
3313 
3314 			if (seg->sec_cnt == 0)
3315 				continue;
3316 
3317 			seg->sec_idxs = calloc(seg->sec_cnt, sizeof(*seg->sec_idxs));
3318 			if (!seg->sec_idxs) {
3319 				err = -ENOMEM;
3320 				goto out;
3321 			}
3322 
3323 			sec_num = 0;
3324 			for_each_btf_ext_sec(seg, sec) {
3325 				/* preventively increment index to avoid doing
3326 				 * this before every continue below
3327 				 */
3328 				sec_num++;
3329 
3330 				sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
3331 				if (str_is_empty(sec_name))
3332 					continue;
3333 				scn = elf_sec_by_name(obj, sec_name);
3334 				if (!scn)
3335 					continue;
3336 
3337 				seg->sec_idxs[sec_num - 1] = elf_ndxscn(scn);
3338 			}
3339 		}
3340 	}
3341 out:
3342 	if (err && libbpf_needs_btf(obj)) {
3343 		pr_warn("BTF is required, but is missing or corrupted.\n");
3344 		return err;
3345 	}
3346 	return 0;
3347 }
3348 
3349 static int compare_vsi_off(const void *_a, const void *_b)
3350 {
3351 	const struct btf_var_secinfo *a = _a;
3352 	const struct btf_var_secinfo *b = _b;
3353 
3354 	return a->offset - b->offset;
3355 }
3356 
3357 static int btf_fixup_datasec(struct bpf_object *obj, struct btf *btf,
3358 			     struct btf_type *t)
3359 {
3360 	__u32 size = 0, i, vars = btf_vlen(t);
3361 	const char *sec_name = btf__name_by_offset(btf, t->name_off);
3362 	struct btf_var_secinfo *vsi;
3363 	bool fixup_offsets = false;
3364 	int err;
3365 
3366 	if (!sec_name) {
3367 		pr_debug("No name found in string section for DATASEC kind.\n");
3368 		return -ENOENT;
3369 	}
3370 
3371 	/* Extern-backing datasecs (.ksyms, .kconfig) have their size and
3372 	 * variable offsets set at the previous step. Further, not every
3373 	 * extern BTF VAR has corresponding ELF symbol preserved, so we skip
3374 	 * all fixups altogether for such sections and go straight to sorting
3375 	 * VARs within their DATASEC.
3376 	 */
3377 	if (strcmp(sec_name, KCONFIG_SEC) == 0 || strcmp(sec_name, KSYMS_SEC) == 0)
3378 		goto sort_vars;
3379 
3380 	/* Clang leaves DATASEC size and VAR offsets as zeroes, so we need to
3381 	 * fix this up. But BPF static linker already fixes this up and fills
3382 	 * all the sizes and offsets during static linking. So this step has
3383 	 * to be optional. But the STV_HIDDEN handling is non-optional for any
3384 	 * non-extern DATASEC, so the variable fixup loop below handles both
3385 	 * functions at the same time, paying the cost of BTF VAR <-> ELF
3386 	 * symbol matching just once.
3387 	 */
3388 	if (t->size == 0) {
3389 		err = find_elf_sec_sz(obj, sec_name, &size);
3390 		if (err || !size) {
3391 			pr_debug("sec '%s': failed to determine size from ELF: size %u, err %s\n",
3392 				 sec_name, size, errstr(err));
3393 			return -ENOENT;
3394 		}
3395 
3396 		t->size = size;
3397 		fixup_offsets = true;
3398 	}
3399 
3400 	for (i = 0, vsi = btf_var_secinfos(t); i < vars; i++, vsi++) {
3401 		const struct btf_type *t_var;
3402 		struct btf_var *var;
3403 		const char *var_name;
3404 		Elf64_Sym *sym;
3405 
3406 		t_var = btf__type_by_id(btf, vsi->type);
3407 		if (!t_var || !btf_is_var(t_var)) {
3408 			pr_debug("sec '%s': unexpected non-VAR type found\n", sec_name);
3409 			return -EINVAL;
3410 		}
3411 
3412 		var = btf_var(t_var);
3413 		if (var->linkage == BTF_VAR_STATIC || var->linkage == BTF_VAR_GLOBAL_EXTERN)
3414 			continue;
3415 
3416 		var_name = btf__name_by_offset(btf, t_var->name_off);
3417 		if (!var_name) {
3418 			pr_debug("sec '%s': failed to find name of DATASEC's member #%d\n",
3419 				 sec_name, i);
3420 			return -ENOENT;
3421 		}
3422 
3423 		sym = find_elf_var_sym(obj, var_name);
3424 		if (IS_ERR(sym)) {
3425 			pr_debug("sec '%s': failed to find ELF symbol for VAR '%s'\n",
3426 				 sec_name, var_name);
3427 			return -ENOENT;
3428 		}
3429 
3430 		if (fixup_offsets)
3431 			vsi->offset = sym->st_value;
3432 
3433 		/* if variable is a global/weak symbol, but has restricted
3434 		 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF VAR
3435 		 * as static. This follows similar logic for functions (BPF
3436 		 * subprogs) and influences libbpf's further decisions about
3437 		 * whether to make global data BPF array maps as
3438 		 * BPF_F_MMAPABLE.
3439 		 */
3440 		if (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
3441 		    || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL)
3442 			var->linkage = BTF_VAR_STATIC;
3443 	}
3444 
3445 sort_vars:
3446 	qsort(btf_var_secinfos(t), vars, sizeof(*vsi), compare_vsi_off);
3447 	return 0;
3448 }
3449 
3450 static int bpf_object_fixup_btf(struct bpf_object *obj)
3451 {
3452 	int i, n, err = 0;
3453 
3454 	if (!obj->btf)
3455 		return 0;
3456 
3457 	n = btf__type_cnt(obj->btf);
3458 	for (i = 1; i < n; i++) {
3459 		struct btf_type *t = btf_type_by_id(obj->btf, i);
3460 
3461 		/* Loader needs to fix up some of the things compiler
3462 		 * couldn't get its hands on while emitting BTF. This
3463 		 * is section size and global variable offset. We use
3464 		 * the info from the ELF itself for this purpose.
3465 		 */
3466 		if (btf_is_datasec(t)) {
3467 			err = btf_fixup_datasec(obj, obj->btf, t);
3468 			if (err)
3469 				return err;
3470 		}
3471 	}
3472 
3473 	return 0;
3474 }
3475 
3476 static bool prog_needs_vmlinux_btf(struct bpf_program *prog)
3477 {
3478 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
3479 	    prog->type == BPF_PROG_TYPE_LSM)
3480 		return true;
3481 
3482 	/* BPF_PROG_TYPE_TRACING programs which do not attach to other programs
3483 	 * also need vmlinux BTF
3484 	 */
3485 	if (prog->type == BPF_PROG_TYPE_TRACING && !prog->attach_prog_fd)
3486 		return true;
3487 
3488 	return false;
3489 }
3490 
3491 static bool map_needs_vmlinux_btf(struct bpf_map *map)
3492 {
3493 	return bpf_map__is_struct_ops(map);
3494 }
3495 
3496 static bool obj_needs_vmlinux_btf(const struct bpf_object *obj)
3497 {
3498 	struct bpf_program *prog;
3499 	struct bpf_map *map;
3500 	int i;
3501 
3502 	/* CO-RE relocations need kernel BTF, only when btf_custom_path
3503 	 * is not specified
3504 	 */
3505 	if (obj->btf_ext && obj->btf_ext->core_relo_info.len && !obj->btf_custom_path)
3506 		return true;
3507 
3508 	/* Support for typed ksyms needs kernel BTF */
3509 	for (i = 0; i < obj->nr_extern; i++) {
3510 		const struct extern_desc *ext;
3511 
3512 		ext = &obj->externs[i];
3513 		if (ext->type == EXT_KSYM && ext->ksym.type_id)
3514 			return true;
3515 	}
3516 
3517 	bpf_object__for_each_program(prog, obj) {
3518 		if (!prog->autoload)
3519 			continue;
3520 		if (prog_needs_vmlinux_btf(prog))
3521 			return true;
3522 	}
3523 
3524 	bpf_object__for_each_map(map, obj) {
3525 		if (map_needs_vmlinux_btf(map))
3526 			return true;
3527 	}
3528 
3529 	return false;
3530 }
3531 
3532 static int bpf_object__load_vmlinux_btf(struct bpf_object *obj, bool force)
3533 {
3534 	int err;
3535 
3536 	/* btf_vmlinux could be loaded earlier */
3537 	if (obj->btf_vmlinux || obj->gen_loader)
3538 		return 0;
3539 
3540 	if (!force && !obj_needs_vmlinux_btf(obj))
3541 		return 0;
3542 
3543 	obj->btf_vmlinux = btf__load_vmlinux_btf();
3544 	err = libbpf_get_error(obj->btf_vmlinux);
3545 	if (err) {
3546 		pr_warn("Error loading vmlinux BTF: %s\n", errstr(err));
3547 		obj->btf_vmlinux = NULL;
3548 		return err;
3549 	}
3550 	return 0;
3551 }
3552 
3553 static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
3554 {
3555 	struct btf *kern_btf = obj->btf;
3556 	bool btf_mandatory, sanitize;
3557 	int i, err = 0;
3558 
3559 	if (!obj->btf)
3560 		return 0;
3561 
3562 	if (!kernel_supports(obj, FEAT_BTF)) {
3563 		if (kernel_needs_btf(obj)) {
3564 			err = -EOPNOTSUPP;
3565 			goto report;
3566 		}
3567 		pr_debug("Kernel doesn't support BTF, skipping uploading it.\n");
3568 		return 0;
3569 	}
3570 
3571 	/* Even though some subprogs are global/weak, user might prefer more
3572 	 * permissive BPF verification process that BPF verifier performs for
3573 	 * static functions, taking into account more context from the caller
3574 	 * functions. In such case, they need to mark such subprogs with
3575 	 * __attribute__((visibility("hidden"))) and libbpf will adjust
3576 	 * corresponding FUNC BTF type to be marked as static and trigger more
3577 	 * involved BPF verification process.
3578 	 */
3579 	for (i = 0; i < obj->nr_programs; i++) {
3580 		struct bpf_program *prog = &obj->programs[i];
3581 		struct btf_type *t;
3582 		const char *name;
3583 		int j, n;
3584 
3585 		if (!prog->mark_btf_static || !prog_is_subprog(obj, prog))
3586 			continue;
3587 
3588 		n = btf__type_cnt(obj->btf);
3589 		for (j = 1; j < n; j++) {
3590 			t = btf_type_by_id(obj->btf, j);
3591 			if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL)
3592 				continue;
3593 
3594 			name = btf__str_by_offset(obj->btf, t->name_off);
3595 			if (strcmp(name, prog->name) != 0)
3596 				continue;
3597 
3598 			t->info = btf_type_info(BTF_KIND_FUNC, BTF_FUNC_STATIC, 0);
3599 			break;
3600 		}
3601 	}
3602 
3603 	sanitize = btf_needs_sanitization(obj);
3604 	if (sanitize) {
3605 		const void *raw_data;
3606 		__u32 sz;
3607 
3608 		/* clone BTF to sanitize a copy and leave the original intact */
3609 		raw_data = btf__raw_data(obj->btf, &sz);
3610 		kern_btf = btf__new(raw_data, sz);
3611 		err = libbpf_get_error(kern_btf);
3612 		if (err)
3613 			return err;
3614 
3615 		/* enforce 8-byte pointers for BPF-targeted BTFs */
3616 		btf__set_pointer_size(obj->btf, 8);
3617 		err = bpf_object__sanitize_btf(obj, kern_btf);
3618 		if (err)
3619 			return err;
3620 	}
3621 
3622 	if (obj->gen_loader) {
3623 		__u32 raw_size = 0;
3624 		const void *raw_data = btf__raw_data(kern_btf, &raw_size);
3625 
3626 		if (!raw_data)
3627 			return -ENOMEM;
3628 		bpf_gen__load_btf(obj->gen_loader, raw_data, raw_size);
3629 		/* Pretend to have valid FD to pass various fd >= 0 checks.
3630 		 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
3631 		 */
3632 		btf__set_fd(kern_btf, 0);
3633 	} else {
3634 		/* currently BPF_BTF_LOAD only supports log_level 1 */
3635 		err = btf_load_into_kernel(kern_btf, obj->log_buf, obj->log_size,
3636 					   obj->log_level ? 1 : 0, obj->token_fd);
3637 	}
3638 	if (sanitize) {
3639 		if (!err) {
3640 			/* move fd to libbpf's BTF */
3641 			btf__set_fd(obj->btf, btf__fd(kern_btf));
3642 			btf__set_fd(kern_btf, -1);
3643 		}
3644 		btf__free(kern_btf);
3645 	}
3646 report:
3647 	if (err) {
3648 		btf_mandatory = kernel_needs_btf(obj);
3649 		if (btf_mandatory) {
3650 			pr_warn("Error loading .BTF into kernel: %s. BTF is mandatory, can't proceed.\n",
3651 				errstr(err));
3652 		} else {
3653 			pr_info("Error loading .BTF into kernel: %s. BTF is optional, ignoring.\n",
3654 				errstr(err));
3655 			err = 0;
3656 		}
3657 	}
3658 	return err;
3659 }
3660 
3661 static const char *elf_sym_str(const struct bpf_object *obj, size_t off)
3662 {
3663 	const char *name;
3664 
3665 	name = elf_strptr(obj->efile.elf, obj->efile.strtabidx, off);
3666 	if (!name) {
3667 		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3668 			off, obj->path, elf_errmsg(-1));
3669 		return NULL;
3670 	}
3671 
3672 	return name;
3673 }
3674 
3675 static const char *elf_sec_str(const struct bpf_object *obj, size_t off)
3676 {
3677 	const char *name;
3678 
3679 	name = elf_strptr(obj->efile.elf, obj->efile.shstrndx, off);
3680 	if (!name) {
3681 		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3682 			off, obj->path, elf_errmsg(-1));
3683 		return NULL;
3684 	}
3685 
3686 	return name;
3687 }
3688 
3689 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx)
3690 {
3691 	Elf_Scn *scn;
3692 
3693 	scn = elf_getscn(obj->efile.elf, idx);
3694 	if (!scn) {
3695 		pr_warn("elf: failed to get section(%zu) from %s: %s\n",
3696 			idx, obj->path, elf_errmsg(-1));
3697 		return NULL;
3698 	}
3699 	return scn;
3700 }
3701 
3702 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name)
3703 {
3704 	Elf_Scn *scn = NULL;
3705 	Elf *elf = obj->efile.elf;
3706 	const char *sec_name;
3707 
3708 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3709 		sec_name = elf_sec_name(obj, scn);
3710 		if (!sec_name)
3711 			return NULL;
3712 
3713 		if (strcmp(sec_name, name) != 0)
3714 			continue;
3715 
3716 		return scn;
3717 	}
3718 	return NULL;
3719 }
3720 
3721 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn)
3722 {
3723 	Elf64_Shdr *shdr;
3724 
3725 	if (!scn)
3726 		return NULL;
3727 
3728 	shdr = elf64_getshdr(scn);
3729 	if (!shdr) {
3730 		pr_warn("elf: failed to get section(%zu) header from %s: %s\n",
3731 			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3732 		return NULL;
3733 	}
3734 
3735 	return shdr;
3736 }
3737 
3738 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn)
3739 {
3740 	const char *name;
3741 	Elf64_Shdr *sh;
3742 
3743 	if (!scn)
3744 		return NULL;
3745 
3746 	sh = elf_sec_hdr(obj, scn);
3747 	if (!sh)
3748 		return NULL;
3749 
3750 	name = elf_sec_str(obj, sh->sh_name);
3751 	if (!name) {
3752 		pr_warn("elf: failed to get section(%zu) name from %s: %s\n",
3753 			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3754 		return NULL;
3755 	}
3756 
3757 	return name;
3758 }
3759 
3760 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn)
3761 {
3762 	Elf_Data *data;
3763 
3764 	if (!scn)
3765 		return NULL;
3766 
3767 	data = elf_getdata(scn, 0);
3768 	if (!data) {
3769 		pr_warn("elf: failed to get section(%zu) %s data from %s: %s\n",
3770 			elf_ndxscn(scn), elf_sec_name(obj, scn) ?: "<?>",
3771 			obj->path, elf_errmsg(-1));
3772 		return NULL;
3773 	}
3774 
3775 	return data;
3776 }
3777 
3778 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx)
3779 {
3780 	if (idx >= obj->efile.symbols->d_size / sizeof(Elf64_Sym))
3781 		return NULL;
3782 
3783 	return (Elf64_Sym *)obj->efile.symbols->d_buf + idx;
3784 }
3785 
3786 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx)
3787 {
3788 	if (idx >= data->d_size / sizeof(Elf64_Rel))
3789 		return NULL;
3790 
3791 	return (Elf64_Rel *)data->d_buf + idx;
3792 }
3793 
3794 static bool is_sec_name_dwarf(const char *name)
3795 {
3796 	/* approximation, but the actual list is too long */
3797 	return str_has_pfx(name, ".debug_");
3798 }
3799 
3800 static bool ignore_elf_section(Elf64_Shdr *hdr, const char *name)
3801 {
3802 	/* no special handling of .strtab */
3803 	if (hdr->sh_type == SHT_STRTAB)
3804 		return true;
3805 
3806 	/* ignore .llvm_addrsig section as well */
3807 	if (hdr->sh_type == SHT_LLVM_ADDRSIG)
3808 		return true;
3809 
3810 	/* no subprograms will lead to an empty .text section, ignore it */
3811 	if (hdr->sh_type == SHT_PROGBITS && hdr->sh_size == 0 &&
3812 	    strcmp(name, ".text") == 0)
3813 		return true;
3814 
3815 	/* DWARF sections */
3816 	if (is_sec_name_dwarf(name))
3817 		return true;
3818 
3819 	if (str_has_pfx(name, ".rel")) {
3820 		name += sizeof(".rel") - 1;
3821 		/* DWARF section relocations */
3822 		if (is_sec_name_dwarf(name))
3823 			return true;
3824 
3825 		/* .BTF and .BTF.ext don't need relocations */
3826 		if (strcmp(name, BTF_ELF_SEC) == 0 ||
3827 		    strcmp(name, BTF_EXT_ELF_SEC) == 0)
3828 			return true;
3829 	}
3830 
3831 	return false;
3832 }
3833 
3834 static int cmp_progs(const void *_a, const void *_b)
3835 {
3836 	const struct bpf_program *a = _a;
3837 	const struct bpf_program *b = _b;
3838 
3839 	if (a->sec_idx != b->sec_idx)
3840 		return a->sec_idx < b->sec_idx ? -1 : 1;
3841 
3842 	/* sec_insn_off can't be the same within the section */
3843 	return a->sec_insn_off < b->sec_insn_off ? -1 : 1;
3844 }
3845 
3846 static int bpf_object__elf_collect(struct bpf_object *obj)
3847 {
3848 	struct elf_sec_desc *sec_desc;
3849 	Elf *elf = obj->efile.elf;
3850 	Elf_Data *btf_ext_data = NULL;
3851 	Elf_Data *btf_data = NULL;
3852 	int idx = 0, err = 0;
3853 	const char *name;
3854 	Elf_Data *data;
3855 	Elf_Scn *scn;
3856 	Elf64_Shdr *sh;
3857 
3858 	/* ELF section indices are 0-based, but sec #0 is special "invalid"
3859 	 * section. Since section count retrieved by elf_getshdrnum() does
3860 	 * include sec #0, it is already the necessary size of an array to keep
3861 	 * all the sections.
3862 	 */
3863 	if (elf_getshdrnum(obj->efile.elf, &obj->efile.sec_cnt)) {
3864 		pr_warn("elf: failed to get the number of sections for %s: %s\n",
3865 			obj->path, elf_errmsg(-1));
3866 		return -LIBBPF_ERRNO__FORMAT;
3867 	}
3868 	obj->efile.secs = calloc(obj->efile.sec_cnt, sizeof(*obj->efile.secs));
3869 	if (!obj->efile.secs)
3870 		return -ENOMEM;
3871 
3872 	/* a bunch of ELF parsing functionality depends on processing symbols,
3873 	 * so do the first pass and find the symbol table
3874 	 */
3875 	scn = NULL;
3876 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3877 		sh = elf_sec_hdr(obj, scn);
3878 		if (!sh)
3879 			return -LIBBPF_ERRNO__FORMAT;
3880 
3881 		if (sh->sh_type == SHT_SYMTAB) {
3882 			if (obj->efile.symbols) {
3883 				pr_warn("elf: multiple symbol tables in %s\n", obj->path);
3884 				return -LIBBPF_ERRNO__FORMAT;
3885 			}
3886 
3887 			data = elf_sec_data(obj, scn);
3888 			if (!data)
3889 				return -LIBBPF_ERRNO__FORMAT;
3890 
3891 			idx = elf_ndxscn(scn);
3892 
3893 			obj->efile.symbols = data;
3894 			obj->efile.symbols_shndx = idx;
3895 			obj->efile.strtabidx = sh->sh_link;
3896 		}
3897 	}
3898 
3899 	if (!obj->efile.symbols) {
3900 		pr_warn("elf: couldn't find symbol table in %s, stripped object file?\n",
3901 			obj->path);
3902 		return -ENOENT;
3903 	}
3904 
3905 	scn = NULL;
3906 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3907 		idx = elf_ndxscn(scn);
3908 		sec_desc = &obj->efile.secs[idx];
3909 
3910 		sh = elf_sec_hdr(obj, scn);
3911 		if (!sh)
3912 			return -LIBBPF_ERRNO__FORMAT;
3913 
3914 		name = elf_sec_str(obj, sh->sh_name);
3915 		if (!name)
3916 			return -LIBBPF_ERRNO__FORMAT;
3917 
3918 		if (ignore_elf_section(sh, name))
3919 			continue;
3920 
3921 		data = elf_sec_data(obj, scn);
3922 		if (!data)
3923 			return -LIBBPF_ERRNO__FORMAT;
3924 
3925 		pr_debug("elf: section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
3926 			 idx, name, (unsigned long)data->d_size,
3927 			 (int)sh->sh_link, (unsigned long)sh->sh_flags,
3928 			 (int)sh->sh_type);
3929 
3930 		if (strcmp(name, "license") == 0) {
3931 			err = bpf_object__init_license(obj, data->d_buf, data->d_size);
3932 			if (err)
3933 				return err;
3934 		} else if (strcmp(name, "version") == 0) {
3935 			err = bpf_object__init_kversion(obj, data->d_buf, data->d_size);
3936 			if (err)
3937 				return err;
3938 		} else if (strcmp(name, "maps") == 0) {
3939 			pr_warn("elf: legacy map definitions in 'maps' section are not supported by libbpf v1.0+\n");
3940 			return -ENOTSUP;
3941 		} else if (strcmp(name, MAPS_ELF_SEC) == 0) {
3942 			obj->efile.btf_maps_shndx = idx;
3943 		} else if (strcmp(name, BTF_ELF_SEC) == 0) {
3944 			if (sh->sh_type != SHT_PROGBITS)
3945 				return -LIBBPF_ERRNO__FORMAT;
3946 			btf_data = data;
3947 		} else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
3948 			if (sh->sh_type != SHT_PROGBITS)
3949 				return -LIBBPF_ERRNO__FORMAT;
3950 			btf_ext_data = data;
3951 		} else if (sh->sh_type == SHT_SYMTAB) {
3952 			/* already processed during the first pass above */
3953 		} else if (sh->sh_type == SHT_PROGBITS && data->d_size > 0) {
3954 			if (sh->sh_flags & SHF_EXECINSTR) {
3955 				if (strcmp(name, ".text") == 0)
3956 					obj->efile.text_shndx = idx;
3957 				err = bpf_object__add_programs(obj, data, name, idx);
3958 				if (err)
3959 					return err;
3960 			} else if (strcmp(name, DATA_SEC) == 0 ||
3961 				   str_has_pfx(name, DATA_SEC ".")) {
3962 				sec_desc->sec_type = SEC_DATA;
3963 				sec_desc->shdr = sh;
3964 				sec_desc->data = data;
3965 			} else if (strcmp(name, RODATA_SEC) == 0 ||
3966 				   str_has_pfx(name, RODATA_SEC ".")) {
3967 				sec_desc->sec_type = SEC_RODATA;
3968 				sec_desc->shdr = sh;
3969 				sec_desc->data = data;
3970 			} else if (strcmp(name, STRUCT_OPS_SEC) == 0 ||
3971 				   strcmp(name, STRUCT_OPS_LINK_SEC) == 0 ||
3972 				   strcmp(name, "?" STRUCT_OPS_SEC) == 0 ||
3973 				   strcmp(name, "?" STRUCT_OPS_LINK_SEC) == 0) {
3974 				sec_desc->sec_type = SEC_ST_OPS;
3975 				sec_desc->shdr = sh;
3976 				sec_desc->data = data;
3977 				obj->efile.has_st_ops = true;
3978 			} else if (strcmp(name, ARENA_SEC) == 0) {
3979 				obj->efile.arena_data = data;
3980 				obj->efile.arena_data_shndx = idx;
3981 			} else if (strcmp(name, JUMPTABLES_SEC) == 0) {
3982 				obj->jumptables_data = malloc(data->d_size);
3983 				if (!obj->jumptables_data)
3984 					return -ENOMEM;
3985 				memcpy(obj->jumptables_data, data->d_buf, data->d_size);
3986 				obj->jumptables_data_sz = data->d_size;
3987 				obj->efile.jumptables_data_shndx = idx;
3988 			} else {
3989 				pr_info("elf: skipping unrecognized data section(%d) %s\n",
3990 					idx, name);
3991 			}
3992 		} else if (sh->sh_type == SHT_REL) {
3993 			int targ_sec_idx = sh->sh_info; /* points to other section */
3994 
3995 			if (sh->sh_entsize != sizeof(Elf64_Rel) ||
3996 			    targ_sec_idx >= obj->efile.sec_cnt)
3997 				return -LIBBPF_ERRNO__FORMAT;
3998 
3999 			/* Only do relo for section with exec instructions */
4000 			if (!section_have_execinstr(obj, targ_sec_idx) &&
4001 			    strcmp(name, ".rel" STRUCT_OPS_SEC) &&
4002 			    strcmp(name, ".rel" STRUCT_OPS_LINK_SEC) &&
4003 			    strcmp(name, ".rel?" STRUCT_OPS_SEC) &&
4004 			    strcmp(name, ".rel?" STRUCT_OPS_LINK_SEC) &&
4005 			    strcmp(name, ".rel" MAPS_ELF_SEC)) {
4006 				pr_info("elf: skipping relo section(%d) %s for section(%d) %s\n",
4007 					idx, name, targ_sec_idx,
4008 					elf_sec_name(obj, elf_sec_by_idx(obj, targ_sec_idx)) ?: "<?>");
4009 				continue;
4010 			}
4011 
4012 			sec_desc->sec_type = SEC_RELO;
4013 			sec_desc->shdr = sh;
4014 			sec_desc->data = data;
4015 		} else if (sh->sh_type == SHT_NOBITS && (strcmp(name, BSS_SEC) == 0 ||
4016 							 str_has_pfx(name, BSS_SEC "."))) {
4017 			sec_desc->sec_type = SEC_BSS;
4018 			sec_desc->shdr = sh;
4019 			sec_desc->data = data;
4020 		} else {
4021 			pr_info("elf: skipping section(%d) %s (size %zu)\n", idx, name,
4022 				(size_t)sh->sh_size);
4023 		}
4024 	}
4025 
4026 	if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) {
4027 		pr_warn("elf: symbol strings section missing or invalid in %s\n", obj->path);
4028 		return -LIBBPF_ERRNO__FORMAT;
4029 	}
4030 
4031 	/* change BPF program insns to native endianness for introspection */
4032 	if (!is_native_endianness(obj))
4033 		bpf_object_bswap_progs(obj);
4034 
4035 	/* sort BPF programs by section name and in-section instruction offset
4036 	 * for faster search
4037 	 */
4038 	if (obj->nr_programs)
4039 		qsort(obj->programs, obj->nr_programs, sizeof(*obj->programs), cmp_progs);
4040 
4041 	return bpf_object__init_btf(obj, btf_data, btf_ext_data);
4042 }
4043 
4044 static bool sym_is_extern(const Elf64_Sym *sym)
4045 {
4046 	int bind = ELF64_ST_BIND(sym->st_info);
4047 	/* externs are symbols w/ type=NOTYPE, bind=GLOBAL|WEAK, section=UND */
4048 	return sym->st_shndx == SHN_UNDEF &&
4049 	       (bind == STB_GLOBAL || bind == STB_WEAK) &&
4050 	       ELF64_ST_TYPE(sym->st_info) == STT_NOTYPE;
4051 }
4052 
4053 static bool sym_is_subprog(const Elf64_Sym *sym, int text_shndx)
4054 {
4055 	int bind = ELF64_ST_BIND(sym->st_info);
4056 	int type = ELF64_ST_TYPE(sym->st_info);
4057 
4058 	/* in .text section */
4059 	if (sym->st_shndx != text_shndx)
4060 		return false;
4061 
4062 	/* local function */
4063 	if (bind == STB_LOCAL && type == STT_SECTION)
4064 		return true;
4065 
4066 	/* global function */
4067 	return (bind == STB_GLOBAL || bind == STB_WEAK) && type == STT_FUNC;
4068 }
4069 
4070 static int find_extern_btf_id(const struct btf *btf, const char *ext_name)
4071 {
4072 	const struct btf_type *t;
4073 	const char *tname;
4074 	int i, n;
4075 
4076 	if (!btf)
4077 		return -ESRCH;
4078 
4079 	n = btf__type_cnt(btf);
4080 	for (i = 1; i < n; i++) {
4081 		t = btf__type_by_id(btf, i);
4082 
4083 		if (!btf_is_var(t) && !btf_is_func(t))
4084 			continue;
4085 
4086 		tname = btf__name_by_offset(btf, t->name_off);
4087 		if (strcmp(tname, ext_name))
4088 			continue;
4089 
4090 		if (btf_is_var(t) &&
4091 		    btf_var(t)->linkage != BTF_VAR_GLOBAL_EXTERN)
4092 			return -EINVAL;
4093 
4094 		if (btf_is_func(t) && btf_func_linkage(t) != BTF_FUNC_EXTERN)
4095 			return -EINVAL;
4096 
4097 		return i;
4098 	}
4099 
4100 	return -ENOENT;
4101 }
4102 
4103 static int find_extern_sec_btf_id(struct btf *btf, int ext_btf_id) {
4104 	const struct btf_var_secinfo *vs;
4105 	const struct btf_type *t;
4106 	int i, j, n;
4107 
4108 	if (!btf)
4109 		return -ESRCH;
4110 
4111 	n = btf__type_cnt(btf);
4112 	for (i = 1; i < n; i++) {
4113 		t = btf__type_by_id(btf, i);
4114 
4115 		if (!btf_is_datasec(t))
4116 			continue;
4117 
4118 		vs = btf_var_secinfos(t);
4119 		for (j = 0; j < btf_vlen(t); j++, vs++) {
4120 			if (vs->type == ext_btf_id)
4121 				return i;
4122 		}
4123 	}
4124 
4125 	return -ENOENT;
4126 }
4127 
4128 static enum kcfg_type find_kcfg_type(const struct btf *btf, int id,
4129 				     bool *is_signed)
4130 {
4131 	const struct btf_type *t;
4132 	const char *name;
4133 
4134 	t = skip_mods_and_typedefs(btf, id, NULL);
4135 	name = btf__name_by_offset(btf, t->name_off);
4136 
4137 	if (is_signed)
4138 		*is_signed = false;
4139 	switch (btf_kind(t)) {
4140 	case BTF_KIND_INT: {
4141 		int enc = btf_int_encoding(t);
4142 
4143 		if (enc & BTF_INT_BOOL)
4144 			return t->size == 1 ? KCFG_BOOL : KCFG_UNKNOWN;
4145 		if (is_signed)
4146 			*is_signed = enc & BTF_INT_SIGNED;
4147 		if (t->size == 1)
4148 			return KCFG_CHAR;
4149 		if (t->size < 1 || t->size > 8 || (t->size & (t->size - 1)))
4150 			return KCFG_UNKNOWN;
4151 		return KCFG_INT;
4152 	}
4153 	case BTF_KIND_ENUM:
4154 		if (t->size != 4)
4155 			return KCFG_UNKNOWN;
4156 		if (strcmp(name, "libbpf_tristate"))
4157 			return KCFG_UNKNOWN;
4158 		return KCFG_TRISTATE;
4159 	case BTF_KIND_ENUM64:
4160 		if (strcmp(name, "libbpf_tristate"))
4161 			return KCFG_UNKNOWN;
4162 		return KCFG_TRISTATE;
4163 	case BTF_KIND_ARRAY:
4164 		if (btf_array(t)->nelems == 0)
4165 			return KCFG_UNKNOWN;
4166 		if (find_kcfg_type(btf, btf_array(t)->type, NULL) != KCFG_CHAR)
4167 			return KCFG_UNKNOWN;
4168 		return KCFG_CHAR_ARR;
4169 	default:
4170 		return KCFG_UNKNOWN;
4171 	}
4172 }
4173 
4174 static int cmp_externs(const void *_a, const void *_b)
4175 {
4176 	const struct extern_desc *a = _a;
4177 	const struct extern_desc *b = _b;
4178 
4179 	if (a->type != b->type)
4180 		return a->type < b->type ? -1 : 1;
4181 
4182 	if (a->type == EXT_KCFG) {
4183 		/* descending order by alignment requirements */
4184 		if (a->kcfg.align != b->kcfg.align)
4185 			return a->kcfg.align > b->kcfg.align ? -1 : 1;
4186 		/* ascending order by size, within same alignment class */
4187 		if (a->kcfg.sz != b->kcfg.sz)
4188 			return a->kcfg.sz < b->kcfg.sz ? -1 : 1;
4189 	}
4190 
4191 	/* resolve ties by name */
4192 	return strcmp(a->name, b->name);
4193 }
4194 
4195 static int find_int_btf_id(const struct btf *btf)
4196 {
4197 	const struct btf_type *t;
4198 	int i, n;
4199 
4200 	n = btf__type_cnt(btf);
4201 	for (i = 1; i < n; i++) {
4202 		t = btf__type_by_id(btf, i);
4203 
4204 		if (btf_is_int(t) && btf_int_bits(t) == 32)
4205 			return i;
4206 	}
4207 
4208 	return 0;
4209 }
4210 
4211 static int add_dummy_ksym_var(struct btf *btf)
4212 {
4213 	int i, int_btf_id, sec_btf_id, dummy_var_btf_id;
4214 	const struct btf_var_secinfo *vs;
4215 	const struct btf_type *sec;
4216 
4217 	if (!btf)
4218 		return 0;
4219 
4220 	sec_btf_id = btf__find_by_name_kind(btf, KSYMS_SEC,
4221 					    BTF_KIND_DATASEC);
4222 	if (sec_btf_id < 0)
4223 		return 0;
4224 
4225 	sec = btf__type_by_id(btf, sec_btf_id);
4226 	vs = btf_var_secinfos(sec);
4227 	for (i = 0; i < btf_vlen(sec); i++, vs++) {
4228 		const struct btf_type *vt;
4229 
4230 		vt = btf__type_by_id(btf, vs->type);
4231 		if (btf_is_func(vt))
4232 			break;
4233 	}
4234 
4235 	/* No func in ksyms sec.  No need to add dummy var. */
4236 	if (i == btf_vlen(sec))
4237 		return 0;
4238 
4239 	int_btf_id = find_int_btf_id(btf);
4240 	dummy_var_btf_id = btf__add_var(btf,
4241 					"dummy_ksym",
4242 					BTF_VAR_GLOBAL_ALLOCATED,
4243 					int_btf_id);
4244 	if (dummy_var_btf_id < 0)
4245 		pr_warn("cannot create a dummy_ksym var\n");
4246 
4247 	return dummy_var_btf_id;
4248 }
4249 
4250 static int bpf_object__collect_externs(struct bpf_object *obj)
4251 {
4252 	struct btf_type *sec, *kcfg_sec = NULL, *ksym_sec = NULL;
4253 	const struct btf_type *t;
4254 	struct extern_desc *ext;
4255 	int i, n, off, dummy_var_btf_id;
4256 	const char *ext_name, *sec_name;
4257 	size_t ext_essent_len;
4258 	Elf_Scn *scn;
4259 	Elf64_Shdr *sh;
4260 
4261 	if (!obj->efile.symbols)
4262 		return 0;
4263 
4264 	scn = elf_sec_by_idx(obj, obj->efile.symbols_shndx);
4265 	sh = elf_sec_hdr(obj, scn);
4266 	if (!sh || sh->sh_entsize != sizeof(Elf64_Sym))
4267 		return -LIBBPF_ERRNO__FORMAT;
4268 
4269 	dummy_var_btf_id = add_dummy_ksym_var(obj->btf);
4270 	if (dummy_var_btf_id < 0)
4271 		return dummy_var_btf_id;
4272 
4273 	n = sh->sh_size / sh->sh_entsize;
4274 	pr_debug("looking for externs among %d symbols...\n", n);
4275 
4276 	for (i = 0; i < n; i++) {
4277 		Elf64_Sym *sym = elf_sym_by_idx(obj, i);
4278 
4279 		if (!sym)
4280 			return -LIBBPF_ERRNO__FORMAT;
4281 		if (!sym_is_extern(sym))
4282 			continue;
4283 		ext_name = elf_sym_str(obj, sym->st_name);
4284 		if (str_is_empty(ext_name))
4285 			continue;
4286 
4287 		ext = obj->externs;
4288 		ext = libbpf_reallocarray(ext, obj->nr_extern + 1, sizeof(*ext));
4289 		if (!ext)
4290 			return -ENOMEM;
4291 		obj->externs = ext;
4292 		ext = &ext[obj->nr_extern];
4293 		memset(ext, 0, sizeof(*ext));
4294 		obj->nr_extern++;
4295 
4296 		ext->btf_id = find_extern_btf_id(obj->btf, ext_name);
4297 		if (ext->btf_id <= 0) {
4298 			pr_warn("failed to find BTF for extern '%s': %d\n",
4299 				ext_name, ext->btf_id);
4300 			return ext->btf_id;
4301 		}
4302 		t = btf__type_by_id(obj->btf, ext->btf_id);
4303 		ext->name = strdup(btf__name_by_offset(obj->btf, t->name_off));
4304 		if (!ext->name)
4305 			return -ENOMEM;
4306 		ext->sym_idx = i;
4307 		ext->is_weak = ELF64_ST_BIND(sym->st_info) == STB_WEAK;
4308 
4309 		ext_essent_len = bpf_core_essential_name_len(ext->name);
4310 		ext->essent_name = NULL;
4311 		if (ext_essent_len != strlen(ext->name)) {
4312 			ext->essent_name = strndup(ext->name, ext_essent_len);
4313 			if (!ext->essent_name)
4314 				return -ENOMEM;
4315 		}
4316 
4317 		ext->sec_btf_id = find_extern_sec_btf_id(obj->btf, ext->btf_id);
4318 		if (ext->sec_btf_id <= 0) {
4319 			pr_warn("failed to find BTF for extern '%s' [%d] section: %d\n",
4320 				ext_name, ext->btf_id, ext->sec_btf_id);
4321 			return ext->sec_btf_id;
4322 		}
4323 		sec = (void *)btf__type_by_id(obj->btf, ext->sec_btf_id);
4324 		sec_name = btf__name_by_offset(obj->btf, sec->name_off);
4325 
4326 		if (strcmp(sec_name, KCONFIG_SEC) == 0) {
4327 			if (btf_is_func(t)) {
4328 				pr_warn("extern function %s is unsupported under %s section\n",
4329 					ext->name, KCONFIG_SEC);
4330 				return -ENOTSUP;
4331 			}
4332 			kcfg_sec = sec;
4333 			ext->type = EXT_KCFG;
4334 			ext->kcfg.sz = btf__resolve_size(obj->btf, t->type);
4335 			if (ext->kcfg.sz <= 0) {
4336 				pr_warn("failed to resolve size of extern (kcfg) '%s': %d\n",
4337 					ext_name, ext->kcfg.sz);
4338 				return ext->kcfg.sz;
4339 			}
4340 			ext->kcfg.align = btf__align_of(obj->btf, t->type);
4341 			if (ext->kcfg.align <= 0) {
4342 				pr_warn("failed to determine alignment of extern (kcfg) '%s': %d\n",
4343 					ext_name, ext->kcfg.align);
4344 				return -EINVAL;
4345 			}
4346 			ext->kcfg.type = find_kcfg_type(obj->btf, t->type,
4347 							&ext->kcfg.is_signed);
4348 			if (ext->kcfg.type == KCFG_UNKNOWN) {
4349 				pr_warn("extern (kcfg) '%s': type is unsupported\n", ext_name);
4350 				return -ENOTSUP;
4351 			}
4352 		} else if (strcmp(sec_name, KSYMS_SEC) == 0) {
4353 			ksym_sec = sec;
4354 			ext->type = EXT_KSYM;
4355 			skip_mods_and_typedefs(obj->btf, t->type,
4356 					       &ext->ksym.type_id);
4357 		} else {
4358 			pr_warn("unrecognized extern section '%s'\n", sec_name);
4359 			return -ENOTSUP;
4360 		}
4361 	}
4362 	pr_debug("collected %d externs total\n", obj->nr_extern);
4363 
4364 	if (!obj->nr_extern)
4365 		return 0;
4366 
4367 	/* sort externs by type, for kcfg ones also by (align, size, name) */
4368 	qsort(obj->externs, obj->nr_extern, sizeof(*ext), cmp_externs);
4369 
4370 	/* for .ksyms section, we need to turn all externs into allocated
4371 	 * variables in BTF to pass kernel verification; we do this by
4372 	 * pretending that each extern is a 8-byte variable
4373 	 */
4374 	if (ksym_sec) {
4375 		/* find existing 4-byte integer type in BTF to use for fake
4376 		 * extern variables in DATASEC
4377 		 */
4378 		int int_btf_id = find_int_btf_id(obj->btf);
4379 		/* For extern function, a dummy_var added earlier
4380 		 * will be used to replace the vs->type and
4381 		 * its name string will be used to refill
4382 		 * the missing param's name.
4383 		 */
4384 		const struct btf_type *dummy_var;
4385 
4386 		dummy_var = btf__type_by_id(obj->btf, dummy_var_btf_id);
4387 		for (i = 0; i < obj->nr_extern; i++) {
4388 			ext = &obj->externs[i];
4389 			if (ext->type != EXT_KSYM)
4390 				continue;
4391 			pr_debug("extern (ksym) #%d: symbol %d, name %s\n",
4392 				 i, ext->sym_idx, ext->name);
4393 		}
4394 
4395 		sec = ksym_sec;
4396 		n = btf_vlen(sec);
4397 		for (i = 0, off = 0; i < n; i++, off += sizeof(int)) {
4398 			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
4399 			struct btf_type *vt;
4400 
4401 			vt = (void *)btf__type_by_id(obj->btf, vs->type);
4402 			ext_name = btf__name_by_offset(obj->btf, vt->name_off);
4403 			ext = find_extern_by_name(obj, ext_name);
4404 			if (!ext) {
4405 				pr_warn("failed to find extern definition for BTF %s '%s'\n",
4406 					btf_kind_str(vt), ext_name);
4407 				return -ESRCH;
4408 			}
4409 			if (btf_is_func(vt)) {
4410 				const struct btf_type *func_proto;
4411 				struct btf_param *param;
4412 				int j;
4413 
4414 				func_proto = btf__type_by_id(obj->btf,
4415 							     vt->type);
4416 				param = btf_params(func_proto);
4417 				/* Reuse the dummy_var string if the
4418 				 * func proto does not have param name.
4419 				 */
4420 				for (j = 0; j < btf_vlen(func_proto); j++)
4421 					if (param[j].type && !param[j].name_off)
4422 						param[j].name_off =
4423 							dummy_var->name_off;
4424 				vs->type = dummy_var_btf_id;
4425 				vt->info &= ~0xffff;
4426 				vt->info |= BTF_FUNC_GLOBAL;
4427 			} else {
4428 				btf_var(vt)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
4429 				vt->type = int_btf_id;
4430 			}
4431 			vs->offset = off;
4432 			vs->size = sizeof(int);
4433 		}
4434 		sec->size = off;
4435 	}
4436 
4437 	if (kcfg_sec) {
4438 		sec = kcfg_sec;
4439 		/* for kcfg externs calculate their offsets within a .kconfig map */
4440 		off = 0;
4441 		for (i = 0; i < obj->nr_extern; i++) {
4442 			ext = &obj->externs[i];
4443 			if (ext->type != EXT_KCFG)
4444 				continue;
4445 
4446 			ext->kcfg.data_off = roundup(off, ext->kcfg.align);
4447 			off = ext->kcfg.data_off + ext->kcfg.sz;
4448 			pr_debug("extern (kcfg) #%d: symbol %d, off %u, name %s\n",
4449 				 i, ext->sym_idx, ext->kcfg.data_off, ext->name);
4450 		}
4451 		sec->size = off;
4452 		n = btf_vlen(sec);
4453 		for (i = 0; i < n; i++) {
4454 			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
4455 
4456 			t = btf__type_by_id(obj->btf, vs->type);
4457 			ext_name = btf__name_by_offset(obj->btf, t->name_off);
4458 			ext = find_extern_by_name(obj, ext_name);
4459 			if (!ext) {
4460 				pr_warn("failed to find extern definition for BTF var '%s'\n",
4461 					ext_name);
4462 				return -ESRCH;
4463 			}
4464 			btf_var(t)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
4465 			vs->offset = ext->kcfg.data_off;
4466 		}
4467 	}
4468 	return 0;
4469 }
4470 
4471 static bool prog_is_subprog(const struct bpf_object *obj, const struct bpf_program *prog)
4472 {
4473 	return prog->sec_idx == obj->efile.text_shndx;
4474 }
4475 
4476 struct bpf_program *
4477 bpf_object__find_program_by_name(const struct bpf_object *obj,
4478 				 const char *name)
4479 {
4480 	struct bpf_program *prog;
4481 
4482 	bpf_object__for_each_program(prog, obj) {
4483 		if (prog_is_subprog(obj, prog))
4484 			continue;
4485 		if (!strcmp(prog->name, name))
4486 			return prog;
4487 	}
4488 	return errno = ENOENT, NULL;
4489 }
4490 
4491 static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
4492 				      int shndx)
4493 {
4494 	switch (obj->efile.secs[shndx].sec_type) {
4495 	case SEC_BSS:
4496 	case SEC_DATA:
4497 	case SEC_RODATA:
4498 		return true;
4499 	default:
4500 		return false;
4501 	}
4502 }
4503 
4504 static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
4505 				      int shndx)
4506 {
4507 	return shndx == obj->efile.btf_maps_shndx;
4508 }
4509 
4510 static enum libbpf_map_type
4511 bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
4512 {
4513 	if (shndx == obj->efile.symbols_shndx)
4514 		return LIBBPF_MAP_KCONFIG;
4515 
4516 	switch (obj->efile.secs[shndx].sec_type) {
4517 	case SEC_BSS:
4518 		return LIBBPF_MAP_BSS;
4519 	case SEC_DATA:
4520 		return LIBBPF_MAP_DATA;
4521 	case SEC_RODATA:
4522 		return LIBBPF_MAP_RODATA;
4523 	default:
4524 		return LIBBPF_MAP_UNSPEC;
4525 	}
4526 }
4527 
4528 static int bpf_prog_compute_hash(struct bpf_program *prog)
4529 {
4530 	struct bpf_insn *purged;
4531 	int i, err = 0;
4532 
4533 	purged = calloc(prog->insns_cnt, BPF_INSN_SZ);
4534 	if (!purged)
4535 		return -ENOMEM;
4536 
4537 	/* If relocations have been done, the map_fd needs to be
4538 	 * discarded for the digest calculation.
4539 	 */
4540 	for (i = 0; i < prog->insns_cnt; i++) {
4541 		purged[i] = prog->insns[i];
4542 		if (purged[i].code == (BPF_LD | BPF_IMM | BPF_DW) &&
4543 		    (purged[i].src_reg == BPF_PSEUDO_MAP_FD ||
4544 		     purged[i].src_reg == BPF_PSEUDO_MAP_VALUE)) {
4545 			purged[i].imm = 0;
4546 			i++;
4547 			if (i >= prog->insns_cnt ||
4548 			    prog->insns[i].code != 0 ||
4549 			    prog->insns[i].dst_reg != 0 ||
4550 			    prog->insns[i].src_reg != 0 ||
4551 			    prog->insns[i].off != 0) {
4552 				err = -EINVAL;
4553 				goto out;
4554 			}
4555 			purged[i] = prog->insns[i];
4556 			purged[i].imm = 0;
4557 		}
4558 	}
4559 	libbpf_sha256(purged, prog->insns_cnt * sizeof(struct bpf_insn),
4560 		      prog->hash);
4561 out:
4562 	free(purged);
4563 	return err;
4564 }
4565 
4566 static int bpf_program__record_reloc(struct bpf_program *prog,
4567 				     struct reloc_desc *reloc_desc,
4568 				     __u32 insn_idx, const char *sym_name,
4569 				     const Elf64_Sym *sym, const Elf64_Rel *rel)
4570 {
4571 	struct bpf_insn *insn = &prog->insns[insn_idx];
4572 	size_t map_idx, nr_maps = prog->obj->nr_maps;
4573 	struct bpf_object *obj = prog->obj;
4574 	__u32 shdr_idx = sym->st_shndx;
4575 	enum libbpf_map_type type;
4576 	const char *sym_sec_name;
4577 	struct bpf_map *map;
4578 
4579 	if (!is_call_insn(insn) && !is_ldimm64_insn(insn)) {
4580 		pr_warn("prog '%s': invalid relo against '%s' for insns[%d].code 0x%x\n",
4581 			prog->name, sym_name, insn_idx, insn->code);
4582 		return -LIBBPF_ERRNO__RELOC;
4583 	}
4584 
4585 	if (sym_is_extern(sym)) {
4586 		int sym_idx = ELF64_R_SYM(rel->r_info);
4587 		int i, n = obj->nr_extern;
4588 		struct extern_desc *ext;
4589 
4590 		for (i = 0; i < n; i++) {
4591 			ext = &obj->externs[i];
4592 			if (ext->sym_idx == sym_idx)
4593 				break;
4594 		}
4595 		if (i >= n) {
4596 			pr_warn("prog '%s': extern relo failed to find extern for '%s' (%d)\n",
4597 				prog->name, sym_name, sym_idx);
4598 			return -LIBBPF_ERRNO__RELOC;
4599 		}
4600 		pr_debug("prog '%s': found extern #%d '%s' (sym %d) for insn #%u\n",
4601 			 prog->name, i, ext->name, ext->sym_idx, insn_idx);
4602 		if (insn->code == (BPF_JMP | BPF_CALL))
4603 			reloc_desc->type = RELO_EXTERN_CALL;
4604 		else
4605 			reloc_desc->type = RELO_EXTERN_LD64;
4606 		reloc_desc->insn_idx = insn_idx;
4607 		reloc_desc->ext_idx = i;
4608 		return 0;
4609 	}
4610 
4611 	/* sub-program call relocation */
4612 	if (is_call_insn(insn)) {
4613 		if (insn->src_reg != BPF_PSEUDO_CALL) {
4614 			pr_warn("prog '%s': incorrect bpf_call opcode\n", prog->name);
4615 			return -LIBBPF_ERRNO__RELOC;
4616 		}
4617 		/* text_shndx can be 0, if no default "main" program exists */
4618 		if (!shdr_idx || shdr_idx != obj->efile.text_shndx) {
4619 			sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4620 			pr_warn("prog '%s': bad call relo against '%s' in section '%s'\n",
4621 				prog->name, sym_name, sym_sec_name);
4622 			return -LIBBPF_ERRNO__RELOC;
4623 		}
4624 		if (sym->st_value % BPF_INSN_SZ) {
4625 			pr_warn("prog '%s': bad call relo against '%s' at offset %zu\n",
4626 				prog->name, sym_name, (size_t)sym->st_value);
4627 			return -LIBBPF_ERRNO__RELOC;
4628 		}
4629 		reloc_desc->type = RELO_CALL;
4630 		reloc_desc->insn_idx = insn_idx;
4631 		reloc_desc->sym_off = sym->st_value;
4632 		return 0;
4633 	}
4634 
4635 	if (!shdr_idx || shdr_idx >= SHN_LORESERVE) {
4636 		pr_warn("prog '%s': invalid relo against '%s' in special section 0x%x; forgot to initialize global var?..\n",
4637 			prog->name, sym_name, shdr_idx);
4638 		return -LIBBPF_ERRNO__RELOC;
4639 	}
4640 
4641 	/* loading subprog addresses */
4642 	if (sym_is_subprog(sym, obj->efile.text_shndx)) {
4643 		/* global_func: sym->st_value = offset in the section, insn->imm = 0.
4644 		 * local_func: sym->st_value = 0, insn->imm = offset in the section.
4645 		 */
4646 		if ((sym->st_value % BPF_INSN_SZ) || (insn->imm % BPF_INSN_SZ)) {
4647 			pr_warn("prog '%s': bad subprog addr relo against '%s' at offset %zu+%d\n",
4648 				prog->name, sym_name, (size_t)sym->st_value, insn->imm);
4649 			return -LIBBPF_ERRNO__RELOC;
4650 		}
4651 
4652 		reloc_desc->type = RELO_SUBPROG_ADDR;
4653 		reloc_desc->insn_idx = insn_idx;
4654 		reloc_desc->sym_off = sym->st_value;
4655 		return 0;
4656 	}
4657 
4658 	type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
4659 	sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4660 
4661 	/* arena data relocation */
4662 	if (shdr_idx == obj->efile.arena_data_shndx) {
4663 		if (obj->arena_map_idx < 0) {
4664 			pr_warn("prog '%s': bad arena data relocation at insn %u, no arena maps defined\n",
4665 				prog->name, insn_idx);
4666 			return -LIBBPF_ERRNO__RELOC;
4667 		}
4668 		reloc_desc->type = RELO_DATA;
4669 		reloc_desc->insn_idx = insn_idx;
4670 		reloc_desc->map_idx = obj->arena_map_idx;
4671 		reloc_desc->sym_off = sym->st_value + obj->arena_data_off;
4672 
4673 		map = &obj->maps[obj->arena_map_idx];
4674 		pr_debug("prog '%s': found arena map %d (%s, sec %d, off %zu) for insn %u\n",
4675 			 prog->name, obj->arena_map_idx, map->name, map->sec_idx,
4676 			 map->sec_offset, insn_idx);
4677 		return 0;
4678 	}
4679 
4680 	/* jump table data relocation */
4681 	if (shdr_idx == obj->efile.jumptables_data_shndx) {
4682 		reloc_desc->type = RELO_INSN_ARRAY;
4683 		reloc_desc->insn_idx = insn_idx;
4684 		reloc_desc->map_idx = -1;
4685 		reloc_desc->sym_off = sym->st_value;
4686 		reloc_desc->sym_size = sym->st_size;
4687 		return 0;
4688 	}
4689 
4690 	/* generic map reference relocation */
4691 	if (type == LIBBPF_MAP_UNSPEC) {
4692 		if (!bpf_object__shndx_is_maps(obj, shdr_idx)) {
4693 			pr_warn("prog '%s': bad map relo against '%s' in section '%s'\n",
4694 				prog->name, sym_name, sym_sec_name);
4695 			return -LIBBPF_ERRNO__RELOC;
4696 		}
4697 		for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4698 			map = &obj->maps[map_idx];
4699 			if (map->libbpf_type != type ||
4700 			    map->sec_idx != sym->st_shndx ||
4701 			    map->sec_offset != sym->st_value)
4702 				continue;
4703 			pr_debug("prog '%s': found map %zd (%s, sec %d, off %zu) for insn #%u\n",
4704 				 prog->name, map_idx, map->name, map->sec_idx,
4705 				 map->sec_offset, insn_idx);
4706 			break;
4707 		}
4708 		if (map_idx >= nr_maps) {
4709 			pr_warn("prog '%s': map relo failed to find map for section '%s', off %zu\n",
4710 				prog->name, sym_sec_name, (size_t)sym->st_value);
4711 			return -LIBBPF_ERRNO__RELOC;
4712 		}
4713 		reloc_desc->type = RELO_LD64;
4714 		reloc_desc->insn_idx = insn_idx;
4715 		reloc_desc->map_idx = map_idx;
4716 		reloc_desc->sym_off = 0; /* sym->st_value determines map_idx */
4717 		return 0;
4718 	}
4719 
4720 	/* global data map relocation */
4721 	if (!bpf_object__shndx_is_data(obj, shdr_idx)) {
4722 		pr_warn("prog '%s': bad data relo against section '%s'\n",
4723 			prog->name, sym_sec_name);
4724 		return -LIBBPF_ERRNO__RELOC;
4725 	}
4726 	for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4727 		map = &obj->maps[map_idx];
4728 		if (map->libbpf_type != type || map->sec_idx != sym->st_shndx)
4729 			continue;
4730 		pr_debug("prog '%s': found data map %zd (%s, sec %d, off %zu) for insn %u\n",
4731 			 prog->name, map_idx, map->name, map->sec_idx,
4732 			 map->sec_offset, insn_idx);
4733 		break;
4734 	}
4735 	if (map_idx >= nr_maps) {
4736 		pr_warn("prog '%s': data relo failed to find map for section '%s'\n",
4737 			prog->name, sym_sec_name);
4738 		return -LIBBPF_ERRNO__RELOC;
4739 	}
4740 
4741 	reloc_desc->type = RELO_DATA;
4742 	reloc_desc->insn_idx = insn_idx;
4743 	reloc_desc->map_idx = map_idx;
4744 	reloc_desc->sym_off = sym->st_value;
4745 	return 0;
4746 }
4747 
4748 static bool prog_contains_insn(const struct bpf_program *prog, size_t insn_idx)
4749 {
4750 	return insn_idx >= prog->sec_insn_off &&
4751 	       insn_idx < prog->sec_insn_off + prog->sec_insn_cnt;
4752 }
4753 
4754 static struct bpf_program *find_prog_by_sec_insn(const struct bpf_object *obj,
4755 						 size_t sec_idx, size_t insn_idx)
4756 {
4757 	int l = 0, r = obj->nr_programs - 1, m;
4758 	struct bpf_program *prog;
4759 
4760 	if (!obj->nr_programs)
4761 		return NULL;
4762 
4763 	while (l < r) {
4764 		m = l + (r - l + 1) / 2;
4765 		prog = &obj->programs[m];
4766 
4767 		if (prog->sec_idx < sec_idx ||
4768 		    (prog->sec_idx == sec_idx && prog->sec_insn_off <= insn_idx))
4769 			l = m;
4770 		else
4771 			r = m - 1;
4772 	}
4773 	/* matching program could be at index l, but it still might be the
4774 	 * wrong one, so we need to double check conditions for the last time
4775 	 */
4776 	prog = &obj->programs[l];
4777 	if (prog->sec_idx == sec_idx && prog_contains_insn(prog, insn_idx))
4778 		return prog;
4779 	return NULL;
4780 }
4781 
4782 static int
4783 bpf_object__collect_prog_relos(struct bpf_object *obj, Elf64_Shdr *shdr, Elf_Data *data)
4784 {
4785 	const char *relo_sec_name, *sec_name;
4786 	size_t sec_idx = shdr->sh_info, sym_idx;
4787 	struct bpf_program *prog;
4788 	struct reloc_desc *relos;
4789 	int err, i, nrels;
4790 	const char *sym_name;
4791 	__u32 insn_idx;
4792 	Elf_Scn *scn;
4793 	Elf_Data *scn_data;
4794 	Elf64_Sym *sym;
4795 	Elf64_Rel *rel;
4796 
4797 	if (sec_idx >= obj->efile.sec_cnt)
4798 		return -EINVAL;
4799 
4800 	scn = elf_sec_by_idx(obj, sec_idx);
4801 	scn_data = elf_sec_data(obj, scn);
4802 	if (!scn_data)
4803 		return -LIBBPF_ERRNO__FORMAT;
4804 
4805 	relo_sec_name = elf_sec_str(obj, shdr->sh_name);
4806 	sec_name = elf_sec_name(obj, scn);
4807 	if (!relo_sec_name || !sec_name)
4808 		return -EINVAL;
4809 
4810 	pr_debug("sec '%s': collecting relocation for section(%zu) '%s'\n",
4811 		 relo_sec_name, sec_idx, sec_name);
4812 	nrels = shdr->sh_size / shdr->sh_entsize;
4813 
4814 	for (i = 0; i < nrels; i++) {
4815 		rel = elf_rel_by_idx(data, i);
4816 		if (!rel) {
4817 			pr_warn("sec '%s': failed to get relo #%d\n", relo_sec_name, i);
4818 			return -LIBBPF_ERRNO__FORMAT;
4819 		}
4820 
4821 		sym_idx = ELF64_R_SYM(rel->r_info);
4822 		sym = elf_sym_by_idx(obj, sym_idx);
4823 		if (!sym) {
4824 			pr_warn("sec '%s': symbol #%zu not found for relo #%d\n",
4825 				relo_sec_name, sym_idx, i);
4826 			return -LIBBPF_ERRNO__FORMAT;
4827 		}
4828 
4829 		if (sym->st_shndx >= obj->efile.sec_cnt) {
4830 			pr_warn("sec '%s': corrupted symbol #%zu pointing to invalid section #%zu for relo #%d\n",
4831 				relo_sec_name, sym_idx, (size_t)sym->st_shndx, i);
4832 			return -LIBBPF_ERRNO__FORMAT;
4833 		}
4834 
4835 		if (rel->r_offset % BPF_INSN_SZ || rel->r_offset >= scn_data->d_size) {
4836 			pr_warn("sec '%s': invalid offset 0x%zx for relo #%d\n",
4837 				relo_sec_name, (size_t)rel->r_offset, i);
4838 			return -LIBBPF_ERRNO__FORMAT;
4839 		}
4840 
4841 		insn_idx = rel->r_offset / BPF_INSN_SZ;
4842 		/* relocations against static functions are recorded as
4843 		 * relocations against the section that contains a function;
4844 		 * in such case, symbol will be STT_SECTION and sym.st_name
4845 		 * will point to empty string (0), so fetch section name
4846 		 * instead
4847 		 */
4848 		if (ELF64_ST_TYPE(sym->st_info) == STT_SECTION && sym->st_name == 0)
4849 			sym_name = elf_sec_name(obj, elf_sec_by_idx(obj, sym->st_shndx));
4850 		else
4851 			sym_name = elf_sym_str(obj, sym->st_name);
4852 		sym_name = sym_name ?: "<?";
4853 
4854 		pr_debug("sec '%s': relo #%d: insn #%u against '%s'\n",
4855 			 relo_sec_name, i, insn_idx, sym_name);
4856 
4857 		prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
4858 		if (!prog) {
4859 			pr_debug("sec '%s': relo #%d: couldn't find program in section '%s' for insn #%u, probably overridden weak function, skipping...\n",
4860 				relo_sec_name, i, sec_name, insn_idx);
4861 			continue;
4862 		}
4863 
4864 		relos = libbpf_reallocarray(prog->reloc_desc,
4865 					    prog->nr_reloc + 1, sizeof(*relos));
4866 		if (!relos)
4867 			return -ENOMEM;
4868 		prog->reloc_desc = relos;
4869 
4870 		/* adjust insn_idx to local BPF program frame of reference */
4871 		insn_idx -= prog->sec_insn_off;
4872 		err = bpf_program__record_reloc(prog, &relos[prog->nr_reloc],
4873 						insn_idx, sym_name, sym, rel);
4874 		if (err)
4875 			return err;
4876 
4877 		prog->nr_reloc++;
4878 	}
4879 	return 0;
4880 }
4881 
4882 static int map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map)
4883 {
4884 	int id;
4885 
4886 	if (!obj->btf)
4887 		return -ENOENT;
4888 
4889 	/* if it's BTF-defined map, we don't need to search for type IDs.
4890 	 * For struct_ops map, it does not need btf_key_type_id and
4891 	 * btf_value_type_id.
4892 	 */
4893 	if (map->sec_idx == obj->efile.btf_maps_shndx || bpf_map__is_struct_ops(map))
4894 		return 0;
4895 
4896 	/*
4897 	 * LLVM annotates global data differently in BTF, that is,
4898 	 * only as '.data', '.bss' or '.rodata'.
4899 	 */
4900 	if (!bpf_map__is_internal(map))
4901 		return -ENOENT;
4902 
4903 	id = btf__find_by_name(obj->btf, map->real_name);
4904 	if (id < 0)
4905 		return id;
4906 
4907 	map->btf_key_type_id = 0;
4908 	map->btf_value_type_id = id;
4909 	return 0;
4910 }
4911 
4912 static int bpf_get_map_info_from_fdinfo(int fd, struct bpf_map_info *info)
4913 {
4914 	char file[PATH_MAX], buff[4096];
4915 	FILE *fp;
4916 	__u32 val;
4917 	int err;
4918 
4919 	snprintf(file, sizeof(file), "/proc/%d/fdinfo/%d", getpid(), fd);
4920 	memset(info, 0, sizeof(*info));
4921 
4922 	fp = fopen(file, "re");
4923 	if (!fp) {
4924 		err = -errno;
4925 		pr_warn("failed to open %s: %s. No procfs support?\n", file,
4926 			errstr(err));
4927 		return err;
4928 	}
4929 
4930 	while (fgets(buff, sizeof(buff), fp)) {
4931 		if (sscanf(buff, "map_type:\t%u", &val) == 1)
4932 			info->type = val;
4933 		else if (sscanf(buff, "key_size:\t%u", &val) == 1)
4934 			info->key_size = val;
4935 		else if (sscanf(buff, "value_size:\t%u", &val) == 1)
4936 			info->value_size = val;
4937 		else if (sscanf(buff, "max_entries:\t%u", &val) == 1)
4938 			info->max_entries = val;
4939 		else if (sscanf(buff, "map_flags:\t%i", &val) == 1)
4940 			info->map_flags = val;
4941 	}
4942 
4943 	fclose(fp);
4944 
4945 	return 0;
4946 }
4947 
4948 static bool map_is_created(const struct bpf_map *map)
4949 {
4950 	return map->obj->state >= OBJ_PREPARED || map->reused;
4951 }
4952 
4953 bool bpf_map__autocreate(const struct bpf_map *map)
4954 {
4955 	return map->autocreate;
4956 }
4957 
4958 int bpf_map__set_autocreate(struct bpf_map *map, bool autocreate)
4959 {
4960 	if (map_is_created(map))
4961 		return libbpf_err(-EBUSY);
4962 
4963 	map->autocreate = autocreate;
4964 	return 0;
4965 }
4966 
4967 int bpf_map__set_autoattach(struct bpf_map *map, bool autoattach)
4968 {
4969 	if (!bpf_map__is_struct_ops(map))
4970 		return libbpf_err(-EINVAL);
4971 
4972 	map->autoattach = autoattach;
4973 	return 0;
4974 }
4975 
4976 bool bpf_map__autoattach(const struct bpf_map *map)
4977 {
4978 	return map->autoattach;
4979 }
4980 
4981 int bpf_map__reuse_fd(struct bpf_map *map, int fd)
4982 {
4983 	struct bpf_map_info info;
4984 	__u32 len = sizeof(info), name_len;
4985 	int new_fd, err;
4986 	char *new_name;
4987 
4988 	memset(&info, 0, len);
4989 	err = bpf_map_get_info_by_fd(fd, &info, &len);
4990 	if (err && errno == EINVAL)
4991 		err = bpf_get_map_info_from_fdinfo(fd, &info);
4992 	if (err)
4993 		return libbpf_err(err);
4994 
4995 	name_len = strlen(info.name);
4996 	if (name_len == BPF_OBJ_NAME_LEN - 1 && strncmp(map->name, info.name, name_len) == 0)
4997 		new_name = strdup(map->name);
4998 	else
4999 		new_name = strdup(info.name);
5000 
5001 	if (!new_name)
5002 		return libbpf_err(-errno);
5003 
5004 	/*
5005 	 * Like dup(), but make sure new FD is >= 3 and has O_CLOEXEC set.
5006 	 * This is similar to what we do in ensure_good_fd(), but without
5007 	 * closing original FD.
5008 	 */
5009 	new_fd = fcntl(fd, F_DUPFD_CLOEXEC, 3);
5010 	if (new_fd < 0) {
5011 		err = -errno;
5012 		goto err_free_new_name;
5013 	}
5014 
5015 	err = reuse_fd(map->fd, new_fd);
5016 	if (err)
5017 		goto err_free_new_name;
5018 
5019 	free(map->name);
5020 
5021 	map->name = new_name;
5022 	map->def.type = info.type;
5023 	map->def.key_size = info.key_size;
5024 	map->def.value_size = info.value_size;
5025 	map->def.max_entries = info.max_entries;
5026 	map->def.map_flags = info.map_flags;
5027 	map->btf_key_type_id = info.btf_key_type_id;
5028 	map->btf_value_type_id = info.btf_value_type_id;
5029 	map->reused = true;
5030 	map->map_extra = info.map_extra;
5031 
5032 	return 0;
5033 
5034 err_free_new_name:
5035 	free(new_name);
5036 	return libbpf_err(err);
5037 }
5038 
5039 __u32 bpf_map__max_entries(const struct bpf_map *map)
5040 {
5041 	return map->def.max_entries;
5042 }
5043 
5044 struct bpf_map *bpf_map__inner_map(struct bpf_map *map)
5045 {
5046 	if (!bpf_map_type__is_map_in_map(map->def.type))
5047 		return errno = EINVAL, NULL;
5048 
5049 	return map->inner_map;
5050 }
5051 
5052 int bpf_map__set_max_entries(struct bpf_map *map, __u32 max_entries)
5053 {
5054 	if (map_is_created(map))
5055 		return libbpf_err(-EBUSY);
5056 
5057 	map->def.max_entries = max_entries;
5058 
5059 	/* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
5060 	if (map_is_ringbuf(map))
5061 		map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
5062 
5063 	return 0;
5064 }
5065 
5066 static int bpf_object_prepare_token(struct bpf_object *obj)
5067 {
5068 	const char *bpffs_path;
5069 	int bpffs_fd = -1, token_fd, err;
5070 	bool mandatory;
5071 	enum libbpf_print_level level;
5072 
5073 	/* token is explicitly prevented */
5074 	if (obj->token_path && obj->token_path[0] == '\0') {
5075 		pr_debug("object '%s': token is prevented, skipping...\n", obj->name);
5076 		return 0;
5077 	}
5078 
5079 	mandatory = obj->token_path != NULL;
5080 	level = mandatory ? LIBBPF_WARN : LIBBPF_DEBUG;
5081 
5082 	bpffs_path = obj->token_path ?: BPF_FS_DEFAULT_PATH;
5083 	bpffs_fd = open(bpffs_path, O_DIRECTORY, O_RDWR);
5084 	if (bpffs_fd < 0) {
5085 		err = -errno;
5086 		__pr(level, "object '%s': failed (%s) to open BPF FS mount at '%s'%s\n",
5087 		     obj->name, errstr(err), bpffs_path,
5088 		     mandatory ? "" : ", skipping optional step...");
5089 		return mandatory ? err : 0;
5090 	}
5091 
5092 	token_fd = bpf_token_create(bpffs_fd, 0);
5093 	close(bpffs_fd);
5094 	if (token_fd < 0) {
5095 		if (!mandatory && token_fd == -ENOENT) {
5096 			pr_debug("object '%s': BPF FS at '%s' doesn't have BPF token delegation set up, skipping...\n",
5097 				 obj->name, bpffs_path);
5098 			return 0;
5099 		}
5100 		__pr(level, "object '%s': failed (%d) to create BPF token from '%s'%s\n",
5101 		     obj->name, token_fd, bpffs_path,
5102 		     mandatory ? "" : ", skipping optional step...");
5103 		return mandatory ? token_fd : 0;
5104 	}
5105 
5106 	obj->feat_cache = calloc(1, sizeof(*obj->feat_cache));
5107 	if (!obj->feat_cache) {
5108 		close(token_fd);
5109 		return -ENOMEM;
5110 	}
5111 
5112 	obj->token_fd = token_fd;
5113 	obj->feat_cache->token_fd = token_fd;
5114 
5115 	return 0;
5116 }
5117 
5118 static int
5119 bpf_object__probe_loading(struct bpf_object *obj)
5120 {
5121 	struct bpf_insn insns[] = {
5122 		BPF_MOV64_IMM(BPF_REG_0, 0),
5123 		BPF_EXIT_INSN(),
5124 	};
5125 	int ret, insn_cnt = ARRAY_SIZE(insns);
5126 	LIBBPF_OPTS(bpf_prog_load_opts, opts,
5127 		.token_fd = obj->token_fd,
5128 		.prog_flags = obj->token_fd ? BPF_F_TOKEN_FD : 0,
5129 	);
5130 
5131 	if (obj->gen_loader)
5132 		return 0;
5133 
5134 	ret = bump_rlimit_memlock();
5135 	if (ret)
5136 		pr_warn("Failed to bump RLIMIT_MEMLOCK (err = %s), you might need to do it explicitly!\n",
5137 			errstr(ret));
5138 
5139 	/* make sure basic loading works */
5140 	ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, &opts);
5141 	if (ret < 0)
5142 		ret = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, &opts);
5143 	if (ret < 0) {
5144 		ret = errno;
5145 		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",
5146 			__func__, errstr(ret));
5147 		return -ret;
5148 	}
5149 	close(ret);
5150 
5151 	return 0;
5152 }
5153 
5154 bool kernel_supports(const struct bpf_object *obj, enum kern_feature_id feat_id)
5155 {
5156 	if (obj->gen_loader)
5157 		/* To generate loader program assume the latest kernel
5158 		 * to avoid doing extra prog_load, map_create syscalls.
5159 		 */
5160 		return true;
5161 
5162 	if (obj->token_fd)
5163 		return feat_supported(obj->feat_cache, feat_id);
5164 
5165 	return feat_supported(NULL, feat_id);
5166 }
5167 
5168 static bool map_is_reuse_compat(const struct bpf_map *map, int map_fd)
5169 {
5170 	struct bpf_map_info map_info;
5171 	__u32 map_info_len = sizeof(map_info);
5172 	int err;
5173 
5174 	memset(&map_info, 0, map_info_len);
5175 	err = bpf_map_get_info_by_fd(map_fd, &map_info, &map_info_len);
5176 	if (err && errno == EINVAL)
5177 		err = bpf_get_map_info_from_fdinfo(map_fd, &map_info);
5178 	if (err) {
5179 		pr_warn("failed to get map info for map FD %d: %s\n", map_fd,
5180 			errstr(err));
5181 		return false;
5182 	}
5183 
5184 	/*
5185 	 * bpf_get_map_info_by_fd() for DEVMAP will always return flags with
5186 	 * BPF_F_RDONLY_PROG set, but it generally is not set at map creation time.
5187 	 * Thus, ignore the BPF_F_RDONLY_PROG flag in the flags returned from
5188 	 * bpf_get_map_info_by_fd() when checking for compatibility with an
5189 	 * existing DEVMAP.
5190 	 */
5191 	if (map->def.type == BPF_MAP_TYPE_DEVMAP || map->def.type == BPF_MAP_TYPE_DEVMAP_HASH)
5192 		map_info.map_flags &= ~BPF_F_RDONLY_PROG;
5193 
5194 	return (map_info.type == map->def.type &&
5195 		map_info.key_size == map->def.key_size &&
5196 		map_info.value_size == map->def.value_size &&
5197 		map_info.max_entries == map->def.max_entries &&
5198 		map_info.map_flags == map->def.map_flags &&
5199 		map_info.map_extra == map->map_extra);
5200 }
5201 
5202 static int
5203 bpf_object__reuse_map(struct bpf_map *map)
5204 {
5205 	int err, pin_fd;
5206 
5207 	pin_fd = bpf_obj_get(map->pin_path);
5208 	if (pin_fd < 0) {
5209 		err = -errno;
5210 		if (err == -ENOENT) {
5211 			pr_debug("found no pinned map to reuse at '%s'\n",
5212 				 map->pin_path);
5213 			return 0;
5214 		}
5215 
5216 		pr_warn("couldn't retrieve pinned map '%s': %s\n",
5217 			map->pin_path, errstr(err));
5218 		return err;
5219 	}
5220 
5221 	if (!map_is_reuse_compat(map, pin_fd)) {
5222 		pr_warn("couldn't reuse pinned map at '%s': parameter mismatch\n",
5223 			map->pin_path);
5224 		close(pin_fd);
5225 		return -EINVAL;
5226 	}
5227 
5228 	err = bpf_map__reuse_fd(map, pin_fd);
5229 	close(pin_fd);
5230 	if (err)
5231 		return err;
5232 
5233 	map->pinned = true;
5234 	pr_debug("reused pinned map at '%s'\n", map->pin_path);
5235 
5236 	return 0;
5237 }
5238 
5239 static int
5240 bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
5241 {
5242 	enum libbpf_map_type map_type = map->libbpf_type;
5243 	int err, zero = 0;
5244 	size_t mmap_sz;
5245 
5246 	if (obj->gen_loader) {
5247 		bpf_gen__map_update_elem(obj->gen_loader, map - obj->maps,
5248 					 map->mmaped, map->def.value_size);
5249 		if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG)
5250 			bpf_gen__map_freeze(obj->gen_loader, map - obj->maps);
5251 		return 0;
5252 	}
5253 
5254 	err = bpf_map_update_elem(map->fd, &zero, map->mmaped, 0);
5255 	if (err) {
5256 		err = -errno;
5257 		pr_warn("map '%s': failed to set initial contents: %s\n",
5258 			bpf_map__name(map), errstr(err));
5259 		return err;
5260 	}
5261 
5262 	/* Freeze .rodata and .kconfig map as read-only from syscall side. */
5263 	if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG) {
5264 		err = bpf_map_freeze(map->fd);
5265 		if (err) {
5266 			err = -errno;
5267 			pr_warn("map '%s': failed to freeze as read-only: %s\n",
5268 				bpf_map__name(map), errstr(err));
5269 			return err;
5270 		}
5271 	}
5272 
5273 	/* Remap anonymous mmap()-ed "map initialization image" as
5274 	 * a BPF map-backed mmap()-ed memory, but preserving the same
5275 	 * memory address. This will cause kernel to change process'
5276 	 * page table to point to a different piece of kernel memory,
5277 	 * but from userspace point of view memory address (and its
5278 	 * contents, being identical at this point) will stay the
5279 	 * same. This mapping will be released by bpf_object__close()
5280 	 * as per normal clean up procedure.
5281 	 */
5282 	mmap_sz = bpf_map_mmap_sz(map);
5283 	if (map->def.map_flags & BPF_F_MMAPABLE) {
5284 		void *mmaped;
5285 		int prot;
5286 
5287 		if (map->def.map_flags & BPF_F_RDONLY_PROG)
5288 			prot = PROT_READ;
5289 		else
5290 			prot = PROT_READ | PROT_WRITE;
5291 		mmaped = mmap(map->mmaped, mmap_sz, prot, MAP_SHARED | MAP_FIXED, map->fd, 0);
5292 		if (mmaped == MAP_FAILED) {
5293 			err = -errno;
5294 			pr_warn("map '%s': failed to re-mmap() contents: %s\n",
5295 				bpf_map__name(map), errstr(err));
5296 			return err;
5297 		}
5298 		map->mmaped = mmaped;
5299 	} else if (map->mmaped) {
5300 		munmap(map->mmaped, mmap_sz);
5301 		map->mmaped = NULL;
5302 	}
5303 
5304 	return 0;
5305 }
5306 
5307 static void bpf_map__destroy(struct bpf_map *map);
5308 
5309 static int bpf_object__create_map(struct bpf_object *obj, struct bpf_map *map, bool is_inner)
5310 {
5311 	LIBBPF_OPTS(bpf_map_create_opts, create_attr);
5312 	struct bpf_map_def *def = &map->def;
5313 	const char *map_name = NULL;
5314 	int err = 0, map_fd;
5315 
5316 	if (kernel_supports(obj, FEAT_PROG_NAME))
5317 		map_name = map->name;
5318 	create_attr.map_ifindex = map->map_ifindex;
5319 	create_attr.map_flags = def->map_flags;
5320 	create_attr.numa_node = map->numa_node;
5321 	create_attr.map_extra = map->map_extra;
5322 	create_attr.token_fd = obj->token_fd;
5323 	if (obj->token_fd)
5324 		create_attr.map_flags |= BPF_F_TOKEN_FD;
5325 	if (map->excl_prog) {
5326 		err = bpf_prog_compute_hash(map->excl_prog);
5327 		if (err)
5328 			return err;
5329 
5330 		create_attr.excl_prog_hash = map->excl_prog->hash;
5331 		create_attr.excl_prog_hash_size = SHA256_DIGEST_LENGTH;
5332 	}
5333 
5334 	if (bpf_map__is_struct_ops(map)) {
5335 		create_attr.btf_vmlinux_value_type_id = map->btf_vmlinux_value_type_id;
5336 		if (map->mod_btf_fd >= 0) {
5337 			create_attr.value_type_btf_obj_fd = map->mod_btf_fd;
5338 			create_attr.map_flags |= BPF_F_VTYPE_BTF_OBJ_FD;
5339 		}
5340 	}
5341 
5342 	if (obj->btf && btf__fd(obj->btf) >= 0) {
5343 		create_attr.btf_fd = btf__fd(obj->btf);
5344 		create_attr.btf_key_type_id = map->btf_key_type_id;
5345 		create_attr.btf_value_type_id = map->btf_value_type_id;
5346 	}
5347 
5348 	if (bpf_map_type__is_map_in_map(def->type)) {
5349 		if (map->inner_map) {
5350 			err = map_set_def_max_entries(map->inner_map);
5351 			if (err)
5352 				return err;
5353 			err = bpf_object__create_map(obj, map->inner_map, true);
5354 			if (err) {
5355 				pr_warn("map '%s': failed to create inner map: %s\n",
5356 					map->name, errstr(err));
5357 				return err;
5358 			}
5359 			map->inner_map_fd = map->inner_map->fd;
5360 		}
5361 		if (map->inner_map_fd >= 0)
5362 			create_attr.inner_map_fd = map->inner_map_fd;
5363 	}
5364 
5365 	switch (def->type) {
5366 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
5367 	case BPF_MAP_TYPE_CGROUP_ARRAY:
5368 	case BPF_MAP_TYPE_STACK_TRACE:
5369 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
5370 	case BPF_MAP_TYPE_HASH_OF_MAPS:
5371 	case BPF_MAP_TYPE_DEVMAP:
5372 	case BPF_MAP_TYPE_DEVMAP_HASH:
5373 	case BPF_MAP_TYPE_CPUMAP:
5374 	case BPF_MAP_TYPE_XSKMAP:
5375 	case BPF_MAP_TYPE_SOCKMAP:
5376 	case BPF_MAP_TYPE_SOCKHASH:
5377 	case BPF_MAP_TYPE_QUEUE:
5378 	case BPF_MAP_TYPE_STACK:
5379 	case BPF_MAP_TYPE_ARENA:
5380 		create_attr.btf_fd = 0;
5381 		create_attr.btf_key_type_id = 0;
5382 		create_attr.btf_value_type_id = 0;
5383 		map->btf_key_type_id = 0;
5384 		map->btf_value_type_id = 0;
5385 		break;
5386 	case BPF_MAP_TYPE_STRUCT_OPS:
5387 		create_attr.btf_value_type_id = 0;
5388 		break;
5389 	default:
5390 		break;
5391 	}
5392 
5393 	if (obj->gen_loader) {
5394 		bpf_gen__map_create(obj->gen_loader, def->type, map_name,
5395 				    def->key_size, def->value_size, def->max_entries,
5396 				    &create_attr, is_inner ? -1 : map - obj->maps);
5397 		/* We keep pretenting we have valid FD to pass various fd >= 0
5398 		 * checks by just keeping original placeholder FDs in place.
5399 		 * See bpf_object__add_map() comment.
5400 		 * This placeholder fd will not be used with any syscall and
5401 		 * will be reset to -1 eventually.
5402 		 */
5403 		map_fd = map->fd;
5404 	} else {
5405 		map_fd = bpf_map_create(def->type, map_name,
5406 					def->key_size, def->value_size,
5407 					def->max_entries, &create_attr);
5408 	}
5409 	if (map_fd < 0 && (create_attr.btf_key_type_id || create_attr.btf_value_type_id)) {
5410 		err = -errno;
5411 		pr_warn("Error in bpf_create_map_xattr(%s): %s. Retrying without BTF.\n",
5412 			map->name, errstr(err));
5413 		create_attr.btf_fd = 0;
5414 		create_attr.btf_key_type_id = 0;
5415 		create_attr.btf_value_type_id = 0;
5416 		map->btf_key_type_id = 0;
5417 		map->btf_value_type_id = 0;
5418 		map_fd = bpf_map_create(def->type, map_name,
5419 					def->key_size, def->value_size,
5420 					def->max_entries, &create_attr);
5421 	}
5422 
5423 	if (bpf_map_type__is_map_in_map(def->type) && map->inner_map) {
5424 		if (obj->gen_loader)
5425 			map->inner_map->fd = -1;
5426 		bpf_map__destroy(map->inner_map);
5427 		zfree(&map->inner_map);
5428 	}
5429 
5430 	if (map_fd < 0)
5431 		return map_fd;
5432 
5433 	/* obj->gen_loader case, prevent reuse_fd() from closing map_fd */
5434 	if (map->fd == map_fd)
5435 		return 0;
5436 
5437 	/* Keep placeholder FD value but now point it to the BPF map object.
5438 	 * This way everything that relied on this map's FD (e.g., relocated
5439 	 * ldimm64 instructions) will stay valid and won't need adjustments.
5440 	 * map->fd stays valid but now point to what map_fd points to.
5441 	 */
5442 	return reuse_fd(map->fd, map_fd);
5443 }
5444 
5445 static int init_map_in_map_slots(struct bpf_object *obj, struct bpf_map *map)
5446 {
5447 	const struct bpf_map *targ_map;
5448 	unsigned int i;
5449 	int fd, err = 0;
5450 
5451 	for (i = 0; i < map->init_slots_sz; i++) {
5452 		if (!map->init_slots[i])
5453 			continue;
5454 
5455 		targ_map = map->init_slots[i];
5456 		fd = targ_map->fd;
5457 
5458 		if (obj->gen_loader) {
5459 			bpf_gen__populate_outer_map(obj->gen_loader,
5460 						    map - obj->maps, i,
5461 						    targ_map - obj->maps);
5462 		} else {
5463 			err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5464 		}
5465 		if (err) {
5466 			err = -errno;
5467 			pr_warn("map '%s': failed to initialize slot [%d] to map '%s' fd=%d: %s\n",
5468 				map->name, i, targ_map->name, fd, errstr(err));
5469 			return err;
5470 		}
5471 		pr_debug("map '%s': slot [%d] set to map '%s' fd=%d\n",
5472 			 map->name, i, targ_map->name, fd);
5473 	}
5474 
5475 	zfree(&map->init_slots);
5476 	map->init_slots_sz = 0;
5477 
5478 	return 0;
5479 }
5480 
5481 static int init_prog_array_slots(struct bpf_object *obj, struct bpf_map *map)
5482 {
5483 	const struct bpf_program *targ_prog;
5484 	unsigned int i;
5485 	int fd, err;
5486 
5487 	if (obj->gen_loader)
5488 		return -ENOTSUP;
5489 
5490 	for (i = 0; i < map->init_slots_sz; i++) {
5491 		if (!map->init_slots[i])
5492 			continue;
5493 
5494 		targ_prog = map->init_slots[i];
5495 		fd = bpf_program__fd(targ_prog);
5496 
5497 		err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5498 		if (err) {
5499 			err = -errno;
5500 			pr_warn("map '%s': failed to initialize slot [%d] to prog '%s' fd=%d: %s\n",
5501 				map->name, i, targ_prog->name, fd, errstr(err));
5502 			return err;
5503 		}
5504 		pr_debug("map '%s': slot [%d] set to prog '%s' fd=%d\n",
5505 			 map->name, i, targ_prog->name, fd);
5506 	}
5507 
5508 	zfree(&map->init_slots);
5509 	map->init_slots_sz = 0;
5510 
5511 	return 0;
5512 }
5513 
5514 static int bpf_object_init_prog_arrays(struct bpf_object *obj)
5515 {
5516 	struct bpf_map *map;
5517 	int i, err;
5518 
5519 	for (i = 0; i < obj->nr_maps; i++) {
5520 		map = &obj->maps[i];
5521 
5522 		if (!map->init_slots_sz || map->def.type != BPF_MAP_TYPE_PROG_ARRAY)
5523 			continue;
5524 
5525 		err = init_prog_array_slots(obj, map);
5526 		if (err < 0)
5527 			return err;
5528 	}
5529 	return 0;
5530 }
5531 
5532 static int map_set_def_max_entries(struct bpf_map *map)
5533 {
5534 	if (map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY && !map->def.max_entries) {
5535 		int nr_cpus;
5536 
5537 		nr_cpus = libbpf_num_possible_cpus();
5538 		if (nr_cpus < 0) {
5539 			pr_warn("map '%s': failed to determine number of system CPUs: %d\n",
5540 				map->name, nr_cpus);
5541 			return nr_cpus;
5542 		}
5543 		pr_debug("map '%s': setting size to %d\n", map->name, nr_cpus);
5544 		map->def.max_entries = nr_cpus;
5545 	}
5546 
5547 	return 0;
5548 }
5549 
5550 static int
5551 bpf_object__create_maps(struct bpf_object *obj)
5552 {
5553 	struct bpf_map *map;
5554 	unsigned int i, j;
5555 	int err;
5556 	bool retried;
5557 
5558 	for (i = 0; i < obj->nr_maps; i++) {
5559 		map = &obj->maps[i];
5560 
5561 		/* To support old kernels, we skip creating global data maps
5562 		 * (.rodata, .data, .kconfig, etc); later on, during program
5563 		 * loading, if we detect that at least one of the to-be-loaded
5564 		 * programs is referencing any global data map, we'll error
5565 		 * out with program name and relocation index logged.
5566 		 * This approach allows to accommodate Clang emitting
5567 		 * unnecessary .rodata.str1.1 sections for string literals,
5568 		 * but also it allows to have CO-RE applications that use
5569 		 * global variables in some of BPF programs, but not others.
5570 		 * If those global variable-using programs are not loaded at
5571 		 * runtime due to bpf_program__set_autoload(prog, false),
5572 		 * bpf_object loading will succeed just fine even on old
5573 		 * kernels.
5574 		 */
5575 		if (bpf_map__is_internal(map) && !kernel_supports(obj, FEAT_GLOBAL_DATA))
5576 			map->autocreate = false;
5577 
5578 		if (!map->autocreate) {
5579 			pr_debug("map '%s': skipped auto-creating...\n", map->name);
5580 			continue;
5581 		}
5582 
5583 		err = map_set_def_max_entries(map);
5584 		if (err)
5585 			goto err_out;
5586 
5587 		retried = false;
5588 retry:
5589 		if (map->pin_path) {
5590 			err = bpf_object__reuse_map(map);
5591 			if (err) {
5592 				pr_warn("map '%s': error reusing pinned map\n",
5593 					map->name);
5594 				goto err_out;
5595 			}
5596 			if (retried && map->fd < 0) {
5597 				pr_warn("map '%s': cannot find pinned map\n",
5598 					map->name);
5599 				err = -ENOENT;
5600 				goto err_out;
5601 			}
5602 		}
5603 
5604 		if (map->reused) {
5605 			pr_debug("map '%s': skipping creation (preset fd=%d)\n",
5606 				 map->name, map->fd);
5607 		} else {
5608 			err = bpf_object__create_map(obj, map, false);
5609 			if (err)
5610 				goto err_out;
5611 
5612 			pr_debug("map '%s': created successfully, fd=%d\n",
5613 				 map->name, map->fd);
5614 
5615 			if (bpf_map__is_internal(map)) {
5616 				err = bpf_object__populate_internal_map(obj, map);
5617 				if (err < 0)
5618 					goto err_out;
5619 			} else if (map->def.type == BPF_MAP_TYPE_ARENA) {
5620 				map->mmaped = mmap((void *)(long)map->map_extra,
5621 						   bpf_map_mmap_sz(map), PROT_READ | PROT_WRITE,
5622 						   map->map_extra ? MAP_SHARED | MAP_FIXED : MAP_SHARED,
5623 						   map->fd, 0);
5624 				if (map->mmaped == MAP_FAILED) {
5625 					err = -errno;
5626 					map->mmaped = NULL;
5627 					pr_warn("map '%s': failed to mmap arena: %s\n",
5628 						map->name, errstr(err));
5629 					return err;
5630 				}
5631 				if (obj->arena_data) {
5632 					memcpy(map->mmaped + obj->arena_data_off, obj->arena_data,
5633 						obj->arena_data_sz);
5634 					zfree(&obj->arena_data);
5635 				}
5636 			}
5637 			if (map->init_slots_sz && map->def.type != BPF_MAP_TYPE_PROG_ARRAY) {
5638 				err = init_map_in_map_slots(obj, map);
5639 				if (err < 0)
5640 					goto err_out;
5641 			}
5642 		}
5643 
5644 		if (map->pin_path && !map->pinned) {
5645 			err = bpf_map__pin(map, NULL);
5646 			if (err) {
5647 				if (!retried && err == -EEXIST) {
5648 					retried = true;
5649 					goto retry;
5650 				}
5651 				pr_warn("map '%s': failed to auto-pin at '%s': %s\n",
5652 					map->name, map->pin_path, errstr(err));
5653 				goto err_out;
5654 			}
5655 		}
5656 	}
5657 
5658 	return 0;
5659 
5660 err_out:
5661 	pr_warn("map '%s': failed to create: %s\n", map->name, errstr(err));
5662 	pr_perm_msg(err);
5663 	for (j = 0; j < i; j++)
5664 		zclose(obj->maps[j].fd);
5665 	return err;
5666 }
5667 
5668 static bool bpf_core_is_flavor_sep(const char *s)
5669 {
5670 	/* check X___Y name pattern, where X and Y are not underscores */
5671 	return s[0] != '_' &&				      /* X */
5672 	       s[1] == '_' && s[2] == '_' && s[3] == '_' &&   /* ___ */
5673 	       s[4] != '_';				      /* Y */
5674 }
5675 
5676 /* Given 'some_struct_name___with_flavor' return the length of a name prefix
5677  * before last triple underscore. Struct name part after last triple
5678  * underscore is ignored by BPF CO-RE relocation during relocation matching.
5679  */
5680 size_t bpf_core_essential_name_len(const char *name)
5681 {
5682 	size_t n = strlen(name);
5683 	int i;
5684 
5685 	for (i = n - 5; i >= 0; i--) {
5686 		if (bpf_core_is_flavor_sep(name + i))
5687 			return i + 1;
5688 	}
5689 	return n;
5690 }
5691 
5692 void bpf_core_free_cands(struct bpf_core_cand_list *cands)
5693 {
5694 	if (!cands)
5695 		return;
5696 
5697 	free(cands->cands);
5698 	free(cands);
5699 }
5700 
5701 int bpf_core_add_cands(struct bpf_core_cand *local_cand,
5702 		       size_t local_essent_len,
5703 		       const struct btf *targ_btf,
5704 		       const char *targ_btf_name,
5705 		       int targ_start_id,
5706 		       struct bpf_core_cand_list *cands)
5707 {
5708 	struct bpf_core_cand *new_cands, *cand;
5709 	const struct btf_type *t, *local_t;
5710 	const char *targ_name, *local_name;
5711 	size_t targ_essent_len;
5712 	int n, i;
5713 
5714 	local_t = btf__type_by_id(local_cand->btf, local_cand->id);
5715 	local_name = btf__str_by_offset(local_cand->btf, local_t->name_off);
5716 
5717 	n = btf__type_cnt(targ_btf);
5718 	for (i = targ_start_id; i < n; i++) {
5719 		t = btf__type_by_id(targ_btf, i);
5720 		if (!btf_kind_core_compat(t, local_t))
5721 			continue;
5722 
5723 		targ_name = btf__name_by_offset(targ_btf, t->name_off);
5724 		if (str_is_empty(targ_name))
5725 			continue;
5726 
5727 		targ_essent_len = bpf_core_essential_name_len(targ_name);
5728 		if (targ_essent_len != local_essent_len)
5729 			continue;
5730 
5731 		if (strncmp(local_name, targ_name, local_essent_len) != 0)
5732 			continue;
5733 
5734 		pr_debug("CO-RE relocating [%d] %s %s: found target candidate [%d] %s %s in [%s]\n",
5735 			 local_cand->id, btf_kind_str(local_t),
5736 			 local_name, i, btf_kind_str(t), targ_name,
5737 			 targ_btf_name);
5738 		new_cands = libbpf_reallocarray(cands->cands, cands->len + 1,
5739 					      sizeof(*cands->cands));
5740 		if (!new_cands)
5741 			return -ENOMEM;
5742 
5743 		cand = &new_cands[cands->len];
5744 		cand->btf = targ_btf;
5745 		cand->id = i;
5746 
5747 		cands->cands = new_cands;
5748 		cands->len++;
5749 	}
5750 	return 0;
5751 }
5752 
5753 static int load_module_btfs(struct bpf_object *obj)
5754 {
5755 	struct bpf_btf_info info;
5756 	struct module_btf *mod_btf;
5757 	struct btf *btf;
5758 	char name[64];
5759 	__u32 id = 0, len;
5760 	int err, fd;
5761 
5762 	if (obj->btf_modules_loaded)
5763 		return 0;
5764 
5765 	if (obj->gen_loader)
5766 		return 0;
5767 
5768 	/* don't do this again, even if we find no module BTFs */
5769 	obj->btf_modules_loaded = true;
5770 
5771 	/* kernel too old to support module BTFs */
5772 	if (!kernel_supports(obj, FEAT_MODULE_BTF))
5773 		return 0;
5774 
5775 	while (true) {
5776 		err = bpf_btf_get_next_id(id, &id);
5777 		if (err && errno == ENOENT)
5778 			return 0;
5779 		if (err && errno == EPERM) {
5780 			pr_debug("skipping module BTFs loading, missing privileges\n");
5781 			return 0;
5782 		}
5783 		if (err) {
5784 			err = -errno;
5785 			pr_warn("failed to iterate BTF objects: %s\n", errstr(err));
5786 			return err;
5787 		}
5788 
5789 		fd = bpf_btf_get_fd_by_id(id);
5790 		if (fd < 0) {
5791 			if (errno == ENOENT)
5792 				continue; /* expected race: BTF was unloaded */
5793 			err = -errno;
5794 			pr_warn("failed to get BTF object #%d FD: %s\n", id, errstr(err));
5795 			return err;
5796 		}
5797 
5798 		len = sizeof(info);
5799 		memset(&info, 0, sizeof(info));
5800 		info.name = ptr_to_u64(name);
5801 		info.name_len = sizeof(name);
5802 
5803 		err = bpf_btf_get_info_by_fd(fd, &info, &len);
5804 		if (err) {
5805 			err = -errno;
5806 			pr_warn("failed to get BTF object #%d info: %s\n", id, errstr(err));
5807 			goto err_out;
5808 		}
5809 
5810 		/* ignore non-module BTFs */
5811 		if (!info.kernel_btf || strcmp(name, "vmlinux") == 0) {
5812 			close(fd);
5813 			continue;
5814 		}
5815 
5816 		btf = btf_get_from_fd(fd, obj->btf_vmlinux);
5817 		err = libbpf_get_error(btf);
5818 		if (err) {
5819 			pr_warn("failed to load module [%s]'s BTF object #%d: %s\n",
5820 				name, id, errstr(err));
5821 			goto err_out;
5822 		}
5823 
5824 		err = libbpf_ensure_mem((void **)&obj->btf_modules, &obj->btf_module_cap,
5825 					sizeof(*obj->btf_modules), obj->btf_module_cnt + 1);
5826 		if (err)
5827 			goto err_out;
5828 
5829 		mod_btf = &obj->btf_modules[obj->btf_module_cnt++];
5830 
5831 		mod_btf->btf = btf;
5832 		mod_btf->id = id;
5833 		mod_btf->fd = fd;
5834 		mod_btf->name = strdup(name);
5835 		if (!mod_btf->name) {
5836 			err = -ENOMEM;
5837 			goto err_out;
5838 		}
5839 		continue;
5840 
5841 err_out:
5842 		close(fd);
5843 		return err;
5844 	}
5845 
5846 	return 0;
5847 }
5848 
5849 static struct bpf_core_cand_list *
5850 bpf_core_find_cands(struct bpf_object *obj, const struct btf *local_btf, __u32 local_type_id)
5851 {
5852 	struct bpf_core_cand local_cand = {};
5853 	struct bpf_core_cand_list *cands;
5854 	const struct btf *main_btf;
5855 	const struct btf_type *local_t;
5856 	const char *local_name;
5857 	size_t local_essent_len;
5858 	int err, i;
5859 
5860 	local_cand.btf = local_btf;
5861 	local_cand.id = local_type_id;
5862 	local_t = btf__type_by_id(local_btf, local_type_id);
5863 	if (!local_t)
5864 		return ERR_PTR(-EINVAL);
5865 
5866 	local_name = btf__name_by_offset(local_btf, local_t->name_off);
5867 	if (str_is_empty(local_name))
5868 		return ERR_PTR(-EINVAL);
5869 	local_essent_len = bpf_core_essential_name_len(local_name);
5870 
5871 	cands = calloc(1, sizeof(*cands));
5872 	if (!cands)
5873 		return ERR_PTR(-ENOMEM);
5874 
5875 	/* Attempt to find target candidates in vmlinux BTF first */
5876 	main_btf = obj->btf_vmlinux_override ?: obj->btf_vmlinux;
5877 	err = bpf_core_add_cands(&local_cand, local_essent_len, main_btf, "vmlinux", 1, cands);
5878 	if (err)
5879 		goto err_out;
5880 
5881 	/* if vmlinux BTF has any candidate, don't got for module BTFs */
5882 	if (cands->len)
5883 		return cands;
5884 
5885 	/* if vmlinux BTF was overridden, don't attempt to load module BTFs */
5886 	if (obj->btf_vmlinux_override)
5887 		return cands;
5888 
5889 	/* now look through module BTFs, trying to still find candidates */
5890 	err = load_module_btfs(obj);
5891 	if (err)
5892 		goto err_out;
5893 
5894 	for (i = 0; i < obj->btf_module_cnt; i++) {
5895 		err = bpf_core_add_cands(&local_cand, local_essent_len,
5896 					 obj->btf_modules[i].btf,
5897 					 obj->btf_modules[i].name,
5898 					 btf__type_cnt(obj->btf_vmlinux),
5899 					 cands);
5900 		if (err)
5901 			goto err_out;
5902 	}
5903 
5904 	return cands;
5905 err_out:
5906 	bpf_core_free_cands(cands);
5907 	return ERR_PTR(err);
5908 }
5909 
5910 /* Check local and target types for compatibility. This check is used for
5911  * type-based CO-RE relocations and follow slightly different rules than
5912  * field-based relocations. This function assumes that root types were already
5913  * checked for name match. Beyond that initial root-level name check, names
5914  * are completely ignored. Compatibility rules are as follows:
5915  *   - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs are considered compatible, but
5916  *     kind should match for local and target types (i.e., STRUCT is not
5917  *     compatible with UNION);
5918  *   - for ENUMs, the size is ignored;
5919  *   - for INT, size and signedness are ignored;
5920  *   - for ARRAY, dimensionality is ignored, element types are checked for
5921  *     compatibility recursively;
5922  *   - CONST/VOLATILE/RESTRICT modifiers are ignored;
5923  *   - TYPEDEFs/PTRs are compatible if types they pointing to are compatible;
5924  *   - FUNC_PROTOs are compatible if they have compatible signature: same
5925  *     number of input args and compatible return and argument types.
5926  * These rules are not set in stone and probably will be adjusted as we get
5927  * more experience with using BPF CO-RE relocations.
5928  */
5929 int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
5930 			      const struct btf *targ_btf, __u32 targ_id)
5931 {
5932 	return __bpf_core_types_are_compat(local_btf, local_id, targ_btf, targ_id, 32);
5933 }
5934 
5935 int bpf_core_types_match(const struct btf *local_btf, __u32 local_id,
5936 			 const struct btf *targ_btf, __u32 targ_id)
5937 {
5938 	return __bpf_core_types_match(local_btf, local_id, targ_btf, targ_id, false, 32);
5939 }
5940 
5941 static size_t bpf_core_hash_fn(const long key, void *ctx)
5942 {
5943 	return key;
5944 }
5945 
5946 static bool bpf_core_equal_fn(const long k1, const long k2, void *ctx)
5947 {
5948 	return k1 == k2;
5949 }
5950 
5951 static int record_relo_core(struct bpf_program *prog,
5952 			    const struct bpf_core_relo *core_relo, int insn_idx)
5953 {
5954 	struct reloc_desc *relos, *relo;
5955 
5956 	relos = libbpf_reallocarray(prog->reloc_desc,
5957 				    prog->nr_reloc + 1, sizeof(*relos));
5958 	if (!relos)
5959 		return -ENOMEM;
5960 	relo = &relos[prog->nr_reloc];
5961 	relo->type = RELO_CORE;
5962 	relo->insn_idx = insn_idx;
5963 	relo->core_relo = core_relo;
5964 	prog->reloc_desc = relos;
5965 	prog->nr_reloc++;
5966 	return 0;
5967 }
5968 
5969 static const struct bpf_core_relo *find_relo_core(struct bpf_program *prog, int insn_idx)
5970 {
5971 	struct reloc_desc *relo;
5972 	int i;
5973 
5974 	for (i = 0; i < prog->nr_reloc; i++) {
5975 		relo = &prog->reloc_desc[i];
5976 		if (relo->type != RELO_CORE || relo->insn_idx != insn_idx)
5977 			continue;
5978 
5979 		return relo->core_relo;
5980 	}
5981 
5982 	return NULL;
5983 }
5984 
5985 static int bpf_core_resolve_relo(struct bpf_program *prog,
5986 				 const struct bpf_core_relo *relo,
5987 				 int relo_idx,
5988 				 const struct btf *local_btf,
5989 				 struct hashmap *cand_cache,
5990 				 struct bpf_core_relo_res *targ_res)
5991 {
5992 	struct bpf_core_spec specs_scratch[3] = {};
5993 	struct bpf_core_cand_list *cands = NULL;
5994 	const char *prog_name = prog->name;
5995 	const struct btf_type *local_type;
5996 	const char *local_name;
5997 	__u32 local_id = relo->type_id;
5998 	int err;
5999 
6000 	local_type = btf__type_by_id(local_btf, local_id);
6001 	if (!local_type)
6002 		return -EINVAL;
6003 
6004 	local_name = btf__name_by_offset(local_btf, local_type->name_off);
6005 	if (!local_name)
6006 		return -EINVAL;
6007 
6008 	if (relo->kind != BPF_CORE_TYPE_ID_LOCAL &&
6009 	    !hashmap__find(cand_cache, local_id, &cands)) {
6010 		cands = bpf_core_find_cands(prog->obj, local_btf, local_id);
6011 		if (IS_ERR(cands)) {
6012 			pr_warn("prog '%s': relo #%d: target candidate search failed for [%d] %s %s: %ld\n",
6013 				prog_name, relo_idx, local_id, btf_kind_str(local_type),
6014 				local_name, PTR_ERR(cands));
6015 			return PTR_ERR(cands);
6016 		}
6017 		err = hashmap__set(cand_cache, local_id, cands, NULL, NULL);
6018 		if (err) {
6019 			bpf_core_free_cands(cands);
6020 			return err;
6021 		}
6022 	}
6023 
6024 	return bpf_core_calc_relo_insn(prog_name, relo, relo_idx, local_btf, cands, specs_scratch,
6025 				       targ_res);
6026 }
6027 
6028 static int
6029 bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
6030 {
6031 	const struct btf_ext_info_sec *sec;
6032 	struct bpf_core_relo_res targ_res;
6033 	const struct bpf_core_relo *rec;
6034 	const struct btf_ext_info *seg;
6035 	struct hashmap_entry *entry;
6036 	struct hashmap *cand_cache = NULL;
6037 	struct bpf_program *prog;
6038 	struct bpf_insn *insn;
6039 	const char *sec_name;
6040 	int i, err = 0, insn_idx, sec_idx, sec_num;
6041 
6042 	if (obj->btf_ext->core_relo_info.len == 0)
6043 		return 0;
6044 
6045 	if (targ_btf_path) {
6046 		obj->btf_vmlinux_override = btf__parse(targ_btf_path, NULL);
6047 		err = libbpf_get_error(obj->btf_vmlinux_override);
6048 		if (err) {
6049 			pr_warn("failed to parse target BTF: %s\n", errstr(err));
6050 			return err;
6051 		}
6052 	}
6053 
6054 	cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
6055 	if (IS_ERR(cand_cache)) {
6056 		err = PTR_ERR(cand_cache);
6057 		goto out;
6058 	}
6059 
6060 	seg = &obj->btf_ext->core_relo_info;
6061 	sec_num = 0;
6062 	for_each_btf_ext_sec(seg, sec) {
6063 		sec_idx = seg->sec_idxs[sec_num];
6064 		sec_num++;
6065 
6066 		sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
6067 		if (str_is_empty(sec_name)) {
6068 			err = -EINVAL;
6069 			goto out;
6070 		}
6071 
6072 		pr_debug("sec '%s': found %d CO-RE relocations\n", sec_name, sec->num_info);
6073 
6074 		for_each_btf_ext_rec(seg, sec, i, rec) {
6075 			if (rec->insn_off % BPF_INSN_SZ)
6076 				return -EINVAL;
6077 			insn_idx = rec->insn_off / BPF_INSN_SZ;
6078 			prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
6079 			if (!prog) {
6080 				/* When __weak subprog is "overridden" by another instance
6081 				 * of the subprog from a different object file, linker still
6082 				 * appends all the .BTF.ext info that used to belong to that
6083 				 * eliminated subprogram.
6084 				 * This is similar to what x86-64 linker does for relocations.
6085 				 * So just ignore such relocations just like we ignore
6086 				 * subprog instructions when discovering subprograms.
6087 				 */
6088 				pr_debug("sec '%s': skipping CO-RE relocation #%d for insn #%d belonging to eliminated weak subprogram\n",
6089 					 sec_name, i, insn_idx);
6090 				continue;
6091 			}
6092 			/* no need to apply CO-RE relocation if the program is
6093 			 * not going to be loaded
6094 			 */
6095 			if (!prog->autoload)
6096 				continue;
6097 
6098 			/* adjust insn_idx from section frame of reference to the local
6099 			 * program's frame of reference; (sub-)program code is not yet
6100 			 * relocated, so it's enough to just subtract in-section offset
6101 			 */
6102 			insn_idx = insn_idx - prog->sec_insn_off;
6103 			if (insn_idx >= prog->insns_cnt)
6104 				return -EINVAL;
6105 			insn = &prog->insns[insn_idx];
6106 
6107 			err = record_relo_core(prog, rec, insn_idx);
6108 			if (err) {
6109 				pr_warn("prog '%s': relo #%d: failed to record relocation: %s\n",
6110 					prog->name, i, errstr(err));
6111 				goto out;
6112 			}
6113 
6114 			if (prog->obj->gen_loader)
6115 				continue;
6116 
6117 			err = bpf_core_resolve_relo(prog, rec, i, obj->btf, cand_cache, &targ_res);
6118 			if (err) {
6119 				pr_warn("prog '%s': relo #%d: failed to relocate: %s\n",
6120 					prog->name, i, errstr(err));
6121 				goto out;
6122 			}
6123 
6124 			err = bpf_core_patch_insn(prog->name, insn, insn_idx, rec, i, &targ_res);
6125 			if (err) {
6126 				pr_warn("prog '%s': relo #%d: failed to patch insn #%u: %s\n",
6127 					prog->name, i, insn_idx, errstr(err));
6128 				goto out;
6129 			}
6130 		}
6131 	}
6132 
6133 out:
6134 	/* obj->btf_vmlinux and module BTFs are freed after object load */
6135 	btf__free(obj->btf_vmlinux_override);
6136 	obj->btf_vmlinux_override = NULL;
6137 
6138 	if (!IS_ERR_OR_NULL(cand_cache)) {
6139 		hashmap__for_each_entry(cand_cache, entry, i) {
6140 			bpf_core_free_cands(entry->pvalue);
6141 		}
6142 		hashmap__free(cand_cache);
6143 	}
6144 	return err;
6145 }
6146 
6147 /* base map load ldimm64 special constant, used also for log fixup logic */
6148 #define POISON_LDIMM64_MAP_BASE 2001000000
6149 #define POISON_LDIMM64_MAP_PFX "200100"
6150 
6151 static void poison_map_ldimm64(struct bpf_program *prog, int relo_idx,
6152 			       int insn_idx, struct bpf_insn *insn,
6153 			       int map_idx, const struct bpf_map *map)
6154 {
6155 	int i;
6156 
6157 	pr_debug("prog '%s': relo #%d: poisoning insn #%d that loads map #%d '%s'\n",
6158 		 prog->name, relo_idx, insn_idx, map_idx, map->name);
6159 
6160 	/* we turn single ldimm64 into two identical invalid calls */
6161 	for (i = 0; i < 2; i++) {
6162 		insn->code = BPF_JMP | BPF_CALL;
6163 		insn->dst_reg = 0;
6164 		insn->src_reg = 0;
6165 		insn->off = 0;
6166 		/* if this instruction is reachable (not a dead code),
6167 		 * verifier will complain with something like:
6168 		 * invalid func unknown#2001000123
6169 		 * where lower 123 is map index into obj->maps[] array
6170 		 */
6171 		insn->imm = POISON_LDIMM64_MAP_BASE + map_idx;
6172 
6173 		insn++;
6174 	}
6175 }
6176 
6177 /* unresolved kfunc call special constant, used also for log fixup logic */
6178 #define POISON_CALL_KFUNC_BASE 2002000000
6179 #define POISON_CALL_KFUNC_PFX "2002"
6180 
6181 static void poison_kfunc_call(struct bpf_program *prog, int relo_idx,
6182 			      int insn_idx, struct bpf_insn *insn,
6183 			      int ext_idx, const struct extern_desc *ext)
6184 {
6185 	pr_debug("prog '%s': relo #%d: poisoning insn #%d that calls kfunc '%s'\n",
6186 		 prog->name, relo_idx, insn_idx, ext->name);
6187 
6188 	/* we turn kfunc call into invalid helper call with identifiable constant */
6189 	insn->code = BPF_JMP | BPF_CALL;
6190 	insn->dst_reg = 0;
6191 	insn->src_reg = 0;
6192 	insn->off = 0;
6193 	/* if this instruction is reachable (not a dead code),
6194 	 * verifier will complain with something like:
6195 	 * invalid func unknown#2001000123
6196 	 * where lower 123 is extern index into obj->externs[] array
6197 	 */
6198 	insn->imm = POISON_CALL_KFUNC_BASE + ext_idx;
6199 }
6200 
6201 static int find_jt_map(struct bpf_object *obj, struct bpf_program *prog, unsigned int sym_off)
6202 {
6203 	size_t i;
6204 
6205 	for (i = 0; i < obj->jumptable_map_cnt; i++) {
6206 		/*
6207 		 * This might happen that same offset is used for two different
6208 		 * programs (as jump tables can be the same). However, for
6209 		 * different programs different maps should be created.
6210 		 */
6211 		if (obj->jumptable_maps[i].sym_off == sym_off &&
6212 		    obj->jumptable_maps[i].prog == prog)
6213 			return obj->jumptable_maps[i].fd;
6214 	}
6215 
6216 	return -ENOENT;
6217 }
6218 
6219 static int add_jt_map(struct bpf_object *obj, struct bpf_program *prog, unsigned int sym_off, int map_fd)
6220 {
6221 	size_t cnt = obj->jumptable_map_cnt;
6222 	size_t size = sizeof(obj->jumptable_maps[0]);
6223 	void *tmp;
6224 
6225 	tmp = libbpf_reallocarray(obj->jumptable_maps, cnt + 1, size);
6226 	if (!tmp)
6227 		return -ENOMEM;
6228 
6229 	obj->jumptable_maps = tmp;
6230 	obj->jumptable_maps[cnt].prog = prog;
6231 	obj->jumptable_maps[cnt].sym_off = sym_off;
6232 	obj->jumptable_maps[cnt].fd = map_fd;
6233 	obj->jumptable_map_cnt++;
6234 
6235 	return 0;
6236 }
6237 
6238 static int find_subprog_idx(struct bpf_program *prog, int insn_idx)
6239 {
6240 	int i;
6241 
6242 	for (i = prog->subprog_cnt - 1; i >= 0; i--) {
6243 		if (insn_idx >= prog->subprogs[i].sub_insn_off)
6244 			return i;
6245 	}
6246 
6247 	return -1;
6248 }
6249 
6250 static int create_jt_map(struct bpf_object *obj, struct bpf_program *prog, struct reloc_desc *relo)
6251 {
6252 	const __u32 jt_entry_size = 8;
6253 	unsigned int sym_off = relo->sym_off;
6254 	int jt_size = relo->sym_size;
6255 	__u32 max_entries = jt_size / jt_entry_size;
6256 	__u32 value_size = sizeof(struct bpf_insn_array_value);
6257 	struct bpf_insn_array_value val = {};
6258 	int subprog_idx;
6259 	int map_fd, err;
6260 	__u64 insn_off;
6261 	__u64 *jt;
6262 	__u32 i;
6263 
6264 	map_fd = find_jt_map(obj, prog, sym_off);
6265 	if (map_fd >= 0)
6266 		return map_fd;
6267 
6268 	if (sym_off % jt_entry_size) {
6269 		pr_warn("map '.jumptables': jumptable start %u should be multiple of %u\n",
6270 			sym_off, jt_entry_size);
6271 		return -EINVAL;
6272 	}
6273 
6274 	if (jt_size % jt_entry_size) {
6275 		pr_warn("map '.jumptables': jumptable size %d should be multiple of %u\n",
6276 			jt_size, jt_entry_size);
6277 		return -EINVAL;
6278 	}
6279 
6280 	map_fd = bpf_map_create(BPF_MAP_TYPE_INSN_ARRAY, ".jumptables",
6281 				4, value_size, max_entries, NULL);
6282 	if (map_fd < 0)
6283 		return map_fd;
6284 
6285 	if (!obj->jumptables_data) {
6286 		pr_warn("map '.jumptables': ELF file is missing jump table data\n");
6287 		err = -EINVAL;
6288 		goto err_close;
6289 	}
6290 	if (sym_off + jt_size > obj->jumptables_data_sz) {
6291 		pr_warn("map '.jumptables': jumptables_data size is %zd, trying to access %d\n",
6292 			obj->jumptables_data_sz, sym_off + jt_size);
6293 		err = -EINVAL;
6294 		goto err_close;
6295 	}
6296 
6297 	subprog_idx = -1; /* main program */
6298 	if (relo->insn_idx < 0 || relo->insn_idx >= prog->insns_cnt) {
6299 		pr_warn("map '.jumptables': invalid instruction index %d\n", relo->insn_idx);
6300 		err = -EINVAL;
6301 		goto err_close;
6302 	}
6303 	if (prog->subprogs)
6304 		subprog_idx = find_subprog_idx(prog, relo->insn_idx);
6305 
6306 	jt = (__u64 *)(obj->jumptables_data + sym_off);
6307 	for (i = 0; i < max_entries; i++) {
6308 		/*
6309 		 * The offset should be made to be relative to the beginning of
6310 		 * the main function, not the subfunction.
6311 		 */
6312 		insn_off = jt[i]/sizeof(struct bpf_insn);
6313 		if (subprog_idx >= 0) {
6314 			insn_off -= prog->subprogs[subprog_idx].sec_insn_off;
6315 			insn_off += prog->subprogs[subprog_idx].sub_insn_off;
6316 		} else {
6317 			insn_off -= prog->sec_insn_off;
6318 		}
6319 
6320 		/*
6321 		 * LLVM-generated jump tables contain u64 records, however
6322 		 * should contain values that fit in u32.
6323 		 */
6324 		if (insn_off > UINT32_MAX) {
6325 			pr_warn("map '.jumptables': invalid jump table value 0x%llx at offset %u\n",
6326 				(long long)jt[i], sym_off + i * jt_entry_size);
6327 			err = -EINVAL;
6328 			goto err_close;
6329 		}
6330 
6331 		val.orig_off = insn_off;
6332 		err = bpf_map_update_elem(map_fd, &i, &val, 0);
6333 		if (err)
6334 			goto err_close;
6335 	}
6336 
6337 	err = bpf_map_freeze(map_fd);
6338 	if (err)
6339 		goto err_close;
6340 
6341 	err = add_jt_map(obj, prog, sym_off, map_fd);
6342 	if (err)
6343 		goto err_close;
6344 
6345 	return map_fd;
6346 
6347 err_close:
6348 	close(map_fd);
6349 	return err;
6350 }
6351 
6352 /* Relocate data references within program code:
6353  *  - map references;
6354  *  - global variable references;
6355  *  - extern references.
6356  */
6357 static int
6358 bpf_object__relocate_data(struct bpf_object *obj, struct bpf_program *prog)
6359 {
6360 	int i;
6361 
6362 	for (i = 0; i < prog->nr_reloc; i++) {
6363 		struct reloc_desc *relo = &prog->reloc_desc[i];
6364 		struct bpf_insn *insn = &prog->insns[relo->insn_idx];
6365 		const struct bpf_map *map;
6366 		struct extern_desc *ext;
6367 
6368 		switch (relo->type) {
6369 		case RELO_LD64:
6370 			map = &obj->maps[relo->map_idx];
6371 			if (obj->gen_loader) {
6372 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX;
6373 				insn[0].imm = relo->map_idx;
6374 			} else if (map->autocreate) {
6375 				insn[0].src_reg = BPF_PSEUDO_MAP_FD;
6376 				insn[0].imm = map->fd;
6377 			} else {
6378 				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
6379 						   relo->map_idx, map);
6380 			}
6381 			break;
6382 		case RELO_DATA:
6383 			map = &obj->maps[relo->map_idx];
6384 			insn[1].imm = insn[0].imm + relo->sym_off;
6385 			if (obj->gen_loader) {
6386 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
6387 				insn[0].imm = relo->map_idx;
6388 			} else if (map->autocreate) {
6389 				insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6390 				insn[0].imm = map->fd;
6391 			} else {
6392 				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
6393 						   relo->map_idx, map);
6394 			}
6395 			break;
6396 		case RELO_EXTERN_LD64:
6397 			ext = &obj->externs[relo->ext_idx];
6398 			if (ext->type == EXT_KCFG) {
6399 				if (obj->gen_loader) {
6400 					insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
6401 					insn[0].imm = obj->kconfig_map_idx;
6402 				} else {
6403 					insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6404 					insn[0].imm = obj->maps[obj->kconfig_map_idx].fd;
6405 				}
6406 				insn[1].imm = ext->kcfg.data_off;
6407 			} else /* EXT_KSYM */ {
6408 				if (ext->ksym.type_id && ext->is_set) { /* typed ksyms */
6409 					insn[0].src_reg = BPF_PSEUDO_BTF_ID;
6410 					insn[0].imm = ext->ksym.kernel_btf_id;
6411 					insn[1].imm = ext->ksym.kernel_btf_obj_fd;
6412 				} else { /* typeless ksyms or unresolved typed ksyms */
6413 					insn[0].imm = (__u32)ext->ksym.addr;
6414 					insn[1].imm = ext->ksym.addr >> 32;
6415 				}
6416 			}
6417 			break;
6418 		case RELO_EXTERN_CALL:
6419 			ext = &obj->externs[relo->ext_idx];
6420 			insn[0].src_reg = BPF_PSEUDO_KFUNC_CALL;
6421 			if (ext->is_set) {
6422 				insn[0].imm = ext->ksym.kernel_btf_id;
6423 				insn[0].off = ext->ksym.btf_fd_idx;
6424 			} else { /* unresolved weak kfunc call */
6425 				poison_kfunc_call(prog, i, relo->insn_idx, insn,
6426 						  relo->ext_idx, ext);
6427 			}
6428 			break;
6429 		case RELO_SUBPROG_ADDR:
6430 			if (insn[0].src_reg != BPF_PSEUDO_FUNC) {
6431 				pr_warn("prog '%s': relo #%d: bad insn\n",
6432 					prog->name, i);
6433 				return -EINVAL;
6434 			}
6435 			/* handled already */
6436 			break;
6437 		case RELO_CALL:
6438 			/* handled already */
6439 			break;
6440 		case RELO_CORE:
6441 			/* will be handled by bpf_program_record_relos() */
6442 			break;
6443 		case RELO_INSN_ARRAY: {
6444 			int map_fd;
6445 
6446 			map_fd = create_jt_map(obj, prog, relo);
6447 			if (map_fd < 0) {
6448 				pr_warn("prog '%s': relo #%d: can't create jump table: sym_off %u\n",
6449 					prog->name, i, relo->sym_off);
6450 				return map_fd;
6451 			}
6452 			insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6453 			insn->imm = map_fd;
6454 			insn->off = 0;
6455 		}
6456 			break;
6457 		default:
6458 			pr_warn("prog '%s': relo #%d: bad relo type %d\n",
6459 				prog->name, i, relo->type);
6460 			return -EINVAL;
6461 		}
6462 	}
6463 
6464 	return 0;
6465 }
6466 
6467 static int adjust_prog_btf_ext_info(const struct bpf_object *obj,
6468 				    const struct bpf_program *prog,
6469 				    const struct btf_ext_info *ext_info,
6470 				    void **prog_info, __u32 *prog_rec_cnt,
6471 				    __u32 *prog_rec_sz)
6472 {
6473 	void *copy_start = NULL, *copy_end = NULL;
6474 	void *rec, *rec_end, *new_prog_info;
6475 	const struct btf_ext_info_sec *sec;
6476 	size_t old_sz, new_sz;
6477 	int i, sec_num, sec_idx, off_adj;
6478 
6479 	sec_num = 0;
6480 	for_each_btf_ext_sec(ext_info, sec) {
6481 		sec_idx = ext_info->sec_idxs[sec_num];
6482 		sec_num++;
6483 		if (prog->sec_idx != sec_idx)
6484 			continue;
6485 
6486 		for_each_btf_ext_rec(ext_info, sec, i, rec) {
6487 			__u32 insn_off = *(__u32 *)rec / BPF_INSN_SZ;
6488 
6489 			if (insn_off < prog->sec_insn_off)
6490 				continue;
6491 			if (insn_off >= prog->sec_insn_off + prog->sec_insn_cnt)
6492 				break;
6493 
6494 			if (!copy_start)
6495 				copy_start = rec;
6496 			copy_end = rec + ext_info->rec_size;
6497 		}
6498 
6499 		if (!copy_start)
6500 			return -ENOENT;
6501 
6502 		/* append func/line info of a given (sub-)program to the main
6503 		 * program func/line info
6504 		 */
6505 		old_sz = (size_t)(*prog_rec_cnt) * ext_info->rec_size;
6506 		new_sz = old_sz + (copy_end - copy_start);
6507 		new_prog_info = realloc(*prog_info, new_sz);
6508 		if (!new_prog_info)
6509 			return -ENOMEM;
6510 		*prog_info = new_prog_info;
6511 		*prog_rec_cnt = new_sz / ext_info->rec_size;
6512 		memcpy(new_prog_info + old_sz, copy_start, copy_end - copy_start);
6513 
6514 		/* Kernel instruction offsets are in units of 8-byte
6515 		 * instructions, while .BTF.ext instruction offsets generated
6516 		 * by Clang are in units of bytes. So convert Clang offsets
6517 		 * into kernel offsets and adjust offset according to program
6518 		 * relocated position.
6519 		 */
6520 		off_adj = prog->sub_insn_off - prog->sec_insn_off;
6521 		rec = new_prog_info + old_sz;
6522 		rec_end = new_prog_info + new_sz;
6523 		for (; rec < rec_end; rec += ext_info->rec_size) {
6524 			__u32 *insn_off = rec;
6525 
6526 			*insn_off = *insn_off / BPF_INSN_SZ + off_adj;
6527 		}
6528 		*prog_rec_sz = ext_info->rec_size;
6529 		return 0;
6530 	}
6531 
6532 	return -ENOENT;
6533 }
6534 
6535 static int
6536 reloc_prog_func_and_line_info(const struct bpf_object *obj,
6537 			      struct bpf_program *main_prog,
6538 			      const struct bpf_program *prog)
6539 {
6540 	int err;
6541 
6542 	/* no .BTF.ext relocation if .BTF.ext is missing or kernel doesn't
6543 	 * support func/line info
6544 	 */
6545 	if (!obj->btf_ext || !kernel_supports(obj, FEAT_BTF_FUNC))
6546 		return 0;
6547 
6548 	/* only attempt func info relocation if main program's func_info
6549 	 * relocation was successful
6550 	 */
6551 	if (main_prog != prog && !main_prog->func_info)
6552 		goto line_info;
6553 
6554 	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->func_info,
6555 				       &main_prog->func_info,
6556 				       &main_prog->func_info_cnt,
6557 				       &main_prog->func_info_rec_size);
6558 	if (err) {
6559 		if (err != -ENOENT) {
6560 			pr_warn("prog '%s': error relocating .BTF.ext function info: %s\n",
6561 				prog->name, errstr(err));
6562 			return err;
6563 		}
6564 		if (main_prog->func_info) {
6565 			/*
6566 			 * Some info has already been found but has problem
6567 			 * in the last btf_ext reloc. Must have to error out.
6568 			 */
6569 			pr_warn("prog '%s': missing .BTF.ext function info.\n", prog->name);
6570 			return err;
6571 		}
6572 		/* Have problem loading the very first info. Ignore the rest. */
6573 		pr_warn("prog '%s': missing .BTF.ext function info for the main program, skipping all of .BTF.ext func info.\n",
6574 			prog->name);
6575 	}
6576 
6577 line_info:
6578 	/* don't relocate line info if main program's relocation failed */
6579 	if (main_prog != prog && !main_prog->line_info)
6580 		return 0;
6581 
6582 	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->line_info,
6583 				       &main_prog->line_info,
6584 				       &main_prog->line_info_cnt,
6585 				       &main_prog->line_info_rec_size);
6586 	if (err) {
6587 		if (err != -ENOENT) {
6588 			pr_warn("prog '%s': error relocating .BTF.ext line info: %s\n",
6589 				prog->name, errstr(err));
6590 			return err;
6591 		}
6592 		if (main_prog->line_info) {
6593 			/*
6594 			 * Some info has already been found but has problem
6595 			 * in the last btf_ext reloc. Must have to error out.
6596 			 */
6597 			pr_warn("prog '%s': missing .BTF.ext line info.\n", prog->name);
6598 			return err;
6599 		}
6600 		/* Have problem loading the very first info. Ignore the rest. */
6601 		pr_warn("prog '%s': missing .BTF.ext line info for the main program, skipping all of .BTF.ext line info.\n",
6602 			prog->name);
6603 	}
6604 	return 0;
6605 }
6606 
6607 static int cmp_relo_by_insn_idx(const void *key, const void *elem)
6608 {
6609 	size_t insn_idx = *(const size_t *)key;
6610 	const struct reloc_desc *relo = elem;
6611 
6612 	if (insn_idx == relo->insn_idx)
6613 		return 0;
6614 	return insn_idx < relo->insn_idx ? -1 : 1;
6615 }
6616 
6617 static struct reloc_desc *find_prog_insn_relo(const struct bpf_program *prog, size_t insn_idx)
6618 {
6619 	if (!prog->nr_reloc)
6620 		return NULL;
6621 	return bsearch(&insn_idx, prog->reloc_desc, prog->nr_reloc,
6622 		       sizeof(*prog->reloc_desc), cmp_relo_by_insn_idx);
6623 }
6624 
6625 static int append_subprog_relos(struct bpf_program *main_prog, struct bpf_program *subprog)
6626 {
6627 	int new_cnt = main_prog->nr_reloc + subprog->nr_reloc;
6628 	struct reloc_desc *relos;
6629 	int i;
6630 
6631 	if (main_prog == subprog)
6632 		return 0;
6633 	relos = libbpf_reallocarray(main_prog->reloc_desc, new_cnt, sizeof(*relos));
6634 	/* if new count is zero, reallocarray can return a valid NULL result;
6635 	 * in this case the previous pointer will be freed, so we *have to*
6636 	 * reassign old pointer to the new value (even if it's NULL)
6637 	 */
6638 	if (!relos && new_cnt)
6639 		return -ENOMEM;
6640 	if (subprog->nr_reloc)
6641 		memcpy(relos + main_prog->nr_reloc, subprog->reloc_desc,
6642 		       sizeof(*relos) * subprog->nr_reloc);
6643 
6644 	for (i = main_prog->nr_reloc; i < new_cnt; i++)
6645 		relos[i].insn_idx += subprog->sub_insn_off;
6646 	/* After insn_idx adjustment the 'relos' array is still sorted
6647 	 * by insn_idx and doesn't break bsearch.
6648 	 */
6649 	main_prog->reloc_desc = relos;
6650 	main_prog->nr_reloc = new_cnt;
6651 	return 0;
6652 }
6653 
6654 static int save_subprog_offsets(struct bpf_program *main_prog, struct bpf_program *subprog)
6655 {
6656 	size_t size = sizeof(main_prog->subprogs[0]);
6657 	int cnt = main_prog->subprog_cnt;
6658 	void *tmp;
6659 
6660 	tmp = libbpf_reallocarray(main_prog->subprogs, cnt + 1, size);
6661 	if (!tmp)
6662 		return -ENOMEM;
6663 
6664 	main_prog->subprogs = tmp;
6665 	main_prog->subprogs[cnt].sec_insn_off = subprog->sec_insn_off;
6666 	main_prog->subprogs[cnt].sub_insn_off = subprog->sub_insn_off;
6667 	main_prog->subprog_cnt++;
6668 
6669 	return 0;
6670 }
6671 
6672 static int
6673 bpf_object__append_subprog_code(struct bpf_object *obj, struct bpf_program *main_prog,
6674 				struct bpf_program *subprog)
6675 {
6676 	struct bpf_insn *insns;
6677 	size_t new_cnt;
6678 	int err;
6679 
6680 	subprog->sub_insn_off = main_prog->insns_cnt;
6681 
6682 	new_cnt = main_prog->insns_cnt + subprog->insns_cnt;
6683 	insns = libbpf_reallocarray(main_prog->insns, new_cnt, sizeof(*insns));
6684 	if (!insns) {
6685 		pr_warn("prog '%s': failed to realloc prog code\n", main_prog->name);
6686 		return -ENOMEM;
6687 	}
6688 	main_prog->insns = insns;
6689 	main_prog->insns_cnt = new_cnt;
6690 
6691 	memcpy(main_prog->insns + subprog->sub_insn_off, subprog->insns,
6692 	       subprog->insns_cnt * sizeof(*insns));
6693 
6694 	pr_debug("prog '%s': added %zu insns from sub-prog '%s'\n",
6695 		 main_prog->name, subprog->insns_cnt, subprog->name);
6696 
6697 	/* The subprog insns are now appended. Append its relos too. */
6698 	err = append_subprog_relos(main_prog, subprog);
6699 	if (err)
6700 		return err;
6701 
6702 	err = save_subprog_offsets(main_prog, subprog);
6703 	if (err) {
6704 		pr_warn("prog '%s': failed to add subprog offsets: %s\n",
6705 			main_prog->name, errstr(err));
6706 		return err;
6707 	}
6708 
6709 	return 0;
6710 }
6711 
6712 static int
6713 bpf_object__reloc_code(struct bpf_object *obj, struct bpf_program *main_prog,
6714 		       struct bpf_program *prog)
6715 {
6716 	size_t sub_insn_idx, insn_idx;
6717 	struct bpf_program *subprog;
6718 	struct reloc_desc *relo;
6719 	struct bpf_insn *insn;
6720 	int err;
6721 
6722 	err = reloc_prog_func_and_line_info(obj, main_prog, prog);
6723 	if (err)
6724 		return err;
6725 
6726 	for (insn_idx = 0; insn_idx < prog->sec_insn_cnt; insn_idx++) {
6727 		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6728 		if (!insn_is_subprog_call(insn) && !insn_is_pseudo_func(insn))
6729 			continue;
6730 
6731 		relo = find_prog_insn_relo(prog, insn_idx);
6732 		if (relo && relo->type == RELO_EXTERN_CALL)
6733 			/* kfunc relocations will be handled later
6734 			 * in bpf_object__relocate_data()
6735 			 */
6736 			continue;
6737 		if (relo && relo->type != RELO_CALL && relo->type != RELO_SUBPROG_ADDR) {
6738 			pr_warn("prog '%s': unexpected relo for insn #%zu, type %d\n",
6739 				prog->name, insn_idx, relo->type);
6740 			return -LIBBPF_ERRNO__RELOC;
6741 		}
6742 		if (relo) {
6743 			/* sub-program instruction index is a combination of
6744 			 * an offset of a symbol pointed to by relocation and
6745 			 * call instruction's imm field; for global functions,
6746 			 * call always has imm = -1, but for static functions
6747 			 * relocation is against STT_SECTION and insn->imm
6748 			 * points to a start of a static function
6749 			 *
6750 			 * for subprog addr relocation, the relo->sym_off + insn->imm is
6751 			 * the byte offset in the corresponding section.
6752 			 */
6753 			if (relo->type == RELO_CALL)
6754 				sub_insn_idx = relo->sym_off / BPF_INSN_SZ + insn->imm + 1;
6755 			else
6756 				sub_insn_idx = (relo->sym_off + insn->imm) / BPF_INSN_SZ;
6757 		} else if (insn_is_pseudo_func(insn)) {
6758 			/*
6759 			 * RELO_SUBPROG_ADDR relo is always emitted even if both
6760 			 * functions are in the same section, so it shouldn't reach here.
6761 			 */
6762 			pr_warn("prog '%s': missing subprog addr relo for insn #%zu\n",
6763 				prog->name, insn_idx);
6764 			return -LIBBPF_ERRNO__RELOC;
6765 		} else {
6766 			/* if subprogram call is to a static function within
6767 			 * the same ELF section, there won't be any relocation
6768 			 * emitted, but it also means there is no additional
6769 			 * offset necessary, insns->imm is relative to
6770 			 * instruction's original position within the section
6771 			 */
6772 			sub_insn_idx = prog->sec_insn_off + insn_idx + insn->imm + 1;
6773 		}
6774 
6775 		/* we enforce that sub-programs should be in .text section */
6776 		subprog = find_prog_by_sec_insn(obj, obj->efile.text_shndx, sub_insn_idx);
6777 		if (!subprog) {
6778 			pr_warn("prog '%s': no .text section found yet sub-program call exists\n",
6779 				prog->name);
6780 			return -LIBBPF_ERRNO__RELOC;
6781 		}
6782 
6783 		/* if it's the first call instruction calling into this
6784 		 * subprogram (meaning this subprog hasn't been processed
6785 		 * yet) within the context of current main program:
6786 		 *   - append it at the end of main program's instructions blog;
6787 		 *   - process is recursively, while current program is put on hold;
6788 		 *   - if that subprogram calls some other not yet processes
6789 		 *   subprogram, same thing will happen recursively until
6790 		 *   there are no more unprocesses subprograms left to append
6791 		 *   and relocate.
6792 		 */
6793 		if (subprog->sub_insn_off == 0) {
6794 			err = bpf_object__append_subprog_code(obj, main_prog, subprog);
6795 			if (err)
6796 				return err;
6797 			err = bpf_object__reloc_code(obj, main_prog, subprog);
6798 			if (err)
6799 				return err;
6800 		}
6801 
6802 		/* main_prog->insns memory could have been re-allocated, so
6803 		 * calculate pointer again
6804 		 */
6805 		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6806 		/* calculate correct instruction position within current main
6807 		 * prog; each main prog can have a different set of
6808 		 * subprograms appended (potentially in different order as
6809 		 * well), so position of any subprog can be different for
6810 		 * different main programs
6811 		 */
6812 		insn->imm = subprog->sub_insn_off - (prog->sub_insn_off + insn_idx) - 1;
6813 
6814 		pr_debug("prog '%s': insn #%zu relocated, imm %d points to subprog '%s' (now at %zu offset)\n",
6815 			 prog->name, insn_idx, insn->imm, subprog->name, subprog->sub_insn_off);
6816 	}
6817 
6818 	return 0;
6819 }
6820 
6821 /*
6822  * Relocate sub-program calls.
6823  *
6824  * Algorithm operates as follows. Each entry-point BPF program (referred to as
6825  * main prog) is processed separately. For each subprog (non-entry functions,
6826  * that can be called from either entry progs or other subprogs) gets their
6827  * sub_insn_off reset to zero. This serves as indicator that this subprogram
6828  * hasn't been yet appended and relocated within current main prog. Once its
6829  * relocated, sub_insn_off will point at the position within current main prog
6830  * where given subprog was appended. This will further be used to relocate all
6831  * the call instructions jumping into this subprog.
6832  *
6833  * We start with main program and process all call instructions. If the call
6834  * is into a subprog that hasn't been processed (i.e., subprog->sub_insn_off
6835  * is zero), subprog instructions are appended at the end of main program's
6836  * instruction array. Then main program is "put on hold" while we recursively
6837  * process newly appended subprogram. If that subprogram calls into another
6838  * subprogram that hasn't been appended, new subprogram is appended again to
6839  * the *main* prog's instructions (subprog's instructions are always left
6840  * untouched, as they need to be in unmodified state for subsequent main progs
6841  * and subprog instructions are always sent only as part of a main prog) and
6842  * the process continues recursively. Once all the subprogs called from a main
6843  * prog or any of its subprogs are appended (and relocated), all their
6844  * positions within finalized instructions array are known, so it's easy to
6845  * rewrite call instructions with correct relative offsets, corresponding to
6846  * desired target subprog.
6847  *
6848  * Its important to realize that some subprogs might not be called from some
6849  * main prog and any of its called/used subprogs. Those will keep their
6850  * subprog->sub_insn_off as zero at all times and won't be appended to current
6851  * main prog and won't be relocated within the context of current main prog.
6852  * They might still be used from other main progs later.
6853  *
6854  * Visually this process can be shown as below. Suppose we have two main
6855  * programs mainA and mainB and BPF object contains three subprogs: subA,
6856  * subB, and subC. mainA calls only subA, mainB calls only subC, but subA and
6857  * subC both call subB:
6858  *
6859  *        +--------+ +-------+
6860  *        |        v v       |
6861  *     +--+---+ +--+-+-+ +---+--+
6862  *     | subA | | subB | | subC |
6863  *     +--+---+ +------+ +---+--+
6864  *        ^                  ^
6865  *        |                  |
6866  *    +---+-------+   +------+----+
6867  *    |   mainA   |   |   mainB   |
6868  *    +-----------+   +-----------+
6869  *
6870  * We'll start relocating mainA, will find subA, append it and start
6871  * processing sub A recursively:
6872  *
6873  *    +-----------+------+
6874  *    |   mainA   | subA |
6875  *    +-----------+------+
6876  *
6877  * At this point we notice that subB is used from subA, so we append it and
6878  * relocate (there are no further subcalls from subB):
6879  *
6880  *    +-----------+------+------+
6881  *    |   mainA   | subA | subB |
6882  *    +-----------+------+------+
6883  *
6884  * At this point, we relocate subA calls, then go one level up and finish with
6885  * relocatin mainA calls. mainA is done.
6886  *
6887  * For mainB process is similar but results in different order. We start with
6888  * mainB and skip subA and subB, as mainB never calls them (at least
6889  * directly), but we see subC is needed, so we append and start processing it:
6890  *
6891  *    +-----------+------+
6892  *    |   mainB   | subC |
6893  *    +-----------+------+
6894  * Now we see subC needs subB, so we go back to it, append and relocate it:
6895  *
6896  *    +-----------+------+------+
6897  *    |   mainB   | subC | subB |
6898  *    +-----------+------+------+
6899  *
6900  * At this point we unwind recursion, relocate calls in subC, then in mainB.
6901  */
6902 static int
6903 bpf_object__relocate_calls(struct bpf_object *obj, struct bpf_program *prog)
6904 {
6905 	struct bpf_program *subprog;
6906 	int i, err;
6907 
6908 	/* mark all subprogs as not relocated (yet) within the context of
6909 	 * current main program
6910 	 */
6911 	for (i = 0; i < obj->nr_programs; i++) {
6912 		subprog = &obj->programs[i];
6913 		if (!prog_is_subprog(obj, subprog))
6914 			continue;
6915 
6916 		subprog->sub_insn_off = 0;
6917 	}
6918 
6919 	err = bpf_object__reloc_code(obj, prog, prog);
6920 	if (err)
6921 		return err;
6922 
6923 	return 0;
6924 }
6925 
6926 static void
6927 bpf_object__free_relocs(struct bpf_object *obj)
6928 {
6929 	struct bpf_program *prog;
6930 	int i;
6931 
6932 	/* free up relocation descriptors */
6933 	for (i = 0; i < obj->nr_programs; i++) {
6934 		prog = &obj->programs[i];
6935 		zfree(&prog->reloc_desc);
6936 		prog->nr_reloc = 0;
6937 	}
6938 }
6939 
6940 static int cmp_relocs(const void *_a, const void *_b)
6941 {
6942 	const struct reloc_desc *a = _a;
6943 	const struct reloc_desc *b = _b;
6944 
6945 	if (a->insn_idx != b->insn_idx)
6946 		return a->insn_idx < b->insn_idx ? -1 : 1;
6947 
6948 	/* no two relocations should have the same insn_idx, but ... */
6949 	if (a->type != b->type)
6950 		return a->type < b->type ? -1 : 1;
6951 
6952 	return 0;
6953 }
6954 
6955 static void bpf_object__sort_relos(struct bpf_object *obj)
6956 {
6957 	int i;
6958 
6959 	for (i = 0; i < obj->nr_programs; i++) {
6960 		struct bpf_program *p = &obj->programs[i];
6961 
6962 		if (!p->nr_reloc)
6963 			continue;
6964 
6965 		qsort(p->reloc_desc, p->nr_reloc, sizeof(*p->reloc_desc), cmp_relocs);
6966 	}
6967 }
6968 
6969 static int bpf_prog_assign_exc_cb(struct bpf_object *obj, struct bpf_program *prog)
6970 {
6971 	const char *str = "exception_callback:";
6972 	size_t pfx_len = strlen(str);
6973 	int i, j, n;
6974 
6975 	if (!obj->btf || !kernel_supports(obj, FEAT_BTF_DECL_TAG))
6976 		return 0;
6977 
6978 	n = btf__type_cnt(obj->btf);
6979 	for (i = 1; i < n; i++) {
6980 		const char *name;
6981 		struct btf_type *t;
6982 
6983 		t = btf_type_by_id(obj->btf, i);
6984 		if (!btf_is_decl_tag(t) || btf_decl_tag(t)->component_idx != -1)
6985 			continue;
6986 
6987 		name = btf__str_by_offset(obj->btf, t->name_off);
6988 		if (strncmp(name, str, pfx_len) != 0)
6989 			continue;
6990 
6991 		t = btf_type_by_id(obj->btf, t->type);
6992 		if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL) {
6993 			pr_warn("prog '%s': exception_callback:<value> decl tag not applied to the main program\n",
6994 				prog->name);
6995 			return -EINVAL;
6996 		}
6997 		if (strcmp(prog->name, btf__str_by_offset(obj->btf, t->name_off)) != 0)
6998 			continue;
6999 		/* Multiple callbacks are specified for the same prog,
7000 		 * the verifier will eventually return an error for this
7001 		 * case, hence simply skip appending a subprog.
7002 		 */
7003 		if (prog->exception_cb_idx >= 0) {
7004 			prog->exception_cb_idx = -1;
7005 			break;
7006 		}
7007 
7008 		name += pfx_len;
7009 		if (str_is_empty(name)) {
7010 			pr_warn("prog '%s': exception_callback:<value> decl tag contains empty value\n",
7011 				prog->name);
7012 			return -EINVAL;
7013 		}
7014 
7015 		for (j = 0; j < obj->nr_programs; j++) {
7016 			struct bpf_program *subprog = &obj->programs[j];
7017 
7018 			if (!prog_is_subprog(obj, subprog))
7019 				continue;
7020 			if (strcmp(name, subprog->name) != 0)
7021 				continue;
7022 			/* Enforce non-hidden, as from verifier point of
7023 			 * view it expects global functions, whereas the
7024 			 * mark_btf_static fixes up linkage as static.
7025 			 */
7026 			if (!subprog->sym_global || subprog->mark_btf_static) {
7027 				pr_warn("prog '%s': exception callback %s must be a global non-hidden function\n",
7028 					prog->name, subprog->name);
7029 				return -EINVAL;
7030 			}
7031 			/* Let's see if we already saw a static exception callback with the same name */
7032 			if (prog->exception_cb_idx >= 0) {
7033 				pr_warn("prog '%s': multiple subprogs with same name as exception callback '%s'\n",
7034 					prog->name, subprog->name);
7035 				return -EINVAL;
7036 			}
7037 			prog->exception_cb_idx = j;
7038 			break;
7039 		}
7040 
7041 		if (prog->exception_cb_idx >= 0)
7042 			continue;
7043 
7044 		pr_warn("prog '%s': cannot find exception callback '%s'\n", prog->name, name);
7045 		return -ENOENT;
7046 	}
7047 
7048 	return 0;
7049 }
7050 
7051 static struct {
7052 	enum bpf_prog_type prog_type;
7053 	const char *ctx_name;
7054 } global_ctx_map[] = {
7055 	{ BPF_PROG_TYPE_CGROUP_DEVICE,           "bpf_cgroup_dev_ctx" },
7056 	{ BPF_PROG_TYPE_CGROUP_SKB,              "__sk_buff" },
7057 	{ BPF_PROG_TYPE_CGROUP_SOCK,             "bpf_sock" },
7058 	{ BPF_PROG_TYPE_CGROUP_SOCK_ADDR,        "bpf_sock_addr" },
7059 	{ BPF_PROG_TYPE_CGROUP_SOCKOPT,          "bpf_sockopt" },
7060 	{ BPF_PROG_TYPE_CGROUP_SYSCTL,           "bpf_sysctl" },
7061 	{ BPF_PROG_TYPE_FLOW_DISSECTOR,          "__sk_buff" },
7062 	{ BPF_PROG_TYPE_KPROBE,                  "bpf_user_pt_regs_t" },
7063 	{ BPF_PROG_TYPE_LWT_IN,                  "__sk_buff" },
7064 	{ BPF_PROG_TYPE_LWT_OUT,                 "__sk_buff" },
7065 	{ BPF_PROG_TYPE_LWT_SEG6LOCAL,           "__sk_buff" },
7066 	{ BPF_PROG_TYPE_LWT_XMIT,                "__sk_buff" },
7067 	{ BPF_PROG_TYPE_NETFILTER,               "bpf_nf_ctx" },
7068 	{ BPF_PROG_TYPE_PERF_EVENT,              "bpf_perf_event_data" },
7069 	{ BPF_PROG_TYPE_RAW_TRACEPOINT,          "bpf_raw_tracepoint_args" },
7070 	{ BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE, "bpf_raw_tracepoint_args" },
7071 	{ BPF_PROG_TYPE_SCHED_ACT,               "__sk_buff" },
7072 	{ BPF_PROG_TYPE_SCHED_CLS,               "__sk_buff" },
7073 	{ BPF_PROG_TYPE_SK_LOOKUP,               "bpf_sk_lookup" },
7074 	{ BPF_PROG_TYPE_SK_MSG,                  "sk_msg_md" },
7075 	{ BPF_PROG_TYPE_SK_REUSEPORT,            "sk_reuseport_md" },
7076 	{ BPF_PROG_TYPE_SK_SKB,                  "__sk_buff" },
7077 	{ BPF_PROG_TYPE_SOCK_OPS,                "bpf_sock_ops" },
7078 	{ BPF_PROG_TYPE_SOCKET_FILTER,           "__sk_buff" },
7079 	{ BPF_PROG_TYPE_XDP,                     "xdp_md" },
7080 	/* all other program types don't have "named" context structs */
7081 };
7082 
7083 /* forward declarations for arch-specific underlying types of bpf_user_pt_regs_t typedef,
7084  * for below __builtin_types_compatible_p() checks;
7085  * with this approach we don't need any extra arch-specific #ifdef guards
7086  */
7087 struct pt_regs;
7088 struct user_pt_regs;
7089 struct user_regs_struct;
7090 
7091 static bool need_func_arg_type_fixup(const struct btf *btf, const struct bpf_program *prog,
7092 				     const char *subprog_name, int arg_idx,
7093 				     int arg_type_id, const char *ctx_name)
7094 {
7095 	const struct btf_type *t;
7096 	const char *tname;
7097 
7098 	/* check if existing parameter already matches verifier expectations */
7099 	t = skip_mods_and_typedefs(btf, arg_type_id, NULL);
7100 	if (!btf_is_ptr(t))
7101 		goto out_warn;
7102 
7103 	/* typedef bpf_user_pt_regs_t is a special PITA case, valid for kprobe
7104 	 * and perf_event programs, so check this case early on and forget
7105 	 * about it for subsequent checks
7106 	 */
7107 	while (btf_is_mod(t))
7108 		t = btf__type_by_id(btf, t->type);
7109 	if (btf_is_typedef(t) &&
7110 	    (prog->type == BPF_PROG_TYPE_KPROBE || prog->type == BPF_PROG_TYPE_PERF_EVENT)) {
7111 		tname = btf__str_by_offset(btf, t->name_off) ?: "<anon>";
7112 		if (strcmp(tname, "bpf_user_pt_regs_t") == 0)
7113 			return false; /* canonical type for kprobe/perf_event */
7114 	}
7115 
7116 	/* now we can ignore typedefs moving forward */
7117 	t = skip_mods_and_typedefs(btf, t->type, NULL);
7118 
7119 	/* if it's `void *`, definitely fix up BTF info */
7120 	if (btf_is_void(t))
7121 		return true;
7122 
7123 	/* if it's already proper canonical type, no need to fix up */
7124 	tname = btf__str_by_offset(btf, t->name_off) ?: "<anon>";
7125 	if (btf_is_struct(t) && strcmp(tname, ctx_name) == 0)
7126 		return false;
7127 
7128 	/* special cases */
7129 	switch (prog->type) {
7130 	case BPF_PROG_TYPE_KPROBE:
7131 		/* `struct pt_regs *` is expected, but we need to fix up */
7132 		if (btf_is_struct(t) && strcmp(tname, "pt_regs") == 0)
7133 			return true;
7134 		break;
7135 	case BPF_PROG_TYPE_PERF_EVENT:
7136 		if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct pt_regs) &&
7137 		    btf_is_struct(t) && strcmp(tname, "pt_regs") == 0)
7138 			return true;
7139 		if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct user_pt_regs) &&
7140 		    btf_is_struct(t) && strcmp(tname, "user_pt_regs") == 0)
7141 			return true;
7142 		if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct user_regs_struct) &&
7143 		    btf_is_struct(t) && strcmp(tname, "user_regs_struct") == 0)
7144 			return true;
7145 		break;
7146 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
7147 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
7148 		/* allow u64* as ctx */
7149 		if (btf_is_int(t) && t->size == 8)
7150 			return true;
7151 		break;
7152 	default:
7153 		break;
7154 	}
7155 
7156 out_warn:
7157 	pr_warn("prog '%s': subprog '%s' arg#%d is expected to be of `struct %s *` type\n",
7158 		prog->name, subprog_name, arg_idx, ctx_name);
7159 	return false;
7160 }
7161 
7162 static int clone_func_btf_info(struct btf *btf, int orig_fn_id, struct bpf_program *prog)
7163 {
7164 	int fn_id, fn_proto_id, ret_type_id, orig_proto_id;
7165 	int i, err, arg_cnt, fn_name_off, linkage;
7166 	struct btf_type *fn_t, *fn_proto_t, *t;
7167 	struct btf_param *p;
7168 
7169 	/* caller already validated FUNC -> FUNC_PROTO validity */
7170 	fn_t = btf_type_by_id(btf, orig_fn_id);
7171 	fn_proto_t = btf_type_by_id(btf, fn_t->type);
7172 
7173 	/* Note that each btf__add_xxx() operation invalidates
7174 	 * all btf_type and string pointers, so we need to be
7175 	 * very careful when cloning BTF types. BTF type
7176 	 * pointers have to be always refetched. And to avoid
7177 	 * problems with invalidated string pointers, we
7178 	 * add empty strings initially, then just fix up
7179 	 * name_off offsets in place. Offsets are stable for
7180 	 * existing strings, so that works out.
7181 	 */
7182 	fn_name_off = fn_t->name_off; /* we are about to invalidate fn_t */
7183 	linkage = btf_func_linkage(fn_t);
7184 	orig_proto_id = fn_t->type; /* original FUNC_PROTO ID */
7185 	ret_type_id = fn_proto_t->type; /* fn_proto_t will be invalidated */
7186 	arg_cnt = btf_vlen(fn_proto_t);
7187 
7188 	/* clone FUNC_PROTO and its params */
7189 	fn_proto_id = btf__add_func_proto(btf, ret_type_id);
7190 	if (fn_proto_id < 0)
7191 		return -EINVAL;
7192 
7193 	for (i = 0; i < arg_cnt; i++) {
7194 		int name_off;
7195 
7196 		/* copy original parameter data */
7197 		t = btf_type_by_id(btf, orig_proto_id);
7198 		p = &btf_params(t)[i];
7199 		name_off = p->name_off;
7200 
7201 		err = btf__add_func_param(btf, "", p->type);
7202 		if (err)
7203 			return err;
7204 
7205 		fn_proto_t = btf_type_by_id(btf, fn_proto_id);
7206 		p = &btf_params(fn_proto_t)[i];
7207 		p->name_off = name_off; /* use remembered str offset */
7208 	}
7209 
7210 	/* clone FUNC now, btf__add_func() enforces non-empty name, so use
7211 	 * entry program's name as a placeholder, which we replace immediately
7212 	 * with original name_off
7213 	 */
7214 	fn_id = btf__add_func(btf, prog->name, linkage, fn_proto_id);
7215 	if (fn_id < 0)
7216 		return -EINVAL;
7217 
7218 	fn_t = btf_type_by_id(btf, fn_id);
7219 	fn_t->name_off = fn_name_off; /* reuse original string */
7220 
7221 	return fn_id;
7222 }
7223 
7224 /* Check if main program or global subprog's function prototype has `arg:ctx`
7225  * argument tags, and, if necessary, substitute correct type to match what BPF
7226  * verifier would expect, taking into account specific program type. This
7227  * allows to support __arg_ctx tag transparently on old kernels that don't yet
7228  * have a native support for it in the verifier, making user's life much
7229  * easier.
7230  */
7231 static int bpf_program_fixup_func_info(struct bpf_object *obj, struct bpf_program *prog)
7232 {
7233 	const char *ctx_name = NULL, *ctx_tag = "arg:ctx", *fn_name;
7234 	struct bpf_func_info_min *func_rec;
7235 	struct btf_type *fn_t, *fn_proto_t;
7236 	struct btf *btf = obj->btf;
7237 	const struct btf_type *t;
7238 	struct btf_param *p;
7239 	int ptr_id = 0, struct_id, tag_id, orig_fn_id;
7240 	int i, n, arg_idx, arg_cnt, err, rec_idx;
7241 	int *orig_ids;
7242 
7243 	/* no .BTF.ext, no problem */
7244 	if (!obj->btf_ext || !prog->func_info)
7245 		return 0;
7246 
7247 	/* don't do any fix ups if kernel natively supports __arg_ctx */
7248 	if (kernel_supports(obj, FEAT_ARG_CTX_TAG))
7249 		return 0;
7250 
7251 	/* some BPF program types just don't have named context structs, so
7252 	 * this fallback mechanism doesn't work for them
7253 	 */
7254 	for (i = 0; i < ARRAY_SIZE(global_ctx_map); i++) {
7255 		if (global_ctx_map[i].prog_type != prog->type)
7256 			continue;
7257 		ctx_name = global_ctx_map[i].ctx_name;
7258 		break;
7259 	}
7260 	if (!ctx_name)
7261 		return 0;
7262 
7263 	/* remember original func BTF IDs to detect if we already cloned them */
7264 	orig_ids = calloc(prog->func_info_cnt, sizeof(*orig_ids));
7265 	if (!orig_ids)
7266 		return -ENOMEM;
7267 	for (i = 0; i < prog->func_info_cnt; i++) {
7268 		func_rec = prog->func_info + prog->func_info_rec_size * i;
7269 		orig_ids[i] = func_rec->type_id;
7270 	}
7271 
7272 	/* go through each DECL_TAG with "arg:ctx" and see if it points to one
7273 	 * of our subprogs; if yes and subprog is global and needs adjustment,
7274 	 * clone and adjust FUNC -> FUNC_PROTO combo
7275 	 */
7276 	for (i = 1, n = btf__type_cnt(btf); i < n; i++) {
7277 		/* only DECL_TAG with "arg:ctx" value are interesting */
7278 		t = btf__type_by_id(btf, i);
7279 		if (!btf_is_decl_tag(t))
7280 			continue;
7281 		if (strcmp(btf__str_by_offset(btf, t->name_off), ctx_tag) != 0)
7282 			continue;
7283 
7284 		/* only global funcs need adjustment, if at all */
7285 		orig_fn_id = t->type;
7286 		fn_t = btf_type_by_id(btf, orig_fn_id);
7287 		if (!btf_is_func(fn_t) || btf_func_linkage(fn_t) != BTF_FUNC_GLOBAL)
7288 			continue;
7289 
7290 		/* sanity check FUNC -> FUNC_PROTO chain, just in case */
7291 		fn_proto_t = btf_type_by_id(btf, fn_t->type);
7292 		if (!fn_proto_t || !btf_is_func_proto(fn_proto_t))
7293 			continue;
7294 
7295 		/* find corresponding func_info record */
7296 		func_rec = NULL;
7297 		for (rec_idx = 0; rec_idx < prog->func_info_cnt; rec_idx++) {
7298 			if (orig_ids[rec_idx] == t->type) {
7299 				func_rec = prog->func_info + prog->func_info_rec_size * rec_idx;
7300 				break;
7301 			}
7302 		}
7303 		/* current main program doesn't call into this subprog */
7304 		if (!func_rec)
7305 			continue;
7306 
7307 		/* some more sanity checking of DECL_TAG */
7308 		arg_cnt = btf_vlen(fn_proto_t);
7309 		arg_idx = btf_decl_tag(t)->component_idx;
7310 		if (arg_idx < 0 || arg_idx >= arg_cnt)
7311 			continue;
7312 
7313 		/* check if we should fix up argument type */
7314 		p = &btf_params(fn_proto_t)[arg_idx];
7315 		fn_name = btf__str_by_offset(btf, fn_t->name_off) ?: "<anon>";
7316 		if (!need_func_arg_type_fixup(btf, prog, fn_name, arg_idx, p->type, ctx_name))
7317 			continue;
7318 
7319 		/* clone fn/fn_proto, unless we already did it for another arg */
7320 		if (func_rec->type_id == orig_fn_id) {
7321 			int fn_id;
7322 
7323 			fn_id = clone_func_btf_info(btf, orig_fn_id, prog);
7324 			if (fn_id < 0) {
7325 				err = fn_id;
7326 				goto err_out;
7327 			}
7328 
7329 			/* point func_info record to a cloned FUNC type */
7330 			func_rec->type_id = fn_id;
7331 		}
7332 
7333 		/* create PTR -> STRUCT type chain to mark PTR_TO_CTX argument;
7334 		 * we do it just once per main BPF program, as all global
7335 		 * funcs share the same program type, so need only PTR ->
7336 		 * STRUCT type chain
7337 		 */
7338 		if (ptr_id == 0) {
7339 			struct_id = btf__add_struct(btf, ctx_name, 0);
7340 			ptr_id = btf__add_ptr(btf, struct_id);
7341 			if (ptr_id < 0 || struct_id < 0) {
7342 				err = -EINVAL;
7343 				goto err_out;
7344 			}
7345 		}
7346 
7347 		/* for completeness, clone DECL_TAG and point it to cloned param */
7348 		tag_id = btf__add_decl_tag(btf, ctx_tag, func_rec->type_id, arg_idx);
7349 		if (tag_id < 0) {
7350 			err = -EINVAL;
7351 			goto err_out;
7352 		}
7353 
7354 		/* all the BTF manipulations invalidated pointers, refetch them */
7355 		fn_t = btf_type_by_id(btf, func_rec->type_id);
7356 		fn_proto_t = btf_type_by_id(btf, fn_t->type);
7357 
7358 		/* fix up type ID pointed to by param */
7359 		p = &btf_params(fn_proto_t)[arg_idx];
7360 		p->type = ptr_id;
7361 	}
7362 
7363 	free(orig_ids);
7364 	return 0;
7365 err_out:
7366 	free(orig_ids);
7367 	return err;
7368 }
7369 
7370 static int bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
7371 {
7372 	struct bpf_program *prog;
7373 	size_t i, j;
7374 	int err;
7375 
7376 	if (obj->btf_ext) {
7377 		err = bpf_object__relocate_core(obj, targ_btf_path);
7378 		if (err) {
7379 			pr_warn("failed to perform CO-RE relocations: %s\n",
7380 				errstr(err));
7381 			return err;
7382 		}
7383 		bpf_object__sort_relos(obj);
7384 	}
7385 
7386 	/* Before relocating calls pre-process relocations and mark
7387 	 * few ld_imm64 instructions that points to subprogs.
7388 	 * Otherwise bpf_object__reloc_code() later would have to consider
7389 	 * all ld_imm64 insns as relocation candidates. That would
7390 	 * reduce relocation speed, since amount of find_prog_insn_relo()
7391 	 * would increase and most of them will fail to find a relo.
7392 	 */
7393 	for (i = 0; i < obj->nr_programs; i++) {
7394 		prog = &obj->programs[i];
7395 		for (j = 0; j < prog->nr_reloc; j++) {
7396 			struct reloc_desc *relo = &prog->reloc_desc[j];
7397 			struct bpf_insn *insn = &prog->insns[relo->insn_idx];
7398 
7399 			/* mark the insn, so it's recognized by insn_is_pseudo_func() */
7400 			if (relo->type == RELO_SUBPROG_ADDR)
7401 				insn[0].src_reg = BPF_PSEUDO_FUNC;
7402 		}
7403 	}
7404 
7405 	/* relocate subprogram calls and append used subprograms to main
7406 	 * programs; each copy of subprogram code needs to be relocated
7407 	 * differently for each main program, because its code location might
7408 	 * have changed.
7409 	 * Append subprog relos to main programs to allow data relos to be
7410 	 * processed after text is completely relocated.
7411 	 */
7412 	for (i = 0; i < obj->nr_programs; i++) {
7413 		prog = &obj->programs[i];
7414 		/* sub-program's sub-calls are relocated within the context of
7415 		 * its main program only
7416 		 */
7417 		if (prog_is_subprog(obj, prog))
7418 			continue;
7419 		if (!prog->autoload)
7420 			continue;
7421 
7422 		err = bpf_object__relocate_calls(obj, prog);
7423 		if (err) {
7424 			pr_warn("prog '%s': failed to relocate calls: %s\n",
7425 				prog->name, errstr(err));
7426 			return err;
7427 		}
7428 
7429 		err = bpf_prog_assign_exc_cb(obj, prog);
7430 		if (err)
7431 			return err;
7432 		/* Now, also append exception callback if it has not been done already. */
7433 		if (prog->exception_cb_idx >= 0) {
7434 			struct bpf_program *subprog = &obj->programs[prog->exception_cb_idx];
7435 
7436 			/* Calling exception callback directly is disallowed, which the
7437 			 * verifier will reject later. In case it was processed already,
7438 			 * we can skip this step, otherwise for all other valid cases we
7439 			 * have to append exception callback now.
7440 			 */
7441 			if (subprog->sub_insn_off == 0) {
7442 				err = bpf_object__append_subprog_code(obj, prog, subprog);
7443 				if (err)
7444 					return err;
7445 				err = bpf_object__reloc_code(obj, prog, subprog);
7446 				if (err)
7447 					return err;
7448 			}
7449 		}
7450 	}
7451 	for (i = 0; i < obj->nr_programs; i++) {
7452 		prog = &obj->programs[i];
7453 		if (prog_is_subprog(obj, prog))
7454 			continue;
7455 		if (!prog->autoload)
7456 			continue;
7457 
7458 		/* Process data relos for main programs */
7459 		err = bpf_object__relocate_data(obj, prog);
7460 		if (err) {
7461 			pr_warn("prog '%s': failed to relocate data references: %s\n",
7462 				prog->name, errstr(err));
7463 			return err;
7464 		}
7465 
7466 		/* Fix up .BTF.ext information, if necessary */
7467 		err = bpf_program_fixup_func_info(obj, prog);
7468 		if (err) {
7469 			pr_warn("prog '%s': failed to perform .BTF.ext fix ups: %s\n",
7470 				prog->name, errstr(err));
7471 			return err;
7472 		}
7473 	}
7474 
7475 	return 0;
7476 }
7477 
7478 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
7479 					    Elf64_Shdr *shdr, Elf_Data *data);
7480 
7481 static int bpf_object__collect_map_relos(struct bpf_object *obj,
7482 					 Elf64_Shdr *shdr, Elf_Data *data)
7483 {
7484 	const int bpf_ptr_sz = 8, host_ptr_sz = sizeof(void *);
7485 	int i, j, nrels, new_sz;
7486 	const struct btf_var_secinfo *vi = NULL;
7487 	const struct btf_type *sec, *var, *def;
7488 	struct bpf_map *map = NULL, *targ_map = NULL;
7489 	struct bpf_program *targ_prog = NULL;
7490 	bool is_prog_array, is_map_in_map;
7491 	const struct btf_member *member;
7492 	const char *name, *mname, *type;
7493 	unsigned int moff;
7494 	Elf64_Sym *sym;
7495 	Elf64_Rel *rel;
7496 	void *tmp;
7497 
7498 	if (!obj->efile.btf_maps_sec_btf_id || !obj->btf)
7499 		return -EINVAL;
7500 	sec = btf__type_by_id(obj->btf, obj->efile.btf_maps_sec_btf_id);
7501 	if (!sec)
7502 		return -EINVAL;
7503 
7504 	nrels = shdr->sh_size / shdr->sh_entsize;
7505 	for (i = 0; i < nrels; i++) {
7506 		rel = elf_rel_by_idx(data, i);
7507 		if (!rel) {
7508 			pr_warn(".maps relo #%d: failed to get ELF relo\n", i);
7509 			return -LIBBPF_ERRNO__FORMAT;
7510 		}
7511 
7512 		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
7513 		if (!sym) {
7514 			pr_warn(".maps relo #%d: symbol %zx not found\n",
7515 				i, (size_t)ELF64_R_SYM(rel->r_info));
7516 			return -LIBBPF_ERRNO__FORMAT;
7517 		}
7518 		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
7519 
7520 		pr_debug(".maps relo #%d: for %zd value %zd rel->r_offset %zu name %d ('%s')\n",
7521 			 i, (ssize_t)(rel->r_info >> 32), (size_t)sym->st_value,
7522 			 (size_t)rel->r_offset, sym->st_name, name);
7523 
7524 		for (j = 0; j < obj->nr_maps; j++) {
7525 			map = &obj->maps[j];
7526 			if (map->sec_idx != obj->efile.btf_maps_shndx)
7527 				continue;
7528 
7529 			vi = btf_var_secinfos(sec) + map->btf_var_idx;
7530 			if (vi->offset <= rel->r_offset &&
7531 			    rel->r_offset + bpf_ptr_sz <= vi->offset + vi->size)
7532 				break;
7533 		}
7534 		if (j == obj->nr_maps) {
7535 			pr_warn(".maps relo #%d: cannot find map '%s' at rel->r_offset %zu\n",
7536 				i, name, (size_t)rel->r_offset);
7537 			return -EINVAL;
7538 		}
7539 
7540 		is_map_in_map = bpf_map_type__is_map_in_map(map->def.type);
7541 		is_prog_array = map->def.type == BPF_MAP_TYPE_PROG_ARRAY;
7542 		type = is_map_in_map ? "map" : "prog";
7543 		if (is_map_in_map) {
7544 			if (sym->st_shndx != obj->efile.btf_maps_shndx) {
7545 				pr_warn(".maps relo #%d: '%s' isn't a BTF-defined map\n",
7546 					i, name);
7547 				return -LIBBPF_ERRNO__RELOC;
7548 			}
7549 			if (map->def.type == BPF_MAP_TYPE_HASH_OF_MAPS &&
7550 			    map->def.key_size != sizeof(int)) {
7551 				pr_warn(".maps relo #%d: hash-of-maps '%s' should have key size %zu.\n",
7552 					i, map->name, sizeof(int));
7553 				return -EINVAL;
7554 			}
7555 			targ_map = bpf_object__find_map_by_name(obj, name);
7556 			if (!targ_map) {
7557 				pr_warn(".maps relo #%d: '%s' isn't a valid map reference\n",
7558 					i, name);
7559 				return -ESRCH;
7560 			}
7561 		} else if (is_prog_array) {
7562 			targ_prog = bpf_object__find_program_by_name(obj, name);
7563 			if (!targ_prog) {
7564 				pr_warn(".maps relo #%d: '%s' isn't a valid program reference\n",
7565 					i, name);
7566 				return -ESRCH;
7567 			}
7568 			if (targ_prog->sec_idx != sym->st_shndx ||
7569 			    targ_prog->sec_insn_off * 8 != sym->st_value ||
7570 			    prog_is_subprog(obj, targ_prog)) {
7571 				pr_warn(".maps relo #%d: '%s' isn't an entry-point program\n",
7572 					i, name);
7573 				return -LIBBPF_ERRNO__RELOC;
7574 			}
7575 		} else {
7576 			return -EINVAL;
7577 		}
7578 
7579 		var = btf__type_by_id(obj->btf, vi->type);
7580 		def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
7581 		if (btf_vlen(def) == 0)
7582 			return -EINVAL;
7583 		member = btf_members(def) + btf_vlen(def) - 1;
7584 		mname = btf__name_by_offset(obj->btf, member->name_off);
7585 		if (strcmp(mname, "values"))
7586 			return -EINVAL;
7587 
7588 		moff = btf_member_bit_offset(def, btf_vlen(def) - 1) / 8;
7589 		if (rel->r_offset - vi->offset < moff)
7590 			return -EINVAL;
7591 
7592 		moff = rel->r_offset - vi->offset - moff;
7593 		/* here we use BPF pointer size, which is always 64 bit, as we
7594 		 * are parsing ELF that was built for BPF target
7595 		 */
7596 		if (moff % bpf_ptr_sz)
7597 			return -EINVAL;
7598 		moff /= bpf_ptr_sz;
7599 		if (moff >= map->init_slots_sz) {
7600 			new_sz = moff + 1;
7601 			tmp = libbpf_reallocarray(map->init_slots, new_sz, host_ptr_sz);
7602 			if (!tmp)
7603 				return -ENOMEM;
7604 			map->init_slots = tmp;
7605 			memset(map->init_slots + map->init_slots_sz, 0,
7606 			       (new_sz - map->init_slots_sz) * host_ptr_sz);
7607 			map->init_slots_sz = new_sz;
7608 		}
7609 		map->init_slots[moff] = is_map_in_map ? (void *)targ_map : (void *)targ_prog;
7610 
7611 		pr_debug(".maps relo #%d: map '%s' slot [%d] points to %s '%s'\n",
7612 			 i, map->name, moff, type, name);
7613 	}
7614 
7615 	return 0;
7616 }
7617 
7618 static int bpf_object__collect_relos(struct bpf_object *obj)
7619 {
7620 	int i, err;
7621 
7622 	for (i = 0; i < obj->efile.sec_cnt; i++) {
7623 		struct elf_sec_desc *sec_desc = &obj->efile.secs[i];
7624 		Elf64_Shdr *shdr;
7625 		Elf_Data *data;
7626 		int idx;
7627 
7628 		if (sec_desc->sec_type != SEC_RELO)
7629 			continue;
7630 
7631 		shdr = sec_desc->shdr;
7632 		data = sec_desc->data;
7633 		idx = shdr->sh_info;
7634 
7635 		if (shdr->sh_type != SHT_REL || idx < 0 || idx >= obj->efile.sec_cnt) {
7636 			pr_warn("internal error at %d\n", __LINE__);
7637 			return -LIBBPF_ERRNO__INTERNAL;
7638 		}
7639 
7640 		if (obj->efile.secs[idx].sec_type == SEC_ST_OPS)
7641 			err = bpf_object__collect_st_ops_relos(obj, shdr, data);
7642 		else if (idx == obj->efile.btf_maps_shndx)
7643 			err = bpf_object__collect_map_relos(obj, shdr, data);
7644 		else
7645 			err = bpf_object__collect_prog_relos(obj, shdr, data);
7646 		if (err)
7647 			return err;
7648 	}
7649 
7650 	bpf_object__sort_relos(obj);
7651 	return 0;
7652 }
7653 
7654 static bool insn_is_helper_call(struct bpf_insn *insn, enum bpf_func_id *func_id)
7655 {
7656 	if (BPF_CLASS(insn->code) == BPF_JMP &&
7657 	    BPF_OP(insn->code) == BPF_CALL &&
7658 	    BPF_SRC(insn->code) == BPF_K &&
7659 	    insn->src_reg == 0 &&
7660 	    insn->dst_reg == 0) {
7661 		    *func_id = insn->imm;
7662 		    return true;
7663 	}
7664 	return false;
7665 }
7666 
7667 static int bpf_object__sanitize_prog(struct bpf_object *obj, struct bpf_program *prog)
7668 {
7669 	struct bpf_insn *insn = prog->insns;
7670 	enum bpf_func_id func_id;
7671 	int i;
7672 
7673 	if (obj->gen_loader)
7674 		return 0;
7675 
7676 	for (i = 0; i < prog->insns_cnt; i++, insn++) {
7677 		if (!insn_is_helper_call(insn, &func_id))
7678 			continue;
7679 
7680 		/* on kernels that don't yet support
7681 		 * bpf_probe_read_{kernel,user}[_str] helpers, fall back
7682 		 * to bpf_probe_read() which works well for old kernels
7683 		 */
7684 		switch (func_id) {
7685 		case BPF_FUNC_probe_read_kernel:
7686 		case BPF_FUNC_probe_read_user:
7687 			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
7688 				insn->imm = BPF_FUNC_probe_read;
7689 			break;
7690 		case BPF_FUNC_probe_read_kernel_str:
7691 		case BPF_FUNC_probe_read_user_str:
7692 			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
7693 				insn->imm = BPF_FUNC_probe_read_str;
7694 			break;
7695 		default:
7696 			break;
7697 		}
7698 	}
7699 	return 0;
7700 }
7701 
7702 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
7703 				     int *btf_obj_fd, int *btf_type_id);
7704 
7705 /* this is called as prog->sec_def->prog_prepare_load_fn for libbpf-supported sec_defs */
7706 static int libbpf_prepare_prog_load(struct bpf_program *prog,
7707 				    struct bpf_prog_load_opts *opts, long cookie)
7708 {
7709 	enum sec_def_flags def = cookie;
7710 
7711 	/* old kernels might not support specifying expected_attach_type */
7712 	if ((def & SEC_EXP_ATTACH_OPT) && !kernel_supports(prog->obj, FEAT_EXP_ATTACH_TYPE))
7713 		opts->expected_attach_type = 0;
7714 
7715 	if (def & SEC_SLEEPABLE)
7716 		opts->prog_flags |= BPF_F_SLEEPABLE;
7717 
7718 	if (prog->type == BPF_PROG_TYPE_XDP && (def & SEC_XDP_FRAGS))
7719 		opts->prog_flags |= BPF_F_XDP_HAS_FRAGS;
7720 
7721 	/* special check for usdt to use uprobe_multi link */
7722 	if ((def & SEC_USDT) && kernel_supports(prog->obj, FEAT_UPROBE_MULTI_LINK)) {
7723 		/* for BPF_TRACE_UPROBE_MULTI, user might want to query expected_attach_type
7724 		 * in prog, and expected_attach_type we set in kernel is from opts, so we
7725 		 * update both.
7726 		 */
7727 		prog->expected_attach_type = BPF_TRACE_UPROBE_MULTI;
7728 		opts->expected_attach_type = BPF_TRACE_UPROBE_MULTI;
7729 	}
7730 
7731 	if ((def & SEC_ATTACH_BTF) && !prog->attach_btf_id) {
7732 		int btf_obj_fd = 0, btf_type_id = 0, err;
7733 		const char *attach_name;
7734 
7735 		attach_name = strchr(prog->sec_name, '/');
7736 		if (!attach_name) {
7737 			/* if BPF program is annotated with just SEC("fentry")
7738 			 * (or similar) without declaratively specifying
7739 			 * target, then it is expected that target will be
7740 			 * specified with bpf_program__set_attach_target() at
7741 			 * runtime before BPF object load step. If not, then
7742 			 * there is nothing to load into the kernel as BPF
7743 			 * verifier won't be able to validate BPF program
7744 			 * correctness anyways.
7745 			 */
7746 			pr_warn("prog '%s': no BTF-based attach target is specified, use bpf_program__set_attach_target()\n",
7747 				prog->name);
7748 			return -EINVAL;
7749 		}
7750 		attach_name++; /* skip over / */
7751 
7752 		err = libbpf_find_attach_btf_id(prog, attach_name, &btf_obj_fd, &btf_type_id);
7753 		if (err)
7754 			return err;
7755 
7756 		/* cache resolved BTF FD and BTF type ID in the prog */
7757 		prog->attach_btf_obj_fd = btf_obj_fd;
7758 		prog->attach_btf_id = btf_type_id;
7759 
7760 		/* but by now libbpf common logic is not utilizing
7761 		 * prog->atach_btf_obj_fd/prog->attach_btf_id anymore because
7762 		 * this callback is called after opts were populated by
7763 		 * libbpf, so this callback has to update opts explicitly here
7764 		 */
7765 		opts->attach_btf_obj_fd = btf_obj_fd;
7766 		opts->attach_btf_id = btf_type_id;
7767 	}
7768 	return 0;
7769 }
7770 
7771 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz);
7772 
7773 static int bpf_object_load_prog(struct bpf_object *obj, struct bpf_program *prog,
7774 				struct bpf_insn *insns, int insns_cnt,
7775 				const char *license, __u32 kern_version, int *prog_fd)
7776 {
7777 	LIBBPF_OPTS(bpf_prog_load_opts, load_attr);
7778 	const char *prog_name = NULL;
7779 	size_t log_buf_size = 0;
7780 	char *log_buf = NULL, *tmp;
7781 	bool own_log_buf = true;
7782 	__u32 log_level = prog->log_level;
7783 	int ret, err;
7784 
7785 	/* Be more helpful by rejecting programs that can't be validated early
7786 	 * with more meaningful and actionable error message.
7787 	 */
7788 	switch (prog->type) {
7789 	case BPF_PROG_TYPE_UNSPEC:
7790 		/*
7791 		 * The program type must be set.  Most likely we couldn't find a proper
7792 		 * section definition at load time, and thus we didn't infer the type.
7793 		 */
7794 		pr_warn("prog '%s': missing BPF prog type, check ELF section name '%s'\n",
7795 			prog->name, prog->sec_name);
7796 		return -EINVAL;
7797 	case BPF_PROG_TYPE_STRUCT_OPS:
7798 		if (prog->attach_btf_id == 0) {
7799 			pr_warn("prog '%s': SEC(\"struct_ops\") program isn't referenced anywhere, did you forget to use it?\n",
7800 				prog->name);
7801 			return -EINVAL;
7802 		}
7803 		break;
7804 	default:
7805 		break;
7806 	}
7807 
7808 	if (!insns || !insns_cnt)
7809 		return -EINVAL;
7810 
7811 	if (kernel_supports(obj, FEAT_PROG_NAME))
7812 		prog_name = prog->name;
7813 	load_attr.attach_prog_fd = prog->attach_prog_fd;
7814 	load_attr.attach_btf_obj_fd = prog->attach_btf_obj_fd;
7815 	load_attr.attach_btf_id = prog->attach_btf_id;
7816 	load_attr.kern_version = kern_version;
7817 	load_attr.prog_ifindex = prog->prog_ifindex;
7818 	load_attr.expected_attach_type = prog->expected_attach_type;
7819 
7820 	/* specify func_info/line_info only if kernel supports them */
7821 	if (obj->btf && btf__fd(obj->btf) >= 0 && kernel_supports(obj, FEAT_BTF_FUNC)) {
7822 		load_attr.prog_btf_fd = btf__fd(obj->btf);
7823 		load_attr.func_info = prog->func_info;
7824 		load_attr.func_info_rec_size = prog->func_info_rec_size;
7825 		load_attr.func_info_cnt = prog->func_info_cnt;
7826 		load_attr.line_info = prog->line_info;
7827 		load_attr.line_info_rec_size = prog->line_info_rec_size;
7828 		load_attr.line_info_cnt = prog->line_info_cnt;
7829 	}
7830 	load_attr.log_level = log_level;
7831 	load_attr.prog_flags = prog->prog_flags;
7832 	load_attr.fd_array = obj->fd_array;
7833 
7834 	load_attr.token_fd = obj->token_fd;
7835 	if (obj->token_fd)
7836 		load_attr.prog_flags |= BPF_F_TOKEN_FD;
7837 
7838 	/* adjust load_attr if sec_def provides custom preload callback */
7839 	if (prog->sec_def && prog->sec_def->prog_prepare_load_fn) {
7840 		err = prog->sec_def->prog_prepare_load_fn(prog, &load_attr, prog->sec_def->cookie);
7841 		if (err < 0) {
7842 			pr_warn("prog '%s': failed to prepare load attributes: %s\n",
7843 				prog->name, errstr(err));
7844 			return err;
7845 		}
7846 		insns = prog->insns;
7847 		insns_cnt = prog->insns_cnt;
7848 	}
7849 
7850 	if (obj->gen_loader) {
7851 		bpf_gen__prog_load(obj->gen_loader, prog->type, prog->name,
7852 				   license, insns, insns_cnt, &load_attr,
7853 				   prog - obj->programs);
7854 		*prog_fd = -1;
7855 		return 0;
7856 	}
7857 
7858 retry_load:
7859 	/* if log_level is zero, we don't request logs initially even if
7860 	 * custom log_buf is specified; if the program load fails, then we'll
7861 	 * bump log_level to 1 and use either custom log_buf or we'll allocate
7862 	 * our own and retry the load to get details on what failed
7863 	 */
7864 	if (log_level) {
7865 		if (prog->log_buf) {
7866 			log_buf = prog->log_buf;
7867 			log_buf_size = prog->log_size;
7868 			own_log_buf = false;
7869 		} else if (obj->log_buf) {
7870 			log_buf = obj->log_buf;
7871 			log_buf_size = obj->log_size;
7872 			own_log_buf = false;
7873 		} else {
7874 			log_buf_size = max((size_t)BPF_LOG_BUF_SIZE, log_buf_size * 2);
7875 			tmp = realloc(log_buf, log_buf_size);
7876 			if (!tmp) {
7877 				ret = -ENOMEM;
7878 				goto out;
7879 			}
7880 			log_buf = tmp;
7881 			log_buf[0] = '\0';
7882 			own_log_buf = true;
7883 		}
7884 	}
7885 
7886 	load_attr.log_buf = log_buf;
7887 	load_attr.log_size = log_buf_size;
7888 	load_attr.log_level = log_level;
7889 
7890 	ret = bpf_prog_load(prog->type, prog_name, license, insns, insns_cnt, &load_attr);
7891 	if (ret >= 0) {
7892 		if (log_level && own_log_buf) {
7893 			pr_debug("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
7894 				 prog->name, log_buf);
7895 		}
7896 
7897 		if (obj->has_rodata && kernel_supports(obj, FEAT_PROG_BIND_MAP)) {
7898 			struct bpf_map *map;
7899 			int i;
7900 
7901 			for (i = 0; i < obj->nr_maps; i++) {
7902 				map = &prog->obj->maps[i];
7903 				if (map->libbpf_type != LIBBPF_MAP_RODATA)
7904 					continue;
7905 
7906 				if (bpf_prog_bind_map(ret, map->fd, NULL)) {
7907 					pr_warn("prog '%s': failed to bind map '%s': %s\n",
7908 						prog->name, map->real_name, errstr(errno));
7909 					/* Don't fail hard if can't bind rodata. */
7910 				}
7911 			}
7912 		}
7913 
7914 		*prog_fd = ret;
7915 		ret = 0;
7916 		goto out;
7917 	}
7918 
7919 	if (log_level == 0) {
7920 		log_level = 1;
7921 		goto retry_load;
7922 	}
7923 	/* On ENOSPC, increase log buffer size and retry, unless custom
7924 	 * log_buf is specified.
7925 	 * Be careful to not overflow u32, though. Kernel's log buf size limit
7926 	 * isn't part of UAPI so it can always be bumped to full 4GB. So don't
7927 	 * multiply by 2 unless we are sure we'll fit within 32 bits.
7928 	 * Currently, we'll get -EINVAL when we reach (UINT_MAX >> 2).
7929 	 */
7930 	if (own_log_buf && errno == ENOSPC && log_buf_size <= UINT_MAX / 2)
7931 		goto retry_load;
7932 
7933 	ret = -errno;
7934 
7935 	/* post-process verifier log to improve error descriptions */
7936 	fixup_verifier_log(prog, log_buf, log_buf_size);
7937 
7938 	pr_warn("prog '%s': BPF program load failed: %s\n", prog->name, errstr(errno));
7939 	pr_perm_msg(ret);
7940 
7941 	if (own_log_buf && log_buf && log_buf[0] != '\0') {
7942 		pr_warn("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
7943 			prog->name, log_buf);
7944 	}
7945 
7946 out:
7947 	if (own_log_buf)
7948 		free(log_buf);
7949 	return ret;
7950 }
7951 
7952 static char *find_prev_line(char *buf, char *cur)
7953 {
7954 	char *p;
7955 
7956 	if (cur == buf) /* end of a log buf */
7957 		return NULL;
7958 
7959 	p = cur - 1;
7960 	while (p - 1 >= buf && *(p - 1) != '\n')
7961 		p--;
7962 
7963 	return p;
7964 }
7965 
7966 static void patch_log(char *buf, size_t buf_sz, size_t log_sz,
7967 		      char *orig, size_t orig_sz, const char *patch)
7968 {
7969 	/* size of the remaining log content to the right from the to-be-replaced part */
7970 	size_t rem_sz = (buf + log_sz) - (orig + orig_sz);
7971 	size_t patch_sz = strlen(patch);
7972 
7973 	if (patch_sz != orig_sz) {
7974 		/* If patch line(s) are longer than original piece of verifier log,
7975 		 * shift log contents by (patch_sz - orig_sz) bytes to the right
7976 		 * starting from after to-be-replaced part of the log.
7977 		 *
7978 		 * If patch line(s) are shorter than original piece of verifier log,
7979 		 * shift log contents by (orig_sz - patch_sz) bytes to the left
7980 		 * starting from after to-be-replaced part of the log
7981 		 *
7982 		 * We need to be careful about not overflowing available
7983 		 * buf_sz capacity. If that's the case, we'll truncate the end
7984 		 * of the original log, as necessary.
7985 		 */
7986 		if (patch_sz > orig_sz) {
7987 			if (orig + patch_sz >= buf + buf_sz) {
7988 				/* patch is big enough to cover remaining space completely */
7989 				patch_sz -= (orig + patch_sz) - (buf + buf_sz) + 1;
7990 				rem_sz = 0;
7991 			} else if (patch_sz - orig_sz > buf_sz - log_sz) {
7992 				/* patch causes part of remaining log to be truncated */
7993 				rem_sz -= (patch_sz - orig_sz) - (buf_sz - log_sz);
7994 			}
7995 		}
7996 		/* shift remaining log to the right by calculated amount */
7997 		memmove(orig + patch_sz, orig + orig_sz, rem_sz);
7998 	}
7999 
8000 	memcpy(orig, patch, patch_sz);
8001 }
8002 
8003 static void fixup_log_failed_core_relo(struct bpf_program *prog,
8004 				       char *buf, size_t buf_sz, size_t log_sz,
8005 				       char *line1, char *line2, char *line3)
8006 {
8007 	/* Expected log for failed and not properly guarded CO-RE relocation:
8008 	 * line1 -> 123: (85) call unknown#195896080
8009 	 * line2 -> invalid func unknown#195896080
8010 	 * line3 -> <anything else or end of buffer>
8011 	 *
8012 	 * "123" is the index of the instruction that was poisoned. We extract
8013 	 * instruction index to find corresponding CO-RE relocation and
8014 	 * replace this part of the log with more relevant information about
8015 	 * failed CO-RE relocation.
8016 	 */
8017 	const struct bpf_core_relo *relo;
8018 	struct bpf_core_spec spec;
8019 	char patch[512], spec_buf[256];
8020 	int insn_idx, err, spec_len;
8021 
8022 	if (sscanf(line1, "%d: (%*d) call unknown#195896080\n", &insn_idx) != 1)
8023 		return;
8024 
8025 	relo = find_relo_core(prog, insn_idx);
8026 	if (!relo)
8027 		return;
8028 
8029 	err = bpf_core_parse_spec(prog->name, prog->obj->btf, relo, &spec);
8030 	if (err)
8031 		return;
8032 
8033 	spec_len = bpf_core_format_spec(spec_buf, sizeof(spec_buf), &spec);
8034 	snprintf(patch, sizeof(patch),
8035 		 "%d: <invalid CO-RE relocation>\n"
8036 		 "failed to resolve CO-RE relocation %s%s\n",
8037 		 insn_idx, spec_buf, spec_len >= sizeof(spec_buf) ? "..." : "");
8038 
8039 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
8040 }
8041 
8042 static void fixup_log_missing_map_load(struct bpf_program *prog,
8043 				       char *buf, size_t buf_sz, size_t log_sz,
8044 				       char *line1, char *line2, char *line3)
8045 {
8046 	/* Expected log for failed and not properly guarded map reference:
8047 	 * line1 -> 123: (85) call unknown#2001000345
8048 	 * line2 -> invalid func unknown#2001000345
8049 	 * line3 -> <anything else or end of buffer>
8050 	 *
8051 	 * "123" is the index of the instruction that was poisoned.
8052 	 * "345" in "2001000345" is a map index in obj->maps to fetch map name.
8053 	 */
8054 	struct bpf_object *obj = prog->obj;
8055 	const struct bpf_map *map;
8056 	int insn_idx, map_idx;
8057 	char patch[128];
8058 
8059 	if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &map_idx) != 2)
8060 		return;
8061 
8062 	map_idx -= POISON_LDIMM64_MAP_BASE;
8063 	if (map_idx < 0 || map_idx >= obj->nr_maps)
8064 		return;
8065 	map = &obj->maps[map_idx];
8066 
8067 	snprintf(patch, sizeof(patch),
8068 		 "%d: <invalid BPF map reference>\n"
8069 		 "BPF map '%s' is referenced but wasn't created\n",
8070 		 insn_idx, map->name);
8071 
8072 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
8073 }
8074 
8075 static void fixup_log_missing_kfunc_call(struct bpf_program *prog,
8076 					 char *buf, size_t buf_sz, size_t log_sz,
8077 					 char *line1, char *line2, char *line3)
8078 {
8079 	/* Expected log for failed and not properly guarded kfunc call:
8080 	 * line1 -> 123: (85) call unknown#2002000345
8081 	 * line2 -> invalid func unknown#2002000345
8082 	 * line3 -> <anything else or end of buffer>
8083 	 *
8084 	 * "123" is the index of the instruction that was poisoned.
8085 	 * "345" in "2002000345" is an extern index in obj->externs to fetch kfunc name.
8086 	 */
8087 	struct bpf_object *obj = prog->obj;
8088 	const struct extern_desc *ext;
8089 	int insn_idx, ext_idx;
8090 	char patch[128];
8091 
8092 	if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &ext_idx) != 2)
8093 		return;
8094 
8095 	ext_idx -= POISON_CALL_KFUNC_BASE;
8096 	if (ext_idx < 0 || ext_idx >= obj->nr_extern)
8097 		return;
8098 	ext = &obj->externs[ext_idx];
8099 
8100 	snprintf(patch, sizeof(patch),
8101 		 "%d: <invalid kfunc call>\n"
8102 		 "kfunc '%s' is referenced but wasn't resolved\n",
8103 		 insn_idx, ext->name);
8104 
8105 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
8106 }
8107 
8108 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz)
8109 {
8110 	/* look for familiar error patterns in last N lines of the log */
8111 	const size_t max_last_line_cnt = 10;
8112 	char *prev_line, *cur_line, *next_line;
8113 	size_t log_sz;
8114 	int i;
8115 
8116 	if (!buf)
8117 		return;
8118 
8119 	log_sz = strlen(buf) + 1;
8120 	next_line = buf + log_sz - 1;
8121 
8122 	for (i = 0; i < max_last_line_cnt; i++, next_line = cur_line) {
8123 		cur_line = find_prev_line(buf, next_line);
8124 		if (!cur_line)
8125 			return;
8126 
8127 		if (str_has_pfx(cur_line, "invalid func unknown#195896080\n")) {
8128 			prev_line = find_prev_line(buf, cur_line);
8129 			if (!prev_line)
8130 				continue;
8131 
8132 			/* failed CO-RE relocation case */
8133 			fixup_log_failed_core_relo(prog, buf, buf_sz, log_sz,
8134 						   prev_line, cur_line, next_line);
8135 			return;
8136 		} else if (str_has_pfx(cur_line, "invalid func unknown#"POISON_LDIMM64_MAP_PFX)) {
8137 			prev_line = find_prev_line(buf, cur_line);
8138 			if (!prev_line)
8139 				continue;
8140 
8141 			/* reference to uncreated BPF map */
8142 			fixup_log_missing_map_load(prog, buf, buf_sz, log_sz,
8143 						   prev_line, cur_line, next_line);
8144 			return;
8145 		} else if (str_has_pfx(cur_line, "invalid func unknown#"POISON_CALL_KFUNC_PFX)) {
8146 			prev_line = find_prev_line(buf, cur_line);
8147 			if (!prev_line)
8148 				continue;
8149 
8150 			/* reference to unresolved kfunc */
8151 			fixup_log_missing_kfunc_call(prog, buf, buf_sz, log_sz,
8152 						     prev_line, cur_line, next_line);
8153 			return;
8154 		}
8155 	}
8156 }
8157 
8158 static int bpf_program_record_relos(struct bpf_program *prog)
8159 {
8160 	struct bpf_object *obj = prog->obj;
8161 	int i;
8162 
8163 	for (i = 0; i < prog->nr_reloc; i++) {
8164 		struct reloc_desc *relo = &prog->reloc_desc[i];
8165 		struct extern_desc *ext = &obj->externs[relo->ext_idx];
8166 		int kind;
8167 
8168 		switch (relo->type) {
8169 		case RELO_EXTERN_LD64:
8170 			if (ext->type != EXT_KSYM)
8171 				continue;
8172 			kind = btf_is_var(btf__type_by_id(obj->btf, ext->btf_id)) ?
8173 				BTF_KIND_VAR : BTF_KIND_FUNC;
8174 			bpf_gen__record_extern(obj->gen_loader, ext->name,
8175 					       ext->is_weak, !ext->ksym.type_id,
8176 					       true, kind, relo->insn_idx);
8177 			break;
8178 		case RELO_EXTERN_CALL:
8179 			bpf_gen__record_extern(obj->gen_loader, ext->name,
8180 					       ext->is_weak, false, false, BTF_KIND_FUNC,
8181 					       relo->insn_idx);
8182 			break;
8183 		case RELO_CORE: {
8184 			struct bpf_core_relo cr = {
8185 				.insn_off = relo->insn_idx * 8,
8186 				.type_id = relo->core_relo->type_id,
8187 				.access_str_off = relo->core_relo->access_str_off,
8188 				.kind = relo->core_relo->kind,
8189 			};
8190 
8191 			bpf_gen__record_relo_core(obj->gen_loader, &cr);
8192 			break;
8193 		}
8194 		default:
8195 			continue;
8196 		}
8197 	}
8198 	return 0;
8199 }
8200 
8201 static int
8202 bpf_object__load_progs(struct bpf_object *obj, int log_level)
8203 {
8204 	struct bpf_program *prog;
8205 	size_t i;
8206 	int err;
8207 
8208 	for (i = 0; i < obj->nr_programs; i++) {
8209 		prog = &obj->programs[i];
8210 		if (prog_is_subprog(obj, prog))
8211 			continue;
8212 		if (!prog->autoload) {
8213 			pr_debug("prog '%s': skipped loading\n", prog->name);
8214 			continue;
8215 		}
8216 		prog->log_level |= log_level;
8217 
8218 		if (obj->gen_loader)
8219 			bpf_program_record_relos(prog);
8220 
8221 		err = bpf_object_load_prog(obj, prog, prog->insns, prog->insns_cnt,
8222 					   obj->license, obj->kern_version, &prog->fd);
8223 		if (err) {
8224 			pr_warn("prog '%s': failed to load: %s\n", prog->name, errstr(err));
8225 			return err;
8226 		}
8227 	}
8228 
8229 	bpf_object__free_relocs(obj);
8230 	return 0;
8231 }
8232 
8233 static int bpf_object_prepare_progs(struct bpf_object *obj)
8234 {
8235 	struct bpf_program *prog;
8236 	size_t i;
8237 	int err;
8238 
8239 	for (i = 0; i < obj->nr_programs; i++) {
8240 		prog = &obj->programs[i];
8241 		err = bpf_object__sanitize_prog(obj, prog);
8242 		if (err)
8243 			return err;
8244 	}
8245 	return 0;
8246 }
8247 
8248 static const struct bpf_sec_def *find_sec_def(const char *sec_name);
8249 
8250 static int bpf_object_init_progs(struct bpf_object *obj, const struct bpf_object_open_opts *opts)
8251 {
8252 	struct bpf_program *prog;
8253 	int err;
8254 
8255 	bpf_object__for_each_program(prog, obj) {
8256 		prog->sec_def = find_sec_def(prog->sec_name);
8257 		if (!prog->sec_def) {
8258 			/* couldn't guess, but user might manually specify */
8259 			pr_debug("prog '%s': unrecognized ELF section name '%s'\n",
8260 				prog->name, prog->sec_name);
8261 			continue;
8262 		}
8263 
8264 		prog->type = prog->sec_def->prog_type;
8265 		prog->expected_attach_type = prog->sec_def->expected_attach_type;
8266 
8267 		/* sec_def can have custom callback which should be called
8268 		 * after bpf_program is initialized to adjust its properties
8269 		 */
8270 		if (prog->sec_def->prog_setup_fn) {
8271 			err = prog->sec_def->prog_setup_fn(prog, prog->sec_def->cookie);
8272 			if (err < 0) {
8273 				pr_warn("prog '%s': failed to initialize: %s\n",
8274 					prog->name, errstr(err));
8275 				return err;
8276 			}
8277 		}
8278 	}
8279 
8280 	return 0;
8281 }
8282 
8283 static struct bpf_object *bpf_object_open(const char *path, const void *obj_buf, size_t obj_buf_sz,
8284 					  const char *obj_name,
8285 					  const struct bpf_object_open_opts *opts)
8286 {
8287 	const char *kconfig, *btf_tmp_path, *token_path;
8288 	struct bpf_object *obj;
8289 	int err;
8290 	char *log_buf;
8291 	size_t log_size;
8292 	__u32 log_level;
8293 
8294 	if (obj_buf && !obj_name)
8295 		return ERR_PTR(-EINVAL);
8296 
8297 	if (elf_version(EV_CURRENT) == EV_NONE) {
8298 		pr_warn("failed to init libelf for %s\n",
8299 			path ? : "(mem buf)");
8300 		return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
8301 	}
8302 
8303 	if (!OPTS_VALID(opts, bpf_object_open_opts))
8304 		return ERR_PTR(-EINVAL);
8305 
8306 	obj_name = OPTS_GET(opts, object_name, NULL) ?: obj_name;
8307 	if (obj_buf) {
8308 		path = obj_name;
8309 		pr_debug("loading object '%s' from buffer\n", obj_name);
8310 	} else {
8311 		pr_debug("loading object from %s\n", path);
8312 	}
8313 
8314 	log_buf = OPTS_GET(opts, kernel_log_buf, NULL);
8315 	log_size = OPTS_GET(opts, kernel_log_size, 0);
8316 	log_level = OPTS_GET(opts, kernel_log_level, 0);
8317 	if (log_size > UINT_MAX)
8318 		return ERR_PTR(-EINVAL);
8319 	if (log_size && !log_buf)
8320 		return ERR_PTR(-EINVAL);
8321 
8322 	token_path = OPTS_GET(opts, bpf_token_path, NULL);
8323 	/* if user didn't specify bpf_token_path explicitly, check if
8324 	 * LIBBPF_BPF_TOKEN_PATH envvar was set and treat it as bpf_token_path
8325 	 * option
8326 	 */
8327 	if (!token_path)
8328 		token_path = getenv("LIBBPF_BPF_TOKEN_PATH");
8329 	if (token_path && strlen(token_path) >= PATH_MAX)
8330 		return ERR_PTR(-ENAMETOOLONG);
8331 
8332 	obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
8333 	if (IS_ERR(obj))
8334 		return obj;
8335 
8336 	obj->log_buf = log_buf;
8337 	obj->log_size = log_size;
8338 	obj->log_level = log_level;
8339 
8340 	if (token_path) {
8341 		obj->token_path = strdup(token_path);
8342 		if (!obj->token_path) {
8343 			err = -ENOMEM;
8344 			goto out;
8345 		}
8346 	}
8347 
8348 	btf_tmp_path = OPTS_GET(opts, btf_custom_path, NULL);
8349 	if (btf_tmp_path) {
8350 		if (strlen(btf_tmp_path) >= PATH_MAX) {
8351 			err = -ENAMETOOLONG;
8352 			goto out;
8353 		}
8354 		obj->btf_custom_path = strdup(btf_tmp_path);
8355 		if (!obj->btf_custom_path) {
8356 			err = -ENOMEM;
8357 			goto out;
8358 		}
8359 	}
8360 
8361 	kconfig = OPTS_GET(opts, kconfig, NULL);
8362 	if (kconfig) {
8363 		obj->kconfig = strdup(kconfig);
8364 		if (!obj->kconfig) {
8365 			err = -ENOMEM;
8366 			goto out;
8367 		}
8368 	}
8369 
8370 	err = bpf_object__elf_init(obj);
8371 	err = err ? : bpf_object__elf_collect(obj);
8372 	err = err ? : bpf_object__collect_externs(obj);
8373 	err = err ? : bpf_object_fixup_btf(obj);
8374 	err = err ? : bpf_object__init_maps(obj, opts);
8375 	err = err ? : bpf_object_init_progs(obj, opts);
8376 	err = err ? : bpf_object__collect_relos(obj);
8377 	if (err)
8378 		goto out;
8379 
8380 	bpf_object__elf_finish(obj);
8381 
8382 	return obj;
8383 out:
8384 	bpf_object__close(obj);
8385 	return ERR_PTR(err);
8386 }
8387 
8388 struct bpf_object *
8389 bpf_object__open_file(const char *path, const struct bpf_object_open_opts *opts)
8390 {
8391 	if (!path)
8392 		return libbpf_err_ptr(-EINVAL);
8393 
8394 	return libbpf_ptr(bpf_object_open(path, NULL, 0, NULL, opts));
8395 }
8396 
8397 struct bpf_object *bpf_object__open(const char *path)
8398 {
8399 	return bpf_object__open_file(path, NULL);
8400 }
8401 
8402 struct bpf_object *
8403 bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
8404 		     const struct bpf_object_open_opts *opts)
8405 {
8406 	char tmp_name[64];
8407 
8408 	if (!obj_buf || obj_buf_sz == 0)
8409 		return libbpf_err_ptr(-EINVAL);
8410 
8411 	/* create a (quite useless) default "name" for this memory buffer object */
8412 	snprintf(tmp_name, sizeof(tmp_name), "%lx-%zx", (unsigned long)obj_buf, obj_buf_sz);
8413 
8414 	return libbpf_ptr(bpf_object_open(NULL, obj_buf, obj_buf_sz, tmp_name, opts));
8415 }
8416 
8417 static int bpf_object_unload(struct bpf_object *obj)
8418 {
8419 	size_t i;
8420 
8421 	if (!obj)
8422 		return libbpf_err(-EINVAL);
8423 
8424 	for (i = 0; i < obj->nr_maps; i++) {
8425 		zclose(obj->maps[i].fd);
8426 		if (obj->maps[i].st_ops)
8427 			zfree(&obj->maps[i].st_ops->kern_vdata);
8428 	}
8429 
8430 	for (i = 0; i < obj->nr_programs; i++)
8431 		bpf_program__unload(&obj->programs[i]);
8432 
8433 	return 0;
8434 }
8435 
8436 static int bpf_object__sanitize_maps(struct bpf_object *obj)
8437 {
8438 	struct bpf_map *m;
8439 
8440 	bpf_object__for_each_map(m, obj) {
8441 		if (!bpf_map__is_internal(m))
8442 			continue;
8443 		if (!kernel_supports(obj, FEAT_ARRAY_MMAP))
8444 			m->def.map_flags &= ~BPF_F_MMAPABLE;
8445 	}
8446 
8447 	return 0;
8448 }
8449 
8450 typedef int (*kallsyms_cb_t)(unsigned long long sym_addr, char sym_type,
8451 			     const char *sym_name, void *ctx);
8452 
8453 static int libbpf_kallsyms_parse(kallsyms_cb_t cb, void *ctx)
8454 {
8455 	char sym_type, sym_name[500];
8456 	unsigned long long sym_addr;
8457 	int ret, err = 0;
8458 	FILE *f;
8459 
8460 	f = fopen("/proc/kallsyms", "re");
8461 	if (!f) {
8462 		err = -errno;
8463 		pr_warn("failed to open /proc/kallsyms: %s\n", errstr(err));
8464 		return err;
8465 	}
8466 
8467 	while (true) {
8468 		ret = fscanf(f, "%llx %c %499s%*[^\n]\n",
8469 			     &sym_addr, &sym_type, sym_name);
8470 		if (ret == EOF && feof(f))
8471 			break;
8472 		if (ret != 3) {
8473 			pr_warn("failed to read kallsyms entry: %d\n", ret);
8474 			err = -EINVAL;
8475 			break;
8476 		}
8477 
8478 		err = cb(sym_addr, sym_type, sym_name, ctx);
8479 		if (err)
8480 			break;
8481 	}
8482 
8483 	fclose(f);
8484 	return err;
8485 }
8486 
8487 static int kallsyms_cb(unsigned long long sym_addr, char sym_type,
8488 		       const char *sym_name, void *ctx)
8489 {
8490 	struct bpf_object *obj = ctx;
8491 	const struct btf_type *t;
8492 	struct extern_desc *ext;
8493 	const char *res;
8494 
8495 	res = strstr(sym_name, ".llvm.");
8496 	if (sym_type == 'd' && res)
8497 		ext = find_extern_by_name_with_len(obj, sym_name, res - sym_name);
8498 	else
8499 		ext = find_extern_by_name(obj, sym_name);
8500 	if (!ext || ext->type != EXT_KSYM)
8501 		return 0;
8502 
8503 	t = btf__type_by_id(obj->btf, ext->btf_id);
8504 	if (!btf_is_var(t))
8505 		return 0;
8506 
8507 	if (ext->is_set && ext->ksym.addr != sym_addr) {
8508 		pr_warn("extern (ksym) '%s': resolution is ambiguous: 0x%llx or 0x%llx\n",
8509 			sym_name, ext->ksym.addr, sym_addr);
8510 		return -EINVAL;
8511 	}
8512 	if (!ext->is_set) {
8513 		ext->is_set = true;
8514 		ext->ksym.addr = sym_addr;
8515 		pr_debug("extern (ksym) '%s': set to 0x%llx\n", sym_name, sym_addr);
8516 	}
8517 	return 0;
8518 }
8519 
8520 static int bpf_object__read_kallsyms_file(struct bpf_object *obj)
8521 {
8522 	return libbpf_kallsyms_parse(kallsyms_cb, obj);
8523 }
8524 
8525 static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
8526 			    __u16 kind, struct btf **res_btf,
8527 			    struct module_btf **res_mod_btf)
8528 {
8529 	struct module_btf *mod_btf;
8530 	struct btf *btf;
8531 	int i, id, err;
8532 
8533 	btf = obj->btf_vmlinux;
8534 	mod_btf = NULL;
8535 	id = btf__find_by_name_kind(btf, ksym_name, kind);
8536 
8537 	if (id == -ENOENT) {
8538 		err = load_module_btfs(obj);
8539 		if (err)
8540 			return err;
8541 
8542 		for (i = 0; i < obj->btf_module_cnt; i++) {
8543 			/* we assume module_btf's BTF FD is always >0 */
8544 			mod_btf = &obj->btf_modules[i];
8545 			btf = mod_btf->btf;
8546 			id = btf__find_by_name_kind_own(btf, ksym_name, kind);
8547 			if (id != -ENOENT)
8548 				break;
8549 		}
8550 	}
8551 	if (id <= 0)
8552 		return -ESRCH;
8553 
8554 	*res_btf = btf;
8555 	*res_mod_btf = mod_btf;
8556 	return id;
8557 }
8558 
8559 static int bpf_object__resolve_ksym_var_btf_id(struct bpf_object *obj,
8560 					       struct extern_desc *ext)
8561 {
8562 	const struct btf_type *targ_var, *targ_type;
8563 	__u32 targ_type_id, local_type_id;
8564 	struct module_btf *mod_btf = NULL;
8565 	const char *targ_var_name;
8566 	struct btf *btf = NULL;
8567 	int id, err;
8568 
8569 	id = find_ksym_btf_id(obj, ext->name, BTF_KIND_VAR, &btf, &mod_btf);
8570 	if (id < 0) {
8571 		if (id == -ESRCH && ext->is_weak)
8572 			return 0;
8573 		pr_warn("extern (var ksym) '%s': not found in kernel BTF\n",
8574 			ext->name);
8575 		return id;
8576 	}
8577 
8578 	/* find local type_id */
8579 	local_type_id = ext->ksym.type_id;
8580 
8581 	/* find target type_id */
8582 	targ_var = btf__type_by_id(btf, id);
8583 	targ_var_name = btf__name_by_offset(btf, targ_var->name_off);
8584 	targ_type = skip_mods_and_typedefs(btf, targ_var->type, &targ_type_id);
8585 
8586 	err = bpf_core_types_are_compat(obj->btf, local_type_id,
8587 					btf, targ_type_id);
8588 	if (err <= 0) {
8589 		const struct btf_type *local_type;
8590 		const char *targ_name, *local_name;
8591 
8592 		local_type = btf__type_by_id(obj->btf, local_type_id);
8593 		local_name = btf__name_by_offset(obj->btf, local_type->name_off);
8594 		targ_name = btf__name_by_offset(btf, targ_type->name_off);
8595 
8596 		pr_warn("extern (var ksym) '%s': incompatible types, expected [%d] %s %s, but kernel has [%d] %s %s\n",
8597 			ext->name, local_type_id,
8598 			btf_kind_str(local_type), local_name, targ_type_id,
8599 			btf_kind_str(targ_type), targ_name);
8600 		return -EINVAL;
8601 	}
8602 
8603 	ext->is_set = true;
8604 	ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
8605 	ext->ksym.kernel_btf_id = id;
8606 	pr_debug("extern (var ksym) '%s': resolved to [%d] %s %s\n",
8607 		 ext->name, id, btf_kind_str(targ_var), targ_var_name);
8608 
8609 	return 0;
8610 }
8611 
8612 static int bpf_object__resolve_ksym_func_btf_id(struct bpf_object *obj,
8613 						struct extern_desc *ext)
8614 {
8615 	int local_func_proto_id, kfunc_proto_id, kfunc_id;
8616 	struct module_btf *mod_btf = NULL;
8617 	const struct btf_type *kern_func;
8618 	struct btf *kern_btf = NULL;
8619 	int ret;
8620 
8621 	local_func_proto_id = ext->ksym.type_id;
8622 
8623 	kfunc_id = find_ksym_btf_id(obj, ext->essent_name ?: ext->name, BTF_KIND_FUNC, &kern_btf,
8624 				    &mod_btf);
8625 	if (kfunc_id < 0) {
8626 		if (kfunc_id == -ESRCH && ext->is_weak)
8627 			return 0;
8628 		pr_warn("extern (func ksym) '%s': not found in kernel or module BTFs\n",
8629 			ext->name);
8630 		return kfunc_id;
8631 	}
8632 
8633 	kern_func = btf__type_by_id(kern_btf, kfunc_id);
8634 	kfunc_proto_id = kern_func->type;
8635 
8636 	ret = bpf_core_types_are_compat(obj->btf, local_func_proto_id,
8637 					kern_btf, kfunc_proto_id);
8638 	if (ret <= 0) {
8639 		if (ext->is_weak)
8640 			return 0;
8641 
8642 		pr_warn("extern (func ksym) '%s': func_proto [%d] incompatible with %s [%d]\n",
8643 			ext->name, local_func_proto_id,
8644 			mod_btf ? mod_btf->name : "vmlinux", kfunc_proto_id);
8645 		return -EINVAL;
8646 	}
8647 
8648 	/* set index for module BTF fd in fd_array, if unset */
8649 	if (mod_btf && !mod_btf->fd_array_idx) {
8650 		/* insn->off is s16 */
8651 		if (obj->fd_array_cnt == INT16_MAX) {
8652 			pr_warn("extern (func ksym) '%s': module BTF fd index %d too big to fit in bpf_insn offset\n",
8653 				ext->name, mod_btf->fd_array_idx);
8654 			return -E2BIG;
8655 		}
8656 		/* Cannot use index 0 for module BTF fd */
8657 		if (!obj->fd_array_cnt)
8658 			obj->fd_array_cnt = 1;
8659 
8660 		ret = libbpf_ensure_mem((void **)&obj->fd_array, &obj->fd_array_cap, sizeof(int),
8661 					obj->fd_array_cnt + 1);
8662 		if (ret)
8663 			return ret;
8664 		mod_btf->fd_array_idx = obj->fd_array_cnt;
8665 		/* we assume module BTF FD is always >0 */
8666 		obj->fd_array[obj->fd_array_cnt++] = mod_btf->fd;
8667 	}
8668 
8669 	ext->is_set = true;
8670 	ext->ksym.kernel_btf_id = kfunc_id;
8671 	ext->ksym.btf_fd_idx = mod_btf ? mod_btf->fd_array_idx : 0;
8672 	/* Also set kernel_btf_obj_fd to make sure that bpf_object__relocate_data()
8673 	 * populates FD into ld_imm64 insn when it's used to point to kfunc.
8674 	 * {kernel_btf_id, btf_fd_idx} -> fixup bpf_call.
8675 	 * {kernel_btf_id, kernel_btf_obj_fd} -> fixup ld_imm64.
8676 	 */
8677 	ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
8678 	pr_debug("extern (func ksym) '%s': resolved to %s [%d]\n",
8679 		 ext->name, mod_btf ? mod_btf->name : "vmlinux", kfunc_id);
8680 
8681 	return 0;
8682 }
8683 
8684 static int bpf_object__resolve_ksyms_btf_id(struct bpf_object *obj)
8685 {
8686 	const struct btf_type *t;
8687 	struct extern_desc *ext;
8688 	int i, err;
8689 
8690 	for (i = 0; i < obj->nr_extern; i++) {
8691 		ext = &obj->externs[i];
8692 		if (ext->type != EXT_KSYM || !ext->ksym.type_id)
8693 			continue;
8694 
8695 		if (obj->gen_loader) {
8696 			ext->is_set = true;
8697 			ext->ksym.kernel_btf_obj_fd = 0;
8698 			ext->ksym.kernel_btf_id = 0;
8699 			continue;
8700 		}
8701 		t = btf__type_by_id(obj->btf, ext->btf_id);
8702 		if (btf_is_var(t))
8703 			err = bpf_object__resolve_ksym_var_btf_id(obj, ext);
8704 		else
8705 			err = bpf_object__resolve_ksym_func_btf_id(obj, ext);
8706 		if (err)
8707 			return err;
8708 	}
8709 	return 0;
8710 }
8711 
8712 static int bpf_object__resolve_externs(struct bpf_object *obj,
8713 				       const char *extra_kconfig)
8714 {
8715 	bool need_config = false, need_kallsyms = false;
8716 	bool need_vmlinux_btf = false;
8717 	struct extern_desc *ext;
8718 	void *kcfg_data = NULL;
8719 	int err, i;
8720 
8721 	if (obj->nr_extern == 0)
8722 		return 0;
8723 
8724 	if (obj->kconfig_map_idx >= 0)
8725 		kcfg_data = obj->maps[obj->kconfig_map_idx].mmaped;
8726 
8727 	for (i = 0; i < obj->nr_extern; i++) {
8728 		ext = &obj->externs[i];
8729 
8730 		if (ext->type == EXT_KSYM) {
8731 			if (ext->ksym.type_id)
8732 				need_vmlinux_btf = true;
8733 			else
8734 				need_kallsyms = true;
8735 			continue;
8736 		} else if (ext->type == EXT_KCFG) {
8737 			void *ext_ptr = kcfg_data + ext->kcfg.data_off;
8738 			__u64 value = 0;
8739 
8740 			/* Kconfig externs need actual /proc/config.gz */
8741 			if (str_has_pfx(ext->name, "CONFIG_")) {
8742 				need_config = true;
8743 				continue;
8744 			}
8745 
8746 			/* Virtual kcfg externs are customly handled by libbpf */
8747 			if (strcmp(ext->name, "LINUX_KERNEL_VERSION") == 0) {
8748 				value = get_kernel_version();
8749 				if (!value) {
8750 					pr_warn("extern (kcfg) '%s': failed to get kernel version\n", ext->name);
8751 					return -EINVAL;
8752 				}
8753 			} else if (strcmp(ext->name, "LINUX_HAS_BPF_COOKIE") == 0) {
8754 				value = kernel_supports(obj, FEAT_BPF_COOKIE);
8755 			} else if (strcmp(ext->name, "LINUX_HAS_SYSCALL_WRAPPER") == 0) {
8756 				value = kernel_supports(obj, FEAT_SYSCALL_WRAPPER);
8757 			} else if (!str_has_pfx(ext->name, "LINUX_") || !ext->is_weak) {
8758 				/* Currently libbpf supports only CONFIG_ and LINUX_ prefixed
8759 				 * __kconfig externs, where LINUX_ ones are virtual and filled out
8760 				 * customly by libbpf (their values don't come from Kconfig).
8761 				 * If LINUX_xxx variable is not recognized by libbpf, but is marked
8762 				 * __weak, it defaults to zero value, just like for CONFIG_xxx
8763 				 * externs.
8764 				 */
8765 				pr_warn("extern (kcfg) '%s': unrecognized virtual extern\n", ext->name);
8766 				return -EINVAL;
8767 			}
8768 
8769 			err = set_kcfg_value_num(ext, ext_ptr, value);
8770 			if (err)
8771 				return err;
8772 			pr_debug("extern (kcfg) '%s': set to 0x%llx\n",
8773 				 ext->name, (long long)value);
8774 		} else {
8775 			pr_warn("extern '%s': unrecognized extern kind\n", ext->name);
8776 			return -EINVAL;
8777 		}
8778 	}
8779 	if (need_config && extra_kconfig) {
8780 		err = bpf_object__read_kconfig_mem(obj, extra_kconfig, kcfg_data);
8781 		if (err)
8782 			return -EINVAL;
8783 		need_config = false;
8784 		for (i = 0; i < obj->nr_extern; i++) {
8785 			ext = &obj->externs[i];
8786 			if (ext->type == EXT_KCFG && !ext->is_set) {
8787 				need_config = true;
8788 				break;
8789 			}
8790 		}
8791 	}
8792 	if (need_config) {
8793 		err = bpf_object__read_kconfig_file(obj, kcfg_data);
8794 		if (err)
8795 			return -EINVAL;
8796 	}
8797 	if (need_kallsyms) {
8798 		err = bpf_object__read_kallsyms_file(obj);
8799 		if (err)
8800 			return -EINVAL;
8801 	}
8802 	if (need_vmlinux_btf) {
8803 		err = bpf_object__resolve_ksyms_btf_id(obj);
8804 		if (err)
8805 			return -EINVAL;
8806 	}
8807 	for (i = 0; i < obj->nr_extern; i++) {
8808 		ext = &obj->externs[i];
8809 
8810 		if (!ext->is_set && !ext->is_weak) {
8811 			pr_warn("extern '%s' (strong): not resolved\n", ext->name);
8812 			return -ESRCH;
8813 		} else if (!ext->is_set) {
8814 			pr_debug("extern '%s' (weak): not resolved, defaulting to zero\n",
8815 				 ext->name);
8816 		}
8817 	}
8818 
8819 	return 0;
8820 }
8821 
8822 static void bpf_map_prepare_vdata(const struct bpf_map *map)
8823 {
8824 	const struct btf_type *type;
8825 	struct bpf_struct_ops *st_ops;
8826 	__u32 i;
8827 
8828 	st_ops = map->st_ops;
8829 	type = btf__type_by_id(map->obj->btf, st_ops->type_id);
8830 	for (i = 0; i < btf_vlen(type); i++) {
8831 		struct bpf_program *prog = st_ops->progs[i];
8832 		void *kern_data;
8833 		int prog_fd;
8834 
8835 		if (!prog)
8836 			continue;
8837 
8838 		prog_fd = bpf_program__fd(prog);
8839 		kern_data = st_ops->kern_vdata + st_ops->kern_func_off[i];
8840 		*(unsigned long *)kern_data = prog_fd;
8841 	}
8842 }
8843 
8844 static int bpf_object_prepare_struct_ops(struct bpf_object *obj)
8845 {
8846 	struct bpf_map *map;
8847 	int i;
8848 
8849 	for (i = 0; i < obj->nr_maps; i++) {
8850 		map = &obj->maps[i];
8851 
8852 		if (!bpf_map__is_struct_ops(map))
8853 			continue;
8854 
8855 		if (!map->autocreate)
8856 			continue;
8857 
8858 		bpf_map_prepare_vdata(map);
8859 	}
8860 
8861 	return 0;
8862 }
8863 
8864 static void bpf_object_unpin(struct bpf_object *obj)
8865 {
8866 	int i;
8867 
8868 	/* unpin any maps that were auto-pinned during load */
8869 	for (i = 0; i < obj->nr_maps; i++)
8870 		if (obj->maps[i].pinned && !obj->maps[i].reused)
8871 			bpf_map__unpin(&obj->maps[i], NULL);
8872 }
8873 
8874 static void bpf_object_post_load_cleanup(struct bpf_object *obj)
8875 {
8876 	int i;
8877 
8878 	/* clean up fd_array */
8879 	zfree(&obj->fd_array);
8880 
8881 	/* clean up module BTFs */
8882 	for (i = 0; i < obj->btf_module_cnt; i++) {
8883 		close(obj->btf_modules[i].fd);
8884 		btf__free(obj->btf_modules[i].btf);
8885 		free(obj->btf_modules[i].name);
8886 	}
8887 	obj->btf_module_cnt = 0;
8888 	zfree(&obj->btf_modules);
8889 
8890 	/* clean up vmlinux BTF */
8891 	btf__free(obj->btf_vmlinux);
8892 	obj->btf_vmlinux = NULL;
8893 }
8894 
8895 static int bpf_object_prepare(struct bpf_object *obj, const char *target_btf_path)
8896 {
8897 	int err;
8898 
8899 	if (obj->state >= OBJ_PREPARED) {
8900 		pr_warn("object '%s': prepare loading can't be attempted twice\n", obj->name);
8901 		return -EINVAL;
8902 	}
8903 
8904 	err = bpf_object_prepare_token(obj);
8905 	err = err ? : bpf_object__probe_loading(obj);
8906 	err = err ? : bpf_object__load_vmlinux_btf(obj, false);
8907 	err = err ? : bpf_object__resolve_externs(obj, obj->kconfig);
8908 	err = err ? : bpf_object__sanitize_maps(obj);
8909 	err = err ? : bpf_object__init_kern_struct_ops_maps(obj);
8910 	err = err ? : bpf_object_adjust_struct_ops_autoload(obj);
8911 	err = err ? : bpf_object__relocate(obj, obj->btf_custom_path ? : target_btf_path);
8912 	err = err ? : bpf_object__sanitize_and_load_btf(obj);
8913 	err = err ? : bpf_object__create_maps(obj);
8914 	err = err ? : bpf_object_prepare_progs(obj);
8915 
8916 	if (err) {
8917 		bpf_object_unpin(obj);
8918 		bpf_object_unload(obj);
8919 		obj->state = OBJ_LOADED;
8920 		return err;
8921 	}
8922 
8923 	obj->state = OBJ_PREPARED;
8924 	return 0;
8925 }
8926 
8927 static int bpf_object_load(struct bpf_object *obj, int extra_log_level, const char *target_btf_path)
8928 {
8929 	int err;
8930 
8931 	if (!obj)
8932 		return libbpf_err(-EINVAL);
8933 
8934 	if (obj->state >= OBJ_LOADED) {
8935 		pr_warn("object '%s': load can't be attempted twice\n", obj->name);
8936 		return libbpf_err(-EINVAL);
8937 	}
8938 
8939 	/* Disallow kernel loading programs of non-native endianness but
8940 	 * permit cross-endian creation of "light skeleton".
8941 	 */
8942 	if (obj->gen_loader) {
8943 		bpf_gen__init(obj->gen_loader, extra_log_level, obj->nr_programs, obj->nr_maps);
8944 	} else if (!is_native_endianness(obj)) {
8945 		pr_warn("object '%s': loading non-native endianness is unsupported\n", obj->name);
8946 		return libbpf_err(-LIBBPF_ERRNO__ENDIAN);
8947 	}
8948 
8949 	if (obj->state < OBJ_PREPARED) {
8950 		err = bpf_object_prepare(obj, target_btf_path);
8951 		if (err)
8952 			return libbpf_err(err);
8953 	}
8954 	err = bpf_object__load_progs(obj, extra_log_level);
8955 	err = err ? : bpf_object_init_prog_arrays(obj);
8956 	err = err ? : bpf_object_prepare_struct_ops(obj);
8957 
8958 	if (obj->gen_loader) {
8959 		/* reset FDs */
8960 		if (obj->btf)
8961 			btf__set_fd(obj->btf, -1);
8962 		if (!err)
8963 			err = bpf_gen__finish(obj->gen_loader, obj->nr_programs, obj->nr_maps);
8964 	}
8965 
8966 	bpf_object_post_load_cleanup(obj);
8967 	obj->state = OBJ_LOADED; /* doesn't matter if successfully or not */
8968 
8969 	if (err) {
8970 		bpf_object_unpin(obj);
8971 		bpf_object_unload(obj);
8972 		pr_warn("failed to load object '%s'\n", obj->path);
8973 		return libbpf_err(err);
8974 	}
8975 
8976 	return 0;
8977 }
8978 
8979 int bpf_object__prepare(struct bpf_object *obj)
8980 {
8981 	return libbpf_err(bpf_object_prepare(obj, NULL));
8982 }
8983 
8984 int bpf_object__load(struct bpf_object *obj)
8985 {
8986 	return bpf_object_load(obj, 0, NULL);
8987 }
8988 
8989 static int make_parent_dir(const char *path)
8990 {
8991 	char *dname, *dir;
8992 	int err = 0;
8993 
8994 	dname = strdup(path);
8995 	if (dname == NULL)
8996 		return -ENOMEM;
8997 
8998 	dir = dirname(dname);
8999 	if (mkdir(dir, 0700) && errno != EEXIST)
9000 		err = -errno;
9001 
9002 	free(dname);
9003 	if (err) {
9004 		pr_warn("failed to mkdir %s: %s\n", path, errstr(err));
9005 	}
9006 	return err;
9007 }
9008 
9009 static int check_path(const char *path)
9010 {
9011 	struct statfs st_fs;
9012 	char *dname, *dir;
9013 	int err = 0;
9014 
9015 	if (path == NULL)
9016 		return -EINVAL;
9017 
9018 	dname = strdup(path);
9019 	if (dname == NULL)
9020 		return -ENOMEM;
9021 
9022 	dir = dirname(dname);
9023 	if (statfs(dir, &st_fs)) {
9024 		pr_warn("failed to statfs %s: %s\n", dir, errstr(errno));
9025 		err = -errno;
9026 	}
9027 	free(dname);
9028 
9029 	if (!err && st_fs.f_type != BPF_FS_MAGIC) {
9030 		pr_warn("specified path %s is not on BPF FS\n", path);
9031 		err = -EINVAL;
9032 	}
9033 
9034 	return err;
9035 }
9036 
9037 int bpf_program__pin(struct bpf_program *prog, const char *path)
9038 {
9039 	int err;
9040 
9041 	if (prog->fd < 0) {
9042 		pr_warn("prog '%s': can't pin program that wasn't loaded\n", prog->name);
9043 		return libbpf_err(-EINVAL);
9044 	}
9045 
9046 	err = make_parent_dir(path);
9047 	if (err)
9048 		return libbpf_err(err);
9049 
9050 	err = check_path(path);
9051 	if (err)
9052 		return libbpf_err(err);
9053 
9054 	if (bpf_obj_pin(prog->fd, path)) {
9055 		err = -errno;
9056 		pr_warn("prog '%s': failed to pin at '%s': %s\n", prog->name, path, errstr(err));
9057 		return libbpf_err(err);
9058 	}
9059 
9060 	pr_debug("prog '%s': pinned at '%s'\n", prog->name, path);
9061 	return 0;
9062 }
9063 
9064 int bpf_program__unpin(struct bpf_program *prog, const char *path)
9065 {
9066 	int err;
9067 
9068 	if (prog->fd < 0) {
9069 		pr_warn("prog '%s': can't unpin program that wasn't loaded\n", prog->name);
9070 		return libbpf_err(-EINVAL);
9071 	}
9072 
9073 	err = check_path(path);
9074 	if (err)
9075 		return libbpf_err(err);
9076 
9077 	err = unlink(path);
9078 	if (err)
9079 		return libbpf_err(-errno);
9080 
9081 	pr_debug("prog '%s': unpinned from '%s'\n", prog->name, path);
9082 	return 0;
9083 }
9084 
9085 int bpf_map__pin(struct bpf_map *map, const char *path)
9086 {
9087 	int err;
9088 
9089 	if (map == NULL) {
9090 		pr_warn("invalid map pointer\n");
9091 		return libbpf_err(-EINVAL);
9092 	}
9093 
9094 	if (map->fd < 0) {
9095 		pr_warn("map '%s': can't pin BPF map without FD (was it created?)\n", map->name);
9096 		return libbpf_err(-EINVAL);
9097 	}
9098 
9099 	if (map->pin_path) {
9100 		if (path && strcmp(path, map->pin_path)) {
9101 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
9102 				bpf_map__name(map), map->pin_path, path);
9103 			return libbpf_err(-EINVAL);
9104 		} else if (map->pinned) {
9105 			pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
9106 				 bpf_map__name(map), map->pin_path);
9107 			return 0;
9108 		}
9109 	} else {
9110 		if (!path) {
9111 			pr_warn("missing a path to pin map '%s' at\n",
9112 				bpf_map__name(map));
9113 			return libbpf_err(-EINVAL);
9114 		} else if (map->pinned) {
9115 			pr_warn("map '%s' already pinned\n", bpf_map__name(map));
9116 			return libbpf_err(-EEXIST);
9117 		}
9118 
9119 		map->pin_path = strdup(path);
9120 		if (!map->pin_path) {
9121 			err = -errno;
9122 			goto out_err;
9123 		}
9124 	}
9125 
9126 	err = make_parent_dir(map->pin_path);
9127 	if (err)
9128 		return libbpf_err(err);
9129 
9130 	err = check_path(map->pin_path);
9131 	if (err)
9132 		return libbpf_err(err);
9133 
9134 	if (bpf_obj_pin(map->fd, map->pin_path)) {
9135 		err = -errno;
9136 		goto out_err;
9137 	}
9138 
9139 	map->pinned = true;
9140 	pr_debug("pinned map '%s'\n", map->pin_path);
9141 
9142 	return 0;
9143 
9144 out_err:
9145 	pr_warn("failed to pin map: %s\n", errstr(err));
9146 	return libbpf_err(err);
9147 }
9148 
9149 int bpf_map__unpin(struct bpf_map *map, const char *path)
9150 {
9151 	int err;
9152 
9153 	if (map == NULL) {
9154 		pr_warn("invalid map pointer\n");
9155 		return libbpf_err(-EINVAL);
9156 	}
9157 
9158 	if (map->pin_path) {
9159 		if (path && strcmp(path, map->pin_path)) {
9160 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
9161 				bpf_map__name(map), map->pin_path, path);
9162 			return libbpf_err(-EINVAL);
9163 		}
9164 		path = map->pin_path;
9165 	} else if (!path) {
9166 		pr_warn("no path to unpin map '%s' from\n",
9167 			bpf_map__name(map));
9168 		return libbpf_err(-EINVAL);
9169 	}
9170 
9171 	err = check_path(path);
9172 	if (err)
9173 		return libbpf_err(err);
9174 
9175 	err = unlink(path);
9176 	if (err != 0)
9177 		return libbpf_err(-errno);
9178 
9179 	map->pinned = false;
9180 	pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path);
9181 
9182 	return 0;
9183 }
9184 
9185 int bpf_map__set_pin_path(struct bpf_map *map, const char *path)
9186 {
9187 	char *new = NULL;
9188 
9189 	if (path) {
9190 		new = strdup(path);
9191 		if (!new)
9192 			return libbpf_err(-errno);
9193 	}
9194 
9195 	free(map->pin_path);
9196 	map->pin_path = new;
9197 	return 0;
9198 }
9199 
9200 __alias(bpf_map__pin_path)
9201 const char *bpf_map__get_pin_path(const struct bpf_map *map);
9202 
9203 const char *bpf_map__pin_path(const struct bpf_map *map)
9204 {
9205 	return map->pin_path;
9206 }
9207 
9208 bool bpf_map__is_pinned(const struct bpf_map *map)
9209 {
9210 	return map->pinned;
9211 }
9212 
9213 static void sanitize_pin_path(char *s)
9214 {
9215 	/* bpffs disallows periods in path names */
9216 	while (*s) {
9217 		if (*s == '.')
9218 			*s = '_';
9219 		s++;
9220 	}
9221 }
9222 
9223 int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
9224 {
9225 	struct bpf_map *map;
9226 	int err;
9227 
9228 	if (!obj)
9229 		return libbpf_err(-ENOENT);
9230 
9231 	if (obj->state < OBJ_PREPARED) {
9232 		pr_warn("object not yet loaded; load it first\n");
9233 		return libbpf_err(-ENOENT);
9234 	}
9235 
9236 	bpf_object__for_each_map(map, obj) {
9237 		char *pin_path = NULL;
9238 		char buf[PATH_MAX];
9239 
9240 		if (!map->autocreate)
9241 			continue;
9242 
9243 		if (path) {
9244 			err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
9245 			if (err)
9246 				goto err_unpin_maps;
9247 			sanitize_pin_path(buf);
9248 			pin_path = buf;
9249 		} else if (!map->pin_path) {
9250 			continue;
9251 		}
9252 
9253 		err = bpf_map__pin(map, pin_path);
9254 		if (err)
9255 			goto err_unpin_maps;
9256 	}
9257 
9258 	return 0;
9259 
9260 err_unpin_maps:
9261 	while ((map = bpf_object__prev_map(obj, map))) {
9262 		if (!map->pin_path)
9263 			continue;
9264 
9265 		bpf_map__unpin(map, NULL);
9266 	}
9267 
9268 	return libbpf_err(err);
9269 }
9270 
9271 int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
9272 {
9273 	struct bpf_map *map;
9274 	int err;
9275 
9276 	if (!obj)
9277 		return libbpf_err(-ENOENT);
9278 
9279 	bpf_object__for_each_map(map, obj) {
9280 		char *pin_path = NULL;
9281 		char buf[PATH_MAX];
9282 
9283 		if (path) {
9284 			err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
9285 			if (err)
9286 				return libbpf_err(err);
9287 			sanitize_pin_path(buf);
9288 			pin_path = buf;
9289 		} else if (!map->pin_path) {
9290 			continue;
9291 		}
9292 
9293 		err = bpf_map__unpin(map, pin_path);
9294 		if (err)
9295 			return libbpf_err(err);
9296 	}
9297 
9298 	return 0;
9299 }
9300 
9301 int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
9302 {
9303 	struct bpf_program *prog;
9304 	char buf[PATH_MAX];
9305 	int err;
9306 
9307 	if (!obj)
9308 		return libbpf_err(-ENOENT);
9309 
9310 	if (obj->state < OBJ_LOADED) {
9311 		pr_warn("object not yet loaded; load it first\n");
9312 		return libbpf_err(-ENOENT);
9313 	}
9314 
9315 	bpf_object__for_each_program(prog, obj) {
9316 		err = pathname_concat(buf, sizeof(buf), path, prog->name);
9317 		if (err)
9318 			goto err_unpin_programs;
9319 
9320 		err = bpf_program__pin(prog, buf);
9321 		if (err)
9322 			goto err_unpin_programs;
9323 	}
9324 
9325 	return 0;
9326 
9327 err_unpin_programs:
9328 	while ((prog = bpf_object__prev_program(obj, prog))) {
9329 		if (pathname_concat(buf, sizeof(buf), path, prog->name))
9330 			continue;
9331 
9332 		bpf_program__unpin(prog, buf);
9333 	}
9334 
9335 	return libbpf_err(err);
9336 }
9337 
9338 int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
9339 {
9340 	struct bpf_program *prog;
9341 	int err;
9342 
9343 	if (!obj)
9344 		return libbpf_err(-ENOENT);
9345 
9346 	bpf_object__for_each_program(prog, obj) {
9347 		char buf[PATH_MAX];
9348 
9349 		err = pathname_concat(buf, sizeof(buf), path, prog->name);
9350 		if (err)
9351 			return libbpf_err(err);
9352 
9353 		err = bpf_program__unpin(prog, buf);
9354 		if (err)
9355 			return libbpf_err(err);
9356 	}
9357 
9358 	return 0;
9359 }
9360 
9361 int bpf_object__pin(struct bpf_object *obj, const char *path)
9362 {
9363 	int err;
9364 
9365 	err = bpf_object__pin_maps(obj, path);
9366 	if (err)
9367 		return libbpf_err(err);
9368 
9369 	err = bpf_object__pin_programs(obj, path);
9370 	if (err) {
9371 		bpf_object__unpin_maps(obj, path);
9372 		return libbpf_err(err);
9373 	}
9374 
9375 	return 0;
9376 }
9377 
9378 int bpf_object__unpin(struct bpf_object *obj, const char *path)
9379 {
9380 	int err;
9381 
9382 	err = bpf_object__unpin_programs(obj, path);
9383 	if (err)
9384 		return libbpf_err(err);
9385 
9386 	err = bpf_object__unpin_maps(obj, path);
9387 	if (err)
9388 		return libbpf_err(err);
9389 
9390 	return 0;
9391 }
9392 
9393 static void bpf_map__destroy(struct bpf_map *map)
9394 {
9395 	if (map->inner_map) {
9396 		bpf_map__destroy(map->inner_map);
9397 		zfree(&map->inner_map);
9398 	}
9399 
9400 	zfree(&map->init_slots);
9401 	map->init_slots_sz = 0;
9402 
9403 	if (map->mmaped && map->mmaped != map->obj->arena_data)
9404 		munmap(map->mmaped, bpf_map_mmap_sz(map));
9405 	map->mmaped = NULL;
9406 
9407 	if (map->st_ops) {
9408 		zfree(&map->st_ops->data);
9409 		zfree(&map->st_ops->progs);
9410 		zfree(&map->st_ops->kern_func_off);
9411 		zfree(&map->st_ops);
9412 	}
9413 
9414 	zfree(&map->name);
9415 	zfree(&map->real_name);
9416 	zfree(&map->pin_path);
9417 
9418 	if (map->fd >= 0)
9419 		zclose(map->fd);
9420 }
9421 
9422 void bpf_object__close(struct bpf_object *obj)
9423 {
9424 	size_t i;
9425 
9426 	if (IS_ERR_OR_NULL(obj))
9427 		return;
9428 
9429 	/*
9430 	 * if user called bpf_object__prepare() without ever getting to
9431 	 * bpf_object__load(), we need to clean up stuff that is normally
9432 	 * cleaned up at the end of loading step
9433 	 */
9434 	bpf_object_post_load_cleanup(obj);
9435 
9436 	usdt_manager_free(obj->usdt_man);
9437 	obj->usdt_man = NULL;
9438 
9439 	bpf_gen__free(obj->gen_loader);
9440 	bpf_object__elf_finish(obj);
9441 	bpf_object_unload(obj);
9442 	btf__free(obj->btf);
9443 	btf__free(obj->btf_vmlinux);
9444 	btf_ext__free(obj->btf_ext);
9445 
9446 	for (i = 0; i < obj->nr_maps; i++)
9447 		bpf_map__destroy(&obj->maps[i]);
9448 
9449 	zfree(&obj->btf_custom_path);
9450 	zfree(&obj->kconfig);
9451 
9452 	for (i = 0; i < obj->nr_extern; i++) {
9453 		zfree(&obj->externs[i].name);
9454 		zfree(&obj->externs[i].essent_name);
9455 	}
9456 
9457 	zfree(&obj->externs);
9458 	obj->nr_extern = 0;
9459 
9460 	zfree(&obj->maps);
9461 	obj->nr_maps = 0;
9462 
9463 	if (obj->programs && obj->nr_programs) {
9464 		for (i = 0; i < obj->nr_programs; i++)
9465 			bpf_program__exit(&obj->programs[i]);
9466 	}
9467 	zfree(&obj->programs);
9468 
9469 	zfree(&obj->feat_cache);
9470 	zfree(&obj->token_path);
9471 	if (obj->token_fd > 0)
9472 		close(obj->token_fd);
9473 
9474 	zfree(&obj->arena_data);
9475 
9476 	zfree(&obj->jumptables_data);
9477 	obj->jumptables_data_sz = 0;
9478 
9479 	for (i = 0; i < obj->jumptable_map_cnt; i++)
9480 		close(obj->jumptable_maps[i].fd);
9481 	zfree(&obj->jumptable_maps);
9482 
9483 	free(obj);
9484 }
9485 
9486 const char *bpf_object__name(const struct bpf_object *obj)
9487 {
9488 	return obj ? obj->name : libbpf_err_ptr(-EINVAL);
9489 }
9490 
9491 unsigned int bpf_object__kversion(const struct bpf_object *obj)
9492 {
9493 	return obj ? obj->kern_version : 0;
9494 }
9495 
9496 int bpf_object__token_fd(const struct bpf_object *obj)
9497 {
9498 	return obj->token_fd ?: -1;
9499 }
9500 
9501 struct btf *bpf_object__btf(const struct bpf_object *obj)
9502 {
9503 	return obj ? obj->btf : NULL;
9504 }
9505 
9506 int bpf_object__btf_fd(const struct bpf_object *obj)
9507 {
9508 	return obj->btf ? btf__fd(obj->btf) : -1;
9509 }
9510 
9511 int bpf_object__set_kversion(struct bpf_object *obj, __u32 kern_version)
9512 {
9513 	if (obj->state >= OBJ_LOADED)
9514 		return libbpf_err(-EINVAL);
9515 
9516 	obj->kern_version = kern_version;
9517 
9518 	return 0;
9519 }
9520 
9521 int bpf_object__gen_loader(struct bpf_object *obj, struct gen_loader_opts *opts)
9522 {
9523 	struct bpf_gen *gen;
9524 
9525 	if (!opts)
9526 		return libbpf_err(-EFAULT);
9527 	if (!OPTS_VALID(opts, gen_loader_opts))
9528 		return libbpf_err(-EINVAL);
9529 	gen = calloc(1, sizeof(*gen));
9530 	if (!gen)
9531 		return libbpf_err(-ENOMEM);
9532 	gen->opts = opts;
9533 	gen->swapped_endian = !is_native_endianness(obj);
9534 	obj->gen_loader = gen;
9535 	return 0;
9536 }
9537 
9538 static struct bpf_program *
9539 __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
9540 		    bool forward)
9541 {
9542 	size_t nr_programs = obj->nr_programs;
9543 	ssize_t idx;
9544 
9545 	if (!nr_programs)
9546 		return NULL;
9547 
9548 	if (!p)
9549 		/* Iter from the beginning */
9550 		return forward ? &obj->programs[0] :
9551 			&obj->programs[nr_programs - 1];
9552 
9553 	if (p->obj != obj) {
9554 		pr_warn("error: program handler doesn't match object\n");
9555 		return errno = EINVAL, NULL;
9556 	}
9557 
9558 	idx = (p - obj->programs) + (forward ? 1 : -1);
9559 	if (idx >= obj->nr_programs || idx < 0)
9560 		return NULL;
9561 	return &obj->programs[idx];
9562 }
9563 
9564 struct bpf_program *
9565 bpf_object__next_program(const struct bpf_object *obj, struct bpf_program *prev)
9566 {
9567 	struct bpf_program *prog = prev;
9568 
9569 	do {
9570 		prog = __bpf_program__iter(prog, obj, true);
9571 	} while (prog && prog_is_subprog(obj, prog));
9572 
9573 	return prog;
9574 }
9575 
9576 struct bpf_program *
9577 bpf_object__prev_program(const struct bpf_object *obj, struct bpf_program *next)
9578 {
9579 	struct bpf_program *prog = next;
9580 
9581 	do {
9582 		prog = __bpf_program__iter(prog, obj, false);
9583 	} while (prog && prog_is_subprog(obj, prog));
9584 
9585 	return prog;
9586 }
9587 
9588 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
9589 {
9590 	prog->prog_ifindex = ifindex;
9591 }
9592 
9593 const char *bpf_program__name(const struct bpf_program *prog)
9594 {
9595 	return prog->name;
9596 }
9597 
9598 const char *bpf_program__section_name(const struct bpf_program *prog)
9599 {
9600 	return prog->sec_name;
9601 }
9602 
9603 bool bpf_program__autoload(const struct bpf_program *prog)
9604 {
9605 	return prog->autoload;
9606 }
9607 
9608 int bpf_program__set_autoload(struct bpf_program *prog, bool autoload)
9609 {
9610 	if (prog->obj->state >= OBJ_LOADED)
9611 		return libbpf_err(-EINVAL);
9612 
9613 	prog->autoload = autoload;
9614 	return 0;
9615 }
9616 
9617 bool bpf_program__autoattach(const struct bpf_program *prog)
9618 {
9619 	return prog->autoattach;
9620 }
9621 
9622 void bpf_program__set_autoattach(struct bpf_program *prog, bool autoattach)
9623 {
9624 	prog->autoattach = autoattach;
9625 }
9626 
9627 const struct bpf_insn *bpf_program__insns(const struct bpf_program *prog)
9628 {
9629 	return prog->insns;
9630 }
9631 
9632 size_t bpf_program__insn_cnt(const struct bpf_program *prog)
9633 {
9634 	return prog->insns_cnt;
9635 }
9636 
9637 int bpf_program__set_insns(struct bpf_program *prog,
9638 			   struct bpf_insn *new_insns, size_t new_insn_cnt)
9639 {
9640 	struct bpf_insn *insns;
9641 
9642 	if (prog->obj->state >= OBJ_LOADED)
9643 		return libbpf_err(-EBUSY);
9644 
9645 	insns = libbpf_reallocarray(prog->insns, new_insn_cnt, sizeof(*insns));
9646 	/* NULL is a valid return from reallocarray if the new count is zero */
9647 	if (!insns && new_insn_cnt) {
9648 		pr_warn("prog '%s': failed to realloc prog code\n", prog->name);
9649 		return libbpf_err(-ENOMEM);
9650 	}
9651 	memcpy(insns, new_insns, new_insn_cnt * sizeof(*insns));
9652 
9653 	prog->insns = insns;
9654 	prog->insns_cnt = new_insn_cnt;
9655 	return 0;
9656 }
9657 
9658 int bpf_program__fd(const struct bpf_program *prog)
9659 {
9660 	if (!prog)
9661 		return libbpf_err(-EINVAL);
9662 
9663 	if (prog->fd < 0)
9664 		return libbpf_err(-ENOENT);
9665 
9666 	return prog->fd;
9667 }
9668 
9669 __alias(bpf_program__type)
9670 enum bpf_prog_type bpf_program__get_type(const struct bpf_program *prog);
9671 
9672 enum bpf_prog_type bpf_program__type(const struct bpf_program *prog)
9673 {
9674 	return prog->type;
9675 }
9676 
9677 static size_t custom_sec_def_cnt;
9678 static struct bpf_sec_def *custom_sec_defs;
9679 static struct bpf_sec_def custom_fallback_def;
9680 static bool has_custom_fallback_def;
9681 static int last_custom_sec_def_handler_id;
9682 
9683 int bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
9684 {
9685 	if (prog->obj->state >= OBJ_LOADED)
9686 		return libbpf_err(-EBUSY);
9687 
9688 	/* if type is not changed, do nothing */
9689 	if (prog->type == type)
9690 		return 0;
9691 
9692 	prog->type = type;
9693 
9694 	/* If a program type was changed, we need to reset associated SEC()
9695 	 * handler, as it will be invalid now. The only exception is a generic
9696 	 * fallback handler, which by definition is program type-agnostic and
9697 	 * is a catch-all custom handler, optionally set by the application,
9698 	 * so should be able to handle any type of BPF program.
9699 	 */
9700 	if (prog->sec_def != &custom_fallback_def)
9701 		prog->sec_def = NULL;
9702 	return 0;
9703 }
9704 
9705 __alias(bpf_program__expected_attach_type)
9706 enum bpf_attach_type bpf_program__get_expected_attach_type(const struct bpf_program *prog);
9707 
9708 enum bpf_attach_type bpf_program__expected_attach_type(const struct bpf_program *prog)
9709 {
9710 	return prog->expected_attach_type;
9711 }
9712 
9713 int bpf_program__set_expected_attach_type(struct bpf_program *prog,
9714 					   enum bpf_attach_type type)
9715 {
9716 	if (prog->obj->state >= OBJ_LOADED)
9717 		return libbpf_err(-EBUSY);
9718 
9719 	prog->expected_attach_type = type;
9720 	return 0;
9721 }
9722 
9723 __u32 bpf_program__flags(const struct bpf_program *prog)
9724 {
9725 	return prog->prog_flags;
9726 }
9727 
9728 int bpf_program__set_flags(struct bpf_program *prog, __u32 flags)
9729 {
9730 	if (prog->obj->state >= OBJ_LOADED)
9731 		return libbpf_err(-EBUSY);
9732 
9733 	prog->prog_flags = flags;
9734 	return 0;
9735 }
9736 
9737 __u32 bpf_program__log_level(const struct bpf_program *prog)
9738 {
9739 	return prog->log_level;
9740 }
9741 
9742 int bpf_program__set_log_level(struct bpf_program *prog, __u32 log_level)
9743 {
9744 	if (prog->obj->state >= OBJ_LOADED)
9745 		return libbpf_err(-EBUSY);
9746 
9747 	prog->log_level = log_level;
9748 	return 0;
9749 }
9750 
9751 const char *bpf_program__log_buf(const struct bpf_program *prog, size_t *log_size)
9752 {
9753 	*log_size = prog->log_size;
9754 	return prog->log_buf;
9755 }
9756 
9757 int bpf_program__set_log_buf(struct bpf_program *prog, char *log_buf, size_t log_size)
9758 {
9759 	if (log_size && !log_buf)
9760 		return libbpf_err(-EINVAL);
9761 	if (prog->log_size > UINT_MAX)
9762 		return libbpf_err(-EINVAL);
9763 	if (prog->obj->state >= OBJ_LOADED)
9764 		return libbpf_err(-EBUSY);
9765 
9766 	prog->log_buf = log_buf;
9767 	prog->log_size = log_size;
9768 	return 0;
9769 }
9770 
9771 struct bpf_func_info *bpf_program__func_info(const struct bpf_program *prog)
9772 {
9773 	if (prog->func_info_rec_size != sizeof(struct bpf_func_info))
9774 		return libbpf_err_ptr(-EOPNOTSUPP);
9775 	return prog->func_info;
9776 }
9777 
9778 __u32 bpf_program__func_info_cnt(const struct bpf_program *prog)
9779 {
9780 	return prog->func_info_cnt;
9781 }
9782 
9783 struct bpf_line_info *bpf_program__line_info(const struct bpf_program *prog)
9784 {
9785 	if (prog->line_info_rec_size != sizeof(struct bpf_line_info))
9786 		return libbpf_err_ptr(-EOPNOTSUPP);
9787 	return prog->line_info;
9788 }
9789 
9790 __u32 bpf_program__line_info_cnt(const struct bpf_program *prog)
9791 {
9792 	return prog->line_info_cnt;
9793 }
9794 
9795 #define SEC_DEF(sec_pfx, ptype, atype, flags, ...) {			    \
9796 	.sec = (char *)sec_pfx,						    \
9797 	.prog_type = BPF_PROG_TYPE_##ptype,				    \
9798 	.expected_attach_type = atype,					    \
9799 	.cookie = (long)(flags),					    \
9800 	.prog_prepare_load_fn = libbpf_prepare_prog_load,		    \
9801 	__VA_ARGS__							    \
9802 }
9803 
9804 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9805 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9806 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9807 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9808 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9809 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9810 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9811 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9812 static int attach_kprobe_session(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9813 static int attach_uprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9814 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9815 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9816 
9817 static const struct bpf_sec_def section_defs[] = {
9818 	SEC_DEF("socket",		SOCKET_FILTER, 0, SEC_NONE),
9819 	SEC_DEF("sk_reuseport/migrate",	SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT_OR_MIGRATE, SEC_ATTACHABLE),
9820 	SEC_DEF("sk_reuseport",		SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT, SEC_ATTACHABLE),
9821 	SEC_DEF("kprobe+",		KPROBE,	0, SEC_NONE, attach_kprobe),
9822 	SEC_DEF("uprobe+",		KPROBE,	0, SEC_NONE, attach_uprobe),
9823 	SEC_DEF("uprobe.s+",		KPROBE,	0, SEC_SLEEPABLE, attach_uprobe),
9824 	SEC_DEF("kretprobe+",		KPROBE, 0, SEC_NONE, attach_kprobe),
9825 	SEC_DEF("uretprobe+",		KPROBE, 0, SEC_NONE, attach_uprobe),
9826 	SEC_DEF("uretprobe.s+",		KPROBE, 0, SEC_SLEEPABLE, attach_uprobe),
9827 	SEC_DEF("kprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
9828 	SEC_DEF("kretprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
9829 	SEC_DEF("kprobe.session+",	KPROBE,	BPF_TRACE_KPROBE_SESSION, SEC_NONE, attach_kprobe_session),
9830 	SEC_DEF("uprobe.multi+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_NONE, attach_uprobe_multi),
9831 	SEC_DEF("uretprobe.multi+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_NONE, attach_uprobe_multi),
9832 	SEC_DEF("uprobe.session+",	KPROBE,	BPF_TRACE_UPROBE_SESSION, SEC_NONE, attach_uprobe_multi),
9833 	SEC_DEF("uprobe.multi.s+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_SLEEPABLE, attach_uprobe_multi),
9834 	SEC_DEF("uretprobe.multi.s+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_SLEEPABLE, attach_uprobe_multi),
9835 	SEC_DEF("uprobe.session.s+",	KPROBE,	BPF_TRACE_UPROBE_SESSION, SEC_SLEEPABLE, attach_uprobe_multi),
9836 	SEC_DEF("ksyscall+",		KPROBE,	0, SEC_NONE, attach_ksyscall),
9837 	SEC_DEF("kretsyscall+",		KPROBE, 0, SEC_NONE, attach_ksyscall),
9838 	SEC_DEF("usdt+",		KPROBE,	0, SEC_USDT, attach_usdt),
9839 	SEC_DEF("usdt.s+",		KPROBE,	0, SEC_USDT | SEC_SLEEPABLE, attach_usdt),
9840 	SEC_DEF("tc/ingress",		SCHED_CLS, BPF_TCX_INGRESS, SEC_NONE), /* alias for tcx */
9841 	SEC_DEF("tc/egress",		SCHED_CLS, BPF_TCX_EGRESS, SEC_NONE),  /* alias for tcx */
9842 	SEC_DEF("tcx/ingress",		SCHED_CLS, BPF_TCX_INGRESS, SEC_NONE),
9843 	SEC_DEF("tcx/egress",		SCHED_CLS, BPF_TCX_EGRESS, SEC_NONE),
9844 	SEC_DEF("tc",			SCHED_CLS, 0, SEC_NONE), /* deprecated / legacy, use tcx */
9845 	SEC_DEF("classifier",		SCHED_CLS, 0, SEC_NONE), /* deprecated / legacy, use tcx */
9846 	SEC_DEF("action",		SCHED_ACT, 0, SEC_NONE), /* deprecated / legacy, use tcx */
9847 	SEC_DEF("netkit/primary",	SCHED_CLS, BPF_NETKIT_PRIMARY, SEC_NONE),
9848 	SEC_DEF("netkit/peer",		SCHED_CLS, BPF_NETKIT_PEER, SEC_NONE),
9849 	SEC_DEF("tracepoint+",		TRACEPOINT, 0, SEC_NONE, attach_tp),
9850 	SEC_DEF("tp+",			TRACEPOINT, 0, SEC_NONE, attach_tp),
9851 	SEC_DEF("raw_tracepoint+",	RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
9852 	SEC_DEF("raw_tp+",		RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
9853 	SEC_DEF("raw_tracepoint.w+",	RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
9854 	SEC_DEF("raw_tp.w+",		RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
9855 	SEC_DEF("tp_btf+",		TRACING, BPF_TRACE_RAW_TP, SEC_ATTACH_BTF, attach_trace),
9856 	SEC_DEF("fentry+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF, attach_trace),
9857 	SEC_DEF("fmod_ret+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF, attach_trace),
9858 	SEC_DEF("fexit+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF, attach_trace),
9859 	SEC_DEF("fentry.s+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
9860 	SEC_DEF("fmod_ret.s+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
9861 	SEC_DEF("fexit.s+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
9862 	SEC_DEF("freplace+",		EXT, 0, SEC_ATTACH_BTF, attach_trace),
9863 	SEC_DEF("lsm+",			LSM, BPF_LSM_MAC, SEC_ATTACH_BTF, attach_lsm),
9864 	SEC_DEF("lsm.s+",		LSM, BPF_LSM_MAC, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_lsm),
9865 	SEC_DEF("lsm_cgroup+",		LSM, BPF_LSM_CGROUP, SEC_ATTACH_BTF),
9866 	SEC_DEF("iter+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF, attach_iter),
9867 	SEC_DEF("iter.s+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_iter),
9868 	SEC_DEF("syscall",		SYSCALL, 0, SEC_SLEEPABLE),
9869 	SEC_DEF("xdp.frags/devmap",	XDP, BPF_XDP_DEVMAP, SEC_XDP_FRAGS),
9870 	SEC_DEF("xdp/devmap",		XDP, BPF_XDP_DEVMAP, SEC_ATTACHABLE),
9871 	SEC_DEF("xdp.frags/cpumap",	XDP, BPF_XDP_CPUMAP, SEC_XDP_FRAGS),
9872 	SEC_DEF("xdp/cpumap",		XDP, BPF_XDP_CPUMAP, SEC_ATTACHABLE),
9873 	SEC_DEF("xdp.frags",		XDP, BPF_XDP, SEC_XDP_FRAGS),
9874 	SEC_DEF("xdp",			XDP, BPF_XDP, SEC_ATTACHABLE_OPT),
9875 	SEC_DEF("perf_event",		PERF_EVENT, 0, SEC_NONE),
9876 	SEC_DEF("lwt_in",		LWT_IN, 0, SEC_NONE),
9877 	SEC_DEF("lwt_out",		LWT_OUT, 0, SEC_NONE),
9878 	SEC_DEF("lwt_xmit",		LWT_XMIT, 0, SEC_NONE),
9879 	SEC_DEF("lwt_seg6local",	LWT_SEG6LOCAL, 0, SEC_NONE),
9880 	SEC_DEF("sockops",		SOCK_OPS, BPF_CGROUP_SOCK_OPS, SEC_ATTACHABLE_OPT),
9881 	SEC_DEF("sk_skb/stream_parser",	SK_SKB, BPF_SK_SKB_STREAM_PARSER, SEC_ATTACHABLE_OPT),
9882 	SEC_DEF("sk_skb/stream_verdict",SK_SKB, BPF_SK_SKB_STREAM_VERDICT, SEC_ATTACHABLE_OPT),
9883 	SEC_DEF("sk_skb/verdict",	SK_SKB, BPF_SK_SKB_VERDICT, SEC_ATTACHABLE_OPT),
9884 	SEC_DEF("sk_skb",		SK_SKB, 0, SEC_NONE),
9885 	SEC_DEF("sk_msg",		SK_MSG, BPF_SK_MSG_VERDICT, SEC_ATTACHABLE_OPT),
9886 	SEC_DEF("lirc_mode2",		LIRC_MODE2, BPF_LIRC_MODE2, SEC_ATTACHABLE_OPT),
9887 	SEC_DEF("flow_dissector",	FLOW_DISSECTOR, BPF_FLOW_DISSECTOR, SEC_ATTACHABLE_OPT),
9888 	SEC_DEF("cgroup_skb/ingress",	CGROUP_SKB, BPF_CGROUP_INET_INGRESS, SEC_ATTACHABLE_OPT),
9889 	SEC_DEF("cgroup_skb/egress",	CGROUP_SKB, BPF_CGROUP_INET_EGRESS, SEC_ATTACHABLE_OPT),
9890 	SEC_DEF("cgroup/skb",		CGROUP_SKB, 0, SEC_NONE),
9891 	SEC_DEF("cgroup/sock_create",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE),
9892 	SEC_DEF("cgroup/sock_release",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_RELEASE, SEC_ATTACHABLE),
9893 	SEC_DEF("cgroup/sock",		CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE_OPT),
9894 	SEC_DEF("cgroup/post_bind4",	CGROUP_SOCK, BPF_CGROUP_INET4_POST_BIND, SEC_ATTACHABLE),
9895 	SEC_DEF("cgroup/post_bind6",	CGROUP_SOCK, BPF_CGROUP_INET6_POST_BIND, SEC_ATTACHABLE),
9896 	SEC_DEF("cgroup/bind4",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND, SEC_ATTACHABLE),
9897 	SEC_DEF("cgroup/bind6",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND, SEC_ATTACHABLE),
9898 	SEC_DEF("cgroup/connect4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT, SEC_ATTACHABLE),
9899 	SEC_DEF("cgroup/connect6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT, SEC_ATTACHABLE),
9900 	SEC_DEF("cgroup/connect_unix",	CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_CONNECT, SEC_ATTACHABLE),
9901 	SEC_DEF("cgroup/sendmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG, SEC_ATTACHABLE),
9902 	SEC_DEF("cgroup/sendmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG, SEC_ATTACHABLE),
9903 	SEC_DEF("cgroup/sendmsg_unix",	CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_SENDMSG, SEC_ATTACHABLE),
9904 	SEC_DEF("cgroup/recvmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_RECVMSG, SEC_ATTACHABLE),
9905 	SEC_DEF("cgroup/recvmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_RECVMSG, SEC_ATTACHABLE),
9906 	SEC_DEF("cgroup/recvmsg_unix",	CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_RECVMSG, SEC_ATTACHABLE),
9907 	SEC_DEF("cgroup/getpeername4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETPEERNAME, SEC_ATTACHABLE),
9908 	SEC_DEF("cgroup/getpeername6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETPEERNAME, SEC_ATTACHABLE),
9909 	SEC_DEF("cgroup/getpeername_unix", CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_GETPEERNAME, SEC_ATTACHABLE),
9910 	SEC_DEF("cgroup/getsockname4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETSOCKNAME, SEC_ATTACHABLE),
9911 	SEC_DEF("cgroup/getsockname6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETSOCKNAME, SEC_ATTACHABLE),
9912 	SEC_DEF("cgroup/getsockname_unix", CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_GETSOCKNAME, SEC_ATTACHABLE),
9913 	SEC_DEF("cgroup/sysctl",	CGROUP_SYSCTL, BPF_CGROUP_SYSCTL, SEC_ATTACHABLE),
9914 	SEC_DEF("cgroup/getsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_GETSOCKOPT, SEC_ATTACHABLE),
9915 	SEC_DEF("cgroup/setsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_SETSOCKOPT, SEC_ATTACHABLE),
9916 	SEC_DEF("cgroup/dev",		CGROUP_DEVICE, BPF_CGROUP_DEVICE, SEC_ATTACHABLE_OPT),
9917 	SEC_DEF("struct_ops+",		STRUCT_OPS, 0, SEC_NONE),
9918 	SEC_DEF("struct_ops.s+",	STRUCT_OPS, 0, SEC_SLEEPABLE),
9919 	SEC_DEF("sk_lookup",		SK_LOOKUP, BPF_SK_LOOKUP, SEC_ATTACHABLE),
9920 	SEC_DEF("netfilter",		NETFILTER, BPF_NETFILTER, SEC_NONE),
9921 };
9922 
9923 int libbpf_register_prog_handler(const char *sec,
9924 				 enum bpf_prog_type prog_type,
9925 				 enum bpf_attach_type exp_attach_type,
9926 				 const struct libbpf_prog_handler_opts *opts)
9927 {
9928 	struct bpf_sec_def *sec_def;
9929 
9930 	if (!OPTS_VALID(opts, libbpf_prog_handler_opts))
9931 		return libbpf_err(-EINVAL);
9932 
9933 	if (last_custom_sec_def_handler_id == INT_MAX) /* prevent overflow */
9934 		return libbpf_err(-E2BIG);
9935 
9936 	if (sec) {
9937 		sec_def = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt + 1,
9938 					      sizeof(*sec_def));
9939 		if (!sec_def)
9940 			return libbpf_err(-ENOMEM);
9941 
9942 		custom_sec_defs = sec_def;
9943 		sec_def = &custom_sec_defs[custom_sec_def_cnt];
9944 	} else {
9945 		if (has_custom_fallback_def)
9946 			return libbpf_err(-EBUSY);
9947 
9948 		sec_def = &custom_fallback_def;
9949 	}
9950 
9951 	sec_def->sec = sec ? strdup(sec) : NULL;
9952 	if (sec && !sec_def->sec)
9953 		return libbpf_err(-ENOMEM);
9954 
9955 	sec_def->prog_type = prog_type;
9956 	sec_def->expected_attach_type = exp_attach_type;
9957 	sec_def->cookie = OPTS_GET(opts, cookie, 0);
9958 
9959 	sec_def->prog_setup_fn = OPTS_GET(opts, prog_setup_fn, NULL);
9960 	sec_def->prog_prepare_load_fn = OPTS_GET(opts, prog_prepare_load_fn, NULL);
9961 	sec_def->prog_attach_fn = OPTS_GET(opts, prog_attach_fn, NULL);
9962 
9963 	sec_def->handler_id = ++last_custom_sec_def_handler_id;
9964 
9965 	if (sec)
9966 		custom_sec_def_cnt++;
9967 	else
9968 		has_custom_fallback_def = true;
9969 
9970 	return sec_def->handler_id;
9971 }
9972 
9973 int libbpf_unregister_prog_handler(int handler_id)
9974 {
9975 	struct bpf_sec_def *sec_defs;
9976 	int i;
9977 
9978 	if (handler_id <= 0)
9979 		return libbpf_err(-EINVAL);
9980 
9981 	if (has_custom_fallback_def && custom_fallback_def.handler_id == handler_id) {
9982 		memset(&custom_fallback_def, 0, sizeof(custom_fallback_def));
9983 		has_custom_fallback_def = false;
9984 		return 0;
9985 	}
9986 
9987 	for (i = 0; i < custom_sec_def_cnt; i++) {
9988 		if (custom_sec_defs[i].handler_id == handler_id)
9989 			break;
9990 	}
9991 
9992 	if (i == custom_sec_def_cnt)
9993 		return libbpf_err(-ENOENT);
9994 
9995 	free(custom_sec_defs[i].sec);
9996 	for (i = i + 1; i < custom_sec_def_cnt; i++)
9997 		custom_sec_defs[i - 1] = custom_sec_defs[i];
9998 	custom_sec_def_cnt--;
9999 
10000 	/* try to shrink the array, but it's ok if we couldn't */
10001 	sec_defs = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt, sizeof(*sec_defs));
10002 	/* if new count is zero, reallocarray can return a valid NULL result;
10003 	 * in this case the previous pointer will be freed, so we *have to*
10004 	 * reassign old pointer to the new value (even if it's NULL)
10005 	 */
10006 	if (sec_defs || custom_sec_def_cnt == 0)
10007 		custom_sec_defs = sec_defs;
10008 
10009 	return 0;
10010 }
10011 
10012 static bool sec_def_matches(const struct bpf_sec_def *sec_def, const char *sec_name)
10013 {
10014 	size_t len = strlen(sec_def->sec);
10015 
10016 	/* "type/" always has to have proper SEC("type/extras") form */
10017 	if (sec_def->sec[len - 1] == '/') {
10018 		if (str_has_pfx(sec_name, sec_def->sec))
10019 			return true;
10020 		return false;
10021 	}
10022 
10023 	/* "type+" means it can be either exact SEC("type") or
10024 	 * well-formed SEC("type/extras") with proper '/' separator
10025 	 */
10026 	if (sec_def->sec[len - 1] == '+') {
10027 		len--;
10028 		/* not even a prefix */
10029 		if (strncmp(sec_name, sec_def->sec, len) != 0)
10030 			return false;
10031 		/* exact match or has '/' separator */
10032 		if (sec_name[len] == '\0' || sec_name[len] == '/')
10033 			return true;
10034 		return false;
10035 	}
10036 
10037 	return strcmp(sec_name, sec_def->sec) == 0;
10038 }
10039 
10040 static const struct bpf_sec_def *find_sec_def(const char *sec_name)
10041 {
10042 	const struct bpf_sec_def *sec_def;
10043 	int i, n;
10044 
10045 	n = custom_sec_def_cnt;
10046 	for (i = 0; i < n; i++) {
10047 		sec_def = &custom_sec_defs[i];
10048 		if (sec_def_matches(sec_def, sec_name))
10049 			return sec_def;
10050 	}
10051 
10052 	n = ARRAY_SIZE(section_defs);
10053 	for (i = 0; i < n; i++) {
10054 		sec_def = &section_defs[i];
10055 		if (sec_def_matches(sec_def, sec_name))
10056 			return sec_def;
10057 	}
10058 
10059 	if (has_custom_fallback_def)
10060 		return &custom_fallback_def;
10061 
10062 	return NULL;
10063 }
10064 
10065 #define MAX_TYPE_NAME_SIZE 32
10066 
10067 static char *libbpf_get_type_names(bool attach_type)
10068 {
10069 	int i, len = ARRAY_SIZE(section_defs) * MAX_TYPE_NAME_SIZE;
10070 	char *buf;
10071 
10072 	buf = malloc(len);
10073 	if (!buf)
10074 		return NULL;
10075 
10076 	buf[0] = '\0';
10077 	/* Forge string buf with all available names */
10078 	for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
10079 		const struct bpf_sec_def *sec_def = &section_defs[i];
10080 
10081 		if (attach_type) {
10082 			if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
10083 				continue;
10084 
10085 			if (!(sec_def->cookie & SEC_ATTACHABLE))
10086 				continue;
10087 		}
10088 
10089 		if (strlen(buf) + strlen(section_defs[i].sec) + 2 > len) {
10090 			free(buf);
10091 			return NULL;
10092 		}
10093 		strcat(buf, " ");
10094 		strcat(buf, section_defs[i].sec);
10095 	}
10096 
10097 	return buf;
10098 }
10099 
10100 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
10101 			     enum bpf_attach_type *expected_attach_type)
10102 {
10103 	const struct bpf_sec_def *sec_def;
10104 	char *type_names;
10105 
10106 	if (!name)
10107 		return libbpf_err(-EINVAL);
10108 
10109 	sec_def = find_sec_def(name);
10110 	if (sec_def) {
10111 		*prog_type = sec_def->prog_type;
10112 		*expected_attach_type = sec_def->expected_attach_type;
10113 		return 0;
10114 	}
10115 
10116 	pr_debug("failed to guess program type from ELF section '%s'\n", name);
10117 	type_names = libbpf_get_type_names(false);
10118 	if (type_names != NULL) {
10119 		pr_debug("supported section(type) names are:%s\n", type_names);
10120 		free(type_names);
10121 	}
10122 
10123 	return libbpf_err(-ESRCH);
10124 }
10125 
10126 const char *libbpf_bpf_attach_type_str(enum bpf_attach_type t)
10127 {
10128 	if (t < 0 || t >= ARRAY_SIZE(attach_type_name))
10129 		return NULL;
10130 
10131 	return attach_type_name[t];
10132 }
10133 
10134 const char *libbpf_bpf_link_type_str(enum bpf_link_type t)
10135 {
10136 	if (t < 0 || t >= ARRAY_SIZE(link_type_name))
10137 		return NULL;
10138 
10139 	return link_type_name[t];
10140 }
10141 
10142 const char *libbpf_bpf_map_type_str(enum bpf_map_type t)
10143 {
10144 	if (t < 0 || t >= ARRAY_SIZE(map_type_name))
10145 		return NULL;
10146 
10147 	return map_type_name[t];
10148 }
10149 
10150 const char *libbpf_bpf_prog_type_str(enum bpf_prog_type t)
10151 {
10152 	if (t < 0 || t >= ARRAY_SIZE(prog_type_name))
10153 		return NULL;
10154 
10155 	return prog_type_name[t];
10156 }
10157 
10158 static struct bpf_map *find_struct_ops_map_by_offset(struct bpf_object *obj,
10159 						     int sec_idx,
10160 						     size_t offset)
10161 {
10162 	struct bpf_map *map;
10163 	size_t i;
10164 
10165 	for (i = 0; i < obj->nr_maps; i++) {
10166 		map = &obj->maps[i];
10167 		if (!bpf_map__is_struct_ops(map))
10168 			continue;
10169 		if (map->sec_idx == sec_idx &&
10170 		    map->sec_offset <= offset &&
10171 		    offset - map->sec_offset < map->def.value_size)
10172 			return map;
10173 	}
10174 
10175 	return NULL;
10176 }
10177 
10178 /* Collect the reloc from ELF, populate the st_ops->progs[], and update
10179  * st_ops->data for shadow type.
10180  */
10181 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
10182 					    Elf64_Shdr *shdr, Elf_Data *data)
10183 {
10184 	const struct btf_type *type;
10185 	const struct btf_member *member;
10186 	struct bpf_struct_ops *st_ops;
10187 	struct bpf_program *prog;
10188 	unsigned int shdr_idx;
10189 	const struct btf *btf;
10190 	struct bpf_map *map;
10191 	unsigned int moff, insn_idx;
10192 	const char *name;
10193 	__u32 member_idx;
10194 	Elf64_Sym *sym;
10195 	Elf64_Rel *rel;
10196 	int i, nrels;
10197 
10198 	btf = obj->btf;
10199 	nrels = shdr->sh_size / shdr->sh_entsize;
10200 	for (i = 0; i < nrels; i++) {
10201 		rel = elf_rel_by_idx(data, i);
10202 		if (!rel) {
10203 			pr_warn("struct_ops reloc: failed to get %d reloc\n", i);
10204 			return -LIBBPF_ERRNO__FORMAT;
10205 		}
10206 
10207 		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
10208 		if (!sym) {
10209 			pr_warn("struct_ops reloc: symbol %zx not found\n",
10210 				(size_t)ELF64_R_SYM(rel->r_info));
10211 			return -LIBBPF_ERRNO__FORMAT;
10212 		}
10213 
10214 		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
10215 		map = find_struct_ops_map_by_offset(obj, shdr->sh_info, rel->r_offset);
10216 		if (!map) {
10217 			pr_warn("struct_ops reloc: cannot find map at rel->r_offset %zu\n",
10218 				(size_t)rel->r_offset);
10219 			return -EINVAL;
10220 		}
10221 
10222 		moff = rel->r_offset - map->sec_offset;
10223 		shdr_idx = sym->st_shndx;
10224 		st_ops = map->st_ops;
10225 		pr_debug("struct_ops reloc %s: for %lld value %lld shdr_idx %u rel->r_offset %zu map->sec_offset %zu name %d (\'%s\')\n",
10226 			 map->name,
10227 			 (long long)(rel->r_info >> 32),
10228 			 (long long)sym->st_value,
10229 			 shdr_idx, (size_t)rel->r_offset,
10230 			 map->sec_offset, sym->st_name, name);
10231 
10232 		if (shdr_idx >= SHN_LORESERVE) {
10233 			pr_warn("struct_ops reloc %s: rel->r_offset %zu shdr_idx %u unsupported non-static function\n",
10234 				map->name, (size_t)rel->r_offset, shdr_idx);
10235 			return -LIBBPF_ERRNO__RELOC;
10236 		}
10237 		if (sym->st_value % BPF_INSN_SZ) {
10238 			pr_warn("struct_ops reloc %s: invalid target program offset %llu\n",
10239 				map->name, (unsigned long long)sym->st_value);
10240 			return -LIBBPF_ERRNO__FORMAT;
10241 		}
10242 		insn_idx = sym->st_value / BPF_INSN_SZ;
10243 
10244 		type = btf__type_by_id(btf, st_ops->type_id);
10245 		member = find_member_by_offset(type, moff * 8);
10246 		if (!member) {
10247 			pr_warn("struct_ops reloc %s: cannot find member at moff %u\n",
10248 				map->name, moff);
10249 			return -EINVAL;
10250 		}
10251 		member_idx = member - btf_members(type);
10252 		name = btf__name_by_offset(btf, member->name_off);
10253 
10254 		if (!resolve_func_ptr(btf, member->type, NULL)) {
10255 			pr_warn("struct_ops reloc %s: cannot relocate non func ptr %s\n",
10256 				map->name, name);
10257 			return -EINVAL;
10258 		}
10259 
10260 		prog = find_prog_by_sec_insn(obj, shdr_idx, insn_idx);
10261 		if (!prog) {
10262 			pr_warn("struct_ops reloc %s: cannot find prog at shdr_idx %u to relocate func ptr %s\n",
10263 				map->name, shdr_idx, name);
10264 			return -EINVAL;
10265 		}
10266 
10267 		/* prevent the use of BPF prog with invalid type */
10268 		if (prog->type != BPF_PROG_TYPE_STRUCT_OPS) {
10269 			pr_warn("struct_ops reloc %s: prog %s is not struct_ops BPF program\n",
10270 				map->name, prog->name);
10271 			return -EINVAL;
10272 		}
10273 
10274 		st_ops->progs[member_idx] = prog;
10275 
10276 		/* st_ops->data will be exposed to users, being returned by
10277 		 * bpf_map__initial_value() as a pointer to the shadow
10278 		 * type. All function pointers in the original struct type
10279 		 * should be converted to a pointer to struct bpf_program
10280 		 * in the shadow type.
10281 		 */
10282 		*((struct bpf_program **)(st_ops->data + moff)) = prog;
10283 	}
10284 
10285 	return 0;
10286 }
10287 
10288 #define BTF_TRACE_PREFIX "btf_trace_"
10289 #define BTF_LSM_PREFIX "bpf_lsm_"
10290 #define BTF_ITER_PREFIX "bpf_iter_"
10291 #define BTF_MAX_NAME_SIZE 128
10292 
10293 void btf_get_kernel_prefix_kind(enum bpf_attach_type attach_type,
10294 				const char **prefix, int *kind)
10295 {
10296 	switch (attach_type) {
10297 	case BPF_TRACE_RAW_TP:
10298 		*prefix = BTF_TRACE_PREFIX;
10299 		*kind = BTF_KIND_TYPEDEF;
10300 		break;
10301 	case BPF_LSM_MAC:
10302 	case BPF_LSM_CGROUP:
10303 		*prefix = BTF_LSM_PREFIX;
10304 		*kind = BTF_KIND_FUNC;
10305 		break;
10306 	case BPF_TRACE_ITER:
10307 		*prefix = BTF_ITER_PREFIX;
10308 		*kind = BTF_KIND_FUNC;
10309 		break;
10310 	default:
10311 		*prefix = "";
10312 		*kind = BTF_KIND_FUNC;
10313 	}
10314 }
10315 
10316 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
10317 				   const char *name, __u32 kind)
10318 {
10319 	char btf_type_name[BTF_MAX_NAME_SIZE];
10320 	int ret;
10321 
10322 	ret = snprintf(btf_type_name, sizeof(btf_type_name),
10323 		       "%s%s", prefix, name);
10324 	/* snprintf returns the number of characters written excluding the
10325 	 * terminating null. So, if >= BTF_MAX_NAME_SIZE are written, it
10326 	 * indicates truncation.
10327 	 */
10328 	if (ret < 0 || ret >= sizeof(btf_type_name))
10329 		return -ENAMETOOLONG;
10330 	return btf__find_by_name_kind(btf, btf_type_name, kind);
10331 }
10332 
10333 static inline int find_attach_btf_id(struct btf *btf, const char *name,
10334 				     enum bpf_attach_type attach_type)
10335 {
10336 	const char *prefix;
10337 	int kind;
10338 
10339 	btf_get_kernel_prefix_kind(attach_type, &prefix, &kind);
10340 	return find_btf_by_prefix_kind(btf, prefix, name, kind);
10341 }
10342 
10343 int libbpf_find_vmlinux_btf_id(const char *name,
10344 			       enum bpf_attach_type attach_type)
10345 {
10346 	struct btf *btf;
10347 	int err;
10348 
10349 	btf = btf__load_vmlinux_btf();
10350 	err = libbpf_get_error(btf);
10351 	if (err) {
10352 		pr_warn("vmlinux BTF is not found\n");
10353 		return libbpf_err(err);
10354 	}
10355 
10356 	err = find_attach_btf_id(btf, name, attach_type);
10357 	if (err <= 0)
10358 		pr_warn("%s is not found in vmlinux BTF\n", name);
10359 
10360 	btf__free(btf);
10361 	return libbpf_err(err);
10362 }
10363 
10364 static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd, int token_fd)
10365 {
10366 	struct bpf_prog_info info;
10367 	__u32 info_len = sizeof(info);
10368 	struct btf *btf;
10369 	int err;
10370 
10371 	memset(&info, 0, info_len);
10372 	err = bpf_prog_get_info_by_fd(attach_prog_fd, &info, &info_len);
10373 	if (err) {
10374 		pr_warn("failed bpf_prog_get_info_by_fd for FD %d: %s\n",
10375 			attach_prog_fd, errstr(err));
10376 		return err;
10377 	}
10378 
10379 	err = -EINVAL;
10380 	if (!info.btf_id) {
10381 		pr_warn("The target program doesn't have BTF\n");
10382 		goto out;
10383 	}
10384 	btf = btf_load_from_kernel(info.btf_id, NULL, token_fd);
10385 	err = libbpf_get_error(btf);
10386 	if (err) {
10387 		pr_warn("Failed to get BTF %d of the program: %s\n", info.btf_id, errstr(err));
10388 		goto out;
10389 	}
10390 	err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
10391 	btf__free(btf);
10392 	if (err <= 0) {
10393 		pr_warn("%s is not found in prog's BTF\n", name);
10394 		goto out;
10395 	}
10396 out:
10397 	return err;
10398 }
10399 
10400 static int find_kernel_btf_id(struct bpf_object *obj, const char *attach_name,
10401 			      enum bpf_attach_type attach_type,
10402 			      int *btf_obj_fd, int *btf_type_id)
10403 {
10404 	int ret, i, mod_len = 0;
10405 	const char *fn_name, *mod_name = NULL;
10406 
10407 	fn_name = strchr(attach_name, ':');
10408 	if (fn_name) {
10409 		mod_name = attach_name;
10410 		mod_len = fn_name - mod_name;
10411 		fn_name++;
10412 	}
10413 
10414 	if (!mod_name || strncmp(mod_name, "vmlinux", mod_len) == 0) {
10415 		ret = find_attach_btf_id(obj->btf_vmlinux,
10416 					 mod_name ? fn_name : attach_name,
10417 					 attach_type);
10418 		if (ret > 0) {
10419 			*btf_obj_fd = 0; /* vmlinux BTF */
10420 			*btf_type_id = ret;
10421 			return 0;
10422 		}
10423 		if (ret != -ENOENT)
10424 			return ret;
10425 	}
10426 
10427 	ret = load_module_btfs(obj);
10428 	if (ret)
10429 		return ret;
10430 
10431 	for (i = 0; i < obj->btf_module_cnt; i++) {
10432 		const struct module_btf *mod = &obj->btf_modules[i];
10433 
10434 		if (mod_name && strncmp(mod->name, mod_name, mod_len) != 0)
10435 			continue;
10436 
10437 		ret = find_attach_btf_id(mod->btf,
10438 					 mod_name ? fn_name : attach_name,
10439 					 attach_type);
10440 		if (ret > 0) {
10441 			*btf_obj_fd = mod->fd;
10442 			*btf_type_id = ret;
10443 			return 0;
10444 		}
10445 		if (ret == -ENOENT)
10446 			continue;
10447 
10448 		return ret;
10449 	}
10450 
10451 	return -ESRCH;
10452 }
10453 
10454 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
10455 				     int *btf_obj_fd, int *btf_type_id)
10456 {
10457 	enum bpf_attach_type attach_type = prog->expected_attach_type;
10458 	__u32 attach_prog_fd = prog->attach_prog_fd;
10459 	int err = 0;
10460 
10461 	/* BPF program's BTF ID */
10462 	if (prog->type == BPF_PROG_TYPE_EXT || attach_prog_fd) {
10463 		if (!attach_prog_fd) {
10464 			pr_warn("prog '%s': attach program FD is not set\n", prog->name);
10465 			return -EINVAL;
10466 		}
10467 		err = libbpf_find_prog_btf_id(attach_name, attach_prog_fd, prog->obj->token_fd);
10468 		if (err < 0) {
10469 			pr_warn("prog '%s': failed to find BPF program (FD %d) BTF ID for '%s': %s\n",
10470 				prog->name, attach_prog_fd, attach_name, errstr(err));
10471 			return err;
10472 		}
10473 		*btf_obj_fd = 0;
10474 		*btf_type_id = err;
10475 		return 0;
10476 	}
10477 
10478 	/* kernel/module BTF ID */
10479 	if (prog->obj->gen_loader) {
10480 		bpf_gen__record_attach_target(prog->obj->gen_loader, attach_name, attach_type);
10481 		*btf_obj_fd = 0;
10482 		*btf_type_id = 1;
10483 	} else {
10484 		err = find_kernel_btf_id(prog->obj, attach_name,
10485 					 attach_type, btf_obj_fd,
10486 					 btf_type_id);
10487 	}
10488 	if (err) {
10489 		pr_warn("prog '%s': failed to find kernel BTF type ID of '%s': %s\n",
10490 			prog->name, attach_name, errstr(err));
10491 		return err;
10492 	}
10493 	return 0;
10494 }
10495 
10496 int libbpf_attach_type_by_name(const char *name,
10497 			       enum bpf_attach_type *attach_type)
10498 {
10499 	char *type_names;
10500 	const struct bpf_sec_def *sec_def;
10501 
10502 	if (!name)
10503 		return libbpf_err(-EINVAL);
10504 
10505 	sec_def = find_sec_def(name);
10506 	if (!sec_def) {
10507 		pr_debug("failed to guess attach type based on ELF section name '%s'\n", name);
10508 		type_names = libbpf_get_type_names(true);
10509 		if (type_names != NULL) {
10510 			pr_debug("attachable section(type) names are:%s\n", type_names);
10511 			free(type_names);
10512 		}
10513 
10514 		return libbpf_err(-EINVAL);
10515 	}
10516 
10517 	if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
10518 		return libbpf_err(-EINVAL);
10519 	if (!(sec_def->cookie & SEC_ATTACHABLE))
10520 		return libbpf_err(-EINVAL);
10521 
10522 	*attach_type = sec_def->expected_attach_type;
10523 	return 0;
10524 }
10525 
10526 int bpf_map__fd(const struct bpf_map *map)
10527 {
10528 	if (!map)
10529 		return libbpf_err(-EINVAL);
10530 	if (!map_is_created(map))
10531 		return -1;
10532 	return map->fd;
10533 }
10534 
10535 static bool map_uses_real_name(const struct bpf_map *map)
10536 {
10537 	/* Since libbpf started to support custom .data.* and .rodata.* maps,
10538 	 * their user-visible name differs from kernel-visible name. Users see
10539 	 * such map's corresponding ELF section name as a map name.
10540 	 * This check distinguishes .data/.rodata from .data.* and .rodata.*
10541 	 * maps to know which name has to be returned to the user.
10542 	 */
10543 	if (map->libbpf_type == LIBBPF_MAP_DATA && strcmp(map->real_name, DATA_SEC) != 0)
10544 		return true;
10545 	if (map->libbpf_type == LIBBPF_MAP_RODATA && strcmp(map->real_name, RODATA_SEC) != 0)
10546 		return true;
10547 	return false;
10548 }
10549 
10550 const char *bpf_map__name(const struct bpf_map *map)
10551 {
10552 	if (!map)
10553 		return NULL;
10554 
10555 	if (map_uses_real_name(map))
10556 		return map->real_name;
10557 
10558 	return map->name;
10559 }
10560 
10561 enum bpf_map_type bpf_map__type(const struct bpf_map *map)
10562 {
10563 	return map->def.type;
10564 }
10565 
10566 int bpf_map__set_type(struct bpf_map *map, enum bpf_map_type type)
10567 {
10568 	if (map_is_created(map))
10569 		return libbpf_err(-EBUSY);
10570 	map->def.type = type;
10571 	return 0;
10572 }
10573 
10574 __u32 bpf_map__map_flags(const struct bpf_map *map)
10575 {
10576 	return map->def.map_flags;
10577 }
10578 
10579 int bpf_map__set_map_flags(struct bpf_map *map, __u32 flags)
10580 {
10581 	if (map_is_created(map))
10582 		return libbpf_err(-EBUSY);
10583 	map->def.map_flags = flags;
10584 	return 0;
10585 }
10586 
10587 __u64 bpf_map__map_extra(const struct bpf_map *map)
10588 {
10589 	return map->map_extra;
10590 }
10591 
10592 int bpf_map__set_map_extra(struct bpf_map *map, __u64 map_extra)
10593 {
10594 	if (map_is_created(map))
10595 		return libbpf_err(-EBUSY);
10596 	map->map_extra = map_extra;
10597 	return 0;
10598 }
10599 
10600 __u32 bpf_map__numa_node(const struct bpf_map *map)
10601 {
10602 	return map->numa_node;
10603 }
10604 
10605 int bpf_map__set_numa_node(struct bpf_map *map, __u32 numa_node)
10606 {
10607 	if (map_is_created(map))
10608 		return libbpf_err(-EBUSY);
10609 	map->numa_node = numa_node;
10610 	return 0;
10611 }
10612 
10613 __u32 bpf_map__key_size(const struct bpf_map *map)
10614 {
10615 	return map->def.key_size;
10616 }
10617 
10618 int bpf_map__set_key_size(struct bpf_map *map, __u32 size)
10619 {
10620 	if (map_is_created(map))
10621 		return libbpf_err(-EBUSY);
10622 	map->def.key_size = size;
10623 	return 0;
10624 }
10625 
10626 __u32 bpf_map__value_size(const struct bpf_map *map)
10627 {
10628 	return map->def.value_size;
10629 }
10630 
10631 static int map_btf_datasec_resize(struct bpf_map *map, __u32 size)
10632 {
10633 	struct btf *btf;
10634 	struct btf_type *datasec_type, *var_type;
10635 	struct btf_var_secinfo *var;
10636 	const struct btf_type *array_type;
10637 	const struct btf_array *array;
10638 	int vlen, element_sz, new_array_id;
10639 	__u32 nr_elements;
10640 
10641 	/* check btf existence */
10642 	btf = bpf_object__btf(map->obj);
10643 	if (!btf)
10644 		return -ENOENT;
10645 
10646 	/* verify map is datasec */
10647 	datasec_type = btf_type_by_id(btf, bpf_map__btf_value_type_id(map));
10648 	if (!btf_is_datasec(datasec_type)) {
10649 		pr_warn("map '%s': cannot be resized, map value type is not a datasec\n",
10650 			bpf_map__name(map));
10651 		return -EINVAL;
10652 	}
10653 
10654 	/* verify datasec has at least one var */
10655 	vlen = btf_vlen(datasec_type);
10656 	if (vlen == 0) {
10657 		pr_warn("map '%s': cannot be resized, map value datasec is empty\n",
10658 			bpf_map__name(map));
10659 		return -EINVAL;
10660 	}
10661 
10662 	/* verify last var in the datasec is an array */
10663 	var = &btf_var_secinfos(datasec_type)[vlen - 1];
10664 	var_type = btf_type_by_id(btf, var->type);
10665 	array_type = skip_mods_and_typedefs(btf, var_type->type, NULL);
10666 	if (!btf_is_array(array_type)) {
10667 		pr_warn("map '%s': cannot be resized, last var must be an array\n",
10668 			bpf_map__name(map));
10669 		return -EINVAL;
10670 	}
10671 
10672 	/* verify request size aligns with array */
10673 	array = btf_array(array_type);
10674 	element_sz = btf__resolve_size(btf, array->type);
10675 	if (element_sz <= 0 || (size - var->offset) % element_sz != 0) {
10676 		pr_warn("map '%s': cannot be resized, element size (%d) doesn't align with new total size (%u)\n",
10677 			bpf_map__name(map), element_sz, size);
10678 		return -EINVAL;
10679 	}
10680 
10681 	/* create a new array based on the existing array, but with new length */
10682 	nr_elements = (size - var->offset) / element_sz;
10683 	new_array_id = btf__add_array(btf, array->index_type, array->type, nr_elements);
10684 	if (new_array_id < 0)
10685 		return new_array_id;
10686 
10687 	/* adding a new btf type invalidates existing pointers to btf objects,
10688 	 * so refresh pointers before proceeding
10689 	 */
10690 	datasec_type = btf_type_by_id(btf, map->btf_value_type_id);
10691 	var = &btf_var_secinfos(datasec_type)[vlen - 1];
10692 	var_type = btf_type_by_id(btf, var->type);
10693 
10694 	/* finally update btf info */
10695 	datasec_type->size = size;
10696 	var->size = size - var->offset;
10697 	var_type->type = new_array_id;
10698 
10699 	return 0;
10700 }
10701 
10702 int bpf_map__set_value_size(struct bpf_map *map, __u32 size)
10703 {
10704 	if (map_is_created(map))
10705 		return libbpf_err(-EBUSY);
10706 
10707 	if (map->mmaped) {
10708 		size_t mmap_old_sz, mmap_new_sz;
10709 		int err;
10710 
10711 		if (map->def.type != BPF_MAP_TYPE_ARRAY)
10712 			return libbpf_err(-EOPNOTSUPP);
10713 
10714 		mmap_old_sz = bpf_map_mmap_sz(map);
10715 		mmap_new_sz = array_map_mmap_sz(size, map->def.max_entries);
10716 		err = bpf_map_mmap_resize(map, mmap_old_sz, mmap_new_sz);
10717 		if (err) {
10718 			pr_warn("map '%s': failed to resize memory-mapped region: %s\n",
10719 				bpf_map__name(map), errstr(err));
10720 			return libbpf_err(err);
10721 		}
10722 		err = map_btf_datasec_resize(map, size);
10723 		if (err && err != -ENOENT) {
10724 			pr_warn("map '%s': failed to adjust resized BTF, clearing BTF key/value info: %s\n",
10725 				bpf_map__name(map), errstr(err));
10726 			map->btf_value_type_id = 0;
10727 			map->btf_key_type_id = 0;
10728 		}
10729 	}
10730 
10731 	map->def.value_size = size;
10732 	return 0;
10733 }
10734 
10735 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
10736 {
10737 	return map ? map->btf_key_type_id : 0;
10738 }
10739 
10740 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
10741 {
10742 	return map ? map->btf_value_type_id : 0;
10743 }
10744 
10745 int bpf_map__set_initial_value(struct bpf_map *map,
10746 			       const void *data, size_t size)
10747 {
10748 	size_t actual_sz;
10749 
10750 	if (map_is_created(map))
10751 		return libbpf_err(-EBUSY);
10752 
10753 	if (!map->mmaped || map->libbpf_type == LIBBPF_MAP_KCONFIG)
10754 		return libbpf_err(-EINVAL);
10755 
10756 	if (map->def.type == BPF_MAP_TYPE_ARENA)
10757 		actual_sz = map->obj->arena_data_sz;
10758 	else
10759 		actual_sz = map->def.value_size;
10760 	if (size != actual_sz)
10761 		return libbpf_err(-EINVAL);
10762 
10763 	memcpy(map->mmaped, data, size);
10764 	return 0;
10765 }
10766 
10767 void *bpf_map__initial_value(const struct bpf_map *map, size_t *psize)
10768 {
10769 	if (bpf_map__is_struct_ops(map)) {
10770 		if (psize)
10771 			*psize = map->def.value_size;
10772 		return map->st_ops->data;
10773 	}
10774 
10775 	if (!map->mmaped)
10776 		return NULL;
10777 
10778 	if (map->def.type == BPF_MAP_TYPE_ARENA)
10779 		*psize = map->obj->arena_data_sz;
10780 	else
10781 		*psize = map->def.value_size;
10782 
10783 	return map->mmaped;
10784 }
10785 
10786 bool bpf_map__is_internal(const struct bpf_map *map)
10787 {
10788 	return map->libbpf_type != LIBBPF_MAP_UNSPEC;
10789 }
10790 
10791 __u32 bpf_map__ifindex(const struct bpf_map *map)
10792 {
10793 	return map->map_ifindex;
10794 }
10795 
10796 int bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
10797 {
10798 	if (map_is_created(map))
10799 		return libbpf_err(-EBUSY);
10800 	map->map_ifindex = ifindex;
10801 	return 0;
10802 }
10803 
10804 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
10805 {
10806 	if (!bpf_map_type__is_map_in_map(map->def.type)) {
10807 		pr_warn("error: unsupported map type\n");
10808 		return libbpf_err(-EINVAL);
10809 	}
10810 	if (map->inner_map_fd != -1) {
10811 		pr_warn("error: inner_map_fd already specified\n");
10812 		return libbpf_err(-EINVAL);
10813 	}
10814 	if (map->inner_map) {
10815 		bpf_map__destroy(map->inner_map);
10816 		zfree(&map->inner_map);
10817 	}
10818 	map->inner_map_fd = fd;
10819 	return 0;
10820 }
10821 
10822 int bpf_map__set_exclusive_program(struct bpf_map *map, struct bpf_program *prog)
10823 {
10824 	if (map_is_created(map)) {
10825 		pr_warn("exclusive programs must be set before map creation\n");
10826 		return libbpf_err(-EINVAL);
10827 	}
10828 
10829 	if (map->obj != prog->obj) {
10830 		pr_warn("excl_prog and map must be from the same bpf object\n");
10831 		return libbpf_err(-EINVAL);
10832 	}
10833 
10834 	map->excl_prog = prog;
10835 	return 0;
10836 }
10837 
10838 struct bpf_program *bpf_map__exclusive_program(struct bpf_map *map)
10839 {
10840 	return map->excl_prog;
10841 }
10842 
10843 static struct bpf_map *
10844 __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
10845 {
10846 	ssize_t idx;
10847 	struct bpf_map *s, *e;
10848 
10849 	if (!obj || !obj->maps)
10850 		return errno = EINVAL, NULL;
10851 
10852 	s = obj->maps;
10853 	e = obj->maps + obj->nr_maps;
10854 
10855 	if ((m < s) || (m >= e)) {
10856 		pr_warn("error in %s: map handler doesn't belong to object\n",
10857 			 __func__);
10858 		return errno = EINVAL, NULL;
10859 	}
10860 
10861 	idx = (m - obj->maps) + i;
10862 	if (idx >= obj->nr_maps || idx < 0)
10863 		return NULL;
10864 	return &obj->maps[idx];
10865 }
10866 
10867 struct bpf_map *
10868 bpf_object__next_map(const struct bpf_object *obj, const struct bpf_map *prev)
10869 {
10870 	if (prev == NULL && obj != NULL)
10871 		return obj->maps;
10872 
10873 	return __bpf_map__iter(prev, obj, 1);
10874 }
10875 
10876 struct bpf_map *
10877 bpf_object__prev_map(const struct bpf_object *obj, const struct bpf_map *next)
10878 {
10879 	if (next == NULL && obj != NULL) {
10880 		if (!obj->nr_maps)
10881 			return NULL;
10882 		return obj->maps + obj->nr_maps - 1;
10883 	}
10884 
10885 	return __bpf_map__iter(next, obj, -1);
10886 }
10887 
10888 struct bpf_map *
10889 bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
10890 {
10891 	struct bpf_map *pos;
10892 
10893 	bpf_object__for_each_map(pos, obj) {
10894 		/* if it's a special internal map name (which always starts
10895 		 * with dot) then check if that special name matches the
10896 		 * real map name (ELF section name)
10897 		 */
10898 		if (name[0] == '.') {
10899 			if (pos->real_name && strcmp(pos->real_name, name) == 0)
10900 				return pos;
10901 			continue;
10902 		}
10903 		/* otherwise map name has to be an exact match */
10904 		if (map_uses_real_name(pos)) {
10905 			if (strcmp(pos->real_name, name) == 0)
10906 				return pos;
10907 			continue;
10908 		}
10909 		if (strcmp(pos->name, name) == 0)
10910 			return pos;
10911 	}
10912 	return errno = ENOENT, NULL;
10913 }
10914 
10915 int
10916 bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
10917 {
10918 	return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
10919 }
10920 
10921 static int validate_map_op(const struct bpf_map *map, size_t key_sz,
10922 			   size_t value_sz, bool check_value_sz, __u64 flags)
10923 {
10924 	if (!map_is_created(map)) /* map is not yet created */
10925 		return -ENOENT;
10926 
10927 	if (map->def.key_size != key_sz) {
10928 		pr_warn("map '%s': unexpected key size %zu provided, expected %u\n",
10929 			map->name, key_sz, map->def.key_size);
10930 		return -EINVAL;
10931 	}
10932 
10933 	if (map->fd < 0) {
10934 		pr_warn("map '%s': can't use BPF map without FD (was it created?)\n", map->name);
10935 		return -EINVAL;
10936 	}
10937 
10938 	if (!check_value_sz)
10939 		return 0;
10940 
10941 	switch (map->def.type) {
10942 	case BPF_MAP_TYPE_PERCPU_ARRAY:
10943 	case BPF_MAP_TYPE_PERCPU_HASH:
10944 	case BPF_MAP_TYPE_LRU_PERCPU_HASH:
10945 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: {
10946 		int num_cpu = libbpf_num_possible_cpus();
10947 		size_t elem_sz = roundup(map->def.value_size, 8);
10948 
10949 		if (flags & (BPF_F_CPU | BPF_F_ALL_CPUS)) {
10950 			if ((flags & BPF_F_CPU) && (flags & BPF_F_ALL_CPUS)) {
10951 				pr_warn("map '%s': BPF_F_CPU and BPF_F_ALL_CPUS are mutually exclusive\n",
10952 					map->name);
10953 				return -EINVAL;
10954 			}
10955 			if (map->def.value_size != value_sz) {
10956 				pr_warn("map '%s': unexpected value size %zu provided for either BPF_F_CPU or BPF_F_ALL_CPUS, expected %u\n",
10957 					map->name, value_sz, map->def.value_size);
10958 				return -EINVAL;
10959 			}
10960 			break;
10961 		}
10962 
10963 		if (value_sz != num_cpu * elem_sz) {
10964 			pr_warn("map '%s': unexpected value size %zu provided for per-CPU map, expected %d * %zu = %zd\n",
10965 				map->name, value_sz, num_cpu, elem_sz, num_cpu * elem_sz);
10966 			return -EINVAL;
10967 		}
10968 		break;
10969 	}
10970 	default:
10971 		if (map->def.value_size != value_sz) {
10972 			pr_warn("map '%s': unexpected value size %zu provided, expected %u\n",
10973 				map->name, value_sz, map->def.value_size);
10974 			return -EINVAL;
10975 		}
10976 		break;
10977 	}
10978 	return 0;
10979 }
10980 
10981 int bpf_map__lookup_elem(const struct bpf_map *map,
10982 			 const void *key, size_t key_sz,
10983 			 void *value, size_t value_sz, __u64 flags)
10984 {
10985 	int err;
10986 
10987 	err = validate_map_op(map, key_sz, value_sz, true, flags);
10988 	if (err)
10989 		return libbpf_err(err);
10990 
10991 	return bpf_map_lookup_elem_flags(map->fd, key, value, flags);
10992 }
10993 
10994 int bpf_map__update_elem(const struct bpf_map *map,
10995 			 const void *key, size_t key_sz,
10996 			 const void *value, size_t value_sz, __u64 flags)
10997 {
10998 	int err;
10999 
11000 	err = validate_map_op(map, key_sz, value_sz, true, flags);
11001 	if (err)
11002 		return libbpf_err(err);
11003 
11004 	return bpf_map_update_elem(map->fd, key, value, flags);
11005 }
11006 
11007 int bpf_map__delete_elem(const struct bpf_map *map,
11008 			 const void *key, size_t key_sz, __u64 flags)
11009 {
11010 	int err;
11011 
11012 	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */, flags);
11013 	if (err)
11014 		return libbpf_err(err);
11015 
11016 	return bpf_map_delete_elem_flags(map->fd, key, flags);
11017 }
11018 
11019 int bpf_map__lookup_and_delete_elem(const struct bpf_map *map,
11020 				    const void *key, size_t key_sz,
11021 				    void *value, size_t value_sz, __u64 flags)
11022 {
11023 	int err;
11024 
11025 	err = validate_map_op(map, key_sz, value_sz, true, flags);
11026 	if (err)
11027 		return libbpf_err(err);
11028 
11029 	return bpf_map_lookup_and_delete_elem_flags(map->fd, key, value, flags);
11030 }
11031 
11032 int bpf_map__get_next_key(const struct bpf_map *map,
11033 			  const void *cur_key, void *next_key, size_t key_sz)
11034 {
11035 	int err;
11036 
11037 	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */, 0);
11038 	if (err)
11039 		return libbpf_err(err);
11040 
11041 	return bpf_map_get_next_key(map->fd, cur_key, next_key);
11042 }
11043 
11044 long libbpf_get_error(const void *ptr)
11045 {
11046 	if (!IS_ERR_OR_NULL(ptr))
11047 		return 0;
11048 
11049 	if (IS_ERR(ptr))
11050 		errno = -PTR_ERR(ptr);
11051 
11052 	/* If ptr == NULL, then errno should be already set by the failing
11053 	 * API, because libbpf never returns NULL on success and it now always
11054 	 * sets errno on error. So no extra errno handling for ptr == NULL
11055 	 * case.
11056 	 */
11057 	return -errno;
11058 }
11059 
11060 /* Replace link's underlying BPF program with the new one */
11061 int bpf_link__update_program(struct bpf_link *link, struct bpf_program *prog)
11062 {
11063 	int ret;
11064 	int prog_fd = bpf_program__fd(prog);
11065 
11066 	if (prog_fd < 0) {
11067 		pr_warn("prog '%s': can't use BPF program without FD (was it loaded?)\n",
11068 			prog->name);
11069 		return libbpf_err(-EINVAL);
11070 	}
11071 
11072 	ret = bpf_link_update(bpf_link__fd(link), prog_fd, NULL);
11073 	return libbpf_err_errno(ret);
11074 }
11075 
11076 /* Release "ownership" of underlying BPF resource (typically, BPF program
11077  * attached to some BPF hook, e.g., tracepoint, kprobe, etc). Disconnected
11078  * link, when destructed through bpf_link__destroy() call won't attempt to
11079  * detach/unregisted that BPF resource. This is useful in situations where,
11080  * say, attached BPF program has to outlive userspace program that attached it
11081  * in the system. Depending on type of BPF program, though, there might be
11082  * additional steps (like pinning BPF program in BPF FS) necessary to ensure
11083  * exit of userspace program doesn't trigger automatic detachment and clean up
11084  * inside the kernel.
11085  */
11086 void bpf_link__disconnect(struct bpf_link *link)
11087 {
11088 	link->disconnected = true;
11089 }
11090 
11091 int bpf_link__destroy(struct bpf_link *link)
11092 {
11093 	int err = 0;
11094 
11095 	if (IS_ERR_OR_NULL(link))
11096 		return 0;
11097 
11098 	if (!link->disconnected && link->detach)
11099 		err = link->detach(link);
11100 	if (link->pin_path)
11101 		free(link->pin_path);
11102 	if (link->dealloc)
11103 		link->dealloc(link);
11104 	else
11105 		free(link);
11106 
11107 	return libbpf_err(err);
11108 }
11109 
11110 int bpf_link__fd(const struct bpf_link *link)
11111 {
11112 	return link->fd;
11113 }
11114 
11115 const char *bpf_link__pin_path(const struct bpf_link *link)
11116 {
11117 	return link->pin_path;
11118 }
11119 
11120 static int bpf_link__detach_fd(struct bpf_link *link)
11121 {
11122 	return libbpf_err_errno(close(link->fd));
11123 }
11124 
11125 struct bpf_link *bpf_link__open(const char *path)
11126 {
11127 	struct bpf_link *link;
11128 	int fd;
11129 
11130 	fd = bpf_obj_get(path);
11131 	if (fd < 0) {
11132 		fd = -errno;
11133 		pr_warn("failed to open link at %s: %d\n", path, fd);
11134 		return libbpf_err_ptr(fd);
11135 	}
11136 
11137 	link = calloc(1, sizeof(*link));
11138 	if (!link) {
11139 		close(fd);
11140 		return libbpf_err_ptr(-ENOMEM);
11141 	}
11142 	link->detach = &bpf_link__detach_fd;
11143 	link->fd = fd;
11144 
11145 	link->pin_path = strdup(path);
11146 	if (!link->pin_path) {
11147 		bpf_link__destroy(link);
11148 		return libbpf_err_ptr(-ENOMEM);
11149 	}
11150 
11151 	return link;
11152 }
11153 
11154 int bpf_link__detach(struct bpf_link *link)
11155 {
11156 	return bpf_link_detach(link->fd) ? -errno : 0;
11157 }
11158 
11159 int bpf_link__pin(struct bpf_link *link, const char *path)
11160 {
11161 	int err;
11162 
11163 	if (link->pin_path)
11164 		return libbpf_err(-EBUSY);
11165 	err = make_parent_dir(path);
11166 	if (err)
11167 		return libbpf_err(err);
11168 	err = check_path(path);
11169 	if (err)
11170 		return libbpf_err(err);
11171 
11172 	link->pin_path = strdup(path);
11173 	if (!link->pin_path)
11174 		return libbpf_err(-ENOMEM);
11175 
11176 	if (bpf_obj_pin(link->fd, link->pin_path)) {
11177 		err = -errno;
11178 		zfree(&link->pin_path);
11179 		return libbpf_err(err);
11180 	}
11181 
11182 	pr_debug("link fd=%d: pinned at %s\n", link->fd, link->pin_path);
11183 	return 0;
11184 }
11185 
11186 int bpf_link__unpin(struct bpf_link *link)
11187 {
11188 	int err;
11189 
11190 	if (!link->pin_path)
11191 		return libbpf_err(-EINVAL);
11192 
11193 	err = unlink(link->pin_path);
11194 	if (err != 0)
11195 		return -errno;
11196 
11197 	pr_debug("link fd=%d: unpinned from %s\n", link->fd, link->pin_path);
11198 	zfree(&link->pin_path);
11199 	return 0;
11200 }
11201 
11202 struct bpf_link_perf {
11203 	struct bpf_link link;
11204 	int perf_event_fd;
11205 	/* legacy kprobe support: keep track of probe identifier and type */
11206 	char *legacy_probe_name;
11207 	bool legacy_is_kprobe;
11208 	bool legacy_is_retprobe;
11209 };
11210 
11211 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe);
11212 static int remove_uprobe_event_legacy(const char *probe_name, bool retprobe);
11213 
11214 static int bpf_link_perf_detach(struct bpf_link *link)
11215 {
11216 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
11217 	int err = 0;
11218 
11219 	if (ioctl(perf_link->perf_event_fd, PERF_EVENT_IOC_DISABLE, 0) < 0)
11220 		err = -errno;
11221 
11222 	if (perf_link->perf_event_fd != link->fd)
11223 		close(perf_link->perf_event_fd);
11224 	close(link->fd);
11225 
11226 	/* legacy uprobe/kprobe needs to be removed after perf event fd closure */
11227 	if (perf_link->legacy_probe_name) {
11228 		if (perf_link->legacy_is_kprobe) {
11229 			err = remove_kprobe_event_legacy(perf_link->legacy_probe_name,
11230 							 perf_link->legacy_is_retprobe);
11231 		} else {
11232 			err = remove_uprobe_event_legacy(perf_link->legacy_probe_name,
11233 							 perf_link->legacy_is_retprobe);
11234 		}
11235 	}
11236 
11237 	return err;
11238 }
11239 
11240 static void bpf_link_perf_dealloc(struct bpf_link *link)
11241 {
11242 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
11243 
11244 	free(perf_link->legacy_probe_name);
11245 	free(perf_link);
11246 }
11247 
11248 struct bpf_link *bpf_program__attach_perf_event_opts(const struct bpf_program *prog, int pfd,
11249 						     const struct bpf_perf_event_opts *opts)
11250 {
11251 	struct bpf_link_perf *link;
11252 	int prog_fd, link_fd = -1, err;
11253 	bool force_ioctl_attach;
11254 
11255 	if (!OPTS_VALID(opts, bpf_perf_event_opts))
11256 		return libbpf_err_ptr(-EINVAL);
11257 
11258 	if (pfd < 0) {
11259 		pr_warn("prog '%s': invalid perf event FD %d\n",
11260 			prog->name, pfd);
11261 		return libbpf_err_ptr(-EINVAL);
11262 	}
11263 	prog_fd = bpf_program__fd(prog);
11264 	if (prog_fd < 0) {
11265 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
11266 			prog->name);
11267 		return libbpf_err_ptr(-EINVAL);
11268 	}
11269 
11270 	link = calloc(1, sizeof(*link));
11271 	if (!link)
11272 		return libbpf_err_ptr(-ENOMEM);
11273 	link->link.detach = &bpf_link_perf_detach;
11274 	link->link.dealloc = &bpf_link_perf_dealloc;
11275 	link->perf_event_fd = pfd;
11276 
11277 	force_ioctl_attach = OPTS_GET(opts, force_ioctl_attach, false);
11278 	if (kernel_supports(prog->obj, FEAT_PERF_LINK) && !force_ioctl_attach) {
11279 		DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_opts,
11280 			.perf_event.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0));
11281 
11282 		link_fd = bpf_link_create(prog_fd, pfd, BPF_PERF_EVENT, &link_opts);
11283 		if (link_fd < 0) {
11284 			err = -errno;
11285 			pr_warn("prog '%s': failed to create BPF link for perf_event FD %d: %s\n",
11286 				prog->name, pfd, errstr(err));
11287 			goto err_out;
11288 		}
11289 		link->link.fd = link_fd;
11290 	} else {
11291 		if (OPTS_GET(opts, bpf_cookie, 0)) {
11292 			pr_warn("prog '%s': user context value is not supported\n", prog->name);
11293 			err = -EOPNOTSUPP;
11294 			goto err_out;
11295 		}
11296 
11297 		if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
11298 			err = -errno;
11299 			pr_warn("prog '%s': failed to attach to perf_event FD %d: %s\n",
11300 				prog->name, pfd, errstr(err));
11301 			if (err == -EPROTO)
11302 				pr_warn("prog '%s': try add PERF_SAMPLE_CALLCHAIN to or remove exclude_callchain_[kernel|user] from pfd %d\n",
11303 					prog->name, pfd);
11304 			goto err_out;
11305 		}
11306 		link->link.fd = pfd;
11307 	}
11308 
11309 	if (!OPTS_GET(opts, dont_enable, false)) {
11310 		if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
11311 			err = -errno;
11312 			pr_warn("prog '%s': failed to enable perf_event FD %d: %s\n",
11313 				prog->name, pfd, errstr(err));
11314 			goto err_out;
11315 		}
11316 	}
11317 
11318 	return &link->link;
11319 err_out:
11320 	if (link_fd >= 0)
11321 		close(link_fd);
11322 	free(link);
11323 	return libbpf_err_ptr(err);
11324 }
11325 
11326 struct bpf_link *bpf_program__attach_perf_event(const struct bpf_program *prog, int pfd)
11327 {
11328 	return bpf_program__attach_perf_event_opts(prog, pfd, NULL);
11329 }
11330 
11331 /*
11332  * this function is expected to parse integer in the range of [0, 2^31-1] from
11333  * given file using scanf format string fmt. If actual parsed value is
11334  * negative, the result might be indistinguishable from error
11335  */
11336 static int parse_uint_from_file(const char *file, const char *fmt)
11337 {
11338 	int err, ret;
11339 	FILE *f;
11340 
11341 	f = fopen(file, "re");
11342 	if (!f) {
11343 		err = -errno;
11344 		pr_debug("failed to open '%s': %s\n", file, errstr(err));
11345 		return err;
11346 	}
11347 	err = fscanf(f, fmt, &ret);
11348 	if (err != 1) {
11349 		err = err == EOF ? -EIO : -errno;
11350 		pr_debug("failed to parse '%s': %s\n", file, errstr(err));
11351 		fclose(f);
11352 		return err;
11353 	}
11354 	fclose(f);
11355 	return ret;
11356 }
11357 
11358 static int determine_kprobe_perf_type(void)
11359 {
11360 	const char *file = "/sys/bus/event_source/devices/kprobe/type";
11361 
11362 	return parse_uint_from_file(file, "%d\n");
11363 }
11364 
11365 static int determine_uprobe_perf_type(void)
11366 {
11367 	const char *file = "/sys/bus/event_source/devices/uprobe/type";
11368 
11369 	return parse_uint_from_file(file, "%d\n");
11370 }
11371 
11372 static int determine_kprobe_retprobe_bit(void)
11373 {
11374 	const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
11375 
11376 	return parse_uint_from_file(file, "config:%d\n");
11377 }
11378 
11379 static int determine_uprobe_retprobe_bit(void)
11380 {
11381 	const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
11382 
11383 	return parse_uint_from_file(file, "config:%d\n");
11384 }
11385 
11386 #define PERF_UPROBE_REF_CTR_OFFSET_BITS 32
11387 #define PERF_UPROBE_REF_CTR_OFFSET_SHIFT 32
11388 
11389 static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
11390 				 uint64_t offset, int pid, size_t ref_ctr_off)
11391 {
11392 	const size_t attr_sz = sizeof(struct perf_event_attr);
11393 	struct perf_event_attr attr;
11394 	int type, pfd;
11395 
11396 	if ((__u64)ref_ctr_off >= (1ULL << PERF_UPROBE_REF_CTR_OFFSET_BITS))
11397 		return -EINVAL;
11398 
11399 	memset(&attr, 0, attr_sz);
11400 
11401 	type = uprobe ? determine_uprobe_perf_type()
11402 		      : determine_kprobe_perf_type();
11403 	if (type < 0) {
11404 		pr_warn("failed to determine %s perf type: %s\n",
11405 			uprobe ? "uprobe" : "kprobe",
11406 			errstr(type));
11407 		return type;
11408 	}
11409 	if (retprobe) {
11410 		int bit = uprobe ? determine_uprobe_retprobe_bit()
11411 				 : determine_kprobe_retprobe_bit();
11412 
11413 		if (bit < 0) {
11414 			pr_warn("failed to determine %s retprobe bit: %s\n",
11415 				uprobe ? "uprobe" : "kprobe",
11416 				errstr(bit));
11417 			return bit;
11418 		}
11419 		attr.config |= 1 << bit;
11420 	}
11421 	attr.size = attr_sz;
11422 	attr.type = type;
11423 	attr.config |= (__u64)ref_ctr_off << PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
11424 	attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
11425 	attr.config2 = offset;		 /* kprobe_addr or probe_offset */
11426 
11427 	/* pid filter is meaningful only for uprobes */
11428 	pfd = syscall(__NR_perf_event_open, &attr,
11429 		      pid < 0 ? -1 : pid /* pid */,
11430 		      pid == -1 ? 0 : -1 /* cpu */,
11431 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
11432 	return pfd >= 0 ? pfd : -errno;
11433 }
11434 
11435 static int append_to_file(const char *file, const char *fmt, ...)
11436 {
11437 	int fd, n, err = 0;
11438 	va_list ap;
11439 	char buf[1024];
11440 
11441 	va_start(ap, fmt);
11442 	n = vsnprintf(buf, sizeof(buf), fmt, ap);
11443 	va_end(ap);
11444 
11445 	if (n < 0 || n >= sizeof(buf))
11446 		return -EINVAL;
11447 
11448 	fd = open(file, O_WRONLY | O_APPEND | O_CLOEXEC, 0);
11449 	if (fd < 0)
11450 		return -errno;
11451 
11452 	if (write(fd, buf, n) < 0)
11453 		err = -errno;
11454 
11455 	close(fd);
11456 	return err;
11457 }
11458 
11459 #define DEBUGFS "/sys/kernel/debug/tracing"
11460 #define TRACEFS "/sys/kernel/tracing"
11461 
11462 static bool use_debugfs(void)
11463 {
11464 	static int has_debugfs = -1;
11465 
11466 	if (has_debugfs < 0)
11467 		has_debugfs = faccessat(AT_FDCWD, DEBUGFS, F_OK, AT_EACCESS) == 0;
11468 
11469 	return has_debugfs == 1;
11470 }
11471 
11472 static const char *tracefs_path(void)
11473 {
11474 	return use_debugfs() ? DEBUGFS : TRACEFS;
11475 }
11476 
11477 static const char *tracefs_kprobe_events(void)
11478 {
11479 	return use_debugfs() ? DEBUGFS"/kprobe_events" : TRACEFS"/kprobe_events";
11480 }
11481 
11482 static const char *tracefs_uprobe_events(void)
11483 {
11484 	return use_debugfs() ? DEBUGFS"/uprobe_events" : TRACEFS"/uprobe_events";
11485 }
11486 
11487 static const char *tracefs_available_filter_functions(void)
11488 {
11489 	return use_debugfs() ? DEBUGFS"/available_filter_functions"
11490 			     : TRACEFS"/available_filter_functions";
11491 }
11492 
11493 static const char *tracefs_available_filter_functions_addrs(void)
11494 {
11495 	return use_debugfs() ? DEBUGFS"/available_filter_functions_addrs"
11496 			     : TRACEFS"/available_filter_functions_addrs";
11497 }
11498 
11499 static void gen_probe_legacy_event_name(char *buf, size_t buf_sz,
11500 					const char *name, size_t offset)
11501 {
11502 	static int index = 0;
11503 	int i;
11504 
11505 	snprintf(buf, buf_sz, "libbpf_%u_%d_%s_0x%zx", getpid(),
11506 		 __sync_fetch_and_add(&index, 1), name, offset);
11507 
11508 	/* sanitize name in the probe name */
11509 	for (i = 0; buf[i]; i++) {
11510 		if (!isalnum(buf[i]))
11511 			buf[i] = '_';
11512 	}
11513 }
11514 
11515 static int add_kprobe_event_legacy(const char *probe_name, bool retprobe,
11516 				   const char *kfunc_name, size_t offset)
11517 {
11518 	return append_to_file(tracefs_kprobe_events(), "%c:%s/%s %s+0x%zx",
11519 			      retprobe ? 'r' : 'p',
11520 			      retprobe ? "kretprobes" : "kprobes",
11521 			      probe_name, kfunc_name, offset);
11522 }
11523 
11524 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe)
11525 {
11526 	return append_to_file(tracefs_kprobe_events(), "-:%s/%s",
11527 			      retprobe ? "kretprobes" : "kprobes", probe_name);
11528 }
11529 
11530 static int determine_kprobe_perf_type_legacy(const char *probe_name, bool retprobe)
11531 {
11532 	char file[256];
11533 
11534 	snprintf(file, sizeof(file), "%s/events/%s/%s/id",
11535 		 tracefs_path(), retprobe ? "kretprobes" : "kprobes", probe_name);
11536 
11537 	return parse_uint_from_file(file, "%d\n");
11538 }
11539 
11540 static int perf_event_kprobe_open_legacy(const char *probe_name, bool retprobe,
11541 					 const char *kfunc_name, size_t offset, int pid)
11542 {
11543 	const size_t attr_sz = sizeof(struct perf_event_attr);
11544 	struct perf_event_attr attr;
11545 	int type, pfd, err;
11546 
11547 	err = add_kprobe_event_legacy(probe_name, retprobe, kfunc_name, offset);
11548 	if (err < 0) {
11549 		pr_warn("failed to add legacy kprobe event for '%s+0x%zx': %s\n",
11550 			kfunc_name, offset,
11551 			errstr(err));
11552 		return err;
11553 	}
11554 	type = determine_kprobe_perf_type_legacy(probe_name, retprobe);
11555 	if (type < 0) {
11556 		err = type;
11557 		pr_warn("failed to determine legacy kprobe event id for '%s+0x%zx': %s\n",
11558 			kfunc_name, offset,
11559 			errstr(err));
11560 		goto err_clean_legacy;
11561 	}
11562 
11563 	memset(&attr, 0, attr_sz);
11564 	attr.size = attr_sz;
11565 	attr.config = type;
11566 	attr.type = PERF_TYPE_TRACEPOINT;
11567 
11568 	pfd = syscall(__NR_perf_event_open, &attr,
11569 		      pid < 0 ? -1 : pid, /* pid */
11570 		      pid == -1 ? 0 : -1, /* cpu */
11571 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
11572 	if (pfd < 0) {
11573 		err = -errno;
11574 		pr_warn("legacy kprobe perf_event_open() failed: %s\n",
11575 			errstr(err));
11576 		goto err_clean_legacy;
11577 	}
11578 	return pfd;
11579 
11580 err_clean_legacy:
11581 	/* Clear the newly added legacy kprobe_event */
11582 	remove_kprobe_event_legacy(probe_name, retprobe);
11583 	return err;
11584 }
11585 
11586 static const char *arch_specific_syscall_pfx(void)
11587 {
11588 #if defined(__x86_64__)
11589 	return "x64";
11590 #elif defined(__i386__)
11591 	return "ia32";
11592 #elif defined(__s390x__)
11593 	return "s390x";
11594 #elif defined(__arm__)
11595 	return "arm";
11596 #elif defined(__aarch64__)
11597 	return "arm64";
11598 #elif defined(__mips__)
11599 	return "mips";
11600 #elif defined(__riscv)
11601 	return "riscv";
11602 #elif defined(__powerpc__)
11603 	return "powerpc";
11604 #elif defined(__powerpc64__)
11605 	return "powerpc64";
11606 #else
11607 	return NULL;
11608 #endif
11609 }
11610 
11611 int probe_kern_syscall_wrapper(int token_fd)
11612 {
11613 	char syscall_name[64];
11614 	const char *ksys_pfx;
11615 
11616 	ksys_pfx = arch_specific_syscall_pfx();
11617 	if (!ksys_pfx)
11618 		return 0;
11619 
11620 	snprintf(syscall_name, sizeof(syscall_name), "__%s_sys_bpf", ksys_pfx);
11621 
11622 	if (determine_kprobe_perf_type() >= 0) {
11623 		int pfd;
11624 
11625 		pfd = perf_event_open_probe(false, false, syscall_name, 0, getpid(), 0);
11626 		if (pfd >= 0)
11627 			close(pfd);
11628 
11629 		return pfd >= 0 ? 1 : 0;
11630 	} else { /* legacy mode */
11631 		char probe_name[MAX_EVENT_NAME_LEN];
11632 
11633 		gen_probe_legacy_event_name(probe_name, sizeof(probe_name), syscall_name, 0);
11634 		if (add_kprobe_event_legacy(probe_name, false, syscall_name, 0) < 0)
11635 			return 0;
11636 
11637 		(void)remove_kprobe_event_legacy(probe_name, false);
11638 		return 1;
11639 	}
11640 }
11641 
11642 struct bpf_link *
11643 bpf_program__attach_kprobe_opts(const struct bpf_program *prog,
11644 				const char *func_name,
11645 				const struct bpf_kprobe_opts *opts)
11646 {
11647 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
11648 	enum probe_attach_mode attach_mode;
11649 	char *legacy_probe = NULL;
11650 	struct bpf_link *link;
11651 	size_t offset;
11652 	bool retprobe, legacy;
11653 	int pfd, err;
11654 
11655 	if (!OPTS_VALID(opts, bpf_kprobe_opts))
11656 		return libbpf_err_ptr(-EINVAL);
11657 
11658 	attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
11659 	retprobe = OPTS_GET(opts, retprobe, false);
11660 	offset = OPTS_GET(opts, offset, 0);
11661 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11662 
11663 	legacy = determine_kprobe_perf_type() < 0;
11664 	switch (attach_mode) {
11665 	case PROBE_ATTACH_MODE_LEGACY:
11666 		legacy = true;
11667 		pe_opts.force_ioctl_attach = true;
11668 		break;
11669 	case PROBE_ATTACH_MODE_PERF:
11670 		if (legacy)
11671 			return libbpf_err_ptr(-ENOTSUP);
11672 		pe_opts.force_ioctl_attach = true;
11673 		break;
11674 	case PROBE_ATTACH_MODE_LINK:
11675 		if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
11676 			return libbpf_err_ptr(-ENOTSUP);
11677 		break;
11678 	case PROBE_ATTACH_MODE_DEFAULT:
11679 		break;
11680 	default:
11681 		return libbpf_err_ptr(-EINVAL);
11682 	}
11683 
11684 	if (!legacy) {
11685 		pfd = perf_event_open_probe(false /* uprobe */, retprobe,
11686 					    func_name, offset,
11687 					    -1 /* pid */, 0 /* ref_ctr_off */);
11688 	} else {
11689 		char probe_name[MAX_EVENT_NAME_LEN];
11690 
11691 		gen_probe_legacy_event_name(probe_name, sizeof(probe_name),
11692 					    func_name, offset);
11693 
11694 		legacy_probe = strdup(probe_name);
11695 		if (!legacy_probe)
11696 			return libbpf_err_ptr(-ENOMEM);
11697 
11698 		pfd = perf_event_kprobe_open_legacy(legacy_probe, retprobe, func_name,
11699 						    offset, -1 /* pid */);
11700 	}
11701 	if (pfd < 0) {
11702 		err = -errno;
11703 		pr_warn("prog '%s': failed to create %s '%s+0x%zx' perf event: %s\n",
11704 			prog->name, retprobe ? "kretprobe" : "kprobe",
11705 			func_name, offset,
11706 			errstr(err));
11707 		goto err_out;
11708 	}
11709 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
11710 	err = libbpf_get_error(link);
11711 	if (err) {
11712 		close(pfd);
11713 		pr_warn("prog '%s': failed to attach to %s '%s+0x%zx': %s\n",
11714 			prog->name, retprobe ? "kretprobe" : "kprobe",
11715 			func_name, offset,
11716 			errstr(err));
11717 		goto err_clean_legacy;
11718 	}
11719 	if (legacy) {
11720 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
11721 
11722 		perf_link->legacy_probe_name = legacy_probe;
11723 		perf_link->legacy_is_kprobe = true;
11724 		perf_link->legacy_is_retprobe = retprobe;
11725 	}
11726 
11727 	return link;
11728 
11729 err_clean_legacy:
11730 	if (legacy)
11731 		remove_kprobe_event_legacy(legacy_probe, retprobe);
11732 err_out:
11733 	free(legacy_probe);
11734 	return libbpf_err_ptr(err);
11735 }
11736 
11737 struct bpf_link *bpf_program__attach_kprobe(const struct bpf_program *prog,
11738 					    bool retprobe,
11739 					    const char *func_name)
11740 {
11741 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts,
11742 		.retprobe = retprobe,
11743 	);
11744 
11745 	return bpf_program__attach_kprobe_opts(prog, func_name, &opts);
11746 }
11747 
11748 struct bpf_link *bpf_program__attach_ksyscall(const struct bpf_program *prog,
11749 					      const char *syscall_name,
11750 					      const struct bpf_ksyscall_opts *opts)
11751 {
11752 	LIBBPF_OPTS(bpf_kprobe_opts, kprobe_opts);
11753 	char func_name[128];
11754 
11755 	if (!OPTS_VALID(opts, bpf_ksyscall_opts))
11756 		return libbpf_err_ptr(-EINVAL);
11757 
11758 	if (kernel_supports(prog->obj, FEAT_SYSCALL_WRAPPER)) {
11759 		/* arch_specific_syscall_pfx() should never return NULL here
11760 		 * because it is guarded by kernel_supports(). However, since
11761 		 * compiler does not know that we have an explicit conditional
11762 		 * as well.
11763 		 */
11764 		snprintf(func_name, sizeof(func_name), "__%s_sys_%s",
11765 			 arch_specific_syscall_pfx() ? : "", syscall_name);
11766 	} else {
11767 		snprintf(func_name, sizeof(func_name), "__se_sys_%s", syscall_name);
11768 	}
11769 
11770 	kprobe_opts.retprobe = OPTS_GET(opts, retprobe, false);
11771 	kprobe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11772 
11773 	return bpf_program__attach_kprobe_opts(prog, func_name, &kprobe_opts);
11774 }
11775 
11776 /* Adapted from perf/util/string.c */
11777 bool glob_match(const char *str, const char *pat)
11778 {
11779 	while (*str && *pat && *pat != '*') {
11780 		if (*pat == '?') {      /* Matches any single character */
11781 			str++;
11782 			pat++;
11783 			continue;
11784 		}
11785 		if (*str != *pat)
11786 			return false;
11787 		str++;
11788 		pat++;
11789 	}
11790 	/* Check wild card */
11791 	if (*pat == '*') {
11792 		while (*pat == '*')
11793 			pat++;
11794 		if (!*pat) /* Tail wild card matches all */
11795 			return true;
11796 		while (*str)
11797 			if (glob_match(str++, pat))
11798 				return true;
11799 	}
11800 	return !*str && !*pat;
11801 }
11802 
11803 struct kprobe_multi_resolve {
11804 	const char *pattern;
11805 	unsigned long *addrs;
11806 	size_t cap;
11807 	size_t cnt;
11808 };
11809 
11810 struct avail_kallsyms_data {
11811 	char **syms;
11812 	size_t cnt;
11813 	struct kprobe_multi_resolve *res;
11814 };
11815 
11816 static int avail_func_cmp(const void *a, const void *b)
11817 {
11818 	return strcmp(*(const char **)a, *(const char **)b);
11819 }
11820 
11821 static int avail_kallsyms_cb(unsigned long long sym_addr, char sym_type,
11822 			     const char *sym_name, void *ctx)
11823 {
11824 	struct avail_kallsyms_data *data = ctx;
11825 	struct kprobe_multi_resolve *res = data->res;
11826 	int err;
11827 
11828 	if (!glob_match(sym_name, res->pattern))
11829 		return 0;
11830 
11831 	if (!bsearch(&sym_name, data->syms, data->cnt, sizeof(*data->syms), avail_func_cmp)) {
11832 		/* Some versions of kernel strip out .llvm.<hash> suffix from
11833 		 * function names reported in available_filter_functions, but
11834 		 * don't do so for kallsyms. While this is clearly a kernel
11835 		 * bug (fixed by [0]) we try to accommodate that in libbpf to
11836 		 * make multi-kprobe usability a bit better: if no match is
11837 		 * found, we will strip .llvm. suffix and try one more time.
11838 		 *
11839 		 *   [0] fb6a421fb615 ("kallsyms: Match symbols exactly with CONFIG_LTO_CLANG")
11840 		 */
11841 		char sym_trim[256], *psym_trim = sym_trim;
11842 		const char *sym_sfx;
11843 
11844 		if (!(sym_sfx = strstr(sym_name, ".llvm.")))
11845 			return 0;
11846 
11847 		/* psym_trim vs sym_trim dance is done to avoid pointer vs array
11848 		 * coercion differences and get proper `const char **` pointer
11849 		 * which avail_func_cmp() expects
11850 		 */
11851 		snprintf(sym_trim, sizeof(sym_trim), "%.*s", (int)(sym_sfx - sym_name), sym_name);
11852 		if (!bsearch(&psym_trim, data->syms, data->cnt, sizeof(*data->syms), avail_func_cmp))
11853 			return 0;
11854 	}
11855 
11856 	err = libbpf_ensure_mem((void **)&res->addrs, &res->cap, sizeof(*res->addrs), res->cnt + 1);
11857 	if (err)
11858 		return err;
11859 
11860 	res->addrs[res->cnt++] = (unsigned long)sym_addr;
11861 	return 0;
11862 }
11863 
11864 static int libbpf_available_kallsyms_parse(struct kprobe_multi_resolve *res)
11865 {
11866 	const char *available_functions_file = tracefs_available_filter_functions();
11867 	struct avail_kallsyms_data data;
11868 	char sym_name[500];
11869 	FILE *f;
11870 	int err = 0, ret, i;
11871 	char **syms = NULL;
11872 	size_t cap = 0, cnt = 0;
11873 
11874 	f = fopen(available_functions_file, "re");
11875 	if (!f) {
11876 		err = -errno;
11877 		pr_warn("failed to open %s: %s\n", available_functions_file, errstr(err));
11878 		return err;
11879 	}
11880 
11881 	while (true) {
11882 		char *name;
11883 
11884 		ret = fscanf(f, "%499s%*[^\n]\n", sym_name);
11885 		if (ret == EOF && feof(f))
11886 			break;
11887 
11888 		if (ret != 1) {
11889 			pr_warn("failed to parse available_filter_functions entry: %d\n", ret);
11890 			err = -EINVAL;
11891 			goto cleanup;
11892 		}
11893 
11894 		if (!glob_match(sym_name, res->pattern))
11895 			continue;
11896 
11897 		err = libbpf_ensure_mem((void **)&syms, &cap, sizeof(*syms), cnt + 1);
11898 		if (err)
11899 			goto cleanup;
11900 
11901 		name = strdup(sym_name);
11902 		if (!name) {
11903 			err = -errno;
11904 			goto cleanup;
11905 		}
11906 
11907 		syms[cnt++] = name;
11908 	}
11909 
11910 	/* no entries found, bail out */
11911 	if (cnt == 0) {
11912 		err = -ENOENT;
11913 		goto cleanup;
11914 	}
11915 
11916 	/* sort available functions */
11917 	qsort(syms, cnt, sizeof(*syms), avail_func_cmp);
11918 
11919 	data.syms = syms;
11920 	data.res = res;
11921 	data.cnt = cnt;
11922 	libbpf_kallsyms_parse(avail_kallsyms_cb, &data);
11923 
11924 	if (res->cnt == 0)
11925 		err = -ENOENT;
11926 
11927 cleanup:
11928 	for (i = 0; i < cnt; i++)
11929 		free((char *)syms[i]);
11930 	free(syms);
11931 
11932 	fclose(f);
11933 	return err;
11934 }
11935 
11936 static bool has_available_filter_functions_addrs(void)
11937 {
11938 	return access(tracefs_available_filter_functions_addrs(), R_OK) != -1;
11939 }
11940 
11941 static int libbpf_available_kprobes_parse(struct kprobe_multi_resolve *res)
11942 {
11943 	const char *available_path = tracefs_available_filter_functions_addrs();
11944 	char sym_name[500];
11945 	FILE *f;
11946 	int ret, err = 0;
11947 	unsigned long long sym_addr;
11948 
11949 	f = fopen(available_path, "re");
11950 	if (!f) {
11951 		err = -errno;
11952 		pr_warn("failed to open %s: %s\n", available_path, errstr(err));
11953 		return err;
11954 	}
11955 
11956 	while (true) {
11957 		ret = fscanf(f, "%llx %499s%*[^\n]\n", &sym_addr, sym_name);
11958 		if (ret == EOF && feof(f))
11959 			break;
11960 
11961 		if (ret != 2) {
11962 			pr_warn("failed to parse available_filter_functions_addrs entry: %d\n",
11963 				ret);
11964 			err = -EINVAL;
11965 			goto cleanup;
11966 		}
11967 
11968 		if (!glob_match(sym_name, res->pattern))
11969 			continue;
11970 
11971 		err = libbpf_ensure_mem((void **)&res->addrs, &res->cap,
11972 					sizeof(*res->addrs), res->cnt + 1);
11973 		if (err)
11974 			goto cleanup;
11975 
11976 		res->addrs[res->cnt++] = (unsigned long)sym_addr;
11977 	}
11978 
11979 	if (res->cnt == 0)
11980 		err = -ENOENT;
11981 
11982 cleanup:
11983 	fclose(f);
11984 	return err;
11985 }
11986 
11987 struct bpf_link *
11988 bpf_program__attach_kprobe_multi_opts(const struct bpf_program *prog,
11989 				      const char *pattern,
11990 				      const struct bpf_kprobe_multi_opts *opts)
11991 {
11992 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
11993 	struct kprobe_multi_resolve res = {
11994 		.pattern = pattern,
11995 	};
11996 	enum bpf_attach_type attach_type;
11997 	struct bpf_link *link = NULL;
11998 	const unsigned long *addrs;
11999 	int err, link_fd, prog_fd;
12000 	bool retprobe, session, unique_match;
12001 	const __u64 *cookies;
12002 	const char **syms;
12003 	size_t cnt;
12004 
12005 	if (!OPTS_VALID(opts, bpf_kprobe_multi_opts))
12006 		return libbpf_err_ptr(-EINVAL);
12007 
12008 	prog_fd = bpf_program__fd(prog);
12009 	if (prog_fd < 0) {
12010 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
12011 			prog->name);
12012 		return libbpf_err_ptr(-EINVAL);
12013 	}
12014 
12015 	syms    = OPTS_GET(opts, syms, false);
12016 	addrs   = OPTS_GET(opts, addrs, false);
12017 	cnt     = OPTS_GET(opts, cnt, false);
12018 	cookies = OPTS_GET(opts, cookies, false);
12019 	unique_match = OPTS_GET(opts, unique_match, false);
12020 
12021 	if (!pattern && !addrs && !syms)
12022 		return libbpf_err_ptr(-EINVAL);
12023 	if (pattern && (addrs || syms || cookies || cnt))
12024 		return libbpf_err_ptr(-EINVAL);
12025 	if (!pattern && !cnt)
12026 		return libbpf_err_ptr(-EINVAL);
12027 	if (!pattern && unique_match)
12028 		return libbpf_err_ptr(-EINVAL);
12029 	if (addrs && syms)
12030 		return libbpf_err_ptr(-EINVAL);
12031 
12032 	if (pattern) {
12033 		if (has_available_filter_functions_addrs())
12034 			err = libbpf_available_kprobes_parse(&res);
12035 		else
12036 			err = libbpf_available_kallsyms_parse(&res);
12037 		if (err)
12038 			goto error;
12039 
12040 		if (unique_match && res.cnt != 1) {
12041 			pr_warn("prog '%s': failed to find a unique match for '%s' (%zu matches)\n",
12042 				prog->name, pattern, res.cnt);
12043 			err = -EINVAL;
12044 			goto error;
12045 		}
12046 
12047 		addrs = res.addrs;
12048 		cnt = res.cnt;
12049 	}
12050 
12051 	retprobe = OPTS_GET(opts, retprobe, false);
12052 	session  = OPTS_GET(opts, session, false);
12053 
12054 	if (retprobe && session)
12055 		return libbpf_err_ptr(-EINVAL);
12056 
12057 	attach_type = session ? BPF_TRACE_KPROBE_SESSION : BPF_TRACE_KPROBE_MULTI;
12058 
12059 	lopts.kprobe_multi.syms = syms;
12060 	lopts.kprobe_multi.addrs = addrs;
12061 	lopts.kprobe_multi.cookies = cookies;
12062 	lopts.kprobe_multi.cnt = cnt;
12063 	lopts.kprobe_multi.flags = retprobe ? BPF_F_KPROBE_MULTI_RETURN : 0;
12064 
12065 	link = calloc(1, sizeof(*link));
12066 	if (!link) {
12067 		err = -ENOMEM;
12068 		goto error;
12069 	}
12070 	link->detach = &bpf_link__detach_fd;
12071 
12072 	link_fd = bpf_link_create(prog_fd, 0, attach_type, &lopts);
12073 	if (link_fd < 0) {
12074 		err = -errno;
12075 		pr_warn("prog '%s': failed to attach: %s\n",
12076 			prog->name, errstr(err));
12077 		goto error;
12078 	}
12079 	link->fd = link_fd;
12080 	free(res.addrs);
12081 	return link;
12082 
12083 error:
12084 	free(link);
12085 	free(res.addrs);
12086 	return libbpf_err_ptr(err);
12087 }
12088 
12089 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12090 {
12091 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts);
12092 	unsigned long offset = 0;
12093 	const char *func_name;
12094 	char *func;
12095 	int n;
12096 
12097 	*link = NULL;
12098 
12099 	/* no auto-attach for SEC("kprobe") and SEC("kretprobe") */
12100 	if (strcmp(prog->sec_name, "kprobe") == 0 || strcmp(prog->sec_name, "kretprobe") == 0)
12101 		return 0;
12102 
12103 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe/");
12104 	if (opts.retprobe)
12105 		func_name = prog->sec_name + sizeof("kretprobe/") - 1;
12106 	else
12107 		func_name = prog->sec_name + sizeof("kprobe/") - 1;
12108 
12109 	n = sscanf(func_name, "%m[a-zA-Z0-9_.]+%li", &func, &offset);
12110 	if (n < 1) {
12111 		pr_warn("kprobe name is invalid: %s\n", func_name);
12112 		return -EINVAL;
12113 	}
12114 	if (opts.retprobe && offset != 0) {
12115 		free(func);
12116 		pr_warn("kretprobes do not support offset specification\n");
12117 		return -EINVAL;
12118 	}
12119 
12120 	opts.offset = offset;
12121 	*link = bpf_program__attach_kprobe_opts(prog, func, &opts);
12122 	free(func);
12123 	return libbpf_get_error(*link);
12124 }
12125 
12126 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12127 {
12128 	LIBBPF_OPTS(bpf_ksyscall_opts, opts);
12129 	const char *syscall_name;
12130 
12131 	*link = NULL;
12132 
12133 	/* no auto-attach for SEC("ksyscall") and SEC("kretsyscall") */
12134 	if (strcmp(prog->sec_name, "ksyscall") == 0 || strcmp(prog->sec_name, "kretsyscall") == 0)
12135 		return 0;
12136 
12137 	opts.retprobe = str_has_pfx(prog->sec_name, "kretsyscall/");
12138 	if (opts.retprobe)
12139 		syscall_name = prog->sec_name + sizeof("kretsyscall/") - 1;
12140 	else
12141 		syscall_name = prog->sec_name + sizeof("ksyscall/") - 1;
12142 
12143 	*link = bpf_program__attach_ksyscall(prog, syscall_name, &opts);
12144 	return *link ? 0 : -errno;
12145 }
12146 
12147 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12148 {
12149 	LIBBPF_OPTS(bpf_kprobe_multi_opts, opts);
12150 	const char *spec;
12151 	char *pattern;
12152 	int n;
12153 
12154 	*link = NULL;
12155 
12156 	/* no auto-attach for SEC("kprobe.multi") and SEC("kretprobe.multi") */
12157 	if (strcmp(prog->sec_name, "kprobe.multi") == 0 ||
12158 	    strcmp(prog->sec_name, "kretprobe.multi") == 0)
12159 		return 0;
12160 
12161 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe.multi/");
12162 	if (opts.retprobe)
12163 		spec = prog->sec_name + sizeof("kretprobe.multi/") - 1;
12164 	else
12165 		spec = prog->sec_name + sizeof("kprobe.multi/") - 1;
12166 
12167 	n = sscanf(spec, "%m[a-zA-Z0-9_.*?]", &pattern);
12168 	if (n < 1) {
12169 		pr_warn("kprobe multi pattern is invalid: %s\n", spec);
12170 		return -EINVAL;
12171 	}
12172 
12173 	*link = bpf_program__attach_kprobe_multi_opts(prog, pattern, &opts);
12174 	free(pattern);
12175 	return libbpf_get_error(*link);
12176 }
12177 
12178 static int attach_kprobe_session(const struct bpf_program *prog, long cookie,
12179 				 struct bpf_link **link)
12180 {
12181 	LIBBPF_OPTS(bpf_kprobe_multi_opts, opts, .session = true);
12182 	const char *spec;
12183 	char *pattern;
12184 	int n;
12185 
12186 	*link = NULL;
12187 
12188 	/* no auto-attach for SEC("kprobe.session") */
12189 	if (strcmp(prog->sec_name, "kprobe.session") == 0)
12190 		return 0;
12191 
12192 	spec = prog->sec_name + sizeof("kprobe.session/") - 1;
12193 	n = sscanf(spec, "%m[a-zA-Z0-9_.*?]", &pattern);
12194 	if (n < 1) {
12195 		pr_warn("kprobe session pattern is invalid: %s\n", spec);
12196 		return -EINVAL;
12197 	}
12198 
12199 	*link = bpf_program__attach_kprobe_multi_opts(prog, pattern, &opts);
12200 	free(pattern);
12201 	return *link ? 0 : -errno;
12202 }
12203 
12204 static int attach_uprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12205 {
12206 	char *probe_type = NULL, *binary_path = NULL, *func_name = NULL;
12207 	LIBBPF_OPTS(bpf_uprobe_multi_opts, opts);
12208 	int n, ret = -EINVAL;
12209 
12210 	*link = NULL;
12211 
12212 	n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[^\n]",
12213 		   &probe_type, &binary_path, &func_name);
12214 	switch (n) {
12215 	case 1:
12216 		/* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
12217 		ret = 0;
12218 		break;
12219 	case 3:
12220 		opts.session = str_has_pfx(probe_type, "uprobe.session");
12221 		opts.retprobe = str_has_pfx(probe_type, "uretprobe.multi");
12222 
12223 		*link = bpf_program__attach_uprobe_multi(prog, -1, binary_path, func_name, &opts);
12224 		ret = libbpf_get_error(*link);
12225 		break;
12226 	default:
12227 		pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
12228 			prog->sec_name);
12229 		break;
12230 	}
12231 	free(probe_type);
12232 	free(binary_path);
12233 	free(func_name);
12234 	return ret;
12235 }
12236 
12237 static inline int add_uprobe_event_legacy(const char *probe_name, bool retprobe,
12238 					  const char *binary_path, size_t offset)
12239 {
12240 	return append_to_file(tracefs_uprobe_events(), "%c:%s/%s %s:0x%zx",
12241 			      retprobe ? 'r' : 'p',
12242 			      retprobe ? "uretprobes" : "uprobes",
12243 			      probe_name, binary_path, offset);
12244 }
12245 
12246 static inline int remove_uprobe_event_legacy(const char *probe_name, bool retprobe)
12247 {
12248 	return append_to_file(tracefs_uprobe_events(), "-:%s/%s",
12249 			      retprobe ? "uretprobes" : "uprobes", probe_name);
12250 }
12251 
12252 static int determine_uprobe_perf_type_legacy(const char *probe_name, bool retprobe)
12253 {
12254 	char file[512];
12255 
12256 	snprintf(file, sizeof(file), "%s/events/%s/%s/id",
12257 		 tracefs_path(), retprobe ? "uretprobes" : "uprobes", probe_name);
12258 
12259 	return parse_uint_from_file(file, "%d\n");
12260 }
12261 
12262 static int perf_event_uprobe_open_legacy(const char *probe_name, bool retprobe,
12263 					 const char *binary_path, size_t offset, int pid)
12264 {
12265 	const size_t attr_sz = sizeof(struct perf_event_attr);
12266 	struct perf_event_attr attr;
12267 	int type, pfd, err;
12268 
12269 	err = add_uprobe_event_legacy(probe_name, retprobe, binary_path, offset);
12270 	if (err < 0) {
12271 		pr_warn("failed to add legacy uprobe event for %s:0x%zx: %s\n",
12272 			binary_path, (size_t)offset, errstr(err));
12273 		return err;
12274 	}
12275 	type = determine_uprobe_perf_type_legacy(probe_name, retprobe);
12276 	if (type < 0) {
12277 		err = type;
12278 		pr_warn("failed to determine legacy uprobe event id for %s:0x%zx: %s\n",
12279 			binary_path, offset, errstr(err));
12280 		goto err_clean_legacy;
12281 	}
12282 
12283 	memset(&attr, 0, attr_sz);
12284 	attr.size = attr_sz;
12285 	attr.config = type;
12286 	attr.type = PERF_TYPE_TRACEPOINT;
12287 
12288 	pfd = syscall(__NR_perf_event_open, &attr,
12289 		      pid < 0 ? -1 : pid, /* pid */
12290 		      pid == -1 ? 0 : -1, /* cpu */
12291 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
12292 	if (pfd < 0) {
12293 		err = -errno;
12294 		pr_warn("legacy uprobe perf_event_open() failed: %s\n", errstr(err));
12295 		goto err_clean_legacy;
12296 	}
12297 	return pfd;
12298 
12299 err_clean_legacy:
12300 	/* Clear the newly added legacy uprobe_event */
12301 	remove_uprobe_event_legacy(probe_name, retprobe);
12302 	return err;
12303 }
12304 
12305 /* Find offset of function name in archive specified by path. Currently
12306  * supported are .zip files that do not compress their contents, as used on
12307  * Android in the form of APKs, for example. "file_name" is the name of the ELF
12308  * file inside the archive. "func_name" matches symbol name or name@@LIB for
12309  * library functions.
12310  *
12311  * An overview of the APK format specifically provided here:
12312  * https://en.wikipedia.org/w/index.php?title=Apk_(file_format)&oldid=1139099120#Package_contents
12313  */
12314 static long elf_find_func_offset_from_archive(const char *archive_path, const char *file_name,
12315 					      const char *func_name)
12316 {
12317 	struct zip_archive *archive;
12318 	struct zip_entry entry;
12319 	long ret;
12320 	Elf *elf;
12321 
12322 	archive = zip_archive_open(archive_path);
12323 	if (IS_ERR(archive)) {
12324 		ret = PTR_ERR(archive);
12325 		pr_warn("zip: failed to open %s: %ld\n", archive_path, ret);
12326 		return ret;
12327 	}
12328 
12329 	ret = zip_archive_find_entry(archive, file_name, &entry);
12330 	if (ret) {
12331 		pr_warn("zip: could not find archive member %s in %s: %ld\n", file_name,
12332 			archive_path, ret);
12333 		goto out;
12334 	}
12335 	pr_debug("zip: found entry for %s in %s at 0x%lx\n", file_name, archive_path,
12336 		 (unsigned long)entry.data_offset);
12337 
12338 	if (entry.compression) {
12339 		pr_warn("zip: entry %s of %s is compressed and cannot be handled\n", file_name,
12340 			archive_path);
12341 		ret = -LIBBPF_ERRNO__FORMAT;
12342 		goto out;
12343 	}
12344 
12345 	elf = elf_memory((void *)entry.data, entry.data_length);
12346 	if (!elf) {
12347 		pr_warn("elf: could not read elf file %s from %s: %s\n", file_name, archive_path,
12348 			elf_errmsg(-1));
12349 		ret = -LIBBPF_ERRNO__LIBELF;
12350 		goto out;
12351 	}
12352 
12353 	ret = elf_find_func_offset(elf, file_name, func_name);
12354 	if (ret > 0) {
12355 		pr_debug("elf: symbol address match for %s of %s in %s: 0x%x + 0x%lx = 0x%lx\n",
12356 			 func_name, file_name, archive_path, entry.data_offset, ret,
12357 			 ret + entry.data_offset);
12358 		ret += entry.data_offset;
12359 	}
12360 	elf_end(elf);
12361 
12362 out:
12363 	zip_archive_close(archive);
12364 	return ret;
12365 }
12366 
12367 static const char *arch_specific_lib_paths(void)
12368 {
12369 	/*
12370 	 * Based on https://packages.debian.org/sid/libc6.
12371 	 *
12372 	 * Assume that the traced program is built for the same architecture
12373 	 * as libbpf, which should cover the vast majority of cases.
12374 	 */
12375 #if defined(__x86_64__)
12376 	return "/lib/x86_64-linux-gnu";
12377 #elif defined(__i386__)
12378 	return "/lib/i386-linux-gnu";
12379 #elif defined(__s390x__)
12380 	return "/lib/s390x-linux-gnu";
12381 #elif defined(__arm__) && defined(__SOFTFP__)
12382 	return "/lib/arm-linux-gnueabi";
12383 #elif defined(__arm__) && !defined(__SOFTFP__)
12384 	return "/lib/arm-linux-gnueabihf";
12385 #elif defined(__aarch64__)
12386 	return "/lib/aarch64-linux-gnu";
12387 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 64
12388 	return "/lib/mips64el-linux-gnuabi64";
12389 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 32
12390 	return "/lib/mipsel-linux-gnu";
12391 #elif defined(__powerpc64__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
12392 	return "/lib/powerpc64le-linux-gnu";
12393 #elif defined(__sparc__) && defined(__arch64__)
12394 	return "/lib/sparc64-linux-gnu";
12395 #elif defined(__riscv) && __riscv_xlen == 64
12396 	return "/lib/riscv64-linux-gnu";
12397 #else
12398 	return NULL;
12399 #endif
12400 }
12401 
12402 /* Get full path to program/shared library. */
12403 static int resolve_full_path(const char *file, char *result, size_t result_sz)
12404 {
12405 	const char *search_paths[3] = {};
12406 	int i, perm;
12407 
12408 	if (str_has_sfx(file, ".so") || strstr(file, ".so.")) {
12409 		search_paths[0] = getenv("LD_LIBRARY_PATH");
12410 		search_paths[1] = "/usr/lib64:/usr/lib";
12411 		search_paths[2] = arch_specific_lib_paths();
12412 		perm = R_OK;
12413 	} else {
12414 		search_paths[0] = getenv("PATH");
12415 		search_paths[1] = "/usr/bin:/usr/sbin";
12416 		perm = R_OK | X_OK;
12417 	}
12418 
12419 	for (i = 0; i < ARRAY_SIZE(search_paths); i++) {
12420 		const char *s;
12421 
12422 		if (!search_paths[i])
12423 			continue;
12424 		for (s = search_paths[i]; s != NULL; s = strchr(s, ':')) {
12425 			const char *next_path;
12426 			int seg_len;
12427 
12428 			if (s[0] == ':')
12429 				s++;
12430 			next_path = strchr(s, ':');
12431 			seg_len = next_path ? next_path - s : strlen(s);
12432 			if (!seg_len)
12433 				continue;
12434 			snprintf(result, result_sz, "%.*s/%s", seg_len, s, file);
12435 			/* ensure it has required permissions */
12436 			if (faccessat(AT_FDCWD, result, perm, AT_EACCESS) < 0)
12437 				continue;
12438 			pr_debug("resolved '%s' to '%s'\n", file, result);
12439 			return 0;
12440 		}
12441 	}
12442 	return -ENOENT;
12443 }
12444 
12445 struct bpf_link *
12446 bpf_program__attach_uprobe_multi(const struct bpf_program *prog,
12447 				 pid_t pid,
12448 				 const char *path,
12449 				 const char *func_pattern,
12450 				 const struct bpf_uprobe_multi_opts *opts)
12451 {
12452 	const unsigned long *ref_ctr_offsets = NULL, *offsets = NULL;
12453 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
12454 	unsigned long *resolved_offsets = NULL;
12455 	enum bpf_attach_type attach_type;
12456 	int err = 0, link_fd, prog_fd;
12457 	struct bpf_link *link = NULL;
12458 	char full_path[PATH_MAX];
12459 	bool retprobe, session;
12460 	const __u64 *cookies;
12461 	const char **syms;
12462 	size_t cnt;
12463 
12464 	if (!OPTS_VALID(opts, bpf_uprobe_multi_opts))
12465 		return libbpf_err_ptr(-EINVAL);
12466 
12467 	prog_fd = bpf_program__fd(prog);
12468 	if (prog_fd < 0) {
12469 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
12470 			prog->name);
12471 		return libbpf_err_ptr(-EINVAL);
12472 	}
12473 
12474 	syms = OPTS_GET(opts, syms, NULL);
12475 	offsets = OPTS_GET(opts, offsets, NULL);
12476 	ref_ctr_offsets = OPTS_GET(opts, ref_ctr_offsets, NULL);
12477 	cookies = OPTS_GET(opts, cookies, NULL);
12478 	cnt = OPTS_GET(opts, cnt, 0);
12479 	retprobe = OPTS_GET(opts, retprobe, false);
12480 	session  = OPTS_GET(opts, session, false);
12481 
12482 	/*
12483 	 * User can specify 2 mutually exclusive set of inputs:
12484 	 *
12485 	 * 1) use only path/func_pattern/pid arguments
12486 	 *
12487 	 * 2) use path/pid with allowed combinations of:
12488 	 *    syms/offsets/ref_ctr_offsets/cookies/cnt
12489 	 *
12490 	 *    - syms and offsets are mutually exclusive
12491 	 *    - ref_ctr_offsets and cookies are optional
12492 	 *
12493 	 * Any other usage results in error.
12494 	 */
12495 
12496 	if (!path)
12497 		return libbpf_err_ptr(-EINVAL);
12498 	if (!func_pattern && cnt == 0)
12499 		return libbpf_err_ptr(-EINVAL);
12500 
12501 	if (func_pattern) {
12502 		if (syms || offsets || ref_ctr_offsets || cookies || cnt)
12503 			return libbpf_err_ptr(-EINVAL);
12504 	} else {
12505 		if (!!syms == !!offsets)
12506 			return libbpf_err_ptr(-EINVAL);
12507 	}
12508 
12509 	if (retprobe && session)
12510 		return libbpf_err_ptr(-EINVAL);
12511 
12512 	if (func_pattern) {
12513 		if (!strchr(path, '/')) {
12514 			err = resolve_full_path(path, full_path, sizeof(full_path));
12515 			if (err) {
12516 				pr_warn("prog '%s': failed to resolve full path for '%s': %s\n",
12517 					prog->name, path, errstr(err));
12518 				return libbpf_err_ptr(err);
12519 			}
12520 			path = full_path;
12521 		}
12522 
12523 		err = elf_resolve_pattern_offsets(path, func_pattern,
12524 						  &resolved_offsets, &cnt);
12525 		if (err < 0)
12526 			return libbpf_err_ptr(err);
12527 		offsets = resolved_offsets;
12528 	} else if (syms) {
12529 		err = elf_resolve_syms_offsets(path, cnt, syms, &resolved_offsets, STT_FUNC);
12530 		if (err < 0)
12531 			return libbpf_err_ptr(err);
12532 		offsets = resolved_offsets;
12533 	}
12534 
12535 	attach_type = session ? BPF_TRACE_UPROBE_SESSION : BPF_TRACE_UPROBE_MULTI;
12536 
12537 	lopts.uprobe_multi.path = path;
12538 	lopts.uprobe_multi.offsets = offsets;
12539 	lopts.uprobe_multi.ref_ctr_offsets = ref_ctr_offsets;
12540 	lopts.uprobe_multi.cookies = cookies;
12541 	lopts.uprobe_multi.cnt = cnt;
12542 	lopts.uprobe_multi.flags = retprobe ? BPF_F_UPROBE_MULTI_RETURN : 0;
12543 
12544 	if (pid == 0)
12545 		pid = getpid();
12546 	if (pid > 0)
12547 		lopts.uprobe_multi.pid = pid;
12548 
12549 	link = calloc(1, sizeof(*link));
12550 	if (!link) {
12551 		err = -ENOMEM;
12552 		goto error;
12553 	}
12554 	link->detach = &bpf_link__detach_fd;
12555 
12556 	link_fd = bpf_link_create(prog_fd, 0, attach_type, &lopts);
12557 	if (link_fd < 0) {
12558 		err = -errno;
12559 		pr_warn("prog '%s': failed to attach multi-uprobe: %s\n",
12560 			prog->name, errstr(err));
12561 		goto error;
12562 	}
12563 	link->fd = link_fd;
12564 	free(resolved_offsets);
12565 	return link;
12566 
12567 error:
12568 	free(resolved_offsets);
12569 	free(link);
12570 	return libbpf_err_ptr(err);
12571 }
12572 
12573 LIBBPF_API struct bpf_link *
12574 bpf_program__attach_uprobe_opts(const struct bpf_program *prog, pid_t pid,
12575 				const char *binary_path, size_t func_offset,
12576 				const struct bpf_uprobe_opts *opts)
12577 {
12578 	const char *archive_path = NULL, *archive_sep = NULL;
12579 	char *legacy_probe = NULL;
12580 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
12581 	enum probe_attach_mode attach_mode;
12582 	char full_path[PATH_MAX];
12583 	struct bpf_link *link;
12584 	size_t ref_ctr_off;
12585 	int pfd, err;
12586 	bool retprobe, legacy;
12587 	const char *func_name;
12588 
12589 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
12590 		return libbpf_err_ptr(-EINVAL);
12591 
12592 	attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
12593 	retprobe = OPTS_GET(opts, retprobe, false);
12594 	ref_ctr_off = OPTS_GET(opts, ref_ctr_offset, 0);
12595 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
12596 
12597 	if (!binary_path)
12598 		return libbpf_err_ptr(-EINVAL);
12599 
12600 	/* Check if "binary_path" refers to an archive. */
12601 	archive_sep = strstr(binary_path, "!/");
12602 	if (archive_sep) {
12603 		full_path[0] = '\0';
12604 		libbpf_strlcpy(full_path, binary_path,
12605 			       min(sizeof(full_path), (size_t)(archive_sep - binary_path + 1)));
12606 		archive_path = full_path;
12607 		binary_path = archive_sep + 2;
12608 	} else if (!strchr(binary_path, '/')) {
12609 		err = resolve_full_path(binary_path, full_path, sizeof(full_path));
12610 		if (err) {
12611 			pr_warn("prog '%s': failed to resolve full path for '%s': %s\n",
12612 				prog->name, binary_path, errstr(err));
12613 			return libbpf_err_ptr(err);
12614 		}
12615 		binary_path = full_path;
12616 	}
12617 	func_name = OPTS_GET(opts, func_name, NULL);
12618 	if (func_name) {
12619 		long sym_off;
12620 
12621 		if (archive_path) {
12622 			sym_off = elf_find_func_offset_from_archive(archive_path, binary_path,
12623 								    func_name);
12624 			binary_path = archive_path;
12625 		} else {
12626 			sym_off = elf_find_func_offset_from_file(binary_path, func_name);
12627 		}
12628 		if (sym_off < 0)
12629 			return libbpf_err_ptr(sym_off);
12630 		func_offset += sym_off;
12631 	}
12632 
12633 	legacy = determine_uprobe_perf_type() < 0;
12634 	switch (attach_mode) {
12635 	case PROBE_ATTACH_MODE_LEGACY:
12636 		legacy = true;
12637 		pe_opts.force_ioctl_attach = true;
12638 		break;
12639 	case PROBE_ATTACH_MODE_PERF:
12640 		if (legacy)
12641 			return libbpf_err_ptr(-ENOTSUP);
12642 		pe_opts.force_ioctl_attach = true;
12643 		break;
12644 	case PROBE_ATTACH_MODE_LINK:
12645 		if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
12646 			return libbpf_err_ptr(-ENOTSUP);
12647 		break;
12648 	case PROBE_ATTACH_MODE_DEFAULT:
12649 		break;
12650 	default:
12651 		return libbpf_err_ptr(-EINVAL);
12652 	}
12653 
12654 	if (!legacy) {
12655 		pfd = perf_event_open_probe(true /* uprobe */, retprobe, binary_path,
12656 					    func_offset, pid, ref_ctr_off);
12657 	} else {
12658 		char probe_name[MAX_EVENT_NAME_LEN];
12659 
12660 		if (ref_ctr_off)
12661 			return libbpf_err_ptr(-EINVAL);
12662 
12663 		gen_probe_legacy_event_name(probe_name, sizeof(probe_name),
12664 					    strrchr(binary_path, '/') ? : binary_path,
12665 					    func_offset);
12666 
12667 		legacy_probe = strdup(probe_name);
12668 		if (!legacy_probe)
12669 			return libbpf_err_ptr(-ENOMEM);
12670 
12671 		pfd = perf_event_uprobe_open_legacy(legacy_probe, retprobe,
12672 						    binary_path, func_offset, pid);
12673 	}
12674 	if (pfd < 0) {
12675 		err = -errno;
12676 		pr_warn("prog '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
12677 			prog->name, retprobe ? "uretprobe" : "uprobe",
12678 			binary_path, func_offset,
12679 			errstr(err));
12680 		goto err_out;
12681 	}
12682 
12683 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
12684 	err = libbpf_get_error(link);
12685 	if (err) {
12686 		close(pfd);
12687 		pr_warn("prog '%s': failed to attach to %s '%s:0x%zx': %s\n",
12688 			prog->name, retprobe ? "uretprobe" : "uprobe",
12689 			binary_path, func_offset,
12690 			errstr(err));
12691 		goto err_clean_legacy;
12692 	}
12693 	if (legacy) {
12694 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
12695 
12696 		perf_link->legacy_probe_name = legacy_probe;
12697 		perf_link->legacy_is_kprobe = false;
12698 		perf_link->legacy_is_retprobe = retprobe;
12699 	}
12700 	return link;
12701 
12702 err_clean_legacy:
12703 	if (legacy)
12704 		remove_uprobe_event_legacy(legacy_probe, retprobe);
12705 err_out:
12706 	free(legacy_probe);
12707 	return libbpf_err_ptr(err);
12708 }
12709 
12710 /* Format of u[ret]probe section definition supporting auto-attach:
12711  * u[ret]probe/binary:function[+offset]
12712  *
12713  * binary can be an absolute/relative path or a filename; the latter is resolved to a
12714  * full binary path via bpf_program__attach_uprobe_opts.
12715  *
12716  * Specifying uprobe+ ensures we carry out strict matching; either "uprobe" must be
12717  * specified (and auto-attach is not possible) or the above format is specified for
12718  * auto-attach.
12719  */
12720 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12721 {
12722 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts);
12723 	char *probe_type = NULL, *binary_path = NULL, *func_name = NULL, *func_off;
12724 	int n, c, ret = -EINVAL;
12725 	long offset = 0;
12726 
12727 	*link = NULL;
12728 
12729 	n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[^\n]",
12730 		   &probe_type, &binary_path, &func_name);
12731 	switch (n) {
12732 	case 1:
12733 		/* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
12734 		ret = 0;
12735 		break;
12736 	case 2:
12737 		pr_warn("prog '%s': section '%s' missing ':function[+offset]' specification\n",
12738 			prog->name, prog->sec_name);
12739 		break;
12740 	case 3:
12741 		/* check if user specifies `+offset`, if yes, this should be
12742 		 * the last part of the string, make sure sscanf read to EOL
12743 		 */
12744 		func_off = strrchr(func_name, '+');
12745 		if (func_off) {
12746 			n = sscanf(func_off, "+%li%n", &offset, &c);
12747 			if (n == 1 && *(func_off + c) == '\0')
12748 				func_off[0] = '\0';
12749 			else
12750 				offset = 0;
12751 		}
12752 		opts.retprobe = strcmp(probe_type, "uretprobe") == 0 ||
12753 				strcmp(probe_type, "uretprobe.s") == 0;
12754 		if (opts.retprobe && offset != 0) {
12755 			pr_warn("prog '%s': uretprobes do not support offset specification\n",
12756 				prog->name);
12757 			break;
12758 		}
12759 		opts.func_name = func_name;
12760 		*link = bpf_program__attach_uprobe_opts(prog, -1, binary_path, offset, &opts);
12761 		ret = libbpf_get_error(*link);
12762 		break;
12763 	default:
12764 		pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
12765 			prog->sec_name);
12766 		break;
12767 	}
12768 	free(probe_type);
12769 	free(binary_path);
12770 	free(func_name);
12771 
12772 	return ret;
12773 }
12774 
12775 struct bpf_link *bpf_program__attach_uprobe(const struct bpf_program *prog,
12776 					    bool retprobe, pid_t pid,
12777 					    const char *binary_path,
12778 					    size_t func_offset)
12779 {
12780 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts, .retprobe = retprobe);
12781 
12782 	return bpf_program__attach_uprobe_opts(prog, pid, binary_path, func_offset, &opts);
12783 }
12784 
12785 struct bpf_link *bpf_program__attach_usdt(const struct bpf_program *prog,
12786 					  pid_t pid, const char *binary_path,
12787 					  const char *usdt_provider, const char *usdt_name,
12788 					  const struct bpf_usdt_opts *opts)
12789 {
12790 	char resolved_path[512];
12791 	struct bpf_object *obj = prog->obj;
12792 	struct bpf_link *link;
12793 	__u64 usdt_cookie;
12794 	int err;
12795 
12796 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
12797 		return libbpf_err_ptr(-EINVAL);
12798 
12799 	if (bpf_program__fd(prog) < 0) {
12800 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
12801 			prog->name);
12802 		return libbpf_err_ptr(-EINVAL);
12803 	}
12804 
12805 	if (!binary_path)
12806 		return libbpf_err_ptr(-EINVAL);
12807 
12808 	if (!strchr(binary_path, '/')) {
12809 		err = resolve_full_path(binary_path, resolved_path, sizeof(resolved_path));
12810 		if (err) {
12811 			pr_warn("prog '%s': failed to resolve full path for '%s': %s\n",
12812 				prog->name, binary_path, errstr(err));
12813 			return libbpf_err_ptr(err);
12814 		}
12815 		binary_path = resolved_path;
12816 	}
12817 
12818 	/* USDT manager is instantiated lazily on first USDT attach. It will
12819 	 * be destroyed together with BPF object in bpf_object__close().
12820 	 */
12821 	if (IS_ERR(obj->usdt_man))
12822 		return libbpf_ptr(obj->usdt_man);
12823 	if (!obj->usdt_man) {
12824 		obj->usdt_man = usdt_manager_new(obj);
12825 		if (IS_ERR(obj->usdt_man))
12826 			return libbpf_ptr(obj->usdt_man);
12827 	}
12828 
12829 	usdt_cookie = OPTS_GET(opts, usdt_cookie, 0);
12830 	link = usdt_manager_attach_usdt(obj->usdt_man, prog, pid, binary_path,
12831 					usdt_provider, usdt_name, usdt_cookie);
12832 	err = libbpf_get_error(link);
12833 	if (err)
12834 		return libbpf_err_ptr(err);
12835 	return link;
12836 }
12837 
12838 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12839 {
12840 	char *path = NULL, *provider = NULL, *name = NULL;
12841 	const char *sec_name;
12842 	int n, err;
12843 
12844 	sec_name = bpf_program__section_name(prog);
12845 	if (strcmp(sec_name, "usdt") == 0) {
12846 		/* no auto-attach for just SEC("usdt") */
12847 		*link = NULL;
12848 		return 0;
12849 	}
12850 
12851 	n = sscanf(sec_name, "usdt/%m[^:]:%m[^:]:%m[^:]", &path, &provider, &name);
12852 	if (n != 3) {
12853 		pr_warn("invalid section '%s', expected SEC(\"usdt/<path>:<provider>:<name>\")\n",
12854 			sec_name);
12855 		err = -EINVAL;
12856 	} else {
12857 		*link = bpf_program__attach_usdt(prog, -1 /* any process */, path,
12858 						 provider, name, NULL);
12859 		err = libbpf_get_error(*link);
12860 	}
12861 	free(path);
12862 	free(provider);
12863 	free(name);
12864 	return err;
12865 }
12866 
12867 static int determine_tracepoint_id(const char *tp_category,
12868 				   const char *tp_name)
12869 {
12870 	char file[PATH_MAX];
12871 	int ret;
12872 
12873 	ret = snprintf(file, sizeof(file), "%s/events/%s/%s/id",
12874 		       tracefs_path(), tp_category, tp_name);
12875 	if (ret < 0)
12876 		return -errno;
12877 	if (ret >= sizeof(file)) {
12878 		pr_debug("tracepoint %s/%s path is too long\n",
12879 			 tp_category, tp_name);
12880 		return -E2BIG;
12881 	}
12882 	return parse_uint_from_file(file, "%d\n");
12883 }
12884 
12885 static int perf_event_open_tracepoint(const char *tp_category,
12886 				      const char *tp_name)
12887 {
12888 	const size_t attr_sz = sizeof(struct perf_event_attr);
12889 	struct perf_event_attr attr;
12890 	int tp_id, pfd, err;
12891 
12892 	tp_id = determine_tracepoint_id(tp_category, tp_name);
12893 	if (tp_id < 0) {
12894 		pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
12895 			tp_category, tp_name,
12896 			errstr(tp_id));
12897 		return tp_id;
12898 	}
12899 
12900 	memset(&attr, 0, attr_sz);
12901 	attr.type = PERF_TYPE_TRACEPOINT;
12902 	attr.size = attr_sz;
12903 	attr.config = tp_id;
12904 
12905 	pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
12906 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
12907 	if (pfd < 0) {
12908 		err = -errno;
12909 		pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
12910 			tp_category, tp_name,
12911 			errstr(err));
12912 		return err;
12913 	}
12914 	return pfd;
12915 }
12916 
12917 struct bpf_link *bpf_program__attach_tracepoint_opts(const struct bpf_program *prog,
12918 						     const char *tp_category,
12919 						     const char *tp_name,
12920 						     const struct bpf_tracepoint_opts *opts)
12921 {
12922 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
12923 	struct bpf_link *link;
12924 	int pfd, err;
12925 
12926 	if (!OPTS_VALID(opts, bpf_tracepoint_opts))
12927 		return libbpf_err_ptr(-EINVAL);
12928 
12929 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
12930 
12931 	pfd = perf_event_open_tracepoint(tp_category, tp_name);
12932 	if (pfd < 0) {
12933 		pr_warn("prog '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
12934 			prog->name, tp_category, tp_name,
12935 			errstr(pfd));
12936 		return libbpf_err_ptr(pfd);
12937 	}
12938 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
12939 	err = libbpf_get_error(link);
12940 	if (err) {
12941 		close(pfd);
12942 		pr_warn("prog '%s': failed to attach to tracepoint '%s/%s': %s\n",
12943 			prog->name, tp_category, tp_name,
12944 			errstr(err));
12945 		return libbpf_err_ptr(err);
12946 	}
12947 	return link;
12948 }
12949 
12950 struct bpf_link *bpf_program__attach_tracepoint(const struct bpf_program *prog,
12951 						const char *tp_category,
12952 						const char *tp_name)
12953 {
12954 	return bpf_program__attach_tracepoint_opts(prog, tp_category, tp_name, NULL);
12955 }
12956 
12957 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12958 {
12959 	char *sec_name, *tp_cat, *tp_name;
12960 
12961 	*link = NULL;
12962 
12963 	/* no auto-attach for SEC("tp") or SEC("tracepoint") */
12964 	if (strcmp(prog->sec_name, "tp") == 0 || strcmp(prog->sec_name, "tracepoint") == 0)
12965 		return 0;
12966 
12967 	sec_name = strdup(prog->sec_name);
12968 	if (!sec_name)
12969 		return -ENOMEM;
12970 
12971 	/* extract "tp/<category>/<name>" or "tracepoint/<category>/<name>" */
12972 	if (str_has_pfx(prog->sec_name, "tp/"))
12973 		tp_cat = sec_name + sizeof("tp/") - 1;
12974 	else
12975 		tp_cat = sec_name + sizeof("tracepoint/") - 1;
12976 	tp_name = strchr(tp_cat, '/');
12977 	if (!tp_name) {
12978 		free(sec_name);
12979 		return -EINVAL;
12980 	}
12981 	*tp_name = '\0';
12982 	tp_name++;
12983 
12984 	*link = bpf_program__attach_tracepoint(prog, tp_cat, tp_name);
12985 	free(sec_name);
12986 	return libbpf_get_error(*link);
12987 }
12988 
12989 struct bpf_link *
12990 bpf_program__attach_raw_tracepoint_opts(const struct bpf_program *prog,
12991 					const char *tp_name,
12992 					struct bpf_raw_tracepoint_opts *opts)
12993 {
12994 	LIBBPF_OPTS(bpf_raw_tp_opts, raw_opts);
12995 	struct bpf_link *link;
12996 	int prog_fd, pfd;
12997 
12998 	if (!OPTS_VALID(opts, bpf_raw_tracepoint_opts))
12999 		return libbpf_err_ptr(-EINVAL);
13000 
13001 	prog_fd = bpf_program__fd(prog);
13002 	if (prog_fd < 0) {
13003 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
13004 		return libbpf_err_ptr(-EINVAL);
13005 	}
13006 
13007 	link = calloc(1, sizeof(*link));
13008 	if (!link)
13009 		return libbpf_err_ptr(-ENOMEM);
13010 	link->detach = &bpf_link__detach_fd;
13011 
13012 	raw_opts.tp_name = tp_name;
13013 	raw_opts.cookie = OPTS_GET(opts, cookie, 0);
13014 	pfd = bpf_raw_tracepoint_open_opts(prog_fd, &raw_opts);
13015 	if (pfd < 0) {
13016 		pfd = -errno;
13017 		free(link);
13018 		pr_warn("prog '%s': failed to attach to raw tracepoint '%s': %s\n",
13019 			prog->name, tp_name, errstr(pfd));
13020 		return libbpf_err_ptr(pfd);
13021 	}
13022 	link->fd = pfd;
13023 	return link;
13024 }
13025 
13026 struct bpf_link *bpf_program__attach_raw_tracepoint(const struct bpf_program *prog,
13027 						    const char *tp_name)
13028 {
13029 	return bpf_program__attach_raw_tracepoint_opts(prog, tp_name, NULL);
13030 }
13031 
13032 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
13033 {
13034 	static const char *const prefixes[] = {
13035 		"raw_tp",
13036 		"raw_tracepoint",
13037 		"raw_tp.w",
13038 		"raw_tracepoint.w",
13039 	};
13040 	size_t i;
13041 	const char *tp_name = NULL;
13042 
13043 	*link = NULL;
13044 
13045 	for (i = 0; i < ARRAY_SIZE(prefixes); i++) {
13046 		size_t pfx_len;
13047 
13048 		if (!str_has_pfx(prog->sec_name, prefixes[i]))
13049 			continue;
13050 
13051 		pfx_len = strlen(prefixes[i]);
13052 		/* no auto-attach case of, e.g., SEC("raw_tp") */
13053 		if (prog->sec_name[pfx_len] == '\0')
13054 			return 0;
13055 
13056 		if (prog->sec_name[pfx_len] != '/')
13057 			continue;
13058 
13059 		tp_name = prog->sec_name + pfx_len + 1;
13060 		break;
13061 	}
13062 
13063 	if (!tp_name) {
13064 		pr_warn("prog '%s': invalid section name '%s'\n",
13065 			prog->name, prog->sec_name);
13066 		return -EINVAL;
13067 	}
13068 
13069 	*link = bpf_program__attach_raw_tracepoint(prog, tp_name);
13070 	return libbpf_get_error(*link);
13071 }
13072 
13073 /* Common logic for all BPF program types that attach to a btf_id */
13074 static struct bpf_link *bpf_program__attach_btf_id(const struct bpf_program *prog,
13075 						   const struct bpf_trace_opts *opts)
13076 {
13077 	LIBBPF_OPTS(bpf_link_create_opts, link_opts);
13078 	struct bpf_link *link;
13079 	int prog_fd, pfd;
13080 
13081 	if (!OPTS_VALID(opts, bpf_trace_opts))
13082 		return libbpf_err_ptr(-EINVAL);
13083 
13084 	prog_fd = bpf_program__fd(prog);
13085 	if (prog_fd < 0) {
13086 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
13087 		return libbpf_err_ptr(-EINVAL);
13088 	}
13089 
13090 	link = calloc(1, sizeof(*link));
13091 	if (!link)
13092 		return libbpf_err_ptr(-ENOMEM);
13093 	link->detach = &bpf_link__detach_fd;
13094 
13095 	/* libbpf is smart enough to redirect to BPF_RAW_TRACEPOINT_OPEN on old kernels */
13096 	link_opts.tracing.cookie = OPTS_GET(opts, cookie, 0);
13097 	pfd = bpf_link_create(prog_fd, 0, bpf_program__expected_attach_type(prog), &link_opts);
13098 	if (pfd < 0) {
13099 		pfd = -errno;
13100 		free(link);
13101 		pr_warn("prog '%s': failed to attach: %s\n",
13102 			prog->name, errstr(pfd));
13103 		return libbpf_err_ptr(pfd);
13104 	}
13105 	link->fd = pfd;
13106 	return link;
13107 }
13108 
13109 struct bpf_link *bpf_program__attach_trace(const struct bpf_program *prog)
13110 {
13111 	return bpf_program__attach_btf_id(prog, NULL);
13112 }
13113 
13114 struct bpf_link *bpf_program__attach_trace_opts(const struct bpf_program *prog,
13115 						const struct bpf_trace_opts *opts)
13116 {
13117 	return bpf_program__attach_btf_id(prog, opts);
13118 }
13119 
13120 struct bpf_link *bpf_program__attach_lsm(const struct bpf_program *prog)
13121 {
13122 	return bpf_program__attach_btf_id(prog, NULL);
13123 }
13124 
13125 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link)
13126 {
13127 	*link = bpf_program__attach_trace(prog);
13128 	return libbpf_get_error(*link);
13129 }
13130 
13131 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link)
13132 {
13133 	*link = bpf_program__attach_lsm(prog);
13134 	return libbpf_get_error(*link);
13135 }
13136 
13137 static struct bpf_link *
13138 bpf_program_attach_fd(const struct bpf_program *prog,
13139 		      int target_fd, const char *target_name,
13140 		      const struct bpf_link_create_opts *opts)
13141 {
13142 	enum bpf_attach_type attach_type;
13143 	struct bpf_link *link;
13144 	int prog_fd, link_fd;
13145 
13146 	prog_fd = bpf_program__fd(prog);
13147 	if (prog_fd < 0) {
13148 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
13149 		return libbpf_err_ptr(-EINVAL);
13150 	}
13151 
13152 	link = calloc(1, sizeof(*link));
13153 	if (!link)
13154 		return libbpf_err_ptr(-ENOMEM);
13155 	link->detach = &bpf_link__detach_fd;
13156 
13157 	attach_type = bpf_program__expected_attach_type(prog);
13158 	link_fd = bpf_link_create(prog_fd, target_fd, attach_type, opts);
13159 	if (link_fd < 0) {
13160 		link_fd = -errno;
13161 		free(link);
13162 		pr_warn("prog '%s': failed to attach to %s: %s\n",
13163 			prog->name, target_name,
13164 			errstr(link_fd));
13165 		return libbpf_err_ptr(link_fd);
13166 	}
13167 	link->fd = link_fd;
13168 	return link;
13169 }
13170 
13171 struct bpf_link *
13172 bpf_program__attach_cgroup(const struct bpf_program *prog, int cgroup_fd)
13173 {
13174 	return bpf_program_attach_fd(prog, cgroup_fd, "cgroup", NULL);
13175 }
13176 
13177 struct bpf_link *
13178 bpf_program__attach_netns(const struct bpf_program *prog, int netns_fd)
13179 {
13180 	return bpf_program_attach_fd(prog, netns_fd, "netns", NULL);
13181 }
13182 
13183 struct bpf_link *
13184 bpf_program__attach_sockmap(const struct bpf_program *prog, int map_fd)
13185 {
13186 	return bpf_program_attach_fd(prog, map_fd, "sockmap", NULL);
13187 }
13188 
13189 struct bpf_link *bpf_program__attach_xdp(const struct bpf_program *prog, int ifindex)
13190 {
13191 	/* target_fd/target_ifindex use the same field in LINK_CREATE */
13192 	return bpf_program_attach_fd(prog, ifindex, "xdp", NULL);
13193 }
13194 
13195 struct bpf_link *
13196 bpf_program__attach_cgroup_opts(const struct bpf_program *prog, int cgroup_fd,
13197 				const struct bpf_cgroup_opts *opts)
13198 {
13199 	LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
13200 	__u32 relative_id;
13201 	int relative_fd;
13202 
13203 	if (!OPTS_VALID(opts, bpf_cgroup_opts))
13204 		return libbpf_err_ptr(-EINVAL);
13205 
13206 	relative_id = OPTS_GET(opts, relative_id, 0);
13207 	relative_fd = OPTS_GET(opts, relative_fd, 0);
13208 
13209 	if (relative_fd && relative_id) {
13210 		pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
13211 			prog->name);
13212 		return libbpf_err_ptr(-EINVAL);
13213 	}
13214 
13215 	link_create_opts.cgroup.expected_revision = OPTS_GET(opts, expected_revision, 0);
13216 	link_create_opts.cgroup.relative_fd = relative_fd;
13217 	link_create_opts.cgroup.relative_id = relative_id;
13218 	link_create_opts.flags = OPTS_GET(opts, flags, 0);
13219 
13220 	return bpf_program_attach_fd(prog, cgroup_fd, "cgroup", &link_create_opts);
13221 }
13222 
13223 struct bpf_link *
13224 bpf_program__attach_tcx(const struct bpf_program *prog, int ifindex,
13225 			const struct bpf_tcx_opts *opts)
13226 {
13227 	LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
13228 	__u32 relative_id;
13229 	int relative_fd;
13230 
13231 	if (!OPTS_VALID(opts, bpf_tcx_opts))
13232 		return libbpf_err_ptr(-EINVAL);
13233 
13234 	relative_id = OPTS_GET(opts, relative_id, 0);
13235 	relative_fd = OPTS_GET(opts, relative_fd, 0);
13236 
13237 	/* validate we don't have unexpected combinations of non-zero fields */
13238 	if (!ifindex) {
13239 		pr_warn("prog '%s': target netdevice ifindex cannot be zero\n",
13240 			prog->name);
13241 		return libbpf_err_ptr(-EINVAL);
13242 	}
13243 	if (relative_fd && relative_id) {
13244 		pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
13245 			prog->name);
13246 		return libbpf_err_ptr(-EINVAL);
13247 	}
13248 
13249 	link_create_opts.tcx.expected_revision = OPTS_GET(opts, expected_revision, 0);
13250 	link_create_opts.tcx.relative_fd = relative_fd;
13251 	link_create_opts.tcx.relative_id = relative_id;
13252 	link_create_opts.flags = OPTS_GET(opts, flags, 0);
13253 
13254 	/* target_fd/target_ifindex use the same field in LINK_CREATE */
13255 	return bpf_program_attach_fd(prog, ifindex, "tcx", &link_create_opts);
13256 }
13257 
13258 struct bpf_link *
13259 bpf_program__attach_netkit(const struct bpf_program *prog, int ifindex,
13260 			   const struct bpf_netkit_opts *opts)
13261 {
13262 	LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
13263 	__u32 relative_id;
13264 	int relative_fd;
13265 
13266 	if (!OPTS_VALID(opts, bpf_netkit_opts))
13267 		return libbpf_err_ptr(-EINVAL);
13268 
13269 	relative_id = OPTS_GET(opts, relative_id, 0);
13270 	relative_fd = OPTS_GET(opts, relative_fd, 0);
13271 
13272 	/* validate we don't have unexpected combinations of non-zero fields */
13273 	if (!ifindex) {
13274 		pr_warn("prog '%s': target netdevice ifindex cannot be zero\n",
13275 			prog->name);
13276 		return libbpf_err_ptr(-EINVAL);
13277 	}
13278 	if (relative_fd && relative_id) {
13279 		pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
13280 			prog->name);
13281 		return libbpf_err_ptr(-EINVAL);
13282 	}
13283 
13284 	link_create_opts.netkit.expected_revision = OPTS_GET(opts, expected_revision, 0);
13285 	link_create_opts.netkit.relative_fd = relative_fd;
13286 	link_create_opts.netkit.relative_id = relative_id;
13287 	link_create_opts.flags = OPTS_GET(opts, flags, 0);
13288 
13289 	return bpf_program_attach_fd(prog, ifindex, "netkit", &link_create_opts);
13290 }
13291 
13292 struct bpf_link *bpf_program__attach_freplace(const struct bpf_program *prog,
13293 					      int target_fd,
13294 					      const char *attach_func_name)
13295 {
13296 	int btf_id;
13297 
13298 	if (!!target_fd != !!attach_func_name) {
13299 		pr_warn("prog '%s': supply none or both of target_fd and attach_func_name\n",
13300 			prog->name);
13301 		return libbpf_err_ptr(-EINVAL);
13302 	}
13303 
13304 	if (prog->type != BPF_PROG_TYPE_EXT) {
13305 		pr_warn("prog '%s': only BPF_PROG_TYPE_EXT can attach as freplace\n",
13306 			prog->name);
13307 		return libbpf_err_ptr(-EINVAL);
13308 	}
13309 
13310 	if (target_fd) {
13311 		LIBBPF_OPTS(bpf_link_create_opts, target_opts);
13312 
13313 		btf_id = libbpf_find_prog_btf_id(attach_func_name, target_fd, prog->obj->token_fd);
13314 		if (btf_id < 0)
13315 			return libbpf_err_ptr(btf_id);
13316 
13317 		target_opts.target_btf_id = btf_id;
13318 
13319 		return bpf_program_attach_fd(prog, target_fd, "freplace",
13320 					     &target_opts);
13321 	} else {
13322 		/* no target, so use raw_tracepoint_open for compatibility
13323 		 * with old kernels
13324 		 */
13325 		return bpf_program__attach_trace(prog);
13326 	}
13327 }
13328 
13329 struct bpf_link *
13330 bpf_program__attach_iter(const struct bpf_program *prog,
13331 			 const struct bpf_iter_attach_opts *opts)
13332 {
13333 	DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
13334 	struct bpf_link *link;
13335 	int prog_fd, link_fd;
13336 	__u32 target_fd = 0;
13337 
13338 	if (!OPTS_VALID(opts, bpf_iter_attach_opts))
13339 		return libbpf_err_ptr(-EINVAL);
13340 
13341 	link_create_opts.iter_info = OPTS_GET(opts, link_info, (void *)0);
13342 	link_create_opts.iter_info_len = OPTS_GET(opts, link_info_len, 0);
13343 
13344 	prog_fd = bpf_program__fd(prog);
13345 	if (prog_fd < 0) {
13346 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
13347 		return libbpf_err_ptr(-EINVAL);
13348 	}
13349 
13350 	link = calloc(1, sizeof(*link));
13351 	if (!link)
13352 		return libbpf_err_ptr(-ENOMEM);
13353 	link->detach = &bpf_link__detach_fd;
13354 
13355 	link_fd = bpf_link_create(prog_fd, target_fd, BPF_TRACE_ITER,
13356 				  &link_create_opts);
13357 	if (link_fd < 0) {
13358 		link_fd = -errno;
13359 		free(link);
13360 		pr_warn("prog '%s': failed to attach to iterator: %s\n",
13361 			prog->name, errstr(link_fd));
13362 		return libbpf_err_ptr(link_fd);
13363 	}
13364 	link->fd = link_fd;
13365 	return link;
13366 }
13367 
13368 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link)
13369 {
13370 	*link = bpf_program__attach_iter(prog, NULL);
13371 	return libbpf_get_error(*link);
13372 }
13373 
13374 struct bpf_link *bpf_program__attach_netfilter(const struct bpf_program *prog,
13375 					       const struct bpf_netfilter_opts *opts)
13376 {
13377 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
13378 	struct bpf_link *link;
13379 	int prog_fd, link_fd;
13380 
13381 	if (!OPTS_VALID(opts, bpf_netfilter_opts))
13382 		return libbpf_err_ptr(-EINVAL);
13383 
13384 	prog_fd = bpf_program__fd(prog);
13385 	if (prog_fd < 0) {
13386 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
13387 		return libbpf_err_ptr(-EINVAL);
13388 	}
13389 
13390 	link = calloc(1, sizeof(*link));
13391 	if (!link)
13392 		return libbpf_err_ptr(-ENOMEM);
13393 
13394 	link->detach = &bpf_link__detach_fd;
13395 
13396 	lopts.netfilter.pf = OPTS_GET(opts, pf, 0);
13397 	lopts.netfilter.hooknum = OPTS_GET(opts, hooknum, 0);
13398 	lopts.netfilter.priority = OPTS_GET(opts, priority, 0);
13399 	lopts.netfilter.flags = OPTS_GET(opts, flags, 0);
13400 
13401 	link_fd = bpf_link_create(prog_fd, 0, BPF_NETFILTER, &lopts);
13402 	if (link_fd < 0) {
13403 		link_fd = -errno;
13404 		free(link);
13405 		pr_warn("prog '%s': failed to attach to netfilter: %s\n",
13406 			prog->name, errstr(link_fd));
13407 		return libbpf_err_ptr(link_fd);
13408 	}
13409 	link->fd = link_fd;
13410 
13411 	return link;
13412 }
13413 
13414 struct bpf_link *bpf_program__attach(const struct bpf_program *prog)
13415 {
13416 	struct bpf_link *link = NULL;
13417 	int err;
13418 
13419 	if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
13420 		return libbpf_err_ptr(-EOPNOTSUPP);
13421 
13422 	if (bpf_program__fd(prog) < 0) {
13423 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
13424 			prog->name);
13425 		return libbpf_err_ptr(-EINVAL);
13426 	}
13427 
13428 	err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, &link);
13429 	if (err)
13430 		return libbpf_err_ptr(err);
13431 
13432 	/* When calling bpf_program__attach() explicitly, auto-attach support
13433 	 * is expected to work, so NULL returned link is considered an error.
13434 	 * This is different for skeleton's attach, see comment in
13435 	 * bpf_object__attach_skeleton().
13436 	 */
13437 	if (!link)
13438 		return libbpf_err_ptr(-EOPNOTSUPP);
13439 
13440 	return link;
13441 }
13442 
13443 struct bpf_link_struct_ops {
13444 	struct bpf_link link;
13445 	int map_fd;
13446 };
13447 
13448 static int bpf_link__detach_struct_ops(struct bpf_link *link)
13449 {
13450 	struct bpf_link_struct_ops *st_link;
13451 	__u32 zero = 0;
13452 
13453 	st_link = container_of(link, struct bpf_link_struct_ops, link);
13454 
13455 	if (st_link->map_fd < 0)
13456 		/* w/o a real link */
13457 		return bpf_map_delete_elem(link->fd, &zero);
13458 
13459 	return close(link->fd);
13460 }
13461 
13462 struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map)
13463 {
13464 	struct bpf_link_struct_ops *link;
13465 	__u32 zero = 0;
13466 	int err, fd;
13467 
13468 	if (!bpf_map__is_struct_ops(map)) {
13469 		pr_warn("map '%s': can't attach non-struct_ops map\n", map->name);
13470 		return libbpf_err_ptr(-EINVAL);
13471 	}
13472 
13473 	if (map->fd < 0) {
13474 		pr_warn("map '%s': can't attach BPF map without FD (was it created?)\n", map->name);
13475 		return libbpf_err_ptr(-EINVAL);
13476 	}
13477 
13478 	link = calloc(1, sizeof(*link));
13479 	if (!link)
13480 		return libbpf_err_ptr(-EINVAL);
13481 
13482 	/* kern_vdata should be prepared during the loading phase. */
13483 	err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
13484 	/* It can be EBUSY if the map has been used to create or
13485 	 * update a link before.  We don't allow updating the value of
13486 	 * a struct_ops once it is set.  That ensures that the value
13487 	 * never changed.  So, it is safe to skip EBUSY.
13488 	 */
13489 	if (err && (!(map->def.map_flags & BPF_F_LINK) || err != -EBUSY)) {
13490 		free(link);
13491 		return libbpf_err_ptr(err);
13492 	}
13493 
13494 	link->link.detach = bpf_link__detach_struct_ops;
13495 
13496 	if (!(map->def.map_flags & BPF_F_LINK)) {
13497 		/* w/o a real link */
13498 		link->link.fd = map->fd;
13499 		link->map_fd = -1;
13500 		return &link->link;
13501 	}
13502 
13503 	fd = bpf_link_create(map->fd, 0, BPF_STRUCT_OPS, NULL);
13504 	if (fd < 0) {
13505 		free(link);
13506 		return libbpf_err_ptr(fd);
13507 	}
13508 
13509 	link->link.fd = fd;
13510 	link->map_fd = map->fd;
13511 
13512 	return &link->link;
13513 }
13514 
13515 /*
13516  * Swap the back struct_ops of a link with a new struct_ops map.
13517  */
13518 int bpf_link__update_map(struct bpf_link *link, const struct bpf_map *map)
13519 {
13520 	struct bpf_link_struct_ops *st_ops_link;
13521 	__u32 zero = 0;
13522 	int err;
13523 
13524 	if (!bpf_map__is_struct_ops(map))
13525 		return libbpf_err(-EINVAL);
13526 
13527 	if (map->fd < 0) {
13528 		pr_warn("map '%s': can't use BPF map without FD (was it created?)\n", map->name);
13529 		return libbpf_err(-EINVAL);
13530 	}
13531 
13532 	st_ops_link = container_of(link, struct bpf_link_struct_ops, link);
13533 	/* Ensure the type of a link is correct */
13534 	if (st_ops_link->map_fd < 0)
13535 		return libbpf_err(-EINVAL);
13536 
13537 	err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
13538 	/* It can be EBUSY if the map has been used to create or
13539 	 * update a link before.  We don't allow updating the value of
13540 	 * a struct_ops once it is set.  That ensures that the value
13541 	 * never changed.  So, it is safe to skip EBUSY.
13542 	 */
13543 	if (err && err != -EBUSY)
13544 		return err;
13545 
13546 	err = bpf_link_update(link->fd, map->fd, NULL);
13547 	if (err < 0)
13548 		return err;
13549 
13550 	st_ops_link->map_fd = map->fd;
13551 
13552 	return 0;
13553 }
13554 
13555 typedef enum bpf_perf_event_ret (*bpf_perf_event_print_t)(struct perf_event_header *hdr,
13556 							  void *private_data);
13557 
13558 static enum bpf_perf_event_ret
13559 perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
13560 		       void **copy_mem, size_t *copy_size,
13561 		       bpf_perf_event_print_t fn, void *private_data)
13562 {
13563 	struct perf_event_mmap_page *header = mmap_mem;
13564 	__u64 data_head = ring_buffer_read_head(header);
13565 	__u64 data_tail = header->data_tail;
13566 	void *base = ((__u8 *)header) + page_size;
13567 	int ret = LIBBPF_PERF_EVENT_CONT;
13568 	struct perf_event_header *ehdr;
13569 	size_t ehdr_size;
13570 
13571 	while (data_head != data_tail) {
13572 		ehdr = base + (data_tail & (mmap_size - 1));
13573 		ehdr_size = ehdr->size;
13574 
13575 		if (((void *)ehdr) + ehdr_size > base + mmap_size) {
13576 			void *copy_start = ehdr;
13577 			size_t len_first = base + mmap_size - copy_start;
13578 			size_t len_secnd = ehdr_size - len_first;
13579 
13580 			if (*copy_size < ehdr_size) {
13581 				free(*copy_mem);
13582 				*copy_mem = malloc(ehdr_size);
13583 				if (!*copy_mem) {
13584 					*copy_size = 0;
13585 					ret = LIBBPF_PERF_EVENT_ERROR;
13586 					break;
13587 				}
13588 				*copy_size = ehdr_size;
13589 			}
13590 
13591 			memcpy(*copy_mem, copy_start, len_first);
13592 			memcpy(*copy_mem + len_first, base, len_secnd);
13593 			ehdr = *copy_mem;
13594 		}
13595 
13596 		ret = fn(ehdr, private_data);
13597 		data_tail += ehdr_size;
13598 		if (ret != LIBBPF_PERF_EVENT_CONT)
13599 			break;
13600 	}
13601 
13602 	ring_buffer_write_tail(header, data_tail);
13603 	return libbpf_err(ret);
13604 }
13605 
13606 struct perf_buffer;
13607 
13608 struct perf_buffer_params {
13609 	struct perf_event_attr *attr;
13610 	/* if event_cb is specified, it takes precendence */
13611 	perf_buffer_event_fn event_cb;
13612 	/* sample_cb and lost_cb are higher-level common-case callbacks */
13613 	perf_buffer_sample_fn sample_cb;
13614 	perf_buffer_lost_fn lost_cb;
13615 	void *ctx;
13616 	int cpu_cnt;
13617 	int *cpus;
13618 	int *map_keys;
13619 };
13620 
13621 struct perf_cpu_buf {
13622 	struct perf_buffer *pb;
13623 	void *base; /* mmap()'ed memory */
13624 	void *buf; /* for reconstructing segmented data */
13625 	size_t buf_size;
13626 	int fd;
13627 	int cpu;
13628 	int map_key;
13629 };
13630 
13631 struct perf_buffer {
13632 	perf_buffer_event_fn event_cb;
13633 	perf_buffer_sample_fn sample_cb;
13634 	perf_buffer_lost_fn lost_cb;
13635 	void *ctx; /* passed into callbacks */
13636 
13637 	size_t page_size;
13638 	size_t mmap_size;
13639 	struct perf_cpu_buf **cpu_bufs;
13640 	struct epoll_event *events;
13641 	int cpu_cnt; /* number of allocated CPU buffers */
13642 	int epoll_fd; /* perf event FD */
13643 	int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
13644 };
13645 
13646 static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
13647 				      struct perf_cpu_buf *cpu_buf)
13648 {
13649 	if (!cpu_buf)
13650 		return;
13651 	if (cpu_buf->base &&
13652 	    munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
13653 		pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
13654 	if (cpu_buf->fd >= 0) {
13655 		ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
13656 		close(cpu_buf->fd);
13657 	}
13658 	free(cpu_buf->buf);
13659 	free(cpu_buf);
13660 }
13661 
13662 void perf_buffer__free(struct perf_buffer *pb)
13663 {
13664 	int i;
13665 
13666 	if (IS_ERR_OR_NULL(pb))
13667 		return;
13668 	if (pb->cpu_bufs) {
13669 		for (i = 0; i < pb->cpu_cnt; i++) {
13670 			struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
13671 
13672 			if (!cpu_buf)
13673 				continue;
13674 
13675 			bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
13676 			perf_buffer__free_cpu_buf(pb, cpu_buf);
13677 		}
13678 		free(pb->cpu_bufs);
13679 	}
13680 	if (pb->epoll_fd >= 0)
13681 		close(pb->epoll_fd);
13682 	free(pb->events);
13683 	free(pb);
13684 }
13685 
13686 static struct perf_cpu_buf *
13687 perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
13688 			  int cpu, int map_key)
13689 {
13690 	struct perf_cpu_buf *cpu_buf;
13691 	int err;
13692 
13693 	cpu_buf = calloc(1, sizeof(*cpu_buf));
13694 	if (!cpu_buf)
13695 		return ERR_PTR(-ENOMEM);
13696 
13697 	cpu_buf->pb = pb;
13698 	cpu_buf->cpu = cpu;
13699 	cpu_buf->map_key = map_key;
13700 
13701 	cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
13702 			      -1, PERF_FLAG_FD_CLOEXEC);
13703 	if (cpu_buf->fd < 0) {
13704 		err = -errno;
13705 		pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
13706 			cpu, errstr(err));
13707 		goto error;
13708 	}
13709 
13710 	cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
13711 			     PROT_READ | PROT_WRITE, MAP_SHARED,
13712 			     cpu_buf->fd, 0);
13713 	if (cpu_buf->base == MAP_FAILED) {
13714 		cpu_buf->base = NULL;
13715 		err = -errno;
13716 		pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
13717 			cpu, errstr(err));
13718 		goto error;
13719 	}
13720 
13721 	if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
13722 		err = -errno;
13723 		pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
13724 			cpu, errstr(err));
13725 		goto error;
13726 	}
13727 
13728 	return cpu_buf;
13729 
13730 error:
13731 	perf_buffer__free_cpu_buf(pb, cpu_buf);
13732 	return (struct perf_cpu_buf *)ERR_PTR(err);
13733 }
13734 
13735 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
13736 					      struct perf_buffer_params *p);
13737 
13738 struct perf_buffer *perf_buffer__new(int map_fd, size_t page_cnt,
13739 				     perf_buffer_sample_fn sample_cb,
13740 				     perf_buffer_lost_fn lost_cb,
13741 				     void *ctx,
13742 				     const struct perf_buffer_opts *opts)
13743 {
13744 	const size_t attr_sz = sizeof(struct perf_event_attr);
13745 	struct perf_buffer_params p = {};
13746 	struct perf_event_attr attr;
13747 	__u32 sample_period;
13748 
13749 	if (!OPTS_VALID(opts, perf_buffer_opts))
13750 		return libbpf_err_ptr(-EINVAL);
13751 
13752 	sample_period = OPTS_GET(opts, sample_period, 1);
13753 	if (!sample_period)
13754 		sample_period = 1;
13755 
13756 	memset(&attr, 0, attr_sz);
13757 	attr.size = attr_sz;
13758 	attr.config = PERF_COUNT_SW_BPF_OUTPUT;
13759 	attr.type = PERF_TYPE_SOFTWARE;
13760 	attr.sample_type = PERF_SAMPLE_RAW;
13761 	attr.wakeup_events = sample_period;
13762 
13763 	p.attr = &attr;
13764 	p.sample_cb = sample_cb;
13765 	p.lost_cb = lost_cb;
13766 	p.ctx = ctx;
13767 
13768 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
13769 }
13770 
13771 struct perf_buffer *perf_buffer__new_raw(int map_fd, size_t page_cnt,
13772 					 struct perf_event_attr *attr,
13773 					 perf_buffer_event_fn event_cb, void *ctx,
13774 					 const struct perf_buffer_raw_opts *opts)
13775 {
13776 	struct perf_buffer_params p = {};
13777 
13778 	if (!attr)
13779 		return libbpf_err_ptr(-EINVAL);
13780 
13781 	if (!OPTS_VALID(opts, perf_buffer_raw_opts))
13782 		return libbpf_err_ptr(-EINVAL);
13783 
13784 	p.attr = attr;
13785 	p.event_cb = event_cb;
13786 	p.ctx = ctx;
13787 	p.cpu_cnt = OPTS_GET(opts, cpu_cnt, 0);
13788 	p.cpus = OPTS_GET(opts, cpus, NULL);
13789 	p.map_keys = OPTS_GET(opts, map_keys, NULL);
13790 
13791 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
13792 }
13793 
13794 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
13795 					      struct perf_buffer_params *p)
13796 {
13797 	const char *online_cpus_file = "/sys/devices/system/cpu/online";
13798 	struct bpf_map_info map;
13799 	struct perf_buffer *pb;
13800 	bool *online = NULL;
13801 	__u32 map_info_len;
13802 	int err, i, j, n;
13803 
13804 	if (page_cnt == 0 || (page_cnt & (page_cnt - 1))) {
13805 		pr_warn("page count should be power of two, but is %zu\n",
13806 			page_cnt);
13807 		return ERR_PTR(-EINVAL);
13808 	}
13809 
13810 	/* best-effort sanity checks */
13811 	memset(&map, 0, sizeof(map));
13812 	map_info_len = sizeof(map);
13813 	err = bpf_map_get_info_by_fd(map_fd, &map, &map_info_len);
13814 	if (err) {
13815 		err = -errno;
13816 		/* if BPF_OBJ_GET_INFO_BY_FD is supported, will return
13817 		 * -EBADFD, -EFAULT, or -E2BIG on real error
13818 		 */
13819 		if (err != -EINVAL) {
13820 			pr_warn("failed to get map info for map FD %d: %s\n",
13821 				map_fd, errstr(err));
13822 			return ERR_PTR(err);
13823 		}
13824 		pr_debug("failed to get map info for FD %d; API not supported? Ignoring...\n",
13825 			 map_fd);
13826 	} else {
13827 		if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
13828 			pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
13829 				map.name);
13830 			return ERR_PTR(-EINVAL);
13831 		}
13832 	}
13833 
13834 	pb = calloc(1, sizeof(*pb));
13835 	if (!pb)
13836 		return ERR_PTR(-ENOMEM);
13837 
13838 	pb->event_cb = p->event_cb;
13839 	pb->sample_cb = p->sample_cb;
13840 	pb->lost_cb = p->lost_cb;
13841 	pb->ctx = p->ctx;
13842 
13843 	pb->page_size = getpagesize();
13844 	pb->mmap_size = pb->page_size * page_cnt;
13845 	pb->map_fd = map_fd;
13846 
13847 	pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
13848 	if (pb->epoll_fd < 0) {
13849 		err = -errno;
13850 		pr_warn("failed to create epoll instance: %s\n",
13851 			errstr(err));
13852 		goto error;
13853 	}
13854 
13855 	if (p->cpu_cnt > 0) {
13856 		pb->cpu_cnt = p->cpu_cnt;
13857 	} else {
13858 		pb->cpu_cnt = libbpf_num_possible_cpus();
13859 		if (pb->cpu_cnt < 0) {
13860 			err = pb->cpu_cnt;
13861 			goto error;
13862 		}
13863 		if (map.max_entries && map.max_entries < pb->cpu_cnt)
13864 			pb->cpu_cnt = map.max_entries;
13865 	}
13866 
13867 	pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
13868 	if (!pb->events) {
13869 		err = -ENOMEM;
13870 		pr_warn("failed to allocate events: out of memory\n");
13871 		goto error;
13872 	}
13873 	pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
13874 	if (!pb->cpu_bufs) {
13875 		err = -ENOMEM;
13876 		pr_warn("failed to allocate buffers: out of memory\n");
13877 		goto error;
13878 	}
13879 
13880 	err = parse_cpu_mask_file(online_cpus_file, &online, &n);
13881 	if (err) {
13882 		pr_warn("failed to get online CPU mask: %s\n", errstr(err));
13883 		goto error;
13884 	}
13885 
13886 	for (i = 0, j = 0; i < pb->cpu_cnt; i++) {
13887 		struct perf_cpu_buf *cpu_buf;
13888 		int cpu, map_key;
13889 
13890 		cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
13891 		map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
13892 
13893 		/* in case user didn't explicitly requested particular CPUs to
13894 		 * be attached to, skip offline/not present CPUs
13895 		 */
13896 		if (p->cpu_cnt <= 0 && (cpu >= n || !online[cpu]))
13897 			continue;
13898 
13899 		cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
13900 		if (IS_ERR(cpu_buf)) {
13901 			err = PTR_ERR(cpu_buf);
13902 			goto error;
13903 		}
13904 
13905 		pb->cpu_bufs[j] = cpu_buf;
13906 
13907 		err = bpf_map_update_elem(pb->map_fd, &map_key,
13908 					  &cpu_buf->fd, 0);
13909 		if (err) {
13910 			err = -errno;
13911 			pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
13912 				cpu, map_key, cpu_buf->fd,
13913 				errstr(err));
13914 			goto error;
13915 		}
13916 
13917 		pb->events[j].events = EPOLLIN;
13918 		pb->events[j].data.ptr = cpu_buf;
13919 		if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
13920 			      &pb->events[j]) < 0) {
13921 			err = -errno;
13922 			pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
13923 				cpu, cpu_buf->fd,
13924 				errstr(err));
13925 			goto error;
13926 		}
13927 		j++;
13928 	}
13929 	pb->cpu_cnt = j;
13930 	free(online);
13931 
13932 	return pb;
13933 
13934 error:
13935 	free(online);
13936 	if (pb)
13937 		perf_buffer__free(pb);
13938 	return ERR_PTR(err);
13939 }
13940 
13941 struct perf_sample_raw {
13942 	struct perf_event_header header;
13943 	uint32_t size;
13944 	char data[];
13945 };
13946 
13947 struct perf_sample_lost {
13948 	struct perf_event_header header;
13949 	uint64_t id;
13950 	uint64_t lost;
13951 	uint64_t sample_id;
13952 };
13953 
13954 static enum bpf_perf_event_ret
13955 perf_buffer__process_record(struct perf_event_header *e, void *ctx)
13956 {
13957 	struct perf_cpu_buf *cpu_buf = ctx;
13958 	struct perf_buffer *pb = cpu_buf->pb;
13959 	void *data = e;
13960 
13961 	/* user wants full control over parsing perf event */
13962 	if (pb->event_cb)
13963 		return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
13964 
13965 	switch (e->type) {
13966 	case PERF_RECORD_SAMPLE: {
13967 		struct perf_sample_raw *s = data;
13968 
13969 		if (pb->sample_cb)
13970 			pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
13971 		break;
13972 	}
13973 	case PERF_RECORD_LOST: {
13974 		struct perf_sample_lost *s = data;
13975 
13976 		if (pb->lost_cb)
13977 			pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
13978 		break;
13979 	}
13980 	default:
13981 		pr_warn("unknown perf sample type %d\n", e->type);
13982 		return LIBBPF_PERF_EVENT_ERROR;
13983 	}
13984 	return LIBBPF_PERF_EVENT_CONT;
13985 }
13986 
13987 static int perf_buffer__process_records(struct perf_buffer *pb,
13988 					struct perf_cpu_buf *cpu_buf)
13989 {
13990 	enum bpf_perf_event_ret ret;
13991 
13992 	ret = perf_event_read_simple(cpu_buf->base, pb->mmap_size,
13993 				     pb->page_size, &cpu_buf->buf,
13994 				     &cpu_buf->buf_size,
13995 				     perf_buffer__process_record, cpu_buf);
13996 	if (ret != LIBBPF_PERF_EVENT_CONT)
13997 		return ret;
13998 	return 0;
13999 }
14000 
14001 int perf_buffer__epoll_fd(const struct perf_buffer *pb)
14002 {
14003 	return pb->epoll_fd;
14004 }
14005 
14006 int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
14007 {
14008 	int i, cnt, err;
14009 
14010 	cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
14011 	if (cnt < 0)
14012 		return -errno;
14013 
14014 	for (i = 0; i < cnt; i++) {
14015 		struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
14016 
14017 		err = perf_buffer__process_records(pb, cpu_buf);
14018 		if (err) {
14019 			pr_warn("error while processing records: %s\n", errstr(err));
14020 			return libbpf_err(err);
14021 		}
14022 	}
14023 	return cnt;
14024 }
14025 
14026 /* Return number of PERF_EVENT_ARRAY map slots set up by this perf_buffer
14027  * manager.
14028  */
14029 size_t perf_buffer__buffer_cnt(const struct perf_buffer *pb)
14030 {
14031 	return pb->cpu_cnt;
14032 }
14033 
14034 /*
14035  * Return perf_event FD of a ring buffer in *buf_idx* slot of
14036  * PERF_EVENT_ARRAY BPF map. This FD can be polled for new data using
14037  * select()/poll()/epoll() Linux syscalls.
14038  */
14039 int perf_buffer__buffer_fd(const struct perf_buffer *pb, size_t buf_idx)
14040 {
14041 	struct perf_cpu_buf *cpu_buf;
14042 
14043 	if (buf_idx >= pb->cpu_cnt)
14044 		return libbpf_err(-EINVAL);
14045 
14046 	cpu_buf = pb->cpu_bufs[buf_idx];
14047 	if (!cpu_buf)
14048 		return libbpf_err(-ENOENT);
14049 
14050 	return cpu_buf->fd;
14051 }
14052 
14053 int perf_buffer__buffer(struct perf_buffer *pb, int buf_idx, void **buf, size_t *buf_size)
14054 {
14055 	struct perf_cpu_buf *cpu_buf;
14056 
14057 	if (buf_idx >= pb->cpu_cnt)
14058 		return libbpf_err(-EINVAL);
14059 
14060 	cpu_buf = pb->cpu_bufs[buf_idx];
14061 	if (!cpu_buf)
14062 		return libbpf_err(-ENOENT);
14063 
14064 	*buf = cpu_buf->base;
14065 	*buf_size = pb->mmap_size;
14066 	return 0;
14067 }
14068 
14069 /*
14070  * Consume data from perf ring buffer corresponding to slot *buf_idx* in
14071  * PERF_EVENT_ARRAY BPF map without waiting/polling. If there is no data to
14072  * consume, do nothing and return success.
14073  * Returns:
14074  *   - 0 on success;
14075  *   - <0 on failure.
14076  */
14077 int perf_buffer__consume_buffer(struct perf_buffer *pb, size_t buf_idx)
14078 {
14079 	struct perf_cpu_buf *cpu_buf;
14080 
14081 	if (buf_idx >= pb->cpu_cnt)
14082 		return libbpf_err(-EINVAL);
14083 
14084 	cpu_buf = pb->cpu_bufs[buf_idx];
14085 	if (!cpu_buf)
14086 		return libbpf_err(-ENOENT);
14087 
14088 	return perf_buffer__process_records(pb, cpu_buf);
14089 }
14090 
14091 int perf_buffer__consume(struct perf_buffer *pb)
14092 {
14093 	int i, err;
14094 
14095 	for (i = 0; i < pb->cpu_cnt; i++) {
14096 		struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
14097 
14098 		if (!cpu_buf)
14099 			continue;
14100 
14101 		err = perf_buffer__process_records(pb, cpu_buf);
14102 		if (err) {
14103 			pr_warn("perf_buffer: failed to process records in buffer #%d: %s\n",
14104 				i, errstr(err));
14105 			return libbpf_err(err);
14106 		}
14107 	}
14108 	return 0;
14109 }
14110 
14111 int bpf_program__set_attach_target(struct bpf_program *prog,
14112 				   int attach_prog_fd,
14113 				   const char *attach_func_name)
14114 {
14115 	int btf_obj_fd = 0, btf_id = 0, err;
14116 
14117 	if (!prog || attach_prog_fd < 0)
14118 		return libbpf_err(-EINVAL);
14119 
14120 	if (prog->obj->state >= OBJ_LOADED)
14121 		return libbpf_err(-EINVAL);
14122 
14123 	if (attach_prog_fd && !attach_func_name) {
14124 		/* Store attach_prog_fd. The BTF ID will be resolved later during
14125 		 * the normal object/program load phase.
14126 		 */
14127 		prog->attach_prog_fd = attach_prog_fd;
14128 		return 0;
14129 	}
14130 
14131 	if (attach_prog_fd) {
14132 		btf_id = libbpf_find_prog_btf_id(attach_func_name,
14133 						 attach_prog_fd, prog->obj->token_fd);
14134 		if (btf_id < 0)
14135 			return libbpf_err(btf_id);
14136 	} else {
14137 		if (!attach_func_name)
14138 			return libbpf_err(-EINVAL);
14139 
14140 		/* load btf_vmlinux, if not yet */
14141 		err = bpf_object__load_vmlinux_btf(prog->obj, true);
14142 		if (err)
14143 			return libbpf_err(err);
14144 		err = find_kernel_btf_id(prog->obj, attach_func_name,
14145 					 prog->expected_attach_type,
14146 					 &btf_obj_fd, &btf_id);
14147 		if (err)
14148 			return libbpf_err(err);
14149 	}
14150 
14151 	prog->attach_btf_id = btf_id;
14152 	prog->attach_btf_obj_fd = btf_obj_fd;
14153 	prog->attach_prog_fd = attach_prog_fd;
14154 	return 0;
14155 }
14156 
14157 int bpf_program__assoc_struct_ops(struct bpf_program *prog, struct bpf_map *map,
14158 				  struct bpf_prog_assoc_struct_ops_opts *opts)
14159 {
14160 	int prog_fd, map_fd;
14161 
14162 	prog_fd = bpf_program__fd(prog);
14163 	if (prog_fd < 0) {
14164 		pr_warn("prog '%s': can't associate BPF program without FD (was it loaded?)\n",
14165 			prog->name);
14166 		return libbpf_err(-EINVAL);
14167 	}
14168 
14169 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS) {
14170 		pr_warn("prog '%s': can't associate struct_ops program\n", prog->name);
14171 		return libbpf_err(-EINVAL);
14172 	}
14173 
14174 	map_fd = bpf_map__fd(map);
14175 	if (map_fd < 0) {
14176 		pr_warn("map '%s': can't associate BPF map without FD (was it created?)\n", map->name);
14177 		return libbpf_err(-EINVAL);
14178 	}
14179 
14180 	if (!bpf_map__is_struct_ops(map)) {
14181 		pr_warn("map '%s': can't associate non-struct_ops map\n", map->name);
14182 		return libbpf_err(-EINVAL);
14183 	}
14184 
14185 	return bpf_prog_assoc_struct_ops(prog_fd, map_fd, opts);
14186 }
14187 
14188 int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz)
14189 {
14190 	int err = 0, n, len, start, end = -1;
14191 	bool *tmp;
14192 
14193 	*mask = NULL;
14194 	*mask_sz = 0;
14195 
14196 	/* Each sub string separated by ',' has format \d+-\d+ or \d+ */
14197 	while (*s) {
14198 		if (*s == ',' || *s == '\n') {
14199 			s++;
14200 			continue;
14201 		}
14202 		n = sscanf(s, "%d%n-%d%n", &start, &len, &end, &len);
14203 		if (n <= 0 || n > 2) {
14204 			pr_warn("Failed to get CPU range %s: %d\n", s, n);
14205 			err = -EINVAL;
14206 			goto cleanup;
14207 		} else if (n == 1) {
14208 			end = start;
14209 		}
14210 		if (start < 0 || start > end) {
14211 			pr_warn("Invalid CPU range [%d,%d] in %s\n",
14212 				start, end, s);
14213 			err = -EINVAL;
14214 			goto cleanup;
14215 		}
14216 		tmp = realloc(*mask, end + 1);
14217 		if (!tmp) {
14218 			err = -ENOMEM;
14219 			goto cleanup;
14220 		}
14221 		*mask = tmp;
14222 		memset(tmp + *mask_sz, 0, start - *mask_sz);
14223 		memset(tmp + start, 1, end - start + 1);
14224 		*mask_sz = end + 1;
14225 		s += len;
14226 	}
14227 	if (!*mask_sz) {
14228 		pr_warn("Empty CPU range\n");
14229 		return -EINVAL;
14230 	}
14231 	return 0;
14232 cleanup:
14233 	free(*mask);
14234 	*mask = NULL;
14235 	return err;
14236 }
14237 
14238 int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz)
14239 {
14240 	int fd, err = 0, len;
14241 	char buf[128];
14242 
14243 	fd = open(fcpu, O_RDONLY | O_CLOEXEC);
14244 	if (fd < 0) {
14245 		err = -errno;
14246 		pr_warn("Failed to open cpu mask file %s: %s\n", fcpu, errstr(err));
14247 		return err;
14248 	}
14249 	len = read(fd, buf, sizeof(buf));
14250 	close(fd);
14251 	if (len <= 0) {
14252 		err = len ? -errno : -EINVAL;
14253 		pr_warn("Failed to read cpu mask from %s: %s\n", fcpu, errstr(err));
14254 		return err;
14255 	}
14256 	if (len >= sizeof(buf)) {
14257 		pr_warn("CPU mask is too big in file %s\n", fcpu);
14258 		return -E2BIG;
14259 	}
14260 	buf[len] = '\0';
14261 
14262 	return parse_cpu_mask_str(buf, mask, mask_sz);
14263 }
14264 
14265 int libbpf_num_possible_cpus(void)
14266 {
14267 	static const char *fcpu = "/sys/devices/system/cpu/possible";
14268 	static int cpus;
14269 	int err, n, i, tmp_cpus;
14270 	bool *mask;
14271 
14272 	tmp_cpus = READ_ONCE(cpus);
14273 	if (tmp_cpus > 0)
14274 		return tmp_cpus;
14275 
14276 	err = parse_cpu_mask_file(fcpu, &mask, &n);
14277 	if (err)
14278 		return libbpf_err(err);
14279 
14280 	tmp_cpus = 0;
14281 	for (i = 0; i < n; i++) {
14282 		if (mask[i])
14283 			tmp_cpus++;
14284 	}
14285 	free(mask);
14286 
14287 	WRITE_ONCE(cpus, tmp_cpus);
14288 	return tmp_cpus;
14289 }
14290 
14291 static int populate_skeleton_maps(const struct bpf_object *obj,
14292 				  struct bpf_map_skeleton *maps,
14293 				  size_t map_cnt, size_t map_skel_sz)
14294 {
14295 	int i;
14296 
14297 	for (i = 0; i < map_cnt; i++) {
14298 		struct bpf_map_skeleton *map_skel = (void *)maps + i * map_skel_sz;
14299 		struct bpf_map **map = map_skel->map;
14300 		const char *name = map_skel->name;
14301 		void **mmaped = map_skel->mmaped;
14302 
14303 		*map = bpf_object__find_map_by_name(obj, name);
14304 		if (!*map) {
14305 			pr_warn("failed to find skeleton map '%s'\n", name);
14306 			return -ESRCH;
14307 		}
14308 
14309 		/* externs shouldn't be pre-setup from user code */
14310 		if (mmaped && (*map)->libbpf_type != LIBBPF_MAP_KCONFIG)
14311 			*mmaped = (*map)->mmaped;
14312 	}
14313 	return 0;
14314 }
14315 
14316 static int populate_skeleton_progs(const struct bpf_object *obj,
14317 				   struct bpf_prog_skeleton *progs,
14318 				   size_t prog_cnt, size_t prog_skel_sz)
14319 {
14320 	int i;
14321 
14322 	for (i = 0; i < prog_cnt; i++) {
14323 		struct bpf_prog_skeleton *prog_skel = (void *)progs + i * prog_skel_sz;
14324 		struct bpf_program **prog = prog_skel->prog;
14325 		const char *name = prog_skel->name;
14326 
14327 		*prog = bpf_object__find_program_by_name(obj, name);
14328 		if (!*prog) {
14329 			pr_warn("failed to find skeleton program '%s'\n", name);
14330 			return -ESRCH;
14331 		}
14332 	}
14333 	return 0;
14334 }
14335 
14336 int bpf_object__open_skeleton(struct bpf_object_skeleton *s,
14337 			      const struct bpf_object_open_opts *opts)
14338 {
14339 	struct bpf_object *obj;
14340 	int err;
14341 
14342 	obj = bpf_object_open(NULL, s->data, s->data_sz, s->name, opts);
14343 	if (IS_ERR(obj)) {
14344 		err = PTR_ERR(obj);
14345 		pr_warn("failed to initialize skeleton BPF object '%s': %s\n",
14346 			s->name, errstr(err));
14347 		return libbpf_err(err);
14348 	}
14349 
14350 	*s->obj = obj;
14351 	err = populate_skeleton_maps(obj, s->maps, s->map_cnt, s->map_skel_sz);
14352 	if (err) {
14353 		pr_warn("failed to populate skeleton maps for '%s': %s\n", s->name, errstr(err));
14354 		return libbpf_err(err);
14355 	}
14356 
14357 	err = populate_skeleton_progs(obj, s->progs, s->prog_cnt, s->prog_skel_sz);
14358 	if (err) {
14359 		pr_warn("failed to populate skeleton progs for '%s': %s\n", s->name, errstr(err));
14360 		return libbpf_err(err);
14361 	}
14362 
14363 	return 0;
14364 }
14365 
14366 int bpf_object__open_subskeleton(struct bpf_object_subskeleton *s)
14367 {
14368 	int err, len, var_idx, i;
14369 	const char *var_name;
14370 	const struct bpf_map *map;
14371 	struct btf *btf;
14372 	__u32 map_type_id;
14373 	const struct btf_type *map_type, *var_type;
14374 	const struct bpf_var_skeleton *var_skel;
14375 	struct btf_var_secinfo *var;
14376 
14377 	if (!s->obj)
14378 		return libbpf_err(-EINVAL);
14379 
14380 	btf = bpf_object__btf(s->obj);
14381 	if (!btf) {
14382 		pr_warn("subskeletons require BTF at runtime (object %s)\n",
14383 			bpf_object__name(s->obj));
14384 		return libbpf_err(-errno);
14385 	}
14386 
14387 	err = populate_skeleton_maps(s->obj, s->maps, s->map_cnt, s->map_skel_sz);
14388 	if (err) {
14389 		pr_warn("failed to populate subskeleton maps: %s\n", errstr(err));
14390 		return libbpf_err(err);
14391 	}
14392 
14393 	err = populate_skeleton_progs(s->obj, s->progs, s->prog_cnt, s->prog_skel_sz);
14394 	if (err) {
14395 		pr_warn("failed to populate subskeleton maps: %s\n", errstr(err));
14396 		return libbpf_err(err);
14397 	}
14398 
14399 	for (var_idx = 0; var_idx < s->var_cnt; var_idx++) {
14400 		var_skel = (void *)s->vars + var_idx * s->var_skel_sz;
14401 		map = *var_skel->map;
14402 		map_type_id = bpf_map__btf_value_type_id(map);
14403 		map_type = btf__type_by_id(btf, map_type_id);
14404 
14405 		if (!btf_is_datasec(map_type)) {
14406 			pr_warn("type for map '%1$s' is not a datasec: %2$s\n",
14407 				bpf_map__name(map),
14408 				__btf_kind_str(btf_kind(map_type)));
14409 			return libbpf_err(-EINVAL);
14410 		}
14411 
14412 		len = btf_vlen(map_type);
14413 		var = btf_var_secinfos(map_type);
14414 		for (i = 0; i < len; i++, var++) {
14415 			var_type = btf__type_by_id(btf, var->type);
14416 			var_name = btf__name_by_offset(btf, var_type->name_off);
14417 			if (strcmp(var_name, var_skel->name) == 0) {
14418 				*var_skel->addr = map->mmaped + var->offset;
14419 				break;
14420 			}
14421 		}
14422 	}
14423 	return 0;
14424 }
14425 
14426 void bpf_object__destroy_subskeleton(struct bpf_object_subskeleton *s)
14427 {
14428 	if (!s)
14429 		return;
14430 	free(s->maps);
14431 	free(s->progs);
14432 	free(s->vars);
14433 	free(s);
14434 }
14435 
14436 int bpf_object__load_skeleton(struct bpf_object_skeleton *s)
14437 {
14438 	int i, err;
14439 
14440 	err = bpf_object__load(*s->obj);
14441 	if (err) {
14442 		pr_warn("failed to load BPF skeleton '%s': %s\n", s->name, errstr(err));
14443 		return libbpf_err(err);
14444 	}
14445 
14446 	for (i = 0; i < s->map_cnt; i++) {
14447 		struct bpf_map_skeleton *map_skel = (void *)s->maps + i * s->map_skel_sz;
14448 		struct bpf_map *map = *map_skel->map;
14449 
14450 		if (!map_skel->mmaped)
14451 			continue;
14452 
14453 		if (map->def.type == BPF_MAP_TYPE_ARENA)
14454 			*map_skel->mmaped = map->mmaped + map->obj->arena_data_off;
14455 		else
14456 			*map_skel->mmaped = map->mmaped;
14457 	}
14458 
14459 	return 0;
14460 }
14461 
14462 int bpf_object__attach_skeleton(struct bpf_object_skeleton *s)
14463 {
14464 	int i, err;
14465 
14466 	for (i = 0; i < s->prog_cnt; i++) {
14467 		struct bpf_prog_skeleton *prog_skel = (void *)s->progs + i * s->prog_skel_sz;
14468 		struct bpf_program *prog = *prog_skel->prog;
14469 		struct bpf_link **link = prog_skel->link;
14470 
14471 		if (!prog->autoload || !prog->autoattach)
14472 			continue;
14473 
14474 		/* auto-attaching not supported for this program */
14475 		if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
14476 			continue;
14477 
14478 		/* if user already set the link manually, don't attempt auto-attach */
14479 		if (*link)
14480 			continue;
14481 
14482 		err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, link);
14483 		if (err) {
14484 			pr_warn("prog '%s': failed to auto-attach: %s\n",
14485 				bpf_program__name(prog), errstr(err));
14486 			return libbpf_err(err);
14487 		}
14488 
14489 		/* It's possible that for some SEC() definitions auto-attach
14490 		 * is supported in some cases (e.g., if definition completely
14491 		 * specifies target information), but is not in other cases.
14492 		 * SEC("uprobe") is one such case. If user specified target
14493 		 * binary and function name, such BPF program can be
14494 		 * auto-attached. But if not, it shouldn't trigger skeleton's
14495 		 * attach to fail. It should just be skipped.
14496 		 * attach_fn signals such case with returning 0 (no error) and
14497 		 * setting link to NULL.
14498 		 */
14499 	}
14500 
14501 
14502 	for (i = 0; i < s->map_cnt; i++) {
14503 		struct bpf_map_skeleton *map_skel = (void *)s->maps + i * s->map_skel_sz;
14504 		struct bpf_map *map = *map_skel->map;
14505 		struct bpf_link **link;
14506 
14507 		if (!map->autocreate || !map->autoattach)
14508 			continue;
14509 
14510 		/* only struct_ops maps can be attached */
14511 		if (!bpf_map__is_struct_ops(map))
14512 			continue;
14513 
14514 		/* skeleton is created with earlier version of bpftool, notify user */
14515 		if (s->map_skel_sz < offsetofend(struct bpf_map_skeleton, link)) {
14516 			pr_warn("map '%s': BPF skeleton version is old, skipping map auto-attachment...\n",
14517 				bpf_map__name(map));
14518 			continue;
14519 		}
14520 
14521 		link = map_skel->link;
14522 		if (!link) {
14523 			pr_warn("map '%s': BPF map skeleton link is uninitialized\n",
14524 				bpf_map__name(map));
14525 			continue;
14526 		}
14527 
14528 		if (*link)
14529 			continue;
14530 
14531 		*link = bpf_map__attach_struct_ops(map);
14532 		if (!*link) {
14533 			err = -errno;
14534 			pr_warn("map '%s': failed to auto-attach: %s\n",
14535 				bpf_map__name(map), errstr(err));
14536 			return libbpf_err(err);
14537 		}
14538 	}
14539 
14540 	return 0;
14541 }
14542 
14543 void bpf_object__detach_skeleton(struct bpf_object_skeleton *s)
14544 {
14545 	int i;
14546 
14547 	for (i = 0; i < s->prog_cnt; i++) {
14548 		struct bpf_prog_skeleton *prog_skel = (void *)s->progs + i * s->prog_skel_sz;
14549 		struct bpf_link **link = prog_skel->link;
14550 
14551 		bpf_link__destroy(*link);
14552 		*link = NULL;
14553 	}
14554 
14555 	if (s->map_skel_sz < sizeof(struct bpf_map_skeleton))
14556 		return;
14557 
14558 	for (i = 0; i < s->map_cnt; i++) {
14559 		struct bpf_map_skeleton *map_skel = (void *)s->maps + i * s->map_skel_sz;
14560 		struct bpf_link **link = map_skel->link;
14561 
14562 		if (link) {
14563 			bpf_link__destroy(*link);
14564 			*link = NULL;
14565 		}
14566 	}
14567 }
14568 
14569 void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s)
14570 {
14571 	if (!s)
14572 		return;
14573 
14574 	bpf_object__detach_skeleton(s);
14575 	if (s->obj)
14576 		bpf_object__close(*s->obj);
14577 	free(s->maps);
14578 	free(s->progs);
14579 	free(s);
14580 }
14581