xref: /linux/tools/lib/bpf/libbpf.c (revision 380044c40b1636a72fd8f188b5806be6ae564279)
1 // SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
2 
3 /*
4  * Common eBPF ELF object loading operations.
5  *
6  * Copyright (C) 2013-2015 Alexei Starovoitov <ast@kernel.org>
7  * Copyright (C) 2015 Wang Nan <wangnan0@huawei.com>
8  * Copyright (C) 2015 Huawei Inc.
9  * Copyright (C) 2017 Nicira, Inc.
10  * Copyright (C) 2019 Isovalent, Inc.
11  */
12 
13 #ifndef _GNU_SOURCE
14 #define _GNU_SOURCE
15 #endif
16 #include <stdlib.h>
17 #include <stdio.h>
18 #include <stdarg.h>
19 #include <libgen.h>
20 #include <inttypes.h>
21 #include <limits.h>
22 #include <string.h>
23 #include <unistd.h>
24 #include <endian.h>
25 #include <fcntl.h>
26 #include <errno.h>
27 #include <ctype.h>
28 #include <asm/unistd.h>
29 #include <linux/err.h>
30 #include <linux/kernel.h>
31 #include <linux/bpf.h>
32 #include <linux/btf.h>
33 #include <linux/filter.h>
34 #include <linux/limits.h>
35 #include <linux/perf_event.h>
36 #include <linux/bpf_perf_event.h>
37 #include <linux/ring_buffer.h>
38 #include <sys/epoll.h>
39 #include <sys/ioctl.h>
40 #include <sys/mman.h>
41 #include <sys/stat.h>
42 #include <sys/types.h>
43 #include <sys/vfs.h>
44 #include <sys/utsname.h>
45 #include <sys/resource.h>
46 #include <libelf.h>
47 #include <gelf.h>
48 #include <zlib.h>
49 
50 #include "libbpf.h"
51 #include "bpf.h"
52 #include "btf.h"
53 #include "libbpf_internal.h"
54 #include "hashmap.h"
55 #include "bpf_gen_internal.h"
56 #include "zip.h"
57 
58 #ifndef BPF_FS_MAGIC
59 #define BPF_FS_MAGIC		0xcafe4a11
60 #endif
61 
62 #define MAX_EVENT_NAME_LEN	64
63 
64 #define BPF_FS_DEFAULT_PATH "/sys/fs/bpf"
65 
66 #define BPF_INSN_SZ (sizeof(struct bpf_insn))
67 
68 /* vsprintf() in __base_pr() uses nonliteral format string. It may break
69  * compilation if user enables corresponding warning. Disable it explicitly.
70  */
71 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
72 
73 #define __printf(a, b)	__attribute__((format(printf, a, b)))
74 
75 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj);
76 static bool prog_is_subprog(const struct bpf_object *obj, const struct bpf_program *prog);
77 static int map_set_def_max_entries(struct bpf_map *map);
78 
79 static const char * const attach_type_name[] = {
80 	[BPF_CGROUP_INET_INGRESS]	= "cgroup_inet_ingress",
81 	[BPF_CGROUP_INET_EGRESS]	= "cgroup_inet_egress",
82 	[BPF_CGROUP_INET_SOCK_CREATE]	= "cgroup_inet_sock_create",
83 	[BPF_CGROUP_INET_SOCK_RELEASE]	= "cgroup_inet_sock_release",
84 	[BPF_CGROUP_SOCK_OPS]		= "cgroup_sock_ops",
85 	[BPF_CGROUP_DEVICE]		= "cgroup_device",
86 	[BPF_CGROUP_INET4_BIND]		= "cgroup_inet4_bind",
87 	[BPF_CGROUP_INET6_BIND]		= "cgroup_inet6_bind",
88 	[BPF_CGROUP_INET4_CONNECT]	= "cgroup_inet4_connect",
89 	[BPF_CGROUP_INET6_CONNECT]	= "cgroup_inet6_connect",
90 	[BPF_CGROUP_UNIX_CONNECT]       = "cgroup_unix_connect",
91 	[BPF_CGROUP_INET4_POST_BIND]	= "cgroup_inet4_post_bind",
92 	[BPF_CGROUP_INET6_POST_BIND]	= "cgroup_inet6_post_bind",
93 	[BPF_CGROUP_INET4_GETPEERNAME]	= "cgroup_inet4_getpeername",
94 	[BPF_CGROUP_INET6_GETPEERNAME]	= "cgroup_inet6_getpeername",
95 	[BPF_CGROUP_UNIX_GETPEERNAME]	= "cgroup_unix_getpeername",
96 	[BPF_CGROUP_INET4_GETSOCKNAME]	= "cgroup_inet4_getsockname",
97 	[BPF_CGROUP_INET6_GETSOCKNAME]	= "cgroup_inet6_getsockname",
98 	[BPF_CGROUP_UNIX_GETSOCKNAME]	= "cgroup_unix_getsockname",
99 	[BPF_CGROUP_UDP4_SENDMSG]	= "cgroup_udp4_sendmsg",
100 	[BPF_CGROUP_UDP6_SENDMSG]	= "cgroup_udp6_sendmsg",
101 	[BPF_CGROUP_UNIX_SENDMSG]	= "cgroup_unix_sendmsg",
102 	[BPF_CGROUP_SYSCTL]		= "cgroup_sysctl",
103 	[BPF_CGROUP_UDP4_RECVMSG]	= "cgroup_udp4_recvmsg",
104 	[BPF_CGROUP_UDP6_RECVMSG]	= "cgroup_udp6_recvmsg",
105 	[BPF_CGROUP_UNIX_RECVMSG]	= "cgroup_unix_recvmsg",
106 	[BPF_CGROUP_GETSOCKOPT]		= "cgroup_getsockopt",
107 	[BPF_CGROUP_SETSOCKOPT]		= "cgroup_setsockopt",
108 	[BPF_SK_SKB_STREAM_PARSER]	= "sk_skb_stream_parser",
109 	[BPF_SK_SKB_STREAM_VERDICT]	= "sk_skb_stream_verdict",
110 	[BPF_SK_SKB_VERDICT]		= "sk_skb_verdict",
111 	[BPF_SK_MSG_VERDICT]		= "sk_msg_verdict",
112 	[BPF_LIRC_MODE2]		= "lirc_mode2",
113 	[BPF_FLOW_DISSECTOR]		= "flow_dissector",
114 	[BPF_TRACE_RAW_TP]		= "trace_raw_tp",
115 	[BPF_TRACE_FENTRY]		= "trace_fentry",
116 	[BPF_TRACE_FEXIT]		= "trace_fexit",
117 	[BPF_MODIFY_RETURN]		= "modify_return",
118 	[BPF_TRACE_FSESSION]		= "trace_fsession",
119 	[BPF_LSM_MAC]			= "lsm_mac",
120 	[BPF_LSM_CGROUP]		= "lsm_cgroup",
121 	[BPF_SK_LOOKUP]			= "sk_lookup",
122 	[BPF_TRACE_ITER]		= "trace_iter",
123 	[BPF_XDP_DEVMAP]		= "xdp_devmap",
124 	[BPF_XDP_CPUMAP]		= "xdp_cpumap",
125 	[BPF_XDP]			= "xdp",
126 	[BPF_SK_REUSEPORT_SELECT]	= "sk_reuseport_select",
127 	[BPF_SK_REUSEPORT_SELECT_OR_MIGRATE]	= "sk_reuseport_select_or_migrate",
128 	[BPF_PERF_EVENT]		= "perf_event",
129 	[BPF_TRACE_KPROBE_MULTI]	= "trace_kprobe_multi",
130 	[BPF_STRUCT_OPS]		= "struct_ops",
131 	[BPF_NETFILTER]			= "netfilter",
132 	[BPF_TCX_INGRESS]		= "tcx_ingress",
133 	[BPF_TCX_EGRESS]		= "tcx_egress",
134 	[BPF_TRACE_UPROBE_MULTI]	= "trace_uprobe_multi",
135 	[BPF_NETKIT_PRIMARY]		= "netkit_primary",
136 	[BPF_NETKIT_PEER]		= "netkit_peer",
137 	[BPF_TRACE_KPROBE_SESSION]	= "trace_kprobe_session",
138 	[BPF_TRACE_UPROBE_SESSION]	= "trace_uprobe_session",
139 };
140 
141 static const char * const link_type_name[] = {
142 	[BPF_LINK_TYPE_UNSPEC]			= "unspec",
143 	[BPF_LINK_TYPE_RAW_TRACEPOINT]		= "raw_tracepoint",
144 	[BPF_LINK_TYPE_TRACING]			= "tracing",
145 	[BPF_LINK_TYPE_CGROUP]			= "cgroup",
146 	[BPF_LINK_TYPE_ITER]			= "iter",
147 	[BPF_LINK_TYPE_NETNS]			= "netns",
148 	[BPF_LINK_TYPE_XDP]			= "xdp",
149 	[BPF_LINK_TYPE_PERF_EVENT]		= "perf_event",
150 	[BPF_LINK_TYPE_KPROBE_MULTI]		= "kprobe_multi",
151 	[BPF_LINK_TYPE_STRUCT_OPS]		= "struct_ops",
152 	[BPF_LINK_TYPE_NETFILTER]		= "netfilter",
153 	[BPF_LINK_TYPE_TCX]			= "tcx",
154 	[BPF_LINK_TYPE_UPROBE_MULTI]		= "uprobe_multi",
155 	[BPF_LINK_TYPE_NETKIT]			= "netkit",
156 	[BPF_LINK_TYPE_SOCKMAP]			= "sockmap",
157 };
158 
159 static const char * const map_type_name[] = {
160 	[BPF_MAP_TYPE_UNSPEC]			= "unspec",
161 	[BPF_MAP_TYPE_HASH]			= "hash",
162 	[BPF_MAP_TYPE_ARRAY]			= "array",
163 	[BPF_MAP_TYPE_PROG_ARRAY]		= "prog_array",
164 	[BPF_MAP_TYPE_PERF_EVENT_ARRAY]		= "perf_event_array",
165 	[BPF_MAP_TYPE_PERCPU_HASH]		= "percpu_hash",
166 	[BPF_MAP_TYPE_PERCPU_ARRAY]		= "percpu_array",
167 	[BPF_MAP_TYPE_STACK_TRACE]		= "stack_trace",
168 	[BPF_MAP_TYPE_CGROUP_ARRAY]		= "cgroup_array",
169 	[BPF_MAP_TYPE_LRU_HASH]			= "lru_hash",
170 	[BPF_MAP_TYPE_LRU_PERCPU_HASH]		= "lru_percpu_hash",
171 	[BPF_MAP_TYPE_LPM_TRIE]			= "lpm_trie",
172 	[BPF_MAP_TYPE_ARRAY_OF_MAPS]		= "array_of_maps",
173 	[BPF_MAP_TYPE_HASH_OF_MAPS]		= "hash_of_maps",
174 	[BPF_MAP_TYPE_DEVMAP]			= "devmap",
175 	[BPF_MAP_TYPE_DEVMAP_HASH]		= "devmap_hash",
176 	[BPF_MAP_TYPE_SOCKMAP]			= "sockmap",
177 	[BPF_MAP_TYPE_CPUMAP]			= "cpumap",
178 	[BPF_MAP_TYPE_XSKMAP]			= "xskmap",
179 	[BPF_MAP_TYPE_SOCKHASH]			= "sockhash",
180 	[BPF_MAP_TYPE_CGROUP_STORAGE]		= "cgroup_storage",
181 	[BPF_MAP_TYPE_REUSEPORT_SOCKARRAY]	= "reuseport_sockarray",
182 	[BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE]	= "percpu_cgroup_storage",
183 	[BPF_MAP_TYPE_QUEUE]			= "queue",
184 	[BPF_MAP_TYPE_STACK]			= "stack",
185 	[BPF_MAP_TYPE_SK_STORAGE]		= "sk_storage",
186 	[BPF_MAP_TYPE_STRUCT_OPS]		= "struct_ops",
187 	[BPF_MAP_TYPE_RINGBUF]			= "ringbuf",
188 	[BPF_MAP_TYPE_INODE_STORAGE]		= "inode_storage",
189 	[BPF_MAP_TYPE_TASK_STORAGE]		= "task_storage",
190 	[BPF_MAP_TYPE_BLOOM_FILTER]		= "bloom_filter",
191 	[BPF_MAP_TYPE_USER_RINGBUF]             = "user_ringbuf",
192 	[BPF_MAP_TYPE_CGRP_STORAGE]		= "cgrp_storage",
193 	[BPF_MAP_TYPE_ARENA]			= "arena",
194 	[BPF_MAP_TYPE_INSN_ARRAY]		= "insn_array",
195 };
196 
197 static const char * const prog_type_name[] = {
198 	[BPF_PROG_TYPE_UNSPEC]			= "unspec",
199 	[BPF_PROG_TYPE_SOCKET_FILTER]		= "socket_filter",
200 	[BPF_PROG_TYPE_KPROBE]			= "kprobe",
201 	[BPF_PROG_TYPE_SCHED_CLS]		= "sched_cls",
202 	[BPF_PROG_TYPE_SCHED_ACT]		= "sched_act",
203 	[BPF_PROG_TYPE_TRACEPOINT]		= "tracepoint",
204 	[BPF_PROG_TYPE_XDP]			= "xdp",
205 	[BPF_PROG_TYPE_PERF_EVENT]		= "perf_event",
206 	[BPF_PROG_TYPE_CGROUP_SKB]		= "cgroup_skb",
207 	[BPF_PROG_TYPE_CGROUP_SOCK]		= "cgroup_sock",
208 	[BPF_PROG_TYPE_LWT_IN]			= "lwt_in",
209 	[BPF_PROG_TYPE_LWT_OUT]			= "lwt_out",
210 	[BPF_PROG_TYPE_LWT_XMIT]		= "lwt_xmit",
211 	[BPF_PROG_TYPE_SOCK_OPS]		= "sock_ops",
212 	[BPF_PROG_TYPE_SK_SKB]			= "sk_skb",
213 	[BPF_PROG_TYPE_CGROUP_DEVICE]		= "cgroup_device",
214 	[BPF_PROG_TYPE_SK_MSG]			= "sk_msg",
215 	[BPF_PROG_TYPE_RAW_TRACEPOINT]		= "raw_tracepoint",
216 	[BPF_PROG_TYPE_CGROUP_SOCK_ADDR]	= "cgroup_sock_addr",
217 	[BPF_PROG_TYPE_LWT_SEG6LOCAL]		= "lwt_seg6local",
218 	[BPF_PROG_TYPE_LIRC_MODE2]		= "lirc_mode2",
219 	[BPF_PROG_TYPE_SK_REUSEPORT]		= "sk_reuseport",
220 	[BPF_PROG_TYPE_FLOW_DISSECTOR]		= "flow_dissector",
221 	[BPF_PROG_TYPE_CGROUP_SYSCTL]		= "cgroup_sysctl",
222 	[BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE]	= "raw_tracepoint_writable",
223 	[BPF_PROG_TYPE_CGROUP_SOCKOPT]		= "cgroup_sockopt",
224 	[BPF_PROG_TYPE_TRACING]			= "tracing",
225 	[BPF_PROG_TYPE_STRUCT_OPS]		= "struct_ops",
226 	[BPF_PROG_TYPE_EXT]			= "ext",
227 	[BPF_PROG_TYPE_LSM]			= "lsm",
228 	[BPF_PROG_TYPE_SK_LOOKUP]		= "sk_lookup",
229 	[BPF_PROG_TYPE_SYSCALL]			= "syscall",
230 	[BPF_PROG_TYPE_NETFILTER]		= "netfilter",
231 };
232 
233 static int __base_pr(enum libbpf_print_level level, const char *format,
234 		     va_list args)
235 {
236 	const char *env_var = "LIBBPF_LOG_LEVEL";
237 	static enum libbpf_print_level min_level = LIBBPF_INFO;
238 	static bool initialized;
239 
240 	if (!initialized) {
241 		char *verbosity;
242 
243 		initialized = true;
244 		verbosity = getenv(env_var);
245 		if (verbosity) {
246 			if (strcasecmp(verbosity, "warn") == 0)
247 				min_level = LIBBPF_WARN;
248 			else if (strcasecmp(verbosity, "debug") == 0)
249 				min_level = LIBBPF_DEBUG;
250 			else if (strcasecmp(verbosity, "info") == 0)
251 				min_level = LIBBPF_INFO;
252 			else
253 				fprintf(stderr, "libbpf: unrecognized '%s' envvar value: '%s', should be one of 'warn', 'debug', or 'info'.\n",
254 					env_var, verbosity);
255 		}
256 	}
257 
258 	/* if too verbose, skip logging  */
259 	if (level > min_level)
260 		return 0;
261 
262 	return vfprintf(stderr, format, args);
263 }
264 
265 static libbpf_print_fn_t __libbpf_pr = __base_pr;
266 
267 libbpf_print_fn_t libbpf_set_print(libbpf_print_fn_t fn)
268 {
269 	libbpf_print_fn_t old_print_fn;
270 
271 	old_print_fn = __atomic_exchange_n(&__libbpf_pr, fn, __ATOMIC_RELAXED);
272 
273 	return old_print_fn;
274 }
275 
276 __printf(2, 3)
277 void libbpf_print(enum libbpf_print_level level, const char *format, ...)
278 {
279 	va_list args;
280 	int old_errno;
281 	libbpf_print_fn_t print_fn;
282 
283 	print_fn = __atomic_load_n(&__libbpf_pr, __ATOMIC_RELAXED);
284 	if (!print_fn)
285 		return;
286 
287 	old_errno = errno;
288 
289 	va_start(args, format);
290 	print_fn(level, format, args);
291 	va_end(args);
292 
293 	errno = old_errno;
294 }
295 
296 static void pr_perm_msg(int err)
297 {
298 	struct rlimit limit;
299 	char buf[100];
300 
301 	if (err != -EPERM || geteuid() != 0)
302 		return;
303 
304 	err = getrlimit(RLIMIT_MEMLOCK, &limit);
305 	if (err)
306 		return;
307 
308 	if (limit.rlim_cur == RLIM_INFINITY)
309 		return;
310 
311 	if (limit.rlim_cur < 1024)
312 		snprintf(buf, sizeof(buf), "%zu bytes", (size_t)limit.rlim_cur);
313 	else if (limit.rlim_cur < 1024*1024)
314 		snprintf(buf, sizeof(buf), "%.1f KiB", (double)limit.rlim_cur / 1024);
315 	else
316 		snprintf(buf, sizeof(buf), "%.1f MiB", (double)limit.rlim_cur / (1024*1024));
317 
318 	pr_warn("permission error while running as root; try raising 'ulimit -l'? current value: %s\n",
319 		buf);
320 }
321 
322 /* Copied from tools/perf/util/util.h */
323 #ifndef zfree
324 # define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
325 #endif
326 
327 #ifndef zclose
328 # define zclose(fd) ({			\
329 	int ___err = 0;			\
330 	if ((fd) >= 0)			\
331 		___err = close((fd));	\
332 	fd = -1;			\
333 	___err; })
334 #endif
335 
336 static inline __u64 ptr_to_u64(const void *ptr)
337 {
338 	return (__u64) (unsigned long) ptr;
339 }
340 
341 int libbpf_set_strict_mode(enum libbpf_strict_mode mode)
342 {
343 	/* as of v1.0 libbpf_set_strict_mode() is a no-op */
344 	return 0;
345 }
346 
347 __u32 libbpf_major_version(void)
348 {
349 	return LIBBPF_MAJOR_VERSION;
350 }
351 
352 __u32 libbpf_minor_version(void)
353 {
354 	return LIBBPF_MINOR_VERSION;
355 }
356 
357 const char *libbpf_version_string(void)
358 {
359 #define __S(X) #X
360 #define _S(X) __S(X)
361 	return  "v" _S(LIBBPF_MAJOR_VERSION) "." _S(LIBBPF_MINOR_VERSION);
362 #undef _S
363 #undef __S
364 }
365 
366 enum reloc_type {
367 	RELO_LD64,
368 	RELO_CALL,
369 	RELO_DATA,
370 	RELO_EXTERN_LD64,
371 	RELO_EXTERN_CALL,
372 	RELO_SUBPROG_ADDR,
373 	RELO_CORE,
374 	RELO_INSN_ARRAY,
375 };
376 
377 struct reloc_desc {
378 	enum reloc_type type;
379 	int insn_idx;
380 	union {
381 		const struct bpf_core_relo *core_relo; /* used when type == RELO_CORE */
382 		struct {
383 			int map_idx;
384 			unsigned int sym_off;
385 			/*
386 			 * The following two fields can be unionized, as the
387 			 * ext_idx field is used for extern symbols, and the
388 			 * sym_size is used for jump tables, which are never
389 			 * extern
390 			 */
391 			union {
392 				int ext_idx;
393 				int sym_size;
394 			};
395 		};
396 	};
397 };
398 
399 /* stored as sec_def->cookie for all libbpf-supported SEC()s */
400 enum sec_def_flags {
401 	SEC_NONE = 0,
402 	/* expected_attach_type is optional, if kernel doesn't support that */
403 	SEC_EXP_ATTACH_OPT = 1,
404 	/* legacy, only used by libbpf_get_type_names() and
405 	 * libbpf_attach_type_by_name(), not used by libbpf itself at all.
406 	 * This used to be associated with cgroup (and few other) BPF programs
407 	 * that were attachable through BPF_PROG_ATTACH command. Pretty
408 	 * meaningless nowadays, though.
409 	 */
410 	SEC_ATTACHABLE = 2,
411 	SEC_ATTACHABLE_OPT = SEC_ATTACHABLE | SEC_EXP_ATTACH_OPT,
412 	/* attachment target is specified through BTF ID in either kernel or
413 	 * other BPF program's BTF object
414 	 */
415 	SEC_ATTACH_BTF = 4,
416 	/* BPF program type allows sleeping/blocking in kernel */
417 	SEC_SLEEPABLE = 8,
418 	/* BPF program support non-linear XDP buffer */
419 	SEC_XDP_FRAGS = 16,
420 	/* Setup proper attach type for usdt probes. */
421 	SEC_USDT = 32,
422 };
423 
424 struct bpf_sec_def {
425 	char *sec;
426 	enum bpf_prog_type prog_type;
427 	enum bpf_attach_type expected_attach_type;
428 	long cookie;
429 	int handler_id;
430 
431 	libbpf_prog_setup_fn_t prog_setup_fn;
432 	libbpf_prog_prepare_load_fn_t prog_prepare_load_fn;
433 	libbpf_prog_attach_fn_t prog_attach_fn;
434 };
435 
436 struct bpf_light_subprog {
437 	__u32 sec_insn_off;
438 	__u32 sub_insn_off;
439 };
440 
441 /*
442  * bpf_prog should be a better name but it has been used in
443  * linux/filter.h.
444  */
445 struct bpf_program {
446 	char *name;
447 	char *sec_name;
448 	size_t sec_idx;
449 	const struct bpf_sec_def *sec_def;
450 	/* this program's instruction offset (in number of instructions)
451 	 * within its containing ELF section
452 	 */
453 	size_t sec_insn_off;
454 	/* number of original instructions in ELF section belonging to this
455 	 * program, not taking into account subprogram instructions possible
456 	 * appended later during relocation
457 	 */
458 	size_t sec_insn_cnt;
459 	/* Offset (in number of instructions) of the start of instruction
460 	 * belonging to this BPF program  within its containing main BPF
461 	 * program. For the entry-point (main) BPF program, this is always
462 	 * zero. For a sub-program, this gets reset before each of main BPF
463 	 * programs are processed and relocated and is used to determined
464 	 * whether sub-program was already appended to the main program, and
465 	 * if yes, at which instruction offset.
466 	 */
467 	size_t sub_insn_off;
468 
469 	/* instructions that belong to BPF program; insns[0] is located at
470 	 * sec_insn_off instruction within its ELF section in ELF file, so
471 	 * when mapping ELF file instruction index to the local instruction,
472 	 * one needs to subtract sec_insn_off; and vice versa.
473 	 */
474 	struct bpf_insn *insns;
475 	/* actual number of instruction in this BPF program's image; for
476 	 * entry-point BPF programs this includes the size of main program
477 	 * itself plus all the used sub-programs, appended at the end
478 	 */
479 	size_t insns_cnt;
480 
481 	struct reloc_desc *reloc_desc;
482 	int nr_reloc;
483 
484 	/* BPF verifier log settings */
485 	char *log_buf;
486 	size_t log_size;
487 	__u32 log_level;
488 
489 	struct bpf_object *obj;
490 
491 	int fd;
492 	bool autoload;
493 	bool autoattach;
494 	bool sym_global;
495 	bool mark_btf_static;
496 	enum bpf_prog_type type;
497 	enum bpf_attach_type expected_attach_type;
498 	int exception_cb_idx;
499 
500 	int prog_ifindex;
501 	__u32 attach_btf_obj_fd;
502 	__u32 attach_btf_id;
503 	__u32 attach_prog_fd;
504 
505 	void *func_info;
506 	__u32 func_info_rec_size;
507 	__u32 func_info_cnt;
508 
509 	void *line_info;
510 	__u32 line_info_rec_size;
511 	__u32 line_info_cnt;
512 	__u32 prog_flags;
513 	__u8  hash[SHA256_DIGEST_LENGTH];
514 
515 	struct bpf_light_subprog *subprogs;
516 	__u32 subprog_cnt;
517 };
518 
519 struct bpf_struct_ops {
520 	struct bpf_program **progs;
521 	__u32 *kern_func_off;
522 	/* e.g. struct tcp_congestion_ops in bpf_prog's btf format */
523 	void *data;
524 	/* e.g. struct bpf_struct_ops_tcp_congestion_ops in
525 	 *      btf_vmlinux's format.
526 	 * struct bpf_struct_ops_tcp_congestion_ops {
527 	 *	[... some other kernel fields ...]
528 	 *	struct tcp_congestion_ops data;
529 	 * }
530 	 * kern_vdata-size == sizeof(struct bpf_struct_ops_tcp_congestion_ops)
531 	 * bpf_map__init_kern_struct_ops() will populate the "kern_vdata"
532 	 * from "data".
533 	 */
534 	void *kern_vdata;
535 	__u32 type_id;
536 };
537 
538 #define DATA_SEC ".data"
539 #define BSS_SEC ".bss"
540 #define RODATA_SEC ".rodata"
541 #define KCONFIG_SEC ".kconfig"
542 #define KSYMS_SEC ".ksyms"
543 #define STRUCT_OPS_SEC ".struct_ops"
544 #define STRUCT_OPS_LINK_SEC ".struct_ops.link"
545 #define ARENA_SEC ".addr_space.1"
546 
547 enum libbpf_map_type {
548 	LIBBPF_MAP_UNSPEC,
549 	LIBBPF_MAP_DATA,
550 	LIBBPF_MAP_BSS,
551 	LIBBPF_MAP_RODATA,
552 	LIBBPF_MAP_KCONFIG,
553 };
554 
555 struct bpf_map_def {
556 	unsigned int type;
557 	unsigned int key_size;
558 	unsigned int value_size;
559 	unsigned int max_entries;
560 	unsigned int map_flags;
561 };
562 
563 struct bpf_map {
564 	struct bpf_object *obj;
565 	char *name;
566 	/* real_name is defined for special internal maps (.rodata*,
567 	 * .data*, .bss, .kconfig) and preserves their original ELF section
568 	 * name. This is important to be able to find corresponding BTF
569 	 * DATASEC information.
570 	 */
571 	char *real_name;
572 	int fd;
573 	int sec_idx;
574 	size_t sec_offset;
575 	int map_ifindex;
576 	int inner_map_fd;
577 	struct bpf_map_def def;
578 	__u32 numa_node;
579 	__u32 btf_var_idx;
580 	int mod_btf_fd;
581 	__u32 btf_key_type_id;
582 	__u32 btf_value_type_id;
583 	__u32 btf_vmlinux_value_type_id;
584 	enum libbpf_map_type libbpf_type;
585 	void *mmaped;
586 	struct bpf_struct_ops *st_ops;
587 	struct bpf_map *inner_map;
588 	void **init_slots;
589 	int init_slots_sz;
590 	char *pin_path;
591 	bool pinned;
592 	bool reused;
593 	bool autocreate;
594 	bool autoattach;
595 	__u64 map_extra;
596 	struct bpf_program *excl_prog;
597 };
598 
599 enum extern_type {
600 	EXT_UNKNOWN,
601 	EXT_KCFG,
602 	EXT_KSYM,
603 };
604 
605 enum kcfg_type {
606 	KCFG_UNKNOWN,
607 	KCFG_CHAR,
608 	KCFG_BOOL,
609 	KCFG_INT,
610 	KCFG_TRISTATE,
611 	KCFG_CHAR_ARR,
612 };
613 
614 struct extern_desc {
615 	enum extern_type type;
616 	int sym_idx;
617 	int btf_id;
618 	int sec_btf_id;
619 	char *name;
620 	char *essent_name;
621 	bool is_set;
622 	bool is_weak;
623 	union {
624 		struct {
625 			enum kcfg_type type;
626 			int sz;
627 			int align;
628 			int data_off;
629 			bool is_signed;
630 		} kcfg;
631 		struct {
632 			unsigned long long addr;
633 
634 			/* target btf_id of the corresponding kernel var. */
635 			int kernel_btf_obj_fd;
636 			int kernel_btf_id;
637 
638 			/* local btf_id of the ksym extern's type. */
639 			__u32 type_id;
640 			/* BTF fd index to be patched in for insn->off, this is
641 			 * 0 for vmlinux BTF, index in obj->fd_array for module
642 			 * BTF
643 			 */
644 			__s16 btf_fd_idx;
645 		} ksym;
646 	};
647 };
648 
649 struct module_btf {
650 	struct btf *btf;
651 	char *name;
652 	__u32 id;
653 	int fd;
654 	int fd_array_idx;
655 };
656 
657 enum sec_type {
658 	SEC_UNUSED = 0,
659 	SEC_RELO,
660 	SEC_BSS,
661 	SEC_DATA,
662 	SEC_RODATA,
663 	SEC_ST_OPS,
664 };
665 
666 struct elf_sec_desc {
667 	enum sec_type sec_type;
668 	Elf64_Shdr *shdr;
669 	Elf_Data *data;
670 };
671 
672 struct elf_state {
673 	int fd;
674 	const void *obj_buf;
675 	size_t obj_buf_sz;
676 	Elf *elf;
677 	Elf64_Ehdr *ehdr;
678 	Elf_Data *symbols;
679 	Elf_Data *arena_data;
680 	size_t shstrndx; /* section index for section name strings */
681 	size_t strtabidx;
682 	struct elf_sec_desc *secs;
683 	size_t sec_cnt;
684 	int btf_maps_shndx;
685 	__u32 btf_maps_sec_btf_id;
686 	int text_shndx;
687 	int symbols_shndx;
688 	bool has_st_ops;
689 	int arena_data_shndx;
690 	int jumptables_data_shndx;
691 };
692 
693 struct usdt_manager;
694 
695 enum bpf_object_state {
696 	OBJ_OPEN,
697 	OBJ_PREPARED,
698 	OBJ_LOADED,
699 };
700 
701 struct bpf_object {
702 	char name[BPF_OBJ_NAME_LEN];
703 	char license[64];
704 	__u32 kern_version;
705 
706 	enum bpf_object_state state;
707 	struct bpf_program *programs;
708 	size_t nr_programs;
709 	struct bpf_map *maps;
710 	size_t nr_maps;
711 	size_t maps_cap;
712 
713 	char *kconfig;
714 	struct extern_desc *externs;
715 	int nr_extern;
716 	int kconfig_map_idx;
717 
718 	bool has_subcalls;
719 	bool has_rodata;
720 
721 	struct bpf_gen *gen_loader;
722 
723 	/* Information when doing ELF related work. Only valid if efile.elf is not NULL */
724 	struct elf_state efile;
725 
726 	unsigned char byteorder;
727 
728 	struct btf *btf;
729 	struct btf_ext *btf_ext;
730 
731 	/* Parse and load BTF vmlinux if any of the programs in the object need
732 	 * it at load time.
733 	 */
734 	struct btf *btf_vmlinux;
735 	/* Path to the custom BTF to be used for BPF CO-RE relocations as an
736 	 * override for vmlinux BTF.
737 	 */
738 	char *btf_custom_path;
739 	/* vmlinux BTF override for CO-RE relocations */
740 	struct btf *btf_vmlinux_override;
741 	/* Lazily initialized kernel module BTFs */
742 	struct module_btf *btf_modules;
743 	bool btf_modules_loaded;
744 	size_t btf_module_cnt;
745 	size_t btf_module_cap;
746 
747 	/* optional log settings passed to BPF_BTF_LOAD and BPF_PROG_LOAD commands */
748 	char *log_buf;
749 	size_t log_size;
750 	__u32 log_level;
751 
752 	int *fd_array;
753 	size_t fd_array_cap;
754 	size_t fd_array_cnt;
755 
756 	struct usdt_manager *usdt_man;
757 
758 	int arena_map_idx;
759 	void *arena_data;
760 	size_t arena_data_sz;
761 	size_t arena_data_off;
762 
763 	void *jumptables_data;
764 	size_t jumptables_data_sz;
765 
766 	struct {
767 		struct bpf_program *prog;
768 		unsigned int sym_off;
769 		int fd;
770 	} *jumptable_maps;
771 	size_t jumptable_map_cnt;
772 
773 	struct kern_feature_cache *feat_cache;
774 	char *token_path;
775 	int token_fd;
776 
777 	char path[];
778 };
779 
780 static const char *elf_sym_str(const struct bpf_object *obj, size_t off);
781 static const char *elf_sec_str(const struct bpf_object *obj, size_t off);
782 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx);
783 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name);
784 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn);
785 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn);
786 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn);
787 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx);
788 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx);
789 
790 void bpf_program__unload(struct bpf_program *prog)
791 {
792 	if (!prog)
793 		return;
794 
795 	zclose(prog->fd);
796 
797 	zfree(&prog->func_info);
798 	zfree(&prog->line_info);
799 	zfree(&prog->subprogs);
800 }
801 
802 static void bpf_program__exit(struct bpf_program *prog)
803 {
804 	if (!prog)
805 		return;
806 
807 	bpf_program__unload(prog);
808 	zfree(&prog->name);
809 	zfree(&prog->sec_name);
810 	zfree(&prog->insns);
811 	zfree(&prog->reloc_desc);
812 
813 	prog->nr_reloc = 0;
814 	prog->insns_cnt = 0;
815 	prog->sec_idx = -1;
816 }
817 
818 static bool insn_is_subprog_call(const struct bpf_insn *insn)
819 {
820 	return BPF_CLASS(insn->code) == BPF_JMP &&
821 	       BPF_OP(insn->code) == BPF_CALL &&
822 	       BPF_SRC(insn->code) == BPF_K &&
823 	       insn->src_reg == BPF_PSEUDO_CALL &&
824 	       insn->dst_reg == 0 &&
825 	       insn->off == 0;
826 }
827 
828 static bool is_call_insn(const struct bpf_insn *insn)
829 {
830 	return insn->code == (BPF_JMP | BPF_CALL);
831 }
832 
833 static bool insn_is_pseudo_func(struct bpf_insn *insn)
834 {
835 	return is_ldimm64_insn(insn) && insn->src_reg == BPF_PSEUDO_FUNC;
836 }
837 
838 static int
839 bpf_object__init_prog(struct bpf_object *obj, struct bpf_program *prog,
840 		      const char *name, size_t sec_idx, const char *sec_name,
841 		      size_t sec_off, void *insn_data, size_t insn_data_sz)
842 {
843 	if (insn_data_sz == 0 || insn_data_sz % BPF_INSN_SZ || sec_off % BPF_INSN_SZ) {
844 		pr_warn("sec '%s': corrupted program '%s', offset %zu, size %zu\n",
845 			sec_name, name, sec_off, insn_data_sz);
846 		return -EINVAL;
847 	}
848 
849 	memset(prog, 0, sizeof(*prog));
850 	prog->obj = obj;
851 
852 	prog->sec_idx = sec_idx;
853 	prog->sec_insn_off = sec_off / BPF_INSN_SZ;
854 	prog->sec_insn_cnt = insn_data_sz / BPF_INSN_SZ;
855 	/* insns_cnt can later be increased by appending used subprograms */
856 	prog->insns_cnt = prog->sec_insn_cnt;
857 
858 	prog->type = BPF_PROG_TYPE_UNSPEC;
859 	prog->fd = -1;
860 	prog->exception_cb_idx = -1;
861 
862 	/* libbpf's convention for SEC("?abc...") is that it's just like
863 	 * SEC("abc...") but the corresponding bpf_program starts out with
864 	 * autoload set to false.
865 	 */
866 	if (sec_name[0] == '?') {
867 		prog->autoload = false;
868 		/* from now on forget there was ? in section name */
869 		sec_name++;
870 	} else {
871 		prog->autoload = true;
872 	}
873 
874 	prog->autoattach = true;
875 
876 	/* inherit object's log_level */
877 	prog->log_level = obj->log_level;
878 
879 	prog->sec_name = strdup(sec_name);
880 	if (!prog->sec_name)
881 		goto errout;
882 
883 	prog->name = strdup(name);
884 	if (!prog->name)
885 		goto errout;
886 
887 	prog->insns = malloc(insn_data_sz);
888 	if (!prog->insns)
889 		goto errout;
890 	memcpy(prog->insns, insn_data, insn_data_sz);
891 
892 	return 0;
893 errout:
894 	pr_warn("sec '%s': failed to allocate memory for prog '%s'\n", sec_name, name);
895 	bpf_program__exit(prog);
896 	return -ENOMEM;
897 }
898 
899 static int
900 bpf_object__add_programs(struct bpf_object *obj, Elf_Data *sec_data,
901 			 const char *sec_name, int sec_idx)
902 {
903 	Elf_Data *symbols = obj->efile.symbols;
904 	struct bpf_program *prog, *progs;
905 	void *data = sec_data->d_buf;
906 	size_t sec_sz = sec_data->d_size, sec_off, prog_sz, nr_syms;
907 	int nr_progs, err, i;
908 	const char *name;
909 	Elf64_Sym *sym;
910 
911 	progs = obj->programs;
912 	nr_progs = obj->nr_programs;
913 	nr_syms = symbols->d_size / sizeof(Elf64_Sym);
914 
915 	for (i = 0; i < nr_syms; i++) {
916 		sym = elf_sym_by_idx(obj, i);
917 
918 		if (sym->st_shndx != sec_idx)
919 			continue;
920 		if (ELF64_ST_TYPE(sym->st_info) != STT_FUNC)
921 			continue;
922 
923 		prog_sz = sym->st_size;
924 		sec_off = sym->st_value;
925 
926 		name = elf_sym_str(obj, sym->st_name);
927 		if (!name) {
928 			pr_warn("sec '%s': failed to get symbol name for offset %zu\n",
929 				sec_name, sec_off);
930 			return -LIBBPF_ERRNO__FORMAT;
931 		}
932 
933 		if (sec_off + prog_sz > sec_sz || sec_off + prog_sz < sec_off) {
934 			pr_warn("sec '%s': program at offset %zu crosses section boundary\n",
935 				sec_name, sec_off);
936 			return -LIBBPF_ERRNO__FORMAT;
937 		}
938 
939 		if (sec_idx != obj->efile.text_shndx && ELF64_ST_BIND(sym->st_info) == STB_LOCAL) {
940 			pr_warn("sec '%s': program '%s' is static and not supported\n", sec_name, name);
941 			return -ENOTSUP;
942 		}
943 
944 		pr_debug("sec '%s': found program '%s' at insn offset %zu (%zu bytes), code size %zu insns (%zu bytes)\n",
945 			 sec_name, name, sec_off / BPF_INSN_SZ, sec_off, prog_sz / BPF_INSN_SZ, prog_sz);
946 
947 		progs = libbpf_reallocarray(progs, nr_progs + 1, sizeof(*progs));
948 		if (!progs) {
949 			/*
950 			 * In this case the original obj->programs
951 			 * is still valid, so don't need special treat for
952 			 * bpf_close_object().
953 			 */
954 			pr_warn("sec '%s': failed to alloc memory for new program '%s'\n",
955 				sec_name, name);
956 			return -ENOMEM;
957 		}
958 		obj->programs = progs;
959 
960 		prog = &progs[nr_progs];
961 
962 		err = bpf_object__init_prog(obj, prog, name, sec_idx, sec_name,
963 					    sec_off, data + sec_off, prog_sz);
964 		if (err)
965 			return err;
966 
967 		if (ELF64_ST_BIND(sym->st_info) != STB_LOCAL)
968 			prog->sym_global = true;
969 
970 		/* if function is a global/weak symbol, but has restricted
971 		 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF FUNC
972 		 * as static to enable more permissive BPF verification mode
973 		 * with more outside context available to BPF verifier
974 		 */
975 		if (prog->sym_global && (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
976 		    || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL))
977 			prog->mark_btf_static = true;
978 
979 		nr_progs++;
980 		obj->nr_programs = nr_progs;
981 	}
982 
983 	return 0;
984 }
985 
986 static void bpf_object_bswap_progs(struct bpf_object *obj)
987 {
988 	struct bpf_program *prog = obj->programs;
989 	struct bpf_insn *insn;
990 	int p, i;
991 
992 	for (p = 0; p < obj->nr_programs; p++, prog++) {
993 		insn = prog->insns;
994 		for (i = 0; i < prog->insns_cnt; i++, insn++)
995 			bpf_insn_bswap(insn);
996 	}
997 	pr_debug("converted %zu BPF programs to native byte order\n", obj->nr_programs);
998 }
999 
1000 static const struct btf_member *
1001 find_member_by_offset(const struct btf_type *t, __u32 bit_offset)
1002 {
1003 	struct btf_member *m;
1004 	int i;
1005 
1006 	for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
1007 		if (btf_member_bit_offset(t, i) == bit_offset)
1008 			return m;
1009 	}
1010 
1011 	return NULL;
1012 }
1013 
1014 static const struct btf_member *
1015 find_member_by_name(const struct btf *btf, const struct btf_type *t,
1016 		    const char *name)
1017 {
1018 	struct btf_member *m;
1019 	int i;
1020 
1021 	for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
1022 		if (!strcmp(btf__name_by_offset(btf, m->name_off), name))
1023 			return m;
1024 	}
1025 
1026 	return NULL;
1027 }
1028 
1029 static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
1030 			    __u16 kind, struct btf **res_btf,
1031 			    struct module_btf **res_mod_btf);
1032 
1033 #define STRUCT_OPS_VALUE_PREFIX "bpf_struct_ops_"
1034 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
1035 				   const char *name, __u32 kind);
1036 
1037 static int
1038 find_struct_ops_kern_types(struct bpf_object *obj, const char *tname_raw,
1039 			   struct module_btf **mod_btf,
1040 			   const struct btf_type **type, __u32 *type_id,
1041 			   const struct btf_type **vtype, __u32 *vtype_id,
1042 			   const struct btf_member **data_member)
1043 {
1044 	const struct btf_type *kern_type, *kern_vtype;
1045 	const struct btf_member *kern_data_member;
1046 	struct btf *btf = NULL;
1047 	__s32 kern_vtype_id, kern_type_id;
1048 	char tname[192], stname[256];
1049 	__u32 i;
1050 
1051 	snprintf(tname, sizeof(tname), "%.*s",
1052 		 (int)bpf_core_essential_name_len(tname_raw), tname_raw);
1053 
1054 	snprintf(stname, sizeof(stname), "%s%s", STRUCT_OPS_VALUE_PREFIX, tname);
1055 
1056 	/* Look for the corresponding "map_value" type that will be used
1057 	 * in map_update(BPF_MAP_TYPE_STRUCT_OPS) first, figure out the btf
1058 	 * and the mod_btf.
1059 	 * For example, find "struct bpf_struct_ops_tcp_congestion_ops".
1060 	 */
1061 	kern_vtype_id = find_ksym_btf_id(obj, stname, BTF_KIND_STRUCT, &btf, mod_btf);
1062 	if (kern_vtype_id < 0) {
1063 		pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n", stname);
1064 		return kern_vtype_id;
1065 	}
1066 	kern_vtype = btf__type_by_id(btf, kern_vtype_id);
1067 
1068 	kern_type_id = btf__find_by_name_kind(btf, tname, BTF_KIND_STRUCT);
1069 	if (kern_type_id < 0) {
1070 		pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n", tname);
1071 		return kern_type_id;
1072 	}
1073 	kern_type = btf__type_by_id(btf, kern_type_id);
1074 
1075 	/* Find "struct tcp_congestion_ops" from
1076 	 * struct bpf_struct_ops_tcp_congestion_ops {
1077 	 *	[ ... ]
1078 	 *	struct tcp_congestion_ops data;
1079 	 * }
1080 	 */
1081 	kern_data_member = btf_members(kern_vtype);
1082 	for (i = 0; i < btf_vlen(kern_vtype); i++, kern_data_member++) {
1083 		if (kern_data_member->type == kern_type_id)
1084 			break;
1085 	}
1086 	if (i == btf_vlen(kern_vtype)) {
1087 		pr_warn("struct_ops init_kern: struct %s data is not found in struct %s\n",
1088 			tname, stname);
1089 		return -EINVAL;
1090 	}
1091 
1092 	*type = kern_type;
1093 	*type_id = kern_type_id;
1094 	*vtype = kern_vtype;
1095 	*vtype_id = kern_vtype_id;
1096 	*data_member = kern_data_member;
1097 
1098 	return 0;
1099 }
1100 
1101 static bool bpf_map__is_struct_ops(const struct bpf_map *map)
1102 {
1103 	return map->def.type == BPF_MAP_TYPE_STRUCT_OPS;
1104 }
1105 
1106 static bool is_valid_st_ops_program(struct bpf_object *obj,
1107 				    const struct bpf_program *prog)
1108 {
1109 	int i;
1110 
1111 	for (i = 0; i < obj->nr_programs; i++) {
1112 		if (&obj->programs[i] == prog)
1113 			return prog->type == BPF_PROG_TYPE_STRUCT_OPS;
1114 	}
1115 
1116 	return false;
1117 }
1118 
1119 /* For each struct_ops program P, referenced from some struct_ops map M,
1120  * enable P.autoload if there are Ms for which M.autocreate is true,
1121  * disable P.autoload if for all Ms M.autocreate is false.
1122  * Don't change P.autoload for programs that are not referenced from any maps.
1123  */
1124 static int bpf_object_adjust_struct_ops_autoload(struct bpf_object *obj)
1125 {
1126 	struct bpf_program *prog, *slot_prog;
1127 	struct bpf_map *map;
1128 	int i, j, k, vlen;
1129 
1130 	for (i = 0; i < obj->nr_programs; ++i) {
1131 		int should_load = false;
1132 		int use_cnt = 0;
1133 
1134 		prog = &obj->programs[i];
1135 		if (prog->type != BPF_PROG_TYPE_STRUCT_OPS)
1136 			continue;
1137 
1138 		for (j = 0; j < obj->nr_maps; ++j) {
1139 			const struct btf_type *type;
1140 
1141 			map = &obj->maps[j];
1142 			if (!bpf_map__is_struct_ops(map))
1143 				continue;
1144 
1145 			type = btf__type_by_id(obj->btf, map->st_ops->type_id);
1146 			vlen = btf_vlen(type);
1147 			for (k = 0; k < vlen; ++k) {
1148 				slot_prog = map->st_ops->progs[k];
1149 				if (prog != slot_prog)
1150 					continue;
1151 
1152 				use_cnt++;
1153 				if (map->autocreate)
1154 					should_load = true;
1155 			}
1156 		}
1157 		if (use_cnt)
1158 			prog->autoload = should_load;
1159 	}
1160 
1161 	return 0;
1162 }
1163 
1164 /* Init the map's fields that depend on kern_btf */
1165 static int bpf_map__init_kern_struct_ops(struct bpf_map *map)
1166 {
1167 	const struct btf_member *member, *kern_member, *kern_data_member;
1168 	const struct btf_type *type, *kern_type, *kern_vtype;
1169 	__u32 i, kern_type_id, kern_vtype_id, kern_data_off;
1170 	struct bpf_object *obj = map->obj;
1171 	const struct btf *btf = obj->btf;
1172 	struct bpf_struct_ops *st_ops;
1173 	const struct btf *kern_btf;
1174 	struct module_btf *mod_btf = NULL;
1175 	void *data, *kern_data;
1176 	const char *tname;
1177 	int err;
1178 
1179 	st_ops = map->st_ops;
1180 	type = btf__type_by_id(btf, st_ops->type_id);
1181 	tname = btf__name_by_offset(btf, type->name_off);
1182 	err = find_struct_ops_kern_types(obj, tname, &mod_btf,
1183 					 &kern_type, &kern_type_id,
1184 					 &kern_vtype, &kern_vtype_id,
1185 					 &kern_data_member);
1186 	if (err)
1187 		return err;
1188 
1189 	kern_btf = mod_btf ? mod_btf->btf : obj->btf_vmlinux;
1190 
1191 	pr_debug("struct_ops init_kern %s: type_id:%u kern_type_id:%u kern_vtype_id:%u\n",
1192 		 map->name, st_ops->type_id, kern_type_id, kern_vtype_id);
1193 
1194 	map->mod_btf_fd = mod_btf ? mod_btf->fd : -1;
1195 	map->def.value_size = kern_vtype->size;
1196 	map->btf_vmlinux_value_type_id = kern_vtype_id;
1197 
1198 	st_ops->kern_vdata = calloc(1, kern_vtype->size);
1199 	if (!st_ops->kern_vdata)
1200 		return -ENOMEM;
1201 
1202 	data = st_ops->data;
1203 	kern_data_off = kern_data_member->offset / 8;
1204 	kern_data = st_ops->kern_vdata + kern_data_off;
1205 
1206 	member = btf_members(type);
1207 	for (i = 0; i < btf_vlen(type); i++, member++) {
1208 		const struct btf_type *mtype, *kern_mtype;
1209 		__u32 mtype_id, kern_mtype_id;
1210 		void *mdata, *kern_mdata;
1211 		struct bpf_program *prog;
1212 		__s64 msize, kern_msize;
1213 		__u32 moff, kern_moff;
1214 		__u32 kern_member_idx;
1215 		const char *mname;
1216 
1217 		mname = btf__name_by_offset(btf, member->name_off);
1218 		moff = member->offset / 8;
1219 		mdata = data + moff;
1220 		msize = btf__resolve_size(btf, member->type);
1221 		if (msize < 0) {
1222 			pr_warn("struct_ops init_kern %s: failed to resolve the size of member %s\n",
1223 				map->name, mname);
1224 			return msize;
1225 		}
1226 
1227 		kern_member = find_member_by_name(kern_btf, kern_type, mname);
1228 		if (!kern_member) {
1229 			if (!libbpf_is_mem_zeroed(mdata, msize)) {
1230 				pr_warn("struct_ops init_kern %s: Cannot find member %s in kernel BTF\n",
1231 					map->name, mname);
1232 				return -ENOTSUP;
1233 			}
1234 
1235 			if (st_ops->progs[i]) {
1236 				/* If we had declaratively set struct_ops callback, we need to
1237 				 * force its autoload to false, because it doesn't have
1238 				 * a chance of succeeding from POV of the current struct_ops map.
1239 				 * If this program is still referenced somewhere else, though,
1240 				 * then bpf_object_adjust_struct_ops_autoload() will update its
1241 				 * autoload accordingly.
1242 				 */
1243 				st_ops->progs[i]->autoload = false;
1244 				st_ops->progs[i] = NULL;
1245 			}
1246 
1247 			/* Skip all-zero/NULL fields if they are not present in the kernel BTF */
1248 			pr_info("struct_ops %s: member %s not found in kernel, skipping it as it's set to zero\n",
1249 				map->name, mname);
1250 			continue;
1251 		}
1252 
1253 		kern_member_idx = kern_member - btf_members(kern_type);
1254 		if (btf_member_bitfield_size(type, i) ||
1255 		    btf_member_bitfield_size(kern_type, kern_member_idx)) {
1256 			pr_warn("struct_ops init_kern %s: bitfield %s is not supported\n",
1257 				map->name, mname);
1258 			return -ENOTSUP;
1259 		}
1260 
1261 		kern_moff = kern_member->offset / 8;
1262 		kern_mdata = kern_data + kern_moff;
1263 
1264 		mtype = skip_mods_and_typedefs(btf, member->type, &mtype_id);
1265 		kern_mtype = skip_mods_and_typedefs(kern_btf, kern_member->type,
1266 						    &kern_mtype_id);
1267 		if (BTF_INFO_KIND(mtype->info) !=
1268 		    BTF_INFO_KIND(kern_mtype->info)) {
1269 			pr_warn("struct_ops init_kern %s: Unmatched member type %s %u != %u(kernel)\n",
1270 				map->name, mname, BTF_INFO_KIND(mtype->info),
1271 				BTF_INFO_KIND(kern_mtype->info));
1272 			return -ENOTSUP;
1273 		}
1274 
1275 		if (btf_is_ptr(mtype)) {
1276 			prog = *(void **)mdata;
1277 			/* just like for !kern_member case above, reset declaratively
1278 			 * set (at compile time) program's autload to false,
1279 			 * if user replaced it with another program or NULL
1280 			 */
1281 			if (st_ops->progs[i] && st_ops->progs[i] != prog)
1282 				st_ops->progs[i]->autoload = false;
1283 
1284 			/* Update the value from the shadow type */
1285 			st_ops->progs[i] = prog;
1286 			if (!prog)
1287 				continue;
1288 
1289 			if (!is_valid_st_ops_program(obj, prog)) {
1290 				pr_warn("struct_ops init_kern %s: member %s is not a struct_ops program\n",
1291 					map->name, mname);
1292 				return -ENOTSUP;
1293 			}
1294 
1295 			kern_mtype = skip_mods_and_typedefs(kern_btf,
1296 							    kern_mtype->type,
1297 							    &kern_mtype_id);
1298 
1299 			/* mtype->type must be a func_proto which was
1300 			 * guaranteed in bpf_object__collect_st_ops_relos(),
1301 			 * so only check kern_mtype for func_proto here.
1302 			 */
1303 			if (!btf_is_func_proto(kern_mtype)) {
1304 				pr_warn("struct_ops init_kern %s: kernel member %s is not a func ptr\n",
1305 					map->name, mname);
1306 				return -ENOTSUP;
1307 			}
1308 
1309 			if (mod_btf)
1310 				prog->attach_btf_obj_fd = mod_btf->fd;
1311 
1312 			/* if we haven't yet processed this BPF program, record proper
1313 			 * attach_btf_id and member_idx
1314 			 */
1315 			if (!prog->attach_btf_id) {
1316 				prog->attach_btf_id = kern_type_id;
1317 				prog->expected_attach_type = kern_member_idx;
1318 			}
1319 
1320 			/* struct_ops BPF prog can be re-used between multiple
1321 			 * .struct_ops & .struct_ops.link as long as it's the
1322 			 * same struct_ops struct definition and the same
1323 			 * function pointer field
1324 			 */
1325 			if (prog->attach_btf_id != kern_type_id) {
1326 				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",
1327 					map->name, mname, prog->name, prog->sec_name, prog->type,
1328 					prog->attach_btf_id, kern_type_id);
1329 				return -EINVAL;
1330 			}
1331 			if (prog->expected_attach_type != kern_member_idx) {
1332 				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",
1333 					map->name, mname, prog->name, prog->sec_name, prog->type,
1334 					prog->expected_attach_type, kern_member_idx);
1335 				return -EINVAL;
1336 			}
1337 
1338 			st_ops->kern_func_off[i] = kern_data_off + kern_moff;
1339 
1340 			pr_debug("struct_ops init_kern %s: func ptr %s is set to prog %s from data(+%u) to kern_data(+%u)\n",
1341 				 map->name, mname, prog->name, moff,
1342 				 kern_moff);
1343 
1344 			continue;
1345 		}
1346 
1347 		kern_msize = btf__resolve_size(kern_btf, kern_mtype_id);
1348 		if (kern_msize < 0 || msize != kern_msize) {
1349 			pr_warn("struct_ops init_kern %s: Error in size of member %s: %zd != %zd(kernel)\n",
1350 				map->name, mname, (ssize_t)msize,
1351 				(ssize_t)kern_msize);
1352 			return -ENOTSUP;
1353 		}
1354 
1355 		pr_debug("struct_ops init_kern %s: copy %s %u bytes from data(+%u) to kern_data(+%u)\n",
1356 			 map->name, mname, (unsigned int)msize,
1357 			 moff, kern_moff);
1358 		memcpy(kern_mdata, mdata, msize);
1359 	}
1360 
1361 	return 0;
1362 }
1363 
1364 static int bpf_object__init_kern_struct_ops_maps(struct bpf_object *obj)
1365 {
1366 	struct bpf_map *map;
1367 	size_t i;
1368 	int err;
1369 
1370 	for (i = 0; i < obj->nr_maps; i++) {
1371 		map = &obj->maps[i];
1372 
1373 		if (!bpf_map__is_struct_ops(map))
1374 			continue;
1375 
1376 		if (!map->autocreate)
1377 			continue;
1378 
1379 		err = bpf_map__init_kern_struct_ops(map);
1380 		if (err)
1381 			return err;
1382 	}
1383 
1384 	return 0;
1385 }
1386 
1387 static int init_struct_ops_maps(struct bpf_object *obj, const char *sec_name,
1388 				int shndx, Elf_Data *data)
1389 {
1390 	const struct btf_type *type, *datasec;
1391 	const struct btf_var_secinfo *vsi;
1392 	struct bpf_struct_ops *st_ops;
1393 	const char *tname, *var_name;
1394 	__s32 type_id, datasec_id;
1395 	const struct btf *btf;
1396 	struct bpf_map *map;
1397 	__u32 i;
1398 
1399 	if (shndx == -1)
1400 		return 0;
1401 
1402 	btf = obj->btf;
1403 	datasec_id = btf__find_by_name_kind(btf, sec_name,
1404 					    BTF_KIND_DATASEC);
1405 	if (datasec_id < 0) {
1406 		pr_warn("struct_ops init: DATASEC %s not found\n",
1407 			sec_name);
1408 		return -EINVAL;
1409 	}
1410 
1411 	datasec = btf__type_by_id(btf, datasec_id);
1412 	vsi = btf_var_secinfos(datasec);
1413 	for (i = 0; i < btf_vlen(datasec); i++, vsi++) {
1414 		type = btf__type_by_id(obj->btf, vsi->type);
1415 		var_name = btf__name_by_offset(obj->btf, type->name_off);
1416 
1417 		type_id = btf__resolve_type(obj->btf, vsi->type);
1418 		if (type_id < 0) {
1419 			pr_warn("struct_ops init: Cannot resolve var type_id %u in DATASEC %s\n",
1420 				vsi->type, sec_name);
1421 			return -EINVAL;
1422 		}
1423 
1424 		type = btf__type_by_id(obj->btf, type_id);
1425 		tname = btf__name_by_offset(obj->btf, type->name_off);
1426 		if (!tname[0]) {
1427 			pr_warn("struct_ops init: anonymous type is not supported\n");
1428 			return -ENOTSUP;
1429 		}
1430 		if (!btf_is_struct(type)) {
1431 			pr_warn("struct_ops init: %s is not a struct\n", tname);
1432 			return -EINVAL;
1433 		}
1434 
1435 		map = bpf_object__add_map(obj);
1436 		if (IS_ERR(map))
1437 			return PTR_ERR(map);
1438 
1439 		map->sec_idx = shndx;
1440 		map->sec_offset = vsi->offset;
1441 		map->name = strdup(var_name);
1442 		if (!map->name)
1443 			return -ENOMEM;
1444 		map->btf_value_type_id = type_id;
1445 
1446 		/* Follow same convention as for programs autoload:
1447 		 * SEC("?.struct_ops") means map is not created by default.
1448 		 */
1449 		if (sec_name[0] == '?') {
1450 			map->autocreate = false;
1451 			/* from now on forget there was ? in section name */
1452 			sec_name++;
1453 		}
1454 
1455 		map->def.type = BPF_MAP_TYPE_STRUCT_OPS;
1456 		map->def.key_size = sizeof(int);
1457 		map->def.value_size = type->size;
1458 		map->def.max_entries = 1;
1459 		map->def.map_flags = strcmp(sec_name, STRUCT_OPS_LINK_SEC) == 0 ? BPF_F_LINK : 0;
1460 		map->autoattach = true;
1461 
1462 		map->st_ops = calloc(1, sizeof(*map->st_ops));
1463 		if (!map->st_ops)
1464 			return -ENOMEM;
1465 		st_ops = map->st_ops;
1466 		st_ops->data = malloc(type->size);
1467 		st_ops->progs = calloc(btf_vlen(type), sizeof(*st_ops->progs));
1468 		st_ops->kern_func_off = malloc(btf_vlen(type) *
1469 					       sizeof(*st_ops->kern_func_off));
1470 		if (!st_ops->data || !st_ops->progs || !st_ops->kern_func_off)
1471 			return -ENOMEM;
1472 
1473 		if (vsi->offset + type->size > data->d_size) {
1474 			pr_warn("struct_ops init: var %s is beyond the end of DATASEC %s\n",
1475 				var_name, sec_name);
1476 			return -EINVAL;
1477 		}
1478 
1479 		memcpy(st_ops->data,
1480 		       data->d_buf + vsi->offset,
1481 		       type->size);
1482 		st_ops->type_id = type_id;
1483 
1484 		pr_debug("struct_ops init: struct %s(type_id=%u) %s found at offset %u\n",
1485 			 tname, type_id, var_name, vsi->offset);
1486 	}
1487 
1488 	return 0;
1489 }
1490 
1491 static int bpf_object_init_struct_ops(struct bpf_object *obj)
1492 {
1493 	const char *sec_name;
1494 	int sec_idx, err;
1495 
1496 	for (sec_idx = 0; sec_idx < obj->efile.sec_cnt; ++sec_idx) {
1497 		struct elf_sec_desc *desc = &obj->efile.secs[sec_idx];
1498 
1499 		if (desc->sec_type != SEC_ST_OPS)
1500 			continue;
1501 
1502 		sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1503 		if (!sec_name)
1504 			return -LIBBPF_ERRNO__FORMAT;
1505 
1506 		err = init_struct_ops_maps(obj, sec_name, sec_idx, desc->data);
1507 		if (err)
1508 			return err;
1509 	}
1510 
1511 	return 0;
1512 }
1513 
1514 static struct bpf_object *bpf_object__new(const char *path,
1515 					  const void *obj_buf,
1516 					  size_t obj_buf_sz,
1517 					  const char *obj_name)
1518 {
1519 	struct bpf_object *obj;
1520 	char *end;
1521 
1522 	obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
1523 	if (!obj) {
1524 		pr_warn("alloc memory failed for %s\n", path);
1525 		return ERR_PTR(-ENOMEM);
1526 	}
1527 
1528 	strcpy(obj->path, path);
1529 	if (obj_name) {
1530 		libbpf_strlcpy(obj->name, obj_name, sizeof(obj->name));
1531 	} else {
1532 		/* Using basename() GNU version which doesn't modify arg. */
1533 		libbpf_strlcpy(obj->name, basename((void *)path), sizeof(obj->name));
1534 		end = strchr(obj->name, '.');
1535 		if (end)
1536 			*end = 0;
1537 	}
1538 
1539 	obj->efile.fd = -1;
1540 	/*
1541 	 * Caller of this function should also call
1542 	 * bpf_object__elf_finish() after data collection to return
1543 	 * obj_buf to user. If not, we should duplicate the buffer to
1544 	 * avoid user freeing them before elf finish.
1545 	 */
1546 	obj->efile.obj_buf = obj_buf;
1547 	obj->efile.obj_buf_sz = obj_buf_sz;
1548 	obj->efile.btf_maps_shndx = -1;
1549 	obj->kconfig_map_idx = -1;
1550 	obj->arena_map_idx = -1;
1551 
1552 	obj->kern_version = get_kernel_version();
1553 	obj->state  = OBJ_OPEN;
1554 
1555 	return obj;
1556 }
1557 
1558 static void bpf_object__elf_finish(struct bpf_object *obj)
1559 {
1560 	if (!obj->efile.elf)
1561 		return;
1562 
1563 	elf_end(obj->efile.elf);
1564 	obj->efile.elf = NULL;
1565 	obj->efile.ehdr = NULL;
1566 	obj->efile.symbols = NULL;
1567 	obj->efile.arena_data = NULL;
1568 
1569 	zfree(&obj->efile.secs);
1570 	obj->efile.sec_cnt = 0;
1571 	zclose(obj->efile.fd);
1572 	obj->efile.obj_buf = NULL;
1573 	obj->efile.obj_buf_sz = 0;
1574 }
1575 
1576 static int bpf_object__elf_init(struct bpf_object *obj)
1577 {
1578 	Elf64_Ehdr *ehdr;
1579 	int err = 0;
1580 	Elf *elf;
1581 
1582 	if (obj->efile.elf) {
1583 		pr_warn("elf: init internal error\n");
1584 		return -LIBBPF_ERRNO__LIBELF;
1585 	}
1586 
1587 	if (obj->efile.obj_buf_sz > 0) {
1588 		/* obj_buf should have been validated by bpf_object__open_mem(). */
1589 		elf = elf_memory((char *)obj->efile.obj_buf, obj->efile.obj_buf_sz);
1590 	} else {
1591 		obj->efile.fd = open(obj->path, O_RDONLY | O_CLOEXEC);
1592 		if (obj->efile.fd < 0) {
1593 			err = -errno;
1594 			pr_warn("elf: failed to open %s: %s\n", obj->path, errstr(err));
1595 			return err;
1596 		}
1597 
1598 		elf = elf_begin(obj->efile.fd, ELF_C_READ_MMAP, NULL);
1599 	}
1600 
1601 	if (!elf) {
1602 		pr_warn("elf: failed to open %s as ELF file: %s\n", obj->path, elf_errmsg(-1));
1603 		err = -LIBBPF_ERRNO__LIBELF;
1604 		goto errout;
1605 	}
1606 
1607 	obj->efile.elf = elf;
1608 
1609 	if (elf_kind(elf) != ELF_K_ELF) {
1610 		err = -LIBBPF_ERRNO__FORMAT;
1611 		pr_warn("elf: '%s' is not a proper ELF object\n", obj->path);
1612 		goto errout;
1613 	}
1614 
1615 	if (gelf_getclass(elf) != ELFCLASS64) {
1616 		err = -LIBBPF_ERRNO__FORMAT;
1617 		pr_warn("elf: '%s' is not a 64-bit ELF object\n", obj->path);
1618 		goto errout;
1619 	}
1620 
1621 	obj->efile.ehdr = ehdr = elf64_getehdr(elf);
1622 	if (!obj->efile.ehdr) {
1623 		pr_warn("elf: failed to get ELF header from %s: %s\n", obj->path, elf_errmsg(-1));
1624 		err = -LIBBPF_ERRNO__FORMAT;
1625 		goto errout;
1626 	}
1627 
1628 	/* Validate ELF object endianness... */
1629 	if (ehdr->e_ident[EI_DATA] != ELFDATA2LSB &&
1630 	    ehdr->e_ident[EI_DATA] != ELFDATA2MSB) {
1631 		err = -LIBBPF_ERRNO__ENDIAN;
1632 		pr_warn("elf: '%s' has unknown byte order\n", obj->path);
1633 		goto errout;
1634 	}
1635 	/* and save after bpf_object_open() frees ELF data */
1636 	obj->byteorder = ehdr->e_ident[EI_DATA];
1637 
1638 	if (elf_getshdrstrndx(elf, &obj->efile.shstrndx)) {
1639 		pr_warn("elf: failed to get section names section index for %s: %s\n",
1640 			obj->path, elf_errmsg(-1));
1641 		err = -LIBBPF_ERRNO__FORMAT;
1642 		goto errout;
1643 	}
1644 
1645 	/* ELF is corrupted/truncated, avoid calling elf_strptr. */
1646 	if (!elf_rawdata(elf_getscn(elf, obj->efile.shstrndx), NULL)) {
1647 		pr_warn("elf: failed to get section names strings from %s: %s\n",
1648 			obj->path, elf_errmsg(-1));
1649 		err = -LIBBPF_ERRNO__FORMAT;
1650 		goto errout;
1651 	}
1652 
1653 	/* Old LLVM set e_machine to EM_NONE */
1654 	if (ehdr->e_type != ET_REL || (ehdr->e_machine && ehdr->e_machine != EM_BPF)) {
1655 		pr_warn("elf: %s is not a valid eBPF object file\n", obj->path);
1656 		err = -LIBBPF_ERRNO__FORMAT;
1657 		goto errout;
1658 	}
1659 
1660 	return 0;
1661 errout:
1662 	bpf_object__elf_finish(obj);
1663 	return err;
1664 }
1665 
1666 static bool is_native_endianness(struct bpf_object *obj)
1667 {
1668 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1669 	return obj->byteorder == ELFDATA2LSB;
1670 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
1671 	return obj->byteorder == ELFDATA2MSB;
1672 #else
1673 # error "Unrecognized __BYTE_ORDER__"
1674 #endif
1675 }
1676 
1677 static int
1678 bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
1679 {
1680 	if (!data) {
1681 		pr_warn("invalid license section in %s\n", obj->path);
1682 		return -LIBBPF_ERRNO__FORMAT;
1683 	}
1684 	/* libbpf_strlcpy() only copies first N - 1 bytes, so size + 1 won't
1685 	 * go over allowed ELF data section buffer
1686 	 */
1687 	libbpf_strlcpy(obj->license, data, min(size + 1, sizeof(obj->license)));
1688 	pr_debug("license of %s is %s\n", obj->path, obj->license);
1689 	return 0;
1690 }
1691 
1692 static int
1693 bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
1694 {
1695 	__u32 kver;
1696 
1697 	if (!data || size != sizeof(kver)) {
1698 		pr_warn("invalid kver section in %s\n", obj->path);
1699 		return -LIBBPF_ERRNO__FORMAT;
1700 	}
1701 	memcpy(&kver, data, sizeof(kver));
1702 	obj->kern_version = kver;
1703 	pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
1704 	return 0;
1705 }
1706 
1707 static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
1708 {
1709 	if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
1710 	    type == BPF_MAP_TYPE_HASH_OF_MAPS)
1711 		return true;
1712 	return false;
1713 }
1714 
1715 static int find_elf_sec_sz(const struct bpf_object *obj, const char *name, __u32 *size)
1716 {
1717 	Elf_Data *data;
1718 	Elf_Scn *scn;
1719 
1720 	if (!name)
1721 		return -EINVAL;
1722 
1723 	scn = elf_sec_by_name(obj, name);
1724 	data = elf_sec_data(obj, scn);
1725 	if (data) {
1726 		*size = data->d_size;
1727 		return 0; /* found it */
1728 	}
1729 
1730 	return -ENOENT;
1731 }
1732 
1733 static Elf64_Sym *find_elf_var_sym(const struct bpf_object *obj, const char *name)
1734 {
1735 	Elf_Data *symbols = obj->efile.symbols;
1736 	const char *sname;
1737 	size_t si;
1738 
1739 	for (si = 0; si < symbols->d_size / sizeof(Elf64_Sym); si++) {
1740 		Elf64_Sym *sym = elf_sym_by_idx(obj, si);
1741 
1742 		if (ELF64_ST_TYPE(sym->st_info) != STT_OBJECT)
1743 			continue;
1744 
1745 		if (ELF64_ST_BIND(sym->st_info) != STB_GLOBAL &&
1746 		    ELF64_ST_BIND(sym->st_info) != STB_WEAK)
1747 			continue;
1748 
1749 		sname = elf_sym_str(obj, sym->st_name);
1750 		if (!sname) {
1751 			pr_warn("failed to get sym name string for var %s\n", name);
1752 			return ERR_PTR(-EIO);
1753 		}
1754 		if (strcmp(name, sname) == 0)
1755 			return sym;
1756 	}
1757 
1758 	return ERR_PTR(-ENOENT);
1759 }
1760 
1761 #ifndef MFD_CLOEXEC
1762 #define MFD_CLOEXEC 0x0001U
1763 #endif
1764 #ifndef MFD_NOEXEC_SEAL
1765 #define MFD_NOEXEC_SEAL 0x0008U
1766 #endif
1767 
1768 static int create_placeholder_fd(void)
1769 {
1770 	unsigned int flags = MFD_CLOEXEC | MFD_NOEXEC_SEAL;
1771 	const char *name = "libbpf-placeholder-fd";
1772 	int fd;
1773 
1774 	fd = ensure_good_fd(sys_memfd_create(name, flags));
1775 	if (fd >= 0)
1776 		return fd;
1777 	else if (errno != EINVAL)
1778 		return -errno;
1779 
1780 	/* Possibly running on kernel without MFD_NOEXEC_SEAL */
1781 	fd = ensure_good_fd(sys_memfd_create(name, flags & ~MFD_NOEXEC_SEAL));
1782 	if (fd < 0)
1783 		return -errno;
1784 	return fd;
1785 }
1786 
1787 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
1788 {
1789 	struct bpf_map *map;
1790 	int err;
1791 
1792 	err = libbpf_ensure_mem((void **)&obj->maps, &obj->maps_cap,
1793 				sizeof(*obj->maps), obj->nr_maps + 1);
1794 	if (err)
1795 		return ERR_PTR(err);
1796 
1797 	map = &obj->maps[obj->nr_maps++];
1798 	map->obj = obj;
1799 	/* Preallocate map FD without actually creating BPF map just yet.
1800 	 * These map FD "placeholders" will be reused later without changing
1801 	 * FD value when map is actually created in the kernel.
1802 	 *
1803 	 * This is useful to be able to perform BPF program relocations
1804 	 * without having to create BPF maps before that step. This allows us
1805 	 * to finalize and load BTF very late in BPF object's loading phase,
1806 	 * right before BPF maps have to be created and BPF programs have to
1807 	 * be loaded. By having these map FD placeholders we can perform all
1808 	 * the sanitizations, relocations, and any other adjustments before we
1809 	 * start creating actual BPF kernel objects (BTF, maps, progs).
1810 	 */
1811 	map->fd = create_placeholder_fd();
1812 	if (map->fd < 0)
1813 		return ERR_PTR(map->fd);
1814 	map->inner_map_fd = -1;
1815 	map->autocreate = true;
1816 
1817 	return map;
1818 }
1819 
1820 static size_t array_map_mmap_sz(unsigned int value_sz, unsigned int max_entries)
1821 {
1822 	const long page_sz = sysconf(_SC_PAGE_SIZE);
1823 	size_t map_sz;
1824 
1825 	map_sz = (size_t)roundup(value_sz, 8) * max_entries;
1826 	map_sz = roundup(map_sz, page_sz);
1827 	return map_sz;
1828 }
1829 
1830 static size_t bpf_map_mmap_sz(const struct bpf_map *map)
1831 {
1832 	const long page_sz = sysconf(_SC_PAGE_SIZE);
1833 
1834 	switch (map->def.type) {
1835 	case BPF_MAP_TYPE_ARRAY:
1836 		return array_map_mmap_sz(map->def.value_size, map->def.max_entries);
1837 	case BPF_MAP_TYPE_ARENA:
1838 		return page_sz * map->def.max_entries;
1839 	default:
1840 		return 0; /* not supported */
1841 	}
1842 }
1843 
1844 static int bpf_map_mmap_resize(struct bpf_map *map, size_t old_sz, size_t new_sz)
1845 {
1846 	void *mmaped;
1847 
1848 	if (!map->mmaped)
1849 		return -EINVAL;
1850 
1851 	if (old_sz == new_sz)
1852 		return 0;
1853 
1854 	mmaped = mmap(NULL, new_sz, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1855 	if (mmaped == MAP_FAILED)
1856 		return -errno;
1857 
1858 	memcpy(mmaped, map->mmaped, min(old_sz, new_sz));
1859 	munmap(map->mmaped, old_sz);
1860 	map->mmaped = mmaped;
1861 	return 0;
1862 }
1863 
1864 static char *internal_map_name(struct bpf_object *obj, const char *real_name)
1865 {
1866 	char map_name[BPF_OBJ_NAME_LEN], *p;
1867 	int pfx_len, sfx_len = max((size_t)7, strlen(real_name));
1868 
1869 	/* This is one of the more confusing parts of libbpf for various
1870 	 * reasons, some of which are historical. The original idea for naming
1871 	 * internal names was to include as much of BPF object name prefix as
1872 	 * possible, so that it can be distinguished from similar internal
1873 	 * maps of a different BPF object.
1874 	 * As an example, let's say we have bpf_object named 'my_object_name'
1875 	 * and internal map corresponding to '.rodata' ELF section. The final
1876 	 * map name advertised to user and to the kernel will be
1877 	 * 'my_objec.rodata', taking first 8 characters of object name and
1878 	 * entire 7 characters of '.rodata'.
1879 	 * Somewhat confusingly, if internal map ELF section name is shorter
1880 	 * than 7 characters, e.g., '.bss', we still reserve 7 characters
1881 	 * for the suffix, even though we only have 4 actual characters, and
1882 	 * resulting map will be called 'my_objec.bss', not even using all 15
1883 	 * characters allowed by the kernel. Oh well, at least the truncated
1884 	 * object name is somewhat consistent in this case. But if the map
1885 	 * name is '.kconfig', we'll still have entirety of '.kconfig' added
1886 	 * (8 chars) and thus will be left with only first 7 characters of the
1887 	 * object name ('my_obje'). Happy guessing, user, that the final map
1888 	 * name will be "my_obje.kconfig".
1889 	 * Now, with libbpf starting to support arbitrarily named .rodata.*
1890 	 * and .data.* data sections, it's possible that ELF section name is
1891 	 * longer than allowed 15 chars, so we now need to be careful to take
1892 	 * only up to 15 first characters of ELF name, taking no BPF object
1893 	 * name characters at all. So '.rodata.abracadabra' will result in
1894 	 * '.rodata.abracad' kernel and user-visible name.
1895 	 * We need to keep this convoluted logic intact for .data, .bss and
1896 	 * .rodata maps, but for new custom .data.custom and .rodata.custom
1897 	 * maps we use their ELF names as is, not prepending bpf_object name
1898 	 * in front. We still need to truncate them to 15 characters for the
1899 	 * kernel. Full name can be recovered for such maps by using DATASEC
1900 	 * BTF type associated with such map's value type, though.
1901 	 */
1902 	if (sfx_len >= BPF_OBJ_NAME_LEN)
1903 		sfx_len = BPF_OBJ_NAME_LEN - 1;
1904 
1905 	/* if there are two or more dots in map name, it's a custom dot map */
1906 	if (strchr(real_name + 1, '.') != NULL)
1907 		pfx_len = 0;
1908 	else
1909 		pfx_len = min((size_t)BPF_OBJ_NAME_LEN - sfx_len - 1, strlen(obj->name));
1910 
1911 	snprintf(map_name, sizeof(map_name), "%.*s%.*s", pfx_len, obj->name,
1912 		 sfx_len, real_name);
1913 
1914 	/* sanities map name to characters allowed by kernel */
1915 	for (p = map_name; *p && p < map_name + sizeof(map_name); p++)
1916 		if (!isalnum(*p) && *p != '_' && *p != '.')
1917 			*p = '_';
1918 
1919 	return strdup(map_name);
1920 }
1921 
1922 static int
1923 map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map);
1924 
1925 /* Internal BPF map is mmap()'able only if at least one of corresponding
1926  * DATASEC's VARs are to be exposed through BPF skeleton. I.e., it's a GLOBAL
1927  * variable and it's not marked as __hidden (which turns it into, effectively,
1928  * a STATIC variable).
1929  */
1930 static bool map_is_mmapable(struct bpf_object *obj, struct bpf_map *map)
1931 {
1932 	const struct btf_type *t, *vt;
1933 	struct btf_var_secinfo *vsi;
1934 	int i, n;
1935 
1936 	if (!map->btf_value_type_id)
1937 		return false;
1938 
1939 	t = btf__type_by_id(obj->btf, map->btf_value_type_id);
1940 	if (!btf_is_datasec(t))
1941 		return false;
1942 
1943 	vsi = btf_var_secinfos(t);
1944 	for (i = 0, n = btf_vlen(t); i < n; i++, vsi++) {
1945 		vt = btf__type_by_id(obj->btf, vsi->type);
1946 		if (!btf_is_var(vt))
1947 			continue;
1948 
1949 		if (btf_var(vt)->linkage != BTF_VAR_STATIC)
1950 			return true;
1951 	}
1952 
1953 	return false;
1954 }
1955 
1956 static int
1957 bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
1958 			      const char *real_name, int sec_idx, void *data, size_t data_sz)
1959 {
1960 	struct bpf_map_def *def;
1961 	struct bpf_map *map;
1962 	size_t mmap_sz;
1963 	int err;
1964 
1965 	map = bpf_object__add_map(obj);
1966 	if (IS_ERR(map))
1967 		return PTR_ERR(map);
1968 
1969 	map->libbpf_type = type;
1970 	map->sec_idx = sec_idx;
1971 	map->sec_offset = 0;
1972 	map->real_name = strdup(real_name);
1973 	map->name = internal_map_name(obj, real_name);
1974 	if (!map->real_name || !map->name) {
1975 		zfree(&map->real_name);
1976 		zfree(&map->name);
1977 		return -ENOMEM;
1978 	}
1979 
1980 	def = &map->def;
1981 	def->type = BPF_MAP_TYPE_ARRAY;
1982 	def->key_size = sizeof(int);
1983 	def->value_size = data_sz;
1984 	def->max_entries = 1;
1985 	def->map_flags = type == LIBBPF_MAP_RODATA || type == LIBBPF_MAP_KCONFIG
1986 		? BPF_F_RDONLY_PROG : 0;
1987 
1988 	/* failures are fine because of maps like .rodata.str1.1 */
1989 	(void) map_fill_btf_type_info(obj, map);
1990 
1991 	if (map_is_mmapable(obj, map))
1992 		def->map_flags |= BPF_F_MMAPABLE;
1993 
1994 	pr_debug("map '%s' (global data): at sec_idx %d, offset %zu, flags %x.\n",
1995 		 map->name, map->sec_idx, map->sec_offset, def->map_flags);
1996 
1997 	mmap_sz = bpf_map_mmap_sz(map);
1998 	map->mmaped = mmap(NULL, mmap_sz, PROT_READ | PROT_WRITE,
1999 			   MAP_SHARED | MAP_ANONYMOUS, -1, 0);
2000 	if (map->mmaped == MAP_FAILED) {
2001 		err = -errno;
2002 		map->mmaped = NULL;
2003 		pr_warn("failed to alloc map '%s' content buffer: %s\n", map->name, errstr(err));
2004 		zfree(&map->real_name);
2005 		zfree(&map->name);
2006 		return err;
2007 	}
2008 
2009 	if (data)
2010 		memcpy(map->mmaped, data, data_sz);
2011 
2012 	pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
2013 	return 0;
2014 }
2015 
2016 static int bpf_object__init_global_data_maps(struct bpf_object *obj)
2017 {
2018 	struct elf_sec_desc *sec_desc;
2019 	const char *sec_name;
2020 	int err = 0, sec_idx;
2021 
2022 	/*
2023 	 * Populate obj->maps with libbpf internal maps.
2024 	 */
2025 	for (sec_idx = 1; sec_idx < obj->efile.sec_cnt; sec_idx++) {
2026 		sec_desc = &obj->efile.secs[sec_idx];
2027 
2028 		/* Skip recognized sections with size 0. */
2029 		if (!sec_desc->data || sec_desc->data->d_size == 0)
2030 			continue;
2031 
2032 		switch (sec_desc->sec_type) {
2033 		case SEC_DATA:
2034 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
2035 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
2036 							    sec_name, sec_idx,
2037 							    sec_desc->data->d_buf,
2038 							    sec_desc->data->d_size);
2039 			break;
2040 		case SEC_RODATA:
2041 			obj->has_rodata = true;
2042 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
2043 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
2044 							    sec_name, sec_idx,
2045 							    sec_desc->data->d_buf,
2046 							    sec_desc->data->d_size);
2047 			break;
2048 		case SEC_BSS:
2049 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
2050 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
2051 							    sec_name, sec_idx,
2052 							    NULL,
2053 							    sec_desc->data->d_size);
2054 			break;
2055 		default:
2056 			/* skip */
2057 			break;
2058 		}
2059 		if (err)
2060 			return err;
2061 	}
2062 	return 0;
2063 }
2064 
2065 
2066 static struct extern_desc *find_extern_by_name(const struct bpf_object *obj,
2067 					       const void *name)
2068 {
2069 	int i;
2070 
2071 	for (i = 0; i < obj->nr_extern; i++) {
2072 		if (strcmp(obj->externs[i].name, name) == 0)
2073 			return &obj->externs[i];
2074 	}
2075 	return NULL;
2076 }
2077 
2078 static struct extern_desc *find_extern_by_name_with_len(const struct bpf_object *obj,
2079 							const void *name, int len)
2080 {
2081 	const char *ext_name;
2082 	int i;
2083 
2084 	for (i = 0; i < obj->nr_extern; i++) {
2085 		ext_name = obj->externs[i].name;
2086 		if (strlen(ext_name) == len && strncmp(ext_name, name, len) == 0)
2087 			return &obj->externs[i];
2088 	}
2089 	return NULL;
2090 }
2091 
2092 static int set_kcfg_value_tri(struct extern_desc *ext, void *ext_val,
2093 			      char value)
2094 {
2095 	switch (ext->kcfg.type) {
2096 	case KCFG_BOOL:
2097 		if (value == 'm') {
2098 			pr_warn("extern (kcfg) '%s': value '%c' implies tristate or char type\n",
2099 				ext->name, value);
2100 			return -EINVAL;
2101 		}
2102 		*(bool *)ext_val = value == 'y' ? true : false;
2103 		break;
2104 	case KCFG_TRISTATE:
2105 		if (value == 'y')
2106 			*(enum libbpf_tristate *)ext_val = TRI_YES;
2107 		else if (value == 'm')
2108 			*(enum libbpf_tristate *)ext_val = TRI_MODULE;
2109 		else /* value == 'n' */
2110 			*(enum libbpf_tristate *)ext_val = TRI_NO;
2111 		break;
2112 	case KCFG_CHAR:
2113 		*(char *)ext_val = value;
2114 		break;
2115 	case KCFG_UNKNOWN:
2116 	case KCFG_INT:
2117 	case KCFG_CHAR_ARR:
2118 	default:
2119 		pr_warn("extern (kcfg) '%s': value '%c' implies bool, tristate, or char type\n",
2120 			ext->name, value);
2121 		return -EINVAL;
2122 	}
2123 	ext->is_set = true;
2124 	return 0;
2125 }
2126 
2127 static int set_kcfg_value_str(struct extern_desc *ext, char *ext_val,
2128 			      const char *value)
2129 {
2130 	size_t len;
2131 
2132 	if (ext->kcfg.type != KCFG_CHAR_ARR) {
2133 		pr_warn("extern (kcfg) '%s': value '%s' implies char array type\n",
2134 			ext->name, value);
2135 		return -EINVAL;
2136 	}
2137 
2138 	len = strlen(value);
2139 	if (len < 2 || value[len - 1] != '"') {
2140 		pr_warn("extern (kcfg) '%s': invalid string config '%s'\n",
2141 			ext->name, value);
2142 		return -EINVAL;
2143 	}
2144 
2145 	/* strip quotes */
2146 	len -= 2;
2147 	if (len >= ext->kcfg.sz) {
2148 		pr_warn("extern (kcfg) '%s': long string '%s' of (%zu bytes) truncated to %d bytes\n",
2149 			ext->name, value, len, ext->kcfg.sz - 1);
2150 		len = ext->kcfg.sz - 1;
2151 	}
2152 	memcpy(ext_val, value + 1, len);
2153 	ext_val[len] = '\0';
2154 	ext->is_set = true;
2155 	return 0;
2156 }
2157 
2158 static int parse_u64(const char *value, __u64 *res)
2159 {
2160 	char *value_end;
2161 	int err;
2162 
2163 	errno = 0;
2164 	*res = strtoull(value, &value_end, 0);
2165 	if (errno) {
2166 		err = -errno;
2167 		pr_warn("failed to parse '%s': %s\n", value, errstr(err));
2168 		return err;
2169 	}
2170 	if (*value_end) {
2171 		pr_warn("failed to parse '%s' as integer completely\n", value);
2172 		return -EINVAL;
2173 	}
2174 	return 0;
2175 }
2176 
2177 static bool is_kcfg_value_in_range(const struct extern_desc *ext, __u64 v)
2178 {
2179 	int bit_sz = ext->kcfg.sz * 8;
2180 
2181 	if (ext->kcfg.sz == 8)
2182 		return true;
2183 
2184 	/* Validate that value stored in u64 fits in integer of `ext->sz`
2185 	 * bytes size without any loss of information. If the target integer
2186 	 * is signed, we rely on the following limits of integer type of
2187 	 * Y bits and subsequent transformation:
2188 	 *
2189 	 *     -2^(Y-1) <= X           <= 2^(Y-1) - 1
2190 	 *            0 <= X + 2^(Y-1) <= 2^Y - 1
2191 	 *            0 <= X + 2^(Y-1) <  2^Y
2192 	 *
2193 	 *  For unsigned target integer, check that all the (64 - Y) bits are
2194 	 *  zero.
2195 	 */
2196 	if (ext->kcfg.is_signed)
2197 		return v + (1ULL << (bit_sz - 1)) < (1ULL << bit_sz);
2198 	else
2199 		return (v >> bit_sz) == 0;
2200 }
2201 
2202 static int set_kcfg_value_num(struct extern_desc *ext, void *ext_val,
2203 			      __u64 value)
2204 {
2205 	if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR &&
2206 	    ext->kcfg.type != KCFG_BOOL) {
2207 		pr_warn("extern (kcfg) '%s': value '%llu' implies integer, char, or boolean type\n",
2208 			ext->name, (unsigned long long)value);
2209 		return -EINVAL;
2210 	}
2211 	if (ext->kcfg.type == KCFG_BOOL && value > 1) {
2212 		pr_warn("extern (kcfg) '%s': value '%llu' isn't boolean compatible\n",
2213 			ext->name, (unsigned long long)value);
2214 		return -EINVAL;
2215 
2216 	}
2217 	if (!is_kcfg_value_in_range(ext, value)) {
2218 		pr_warn("extern (kcfg) '%s': value '%llu' doesn't fit in %d bytes\n",
2219 			ext->name, (unsigned long long)value, ext->kcfg.sz);
2220 		return -ERANGE;
2221 	}
2222 	switch (ext->kcfg.sz) {
2223 	case 1:
2224 		*(__u8 *)ext_val = value;
2225 		break;
2226 	case 2:
2227 		*(__u16 *)ext_val = value;
2228 		break;
2229 	case 4:
2230 		*(__u32 *)ext_val = value;
2231 		break;
2232 	case 8:
2233 		*(__u64 *)ext_val = value;
2234 		break;
2235 	default:
2236 		return -EINVAL;
2237 	}
2238 	ext->is_set = true;
2239 	return 0;
2240 }
2241 
2242 static int bpf_object__process_kconfig_line(struct bpf_object *obj,
2243 					    char *buf, void *data)
2244 {
2245 	struct extern_desc *ext;
2246 	char *sep, *value;
2247 	int len, err = 0;
2248 	void *ext_val;
2249 	__u64 num;
2250 
2251 	if (!str_has_pfx(buf, "CONFIG_"))
2252 		return 0;
2253 
2254 	sep = strchr(buf, '=');
2255 	if (!sep) {
2256 		pr_warn("failed to parse '%s': no separator\n", buf);
2257 		return -EINVAL;
2258 	}
2259 
2260 	/* Trim ending '\n' */
2261 	len = strlen(buf);
2262 	if (buf[len - 1] == '\n')
2263 		buf[len - 1] = '\0';
2264 	/* Split on '=' and ensure that a value is present. */
2265 	*sep = '\0';
2266 	if (!sep[1]) {
2267 		*sep = '=';
2268 		pr_warn("failed to parse '%s': no value\n", buf);
2269 		return -EINVAL;
2270 	}
2271 
2272 	ext = find_extern_by_name(obj, buf);
2273 	if (!ext || ext->is_set)
2274 		return 0;
2275 
2276 	ext_val = data + ext->kcfg.data_off;
2277 	value = sep + 1;
2278 
2279 	switch (*value) {
2280 	case 'y': case 'n': case 'm':
2281 		err = set_kcfg_value_tri(ext, ext_val, *value);
2282 		break;
2283 	case '"':
2284 		err = set_kcfg_value_str(ext, ext_val, value);
2285 		break;
2286 	default:
2287 		/* assume integer */
2288 		err = parse_u64(value, &num);
2289 		if (err) {
2290 			pr_warn("extern (kcfg) '%s': value '%s' isn't a valid integer\n", ext->name, value);
2291 			return err;
2292 		}
2293 		if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR) {
2294 			pr_warn("extern (kcfg) '%s': value '%s' implies integer type\n", ext->name, value);
2295 			return -EINVAL;
2296 		}
2297 		err = set_kcfg_value_num(ext, ext_val, num);
2298 		break;
2299 	}
2300 	if (err)
2301 		return err;
2302 	pr_debug("extern (kcfg) '%s': set to %s\n", ext->name, value);
2303 	return 0;
2304 }
2305 
2306 static int bpf_object__read_kconfig_file(struct bpf_object *obj, void *data)
2307 {
2308 	char buf[PATH_MAX];
2309 	struct utsname uts;
2310 	int len, err = 0;
2311 	gzFile file;
2312 
2313 	uname(&uts);
2314 	len = snprintf(buf, PATH_MAX, "/boot/config-%s", uts.release);
2315 	if (len < 0)
2316 		return -EINVAL;
2317 	else if (len >= PATH_MAX)
2318 		return -ENAMETOOLONG;
2319 
2320 	/* gzopen also accepts uncompressed files. */
2321 	file = gzopen(buf, "re");
2322 	if (!file)
2323 		file = gzopen("/proc/config.gz", "re");
2324 
2325 	if (!file) {
2326 		pr_warn("failed to open system Kconfig\n");
2327 		return -ENOENT;
2328 	}
2329 
2330 	while (gzgets(file, buf, sizeof(buf))) {
2331 		err = bpf_object__process_kconfig_line(obj, buf, data);
2332 		if (err) {
2333 			pr_warn("error parsing system Kconfig line '%s': %s\n",
2334 				buf, errstr(err));
2335 			goto out;
2336 		}
2337 	}
2338 
2339 out:
2340 	gzclose(file);
2341 	return err;
2342 }
2343 
2344 static int bpf_object__read_kconfig_mem(struct bpf_object *obj,
2345 					const char *config, void *data)
2346 {
2347 	char buf[PATH_MAX];
2348 	int err = 0;
2349 	FILE *file;
2350 
2351 	file = fmemopen((void *)config, strlen(config), "r");
2352 	if (!file) {
2353 		err = -errno;
2354 		pr_warn("failed to open in-memory Kconfig: %s\n", errstr(err));
2355 		return err;
2356 	}
2357 
2358 	while (fgets(buf, sizeof(buf), file)) {
2359 		err = bpf_object__process_kconfig_line(obj, buf, data);
2360 		if (err) {
2361 			pr_warn("error parsing in-memory Kconfig line '%s': %s\n",
2362 				buf, errstr(err));
2363 			break;
2364 		}
2365 	}
2366 
2367 	fclose(file);
2368 	return err;
2369 }
2370 
2371 static int bpf_object__init_kconfig_map(struct bpf_object *obj)
2372 {
2373 	struct extern_desc *last_ext = NULL, *ext;
2374 	size_t map_sz;
2375 	int i, err;
2376 
2377 	for (i = 0; i < obj->nr_extern; i++) {
2378 		ext = &obj->externs[i];
2379 		if (ext->type == EXT_KCFG)
2380 			last_ext = ext;
2381 	}
2382 
2383 	if (!last_ext)
2384 		return 0;
2385 
2386 	map_sz = last_ext->kcfg.data_off + last_ext->kcfg.sz;
2387 	err = bpf_object__init_internal_map(obj, LIBBPF_MAP_KCONFIG,
2388 					    ".kconfig", obj->efile.symbols_shndx,
2389 					    NULL, map_sz);
2390 	if (err)
2391 		return err;
2392 
2393 	obj->kconfig_map_idx = obj->nr_maps - 1;
2394 
2395 	return 0;
2396 }
2397 
2398 const struct btf_type *
2399 skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id)
2400 {
2401 	const struct btf_type *t = btf__type_by_id(btf, id);
2402 
2403 	if (res_id)
2404 		*res_id = id;
2405 
2406 	while (btf_is_mod(t) || btf_is_typedef(t)) {
2407 		if (res_id)
2408 			*res_id = t->type;
2409 		t = btf__type_by_id(btf, t->type);
2410 	}
2411 
2412 	return t;
2413 }
2414 
2415 static const struct btf_type *
2416 resolve_func_ptr(const struct btf *btf, __u32 id, __u32 *res_id)
2417 {
2418 	const struct btf_type *t;
2419 
2420 	t = skip_mods_and_typedefs(btf, id, NULL);
2421 	if (!btf_is_ptr(t))
2422 		return NULL;
2423 
2424 	t = skip_mods_and_typedefs(btf, t->type, res_id);
2425 
2426 	return btf_is_func_proto(t) ? t : NULL;
2427 }
2428 
2429 static const char *__btf_kind_str(__u16 kind)
2430 {
2431 	switch (kind) {
2432 	case BTF_KIND_UNKN: return "void";
2433 	case BTF_KIND_INT: return "int";
2434 	case BTF_KIND_PTR: return "ptr";
2435 	case BTF_KIND_ARRAY: return "array";
2436 	case BTF_KIND_STRUCT: return "struct";
2437 	case BTF_KIND_UNION: return "union";
2438 	case BTF_KIND_ENUM: return "enum";
2439 	case BTF_KIND_FWD: return "fwd";
2440 	case BTF_KIND_TYPEDEF: return "typedef";
2441 	case BTF_KIND_VOLATILE: return "volatile";
2442 	case BTF_KIND_CONST: return "const";
2443 	case BTF_KIND_RESTRICT: return "restrict";
2444 	case BTF_KIND_FUNC: return "func";
2445 	case BTF_KIND_FUNC_PROTO: return "func_proto";
2446 	case BTF_KIND_VAR: return "var";
2447 	case BTF_KIND_DATASEC: return "datasec";
2448 	case BTF_KIND_FLOAT: return "float";
2449 	case BTF_KIND_DECL_TAG: return "decl_tag";
2450 	case BTF_KIND_TYPE_TAG: return "type_tag";
2451 	case BTF_KIND_ENUM64: return "enum64";
2452 	default: return "unknown";
2453 	}
2454 }
2455 
2456 const char *btf_kind_str(const struct btf_type *t)
2457 {
2458 	return __btf_kind_str(btf_kind(t));
2459 }
2460 
2461 /*
2462  * Fetch integer attribute of BTF map definition. Such attributes are
2463  * represented using a pointer to an array, in which dimensionality of array
2464  * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
2465  * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
2466  * type definition, while using only sizeof(void *) space in ELF data section.
2467  */
2468 static bool get_map_field_int(const char *map_name, const struct btf *btf,
2469 			      const struct btf_member *m, __u32 *res)
2470 {
2471 	const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
2472 	const char *name = btf__name_by_offset(btf, m->name_off);
2473 	const struct btf_array *arr_info;
2474 	const struct btf_type *arr_t;
2475 
2476 	if (!btf_is_ptr(t)) {
2477 		pr_warn("map '%s': attr '%s': expected PTR, got %s.\n",
2478 			map_name, name, btf_kind_str(t));
2479 		return false;
2480 	}
2481 
2482 	arr_t = btf__type_by_id(btf, t->type);
2483 	if (!arr_t) {
2484 		pr_warn("map '%s': attr '%s': type [%u] not found.\n",
2485 			map_name, name, t->type);
2486 		return false;
2487 	}
2488 	if (!btf_is_array(arr_t)) {
2489 		pr_warn("map '%s': attr '%s': expected ARRAY, got %s.\n",
2490 			map_name, name, btf_kind_str(arr_t));
2491 		return false;
2492 	}
2493 	arr_info = btf_array(arr_t);
2494 	*res = arr_info->nelems;
2495 	return true;
2496 }
2497 
2498 static bool get_map_field_long(const char *map_name, const struct btf *btf,
2499 			       const struct btf_member *m, __u64 *res)
2500 {
2501 	const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
2502 	const char *name = btf__name_by_offset(btf, m->name_off);
2503 
2504 	if (btf_is_ptr(t)) {
2505 		__u32 res32;
2506 		bool ret;
2507 
2508 		ret = get_map_field_int(map_name, btf, m, &res32);
2509 		if (ret)
2510 			*res = (__u64)res32;
2511 		return ret;
2512 	}
2513 
2514 	if (!btf_is_enum(t) && !btf_is_enum64(t)) {
2515 		pr_warn("map '%s': attr '%s': expected ENUM or ENUM64, got %s.\n",
2516 			map_name, name, btf_kind_str(t));
2517 		return false;
2518 	}
2519 
2520 	if (btf_vlen(t) != 1) {
2521 		pr_warn("map '%s': attr '%s': invalid __ulong\n",
2522 			map_name, name);
2523 		return false;
2524 	}
2525 
2526 	if (btf_is_enum(t)) {
2527 		const struct btf_enum *e = btf_enum(t);
2528 
2529 		*res = e->val;
2530 	} else {
2531 		const struct btf_enum64 *e = btf_enum64(t);
2532 
2533 		*res = btf_enum64_value(e);
2534 	}
2535 	return true;
2536 }
2537 
2538 static int pathname_concat(char *buf, size_t buf_sz, const char *path, const char *name)
2539 {
2540 	int len;
2541 
2542 	len = snprintf(buf, buf_sz, "%s/%s", path, name);
2543 	if (len < 0)
2544 		return -EINVAL;
2545 	if (len >= buf_sz)
2546 		return -ENAMETOOLONG;
2547 
2548 	return 0;
2549 }
2550 
2551 static int build_map_pin_path(struct bpf_map *map, const char *path)
2552 {
2553 	char buf[PATH_MAX];
2554 	int err;
2555 
2556 	if (!path)
2557 		path = BPF_FS_DEFAULT_PATH;
2558 
2559 	err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
2560 	if (err)
2561 		return err;
2562 
2563 	return bpf_map__set_pin_path(map, buf);
2564 }
2565 
2566 /* should match definition in bpf_helpers.h */
2567 enum libbpf_pin_type {
2568 	LIBBPF_PIN_NONE,
2569 	/* PIN_BY_NAME: pin maps by name (in /sys/fs/bpf by default) */
2570 	LIBBPF_PIN_BY_NAME,
2571 };
2572 
2573 int parse_btf_map_def(const char *map_name, struct btf *btf,
2574 		      const struct btf_type *def_t, bool strict,
2575 		      struct btf_map_def *map_def, struct btf_map_def *inner_def)
2576 {
2577 	const struct btf_type *t;
2578 	const struct btf_member *m;
2579 	bool is_inner = inner_def == NULL;
2580 	int vlen, i;
2581 
2582 	vlen = btf_vlen(def_t);
2583 	m = btf_members(def_t);
2584 	for (i = 0; i < vlen; i++, m++) {
2585 		const char *name = btf__name_by_offset(btf, m->name_off);
2586 
2587 		if (!name) {
2588 			pr_warn("map '%s': invalid field #%d.\n", map_name, i);
2589 			return -EINVAL;
2590 		}
2591 		if (strcmp(name, "type") == 0) {
2592 			if (!get_map_field_int(map_name, btf, m, &map_def->map_type))
2593 				return -EINVAL;
2594 			map_def->parts |= MAP_DEF_MAP_TYPE;
2595 		} else if (strcmp(name, "max_entries") == 0) {
2596 			if (!get_map_field_int(map_name, btf, m, &map_def->max_entries))
2597 				return -EINVAL;
2598 			map_def->parts |= MAP_DEF_MAX_ENTRIES;
2599 		} else if (strcmp(name, "map_flags") == 0) {
2600 			if (!get_map_field_int(map_name, btf, m, &map_def->map_flags))
2601 				return -EINVAL;
2602 			map_def->parts |= MAP_DEF_MAP_FLAGS;
2603 		} else if (strcmp(name, "numa_node") == 0) {
2604 			if (!get_map_field_int(map_name, btf, m, &map_def->numa_node))
2605 				return -EINVAL;
2606 			map_def->parts |= MAP_DEF_NUMA_NODE;
2607 		} else if (strcmp(name, "key_size") == 0) {
2608 			__u32 sz;
2609 
2610 			if (!get_map_field_int(map_name, btf, m, &sz))
2611 				return -EINVAL;
2612 			if (map_def->key_size && map_def->key_size != sz) {
2613 				pr_warn("map '%s': conflicting key size %u != %u.\n",
2614 					map_name, map_def->key_size, sz);
2615 				return -EINVAL;
2616 			}
2617 			map_def->key_size = sz;
2618 			map_def->parts |= MAP_DEF_KEY_SIZE;
2619 		} else if (strcmp(name, "key") == 0) {
2620 			__s64 sz;
2621 
2622 			t = btf__type_by_id(btf, m->type);
2623 			if (!t) {
2624 				pr_warn("map '%s': key type [%d] not found.\n",
2625 					map_name, m->type);
2626 				return -EINVAL;
2627 			}
2628 			if (!btf_is_ptr(t)) {
2629 				pr_warn("map '%s': key spec is not PTR: %s.\n",
2630 					map_name, btf_kind_str(t));
2631 				return -EINVAL;
2632 			}
2633 			sz = btf__resolve_size(btf, t->type);
2634 			if (sz < 0) {
2635 				pr_warn("map '%s': can't determine key size for type [%u]: %zd.\n",
2636 					map_name, t->type, (ssize_t)sz);
2637 				return sz;
2638 			}
2639 			if (map_def->key_size && map_def->key_size != sz) {
2640 				pr_warn("map '%s': conflicting key size %u != %zd.\n",
2641 					map_name, map_def->key_size, (ssize_t)sz);
2642 				return -EINVAL;
2643 			}
2644 			map_def->key_size = sz;
2645 			map_def->key_type_id = t->type;
2646 			map_def->parts |= MAP_DEF_KEY_SIZE | MAP_DEF_KEY_TYPE;
2647 		} else if (strcmp(name, "value_size") == 0) {
2648 			__u32 sz;
2649 
2650 			if (!get_map_field_int(map_name, btf, m, &sz))
2651 				return -EINVAL;
2652 			if (map_def->value_size && map_def->value_size != sz) {
2653 				pr_warn("map '%s': conflicting value size %u != %u.\n",
2654 					map_name, map_def->value_size, sz);
2655 				return -EINVAL;
2656 			}
2657 			map_def->value_size = sz;
2658 			map_def->parts |= MAP_DEF_VALUE_SIZE;
2659 		} else if (strcmp(name, "value") == 0) {
2660 			__s64 sz;
2661 
2662 			t = btf__type_by_id(btf, m->type);
2663 			if (!t) {
2664 				pr_warn("map '%s': value type [%d] not found.\n",
2665 					map_name, m->type);
2666 				return -EINVAL;
2667 			}
2668 			if (!btf_is_ptr(t)) {
2669 				pr_warn("map '%s': value spec is not PTR: %s.\n",
2670 					map_name, btf_kind_str(t));
2671 				return -EINVAL;
2672 			}
2673 			sz = btf__resolve_size(btf, t->type);
2674 			if (sz < 0) {
2675 				pr_warn("map '%s': can't determine value size for type [%u]: %zd.\n",
2676 					map_name, t->type, (ssize_t)sz);
2677 				return sz;
2678 			}
2679 			if (map_def->value_size && map_def->value_size != sz) {
2680 				pr_warn("map '%s': conflicting value size %u != %zd.\n",
2681 					map_name, map_def->value_size, (ssize_t)sz);
2682 				return -EINVAL;
2683 			}
2684 			map_def->value_size = sz;
2685 			map_def->value_type_id = t->type;
2686 			map_def->parts |= MAP_DEF_VALUE_SIZE | MAP_DEF_VALUE_TYPE;
2687 		}
2688 		else if (strcmp(name, "values") == 0) {
2689 			bool is_map_in_map = bpf_map_type__is_map_in_map(map_def->map_type);
2690 			bool is_prog_array = map_def->map_type == BPF_MAP_TYPE_PROG_ARRAY;
2691 			const char *desc = is_map_in_map ? "map-in-map inner" : "prog-array value";
2692 			char inner_map_name[128];
2693 			int err;
2694 
2695 			if (is_inner) {
2696 				pr_warn("map '%s': multi-level inner maps not supported.\n",
2697 					map_name);
2698 				return -ENOTSUP;
2699 			}
2700 			if (i != vlen - 1) {
2701 				pr_warn("map '%s': '%s' member should be last.\n",
2702 					map_name, name);
2703 				return -EINVAL;
2704 			}
2705 			if (!is_map_in_map && !is_prog_array) {
2706 				pr_warn("map '%s': should be map-in-map or prog-array.\n",
2707 					map_name);
2708 				return -ENOTSUP;
2709 			}
2710 			if (map_def->value_size && map_def->value_size != 4) {
2711 				pr_warn("map '%s': conflicting value size %u != 4.\n",
2712 					map_name, map_def->value_size);
2713 				return -EINVAL;
2714 			}
2715 			map_def->value_size = 4;
2716 			t = btf__type_by_id(btf, m->type);
2717 			if (!t) {
2718 				pr_warn("map '%s': %s type [%d] not found.\n",
2719 					map_name, desc, m->type);
2720 				return -EINVAL;
2721 			}
2722 			if (!btf_is_array(t) || btf_array(t)->nelems) {
2723 				pr_warn("map '%s': %s spec is not a zero-sized array.\n",
2724 					map_name, desc);
2725 				return -EINVAL;
2726 			}
2727 			t = skip_mods_and_typedefs(btf, btf_array(t)->type, NULL);
2728 			if (!btf_is_ptr(t)) {
2729 				pr_warn("map '%s': %s def is of unexpected kind %s.\n",
2730 					map_name, desc, btf_kind_str(t));
2731 				return -EINVAL;
2732 			}
2733 			t = skip_mods_and_typedefs(btf, t->type, NULL);
2734 			if (is_prog_array) {
2735 				if (!btf_is_func_proto(t)) {
2736 					pr_warn("map '%s': prog-array value def is of unexpected kind %s.\n",
2737 						map_name, btf_kind_str(t));
2738 					return -EINVAL;
2739 				}
2740 				continue;
2741 			}
2742 			if (!btf_is_struct(t)) {
2743 				pr_warn("map '%s': map-in-map inner def is of unexpected kind %s.\n",
2744 					map_name, btf_kind_str(t));
2745 				return -EINVAL;
2746 			}
2747 
2748 			snprintf(inner_map_name, sizeof(inner_map_name), "%s.inner", map_name);
2749 			err = parse_btf_map_def(inner_map_name, btf, t, strict, inner_def, NULL);
2750 			if (err)
2751 				return err;
2752 
2753 			map_def->parts |= MAP_DEF_INNER_MAP;
2754 		} else if (strcmp(name, "pinning") == 0) {
2755 			__u32 val;
2756 
2757 			if (is_inner) {
2758 				pr_warn("map '%s': inner def can't be pinned.\n", map_name);
2759 				return -EINVAL;
2760 			}
2761 			if (!get_map_field_int(map_name, btf, m, &val))
2762 				return -EINVAL;
2763 			if (val != LIBBPF_PIN_NONE && val != LIBBPF_PIN_BY_NAME) {
2764 				pr_warn("map '%s': invalid pinning value %u.\n",
2765 					map_name, val);
2766 				return -EINVAL;
2767 			}
2768 			map_def->pinning = val;
2769 			map_def->parts |= MAP_DEF_PINNING;
2770 		} else if (strcmp(name, "map_extra") == 0) {
2771 			__u64 map_extra;
2772 
2773 			if (!get_map_field_long(map_name, btf, m, &map_extra))
2774 				return -EINVAL;
2775 			map_def->map_extra = map_extra;
2776 			map_def->parts |= MAP_DEF_MAP_EXTRA;
2777 		} else {
2778 			if (strict) {
2779 				pr_warn("map '%s': unknown field '%s'.\n", map_name, name);
2780 				return -ENOTSUP;
2781 			}
2782 			pr_debug("map '%s': ignoring unknown field '%s'.\n", map_name, name);
2783 		}
2784 	}
2785 
2786 	if (map_def->map_type == BPF_MAP_TYPE_UNSPEC) {
2787 		pr_warn("map '%s': map type isn't specified.\n", map_name);
2788 		return -EINVAL;
2789 	}
2790 
2791 	return 0;
2792 }
2793 
2794 static size_t adjust_ringbuf_sz(size_t sz)
2795 {
2796 	__u32 page_sz = sysconf(_SC_PAGE_SIZE);
2797 	__u32 mul;
2798 
2799 	/* if user forgot to set any size, make sure they see error */
2800 	if (sz == 0)
2801 		return 0;
2802 	/* Kernel expects BPF_MAP_TYPE_RINGBUF's max_entries to be
2803 	 * a power-of-2 multiple of kernel's page size. If user diligently
2804 	 * satisified these conditions, pass the size through.
2805 	 */
2806 	if ((sz % page_sz) == 0 && is_pow_of_2(sz / page_sz))
2807 		return sz;
2808 
2809 	/* Otherwise find closest (page_sz * power_of_2) product bigger than
2810 	 * user-set size to satisfy both user size request and kernel
2811 	 * requirements and substitute correct max_entries for map creation.
2812 	 */
2813 	for (mul = 1; mul <= UINT_MAX / page_sz; mul <<= 1) {
2814 		if (mul * page_sz > sz)
2815 			return mul * page_sz;
2816 	}
2817 
2818 	/* if it's impossible to satisfy the conditions (i.e., user size is
2819 	 * very close to UINT_MAX but is not a power-of-2 multiple of
2820 	 * page_size) then just return original size and let kernel reject it
2821 	 */
2822 	return sz;
2823 }
2824 
2825 static bool map_is_ringbuf(const struct bpf_map *map)
2826 {
2827 	return map->def.type == BPF_MAP_TYPE_RINGBUF ||
2828 	       map->def.type == BPF_MAP_TYPE_USER_RINGBUF;
2829 }
2830 
2831 static void fill_map_from_def(struct bpf_map *map, const struct btf_map_def *def)
2832 {
2833 	map->def.type = def->map_type;
2834 	map->def.key_size = def->key_size;
2835 	map->def.value_size = def->value_size;
2836 	map->def.max_entries = def->max_entries;
2837 	map->def.map_flags = def->map_flags;
2838 	map->map_extra = def->map_extra;
2839 
2840 	map->numa_node = def->numa_node;
2841 	map->btf_key_type_id = def->key_type_id;
2842 	map->btf_value_type_id = def->value_type_id;
2843 
2844 	/* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
2845 	if (map_is_ringbuf(map))
2846 		map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
2847 
2848 	if (def->parts & MAP_DEF_MAP_TYPE)
2849 		pr_debug("map '%s': found type = %u.\n", map->name, def->map_type);
2850 
2851 	if (def->parts & MAP_DEF_KEY_TYPE)
2852 		pr_debug("map '%s': found key [%u], sz = %u.\n",
2853 			 map->name, def->key_type_id, def->key_size);
2854 	else if (def->parts & MAP_DEF_KEY_SIZE)
2855 		pr_debug("map '%s': found key_size = %u.\n", map->name, def->key_size);
2856 
2857 	if (def->parts & MAP_DEF_VALUE_TYPE)
2858 		pr_debug("map '%s': found value [%u], sz = %u.\n",
2859 			 map->name, def->value_type_id, def->value_size);
2860 	else if (def->parts & MAP_DEF_VALUE_SIZE)
2861 		pr_debug("map '%s': found value_size = %u.\n", map->name, def->value_size);
2862 
2863 	if (def->parts & MAP_DEF_MAX_ENTRIES)
2864 		pr_debug("map '%s': found max_entries = %u.\n", map->name, def->max_entries);
2865 	if (def->parts & MAP_DEF_MAP_FLAGS)
2866 		pr_debug("map '%s': found map_flags = 0x%x.\n", map->name, def->map_flags);
2867 	if (def->parts & MAP_DEF_MAP_EXTRA)
2868 		pr_debug("map '%s': found map_extra = 0x%llx.\n", map->name,
2869 			 (unsigned long long)def->map_extra);
2870 	if (def->parts & MAP_DEF_PINNING)
2871 		pr_debug("map '%s': found pinning = %u.\n", map->name, def->pinning);
2872 	if (def->parts & MAP_DEF_NUMA_NODE)
2873 		pr_debug("map '%s': found numa_node = %u.\n", map->name, def->numa_node);
2874 
2875 	if (def->parts & MAP_DEF_INNER_MAP)
2876 		pr_debug("map '%s': found inner map definition.\n", map->name);
2877 }
2878 
2879 static const char *btf_var_linkage_str(__u32 linkage)
2880 {
2881 	switch (linkage) {
2882 	case BTF_VAR_STATIC: return "static";
2883 	case BTF_VAR_GLOBAL_ALLOCATED: return "global";
2884 	case BTF_VAR_GLOBAL_EXTERN: return "extern";
2885 	default: return "unknown";
2886 	}
2887 }
2888 
2889 static int bpf_object__init_user_btf_map(struct bpf_object *obj,
2890 					 const struct btf_type *sec,
2891 					 int var_idx, int sec_idx,
2892 					 const Elf_Data *data, bool strict,
2893 					 const char *pin_root_path)
2894 {
2895 	struct btf_map_def map_def = {}, inner_def = {};
2896 	const struct btf_type *var, *def;
2897 	const struct btf_var_secinfo *vi;
2898 	const struct btf_var *var_extra;
2899 	const char *map_name;
2900 	struct bpf_map *map;
2901 	int err;
2902 
2903 	vi = btf_var_secinfos(sec) + var_idx;
2904 	var = btf__type_by_id(obj->btf, vi->type);
2905 	var_extra = btf_var(var);
2906 	map_name = btf__name_by_offset(obj->btf, var->name_off);
2907 
2908 	if (str_is_empty(map_name)) {
2909 		pr_warn("map #%d: empty name.\n", var_idx);
2910 		return -EINVAL;
2911 	}
2912 	if ((__u64)vi->offset + vi->size > data->d_size) {
2913 		pr_warn("map '%s' BTF data is corrupted.\n", map_name);
2914 		return -EINVAL;
2915 	}
2916 	if (!btf_is_var(var)) {
2917 		pr_warn("map '%s': unexpected var kind %s.\n",
2918 			map_name, btf_kind_str(var));
2919 		return -EINVAL;
2920 	}
2921 	if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED) {
2922 		pr_warn("map '%s': unsupported map linkage %s.\n",
2923 			map_name, btf_var_linkage_str(var_extra->linkage));
2924 		return -EOPNOTSUPP;
2925 	}
2926 
2927 	def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
2928 	if (!btf_is_struct(def)) {
2929 		pr_warn("map '%s': unexpected def kind %s.\n",
2930 			map_name, btf_kind_str(var));
2931 		return -EINVAL;
2932 	}
2933 	if (def->size > vi->size) {
2934 		pr_warn("map '%s': invalid def size.\n", map_name);
2935 		return -EINVAL;
2936 	}
2937 
2938 	map = bpf_object__add_map(obj);
2939 	if (IS_ERR(map))
2940 		return PTR_ERR(map);
2941 	map->name = strdup(map_name);
2942 	if (!map->name) {
2943 		pr_warn("map '%s': failed to alloc map name.\n", map_name);
2944 		return -ENOMEM;
2945 	}
2946 	map->libbpf_type = LIBBPF_MAP_UNSPEC;
2947 	map->def.type = BPF_MAP_TYPE_UNSPEC;
2948 	map->sec_idx = sec_idx;
2949 	map->sec_offset = vi->offset;
2950 	map->btf_var_idx = var_idx;
2951 	pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
2952 		 map_name, map->sec_idx, map->sec_offset);
2953 
2954 	err = parse_btf_map_def(map->name, obj->btf, def, strict, &map_def, &inner_def);
2955 	if (err)
2956 		return err;
2957 
2958 	fill_map_from_def(map, &map_def);
2959 
2960 	if (map_def.pinning == LIBBPF_PIN_BY_NAME) {
2961 		err = build_map_pin_path(map, pin_root_path);
2962 		if (err) {
2963 			pr_warn("map '%s': couldn't build pin path.\n", map->name);
2964 			return err;
2965 		}
2966 	}
2967 
2968 	if (map_def.parts & MAP_DEF_INNER_MAP) {
2969 		map->inner_map = calloc(1, sizeof(*map->inner_map));
2970 		if (!map->inner_map)
2971 			return -ENOMEM;
2972 		map->inner_map->fd = create_placeholder_fd();
2973 		if (map->inner_map->fd < 0)
2974 			return map->inner_map->fd;
2975 		map->inner_map->sec_idx = sec_idx;
2976 		map->inner_map->name = malloc(strlen(map_name) + sizeof(".inner") + 1);
2977 		if (!map->inner_map->name)
2978 			return -ENOMEM;
2979 		sprintf(map->inner_map->name, "%s.inner", map_name);
2980 
2981 		fill_map_from_def(map->inner_map, &inner_def);
2982 	}
2983 
2984 	err = map_fill_btf_type_info(obj, map);
2985 	if (err)
2986 		return err;
2987 
2988 	return 0;
2989 }
2990 
2991 static int init_arena_map_data(struct bpf_object *obj, struct bpf_map *map,
2992 			       const char *sec_name, int sec_idx,
2993 			       void *data, size_t data_sz)
2994 {
2995 	const long page_sz = sysconf(_SC_PAGE_SIZE);
2996 	const size_t data_alloc_sz = roundup(data_sz, page_sz);
2997 	size_t mmap_sz;
2998 
2999 	mmap_sz = bpf_map_mmap_sz(map);
3000 	if (data_alloc_sz > mmap_sz) {
3001 		pr_warn("elf: sec '%s': declared ARENA map size (%zu) is too small to hold global __arena variables of size %zu\n",
3002 			sec_name, mmap_sz, data_sz);
3003 		return -E2BIG;
3004 	}
3005 
3006 	obj->arena_data = malloc(data_sz);
3007 	if (!obj->arena_data)
3008 		return -ENOMEM;
3009 	memcpy(obj->arena_data, data, data_sz);
3010 	obj->arena_data_sz = data_sz;
3011 
3012 	/* make bpf_map__init_value() work for ARENA maps */
3013 	map->mmaped = obj->arena_data;
3014 
3015 	return 0;
3016 }
3017 
3018 static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict,
3019 					  const char *pin_root_path)
3020 {
3021 	const struct btf_type *sec = NULL;
3022 	int nr_types, i, vlen, err;
3023 	const struct btf_type *t;
3024 	const char *name;
3025 	Elf_Data *data;
3026 	Elf_Scn *scn;
3027 
3028 	if (obj->efile.btf_maps_shndx < 0)
3029 		return 0;
3030 
3031 	scn = elf_sec_by_idx(obj, obj->efile.btf_maps_shndx);
3032 	data = elf_sec_data(obj, scn);
3033 	if (!data) {
3034 		pr_warn("elf: failed to get %s map definitions for %s\n",
3035 			MAPS_ELF_SEC, obj->path);
3036 		return -EINVAL;
3037 	}
3038 
3039 	nr_types = btf__type_cnt(obj->btf);
3040 	for (i = 1; i < nr_types; i++) {
3041 		t = btf__type_by_id(obj->btf, i);
3042 		if (!btf_is_datasec(t))
3043 			continue;
3044 		name = btf__name_by_offset(obj->btf, t->name_off);
3045 		if (strcmp(name, MAPS_ELF_SEC) == 0) {
3046 			sec = t;
3047 			obj->efile.btf_maps_sec_btf_id = i;
3048 			break;
3049 		}
3050 	}
3051 
3052 	if (!sec) {
3053 		pr_warn("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
3054 		return -ENOENT;
3055 	}
3056 
3057 	vlen = btf_vlen(sec);
3058 	for (i = 0; i < vlen; i++) {
3059 		err = bpf_object__init_user_btf_map(obj, sec, i,
3060 						    obj->efile.btf_maps_shndx,
3061 						    data, strict,
3062 						    pin_root_path);
3063 		if (err)
3064 			return err;
3065 	}
3066 
3067 	for (i = 0; i < obj->nr_maps; i++) {
3068 		struct bpf_map *map = &obj->maps[i];
3069 
3070 		if (map->def.type != BPF_MAP_TYPE_ARENA)
3071 			continue;
3072 
3073 		if (obj->arena_map_idx >= 0) {
3074 			pr_warn("map '%s': only single ARENA map is supported (map '%s' is also ARENA)\n",
3075 				map->name, obj->maps[obj->arena_map_idx].name);
3076 			return -EINVAL;
3077 		}
3078 		obj->arena_map_idx = i;
3079 
3080 		if (obj->efile.arena_data) {
3081 			err = init_arena_map_data(obj, map, ARENA_SEC, obj->efile.arena_data_shndx,
3082 						  obj->efile.arena_data->d_buf,
3083 						  obj->efile.arena_data->d_size);
3084 			if (err)
3085 				return err;
3086 		}
3087 	}
3088 	if (obj->efile.arena_data && obj->arena_map_idx < 0) {
3089 		pr_warn("elf: sec '%s': to use global __arena variables the ARENA map should be explicitly declared in SEC(\".maps\")\n",
3090 			ARENA_SEC);
3091 		return -ENOENT;
3092 	}
3093 
3094 	return 0;
3095 }
3096 
3097 static int bpf_object__init_maps(struct bpf_object *obj,
3098 				 const struct bpf_object_open_opts *opts)
3099 {
3100 	const char *pin_root_path;
3101 	bool strict;
3102 	int err = 0;
3103 
3104 	strict = !OPTS_GET(opts, relaxed_maps, false);
3105 	pin_root_path = OPTS_GET(opts, pin_root_path, NULL);
3106 
3107 	err = bpf_object__init_user_btf_maps(obj, strict, pin_root_path);
3108 	err = err ?: bpf_object__init_global_data_maps(obj);
3109 	err = err ?: bpf_object__init_kconfig_map(obj);
3110 	err = err ?: bpf_object_init_struct_ops(obj);
3111 
3112 	return err;
3113 }
3114 
3115 static bool section_have_execinstr(struct bpf_object *obj, int idx)
3116 {
3117 	Elf64_Shdr *sh;
3118 
3119 	sh = elf_sec_hdr(obj, elf_sec_by_idx(obj, idx));
3120 	if (!sh)
3121 		return false;
3122 
3123 	return sh->sh_flags & SHF_EXECINSTR;
3124 }
3125 
3126 static bool starts_with_qmark(const char *s)
3127 {
3128 	return s && s[0] == '?';
3129 }
3130 
3131 static bool btf_needs_sanitization(struct bpf_object *obj)
3132 {
3133 	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
3134 	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
3135 	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
3136 	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
3137 	bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
3138 	bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
3139 	bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
3140 	bool has_qmark_datasec = kernel_supports(obj, FEAT_BTF_QMARK_DATASEC);
3141 	bool has_layout = kernel_supports(obj, FEAT_BTF_LAYOUT);
3142 
3143 	return !has_func || !has_datasec || !has_func_global || !has_float ||
3144 	       !has_decl_tag || !has_type_tag || !has_enum64 || !has_qmark_datasec ||
3145 	       !has_layout;
3146 }
3147 
3148 struct btf *bpf_object__sanitize_btf(struct bpf_object *obj, struct btf *orig_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 	bool has_layout = kernel_supports(obj, FEAT_BTF_LAYOUT);
3159 	int enum64_placeholder_id = 0;
3160 	const struct btf_header *hdr;
3161 	struct btf *btf = NULL;
3162 	const void *raw_data;
3163 	struct btf_type *t;
3164 	int i, j, vlen;
3165 	__u32 sz;
3166 	int err;
3167 
3168 	/* clone BTF to sanitize a copy and leave the original intact */
3169 	raw_data = btf__raw_data(orig_btf, &sz);
3170 	if (!raw_data)
3171 		return ERR_PTR(-ENOMEM);
3172 	/* btf_header() gives us endian-safe header info */
3173 	hdr = btf_header(orig_btf);
3174 
3175 	if (!has_layout && hdr->hdr_len >= sizeof(struct btf_header) &&
3176 	    (hdr->layout_len != 0 || hdr->layout_off != 0)) {
3177 		const struct btf_header *old_hdr = raw_data;
3178 		struct btf_header *new_hdr;
3179 		void *new_raw_data;
3180 		__u32 new_str_off;
3181 
3182 		/*
3183 		 * Need to rewrite BTF to exclude layout information and
3184 		 * move string section to immediately after types.
3185 		 */
3186 		new_raw_data = malloc(sz);
3187 		if (!new_raw_data)
3188 			return ERR_PTR(-ENOMEM);
3189 
3190 		memcpy(new_raw_data, raw_data, sz);
3191 		new_hdr = new_raw_data;
3192 		new_hdr->layout_off = 0;
3193 		new_hdr->layout_len = 0;
3194 		new_str_off = hdr->type_off + hdr->type_len;
3195 		/* Handle swapped endian case */
3196 		if (old_hdr->magic != hdr->magic)
3197 			new_hdr->str_off = bswap_32(new_str_off);
3198 		else
3199 			new_hdr->str_off = new_str_off;
3200 
3201 		memmove(new_raw_data + hdr->hdr_len + new_str_off,
3202 			new_raw_data + hdr->hdr_len + hdr->str_off,
3203 			hdr->str_len);
3204 		sz = hdr->hdr_len + hdr->type_off + hdr->type_len + hdr->str_len;
3205 		btf = btf__new(new_raw_data, sz);
3206 		free(new_raw_data);
3207 	} else {
3208 		btf = btf__new(raw_data, sz);
3209 	}
3210 	err = libbpf_get_error(btf);
3211 	if (err)
3212 		return ERR_PTR(err);
3213 
3214 	/* enforce 8-byte pointers for BPF-targeted BTFs */
3215 	btf__set_pointer_size(btf, 8);
3216 
3217 	for (i = 1; i < btf__type_cnt(btf); i++) {
3218 		t = (struct btf_type *)btf__type_by_id(btf, i);
3219 
3220 		if ((!has_datasec && btf_is_var(t)) || (!has_decl_tag && btf_is_decl_tag(t))) {
3221 			/* replace VAR/DECL_TAG with INT */
3222 			t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
3223 			/*
3224 			 * using size = 1 is the safest choice, 4 will be too
3225 			 * big and cause kernel BTF validation failure if
3226 			 * original variable took less than 4 bytes
3227 			 */
3228 			t->size = 1;
3229 			*(int *)(t + 1) = BTF_INT_ENC(0, 0, 8);
3230 		} else if (!has_datasec && btf_is_datasec(t)) {
3231 			/* replace DATASEC with STRUCT */
3232 			const struct btf_var_secinfo *v = btf_var_secinfos(t);
3233 			struct btf_member *m = btf_members(t);
3234 			struct btf_type *vt;
3235 			char *name;
3236 
3237 			name = (char *)btf__name_by_offset(btf, t->name_off);
3238 			while (*name) {
3239 				if (*name == '.' || *name == '?')
3240 					*name = '_';
3241 				name++;
3242 			}
3243 
3244 			vlen = btf_vlen(t);
3245 			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
3246 			for (j = 0; j < vlen; j++, v++, m++) {
3247 				/* order of field assignments is important */
3248 				m->offset = v->offset * 8;
3249 				m->type = v->type;
3250 				/* preserve variable name as member name */
3251 				vt = (void *)btf__type_by_id(btf, v->type);
3252 				m->name_off = vt->name_off;
3253 			}
3254 		} else if (!has_qmark_datasec && btf_is_datasec(t) &&
3255 			   starts_with_qmark(btf__name_by_offset(btf, t->name_off))) {
3256 			/* replace '?' prefix with '_' for DATASEC names */
3257 			char *name;
3258 
3259 			name = (char *)btf__name_by_offset(btf, t->name_off);
3260 			if (name[0] == '?')
3261 				name[0] = '_';
3262 		} else if (!has_func && btf_is_func_proto(t)) {
3263 			/* replace FUNC_PROTO with ENUM */
3264 			vlen = btf_vlen(t);
3265 			t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
3266 			t->size = sizeof(__u32); /* kernel enforced */
3267 		} else if (!has_func && btf_is_func(t)) {
3268 			/* replace FUNC with TYPEDEF */
3269 			t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
3270 		} else if (!has_func_global && btf_is_func(t)) {
3271 			/* replace BTF_FUNC_GLOBAL with BTF_FUNC_STATIC */
3272 			t->info = BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0);
3273 		} else if (!has_float && btf_is_float(t)) {
3274 			/* replace FLOAT with an equally-sized empty STRUCT;
3275 			 * since C compilers do not accept e.g. "float" as a
3276 			 * valid struct name, make it anonymous
3277 			 */
3278 			t->name_off = 0;
3279 			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, 0);
3280 		} else if (!has_type_tag && btf_is_type_tag(t)) {
3281 			/* replace TYPE_TAG with a CONST */
3282 			t->name_off = 0;
3283 			t->info = BTF_INFO_ENC(BTF_KIND_CONST, 0, 0);
3284 		} else if (!has_enum64 && btf_is_enum(t)) {
3285 			/* clear the kflag */
3286 			t->info = btf_type_info(btf_kind(t), btf_vlen(t), false);
3287 		} else if (!has_enum64 && btf_is_enum64(t)) {
3288 			/* replace ENUM64 with a union */
3289 			struct btf_member *m;
3290 
3291 			if (enum64_placeholder_id == 0) {
3292 				enum64_placeholder_id = btf__add_int(btf, "enum64_placeholder", 1, 0);
3293 				if (enum64_placeholder_id < 0) {
3294 					btf__free(btf);
3295 					return ERR_PTR(enum64_placeholder_id);
3296 				}
3297 				t = (struct btf_type *)btf__type_by_id(btf, i);
3298 			}
3299 
3300 			m = btf_members(t);
3301 			vlen = btf_vlen(t);
3302 			t->info = BTF_INFO_ENC(BTF_KIND_UNION, 0, vlen);
3303 			for (j = 0; j < vlen; j++, m++) {
3304 				m->type = enum64_placeholder_id;
3305 				m->offset = 0;
3306 			}
3307 		}
3308 	}
3309 
3310 	return btf;
3311 }
3312 
3313 static bool libbpf_needs_btf(const struct bpf_object *obj)
3314 {
3315 	return obj->efile.btf_maps_shndx >= 0 ||
3316 	       obj->efile.has_st_ops ||
3317 	       obj->nr_extern > 0;
3318 }
3319 
3320 static bool kernel_needs_btf(const struct bpf_object *obj)
3321 {
3322 	return obj->efile.has_st_ops;
3323 }
3324 
3325 static int bpf_object__init_btf(struct bpf_object *obj,
3326 				Elf_Data *btf_data,
3327 				Elf_Data *btf_ext_data)
3328 {
3329 	int err = -ENOENT;
3330 
3331 	if (btf_data) {
3332 		obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
3333 		err = libbpf_get_error(obj->btf);
3334 		if (err) {
3335 			obj->btf = NULL;
3336 			pr_warn("Error loading ELF section %s: %s.\n", BTF_ELF_SEC, errstr(err));
3337 			goto out;
3338 		}
3339 		/* enforce 8-byte pointers for BPF-targeted BTFs */
3340 		btf__set_pointer_size(obj->btf, 8);
3341 	}
3342 	if (btf_ext_data) {
3343 		struct btf_ext_info *ext_segs[3];
3344 		int seg_num, sec_num;
3345 
3346 		if (!obj->btf) {
3347 			pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
3348 				 BTF_EXT_ELF_SEC, BTF_ELF_SEC);
3349 			goto out;
3350 		}
3351 		obj->btf_ext = btf_ext__new(btf_ext_data->d_buf, btf_ext_data->d_size);
3352 		err = libbpf_get_error(obj->btf_ext);
3353 		if (err) {
3354 			pr_warn("Error loading ELF section %s: %s. Ignored and continue.\n",
3355 				BTF_EXT_ELF_SEC, errstr(err));
3356 			obj->btf_ext = NULL;
3357 			goto out;
3358 		}
3359 
3360 		/* setup .BTF.ext to ELF section mapping */
3361 		ext_segs[0] = &obj->btf_ext->func_info;
3362 		ext_segs[1] = &obj->btf_ext->line_info;
3363 		ext_segs[2] = &obj->btf_ext->core_relo_info;
3364 		for (seg_num = 0; seg_num < ARRAY_SIZE(ext_segs); seg_num++) {
3365 			struct btf_ext_info *seg = ext_segs[seg_num];
3366 			const struct btf_ext_info_sec *sec;
3367 			const char *sec_name;
3368 			Elf_Scn *scn;
3369 
3370 			if (seg->sec_cnt == 0)
3371 				continue;
3372 
3373 			seg->sec_idxs = calloc(seg->sec_cnt, sizeof(*seg->sec_idxs));
3374 			if (!seg->sec_idxs) {
3375 				err = -ENOMEM;
3376 				goto out;
3377 			}
3378 
3379 			sec_num = 0;
3380 			for_each_btf_ext_sec(seg, sec) {
3381 				/* preventively increment index to avoid doing
3382 				 * this before every continue below
3383 				 */
3384 				sec_num++;
3385 
3386 				sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
3387 				if (str_is_empty(sec_name))
3388 					continue;
3389 				scn = elf_sec_by_name(obj, sec_name);
3390 				if (!scn)
3391 					continue;
3392 
3393 				seg->sec_idxs[sec_num - 1] = elf_ndxscn(scn);
3394 			}
3395 		}
3396 	}
3397 out:
3398 	if (err && libbpf_needs_btf(obj)) {
3399 		pr_warn("BTF is required, but is missing or corrupted.\n");
3400 		return err;
3401 	}
3402 	return 0;
3403 }
3404 
3405 static int compare_vsi_off(const void *_a, const void *_b)
3406 {
3407 	const struct btf_var_secinfo *a = _a;
3408 	const struct btf_var_secinfo *b = _b;
3409 
3410 	return a->offset - b->offset;
3411 }
3412 
3413 static int btf_fixup_datasec(struct bpf_object *obj, struct btf *btf,
3414 			     struct btf_type *t)
3415 {
3416 	__u32 size = 0, i, vars = btf_vlen(t);
3417 	const char *sec_name = btf__name_by_offset(btf, t->name_off);
3418 	struct btf_var_secinfo *vsi;
3419 	bool fixup_offsets = false;
3420 	int err;
3421 
3422 	if (!sec_name) {
3423 		pr_debug("No name found in string section for DATASEC kind.\n");
3424 		return -ENOENT;
3425 	}
3426 
3427 	/* Extern-backing datasecs (.ksyms, .kconfig) have their size and
3428 	 * variable offsets set at the previous step. Further, not every
3429 	 * extern BTF VAR has corresponding ELF symbol preserved, so we skip
3430 	 * all fixups altogether for such sections and go straight to sorting
3431 	 * VARs within their DATASEC.
3432 	 */
3433 	if (strcmp(sec_name, KCONFIG_SEC) == 0 || strcmp(sec_name, KSYMS_SEC) == 0)
3434 		goto sort_vars;
3435 
3436 	/* Clang leaves DATASEC size and VAR offsets as zeroes, so we need to
3437 	 * fix this up. But BPF static linker already fixes this up and fills
3438 	 * all the sizes and offsets during static linking. So this step has
3439 	 * to be optional. But the STV_HIDDEN handling is non-optional for any
3440 	 * non-extern DATASEC, so the variable fixup loop below handles both
3441 	 * functions at the same time, paying the cost of BTF VAR <-> ELF
3442 	 * symbol matching just once.
3443 	 */
3444 	if (t->size == 0) {
3445 		err = find_elf_sec_sz(obj, sec_name, &size);
3446 		if (err || !size) {
3447 			pr_debug("sec '%s': failed to determine size from ELF: size %u, err %s\n",
3448 				 sec_name, size, errstr(err));
3449 			return -ENOENT;
3450 		}
3451 
3452 		t->size = size;
3453 		fixup_offsets = true;
3454 	}
3455 
3456 	for (i = 0, vsi = btf_var_secinfos(t); i < vars; i++, vsi++) {
3457 		const struct btf_type *t_var;
3458 		struct btf_var *var;
3459 		const char *var_name;
3460 		Elf64_Sym *sym;
3461 
3462 		t_var = btf__type_by_id(btf, vsi->type);
3463 		if (!t_var || !btf_is_var(t_var)) {
3464 			pr_debug("sec '%s': unexpected non-VAR type found\n", sec_name);
3465 			return -EINVAL;
3466 		}
3467 
3468 		var = btf_var(t_var);
3469 		if (var->linkage == BTF_VAR_STATIC || var->linkage == BTF_VAR_GLOBAL_EXTERN)
3470 			continue;
3471 
3472 		var_name = btf__name_by_offset(btf, t_var->name_off);
3473 		if (!var_name) {
3474 			pr_debug("sec '%s': failed to find name of DATASEC's member #%d\n",
3475 				 sec_name, i);
3476 			return -ENOENT;
3477 		}
3478 
3479 		sym = find_elf_var_sym(obj, var_name);
3480 		if (IS_ERR(sym)) {
3481 			pr_debug("sec '%s': failed to find ELF symbol for VAR '%s'\n",
3482 				 sec_name, var_name);
3483 			return -ENOENT;
3484 		}
3485 
3486 		if (fixup_offsets)
3487 			vsi->offset = sym->st_value;
3488 
3489 		/* if variable is a global/weak symbol, but has restricted
3490 		 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF VAR
3491 		 * as static. This follows similar logic for functions (BPF
3492 		 * subprogs) and influences libbpf's further decisions about
3493 		 * whether to make global data BPF array maps as
3494 		 * BPF_F_MMAPABLE.
3495 		 */
3496 		if (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
3497 		    || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL)
3498 			var->linkage = BTF_VAR_STATIC;
3499 	}
3500 
3501 sort_vars:
3502 	qsort(btf_var_secinfos(t), vars, sizeof(*vsi), compare_vsi_off);
3503 	return 0;
3504 }
3505 
3506 static int bpf_object_fixup_btf(struct bpf_object *obj)
3507 {
3508 	int i, n, err = 0;
3509 
3510 	if (!obj->btf)
3511 		return 0;
3512 
3513 	n = btf__type_cnt(obj->btf);
3514 	for (i = 1; i < n; i++) {
3515 		struct btf_type *t = btf_type_by_id(obj->btf, i);
3516 
3517 		/* Loader needs to fix up some of the things compiler
3518 		 * couldn't get its hands on while emitting BTF. This
3519 		 * is section size and global variable offset. We use
3520 		 * the info from the ELF itself for this purpose.
3521 		 */
3522 		if (btf_is_datasec(t)) {
3523 			err = btf_fixup_datasec(obj, obj->btf, t);
3524 			if (err)
3525 				return err;
3526 		}
3527 	}
3528 
3529 	return 0;
3530 }
3531 
3532 static bool prog_needs_vmlinux_btf(struct bpf_program *prog)
3533 {
3534 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
3535 	    prog->type == BPF_PROG_TYPE_LSM)
3536 		return true;
3537 
3538 	/* BPF_PROG_TYPE_TRACING programs which do not attach to other programs
3539 	 * also need vmlinux BTF
3540 	 */
3541 	if (prog->type == BPF_PROG_TYPE_TRACING && !prog->attach_prog_fd)
3542 		return true;
3543 
3544 	return false;
3545 }
3546 
3547 static bool map_needs_vmlinux_btf(struct bpf_map *map)
3548 {
3549 	return bpf_map__is_struct_ops(map);
3550 }
3551 
3552 static bool obj_needs_vmlinux_btf(const struct bpf_object *obj)
3553 {
3554 	struct bpf_program *prog;
3555 	struct bpf_map *map;
3556 	int i;
3557 
3558 	/* CO-RE relocations need kernel BTF, only when btf_custom_path
3559 	 * is not specified
3560 	 */
3561 	if (obj->btf_ext && obj->btf_ext->core_relo_info.len && !obj->btf_custom_path)
3562 		return true;
3563 
3564 	/* Support for typed ksyms needs kernel BTF */
3565 	for (i = 0; i < obj->nr_extern; i++) {
3566 		const struct extern_desc *ext;
3567 
3568 		ext = &obj->externs[i];
3569 		if (ext->type == EXT_KSYM && ext->ksym.type_id)
3570 			return true;
3571 	}
3572 
3573 	bpf_object__for_each_program(prog, obj) {
3574 		if (!prog->autoload)
3575 			continue;
3576 		if (prog_needs_vmlinux_btf(prog))
3577 			return true;
3578 	}
3579 
3580 	bpf_object__for_each_map(map, obj) {
3581 		if (map_needs_vmlinux_btf(map))
3582 			return true;
3583 	}
3584 
3585 	return false;
3586 }
3587 
3588 static int bpf_object__load_vmlinux_btf(struct bpf_object *obj, bool force)
3589 {
3590 	int err;
3591 
3592 	/* btf_vmlinux could be loaded earlier */
3593 	if (obj->btf_vmlinux || obj->gen_loader)
3594 		return 0;
3595 
3596 	if (!force && !obj_needs_vmlinux_btf(obj))
3597 		return 0;
3598 
3599 	obj->btf_vmlinux = btf__load_vmlinux_btf();
3600 	err = libbpf_get_error(obj->btf_vmlinux);
3601 	if (err) {
3602 		pr_warn("Error loading vmlinux BTF: %s\n", errstr(err));
3603 		obj->btf_vmlinux = NULL;
3604 		return err;
3605 	}
3606 	return 0;
3607 }
3608 
3609 static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
3610 {
3611 	struct btf *kern_btf = obj->btf;
3612 	bool btf_mandatory, sanitize;
3613 	int i, err = 0;
3614 
3615 	if (!obj->btf)
3616 		return 0;
3617 
3618 	if (!kernel_supports(obj, FEAT_BTF)) {
3619 		if (kernel_needs_btf(obj)) {
3620 			err = -EOPNOTSUPP;
3621 			goto report;
3622 		}
3623 		pr_debug("Kernel doesn't support BTF, skipping uploading it.\n");
3624 		return 0;
3625 	}
3626 
3627 	/* Even though some subprogs are global/weak, user might prefer more
3628 	 * permissive BPF verification process that BPF verifier performs for
3629 	 * static functions, taking into account more context from the caller
3630 	 * functions. In such case, they need to mark such subprogs with
3631 	 * __attribute__((visibility("hidden"))) and libbpf will adjust
3632 	 * corresponding FUNC BTF type to be marked as static and trigger more
3633 	 * involved BPF verification process.
3634 	 */
3635 	for (i = 0; i < obj->nr_programs; i++) {
3636 		struct bpf_program *prog = &obj->programs[i];
3637 		struct btf_type *t;
3638 		const char *name;
3639 		int j, n;
3640 
3641 		if (!prog->mark_btf_static || !prog_is_subprog(obj, prog))
3642 			continue;
3643 
3644 		n = btf__type_cnt(obj->btf);
3645 		for (j = 1; j < n; j++) {
3646 			t = btf_type_by_id(obj->btf, j);
3647 			if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL)
3648 				continue;
3649 
3650 			name = btf__str_by_offset(obj->btf, t->name_off);
3651 			if (strcmp(name, prog->name) != 0)
3652 				continue;
3653 
3654 			t->info = btf_type_info(BTF_KIND_FUNC, BTF_FUNC_STATIC, 0);
3655 			break;
3656 		}
3657 	}
3658 
3659 	sanitize = btf_needs_sanitization(obj);
3660 	if (sanitize) {
3661 		kern_btf = bpf_object__sanitize_btf(obj, obj->btf);
3662 		if (IS_ERR(kern_btf))
3663 			return PTR_ERR(kern_btf);
3664 	}
3665 
3666 	if (obj->gen_loader) {
3667 		__u32 raw_size = 0;
3668 		const void *raw_data = btf__raw_data(kern_btf, &raw_size);
3669 
3670 		if (!raw_data)
3671 			return -ENOMEM;
3672 		bpf_gen__load_btf(obj->gen_loader, raw_data, raw_size);
3673 		/* Pretend to have valid FD to pass various fd >= 0 checks.
3674 		 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
3675 		 */
3676 		btf__set_fd(kern_btf, 0);
3677 	} else {
3678 		/* currently BPF_BTF_LOAD only supports log_level 1 */
3679 		err = btf_load_into_kernel(kern_btf, obj->log_buf, obj->log_size,
3680 					   obj->log_level ? 1 : 0, obj->token_fd);
3681 	}
3682 	if (sanitize) {
3683 		if (!err) {
3684 			/* move fd to libbpf's BTF */
3685 			btf__set_fd(obj->btf, btf__fd(kern_btf));
3686 			btf__set_fd(kern_btf, -1);
3687 		}
3688 		btf__free(kern_btf);
3689 	}
3690 report:
3691 	if (err) {
3692 		btf_mandatory = kernel_needs_btf(obj);
3693 		if (btf_mandatory) {
3694 			pr_warn("Error loading .BTF into kernel: %s. BTF is mandatory, can't proceed.\n",
3695 				errstr(err));
3696 		} else {
3697 			pr_info("Error loading .BTF into kernel: %s. BTF is optional, ignoring.\n",
3698 				errstr(err));
3699 			err = 0;
3700 		}
3701 	}
3702 	return err;
3703 }
3704 
3705 static const char *elf_sym_str(const struct bpf_object *obj, size_t off)
3706 {
3707 	const char *name;
3708 
3709 	name = elf_strptr(obj->efile.elf, obj->efile.strtabidx, off);
3710 	if (!name) {
3711 		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3712 			off, obj->path, elf_errmsg(-1));
3713 		return NULL;
3714 	}
3715 
3716 	return name;
3717 }
3718 
3719 static const char *elf_sec_str(const struct bpf_object *obj, size_t off)
3720 {
3721 	const char *name;
3722 
3723 	name = elf_strptr(obj->efile.elf, obj->efile.shstrndx, off);
3724 	if (!name) {
3725 		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3726 			off, obj->path, elf_errmsg(-1));
3727 		return NULL;
3728 	}
3729 
3730 	return name;
3731 }
3732 
3733 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx)
3734 {
3735 	Elf_Scn *scn;
3736 
3737 	scn = elf_getscn(obj->efile.elf, idx);
3738 	if (!scn) {
3739 		pr_warn("elf: failed to get section(%zu) from %s: %s\n",
3740 			idx, obj->path, elf_errmsg(-1));
3741 		return NULL;
3742 	}
3743 	return scn;
3744 }
3745 
3746 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name)
3747 {
3748 	Elf_Scn *scn = NULL;
3749 	Elf *elf = obj->efile.elf;
3750 	const char *sec_name;
3751 
3752 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3753 		sec_name = elf_sec_name(obj, scn);
3754 		if (!sec_name)
3755 			return NULL;
3756 
3757 		if (strcmp(sec_name, name) != 0)
3758 			continue;
3759 
3760 		return scn;
3761 	}
3762 	return NULL;
3763 }
3764 
3765 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn)
3766 {
3767 	Elf64_Shdr *shdr;
3768 
3769 	if (!scn)
3770 		return NULL;
3771 
3772 	shdr = elf64_getshdr(scn);
3773 	if (!shdr) {
3774 		pr_warn("elf: failed to get section(%zu) header from %s: %s\n",
3775 			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3776 		return NULL;
3777 	}
3778 
3779 	return shdr;
3780 }
3781 
3782 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn)
3783 {
3784 	const char *name;
3785 	Elf64_Shdr *sh;
3786 
3787 	if (!scn)
3788 		return NULL;
3789 
3790 	sh = elf_sec_hdr(obj, scn);
3791 	if (!sh)
3792 		return NULL;
3793 
3794 	name = elf_sec_str(obj, sh->sh_name);
3795 	if (!name) {
3796 		pr_warn("elf: failed to get section(%zu) name from %s: %s\n",
3797 			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3798 		return NULL;
3799 	}
3800 
3801 	return name;
3802 }
3803 
3804 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn)
3805 {
3806 	Elf_Data *data;
3807 
3808 	if (!scn)
3809 		return NULL;
3810 
3811 	data = elf_getdata(scn, 0);
3812 	if (!data) {
3813 		pr_warn("elf: failed to get section(%zu) %s data from %s: %s\n",
3814 			elf_ndxscn(scn), elf_sec_name(obj, scn) ?: "<?>",
3815 			obj->path, elf_errmsg(-1));
3816 		return NULL;
3817 	}
3818 
3819 	return data;
3820 }
3821 
3822 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx)
3823 {
3824 	if (idx >= obj->efile.symbols->d_size / sizeof(Elf64_Sym))
3825 		return NULL;
3826 
3827 	return (Elf64_Sym *)obj->efile.symbols->d_buf + idx;
3828 }
3829 
3830 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx)
3831 {
3832 	if (idx >= data->d_size / sizeof(Elf64_Rel))
3833 		return NULL;
3834 
3835 	return (Elf64_Rel *)data->d_buf + idx;
3836 }
3837 
3838 static bool is_sec_name_dwarf(const char *name)
3839 {
3840 	/* approximation, but the actual list is too long */
3841 	return str_has_pfx(name, ".debug_");
3842 }
3843 
3844 static bool ignore_elf_section(Elf64_Shdr *hdr, const char *name)
3845 {
3846 	/* no special handling of .strtab */
3847 	if (hdr->sh_type == SHT_STRTAB)
3848 		return true;
3849 
3850 	/* ignore .llvm_addrsig section as well */
3851 	if (hdr->sh_type == SHT_LLVM_ADDRSIG)
3852 		return true;
3853 
3854 	/* no subprograms will lead to an empty .text section, ignore it */
3855 	if (hdr->sh_type == SHT_PROGBITS && hdr->sh_size == 0 &&
3856 	    strcmp(name, ".text") == 0)
3857 		return true;
3858 
3859 	/* DWARF sections */
3860 	if (is_sec_name_dwarf(name))
3861 		return true;
3862 
3863 	if (str_has_pfx(name, ".rel")) {
3864 		name += sizeof(".rel") - 1;
3865 		/* DWARF section relocations */
3866 		if (is_sec_name_dwarf(name))
3867 			return true;
3868 
3869 		/* .BTF and .BTF.ext don't need relocations */
3870 		if (strcmp(name, BTF_ELF_SEC) == 0 ||
3871 		    strcmp(name, BTF_EXT_ELF_SEC) == 0)
3872 			return true;
3873 	}
3874 
3875 	return false;
3876 }
3877 
3878 static int cmp_progs(const void *_a, const void *_b)
3879 {
3880 	const struct bpf_program *a = _a;
3881 	const struct bpf_program *b = _b;
3882 
3883 	if (a->sec_idx != b->sec_idx)
3884 		return a->sec_idx < b->sec_idx ? -1 : 1;
3885 
3886 	/* sec_insn_off can't be the same within the section */
3887 	return a->sec_insn_off < b->sec_insn_off ? -1 : 1;
3888 }
3889 
3890 static int bpf_object__elf_collect(struct bpf_object *obj)
3891 {
3892 	struct elf_sec_desc *sec_desc;
3893 	Elf *elf = obj->efile.elf;
3894 	Elf_Data *btf_ext_data = NULL;
3895 	Elf_Data *btf_data = NULL;
3896 	int idx = 0, err = 0;
3897 	const char *name;
3898 	Elf_Data *data;
3899 	Elf_Scn *scn;
3900 	Elf64_Shdr *sh;
3901 
3902 	/* ELF section indices are 0-based, but sec #0 is special "invalid"
3903 	 * section. Since section count retrieved by elf_getshdrnum() does
3904 	 * include sec #0, it is already the necessary size of an array to keep
3905 	 * all the sections.
3906 	 */
3907 	if (elf_getshdrnum(obj->efile.elf, &obj->efile.sec_cnt)) {
3908 		pr_warn("elf: failed to get the number of sections for %s: %s\n",
3909 			obj->path, elf_errmsg(-1));
3910 		return -LIBBPF_ERRNO__FORMAT;
3911 	}
3912 	obj->efile.secs = calloc(obj->efile.sec_cnt, sizeof(*obj->efile.secs));
3913 	if (!obj->efile.secs)
3914 		return -ENOMEM;
3915 
3916 	/* a bunch of ELF parsing functionality depends on processing symbols,
3917 	 * so do the first pass and find the symbol table
3918 	 */
3919 	scn = NULL;
3920 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3921 		sh = elf_sec_hdr(obj, scn);
3922 		if (!sh)
3923 			return -LIBBPF_ERRNO__FORMAT;
3924 
3925 		if (sh->sh_type == SHT_SYMTAB) {
3926 			if (obj->efile.symbols) {
3927 				pr_warn("elf: multiple symbol tables in %s\n", obj->path);
3928 				return -LIBBPF_ERRNO__FORMAT;
3929 			}
3930 
3931 			data = elf_sec_data(obj, scn);
3932 			if (!data)
3933 				return -LIBBPF_ERRNO__FORMAT;
3934 
3935 			idx = elf_ndxscn(scn);
3936 
3937 			obj->efile.symbols = data;
3938 			obj->efile.symbols_shndx = idx;
3939 			obj->efile.strtabidx = sh->sh_link;
3940 		}
3941 	}
3942 
3943 	if (!obj->efile.symbols) {
3944 		pr_warn("elf: couldn't find symbol table in %s, stripped object file?\n",
3945 			obj->path);
3946 		return -ENOENT;
3947 	}
3948 
3949 	scn = NULL;
3950 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3951 		idx = elf_ndxscn(scn);
3952 		sec_desc = &obj->efile.secs[idx];
3953 
3954 		sh = elf_sec_hdr(obj, scn);
3955 		if (!sh)
3956 			return -LIBBPF_ERRNO__FORMAT;
3957 
3958 		name = elf_sec_str(obj, sh->sh_name);
3959 		if (!name)
3960 			return -LIBBPF_ERRNO__FORMAT;
3961 
3962 		if (ignore_elf_section(sh, name))
3963 			continue;
3964 
3965 		data = elf_sec_data(obj, scn);
3966 		if (!data)
3967 			return -LIBBPF_ERRNO__FORMAT;
3968 
3969 		pr_debug("elf: section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
3970 			 idx, name, (unsigned long)data->d_size,
3971 			 (int)sh->sh_link, (unsigned long)sh->sh_flags,
3972 			 (int)sh->sh_type);
3973 
3974 		if (strcmp(name, "license") == 0) {
3975 			err = bpf_object__init_license(obj, data->d_buf, data->d_size);
3976 			if (err)
3977 				return err;
3978 		} else if (strcmp(name, "version") == 0) {
3979 			err = bpf_object__init_kversion(obj, data->d_buf, data->d_size);
3980 			if (err)
3981 				return err;
3982 		} else if (strcmp(name, "maps") == 0) {
3983 			pr_warn("elf: legacy map definitions in 'maps' section are not supported by libbpf v1.0+\n");
3984 			return -ENOTSUP;
3985 		} else if (strcmp(name, MAPS_ELF_SEC) == 0) {
3986 			obj->efile.btf_maps_shndx = idx;
3987 		} else if (strcmp(name, BTF_ELF_SEC) == 0) {
3988 			if (sh->sh_type != SHT_PROGBITS)
3989 				return -LIBBPF_ERRNO__FORMAT;
3990 			btf_data = data;
3991 		} else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
3992 			if (sh->sh_type != SHT_PROGBITS)
3993 				return -LIBBPF_ERRNO__FORMAT;
3994 			btf_ext_data = data;
3995 		} else if (sh->sh_type == SHT_SYMTAB) {
3996 			/* already processed during the first pass above */
3997 		} else if (sh->sh_type == SHT_PROGBITS && data->d_size > 0) {
3998 			if (sh->sh_flags & SHF_EXECINSTR) {
3999 				if (strcmp(name, ".text") == 0)
4000 					obj->efile.text_shndx = idx;
4001 				err = bpf_object__add_programs(obj, data, name, idx);
4002 				if (err)
4003 					return err;
4004 			} else if (strcmp(name, DATA_SEC) == 0 ||
4005 				   str_has_pfx(name, DATA_SEC ".")) {
4006 				sec_desc->sec_type = SEC_DATA;
4007 				sec_desc->shdr = sh;
4008 				sec_desc->data = data;
4009 			} else if (strcmp(name, RODATA_SEC) == 0 ||
4010 				   str_has_pfx(name, RODATA_SEC ".")) {
4011 				sec_desc->sec_type = SEC_RODATA;
4012 				sec_desc->shdr = sh;
4013 				sec_desc->data = data;
4014 			} else if (strcmp(name, STRUCT_OPS_SEC) == 0 ||
4015 				   strcmp(name, STRUCT_OPS_LINK_SEC) == 0 ||
4016 				   strcmp(name, "?" STRUCT_OPS_SEC) == 0 ||
4017 				   strcmp(name, "?" STRUCT_OPS_LINK_SEC) == 0) {
4018 				sec_desc->sec_type = SEC_ST_OPS;
4019 				sec_desc->shdr = sh;
4020 				sec_desc->data = data;
4021 				obj->efile.has_st_ops = true;
4022 			} else if (strcmp(name, ARENA_SEC) == 0) {
4023 				obj->efile.arena_data = data;
4024 				obj->efile.arena_data_shndx = idx;
4025 			} else if (strcmp(name, JUMPTABLES_SEC) == 0) {
4026 				obj->jumptables_data = malloc(data->d_size);
4027 				if (!obj->jumptables_data)
4028 					return -ENOMEM;
4029 				memcpy(obj->jumptables_data, data->d_buf, data->d_size);
4030 				obj->jumptables_data_sz = data->d_size;
4031 				obj->efile.jumptables_data_shndx = idx;
4032 			} else {
4033 				pr_info("elf: skipping unrecognized data section(%d) %s\n",
4034 					idx, name);
4035 			}
4036 		} else if (sh->sh_type == SHT_REL) {
4037 			int targ_sec_idx = sh->sh_info; /* points to other section */
4038 
4039 			if (sh->sh_entsize != sizeof(Elf64_Rel) ||
4040 			    targ_sec_idx >= obj->efile.sec_cnt)
4041 				return -LIBBPF_ERRNO__FORMAT;
4042 
4043 			/* Only do relo for section with exec instructions */
4044 			if (!section_have_execinstr(obj, targ_sec_idx) &&
4045 			    strcmp(name, ".rel" STRUCT_OPS_SEC) &&
4046 			    strcmp(name, ".rel" STRUCT_OPS_LINK_SEC) &&
4047 			    strcmp(name, ".rel?" STRUCT_OPS_SEC) &&
4048 			    strcmp(name, ".rel?" STRUCT_OPS_LINK_SEC) &&
4049 			    strcmp(name, ".rel" MAPS_ELF_SEC)) {
4050 				pr_info("elf: skipping relo section(%d) %s for section(%d) %s\n",
4051 					idx, name, targ_sec_idx,
4052 					elf_sec_name(obj, elf_sec_by_idx(obj, targ_sec_idx)) ?: "<?>");
4053 				continue;
4054 			}
4055 
4056 			sec_desc->sec_type = SEC_RELO;
4057 			sec_desc->shdr = sh;
4058 			sec_desc->data = data;
4059 		} else if (sh->sh_type == SHT_NOBITS && (strcmp(name, BSS_SEC) == 0 ||
4060 							 str_has_pfx(name, BSS_SEC "."))) {
4061 			sec_desc->sec_type = SEC_BSS;
4062 			sec_desc->shdr = sh;
4063 			sec_desc->data = data;
4064 		} else {
4065 			pr_info("elf: skipping section(%d) %s (size %zu)\n", idx, name,
4066 				(size_t)sh->sh_size);
4067 		}
4068 	}
4069 
4070 	if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) {
4071 		pr_warn("elf: symbol strings section missing or invalid in %s\n", obj->path);
4072 		return -LIBBPF_ERRNO__FORMAT;
4073 	}
4074 
4075 	/* change BPF program insns to native endianness for introspection */
4076 	if (!is_native_endianness(obj))
4077 		bpf_object_bswap_progs(obj);
4078 
4079 	/* sort BPF programs by section name and in-section instruction offset
4080 	 * for faster search
4081 	 */
4082 	if (obj->nr_programs)
4083 		qsort(obj->programs, obj->nr_programs, sizeof(*obj->programs), cmp_progs);
4084 
4085 	return bpf_object__init_btf(obj, btf_data, btf_ext_data);
4086 }
4087 
4088 static bool sym_is_extern(const Elf64_Sym *sym)
4089 {
4090 	int bind = ELF64_ST_BIND(sym->st_info);
4091 	/* externs are symbols w/ type=NOTYPE, bind=GLOBAL|WEAK, section=UND */
4092 	return sym->st_shndx == SHN_UNDEF &&
4093 	       (bind == STB_GLOBAL || bind == STB_WEAK) &&
4094 	       ELF64_ST_TYPE(sym->st_info) == STT_NOTYPE;
4095 }
4096 
4097 static bool sym_is_subprog(const Elf64_Sym *sym, int text_shndx)
4098 {
4099 	int bind = ELF64_ST_BIND(sym->st_info);
4100 	int type = ELF64_ST_TYPE(sym->st_info);
4101 
4102 	/* in .text section */
4103 	if (sym->st_shndx != text_shndx)
4104 		return false;
4105 
4106 	/* local function */
4107 	if (bind == STB_LOCAL && type == STT_SECTION)
4108 		return true;
4109 
4110 	/* global function */
4111 	return (bind == STB_GLOBAL || bind == STB_WEAK) && type == STT_FUNC;
4112 }
4113 
4114 static int find_extern_btf_id(const struct btf *btf, const char *ext_name)
4115 {
4116 	const struct btf_type *t;
4117 	const char *tname;
4118 	int i, n;
4119 
4120 	if (!btf)
4121 		return -ESRCH;
4122 
4123 	n = btf__type_cnt(btf);
4124 	for (i = 1; i < n; i++) {
4125 		t = btf__type_by_id(btf, i);
4126 
4127 		if (!btf_is_var(t) && !btf_is_func(t))
4128 			continue;
4129 
4130 		tname = btf__name_by_offset(btf, t->name_off);
4131 		if (strcmp(tname, ext_name))
4132 			continue;
4133 
4134 		if (btf_is_var(t) &&
4135 		    btf_var(t)->linkage != BTF_VAR_GLOBAL_EXTERN)
4136 			return -EINVAL;
4137 
4138 		if (btf_is_func(t) && btf_func_linkage(t) != BTF_FUNC_EXTERN)
4139 			return -EINVAL;
4140 
4141 		return i;
4142 	}
4143 
4144 	return -ENOENT;
4145 }
4146 
4147 static int find_extern_sec_btf_id(struct btf *btf, int ext_btf_id) {
4148 	const struct btf_var_secinfo *vs;
4149 	const struct btf_type *t;
4150 	int i, j, n;
4151 
4152 	if (!btf)
4153 		return -ESRCH;
4154 
4155 	n = btf__type_cnt(btf);
4156 	for (i = 1; i < n; i++) {
4157 		t = btf__type_by_id(btf, i);
4158 
4159 		if (!btf_is_datasec(t))
4160 			continue;
4161 
4162 		vs = btf_var_secinfos(t);
4163 		for (j = 0; j < btf_vlen(t); j++, vs++) {
4164 			if (vs->type == ext_btf_id)
4165 				return i;
4166 		}
4167 	}
4168 
4169 	return -ENOENT;
4170 }
4171 
4172 static enum kcfg_type find_kcfg_type(const struct btf *btf, int id,
4173 				     bool *is_signed)
4174 {
4175 	const struct btf_type *t;
4176 	const char *name;
4177 
4178 	t = skip_mods_and_typedefs(btf, id, NULL);
4179 	name = btf__name_by_offset(btf, t->name_off);
4180 
4181 	if (is_signed)
4182 		*is_signed = false;
4183 	switch (btf_kind(t)) {
4184 	case BTF_KIND_INT: {
4185 		int enc = btf_int_encoding(t);
4186 
4187 		if (enc & BTF_INT_BOOL)
4188 			return t->size == 1 ? KCFG_BOOL : KCFG_UNKNOWN;
4189 		if (is_signed)
4190 			*is_signed = enc & BTF_INT_SIGNED;
4191 		if (t->size == 1)
4192 			return KCFG_CHAR;
4193 		if (t->size < 1 || t->size > 8 || (t->size & (t->size - 1)))
4194 			return KCFG_UNKNOWN;
4195 		return KCFG_INT;
4196 	}
4197 	case BTF_KIND_ENUM:
4198 		if (t->size != 4)
4199 			return KCFG_UNKNOWN;
4200 		if (strcmp(name, "libbpf_tristate"))
4201 			return KCFG_UNKNOWN;
4202 		return KCFG_TRISTATE;
4203 	case BTF_KIND_ENUM64:
4204 		if (strcmp(name, "libbpf_tristate"))
4205 			return KCFG_UNKNOWN;
4206 		return KCFG_TRISTATE;
4207 	case BTF_KIND_ARRAY:
4208 		if (btf_array(t)->nelems == 0)
4209 			return KCFG_UNKNOWN;
4210 		if (find_kcfg_type(btf, btf_array(t)->type, NULL) != KCFG_CHAR)
4211 			return KCFG_UNKNOWN;
4212 		return KCFG_CHAR_ARR;
4213 	default:
4214 		return KCFG_UNKNOWN;
4215 	}
4216 }
4217 
4218 static int cmp_externs(const void *_a, const void *_b)
4219 {
4220 	const struct extern_desc *a = _a;
4221 	const struct extern_desc *b = _b;
4222 
4223 	if (a->type != b->type)
4224 		return a->type < b->type ? -1 : 1;
4225 
4226 	if (a->type == EXT_KCFG) {
4227 		/* descending order by alignment requirements */
4228 		if (a->kcfg.align != b->kcfg.align)
4229 			return a->kcfg.align > b->kcfg.align ? -1 : 1;
4230 		/* ascending order by size, within same alignment class */
4231 		if (a->kcfg.sz != b->kcfg.sz)
4232 			return a->kcfg.sz < b->kcfg.sz ? -1 : 1;
4233 	}
4234 
4235 	/* resolve ties by name */
4236 	return strcmp(a->name, b->name);
4237 }
4238 
4239 static int find_int_btf_id(const struct btf *btf)
4240 {
4241 	const struct btf_type *t;
4242 	int i, n;
4243 
4244 	n = btf__type_cnt(btf);
4245 	for (i = 1; i < n; i++) {
4246 		t = btf__type_by_id(btf, i);
4247 
4248 		if (btf_is_int(t) && btf_int_bits(t) == 32)
4249 			return i;
4250 	}
4251 
4252 	return 0;
4253 }
4254 
4255 static int add_dummy_ksym_var(struct btf *btf)
4256 {
4257 	int i, int_btf_id, sec_btf_id, dummy_var_btf_id;
4258 	const struct btf_var_secinfo *vs;
4259 	const struct btf_type *sec;
4260 
4261 	if (!btf)
4262 		return 0;
4263 
4264 	sec_btf_id = btf__find_by_name_kind(btf, KSYMS_SEC,
4265 					    BTF_KIND_DATASEC);
4266 	if (sec_btf_id < 0)
4267 		return 0;
4268 
4269 	sec = btf__type_by_id(btf, sec_btf_id);
4270 	vs = btf_var_secinfos(sec);
4271 	for (i = 0; i < btf_vlen(sec); i++, vs++) {
4272 		const struct btf_type *vt;
4273 
4274 		vt = btf__type_by_id(btf, vs->type);
4275 		if (btf_is_func(vt))
4276 			break;
4277 	}
4278 
4279 	/* No func in ksyms sec.  No need to add dummy var. */
4280 	if (i == btf_vlen(sec))
4281 		return 0;
4282 
4283 	int_btf_id = find_int_btf_id(btf);
4284 	dummy_var_btf_id = btf__add_var(btf,
4285 					"dummy_ksym",
4286 					BTF_VAR_GLOBAL_ALLOCATED,
4287 					int_btf_id);
4288 	if (dummy_var_btf_id < 0)
4289 		pr_warn("cannot create a dummy_ksym var\n");
4290 
4291 	return dummy_var_btf_id;
4292 }
4293 
4294 static int bpf_object__collect_externs(struct bpf_object *obj)
4295 {
4296 	struct btf_type *sec, *kcfg_sec = NULL, *ksym_sec = NULL;
4297 	const struct btf_type *t;
4298 	struct extern_desc *ext;
4299 	int i, n, off, dummy_var_btf_id;
4300 	const char *ext_name, *sec_name;
4301 	size_t ext_essent_len;
4302 	Elf_Scn *scn;
4303 	Elf64_Shdr *sh;
4304 
4305 	if (!obj->efile.symbols)
4306 		return 0;
4307 
4308 	scn = elf_sec_by_idx(obj, obj->efile.symbols_shndx);
4309 	sh = elf_sec_hdr(obj, scn);
4310 	if (!sh || sh->sh_entsize != sizeof(Elf64_Sym))
4311 		return -LIBBPF_ERRNO__FORMAT;
4312 
4313 	dummy_var_btf_id = add_dummy_ksym_var(obj->btf);
4314 	if (dummy_var_btf_id < 0)
4315 		return dummy_var_btf_id;
4316 
4317 	n = sh->sh_size / sh->sh_entsize;
4318 	pr_debug("looking for externs among %d symbols...\n", n);
4319 
4320 	for (i = 0; i < n; i++) {
4321 		Elf64_Sym *sym = elf_sym_by_idx(obj, i);
4322 
4323 		if (!sym)
4324 			return -LIBBPF_ERRNO__FORMAT;
4325 		if (!sym_is_extern(sym))
4326 			continue;
4327 		ext_name = elf_sym_str(obj, sym->st_name);
4328 		if (str_is_empty(ext_name))
4329 			continue;
4330 
4331 		ext = obj->externs;
4332 		ext = libbpf_reallocarray(ext, obj->nr_extern + 1, sizeof(*ext));
4333 		if (!ext)
4334 			return -ENOMEM;
4335 		obj->externs = ext;
4336 		ext = &ext[obj->nr_extern];
4337 		memset(ext, 0, sizeof(*ext));
4338 		obj->nr_extern++;
4339 
4340 		ext->btf_id = find_extern_btf_id(obj->btf, ext_name);
4341 		if (ext->btf_id <= 0) {
4342 			pr_warn("failed to find BTF for extern '%s': %d\n",
4343 				ext_name, ext->btf_id);
4344 			return ext->btf_id;
4345 		}
4346 		t = btf__type_by_id(obj->btf, ext->btf_id);
4347 		ext->name = strdup(btf__name_by_offset(obj->btf, t->name_off));
4348 		if (!ext->name)
4349 			return -ENOMEM;
4350 		ext->sym_idx = i;
4351 		ext->is_weak = ELF64_ST_BIND(sym->st_info) == STB_WEAK;
4352 
4353 		ext_essent_len = bpf_core_essential_name_len(ext->name);
4354 		ext->essent_name = NULL;
4355 		if (ext_essent_len != strlen(ext->name)) {
4356 			ext->essent_name = strndup(ext->name, ext_essent_len);
4357 			if (!ext->essent_name)
4358 				return -ENOMEM;
4359 		}
4360 
4361 		ext->sec_btf_id = find_extern_sec_btf_id(obj->btf, ext->btf_id);
4362 		if (ext->sec_btf_id <= 0) {
4363 			pr_warn("failed to find BTF for extern '%s' [%d] section: %d\n",
4364 				ext_name, ext->btf_id, ext->sec_btf_id);
4365 			return ext->sec_btf_id;
4366 		}
4367 		sec = (void *)btf__type_by_id(obj->btf, ext->sec_btf_id);
4368 		sec_name = btf__name_by_offset(obj->btf, sec->name_off);
4369 
4370 		if (strcmp(sec_name, KCONFIG_SEC) == 0) {
4371 			if (btf_is_func(t)) {
4372 				pr_warn("extern function %s is unsupported under %s section\n",
4373 					ext->name, KCONFIG_SEC);
4374 				return -ENOTSUP;
4375 			}
4376 			kcfg_sec = sec;
4377 			ext->type = EXT_KCFG;
4378 			ext->kcfg.sz = btf__resolve_size(obj->btf, t->type);
4379 			if (ext->kcfg.sz <= 0) {
4380 				pr_warn("failed to resolve size of extern (kcfg) '%s': %d\n",
4381 					ext_name, ext->kcfg.sz);
4382 				return ext->kcfg.sz;
4383 			}
4384 			ext->kcfg.align = btf__align_of(obj->btf, t->type);
4385 			if (ext->kcfg.align <= 0) {
4386 				pr_warn("failed to determine alignment of extern (kcfg) '%s': %d\n",
4387 					ext_name, ext->kcfg.align);
4388 				return -EINVAL;
4389 			}
4390 			ext->kcfg.type = find_kcfg_type(obj->btf, t->type,
4391 							&ext->kcfg.is_signed);
4392 			if (ext->kcfg.type == KCFG_UNKNOWN) {
4393 				pr_warn("extern (kcfg) '%s': type is unsupported\n", ext_name);
4394 				return -ENOTSUP;
4395 			}
4396 		} else if (strcmp(sec_name, KSYMS_SEC) == 0) {
4397 			ksym_sec = sec;
4398 			ext->type = EXT_KSYM;
4399 			skip_mods_and_typedefs(obj->btf, t->type,
4400 					       &ext->ksym.type_id);
4401 		} else {
4402 			pr_warn("unrecognized extern section '%s'\n", sec_name);
4403 			return -ENOTSUP;
4404 		}
4405 	}
4406 	pr_debug("collected %d externs total\n", obj->nr_extern);
4407 
4408 	if (!obj->nr_extern)
4409 		return 0;
4410 
4411 	/* sort externs by type, for kcfg ones also by (align, size, name) */
4412 	qsort(obj->externs, obj->nr_extern, sizeof(*ext), cmp_externs);
4413 
4414 	/* for .ksyms section, we need to turn all externs into allocated
4415 	 * variables in BTF to pass kernel verification; we do this by
4416 	 * pretending that each extern is a 8-byte variable
4417 	 */
4418 	if (ksym_sec) {
4419 		/* find existing 4-byte integer type in BTF to use for fake
4420 		 * extern variables in DATASEC
4421 		 */
4422 		int int_btf_id = find_int_btf_id(obj->btf);
4423 		/* For extern function, a dummy_var added earlier
4424 		 * will be used to replace the vs->type and
4425 		 * its name string will be used to refill
4426 		 * the missing param's name.
4427 		 */
4428 		const struct btf_type *dummy_var;
4429 
4430 		dummy_var = btf__type_by_id(obj->btf, dummy_var_btf_id);
4431 		for (i = 0; i < obj->nr_extern; i++) {
4432 			ext = &obj->externs[i];
4433 			if (ext->type != EXT_KSYM)
4434 				continue;
4435 			pr_debug("extern (ksym) #%d: symbol %d, name %s\n",
4436 				 i, ext->sym_idx, ext->name);
4437 		}
4438 
4439 		sec = ksym_sec;
4440 		n = btf_vlen(sec);
4441 		for (i = 0, off = 0; i < n; i++, off += sizeof(int)) {
4442 			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
4443 			struct btf_type *vt;
4444 
4445 			vt = (void *)btf__type_by_id(obj->btf, vs->type);
4446 			ext_name = btf__name_by_offset(obj->btf, vt->name_off);
4447 			ext = find_extern_by_name(obj, ext_name);
4448 			if (!ext) {
4449 				pr_warn("failed to find extern definition for BTF %s '%s'\n",
4450 					btf_kind_str(vt), ext_name);
4451 				return -ESRCH;
4452 			}
4453 			if (btf_is_func(vt)) {
4454 				const struct btf_type *func_proto;
4455 				struct btf_param *param;
4456 				int j;
4457 
4458 				func_proto = btf__type_by_id(obj->btf,
4459 							     vt->type);
4460 				param = btf_params(func_proto);
4461 				/* Reuse the dummy_var string if the
4462 				 * func proto does not have param name.
4463 				 */
4464 				for (j = 0; j < btf_vlen(func_proto); j++)
4465 					if (param[j].type && !param[j].name_off)
4466 						param[j].name_off =
4467 							dummy_var->name_off;
4468 				vs->type = dummy_var_btf_id;
4469 				vt->info &= ~0xffff;
4470 				vt->info |= BTF_FUNC_GLOBAL;
4471 			} else {
4472 				btf_var(vt)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
4473 				vt->type = int_btf_id;
4474 			}
4475 			vs->offset = off;
4476 			vs->size = sizeof(int);
4477 		}
4478 		sec->size = off;
4479 	}
4480 
4481 	if (kcfg_sec) {
4482 		sec = kcfg_sec;
4483 		/* for kcfg externs calculate their offsets within a .kconfig map */
4484 		off = 0;
4485 		for (i = 0; i < obj->nr_extern; i++) {
4486 			ext = &obj->externs[i];
4487 			if (ext->type != EXT_KCFG)
4488 				continue;
4489 
4490 			ext->kcfg.data_off = roundup(off, ext->kcfg.align);
4491 			off = ext->kcfg.data_off + ext->kcfg.sz;
4492 			pr_debug("extern (kcfg) #%d: symbol %d, off %u, name %s\n",
4493 				 i, ext->sym_idx, ext->kcfg.data_off, ext->name);
4494 		}
4495 		sec->size = off;
4496 		n = btf_vlen(sec);
4497 		for (i = 0; i < n; i++) {
4498 			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
4499 
4500 			t = btf__type_by_id(obj->btf, vs->type);
4501 			ext_name = btf__name_by_offset(obj->btf, t->name_off);
4502 			ext = find_extern_by_name(obj, ext_name);
4503 			if (!ext) {
4504 				pr_warn("failed to find extern definition for BTF var '%s'\n",
4505 					ext_name);
4506 				return -ESRCH;
4507 			}
4508 			btf_var(t)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
4509 			vs->offset = ext->kcfg.data_off;
4510 		}
4511 	}
4512 	return 0;
4513 }
4514 
4515 static bool prog_is_subprog(const struct bpf_object *obj, const struct bpf_program *prog)
4516 {
4517 	return prog->sec_idx == obj->efile.text_shndx;
4518 }
4519 
4520 struct bpf_program *
4521 bpf_object__find_program_by_name(const struct bpf_object *obj,
4522 				 const char *name)
4523 {
4524 	struct bpf_program *prog;
4525 
4526 	bpf_object__for_each_program(prog, obj) {
4527 		if (prog_is_subprog(obj, prog))
4528 			continue;
4529 		if (!strcmp(prog->name, name))
4530 			return prog;
4531 	}
4532 	return errno = ENOENT, NULL;
4533 }
4534 
4535 static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
4536 				      int shndx)
4537 {
4538 	switch (obj->efile.secs[shndx].sec_type) {
4539 	case SEC_BSS:
4540 	case SEC_DATA:
4541 	case SEC_RODATA:
4542 		return true;
4543 	default:
4544 		return false;
4545 	}
4546 }
4547 
4548 static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
4549 				      int shndx)
4550 {
4551 	return shndx == obj->efile.btf_maps_shndx;
4552 }
4553 
4554 static enum libbpf_map_type
4555 bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
4556 {
4557 	if (shndx == obj->efile.symbols_shndx)
4558 		return LIBBPF_MAP_KCONFIG;
4559 
4560 	switch (obj->efile.secs[shndx].sec_type) {
4561 	case SEC_BSS:
4562 		return LIBBPF_MAP_BSS;
4563 	case SEC_DATA:
4564 		return LIBBPF_MAP_DATA;
4565 	case SEC_RODATA:
4566 		return LIBBPF_MAP_RODATA;
4567 	default:
4568 		return LIBBPF_MAP_UNSPEC;
4569 	}
4570 }
4571 
4572 static int bpf_prog_compute_hash(struct bpf_program *prog)
4573 {
4574 	struct bpf_insn *purged;
4575 	int i, err = 0;
4576 
4577 	purged = calloc(prog->insns_cnt, BPF_INSN_SZ);
4578 	if (!purged)
4579 		return -ENOMEM;
4580 
4581 	/* If relocations have been done, the map_fd needs to be
4582 	 * discarded for the digest calculation.
4583 	 */
4584 	for (i = 0; i < prog->insns_cnt; i++) {
4585 		purged[i] = prog->insns[i];
4586 		if (purged[i].code == (BPF_LD | BPF_IMM | BPF_DW) &&
4587 		    (purged[i].src_reg == BPF_PSEUDO_MAP_FD ||
4588 		     purged[i].src_reg == BPF_PSEUDO_MAP_VALUE)) {
4589 			purged[i].imm = 0;
4590 			i++;
4591 			if (i >= prog->insns_cnt ||
4592 			    prog->insns[i].code != 0 ||
4593 			    prog->insns[i].dst_reg != 0 ||
4594 			    prog->insns[i].src_reg != 0 ||
4595 			    prog->insns[i].off != 0) {
4596 				err = -EINVAL;
4597 				goto out;
4598 			}
4599 			purged[i] = prog->insns[i];
4600 			purged[i].imm = 0;
4601 		}
4602 	}
4603 	libbpf_sha256(purged, prog->insns_cnt * sizeof(struct bpf_insn),
4604 		      prog->hash);
4605 out:
4606 	free(purged);
4607 	return err;
4608 }
4609 
4610 static int bpf_program__record_reloc(struct bpf_program *prog,
4611 				     struct reloc_desc *reloc_desc,
4612 				     __u32 insn_idx, const char *sym_name,
4613 				     const Elf64_Sym *sym, const Elf64_Rel *rel)
4614 {
4615 	struct bpf_insn *insn = &prog->insns[insn_idx];
4616 	size_t map_idx, nr_maps = prog->obj->nr_maps;
4617 	struct bpf_object *obj = prog->obj;
4618 	__u32 shdr_idx = sym->st_shndx;
4619 	enum libbpf_map_type type;
4620 	const char *sym_sec_name;
4621 	struct bpf_map *map;
4622 
4623 	if (!is_call_insn(insn) && !is_ldimm64_insn(insn)) {
4624 		pr_warn("prog '%s': invalid relo against '%s' for insns[%d].code 0x%x\n",
4625 			prog->name, sym_name, insn_idx, insn->code);
4626 		return -LIBBPF_ERRNO__RELOC;
4627 	}
4628 
4629 	if (sym_is_extern(sym)) {
4630 		int sym_idx = ELF64_R_SYM(rel->r_info);
4631 		int i, n = obj->nr_extern;
4632 		struct extern_desc *ext;
4633 
4634 		for (i = 0; i < n; i++) {
4635 			ext = &obj->externs[i];
4636 			if (ext->sym_idx == sym_idx)
4637 				break;
4638 		}
4639 		if (i >= n) {
4640 			pr_warn("prog '%s': extern relo failed to find extern for '%s' (%d)\n",
4641 				prog->name, sym_name, sym_idx);
4642 			return -LIBBPF_ERRNO__RELOC;
4643 		}
4644 		pr_debug("prog '%s': found extern #%d '%s' (sym %d) for insn #%u\n",
4645 			 prog->name, i, ext->name, ext->sym_idx, insn_idx);
4646 		if (insn->code == (BPF_JMP | BPF_CALL))
4647 			reloc_desc->type = RELO_EXTERN_CALL;
4648 		else
4649 			reloc_desc->type = RELO_EXTERN_LD64;
4650 		reloc_desc->insn_idx = insn_idx;
4651 		reloc_desc->ext_idx = i;
4652 		return 0;
4653 	}
4654 
4655 	/* sub-program call relocation */
4656 	if (is_call_insn(insn)) {
4657 		if (insn->src_reg != BPF_PSEUDO_CALL) {
4658 			pr_warn("prog '%s': incorrect bpf_call opcode\n", prog->name);
4659 			return -LIBBPF_ERRNO__RELOC;
4660 		}
4661 		/* text_shndx can be 0, if no default "main" program exists */
4662 		if (!shdr_idx || shdr_idx != obj->efile.text_shndx) {
4663 			sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4664 			pr_warn("prog '%s': bad call relo against '%s' in section '%s'\n",
4665 				prog->name, sym_name, sym_sec_name);
4666 			return -LIBBPF_ERRNO__RELOC;
4667 		}
4668 		if (sym->st_value % BPF_INSN_SZ) {
4669 			pr_warn("prog '%s': bad call relo against '%s' at offset %zu\n",
4670 				prog->name, sym_name, (size_t)sym->st_value);
4671 			return -LIBBPF_ERRNO__RELOC;
4672 		}
4673 		reloc_desc->type = RELO_CALL;
4674 		reloc_desc->insn_idx = insn_idx;
4675 		reloc_desc->sym_off = sym->st_value;
4676 		return 0;
4677 	}
4678 
4679 	if (!shdr_idx || shdr_idx >= SHN_LORESERVE) {
4680 		pr_warn("prog '%s': invalid relo against '%s' in special section 0x%x; forgot to initialize global var?..\n",
4681 			prog->name, sym_name, shdr_idx);
4682 		return -LIBBPF_ERRNO__RELOC;
4683 	}
4684 
4685 	/* loading subprog addresses */
4686 	if (sym_is_subprog(sym, obj->efile.text_shndx)) {
4687 		/* global_func: sym->st_value = offset in the section, insn->imm = 0.
4688 		 * local_func: sym->st_value = 0, insn->imm = offset in the section.
4689 		 */
4690 		if ((sym->st_value % BPF_INSN_SZ) || (insn->imm % BPF_INSN_SZ)) {
4691 			pr_warn("prog '%s': bad subprog addr relo against '%s' at offset %zu+%d\n",
4692 				prog->name, sym_name, (size_t)sym->st_value, insn->imm);
4693 			return -LIBBPF_ERRNO__RELOC;
4694 		}
4695 
4696 		reloc_desc->type = RELO_SUBPROG_ADDR;
4697 		reloc_desc->insn_idx = insn_idx;
4698 		reloc_desc->sym_off = sym->st_value;
4699 		return 0;
4700 	}
4701 
4702 	type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
4703 	sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4704 
4705 	/* arena data relocation */
4706 	if (shdr_idx == obj->efile.arena_data_shndx) {
4707 		if (obj->arena_map_idx < 0) {
4708 			pr_warn("prog '%s': bad arena data relocation at insn %u, no arena maps defined\n",
4709 				prog->name, insn_idx);
4710 			return -LIBBPF_ERRNO__RELOC;
4711 		}
4712 		reloc_desc->type = RELO_DATA;
4713 		reloc_desc->insn_idx = insn_idx;
4714 		reloc_desc->map_idx = obj->arena_map_idx;
4715 		reloc_desc->sym_off = sym->st_value;
4716 
4717 		map = &obj->maps[obj->arena_map_idx];
4718 		pr_debug("prog '%s': found arena map %d (%s, sec %d, off %zu) for insn %u\n",
4719 			 prog->name, obj->arena_map_idx, map->name, map->sec_idx,
4720 			 map->sec_offset, insn_idx);
4721 		return 0;
4722 	}
4723 
4724 	/* jump table data relocation */
4725 	if (shdr_idx == obj->efile.jumptables_data_shndx) {
4726 		reloc_desc->type = RELO_INSN_ARRAY;
4727 		reloc_desc->insn_idx = insn_idx;
4728 		reloc_desc->map_idx = -1;
4729 		reloc_desc->sym_off = sym->st_value;
4730 		reloc_desc->sym_size = sym->st_size;
4731 		return 0;
4732 	}
4733 
4734 	/* generic map reference relocation */
4735 	if (type == LIBBPF_MAP_UNSPEC) {
4736 		if (!bpf_object__shndx_is_maps(obj, shdr_idx)) {
4737 			pr_warn("prog '%s': bad map relo against '%s' in section '%s'\n",
4738 				prog->name, sym_name, sym_sec_name);
4739 			return -LIBBPF_ERRNO__RELOC;
4740 		}
4741 		for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4742 			map = &obj->maps[map_idx];
4743 			if (map->libbpf_type != type ||
4744 			    map->sec_idx != sym->st_shndx ||
4745 			    map->sec_offset != sym->st_value)
4746 				continue;
4747 			pr_debug("prog '%s': found map %zd (%s, sec %d, off %zu) for insn #%u\n",
4748 				 prog->name, map_idx, map->name, map->sec_idx,
4749 				 map->sec_offset, insn_idx);
4750 			break;
4751 		}
4752 		if (map_idx >= nr_maps) {
4753 			pr_warn("prog '%s': map relo failed to find map for section '%s', off %zu\n",
4754 				prog->name, sym_sec_name, (size_t)sym->st_value);
4755 			return -LIBBPF_ERRNO__RELOC;
4756 		}
4757 		reloc_desc->type = RELO_LD64;
4758 		reloc_desc->insn_idx = insn_idx;
4759 		reloc_desc->map_idx = map_idx;
4760 		reloc_desc->sym_off = 0; /* sym->st_value determines map_idx */
4761 		return 0;
4762 	}
4763 
4764 	/* global data map relocation */
4765 	if (!bpf_object__shndx_is_data(obj, shdr_idx)) {
4766 		pr_warn("prog '%s': bad data relo against section '%s'\n",
4767 			prog->name, sym_sec_name);
4768 		return -LIBBPF_ERRNO__RELOC;
4769 	}
4770 	for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4771 		map = &obj->maps[map_idx];
4772 		if (map->libbpf_type != type || map->sec_idx != sym->st_shndx)
4773 			continue;
4774 		pr_debug("prog '%s': found data map %zd (%s, sec %d, off %zu) for insn %u\n",
4775 			 prog->name, map_idx, map->name, map->sec_idx,
4776 			 map->sec_offset, insn_idx);
4777 		break;
4778 	}
4779 	if (map_idx >= nr_maps) {
4780 		pr_warn("prog '%s': data relo failed to find map for section '%s'\n",
4781 			prog->name, sym_sec_name);
4782 		return -LIBBPF_ERRNO__RELOC;
4783 	}
4784 
4785 	reloc_desc->type = RELO_DATA;
4786 	reloc_desc->insn_idx = insn_idx;
4787 	reloc_desc->map_idx = map_idx;
4788 	reloc_desc->sym_off = sym->st_value;
4789 	return 0;
4790 }
4791 
4792 static bool prog_contains_insn(const struct bpf_program *prog, size_t insn_idx)
4793 {
4794 	return insn_idx >= prog->sec_insn_off &&
4795 	       insn_idx < prog->sec_insn_off + prog->sec_insn_cnt;
4796 }
4797 
4798 static struct bpf_program *find_prog_by_sec_insn(const struct bpf_object *obj,
4799 						 size_t sec_idx, size_t insn_idx)
4800 {
4801 	int l = 0, r = obj->nr_programs - 1, m;
4802 	struct bpf_program *prog;
4803 
4804 	if (!obj->nr_programs)
4805 		return NULL;
4806 
4807 	while (l < r) {
4808 		m = l + (r - l + 1) / 2;
4809 		prog = &obj->programs[m];
4810 
4811 		if (prog->sec_idx < sec_idx ||
4812 		    (prog->sec_idx == sec_idx && prog->sec_insn_off <= insn_idx))
4813 			l = m;
4814 		else
4815 			r = m - 1;
4816 	}
4817 	/* matching program could be at index l, but it still might be the
4818 	 * wrong one, so we need to double check conditions for the last time
4819 	 */
4820 	prog = &obj->programs[l];
4821 	if (prog->sec_idx == sec_idx && prog_contains_insn(prog, insn_idx))
4822 		return prog;
4823 	return NULL;
4824 }
4825 
4826 static int
4827 bpf_object__collect_prog_relos(struct bpf_object *obj, Elf64_Shdr *shdr, Elf_Data *data)
4828 {
4829 	const char *relo_sec_name, *sec_name;
4830 	size_t sec_idx = shdr->sh_info, sym_idx;
4831 	struct bpf_program *prog;
4832 	struct reloc_desc *relos;
4833 	int err, i, nrels;
4834 	const char *sym_name;
4835 	__u32 insn_idx;
4836 	Elf_Scn *scn;
4837 	Elf_Data *scn_data;
4838 	Elf64_Sym *sym;
4839 	Elf64_Rel *rel;
4840 
4841 	if (sec_idx >= obj->efile.sec_cnt)
4842 		return -EINVAL;
4843 
4844 	scn = elf_sec_by_idx(obj, sec_idx);
4845 	scn_data = elf_sec_data(obj, scn);
4846 	if (!scn_data)
4847 		return -LIBBPF_ERRNO__FORMAT;
4848 
4849 	relo_sec_name = elf_sec_str(obj, shdr->sh_name);
4850 	sec_name = elf_sec_name(obj, scn);
4851 	if (!relo_sec_name || !sec_name)
4852 		return -EINVAL;
4853 
4854 	pr_debug("sec '%s': collecting relocation for section(%zu) '%s'\n",
4855 		 relo_sec_name, sec_idx, sec_name);
4856 	nrels = shdr->sh_size / shdr->sh_entsize;
4857 
4858 	for (i = 0; i < nrels; i++) {
4859 		rel = elf_rel_by_idx(data, i);
4860 		if (!rel) {
4861 			pr_warn("sec '%s': failed to get relo #%d\n", relo_sec_name, i);
4862 			return -LIBBPF_ERRNO__FORMAT;
4863 		}
4864 
4865 		sym_idx = ELF64_R_SYM(rel->r_info);
4866 		sym = elf_sym_by_idx(obj, sym_idx);
4867 		if (!sym) {
4868 			pr_warn("sec '%s': symbol #%zu not found for relo #%d\n",
4869 				relo_sec_name, sym_idx, i);
4870 			return -LIBBPF_ERRNO__FORMAT;
4871 		}
4872 
4873 		if (sym->st_shndx >= obj->efile.sec_cnt) {
4874 			pr_warn("sec '%s': corrupted symbol #%zu pointing to invalid section #%zu for relo #%d\n",
4875 				relo_sec_name, sym_idx, (size_t)sym->st_shndx, i);
4876 			return -LIBBPF_ERRNO__FORMAT;
4877 		}
4878 
4879 		if (rel->r_offset % BPF_INSN_SZ || rel->r_offset >= scn_data->d_size) {
4880 			pr_warn("sec '%s': invalid offset 0x%zx for relo #%d\n",
4881 				relo_sec_name, (size_t)rel->r_offset, i);
4882 			return -LIBBPF_ERRNO__FORMAT;
4883 		}
4884 
4885 		insn_idx = rel->r_offset / BPF_INSN_SZ;
4886 		/* relocations against static functions are recorded as
4887 		 * relocations against the section that contains a function;
4888 		 * in such case, symbol will be STT_SECTION and sym.st_name
4889 		 * will point to empty string (0), so fetch section name
4890 		 * instead
4891 		 */
4892 		if (ELF64_ST_TYPE(sym->st_info) == STT_SECTION && sym->st_name == 0)
4893 			sym_name = elf_sec_name(obj, elf_sec_by_idx(obj, sym->st_shndx));
4894 		else
4895 			sym_name = elf_sym_str(obj, sym->st_name);
4896 		sym_name = sym_name ?: "<?";
4897 
4898 		pr_debug("sec '%s': relo #%d: insn #%u against '%s'\n",
4899 			 relo_sec_name, i, insn_idx, sym_name);
4900 
4901 		prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
4902 		if (!prog) {
4903 			pr_debug("sec '%s': relo #%d: couldn't find program in section '%s' for insn #%u, probably overridden weak function, skipping...\n",
4904 				relo_sec_name, i, sec_name, insn_idx);
4905 			continue;
4906 		}
4907 
4908 		relos = libbpf_reallocarray(prog->reloc_desc,
4909 					    prog->nr_reloc + 1, sizeof(*relos));
4910 		if (!relos)
4911 			return -ENOMEM;
4912 		prog->reloc_desc = relos;
4913 
4914 		/* adjust insn_idx to local BPF program frame of reference */
4915 		insn_idx -= prog->sec_insn_off;
4916 		err = bpf_program__record_reloc(prog, &relos[prog->nr_reloc],
4917 						insn_idx, sym_name, sym, rel);
4918 		if (err)
4919 			return err;
4920 
4921 		prog->nr_reloc++;
4922 	}
4923 	return 0;
4924 }
4925 
4926 static int map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map)
4927 {
4928 	int id;
4929 
4930 	if (!obj->btf)
4931 		return -ENOENT;
4932 
4933 	/* if it's BTF-defined map, we don't need to search for type IDs.
4934 	 * For struct_ops map, it does not need btf_key_type_id and
4935 	 * btf_value_type_id.
4936 	 */
4937 	if (map->sec_idx == obj->efile.btf_maps_shndx || bpf_map__is_struct_ops(map))
4938 		return 0;
4939 
4940 	/*
4941 	 * LLVM annotates global data differently in BTF, that is,
4942 	 * only as '.data', '.bss' or '.rodata'.
4943 	 */
4944 	if (!bpf_map__is_internal(map))
4945 		return -ENOENT;
4946 
4947 	id = btf__find_by_name(obj->btf, map->real_name);
4948 	if (id < 0)
4949 		return id;
4950 
4951 	map->btf_key_type_id = 0;
4952 	map->btf_value_type_id = id;
4953 	return 0;
4954 }
4955 
4956 static int bpf_get_map_info_from_fdinfo(int fd, struct bpf_map_info *info)
4957 {
4958 	char file[PATH_MAX], buff[4096];
4959 	FILE *fp;
4960 	__u32 val;
4961 	int err;
4962 
4963 	snprintf(file, sizeof(file), "/proc/%d/fdinfo/%d", getpid(), fd);
4964 	memset(info, 0, sizeof(*info));
4965 
4966 	fp = fopen(file, "re");
4967 	if (!fp) {
4968 		err = -errno;
4969 		pr_warn("failed to open %s: %s. No procfs support?\n", file,
4970 			errstr(err));
4971 		return err;
4972 	}
4973 
4974 	while (fgets(buff, sizeof(buff), fp)) {
4975 		if (sscanf(buff, "map_type:\t%u", &val) == 1)
4976 			info->type = val;
4977 		else if (sscanf(buff, "key_size:\t%u", &val) == 1)
4978 			info->key_size = val;
4979 		else if (sscanf(buff, "value_size:\t%u", &val) == 1)
4980 			info->value_size = val;
4981 		else if (sscanf(buff, "max_entries:\t%u", &val) == 1)
4982 			info->max_entries = val;
4983 		else if (sscanf(buff, "map_flags:\t%i", &val) == 1)
4984 			info->map_flags = val;
4985 	}
4986 
4987 	fclose(fp);
4988 
4989 	return 0;
4990 }
4991 
4992 static bool map_is_created(const struct bpf_map *map)
4993 {
4994 	return map->obj->state >= OBJ_PREPARED || map->reused;
4995 }
4996 
4997 bool bpf_map__autocreate(const struct bpf_map *map)
4998 {
4999 	return map->autocreate;
5000 }
5001 
5002 int bpf_map__set_autocreate(struct bpf_map *map, bool autocreate)
5003 {
5004 	if (map_is_created(map))
5005 		return libbpf_err(-EBUSY);
5006 
5007 	map->autocreate = autocreate;
5008 	return 0;
5009 }
5010 
5011 int bpf_map__set_autoattach(struct bpf_map *map, bool autoattach)
5012 {
5013 	if (!bpf_map__is_struct_ops(map))
5014 		return libbpf_err(-EINVAL);
5015 
5016 	map->autoattach = autoattach;
5017 	return 0;
5018 }
5019 
5020 bool bpf_map__autoattach(const struct bpf_map *map)
5021 {
5022 	return map->autoattach;
5023 }
5024 
5025 int bpf_map__reuse_fd(struct bpf_map *map, int fd)
5026 {
5027 	struct bpf_map_info info;
5028 	__u32 len = sizeof(info), name_len;
5029 	int new_fd, err;
5030 	char *new_name;
5031 
5032 	memset(&info, 0, len);
5033 	err = bpf_map_get_info_by_fd(fd, &info, &len);
5034 	if (err && errno == EINVAL)
5035 		err = bpf_get_map_info_from_fdinfo(fd, &info);
5036 	if (err)
5037 		return libbpf_err(err);
5038 
5039 	name_len = strlen(info.name);
5040 	if (name_len == BPF_OBJ_NAME_LEN - 1 && strncmp(map->name, info.name, name_len) == 0)
5041 		new_name = strdup(map->name);
5042 	else
5043 		new_name = strdup(info.name);
5044 
5045 	if (!new_name)
5046 		return libbpf_err(-errno);
5047 
5048 	/*
5049 	 * Like dup(), but make sure new FD is >= 3 and has O_CLOEXEC set.
5050 	 * This is similar to what we do in ensure_good_fd(), but without
5051 	 * closing original FD.
5052 	 */
5053 	new_fd = fcntl(fd, F_DUPFD_CLOEXEC, 3);
5054 	if (new_fd < 0) {
5055 		err = -errno;
5056 		goto err_free_new_name;
5057 	}
5058 
5059 	err = reuse_fd(map->fd, new_fd);
5060 	if (err)
5061 		goto err_free_new_name;
5062 
5063 	free(map->name);
5064 
5065 	map->name = new_name;
5066 	map->def.type = info.type;
5067 	map->def.key_size = info.key_size;
5068 	map->def.value_size = info.value_size;
5069 	map->def.max_entries = info.max_entries;
5070 	map->def.map_flags = info.map_flags;
5071 	map->btf_key_type_id = info.btf_key_type_id;
5072 	map->btf_value_type_id = info.btf_value_type_id;
5073 	map->reused = true;
5074 	map->map_extra = info.map_extra;
5075 
5076 	return 0;
5077 
5078 err_free_new_name:
5079 	free(new_name);
5080 	return libbpf_err(err);
5081 }
5082 
5083 __u32 bpf_map__max_entries(const struct bpf_map *map)
5084 {
5085 	return map->def.max_entries;
5086 }
5087 
5088 struct bpf_map *bpf_map__inner_map(struct bpf_map *map)
5089 {
5090 	if (!bpf_map_type__is_map_in_map(map->def.type))
5091 		return errno = EINVAL, NULL;
5092 
5093 	return map->inner_map;
5094 }
5095 
5096 int bpf_map__set_max_entries(struct bpf_map *map, __u32 max_entries)
5097 {
5098 	if (map_is_created(map))
5099 		return libbpf_err(-EBUSY);
5100 
5101 	map->def.max_entries = max_entries;
5102 
5103 	/* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
5104 	if (map_is_ringbuf(map))
5105 		map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
5106 
5107 	return 0;
5108 }
5109 
5110 static int bpf_object_prepare_token(struct bpf_object *obj)
5111 {
5112 	const char *bpffs_path;
5113 	int bpffs_fd = -1, token_fd, err;
5114 	bool mandatory;
5115 	enum libbpf_print_level level;
5116 
5117 	/* token is explicitly prevented */
5118 	if (obj->token_path && obj->token_path[0] == '\0') {
5119 		pr_debug("object '%s': token is prevented, skipping...\n", obj->name);
5120 		return 0;
5121 	}
5122 
5123 	mandatory = obj->token_path != NULL;
5124 	level = mandatory ? LIBBPF_WARN : LIBBPF_DEBUG;
5125 
5126 	bpffs_path = obj->token_path ?: BPF_FS_DEFAULT_PATH;
5127 	bpffs_fd = open(bpffs_path, O_DIRECTORY, O_RDWR);
5128 	if (bpffs_fd < 0) {
5129 		err = -errno;
5130 		__pr(level, "object '%s': failed (%s) to open BPF FS mount at '%s'%s\n",
5131 		     obj->name, errstr(err), bpffs_path,
5132 		     mandatory ? "" : ", skipping optional step...");
5133 		return mandatory ? err : 0;
5134 	}
5135 
5136 	token_fd = bpf_token_create(bpffs_fd, 0);
5137 	close(bpffs_fd);
5138 	if (token_fd < 0) {
5139 		if (!mandatory && token_fd == -ENOENT) {
5140 			pr_debug("object '%s': BPF FS at '%s' doesn't have BPF token delegation set up, skipping...\n",
5141 				 obj->name, bpffs_path);
5142 			return 0;
5143 		}
5144 		__pr(level, "object '%s': failed (%d) to create BPF token from '%s'%s\n",
5145 		     obj->name, token_fd, bpffs_path,
5146 		     mandatory ? "" : ", skipping optional step...");
5147 		return mandatory ? token_fd : 0;
5148 	}
5149 
5150 	obj->feat_cache = calloc(1, sizeof(*obj->feat_cache));
5151 	if (!obj->feat_cache) {
5152 		close(token_fd);
5153 		return -ENOMEM;
5154 	}
5155 
5156 	obj->token_fd = token_fd;
5157 	obj->feat_cache->token_fd = token_fd;
5158 
5159 	return 0;
5160 }
5161 
5162 static int
5163 bpf_object__probe_loading(struct bpf_object *obj)
5164 {
5165 	struct bpf_insn insns[] = {
5166 		BPF_MOV64_IMM(BPF_REG_0, 0),
5167 		BPF_EXIT_INSN(),
5168 	};
5169 	int ret, insn_cnt = ARRAY_SIZE(insns);
5170 	LIBBPF_OPTS(bpf_prog_load_opts, opts,
5171 		.token_fd = obj->token_fd,
5172 		.prog_flags = obj->token_fd ? BPF_F_TOKEN_FD : 0,
5173 	);
5174 
5175 	if (obj->gen_loader)
5176 		return 0;
5177 
5178 	ret = bump_rlimit_memlock();
5179 	if (ret)
5180 		pr_warn("Failed to bump RLIMIT_MEMLOCK (err = %s), you might need to do it explicitly!\n",
5181 			errstr(ret));
5182 
5183 	/* make sure basic loading works */
5184 	ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, &opts);
5185 	if (ret < 0)
5186 		ret = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, &opts);
5187 	if (ret < 0) {
5188 		ret = errno;
5189 		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",
5190 			__func__, errstr(ret));
5191 		return -ret;
5192 	}
5193 	close(ret);
5194 
5195 	return 0;
5196 }
5197 
5198 bool kernel_supports(const struct bpf_object *obj, enum kern_feature_id feat_id)
5199 {
5200 	if (obj->gen_loader)
5201 		/* To generate loader program assume the latest kernel
5202 		 * to avoid doing extra prog_load, map_create syscalls.
5203 		 */
5204 		return true;
5205 
5206 	if (obj->feat_cache)
5207 		return feat_supported(obj->feat_cache, feat_id);
5208 
5209 	return feat_supported(NULL, feat_id);
5210 }
5211 
5212 /* Used in testing to simulate missing features. */
5213 void bpf_object_set_feat_cache(struct bpf_object *obj, struct kern_feature_cache *cache)
5214 {
5215 	if (obj->feat_cache)
5216 		free(obj->feat_cache);
5217 	obj->feat_cache = cache;
5218 }
5219 
5220 static bool map_is_reuse_compat(const struct bpf_map *map, int map_fd)
5221 {
5222 	struct bpf_map_info map_info;
5223 	__u32 map_info_len = sizeof(map_info);
5224 	int err;
5225 
5226 	memset(&map_info, 0, map_info_len);
5227 	err = bpf_map_get_info_by_fd(map_fd, &map_info, &map_info_len);
5228 	if (err && errno == EINVAL)
5229 		err = bpf_get_map_info_from_fdinfo(map_fd, &map_info);
5230 	if (err) {
5231 		pr_warn("failed to get map info for map FD %d: %s\n", map_fd,
5232 			errstr(err));
5233 		return false;
5234 	}
5235 
5236 	/*
5237 	 * bpf_get_map_info_by_fd() for DEVMAP will always return flags with
5238 	 * BPF_F_RDONLY_PROG set, but it generally is not set at map creation time.
5239 	 * Thus, ignore the BPF_F_RDONLY_PROG flag in the flags returned from
5240 	 * bpf_get_map_info_by_fd() when checking for compatibility with an
5241 	 * existing DEVMAP.
5242 	 */
5243 	if (map->def.type == BPF_MAP_TYPE_DEVMAP || map->def.type == BPF_MAP_TYPE_DEVMAP_HASH)
5244 		map_info.map_flags &= ~BPF_F_RDONLY_PROG;
5245 
5246 	return (map_info.type == map->def.type &&
5247 		map_info.key_size == map->def.key_size &&
5248 		map_info.value_size == map->def.value_size &&
5249 		map_info.max_entries == map->def.max_entries &&
5250 		map_info.map_flags == map->def.map_flags &&
5251 		map_info.map_extra == map->map_extra);
5252 }
5253 
5254 static int
5255 bpf_object__reuse_map(struct bpf_map *map)
5256 {
5257 	int err, pin_fd;
5258 
5259 	pin_fd = bpf_obj_get(map->pin_path);
5260 	if (pin_fd < 0) {
5261 		err = -errno;
5262 		if (err == -ENOENT) {
5263 			pr_debug("found no pinned map to reuse at '%s'\n",
5264 				 map->pin_path);
5265 			return 0;
5266 		}
5267 
5268 		pr_warn("couldn't retrieve pinned map '%s': %s\n",
5269 			map->pin_path, errstr(err));
5270 		return err;
5271 	}
5272 
5273 	if (!map_is_reuse_compat(map, pin_fd)) {
5274 		pr_warn("couldn't reuse pinned map at '%s': parameter mismatch\n",
5275 			map->pin_path);
5276 		close(pin_fd);
5277 		return -EINVAL;
5278 	}
5279 
5280 	err = bpf_map__reuse_fd(map, pin_fd);
5281 	close(pin_fd);
5282 	if (err)
5283 		return err;
5284 
5285 	map->pinned = true;
5286 	pr_debug("reused pinned map at '%s'\n", map->pin_path);
5287 
5288 	return 0;
5289 }
5290 
5291 static int
5292 bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
5293 {
5294 	enum libbpf_map_type map_type = map->libbpf_type;
5295 	int err, zero = 0;
5296 	size_t mmap_sz;
5297 
5298 	if (obj->gen_loader) {
5299 		bpf_gen__map_update_elem(obj->gen_loader, map - obj->maps,
5300 					 map->mmaped, map->def.value_size);
5301 		if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG)
5302 			bpf_gen__map_freeze(obj->gen_loader, map - obj->maps);
5303 		return 0;
5304 	}
5305 
5306 	err = bpf_map_update_elem(map->fd, &zero, map->mmaped, 0);
5307 	if (err) {
5308 		err = -errno;
5309 		pr_warn("map '%s': failed to set initial contents: %s\n",
5310 			bpf_map__name(map), errstr(err));
5311 		return err;
5312 	}
5313 
5314 	/* Freeze .rodata and .kconfig map as read-only from syscall side. */
5315 	if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG) {
5316 		err = bpf_map_freeze(map->fd);
5317 		if (err) {
5318 			err = -errno;
5319 			pr_warn("map '%s': failed to freeze as read-only: %s\n",
5320 				bpf_map__name(map), errstr(err));
5321 			return err;
5322 		}
5323 	}
5324 
5325 	/* Remap anonymous mmap()-ed "map initialization image" as
5326 	 * a BPF map-backed mmap()-ed memory, but preserving the same
5327 	 * memory address. This will cause kernel to change process'
5328 	 * page table to point to a different piece of kernel memory,
5329 	 * but from userspace point of view memory address (and its
5330 	 * contents, being identical at this point) will stay the
5331 	 * same. This mapping will be released by bpf_object__close()
5332 	 * as per normal clean up procedure.
5333 	 */
5334 	mmap_sz = bpf_map_mmap_sz(map);
5335 	if (map->def.map_flags & BPF_F_MMAPABLE) {
5336 		void *mmaped;
5337 		int prot;
5338 
5339 		if (map->def.map_flags & BPF_F_RDONLY_PROG)
5340 			prot = PROT_READ;
5341 		else
5342 			prot = PROT_READ | PROT_WRITE;
5343 		mmaped = mmap(map->mmaped, mmap_sz, prot, MAP_SHARED | MAP_FIXED, map->fd, 0);
5344 		if (mmaped == MAP_FAILED) {
5345 			err = -errno;
5346 			pr_warn("map '%s': failed to re-mmap() contents: %s\n",
5347 				bpf_map__name(map), errstr(err));
5348 			return err;
5349 		}
5350 		map->mmaped = mmaped;
5351 	} else if (map->mmaped) {
5352 		munmap(map->mmaped, mmap_sz);
5353 		map->mmaped = NULL;
5354 	}
5355 
5356 	return 0;
5357 }
5358 
5359 static void bpf_map__destroy(struct bpf_map *map);
5360 
5361 static int bpf_object__create_map(struct bpf_object *obj, struct bpf_map *map, bool is_inner)
5362 {
5363 	LIBBPF_OPTS(bpf_map_create_opts, create_attr);
5364 	struct bpf_map_def *def = &map->def;
5365 	const char *map_name = NULL;
5366 	int err = 0, map_fd;
5367 
5368 	if (kernel_supports(obj, FEAT_PROG_NAME))
5369 		map_name = map->name;
5370 	create_attr.map_ifindex = map->map_ifindex;
5371 	create_attr.map_flags = def->map_flags;
5372 	create_attr.numa_node = map->numa_node;
5373 	create_attr.map_extra = map->map_extra;
5374 	create_attr.token_fd = obj->token_fd;
5375 	if (obj->token_fd)
5376 		create_attr.map_flags |= BPF_F_TOKEN_FD;
5377 	if (map->excl_prog) {
5378 		err = bpf_prog_compute_hash(map->excl_prog);
5379 		if (err)
5380 			return err;
5381 
5382 		create_attr.excl_prog_hash = map->excl_prog->hash;
5383 		create_attr.excl_prog_hash_size = SHA256_DIGEST_LENGTH;
5384 	}
5385 
5386 	if (bpf_map__is_struct_ops(map)) {
5387 		create_attr.btf_vmlinux_value_type_id = map->btf_vmlinux_value_type_id;
5388 		if (map->mod_btf_fd >= 0) {
5389 			create_attr.value_type_btf_obj_fd = map->mod_btf_fd;
5390 			create_attr.map_flags |= BPF_F_VTYPE_BTF_OBJ_FD;
5391 		}
5392 	}
5393 
5394 	if (obj->btf && btf__fd(obj->btf) >= 0) {
5395 		create_attr.btf_fd = btf__fd(obj->btf);
5396 		create_attr.btf_key_type_id = map->btf_key_type_id;
5397 		create_attr.btf_value_type_id = map->btf_value_type_id;
5398 	}
5399 
5400 	if (bpf_map_type__is_map_in_map(def->type)) {
5401 		if (map->inner_map) {
5402 			err = map_set_def_max_entries(map->inner_map);
5403 			if (err)
5404 				return err;
5405 			err = bpf_object__create_map(obj, map->inner_map, true);
5406 			if (err) {
5407 				pr_warn("map '%s': failed to create inner map: %s\n",
5408 					map->name, errstr(err));
5409 				return err;
5410 			}
5411 			map->inner_map_fd = map->inner_map->fd;
5412 		}
5413 		if (map->inner_map_fd >= 0)
5414 			create_attr.inner_map_fd = map->inner_map_fd;
5415 	}
5416 
5417 	switch (def->type) {
5418 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
5419 	case BPF_MAP_TYPE_CGROUP_ARRAY:
5420 	case BPF_MAP_TYPE_STACK_TRACE:
5421 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
5422 	case BPF_MAP_TYPE_HASH_OF_MAPS:
5423 	case BPF_MAP_TYPE_DEVMAP:
5424 	case BPF_MAP_TYPE_DEVMAP_HASH:
5425 	case BPF_MAP_TYPE_CPUMAP:
5426 	case BPF_MAP_TYPE_XSKMAP:
5427 	case BPF_MAP_TYPE_SOCKMAP:
5428 	case BPF_MAP_TYPE_SOCKHASH:
5429 	case BPF_MAP_TYPE_QUEUE:
5430 	case BPF_MAP_TYPE_STACK:
5431 	case BPF_MAP_TYPE_ARENA:
5432 		create_attr.btf_fd = 0;
5433 		create_attr.btf_key_type_id = 0;
5434 		create_attr.btf_value_type_id = 0;
5435 		map->btf_key_type_id = 0;
5436 		map->btf_value_type_id = 0;
5437 		break;
5438 	case BPF_MAP_TYPE_STRUCT_OPS:
5439 		create_attr.btf_value_type_id = 0;
5440 		break;
5441 	default:
5442 		break;
5443 	}
5444 
5445 	if (obj->gen_loader) {
5446 		bpf_gen__map_create(obj->gen_loader, def->type, map_name,
5447 				    def->key_size, def->value_size, def->max_entries,
5448 				    &create_attr, is_inner ? -1 : map - obj->maps);
5449 		/* We keep pretenting we have valid FD to pass various fd >= 0
5450 		 * checks by just keeping original placeholder FDs in place.
5451 		 * See bpf_object__add_map() comment.
5452 		 * This placeholder fd will not be used with any syscall and
5453 		 * will be reset to -1 eventually.
5454 		 */
5455 		map_fd = map->fd;
5456 	} else {
5457 		map_fd = bpf_map_create(def->type, map_name,
5458 					def->key_size, def->value_size,
5459 					def->max_entries, &create_attr);
5460 	}
5461 	if (map_fd < 0 && (create_attr.btf_key_type_id || create_attr.btf_value_type_id)) {
5462 		err = -errno;
5463 		pr_warn("Error in bpf_create_map_xattr(%s): %s. Retrying without BTF.\n",
5464 			map->name, errstr(err));
5465 		create_attr.btf_fd = 0;
5466 		create_attr.btf_key_type_id = 0;
5467 		create_attr.btf_value_type_id = 0;
5468 		map->btf_key_type_id = 0;
5469 		map->btf_value_type_id = 0;
5470 		map_fd = bpf_map_create(def->type, map_name,
5471 					def->key_size, def->value_size,
5472 					def->max_entries, &create_attr);
5473 	}
5474 
5475 	if (bpf_map_type__is_map_in_map(def->type) && map->inner_map) {
5476 		if (obj->gen_loader)
5477 			map->inner_map->fd = -1;
5478 		bpf_map__destroy(map->inner_map);
5479 		zfree(&map->inner_map);
5480 	}
5481 
5482 	if (map_fd < 0)
5483 		return map_fd;
5484 
5485 	/* obj->gen_loader case, prevent reuse_fd() from closing map_fd */
5486 	if (map->fd == map_fd)
5487 		return 0;
5488 
5489 	/* Keep placeholder FD value but now point it to the BPF map object.
5490 	 * This way everything that relied on this map's FD (e.g., relocated
5491 	 * ldimm64 instructions) will stay valid and won't need adjustments.
5492 	 * map->fd stays valid but now point to what map_fd points to.
5493 	 */
5494 	return reuse_fd(map->fd, map_fd);
5495 }
5496 
5497 static int init_map_in_map_slots(struct bpf_object *obj, struct bpf_map *map)
5498 {
5499 	const struct bpf_map *targ_map;
5500 	unsigned int i;
5501 	int fd, err = 0;
5502 
5503 	for (i = 0; i < map->init_slots_sz; i++) {
5504 		if (!map->init_slots[i])
5505 			continue;
5506 
5507 		targ_map = map->init_slots[i];
5508 		fd = targ_map->fd;
5509 
5510 		if (obj->gen_loader) {
5511 			bpf_gen__populate_outer_map(obj->gen_loader,
5512 						    map - obj->maps, i,
5513 						    targ_map - obj->maps);
5514 		} else {
5515 			err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5516 		}
5517 		if (err) {
5518 			err = -errno;
5519 			pr_warn("map '%s': failed to initialize slot [%d] to map '%s' fd=%d: %s\n",
5520 				map->name, i, targ_map->name, fd, errstr(err));
5521 			return err;
5522 		}
5523 		pr_debug("map '%s': slot [%d] set to map '%s' fd=%d\n",
5524 			 map->name, i, targ_map->name, fd);
5525 	}
5526 
5527 	zfree(&map->init_slots);
5528 	map->init_slots_sz = 0;
5529 
5530 	return 0;
5531 }
5532 
5533 static int init_prog_array_slots(struct bpf_object *obj, struct bpf_map *map)
5534 {
5535 	const struct bpf_program *targ_prog;
5536 	unsigned int i;
5537 	int fd, err;
5538 
5539 	if (obj->gen_loader)
5540 		return -ENOTSUP;
5541 
5542 	for (i = 0; i < map->init_slots_sz; i++) {
5543 		if (!map->init_slots[i])
5544 			continue;
5545 
5546 		targ_prog = map->init_slots[i];
5547 		fd = bpf_program__fd(targ_prog);
5548 
5549 		err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5550 		if (err) {
5551 			err = -errno;
5552 			pr_warn("map '%s': failed to initialize slot [%d] to prog '%s' fd=%d: %s\n",
5553 				map->name, i, targ_prog->name, fd, errstr(err));
5554 			return err;
5555 		}
5556 		pr_debug("map '%s': slot [%d] set to prog '%s' fd=%d\n",
5557 			 map->name, i, targ_prog->name, fd);
5558 	}
5559 
5560 	zfree(&map->init_slots);
5561 	map->init_slots_sz = 0;
5562 
5563 	return 0;
5564 }
5565 
5566 static int bpf_object_init_prog_arrays(struct bpf_object *obj)
5567 {
5568 	struct bpf_map *map;
5569 	int i, err;
5570 
5571 	for (i = 0; i < obj->nr_maps; i++) {
5572 		map = &obj->maps[i];
5573 
5574 		if (!map->init_slots_sz || map->def.type != BPF_MAP_TYPE_PROG_ARRAY)
5575 			continue;
5576 
5577 		err = init_prog_array_slots(obj, map);
5578 		if (err < 0)
5579 			return err;
5580 	}
5581 	return 0;
5582 }
5583 
5584 static int map_set_def_max_entries(struct bpf_map *map)
5585 {
5586 	if (map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY && !map->def.max_entries) {
5587 		int nr_cpus;
5588 
5589 		nr_cpus = libbpf_num_possible_cpus();
5590 		if (nr_cpus < 0) {
5591 			pr_warn("map '%s': failed to determine number of system CPUs: %d\n",
5592 				map->name, nr_cpus);
5593 			return nr_cpus;
5594 		}
5595 		pr_debug("map '%s': setting size to %d\n", map->name, nr_cpus);
5596 		map->def.max_entries = nr_cpus;
5597 	}
5598 
5599 	return 0;
5600 }
5601 
5602 static int
5603 bpf_object__create_maps(struct bpf_object *obj)
5604 {
5605 	struct bpf_map *map;
5606 	unsigned int i, j;
5607 	int err;
5608 	bool retried;
5609 
5610 	for (i = 0; i < obj->nr_maps; i++) {
5611 		map = &obj->maps[i];
5612 
5613 		/* To support old kernels, we skip creating global data maps
5614 		 * (.rodata, .data, .kconfig, etc); later on, during program
5615 		 * loading, if we detect that at least one of the to-be-loaded
5616 		 * programs is referencing any global data map, we'll error
5617 		 * out with program name and relocation index logged.
5618 		 * This approach allows to accommodate Clang emitting
5619 		 * unnecessary .rodata.str1.1 sections for string literals,
5620 		 * but also it allows to have CO-RE applications that use
5621 		 * global variables in some of BPF programs, but not others.
5622 		 * If those global variable-using programs are not loaded at
5623 		 * runtime due to bpf_program__set_autoload(prog, false),
5624 		 * bpf_object loading will succeed just fine even on old
5625 		 * kernels.
5626 		 */
5627 		if (bpf_map__is_internal(map) && !kernel_supports(obj, FEAT_GLOBAL_DATA))
5628 			map->autocreate = false;
5629 
5630 		if (!map->autocreate) {
5631 			pr_debug("map '%s': skipped auto-creating...\n", map->name);
5632 			continue;
5633 		}
5634 
5635 		err = map_set_def_max_entries(map);
5636 		if (err)
5637 			goto err_out;
5638 
5639 		retried = false;
5640 retry:
5641 		if (map->pin_path) {
5642 			err = bpf_object__reuse_map(map);
5643 			if (err) {
5644 				pr_warn("map '%s': error reusing pinned map\n",
5645 					map->name);
5646 				goto err_out;
5647 			}
5648 			if (retried && map->fd < 0) {
5649 				pr_warn("map '%s': cannot find pinned map\n",
5650 					map->name);
5651 				err = -ENOENT;
5652 				goto err_out;
5653 			}
5654 		}
5655 
5656 		if (map->reused) {
5657 			pr_debug("map '%s': skipping creation (preset fd=%d)\n",
5658 				 map->name, map->fd);
5659 		} else {
5660 			err = bpf_object__create_map(obj, map, false);
5661 			if (err)
5662 				goto err_out;
5663 
5664 			pr_debug("map '%s': created successfully, fd=%d\n",
5665 				 map->name, map->fd);
5666 
5667 			if (bpf_map__is_internal(map)) {
5668 				err = bpf_object__populate_internal_map(obj, map);
5669 				if (err < 0)
5670 					goto err_out;
5671 			} else if (map->def.type == BPF_MAP_TYPE_ARENA) {
5672 				map->mmaped = mmap((void *)(long)map->map_extra,
5673 						   bpf_map_mmap_sz(map), PROT_READ | PROT_WRITE,
5674 						   map->map_extra ? MAP_SHARED | MAP_FIXED : MAP_SHARED,
5675 						   map->fd, 0);
5676 				if (map->mmaped == MAP_FAILED) {
5677 					err = -errno;
5678 					map->mmaped = NULL;
5679 					pr_warn("map '%s': failed to mmap arena: %s\n",
5680 						map->name, errstr(err));
5681 					return err;
5682 				}
5683 				if (obj->arena_data) {
5684 					memcpy(map->mmaped + obj->arena_data_off, obj->arena_data,
5685 						obj->arena_data_sz);
5686 					zfree(&obj->arena_data);
5687 				}
5688 			}
5689 			if (map->init_slots_sz && map->def.type != BPF_MAP_TYPE_PROG_ARRAY) {
5690 				err = init_map_in_map_slots(obj, map);
5691 				if (err < 0)
5692 					goto err_out;
5693 			}
5694 		}
5695 
5696 		if (map->pin_path && !map->pinned) {
5697 			err = bpf_map__pin(map, NULL);
5698 			if (err) {
5699 				if (!retried && err == -EEXIST) {
5700 					retried = true;
5701 					goto retry;
5702 				}
5703 				pr_warn("map '%s': failed to auto-pin at '%s': %s\n",
5704 					map->name, map->pin_path, errstr(err));
5705 				goto err_out;
5706 			}
5707 		}
5708 	}
5709 
5710 	return 0;
5711 
5712 err_out:
5713 	pr_warn("map '%s': failed to create: %s\n", map->name, errstr(err));
5714 	pr_perm_msg(err);
5715 	for (j = 0; j < i; j++)
5716 		zclose(obj->maps[j].fd);
5717 	return err;
5718 }
5719 
5720 static bool bpf_core_is_flavor_sep(const char *s)
5721 {
5722 	/* check X___Y name pattern, where X and Y are not underscores */
5723 	return s[0] != '_' &&				      /* X */
5724 	       s[1] == '_' && s[2] == '_' && s[3] == '_' &&   /* ___ */
5725 	       s[4] != '_';				      /* Y */
5726 }
5727 
5728 /* Given 'some_struct_name___with_flavor' return the length of a name prefix
5729  * before last triple underscore. Struct name part after last triple
5730  * underscore is ignored by BPF CO-RE relocation during relocation matching.
5731  */
5732 size_t bpf_core_essential_name_len(const char *name)
5733 {
5734 	size_t n = strlen(name);
5735 	int i;
5736 
5737 	for (i = n - 5; i >= 0; i--) {
5738 		if (bpf_core_is_flavor_sep(name + i))
5739 			return i + 1;
5740 	}
5741 	return n;
5742 }
5743 
5744 void bpf_core_free_cands(struct bpf_core_cand_list *cands)
5745 {
5746 	if (!cands)
5747 		return;
5748 
5749 	free(cands->cands);
5750 	free(cands);
5751 }
5752 
5753 int bpf_core_add_cands(struct bpf_core_cand *local_cand,
5754 		       size_t local_essent_len,
5755 		       const struct btf *targ_btf,
5756 		       const char *targ_btf_name,
5757 		       int targ_start_id,
5758 		       struct bpf_core_cand_list *cands)
5759 {
5760 	struct bpf_core_cand *new_cands, *cand;
5761 	const struct btf_type *t, *local_t;
5762 	const char *targ_name, *local_name;
5763 	size_t targ_essent_len;
5764 	int n, i;
5765 
5766 	local_t = btf__type_by_id(local_cand->btf, local_cand->id);
5767 	local_name = btf__str_by_offset(local_cand->btf, local_t->name_off);
5768 
5769 	n = btf__type_cnt(targ_btf);
5770 	for (i = targ_start_id; i < n; i++) {
5771 		t = btf__type_by_id(targ_btf, i);
5772 		if (!btf_kind_core_compat(t, local_t))
5773 			continue;
5774 
5775 		targ_name = btf__name_by_offset(targ_btf, t->name_off);
5776 		if (str_is_empty(targ_name))
5777 			continue;
5778 
5779 		targ_essent_len = bpf_core_essential_name_len(targ_name);
5780 		if (targ_essent_len != local_essent_len)
5781 			continue;
5782 
5783 		if (strncmp(local_name, targ_name, local_essent_len) != 0)
5784 			continue;
5785 
5786 		pr_debug("CO-RE relocating [%d] %s %s: found target candidate [%d] %s %s in [%s]\n",
5787 			 local_cand->id, btf_kind_str(local_t),
5788 			 local_name, i, btf_kind_str(t), targ_name,
5789 			 targ_btf_name);
5790 		new_cands = libbpf_reallocarray(cands->cands, cands->len + 1,
5791 					      sizeof(*cands->cands));
5792 		if (!new_cands)
5793 			return -ENOMEM;
5794 
5795 		cand = &new_cands[cands->len];
5796 		cand->btf = targ_btf;
5797 		cand->id = i;
5798 
5799 		cands->cands = new_cands;
5800 		cands->len++;
5801 	}
5802 	return 0;
5803 }
5804 
5805 static int load_module_btfs(struct bpf_object *obj)
5806 {
5807 	struct bpf_btf_info info;
5808 	struct module_btf *mod_btf;
5809 	struct btf *btf;
5810 	char name[64];
5811 	__u32 id = 0, len;
5812 	int err, fd;
5813 
5814 	if (obj->btf_modules_loaded)
5815 		return 0;
5816 
5817 	if (obj->gen_loader)
5818 		return 0;
5819 
5820 	/* don't do this again, even if we find no module BTFs */
5821 	obj->btf_modules_loaded = true;
5822 
5823 	/* kernel too old to support module BTFs */
5824 	if (!kernel_supports(obj, FEAT_MODULE_BTF))
5825 		return 0;
5826 
5827 	while (true) {
5828 		err = bpf_btf_get_next_id(id, &id);
5829 		if (err && errno == ENOENT)
5830 			return 0;
5831 		if (err && errno == EPERM) {
5832 			pr_debug("skipping module BTFs loading, missing privileges\n");
5833 			return 0;
5834 		}
5835 		if (err) {
5836 			err = -errno;
5837 			pr_warn("failed to iterate BTF objects: %s\n", errstr(err));
5838 			return err;
5839 		}
5840 
5841 		fd = bpf_btf_get_fd_by_id(id);
5842 		if (fd < 0) {
5843 			if (errno == ENOENT)
5844 				continue; /* expected race: BTF was unloaded */
5845 			err = -errno;
5846 			pr_warn("failed to get BTF object #%d FD: %s\n", id, errstr(err));
5847 			return err;
5848 		}
5849 
5850 		len = sizeof(info);
5851 		memset(&info, 0, sizeof(info));
5852 		info.name = ptr_to_u64(name);
5853 		info.name_len = sizeof(name);
5854 
5855 		btf = NULL;
5856 		err = bpf_btf_get_info_by_fd(fd, &info, &len);
5857 		if (err) {
5858 			err = -errno;
5859 			pr_warn("failed to get BTF object #%d info: %s\n", id, errstr(err));
5860 			break;
5861 		}
5862 
5863 		/* ignore non-module BTFs */
5864 		if (!info.kernel_btf || strcmp(name, "vmlinux") == 0) {
5865 			close(fd);
5866 			continue;
5867 		}
5868 
5869 		btf = btf_get_from_fd(fd, obj->btf_vmlinux);
5870 		err = libbpf_get_error(btf);
5871 		if (err) {
5872 			pr_warn("failed to load module [%s]'s BTF object #%d: %s\n",
5873 				name, id, errstr(err));
5874 			break;
5875 		}
5876 
5877 		err = libbpf_ensure_mem((void **)&obj->btf_modules, &obj->btf_module_cap,
5878 					sizeof(*obj->btf_modules), obj->btf_module_cnt + 1);
5879 		if (err)
5880 			break;
5881 
5882 		mod_btf = &obj->btf_modules[obj->btf_module_cnt];
5883 
5884 		mod_btf->btf = btf;
5885 		mod_btf->id = id;
5886 		mod_btf->fd = fd;
5887 		mod_btf->name = strdup(name);
5888 		if (!mod_btf->name) {
5889 			err = -ENOMEM;
5890 			break;
5891 		}
5892 		obj->btf_module_cnt++;
5893 	}
5894 
5895 	if (err) {
5896 		btf__free(btf);
5897 		close(fd);
5898 	}
5899 	return err;
5900 }
5901 
5902 static struct bpf_core_cand_list *
5903 bpf_core_find_cands(struct bpf_object *obj, const struct btf *local_btf, __u32 local_type_id)
5904 {
5905 	struct bpf_core_cand local_cand = {};
5906 	struct bpf_core_cand_list *cands;
5907 	const struct btf *main_btf;
5908 	const struct btf_type *local_t;
5909 	const char *local_name;
5910 	size_t local_essent_len;
5911 	int err, i;
5912 
5913 	local_cand.btf = local_btf;
5914 	local_cand.id = local_type_id;
5915 	local_t = btf__type_by_id(local_btf, local_type_id);
5916 	if (!local_t)
5917 		return ERR_PTR(-EINVAL);
5918 
5919 	local_name = btf__name_by_offset(local_btf, local_t->name_off);
5920 	if (str_is_empty(local_name))
5921 		return ERR_PTR(-EINVAL);
5922 	local_essent_len = bpf_core_essential_name_len(local_name);
5923 
5924 	cands = calloc(1, sizeof(*cands));
5925 	if (!cands)
5926 		return ERR_PTR(-ENOMEM);
5927 
5928 	/* Attempt to find target candidates in vmlinux BTF first */
5929 	main_btf = obj->btf_vmlinux_override ?: obj->btf_vmlinux;
5930 	err = bpf_core_add_cands(&local_cand, local_essent_len, main_btf, "vmlinux", 1, cands);
5931 	if (err)
5932 		goto err_out;
5933 
5934 	/* if vmlinux BTF has any candidate, don't got for module BTFs */
5935 	if (cands->len)
5936 		return cands;
5937 
5938 	/* if vmlinux BTF was overridden, don't attempt to load module BTFs */
5939 	if (obj->btf_vmlinux_override)
5940 		return cands;
5941 
5942 	/* now look through module BTFs, trying to still find candidates */
5943 	err = load_module_btfs(obj);
5944 	if (err)
5945 		goto err_out;
5946 
5947 	for (i = 0; i < obj->btf_module_cnt; i++) {
5948 		err = bpf_core_add_cands(&local_cand, local_essent_len,
5949 					 obj->btf_modules[i].btf,
5950 					 obj->btf_modules[i].name,
5951 					 btf__type_cnt(obj->btf_vmlinux),
5952 					 cands);
5953 		if (err)
5954 			goto err_out;
5955 	}
5956 
5957 	return cands;
5958 err_out:
5959 	bpf_core_free_cands(cands);
5960 	return ERR_PTR(err);
5961 }
5962 
5963 /* Check local and target types for compatibility. This check is used for
5964  * type-based CO-RE relocations and follow slightly different rules than
5965  * field-based relocations. This function assumes that root types were already
5966  * checked for name match. Beyond that initial root-level name check, names
5967  * are completely ignored. Compatibility rules are as follows:
5968  *   - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs are considered compatible, but
5969  *     kind should match for local and target types (i.e., STRUCT is not
5970  *     compatible with UNION);
5971  *   - for ENUMs, the size is ignored;
5972  *   - for INT, size and signedness are ignored;
5973  *   - for ARRAY, dimensionality is ignored, element types are checked for
5974  *     compatibility recursively;
5975  *   - CONST/VOLATILE/RESTRICT modifiers are ignored;
5976  *   - TYPEDEFs/PTRs are compatible if types they pointing to are compatible;
5977  *   - FUNC_PROTOs are compatible if they have compatible signature: same
5978  *     number of input args and compatible return and argument types.
5979  * These rules are not set in stone and probably will be adjusted as we get
5980  * more experience with using BPF CO-RE relocations.
5981  */
5982 int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
5983 			      const struct btf *targ_btf, __u32 targ_id)
5984 {
5985 	return __bpf_core_types_are_compat(local_btf, local_id, targ_btf, targ_id, 32);
5986 }
5987 
5988 int bpf_core_types_match(const struct btf *local_btf, __u32 local_id,
5989 			 const struct btf *targ_btf, __u32 targ_id)
5990 {
5991 	return __bpf_core_types_match(local_btf, local_id, targ_btf, targ_id, false, 32);
5992 }
5993 
5994 static size_t bpf_core_hash_fn(const long key, void *ctx)
5995 {
5996 	return key;
5997 }
5998 
5999 static bool bpf_core_equal_fn(const long k1, const long k2, void *ctx)
6000 {
6001 	return k1 == k2;
6002 }
6003 
6004 static int record_relo_core(struct bpf_program *prog,
6005 			    const struct bpf_core_relo *core_relo, int insn_idx)
6006 {
6007 	struct reloc_desc *relos, *relo;
6008 
6009 	relos = libbpf_reallocarray(prog->reloc_desc,
6010 				    prog->nr_reloc + 1, sizeof(*relos));
6011 	if (!relos)
6012 		return -ENOMEM;
6013 	relo = &relos[prog->nr_reloc];
6014 	relo->type = RELO_CORE;
6015 	relo->insn_idx = insn_idx;
6016 	relo->core_relo = core_relo;
6017 	prog->reloc_desc = relos;
6018 	prog->nr_reloc++;
6019 	return 0;
6020 }
6021 
6022 static const struct bpf_core_relo *find_relo_core(struct bpf_program *prog, int insn_idx)
6023 {
6024 	struct reloc_desc *relo;
6025 	int i;
6026 
6027 	for (i = 0; i < prog->nr_reloc; i++) {
6028 		relo = &prog->reloc_desc[i];
6029 		if (relo->type != RELO_CORE || relo->insn_idx != insn_idx)
6030 			continue;
6031 
6032 		return relo->core_relo;
6033 	}
6034 
6035 	return NULL;
6036 }
6037 
6038 static int bpf_core_resolve_relo(struct bpf_program *prog,
6039 				 const struct bpf_core_relo *relo,
6040 				 int relo_idx,
6041 				 const struct btf *local_btf,
6042 				 struct hashmap *cand_cache,
6043 				 struct bpf_core_relo_res *targ_res)
6044 {
6045 	struct bpf_core_spec specs_scratch[3] = {};
6046 	struct bpf_core_cand_list *cands = NULL;
6047 	const char *prog_name = prog->name;
6048 	const struct btf_type *local_type;
6049 	const char *local_name;
6050 	__u32 local_id = relo->type_id;
6051 	int err;
6052 
6053 	local_type = btf__type_by_id(local_btf, local_id);
6054 	if (!local_type)
6055 		return -EINVAL;
6056 
6057 	local_name = btf__name_by_offset(local_btf, local_type->name_off);
6058 	if (!local_name)
6059 		return -EINVAL;
6060 
6061 	if (relo->kind != BPF_CORE_TYPE_ID_LOCAL &&
6062 	    !hashmap__find(cand_cache, local_id, &cands)) {
6063 		cands = bpf_core_find_cands(prog->obj, local_btf, local_id);
6064 		if (IS_ERR(cands)) {
6065 			pr_warn("prog '%s': relo #%d: target candidate search failed for [%d] %s %s: %ld\n",
6066 				prog_name, relo_idx, local_id, btf_kind_str(local_type),
6067 				local_name, PTR_ERR(cands));
6068 			return PTR_ERR(cands);
6069 		}
6070 		err = hashmap__set(cand_cache, local_id, cands, NULL, NULL);
6071 		if (err) {
6072 			bpf_core_free_cands(cands);
6073 			return err;
6074 		}
6075 	}
6076 
6077 	return bpf_core_calc_relo_insn(prog_name, relo, relo_idx, local_btf, cands, specs_scratch,
6078 				       targ_res);
6079 }
6080 
6081 static int
6082 bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
6083 {
6084 	const struct btf_ext_info_sec *sec;
6085 	struct bpf_core_relo_res targ_res;
6086 	const struct bpf_core_relo *rec;
6087 	const struct btf_ext_info *seg;
6088 	struct hashmap_entry *entry;
6089 	struct hashmap *cand_cache = NULL;
6090 	struct bpf_program *prog;
6091 	struct bpf_insn *insn;
6092 	const char *sec_name;
6093 	int i, err = 0, insn_idx, sec_idx, sec_num;
6094 
6095 	if (obj->btf_ext->core_relo_info.len == 0)
6096 		return 0;
6097 
6098 	if (targ_btf_path) {
6099 		obj->btf_vmlinux_override = btf__parse(targ_btf_path, NULL);
6100 		err = libbpf_get_error(obj->btf_vmlinux_override);
6101 		if (err) {
6102 			pr_warn("failed to parse target BTF: %s\n", errstr(err));
6103 			return err;
6104 		}
6105 	}
6106 
6107 	cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
6108 	if (IS_ERR(cand_cache)) {
6109 		err = PTR_ERR(cand_cache);
6110 		goto out;
6111 	}
6112 
6113 	seg = &obj->btf_ext->core_relo_info;
6114 	sec_num = 0;
6115 	for_each_btf_ext_sec(seg, sec) {
6116 		sec_idx = seg->sec_idxs[sec_num];
6117 		sec_num++;
6118 
6119 		sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
6120 		if (str_is_empty(sec_name)) {
6121 			err = -EINVAL;
6122 			goto out;
6123 		}
6124 
6125 		pr_debug("sec '%s': found %d CO-RE relocations\n", sec_name, sec->num_info);
6126 
6127 		for_each_btf_ext_rec(seg, sec, i, rec) {
6128 			if (rec->insn_off % BPF_INSN_SZ)
6129 				return -EINVAL;
6130 			insn_idx = rec->insn_off / BPF_INSN_SZ;
6131 			prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
6132 			if (!prog) {
6133 				/* When __weak subprog is "overridden" by another instance
6134 				 * of the subprog from a different object file, linker still
6135 				 * appends all the .BTF.ext info that used to belong to that
6136 				 * eliminated subprogram.
6137 				 * This is similar to what x86-64 linker does for relocations.
6138 				 * So just ignore such relocations just like we ignore
6139 				 * subprog instructions when discovering subprograms.
6140 				 */
6141 				pr_debug("sec '%s': skipping CO-RE relocation #%d for insn #%d belonging to eliminated weak subprogram\n",
6142 					 sec_name, i, insn_idx);
6143 				continue;
6144 			}
6145 			/* no need to apply CO-RE relocation if the program is
6146 			 * not going to be loaded
6147 			 */
6148 			if (!prog->autoload)
6149 				continue;
6150 
6151 			/* adjust insn_idx from section frame of reference to the local
6152 			 * program's frame of reference; (sub-)program code is not yet
6153 			 * relocated, so it's enough to just subtract in-section offset
6154 			 */
6155 			insn_idx = insn_idx - prog->sec_insn_off;
6156 			if (insn_idx >= prog->insns_cnt)
6157 				return -EINVAL;
6158 			insn = &prog->insns[insn_idx];
6159 
6160 			err = record_relo_core(prog, rec, insn_idx);
6161 			if (err) {
6162 				pr_warn("prog '%s': relo #%d: failed to record relocation: %s\n",
6163 					prog->name, i, errstr(err));
6164 				goto out;
6165 			}
6166 
6167 			if (prog->obj->gen_loader)
6168 				continue;
6169 
6170 			err = bpf_core_resolve_relo(prog, rec, i, obj->btf, cand_cache, &targ_res);
6171 			if (err) {
6172 				pr_warn("prog '%s': relo #%d: failed to relocate: %s\n",
6173 					prog->name, i, errstr(err));
6174 				goto out;
6175 			}
6176 
6177 			err = bpf_core_patch_insn(prog->name, insn, insn_idx, rec, i, &targ_res);
6178 			if (err) {
6179 				pr_warn("prog '%s': relo #%d: failed to patch insn #%u: %s\n",
6180 					prog->name, i, insn_idx, errstr(err));
6181 				goto out;
6182 			}
6183 		}
6184 	}
6185 
6186 out:
6187 	/* obj->btf_vmlinux and module BTFs are freed after object load */
6188 	btf__free(obj->btf_vmlinux_override);
6189 	obj->btf_vmlinux_override = NULL;
6190 
6191 	if (!IS_ERR_OR_NULL(cand_cache)) {
6192 		hashmap__for_each_entry(cand_cache, entry, i) {
6193 			bpf_core_free_cands(entry->pvalue);
6194 		}
6195 		hashmap__free(cand_cache);
6196 	}
6197 	return err;
6198 }
6199 
6200 /* base map load ldimm64 special constant, used also for log fixup logic */
6201 #define POISON_LDIMM64_MAP_BASE 2001000000
6202 #define POISON_LDIMM64_MAP_PFX "200100"
6203 
6204 static void poison_map_ldimm64(struct bpf_program *prog, int relo_idx,
6205 			       int insn_idx, struct bpf_insn *insn,
6206 			       int map_idx, const struct bpf_map *map)
6207 {
6208 	int i;
6209 
6210 	pr_debug("prog '%s': relo #%d: poisoning insn #%d that loads map #%d '%s'\n",
6211 		 prog->name, relo_idx, insn_idx, map_idx, map->name);
6212 
6213 	/* we turn single ldimm64 into two identical invalid calls */
6214 	for (i = 0; i < 2; i++) {
6215 		insn->code = BPF_JMP | BPF_CALL;
6216 		insn->dst_reg = 0;
6217 		insn->src_reg = 0;
6218 		insn->off = 0;
6219 		/* if this instruction is reachable (not a dead code),
6220 		 * verifier will complain with something like:
6221 		 * invalid func unknown#2001000123
6222 		 * where lower 123 is map index into obj->maps[] array
6223 		 */
6224 		insn->imm = POISON_LDIMM64_MAP_BASE + map_idx;
6225 
6226 		insn++;
6227 	}
6228 }
6229 
6230 /* unresolved kfunc call special constant, used also for log fixup logic */
6231 #define POISON_CALL_KFUNC_BASE 2002000000
6232 #define POISON_CALL_KFUNC_PFX "2002"
6233 
6234 static void poison_kfunc_call(struct bpf_program *prog, int relo_idx,
6235 			      int insn_idx, struct bpf_insn *insn,
6236 			      int ext_idx, const struct extern_desc *ext)
6237 {
6238 	pr_debug("prog '%s': relo #%d: poisoning insn #%d that calls kfunc '%s'\n",
6239 		 prog->name, relo_idx, insn_idx, ext->name);
6240 
6241 	/* we turn kfunc call into invalid helper call with identifiable constant */
6242 	insn->code = BPF_JMP | BPF_CALL;
6243 	insn->dst_reg = 0;
6244 	insn->src_reg = 0;
6245 	insn->off = 0;
6246 	/* if this instruction is reachable (not a dead code),
6247 	 * verifier will complain with something like:
6248 	 * invalid func unknown#2001000123
6249 	 * where lower 123 is extern index into obj->externs[] array
6250 	 */
6251 	insn->imm = POISON_CALL_KFUNC_BASE + ext_idx;
6252 }
6253 
6254 static int find_jt_map(struct bpf_object *obj, struct bpf_program *prog, unsigned int sym_off)
6255 {
6256 	size_t i;
6257 
6258 	for (i = 0; i < obj->jumptable_map_cnt; i++) {
6259 		/*
6260 		 * This might happen that same offset is used for two different
6261 		 * programs (as jump tables can be the same). However, for
6262 		 * different programs different maps should be created.
6263 		 */
6264 		if (obj->jumptable_maps[i].sym_off == sym_off &&
6265 		    obj->jumptable_maps[i].prog == prog)
6266 			return obj->jumptable_maps[i].fd;
6267 	}
6268 
6269 	return -ENOENT;
6270 }
6271 
6272 static int add_jt_map(struct bpf_object *obj, struct bpf_program *prog, unsigned int sym_off, int map_fd)
6273 {
6274 	size_t cnt = obj->jumptable_map_cnt;
6275 	size_t size = sizeof(obj->jumptable_maps[0]);
6276 	void *tmp;
6277 
6278 	tmp = libbpf_reallocarray(obj->jumptable_maps, cnt + 1, size);
6279 	if (!tmp)
6280 		return -ENOMEM;
6281 
6282 	obj->jumptable_maps = tmp;
6283 	obj->jumptable_maps[cnt].prog = prog;
6284 	obj->jumptable_maps[cnt].sym_off = sym_off;
6285 	obj->jumptable_maps[cnt].fd = map_fd;
6286 	obj->jumptable_map_cnt++;
6287 
6288 	return 0;
6289 }
6290 
6291 static int find_subprog_idx(struct bpf_program *prog, int insn_idx)
6292 {
6293 	int i;
6294 
6295 	for (i = prog->subprog_cnt - 1; i >= 0; i--) {
6296 		if (insn_idx >= prog->subprogs[i].sub_insn_off)
6297 			return i;
6298 	}
6299 
6300 	return -1;
6301 }
6302 
6303 static int create_jt_map(struct bpf_object *obj, struct bpf_program *prog, struct reloc_desc *relo)
6304 {
6305 	const __u32 jt_entry_size = 8;
6306 	unsigned int sym_off = relo->sym_off;
6307 	int jt_size = relo->sym_size;
6308 	__u32 max_entries = jt_size / jt_entry_size;
6309 	__u32 value_size = sizeof(struct bpf_insn_array_value);
6310 	struct bpf_insn_array_value val = {};
6311 	int subprog_idx;
6312 	int map_fd, err;
6313 	__u64 insn_off;
6314 	__u64 *jt;
6315 	__u32 i;
6316 
6317 	map_fd = find_jt_map(obj, prog, sym_off);
6318 	if (map_fd >= 0)
6319 		return map_fd;
6320 
6321 	if (sym_off % jt_entry_size) {
6322 		pr_warn("map '.jumptables': jumptable start %u should be multiple of %u\n",
6323 			sym_off, jt_entry_size);
6324 		return -EINVAL;
6325 	}
6326 
6327 	if (jt_size % jt_entry_size) {
6328 		pr_warn("map '.jumptables': jumptable size %d should be multiple of %u\n",
6329 			jt_size, jt_entry_size);
6330 		return -EINVAL;
6331 	}
6332 
6333 	map_fd = bpf_map_create(BPF_MAP_TYPE_INSN_ARRAY, ".jumptables",
6334 				4, value_size, max_entries, NULL);
6335 	if (map_fd < 0)
6336 		return map_fd;
6337 
6338 	if (!obj->jumptables_data) {
6339 		pr_warn("map '.jumptables': ELF file is missing jump table data\n");
6340 		err = -EINVAL;
6341 		goto err_close;
6342 	}
6343 	if (sym_off + jt_size > obj->jumptables_data_sz) {
6344 		pr_warn("map '.jumptables': jumptables_data size is %zd, trying to access %d\n",
6345 			obj->jumptables_data_sz, sym_off + jt_size);
6346 		err = -EINVAL;
6347 		goto err_close;
6348 	}
6349 
6350 	subprog_idx = -1; /* main program */
6351 	if (relo->insn_idx < 0 || relo->insn_idx >= prog->insns_cnt) {
6352 		pr_warn("map '.jumptables': invalid instruction index %d\n", relo->insn_idx);
6353 		err = -EINVAL;
6354 		goto err_close;
6355 	}
6356 	if (prog->subprogs)
6357 		subprog_idx = find_subprog_idx(prog, relo->insn_idx);
6358 
6359 	jt = (__u64 *)(obj->jumptables_data + sym_off);
6360 	for (i = 0; i < max_entries; i++) {
6361 		/*
6362 		 * The offset should be made to be relative to the beginning of
6363 		 * the main function, not the subfunction.
6364 		 */
6365 		insn_off = jt[i]/sizeof(struct bpf_insn);
6366 		if (subprog_idx >= 0) {
6367 			insn_off -= prog->subprogs[subprog_idx].sec_insn_off;
6368 			insn_off += prog->subprogs[subprog_idx].sub_insn_off;
6369 		} else {
6370 			insn_off -= prog->sec_insn_off;
6371 		}
6372 
6373 		/*
6374 		 * LLVM-generated jump tables contain u64 records, however
6375 		 * should contain values that fit in u32.
6376 		 */
6377 		if (insn_off > UINT32_MAX) {
6378 			pr_warn("map '.jumptables': invalid jump table value 0x%llx at offset %u\n",
6379 				(long long)jt[i], sym_off + i * jt_entry_size);
6380 			err = -EINVAL;
6381 			goto err_close;
6382 		}
6383 
6384 		val.orig_off = insn_off;
6385 		err = bpf_map_update_elem(map_fd, &i, &val, 0);
6386 		if (err)
6387 			goto err_close;
6388 	}
6389 
6390 	err = bpf_map_freeze(map_fd);
6391 	if (err)
6392 		goto err_close;
6393 
6394 	err = add_jt_map(obj, prog, sym_off, map_fd);
6395 	if (err)
6396 		goto err_close;
6397 
6398 	return map_fd;
6399 
6400 err_close:
6401 	close(map_fd);
6402 	return err;
6403 }
6404 
6405 /* Relocate data references within program code:
6406  *  - map references;
6407  *  - global variable references;
6408  *  - extern references.
6409  */
6410 static int
6411 bpf_object__relocate_data(struct bpf_object *obj, struct bpf_program *prog)
6412 {
6413 	int i;
6414 
6415 	for (i = 0; i < prog->nr_reloc; i++) {
6416 		struct reloc_desc *relo = &prog->reloc_desc[i];
6417 		struct bpf_insn *insn = &prog->insns[relo->insn_idx];
6418 		const struct bpf_map *map;
6419 		struct extern_desc *ext;
6420 
6421 		switch (relo->type) {
6422 		case RELO_LD64:
6423 			map = &obj->maps[relo->map_idx];
6424 			if (obj->gen_loader) {
6425 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX;
6426 				insn[0].imm = relo->map_idx;
6427 			} else if (map->autocreate) {
6428 				insn[0].src_reg = BPF_PSEUDO_MAP_FD;
6429 				insn[0].imm = map->fd;
6430 			} else {
6431 				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
6432 						   relo->map_idx, map);
6433 			}
6434 			break;
6435 		case RELO_DATA:
6436 			map = &obj->maps[relo->map_idx];
6437 			insn[1].imm = insn[0].imm + relo->sym_off;
6438 
6439 			if (relo->map_idx == obj->arena_map_idx)
6440 				insn[1].imm += obj->arena_data_off;
6441 
6442 			if (obj->gen_loader) {
6443 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
6444 				insn[0].imm = relo->map_idx;
6445 			} else if (map->autocreate) {
6446 				insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6447 				insn[0].imm = map->fd;
6448 			} else {
6449 				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
6450 						   relo->map_idx, map);
6451 			}
6452 			break;
6453 		case RELO_EXTERN_LD64:
6454 			ext = &obj->externs[relo->ext_idx];
6455 			if (ext->type == EXT_KCFG) {
6456 				if (obj->gen_loader) {
6457 					insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
6458 					insn[0].imm = obj->kconfig_map_idx;
6459 				} else {
6460 					insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6461 					insn[0].imm = obj->maps[obj->kconfig_map_idx].fd;
6462 				}
6463 				insn[1].imm = ext->kcfg.data_off;
6464 			} else /* EXT_KSYM */ {
6465 				if (ext->ksym.type_id && ext->is_set) { /* typed ksyms */
6466 					insn[0].src_reg = BPF_PSEUDO_BTF_ID;
6467 					insn[0].imm = ext->ksym.kernel_btf_id;
6468 					insn[1].imm = ext->ksym.kernel_btf_obj_fd;
6469 				} else { /* typeless ksyms or unresolved typed ksyms */
6470 					insn[0].imm = (__u32)ext->ksym.addr;
6471 					insn[1].imm = ext->ksym.addr >> 32;
6472 				}
6473 			}
6474 			break;
6475 		case RELO_EXTERN_CALL:
6476 			ext = &obj->externs[relo->ext_idx];
6477 			insn[0].src_reg = BPF_PSEUDO_KFUNC_CALL;
6478 			if (ext->is_set) {
6479 				insn[0].imm = ext->ksym.kernel_btf_id;
6480 				insn[0].off = ext->ksym.btf_fd_idx;
6481 			} else { /* unresolved weak kfunc call */
6482 				poison_kfunc_call(prog, i, relo->insn_idx, insn,
6483 						  relo->ext_idx, ext);
6484 			}
6485 			break;
6486 		case RELO_SUBPROG_ADDR:
6487 			if (insn[0].src_reg != BPF_PSEUDO_FUNC) {
6488 				pr_warn("prog '%s': relo #%d: bad insn\n",
6489 					prog->name, i);
6490 				return -EINVAL;
6491 			}
6492 			/* handled already */
6493 			break;
6494 		case RELO_CALL:
6495 			/* handled already */
6496 			break;
6497 		case RELO_CORE:
6498 			/* will be handled by bpf_program_record_relos() */
6499 			break;
6500 		case RELO_INSN_ARRAY: {
6501 			int map_fd;
6502 
6503 			map_fd = create_jt_map(obj, prog, relo);
6504 			if (map_fd < 0) {
6505 				pr_warn("prog '%s': relo #%d: can't create jump table: sym_off %u\n",
6506 					prog->name, i, relo->sym_off);
6507 				return map_fd;
6508 			}
6509 			insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6510 			insn->imm = map_fd;
6511 			insn->off = 0;
6512 		}
6513 			break;
6514 		default:
6515 			pr_warn("prog '%s': relo #%d: bad relo type %d\n",
6516 				prog->name, i, relo->type);
6517 			return -EINVAL;
6518 		}
6519 	}
6520 
6521 	return 0;
6522 }
6523 
6524 static int adjust_prog_btf_ext_info(const struct bpf_object *obj,
6525 				    const struct bpf_program *prog,
6526 				    const struct btf_ext_info *ext_info,
6527 				    void **prog_info, __u32 *prog_rec_cnt,
6528 				    __u32 *prog_rec_sz)
6529 {
6530 	void *copy_start = NULL, *copy_end = NULL;
6531 	void *rec, *rec_end, *new_prog_info;
6532 	const struct btf_ext_info_sec *sec;
6533 	size_t old_sz, new_sz;
6534 	int i, sec_num, sec_idx, off_adj;
6535 
6536 	sec_num = 0;
6537 	for_each_btf_ext_sec(ext_info, sec) {
6538 		sec_idx = ext_info->sec_idxs[sec_num];
6539 		sec_num++;
6540 		if (prog->sec_idx != sec_idx)
6541 			continue;
6542 
6543 		for_each_btf_ext_rec(ext_info, sec, i, rec) {
6544 			__u32 insn_off = *(__u32 *)rec / BPF_INSN_SZ;
6545 
6546 			if (insn_off < prog->sec_insn_off)
6547 				continue;
6548 			if (insn_off >= prog->sec_insn_off + prog->sec_insn_cnt)
6549 				break;
6550 
6551 			if (!copy_start)
6552 				copy_start = rec;
6553 			copy_end = rec + ext_info->rec_size;
6554 		}
6555 
6556 		if (!copy_start)
6557 			return -ENOENT;
6558 
6559 		/* append func/line info of a given (sub-)program to the main
6560 		 * program func/line info
6561 		 */
6562 		old_sz = (size_t)(*prog_rec_cnt) * ext_info->rec_size;
6563 		new_sz = old_sz + (copy_end - copy_start);
6564 		new_prog_info = realloc(*prog_info, new_sz);
6565 		if (!new_prog_info)
6566 			return -ENOMEM;
6567 		*prog_info = new_prog_info;
6568 		*prog_rec_cnt = new_sz / ext_info->rec_size;
6569 		memcpy(new_prog_info + old_sz, copy_start, copy_end - copy_start);
6570 
6571 		/* Kernel instruction offsets are in units of 8-byte
6572 		 * instructions, while .BTF.ext instruction offsets generated
6573 		 * by Clang are in units of bytes. So convert Clang offsets
6574 		 * into kernel offsets and adjust offset according to program
6575 		 * relocated position.
6576 		 */
6577 		off_adj = prog->sub_insn_off - prog->sec_insn_off;
6578 		rec = new_prog_info + old_sz;
6579 		rec_end = new_prog_info + new_sz;
6580 		for (; rec < rec_end; rec += ext_info->rec_size) {
6581 			__u32 *insn_off = rec;
6582 
6583 			*insn_off = *insn_off / BPF_INSN_SZ + off_adj;
6584 		}
6585 		*prog_rec_sz = ext_info->rec_size;
6586 		return 0;
6587 	}
6588 
6589 	return -ENOENT;
6590 }
6591 
6592 static int
6593 reloc_prog_func_and_line_info(const struct bpf_object *obj,
6594 			      struct bpf_program *main_prog,
6595 			      const struct bpf_program *prog)
6596 {
6597 	int err;
6598 
6599 	/* no .BTF.ext relocation if .BTF.ext is missing or kernel doesn't
6600 	 * support func/line info
6601 	 */
6602 	if (!obj->btf_ext || !kernel_supports(obj, FEAT_BTF_FUNC))
6603 		return 0;
6604 
6605 	/* only attempt func info relocation if main program's func_info
6606 	 * relocation was successful
6607 	 */
6608 	if (main_prog != prog && !main_prog->func_info)
6609 		goto line_info;
6610 
6611 	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->func_info,
6612 				       &main_prog->func_info,
6613 				       &main_prog->func_info_cnt,
6614 				       &main_prog->func_info_rec_size);
6615 	if (err) {
6616 		if (err != -ENOENT) {
6617 			pr_warn("prog '%s': error relocating .BTF.ext function info: %s\n",
6618 				prog->name, errstr(err));
6619 			return err;
6620 		}
6621 		if (main_prog->func_info) {
6622 			/*
6623 			 * Some info has already been found but has problem
6624 			 * in the last btf_ext reloc. Must have to error out.
6625 			 */
6626 			pr_warn("prog '%s': missing .BTF.ext function info.\n", prog->name);
6627 			return err;
6628 		}
6629 		/* Have problem loading the very first info. Ignore the rest. */
6630 		pr_warn("prog '%s': missing .BTF.ext function info for the main program, skipping all of .BTF.ext func info.\n",
6631 			prog->name);
6632 	}
6633 
6634 line_info:
6635 	/* don't relocate line info if main program's relocation failed */
6636 	if (main_prog != prog && !main_prog->line_info)
6637 		return 0;
6638 
6639 	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->line_info,
6640 				       &main_prog->line_info,
6641 				       &main_prog->line_info_cnt,
6642 				       &main_prog->line_info_rec_size);
6643 	if (err) {
6644 		if (err != -ENOENT) {
6645 			pr_warn("prog '%s': error relocating .BTF.ext line info: %s\n",
6646 				prog->name, errstr(err));
6647 			return err;
6648 		}
6649 		if (main_prog->line_info) {
6650 			/*
6651 			 * Some info has already been found but has problem
6652 			 * in the last btf_ext reloc. Must have to error out.
6653 			 */
6654 			pr_warn("prog '%s': missing .BTF.ext line info.\n", prog->name);
6655 			return err;
6656 		}
6657 		/* Have problem loading the very first info. Ignore the rest. */
6658 		pr_warn("prog '%s': missing .BTF.ext line info for the main program, skipping all of .BTF.ext line info.\n",
6659 			prog->name);
6660 	}
6661 	return 0;
6662 }
6663 
6664 static int cmp_relo_by_insn_idx(const void *key, const void *elem)
6665 {
6666 	size_t insn_idx = *(const size_t *)key;
6667 	const struct reloc_desc *relo = elem;
6668 
6669 	if (insn_idx == relo->insn_idx)
6670 		return 0;
6671 	return insn_idx < relo->insn_idx ? -1 : 1;
6672 }
6673 
6674 static struct reloc_desc *find_prog_insn_relo(const struct bpf_program *prog, size_t insn_idx)
6675 {
6676 	if (!prog->nr_reloc)
6677 		return NULL;
6678 	return bsearch(&insn_idx, prog->reloc_desc, prog->nr_reloc,
6679 		       sizeof(*prog->reloc_desc), cmp_relo_by_insn_idx);
6680 }
6681 
6682 static int append_subprog_relos(struct bpf_program *main_prog, struct bpf_program *subprog)
6683 {
6684 	int new_cnt = main_prog->nr_reloc + subprog->nr_reloc;
6685 	struct reloc_desc *relos;
6686 	int i;
6687 
6688 	if (main_prog == subprog)
6689 		return 0;
6690 	relos = libbpf_reallocarray(main_prog->reloc_desc, new_cnt, sizeof(*relos));
6691 	/* if new count is zero, reallocarray can return a valid NULL result;
6692 	 * in this case the previous pointer will be freed, so we *have to*
6693 	 * reassign old pointer to the new value (even if it's NULL)
6694 	 */
6695 	if (!relos && new_cnt)
6696 		return -ENOMEM;
6697 	if (subprog->nr_reloc)
6698 		memcpy(relos + main_prog->nr_reloc, subprog->reloc_desc,
6699 		       sizeof(*relos) * subprog->nr_reloc);
6700 
6701 	for (i = main_prog->nr_reloc; i < new_cnt; i++)
6702 		relos[i].insn_idx += subprog->sub_insn_off;
6703 	/* After insn_idx adjustment the 'relos' array is still sorted
6704 	 * by insn_idx and doesn't break bsearch.
6705 	 */
6706 	main_prog->reloc_desc = relos;
6707 	main_prog->nr_reloc = new_cnt;
6708 	return 0;
6709 }
6710 
6711 static int save_subprog_offsets(struct bpf_program *main_prog, struct bpf_program *subprog)
6712 {
6713 	size_t size = sizeof(main_prog->subprogs[0]);
6714 	int cnt = main_prog->subprog_cnt;
6715 	void *tmp;
6716 
6717 	tmp = libbpf_reallocarray(main_prog->subprogs, cnt + 1, size);
6718 	if (!tmp)
6719 		return -ENOMEM;
6720 
6721 	main_prog->subprogs = tmp;
6722 	main_prog->subprogs[cnt].sec_insn_off = subprog->sec_insn_off;
6723 	main_prog->subprogs[cnt].sub_insn_off = subprog->sub_insn_off;
6724 	main_prog->subprog_cnt++;
6725 
6726 	return 0;
6727 }
6728 
6729 static int
6730 bpf_object__append_subprog_code(struct bpf_object *obj, struct bpf_program *main_prog,
6731 				struct bpf_program *subprog)
6732 {
6733 	struct bpf_insn *insns;
6734 	size_t new_cnt;
6735 	int err;
6736 
6737 	subprog->sub_insn_off = main_prog->insns_cnt;
6738 
6739 	new_cnt = main_prog->insns_cnt + subprog->insns_cnt;
6740 	insns = libbpf_reallocarray(main_prog->insns, new_cnt, sizeof(*insns));
6741 	if (!insns) {
6742 		pr_warn("prog '%s': failed to realloc prog code\n", main_prog->name);
6743 		return -ENOMEM;
6744 	}
6745 	main_prog->insns = insns;
6746 	main_prog->insns_cnt = new_cnt;
6747 
6748 	memcpy(main_prog->insns + subprog->sub_insn_off, subprog->insns,
6749 	       subprog->insns_cnt * sizeof(*insns));
6750 
6751 	pr_debug("prog '%s': added %zu insns from sub-prog '%s'\n",
6752 		 main_prog->name, subprog->insns_cnt, subprog->name);
6753 
6754 	/* The subprog insns are now appended. Append its relos too. */
6755 	err = append_subprog_relos(main_prog, subprog);
6756 	if (err)
6757 		return err;
6758 
6759 	err = save_subprog_offsets(main_prog, subprog);
6760 	if (err) {
6761 		pr_warn("prog '%s': failed to add subprog offsets: %s\n",
6762 			main_prog->name, errstr(err));
6763 		return err;
6764 	}
6765 
6766 	return 0;
6767 }
6768 
6769 static int
6770 bpf_object__reloc_code(struct bpf_object *obj, struct bpf_program *main_prog,
6771 		       struct bpf_program *prog)
6772 {
6773 	size_t sub_insn_idx, insn_idx;
6774 	struct bpf_program *subprog;
6775 	struct reloc_desc *relo;
6776 	struct bpf_insn *insn;
6777 	int err;
6778 
6779 	err = reloc_prog_func_and_line_info(obj, main_prog, prog);
6780 	if (err)
6781 		return err;
6782 
6783 	for (insn_idx = 0; insn_idx < prog->sec_insn_cnt; insn_idx++) {
6784 		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6785 		if (!insn_is_subprog_call(insn) && !insn_is_pseudo_func(insn))
6786 			continue;
6787 
6788 		relo = find_prog_insn_relo(prog, insn_idx);
6789 		if (relo && relo->type == RELO_EXTERN_CALL)
6790 			/* kfunc relocations will be handled later
6791 			 * in bpf_object__relocate_data()
6792 			 */
6793 			continue;
6794 		if (relo && relo->type != RELO_CALL && relo->type != RELO_SUBPROG_ADDR) {
6795 			pr_warn("prog '%s': unexpected relo for insn #%zu, type %d\n",
6796 				prog->name, insn_idx, relo->type);
6797 			return -LIBBPF_ERRNO__RELOC;
6798 		}
6799 		if (relo) {
6800 			/* sub-program instruction index is a combination of
6801 			 * an offset of a symbol pointed to by relocation and
6802 			 * call instruction's imm field; for global functions,
6803 			 * call always has imm = -1, but for static functions
6804 			 * relocation is against STT_SECTION and insn->imm
6805 			 * points to a start of a static function
6806 			 *
6807 			 * for subprog addr relocation, the relo->sym_off + insn->imm is
6808 			 * the byte offset in the corresponding section.
6809 			 */
6810 			if (relo->type == RELO_CALL)
6811 				sub_insn_idx = relo->sym_off / BPF_INSN_SZ + insn->imm + 1;
6812 			else
6813 				sub_insn_idx = (relo->sym_off + insn->imm) / BPF_INSN_SZ;
6814 		} else if (insn_is_pseudo_func(insn)) {
6815 			/*
6816 			 * RELO_SUBPROG_ADDR relo is always emitted even if both
6817 			 * functions are in the same section, so it shouldn't reach here.
6818 			 */
6819 			pr_warn("prog '%s': missing subprog addr relo for insn #%zu\n",
6820 				prog->name, insn_idx);
6821 			return -LIBBPF_ERRNO__RELOC;
6822 		} else {
6823 			/* if subprogram call is to a static function within
6824 			 * the same ELF section, there won't be any relocation
6825 			 * emitted, but it also means there is no additional
6826 			 * offset necessary, insns->imm is relative to
6827 			 * instruction's original position within the section
6828 			 */
6829 			sub_insn_idx = prog->sec_insn_off + insn_idx + insn->imm + 1;
6830 		}
6831 
6832 		/* we enforce that sub-programs should be in .text section */
6833 		subprog = find_prog_by_sec_insn(obj, obj->efile.text_shndx, sub_insn_idx);
6834 		if (!subprog) {
6835 			pr_warn("prog '%s': no .text section found yet sub-program call exists\n",
6836 				prog->name);
6837 			return -LIBBPF_ERRNO__RELOC;
6838 		}
6839 
6840 		/* if it's the first call instruction calling into this
6841 		 * subprogram (meaning this subprog hasn't been processed
6842 		 * yet) within the context of current main program:
6843 		 *   - append it at the end of main program's instructions blog;
6844 		 *   - process is recursively, while current program is put on hold;
6845 		 *   - if that subprogram calls some other not yet processes
6846 		 *   subprogram, same thing will happen recursively until
6847 		 *   there are no more unprocesses subprograms left to append
6848 		 *   and relocate.
6849 		 */
6850 		if (subprog->sub_insn_off == 0) {
6851 			err = bpf_object__append_subprog_code(obj, main_prog, subprog);
6852 			if (err)
6853 				return err;
6854 			err = bpf_object__reloc_code(obj, main_prog, subprog);
6855 			if (err)
6856 				return err;
6857 		}
6858 
6859 		/* main_prog->insns memory could have been re-allocated, so
6860 		 * calculate pointer again
6861 		 */
6862 		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6863 		/* calculate correct instruction position within current main
6864 		 * prog; each main prog can have a different set of
6865 		 * subprograms appended (potentially in different order as
6866 		 * well), so position of any subprog can be different for
6867 		 * different main programs
6868 		 */
6869 		insn->imm = subprog->sub_insn_off - (prog->sub_insn_off + insn_idx) - 1;
6870 
6871 		pr_debug("prog '%s': insn #%zu relocated, imm %d points to subprog '%s' (now at %zu offset)\n",
6872 			 prog->name, insn_idx, insn->imm, subprog->name, subprog->sub_insn_off);
6873 	}
6874 
6875 	return 0;
6876 }
6877 
6878 /*
6879  * Relocate sub-program calls.
6880  *
6881  * Algorithm operates as follows. Each entry-point BPF program (referred to as
6882  * main prog) is processed separately. For each subprog (non-entry functions,
6883  * that can be called from either entry progs or other subprogs) gets their
6884  * sub_insn_off reset to zero. This serves as indicator that this subprogram
6885  * hasn't been yet appended and relocated within current main prog. Once its
6886  * relocated, sub_insn_off will point at the position within current main prog
6887  * where given subprog was appended. This will further be used to relocate all
6888  * the call instructions jumping into this subprog.
6889  *
6890  * We start with main program and process all call instructions. If the call
6891  * is into a subprog that hasn't been processed (i.e., subprog->sub_insn_off
6892  * is zero), subprog instructions are appended at the end of main program's
6893  * instruction array. Then main program is "put on hold" while we recursively
6894  * process newly appended subprogram. If that subprogram calls into another
6895  * subprogram that hasn't been appended, new subprogram is appended again to
6896  * the *main* prog's instructions (subprog's instructions are always left
6897  * untouched, as they need to be in unmodified state for subsequent main progs
6898  * and subprog instructions are always sent only as part of a main prog) and
6899  * the process continues recursively. Once all the subprogs called from a main
6900  * prog or any of its subprogs are appended (and relocated), all their
6901  * positions within finalized instructions array are known, so it's easy to
6902  * rewrite call instructions with correct relative offsets, corresponding to
6903  * desired target subprog.
6904  *
6905  * Its important to realize that some subprogs might not be called from some
6906  * main prog and any of its called/used subprogs. Those will keep their
6907  * subprog->sub_insn_off as zero at all times and won't be appended to current
6908  * main prog and won't be relocated within the context of current main prog.
6909  * They might still be used from other main progs later.
6910  *
6911  * Visually this process can be shown as below. Suppose we have two main
6912  * programs mainA and mainB and BPF object contains three subprogs: subA,
6913  * subB, and subC. mainA calls only subA, mainB calls only subC, but subA and
6914  * subC both call subB:
6915  *
6916  *        +--------+ +-------+
6917  *        |        v v       |
6918  *     +--+---+ +--+-+-+ +---+--+
6919  *     | subA | | subB | | subC |
6920  *     +--+---+ +------+ +---+--+
6921  *        ^                  ^
6922  *        |                  |
6923  *    +---+-------+   +------+----+
6924  *    |   mainA   |   |   mainB   |
6925  *    +-----------+   +-----------+
6926  *
6927  * We'll start relocating mainA, will find subA, append it and start
6928  * processing sub A recursively:
6929  *
6930  *    +-----------+------+
6931  *    |   mainA   | subA |
6932  *    +-----------+------+
6933  *
6934  * At this point we notice that subB is used from subA, so we append it and
6935  * relocate (there are no further subcalls from subB):
6936  *
6937  *    +-----------+------+------+
6938  *    |   mainA   | subA | subB |
6939  *    +-----------+------+------+
6940  *
6941  * At this point, we relocate subA calls, then go one level up and finish with
6942  * relocatin mainA calls. mainA is done.
6943  *
6944  * For mainB process is similar but results in different order. We start with
6945  * mainB and skip subA and subB, as mainB never calls them (at least
6946  * directly), but we see subC is needed, so we append and start processing it:
6947  *
6948  *    +-----------+------+
6949  *    |   mainB   | subC |
6950  *    +-----------+------+
6951  * Now we see subC needs subB, so we go back to it, append and relocate it:
6952  *
6953  *    +-----------+------+------+
6954  *    |   mainB   | subC | subB |
6955  *    +-----------+------+------+
6956  *
6957  * At this point we unwind recursion, relocate calls in subC, then in mainB.
6958  */
6959 static int
6960 bpf_object__relocate_calls(struct bpf_object *obj, struct bpf_program *prog)
6961 {
6962 	struct bpf_program *subprog;
6963 	int i, err;
6964 
6965 	/* mark all subprogs as not relocated (yet) within the context of
6966 	 * current main program
6967 	 */
6968 	for (i = 0; i < obj->nr_programs; i++) {
6969 		subprog = &obj->programs[i];
6970 		if (!prog_is_subprog(obj, subprog))
6971 			continue;
6972 
6973 		subprog->sub_insn_off = 0;
6974 	}
6975 
6976 	err = bpf_object__reloc_code(obj, prog, prog);
6977 	if (err)
6978 		return err;
6979 
6980 	return 0;
6981 }
6982 
6983 static void
6984 bpf_object__free_relocs(struct bpf_object *obj)
6985 {
6986 	struct bpf_program *prog;
6987 	int i;
6988 
6989 	/* free up relocation descriptors */
6990 	for (i = 0; i < obj->nr_programs; i++) {
6991 		prog = &obj->programs[i];
6992 		zfree(&prog->reloc_desc);
6993 		prog->nr_reloc = 0;
6994 	}
6995 }
6996 
6997 static int cmp_relocs(const void *_a, const void *_b)
6998 {
6999 	const struct reloc_desc *a = _a;
7000 	const struct reloc_desc *b = _b;
7001 
7002 	if (a->insn_idx != b->insn_idx)
7003 		return a->insn_idx < b->insn_idx ? -1 : 1;
7004 
7005 	/* no two relocations should have the same insn_idx, but ... */
7006 	if (a->type != b->type)
7007 		return a->type < b->type ? -1 : 1;
7008 
7009 	return 0;
7010 }
7011 
7012 static void bpf_object__sort_relos(struct bpf_object *obj)
7013 {
7014 	int i;
7015 
7016 	for (i = 0; i < obj->nr_programs; i++) {
7017 		struct bpf_program *p = &obj->programs[i];
7018 
7019 		if (!p->nr_reloc)
7020 			continue;
7021 
7022 		qsort(p->reloc_desc, p->nr_reloc, sizeof(*p->reloc_desc), cmp_relocs);
7023 	}
7024 }
7025 
7026 static int bpf_prog_assign_exc_cb(struct bpf_object *obj, struct bpf_program *prog)
7027 {
7028 	const char *str = "exception_callback:";
7029 	size_t pfx_len = strlen(str);
7030 	int i, j, n;
7031 
7032 	if (!obj->btf || !kernel_supports(obj, FEAT_BTF_DECL_TAG))
7033 		return 0;
7034 
7035 	n = btf__type_cnt(obj->btf);
7036 	for (i = 1; i < n; i++) {
7037 		const char *name;
7038 		struct btf_type *t;
7039 
7040 		t = btf_type_by_id(obj->btf, i);
7041 		if (!btf_is_decl_tag(t) || btf_decl_tag(t)->component_idx != -1)
7042 			continue;
7043 
7044 		name = btf__str_by_offset(obj->btf, t->name_off);
7045 		if (strncmp(name, str, pfx_len) != 0)
7046 			continue;
7047 
7048 		t = btf_type_by_id(obj->btf, t->type);
7049 		if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL) {
7050 			pr_warn("prog '%s': exception_callback:<value> decl tag not applied to the main program\n",
7051 				prog->name);
7052 			return -EINVAL;
7053 		}
7054 		if (strcmp(prog->name, btf__str_by_offset(obj->btf, t->name_off)) != 0)
7055 			continue;
7056 		/* Multiple callbacks are specified for the same prog,
7057 		 * the verifier will eventually return an error for this
7058 		 * case, hence simply skip appending a subprog.
7059 		 */
7060 		if (prog->exception_cb_idx >= 0) {
7061 			prog->exception_cb_idx = -1;
7062 			break;
7063 		}
7064 
7065 		name += pfx_len;
7066 		if (str_is_empty(name)) {
7067 			pr_warn("prog '%s': exception_callback:<value> decl tag contains empty value\n",
7068 				prog->name);
7069 			return -EINVAL;
7070 		}
7071 
7072 		for (j = 0; j < obj->nr_programs; j++) {
7073 			struct bpf_program *subprog = &obj->programs[j];
7074 
7075 			if (!prog_is_subprog(obj, subprog))
7076 				continue;
7077 			if (strcmp(name, subprog->name) != 0)
7078 				continue;
7079 			/* Enforce non-hidden, as from verifier point of
7080 			 * view it expects global functions, whereas the
7081 			 * mark_btf_static fixes up linkage as static.
7082 			 */
7083 			if (!subprog->sym_global || subprog->mark_btf_static) {
7084 				pr_warn("prog '%s': exception callback %s must be a global non-hidden function\n",
7085 					prog->name, subprog->name);
7086 				return -EINVAL;
7087 			}
7088 			/* Let's see if we already saw a static exception callback with the same name */
7089 			if (prog->exception_cb_idx >= 0) {
7090 				pr_warn("prog '%s': multiple subprogs with same name as exception callback '%s'\n",
7091 					prog->name, subprog->name);
7092 				return -EINVAL;
7093 			}
7094 			prog->exception_cb_idx = j;
7095 			break;
7096 		}
7097 
7098 		if (prog->exception_cb_idx >= 0)
7099 			continue;
7100 
7101 		pr_warn("prog '%s': cannot find exception callback '%s'\n", prog->name, name);
7102 		return -ENOENT;
7103 	}
7104 
7105 	return 0;
7106 }
7107 
7108 static struct {
7109 	enum bpf_prog_type prog_type;
7110 	const char *ctx_name;
7111 } global_ctx_map[] = {
7112 	{ BPF_PROG_TYPE_CGROUP_DEVICE,           "bpf_cgroup_dev_ctx" },
7113 	{ BPF_PROG_TYPE_CGROUP_SKB,              "__sk_buff" },
7114 	{ BPF_PROG_TYPE_CGROUP_SOCK,             "bpf_sock" },
7115 	{ BPF_PROG_TYPE_CGROUP_SOCK_ADDR,        "bpf_sock_addr" },
7116 	{ BPF_PROG_TYPE_CGROUP_SOCKOPT,          "bpf_sockopt" },
7117 	{ BPF_PROG_TYPE_CGROUP_SYSCTL,           "bpf_sysctl" },
7118 	{ BPF_PROG_TYPE_FLOW_DISSECTOR,          "__sk_buff" },
7119 	{ BPF_PROG_TYPE_KPROBE,                  "bpf_user_pt_regs_t" },
7120 	{ BPF_PROG_TYPE_LWT_IN,                  "__sk_buff" },
7121 	{ BPF_PROG_TYPE_LWT_OUT,                 "__sk_buff" },
7122 	{ BPF_PROG_TYPE_LWT_SEG6LOCAL,           "__sk_buff" },
7123 	{ BPF_PROG_TYPE_LWT_XMIT,                "__sk_buff" },
7124 	{ BPF_PROG_TYPE_NETFILTER,               "bpf_nf_ctx" },
7125 	{ BPF_PROG_TYPE_PERF_EVENT,              "bpf_perf_event_data" },
7126 	{ BPF_PROG_TYPE_RAW_TRACEPOINT,          "bpf_raw_tracepoint_args" },
7127 	{ BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE, "bpf_raw_tracepoint_args" },
7128 	{ BPF_PROG_TYPE_SCHED_ACT,               "__sk_buff" },
7129 	{ BPF_PROG_TYPE_SCHED_CLS,               "__sk_buff" },
7130 	{ BPF_PROG_TYPE_SK_LOOKUP,               "bpf_sk_lookup" },
7131 	{ BPF_PROG_TYPE_SK_MSG,                  "sk_msg_md" },
7132 	{ BPF_PROG_TYPE_SK_REUSEPORT,            "sk_reuseport_md" },
7133 	{ BPF_PROG_TYPE_SK_SKB,                  "__sk_buff" },
7134 	{ BPF_PROG_TYPE_SOCK_OPS,                "bpf_sock_ops" },
7135 	{ BPF_PROG_TYPE_SOCKET_FILTER,           "__sk_buff" },
7136 	{ BPF_PROG_TYPE_XDP,                     "xdp_md" },
7137 	/* all other program types don't have "named" context structs */
7138 };
7139 
7140 /* forward declarations for arch-specific underlying types of bpf_user_pt_regs_t typedef,
7141  * for below __builtin_types_compatible_p() checks;
7142  * with this approach we don't need any extra arch-specific #ifdef guards
7143  */
7144 struct pt_regs;
7145 struct user_pt_regs;
7146 struct user_regs_struct;
7147 
7148 static bool need_func_arg_type_fixup(const struct btf *btf, const struct bpf_program *prog,
7149 				     const char *subprog_name, int arg_idx,
7150 				     int arg_type_id, const char *ctx_name)
7151 {
7152 	const struct btf_type *t;
7153 	const char *tname;
7154 
7155 	/* check if existing parameter already matches verifier expectations */
7156 	t = skip_mods_and_typedefs(btf, arg_type_id, NULL);
7157 	if (!btf_is_ptr(t))
7158 		goto out_warn;
7159 
7160 	/* typedef bpf_user_pt_regs_t is a special PITA case, valid for kprobe
7161 	 * and perf_event programs, so check this case early on and forget
7162 	 * about it for subsequent checks
7163 	 */
7164 	while (btf_is_mod(t))
7165 		t = btf__type_by_id(btf, t->type);
7166 	if (btf_is_typedef(t) &&
7167 	    (prog->type == BPF_PROG_TYPE_KPROBE || prog->type == BPF_PROG_TYPE_PERF_EVENT)) {
7168 		tname = btf__str_by_offset(btf, t->name_off) ?: "<anon>";
7169 		if (strcmp(tname, "bpf_user_pt_regs_t") == 0)
7170 			return false; /* canonical type for kprobe/perf_event */
7171 	}
7172 
7173 	/* now we can ignore typedefs moving forward */
7174 	t = skip_mods_and_typedefs(btf, t->type, NULL);
7175 
7176 	/* if it's `void *`, definitely fix up BTF info */
7177 	if (btf_is_void(t))
7178 		return true;
7179 
7180 	/* if it's already proper canonical type, no need to fix up */
7181 	tname = btf__str_by_offset(btf, t->name_off) ?: "<anon>";
7182 	if (btf_is_struct(t) && strcmp(tname, ctx_name) == 0)
7183 		return false;
7184 
7185 	/* special cases */
7186 	switch (prog->type) {
7187 	case BPF_PROG_TYPE_KPROBE:
7188 		/* `struct pt_regs *` is expected, but we need to fix up */
7189 		if (btf_is_struct(t) && strcmp(tname, "pt_regs") == 0)
7190 			return true;
7191 		break;
7192 	case BPF_PROG_TYPE_PERF_EVENT:
7193 		if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct pt_regs) &&
7194 		    btf_is_struct(t) && strcmp(tname, "pt_regs") == 0)
7195 			return true;
7196 		if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct user_pt_regs) &&
7197 		    btf_is_struct(t) && strcmp(tname, "user_pt_regs") == 0)
7198 			return true;
7199 		if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct user_regs_struct) &&
7200 		    btf_is_struct(t) && strcmp(tname, "user_regs_struct") == 0)
7201 			return true;
7202 		break;
7203 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
7204 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
7205 		/* allow u64* as ctx */
7206 		if (btf_is_int(t) && t->size == 8)
7207 			return true;
7208 		break;
7209 	default:
7210 		break;
7211 	}
7212 
7213 out_warn:
7214 	pr_warn("prog '%s': subprog '%s' arg#%d is expected to be of `struct %s *` type\n",
7215 		prog->name, subprog_name, arg_idx, ctx_name);
7216 	return false;
7217 }
7218 
7219 static int clone_func_btf_info(struct btf *btf, int orig_fn_id, struct bpf_program *prog)
7220 {
7221 	int fn_id, fn_proto_id, ret_type_id, orig_proto_id;
7222 	int i, err, arg_cnt, fn_name_off, linkage;
7223 	struct btf_type *fn_t, *fn_proto_t, *t;
7224 	struct btf_param *p;
7225 
7226 	/* caller already validated FUNC -> FUNC_PROTO validity */
7227 	fn_t = btf_type_by_id(btf, orig_fn_id);
7228 	fn_proto_t = btf_type_by_id(btf, fn_t->type);
7229 
7230 	/* Note that each btf__add_xxx() operation invalidates
7231 	 * all btf_type and string pointers, so we need to be
7232 	 * very careful when cloning BTF types. BTF type
7233 	 * pointers have to be always refetched. And to avoid
7234 	 * problems with invalidated string pointers, we
7235 	 * add empty strings initially, then just fix up
7236 	 * name_off offsets in place. Offsets are stable for
7237 	 * existing strings, so that works out.
7238 	 */
7239 	fn_name_off = fn_t->name_off; /* we are about to invalidate fn_t */
7240 	linkage = btf_func_linkage(fn_t);
7241 	orig_proto_id = fn_t->type; /* original FUNC_PROTO ID */
7242 	ret_type_id = fn_proto_t->type; /* fn_proto_t will be invalidated */
7243 	arg_cnt = btf_vlen(fn_proto_t);
7244 
7245 	/* clone FUNC_PROTO and its params */
7246 	fn_proto_id = btf__add_func_proto(btf, ret_type_id);
7247 	if (fn_proto_id < 0)
7248 		return -EINVAL;
7249 
7250 	for (i = 0; i < arg_cnt; i++) {
7251 		int name_off;
7252 
7253 		/* copy original parameter data */
7254 		t = btf_type_by_id(btf, orig_proto_id);
7255 		p = &btf_params(t)[i];
7256 		name_off = p->name_off;
7257 
7258 		err = btf__add_func_param(btf, "", p->type);
7259 		if (err)
7260 			return err;
7261 
7262 		fn_proto_t = btf_type_by_id(btf, fn_proto_id);
7263 		p = &btf_params(fn_proto_t)[i];
7264 		p->name_off = name_off; /* use remembered str offset */
7265 	}
7266 
7267 	/* clone FUNC now, btf__add_func() enforces non-empty name, so use
7268 	 * entry program's name as a placeholder, which we replace immediately
7269 	 * with original name_off
7270 	 */
7271 	fn_id = btf__add_func(btf, prog->name, linkage, fn_proto_id);
7272 	if (fn_id < 0)
7273 		return -EINVAL;
7274 
7275 	fn_t = btf_type_by_id(btf, fn_id);
7276 	fn_t->name_off = fn_name_off; /* reuse original string */
7277 
7278 	return fn_id;
7279 }
7280 
7281 /* Check if main program or global subprog's function prototype has `arg:ctx`
7282  * argument tags, and, if necessary, substitute correct type to match what BPF
7283  * verifier would expect, taking into account specific program type. This
7284  * allows to support __arg_ctx tag transparently on old kernels that don't yet
7285  * have a native support for it in the verifier, making user's life much
7286  * easier.
7287  */
7288 static int bpf_program_fixup_func_info(struct bpf_object *obj, struct bpf_program *prog)
7289 {
7290 	const char *ctx_name = NULL, *ctx_tag = "arg:ctx", *fn_name;
7291 	struct bpf_func_info_min *func_rec;
7292 	struct btf_type *fn_t, *fn_proto_t;
7293 	struct btf *btf = obj->btf;
7294 	const struct btf_type *t;
7295 	struct btf_param *p;
7296 	int ptr_id = 0, struct_id, tag_id, orig_fn_id;
7297 	int i, n, arg_idx, arg_cnt, err, rec_idx;
7298 	int *orig_ids;
7299 
7300 	/* no .BTF.ext, no problem */
7301 	if (!obj->btf_ext || !prog->func_info)
7302 		return 0;
7303 
7304 	/* don't do any fix ups if kernel natively supports __arg_ctx */
7305 	if (kernel_supports(obj, FEAT_ARG_CTX_TAG))
7306 		return 0;
7307 
7308 	/* some BPF program types just don't have named context structs, so
7309 	 * this fallback mechanism doesn't work for them
7310 	 */
7311 	for (i = 0; i < ARRAY_SIZE(global_ctx_map); i++) {
7312 		if (global_ctx_map[i].prog_type != prog->type)
7313 			continue;
7314 		ctx_name = global_ctx_map[i].ctx_name;
7315 		break;
7316 	}
7317 	if (!ctx_name)
7318 		return 0;
7319 
7320 	/* remember original func BTF IDs to detect if we already cloned them */
7321 	orig_ids = calloc(prog->func_info_cnt, sizeof(*orig_ids));
7322 	if (!orig_ids)
7323 		return -ENOMEM;
7324 	for (i = 0; i < prog->func_info_cnt; i++) {
7325 		func_rec = prog->func_info + prog->func_info_rec_size * i;
7326 		orig_ids[i] = func_rec->type_id;
7327 	}
7328 
7329 	/* go through each DECL_TAG with "arg:ctx" and see if it points to one
7330 	 * of our subprogs; if yes and subprog is global and needs adjustment,
7331 	 * clone and adjust FUNC -> FUNC_PROTO combo
7332 	 */
7333 	for (i = 1, n = btf__type_cnt(btf); i < n; i++) {
7334 		/* only DECL_TAG with "arg:ctx" value are interesting */
7335 		t = btf__type_by_id(btf, i);
7336 		if (!btf_is_decl_tag(t))
7337 			continue;
7338 		if (strcmp(btf__str_by_offset(btf, t->name_off), ctx_tag) != 0)
7339 			continue;
7340 
7341 		/* only global funcs need adjustment, if at all */
7342 		orig_fn_id = t->type;
7343 		fn_t = btf_type_by_id(btf, orig_fn_id);
7344 		if (!btf_is_func(fn_t) || btf_func_linkage(fn_t) != BTF_FUNC_GLOBAL)
7345 			continue;
7346 
7347 		/* sanity check FUNC -> FUNC_PROTO chain, just in case */
7348 		fn_proto_t = btf_type_by_id(btf, fn_t->type);
7349 		if (!fn_proto_t || !btf_is_func_proto(fn_proto_t))
7350 			continue;
7351 
7352 		/* find corresponding func_info record */
7353 		func_rec = NULL;
7354 		for (rec_idx = 0; rec_idx < prog->func_info_cnt; rec_idx++) {
7355 			if (orig_ids[rec_idx] == t->type) {
7356 				func_rec = prog->func_info + prog->func_info_rec_size * rec_idx;
7357 				break;
7358 			}
7359 		}
7360 		/* current main program doesn't call into this subprog */
7361 		if (!func_rec)
7362 			continue;
7363 
7364 		/* some more sanity checking of DECL_TAG */
7365 		arg_cnt = btf_vlen(fn_proto_t);
7366 		arg_idx = btf_decl_tag(t)->component_idx;
7367 		if (arg_idx < 0 || arg_idx >= arg_cnt)
7368 			continue;
7369 
7370 		/* check if we should fix up argument type */
7371 		p = &btf_params(fn_proto_t)[arg_idx];
7372 		fn_name = btf__str_by_offset(btf, fn_t->name_off) ?: "<anon>";
7373 		if (!need_func_arg_type_fixup(btf, prog, fn_name, arg_idx, p->type, ctx_name))
7374 			continue;
7375 
7376 		/* clone fn/fn_proto, unless we already did it for another arg */
7377 		if (func_rec->type_id == orig_fn_id) {
7378 			int fn_id;
7379 
7380 			fn_id = clone_func_btf_info(btf, orig_fn_id, prog);
7381 			if (fn_id < 0) {
7382 				err = fn_id;
7383 				goto err_out;
7384 			}
7385 
7386 			/* point func_info record to a cloned FUNC type */
7387 			func_rec->type_id = fn_id;
7388 		}
7389 
7390 		/* create PTR -> STRUCT type chain to mark PTR_TO_CTX argument;
7391 		 * we do it just once per main BPF program, as all global
7392 		 * funcs share the same program type, so need only PTR ->
7393 		 * STRUCT type chain
7394 		 */
7395 		if (ptr_id == 0) {
7396 			struct_id = btf__add_struct(btf, ctx_name, 0);
7397 			ptr_id = btf__add_ptr(btf, struct_id);
7398 			if (ptr_id < 0 || struct_id < 0) {
7399 				err = -EINVAL;
7400 				goto err_out;
7401 			}
7402 		}
7403 
7404 		/* for completeness, clone DECL_TAG and point it to cloned param */
7405 		tag_id = btf__add_decl_tag(btf, ctx_tag, func_rec->type_id, arg_idx);
7406 		if (tag_id < 0) {
7407 			err = -EINVAL;
7408 			goto err_out;
7409 		}
7410 
7411 		/* all the BTF manipulations invalidated pointers, refetch them */
7412 		fn_t = btf_type_by_id(btf, func_rec->type_id);
7413 		fn_proto_t = btf_type_by_id(btf, fn_t->type);
7414 
7415 		/* fix up type ID pointed to by param */
7416 		p = &btf_params(fn_proto_t)[arg_idx];
7417 		p->type = ptr_id;
7418 	}
7419 
7420 	free(orig_ids);
7421 	return 0;
7422 err_out:
7423 	free(orig_ids);
7424 	return err;
7425 }
7426 
7427 static int bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
7428 {
7429 	struct bpf_program *prog;
7430 	size_t i, j;
7431 	int err;
7432 
7433 	if (obj->btf_ext) {
7434 		err = bpf_object__relocate_core(obj, targ_btf_path);
7435 		if (err) {
7436 			pr_warn("failed to perform CO-RE relocations: %s\n",
7437 				errstr(err));
7438 			return err;
7439 		}
7440 		bpf_object__sort_relos(obj);
7441 	}
7442 
7443 	/* place globals at the end of the arena (if supported) */
7444 	if (obj->arena_map_idx >= 0 && kernel_supports(obj, FEAT_LDIMM64_FULL_RANGE_OFF)) {
7445 		struct bpf_map *arena_map = &obj->maps[obj->arena_map_idx];
7446 
7447 		obj->arena_data_off = bpf_map_mmap_sz(arena_map) -
7448 				      roundup(obj->arena_data_sz, sysconf(_SC_PAGE_SIZE));
7449 	}
7450 
7451 	/* Before relocating calls pre-process relocations and mark
7452 	 * few ld_imm64 instructions that points to subprogs.
7453 	 * Otherwise bpf_object__reloc_code() later would have to consider
7454 	 * all ld_imm64 insns as relocation candidates. That would
7455 	 * reduce relocation speed, since amount of find_prog_insn_relo()
7456 	 * would increase and most of them will fail to find a relo.
7457 	 */
7458 	for (i = 0; i < obj->nr_programs; i++) {
7459 		prog = &obj->programs[i];
7460 		for (j = 0; j < prog->nr_reloc; j++) {
7461 			struct reloc_desc *relo = &prog->reloc_desc[j];
7462 			struct bpf_insn *insn = &prog->insns[relo->insn_idx];
7463 
7464 			/* mark the insn, so it's recognized by insn_is_pseudo_func() */
7465 			if (relo->type == RELO_SUBPROG_ADDR)
7466 				insn[0].src_reg = BPF_PSEUDO_FUNC;
7467 		}
7468 	}
7469 
7470 	/* relocate subprogram calls and append used subprograms to main
7471 	 * programs; each copy of subprogram code needs to be relocated
7472 	 * differently for each main program, because its code location might
7473 	 * have changed.
7474 	 * Append subprog relos to main programs to allow data relos to be
7475 	 * processed after text is completely relocated.
7476 	 */
7477 	for (i = 0; i < obj->nr_programs; i++) {
7478 		prog = &obj->programs[i];
7479 		/* sub-program's sub-calls are relocated within the context of
7480 		 * its main program only
7481 		 */
7482 		if (prog_is_subprog(obj, prog))
7483 			continue;
7484 		if (!prog->autoload)
7485 			continue;
7486 
7487 		err = bpf_object__relocate_calls(obj, prog);
7488 		if (err) {
7489 			pr_warn("prog '%s': failed to relocate calls: %s\n",
7490 				prog->name, errstr(err));
7491 			return err;
7492 		}
7493 
7494 		err = bpf_prog_assign_exc_cb(obj, prog);
7495 		if (err)
7496 			return err;
7497 		/* Now, also append exception callback if it has not been done already. */
7498 		if (prog->exception_cb_idx >= 0) {
7499 			struct bpf_program *subprog = &obj->programs[prog->exception_cb_idx];
7500 
7501 			/* Calling exception callback directly is disallowed, which the
7502 			 * verifier will reject later. In case it was processed already,
7503 			 * we can skip this step, otherwise for all other valid cases we
7504 			 * have to append exception callback now.
7505 			 */
7506 			if (subprog->sub_insn_off == 0) {
7507 				err = bpf_object__append_subprog_code(obj, prog, subprog);
7508 				if (err)
7509 					return err;
7510 				err = bpf_object__reloc_code(obj, prog, subprog);
7511 				if (err)
7512 					return err;
7513 			}
7514 		}
7515 	}
7516 	for (i = 0; i < obj->nr_programs; i++) {
7517 		prog = &obj->programs[i];
7518 		if (prog_is_subprog(obj, prog))
7519 			continue;
7520 		if (!prog->autoload)
7521 			continue;
7522 
7523 		/* Process data relos for main programs */
7524 		err = bpf_object__relocate_data(obj, prog);
7525 		if (err) {
7526 			pr_warn("prog '%s': failed to relocate data references: %s\n",
7527 				prog->name, errstr(err));
7528 			return err;
7529 		}
7530 
7531 		/* Fix up .BTF.ext information, if necessary */
7532 		err = bpf_program_fixup_func_info(obj, prog);
7533 		if (err) {
7534 			pr_warn("prog '%s': failed to perform .BTF.ext fix ups: %s\n",
7535 				prog->name, errstr(err));
7536 			return err;
7537 		}
7538 	}
7539 
7540 	return 0;
7541 }
7542 
7543 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
7544 					    Elf64_Shdr *shdr, Elf_Data *data);
7545 
7546 static int bpf_object__collect_map_relos(struct bpf_object *obj,
7547 					 Elf64_Shdr *shdr, Elf_Data *data)
7548 {
7549 	const int bpf_ptr_sz = 8, host_ptr_sz = sizeof(void *);
7550 	int i, j, nrels, new_sz;
7551 	const struct btf_var_secinfo *vi = NULL;
7552 	const struct btf_type *sec, *var, *def;
7553 	struct bpf_map *map = NULL, *targ_map = NULL;
7554 	struct bpf_program *targ_prog = NULL;
7555 	bool is_prog_array, is_map_in_map;
7556 	const struct btf_member *member;
7557 	const char *name, *mname, *type;
7558 	unsigned int moff;
7559 	Elf64_Sym *sym;
7560 	Elf64_Rel *rel;
7561 	void *tmp;
7562 
7563 	if (!obj->efile.btf_maps_sec_btf_id || !obj->btf)
7564 		return -EINVAL;
7565 	sec = btf__type_by_id(obj->btf, obj->efile.btf_maps_sec_btf_id);
7566 	if (!sec)
7567 		return -EINVAL;
7568 
7569 	nrels = shdr->sh_size / shdr->sh_entsize;
7570 	for (i = 0; i < nrels; i++) {
7571 		rel = elf_rel_by_idx(data, i);
7572 		if (!rel) {
7573 			pr_warn(".maps relo #%d: failed to get ELF relo\n", i);
7574 			return -LIBBPF_ERRNO__FORMAT;
7575 		}
7576 
7577 		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
7578 		if (!sym) {
7579 			pr_warn(".maps relo #%d: symbol %zx not found\n",
7580 				i, (size_t)ELF64_R_SYM(rel->r_info));
7581 			return -LIBBPF_ERRNO__FORMAT;
7582 		}
7583 		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
7584 
7585 		pr_debug(".maps relo #%d: for %zd value %zd rel->r_offset %zu name %d ('%s')\n",
7586 			 i, (ssize_t)(rel->r_info >> 32), (size_t)sym->st_value,
7587 			 (size_t)rel->r_offset, sym->st_name, name);
7588 
7589 		for (j = 0; j < obj->nr_maps; j++) {
7590 			map = &obj->maps[j];
7591 			if (map->sec_idx != obj->efile.btf_maps_shndx)
7592 				continue;
7593 
7594 			vi = btf_var_secinfos(sec) + map->btf_var_idx;
7595 			if (vi->offset <= rel->r_offset &&
7596 			    rel->r_offset + bpf_ptr_sz <= vi->offset + vi->size)
7597 				break;
7598 		}
7599 		if (j == obj->nr_maps) {
7600 			pr_warn(".maps relo #%d: cannot find map '%s' at rel->r_offset %zu\n",
7601 				i, name, (size_t)rel->r_offset);
7602 			return -EINVAL;
7603 		}
7604 
7605 		is_map_in_map = bpf_map_type__is_map_in_map(map->def.type);
7606 		is_prog_array = map->def.type == BPF_MAP_TYPE_PROG_ARRAY;
7607 		type = is_map_in_map ? "map" : "prog";
7608 		if (is_map_in_map) {
7609 			if (sym->st_shndx != obj->efile.btf_maps_shndx) {
7610 				pr_warn(".maps relo #%d: '%s' isn't a BTF-defined map\n",
7611 					i, name);
7612 				return -LIBBPF_ERRNO__RELOC;
7613 			}
7614 			if (map->def.type == BPF_MAP_TYPE_HASH_OF_MAPS &&
7615 			    map->def.key_size != sizeof(int)) {
7616 				pr_warn(".maps relo #%d: hash-of-maps '%s' should have key size %zu.\n",
7617 					i, map->name, sizeof(int));
7618 				return -EINVAL;
7619 			}
7620 			targ_map = bpf_object__find_map_by_name(obj, name);
7621 			if (!targ_map) {
7622 				pr_warn(".maps relo #%d: '%s' isn't a valid map reference\n",
7623 					i, name);
7624 				return -ESRCH;
7625 			}
7626 		} else if (is_prog_array) {
7627 			targ_prog = bpf_object__find_program_by_name(obj, name);
7628 			if (!targ_prog) {
7629 				pr_warn(".maps relo #%d: '%s' isn't a valid program reference\n",
7630 					i, name);
7631 				return -ESRCH;
7632 			}
7633 			if (targ_prog->sec_idx != sym->st_shndx ||
7634 			    targ_prog->sec_insn_off * 8 != sym->st_value ||
7635 			    prog_is_subprog(obj, targ_prog)) {
7636 				pr_warn(".maps relo #%d: '%s' isn't an entry-point program\n",
7637 					i, name);
7638 				return -LIBBPF_ERRNO__RELOC;
7639 			}
7640 		} else {
7641 			return -EINVAL;
7642 		}
7643 
7644 		var = btf__type_by_id(obj->btf, vi->type);
7645 		def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
7646 		if (btf_vlen(def) == 0)
7647 			return -EINVAL;
7648 		member = btf_members(def) + btf_vlen(def) - 1;
7649 		mname = btf__name_by_offset(obj->btf, member->name_off);
7650 		if (strcmp(mname, "values"))
7651 			return -EINVAL;
7652 
7653 		moff = btf_member_bit_offset(def, btf_vlen(def) - 1) / 8;
7654 		if (rel->r_offset - vi->offset < moff)
7655 			return -EINVAL;
7656 
7657 		moff = rel->r_offset - vi->offset - moff;
7658 		/* here we use BPF pointer size, which is always 64 bit, as we
7659 		 * are parsing ELF that was built for BPF target
7660 		 */
7661 		if (moff % bpf_ptr_sz)
7662 			return -EINVAL;
7663 		moff /= bpf_ptr_sz;
7664 		if (moff >= map->init_slots_sz) {
7665 			new_sz = moff + 1;
7666 			tmp = libbpf_reallocarray(map->init_slots, new_sz, host_ptr_sz);
7667 			if (!tmp)
7668 				return -ENOMEM;
7669 			map->init_slots = tmp;
7670 			memset(map->init_slots + map->init_slots_sz, 0,
7671 			       (new_sz - map->init_slots_sz) * host_ptr_sz);
7672 			map->init_slots_sz = new_sz;
7673 		}
7674 		map->init_slots[moff] = is_map_in_map ? (void *)targ_map : (void *)targ_prog;
7675 
7676 		pr_debug(".maps relo #%d: map '%s' slot [%d] points to %s '%s'\n",
7677 			 i, map->name, moff, type, name);
7678 	}
7679 
7680 	return 0;
7681 }
7682 
7683 static int bpf_object__collect_relos(struct bpf_object *obj)
7684 {
7685 	int i, err;
7686 
7687 	for (i = 0; i < obj->efile.sec_cnt; i++) {
7688 		struct elf_sec_desc *sec_desc = &obj->efile.secs[i];
7689 		Elf64_Shdr *shdr;
7690 		Elf_Data *data;
7691 		int idx;
7692 
7693 		if (sec_desc->sec_type != SEC_RELO)
7694 			continue;
7695 
7696 		shdr = sec_desc->shdr;
7697 		data = sec_desc->data;
7698 		idx = shdr->sh_info;
7699 
7700 		if (shdr->sh_type != SHT_REL || idx < 0 || idx >= obj->efile.sec_cnt) {
7701 			pr_warn("internal error at %d\n", __LINE__);
7702 			return -LIBBPF_ERRNO__INTERNAL;
7703 		}
7704 
7705 		if (obj->efile.secs[idx].sec_type == SEC_ST_OPS)
7706 			err = bpf_object__collect_st_ops_relos(obj, shdr, data);
7707 		else if (idx == obj->efile.btf_maps_shndx)
7708 			err = bpf_object__collect_map_relos(obj, shdr, data);
7709 		else
7710 			err = bpf_object__collect_prog_relos(obj, shdr, data);
7711 		if (err)
7712 			return err;
7713 	}
7714 
7715 	bpf_object__sort_relos(obj);
7716 	return 0;
7717 }
7718 
7719 static bool insn_is_helper_call(struct bpf_insn *insn, enum bpf_func_id *func_id)
7720 {
7721 	if (BPF_CLASS(insn->code) == BPF_JMP &&
7722 	    BPF_OP(insn->code) == BPF_CALL &&
7723 	    BPF_SRC(insn->code) == BPF_K &&
7724 	    insn->src_reg == 0 &&
7725 	    insn->dst_reg == 0) {
7726 		    *func_id = insn->imm;
7727 		    return true;
7728 	}
7729 	return false;
7730 }
7731 
7732 static int bpf_object__sanitize_prog(struct bpf_object *obj, struct bpf_program *prog)
7733 {
7734 	struct bpf_insn *insn = prog->insns;
7735 	enum bpf_func_id func_id;
7736 	int i;
7737 
7738 	if (obj->gen_loader)
7739 		return 0;
7740 
7741 	for (i = 0; i < prog->insns_cnt; i++, insn++) {
7742 		if (!insn_is_helper_call(insn, &func_id))
7743 			continue;
7744 
7745 		/* on kernels that don't yet support
7746 		 * bpf_probe_read_{kernel,user}[_str] helpers, fall back
7747 		 * to bpf_probe_read() which works well for old kernels
7748 		 */
7749 		switch (func_id) {
7750 		case BPF_FUNC_probe_read_kernel:
7751 		case BPF_FUNC_probe_read_user:
7752 			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
7753 				insn->imm = BPF_FUNC_probe_read;
7754 			break;
7755 		case BPF_FUNC_probe_read_kernel_str:
7756 		case BPF_FUNC_probe_read_user_str:
7757 			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
7758 				insn->imm = BPF_FUNC_probe_read_str;
7759 			break;
7760 		default:
7761 			break;
7762 		}
7763 	}
7764 	return 0;
7765 }
7766 
7767 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
7768 				     int *btf_obj_fd, int *btf_type_id);
7769 
7770 /* this is called as prog->sec_def->prog_prepare_load_fn for libbpf-supported sec_defs */
7771 static int libbpf_prepare_prog_load(struct bpf_program *prog,
7772 				    struct bpf_prog_load_opts *opts, long cookie)
7773 {
7774 	enum sec_def_flags def = cookie;
7775 
7776 	/* old kernels might not support specifying expected_attach_type */
7777 	if ((def & SEC_EXP_ATTACH_OPT) && !kernel_supports(prog->obj, FEAT_EXP_ATTACH_TYPE))
7778 		opts->expected_attach_type = 0;
7779 
7780 	if (def & SEC_SLEEPABLE)
7781 		opts->prog_flags |= BPF_F_SLEEPABLE;
7782 
7783 	if (prog->type == BPF_PROG_TYPE_XDP && (def & SEC_XDP_FRAGS))
7784 		opts->prog_flags |= BPF_F_XDP_HAS_FRAGS;
7785 
7786 	/* special check for usdt to use uprobe_multi link */
7787 	if ((def & SEC_USDT) && kernel_supports(prog->obj, FEAT_UPROBE_MULTI_LINK)) {
7788 		/* for BPF_TRACE_UPROBE_MULTI, user might want to query expected_attach_type
7789 		 * in prog, and expected_attach_type we set in kernel is from opts, so we
7790 		 * update both.
7791 		 */
7792 		prog->expected_attach_type = BPF_TRACE_UPROBE_MULTI;
7793 		opts->expected_attach_type = BPF_TRACE_UPROBE_MULTI;
7794 	}
7795 
7796 	if ((def & SEC_ATTACH_BTF) && !prog->attach_btf_id) {
7797 		int btf_obj_fd = 0, btf_type_id = 0, err;
7798 		const char *attach_name;
7799 
7800 		attach_name = strchr(prog->sec_name, '/');
7801 		if (!attach_name) {
7802 			/* if BPF program is annotated with just SEC("fentry")
7803 			 * (or similar) without declaratively specifying
7804 			 * target, then it is expected that target will be
7805 			 * specified with bpf_program__set_attach_target() at
7806 			 * runtime before BPF object load step. If not, then
7807 			 * there is nothing to load into the kernel as BPF
7808 			 * verifier won't be able to validate BPF program
7809 			 * correctness anyways.
7810 			 */
7811 			pr_warn("prog '%s': no BTF-based attach target is specified, use bpf_program__set_attach_target()\n",
7812 				prog->name);
7813 			return -EINVAL;
7814 		}
7815 		attach_name++; /* skip over / */
7816 
7817 		err = libbpf_find_attach_btf_id(prog, attach_name, &btf_obj_fd, &btf_type_id);
7818 		if (err)
7819 			return err;
7820 
7821 		/* cache resolved BTF FD and BTF type ID in the prog */
7822 		prog->attach_btf_obj_fd = btf_obj_fd;
7823 		prog->attach_btf_id = btf_type_id;
7824 
7825 		/* but by now libbpf common logic is not utilizing
7826 		 * prog->atach_btf_obj_fd/prog->attach_btf_id anymore because
7827 		 * this callback is called after opts were populated by
7828 		 * libbpf, so this callback has to update opts explicitly here
7829 		 */
7830 		opts->attach_btf_obj_fd = btf_obj_fd;
7831 		opts->attach_btf_id = btf_type_id;
7832 	}
7833 	return 0;
7834 }
7835 
7836 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz);
7837 
7838 static int bpf_object_load_prog(struct bpf_object *obj, struct bpf_program *prog,
7839 				struct bpf_insn *insns, int insns_cnt,
7840 				const char *license, __u32 kern_version, int *prog_fd)
7841 {
7842 	LIBBPF_OPTS(bpf_prog_load_opts, load_attr);
7843 	const char *prog_name = NULL;
7844 	size_t log_buf_size = 0;
7845 	char *log_buf = NULL, *tmp;
7846 	bool own_log_buf = true;
7847 	__u32 log_level = prog->log_level;
7848 	int ret, err;
7849 
7850 	/* Be more helpful by rejecting programs that can't be validated early
7851 	 * with more meaningful and actionable error message.
7852 	 */
7853 	switch (prog->type) {
7854 	case BPF_PROG_TYPE_UNSPEC:
7855 		/*
7856 		 * The program type must be set.  Most likely we couldn't find a proper
7857 		 * section definition at load time, and thus we didn't infer the type.
7858 		 */
7859 		pr_warn("prog '%s': missing BPF prog type, check ELF section name '%s'\n",
7860 			prog->name, prog->sec_name);
7861 		return -EINVAL;
7862 	case BPF_PROG_TYPE_STRUCT_OPS:
7863 		if (prog->attach_btf_id == 0) {
7864 			pr_warn("prog '%s': SEC(\"struct_ops\") program isn't referenced anywhere, did you forget to use it?\n",
7865 				prog->name);
7866 			return -EINVAL;
7867 		}
7868 		break;
7869 	default:
7870 		break;
7871 	}
7872 
7873 	if (!insns || !insns_cnt)
7874 		return -EINVAL;
7875 
7876 	if (kernel_supports(obj, FEAT_PROG_NAME))
7877 		prog_name = prog->name;
7878 	load_attr.attach_prog_fd = prog->attach_prog_fd;
7879 	load_attr.attach_btf_obj_fd = prog->attach_btf_obj_fd;
7880 	load_attr.attach_btf_id = prog->attach_btf_id;
7881 	load_attr.kern_version = kern_version;
7882 	load_attr.prog_ifindex = prog->prog_ifindex;
7883 	load_attr.expected_attach_type = prog->expected_attach_type;
7884 
7885 	/* specify func_info/line_info only if kernel supports them */
7886 	if (obj->btf && btf__fd(obj->btf) >= 0 && kernel_supports(obj, FEAT_BTF_FUNC)) {
7887 		load_attr.prog_btf_fd = btf__fd(obj->btf);
7888 		load_attr.func_info = prog->func_info;
7889 		load_attr.func_info_rec_size = prog->func_info_rec_size;
7890 		load_attr.func_info_cnt = prog->func_info_cnt;
7891 		load_attr.line_info = prog->line_info;
7892 		load_attr.line_info_rec_size = prog->line_info_rec_size;
7893 		load_attr.line_info_cnt = prog->line_info_cnt;
7894 	}
7895 	load_attr.log_level = log_level;
7896 	load_attr.prog_flags = prog->prog_flags;
7897 	load_attr.fd_array = obj->fd_array;
7898 
7899 	load_attr.token_fd = obj->token_fd;
7900 	if (obj->token_fd)
7901 		load_attr.prog_flags |= BPF_F_TOKEN_FD;
7902 
7903 	/* adjust load_attr if sec_def provides custom preload callback */
7904 	if (prog->sec_def && prog->sec_def->prog_prepare_load_fn) {
7905 		err = prog->sec_def->prog_prepare_load_fn(prog, &load_attr, prog->sec_def->cookie);
7906 		if (err < 0) {
7907 			pr_warn("prog '%s': failed to prepare load attributes: %s\n",
7908 				prog->name, errstr(err));
7909 			return err;
7910 		}
7911 		insns = prog->insns;
7912 		insns_cnt = prog->insns_cnt;
7913 	}
7914 
7915 	if (obj->gen_loader) {
7916 		bpf_gen__prog_load(obj->gen_loader, prog->type, prog->name,
7917 				   license, insns, insns_cnt, &load_attr,
7918 				   prog - obj->programs);
7919 		*prog_fd = -1;
7920 		return 0;
7921 	}
7922 
7923 retry_load:
7924 	/* if log_level is zero, we don't request logs initially even if
7925 	 * custom log_buf is specified; if the program load fails, then we'll
7926 	 * bump log_level to 1 and use either custom log_buf or we'll allocate
7927 	 * our own and retry the load to get details on what failed
7928 	 */
7929 	if (log_level) {
7930 		if (prog->log_buf) {
7931 			log_buf = prog->log_buf;
7932 			log_buf_size = prog->log_size;
7933 			own_log_buf = false;
7934 		} else if (obj->log_buf) {
7935 			log_buf = obj->log_buf;
7936 			log_buf_size = obj->log_size;
7937 			own_log_buf = false;
7938 		} else {
7939 			log_buf_size = max((size_t)BPF_LOG_BUF_SIZE, log_buf_size * 2);
7940 			tmp = realloc(log_buf, log_buf_size);
7941 			if (!tmp) {
7942 				ret = -ENOMEM;
7943 				goto out;
7944 			}
7945 			log_buf = tmp;
7946 			log_buf[0] = '\0';
7947 			own_log_buf = true;
7948 		}
7949 	}
7950 
7951 	load_attr.log_buf = log_buf;
7952 	load_attr.log_size = log_buf_size;
7953 	load_attr.log_level = log_level;
7954 
7955 	ret = bpf_prog_load(prog->type, prog_name, license, insns, insns_cnt, &load_attr);
7956 	if (ret >= 0) {
7957 		if (log_level && own_log_buf) {
7958 			pr_debug("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
7959 				 prog->name, log_buf);
7960 		}
7961 
7962 		if (obj->has_rodata && kernel_supports(obj, FEAT_PROG_BIND_MAP)) {
7963 			struct bpf_map *map;
7964 			int i;
7965 
7966 			for (i = 0; i < obj->nr_maps; i++) {
7967 				map = &prog->obj->maps[i];
7968 				if (map->libbpf_type != LIBBPF_MAP_RODATA)
7969 					continue;
7970 
7971 				if (bpf_prog_bind_map(ret, map->fd, NULL)) {
7972 					pr_warn("prog '%s': failed to bind map '%s': %s\n",
7973 						prog->name, map->real_name, errstr(errno));
7974 					/* Don't fail hard if can't bind rodata. */
7975 				}
7976 			}
7977 		}
7978 
7979 		*prog_fd = ret;
7980 		ret = 0;
7981 		goto out;
7982 	}
7983 
7984 	if (log_level == 0) {
7985 		log_level = 1;
7986 		goto retry_load;
7987 	}
7988 	/* On ENOSPC, increase log buffer size and retry, unless custom
7989 	 * log_buf is specified.
7990 	 * Be careful to not overflow u32, though. Kernel's log buf size limit
7991 	 * isn't part of UAPI so it can always be bumped to full 4GB. So don't
7992 	 * multiply by 2 unless we are sure we'll fit within 32 bits.
7993 	 * Currently, we'll get -EINVAL when we reach (UINT_MAX >> 2).
7994 	 */
7995 	if (own_log_buf && errno == ENOSPC && log_buf_size <= UINT_MAX / 2)
7996 		goto retry_load;
7997 
7998 	ret = -errno;
7999 
8000 	/* post-process verifier log to improve error descriptions */
8001 	fixup_verifier_log(prog, log_buf, log_buf_size);
8002 
8003 	pr_warn("prog '%s': BPF program load failed: %s\n", prog->name, errstr(errno));
8004 	pr_perm_msg(ret);
8005 
8006 	if (own_log_buf && log_buf && log_buf[0] != '\0') {
8007 		pr_warn("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
8008 			prog->name, log_buf);
8009 	}
8010 
8011 out:
8012 	if (own_log_buf)
8013 		free(log_buf);
8014 	return ret;
8015 }
8016 
8017 static char *find_prev_line(char *buf, char *cur)
8018 {
8019 	char *p;
8020 
8021 	if (cur == buf) /* end of a log buf */
8022 		return NULL;
8023 
8024 	p = cur - 1;
8025 	while (p - 1 >= buf && *(p - 1) != '\n')
8026 		p--;
8027 
8028 	return p;
8029 }
8030 
8031 static void patch_log(char *buf, size_t buf_sz, size_t log_sz,
8032 		      char *orig, size_t orig_sz, const char *patch)
8033 {
8034 	/* size of the remaining log content to the right from the to-be-replaced part */
8035 	size_t rem_sz = (buf + log_sz) - (orig + orig_sz);
8036 	size_t patch_sz = strlen(patch);
8037 
8038 	if (patch_sz != orig_sz) {
8039 		/* If patch line(s) are longer than original piece of verifier log,
8040 		 * shift log contents by (patch_sz - orig_sz) bytes to the right
8041 		 * starting from after to-be-replaced part of the log.
8042 		 *
8043 		 * If patch line(s) are shorter than original piece of verifier log,
8044 		 * shift log contents by (orig_sz - patch_sz) bytes to the left
8045 		 * starting from after to-be-replaced part of the log
8046 		 *
8047 		 * We need to be careful about not overflowing available
8048 		 * buf_sz capacity. If that's the case, we'll truncate the end
8049 		 * of the original log, as necessary.
8050 		 */
8051 		if (patch_sz > orig_sz) {
8052 			if (orig + patch_sz >= buf + buf_sz) {
8053 				/* patch is big enough to cover remaining space completely */
8054 				patch_sz -= (orig + patch_sz) - (buf + buf_sz) + 1;
8055 				rem_sz = 0;
8056 			} else if (patch_sz - orig_sz > buf_sz - log_sz) {
8057 				/* patch causes part of remaining log to be truncated */
8058 				rem_sz -= (patch_sz - orig_sz) - (buf_sz - log_sz);
8059 			}
8060 		}
8061 		/* shift remaining log to the right by calculated amount */
8062 		memmove(orig + patch_sz, orig + orig_sz, rem_sz);
8063 	}
8064 
8065 	memcpy(orig, patch, patch_sz);
8066 }
8067 
8068 static void fixup_log_failed_core_relo(struct bpf_program *prog,
8069 				       char *buf, size_t buf_sz, size_t log_sz,
8070 				       char *line1, char *line2, char *line3)
8071 {
8072 	/* Expected log for failed and not properly guarded CO-RE relocation:
8073 	 * line1 -> 123: (85) call unknown#195896080
8074 	 * line2 -> invalid func unknown#195896080
8075 	 * line3 -> <anything else or end of buffer>
8076 	 *
8077 	 * "123" is the index of the instruction that was poisoned. We extract
8078 	 * instruction index to find corresponding CO-RE relocation and
8079 	 * replace this part of the log with more relevant information about
8080 	 * failed CO-RE relocation.
8081 	 */
8082 	const struct bpf_core_relo *relo;
8083 	struct bpf_core_spec spec;
8084 	char patch[512], spec_buf[256];
8085 	int insn_idx, err, spec_len;
8086 
8087 	if (sscanf(line1, "%d: (%*d) call unknown#195896080\n", &insn_idx) != 1)
8088 		return;
8089 
8090 	relo = find_relo_core(prog, insn_idx);
8091 	if (!relo)
8092 		return;
8093 
8094 	err = bpf_core_parse_spec(prog->name, prog->obj->btf, relo, &spec);
8095 	if (err)
8096 		return;
8097 
8098 	spec_len = bpf_core_format_spec(spec_buf, sizeof(spec_buf), &spec);
8099 	snprintf(patch, sizeof(patch),
8100 		 "%d: <invalid CO-RE relocation>\n"
8101 		 "failed to resolve CO-RE relocation %s%s\n",
8102 		 insn_idx, spec_buf, spec_len >= sizeof(spec_buf) ? "..." : "");
8103 
8104 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
8105 }
8106 
8107 static void fixup_log_missing_map_load(struct bpf_program *prog,
8108 				       char *buf, size_t buf_sz, size_t log_sz,
8109 				       char *line1, char *line2, char *line3)
8110 {
8111 	/* Expected log for failed and not properly guarded map reference:
8112 	 * line1 -> 123: (85) call unknown#2001000345
8113 	 * line2 -> invalid func unknown#2001000345
8114 	 * line3 -> <anything else or end of buffer>
8115 	 *
8116 	 * "123" is the index of the instruction that was poisoned.
8117 	 * "345" in "2001000345" is a map index in obj->maps to fetch map name.
8118 	 */
8119 	struct bpf_object *obj = prog->obj;
8120 	const struct bpf_map *map;
8121 	int insn_idx, map_idx;
8122 	char patch[128];
8123 
8124 	if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &map_idx) != 2)
8125 		return;
8126 
8127 	map_idx -= POISON_LDIMM64_MAP_BASE;
8128 	if (map_idx < 0 || map_idx >= obj->nr_maps)
8129 		return;
8130 	map = &obj->maps[map_idx];
8131 
8132 	snprintf(patch, sizeof(patch),
8133 		 "%d: <invalid BPF map reference>\n"
8134 		 "BPF map '%s' is referenced but wasn't created\n",
8135 		 insn_idx, map->name);
8136 
8137 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
8138 }
8139 
8140 static void fixup_log_missing_kfunc_call(struct bpf_program *prog,
8141 					 char *buf, size_t buf_sz, size_t log_sz,
8142 					 char *line1, char *line2, char *line3)
8143 {
8144 	/* Expected log for failed and not properly guarded kfunc call:
8145 	 * line1 -> 123: (85) call unknown#2002000345
8146 	 * line2 -> invalid func unknown#2002000345
8147 	 * line3 -> <anything else or end of buffer>
8148 	 *
8149 	 * "123" is the index of the instruction that was poisoned.
8150 	 * "345" in "2002000345" is an extern index in obj->externs to fetch kfunc name.
8151 	 */
8152 	struct bpf_object *obj = prog->obj;
8153 	const struct extern_desc *ext;
8154 	int insn_idx, ext_idx;
8155 	char patch[128];
8156 
8157 	if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &ext_idx) != 2)
8158 		return;
8159 
8160 	ext_idx -= POISON_CALL_KFUNC_BASE;
8161 	if (ext_idx < 0 || ext_idx >= obj->nr_extern)
8162 		return;
8163 	ext = &obj->externs[ext_idx];
8164 
8165 	snprintf(patch, sizeof(patch),
8166 		 "%d: <invalid kfunc call>\n"
8167 		 "kfunc '%s' is referenced but wasn't resolved\n",
8168 		 insn_idx, ext->name);
8169 
8170 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
8171 }
8172 
8173 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz)
8174 {
8175 	/* look for familiar error patterns in last N lines of the log */
8176 	const size_t max_last_line_cnt = 10;
8177 	char *prev_line, *cur_line, *next_line;
8178 	size_t log_sz;
8179 	int i;
8180 
8181 	if (!buf)
8182 		return;
8183 
8184 	log_sz = strlen(buf) + 1;
8185 	next_line = buf + log_sz - 1;
8186 
8187 	for (i = 0; i < max_last_line_cnt; i++, next_line = cur_line) {
8188 		cur_line = find_prev_line(buf, next_line);
8189 		if (!cur_line)
8190 			return;
8191 
8192 		if (str_has_pfx(cur_line, "invalid func unknown#195896080\n")) {
8193 			prev_line = find_prev_line(buf, cur_line);
8194 			if (!prev_line)
8195 				continue;
8196 
8197 			/* failed CO-RE relocation case */
8198 			fixup_log_failed_core_relo(prog, buf, buf_sz, log_sz,
8199 						   prev_line, cur_line, next_line);
8200 			return;
8201 		} else if (str_has_pfx(cur_line, "invalid func unknown#"POISON_LDIMM64_MAP_PFX)) {
8202 			prev_line = find_prev_line(buf, cur_line);
8203 			if (!prev_line)
8204 				continue;
8205 
8206 			/* reference to uncreated BPF map */
8207 			fixup_log_missing_map_load(prog, buf, buf_sz, log_sz,
8208 						   prev_line, cur_line, next_line);
8209 			return;
8210 		} else if (str_has_pfx(cur_line, "invalid func unknown#"POISON_CALL_KFUNC_PFX)) {
8211 			prev_line = find_prev_line(buf, cur_line);
8212 			if (!prev_line)
8213 				continue;
8214 
8215 			/* reference to unresolved kfunc */
8216 			fixup_log_missing_kfunc_call(prog, buf, buf_sz, log_sz,
8217 						     prev_line, cur_line, next_line);
8218 			return;
8219 		}
8220 	}
8221 }
8222 
8223 static int bpf_program_record_relos(struct bpf_program *prog)
8224 {
8225 	struct bpf_object *obj = prog->obj;
8226 	int i;
8227 
8228 	for (i = 0; i < prog->nr_reloc; i++) {
8229 		struct reloc_desc *relo = &prog->reloc_desc[i];
8230 		struct extern_desc *ext = &obj->externs[relo->ext_idx];
8231 		int kind;
8232 
8233 		switch (relo->type) {
8234 		case RELO_EXTERN_LD64:
8235 			if (ext->type != EXT_KSYM)
8236 				continue;
8237 			kind = btf_is_var(btf__type_by_id(obj->btf, ext->btf_id)) ?
8238 				BTF_KIND_VAR : BTF_KIND_FUNC;
8239 			bpf_gen__record_extern(obj->gen_loader, ext->name,
8240 					       ext->is_weak, !ext->ksym.type_id,
8241 					       true, kind, relo->insn_idx);
8242 			break;
8243 		case RELO_EXTERN_CALL:
8244 			bpf_gen__record_extern(obj->gen_loader, ext->name,
8245 					       ext->is_weak, false, false, BTF_KIND_FUNC,
8246 					       relo->insn_idx);
8247 			break;
8248 		case RELO_CORE: {
8249 			struct bpf_core_relo cr = {
8250 				.insn_off = relo->insn_idx * 8,
8251 				.type_id = relo->core_relo->type_id,
8252 				.access_str_off = relo->core_relo->access_str_off,
8253 				.kind = relo->core_relo->kind,
8254 			};
8255 
8256 			bpf_gen__record_relo_core(obj->gen_loader, &cr);
8257 			break;
8258 		}
8259 		default:
8260 			continue;
8261 		}
8262 	}
8263 	return 0;
8264 }
8265 
8266 static int
8267 bpf_object__load_progs(struct bpf_object *obj, int log_level)
8268 {
8269 	struct bpf_program *prog;
8270 	size_t i;
8271 	int err;
8272 
8273 	for (i = 0; i < obj->nr_programs; i++) {
8274 		prog = &obj->programs[i];
8275 		if (prog_is_subprog(obj, prog))
8276 			continue;
8277 		if (!prog->autoload) {
8278 			pr_debug("prog '%s': skipped loading\n", prog->name);
8279 			continue;
8280 		}
8281 		prog->log_level |= log_level;
8282 
8283 		if (obj->gen_loader)
8284 			bpf_program_record_relos(prog);
8285 
8286 		err = bpf_object_load_prog(obj, prog, prog->insns, prog->insns_cnt,
8287 					   obj->license, obj->kern_version, &prog->fd);
8288 		if (err) {
8289 			pr_warn("prog '%s': failed to load: %s\n", prog->name, errstr(err));
8290 			return err;
8291 		}
8292 	}
8293 
8294 	bpf_object__free_relocs(obj);
8295 	return 0;
8296 }
8297 
8298 static int bpf_object_prepare_progs(struct bpf_object *obj)
8299 {
8300 	struct bpf_program *prog;
8301 	size_t i;
8302 	int err;
8303 
8304 	for (i = 0; i < obj->nr_programs; i++) {
8305 		prog = &obj->programs[i];
8306 		err = bpf_object__sanitize_prog(obj, prog);
8307 		if (err)
8308 			return err;
8309 	}
8310 	return 0;
8311 }
8312 
8313 static const struct bpf_sec_def *find_sec_def(const char *sec_name);
8314 
8315 static int bpf_object_init_progs(struct bpf_object *obj, const struct bpf_object_open_opts *opts)
8316 {
8317 	struct bpf_program *prog;
8318 	int err;
8319 
8320 	bpf_object__for_each_program(prog, obj) {
8321 		prog->sec_def = find_sec_def(prog->sec_name);
8322 		if (!prog->sec_def) {
8323 			/* couldn't guess, but user might manually specify */
8324 			pr_debug("prog '%s': unrecognized ELF section name '%s'\n",
8325 				prog->name, prog->sec_name);
8326 			continue;
8327 		}
8328 
8329 		prog->type = prog->sec_def->prog_type;
8330 		prog->expected_attach_type = prog->sec_def->expected_attach_type;
8331 
8332 		/* sec_def can have custom callback which should be called
8333 		 * after bpf_program is initialized to adjust its properties
8334 		 */
8335 		if (prog->sec_def->prog_setup_fn) {
8336 			err = prog->sec_def->prog_setup_fn(prog, prog->sec_def->cookie);
8337 			if (err < 0) {
8338 				pr_warn("prog '%s': failed to initialize: %s\n",
8339 					prog->name, errstr(err));
8340 				return err;
8341 			}
8342 		}
8343 	}
8344 
8345 	return 0;
8346 }
8347 
8348 static struct bpf_object *bpf_object_open(const char *path, const void *obj_buf, size_t obj_buf_sz,
8349 					  const char *obj_name,
8350 					  const struct bpf_object_open_opts *opts)
8351 {
8352 	const char *kconfig, *btf_tmp_path, *token_path;
8353 	struct bpf_object *obj;
8354 	int err;
8355 	char *log_buf;
8356 	size_t log_size;
8357 	__u32 log_level;
8358 
8359 	if (obj_buf && !obj_name)
8360 		return ERR_PTR(-EINVAL);
8361 
8362 	if (elf_version(EV_CURRENT) == EV_NONE) {
8363 		pr_warn("failed to init libelf for %s\n",
8364 			path ? : "(mem buf)");
8365 		return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
8366 	}
8367 
8368 	if (!OPTS_VALID(opts, bpf_object_open_opts))
8369 		return ERR_PTR(-EINVAL);
8370 
8371 	obj_name = OPTS_GET(opts, object_name, NULL) ?: obj_name;
8372 	if (obj_buf) {
8373 		path = obj_name;
8374 		pr_debug("loading object '%s' from buffer\n", obj_name);
8375 	} else {
8376 		pr_debug("loading object from %s\n", path);
8377 	}
8378 
8379 	log_buf = OPTS_GET(opts, kernel_log_buf, NULL);
8380 	log_size = OPTS_GET(opts, kernel_log_size, 0);
8381 	log_level = OPTS_GET(opts, kernel_log_level, 0);
8382 	if (log_size > UINT_MAX)
8383 		return ERR_PTR(-EINVAL);
8384 	if (log_size && !log_buf)
8385 		return ERR_PTR(-EINVAL);
8386 
8387 	token_path = OPTS_GET(opts, bpf_token_path, NULL);
8388 	/* if user didn't specify bpf_token_path explicitly, check if
8389 	 * LIBBPF_BPF_TOKEN_PATH envvar was set and treat it as bpf_token_path
8390 	 * option
8391 	 */
8392 	if (!token_path)
8393 		token_path = getenv("LIBBPF_BPF_TOKEN_PATH");
8394 	if (token_path && strlen(token_path) >= PATH_MAX)
8395 		return ERR_PTR(-ENAMETOOLONG);
8396 
8397 	obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
8398 	if (IS_ERR(obj))
8399 		return obj;
8400 
8401 	obj->log_buf = log_buf;
8402 	obj->log_size = log_size;
8403 	obj->log_level = log_level;
8404 
8405 	if (token_path) {
8406 		obj->token_path = strdup(token_path);
8407 		if (!obj->token_path) {
8408 			err = -ENOMEM;
8409 			goto out;
8410 		}
8411 	}
8412 
8413 	btf_tmp_path = OPTS_GET(opts, btf_custom_path, NULL);
8414 	if (btf_tmp_path) {
8415 		if (strlen(btf_tmp_path) >= PATH_MAX) {
8416 			err = -ENAMETOOLONG;
8417 			goto out;
8418 		}
8419 		obj->btf_custom_path = strdup(btf_tmp_path);
8420 		if (!obj->btf_custom_path) {
8421 			err = -ENOMEM;
8422 			goto out;
8423 		}
8424 	}
8425 
8426 	kconfig = OPTS_GET(opts, kconfig, NULL);
8427 	if (kconfig) {
8428 		obj->kconfig = strdup(kconfig);
8429 		if (!obj->kconfig) {
8430 			err = -ENOMEM;
8431 			goto out;
8432 		}
8433 	}
8434 
8435 	err = bpf_object__elf_init(obj);
8436 	err = err ? : bpf_object__elf_collect(obj);
8437 	err = err ? : bpf_object__collect_externs(obj);
8438 	err = err ? : bpf_object_fixup_btf(obj);
8439 	err = err ? : bpf_object__init_maps(obj, opts);
8440 	err = err ? : bpf_object_init_progs(obj, opts);
8441 	err = err ? : bpf_object__collect_relos(obj);
8442 	if (err)
8443 		goto out;
8444 
8445 	bpf_object__elf_finish(obj);
8446 
8447 	return obj;
8448 out:
8449 	bpf_object__close(obj);
8450 	return ERR_PTR(err);
8451 }
8452 
8453 struct bpf_object *
8454 bpf_object__open_file(const char *path, const struct bpf_object_open_opts *opts)
8455 {
8456 	if (!path)
8457 		return libbpf_err_ptr(-EINVAL);
8458 
8459 	return libbpf_ptr(bpf_object_open(path, NULL, 0, NULL, opts));
8460 }
8461 
8462 struct bpf_object *bpf_object__open(const char *path)
8463 {
8464 	return bpf_object__open_file(path, NULL);
8465 }
8466 
8467 struct bpf_object *
8468 bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
8469 		     const struct bpf_object_open_opts *opts)
8470 {
8471 	char tmp_name[64];
8472 
8473 	if (!obj_buf || obj_buf_sz == 0)
8474 		return libbpf_err_ptr(-EINVAL);
8475 
8476 	/* create a (quite useless) default "name" for this memory buffer object */
8477 	snprintf(tmp_name, sizeof(tmp_name), "%lx-%zx", (unsigned long)obj_buf, obj_buf_sz);
8478 
8479 	return libbpf_ptr(bpf_object_open(NULL, obj_buf, obj_buf_sz, tmp_name, opts));
8480 }
8481 
8482 static int bpf_object_unload(struct bpf_object *obj)
8483 {
8484 	size_t i;
8485 
8486 	if (!obj)
8487 		return libbpf_err(-EINVAL);
8488 
8489 	for (i = 0; i < obj->nr_maps; i++) {
8490 		zclose(obj->maps[i].fd);
8491 		if (obj->maps[i].st_ops)
8492 			zfree(&obj->maps[i].st_ops->kern_vdata);
8493 	}
8494 
8495 	for (i = 0; i < obj->nr_programs; i++)
8496 		bpf_program__unload(&obj->programs[i]);
8497 
8498 	return 0;
8499 }
8500 
8501 static int bpf_object__sanitize_maps(struct bpf_object *obj)
8502 {
8503 	struct bpf_map *m;
8504 
8505 	bpf_object__for_each_map(m, obj) {
8506 		if (!bpf_map__is_internal(m))
8507 			continue;
8508 		if (!kernel_supports(obj, FEAT_ARRAY_MMAP))
8509 			m->def.map_flags &= ~BPF_F_MMAPABLE;
8510 	}
8511 
8512 	return 0;
8513 }
8514 
8515 typedef int (*kallsyms_cb_t)(unsigned long long sym_addr, char sym_type,
8516 			     const char *sym_name, void *ctx);
8517 
8518 static int libbpf_kallsyms_parse(kallsyms_cb_t cb, void *ctx)
8519 {
8520 	char sym_type, sym_name[500];
8521 	unsigned long long sym_addr;
8522 	int ret, err = 0;
8523 	FILE *f;
8524 
8525 	f = fopen("/proc/kallsyms", "re");
8526 	if (!f) {
8527 		err = -errno;
8528 		pr_warn("failed to open /proc/kallsyms: %s\n", errstr(err));
8529 		return err;
8530 	}
8531 
8532 	while (true) {
8533 		ret = fscanf(f, "%llx %c %499s%*[^\n]\n",
8534 			     &sym_addr, &sym_type, sym_name);
8535 		if (ret == EOF && feof(f))
8536 			break;
8537 		if (ret != 3) {
8538 			pr_warn("failed to read kallsyms entry: %d\n", ret);
8539 			err = -EINVAL;
8540 			break;
8541 		}
8542 
8543 		err = cb(sym_addr, sym_type, sym_name, ctx);
8544 		if (err)
8545 			break;
8546 	}
8547 
8548 	fclose(f);
8549 	return err;
8550 }
8551 
8552 static int kallsyms_cb(unsigned long long sym_addr, char sym_type,
8553 		       const char *sym_name, void *ctx)
8554 {
8555 	struct bpf_object *obj = ctx;
8556 	const struct btf_type *t;
8557 	struct extern_desc *ext;
8558 	const char *res;
8559 
8560 	res = strstr(sym_name, ".llvm.");
8561 	if (sym_type == 'd' && res)
8562 		ext = find_extern_by_name_with_len(obj, sym_name, res - sym_name);
8563 	else
8564 		ext = find_extern_by_name(obj, sym_name);
8565 	if (!ext || ext->type != EXT_KSYM)
8566 		return 0;
8567 
8568 	t = btf__type_by_id(obj->btf, ext->btf_id);
8569 	if (!btf_is_var(t))
8570 		return 0;
8571 
8572 	if (ext->is_set && ext->ksym.addr != sym_addr) {
8573 		pr_warn("extern (ksym) '%s': resolution is ambiguous: 0x%llx or 0x%llx\n",
8574 			sym_name, ext->ksym.addr, sym_addr);
8575 		return -EINVAL;
8576 	}
8577 	if (!ext->is_set) {
8578 		ext->is_set = true;
8579 		ext->ksym.addr = sym_addr;
8580 		pr_debug("extern (ksym) '%s': set to 0x%llx\n", sym_name, sym_addr);
8581 	}
8582 	return 0;
8583 }
8584 
8585 static int bpf_object__read_kallsyms_file(struct bpf_object *obj)
8586 {
8587 	return libbpf_kallsyms_parse(kallsyms_cb, obj);
8588 }
8589 
8590 static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
8591 			    __u16 kind, struct btf **res_btf,
8592 			    struct module_btf **res_mod_btf)
8593 {
8594 	struct module_btf *mod_btf;
8595 	struct btf *btf;
8596 	int i, id, err;
8597 
8598 	btf = obj->btf_vmlinux;
8599 	mod_btf = NULL;
8600 	id = btf__find_by_name_kind(btf, ksym_name, kind);
8601 
8602 	if (id == -ENOENT) {
8603 		err = load_module_btfs(obj);
8604 		if (err)
8605 			return err;
8606 
8607 		for (i = 0; i < obj->btf_module_cnt; i++) {
8608 			/* we assume module_btf's BTF FD is always >0 */
8609 			mod_btf = &obj->btf_modules[i];
8610 			btf = mod_btf->btf;
8611 			id = btf__find_by_name_kind_own(btf, ksym_name, kind);
8612 			if (id != -ENOENT)
8613 				break;
8614 		}
8615 	}
8616 	if (id <= 0)
8617 		return -ESRCH;
8618 
8619 	*res_btf = btf;
8620 	*res_mod_btf = mod_btf;
8621 	return id;
8622 }
8623 
8624 static int bpf_object__resolve_ksym_var_btf_id(struct bpf_object *obj,
8625 					       struct extern_desc *ext)
8626 {
8627 	const struct btf_type *targ_var, *targ_type;
8628 	__u32 targ_type_id, local_type_id;
8629 	struct module_btf *mod_btf = NULL;
8630 	const char *targ_var_name;
8631 	struct btf *btf = NULL;
8632 	int id, err;
8633 
8634 	id = find_ksym_btf_id(obj, ext->name, BTF_KIND_VAR, &btf, &mod_btf);
8635 	if (id < 0) {
8636 		if (id == -ESRCH && ext->is_weak)
8637 			return 0;
8638 		pr_warn("extern (var ksym) '%s': not found in kernel BTF\n",
8639 			ext->name);
8640 		return id;
8641 	}
8642 
8643 	/* find local type_id */
8644 	local_type_id = ext->ksym.type_id;
8645 
8646 	/* find target type_id */
8647 	targ_var = btf__type_by_id(btf, id);
8648 	targ_var_name = btf__name_by_offset(btf, targ_var->name_off);
8649 	targ_type = skip_mods_and_typedefs(btf, targ_var->type, &targ_type_id);
8650 
8651 	err = bpf_core_types_are_compat(obj->btf, local_type_id,
8652 					btf, targ_type_id);
8653 	if (err <= 0) {
8654 		const struct btf_type *local_type;
8655 		const char *targ_name, *local_name;
8656 
8657 		local_type = btf__type_by_id(obj->btf, local_type_id);
8658 		local_name = btf__name_by_offset(obj->btf, local_type->name_off);
8659 		targ_name = btf__name_by_offset(btf, targ_type->name_off);
8660 
8661 		pr_warn("extern (var ksym) '%s': incompatible types, expected [%d] %s %s, but kernel has [%d] %s %s\n",
8662 			ext->name, local_type_id,
8663 			btf_kind_str(local_type), local_name, targ_type_id,
8664 			btf_kind_str(targ_type), targ_name);
8665 		return -EINVAL;
8666 	}
8667 
8668 	ext->is_set = true;
8669 	ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
8670 	ext->ksym.kernel_btf_id = id;
8671 	pr_debug("extern (var ksym) '%s': resolved to [%d] %s %s\n",
8672 		 ext->name, id, btf_kind_str(targ_var), targ_var_name);
8673 
8674 	return 0;
8675 }
8676 
8677 static int bpf_object__resolve_ksym_func_btf_id(struct bpf_object *obj,
8678 						struct extern_desc *ext)
8679 {
8680 	int local_func_proto_id, kfunc_proto_id, kfunc_id;
8681 	struct module_btf *mod_btf = NULL;
8682 	const struct btf_type *kern_func;
8683 	struct btf *kern_btf = NULL;
8684 	int ret;
8685 
8686 	local_func_proto_id = ext->ksym.type_id;
8687 
8688 	kfunc_id = find_ksym_btf_id(obj, ext->essent_name ?: ext->name, BTF_KIND_FUNC, &kern_btf,
8689 				    &mod_btf);
8690 	if (kfunc_id < 0) {
8691 		if (kfunc_id == -ESRCH && ext->is_weak)
8692 			return 0;
8693 		pr_warn("extern (func ksym) '%s': not found in kernel or module BTFs\n",
8694 			ext->name);
8695 		return kfunc_id;
8696 	}
8697 
8698 	kern_func = btf__type_by_id(kern_btf, kfunc_id);
8699 	kfunc_proto_id = kern_func->type;
8700 
8701 	ret = bpf_core_types_are_compat(obj->btf, local_func_proto_id,
8702 					kern_btf, kfunc_proto_id);
8703 	if (ret <= 0) {
8704 		if (ext->is_weak)
8705 			return 0;
8706 
8707 		pr_warn("extern (func ksym) '%s': func_proto [%d] incompatible with %s [%d]\n",
8708 			ext->name, local_func_proto_id,
8709 			mod_btf ? mod_btf->name : "vmlinux", kfunc_proto_id);
8710 		return -EINVAL;
8711 	}
8712 
8713 	/* set index for module BTF fd in fd_array, if unset */
8714 	if (mod_btf && !mod_btf->fd_array_idx) {
8715 		/* insn->off is s16 */
8716 		if (obj->fd_array_cnt == INT16_MAX) {
8717 			pr_warn("extern (func ksym) '%s': module BTF fd index %d too big to fit in bpf_insn offset\n",
8718 				ext->name, mod_btf->fd_array_idx);
8719 			return -E2BIG;
8720 		}
8721 		/* Cannot use index 0 for module BTF fd */
8722 		if (!obj->fd_array_cnt)
8723 			obj->fd_array_cnt = 1;
8724 
8725 		ret = libbpf_ensure_mem((void **)&obj->fd_array, &obj->fd_array_cap, sizeof(int),
8726 					obj->fd_array_cnt + 1);
8727 		if (ret)
8728 			return ret;
8729 		mod_btf->fd_array_idx = obj->fd_array_cnt;
8730 		/* we assume module BTF FD is always >0 */
8731 		obj->fd_array[obj->fd_array_cnt++] = mod_btf->fd;
8732 	}
8733 
8734 	ext->is_set = true;
8735 	ext->ksym.kernel_btf_id = kfunc_id;
8736 	ext->ksym.btf_fd_idx = mod_btf ? mod_btf->fd_array_idx : 0;
8737 	/* Also set kernel_btf_obj_fd to make sure that bpf_object__relocate_data()
8738 	 * populates FD into ld_imm64 insn when it's used to point to kfunc.
8739 	 * {kernel_btf_id, btf_fd_idx} -> fixup bpf_call.
8740 	 * {kernel_btf_id, kernel_btf_obj_fd} -> fixup ld_imm64.
8741 	 */
8742 	ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
8743 	pr_debug("extern (func ksym) '%s': resolved to %s [%d]\n",
8744 		 ext->name, mod_btf ? mod_btf->name : "vmlinux", kfunc_id);
8745 
8746 	return 0;
8747 }
8748 
8749 static int bpf_object__resolve_ksyms_btf_id(struct bpf_object *obj)
8750 {
8751 	const struct btf_type *t;
8752 	struct extern_desc *ext;
8753 	int i, err;
8754 
8755 	for (i = 0; i < obj->nr_extern; i++) {
8756 		ext = &obj->externs[i];
8757 		if (ext->type != EXT_KSYM || !ext->ksym.type_id)
8758 			continue;
8759 
8760 		if (obj->gen_loader) {
8761 			ext->is_set = true;
8762 			ext->ksym.kernel_btf_obj_fd = 0;
8763 			ext->ksym.kernel_btf_id = 0;
8764 			continue;
8765 		}
8766 		t = btf__type_by_id(obj->btf, ext->btf_id);
8767 		if (btf_is_var(t))
8768 			err = bpf_object__resolve_ksym_var_btf_id(obj, ext);
8769 		else
8770 			err = bpf_object__resolve_ksym_func_btf_id(obj, ext);
8771 		if (err)
8772 			return err;
8773 	}
8774 	return 0;
8775 }
8776 
8777 static int bpf_object__resolve_externs(struct bpf_object *obj,
8778 				       const char *extra_kconfig)
8779 {
8780 	bool need_config = false, need_kallsyms = false;
8781 	bool need_vmlinux_btf = false;
8782 	struct extern_desc *ext;
8783 	void *kcfg_data = NULL;
8784 	int err, i;
8785 
8786 	if (obj->nr_extern == 0)
8787 		return 0;
8788 
8789 	if (obj->kconfig_map_idx >= 0)
8790 		kcfg_data = obj->maps[obj->kconfig_map_idx].mmaped;
8791 
8792 	for (i = 0; i < obj->nr_extern; i++) {
8793 		ext = &obj->externs[i];
8794 
8795 		if (ext->type == EXT_KSYM) {
8796 			if (ext->ksym.type_id)
8797 				need_vmlinux_btf = true;
8798 			else
8799 				need_kallsyms = true;
8800 			continue;
8801 		} else if (ext->type == EXT_KCFG) {
8802 			void *ext_ptr = kcfg_data + ext->kcfg.data_off;
8803 			__u64 value = 0;
8804 
8805 			/* Kconfig externs need actual /proc/config.gz */
8806 			if (str_has_pfx(ext->name, "CONFIG_")) {
8807 				need_config = true;
8808 				continue;
8809 			}
8810 
8811 			/* Virtual kcfg externs are customly handled by libbpf */
8812 			if (strcmp(ext->name, "LINUX_KERNEL_VERSION") == 0) {
8813 				value = get_kernel_version();
8814 				if (!value) {
8815 					pr_warn("extern (kcfg) '%s': failed to get kernel version\n", ext->name);
8816 					return -EINVAL;
8817 				}
8818 			} else if (strcmp(ext->name, "LINUX_HAS_BPF_COOKIE") == 0) {
8819 				value = kernel_supports(obj, FEAT_BPF_COOKIE);
8820 			} else if (strcmp(ext->name, "LINUX_HAS_SYSCALL_WRAPPER") == 0) {
8821 				value = kernel_supports(obj, FEAT_SYSCALL_WRAPPER);
8822 			} else if (!str_has_pfx(ext->name, "LINUX_") || !ext->is_weak) {
8823 				/* Currently libbpf supports only CONFIG_ and LINUX_ prefixed
8824 				 * __kconfig externs, where LINUX_ ones are virtual and filled out
8825 				 * customly by libbpf (their values don't come from Kconfig).
8826 				 * If LINUX_xxx variable is not recognized by libbpf, but is marked
8827 				 * __weak, it defaults to zero value, just like for CONFIG_xxx
8828 				 * externs.
8829 				 */
8830 				pr_warn("extern (kcfg) '%s': unrecognized virtual extern\n", ext->name);
8831 				return -EINVAL;
8832 			}
8833 
8834 			err = set_kcfg_value_num(ext, ext_ptr, value);
8835 			if (err)
8836 				return err;
8837 			pr_debug("extern (kcfg) '%s': set to 0x%llx\n",
8838 				 ext->name, (long long)value);
8839 		} else {
8840 			pr_warn("extern '%s': unrecognized extern kind\n", ext->name);
8841 			return -EINVAL;
8842 		}
8843 	}
8844 	if (need_config && extra_kconfig) {
8845 		err = bpf_object__read_kconfig_mem(obj, extra_kconfig, kcfg_data);
8846 		if (err)
8847 			return -EINVAL;
8848 		need_config = false;
8849 		for (i = 0; i < obj->nr_extern; i++) {
8850 			ext = &obj->externs[i];
8851 			if (ext->type == EXT_KCFG && !ext->is_set) {
8852 				need_config = true;
8853 				break;
8854 			}
8855 		}
8856 	}
8857 	if (need_config) {
8858 		err = bpf_object__read_kconfig_file(obj, kcfg_data);
8859 		if (err)
8860 			return -EINVAL;
8861 	}
8862 	if (need_kallsyms) {
8863 		err = bpf_object__read_kallsyms_file(obj);
8864 		if (err)
8865 			return -EINVAL;
8866 	}
8867 	if (need_vmlinux_btf) {
8868 		err = bpf_object__resolve_ksyms_btf_id(obj);
8869 		if (err)
8870 			return -EINVAL;
8871 	}
8872 	for (i = 0; i < obj->nr_extern; i++) {
8873 		ext = &obj->externs[i];
8874 
8875 		if (!ext->is_set && !ext->is_weak) {
8876 			pr_warn("extern '%s' (strong): not resolved\n", ext->name);
8877 			return -ESRCH;
8878 		} else if (!ext->is_set) {
8879 			pr_debug("extern '%s' (weak): not resolved, defaulting to zero\n",
8880 				 ext->name);
8881 		}
8882 	}
8883 
8884 	return 0;
8885 }
8886 
8887 static void bpf_map_prepare_vdata(const struct bpf_map *map)
8888 {
8889 	const struct btf_type *type;
8890 	struct bpf_struct_ops *st_ops;
8891 	__u32 i;
8892 
8893 	st_ops = map->st_ops;
8894 	type = btf__type_by_id(map->obj->btf, st_ops->type_id);
8895 	for (i = 0; i < btf_vlen(type); i++) {
8896 		struct bpf_program *prog = st_ops->progs[i];
8897 		void *kern_data;
8898 		int prog_fd;
8899 
8900 		if (!prog)
8901 			continue;
8902 
8903 		prog_fd = bpf_program__fd(prog);
8904 		kern_data = st_ops->kern_vdata + st_ops->kern_func_off[i];
8905 		*(unsigned long *)kern_data = prog_fd;
8906 	}
8907 }
8908 
8909 static int bpf_object_prepare_struct_ops(struct bpf_object *obj)
8910 {
8911 	struct bpf_map *map;
8912 	int i;
8913 
8914 	for (i = 0; i < obj->nr_maps; i++) {
8915 		map = &obj->maps[i];
8916 
8917 		if (!bpf_map__is_struct_ops(map))
8918 			continue;
8919 
8920 		if (!map->autocreate)
8921 			continue;
8922 
8923 		bpf_map_prepare_vdata(map);
8924 	}
8925 
8926 	return 0;
8927 }
8928 
8929 static void bpf_object_unpin(struct bpf_object *obj)
8930 {
8931 	int i;
8932 
8933 	/* unpin any maps that were auto-pinned during load */
8934 	for (i = 0; i < obj->nr_maps; i++)
8935 		if (obj->maps[i].pinned && !obj->maps[i].reused)
8936 			bpf_map__unpin(&obj->maps[i], NULL);
8937 }
8938 
8939 static void bpf_object_post_load_cleanup(struct bpf_object *obj)
8940 {
8941 	int i;
8942 
8943 	/* clean up fd_array */
8944 	zfree(&obj->fd_array);
8945 
8946 	/* clean up module BTFs */
8947 	for (i = 0; i < obj->btf_module_cnt; i++) {
8948 		close(obj->btf_modules[i].fd);
8949 		btf__free(obj->btf_modules[i].btf);
8950 		free(obj->btf_modules[i].name);
8951 	}
8952 	obj->btf_module_cnt = 0;
8953 	zfree(&obj->btf_modules);
8954 
8955 	/* clean up vmlinux BTF */
8956 	btf__free(obj->btf_vmlinux);
8957 	obj->btf_vmlinux = NULL;
8958 }
8959 
8960 static int bpf_object_prepare(struct bpf_object *obj, const char *target_btf_path)
8961 {
8962 	int err;
8963 
8964 	if (obj->state >= OBJ_PREPARED) {
8965 		pr_warn("object '%s': prepare loading can't be attempted twice\n", obj->name);
8966 		return -EINVAL;
8967 	}
8968 
8969 	err = bpf_object_prepare_token(obj);
8970 	err = err ? : bpf_object__probe_loading(obj);
8971 	err = err ? : bpf_object__load_vmlinux_btf(obj, false);
8972 	err = err ? : bpf_object__resolve_externs(obj, obj->kconfig);
8973 	err = err ? : bpf_object__sanitize_maps(obj);
8974 	err = err ? : bpf_object__init_kern_struct_ops_maps(obj);
8975 	err = err ? : bpf_object_adjust_struct_ops_autoload(obj);
8976 	err = err ? : bpf_object__relocate(obj, obj->btf_custom_path ? : target_btf_path);
8977 	err = err ? : bpf_object__sanitize_and_load_btf(obj);
8978 	err = err ? : bpf_object__create_maps(obj);
8979 	err = err ? : bpf_object_prepare_progs(obj);
8980 
8981 	if (err) {
8982 		bpf_object_unpin(obj);
8983 		bpf_object_unload(obj);
8984 		obj->state = OBJ_LOADED;
8985 		return err;
8986 	}
8987 
8988 	obj->state = OBJ_PREPARED;
8989 	return 0;
8990 }
8991 
8992 static int bpf_object_load(struct bpf_object *obj, int extra_log_level, const char *target_btf_path)
8993 {
8994 	int err;
8995 
8996 	if (!obj)
8997 		return libbpf_err(-EINVAL);
8998 
8999 	if (obj->state >= OBJ_LOADED) {
9000 		pr_warn("object '%s': load can't be attempted twice\n", obj->name);
9001 		return libbpf_err(-EINVAL);
9002 	}
9003 
9004 	/* Disallow kernel loading programs of non-native endianness but
9005 	 * permit cross-endian creation of "light skeleton".
9006 	 */
9007 	if (obj->gen_loader) {
9008 		bpf_gen__init(obj->gen_loader, extra_log_level, obj->nr_programs, obj->nr_maps);
9009 	} else if (!is_native_endianness(obj)) {
9010 		pr_warn("object '%s': loading non-native endianness is unsupported\n", obj->name);
9011 		return libbpf_err(-LIBBPF_ERRNO__ENDIAN);
9012 	}
9013 
9014 	if (obj->state < OBJ_PREPARED) {
9015 		err = bpf_object_prepare(obj, target_btf_path);
9016 		if (err)
9017 			return libbpf_err(err);
9018 	}
9019 	err = bpf_object__load_progs(obj, extra_log_level);
9020 	err = err ? : bpf_object_init_prog_arrays(obj);
9021 	err = err ? : bpf_object_prepare_struct_ops(obj);
9022 
9023 	if (obj->gen_loader) {
9024 		/* reset FDs */
9025 		if (obj->btf)
9026 			btf__set_fd(obj->btf, -1);
9027 		if (!err)
9028 			err = bpf_gen__finish(obj->gen_loader, obj->nr_programs, obj->nr_maps);
9029 	}
9030 
9031 	bpf_object_post_load_cleanup(obj);
9032 	obj->state = OBJ_LOADED; /* doesn't matter if successfully or not */
9033 
9034 	if (err) {
9035 		bpf_object_unpin(obj);
9036 		bpf_object_unload(obj);
9037 		pr_warn("failed to load object '%s'\n", obj->path);
9038 		return libbpf_err(err);
9039 	}
9040 
9041 	return 0;
9042 }
9043 
9044 int bpf_object__prepare(struct bpf_object *obj)
9045 {
9046 	return libbpf_err(bpf_object_prepare(obj, NULL));
9047 }
9048 
9049 int bpf_object__load(struct bpf_object *obj)
9050 {
9051 	return bpf_object_load(obj, 0, NULL);
9052 }
9053 
9054 static int make_parent_dir(const char *path)
9055 {
9056 	char *dname, *dir;
9057 	int err = 0;
9058 
9059 	dname = strdup(path);
9060 	if (dname == NULL)
9061 		return -ENOMEM;
9062 
9063 	dir = dirname(dname);
9064 	if (mkdir(dir, 0700) && errno != EEXIST)
9065 		err = -errno;
9066 
9067 	free(dname);
9068 	if (err) {
9069 		pr_warn("failed to mkdir %s: %s\n", path, errstr(err));
9070 	}
9071 	return err;
9072 }
9073 
9074 static int check_path(const char *path)
9075 {
9076 	struct statfs st_fs;
9077 	char *dname, *dir;
9078 	int err = 0;
9079 
9080 	if (path == NULL)
9081 		return -EINVAL;
9082 
9083 	dname = strdup(path);
9084 	if (dname == NULL)
9085 		return -ENOMEM;
9086 
9087 	dir = dirname(dname);
9088 	if (statfs(dir, &st_fs)) {
9089 		pr_warn("failed to statfs %s: %s\n", dir, errstr(errno));
9090 		err = -errno;
9091 	}
9092 	free(dname);
9093 
9094 	if (!err && st_fs.f_type != BPF_FS_MAGIC) {
9095 		pr_warn("specified path %s is not on BPF FS\n", path);
9096 		err = -EINVAL;
9097 	}
9098 
9099 	return err;
9100 }
9101 
9102 int bpf_program__pin(struct bpf_program *prog, const char *path)
9103 {
9104 	int err;
9105 
9106 	if (prog->fd < 0) {
9107 		pr_warn("prog '%s': can't pin program that wasn't loaded\n", prog->name);
9108 		return libbpf_err(-EINVAL);
9109 	}
9110 
9111 	err = make_parent_dir(path);
9112 	if (err)
9113 		return libbpf_err(err);
9114 
9115 	err = check_path(path);
9116 	if (err)
9117 		return libbpf_err(err);
9118 
9119 	if (bpf_obj_pin(prog->fd, path)) {
9120 		err = -errno;
9121 		pr_warn("prog '%s': failed to pin at '%s': %s\n", prog->name, path, errstr(err));
9122 		return libbpf_err(err);
9123 	}
9124 
9125 	pr_debug("prog '%s': pinned at '%s'\n", prog->name, path);
9126 	return 0;
9127 }
9128 
9129 int bpf_program__unpin(struct bpf_program *prog, const char *path)
9130 {
9131 	int err;
9132 
9133 	if (prog->fd < 0) {
9134 		pr_warn("prog '%s': can't unpin program that wasn't loaded\n", prog->name);
9135 		return libbpf_err(-EINVAL);
9136 	}
9137 
9138 	err = check_path(path);
9139 	if (err)
9140 		return libbpf_err(err);
9141 
9142 	err = unlink(path);
9143 	if (err)
9144 		return libbpf_err(-errno);
9145 
9146 	pr_debug("prog '%s': unpinned from '%s'\n", prog->name, path);
9147 	return 0;
9148 }
9149 
9150 int bpf_map__pin(struct bpf_map *map, const char *path)
9151 {
9152 	int err;
9153 
9154 	if (map == NULL) {
9155 		pr_warn("invalid map pointer\n");
9156 		return libbpf_err(-EINVAL);
9157 	}
9158 
9159 	if (map->fd < 0) {
9160 		pr_warn("map '%s': can't pin BPF map without FD (was it created?)\n", map->name);
9161 		return libbpf_err(-EINVAL);
9162 	}
9163 
9164 	if (map->pin_path) {
9165 		if (path && strcmp(path, map->pin_path)) {
9166 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
9167 				bpf_map__name(map), map->pin_path, path);
9168 			return libbpf_err(-EINVAL);
9169 		} else if (map->pinned) {
9170 			pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
9171 				 bpf_map__name(map), map->pin_path);
9172 			return 0;
9173 		}
9174 	} else {
9175 		if (!path) {
9176 			pr_warn("missing a path to pin map '%s' at\n",
9177 				bpf_map__name(map));
9178 			return libbpf_err(-EINVAL);
9179 		} else if (map->pinned) {
9180 			pr_warn("map '%s' already pinned\n", bpf_map__name(map));
9181 			return libbpf_err(-EEXIST);
9182 		}
9183 
9184 		map->pin_path = strdup(path);
9185 		if (!map->pin_path) {
9186 			err = -errno;
9187 			goto out_err;
9188 		}
9189 	}
9190 
9191 	err = make_parent_dir(map->pin_path);
9192 	if (err)
9193 		return libbpf_err(err);
9194 
9195 	err = check_path(map->pin_path);
9196 	if (err)
9197 		return libbpf_err(err);
9198 
9199 	if (bpf_obj_pin(map->fd, map->pin_path)) {
9200 		err = -errno;
9201 		goto out_err;
9202 	}
9203 
9204 	map->pinned = true;
9205 	pr_debug("pinned map '%s'\n", map->pin_path);
9206 
9207 	return 0;
9208 
9209 out_err:
9210 	pr_warn("failed to pin map: %s\n", errstr(err));
9211 	return libbpf_err(err);
9212 }
9213 
9214 int bpf_map__unpin(struct bpf_map *map, const char *path)
9215 {
9216 	int err;
9217 
9218 	if (map == NULL) {
9219 		pr_warn("invalid map pointer\n");
9220 		return libbpf_err(-EINVAL);
9221 	}
9222 
9223 	if (map->pin_path) {
9224 		if (path && strcmp(path, map->pin_path)) {
9225 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
9226 				bpf_map__name(map), map->pin_path, path);
9227 			return libbpf_err(-EINVAL);
9228 		}
9229 		path = map->pin_path;
9230 	} else if (!path) {
9231 		pr_warn("no path to unpin map '%s' from\n",
9232 			bpf_map__name(map));
9233 		return libbpf_err(-EINVAL);
9234 	}
9235 
9236 	err = check_path(path);
9237 	if (err)
9238 		return libbpf_err(err);
9239 
9240 	err = unlink(path);
9241 	if (err != 0)
9242 		return libbpf_err(-errno);
9243 
9244 	map->pinned = false;
9245 	pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path);
9246 
9247 	return 0;
9248 }
9249 
9250 int bpf_map__set_pin_path(struct bpf_map *map, const char *path)
9251 {
9252 	char *new = NULL;
9253 
9254 	if (path) {
9255 		new = strdup(path);
9256 		if (!new)
9257 			return libbpf_err(-errno);
9258 	}
9259 
9260 	free(map->pin_path);
9261 	map->pin_path = new;
9262 	return 0;
9263 }
9264 
9265 __alias(bpf_map__pin_path)
9266 const char *bpf_map__get_pin_path(const struct bpf_map *map);
9267 
9268 const char *bpf_map__pin_path(const struct bpf_map *map)
9269 {
9270 	return map->pin_path;
9271 }
9272 
9273 bool bpf_map__is_pinned(const struct bpf_map *map)
9274 {
9275 	return map->pinned;
9276 }
9277 
9278 static void sanitize_pin_path(char *s)
9279 {
9280 	/* bpffs disallows periods in path names */
9281 	while (*s) {
9282 		if (*s == '.')
9283 			*s = '_';
9284 		s++;
9285 	}
9286 }
9287 
9288 int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
9289 {
9290 	struct bpf_map *map;
9291 	int err;
9292 
9293 	if (!obj)
9294 		return libbpf_err(-ENOENT);
9295 
9296 	if (obj->state < OBJ_PREPARED) {
9297 		pr_warn("object not yet loaded; load it first\n");
9298 		return libbpf_err(-ENOENT);
9299 	}
9300 
9301 	bpf_object__for_each_map(map, obj) {
9302 		char *pin_path = NULL;
9303 		char buf[PATH_MAX];
9304 
9305 		if (!map->autocreate)
9306 			continue;
9307 
9308 		if (path) {
9309 			err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
9310 			if (err)
9311 				goto err_unpin_maps;
9312 			sanitize_pin_path(buf);
9313 			pin_path = buf;
9314 		} else if (!map->pin_path) {
9315 			continue;
9316 		}
9317 
9318 		err = bpf_map__pin(map, pin_path);
9319 		if (err)
9320 			goto err_unpin_maps;
9321 	}
9322 
9323 	return 0;
9324 
9325 err_unpin_maps:
9326 	while ((map = bpf_object__prev_map(obj, map))) {
9327 		if (!map->pin_path)
9328 			continue;
9329 
9330 		bpf_map__unpin(map, NULL);
9331 	}
9332 
9333 	return libbpf_err(err);
9334 }
9335 
9336 int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
9337 {
9338 	struct bpf_map *map;
9339 	int err;
9340 
9341 	if (!obj)
9342 		return libbpf_err(-ENOENT);
9343 
9344 	bpf_object__for_each_map(map, obj) {
9345 		char *pin_path = NULL;
9346 		char buf[PATH_MAX];
9347 
9348 		if (path) {
9349 			err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
9350 			if (err)
9351 				return libbpf_err(err);
9352 			sanitize_pin_path(buf);
9353 			pin_path = buf;
9354 		} else if (!map->pin_path) {
9355 			continue;
9356 		}
9357 
9358 		err = bpf_map__unpin(map, pin_path);
9359 		if (err)
9360 			return libbpf_err(err);
9361 	}
9362 
9363 	return 0;
9364 }
9365 
9366 int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
9367 {
9368 	struct bpf_program *prog;
9369 	char buf[PATH_MAX];
9370 	int err;
9371 
9372 	if (!obj)
9373 		return libbpf_err(-ENOENT);
9374 
9375 	if (obj->state < OBJ_LOADED) {
9376 		pr_warn("object not yet loaded; load it first\n");
9377 		return libbpf_err(-ENOENT);
9378 	}
9379 
9380 	bpf_object__for_each_program(prog, obj) {
9381 		err = pathname_concat(buf, sizeof(buf), path, prog->name);
9382 		if (err)
9383 			goto err_unpin_programs;
9384 
9385 		err = bpf_program__pin(prog, buf);
9386 		if (err)
9387 			goto err_unpin_programs;
9388 	}
9389 
9390 	return 0;
9391 
9392 err_unpin_programs:
9393 	while ((prog = bpf_object__prev_program(obj, prog))) {
9394 		if (pathname_concat(buf, sizeof(buf), path, prog->name))
9395 			continue;
9396 
9397 		bpf_program__unpin(prog, buf);
9398 	}
9399 
9400 	return libbpf_err(err);
9401 }
9402 
9403 int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
9404 {
9405 	struct bpf_program *prog;
9406 	int err;
9407 
9408 	if (!obj)
9409 		return libbpf_err(-ENOENT);
9410 
9411 	bpf_object__for_each_program(prog, obj) {
9412 		char buf[PATH_MAX];
9413 
9414 		err = pathname_concat(buf, sizeof(buf), path, prog->name);
9415 		if (err)
9416 			return libbpf_err(err);
9417 
9418 		err = bpf_program__unpin(prog, buf);
9419 		if (err)
9420 			return libbpf_err(err);
9421 	}
9422 
9423 	return 0;
9424 }
9425 
9426 int bpf_object__pin(struct bpf_object *obj, const char *path)
9427 {
9428 	int err;
9429 
9430 	err = bpf_object__pin_maps(obj, path);
9431 	if (err)
9432 		return libbpf_err(err);
9433 
9434 	err = bpf_object__pin_programs(obj, path);
9435 	if (err) {
9436 		bpf_object__unpin_maps(obj, path);
9437 		return libbpf_err(err);
9438 	}
9439 
9440 	return 0;
9441 }
9442 
9443 int bpf_object__unpin(struct bpf_object *obj, const char *path)
9444 {
9445 	int err;
9446 
9447 	err = bpf_object__unpin_programs(obj, path);
9448 	if (err)
9449 		return libbpf_err(err);
9450 
9451 	err = bpf_object__unpin_maps(obj, path);
9452 	if (err)
9453 		return libbpf_err(err);
9454 
9455 	return 0;
9456 }
9457 
9458 static void bpf_map__destroy(struct bpf_map *map)
9459 {
9460 	if (map->inner_map) {
9461 		bpf_map__destroy(map->inner_map);
9462 		zfree(&map->inner_map);
9463 	}
9464 
9465 	zfree(&map->init_slots);
9466 	map->init_slots_sz = 0;
9467 
9468 	if (map->mmaped && map->mmaped != map->obj->arena_data)
9469 		munmap(map->mmaped, bpf_map_mmap_sz(map));
9470 	map->mmaped = NULL;
9471 
9472 	if (map->st_ops) {
9473 		zfree(&map->st_ops->data);
9474 		zfree(&map->st_ops->progs);
9475 		zfree(&map->st_ops->kern_func_off);
9476 		zfree(&map->st_ops);
9477 	}
9478 
9479 	zfree(&map->name);
9480 	zfree(&map->real_name);
9481 	zfree(&map->pin_path);
9482 
9483 	if (map->fd >= 0)
9484 		zclose(map->fd);
9485 }
9486 
9487 void bpf_object__close(struct bpf_object *obj)
9488 {
9489 	size_t i;
9490 
9491 	if (IS_ERR_OR_NULL(obj))
9492 		return;
9493 
9494 	/*
9495 	 * if user called bpf_object__prepare() without ever getting to
9496 	 * bpf_object__load(), we need to clean up stuff that is normally
9497 	 * cleaned up at the end of loading step
9498 	 */
9499 	bpf_object_post_load_cleanup(obj);
9500 
9501 	usdt_manager_free(obj->usdt_man);
9502 	obj->usdt_man = NULL;
9503 
9504 	bpf_gen__free(obj->gen_loader);
9505 	bpf_object__elf_finish(obj);
9506 	bpf_object_unload(obj);
9507 	btf__free(obj->btf);
9508 	btf__free(obj->btf_vmlinux);
9509 	btf_ext__free(obj->btf_ext);
9510 
9511 	for (i = 0; i < obj->nr_maps; i++)
9512 		bpf_map__destroy(&obj->maps[i]);
9513 
9514 	zfree(&obj->btf_custom_path);
9515 	zfree(&obj->kconfig);
9516 
9517 	for (i = 0; i < obj->nr_extern; i++) {
9518 		zfree(&obj->externs[i].name);
9519 		zfree(&obj->externs[i].essent_name);
9520 	}
9521 
9522 	zfree(&obj->externs);
9523 	obj->nr_extern = 0;
9524 
9525 	zfree(&obj->maps);
9526 	obj->nr_maps = 0;
9527 
9528 	if (obj->programs && obj->nr_programs) {
9529 		for (i = 0; i < obj->nr_programs; i++)
9530 			bpf_program__exit(&obj->programs[i]);
9531 	}
9532 	zfree(&obj->programs);
9533 
9534 	zfree(&obj->feat_cache);
9535 	zfree(&obj->token_path);
9536 	if (obj->token_fd > 0)
9537 		close(obj->token_fd);
9538 
9539 	zfree(&obj->arena_data);
9540 
9541 	zfree(&obj->jumptables_data);
9542 	obj->jumptables_data_sz = 0;
9543 
9544 	for (i = 0; i < obj->jumptable_map_cnt; i++)
9545 		close(obj->jumptable_maps[i].fd);
9546 	zfree(&obj->jumptable_maps);
9547 
9548 	free(obj);
9549 }
9550 
9551 const char *bpf_object__name(const struct bpf_object *obj)
9552 {
9553 	return obj ? obj->name : libbpf_err_ptr(-EINVAL);
9554 }
9555 
9556 unsigned int bpf_object__kversion(const struct bpf_object *obj)
9557 {
9558 	return obj ? obj->kern_version : 0;
9559 }
9560 
9561 int bpf_object__token_fd(const struct bpf_object *obj)
9562 {
9563 	return obj->token_fd ?: -1;
9564 }
9565 
9566 struct btf *bpf_object__btf(const struct bpf_object *obj)
9567 {
9568 	return obj ? obj->btf : NULL;
9569 }
9570 
9571 int bpf_object__btf_fd(const struct bpf_object *obj)
9572 {
9573 	return obj->btf ? btf__fd(obj->btf) : -1;
9574 }
9575 
9576 int bpf_object__set_kversion(struct bpf_object *obj, __u32 kern_version)
9577 {
9578 	if (obj->state >= OBJ_LOADED)
9579 		return libbpf_err(-EINVAL);
9580 
9581 	obj->kern_version = kern_version;
9582 
9583 	return 0;
9584 }
9585 
9586 int bpf_object__gen_loader(struct bpf_object *obj, struct gen_loader_opts *opts)
9587 {
9588 	struct bpf_gen *gen;
9589 
9590 	if (!opts)
9591 		return libbpf_err(-EFAULT);
9592 	if (!OPTS_VALID(opts, gen_loader_opts))
9593 		return libbpf_err(-EINVAL);
9594 	gen = calloc(1, sizeof(*gen));
9595 	if (!gen)
9596 		return libbpf_err(-ENOMEM);
9597 	gen->opts = opts;
9598 	gen->swapped_endian = !is_native_endianness(obj);
9599 	obj->gen_loader = gen;
9600 	return 0;
9601 }
9602 
9603 static struct bpf_program *
9604 __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
9605 		    bool forward)
9606 {
9607 	size_t nr_programs = obj->nr_programs;
9608 	ssize_t idx;
9609 
9610 	if (!nr_programs)
9611 		return NULL;
9612 
9613 	if (!p)
9614 		/* Iter from the beginning */
9615 		return forward ? &obj->programs[0] :
9616 			&obj->programs[nr_programs - 1];
9617 
9618 	if (p->obj != obj) {
9619 		pr_warn("error: program handler doesn't match object\n");
9620 		return errno = EINVAL, NULL;
9621 	}
9622 
9623 	idx = (p - obj->programs) + (forward ? 1 : -1);
9624 	if (idx >= obj->nr_programs || idx < 0)
9625 		return NULL;
9626 	return &obj->programs[idx];
9627 }
9628 
9629 struct bpf_program *
9630 bpf_object__next_program(const struct bpf_object *obj, struct bpf_program *prev)
9631 {
9632 	struct bpf_program *prog = prev;
9633 
9634 	do {
9635 		prog = __bpf_program__iter(prog, obj, true);
9636 	} while (prog && prog_is_subprog(obj, prog));
9637 
9638 	return prog;
9639 }
9640 
9641 struct bpf_program *
9642 bpf_object__prev_program(const struct bpf_object *obj, struct bpf_program *next)
9643 {
9644 	struct bpf_program *prog = next;
9645 
9646 	do {
9647 		prog = __bpf_program__iter(prog, obj, false);
9648 	} while (prog && prog_is_subprog(obj, prog));
9649 
9650 	return prog;
9651 }
9652 
9653 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
9654 {
9655 	prog->prog_ifindex = ifindex;
9656 }
9657 
9658 const char *bpf_program__name(const struct bpf_program *prog)
9659 {
9660 	return prog->name;
9661 }
9662 
9663 const char *bpf_program__section_name(const struct bpf_program *prog)
9664 {
9665 	return prog->sec_name;
9666 }
9667 
9668 bool bpf_program__autoload(const struct bpf_program *prog)
9669 {
9670 	return prog->autoload;
9671 }
9672 
9673 int bpf_program__set_autoload(struct bpf_program *prog, bool autoload)
9674 {
9675 	if (prog->obj->state >= OBJ_LOADED)
9676 		return libbpf_err(-EINVAL);
9677 
9678 	prog->autoload = autoload;
9679 	return 0;
9680 }
9681 
9682 bool bpf_program__autoattach(const struct bpf_program *prog)
9683 {
9684 	return prog->autoattach;
9685 }
9686 
9687 void bpf_program__set_autoattach(struct bpf_program *prog, bool autoattach)
9688 {
9689 	prog->autoattach = autoattach;
9690 }
9691 
9692 const struct bpf_insn *bpf_program__insns(const struct bpf_program *prog)
9693 {
9694 	return prog->insns;
9695 }
9696 
9697 size_t bpf_program__insn_cnt(const struct bpf_program *prog)
9698 {
9699 	return prog->insns_cnt;
9700 }
9701 
9702 int bpf_program__set_insns(struct bpf_program *prog,
9703 			   struct bpf_insn *new_insns, size_t new_insn_cnt)
9704 {
9705 	struct bpf_insn *insns;
9706 
9707 	if (prog->obj->state >= OBJ_LOADED)
9708 		return libbpf_err(-EBUSY);
9709 
9710 	insns = libbpf_reallocarray(prog->insns, new_insn_cnt, sizeof(*insns));
9711 	/* NULL is a valid return from reallocarray if the new count is zero */
9712 	if (!insns && new_insn_cnt) {
9713 		pr_warn("prog '%s': failed to realloc prog code\n", prog->name);
9714 		return libbpf_err(-ENOMEM);
9715 	}
9716 	memcpy(insns, new_insns, new_insn_cnt * sizeof(*insns));
9717 
9718 	prog->insns = insns;
9719 	prog->insns_cnt = new_insn_cnt;
9720 	return 0;
9721 }
9722 
9723 int bpf_program__fd(const struct bpf_program *prog)
9724 {
9725 	if (!prog)
9726 		return libbpf_err(-EINVAL);
9727 
9728 	if (prog->fd < 0)
9729 		return libbpf_err(-ENOENT);
9730 
9731 	return prog->fd;
9732 }
9733 
9734 __alias(bpf_program__type)
9735 enum bpf_prog_type bpf_program__get_type(const struct bpf_program *prog);
9736 
9737 enum bpf_prog_type bpf_program__type(const struct bpf_program *prog)
9738 {
9739 	return prog->type;
9740 }
9741 
9742 static size_t custom_sec_def_cnt;
9743 static struct bpf_sec_def *custom_sec_defs;
9744 static struct bpf_sec_def custom_fallback_def;
9745 static bool has_custom_fallback_def;
9746 static int last_custom_sec_def_handler_id;
9747 
9748 int bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
9749 {
9750 	if (prog->obj->state >= OBJ_LOADED)
9751 		return libbpf_err(-EBUSY);
9752 
9753 	/* if type is not changed, do nothing */
9754 	if (prog->type == type)
9755 		return 0;
9756 
9757 	prog->type = type;
9758 
9759 	/* If a program type was changed, we need to reset associated SEC()
9760 	 * handler, as it will be invalid now. The only exception is a generic
9761 	 * fallback handler, which by definition is program type-agnostic and
9762 	 * is a catch-all custom handler, optionally set by the application,
9763 	 * so should be able to handle any type of BPF program.
9764 	 */
9765 	if (prog->sec_def != &custom_fallback_def)
9766 		prog->sec_def = NULL;
9767 	return 0;
9768 }
9769 
9770 __alias(bpf_program__expected_attach_type)
9771 enum bpf_attach_type bpf_program__get_expected_attach_type(const struct bpf_program *prog);
9772 
9773 enum bpf_attach_type bpf_program__expected_attach_type(const struct bpf_program *prog)
9774 {
9775 	return prog->expected_attach_type;
9776 }
9777 
9778 int bpf_program__set_expected_attach_type(struct bpf_program *prog,
9779 					   enum bpf_attach_type type)
9780 {
9781 	if (prog->obj->state >= OBJ_LOADED)
9782 		return libbpf_err(-EBUSY);
9783 
9784 	prog->expected_attach_type = type;
9785 	return 0;
9786 }
9787 
9788 __u32 bpf_program__flags(const struct bpf_program *prog)
9789 {
9790 	return prog->prog_flags;
9791 }
9792 
9793 int bpf_program__set_flags(struct bpf_program *prog, __u32 flags)
9794 {
9795 	if (prog->obj->state >= OBJ_LOADED)
9796 		return libbpf_err(-EBUSY);
9797 
9798 	prog->prog_flags = flags;
9799 	return 0;
9800 }
9801 
9802 __u32 bpf_program__log_level(const struct bpf_program *prog)
9803 {
9804 	return prog->log_level;
9805 }
9806 
9807 int bpf_program__set_log_level(struct bpf_program *prog, __u32 log_level)
9808 {
9809 	if (prog->obj->state >= OBJ_LOADED)
9810 		return libbpf_err(-EBUSY);
9811 
9812 	prog->log_level = log_level;
9813 	return 0;
9814 }
9815 
9816 const char *bpf_program__log_buf(const struct bpf_program *prog, size_t *log_size)
9817 {
9818 	*log_size = prog->log_size;
9819 	return prog->log_buf;
9820 }
9821 
9822 int bpf_program__set_log_buf(struct bpf_program *prog, char *log_buf, size_t log_size)
9823 {
9824 	if (log_size && !log_buf)
9825 		return libbpf_err(-EINVAL);
9826 	if (prog->log_size > UINT_MAX)
9827 		return libbpf_err(-EINVAL);
9828 	if (prog->obj->state >= OBJ_LOADED)
9829 		return libbpf_err(-EBUSY);
9830 
9831 	prog->log_buf = log_buf;
9832 	prog->log_size = log_size;
9833 	return 0;
9834 }
9835 
9836 struct bpf_func_info *bpf_program__func_info(const struct bpf_program *prog)
9837 {
9838 	if (prog->func_info_rec_size != sizeof(struct bpf_func_info))
9839 		return libbpf_err_ptr(-EOPNOTSUPP);
9840 	return prog->func_info;
9841 }
9842 
9843 __u32 bpf_program__func_info_cnt(const struct bpf_program *prog)
9844 {
9845 	return prog->func_info_cnt;
9846 }
9847 
9848 struct bpf_line_info *bpf_program__line_info(const struct bpf_program *prog)
9849 {
9850 	if (prog->line_info_rec_size != sizeof(struct bpf_line_info))
9851 		return libbpf_err_ptr(-EOPNOTSUPP);
9852 	return prog->line_info;
9853 }
9854 
9855 __u32 bpf_program__line_info_cnt(const struct bpf_program *prog)
9856 {
9857 	return prog->line_info_cnt;
9858 }
9859 
9860 int bpf_program__clone(struct bpf_program *prog, const struct bpf_prog_load_opts *opts)
9861 {
9862 	LIBBPF_OPTS(bpf_prog_load_opts, attr);
9863 	struct bpf_object *obj;
9864 	const void *info;
9865 	__u32 info_cnt, info_rec_size;
9866 	int err, fd, prog_btf_fd;
9867 
9868 	if (!prog)
9869 		return libbpf_err(-EINVAL);
9870 
9871 	if (!OPTS_VALID(opts, bpf_prog_load_opts))
9872 		return libbpf_err(-EINVAL);
9873 
9874 	obj = prog->obj;
9875 	if (obj->state < OBJ_PREPARED)
9876 		return libbpf_err(-EINVAL);
9877 
9878 	/*
9879 	 * Caller-provided opts take priority; fall back to
9880 	 * prog/object defaults when the caller leaves them zero.
9881 	 */
9882 	attr.attach_prog_fd = OPTS_GET(opts, attach_prog_fd, 0) ?: prog->attach_prog_fd;
9883 	attr.prog_flags = OPTS_GET(opts, prog_flags, 0) ?: prog->prog_flags;
9884 	attr.prog_ifindex = OPTS_GET(opts, prog_ifindex, 0) ?: prog->prog_ifindex;
9885 	attr.kern_version = OPTS_GET(opts, kern_version, 0) ?: obj->kern_version;
9886 	attr.fd_array = OPTS_GET(opts, fd_array, NULL) ?: obj->fd_array;
9887 	attr.fd_array_cnt = OPTS_GET(opts, fd_array_cnt, 0) ?: obj->fd_array_cnt;
9888 	attr.token_fd = OPTS_GET(opts, token_fd, 0) ?: obj->token_fd;
9889 	if (attr.token_fd)
9890 		attr.prog_flags |= BPF_F_TOKEN_FD;
9891 
9892 	prog_btf_fd = OPTS_GET(opts, prog_btf_fd, 0);
9893 	if (!prog_btf_fd && obj->btf)
9894 		prog_btf_fd = btf__fd(obj->btf);
9895 
9896 	/* BTF func/line info: only pass if kernel supports it */
9897 	if (kernel_supports(obj, FEAT_BTF_FUNC) && prog_btf_fd > 0) {
9898 		attr.prog_btf_fd = prog_btf_fd;
9899 
9900 		/* func_info/line_info triples: all-or-nothing from caller */
9901 		info = OPTS_GET(opts, func_info, NULL);
9902 		info_cnt = OPTS_GET(opts, func_info_cnt, 0);
9903 		info_rec_size = OPTS_GET(opts, func_info_rec_size, 0);
9904 		if (!!info != !!info_cnt || !!info != !!info_rec_size) {
9905 			pr_warn("prog '%s': func_info, func_info_cnt, and func_info_rec_size must all be specified or all omitted\n",
9906 				prog->name);
9907 			return libbpf_err(-EINVAL);
9908 		}
9909 		attr.func_info = info ?: prog->func_info;
9910 		attr.func_info_cnt = info ? info_cnt : prog->func_info_cnt;
9911 		attr.func_info_rec_size = info ? info_rec_size : prog->func_info_rec_size;
9912 
9913 		info = OPTS_GET(opts, line_info, NULL);
9914 		info_cnt = OPTS_GET(opts, line_info_cnt, 0);
9915 		info_rec_size = OPTS_GET(opts, line_info_rec_size, 0);
9916 		if (!!info != !!info_cnt || !!info != !!info_rec_size) {
9917 			pr_warn("prog '%s': line_info, line_info_cnt, and line_info_rec_size must all be specified or all omitted\n",
9918 				prog->name);
9919 			return libbpf_err(-EINVAL);
9920 		}
9921 		attr.line_info = info ?: prog->line_info;
9922 		attr.line_info_cnt = info ? info_cnt : prog->line_info_cnt;
9923 		attr.line_info_rec_size = info ? info_rec_size : prog->line_info_rec_size;
9924 	}
9925 
9926 	/* Logging is caller-controlled; no fallback to prog/obj log settings */
9927 	attr.log_buf = OPTS_GET(opts, log_buf, NULL);
9928 	attr.log_size = OPTS_GET(opts, log_size, 0);
9929 	attr.log_level = OPTS_GET(opts, log_level, 0);
9930 
9931 	/*
9932 	 * Fields below may be mutated by prog_prepare_load_fn:
9933 	 * Seed them from prog/obj defaults here;
9934 	 * Later override with caller-provided opts.
9935 	 */
9936 	attr.expected_attach_type = prog->expected_attach_type;
9937 	attr.attach_btf_id = prog->attach_btf_id;
9938 	attr.attach_btf_obj_fd = prog->attach_btf_obj_fd;
9939 
9940 	if (prog->sec_def && prog->sec_def->prog_prepare_load_fn) {
9941 		err = prog->sec_def->prog_prepare_load_fn(prog, &attr, prog->sec_def->cookie);
9942 		if (err)
9943 			return libbpf_err(err);
9944 	}
9945 
9946 	/* Re-apply caller overrides for output fields */
9947 	if (OPTS_GET(opts, expected_attach_type, 0))
9948 		attr.expected_attach_type = OPTS_GET(opts, expected_attach_type, 0);
9949 	if (OPTS_GET(opts, attach_btf_id, 0))
9950 		attr.attach_btf_id = OPTS_GET(opts, attach_btf_id, 0);
9951 	if (OPTS_GET(opts, attach_btf_obj_fd, 0))
9952 		attr.attach_btf_obj_fd = OPTS_GET(opts, attach_btf_obj_fd, 0);
9953 
9954 	/*
9955 	 * Unlike bpf_object_load_prog(), we intentionally do not call bpf_prog_bind_map()
9956 	 * for RODATA maps here to avoid mutating the object's state. Callers can bind the
9957 	 * required maps themselves using bpf_prog_bind_map().
9958 	 */
9959 	fd = bpf_prog_load(prog->type, prog->name, obj->license, prog->insns, prog->insns_cnt,
9960 			   &attr);
9961 
9962 	return libbpf_err(fd);
9963 }
9964 
9965 #define SEC_DEF(sec_pfx, ptype, atype, flags, ...) {			    \
9966 	.sec = (char *)sec_pfx,						    \
9967 	.prog_type = BPF_PROG_TYPE_##ptype,				    \
9968 	.expected_attach_type = atype,					    \
9969 	.cookie = (long)(flags),					    \
9970 	.prog_prepare_load_fn = libbpf_prepare_prog_load,		    \
9971 	__VA_ARGS__							    \
9972 }
9973 
9974 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9975 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9976 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9977 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9978 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9979 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9980 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9981 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9982 static int attach_kprobe_session(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9983 static int attach_uprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9984 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9985 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9986 
9987 static const struct bpf_sec_def section_defs[] = {
9988 	SEC_DEF("socket",		SOCKET_FILTER, 0, SEC_NONE),
9989 	SEC_DEF("sk_reuseport/migrate",	SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT_OR_MIGRATE, SEC_ATTACHABLE),
9990 	SEC_DEF("sk_reuseport",		SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT, SEC_ATTACHABLE),
9991 	SEC_DEF("kprobe+",		KPROBE,	0, SEC_NONE, attach_kprobe),
9992 	SEC_DEF("uprobe+",		KPROBE,	0, SEC_NONE, attach_uprobe),
9993 	SEC_DEF("uprobe.s+",		KPROBE,	0, SEC_SLEEPABLE, attach_uprobe),
9994 	SEC_DEF("kretprobe+",		KPROBE, 0, SEC_NONE, attach_kprobe),
9995 	SEC_DEF("uretprobe+",		KPROBE, 0, SEC_NONE, attach_uprobe),
9996 	SEC_DEF("uretprobe.s+",		KPROBE, 0, SEC_SLEEPABLE, attach_uprobe),
9997 	SEC_DEF("kprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
9998 	SEC_DEF("kretprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
9999 	SEC_DEF("kprobe.session+",	KPROBE,	BPF_TRACE_KPROBE_SESSION, SEC_NONE, attach_kprobe_session),
10000 	SEC_DEF("uprobe.multi+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_NONE, attach_uprobe_multi),
10001 	SEC_DEF("uretprobe.multi+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_NONE, attach_uprobe_multi),
10002 	SEC_DEF("uprobe.session+",	KPROBE,	BPF_TRACE_UPROBE_SESSION, SEC_NONE, attach_uprobe_multi),
10003 	SEC_DEF("uprobe.multi.s+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_SLEEPABLE, attach_uprobe_multi),
10004 	SEC_DEF("uretprobe.multi.s+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_SLEEPABLE, attach_uprobe_multi),
10005 	SEC_DEF("uprobe.session.s+",	KPROBE,	BPF_TRACE_UPROBE_SESSION, SEC_SLEEPABLE, attach_uprobe_multi),
10006 	SEC_DEF("ksyscall+",		KPROBE,	0, SEC_NONE, attach_ksyscall),
10007 	SEC_DEF("kretsyscall+",		KPROBE, 0, SEC_NONE, attach_ksyscall),
10008 	SEC_DEF("usdt+",		KPROBE,	0, SEC_USDT, attach_usdt),
10009 	SEC_DEF("usdt.s+",		KPROBE,	0, SEC_USDT | SEC_SLEEPABLE, attach_usdt),
10010 	SEC_DEF("tc/ingress",		SCHED_CLS, BPF_TCX_INGRESS, SEC_NONE), /* alias for tcx */
10011 	SEC_DEF("tc/egress",		SCHED_CLS, BPF_TCX_EGRESS, SEC_NONE),  /* alias for tcx */
10012 	SEC_DEF("tcx/ingress",		SCHED_CLS, BPF_TCX_INGRESS, SEC_NONE),
10013 	SEC_DEF("tcx/egress",		SCHED_CLS, BPF_TCX_EGRESS, SEC_NONE),
10014 	SEC_DEF("tc",			SCHED_CLS, 0, SEC_NONE), /* deprecated / legacy, use tcx */
10015 	SEC_DEF("classifier",		SCHED_CLS, 0, SEC_NONE), /* deprecated / legacy, use tcx */
10016 	SEC_DEF("action",		SCHED_ACT, 0, SEC_NONE), /* deprecated / legacy, use tcx */
10017 	SEC_DEF("netkit/primary",	SCHED_CLS, BPF_NETKIT_PRIMARY, SEC_NONE),
10018 	SEC_DEF("netkit/peer",		SCHED_CLS, BPF_NETKIT_PEER, SEC_NONE),
10019 	SEC_DEF("tracepoint+",		TRACEPOINT, 0, SEC_NONE, attach_tp),
10020 	SEC_DEF("tp+",			TRACEPOINT, 0, SEC_NONE, attach_tp),
10021 	SEC_DEF("raw_tracepoint+",	RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
10022 	SEC_DEF("raw_tp+",		RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
10023 	SEC_DEF("raw_tracepoint.w+",	RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
10024 	SEC_DEF("raw_tp.w+",		RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
10025 	SEC_DEF("tp_btf+",		TRACING, BPF_TRACE_RAW_TP, SEC_ATTACH_BTF, attach_trace),
10026 	SEC_DEF("fentry+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF, attach_trace),
10027 	SEC_DEF("fmod_ret+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF, attach_trace),
10028 	SEC_DEF("fexit+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF, attach_trace),
10029 	SEC_DEF("fentry.s+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
10030 	SEC_DEF("fmod_ret.s+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
10031 	SEC_DEF("fexit.s+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
10032 	SEC_DEF("fsession+",		TRACING, BPF_TRACE_FSESSION, SEC_ATTACH_BTF, attach_trace),
10033 	SEC_DEF("fsession.s+",		TRACING, BPF_TRACE_FSESSION, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
10034 	SEC_DEF("freplace+",		EXT, 0, SEC_ATTACH_BTF, attach_trace),
10035 	SEC_DEF("lsm+",			LSM, BPF_LSM_MAC, SEC_ATTACH_BTF, attach_lsm),
10036 	SEC_DEF("lsm.s+",		LSM, BPF_LSM_MAC, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_lsm),
10037 	SEC_DEF("lsm_cgroup+",		LSM, BPF_LSM_CGROUP, SEC_ATTACH_BTF),
10038 	SEC_DEF("iter+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF, attach_iter),
10039 	SEC_DEF("iter.s+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_iter),
10040 	SEC_DEF("syscall",		SYSCALL, 0, SEC_SLEEPABLE),
10041 	SEC_DEF("xdp.frags/devmap",	XDP, BPF_XDP_DEVMAP, SEC_XDP_FRAGS),
10042 	SEC_DEF("xdp/devmap",		XDP, BPF_XDP_DEVMAP, SEC_ATTACHABLE),
10043 	SEC_DEF("xdp.frags/cpumap",	XDP, BPF_XDP_CPUMAP, SEC_XDP_FRAGS),
10044 	SEC_DEF("xdp/cpumap",		XDP, BPF_XDP_CPUMAP, SEC_ATTACHABLE),
10045 	SEC_DEF("xdp.frags",		XDP, BPF_XDP, SEC_XDP_FRAGS),
10046 	SEC_DEF("xdp",			XDP, BPF_XDP, SEC_ATTACHABLE_OPT),
10047 	SEC_DEF("perf_event",		PERF_EVENT, 0, SEC_NONE),
10048 	SEC_DEF("lwt_in",		LWT_IN, 0, SEC_NONE),
10049 	SEC_DEF("lwt_out",		LWT_OUT, 0, SEC_NONE),
10050 	SEC_DEF("lwt_xmit",		LWT_XMIT, 0, SEC_NONE),
10051 	SEC_DEF("lwt_seg6local",	LWT_SEG6LOCAL, 0, SEC_NONE),
10052 	SEC_DEF("sockops",		SOCK_OPS, BPF_CGROUP_SOCK_OPS, SEC_ATTACHABLE_OPT),
10053 	SEC_DEF("sk_skb/stream_parser",	SK_SKB, BPF_SK_SKB_STREAM_PARSER, SEC_ATTACHABLE_OPT),
10054 	SEC_DEF("sk_skb/stream_verdict",SK_SKB, BPF_SK_SKB_STREAM_VERDICT, SEC_ATTACHABLE_OPT),
10055 	SEC_DEF("sk_skb/verdict",	SK_SKB, BPF_SK_SKB_VERDICT, SEC_ATTACHABLE_OPT),
10056 	SEC_DEF("sk_skb",		SK_SKB, 0, SEC_NONE),
10057 	SEC_DEF("sk_msg",		SK_MSG, BPF_SK_MSG_VERDICT, SEC_ATTACHABLE_OPT),
10058 	SEC_DEF("lirc_mode2",		LIRC_MODE2, BPF_LIRC_MODE2, SEC_ATTACHABLE_OPT),
10059 	SEC_DEF("flow_dissector",	FLOW_DISSECTOR, BPF_FLOW_DISSECTOR, SEC_ATTACHABLE_OPT),
10060 	SEC_DEF("cgroup_skb/ingress",	CGROUP_SKB, BPF_CGROUP_INET_INGRESS, SEC_ATTACHABLE_OPT),
10061 	SEC_DEF("cgroup_skb/egress",	CGROUP_SKB, BPF_CGROUP_INET_EGRESS, SEC_ATTACHABLE_OPT),
10062 	SEC_DEF("cgroup/skb",		CGROUP_SKB, 0, SEC_NONE),
10063 	SEC_DEF("cgroup/sock_create",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE),
10064 	SEC_DEF("cgroup/sock_release",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_RELEASE, SEC_ATTACHABLE),
10065 	SEC_DEF("cgroup/sock",		CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE_OPT),
10066 	SEC_DEF("cgroup/post_bind4",	CGROUP_SOCK, BPF_CGROUP_INET4_POST_BIND, SEC_ATTACHABLE),
10067 	SEC_DEF("cgroup/post_bind6",	CGROUP_SOCK, BPF_CGROUP_INET6_POST_BIND, SEC_ATTACHABLE),
10068 	SEC_DEF("cgroup/bind4",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND, SEC_ATTACHABLE),
10069 	SEC_DEF("cgroup/bind6",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND, SEC_ATTACHABLE),
10070 	SEC_DEF("cgroup/connect4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT, SEC_ATTACHABLE),
10071 	SEC_DEF("cgroup/connect6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT, SEC_ATTACHABLE),
10072 	SEC_DEF("cgroup/connect_unix",	CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_CONNECT, SEC_ATTACHABLE),
10073 	SEC_DEF("cgroup/sendmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG, SEC_ATTACHABLE),
10074 	SEC_DEF("cgroup/sendmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG, SEC_ATTACHABLE),
10075 	SEC_DEF("cgroup/sendmsg_unix",	CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_SENDMSG, SEC_ATTACHABLE),
10076 	SEC_DEF("cgroup/recvmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_RECVMSG, SEC_ATTACHABLE),
10077 	SEC_DEF("cgroup/recvmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_RECVMSG, SEC_ATTACHABLE),
10078 	SEC_DEF("cgroup/recvmsg_unix",	CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_RECVMSG, SEC_ATTACHABLE),
10079 	SEC_DEF("cgroup/getpeername4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETPEERNAME, SEC_ATTACHABLE),
10080 	SEC_DEF("cgroup/getpeername6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETPEERNAME, SEC_ATTACHABLE),
10081 	SEC_DEF("cgroup/getpeername_unix", CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_GETPEERNAME, SEC_ATTACHABLE),
10082 	SEC_DEF("cgroup/getsockname4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETSOCKNAME, SEC_ATTACHABLE),
10083 	SEC_DEF("cgroup/getsockname6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETSOCKNAME, SEC_ATTACHABLE),
10084 	SEC_DEF("cgroup/getsockname_unix", CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_GETSOCKNAME, SEC_ATTACHABLE),
10085 	SEC_DEF("cgroup/sysctl",	CGROUP_SYSCTL, BPF_CGROUP_SYSCTL, SEC_ATTACHABLE),
10086 	SEC_DEF("cgroup/getsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_GETSOCKOPT, SEC_ATTACHABLE),
10087 	SEC_DEF("cgroup/setsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_SETSOCKOPT, SEC_ATTACHABLE),
10088 	SEC_DEF("cgroup/dev",		CGROUP_DEVICE, BPF_CGROUP_DEVICE, SEC_ATTACHABLE_OPT),
10089 	SEC_DEF("struct_ops+",		STRUCT_OPS, 0, SEC_NONE),
10090 	SEC_DEF("struct_ops.s+",	STRUCT_OPS, 0, SEC_SLEEPABLE),
10091 	SEC_DEF("sk_lookup",		SK_LOOKUP, BPF_SK_LOOKUP, SEC_ATTACHABLE),
10092 	SEC_DEF("netfilter",		NETFILTER, BPF_NETFILTER, SEC_NONE),
10093 };
10094 
10095 int libbpf_register_prog_handler(const char *sec,
10096 				 enum bpf_prog_type prog_type,
10097 				 enum bpf_attach_type exp_attach_type,
10098 				 const struct libbpf_prog_handler_opts *opts)
10099 {
10100 	struct bpf_sec_def *sec_def;
10101 
10102 	if (!OPTS_VALID(opts, libbpf_prog_handler_opts))
10103 		return libbpf_err(-EINVAL);
10104 
10105 	if (last_custom_sec_def_handler_id == INT_MAX) /* prevent overflow */
10106 		return libbpf_err(-E2BIG);
10107 
10108 	if (sec) {
10109 		sec_def = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt + 1,
10110 					      sizeof(*sec_def));
10111 		if (!sec_def)
10112 			return libbpf_err(-ENOMEM);
10113 
10114 		custom_sec_defs = sec_def;
10115 		sec_def = &custom_sec_defs[custom_sec_def_cnt];
10116 	} else {
10117 		if (has_custom_fallback_def)
10118 			return libbpf_err(-EBUSY);
10119 
10120 		sec_def = &custom_fallback_def;
10121 	}
10122 
10123 	sec_def->sec = sec ? strdup(sec) : NULL;
10124 	if (sec && !sec_def->sec)
10125 		return libbpf_err(-ENOMEM);
10126 
10127 	sec_def->prog_type = prog_type;
10128 	sec_def->expected_attach_type = exp_attach_type;
10129 	sec_def->cookie = OPTS_GET(opts, cookie, 0);
10130 
10131 	sec_def->prog_setup_fn = OPTS_GET(opts, prog_setup_fn, NULL);
10132 	sec_def->prog_prepare_load_fn = OPTS_GET(opts, prog_prepare_load_fn, NULL);
10133 	sec_def->prog_attach_fn = OPTS_GET(opts, prog_attach_fn, NULL);
10134 
10135 	sec_def->handler_id = ++last_custom_sec_def_handler_id;
10136 
10137 	if (sec)
10138 		custom_sec_def_cnt++;
10139 	else
10140 		has_custom_fallback_def = true;
10141 
10142 	return sec_def->handler_id;
10143 }
10144 
10145 int libbpf_unregister_prog_handler(int handler_id)
10146 {
10147 	struct bpf_sec_def *sec_defs;
10148 	int i;
10149 
10150 	if (handler_id <= 0)
10151 		return libbpf_err(-EINVAL);
10152 
10153 	if (has_custom_fallback_def && custom_fallback_def.handler_id == handler_id) {
10154 		memset(&custom_fallback_def, 0, sizeof(custom_fallback_def));
10155 		has_custom_fallback_def = false;
10156 		return 0;
10157 	}
10158 
10159 	for (i = 0; i < custom_sec_def_cnt; i++) {
10160 		if (custom_sec_defs[i].handler_id == handler_id)
10161 			break;
10162 	}
10163 
10164 	if (i == custom_sec_def_cnt)
10165 		return libbpf_err(-ENOENT);
10166 
10167 	free(custom_sec_defs[i].sec);
10168 	for (i = i + 1; i < custom_sec_def_cnt; i++)
10169 		custom_sec_defs[i - 1] = custom_sec_defs[i];
10170 	custom_sec_def_cnt--;
10171 
10172 	/* try to shrink the array, but it's ok if we couldn't */
10173 	sec_defs = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt, sizeof(*sec_defs));
10174 	/* if new count is zero, reallocarray can return a valid NULL result;
10175 	 * in this case the previous pointer will be freed, so we *have to*
10176 	 * reassign old pointer to the new value (even if it's NULL)
10177 	 */
10178 	if (sec_defs || custom_sec_def_cnt == 0)
10179 		custom_sec_defs = sec_defs;
10180 
10181 	return 0;
10182 }
10183 
10184 static bool sec_def_matches(const struct bpf_sec_def *sec_def, const char *sec_name)
10185 {
10186 	size_t len = strlen(sec_def->sec);
10187 
10188 	/* "type/" always has to have proper SEC("type/extras") form */
10189 	if (sec_def->sec[len - 1] == '/') {
10190 		if (str_has_pfx(sec_name, sec_def->sec))
10191 			return true;
10192 		return false;
10193 	}
10194 
10195 	/* "type+" means it can be either exact SEC("type") or
10196 	 * well-formed SEC("type/extras") with proper '/' separator
10197 	 */
10198 	if (sec_def->sec[len - 1] == '+') {
10199 		len--;
10200 		/* not even a prefix */
10201 		if (strncmp(sec_name, sec_def->sec, len) != 0)
10202 			return false;
10203 		/* exact match or has '/' separator */
10204 		if (sec_name[len] == '\0' || sec_name[len] == '/')
10205 			return true;
10206 		return false;
10207 	}
10208 
10209 	return strcmp(sec_name, sec_def->sec) == 0;
10210 }
10211 
10212 static const struct bpf_sec_def *find_sec_def(const char *sec_name)
10213 {
10214 	const struct bpf_sec_def *sec_def;
10215 	int i, n;
10216 
10217 	n = custom_sec_def_cnt;
10218 	for (i = 0; i < n; i++) {
10219 		sec_def = &custom_sec_defs[i];
10220 		if (sec_def_matches(sec_def, sec_name))
10221 			return sec_def;
10222 	}
10223 
10224 	n = ARRAY_SIZE(section_defs);
10225 	for (i = 0; i < n; i++) {
10226 		sec_def = &section_defs[i];
10227 		if (sec_def_matches(sec_def, sec_name))
10228 			return sec_def;
10229 	}
10230 
10231 	if (has_custom_fallback_def)
10232 		return &custom_fallback_def;
10233 
10234 	return NULL;
10235 }
10236 
10237 #define MAX_TYPE_NAME_SIZE 32
10238 
10239 static char *libbpf_get_type_names(bool attach_type)
10240 {
10241 	int i, len = ARRAY_SIZE(section_defs) * MAX_TYPE_NAME_SIZE;
10242 	char *buf;
10243 
10244 	buf = malloc(len);
10245 	if (!buf)
10246 		return NULL;
10247 
10248 	buf[0] = '\0';
10249 	/* Forge string buf with all available names */
10250 	for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
10251 		const struct bpf_sec_def *sec_def = &section_defs[i];
10252 
10253 		if (attach_type) {
10254 			if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
10255 				continue;
10256 
10257 			if (!(sec_def->cookie & SEC_ATTACHABLE))
10258 				continue;
10259 		}
10260 
10261 		if (strlen(buf) + strlen(section_defs[i].sec) + 2 > len) {
10262 			free(buf);
10263 			return NULL;
10264 		}
10265 		strcat(buf, " ");
10266 		strcat(buf, section_defs[i].sec);
10267 	}
10268 
10269 	return buf;
10270 }
10271 
10272 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
10273 			     enum bpf_attach_type *expected_attach_type)
10274 {
10275 	const struct bpf_sec_def *sec_def;
10276 	char *type_names;
10277 
10278 	if (!name)
10279 		return libbpf_err(-EINVAL);
10280 
10281 	sec_def = find_sec_def(name);
10282 	if (sec_def) {
10283 		*prog_type = sec_def->prog_type;
10284 		*expected_attach_type = sec_def->expected_attach_type;
10285 		return 0;
10286 	}
10287 
10288 	pr_debug("failed to guess program type from ELF section '%s'\n", name);
10289 	type_names = libbpf_get_type_names(false);
10290 	if (type_names != NULL) {
10291 		pr_debug("supported section(type) names are:%s\n", type_names);
10292 		free(type_names);
10293 	}
10294 
10295 	return libbpf_err(-ESRCH);
10296 }
10297 
10298 const char *libbpf_bpf_attach_type_str(enum bpf_attach_type t)
10299 {
10300 	if (t < 0 || t >= ARRAY_SIZE(attach_type_name))
10301 		return NULL;
10302 
10303 	return attach_type_name[t];
10304 }
10305 
10306 const char *libbpf_bpf_link_type_str(enum bpf_link_type t)
10307 {
10308 	if (t < 0 || t >= ARRAY_SIZE(link_type_name))
10309 		return NULL;
10310 
10311 	return link_type_name[t];
10312 }
10313 
10314 const char *libbpf_bpf_map_type_str(enum bpf_map_type t)
10315 {
10316 	if (t < 0 || t >= ARRAY_SIZE(map_type_name))
10317 		return NULL;
10318 
10319 	return map_type_name[t];
10320 }
10321 
10322 const char *libbpf_bpf_prog_type_str(enum bpf_prog_type t)
10323 {
10324 	if (t < 0 || t >= ARRAY_SIZE(prog_type_name))
10325 		return NULL;
10326 
10327 	return prog_type_name[t];
10328 }
10329 
10330 static struct bpf_map *find_struct_ops_map_by_offset(struct bpf_object *obj,
10331 						     int sec_idx,
10332 						     size_t offset)
10333 {
10334 	struct bpf_map *map;
10335 	size_t i;
10336 
10337 	for (i = 0; i < obj->nr_maps; i++) {
10338 		map = &obj->maps[i];
10339 		if (!bpf_map__is_struct_ops(map))
10340 			continue;
10341 		if (map->sec_idx == sec_idx &&
10342 		    map->sec_offset <= offset &&
10343 		    offset - map->sec_offset < map->def.value_size)
10344 			return map;
10345 	}
10346 
10347 	return NULL;
10348 }
10349 
10350 /* Collect the reloc from ELF, populate the st_ops->progs[], and update
10351  * st_ops->data for shadow type.
10352  */
10353 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
10354 					    Elf64_Shdr *shdr, Elf_Data *data)
10355 {
10356 	const struct btf_type *type;
10357 	const struct btf_member *member;
10358 	struct bpf_struct_ops *st_ops;
10359 	struct bpf_program *prog;
10360 	unsigned int shdr_idx;
10361 	const struct btf *btf;
10362 	struct bpf_map *map;
10363 	unsigned int moff, insn_idx;
10364 	const char *name;
10365 	__u32 member_idx;
10366 	Elf64_Sym *sym;
10367 	Elf64_Rel *rel;
10368 	int i, nrels;
10369 
10370 	btf = obj->btf;
10371 	nrels = shdr->sh_size / shdr->sh_entsize;
10372 	for (i = 0; i < nrels; i++) {
10373 		rel = elf_rel_by_idx(data, i);
10374 		if (!rel) {
10375 			pr_warn("struct_ops reloc: failed to get %d reloc\n", i);
10376 			return -LIBBPF_ERRNO__FORMAT;
10377 		}
10378 
10379 		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
10380 		if (!sym) {
10381 			pr_warn("struct_ops reloc: symbol %zx not found\n",
10382 				(size_t)ELF64_R_SYM(rel->r_info));
10383 			return -LIBBPF_ERRNO__FORMAT;
10384 		}
10385 
10386 		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
10387 		map = find_struct_ops_map_by_offset(obj, shdr->sh_info, rel->r_offset);
10388 		if (!map) {
10389 			pr_warn("struct_ops reloc: cannot find map at rel->r_offset %zu\n",
10390 				(size_t)rel->r_offset);
10391 			return -EINVAL;
10392 		}
10393 
10394 		moff = rel->r_offset - map->sec_offset;
10395 		shdr_idx = sym->st_shndx;
10396 		st_ops = map->st_ops;
10397 		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",
10398 			 map->name,
10399 			 (long long)(rel->r_info >> 32),
10400 			 (long long)sym->st_value,
10401 			 shdr_idx, (size_t)rel->r_offset,
10402 			 map->sec_offset, sym->st_name, name);
10403 
10404 		if (shdr_idx >= SHN_LORESERVE) {
10405 			pr_warn("struct_ops reloc %s: rel->r_offset %zu shdr_idx %u unsupported non-static function\n",
10406 				map->name, (size_t)rel->r_offset, shdr_idx);
10407 			return -LIBBPF_ERRNO__RELOC;
10408 		}
10409 		if (sym->st_value % BPF_INSN_SZ) {
10410 			pr_warn("struct_ops reloc %s: invalid target program offset %llu\n",
10411 				map->name, (unsigned long long)sym->st_value);
10412 			return -LIBBPF_ERRNO__FORMAT;
10413 		}
10414 		insn_idx = sym->st_value / BPF_INSN_SZ;
10415 
10416 		type = btf__type_by_id(btf, st_ops->type_id);
10417 		member = find_member_by_offset(type, moff * 8);
10418 		if (!member) {
10419 			pr_warn("struct_ops reloc %s: cannot find member at moff %u\n",
10420 				map->name, moff);
10421 			return -EINVAL;
10422 		}
10423 		member_idx = member - btf_members(type);
10424 		name = btf__name_by_offset(btf, member->name_off);
10425 
10426 		if (!resolve_func_ptr(btf, member->type, NULL)) {
10427 			pr_warn("struct_ops reloc %s: cannot relocate non func ptr %s\n",
10428 				map->name, name);
10429 			return -EINVAL;
10430 		}
10431 
10432 		prog = find_prog_by_sec_insn(obj, shdr_idx, insn_idx);
10433 		if (!prog) {
10434 			pr_warn("struct_ops reloc %s: cannot find prog at shdr_idx %u to relocate func ptr %s\n",
10435 				map->name, shdr_idx, name);
10436 			return -EINVAL;
10437 		}
10438 
10439 		/* prevent the use of BPF prog with invalid type */
10440 		if (prog->type != BPF_PROG_TYPE_STRUCT_OPS) {
10441 			pr_warn("struct_ops reloc %s: prog %s is not struct_ops BPF program\n",
10442 				map->name, prog->name);
10443 			return -EINVAL;
10444 		}
10445 
10446 		st_ops->progs[member_idx] = prog;
10447 
10448 		/* st_ops->data will be exposed to users, being returned by
10449 		 * bpf_map__initial_value() as a pointer to the shadow
10450 		 * type. All function pointers in the original struct type
10451 		 * should be converted to a pointer to struct bpf_program
10452 		 * in the shadow type.
10453 		 */
10454 		*((struct bpf_program **)(st_ops->data + moff)) = prog;
10455 	}
10456 
10457 	return 0;
10458 }
10459 
10460 #define BTF_TRACE_PREFIX "btf_trace_"
10461 #define BTF_LSM_PREFIX "bpf_lsm_"
10462 #define BTF_ITER_PREFIX "bpf_iter_"
10463 #define BTF_MAX_NAME_SIZE 128
10464 
10465 void btf_get_kernel_prefix_kind(enum bpf_attach_type attach_type,
10466 				const char **prefix, int *kind)
10467 {
10468 	switch (attach_type) {
10469 	case BPF_TRACE_RAW_TP:
10470 		*prefix = BTF_TRACE_PREFIX;
10471 		*kind = BTF_KIND_TYPEDEF;
10472 		break;
10473 	case BPF_LSM_MAC:
10474 	case BPF_LSM_CGROUP:
10475 		*prefix = BTF_LSM_PREFIX;
10476 		*kind = BTF_KIND_FUNC;
10477 		break;
10478 	case BPF_TRACE_ITER:
10479 		*prefix = BTF_ITER_PREFIX;
10480 		*kind = BTF_KIND_FUNC;
10481 		break;
10482 	default:
10483 		*prefix = "";
10484 		*kind = BTF_KIND_FUNC;
10485 	}
10486 }
10487 
10488 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
10489 				   const char *name, __u32 kind)
10490 {
10491 	char btf_type_name[BTF_MAX_NAME_SIZE];
10492 	int ret;
10493 
10494 	ret = snprintf(btf_type_name, sizeof(btf_type_name),
10495 		       "%s%s", prefix, name);
10496 	/* snprintf returns the number of characters written excluding the
10497 	 * terminating null. So, if >= BTF_MAX_NAME_SIZE are written, it
10498 	 * indicates truncation.
10499 	 */
10500 	if (ret < 0 || ret >= sizeof(btf_type_name))
10501 		return -ENAMETOOLONG;
10502 	return btf__find_by_name_kind(btf, btf_type_name, kind);
10503 }
10504 
10505 static inline int find_attach_btf_id(struct btf *btf, const char *name,
10506 				     enum bpf_attach_type attach_type)
10507 {
10508 	const char *prefix;
10509 	int kind;
10510 
10511 	btf_get_kernel_prefix_kind(attach_type, &prefix, &kind);
10512 	return find_btf_by_prefix_kind(btf, prefix, name, kind);
10513 }
10514 
10515 int libbpf_find_vmlinux_btf_id(const char *name,
10516 			       enum bpf_attach_type attach_type)
10517 {
10518 	struct btf *btf;
10519 	int err;
10520 
10521 	btf = btf__load_vmlinux_btf();
10522 	err = libbpf_get_error(btf);
10523 	if (err) {
10524 		pr_warn("vmlinux BTF is not found\n");
10525 		return libbpf_err(err);
10526 	}
10527 
10528 	err = find_attach_btf_id(btf, name, attach_type);
10529 	if (err <= 0)
10530 		pr_warn("%s is not found in vmlinux BTF\n", name);
10531 
10532 	btf__free(btf);
10533 	return libbpf_err(err);
10534 }
10535 
10536 static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd, int token_fd)
10537 {
10538 	struct bpf_prog_info info;
10539 	__u32 info_len = sizeof(info);
10540 	struct btf *btf;
10541 	int err;
10542 
10543 	memset(&info, 0, info_len);
10544 	err = bpf_prog_get_info_by_fd(attach_prog_fd, &info, &info_len);
10545 	if (err) {
10546 		pr_warn("failed bpf_prog_get_info_by_fd for FD %d: %s\n",
10547 			attach_prog_fd, errstr(err));
10548 		return err;
10549 	}
10550 
10551 	err = -EINVAL;
10552 	if (!info.btf_id) {
10553 		pr_warn("The target program doesn't have BTF\n");
10554 		goto out;
10555 	}
10556 	btf = btf_load_from_kernel(info.btf_id, NULL, token_fd);
10557 	err = libbpf_get_error(btf);
10558 	if (err) {
10559 		pr_warn("Failed to get BTF %d of the program: %s\n", info.btf_id, errstr(err));
10560 		goto out;
10561 	}
10562 	err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
10563 	btf__free(btf);
10564 	if (err <= 0) {
10565 		pr_warn("%s is not found in prog's BTF\n", name);
10566 		goto out;
10567 	}
10568 out:
10569 	return err;
10570 }
10571 
10572 static int find_kernel_btf_id(struct bpf_object *obj, const char *attach_name,
10573 			      enum bpf_attach_type attach_type,
10574 			      int *btf_obj_fd, int *btf_type_id)
10575 {
10576 	int ret, i, mod_len = 0;
10577 	const char *fn_name, *mod_name = NULL;
10578 
10579 	fn_name = strchr(attach_name, ':');
10580 	if (fn_name) {
10581 		mod_name = attach_name;
10582 		mod_len = fn_name - mod_name;
10583 		fn_name++;
10584 	}
10585 
10586 	if (!mod_name || strncmp(mod_name, "vmlinux", mod_len) == 0) {
10587 		ret = find_attach_btf_id(obj->btf_vmlinux,
10588 					 mod_name ? fn_name : attach_name,
10589 					 attach_type);
10590 		if (ret > 0) {
10591 			*btf_obj_fd = 0; /* vmlinux BTF */
10592 			*btf_type_id = ret;
10593 			return 0;
10594 		}
10595 		if (ret != -ENOENT)
10596 			return ret;
10597 	}
10598 
10599 	ret = load_module_btfs(obj);
10600 	if (ret)
10601 		return ret;
10602 
10603 	for (i = 0; i < obj->btf_module_cnt; i++) {
10604 		const struct module_btf *mod = &obj->btf_modules[i];
10605 
10606 		if (mod_name && strncmp(mod->name, mod_name, mod_len) != 0)
10607 			continue;
10608 
10609 		ret = find_attach_btf_id(mod->btf,
10610 					 mod_name ? fn_name : attach_name,
10611 					 attach_type);
10612 		if (ret > 0) {
10613 			*btf_obj_fd = mod->fd;
10614 			*btf_type_id = ret;
10615 			return 0;
10616 		}
10617 		if (ret == -ENOENT)
10618 			continue;
10619 
10620 		return ret;
10621 	}
10622 
10623 	return -ESRCH;
10624 }
10625 
10626 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
10627 				     int *btf_obj_fd, int *btf_type_id)
10628 {
10629 	enum bpf_attach_type attach_type = prog->expected_attach_type;
10630 	__u32 attach_prog_fd = prog->attach_prog_fd;
10631 	int err = 0;
10632 
10633 	/* BPF program's BTF ID */
10634 	if (prog->type == BPF_PROG_TYPE_EXT || attach_prog_fd) {
10635 		if (!attach_prog_fd) {
10636 			pr_warn("prog '%s': attach program FD is not set\n", prog->name);
10637 			return -EINVAL;
10638 		}
10639 		err = libbpf_find_prog_btf_id(attach_name, attach_prog_fd, prog->obj->token_fd);
10640 		if (err < 0) {
10641 			pr_warn("prog '%s': failed to find BPF program (FD %d) BTF ID for '%s': %s\n",
10642 				prog->name, attach_prog_fd, attach_name, errstr(err));
10643 			return err;
10644 		}
10645 		*btf_obj_fd = 0;
10646 		*btf_type_id = err;
10647 		return 0;
10648 	}
10649 
10650 	/* kernel/module BTF ID */
10651 	if (prog->obj->gen_loader) {
10652 		bpf_gen__record_attach_target(prog->obj->gen_loader, attach_name, attach_type);
10653 		*btf_obj_fd = 0;
10654 		*btf_type_id = 1;
10655 	} else {
10656 		err = find_kernel_btf_id(prog->obj, attach_name,
10657 					 attach_type, btf_obj_fd,
10658 					 btf_type_id);
10659 	}
10660 	if (err) {
10661 		pr_warn("prog '%s': failed to find kernel BTF type ID of '%s': %s\n",
10662 			prog->name, attach_name, errstr(err));
10663 		return err;
10664 	}
10665 	return 0;
10666 }
10667 
10668 int libbpf_attach_type_by_name(const char *name,
10669 			       enum bpf_attach_type *attach_type)
10670 {
10671 	char *type_names;
10672 	const struct bpf_sec_def *sec_def;
10673 
10674 	if (!name)
10675 		return libbpf_err(-EINVAL);
10676 
10677 	sec_def = find_sec_def(name);
10678 	if (!sec_def) {
10679 		pr_debug("failed to guess attach type based on ELF section name '%s'\n", name);
10680 		type_names = libbpf_get_type_names(true);
10681 		if (type_names != NULL) {
10682 			pr_debug("attachable section(type) names are:%s\n", type_names);
10683 			free(type_names);
10684 		}
10685 
10686 		return libbpf_err(-EINVAL);
10687 	}
10688 
10689 	if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
10690 		return libbpf_err(-EINVAL);
10691 	if (!(sec_def->cookie & SEC_ATTACHABLE))
10692 		return libbpf_err(-EINVAL);
10693 
10694 	*attach_type = sec_def->expected_attach_type;
10695 	return 0;
10696 }
10697 
10698 int bpf_map__fd(const struct bpf_map *map)
10699 {
10700 	if (!map)
10701 		return libbpf_err(-EINVAL);
10702 	if (!map_is_created(map))
10703 		return -1;
10704 	return map->fd;
10705 }
10706 
10707 static bool map_uses_real_name(const struct bpf_map *map)
10708 {
10709 	/* Since libbpf started to support custom .data.* and .rodata.* maps,
10710 	 * their user-visible name differs from kernel-visible name. Users see
10711 	 * such map's corresponding ELF section name as a map name.
10712 	 * This check distinguishes .data/.rodata from .data.* and .rodata.*
10713 	 * maps to know which name has to be returned to the user.
10714 	 */
10715 	if (map->libbpf_type == LIBBPF_MAP_DATA && strcmp(map->real_name, DATA_SEC) != 0)
10716 		return true;
10717 	if (map->libbpf_type == LIBBPF_MAP_RODATA && strcmp(map->real_name, RODATA_SEC) != 0)
10718 		return true;
10719 	return false;
10720 }
10721 
10722 const char *bpf_map__name(const struct bpf_map *map)
10723 {
10724 	if (!map)
10725 		return NULL;
10726 
10727 	if (map_uses_real_name(map))
10728 		return map->real_name;
10729 
10730 	return map->name;
10731 }
10732 
10733 enum bpf_map_type bpf_map__type(const struct bpf_map *map)
10734 {
10735 	return map->def.type;
10736 }
10737 
10738 int bpf_map__set_type(struct bpf_map *map, enum bpf_map_type type)
10739 {
10740 	if (map_is_created(map))
10741 		return libbpf_err(-EBUSY);
10742 	map->def.type = type;
10743 	return 0;
10744 }
10745 
10746 __u32 bpf_map__map_flags(const struct bpf_map *map)
10747 {
10748 	return map->def.map_flags;
10749 }
10750 
10751 int bpf_map__set_map_flags(struct bpf_map *map, __u32 flags)
10752 {
10753 	if (map_is_created(map))
10754 		return libbpf_err(-EBUSY);
10755 	map->def.map_flags = flags;
10756 	return 0;
10757 }
10758 
10759 __u64 bpf_map__map_extra(const struct bpf_map *map)
10760 {
10761 	return map->map_extra;
10762 }
10763 
10764 int bpf_map__set_map_extra(struct bpf_map *map, __u64 map_extra)
10765 {
10766 	if (map_is_created(map))
10767 		return libbpf_err(-EBUSY);
10768 	map->map_extra = map_extra;
10769 	return 0;
10770 }
10771 
10772 __u32 bpf_map__numa_node(const struct bpf_map *map)
10773 {
10774 	return map->numa_node;
10775 }
10776 
10777 int bpf_map__set_numa_node(struct bpf_map *map, __u32 numa_node)
10778 {
10779 	if (map_is_created(map))
10780 		return libbpf_err(-EBUSY);
10781 	map->numa_node = numa_node;
10782 	return 0;
10783 }
10784 
10785 __u32 bpf_map__key_size(const struct bpf_map *map)
10786 {
10787 	return map->def.key_size;
10788 }
10789 
10790 int bpf_map__set_key_size(struct bpf_map *map, __u32 size)
10791 {
10792 	if (map_is_created(map))
10793 		return libbpf_err(-EBUSY);
10794 	map->def.key_size = size;
10795 	return 0;
10796 }
10797 
10798 __u32 bpf_map__value_size(const struct bpf_map *map)
10799 {
10800 	return map->def.value_size;
10801 }
10802 
10803 static int map_btf_datasec_resize(struct bpf_map *map, __u32 size)
10804 {
10805 	struct btf *btf;
10806 	struct btf_type *datasec_type, *var_type;
10807 	struct btf_var_secinfo *var;
10808 	const struct btf_type *array_type;
10809 	const struct btf_array *array;
10810 	int vlen, element_sz, new_array_id;
10811 	__u32 nr_elements;
10812 
10813 	/* check btf existence */
10814 	btf = bpf_object__btf(map->obj);
10815 	if (!btf)
10816 		return -ENOENT;
10817 
10818 	/* verify map is datasec */
10819 	datasec_type = btf_type_by_id(btf, bpf_map__btf_value_type_id(map));
10820 	if (!btf_is_datasec(datasec_type)) {
10821 		pr_warn("map '%s': cannot be resized, map value type is not a datasec\n",
10822 			bpf_map__name(map));
10823 		return -EINVAL;
10824 	}
10825 
10826 	/* verify datasec has at least one var */
10827 	vlen = btf_vlen(datasec_type);
10828 	if (vlen == 0) {
10829 		pr_warn("map '%s': cannot be resized, map value datasec is empty\n",
10830 			bpf_map__name(map));
10831 		return -EINVAL;
10832 	}
10833 
10834 	/* verify last var in the datasec is an array */
10835 	var = &btf_var_secinfos(datasec_type)[vlen - 1];
10836 	var_type = btf_type_by_id(btf, var->type);
10837 	array_type = skip_mods_and_typedefs(btf, var_type->type, NULL);
10838 	if (!btf_is_array(array_type)) {
10839 		pr_warn("map '%s': cannot be resized, last var must be an array\n",
10840 			bpf_map__name(map));
10841 		return -EINVAL;
10842 	}
10843 
10844 	/* verify request size aligns with array */
10845 	array = btf_array(array_type);
10846 	element_sz = btf__resolve_size(btf, array->type);
10847 	if (element_sz <= 0 || (size - var->offset) % element_sz != 0) {
10848 		pr_warn("map '%s': cannot be resized, element size (%d) doesn't align with new total size (%u)\n",
10849 			bpf_map__name(map), element_sz, size);
10850 		return -EINVAL;
10851 	}
10852 
10853 	/* create a new array based on the existing array, but with new length */
10854 	nr_elements = (size - var->offset) / element_sz;
10855 	new_array_id = btf__add_array(btf, array->index_type, array->type, nr_elements);
10856 	if (new_array_id < 0)
10857 		return new_array_id;
10858 
10859 	/* adding a new btf type invalidates existing pointers to btf objects,
10860 	 * so refresh pointers before proceeding
10861 	 */
10862 	datasec_type = btf_type_by_id(btf, map->btf_value_type_id);
10863 	var = &btf_var_secinfos(datasec_type)[vlen - 1];
10864 	var_type = btf_type_by_id(btf, var->type);
10865 
10866 	/* finally update btf info */
10867 	datasec_type->size = size;
10868 	var->size = size - var->offset;
10869 	var_type->type = new_array_id;
10870 
10871 	return 0;
10872 }
10873 
10874 int bpf_map__set_value_size(struct bpf_map *map, __u32 size)
10875 {
10876 	if (map_is_created(map))
10877 		return libbpf_err(-EBUSY);
10878 
10879 	if (map->mmaped) {
10880 		size_t mmap_old_sz, mmap_new_sz;
10881 		int err;
10882 
10883 		if (map->def.type != BPF_MAP_TYPE_ARRAY)
10884 			return libbpf_err(-EOPNOTSUPP);
10885 
10886 		mmap_old_sz = bpf_map_mmap_sz(map);
10887 		mmap_new_sz = array_map_mmap_sz(size, map->def.max_entries);
10888 		err = bpf_map_mmap_resize(map, mmap_old_sz, mmap_new_sz);
10889 		if (err) {
10890 			pr_warn("map '%s': failed to resize memory-mapped region: %s\n",
10891 				bpf_map__name(map), errstr(err));
10892 			return libbpf_err(err);
10893 		}
10894 		err = map_btf_datasec_resize(map, size);
10895 		if (err && err != -ENOENT) {
10896 			pr_warn("map '%s': failed to adjust resized BTF, clearing BTF key/value info: %s\n",
10897 				bpf_map__name(map), errstr(err));
10898 			map->btf_value_type_id = 0;
10899 			map->btf_key_type_id = 0;
10900 		}
10901 	}
10902 
10903 	map->def.value_size = size;
10904 	return 0;
10905 }
10906 
10907 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
10908 {
10909 	return map ? map->btf_key_type_id : 0;
10910 }
10911 
10912 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
10913 {
10914 	return map ? map->btf_value_type_id : 0;
10915 }
10916 
10917 int bpf_map__set_initial_value(struct bpf_map *map,
10918 			       const void *data, size_t size)
10919 {
10920 	size_t actual_sz;
10921 
10922 	if (map_is_created(map))
10923 		return libbpf_err(-EBUSY);
10924 
10925 	if (!map->mmaped || map->libbpf_type == LIBBPF_MAP_KCONFIG)
10926 		return libbpf_err(-EINVAL);
10927 
10928 	if (map->def.type == BPF_MAP_TYPE_ARENA)
10929 		actual_sz = map->obj->arena_data_sz;
10930 	else
10931 		actual_sz = map->def.value_size;
10932 	if (size != actual_sz)
10933 		return libbpf_err(-EINVAL);
10934 
10935 	memcpy(map->mmaped, data, size);
10936 	return 0;
10937 }
10938 
10939 void *bpf_map__initial_value(const struct bpf_map *map, size_t *psize)
10940 {
10941 	if (bpf_map__is_struct_ops(map)) {
10942 		if (psize)
10943 			*psize = map->def.value_size;
10944 		return map->st_ops->data;
10945 	}
10946 
10947 	if (!map->mmaped)
10948 		return NULL;
10949 
10950 	if (map->def.type == BPF_MAP_TYPE_ARENA)
10951 		*psize = map->obj->arena_data_sz;
10952 	else
10953 		*psize = map->def.value_size;
10954 
10955 	return map->mmaped;
10956 }
10957 
10958 bool bpf_map__is_internal(const struct bpf_map *map)
10959 {
10960 	return map->libbpf_type != LIBBPF_MAP_UNSPEC;
10961 }
10962 
10963 __u32 bpf_map__ifindex(const struct bpf_map *map)
10964 {
10965 	return map->map_ifindex;
10966 }
10967 
10968 int bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
10969 {
10970 	if (map_is_created(map))
10971 		return libbpf_err(-EBUSY);
10972 	map->map_ifindex = ifindex;
10973 	return 0;
10974 }
10975 
10976 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
10977 {
10978 	if (!bpf_map_type__is_map_in_map(map->def.type)) {
10979 		pr_warn("error: unsupported map type\n");
10980 		return libbpf_err(-EINVAL);
10981 	}
10982 	if (map->inner_map_fd != -1) {
10983 		pr_warn("error: inner_map_fd already specified\n");
10984 		return libbpf_err(-EINVAL);
10985 	}
10986 	if (map->inner_map) {
10987 		bpf_map__destroy(map->inner_map);
10988 		zfree(&map->inner_map);
10989 	}
10990 	map->inner_map_fd = fd;
10991 	return 0;
10992 }
10993 
10994 int bpf_map__set_exclusive_program(struct bpf_map *map, struct bpf_program *prog)
10995 {
10996 	if (map_is_created(map)) {
10997 		pr_warn("exclusive programs must be set before map creation\n");
10998 		return libbpf_err(-EINVAL);
10999 	}
11000 
11001 	if (map->obj != prog->obj) {
11002 		pr_warn("excl_prog and map must be from the same bpf object\n");
11003 		return libbpf_err(-EINVAL);
11004 	}
11005 
11006 	map->excl_prog = prog;
11007 	return 0;
11008 }
11009 
11010 struct bpf_program *bpf_map__exclusive_program(struct bpf_map *map)
11011 {
11012 	return map->excl_prog;
11013 }
11014 
11015 static struct bpf_map *
11016 __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
11017 {
11018 	ssize_t idx;
11019 	struct bpf_map *s, *e;
11020 
11021 	if (!obj || !obj->maps)
11022 		return errno = EINVAL, NULL;
11023 
11024 	s = obj->maps;
11025 	e = obj->maps + obj->nr_maps;
11026 
11027 	if ((m < s) || (m >= e)) {
11028 		pr_warn("error in %s: map handler doesn't belong to object\n",
11029 			 __func__);
11030 		return errno = EINVAL, NULL;
11031 	}
11032 
11033 	idx = (m - obj->maps) + i;
11034 	if (idx >= obj->nr_maps || idx < 0)
11035 		return NULL;
11036 	return &obj->maps[idx];
11037 }
11038 
11039 struct bpf_map *
11040 bpf_object__next_map(const struct bpf_object *obj, const struct bpf_map *prev)
11041 {
11042 	if (prev == NULL && obj != NULL)
11043 		return obj->maps;
11044 
11045 	return __bpf_map__iter(prev, obj, 1);
11046 }
11047 
11048 struct bpf_map *
11049 bpf_object__prev_map(const struct bpf_object *obj, const struct bpf_map *next)
11050 {
11051 	if (next == NULL && obj != NULL) {
11052 		if (!obj->nr_maps)
11053 			return NULL;
11054 		return obj->maps + obj->nr_maps - 1;
11055 	}
11056 
11057 	return __bpf_map__iter(next, obj, -1);
11058 }
11059 
11060 struct bpf_map *
11061 bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
11062 {
11063 	struct bpf_map *pos;
11064 
11065 	bpf_object__for_each_map(pos, obj) {
11066 		/* if it's a special internal map name (which always starts
11067 		 * with dot) then check if that special name matches the
11068 		 * real map name (ELF section name)
11069 		 */
11070 		if (name[0] == '.') {
11071 			if (pos->real_name && strcmp(pos->real_name, name) == 0)
11072 				return pos;
11073 			continue;
11074 		}
11075 		/* otherwise map name has to be an exact match */
11076 		if (map_uses_real_name(pos)) {
11077 			if (strcmp(pos->real_name, name) == 0)
11078 				return pos;
11079 			continue;
11080 		}
11081 		if (strcmp(pos->name, name) == 0)
11082 			return pos;
11083 	}
11084 	return errno = ENOENT, NULL;
11085 }
11086 
11087 int
11088 bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
11089 {
11090 	return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
11091 }
11092 
11093 static int validate_map_op(const struct bpf_map *map, size_t key_sz,
11094 			   size_t value_sz, bool check_value_sz, __u64 flags)
11095 {
11096 	if (!map_is_created(map)) /* map is not yet created */
11097 		return -ENOENT;
11098 
11099 	if (map->def.key_size != key_sz) {
11100 		pr_warn("map '%s': unexpected key size %zu provided, expected %u\n",
11101 			map->name, key_sz, map->def.key_size);
11102 		return -EINVAL;
11103 	}
11104 
11105 	if (map->fd < 0) {
11106 		pr_warn("map '%s': can't use BPF map without FD (was it created?)\n", map->name);
11107 		return -EINVAL;
11108 	}
11109 
11110 	if (!check_value_sz)
11111 		return 0;
11112 
11113 	switch (map->def.type) {
11114 	case BPF_MAP_TYPE_PERCPU_ARRAY:
11115 	case BPF_MAP_TYPE_PERCPU_HASH:
11116 	case BPF_MAP_TYPE_LRU_PERCPU_HASH:
11117 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: {
11118 		int num_cpu = libbpf_num_possible_cpus();
11119 		size_t elem_sz = roundup(map->def.value_size, 8);
11120 
11121 		if (flags & (BPF_F_CPU | BPF_F_ALL_CPUS)) {
11122 			if ((flags & BPF_F_CPU) && (flags & BPF_F_ALL_CPUS)) {
11123 				pr_warn("map '%s': BPF_F_CPU and BPF_F_ALL_CPUS are mutually exclusive\n",
11124 					map->name);
11125 				return -EINVAL;
11126 			}
11127 			if (map->def.value_size != value_sz) {
11128 				pr_warn("map '%s': unexpected value size %zu provided for either BPF_F_CPU or BPF_F_ALL_CPUS, expected %u\n",
11129 					map->name, value_sz, map->def.value_size);
11130 				return -EINVAL;
11131 			}
11132 			break;
11133 		}
11134 
11135 		if (value_sz != num_cpu * elem_sz) {
11136 			pr_warn("map '%s': unexpected value size %zu provided for per-CPU map, expected %d * %zu = %zd\n",
11137 				map->name, value_sz, num_cpu, elem_sz, num_cpu * elem_sz);
11138 			return -EINVAL;
11139 		}
11140 		break;
11141 	}
11142 	default:
11143 		if (map->def.value_size != value_sz) {
11144 			pr_warn("map '%s': unexpected value size %zu provided, expected %u\n",
11145 				map->name, value_sz, map->def.value_size);
11146 			return -EINVAL;
11147 		}
11148 		break;
11149 	}
11150 	return 0;
11151 }
11152 
11153 int bpf_map__lookup_elem(const struct bpf_map *map,
11154 			 const void *key, size_t key_sz,
11155 			 void *value, size_t value_sz, __u64 flags)
11156 {
11157 	int err;
11158 
11159 	err = validate_map_op(map, key_sz, value_sz, true, flags);
11160 	if (err)
11161 		return libbpf_err(err);
11162 
11163 	return bpf_map_lookup_elem_flags(map->fd, key, value, flags);
11164 }
11165 
11166 int bpf_map__update_elem(const struct bpf_map *map,
11167 			 const void *key, size_t key_sz,
11168 			 const void *value, size_t value_sz, __u64 flags)
11169 {
11170 	int err;
11171 
11172 	err = validate_map_op(map, key_sz, value_sz, true, flags);
11173 	if (err)
11174 		return libbpf_err(err);
11175 
11176 	return bpf_map_update_elem(map->fd, key, value, flags);
11177 }
11178 
11179 int bpf_map__delete_elem(const struct bpf_map *map,
11180 			 const void *key, size_t key_sz, __u64 flags)
11181 {
11182 	int err;
11183 
11184 	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */, flags);
11185 	if (err)
11186 		return libbpf_err(err);
11187 
11188 	return bpf_map_delete_elem_flags(map->fd, key, flags);
11189 }
11190 
11191 int bpf_map__lookup_and_delete_elem(const struct bpf_map *map,
11192 				    const void *key, size_t key_sz,
11193 				    void *value, size_t value_sz, __u64 flags)
11194 {
11195 	int err;
11196 
11197 	err = validate_map_op(map, key_sz, value_sz, true, flags);
11198 	if (err)
11199 		return libbpf_err(err);
11200 
11201 	return bpf_map_lookup_and_delete_elem_flags(map->fd, key, value, flags);
11202 }
11203 
11204 int bpf_map__get_next_key(const struct bpf_map *map,
11205 			  const void *cur_key, void *next_key, size_t key_sz)
11206 {
11207 	int err;
11208 
11209 	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */, 0);
11210 	if (err)
11211 		return libbpf_err(err);
11212 
11213 	return bpf_map_get_next_key(map->fd, cur_key, next_key);
11214 }
11215 
11216 long libbpf_get_error(const void *ptr)
11217 {
11218 	if (!IS_ERR_OR_NULL(ptr))
11219 		return 0;
11220 
11221 	if (IS_ERR(ptr))
11222 		errno = -PTR_ERR(ptr);
11223 
11224 	/* If ptr == NULL, then errno should be already set by the failing
11225 	 * API, because libbpf never returns NULL on success and it now always
11226 	 * sets errno on error. So no extra errno handling for ptr == NULL
11227 	 * case.
11228 	 */
11229 	return -errno;
11230 }
11231 
11232 /* Replace link's underlying BPF program with the new one */
11233 int bpf_link__update_program(struct bpf_link *link, struct bpf_program *prog)
11234 {
11235 	int ret;
11236 	int prog_fd = bpf_program__fd(prog);
11237 
11238 	if (prog_fd < 0) {
11239 		pr_warn("prog '%s': can't use BPF program without FD (was it loaded?)\n",
11240 			prog->name);
11241 		return libbpf_err(-EINVAL);
11242 	}
11243 
11244 	ret = bpf_link_update(bpf_link__fd(link), prog_fd, NULL);
11245 	return libbpf_err_errno(ret);
11246 }
11247 
11248 /* Release "ownership" of underlying BPF resource (typically, BPF program
11249  * attached to some BPF hook, e.g., tracepoint, kprobe, etc). Disconnected
11250  * link, when destructed through bpf_link__destroy() call won't attempt to
11251  * detach/unregisted that BPF resource. This is useful in situations where,
11252  * say, attached BPF program has to outlive userspace program that attached it
11253  * in the system. Depending on type of BPF program, though, there might be
11254  * additional steps (like pinning BPF program in BPF FS) necessary to ensure
11255  * exit of userspace program doesn't trigger automatic detachment and clean up
11256  * inside the kernel.
11257  */
11258 void bpf_link__disconnect(struct bpf_link *link)
11259 {
11260 	link->disconnected = true;
11261 }
11262 
11263 int bpf_link__destroy(struct bpf_link *link)
11264 {
11265 	int err = 0;
11266 
11267 	if (IS_ERR_OR_NULL(link))
11268 		return 0;
11269 
11270 	if (!link->disconnected && link->detach)
11271 		err = link->detach(link);
11272 	if (link->pin_path)
11273 		free(link->pin_path);
11274 	if (link->dealloc)
11275 		link->dealloc(link);
11276 	else
11277 		free(link);
11278 
11279 	return libbpf_err(err);
11280 }
11281 
11282 int bpf_link__fd(const struct bpf_link *link)
11283 {
11284 	return link->fd;
11285 }
11286 
11287 const char *bpf_link__pin_path(const struct bpf_link *link)
11288 {
11289 	return link->pin_path;
11290 }
11291 
11292 static int bpf_link__detach_fd(struct bpf_link *link)
11293 {
11294 	return libbpf_err_errno(close(link->fd));
11295 }
11296 
11297 struct bpf_link *bpf_link__open(const char *path)
11298 {
11299 	struct bpf_link *link;
11300 	int fd;
11301 
11302 	fd = bpf_obj_get(path);
11303 	if (fd < 0) {
11304 		fd = -errno;
11305 		pr_warn("failed to open link at %s: %d\n", path, fd);
11306 		return libbpf_err_ptr(fd);
11307 	}
11308 
11309 	link = calloc(1, sizeof(*link));
11310 	if (!link) {
11311 		close(fd);
11312 		return libbpf_err_ptr(-ENOMEM);
11313 	}
11314 	link->detach = &bpf_link__detach_fd;
11315 	link->fd = fd;
11316 
11317 	link->pin_path = strdup(path);
11318 	if (!link->pin_path) {
11319 		bpf_link__destroy(link);
11320 		return libbpf_err_ptr(-ENOMEM);
11321 	}
11322 
11323 	return link;
11324 }
11325 
11326 int bpf_link__detach(struct bpf_link *link)
11327 {
11328 	return bpf_link_detach(link->fd) ? -errno : 0;
11329 }
11330 
11331 int bpf_link__pin(struct bpf_link *link, const char *path)
11332 {
11333 	int err;
11334 
11335 	if (link->pin_path)
11336 		return libbpf_err(-EBUSY);
11337 	err = make_parent_dir(path);
11338 	if (err)
11339 		return libbpf_err(err);
11340 	err = check_path(path);
11341 	if (err)
11342 		return libbpf_err(err);
11343 
11344 	link->pin_path = strdup(path);
11345 	if (!link->pin_path)
11346 		return libbpf_err(-ENOMEM);
11347 
11348 	if (bpf_obj_pin(link->fd, link->pin_path)) {
11349 		err = -errno;
11350 		zfree(&link->pin_path);
11351 		return libbpf_err(err);
11352 	}
11353 
11354 	pr_debug("link fd=%d: pinned at %s\n", link->fd, link->pin_path);
11355 	return 0;
11356 }
11357 
11358 int bpf_link__unpin(struct bpf_link *link)
11359 {
11360 	int err;
11361 
11362 	if (!link->pin_path)
11363 		return libbpf_err(-EINVAL);
11364 
11365 	err = unlink(link->pin_path);
11366 	if (err != 0)
11367 		return -errno;
11368 
11369 	pr_debug("link fd=%d: unpinned from %s\n", link->fd, link->pin_path);
11370 	zfree(&link->pin_path);
11371 	return 0;
11372 }
11373 
11374 struct bpf_link_perf {
11375 	struct bpf_link link;
11376 	int perf_event_fd;
11377 	/* legacy kprobe support: keep track of probe identifier and type */
11378 	char *legacy_probe_name;
11379 	bool legacy_is_kprobe;
11380 	bool legacy_is_retprobe;
11381 };
11382 
11383 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe);
11384 static int remove_uprobe_event_legacy(const char *probe_name, bool retprobe);
11385 
11386 static int bpf_link_perf_detach(struct bpf_link *link)
11387 {
11388 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
11389 	int err = 0;
11390 
11391 	if (ioctl(perf_link->perf_event_fd, PERF_EVENT_IOC_DISABLE, 0) < 0)
11392 		err = -errno;
11393 
11394 	if (perf_link->perf_event_fd != link->fd)
11395 		close(perf_link->perf_event_fd);
11396 	close(link->fd);
11397 
11398 	/* legacy uprobe/kprobe needs to be removed after perf event fd closure */
11399 	if (perf_link->legacy_probe_name) {
11400 		if (perf_link->legacy_is_kprobe) {
11401 			err = remove_kprobe_event_legacy(perf_link->legacy_probe_name,
11402 							 perf_link->legacy_is_retprobe);
11403 		} else {
11404 			err = remove_uprobe_event_legacy(perf_link->legacy_probe_name,
11405 							 perf_link->legacy_is_retprobe);
11406 		}
11407 	}
11408 
11409 	return err;
11410 }
11411 
11412 static void bpf_link_perf_dealloc(struct bpf_link *link)
11413 {
11414 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
11415 
11416 	free(perf_link->legacy_probe_name);
11417 	free(perf_link);
11418 }
11419 
11420 struct bpf_link *bpf_program__attach_perf_event_opts(const struct bpf_program *prog, int pfd,
11421 						     const struct bpf_perf_event_opts *opts)
11422 {
11423 	struct bpf_link_perf *link;
11424 	int prog_fd, link_fd = -1, err;
11425 	bool force_ioctl_attach;
11426 
11427 	if (!OPTS_VALID(opts, bpf_perf_event_opts))
11428 		return libbpf_err_ptr(-EINVAL);
11429 
11430 	if (pfd < 0) {
11431 		pr_warn("prog '%s': invalid perf event FD %d\n",
11432 			prog->name, pfd);
11433 		return libbpf_err_ptr(-EINVAL);
11434 	}
11435 	prog_fd = bpf_program__fd(prog);
11436 	if (prog_fd < 0) {
11437 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
11438 			prog->name);
11439 		return libbpf_err_ptr(-EINVAL);
11440 	}
11441 
11442 	link = calloc(1, sizeof(*link));
11443 	if (!link)
11444 		return libbpf_err_ptr(-ENOMEM);
11445 	link->link.detach = &bpf_link_perf_detach;
11446 	link->link.dealloc = &bpf_link_perf_dealloc;
11447 	link->perf_event_fd = pfd;
11448 
11449 	force_ioctl_attach = OPTS_GET(opts, force_ioctl_attach, false);
11450 	if (kernel_supports(prog->obj, FEAT_PERF_LINK) && !force_ioctl_attach) {
11451 		DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_opts,
11452 			.perf_event.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0));
11453 
11454 		link_fd = bpf_link_create(prog_fd, pfd, BPF_PERF_EVENT, &link_opts);
11455 		if (link_fd < 0) {
11456 			err = -errno;
11457 			pr_warn("prog '%s': failed to create BPF link for perf_event FD %d: %s\n",
11458 				prog->name, pfd, errstr(err));
11459 			goto err_out;
11460 		}
11461 		link->link.fd = link_fd;
11462 	} else {
11463 		if (OPTS_GET(opts, bpf_cookie, 0)) {
11464 			pr_warn("prog '%s': user context value is not supported\n", prog->name);
11465 			err = -EOPNOTSUPP;
11466 			goto err_out;
11467 		}
11468 
11469 		if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
11470 			err = -errno;
11471 			pr_warn("prog '%s': failed to attach to perf_event FD %d: %s\n",
11472 				prog->name, pfd, errstr(err));
11473 			if (err == -EPROTO)
11474 				pr_warn("prog '%s': try add PERF_SAMPLE_CALLCHAIN to or remove exclude_callchain_[kernel|user] from pfd %d\n",
11475 					prog->name, pfd);
11476 			goto err_out;
11477 		}
11478 		link->link.fd = pfd;
11479 	}
11480 
11481 	if (!OPTS_GET(opts, dont_enable, false)) {
11482 		if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
11483 			err = -errno;
11484 			pr_warn("prog '%s': failed to enable perf_event FD %d: %s\n",
11485 				prog->name, pfd, errstr(err));
11486 			goto err_out;
11487 		}
11488 	}
11489 
11490 	return &link->link;
11491 err_out:
11492 	if (link_fd >= 0)
11493 		close(link_fd);
11494 	free(link);
11495 	return libbpf_err_ptr(err);
11496 }
11497 
11498 struct bpf_link *bpf_program__attach_perf_event(const struct bpf_program *prog, int pfd)
11499 {
11500 	return bpf_program__attach_perf_event_opts(prog, pfd, NULL);
11501 }
11502 
11503 /*
11504  * this function is expected to parse integer in the range of [0, 2^31-1] from
11505  * given file using scanf format string fmt. If actual parsed value is
11506  * negative, the result might be indistinguishable from error
11507  */
11508 static int parse_uint_from_file(const char *file, const char *fmt)
11509 {
11510 	int err, ret;
11511 	FILE *f;
11512 
11513 	f = fopen(file, "re");
11514 	if (!f) {
11515 		err = -errno;
11516 		pr_debug("failed to open '%s': %s\n", file, errstr(err));
11517 		return err;
11518 	}
11519 	err = fscanf(f, fmt, &ret);
11520 	if (err != 1) {
11521 		err = err == EOF ? -EIO : -errno;
11522 		pr_debug("failed to parse '%s': %s\n", file, errstr(err));
11523 		fclose(f);
11524 		return err;
11525 	}
11526 	fclose(f);
11527 	return ret;
11528 }
11529 
11530 static int determine_kprobe_perf_type(void)
11531 {
11532 	const char *file = "/sys/bus/event_source/devices/kprobe/type";
11533 
11534 	return parse_uint_from_file(file, "%d\n");
11535 }
11536 
11537 static int determine_uprobe_perf_type(void)
11538 {
11539 	const char *file = "/sys/bus/event_source/devices/uprobe/type";
11540 
11541 	return parse_uint_from_file(file, "%d\n");
11542 }
11543 
11544 static int determine_kprobe_retprobe_bit(void)
11545 {
11546 	const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
11547 
11548 	return parse_uint_from_file(file, "config:%d\n");
11549 }
11550 
11551 static int determine_uprobe_retprobe_bit(void)
11552 {
11553 	const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
11554 
11555 	return parse_uint_from_file(file, "config:%d\n");
11556 }
11557 
11558 #define PERF_UPROBE_REF_CTR_OFFSET_BITS 32
11559 #define PERF_UPROBE_REF_CTR_OFFSET_SHIFT 32
11560 
11561 static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
11562 				 uint64_t offset, int pid, size_t ref_ctr_off)
11563 {
11564 	const size_t attr_sz = sizeof(struct perf_event_attr);
11565 	struct perf_event_attr attr;
11566 	int type, pfd;
11567 
11568 	if ((__u64)ref_ctr_off >= (1ULL << PERF_UPROBE_REF_CTR_OFFSET_BITS))
11569 		return -EINVAL;
11570 
11571 	memset(&attr, 0, attr_sz);
11572 
11573 	type = uprobe ? determine_uprobe_perf_type()
11574 		      : determine_kprobe_perf_type();
11575 	if (type < 0) {
11576 		pr_warn("failed to determine %s perf type: %s\n",
11577 			uprobe ? "uprobe" : "kprobe",
11578 			errstr(type));
11579 		return type;
11580 	}
11581 	if (retprobe) {
11582 		int bit = uprobe ? determine_uprobe_retprobe_bit()
11583 				 : determine_kprobe_retprobe_bit();
11584 
11585 		if (bit < 0) {
11586 			pr_warn("failed to determine %s retprobe bit: %s\n",
11587 				uprobe ? "uprobe" : "kprobe",
11588 				errstr(bit));
11589 			return bit;
11590 		}
11591 		attr.config |= 1 << bit;
11592 	}
11593 	attr.size = attr_sz;
11594 	attr.type = type;
11595 	attr.config |= (__u64)ref_ctr_off << PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
11596 	attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
11597 	attr.config2 = offset;		 /* kprobe_addr or probe_offset */
11598 
11599 	/* pid filter is meaningful only for uprobes */
11600 	pfd = syscall(__NR_perf_event_open, &attr,
11601 		      pid < 0 ? -1 : pid /* pid */,
11602 		      pid == -1 ? 0 : -1 /* cpu */,
11603 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
11604 	return pfd >= 0 ? pfd : -errno;
11605 }
11606 
11607 static int append_to_file(const char *file, const char *fmt, ...)
11608 {
11609 	int fd, n, err = 0;
11610 	va_list ap;
11611 	char buf[1024];
11612 
11613 	va_start(ap, fmt);
11614 	n = vsnprintf(buf, sizeof(buf), fmt, ap);
11615 	va_end(ap);
11616 
11617 	if (n < 0 || n >= sizeof(buf))
11618 		return -EINVAL;
11619 
11620 	fd = open(file, O_WRONLY | O_APPEND | O_CLOEXEC, 0);
11621 	if (fd < 0)
11622 		return -errno;
11623 
11624 	if (write(fd, buf, n) < 0)
11625 		err = -errno;
11626 
11627 	close(fd);
11628 	return err;
11629 }
11630 
11631 #define DEBUGFS "/sys/kernel/debug/tracing"
11632 #define TRACEFS "/sys/kernel/tracing"
11633 
11634 static bool use_debugfs(void)
11635 {
11636 	static int has_debugfs = -1;
11637 
11638 	if (has_debugfs < 0)
11639 		has_debugfs = faccessat(AT_FDCWD, DEBUGFS, F_OK, AT_EACCESS) == 0;
11640 
11641 	return has_debugfs == 1;
11642 }
11643 
11644 static const char *tracefs_path(void)
11645 {
11646 	return use_debugfs() ? DEBUGFS : TRACEFS;
11647 }
11648 
11649 static const char *tracefs_kprobe_events(void)
11650 {
11651 	return use_debugfs() ? DEBUGFS"/kprobe_events" : TRACEFS"/kprobe_events";
11652 }
11653 
11654 static const char *tracefs_uprobe_events(void)
11655 {
11656 	return use_debugfs() ? DEBUGFS"/uprobe_events" : TRACEFS"/uprobe_events";
11657 }
11658 
11659 static const char *tracefs_available_filter_functions(void)
11660 {
11661 	return use_debugfs() ? DEBUGFS"/available_filter_functions"
11662 			     : TRACEFS"/available_filter_functions";
11663 }
11664 
11665 static const char *tracefs_available_filter_functions_addrs(void)
11666 {
11667 	return use_debugfs() ? DEBUGFS"/available_filter_functions_addrs"
11668 			     : TRACEFS"/available_filter_functions_addrs";
11669 }
11670 
11671 static void gen_probe_legacy_event_name(char *buf, size_t buf_sz,
11672 					const char *name, size_t offset)
11673 {
11674 	static int index = 0;
11675 	int i;
11676 
11677 	snprintf(buf, buf_sz, "libbpf_%u_%d_%s_0x%zx", getpid(),
11678 		 __sync_fetch_and_add(&index, 1), name, offset);
11679 
11680 	/* sanitize name in the probe name */
11681 	for (i = 0; buf[i]; i++) {
11682 		if (!isalnum(buf[i]))
11683 			buf[i] = '_';
11684 	}
11685 }
11686 
11687 static int add_kprobe_event_legacy(const char *probe_name, bool retprobe,
11688 				   const char *kfunc_name, size_t offset)
11689 {
11690 	return append_to_file(tracefs_kprobe_events(), "%c:%s/%s %s+0x%zx",
11691 			      retprobe ? 'r' : 'p',
11692 			      retprobe ? "kretprobes" : "kprobes",
11693 			      probe_name, kfunc_name, offset);
11694 }
11695 
11696 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe)
11697 {
11698 	return append_to_file(tracefs_kprobe_events(), "-:%s/%s",
11699 			      retprobe ? "kretprobes" : "kprobes", probe_name);
11700 }
11701 
11702 static int determine_kprobe_perf_type_legacy(const char *probe_name, bool retprobe)
11703 {
11704 	char file[256];
11705 
11706 	snprintf(file, sizeof(file), "%s/events/%s/%s/id",
11707 		 tracefs_path(), retprobe ? "kretprobes" : "kprobes", probe_name);
11708 
11709 	return parse_uint_from_file(file, "%d\n");
11710 }
11711 
11712 static int perf_event_kprobe_open_legacy(const char *probe_name, bool retprobe,
11713 					 const char *kfunc_name, size_t offset, int pid)
11714 {
11715 	const size_t attr_sz = sizeof(struct perf_event_attr);
11716 	struct perf_event_attr attr;
11717 	int type, pfd, err;
11718 
11719 	err = add_kprobe_event_legacy(probe_name, retprobe, kfunc_name, offset);
11720 	if (err < 0) {
11721 		pr_warn("failed to add legacy kprobe event for '%s+0x%zx': %s\n",
11722 			kfunc_name, offset,
11723 			errstr(err));
11724 		return err;
11725 	}
11726 	type = determine_kprobe_perf_type_legacy(probe_name, retprobe);
11727 	if (type < 0) {
11728 		err = type;
11729 		pr_warn("failed to determine legacy kprobe event id for '%s+0x%zx': %s\n",
11730 			kfunc_name, offset,
11731 			errstr(err));
11732 		goto err_clean_legacy;
11733 	}
11734 
11735 	memset(&attr, 0, attr_sz);
11736 	attr.size = attr_sz;
11737 	attr.config = type;
11738 	attr.type = PERF_TYPE_TRACEPOINT;
11739 
11740 	pfd = syscall(__NR_perf_event_open, &attr,
11741 		      pid < 0 ? -1 : pid, /* pid */
11742 		      pid == -1 ? 0 : -1, /* cpu */
11743 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
11744 	if (pfd < 0) {
11745 		err = -errno;
11746 		pr_warn("legacy kprobe perf_event_open() failed: %s\n",
11747 			errstr(err));
11748 		goto err_clean_legacy;
11749 	}
11750 	return pfd;
11751 
11752 err_clean_legacy:
11753 	/* Clear the newly added legacy kprobe_event */
11754 	remove_kprobe_event_legacy(probe_name, retprobe);
11755 	return err;
11756 }
11757 
11758 static const char *arch_specific_syscall_pfx(void)
11759 {
11760 #if defined(__x86_64__)
11761 	return "x64";
11762 #elif defined(__i386__)
11763 	return "ia32";
11764 #elif defined(__s390x__)
11765 	return "s390x";
11766 #elif defined(__arm__)
11767 	return "arm";
11768 #elif defined(__aarch64__)
11769 	return "arm64";
11770 #elif defined(__mips__)
11771 	return "mips";
11772 #elif defined(__riscv)
11773 	return "riscv";
11774 #elif defined(__powerpc__)
11775 	return "powerpc";
11776 #elif defined(__powerpc64__)
11777 	return "powerpc64";
11778 #else
11779 	return NULL;
11780 #endif
11781 }
11782 
11783 int probe_kern_syscall_wrapper(int token_fd)
11784 {
11785 	char syscall_name[64];
11786 	const char *ksys_pfx;
11787 
11788 	ksys_pfx = arch_specific_syscall_pfx();
11789 	if (!ksys_pfx)
11790 		return 0;
11791 
11792 	snprintf(syscall_name, sizeof(syscall_name), "__%s_sys_bpf", ksys_pfx);
11793 
11794 	if (determine_kprobe_perf_type() >= 0) {
11795 		int pfd;
11796 
11797 		pfd = perf_event_open_probe(false, false, syscall_name, 0, getpid(), 0);
11798 		if (pfd >= 0)
11799 			close(pfd);
11800 
11801 		return pfd >= 0 ? 1 : 0;
11802 	} else { /* legacy mode */
11803 		char probe_name[MAX_EVENT_NAME_LEN];
11804 
11805 		gen_probe_legacy_event_name(probe_name, sizeof(probe_name), syscall_name, 0);
11806 		if (add_kprobe_event_legacy(probe_name, false, syscall_name, 0) < 0)
11807 			return 0;
11808 
11809 		(void)remove_kprobe_event_legacy(probe_name, false);
11810 		return 1;
11811 	}
11812 }
11813 
11814 struct bpf_link *
11815 bpf_program__attach_kprobe_opts(const struct bpf_program *prog,
11816 				const char *func_name,
11817 				const struct bpf_kprobe_opts *opts)
11818 {
11819 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
11820 	enum probe_attach_mode attach_mode;
11821 	char *legacy_probe = NULL;
11822 	struct bpf_link *link;
11823 	size_t offset;
11824 	bool retprobe, legacy;
11825 	int pfd, err;
11826 
11827 	if (!OPTS_VALID(opts, bpf_kprobe_opts))
11828 		return libbpf_err_ptr(-EINVAL);
11829 
11830 	attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
11831 	retprobe = OPTS_GET(opts, retprobe, false);
11832 	offset = OPTS_GET(opts, offset, 0);
11833 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11834 
11835 	legacy = determine_kprobe_perf_type() < 0;
11836 	switch (attach_mode) {
11837 	case PROBE_ATTACH_MODE_LEGACY:
11838 		legacy = true;
11839 		pe_opts.force_ioctl_attach = true;
11840 		break;
11841 	case PROBE_ATTACH_MODE_PERF:
11842 		if (legacy)
11843 			return libbpf_err_ptr(-ENOTSUP);
11844 		pe_opts.force_ioctl_attach = true;
11845 		break;
11846 	case PROBE_ATTACH_MODE_LINK:
11847 		if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
11848 			return libbpf_err_ptr(-ENOTSUP);
11849 		break;
11850 	case PROBE_ATTACH_MODE_DEFAULT:
11851 		break;
11852 	default:
11853 		return libbpf_err_ptr(-EINVAL);
11854 	}
11855 	if (!func_name && legacy)
11856 		return libbpf_err_ptr(-EOPNOTSUPP);
11857 
11858 	if (!legacy) {
11859 		pfd = perf_event_open_probe(false /* uprobe */, retprobe,
11860 					    func_name, offset,
11861 					    -1 /* pid */, 0 /* ref_ctr_off */);
11862 	} else {
11863 		char probe_name[MAX_EVENT_NAME_LEN];
11864 
11865 		gen_probe_legacy_event_name(probe_name, sizeof(probe_name),
11866 					    func_name, offset);
11867 
11868 		legacy_probe = strdup(probe_name);
11869 		if (!legacy_probe)
11870 			return libbpf_err_ptr(-ENOMEM);
11871 
11872 		pfd = perf_event_kprobe_open_legacy(legacy_probe, retprobe, func_name,
11873 						    offset, -1 /* pid */);
11874 	}
11875 	if (pfd < 0) {
11876 		err = pfd;
11877 		pr_warn("prog '%s': failed to create %s '%s%s0x%zx' perf event: %s\n",
11878 			prog->name, retprobe ? "kretprobe" : "kprobe",
11879 			func_name ?: "", func_name ? "+" : "",
11880 			offset, errstr(err));
11881 		goto err_out;
11882 	}
11883 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
11884 	err = libbpf_get_error(link);
11885 	if (err) {
11886 		close(pfd);
11887 		pr_warn("prog '%s': failed to attach to %s '%s%s0x%zx': %s\n",
11888 			prog->name, retprobe ? "kretprobe" : "kprobe",
11889 			func_name ?: "", func_name ? "+" : "",
11890 			offset, errstr(err));
11891 		goto err_clean_legacy;
11892 	}
11893 	if (legacy) {
11894 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
11895 
11896 		perf_link->legacy_probe_name = legacy_probe;
11897 		perf_link->legacy_is_kprobe = true;
11898 		perf_link->legacy_is_retprobe = retprobe;
11899 	}
11900 
11901 	return link;
11902 
11903 err_clean_legacy:
11904 	if (legacy)
11905 		remove_kprobe_event_legacy(legacy_probe, retprobe);
11906 err_out:
11907 	free(legacy_probe);
11908 	return libbpf_err_ptr(err);
11909 }
11910 
11911 struct bpf_link *bpf_program__attach_kprobe(const struct bpf_program *prog,
11912 					    bool retprobe,
11913 					    const char *func_name)
11914 {
11915 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts,
11916 		.retprobe = retprobe,
11917 	);
11918 
11919 	return bpf_program__attach_kprobe_opts(prog, func_name, &opts);
11920 }
11921 
11922 struct bpf_link *bpf_program__attach_ksyscall(const struct bpf_program *prog,
11923 					      const char *syscall_name,
11924 					      const struct bpf_ksyscall_opts *opts)
11925 {
11926 	LIBBPF_OPTS(bpf_kprobe_opts, kprobe_opts);
11927 	char func_name[128];
11928 
11929 	if (!OPTS_VALID(opts, bpf_ksyscall_opts))
11930 		return libbpf_err_ptr(-EINVAL);
11931 
11932 	if (kernel_supports(prog->obj, FEAT_SYSCALL_WRAPPER)) {
11933 		/* arch_specific_syscall_pfx() should never return NULL here
11934 		 * because it is guarded by kernel_supports(). However, since
11935 		 * compiler does not know that we have an explicit conditional
11936 		 * as well.
11937 		 */
11938 		snprintf(func_name, sizeof(func_name), "__%s_sys_%s",
11939 			 arch_specific_syscall_pfx() ? : "", syscall_name);
11940 	} else {
11941 		snprintf(func_name, sizeof(func_name), "__se_sys_%s", syscall_name);
11942 	}
11943 
11944 	kprobe_opts.retprobe = OPTS_GET(opts, retprobe, false);
11945 	kprobe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11946 
11947 	return bpf_program__attach_kprobe_opts(prog, func_name, &kprobe_opts);
11948 }
11949 
11950 /* Adapted from perf/util/string.c */
11951 bool glob_match(const char *str, const char *pat)
11952 {
11953 	while (*str && *pat && *pat != '*') {
11954 		if (*pat == '?') {      /* Matches any single character */
11955 			str++;
11956 			pat++;
11957 			continue;
11958 		}
11959 		if (*str != *pat)
11960 			return false;
11961 		str++;
11962 		pat++;
11963 	}
11964 	/* Check wild card */
11965 	if (*pat == '*') {
11966 		while (*pat == '*')
11967 			pat++;
11968 		if (!*pat) /* Tail wild card matches all */
11969 			return true;
11970 		while (*str)
11971 			if (glob_match(str++, pat))
11972 				return true;
11973 	}
11974 	return !*str && !*pat;
11975 }
11976 
11977 struct kprobe_multi_resolve {
11978 	const char *pattern;
11979 	unsigned long *addrs;
11980 	size_t cap;
11981 	size_t cnt;
11982 };
11983 
11984 struct avail_kallsyms_data {
11985 	char **syms;
11986 	size_t cnt;
11987 	struct kprobe_multi_resolve *res;
11988 };
11989 
11990 static int avail_func_cmp(const void *a, const void *b)
11991 {
11992 	return strcmp(*(const char **)a, *(const char **)b);
11993 }
11994 
11995 static int avail_kallsyms_cb(unsigned long long sym_addr, char sym_type,
11996 			     const char *sym_name, void *ctx)
11997 {
11998 	struct avail_kallsyms_data *data = ctx;
11999 	struct kprobe_multi_resolve *res = data->res;
12000 	int err;
12001 
12002 	if (!glob_match(sym_name, res->pattern))
12003 		return 0;
12004 
12005 	if (!bsearch(&sym_name, data->syms, data->cnt, sizeof(*data->syms), avail_func_cmp)) {
12006 		/* Some versions of kernel strip out .llvm.<hash> suffix from
12007 		 * function names reported in available_filter_functions, but
12008 		 * don't do so for kallsyms. While this is clearly a kernel
12009 		 * bug (fixed by [0]) we try to accommodate that in libbpf to
12010 		 * make multi-kprobe usability a bit better: if no match is
12011 		 * found, we will strip .llvm. suffix and try one more time.
12012 		 *
12013 		 *   [0] fb6a421fb615 ("kallsyms: Match symbols exactly with CONFIG_LTO_CLANG")
12014 		 */
12015 		char sym_trim[256], *psym_trim = sym_trim;
12016 		const char *sym_sfx;
12017 
12018 		if (!(sym_sfx = strstr(sym_name, ".llvm.")))
12019 			return 0;
12020 
12021 		/* psym_trim vs sym_trim dance is done to avoid pointer vs array
12022 		 * coercion differences and get proper `const char **` pointer
12023 		 * which avail_func_cmp() expects
12024 		 */
12025 		snprintf(sym_trim, sizeof(sym_trim), "%.*s", (int)(sym_sfx - sym_name), sym_name);
12026 		if (!bsearch(&psym_trim, data->syms, data->cnt, sizeof(*data->syms), avail_func_cmp))
12027 			return 0;
12028 	}
12029 
12030 	err = libbpf_ensure_mem((void **)&res->addrs, &res->cap, sizeof(*res->addrs), res->cnt + 1);
12031 	if (err)
12032 		return err;
12033 
12034 	res->addrs[res->cnt++] = (unsigned long)sym_addr;
12035 	return 0;
12036 }
12037 
12038 static int libbpf_available_kallsyms_parse(struct kprobe_multi_resolve *res)
12039 {
12040 	const char *available_functions_file = tracefs_available_filter_functions();
12041 	struct avail_kallsyms_data data;
12042 	char sym_name[500];
12043 	FILE *f;
12044 	int err = 0, ret, i;
12045 	char **syms = NULL;
12046 	size_t cap = 0, cnt = 0;
12047 
12048 	f = fopen(available_functions_file, "re");
12049 	if (!f) {
12050 		err = -errno;
12051 		pr_warn("failed to open %s: %s\n", available_functions_file, errstr(err));
12052 		return err;
12053 	}
12054 
12055 	while (true) {
12056 		char *name;
12057 
12058 		ret = fscanf(f, "%499s%*[^\n]\n", sym_name);
12059 		if (ret == EOF && feof(f))
12060 			break;
12061 
12062 		if (ret != 1) {
12063 			pr_warn("failed to parse available_filter_functions entry: %d\n", ret);
12064 			err = -EINVAL;
12065 			goto cleanup;
12066 		}
12067 
12068 		if (!glob_match(sym_name, res->pattern))
12069 			continue;
12070 
12071 		err = libbpf_ensure_mem((void **)&syms, &cap, sizeof(*syms), cnt + 1);
12072 		if (err)
12073 			goto cleanup;
12074 
12075 		name = strdup(sym_name);
12076 		if (!name) {
12077 			err = -errno;
12078 			goto cleanup;
12079 		}
12080 
12081 		syms[cnt++] = name;
12082 	}
12083 
12084 	/* no entries found, bail out */
12085 	if (cnt == 0) {
12086 		err = -ENOENT;
12087 		goto cleanup;
12088 	}
12089 
12090 	/* sort available functions */
12091 	qsort(syms, cnt, sizeof(*syms), avail_func_cmp);
12092 
12093 	data.syms = syms;
12094 	data.res = res;
12095 	data.cnt = cnt;
12096 	libbpf_kallsyms_parse(avail_kallsyms_cb, &data);
12097 
12098 	if (res->cnt == 0)
12099 		err = -ENOENT;
12100 
12101 cleanup:
12102 	for (i = 0; i < cnt; i++)
12103 		free((char *)syms[i]);
12104 	free(syms);
12105 
12106 	fclose(f);
12107 	return err;
12108 }
12109 
12110 static bool has_available_filter_functions_addrs(void)
12111 {
12112 	return access(tracefs_available_filter_functions_addrs(), R_OK) != -1;
12113 }
12114 
12115 static int libbpf_available_kprobes_parse(struct kprobe_multi_resolve *res)
12116 {
12117 	const char *available_path = tracefs_available_filter_functions_addrs();
12118 	char sym_name[500];
12119 	FILE *f;
12120 	int ret, err = 0;
12121 	unsigned long long sym_addr;
12122 
12123 	f = fopen(available_path, "re");
12124 	if (!f) {
12125 		err = -errno;
12126 		pr_warn("failed to open %s: %s\n", available_path, errstr(err));
12127 		return err;
12128 	}
12129 
12130 	while (true) {
12131 		ret = fscanf(f, "%llx %499s%*[^\n]\n", &sym_addr, sym_name);
12132 		if (ret == EOF && feof(f))
12133 			break;
12134 
12135 		if (ret != 2) {
12136 			pr_warn("failed to parse available_filter_functions_addrs entry: %d\n",
12137 				ret);
12138 			err = -EINVAL;
12139 			goto cleanup;
12140 		}
12141 
12142 		if (!glob_match(sym_name, res->pattern))
12143 			continue;
12144 
12145 		err = libbpf_ensure_mem((void **)&res->addrs, &res->cap,
12146 					sizeof(*res->addrs), res->cnt + 1);
12147 		if (err)
12148 			goto cleanup;
12149 
12150 		res->addrs[res->cnt++] = (unsigned long)sym_addr;
12151 	}
12152 
12153 	if (res->cnt == 0)
12154 		err = -ENOENT;
12155 
12156 cleanup:
12157 	fclose(f);
12158 	return err;
12159 }
12160 
12161 struct bpf_link *
12162 bpf_program__attach_kprobe_multi_opts(const struct bpf_program *prog,
12163 				      const char *pattern,
12164 				      const struct bpf_kprobe_multi_opts *opts)
12165 {
12166 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
12167 	struct kprobe_multi_resolve res = {
12168 		.pattern = pattern,
12169 	};
12170 	enum bpf_attach_type attach_type;
12171 	struct bpf_link *link = NULL;
12172 	const unsigned long *addrs;
12173 	int err, link_fd, prog_fd;
12174 	bool retprobe, session, unique_match;
12175 	const __u64 *cookies;
12176 	const char **syms;
12177 	size_t cnt;
12178 
12179 	if (!OPTS_VALID(opts, bpf_kprobe_multi_opts))
12180 		return libbpf_err_ptr(-EINVAL);
12181 
12182 	prog_fd = bpf_program__fd(prog);
12183 	if (prog_fd < 0) {
12184 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
12185 			prog->name);
12186 		return libbpf_err_ptr(-EINVAL);
12187 	}
12188 
12189 	syms    = OPTS_GET(opts, syms, false);
12190 	addrs   = OPTS_GET(opts, addrs, false);
12191 	cnt     = OPTS_GET(opts, cnt, false);
12192 	cookies = OPTS_GET(opts, cookies, false);
12193 	unique_match = OPTS_GET(opts, unique_match, false);
12194 
12195 	if (!pattern && !addrs && !syms)
12196 		return libbpf_err_ptr(-EINVAL);
12197 	if (pattern && (addrs || syms || cookies || cnt))
12198 		return libbpf_err_ptr(-EINVAL);
12199 	if (!pattern && !cnt)
12200 		return libbpf_err_ptr(-EINVAL);
12201 	if (!pattern && unique_match)
12202 		return libbpf_err_ptr(-EINVAL);
12203 	if (addrs && syms)
12204 		return libbpf_err_ptr(-EINVAL);
12205 
12206 	/*
12207 	 * Exact function name (no wildcards) without unique_match:
12208 	 * bypass kallsyms parsing and pass the symbol directly to the
12209 	 * kernel via syms[] array.  When unique_match is set, fall
12210 	 * through to the slow path which detects duplicate symbols.
12211 	 */
12212 	if (pattern && !strpbrk(pattern, "*?") && !unique_match) {
12213 		syms = &pattern;
12214 		cnt = 1;
12215 	} else if (pattern) {
12216 		if (has_available_filter_functions_addrs())
12217 			err = libbpf_available_kprobes_parse(&res);
12218 		else
12219 			err = libbpf_available_kallsyms_parse(&res);
12220 		if (err)
12221 			goto error;
12222 
12223 		if (unique_match && res.cnt != 1) {
12224 			pr_warn("prog '%s': failed to find a unique match for '%s' (%zu matches)\n",
12225 				prog->name, pattern, res.cnt);
12226 			err = -EINVAL;
12227 			goto error;
12228 		}
12229 
12230 		addrs = res.addrs;
12231 		cnt = res.cnt;
12232 	}
12233 
12234 	retprobe = OPTS_GET(opts, retprobe, false);
12235 	session  = OPTS_GET(opts, session, false);
12236 
12237 	if (retprobe && session)
12238 		return libbpf_err_ptr(-EINVAL);
12239 
12240 	attach_type = session ? BPF_TRACE_KPROBE_SESSION : BPF_TRACE_KPROBE_MULTI;
12241 
12242 	lopts.kprobe_multi.syms = syms;
12243 	lopts.kprobe_multi.addrs = addrs;
12244 	lopts.kprobe_multi.cookies = cookies;
12245 	lopts.kprobe_multi.cnt = cnt;
12246 	lopts.kprobe_multi.flags = retprobe ? BPF_F_KPROBE_MULTI_RETURN : 0;
12247 
12248 	link = calloc(1, sizeof(*link));
12249 	if (!link) {
12250 		err = -ENOMEM;
12251 		goto error;
12252 	}
12253 	link->detach = &bpf_link__detach_fd;
12254 
12255 	link_fd = bpf_link_create(prog_fd, 0, attach_type, &lopts);
12256 	if (link_fd < 0) {
12257 		err = -errno;
12258 		/*
12259 		 * Normalize error code: when exact name bypasses kallsyms
12260 		 * parsing, kernel returns ESRCH from ftrace_lookup_symbols().
12261 		 * Convert to ENOENT for API consistency with the pattern
12262 		 * matching path which returns ENOENT from userspace.
12263 		 */
12264 		if (err == -ESRCH)
12265 			err = -ENOENT;
12266 		pr_warn("prog '%s': failed to attach: %s\n",
12267 			prog->name, errstr(err));
12268 		goto error;
12269 	}
12270 	link->fd = link_fd;
12271 	free(res.addrs);
12272 	return link;
12273 
12274 error:
12275 	free(link);
12276 	free(res.addrs);
12277 	return libbpf_err_ptr(err);
12278 }
12279 
12280 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12281 {
12282 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts);
12283 	unsigned long offset = 0;
12284 	const char *func_name;
12285 	char *func;
12286 	int n;
12287 
12288 	*link = NULL;
12289 
12290 	/* no auto-attach for SEC("kprobe") and SEC("kretprobe") */
12291 	if (strcmp(prog->sec_name, "kprobe") == 0 || strcmp(prog->sec_name, "kretprobe") == 0)
12292 		return 0;
12293 
12294 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe/");
12295 	if (opts.retprobe)
12296 		func_name = prog->sec_name + sizeof("kretprobe/") - 1;
12297 	else
12298 		func_name = prog->sec_name + sizeof("kprobe/") - 1;
12299 
12300 	n = sscanf(func_name, "%m[a-zA-Z0-9_.]+%li", &func, &offset);
12301 	if (n < 1) {
12302 		pr_warn("kprobe name is invalid: %s\n", func_name);
12303 		return -EINVAL;
12304 	}
12305 	if (opts.retprobe && offset != 0) {
12306 		free(func);
12307 		pr_warn("kretprobes do not support offset specification\n");
12308 		return -EINVAL;
12309 	}
12310 
12311 	opts.offset = offset;
12312 	*link = bpf_program__attach_kprobe_opts(prog, func, &opts);
12313 	free(func);
12314 	return libbpf_get_error(*link);
12315 }
12316 
12317 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12318 {
12319 	LIBBPF_OPTS(bpf_ksyscall_opts, opts);
12320 	const char *syscall_name;
12321 
12322 	*link = NULL;
12323 
12324 	/* no auto-attach for SEC("ksyscall") and SEC("kretsyscall") */
12325 	if (strcmp(prog->sec_name, "ksyscall") == 0 || strcmp(prog->sec_name, "kretsyscall") == 0)
12326 		return 0;
12327 
12328 	opts.retprobe = str_has_pfx(prog->sec_name, "kretsyscall/");
12329 	if (opts.retprobe)
12330 		syscall_name = prog->sec_name + sizeof("kretsyscall/") - 1;
12331 	else
12332 		syscall_name = prog->sec_name + sizeof("ksyscall/") - 1;
12333 
12334 	*link = bpf_program__attach_ksyscall(prog, syscall_name, &opts);
12335 	return *link ? 0 : -errno;
12336 }
12337 
12338 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12339 {
12340 	LIBBPF_OPTS(bpf_kprobe_multi_opts, opts);
12341 	const char *spec;
12342 	char *pattern;
12343 	int n;
12344 
12345 	*link = NULL;
12346 
12347 	/* no auto-attach for SEC("kprobe.multi") and SEC("kretprobe.multi") */
12348 	if (strcmp(prog->sec_name, "kprobe.multi") == 0 ||
12349 	    strcmp(prog->sec_name, "kretprobe.multi") == 0)
12350 		return 0;
12351 
12352 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe.multi/");
12353 	if (opts.retprobe)
12354 		spec = prog->sec_name + sizeof("kretprobe.multi/") - 1;
12355 	else
12356 		spec = prog->sec_name + sizeof("kprobe.multi/") - 1;
12357 
12358 	n = sscanf(spec, "%m[a-zA-Z0-9_.*?]", &pattern);
12359 	if (n < 1) {
12360 		pr_warn("kprobe multi pattern is invalid: %s\n", spec);
12361 		return -EINVAL;
12362 	}
12363 
12364 	*link = bpf_program__attach_kprobe_multi_opts(prog, pattern, &opts);
12365 	free(pattern);
12366 	return libbpf_get_error(*link);
12367 }
12368 
12369 static int attach_kprobe_session(const struct bpf_program *prog, long cookie,
12370 				 struct bpf_link **link)
12371 {
12372 	LIBBPF_OPTS(bpf_kprobe_multi_opts, opts, .session = true);
12373 	const char *spec;
12374 	char *pattern;
12375 	int n;
12376 
12377 	*link = NULL;
12378 
12379 	/* no auto-attach for SEC("kprobe.session") */
12380 	if (strcmp(prog->sec_name, "kprobe.session") == 0)
12381 		return 0;
12382 
12383 	spec = prog->sec_name + sizeof("kprobe.session/") - 1;
12384 	n = sscanf(spec, "%m[a-zA-Z0-9_.*?]", &pattern);
12385 	if (n < 1) {
12386 		pr_warn("kprobe session pattern is invalid: %s\n", spec);
12387 		return -EINVAL;
12388 	}
12389 
12390 	*link = bpf_program__attach_kprobe_multi_opts(prog, pattern, &opts);
12391 	free(pattern);
12392 	return *link ? 0 : -errno;
12393 }
12394 
12395 static int attach_uprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12396 {
12397 	char *probe_type = NULL, *binary_path = NULL, *func_name = NULL;
12398 	LIBBPF_OPTS(bpf_uprobe_multi_opts, opts);
12399 	int n, ret = -EINVAL;
12400 
12401 	*link = NULL;
12402 
12403 	n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[^\n]",
12404 		   &probe_type, &binary_path, &func_name);
12405 	switch (n) {
12406 	case 1:
12407 		/* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
12408 		ret = 0;
12409 		break;
12410 	case 3:
12411 		opts.session = str_has_pfx(probe_type, "uprobe.session");
12412 		opts.retprobe = str_has_pfx(probe_type, "uretprobe.multi");
12413 
12414 		*link = bpf_program__attach_uprobe_multi(prog, -1, binary_path, func_name, &opts);
12415 		ret = libbpf_get_error(*link);
12416 		break;
12417 	default:
12418 		pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
12419 			prog->sec_name);
12420 		break;
12421 	}
12422 	free(probe_type);
12423 	free(binary_path);
12424 	free(func_name);
12425 	return ret;
12426 }
12427 
12428 static inline int add_uprobe_event_legacy(const char *probe_name, bool retprobe,
12429 					  const char *binary_path, size_t offset)
12430 {
12431 	return append_to_file(tracefs_uprobe_events(), "%c:%s/%s %s:0x%zx",
12432 			      retprobe ? 'r' : 'p',
12433 			      retprobe ? "uretprobes" : "uprobes",
12434 			      probe_name, binary_path, offset);
12435 }
12436 
12437 static inline int remove_uprobe_event_legacy(const char *probe_name, bool retprobe)
12438 {
12439 	return append_to_file(tracefs_uprobe_events(), "-:%s/%s",
12440 			      retprobe ? "uretprobes" : "uprobes", probe_name);
12441 }
12442 
12443 static int determine_uprobe_perf_type_legacy(const char *probe_name, bool retprobe)
12444 {
12445 	char file[512];
12446 
12447 	snprintf(file, sizeof(file), "%s/events/%s/%s/id",
12448 		 tracefs_path(), retprobe ? "uretprobes" : "uprobes", probe_name);
12449 
12450 	return parse_uint_from_file(file, "%d\n");
12451 }
12452 
12453 static int perf_event_uprobe_open_legacy(const char *probe_name, bool retprobe,
12454 					 const char *binary_path, size_t offset, int pid)
12455 {
12456 	const size_t attr_sz = sizeof(struct perf_event_attr);
12457 	struct perf_event_attr attr;
12458 	int type, pfd, err;
12459 
12460 	err = add_uprobe_event_legacy(probe_name, retprobe, binary_path, offset);
12461 	if (err < 0) {
12462 		pr_warn("failed to add legacy uprobe event for %s:0x%zx: %s\n",
12463 			binary_path, (size_t)offset, errstr(err));
12464 		return err;
12465 	}
12466 	type = determine_uprobe_perf_type_legacy(probe_name, retprobe);
12467 	if (type < 0) {
12468 		err = type;
12469 		pr_warn("failed to determine legacy uprobe event id for %s:0x%zx: %s\n",
12470 			binary_path, offset, errstr(err));
12471 		goto err_clean_legacy;
12472 	}
12473 
12474 	memset(&attr, 0, attr_sz);
12475 	attr.size = attr_sz;
12476 	attr.config = type;
12477 	attr.type = PERF_TYPE_TRACEPOINT;
12478 
12479 	pfd = syscall(__NR_perf_event_open, &attr,
12480 		      pid < 0 ? -1 : pid, /* pid */
12481 		      pid == -1 ? 0 : -1, /* cpu */
12482 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
12483 	if (pfd < 0) {
12484 		err = -errno;
12485 		pr_warn("legacy uprobe perf_event_open() failed: %s\n", errstr(err));
12486 		goto err_clean_legacy;
12487 	}
12488 	return pfd;
12489 
12490 err_clean_legacy:
12491 	/* Clear the newly added legacy uprobe_event */
12492 	remove_uprobe_event_legacy(probe_name, retprobe);
12493 	return err;
12494 }
12495 
12496 /* Find offset of function name in archive specified by path. Currently
12497  * supported are .zip files that do not compress their contents, as used on
12498  * Android in the form of APKs, for example. "file_name" is the name of the ELF
12499  * file inside the archive. "func_name" matches symbol name or name@@LIB for
12500  * library functions.
12501  *
12502  * An overview of the APK format specifically provided here:
12503  * https://en.wikipedia.org/w/index.php?title=Apk_(file_format)&oldid=1139099120#Package_contents
12504  */
12505 static long elf_find_func_offset_from_archive(const char *archive_path, const char *file_name,
12506 					      const char *func_name)
12507 {
12508 	struct zip_archive *archive;
12509 	struct zip_entry entry;
12510 	long ret;
12511 	Elf *elf;
12512 
12513 	archive = zip_archive_open(archive_path);
12514 	if (IS_ERR(archive)) {
12515 		ret = PTR_ERR(archive);
12516 		pr_warn("zip: failed to open %s: %ld\n", archive_path, ret);
12517 		return ret;
12518 	}
12519 
12520 	ret = zip_archive_find_entry(archive, file_name, &entry);
12521 	if (ret) {
12522 		pr_warn("zip: could not find archive member %s in %s: %ld\n", file_name,
12523 			archive_path, ret);
12524 		goto out;
12525 	}
12526 	pr_debug("zip: found entry for %s in %s at 0x%lx\n", file_name, archive_path,
12527 		 (unsigned long)entry.data_offset);
12528 
12529 	if (entry.compression) {
12530 		pr_warn("zip: entry %s of %s is compressed and cannot be handled\n", file_name,
12531 			archive_path);
12532 		ret = -LIBBPF_ERRNO__FORMAT;
12533 		goto out;
12534 	}
12535 
12536 	elf = elf_memory((void *)entry.data, entry.data_length);
12537 	if (!elf) {
12538 		pr_warn("elf: could not read elf file %s from %s: %s\n", file_name, archive_path,
12539 			elf_errmsg(-1));
12540 		ret = -LIBBPF_ERRNO__LIBELF;
12541 		goto out;
12542 	}
12543 
12544 	ret = elf_find_func_offset(elf, file_name, func_name);
12545 	if (ret > 0) {
12546 		pr_debug("elf: symbol address match for %s of %s in %s: 0x%x + 0x%lx = 0x%lx\n",
12547 			 func_name, file_name, archive_path, entry.data_offset, ret,
12548 			 ret + entry.data_offset);
12549 		ret += entry.data_offset;
12550 	}
12551 	elf_end(elf);
12552 
12553 out:
12554 	zip_archive_close(archive);
12555 	return ret;
12556 }
12557 
12558 static const char *arch_specific_lib_paths(void)
12559 {
12560 	/*
12561 	 * Based on https://packages.debian.org/sid/libc6.
12562 	 *
12563 	 * Assume that the traced program is built for the same architecture
12564 	 * as libbpf, which should cover the vast majority of cases.
12565 	 */
12566 #if defined(__x86_64__)
12567 	return "/lib/x86_64-linux-gnu";
12568 #elif defined(__i386__)
12569 	return "/lib/i386-linux-gnu";
12570 #elif defined(__s390x__)
12571 	return "/lib/s390x-linux-gnu";
12572 #elif defined(__arm__) && defined(__SOFTFP__)
12573 	return "/lib/arm-linux-gnueabi";
12574 #elif defined(__arm__) && !defined(__SOFTFP__)
12575 	return "/lib/arm-linux-gnueabihf";
12576 #elif defined(__aarch64__)
12577 	return "/lib/aarch64-linux-gnu";
12578 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 64
12579 	return "/lib/mips64el-linux-gnuabi64";
12580 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 32
12581 	return "/lib/mipsel-linux-gnu";
12582 #elif defined(__powerpc64__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
12583 	return "/lib/powerpc64le-linux-gnu";
12584 #elif defined(__sparc__) && defined(__arch64__)
12585 	return "/lib/sparc64-linux-gnu";
12586 #elif defined(__riscv) && __riscv_xlen == 64
12587 	return "/lib/riscv64-linux-gnu";
12588 #else
12589 	return NULL;
12590 #endif
12591 }
12592 
12593 /* Get full path to program/shared library. */
12594 static int resolve_full_path(const char *file, char *result, size_t result_sz)
12595 {
12596 	const char *search_paths[3] = {};
12597 	int i, perm;
12598 
12599 	if (str_has_sfx(file, ".so") || strstr(file, ".so.")) {
12600 		search_paths[0] = getenv("LD_LIBRARY_PATH");
12601 		search_paths[1] = "/usr/lib64:/usr/lib";
12602 		search_paths[2] = arch_specific_lib_paths();
12603 		perm = R_OK;
12604 	} else {
12605 		search_paths[0] = getenv("PATH");
12606 		search_paths[1] = "/usr/bin:/usr/sbin";
12607 		perm = R_OK | X_OK;
12608 	}
12609 
12610 	for (i = 0; i < ARRAY_SIZE(search_paths); i++) {
12611 		const char *s;
12612 
12613 		if (!search_paths[i])
12614 			continue;
12615 		for (s = search_paths[i]; s != NULL; s = strchr(s, ':')) {
12616 			const char *next_path;
12617 			int seg_len;
12618 
12619 			if (s[0] == ':')
12620 				s++;
12621 			next_path = strchr(s, ':');
12622 			seg_len = next_path ? next_path - s : strlen(s);
12623 			if (!seg_len)
12624 				continue;
12625 			snprintf(result, result_sz, "%.*s/%s", seg_len, s, file);
12626 			/* ensure it has required permissions */
12627 			if (faccessat(AT_FDCWD, result, perm, AT_EACCESS) < 0)
12628 				continue;
12629 			pr_debug("resolved '%s' to '%s'\n", file, result);
12630 			return 0;
12631 		}
12632 	}
12633 	return -ENOENT;
12634 }
12635 
12636 struct bpf_link *
12637 bpf_program__attach_uprobe_multi(const struct bpf_program *prog,
12638 				 pid_t pid,
12639 				 const char *path,
12640 				 const char *func_pattern,
12641 				 const struct bpf_uprobe_multi_opts *opts)
12642 {
12643 	const unsigned long *ref_ctr_offsets = NULL, *offsets = NULL;
12644 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
12645 	unsigned long *resolved_offsets = NULL;
12646 	enum bpf_attach_type attach_type;
12647 	int err = 0, link_fd, prog_fd;
12648 	struct bpf_link *link = NULL;
12649 	char full_path[PATH_MAX];
12650 	bool retprobe, session;
12651 	const __u64 *cookies;
12652 	const char **syms;
12653 	size_t cnt;
12654 
12655 	if (!OPTS_VALID(opts, bpf_uprobe_multi_opts))
12656 		return libbpf_err_ptr(-EINVAL);
12657 
12658 	prog_fd = bpf_program__fd(prog);
12659 	if (prog_fd < 0) {
12660 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
12661 			prog->name);
12662 		return libbpf_err_ptr(-EINVAL);
12663 	}
12664 
12665 	syms = OPTS_GET(opts, syms, NULL);
12666 	offsets = OPTS_GET(opts, offsets, NULL);
12667 	ref_ctr_offsets = OPTS_GET(opts, ref_ctr_offsets, NULL);
12668 	cookies = OPTS_GET(opts, cookies, NULL);
12669 	cnt = OPTS_GET(opts, cnt, 0);
12670 	retprobe = OPTS_GET(opts, retprobe, false);
12671 	session  = OPTS_GET(opts, session, false);
12672 
12673 	/*
12674 	 * User can specify 2 mutually exclusive set of inputs:
12675 	 *
12676 	 * 1) use only path/func_pattern/pid arguments
12677 	 *
12678 	 * 2) use path/pid with allowed combinations of:
12679 	 *    syms/offsets/ref_ctr_offsets/cookies/cnt
12680 	 *
12681 	 *    - syms and offsets are mutually exclusive
12682 	 *    - ref_ctr_offsets and cookies are optional
12683 	 *
12684 	 * Any other usage results in error.
12685 	 */
12686 
12687 	if (!path)
12688 		return libbpf_err_ptr(-EINVAL);
12689 	if (!func_pattern && cnt == 0)
12690 		return libbpf_err_ptr(-EINVAL);
12691 
12692 	if (func_pattern) {
12693 		if (syms || offsets || ref_ctr_offsets || cookies || cnt)
12694 			return libbpf_err_ptr(-EINVAL);
12695 	} else {
12696 		if (!!syms == !!offsets)
12697 			return libbpf_err_ptr(-EINVAL);
12698 	}
12699 
12700 	if (retprobe && session)
12701 		return libbpf_err_ptr(-EINVAL);
12702 
12703 	if (func_pattern) {
12704 		if (!strchr(path, '/')) {
12705 			err = resolve_full_path(path, full_path, sizeof(full_path));
12706 			if (err) {
12707 				pr_warn("prog '%s': failed to resolve full path for '%s': %s\n",
12708 					prog->name, path, errstr(err));
12709 				return libbpf_err_ptr(err);
12710 			}
12711 			path = full_path;
12712 		}
12713 
12714 		err = elf_resolve_pattern_offsets(path, func_pattern,
12715 						  &resolved_offsets, &cnt);
12716 		if (err < 0)
12717 			return libbpf_err_ptr(err);
12718 		offsets = resolved_offsets;
12719 	} else if (syms) {
12720 		err = elf_resolve_syms_offsets(path, cnt, syms, &resolved_offsets, STT_FUNC);
12721 		if (err < 0)
12722 			return libbpf_err_ptr(err);
12723 		offsets = resolved_offsets;
12724 	}
12725 
12726 	attach_type = session ? BPF_TRACE_UPROBE_SESSION : BPF_TRACE_UPROBE_MULTI;
12727 
12728 	lopts.uprobe_multi.path = path;
12729 	lopts.uprobe_multi.offsets = offsets;
12730 	lopts.uprobe_multi.ref_ctr_offsets = ref_ctr_offsets;
12731 	lopts.uprobe_multi.cookies = cookies;
12732 	lopts.uprobe_multi.cnt = cnt;
12733 	lopts.uprobe_multi.flags = retprobe ? BPF_F_UPROBE_MULTI_RETURN : 0;
12734 
12735 	if (pid == 0)
12736 		pid = getpid();
12737 	if (pid > 0)
12738 		lopts.uprobe_multi.pid = pid;
12739 
12740 	link = calloc(1, sizeof(*link));
12741 	if (!link) {
12742 		err = -ENOMEM;
12743 		goto error;
12744 	}
12745 	link->detach = &bpf_link__detach_fd;
12746 
12747 	link_fd = bpf_link_create(prog_fd, 0, attach_type, &lopts);
12748 	if (link_fd < 0) {
12749 		err = -errno;
12750 		pr_warn("prog '%s': failed to attach multi-uprobe: %s\n",
12751 			prog->name, errstr(err));
12752 		goto error;
12753 	}
12754 	link->fd = link_fd;
12755 	free(resolved_offsets);
12756 	return link;
12757 
12758 error:
12759 	free(resolved_offsets);
12760 	free(link);
12761 	return libbpf_err_ptr(err);
12762 }
12763 
12764 LIBBPF_API struct bpf_link *
12765 bpf_program__attach_uprobe_opts(const struct bpf_program *prog, pid_t pid,
12766 				const char *binary_path, size_t func_offset,
12767 				const struct bpf_uprobe_opts *opts)
12768 {
12769 	const char *archive_path = NULL, *archive_sep = NULL;
12770 	char *legacy_probe = NULL;
12771 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
12772 	enum probe_attach_mode attach_mode;
12773 	char full_path[PATH_MAX];
12774 	struct bpf_link *link;
12775 	size_t ref_ctr_off;
12776 	int pfd, err;
12777 	bool retprobe, legacy;
12778 	const char *func_name;
12779 
12780 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
12781 		return libbpf_err_ptr(-EINVAL);
12782 
12783 	attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
12784 	retprobe = OPTS_GET(opts, retprobe, false);
12785 	ref_ctr_off = OPTS_GET(opts, ref_ctr_offset, 0);
12786 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
12787 
12788 	if (!binary_path)
12789 		return libbpf_err_ptr(-EINVAL);
12790 
12791 	/* Check if "binary_path" refers to an archive. */
12792 	archive_sep = strstr(binary_path, "!/");
12793 	if (archive_sep) {
12794 		full_path[0] = '\0';
12795 		libbpf_strlcpy(full_path, binary_path,
12796 			       min(sizeof(full_path), (size_t)(archive_sep - binary_path + 1)));
12797 		archive_path = full_path;
12798 		binary_path = archive_sep + 2;
12799 	} else if (!strchr(binary_path, '/')) {
12800 		err = resolve_full_path(binary_path, full_path, sizeof(full_path));
12801 		if (err) {
12802 			pr_warn("prog '%s': failed to resolve full path for '%s': %s\n",
12803 				prog->name, binary_path, errstr(err));
12804 			return libbpf_err_ptr(err);
12805 		}
12806 		binary_path = full_path;
12807 	}
12808 	func_name = OPTS_GET(opts, func_name, NULL);
12809 	if (func_name) {
12810 		long sym_off;
12811 
12812 		if (archive_path) {
12813 			sym_off = elf_find_func_offset_from_archive(archive_path, binary_path,
12814 								    func_name);
12815 			binary_path = archive_path;
12816 		} else {
12817 			sym_off = elf_find_func_offset_from_file(binary_path, func_name);
12818 		}
12819 		if (sym_off < 0)
12820 			return libbpf_err_ptr(sym_off);
12821 		func_offset += sym_off;
12822 	}
12823 
12824 	legacy = determine_uprobe_perf_type() < 0;
12825 	switch (attach_mode) {
12826 	case PROBE_ATTACH_MODE_LEGACY:
12827 		legacy = true;
12828 		pe_opts.force_ioctl_attach = true;
12829 		break;
12830 	case PROBE_ATTACH_MODE_PERF:
12831 		if (legacy)
12832 			return libbpf_err_ptr(-ENOTSUP);
12833 		pe_opts.force_ioctl_attach = true;
12834 		break;
12835 	case PROBE_ATTACH_MODE_LINK:
12836 		if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
12837 			return libbpf_err_ptr(-ENOTSUP);
12838 		break;
12839 	case PROBE_ATTACH_MODE_DEFAULT:
12840 		break;
12841 	default:
12842 		return libbpf_err_ptr(-EINVAL);
12843 	}
12844 
12845 	if (!legacy) {
12846 		pfd = perf_event_open_probe(true /* uprobe */, retprobe, binary_path,
12847 					    func_offset, pid, ref_ctr_off);
12848 	} else {
12849 		char probe_name[MAX_EVENT_NAME_LEN];
12850 
12851 		if (ref_ctr_off)
12852 			return libbpf_err_ptr(-EINVAL);
12853 
12854 		gen_probe_legacy_event_name(probe_name, sizeof(probe_name),
12855 					    strrchr(binary_path, '/') ? : binary_path,
12856 					    func_offset);
12857 
12858 		legacy_probe = strdup(probe_name);
12859 		if (!legacy_probe)
12860 			return libbpf_err_ptr(-ENOMEM);
12861 
12862 		pfd = perf_event_uprobe_open_legacy(legacy_probe, retprobe,
12863 						    binary_path, func_offset, pid);
12864 	}
12865 	if (pfd < 0) {
12866 		err = pfd;
12867 		pr_warn("prog '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
12868 			prog->name, retprobe ? "uretprobe" : "uprobe",
12869 			binary_path, func_offset,
12870 			errstr(err));
12871 		goto err_out;
12872 	}
12873 
12874 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
12875 	err = libbpf_get_error(link);
12876 	if (err) {
12877 		close(pfd);
12878 		pr_warn("prog '%s': failed to attach to %s '%s:0x%zx': %s\n",
12879 			prog->name, retprobe ? "uretprobe" : "uprobe",
12880 			binary_path, func_offset,
12881 			errstr(err));
12882 		goto err_clean_legacy;
12883 	}
12884 	if (legacy) {
12885 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
12886 
12887 		perf_link->legacy_probe_name = legacy_probe;
12888 		perf_link->legacy_is_kprobe = false;
12889 		perf_link->legacy_is_retprobe = retprobe;
12890 	}
12891 	return link;
12892 
12893 err_clean_legacy:
12894 	if (legacy)
12895 		remove_uprobe_event_legacy(legacy_probe, retprobe);
12896 err_out:
12897 	free(legacy_probe);
12898 	return libbpf_err_ptr(err);
12899 }
12900 
12901 /* Format of u[ret]probe section definition supporting auto-attach:
12902  * u[ret]probe/binary:function[+offset]
12903  *
12904  * binary can be an absolute/relative path or a filename; the latter is resolved to a
12905  * full binary path via bpf_program__attach_uprobe_opts.
12906  *
12907  * Specifying uprobe+ ensures we carry out strict matching; either "uprobe" must be
12908  * specified (and auto-attach is not possible) or the above format is specified for
12909  * auto-attach.
12910  */
12911 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12912 {
12913 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts);
12914 	char *probe_type = NULL, *binary_path = NULL, *func_name = NULL, *func_off;
12915 	int n, c, ret = -EINVAL;
12916 	long offset = 0;
12917 
12918 	*link = NULL;
12919 
12920 	n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[^\n]",
12921 		   &probe_type, &binary_path, &func_name);
12922 	switch (n) {
12923 	case 1:
12924 		/* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
12925 		ret = 0;
12926 		break;
12927 	case 2:
12928 		pr_warn("prog '%s': section '%s' missing ':function[+offset]' specification\n",
12929 			prog->name, prog->sec_name);
12930 		break;
12931 	case 3:
12932 		/* check if user specifies `+offset`, if yes, this should be
12933 		 * the last part of the string, make sure sscanf read to EOL
12934 		 */
12935 		func_off = strrchr(func_name, '+');
12936 		if (func_off) {
12937 			n = sscanf(func_off, "+%li%n", &offset, &c);
12938 			if (n == 1 && *(func_off + c) == '\0')
12939 				func_off[0] = '\0';
12940 			else
12941 				offset = 0;
12942 		}
12943 		opts.retprobe = strcmp(probe_type, "uretprobe") == 0 ||
12944 				strcmp(probe_type, "uretprobe.s") == 0;
12945 		if (opts.retprobe && offset != 0) {
12946 			pr_warn("prog '%s': uretprobes do not support offset specification\n",
12947 				prog->name);
12948 			break;
12949 		}
12950 		opts.func_name = func_name;
12951 		*link = bpf_program__attach_uprobe_opts(prog, -1, binary_path, offset, &opts);
12952 		ret = libbpf_get_error(*link);
12953 		break;
12954 	default:
12955 		pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
12956 			prog->sec_name);
12957 		break;
12958 	}
12959 	free(probe_type);
12960 	free(binary_path);
12961 	free(func_name);
12962 
12963 	return ret;
12964 }
12965 
12966 struct bpf_link *bpf_program__attach_uprobe(const struct bpf_program *prog,
12967 					    bool retprobe, pid_t pid,
12968 					    const char *binary_path,
12969 					    size_t func_offset)
12970 {
12971 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts, .retprobe = retprobe);
12972 
12973 	return bpf_program__attach_uprobe_opts(prog, pid, binary_path, func_offset, &opts);
12974 }
12975 
12976 struct bpf_link *bpf_program__attach_usdt(const struct bpf_program *prog,
12977 					  pid_t pid, const char *binary_path,
12978 					  const char *usdt_provider, const char *usdt_name,
12979 					  const struct bpf_usdt_opts *opts)
12980 {
12981 	char resolved_path[512];
12982 	struct bpf_object *obj = prog->obj;
12983 	struct bpf_link *link;
12984 	__u64 usdt_cookie;
12985 	int err;
12986 
12987 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
12988 		return libbpf_err_ptr(-EINVAL);
12989 
12990 	if (bpf_program__fd(prog) < 0) {
12991 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
12992 			prog->name);
12993 		return libbpf_err_ptr(-EINVAL);
12994 	}
12995 
12996 	if (!binary_path)
12997 		return libbpf_err_ptr(-EINVAL);
12998 
12999 	if (!strchr(binary_path, '/')) {
13000 		err = resolve_full_path(binary_path, resolved_path, sizeof(resolved_path));
13001 		if (err) {
13002 			pr_warn("prog '%s': failed to resolve full path for '%s': %s\n",
13003 				prog->name, binary_path, errstr(err));
13004 			return libbpf_err_ptr(err);
13005 		}
13006 		binary_path = resolved_path;
13007 	}
13008 
13009 	/* USDT manager is instantiated lazily on first USDT attach. It will
13010 	 * be destroyed together with BPF object in bpf_object__close().
13011 	 */
13012 	if (IS_ERR(obj->usdt_man))
13013 		return libbpf_ptr(obj->usdt_man);
13014 	if (!obj->usdt_man) {
13015 		obj->usdt_man = usdt_manager_new(obj);
13016 		if (IS_ERR(obj->usdt_man))
13017 			return libbpf_ptr(obj->usdt_man);
13018 	}
13019 
13020 	usdt_cookie = OPTS_GET(opts, usdt_cookie, 0);
13021 	link = usdt_manager_attach_usdt(obj->usdt_man, prog, pid, binary_path,
13022 					usdt_provider, usdt_name, usdt_cookie);
13023 	err = libbpf_get_error(link);
13024 	if (err)
13025 		return libbpf_err_ptr(err);
13026 	return link;
13027 }
13028 
13029 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link)
13030 {
13031 	char *path = NULL, *provider = NULL, *name = NULL;
13032 	const char *sec_name;
13033 	int n, err;
13034 
13035 	sec_name = bpf_program__section_name(prog);
13036 	if (strcmp(sec_name, "usdt") == 0) {
13037 		/* no auto-attach for just SEC("usdt") */
13038 		*link = NULL;
13039 		return 0;
13040 	}
13041 
13042 	n = sscanf(sec_name, "usdt/%m[^:]:%m[^:]:%m[^:]", &path, &provider, &name);
13043 	if (n != 3) {
13044 		pr_warn("invalid section '%s', expected SEC(\"usdt/<path>:<provider>:<name>\")\n",
13045 			sec_name);
13046 		err = -EINVAL;
13047 	} else {
13048 		*link = bpf_program__attach_usdt(prog, -1 /* any process */, path,
13049 						 provider, name, NULL);
13050 		err = libbpf_get_error(*link);
13051 	}
13052 	free(path);
13053 	free(provider);
13054 	free(name);
13055 	return err;
13056 }
13057 
13058 static int determine_tracepoint_id(const char *tp_category,
13059 				   const char *tp_name)
13060 {
13061 	char file[PATH_MAX];
13062 	int ret;
13063 
13064 	ret = snprintf(file, sizeof(file), "%s/events/%s/%s/id",
13065 		       tracefs_path(), tp_category, tp_name);
13066 	if (ret < 0)
13067 		return -errno;
13068 	if (ret >= sizeof(file)) {
13069 		pr_debug("tracepoint %s/%s path is too long\n",
13070 			 tp_category, tp_name);
13071 		return -E2BIG;
13072 	}
13073 	return parse_uint_from_file(file, "%d\n");
13074 }
13075 
13076 static int perf_event_open_tracepoint(const char *tp_category,
13077 				      const char *tp_name)
13078 {
13079 	const size_t attr_sz = sizeof(struct perf_event_attr);
13080 	struct perf_event_attr attr;
13081 	int tp_id, pfd, err;
13082 
13083 	tp_id = determine_tracepoint_id(tp_category, tp_name);
13084 	if (tp_id < 0) {
13085 		pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
13086 			tp_category, tp_name,
13087 			errstr(tp_id));
13088 		return tp_id;
13089 	}
13090 
13091 	memset(&attr, 0, attr_sz);
13092 	attr.type = PERF_TYPE_TRACEPOINT;
13093 	attr.size = attr_sz;
13094 	attr.config = tp_id;
13095 
13096 	pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
13097 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
13098 	if (pfd < 0) {
13099 		err = -errno;
13100 		pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
13101 			tp_category, tp_name,
13102 			errstr(err));
13103 		return err;
13104 	}
13105 	return pfd;
13106 }
13107 
13108 struct bpf_link *bpf_program__attach_tracepoint_opts(const struct bpf_program *prog,
13109 						     const char *tp_category,
13110 						     const char *tp_name,
13111 						     const struct bpf_tracepoint_opts *opts)
13112 {
13113 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
13114 	struct bpf_link *link;
13115 	int pfd, err;
13116 
13117 	if (!OPTS_VALID(opts, bpf_tracepoint_opts))
13118 		return libbpf_err_ptr(-EINVAL);
13119 
13120 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
13121 
13122 	pfd = perf_event_open_tracepoint(tp_category, tp_name);
13123 	if (pfd < 0) {
13124 		pr_warn("prog '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
13125 			prog->name, tp_category, tp_name,
13126 			errstr(pfd));
13127 		return libbpf_err_ptr(pfd);
13128 	}
13129 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
13130 	err = libbpf_get_error(link);
13131 	if (err) {
13132 		close(pfd);
13133 		pr_warn("prog '%s': failed to attach to tracepoint '%s/%s': %s\n",
13134 			prog->name, tp_category, tp_name,
13135 			errstr(err));
13136 		return libbpf_err_ptr(err);
13137 	}
13138 	return link;
13139 }
13140 
13141 struct bpf_link *bpf_program__attach_tracepoint(const struct bpf_program *prog,
13142 						const char *tp_category,
13143 						const char *tp_name)
13144 {
13145 	return bpf_program__attach_tracepoint_opts(prog, tp_category, tp_name, NULL);
13146 }
13147 
13148 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
13149 {
13150 	char *sec_name, *tp_cat, *tp_name;
13151 
13152 	*link = NULL;
13153 
13154 	/* no auto-attach for SEC("tp") or SEC("tracepoint") */
13155 	if (strcmp(prog->sec_name, "tp") == 0 || strcmp(prog->sec_name, "tracepoint") == 0)
13156 		return 0;
13157 
13158 	sec_name = strdup(prog->sec_name);
13159 	if (!sec_name)
13160 		return -ENOMEM;
13161 
13162 	/* extract "tp/<category>/<name>" or "tracepoint/<category>/<name>" */
13163 	if (str_has_pfx(prog->sec_name, "tp/"))
13164 		tp_cat = sec_name + sizeof("tp/") - 1;
13165 	else
13166 		tp_cat = sec_name + sizeof("tracepoint/") - 1;
13167 	tp_name = strchr(tp_cat, '/');
13168 	if (!tp_name) {
13169 		free(sec_name);
13170 		return -EINVAL;
13171 	}
13172 	*tp_name = '\0';
13173 	tp_name++;
13174 
13175 	*link = bpf_program__attach_tracepoint(prog, tp_cat, tp_name);
13176 	free(sec_name);
13177 	return libbpf_get_error(*link);
13178 }
13179 
13180 struct bpf_link *
13181 bpf_program__attach_raw_tracepoint_opts(const struct bpf_program *prog,
13182 					const char *tp_name,
13183 					struct bpf_raw_tracepoint_opts *opts)
13184 {
13185 	LIBBPF_OPTS(bpf_raw_tp_opts, raw_opts);
13186 	struct bpf_link *link;
13187 	int prog_fd, pfd;
13188 
13189 	if (!OPTS_VALID(opts, bpf_raw_tracepoint_opts))
13190 		return libbpf_err_ptr(-EINVAL);
13191 
13192 	prog_fd = bpf_program__fd(prog);
13193 	if (prog_fd < 0) {
13194 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
13195 		return libbpf_err_ptr(-EINVAL);
13196 	}
13197 
13198 	link = calloc(1, sizeof(*link));
13199 	if (!link)
13200 		return libbpf_err_ptr(-ENOMEM);
13201 	link->detach = &bpf_link__detach_fd;
13202 
13203 	raw_opts.tp_name = tp_name;
13204 	raw_opts.cookie = OPTS_GET(opts, cookie, 0);
13205 	pfd = bpf_raw_tracepoint_open_opts(prog_fd, &raw_opts);
13206 	if (pfd < 0) {
13207 		pfd = -errno;
13208 		free(link);
13209 		pr_warn("prog '%s': failed to attach to raw tracepoint '%s': %s\n",
13210 			prog->name, tp_name, errstr(pfd));
13211 		return libbpf_err_ptr(pfd);
13212 	}
13213 	link->fd = pfd;
13214 	return link;
13215 }
13216 
13217 struct bpf_link *bpf_program__attach_raw_tracepoint(const struct bpf_program *prog,
13218 						    const char *tp_name)
13219 {
13220 	return bpf_program__attach_raw_tracepoint_opts(prog, tp_name, NULL);
13221 }
13222 
13223 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
13224 {
13225 	static const char *const prefixes[] = {
13226 		"raw_tp",
13227 		"raw_tracepoint",
13228 		"raw_tp.w",
13229 		"raw_tracepoint.w",
13230 	};
13231 	size_t i;
13232 	const char *tp_name = NULL;
13233 
13234 	*link = NULL;
13235 
13236 	for (i = 0; i < ARRAY_SIZE(prefixes); i++) {
13237 		size_t pfx_len;
13238 
13239 		if (!str_has_pfx(prog->sec_name, prefixes[i]))
13240 			continue;
13241 
13242 		pfx_len = strlen(prefixes[i]);
13243 		/* no auto-attach case of, e.g., SEC("raw_tp") */
13244 		if (prog->sec_name[pfx_len] == '\0')
13245 			return 0;
13246 
13247 		if (prog->sec_name[pfx_len] != '/')
13248 			continue;
13249 
13250 		tp_name = prog->sec_name + pfx_len + 1;
13251 		break;
13252 	}
13253 
13254 	if (!tp_name) {
13255 		pr_warn("prog '%s': invalid section name '%s'\n",
13256 			prog->name, prog->sec_name);
13257 		return -EINVAL;
13258 	}
13259 
13260 	*link = bpf_program__attach_raw_tracepoint(prog, tp_name);
13261 	return libbpf_get_error(*link);
13262 }
13263 
13264 /* Common logic for all BPF program types that attach to a btf_id */
13265 static struct bpf_link *bpf_program__attach_btf_id(const struct bpf_program *prog,
13266 						   const struct bpf_trace_opts *opts)
13267 {
13268 	LIBBPF_OPTS(bpf_link_create_opts, link_opts);
13269 	struct bpf_link *link;
13270 	int prog_fd, pfd;
13271 
13272 	if (!OPTS_VALID(opts, bpf_trace_opts))
13273 		return libbpf_err_ptr(-EINVAL);
13274 
13275 	prog_fd = bpf_program__fd(prog);
13276 	if (prog_fd < 0) {
13277 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
13278 		return libbpf_err_ptr(-EINVAL);
13279 	}
13280 
13281 	link = calloc(1, sizeof(*link));
13282 	if (!link)
13283 		return libbpf_err_ptr(-ENOMEM);
13284 	link->detach = &bpf_link__detach_fd;
13285 
13286 	/* libbpf is smart enough to redirect to BPF_RAW_TRACEPOINT_OPEN on old kernels */
13287 	link_opts.tracing.cookie = OPTS_GET(opts, cookie, 0);
13288 	pfd = bpf_link_create(prog_fd, 0, bpf_program__expected_attach_type(prog), &link_opts);
13289 	if (pfd < 0) {
13290 		pfd = -errno;
13291 		free(link);
13292 		pr_warn("prog '%s': failed to attach: %s\n",
13293 			prog->name, errstr(pfd));
13294 		return libbpf_err_ptr(pfd);
13295 	}
13296 	link->fd = pfd;
13297 	return link;
13298 }
13299 
13300 struct bpf_link *bpf_program__attach_trace(const struct bpf_program *prog)
13301 {
13302 	return bpf_program__attach_btf_id(prog, NULL);
13303 }
13304 
13305 struct bpf_link *bpf_program__attach_trace_opts(const struct bpf_program *prog,
13306 						const struct bpf_trace_opts *opts)
13307 {
13308 	return bpf_program__attach_btf_id(prog, opts);
13309 }
13310 
13311 struct bpf_link *bpf_program__attach_lsm(const struct bpf_program *prog)
13312 {
13313 	return bpf_program__attach_btf_id(prog, NULL);
13314 }
13315 
13316 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link)
13317 {
13318 	*link = bpf_program__attach_trace(prog);
13319 	return libbpf_get_error(*link);
13320 }
13321 
13322 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link)
13323 {
13324 	*link = bpf_program__attach_lsm(prog);
13325 	return libbpf_get_error(*link);
13326 }
13327 
13328 static struct bpf_link *
13329 bpf_program_attach_fd(const struct bpf_program *prog,
13330 		      int target_fd, const char *target_name,
13331 		      const struct bpf_link_create_opts *opts)
13332 {
13333 	enum bpf_attach_type attach_type;
13334 	struct bpf_link *link;
13335 	int prog_fd, link_fd;
13336 
13337 	prog_fd = bpf_program__fd(prog);
13338 	if (prog_fd < 0) {
13339 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
13340 		return libbpf_err_ptr(-EINVAL);
13341 	}
13342 
13343 	link = calloc(1, sizeof(*link));
13344 	if (!link)
13345 		return libbpf_err_ptr(-ENOMEM);
13346 	link->detach = &bpf_link__detach_fd;
13347 
13348 	attach_type = bpf_program__expected_attach_type(prog);
13349 	link_fd = bpf_link_create(prog_fd, target_fd, attach_type, opts);
13350 	if (link_fd < 0) {
13351 		link_fd = -errno;
13352 		free(link);
13353 		pr_warn("prog '%s': failed to attach to %s: %s\n",
13354 			prog->name, target_name,
13355 			errstr(link_fd));
13356 		return libbpf_err_ptr(link_fd);
13357 	}
13358 	link->fd = link_fd;
13359 	return link;
13360 }
13361 
13362 struct bpf_link *
13363 bpf_program__attach_cgroup(const struct bpf_program *prog, int cgroup_fd)
13364 {
13365 	return bpf_program_attach_fd(prog, cgroup_fd, "cgroup", NULL);
13366 }
13367 
13368 struct bpf_link *
13369 bpf_program__attach_netns(const struct bpf_program *prog, int netns_fd)
13370 {
13371 	return bpf_program_attach_fd(prog, netns_fd, "netns", NULL);
13372 }
13373 
13374 struct bpf_link *
13375 bpf_program__attach_sockmap(const struct bpf_program *prog, int map_fd)
13376 {
13377 	return bpf_program_attach_fd(prog, map_fd, "sockmap", NULL);
13378 }
13379 
13380 struct bpf_link *bpf_program__attach_xdp(const struct bpf_program *prog, int ifindex)
13381 {
13382 	/* target_fd/target_ifindex use the same field in LINK_CREATE */
13383 	return bpf_program_attach_fd(prog, ifindex, "xdp", NULL);
13384 }
13385 
13386 struct bpf_link *
13387 bpf_program__attach_cgroup_opts(const struct bpf_program *prog, int cgroup_fd,
13388 				const struct bpf_cgroup_opts *opts)
13389 {
13390 	LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
13391 	__u32 relative_id;
13392 	int relative_fd;
13393 
13394 	if (!OPTS_VALID(opts, bpf_cgroup_opts))
13395 		return libbpf_err_ptr(-EINVAL);
13396 
13397 	relative_id = OPTS_GET(opts, relative_id, 0);
13398 	relative_fd = OPTS_GET(opts, relative_fd, 0);
13399 
13400 	if (relative_fd && relative_id) {
13401 		pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
13402 			prog->name);
13403 		return libbpf_err_ptr(-EINVAL);
13404 	}
13405 
13406 	link_create_opts.cgroup.expected_revision = OPTS_GET(opts, expected_revision, 0);
13407 	link_create_opts.cgroup.relative_fd = relative_fd;
13408 	link_create_opts.cgroup.relative_id = relative_id;
13409 	link_create_opts.flags = OPTS_GET(opts, flags, 0);
13410 
13411 	return bpf_program_attach_fd(prog, cgroup_fd, "cgroup", &link_create_opts);
13412 }
13413 
13414 struct bpf_link *
13415 bpf_program__attach_tcx(const struct bpf_program *prog, int ifindex,
13416 			const struct bpf_tcx_opts *opts)
13417 {
13418 	LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
13419 	__u32 relative_id;
13420 	int relative_fd;
13421 
13422 	if (!OPTS_VALID(opts, bpf_tcx_opts))
13423 		return libbpf_err_ptr(-EINVAL);
13424 
13425 	relative_id = OPTS_GET(opts, relative_id, 0);
13426 	relative_fd = OPTS_GET(opts, relative_fd, 0);
13427 
13428 	/* validate we don't have unexpected combinations of non-zero fields */
13429 	if (!ifindex) {
13430 		pr_warn("prog '%s': target netdevice ifindex cannot be zero\n",
13431 			prog->name);
13432 		return libbpf_err_ptr(-EINVAL);
13433 	}
13434 	if (relative_fd && relative_id) {
13435 		pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
13436 			prog->name);
13437 		return libbpf_err_ptr(-EINVAL);
13438 	}
13439 
13440 	link_create_opts.tcx.expected_revision = OPTS_GET(opts, expected_revision, 0);
13441 	link_create_opts.tcx.relative_fd = relative_fd;
13442 	link_create_opts.tcx.relative_id = relative_id;
13443 	link_create_opts.flags = OPTS_GET(opts, flags, 0);
13444 
13445 	/* target_fd/target_ifindex use the same field in LINK_CREATE */
13446 	return bpf_program_attach_fd(prog, ifindex, "tcx", &link_create_opts);
13447 }
13448 
13449 struct bpf_link *
13450 bpf_program__attach_netkit(const struct bpf_program *prog, int ifindex,
13451 			   const struct bpf_netkit_opts *opts)
13452 {
13453 	LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
13454 	__u32 relative_id;
13455 	int relative_fd;
13456 
13457 	if (!OPTS_VALID(opts, bpf_netkit_opts))
13458 		return libbpf_err_ptr(-EINVAL);
13459 
13460 	relative_id = OPTS_GET(opts, relative_id, 0);
13461 	relative_fd = OPTS_GET(opts, relative_fd, 0);
13462 
13463 	/* validate we don't have unexpected combinations of non-zero fields */
13464 	if (!ifindex) {
13465 		pr_warn("prog '%s': target netdevice ifindex cannot be zero\n",
13466 			prog->name);
13467 		return libbpf_err_ptr(-EINVAL);
13468 	}
13469 	if (relative_fd && relative_id) {
13470 		pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
13471 			prog->name);
13472 		return libbpf_err_ptr(-EINVAL);
13473 	}
13474 
13475 	link_create_opts.netkit.expected_revision = OPTS_GET(opts, expected_revision, 0);
13476 	link_create_opts.netkit.relative_fd = relative_fd;
13477 	link_create_opts.netkit.relative_id = relative_id;
13478 	link_create_opts.flags = OPTS_GET(opts, flags, 0);
13479 
13480 	return bpf_program_attach_fd(prog, ifindex, "netkit", &link_create_opts);
13481 }
13482 
13483 struct bpf_link *bpf_program__attach_freplace(const struct bpf_program *prog,
13484 					      int target_fd,
13485 					      const char *attach_func_name)
13486 {
13487 	int btf_id;
13488 
13489 	if (!!target_fd != !!attach_func_name) {
13490 		pr_warn("prog '%s': supply none or both of target_fd and attach_func_name\n",
13491 			prog->name);
13492 		return libbpf_err_ptr(-EINVAL);
13493 	}
13494 
13495 	if (prog->type != BPF_PROG_TYPE_EXT) {
13496 		pr_warn("prog '%s': only BPF_PROG_TYPE_EXT can attach as freplace\n",
13497 			prog->name);
13498 		return libbpf_err_ptr(-EINVAL);
13499 	}
13500 
13501 	if (target_fd) {
13502 		LIBBPF_OPTS(bpf_link_create_opts, target_opts);
13503 
13504 		btf_id = libbpf_find_prog_btf_id(attach_func_name, target_fd, prog->obj->token_fd);
13505 		if (btf_id < 0)
13506 			return libbpf_err_ptr(btf_id);
13507 
13508 		target_opts.target_btf_id = btf_id;
13509 
13510 		return bpf_program_attach_fd(prog, target_fd, "freplace",
13511 					     &target_opts);
13512 	} else {
13513 		/* no target, so use raw_tracepoint_open for compatibility
13514 		 * with old kernels
13515 		 */
13516 		return bpf_program__attach_trace(prog);
13517 	}
13518 }
13519 
13520 struct bpf_link *
13521 bpf_program__attach_iter(const struct bpf_program *prog,
13522 			 const struct bpf_iter_attach_opts *opts)
13523 {
13524 	DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
13525 	struct bpf_link *link;
13526 	int prog_fd, link_fd;
13527 	__u32 target_fd = 0;
13528 
13529 	if (!OPTS_VALID(opts, bpf_iter_attach_opts))
13530 		return libbpf_err_ptr(-EINVAL);
13531 
13532 	link_create_opts.iter_info = OPTS_GET(opts, link_info, (void *)0);
13533 	link_create_opts.iter_info_len = OPTS_GET(opts, link_info_len, 0);
13534 
13535 	prog_fd = bpf_program__fd(prog);
13536 	if (prog_fd < 0) {
13537 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
13538 		return libbpf_err_ptr(-EINVAL);
13539 	}
13540 
13541 	link = calloc(1, sizeof(*link));
13542 	if (!link)
13543 		return libbpf_err_ptr(-ENOMEM);
13544 	link->detach = &bpf_link__detach_fd;
13545 
13546 	link_fd = bpf_link_create(prog_fd, target_fd, BPF_TRACE_ITER,
13547 				  &link_create_opts);
13548 	if (link_fd < 0) {
13549 		link_fd = -errno;
13550 		free(link);
13551 		pr_warn("prog '%s': failed to attach to iterator: %s\n",
13552 			prog->name, errstr(link_fd));
13553 		return libbpf_err_ptr(link_fd);
13554 	}
13555 	link->fd = link_fd;
13556 	return link;
13557 }
13558 
13559 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link)
13560 {
13561 	*link = bpf_program__attach_iter(prog, NULL);
13562 	return libbpf_get_error(*link);
13563 }
13564 
13565 struct bpf_link *bpf_program__attach_netfilter(const struct bpf_program *prog,
13566 					       const struct bpf_netfilter_opts *opts)
13567 {
13568 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
13569 	struct bpf_link *link;
13570 	int prog_fd, link_fd;
13571 
13572 	if (!OPTS_VALID(opts, bpf_netfilter_opts))
13573 		return libbpf_err_ptr(-EINVAL);
13574 
13575 	prog_fd = bpf_program__fd(prog);
13576 	if (prog_fd < 0) {
13577 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
13578 		return libbpf_err_ptr(-EINVAL);
13579 	}
13580 
13581 	link = calloc(1, sizeof(*link));
13582 	if (!link)
13583 		return libbpf_err_ptr(-ENOMEM);
13584 
13585 	link->detach = &bpf_link__detach_fd;
13586 
13587 	lopts.netfilter.pf = OPTS_GET(opts, pf, 0);
13588 	lopts.netfilter.hooknum = OPTS_GET(opts, hooknum, 0);
13589 	lopts.netfilter.priority = OPTS_GET(opts, priority, 0);
13590 	lopts.netfilter.flags = OPTS_GET(opts, flags, 0);
13591 
13592 	link_fd = bpf_link_create(prog_fd, 0, BPF_NETFILTER, &lopts);
13593 	if (link_fd < 0) {
13594 		link_fd = -errno;
13595 		free(link);
13596 		pr_warn("prog '%s': failed to attach to netfilter: %s\n",
13597 			prog->name, errstr(link_fd));
13598 		return libbpf_err_ptr(link_fd);
13599 	}
13600 	link->fd = link_fd;
13601 
13602 	return link;
13603 }
13604 
13605 struct bpf_link *bpf_program__attach(const struct bpf_program *prog)
13606 {
13607 	struct bpf_link *link = NULL;
13608 	int err;
13609 
13610 	if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
13611 		return libbpf_err_ptr(-EOPNOTSUPP);
13612 
13613 	if (bpf_program__fd(prog) < 0) {
13614 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
13615 			prog->name);
13616 		return libbpf_err_ptr(-EINVAL);
13617 	}
13618 
13619 	err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, &link);
13620 	if (err)
13621 		return libbpf_err_ptr(err);
13622 
13623 	/* When calling bpf_program__attach() explicitly, auto-attach support
13624 	 * is expected to work, so NULL returned link is considered an error.
13625 	 * This is different for skeleton's attach, see comment in
13626 	 * bpf_object__attach_skeleton().
13627 	 */
13628 	if (!link)
13629 		return libbpf_err_ptr(-EOPNOTSUPP);
13630 
13631 	return link;
13632 }
13633 
13634 struct bpf_link_struct_ops {
13635 	struct bpf_link link;
13636 	int map_fd;
13637 };
13638 
13639 static int bpf_link__detach_struct_ops(struct bpf_link *link)
13640 {
13641 	struct bpf_link_struct_ops *st_link;
13642 	__u32 zero = 0;
13643 
13644 	st_link = container_of(link, struct bpf_link_struct_ops, link);
13645 
13646 	if (st_link->map_fd < 0)
13647 		/* w/o a real link */
13648 		return bpf_map_delete_elem(link->fd, &zero);
13649 
13650 	return close(link->fd);
13651 }
13652 
13653 struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map)
13654 {
13655 	struct bpf_link_struct_ops *link;
13656 	__u32 zero = 0;
13657 	int err, fd;
13658 
13659 	if (!bpf_map__is_struct_ops(map)) {
13660 		pr_warn("map '%s': can't attach non-struct_ops map\n", map->name);
13661 		return libbpf_err_ptr(-EINVAL);
13662 	}
13663 
13664 	if (map->fd < 0) {
13665 		pr_warn("map '%s': can't attach BPF map without FD (was it created?)\n", map->name);
13666 		return libbpf_err_ptr(-EINVAL);
13667 	}
13668 
13669 	link = calloc(1, sizeof(*link));
13670 	if (!link)
13671 		return libbpf_err_ptr(-EINVAL);
13672 
13673 	/* kern_vdata should be prepared during the loading phase. */
13674 	err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
13675 	/* It can be EBUSY if the map has been used to create or
13676 	 * update a link before.  We don't allow updating the value of
13677 	 * a struct_ops once it is set.  That ensures that the value
13678 	 * never changed.  So, it is safe to skip EBUSY.
13679 	 */
13680 	if (err && (!(map->def.map_flags & BPF_F_LINK) || err != -EBUSY)) {
13681 		free(link);
13682 		return libbpf_err_ptr(err);
13683 	}
13684 
13685 	link->link.detach = bpf_link__detach_struct_ops;
13686 
13687 	if (!(map->def.map_flags & BPF_F_LINK)) {
13688 		/* w/o a real link */
13689 		link->link.fd = map->fd;
13690 		link->map_fd = -1;
13691 		return &link->link;
13692 	}
13693 
13694 	fd = bpf_link_create(map->fd, 0, BPF_STRUCT_OPS, NULL);
13695 	if (fd < 0) {
13696 		free(link);
13697 		return libbpf_err_ptr(fd);
13698 	}
13699 
13700 	link->link.fd = fd;
13701 	link->map_fd = map->fd;
13702 
13703 	return &link->link;
13704 }
13705 
13706 /*
13707  * Swap the back struct_ops of a link with a new struct_ops map.
13708  */
13709 int bpf_link__update_map(struct bpf_link *link, const struct bpf_map *map)
13710 {
13711 	struct bpf_link_struct_ops *st_ops_link;
13712 	__u32 zero = 0;
13713 	int err;
13714 
13715 	if (!bpf_map__is_struct_ops(map))
13716 		return libbpf_err(-EINVAL);
13717 
13718 	if (map->fd < 0) {
13719 		pr_warn("map '%s': can't use BPF map without FD (was it created?)\n", map->name);
13720 		return libbpf_err(-EINVAL);
13721 	}
13722 
13723 	st_ops_link = container_of(link, struct bpf_link_struct_ops, link);
13724 	/* Ensure the type of a link is correct */
13725 	if (st_ops_link->map_fd < 0)
13726 		return libbpf_err(-EINVAL);
13727 
13728 	err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
13729 	/* It can be EBUSY if the map has been used to create or
13730 	 * update a link before.  We don't allow updating the value of
13731 	 * a struct_ops once it is set.  That ensures that the value
13732 	 * never changed.  So, it is safe to skip EBUSY.
13733 	 */
13734 	if (err && err != -EBUSY)
13735 		return err;
13736 
13737 	err = bpf_link_update(link->fd, map->fd, NULL);
13738 	if (err < 0)
13739 		return err;
13740 
13741 	st_ops_link->map_fd = map->fd;
13742 
13743 	return 0;
13744 }
13745 
13746 typedef enum bpf_perf_event_ret (*bpf_perf_event_print_t)(struct perf_event_header *hdr,
13747 							  void *private_data);
13748 
13749 static enum bpf_perf_event_ret
13750 perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
13751 		       void **copy_mem, size_t *copy_size,
13752 		       bpf_perf_event_print_t fn, void *private_data)
13753 {
13754 	struct perf_event_mmap_page *header = mmap_mem;
13755 	__u64 data_head = ring_buffer_read_head(header);
13756 	__u64 data_tail = header->data_tail;
13757 	void *base = ((__u8 *)header) + page_size;
13758 	int ret = LIBBPF_PERF_EVENT_CONT;
13759 	struct perf_event_header *ehdr;
13760 	size_t ehdr_size;
13761 
13762 	while (data_head != data_tail) {
13763 		ehdr = base + (data_tail & (mmap_size - 1));
13764 		ehdr_size = ehdr->size;
13765 
13766 		if (((void *)ehdr) + ehdr_size > base + mmap_size) {
13767 			void *copy_start = ehdr;
13768 			size_t len_first = base + mmap_size - copy_start;
13769 			size_t len_secnd = ehdr_size - len_first;
13770 
13771 			if (*copy_size < ehdr_size) {
13772 				free(*copy_mem);
13773 				*copy_mem = malloc(ehdr_size);
13774 				if (!*copy_mem) {
13775 					*copy_size = 0;
13776 					ret = LIBBPF_PERF_EVENT_ERROR;
13777 					break;
13778 				}
13779 				*copy_size = ehdr_size;
13780 			}
13781 
13782 			memcpy(*copy_mem, copy_start, len_first);
13783 			memcpy(*copy_mem + len_first, base, len_secnd);
13784 			ehdr = *copy_mem;
13785 		}
13786 
13787 		ret = fn(ehdr, private_data);
13788 		data_tail += ehdr_size;
13789 		if (ret != LIBBPF_PERF_EVENT_CONT)
13790 			break;
13791 	}
13792 
13793 	ring_buffer_write_tail(header, data_tail);
13794 	return libbpf_err(ret);
13795 }
13796 
13797 struct perf_buffer;
13798 
13799 struct perf_buffer_params {
13800 	struct perf_event_attr *attr;
13801 	/* if event_cb is specified, it takes precendence */
13802 	perf_buffer_event_fn event_cb;
13803 	/* sample_cb and lost_cb are higher-level common-case callbacks */
13804 	perf_buffer_sample_fn sample_cb;
13805 	perf_buffer_lost_fn lost_cb;
13806 	void *ctx;
13807 	int cpu_cnt;
13808 	int *cpus;
13809 	int *map_keys;
13810 };
13811 
13812 struct perf_cpu_buf {
13813 	struct perf_buffer *pb;
13814 	void *base; /* mmap()'ed memory */
13815 	void *buf; /* for reconstructing segmented data */
13816 	size_t buf_size;
13817 	int fd;
13818 	int cpu;
13819 	int map_key;
13820 };
13821 
13822 struct perf_buffer {
13823 	perf_buffer_event_fn event_cb;
13824 	perf_buffer_sample_fn sample_cb;
13825 	perf_buffer_lost_fn lost_cb;
13826 	void *ctx; /* passed into callbacks */
13827 
13828 	size_t page_size;
13829 	size_t mmap_size;
13830 	struct perf_cpu_buf **cpu_bufs;
13831 	struct epoll_event *events;
13832 	int cpu_cnt; /* number of allocated CPU buffers */
13833 	int epoll_fd; /* perf event FD */
13834 	int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
13835 };
13836 
13837 static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
13838 				      struct perf_cpu_buf *cpu_buf)
13839 {
13840 	if (!cpu_buf)
13841 		return;
13842 	if (cpu_buf->base &&
13843 	    munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
13844 		pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
13845 	if (cpu_buf->fd >= 0) {
13846 		ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
13847 		close(cpu_buf->fd);
13848 	}
13849 	free(cpu_buf->buf);
13850 	free(cpu_buf);
13851 }
13852 
13853 void perf_buffer__free(struct perf_buffer *pb)
13854 {
13855 	int i;
13856 
13857 	if (IS_ERR_OR_NULL(pb))
13858 		return;
13859 	if (pb->cpu_bufs) {
13860 		for (i = 0; i < pb->cpu_cnt; i++) {
13861 			struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
13862 
13863 			if (!cpu_buf)
13864 				continue;
13865 
13866 			bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
13867 			perf_buffer__free_cpu_buf(pb, cpu_buf);
13868 		}
13869 		free(pb->cpu_bufs);
13870 	}
13871 	if (pb->epoll_fd >= 0)
13872 		close(pb->epoll_fd);
13873 	free(pb->events);
13874 	free(pb);
13875 }
13876 
13877 static struct perf_cpu_buf *
13878 perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
13879 			  int cpu, int map_key)
13880 {
13881 	struct perf_cpu_buf *cpu_buf;
13882 	int err;
13883 
13884 	cpu_buf = calloc(1, sizeof(*cpu_buf));
13885 	if (!cpu_buf)
13886 		return ERR_PTR(-ENOMEM);
13887 
13888 	cpu_buf->pb = pb;
13889 	cpu_buf->cpu = cpu;
13890 	cpu_buf->map_key = map_key;
13891 
13892 	cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
13893 			      -1, PERF_FLAG_FD_CLOEXEC);
13894 	if (cpu_buf->fd < 0) {
13895 		err = -errno;
13896 		pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
13897 			cpu, errstr(err));
13898 		goto error;
13899 	}
13900 
13901 	cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
13902 			     PROT_READ | PROT_WRITE, MAP_SHARED,
13903 			     cpu_buf->fd, 0);
13904 	if (cpu_buf->base == MAP_FAILED) {
13905 		cpu_buf->base = NULL;
13906 		err = -errno;
13907 		pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
13908 			cpu, errstr(err));
13909 		goto error;
13910 	}
13911 
13912 	if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
13913 		err = -errno;
13914 		pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
13915 			cpu, errstr(err));
13916 		goto error;
13917 	}
13918 
13919 	return cpu_buf;
13920 
13921 error:
13922 	perf_buffer__free_cpu_buf(pb, cpu_buf);
13923 	return (struct perf_cpu_buf *)ERR_PTR(err);
13924 }
13925 
13926 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
13927 					      struct perf_buffer_params *p);
13928 
13929 struct perf_buffer *perf_buffer__new(int map_fd, size_t page_cnt,
13930 				     perf_buffer_sample_fn sample_cb,
13931 				     perf_buffer_lost_fn lost_cb,
13932 				     void *ctx,
13933 				     const struct perf_buffer_opts *opts)
13934 {
13935 	const size_t attr_sz = sizeof(struct perf_event_attr);
13936 	struct perf_buffer_params p = {};
13937 	struct perf_event_attr attr;
13938 	__u32 sample_period;
13939 
13940 	if (!OPTS_VALID(opts, perf_buffer_opts))
13941 		return libbpf_err_ptr(-EINVAL);
13942 
13943 	sample_period = OPTS_GET(opts, sample_period, 1);
13944 	if (!sample_period)
13945 		sample_period = 1;
13946 
13947 	memset(&attr, 0, attr_sz);
13948 	attr.size = attr_sz;
13949 	attr.config = PERF_COUNT_SW_BPF_OUTPUT;
13950 	attr.type = PERF_TYPE_SOFTWARE;
13951 	attr.sample_type = PERF_SAMPLE_RAW;
13952 	attr.wakeup_events = sample_period;
13953 
13954 	p.attr = &attr;
13955 	p.sample_cb = sample_cb;
13956 	p.lost_cb = lost_cb;
13957 	p.ctx = ctx;
13958 
13959 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
13960 }
13961 
13962 struct perf_buffer *perf_buffer__new_raw(int map_fd, size_t page_cnt,
13963 					 struct perf_event_attr *attr,
13964 					 perf_buffer_event_fn event_cb, void *ctx,
13965 					 const struct perf_buffer_raw_opts *opts)
13966 {
13967 	struct perf_buffer_params p = {};
13968 
13969 	if (!attr)
13970 		return libbpf_err_ptr(-EINVAL);
13971 
13972 	if (!OPTS_VALID(opts, perf_buffer_raw_opts))
13973 		return libbpf_err_ptr(-EINVAL);
13974 
13975 	p.attr = attr;
13976 	p.event_cb = event_cb;
13977 	p.ctx = ctx;
13978 	p.cpu_cnt = OPTS_GET(opts, cpu_cnt, 0);
13979 	p.cpus = OPTS_GET(opts, cpus, NULL);
13980 	p.map_keys = OPTS_GET(opts, map_keys, NULL);
13981 
13982 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
13983 }
13984 
13985 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
13986 					      struct perf_buffer_params *p)
13987 {
13988 	const char *online_cpus_file = "/sys/devices/system/cpu/online";
13989 	struct bpf_map_info map;
13990 	struct perf_buffer *pb;
13991 	bool *online = NULL;
13992 	__u32 map_info_len;
13993 	int err, i, j, n;
13994 
13995 	if (page_cnt == 0 || (page_cnt & (page_cnt - 1))) {
13996 		pr_warn("page count should be power of two, but is %zu\n",
13997 			page_cnt);
13998 		return ERR_PTR(-EINVAL);
13999 	}
14000 
14001 	/* best-effort sanity checks */
14002 	memset(&map, 0, sizeof(map));
14003 	map_info_len = sizeof(map);
14004 	err = bpf_map_get_info_by_fd(map_fd, &map, &map_info_len);
14005 	if (err) {
14006 		err = -errno;
14007 		/* if BPF_OBJ_GET_INFO_BY_FD is supported, will return
14008 		 * -EBADFD, -EFAULT, or -E2BIG on real error
14009 		 */
14010 		if (err != -EINVAL) {
14011 			pr_warn("failed to get map info for map FD %d: %s\n",
14012 				map_fd, errstr(err));
14013 			return ERR_PTR(err);
14014 		}
14015 		pr_debug("failed to get map info for FD %d; API not supported? Ignoring...\n",
14016 			 map_fd);
14017 	} else {
14018 		if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
14019 			pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
14020 				map.name);
14021 			return ERR_PTR(-EINVAL);
14022 		}
14023 	}
14024 
14025 	pb = calloc(1, sizeof(*pb));
14026 	if (!pb)
14027 		return ERR_PTR(-ENOMEM);
14028 
14029 	pb->event_cb = p->event_cb;
14030 	pb->sample_cb = p->sample_cb;
14031 	pb->lost_cb = p->lost_cb;
14032 	pb->ctx = p->ctx;
14033 
14034 	pb->page_size = getpagesize();
14035 	pb->mmap_size = pb->page_size * page_cnt;
14036 	pb->map_fd = map_fd;
14037 
14038 	pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
14039 	if (pb->epoll_fd < 0) {
14040 		err = -errno;
14041 		pr_warn("failed to create epoll instance: %s\n",
14042 			errstr(err));
14043 		goto error;
14044 	}
14045 
14046 	if (p->cpu_cnt > 0) {
14047 		pb->cpu_cnt = p->cpu_cnt;
14048 	} else {
14049 		pb->cpu_cnt = libbpf_num_possible_cpus();
14050 		if (pb->cpu_cnt < 0) {
14051 			err = pb->cpu_cnt;
14052 			goto error;
14053 		}
14054 		if (map.max_entries && map.max_entries < pb->cpu_cnt)
14055 			pb->cpu_cnt = map.max_entries;
14056 	}
14057 
14058 	pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
14059 	if (!pb->events) {
14060 		err = -ENOMEM;
14061 		pr_warn("failed to allocate events: out of memory\n");
14062 		goto error;
14063 	}
14064 	pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
14065 	if (!pb->cpu_bufs) {
14066 		err = -ENOMEM;
14067 		pr_warn("failed to allocate buffers: out of memory\n");
14068 		goto error;
14069 	}
14070 
14071 	err = parse_cpu_mask_file(online_cpus_file, &online, &n);
14072 	if (err) {
14073 		pr_warn("failed to get online CPU mask: %s\n", errstr(err));
14074 		goto error;
14075 	}
14076 
14077 	for (i = 0, j = 0; i < pb->cpu_cnt; i++) {
14078 		struct perf_cpu_buf *cpu_buf;
14079 		int cpu, map_key;
14080 
14081 		cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
14082 		map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
14083 
14084 		/* in case user didn't explicitly requested particular CPUs to
14085 		 * be attached to, skip offline/not present CPUs
14086 		 */
14087 		if (p->cpu_cnt <= 0 && (cpu >= n || !online[cpu]))
14088 			continue;
14089 
14090 		cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
14091 		if (IS_ERR(cpu_buf)) {
14092 			err = PTR_ERR(cpu_buf);
14093 			goto error;
14094 		}
14095 
14096 		pb->cpu_bufs[j] = cpu_buf;
14097 
14098 		err = bpf_map_update_elem(pb->map_fd, &map_key,
14099 					  &cpu_buf->fd, 0);
14100 		if (err) {
14101 			err = -errno;
14102 			pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
14103 				cpu, map_key, cpu_buf->fd,
14104 				errstr(err));
14105 			goto error;
14106 		}
14107 
14108 		pb->events[j].events = EPOLLIN;
14109 		pb->events[j].data.ptr = cpu_buf;
14110 		if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
14111 			      &pb->events[j]) < 0) {
14112 			err = -errno;
14113 			pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
14114 				cpu, cpu_buf->fd,
14115 				errstr(err));
14116 			goto error;
14117 		}
14118 		j++;
14119 	}
14120 	pb->cpu_cnt = j;
14121 	free(online);
14122 
14123 	return pb;
14124 
14125 error:
14126 	free(online);
14127 	if (pb)
14128 		perf_buffer__free(pb);
14129 	return ERR_PTR(err);
14130 }
14131 
14132 struct perf_sample_raw {
14133 	struct perf_event_header header;
14134 	uint32_t size;
14135 	char data[];
14136 };
14137 
14138 struct perf_sample_lost {
14139 	struct perf_event_header header;
14140 	uint64_t id;
14141 	uint64_t lost;
14142 	uint64_t sample_id;
14143 };
14144 
14145 static enum bpf_perf_event_ret
14146 perf_buffer__process_record(struct perf_event_header *e, void *ctx)
14147 {
14148 	struct perf_cpu_buf *cpu_buf = ctx;
14149 	struct perf_buffer *pb = cpu_buf->pb;
14150 	void *data = e;
14151 
14152 	/* user wants full control over parsing perf event */
14153 	if (pb->event_cb)
14154 		return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
14155 
14156 	switch (e->type) {
14157 	case PERF_RECORD_SAMPLE: {
14158 		struct perf_sample_raw *s = data;
14159 
14160 		if (pb->sample_cb)
14161 			pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
14162 		break;
14163 	}
14164 	case PERF_RECORD_LOST: {
14165 		struct perf_sample_lost *s = data;
14166 
14167 		if (pb->lost_cb)
14168 			pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
14169 		break;
14170 	}
14171 	default:
14172 		pr_warn("unknown perf sample type %d\n", e->type);
14173 		return LIBBPF_PERF_EVENT_ERROR;
14174 	}
14175 	return LIBBPF_PERF_EVENT_CONT;
14176 }
14177 
14178 static int perf_buffer__process_records(struct perf_buffer *pb,
14179 					struct perf_cpu_buf *cpu_buf)
14180 {
14181 	enum bpf_perf_event_ret ret;
14182 
14183 	ret = perf_event_read_simple(cpu_buf->base, pb->mmap_size,
14184 				     pb->page_size, &cpu_buf->buf,
14185 				     &cpu_buf->buf_size,
14186 				     perf_buffer__process_record, cpu_buf);
14187 	if (ret != LIBBPF_PERF_EVENT_CONT)
14188 		return ret;
14189 	return 0;
14190 }
14191 
14192 int perf_buffer__epoll_fd(const struct perf_buffer *pb)
14193 {
14194 	return pb->epoll_fd;
14195 }
14196 
14197 int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
14198 {
14199 	int i, cnt, err;
14200 
14201 	cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
14202 	if (cnt < 0)
14203 		return -errno;
14204 
14205 	for (i = 0; i < cnt; i++) {
14206 		struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
14207 
14208 		err = perf_buffer__process_records(pb, cpu_buf);
14209 		if (err) {
14210 			pr_warn("error while processing records: %s\n", errstr(err));
14211 			return libbpf_err(err);
14212 		}
14213 	}
14214 	return cnt;
14215 }
14216 
14217 /* Return number of PERF_EVENT_ARRAY map slots set up by this perf_buffer
14218  * manager.
14219  */
14220 size_t perf_buffer__buffer_cnt(const struct perf_buffer *pb)
14221 {
14222 	return pb->cpu_cnt;
14223 }
14224 
14225 /*
14226  * Return perf_event FD of a ring buffer in *buf_idx* slot of
14227  * PERF_EVENT_ARRAY BPF map. This FD can be polled for new data using
14228  * select()/poll()/epoll() Linux syscalls.
14229  */
14230 int perf_buffer__buffer_fd(const struct perf_buffer *pb, size_t buf_idx)
14231 {
14232 	struct perf_cpu_buf *cpu_buf;
14233 
14234 	if (buf_idx >= pb->cpu_cnt)
14235 		return libbpf_err(-EINVAL);
14236 
14237 	cpu_buf = pb->cpu_bufs[buf_idx];
14238 	if (!cpu_buf)
14239 		return libbpf_err(-ENOENT);
14240 
14241 	return cpu_buf->fd;
14242 }
14243 
14244 int perf_buffer__buffer(struct perf_buffer *pb, int buf_idx, void **buf, size_t *buf_size)
14245 {
14246 	struct perf_cpu_buf *cpu_buf;
14247 
14248 	if (buf_idx >= pb->cpu_cnt)
14249 		return libbpf_err(-EINVAL);
14250 
14251 	cpu_buf = pb->cpu_bufs[buf_idx];
14252 	if (!cpu_buf)
14253 		return libbpf_err(-ENOENT);
14254 
14255 	*buf = cpu_buf->base;
14256 	*buf_size = pb->mmap_size;
14257 	return 0;
14258 }
14259 
14260 /*
14261  * Consume data from perf ring buffer corresponding to slot *buf_idx* in
14262  * PERF_EVENT_ARRAY BPF map without waiting/polling. If there is no data to
14263  * consume, do nothing and return success.
14264  * Returns:
14265  *   - 0 on success;
14266  *   - <0 on failure.
14267  */
14268 int perf_buffer__consume_buffer(struct perf_buffer *pb, size_t buf_idx)
14269 {
14270 	struct perf_cpu_buf *cpu_buf;
14271 
14272 	if (buf_idx >= pb->cpu_cnt)
14273 		return libbpf_err(-EINVAL);
14274 
14275 	cpu_buf = pb->cpu_bufs[buf_idx];
14276 	if (!cpu_buf)
14277 		return libbpf_err(-ENOENT);
14278 
14279 	return perf_buffer__process_records(pb, cpu_buf);
14280 }
14281 
14282 int perf_buffer__consume(struct perf_buffer *pb)
14283 {
14284 	int i, err;
14285 
14286 	for (i = 0; i < pb->cpu_cnt; i++) {
14287 		struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
14288 
14289 		if (!cpu_buf)
14290 			continue;
14291 
14292 		err = perf_buffer__process_records(pb, cpu_buf);
14293 		if (err) {
14294 			pr_warn("perf_buffer: failed to process records in buffer #%d: %s\n",
14295 				i, errstr(err));
14296 			return libbpf_err(err);
14297 		}
14298 	}
14299 	return 0;
14300 }
14301 
14302 int bpf_program__set_attach_target(struct bpf_program *prog,
14303 				   int attach_prog_fd,
14304 				   const char *attach_func_name)
14305 {
14306 	int btf_obj_fd = 0, btf_id = 0, err;
14307 
14308 	if (!prog || attach_prog_fd < 0)
14309 		return libbpf_err(-EINVAL);
14310 
14311 	if (prog->obj->state >= OBJ_LOADED)
14312 		return libbpf_err(-EINVAL);
14313 
14314 	if (attach_prog_fd && !attach_func_name) {
14315 		/* Store attach_prog_fd. The BTF ID will be resolved later during
14316 		 * the normal object/program load phase.
14317 		 */
14318 		prog->attach_prog_fd = attach_prog_fd;
14319 		return 0;
14320 	}
14321 
14322 	if (attach_prog_fd) {
14323 		btf_id = libbpf_find_prog_btf_id(attach_func_name,
14324 						 attach_prog_fd, prog->obj->token_fd);
14325 		if (btf_id < 0)
14326 			return libbpf_err(btf_id);
14327 	} else {
14328 		if (!attach_func_name)
14329 			return libbpf_err(-EINVAL);
14330 
14331 		/* load btf_vmlinux, if not yet */
14332 		err = bpf_object__load_vmlinux_btf(prog->obj, true);
14333 		if (err)
14334 			return libbpf_err(err);
14335 		err = find_kernel_btf_id(prog->obj, attach_func_name,
14336 					 prog->expected_attach_type,
14337 					 &btf_obj_fd, &btf_id);
14338 		if (err)
14339 			return libbpf_err(err);
14340 	}
14341 
14342 	prog->attach_btf_id = btf_id;
14343 	prog->attach_btf_obj_fd = btf_obj_fd;
14344 	prog->attach_prog_fd = attach_prog_fd;
14345 	return 0;
14346 }
14347 
14348 int bpf_program__assoc_struct_ops(struct bpf_program *prog, struct bpf_map *map,
14349 				  struct bpf_prog_assoc_struct_ops_opts *opts)
14350 {
14351 	int prog_fd, map_fd;
14352 
14353 	prog_fd = bpf_program__fd(prog);
14354 	if (prog_fd < 0) {
14355 		pr_warn("prog '%s': can't associate BPF program without FD (was it loaded?)\n",
14356 			prog->name);
14357 		return libbpf_err(-EINVAL);
14358 	}
14359 
14360 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS) {
14361 		pr_warn("prog '%s': can't associate struct_ops program\n", prog->name);
14362 		return libbpf_err(-EINVAL);
14363 	}
14364 
14365 	map_fd = bpf_map__fd(map);
14366 	if (map_fd < 0) {
14367 		pr_warn("map '%s': can't associate BPF map without FD (was it created?)\n", map->name);
14368 		return libbpf_err(-EINVAL);
14369 	}
14370 
14371 	if (!bpf_map__is_struct_ops(map)) {
14372 		pr_warn("map '%s': can't associate non-struct_ops map\n", map->name);
14373 		return libbpf_err(-EINVAL);
14374 	}
14375 
14376 	return bpf_prog_assoc_struct_ops(prog_fd, map_fd, opts);
14377 }
14378 
14379 int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz)
14380 {
14381 	int err = 0, n, len, start, end = -1;
14382 	bool *tmp;
14383 
14384 	*mask = NULL;
14385 	*mask_sz = 0;
14386 
14387 	/* Each sub string separated by ',' has format \d+-\d+ or \d+ */
14388 	while (*s) {
14389 		if (*s == ',' || *s == '\n') {
14390 			s++;
14391 			continue;
14392 		}
14393 		n = sscanf(s, "%d%n-%d%n", &start, &len, &end, &len);
14394 		if (n <= 0 || n > 2) {
14395 			pr_warn("Failed to get CPU range %s: %d\n", s, n);
14396 			err = -EINVAL;
14397 			goto cleanup;
14398 		} else if (n == 1) {
14399 			end = start;
14400 		}
14401 		if (start < 0 || start > end) {
14402 			pr_warn("Invalid CPU range [%d,%d] in %s\n",
14403 				start, end, s);
14404 			err = -EINVAL;
14405 			goto cleanup;
14406 		}
14407 		tmp = realloc(*mask, end + 1);
14408 		if (!tmp) {
14409 			err = -ENOMEM;
14410 			goto cleanup;
14411 		}
14412 		*mask = tmp;
14413 		memset(tmp + *mask_sz, 0, start - *mask_sz);
14414 		memset(tmp + start, 1, end - start + 1);
14415 		*mask_sz = end + 1;
14416 		s += len;
14417 	}
14418 	if (!*mask_sz) {
14419 		pr_warn("Empty CPU range\n");
14420 		return -EINVAL;
14421 	}
14422 	return 0;
14423 cleanup:
14424 	free(*mask);
14425 	*mask = NULL;
14426 	return err;
14427 }
14428 
14429 int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz)
14430 {
14431 	int fd, err = 0, len;
14432 	char buf[128];
14433 
14434 	fd = open(fcpu, O_RDONLY | O_CLOEXEC);
14435 	if (fd < 0) {
14436 		err = -errno;
14437 		pr_warn("Failed to open cpu mask file %s: %s\n", fcpu, errstr(err));
14438 		return err;
14439 	}
14440 	len = read(fd, buf, sizeof(buf));
14441 	close(fd);
14442 	if (len <= 0) {
14443 		err = len ? -errno : -EINVAL;
14444 		pr_warn("Failed to read cpu mask from %s: %s\n", fcpu, errstr(err));
14445 		return err;
14446 	}
14447 	if (len >= sizeof(buf)) {
14448 		pr_warn("CPU mask is too big in file %s\n", fcpu);
14449 		return -E2BIG;
14450 	}
14451 	buf[len] = '\0';
14452 
14453 	return parse_cpu_mask_str(buf, mask, mask_sz);
14454 }
14455 
14456 int libbpf_num_possible_cpus(void)
14457 {
14458 	static const char *fcpu = "/sys/devices/system/cpu/possible";
14459 	static int cpus;
14460 	int err, n, i, tmp_cpus;
14461 	bool *mask;
14462 
14463 	tmp_cpus = READ_ONCE(cpus);
14464 	if (tmp_cpus > 0)
14465 		return tmp_cpus;
14466 
14467 	err = parse_cpu_mask_file(fcpu, &mask, &n);
14468 	if (err)
14469 		return libbpf_err(err);
14470 
14471 	tmp_cpus = 0;
14472 	for (i = 0; i < n; i++) {
14473 		if (mask[i])
14474 			tmp_cpus++;
14475 	}
14476 	free(mask);
14477 
14478 	WRITE_ONCE(cpus, tmp_cpus);
14479 	return tmp_cpus;
14480 }
14481 
14482 static int populate_skeleton_maps(const struct bpf_object *obj,
14483 				  struct bpf_map_skeleton *maps,
14484 				  size_t map_cnt, size_t map_skel_sz)
14485 {
14486 	int i;
14487 
14488 	for (i = 0; i < map_cnt; i++) {
14489 		struct bpf_map_skeleton *map_skel = (void *)maps + i * map_skel_sz;
14490 		struct bpf_map **map = map_skel->map;
14491 		const char *name = map_skel->name;
14492 		void **mmaped = map_skel->mmaped;
14493 
14494 		*map = bpf_object__find_map_by_name(obj, name);
14495 		if (!*map) {
14496 			pr_warn("failed to find skeleton map '%s'\n", name);
14497 			return -ESRCH;
14498 		}
14499 
14500 		/* externs shouldn't be pre-setup from user code */
14501 		if (mmaped && (*map)->libbpf_type != LIBBPF_MAP_KCONFIG)
14502 			*mmaped = (*map)->mmaped;
14503 	}
14504 	return 0;
14505 }
14506 
14507 static int populate_skeleton_progs(const struct bpf_object *obj,
14508 				   struct bpf_prog_skeleton *progs,
14509 				   size_t prog_cnt, size_t prog_skel_sz)
14510 {
14511 	int i;
14512 
14513 	for (i = 0; i < prog_cnt; i++) {
14514 		struct bpf_prog_skeleton *prog_skel = (void *)progs + i * prog_skel_sz;
14515 		struct bpf_program **prog = prog_skel->prog;
14516 		const char *name = prog_skel->name;
14517 
14518 		*prog = bpf_object__find_program_by_name(obj, name);
14519 		if (!*prog) {
14520 			pr_warn("failed to find skeleton program '%s'\n", name);
14521 			return -ESRCH;
14522 		}
14523 	}
14524 	return 0;
14525 }
14526 
14527 int bpf_object__open_skeleton(struct bpf_object_skeleton *s,
14528 			      const struct bpf_object_open_opts *opts)
14529 {
14530 	struct bpf_object *obj;
14531 	int err;
14532 
14533 	obj = bpf_object_open(NULL, s->data, s->data_sz, s->name, opts);
14534 	if (IS_ERR(obj)) {
14535 		err = PTR_ERR(obj);
14536 		pr_warn("failed to initialize skeleton BPF object '%s': %s\n",
14537 			s->name, errstr(err));
14538 		return libbpf_err(err);
14539 	}
14540 
14541 	*s->obj = obj;
14542 	err = populate_skeleton_maps(obj, s->maps, s->map_cnt, s->map_skel_sz);
14543 	if (err) {
14544 		pr_warn("failed to populate skeleton maps for '%s': %s\n", s->name, errstr(err));
14545 		return libbpf_err(err);
14546 	}
14547 
14548 	err = populate_skeleton_progs(obj, s->progs, s->prog_cnt, s->prog_skel_sz);
14549 	if (err) {
14550 		pr_warn("failed to populate skeleton progs for '%s': %s\n", s->name, errstr(err));
14551 		return libbpf_err(err);
14552 	}
14553 
14554 	return 0;
14555 }
14556 
14557 int bpf_object__open_subskeleton(struct bpf_object_subskeleton *s)
14558 {
14559 	int err, len, var_idx, i;
14560 	const char *var_name;
14561 	const struct bpf_map *map;
14562 	struct btf *btf;
14563 	__u32 map_type_id;
14564 	const struct btf_type *map_type, *var_type;
14565 	const struct bpf_var_skeleton *var_skel;
14566 	struct btf_var_secinfo *var;
14567 
14568 	if (!s->obj)
14569 		return libbpf_err(-EINVAL);
14570 
14571 	btf = bpf_object__btf(s->obj);
14572 	if (!btf) {
14573 		pr_warn("subskeletons require BTF at runtime (object %s)\n",
14574 			bpf_object__name(s->obj));
14575 		return libbpf_err(-errno);
14576 	}
14577 
14578 	err = populate_skeleton_maps(s->obj, s->maps, s->map_cnt, s->map_skel_sz);
14579 	if (err) {
14580 		pr_warn("failed to populate subskeleton maps: %s\n", errstr(err));
14581 		return libbpf_err(err);
14582 	}
14583 
14584 	err = populate_skeleton_progs(s->obj, s->progs, s->prog_cnt, s->prog_skel_sz);
14585 	if (err) {
14586 		pr_warn("failed to populate subskeleton maps: %s\n", errstr(err));
14587 		return libbpf_err(err);
14588 	}
14589 
14590 	for (var_idx = 0; var_idx < s->var_cnt; var_idx++) {
14591 		var_skel = (void *)s->vars + var_idx * s->var_skel_sz;
14592 		map = *var_skel->map;
14593 		map_type_id = bpf_map__btf_value_type_id(map);
14594 		map_type = btf__type_by_id(btf, map_type_id);
14595 
14596 		if (!btf_is_datasec(map_type)) {
14597 			pr_warn("type for map '%1$s' is not a datasec: %2$s\n",
14598 				bpf_map__name(map),
14599 				__btf_kind_str(btf_kind(map_type)));
14600 			return libbpf_err(-EINVAL);
14601 		}
14602 
14603 		len = btf_vlen(map_type);
14604 		var = btf_var_secinfos(map_type);
14605 		for (i = 0; i < len; i++, var++) {
14606 			var_type = btf__type_by_id(btf, var->type);
14607 			var_name = btf__name_by_offset(btf, var_type->name_off);
14608 			if (strcmp(var_name, var_skel->name) == 0) {
14609 				*var_skel->addr = map->mmaped + var->offset;
14610 				break;
14611 			}
14612 		}
14613 	}
14614 	return 0;
14615 }
14616 
14617 void bpf_object__destroy_subskeleton(struct bpf_object_subskeleton *s)
14618 {
14619 	if (!s)
14620 		return;
14621 	free(s->maps);
14622 	free(s->progs);
14623 	free(s->vars);
14624 	free(s);
14625 }
14626 
14627 int bpf_object__load_skeleton(struct bpf_object_skeleton *s)
14628 {
14629 	int i, err;
14630 
14631 	err = bpf_object__load(*s->obj);
14632 	if (err) {
14633 		pr_warn("failed to load BPF skeleton '%s': %s\n", s->name, errstr(err));
14634 		return libbpf_err(err);
14635 	}
14636 
14637 	for (i = 0; i < s->map_cnt; i++) {
14638 		struct bpf_map_skeleton *map_skel = (void *)s->maps + i * s->map_skel_sz;
14639 		struct bpf_map *map = *map_skel->map;
14640 
14641 		if (!map_skel->mmaped)
14642 			continue;
14643 
14644 		if (map->def.type == BPF_MAP_TYPE_ARENA)
14645 			*map_skel->mmaped = map->mmaped + map->obj->arena_data_off;
14646 		else
14647 			*map_skel->mmaped = map->mmaped;
14648 	}
14649 
14650 	return 0;
14651 }
14652 
14653 int bpf_object__attach_skeleton(struct bpf_object_skeleton *s)
14654 {
14655 	int i, err;
14656 
14657 	for (i = 0; i < s->prog_cnt; i++) {
14658 		struct bpf_prog_skeleton *prog_skel = (void *)s->progs + i * s->prog_skel_sz;
14659 		struct bpf_program *prog = *prog_skel->prog;
14660 		struct bpf_link **link = prog_skel->link;
14661 
14662 		if (!prog->autoload || !prog->autoattach)
14663 			continue;
14664 
14665 		/* auto-attaching not supported for this program */
14666 		if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
14667 			continue;
14668 
14669 		/* if user already set the link manually, don't attempt auto-attach */
14670 		if (*link)
14671 			continue;
14672 
14673 		err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, link);
14674 		if (err) {
14675 			pr_warn("prog '%s': failed to auto-attach: %s\n",
14676 				bpf_program__name(prog), errstr(err));
14677 			return libbpf_err(err);
14678 		}
14679 
14680 		/* It's possible that for some SEC() definitions auto-attach
14681 		 * is supported in some cases (e.g., if definition completely
14682 		 * specifies target information), but is not in other cases.
14683 		 * SEC("uprobe") is one such case. If user specified target
14684 		 * binary and function name, such BPF program can be
14685 		 * auto-attached. But if not, it shouldn't trigger skeleton's
14686 		 * attach to fail. It should just be skipped.
14687 		 * attach_fn signals such case with returning 0 (no error) and
14688 		 * setting link to NULL.
14689 		 */
14690 	}
14691 
14692 
14693 	for (i = 0; i < s->map_cnt; i++) {
14694 		struct bpf_map_skeleton *map_skel = (void *)s->maps + i * s->map_skel_sz;
14695 		struct bpf_map *map = *map_skel->map;
14696 		struct bpf_link **link;
14697 
14698 		if (!map->autocreate || !map->autoattach)
14699 			continue;
14700 
14701 		/* only struct_ops maps can be attached */
14702 		if (!bpf_map__is_struct_ops(map))
14703 			continue;
14704 
14705 		/* skeleton is created with earlier version of bpftool, notify user */
14706 		if (s->map_skel_sz < offsetofend(struct bpf_map_skeleton, link)) {
14707 			pr_warn("map '%s': BPF skeleton version is old, skipping map auto-attachment...\n",
14708 				bpf_map__name(map));
14709 			continue;
14710 		}
14711 
14712 		link = map_skel->link;
14713 		if (!link) {
14714 			pr_warn("map '%s': BPF map skeleton link is uninitialized\n",
14715 				bpf_map__name(map));
14716 			continue;
14717 		}
14718 
14719 		if (*link)
14720 			continue;
14721 
14722 		*link = bpf_map__attach_struct_ops(map);
14723 		if (!*link) {
14724 			err = -errno;
14725 			pr_warn("map '%s': failed to auto-attach: %s\n",
14726 				bpf_map__name(map), errstr(err));
14727 			return libbpf_err(err);
14728 		}
14729 	}
14730 
14731 	return 0;
14732 }
14733 
14734 void bpf_object__detach_skeleton(struct bpf_object_skeleton *s)
14735 {
14736 	int i;
14737 
14738 	for (i = 0; i < s->prog_cnt; i++) {
14739 		struct bpf_prog_skeleton *prog_skel = (void *)s->progs + i * s->prog_skel_sz;
14740 		struct bpf_link **link = prog_skel->link;
14741 
14742 		bpf_link__destroy(*link);
14743 		*link = NULL;
14744 	}
14745 
14746 	if (s->map_skel_sz < sizeof(struct bpf_map_skeleton))
14747 		return;
14748 
14749 	for (i = 0; i < s->map_cnt; i++) {
14750 		struct bpf_map_skeleton *map_skel = (void *)s->maps + i * s->map_skel_sz;
14751 		struct bpf_link **link = map_skel->link;
14752 
14753 		if (link) {
14754 			bpf_link__destroy(*link);
14755 			*link = NULL;
14756 		}
14757 	}
14758 }
14759 
14760 void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s)
14761 {
14762 	if (!s)
14763 		return;
14764 
14765 	bpf_object__detach_skeleton(s);
14766 	if (s->obj)
14767 		bpf_object__close(*s->obj);
14768 	free(s->maps);
14769 	free(s->progs);
14770 	free(s);
14771 }
14772