xref: /linux/tools/lib/bpf/libbpf.c (revision 40286d6379aacfcc053253ef78dc78b09addffda)
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 		err = bpf_btf_get_info_by_fd(fd, &info, &len);
5856 		if (err) {
5857 			err = -errno;
5858 			pr_warn("failed to get BTF object #%d info: %s\n", id, errstr(err));
5859 			goto err_out;
5860 		}
5861 
5862 		/* ignore non-module BTFs */
5863 		if (!info.kernel_btf || strcmp(name, "vmlinux") == 0) {
5864 			close(fd);
5865 			continue;
5866 		}
5867 
5868 		btf = btf_get_from_fd(fd, obj->btf_vmlinux);
5869 		err = libbpf_get_error(btf);
5870 		if (err) {
5871 			pr_warn("failed to load module [%s]'s BTF object #%d: %s\n",
5872 				name, id, errstr(err));
5873 			goto err_out;
5874 		}
5875 
5876 		err = libbpf_ensure_mem((void **)&obj->btf_modules, &obj->btf_module_cap,
5877 					sizeof(*obj->btf_modules), obj->btf_module_cnt + 1);
5878 		if (err)
5879 			goto err_out;
5880 
5881 		mod_btf = &obj->btf_modules[obj->btf_module_cnt++];
5882 
5883 		mod_btf->btf = btf;
5884 		mod_btf->id = id;
5885 		mod_btf->fd = fd;
5886 		mod_btf->name = strdup(name);
5887 		if (!mod_btf->name) {
5888 			err = -ENOMEM;
5889 			goto err_out;
5890 		}
5891 		continue;
5892 
5893 err_out:
5894 		close(fd);
5895 		return err;
5896 	}
5897 
5898 	return 0;
5899 }
5900 
5901 static struct bpf_core_cand_list *
5902 bpf_core_find_cands(struct bpf_object *obj, const struct btf *local_btf, __u32 local_type_id)
5903 {
5904 	struct bpf_core_cand local_cand = {};
5905 	struct bpf_core_cand_list *cands;
5906 	const struct btf *main_btf;
5907 	const struct btf_type *local_t;
5908 	const char *local_name;
5909 	size_t local_essent_len;
5910 	int err, i;
5911 
5912 	local_cand.btf = local_btf;
5913 	local_cand.id = local_type_id;
5914 	local_t = btf__type_by_id(local_btf, local_type_id);
5915 	if (!local_t)
5916 		return ERR_PTR(-EINVAL);
5917 
5918 	local_name = btf__name_by_offset(local_btf, local_t->name_off);
5919 	if (str_is_empty(local_name))
5920 		return ERR_PTR(-EINVAL);
5921 	local_essent_len = bpf_core_essential_name_len(local_name);
5922 
5923 	cands = calloc(1, sizeof(*cands));
5924 	if (!cands)
5925 		return ERR_PTR(-ENOMEM);
5926 
5927 	/* Attempt to find target candidates in vmlinux BTF first */
5928 	main_btf = obj->btf_vmlinux_override ?: obj->btf_vmlinux;
5929 	err = bpf_core_add_cands(&local_cand, local_essent_len, main_btf, "vmlinux", 1, cands);
5930 	if (err)
5931 		goto err_out;
5932 
5933 	/* if vmlinux BTF has any candidate, don't got for module BTFs */
5934 	if (cands->len)
5935 		return cands;
5936 
5937 	/* if vmlinux BTF was overridden, don't attempt to load module BTFs */
5938 	if (obj->btf_vmlinux_override)
5939 		return cands;
5940 
5941 	/* now look through module BTFs, trying to still find candidates */
5942 	err = load_module_btfs(obj);
5943 	if (err)
5944 		goto err_out;
5945 
5946 	for (i = 0; i < obj->btf_module_cnt; i++) {
5947 		err = bpf_core_add_cands(&local_cand, local_essent_len,
5948 					 obj->btf_modules[i].btf,
5949 					 obj->btf_modules[i].name,
5950 					 btf__type_cnt(obj->btf_vmlinux),
5951 					 cands);
5952 		if (err)
5953 			goto err_out;
5954 	}
5955 
5956 	return cands;
5957 err_out:
5958 	bpf_core_free_cands(cands);
5959 	return ERR_PTR(err);
5960 }
5961 
5962 /* Check local and target types for compatibility. This check is used for
5963  * type-based CO-RE relocations and follow slightly different rules than
5964  * field-based relocations. This function assumes that root types were already
5965  * checked for name match. Beyond that initial root-level name check, names
5966  * are completely ignored. Compatibility rules are as follows:
5967  *   - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs are considered compatible, but
5968  *     kind should match for local and target types (i.e., STRUCT is not
5969  *     compatible with UNION);
5970  *   - for ENUMs, the size is ignored;
5971  *   - for INT, size and signedness are ignored;
5972  *   - for ARRAY, dimensionality is ignored, element types are checked for
5973  *     compatibility recursively;
5974  *   - CONST/VOLATILE/RESTRICT modifiers are ignored;
5975  *   - TYPEDEFs/PTRs are compatible if types they pointing to are compatible;
5976  *   - FUNC_PROTOs are compatible if they have compatible signature: same
5977  *     number of input args and compatible return and argument types.
5978  * These rules are not set in stone and probably will be adjusted as we get
5979  * more experience with using BPF CO-RE relocations.
5980  */
5981 int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
5982 			      const struct btf *targ_btf, __u32 targ_id)
5983 {
5984 	return __bpf_core_types_are_compat(local_btf, local_id, targ_btf, targ_id, 32);
5985 }
5986 
5987 int bpf_core_types_match(const struct btf *local_btf, __u32 local_id,
5988 			 const struct btf *targ_btf, __u32 targ_id)
5989 {
5990 	return __bpf_core_types_match(local_btf, local_id, targ_btf, targ_id, false, 32);
5991 }
5992 
5993 static size_t bpf_core_hash_fn(const long key, void *ctx)
5994 {
5995 	return key;
5996 }
5997 
5998 static bool bpf_core_equal_fn(const long k1, const long k2, void *ctx)
5999 {
6000 	return k1 == k2;
6001 }
6002 
6003 static int record_relo_core(struct bpf_program *prog,
6004 			    const struct bpf_core_relo *core_relo, int insn_idx)
6005 {
6006 	struct reloc_desc *relos, *relo;
6007 
6008 	relos = libbpf_reallocarray(prog->reloc_desc,
6009 				    prog->nr_reloc + 1, sizeof(*relos));
6010 	if (!relos)
6011 		return -ENOMEM;
6012 	relo = &relos[prog->nr_reloc];
6013 	relo->type = RELO_CORE;
6014 	relo->insn_idx = insn_idx;
6015 	relo->core_relo = core_relo;
6016 	prog->reloc_desc = relos;
6017 	prog->nr_reloc++;
6018 	return 0;
6019 }
6020 
6021 static const struct bpf_core_relo *find_relo_core(struct bpf_program *prog, int insn_idx)
6022 {
6023 	struct reloc_desc *relo;
6024 	int i;
6025 
6026 	for (i = 0; i < prog->nr_reloc; i++) {
6027 		relo = &prog->reloc_desc[i];
6028 		if (relo->type != RELO_CORE || relo->insn_idx != insn_idx)
6029 			continue;
6030 
6031 		return relo->core_relo;
6032 	}
6033 
6034 	return NULL;
6035 }
6036 
6037 static int bpf_core_resolve_relo(struct bpf_program *prog,
6038 				 const struct bpf_core_relo *relo,
6039 				 int relo_idx,
6040 				 const struct btf *local_btf,
6041 				 struct hashmap *cand_cache,
6042 				 struct bpf_core_relo_res *targ_res)
6043 {
6044 	struct bpf_core_spec specs_scratch[3] = {};
6045 	struct bpf_core_cand_list *cands = NULL;
6046 	const char *prog_name = prog->name;
6047 	const struct btf_type *local_type;
6048 	const char *local_name;
6049 	__u32 local_id = relo->type_id;
6050 	int err;
6051 
6052 	local_type = btf__type_by_id(local_btf, local_id);
6053 	if (!local_type)
6054 		return -EINVAL;
6055 
6056 	local_name = btf__name_by_offset(local_btf, local_type->name_off);
6057 	if (!local_name)
6058 		return -EINVAL;
6059 
6060 	if (relo->kind != BPF_CORE_TYPE_ID_LOCAL &&
6061 	    !hashmap__find(cand_cache, local_id, &cands)) {
6062 		cands = bpf_core_find_cands(prog->obj, local_btf, local_id);
6063 		if (IS_ERR(cands)) {
6064 			pr_warn("prog '%s': relo #%d: target candidate search failed for [%d] %s %s: %ld\n",
6065 				prog_name, relo_idx, local_id, btf_kind_str(local_type),
6066 				local_name, PTR_ERR(cands));
6067 			return PTR_ERR(cands);
6068 		}
6069 		err = hashmap__set(cand_cache, local_id, cands, NULL, NULL);
6070 		if (err) {
6071 			bpf_core_free_cands(cands);
6072 			return err;
6073 		}
6074 	}
6075 
6076 	return bpf_core_calc_relo_insn(prog_name, relo, relo_idx, local_btf, cands, specs_scratch,
6077 				       targ_res);
6078 }
6079 
6080 static int
6081 bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
6082 {
6083 	const struct btf_ext_info_sec *sec;
6084 	struct bpf_core_relo_res targ_res;
6085 	const struct bpf_core_relo *rec;
6086 	const struct btf_ext_info *seg;
6087 	struct hashmap_entry *entry;
6088 	struct hashmap *cand_cache = NULL;
6089 	struct bpf_program *prog;
6090 	struct bpf_insn *insn;
6091 	const char *sec_name;
6092 	int i, err = 0, insn_idx, sec_idx, sec_num;
6093 
6094 	if (obj->btf_ext->core_relo_info.len == 0)
6095 		return 0;
6096 
6097 	if (targ_btf_path) {
6098 		obj->btf_vmlinux_override = btf__parse(targ_btf_path, NULL);
6099 		err = libbpf_get_error(obj->btf_vmlinux_override);
6100 		if (err) {
6101 			pr_warn("failed to parse target BTF: %s\n", errstr(err));
6102 			return err;
6103 		}
6104 	}
6105 
6106 	cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
6107 	if (IS_ERR(cand_cache)) {
6108 		err = PTR_ERR(cand_cache);
6109 		goto out;
6110 	}
6111 
6112 	seg = &obj->btf_ext->core_relo_info;
6113 	sec_num = 0;
6114 	for_each_btf_ext_sec(seg, sec) {
6115 		sec_idx = seg->sec_idxs[sec_num];
6116 		sec_num++;
6117 
6118 		sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
6119 		if (str_is_empty(sec_name)) {
6120 			err = -EINVAL;
6121 			goto out;
6122 		}
6123 
6124 		pr_debug("sec '%s': found %d CO-RE relocations\n", sec_name, sec->num_info);
6125 
6126 		for_each_btf_ext_rec(seg, sec, i, rec) {
6127 			if (rec->insn_off % BPF_INSN_SZ)
6128 				return -EINVAL;
6129 			insn_idx = rec->insn_off / BPF_INSN_SZ;
6130 			prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
6131 			if (!prog) {
6132 				/* When __weak subprog is "overridden" by another instance
6133 				 * of the subprog from a different object file, linker still
6134 				 * appends all the .BTF.ext info that used to belong to that
6135 				 * eliminated subprogram.
6136 				 * This is similar to what x86-64 linker does for relocations.
6137 				 * So just ignore such relocations just like we ignore
6138 				 * subprog instructions when discovering subprograms.
6139 				 */
6140 				pr_debug("sec '%s': skipping CO-RE relocation #%d for insn #%d belonging to eliminated weak subprogram\n",
6141 					 sec_name, i, insn_idx);
6142 				continue;
6143 			}
6144 			/* no need to apply CO-RE relocation if the program is
6145 			 * not going to be loaded
6146 			 */
6147 			if (!prog->autoload)
6148 				continue;
6149 
6150 			/* adjust insn_idx from section frame of reference to the local
6151 			 * program's frame of reference; (sub-)program code is not yet
6152 			 * relocated, so it's enough to just subtract in-section offset
6153 			 */
6154 			insn_idx = insn_idx - prog->sec_insn_off;
6155 			if (insn_idx >= prog->insns_cnt)
6156 				return -EINVAL;
6157 			insn = &prog->insns[insn_idx];
6158 
6159 			err = record_relo_core(prog, rec, insn_idx);
6160 			if (err) {
6161 				pr_warn("prog '%s': relo #%d: failed to record relocation: %s\n",
6162 					prog->name, i, errstr(err));
6163 				goto out;
6164 			}
6165 
6166 			if (prog->obj->gen_loader)
6167 				continue;
6168 
6169 			err = bpf_core_resolve_relo(prog, rec, i, obj->btf, cand_cache, &targ_res);
6170 			if (err) {
6171 				pr_warn("prog '%s': relo #%d: failed to relocate: %s\n",
6172 					prog->name, i, errstr(err));
6173 				goto out;
6174 			}
6175 
6176 			err = bpf_core_patch_insn(prog->name, insn, insn_idx, rec, i, &targ_res);
6177 			if (err) {
6178 				pr_warn("prog '%s': relo #%d: failed to patch insn #%u: %s\n",
6179 					prog->name, i, insn_idx, errstr(err));
6180 				goto out;
6181 			}
6182 		}
6183 	}
6184 
6185 out:
6186 	/* obj->btf_vmlinux and module BTFs are freed after object load */
6187 	btf__free(obj->btf_vmlinux_override);
6188 	obj->btf_vmlinux_override = NULL;
6189 
6190 	if (!IS_ERR_OR_NULL(cand_cache)) {
6191 		hashmap__for_each_entry(cand_cache, entry, i) {
6192 			bpf_core_free_cands(entry->pvalue);
6193 		}
6194 		hashmap__free(cand_cache);
6195 	}
6196 	return err;
6197 }
6198 
6199 /* base map load ldimm64 special constant, used also for log fixup logic */
6200 #define POISON_LDIMM64_MAP_BASE 2001000000
6201 #define POISON_LDIMM64_MAP_PFX "200100"
6202 
6203 static void poison_map_ldimm64(struct bpf_program *prog, int relo_idx,
6204 			       int insn_idx, struct bpf_insn *insn,
6205 			       int map_idx, const struct bpf_map *map)
6206 {
6207 	int i;
6208 
6209 	pr_debug("prog '%s': relo #%d: poisoning insn #%d that loads map #%d '%s'\n",
6210 		 prog->name, relo_idx, insn_idx, map_idx, map->name);
6211 
6212 	/* we turn single ldimm64 into two identical invalid calls */
6213 	for (i = 0; i < 2; i++) {
6214 		insn->code = BPF_JMP | BPF_CALL;
6215 		insn->dst_reg = 0;
6216 		insn->src_reg = 0;
6217 		insn->off = 0;
6218 		/* if this instruction is reachable (not a dead code),
6219 		 * verifier will complain with something like:
6220 		 * invalid func unknown#2001000123
6221 		 * where lower 123 is map index into obj->maps[] array
6222 		 */
6223 		insn->imm = POISON_LDIMM64_MAP_BASE + map_idx;
6224 
6225 		insn++;
6226 	}
6227 }
6228 
6229 /* unresolved kfunc call special constant, used also for log fixup logic */
6230 #define POISON_CALL_KFUNC_BASE 2002000000
6231 #define POISON_CALL_KFUNC_PFX "2002"
6232 
6233 static void poison_kfunc_call(struct bpf_program *prog, int relo_idx,
6234 			      int insn_idx, struct bpf_insn *insn,
6235 			      int ext_idx, const struct extern_desc *ext)
6236 {
6237 	pr_debug("prog '%s': relo #%d: poisoning insn #%d that calls kfunc '%s'\n",
6238 		 prog->name, relo_idx, insn_idx, ext->name);
6239 
6240 	/* we turn kfunc call into invalid helper call with identifiable constant */
6241 	insn->code = BPF_JMP | BPF_CALL;
6242 	insn->dst_reg = 0;
6243 	insn->src_reg = 0;
6244 	insn->off = 0;
6245 	/* if this instruction is reachable (not a dead code),
6246 	 * verifier will complain with something like:
6247 	 * invalid func unknown#2001000123
6248 	 * where lower 123 is extern index into obj->externs[] array
6249 	 */
6250 	insn->imm = POISON_CALL_KFUNC_BASE + ext_idx;
6251 }
6252 
6253 static int find_jt_map(struct bpf_object *obj, struct bpf_program *prog, unsigned int sym_off)
6254 {
6255 	size_t i;
6256 
6257 	for (i = 0; i < obj->jumptable_map_cnt; i++) {
6258 		/*
6259 		 * This might happen that same offset is used for two different
6260 		 * programs (as jump tables can be the same). However, for
6261 		 * different programs different maps should be created.
6262 		 */
6263 		if (obj->jumptable_maps[i].sym_off == sym_off &&
6264 		    obj->jumptable_maps[i].prog == prog)
6265 			return obj->jumptable_maps[i].fd;
6266 	}
6267 
6268 	return -ENOENT;
6269 }
6270 
6271 static int add_jt_map(struct bpf_object *obj, struct bpf_program *prog, unsigned int sym_off, int map_fd)
6272 {
6273 	size_t cnt = obj->jumptable_map_cnt;
6274 	size_t size = sizeof(obj->jumptable_maps[0]);
6275 	void *tmp;
6276 
6277 	tmp = libbpf_reallocarray(obj->jumptable_maps, cnt + 1, size);
6278 	if (!tmp)
6279 		return -ENOMEM;
6280 
6281 	obj->jumptable_maps = tmp;
6282 	obj->jumptable_maps[cnt].prog = prog;
6283 	obj->jumptable_maps[cnt].sym_off = sym_off;
6284 	obj->jumptable_maps[cnt].fd = map_fd;
6285 	obj->jumptable_map_cnt++;
6286 
6287 	return 0;
6288 }
6289 
6290 static int find_subprog_idx(struct bpf_program *prog, int insn_idx)
6291 {
6292 	int i;
6293 
6294 	for (i = prog->subprog_cnt - 1; i >= 0; i--) {
6295 		if (insn_idx >= prog->subprogs[i].sub_insn_off)
6296 			return i;
6297 	}
6298 
6299 	return -1;
6300 }
6301 
6302 static int create_jt_map(struct bpf_object *obj, struct bpf_program *prog, struct reloc_desc *relo)
6303 {
6304 	const __u32 jt_entry_size = 8;
6305 	unsigned int sym_off = relo->sym_off;
6306 	int jt_size = relo->sym_size;
6307 	__u32 max_entries = jt_size / jt_entry_size;
6308 	__u32 value_size = sizeof(struct bpf_insn_array_value);
6309 	struct bpf_insn_array_value val = {};
6310 	int subprog_idx;
6311 	int map_fd, err;
6312 	__u64 insn_off;
6313 	__u64 *jt;
6314 	__u32 i;
6315 
6316 	map_fd = find_jt_map(obj, prog, sym_off);
6317 	if (map_fd >= 0)
6318 		return map_fd;
6319 
6320 	if (sym_off % jt_entry_size) {
6321 		pr_warn("map '.jumptables': jumptable start %u should be multiple of %u\n",
6322 			sym_off, jt_entry_size);
6323 		return -EINVAL;
6324 	}
6325 
6326 	if (jt_size % jt_entry_size) {
6327 		pr_warn("map '.jumptables': jumptable size %d should be multiple of %u\n",
6328 			jt_size, jt_entry_size);
6329 		return -EINVAL;
6330 	}
6331 
6332 	map_fd = bpf_map_create(BPF_MAP_TYPE_INSN_ARRAY, ".jumptables",
6333 				4, value_size, max_entries, NULL);
6334 	if (map_fd < 0)
6335 		return map_fd;
6336 
6337 	if (!obj->jumptables_data) {
6338 		pr_warn("map '.jumptables': ELF file is missing jump table data\n");
6339 		err = -EINVAL;
6340 		goto err_close;
6341 	}
6342 	if (sym_off + jt_size > obj->jumptables_data_sz) {
6343 		pr_warn("map '.jumptables': jumptables_data size is %zd, trying to access %d\n",
6344 			obj->jumptables_data_sz, sym_off + jt_size);
6345 		err = -EINVAL;
6346 		goto err_close;
6347 	}
6348 
6349 	subprog_idx = -1; /* main program */
6350 	if (relo->insn_idx < 0 || relo->insn_idx >= prog->insns_cnt) {
6351 		pr_warn("map '.jumptables': invalid instruction index %d\n", relo->insn_idx);
6352 		err = -EINVAL;
6353 		goto err_close;
6354 	}
6355 	if (prog->subprogs)
6356 		subprog_idx = find_subprog_idx(prog, relo->insn_idx);
6357 
6358 	jt = (__u64 *)(obj->jumptables_data + sym_off);
6359 	for (i = 0; i < max_entries; i++) {
6360 		/*
6361 		 * The offset should be made to be relative to the beginning of
6362 		 * the main function, not the subfunction.
6363 		 */
6364 		insn_off = jt[i]/sizeof(struct bpf_insn);
6365 		if (subprog_idx >= 0) {
6366 			insn_off -= prog->subprogs[subprog_idx].sec_insn_off;
6367 			insn_off += prog->subprogs[subprog_idx].sub_insn_off;
6368 		} else {
6369 			insn_off -= prog->sec_insn_off;
6370 		}
6371 
6372 		/*
6373 		 * LLVM-generated jump tables contain u64 records, however
6374 		 * should contain values that fit in u32.
6375 		 */
6376 		if (insn_off > UINT32_MAX) {
6377 			pr_warn("map '.jumptables': invalid jump table value 0x%llx at offset %u\n",
6378 				(long long)jt[i], sym_off + i * jt_entry_size);
6379 			err = -EINVAL;
6380 			goto err_close;
6381 		}
6382 
6383 		val.orig_off = insn_off;
6384 		err = bpf_map_update_elem(map_fd, &i, &val, 0);
6385 		if (err)
6386 			goto err_close;
6387 	}
6388 
6389 	err = bpf_map_freeze(map_fd);
6390 	if (err)
6391 		goto err_close;
6392 
6393 	err = add_jt_map(obj, prog, sym_off, map_fd);
6394 	if (err)
6395 		goto err_close;
6396 
6397 	return map_fd;
6398 
6399 err_close:
6400 	close(map_fd);
6401 	return err;
6402 }
6403 
6404 /* Relocate data references within program code:
6405  *  - map references;
6406  *  - global variable references;
6407  *  - extern references.
6408  */
6409 static int
6410 bpf_object__relocate_data(struct bpf_object *obj, struct bpf_program *prog)
6411 {
6412 	int i;
6413 
6414 	for (i = 0; i < prog->nr_reloc; i++) {
6415 		struct reloc_desc *relo = &prog->reloc_desc[i];
6416 		struct bpf_insn *insn = &prog->insns[relo->insn_idx];
6417 		const struct bpf_map *map;
6418 		struct extern_desc *ext;
6419 
6420 		switch (relo->type) {
6421 		case RELO_LD64:
6422 			map = &obj->maps[relo->map_idx];
6423 			if (obj->gen_loader) {
6424 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX;
6425 				insn[0].imm = relo->map_idx;
6426 			} else if (map->autocreate) {
6427 				insn[0].src_reg = BPF_PSEUDO_MAP_FD;
6428 				insn[0].imm = map->fd;
6429 			} else {
6430 				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
6431 						   relo->map_idx, map);
6432 			}
6433 			break;
6434 		case RELO_DATA:
6435 			map = &obj->maps[relo->map_idx];
6436 			insn[1].imm = insn[0].imm + relo->sym_off;
6437 
6438 			if (relo->map_idx == obj->arena_map_idx)
6439 				insn[1].imm += obj->arena_data_off;
6440 
6441 			if (obj->gen_loader) {
6442 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
6443 				insn[0].imm = relo->map_idx;
6444 			} else if (map->autocreate) {
6445 				insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6446 				insn[0].imm = map->fd;
6447 			} else {
6448 				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
6449 						   relo->map_idx, map);
6450 			}
6451 			break;
6452 		case RELO_EXTERN_LD64:
6453 			ext = &obj->externs[relo->ext_idx];
6454 			if (ext->type == EXT_KCFG) {
6455 				if (obj->gen_loader) {
6456 					insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
6457 					insn[0].imm = obj->kconfig_map_idx;
6458 				} else {
6459 					insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6460 					insn[0].imm = obj->maps[obj->kconfig_map_idx].fd;
6461 				}
6462 				insn[1].imm = ext->kcfg.data_off;
6463 			} else /* EXT_KSYM */ {
6464 				if (ext->ksym.type_id && ext->is_set) { /* typed ksyms */
6465 					insn[0].src_reg = BPF_PSEUDO_BTF_ID;
6466 					insn[0].imm = ext->ksym.kernel_btf_id;
6467 					insn[1].imm = ext->ksym.kernel_btf_obj_fd;
6468 				} else { /* typeless ksyms or unresolved typed ksyms */
6469 					insn[0].imm = (__u32)ext->ksym.addr;
6470 					insn[1].imm = ext->ksym.addr >> 32;
6471 				}
6472 			}
6473 			break;
6474 		case RELO_EXTERN_CALL:
6475 			ext = &obj->externs[relo->ext_idx];
6476 			insn[0].src_reg = BPF_PSEUDO_KFUNC_CALL;
6477 			if (ext->is_set) {
6478 				insn[0].imm = ext->ksym.kernel_btf_id;
6479 				insn[0].off = ext->ksym.btf_fd_idx;
6480 			} else { /* unresolved weak kfunc call */
6481 				poison_kfunc_call(prog, i, relo->insn_idx, insn,
6482 						  relo->ext_idx, ext);
6483 			}
6484 			break;
6485 		case RELO_SUBPROG_ADDR:
6486 			if (insn[0].src_reg != BPF_PSEUDO_FUNC) {
6487 				pr_warn("prog '%s': relo #%d: bad insn\n",
6488 					prog->name, i);
6489 				return -EINVAL;
6490 			}
6491 			/* handled already */
6492 			break;
6493 		case RELO_CALL:
6494 			/* handled already */
6495 			break;
6496 		case RELO_CORE:
6497 			/* will be handled by bpf_program_record_relos() */
6498 			break;
6499 		case RELO_INSN_ARRAY: {
6500 			int map_fd;
6501 
6502 			map_fd = create_jt_map(obj, prog, relo);
6503 			if (map_fd < 0) {
6504 				pr_warn("prog '%s': relo #%d: can't create jump table: sym_off %u\n",
6505 					prog->name, i, relo->sym_off);
6506 				return map_fd;
6507 			}
6508 			insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6509 			insn->imm = map_fd;
6510 			insn->off = 0;
6511 		}
6512 			break;
6513 		default:
6514 			pr_warn("prog '%s': relo #%d: bad relo type %d\n",
6515 				prog->name, i, relo->type);
6516 			return -EINVAL;
6517 		}
6518 	}
6519 
6520 	return 0;
6521 }
6522 
6523 static int adjust_prog_btf_ext_info(const struct bpf_object *obj,
6524 				    const struct bpf_program *prog,
6525 				    const struct btf_ext_info *ext_info,
6526 				    void **prog_info, __u32 *prog_rec_cnt,
6527 				    __u32 *prog_rec_sz)
6528 {
6529 	void *copy_start = NULL, *copy_end = NULL;
6530 	void *rec, *rec_end, *new_prog_info;
6531 	const struct btf_ext_info_sec *sec;
6532 	size_t old_sz, new_sz;
6533 	int i, sec_num, sec_idx, off_adj;
6534 
6535 	sec_num = 0;
6536 	for_each_btf_ext_sec(ext_info, sec) {
6537 		sec_idx = ext_info->sec_idxs[sec_num];
6538 		sec_num++;
6539 		if (prog->sec_idx != sec_idx)
6540 			continue;
6541 
6542 		for_each_btf_ext_rec(ext_info, sec, i, rec) {
6543 			__u32 insn_off = *(__u32 *)rec / BPF_INSN_SZ;
6544 
6545 			if (insn_off < prog->sec_insn_off)
6546 				continue;
6547 			if (insn_off >= prog->sec_insn_off + prog->sec_insn_cnt)
6548 				break;
6549 
6550 			if (!copy_start)
6551 				copy_start = rec;
6552 			copy_end = rec + ext_info->rec_size;
6553 		}
6554 
6555 		if (!copy_start)
6556 			return -ENOENT;
6557 
6558 		/* append func/line info of a given (sub-)program to the main
6559 		 * program func/line info
6560 		 */
6561 		old_sz = (size_t)(*prog_rec_cnt) * ext_info->rec_size;
6562 		new_sz = old_sz + (copy_end - copy_start);
6563 		new_prog_info = realloc(*prog_info, new_sz);
6564 		if (!new_prog_info)
6565 			return -ENOMEM;
6566 		*prog_info = new_prog_info;
6567 		*prog_rec_cnt = new_sz / ext_info->rec_size;
6568 		memcpy(new_prog_info + old_sz, copy_start, copy_end - copy_start);
6569 
6570 		/* Kernel instruction offsets are in units of 8-byte
6571 		 * instructions, while .BTF.ext instruction offsets generated
6572 		 * by Clang are in units of bytes. So convert Clang offsets
6573 		 * into kernel offsets and adjust offset according to program
6574 		 * relocated position.
6575 		 */
6576 		off_adj = prog->sub_insn_off - prog->sec_insn_off;
6577 		rec = new_prog_info + old_sz;
6578 		rec_end = new_prog_info + new_sz;
6579 		for (; rec < rec_end; rec += ext_info->rec_size) {
6580 			__u32 *insn_off = rec;
6581 
6582 			*insn_off = *insn_off / BPF_INSN_SZ + off_adj;
6583 		}
6584 		*prog_rec_sz = ext_info->rec_size;
6585 		return 0;
6586 	}
6587 
6588 	return -ENOENT;
6589 }
6590 
6591 static int
6592 reloc_prog_func_and_line_info(const struct bpf_object *obj,
6593 			      struct bpf_program *main_prog,
6594 			      const struct bpf_program *prog)
6595 {
6596 	int err;
6597 
6598 	/* no .BTF.ext relocation if .BTF.ext is missing or kernel doesn't
6599 	 * support func/line info
6600 	 */
6601 	if (!obj->btf_ext || !kernel_supports(obj, FEAT_BTF_FUNC))
6602 		return 0;
6603 
6604 	/* only attempt func info relocation if main program's func_info
6605 	 * relocation was successful
6606 	 */
6607 	if (main_prog != prog && !main_prog->func_info)
6608 		goto line_info;
6609 
6610 	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->func_info,
6611 				       &main_prog->func_info,
6612 				       &main_prog->func_info_cnt,
6613 				       &main_prog->func_info_rec_size);
6614 	if (err) {
6615 		if (err != -ENOENT) {
6616 			pr_warn("prog '%s': error relocating .BTF.ext function info: %s\n",
6617 				prog->name, errstr(err));
6618 			return err;
6619 		}
6620 		if (main_prog->func_info) {
6621 			/*
6622 			 * Some info has already been found but has problem
6623 			 * in the last btf_ext reloc. Must have to error out.
6624 			 */
6625 			pr_warn("prog '%s': missing .BTF.ext function info.\n", prog->name);
6626 			return err;
6627 		}
6628 		/* Have problem loading the very first info. Ignore the rest. */
6629 		pr_warn("prog '%s': missing .BTF.ext function info for the main program, skipping all of .BTF.ext func info.\n",
6630 			prog->name);
6631 	}
6632 
6633 line_info:
6634 	/* don't relocate line info if main program's relocation failed */
6635 	if (main_prog != prog && !main_prog->line_info)
6636 		return 0;
6637 
6638 	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->line_info,
6639 				       &main_prog->line_info,
6640 				       &main_prog->line_info_cnt,
6641 				       &main_prog->line_info_rec_size);
6642 	if (err) {
6643 		if (err != -ENOENT) {
6644 			pr_warn("prog '%s': error relocating .BTF.ext line info: %s\n",
6645 				prog->name, errstr(err));
6646 			return err;
6647 		}
6648 		if (main_prog->line_info) {
6649 			/*
6650 			 * Some info has already been found but has problem
6651 			 * in the last btf_ext reloc. Must have to error out.
6652 			 */
6653 			pr_warn("prog '%s': missing .BTF.ext line info.\n", prog->name);
6654 			return err;
6655 		}
6656 		/* Have problem loading the very first info. Ignore the rest. */
6657 		pr_warn("prog '%s': missing .BTF.ext line info for the main program, skipping all of .BTF.ext line info.\n",
6658 			prog->name);
6659 	}
6660 	return 0;
6661 }
6662 
6663 static int cmp_relo_by_insn_idx(const void *key, const void *elem)
6664 {
6665 	size_t insn_idx = *(const size_t *)key;
6666 	const struct reloc_desc *relo = elem;
6667 
6668 	if (insn_idx == relo->insn_idx)
6669 		return 0;
6670 	return insn_idx < relo->insn_idx ? -1 : 1;
6671 }
6672 
6673 static struct reloc_desc *find_prog_insn_relo(const struct bpf_program *prog, size_t insn_idx)
6674 {
6675 	if (!prog->nr_reloc)
6676 		return NULL;
6677 	return bsearch(&insn_idx, prog->reloc_desc, prog->nr_reloc,
6678 		       sizeof(*prog->reloc_desc), cmp_relo_by_insn_idx);
6679 }
6680 
6681 static int append_subprog_relos(struct bpf_program *main_prog, struct bpf_program *subprog)
6682 {
6683 	int new_cnt = main_prog->nr_reloc + subprog->nr_reloc;
6684 	struct reloc_desc *relos;
6685 	int i;
6686 
6687 	if (main_prog == subprog)
6688 		return 0;
6689 	relos = libbpf_reallocarray(main_prog->reloc_desc, new_cnt, sizeof(*relos));
6690 	/* if new count is zero, reallocarray can return a valid NULL result;
6691 	 * in this case the previous pointer will be freed, so we *have to*
6692 	 * reassign old pointer to the new value (even if it's NULL)
6693 	 */
6694 	if (!relos && new_cnt)
6695 		return -ENOMEM;
6696 	if (subprog->nr_reloc)
6697 		memcpy(relos + main_prog->nr_reloc, subprog->reloc_desc,
6698 		       sizeof(*relos) * subprog->nr_reloc);
6699 
6700 	for (i = main_prog->nr_reloc; i < new_cnt; i++)
6701 		relos[i].insn_idx += subprog->sub_insn_off;
6702 	/* After insn_idx adjustment the 'relos' array is still sorted
6703 	 * by insn_idx and doesn't break bsearch.
6704 	 */
6705 	main_prog->reloc_desc = relos;
6706 	main_prog->nr_reloc = new_cnt;
6707 	return 0;
6708 }
6709 
6710 static int save_subprog_offsets(struct bpf_program *main_prog, struct bpf_program *subprog)
6711 {
6712 	size_t size = sizeof(main_prog->subprogs[0]);
6713 	int cnt = main_prog->subprog_cnt;
6714 	void *tmp;
6715 
6716 	tmp = libbpf_reallocarray(main_prog->subprogs, cnt + 1, size);
6717 	if (!tmp)
6718 		return -ENOMEM;
6719 
6720 	main_prog->subprogs = tmp;
6721 	main_prog->subprogs[cnt].sec_insn_off = subprog->sec_insn_off;
6722 	main_prog->subprogs[cnt].sub_insn_off = subprog->sub_insn_off;
6723 	main_prog->subprog_cnt++;
6724 
6725 	return 0;
6726 }
6727 
6728 static int
6729 bpf_object__append_subprog_code(struct bpf_object *obj, struct bpf_program *main_prog,
6730 				struct bpf_program *subprog)
6731 {
6732 	struct bpf_insn *insns;
6733 	size_t new_cnt;
6734 	int err;
6735 
6736 	subprog->sub_insn_off = main_prog->insns_cnt;
6737 
6738 	new_cnt = main_prog->insns_cnt + subprog->insns_cnt;
6739 	insns = libbpf_reallocarray(main_prog->insns, new_cnt, sizeof(*insns));
6740 	if (!insns) {
6741 		pr_warn("prog '%s': failed to realloc prog code\n", main_prog->name);
6742 		return -ENOMEM;
6743 	}
6744 	main_prog->insns = insns;
6745 	main_prog->insns_cnt = new_cnt;
6746 
6747 	memcpy(main_prog->insns + subprog->sub_insn_off, subprog->insns,
6748 	       subprog->insns_cnt * sizeof(*insns));
6749 
6750 	pr_debug("prog '%s': added %zu insns from sub-prog '%s'\n",
6751 		 main_prog->name, subprog->insns_cnt, subprog->name);
6752 
6753 	/* The subprog insns are now appended. Append its relos too. */
6754 	err = append_subprog_relos(main_prog, subprog);
6755 	if (err)
6756 		return err;
6757 
6758 	err = save_subprog_offsets(main_prog, subprog);
6759 	if (err) {
6760 		pr_warn("prog '%s': failed to add subprog offsets: %s\n",
6761 			main_prog->name, errstr(err));
6762 		return err;
6763 	}
6764 
6765 	return 0;
6766 }
6767 
6768 static int
6769 bpf_object__reloc_code(struct bpf_object *obj, struct bpf_program *main_prog,
6770 		       struct bpf_program *prog)
6771 {
6772 	size_t sub_insn_idx, insn_idx;
6773 	struct bpf_program *subprog;
6774 	struct reloc_desc *relo;
6775 	struct bpf_insn *insn;
6776 	int err;
6777 
6778 	err = reloc_prog_func_and_line_info(obj, main_prog, prog);
6779 	if (err)
6780 		return err;
6781 
6782 	for (insn_idx = 0; insn_idx < prog->sec_insn_cnt; insn_idx++) {
6783 		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6784 		if (!insn_is_subprog_call(insn) && !insn_is_pseudo_func(insn))
6785 			continue;
6786 
6787 		relo = find_prog_insn_relo(prog, insn_idx);
6788 		if (relo && relo->type == RELO_EXTERN_CALL)
6789 			/* kfunc relocations will be handled later
6790 			 * in bpf_object__relocate_data()
6791 			 */
6792 			continue;
6793 		if (relo && relo->type != RELO_CALL && relo->type != RELO_SUBPROG_ADDR) {
6794 			pr_warn("prog '%s': unexpected relo for insn #%zu, type %d\n",
6795 				prog->name, insn_idx, relo->type);
6796 			return -LIBBPF_ERRNO__RELOC;
6797 		}
6798 		if (relo) {
6799 			/* sub-program instruction index is a combination of
6800 			 * an offset of a symbol pointed to by relocation and
6801 			 * call instruction's imm field; for global functions,
6802 			 * call always has imm = -1, but for static functions
6803 			 * relocation is against STT_SECTION and insn->imm
6804 			 * points to a start of a static function
6805 			 *
6806 			 * for subprog addr relocation, the relo->sym_off + insn->imm is
6807 			 * the byte offset in the corresponding section.
6808 			 */
6809 			if (relo->type == RELO_CALL)
6810 				sub_insn_idx = relo->sym_off / BPF_INSN_SZ + insn->imm + 1;
6811 			else
6812 				sub_insn_idx = (relo->sym_off + insn->imm) / BPF_INSN_SZ;
6813 		} else if (insn_is_pseudo_func(insn)) {
6814 			/*
6815 			 * RELO_SUBPROG_ADDR relo is always emitted even if both
6816 			 * functions are in the same section, so it shouldn't reach here.
6817 			 */
6818 			pr_warn("prog '%s': missing subprog addr relo for insn #%zu\n",
6819 				prog->name, insn_idx);
6820 			return -LIBBPF_ERRNO__RELOC;
6821 		} else {
6822 			/* if subprogram call is to a static function within
6823 			 * the same ELF section, there won't be any relocation
6824 			 * emitted, but it also means there is no additional
6825 			 * offset necessary, insns->imm is relative to
6826 			 * instruction's original position within the section
6827 			 */
6828 			sub_insn_idx = prog->sec_insn_off + insn_idx + insn->imm + 1;
6829 		}
6830 
6831 		/* we enforce that sub-programs should be in .text section */
6832 		subprog = find_prog_by_sec_insn(obj, obj->efile.text_shndx, sub_insn_idx);
6833 		if (!subprog) {
6834 			pr_warn("prog '%s': no .text section found yet sub-program call exists\n",
6835 				prog->name);
6836 			return -LIBBPF_ERRNO__RELOC;
6837 		}
6838 
6839 		/* if it's the first call instruction calling into this
6840 		 * subprogram (meaning this subprog hasn't been processed
6841 		 * yet) within the context of current main program:
6842 		 *   - append it at the end of main program's instructions blog;
6843 		 *   - process is recursively, while current program is put on hold;
6844 		 *   - if that subprogram calls some other not yet processes
6845 		 *   subprogram, same thing will happen recursively until
6846 		 *   there are no more unprocesses subprograms left to append
6847 		 *   and relocate.
6848 		 */
6849 		if (subprog->sub_insn_off == 0) {
6850 			err = bpf_object__append_subprog_code(obj, main_prog, subprog);
6851 			if (err)
6852 				return err;
6853 			err = bpf_object__reloc_code(obj, main_prog, subprog);
6854 			if (err)
6855 				return err;
6856 		}
6857 
6858 		/* main_prog->insns memory could have been re-allocated, so
6859 		 * calculate pointer again
6860 		 */
6861 		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6862 		/* calculate correct instruction position within current main
6863 		 * prog; each main prog can have a different set of
6864 		 * subprograms appended (potentially in different order as
6865 		 * well), so position of any subprog can be different for
6866 		 * different main programs
6867 		 */
6868 		insn->imm = subprog->sub_insn_off - (prog->sub_insn_off + insn_idx) - 1;
6869 
6870 		pr_debug("prog '%s': insn #%zu relocated, imm %d points to subprog '%s' (now at %zu offset)\n",
6871 			 prog->name, insn_idx, insn->imm, subprog->name, subprog->sub_insn_off);
6872 	}
6873 
6874 	return 0;
6875 }
6876 
6877 /*
6878  * Relocate sub-program calls.
6879  *
6880  * Algorithm operates as follows. Each entry-point BPF program (referred to as
6881  * main prog) is processed separately. For each subprog (non-entry functions,
6882  * that can be called from either entry progs or other subprogs) gets their
6883  * sub_insn_off reset to zero. This serves as indicator that this subprogram
6884  * hasn't been yet appended and relocated within current main prog. Once its
6885  * relocated, sub_insn_off will point at the position within current main prog
6886  * where given subprog was appended. This will further be used to relocate all
6887  * the call instructions jumping into this subprog.
6888  *
6889  * We start with main program and process all call instructions. If the call
6890  * is into a subprog that hasn't been processed (i.e., subprog->sub_insn_off
6891  * is zero), subprog instructions are appended at the end of main program's
6892  * instruction array. Then main program is "put on hold" while we recursively
6893  * process newly appended subprogram. If that subprogram calls into another
6894  * subprogram that hasn't been appended, new subprogram is appended again to
6895  * the *main* prog's instructions (subprog's instructions are always left
6896  * untouched, as they need to be in unmodified state for subsequent main progs
6897  * and subprog instructions are always sent only as part of a main prog) and
6898  * the process continues recursively. Once all the subprogs called from a main
6899  * prog or any of its subprogs are appended (and relocated), all their
6900  * positions within finalized instructions array are known, so it's easy to
6901  * rewrite call instructions with correct relative offsets, corresponding to
6902  * desired target subprog.
6903  *
6904  * Its important to realize that some subprogs might not be called from some
6905  * main prog and any of its called/used subprogs. Those will keep their
6906  * subprog->sub_insn_off as zero at all times and won't be appended to current
6907  * main prog and won't be relocated within the context of current main prog.
6908  * They might still be used from other main progs later.
6909  *
6910  * Visually this process can be shown as below. Suppose we have two main
6911  * programs mainA and mainB and BPF object contains three subprogs: subA,
6912  * subB, and subC. mainA calls only subA, mainB calls only subC, but subA and
6913  * subC both call subB:
6914  *
6915  *        +--------+ +-------+
6916  *        |        v v       |
6917  *     +--+---+ +--+-+-+ +---+--+
6918  *     | subA | | subB | | subC |
6919  *     +--+---+ +------+ +---+--+
6920  *        ^                  ^
6921  *        |                  |
6922  *    +---+-------+   +------+----+
6923  *    |   mainA   |   |   mainB   |
6924  *    +-----------+   +-----------+
6925  *
6926  * We'll start relocating mainA, will find subA, append it and start
6927  * processing sub A recursively:
6928  *
6929  *    +-----------+------+
6930  *    |   mainA   | subA |
6931  *    +-----------+------+
6932  *
6933  * At this point we notice that subB is used from subA, so we append it and
6934  * relocate (there are no further subcalls from subB):
6935  *
6936  *    +-----------+------+------+
6937  *    |   mainA   | subA | subB |
6938  *    +-----------+------+------+
6939  *
6940  * At this point, we relocate subA calls, then go one level up and finish with
6941  * relocatin mainA calls. mainA is done.
6942  *
6943  * For mainB process is similar but results in different order. We start with
6944  * mainB and skip subA and subB, as mainB never calls them (at least
6945  * directly), but we see subC is needed, so we append and start processing it:
6946  *
6947  *    +-----------+------+
6948  *    |   mainB   | subC |
6949  *    +-----------+------+
6950  * Now we see subC needs subB, so we go back to it, append and relocate it:
6951  *
6952  *    +-----------+------+------+
6953  *    |   mainB   | subC | subB |
6954  *    +-----------+------+------+
6955  *
6956  * At this point we unwind recursion, relocate calls in subC, then in mainB.
6957  */
6958 static int
6959 bpf_object__relocate_calls(struct bpf_object *obj, struct bpf_program *prog)
6960 {
6961 	struct bpf_program *subprog;
6962 	int i, err;
6963 
6964 	/* mark all subprogs as not relocated (yet) within the context of
6965 	 * current main program
6966 	 */
6967 	for (i = 0; i < obj->nr_programs; i++) {
6968 		subprog = &obj->programs[i];
6969 		if (!prog_is_subprog(obj, subprog))
6970 			continue;
6971 
6972 		subprog->sub_insn_off = 0;
6973 	}
6974 
6975 	err = bpf_object__reloc_code(obj, prog, prog);
6976 	if (err)
6977 		return err;
6978 
6979 	return 0;
6980 }
6981 
6982 static void
6983 bpf_object__free_relocs(struct bpf_object *obj)
6984 {
6985 	struct bpf_program *prog;
6986 	int i;
6987 
6988 	/* free up relocation descriptors */
6989 	for (i = 0; i < obj->nr_programs; i++) {
6990 		prog = &obj->programs[i];
6991 		zfree(&prog->reloc_desc);
6992 		prog->nr_reloc = 0;
6993 	}
6994 }
6995 
6996 static int cmp_relocs(const void *_a, const void *_b)
6997 {
6998 	const struct reloc_desc *a = _a;
6999 	const struct reloc_desc *b = _b;
7000 
7001 	if (a->insn_idx != b->insn_idx)
7002 		return a->insn_idx < b->insn_idx ? -1 : 1;
7003 
7004 	/* no two relocations should have the same insn_idx, but ... */
7005 	if (a->type != b->type)
7006 		return a->type < b->type ? -1 : 1;
7007 
7008 	return 0;
7009 }
7010 
7011 static void bpf_object__sort_relos(struct bpf_object *obj)
7012 {
7013 	int i;
7014 
7015 	for (i = 0; i < obj->nr_programs; i++) {
7016 		struct bpf_program *p = &obj->programs[i];
7017 
7018 		if (!p->nr_reloc)
7019 			continue;
7020 
7021 		qsort(p->reloc_desc, p->nr_reloc, sizeof(*p->reloc_desc), cmp_relocs);
7022 	}
7023 }
7024 
7025 static int bpf_prog_assign_exc_cb(struct bpf_object *obj, struct bpf_program *prog)
7026 {
7027 	const char *str = "exception_callback:";
7028 	size_t pfx_len = strlen(str);
7029 	int i, j, n;
7030 
7031 	if (!obj->btf || !kernel_supports(obj, FEAT_BTF_DECL_TAG))
7032 		return 0;
7033 
7034 	n = btf__type_cnt(obj->btf);
7035 	for (i = 1; i < n; i++) {
7036 		const char *name;
7037 		struct btf_type *t;
7038 
7039 		t = btf_type_by_id(obj->btf, i);
7040 		if (!btf_is_decl_tag(t) || btf_decl_tag(t)->component_idx != -1)
7041 			continue;
7042 
7043 		name = btf__str_by_offset(obj->btf, t->name_off);
7044 		if (strncmp(name, str, pfx_len) != 0)
7045 			continue;
7046 
7047 		t = btf_type_by_id(obj->btf, t->type);
7048 		if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL) {
7049 			pr_warn("prog '%s': exception_callback:<value> decl tag not applied to the main program\n",
7050 				prog->name);
7051 			return -EINVAL;
7052 		}
7053 		if (strcmp(prog->name, btf__str_by_offset(obj->btf, t->name_off)) != 0)
7054 			continue;
7055 		/* Multiple callbacks are specified for the same prog,
7056 		 * the verifier will eventually return an error for this
7057 		 * case, hence simply skip appending a subprog.
7058 		 */
7059 		if (prog->exception_cb_idx >= 0) {
7060 			prog->exception_cb_idx = -1;
7061 			break;
7062 		}
7063 
7064 		name += pfx_len;
7065 		if (str_is_empty(name)) {
7066 			pr_warn("prog '%s': exception_callback:<value> decl tag contains empty value\n",
7067 				prog->name);
7068 			return -EINVAL;
7069 		}
7070 
7071 		for (j = 0; j < obj->nr_programs; j++) {
7072 			struct bpf_program *subprog = &obj->programs[j];
7073 
7074 			if (!prog_is_subprog(obj, subprog))
7075 				continue;
7076 			if (strcmp(name, subprog->name) != 0)
7077 				continue;
7078 			/* Enforce non-hidden, as from verifier point of
7079 			 * view it expects global functions, whereas the
7080 			 * mark_btf_static fixes up linkage as static.
7081 			 */
7082 			if (!subprog->sym_global || subprog->mark_btf_static) {
7083 				pr_warn("prog '%s': exception callback %s must be a global non-hidden function\n",
7084 					prog->name, subprog->name);
7085 				return -EINVAL;
7086 			}
7087 			/* Let's see if we already saw a static exception callback with the same name */
7088 			if (prog->exception_cb_idx >= 0) {
7089 				pr_warn("prog '%s': multiple subprogs with same name as exception callback '%s'\n",
7090 					prog->name, subprog->name);
7091 				return -EINVAL;
7092 			}
7093 			prog->exception_cb_idx = j;
7094 			break;
7095 		}
7096 
7097 		if (prog->exception_cb_idx >= 0)
7098 			continue;
7099 
7100 		pr_warn("prog '%s': cannot find exception callback '%s'\n", prog->name, name);
7101 		return -ENOENT;
7102 	}
7103 
7104 	return 0;
7105 }
7106 
7107 static struct {
7108 	enum bpf_prog_type prog_type;
7109 	const char *ctx_name;
7110 } global_ctx_map[] = {
7111 	{ BPF_PROG_TYPE_CGROUP_DEVICE,           "bpf_cgroup_dev_ctx" },
7112 	{ BPF_PROG_TYPE_CGROUP_SKB,              "__sk_buff" },
7113 	{ BPF_PROG_TYPE_CGROUP_SOCK,             "bpf_sock" },
7114 	{ BPF_PROG_TYPE_CGROUP_SOCK_ADDR,        "bpf_sock_addr" },
7115 	{ BPF_PROG_TYPE_CGROUP_SOCKOPT,          "bpf_sockopt" },
7116 	{ BPF_PROG_TYPE_CGROUP_SYSCTL,           "bpf_sysctl" },
7117 	{ BPF_PROG_TYPE_FLOW_DISSECTOR,          "__sk_buff" },
7118 	{ BPF_PROG_TYPE_KPROBE,                  "bpf_user_pt_regs_t" },
7119 	{ BPF_PROG_TYPE_LWT_IN,                  "__sk_buff" },
7120 	{ BPF_PROG_TYPE_LWT_OUT,                 "__sk_buff" },
7121 	{ BPF_PROG_TYPE_LWT_SEG6LOCAL,           "__sk_buff" },
7122 	{ BPF_PROG_TYPE_LWT_XMIT,                "__sk_buff" },
7123 	{ BPF_PROG_TYPE_NETFILTER,               "bpf_nf_ctx" },
7124 	{ BPF_PROG_TYPE_PERF_EVENT,              "bpf_perf_event_data" },
7125 	{ BPF_PROG_TYPE_RAW_TRACEPOINT,          "bpf_raw_tracepoint_args" },
7126 	{ BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE, "bpf_raw_tracepoint_args" },
7127 	{ BPF_PROG_TYPE_SCHED_ACT,               "__sk_buff" },
7128 	{ BPF_PROG_TYPE_SCHED_CLS,               "__sk_buff" },
7129 	{ BPF_PROG_TYPE_SK_LOOKUP,               "bpf_sk_lookup" },
7130 	{ BPF_PROG_TYPE_SK_MSG,                  "sk_msg_md" },
7131 	{ BPF_PROG_TYPE_SK_REUSEPORT,            "sk_reuseport_md" },
7132 	{ BPF_PROG_TYPE_SK_SKB,                  "__sk_buff" },
7133 	{ BPF_PROG_TYPE_SOCK_OPS,                "bpf_sock_ops" },
7134 	{ BPF_PROG_TYPE_SOCKET_FILTER,           "__sk_buff" },
7135 	{ BPF_PROG_TYPE_XDP,                     "xdp_md" },
7136 	/* all other program types don't have "named" context structs */
7137 };
7138 
7139 /* forward declarations for arch-specific underlying types of bpf_user_pt_regs_t typedef,
7140  * for below __builtin_types_compatible_p() checks;
7141  * with this approach we don't need any extra arch-specific #ifdef guards
7142  */
7143 struct pt_regs;
7144 struct user_pt_regs;
7145 struct user_regs_struct;
7146 
7147 static bool need_func_arg_type_fixup(const struct btf *btf, const struct bpf_program *prog,
7148 				     const char *subprog_name, int arg_idx,
7149 				     int arg_type_id, const char *ctx_name)
7150 {
7151 	const struct btf_type *t;
7152 	const char *tname;
7153 
7154 	/* check if existing parameter already matches verifier expectations */
7155 	t = skip_mods_and_typedefs(btf, arg_type_id, NULL);
7156 	if (!btf_is_ptr(t))
7157 		goto out_warn;
7158 
7159 	/* typedef bpf_user_pt_regs_t is a special PITA case, valid for kprobe
7160 	 * and perf_event programs, so check this case early on and forget
7161 	 * about it for subsequent checks
7162 	 */
7163 	while (btf_is_mod(t))
7164 		t = btf__type_by_id(btf, t->type);
7165 	if (btf_is_typedef(t) &&
7166 	    (prog->type == BPF_PROG_TYPE_KPROBE || prog->type == BPF_PROG_TYPE_PERF_EVENT)) {
7167 		tname = btf__str_by_offset(btf, t->name_off) ?: "<anon>";
7168 		if (strcmp(tname, "bpf_user_pt_regs_t") == 0)
7169 			return false; /* canonical type for kprobe/perf_event */
7170 	}
7171 
7172 	/* now we can ignore typedefs moving forward */
7173 	t = skip_mods_and_typedefs(btf, t->type, NULL);
7174 
7175 	/* if it's `void *`, definitely fix up BTF info */
7176 	if (btf_is_void(t))
7177 		return true;
7178 
7179 	/* if it's already proper canonical type, no need to fix up */
7180 	tname = btf__str_by_offset(btf, t->name_off) ?: "<anon>";
7181 	if (btf_is_struct(t) && strcmp(tname, ctx_name) == 0)
7182 		return false;
7183 
7184 	/* special cases */
7185 	switch (prog->type) {
7186 	case BPF_PROG_TYPE_KPROBE:
7187 		/* `struct pt_regs *` is expected, but we need to fix up */
7188 		if (btf_is_struct(t) && strcmp(tname, "pt_regs") == 0)
7189 			return true;
7190 		break;
7191 	case BPF_PROG_TYPE_PERF_EVENT:
7192 		if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct pt_regs) &&
7193 		    btf_is_struct(t) && strcmp(tname, "pt_regs") == 0)
7194 			return true;
7195 		if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct user_pt_regs) &&
7196 		    btf_is_struct(t) && strcmp(tname, "user_pt_regs") == 0)
7197 			return true;
7198 		if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct user_regs_struct) &&
7199 		    btf_is_struct(t) && strcmp(tname, "user_regs_struct") == 0)
7200 			return true;
7201 		break;
7202 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
7203 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
7204 		/* allow u64* as ctx */
7205 		if (btf_is_int(t) && t->size == 8)
7206 			return true;
7207 		break;
7208 	default:
7209 		break;
7210 	}
7211 
7212 out_warn:
7213 	pr_warn("prog '%s': subprog '%s' arg#%d is expected to be of `struct %s *` type\n",
7214 		prog->name, subprog_name, arg_idx, ctx_name);
7215 	return false;
7216 }
7217 
7218 static int clone_func_btf_info(struct btf *btf, int orig_fn_id, struct bpf_program *prog)
7219 {
7220 	int fn_id, fn_proto_id, ret_type_id, orig_proto_id;
7221 	int i, err, arg_cnt, fn_name_off, linkage;
7222 	struct btf_type *fn_t, *fn_proto_t, *t;
7223 	struct btf_param *p;
7224 
7225 	/* caller already validated FUNC -> FUNC_PROTO validity */
7226 	fn_t = btf_type_by_id(btf, orig_fn_id);
7227 	fn_proto_t = btf_type_by_id(btf, fn_t->type);
7228 
7229 	/* Note that each btf__add_xxx() operation invalidates
7230 	 * all btf_type and string pointers, so we need to be
7231 	 * very careful when cloning BTF types. BTF type
7232 	 * pointers have to be always refetched. And to avoid
7233 	 * problems with invalidated string pointers, we
7234 	 * add empty strings initially, then just fix up
7235 	 * name_off offsets in place. Offsets are stable for
7236 	 * existing strings, so that works out.
7237 	 */
7238 	fn_name_off = fn_t->name_off; /* we are about to invalidate fn_t */
7239 	linkage = btf_func_linkage(fn_t);
7240 	orig_proto_id = fn_t->type; /* original FUNC_PROTO ID */
7241 	ret_type_id = fn_proto_t->type; /* fn_proto_t will be invalidated */
7242 	arg_cnt = btf_vlen(fn_proto_t);
7243 
7244 	/* clone FUNC_PROTO and its params */
7245 	fn_proto_id = btf__add_func_proto(btf, ret_type_id);
7246 	if (fn_proto_id < 0)
7247 		return -EINVAL;
7248 
7249 	for (i = 0; i < arg_cnt; i++) {
7250 		int name_off;
7251 
7252 		/* copy original parameter data */
7253 		t = btf_type_by_id(btf, orig_proto_id);
7254 		p = &btf_params(t)[i];
7255 		name_off = p->name_off;
7256 
7257 		err = btf__add_func_param(btf, "", p->type);
7258 		if (err)
7259 			return err;
7260 
7261 		fn_proto_t = btf_type_by_id(btf, fn_proto_id);
7262 		p = &btf_params(fn_proto_t)[i];
7263 		p->name_off = name_off; /* use remembered str offset */
7264 	}
7265 
7266 	/* clone FUNC now, btf__add_func() enforces non-empty name, so use
7267 	 * entry program's name as a placeholder, which we replace immediately
7268 	 * with original name_off
7269 	 */
7270 	fn_id = btf__add_func(btf, prog->name, linkage, fn_proto_id);
7271 	if (fn_id < 0)
7272 		return -EINVAL;
7273 
7274 	fn_t = btf_type_by_id(btf, fn_id);
7275 	fn_t->name_off = fn_name_off; /* reuse original string */
7276 
7277 	return fn_id;
7278 }
7279 
7280 /* Check if main program or global subprog's function prototype has `arg:ctx`
7281  * argument tags, and, if necessary, substitute correct type to match what BPF
7282  * verifier would expect, taking into account specific program type. This
7283  * allows to support __arg_ctx tag transparently on old kernels that don't yet
7284  * have a native support for it in the verifier, making user's life much
7285  * easier.
7286  */
7287 static int bpf_program_fixup_func_info(struct bpf_object *obj, struct bpf_program *prog)
7288 {
7289 	const char *ctx_name = NULL, *ctx_tag = "arg:ctx", *fn_name;
7290 	struct bpf_func_info_min *func_rec;
7291 	struct btf_type *fn_t, *fn_proto_t;
7292 	struct btf *btf = obj->btf;
7293 	const struct btf_type *t;
7294 	struct btf_param *p;
7295 	int ptr_id = 0, struct_id, tag_id, orig_fn_id;
7296 	int i, n, arg_idx, arg_cnt, err, rec_idx;
7297 	int *orig_ids;
7298 
7299 	/* no .BTF.ext, no problem */
7300 	if (!obj->btf_ext || !prog->func_info)
7301 		return 0;
7302 
7303 	/* don't do any fix ups if kernel natively supports __arg_ctx */
7304 	if (kernel_supports(obj, FEAT_ARG_CTX_TAG))
7305 		return 0;
7306 
7307 	/* some BPF program types just don't have named context structs, so
7308 	 * this fallback mechanism doesn't work for them
7309 	 */
7310 	for (i = 0; i < ARRAY_SIZE(global_ctx_map); i++) {
7311 		if (global_ctx_map[i].prog_type != prog->type)
7312 			continue;
7313 		ctx_name = global_ctx_map[i].ctx_name;
7314 		break;
7315 	}
7316 	if (!ctx_name)
7317 		return 0;
7318 
7319 	/* remember original func BTF IDs to detect if we already cloned them */
7320 	orig_ids = calloc(prog->func_info_cnt, sizeof(*orig_ids));
7321 	if (!orig_ids)
7322 		return -ENOMEM;
7323 	for (i = 0; i < prog->func_info_cnt; i++) {
7324 		func_rec = prog->func_info + prog->func_info_rec_size * i;
7325 		orig_ids[i] = func_rec->type_id;
7326 	}
7327 
7328 	/* go through each DECL_TAG with "arg:ctx" and see if it points to one
7329 	 * of our subprogs; if yes and subprog is global and needs adjustment,
7330 	 * clone and adjust FUNC -> FUNC_PROTO combo
7331 	 */
7332 	for (i = 1, n = btf__type_cnt(btf); i < n; i++) {
7333 		/* only DECL_TAG with "arg:ctx" value are interesting */
7334 		t = btf__type_by_id(btf, i);
7335 		if (!btf_is_decl_tag(t))
7336 			continue;
7337 		if (strcmp(btf__str_by_offset(btf, t->name_off), ctx_tag) != 0)
7338 			continue;
7339 
7340 		/* only global funcs need adjustment, if at all */
7341 		orig_fn_id = t->type;
7342 		fn_t = btf_type_by_id(btf, orig_fn_id);
7343 		if (!btf_is_func(fn_t) || btf_func_linkage(fn_t) != BTF_FUNC_GLOBAL)
7344 			continue;
7345 
7346 		/* sanity check FUNC -> FUNC_PROTO chain, just in case */
7347 		fn_proto_t = btf_type_by_id(btf, fn_t->type);
7348 		if (!fn_proto_t || !btf_is_func_proto(fn_proto_t))
7349 			continue;
7350 
7351 		/* find corresponding func_info record */
7352 		func_rec = NULL;
7353 		for (rec_idx = 0; rec_idx < prog->func_info_cnt; rec_idx++) {
7354 			if (orig_ids[rec_idx] == t->type) {
7355 				func_rec = prog->func_info + prog->func_info_rec_size * rec_idx;
7356 				break;
7357 			}
7358 		}
7359 		/* current main program doesn't call into this subprog */
7360 		if (!func_rec)
7361 			continue;
7362 
7363 		/* some more sanity checking of DECL_TAG */
7364 		arg_cnt = btf_vlen(fn_proto_t);
7365 		arg_idx = btf_decl_tag(t)->component_idx;
7366 		if (arg_idx < 0 || arg_idx >= arg_cnt)
7367 			continue;
7368 
7369 		/* check if we should fix up argument type */
7370 		p = &btf_params(fn_proto_t)[arg_idx];
7371 		fn_name = btf__str_by_offset(btf, fn_t->name_off) ?: "<anon>";
7372 		if (!need_func_arg_type_fixup(btf, prog, fn_name, arg_idx, p->type, ctx_name))
7373 			continue;
7374 
7375 		/* clone fn/fn_proto, unless we already did it for another arg */
7376 		if (func_rec->type_id == orig_fn_id) {
7377 			int fn_id;
7378 
7379 			fn_id = clone_func_btf_info(btf, orig_fn_id, prog);
7380 			if (fn_id < 0) {
7381 				err = fn_id;
7382 				goto err_out;
7383 			}
7384 
7385 			/* point func_info record to a cloned FUNC type */
7386 			func_rec->type_id = fn_id;
7387 		}
7388 
7389 		/* create PTR -> STRUCT type chain to mark PTR_TO_CTX argument;
7390 		 * we do it just once per main BPF program, as all global
7391 		 * funcs share the same program type, so need only PTR ->
7392 		 * STRUCT type chain
7393 		 */
7394 		if (ptr_id == 0) {
7395 			struct_id = btf__add_struct(btf, ctx_name, 0);
7396 			ptr_id = btf__add_ptr(btf, struct_id);
7397 			if (ptr_id < 0 || struct_id < 0) {
7398 				err = -EINVAL;
7399 				goto err_out;
7400 			}
7401 		}
7402 
7403 		/* for completeness, clone DECL_TAG and point it to cloned param */
7404 		tag_id = btf__add_decl_tag(btf, ctx_tag, func_rec->type_id, arg_idx);
7405 		if (tag_id < 0) {
7406 			err = -EINVAL;
7407 			goto err_out;
7408 		}
7409 
7410 		/* all the BTF manipulations invalidated pointers, refetch them */
7411 		fn_t = btf_type_by_id(btf, func_rec->type_id);
7412 		fn_proto_t = btf_type_by_id(btf, fn_t->type);
7413 
7414 		/* fix up type ID pointed to by param */
7415 		p = &btf_params(fn_proto_t)[arg_idx];
7416 		p->type = ptr_id;
7417 	}
7418 
7419 	free(orig_ids);
7420 	return 0;
7421 err_out:
7422 	free(orig_ids);
7423 	return err;
7424 }
7425 
7426 static int bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
7427 {
7428 	struct bpf_program *prog;
7429 	size_t i, j;
7430 	int err;
7431 
7432 	if (obj->btf_ext) {
7433 		err = bpf_object__relocate_core(obj, targ_btf_path);
7434 		if (err) {
7435 			pr_warn("failed to perform CO-RE relocations: %s\n",
7436 				errstr(err));
7437 			return err;
7438 		}
7439 		bpf_object__sort_relos(obj);
7440 	}
7441 
7442 	/* place globals at the end of the arena (if supported) */
7443 	if (obj->arena_map_idx >= 0 && kernel_supports(obj, FEAT_LDIMM64_FULL_RANGE_OFF)) {
7444 		struct bpf_map *arena_map = &obj->maps[obj->arena_map_idx];
7445 
7446 		obj->arena_data_off = bpf_map_mmap_sz(arena_map) -
7447 				      roundup(obj->arena_data_sz, sysconf(_SC_PAGE_SIZE));
7448 	}
7449 
7450 	/* Before relocating calls pre-process relocations and mark
7451 	 * few ld_imm64 instructions that points to subprogs.
7452 	 * Otherwise bpf_object__reloc_code() later would have to consider
7453 	 * all ld_imm64 insns as relocation candidates. That would
7454 	 * reduce relocation speed, since amount of find_prog_insn_relo()
7455 	 * would increase and most of them will fail to find a relo.
7456 	 */
7457 	for (i = 0; i < obj->nr_programs; i++) {
7458 		prog = &obj->programs[i];
7459 		for (j = 0; j < prog->nr_reloc; j++) {
7460 			struct reloc_desc *relo = &prog->reloc_desc[j];
7461 			struct bpf_insn *insn = &prog->insns[relo->insn_idx];
7462 
7463 			/* mark the insn, so it's recognized by insn_is_pseudo_func() */
7464 			if (relo->type == RELO_SUBPROG_ADDR)
7465 				insn[0].src_reg = BPF_PSEUDO_FUNC;
7466 		}
7467 	}
7468 
7469 	/* relocate subprogram calls and append used subprograms to main
7470 	 * programs; each copy of subprogram code needs to be relocated
7471 	 * differently for each main program, because its code location might
7472 	 * have changed.
7473 	 * Append subprog relos to main programs to allow data relos to be
7474 	 * processed after text is completely relocated.
7475 	 */
7476 	for (i = 0; i < obj->nr_programs; i++) {
7477 		prog = &obj->programs[i];
7478 		/* sub-program's sub-calls are relocated within the context of
7479 		 * its main program only
7480 		 */
7481 		if (prog_is_subprog(obj, prog))
7482 			continue;
7483 		if (!prog->autoload)
7484 			continue;
7485 
7486 		err = bpf_object__relocate_calls(obj, prog);
7487 		if (err) {
7488 			pr_warn("prog '%s': failed to relocate calls: %s\n",
7489 				prog->name, errstr(err));
7490 			return err;
7491 		}
7492 
7493 		err = bpf_prog_assign_exc_cb(obj, prog);
7494 		if (err)
7495 			return err;
7496 		/* Now, also append exception callback if it has not been done already. */
7497 		if (prog->exception_cb_idx >= 0) {
7498 			struct bpf_program *subprog = &obj->programs[prog->exception_cb_idx];
7499 
7500 			/* Calling exception callback directly is disallowed, which the
7501 			 * verifier will reject later. In case it was processed already,
7502 			 * we can skip this step, otherwise for all other valid cases we
7503 			 * have to append exception callback now.
7504 			 */
7505 			if (subprog->sub_insn_off == 0) {
7506 				err = bpf_object__append_subprog_code(obj, prog, subprog);
7507 				if (err)
7508 					return err;
7509 				err = bpf_object__reloc_code(obj, prog, subprog);
7510 				if (err)
7511 					return err;
7512 			}
7513 		}
7514 	}
7515 	for (i = 0; i < obj->nr_programs; i++) {
7516 		prog = &obj->programs[i];
7517 		if (prog_is_subprog(obj, prog))
7518 			continue;
7519 		if (!prog->autoload)
7520 			continue;
7521 
7522 		/* Process data relos for main programs */
7523 		err = bpf_object__relocate_data(obj, prog);
7524 		if (err) {
7525 			pr_warn("prog '%s': failed to relocate data references: %s\n",
7526 				prog->name, errstr(err));
7527 			return err;
7528 		}
7529 
7530 		/* Fix up .BTF.ext information, if necessary */
7531 		err = bpf_program_fixup_func_info(obj, prog);
7532 		if (err) {
7533 			pr_warn("prog '%s': failed to perform .BTF.ext fix ups: %s\n",
7534 				prog->name, errstr(err));
7535 			return err;
7536 		}
7537 	}
7538 
7539 	return 0;
7540 }
7541 
7542 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
7543 					    Elf64_Shdr *shdr, Elf_Data *data);
7544 
7545 static int bpf_object__collect_map_relos(struct bpf_object *obj,
7546 					 Elf64_Shdr *shdr, Elf_Data *data)
7547 {
7548 	const int bpf_ptr_sz = 8, host_ptr_sz = sizeof(void *);
7549 	int i, j, nrels, new_sz;
7550 	const struct btf_var_secinfo *vi = NULL;
7551 	const struct btf_type *sec, *var, *def;
7552 	struct bpf_map *map = NULL, *targ_map = NULL;
7553 	struct bpf_program *targ_prog = NULL;
7554 	bool is_prog_array, is_map_in_map;
7555 	const struct btf_member *member;
7556 	const char *name, *mname, *type;
7557 	unsigned int moff;
7558 	Elf64_Sym *sym;
7559 	Elf64_Rel *rel;
7560 	void *tmp;
7561 
7562 	if (!obj->efile.btf_maps_sec_btf_id || !obj->btf)
7563 		return -EINVAL;
7564 	sec = btf__type_by_id(obj->btf, obj->efile.btf_maps_sec_btf_id);
7565 	if (!sec)
7566 		return -EINVAL;
7567 
7568 	nrels = shdr->sh_size / shdr->sh_entsize;
7569 	for (i = 0; i < nrels; i++) {
7570 		rel = elf_rel_by_idx(data, i);
7571 		if (!rel) {
7572 			pr_warn(".maps relo #%d: failed to get ELF relo\n", i);
7573 			return -LIBBPF_ERRNO__FORMAT;
7574 		}
7575 
7576 		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
7577 		if (!sym) {
7578 			pr_warn(".maps relo #%d: symbol %zx not found\n",
7579 				i, (size_t)ELF64_R_SYM(rel->r_info));
7580 			return -LIBBPF_ERRNO__FORMAT;
7581 		}
7582 		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
7583 
7584 		pr_debug(".maps relo #%d: for %zd value %zd rel->r_offset %zu name %d ('%s')\n",
7585 			 i, (ssize_t)(rel->r_info >> 32), (size_t)sym->st_value,
7586 			 (size_t)rel->r_offset, sym->st_name, name);
7587 
7588 		for (j = 0; j < obj->nr_maps; j++) {
7589 			map = &obj->maps[j];
7590 			if (map->sec_idx != obj->efile.btf_maps_shndx)
7591 				continue;
7592 
7593 			vi = btf_var_secinfos(sec) + map->btf_var_idx;
7594 			if (vi->offset <= rel->r_offset &&
7595 			    rel->r_offset + bpf_ptr_sz <= vi->offset + vi->size)
7596 				break;
7597 		}
7598 		if (j == obj->nr_maps) {
7599 			pr_warn(".maps relo #%d: cannot find map '%s' at rel->r_offset %zu\n",
7600 				i, name, (size_t)rel->r_offset);
7601 			return -EINVAL;
7602 		}
7603 
7604 		is_map_in_map = bpf_map_type__is_map_in_map(map->def.type);
7605 		is_prog_array = map->def.type == BPF_MAP_TYPE_PROG_ARRAY;
7606 		type = is_map_in_map ? "map" : "prog";
7607 		if (is_map_in_map) {
7608 			if (sym->st_shndx != obj->efile.btf_maps_shndx) {
7609 				pr_warn(".maps relo #%d: '%s' isn't a BTF-defined map\n",
7610 					i, name);
7611 				return -LIBBPF_ERRNO__RELOC;
7612 			}
7613 			if (map->def.type == BPF_MAP_TYPE_HASH_OF_MAPS &&
7614 			    map->def.key_size != sizeof(int)) {
7615 				pr_warn(".maps relo #%d: hash-of-maps '%s' should have key size %zu.\n",
7616 					i, map->name, sizeof(int));
7617 				return -EINVAL;
7618 			}
7619 			targ_map = bpf_object__find_map_by_name(obj, name);
7620 			if (!targ_map) {
7621 				pr_warn(".maps relo #%d: '%s' isn't a valid map reference\n",
7622 					i, name);
7623 				return -ESRCH;
7624 			}
7625 		} else if (is_prog_array) {
7626 			targ_prog = bpf_object__find_program_by_name(obj, name);
7627 			if (!targ_prog) {
7628 				pr_warn(".maps relo #%d: '%s' isn't a valid program reference\n",
7629 					i, name);
7630 				return -ESRCH;
7631 			}
7632 			if (targ_prog->sec_idx != sym->st_shndx ||
7633 			    targ_prog->sec_insn_off * 8 != sym->st_value ||
7634 			    prog_is_subprog(obj, targ_prog)) {
7635 				pr_warn(".maps relo #%d: '%s' isn't an entry-point program\n",
7636 					i, name);
7637 				return -LIBBPF_ERRNO__RELOC;
7638 			}
7639 		} else {
7640 			return -EINVAL;
7641 		}
7642 
7643 		var = btf__type_by_id(obj->btf, vi->type);
7644 		def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
7645 		if (btf_vlen(def) == 0)
7646 			return -EINVAL;
7647 		member = btf_members(def) + btf_vlen(def) - 1;
7648 		mname = btf__name_by_offset(obj->btf, member->name_off);
7649 		if (strcmp(mname, "values"))
7650 			return -EINVAL;
7651 
7652 		moff = btf_member_bit_offset(def, btf_vlen(def) - 1) / 8;
7653 		if (rel->r_offset - vi->offset < moff)
7654 			return -EINVAL;
7655 
7656 		moff = rel->r_offset - vi->offset - moff;
7657 		/* here we use BPF pointer size, which is always 64 bit, as we
7658 		 * are parsing ELF that was built for BPF target
7659 		 */
7660 		if (moff % bpf_ptr_sz)
7661 			return -EINVAL;
7662 		moff /= bpf_ptr_sz;
7663 		if (moff >= map->init_slots_sz) {
7664 			new_sz = moff + 1;
7665 			tmp = libbpf_reallocarray(map->init_slots, new_sz, host_ptr_sz);
7666 			if (!tmp)
7667 				return -ENOMEM;
7668 			map->init_slots = tmp;
7669 			memset(map->init_slots + map->init_slots_sz, 0,
7670 			       (new_sz - map->init_slots_sz) * host_ptr_sz);
7671 			map->init_slots_sz = new_sz;
7672 		}
7673 		map->init_slots[moff] = is_map_in_map ? (void *)targ_map : (void *)targ_prog;
7674 
7675 		pr_debug(".maps relo #%d: map '%s' slot [%d] points to %s '%s'\n",
7676 			 i, map->name, moff, type, name);
7677 	}
7678 
7679 	return 0;
7680 }
7681 
7682 static int bpf_object__collect_relos(struct bpf_object *obj)
7683 {
7684 	int i, err;
7685 
7686 	for (i = 0; i < obj->efile.sec_cnt; i++) {
7687 		struct elf_sec_desc *sec_desc = &obj->efile.secs[i];
7688 		Elf64_Shdr *shdr;
7689 		Elf_Data *data;
7690 		int idx;
7691 
7692 		if (sec_desc->sec_type != SEC_RELO)
7693 			continue;
7694 
7695 		shdr = sec_desc->shdr;
7696 		data = sec_desc->data;
7697 		idx = shdr->sh_info;
7698 
7699 		if (shdr->sh_type != SHT_REL || idx < 0 || idx >= obj->efile.sec_cnt) {
7700 			pr_warn("internal error at %d\n", __LINE__);
7701 			return -LIBBPF_ERRNO__INTERNAL;
7702 		}
7703 
7704 		if (obj->efile.secs[idx].sec_type == SEC_ST_OPS)
7705 			err = bpf_object__collect_st_ops_relos(obj, shdr, data);
7706 		else if (idx == obj->efile.btf_maps_shndx)
7707 			err = bpf_object__collect_map_relos(obj, shdr, data);
7708 		else
7709 			err = bpf_object__collect_prog_relos(obj, shdr, data);
7710 		if (err)
7711 			return err;
7712 	}
7713 
7714 	bpf_object__sort_relos(obj);
7715 	return 0;
7716 }
7717 
7718 static bool insn_is_helper_call(struct bpf_insn *insn, enum bpf_func_id *func_id)
7719 {
7720 	if (BPF_CLASS(insn->code) == BPF_JMP &&
7721 	    BPF_OP(insn->code) == BPF_CALL &&
7722 	    BPF_SRC(insn->code) == BPF_K &&
7723 	    insn->src_reg == 0 &&
7724 	    insn->dst_reg == 0) {
7725 		    *func_id = insn->imm;
7726 		    return true;
7727 	}
7728 	return false;
7729 }
7730 
7731 static int bpf_object__sanitize_prog(struct bpf_object *obj, struct bpf_program *prog)
7732 {
7733 	struct bpf_insn *insn = prog->insns;
7734 	enum bpf_func_id func_id;
7735 	int i;
7736 
7737 	if (obj->gen_loader)
7738 		return 0;
7739 
7740 	for (i = 0; i < prog->insns_cnt; i++, insn++) {
7741 		if (!insn_is_helper_call(insn, &func_id))
7742 			continue;
7743 
7744 		/* on kernels that don't yet support
7745 		 * bpf_probe_read_{kernel,user}[_str] helpers, fall back
7746 		 * to bpf_probe_read() which works well for old kernels
7747 		 */
7748 		switch (func_id) {
7749 		case BPF_FUNC_probe_read_kernel:
7750 		case BPF_FUNC_probe_read_user:
7751 			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
7752 				insn->imm = BPF_FUNC_probe_read;
7753 			break;
7754 		case BPF_FUNC_probe_read_kernel_str:
7755 		case BPF_FUNC_probe_read_user_str:
7756 			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
7757 				insn->imm = BPF_FUNC_probe_read_str;
7758 			break;
7759 		default:
7760 			break;
7761 		}
7762 	}
7763 	return 0;
7764 }
7765 
7766 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
7767 				     int *btf_obj_fd, int *btf_type_id);
7768 
7769 /* this is called as prog->sec_def->prog_prepare_load_fn for libbpf-supported sec_defs */
7770 static int libbpf_prepare_prog_load(struct bpf_program *prog,
7771 				    struct bpf_prog_load_opts *opts, long cookie)
7772 {
7773 	enum sec_def_flags def = cookie;
7774 
7775 	/* old kernels might not support specifying expected_attach_type */
7776 	if ((def & SEC_EXP_ATTACH_OPT) && !kernel_supports(prog->obj, FEAT_EXP_ATTACH_TYPE))
7777 		opts->expected_attach_type = 0;
7778 
7779 	if (def & SEC_SLEEPABLE)
7780 		opts->prog_flags |= BPF_F_SLEEPABLE;
7781 
7782 	if (prog->type == BPF_PROG_TYPE_XDP && (def & SEC_XDP_FRAGS))
7783 		opts->prog_flags |= BPF_F_XDP_HAS_FRAGS;
7784 
7785 	/* special check for usdt to use uprobe_multi link */
7786 	if ((def & SEC_USDT) && kernel_supports(prog->obj, FEAT_UPROBE_MULTI_LINK)) {
7787 		/* for BPF_TRACE_UPROBE_MULTI, user might want to query expected_attach_type
7788 		 * in prog, and expected_attach_type we set in kernel is from opts, so we
7789 		 * update both.
7790 		 */
7791 		prog->expected_attach_type = BPF_TRACE_UPROBE_MULTI;
7792 		opts->expected_attach_type = BPF_TRACE_UPROBE_MULTI;
7793 	}
7794 
7795 	if ((def & SEC_ATTACH_BTF) && !prog->attach_btf_id) {
7796 		int btf_obj_fd = 0, btf_type_id = 0, err;
7797 		const char *attach_name;
7798 
7799 		attach_name = strchr(prog->sec_name, '/');
7800 		if (!attach_name) {
7801 			/* if BPF program is annotated with just SEC("fentry")
7802 			 * (or similar) without declaratively specifying
7803 			 * target, then it is expected that target will be
7804 			 * specified with bpf_program__set_attach_target() at
7805 			 * runtime before BPF object load step. If not, then
7806 			 * there is nothing to load into the kernel as BPF
7807 			 * verifier won't be able to validate BPF program
7808 			 * correctness anyways.
7809 			 */
7810 			pr_warn("prog '%s': no BTF-based attach target is specified, use bpf_program__set_attach_target()\n",
7811 				prog->name);
7812 			return -EINVAL;
7813 		}
7814 		attach_name++; /* skip over / */
7815 
7816 		err = libbpf_find_attach_btf_id(prog, attach_name, &btf_obj_fd, &btf_type_id);
7817 		if (err)
7818 			return err;
7819 
7820 		/* cache resolved BTF FD and BTF type ID in the prog */
7821 		prog->attach_btf_obj_fd = btf_obj_fd;
7822 		prog->attach_btf_id = btf_type_id;
7823 
7824 		/* but by now libbpf common logic is not utilizing
7825 		 * prog->atach_btf_obj_fd/prog->attach_btf_id anymore because
7826 		 * this callback is called after opts were populated by
7827 		 * libbpf, so this callback has to update opts explicitly here
7828 		 */
7829 		opts->attach_btf_obj_fd = btf_obj_fd;
7830 		opts->attach_btf_id = btf_type_id;
7831 	}
7832 	return 0;
7833 }
7834 
7835 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz);
7836 
7837 static int bpf_object_load_prog(struct bpf_object *obj, struct bpf_program *prog,
7838 				struct bpf_insn *insns, int insns_cnt,
7839 				const char *license, __u32 kern_version, int *prog_fd)
7840 {
7841 	LIBBPF_OPTS(bpf_prog_load_opts, load_attr);
7842 	const char *prog_name = NULL;
7843 	size_t log_buf_size = 0;
7844 	char *log_buf = NULL, *tmp;
7845 	bool own_log_buf = true;
7846 	__u32 log_level = prog->log_level;
7847 	int ret, err;
7848 
7849 	/* Be more helpful by rejecting programs that can't be validated early
7850 	 * with more meaningful and actionable error message.
7851 	 */
7852 	switch (prog->type) {
7853 	case BPF_PROG_TYPE_UNSPEC:
7854 		/*
7855 		 * The program type must be set.  Most likely we couldn't find a proper
7856 		 * section definition at load time, and thus we didn't infer the type.
7857 		 */
7858 		pr_warn("prog '%s': missing BPF prog type, check ELF section name '%s'\n",
7859 			prog->name, prog->sec_name);
7860 		return -EINVAL;
7861 	case BPF_PROG_TYPE_STRUCT_OPS:
7862 		if (prog->attach_btf_id == 0) {
7863 			pr_warn("prog '%s': SEC(\"struct_ops\") program isn't referenced anywhere, did you forget to use it?\n",
7864 				prog->name);
7865 			return -EINVAL;
7866 		}
7867 		break;
7868 	default:
7869 		break;
7870 	}
7871 
7872 	if (!insns || !insns_cnt)
7873 		return -EINVAL;
7874 
7875 	if (kernel_supports(obj, FEAT_PROG_NAME))
7876 		prog_name = prog->name;
7877 	load_attr.attach_prog_fd = prog->attach_prog_fd;
7878 	load_attr.attach_btf_obj_fd = prog->attach_btf_obj_fd;
7879 	load_attr.attach_btf_id = prog->attach_btf_id;
7880 	load_attr.kern_version = kern_version;
7881 	load_attr.prog_ifindex = prog->prog_ifindex;
7882 	load_attr.expected_attach_type = prog->expected_attach_type;
7883 
7884 	/* specify func_info/line_info only if kernel supports them */
7885 	if (obj->btf && btf__fd(obj->btf) >= 0 && kernel_supports(obj, FEAT_BTF_FUNC)) {
7886 		load_attr.prog_btf_fd = btf__fd(obj->btf);
7887 		load_attr.func_info = prog->func_info;
7888 		load_attr.func_info_rec_size = prog->func_info_rec_size;
7889 		load_attr.func_info_cnt = prog->func_info_cnt;
7890 		load_attr.line_info = prog->line_info;
7891 		load_attr.line_info_rec_size = prog->line_info_rec_size;
7892 		load_attr.line_info_cnt = prog->line_info_cnt;
7893 	}
7894 	load_attr.log_level = log_level;
7895 	load_attr.prog_flags = prog->prog_flags;
7896 	load_attr.fd_array = obj->fd_array;
7897 
7898 	load_attr.token_fd = obj->token_fd;
7899 	if (obj->token_fd)
7900 		load_attr.prog_flags |= BPF_F_TOKEN_FD;
7901 
7902 	/* adjust load_attr if sec_def provides custom preload callback */
7903 	if (prog->sec_def && prog->sec_def->prog_prepare_load_fn) {
7904 		err = prog->sec_def->prog_prepare_load_fn(prog, &load_attr, prog->sec_def->cookie);
7905 		if (err < 0) {
7906 			pr_warn("prog '%s': failed to prepare load attributes: %s\n",
7907 				prog->name, errstr(err));
7908 			return err;
7909 		}
7910 		insns = prog->insns;
7911 		insns_cnt = prog->insns_cnt;
7912 	}
7913 
7914 	if (obj->gen_loader) {
7915 		bpf_gen__prog_load(obj->gen_loader, prog->type, prog->name,
7916 				   license, insns, insns_cnt, &load_attr,
7917 				   prog - obj->programs);
7918 		*prog_fd = -1;
7919 		return 0;
7920 	}
7921 
7922 retry_load:
7923 	/* if log_level is zero, we don't request logs initially even if
7924 	 * custom log_buf is specified; if the program load fails, then we'll
7925 	 * bump log_level to 1 and use either custom log_buf or we'll allocate
7926 	 * our own and retry the load to get details on what failed
7927 	 */
7928 	if (log_level) {
7929 		if (prog->log_buf) {
7930 			log_buf = prog->log_buf;
7931 			log_buf_size = prog->log_size;
7932 			own_log_buf = false;
7933 		} else if (obj->log_buf) {
7934 			log_buf = obj->log_buf;
7935 			log_buf_size = obj->log_size;
7936 			own_log_buf = false;
7937 		} else {
7938 			log_buf_size = max((size_t)BPF_LOG_BUF_SIZE, log_buf_size * 2);
7939 			tmp = realloc(log_buf, log_buf_size);
7940 			if (!tmp) {
7941 				ret = -ENOMEM;
7942 				goto out;
7943 			}
7944 			log_buf = tmp;
7945 			log_buf[0] = '\0';
7946 			own_log_buf = true;
7947 		}
7948 	}
7949 
7950 	load_attr.log_buf = log_buf;
7951 	load_attr.log_size = log_buf_size;
7952 	load_attr.log_level = log_level;
7953 
7954 	ret = bpf_prog_load(prog->type, prog_name, license, insns, insns_cnt, &load_attr);
7955 	if (ret >= 0) {
7956 		if (log_level && own_log_buf) {
7957 			pr_debug("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
7958 				 prog->name, log_buf);
7959 		}
7960 
7961 		if (obj->has_rodata && kernel_supports(obj, FEAT_PROG_BIND_MAP)) {
7962 			struct bpf_map *map;
7963 			int i;
7964 
7965 			for (i = 0; i < obj->nr_maps; i++) {
7966 				map = &prog->obj->maps[i];
7967 				if (map->libbpf_type != LIBBPF_MAP_RODATA)
7968 					continue;
7969 
7970 				if (bpf_prog_bind_map(ret, map->fd, NULL)) {
7971 					pr_warn("prog '%s': failed to bind map '%s': %s\n",
7972 						prog->name, map->real_name, errstr(errno));
7973 					/* Don't fail hard if can't bind rodata. */
7974 				}
7975 			}
7976 		}
7977 
7978 		*prog_fd = ret;
7979 		ret = 0;
7980 		goto out;
7981 	}
7982 
7983 	if (log_level == 0) {
7984 		log_level = 1;
7985 		goto retry_load;
7986 	}
7987 	/* On ENOSPC, increase log buffer size and retry, unless custom
7988 	 * log_buf is specified.
7989 	 * Be careful to not overflow u32, though. Kernel's log buf size limit
7990 	 * isn't part of UAPI so it can always be bumped to full 4GB. So don't
7991 	 * multiply by 2 unless we are sure we'll fit within 32 bits.
7992 	 * Currently, we'll get -EINVAL when we reach (UINT_MAX >> 2).
7993 	 */
7994 	if (own_log_buf && errno == ENOSPC && log_buf_size <= UINT_MAX / 2)
7995 		goto retry_load;
7996 
7997 	ret = -errno;
7998 
7999 	/* post-process verifier log to improve error descriptions */
8000 	fixup_verifier_log(prog, log_buf, log_buf_size);
8001 
8002 	pr_warn("prog '%s': BPF program load failed: %s\n", prog->name, errstr(errno));
8003 	pr_perm_msg(ret);
8004 
8005 	if (own_log_buf && log_buf && log_buf[0] != '\0') {
8006 		pr_warn("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
8007 			prog->name, log_buf);
8008 	}
8009 
8010 out:
8011 	if (own_log_buf)
8012 		free(log_buf);
8013 	return ret;
8014 }
8015 
8016 static char *find_prev_line(char *buf, char *cur)
8017 {
8018 	char *p;
8019 
8020 	if (cur == buf) /* end of a log buf */
8021 		return NULL;
8022 
8023 	p = cur - 1;
8024 	while (p - 1 >= buf && *(p - 1) != '\n')
8025 		p--;
8026 
8027 	return p;
8028 }
8029 
8030 static void patch_log(char *buf, size_t buf_sz, size_t log_sz,
8031 		      char *orig, size_t orig_sz, const char *patch)
8032 {
8033 	/* size of the remaining log content to the right from the to-be-replaced part */
8034 	size_t rem_sz = (buf + log_sz) - (orig + orig_sz);
8035 	size_t patch_sz = strlen(patch);
8036 
8037 	if (patch_sz != orig_sz) {
8038 		/* If patch line(s) are longer than original piece of verifier log,
8039 		 * shift log contents by (patch_sz - orig_sz) bytes to the right
8040 		 * starting from after to-be-replaced part of the log.
8041 		 *
8042 		 * If patch line(s) are shorter than original piece of verifier log,
8043 		 * shift log contents by (orig_sz - patch_sz) bytes to the left
8044 		 * starting from after to-be-replaced part of the log
8045 		 *
8046 		 * We need to be careful about not overflowing available
8047 		 * buf_sz capacity. If that's the case, we'll truncate the end
8048 		 * of the original log, as necessary.
8049 		 */
8050 		if (patch_sz > orig_sz) {
8051 			if (orig + patch_sz >= buf + buf_sz) {
8052 				/* patch is big enough to cover remaining space completely */
8053 				patch_sz -= (orig + patch_sz) - (buf + buf_sz) + 1;
8054 				rem_sz = 0;
8055 			} else if (patch_sz - orig_sz > buf_sz - log_sz) {
8056 				/* patch causes part of remaining log to be truncated */
8057 				rem_sz -= (patch_sz - orig_sz) - (buf_sz - log_sz);
8058 			}
8059 		}
8060 		/* shift remaining log to the right by calculated amount */
8061 		memmove(orig + patch_sz, orig + orig_sz, rem_sz);
8062 	}
8063 
8064 	memcpy(orig, patch, patch_sz);
8065 }
8066 
8067 static void fixup_log_failed_core_relo(struct bpf_program *prog,
8068 				       char *buf, size_t buf_sz, size_t log_sz,
8069 				       char *line1, char *line2, char *line3)
8070 {
8071 	/* Expected log for failed and not properly guarded CO-RE relocation:
8072 	 * line1 -> 123: (85) call unknown#195896080
8073 	 * line2 -> invalid func unknown#195896080
8074 	 * line3 -> <anything else or end of buffer>
8075 	 *
8076 	 * "123" is the index of the instruction that was poisoned. We extract
8077 	 * instruction index to find corresponding CO-RE relocation and
8078 	 * replace this part of the log with more relevant information about
8079 	 * failed CO-RE relocation.
8080 	 */
8081 	const struct bpf_core_relo *relo;
8082 	struct bpf_core_spec spec;
8083 	char patch[512], spec_buf[256];
8084 	int insn_idx, err, spec_len;
8085 
8086 	if (sscanf(line1, "%d: (%*d) call unknown#195896080\n", &insn_idx) != 1)
8087 		return;
8088 
8089 	relo = find_relo_core(prog, insn_idx);
8090 	if (!relo)
8091 		return;
8092 
8093 	err = bpf_core_parse_spec(prog->name, prog->obj->btf, relo, &spec);
8094 	if (err)
8095 		return;
8096 
8097 	spec_len = bpf_core_format_spec(spec_buf, sizeof(spec_buf), &spec);
8098 	snprintf(patch, sizeof(patch),
8099 		 "%d: <invalid CO-RE relocation>\n"
8100 		 "failed to resolve CO-RE relocation %s%s\n",
8101 		 insn_idx, spec_buf, spec_len >= sizeof(spec_buf) ? "..." : "");
8102 
8103 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
8104 }
8105 
8106 static void fixup_log_missing_map_load(struct bpf_program *prog,
8107 				       char *buf, size_t buf_sz, size_t log_sz,
8108 				       char *line1, char *line2, char *line3)
8109 {
8110 	/* Expected log for failed and not properly guarded map reference:
8111 	 * line1 -> 123: (85) call unknown#2001000345
8112 	 * line2 -> invalid func unknown#2001000345
8113 	 * line3 -> <anything else or end of buffer>
8114 	 *
8115 	 * "123" is the index of the instruction that was poisoned.
8116 	 * "345" in "2001000345" is a map index in obj->maps to fetch map name.
8117 	 */
8118 	struct bpf_object *obj = prog->obj;
8119 	const struct bpf_map *map;
8120 	int insn_idx, map_idx;
8121 	char patch[128];
8122 
8123 	if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &map_idx) != 2)
8124 		return;
8125 
8126 	map_idx -= POISON_LDIMM64_MAP_BASE;
8127 	if (map_idx < 0 || map_idx >= obj->nr_maps)
8128 		return;
8129 	map = &obj->maps[map_idx];
8130 
8131 	snprintf(patch, sizeof(patch),
8132 		 "%d: <invalid BPF map reference>\n"
8133 		 "BPF map '%s' is referenced but wasn't created\n",
8134 		 insn_idx, map->name);
8135 
8136 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
8137 }
8138 
8139 static void fixup_log_missing_kfunc_call(struct bpf_program *prog,
8140 					 char *buf, size_t buf_sz, size_t log_sz,
8141 					 char *line1, char *line2, char *line3)
8142 {
8143 	/* Expected log for failed and not properly guarded kfunc call:
8144 	 * line1 -> 123: (85) call unknown#2002000345
8145 	 * line2 -> invalid func unknown#2002000345
8146 	 * line3 -> <anything else or end of buffer>
8147 	 *
8148 	 * "123" is the index of the instruction that was poisoned.
8149 	 * "345" in "2002000345" is an extern index in obj->externs to fetch kfunc name.
8150 	 */
8151 	struct bpf_object *obj = prog->obj;
8152 	const struct extern_desc *ext;
8153 	int insn_idx, ext_idx;
8154 	char patch[128];
8155 
8156 	if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &ext_idx) != 2)
8157 		return;
8158 
8159 	ext_idx -= POISON_CALL_KFUNC_BASE;
8160 	if (ext_idx < 0 || ext_idx >= obj->nr_extern)
8161 		return;
8162 	ext = &obj->externs[ext_idx];
8163 
8164 	snprintf(patch, sizeof(patch),
8165 		 "%d: <invalid kfunc call>\n"
8166 		 "kfunc '%s' is referenced but wasn't resolved\n",
8167 		 insn_idx, ext->name);
8168 
8169 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
8170 }
8171 
8172 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz)
8173 {
8174 	/* look for familiar error patterns in last N lines of the log */
8175 	const size_t max_last_line_cnt = 10;
8176 	char *prev_line, *cur_line, *next_line;
8177 	size_t log_sz;
8178 	int i;
8179 
8180 	if (!buf)
8181 		return;
8182 
8183 	log_sz = strlen(buf) + 1;
8184 	next_line = buf + log_sz - 1;
8185 
8186 	for (i = 0; i < max_last_line_cnt; i++, next_line = cur_line) {
8187 		cur_line = find_prev_line(buf, next_line);
8188 		if (!cur_line)
8189 			return;
8190 
8191 		if (str_has_pfx(cur_line, "invalid func unknown#195896080\n")) {
8192 			prev_line = find_prev_line(buf, cur_line);
8193 			if (!prev_line)
8194 				continue;
8195 
8196 			/* failed CO-RE relocation case */
8197 			fixup_log_failed_core_relo(prog, buf, buf_sz, log_sz,
8198 						   prev_line, cur_line, next_line);
8199 			return;
8200 		} else if (str_has_pfx(cur_line, "invalid func unknown#"POISON_LDIMM64_MAP_PFX)) {
8201 			prev_line = find_prev_line(buf, cur_line);
8202 			if (!prev_line)
8203 				continue;
8204 
8205 			/* reference to uncreated BPF map */
8206 			fixup_log_missing_map_load(prog, buf, buf_sz, log_sz,
8207 						   prev_line, cur_line, next_line);
8208 			return;
8209 		} else if (str_has_pfx(cur_line, "invalid func unknown#"POISON_CALL_KFUNC_PFX)) {
8210 			prev_line = find_prev_line(buf, cur_line);
8211 			if (!prev_line)
8212 				continue;
8213 
8214 			/* reference to unresolved kfunc */
8215 			fixup_log_missing_kfunc_call(prog, buf, buf_sz, log_sz,
8216 						     prev_line, cur_line, next_line);
8217 			return;
8218 		}
8219 	}
8220 }
8221 
8222 static int bpf_program_record_relos(struct bpf_program *prog)
8223 {
8224 	struct bpf_object *obj = prog->obj;
8225 	int i;
8226 
8227 	for (i = 0; i < prog->nr_reloc; i++) {
8228 		struct reloc_desc *relo = &prog->reloc_desc[i];
8229 		struct extern_desc *ext = &obj->externs[relo->ext_idx];
8230 		int kind;
8231 
8232 		switch (relo->type) {
8233 		case RELO_EXTERN_LD64:
8234 			if (ext->type != EXT_KSYM)
8235 				continue;
8236 			kind = btf_is_var(btf__type_by_id(obj->btf, ext->btf_id)) ?
8237 				BTF_KIND_VAR : BTF_KIND_FUNC;
8238 			bpf_gen__record_extern(obj->gen_loader, ext->name,
8239 					       ext->is_weak, !ext->ksym.type_id,
8240 					       true, kind, relo->insn_idx);
8241 			break;
8242 		case RELO_EXTERN_CALL:
8243 			bpf_gen__record_extern(obj->gen_loader, ext->name,
8244 					       ext->is_weak, false, false, BTF_KIND_FUNC,
8245 					       relo->insn_idx);
8246 			break;
8247 		case RELO_CORE: {
8248 			struct bpf_core_relo cr = {
8249 				.insn_off = relo->insn_idx * 8,
8250 				.type_id = relo->core_relo->type_id,
8251 				.access_str_off = relo->core_relo->access_str_off,
8252 				.kind = relo->core_relo->kind,
8253 			};
8254 
8255 			bpf_gen__record_relo_core(obj->gen_loader, &cr);
8256 			break;
8257 		}
8258 		default:
8259 			continue;
8260 		}
8261 	}
8262 	return 0;
8263 }
8264 
8265 static int
8266 bpf_object__load_progs(struct bpf_object *obj, int log_level)
8267 {
8268 	struct bpf_program *prog;
8269 	size_t i;
8270 	int err;
8271 
8272 	for (i = 0; i < obj->nr_programs; i++) {
8273 		prog = &obj->programs[i];
8274 		if (prog_is_subprog(obj, prog))
8275 			continue;
8276 		if (!prog->autoload) {
8277 			pr_debug("prog '%s': skipped loading\n", prog->name);
8278 			continue;
8279 		}
8280 		prog->log_level |= log_level;
8281 
8282 		if (obj->gen_loader)
8283 			bpf_program_record_relos(prog);
8284 
8285 		err = bpf_object_load_prog(obj, prog, prog->insns, prog->insns_cnt,
8286 					   obj->license, obj->kern_version, &prog->fd);
8287 		if (err) {
8288 			pr_warn("prog '%s': failed to load: %s\n", prog->name, errstr(err));
8289 			return err;
8290 		}
8291 	}
8292 
8293 	bpf_object__free_relocs(obj);
8294 	return 0;
8295 }
8296 
8297 static int bpf_object_prepare_progs(struct bpf_object *obj)
8298 {
8299 	struct bpf_program *prog;
8300 	size_t i;
8301 	int err;
8302 
8303 	for (i = 0; i < obj->nr_programs; i++) {
8304 		prog = &obj->programs[i];
8305 		err = bpf_object__sanitize_prog(obj, prog);
8306 		if (err)
8307 			return err;
8308 	}
8309 	return 0;
8310 }
8311 
8312 static const struct bpf_sec_def *find_sec_def(const char *sec_name);
8313 
8314 static int bpf_object_init_progs(struct bpf_object *obj, const struct bpf_object_open_opts *opts)
8315 {
8316 	struct bpf_program *prog;
8317 	int err;
8318 
8319 	bpf_object__for_each_program(prog, obj) {
8320 		prog->sec_def = find_sec_def(prog->sec_name);
8321 		if (!prog->sec_def) {
8322 			/* couldn't guess, but user might manually specify */
8323 			pr_debug("prog '%s': unrecognized ELF section name '%s'\n",
8324 				prog->name, prog->sec_name);
8325 			continue;
8326 		}
8327 
8328 		prog->type = prog->sec_def->prog_type;
8329 		prog->expected_attach_type = prog->sec_def->expected_attach_type;
8330 
8331 		/* sec_def can have custom callback which should be called
8332 		 * after bpf_program is initialized to adjust its properties
8333 		 */
8334 		if (prog->sec_def->prog_setup_fn) {
8335 			err = prog->sec_def->prog_setup_fn(prog, prog->sec_def->cookie);
8336 			if (err < 0) {
8337 				pr_warn("prog '%s': failed to initialize: %s\n",
8338 					prog->name, errstr(err));
8339 				return err;
8340 			}
8341 		}
8342 	}
8343 
8344 	return 0;
8345 }
8346 
8347 static struct bpf_object *bpf_object_open(const char *path, const void *obj_buf, size_t obj_buf_sz,
8348 					  const char *obj_name,
8349 					  const struct bpf_object_open_opts *opts)
8350 {
8351 	const char *kconfig, *btf_tmp_path, *token_path;
8352 	struct bpf_object *obj;
8353 	int err;
8354 	char *log_buf;
8355 	size_t log_size;
8356 	__u32 log_level;
8357 
8358 	if (obj_buf && !obj_name)
8359 		return ERR_PTR(-EINVAL);
8360 
8361 	if (elf_version(EV_CURRENT) == EV_NONE) {
8362 		pr_warn("failed to init libelf for %s\n",
8363 			path ? : "(mem buf)");
8364 		return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
8365 	}
8366 
8367 	if (!OPTS_VALID(opts, bpf_object_open_opts))
8368 		return ERR_PTR(-EINVAL);
8369 
8370 	obj_name = OPTS_GET(opts, object_name, NULL) ?: obj_name;
8371 	if (obj_buf) {
8372 		path = obj_name;
8373 		pr_debug("loading object '%s' from buffer\n", obj_name);
8374 	} else {
8375 		pr_debug("loading object from %s\n", path);
8376 	}
8377 
8378 	log_buf = OPTS_GET(opts, kernel_log_buf, NULL);
8379 	log_size = OPTS_GET(opts, kernel_log_size, 0);
8380 	log_level = OPTS_GET(opts, kernel_log_level, 0);
8381 	if (log_size > UINT_MAX)
8382 		return ERR_PTR(-EINVAL);
8383 	if (log_size && !log_buf)
8384 		return ERR_PTR(-EINVAL);
8385 
8386 	token_path = OPTS_GET(opts, bpf_token_path, NULL);
8387 	/* if user didn't specify bpf_token_path explicitly, check if
8388 	 * LIBBPF_BPF_TOKEN_PATH envvar was set and treat it as bpf_token_path
8389 	 * option
8390 	 */
8391 	if (!token_path)
8392 		token_path = getenv("LIBBPF_BPF_TOKEN_PATH");
8393 	if (token_path && strlen(token_path) >= PATH_MAX)
8394 		return ERR_PTR(-ENAMETOOLONG);
8395 
8396 	obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
8397 	if (IS_ERR(obj))
8398 		return obj;
8399 
8400 	obj->log_buf = log_buf;
8401 	obj->log_size = log_size;
8402 	obj->log_level = log_level;
8403 
8404 	if (token_path) {
8405 		obj->token_path = strdup(token_path);
8406 		if (!obj->token_path) {
8407 			err = -ENOMEM;
8408 			goto out;
8409 		}
8410 	}
8411 
8412 	btf_tmp_path = OPTS_GET(opts, btf_custom_path, NULL);
8413 	if (btf_tmp_path) {
8414 		if (strlen(btf_tmp_path) >= PATH_MAX) {
8415 			err = -ENAMETOOLONG;
8416 			goto out;
8417 		}
8418 		obj->btf_custom_path = strdup(btf_tmp_path);
8419 		if (!obj->btf_custom_path) {
8420 			err = -ENOMEM;
8421 			goto out;
8422 		}
8423 	}
8424 
8425 	kconfig = OPTS_GET(opts, kconfig, NULL);
8426 	if (kconfig) {
8427 		obj->kconfig = strdup(kconfig);
8428 		if (!obj->kconfig) {
8429 			err = -ENOMEM;
8430 			goto out;
8431 		}
8432 	}
8433 
8434 	err = bpf_object__elf_init(obj);
8435 	err = err ? : bpf_object__elf_collect(obj);
8436 	err = err ? : bpf_object__collect_externs(obj);
8437 	err = err ? : bpf_object_fixup_btf(obj);
8438 	err = err ? : bpf_object__init_maps(obj, opts);
8439 	err = err ? : bpf_object_init_progs(obj, opts);
8440 	err = err ? : bpf_object__collect_relos(obj);
8441 	if (err)
8442 		goto out;
8443 
8444 	bpf_object__elf_finish(obj);
8445 
8446 	return obj;
8447 out:
8448 	bpf_object__close(obj);
8449 	return ERR_PTR(err);
8450 }
8451 
8452 struct bpf_object *
8453 bpf_object__open_file(const char *path, const struct bpf_object_open_opts *opts)
8454 {
8455 	if (!path)
8456 		return libbpf_err_ptr(-EINVAL);
8457 
8458 	return libbpf_ptr(bpf_object_open(path, NULL, 0, NULL, opts));
8459 }
8460 
8461 struct bpf_object *bpf_object__open(const char *path)
8462 {
8463 	return bpf_object__open_file(path, NULL);
8464 }
8465 
8466 struct bpf_object *
8467 bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
8468 		     const struct bpf_object_open_opts *opts)
8469 {
8470 	char tmp_name[64];
8471 
8472 	if (!obj_buf || obj_buf_sz == 0)
8473 		return libbpf_err_ptr(-EINVAL);
8474 
8475 	/* create a (quite useless) default "name" for this memory buffer object */
8476 	snprintf(tmp_name, sizeof(tmp_name), "%lx-%zx", (unsigned long)obj_buf, obj_buf_sz);
8477 
8478 	return libbpf_ptr(bpf_object_open(NULL, obj_buf, obj_buf_sz, tmp_name, opts));
8479 }
8480 
8481 static int bpf_object_unload(struct bpf_object *obj)
8482 {
8483 	size_t i;
8484 
8485 	if (!obj)
8486 		return libbpf_err(-EINVAL);
8487 
8488 	for (i = 0; i < obj->nr_maps; i++) {
8489 		zclose(obj->maps[i].fd);
8490 		if (obj->maps[i].st_ops)
8491 			zfree(&obj->maps[i].st_ops->kern_vdata);
8492 	}
8493 
8494 	for (i = 0; i < obj->nr_programs; i++)
8495 		bpf_program__unload(&obj->programs[i]);
8496 
8497 	return 0;
8498 }
8499 
8500 static int bpf_object__sanitize_maps(struct bpf_object *obj)
8501 {
8502 	struct bpf_map *m;
8503 
8504 	bpf_object__for_each_map(m, obj) {
8505 		if (!bpf_map__is_internal(m))
8506 			continue;
8507 		if (!kernel_supports(obj, FEAT_ARRAY_MMAP))
8508 			m->def.map_flags &= ~BPF_F_MMAPABLE;
8509 	}
8510 
8511 	return 0;
8512 }
8513 
8514 typedef int (*kallsyms_cb_t)(unsigned long long sym_addr, char sym_type,
8515 			     const char *sym_name, void *ctx);
8516 
8517 static int libbpf_kallsyms_parse(kallsyms_cb_t cb, void *ctx)
8518 {
8519 	char sym_type, sym_name[500];
8520 	unsigned long long sym_addr;
8521 	int ret, err = 0;
8522 	FILE *f;
8523 
8524 	f = fopen("/proc/kallsyms", "re");
8525 	if (!f) {
8526 		err = -errno;
8527 		pr_warn("failed to open /proc/kallsyms: %s\n", errstr(err));
8528 		return err;
8529 	}
8530 
8531 	while (true) {
8532 		ret = fscanf(f, "%llx %c %499s%*[^\n]\n",
8533 			     &sym_addr, &sym_type, sym_name);
8534 		if (ret == EOF && feof(f))
8535 			break;
8536 		if (ret != 3) {
8537 			pr_warn("failed to read kallsyms entry: %d\n", ret);
8538 			err = -EINVAL;
8539 			break;
8540 		}
8541 
8542 		err = cb(sym_addr, sym_type, sym_name, ctx);
8543 		if (err)
8544 			break;
8545 	}
8546 
8547 	fclose(f);
8548 	return err;
8549 }
8550 
8551 static int kallsyms_cb(unsigned long long sym_addr, char sym_type,
8552 		       const char *sym_name, void *ctx)
8553 {
8554 	struct bpf_object *obj = ctx;
8555 	const struct btf_type *t;
8556 	struct extern_desc *ext;
8557 	const char *res;
8558 
8559 	res = strstr(sym_name, ".llvm.");
8560 	if (sym_type == 'd' && res)
8561 		ext = find_extern_by_name_with_len(obj, sym_name, res - sym_name);
8562 	else
8563 		ext = find_extern_by_name(obj, sym_name);
8564 	if (!ext || ext->type != EXT_KSYM)
8565 		return 0;
8566 
8567 	t = btf__type_by_id(obj->btf, ext->btf_id);
8568 	if (!btf_is_var(t))
8569 		return 0;
8570 
8571 	if (ext->is_set && ext->ksym.addr != sym_addr) {
8572 		pr_warn("extern (ksym) '%s': resolution is ambiguous: 0x%llx or 0x%llx\n",
8573 			sym_name, ext->ksym.addr, sym_addr);
8574 		return -EINVAL;
8575 	}
8576 	if (!ext->is_set) {
8577 		ext->is_set = true;
8578 		ext->ksym.addr = sym_addr;
8579 		pr_debug("extern (ksym) '%s': set to 0x%llx\n", sym_name, sym_addr);
8580 	}
8581 	return 0;
8582 }
8583 
8584 static int bpf_object__read_kallsyms_file(struct bpf_object *obj)
8585 {
8586 	return libbpf_kallsyms_parse(kallsyms_cb, obj);
8587 }
8588 
8589 static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
8590 			    __u16 kind, struct btf **res_btf,
8591 			    struct module_btf **res_mod_btf)
8592 {
8593 	struct module_btf *mod_btf;
8594 	struct btf *btf;
8595 	int i, id, err;
8596 
8597 	btf = obj->btf_vmlinux;
8598 	mod_btf = NULL;
8599 	id = btf__find_by_name_kind(btf, ksym_name, kind);
8600 
8601 	if (id == -ENOENT) {
8602 		err = load_module_btfs(obj);
8603 		if (err)
8604 			return err;
8605 
8606 		for (i = 0; i < obj->btf_module_cnt; i++) {
8607 			/* we assume module_btf's BTF FD is always >0 */
8608 			mod_btf = &obj->btf_modules[i];
8609 			btf = mod_btf->btf;
8610 			id = btf__find_by_name_kind_own(btf, ksym_name, kind);
8611 			if (id != -ENOENT)
8612 				break;
8613 		}
8614 	}
8615 	if (id <= 0)
8616 		return -ESRCH;
8617 
8618 	*res_btf = btf;
8619 	*res_mod_btf = mod_btf;
8620 	return id;
8621 }
8622 
8623 static int bpf_object__resolve_ksym_var_btf_id(struct bpf_object *obj,
8624 					       struct extern_desc *ext)
8625 {
8626 	const struct btf_type *targ_var, *targ_type;
8627 	__u32 targ_type_id, local_type_id;
8628 	struct module_btf *mod_btf = NULL;
8629 	const char *targ_var_name;
8630 	struct btf *btf = NULL;
8631 	int id, err;
8632 
8633 	id = find_ksym_btf_id(obj, ext->name, BTF_KIND_VAR, &btf, &mod_btf);
8634 	if (id < 0) {
8635 		if (id == -ESRCH && ext->is_weak)
8636 			return 0;
8637 		pr_warn("extern (var ksym) '%s': not found in kernel BTF\n",
8638 			ext->name);
8639 		return id;
8640 	}
8641 
8642 	/* find local type_id */
8643 	local_type_id = ext->ksym.type_id;
8644 
8645 	/* find target type_id */
8646 	targ_var = btf__type_by_id(btf, id);
8647 	targ_var_name = btf__name_by_offset(btf, targ_var->name_off);
8648 	targ_type = skip_mods_and_typedefs(btf, targ_var->type, &targ_type_id);
8649 
8650 	err = bpf_core_types_are_compat(obj->btf, local_type_id,
8651 					btf, targ_type_id);
8652 	if (err <= 0) {
8653 		const struct btf_type *local_type;
8654 		const char *targ_name, *local_name;
8655 
8656 		local_type = btf__type_by_id(obj->btf, local_type_id);
8657 		local_name = btf__name_by_offset(obj->btf, local_type->name_off);
8658 		targ_name = btf__name_by_offset(btf, targ_type->name_off);
8659 
8660 		pr_warn("extern (var ksym) '%s': incompatible types, expected [%d] %s %s, but kernel has [%d] %s %s\n",
8661 			ext->name, local_type_id,
8662 			btf_kind_str(local_type), local_name, targ_type_id,
8663 			btf_kind_str(targ_type), targ_name);
8664 		return -EINVAL;
8665 	}
8666 
8667 	ext->is_set = true;
8668 	ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
8669 	ext->ksym.kernel_btf_id = id;
8670 	pr_debug("extern (var ksym) '%s': resolved to [%d] %s %s\n",
8671 		 ext->name, id, btf_kind_str(targ_var), targ_var_name);
8672 
8673 	return 0;
8674 }
8675 
8676 static int bpf_object__resolve_ksym_func_btf_id(struct bpf_object *obj,
8677 						struct extern_desc *ext)
8678 {
8679 	int local_func_proto_id, kfunc_proto_id, kfunc_id;
8680 	struct module_btf *mod_btf = NULL;
8681 	const struct btf_type *kern_func;
8682 	struct btf *kern_btf = NULL;
8683 	int ret;
8684 
8685 	local_func_proto_id = ext->ksym.type_id;
8686 
8687 	kfunc_id = find_ksym_btf_id(obj, ext->essent_name ?: ext->name, BTF_KIND_FUNC, &kern_btf,
8688 				    &mod_btf);
8689 	if (kfunc_id < 0) {
8690 		if (kfunc_id == -ESRCH && ext->is_weak)
8691 			return 0;
8692 		pr_warn("extern (func ksym) '%s': not found in kernel or module BTFs\n",
8693 			ext->name);
8694 		return kfunc_id;
8695 	}
8696 
8697 	kern_func = btf__type_by_id(kern_btf, kfunc_id);
8698 	kfunc_proto_id = kern_func->type;
8699 
8700 	ret = bpf_core_types_are_compat(obj->btf, local_func_proto_id,
8701 					kern_btf, kfunc_proto_id);
8702 	if (ret <= 0) {
8703 		if (ext->is_weak)
8704 			return 0;
8705 
8706 		pr_warn("extern (func ksym) '%s': func_proto [%d] incompatible with %s [%d]\n",
8707 			ext->name, local_func_proto_id,
8708 			mod_btf ? mod_btf->name : "vmlinux", kfunc_proto_id);
8709 		return -EINVAL;
8710 	}
8711 
8712 	/* set index for module BTF fd in fd_array, if unset */
8713 	if (mod_btf && !mod_btf->fd_array_idx) {
8714 		/* insn->off is s16 */
8715 		if (obj->fd_array_cnt == INT16_MAX) {
8716 			pr_warn("extern (func ksym) '%s': module BTF fd index %d too big to fit in bpf_insn offset\n",
8717 				ext->name, mod_btf->fd_array_idx);
8718 			return -E2BIG;
8719 		}
8720 		/* Cannot use index 0 for module BTF fd */
8721 		if (!obj->fd_array_cnt)
8722 			obj->fd_array_cnt = 1;
8723 
8724 		ret = libbpf_ensure_mem((void **)&obj->fd_array, &obj->fd_array_cap, sizeof(int),
8725 					obj->fd_array_cnt + 1);
8726 		if (ret)
8727 			return ret;
8728 		mod_btf->fd_array_idx = obj->fd_array_cnt;
8729 		/* we assume module BTF FD is always >0 */
8730 		obj->fd_array[obj->fd_array_cnt++] = mod_btf->fd;
8731 	}
8732 
8733 	ext->is_set = true;
8734 	ext->ksym.kernel_btf_id = kfunc_id;
8735 	ext->ksym.btf_fd_idx = mod_btf ? mod_btf->fd_array_idx : 0;
8736 	/* Also set kernel_btf_obj_fd to make sure that bpf_object__relocate_data()
8737 	 * populates FD into ld_imm64 insn when it's used to point to kfunc.
8738 	 * {kernel_btf_id, btf_fd_idx} -> fixup bpf_call.
8739 	 * {kernel_btf_id, kernel_btf_obj_fd} -> fixup ld_imm64.
8740 	 */
8741 	ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
8742 	pr_debug("extern (func ksym) '%s': resolved to %s [%d]\n",
8743 		 ext->name, mod_btf ? mod_btf->name : "vmlinux", kfunc_id);
8744 
8745 	return 0;
8746 }
8747 
8748 static int bpf_object__resolve_ksyms_btf_id(struct bpf_object *obj)
8749 {
8750 	const struct btf_type *t;
8751 	struct extern_desc *ext;
8752 	int i, err;
8753 
8754 	for (i = 0; i < obj->nr_extern; i++) {
8755 		ext = &obj->externs[i];
8756 		if (ext->type != EXT_KSYM || !ext->ksym.type_id)
8757 			continue;
8758 
8759 		if (obj->gen_loader) {
8760 			ext->is_set = true;
8761 			ext->ksym.kernel_btf_obj_fd = 0;
8762 			ext->ksym.kernel_btf_id = 0;
8763 			continue;
8764 		}
8765 		t = btf__type_by_id(obj->btf, ext->btf_id);
8766 		if (btf_is_var(t))
8767 			err = bpf_object__resolve_ksym_var_btf_id(obj, ext);
8768 		else
8769 			err = bpf_object__resolve_ksym_func_btf_id(obj, ext);
8770 		if (err)
8771 			return err;
8772 	}
8773 	return 0;
8774 }
8775 
8776 static int bpf_object__resolve_externs(struct bpf_object *obj,
8777 				       const char *extra_kconfig)
8778 {
8779 	bool need_config = false, need_kallsyms = false;
8780 	bool need_vmlinux_btf = false;
8781 	struct extern_desc *ext;
8782 	void *kcfg_data = NULL;
8783 	int err, i;
8784 
8785 	if (obj->nr_extern == 0)
8786 		return 0;
8787 
8788 	if (obj->kconfig_map_idx >= 0)
8789 		kcfg_data = obj->maps[obj->kconfig_map_idx].mmaped;
8790 
8791 	for (i = 0; i < obj->nr_extern; i++) {
8792 		ext = &obj->externs[i];
8793 
8794 		if (ext->type == EXT_KSYM) {
8795 			if (ext->ksym.type_id)
8796 				need_vmlinux_btf = true;
8797 			else
8798 				need_kallsyms = true;
8799 			continue;
8800 		} else if (ext->type == EXT_KCFG) {
8801 			void *ext_ptr = kcfg_data + ext->kcfg.data_off;
8802 			__u64 value = 0;
8803 
8804 			/* Kconfig externs need actual /proc/config.gz */
8805 			if (str_has_pfx(ext->name, "CONFIG_")) {
8806 				need_config = true;
8807 				continue;
8808 			}
8809 
8810 			/* Virtual kcfg externs are customly handled by libbpf */
8811 			if (strcmp(ext->name, "LINUX_KERNEL_VERSION") == 0) {
8812 				value = get_kernel_version();
8813 				if (!value) {
8814 					pr_warn("extern (kcfg) '%s': failed to get kernel version\n", ext->name);
8815 					return -EINVAL;
8816 				}
8817 			} else if (strcmp(ext->name, "LINUX_HAS_BPF_COOKIE") == 0) {
8818 				value = kernel_supports(obj, FEAT_BPF_COOKIE);
8819 			} else if (strcmp(ext->name, "LINUX_HAS_SYSCALL_WRAPPER") == 0) {
8820 				value = kernel_supports(obj, FEAT_SYSCALL_WRAPPER);
8821 			} else if (!str_has_pfx(ext->name, "LINUX_") || !ext->is_weak) {
8822 				/* Currently libbpf supports only CONFIG_ and LINUX_ prefixed
8823 				 * __kconfig externs, where LINUX_ ones are virtual and filled out
8824 				 * customly by libbpf (their values don't come from Kconfig).
8825 				 * If LINUX_xxx variable is not recognized by libbpf, but is marked
8826 				 * __weak, it defaults to zero value, just like for CONFIG_xxx
8827 				 * externs.
8828 				 */
8829 				pr_warn("extern (kcfg) '%s': unrecognized virtual extern\n", ext->name);
8830 				return -EINVAL;
8831 			}
8832 
8833 			err = set_kcfg_value_num(ext, ext_ptr, value);
8834 			if (err)
8835 				return err;
8836 			pr_debug("extern (kcfg) '%s': set to 0x%llx\n",
8837 				 ext->name, (long long)value);
8838 		} else {
8839 			pr_warn("extern '%s': unrecognized extern kind\n", ext->name);
8840 			return -EINVAL;
8841 		}
8842 	}
8843 	if (need_config && extra_kconfig) {
8844 		err = bpf_object__read_kconfig_mem(obj, extra_kconfig, kcfg_data);
8845 		if (err)
8846 			return -EINVAL;
8847 		need_config = false;
8848 		for (i = 0; i < obj->nr_extern; i++) {
8849 			ext = &obj->externs[i];
8850 			if (ext->type == EXT_KCFG && !ext->is_set) {
8851 				need_config = true;
8852 				break;
8853 			}
8854 		}
8855 	}
8856 	if (need_config) {
8857 		err = bpf_object__read_kconfig_file(obj, kcfg_data);
8858 		if (err)
8859 			return -EINVAL;
8860 	}
8861 	if (need_kallsyms) {
8862 		err = bpf_object__read_kallsyms_file(obj);
8863 		if (err)
8864 			return -EINVAL;
8865 	}
8866 	if (need_vmlinux_btf) {
8867 		err = bpf_object__resolve_ksyms_btf_id(obj);
8868 		if (err)
8869 			return -EINVAL;
8870 	}
8871 	for (i = 0; i < obj->nr_extern; i++) {
8872 		ext = &obj->externs[i];
8873 
8874 		if (!ext->is_set && !ext->is_weak) {
8875 			pr_warn("extern '%s' (strong): not resolved\n", ext->name);
8876 			return -ESRCH;
8877 		} else if (!ext->is_set) {
8878 			pr_debug("extern '%s' (weak): not resolved, defaulting to zero\n",
8879 				 ext->name);
8880 		}
8881 	}
8882 
8883 	return 0;
8884 }
8885 
8886 static void bpf_map_prepare_vdata(const struct bpf_map *map)
8887 {
8888 	const struct btf_type *type;
8889 	struct bpf_struct_ops *st_ops;
8890 	__u32 i;
8891 
8892 	st_ops = map->st_ops;
8893 	type = btf__type_by_id(map->obj->btf, st_ops->type_id);
8894 	for (i = 0; i < btf_vlen(type); i++) {
8895 		struct bpf_program *prog = st_ops->progs[i];
8896 		void *kern_data;
8897 		int prog_fd;
8898 
8899 		if (!prog)
8900 			continue;
8901 
8902 		prog_fd = bpf_program__fd(prog);
8903 		kern_data = st_ops->kern_vdata + st_ops->kern_func_off[i];
8904 		*(unsigned long *)kern_data = prog_fd;
8905 	}
8906 }
8907 
8908 static int bpf_object_prepare_struct_ops(struct bpf_object *obj)
8909 {
8910 	struct bpf_map *map;
8911 	int i;
8912 
8913 	for (i = 0; i < obj->nr_maps; i++) {
8914 		map = &obj->maps[i];
8915 
8916 		if (!bpf_map__is_struct_ops(map))
8917 			continue;
8918 
8919 		if (!map->autocreate)
8920 			continue;
8921 
8922 		bpf_map_prepare_vdata(map);
8923 	}
8924 
8925 	return 0;
8926 }
8927 
8928 static void bpf_object_unpin(struct bpf_object *obj)
8929 {
8930 	int i;
8931 
8932 	/* unpin any maps that were auto-pinned during load */
8933 	for (i = 0; i < obj->nr_maps; i++)
8934 		if (obj->maps[i].pinned && !obj->maps[i].reused)
8935 			bpf_map__unpin(&obj->maps[i], NULL);
8936 }
8937 
8938 static void bpf_object_post_load_cleanup(struct bpf_object *obj)
8939 {
8940 	int i;
8941 
8942 	/* clean up fd_array */
8943 	zfree(&obj->fd_array);
8944 
8945 	/* clean up module BTFs */
8946 	for (i = 0; i < obj->btf_module_cnt; i++) {
8947 		close(obj->btf_modules[i].fd);
8948 		btf__free(obj->btf_modules[i].btf);
8949 		free(obj->btf_modules[i].name);
8950 	}
8951 	obj->btf_module_cnt = 0;
8952 	zfree(&obj->btf_modules);
8953 
8954 	/* clean up vmlinux BTF */
8955 	btf__free(obj->btf_vmlinux);
8956 	obj->btf_vmlinux = NULL;
8957 }
8958 
8959 static int bpf_object_prepare(struct bpf_object *obj, const char *target_btf_path)
8960 {
8961 	int err;
8962 
8963 	if (obj->state >= OBJ_PREPARED) {
8964 		pr_warn("object '%s': prepare loading can't be attempted twice\n", obj->name);
8965 		return -EINVAL;
8966 	}
8967 
8968 	err = bpf_object_prepare_token(obj);
8969 	err = err ? : bpf_object__probe_loading(obj);
8970 	err = err ? : bpf_object__load_vmlinux_btf(obj, false);
8971 	err = err ? : bpf_object__resolve_externs(obj, obj->kconfig);
8972 	err = err ? : bpf_object__sanitize_maps(obj);
8973 	err = err ? : bpf_object__init_kern_struct_ops_maps(obj);
8974 	err = err ? : bpf_object_adjust_struct_ops_autoload(obj);
8975 	err = err ? : bpf_object__relocate(obj, obj->btf_custom_path ? : target_btf_path);
8976 	err = err ? : bpf_object__sanitize_and_load_btf(obj);
8977 	err = err ? : bpf_object__create_maps(obj);
8978 	err = err ? : bpf_object_prepare_progs(obj);
8979 
8980 	if (err) {
8981 		bpf_object_unpin(obj);
8982 		bpf_object_unload(obj);
8983 		obj->state = OBJ_LOADED;
8984 		return err;
8985 	}
8986 
8987 	obj->state = OBJ_PREPARED;
8988 	return 0;
8989 }
8990 
8991 static int bpf_object_load(struct bpf_object *obj, int extra_log_level, const char *target_btf_path)
8992 {
8993 	int err;
8994 
8995 	if (!obj)
8996 		return libbpf_err(-EINVAL);
8997 
8998 	if (obj->state >= OBJ_LOADED) {
8999 		pr_warn("object '%s': load can't be attempted twice\n", obj->name);
9000 		return libbpf_err(-EINVAL);
9001 	}
9002 
9003 	/* Disallow kernel loading programs of non-native endianness but
9004 	 * permit cross-endian creation of "light skeleton".
9005 	 */
9006 	if (obj->gen_loader) {
9007 		bpf_gen__init(obj->gen_loader, extra_log_level, obj->nr_programs, obj->nr_maps);
9008 	} else if (!is_native_endianness(obj)) {
9009 		pr_warn("object '%s': loading non-native endianness is unsupported\n", obj->name);
9010 		return libbpf_err(-LIBBPF_ERRNO__ENDIAN);
9011 	}
9012 
9013 	if (obj->state < OBJ_PREPARED) {
9014 		err = bpf_object_prepare(obj, target_btf_path);
9015 		if (err)
9016 			return libbpf_err(err);
9017 	}
9018 	err = bpf_object__load_progs(obj, extra_log_level);
9019 	err = err ? : bpf_object_init_prog_arrays(obj);
9020 	err = err ? : bpf_object_prepare_struct_ops(obj);
9021 
9022 	if (obj->gen_loader) {
9023 		/* reset FDs */
9024 		if (obj->btf)
9025 			btf__set_fd(obj->btf, -1);
9026 		if (!err)
9027 			err = bpf_gen__finish(obj->gen_loader, obj->nr_programs, obj->nr_maps);
9028 	}
9029 
9030 	bpf_object_post_load_cleanup(obj);
9031 	obj->state = OBJ_LOADED; /* doesn't matter if successfully or not */
9032 
9033 	if (err) {
9034 		bpf_object_unpin(obj);
9035 		bpf_object_unload(obj);
9036 		pr_warn("failed to load object '%s'\n", obj->path);
9037 		return libbpf_err(err);
9038 	}
9039 
9040 	return 0;
9041 }
9042 
9043 int bpf_object__prepare(struct bpf_object *obj)
9044 {
9045 	return libbpf_err(bpf_object_prepare(obj, NULL));
9046 }
9047 
9048 int bpf_object__load(struct bpf_object *obj)
9049 {
9050 	return bpf_object_load(obj, 0, NULL);
9051 }
9052 
9053 static int make_parent_dir(const char *path)
9054 {
9055 	char *dname, *dir;
9056 	int err = 0;
9057 
9058 	dname = strdup(path);
9059 	if (dname == NULL)
9060 		return -ENOMEM;
9061 
9062 	dir = dirname(dname);
9063 	if (mkdir(dir, 0700) && errno != EEXIST)
9064 		err = -errno;
9065 
9066 	free(dname);
9067 	if (err) {
9068 		pr_warn("failed to mkdir %s: %s\n", path, errstr(err));
9069 	}
9070 	return err;
9071 }
9072 
9073 static int check_path(const char *path)
9074 {
9075 	struct statfs st_fs;
9076 	char *dname, *dir;
9077 	int err = 0;
9078 
9079 	if (path == NULL)
9080 		return -EINVAL;
9081 
9082 	dname = strdup(path);
9083 	if (dname == NULL)
9084 		return -ENOMEM;
9085 
9086 	dir = dirname(dname);
9087 	if (statfs(dir, &st_fs)) {
9088 		pr_warn("failed to statfs %s: %s\n", dir, errstr(errno));
9089 		err = -errno;
9090 	}
9091 	free(dname);
9092 
9093 	if (!err && st_fs.f_type != BPF_FS_MAGIC) {
9094 		pr_warn("specified path %s is not on BPF FS\n", path);
9095 		err = -EINVAL;
9096 	}
9097 
9098 	return err;
9099 }
9100 
9101 int bpf_program__pin(struct bpf_program *prog, const char *path)
9102 {
9103 	int err;
9104 
9105 	if (prog->fd < 0) {
9106 		pr_warn("prog '%s': can't pin program that wasn't loaded\n", prog->name);
9107 		return libbpf_err(-EINVAL);
9108 	}
9109 
9110 	err = make_parent_dir(path);
9111 	if (err)
9112 		return libbpf_err(err);
9113 
9114 	err = check_path(path);
9115 	if (err)
9116 		return libbpf_err(err);
9117 
9118 	if (bpf_obj_pin(prog->fd, path)) {
9119 		err = -errno;
9120 		pr_warn("prog '%s': failed to pin at '%s': %s\n", prog->name, path, errstr(err));
9121 		return libbpf_err(err);
9122 	}
9123 
9124 	pr_debug("prog '%s': pinned at '%s'\n", prog->name, path);
9125 	return 0;
9126 }
9127 
9128 int bpf_program__unpin(struct bpf_program *prog, const char *path)
9129 {
9130 	int err;
9131 
9132 	if (prog->fd < 0) {
9133 		pr_warn("prog '%s': can't unpin program that wasn't loaded\n", prog->name);
9134 		return libbpf_err(-EINVAL);
9135 	}
9136 
9137 	err = check_path(path);
9138 	if (err)
9139 		return libbpf_err(err);
9140 
9141 	err = unlink(path);
9142 	if (err)
9143 		return libbpf_err(-errno);
9144 
9145 	pr_debug("prog '%s': unpinned from '%s'\n", prog->name, path);
9146 	return 0;
9147 }
9148 
9149 int bpf_map__pin(struct bpf_map *map, const char *path)
9150 {
9151 	int err;
9152 
9153 	if (map == NULL) {
9154 		pr_warn("invalid map pointer\n");
9155 		return libbpf_err(-EINVAL);
9156 	}
9157 
9158 	if (map->fd < 0) {
9159 		pr_warn("map '%s': can't pin BPF map without FD (was it created?)\n", map->name);
9160 		return libbpf_err(-EINVAL);
9161 	}
9162 
9163 	if (map->pin_path) {
9164 		if (path && strcmp(path, map->pin_path)) {
9165 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
9166 				bpf_map__name(map), map->pin_path, path);
9167 			return libbpf_err(-EINVAL);
9168 		} else if (map->pinned) {
9169 			pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
9170 				 bpf_map__name(map), map->pin_path);
9171 			return 0;
9172 		}
9173 	} else {
9174 		if (!path) {
9175 			pr_warn("missing a path to pin map '%s' at\n",
9176 				bpf_map__name(map));
9177 			return libbpf_err(-EINVAL);
9178 		} else if (map->pinned) {
9179 			pr_warn("map '%s' already pinned\n", bpf_map__name(map));
9180 			return libbpf_err(-EEXIST);
9181 		}
9182 
9183 		map->pin_path = strdup(path);
9184 		if (!map->pin_path) {
9185 			err = -errno;
9186 			goto out_err;
9187 		}
9188 	}
9189 
9190 	err = make_parent_dir(map->pin_path);
9191 	if (err)
9192 		return libbpf_err(err);
9193 
9194 	err = check_path(map->pin_path);
9195 	if (err)
9196 		return libbpf_err(err);
9197 
9198 	if (bpf_obj_pin(map->fd, map->pin_path)) {
9199 		err = -errno;
9200 		goto out_err;
9201 	}
9202 
9203 	map->pinned = true;
9204 	pr_debug("pinned map '%s'\n", map->pin_path);
9205 
9206 	return 0;
9207 
9208 out_err:
9209 	pr_warn("failed to pin map: %s\n", errstr(err));
9210 	return libbpf_err(err);
9211 }
9212 
9213 int bpf_map__unpin(struct bpf_map *map, const char *path)
9214 {
9215 	int err;
9216 
9217 	if (map == NULL) {
9218 		pr_warn("invalid map pointer\n");
9219 		return libbpf_err(-EINVAL);
9220 	}
9221 
9222 	if (map->pin_path) {
9223 		if (path && strcmp(path, map->pin_path)) {
9224 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
9225 				bpf_map__name(map), map->pin_path, path);
9226 			return libbpf_err(-EINVAL);
9227 		}
9228 		path = map->pin_path;
9229 	} else if (!path) {
9230 		pr_warn("no path to unpin map '%s' from\n",
9231 			bpf_map__name(map));
9232 		return libbpf_err(-EINVAL);
9233 	}
9234 
9235 	err = check_path(path);
9236 	if (err)
9237 		return libbpf_err(err);
9238 
9239 	err = unlink(path);
9240 	if (err != 0)
9241 		return libbpf_err(-errno);
9242 
9243 	map->pinned = false;
9244 	pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path);
9245 
9246 	return 0;
9247 }
9248 
9249 int bpf_map__set_pin_path(struct bpf_map *map, const char *path)
9250 {
9251 	char *new = NULL;
9252 
9253 	if (path) {
9254 		new = strdup(path);
9255 		if (!new)
9256 			return libbpf_err(-errno);
9257 	}
9258 
9259 	free(map->pin_path);
9260 	map->pin_path = new;
9261 	return 0;
9262 }
9263 
9264 __alias(bpf_map__pin_path)
9265 const char *bpf_map__get_pin_path(const struct bpf_map *map);
9266 
9267 const char *bpf_map__pin_path(const struct bpf_map *map)
9268 {
9269 	return map->pin_path;
9270 }
9271 
9272 bool bpf_map__is_pinned(const struct bpf_map *map)
9273 {
9274 	return map->pinned;
9275 }
9276 
9277 static void sanitize_pin_path(char *s)
9278 {
9279 	/* bpffs disallows periods in path names */
9280 	while (*s) {
9281 		if (*s == '.')
9282 			*s = '_';
9283 		s++;
9284 	}
9285 }
9286 
9287 int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
9288 {
9289 	struct bpf_map *map;
9290 	int err;
9291 
9292 	if (!obj)
9293 		return libbpf_err(-ENOENT);
9294 
9295 	if (obj->state < OBJ_PREPARED) {
9296 		pr_warn("object not yet loaded; load it first\n");
9297 		return libbpf_err(-ENOENT);
9298 	}
9299 
9300 	bpf_object__for_each_map(map, obj) {
9301 		char *pin_path = NULL;
9302 		char buf[PATH_MAX];
9303 
9304 		if (!map->autocreate)
9305 			continue;
9306 
9307 		if (path) {
9308 			err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
9309 			if (err)
9310 				goto err_unpin_maps;
9311 			sanitize_pin_path(buf);
9312 			pin_path = buf;
9313 		} else if (!map->pin_path) {
9314 			continue;
9315 		}
9316 
9317 		err = bpf_map__pin(map, pin_path);
9318 		if (err)
9319 			goto err_unpin_maps;
9320 	}
9321 
9322 	return 0;
9323 
9324 err_unpin_maps:
9325 	while ((map = bpf_object__prev_map(obj, map))) {
9326 		if (!map->pin_path)
9327 			continue;
9328 
9329 		bpf_map__unpin(map, NULL);
9330 	}
9331 
9332 	return libbpf_err(err);
9333 }
9334 
9335 int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
9336 {
9337 	struct bpf_map *map;
9338 	int err;
9339 
9340 	if (!obj)
9341 		return libbpf_err(-ENOENT);
9342 
9343 	bpf_object__for_each_map(map, obj) {
9344 		char *pin_path = NULL;
9345 		char buf[PATH_MAX];
9346 
9347 		if (path) {
9348 			err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
9349 			if (err)
9350 				return libbpf_err(err);
9351 			sanitize_pin_path(buf);
9352 			pin_path = buf;
9353 		} else if (!map->pin_path) {
9354 			continue;
9355 		}
9356 
9357 		err = bpf_map__unpin(map, pin_path);
9358 		if (err)
9359 			return libbpf_err(err);
9360 	}
9361 
9362 	return 0;
9363 }
9364 
9365 int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
9366 {
9367 	struct bpf_program *prog;
9368 	char buf[PATH_MAX];
9369 	int err;
9370 
9371 	if (!obj)
9372 		return libbpf_err(-ENOENT);
9373 
9374 	if (obj->state < OBJ_LOADED) {
9375 		pr_warn("object not yet loaded; load it first\n");
9376 		return libbpf_err(-ENOENT);
9377 	}
9378 
9379 	bpf_object__for_each_program(prog, obj) {
9380 		err = pathname_concat(buf, sizeof(buf), path, prog->name);
9381 		if (err)
9382 			goto err_unpin_programs;
9383 
9384 		err = bpf_program__pin(prog, buf);
9385 		if (err)
9386 			goto err_unpin_programs;
9387 	}
9388 
9389 	return 0;
9390 
9391 err_unpin_programs:
9392 	while ((prog = bpf_object__prev_program(obj, prog))) {
9393 		if (pathname_concat(buf, sizeof(buf), path, prog->name))
9394 			continue;
9395 
9396 		bpf_program__unpin(prog, buf);
9397 	}
9398 
9399 	return libbpf_err(err);
9400 }
9401 
9402 int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
9403 {
9404 	struct bpf_program *prog;
9405 	int err;
9406 
9407 	if (!obj)
9408 		return libbpf_err(-ENOENT);
9409 
9410 	bpf_object__for_each_program(prog, obj) {
9411 		char buf[PATH_MAX];
9412 
9413 		err = pathname_concat(buf, sizeof(buf), path, prog->name);
9414 		if (err)
9415 			return libbpf_err(err);
9416 
9417 		err = bpf_program__unpin(prog, buf);
9418 		if (err)
9419 			return libbpf_err(err);
9420 	}
9421 
9422 	return 0;
9423 }
9424 
9425 int bpf_object__pin(struct bpf_object *obj, const char *path)
9426 {
9427 	int err;
9428 
9429 	err = bpf_object__pin_maps(obj, path);
9430 	if (err)
9431 		return libbpf_err(err);
9432 
9433 	err = bpf_object__pin_programs(obj, path);
9434 	if (err) {
9435 		bpf_object__unpin_maps(obj, path);
9436 		return libbpf_err(err);
9437 	}
9438 
9439 	return 0;
9440 }
9441 
9442 int bpf_object__unpin(struct bpf_object *obj, const char *path)
9443 {
9444 	int err;
9445 
9446 	err = bpf_object__unpin_programs(obj, path);
9447 	if (err)
9448 		return libbpf_err(err);
9449 
9450 	err = bpf_object__unpin_maps(obj, path);
9451 	if (err)
9452 		return libbpf_err(err);
9453 
9454 	return 0;
9455 }
9456 
9457 static void bpf_map__destroy(struct bpf_map *map)
9458 {
9459 	if (map->inner_map) {
9460 		bpf_map__destroy(map->inner_map);
9461 		zfree(&map->inner_map);
9462 	}
9463 
9464 	zfree(&map->init_slots);
9465 	map->init_slots_sz = 0;
9466 
9467 	if (map->mmaped && map->mmaped != map->obj->arena_data)
9468 		munmap(map->mmaped, bpf_map_mmap_sz(map));
9469 	map->mmaped = NULL;
9470 
9471 	if (map->st_ops) {
9472 		zfree(&map->st_ops->data);
9473 		zfree(&map->st_ops->progs);
9474 		zfree(&map->st_ops->kern_func_off);
9475 		zfree(&map->st_ops);
9476 	}
9477 
9478 	zfree(&map->name);
9479 	zfree(&map->real_name);
9480 	zfree(&map->pin_path);
9481 
9482 	if (map->fd >= 0)
9483 		zclose(map->fd);
9484 }
9485 
9486 void bpf_object__close(struct bpf_object *obj)
9487 {
9488 	size_t i;
9489 
9490 	if (IS_ERR_OR_NULL(obj))
9491 		return;
9492 
9493 	/*
9494 	 * if user called bpf_object__prepare() without ever getting to
9495 	 * bpf_object__load(), we need to clean up stuff that is normally
9496 	 * cleaned up at the end of loading step
9497 	 */
9498 	bpf_object_post_load_cleanup(obj);
9499 
9500 	usdt_manager_free(obj->usdt_man);
9501 	obj->usdt_man = NULL;
9502 
9503 	bpf_gen__free(obj->gen_loader);
9504 	bpf_object__elf_finish(obj);
9505 	bpf_object_unload(obj);
9506 	btf__free(obj->btf);
9507 	btf__free(obj->btf_vmlinux);
9508 	btf_ext__free(obj->btf_ext);
9509 
9510 	for (i = 0; i < obj->nr_maps; i++)
9511 		bpf_map__destroy(&obj->maps[i]);
9512 
9513 	zfree(&obj->btf_custom_path);
9514 	zfree(&obj->kconfig);
9515 
9516 	for (i = 0; i < obj->nr_extern; i++) {
9517 		zfree(&obj->externs[i].name);
9518 		zfree(&obj->externs[i].essent_name);
9519 	}
9520 
9521 	zfree(&obj->externs);
9522 	obj->nr_extern = 0;
9523 
9524 	zfree(&obj->maps);
9525 	obj->nr_maps = 0;
9526 
9527 	if (obj->programs && obj->nr_programs) {
9528 		for (i = 0; i < obj->nr_programs; i++)
9529 			bpf_program__exit(&obj->programs[i]);
9530 	}
9531 	zfree(&obj->programs);
9532 
9533 	zfree(&obj->feat_cache);
9534 	zfree(&obj->token_path);
9535 	if (obj->token_fd > 0)
9536 		close(obj->token_fd);
9537 
9538 	zfree(&obj->arena_data);
9539 
9540 	zfree(&obj->jumptables_data);
9541 	obj->jumptables_data_sz = 0;
9542 
9543 	for (i = 0; i < obj->jumptable_map_cnt; i++)
9544 		close(obj->jumptable_maps[i].fd);
9545 	zfree(&obj->jumptable_maps);
9546 
9547 	free(obj);
9548 }
9549 
9550 const char *bpf_object__name(const struct bpf_object *obj)
9551 {
9552 	return obj ? obj->name : libbpf_err_ptr(-EINVAL);
9553 }
9554 
9555 unsigned int bpf_object__kversion(const struct bpf_object *obj)
9556 {
9557 	return obj ? obj->kern_version : 0;
9558 }
9559 
9560 int bpf_object__token_fd(const struct bpf_object *obj)
9561 {
9562 	return obj->token_fd ?: -1;
9563 }
9564 
9565 struct btf *bpf_object__btf(const struct bpf_object *obj)
9566 {
9567 	return obj ? obj->btf : NULL;
9568 }
9569 
9570 int bpf_object__btf_fd(const struct bpf_object *obj)
9571 {
9572 	return obj->btf ? btf__fd(obj->btf) : -1;
9573 }
9574 
9575 int bpf_object__set_kversion(struct bpf_object *obj, __u32 kern_version)
9576 {
9577 	if (obj->state >= OBJ_LOADED)
9578 		return libbpf_err(-EINVAL);
9579 
9580 	obj->kern_version = kern_version;
9581 
9582 	return 0;
9583 }
9584 
9585 int bpf_object__gen_loader(struct bpf_object *obj, struct gen_loader_opts *opts)
9586 {
9587 	struct bpf_gen *gen;
9588 
9589 	if (!opts)
9590 		return libbpf_err(-EFAULT);
9591 	if (!OPTS_VALID(opts, gen_loader_opts))
9592 		return libbpf_err(-EINVAL);
9593 	gen = calloc(1, sizeof(*gen));
9594 	if (!gen)
9595 		return libbpf_err(-ENOMEM);
9596 	gen->opts = opts;
9597 	gen->swapped_endian = !is_native_endianness(obj);
9598 	obj->gen_loader = gen;
9599 	return 0;
9600 }
9601 
9602 static struct bpf_program *
9603 __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
9604 		    bool forward)
9605 {
9606 	size_t nr_programs = obj->nr_programs;
9607 	ssize_t idx;
9608 
9609 	if (!nr_programs)
9610 		return NULL;
9611 
9612 	if (!p)
9613 		/* Iter from the beginning */
9614 		return forward ? &obj->programs[0] :
9615 			&obj->programs[nr_programs - 1];
9616 
9617 	if (p->obj != obj) {
9618 		pr_warn("error: program handler doesn't match object\n");
9619 		return errno = EINVAL, NULL;
9620 	}
9621 
9622 	idx = (p - obj->programs) + (forward ? 1 : -1);
9623 	if (idx >= obj->nr_programs || idx < 0)
9624 		return NULL;
9625 	return &obj->programs[idx];
9626 }
9627 
9628 struct bpf_program *
9629 bpf_object__next_program(const struct bpf_object *obj, struct bpf_program *prev)
9630 {
9631 	struct bpf_program *prog = prev;
9632 
9633 	do {
9634 		prog = __bpf_program__iter(prog, obj, true);
9635 	} while (prog && prog_is_subprog(obj, prog));
9636 
9637 	return prog;
9638 }
9639 
9640 struct bpf_program *
9641 bpf_object__prev_program(const struct bpf_object *obj, struct bpf_program *next)
9642 {
9643 	struct bpf_program *prog = next;
9644 
9645 	do {
9646 		prog = __bpf_program__iter(prog, obj, false);
9647 	} while (prog && prog_is_subprog(obj, prog));
9648 
9649 	return prog;
9650 }
9651 
9652 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
9653 {
9654 	prog->prog_ifindex = ifindex;
9655 }
9656 
9657 const char *bpf_program__name(const struct bpf_program *prog)
9658 {
9659 	return prog->name;
9660 }
9661 
9662 const char *bpf_program__section_name(const struct bpf_program *prog)
9663 {
9664 	return prog->sec_name;
9665 }
9666 
9667 bool bpf_program__autoload(const struct bpf_program *prog)
9668 {
9669 	return prog->autoload;
9670 }
9671 
9672 int bpf_program__set_autoload(struct bpf_program *prog, bool autoload)
9673 {
9674 	if (prog->obj->state >= OBJ_LOADED)
9675 		return libbpf_err(-EINVAL);
9676 
9677 	prog->autoload = autoload;
9678 	return 0;
9679 }
9680 
9681 bool bpf_program__autoattach(const struct bpf_program *prog)
9682 {
9683 	return prog->autoattach;
9684 }
9685 
9686 void bpf_program__set_autoattach(struct bpf_program *prog, bool autoattach)
9687 {
9688 	prog->autoattach = autoattach;
9689 }
9690 
9691 const struct bpf_insn *bpf_program__insns(const struct bpf_program *prog)
9692 {
9693 	return prog->insns;
9694 }
9695 
9696 size_t bpf_program__insn_cnt(const struct bpf_program *prog)
9697 {
9698 	return prog->insns_cnt;
9699 }
9700 
9701 int bpf_program__set_insns(struct bpf_program *prog,
9702 			   struct bpf_insn *new_insns, size_t new_insn_cnt)
9703 {
9704 	struct bpf_insn *insns;
9705 
9706 	if (prog->obj->state >= OBJ_LOADED)
9707 		return libbpf_err(-EBUSY);
9708 
9709 	insns = libbpf_reallocarray(prog->insns, new_insn_cnt, sizeof(*insns));
9710 	/* NULL is a valid return from reallocarray if the new count is zero */
9711 	if (!insns && new_insn_cnt) {
9712 		pr_warn("prog '%s': failed to realloc prog code\n", prog->name);
9713 		return libbpf_err(-ENOMEM);
9714 	}
9715 	memcpy(insns, new_insns, new_insn_cnt * sizeof(*insns));
9716 
9717 	prog->insns = insns;
9718 	prog->insns_cnt = new_insn_cnt;
9719 	return 0;
9720 }
9721 
9722 int bpf_program__fd(const struct bpf_program *prog)
9723 {
9724 	if (!prog)
9725 		return libbpf_err(-EINVAL);
9726 
9727 	if (prog->fd < 0)
9728 		return libbpf_err(-ENOENT);
9729 
9730 	return prog->fd;
9731 }
9732 
9733 __alias(bpf_program__type)
9734 enum bpf_prog_type bpf_program__get_type(const struct bpf_program *prog);
9735 
9736 enum bpf_prog_type bpf_program__type(const struct bpf_program *prog)
9737 {
9738 	return prog->type;
9739 }
9740 
9741 static size_t custom_sec_def_cnt;
9742 static struct bpf_sec_def *custom_sec_defs;
9743 static struct bpf_sec_def custom_fallback_def;
9744 static bool has_custom_fallback_def;
9745 static int last_custom_sec_def_handler_id;
9746 
9747 int bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
9748 {
9749 	if (prog->obj->state >= OBJ_LOADED)
9750 		return libbpf_err(-EBUSY);
9751 
9752 	/* if type is not changed, do nothing */
9753 	if (prog->type == type)
9754 		return 0;
9755 
9756 	prog->type = type;
9757 
9758 	/* If a program type was changed, we need to reset associated SEC()
9759 	 * handler, as it will be invalid now. The only exception is a generic
9760 	 * fallback handler, which by definition is program type-agnostic and
9761 	 * is a catch-all custom handler, optionally set by the application,
9762 	 * so should be able to handle any type of BPF program.
9763 	 */
9764 	if (prog->sec_def != &custom_fallback_def)
9765 		prog->sec_def = NULL;
9766 	return 0;
9767 }
9768 
9769 __alias(bpf_program__expected_attach_type)
9770 enum bpf_attach_type bpf_program__get_expected_attach_type(const struct bpf_program *prog);
9771 
9772 enum bpf_attach_type bpf_program__expected_attach_type(const struct bpf_program *prog)
9773 {
9774 	return prog->expected_attach_type;
9775 }
9776 
9777 int bpf_program__set_expected_attach_type(struct bpf_program *prog,
9778 					   enum bpf_attach_type type)
9779 {
9780 	if (prog->obj->state >= OBJ_LOADED)
9781 		return libbpf_err(-EBUSY);
9782 
9783 	prog->expected_attach_type = type;
9784 	return 0;
9785 }
9786 
9787 __u32 bpf_program__flags(const struct bpf_program *prog)
9788 {
9789 	return prog->prog_flags;
9790 }
9791 
9792 int bpf_program__set_flags(struct bpf_program *prog, __u32 flags)
9793 {
9794 	if (prog->obj->state >= OBJ_LOADED)
9795 		return libbpf_err(-EBUSY);
9796 
9797 	prog->prog_flags = flags;
9798 	return 0;
9799 }
9800 
9801 __u32 bpf_program__log_level(const struct bpf_program *prog)
9802 {
9803 	return prog->log_level;
9804 }
9805 
9806 int bpf_program__set_log_level(struct bpf_program *prog, __u32 log_level)
9807 {
9808 	if (prog->obj->state >= OBJ_LOADED)
9809 		return libbpf_err(-EBUSY);
9810 
9811 	prog->log_level = log_level;
9812 	return 0;
9813 }
9814 
9815 const char *bpf_program__log_buf(const struct bpf_program *prog, size_t *log_size)
9816 {
9817 	*log_size = prog->log_size;
9818 	return prog->log_buf;
9819 }
9820 
9821 int bpf_program__set_log_buf(struct bpf_program *prog, char *log_buf, size_t log_size)
9822 {
9823 	if (log_size && !log_buf)
9824 		return libbpf_err(-EINVAL);
9825 	if (prog->log_size > UINT_MAX)
9826 		return libbpf_err(-EINVAL);
9827 	if (prog->obj->state >= OBJ_LOADED)
9828 		return libbpf_err(-EBUSY);
9829 
9830 	prog->log_buf = log_buf;
9831 	prog->log_size = log_size;
9832 	return 0;
9833 }
9834 
9835 struct bpf_func_info *bpf_program__func_info(const struct bpf_program *prog)
9836 {
9837 	if (prog->func_info_rec_size != sizeof(struct bpf_func_info))
9838 		return libbpf_err_ptr(-EOPNOTSUPP);
9839 	return prog->func_info;
9840 }
9841 
9842 __u32 bpf_program__func_info_cnt(const struct bpf_program *prog)
9843 {
9844 	return prog->func_info_cnt;
9845 }
9846 
9847 struct bpf_line_info *bpf_program__line_info(const struct bpf_program *prog)
9848 {
9849 	if (prog->line_info_rec_size != sizeof(struct bpf_line_info))
9850 		return libbpf_err_ptr(-EOPNOTSUPP);
9851 	return prog->line_info;
9852 }
9853 
9854 __u32 bpf_program__line_info_cnt(const struct bpf_program *prog)
9855 {
9856 	return prog->line_info_cnt;
9857 }
9858 
9859 int bpf_program__clone(struct bpf_program *prog, const struct bpf_prog_load_opts *opts)
9860 {
9861 	LIBBPF_OPTS(bpf_prog_load_opts, attr);
9862 	struct bpf_object *obj;
9863 	const void *info;
9864 	__u32 info_cnt, info_rec_size;
9865 	int err, fd, prog_btf_fd;
9866 
9867 	if (!prog)
9868 		return libbpf_err(-EINVAL);
9869 
9870 	if (!OPTS_VALID(opts, bpf_prog_load_opts))
9871 		return libbpf_err(-EINVAL);
9872 
9873 	obj = prog->obj;
9874 	if (obj->state < OBJ_PREPARED)
9875 		return libbpf_err(-EINVAL);
9876 
9877 	/*
9878 	 * Caller-provided opts take priority; fall back to
9879 	 * prog/object defaults when the caller leaves them zero.
9880 	 */
9881 	attr.attach_prog_fd = OPTS_GET(opts, attach_prog_fd, 0) ?: prog->attach_prog_fd;
9882 	attr.prog_flags = OPTS_GET(opts, prog_flags, 0) ?: prog->prog_flags;
9883 	attr.prog_ifindex = OPTS_GET(opts, prog_ifindex, 0) ?: prog->prog_ifindex;
9884 	attr.kern_version = OPTS_GET(opts, kern_version, 0) ?: obj->kern_version;
9885 	attr.fd_array = OPTS_GET(opts, fd_array, NULL) ?: obj->fd_array;
9886 	attr.fd_array_cnt = OPTS_GET(opts, fd_array_cnt, 0) ?: obj->fd_array_cnt;
9887 	attr.token_fd = OPTS_GET(opts, token_fd, 0) ?: obj->token_fd;
9888 	if (attr.token_fd)
9889 		attr.prog_flags |= BPF_F_TOKEN_FD;
9890 
9891 	prog_btf_fd = OPTS_GET(opts, prog_btf_fd, 0);
9892 	if (!prog_btf_fd && obj->btf)
9893 		prog_btf_fd = btf__fd(obj->btf);
9894 
9895 	/* BTF func/line info: only pass if kernel supports it */
9896 	if (kernel_supports(obj, FEAT_BTF_FUNC) && prog_btf_fd > 0) {
9897 		attr.prog_btf_fd = prog_btf_fd;
9898 
9899 		/* func_info/line_info triples: all-or-nothing from caller */
9900 		info = OPTS_GET(opts, func_info, NULL);
9901 		info_cnt = OPTS_GET(opts, func_info_cnt, 0);
9902 		info_rec_size = OPTS_GET(opts, func_info_rec_size, 0);
9903 		if (!!info != !!info_cnt || !!info != !!info_rec_size) {
9904 			pr_warn("prog '%s': func_info, func_info_cnt, and func_info_rec_size must all be specified or all omitted\n",
9905 				prog->name);
9906 			return libbpf_err(-EINVAL);
9907 		}
9908 		attr.func_info = info ?: prog->func_info;
9909 		attr.func_info_cnt = info ? info_cnt : prog->func_info_cnt;
9910 		attr.func_info_rec_size = info ? info_rec_size : prog->func_info_rec_size;
9911 
9912 		info = OPTS_GET(opts, line_info, NULL);
9913 		info_cnt = OPTS_GET(opts, line_info_cnt, 0);
9914 		info_rec_size = OPTS_GET(opts, line_info_rec_size, 0);
9915 		if (!!info != !!info_cnt || !!info != !!info_rec_size) {
9916 			pr_warn("prog '%s': line_info, line_info_cnt, and line_info_rec_size must all be specified or all omitted\n",
9917 				prog->name);
9918 			return libbpf_err(-EINVAL);
9919 		}
9920 		attr.line_info = info ?: prog->line_info;
9921 		attr.line_info_cnt = info ? info_cnt : prog->line_info_cnt;
9922 		attr.line_info_rec_size = info ? info_rec_size : prog->line_info_rec_size;
9923 	}
9924 
9925 	/* Logging is caller-controlled; no fallback to prog/obj log settings */
9926 	attr.log_buf = OPTS_GET(opts, log_buf, NULL);
9927 	attr.log_size = OPTS_GET(opts, log_size, 0);
9928 	attr.log_level = OPTS_GET(opts, log_level, 0);
9929 
9930 	/*
9931 	 * Fields below may be mutated by prog_prepare_load_fn:
9932 	 * Seed them from prog/obj defaults here;
9933 	 * Later override with caller-provided opts.
9934 	 */
9935 	attr.expected_attach_type = prog->expected_attach_type;
9936 	attr.attach_btf_id = prog->attach_btf_id;
9937 	attr.attach_btf_obj_fd = prog->attach_btf_obj_fd;
9938 
9939 	if (prog->sec_def && prog->sec_def->prog_prepare_load_fn) {
9940 		err = prog->sec_def->prog_prepare_load_fn(prog, &attr, prog->sec_def->cookie);
9941 		if (err)
9942 			return libbpf_err(err);
9943 	}
9944 
9945 	/* Re-apply caller overrides for output fields */
9946 	if (OPTS_GET(opts, expected_attach_type, 0))
9947 		attr.expected_attach_type = OPTS_GET(opts, expected_attach_type, 0);
9948 	if (OPTS_GET(opts, attach_btf_id, 0))
9949 		attr.attach_btf_id = OPTS_GET(opts, attach_btf_id, 0);
9950 	if (OPTS_GET(opts, attach_btf_obj_fd, 0))
9951 		attr.attach_btf_obj_fd = OPTS_GET(opts, attach_btf_obj_fd, 0);
9952 
9953 	/*
9954 	 * Unlike bpf_object_load_prog(), we intentionally do not call bpf_prog_bind_map()
9955 	 * for RODATA maps here to avoid mutating the object's state. Callers can bind the
9956 	 * required maps themselves using bpf_prog_bind_map().
9957 	 */
9958 	fd = bpf_prog_load(prog->type, prog->name, obj->license, prog->insns, prog->insns_cnt,
9959 			   &attr);
9960 
9961 	return libbpf_err(fd);
9962 }
9963 
9964 #define SEC_DEF(sec_pfx, ptype, atype, flags, ...) {			    \
9965 	.sec = (char *)sec_pfx,						    \
9966 	.prog_type = BPF_PROG_TYPE_##ptype,				    \
9967 	.expected_attach_type = atype,					    \
9968 	.cookie = (long)(flags),					    \
9969 	.prog_prepare_load_fn = libbpf_prepare_prog_load,		    \
9970 	__VA_ARGS__							    \
9971 }
9972 
9973 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9974 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9975 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9976 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9977 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9978 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9979 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9980 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9981 static int attach_kprobe_session(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9982 static int attach_uprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9983 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9984 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9985 
9986 static const struct bpf_sec_def section_defs[] = {
9987 	SEC_DEF("socket",		SOCKET_FILTER, 0, SEC_NONE),
9988 	SEC_DEF("sk_reuseport/migrate",	SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT_OR_MIGRATE, SEC_ATTACHABLE),
9989 	SEC_DEF("sk_reuseport",		SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT, SEC_ATTACHABLE),
9990 	SEC_DEF("kprobe+",		KPROBE,	0, SEC_NONE, attach_kprobe),
9991 	SEC_DEF("uprobe+",		KPROBE,	0, SEC_NONE, attach_uprobe),
9992 	SEC_DEF("uprobe.s+",		KPROBE,	0, SEC_SLEEPABLE, attach_uprobe),
9993 	SEC_DEF("kretprobe+",		KPROBE, 0, SEC_NONE, attach_kprobe),
9994 	SEC_DEF("uretprobe+",		KPROBE, 0, SEC_NONE, attach_uprobe),
9995 	SEC_DEF("uretprobe.s+",		KPROBE, 0, SEC_SLEEPABLE, attach_uprobe),
9996 	SEC_DEF("kprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
9997 	SEC_DEF("kretprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
9998 	SEC_DEF("kprobe.session+",	KPROBE,	BPF_TRACE_KPROBE_SESSION, SEC_NONE, attach_kprobe_session),
9999 	SEC_DEF("uprobe.multi+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_NONE, attach_uprobe_multi),
10000 	SEC_DEF("uretprobe.multi+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_NONE, attach_uprobe_multi),
10001 	SEC_DEF("uprobe.session+",	KPROBE,	BPF_TRACE_UPROBE_SESSION, SEC_NONE, attach_uprobe_multi),
10002 	SEC_DEF("uprobe.multi.s+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_SLEEPABLE, attach_uprobe_multi),
10003 	SEC_DEF("uretprobe.multi.s+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_SLEEPABLE, attach_uprobe_multi),
10004 	SEC_DEF("uprobe.session.s+",	KPROBE,	BPF_TRACE_UPROBE_SESSION, SEC_SLEEPABLE, attach_uprobe_multi),
10005 	SEC_DEF("ksyscall+",		KPROBE,	0, SEC_NONE, attach_ksyscall),
10006 	SEC_DEF("kretsyscall+",		KPROBE, 0, SEC_NONE, attach_ksyscall),
10007 	SEC_DEF("usdt+",		KPROBE,	0, SEC_USDT, attach_usdt),
10008 	SEC_DEF("usdt.s+",		KPROBE,	0, SEC_USDT | SEC_SLEEPABLE, attach_usdt),
10009 	SEC_DEF("tc/ingress",		SCHED_CLS, BPF_TCX_INGRESS, SEC_NONE), /* alias for tcx */
10010 	SEC_DEF("tc/egress",		SCHED_CLS, BPF_TCX_EGRESS, SEC_NONE),  /* alias for tcx */
10011 	SEC_DEF("tcx/ingress",		SCHED_CLS, BPF_TCX_INGRESS, SEC_NONE),
10012 	SEC_DEF("tcx/egress",		SCHED_CLS, BPF_TCX_EGRESS, SEC_NONE),
10013 	SEC_DEF("tc",			SCHED_CLS, 0, SEC_NONE), /* deprecated / legacy, use tcx */
10014 	SEC_DEF("classifier",		SCHED_CLS, 0, SEC_NONE), /* deprecated / legacy, use tcx */
10015 	SEC_DEF("action",		SCHED_ACT, 0, SEC_NONE), /* deprecated / legacy, use tcx */
10016 	SEC_DEF("netkit/primary",	SCHED_CLS, BPF_NETKIT_PRIMARY, SEC_NONE),
10017 	SEC_DEF("netkit/peer",		SCHED_CLS, BPF_NETKIT_PEER, SEC_NONE),
10018 	SEC_DEF("tracepoint+",		TRACEPOINT, 0, SEC_NONE, attach_tp),
10019 	SEC_DEF("tp+",			TRACEPOINT, 0, SEC_NONE, attach_tp),
10020 	SEC_DEF("raw_tracepoint+",	RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
10021 	SEC_DEF("raw_tp+",		RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
10022 	SEC_DEF("raw_tracepoint.w+",	RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
10023 	SEC_DEF("raw_tp.w+",		RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
10024 	SEC_DEF("tp_btf+",		TRACING, BPF_TRACE_RAW_TP, SEC_ATTACH_BTF, attach_trace),
10025 	SEC_DEF("fentry+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF, attach_trace),
10026 	SEC_DEF("fmod_ret+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF, attach_trace),
10027 	SEC_DEF("fexit+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF, attach_trace),
10028 	SEC_DEF("fentry.s+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
10029 	SEC_DEF("fmod_ret.s+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
10030 	SEC_DEF("fexit.s+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
10031 	SEC_DEF("fsession+",		TRACING, BPF_TRACE_FSESSION, SEC_ATTACH_BTF, attach_trace),
10032 	SEC_DEF("fsession.s+",		TRACING, BPF_TRACE_FSESSION, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
10033 	SEC_DEF("freplace+",		EXT, 0, SEC_ATTACH_BTF, attach_trace),
10034 	SEC_DEF("lsm+",			LSM, BPF_LSM_MAC, SEC_ATTACH_BTF, attach_lsm),
10035 	SEC_DEF("lsm.s+",		LSM, BPF_LSM_MAC, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_lsm),
10036 	SEC_DEF("lsm_cgroup+",		LSM, BPF_LSM_CGROUP, SEC_ATTACH_BTF),
10037 	SEC_DEF("iter+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF, attach_iter),
10038 	SEC_DEF("iter.s+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_iter),
10039 	SEC_DEF("syscall",		SYSCALL, 0, SEC_SLEEPABLE),
10040 	SEC_DEF("xdp.frags/devmap",	XDP, BPF_XDP_DEVMAP, SEC_XDP_FRAGS),
10041 	SEC_DEF("xdp/devmap",		XDP, BPF_XDP_DEVMAP, SEC_ATTACHABLE),
10042 	SEC_DEF("xdp.frags/cpumap",	XDP, BPF_XDP_CPUMAP, SEC_XDP_FRAGS),
10043 	SEC_DEF("xdp/cpumap",		XDP, BPF_XDP_CPUMAP, SEC_ATTACHABLE),
10044 	SEC_DEF("xdp.frags",		XDP, BPF_XDP, SEC_XDP_FRAGS),
10045 	SEC_DEF("xdp",			XDP, BPF_XDP, SEC_ATTACHABLE_OPT),
10046 	SEC_DEF("perf_event",		PERF_EVENT, 0, SEC_NONE),
10047 	SEC_DEF("lwt_in",		LWT_IN, 0, SEC_NONE),
10048 	SEC_DEF("lwt_out",		LWT_OUT, 0, SEC_NONE),
10049 	SEC_DEF("lwt_xmit",		LWT_XMIT, 0, SEC_NONE),
10050 	SEC_DEF("lwt_seg6local",	LWT_SEG6LOCAL, 0, SEC_NONE),
10051 	SEC_DEF("sockops",		SOCK_OPS, BPF_CGROUP_SOCK_OPS, SEC_ATTACHABLE_OPT),
10052 	SEC_DEF("sk_skb/stream_parser",	SK_SKB, BPF_SK_SKB_STREAM_PARSER, SEC_ATTACHABLE_OPT),
10053 	SEC_DEF("sk_skb/stream_verdict",SK_SKB, BPF_SK_SKB_STREAM_VERDICT, SEC_ATTACHABLE_OPT),
10054 	SEC_DEF("sk_skb/verdict",	SK_SKB, BPF_SK_SKB_VERDICT, SEC_ATTACHABLE_OPT),
10055 	SEC_DEF("sk_skb",		SK_SKB, 0, SEC_NONE),
10056 	SEC_DEF("sk_msg",		SK_MSG, BPF_SK_MSG_VERDICT, SEC_ATTACHABLE_OPT),
10057 	SEC_DEF("lirc_mode2",		LIRC_MODE2, BPF_LIRC_MODE2, SEC_ATTACHABLE_OPT),
10058 	SEC_DEF("flow_dissector",	FLOW_DISSECTOR, BPF_FLOW_DISSECTOR, SEC_ATTACHABLE_OPT),
10059 	SEC_DEF("cgroup_skb/ingress",	CGROUP_SKB, BPF_CGROUP_INET_INGRESS, SEC_ATTACHABLE_OPT),
10060 	SEC_DEF("cgroup_skb/egress",	CGROUP_SKB, BPF_CGROUP_INET_EGRESS, SEC_ATTACHABLE_OPT),
10061 	SEC_DEF("cgroup/skb",		CGROUP_SKB, 0, SEC_NONE),
10062 	SEC_DEF("cgroup/sock_create",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE),
10063 	SEC_DEF("cgroup/sock_release",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_RELEASE, SEC_ATTACHABLE),
10064 	SEC_DEF("cgroup/sock",		CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE_OPT),
10065 	SEC_DEF("cgroup/post_bind4",	CGROUP_SOCK, BPF_CGROUP_INET4_POST_BIND, SEC_ATTACHABLE),
10066 	SEC_DEF("cgroup/post_bind6",	CGROUP_SOCK, BPF_CGROUP_INET6_POST_BIND, SEC_ATTACHABLE),
10067 	SEC_DEF("cgroup/bind4",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND, SEC_ATTACHABLE),
10068 	SEC_DEF("cgroup/bind6",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND, SEC_ATTACHABLE),
10069 	SEC_DEF("cgroup/connect4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT, SEC_ATTACHABLE),
10070 	SEC_DEF("cgroup/connect6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT, SEC_ATTACHABLE),
10071 	SEC_DEF("cgroup/connect_unix",	CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_CONNECT, SEC_ATTACHABLE),
10072 	SEC_DEF("cgroup/sendmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG, SEC_ATTACHABLE),
10073 	SEC_DEF("cgroup/sendmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG, SEC_ATTACHABLE),
10074 	SEC_DEF("cgroup/sendmsg_unix",	CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_SENDMSG, SEC_ATTACHABLE),
10075 	SEC_DEF("cgroup/recvmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_RECVMSG, SEC_ATTACHABLE),
10076 	SEC_DEF("cgroup/recvmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_RECVMSG, SEC_ATTACHABLE),
10077 	SEC_DEF("cgroup/recvmsg_unix",	CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_RECVMSG, SEC_ATTACHABLE),
10078 	SEC_DEF("cgroup/getpeername4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETPEERNAME, SEC_ATTACHABLE),
10079 	SEC_DEF("cgroup/getpeername6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETPEERNAME, SEC_ATTACHABLE),
10080 	SEC_DEF("cgroup/getpeername_unix", CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_GETPEERNAME, SEC_ATTACHABLE),
10081 	SEC_DEF("cgroup/getsockname4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETSOCKNAME, SEC_ATTACHABLE),
10082 	SEC_DEF("cgroup/getsockname6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETSOCKNAME, SEC_ATTACHABLE),
10083 	SEC_DEF("cgroup/getsockname_unix", CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_GETSOCKNAME, SEC_ATTACHABLE),
10084 	SEC_DEF("cgroup/sysctl",	CGROUP_SYSCTL, BPF_CGROUP_SYSCTL, SEC_ATTACHABLE),
10085 	SEC_DEF("cgroup/getsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_GETSOCKOPT, SEC_ATTACHABLE),
10086 	SEC_DEF("cgroup/setsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_SETSOCKOPT, SEC_ATTACHABLE),
10087 	SEC_DEF("cgroup/dev",		CGROUP_DEVICE, BPF_CGROUP_DEVICE, SEC_ATTACHABLE_OPT),
10088 	SEC_DEF("struct_ops+",		STRUCT_OPS, 0, SEC_NONE),
10089 	SEC_DEF("struct_ops.s+",	STRUCT_OPS, 0, SEC_SLEEPABLE),
10090 	SEC_DEF("sk_lookup",		SK_LOOKUP, BPF_SK_LOOKUP, SEC_ATTACHABLE),
10091 	SEC_DEF("netfilter",		NETFILTER, BPF_NETFILTER, SEC_NONE),
10092 };
10093 
10094 int libbpf_register_prog_handler(const char *sec,
10095 				 enum bpf_prog_type prog_type,
10096 				 enum bpf_attach_type exp_attach_type,
10097 				 const struct libbpf_prog_handler_opts *opts)
10098 {
10099 	struct bpf_sec_def *sec_def;
10100 
10101 	if (!OPTS_VALID(opts, libbpf_prog_handler_opts))
10102 		return libbpf_err(-EINVAL);
10103 
10104 	if (last_custom_sec_def_handler_id == INT_MAX) /* prevent overflow */
10105 		return libbpf_err(-E2BIG);
10106 
10107 	if (sec) {
10108 		sec_def = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt + 1,
10109 					      sizeof(*sec_def));
10110 		if (!sec_def)
10111 			return libbpf_err(-ENOMEM);
10112 
10113 		custom_sec_defs = sec_def;
10114 		sec_def = &custom_sec_defs[custom_sec_def_cnt];
10115 	} else {
10116 		if (has_custom_fallback_def)
10117 			return libbpf_err(-EBUSY);
10118 
10119 		sec_def = &custom_fallback_def;
10120 	}
10121 
10122 	sec_def->sec = sec ? strdup(sec) : NULL;
10123 	if (sec && !sec_def->sec)
10124 		return libbpf_err(-ENOMEM);
10125 
10126 	sec_def->prog_type = prog_type;
10127 	sec_def->expected_attach_type = exp_attach_type;
10128 	sec_def->cookie = OPTS_GET(opts, cookie, 0);
10129 
10130 	sec_def->prog_setup_fn = OPTS_GET(opts, prog_setup_fn, NULL);
10131 	sec_def->prog_prepare_load_fn = OPTS_GET(opts, prog_prepare_load_fn, NULL);
10132 	sec_def->prog_attach_fn = OPTS_GET(opts, prog_attach_fn, NULL);
10133 
10134 	sec_def->handler_id = ++last_custom_sec_def_handler_id;
10135 
10136 	if (sec)
10137 		custom_sec_def_cnt++;
10138 	else
10139 		has_custom_fallback_def = true;
10140 
10141 	return sec_def->handler_id;
10142 }
10143 
10144 int libbpf_unregister_prog_handler(int handler_id)
10145 {
10146 	struct bpf_sec_def *sec_defs;
10147 	int i;
10148 
10149 	if (handler_id <= 0)
10150 		return libbpf_err(-EINVAL);
10151 
10152 	if (has_custom_fallback_def && custom_fallback_def.handler_id == handler_id) {
10153 		memset(&custom_fallback_def, 0, sizeof(custom_fallback_def));
10154 		has_custom_fallback_def = false;
10155 		return 0;
10156 	}
10157 
10158 	for (i = 0; i < custom_sec_def_cnt; i++) {
10159 		if (custom_sec_defs[i].handler_id == handler_id)
10160 			break;
10161 	}
10162 
10163 	if (i == custom_sec_def_cnt)
10164 		return libbpf_err(-ENOENT);
10165 
10166 	free(custom_sec_defs[i].sec);
10167 	for (i = i + 1; i < custom_sec_def_cnt; i++)
10168 		custom_sec_defs[i - 1] = custom_sec_defs[i];
10169 	custom_sec_def_cnt--;
10170 
10171 	/* try to shrink the array, but it's ok if we couldn't */
10172 	sec_defs = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt, sizeof(*sec_defs));
10173 	/* if new count is zero, reallocarray can return a valid NULL result;
10174 	 * in this case the previous pointer will be freed, so we *have to*
10175 	 * reassign old pointer to the new value (even if it's NULL)
10176 	 */
10177 	if (sec_defs || custom_sec_def_cnt == 0)
10178 		custom_sec_defs = sec_defs;
10179 
10180 	return 0;
10181 }
10182 
10183 static bool sec_def_matches(const struct bpf_sec_def *sec_def, const char *sec_name)
10184 {
10185 	size_t len = strlen(sec_def->sec);
10186 
10187 	/* "type/" always has to have proper SEC("type/extras") form */
10188 	if (sec_def->sec[len - 1] == '/') {
10189 		if (str_has_pfx(sec_name, sec_def->sec))
10190 			return true;
10191 		return false;
10192 	}
10193 
10194 	/* "type+" means it can be either exact SEC("type") or
10195 	 * well-formed SEC("type/extras") with proper '/' separator
10196 	 */
10197 	if (sec_def->sec[len - 1] == '+') {
10198 		len--;
10199 		/* not even a prefix */
10200 		if (strncmp(sec_name, sec_def->sec, len) != 0)
10201 			return false;
10202 		/* exact match or has '/' separator */
10203 		if (sec_name[len] == '\0' || sec_name[len] == '/')
10204 			return true;
10205 		return false;
10206 	}
10207 
10208 	return strcmp(sec_name, sec_def->sec) == 0;
10209 }
10210 
10211 static const struct bpf_sec_def *find_sec_def(const char *sec_name)
10212 {
10213 	const struct bpf_sec_def *sec_def;
10214 	int i, n;
10215 
10216 	n = custom_sec_def_cnt;
10217 	for (i = 0; i < n; i++) {
10218 		sec_def = &custom_sec_defs[i];
10219 		if (sec_def_matches(sec_def, sec_name))
10220 			return sec_def;
10221 	}
10222 
10223 	n = ARRAY_SIZE(section_defs);
10224 	for (i = 0; i < n; i++) {
10225 		sec_def = &section_defs[i];
10226 		if (sec_def_matches(sec_def, sec_name))
10227 			return sec_def;
10228 	}
10229 
10230 	if (has_custom_fallback_def)
10231 		return &custom_fallback_def;
10232 
10233 	return NULL;
10234 }
10235 
10236 #define MAX_TYPE_NAME_SIZE 32
10237 
10238 static char *libbpf_get_type_names(bool attach_type)
10239 {
10240 	int i, len = ARRAY_SIZE(section_defs) * MAX_TYPE_NAME_SIZE;
10241 	char *buf;
10242 
10243 	buf = malloc(len);
10244 	if (!buf)
10245 		return NULL;
10246 
10247 	buf[0] = '\0';
10248 	/* Forge string buf with all available names */
10249 	for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
10250 		const struct bpf_sec_def *sec_def = &section_defs[i];
10251 
10252 		if (attach_type) {
10253 			if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
10254 				continue;
10255 
10256 			if (!(sec_def->cookie & SEC_ATTACHABLE))
10257 				continue;
10258 		}
10259 
10260 		if (strlen(buf) + strlen(section_defs[i].sec) + 2 > len) {
10261 			free(buf);
10262 			return NULL;
10263 		}
10264 		strcat(buf, " ");
10265 		strcat(buf, section_defs[i].sec);
10266 	}
10267 
10268 	return buf;
10269 }
10270 
10271 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
10272 			     enum bpf_attach_type *expected_attach_type)
10273 {
10274 	const struct bpf_sec_def *sec_def;
10275 	char *type_names;
10276 
10277 	if (!name)
10278 		return libbpf_err(-EINVAL);
10279 
10280 	sec_def = find_sec_def(name);
10281 	if (sec_def) {
10282 		*prog_type = sec_def->prog_type;
10283 		*expected_attach_type = sec_def->expected_attach_type;
10284 		return 0;
10285 	}
10286 
10287 	pr_debug("failed to guess program type from ELF section '%s'\n", name);
10288 	type_names = libbpf_get_type_names(false);
10289 	if (type_names != NULL) {
10290 		pr_debug("supported section(type) names are:%s\n", type_names);
10291 		free(type_names);
10292 	}
10293 
10294 	return libbpf_err(-ESRCH);
10295 }
10296 
10297 const char *libbpf_bpf_attach_type_str(enum bpf_attach_type t)
10298 {
10299 	if (t < 0 || t >= ARRAY_SIZE(attach_type_name))
10300 		return NULL;
10301 
10302 	return attach_type_name[t];
10303 }
10304 
10305 const char *libbpf_bpf_link_type_str(enum bpf_link_type t)
10306 {
10307 	if (t < 0 || t >= ARRAY_SIZE(link_type_name))
10308 		return NULL;
10309 
10310 	return link_type_name[t];
10311 }
10312 
10313 const char *libbpf_bpf_map_type_str(enum bpf_map_type t)
10314 {
10315 	if (t < 0 || t >= ARRAY_SIZE(map_type_name))
10316 		return NULL;
10317 
10318 	return map_type_name[t];
10319 }
10320 
10321 const char *libbpf_bpf_prog_type_str(enum bpf_prog_type t)
10322 {
10323 	if (t < 0 || t >= ARRAY_SIZE(prog_type_name))
10324 		return NULL;
10325 
10326 	return prog_type_name[t];
10327 }
10328 
10329 static struct bpf_map *find_struct_ops_map_by_offset(struct bpf_object *obj,
10330 						     int sec_idx,
10331 						     size_t offset)
10332 {
10333 	struct bpf_map *map;
10334 	size_t i;
10335 
10336 	for (i = 0; i < obj->nr_maps; i++) {
10337 		map = &obj->maps[i];
10338 		if (!bpf_map__is_struct_ops(map))
10339 			continue;
10340 		if (map->sec_idx == sec_idx &&
10341 		    map->sec_offset <= offset &&
10342 		    offset - map->sec_offset < map->def.value_size)
10343 			return map;
10344 	}
10345 
10346 	return NULL;
10347 }
10348 
10349 /* Collect the reloc from ELF, populate the st_ops->progs[], and update
10350  * st_ops->data for shadow type.
10351  */
10352 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
10353 					    Elf64_Shdr *shdr, Elf_Data *data)
10354 {
10355 	const struct btf_type *type;
10356 	const struct btf_member *member;
10357 	struct bpf_struct_ops *st_ops;
10358 	struct bpf_program *prog;
10359 	unsigned int shdr_idx;
10360 	const struct btf *btf;
10361 	struct bpf_map *map;
10362 	unsigned int moff, insn_idx;
10363 	const char *name;
10364 	__u32 member_idx;
10365 	Elf64_Sym *sym;
10366 	Elf64_Rel *rel;
10367 	int i, nrels;
10368 
10369 	btf = obj->btf;
10370 	nrels = shdr->sh_size / shdr->sh_entsize;
10371 	for (i = 0; i < nrels; i++) {
10372 		rel = elf_rel_by_idx(data, i);
10373 		if (!rel) {
10374 			pr_warn("struct_ops reloc: failed to get %d reloc\n", i);
10375 			return -LIBBPF_ERRNO__FORMAT;
10376 		}
10377 
10378 		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
10379 		if (!sym) {
10380 			pr_warn("struct_ops reloc: symbol %zx not found\n",
10381 				(size_t)ELF64_R_SYM(rel->r_info));
10382 			return -LIBBPF_ERRNO__FORMAT;
10383 		}
10384 
10385 		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
10386 		map = find_struct_ops_map_by_offset(obj, shdr->sh_info, rel->r_offset);
10387 		if (!map) {
10388 			pr_warn("struct_ops reloc: cannot find map at rel->r_offset %zu\n",
10389 				(size_t)rel->r_offset);
10390 			return -EINVAL;
10391 		}
10392 
10393 		moff = rel->r_offset - map->sec_offset;
10394 		shdr_idx = sym->st_shndx;
10395 		st_ops = map->st_ops;
10396 		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",
10397 			 map->name,
10398 			 (long long)(rel->r_info >> 32),
10399 			 (long long)sym->st_value,
10400 			 shdr_idx, (size_t)rel->r_offset,
10401 			 map->sec_offset, sym->st_name, name);
10402 
10403 		if (shdr_idx >= SHN_LORESERVE) {
10404 			pr_warn("struct_ops reloc %s: rel->r_offset %zu shdr_idx %u unsupported non-static function\n",
10405 				map->name, (size_t)rel->r_offset, shdr_idx);
10406 			return -LIBBPF_ERRNO__RELOC;
10407 		}
10408 		if (sym->st_value % BPF_INSN_SZ) {
10409 			pr_warn("struct_ops reloc %s: invalid target program offset %llu\n",
10410 				map->name, (unsigned long long)sym->st_value);
10411 			return -LIBBPF_ERRNO__FORMAT;
10412 		}
10413 		insn_idx = sym->st_value / BPF_INSN_SZ;
10414 
10415 		type = btf__type_by_id(btf, st_ops->type_id);
10416 		member = find_member_by_offset(type, moff * 8);
10417 		if (!member) {
10418 			pr_warn("struct_ops reloc %s: cannot find member at moff %u\n",
10419 				map->name, moff);
10420 			return -EINVAL;
10421 		}
10422 		member_idx = member - btf_members(type);
10423 		name = btf__name_by_offset(btf, member->name_off);
10424 
10425 		if (!resolve_func_ptr(btf, member->type, NULL)) {
10426 			pr_warn("struct_ops reloc %s: cannot relocate non func ptr %s\n",
10427 				map->name, name);
10428 			return -EINVAL;
10429 		}
10430 
10431 		prog = find_prog_by_sec_insn(obj, shdr_idx, insn_idx);
10432 		if (!prog) {
10433 			pr_warn("struct_ops reloc %s: cannot find prog at shdr_idx %u to relocate func ptr %s\n",
10434 				map->name, shdr_idx, name);
10435 			return -EINVAL;
10436 		}
10437 
10438 		/* prevent the use of BPF prog with invalid type */
10439 		if (prog->type != BPF_PROG_TYPE_STRUCT_OPS) {
10440 			pr_warn("struct_ops reloc %s: prog %s is not struct_ops BPF program\n",
10441 				map->name, prog->name);
10442 			return -EINVAL;
10443 		}
10444 
10445 		st_ops->progs[member_idx] = prog;
10446 
10447 		/* st_ops->data will be exposed to users, being returned by
10448 		 * bpf_map__initial_value() as a pointer to the shadow
10449 		 * type. All function pointers in the original struct type
10450 		 * should be converted to a pointer to struct bpf_program
10451 		 * in the shadow type.
10452 		 */
10453 		*((struct bpf_program **)(st_ops->data + moff)) = prog;
10454 	}
10455 
10456 	return 0;
10457 }
10458 
10459 #define BTF_TRACE_PREFIX "btf_trace_"
10460 #define BTF_LSM_PREFIX "bpf_lsm_"
10461 #define BTF_ITER_PREFIX "bpf_iter_"
10462 #define BTF_MAX_NAME_SIZE 128
10463 
10464 void btf_get_kernel_prefix_kind(enum bpf_attach_type attach_type,
10465 				const char **prefix, int *kind)
10466 {
10467 	switch (attach_type) {
10468 	case BPF_TRACE_RAW_TP:
10469 		*prefix = BTF_TRACE_PREFIX;
10470 		*kind = BTF_KIND_TYPEDEF;
10471 		break;
10472 	case BPF_LSM_MAC:
10473 	case BPF_LSM_CGROUP:
10474 		*prefix = BTF_LSM_PREFIX;
10475 		*kind = BTF_KIND_FUNC;
10476 		break;
10477 	case BPF_TRACE_ITER:
10478 		*prefix = BTF_ITER_PREFIX;
10479 		*kind = BTF_KIND_FUNC;
10480 		break;
10481 	default:
10482 		*prefix = "";
10483 		*kind = BTF_KIND_FUNC;
10484 	}
10485 }
10486 
10487 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
10488 				   const char *name, __u32 kind)
10489 {
10490 	char btf_type_name[BTF_MAX_NAME_SIZE];
10491 	int ret;
10492 
10493 	ret = snprintf(btf_type_name, sizeof(btf_type_name),
10494 		       "%s%s", prefix, name);
10495 	/* snprintf returns the number of characters written excluding the
10496 	 * terminating null. So, if >= BTF_MAX_NAME_SIZE are written, it
10497 	 * indicates truncation.
10498 	 */
10499 	if (ret < 0 || ret >= sizeof(btf_type_name))
10500 		return -ENAMETOOLONG;
10501 	return btf__find_by_name_kind(btf, btf_type_name, kind);
10502 }
10503 
10504 static inline int find_attach_btf_id(struct btf *btf, const char *name,
10505 				     enum bpf_attach_type attach_type)
10506 {
10507 	const char *prefix;
10508 	int kind;
10509 
10510 	btf_get_kernel_prefix_kind(attach_type, &prefix, &kind);
10511 	return find_btf_by_prefix_kind(btf, prefix, name, kind);
10512 }
10513 
10514 int libbpf_find_vmlinux_btf_id(const char *name,
10515 			       enum bpf_attach_type attach_type)
10516 {
10517 	struct btf *btf;
10518 	int err;
10519 
10520 	btf = btf__load_vmlinux_btf();
10521 	err = libbpf_get_error(btf);
10522 	if (err) {
10523 		pr_warn("vmlinux BTF is not found\n");
10524 		return libbpf_err(err);
10525 	}
10526 
10527 	err = find_attach_btf_id(btf, name, attach_type);
10528 	if (err <= 0)
10529 		pr_warn("%s is not found in vmlinux BTF\n", name);
10530 
10531 	btf__free(btf);
10532 	return libbpf_err(err);
10533 }
10534 
10535 static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd, int token_fd)
10536 {
10537 	struct bpf_prog_info info;
10538 	__u32 info_len = sizeof(info);
10539 	struct btf *btf;
10540 	int err;
10541 
10542 	memset(&info, 0, info_len);
10543 	err = bpf_prog_get_info_by_fd(attach_prog_fd, &info, &info_len);
10544 	if (err) {
10545 		pr_warn("failed bpf_prog_get_info_by_fd for FD %d: %s\n",
10546 			attach_prog_fd, errstr(err));
10547 		return err;
10548 	}
10549 
10550 	err = -EINVAL;
10551 	if (!info.btf_id) {
10552 		pr_warn("The target program doesn't have BTF\n");
10553 		goto out;
10554 	}
10555 	btf = btf_load_from_kernel(info.btf_id, NULL, token_fd);
10556 	err = libbpf_get_error(btf);
10557 	if (err) {
10558 		pr_warn("Failed to get BTF %d of the program: %s\n", info.btf_id, errstr(err));
10559 		goto out;
10560 	}
10561 	err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
10562 	btf__free(btf);
10563 	if (err <= 0) {
10564 		pr_warn("%s is not found in prog's BTF\n", name);
10565 		goto out;
10566 	}
10567 out:
10568 	return err;
10569 }
10570 
10571 static int find_kernel_btf_id(struct bpf_object *obj, const char *attach_name,
10572 			      enum bpf_attach_type attach_type,
10573 			      int *btf_obj_fd, int *btf_type_id)
10574 {
10575 	int ret, i, mod_len = 0;
10576 	const char *fn_name, *mod_name = NULL;
10577 
10578 	fn_name = strchr(attach_name, ':');
10579 	if (fn_name) {
10580 		mod_name = attach_name;
10581 		mod_len = fn_name - mod_name;
10582 		fn_name++;
10583 	}
10584 
10585 	if (!mod_name || strncmp(mod_name, "vmlinux", mod_len) == 0) {
10586 		ret = find_attach_btf_id(obj->btf_vmlinux,
10587 					 mod_name ? fn_name : attach_name,
10588 					 attach_type);
10589 		if (ret > 0) {
10590 			*btf_obj_fd = 0; /* vmlinux BTF */
10591 			*btf_type_id = ret;
10592 			return 0;
10593 		}
10594 		if (ret != -ENOENT)
10595 			return ret;
10596 	}
10597 
10598 	ret = load_module_btfs(obj);
10599 	if (ret)
10600 		return ret;
10601 
10602 	for (i = 0; i < obj->btf_module_cnt; i++) {
10603 		const struct module_btf *mod = &obj->btf_modules[i];
10604 
10605 		if (mod_name && strncmp(mod->name, mod_name, mod_len) != 0)
10606 			continue;
10607 
10608 		ret = find_attach_btf_id(mod->btf,
10609 					 mod_name ? fn_name : attach_name,
10610 					 attach_type);
10611 		if (ret > 0) {
10612 			*btf_obj_fd = mod->fd;
10613 			*btf_type_id = ret;
10614 			return 0;
10615 		}
10616 		if (ret == -ENOENT)
10617 			continue;
10618 
10619 		return ret;
10620 	}
10621 
10622 	return -ESRCH;
10623 }
10624 
10625 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
10626 				     int *btf_obj_fd, int *btf_type_id)
10627 {
10628 	enum bpf_attach_type attach_type = prog->expected_attach_type;
10629 	__u32 attach_prog_fd = prog->attach_prog_fd;
10630 	int err = 0;
10631 
10632 	/* BPF program's BTF ID */
10633 	if (prog->type == BPF_PROG_TYPE_EXT || attach_prog_fd) {
10634 		if (!attach_prog_fd) {
10635 			pr_warn("prog '%s': attach program FD is not set\n", prog->name);
10636 			return -EINVAL;
10637 		}
10638 		err = libbpf_find_prog_btf_id(attach_name, attach_prog_fd, prog->obj->token_fd);
10639 		if (err < 0) {
10640 			pr_warn("prog '%s': failed to find BPF program (FD %d) BTF ID for '%s': %s\n",
10641 				prog->name, attach_prog_fd, attach_name, errstr(err));
10642 			return err;
10643 		}
10644 		*btf_obj_fd = 0;
10645 		*btf_type_id = err;
10646 		return 0;
10647 	}
10648 
10649 	/* kernel/module BTF ID */
10650 	if (prog->obj->gen_loader) {
10651 		bpf_gen__record_attach_target(prog->obj->gen_loader, attach_name, attach_type);
10652 		*btf_obj_fd = 0;
10653 		*btf_type_id = 1;
10654 	} else {
10655 		err = find_kernel_btf_id(prog->obj, attach_name,
10656 					 attach_type, btf_obj_fd,
10657 					 btf_type_id);
10658 	}
10659 	if (err) {
10660 		pr_warn("prog '%s': failed to find kernel BTF type ID of '%s': %s\n",
10661 			prog->name, attach_name, errstr(err));
10662 		return err;
10663 	}
10664 	return 0;
10665 }
10666 
10667 int libbpf_attach_type_by_name(const char *name,
10668 			       enum bpf_attach_type *attach_type)
10669 {
10670 	char *type_names;
10671 	const struct bpf_sec_def *sec_def;
10672 
10673 	if (!name)
10674 		return libbpf_err(-EINVAL);
10675 
10676 	sec_def = find_sec_def(name);
10677 	if (!sec_def) {
10678 		pr_debug("failed to guess attach type based on ELF section name '%s'\n", name);
10679 		type_names = libbpf_get_type_names(true);
10680 		if (type_names != NULL) {
10681 			pr_debug("attachable section(type) names are:%s\n", type_names);
10682 			free(type_names);
10683 		}
10684 
10685 		return libbpf_err(-EINVAL);
10686 	}
10687 
10688 	if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
10689 		return libbpf_err(-EINVAL);
10690 	if (!(sec_def->cookie & SEC_ATTACHABLE))
10691 		return libbpf_err(-EINVAL);
10692 
10693 	*attach_type = sec_def->expected_attach_type;
10694 	return 0;
10695 }
10696 
10697 int bpf_map__fd(const struct bpf_map *map)
10698 {
10699 	if (!map)
10700 		return libbpf_err(-EINVAL);
10701 	if (!map_is_created(map))
10702 		return -1;
10703 	return map->fd;
10704 }
10705 
10706 static bool map_uses_real_name(const struct bpf_map *map)
10707 {
10708 	/* Since libbpf started to support custom .data.* and .rodata.* maps,
10709 	 * their user-visible name differs from kernel-visible name. Users see
10710 	 * such map's corresponding ELF section name as a map name.
10711 	 * This check distinguishes .data/.rodata from .data.* and .rodata.*
10712 	 * maps to know which name has to be returned to the user.
10713 	 */
10714 	if (map->libbpf_type == LIBBPF_MAP_DATA && strcmp(map->real_name, DATA_SEC) != 0)
10715 		return true;
10716 	if (map->libbpf_type == LIBBPF_MAP_RODATA && strcmp(map->real_name, RODATA_SEC) != 0)
10717 		return true;
10718 	return false;
10719 }
10720 
10721 const char *bpf_map__name(const struct bpf_map *map)
10722 {
10723 	if (!map)
10724 		return NULL;
10725 
10726 	if (map_uses_real_name(map))
10727 		return map->real_name;
10728 
10729 	return map->name;
10730 }
10731 
10732 enum bpf_map_type bpf_map__type(const struct bpf_map *map)
10733 {
10734 	return map->def.type;
10735 }
10736 
10737 int bpf_map__set_type(struct bpf_map *map, enum bpf_map_type type)
10738 {
10739 	if (map_is_created(map))
10740 		return libbpf_err(-EBUSY);
10741 	map->def.type = type;
10742 	return 0;
10743 }
10744 
10745 __u32 bpf_map__map_flags(const struct bpf_map *map)
10746 {
10747 	return map->def.map_flags;
10748 }
10749 
10750 int bpf_map__set_map_flags(struct bpf_map *map, __u32 flags)
10751 {
10752 	if (map_is_created(map))
10753 		return libbpf_err(-EBUSY);
10754 	map->def.map_flags = flags;
10755 	return 0;
10756 }
10757 
10758 __u64 bpf_map__map_extra(const struct bpf_map *map)
10759 {
10760 	return map->map_extra;
10761 }
10762 
10763 int bpf_map__set_map_extra(struct bpf_map *map, __u64 map_extra)
10764 {
10765 	if (map_is_created(map))
10766 		return libbpf_err(-EBUSY);
10767 	map->map_extra = map_extra;
10768 	return 0;
10769 }
10770 
10771 __u32 bpf_map__numa_node(const struct bpf_map *map)
10772 {
10773 	return map->numa_node;
10774 }
10775 
10776 int bpf_map__set_numa_node(struct bpf_map *map, __u32 numa_node)
10777 {
10778 	if (map_is_created(map))
10779 		return libbpf_err(-EBUSY);
10780 	map->numa_node = numa_node;
10781 	return 0;
10782 }
10783 
10784 __u32 bpf_map__key_size(const struct bpf_map *map)
10785 {
10786 	return map->def.key_size;
10787 }
10788 
10789 int bpf_map__set_key_size(struct bpf_map *map, __u32 size)
10790 {
10791 	if (map_is_created(map))
10792 		return libbpf_err(-EBUSY);
10793 	map->def.key_size = size;
10794 	return 0;
10795 }
10796 
10797 __u32 bpf_map__value_size(const struct bpf_map *map)
10798 {
10799 	return map->def.value_size;
10800 }
10801 
10802 static int map_btf_datasec_resize(struct bpf_map *map, __u32 size)
10803 {
10804 	struct btf *btf;
10805 	struct btf_type *datasec_type, *var_type;
10806 	struct btf_var_secinfo *var;
10807 	const struct btf_type *array_type;
10808 	const struct btf_array *array;
10809 	int vlen, element_sz, new_array_id;
10810 	__u32 nr_elements;
10811 
10812 	/* check btf existence */
10813 	btf = bpf_object__btf(map->obj);
10814 	if (!btf)
10815 		return -ENOENT;
10816 
10817 	/* verify map is datasec */
10818 	datasec_type = btf_type_by_id(btf, bpf_map__btf_value_type_id(map));
10819 	if (!btf_is_datasec(datasec_type)) {
10820 		pr_warn("map '%s': cannot be resized, map value type is not a datasec\n",
10821 			bpf_map__name(map));
10822 		return -EINVAL;
10823 	}
10824 
10825 	/* verify datasec has at least one var */
10826 	vlen = btf_vlen(datasec_type);
10827 	if (vlen == 0) {
10828 		pr_warn("map '%s': cannot be resized, map value datasec is empty\n",
10829 			bpf_map__name(map));
10830 		return -EINVAL;
10831 	}
10832 
10833 	/* verify last var in the datasec is an array */
10834 	var = &btf_var_secinfos(datasec_type)[vlen - 1];
10835 	var_type = btf_type_by_id(btf, var->type);
10836 	array_type = skip_mods_and_typedefs(btf, var_type->type, NULL);
10837 	if (!btf_is_array(array_type)) {
10838 		pr_warn("map '%s': cannot be resized, last var must be an array\n",
10839 			bpf_map__name(map));
10840 		return -EINVAL;
10841 	}
10842 
10843 	/* verify request size aligns with array */
10844 	array = btf_array(array_type);
10845 	element_sz = btf__resolve_size(btf, array->type);
10846 	if (element_sz <= 0 || (size - var->offset) % element_sz != 0) {
10847 		pr_warn("map '%s': cannot be resized, element size (%d) doesn't align with new total size (%u)\n",
10848 			bpf_map__name(map), element_sz, size);
10849 		return -EINVAL;
10850 	}
10851 
10852 	/* create a new array based on the existing array, but with new length */
10853 	nr_elements = (size - var->offset) / element_sz;
10854 	new_array_id = btf__add_array(btf, array->index_type, array->type, nr_elements);
10855 	if (new_array_id < 0)
10856 		return new_array_id;
10857 
10858 	/* adding a new btf type invalidates existing pointers to btf objects,
10859 	 * so refresh pointers before proceeding
10860 	 */
10861 	datasec_type = btf_type_by_id(btf, map->btf_value_type_id);
10862 	var = &btf_var_secinfos(datasec_type)[vlen - 1];
10863 	var_type = btf_type_by_id(btf, var->type);
10864 
10865 	/* finally update btf info */
10866 	datasec_type->size = size;
10867 	var->size = size - var->offset;
10868 	var_type->type = new_array_id;
10869 
10870 	return 0;
10871 }
10872 
10873 int bpf_map__set_value_size(struct bpf_map *map, __u32 size)
10874 {
10875 	if (map_is_created(map))
10876 		return libbpf_err(-EBUSY);
10877 
10878 	if (map->mmaped) {
10879 		size_t mmap_old_sz, mmap_new_sz;
10880 		int err;
10881 
10882 		if (map->def.type != BPF_MAP_TYPE_ARRAY)
10883 			return libbpf_err(-EOPNOTSUPP);
10884 
10885 		mmap_old_sz = bpf_map_mmap_sz(map);
10886 		mmap_new_sz = array_map_mmap_sz(size, map->def.max_entries);
10887 		err = bpf_map_mmap_resize(map, mmap_old_sz, mmap_new_sz);
10888 		if (err) {
10889 			pr_warn("map '%s': failed to resize memory-mapped region: %s\n",
10890 				bpf_map__name(map), errstr(err));
10891 			return libbpf_err(err);
10892 		}
10893 		err = map_btf_datasec_resize(map, size);
10894 		if (err && err != -ENOENT) {
10895 			pr_warn("map '%s': failed to adjust resized BTF, clearing BTF key/value info: %s\n",
10896 				bpf_map__name(map), errstr(err));
10897 			map->btf_value_type_id = 0;
10898 			map->btf_key_type_id = 0;
10899 		}
10900 	}
10901 
10902 	map->def.value_size = size;
10903 	return 0;
10904 }
10905 
10906 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
10907 {
10908 	return map ? map->btf_key_type_id : 0;
10909 }
10910 
10911 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
10912 {
10913 	return map ? map->btf_value_type_id : 0;
10914 }
10915 
10916 int bpf_map__set_initial_value(struct bpf_map *map,
10917 			       const void *data, size_t size)
10918 {
10919 	size_t actual_sz;
10920 
10921 	if (map_is_created(map))
10922 		return libbpf_err(-EBUSY);
10923 
10924 	if (!map->mmaped || map->libbpf_type == LIBBPF_MAP_KCONFIG)
10925 		return libbpf_err(-EINVAL);
10926 
10927 	if (map->def.type == BPF_MAP_TYPE_ARENA)
10928 		actual_sz = map->obj->arena_data_sz;
10929 	else
10930 		actual_sz = map->def.value_size;
10931 	if (size != actual_sz)
10932 		return libbpf_err(-EINVAL);
10933 
10934 	memcpy(map->mmaped, data, size);
10935 	return 0;
10936 }
10937 
10938 void *bpf_map__initial_value(const struct bpf_map *map, size_t *psize)
10939 {
10940 	if (bpf_map__is_struct_ops(map)) {
10941 		if (psize)
10942 			*psize = map->def.value_size;
10943 		return map->st_ops->data;
10944 	}
10945 
10946 	if (!map->mmaped)
10947 		return NULL;
10948 
10949 	if (map->def.type == BPF_MAP_TYPE_ARENA)
10950 		*psize = map->obj->arena_data_sz;
10951 	else
10952 		*psize = map->def.value_size;
10953 
10954 	return map->mmaped;
10955 }
10956 
10957 bool bpf_map__is_internal(const struct bpf_map *map)
10958 {
10959 	return map->libbpf_type != LIBBPF_MAP_UNSPEC;
10960 }
10961 
10962 __u32 bpf_map__ifindex(const struct bpf_map *map)
10963 {
10964 	return map->map_ifindex;
10965 }
10966 
10967 int bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
10968 {
10969 	if (map_is_created(map))
10970 		return libbpf_err(-EBUSY);
10971 	map->map_ifindex = ifindex;
10972 	return 0;
10973 }
10974 
10975 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
10976 {
10977 	if (!bpf_map_type__is_map_in_map(map->def.type)) {
10978 		pr_warn("error: unsupported map type\n");
10979 		return libbpf_err(-EINVAL);
10980 	}
10981 	if (map->inner_map_fd != -1) {
10982 		pr_warn("error: inner_map_fd already specified\n");
10983 		return libbpf_err(-EINVAL);
10984 	}
10985 	if (map->inner_map) {
10986 		bpf_map__destroy(map->inner_map);
10987 		zfree(&map->inner_map);
10988 	}
10989 	map->inner_map_fd = fd;
10990 	return 0;
10991 }
10992 
10993 int bpf_map__set_exclusive_program(struct bpf_map *map, struct bpf_program *prog)
10994 {
10995 	if (map_is_created(map)) {
10996 		pr_warn("exclusive programs must be set before map creation\n");
10997 		return libbpf_err(-EINVAL);
10998 	}
10999 
11000 	if (map->obj != prog->obj) {
11001 		pr_warn("excl_prog and map must be from the same bpf object\n");
11002 		return libbpf_err(-EINVAL);
11003 	}
11004 
11005 	map->excl_prog = prog;
11006 	return 0;
11007 }
11008 
11009 struct bpf_program *bpf_map__exclusive_program(struct bpf_map *map)
11010 {
11011 	return map->excl_prog;
11012 }
11013 
11014 static struct bpf_map *
11015 __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
11016 {
11017 	ssize_t idx;
11018 	struct bpf_map *s, *e;
11019 
11020 	if (!obj || !obj->maps)
11021 		return errno = EINVAL, NULL;
11022 
11023 	s = obj->maps;
11024 	e = obj->maps + obj->nr_maps;
11025 
11026 	if ((m < s) || (m >= e)) {
11027 		pr_warn("error in %s: map handler doesn't belong to object\n",
11028 			 __func__);
11029 		return errno = EINVAL, NULL;
11030 	}
11031 
11032 	idx = (m - obj->maps) + i;
11033 	if (idx >= obj->nr_maps || idx < 0)
11034 		return NULL;
11035 	return &obj->maps[idx];
11036 }
11037 
11038 struct bpf_map *
11039 bpf_object__next_map(const struct bpf_object *obj, const struct bpf_map *prev)
11040 {
11041 	if (prev == NULL && obj != NULL)
11042 		return obj->maps;
11043 
11044 	return __bpf_map__iter(prev, obj, 1);
11045 }
11046 
11047 struct bpf_map *
11048 bpf_object__prev_map(const struct bpf_object *obj, const struct bpf_map *next)
11049 {
11050 	if (next == NULL && obj != NULL) {
11051 		if (!obj->nr_maps)
11052 			return NULL;
11053 		return obj->maps + obj->nr_maps - 1;
11054 	}
11055 
11056 	return __bpf_map__iter(next, obj, -1);
11057 }
11058 
11059 struct bpf_map *
11060 bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
11061 {
11062 	struct bpf_map *pos;
11063 
11064 	bpf_object__for_each_map(pos, obj) {
11065 		/* if it's a special internal map name (which always starts
11066 		 * with dot) then check if that special name matches the
11067 		 * real map name (ELF section name)
11068 		 */
11069 		if (name[0] == '.') {
11070 			if (pos->real_name && strcmp(pos->real_name, name) == 0)
11071 				return pos;
11072 			continue;
11073 		}
11074 		/* otherwise map name has to be an exact match */
11075 		if (map_uses_real_name(pos)) {
11076 			if (strcmp(pos->real_name, name) == 0)
11077 				return pos;
11078 			continue;
11079 		}
11080 		if (strcmp(pos->name, name) == 0)
11081 			return pos;
11082 	}
11083 	return errno = ENOENT, NULL;
11084 }
11085 
11086 int
11087 bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
11088 {
11089 	return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
11090 }
11091 
11092 static int validate_map_op(const struct bpf_map *map, size_t key_sz,
11093 			   size_t value_sz, bool check_value_sz, __u64 flags)
11094 {
11095 	if (!map_is_created(map)) /* map is not yet created */
11096 		return -ENOENT;
11097 
11098 	if (map->def.key_size != key_sz) {
11099 		pr_warn("map '%s': unexpected key size %zu provided, expected %u\n",
11100 			map->name, key_sz, map->def.key_size);
11101 		return -EINVAL;
11102 	}
11103 
11104 	if (map->fd < 0) {
11105 		pr_warn("map '%s': can't use BPF map without FD (was it created?)\n", map->name);
11106 		return -EINVAL;
11107 	}
11108 
11109 	if (!check_value_sz)
11110 		return 0;
11111 
11112 	switch (map->def.type) {
11113 	case BPF_MAP_TYPE_PERCPU_ARRAY:
11114 	case BPF_MAP_TYPE_PERCPU_HASH:
11115 	case BPF_MAP_TYPE_LRU_PERCPU_HASH:
11116 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: {
11117 		int num_cpu = libbpf_num_possible_cpus();
11118 		size_t elem_sz = roundup(map->def.value_size, 8);
11119 
11120 		if (flags & (BPF_F_CPU | BPF_F_ALL_CPUS)) {
11121 			if ((flags & BPF_F_CPU) && (flags & BPF_F_ALL_CPUS)) {
11122 				pr_warn("map '%s': BPF_F_CPU and BPF_F_ALL_CPUS are mutually exclusive\n",
11123 					map->name);
11124 				return -EINVAL;
11125 			}
11126 			if (map->def.value_size != value_sz) {
11127 				pr_warn("map '%s': unexpected value size %zu provided for either BPF_F_CPU or BPF_F_ALL_CPUS, expected %u\n",
11128 					map->name, value_sz, map->def.value_size);
11129 				return -EINVAL;
11130 			}
11131 			break;
11132 		}
11133 
11134 		if (value_sz != num_cpu * elem_sz) {
11135 			pr_warn("map '%s': unexpected value size %zu provided for per-CPU map, expected %d * %zu = %zd\n",
11136 				map->name, value_sz, num_cpu, elem_sz, num_cpu * elem_sz);
11137 			return -EINVAL;
11138 		}
11139 		break;
11140 	}
11141 	default:
11142 		if (map->def.value_size != value_sz) {
11143 			pr_warn("map '%s': unexpected value size %zu provided, expected %u\n",
11144 				map->name, value_sz, map->def.value_size);
11145 			return -EINVAL;
11146 		}
11147 		break;
11148 	}
11149 	return 0;
11150 }
11151 
11152 int bpf_map__lookup_elem(const struct bpf_map *map,
11153 			 const void *key, size_t key_sz,
11154 			 void *value, size_t value_sz, __u64 flags)
11155 {
11156 	int err;
11157 
11158 	err = validate_map_op(map, key_sz, value_sz, true, flags);
11159 	if (err)
11160 		return libbpf_err(err);
11161 
11162 	return bpf_map_lookup_elem_flags(map->fd, key, value, flags);
11163 }
11164 
11165 int bpf_map__update_elem(const struct bpf_map *map,
11166 			 const void *key, size_t key_sz,
11167 			 const void *value, size_t value_sz, __u64 flags)
11168 {
11169 	int err;
11170 
11171 	err = validate_map_op(map, key_sz, value_sz, true, flags);
11172 	if (err)
11173 		return libbpf_err(err);
11174 
11175 	return bpf_map_update_elem(map->fd, key, value, flags);
11176 }
11177 
11178 int bpf_map__delete_elem(const struct bpf_map *map,
11179 			 const void *key, size_t key_sz, __u64 flags)
11180 {
11181 	int err;
11182 
11183 	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */, flags);
11184 	if (err)
11185 		return libbpf_err(err);
11186 
11187 	return bpf_map_delete_elem_flags(map->fd, key, flags);
11188 }
11189 
11190 int bpf_map__lookup_and_delete_elem(const struct bpf_map *map,
11191 				    const void *key, size_t key_sz,
11192 				    void *value, size_t value_sz, __u64 flags)
11193 {
11194 	int err;
11195 
11196 	err = validate_map_op(map, key_sz, value_sz, true, flags);
11197 	if (err)
11198 		return libbpf_err(err);
11199 
11200 	return bpf_map_lookup_and_delete_elem_flags(map->fd, key, value, flags);
11201 }
11202 
11203 int bpf_map__get_next_key(const struct bpf_map *map,
11204 			  const void *cur_key, void *next_key, size_t key_sz)
11205 {
11206 	int err;
11207 
11208 	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */, 0);
11209 	if (err)
11210 		return libbpf_err(err);
11211 
11212 	return bpf_map_get_next_key(map->fd, cur_key, next_key);
11213 }
11214 
11215 long libbpf_get_error(const void *ptr)
11216 {
11217 	if (!IS_ERR_OR_NULL(ptr))
11218 		return 0;
11219 
11220 	if (IS_ERR(ptr))
11221 		errno = -PTR_ERR(ptr);
11222 
11223 	/* If ptr == NULL, then errno should be already set by the failing
11224 	 * API, because libbpf never returns NULL on success and it now always
11225 	 * sets errno on error. So no extra errno handling for ptr == NULL
11226 	 * case.
11227 	 */
11228 	return -errno;
11229 }
11230 
11231 /* Replace link's underlying BPF program with the new one */
11232 int bpf_link__update_program(struct bpf_link *link, struct bpf_program *prog)
11233 {
11234 	int ret;
11235 	int prog_fd = bpf_program__fd(prog);
11236 
11237 	if (prog_fd < 0) {
11238 		pr_warn("prog '%s': can't use BPF program without FD (was it loaded?)\n",
11239 			prog->name);
11240 		return libbpf_err(-EINVAL);
11241 	}
11242 
11243 	ret = bpf_link_update(bpf_link__fd(link), prog_fd, NULL);
11244 	return libbpf_err_errno(ret);
11245 }
11246 
11247 /* Release "ownership" of underlying BPF resource (typically, BPF program
11248  * attached to some BPF hook, e.g., tracepoint, kprobe, etc). Disconnected
11249  * link, when destructed through bpf_link__destroy() call won't attempt to
11250  * detach/unregisted that BPF resource. This is useful in situations where,
11251  * say, attached BPF program has to outlive userspace program that attached it
11252  * in the system. Depending on type of BPF program, though, there might be
11253  * additional steps (like pinning BPF program in BPF FS) necessary to ensure
11254  * exit of userspace program doesn't trigger automatic detachment and clean up
11255  * inside the kernel.
11256  */
11257 void bpf_link__disconnect(struct bpf_link *link)
11258 {
11259 	link->disconnected = true;
11260 }
11261 
11262 int bpf_link__destroy(struct bpf_link *link)
11263 {
11264 	int err = 0;
11265 
11266 	if (IS_ERR_OR_NULL(link))
11267 		return 0;
11268 
11269 	if (!link->disconnected && link->detach)
11270 		err = link->detach(link);
11271 	if (link->pin_path)
11272 		free(link->pin_path);
11273 	if (link->dealloc)
11274 		link->dealloc(link);
11275 	else
11276 		free(link);
11277 
11278 	return libbpf_err(err);
11279 }
11280 
11281 int bpf_link__fd(const struct bpf_link *link)
11282 {
11283 	return link->fd;
11284 }
11285 
11286 const char *bpf_link__pin_path(const struct bpf_link *link)
11287 {
11288 	return link->pin_path;
11289 }
11290 
11291 static int bpf_link__detach_fd(struct bpf_link *link)
11292 {
11293 	return libbpf_err_errno(close(link->fd));
11294 }
11295 
11296 struct bpf_link *bpf_link__open(const char *path)
11297 {
11298 	struct bpf_link *link;
11299 	int fd;
11300 
11301 	fd = bpf_obj_get(path);
11302 	if (fd < 0) {
11303 		fd = -errno;
11304 		pr_warn("failed to open link at %s: %d\n", path, fd);
11305 		return libbpf_err_ptr(fd);
11306 	}
11307 
11308 	link = calloc(1, sizeof(*link));
11309 	if (!link) {
11310 		close(fd);
11311 		return libbpf_err_ptr(-ENOMEM);
11312 	}
11313 	link->detach = &bpf_link__detach_fd;
11314 	link->fd = fd;
11315 
11316 	link->pin_path = strdup(path);
11317 	if (!link->pin_path) {
11318 		bpf_link__destroy(link);
11319 		return libbpf_err_ptr(-ENOMEM);
11320 	}
11321 
11322 	return link;
11323 }
11324 
11325 int bpf_link__detach(struct bpf_link *link)
11326 {
11327 	return bpf_link_detach(link->fd) ? -errno : 0;
11328 }
11329 
11330 int bpf_link__pin(struct bpf_link *link, const char *path)
11331 {
11332 	int err;
11333 
11334 	if (link->pin_path)
11335 		return libbpf_err(-EBUSY);
11336 	err = make_parent_dir(path);
11337 	if (err)
11338 		return libbpf_err(err);
11339 	err = check_path(path);
11340 	if (err)
11341 		return libbpf_err(err);
11342 
11343 	link->pin_path = strdup(path);
11344 	if (!link->pin_path)
11345 		return libbpf_err(-ENOMEM);
11346 
11347 	if (bpf_obj_pin(link->fd, link->pin_path)) {
11348 		err = -errno;
11349 		zfree(&link->pin_path);
11350 		return libbpf_err(err);
11351 	}
11352 
11353 	pr_debug("link fd=%d: pinned at %s\n", link->fd, link->pin_path);
11354 	return 0;
11355 }
11356 
11357 int bpf_link__unpin(struct bpf_link *link)
11358 {
11359 	int err;
11360 
11361 	if (!link->pin_path)
11362 		return libbpf_err(-EINVAL);
11363 
11364 	err = unlink(link->pin_path);
11365 	if (err != 0)
11366 		return -errno;
11367 
11368 	pr_debug("link fd=%d: unpinned from %s\n", link->fd, link->pin_path);
11369 	zfree(&link->pin_path);
11370 	return 0;
11371 }
11372 
11373 struct bpf_link_perf {
11374 	struct bpf_link link;
11375 	int perf_event_fd;
11376 	/* legacy kprobe support: keep track of probe identifier and type */
11377 	char *legacy_probe_name;
11378 	bool legacy_is_kprobe;
11379 	bool legacy_is_retprobe;
11380 };
11381 
11382 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe);
11383 static int remove_uprobe_event_legacy(const char *probe_name, bool retprobe);
11384 
11385 static int bpf_link_perf_detach(struct bpf_link *link)
11386 {
11387 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
11388 	int err = 0;
11389 
11390 	if (ioctl(perf_link->perf_event_fd, PERF_EVENT_IOC_DISABLE, 0) < 0)
11391 		err = -errno;
11392 
11393 	if (perf_link->perf_event_fd != link->fd)
11394 		close(perf_link->perf_event_fd);
11395 	close(link->fd);
11396 
11397 	/* legacy uprobe/kprobe needs to be removed after perf event fd closure */
11398 	if (perf_link->legacy_probe_name) {
11399 		if (perf_link->legacy_is_kprobe) {
11400 			err = remove_kprobe_event_legacy(perf_link->legacy_probe_name,
11401 							 perf_link->legacy_is_retprobe);
11402 		} else {
11403 			err = remove_uprobe_event_legacy(perf_link->legacy_probe_name,
11404 							 perf_link->legacy_is_retprobe);
11405 		}
11406 	}
11407 
11408 	return err;
11409 }
11410 
11411 static void bpf_link_perf_dealloc(struct bpf_link *link)
11412 {
11413 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
11414 
11415 	free(perf_link->legacy_probe_name);
11416 	free(perf_link);
11417 }
11418 
11419 struct bpf_link *bpf_program__attach_perf_event_opts(const struct bpf_program *prog, int pfd,
11420 						     const struct bpf_perf_event_opts *opts)
11421 {
11422 	struct bpf_link_perf *link;
11423 	int prog_fd, link_fd = -1, err;
11424 	bool force_ioctl_attach;
11425 
11426 	if (!OPTS_VALID(opts, bpf_perf_event_opts))
11427 		return libbpf_err_ptr(-EINVAL);
11428 
11429 	if (pfd < 0) {
11430 		pr_warn("prog '%s': invalid perf event FD %d\n",
11431 			prog->name, pfd);
11432 		return libbpf_err_ptr(-EINVAL);
11433 	}
11434 	prog_fd = bpf_program__fd(prog);
11435 	if (prog_fd < 0) {
11436 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
11437 			prog->name);
11438 		return libbpf_err_ptr(-EINVAL);
11439 	}
11440 
11441 	link = calloc(1, sizeof(*link));
11442 	if (!link)
11443 		return libbpf_err_ptr(-ENOMEM);
11444 	link->link.detach = &bpf_link_perf_detach;
11445 	link->link.dealloc = &bpf_link_perf_dealloc;
11446 	link->perf_event_fd = pfd;
11447 
11448 	force_ioctl_attach = OPTS_GET(opts, force_ioctl_attach, false);
11449 	if (kernel_supports(prog->obj, FEAT_PERF_LINK) && !force_ioctl_attach) {
11450 		DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_opts,
11451 			.perf_event.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0));
11452 
11453 		link_fd = bpf_link_create(prog_fd, pfd, BPF_PERF_EVENT, &link_opts);
11454 		if (link_fd < 0) {
11455 			err = -errno;
11456 			pr_warn("prog '%s': failed to create BPF link for perf_event FD %d: %s\n",
11457 				prog->name, pfd, errstr(err));
11458 			goto err_out;
11459 		}
11460 		link->link.fd = link_fd;
11461 	} else {
11462 		if (OPTS_GET(opts, bpf_cookie, 0)) {
11463 			pr_warn("prog '%s': user context value is not supported\n", prog->name);
11464 			err = -EOPNOTSUPP;
11465 			goto err_out;
11466 		}
11467 
11468 		if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
11469 			err = -errno;
11470 			pr_warn("prog '%s': failed to attach to perf_event FD %d: %s\n",
11471 				prog->name, pfd, errstr(err));
11472 			if (err == -EPROTO)
11473 				pr_warn("prog '%s': try add PERF_SAMPLE_CALLCHAIN to or remove exclude_callchain_[kernel|user] from pfd %d\n",
11474 					prog->name, pfd);
11475 			goto err_out;
11476 		}
11477 		link->link.fd = pfd;
11478 	}
11479 
11480 	if (!OPTS_GET(opts, dont_enable, false)) {
11481 		if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
11482 			err = -errno;
11483 			pr_warn("prog '%s': failed to enable perf_event FD %d: %s\n",
11484 				prog->name, pfd, errstr(err));
11485 			goto err_out;
11486 		}
11487 	}
11488 
11489 	return &link->link;
11490 err_out:
11491 	if (link_fd >= 0)
11492 		close(link_fd);
11493 	free(link);
11494 	return libbpf_err_ptr(err);
11495 }
11496 
11497 struct bpf_link *bpf_program__attach_perf_event(const struct bpf_program *prog, int pfd)
11498 {
11499 	return bpf_program__attach_perf_event_opts(prog, pfd, NULL);
11500 }
11501 
11502 /*
11503  * this function is expected to parse integer in the range of [0, 2^31-1] from
11504  * given file using scanf format string fmt. If actual parsed value is
11505  * negative, the result might be indistinguishable from error
11506  */
11507 static int parse_uint_from_file(const char *file, const char *fmt)
11508 {
11509 	int err, ret;
11510 	FILE *f;
11511 
11512 	f = fopen(file, "re");
11513 	if (!f) {
11514 		err = -errno;
11515 		pr_debug("failed to open '%s': %s\n", file, errstr(err));
11516 		return err;
11517 	}
11518 	err = fscanf(f, fmt, &ret);
11519 	if (err != 1) {
11520 		err = err == EOF ? -EIO : -errno;
11521 		pr_debug("failed to parse '%s': %s\n", file, errstr(err));
11522 		fclose(f);
11523 		return err;
11524 	}
11525 	fclose(f);
11526 	return ret;
11527 }
11528 
11529 static int determine_kprobe_perf_type(void)
11530 {
11531 	const char *file = "/sys/bus/event_source/devices/kprobe/type";
11532 
11533 	return parse_uint_from_file(file, "%d\n");
11534 }
11535 
11536 static int determine_uprobe_perf_type(void)
11537 {
11538 	const char *file = "/sys/bus/event_source/devices/uprobe/type";
11539 
11540 	return parse_uint_from_file(file, "%d\n");
11541 }
11542 
11543 static int determine_kprobe_retprobe_bit(void)
11544 {
11545 	const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
11546 
11547 	return parse_uint_from_file(file, "config:%d\n");
11548 }
11549 
11550 static int determine_uprobe_retprobe_bit(void)
11551 {
11552 	const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
11553 
11554 	return parse_uint_from_file(file, "config:%d\n");
11555 }
11556 
11557 #define PERF_UPROBE_REF_CTR_OFFSET_BITS 32
11558 #define PERF_UPROBE_REF_CTR_OFFSET_SHIFT 32
11559 
11560 static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
11561 				 uint64_t offset, int pid, size_t ref_ctr_off)
11562 {
11563 	const size_t attr_sz = sizeof(struct perf_event_attr);
11564 	struct perf_event_attr attr;
11565 	int type, pfd;
11566 
11567 	if ((__u64)ref_ctr_off >= (1ULL << PERF_UPROBE_REF_CTR_OFFSET_BITS))
11568 		return -EINVAL;
11569 
11570 	memset(&attr, 0, attr_sz);
11571 
11572 	type = uprobe ? determine_uprobe_perf_type()
11573 		      : determine_kprobe_perf_type();
11574 	if (type < 0) {
11575 		pr_warn("failed to determine %s perf type: %s\n",
11576 			uprobe ? "uprobe" : "kprobe",
11577 			errstr(type));
11578 		return type;
11579 	}
11580 	if (retprobe) {
11581 		int bit = uprobe ? determine_uprobe_retprobe_bit()
11582 				 : determine_kprobe_retprobe_bit();
11583 
11584 		if (bit < 0) {
11585 			pr_warn("failed to determine %s retprobe bit: %s\n",
11586 				uprobe ? "uprobe" : "kprobe",
11587 				errstr(bit));
11588 			return bit;
11589 		}
11590 		attr.config |= 1 << bit;
11591 	}
11592 	attr.size = attr_sz;
11593 	attr.type = type;
11594 	attr.config |= (__u64)ref_ctr_off << PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
11595 	attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
11596 	attr.config2 = offset;		 /* kprobe_addr or probe_offset */
11597 
11598 	/* pid filter is meaningful only for uprobes */
11599 	pfd = syscall(__NR_perf_event_open, &attr,
11600 		      pid < 0 ? -1 : pid /* pid */,
11601 		      pid == -1 ? 0 : -1 /* cpu */,
11602 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
11603 	return pfd >= 0 ? pfd : -errno;
11604 }
11605 
11606 static int append_to_file(const char *file, const char *fmt, ...)
11607 {
11608 	int fd, n, err = 0;
11609 	va_list ap;
11610 	char buf[1024];
11611 
11612 	va_start(ap, fmt);
11613 	n = vsnprintf(buf, sizeof(buf), fmt, ap);
11614 	va_end(ap);
11615 
11616 	if (n < 0 || n >= sizeof(buf))
11617 		return -EINVAL;
11618 
11619 	fd = open(file, O_WRONLY | O_APPEND | O_CLOEXEC, 0);
11620 	if (fd < 0)
11621 		return -errno;
11622 
11623 	if (write(fd, buf, n) < 0)
11624 		err = -errno;
11625 
11626 	close(fd);
11627 	return err;
11628 }
11629 
11630 #define DEBUGFS "/sys/kernel/debug/tracing"
11631 #define TRACEFS "/sys/kernel/tracing"
11632 
11633 static bool use_debugfs(void)
11634 {
11635 	static int has_debugfs = -1;
11636 
11637 	if (has_debugfs < 0)
11638 		has_debugfs = faccessat(AT_FDCWD, DEBUGFS, F_OK, AT_EACCESS) == 0;
11639 
11640 	return has_debugfs == 1;
11641 }
11642 
11643 static const char *tracefs_path(void)
11644 {
11645 	return use_debugfs() ? DEBUGFS : TRACEFS;
11646 }
11647 
11648 static const char *tracefs_kprobe_events(void)
11649 {
11650 	return use_debugfs() ? DEBUGFS"/kprobe_events" : TRACEFS"/kprobe_events";
11651 }
11652 
11653 static const char *tracefs_uprobe_events(void)
11654 {
11655 	return use_debugfs() ? DEBUGFS"/uprobe_events" : TRACEFS"/uprobe_events";
11656 }
11657 
11658 static const char *tracefs_available_filter_functions(void)
11659 {
11660 	return use_debugfs() ? DEBUGFS"/available_filter_functions"
11661 			     : TRACEFS"/available_filter_functions";
11662 }
11663 
11664 static const char *tracefs_available_filter_functions_addrs(void)
11665 {
11666 	return use_debugfs() ? DEBUGFS"/available_filter_functions_addrs"
11667 			     : TRACEFS"/available_filter_functions_addrs";
11668 }
11669 
11670 static void gen_probe_legacy_event_name(char *buf, size_t buf_sz,
11671 					const char *name, size_t offset)
11672 {
11673 	static int index = 0;
11674 	int i;
11675 
11676 	snprintf(buf, buf_sz, "libbpf_%u_%d_%s_0x%zx", getpid(),
11677 		 __sync_fetch_and_add(&index, 1), name, offset);
11678 
11679 	/* sanitize name in the probe name */
11680 	for (i = 0; buf[i]; i++) {
11681 		if (!isalnum(buf[i]))
11682 			buf[i] = '_';
11683 	}
11684 }
11685 
11686 static int add_kprobe_event_legacy(const char *probe_name, bool retprobe,
11687 				   const char *kfunc_name, size_t offset)
11688 {
11689 	return append_to_file(tracefs_kprobe_events(), "%c:%s/%s %s+0x%zx",
11690 			      retprobe ? 'r' : 'p',
11691 			      retprobe ? "kretprobes" : "kprobes",
11692 			      probe_name, kfunc_name, offset);
11693 }
11694 
11695 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe)
11696 {
11697 	return append_to_file(tracefs_kprobe_events(), "-:%s/%s",
11698 			      retprobe ? "kretprobes" : "kprobes", probe_name);
11699 }
11700 
11701 static int determine_kprobe_perf_type_legacy(const char *probe_name, bool retprobe)
11702 {
11703 	char file[256];
11704 
11705 	snprintf(file, sizeof(file), "%s/events/%s/%s/id",
11706 		 tracefs_path(), retprobe ? "kretprobes" : "kprobes", probe_name);
11707 
11708 	return parse_uint_from_file(file, "%d\n");
11709 }
11710 
11711 static int perf_event_kprobe_open_legacy(const char *probe_name, bool retprobe,
11712 					 const char *kfunc_name, size_t offset, int pid)
11713 {
11714 	const size_t attr_sz = sizeof(struct perf_event_attr);
11715 	struct perf_event_attr attr;
11716 	int type, pfd, err;
11717 
11718 	err = add_kprobe_event_legacy(probe_name, retprobe, kfunc_name, offset);
11719 	if (err < 0) {
11720 		pr_warn("failed to add legacy kprobe event for '%s+0x%zx': %s\n",
11721 			kfunc_name, offset,
11722 			errstr(err));
11723 		return err;
11724 	}
11725 	type = determine_kprobe_perf_type_legacy(probe_name, retprobe);
11726 	if (type < 0) {
11727 		err = type;
11728 		pr_warn("failed to determine legacy kprobe event id for '%s+0x%zx': %s\n",
11729 			kfunc_name, offset,
11730 			errstr(err));
11731 		goto err_clean_legacy;
11732 	}
11733 
11734 	memset(&attr, 0, attr_sz);
11735 	attr.size = attr_sz;
11736 	attr.config = type;
11737 	attr.type = PERF_TYPE_TRACEPOINT;
11738 
11739 	pfd = syscall(__NR_perf_event_open, &attr,
11740 		      pid < 0 ? -1 : pid, /* pid */
11741 		      pid == -1 ? 0 : -1, /* cpu */
11742 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
11743 	if (pfd < 0) {
11744 		err = -errno;
11745 		pr_warn("legacy kprobe perf_event_open() failed: %s\n",
11746 			errstr(err));
11747 		goto err_clean_legacy;
11748 	}
11749 	return pfd;
11750 
11751 err_clean_legacy:
11752 	/* Clear the newly added legacy kprobe_event */
11753 	remove_kprobe_event_legacy(probe_name, retprobe);
11754 	return err;
11755 }
11756 
11757 static const char *arch_specific_syscall_pfx(void)
11758 {
11759 #if defined(__x86_64__)
11760 	return "x64";
11761 #elif defined(__i386__)
11762 	return "ia32";
11763 #elif defined(__s390x__)
11764 	return "s390x";
11765 #elif defined(__arm__)
11766 	return "arm";
11767 #elif defined(__aarch64__)
11768 	return "arm64";
11769 #elif defined(__mips__)
11770 	return "mips";
11771 #elif defined(__riscv)
11772 	return "riscv";
11773 #elif defined(__powerpc__)
11774 	return "powerpc";
11775 #elif defined(__powerpc64__)
11776 	return "powerpc64";
11777 #else
11778 	return NULL;
11779 #endif
11780 }
11781 
11782 int probe_kern_syscall_wrapper(int token_fd)
11783 {
11784 	char syscall_name[64];
11785 	const char *ksys_pfx;
11786 
11787 	ksys_pfx = arch_specific_syscall_pfx();
11788 	if (!ksys_pfx)
11789 		return 0;
11790 
11791 	snprintf(syscall_name, sizeof(syscall_name), "__%s_sys_bpf", ksys_pfx);
11792 
11793 	if (determine_kprobe_perf_type() >= 0) {
11794 		int pfd;
11795 
11796 		pfd = perf_event_open_probe(false, false, syscall_name, 0, getpid(), 0);
11797 		if (pfd >= 0)
11798 			close(pfd);
11799 
11800 		return pfd >= 0 ? 1 : 0;
11801 	} else { /* legacy mode */
11802 		char probe_name[MAX_EVENT_NAME_LEN];
11803 
11804 		gen_probe_legacy_event_name(probe_name, sizeof(probe_name), syscall_name, 0);
11805 		if (add_kprobe_event_legacy(probe_name, false, syscall_name, 0) < 0)
11806 			return 0;
11807 
11808 		(void)remove_kprobe_event_legacy(probe_name, false);
11809 		return 1;
11810 	}
11811 }
11812 
11813 struct bpf_link *
11814 bpf_program__attach_kprobe_opts(const struct bpf_program *prog,
11815 				const char *func_name,
11816 				const struct bpf_kprobe_opts *opts)
11817 {
11818 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
11819 	enum probe_attach_mode attach_mode;
11820 	char *legacy_probe = NULL;
11821 	struct bpf_link *link;
11822 	size_t offset;
11823 	bool retprobe, legacy;
11824 	int pfd, err;
11825 
11826 	if (!OPTS_VALID(opts, bpf_kprobe_opts))
11827 		return libbpf_err_ptr(-EINVAL);
11828 
11829 	attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
11830 	retprobe = OPTS_GET(opts, retprobe, false);
11831 	offset = OPTS_GET(opts, offset, 0);
11832 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11833 
11834 	legacy = determine_kprobe_perf_type() < 0;
11835 	switch (attach_mode) {
11836 	case PROBE_ATTACH_MODE_LEGACY:
11837 		legacy = true;
11838 		pe_opts.force_ioctl_attach = true;
11839 		break;
11840 	case PROBE_ATTACH_MODE_PERF:
11841 		if (legacy)
11842 			return libbpf_err_ptr(-ENOTSUP);
11843 		pe_opts.force_ioctl_attach = true;
11844 		break;
11845 	case PROBE_ATTACH_MODE_LINK:
11846 		if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
11847 			return libbpf_err_ptr(-ENOTSUP);
11848 		break;
11849 	case PROBE_ATTACH_MODE_DEFAULT:
11850 		break;
11851 	default:
11852 		return libbpf_err_ptr(-EINVAL);
11853 	}
11854 	if (!func_name && legacy)
11855 		return libbpf_err_ptr(-EOPNOTSUPP);
11856 
11857 	if (!legacy) {
11858 		pfd = perf_event_open_probe(false /* uprobe */, retprobe,
11859 					    func_name, offset,
11860 					    -1 /* pid */, 0 /* ref_ctr_off */);
11861 	} else {
11862 		char probe_name[MAX_EVENT_NAME_LEN];
11863 
11864 		gen_probe_legacy_event_name(probe_name, sizeof(probe_name),
11865 					    func_name, offset);
11866 
11867 		legacy_probe = strdup(probe_name);
11868 		if (!legacy_probe)
11869 			return libbpf_err_ptr(-ENOMEM);
11870 
11871 		pfd = perf_event_kprobe_open_legacy(legacy_probe, retprobe, func_name,
11872 						    offset, -1 /* pid */);
11873 	}
11874 	if (pfd < 0) {
11875 		err = pfd;
11876 		pr_warn("prog '%s': failed to create %s '%s%s0x%zx' perf event: %s\n",
11877 			prog->name, retprobe ? "kretprobe" : "kprobe",
11878 			func_name ?: "", func_name ? "+" : "",
11879 			offset, errstr(err));
11880 		goto err_out;
11881 	}
11882 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
11883 	err = libbpf_get_error(link);
11884 	if (err) {
11885 		close(pfd);
11886 		pr_warn("prog '%s': failed to attach to %s '%s%s0x%zx': %s\n",
11887 			prog->name, retprobe ? "kretprobe" : "kprobe",
11888 			func_name ?: "", func_name ? "+" : "",
11889 			offset, errstr(err));
11890 		goto err_clean_legacy;
11891 	}
11892 	if (legacy) {
11893 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
11894 
11895 		perf_link->legacy_probe_name = legacy_probe;
11896 		perf_link->legacy_is_kprobe = true;
11897 		perf_link->legacy_is_retprobe = retprobe;
11898 	}
11899 
11900 	return link;
11901 
11902 err_clean_legacy:
11903 	if (legacy)
11904 		remove_kprobe_event_legacy(legacy_probe, retprobe);
11905 err_out:
11906 	free(legacy_probe);
11907 	return libbpf_err_ptr(err);
11908 }
11909 
11910 struct bpf_link *bpf_program__attach_kprobe(const struct bpf_program *prog,
11911 					    bool retprobe,
11912 					    const char *func_name)
11913 {
11914 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts,
11915 		.retprobe = retprobe,
11916 	);
11917 
11918 	return bpf_program__attach_kprobe_opts(prog, func_name, &opts);
11919 }
11920 
11921 struct bpf_link *bpf_program__attach_ksyscall(const struct bpf_program *prog,
11922 					      const char *syscall_name,
11923 					      const struct bpf_ksyscall_opts *opts)
11924 {
11925 	LIBBPF_OPTS(bpf_kprobe_opts, kprobe_opts);
11926 	char func_name[128];
11927 
11928 	if (!OPTS_VALID(opts, bpf_ksyscall_opts))
11929 		return libbpf_err_ptr(-EINVAL);
11930 
11931 	if (kernel_supports(prog->obj, FEAT_SYSCALL_WRAPPER)) {
11932 		/* arch_specific_syscall_pfx() should never return NULL here
11933 		 * because it is guarded by kernel_supports(). However, since
11934 		 * compiler does not know that we have an explicit conditional
11935 		 * as well.
11936 		 */
11937 		snprintf(func_name, sizeof(func_name), "__%s_sys_%s",
11938 			 arch_specific_syscall_pfx() ? : "", syscall_name);
11939 	} else {
11940 		snprintf(func_name, sizeof(func_name), "__se_sys_%s", syscall_name);
11941 	}
11942 
11943 	kprobe_opts.retprobe = OPTS_GET(opts, retprobe, false);
11944 	kprobe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11945 
11946 	return bpf_program__attach_kprobe_opts(prog, func_name, &kprobe_opts);
11947 }
11948 
11949 /* Adapted from perf/util/string.c */
11950 bool glob_match(const char *str, const char *pat)
11951 {
11952 	while (*str && *pat && *pat != '*') {
11953 		if (*pat == '?') {      /* Matches any single character */
11954 			str++;
11955 			pat++;
11956 			continue;
11957 		}
11958 		if (*str != *pat)
11959 			return false;
11960 		str++;
11961 		pat++;
11962 	}
11963 	/* Check wild card */
11964 	if (*pat == '*') {
11965 		while (*pat == '*')
11966 			pat++;
11967 		if (!*pat) /* Tail wild card matches all */
11968 			return true;
11969 		while (*str)
11970 			if (glob_match(str++, pat))
11971 				return true;
11972 	}
11973 	return !*str && !*pat;
11974 }
11975 
11976 struct kprobe_multi_resolve {
11977 	const char *pattern;
11978 	unsigned long *addrs;
11979 	size_t cap;
11980 	size_t cnt;
11981 };
11982 
11983 struct avail_kallsyms_data {
11984 	char **syms;
11985 	size_t cnt;
11986 	struct kprobe_multi_resolve *res;
11987 };
11988 
11989 static int avail_func_cmp(const void *a, const void *b)
11990 {
11991 	return strcmp(*(const char **)a, *(const char **)b);
11992 }
11993 
11994 static int avail_kallsyms_cb(unsigned long long sym_addr, char sym_type,
11995 			     const char *sym_name, void *ctx)
11996 {
11997 	struct avail_kallsyms_data *data = ctx;
11998 	struct kprobe_multi_resolve *res = data->res;
11999 	int err;
12000 
12001 	if (!glob_match(sym_name, res->pattern))
12002 		return 0;
12003 
12004 	if (!bsearch(&sym_name, data->syms, data->cnt, sizeof(*data->syms), avail_func_cmp)) {
12005 		/* Some versions of kernel strip out .llvm.<hash> suffix from
12006 		 * function names reported in available_filter_functions, but
12007 		 * don't do so for kallsyms. While this is clearly a kernel
12008 		 * bug (fixed by [0]) we try to accommodate that in libbpf to
12009 		 * make multi-kprobe usability a bit better: if no match is
12010 		 * found, we will strip .llvm. suffix and try one more time.
12011 		 *
12012 		 *   [0] fb6a421fb615 ("kallsyms: Match symbols exactly with CONFIG_LTO_CLANG")
12013 		 */
12014 		char sym_trim[256], *psym_trim = sym_trim;
12015 		const char *sym_sfx;
12016 
12017 		if (!(sym_sfx = strstr(sym_name, ".llvm.")))
12018 			return 0;
12019 
12020 		/* psym_trim vs sym_trim dance is done to avoid pointer vs array
12021 		 * coercion differences and get proper `const char **` pointer
12022 		 * which avail_func_cmp() expects
12023 		 */
12024 		snprintf(sym_trim, sizeof(sym_trim), "%.*s", (int)(sym_sfx - sym_name), sym_name);
12025 		if (!bsearch(&psym_trim, data->syms, data->cnt, sizeof(*data->syms), avail_func_cmp))
12026 			return 0;
12027 	}
12028 
12029 	err = libbpf_ensure_mem((void **)&res->addrs, &res->cap, sizeof(*res->addrs), res->cnt + 1);
12030 	if (err)
12031 		return err;
12032 
12033 	res->addrs[res->cnt++] = (unsigned long)sym_addr;
12034 	return 0;
12035 }
12036 
12037 static int libbpf_available_kallsyms_parse(struct kprobe_multi_resolve *res)
12038 {
12039 	const char *available_functions_file = tracefs_available_filter_functions();
12040 	struct avail_kallsyms_data data;
12041 	char sym_name[500];
12042 	FILE *f;
12043 	int err = 0, ret, i;
12044 	char **syms = NULL;
12045 	size_t cap = 0, cnt = 0;
12046 
12047 	f = fopen(available_functions_file, "re");
12048 	if (!f) {
12049 		err = -errno;
12050 		pr_warn("failed to open %s: %s\n", available_functions_file, errstr(err));
12051 		return err;
12052 	}
12053 
12054 	while (true) {
12055 		char *name;
12056 
12057 		ret = fscanf(f, "%499s%*[^\n]\n", sym_name);
12058 		if (ret == EOF && feof(f))
12059 			break;
12060 
12061 		if (ret != 1) {
12062 			pr_warn("failed to parse available_filter_functions entry: %d\n", ret);
12063 			err = -EINVAL;
12064 			goto cleanup;
12065 		}
12066 
12067 		if (!glob_match(sym_name, res->pattern))
12068 			continue;
12069 
12070 		err = libbpf_ensure_mem((void **)&syms, &cap, sizeof(*syms), cnt + 1);
12071 		if (err)
12072 			goto cleanup;
12073 
12074 		name = strdup(sym_name);
12075 		if (!name) {
12076 			err = -errno;
12077 			goto cleanup;
12078 		}
12079 
12080 		syms[cnt++] = name;
12081 	}
12082 
12083 	/* no entries found, bail out */
12084 	if (cnt == 0) {
12085 		err = -ENOENT;
12086 		goto cleanup;
12087 	}
12088 
12089 	/* sort available functions */
12090 	qsort(syms, cnt, sizeof(*syms), avail_func_cmp);
12091 
12092 	data.syms = syms;
12093 	data.res = res;
12094 	data.cnt = cnt;
12095 	libbpf_kallsyms_parse(avail_kallsyms_cb, &data);
12096 
12097 	if (res->cnt == 0)
12098 		err = -ENOENT;
12099 
12100 cleanup:
12101 	for (i = 0; i < cnt; i++)
12102 		free((char *)syms[i]);
12103 	free(syms);
12104 
12105 	fclose(f);
12106 	return err;
12107 }
12108 
12109 static bool has_available_filter_functions_addrs(void)
12110 {
12111 	return access(tracefs_available_filter_functions_addrs(), R_OK) != -1;
12112 }
12113 
12114 static int libbpf_available_kprobes_parse(struct kprobe_multi_resolve *res)
12115 {
12116 	const char *available_path = tracefs_available_filter_functions_addrs();
12117 	char sym_name[500];
12118 	FILE *f;
12119 	int ret, err = 0;
12120 	unsigned long long sym_addr;
12121 
12122 	f = fopen(available_path, "re");
12123 	if (!f) {
12124 		err = -errno;
12125 		pr_warn("failed to open %s: %s\n", available_path, errstr(err));
12126 		return err;
12127 	}
12128 
12129 	while (true) {
12130 		ret = fscanf(f, "%llx %499s%*[^\n]\n", &sym_addr, sym_name);
12131 		if (ret == EOF && feof(f))
12132 			break;
12133 
12134 		if (ret != 2) {
12135 			pr_warn("failed to parse available_filter_functions_addrs entry: %d\n",
12136 				ret);
12137 			err = -EINVAL;
12138 			goto cleanup;
12139 		}
12140 
12141 		if (!glob_match(sym_name, res->pattern))
12142 			continue;
12143 
12144 		err = libbpf_ensure_mem((void **)&res->addrs, &res->cap,
12145 					sizeof(*res->addrs), res->cnt + 1);
12146 		if (err)
12147 			goto cleanup;
12148 
12149 		res->addrs[res->cnt++] = (unsigned long)sym_addr;
12150 	}
12151 
12152 	if (res->cnt == 0)
12153 		err = -ENOENT;
12154 
12155 cleanup:
12156 	fclose(f);
12157 	return err;
12158 }
12159 
12160 struct bpf_link *
12161 bpf_program__attach_kprobe_multi_opts(const struct bpf_program *prog,
12162 				      const char *pattern,
12163 				      const struct bpf_kprobe_multi_opts *opts)
12164 {
12165 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
12166 	struct kprobe_multi_resolve res = {
12167 		.pattern = pattern,
12168 	};
12169 	enum bpf_attach_type attach_type;
12170 	struct bpf_link *link = NULL;
12171 	const unsigned long *addrs;
12172 	int err, link_fd, prog_fd;
12173 	bool retprobe, session, unique_match;
12174 	const __u64 *cookies;
12175 	const char **syms;
12176 	size_t cnt;
12177 
12178 	if (!OPTS_VALID(opts, bpf_kprobe_multi_opts))
12179 		return libbpf_err_ptr(-EINVAL);
12180 
12181 	prog_fd = bpf_program__fd(prog);
12182 	if (prog_fd < 0) {
12183 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
12184 			prog->name);
12185 		return libbpf_err_ptr(-EINVAL);
12186 	}
12187 
12188 	syms    = OPTS_GET(opts, syms, false);
12189 	addrs   = OPTS_GET(opts, addrs, false);
12190 	cnt     = OPTS_GET(opts, cnt, false);
12191 	cookies = OPTS_GET(opts, cookies, false);
12192 	unique_match = OPTS_GET(opts, unique_match, false);
12193 
12194 	if (!pattern && !addrs && !syms)
12195 		return libbpf_err_ptr(-EINVAL);
12196 	if (pattern && (addrs || syms || cookies || cnt))
12197 		return libbpf_err_ptr(-EINVAL);
12198 	if (!pattern && !cnt)
12199 		return libbpf_err_ptr(-EINVAL);
12200 	if (!pattern && unique_match)
12201 		return libbpf_err_ptr(-EINVAL);
12202 	if (addrs && syms)
12203 		return libbpf_err_ptr(-EINVAL);
12204 
12205 	/*
12206 	 * Exact function name (no wildcards) without unique_match:
12207 	 * bypass kallsyms parsing and pass the symbol directly to the
12208 	 * kernel via syms[] array.  When unique_match is set, fall
12209 	 * through to the slow path which detects duplicate symbols.
12210 	 */
12211 	if (pattern && !strpbrk(pattern, "*?") && !unique_match) {
12212 		syms = &pattern;
12213 		cnt = 1;
12214 	} else if (pattern) {
12215 		if (has_available_filter_functions_addrs())
12216 			err = libbpf_available_kprobes_parse(&res);
12217 		else
12218 			err = libbpf_available_kallsyms_parse(&res);
12219 		if (err)
12220 			goto error;
12221 
12222 		if (unique_match && res.cnt != 1) {
12223 			pr_warn("prog '%s': failed to find a unique match for '%s' (%zu matches)\n",
12224 				prog->name, pattern, res.cnt);
12225 			err = -EINVAL;
12226 			goto error;
12227 		}
12228 
12229 		addrs = res.addrs;
12230 		cnt = res.cnt;
12231 	}
12232 
12233 	retprobe = OPTS_GET(opts, retprobe, false);
12234 	session  = OPTS_GET(opts, session, false);
12235 
12236 	if (retprobe && session)
12237 		return libbpf_err_ptr(-EINVAL);
12238 
12239 	attach_type = session ? BPF_TRACE_KPROBE_SESSION : BPF_TRACE_KPROBE_MULTI;
12240 
12241 	lopts.kprobe_multi.syms = syms;
12242 	lopts.kprobe_multi.addrs = addrs;
12243 	lopts.kprobe_multi.cookies = cookies;
12244 	lopts.kprobe_multi.cnt = cnt;
12245 	lopts.kprobe_multi.flags = retprobe ? BPF_F_KPROBE_MULTI_RETURN : 0;
12246 
12247 	link = calloc(1, sizeof(*link));
12248 	if (!link) {
12249 		err = -ENOMEM;
12250 		goto error;
12251 	}
12252 	link->detach = &bpf_link__detach_fd;
12253 
12254 	link_fd = bpf_link_create(prog_fd, 0, attach_type, &lopts);
12255 	if (link_fd < 0) {
12256 		err = -errno;
12257 		/*
12258 		 * Normalize error code: when exact name bypasses kallsyms
12259 		 * parsing, kernel returns ESRCH from ftrace_lookup_symbols().
12260 		 * Convert to ENOENT for API consistency with the pattern
12261 		 * matching path which returns ENOENT from userspace.
12262 		 */
12263 		if (err == -ESRCH)
12264 			err = -ENOENT;
12265 		pr_warn("prog '%s': failed to attach: %s\n",
12266 			prog->name, errstr(err));
12267 		goto error;
12268 	}
12269 	link->fd = link_fd;
12270 	free(res.addrs);
12271 	return link;
12272 
12273 error:
12274 	free(link);
12275 	free(res.addrs);
12276 	return libbpf_err_ptr(err);
12277 }
12278 
12279 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12280 {
12281 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts);
12282 	unsigned long offset = 0;
12283 	const char *func_name;
12284 	char *func;
12285 	int n;
12286 
12287 	*link = NULL;
12288 
12289 	/* no auto-attach for SEC("kprobe") and SEC("kretprobe") */
12290 	if (strcmp(prog->sec_name, "kprobe") == 0 || strcmp(prog->sec_name, "kretprobe") == 0)
12291 		return 0;
12292 
12293 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe/");
12294 	if (opts.retprobe)
12295 		func_name = prog->sec_name + sizeof("kretprobe/") - 1;
12296 	else
12297 		func_name = prog->sec_name + sizeof("kprobe/") - 1;
12298 
12299 	n = sscanf(func_name, "%m[a-zA-Z0-9_.]+%li", &func, &offset);
12300 	if (n < 1) {
12301 		pr_warn("kprobe name is invalid: %s\n", func_name);
12302 		return -EINVAL;
12303 	}
12304 	if (opts.retprobe && offset != 0) {
12305 		free(func);
12306 		pr_warn("kretprobes do not support offset specification\n");
12307 		return -EINVAL;
12308 	}
12309 
12310 	opts.offset = offset;
12311 	*link = bpf_program__attach_kprobe_opts(prog, func, &opts);
12312 	free(func);
12313 	return libbpf_get_error(*link);
12314 }
12315 
12316 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12317 {
12318 	LIBBPF_OPTS(bpf_ksyscall_opts, opts);
12319 	const char *syscall_name;
12320 
12321 	*link = NULL;
12322 
12323 	/* no auto-attach for SEC("ksyscall") and SEC("kretsyscall") */
12324 	if (strcmp(prog->sec_name, "ksyscall") == 0 || strcmp(prog->sec_name, "kretsyscall") == 0)
12325 		return 0;
12326 
12327 	opts.retprobe = str_has_pfx(prog->sec_name, "kretsyscall/");
12328 	if (opts.retprobe)
12329 		syscall_name = prog->sec_name + sizeof("kretsyscall/") - 1;
12330 	else
12331 		syscall_name = prog->sec_name + sizeof("ksyscall/") - 1;
12332 
12333 	*link = bpf_program__attach_ksyscall(prog, syscall_name, &opts);
12334 	return *link ? 0 : -errno;
12335 }
12336 
12337 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12338 {
12339 	LIBBPF_OPTS(bpf_kprobe_multi_opts, opts);
12340 	const char *spec;
12341 	char *pattern;
12342 	int n;
12343 
12344 	*link = NULL;
12345 
12346 	/* no auto-attach for SEC("kprobe.multi") and SEC("kretprobe.multi") */
12347 	if (strcmp(prog->sec_name, "kprobe.multi") == 0 ||
12348 	    strcmp(prog->sec_name, "kretprobe.multi") == 0)
12349 		return 0;
12350 
12351 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe.multi/");
12352 	if (opts.retprobe)
12353 		spec = prog->sec_name + sizeof("kretprobe.multi/") - 1;
12354 	else
12355 		spec = prog->sec_name + sizeof("kprobe.multi/") - 1;
12356 
12357 	n = sscanf(spec, "%m[a-zA-Z0-9_.*?]", &pattern);
12358 	if (n < 1) {
12359 		pr_warn("kprobe multi pattern is invalid: %s\n", spec);
12360 		return -EINVAL;
12361 	}
12362 
12363 	*link = bpf_program__attach_kprobe_multi_opts(prog, pattern, &opts);
12364 	free(pattern);
12365 	return libbpf_get_error(*link);
12366 }
12367 
12368 static int attach_kprobe_session(const struct bpf_program *prog, long cookie,
12369 				 struct bpf_link **link)
12370 {
12371 	LIBBPF_OPTS(bpf_kprobe_multi_opts, opts, .session = true);
12372 	const char *spec;
12373 	char *pattern;
12374 	int n;
12375 
12376 	*link = NULL;
12377 
12378 	/* no auto-attach for SEC("kprobe.session") */
12379 	if (strcmp(prog->sec_name, "kprobe.session") == 0)
12380 		return 0;
12381 
12382 	spec = prog->sec_name + sizeof("kprobe.session/") - 1;
12383 	n = sscanf(spec, "%m[a-zA-Z0-9_.*?]", &pattern);
12384 	if (n < 1) {
12385 		pr_warn("kprobe session pattern is invalid: %s\n", spec);
12386 		return -EINVAL;
12387 	}
12388 
12389 	*link = bpf_program__attach_kprobe_multi_opts(prog, pattern, &opts);
12390 	free(pattern);
12391 	return *link ? 0 : -errno;
12392 }
12393 
12394 static int attach_uprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12395 {
12396 	char *probe_type = NULL, *binary_path = NULL, *func_name = NULL;
12397 	LIBBPF_OPTS(bpf_uprobe_multi_opts, opts);
12398 	int n, ret = -EINVAL;
12399 
12400 	*link = NULL;
12401 
12402 	n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[^\n]",
12403 		   &probe_type, &binary_path, &func_name);
12404 	switch (n) {
12405 	case 1:
12406 		/* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
12407 		ret = 0;
12408 		break;
12409 	case 3:
12410 		opts.session = str_has_pfx(probe_type, "uprobe.session");
12411 		opts.retprobe = str_has_pfx(probe_type, "uretprobe.multi");
12412 
12413 		*link = bpf_program__attach_uprobe_multi(prog, -1, binary_path, func_name, &opts);
12414 		ret = libbpf_get_error(*link);
12415 		break;
12416 	default:
12417 		pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
12418 			prog->sec_name);
12419 		break;
12420 	}
12421 	free(probe_type);
12422 	free(binary_path);
12423 	free(func_name);
12424 	return ret;
12425 }
12426 
12427 static inline int add_uprobe_event_legacy(const char *probe_name, bool retprobe,
12428 					  const char *binary_path, size_t offset)
12429 {
12430 	return append_to_file(tracefs_uprobe_events(), "%c:%s/%s %s:0x%zx",
12431 			      retprobe ? 'r' : 'p',
12432 			      retprobe ? "uretprobes" : "uprobes",
12433 			      probe_name, binary_path, offset);
12434 }
12435 
12436 static inline int remove_uprobe_event_legacy(const char *probe_name, bool retprobe)
12437 {
12438 	return append_to_file(tracefs_uprobe_events(), "-:%s/%s",
12439 			      retprobe ? "uretprobes" : "uprobes", probe_name);
12440 }
12441 
12442 static int determine_uprobe_perf_type_legacy(const char *probe_name, bool retprobe)
12443 {
12444 	char file[512];
12445 
12446 	snprintf(file, sizeof(file), "%s/events/%s/%s/id",
12447 		 tracefs_path(), retprobe ? "uretprobes" : "uprobes", probe_name);
12448 
12449 	return parse_uint_from_file(file, "%d\n");
12450 }
12451 
12452 static int perf_event_uprobe_open_legacy(const char *probe_name, bool retprobe,
12453 					 const char *binary_path, size_t offset, int pid)
12454 {
12455 	const size_t attr_sz = sizeof(struct perf_event_attr);
12456 	struct perf_event_attr attr;
12457 	int type, pfd, err;
12458 
12459 	err = add_uprobe_event_legacy(probe_name, retprobe, binary_path, offset);
12460 	if (err < 0) {
12461 		pr_warn("failed to add legacy uprobe event for %s:0x%zx: %s\n",
12462 			binary_path, (size_t)offset, errstr(err));
12463 		return err;
12464 	}
12465 	type = determine_uprobe_perf_type_legacy(probe_name, retprobe);
12466 	if (type < 0) {
12467 		err = type;
12468 		pr_warn("failed to determine legacy uprobe event id for %s:0x%zx: %s\n",
12469 			binary_path, offset, errstr(err));
12470 		goto err_clean_legacy;
12471 	}
12472 
12473 	memset(&attr, 0, attr_sz);
12474 	attr.size = attr_sz;
12475 	attr.config = type;
12476 	attr.type = PERF_TYPE_TRACEPOINT;
12477 
12478 	pfd = syscall(__NR_perf_event_open, &attr,
12479 		      pid < 0 ? -1 : pid, /* pid */
12480 		      pid == -1 ? 0 : -1, /* cpu */
12481 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
12482 	if (pfd < 0) {
12483 		err = -errno;
12484 		pr_warn("legacy uprobe perf_event_open() failed: %s\n", errstr(err));
12485 		goto err_clean_legacy;
12486 	}
12487 	return pfd;
12488 
12489 err_clean_legacy:
12490 	/* Clear the newly added legacy uprobe_event */
12491 	remove_uprobe_event_legacy(probe_name, retprobe);
12492 	return err;
12493 }
12494 
12495 /* Find offset of function name in archive specified by path. Currently
12496  * supported are .zip files that do not compress their contents, as used on
12497  * Android in the form of APKs, for example. "file_name" is the name of the ELF
12498  * file inside the archive. "func_name" matches symbol name or name@@LIB for
12499  * library functions.
12500  *
12501  * An overview of the APK format specifically provided here:
12502  * https://en.wikipedia.org/w/index.php?title=Apk_(file_format)&oldid=1139099120#Package_contents
12503  */
12504 static long elf_find_func_offset_from_archive(const char *archive_path, const char *file_name,
12505 					      const char *func_name)
12506 {
12507 	struct zip_archive *archive;
12508 	struct zip_entry entry;
12509 	long ret;
12510 	Elf *elf;
12511 
12512 	archive = zip_archive_open(archive_path);
12513 	if (IS_ERR(archive)) {
12514 		ret = PTR_ERR(archive);
12515 		pr_warn("zip: failed to open %s: %ld\n", archive_path, ret);
12516 		return ret;
12517 	}
12518 
12519 	ret = zip_archive_find_entry(archive, file_name, &entry);
12520 	if (ret) {
12521 		pr_warn("zip: could not find archive member %s in %s: %ld\n", file_name,
12522 			archive_path, ret);
12523 		goto out;
12524 	}
12525 	pr_debug("zip: found entry for %s in %s at 0x%lx\n", file_name, archive_path,
12526 		 (unsigned long)entry.data_offset);
12527 
12528 	if (entry.compression) {
12529 		pr_warn("zip: entry %s of %s is compressed and cannot be handled\n", file_name,
12530 			archive_path);
12531 		ret = -LIBBPF_ERRNO__FORMAT;
12532 		goto out;
12533 	}
12534 
12535 	elf = elf_memory((void *)entry.data, entry.data_length);
12536 	if (!elf) {
12537 		pr_warn("elf: could not read elf file %s from %s: %s\n", file_name, archive_path,
12538 			elf_errmsg(-1));
12539 		ret = -LIBBPF_ERRNO__LIBELF;
12540 		goto out;
12541 	}
12542 
12543 	ret = elf_find_func_offset(elf, file_name, func_name);
12544 	if (ret > 0) {
12545 		pr_debug("elf: symbol address match for %s of %s in %s: 0x%x + 0x%lx = 0x%lx\n",
12546 			 func_name, file_name, archive_path, entry.data_offset, ret,
12547 			 ret + entry.data_offset);
12548 		ret += entry.data_offset;
12549 	}
12550 	elf_end(elf);
12551 
12552 out:
12553 	zip_archive_close(archive);
12554 	return ret;
12555 }
12556 
12557 static const char *arch_specific_lib_paths(void)
12558 {
12559 	/*
12560 	 * Based on https://packages.debian.org/sid/libc6.
12561 	 *
12562 	 * Assume that the traced program is built for the same architecture
12563 	 * as libbpf, which should cover the vast majority of cases.
12564 	 */
12565 #if defined(__x86_64__)
12566 	return "/lib/x86_64-linux-gnu";
12567 #elif defined(__i386__)
12568 	return "/lib/i386-linux-gnu";
12569 #elif defined(__s390x__)
12570 	return "/lib/s390x-linux-gnu";
12571 #elif defined(__arm__) && defined(__SOFTFP__)
12572 	return "/lib/arm-linux-gnueabi";
12573 #elif defined(__arm__) && !defined(__SOFTFP__)
12574 	return "/lib/arm-linux-gnueabihf";
12575 #elif defined(__aarch64__)
12576 	return "/lib/aarch64-linux-gnu";
12577 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 64
12578 	return "/lib/mips64el-linux-gnuabi64";
12579 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 32
12580 	return "/lib/mipsel-linux-gnu";
12581 #elif defined(__powerpc64__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
12582 	return "/lib/powerpc64le-linux-gnu";
12583 #elif defined(__sparc__) && defined(__arch64__)
12584 	return "/lib/sparc64-linux-gnu";
12585 #elif defined(__riscv) && __riscv_xlen == 64
12586 	return "/lib/riscv64-linux-gnu";
12587 #else
12588 	return NULL;
12589 #endif
12590 }
12591 
12592 /* Get full path to program/shared library. */
12593 static int resolve_full_path(const char *file, char *result, size_t result_sz)
12594 {
12595 	const char *search_paths[3] = {};
12596 	int i, perm;
12597 
12598 	if (str_has_sfx(file, ".so") || strstr(file, ".so.")) {
12599 		search_paths[0] = getenv("LD_LIBRARY_PATH");
12600 		search_paths[1] = "/usr/lib64:/usr/lib";
12601 		search_paths[2] = arch_specific_lib_paths();
12602 		perm = R_OK;
12603 	} else {
12604 		search_paths[0] = getenv("PATH");
12605 		search_paths[1] = "/usr/bin:/usr/sbin";
12606 		perm = R_OK | X_OK;
12607 	}
12608 
12609 	for (i = 0; i < ARRAY_SIZE(search_paths); i++) {
12610 		const char *s;
12611 
12612 		if (!search_paths[i])
12613 			continue;
12614 		for (s = search_paths[i]; s != NULL; s = strchr(s, ':')) {
12615 			const char *next_path;
12616 			int seg_len;
12617 
12618 			if (s[0] == ':')
12619 				s++;
12620 			next_path = strchr(s, ':');
12621 			seg_len = next_path ? next_path - s : strlen(s);
12622 			if (!seg_len)
12623 				continue;
12624 			snprintf(result, result_sz, "%.*s/%s", seg_len, s, file);
12625 			/* ensure it has required permissions */
12626 			if (faccessat(AT_FDCWD, result, perm, AT_EACCESS) < 0)
12627 				continue;
12628 			pr_debug("resolved '%s' to '%s'\n", file, result);
12629 			return 0;
12630 		}
12631 	}
12632 	return -ENOENT;
12633 }
12634 
12635 struct bpf_link *
12636 bpf_program__attach_uprobe_multi(const struct bpf_program *prog,
12637 				 pid_t pid,
12638 				 const char *path,
12639 				 const char *func_pattern,
12640 				 const struct bpf_uprobe_multi_opts *opts)
12641 {
12642 	const unsigned long *ref_ctr_offsets = NULL, *offsets = NULL;
12643 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
12644 	unsigned long *resolved_offsets = NULL;
12645 	enum bpf_attach_type attach_type;
12646 	int err = 0, link_fd, prog_fd;
12647 	struct bpf_link *link = NULL;
12648 	char full_path[PATH_MAX];
12649 	bool retprobe, session;
12650 	const __u64 *cookies;
12651 	const char **syms;
12652 	size_t cnt;
12653 
12654 	if (!OPTS_VALID(opts, bpf_uprobe_multi_opts))
12655 		return libbpf_err_ptr(-EINVAL);
12656 
12657 	prog_fd = bpf_program__fd(prog);
12658 	if (prog_fd < 0) {
12659 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
12660 			prog->name);
12661 		return libbpf_err_ptr(-EINVAL);
12662 	}
12663 
12664 	syms = OPTS_GET(opts, syms, NULL);
12665 	offsets = OPTS_GET(opts, offsets, NULL);
12666 	ref_ctr_offsets = OPTS_GET(opts, ref_ctr_offsets, NULL);
12667 	cookies = OPTS_GET(opts, cookies, NULL);
12668 	cnt = OPTS_GET(opts, cnt, 0);
12669 	retprobe = OPTS_GET(opts, retprobe, false);
12670 	session  = OPTS_GET(opts, session, false);
12671 
12672 	/*
12673 	 * User can specify 2 mutually exclusive set of inputs:
12674 	 *
12675 	 * 1) use only path/func_pattern/pid arguments
12676 	 *
12677 	 * 2) use path/pid with allowed combinations of:
12678 	 *    syms/offsets/ref_ctr_offsets/cookies/cnt
12679 	 *
12680 	 *    - syms and offsets are mutually exclusive
12681 	 *    - ref_ctr_offsets and cookies are optional
12682 	 *
12683 	 * Any other usage results in error.
12684 	 */
12685 
12686 	if (!path)
12687 		return libbpf_err_ptr(-EINVAL);
12688 	if (!func_pattern && cnt == 0)
12689 		return libbpf_err_ptr(-EINVAL);
12690 
12691 	if (func_pattern) {
12692 		if (syms || offsets || ref_ctr_offsets || cookies || cnt)
12693 			return libbpf_err_ptr(-EINVAL);
12694 	} else {
12695 		if (!!syms == !!offsets)
12696 			return libbpf_err_ptr(-EINVAL);
12697 	}
12698 
12699 	if (retprobe && session)
12700 		return libbpf_err_ptr(-EINVAL);
12701 
12702 	if (func_pattern) {
12703 		if (!strchr(path, '/')) {
12704 			err = resolve_full_path(path, full_path, sizeof(full_path));
12705 			if (err) {
12706 				pr_warn("prog '%s': failed to resolve full path for '%s': %s\n",
12707 					prog->name, path, errstr(err));
12708 				return libbpf_err_ptr(err);
12709 			}
12710 			path = full_path;
12711 		}
12712 
12713 		err = elf_resolve_pattern_offsets(path, func_pattern,
12714 						  &resolved_offsets, &cnt);
12715 		if (err < 0)
12716 			return libbpf_err_ptr(err);
12717 		offsets = resolved_offsets;
12718 	} else if (syms) {
12719 		err = elf_resolve_syms_offsets(path, cnt, syms, &resolved_offsets, STT_FUNC);
12720 		if (err < 0)
12721 			return libbpf_err_ptr(err);
12722 		offsets = resolved_offsets;
12723 	}
12724 
12725 	attach_type = session ? BPF_TRACE_UPROBE_SESSION : BPF_TRACE_UPROBE_MULTI;
12726 
12727 	lopts.uprobe_multi.path = path;
12728 	lopts.uprobe_multi.offsets = offsets;
12729 	lopts.uprobe_multi.ref_ctr_offsets = ref_ctr_offsets;
12730 	lopts.uprobe_multi.cookies = cookies;
12731 	lopts.uprobe_multi.cnt = cnt;
12732 	lopts.uprobe_multi.flags = retprobe ? BPF_F_UPROBE_MULTI_RETURN : 0;
12733 
12734 	if (pid == 0)
12735 		pid = getpid();
12736 	if (pid > 0)
12737 		lopts.uprobe_multi.pid = pid;
12738 
12739 	link = calloc(1, sizeof(*link));
12740 	if (!link) {
12741 		err = -ENOMEM;
12742 		goto error;
12743 	}
12744 	link->detach = &bpf_link__detach_fd;
12745 
12746 	link_fd = bpf_link_create(prog_fd, 0, attach_type, &lopts);
12747 	if (link_fd < 0) {
12748 		err = -errno;
12749 		pr_warn("prog '%s': failed to attach multi-uprobe: %s\n",
12750 			prog->name, errstr(err));
12751 		goto error;
12752 	}
12753 	link->fd = link_fd;
12754 	free(resolved_offsets);
12755 	return link;
12756 
12757 error:
12758 	free(resolved_offsets);
12759 	free(link);
12760 	return libbpf_err_ptr(err);
12761 }
12762 
12763 LIBBPF_API struct bpf_link *
12764 bpf_program__attach_uprobe_opts(const struct bpf_program *prog, pid_t pid,
12765 				const char *binary_path, size_t func_offset,
12766 				const struct bpf_uprobe_opts *opts)
12767 {
12768 	const char *archive_path = NULL, *archive_sep = NULL;
12769 	char *legacy_probe = NULL;
12770 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
12771 	enum probe_attach_mode attach_mode;
12772 	char full_path[PATH_MAX];
12773 	struct bpf_link *link;
12774 	size_t ref_ctr_off;
12775 	int pfd, err;
12776 	bool retprobe, legacy;
12777 	const char *func_name;
12778 
12779 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
12780 		return libbpf_err_ptr(-EINVAL);
12781 
12782 	attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
12783 	retprobe = OPTS_GET(opts, retprobe, false);
12784 	ref_ctr_off = OPTS_GET(opts, ref_ctr_offset, 0);
12785 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
12786 
12787 	if (!binary_path)
12788 		return libbpf_err_ptr(-EINVAL);
12789 
12790 	/* Check if "binary_path" refers to an archive. */
12791 	archive_sep = strstr(binary_path, "!/");
12792 	if (archive_sep) {
12793 		full_path[0] = '\0';
12794 		libbpf_strlcpy(full_path, binary_path,
12795 			       min(sizeof(full_path), (size_t)(archive_sep - binary_path + 1)));
12796 		archive_path = full_path;
12797 		binary_path = archive_sep + 2;
12798 	} else if (!strchr(binary_path, '/')) {
12799 		err = resolve_full_path(binary_path, full_path, sizeof(full_path));
12800 		if (err) {
12801 			pr_warn("prog '%s': failed to resolve full path for '%s': %s\n",
12802 				prog->name, binary_path, errstr(err));
12803 			return libbpf_err_ptr(err);
12804 		}
12805 		binary_path = full_path;
12806 	}
12807 	func_name = OPTS_GET(opts, func_name, NULL);
12808 	if (func_name) {
12809 		long sym_off;
12810 
12811 		if (archive_path) {
12812 			sym_off = elf_find_func_offset_from_archive(archive_path, binary_path,
12813 								    func_name);
12814 			binary_path = archive_path;
12815 		} else {
12816 			sym_off = elf_find_func_offset_from_file(binary_path, func_name);
12817 		}
12818 		if (sym_off < 0)
12819 			return libbpf_err_ptr(sym_off);
12820 		func_offset += sym_off;
12821 	}
12822 
12823 	legacy = determine_uprobe_perf_type() < 0;
12824 	switch (attach_mode) {
12825 	case PROBE_ATTACH_MODE_LEGACY:
12826 		legacy = true;
12827 		pe_opts.force_ioctl_attach = true;
12828 		break;
12829 	case PROBE_ATTACH_MODE_PERF:
12830 		if (legacy)
12831 			return libbpf_err_ptr(-ENOTSUP);
12832 		pe_opts.force_ioctl_attach = true;
12833 		break;
12834 	case PROBE_ATTACH_MODE_LINK:
12835 		if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
12836 			return libbpf_err_ptr(-ENOTSUP);
12837 		break;
12838 	case PROBE_ATTACH_MODE_DEFAULT:
12839 		break;
12840 	default:
12841 		return libbpf_err_ptr(-EINVAL);
12842 	}
12843 
12844 	if (!legacy) {
12845 		pfd = perf_event_open_probe(true /* uprobe */, retprobe, binary_path,
12846 					    func_offset, pid, ref_ctr_off);
12847 	} else {
12848 		char probe_name[MAX_EVENT_NAME_LEN];
12849 
12850 		if (ref_ctr_off)
12851 			return libbpf_err_ptr(-EINVAL);
12852 
12853 		gen_probe_legacy_event_name(probe_name, sizeof(probe_name),
12854 					    strrchr(binary_path, '/') ? : binary_path,
12855 					    func_offset);
12856 
12857 		legacy_probe = strdup(probe_name);
12858 		if (!legacy_probe)
12859 			return libbpf_err_ptr(-ENOMEM);
12860 
12861 		pfd = perf_event_uprobe_open_legacy(legacy_probe, retprobe,
12862 						    binary_path, func_offset, pid);
12863 	}
12864 	if (pfd < 0) {
12865 		err = pfd;
12866 		pr_warn("prog '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
12867 			prog->name, retprobe ? "uretprobe" : "uprobe",
12868 			binary_path, func_offset,
12869 			errstr(err));
12870 		goto err_out;
12871 	}
12872 
12873 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
12874 	err = libbpf_get_error(link);
12875 	if (err) {
12876 		close(pfd);
12877 		pr_warn("prog '%s': failed to attach to %s '%s:0x%zx': %s\n",
12878 			prog->name, retprobe ? "uretprobe" : "uprobe",
12879 			binary_path, func_offset,
12880 			errstr(err));
12881 		goto err_clean_legacy;
12882 	}
12883 	if (legacy) {
12884 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
12885 
12886 		perf_link->legacy_probe_name = legacy_probe;
12887 		perf_link->legacy_is_kprobe = false;
12888 		perf_link->legacy_is_retprobe = retprobe;
12889 	}
12890 	return link;
12891 
12892 err_clean_legacy:
12893 	if (legacy)
12894 		remove_uprobe_event_legacy(legacy_probe, retprobe);
12895 err_out:
12896 	free(legacy_probe);
12897 	return libbpf_err_ptr(err);
12898 }
12899 
12900 /* Format of u[ret]probe section definition supporting auto-attach:
12901  * u[ret]probe/binary:function[+offset]
12902  *
12903  * binary can be an absolute/relative path or a filename; the latter is resolved to a
12904  * full binary path via bpf_program__attach_uprobe_opts.
12905  *
12906  * Specifying uprobe+ ensures we carry out strict matching; either "uprobe" must be
12907  * specified (and auto-attach is not possible) or the above format is specified for
12908  * auto-attach.
12909  */
12910 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12911 {
12912 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts);
12913 	char *probe_type = NULL, *binary_path = NULL, *func_name = NULL, *func_off;
12914 	int n, c, ret = -EINVAL;
12915 	long offset = 0;
12916 
12917 	*link = NULL;
12918 
12919 	n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[^\n]",
12920 		   &probe_type, &binary_path, &func_name);
12921 	switch (n) {
12922 	case 1:
12923 		/* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
12924 		ret = 0;
12925 		break;
12926 	case 2:
12927 		pr_warn("prog '%s': section '%s' missing ':function[+offset]' specification\n",
12928 			prog->name, prog->sec_name);
12929 		break;
12930 	case 3:
12931 		/* check if user specifies `+offset`, if yes, this should be
12932 		 * the last part of the string, make sure sscanf read to EOL
12933 		 */
12934 		func_off = strrchr(func_name, '+');
12935 		if (func_off) {
12936 			n = sscanf(func_off, "+%li%n", &offset, &c);
12937 			if (n == 1 && *(func_off + c) == '\0')
12938 				func_off[0] = '\0';
12939 			else
12940 				offset = 0;
12941 		}
12942 		opts.retprobe = strcmp(probe_type, "uretprobe") == 0 ||
12943 				strcmp(probe_type, "uretprobe.s") == 0;
12944 		if (opts.retprobe && offset != 0) {
12945 			pr_warn("prog '%s': uretprobes do not support offset specification\n",
12946 				prog->name);
12947 			break;
12948 		}
12949 		opts.func_name = func_name;
12950 		*link = bpf_program__attach_uprobe_opts(prog, -1, binary_path, offset, &opts);
12951 		ret = libbpf_get_error(*link);
12952 		break;
12953 	default:
12954 		pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
12955 			prog->sec_name);
12956 		break;
12957 	}
12958 	free(probe_type);
12959 	free(binary_path);
12960 	free(func_name);
12961 
12962 	return ret;
12963 }
12964 
12965 struct bpf_link *bpf_program__attach_uprobe(const struct bpf_program *prog,
12966 					    bool retprobe, pid_t pid,
12967 					    const char *binary_path,
12968 					    size_t func_offset)
12969 {
12970 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts, .retprobe = retprobe);
12971 
12972 	return bpf_program__attach_uprobe_opts(prog, pid, binary_path, func_offset, &opts);
12973 }
12974 
12975 struct bpf_link *bpf_program__attach_usdt(const struct bpf_program *prog,
12976 					  pid_t pid, const char *binary_path,
12977 					  const char *usdt_provider, const char *usdt_name,
12978 					  const struct bpf_usdt_opts *opts)
12979 {
12980 	char resolved_path[512];
12981 	struct bpf_object *obj = prog->obj;
12982 	struct bpf_link *link;
12983 	__u64 usdt_cookie;
12984 	int err;
12985 
12986 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
12987 		return libbpf_err_ptr(-EINVAL);
12988 
12989 	if (bpf_program__fd(prog) < 0) {
12990 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
12991 			prog->name);
12992 		return libbpf_err_ptr(-EINVAL);
12993 	}
12994 
12995 	if (!binary_path)
12996 		return libbpf_err_ptr(-EINVAL);
12997 
12998 	if (!strchr(binary_path, '/')) {
12999 		err = resolve_full_path(binary_path, resolved_path, sizeof(resolved_path));
13000 		if (err) {
13001 			pr_warn("prog '%s': failed to resolve full path for '%s': %s\n",
13002 				prog->name, binary_path, errstr(err));
13003 			return libbpf_err_ptr(err);
13004 		}
13005 		binary_path = resolved_path;
13006 	}
13007 
13008 	/* USDT manager is instantiated lazily on first USDT attach. It will
13009 	 * be destroyed together with BPF object in bpf_object__close().
13010 	 */
13011 	if (IS_ERR(obj->usdt_man))
13012 		return libbpf_ptr(obj->usdt_man);
13013 	if (!obj->usdt_man) {
13014 		obj->usdt_man = usdt_manager_new(obj);
13015 		if (IS_ERR(obj->usdt_man))
13016 			return libbpf_ptr(obj->usdt_man);
13017 	}
13018 
13019 	usdt_cookie = OPTS_GET(opts, usdt_cookie, 0);
13020 	link = usdt_manager_attach_usdt(obj->usdt_man, prog, pid, binary_path,
13021 					usdt_provider, usdt_name, usdt_cookie);
13022 	err = libbpf_get_error(link);
13023 	if (err)
13024 		return libbpf_err_ptr(err);
13025 	return link;
13026 }
13027 
13028 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link)
13029 {
13030 	char *path = NULL, *provider = NULL, *name = NULL;
13031 	const char *sec_name;
13032 	int n, err;
13033 
13034 	sec_name = bpf_program__section_name(prog);
13035 	if (strcmp(sec_name, "usdt") == 0) {
13036 		/* no auto-attach for just SEC("usdt") */
13037 		*link = NULL;
13038 		return 0;
13039 	}
13040 
13041 	n = sscanf(sec_name, "usdt/%m[^:]:%m[^:]:%m[^:]", &path, &provider, &name);
13042 	if (n != 3) {
13043 		pr_warn("invalid section '%s', expected SEC(\"usdt/<path>:<provider>:<name>\")\n",
13044 			sec_name);
13045 		err = -EINVAL;
13046 	} else {
13047 		*link = bpf_program__attach_usdt(prog, -1 /* any process */, path,
13048 						 provider, name, NULL);
13049 		err = libbpf_get_error(*link);
13050 	}
13051 	free(path);
13052 	free(provider);
13053 	free(name);
13054 	return err;
13055 }
13056 
13057 static int determine_tracepoint_id(const char *tp_category,
13058 				   const char *tp_name)
13059 {
13060 	char file[PATH_MAX];
13061 	int ret;
13062 
13063 	ret = snprintf(file, sizeof(file), "%s/events/%s/%s/id",
13064 		       tracefs_path(), tp_category, tp_name);
13065 	if (ret < 0)
13066 		return -errno;
13067 	if (ret >= sizeof(file)) {
13068 		pr_debug("tracepoint %s/%s path is too long\n",
13069 			 tp_category, tp_name);
13070 		return -E2BIG;
13071 	}
13072 	return parse_uint_from_file(file, "%d\n");
13073 }
13074 
13075 static int perf_event_open_tracepoint(const char *tp_category,
13076 				      const char *tp_name)
13077 {
13078 	const size_t attr_sz = sizeof(struct perf_event_attr);
13079 	struct perf_event_attr attr;
13080 	int tp_id, pfd, err;
13081 
13082 	tp_id = determine_tracepoint_id(tp_category, tp_name);
13083 	if (tp_id < 0) {
13084 		pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
13085 			tp_category, tp_name,
13086 			errstr(tp_id));
13087 		return tp_id;
13088 	}
13089 
13090 	memset(&attr, 0, attr_sz);
13091 	attr.type = PERF_TYPE_TRACEPOINT;
13092 	attr.size = attr_sz;
13093 	attr.config = tp_id;
13094 
13095 	pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
13096 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
13097 	if (pfd < 0) {
13098 		err = -errno;
13099 		pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
13100 			tp_category, tp_name,
13101 			errstr(err));
13102 		return err;
13103 	}
13104 	return pfd;
13105 }
13106 
13107 struct bpf_link *bpf_program__attach_tracepoint_opts(const struct bpf_program *prog,
13108 						     const char *tp_category,
13109 						     const char *tp_name,
13110 						     const struct bpf_tracepoint_opts *opts)
13111 {
13112 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
13113 	struct bpf_link *link;
13114 	int pfd, err;
13115 
13116 	if (!OPTS_VALID(opts, bpf_tracepoint_opts))
13117 		return libbpf_err_ptr(-EINVAL);
13118 
13119 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
13120 
13121 	pfd = perf_event_open_tracepoint(tp_category, tp_name);
13122 	if (pfd < 0) {
13123 		pr_warn("prog '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
13124 			prog->name, tp_category, tp_name,
13125 			errstr(pfd));
13126 		return libbpf_err_ptr(pfd);
13127 	}
13128 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
13129 	err = libbpf_get_error(link);
13130 	if (err) {
13131 		close(pfd);
13132 		pr_warn("prog '%s': failed to attach to tracepoint '%s/%s': %s\n",
13133 			prog->name, tp_category, tp_name,
13134 			errstr(err));
13135 		return libbpf_err_ptr(err);
13136 	}
13137 	return link;
13138 }
13139 
13140 struct bpf_link *bpf_program__attach_tracepoint(const struct bpf_program *prog,
13141 						const char *tp_category,
13142 						const char *tp_name)
13143 {
13144 	return bpf_program__attach_tracepoint_opts(prog, tp_category, tp_name, NULL);
13145 }
13146 
13147 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
13148 {
13149 	char *sec_name, *tp_cat, *tp_name;
13150 
13151 	*link = NULL;
13152 
13153 	/* no auto-attach for SEC("tp") or SEC("tracepoint") */
13154 	if (strcmp(prog->sec_name, "tp") == 0 || strcmp(prog->sec_name, "tracepoint") == 0)
13155 		return 0;
13156 
13157 	sec_name = strdup(prog->sec_name);
13158 	if (!sec_name)
13159 		return -ENOMEM;
13160 
13161 	/* extract "tp/<category>/<name>" or "tracepoint/<category>/<name>" */
13162 	if (str_has_pfx(prog->sec_name, "tp/"))
13163 		tp_cat = sec_name + sizeof("tp/") - 1;
13164 	else
13165 		tp_cat = sec_name + sizeof("tracepoint/") - 1;
13166 	tp_name = strchr(tp_cat, '/');
13167 	if (!tp_name) {
13168 		free(sec_name);
13169 		return -EINVAL;
13170 	}
13171 	*tp_name = '\0';
13172 	tp_name++;
13173 
13174 	*link = bpf_program__attach_tracepoint(prog, tp_cat, tp_name);
13175 	free(sec_name);
13176 	return libbpf_get_error(*link);
13177 }
13178 
13179 struct bpf_link *
13180 bpf_program__attach_raw_tracepoint_opts(const struct bpf_program *prog,
13181 					const char *tp_name,
13182 					struct bpf_raw_tracepoint_opts *opts)
13183 {
13184 	LIBBPF_OPTS(bpf_raw_tp_opts, raw_opts);
13185 	struct bpf_link *link;
13186 	int prog_fd, pfd;
13187 
13188 	if (!OPTS_VALID(opts, bpf_raw_tracepoint_opts))
13189 		return libbpf_err_ptr(-EINVAL);
13190 
13191 	prog_fd = bpf_program__fd(prog);
13192 	if (prog_fd < 0) {
13193 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
13194 		return libbpf_err_ptr(-EINVAL);
13195 	}
13196 
13197 	link = calloc(1, sizeof(*link));
13198 	if (!link)
13199 		return libbpf_err_ptr(-ENOMEM);
13200 	link->detach = &bpf_link__detach_fd;
13201 
13202 	raw_opts.tp_name = tp_name;
13203 	raw_opts.cookie = OPTS_GET(opts, cookie, 0);
13204 	pfd = bpf_raw_tracepoint_open_opts(prog_fd, &raw_opts);
13205 	if (pfd < 0) {
13206 		pfd = -errno;
13207 		free(link);
13208 		pr_warn("prog '%s': failed to attach to raw tracepoint '%s': %s\n",
13209 			prog->name, tp_name, errstr(pfd));
13210 		return libbpf_err_ptr(pfd);
13211 	}
13212 	link->fd = pfd;
13213 	return link;
13214 }
13215 
13216 struct bpf_link *bpf_program__attach_raw_tracepoint(const struct bpf_program *prog,
13217 						    const char *tp_name)
13218 {
13219 	return bpf_program__attach_raw_tracepoint_opts(prog, tp_name, NULL);
13220 }
13221 
13222 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
13223 {
13224 	static const char *const prefixes[] = {
13225 		"raw_tp",
13226 		"raw_tracepoint",
13227 		"raw_tp.w",
13228 		"raw_tracepoint.w",
13229 	};
13230 	size_t i;
13231 	const char *tp_name = NULL;
13232 
13233 	*link = NULL;
13234 
13235 	for (i = 0; i < ARRAY_SIZE(prefixes); i++) {
13236 		size_t pfx_len;
13237 
13238 		if (!str_has_pfx(prog->sec_name, prefixes[i]))
13239 			continue;
13240 
13241 		pfx_len = strlen(prefixes[i]);
13242 		/* no auto-attach case of, e.g., SEC("raw_tp") */
13243 		if (prog->sec_name[pfx_len] == '\0')
13244 			return 0;
13245 
13246 		if (prog->sec_name[pfx_len] != '/')
13247 			continue;
13248 
13249 		tp_name = prog->sec_name + pfx_len + 1;
13250 		break;
13251 	}
13252 
13253 	if (!tp_name) {
13254 		pr_warn("prog '%s': invalid section name '%s'\n",
13255 			prog->name, prog->sec_name);
13256 		return -EINVAL;
13257 	}
13258 
13259 	*link = bpf_program__attach_raw_tracepoint(prog, tp_name);
13260 	return libbpf_get_error(*link);
13261 }
13262 
13263 /* Common logic for all BPF program types that attach to a btf_id */
13264 static struct bpf_link *bpf_program__attach_btf_id(const struct bpf_program *prog,
13265 						   const struct bpf_trace_opts *opts)
13266 {
13267 	LIBBPF_OPTS(bpf_link_create_opts, link_opts);
13268 	struct bpf_link *link;
13269 	int prog_fd, pfd;
13270 
13271 	if (!OPTS_VALID(opts, bpf_trace_opts))
13272 		return libbpf_err_ptr(-EINVAL);
13273 
13274 	prog_fd = bpf_program__fd(prog);
13275 	if (prog_fd < 0) {
13276 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
13277 		return libbpf_err_ptr(-EINVAL);
13278 	}
13279 
13280 	link = calloc(1, sizeof(*link));
13281 	if (!link)
13282 		return libbpf_err_ptr(-ENOMEM);
13283 	link->detach = &bpf_link__detach_fd;
13284 
13285 	/* libbpf is smart enough to redirect to BPF_RAW_TRACEPOINT_OPEN on old kernels */
13286 	link_opts.tracing.cookie = OPTS_GET(opts, cookie, 0);
13287 	pfd = bpf_link_create(prog_fd, 0, bpf_program__expected_attach_type(prog), &link_opts);
13288 	if (pfd < 0) {
13289 		pfd = -errno;
13290 		free(link);
13291 		pr_warn("prog '%s': failed to attach: %s\n",
13292 			prog->name, errstr(pfd));
13293 		return libbpf_err_ptr(pfd);
13294 	}
13295 	link->fd = pfd;
13296 	return link;
13297 }
13298 
13299 struct bpf_link *bpf_program__attach_trace(const struct bpf_program *prog)
13300 {
13301 	return bpf_program__attach_btf_id(prog, NULL);
13302 }
13303 
13304 struct bpf_link *bpf_program__attach_trace_opts(const struct bpf_program *prog,
13305 						const struct bpf_trace_opts *opts)
13306 {
13307 	return bpf_program__attach_btf_id(prog, opts);
13308 }
13309 
13310 struct bpf_link *bpf_program__attach_lsm(const struct bpf_program *prog)
13311 {
13312 	return bpf_program__attach_btf_id(prog, NULL);
13313 }
13314 
13315 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link)
13316 {
13317 	*link = bpf_program__attach_trace(prog);
13318 	return libbpf_get_error(*link);
13319 }
13320 
13321 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link)
13322 {
13323 	*link = bpf_program__attach_lsm(prog);
13324 	return libbpf_get_error(*link);
13325 }
13326 
13327 static struct bpf_link *
13328 bpf_program_attach_fd(const struct bpf_program *prog,
13329 		      int target_fd, const char *target_name,
13330 		      const struct bpf_link_create_opts *opts)
13331 {
13332 	enum bpf_attach_type attach_type;
13333 	struct bpf_link *link;
13334 	int prog_fd, link_fd;
13335 
13336 	prog_fd = bpf_program__fd(prog);
13337 	if (prog_fd < 0) {
13338 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
13339 		return libbpf_err_ptr(-EINVAL);
13340 	}
13341 
13342 	link = calloc(1, sizeof(*link));
13343 	if (!link)
13344 		return libbpf_err_ptr(-ENOMEM);
13345 	link->detach = &bpf_link__detach_fd;
13346 
13347 	attach_type = bpf_program__expected_attach_type(prog);
13348 	link_fd = bpf_link_create(prog_fd, target_fd, attach_type, opts);
13349 	if (link_fd < 0) {
13350 		link_fd = -errno;
13351 		free(link);
13352 		pr_warn("prog '%s': failed to attach to %s: %s\n",
13353 			prog->name, target_name,
13354 			errstr(link_fd));
13355 		return libbpf_err_ptr(link_fd);
13356 	}
13357 	link->fd = link_fd;
13358 	return link;
13359 }
13360 
13361 struct bpf_link *
13362 bpf_program__attach_cgroup(const struct bpf_program *prog, int cgroup_fd)
13363 {
13364 	return bpf_program_attach_fd(prog, cgroup_fd, "cgroup", NULL);
13365 }
13366 
13367 struct bpf_link *
13368 bpf_program__attach_netns(const struct bpf_program *prog, int netns_fd)
13369 {
13370 	return bpf_program_attach_fd(prog, netns_fd, "netns", NULL);
13371 }
13372 
13373 struct bpf_link *
13374 bpf_program__attach_sockmap(const struct bpf_program *prog, int map_fd)
13375 {
13376 	return bpf_program_attach_fd(prog, map_fd, "sockmap", NULL);
13377 }
13378 
13379 struct bpf_link *bpf_program__attach_xdp(const struct bpf_program *prog, int ifindex)
13380 {
13381 	/* target_fd/target_ifindex use the same field in LINK_CREATE */
13382 	return bpf_program_attach_fd(prog, ifindex, "xdp", NULL);
13383 }
13384 
13385 struct bpf_link *
13386 bpf_program__attach_cgroup_opts(const struct bpf_program *prog, int cgroup_fd,
13387 				const struct bpf_cgroup_opts *opts)
13388 {
13389 	LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
13390 	__u32 relative_id;
13391 	int relative_fd;
13392 
13393 	if (!OPTS_VALID(opts, bpf_cgroup_opts))
13394 		return libbpf_err_ptr(-EINVAL);
13395 
13396 	relative_id = OPTS_GET(opts, relative_id, 0);
13397 	relative_fd = OPTS_GET(opts, relative_fd, 0);
13398 
13399 	if (relative_fd && relative_id) {
13400 		pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
13401 			prog->name);
13402 		return libbpf_err_ptr(-EINVAL);
13403 	}
13404 
13405 	link_create_opts.cgroup.expected_revision = OPTS_GET(opts, expected_revision, 0);
13406 	link_create_opts.cgroup.relative_fd = relative_fd;
13407 	link_create_opts.cgroup.relative_id = relative_id;
13408 	link_create_opts.flags = OPTS_GET(opts, flags, 0);
13409 
13410 	return bpf_program_attach_fd(prog, cgroup_fd, "cgroup", &link_create_opts);
13411 }
13412 
13413 struct bpf_link *
13414 bpf_program__attach_tcx(const struct bpf_program *prog, int ifindex,
13415 			const struct bpf_tcx_opts *opts)
13416 {
13417 	LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
13418 	__u32 relative_id;
13419 	int relative_fd;
13420 
13421 	if (!OPTS_VALID(opts, bpf_tcx_opts))
13422 		return libbpf_err_ptr(-EINVAL);
13423 
13424 	relative_id = OPTS_GET(opts, relative_id, 0);
13425 	relative_fd = OPTS_GET(opts, relative_fd, 0);
13426 
13427 	/* validate we don't have unexpected combinations of non-zero fields */
13428 	if (!ifindex) {
13429 		pr_warn("prog '%s': target netdevice ifindex cannot be zero\n",
13430 			prog->name);
13431 		return libbpf_err_ptr(-EINVAL);
13432 	}
13433 	if (relative_fd && relative_id) {
13434 		pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
13435 			prog->name);
13436 		return libbpf_err_ptr(-EINVAL);
13437 	}
13438 
13439 	link_create_opts.tcx.expected_revision = OPTS_GET(opts, expected_revision, 0);
13440 	link_create_opts.tcx.relative_fd = relative_fd;
13441 	link_create_opts.tcx.relative_id = relative_id;
13442 	link_create_opts.flags = OPTS_GET(opts, flags, 0);
13443 
13444 	/* target_fd/target_ifindex use the same field in LINK_CREATE */
13445 	return bpf_program_attach_fd(prog, ifindex, "tcx", &link_create_opts);
13446 }
13447 
13448 struct bpf_link *
13449 bpf_program__attach_netkit(const struct bpf_program *prog, int ifindex,
13450 			   const struct bpf_netkit_opts *opts)
13451 {
13452 	LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
13453 	__u32 relative_id;
13454 	int relative_fd;
13455 
13456 	if (!OPTS_VALID(opts, bpf_netkit_opts))
13457 		return libbpf_err_ptr(-EINVAL);
13458 
13459 	relative_id = OPTS_GET(opts, relative_id, 0);
13460 	relative_fd = OPTS_GET(opts, relative_fd, 0);
13461 
13462 	/* validate we don't have unexpected combinations of non-zero fields */
13463 	if (!ifindex) {
13464 		pr_warn("prog '%s': target netdevice ifindex cannot be zero\n",
13465 			prog->name);
13466 		return libbpf_err_ptr(-EINVAL);
13467 	}
13468 	if (relative_fd && relative_id) {
13469 		pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
13470 			prog->name);
13471 		return libbpf_err_ptr(-EINVAL);
13472 	}
13473 
13474 	link_create_opts.netkit.expected_revision = OPTS_GET(opts, expected_revision, 0);
13475 	link_create_opts.netkit.relative_fd = relative_fd;
13476 	link_create_opts.netkit.relative_id = relative_id;
13477 	link_create_opts.flags = OPTS_GET(opts, flags, 0);
13478 
13479 	return bpf_program_attach_fd(prog, ifindex, "netkit", &link_create_opts);
13480 }
13481 
13482 struct bpf_link *bpf_program__attach_freplace(const struct bpf_program *prog,
13483 					      int target_fd,
13484 					      const char *attach_func_name)
13485 {
13486 	int btf_id;
13487 
13488 	if (!!target_fd != !!attach_func_name) {
13489 		pr_warn("prog '%s': supply none or both of target_fd and attach_func_name\n",
13490 			prog->name);
13491 		return libbpf_err_ptr(-EINVAL);
13492 	}
13493 
13494 	if (prog->type != BPF_PROG_TYPE_EXT) {
13495 		pr_warn("prog '%s': only BPF_PROG_TYPE_EXT can attach as freplace\n",
13496 			prog->name);
13497 		return libbpf_err_ptr(-EINVAL);
13498 	}
13499 
13500 	if (target_fd) {
13501 		LIBBPF_OPTS(bpf_link_create_opts, target_opts);
13502 
13503 		btf_id = libbpf_find_prog_btf_id(attach_func_name, target_fd, prog->obj->token_fd);
13504 		if (btf_id < 0)
13505 			return libbpf_err_ptr(btf_id);
13506 
13507 		target_opts.target_btf_id = btf_id;
13508 
13509 		return bpf_program_attach_fd(prog, target_fd, "freplace",
13510 					     &target_opts);
13511 	} else {
13512 		/* no target, so use raw_tracepoint_open for compatibility
13513 		 * with old kernels
13514 		 */
13515 		return bpf_program__attach_trace(prog);
13516 	}
13517 }
13518 
13519 struct bpf_link *
13520 bpf_program__attach_iter(const struct bpf_program *prog,
13521 			 const struct bpf_iter_attach_opts *opts)
13522 {
13523 	DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
13524 	struct bpf_link *link;
13525 	int prog_fd, link_fd;
13526 	__u32 target_fd = 0;
13527 
13528 	if (!OPTS_VALID(opts, bpf_iter_attach_opts))
13529 		return libbpf_err_ptr(-EINVAL);
13530 
13531 	link_create_opts.iter_info = OPTS_GET(opts, link_info, (void *)0);
13532 	link_create_opts.iter_info_len = OPTS_GET(opts, link_info_len, 0);
13533 
13534 	prog_fd = bpf_program__fd(prog);
13535 	if (prog_fd < 0) {
13536 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
13537 		return libbpf_err_ptr(-EINVAL);
13538 	}
13539 
13540 	link = calloc(1, sizeof(*link));
13541 	if (!link)
13542 		return libbpf_err_ptr(-ENOMEM);
13543 	link->detach = &bpf_link__detach_fd;
13544 
13545 	link_fd = bpf_link_create(prog_fd, target_fd, BPF_TRACE_ITER,
13546 				  &link_create_opts);
13547 	if (link_fd < 0) {
13548 		link_fd = -errno;
13549 		free(link);
13550 		pr_warn("prog '%s': failed to attach to iterator: %s\n",
13551 			prog->name, errstr(link_fd));
13552 		return libbpf_err_ptr(link_fd);
13553 	}
13554 	link->fd = link_fd;
13555 	return link;
13556 }
13557 
13558 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link)
13559 {
13560 	*link = bpf_program__attach_iter(prog, NULL);
13561 	return libbpf_get_error(*link);
13562 }
13563 
13564 struct bpf_link *bpf_program__attach_netfilter(const struct bpf_program *prog,
13565 					       const struct bpf_netfilter_opts *opts)
13566 {
13567 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
13568 	struct bpf_link *link;
13569 	int prog_fd, link_fd;
13570 
13571 	if (!OPTS_VALID(opts, bpf_netfilter_opts))
13572 		return libbpf_err_ptr(-EINVAL);
13573 
13574 	prog_fd = bpf_program__fd(prog);
13575 	if (prog_fd < 0) {
13576 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
13577 		return libbpf_err_ptr(-EINVAL);
13578 	}
13579 
13580 	link = calloc(1, sizeof(*link));
13581 	if (!link)
13582 		return libbpf_err_ptr(-ENOMEM);
13583 
13584 	link->detach = &bpf_link__detach_fd;
13585 
13586 	lopts.netfilter.pf = OPTS_GET(opts, pf, 0);
13587 	lopts.netfilter.hooknum = OPTS_GET(opts, hooknum, 0);
13588 	lopts.netfilter.priority = OPTS_GET(opts, priority, 0);
13589 	lopts.netfilter.flags = OPTS_GET(opts, flags, 0);
13590 
13591 	link_fd = bpf_link_create(prog_fd, 0, BPF_NETFILTER, &lopts);
13592 	if (link_fd < 0) {
13593 		link_fd = -errno;
13594 		free(link);
13595 		pr_warn("prog '%s': failed to attach to netfilter: %s\n",
13596 			prog->name, errstr(link_fd));
13597 		return libbpf_err_ptr(link_fd);
13598 	}
13599 	link->fd = link_fd;
13600 
13601 	return link;
13602 }
13603 
13604 struct bpf_link *bpf_program__attach(const struct bpf_program *prog)
13605 {
13606 	struct bpf_link *link = NULL;
13607 	int err;
13608 
13609 	if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
13610 		return libbpf_err_ptr(-EOPNOTSUPP);
13611 
13612 	if (bpf_program__fd(prog) < 0) {
13613 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
13614 			prog->name);
13615 		return libbpf_err_ptr(-EINVAL);
13616 	}
13617 
13618 	err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, &link);
13619 	if (err)
13620 		return libbpf_err_ptr(err);
13621 
13622 	/* When calling bpf_program__attach() explicitly, auto-attach support
13623 	 * is expected to work, so NULL returned link is considered an error.
13624 	 * This is different for skeleton's attach, see comment in
13625 	 * bpf_object__attach_skeleton().
13626 	 */
13627 	if (!link)
13628 		return libbpf_err_ptr(-EOPNOTSUPP);
13629 
13630 	return link;
13631 }
13632 
13633 struct bpf_link_struct_ops {
13634 	struct bpf_link link;
13635 	int map_fd;
13636 };
13637 
13638 static int bpf_link__detach_struct_ops(struct bpf_link *link)
13639 {
13640 	struct bpf_link_struct_ops *st_link;
13641 	__u32 zero = 0;
13642 
13643 	st_link = container_of(link, struct bpf_link_struct_ops, link);
13644 
13645 	if (st_link->map_fd < 0)
13646 		/* w/o a real link */
13647 		return bpf_map_delete_elem(link->fd, &zero);
13648 
13649 	return close(link->fd);
13650 }
13651 
13652 struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map)
13653 {
13654 	struct bpf_link_struct_ops *link;
13655 	__u32 zero = 0;
13656 	int err, fd;
13657 
13658 	if (!bpf_map__is_struct_ops(map)) {
13659 		pr_warn("map '%s': can't attach non-struct_ops map\n", map->name);
13660 		return libbpf_err_ptr(-EINVAL);
13661 	}
13662 
13663 	if (map->fd < 0) {
13664 		pr_warn("map '%s': can't attach BPF map without FD (was it created?)\n", map->name);
13665 		return libbpf_err_ptr(-EINVAL);
13666 	}
13667 
13668 	link = calloc(1, sizeof(*link));
13669 	if (!link)
13670 		return libbpf_err_ptr(-EINVAL);
13671 
13672 	/* kern_vdata should be prepared during the loading phase. */
13673 	err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
13674 	/* It can be EBUSY if the map has been used to create or
13675 	 * update a link before.  We don't allow updating the value of
13676 	 * a struct_ops once it is set.  That ensures that the value
13677 	 * never changed.  So, it is safe to skip EBUSY.
13678 	 */
13679 	if (err && (!(map->def.map_flags & BPF_F_LINK) || err != -EBUSY)) {
13680 		free(link);
13681 		return libbpf_err_ptr(err);
13682 	}
13683 
13684 	link->link.detach = bpf_link__detach_struct_ops;
13685 
13686 	if (!(map->def.map_flags & BPF_F_LINK)) {
13687 		/* w/o a real link */
13688 		link->link.fd = map->fd;
13689 		link->map_fd = -1;
13690 		return &link->link;
13691 	}
13692 
13693 	fd = bpf_link_create(map->fd, 0, BPF_STRUCT_OPS, NULL);
13694 	if (fd < 0) {
13695 		free(link);
13696 		return libbpf_err_ptr(fd);
13697 	}
13698 
13699 	link->link.fd = fd;
13700 	link->map_fd = map->fd;
13701 
13702 	return &link->link;
13703 }
13704 
13705 /*
13706  * Swap the back struct_ops of a link with a new struct_ops map.
13707  */
13708 int bpf_link__update_map(struct bpf_link *link, const struct bpf_map *map)
13709 {
13710 	struct bpf_link_struct_ops *st_ops_link;
13711 	__u32 zero = 0;
13712 	int err;
13713 
13714 	if (!bpf_map__is_struct_ops(map))
13715 		return libbpf_err(-EINVAL);
13716 
13717 	if (map->fd < 0) {
13718 		pr_warn("map '%s': can't use BPF map without FD (was it created?)\n", map->name);
13719 		return libbpf_err(-EINVAL);
13720 	}
13721 
13722 	st_ops_link = container_of(link, struct bpf_link_struct_ops, link);
13723 	/* Ensure the type of a link is correct */
13724 	if (st_ops_link->map_fd < 0)
13725 		return libbpf_err(-EINVAL);
13726 
13727 	err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
13728 	/* It can be EBUSY if the map has been used to create or
13729 	 * update a link before.  We don't allow updating the value of
13730 	 * a struct_ops once it is set.  That ensures that the value
13731 	 * never changed.  So, it is safe to skip EBUSY.
13732 	 */
13733 	if (err && err != -EBUSY)
13734 		return err;
13735 
13736 	err = bpf_link_update(link->fd, map->fd, NULL);
13737 	if (err < 0)
13738 		return err;
13739 
13740 	st_ops_link->map_fd = map->fd;
13741 
13742 	return 0;
13743 }
13744 
13745 typedef enum bpf_perf_event_ret (*bpf_perf_event_print_t)(struct perf_event_header *hdr,
13746 							  void *private_data);
13747 
13748 static enum bpf_perf_event_ret
13749 perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
13750 		       void **copy_mem, size_t *copy_size,
13751 		       bpf_perf_event_print_t fn, void *private_data)
13752 {
13753 	struct perf_event_mmap_page *header = mmap_mem;
13754 	__u64 data_head = ring_buffer_read_head(header);
13755 	__u64 data_tail = header->data_tail;
13756 	void *base = ((__u8 *)header) + page_size;
13757 	int ret = LIBBPF_PERF_EVENT_CONT;
13758 	struct perf_event_header *ehdr;
13759 	size_t ehdr_size;
13760 
13761 	while (data_head != data_tail) {
13762 		ehdr = base + (data_tail & (mmap_size - 1));
13763 		ehdr_size = ehdr->size;
13764 
13765 		if (((void *)ehdr) + ehdr_size > base + mmap_size) {
13766 			void *copy_start = ehdr;
13767 			size_t len_first = base + mmap_size - copy_start;
13768 			size_t len_secnd = ehdr_size - len_first;
13769 
13770 			if (*copy_size < ehdr_size) {
13771 				free(*copy_mem);
13772 				*copy_mem = malloc(ehdr_size);
13773 				if (!*copy_mem) {
13774 					*copy_size = 0;
13775 					ret = LIBBPF_PERF_EVENT_ERROR;
13776 					break;
13777 				}
13778 				*copy_size = ehdr_size;
13779 			}
13780 
13781 			memcpy(*copy_mem, copy_start, len_first);
13782 			memcpy(*copy_mem + len_first, base, len_secnd);
13783 			ehdr = *copy_mem;
13784 		}
13785 
13786 		ret = fn(ehdr, private_data);
13787 		data_tail += ehdr_size;
13788 		if (ret != LIBBPF_PERF_EVENT_CONT)
13789 			break;
13790 	}
13791 
13792 	ring_buffer_write_tail(header, data_tail);
13793 	return libbpf_err(ret);
13794 }
13795 
13796 struct perf_buffer;
13797 
13798 struct perf_buffer_params {
13799 	struct perf_event_attr *attr;
13800 	/* if event_cb is specified, it takes precendence */
13801 	perf_buffer_event_fn event_cb;
13802 	/* sample_cb and lost_cb are higher-level common-case callbacks */
13803 	perf_buffer_sample_fn sample_cb;
13804 	perf_buffer_lost_fn lost_cb;
13805 	void *ctx;
13806 	int cpu_cnt;
13807 	int *cpus;
13808 	int *map_keys;
13809 };
13810 
13811 struct perf_cpu_buf {
13812 	struct perf_buffer *pb;
13813 	void *base; /* mmap()'ed memory */
13814 	void *buf; /* for reconstructing segmented data */
13815 	size_t buf_size;
13816 	int fd;
13817 	int cpu;
13818 	int map_key;
13819 };
13820 
13821 struct perf_buffer {
13822 	perf_buffer_event_fn event_cb;
13823 	perf_buffer_sample_fn sample_cb;
13824 	perf_buffer_lost_fn lost_cb;
13825 	void *ctx; /* passed into callbacks */
13826 
13827 	size_t page_size;
13828 	size_t mmap_size;
13829 	struct perf_cpu_buf **cpu_bufs;
13830 	struct epoll_event *events;
13831 	int cpu_cnt; /* number of allocated CPU buffers */
13832 	int epoll_fd; /* perf event FD */
13833 	int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
13834 };
13835 
13836 static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
13837 				      struct perf_cpu_buf *cpu_buf)
13838 {
13839 	if (!cpu_buf)
13840 		return;
13841 	if (cpu_buf->base &&
13842 	    munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
13843 		pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
13844 	if (cpu_buf->fd >= 0) {
13845 		ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
13846 		close(cpu_buf->fd);
13847 	}
13848 	free(cpu_buf->buf);
13849 	free(cpu_buf);
13850 }
13851 
13852 void perf_buffer__free(struct perf_buffer *pb)
13853 {
13854 	int i;
13855 
13856 	if (IS_ERR_OR_NULL(pb))
13857 		return;
13858 	if (pb->cpu_bufs) {
13859 		for (i = 0; i < pb->cpu_cnt; i++) {
13860 			struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
13861 
13862 			if (!cpu_buf)
13863 				continue;
13864 
13865 			bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
13866 			perf_buffer__free_cpu_buf(pb, cpu_buf);
13867 		}
13868 		free(pb->cpu_bufs);
13869 	}
13870 	if (pb->epoll_fd >= 0)
13871 		close(pb->epoll_fd);
13872 	free(pb->events);
13873 	free(pb);
13874 }
13875 
13876 static struct perf_cpu_buf *
13877 perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
13878 			  int cpu, int map_key)
13879 {
13880 	struct perf_cpu_buf *cpu_buf;
13881 	int err;
13882 
13883 	cpu_buf = calloc(1, sizeof(*cpu_buf));
13884 	if (!cpu_buf)
13885 		return ERR_PTR(-ENOMEM);
13886 
13887 	cpu_buf->pb = pb;
13888 	cpu_buf->cpu = cpu;
13889 	cpu_buf->map_key = map_key;
13890 
13891 	cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
13892 			      -1, PERF_FLAG_FD_CLOEXEC);
13893 	if (cpu_buf->fd < 0) {
13894 		err = -errno;
13895 		pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
13896 			cpu, errstr(err));
13897 		goto error;
13898 	}
13899 
13900 	cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
13901 			     PROT_READ | PROT_WRITE, MAP_SHARED,
13902 			     cpu_buf->fd, 0);
13903 	if (cpu_buf->base == MAP_FAILED) {
13904 		cpu_buf->base = NULL;
13905 		err = -errno;
13906 		pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
13907 			cpu, errstr(err));
13908 		goto error;
13909 	}
13910 
13911 	if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
13912 		err = -errno;
13913 		pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
13914 			cpu, errstr(err));
13915 		goto error;
13916 	}
13917 
13918 	return cpu_buf;
13919 
13920 error:
13921 	perf_buffer__free_cpu_buf(pb, cpu_buf);
13922 	return (struct perf_cpu_buf *)ERR_PTR(err);
13923 }
13924 
13925 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
13926 					      struct perf_buffer_params *p);
13927 
13928 struct perf_buffer *perf_buffer__new(int map_fd, size_t page_cnt,
13929 				     perf_buffer_sample_fn sample_cb,
13930 				     perf_buffer_lost_fn lost_cb,
13931 				     void *ctx,
13932 				     const struct perf_buffer_opts *opts)
13933 {
13934 	const size_t attr_sz = sizeof(struct perf_event_attr);
13935 	struct perf_buffer_params p = {};
13936 	struct perf_event_attr attr;
13937 	__u32 sample_period;
13938 
13939 	if (!OPTS_VALID(opts, perf_buffer_opts))
13940 		return libbpf_err_ptr(-EINVAL);
13941 
13942 	sample_period = OPTS_GET(opts, sample_period, 1);
13943 	if (!sample_period)
13944 		sample_period = 1;
13945 
13946 	memset(&attr, 0, attr_sz);
13947 	attr.size = attr_sz;
13948 	attr.config = PERF_COUNT_SW_BPF_OUTPUT;
13949 	attr.type = PERF_TYPE_SOFTWARE;
13950 	attr.sample_type = PERF_SAMPLE_RAW;
13951 	attr.wakeup_events = sample_period;
13952 
13953 	p.attr = &attr;
13954 	p.sample_cb = sample_cb;
13955 	p.lost_cb = lost_cb;
13956 	p.ctx = ctx;
13957 
13958 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
13959 }
13960 
13961 struct perf_buffer *perf_buffer__new_raw(int map_fd, size_t page_cnt,
13962 					 struct perf_event_attr *attr,
13963 					 perf_buffer_event_fn event_cb, void *ctx,
13964 					 const struct perf_buffer_raw_opts *opts)
13965 {
13966 	struct perf_buffer_params p = {};
13967 
13968 	if (!attr)
13969 		return libbpf_err_ptr(-EINVAL);
13970 
13971 	if (!OPTS_VALID(opts, perf_buffer_raw_opts))
13972 		return libbpf_err_ptr(-EINVAL);
13973 
13974 	p.attr = attr;
13975 	p.event_cb = event_cb;
13976 	p.ctx = ctx;
13977 	p.cpu_cnt = OPTS_GET(opts, cpu_cnt, 0);
13978 	p.cpus = OPTS_GET(opts, cpus, NULL);
13979 	p.map_keys = OPTS_GET(opts, map_keys, NULL);
13980 
13981 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
13982 }
13983 
13984 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
13985 					      struct perf_buffer_params *p)
13986 {
13987 	const char *online_cpus_file = "/sys/devices/system/cpu/online";
13988 	struct bpf_map_info map;
13989 	struct perf_buffer *pb;
13990 	bool *online = NULL;
13991 	__u32 map_info_len;
13992 	int err, i, j, n;
13993 
13994 	if (page_cnt == 0 || (page_cnt & (page_cnt - 1))) {
13995 		pr_warn("page count should be power of two, but is %zu\n",
13996 			page_cnt);
13997 		return ERR_PTR(-EINVAL);
13998 	}
13999 
14000 	/* best-effort sanity checks */
14001 	memset(&map, 0, sizeof(map));
14002 	map_info_len = sizeof(map);
14003 	err = bpf_map_get_info_by_fd(map_fd, &map, &map_info_len);
14004 	if (err) {
14005 		err = -errno;
14006 		/* if BPF_OBJ_GET_INFO_BY_FD is supported, will return
14007 		 * -EBADFD, -EFAULT, or -E2BIG on real error
14008 		 */
14009 		if (err != -EINVAL) {
14010 			pr_warn("failed to get map info for map FD %d: %s\n",
14011 				map_fd, errstr(err));
14012 			return ERR_PTR(err);
14013 		}
14014 		pr_debug("failed to get map info for FD %d; API not supported? Ignoring...\n",
14015 			 map_fd);
14016 	} else {
14017 		if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
14018 			pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
14019 				map.name);
14020 			return ERR_PTR(-EINVAL);
14021 		}
14022 	}
14023 
14024 	pb = calloc(1, sizeof(*pb));
14025 	if (!pb)
14026 		return ERR_PTR(-ENOMEM);
14027 
14028 	pb->event_cb = p->event_cb;
14029 	pb->sample_cb = p->sample_cb;
14030 	pb->lost_cb = p->lost_cb;
14031 	pb->ctx = p->ctx;
14032 
14033 	pb->page_size = getpagesize();
14034 	pb->mmap_size = pb->page_size * page_cnt;
14035 	pb->map_fd = map_fd;
14036 
14037 	pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
14038 	if (pb->epoll_fd < 0) {
14039 		err = -errno;
14040 		pr_warn("failed to create epoll instance: %s\n",
14041 			errstr(err));
14042 		goto error;
14043 	}
14044 
14045 	if (p->cpu_cnt > 0) {
14046 		pb->cpu_cnt = p->cpu_cnt;
14047 	} else {
14048 		pb->cpu_cnt = libbpf_num_possible_cpus();
14049 		if (pb->cpu_cnt < 0) {
14050 			err = pb->cpu_cnt;
14051 			goto error;
14052 		}
14053 		if (map.max_entries && map.max_entries < pb->cpu_cnt)
14054 			pb->cpu_cnt = map.max_entries;
14055 	}
14056 
14057 	pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
14058 	if (!pb->events) {
14059 		err = -ENOMEM;
14060 		pr_warn("failed to allocate events: out of memory\n");
14061 		goto error;
14062 	}
14063 	pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
14064 	if (!pb->cpu_bufs) {
14065 		err = -ENOMEM;
14066 		pr_warn("failed to allocate buffers: out of memory\n");
14067 		goto error;
14068 	}
14069 
14070 	err = parse_cpu_mask_file(online_cpus_file, &online, &n);
14071 	if (err) {
14072 		pr_warn("failed to get online CPU mask: %s\n", errstr(err));
14073 		goto error;
14074 	}
14075 
14076 	for (i = 0, j = 0; i < pb->cpu_cnt; i++) {
14077 		struct perf_cpu_buf *cpu_buf;
14078 		int cpu, map_key;
14079 
14080 		cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
14081 		map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
14082 
14083 		/* in case user didn't explicitly requested particular CPUs to
14084 		 * be attached to, skip offline/not present CPUs
14085 		 */
14086 		if (p->cpu_cnt <= 0 && (cpu >= n || !online[cpu]))
14087 			continue;
14088 
14089 		cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
14090 		if (IS_ERR(cpu_buf)) {
14091 			err = PTR_ERR(cpu_buf);
14092 			goto error;
14093 		}
14094 
14095 		pb->cpu_bufs[j] = cpu_buf;
14096 
14097 		err = bpf_map_update_elem(pb->map_fd, &map_key,
14098 					  &cpu_buf->fd, 0);
14099 		if (err) {
14100 			err = -errno;
14101 			pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
14102 				cpu, map_key, cpu_buf->fd,
14103 				errstr(err));
14104 			goto error;
14105 		}
14106 
14107 		pb->events[j].events = EPOLLIN;
14108 		pb->events[j].data.ptr = cpu_buf;
14109 		if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
14110 			      &pb->events[j]) < 0) {
14111 			err = -errno;
14112 			pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
14113 				cpu, cpu_buf->fd,
14114 				errstr(err));
14115 			goto error;
14116 		}
14117 		j++;
14118 	}
14119 	pb->cpu_cnt = j;
14120 	free(online);
14121 
14122 	return pb;
14123 
14124 error:
14125 	free(online);
14126 	if (pb)
14127 		perf_buffer__free(pb);
14128 	return ERR_PTR(err);
14129 }
14130 
14131 struct perf_sample_raw {
14132 	struct perf_event_header header;
14133 	uint32_t size;
14134 	char data[];
14135 };
14136 
14137 struct perf_sample_lost {
14138 	struct perf_event_header header;
14139 	uint64_t id;
14140 	uint64_t lost;
14141 	uint64_t sample_id;
14142 };
14143 
14144 static enum bpf_perf_event_ret
14145 perf_buffer__process_record(struct perf_event_header *e, void *ctx)
14146 {
14147 	struct perf_cpu_buf *cpu_buf = ctx;
14148 	struct perf_buffer *pb = cpu_buf->pb;
14149 	void *data = e;
14150 
14151 	/* user wants full control over parsing perf event */
14152 	if (pb->event_cb)
14153 		return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
14154 
14155 	switch (e->type) {
14156 	case PERF_RECORD_SAMPLE: {
14157 		struct perf_sample_raw *s = data;
14158 
14159 		if (pb->sample_cb)
14160 			pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
14161 		break;
14162 	}
14163 	case PERF_RECORD_LOST: {
14164 		struct perf_sample_lost *s = data;
14165 
14166 		if (pb->lost_cb)
14167 			pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
14168 		break;
14169 	}
14170 	default:
14171 		pr_warn("unknown perf sample type %d\n", e->type);
14172 		return LIBBPF_PERF_EVENT_ERROR;
14173 	}
14174 	return LIBBPF_PERF_EVENT_CONT;
14175 }
14176 
14177 static int perf_buffer__process_records(struct perf_buffer *pb,
14178 					struct perf_cpu_buf *cpu_buf)
14179 {
14180 	enum bpf_perf_event_ret ret;
14181 
14182 	ret = perf_event_read_simple(cpu_buf->base, pb->mmap_size,
14183 				     pb->page_size, &cpu_buf->buf,
14184 				     &cpu_buf->buf_size,
14185 				     perf_buffer__process_record, cpu_buf);
14186 	if (ret != LIBBPF_PERF_EVENT_CONT)
14187 		return ret;
14188 	return 0;
14189 }
14190 
14191 int perf_buffer__epoll_fd(const struct perf_buffer *pb)
14192 {
14193 	return pb->epoll_fd;
14194 }
14195 
14196 int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
14197 {
14198 	int i, cnt, err;
14199 
14200 	cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
14201 	if (cnt < 0)
14202 		return -errno;
14203 
14204 	for (i = 0; i < cnt; i++) {
14205 		struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
14206 
14207 		err = perf_buffer__process_records(pb, cpu_buf);
14208 		if (err) {
14209 			pr_warn("error while processing records: %s\n", errstr(err));
14210 			return libbpf_err(err);
14211 		}
14212 	}
14213 	return cnt;
14214 }
14215 
14216 /* Return number of PERF_EVENT_ARRAY map slots set up by this perf_buffer
14217  * manager.
14218  */
14219 size_t perf_buffer__buffer_cnt(const struct perf_buffer *pb)
14220 {
14221 	return pb->cpu_cnt;
14222 }
14223 
14224 /*
14225  * Return perf_event FD of a ring buffer in *buf_idx* slot of
14226  * PERF_EVENT_ARRAY BPF map. This FD can be polled for new data using
14227  * select()/poll()/epoll() Linux syscalls.
14228  */
14229 int perf_buffer__buffer_fd(const struct perf_buffer *pb, size_t buf_idx)
14230 {
14231 	struct perf_cpu_buf *cpu_buf;
14232 
14233 	if (buf_idx >= pb->cpu_cnt)
14234 		return libbpf_err(-EINVAL);
14235 
14236 	cpu_buf = pb->cpu_bufs[buf_idx];
14237 	if (!cpu_buf)
14238 		return libbpf_err(-ENOENT);
14239 
14240 	return cpu_buf->fd;
14241 }
14242 
14243 int perf_buffer__buffer(struct perf_buffer *pb, int buf_idx, void **buf, size_t *buf_size)
14244 {
14245 	struct perf_cpu_buf *cpu_buf;
14246 
14247 	if (buf_idx >= pb->cpu_cnt)
14248 		return libbpf_err(-EINVAL);
14249 
14250 	cpu_buf = pb->cpu_bufs[buf_idx];
14251 	if (!cpu_buf)
14252 		return libbpf_err(-ENOENT);
14253 
14254 	*buf = cpu_buf->base;
14255 	*buf_size = pb->mmap_size;
14256 	return 0;
14257 }
14258 
14259 /*
14260  * Consume data from perf ring buffer corresponding to slot *buf_idx* in
14261  * PERF_EVENT_ARRAY BPF map without waiting/polling. If there is no data to
14262  * consume, do nothing and return success.
14263  * Returns:
14264  *   - 0 on success;
14265  *   - <0 on failure.
14266  */
14267 int perf_buffer__consume_buffer(struct perf_buffer *pb, size_t buf_idx)
14268 {
14269 	struct perf_cpu_buf *cpu_buf;
14270 
14271 	if (buf_idx >= pb->cpu_cnt)
14272 		return libbpf_err(-EINVAL);
14273 
14274 	cpu_buf = pb->cpu_bufs[buf_idx];
14275 	if (!cpu_buf)
14276 		return libbpf_err(-ENOENT);
14277 
14278 	return perf_buffer__process_records(pb, cpu_buf);
14279 }
14280 
14281 int perf_buffer__consume(struct perf_buffer *pb)
14282 {
14283 	int i, err;
14284 
14285 	for (i = 0; i < pb->cpu_cnt; i++) {
14286 		struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
14287 
14288 		if (!cpu_buf)
14289 			continue;
14290 
14291 		err = perf_buffer__process_records(pb, cpu_buf);
14292 		if (err) {
14293 			pr_warn("perf_buffer: failed to process records in buffer #%d: %s\n",
14294 				i, errstr(err));
14295 			return libbpf_err(err);
14296 		}
14297 	}
14298 	return 0;
14299 }
14300 
14301 int bpf_program__set_attach_target(struct bpf_program *prog,
14302 				   int attach_prog_fd,
14303 				   const char *attach_func_name)
14304 {
14305 	int btf_obj_fd = 0, btf_id = 0, err;
14306 
14307 	if (!prog || attach_prog_fd < 0)
14308 		return libbpf_err(-EINVAL);
14309 
14310 	if (prog->obj->state >= OBJ_LOADED)
14311 		return libbpf_err(-EINVAL);
14312 
14313 	if (attach_prog_fd && !attach_func_name) {
14314 		/* Store attach_prog_fd. The BTF ID will be resolved later during
14315 		 * the normal object/program load phase.
14316 		 */
14317 		prog->attach_prog_fd = attach_prog_fd;
14318 		return 0;
14319 	}
14320 
14321 	if (attach_prog_fd) {
14322 		btf_id = libbpf_find_prog_btf_id(attach_func_name,
14323 						 attach_prog_fd, prog->obj->token_fd);
14324 		if (btf_id < 0)
14325 			return libbpf_err(btf_id);
14326 	} else {
14327 		if (!attach_func_name)
14328 			return libbpf_err(-EINVAL);
14329 
14330 		/* load btf_vmlinux, if not yet */
14331 		err = bpf_object__load_vmlinux_btf(prog->obj, true);
14332 		if (err)
14333 			return libbpf_err(err);
14334 		err = find_kernel_btf_id(prog->obj, attach_func_name,
14335 					 prog->expected_attach_type,
14336 					 &btf_obj_fd, &btf_id);
14337 		if (err)
14338 			return libbpf_err(err);
14339 	}
14340 
14341 	prog->attach_btf_id = btf_id;
14342 	prog->attach_btf_obj_fd = btf_obj_fd;
14343 	prog->attach_prog_fd = attach_prog_fd;
14344 	return 0;
14345 }
14346 
14347 int bpf_program__assoc_struct_ops(struct bpf_program *prog, struct bpf_map *map,
14348 				  struct bpf_prog_assoc_struct_ops_opts *opts)
14349 {
14350 	int prog_fd, map_fd;
14351 
14352 	prog_fd = bpf_program__fd(prog);
14353 	if (prog_fd < 0) {
14354 		pr_warn("prog '%s': can't associate BPF program without FD (was it loaded?)\n",
14355 			prog->name);
14356 		return libbpf_err(-EINVAL);
14357 	}
14358 
14359 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS) {
14360 		pr_warn("prog '%s': can't associate struct_ops program\n", prog->name);
14361 		return libbpf_err(-EINVAL);
14362 	}
14363 
14364 	map_fd = bpf_map__fd(map);
14365 	if (map_fd < 0) {
14366 		pr_warn("map '%s': can't associate BPF map without FD (was it created?)\n", map->name);
14367 		return libbpf_err(-EINVAL);
14368 	}
14369 
14370 	if (!bpf_map__is_struct_ops(map)) {
14371 		pr_warn("map '%s': can't associate non-struct_ops map\n", map->name);
14372 		return libbpf_err(-EINVAL);
14373 	}
14374 
14375 	return bpf_prog_assoc_struct_ops(prog_fd, map_fd, opts);
14376 }
14377 
14378 int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz)
14379 {
14380 	int err = 0, n, len, start, end = -1;
14381 	bool *tmp;
14382 
14383 	*mask = NULL;
14384 	*mask_sz = 0;
14385 
14386 	/* Each sub string separated by ',' has format \d+-\d+ or \d+ */
14387 	while (*s) {
14388 		if (*s == ',' || *s == '\n') {
14389 			s++;
14390 			continue;
14391 		}
14392 		n = sscanf(s, "%d%n-%d%n", &start, &len, &end, &len);
14393 		if (n <= 0 || n > 2) {
14394 			pr_warn("Failed to get CPU range %s: %d\n", s, n);
14395 			err = -EINVAL;
14396 			goto cleanup;
14397 		} else if (n == 1) {
14398 			end = start;
14399 		}
14400 		if (start < 0 || start > end) {
14401 			pr_warn("Invalid CPU range [%d,%d] in %s\n",
14402 				start, end, s);
14403 			err = -EINVAL;
14404 			goto cleanup;
14405 		}
14406 		tmp = realloc(*mask, end + 1);
14407 		if (!tmp) {
14408 			err = -ENOMEM;
14409 			goto cleanup;
14410 		}
14411 		*mask = tmp;
14412 		memset(tmp + *mask_sz, 0, start - *mask_sz);
14413 		memset(tmp + start, 1, end - start + 1);
14414 		*mask_sz = end + 1;
14415 		s += len;
14416 	}
14417 	if (!*mask_sz) {
14418 		pr_warn("Empty CPU range\n");
14419 		return -EINVAL;
14420 	}
14421 	return 0;
14422 cleanup:
14423 	free(*mask);
14424 	*mask = NULL;
14425 	return err;
14426 }
14427 
14428 int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz)
14429 {
14430 	int fd, err = 0, len;
14431 	char buf[128];
14432 
14433 	fd = open(fcpu, O_RDONLY | O_CLOEXEC);
14434 	if (fd < 0) {
14435 		err = -errno;
14436 		pr_warn("Failed to open cpu mask file %s: %s\n", fcpu, errstr(err));
14437 		return err;
14438 	}
14439 	len = read(fd, buf, sizeof(buf));
14440 	close(fd);
14441 	if (len <= 0) {
14442 		err = len ? -errno : -EINVAL;
14443 		pr_warn("Failed to read cpu mask from %s: %s\n", fcpu, errstr(err));
14444 		return err;
14445 	}
14446 	if (len >= sizeof(buf)) {
14447 		pr_warn("CPU mask is too big in file %s\n", fcpu);
14448 		return -E2BIG;
14449 	}
14450 	buf[len] = '\0';
14451 
14452 	return parse_cpu_mask_str(buf, mask, mask_sz);
14453 }
14454 
14455 int libbpf_num_possible_cpus(void)
14456 {
14457 	static const char *fcpu = "/sys/devices/system/cpu/possible";
14458 	static int cpus;
14459 	int err, n, i, tmp_cpus;
14460 	bool *mask;
14461 
14462 	tmp_cpus = READ_ONCE(cpus);
14463 	if (tmp_cpus > 0)
14464 		return tmp_cpus;
14465 
14466 	err = parse_cpu_mask_file(fcpu, &mask, &n);
14467 	if (err)
14468 		return libbpf_err(err);
14469 
14470 	tmp_cpus = 0;
14471 	for (i = 0; i < n; i++) {
14472 		if (mask[i])
14473 			tmp_cpus++;
14474 	}
14475 	free(mask);
14476 
14477 	WRITE_ONCE(cpus, tmp_cpus);
14478 	return tmp_cpus;
14479 }
14480 
14481 static int populate_skeleton_maps(const struct bpf_object *obj,
14482 				  struct bpf_map_skeleton *maps,
14483 				  size_t map_cnt, size_t map_skel_sz)
14484 {
14485 	int i;
14486 
14487 	for (i = 0; i < map_cnt; i++) {
14488 		struct bpf_map_skeleton *map_skel = (void *)maps + i * map_skel_sz;
14489 		struct bpf_map **map = map_skel->map;
14490 		const char *name = map_skel->name;
14491 		void **mmaped = map_skel->mmaped;
14492 
14493 		*map = bpf_object__find_map_by_name(obj, name);
14494 		if (!*map) {
14495 			pr_warn("failed to find skeleton map '%s'\n", name);
14496 			return -ESRCH;
14497 		}
14498 
14499 		/* externs shouldn't be pre-setup from user code */
14500 		if (mmaped && (*map)->libbpf_type != LIBBPF_MAP_KCONFIG)
14501 			*mmaped = (*map)->mmaped;
14502 	}
14503 	return 0;
14504 }
14505 
14506 static int populate_skeleton_progs(const struct bpf_object *obj,
14507 				   struct bpf_prog_skeleton *progs,
14508 				   size_t prog_cnt, size_t prog_skel_sz)
14509 {
14510 	int i;
14511 
14512 	for (i = 0; i < prog_cnt; i++) {
14513 		struct bpf_prog_skeleton *prog_skel = (void *)progs + i * prog_skel_sz;
14514 		struct bpf_program **prog = prog_skel->prog;
14515 		const char *name = prog_skel->name;
14516 
14517 		*prog = bpf_object__find_program_by_name(obj, name);
14518 		if (!*prog) {
14519 			pr_warn("failed to find skeleton program '%s'\n", name);
14520 			return -ESRCH;
14521 		}
14522 	}
14523 	return 0;
14524 }
14525 
14526 int bpf_object__open_skeleton(struct bpf_object_skeleton *s,
14527 			      const struct bpf_object_open_opts *opts)
14528 {
14529 	struct bpf_object *obj;
14530 	int err;
14531 
14532 	obj = bpf_object_open(NULL, s->data, s->data_sz, s->name, opts);
14533 	if (IS_ERR(obj)) {
14534 		err = PTR_ERR(obj);
14535 		pr_warn("failed to initialize skeleton BPF object '%s': %s\n",
14536 			s->name, errstr(err));
14537 		return libbpf_err(err);
14538 	}
14539 
14540 	*s->obj = obj;
14541 	err = populate_skeleton_maps(obj, s->maps, s->map_cnt, s->map_skel_sz);
14542 	if (err) {
14543 		pr_warn("failed to populate skeleton maps for '%s': %s\n", s->name, errstr(err));
14544 		return libbpf_err(err);
14545 	}
14546 
14547 	err = populate_skeleton_progs(obj, s->progs, s->prog_cnt, s->prog_skel_sz);
14548 	if (err) {
14549 		pr_warn("failed to populate skeleton progs for '%s': %s\n", s->name, errstr(err));
14550 		return libbpf_err(err);
14551 	}
14552 
14553 	return 0;
14554 }
14555 
14556 int bpf_object__open_subskeleton(struct bpf_object_subskeleton *s)
14557 {
14558 	int err, len, var_idx, i;
14559 	const char *var_name;
14560 	const struct bpf_map *map;
14561 	struct btf *btf;
14562 	__u32 map_type_id;
14563 	const struct btf_type *map_type, *var_type;
14564 	const struct bpf_var_skeleton *var_skel;
14565 	struct btf_var_secinfo *var;
14566 
14567 	if (!s->obj)
14568 		return libbpf_err(-EINVAL);
14569 
14570 	btf = bpf_object__btf(s->obj);
14571 	if (!btf) {
14572 		pr_warn("subskeletons require BTF at runtime (object %s)\n",
14573 			bpf_object__name(s->obj));
14574 		return libbpf_err(-errno);
14575 	}
14576 
14577 	err = populate_skeleton_maps(s->obj, s->maps, s->map_cnt, s->map_skel_sz);
14578 	if (err) {
14579 		pr_warn("failed to populate subskeleton maps: %s\n", errstr(err));
14580 		return libbpf_err(err);
14581 	}
14582 
14583 	err = populate_skeleton_progs(s->obj, s->progs, s->prog_cnt, s->prog_skel_sz);
14584 	if (err) {
14585 		pr_warn("failed to populate subskeleton maps: %s\n", errstr(err));
14586 		return libbpf_err(err);
14587 	}
14588 
14589 	for (var_idx = 0; var_idx < s->var_cnt; var_idx++) {
14590 		var_skel = (void *)s->vars + var_idx * s->var_skel_sz;
14591 		map = *var_skel->map;
14592 		map_type_id = bpf_map__btf_value_type_id(map);
14593 		map_type = btf__type_by_id(btf, map_type_id);
14594 
14595 		if (!btf_is_datasec(map_type)) {
14596 			pr_warn("type for map '%1$s' is not a datasec: %2$s\n",
14597 				bpf_map__name(map),
14598 				__btf_kind_str(btf_kind(map_type)));
14599 			return libbpf_err(-EINVAL);
14600 		}
14601 
14602 		len = btf_vlen(map_type);
14603 		var = btf_var_secinfos(map_type);
14604 		for (i = 0; i < len; i++, var++) {
14605 			var_type = btf__type_by_id(btf, var->type);
14606 			var_name = btf__name_by_offset(btf, var_type->name_off);
14607 			if (strcmp(var_name, var_skel->name) == 0) {
14608 				*var_skel->addr = map->mmaped + var->offset;
14609 				break;
14610 			}
14611 		}
14612 	}
14613 	return 0;
14614 }
14615 
14616 void bpf_object__destroy_subskeleton(struct bpf_object_subskeleton *s)
14617 {
14618 	if (!s)
14619 		return;
14620 	free(s->maps);
14621 	free(s->progs);
14622 	free(s->vars);
14623 	free(s);
14624 }
14625 
14626 int bpf_object__load_skeleton(struct bpf_object_skeleton *s)
14627 {
14628 	int i, err;
14629 
14630 	err = bpf_object__load(*s->obj);
14631 	if (err) {
14632 		pr_warn("failed to load BPF skeleton '%s': %s\n", s->name, errstr(err));
14633 		return libbpf_err(err);
14634 	}
14635 
14636 	for (i = 0; i < s->map_cnt; i++) {
14637 		struct bpf_map_skeleton *map_skel = (void *)s->maps + i * s->map_skel_sz;
14638 		struct bpf_map *map = *map_skel->map;
14639 
14640 		if (!map_skel->mmaped)
14641 			continue;
14642 
14643 		if (map->def.type == BPF_MAP_TYPE_ARENA)
14644 			*map_skel->mmaped = map->mmaped + map->obj->arena_data_off;
14645 		else
14646 			*map_skel->mmaped = map->mmaped;
14647 	}
14648 
14649 	return 0;
14650 }
14651 
14652 int bpf_object__attach_skeleton(struct bpf_object_skeleton *s)
14653 {
14654 	int i, err;
14655 
14656 	for (i = 0; i < s->prog_cnt; i++) {
14657 		struct bpf_prog_skeleton *prog_skel = (void *)s->progs + i * s->prog_skel_sz;
14658 		struct bpf_program *prog = *prog_skel->prog;
14659 		struct bpf_link **link = prog_skel->link;
14660 
14661 		if (!prog->autoload || !prog->autoattach)
14662 			continue;
14663 
14664 		/* auto-attaching not supported for this program */
14665 		if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
14666 			continue;
14667 
14668 		/* if user already set the link manually, don't attempt auto-attach */
14669 		if (*link)
14670 			continue;
14671 
14672 		err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, link);
14673 		if (err) {
14674 			pr_warn("prog '%s': failed to auto-attach: %s\n",
14675 				bpf_program__name(prog), errstr(err));
14676 			return libbpf_err(err);
14677 		}
14678 
14679 		/* It's possible that for some SEC() definitions auto-attach
14680 		 * is supported in some cases (e.g., if definition completely
14681 		 * specifies target information), but is not in other cases.
14682 		 * SEC("uprobe") is one such case. If user specified target
14683 		 * binary and function name, such BPF program can be
14684 		 * auto-attached. But if not, it shouldn't trigger skeleton's
14685 		 * attach to fail. It should just be skipped.
14686 		 * attach_fn signals such case with returning 0 (no error) and
14687 		 * setting link to NULL.
14688 		 */
14689 	}
14690 
14691 
14692 	for (i = 0; i < s->map_cnt; i++) {
14693 		struct bpf_map_skeleton *map_skel = (void *)s->maps + i * s->map_skel_sz;
14694 		struct bpf_map *map = *map_skel->map;
14695 		struct bpf_link **link;
14696 
14697 		if (!map->autocreate || !map->autoattach)
14698 			continue;
14699 
14700 		/* only struct_ops maps can be attached */
14701 		if (!bpf_map__is_struct_ops(map))
14702 			continue;
14703 
14704 		/* skeleton is created with earlier version of bpftool, notify user */
14705 		if (s->map_skel_sz < offsetofend(struct bpf_map_skeleton, link)) {
14706 			pr_warn("map '%s': BPF skeleton version is old, skipping map auto-attachment...\n",
14707 				bpf_map__name(map));
14708 			continue;
14709 		}
14710 
14711 		link = map_skel->link;
14712 		if (!link) {
14713 			pr_warn("map '%s': BPF map skeleton link is uninitialized\n",
14714 				bpf_map__name(map));
14715 			continue;
14716 		}
14717 
14718 		if (*link)
14719 			continue;
14720 
14721 		*link = bpf_map__attach_struct_ops(map);
14722 		if (!*link) {
14723 			err = -errno;
14724 			pr_warn("map '%s': failed to auto-attach: %s\n",
14725 				bpf_map__name(map), errstr(err));
14726 			return libbpf_err(err);
14727 		}
14728 	}
14729 
14730 	return 0;
14731 }
14732 
14733 void bpf_object__detach_skeleton(struct bpf_object_skeleton *s)
14734 {
14735 	int i;
14736 
14737 	for (i = 0; i < s->prog_cnt; i++) {
14738 		struct bpf_prog_skeleton *prog_skel = (void *)s->progs + i * s->prog_skel_sz;
14739 		struct bpf_link **link = prog_skel->link;
14740 
14741 		bpf_link__destroy(*link);
14742 		*link = NULL;
14743 	}
14744 
14745 	if (s->map_skel_sz < sizeof(struct bpf_map_skeleton))
14746 		return;
14747 
14748 	for (i = 0; i < s->map_cnt; i++) {
14749 		struct bpf_map_skeleton *map_skel = (void *)s->maps + i * s->map_skel_sz;
14750 		struct bpf_link **link = map_skel->link;
14751 
14752 		if (link) {
14753 			bpf_link__destroy(*link);
14754 			*link = NULL;
14755 		}
14756 	}
14757 }
14758 
14759 void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s)
14760 {
14761 	if (!s)
14762 		return;
14763 
14764 	bpf_object__detach_skeleton(s);
14765 	if (s->obj)
14766 		bpf_object__close(*s->obj);
14767 	free(s->maps);
14768 	free(s->progs);
14769 	free(s);
14770 }
14771