xref: /linux/tools/lib/bpf/libbpf.c (revision 434ea9c5125a8c3ad16e241687e1983309f99d1c)
1 // SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
2 
3 /*
4  * Common eBPF ELF object loading operations.
5  *
6  * Copyright (C) 2013-2015 Alexei Starovoitov <ast@kernel.org>
7  * Copyright (C) 2015 Wang Nan <wangnan0@huawei.com>
8  * Copyright (C) 2015 Huawei Inc.
9  * Copyright (C) 2017 Nicira, Inc.
10  * Copyright (C) 2019 Isovalent, Inc.
11  */
12 
13 #ifndef _GNU_SOURCE
14 #define _GNU_SOURCE
15 #endif
16 #include <stdlib.h>
17 #include <stdio.h>
18 #include <stdarg.h>
19 #include <libgen.h>
20 #include <inttypes.h>
21 #include <limits.h>
22 #include <string.h>
23 #include <unistd.h>
24 #include <endian.h>
25 #include <fcntl.h>
26 #include <errno.h>
27 #include <ctype.h>
28 #include <asm/unistd.h>
29 #include <linux/err.h>
30 #include <linux/kernel.h>
31 #include <linux/bpf.h>
32 #include <linux/btf.h>
33 #include <linux/filter.h>
34 #include <linux/limits.h>
35 #include <linux/perf_event.h>
36 #include <linux/bpf_perf_event.h>
37 #include <linux/ring_buffer.h>
38 #include <sys/epoll.h>
39 #include <sys/ioctl.h>
40 #include <sys/mman.h>
41 #include <sys/stat.h>
42 #include <sys/types.h>
43 #include <sys/vfs.h>
44 #include <sys/utsname.h>
45 #include <sys/resource.h>
46 #include <libelf.h>
47 #include <gelf.h>
48 #include <zlib.h>
49 
50 #include "libbpf.h"
51 #include "bpf.h"
52 #include "btf.h"
53 #include "libbpf_internal.h"
54 #include "hashmap.h"
55 #include "bpf_gen_internal.h"
56 #include "zip.h"
57 
58 #ifndef BPF_FS_MAGIC
59 #define BPF_FS_MAGIC		0xcafe4a11
60 #endif
61 
62 #define MAX_EVENT_NAME_LEN	64
63 
64 #define BPF_FS_DEFAULT_PATH "/sys/fs/bpf"
65 
66 #define BPF_INSN_SZ (sizeof(struct bpf_insn))
67 
68 /* vsprintf() in __base_pr() uses nonliteral format string. It may break
69  * compilation if user enables corresponding warning. Disable it explicitly.
70  */
71 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
72 
73 #define __printf(a, b)	__attribute__((format(printf, a, b)))
74 
75 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj);
76 static bool prog_is_subprog(const struct bpf_object *obj, const struct bpf_program *prog);
77 static int map_set_def_max_entries(struct bpf_map *map);
78 
79 static const char * const attach_type_name[] = {
80 	[BPF_CGROUP_INET_INGRESS]	= "cgroup_inet_ingress",
81 	[BPF_CGROUP_INET_EGRESS]	= "cgroup_inet_egress",
82 	[BPF_CGROUP_INET_SOCK_CREATE]	= "cgroup_inet_sock_create",
83 	[BPF_CGROUP_INET_SOCK_RELEASE]	= "cgroup_inet_sock_release",
84 	[BPF_CGROUP_SOCK_OPS]		= "cgroup_sock_ops",
85 	[BPF_CGROUP_DEVICE]		= "cgroup_device",
86 	[BPF_CGROUP_INET4_BIND]		= "cgroup_inet4_bind",
87 	[BPF_CGROUP_INET6_BIND]		= "cgroup_inet6_bind",
88 	[BPF_CGROUP_INET4_CONNECT]	= "cgroup_inet4_connect",
89 	[BPF_CGROUP_INET6_CONNECT]	= "cgroup_inet6_connect",
90 	[BPF_CGROUP_UNIX_CONNECT]       = "cgroup_unix_connect",
91 	[BPF_CGROUP_INET4_POST_BIND]	= "cgroup_inet4_post_bind",
92 	[BPF_CGROUP_INET6_POST_BIND]	= "cgroup_inet6_post_bind",
93 	[BPF_CGROUP_INET4_GETPEERNAME]	= "cgroup_inet4_getpeername",
94 	[BPF_CGROUP_INET6_GETPEERNAME]	= "cgroup_inet6_getpeername",
95 	[BPF_CGROUP_UNIX_GETPEERNAME]	= "cgroup_unix_getpeername",
96 	[BPF_CGROUP_INET4_GETSOCKNAME]	= "cgroup_inet4_getsockname",
97 	[BPF_CGROUP_INET6_GETSOCKNAME]	= "cgroup_inet6_getsockname",
98 	[BPF_CGROUP_UNIX_GETSOCKNAME]	= "cgroup_unix_getsockname",
99 	[BPF_CGROUP_UDP4_SENDMSG]	= "cgroup_udp4_sendmsg",
100 	[BPF_CGROUP_UDP6_SENDMSG]	= "cgroup_udp6_sendmsg",
101 	[BPF_CGROUP_UNIX_SENDMSG]	= "cgroup_unix_sendmsg",
102 	[BPF_CGROUP_SYSCTL]		= "cgroup_sysctl",
103 	[BPF_CGROUP_UDP4_RECVMSG]	= "cgroup_udp4_recvmsg",
104 	[BPF_CGROUP_UDP6_RECVMSG]	= "cgroup_udp6_recvmsg",
105 	[BPF_CGROUP_UNIX_RECVMSG]	= "cgroup_unix_recvmsg",
106 	[BPF_CGROUP_GETSOCKOPT]		= "cgroup_getsockopt",
107 	[BPF_CGROUP_SETSOCKOPT]		= "cgroup_setsockopt",
108 	[BPF_SK_SKB_STREAM_PARSER]	= "sk_skb_stream_parser",
109 	[BPF_SK_SKB_STREAM_VERDICT]	= "sk_skb_stream_verdict",
110 	[BPF_SK_SKB_VERDICT]		= "sk_skb_verdict",
111 	[BPF_SK_MSG_VERDICT]		= "sk_msg_verdict",
112 	[BPF_LIRC_MODE2]		= "lirc_mode2",
113 	[BPF_FLOW_DISSECTOR]		= "flow_dissector",
114 	[BPF_TRACE_RAW_TP]		= "trace_raw_tp",
115 	[BPF_TRACE_FENTRY]		= "trace_fentry",
116 	[BPF_TRACE_FEXIT]		= "trace_fexit",
117 	[BPF_MODIFY_RETURN]		= "modify_return",
118 	[BPF_TRACE_FSESSION]		= "trace_fsession",
119 	[BPF_LSM_MAC]			= "lsm_mac",
120 	[BPF_LSM_CGROUP]		= "lsm_cgroup",
121 	[BPF_SK_LOOKUP]			= "sk_lookup",
122 	[BPF_TRACE_ITER]		= "trace_iter",
123 	[BPF_XDP_DEVMAP]		= "xdp_devmap",
124 	[BPF_XDP_CPUMAP]		= "xdp_cpumap",
125 	[BPF_XDP]			= "xdp",
126 	[BPF_SK_REUSEPORT_SELECT]	= "sk_reuseport_select",
127 	[BPF_SK_REUSEPORT_SELECT_OR_MIGRATE]	= "sk_reuseport_select_or_migrate",
128 	[BPF_PERF_EVENT]		= "perf_event",
129 	[BPF_TRACE_KPROBE_MULTI]	= "trace_kprobe_multi",
130 	[BPF_STRUCT_OPS]		= "struct_ops",
131 	[BPF_NETFILTER]			= "netfilter",
132 	[BPF_TCX_INGRESS]		= "tcx_ingress",
133 	[BPF_TCX_EGRESS]		= "tcx_egress",
134 	[BPF_TRACE_UPROBE_MULTI]	= "trace_uprobe_multi",
135 	[BPF_NETKIT_PRIMARY]		= "netkit_primary",
136 	[BPF_NETKIT_PEER]		= "netkit_peer",
137 	[BPF_TRACE_KPROBE_SESSION]	= "trace_kprobe_session",
138 	[BPF_TRACE_UPROBE_SESSION]	= "trace_uprobe_session",
139 	[BPF_TRACE_FENTRY_MULTI]	= "trace_fentry_multi",
140 	[BPF_TRACE_FEXIT_MULTI]		= "trace_fexit_multi",
141 	[BPF_TRACE_FSESSION_MULTI]	= "trace_fsession_multi",
142 };
143 
144 static const char * const link_type_name[] = {
145 	[BPF_LINK_TYPE_UNSPEC]			= "unspec",
146 	[BPF_LINK_TYPE_RAW_TRACEPOINT]		= "raw_tracepoint",
147 	[BPF_LINK_TYPE_TRACING]			= "tracing",
148 	[BPF_LINK_TYPE_CGROUP]			= "cgroup",
149 	[BPF_LINK_TYPE_ITER]			= "iter",
150 	[BPF_LINK_TYPE_NETNS]			= "netns",
151 	[BPF_LINK_TYPE_XDP]			= "xdp",
152 	[BPF_LINK_TYPE_PERF_EVENT]		= "perf_event",
153 	[BPF_LINK_TYPE_KPROBE_MULTI]		= "kprobe_multi",
154 	[BPF_LINK_TYPE_STRUCT_OPS]		= "struct_ops",
155 	[BPF_LINK_TYPE_NETFILTER]		= "netfilter",
156 	[BPF_LINK_TYPE_TCX]			= "tcx",
157 	[BPF_LINK_TYPE_UPROBE_MULTI]		= "uprobe_multi",
158 	[BPF_LINK_TYPE_NETKIT]			= "netkit",
159 	[BPF_LINK_TYPE_SOCKMAP]			= "sockmap",
160 	[BPF_LINK_TYPE_TRACING_MULTI]		= "tracing_multi",
161 };
162 
163 static const char * const map_type_name[] = {
164 	[BPF_MAP_TYPE_UNSPEC]			= "unspec",
165 	[BPF_MAP_TYPE_HASH]			= "hash",
166 	[BPF_MAP_TYPE_ARRAY]			= "array",
167 	[BPF_MAP_TYPE_PROG_ARRAY]		= "prog_array",
168 	[BPF_MAP_TYPE_PERF_EVENT_ARRAY]		= "perf_event_array",
169 	[BPF_MAP_TYPE_PERCPU_HASH]		= "percpu_hash",
170 	[BPF_MAP_TYPE_PERCPU_ARRAY]		= "percpu_array",
171 	[BPF_MAP_TYPE_STACK_TRACE]		= "stack_trace",
172 	[BPF_MAP_TYPE_CGROUP_ARRAY]		= "cgroup_array",
173 	[BPF_MAP_TYPE_LRU_HASH]			= "lru_hash",
174 	[BPF_MAP_TYPE_LRU_PERCPU_HASH]		= "lru_percpu_hash",
175 	[BPF_MAP_TYPE_LPM_TRIE]			= "lpm_trie",
176 	[BPF_MAP_TYPE_ARRAY_OF_MAPS]		= "array_of_maps",
177 	[BPF_MAP_TYPE_HASH_OF_MAPS]		= "hash_of_maps",
178 	[BPF_MAP_TYPE_DEVMAP]			= "devmap",
179 	[BPF_MAP_TYPE_DEVMAP_HASH]		= "devmap_hash",
180 	[BPF_MAP_TYPE_SOCKMAP]			= "sockmap",
181 	[BPF_MAP_TYPE_CPUMAP]			= "cpumap",
182 	[BPF_MAP_TYPE_XSKMAP]			= "xskmap",
183 	[BPF_MAP_TYPE_SOCKHASH]			= "sockhash",
184 	[BPF_MAP_TYPE_CGROUP_STORAGE]		= "cgroup_storage",
185 	[BPF_MAP_TYPE_REUSEPORT_SOCKARRAY]	= "reuseport_sockarray",
186 	[BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE]	= "percpu_cgroup_storage",
187 	[BPF_MAP_TYPE_QUEUE]			= "queue",
188 	[BPF_MAP_TYPE_STACK]			= "stack",
189 	[BPF_MAP_TYPE_SK_STORAGE]		= "sk_storage",
190 	[BPF_MAP_TYPE_STRUCT_OPS]		= "struct_ops",
191 	[BPF_MAP_TYPE_RINGBUF]			= "ringbuf",
192 	[BPF_MAP_TYPE_INODE_STORAGE]		= "inode_storage",
193 	[BPF_MAP_TYPE_TASK_STORAGE]		= "task_storage",
194 	[BPF_MAP_TYPE_BLOOM_FILTER]		= "bloom_filter",
195 	[BPF_MAP_TYPE_USER_RINGBUF]             = "user_ringbuf",
196 	[BPF_MAP_TYPE_CGRP_STORAGE]		= "cgrp_storage",
197 	[BPF_MAP_TYPE_ARENA]			= "arena",
198 	[BPF_MAP_TYPE_INSN_ARRAY]		= "insn_array",
199 	[BPF_MAP_TYPE_RHASH]			= "rhash",
200 };
201 
202 static const char * const prog_type_name[] = {
203 	[BPF_PROG_TYPE_UNSPEC]			= "unspec",
204 	[BPF_PROG_TYPE_SOCKET_FILTER]		= "socket_filter",
205 	[BPF_PROG_TYPE_KPROBE]			= "kprobe",
206 	[BPF_PROG_TYPE_SCHED_CLS]		= "sched_cls",
207 	[BPF_PROG_TYPE_SCHED_ACT]		= "sched_act",
208 	[BPF_PROG_TYPE_TRACEPOINT]		= "tracepoint",
209 	[BPF_PROG_TYPE_XDP]			= "xdp",
210 	[BPF_PROG_TYPE_PERF_EVENT]		= "perf_event",
211 	[BPF_PROG_TYPE_CGROUP_SKB]		= "cgroup_skb",
212 	[BPF_PROG_TYPE_CGROUP_SOCK]		= "cgroup_sock",
213 	[BPF_PROG_TYPE_LWT_IN]			= "lwt_in",
214 	[BPF_PROG_TYPE_LWT_OUT]			= "lwt_out",
215 	[BPF_PROG_TYPE_LWT_XMIT]		= "lwt_xmit",
216 	[BPF_PROG_TYPE_SOCK_OPS]		= "sock_ops",
217 	[BPF_PROG_TYPE_SK_SKB]			= "sk_skb",
218 	[BPF_PROG_TYPE_CGROUP_DEVICE]		= "cgroup_device",
219 	[BPF_PROG_TYPE_SK_MSG]			= "sk_msg",
220 	[BPF_PROG_TYPE_RAW_TRACEPOINT]		= "raw_tracepoint",
221 	[BPF_PROG_TYPE_CGROUP_SOCK_ADDR]	= "cgroup_sock_addr",
222 	[BPF_PROG_TYPE_LWT_SEG6LOCAL]		= "lwt_seg6local",
223 	[BPF_PROG_TYPE_LIRC_MODE2]		= "lirc_mode2",
224 	[BPF_PROG_TYPE_SK_REUSEPORT]		= "sk_reuseport",
225 	[BPF_PROG_TYPE_FLOW_DISSECTOR]		= "flow_dissector",
226 	[BPF_PROG_TYPE_CGROUP_SYSCTL]		= "cgroup_sysctl",
227 	[BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE]	= "raw_tracepoint_writable",
228 	[BPF_PROG_TYPE_CGROUP_SOCKOPT]		= "cgroup_sockopt",
229 	[BPF_PROG_TYPE_TRACING]			= "tracing",
230 	[BPF_PROG_TYPE_STRUCT_OPS]		= "struct_ops",
231 	[BPF_PROG_TYPE_EXT]			= "ext",
232 	[BPF_PROG_TYPE_LSM]			= "lsm",
233 	[BPF_PROG_TYPE_SK_LOOKUP]		= "sk_lookup",
234 	[BPF_PROG_TYPE_SYSCALL]			= "syscall",
235 	[BPF_PROG_TYPE_NETFILTER]		= "netfilter",
236 };
237 
238 static int __base_pr(enum libbpf_print_level level, const char *format,
239 		     va_list args)
240 {
241 	const char *env_var = "LIBBPF_LOG_LEVEL";
242 	static enum libbpf_print_level min_level = LIBBPF_INFO;
243 	static bool initialized;
244 
245 	if (!initialized) {
246 		char *verbosity;
247 
248 		initialized = true;
249 		verbosity = getenv(env_var);
250 		if (verbosity) {
251 			if (strcasecmp(verbosity, "warn") == 0)
252 				min_level = LIBBPF_WARN;
253 			else if (strcasecmp(verbosity, "debug") == 0)
254 				min_level = LIBBPF_DEBUG;
255 			else if (strcasecmp(verbosity, "info") == 0)
256 				min_level = LIBBPF_INFO;
257 			else
258 				fprintf(stderr, "libbpf: unrecognized '%s' envvar value: '%s', should be one of 'warn', 'debug', or 'info'.\n",
259 					env_var, verbosity);
260 		}
261 	}
262 
263 	/* if too verbose, skip logging  */
264 	if (level > min_level)
265 		return 0;
266 
267 	return vfprintf(stderr, format, args);
268 }
269 
270 static libbpf_print_fn_t __libbpf_pr = __base_pr;
271 
272 libbpf_print_fn_t libbpf_set_print(libbpf_print_fn_t fn)
273 {
274 	libbpf_print_fn_t old_print_fn;
275 
276 	old_print_fn = __atomic_exchange_n(&__libbpf_pr, fn, __ATOMIC_RELAXED);
277 
278 	return old_print_fn;
279 }
280 
281 __printf(2, 3)
282 void libbpf_print(enum libbpf_print_level level, const char *format, ...)
283 {
284 	va_list args;
285 	int old_errno;
286 	libbpf_print_fn_t print_fn;
287 
288 	print_fn = __atomic_load_n(&__libbpf_pr, __ATOMIC_RELAXED);
289 	if (!print_fn)
290 		return;
291 
292 	old_errno = errno;
293 
294 	va_start(args, format);
295 	print_fn(level, format, args);
296 	va_end(args);
297 
298 	errno = old_errno;
299 }
300 
301 static void pr_perm_msg(int err)
302 {
303 	struct rlimit limit;
304 	char buf[100];
305 
306 	if (err != -EPERM || geteuid() != 0)
307 		return;
308 
309 	err = getrlimit(RLIMIT_MEMLOCK, &limit);
310 	if (err)
311 		return;
312 
313 	if (limit.rlim_cur == RLIM_INFINITY)
314 		return;
315 
316 	if (limit.rlim_cur < 1024)
317 		snprintf(buf, sizeof(buf), "%zu bytes", (size_t)limit.rlim_cur);
318 	else if (limit.rlim_cur < 1024*1024)
319 		snprintf(buf, sizeof(buf), "%.1f KiB", (double)limit.rlim_cur / 1024);
320 	else
321 		snprintf(buf, sizeof(buf), "%.1f MiB", (double)limit.rlim_cur / (1024*1024));
322 
323 	pr_warn("permission error while running as root; try raising 'ulimit -l'? current value: %s\n",
324 		buf);
325 }
326 
327 /* Copied from tools/perf/util/util.h */
328 #ifndef zfree
329 # define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
330 #endif
331 
332 #ifndef zclose
333 # define zclose(fd) ({			\
334 	int ___err = 0;			\
335 	if ((fd) >= 0)			\
336 		___err = close((fd));	\
337 	fd = -1;			\
338 	___err; })
339 #endif
340 
341 static inline __u64 ptr_to_u64(const void *ptr)
342 {
343 	return (__u64) (unsigned long) ptr;
344 }
345 
346 int libbpf_set_strict_mode(enum libbpf_strict_mode mode)
347 {
348 	/* as of v1.0 libbpf_set_strict_mode() is a no-op */
349 	return 0;
350 }
351 
352 __u32 libbpf_major_version(void)
353 {
354 	return LIBBPF_MAJOR_VERSION;
355 }
356 
357 __u32 libbpf_minor_version(void)
358 {
359 	return LIBBPF_MINOR_VERSION;
360 }
361 
362 const char *libbpf_version_string(void)
363 {
364 #define __S(X) #X
365 #define _S(X) __S(X)
366 	return  "v" _S(LIBBPF_MAJOR_VERSION) "." _S(LIBBPF_MINOR_VERSION);
367 #undef _S
368 #undef __S
369 }
370 
371 enum reloc_type {
372 	RELO_LD64,
373 	RELO_CALL,
374 	RELO_DATA,
375 	RELO_EXTERN_LD64,
376 	RELO_EXTERN_CALL,
377 	RELO_SUBPROG_ADDR,
378 	RELO_CORE,
379 	RELO_INSN_ARRAY,
380 };
381 
382 struct reloc_desc {
383 	enum reloc_type type;
384 	int insn_idx;
385 	union {
386 		const struct bpf_core_relo *core_relo; /* used when type == RELO_CORE */
387 		struct {
388 			int map_idx;
389 			unsigned int sym_off;
390 			/*
391 			 * The following two fields can be unionized, as the
392 			 * ext_idx field is used for extern symbols, and the
393 			 * sym_size is used for jump tables, which are never
394 			 * extern
395 			 */
396 			union {
397 				int ext_idx;
398 				int sym_size;
399 			};
400 		};
401 	};
402 };
403 
404 /* stored as sec_def->cookie for all libbpf-supported SEC()s */
405 enum sec_def_flags {
406 	SEC_NONE = 0,
407 	/* expected_attach_type is optional, if kernel doesn't support that */
408 	SEC_EXP_ATTACH_OPT = 1,
409 	/* legacy, only used by libbpf_get_type_names() and
410 	 * libbpf_attach_type_by_name(), not used by libbpf itself at all.
411 	 * This used to be associated with cgroup (and few other) BPF programs
412 	 * that were attachable through BPF_PROG_ATTACH command. Pretty
413 	 * meaningless nowadays, though.
414 	 */
415 	SEC_ATTACHABLE = 2,
416 	SEC_ATTACHABLE_OPT = SEC_ATTACHABLE | SEC_EXP_ATTACH_OPT,
417 	/* attachment target is specified through BTF ID in either kernel or
418 	 * other BPF program's BTF object
419 	 */
420 	SEC_ATTACH_BTF = 4,
421 	/* BPF program type allows sleeping/blocking in kernel */
422 	SEC_SLEEPABLE = 8,
423 	/* BPF program support non-linear XDP buffer */
424 	SEC_XDP_FRAGS = 16,
425 	/* Setup proper attach type for usdt probes. */
426 	SEC_USDT = 32,
427 };
428 
429 struct bpf_sec_def {
430 	char *sec;
431 	enum bpf_prog_type prog_type;
432 	enum bpf_attach_type expected_attach_type;
433 	long cookie;
434 	int handler_id;
435 
436 	libbpf_prog_setup_fn_t prog_setup_fn;
437 	libbpf_prog_prepare_load_fn_t prog_prepare_load_fn;
438 	libbpf_prog_attach_fn_t prog_attach_fn;
439 };
440 
441 struct bpf_light_subprog {
442 	__u32 sec_insn_off;
443 	__u32 sub_insn_off;
444 };
445 
446 /*
447  * bpf_prog should be a better name but it has been used in
448  * linux/filter.h.
449  */
450 struct bpf_program {
451 	char *name;
452 	char *sec_name;
453 	size_t sec_idx;
454 	const struct bpf_sec_def *sec_def;
455 	/* this program's instruction offset (in number of instructions)
456 	 * within its containing ELF section
457 	 */
458 	size_t sec_insn_off;
459 	/* number of original instructions in ELF section belonging to this
460 	 * program, not taking into account subprogram instructions possible
461 	 * appended later during relocation
462 	 */
463 	size_t sec_insn_cnt;
464 	/* Offset (in number of instructions) of the start of instruction
465 	 * belonging to this BPF program  within its containing main BPF
466 	 * program. For the entry-point (main) BPF program, this is always
467 	 * zero. For a sub-program, this gets reset before each of main BPF
468 	 * programs are processed and relocated and is used to determined
469 	 * whether sub-program was already appended to the main program, and
470 	 * if yes, at which instruction offset.
471 	 */
472 	size_t sub_insn_off;
473 
474 	/* instructions that belong to BPF program; insns[0] is located at
475 	 * sec_insn_off instruction within its ELF section in ELF file, so
476 	 * when mapping ELF file instruction index to the local instruction,
477 	 * one needs to subtract sec_insn_off; and vice versa.
478 	 */
479 	struct bpf_insn *insns;
480 	/* actual number of instruction in this BPF program's image; for
481 	 * entry-point BPF programs this includes the size of main program
482 	 * itself plus all the used sub-programs, appended at the end
483 	 */
484 	size_t insns_cnt;
485 
486 	struct reloc_desc *reloc_desc;
487 	int nr_reloc;
488 
489 	/* BPF verifier log settings */
490 	char *log_buf;
491 	size_t log_size;
492 	__u32 log_level;
493 
494 	struct bpf_object *obj;
495 
496 	int fd;
497 	bool autoload;
498 	bool autoattach;
499 	bool sym_global;
500 	/* the program or a function that it calls has callx */
501 	bool has_callx;
502 	bool mark_btf_static;
503 	enum bpf_prog_type type;
504 	enum bpf_attach_type expected_attach_type;
505 	int exception_cb_idx;
506 
507 	int prog_ifindex;
508 	__u32 attach_btf_obj_fd;
509 	__u32 attach_btf_id;
510 	__u32 attach_prog_fd;
511 
512 	void *func_info;
513 	__u32 func_info_rec_size;
514 	__u32 func_info_cnt;
515 
516 	void *line_info;
517 	__u32 line_info_rec_size;
518 	__u32 line_info_cnt;
519 	__u32 prog_flags;
520 	__u8  hash[SHA256_DIGEST_LENGTH];
521 
522 	struct bpf_light_subprog *subprogs;
523 	__u32 subprog_cnt;
524 };
525 
526 struct bpf_struct_ops {
527 	struct bpf_program **progs;
528 	__u32 *kern_func_off;
529 	/* e.g. struct tcp_congestion_ops in bpf_prog's btf format */
530 	void *data;
531 	/* e.g. struct bpf_struct_ops_tcp_congestion_ops in
532 	 *      btf_vmlinux's format.
533 	 * struct bpf_struct_ops_tcp_congestion_ops {
534 	 *	[... some other kernel fields ...]
535 	 *	struct tcp_congestion_ops data;
536 	 * }
537 	 * kern_vdata-size == sizeof(struct bpf_struct_ops_tcp_congestion_ops)
538 	 * bpf_map__init_kern_struct_ops() will populate the "kern_vdata"
539 	 * from "data".
540 	 */
541 	void *kern_vdata;
542 	__u32 type_id;
543 };
544 
545 #define DATA_SEC ".data"
546 #define PERCPU_SEC ".percpu"
547 #define BSS_SEC ".bss"
548 #define RODATA_SEC ".rodata"
549 #define DATA_REL_RO_SEC ".data.rel.ro"
550 #define KCONFIG_SEC ".kconfig"
551 #define KSYMS_SEC ".ksyms"
552 #define STRUCT_OPS_SEC ".struct_ops"
553 #define STRUCT_OPS_LINK_SEC ".struct_ops.link"
554 #define ARENA_SEC ".addr_space.1"
555 
556 enum libbpf_map_type {
557 	LIBBPF_MAP_UNSPEC,
558 	LIBBPF_MAP_DATA,
559 	LIBBPF_MAP_BSS,
560 	LIBBPF_MAP_RODATA,
561 	LIBBPF_MAP_KCONFIG,
562 	LIBBPF_MAP_PERCPU,
563 };
564 
565 struct bpf_map_def {
566 	unsigned int type;
567 	unsigned int key_size;
568 	unsigned int value_size;
569 	unsigned int max_entries;
570 	unsigned int map_flags;
571 };
572 
573 struct bpf_map {
574 	struct bpf_object *obj;
575 	char *name;
576 	/* real_name is defined for special internal maps (.rodata*,
577 	 * .data*, .bss, .kconfig) and preserves their original ELF section
578 	 * name. This is important to be able to find corresponding BTF
579 	 * DATASEC information.
580 	 */
581 	char *real_name;
582 	int fd;
583 	int sec_idx;
584 	size_t sec_offset;
585 	int map_ifindex;
586 	int inner_map_fd;
587 	struct bpf_map_def def;
588 	__u32 numa_node;
589 	__u32 btf_var_idx;
590 	int mod_btf_fd;
591 	__u32 btf_key_type_id;
592 	__u32 btf_value_type_id;
593 	__u32 btf_vmlinux_value_type_id;
594 	enum libbpf_map_type libbpf_type;
595 	void *mmaped;
596 	struct bpf_struct_ops *st_ops;
597 	struct bpf_map *inner_map;
598 	void **init_slots;
599 	int init_slots_sz;
600 	char *pin_path;
601 	bool pinned;
602 	bool reused;
603 	bool autocreate;
604 	bool autoattach;
605 	__u64 map_extra;
606 	struct bpf_program *excl_prog;
607 	/* pointers to functions in the data of an internal map, see obj->func_ptrs */
608 	struct func_ptr *func_ptrs;
609 	size_t func_ptr_cnt;
610 };
611 
612 enum extern_type {
613 	EXT_UNKNOWN,
614 	EXT_KCFG,
615 	EXT_KSYM,
616 };
617 
618 enum kcfg_type {
619 	KCFG_UNKNOWN,
620 	KCFG_CHAR,
621 	KCFG_BOOL,
622 	KCFG_INT,
623 	KCFG_TRISTATE,
624 	KCFG_CHAR_ARR,
625 };
626 
627 struct extern_desc {
628 	enum extern_type type;
629 	int sym_idx;
630 	int btf_id;
631 	int sec_btf_id;
632 	char *name;
633 	char *essent_name;
634 	bool is_set;
635 	bool is_weak;
636 	union {
637 		struct {
638 			enum kcfg_type type;
639 			int sz;
640 			int align;
641 			int data_off;
642 			bool is_signed;
643 		} kcfg;
644 		struct {
645 			unsigned long long addr;
646 
647 			/* target btf_id of the corresponding kernel var. */
648 			int kernel_btf_obj_fd;
649 			int kernel_btf_id;
650 
651 			/* local btf_id of the ksym extern's type. */
652 			__u32 type_id;
653 			/* BTF fd index to be patched in for insn->off, this is
654 			 * 0 for vmlinux BTF, index in obj->fd_array for module
655 			 * BTF
656 			 */
657 			__s16 btf_fd_idx;
658 		} ksym;
659 	};
660 };
661 
662 struct module_btf {
663 	struct btf *btf;
664 	char *name;
665 	__u32 id;
666 	int fd;
667 	int fd_array_idx;
668 };
669 
670 enum sec_type {
671 	SEC_UNUSED = 0,
672 	SEC_RELO,
673 	SEC_BSS,
674 	SEC_DATA,
675 	SEC_RODATA,
676 	SEC_ST_OPS,
677 	SEC_PERCPU,
678 };
679 
680 struct elf_sec_desc {
681 	enum sec_type sec_type;
682 	Elf64_Shdr *shdr;
683 	Elf_Data *data;
684 };
685 
686 struct elf_state {
687 	int fd;
688 	const void *obj_buf;
689 	size_t obj_buf_sz;
690 	Elf *elf;
691 	Elf64_Ehdr *ehdr;
692 	Elf_Data *symbols;
693 	Elf_Data *arena_data;
694 	size_t shstrndx; /* section index for section name strings */
695 	size_t strtabidx;
696 	struct elf_sec_desc *secs;
697 	size_t sec_cnt;
698 	int btf_maps_shndx;
699 	__u32 btf_maps_sec_btf_id;
700 	int text_shndx;
701 	int symbols_shndx;
702 	bool has_st_ops;
703 	int arena_data_shndx;
704 	int jumptables_data_shndx;
705 };
706 
707 struct usdt_manager;
708 
709 enum bpf_object_state {
710 	OBJ_OPEN,
711 	OBJ_PREPARED,
712 	OBJ_LOADED,
713 };
714 
715 struct bpf_object {
716 	char name[BPF_OBJ_NAME_LEN];
717 	char license[64];
718 	__u32 kern_version;
719 
720 	enum bpf_object_state state;
721 	struct bpf_program *programs;
722 	size_t nr_programs;
723 	struct bpf_map *maps;
724 	size_t nr_maps;
725 	size_t maps_cap;
726 
727 	char *kconfig;
728 	struct extern_desc *externs;
729 	int nr_extern;
730 	int kconfig_map_idx;
731 
732 	bool has_subcalls;
733 	bool has_rodata;
734 
735 	struct bpf_gen *gen_loader;
736 
737 	/* Information when doing ELF related work. Only valid if efile.elf is not NULL */
738 	struct elf_state efile;
739 
740 	unsigned char byteorder;
741 
742 	struct btf *btf;
743 	struct btf_ext *btf_ext;
744 
745 	/* Parse and load BTF vmlinux if any of the programs in the object need
746 	 * it at load time.
747 	 */
748 	struct btf *btf_vmlinux;
749 	/* Path to the custom BTF to be used for BPF CO-RE relocations as an
750 	 * override for vmlinux BTF.
751 	 */
752 	char *btf_custom_path;
753 	/* vmlinux BTF override for CO-RE relocations */
754 	struct btf *btf_vmlinux_override;
755 	/* Lazily initialized kernel module BTFs */
756 	struct module_btf *btf_modules;
757 	bool btf_modules_loaded;
758 	size_t btf_module_cnt;
759 	size_t btf_module_cap;
760 	char **btf_module_allowlist;
761 	ssize_t btf_module_allowlist_cnt;
762 
763 	/* optional log settings passed to BPF_BTF_LOAD and BPF_PROG_LOAD commands */
764 	char *log_buf;
765 	size_t log_size;
766 	__u32 log_level;
767 
768 	int *fd_array;
769 	size_t fd_array_cap;
770 	/*
771 	 * Slots handed out so far, slot 0 included. A kfunc insn names a module
772 	 * BTF slot through its offset, slot 0 stands for vmlinux BTF and stays
773 	 * empty, so the array goes to the kernel without a count, unless
774 	 * bpf_object__bind_arena() puts the arena of the object there.
775 	 */
776 	size_t fd_array_used;
777 
778 	struct usdt_manager *usdt_man;
779 
780 	int arena_map_idx;
781 	void *arena_data;
782 	size_t arena_data_sz;
783 	size_t arena_data_off;
784 
785 	void *jumptables_data;
786 	size_t jumptables_data_sz;
787 
788 	struct {
789 		struct bpf_program *prog;
790 		unsigned int sym_off;
791 		int fd;
792 	} *jumptable_maps;
793 	size_t jumptable_map_cnt;
794 
795 	/*
796 	 * Pointers to functions found in read-only data sections: tables of
797 	 * functions, structures of operations, vtables. Sorted by section
798 	 * and offset.
799 	 */
800 	struct func_ptr {
801 		int sec_idx;		/* ELF section that contains the pointer */
802 		size_t sec_off;		/* offset of the pointer in the section */
803 		size_t text_off;	/* offset of the function in .text section */
804 	} *func_ptrs;
805 	size_t func_ptr_cnt;
806 
807 	/*
808 	 * Read-only data with pointers to functions is different for every
809 	 * program that uses it, because so are the offsets of the functions.
810 	 */
811 	struct {
812 		struct bpf_program *prog;
813 		int map_idx;
814 		int fd;
815 	} *func_ptr_maps;
816 	size_t func_ptr_map_cnt;
817 
818 	struct kern_feature_cache *feat_cache;
819 	char *token_path;
820 	int token_fd;
821 
822 	char path[];
823 };
824 
825 static const char *elf_sym_str(const struct bpf_object *obj, size_t off);
826 static const char *elf_sec_str(const struct bpf_object *obj, size_t off);
827 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx);
828 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name);
829 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn);
830 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn);
831 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn);
832 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx);
833 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx);
834 
835 void bpf_program__unload(struct bpf_program *prog)
836 {
837 	if (!prog)
838 		return;
839 
840 	zclose(prog->fd);
841 
842 	zfree(&prog->func_info);
843 	zfree(&prog->line_info);
844 	zfree(&prog->subprogs);
845 }
846 
847 static void bpf_program__exit(struct bpf_program *prog)
848 {
849 	if (!prog)
850 		return;
851 
852 	bpf_program__unload(prog);
853 	zfree(&prog->name);
854 	zfree(&prog->sec_name);
855 	zfree(&prog->insns);
856 	zfree(&prog->reloc_desc);
857 
858 	prog->nr_reloc = 0;
859 	prog->insns_cnt = 0;
860 	prog->sec_idx = -1;
861 }
862 
863 static bool insn_is_subprog_call(const struct bpf_insn *insn)
864 {
865 	return BPF_CLASS(insn->code) == BPF_JMP &&
866 	       BPF_OP(insn->code) == BPF_CALL &&
867 	       BPF_SRC(insn->code) == BPF_K &&
868 	       insn->src_reg == BPF_PSEUDO_CALL &&
869 	       insn->dst_reg == 0 &&
870 	       insn->off == 0;
871 }
872 
873 static bool is_call_insn(const struct bpf_insn *insn)
874 {
875 	return insn->code == (BPF_JMP | BPF_CALL);
876 }
877 
878 static bool insn_is_pseudo_func(struct bpf_insn *insn)
879 {
880 	return is_ldimm64_insn(insn) && insn->src_reg == BPF_PSEUDO_FUNC;
881 }
882 
883 static bool prog_has_callx(const struct bpf_program *prog)
884 {
885 	size_t i;
886 
887 	for (i = 0; i < prog->insns_cnt; i++)
888 		if (prog->insns[i].code == (BPF_JMP | BPF_CALL | BPF_X))
889 			return true;
890 	return false;
891 }
892 
893 static int
894 bpf_object__init_prog(struct bpf_object *obj, struct bpf_program *prog,
895 		      const char *name, size_t sec_idx, const char *sec_name,
896 		      size_t sec_off, void *insn_data, size_t insn_data_sz)
897 {
898 	if (insn_data_sz == 0 || insn_data_sz % BPF_INSN_SZ || sec_off % BPF_INSN_SZ) {
899 		pr_warn("sec '%s': corrupted program '%s', offset %zu, size %zu\n",
900 			sec_name, name, sec_off, insn_data_sz);
901 		return -EINVAL;
902 	}
903 
904 	memset(prog, 0, sizeof(*prog));
905 	prog->obj = obj;
906 
907 	prog->sec_idx = sec_idx;
908 	prog->sec_insn_off = sec_off / BPF_INSN_SZ;
909 	prog->sec_insn_cnt = insn_data_sz / BPF_INSN_SZ;
910 	/* insns_cnt can later be increased by appending used subprograms */
911 	prog->insns_cnt = prog->sec_insn_cnt;
912 
913 	prog->type = BPF_PROG_TYPE_UNSPEC;
914 	prog->fd = -1;
915 	prog->exception_cb_idx = -1;
916 
917 	/* libbpf's convention for SEC("?abc...") is that it's just like
918 	 * SEC("abc...") but the corresponding bpf_program starts out with
919 	 * autoload set to false.
920 	 */
921 	if (sec_name[0] == '?') {
922 		prog->autoload = false;
923 		/* from now on forget there was ? in section name */
924 		sec_name++;
925 	} else {
926 		prog->autoload = true;
927 	}
928 
929 	prog->autoattach = true;
930 
931 	/* inherit object's log_level */
932 	prog->log_level = obj->log_level;
933 
934 	prog->sec_name = strdup(sec_name);
935 	if (!prog->sec_name)
936 		goto errout;
937 
938 	prog->name = strdup(name);
939 	if (!prog->name)
940 		goto errout;
941 
942 	prog->insns = malloc(insn_data_sz);
943 	if (!prog->insns)
944 		goto errout;
945 	memcpy(prog->insns, insn_data, insn_data_sz);
946 
947 	return 0;
948 errout:
949 	pr_warn("sec '%s': failed to allocate memory for prog '%s'\n", sec_name, name);
950 	bpf_program__exit(prog);
951 	return -ENOMEM;
952 }
953 
954 static int
955 bpf_object__add_programs(struct bpf_object *obj, Elf_Data *sec_data,
956 			 const char *sec_name, int sec_idx)
957 {
958 	Elf_Data *symbols = obj->efile.symbols;
959 	struct bpf_program *prog, *progs;
960 	void *data = sec_data->d_buf;
961 	size_t sec_sz = sec_data->d_size, sec_off, prog_sz, nr_syms;
962 	int nr_progs, err, i;
963 	const char *name;
964 	Elf64_Sym *sym;
965 
966 	progs = obj->programs;
967 	nr_progs = obj->nr_programs;
968 	nr_syms = symbols->d_size / sizeof(Elf64_Sym);
969 
970 	for (i = 0; i < nr_syms; i++) {
971 		sym = elf_sym_by_idx(obj, i);
972 
973 		if (sym->st_shndx != sec_idx)
974 			continue;
975 		if (ELF64_ST_TYPE(sym->st_info) != STT_FUNC)
976 			continue;
977 
978 		prog_sz = sym->st_size;
979 		sec_off = sym->st_value;
980 
981 		name = elf_sym_str(obj, sym->st_name);
982 		if (!name) {
983 			pr_warn("sec '%s': failed to get symbol name for offset %zu\n",
984 				sec_name, sec_off);
985 			return -LIBBPF_ERRNO__FORMAT;
986 		}
987 
988 		if (sec_off + prog_sz > sec_sz || sec_off + prog_sz < sec_off) {
989 			pr_warn("sec '%s': program at offset %zu crosses section boundary\n",
990 				sec_name, sec_off);
991 			return -LIBBPF_ERRNO__FORMAT;
992 		}
993 
994 		if (sec_idx != obj->efile.text_shndx && ELF64_ST_BIND(sym->st_info) == STB_LOCAL) {
995 			pr_warn("sec '%s': program '%s' is static and not supported\n", sec_name, name);
996 			return -ENOTSUP;
997 		}
998 
999 		pr_debug("sec '%s': found program '%s' at insn offset %zu (%zu bytes), code size %zu insns (%zu bytes)\n",
1000 			 sec_name, name, sec_off / BPF_INSN_SZ, sec_off, prog_sz / BPF_INSN_SZ, prog_sz);
1001 
1002 		progs = libbpf_reallocarray(progs, nr_progs + 1, sizeof(*progs));
1003 		if (!progs) {
1004 			/*
1005 			 * In this case the original obj->programs
1006 			 * is still valid, so don't need special treat for
1007 			 * bpf_close_object().
1008 			 */
1009 			pr_warn("sec '%s': failed to alloc memory for new program '%s'\n",
1010 				sec_name, name);
1011 			return -ENOMEM;
1012 		}
1013 		obj->programs = progs;
1014 
1015 		prog = &progs[nr_progs];
1016 
1017 		err = bpf_object__init_prog(obj, prog, name, sec_idx, sec_name,
1018 					    sec_off, data + sec_off, prog_sz);
1019 		if (err)
1020 			return err;
1021 
1022 		if (ELF64_ST_BIND(sym->st_info) != STB_LOCAL)
1023 			prog->sym_global = true;
1024 
1025 		/* if function is a global/weak symbol, but has restricted
1026 		 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF FUNC
1027 		 * as static to enable more permissive BPF verification mode
1028 		 * with more outside context available to BPF verifier
1029 		 */
1030 		if (prog->sym_global && (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
1031 		    || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL))
1032 			prog->mark_btf_static = true;
1033 
1034 		nr_progs++;
1035 		obj->nr_programs = nr_progs;
1036 	}
1037 
1038 	return 0;
1039 }
1040 
1041 static void bpf_object_bswap_progs(struct bpf_object *obj)
1042 {
1043 	struct bpf_program *prog = obj->programs;
1044 	struct bpf_insn *insn;
1045 	int p, i;
1046 
1047 	for (p = 0; p < obj->nr_programs; p++, prog++) {
1048 		insn = prog->insns;
1049 		for (i = 0; i < prog->insns_cnt; i++, insn++)
1050 			bpf_insn_bswap(insn);
1051 	}
1052 	pr_debug("converted %zu BPF programs to native byte order\n", obj->nr_programs);
1053 }
1054 
1055 static const struct btf_member *
1056 find_member_by_offset(const struct btf_type *t, __u32 bit_offset)
1057 {
1058 	struct btf_member *m;
1059 	int i;
1060 
1061 	for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
1062 		if (btf_member_bit_offset(t, i) == bit_offset)
1063 			return m;
1064 	}
1065 
1066 	return NULL;
1067 }
1068 
1069 static const struct btf_member *
1070 find_member_by_name(const struct btf *btf, const struct btf_type *t,
1071 		    const char *name)
1072 {
1073 	struct btf_member *m;
1074 	int i;
1075 
1076 	for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
1077 		if (!strcmp(btf__name_by_offset(btf, m->name_off), name))
1078 			return m;
1079 	}
1080 
1081 	return NULL;
1082 }
1083 
1084 static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
1085 			    __u16 kind, struct btf **res_btf,
1086 			    struct module_btf **res_mod_btf);
1087 
1088 #define STRUCT_OPS_VALUE_PREFIX "bpf_struct_ops_"
1089 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
1090 				   const char *name, __u32 kind);
1091 
1092 static int
1093 find_struct_ops_kern_types(struct bpf_object *obj, const char *tname_raw,
1094 			   struct module_btf **mod_btf,
1095 			   const struct btf_type **type, __u32 *type_id,
1096 			   const struct btf_type **vtype, __u32 *vtype_id,
1097 			   const struct btf_member **data_member)
1098 {
1099 	const struct btf_type *kern_type, *kern_vtype;
1100 	const struct btf_member *kern_data_member;
1101 	struct btf *btf = NULL;
1102 	__s32 kern_vtype_id, kern_type_id;
1103 	char tname[192], stname[256];
1104 	__u32 i;
1105 
1106 	snprintf(tname, sizeof(tname), "%.*s",
1107 		 (int)bpf_core_essential_name_len(tname_raw), tname_raw);
1108 
1109 	snprintf(stname, sizeof(stname), "%s%s", STRUCT_OPS_VALUE_PREFIX, tname);
1110 
1111 	/* Look for the corresponding "map_value" type that will be used
1112 	 * in map_update(BPF_MAP_TYPE_STRUCT_OPS) first, figure out the btf
1113 	 * and the mod_btf.
1114 	 * For example, find "struct bpf_struct_ops_tcp_congestion_ops".
1115 	 */
1116 	kern_vtype_id = find_ksym_btf_id(obj, stname, BTF_KIND_STRUCT, &btf, mod_btf);
1117 	if (kern_vtype_id < 0) {
1118 		pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n", stname);
1119 		return kern_vtype_id;
1120 	}
1121 	kern_vtype = btf__type_by_id(btf, kern_vtype_id);
1122 
1123 	kern_type_id = btf__find_by_name_kind(btf, tname, BTF_KIND_STRUCT);
1124 	if (kern_type_id < 0) {
1125 		pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n", tname);
1126 		return kern_type_id;
1127 	}
1128 	kern_type = btf__type_by_id(btf, kern_type_id);
1129 
1130 	/* Find "struct tcp_congestion_ops" from
1131 	 * struct bpf_struct_ops_tcp_congestion_ops {
1132 	 *	[ ... ]
1133 	 *	struct tcp_congestion_ops data;
1134 	 * }
1135 	 */
1136 	kern_data_member = btf_members(kern_vtype);
1137 	for (i = 0; i < btf_vlen(kern_vtype); i++, kern_data_member++) {
1138 		if (kern_data_member->type == kern_type_id)
1139 			break;
1140 	}
1141 	if (i == btf_vlen(kern_vtype)) {
1142 		pr_warn("struct_ops init_kern: struct %s data is not found in struct %s\n",
1143 			tname, stname);
1144 		return -EINVAL;
1145 	}
1146 
1147 	*type = kern_type;
1148 	*type_id = kern_type_id;
1149 	*vtype = kern_vtype;
1150 	*vtype_id = kern_vtype_id;
1151 	*data_member = kern_data_member;
1152 
1153 	return 0;
1154 }
1155 
1156 static bool bpf_map__is_struct_ops(const struct bpf_map *map)
1157 {
1158 	return map->def.type == BPF_MAP_TYPE_STRUCT_OPS;
1159 }
1160 
1161 static bool is_valid_st_ops_program(struct bpf_object *obj,
1162 				    const struct bpf_program *prog)
1163 {
1164 	int i;
1165 
1166 	for (i = 0; i < obj->nr_programs; i++) {
1167 		if (&obj->programs[i] == prog)
1168 			return prog->type == BPF_PROG_TYPE_STRUCT_OPS;
1169 	}
1170 
1171 	return false;
1172 }
1173 
1174 /* For each struct_ops program P, referenced from some struct_ops map M,
1175  * enable P.autoload if there are Ms for which M.autocreate is true,
1176  * disable P.autoload if for all Ms M.autocreate is false.
1177  * Don't change P.autoload for programs that are not referenced from any maps.
1178  */
1179 static int bpf_object_adjust_struct_ops_autoload(struct bpf_object *obj)
1180 {
1181 	struct bpf_program *prog, *slot_prog;
1182 	struct bpf_map *map;
1183 	int i, j, k, vlen;
1184 
1185 	for (i = 0; i < obj->nr_programs; ++i) {
1186 		int should_load = false;
1187 		int use_cnt = 0;
1188 
1189 		prog = &obj->programs[i];
1190 		if (prog->type != BPF_PROG_TYPE_STRUCT_OPS)
1191 			continue;
1192 
1193 		for (j = 0; j < obj->nr_maps; ++j) {
1194 			const struct btf_type *type;
1195 
1196 			map = &obj->maps[j];
1197 			if (!bpf_map__is_struct_ops(map))
1198 				continue;
1199 
1200 			type = btf__type_by_id(obj->btf, map->st_ops->type_id);
1201 			vlen = btf_vlen(type);
1202 			for (k = 0; k < vlen; ++k) {
1203 				slot_prog = map->st_ops->progs[k];
1204 				if (prog != slot_prog)
1205 					continue;
1206 
1207 				use_cnt++;
1208 				if (map->autocreate)
1209 					should_load = true;
1210 			}
1211 		}
1212 		if (use_cnt)
1213 			prog->autoload = should_load;
1214 	}
1215 
1216 	return 0;
1217 }
1218 
1219 /* Init the map's fields that depend on kern_btf */
1220 static int bpf_map__init_kern_struct_ops(struct bpf_map *map)
1221 {
1222 	const struct btf_member *member, *kern_member, *kern_data_member;
1223 	const struct btf_type *type, *kern_type, *kern_vtype;
1224 	__u32 i, kern_type_id, kern_vtype_id, kern_data_off;
1225 	struct bpf_object *obj = map->obj;
1226 	const struct btf *btf = obj->btf;
1227 	struct bpf_struct_ops *st_ops;
1228 	const struct btf *kern_btf;
1229 	struct module_btf *mod_btf = NULL;
1230 	void *data, *kern_data;
1231 	const char *tname;
1232 	int err;
1233 
1234 	st_ops = map->st_ops;
1235 	type = btf__type_by_id(btf, st_ops->type_id);
1236 	tname = btf__name_by_offset(btf, type->name_off);
1237 	err = find_struct_ops_kern_types(obj, tname, &mod_btf,
1238 					 &kern_type, &kern_type_id,
1239 					 &kern_vtype, &kern_vtype_id,
1240 					 &kern_data_member);
1241 	if (err)
1242 		return err;
1243 
1244 	kern_btf = mod_btf ? mod_btf->btf : obj->btf_vmlinux;
1245 
1246 	pr_debug("struct_ops init_kern %s: type_id:%u kern_type_id:%u kern_vtype_id:%u\n",
1247 		 map->name, st_ops->type_id, kern_type_id, kern_vtype_id);
1248 
1249 	map->mod_btf_fd = mod_btf ? mod_btf->fd : -1;
1250 	map->def.value_size = kern_vtype->size;
1251 	map->btf_vmlinux_value_type_id = kern_vtype_id;
1252 
1253 	st_ops->kern_vdata = calloc(1, kern_vtype->size);
1254 	if (!st_ops->kern_vdata)
1255 		return -ENOMEM;
1256 
1257 	data = st_ops->data;
1258 	kern_data_off = kern_data_member->offset / 8;
1259 	kern_data = st_ops->kern_vdata + kern_data_off;
1260 
1261 	member = btf_members(type);
1262 	for (i = 0; i < btf_vlen(type); i++, member++) {
1263 		const struct btf_type *mtype, *kern_mtype;
1264 		__u32 mtype_id, kern_mtype_id;
1265 		void *mdata, *kern_mdata;
1266 		struct bpf_program *prog;
1267 		__s64 msize, kern_msize;
1268 		__u32 moff, kern_moff;
1269 		__u32 kern_member_idx;
1270 		const char *mname;
1271 
1272 		mname = btf__name_by_offset(btf, member->name_off);
1273 		if (btf_member_bitfield_size(type, i)) {
1274 			pr_warn("struct_ops init_kern %s: local bitfield %s is not supported\n",
1275 				map->name, mname);
1276 			return -ENOTSUP;
1277 		}
1278 
1279 		moff = member->offset / 8;
1280 		mdata = data + moff;
1281 		msize = btf__resolve_size(btf, member->type);
1282 		if (msize < 0) {
1283 			pr_warn("struct_ops init_kern %s: failed to resolve the size of member %s\n",
1284 				map->name, mname);
1285 			return msize;
1286 		}
1287 
1288 		kern_member = find_member_by_name(kern_btf, kern_type, mname);
1289 		if (!kern_member) {
1290 			if (!libbpf_is_mem_zeroed(mdata, msize)) {
1291 				pr_warn("struct_ops init_kern %s: Cannot find member %s in kernel BTF\n",
1292 					map->name, mname);
1293 				return -ENOTSUP;
1294 			}
1295 
1296 			if (st_ops->progs[i]) {
1297 				/* If we had declaratively set struct_ops callback, we need to
1298 				 * force its autoload to false, because it doesn't have
1299 				 * a chance of succeeding from POV of the current struct_ops map.
1300 				 * If this program is still referenced somewhere else, though,
1301 				 * then bpf_object_adjust_struct_ops_autoload() will update its
1302 				 * autoload accordingly.
1303 				 */
1304 				st_ops->progs[i]->autoload = false;
1305 				st_ops->progs[i] = NULL;
1306 			}
1307 
1308 			/* Skip all-zero/NULL fields if they are not present in the kernel BTF */
1309 			pr_info("struct_ops %s: member %s not found in kernel, skipping it as it's set to zero\n",
1310 				map->name, mname);
1311 			continue;
1312 		}
1313 
1314 		kern_member_idx = kern_member - btf_members(kern_type);
1315 		if (btf_member_bitfield_size(kern_type, kern_member_idx)) {
1316 			pr_warn("struct_ops init_kern %s: bitfield %s is not supported\n",
1317 				map->name, mname);
1318 			return -ENOTSUP;
1319 		}
1320 
1321 		kern_moff = kern_member->offset / 8;
1322 		kern_mdata = kern_data + kern_moff;
1323 
1324 		mtype = skip_mods_and_typedefs(btf, member->type, &mtype_id);
1325 		kern_mtype = skip_mods_and_typedefs(kern_btf, kern_member->type,
1326 						    &kern_mtype_id);
1327 		if (BTF_INFO_KIND(mtype->info) !=
1328 		    BTF_INFO_KIND(kern_mtype->info)) {
1329 			pr_warn("struct_ops init_kern %s: Unmatched member type %s %u != %u(kernel)\n",
1330 				map->name, mname, BTF_INFO_KIND(mtype->info),
1331 				BTF_INFO_KIND(kern_mtype->info));
1332 			return -ENOTSUP;
1333 		}
1334 
1335 		if (btf_is_ptr(mtype)) {
1336 			prog = *(void **)mdata;
1337 			/* just like for !kern_member case above, reset declaratively
1338 			 * set (at compile time) program's autload to false,
1339 			 * if user replaced it with another program or NULL
1340 			 */
1341 			if (st_ops->progs[i] && st_ops->progs[i] != prog)
1342 				st_ops->progs[i]->autoload = false;
1343 
1344 			/* Update the value from the shadow type */
1345 			st_ops->progs[i] = prog;
1346 			if (!prog)
1347 				continue;
1348 
1349 			if (!is_valid_st_ops_program(obj, prog)) {
1350 				pr_warn("struct_ops init_kern %s: member %s is not a struct_ops program\n",
1351 					map->name, mname);
1352 				return -ENOTSUP;
1353 			}
1354 
1355 			kern_mtype = skip_mods_and_typedefs(kern_btf,
1356 							    kern_mtype->type,
1357 							    &kern_mtype_id);
1358 
1359 			/* mtype->type must be a func_proto which was
1360 			 * guaranteed in bpf_object__collect_st_ops_relos(),
1361 			 * so only check kern_mtype for func_proto here.
1362 			 */
1363 			if (!btf_is_func_proto(kern_mtype)) {
1364 				pr_warn("struct_ops init_kern %s: kernel member %s is not a func ptr\n",
1365 					map->name, mname);
1366 				return -ENOTSUP;
1367 			}
1368 
1369 			if (mod_btf)
1370 				prog->attach_btf_obj_fd = mod_btf->fd;
1371 
1372 			/* if we haven't yet processed this BPF program, record proper
1373 			 * attach_btf_id and member_idx
1374 			 */
1375 			if (!prog->attach_btf_id) {
1376 				prog->attach_btf_id = kern_type_id;
1377 				prog->expected_attach_type = kern_member_idx;
1378 			}
1379 
1380 			/* struct_ops BPF prog can be re-used between multiple
1381 			 * .struct_ops & .struct_ops.link as long as it's the
1382 			 * same struct_ops struct definition and the same
1383 			 * function pointer field
1384 			 */
1385 			if (prog->attach_btf_id != kern_type_id) {
1386 				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",
1387 					map->name, mname, prog->name, prog->sec_name, prog->type,
1388 					prog->attach_btf_id, kern_type_id);
1389 				return -EINVAL;
1390 			}
1391 			if (prog->expected_attach_type != kern_member_idx) {
1392 				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",
1393 					map->name, mname, prog->name, prog->sec_name, prog->type,
1394 					prog->expected_attach_type, kern_member_idx);
1395 				return -EINVAL;
1396 			}
1397 
1398 			st_ops->kern_func_off[i] = kern_data_off + kern_moff;
1399 
1400 			pr_debug("struct_ops init_kern %s: func ptr %s is set to prog %s from data(+%u) to kern_data(+%u)\n",
1401 				 map->name, mname, prog->name, moff,
1402 				 kern_moff);
1403 
1404 			continue;
1405 		}
1406 
1407 		kern_msize = btf__resolve_size(kern_btf, kern_mtype_id);
1408 		if (kern_msize < 0 || msize != kern_msize) {
1409 			pr_warn("struct_ops init_kern %s: Error in size of member %s: %zd != %zd(kernel)\n",
1410 				map->name, mname, (ssize_t)msize,
1411 				(ssize_t)kern_msize);
1412 			return -ENOTSUP;
1413 		}
1414 
1415 		pr_debug("struct_ops init_kern %s: copy %s %u bytes from data(+%u) to kern_data(+%u)\n",
1416 			 map->name, mname, (unsigned int)msize,
1417 			 moff, kern_moff);
1418 		memcpy(kern_mdata, mdata, msize);
1419 	}
1420 
1421 	return 0;
1422 }
1423 
1424 static int bpf_object__init_kern_struct_ops_maps(struct bpf_object *obj)
1425 {
1426 	struct bpf_map *map;
1427 	size_t i;
1428 	int err;
1429 
1430 	for (i = 0; i < obj->nr_maps; i++) {
1431 		map = &obj->maps[i];
1432 
1433 		if (!bpf_map__is_struct_ops(map))
1434 			continue;
1435 
1436 		if (!map->autocreate)
1437 			continue;
1438 
1439 		err = bpf_map__init_kern_struct_ops(map);
1440 		if (err)
1441 			return err;
1442 	}
1443 
1444 	return 0;
1445 }
1446 
1447 static int init_struct_ops_maps(struct bpf_object *obj, const char *sec_name,
1448 				int shndx, Elf_Data *data)
1449 {
1450 	const struct btf_type *type, *datasec;
1451 	const struct btf_var_secinfo *vsi;
1452 	struct bpf_struct_ops *st_ops;
1453 	const char *tname, *var_name;
1454 	__s32 type_id, datasec_id;
1455 	const struct btf *btf;
1456 	struct bpf_map *map;
1457 	bool optional;
1458 	__u32 i;
1459 
1460 	if (shndx == -1)
1461 		return 0;
1462 
1463 	btf = obj->btf;
1464 	datasec_id = btf__find_by_name_kind(btf, sec_name,
1465 					    BTF_KIND_DATASEC);
1466 	if (datasec_id < 0) {
1467 		pr_warn("struct_ops init: DATASEC %s not found\n",
1468 			sec_name);
1469 		return -EINVAL;
1470 	}
1471 
1472 	/*
1473 	 * Follow same convention as for programs autoload:
1474 	 * SEC("?.struct_ops") means map is not created by default.
1475 	 */
1476 	optional = sec_name[0] == '?';
1477 	/* from now on forget there was ? in section name */
1478 	sec_name += optional;
1479 
1480 	datasec = btf__type_by_id(btf, datasec_id);
1481 	vsi = btf_var_secinfos(datasec);
1482 	for (i = 0; i < btf_vlen(datasec); i++, vsi++) {
1483 		type = btf__type_by_id(obj->btf, vsi->type);
1484 		var_name = btf__name_by_offset(obj->btf, type->name_off);
1485 
1486 		type_id = btf__resolve_type(obj->btf, vsi->type);
1487 		if (type_id < 0) {
1488 			pr_warn("struct_ops init: Cannot resolve var type_id %u in DATASEC %s\n",
1489 				vsi->type, sec_name);
1490 			return -EINVAL;
1491 		}
1492 
1493 		type = btf__type_by_id(obj->btf, type_id);
1494 		tname = btf__name_by_offset(obj->btf, type->name_off);
1495 		if (!tname[0]) {
1496 			pr_warn("struct_ops init: anonymous type is not supported\n");
1497 			return -ENOTSUP;
1498 		}
1499 		if (!btf_is_struct(type)) {
1500 			pr_warn("struct_ops init: %s is not a struct\n", tname);
1501 			return -EINVAL;
1502 		}
1503 
1504 		map = bpf_object__add_map(obj);
1505 		if (IS_ERR(map))
1506 			return PTR_ERR(map);
1507 
1508 		map->sec_idx = shndx;
1509 		map->sec_offset = vsi->offset;
1510 		map->name = strdup(var_name);
1511 		if (!map->name)
1512 			return -ENOMEM;
1513 		map->btf_value_type_id = type_id;
1514 
1515 		if (optional)
1516 			map->autocreate = false;
1517 
1518 		map->def.type = BPF_MAP_TYPE_STRUCT_OPS;
1519 		map->def.key_size = sizeof(int);
1520 		map->def.value_size = type->size;
1521 		map->def.max_entries = 1;
1522 		map->def.map_flags = strcmp(sec_name, STRUCT_OPS_LINK_SEC) == 0 ? BPF_F_LINK : 0;
1523 		map->autoattach = true;
1524 
1525 		map->st_ops = calloc(1, sizeof(*map->st_ops));
1526 		if (!map->st_ops)
1527 			return -ENOMEM;
1528 		st_ops = map->st_ops;
1529 		st_ops->data = malloc(type->size);
1530 		st_ops->progs = calloc(btf_vlen(type), sizeof(*st_ops->progs));
1531 		st_ops->kern_func_off = malloc(btf_vlen(type) *
1532 					       sizeof(*st_ops->kern_func_off));
1533 		if (!st_ops->data || !st_ops->progs || !st_ops->kern_func_off)
1534 			return -ENOMEM;
1535 
1536 		if (vsi->offset + type->size > data->d_size) {
1537 			pr_warn("struct_ops init: var %s is beyond the end of DATASEC %s\n",
1538 				var_name, sec_name);
1539 			return -EINVAL;
1540 		}
1541 
1542 		memcpy(st_ops->data,
1543 		       data->d_buf + vsi->offset,
1544 		       type->size);
1545 		st_ops->type_id = type_id;
1546 
1547 		pr_debug("struct_ops init: struct %s(type_id=%d) %s found at offset %u\n",
1548 			 tname, type_id, var_name, vsi->offset);
1549 	}
1550 
1551 	return 0;
1552 }
1553 
1554 static int bpf_object_init_struct_ops(struct bpf_object *obj)
1555 {
1556 	const char *sec_name;
1557 	int sec_idx, err;
1558 
1559 	for (sec_idx = 0; sec_idx < obj->efile.sec_cnt; ++sec_idx) {
1560 		struct elf_sec_desc *desc = &obj->efile.secs[sec_idx];
1561 
1562 		if (desc->sec_type != SEC_ST_OPS)
1563 			continue;
1564 
1565 		sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1566 		if (!sec_name)
1567 			return -LIBBPF_ERRNO__FORMAT;
1568 
1569 		err = init_struct_ops_maps(obj, sec_name, sec_idx, desc->data);
1570 		if (err)
1571 			return err;
1572 	}
1573 
1574 	return 0;
1575 }
1576 
1577 static struct bpf_object *bpf_object__new(const char *path,
1578 					  const void *obj_buf,
1579 					  size_t obj_buf_sz,
1580 					  const char *obj_name)
1581 {
1582 	struct bpf_object *obj;
1583 	char *end;
1584 
1585 	obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
1586 	if (!obj) {
1587 		pr_warn("alloc memory failed for %s\n", path);
1588 		return ERR_PTR(-ENOMEM);
1589 	}
1590 
1591 	strcpy(obj->path, path);
1592 	if (obj_name) {
1593 		libbpf_strlcpy(obj->name, obj_name, sizeof(obj->name));
1594 	} else {
1595 		/* Using basename() GNU version which doesn't modify arg. */
1596 		libbpf_strlcpy(obj->name, basename((void *)path), sizeof(obj->name));
1597 		end = strchr(obj->name, '.');
1598 		if (end)
1599 			*end = 0;
1600 	}
1601 
1602 	obj->efile.fd = -1;
1603 	/*
1604 	 * Caller of this function should also call
1605 	 * bpf_object__elf_finish() after data collection to return
1606 	 * obj_buf to user. If not, we should duplicate the buffer to
1607 	 * avoid user freeing them before elf finish.
1608 	 */
1609 	obj->efile.obj_buf = obj_buf;
1610 	obj->efile.obj_buf_sz = obj_buf_sz;
1611 	obj->efile.btf_maps_shndx = -1;
1612 	obj->kconfig_map_idx = -1;
1613 	obj->arena_map_idx = -1;
1614 
1615 	obj->kern_version = get_kernel_version();
1616 	obj->state  = OBJ_OPEN;
1617 
1618 	return obj;
1619 }
1620 
1621 static void bpf_object__elf_finish(struct bpf_object *obj)
1622 {
1623 	if (!obj->efile.elf)
1624 		return;
1625 
1626 	elf_end(obj->efile.elf);
1627 	obj->efile.elf = NULL;
1628 	obj->efile.ehdr = NULL;
1629 	obj->efile.symbols = NULL;
1630 	obj->efile.arena_data = NULL;
1631 
1632 	zfree(&obj->efile.secs);
1633 	obj->efile.sec_cnt = 0;
1634 	zclose(obj->efile.fd);
1635 	obj->efile.obj_buf = NULL;
1636 	obj->efile.obj_buf_sz = 0;
1637 }
1638 
1639 static int bpf_object__elf_init(struct bpf_object *obj)
1640 {
1641 	Elf64_Ehdr *ehdr;
1642 	int err = 0;
1643 	Elf *elf;
1644 
1645 	if (obj->efile.elf) {
1646 		pr_warn("elf: init internal error\n");
1647 		return -LIBBPF_ERRNO__LIBELF;
1648 	}
1649 
1650 	if (obj->efile.obj_buf_sz > 0) {
1651 		/* obj_buf should have been validated by bpf_object__open_mem(). */
1652 		elf = elf_memory((char *)obj->efile.obj_buf, obj->efile.obj_buf_sz);
1653 	} else {
1654 		obj->efile.fd = open(obj->path, O_RDONLY | O_CLOEXEC);
1655 		if (obj->efile.fd < 0) {
1656 			err = -errno;
1657 			pr_warn("elf: failed to open %s: %s\n", obj->path, errstr(err));
1658 			return err;
1659 		}
1660 
1661 		elf = elf_begin(obj->efile.fd, ELF_C_READ_MMAP, NULL);
1662 	}
1663 
1664 	if (!elf) {
1665 		pr_warn("elf: failed to open %s as ELF file: %s\n", obj->path, elf_errmsg(-1));
1666 		err = -LIBBPF_ERRNO__LIBELF;
1667 		goto errout;
1668 	}
1669 
1670 	obj->efile.elf = elf;
1671 
1672 	if (elf_kind(elf) != ELF_K_ELF) {
1673 		err = -LIBBPF_ERRNO__FORMAT;
1674 		pr_warn("elf: '%s' is not a proper ELF object\n", obj->path);
1675 		goto errout;
1676 	}
1677 
1678 	if (gelf_getclass(elf) != ELFCLASS64) {
1679 		err = -LIBBPF_ERRNO__FORMAT;
1680 		pr_warn("elf: '%s' is not a 64-bit ELF object\n", obj->path);
1681 		goto errout;
1682 	}
1683 
1684 	obj->efile.ehdr = ehdr = elf64_getehdr(elf);
1685 	if (!obj->efile.ehdr) {
1686 		pr_warn("elf: failed to get ELF header from %s: %s\n", obj->path, elf_errmsg(-1));
1687 		err = -LIBBPF_ERRNO__FORMAT;
1688 		goto errout;
1689 	}
1690 
1691 	/* Validate ELF object endianness... */
1692 	if (ehdr->e_ident[EI_DATA] != ELFDATA2LSB &&
1693 	    ehdr->e_ident[EI_DATA] != ELFDATA2MSB) {
1694 		err = -LIBBPF_ERRNO__ENDIAN;
1695 		pr_warn("elf: '%s' has unknown byte order\n", obj->path);
1696 		goto errout;
1697 	}
1698 	/* and save after bpf_object_open() frees ELF data */
1699 	obj->byteorder = ehdr->e_ident[EI_DATA];
1700 
1701 	if (elf_getshdrstrndx(elf, &obj->efile.shstrndx)) {
1702 		pr_warn("elf: failed to get section names section index for %s: %s\n",
1703 			obj->path, elf_errmsg(-1));
1704 		err = -LIBBPF_ERRNO__FORMAT;
1705 		goto errout;
1706 	}
1707 
1708 	/* ELF is corrupted/truncated, avoid calling elf_strptr. */
1709 	if (!elf_rawdata(elf_getscn(elf, obj->efile.shstrndx), NULL)) {
1710 		pr_warn("elf: failed to get section names strings from %s: %s\n",
1711 			obj->path, elf_errmsg(-1));
1712 		err = -LIBBPF_ERRNO__FORMAT;
1713 		goto errout;
1714 	}
1715 
1716 	/* Old LLVM set e_machine to EM_NONE */
1717 	if (ehdr->e_type != ET_REL || (ehdr->e_machine && ehdr->e_machine != EM_BPF)) {
1718 		pr_warn("elf: %s is not a valid eBPF object file\n", obj->path);
1719 		err = -LIBBPF_ERRNO__FORMAT;
1720 		goto errout;
1721 	}
1722 
1723 	return 0;
1724 errout:
1725 	bpf_object__elf_finish(obj);
1726 	return err;
1727 }
1728 
1729 static bool is_native_endianness(struct bpf_object *obj)
1730 {
1731 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1732 	return obj->byteorder == ELFDATA2LSB;
1733 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
1734 	return obj->byteorder == ELFDATA2MSB;
1735 #else
1736 # error "Unrecognized __BYTE_ORDER__"
1737 #endif
1738 }
1739 
1740 static int
1741 bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
1742 {
1743 	if (!data) {
1744 		pr_warn("invalid license section in %s\n", obj->path);
1745 		return -LIBBPF_ERRNO__FORMAT;
1746 	}
1747 	/* libbpf_strlcpy() only copies first N - 1 bytes, so size + 1 won't
1748 	 * go over allowed ELF data section buffer
1749 	 */
1750 	libbpf_strlcpy(obj->license, data, min(size + 1, sizeof(obj->license)));
1751 	pr_debug("license of %s is %s\n", obj->path, obj->license);
1752 	return 0;
1753 }
1754 
1755 static int
1756 bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
1757 {
1758 	__u32 kver;
1759 
1760 	if (!data || size != sizeof(kver)) {
1761 		pr_warn("invalid kver section in %s\n", obj->path);
1762 		return -LIBBPF_ERRNO__FORMAT;
1763 	}
1764 	memcpy(&kver, data, sizeof(kver));
1765 	obj->kern_version = kver;
1766 	pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
1767 	return 0;
1768 }
1769 
1770 static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
1771 {
1772 	if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
1773 	    type == BPF_MAP_TYPE_HASH_OF_MAPS)
1774 		return true;
1775 	return false;
1776 }
1777 
1778 static int find_elf_sec_sz(const struct bpf_object *obj, const char *name, __u32 *size)
1779 {
1780 	Elf_Data *data;
1781 	Elf_Scn *scn;
1782 
1783 	if (!name)
1784 		return -EINVAL;
1785 
1786 	scn = elf_sec_by_name(obj, name);
1787 	data = elf_sec_data(obj, scn);
1788 	if (data) {
1789 		*size = data->d_size;
1790 		return 0; /* found it */
1791 	}
1792 
1793 	return -ENOENT;
1794 }
1795 
1796 static Elf64_Sym *find_elf_var_sym(const struct bpf_object *obj, const char *name)
1797 {
1798 	Elf_Data *symbols = obj->efile.symbols;
1799 	const char *sname;
1800 	size_t si;
1801 
1802 	for (si = 0; si < symbols->d_size / sizeof(Elf64_Sym); si++) {
1803 		Elf64_Sym *sym = elf_sym_by_idx(obj, si);
1804 
1805 		if (ELF64_ST_TYPE(sym->st_info) != STT_OBJECT)
1806 			continue;
1807 
1808 		if (ELF64_ST_BIND(sym->st_info) != STB_GLOBAL &&
1809 		    ELF64_ST_BIND(sym->st_info) != STB_WEAK)
1810 			continue;
1811 
1812 		sname = elf_sym_str(obj, sym->st_name);
1813 		if (!sname) {
1814 			pr_warn("failed to get sym name string for var %s\n", name);
1815 			return ERR_PTR(-EIO);
1816 		}
1817 		if (strcmp(name, sname) == 0)
1818 			return sym;
1819 	}
1820 
1821 	return ERR_PTR(-ENOENT);
1822 }
1823 
1824 #ifndef MFD_CLOEXEC
1825 #define MFD_CLOEXEC 0x0001U
1826 #endif
1827 #ifndef MFD_NOEXEC_SEAL
1828 #define MFD_NOEXEC_SEAL 0x0008U
1829 #endif
1830 
1831 static int create_placeholder_fd(void)
1832 {
1833 	unsigned int flags = MFD_CLOEXEC | MFD_NOEXEC_SEAL;
1834 	const char *name = "libbpf-placeholder-fd";
1835 	int fd;
1836 
1837 	fd = ensure_good_fd(sys_memfd_create(name, flags));
1838 	if (fd >= 0)
1839 		return fd;
1840 	else if (errno != EINVAL)
1841 		return -errno;
1842 
1843 	/* Possibly running on kernel without MFD_NOEXEC_SEAL */
1844 	fd = ensure_good_fd(sys_memfd_create(name, flags & ~MFD_NOEXEC_SEAL));
1845 	if (fd < 0)
1846 		return -errno;
1847 	return fd;
1848 }
1849 
1850 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
1851 {
1852 	struct bpf_map *map;
1853 	int err;
1854 
1855 	err = libbpf_ensure_mem((void **)&obj->maps, &obj->maps_cap,
1856 				sizeof(*obj->maps), obj->nr_maps + 1);
1857 	if (err)
1858 		return ERR_PTR(err);
1859 
1860 	map = &obj->maps[obj->nr_maps++];
1861 	map->obj = obj;
1862 	/* Preallocate map FD without actually creating BPF map just yet.
1863 	 * These map FD "placeholders" will be reused later without changing
1864 	 * FD value when map is actually created in the kernel.
1865 	 *
1866 	 * This is useful to be able to perform BPF program relocations
1867 	 * without having to create BPF maps before that step. This allows us
1868 	 * to finalize and load BTF very late in BPF object's loading phase,
1869 	 * right before BPF maps have to be created and BPF programs have to
1870 	 * be loaded. By having these map FD placeholders we can perform all
1871 	 * the sanitizations, relocations, and any other adjustments before we
1872 	 * start creating actual BPF kernel objects (BTF, maps, progs).
1873 	 */
1874 	map->fd = create_placeholder_fd();
1875 	if (map->fd < 0)
1876 		return ERR_PTR(map->fd);
1877 	map->inner_map_fd = -1;
1878 	map->autocreate = true;
1879 
1880 	return map;
1881 }
1882 
1883 static size_t array_map_mmap_sz(unsigned int value_sz, unsigned int max_entries)
1884 {
1885 	const long page_sz = sysconf(_SC_PAGE_SIZE);
1886 	size_t map_sz;
1887 
1888 	map_sz = (size_t)roundup(value_sz, 8) * max_entries;
1889 	map_sz = roundup(map_sz, page_sz);
1890 	return map_sz;
1891 }
1892 
1893 static size_t bpf_map_mmap_sz(const struct bpf_map *map)
1894 {
1895 	const long page_sz = sysconf(_SC_PAGE_SIZE);
1896 
1897 	switch (map->def.type) {
1898 	case BPF_MAP_TYPE_ARRAY:
1899 	case BPF_MAP_TYPE_PERCPU_ARRAY:
1900 		return array_map_mmap_sz(map->def.value_size, map->def.max_entries);
1901 	case BPF_MAP_TYPE_ARENA:
1902 		return page_sz * map->def.max_entries;
1903 	default:
1904 		return 0; /* not supported */
1905 	}
1906 }
1907 
1908 static int bpf_map_mmap_resize(struct bpf_map *map, size_t old_sz, size_t new_sz)
1909 {
1910 	void *mmaped;
1911 
1912 	if (!map->mmaped)
1913 		return -EINVAL;
1914 
1915 	if (old_sz == new_sz)
1916 		return 0;
1917 
1918 	mmaped = mmap(NULL, new_sz, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1919 	if (mmaped == MAP_FAILED)
1920 		return -errno;
1921 
1922 	memcpy(mmaped, map->mmaped, min(old_sz, new_sz));
1923 	munmap(map->mmaped, old_sz);
1924 	map->mmaped = mmaped;
1925 	return 0;
1926 }
1927 
1928 static char *internal_map_name(struct bpf_object *obj, const char *real_name,
1929 			       enum libbpf_map_type type)
1930 {
1931 	char map_name[BPF_OBJ_NAME_LEN], *p;
1932 	int pfx_len, sfx_len = max((size_t)7, strlen(real_name));
1933 
1934 	/* This is one of the more confusing parts of libbpf for various
1935 	 * reasons, some of which are historical. The original idea for naming
1936 	 * internal names was to include as much of BPF object name prefix as
1937 	 * possible, so that it can be distinguished from similar internal
1938 	 * maps of a different BPF object.
1939 	 * As an example, let's say we have bpf_object named 'my_object_name'
1940 	 * and internal map corresponding to '.rodata' ELF section. The final
1941 	 * map name advertised to user and to the kernel will be
1942 	 * 'my_objec.rodata', taking first 8 characters of object name and
1943 	 * entire 7 characters of '.rodata'.
1944 	 * Somewhat confusingly, if internal map ELF section name is shorter
1945 	 * than 7 characters, e.g., '.bss', we still reserve 7 characters
1946 	 * for the suffix, even though we only have 4 actual characters, and
1947 	 * resulting map will be called 'my_objec.bss', not even using all 15
1948 	 * characters allowed by the kernel. Oh well, at least the truncated
1949 	 * object name is somewhat consistent in this case. But if the map
1950 	 * name is '.kconfig', we'll still have entirety of '.kconfig' added
1951 	 * (8 chars) and thus will be left with only first 7 characters of the
1952 	 * object name ('my_obje'). Happy guessing, user, that the final map
1953 	 * name will be "my_obje.kconfig".
1954 	 * Now, with libbpf starting to support arbitrarily named .rodata.*
1955 	 * and .data.* data sections, it's possible that ELF section name is
1956 	 * longer than allowed 15 chars, so we now need to be careful to take
1957 	 * only up to 15 first characters of ELF name, taking no BPF object
1958 	 * name characters at all. So '.rodata.abracadabra' will result in
1959 	 * '.rodata.abracad' kernel and user-visible name.
1960 	 * We need to keep this convoluted logic intact for .data, .bss and
1961 	 * .rodata maps, but for new custom .data.custom and .rodata.custom
1962 	 * maps we use their ELF names as is, not prepending bpf_object name
1963 	 * in front. We still need to truncate them to 15 characters for the
1964 	 * kernel. Full name can be recovered for such maps by using DATASEC
1965 	 * BTF type associated with such map's value type, though.
1966 	 */
1967 	if (sfx_len >= BPF_OBJ_NAME_LEN)
1968 		sfx_len = BPF_OBJ_NAME_LEN - 1;
1969 
1970 	/*
1971 	 * Don't prefix the bpf_object name if this is a custom dot map
1972 	 * (containing two or more dots) or a percpu data map.
1973 	 */
1974 	if (strchr(real_name + 1, '.') != NULL || type == LIBBPF_MAP_PERCPU)
1975 		pfx_len = 0;
1976 	else
1977 		pfx_len = min((size_t)BPF_OBJ_NAME_LEN - sfx_len - 1, strlen(obj->name));
1978 
1979 	snprintf(map_name, sizeof(map_name), "%.*s%.*s", pfx_len, obj->name,
1980 		 sfx_len, real_name);
1981 
1982 	/* sanities map name to characters allowed by kernel */
1983 	for (p = map_name; *p && p < map_name + sizeof(map_name); p++)
1984 		if (!isalnum(*p) && *p != '_' && *p != '.')
1985 			*p = '_';
1986 
1987 	return strdup(map_name);
1988 }
1989 
1990 static int
1991 map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map);
1992 
1993 /* Internal BPF map is mmap()'able only if at least one of corresponding
1994  * DATASEC's VARs are to be exposed through BPF skeleton. I.e., it's a GLOBAL
1995  * variable and it's not marked as __hidden (which turns it into, effectively,
1996  * a STATIC variable).
1997  */
1998 static bool map_is_mmapable(struct bpf_object *obj, struct bpf_map *map)
1999 {
2000 	const struct btf_type *t, *vt;
2001 	struct btf_var_secinfo *vsi;
2002 	int i, n;
2003 
2004 	if (!map->btf_value_type_id)
2005 		return false;
2006 
2007 	/*
2008 	 * The internal PERCPU maps are not mmapable because the underlying
2009 	 * percpu_array maps do not have mmap support.
2010 	 */
2011 	if (map->libbpf_type == LIBBPF_MAP_PERCPU)
2012 		return false;
2013 
2014 	t = btf__type_by_id(obj->btf, map->btf_value_type_id);
2015 	if (!btf_is_datasec(t))
2016 		return false;
2017 
2018 	vsi = btf_var_secinfos(t);
2019 	for (i = 0, n = btf_vlen(t); i < n; i++, vsi++) {
2020 		vt = btf__type_by_id(obj->btf, vsi->type);
2021 		if (!btf_is_var(vt))
2022 			continue;
2023 
2024 		if (btf_var(vt)->linkage != BTF_VAR_STATIC)
2025 			return true;
2026 	}
2027 
2028 	return false;
2029 }
2030 
2031 static int
2032 bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
2033 			      const char *real_name, int sec_idx, void *data, size_t data_sz)
2034 {
2035 	bool is_percpu = type == LIBBPF_MAP_PERCPU;
2036 	struct bpf_map_def *def;
2037 	struct bpf_map *map;
2038 	size_t mmap_sz;
2039 	int err;
2040 
2041 	map = bpf_object__add_map(obj);
2042 	if (IS_ERR(map))
2043 		return PTR_ERR(map);
2044 
2045 	map->libbpf_type = type;
2046 	map->sec_idx = sec_idx;
2047 	map->sec_offset = 0;
2048 	map->real_name = strdup(real_name);
2049 	map->name = internal_map_name(obj, real_name, type);
2050 	if (!map->real_name || !map->name) {
2051 		zfree(&map->real_name);
2052 		zfree(&map->name);
2053 		return -ENOMEM;
2054 	}
2055 
2056 	def = &map->def;
2057 	def->type = is_percpu ? BPF_MAP_TYPE_PERCPU_ARRAY : BPF_MAP_TYPE_ARRAY;
2058 	def->key_size = sizeof(int);
2059 	def->value_size = data_sz;
2060 	def->max_entries = 1;
2061 	def->map_flags = type == LIBBPF_MAP_RODATA || type == LIBBPF_MAP_KCONFIG
2062 		? BPF_F_RDONLY_PROG : 0;
2063 
2064 	/* failures are fine because of maps like .rodata.str1.1 */
2065 	(void) map_fill_btf_type_info(obj, map);
2066 
2067 	if (map_is_mmapable(obj, map))
2068 		def->map_flags |= BPF_F_MMAPABLE;
2069 
2070 	pr_debug("map '%s' (global %sdata): at sec_idx %d, offset %zu, flags %x.\n",
2071 		 map->name, is_percpu ? "percpu " : "", map->sec_idx,
2072 		 map->sec_offset, def->map_flags);
2073 
2074 	mmap_sz = bpf_map_mmap_sz(map);
2075 	map->mmaped = mmap(NULL, mmap_sz, PROT_READ | PROT_WRITE,
2076 			   MAP_SHARED | MAP_ANONYMOUS, -1, 0);
2077 	if (map->mmaped == MAP_FAILED) {
2078 		err = -errno;
2079 		map->mmaped = NULL;
2080 		pr_warn("failed to alloc map '%s' content buffer: %s\n", map->name, errstr(err));
2081 		zfree(&map->real_name);
2082 		zfree(&map->name);
2083 		return err;
2084 	}
2085 
2086 	if (data)
2087 		memcpy(map->mmaped, data, data_sz);
2088 
2089 	pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
2090 	return 0;
2091 }
2092 
2093 static int bpf_object__init_global_data_maps(struct bpf_object *obj)
2094 {
2095 	struct elf_sec_desc *sec_desc;
2096 	const char *sec_name;
2097 	int err = 0, sec_idx;
2098 
2099 	/*
2100 	 * Populate obj->maps with libbpf internal maps.
2101 	 */
2102 	for (sec_idx = 1; sec_idx < obj->efile.sec_cnt; sec_idx++) {
2103 		sec_desc = &obj->efile.secs[sec_idx];
2104 
2105 		/* Skip recognized sections with size 0. */
2106 		if (!sec_desc->data || sec_desc->data->d_size == 0)
2107 			continue;
2108 
2109 		switch (sec_desc->sec_type) {
2110 		case SEC_DATA:
2111 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
2112 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
2113 							    sec_name, sec_idx,
2114 							    sec_desc->data->d_buf,
2115 							    sec_desc->data->d_size);
2116 			break;
2117 		case SEC_RODATA:
2118 			obj->has_rodata = true;
2119 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
2120 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
2121 							    sec_name, sec_idx,
2122 							    sec_desc->data->d_buf,
2123 							    sec_desc->data->d_size);
2124 			break;
2125 		case SEC_BSS:
2126 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
2127 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
2128 							    sec_name, sec_idx,
2129 							    NULL,
2130 							    sec_desc->data->d_size);
2131 			break;
2132 		case SEC_PERCPU:
2133 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
2134 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_PERCPU,
2135 							    sec_name, sec_idx,
2136 							    sec_desc->data->d_buf,
2137 							    sec_desc->data->d_size);
2138 			break;
2139 		default:
2140 			/* skip */
2141 			break;
2142 		}
2143 		if (err)
2144 			return err;
2145 	}
2146 	return 0;
2147 }
2148 
2149 
2150 static struct extern_desc *find_extern_by_name(const struct bpf_object *obj,
2151 					       const void *name)
2152 {
2153 	int i;
2154 
2155 	for (i = 0; i < obj->nr_extern; i++) {
2156 		if (strcmp(obj->externs[i].name, name) == 0)
2157 			return &obj->externs[i];
2158 	}
2159 	return NULL;
2160 }
2161 
2162 static struct extern_desc *find_extern_by_name_with_len(const struct bpf_object *obj,
2163 							const void *name, int len)
2164 {
2165 	const char *ext_name;
2166 	int i;
2167 
2168 	for (i = 0; i < obj->nr_extern; i++) {
2169 		ext_name = obj->externs[i].name;
2170 		if (strlen(ext_name) == len && strncmp(ext_name, name, len) == 0)
2171 			return &obj->externs[i];
2172 	}
2173 	return NULL;
2174 }
2175 
2176 static int set_kcfg_value_tri(struct extern_desc *ext, void *ext_val,
2177 			      char value)
2178 {
2179 	switch (ext->kcfg.type) {
2180 	case KCFG_BOOL:
2181 		if (value == 'm') {
2182 			pr_warn("extern (kcfg) '%s': value '%c' implies tristate or char type\n",
2183 				ext->name, value);
2184 			return -EINVAL;
2185 		}
2186 		*(bool *)ext_val = value == 'y' ? true : false;
2187 		break;
2188 	case KCFG_TRISTATE:
2189 		if (value == 'y')
2190 			*(enum libbpf_tristate *)ext_val = TRI_YES;
2191 		else if (value == 'm')
2192 			*(enum libbpf_tristate *)ext_val = TRI_MODULE;
2193 		else /* value == 'n' */
2194 			*(enum libbpf_tristate *)ext_val = TRI_NO;
2195 		break;
2196 	case KCFG_CHAR:
2197 		*(char *)ext_val = value;
2198 		break;
2199 	case KCFG_UNKNOWN:
2200 	case KCFG_INT:
2201 	case KCFG_CHAR_ARR:
2202 	default:
2203 		pr_warn("extern (kcfg) '%s': value '%c' implies bool, tristate, or char type\n",
2204 			ext->name, value);
2205 		return -EINVAL;
2206 	}
2207 	ext->is_set = true;
2208 	return 0;
2209 }
2210 
2211 static int set_kcfg_value_str(struct extern_desc *ext, char *ext_val,
2212 			      const char *value)
2213 {
2214 	size_t len;
2215 
2216 	if (ext->kcfg.type != KCFG_CHAR_ARR) {
2217 		pr_warn("extern (kcfg) '%s': value '%s' implies char array type\n",
2218 			ext->name, value);
2219 		return -EINVAL;
2220 	}
2221 
2222 	len = strlen(value);
2223 	if (len < 2 || value[len - 1] != '"') {
2224 		pr_warn("extern (kcfg) '%s': invalid string config '%s'\n",
2225 			ext->name, value);
2226 		return -EINVAL;
2227 	}
2228 
2229 	/* strip quotes */
2230 	len -= 2;
2231 	if (len >= ext->kcfg.sz) {
2232 		pr_warn("extern (kcfg) '%s': long string '%s' of (%zu bytes) truncated to %d bytes\n",
2233 			ext->name, value, len, ext->kcfg.sz - 1);
2234 		len = ext->kcfg.sz - 1;
2235 	}
2236 	memcpy(ext_val, value + 1, len);
2237 	ext_val[len] = '\0';
2238 	ext->is_set = true;
2239 	return 0;
2240 }
2241 
2242 static int parse_u64(const char *value, __u64 *res)
2243 {
2244 	char *value_end;
2245 	int err;
2246 
2247 	errno = 0;
2248 	*res = strtoull(value, &value_end, 0);
2249 	if (errno) {
2250 		err = -errno;
2251 		pr_warn("failed to parse '%s': %s\n", value, errstr(err));
2252 		return err;
2253 	}
2254 	if (*value_end) {
2255 		pr_warn("failed to parse '%s' as integer completely\n", value);
2256 		return -EINVAL;
2257 	}
2258 	return 0;
2259 }
2260 
2261 static bool is_kcfg_value_in_range(const struct extern_desc *ext, __u64 v)
2262 {
2263 	int bit_sz = ext->kcfg.sz * 8;
2264 
2265 	if (ext->kcfg.sz == 8)
2266 		return true;
2267 
2268 	/* Validate that value stored in u64 fits in integer of `ext->sz`
2269 	 * bytes size without any loss of information. If the target integer
2270 	 * is signed, we rely on the following limits of integer type of
2271 	 * Y bits and subsequent transformation:
2272 	 *
2273 	 *     -2^(Y-1) <= X           <= 2^(Y-1) - 1
2274 	 *            0 <= X + 2^(Y-1) <= 2^Y - 1
2275 	 *            0 <= X + 2^(Y-1) <  2^Y
2276 	 *
2277 	 *  For unsigned target integer, check that all the (64 - Y) bits are
2278 	 *  zero.
2279 	 */
2280 	if (ext->kcfg.is_signed)
2281 		return v + (1ULL << (bit_sz - 1)) < (1ULL << bit_sz);
2282 	else
2283 		return (v >> bit_sz) == 0;
2284 }
2285 
2286 static int set_kcfg_value_num(struct extern_desc *ext, void *ext_val,
2287 			      __u64 value)
2288 {
2289 	if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR &&
2290 	    ext->kcfg.type != KCFG_BOOL) {
2291 		pr_warn("extern (kcfg) '%s': value '%llu' implies integer, char, or boolean type\n",
2292 			ext->name, (unsigned long long)value);
2293 		return -EINVAL;
2294 	}
2295 	if (ext->kcfg.type == KCFG_BOOL && value > 1) {
2296 		pr_warn("extern (kcfg) '%s': value '%llu' isn't boolean compatible\n",
2297 			ext->name, (unsigned long long)value);
2298 		return -EINVAL;
2299 
2300 	}
2301 	if (!is_kcfg_value_in_range(ext, value)) {
2302 		pr_warn("extern (kcfg) '%s': value '%llu' doesn't fit in %d bytes\n",
2303 			ext->name, (unsigned long long)value, ext->kcfg.sz);
2304 		return -ERANGE;
2305 	}
2306 	switch (ext->kcfg.sz) {
2307 	case 1:
2308 		*(__u8 *)ext_val = value;
2309 		break;
2310 	case 2:
2311 		*(__u16 *)ext_val = value;
2312 		break;
2313 	case 4:
2314 		*(__u32 *)ext_val = value;
2315 		break;
2316 	case 8:
2317 		*(__u64 *)ext_val = value;
2318 		break;
2319 	default:
2320 		return -EINVAL;
2321 	}
2322 	ext->is_set = true;
2323 	return 0;
2324 }
2325 
2326 static int bpf_object__process_kconfig_line(struct bpf_object *obj,
2327 					    char *buf, void *data)
2328 {
2329 	struct extern_desc *ext;
2330 	char *sep, *value;
2331 	int len, err = 0;
2332 	void *ext_val;
2333 	__u64 num;
2334 
2335 	if (!str_has_pfx(buf, "CONFIG_"))
2336 		return 0;
2337 
2338 	sep = strchr(buf, '=');
2339 	if (!sep) {
2340 		pr_warn("failed to parse '%s': no separator\n", buf);
2341 		return -EINVAL;
2342 	}
2343 
2344 	/* Trim ending '\n' */
2345 	len = strlen(buf);
2346 	if (buf[len - 1] == '\n')
2347 		buf[len - 1] = '\0';
2348 	/* Split on '=' and ensure that a value is present. */
2349 	*sep = '\0';
2350 	if (!sep[1]) {
2351 		*sep = '=';
2352 		pr_warn("failed to parse '%s': no value\n", buf);
2353 		return -EINVAL;
2354 	}
2355 
2356 	ext = find_extern_by_name(obj, buf);
2357 	if (!ext || ext->is_set)
2358 		return 0;
2359 
2360 	ext_val = data + ext->kcfg.data_off;
2361 	value = sep + 1;
2362 
2363 	switch (*value) {
2364 	case 'y': case 'n': case 'm':
2365 		err = set_kcfg_value_tri(ext, ext_val, *value);
2366 		break;
2367 	case '"':
2368 		err = set_kcfg_value_str(ext, ext_val, value);
2369 		break;
2370 	default:
2371 		/* assume integer */
2372 		err = parse_u64(value, &num);
2373 		if (err) {
2374 			pr_warn("extern (kcfg) '%s': value '%s' isn't a valid integer\n", ext->name, value);
2375 			return err;
2376 		}
2377 		if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR) {
2378 			pr_warn("extern (kcfg) '%s': value '%s' implies integer type\n", ext->name, value);
2379 			return -EINVAL;
2380 		}
2381 		err = set_kcfg_value_num(ext, ext_val, num);
2382 		break;
2383 	}
2384 	if (err)
2385 		return err;
2386 	pr_debug("extern (kcfg) '%s': set to %s\n", ext->name, value);
2387 	return 0;
2388 }
2389 
2390 static int bpf_object__read_kconfig_file(struct bpf_object *obj, void *data)
2391 {
2392 	char buf[PATH_MAX];
2393 	struct utsname uts;
2394 	int len, err = 0;
2395 	gzFile file;
2396 
2397 	uname(&uts);
2398 	len = snprintf(buf, PATH_MAX, "/boot/config-%s", uts.release);
2399 	if (len < 0)
2400 		return -EINVAL;
2401 	else if (len >= PATH_MAX)
2402 		return -ENAMETOOLONG;
2403 
2404 	/* gzopen also accepts uncompressed files. */
2405 	file = gzopen(buf, "re");
2406 	if (!file)
2407 		file = gzopen("/proc/config.gz", "re");
2408 
2409 	if (!file) {
2410 		pr_warn("failed to open system Kconfig\n");
2411 		return -ENOENT;
2412 	}
2413 
2414 	while (gzgets(file, buf, sizeof(buf))) {
2415 		err = bpf_object__process_kconfig_line(obj, buf, data);
2416 		if (err) {
2417 			pr_warn("error parsing system Kconfig line '%s': %s\n",
2418 				buf, errstr(err));
2419 			goto out;
2420 		}
2421 	}
2422 
2423 out:
2424 	gzclose(file);
2425 	return err;
2426 }
2427 
2428 static int bpf_object__read_kconfig_mem(struct bpf_object *obj,
2429 					const char *config, void *data)
2430 {
2431 	char buf[PATH_MAX];
2432 	int err = 0;
2433 	FILE *file;
2434 
2435 	file = fmemopen((void *)config, strlen(config), "r");
2436 	if (!file) {
2437 		err = -errno;
2438 		pr_warn("failed to open in-memory Kconfig: %s\n", errstr(err));
2439 		return err;
2440 	}
2441 
2442 	while (fgets(buf, sizeof(buf), file)) {
2443 		err = bpf_object__process_kconfig_line(obj, buf, data);
2444 		if (err) {
2445 			pr_warn("error parsing in-memory Kconfig line '%s': %s\n",
2446 				buf, errstr(err));
2447 			break;
2448 		}
2449 	}
2450 
2451 	fclose(file);
2452 	return err;
2453 }
2454 
2455 static int bpf_object__init_kconfig_map(struct bpf_object *obj)
2456 {
2457 	struct extern_desc *last_ext = NULL, *ext;
2458 	size_t map_sz;
2459 	int i, err;
2460 
2461 	for (i = 0; i < obj->nr_extern; i++) {
2462 		ext = &obj->externs[i];
2463 		if (ext->type == EXT_KCFG)
2464 			last_ext = ext;
2465 	}
2466 
2467 	if (!last_ext)
2468 		return 0;
2469 
2470 	map_sz = last_ext->kcfg.data_off + last_ext->kcfg.sz;
2471 	err = bpf_object__init_internal_map(obj, LIBBPF_MAP_KCONFIG,
2472 					    ".kconfig", obj->efile.symbols_shndx,
2473 					    NULL, map_sz);
2474 	if (err)
2475 		return err;
2476 
2477 	obj->kconfig_map_idx = obj->nr_maps - 1;
2478 
2479 	return 0;
2480 }
2481 
2482 const struct btf_type *
2483 skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id)
2484 {
2485 	const struct btf_type *t = btf__type_by_id(btf, id);
2486 
2487 	if (res_id)
2488 		*res_id = id;
2489 
2490 	while (btf_is_mod(t) || btf_is_typedef(t)) {
2491 		if (res_id)
2492 			*res_id = t->type;
2493 		t = btf__type_by_id(btf, t->type);
2494 	}
2495 
2496 	return t;
2497 }
2498 
2499 static const struct btf_type *
2500 resolve_func_ptr(const struct btf *btf, __u32 id, __u32 *res_id)
2501 {
2502 	const struct btf_type *t;
2503 
2504 	t = skip_mods_and_typedefs(btf, id, NULL);
2505 	if (!btf_is_ptr(t))
2506 		return NULL;
2507 
2508 	t = skip_mods_and_typedefs(btf, t->type, res_id);
2509 
2510 	return btf_is_func_proto(t) ? t : NULL;
2511 }
2512 
2513 static const char *__btf_kind_str(__u16 kind)
2514 {
2515 	switch (kind) {
2516 	case BTF_KIND_UNKN: return "void";
2517 	case BTF_KIND_INT: return "int";
2518 	case BTF_KIND_PTR: return "ptr";
2519 	case BTF_KIND_ARRAY: return "array";
2520 	case BTF_KIND_STRUCT: return "struct";
2521 	case BTF_KIND_UNION: return "union";
2522 	case BTF_KIND_ENUM: return "enum";
2523 	case BTF_KIND_FWD: return "fwd";
2524 	case BTF_KIND_TYPEDEF: return "typedef";
2525 	case BTF_KIND_VOLATILE: return "volatile";
2526 	case BTF_KIND_CONST: return "const";
2527 	case BTF_KIND_RESTRICT: return "restrict";
2528 	case BTF_KIND_FUNC: return "func";
2529 	case BTF_KIND_FUNC_PROTO: return "func_proto";
2530 	case BTF_KIND_VAR: return "var";
2531 	case BTF_KIND_DATASEC: return "datasec";
2532 	case BTF_KIND_FLOAT: return "float";
2533 	case BTF_KIND_DECL_TAG: return "decl_tag";
2534 	case BTF_KIND_TYPE_TAG: return "type_tag";
2535 	case BTF_KIND_ENUM64: return "enum64";
2536 	case BTF_KIND_LOC_PARAM: return "loc_param";
2537 	case BTF_KIND_LOC_PROTO: return "loc_proto";
2538 	case BTF_KIND_LOCSEC: return "locsec";
2539 	default: return "unknown";
2540 	}
2541 }
2542 
2543 const char *btf_kind_str(const struct btf_type *t)
2544 {
2545 	return __btf_kind_str(btf_kind(t));
2546 }
2547 
2548 /*
2549  * Fetch integer attribute of BTF map definition. Such attributes are
2550  * represented using a pointer to an array, in which dimensionality of array
2551  * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
2552  * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
2553  * type definition, while using only sizeof(void *) space in ELF data section.
2554  */
2555 static bool get_map_field_int(const char *map_name, const struct btf *btf,
2556 			      const struct btf_member *m, __u32 *res)
2557 {
2558 	const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
2559 	const char *name = btf__name_by_offset(btf, m->name_off);
2560 	const struct btf_array *arr_info;
2561 	const struct btf_type *arr_t;
2562 
2563 	if (!btf_is_ptr(t)) {
2564 		pr_warn("map '%s': attr '%s': expected PTR, got %s.\n",
2565 			map_name, name, btf_kind_str(t));
2566 		return false;
2567 	}
2568 
2569 	arr_t = btf__type_by_id(btf, t->type);
2570 	if (!arr_t) {
2571 		pr_warn("map '%s': attr '%s': type [%u] not found.\n",
2572 			map_name, name, t->type);
2573 		return false;
2574 	}
2575 	if (!btf_is_array(arr_t)) {
2576 		pr_warn("map '%s': attr '%s': expected ARRAY, got %s.\n",
2577 			map_name, name, btf_kind_str(arr_t));
2578 		return false;
2579 	}
2580 	arr_info = btf_array(arr_t);
2581 	*res = arr_info->nelems;
2582 	return true;
2583 }
2584 
2585 static bool get_map_field_long(const char *map_name, const struct btf *btf,
2586 			       const struct btf_member *m, __u64 *res)
2587 {
2588 	const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
2589 	const char *name = btf__name_by_offset(btf, m->name_off);
2590 
2591 	if (btf_is_ptr(t)) {
2592 		__u32 res32;
2593 		bool ret;
2594 
2595 		ret = get_map_field_int(map_name, btf, m, &res32);
2596 		if (ret)
2597 			*res = (__u64)res32;
2598 		return ret;
2599 	}
2600 
2601 	if (!btf_is_enum(t) && !btf_is_enum64(t)) {
2602 		pr_warn("map '%s': attr '%s': expected ENUM or ENUM64, got %s.\n",
2603 			map_name, name, btf_kind_str(t));
2604 		return false;
2605 	}
2606 
2607 	if (btf_vlen(t) != 1) {
2608 		pr_warn("map '%s': attr '%s': invalid __ulong\n",
2609 			map_name, name);
2610 		return false;
2611 	}
2612 
2613 	if (btf_is_enum(t)) {
2614 		const struct btf_enum *e = btf_enum(t);
2615 
2616 		*res = e->val;
2617 	} else {
2618 		const struct btf_enum64 *e = btf_enum64(t);
2619 
2620 		*res = btf_enum64_value(e);
2621 	}
2622 	return true;
2623 }
2624 
2625 static int pathname_concat(char *buf, size_t buf_sz, const char *path, const char *name)
2626 {
2627 	int len;
2628 
2629 	len = snprintf(buf, buf_sz, "%s/%s", path, name);
2630 	if (len < 0)
2631 		return -EINVAL;
2632 	if (len >= buf_sz)
2633 		return -ENAMETOOLONG;
2634 
2635 	return 0;
2636 }
2637 
2638 static int build_map_pin_path(struct bpf_map *map, const char *path)
2639 {
2640 	char buf[PATH_MAX];
2641 	int err;
2642 
2643 	if (!path)
2644 		path = BPF_FS_DEFAULT_PATH;
2645 
2646 	err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
2647 	if (err)
2648 		return err;
2649 
2650 	return bpf_map__set_pin_path(map, buf);
2651 }
2652 
2653 /* should match definition in bpf_helpers.h */
2654 enum libbpf_pin_type {
2655 	LIBBPF_PIN_NONE,
2656 	/* PIN_BY_NAME: pin maps by name (in /sys/fs/bpf by default) */
2657 	LIBBPF_PIN_BY_NAME,
2658 };
2659 
2660 int parse_btf_map_def(const char *map_name, struct btf *btf,
2661 		      const struct btf_type *def_t, bool strict,
2662 		      struct btf_map_def *map_def, struct btf_map_def *inner_def)
2663 {
2664 	const struct btf_type *t;
2665 	const struct btf_member *m;
2666 	bool is_inner = inner_def == NULL;
2667 	int vlen, i;
2668 
2669 	vlen = btf_vlen(def_t);
2670 	m = btf_members(def_t);
2671 	for (i = 0; i < vlen; i++, m++) {
2672 		const char *name = btf__name_by_offset(btf, m->name_off);
2673 
2674 		if (!name) {
2675 			pr_warn("map '%s': invalid field #%d.\n", map_name, i);
2676 			return -EINVAL;
2677 		}
2678 		if (strcmp(name, "type") == 0) {
2679 			if (!get_map_field_int(map_name, btf, m, &map_def->map_type))
2680 				return -EINVAL;
2681 			map_def->parts |= MAP_DEF_MAP_TYPE;
2682 		} else if (strcmp(name, "max_entries") == 0) {
2683 			if (!get_map_field_int(map_name, btf, m, &map_def->max_entries))
2684 				return -EINVAL;
2685 			map_def->parts |= MAP_DEF_MAX_ENTRIES;
2686 		} else if (strcmp(name, "map_flags") == 0) {
2687 			if (!get_map_field_int(map_name, btf, m, &map_def->map_flags))
2688 				return -EINVAL;
2689 			map_def->parts |= MAP_DEF_MAP_FLAGS;
2690 		} else if (strcmp(name, "numa_node") == 0) {
2691 			if (!get_map_field_int(map_name, btf, m, &map_def->numa_node))
2692 				return -EINVAL;
2693 			map_def->parts |= MAP_DEF_NUMA_NODE;
2694 		} else if (strcmp(name, "key_size") == 0) {
2695 			__u32 sz;
2696 
2697 			if (!get_map_field_int(map_name, btf, m, &sz))
2698 				return -EINVAL;
2699 			if (map_def->key_size && map_def->key_size != sz) {
2700 				pr_warn("map '%s': conflicting key size %u != %u.\n",
2701 					map_name, map_def->key_size, sz);
2702 				return -EINVAL;
2703 			}
2704 			map_def->key_size = sz;
2705 			map_def->parts |= MAP_DEF_KEY_SIZE;
2706 		} else if (strcmp(name, "key") == 0) {
2707 			__s64 sz;
2708 
2709 			t = btf__type_by_id(btf, m->type);
2710 			if (!t) {
2711 				pr_warn("map '%s': key type [%u] not found.\n",
2712 					map_name, m->type);
2713 				return -EINVAL;
2714 			}
2715 			if (!btf_is_ptr(t)) {
2716 				pr_warn("map '%s': key spec is not PTR: %s.\n",
2717 					map_name, btf_kind_str(t));
2718 				return -EINVAL;
2719 			}
2720 			sz = btf__resolve_size(btf, t->type);
2721 			if (sz < 0) {
2722 				pr_warn("map '%s': can't determine key size for type [%u]: %zd.\n",
2723 					map_name, t->type, (ssize_t)sz);
2724 				return sz;
2725 			}
2726 			if (map_def->key_size && map_def->key_size != sz) {
2727 				pr_warn("map '%s': conflicting key size %u != %zd.\n",
2728 					map_name, map_def->key_size, (ssize_t)sz);
2729 				return -EINVAL;
2730 			}
2731 			map_def->key_size = sz;
2732 			map_def->key_type_id = t->type;
2733 			map_def->parts |= MAP_DEF_KEY_SIZE | MAP_DEF_KEY_TYPE;
2734 		} else if (strcmp(name, "value_size") == 0) {
2735 			__u32 sz;
2736 
2737 			if (!get_map_field_int(map_name, btf, m, &sz))
2738 				return -EINVAL;
2739 			if (map_def->value_size && map_def->value_size != sz) {
2740 				pr_warn("map '%s': conflicting value size %u != %u.\n",
2741 					map_name, map_def->value_size, sz);
2742 				return -EINVAL;
2743 			}
2744 			map_def->value_size = sz;
2745 			map_def->parts |= MAP_DEF_VALUE_SIZE;
2746 		} else if (strcmp(name, "value") == 0) {
2747 			__s64 sz;
2748 
2749 			t = btf__type_by_id(btf, m->type);
2750 			if (!t) {
2751 				pr_warn("map '%s': value type [%u] not found.\n",
2752 					map_name, m->type);
2753 				return -EINVAL;
2754 			}
2755 			if (!btf_is_ptr(t)) {
2756 				pr_warn("map '%s': value spec is not PTR: %s.\n",
2757 					map_name, btf_kind_str(t));
2758 				return -EINVAL;
2759 			}
2760 			sz = btf__resolve_size(btf, t->type);
2761 			if (sz < 0) {
2762 				pr_warn("map '%s': can't determine value size for type [%u]: %zd.\n",
2763 					map_name, t->type, (ssize_t)sz);
2764 				return sz;
2765 			}
2766 			if (map_def->value_size && map_def->value_size != sz) {
2767 				pr_warn("map '%s': conflicting value size %u != %zd.\n",
2768 					map_name, map_def->value_size, (ssize_t)sz);
2769 				return -EINVAL;
2770 			}
2771 			map_def->value_size = sz;
2772 			map_def->value_type_id = t->type;
2773 			map_def->parts |= MAP_DEF_VALUE_SIZE | MAP_DEF_VALUE_TYPE;
2774 		}
2775 		else if (strcmp(name, "values") == 0) {
2776 			bool is_map_in_map = bpf_map_type__is_map_in_map(map_def->map_type);
2777 			bool is_prog_array = map_def->map_type == BPF_MAP_TYPE_PROG_ARRAY;
2778 			const char *desc = is_map_in_map ? "map-in-map inner" : "prog-array value";
2779 			char inner_map_name[128];
2780 			int err;
2781 
2782 			if (is_inner) {
2783 				pr_warn("map '%s': multi-level inner maps not supported.\n",
2784 					map_name);
2785 				return -ENOTSUP;
2786 			}
2787 			if (i != vlen - 1) {
2788 				pr_warn("map '%s': '%s' member should be last.\n",
2789 					map_name, name);
2790 				return -EINVAL;
2791 			}
2792 			if (!is_map_in_map && !is_prog_array) {
2793 				pr_warn("map '%s': should be map-in-map or prog-array.\n",
2794 					map_name);
2795 				return -ENOTSUP;
2796 			}
2797 			if (map_def->value_size && map_def->value_size != 4) {
2798 				pr_warn("map '%s': conflicting value size %u != 4.\n",
2799 					map_name, map_def->value_size);
2800 				return -EINVAL;
2801 			}
2802 			map_def->value_size = 4;
2803 			t = btf__type_by_id(btf, m->type);
2804 			if (!t) {
2805 				pr_warn("map '%s': %s type [%u] not found.\n",
2806 					map_name, desc, m->type);
2807 				return -EINVAL;
2808 			}
2809 			if (!btf_is_array(t) || btf_array(t)->nelems) {
2810 				pr_warn("map '%s': %s spec is not a zero-sized array.\n",
2811 					map_name, desc);
2812 				return -EINVAL;
2813 			}
2814 			t = skip_mods_and_typedefs(btf, btf_array(t)->type, NULL);
2815 			if (!btf_is_ptr(t)) {
2816 				pr_warn("map '%s': %s def is of unexpected kind %s.\n",
2817 					map_name, desc, btf_kind_str(t));
2818 				return -EINVAL;
2819 			}
2820 			t = skip_mods_and_typedefs(btf, t->type, NULL);
2821 			if (is_prog_array) {
2822 				if (!btf_is_func_proto(t)) {
2823 					pr_warn("map '%s': prog-array value def is of unexpected kind %s.\n",
2824 						map_name, btf_kind_str(t));
2825 					return -EINVAL;
2826 				}
2827 				continue;
2828 			}
2829 			if (!btf_is_struct(t)) {
2830 				pr_warn("map '%s': map-in-map inner def is of unexpected kind %s.\n",
2831 					map_name, btf_kind_str(t));
2832 				return -EINVAL;
2833 			}
2834 
2835 			snprintf(inner_map_name, sizeof(inner_map_name), "%s.inner", map_name);
2836 			err = parse_btf_map_def(inner_map_name, btf, t, strict, inner_def, NULL);
2837 			if (err)
2838 				return err;
2839 
2840 			map_def->parts |= MAP_DEF_INNER_MAP;
2841 		} else if (strcmp(name, "pinning") == 0) {
2842 			__u32 val;
2843 
2844 			if (is_inner) {
2845 				pr_warn("map '%s': inner def can't be pinned.\n", map_name);
2846 				return -EINVAL;
2847 			}
2848 			if (!get_map_field_int(map_name, btf, m, &val))
2849 				return -EINVAL;
2850 			if (val != LIBBPF_PIN_NONE && val != LIBBPF_PIN_BY_NAME) {
2851 				pr_warn("map '%s': invalid pinning value %u.\n",
2852 					map_name, val);
2853 				return -EINVAL;
2854 			}
2855 			map_def->pinning = val;
2856 			map_def->parts |= MAP_DEF_PINNING;
2857 		} else if (strcmp(name, "map_extra") == 0) {
2858 			__u64 map_extra;
2859 
2860 			if (!get_map_field_long(map_name, btf, m, &map_extra))
2861 				return -EINVAL;
2862 			map_def->map_extra = map_extra;
2863 			map_def->parts |= MAP_DEF_MAP_EXTRA;
2864 		} else {
2865 			if (strict) {
2866 				pr_warn("map '%s': unknown field '%s'.\n", map_name, name);
2867 				return -ENOTSUP;
2868 			}
2869 			pr_debug("map '%s': ignoring unknown field '%s'.\n", map_name, name);
2870 		}
2871 	}
2872 
2873 	if (map_def->map_type == BPF_MAP_TYPE_UNSPEC) {
2874 		pr_warn("map '%s': map type isn't specified.\n", map_name);
2875 		return -EINVAL;
2876 	}
2877 
2878 	return 0;
2879 }
2880 
2881 static size_t adjust_ringbuf_sz(size_t sz)
2882 {
2883 	__u32 page_sz = sysconf(_SC_PAGE_SIZE);
2884 	__u32 mul;
2885 
2886 	/* if user forgot to set any size, make sure they see error */
2887 	if (sz == 0)
2888 		return 0;
2889 	/* Kernel expects BPF_MAP_TYPE_RINGBUF's max_entries to be
2890 	 * a power-of-2 multiple of kernel's page size. If user diligently
2891 	 * satisfied these conditions, pass the size through.
2892 	 */
2893 	if ((sz % page_sz) == 0 && is_pow_of_2(sz / page_sz))
2894 		return sz;
2895 
2896 	/* Otherwise find closest (page_sz * power_of_2) product bigger than
2897 	 * user-set size to satisfy both user size request and kernel
2898 	 * requirements and substitute correct max_entries for map creation.
2899 	 */
2900 	for (mul = 1; mul <= UINT_MAX / page_sz; mul <<= 1) {
2901 		if (mul * page_sz > sz)
2902 			return mul * page_sz;
2903 	}
2904 
2905 	/* if it's impossible to satisfy the conditions (i.e., user size is
2906 	 * very close to UINT_MAX but is not a power-of-2 multiple of
2907 	 * page_size) then just return original size and let kernel reject it
2908 	 */
2909 	return sz;
2910 }
2911 
2912 static bool map_is_ringbuf(const struct bpf_map *map)
2913 {
2914 	return map->def.type == BPF_MAP_TYPE_RINGBUF ||
2915 	       map->def.type == BPF_MAP_TYPE_USER_RINGBUF;
2916 }
2917 
2918 static void fill_map_from_def(struct bpf_map *map, const struct btf_map_def *def)
2919 {
2920 	map->def.type = def->map_type;
2921 	map->def.key_size = def->key_size;
2922 	map->def.value_size = def->value_size;
2923 	map->def.max_entries = def->max_entries;
2924 	map->def.map_flags = def->map_flags;
2925 	map->map_extra = def->map_extra;
2926 
2927 	map->numa_node = def->numa_node;
2928 	map->btf_key_type_id = def->key_type_id;
2929 	map->btf_value_type_id = def->value_type_id;
2930 
2931 	/* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
2932 	if (map_is_ringbuf(map))
2933 		map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
2934 
2935 	if (def->parts & MAP_DEF_MAP_TYPE)
2936 		pr_debug("map '%s': found type = %u.\n", map->name, def->map_type);
2937 
2938 	if (def->parts & MAP_DEF_KEY_TYPE)
2939 		pr_debug("map '%s': found key [%u], sz = %u.\n",
2940 			 map->name, def->key_type_id, def->key_size);
2941 	else if (def->parts & MAP_DEF_KEY_SIZE)
2942 		pr_debug("map '%s': found key_size = %u.\n", map->name, def->key_size);
2943 
2944 	if (def->parts & MAP_DEF_VALUE_TYPE)
2945 		pr_debug("map '%s': found value [%u], sz = %u.\n",
2946 			 map->name, def->value_type_id, def->value_size);
2947 	else if (def->parts & MAP_DEF_VALUE_SIZE)
2948 		pr_debug("map '%s': found value_size = %u.\n", map->name, def->value_size);
2949 
2950 	if (def->parts & MAP_DEF_MAX_ENTRIES)
2951 		pr_debug("map '%s': found max_entries = %u.\n", map->name, def->max_entries);
2952 	if (def->parts & MAP_DEF_MAP_FLAGS)
2953 		pr_debug("map '%s': found map_flags = 0x%x.\n", map->name, def->map_flags);
2954 	if (def->parts & MAP_DEF_MAP_EXTRA)
2955 		pr_debug("map '%s': found map_extra = 0x%llx.\n", map->name,
2956 			 (unsigned long long)def->map_extra);
2957 	if (def->parts & MAP_DEF_PINNING)
2958 		pr_debug("map '%s': found pinning = %u.\n", map->name, def->pinning);
2959 	if (def->parts & MAP_DEF_NUMA_NODE)
2960 		pr_debug("map '%s': found numa_node = %u.\n", map->name, def->numa_node);
2961 
2962 	if (def->parts & MAP_DEF_INNER_MAP)
2963 		pr_debug("map '%s': found inner map definition.\n", map->name);
2964 }
2965 
2966 static const char *btf_var_linkage_str(__u32 linkage)
2967 {
2968 	switch (linkage) {
2969 	case BTF_VAR_STATIC: return "static";
2970 	case BTF_VAR_GLOBAL_ALLOCATED: return "global";
2971 	case BTF_VAR_GLOBAL_EXTERN: return "extern";
2972 	default: return "unknown";
2973 	}
2974 }
2975 
2976 static int bpf_object__init_user_btf_map(struct bpf_object *obj,
2977 					 const struct btf_type *sec,
2978 					 int var_idx, int sec_idx,
2979 					 const Elf_Data *data, bool strict,
2980 					 const char *pin_root_path)
2981 {
2982 	struct btf_map_def map_def = {}, inner_def = {};
2983 	const struct btf_type *var, *def;
2984 	const struct btf_var_secinfo *vi;
2985 	const struct btf_var *var_extra;
2986 	const char *map_name;
2987 	struct bpf_map *map;
2988 	int err;
2989 
2990 	vi = btf_var_secinfos(sec) + var_idx;
2991 	var = btf__type_by_id(obj->btf, vi->type);
2992 	var_extra = btf_var(var);
2993 	map_name = btf__name_by_offset(obj->btf, var->name_off);
2994 
2995 	if (str_is_empty(map_name)) {
2996 		pr_warn("map #%d: empty name.\n", var_idx);
2997 		return -EINVAL;
2998 	}
2999 	if ((__u64)vi->offset + vi->size > data->d_size) {
3000 		pr_warn("map '%s' BTF data is corrupted.\n", map_name);
3001 		return -EINVAL;
3002 	}
3003 	if (!btf_is_var(var)) {
3004 		pr_warn("map '%s': unexpected var kind %s.\n",
3005 			map_name, btf_kind_str(var));
3006 		return -EINVAL;
3007 	}
3008 	if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED) {
3009 		pr_warn("map '%s': unsupported map linkage %s.\n",
3010 			map_name, btf_var_linkage_str(var_extra->linkage));
3011 		return -EOPNOTSUPP;
3012 	}
3013 
3014 	def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
3015 	if (!btf_is_struct(def)) {
3016 		pr_warn("map '%s': unexpected def kind %s.\n",
3017 			map_name, btf_kind_str(var));
3018 		return -EINVAL;
3019 	}
3020 	if (def->size > vi->size) {
3021 		pr_warn("map '%s': invalid def size.\n", map_name);
3022 		return -EINVAL;
3023 	}
3024 
3025 	map = bpf_object__add_map(obj);
3026 	if (IS_ERR(map))
3027 		return PTR_ERR(map);
3028 	map->name = strdup(map_name);
3029 	if (!map->name) {
3030 		pr_warn("map '%s': failed to alloc map name.\n", map_name);
3031 		return -ENOMEM;
3032 	}
3033 	map->libbpf_type = LIBBPF_MAP_UNSPEC;
3034 	map->def.type = BPF_MAP_TYPE_UNSPEC;
3035 	map->sec_idx = sec_idx;
3036 	map->sec_offset = vi->offset;
3037 	map->btf_var_idx = var_idx;
3038 	pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
3039 		 map_name, map->sec_idx, map->sec_offset);
3040 
3041 	err = parse_btf_map_def(map->name, obj->btf, def, strict, &map_def, &inner_def);
3042 	if (err)
3043 		return err;
3044 
3045 	fill_map_from_def(map, &map_def);
3046 
3047 	if (map_def.pinning == LIBBPF_PIN_BY_NAME) {
3048 		err = build_map_pin_path(map, pin_root_path);
3049 		if (err) {
3050 			pr_warn("map '%s': couldn't build pin path.\n", map->name);
3051 			return err;
3052 		}
3053 	}
3054 
3055 	if (map_def.parts & MAP_DEF_INNER_MAP) {
3056 		map->inner_map = calloc(1, sizeof(*map->inner_map));
3057 		if (!map->inner_map)
3058 			return -ENOMEM;
3059 		map->inner_map->fd = create_placeholder_fd();
3060 		if (map->inner_map->fd < 0)
3061 			return map->inner_map->fd;
3062 		map->inner_map->sec_idx = sec_idx;
3063 		map->inner_map->name = malloc(strlen(map_name) + sizeof(".inner") + 1);
3064 		if (!map->inner_map->name)
3065 			return -ENOMEM;
3066 		sprintf(map->inner_map->name, "%s.inner", map_name);
3067 
3068 		fill_map_from_def(map->inner_map, &inner_def);
3069 	}
3070 
3071 	err = map_fill_btf_type_info(obj, map);
3072 	if (err)
3073 		return err;
3074 
3075 	return 0;
3076 }
3077 
3078 static int init_arena_map_data(struct bpf_object *obj, struct bpf_map *map,
3079 			       void *data, size_t data_sz)
3080 {
3081 	obj->arena_data = malloc(data_sz);
3082 	if (!obj->arena_data)
3083 		return -ENOMEM;
3084 	memcpy(obj->arena_data, data, data_sz);
3085 	obj->arena_data_sz = data_sz;
3086 
3087 	/* make bpf_map__init_value() work for ARENA maps */
3088 	map->mmaped = obj->arena_data;
3089 
3090 	return 0;
3091 }
3092 
3093 static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict,
3094 					  const char *pin_root_path)
3095 {
3096 	const struct btf_type *sec = NULL;
3097 	int nr_types, i, vlen, err;
3098 	const struct btf_type *t;
3099 	const char *name;
3100 	Elf_Data *data;
3101 	Elf_Scn *scn;
3102 
3103 	if (obj->efile.btf_maps_shndx < 0)
3104 		return 0;
3105 
3106 	scn = elf_sec_by_idx(obj, obj->efile.btf_maps_shndx);
3107 	data = elf_sec_data(obj, scn);
3108 	if (!data) {
3109 		pr_warn("elf: failed to get %s map definitions for %s\n",
3110 			MAPS_ELF_SEC, obj->path);
3111 		return -EINVAL;
3112 	}
3113 
3114 	nr_types = btf__type_cnt(obj->btf);
3115 	for (i = 1; i < nr_types; i++) {
3116 		t = btf__type_by_id(obj->btf, i);
3117 		if (!btf_is_datasec(t))
3118 			continue;
3119 		name = btf__name_by_offset(obj->btf, t->name_off);
3120 		if (strcmp(name, MAPS_ELF_SEC) == 0) {
3121 			sec = t;
3122 			obj->efile.btf_maps_sec_btf_id = i;
3123 			break;
3124 		}
3125 	}
3126 
3127 	if (!sec) {
3128 		pr_warn("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
3129 		return -ENOENT;
3130 	}
3131 
3132 	vlen = btf_vlen(sec);
3133 	for (i = 0; i < vlen; i++) {
3134 		err = bpf_object__init_user_btf_map(obj, sec, i,
3135 						    obj->efile.btf_maps_shndx,
3136 						    data, strict,
3137 						    pin_root_path);
3138 		if (err)
3139 			return err;
3140 	}
3141 
3142 	for (i = 0; i < obj->nr_maps; i++) {
3143 		struct bpf_map *map = &obj->maps[i];
3144 
3145 		if (map->def.type != BPF_MAP_TYPE_ARENA)
3146 			continue;
3147 
3148 		if (obj->arena_map_idx >= 0) {
3149 			pr_warn("map '%s': only single ARENA map is supported (map '%s' is also ARENA)\n",
3150 				map->name, obj->maps[obj->arena_map_idx].name);
3151 			return -EINVAL;
3152 		}
3153 		obj->arena_map_idx = i;
3154 
3155 		if (obj->efile.arena_data) {
3156 			err = init_arena_map_data(obj, map, obj->efile.arena_data->d_buf,
3157 						  obj->efile.arena_data->d_size);
3158 			if (err)
3159 				return err;
3160 		}
3161 	}
3162 	if (obj->efile.arena_data && obj->arena_map_idx < 0) {
3163 		pr_warn("elf: sec '%s': to use global __arena variables the ARENA map should be explicitly declared in SEC(\".maps\")\n",
3164 			ARENA_SEC);
3165 		return -ENOENT;
3166 	}
3167 
3168 	return 0;
3169 }
3170 
3171 static int bpf_object__init_maps(struct bpf_object *obj,
3172 				 const struct bpf_object_open_opts *opts)
3173 {
3174 	const char *pin_root_path;
3175 	bool strict;
3176 	int err = 0;
3177 
3178 	strict = !OPTS_GET(opts, relaxed_maps, false);
3179 	pin_root_path = OPTS_GET(opts, pin_root_path, NULL);
3180 
3181 	err = bpf_object__init_user_btf_maps(obj, strict, pin_root_path);
3182 	err = err ?: bpf_object__init_global_data_maps(obj);
3183 	err = err ?: bpf_object__init_kconfig_map(obj);
3184 	err = err ?: bpf_object_init_struct_ops(obj);
3185 
3186 	return err;
3187 }
3188 
3189 static bool section_have_execinstr(struct bpf_object *obj, int idx)
3190 {
3191 	Elf64_Shdr *sh;
3192 
3193 	sh = elf_sec_hdr(obj, elf_sec_by_idx(obj, idx));
3194 	if (!sh)
3195 		return false;
3196 
3197 	return sh->sh_flags & SHF_EXECINSTR;
3198 }
3199 
3200 static bool starts_with_qmark(const char *s)
3201 {
3202 	return s && s[0] == '?';
3203 }
3204 
3205 static bool btf_needs_sanitization(struct bpf_object *obj)
3206 {
3207 	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
3208 	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
3209 	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
3210 	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
3211 	bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
3212 	bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
3213 	bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
3214 	bool has_qmark_datasec = kernel_supports(obj, FEAT_BTF_QMARK_DATASEC);
3215 	bool has_layout = kernel_supports(obj, FEAT_BTF_LAYOUT);
3216 
3217 	return !has_func || !has_datasec || !has_func_global || !has_float ||
3218 	       !has_decl_tag || !has_type_tag || !has_enum64 || !has_qmark_datasec ||
3219 	       !has_layout;
3220 }
3221 
3222 struct btf *bpf_object__sanitize_btf(struct bpf_object *obj, struct btf *orig_btf)
3223 {
3224 	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
3225 	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
3226 	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
3227 	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
3228 	bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
3229 	bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
3230 	bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
3231 	bool has_qmark_datasec = kernel_supports(obj, FEAT_BTF_QMARK_DATASEC);
3232 	bool has_layout = kernel_supports(obj, FEAT_BTF_LAYOUT);
3233 	int enum64_placeholder_id = 0;
3234 	const struct btf_header *hdr;
3235 	struct btf *btf = NULL;
3236 	const void *raw_data;
3237 	struct btf_type *t;
3238 	int i, j, vlen;
3239 	__u32 sz;
3240 	int err;
3241 
3242 	/* clone BTF to sanitize a copy and leave the original intact */
3243 	raw_data = btf__raw_data(orig_btf, &sz);
3244 	if (!raw_data)
3245 		return ERR_PTR(-ENOMEM);
3246 	/* btf_header() gives us endian-safe header info */
3247 	hdr = btf_header(orig_btf);
3248 
3249 	if (!has_layout && hdr->hdr_len >= sizeof(struct btf_header) &&
3250 	    (hdr->layout_len != 0 || hdr->layout_off != 0)) {
3251 		const struct btf_header *old_hdr = raw_data;
3252 		struct btf_header *new_hdr;
3253 		void *new_raw_data;
3254 		__u32 new_str_off;
3255 
3256 		/*
3257 		 * Need to rewrite BTF to exclude layout information and
3258 		 * move string section to immediately after types.
3259 		 */
3260 		new_raw_data = malloc(sz);
3261 		if (!new_raw_data)
3262 			return ERR_PTR(-ENOMEM);
3263 
3264 		memcpy(new_raw_data, raw_data, sz);
3265 		new_hdr = new_raw_data;
3266 		new_hdr->layout_off = 0;
3267 		new_hdr->layout_len = 0;
3268 		new_str_off = hdr->type_off + hdr->type_len;
3269 		/* Handle swapped endian case */
3270 		if (old_hdr->magic != hdr->magic)
3271 			new_hdr->str_off = bswap_32(new_str_off);
3272 		else
3273 			new_hdr->str_off = new_str_off;
3274 
3275 		memmove(new_raw_data + hdr->hdr_len + new_str_off,
3276 			new_raw_data + hdr->hdr_len + hdr->str_off,
3277 			hdr->str_len);
3278 		sz = hdr->hdr_len + hdr->type_off + hdr->type_len + hdr->str_len;
3279 		btf = btf__new(new_raw_data, sz);
3280 		free(new_raw_data);
3281 	} else {
3282 		btf = btf__new(raw_data, sz);
3283 	}
3284 	err = libbpf_get_error(btf);
3285 	if (err)
3286 		return ERR_PTR(err);
3287 
3288 	/* enforce 8-byte pointers for BPF-targeted BTFs */
3289 	btf__set_pointer_size(btf, 8);
3290 
3291 	for (i = 1; i < btf__type_cnt(btf); i++) {
3292 		t = (struct btf_type *)btf__type_by_id(btf, i);
3293 
3294 		if ((!has_datasec && btf_is_var(t)) || (!has_decl_tag && btf_is_decl_tag(t))) {
3295 			/* replace VAR/DECL_TAG with INT */
3296 			t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
3297 			/*
3298 			 * using size = 1 is the safest choice, 4 will be too
3299 			 * big and cause kernel BTF validation failure if
3300 			 * original variable took less than 4 bytes
3301 			 */
3302 			t->size = 1;
3303 			*(int *)(t + 1) = BTF_INT_ENC(0, 0, 8);
3304 		} else if (!has_datasec && btf_is_datasec(t)) {
3305 			/* replace DATASEC with STRUCT */
3306 			const struct btf_var_secinfo *v = btf_var_secinfos(t);
3307 			struct btf_member *m = btf_members(t);
3308 			struct btf_type *vt;
3309 			char *name;
3310 
3311 			name = (char *)btf__name_by_offset(btf, t->name_off);
3312 			while (*name) {
3313 				if (*name == '.' || *name == '?')
3314 					*name = '_';
3315 				name++;
3316 			}
3317 
3318 			vlen = btf_vlen(t);
3319 			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
3320 			for (j = 0; j < vlen; j++, v++, m++) {
3321 				/* order of field assignments is important */
3322 				m->offset = v->offset * 8;
3323 				m->type = v->type;
3324 				/* preserve variable name as member name */
3325 				vt = (void *)btf__type_by_id(btf, v->type);
3326 				m->name_off = vt->name_off;
3327 			}
3328 		} else if (!has_qmark_datasec && btf_is_datasec(t) &&
3329 			   starts_with_qmark(btf__name_by_offset(btf, t->name_off))) {
3330 			/* replace '?' prefix with '_' for DATASEC names */
3331 			char *name;
3332 
3333 			name = (char *)btf__name_by_offset(btf, t->name_off);
3334 			if (name[0] == '?')
3335 				name[0] = '_';
3336 		} else if (!has_func && btf_is_func_proto(t)) {
3337 			/* replace FUNC_PROTO with ENUM */
3338 			vlen = btf_vlen(t);
3339 			t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
3340 			t->size = sizeof(__u32); /* kernel enforced */
3341 		} else if (!has_func && btf_is_func(t)) {
3342 			/* replace FUNC with TYPEDEF */
3343 			t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
3344 		} else if (!has_func_global && btf_is_func(t)) {
3345 			/* replace BTF_FUNC_GLOBAL with BTF_FUNC_STATIC */
3346 			t->info = BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0);
3347 		} else if (!has_float && btf_is_float(t)) {
3348 			/* replace FLOAT with an equally-sized empty STRUCT;
3349 			 * since C compilers do not accept e.g. "float" as a
3350 			 * valid struct name, make it anonymous
3351 			 */
3352 			t->name_off = 0;
3353 			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, 0);
3354 		} else if (!has_type_tag && btf_is_type_tag(t)) {
3355 			/* replace TYPE_TAG with a CONST */
3356 			t->name_off = 0;
3357 			t->info = BTF_INFO_ENC(BTF_KIND_CONST, 0, 0);
3358 		} else if (!has_enum64 && btf_is_enum(t)) {
3359 			/* clear the kflag */
3360 			t->info = btf_type_info(btf_kind(t), btf_vlen(t), false);
3361 		} else if (!has_enum64 && btf_is_enum64(t)) {
3362 			/* replace ENUM64 with a union */
3363 			struct btf_member *m;
3364 
3365 			if (enum64_placeholder_id == 0) {
3366 				enum64_placeholder_id = btf__add_int(btf, "enum64_placeholder", 1, 0);
3367 				if (enum64_placeholder_id < 0) {
3368 					btf__free(btf);
3369 					return ERR_PTR(enum64_placeholder_id);
3370 				}
3371 				t = (struct btf_type *)btf__type_by_id(btf, i);
3372 			}
3373 
3374 			m = btf_members(t);
3375 			vlen = btf_vlen(t);
3376 			t->info = BTF_INFO_ENC(BTF_KIND_UNION, 0, vlen);
3377 			for (j = 0; j < vlen; j++, m++) {
3378 				m->type = enum64_placeholder_id;
3379 				m->offset = 0;
3380 			}
3381 		}
3382 	}
3383 
3384 	return btf;
3385 }
3386 
3387 static bool libbpf_needs_btf(const struct bpf_object *obj)
3388 {
3389 	return obj->efile.btf_maps_shndx >= 0 ||
3390 	       obj->efile.has_st_ops ||
3391 	       obj->nr_extern > 0;
3392 }
3393 
3394 static bool kernel_needs_btf(const struct bpf_object *obj)
3395 {
3396 	return obj->efile.has_st_ops;
3397 }
3398 
3399 static int bpf_object__init_btf(struct bpf_object *obj,
3400 				Elf_Data *btf_data,
3401 				Elf_Data *btf_ext_data)
3402 {
3403 	int err = -ENOENT;
3404 
3405 	if (btf_data) {
3406 		obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
3407 		err = libbpf_get_error(obj->btf);
3408 		if (err) {
3409 			obj->btf = NULL;
3410 			pr_warn("Error loading ELF section %s: %s.\n", BTF_ELF_SEC, errstr(err));
3411 			goto out;
3412 		}
3413 		/* enforce 8-byte pointers for BPF-targeted BTFs */
3414 		btf__set_pointer_size(obj->btf, 8);
3415 	}
3416 	if (btf_ext_data) {
3417 		struct btf_ext_info *ext_segs[3];
3418 		int seg_num, sec_num;
3419 
3420 		if (!obj->btf) {
3421 			pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
3422 				 BTF_EXT_ELF_SEC, BTF_ELF_SEC);
3423 			goto out;
3424 		}
3425 		obj->btf_ext = btf_ext__new(btf_ext_data->d_buf, btf_ext_data->d_size);
3426 		err = libbpf_get_error(obj->btf_ext);
3427 		if (err) {
3428 			pr_warn("Error loading ELF section %s: %s. Ignored and continue.\n",
3429 				BTF_EXT_ELF_SEC, errstr(err));
3430 			obj->btf_ext = NULL;
3431 			goto out;
3432 		}
3433 
3434 		/* setup .BTF.ext to ELF section mapping */
3435 		ext_segs[0] = &obj->btf_ext->func_info;
3436 		ext_segs[1] = &obj->btf_ext->line_info;
3437 		ext_segs[2] = &obj->btf_ext->core_relo_info;
3438 		for (seg_num = 0; seg_num < ARRAY_SIZE(ext_segs); seg_num++) {
3439 			struct btf_ext_info *seg = ext_segs[seg_num];
3440 			const struct btf_ext_info_sec *sec;
3441 			const char *sec_name;
3442 			Elf_Scn *scn;
3443 
3444 			if (seg->sec_cnt == 0)
3445 				continue;
3446 
3447 			seg->sec_idxs = calloc(seg->sec_cnt, sizeof(*seg->sec_idxs));
3448 			if (!seg->sec_idxs) {
3449 				err = -ENOMEM;
3450 				goto out;
3451 			}
3452 
3453 			sec_num = 0;
3454 			for_each_btf_ext_sec(seg, sec) {
3455 				/* preventively increment index to avoid doing
3456 				 * this before every continue below
3457 				 */
3458 				sec_num++;
3459 
3460 				sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
3461 				if (str_is_empty(sec_name))
3462 					continue;
3463 				scn = elf_sec_by_name(obj, sec_name);
3464 				if (!scn)
3465 					continue;
3466 
3467 				seg->sec_idxs[sec_num - 1] = elf_ndxscn(scn);
3468 			}
3469 		}
3470 	}
3471 out:
3472 	if (err && libbpf_needs_btf(obj)) {
3473 		pr_warn("BTF is required, but is missing or corrupted.\n");
3474 		return err;
3475 	}
3476 	return 0;
3477 }
3478 
3479 static int compare_vsi_off(const void *_a, const void *_b)
3480 {
3481 	const struct btf_var_secinfo *a = _a;
3482 	const struct btf_var_secinfo *b = _b;
3483 
3484 	return a->offset - b->offset;
3485 }
3486 
3487 static int btf_fixup_datasec(struct bpf_object *obj, struct btf *btf,
3488 			     struct btf_type *t)
3489 {
3490 	__u32 size = 0, i, vars = btf_vlen(t);
3491 	const char *sec_name = btf__name_by_offset(btf, t->name_off);
3492 	struct btf_var_secinfo *vsi;
3493 	bool fixup_offsets = false;
3494 	int err;
3495 
3496 	if (!sec_name) {
3497 		pr_debug("No name found in string section for DATASEC kind.\n");
3498 		return -ENOENT;
3499 	}
3500 
3501 	/* Extern-backing datasecs (.ksyms, .kconfig) have their size and
3502 	 * variable offsets set at the previous step. Further, not every
3503 	 * extern BTF VAR has corresponding ELF symbol preserved, so we skip
3504 	 * all fixups altogether for such sections and go straight to sorting
3505 	 * VARs within their DATASEC.
3506 	 */
3507 	if (strcmp(sec_name, KCONFIG_SEC) == 0 || strcmp(sec_name, KSYMS_SEC) == 0)
3508 		goto sort_vars;
3509 
3510 	/* Clang leaves DATASEC size and VAR offsets as zeroes, so we need to
3511 	 * fix this up. But BPF static linker already fixes this up and fills
3512 	 * all the sizes and offsets during static linking. So this step has
3513 	 * to be optional. But the STV_HIDDEN handling is non-optional for any
3514 	 * non-extern DATASEC, so the variable fixup loop below handles both
3515 	 * functions at the same time, paying the cost of BTF VAR <-> ELF
3516 	 * symbol matching just once.
3517 	 */
3518 	if (t->size == 0) {
3519 		err = find_elf_sec_sz(obj, sec_name, &size);
3520 		if (err || !size) {
3521 			pr_debug("sec '%s': failed to determine size from ELF: size %u, err %s\n",
3522 				 sec_name, size, errstr(err));
3523 			return -ENOENT;
3524 		}
3525 
3526 		t->size = size;
3527 		fixup_offsets = true;
3528 	}
3529 
3530 	for (i = 0, vsi = btf_var_secinfos(t); i < vars; i++, vsi++) {
3531 		const struct btf_type *t_var;
3532 		struct btf_var *var;
3533 		const char *var_name;
3534 		Elf64_Sym *sym;
3535 
3536 		t_var = btf__type_by_id(btf, vsi->type);
3537 		if (!t_var || !btf_is_var(t_var)) {
3538 			pr_debug("sec '%s': unexpected non-VAR type found\n", sec_name);
3539 			return -EINVAL;
3540 		}
3541 
3542 		var = btf_var(t_var);
3543 		if (var->linkage == BTF_VAR_STATIC || var->linkage == BTF_VAR_GLOBAL_EXTERN)
3544 			continue;
3545 
3546 		var_name = btf__name_by_offset(btf, t_var->name_off);
3547 		if (!var_name) {
3548 			pr_debug("sec '%s': failed to find name of DATASEC's member #%u\n",
3549 				 sec_name, i);
3550 			return -ENOENT;
3551 		}
3552 
3553 		sym = find_elf_var_sym(obj, var_name);
3554 		if (IS_ERR(sym)) {
3555 			pr_debug("sec '%s': failed to find ELF symbol for VAR '%s'\n",
3556 				 sec_name, var_name);
3557 			return -ENOENT;
3558 		}
3559 
3560 		if (fixup_offsets)
3561 			vsi->offset = sym->st_value;
3562 
3563 		/* if variable is a global/weak symbol, but has restricted
3564 		 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF VAR
3565 		 * as static. This follows similar logic for functions (BPF
3566 		 * subprogs) and influences libbpf's further decisions about
3567 		 * whether to make global data BPF array maps as
3568 		 * BPF_F_MMAPABLE.
3569 		 */
3570 		if (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
3571 		    || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL)
3572 			var->linkage = BTF_VAR_STATIC;
3573 	}
3574 
3575 sort_vars:
3576 	qsort(btf_var_secinfos(t), vars, sizeof(*vsi), compare_vsi_off);
3577 	return 0;
3578 }
3579 
3580 static int bpf_object_fixup_btf(struct bpf_object *obj)
3581 {
3582 	int i, n, err = 0;
3583 
3584 	if (!obj->btf)
3585 		return 0;
3586 
3587 	n = btf__type_cnt(obj->btf);
3588 	for (i = 1; i < n; i++) {
3589 		struct btf_type *t = btf_type_by_id(obj->btf, i);
3590 
3591 		/* Loader needs to fix up some of the things compiler
3592 		 * couldn't get its hands on while emitting BTF. This
3593 		 * is section size and global variable offset. We use
3594 		 * the info from the ELF itself for this purpose.
3595 		 */
3596 		if (btf_is_datasec(t)) {
3597 			err = btf_fixup_datasec(obj, obj->btf, t);
3598 			if (err)
3599 				return err;
3600 		}
3601 	}
3602 
3603 	return 0;
3604 }
3605 
3606 static bool prog_needs_vmlinux_btf(struct bpf_program *prog)
3607 {
3608 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
3609 	    prog->type == BPF_PROG_TYPE_LSM)
3610 		return true;
3611 
3612 	/* BPF_PROG_TYPE_TRACING programs which do not attach to other programs
3613 	 * also need vmlinux BTF
3614 	 */
3615 	if (prog->type == BPF_PROG_TYPE_TRACING && !prog->attach_prog_fd)
3616 		return true;
3617 
3618 	return false;
3619 }
3620 
3621 static bool map_needs_vmlinux_btf(struct bpf_map *map)
3622 {
3623 	return bpf_map__is_struct_ops(map);
3624 }
3625 
3626 static bool obj_needs_vmlinux_btf(const struct bpf_object *obj)
3627 {
3628 	struct bpf_program *prog;
3629 	struct bpf_map *map;
3630 	int i;
3631 
3632 	/* CO-RE relocations need kernel BTF, only when btf_custom_path
3633 	 * is not specified
3634 	 */
3635 	if (obj->btf_ext && obj->btf_ext->core_relo_info.len && !obj->btf_custom_path)
3636 		return true;
3637 
3638 	/* Support for typed ksyms needs kernel BTF */
3639 	for (i = 0; i < obj->nr_extern; i++) {
3640 		const struct extern_desc *ext;
3641 
3642 		ext = &obj->externs[i];
3643 		if (ext->type == EXT_KSYM && ext->ksym.type_id)
3644 			return true;
3645 	}
3646 
3647 	bpf_object__for_each_program(prog, obj) {
3648 		if (!prog->autoload)
3649 			continue;
3650 		if (prog_needs_vmlinux_btf(prog))
3651 			return true;
3652 	}
3653 
3654 	bpf_object__for_each_map(map, obj) {
3655 		if (map_needs_vmlinux_btf(map))
3656 			return true;
3657 	}
3658 
3659 	return false;
3660 }
3661 
3662 static int bpf_object__load_vmlinux_btf(struct bpf_object *obj, bool force)
3663 {
3664 	int err;
3665 
3666 	/* btf_vmlinux could be loaded earlier */
3667 	if (obj->btf_vmlinux || obj->gen_loader)
3668 		return 0;
3669 
3670 	if (!force && !obj_needs_vmlinux_btf(obj))
3671 		return 0;
3672 
3673 	obj->btf_vmlinux = btf__load_vmlinux_btf();
3674 	err = libbpf_get_error(obj->btf_vmlinux);
3675 	if (err) {
3676 		pr_warn("Error loading vmlinux BTF: %s\n", errstr(err));
3677 		obj->btf_vmlinux = NULL;
3678 		return err;
3679 	}
3680 	return 0;
3681 }
3682 
3683 static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
3684 {
3685 	struct btf *kern_btf = obj->btf;
3686 	bool btf_mandatory, sanitize;
3687 	int i, err = 0;
3688 
3689 	if (!obj->btf)
3690 		return 0;
3691 
3692 	if (!kernel_supports(obj, FEAT_BTF)) {
3693 		if (kernel_needs_btf(obj)) {
3694 			err = -EOPNOTSUPP;
3695 			goto report;
3696 		}
3697 		pr_debug("Kernel doesn't support BTF, skipping uploading it.\n");
3698 		return 0;
3699 	}
3700 
3701 	/* Even though some subprogs are global/weak, user might prefer more
3702 	 * permissive BPF verification process that BPF verifier performs for
3703 	 * static functions, taking into account more context from the caller
3704 	 * functions. In such case, they need to mark such subprogs with
3705 	 * __attribute__((visibility("hidden"))) and libbpf will adjust
3706 	 * corresponding FUNC BTF type to be marked as static and trigger more
3707 	 * involved BPF verification process.
3708 	 */
3709 	for (i = 0; i < obj->nr_programs; i++) {
3710 		struct bpf_program *prog = &obj->programs[i];
3711 		struct btf_type *t;
3712 		const char *name;
3713 		int j, n;
3714 
3715 		if (!prog->mark_btf_static || !prog_is_subprog(obj, prog))
3716 			continue;
3717 
3718 		n = btf__type_cnt(obj->btf);
3719 		for (j = 1; j < n; j++) {
3720 			t = btf_type_by_id(obj->btf, j);
3721 			if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL)
3722 				continue;
3723 
3724 			name = btf__str_by_offset(obj->btf, t->name_off);
3725 			if (strcmp(name, prog->name) != 0)
3726 				continue;
3727 
3728 			t->info = btf_type_info(BTF_KIND_FUNC, BTF_FUNC_STATIC, 0);
3729 			break;
3730 		}
3731 	}
3732 
3733 	sanitize = btf_needs_sanitization(obj);
3734 	if (sanitize) {
3735 		kern_btf = bpf_object__sanitize_btf(obj, obj->btf);
3736 		if (IS_ERR(kern_btf))
3737 			return PTR_ERR(kern_btf);
3738 	}
3739 
3740 	if (obj->gen_loader) {
3741 		__u32 raw_size = 0;
3742 		const void *raw_data = btf__raw_data(kern_btf, &raw_size);
3743 
3744 		if (!raw_data)
3745 			return -ENOMEM;
3746 		bpf_gen__load_btf(obj->gen_loader, raw_data, raw_size);
3747 		/* Pretend to have valid FD to pass various fd >= 0 checks.
3748 		 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
3749 		 */
3750 		btf__set_fd(kern_btf, 0);
3751 	} else {
3752 		/* currently BPF_BTF_LOAD only supports log_level 1 */
3753 		err = btf_load_into_kernel(kern_btf, obj->log_buf, obj->log_size,
3754 					   obj->log_level ? 1 : 0, obj->token_fd);
3755 	}
3756 	if (sanitize) {
3757 		if (!err) {
3758 			/* move fd to libbpf's BTF */
3759 			btf__set_fd(obj->btf, btf__fd(kern_btf));
3760 			btf__set_fd(kern_btf, -1);
3761 		}
3762 		btf__free(kern_btf);
3763 	}
3764 report:
3765 	if (err) {
3766 		btf_mandatory = kernel_needs_btf(obj);
3767 		if (btf_mandatory) {
3768 			pr_warn("Error loading .BTF into kernel: %s. BTF is mandatory, can't proceed.\n",
3769 				errstr(err));
3770 		} else {
3771 			pr_info("Error loading .BTF into kernel: %s. BTF is optional, ignoring.\n",
3772 				errstr(err));
3773 			err = 0;
3774 		}
3775 	}
3776 	return err;
3777 }
3778 
3779 static const char *elf_sym_str(const struct bpf_object *obj, size_t off)
3780 {
3781 	const char *name;
3782 
3783 	name = elf_strptr(obj->efile.elf, obj->efile.strtabidx, off);
3784 	if (!name) {
3785 		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3786 			off, obj->path, elf_errmsg(-1));
3787 		return NULL;
3788 	}
3789 
3790 	return name;
3791 }
3792 
3793 static const char *elf_sec_str(const struct bpf_object *obj, size_t off)
3794 {
3795 	const char *name;
3796 
3797 	name = elf_strptr(obj->efile.elf, obj->efile.shstrndx, off);
3798 	if (!name) {
3799 		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3800 			off, obj->path, elf_errmsg(-1));
3801 		return NULL;
3802 	}
3803 
3804 	return name;
3805 }
3806 
3807 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx)
3808 {
3809 	Elf_Scn *scn;
3810 
3811 	scn = elf_getscn(obj->efile.elf, idx);
3812 	if (!scn) {
3813 		pr_warn("elf: failed to get section(%zu) from %s: %s\n",
3814 			idx, obj->path, elf_errmsg(-1));
3815 		return NULL;
3816 	}
3817 	return scn;
3818 }
3819 
3820 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name)
3821 {
3822 	Elf_Scn *scn = NULL;
3823 	Elf *elf = obj->efile.elf;
3824 	const char *sec_name;
3825 
3826 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3827 		sec_name = elf_sec_name(obj, scn);
3828 		if (!sec_name)
3829 			return NULL;
3830 
3831 		if (strcmp(sec_name, name) != 0)
3832 			continue;
3833 
3834 		return scn;
3835 	}
3836 	return NULL;
3837 }
3838 
3839 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn)
3840 {
3841 	Elf64_Shdr *shdr;
3842 
3843 	if (!scn)
3844 		return NULL;
3845 
3846 	shdr = elf64_getshdr(scn);
3847 	if (!shdr) {
3848 		pr_warn("elf: failed to get section(%zu) header from %s: %s\n",
3849 			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3850 		return NULL;
3851 	}
3852 
3853 	return shdr;
3854 }
3855 
3856 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn)
3857 {
3858 	const char *name;
3859 	Elf64_Shdr *sh;
3860 
3861 	if (!scn)
3862 		return NULL;
3863 
3864 	sh = elf_sec_hdr(obj, scn);
3865 	if (!sh)
3866 		return NULL;
3867 
3868 	name = elf_sec_str(obj, sh->sh_name);
3869 	if (!name) {
3870 		pr_warn("elf: failed to get section(%zu) name from %s: %s\n",
3871 			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3872 		return NULL;
3873 	}
3874 
3875 	return name;
3876 }
3877 
3878 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn)
3879 {
3880 	Elf_Data *data;
3881 
3882 	if (!scn)
3883 		return NULL;
3884 
3885 	data = elf_getdata(scn, 0);
3886 	if (!data) {
3887 		pr_warn("elf: failed to get section(%zu) %s data from %s: %s\n",
3888 			elf_ndxscn(scn), elf_sec_name(obj, scn) ?: "<?>",
3889 			obj->path, elf_errmsg(-1));
3890 		return NULL;
3891 	}
3892 
3893 	return data;
3894 }
3895 
3896 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx)
3897 {
3898 	if (idx >= obj->efile.symbols->d_size / sizeof(Elf64_Sym))
3899 		return NULL;
3900 
3901 	return (Elf64_Sym *)obj->efile.symbols->d_buf + idx;
3902 }
3903 
3904 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx)
3905 {
3906 	if (idx >= data->d_size / sizeof(Elf64_Rel))
3907 		return NULL;
3908 
3909 	return (Elf64_Rel *)data->d_buf + idx;
3910 }
3911 
3912 static bool is_sec_name_dwarf(const char *name)
3913 {
3914 	/* approximation, but the actual list is too long */
3915 	return str_has_pfx(name, ".debug_");
3916 }
3917 
3918 static bool ignore_elf_section(Elf64_Shdr *hdr, const char *name)
3919 {
3920 	/* no special handling of .strtab */
3921 	if (hdr->sh_type == SHT_STRTAB)
3922 		return true;
3923 
3924 	/* ignore .llvm_addrsig section as well */
3925 	if (hdr->sh_type == SHT_LLVM_ADDRSIG)
3926 		return true;
3927 
3928 	/* no subprograms will lead to an empty .text section, ignore it */
3929 	if (hdr->sh_type == SHT_PROGBITS && hdr->sh_size == 0 &&
3930 	    strcmp(name, ".text") == 0)
3931 		return true;
3932 
3933 	/* DWARF sections */
3934 	if (is_sec_name_dwarf(name))
3935 		return true;
3936 
3937 	if (str_has_pfx(name, ".rel")) {
3938 		name += sizeof(".rel") - 1;
3939 		/* DWARF section relocations */
3940 		if (is_sec_name_dwarf(name))
3941 			return true;
3942 
3943 		/* .BTF and .BTF.ext don't need relocations */
3944 		if (strcmp(name, BTF_ELF_SEC) == 0 ||
3945 		    strcmp(name, BTF_EXT_ELF_SEC) == 0)
3946 			return true;
3947 	}
3948 
3949 	return false;
3950 }
3951 
3952 static int cmp_progs(const void *_a, const void *_b)
3953 {
3954 	const struct bpf_program *a = _a;
3955 	const struct bpf_program *b = _b;
3956 
3957 	if (a->sec_idx != b->sec_idx)
3958 		return a->sec_idx < b->sec_idx ? -1 : 1;
3959 
3960 	/* sec_insn_off can't be the same within the section */
3961 	return a->sec_insn_off < b->sec_insn_off ? -1 : 1;
3962 }
3963 
3964 static int bpf_object__elf_collect(struct bpf_object *obj)
3965 {
3966 	struct elf_sec_desc *sec_desc;
3967 	Elf *elf = obj->efile.elf;
3968 	Elf_Data *btf_ext_data = NULL;
3969 	Elf_Data *btf_data = NULL;
3970 	int idx = 0, err = 0;
3971 	const char *name;
3972 	Elf_Data *data;
3973 	Elf_Scn *scn;
3974 	Elf64_Shdr *sh;
3975 
3976 	/* ELF section indices are 0-based, but sec #0 is special "invalid"
3977 	 * section. Since section count retrieved by elf_getshdrnum() does
3978 	 * include sec #0, it is already the necessary size of an array to keep
3979 	 * all the sections.
3980 	 */
3981 	if (elf_getshdrnum(obj->efile.elf, &obj->efile.sec_cnt)) {
3982 		pr_warn("elf: failed to get the number of sections for %s: %s\n",
3983 			obj->path, elf_errmsg(-1));
3984 		return -LIBBPF_ERRNO__FORMAT;
3985 	}
3986 	obj->efile.secs = calloc(obj->efile.sec_cnt, sizeof(*obj->efile.secs));
3987 	if (!obj->efile.secs)
3988 		return -ENOMEM;
3989 
3990 	/* a bunch of ELF parsing functionality depends on processing symbols,
3991 	 * so do the first pass and find the symbol table
3992 	 */
3993 	scn = NULL;
3994 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3995 		sh = elf_sec_hdr(obj, scn);
3996 		if (!sh)
3997 			return -LIBBPF_ERRNO__FORMAT;
3998 
3999 		if (sh->sh_type == SHT_SYMTAB) {
4000 			if (obj->efile.symbols) {
4001 				pr_warn("elf: multiple symbol tables in %s\n", obj->path);
4002 				return -LIBBPF_ERRNO__FORMAT;
4003 			}
4004 
4005 			data = elf_sec_data(obj, scn);
4006 			if (!data)
4007 				return -LIBBPF_ERRNO__FORMAT;
4008 
4009 			idx = elf_ndxscn(scn);
4010 
4011 			obj->efile.symbols = data;
4012 			obj->efile.symbols_shndx = idx;
4013 			obj->efile.strtabidx = sh->sh_link;
4014 		}
4015 	}
4016 
4017 	if (!obj->efile.symbols) {
4018 		pr_warn("elf: couldn't find symbol table in %s, stripped object file?\n",
4019 			obj->path);
4020 		return -ENOENT;
4021 	}
4022 
4023 	scn = NULL;
4024 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
4025 		idx = elf_ndxscn(scn);
4026 		sec_desc = &obj->efile.secs[idx];
4027 
4028 		sh = elf_sec_hdr(obj, scn);
4029 		if (!sh)
4030 			return -LIBBPF_ERRNO__FORMAT;
4031 
4032 		name = elf_sec_str(obj, sh->sh_name);
4033 		if (!name)
4034 			return -LIBBPF_ERRNO__FORMAT;
4035 
4036 		if (ignore_elf_section(sh, name))
4037 			continue;
4038 
4039 		data = elf_sec_data(obj, scn);
4040 		if (!data)
4041 			return -LIBBPF_ERRNO__FORMAT;
4042 
4043 		pr_debug("elf: section(%d) %s, size %lu, link %d, flags %lx, type=%d\n",
4044 			 idx, name, (unsigned long)data->d_size,
4045 			 (int)sh->sh_link, (unsigned long)sh->sh_flags,
4046 			 (int)sh->sh_type);
4047 
4048 		if (strcmp(name, "license") == 0) {
4049 			err = bpf_object__init_license(obj, data->d_buf, data->d_size);
4050 			if (err)
4051 				return err;
4052 		} else if (strcmp(name, "version") == 0) {
4053 			err = bpf_object__init_kversion(obj, data->d_buf, data->d_size);
4054 			if (err)
4055 				return err;
4056 		} else if (strcmp(name, "maps") == 0) {
4057 			pr_warn("elf: legacy map definitions in 'maps' section are not supported by libbpf v1.0+\n");
4058 			return -ENOTSUP;
4059 		} else if (strcmp(name, MAPS_ELF_SEC) == 0) {
4060 			obj->efile.btf_maps_shndx = idx;
4061 		} else if (strcmp(name, BTF_ELF_SEC) == 0) {
4062 			if (sh->sh_type != SHT_PROGBITS)
4063 				return -LIBBPF_ERRNO__FORMAT;
4064 			btf_data = data;
4065 		} else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
4066 			if (sh->sh_type != SHT_PROGBITS)
4067 				return -LIBBPF_ERRNO__FORMAT;
4068 			btf_ext_data = data;
4069 		} else if (sh->sh_type == SHT_SYMTAB) {
4070 			/* already processed during the first pass above */
4071 		} else if (sh->sh_type == SHT_PROGBITS && data->d_size > 0) {
4072 			if (sh->sh_flags & SHF_EXECINSTR) {
4073 				if (strcmp(name, ".text") == 0)
4074 					obj->efile.text_shndx = idx;
4075 				err = bpf_object__add_programs(obj, data, name, idx);
4076 				if (err)
4077 					return err;
4078 			} else if (strcmp(name, DATA_REL_RO_SEC) == 0 ||
4079 				   str_has_pfx(name, DATA_REL_RO_SEC ".")) {
4080 				/*
4081 				 * Constants with pointers in them, e.g. vtables,
4082 				 * that position independent code keeps here to
4083 				 * have them relocated. There is nothing that
4084 				 * writes to it after that.
4085 				 */
4086 				sec_desc->sec_type = SEC_RODATA;
4087 				sec_desc->shdr = sh;
4088 				sec_desc->data = data;
4089 			} else if (strcmp(name, DATA_SEC) == 0 ||
4090 				   str_has_pfx(name, DATA_SEC ".")) {
4091 				sec_desc->sec_type = SEC_DATA;
4092 				sec_desc->shdr = sh;
4093 				sec_desc->data = data;
4094 			} else if (strcmp(name, RODATA_SEC) == 0 ||
4095 				   str_has_pfx(name, RODATA_SEC ".")) {
4096 				sec_desc->sec_type = SEC_RODATA;
4097 				sec_desc->shdr = sh;
4098 				sec_desc->data = data;
4099 			} else if (strcmp(name, PERCPU_SEC) == 0 ||
4100 				   str_has_pfx(name, PERCPU_SEC ".")) {
4101 				sec_desc->sec_type = SEC_PERCPU;
4102 				sec_desc->shdr = sh;
4103 				sec_desc->data = data;
4104 			} else if (strcmp(name, STRUCT_OPS_SEC) == 0 ||
4105 				   strcmp(name, STRUCT_OPS_LINK_SEC) == 0 ||
4106 				   strcmp(name, "?" STRUCT_OPS_SEC) == 0 ||
4107 				   strcmp(name, "?" STRUCT_OPS_LINK_SEC) == 0) {
4108 				sec_desc->sec_type = SEC_ST_OPS;
4109 				sec_desc->shdr = sh;
4110 				sec_desc->data = data;
4111 				obj->efile.has_st_ops = true;
4112 			} else if (strcmp(name, ARENA_SEC) == 0) {
4113 				obj->efile.arena_data = data;
4114 				obj->efile.arena_data_shndx = idx;
4115 			} else if (strcmp(name, JUMPTABLES_SEC) == 0) {
4116 				obj->jumptables_data = malloc(data->d_size);
4117 				if (!obj->jumptables_data)
4118 					return -ENOMEM;
4119 				memcpy(obj->jumptables_data, data->d_buf, data->d_size);
4120 				obj->jumptables_data_sz = data->d_size;
4121 				obj->efile.jumptables_data_shndx = idx;
4122 			} else {
4123 				pr_info("elf: skipping unrecognized data section(%d) %s\n",
4124 					idx, name);
4125 			}
4126 		} else if (sh->sh_type == SHT_REL) {
4127 			int targ_sec_idx = sh->sh_info; /* points to other section */
4128 
4129 			if (sh->sh_entsize != sizeof(Elf64_Rel) ||
4130 			    targ_sec_idx >= obj->efile.sec_cnt)
4131 				return -LIBBPF_ERRNO__FORMAT;
4132 
4133 			/*
4134 			 * Only do relo for section with exec instructions,
4135 			 * struct_ops, maps, and read-only data that might
4136 			 * have pointers to functions.
4137 			 */
4138 			if (!section_have_execinstr(obj, targ_sec_idx) &&
4139 			    strcmp(name, ".rel" RODATA_SEC) &&
4140 			    !str_has_pfx(name, ".rel" RODATA_SEC ".") &&
4141 			    strcmp(name, ".rel" DATA_REL_RO_SEC) &&
4142 			    !str_has_pfx(name, ".rel" DATA_REL_RO_SEC ".") &&
4143 			    strcmp(name, ".rel" STRUCT_OPS_SEC) &&
4144 			    strcmp(name, ".rel" STRUCT_OPS_LINK_SEC) &&
4145 			    strcmp(name, ".rel?" STRUCT_OPS_SEC) &&
4146 			    strcmp(name, ".rel?" STRUCT_OPS_LINK_SEC) &&
4147 			    strcmp(name, ".rel" MAPS_ELF_SEC)) {
4148 				pr_info("elf: skipping relo section(%d) %s for section(%d) %s\n",
4149 					idx, name, targ_sec_idx,
4150 					elf_sec_name(obj, elf_sec_by_idx(obj, targ_sec_idx)) ?: "<?>");
4151 				continue;
4152 			}
4153 
4154 			sec_desc->sec_type = SEC_RELO;
4155 			sec_desc->shdr = sh;
4156 			sec_desc->data = data;
4157 		} else if (sh->sh_type == SHT_NOBITS && (strcmp(name, BSS_SEC) == 0 ||
4158 							 str_has_pfx(name, BSS_SEC "."))) {
4159 			sec_desc->sec_type = SEC_BSS;
4160 			sec_desc->shdr = sh;
4161 			sec_desc->data = data;
4162 		} else {
4163 			pr_info("elf: skipping section(%d) %s (size %zu)\n", idx, name,
4164 				(size_t)sh->sh_size);
4165 		}
4166 	}
4167 
4168 	if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) {
4169 		pr_warn("elf: symbol strings section missing or invalid in %s\n", obj->path);
4170 		return -LIBBPF_ERRNO__FORMAT;
4171 	}
4172 
4173 	/* change BPF program insns to native endianness for introspection */
4174 	if (!is_native_endianness(obj))
4175 		bpf_object_bswap_progs(obj);
4176 
4177 	/* sort BPF programs by section name and in-section instruction offset
4178 	 * for faster search
4179 	 */
4180 	if (obj->nr_programs)
4181 		qsort(obj->programs, obj->nr_programs, sizeof(*obj->programs), cmp_progs);
4182 
4183 	return bpf_object__init_btf(obj, btf_data, btf_ext_data);
4184 }
4185 
4186 static bool sym_is_extern(const Elf64_Sym *sym)
4187 {
4188 	int bind = ELF64_ST_BIND(sym->st_info);
4189 	/* externs are symbols w/ type=NOTYPE, bind=GLOBAL|WEAK, section=UND */
4190 	return sym->st_shndx == SHN_UNDEF &&
4191 	       (bind == STB_GLOBAL || bind == STB_WEAK) &&
4192 	       ELF64_ST_TYPE(sym->st_info) == STT_NOTYPE;
4193 }
4194 
4195 static bool sym_is_subprog(const Elf64_Sym *sym, int text_shndx)
4196 {
4197 	int bind = ELF64_ST_BIND(sym->st_info);
4198 	int type = ELF64_ST_TYPE(sym->st_info);
4199 
4200 	/* in .text section */
4201 	if (sym->st_shndx != text_shndx)
4202 		return false;
4203 
4204 	/* local function */
4205 	if (bind == STB_LOCAL && type == STT_SECTION)
4206 		return true;
4207 
4208 	/* global function */
4209 	return (bind == STB_GLOBAL || bind == STB_WEAK) && type == STT_FUNC;
4210 }
4211 
4212 static int find_extern_btf_id(const struct btf *btf, const char *ext_name)
4213 {
4214 	const struct btf_type *t;
4215 	const char *tname;
4216 	int i, n;
4217 
4218 	if (!btf)
4219 		return -ESRCH;
4220 
4221 	n = btf__type_cnt(btf);
4222 	for (i = 1; i < n; i++) {
4223 		t = btf__type_by_id(btf, i);
4224 
4225 		if (!btf_is_var(t) && !btf_is_func(t))
4226 			continue;
4227 
4228 		tname = btf__name_by_offset(btf, t->name_off);
4229 		if (strcmp(tname, ext_name))
4230 			continue;
4231 
4232 		if (btf_is_var(t) &&
4233 		    btf_var(t)->linkage != BTF_VAR_GLOBAL_EXTERN)
4234 			return -EINVAL;
4235 
4236 		if (btf_is_func(t) && btf_func_linkage(t) != BTF_FUNC_EXTERN)
4237 			return -EINVAL;
4238 
4239 		return i;
4240 	}
4241 
4242 	return -ENOENT;
4243 }
4244 
4245 static int find_extern_sec_btf_id(struct btf *btf, int ext_btf_id) {
4246 	const struct btf_var_secinfo *vs;
4247 	const struct btf_type *t;
4248 	int i, j, n;
4249 
4250 	if (!btf)
4251 		return -ESRCH;
4252 
4253 	n = btf__type_cnt(btf);
4254 	for (i = 1; i < n; i++) {
4255 		t = btf__type_by_id(btf, i);
4256 
4257 		if (!btf_is_datasec(t))
4258 			continue;
4259 
4260 		vs = btf_var_secinfos(t);
4261 		for (j = 0; j < btf_vlen(t); j++, vs++) {
4262 			if (vs->type == ext_btf_id)
4263 				return i;
4264 		}
4265 	}
4266 
4267 	return -ENOENT;
4268 }
4269 
4270 static enum kcfg_type find_kcfg_type(const struct btf *btf, int id,
4271 				     bool *is_signed)
4272 {
4273 	const struct btf_type *t;
4274 	const char *name;
4275 
4276 	t = skip_mods_and_typedefs(btf, id, NULL);
4277 	name = btf__name_by_offset(btf, t->name_off);
4278 
4279 	if (is_signed)
4280 		*is_signed = false;
4281 	switch (btf_kind(t)) {
4282 	case BTF_KIND_INT: {
4283 		int enc = btf_int_encoding(t);
4284 
4285 		if (enc & BTF_INT_BOOL)
4286 			return t->size == 1 ? KCFG_BOOL : KCFG_UNKNOWN;
4287 		if (is_signed)
4288 			*is_signed = enc & BTF_INT_SIGNED;
4289 		if (t->size == 1)
4290 			return KCFG_CHAR;
4291 		if (t->size < 1 || t->size > 8 || (t->size & (t->size - 1)))
4292 			return KCFG_UNKNOWN;
4293 		return KCFG_INT;
4294 	}
4295 	case BTF_KIND_ENUM:
4296 		if (t->size != 4)
4297 			return KCFG_UNKNOWN;
4298 		if (strcmp(name, "libbpf_tristate"))
4299 			return KCFG_UNKNOWN;
4300 		return KCFG_TRISTATE;
4301 	case BTF_KIND_ENUM64:
4302 		if (strcmp(name, "libbpf_tristate"))
4303 			return KCFG_UNKNOWN;
4304 		return KCFG_TRISTATE;
4305 	case BTF_KIND_ARRAY:
4306 		if (btf_array(t)->nelems == 0)
4307 			return KCFG_UNKNOWN;
4308 		if (find_kcfg_type(btf, btf_array(t)->type, NULL) != KCFG_CHAR)
4309 			return KCFG_UNKNOWN;
4310 		return KCFG_CHAR_ARR;
4311 	default:
4312 		return KCFG_UNKNOWN;
4313 	}
4314 }
4315 
4316 static int cmp_externs(const void *_a, const void *_b)
4317 {
4318 	const struct extern_desc *a = _a;
4319 	const struct extern_desc *b = _b;
4320 
4321 	if (a->type != b->type)
4322 		return a->type < b->type ? -1 : 1;
4323 
4324 	if (a->type == EXT_KCFG) {
4325 		/* descending order by alignment requirements */
4326 		if (a->kcfg.align != b->kcfg.align)
4327 			return a->kcfg.align > b->kcfg.align ? -1 : 1;
4328 		/* ascending order by size, within same alignment class */
4329 		if (a->kcfg.sz != b->kcfg.sz)
4330 			return a->kcfg.sz < b->kcfg.sz ? -1 : 1;
4331 	}
4332 
4333 	/* resolve ties by name */
4334 	return strcmp(a->name, b->name);
4335 }
4336 
4337 static int find_int_btf_id(const struct btf *btf)
4338 {
4339 	const struct btf_type *t;
4340 	int i, n;
4341 
4342 	n = btf__type_cnt(btf);
4343 	for (i = 1; i < n; i++) {
4344 		t = btf__type_by_id(btf, i);
4345 
4346 		if (btf_is_int(t) && btf_int_bits(t) == 32)
4347 			return i;
4348 	}
4349 
4350 	return 0;
4351 }
4352 
4353 static int add_dummy_ksym_var(struct btf *btf)
4354 {
4355 	int i, int_btf_id, sec_btf_id, dummy_var_btf_id;
4356 	const struct btf_var_secinfo *vs;
4357 	const struct btf_type *sec;
4358 
4359 	if (!btf)
4360 		return 0;
4361 
4362 	sec_btf_id = btf__find_by_name_kind(btf, KSYMS_SEC,
4363 					    BTF_KIND_DATASEC);
4364 	if (sec_btf_id < 0)
4365 		return 0;
4366 
4367 	sec = btf__type_by_id(btf, sec_btf_id);
4368 	vs = btf_var_secinfos(sec);
4369 	for (i = 0; i < btf_vlen(sec); i++, vs++) {
4370 		const struct btf_type *vt;
4371 
4372 		vt = btf__type_by_id(btf, vs->type);
4373 		if (btf_is_func(vt))
4374 			break;
4375 	}
4376 
4377 	/* No func in ksyms sec.  No need to add dummy var. */
4378 	if (i == btf_vlen(sec))
4379 		return 0;
4380 
4381 	int_btf_id = find_int_btf_id(btf);
4382 	dummy_var_btf_id = btf__add_var(btf,
4383 					"dummy_ksym",
4384 					BTF_VAR_GLOBAL_ALLOCATED,
4385 					int_btf_id);
4386 	if (dummy_var_btf_id < 0)
4387 		pr_warn("cannot create a dummy_ksym var\n");
4388 
4389 	return dummy_var_btf_id;
4390 }
4391 
4392 static int bpf_object__collect_externs(struct bpf_object *obj)
4393 {
4394 	struct btf_type *sec, *kcfg_sec = NULL, *ksym_sec = NULL;
4395 	const struct btf_type *t;
4396 	struct extern_desc *ext;
4397 	int i, n, off, dummy_var_btf_id;
4398 	const char *ext_name, *sec_name;
4399 	size_t ext_essent_len;
4400 	Elf_Scn *scn;
4401 	Elf64_Shdr *sh;
4402 
4403 	if (!obj->efile.symbols)
4404 		return 0;
4405 
4406 	scn = elf_sec_by_idx(obj, obj->efile.symbols_shndx);
4407 	sh = elf_sec_hdr(obj, scn);
4408 	if (!sh || sh->sh_entsize != sizeof(Elf64_Sym))
4409 		return -LIBBPF_ERRNO__FORMAT;
4410 
4411 	dummy_var_btf_id = add_dummy_ksym_var(obj->btf);
4412 	if (dummy_var_btf_id < 0)
4413 		return dummy_var_btf_id;
4414 
4415 	n = sh->sh_size / sh->sh_entsize;
4416 	pr_debug("looking for externs among %d symbols...\n", n);
4417 
4418 	for (i = 0; i < n; i++) {
4419 		Elf64_Sym *sym = elf_sym_by_idx(obj, i);
4420 
4421 		if (!sym)
4422 			return -LIBBPF_ERRNO__FORMAT;
4423 		if (!sym_is_extern(sym))
4424 			continue;
4425 		ext_name = elf_sym_str(obj, sym->st_name);
4426 		if (str_is_empty(ext_name))
4427 			continue;
4428 
4429 		ext = obj->externs;
4430 		ext = libbpf_reallocarray(ext, obj->nr_extern + 1, sizeof(*ext));
4431 		if (!ext)
4432 			return -ENOMEM;
4433 		obj->externs = ext;
4434 		ext = &ext[obj->nr_extern];
4435 		memset(ext, 0, sizeof(*ext));
4436 		obj->nr_extern++;
4437 
4438 		ext->btf_id = find_extern_btf_id(obj->btf, ext_name);
4439 		if (ext->btf_id <= 0) {
4440 			pr_warn("failed to find BTF for extern '%s': %d\n",
4441 				ext_name, ext->btf_id);
4442 			return ext->btf_id;
4443 		}
4444 		t = btf__type_by_id(obj->btf, ext->btf_id);
4445 		ext->name = strdup(btf__name_by_offset(obj->btf, t->name_off));
4446 		if (!ext->name)
4447 			return -ENOMEM;
4448 		ext->sym_idx = i;
4449 		ext->is_weak = ELF64_ST_BIND(sym->st_info) == STB_WEAK;
4450 
4451 		ext_essent_len = bpf_core_essential_name_len(ext->name);
4452 		ext->essent_name = NULL;
4453 		if (ext_essent_len != strlen(ext->name)) {
4454 			ext->essent_name = strndup(ext->name, ext_essent_len);
4455 			if (!ext->essent_name)
4456 				return -ENOMEM;
4457 		}
4458 
4459 		ext->sec_btf_id = find_extern_sec_btf_id(obj->btf, ext->btf_id);
4460 		if (ext->sec_btf_id <= 0) {
4461 			pr_warn("failed to find BTF for extern '%s' [%d] section: %d\n",
4462 				ext_name, ext->btf_id, ext->sec_btf_id);
4463 			return ext->sec_btf_id;
4464 		}
4465 		sec = (void *)btf__type_by_id(obj->btf, ext->sec_btf_id);
4466 		sec_name = btf__name_by_offset(obj->btf, sec->name_off);
4467 
4468 		if (strcmp(sec_name, KCONFIG_SEC) == 0) {
4469 			if (btf_is_func(t)) {
4470 				pr_warn("extern function %s is unsupported under %s section\n",
4471 					ext->name, KCONFIG_SEC);
4472 				return -ENOTSUP;
4473 			}
4474 			kcfg_sec = sec;
4475 			ext->type = EXT_KCFG;
4476 			ext->kcfg.sz = btf__resolve_size(obj->btf, t->type);
4477 			if (ext->kcfg.sz <= 0) {
4478 				pr_warn("failed to resolve size of extern (kcfg) '%s': %d\n",
4479 					ext_name, ext->kcfg.sz);
4480 				return ext->kcfg.sz;
4481 			}
4482 			ext->kcfg.align = btf__align_of(obj->btf, t->type);
4483 			if (ext->kcfg.align <= 0) {
4484 				pr_warn("failed to determine alignment of extern (kcfg) '%s': %d\n",
4485 					ext_name, ext->kcfg.align);
4486 				return -EINVAL;
4487 			}
4488 			ext->kcfg.type = find_kcfg_type(obj->btf, t->type,
4489 							&ext->kcfg.is_signed);
4490 			if (ext->kcfg.type == KCFG_UNKNOWN) {
4491 				pr_warn("extern (kcfg) '%s': type is unsupported\n", ext_name);
4492 				return -ENOTSUP;
4493 			}
4494 		} else if (strcmp(sec_name, KSYMS_SEC) == 0) {
4495 			ksym_sec = sec;
4496 			ext->type = EXT_KSYM;
4497 			skip_mods_and_typedefs(obj->btf, t->type,
4498 					       &ext->ksym.type_id);
4499 		} else {
4500 			pr_warn("unrecognized extern section '%s'\n", sec_name);
4501 			return -ENOTSUP;
4502 		}
4503 	}
4504 	pr_debug("collected %d externs total\n", obj->nr_extern);
4505 
4506 	if (!obj->nr_extern)
4507 		return 0;
4508 
4509 	/* sort externs by type, for kcfg ones also by (align, size, name) */
4510 	qsort(obj->externs, obj->nr_extern, sizeof(*ext), cmp_externs);
4511 
4512 	/* for .ksyms section, we need to turn all externs into allocated
4513 	 * variables in BTF to pass kernel verification; we do this by
4514 	 * pretending that each extern is a 8-byte variable
4515 	 */
4516 	if (ksym_sec) {
4517 		/* find existing 4-byte integer type in BTF to use for fake
4518 		 * extern variables in DATASEC
4519 		 */
4520 		int int_btf_id = find_int_btf_id(obj->btf);
4521 		/* For extern function, a dummy_var added earlier
4522 		 * will be used to replace the vs->type and
4523 		 * its name string will be used to refill
4524 		 * the missing param's name.
4525 		 */
4526 		const struct btf_type *dummy_var;
4527 
4528 		dummy_var = btf__type_by_id(obj->btf, dummy_var_btf_id);
4529 		for (i = 0; i < obj->nr_extern; i++) {
4530 			ext = &obj->externs[i];
4531 			if (ext->type != EXT_KSYM)
4532 				continue;
4533 			pr_debug("extern (ksym) #%d: symbol %d, name %s\n",
4534 				 i, ext->sym_idx, ext->name);
4535 		}
4536 
4537 		sec = ksym_sec;
4538 		n = btf_vlen(sec);
4539 		for (i = 0, off = 0; i < n; i++, off += sizeof(int)) {
4540 			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
4541 			struct btf_type *vt;
4542 
4543 			vt = (void *)btf__type_by_id(obj->btf, vs->type);
4544 			ext_name = btf__name_by_offset(obj->btf, vt->name_off);
4545 			ext = find_extern_by_name(obj, ext_name);
4546 			if (!ext) {
4547 				pr_warn("failed to find extern definition for BTF %s '%s'\n",
4548 					btf_kind_str(vt), ext_name);
4549 				return -ESRCH;
4550 			}
4551 			if (btf_is_func(vt)) {
4552 				const struct btf_type *func_proto;
4553 				struct btf_param *param;
4554 				int j;
4555 
4556 				func_proto = btf__type_by_id(obj->btf,
4557 							     vt->type);
4558 				param = btf_params(func_proto);
4559 				/* Reuse the dummy_var string if the
4560 				 * func proto does not have param name.
4561 				 */
4562 				for (j = 0; j < btf_vlen(func_proto); j++)
4563 					if (param[j].type && !param[j].name_off)
4564 						param[j].name_off =
4565 							dummy_var->name_off;
4566 				vs->type = dummy_var_btf_id;
4567 				vt->info &= ~0xffff;
4568 				vt->info |= BTF_FUNC_GLOBAL;
4569 			} else {
4570 				btf_var(vt)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
4571 				vt->type = int_btf_id;
4572 			}
4573 			vs->offset = off;
4574 			vs->size = sizeof(int);
4575 		}
4576 		sec->size = off;
4577 	}
4578 
4579 	if (kcfg_sec) {
4580 		sec = kcfg_sec;
4581 		/* for kcfg externs calculate their offsets within a .kconfig map */
4582 		off = 0;
4583 		for (i = 0; i < obj->nr_extern; i++) {
4584 			ext = &obj->externs[i];
4585 			if (ext->type != EXT_KCFG)
4586 				continue;
4587 
4588 			ext->kcfg.data_off = roundup(off, ext->kcfg.align);
4589 			off = ext->kcfg.data_off + ext->kcfg.sz;
4590 			pr_debug("extern (kcfg) #%d: symbol %d, off %d, name %s\n",
4591 				 i, ext->sym_idx, ext->kcfg.data_off, ext->name);
4592 		}
4593 		sec->size = off;
4594 		n = btf_vlen(sec);
4595 		for (i = 0; i < n; i++) {
4596 			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
4597 
4598 			t = btf__type_by_id(obj->btf, vs->type);
4599 			ext_name = btf__name_by_offset(obj->btf, t->name_off);
4600 			ext = find_extern_by_name(obj, ext_name);
4601 			if (!ext) {
4602 				pr_warn("failed to find extern definition for BTF var '%s'\n",
4603 					ext_name);
4604 				return -ESRCH;
4605 			}
4606 			btf_var(t)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
4607 			vs->offset = ext->kcfg.data_off;
4608 		}
4609 	}
4610 	return 0;
4611 }
4612 
4613 static bool prog_is_subprog(const struct bpf_object *obj, const struct bpf_program *prog)
4614 {
4615 	return prog->sec_idx == obj->efile.text_shndx;
4616 }
4617 
4618 struct bpf_program *
4619 bpf_object__find_program_by_name(const struct bpf_object *obj,
4620 				 const char *name)
4621 {
4622 	struct bpf_program *prog;
4623 
4624 	bpf_object__for_each_program(prog, obj) {
4625 		if (prog_is_subprog(obj, prog))
4626 			continue;
4627 		if (!strcmp(prog->name, name))
4628 			return prog;
4629 	}
4630 	return errno = ENOENT, NULL;
4631 }
4632 
4633 static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
4634 				      int shndx)
4635 {
4636 	switch (obj->efile.secs[shndx].sec_type) {
4637 	case SEC_BSS:
4638 	case SEC_DATA:
4639 	case SEC_RODATA:
4640 	case SEC_PERCPU:
4641 		return true;
4642 	default:
4643 		return false;
4644 	}
4645 }
4646 
4647 static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
4648 				      int shndx)
4649 {
4650 	return shndx == obj->efile.btf_maps_shndx;
4651 }
4652 
4653 static enum libbpf_map_type
4654 bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
4655 {
4656 	if (shndx == obj->efile.symbols_shndx)
4657 		return LIBBPF_MAP_KCONFIG;
4658 
4659 	switch (obj->efile.secs[shndx].sec_type) {
4660 	case SEC_BSS:
4661 		return LIBBPF_MAP_BSS;
4662 	case SEC_DATA:
4663 		return LIBBPF_MAP_DATA;
4664 	case SEC_RODATA:
4665 		return LIBBPF_MAP_RODATA;
4666 	case SEC_PERCPU:
4667 		return LIBBPF_MAP_PERCPU;
4668 	default:
4669 		return LIBBPF_MAP_UNSPEC;
4670 	}
4671 }
4672 
4673 static int bpf_prog_compute_hash(struct bpf_program *prog)
4674 {
4675 	struct bpf_insn *purged;
4676 	int i, err = 0;
4677 
4678 	purged = calloc(prog->insns_cnt, BPF_INSN_SZ);
4679 	if (!purged)
4680 		return -ENOMEM;
4681 
4682 	/* If relocations have been done, the map_fd needs to be
4683 	 * discarded for the digest calculation.
4684 	 */
4685 	for (i = 0; i < prog->insns_cnt; i++) {
4686 		purged[i] = prog->insns[i];
4687 		if (purged[i].code == (BPF_LD | BPF_IMM | BPF_DW) &&
4688 		    (purged[i].src_reg == BPF_PSEUDO_MAP_FD ||
4689 		     purged[i].src_reg == BPF_PSEUDO_MAP_VALUE)) {
4690 			purged[i].imm = 0;
4691 			i++;
4692 			if (i >= prog->insns_cnt ||
4693 			    prog->insns[i].code != 0 ||
4694 			    prog->insns[i].dst_reg != 0 ||
4695 			    prog->insns[i].src_reg != 0 ||
4696 			    prog->insns[i].off != 0) {
4697 				err = -EINVAL;
4698 				goto out;
4699 			}
4700 			purged[i] = prog->insns[i];
4701 			purged[i].imm = 0;
4702 		}
4703 	}
4704 	libbpf_sha256(purged, prog->insns_cnt * sizeof(struct bpf_insn),
4705 		      prog->hash);
4706 out:
4707 	free(purged);
4708 	return err;
4709 }
4710 
4711 static int bpf_program__record_reloc(struct bpf_program *prog,
4712 				     struct reloc_desc *reloc_desc,
4713 				     __u32 insn_idx, const char *sym_name,
4714 				     const Elf64_Sym *sym, const Elf64_Rel *rel)
4715 {
4716 	struct bpf_insn *insn = &prog->insns[insn_idx];
4717 	size_t map_idx, nr_maps = prog->obj->nr_maps;
4718 	struct bpf_object *obj = prog->obj;
4719 	__u32 shdr_idx = sym->st_shndx;
4720 	enum libbpf_map_type type;
4721 	const char *sym_sec_name;
4722 	struct bpf_map *map;
4723 
4724 	if (!is_call_insn(insn) && !is_ldimm64_insn(insn)) {
4725 		pr_warn("prog '%s': invalid relo against '%s' for insns[%u].code 0x%x\n",
4726 			prog->name, sym_name, insn_idx, insn->code);
4727 		return -LIBBPF_ERRNO__RELOC;
4728 	}
4729 
4730 	if (sym_is_extern(sym)) {
4731 		int sym_idx = ELF64_R_SYM(rel->r_info);
4732 		int i, n = obj->nr_extern;
4733 		struct extern_desc *ext;
4734 
4735 		for (i = 0; i < n; i++) {
4736 			ext = &obj->externs[i];
4737 			if (ext->sym_idx == sym_idx)
4738 				break;
4739 		}
4740 		if (i >= n) {
4741 			pr_warn("prog '%s': extern relo failed to find extern for '%s' (%d)\n",
4742 				prog->name, sym_name, sym_idx);
4743 			return -LIBBPF_ERRNO__RELOC;
4744 		}
4745 		pr_debug("prog '%s': found extern #%d '%s' (sym %d) for insn #%u\n",
4746 			 prog->name, i, ext->name, ext->sym_idx, insn_idx);
4747 		if (insn->code == (BPF_JMP | BPF_CALL))
4748 			reloc_desc->type = RELO_EXTERN_CALL;
4749 		else
4750 			reloc_desc->type = RELO_EXTERN_LD64;
4751 		reloc_desc->insn_idx = insn_idx;
4752 		reloc_desc->ext_idx = i;
4753 		return 0;
4754 	}
4755 
4756 	/* sub-program call relocation */
4757 	if (is_call_insn(insn)) {
4758 		if (insn->src_reg != BPF_PSEUDO_CALL) {
4759 			pr_warn("prog '%s': incorrect bpf_call opcode\n", prog->name);
4760 			return -LIBBPF_ERRNO__RELOC;
4761 		}
4762 		/* text_shndx can be 0, if no default "main" program exists */
4763 		if (!shdr_idx || shdr_idx != obj->efile.text_shndx) {
4764 			sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4765 			pr_warn("prog '%s': bad call relo against '%s' in section '%s'\n",
4766 				prog->name, sym_name, sym_sec_name);
4767 			return -LIBBPF_ERRNO__RELOC;
4768 		}
4769 		if (sym->st_value % BPF_INSN_SZ) {
4770 			pr_warn("prog '%s': bad call relo against '%s' at offset %zu\n",
4771 				prog->name, sym_name, (size_t)sym->st_value);
4772 			return -LIBBPF_ERRNO__RELOC;
4773 		}
4774 		reloc_desc->type = RELO_CALL;
4775 		reloc_desc->insn_idx = insn_idx;
4776 		reloc_desc->sym_off = sym->st_value;
4777 		return 0;
4778 	}
4779 
4780 	if (!shdr_idx || shdr_idx >= SHN_LORESERVE) {
4781 		pr_warn("prog '%s': invalid relo against '%s' in special section 0x%x; forgot to initialize global var?..\n",
4782 			prog->name, sym_name, shdr_idx);
4783 		return -LIBBPF_ERRNO__RELOC;
4784 	}
4785 
4786 	/* loading subprog addresses */
4787 	if (sym_is_subprog(sym, obj->efile.text_shndx)) {
4788 		/* global_func: sym->st_value = offset in the section, insn->imm = 0.
4789 		 * local_func: sym->st_value = 0, insn->imm = offset in the section.
4790 		 */
4791 		if ((sym->st_value % BPF_INSN_SZ) || (insn->imm % BPF_INSN_SZ)) {
4792 			pr_warn("prog '%s': bad subprog addr relo against '%s' at offset %zu+%d\n",
4793 				prog->name, sym_name, (size_t)sym->st_value, insn->imm);
4794 			return -LIBBPF_ERRNO__RELOC;
4795 		}
4796 
4797 		reloc_desc->type = RELO_SUBPROG_ADDR;
4798 		reloc_desc->insn_idx = insn_idx;
4799 		reloc_desc->sym_off = sym->st_value;
4800 		return 0;
4801 	}
4802 
4803 	type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
4804 	sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4805 
4806 	/* arena data relocation */
4807 	if (shdr_idx == obj->efile.arena_data_shndx) {
4808 		if (obj->arena_map_idx < 0) {
4809 			pr_warn("prog '%s': bad arena data relocation at insn %u, no arena maps defined\n",
4810 				prog->name, insn_idx);
4811 			return -LIBBPF_ERRNO__RELOC;
4812 		}
4813 		reloc_desc->type = RELO_DATA;
4814 		reloc_desc->insn_idx = insn_idx;
4815 		reloc_desc->map_idx = obj->arena_map_idx;
4816 		reloc_desc->sym_off = sym->st_value;
4817 
4818 		map = &obj->maps[obj->arena_map_idx];
4819 		pr_debug("prog '%s': found arena map %d (%s, sec %d, off %zu) for insn %u\n",
4820 			 prog->name, obj->arena_map_idx, map->name, map->sec_idx,
4821 			 map->sec_offset, insn_idx);
4822 		return 0;
4823 	}
4824 
4825 	/* jump table data relocation */
4826 	if (shdr_idx == obj->efile.jumptables_data_shndx) {
4827 		reloc_desc->type = RELO_INSN_ARRAY;
4828 		reloc_desc->insn_idx = insn_idx;
4829 		reloc_desc->map_idx = -1;
4830 		reloc_desc->sym_off = sym->st_value;
4831 		reloc_desc->sym_size = sym->st_size;
4832 		return 0;
4833 	}
4834 
4835 	/* generic map reference relocation */
4836 	if (type == LIBBPF_MAP_UNSPEC) {
4837 		if (!bpf_object__shndx_is_maps(obj, shdr_idx)) {
4838 			pr_warn("prog '%s': bad map relo against '%s' in section '%s'\n",
4839 				prog->name, sym_name, sym_sec_name);
4840 			return -LIBBPF_ERRNO__RELOC;
4841 		}
4842 		for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4843 			map = &obj->maps[map_idx];
4844 			if (map->libbpf_type != type ||
4845 			    map->sec_idx != sym->st_shndx ||
4846 			    map->sec_offset != sym->st_value)
4847 				continue;
4848 			pr_debug("prog '%s': found map %zu (%s, sec %d, off %zu) for insn #%u\n",
4849 				 prog->name, map_idx, map->name, map->sec_idx,
4850 				 map->sec_offset, insn_idx);
4851 			break;
4852 		}
4853 		if (map_idx >= nr_maps) {
4854 			pr_warn("prog '%s': map relo failed to find map for section '%s', off %zu\n",
4855 				prog->name, sym_sec_name, (size_t)sym->st_value);
4856 			return -LIBBPF_ERRNO__RELOC;
4857 		}
4858 		reloc_desc->type = RELO_LD64;
4859 		reloc_desc->insn_idx = insn_idx;
4860 		reloc_desc->map_idx = map_idx;
4861 		reloc_desc->sym_off = 0; /* sym->st_value determines map_idx */
4862 		return 0;
4863 	}
4864 
4865 	/* global data map relocation */
4866 	if (!bpf_object__shndx_is_data(obj, shdr_idx)) {
4867 		pr_warn("prog '%s': bad data relo against section '%s'\n",
4868 			prog->name, sym_sec_name);
4869 		return -LIBBPF_ERRNO__RELOC;
4870 	}
4871 	for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4872 		map = &obj->maps[map_idx];
4873 		if (map->libbpf_type != type || map->sec_idx != sym->st_shndx)
4874 			continue;
4875 		pr_debug("prog '%s': found data map %zu (%s, sec %d, off %zu) for insn %u\n",
4876 			 prog->name, map_idx, map->name, map->sec_idx,
4877 			 map->sec_offset, insn_idx);
4878 		break;
4879 	}
4880 	if (map_idx >= nr_maps) {
4881 		pr_warn("prog '%s': data relo failed to find map for section '%s'\n",
4882 			prog->name, sym_sec_name);
4883 		return -LIBBPF_ERRNO__RELOC;
4884 	}
4885 
4886 	reloc_desc->type = RELO_DATA;
4887 	reloc_desc->insn_idx = insn_idx;
4888 	reloc_desc->map_idx = map_idx;
4889 	reloc_desc->sym_off = sym->st_value;
4890 	return 0;
4891 }
4892 
4893 static bool prog_contains_insn(const struct bpf_program *prog, size_t insn_idx)
4894 {
4895 	return insn_idx >= prog->sec_insn_off &&
4896 	       insn_idx < prog->sec_insn_off + prog->sec_insn_cnt;
4897 }
4898 
4899 static struct bpf_program *find_prog_by_sec_insn(const struct bpf_object *obj,
4900 						 size_t sec_idx, size_t insn_idx)
4901 {
4902 	int l = 0, r = obj->nr_programs - 1, m;
4903 	struct bpf_program *prog;
4904 
4905 	if (!obj->nr_programs)
4906 		return NULL;
4907 
4908 	while (l < r) {
4909 		m = l + (r - l + 1) / 2;
4910 		prog = &obj->programs[m];
4911 
4912 		if (prog->sec_idx < sec_idx ||
4913 		    (prog->sec_idx == sec_idx && prog->sec_insn_off <= insn_idx))
4914 			l = m;
4915 		else
4916 			r = m - 1;
4917 	}
4918 	/* matching program could be at index l, but it still might be the
4919 	 * wrong one, so we need to double check conditions for the last time
4920 	 */
4921 	prog = &obj->programs[l];
4922 	if (prog->sec_idx == sec_idx && prog_contains_insn(prog, insn_idx))
4923 		return prog;
4924 	return NULL;
4925 }
4926 
4927 static int
4928 bpf_object__collect_prog_relos(struct bpf_object *obj, Elf64_Shdr *shdr, Elf_Data *data)
4929 {
4930 	const char *relo_sec_name, *sec_name;
4931 	size_t sec_idx = shdr->sh_info, sym_idx;
4932 	struct bpf_program *prog;
4933 	struct reloc_desc *relos;
4934 	int err, i, nrels;
4935 	const char *sym_name;
4936 	__u32 insn_idx;
4937 	Elf_Scn *scn;
4938 	Elf_Data *scn_data;
4939 	Elf64_Sym *sym;
4940 	Elf64_Rel *rel;
4941 
4942 	if (sec_idx >= obj->efile.sec_cnt)
4943 		return -EINVAL;
4944 
4945 	scn = elf_sec_by_idx(obj, sec_idx);
4946 	scn_data = elf_sec_data(obj, scn);
4947 	if (!scn_data)
4948 		return -LIBBPF_ERRNO__FORMAT;
4949 
4950 	relo_sec_name = elf_sec_str(obj, shdr->sh_name);
4951 	sec_name = elf_sec_name(obj, scn);
4952 	if (!relo_sec_name || !sec_name)
4953 		return -EINVAL;
4954 
4955 	pr_debug("sec '%s': collecting relocation for section(%zu) '%s'\n",
4956 		 relo_sec_name, sec_idx, sec_name);
4957 	nrels = shdr->sh_size / shdr->sh_entsize;
4958 
4959 	for (i = 0; i < nrels; i++) {
4960 		rel = elf_rel_by_idx(data, i);
4961 		if (!rel) {
4962 			pr_warn("sec '%s': failed to get relo #%d\n", relo_sec_name, i);
4963 			return -LIBBPF_ERRNO__FORMAT;
4964 		}
4965 
4966 		sym_idx = ELF64_R_SYM(rel->r_info);
4967 		sym = elf_sym_by_idx(obj, sym_idx);
4968 		if (!sym) {
4969 			pr_warn("sec '%s': symbol #%zu not found for relo #%d\n",
4970 				relo_sec_name, sym_idx, i);
4971 			return -LIBBPF_ERRNO__FORMAT;
4972 		}
4973 
4974 		if (sym->st_shndx >= obj->efile.sec_cnt) {
4975 			pr_warn("sec '%s': corrupted symbol #%zu pointing to invalid section #%zu for relo #%d\n",
4976 				relo_sec_name, sym_idx, (size_t)sym->st_shndx, i);
4977 			return -LIBBPF_ERRNO__FORMAT;
4978 		}
4979 
4980 		if (rel->r_offset % BPF_INSN_SZ || rel->r_offset >= scn_data->d_size) {
4981 			pr_warn("sec '%s': invalid offset 0x%zx for relo #%d\n",
4982 				relo_sec_name, (size_t)rel->r_offset, i);
4983 			return -LIBBPF_ERRNO__FORMAT;
4984 		}
4985 
4986 		insn_idx = rel->r_offset / BPF_INSN_SZ;
4987 		/* relocations against static functions are recorded as
4988 		 * relocations against the section that contains a function;
4989 		 * in such case, symbol will be STT_SECTION and sym.st_name
4990 		 * will point to empty string (0), so fetch section name
4991 		 * instead
4992 		 */
4993 		if (ELF64_ST_TYPE(sym->st_info) == STT_SECTION && sym->st_name == 0)
4994 			sym_name = elf_sec_name(obj, elf_sec_by_idx(obj, sym->st_shndx));
4995 		else
4996 			sym_name = elf_sym_str(obj, sym->st_name);
4997 		sym_name = sym_name ?: "<?";
4998 
4999 		pr_debug("sec '%s': relo #%d: insn #%u against '%s'\n",
5000 			 relo_sec_name, i, insn_idx, sym_name);
5001 
5002 		prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
5003 		if (!prog) {
5004 			pr_debug("sec '%s': relo #%d: couldn't find program in section '%s' for insn #%u, probably overridden weak function, skipping...\n",
5005 				relo_sec_name, i, sec_name, insn_idx);
5006 			continue;
5007 		}
5008 
5009 		relos = libbpf_reallocarray(prog->reloc_desc,
5010 					    prog->nr_reloc + 1, sizeof(*relos));
5011 		if (!relos)
5012 			return -ENOMEM;
5013 		prog->reloc_desc = relos;
5014 
5015 		/* adjust insn_idx to local BPF program frame of reference */
5016 		insn_idx -= prog->sec_insn_off;
5017 		err = bpf_program__record_reloc(prog, &relos[prog->nr_reloc],
5018 						insn_idx, sym_name, sym, rel);
5019 		if (err)
5020 			return err;
5021 
5022 		prog->nr_reloc++;
5023 	}
5024 	return 0;
5025 }
5026 
5027 static int map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map)
5028 {
5029 	int id;
5030 
5031 	if (!obj->btf)
5032 		return -ENOENT;
5033 
5034 	/* if it's BTF-defined map, we don't need to search for type IDs.
5035 	 * For struct_ops map, it does not need btf_key_type_id and
5036 	 * btf_value_type_id.
5037 	 */
5038 	if (map->sec_idx == obj->efile.btf_maps_shndx || bpf_map__is_struct_ops(map))
5039 		return 0;
5040 
5041 	/*
5042 	 * LLVM annotates global data differently in BTF, that is,
5043 	 * only as '.data', '.bss', '.percpu' or '.rodata'.
5044 	 */
5045 	if (!bpf_map__is_internal(map))
5046 		return -ENOENT;
5047 
5048 	id = btf__find_by_name(obj->btf, map->real_name);
5049 	if (id < 0)
5050 		return id;
5051 
5052 	map->btf_key_type_id = 0;
5053 	map->btf_value_type_id = id;
5054 	return 0;
5055 }
5056 
5057 static int bpf_get_map_info_from_fdinfo(int fd, struct bpf_map_info *info)
5058 {
5059 	char file[PATH_MAX], buff[4096];
5060 	FILE *fp;
5061 	__u32 val;
5062 	int err;
5063 
5064 	snprintf(file, sizeof(file), "/proc/%d/fdinfo/%d", getpid(), fd);
5065 	memset(info, 0, sizeof(*info));
5066 
5067 	fp = fopen(file, "re");
5068 	if (!fp) {
5069 		err = -errno;
5070 		pr_warn("failed to open %s: %s. No procfs support?\n", file,
5071 			errstr(err));
5072 		return err;
5073 	}
5074 
5075 	while (fgets(buff, sizeof(buff), fp)) {
5076 		if (sscanf(buff, "map_type:\t%u", &val) == 1)
5077 			info->type = val;
5078 		else if (sscanf(buff, "key_size:\t%u", &val) == 1)
5079 			info->key_size = val;
5080 		else if (sscanf(buff, "value_size:\t%u", &val) == 1)
5081 			info->value_size = val;
5082 		else if (sscanf(buff, "max_entries:\t%u", &val) == 1)
5083 			info->max_entries = val;
5084 		else if (sscanf(buff, "map_flags:\t%x", &val) == 1)
5085 			info->map_flags = val;
5086 	}
5087 
5088 	fclose(fp);
5089 
5090 	return 0;
5091 }
5092 
5093 static bool map_is_created(const struct bpf_map *map)
5094 {
5095 	return map->obj->state >= OBJ_PREPARED || map->reused;
5096 }
5097 
5098 bool bpf_map__autocreate(const struct bpf_map *map)
5099 {
5100 	return map->autocreate;
5101 }
5102 
5103 int bpf_map__set_autocreate(struct bpf_map *map, bool autocreate)
5104 {
5105 	if (map_is_created(map))
5106 		return libbpf_err(-EBUSY);
5107 
5108 	map->autocreate = autocreate;
5109 	return 0;
5110 }
5111 
5112 int bpf_map__set_autoattach(struct bpf_map *map, bool autoattach)
5113 {
5114 	if (!bpf_map__is_struct_ops(map))
5115 		return libbpf_err(-EINVAL);
5116 
5117 	map->autoattach = autoattach;
5118 	return 0;
5119 }
5120 
5121 bool bpf_map__autoattach(const struct bpf_map *map)
5122 {
5123 	return map->autoattach;
5124 }
5125 
5126 int bpf_map__reuse_fd(struct bpf_map *map, int fd)
5127 {
5128 	struct bpf_map_info info;
5129 	__u32 len = sizeof(info), name_len;
5130 	int new_fd, err;
5131 	char *new_name;
5132 
5133 	memset(&info, 0, len);
5134 	err = bpf_map_get_info_by_fd(fd, &info, &len);
5135 	if (err && errno == EINVAL)
5136 		err = bpf_get_map_info_from_fdinfo(fd, &info);
5137 	if (err)
5138 		return libbpf_err(err);
5139 
5140 	name_len = strlen(info.name);
5141 	if (name_len == BPF_OBJ_NAME_LEN - 1 && strncmp(map->name, info.name, name_len) == 0)
5142 		new_name = strdup(map->name);
5143 	else
5144 		new_name = strdup(info.name);
5145 
5146 	if (!new_name)
5147 		return libbpf_err(-errno);
5148 
5149 	/*
5150 	 * Like dup(), but make sure new FD is >= 3 and has O_CLOEXEC set.
5151 	 * This is similar to what we do in ensure_good_fd(), but without
5152 	 * closing original FD.
5153 	 */
5154 	new_fd = fcntl(fd, F_DUPFD_CLOEXEC, 3);
5155 	if (new_fd < 0) {
5156 		err = -errno;
5157 		goto err_free_new_name;
5158 	}
5159 
5160 	err = reuse_fd(map->fd, new_fd);
5161 	if (err)
5162 		goto err_free_new_name;
5163 
5164 	free(map->name);
5165 
5166 	map->name = new_name;
5167 	map->def.type = info.type;
5168 	map->def.key_size = info.key_size;
5169 	map->def.value_size = info.value_size;
5170 	map->def.max_entries = info.max_entries;
5171 	map->def.map_flags = info.map_flags;
5172 	map->btf_key_type_id = info.btf_key_type_id;
5173 	map->btf_value_type_id = info.btf_value_type_id;
5174 	map->reused = true;
5175 	map->map_extra = info.map_extra;
5176 
5177 	return 0;
5178 
5179 err_free_new_name:
5180 	free(new_name);
5181 	return libbpf_err(err);
5182 }
5183 
5184 __u32 bpf_map__max_entries(const struct bpf_map *map)
5185 {
5186 	return map->def.max_entries;
5187 }
5188 
5189 struct bpf_map *bpf_map__inner_map(struct bpf_map *map)
5190 {
5191 	if (!bpf_map_type__is_map_in_map(map->def.type))
5192 		return errno = EINVAL, NULL;
5193 
5194 	return map->inner_map;
5195 }
5196 
5197 int bpf_map__set_max_entries(struct bpf_map *map, __u32 max_entries)
5198 {
5199 	if (map_is_created(map))
5200 		return libbpf_err(-EBUSY);
5201 
5202 	map->def.max_entries = max_entries;
5203 
5204 	/* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
5205 	if (map_is_ringbuf(map))
5206 		map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
5207 
5208 	return 0;
5209 }
5210 
5211 static int bpf_object_prepare_token(struct bpf_object *obj)
5212 {
5213 	const char *bpffs_path;
5214 	int bpffs_fd = -1, token_fd, err;
5215 	bool mandatory;
5216 	enum libbpf_print_level level;
5217 
5218 	/* token is explicitly prevented */
5219 	if (obj->token_path && obj->token_path[0] == '\0') {
5220 		pr_debug("object '%s': token is prevented, skipping...\n", obj->name);
5221 		return 0;
5222 	}
5223 
5224 	mandatory = obj->token_path != NULL;
5225 	level = mandatory ? LIBBPF_WARN : LIBBPF_DEBUG;
5226 
5227 	bpffs_path = obj->token_path ?: BPF_FS_DEFAULT_PATH;
5228 	bpffs_fd = open(bpffs_path, O_DIRECTORY, O_RDWR);
5229 	if (bpffs_fd < 0) {
5230 		err = -errno;
5231 		__pr(level, "object '%s': failed (%s) to open BPF FS mount at '%s'%s\n",
5232 		     obj->name, errstr(err), bpffs_path,
5233 		     mandatory ? "" : ", skipping optional step...");
5234 		return mandatory ? err : 0;
5235 	}
5236 
5237 	token_fd = bpf_token_create(bpffs_fd, 0);
5238 	close(bpffs_fd);
5239 	if (token_fd < 0) {
5240 		if (!mandatory && token_fd == -ENOENT) {
5241 			pr_debug("object '%s': BPF FS at '%s' doesn't have BPF token delegation set up, skipping...\n",
5242 				 obj->name, bpffs_path);
5243 			return 0;
5244 		}
5245 		__pr(level, "object '%s': failed (%d) to create BPF token from '%s'%s\n",
5246 		     obj->name, token_fd, bpffs_path,
5247 		     mandatory ? "" : ", skipping optional step...");
5248 		return mandatory ? token_fd : 0;
5249 	}
5250 
5251 	obj->feat_cache = calloc(1, sizeof(*obj->feat_cache));
5252 	if (!obj->feat_cache) {
5253 		close(token_fd);
5254 		return -ENOMEM;
5255 	}
5256 
5257 	obj->token_fd = token_fd;
5258 	obj->feat_cache->token_fd = token_fd;
5259 
5260 	return 0;
5261 }
5262 
5263 static int
5264 bpf_object__probe_loading(struct bpf_object *obj)
5265 {
5266 	struct bpf_insn insns[] = {
5267 		BPF_MOV64_IMM(BPF_REG_0, 0),
5268 		BPF_EXIT_INSN(),
5269 	};
5270 	int ret, insn_cnt = ARRAY_SIZE(insns);
5271 
5272 	if (obj->gen_loader || obj->token_fd)
5273 		return 0;
5274 
5275 	ret = bump_rlimit_memlock();
5276 	if (ret)
5277 		pr_warn("Failed to bump RLIMIT_MEMLOCK (err = %s), you might need to do it explicitly!\n",
5278 			errstr(ret));
5279 
5280 	/* make sure basic loading works */
5281 	ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
5282 	if (ret < 0)
5283 		ret = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, NULL);
5284 	if (ret < 0) {
5285 		ret = errno;
5286 		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",
5287 			__func__, errstr(ret));
5288 		return -ret;
5289 	}
5290 	close(ret);
5291 
5292 	return 0;
5293 }
5294 
5295 bool kernel_supports(const struct bpf_object *obj, enum kern_feature_id feat_id)
5296 {
5297 	if (obj->gen_loader)
5298 		/* To generate loader program assume the latest kernel
5299 		 * to avoid doing extra prog_load, map_create syscalls.
5300 		 */
5301 		return true;
5302 
5303 	if (obj->feat_cache)
5304 		return feat_supported(obj->feat_cache, feat_id);
5305 
5306 	return feat_supported(NULL, feat_id);
5307 }
5308 
5309 /* Used in testing to simulate missing features. */
5310 void bpf_object_set_feat_cache(struct bpf_object *obj, struct kern_feature_cache *cache)
5311 {
5312 	if (obj->feat_cache)
5313 		free(obj->feat_cache);
5314 	obj->feat_cache = cache;
5315 }
5316 
5317 static bool map_is_reuse_compat(const struct bpf_map *map, int map_fd)
5318 {
5319 	struct bpf_map_info map_info;
5320 	__u32 map_info_len = sizeof(map_info);
5321 	int err;
5322 
5323 	memset(&map_info, 0, map_info_len);
5324 	err = bpf_map_get_info_by_fd(map_fd, &map_info, &map_info_len);
5325 	if (err && errno == EINVAL)
5326 		err = bpf_get_map_info_from_fdinfo(map_fd, &map_info);
5327 	if (err) {
5328 		pr_warn("failed to get map info for map FD %d: %s\n", map_fd,
5329 			errstr(err));
5330 		return false;
5331 	}
5332 
5333 	/*
5334 	 * bpf_get_map_info_by_fd() for DEVMAP will always return flags with
5335 	 * BPF_F_RDONLY_PROG set, but it generally is not set at map creation time.
5336 	 * Thus, ignore the BPF_F_RDONLY_PROG flag in the flags returned from
5337 	 * bpf_get_map_info_by_fd() when checking for compatibility with an
5338 	 * existing DEVMAP.
5339 	 */
5340 	if (map->def.type == BPF_MAP_TYPE_DEVMAP || map->def.type == BPF_MAP_TYPE_DEVMAP_HASH)
5341 		map_info.map_flags &= ~BPF_F_RDONLY_PROG;
5342 
5343 	return (map_info.type == map->def.type &&
5344 		map_info.key_size == map->def.key_size &&
5345 		map_info.value_size == map->def.value_size &&
5346 		map_info.max_entries == map->def.max_entries &&
5347 		map_info.map_flags == map->def.map_flags &&
5348 		map_info.map_extra == map->map_extra);
5349 }
5350 
5351 static int
5352 bpf_object__reuse_map(struct bpf_map *map)
5353 {
5354 	int err, pin_fd;
5355 
5356 	pin_fd = bpf_obj_get(map->pin_path);
5357 	if (pin_fd < 0) {
5358 		err = -errno;
5359 		if (err == -ENOENT) {
5360 			pr_debug("found no pinned map to reuse at '%s'\n",
5361 				 map->pin_path);
5362 			return 0;
5363 		}
5364 
5365 		pr_warn("couldn't retrieve pinned map '%s': %s\n",
5366 			map->pin_path, errstr(err));
5367 		return err;
5368 	}
5369 
5370 	if (!map_is_reuse_compat(map, pin_fd)) {
5371 		pr_warn("couldn't reuse pinned map at '%s': parameter mismatch\n",
5372 			map->pin_path);
5373 		close(pin_fd);
5374 		return -EINVAL;
5375 	}
5376 
5377 	err = bpf_map__reuse_fd(map, pin_fd);
5378 	close(pin_fd);
5379 	if (err)
5380 		return err;
5381 
5382 	map->pinned = true;
5383 	pr_debug("reused pinned map at '%s'\n", map->pin_path);
5384 
5385 	return 0;
5386 }
5387 
5388 static int
5389 bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
5390 {
5391 	enum libbpf_map_type map_type = map->libbpf_type;
5392 	bool is_percpu = map_type == LIBBPF_MAP_PERCPU;
5393 	const __u64 update_flags = is_percpu ? BPF_F_ALL_CPUS : 0;
5394 	int err, zero = 0;
5395 	size_t mmap_sz;
5396 
5397 	if (obj->gen_loader) {
5398 		bpf_gen__map_update_elem(obj->gen_loader, map - obj->maps,
5399 					 map->mmaped, map->def.value_size, update_flags);
5400 		if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG)
5401 			bpf_gen__map_freeze(obj->gen_loader, map - obj->maps);
5402 		return 0;
5403 	}
5404 
5405 	err = bpf_map_update_elem(map->fd, &zero, map->mmaped, update_flags);
5406 	if (err) {
5407 		err = -errno;
5408 		pr_warn("map '%s': failed to set initial contents: %s\n",
5409 			bpf_map__name(map), errstr(err));
5410 		return err;
5411 	}
5412 
5413 	/* Freeze .rodata and .kconfig map as read-only from syscall side. */
5414 	if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG) {
5415 		err = bpf_map_freeze(map->fd);
5416 		if (err) {
5417 			err = -errno;
5418 			pr_warn("map '%s': failed to freeze as read-only: %s\n",
5419 				bpf_map__name(map), errstr(err));
5420 			return err;
5421 		}
5422 	}
5423 
5424 	/* Remap anonymous mmap()-ed "map initialization image" as
5425 	 * a BPF map-backed mmap()-ed memory, but preserving the same
5426 	 * memory address. This will cause kernel to change process'
5427 	 * page table to point to a different piece of kernel memory,
5428 	 * but from userspace point of view memory address (and its
5429 	 * contents, being identical at this point) will stay the
5430 	 * same. This mapping will be released by bpf_object__close()
5431 	 * as per normal clean up procedure.
5432 	 */
5433 	mmap_sz = bpf_map_mmap_sz(map);
5434 	if (map->def.map_flags & BPF_F_MMAPABLE) {
5435 		void *mmaped;
5436 		int prot;
5437 
5438 		if (map->def.map_flags & BPF_F_RDONLY_PROG)
5439 			prot = PROT_READ;
5440 		else
5441 			prot = PROT_READ | PROT_WRITE;
5442 		mmaped = mmap(map->mmaped, mmap_sz, prot, MAP_SHARED | MAP_FIXED, map->fd, 0);
5443 		if (mmaped == MAP_FAILED) {
5444 			err = -errno;
5445 			pr_warn("map '%s': failed to re-mmap() contents: %s\n",
5446 				bpf_map__name(map), errstr(err));
5447 			return err;
5448 		}
5449 		map->mmaped = mmaped;
5450 	} else if (is_percpu) {
5451 		if (mprotect(map->mmaped, mmap_sz, PROT_READ)) {
5452 			err = -errno;
5453 			pr_warn("map '%s': failed to mprotect() contents: %s\n",
5454 				bpf_map__name(map), errstr(err));
5455 			return err;
5456 		}
5457 	} else if (map->mmaped) {
5458 		munmap(map->mmaped, mmap_sz);
5459 		map->mmaped = NULL;
5460 	}
5461 
5462 	return 0;
5463 }
5464 
5465 static void bpf_map__destroy(struct bpf_map *map);
5466 
5467 static int bpf_object__create_map(struct bpf_object *obj, struct bpf_map *map, bool is_inner)
5468 {
5469 	LIBBPF_OPTS(bpf_map_create_opts, create_attr);
5470 	struct bpf_map_def *def = &map->def;
5471 	const char *map_name = NULL;
5472 	int err = 0, map_fd;
5473 
5474 	if (kernel_supports(obj, FEAT_PROG_NAME))
5475 		map_name = map->name;
5476 	create_attr.map_ifindex = map->map_ifindex;
5477 	create_attr.map_flags = def->map_flags;
5478 	create_attr.numa_node = map->numa_node;
5479 	create_attr.map_extra = map->map_extra;
5480 	create_attr.token_fd = obj->token_fd;
5481 	if (obj->token_fd)
5482 		create_attr.map_flags |= BPF_F_TOKEN_FD;
5483 	if (map->excl_prog) {
5484 		err = bpf_prog_compute_hash(map->excl_prog);
5485 		if (err)
5486 			return err;
5487 
5488 		create_attr.excl_prog_hash = map->excl_prog->hash;
5489 		create_attr.excl_prog_hash_size = SHA256_DIGEST_LENGTH;
5490 	}
5491 
5492 	if (bpf_map__is_struct_ops(map)) {
5493 		create_attr.btf_vmlinux_value_type_id = map->btf_vmlinux_value_type_id;
5494 		if (map->mod_btf_fd >= 0) {
5495 			create_attr.value_type_btf_obj_fd = map->mod_btf_fd;
5496 			create_attr.map_flags |= BPF_F_VTYPE_BTF_OBJ_FD;
5497 		}
5498 	}
5499 
5500 	if (obj->btf && btf__fd(obj->btf) >= 0) {
5501 		create_attr.btf_fd = btf__fd(obj->btf);
5502 		create_attr.btf_key_type_id = map->btf_key_type_id;
5503 		create_attr.btf_value_type_id = map->btf_value_type_id;
5504 	}
5505 
5506 	if (bpf_map_type__is_map_in_map(def->type)) {
5507 		if (map->inner_map) {
5508 			err = map_set_def_max_entries(map->inner_map);
5509 			if (err)
5510 				return err;
5511 			err = bpf_object__create_map(obj, map->inner_map, true);
5512 			if (err) {
5513 				pr_warn("map '%s': failed to create inner map: %s\n",
5514 					map->name, errstr(err));
5515 				return err;
5516 			}
5517 			map->inner_map_fd = map->inner_map->fd;
5518 		}
5519 		if (map->inner_map_fd >= 0)
5520 			create_attr.inner_map_fd = map->inner_map_fd;
5521 	}
5522 
5523 	switch (def->type) {
5524 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
5525 	case BPF_MAP_TYPE_CGROUP_ARRAY:
5526 	case BPF_MAP_TYPE_STACK_TRACE:
5527 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
5528 	case BPF_MAP_TYPE_HASH_OF_MAPS:
5529 	case BPF_MAP_TYPE_DEVMAP:
5530 	case BPF_MAP_TYPE_DEVMAP_HASH:
5531 	case BPF_MAP_TYPE_CPUMAP:
5532 	case BPF_MAP_TYPE_XSKMAP:
5533 	case BPF_MAP_TYPE_SOCKMAP:
5534 	case BPF_MAP_TYPE_SOCKHASH:
5535 	case BPF_MAP_TYPE_QUEUE:
5536 	case BPF_MAP_TYPE_STACK:
5537 	case BPF_MAP_TYPE_ARENA:
5538 		create_attr.btf_fd = 0;
5539 		create_attr.btf_key_type_id = 0;
5540 		create_attr.btf_value_type_id = 0;
5541 		map->btf_key_type_id = 0;
5542 		map->btf_value_type_id = 0;
5543 		break;
5544 	case BPF_MAP_TYPE_STRUCT_OPS:
5545 		create_attr.btf_value_type_id = 0;
5546 		break;
5547 	default:
5548 		break;
5549 	}
5550 
5551 	if (obj->gen_loader) {
5552 		bpf_gen__map_create(obj->gen_loader, def->type, map_name,
5553 				    def->key_size, def->value_size, def->max_entries,
5554 				    &create_attr, is_inner ? -1 : map - obj->maps);
5555 		/* We keep pretenting we have valid FD to pass various fd >= 0
5556 		 * checks by just keeping original placeholder FDs in place.
5557 		 * See bpf_object__add_map() comment.
5558 		 * This placeholder fd will not be used with any syscall and
5559 		 * will be reset to -1 eventually.
5560 		 */
5561 		map_fd = map->fd;
5562 	} else {
5563 		map_fd = bpf_map_create(def->type, map_name,
5564 					def->key_size, def->value_size,
5565 					def->max_entries, &create_attr);
5566 	}
5567 	if (map_fd < 0 && (create_attr.btf_key_type_id || create_attr.btf_value_type_id)) {
5568 		err = -errno;
5569 		pr_warn("Error in bpf_create_map_xattr(%s): %s. Retrying without BTF.\n",
5570 			map->name, errstr(err));
5571 		create_attr.btf_fd = 0;
5572 		create_attr.btf_key_type_id = 0;
5573 		create_attr.btf_value_type_id = 0;
5574 		map->btf_key_type_id = 0;
5575 		map->btf_value_type_id = 0;
5576 		map_fd = bpf_map_create(def->type, map_name,
5577 					def->key_size, def->value_size,
5578 					def->max_entries, &create_attr);
5579 	}
5580 
5581 	if (bpf_map_type__is_map_in_map(def->type) && map->inner_map) {
5582 		if (obj->gen_loader)
5583 			map->inner_map->fd = -1;
5584 		bpf_map__destroy(map->inner_map);
5585 		zfree(&map->inner_map);
5586 	}
5587 
5588 	if (map_fd < 0)
5589 		return map_fd;
5590 
5591 	/* obj->gen_loader case, prevent reuse_fd() from closing map_fd */
5592 	if (map->fd == map_fd)
5593 		return 0;
5594 
5595 	/* Keep placeholder FD value but now point it to the BPF map object.
5596 	 * This way everything that relied on this map's FD (e.g., relocated
5597 	 * ldimm64 instructions) will stay valid and won't need adjustments.
5598 	 * map->fd stays valid but now point to what map_fd points to.
5599 	 */
5600 	return reuse_fd(map->fd, map_fd);
5601 }
5602 
5603 static int init_map_in_map_slots(struct bpf_object *obj, struct bpf_map *map)
5604 {
5605 	const struct bpf_map *targ_map;
5606 	unsigned int i;
5607 	int fd, err = 0;
5608 
5609 	for (i = 0; i < map->init_slots_sz; i++) {
5610 		if (!map->init_slots[i])
5611 			continue;
5612 
5613 		targ_map = map->init_slots[i];
5614 		fd = targ_map->fd;
5615 
5616 		if (obj->gen_loader) {
5617 			bpf_gen__populate_outer_map(obj->gen_loader,
5618 						    map - obj->maps, i,
5619 						    targ_map - obj->maps);
5620 		} else {
5621 			err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5622 		}
5623 		if (err) {
5624 			err = -errno;
5625 			pr_warn("map '%s': failed to initialize slot [%u] to map '%s' fd=%d: %s\n",
5626 				map->name, i, targ_map->name, fd, errstr(err));
5627 			return err;
5628 		}
5629 		pr_debug("map '%s': slot [%u] set to map '%s' fd=%d\n",
5630 			 map->name, i, targ_map->name, fd);
5631 	}
5632 
5633 	zfree(&map->init_slots);
5634 	map->init_slots_sz = 0;
5635 
5636 	return 0;
5637 }
5638 
5639 static int init_prog_array_slots(struct bpf_object *obj, struct bpf_map *map)
5640 {
5641 	const struct bpf_program *targ_prog;
5642 	unsigned int i;
5643 	int fd, err;
5644 
5645 	if (obj->gen_loader)
5646 		return -ENOTSUP;
5647 
5648 	for (i = 0; i < map->init_slots_sz; i++) {
5649 		if (!map->init_slots[i])
5650 			continue;
5651 
5652 		targ_prog = map->init_slots[i];
5653 		fd = bpf_program__fd(targ_prog);
5654 
5655 		err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5656 		if (err) {
5657 			err = -errno;
5658 			pr_warn("map '%s': failed to initialize slot [%u] to prog '%s' fd=%d: %s\n",
5659 				map->name, i, targ_prog->name, fd, errstr(err));
5660 			return err;
5661 		}
5662 		pr_debug("map '%s': slot [%u] set to prog '%s' fd=%d\n",
5663 			 map->name, i, targ_prog->name, fd);
5664 	}
5665 
5666 	zfree(&map->init_slots);
5667 	map->init_slots_sz = 0;
5668 
5669 	return 0;
5670 }
5671 
5672 static int bpf_object_init_prog_arrays(struct bpf_object *obj)
5673 {
5674 	struct bpf_map *map;
5675 	int i, err;
5676 
5677 	for (i = 0; i < obj->nr_maps; i++) {
5678 		map = &obj->maps[i];
5679 
5680 		if (!map->init_slots_sz || map->def.type != BPF_MAP_TYPE_PROG_ARRAY)
5681 			continue;
5682 
5683 		err = init_prog_array_slots(obj, map);
5684 		if (err < 0)
5685 			return err;
5686 	}
5687 	return 0;
5688 }
5689 
5690 static int map_set_def_max_entries(struct bpf_map *map)
5691 {
5692 	if (map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY && !map->def.max_entries) {
5693 		int nr_cpus;
5694 
5695 		nr_cpus = libbpf_num_possible_cpus();
5696 		if (nr_cpus < 0) {
5697 			pr_warn("map '%s': failed to determine number of system CPUs: %d\n",
5698 				map->name, nr_cpus);
5699 			return nr_cpus;
5700 		}
5701 		pr_debug("map '%s': setting size to %d\n", map->name, nr_cpus);
5702 		map->def.max_entries = nr_cpus;
5703 	}
5704 
5705 	return 0;
5706 }
5707 
5708 static int
5709 bpf_object__create_maps(struct bpf_object *obj)
5710 {
5711 	struct bpf_map *map;
5712 	unsigned int i, j;
5713 	int err;
5714 	bool retried;
5715 
5716 	for (i = 0; i < obj->nr_maps; i++) {
5717 		map = &obj->maps[i];
5718 
5719 		/* To support old kernels, we skip creating global data maps
5720 		 * (.rodata, .data, .kconfig, etc); later on, during program
5721 		 * loading, if we detect that at least one of the to-be-loaded
5722 		 * programs is referencing any global data map, we'll error
5723 		 * out with program name and relocation index logged.
5724 		 * This approach allows to accommodate Clang emitting
5725 		 * unnecessary .rodata.str1.1 sections for string literals,
5726 		 * but also it allows to have CO-RE applications that use
5727 		 * global variables in some of BPF programs, but not others.
5728 		 * If those global variable-using programs are not loaded at
5729 		 * runtime due to bpf_program__set_autoload(prog, false),
5730 		 * bpf_object loading will succeed just fine even on old
5731 		 * kernels.
5732 		 * Same skipping applies to percpu data.
5733 		 */
5734 		if (bpf_map__is_internal(map)) {
5735 			bool is_percpu = map->libbpf_type == LIBBPF_MAP_PERCPU;
5736 			enum kern_feature_id feat_id;
5737 
5738 			feat_id = is_percpu ? FEAT_PERCPU_DATA : FEAT_GLOBAL_DATA;
5739 			if (!kernel_supports(obj, feat_id))
5740 				map->autocreate = false;
5741 		}
5742 
5743 		if (!map->autocreate) {
5744 			pr_debug("map '%s': skipped auto-creating...\n", map->name);
5745 			continue;
5746 		}
5747 
5748 		err = map_set_def_max_entries(map);
5749 		if (err)
5750 			goto err_out;
5751 
5752 		retried = false;
5753 retry:
5754 		if (map->pin_path) {
5755 			err = bpf_object__reuse_map(map);
5756 			if (err) {
5757 				pr_warn("map '%s': error reusing pinned map\n",
5758 					map->name);
5759 				goto err_out;
5760 			}
5761 			if (retried && map->fd < 0) {
5762 				pr_warn("map '%s': cannot find pinned map\n",
5763 					map->name);
5764 				err = -ENOENT;
5765 				goto err_out;
5766 			}
5767 		}
5768 
5769 		if (map->reused) {
5770 			pr_debug("map '%s': skipping creation (preset fd=%d)\n",
5771 				 map->name, map->fd);
5772 		} else {
5773 			err = bpf_object__create_map(obj, map, false);
5774 			if (err)
5775 				goto err_out;
5776 
5777 			pr_debug("map '%s': created successfully, fd=%d\n",
5778 				 map->name, map->fd);
5779 
5780 			if (bpf_map__is_internal(map)) {
5781 				err = bpf_object__populate_internal_map(obj, map);
5782 				if (err < 0)
5783 					goto err_out;
5784 			} else if (map->def.type == BPF_MAP_TYPE_ARENA) {
5785 				map->mmaped = mmap((void *)(long)map->map_extra,
5786 						   bpf_map_mmap_sz(map), PROT_READ | PROT_WRITE,
5787 						   map->map_extra ? MAP_SHARED | MAP_FIXED : MAP_SHARED,
5788 						   map->fd, 0);
5789 				if (map->mmaped == MAP_FAILED) {
5790 					err = -errno;
5791 					map->mmaped = NULL;
5792 					pr_warn("map '%s': failed to mmap arena: %s\n",
5793 						map->name, errstr(err));
5794 					return err;
5795 				}
5796 				if (obj->arena_data) {
5797 					memcpy(map->mmaped + obj->arena_data_off, obj->arena_data,
5798 						obj->arena_data_sz);
5799 					zfree(&obj->arena_data);
5800 				}
5801 			}
5802 			if (map->init_slots_sz && map->def.type != BPF_MAP_TYPE_PROG_ARRAY) {
5803 				err = init_map_in_map_slots(obj, map);
5804 				if (err < 0)
5805 					goto err_out;
5806 			}
5807 		}
5808 
5809 		if (map->pin_path && !map->pinned) {
5810 			err = bpf_map__pin(map, NULL);
5811 			if (err) {
5812 				if (!retried && err == -EEXIST) {
5813 					retried = true;
5814 					goto retry;
5815 				}
5816 				pr_warn("map '%s': failed to auto-pin at '%s': %s\n",
5817 					map->name, map->pin_path, errstr(err));
5818 				goto err_out;
5819 			}
5820 		}
5821 	}
5822 
5823 	return 0;
5824 
5825 err_out:
5826 	pr_warn("map '%s': failed to create: %s\n", map->name, errstr(err));
5827 	pr_perm_msg(err);
5828 	for (j = 0; j < i; j++)
5829 		zclose(obj->maps[j].fd);
5830 	return err;
5831 }
5832 
5833 static bool bpf_core_is_flavor_sep(const char *s)
5834 {
5835 	/* check X___Y name pattern, where X and Y are not underscores */
5836 	return s[0] != '_' &&				      /* X */
5837 	       s[1] == '_' && s[2] == '_' && s[3] == '_' &&   /* ___ */
5838 	       s[4] != '_';				      /* Y */
5839 }
5840 
5841 /* Given 'some_struct_name___with_flavor' return the length of a name prefix
5842  * before last triple underscore. Struct name part after last triple
5843  * underscore is ignored by BPF CO-RE relocation during relocation matching.
5844  */
5845 size_t bpf_core_essential_name_len(const char *name)
5846 {
5847 	size_t n = strlen(name);
5848 	int i;
5849 
5850 	for (i = n - 5; i >= 0; i--) {
5851 		if (bpf_core_is_flavor_sep(name + i))
5852 			return i + 1;
5853 	}
5854 	return n;
5855 }
5856 
5857 void bpf_core_free_cands(struct bpf_core_cand_list *cands)
5858 {
5859 	if (!cands)
5860 		return;
5861 
5862 	free(cands->cands);
5863 	free(cands);
5864 }
5865 
5866 int bpf_core_add_cands(struct bpf_core_cand *local_cand,
5867 		       size_t local_essent_len,
5868 		       const struct btf *targ_btf,
5869 		       const char *targ_btf_name,
5870 		       int targ_start_id,
5871 		       struct bpf_core_cand_list *cands)
5872 {
5873 	struct bpf_core_cand *new_cands, *cand;
5874 	const struct btf_type *t, *local_t;
5875 	const char *targ_name, *local_name;
5876 	size_t targ_essent_len;
5877 	int n, i;
5878 
5879 	local_t = btf__type_by_id(local_cand->btf, local_cand->id);
5880 	local_name = btf__str_by_offset(local_cand->btf, local_t->name_off);
5881 
5882 	n = btf__type_cnt(targ_btf);
5883 	for (i = targ_start_id; i < n; i++) {
5884 		t = btf__type_by_id(targ_btf, i);
5885 		if (!btf_kind_core_compat(t, local_t))
5886 			continue;
5887 
5888 		targ_name = btf__name_by_offset(targ_btf, t->name_off);
5889 		if (str_is_empty(targ_name))
5890 			continue;
5891 
5892 		targ_essent_len = bpf_core_essential_name_len(targ_name);
5893 		if (targ_essent_len != local_essent_len)
5894 			continue;
5895 
5896 		if (strncmp(local_name, targ_name, local_essent_len) != 0)
5897 			continue;
5898 
5899 		pr_debug("CO-RE relocating [%u] %s %s: found target candidate [%d] %s %s in [%s]\n",
5900 			 local_cand->id, btf_kind_str(local_t),
5901 			 local_name, i, btf_kind_str(t), targ_name,
5902 			 targ_btf_name);
5903 		new_cands = libbpf_reallocarray(cands->cands, cands->len + 1,
5904 					      sizeof(*cands->cands));
5905 		if (!new_cands)
5906 			return -ENOMEM;
5907 
5908 		cand = &new_cands[cands->len];
5909 		cand->btf = targ_btf;
5910 		cand->id = i;
5911 
5912 		cands->cands = new_cands;
5913 		cands->len++;
5914 	}
5915 	return 0;
5916 }
5917 
5918 static bool is_btf_mod_allowed(const struct bpf_object *obj, const char *name)
5919 {
5920 	ssize_t i;
5921 
5922 	if (obj->btf_module_allowlist_cnt < 0)
5923 		return true;
5924 
5925 	for (i = 0; i < obj->btf_module_allowlist_cnt; i++) {
5926 		if (strcmp(obj->btf_module_allowlist[i], name) == 0)
5927 			return true;
5928 	}
5929 
5930 	return false;
5931 }
5932 
5933 static int load_module_btfs(struct bpf_object *obj)
5934 {
5935 	struct bpf_btf_info info;
5936 	struct module_btf *mod_btf;
5937 	struct btf *btf;
5938 	char name[64];
5939 	__u32 id = 0, len;
5940 	int err, fd;
5941 
5942 	if (obj->btf_modules_loaded)
5943 		return 0;
5944 
5945 	if (obj->gen_loader)
5946 		return 0;
5947 
5948 	/* don't do this again, even if we find no module BTFs */
5949 	obj->btf_modules_loaded = true;
5950 
5951 	/* kernel too old to support module BTFs */
5952 	if (!kernel_supports(obj, FEAT_MODULE_BTF))
5953 		return 0;
5954 
5955 	if (obj->btf_module_allowlist_cnt == 0)
5956 		return 0;
5957 
5958 	while (true) {
5959 		err = bpf_btf_get_next_id(id, &id);
5960 		if (err && errno == ENOENT)
5961 			return 0;
5962 		if (err && errno == EPERM) {
5963 			pr_debug("skipping module BTFs loading, missing privileges\n");
5964 			return 0;
5965 		}
5966 		if (err) {
5967 			err = -errno;
5968 			pr_warn("failed to iterate BTF objects: %s\n", errstr(err));
5969 			return err;
5970 		}
5971 
5972 		fd = bpf_btf_get_fd_by_id(id);
5973 		if (fd < 0) {
5974 			if (errno == ENOENT)
5975 				continue; /* expected race: BTF was unloaded */
5976 			err = -errno;
5977 			pr_warn("failed to get BTF object #%u FD: %s\n", id, errstr(err));
5978 			return err;
5979 		}
5980 
5981 		len = sizeof(info);
5982 		memset(&info, 0, sizeof(info));
5983 		info.name = ptr_to_u64(name);
5984 		info.name_len = sizeof(name);
5985 
5986 		btf = NULL;
5987 		err = bpf_btf_get_info_by_fd(fd, &info, &len);
5988 		if (err) {
5989 			err = -errno;
5990 			pr_warn("failed to get BTF object #%u info: %s\n", id, errstr(err));
5991 			break;
5992 		}
5993 
5994 		/* ignore non-module BTFs */
5995 		if (!info.kernel_btf || strcmp(name, "vmlinux") == 0) {
5996 			close(fd);
5997 			continue;
5998 		}
5999 
6000 		if (!is_btf_mod_allowed(obj, name)) {
6001 			close(fd);
6002 			continue;
6003 		}
6004 
6005 		btf = btf_get_from_fd(fd, obj->btf_vmlinux);
6006 		err = libbpf_get_error(btf);
6007 		if (err) {
6008 			pr_warn("failed to load module [%s]'s BTF object #%u: %s\n",
6009 				name, id, errstr(err));
6010 			break;
6011 		}
6012 
6013 		err = libbpf_ensure_mem((void **)&obj->btf_modules, &obj->btf_module_cap,
6014 					sizeof(*obj->btf_modules), obj->btf_module_cnt + 1);
6015 		if (err)
6016 			break;
6017 
6018 		mod_btf = &obj->btf_modules[obj->btf_module_cnt];
6019 
6020 		mod_btf->btf = btf;
6021 		mod_btf->id = id;
6022 		mod_btf->fd = fd;
6023 		mod_btf->name = strdup(name);
6024 		if (!mod_btf->name) {
6025 			err = -ENOMEM;
6026 			break;
6027 		}
6028 		obj->btf_module_cnt++;
6029 
6030 		if (obj->btf_module_allowlist_cnt == obj->btf_module_cnt)
6031 			break;
6032 	}
6033 
6034 	if (err) {
6035 		btf__free(btf);
6036 		close(fd);
6037 	}
6038 	return err;
6039 }
6040 
6041 static struct bpf_core_cand_list *
6042 bpf_core_find_cands(struct bpf_object *obj, const struct btf *local_btf, __u32 local_type_id)
6043 {
6044 	struct bpf_core_cand local_cand = {};
6045 	struct bpf_core_cand_list *cands;
6046 	const struct btf *main_btf;
6047 	const struct btf_type *local_t;
6048 	const char *local_name;
6049 	size_t local_essent_len;
6050 	int err, i;
6051 
6052 	local_cand.btf = local_btf;
6053 	local_cand.id = local_type_id;
6054 	local_t = btf__type_by_id(local_btf, local_type_id);
6055 	if (!local_t)
6056 		return ERR_PTR(-EINVAL);
6057 
6058 	local_name = btf__name_by_offset(local_btf, local_t->name_off);
6059 	if (str_is_empty(local_name))
6060 		return ERR_PTR(-EINVAL);
6061 	local_essent_len = bpf_core_essential_name_len(local_name);
6062 
6063 	cands = calloc(1, sizeof(*cands));
6064 	if (!cands)
6065 		return ERR_PTR(-ENOMEM);
6066 
6067 	/* Attempt to find target candidates in vmlinux BTF first */
6068 	main_btf = obj->btf_vmlinux_override ?: obj->btf_vmlinux;
6069 	err = bpf_core_add_cands(&local_cand, local_essent_len, main_btf, "vmlinux", 1, cands);
6070 	if (err)
6071 		goto err_out;
6072 
6073 	/* if vmlinux BTF has any candidate, don't got for module BTFs */
6074 	if (cands->len)
6075 		return cands;
6076 
6077 	/* if vmlinux BTF was overridden, don't attempt to load module BTFs */
6078 	if (obj->btf_vmlinux_override)
6079 		return cands;
6080 
6081 	/* now look through module BTFs, trying to still find candidates */
6082 	err = load_module_btfs(obj);
6083 	if (err)
6084 		goto err_out;
6085 
6086 	for (i = 0; i < obj->btf_module_cnt; i++) {
6087 		err = bpf_core_add_cands(&local_cand, local_essent_len,
6088 					 obj->btf_modules[i].btf,
6089 					 obj->btf_modules[i].name,
6090 					 btf__type_cnt(obj->btf_vmlinux),
6091 					 cands);
6092 		if (err)
6093 			goto err_out;
6094 	}
6095 
6096 	return cands;
6097 err_out:
6098 	bpf_core_free_cands(cands);
6099 	return ERR_PTR(err);
6100 }
6101 
6102 /* Check local and target types for compatibility. This check is used for
6103  * type-based CO-RE relocations and follow slightly different rules than
6104  * field-based relocations. This function assumes that root types were already
6105  * checked for name match. Beyond that initial root-level name check, names
6106  * are completely ignored. Compatibility rules are as follows:
6107  *   - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs are considered compatible, but
6108  *     kind should match for local and target types (i.e., STRUCT is not
6109  *     compatible with UNION);
6110  *   - for ENUMs, the size is ignored;
6111  *   - for INT, size and signedness are ignored;
6112  *   - for ARRAY, dimensionality is ignored, element types are checked for
6113  *     compatibility recursively;
6114  *   - CONST/VOLATILE/RESTRICT modifiers are ignored;
6115  *   - TYPEDEFs/PTRs are compatible if types they pointing to are compatible;
6116  *   - FUNC_PROTOs are compatible if they have compatible signature: same
6117  *     number of input args and compatible return and argument types.
6118  * These rules are not set in stone and probably will be adjusted as we get
6119  * more experience with using BPF CO-RE relocations.
6120  */
6121 int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
6122 			      const struct btf *targ_btf, __u32 targ_id)
6123 {
6124 	return __bpf_core_types_are_compat(local_btf, local_id, targ_btf, targ_id, 32);
6125 }
6126 
6127 int bpf_core_types_match(const struct btf *local_btf, __u32 local_id,
6128 			 const struct btf *targ_btf, __u32 targ_id)
6129 {
6130 	return __bpf_core_types_match(local_btf, local_id, targ_btf, targ_id, false, 32);
6131 }
6132 
6133 static size_t bpf_core_hash_fn(const long key, void *ctx)
6134 {
6135 	return key;
6136 }
6137 
6138 static bool bpf_core_equal_fn(const long k1, const long k2, void *ctx)
6139 {
6140 	return k1 == k2;
6141 }
6142 
6143 static int record_relo_core(struct bpf_program *prog,
6144 			    const struct bpf_core_relo *core_relo, int insn_idx)
6145 {
6146 	struct reloc_desc *relos, *relo;
6147 
6148 	relos = libbpf_reallocarray(prog->reloc_desc,
6149 				    prog->nr_reloc + 1, sizeof(*relos));
6150 	if (!relos)
6151 		return -ENOMEM;
6152 	relo = &relos[prog->nr_reloc];
6153 	relo->type = RELO_CORE;
6154 	relo->insn_idx = insn_idx;
6155 	relo->core_relo = core_relo;
6156 	prog->reloc_desc = relos;
6157 	prog->nr_reloc++;
6158 	return 0;
6159 }
6160 
6161 static const struct bpf_core_relo *find_relo_core(struct bpf_program *prog, int insn_idx)
6162 {
6163 	struct reloc_desc *relo;
6164 	int i;
6165 
6166 	for (i = 0; i < prog->nr_reloc; i++) {
6167 		relo = &prog->reloc_desc[i];
6168 		if (relo->type != RELO_CORE || relo->insn_idx != insn_idx)
6169 			continue;
6170 
6171 		return relo->core_relo;
6172 	}
6173 
6174 	return NULL;
6175 }
6176 
6177 static int bpf_core_resolve_relo(struct bpf_program *prog,
6178 				 const struct bpf_core_relo *relo,
6179 				 int relo_idx,
6180 				 const struct btf *local_btf,
6181 				 struct hashmap *cand_cache,
6182 				 struct bpf_core_relo_res *targ_res)
6183 {
6184 	struct bpf_core_spec specs_scratch[3] = {};
6185 	struct bpf_core_cand_list *cands = NULL;
6186 	const char *prog_name = prog->name;
6187 	const struct btf_type *local_type;
6188 	const char *local_name;
6189 	__u32 local_id = relo->type_id;
6190 	int err;
6191 
6192 	local_type = btf__type_by_id(local_btf, local_id);
6193 	if (!local_type)
6194 		return -EINVAL;
6195 
6196 	local_name = btf__name_by_offset(local_btf, local_type->name_off);
6197 	if (!local_name)
6198 		return -EINVAL;
6199 
6200 	if (relo->kind != BPF_CORE_TYPE_ID_LOCAL &&
6201 	    !hashmap__find(cand_cache, local_id, &cands)) {
6202 		cands = bpf_core_find_cands(prog->obj, local_btf, local_id);
6203 		if (IS_ERR(cands)) {
6204 			pr_warn("prog '%s': relo #%d: target candidate search failed for [%u] %s %s: %ld\n",
6205 				prog_name, relo_idx, local_id, btf_kind_str(local_type),
6206 				local_name, PTR_ERR(cands));
6207 			return PTR_ERR(cands);
6208 		}
6209 		err = hashmap__set(cand_cache, local_id, cands, NULL, NULL);
6210 		if (err) {
6211 			bpf_core_free_cands(cands);
6212 			return err;
6213 		}
6214 	}
6215 
6216 	return bpf_core_calc_relo_insn(prog_name, relo, relo_idx, local_btf, cands, specs_scratch,
6217 				       targ_res);
6218 }
6219 
6220 static int
6221 bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
6222 {
6223 	const struct btf_ext_info_sec *sec;
6224 	struct bpf_core_relo_res targ_res;
6225 	const struct bpf_core_relo *rec;
6226 	const struct btf_ext_info *seg;
6227 	struct hashmap_entry *entry;
6228 	struct hashmap *cand_cache = NULL;
6229 	struct bpf_program *prog;
6230 	struct bpf_insn *insn;
6231 	const char *sec_name;
6232 	int i, err = 0, insn_idx, sec_idx, sec_num;
6233 
6234 	if (obj->btf_ext->core_relo_info.len == 0)
6235 		return 0;
6236 
6237 	if (targ_btf_path) {
6238 		obj->btf_vmlinux_override = btf__parse(targ_btf_path, NULL);
6239 		err = libbpf_get_error(obj->btf_vmlinux_override);
6240 		if (err) {
6241 			pr_warn("failed to parse target BTF: %s\n", errstr(err));
6242 			return err;
6243 		}
6244 	}
6245 
6246 	cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
6247 	if (IS_ERR(cand_cache)) {
6248 		err = PTR_ERR(cand_cache);
6249 		goto out;
6250 	}
6251 
6252 	seg = &obj->btf_ext->core_relo_info;
6253 	sec_num = 0;
6254 	for_each_btf_ext_sec(seg, sec) {
6255 		sec_idx = seg->sec_idxs[sec_num];
6256 		sec_num++;
6257 
6258 		sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
6259 		if (str_is_empty(sec_name)) {
6260 			err = -EINVAL;
6261 			goto out;
6262 		}
6263 
6264 		pr_debug("sec '%s': found %u CO-RE relocations\n", sec_name, sec->num_info);
6265 
6266 		for_each_btf_ext_rec(seg, sec, i, rec) {
6267 			if (rec->insn_off % BPF_INSN_SZ) {
6268 				err = -EINVAL;
6269 				goto out;
6270 			}
6271 
6272 			insn_idx = rec->insn_off / BPF_INSN_SZ;
6273 			prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
6274 			if (!prog) {
6275 				/* When __weak subprog is "overridden" by another instance
6276 				 * of the subprog from a different object file, linker still
6277 				 * appends all the .BTF.ext info that used to belong to that
6278 				 * eliminated subprogram.
6279 				 * This is similar to what x86-64 linker does for relocations.
6280 				 * So just ignore such relocations just like we ignore
6281 				 * subprog instructions when discovering subprograms.
6282 				 */
6283 				pr_debug("sec '%s': skipping CO-RE relocation #%d for insn #%d belonging to eliminated weak subprogram\n",
6284 					 sec_name, i, insn_idx);
6285 				continue;
6286 			}
6287 			/* no need to apply CO-RE relocation if the program is
6288 			 * not going to be loaded
6289 			 */
6290 			if (!prog->autoload)
6291 				continue;
6292 
6293 			/* adjust insn_idx from section frame of reference to the local
6294 			 * program's frame of reference; (sub-)program code is not yet
6295 			 * relocated, so it's enough to just subtract in-section offset
6296 			 */
6297 			insn_idx = insn_idx - prog->sec_insn_off;
6298 			if (insn_idx >= prog->insns_cnt) {
6299 				err = -EINVAL;
6300 				goto out;
6301 			}
6302 			insn = &prog->insns[insn_idx];
6303 
6304 			if (is_ldimm64_insn(insn) && (size_t)insn_idx + 1 >= prog->insns_cnt) {
6305 				pr_warn("prog '%s': relo #%d: insn #%d (LDIMM64) is truncated\n",
6306 					prog->name, i, insn_idx);
6307 				err = -EINVAL;
6308 				goto out;
6309 			}
6310 
6311 			err = record_relo_core(prog, rec, insn_idx);
6312 			if (err) {
6313 				pr_warn("prog '%s': relo #%d: failed to record relocation: %s\n",
6314 					prog->name, i, errstr(err));
6315 				goto out;
6316 			}
6317 
6318 			if (prog->obj->gen_loader)
6319 				continue;
6320 
6321 			err = bpf_core_resolve_relo(prog, rec, i, obj->btf, cand_cache, &targ_res);
6322 			if (err) {
6323 				pr_warn("prog '%s': relo #%d: failed to relocate: %s\n",
6324 					prog->name, i, errstr(err));
6325 				goto out;
6326 			}
6327 
6328 			err = bpf_core_patch_insn(prog->name, insn, insn_idx, rec, i, &targ_res);
6329 			if (err) {
6330 				pr_warn("prog '%s': relo #%d: failed to patch insn #%d: %s\n",
6331 					prog->name, i, insn_idx, errstr(err));
6332 				goto out;
6333 			}
6334 		}
6335 	}
6336 
6337 out:
6338 	/* obj->btf_vmlinux and module BTFs are freed after object load */
6339 	btf__free(obj->btf_vmlinux_override);
6340 	obj->btf_vmlinux_override = NULL;
6341 
6342 	if (!IS_ERR_OR_NULL(cand_cache)) {
6343 		hashmap__for_each_entry(cand_cache, entry, i) {
6344 			bpf_core_free_cands(entry->pvalue);
6345 		}
6346 		hashmap__free(cand_cache);
6347 	}
6348 	return err;
6349 }
6350 
6351 /* base map load ldimm64 special constant, used also for log fixup logic */
6352 #define POISON_LDIMM64_MAP_BASE 2001000000
6353 #define POISON_LDIMM64_MAP_PFX "200100"
6354 
6355 static void poison_map_ldimm64(struct bpf_program *prog, int relo_idx,
6356 			       int insn_idx, struct bpf_insn *insn,
6357 			       int map_idx, const struct bpf_map *map)
6358 {
6359 	int i;
6360 
6361 	pr_debug("prog '%s': relo #%d: poisoning insn #%d that loads map #%d '%s'\n",
6362 		 prog->name, relo_idx, insn_idx, map_idx, map->name);
6363 
6364 	/* we turn single ldimm64 into two identical invalid calls */
6365 	for (i = 0; i < 2; i++) {
6366 		insn->code = BPF_JMP | BPF_CALL;
6367 		insn->dst_reg = 0;
6368 		insn->src_reg = 0;
6369 		insn->off = 0;
6370 		/* if this instruction is reachable (not a dead code),
6371 		 * verifier will complain with something like:
6372 		 * invalid func unknown#2001000123
6373 		 * where lower 123 is map index into obj->maps[] array
6374 		 */
6375 		insn->imm = POISON_LDIMM64_MAP_BASE + map_idx;
6376 
6377 		insn++;
6378 	}
6379 }
6380 
6381 /* unresolved kfunc call special constant, used also for log fixup logic */
6382 #define POISON_CALL_KFUNC_BASE 2002000000
6383 #define POISON_CALL_KFUNC_PFX "2002"
6384 
6385 static void poison_kfunc_call(struct bpf_program *prog, int relo_idx,
6386 			      int insn_idx, struct bpf_insn *insn,
6387 			      int ext_idx, const struct extern_desc *ext)
6388 {
6389 	pr_debug("prog '%s': relo #%d: poisoning insn #%d that calls kfunc '%s'\n",
6390 		 prog->name, relo_idx, insn_idx, ext->name);
6391 
6392 	/* we turn kfunc call into invalid helper call with identifiable constant */
6393 	insn->code = BPF_JMP | BPF_CALL;
6394 	insn->dst_reg = 0;
6395 	insn->src_reg = 0;
6396 	insn->off = 0;
6397 	/* if this instruction is reachable (not a dead code),
6398 	 * verifier will complain with something like:
6399 	 * invalid func unknown#2001000123
6400 	 * where lower 123 is extern index into obj->externs[] array
6401 	 */
6402 	insn->imm = POISON_CALL_KFUNC_BASE + ext_idx;
6403 }
6404 
6405 static int find_jt_map(struct bpf_object *obj, struct bpf_program *prog, unsigned int sym_off)
6406 {
6407 	size_t i;
6408 
6409 	for (i = 0; i < obj->jumptable_map_cnt; i++) {
6410 		/*
6411 		 * This might happen that same offset is used for two different
6412 		 * programs (as jump tables can be the same). However, for
6413 		 * different programs different maps should be created.
6414 		 */
6415 		if (obj->jumptable_maps[i].sym_off == sym_off &&
6416 		    obj->jumptable_maps[i].prog == prog)
6417 			return obj->jumptable_maps[i].fd;
6418 	}
6419 
6420 	return -ENOENT;
6421 }
6422 
6423 static int add_jt_map(struct bpf_object *obj, struct bpf_program *prog, unsigned int sym_off, int map_fd)
6424 {
6425 	size_t cnt = obj->jumptable_map_cnt;
6426 	size_t size = sizeof(obj->jumptable_maps[0]);
6427 	void *tmp;
6428 
6429 	tmp = libbpf_reallocarray(obj->jumptable_maps, cnt + 1, size);
6430 	if (!tmp)
6431 		return -ENOMEM;
6432 
6433 	obj->jumptable_maps = tmp;
6434 	obj->jumptable_maps[cnt].prog = prog;
6435 	obj->jumptable_maps[cnt].sym_off = sym_off;
6436 	obj->jumptable_maps[cnt].fd = map_fd;
6437 	obj->jumptable_map_cnt++;
6438 
6439 	return 0;
6440 }
6441 
6442 static int find_subprog_idx(struct bpf_program *prog, int insn_idx)
6443 {
6444 	int i;
6445 
6446 	for (i = prog->subprog_cnt - 1; i >= 0; i--) {
6447 		if (insn_idx >= prog->subprogs[i].sub_insn_off)
6448 			return i;
6449 	}
6450 
6451 	return -1;
6452 }
6453 
6454 static int create_jt_map(struct bpf_object *obj, struct bpf_program *prog, struct reloc_desc *relo)
6455 {
6456 	const __u32 jt_entry_size = 8;
6457 	unsigned int sym_off = relo->sym_off;
6458 	int jt_size = relo->sym_size;
6459 	__u32 max_entries = jt_size / jt_entry_size;
6460 	__u32 value_size = sizeof(struct bpf_insn_array_value);
6461 	struct bpf_insn_array_value val = {};
6462 	int subprog_idx;
6463 	int map_fd, err;
6464 	__u64 insn_off;
6465 	__u64 *jt;
6466 	__u32 i;
6467 
6468 	map_fd = find_jt_map(obj, prog, sym_off);
6469 	if (map_fd >= 0)
6470 		return map_fd;
6471 
6472 	if (sym_off % jt_entry_size) {
6473 		pr_warn("map '.jumptables': jumptable start %u should be multiple of %u\n",
6474 			sym_off, jt_entry_size);
6475 		return -EINVAL;
6476 	}
6477 
6478 	if (jt_size % jt_entry_size) {
6479 		pr_warn("map '.jumptables': jumptable size %d should be multiple of %u\n",
6480 			jt_size, jt_entry_size);
6481 		return -EINVAL;
6482 	}
6483 
6484 	map_fd = bpf_map_create(BPF_MAP_TYPE_INSN_ARRAY, ".jumptables",
6485 				4, value_size, max_entries, NULL);
6486 	if (map_fd < 0)
6487 		return map_fd;
6488 
6489 	if (!obj->jumptables_data) {
6490 		pr_warn("map '.jumptables': ELF file is missing jump table data\n");
6491 		err = -EINVAL;
6492 		goto err_close;
6493 	}
6494 	if (sym_off + jt_size > obj->jumptables_data_sz) {
6495 		pr_warn("map '.jumptables': jumptables_data size is %zu, trying to access %u\n",
6496 			obj->jumptables_data_sz, sym_off + jt_size);
6497 		err = -EINVAL;
6498 		goto err_close;
6499 	}
6500 
6501 	subprog_idx = -1; /* main program */
6502 	if (relo->insn_idx < 0 || relo->insn_idx >= prog->insns_cnt) {
6503 		pr_warn("map '.jumptables': invalid instruction index %d\n", relo->insn_idx);
6504 		err = -EINVAL;
6505 		goto err_close;
6506 	}
6507 	if (prog->subprogs)
6508 		subprog_idx = find_subprog_idx(prog, relo->insn_idx);
6509 
6510 	jt = (__u64 *)(obj->jumptables_data + sym_off);
6511 	for (i = 0; i < max_entries; i++) {
6512 		/*
6513 		 * The offset should be made to be relative to the beginning of
6514 		 * the main function, not the subfunction.
6515 		 */
6516 		insn_off = jt[i]/sizeof(struct bpf_insn);
6517 		if (subprog_idx >= 0) {
6518 			insn_off -= prog->subprogs[subprog_idx].sec_insn_off;
6519 			insn_off += prog->subprogs[subprog_idx].sub_insn_off;
6520 		} else {
6521 			insn_off -= prog->sec_insn_off;
6522 		}
6523 
6524 		/*
6525 		 * LLVM-generated jump tables contain u64 records, however
6526 		 * should contain values that fit in u32.
6527 		 */
6528 		if (insn_off > UINT32_MAX) {
6529 			pr_warn("map '.jumptables': invalid jump table value 0x%llx at offset %u\n",
6530 				(unsigned long long)jt[i], sym_off + i * jt_entry_size);
6531 			err = -EINVAL;
6532 			goto err_close;
6533 		}
6534 
6535 		val.orig_off = insn_off;
6536 		err = bpf_map_update_elem(map_fd, &i, &val, 0);
6537 		if (err)
6538 			goto err_close;
6539 	}
6540 
6541 	err = bpf_map_freeze(map_fd);
6542 	if (err)
6543 		goto err_close;
6544 
6545 	err = add_jt_map(obj, prog, sym_off, map_fd);
6546 	if (err)
6547 		goto err_close;
6548 
6549 	return map_fd;
6550 
6551 err_close:
6552 	close(map_fd);
6553 	return err;
6554 }
6555 
6556 /*
6557  * The kernel recognizes a pointer to a function in a frozen read-only map by
6558  * its value: the offset in bytes of the function in the program. It makes
6559  * callx work for tables of functions, structures of operations and vtables,
6560  * where pointers are mixed with other data. Functions have different offsets
6561  * in different programs, so create a copy of the map for the program.
6562  * The kernel replaces the offsets with the addresses of the functions when it
6563  * loads the program, which has to be the only user of the map.
6564  */
6565 static int create_func_ptr_map(struct bpf_object *obj, struct bpf_program *prog, int map_idx)
6566 {
6567 	LIBBPF_OPTS(bpf_map_create_opts, opts, .map_flags = BPF_F_RDONLY_PROG);
6568 	struct bpf_map *map = &obj->maps[map_idx];
6569 	__u32 value_size = map->def.value_size;
6570 	size_t i, j, cnt, sec_insn_off;
6571 	struct func_ptr *ptrs;
6572 	int map_fd, err, zero = 0;
6573 	__u64 val;
6574 	void *data, *tmp;
6575 
6576 	for (i = 0; i < obj->func_ptr_map_cnt; i++)
6577 		if (obj->func_ptr_maps[i].prog == prog &&
6578 		    obj->func_ptr_maps[i].map_idx == map_idx)
6579 			return obj->func_ptr_maps[i].fd;
6580 
6581 	/* the map is not created yet, what it's going to have is in mmaped */
6582 	if (!map->mmaped)
6583 		return -EINVAL;
6584 
6585 	data = malloc(value_size);
6586 	if (!data)
6587 		return -ENOMEM;
6588 	memcpy(data, map->mmaped, value_size);
6589 
6590 	ptrs = map->func_ptrs;
6591 	cnt = map->func_ptr_cnt;
6592 	for (i = 0; i < cnt; i++) {
6593 		if (ptrs[i].sec_off + sizeof(val) > value_size) {
6594 			err = -LIBBPF_ERRNO__FORMAT;
6595 			goto err_free;
6596 		}
6597 		/*
6598 		 * Static functions were appended by bpf_object__append_func_ptrs_code().
6599 		 * A global function is in the program only if the code refers to it.
6600 		 */
6601 		sec_insn_off = ptrs[i].text_off / BPF_INSN_SZ;
6602 		for (j = 0; j < prog->subprog_cnt; j++)
6603 			if (prog->subprogs[j].sec_insn_off == sec_insn_off)
6604 				break;
6605 		if (j == prog->subprog_cnt) {
6606 			pr_debug("prog '%s': map '%s': no function for the pointer at offset %zu, it's NULL\n",
6607 				 prog->name, map->name, ptrs[i].sec_off);
6608 			val = 0;
6609 		} else {
6610 			val = (__u64)prog->subprogs[j].sub_insn_off * BPF_INSN_SZ;
6611 		}
6612 		/* light skeleton can be generated for a target of another endianness */
6613 		if (!is_native_endianness(obj))
6614 			val = bswap_64(val);
6615 		memcpy(data + ptrs[i].sec_off, &val, sizeof(val));
6616 	}
6617 
6618 	/*
6619 	 * The kernel takes any aligned 64-bit value that is equal to the offset
6620 	 * of a function for a pointer. Tell when it's going to get it wrong.
6621 	 */
6622 	for (i = 0, j = 0; i + sizeof(val) <= value_size; i += sizeof(val)) {
6623 		__u32 k;
6624 
6625 		while (j < cnt && ptrs[j].sec_off < i)
6626 			j++;
6627 		if (j < cnt && ptrs[j].sec_off == i)
6628 			continue;
6629 		memcpy(&val, data + i, sizeof(val));
6630 		if (!is_native_endianness(obj))
6631 			val = bswap_64(val);
6632 		if (!val || val % BPF_INSN_SZ)
6633 			continue;
6634 		for (k = 0; k < prog->subprog_cnt; k++) {
6635 			if ((__u64)prog->subprogs[k].sub_insn_off * BPF_INSN_SZ != val)
6636 				continue;
6637 			pr_warn("prog '%s': map '%s': value %llu at offset %zu is the offset of a function, the kernel will treat it as a pointer to it\n",
6638 				prog->name, map->name, (unsigned long long)val, i);
6639 			break;
6640 		}
6641 	}
6642 
6643 	if (obj->gen_loader) {
6644 		__u32 *ptr_offs = calloc(cnt, sizeof(*ptr_offs));
6645 		__u64 *ptr_vals = calloc(cnt, sizeof(*ptr_vals));
6646 
6647 		if (!ptr_offs || !ptr_vals) {
6648 			free(ptr_offs);
6649 			free(ptr_vals);
6650 			err = -ENOMEM;
6651 			goto err_free;
6652 		}
6653 		for (i = 0; i < cnt; i++) {
6654 			ptr_offs[i] = ptrs[i].sec_off;
6655 			memcpy(&ptr_vals[i], data + ptrs[i].sec_off, sizeof(val));
6656 			if (!is_native_endianness(obj))
6657 				ptr_vals[i] = bswap_64(ptr_vals[i]);
6658 		}
6659 		/* it's an index in fd_array of the loader, not an fd */
6660 		map_fd = bpf_gen__func_ptr_map_create(obj->gen_loader, map->name, map_idx, data,
6661 						      value_size, ptr_offs, ptr_vals, cnt);
6662 		free(ptr_offs);
6663 		free(ptr_vals);
6664 		goto done;
6665 	}
6666 
6667 	opts.token_fd = obj->token_fd;
6668 	if (obj->token_fd)
6669 		opts.map_flags |= BPF_F_TOKEN_FD;
6670 
6671 	map_fd = bpf_map_create(BPF_MAP_TYPE_ARRAY, map->name, sizeof(int), value_size, 1, &opts);
6672 	if (map_fd < 0) {
6673 		err = map_fd;
6674 		goto err_free;
6675 	}
6676 
6677 	err = bpf_map_update_elem(map_fd, &zero, data, 0);
6678 	if (!err)
6679 		err = bpf_map_freeze(map_fd);
6680 	if (err) {
6681 		err = -errno;
6682 		goto err_close;
6683 	}
6684 done:
6685 
6686 	tmp = libbpf_reallocarray(obj->func_ptr_maps, obj->func_ptr_map_cnt + 1,
6687 				  sizeof(*obj->func_ptr_maps));
6688 	if (!tmp) {
6689 		err = -ENOMEM;
6690 		goto err_close;
6691 	}
6692 	obj->func_ptr_maps = tmp;
6693 	obj->func_ptr_maps[obj->func_ptr_map_cnt].prog = prog;
6694 	obj->func_ptr_maps[obj->func_ptr_map_cnt].map_idx = map_idx;
6695 	obj->func_ptr_maps[obj->func_ptr_map_cnt].fd = map_fd;
6696 	obj->func_ptr_map_cnt++;
6697 
6698 	pr_debug("prog '%s': created a copy of map '%s' with %zu pointers to functions\n",
6699 		 prog->name, map->name, cnt);
6700 	free(data);
6701 	return map_fd;
6702 
6703 err_close:
6704 	if (!obj->gen_loader)
6705 		close(map_fd);
6706 err_free:
6707 	free(data);
6708 	return err;
6709 }
6710 
6711 /* Relocate data references within program code:
6712  *  - map references;
6713  *  - global variable references;
6714  *  - extern references.
6715  */
6716 static int
6717 bpf_object__relocate_data(struct bpf_object *obj, struct bpf_program *prog)
6718 {
6719 	int i;
6720 
6721 	for (i = 0; i < prog->nr_reloc; i++) {
6722 		struct reloc_desc *relo = &prog->reloc_desc[i];
6723 		struct bpf_insn *insn = &prog->insns[relo->insn_idx];
6724 		const struct bpf_map *map;
6725 		struct extern_desc *ext;
6726 
6727 		switch (relo->type) {
6728 		case RELO_LD64:
6729 			map = &obj->maps[relo->map_idx];
6730 			if (obj->gen_loader) {
6731 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX;
6732 				insn[0].imm = relo->map_idx;
6733 			} else if (map->autocreate) {
6734 				insn[0].src_reg = BPF_PSEUDO_MAP_FD;
6735 				insn[0].imm = map->fd;
6736 			} else {
6737 				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
6738 						   relo->map_idx, map);
6739 			}
6740 			break;
6741 		case RELO_DATA:
6742 			map = &obj->maps[relo->map_idx];
6743 			insn[1].imm = insn[0].imm + relo->sym_off;
6744 
6745 			if (relo->map_idx == obj->arena_map_idx)
6746 				insn[1].imm += obj->arena_data_off;
6747 
6748 			if (map->autocreate && map->func_ptr_cnt && prog->has_callx) {
6749 				int map_fd;
6750 
6751 				/* the program gets its own map with pointers to its functions */
6752 				map_fd = create_func_ptr_map(obj, prog, relo->map_idx);
6753 				if (map_fd < 0) {
6754 					pr_warn("prog '%s': relo #%d: can't create a copy of map '%s' with pointers to functions\n",
6755 						prog->name, i, map->name);
6756 					return map_fd;
6757 				}
6758 				insn[0].src_reg = obj->gen_loader ? BPF_PSEUDO_MAP_IDX_VALUE :
6759 								    BPF_PSEUDO_MAP_VALUE;
6760 				insn[0].imm = map_fd;
6761 			} else if (obj->gen_loader) {
6762 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
6763 				insn[0].imm = relo->map_idx;
6764 			} else if (map->autocreate) {
6765 				insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6766 				insn[0].imm = map->fd;
6767 			} else {
6768 				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
6769 						   relo->map_idx, map);
6770 			}
6771 			break;
6772 		case RELO_EXTERN_LD64:
6773 			ext = &obj->externs[relo->ext_idx];
6774 			if (ext->type == EXT_KCFG) {
6775 				if (obj->gen_loader) {
6776 					insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
6777 					insn[0].imm = obj->kconfig_map_idx;
6778 				} else {
6779 					insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6780 					insn[0].imm = obj->maps[obj->kconfig_map_idx].fd;
6781 				}
6782 				insn[1].imm = ext->kcfg.data_off;
6783 			} else /* EXT_KSYM */ {
6784 				if (ext->ksym.type_id && ext->is_set) { /* typed ksyms */
6785 					insn[0].src_reg = BPF_PSEUDO_BTF_ID;
6786 					insn[0].imm = ext->ksym.kernel_btf_id;
6787 					insn[1].imm = ext->ksym.kernel_btf_obj_fd;
6788 				} else { /* typeless ksyms or unresolved typed ksyms */
6789 					insn[0].imm = (__u32)ext->ksym.addr;
6790 					insn[1].imm = ext->ksym.addr >> 32;
6791 				}
6792 			}
6793 			break;
6794 		case RELO_EXTERN_CALL:
6795 			ext = &obj->externs[relo->ext_idx];
6796 			insn[0].src_reg = BPF_PSEUDO_KFUNC_CALL;
6797 			if (ext->is_set) {
6798 				insn[0].imm = ext->ksym.kernel_btf_id;
6799 				insn[0].off = ext->ksym.btf_fd_idx;
6800 			} else { /* unresolved weak kfunc call */
6801 				poison_kfunc_call(prog, i, relo->insn_idx, insn,
6802 						  relo->ext_idx, ext);
6803 			}
6804 			break;
6805 		case RELO_SUBPROG_ADDR:
6806 			if (insn[0].src_reg != BPF_PSEUDO_FUNC) {
6807 				pr_warn("prog '%s': relo #%d: bad insn\n",
6808 					prog->name, i);
6809 				return -EINVAL;
6810 			}
6811 			/* handled already */
6812 			break;
6813 		case RELO_CALL:
6814 			/* handled already */
6815 			break;
6816 		case RELO_CORE:
6817 			/* will be handled by bpf_program_record_relos() */
6818 			break;
6819 		case RELO_INSN_ARRAY: {
6820 			int map_fd;
6821 
6822 			map_fd = create_jt_map(obj, prog, relo);
6823 			if (map_fd < 0) {
6824 				pr_warn("prog '%s': relo #%d: can't create jump table: sym_off %u\n",
6825 					prog->name, i, relo->sym_off);
6826 				return map_fd;
6827 			}
6828 			insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6829 			insn->imm = map_fd;
6830 			insn->off = 0;
6831 		}
6832 			break;
6833 		default:
6834 			pr_warn("prog '%s': relo #%d: bad relo type %u\n",
6835 				prog->name, i, relo->type);
6836 			return -EINVAL;
6837 		}
6838 	}
6839 
6840 	return 0;
6841 }
6842 
6843 static int adjust_prog_btf_ext_info(const struct bpf_object *obj,
6844 				    const struct bpf_program *prog,
6845 				    const struct btf_ext_info *ext_info,
6846 				    void **prog_info, __u32 *prog_rec_cnt,
6847 				    __u32 *prog_rec_sz)
6848 {
6849 	void *copy_start = NULL, *copy_end = NULL;
6850 	void *rec, *rec_end, *new_prog_info;
6851 	const struct btf_ext_info_sec *sec;
6852 	size_t old_sz, new_sz;
6853 	int i, sec_num, sec_idx, off_adj;
6854 
6855 	sec_num = 0;
6856 	for_each_btf_ext_sec(ext_info, sec) {
6857 		sec_idx = ext_info->sec_idxs[sec_num];
6858 		sec_num++;
6859 		if (prog->sec_idx != sec_idx)
6860 			continue;
6861 
6862 		for_each_btf_ext_rec(ext_info, sec, i, rec) {
6863 			__u32 insn_off = *(__u32 *)rec / BPF_INSN_SZ;
6864 
6865 			if (insn_off < prog->sec_insn_off)
6866 				continue;
6867 			if (insn_off >= prog->sec_insn_off + prog->sec_insn_cnt)
6868 				break;
6869 
6870 			if (!copy_start)
6871 				copy_start = rec;
6872 			copy_end = rec + ext_info->rec_size;
6873 		}
6874 
6875 		if (!copy_start)
6876 			return -ENOENT;
6877 
6878 		/* append func/line info of a given (sub-)program to the main
6879 		 * program func/line info
6880 		 */
6881 		old_sz = (size_t)(*prog_rec_cnt) * ext_info->rec_size;
6882 		new_sz = old_sz + (copy_end - copy_start);
6883 		new_prog_info = realloc(*prog_info, new_sz);
6884 		if (!new_prog_info)
6885 			return -ENOMEM;
6886 		*prog_info = new_prog_info;
6887 		*prog_rec_cnt = new_sz / ext_info->rec_size;
6888 		memcpy(new_prog_info + old_sz, copy_start, copy_end - copy_start);
6889 
6890 		/* Kernel instruction offsets are in units of 8-byte
6891 		 * instructions, while .BTF.ext instruction offsets generated
6892 		 * by Clang are in units of bytes. So convert Clang offsets
6893 		 * into kernel offsets and adjust offset according to program
6894 		 * relocated position.
6895 		 */
6896 		off_adj = prog->sub_insn_off - prog->sec_insn_off;
6897 		rec = new_prog_info + old_sz;
6898 		rec_end = new_prog_info + new_sz;
6899 		for (; rec < rec_end; rec += ext_info->rec_size) {
6900 			__u32 *insn_off = rec;
6901 
6902 			*insn_off = *insn_off / BPF_INSN_SZ + off_adj;
6903 		}
6904 		*prog_rec_sz = ext_info->rec_size;
6905 		return 0;
6906 	}
6907 
6908 	return -ENOENT;
6909 }
6910 
6911 static int
6912 reloc_prog_func_and_line_info(const struct bpf_object *obj,
6913 			      struct bpf_program *main_prog,
6914 			      const struct bpf_program *prog)
6915 {
6916 	int err;
6917 
6918 	/* no .BTF.ext relocation if .BTF.ext is missing or kernel doesn't
6919 	 * support func/line info
6920 	 */
6921 	if (!obj->btf_ext || !kernel_supports(obj, FEAT_BTF_FUNC))
6922 		return 0;
6923 
6924 	/* only attempt func info relocation if main program's func_info
6925 	 * relocation was successful
6926 	 */
6927 	if (main_prog != prog && !main_prog->func_info)
6928 		goto line_info;
6929 
6930 	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->func_info,
6931 				       &main_prog->func_info,
6932 				       &main_prog->func_info_cnt,
6933 				       &main_prog->func_info_rec_size);
6934 	if (err) {
6935 		if (err != -ENOENT) {
6936 			pr_warn("prog '%s': error relocating .BTF.ext function info: %s\n",
6937 				prog->name, errstr(err));
6938 			return err;
6939 		}
6940 		if (main_prog->func_info) {
6941 			/*
6942 			 * Some info has already been found but has problem
6943 			 * in the last btf_ext reloc. Must have to error out.
6944 			 */
6945 			pr_warn("prog '%s': missing .BTF.ext function info.\n", prog->name);
6946 			return err;
6947 		}
6948 		/* Have problem loading the very first info. Ignore the rest. */
6949 		pr_warn("prog '%s': missing .BTF.ext function info for the main program, skipping all of .BTF.ext func info.\n",
6950 			prog->name);
6951 	}
6952 
6953 line_info:
6954 	/* don't relocate line info if main program's relocation failed */
6955 	if (main_prog != prog && !main_prog->line_info)
6956 		return 0;
6957 
6958 	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->line_info,
6959 				       &main_prog->line_info,
6960 				       &main_prog->line_info_cnt,
6961 				       &main_prog->line_info_rec_size);
6962 	if (err) {
6963 		if (err != -ENOENT) {
6964 			pr_warn("prog '%s': error relocating .BTF.ext line info: %s\n",
6965 				prog->name, errstr(err));
6966 			return err;
6967 		}
6968 		if (main_prog->line_info) {
6969 			/*
6970 			 * Some info has already been found but has problem
6971 			 * in the last btf_ext reloc. Must have to error out.
6972 			 */
6973 			pr_warn("prog '%s': missing .BTF.ext line info.\n", prog->name);
6974 			return err;
6975 		}
6976 		/* Have problem loading the very first info. Ignore the rest. */
6977 		pr_warn("prog '%s': missing .BTF.ext line info for the main program, skipping all of .BTF.ext line info.\n",
6978 			prog->name);
6979 	}
6980 	return 0;
6981 }
6982 
6983 static int cmp_relo_by_insn_idx(const void *key, const void *elem)
6984 {
6985 	size_t insn_idx = *(const size_t *)key;
6986 	const struct reloc_desc *relo = elem;
6987 
6988 	if (insn_idx == relo->insn_idx)
6989 		return 0;
6990 	return insn_idx < relo->insn_idx ? -1 : 1;
6991 }
6992 
6993 static struct reloc_desc *find_prog_insn_relo(const struct bpf_program *prog, size_t insn_idx)
6994 {
6995 	if (!prog->nr_reloc)
6996 		return NULL;
6997 	return bsearch(&insn_idx, prog->reloc_desc, prog->nr_reloc,
6998 		       sizeof(*prog->reloc_desc), cmp_relo_by_insn_idx);
6999 }
7000 
7001 static int append_subprog_relos(struct bpf_program *main_prog, struct bpf_program *subprog)
7002 {
7003 	int new_cnt = main_prog->nr_reloc + subprog->nr_reloc;
7004 	struct reloc_desc *relos;
7005 	int i;
7006 
7007 	if (main_prog == subprog)
7008 		return 0;
7009 	relos = libbpf_reallocarray(main_prog->reloc_desc, new_cnt, sizeof(*relos));
7010 	/* if new count is zero, reallocarray can return a valid NULL result;
7011 	 * in this case the previous pointer will be freed, so we *have to*
7012 	 * reassign old pointer to the new value (even if it's NULL)
7013 	 */
7014 	if (!relos && new_cnt)
7015 		return -ENOMEM;
7016 	if (subprog->nr_reloc)
7017 		memcpy(relos + main_prog->nr_reloc, subprog->reloc_desc,
7018 		       sizeof(*relos) * subprog->nr_reloc);
7019 
7020 	for (i = main_prog->nr_reloc; i < new_cnt; i++)
7021 		relos[i].insn_idx += subprog->sub_insn_off;
7022 	/* After insn_idx adjustment the 'relos' array is still sorted
7023 	 * by insn_idx and doesn't break bsearch.
7024 	 */
7025 	main_prog->reloc_desc = relos;
7026 	main_prog->nr_reloc = new_cnt;
7027 	return 0;
7028 }
7029 
7030 static int save_subprog_offsets(struct bpf_program *main_prog, struct bpf_program *subprog)
7031 {
7032 	size_t size = sizeof(main_prog->subprogs[0]);
7033 	int cnt = main_prog->subprog_cnt;
7034 	void *tmp;
7035 
7036 	tmp = libbpf_reallocarray(main_prog->subprogs, cnt + 1, size);
7037 	if (!tmp)
7038 		return -ENOMEM;
7039 
7040 	main_prog->subprogs = tmp;
7041 	main_prog->subprogs[cnt].sec_insn_off = subprog->sec_insn_off;
7042 	main_prog->subprogs[cnt].sub_insn_off = subprog->sub_insn_off;
7043 	main_prog->subprog_cnt++;
7044 
7045 	return 0;
7046 }
7047 
7048 static int
7049 bpf_object__append_subprog_code(struct bpf_object *obj, struct bpf_program *main_prog,
7050 				struct bpf_program *subprog)
7051 {
7052 	struct bpf_insn *insns;
7053 	size_t new_cnt;
7054 	int err;
7055 
7056 	subprog->sub_insn_off = main_prog->insns_cnt;
7057 
7058 	new_cnt = main_prog->insns_cnt + subprog->insns_cnt;
7059 	insns = libbpf_reallocarray(main_prog->insns, new_cnt, sizeof(*insns));
7060 	if (!insns) {
7061 		pr_warn("prog '%s': failed to realloc prog code\n", main_prog->name);
7062 		return -ENOMEM;
7063 	}
7064 	main_prog->insns = insns;
7065 	main_prog->insns_cnt = new_cnt;
7066 
7067 	memcpy(main_prog->insns + subprog->sub_insn_off, subprog->insns,
7068 	       subprog->insns_cnt * sizeof(*insns));
7069 
7070 	pr_debug("prog '%s': added %zu insns from sub-prog '%s'\n",
7071 		 main_prog->name, subprog->insns_cnt, subprog->name);
7072 
7073 	/* The subprog insns are now appended. Append its relos too. */
7074 	err = append_subprog_relos(main_prog, subprog);
7075 	if (err)
7076 		return err;
7077 
7078 	err = save_subprog_offsets(main_prog, subprog);
7079 	if (err) {
7080 		pr_warn("prog '%s': failed to add subprog offsets: %s\n",
7081 			main_prog->name, errstr(err));
7082 		return err;
7083 	}
7084 
7085 	return 0;
7086 }
7087 
7088 static int
7089 bpf_object__reloc_code(struct bpf_object *obj, struct bpf_program *main_prog,
7090 		       struct bpf_program *prog)
7091 {
7092 	size_t sub_insn_idx, insn_idx;
7093 	struct bpf_program *subprog;
7094 	struct reloc_desc *relo;
7095 	struct bpf_insn *insn;
7096 	int err;
7097 
7098 	err = reloc_prog_func_and_line_info(obj, main_prog, prog);
7099 	if (err)
7100 		return err;
7101 
7102 	for (insn_idx = 0; insn_idx < prog->sec_insn_cnt; insn_idx++) {
7103 		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
7104 		if (!insn_is_subprog_call(insn) && !insn_is_pseudo_func(insn))
7105 			continue;
7106 
7107 		relo = find_prog_insn_relo(prog, insn_idx);
7108 		if (relo && relo->type == RELO_EXTERN_CALL)
7109 			/* kfunc relocations will be handled later
7110 			 * in bpf_object__relocate_data()
7111 			 */
7112 			continue;
7113 		if (relo && relo->type != RELO_CALL && relo->type != RELO_SUBPROG_ADDR) {
7114 			pr_warn("prog '%s': unexpected relo for insn #%zu, type %u\n",
7115 				prog->name, insn_idx, relo->type);
7116 			return -LIBBPF_ERRNO__RELOC;
7117 		}
7118 		if (relo) {
7119 			/* sub-program instruction index is a combination of
7120 			 * an offset of a symbol pointed to by relocation and
7121 			 * call instruction's imm field; for global functions,
7122 			 * call always has imm = -1, but for static functions
7123 			 * relocation is against STT_SECTION and insn->imm
7124 			 * points to a start of a static function
7125 			 *
7126 			 * for subprog addr relocation, the relo->sym_off + insn->imm is
7127 			 * the byte offset in the corresponding section.
7128 			 */
7129 			if (relo->type == RELO_CALL)
7130 				sub_insn_idx = relo->sym_off / BPF_INSN_SZ + insn->imm + 1;
7131 			else
7132 				sub_insn_idx = (relo->sym_off + insn->imm) / BPF_INSN_SZ;
7133 		} else if (insn_is_pseudo_func(insn)) {
7134 			/*
7135 			 * RELO_SUBPROG_ADDR relo is always emitted even if both
7136 			 * functions are in the same section, so it shouldn't reach here.
7137 			 */
7138 			pr_warn("prog '%s': missing subprog addr relo for insn #%zu\n",
7139 				prog->name, insn_idx);
7140 			return -LIBBPF_ERRNO__RELOC;
7141 		} else {
7142 			/* if subprogram call is to a static function within
7143 			 * the same ELF section, there won't be any relocation
7144 			 * emitted, but it also means there is no additional
7145 			 * offset necessary, insns->imm is relative to
7146 			 * instruction's original position within the section
7147 			 */
7148 			sub_insn_idx = prog->sec_insn_off + insn_idx + insn->imm + 1;
7149 		}
7150 
7151 		/* we enforce that sub-programs should be in .text section */
7152 		subprog = find_prog_by_sec_insn(obj, obj->efile.text_shndx, sub_insn_idx);
7153 		if (!subprog) {
7154 			pr_warn("prog '%s': no .text section found yet sub-program call exists\n",
7155 				prog->name);
7156 			return -LIBBPF_ERRNO__RELOC;
7157 		}
7158 
7159 		/* if it's the first call instruction calling into this
7160 		 * subprogram (meaning this subprog hasn't been processed
7161 		 * yet) within the context of current main program:
7162 		 *   - append it at the end of main program's instructions blog;
7163 		 *   - process is recursively, while current program is put on hold;
7164 		 *   - if that subprogram calls some other not yet processes
7165 		 *   subprogram, same thing will happen recursively until
7166 		 *   there are no more unprocesses subprograms left to append
7167 		 *   and relocate.
7168 		 */
7169 		if (subprog->sub_insn_off == 0) {
7170 			err = bpf_object__append_subprog_code(obj, main_prog, subprog);
7171 			if (err)
7172 				return err;
7173 			err = bpf_object__reloc_code(obj, main_prog, subprog);
7174 			if (err)
7175 				return err;
7176 		}
7177 
7178 		/* main_prog->insns memory could have been re-allocated, so
7179 		 * calculate pointer again
7180 		 */
7181 		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
7182 		/* calculate correct instruction position within current main
7183 		 * prog; each main prog can have a different set of
7184 		 * subprograms appended (potentially in different order as
7185 		 * well), so position of any subprog can be different for
7186 		 * different main programs
7187 		 */
7188 		insn->imm = subprog->sub_insn_off - (prog->sub_insn_off + insn_idx) - 1;
7189 
7190 		pr_debug("prog '%s': insn #%zu relocated, imm %d points to subprog '%s' (now at %zu offset)\n",
7191 			 prog->name, insn_idx, insn->imm, subprog->name, subprog->sub_insn_off);
7192 	}
7193 
7194 	return 0;
7195 }
7196 
7197 /* Append to the main program all functions that the data of the map points to */
7198 static int
7199 bpf_object__append_func_ptrs_code(struct bpf_object *obj, struct bpf_program *main_prog,
7200 				  const struct bpf_map *map)
7201 {
7202 	struct bpf_program *subprog;
7203 	size_t i, cnt, sec_insn_off;
7204 	struct func_ptr *ptrs;
7205 	int err;
7206 
7207 	ptrs = map->func_ptrs;
7208 	cnt = map->func_ptr_cnt;
7209 	for (i = 0; i < cnt; i++) {
7210 		sec_insn_off = ptrs[i].text_off / BPF_INSN_SZ;
7211 		subprog = find_prog_by_sec_insn(obj, obj->efile.text_shndx, sec_insn_off);
7212 		if (!subprog || subprog->sec_insn_off != sec_insn_off) {
7213 			pr_warn("prog '%s': map '%s': no function at .text+%zu for the pointer at offset %zu\n",
7214 				main_prog->name, map->name, ptrs[i].text_off, ptrs[i].sec_off);
7215 			return -LIBBPF_ERRNO__RELOC;
7216 		}
7217 
7218 		/*
7219 		 * callx can't call global functions. Don't add one to the
7220 		 * program only because the data points to it.
7221 		 */
7222 		if (subprog->sym_global)
7223 			continue;
7224 
7225 		/* see the comment in bpf_object__reloc_code() */
7226 		if (subprog->sub_insn_off == 0) {
7227 			err = bpf_object__append_subprog_code(obj, main_prog, subprog);
7228 			if (err)
7229 				return err;
7230 			err = bpf_object__reloc_code(obj, main_prog, subprog);
7231 			if (err)
7232 				return err;
7233 		}
7234 	}
7235 	return 0;
7236 }
7237 
7238 /*
7239  * The program that has callx might call any function that the data it refers
7240  * to points to. Append them. Programs that don't have callx can't call them
7241  * and the kernel doesn't look for pointers to functions in their data.
7242  */
7243 static int
7244 bpf_object__append_func_ptrs(struct bpf_object *obj, struct bpf_program *prog)
7245 {
7246 	size_t i;
7247 	int err;
7248 
7249 	prog->has_callx = prog_has_callx(prog);
7250 	if (!prog->has_callx)
7251 		return 0;
7252 
7253 	/* relocations of the functions that are appended are appended too */
7254 	for (i = 0; i < prog->nr_reloc; i++) {
7255 		struct reloc_desc *relo = &prog->reloc_desc[i];
7256 
7257 		if (relo->type != RELO_DATA || !obj->maps[relo->map_idx].func_ptr_cnt)
7258 			continue;
7259 		err = bpf_object__append_func_ptrs_code(obj, prog, &obj->maps[relo->map_idx]);
7260 		if (err)
7261 			return err;
7262 	}
7263 	return 0;
7264 }
7265 
7266 /*
7267  * Relocate sub-program calls.
7268  *
7269  * Algorithm operates as follows. Each entry-point BPF program (referred to as
7270  * main prog) is processed separately. For each subprog (non-entry functions,
7271  * that can be called from either entry progs or other subprogs) gets their
7272  * sub_insn_off reset to zero. This serves as indicator that this subprogram
7273  * hasn't been yet appended and relocated within current main prog. Once its
7274  * relocated, sub_insn_off will point at the position within current main prog
7275  * where given subprog was appended. This will further be used to relocate all
7276  * the call instructions jumping into this subprog.
7277  *
7278  * We start with main program and process all call instructions. If the call
7279  * is into a subprog that hasn't been processed (i.e., subprog->sub_insn_off
7280  * is zero), subprog instructions are appended at the end of main program's
7281  * instruction array. Then main program is "put on hold" while we recursively
7282  * process newly appended subprogram. If that subprogram calls into another
7283  * subprogram that hasn't been appended, new subprogram is appended again to
7284  * the *main* prog's instructions (subprog's instructions are always left
7285  * untouched, as they need to be in unmodified state for subsequent main progs
7286  * and subprog instructions are always sent only as part of a main prog) and
7287  * the process continues recursively. Once all the subprogs called from a main
7288  * prog or any of its subprogs are appended (and relocated), all their
7289  * positions within finalized instructions array are known, so it's easy to
7290  * rewrite call instructions with correct relative offsets, corresponding to
7291  * desired target subprog.
7292  *
7293  * Its important to realize that some subprogs might not be called from some
7294  * main prog and any of its called/used subprogs. Those will keep their
7295  * subprog->sub_insn_off as zero at all times and won't be appended to current
7296  * main prog and won't be relocated within the context of current main prog.
7297  * They might still be used from other main progs later.
7298  *
7299  * Visually this process can be shown as below. Suppose we have two main
7300  * programs mainA and mainB and BPF object contains three subprogs: subA,
7301  * subB, and subC. mainA calls only subA, mainB calls only subC, but subA and
7302  * subC both call subB:
7303  *
7304  *        +--------+ +-------+
7305  *        |        v v       |
7306  *     +--+---+ +--+-+-+ +---+--+
7307  *     | subA | | subB | | subC |
7308  *     +--+---+ +------+ +---+--+
7309  *        ^                  ^
7310  *        |                  |
7311  *    +---+-------+   +------+----+
7312  *    |   mainA   |   |   mainB   |
7313  *    +-----------+   +-----------+
7314  *
7315  * We'll start relocating mainA, will find subA, append it and start
7316  * processing sub A recursively:
7317  *
7318  *    +-----------+------+
7319  *    |   mainA   | subA |
7320  *    +-----------+------+
7321  *
7322  * At this point we notice that subB is used from subA, so we append it and
7323  * relocate (there are no further subcalls from subB):
7324  *
7325  *    +-----------+------+------+
7326  *    |   mainA   | subA | subB |
7327  *    +-----------+------+------+
7328  *
7329  * At this point, we relocate subA calls, then go one level up and finish with
7330  * relocation mainA calls. mainA is done.
7331  *
7332  * For mainB process is similar but results in different order. We start with
7333  * mainB and skip subA and subB, as mainB never calls them (at least
7334  * directly), but we see subC is needed, so we append and start processing it:
7335  *
7336  *    +-----------+------+
7337  *    |   mainB   | subC |
7338  *    +-----------+------+
7339  * Now we see subC needs subB, so we go back to it, append and relocate it:
7340  *
7341  *    +-----------+------+------+
7342  *    |   mainB   | subC | subB |
7343  *    +-----------+------+------+
7344  *
7345  * At this point we unwind recursion, relocate calls in subC, then in mainB.
7346  */
7347 static int
7348 bpf_object__relocate_calls(struct bpf_object *obj, struct bpf_program *prog)
7349 {
7350 	struct bpf_program *subprog;
7351 	int i, err;
7352 
7353 	/* mark all subprogs as not relocated (yet) within the context of
7354 	 * current main program
7355 	 */
7356 	for (i = 0; i < obj->nr_programs; i++) {
7357 		subprog = &obj->programs[i];
7358 		if (!prog_is_subprog(obj, subprog))
7359 			continue;
7360 
7361 		subprog->sub_insn_off = 0;
7362 	}
7363 
7364 	err = bpf_object__reloc_code(obj, prog, prog);
7365 	if (err)
7366 		return err;
7367 
7368 	return bpf_object__append_func_ptrs(obj, prog);
7369 }
7370 
7371 static void
7372 bpf_object__free_relocs(struct bpf_object *obj)
7373 {
7374 	struct bpf_program *prog;
7375 	int i;
7376 
7377 	/* free up relocation descriptors */
7378 	for (i = 0; i < obj->nr_programs; i++) {
7379 		prog = &obj->programs[i];
7380 		zfree(&prog->reloc_desc);
7381 		prog->nr_reloc = 0;
7382 	}
7383 }
7384 
7385 static int cmp_relocs(const void *_a, const void *_b)
7386 {
7387 	const struct reloc_desc *a = _a;
7388 	const struct reloc_desc *b = _b;
7389 
7390 	if (a->insn_idx != b->insn_idx)
7391 		return a->insn_idx < b->insn_idx ? -1 : 1;
7392 
7393 	/* no two relocations should have the same insn_idx, but ... */
7394 	if (a->type != b->type)
7395 		return a->type < b->type ? -1 : 1;
7396 
7397 	return 0;
7398 }
7399 
7400 static void bpf_object__sort_relos(struct bpf_object *obj)
7401 {
7402 	int i;
7403 
7404 	for (i = 0; i < obj->nr_programs; i++) {
7405 		struct bpf_program *p = &obj->programs[i];
7406 
7407 		if (!p->nr_reloc)
7408 			continue;
7409 
7410 		qsort(p->reloc_desc, p->nr_reloc, sizeof(*p->reloc_desc), cmp_relocs);
7411 	}
7412 }
7413 
7414 static int bpf_prog_assign_exc_cb(struct bpf_object *obj, struct bpf_program *prog)
7415 {
7416 	const char *str = "exception_callback:";
7417 	size_t pfx_len = strlen(str);
7418 	int i, j, n;
7419 
7420 	if (!obj->btf || !kernel_supports(obj, FEAT_BTF_DECL_TAG))
7421 		return 0;
7422 
7423 	n = btf__type_cnt(obj->btf);
7424 	for (i = 1; i < n; i++) {
7425 		const char *name;
7426 		struct btf_type *t;
7427 
7428 		t = btf_type_by_id(obj->btf, i);
7429 		if (!btf_is_decl_tag(t) || btf_decl_tag(t)->component_idx != -1)
7430 			continue;
7431 
7432 		name = btf__str_by_offset(obj->btf, t->name_off);
7433 		if (strncmp(name, str, pfx_len) != 0)
7434 			continue;
7435 
7436 		t = btf_type_by_id(obj->btf, t->type);
7437 		if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL) {
7438 			pr_warn("prog '%s': exception_callback:<value> decl tag not applied to the main program\n",
7439 				prog->name);
7440 			return -EINVAL;
7441 		}
7442 		if (strcmp(prog->name, btf__str_by_offset(obj->btf, t->name_off)) != 0)
7443 			continue;
7444 		/* Multiple callbacks are specified for the same prog,
7445 		 * the verifier will eventually return an error for this
7446 		 * case, hence simply skip appending a subprog.
7447 		 */
7448 		if (prog->exception_cb_idx >= 0) {
7449 			prog->exception_cb_idx = -1;
7450 			break;
7451 		}
7452 
7453 		name += pfx_len;
7454 		if (str_is_empty(name)) {
7455 			pr_warn("prog '%s': exception_callback:<value> decl tag contains empty value\n",
7456 				prog->name);
7457 			return -EINVAL;
7458 		}
7459 
7460 		for (j = 0; j < obj->nr_programs; j++) {
7461 			struct bpf_program *subprog = &obj->programs[j];
7462 
7463 			if (!prog_is_subprog(obj, subprog))
7464 				continue;
7465 			if (strcmp(name, subprog->name) != 0)
7466 				continue;
7467 			/* Enforce non-hidden, as from verifier point of
7468 			 * view it expects global functions, whereas the
7469 			 * mark_btf_static fixes up linkage as static.
7470 			 */
7471 			if (!subprog->sym_global || subprog->mark_btf_static) {
7472 				pr_warn("prog '%s': exception callback %s must be a global non-hidden function\n",
7473 					prog->name, subprog->name);
7474 				return -EINVAL;
7475 			}
7476 			/* Let's see if we already saw a static exception callback with the same name */
7477 			if (prog->exception_cb_idx >= 0) {
7478 				pr_warn("prog '%s': multiple subprogs with same name as exception callback '%s'\n",
7479 					prog->name, subprog->name);
7480 				return -EINVAL;
7481 			}
7482 			prog->exception_cb_idx = j;
7483 			break;
7484 		}
7485 
7486 		if (prog->exception_cb_idx >= 0)
7487 			continue;
7488 
7489 		pr_warn("prog '%s': cannot find exception callback '%s'\n", prog->name, name);
7490 		return -ENOENT;
7491 	}
7492 
7493 	return 0;
7494 }
7495 
7496 static struct {
7497 	enum bpf_prog_type prog_type;
7498 	const char *ctx_name;
7499 } global_ctx_map[] = {
7500 	{ BPF_PROG_TYPE_CGROUP_DEVICE,           "bpf_cgroup_dev_ctx" },
7501 	{ BPF_PROG_TYPE_CGROUP_SKB,              "__sk_buff" },
7502 	{ BPF_PROG_TYPE_CGROUP_SOCK,             "bpf_sock" },
7503 	{ BPF_PROG_TYPE_CGROUP_SOCK_ADDR,        "bpf_sock_addr" },
7504 	{ BPF_PROG_TYPE_CGROUP_SOCKOPT,          "bpf_sockopt" },
7505 	{ BPF_PROG_TYPE_CGROUP_SYSCTL,           "bpf_sysctl" },
7506 	{ BPF_PROG_TYPE_FLOW_DISSECTOR,          "__sk_buff" },
7507 	{ BPF_PROG_TYPE_KPROBE,                  "bpf_user_pt_regs_t" },
7508 	{ BPF_PROG_TYPE_LWT_IN,                  "__sk_buff" },
7509 	{ BPF_PROG_TYPE_LWT_OUT,                 "__sk_buff" },
7510 	{ BPF_PROG_TYPE_LWT_SEG6LOCAL,           "__sk_buff" },
7511 	{ BPF_PROG_TYPE_LWT_XMIT,                "__sk_buff" },
7512 	{ BPF_PROG_TYPE_NETFILTER,               "bpf_nf_ctx" },
7513 	{ BPF_PROG_TYPE_PERF_EVENT,              "bpf_perf_event_data" },
7514 	{ BPF_PROG_TYPE_RAW_TRACEPOINT,          "bpf_raw_tracepoint_args" },
7515 	{ BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE, "bpf_raw_tracepoint_args" },
7516 	{ BPF_PROG_TYPE_SCHED_ACT,               "__sk_buff" },
7517 	{ BPF_PROG_TYPE_SCHED_CLS,               "__sk_buff" },
7518 	{ BPF_PROG_TYPE_SK_LOOKUP,               "bpf_sk_lookup" },
7519 	{ BPF_PROG_TYPE_SK_MSG,                  "sk_msg_md" },
7520 	{ BPF_PROG_TYPE_SK_REUSEPORT,            "sk_reuseport_md" },
7521 	{ BPF_PROG_TYPE_SK_SKB,                  "__sk_buff" },
7522 	{ BPF_PROG_TYPE_SOCK_OPS,                "bpf_sock_ops" },
7523 	{ BPF_PROG_TYPE_SOCKET_FILTER,           "__sk_buff" },
7524 	{ BPF_PROG_TYPE_XDP,                     "xdp_md" },
7525 	/* all other program types don't have "named" context structs */
7526 };
7527 
7528 /* forward declarations for arch-specific underlying types of bpf_user_pt_regs_t typedef,
7529  * for below __builtin_types_compatible_p() checks;
7530  * with this approach we don't need any extra arch-specific #ifdef guards
7531  */
7532 struct pt_regs;
7533 struct user_pt_regs;
7534 struct user_regs_struct;
7535 
7536 static bool need_func_arg_type_fixup(const struct btf *btf, const struct bpf_program *prog,
7537 				     const char *subprog_name, int arg_idx,
7538 				     int arg_type_id, const char *ctx_name)
7539 {
7540 	const struct btf_type *t;
7541 	const char *tname;
7542 
7543 	/* check if existing parameter already matches verifier expectations */
7544 	t = skip_mods_and_typedefs(btf, arg_type_id, NULL);
7545 	if (!btf_is_ptr(t))
7546 		goto out_warn;
7547 
7548 	/* typedef bpf_user_pt_regs_t is a special PITA case, valid for kprobe
7549 	 * and perf_event programs, so check this case early on and forget
7550 	 * about it for subsequent checks
7551 	 */
7552 	while (btf_is_mod(t))
7553 		t = btf__type_by_id(btf, t->type);
7554 	if (btf_is_typedef(t) &&
7555 	    (prog->type == BPF_PROG_TYPE_KPROBE || prog->type == BPF_PROG_TYPE_PERF_EVENT)) {
7556 		tname = btf__str_by_offset(btf, t->name_off) ?: "<anon>";
7557 		if (strcmp(tname, "bpf_user_pt_regs_t") == 0)
7558 			return false; /* canonical type for kprobe/perf_event */
7559 	}
7560 
7561 	/* now we can ignore typedefs moving forward */
7562 	t = skip_mods_and_typedefs(btf, t->type, NULL);
7563 
7564 	/* if it's `void *`, definitely fix up BTF info */
7565 	if (btf_is_void(t))
7566 		return true;
7567 
7568 	/* if it's already proper canonical type, no need to fix up */
7569 	tname = btf__str_by_offset(btf, t->name_off) ?: "<anon>";
7570 	if (btf_is_struct(t) && strcmp(tname, ctx_name) == 0)
7571 		return false;
7572 
7573 	/* special cases */
7574 	switch (prog->type) {
7575 	case BPF_PROG_TYPE_KPROBE:
7576 		/* `struct pt_regs *` is expected, but we need to fix up */
7577 		if (btf_is_struct(t) && strcmp(tname, "pt_regs") == 0)
7578 			return true;
7579 		break;
7580 	case BPF_PROG_TYPE_PERF_EVENT:
7581 		if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct pt_regs) &&
7582 		    btf_is_struct(t) && strcmp(tname, "pt_regs") == 0)
7583 			return true;
7584 		if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct user_pt_regs) &&
7585 		    btf_is_struct(t) && strcmp(tname, "user_pt_regs") == 0)
7586 			return true;
7587 		if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct user_regs_struct) &&
7588 		    btf_is_struct(t) && strcmp(tname, "user_regs_struct") == 0)
7589 			return true;
7590 		break;
7591 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
7592 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
7593 		/* allow u64* as ctx */
7594 		if (btf_is_int(t) && t->size == 8)
7595 			return true;
7596 		break;
7597 	default:
7598 		break;
7599 	}
7600 
7601 out_warn:
7602 	pr_warn("prog '%s': subprog '%s' arg#%d is expected to be of `struct %s *` type\n",
7603 		prog->name, subprog_name, arg_idx, ctx_name);
7604 	return false;
7605 }
7606 
7607 static int clone_func_btf_info(struct btf *btf, int orig_fn_id, struct bpf_program *prog)
7608 {
7609 	int fn_id, fn_proto_id, ret_type_id, orig_proto_id;
7610 	int i, err, arg_cnt, fn_name_off, linkage;
7611 	struct btf_type *fn_t, *fn_proto_t, *t;
7612 	struct btf_param *p;
7613 
7614 	/* caller already validated FUNC -> FUNC_PROTO validity */
7615 	fn_t = btf_type_by_id(btf, orig_fn_id);
7616 	fn_proto_t = btf_type_by_id(btf, fn_t->type);
7617 
7618 	/* Note that each btf__add_xxx() operation invalidates
7619 	 * all btf_type and string pointers, so we need to be
7620 	 * very careful when cloning BTF types. BTF type
7621 	 * pointers have to be always refetched. And to avoid
7622 	 * problems with invalidated string pointers, we
7623 	 * add empty strings initially, then just fix up
7624 	 * name_off offsets in place. Offsets are stable for
7625 	 * existing strings, so that works out.
7626 	 */
7627 	fn_name_off = fn_t->name_off; /* we are about to invalidate fn_t */
7628 	linkage = btf_func_linkage(fn_t);
7629 	orig_proto_id = fn_t->type; /* original FUNC_PROTO ID */
7630 	ret_type_id = fn_proto_t->type; /* fn_proto_t will be invalidated */
7631 	arg_cnt = btf_vlen(fn_proto_t);
7632 
7633 	/* clone FUNC_PROTO and its params */
7634 	fn_proto_id = btf__add_func_proto(btf, ret_type_id);
7635 	if (fn_proto_id < 0)
7636 		return -EINVAL;
7637 
7638 	for (i = 0; i < arg_cnt; i++) {
7639 		int name_off;
7640 
7641 		/* copy original parameter data */
7642 		t = btf_type_by_id(btf, orig_proto_id);
7643 		p = &btf_params(t)[i];
7644 		name_off = p->name_off;
7645 
7646 		err = btf__add_func_param(btf, "", p->type);
7647 		if (err)
7648 			return err;
7649 
7650 		fn_proto_t = btf_type_by_id(btf, fn_proto_id);
7651 		p = &btf_params(fn_proto_t)[i];
7652 		p->name_off = name_off; /* use remembered str offset */
7653 	}
7654 
7655 	/* clone FUNC now, btf__add_func() enforces non-empty name, so use
7656 	 * entry program's name as a placeholder, which we replace immediately
7657 	 * with original name_off
7658 	 */
7659 	fn_id = btf__add_func(btf, prog->name, linkage, fn_proto_id);
7660 	if (fn_id < 0)
7661 		return -EINVAL;
7662 
7663 	fn_t = btf_type_by_id(btf, fn_id);
7664 	fn_t->name_off = fn_name_off; /* reuse original string */
7665 
7666 	return fn_id;
7667 }
7668 
7669 /* Check if main program or global subprog's function prototype has `arg:ctx`
7670  * argument tags, and, if necessary, substitute correct type to match what BPF
7671  * verifier would expect, taking into account specific program type. This
7672  * allows to support __arg_ctx tag transparently on old kernels that don't yet
7673  * have a native support for it in the verifier, making user's life much
7674  * easier.
7675  */
7676 static int bpf_program_fixup_func_info(struct bpf_object *obj, struct bpf_program *prog)
7677 {
7678 	const char *ctx_name = NULL, *ctx_tag = "arg:ctx", *fn_name;
7679 	struct bpf_func_info_min *func_rec;
7680 	struct btf_type *fn_t, *fn_proto_t;
7681 	struct btf *btf = obj->btf;
7682 	const struct btf_type *t;
7683 	struct btf_param *p;
7684 	int ptr_id = 0, struct_id, tag_id, orig_fn_id;
7685 	int i, n, arg_idx, arg_cnt, err, rec_idx;
7686 	int *orig_ids;
7687 
7688 	/* no .BTF.ext, no problem */
7689 	if (!obj->btf_ext || !prog->func_info)
7690 		return 0;
7691 
7692 	/* don't do any fix ups if kernel natively supports __arg_ctx */
7693 	if (kernel_supports(obj, FEAT_ARG_CTX_TAG))
7694 		return 0;
7695 
7696 	/* some BPF program types just don't have named context structs, so
7697 	 * this fallback mechanism doesn't work for them
7698 	 */
7699 	for (i = 0; i < ARRAY_SIZE(global_ctx_map); i++) {
7700 		if (global_ctx_map[i].prog_type != prog->type)
7701 			continue;
7702 		ctx_name = global_ctx_map[i].ctx_name;
7703 		break;
7704 	}
7705 	if (!ctx_name)
7706 		return 0;
7707 
7708 	/* remember original func BTF IDs to detect if we already cloned them */
7709 	orig_ids = calloc(prog->func_info_cnt, sizeof(*orig_ids));
7710 	if (!orig_ids)
7711 		return -ENOMEM;
7712 	for (i = 0; i < prog->func_info_cnt; i++) {
7713 		func_rec = prog->func_info + prog->func_info_rec_size * i;
7714 		orig_ids[i] = func_rec->type_id;
7715 	}
7716 
7717 	/* go through each DECL_TAG with "arg:ctx" and see if it points to one
7718 	 * of our subprogs; if yes and subprog is global and needs adjustment,
7719 	 * clone and adjust FUNC -> FUNC_PROTO combo
7720 	 */
7721 	for (i = 1, n = btf__type_cnt(btf); i < n; i++) {
7722 		/* only DECL_TAG with "arg:ctx" value are interesting */
7723 		t = btf__type_by_id(btf, i);
7724 		if (!btf_is_decl_tag(t))
7725 			continue;
7726 		if (strcmp(btf__str_by_offset(btf, t->name_off), ctx_tag) != 0)
7727 			continue;
7728 
7729 		/* only global funcs need adjustment, if at all */
7730 		orig_fn_id = t->type;
7731 		fn_t = btf_type_by_id(btf, orig_fn_id);
7732 		if (!btf_is_func(fn_t) || btf_func_linkage(fn_t) != BTF_FUNC_GLOBAL)
7733 			continue;
7734 
7735 		/* sanity check FUNC -> FUNC_PROTO chain, just in case */
7736 		fn_proto_t = btf_type_by_id(btf, fn_t->type);
7737 		if (!fn_proto_t || !btf_is_func_proto(fn_proto_t))
7738 			continue;
7739 
7740 		/* find corresponding func_info record */
7741 		func_rec = NULL;
7742 		for (rec_idx = 0; rec_idx < prog->func_info_cnt; rec_idx++) {
7743 			if (orig_ids[rec_idx] == t->type) {
7744 				func_rec = prog->func_info + prog->func_info_rec_size * rec_idx;
7745 				break;
7746 			}
7747 		}
7748 		/* current main program doesn't call into this subprog */
7749 		if (!func_rec)
7750 			continue;
7751 
7752 		/* some more sanity checking of DECL_TAG */
7753 		arg_cnt = btf_vlen(fn_proto_t);
7754 		arg_idx = btf_decl_tag(t)->component_idx;
7755 		if (arg_idx < 0 || arg_idx >= arg_cnt)
7756 			continue;
7757 
7758 		/* check if we should fix up argument type */
7759 		p = &btf_params(fn_proto_t)[arg_idx];
7760 		fn_name = btf__str_by_offset(btf, fn_t->name_off) ?: "<anon>";
7761 		if (!need_func_arg_type_fixup(btf, prog, fn_name, arg_idx, p->type, ctx_name))
7762 			continue;
7763 
7764 		/* clone fn/fn_proto, unless we already did it for another arg */
7765 		if (func_rec->type_id == orig_fn_id) {
7766 			int fn_id;
7767 
7768 			fn_id = clone_func_btf_info(btf, orig_fn_id, prog);
7769 			if (fn_id < 0) {
7770 				err = fn_id;
7771 				goto err_out;
7772 			}
7773 
7774 			/* point func_info record to a cloned FUNC type */
7775 			func_rec->type_id = fn_id;
7776 		}
7777 
7778 		/* create PTR -> STRUCT type chain to mark PTR_TO_CTX argument;
7779 		 * we do it just once per main BPF program, as all global
7780 		 * funcs share the same program type, so need only PTR ->
7781 		 * STRUCT type chain
7782 		 */
7783 		if (ptr_id == 0) {
7784 			struct_id = btf__add_struct(btf, ctx_name, 0);
7785 			ptr_id = btf__add_ptr(btf, struct_id);
7786 			if (ptr_id < 0 || struct_id < 0) {
7787 				err = -EINVAL;
7788 				goto err_out;
7789 			}
7790 		}
7791 
7792 		/* for completeness, clone DECL_TAG and point it to cloned param */
7793 		tag_id = btf__add_decl_tag(btf, ctx_tag, func_rec->type_id, arg_idx);
7794 		if (tag_id < 0) {
7795 			err = -EINVAL;
7796 			goto err_out;
7797 		}
7798 
7799 		/* all the BTF manipulations invalidated pointers, refetch them */
7800 		fn_t = btf_type_by_id(btf, func_rec->type_id);
7801 		fn_proto_t = btf_type_by_id(btf, fn_t->type);
7802 
7803 		/* fix up type ID pointed to by param */
7804 		p = &btf_params(fn_proto_t)[arg_idx];
7805 		p->type = ptr_id;
7806 	}
7807 
7808 	free(orig_ids);
7809 	return 0;
7810 err_out:
7811 	free(orig_ids);
7812 	return err;
7813 }
7814 
7815 static int bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
7816 {
7817 	struct bpf_program *prog;
7818 	size_t i, j;
7819 	int err;
7820 
7821 	if (obj->btf_ext) {
7822 		err = bpf_object__relocate_core(obj, targ_btf_path);
7823 		if (err) {
7824 			pr_warn("failed to perform CO-RE relocations: %s\n",
7825 				errstr(err));
7826 			return err;
7827 		}
7828 		bpf_object__sort_relos(obj);
7829 	}
7830 
7831 	if (obj->arena_map_idx >= 0) {
7832 		struct bpf_map *arena_map = &obj->maps[obj->arena_map_idx];
7833 		size_t data_sz = roundup(obj->arena_data_sz, sysconf(_SC_PAGE_SIZE));
7834 		size_t mmap_sz = bpf_map_mmap_sz(arena_map);
7835 
7836 		if (data_sz > mmap_sz) {
7837 			pr_warn("map '%s': declared ARENA map size (%zu) is too small to hold global __arena variables of size %zu\n",
7838 				arena_map->name, mmap_sz, obj->arena_data_sz);
7839 			return -E2BIG;
7840 		}
7841 
7842 		/* place globals at the end of the arena (if supported) */
7843 		if (kernel_supports(obj, FEAT_LDIMM64_FULL_RANGE_OFF))
7844 			obj->arena_data_off = mmap_sz - data_sz;
7845 	}
7846 
7847 	/* Before relocating calls pre-process relocations and mark
7848 	 * few ld_imm64 instructions that points to subprogs.
7849 	 * Otherwise bpf_object__reloc_code() later would have to consider
7850 	 * all ld_imm64 insns as relocation candidates. That would
7851 	 * reduce relocation speed, since amount of find_prog_insn_relo()
7852 	 * would increase and most of them will fail to find a relo.
7853 	 */
7854 	for (i = 0; i < obj->nr_programs; i++) {
7855 		prog = &obj->programs[i];
7856 		for (j = 0; j < prog->nr_reloc; j++) {
7857 			struct reloc_desc *relo = &prog->reloc_desc[j];
7858 			struct bpf_insn *insn = &prog->insns[relo->insn_idx];
7859 
7860 			/* mark the insn, so it's recognized by insn_is_pseudo_func() */
7861 			if (relo->type == RELO_SUBPROG_ADDR)
7862 				insn[0].src_reg = BPF_PSEUDO_FUNC;
7863 		}
7864 	}
7865 
7866 	/* relocate subprogram calls and append used subprograms to main
7867 	 * programs; each copy of subprogram code needs to be relocated
7868 	 * differently for each main program, because its code location might
7869 	 * have changed.
7870 	 * Append subprog relos to main programs to allow data relos to be
7871 	 * processed after text is completely relocated.
7872 	 */
7873 	for (i = 0; i < obj->nr_programs; i++) {
7874 		prog = &obj->programs[i];
7875 		/* sub-program's sub-calls are relocated within the context of
7876 		 * its main program only
7877 		 */
7878 		if (prog_is_subprog(obj, prog))
7879 			continue;
7880 		if (!prog->autoload)
7881 			continue;
7882 
7883 		err = bpf_object__relocate_calls(obj, prog);
7884 		if (err) {
7885 			pr_warn("prog '%s': failed to relocate calls: %s\n",
7886 				prog->name, errstr(err));
7887 			return err;
7888 		}
7889 
7890 		err = bpf_prog_assign_exc_cb(obj, prog);
7891 		if (err)
7892 			return err;
7893 		/* Now, also append exception callback if it has not been done already. */
7894 		if (prog->exception_cb_idx >= 0) {
7895 			struct bpf_program *subprog = &obj->programs[prog->exception_cb_idx];
7896 
7897 			/* Calling exception callback directly is disallowed, which the
7898 			 * verifier will reject later. In case it was processed already,
7899 			 * we can skip this step, otherwise for all other valid cases we
7900 			 * have to append exception callback now.
7901 			 */
7902 			if (subprog->sub_insn_off == 0) {
7903 				err = bpf_object__append_subprog_code(obj, prog, subprog);
7904 				if (err)
7905 					return err;
7906 				err = bpf_object__reloc_code(obj, prog, subprog);
7907 				if (err)
7908 					return err;
7909 			}
7910 		}
7911 	}
7912 	for (i = 0; i < obj->nr_programs; i++) {
7913 		prog = &obj->programs[i];
7914 		if (prog_is_subprog(obj, prog))
7915 			continue;
7916 		if (!prog->autoload)
7917 			continue;
7918 
7919 		/* Process data relos for main programs */
7920 		err = bpf_object__relocate_data(obj, prog);
7921 		if (err) {
7922 			pr_warn("prog '%s': failed to relocate data references: %s\n",
7923 				prog->name, errstr(err));
7924 			return err;
7925 		}
7926 
7927 		/* Fix up .BTF.ext information, if necessary */
7928 		err = bpf_program_fixup_func_info(obj, prog);
7929 		if (err) {
7930 			pr_warn("prog '%s': failed to perform .BTF.ext fix ups: %s\n",
7931 				prog->name, errstr(err));
7932 			return err;
7933 		}
7934 	}
7935 
7936 	return 0;
7937 }
7938 
7939 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
7940 					    Elf64_Shdr *shdr, Elf_Data *data);
7941 
7942 static int bpf_object__collect_map_relos(struct bpf_object *obj,
7943 					 Elf64_Shdr *shdr, Elf_Data *data)
7944 {
7945 	const int bpf_ptr_sz = 8, host_ptr_sz = sizeof(void *);
7946 	int i, j, nrels, new_sz;
7947 	const struct btf_var_secinfo *vi = NULL;
7948 	const struct btf_type *sec, *var, *def;
7949 	struct bpf_map *map = NULL, *targ_map = NULL;
7950 	struct bpf_program *targ_prog = NULL;
7951 	bool is_prog_array, is_map_in_map;
7952 	const struct btf_member *member;
7953 	const char *name, *mname, *type;
7954 	unsigned int moff;
7955 	Elf64_Sym *sym;
7956 	Elf64_Rel *rel;
7957 	void *tmp;
7958 
7959 	if (!obj->efile.btf_maps_sec_btf_id || !obj->btf)
7960 		return -EINVAL;
7961 	sec = btf__type_by_id(obj->btf, obj->efile.btf_maps_sec_btf_id);
7962 	if (!sec)
7963 		return -EINVAL;
7964 
7965 	nrels = shdr->sh_size / shdr->sh_entsize;
7966 	for (i = 0; i < nrels; i++) {
7967 		rel = elf_rel_by_idx(data, i);
7968 		if (!rel) {
7969 			pr_warn(".maps relo #%d: failed to get ELF relo\n", i);
7970 			return -LIBBPF_ERRNO__FORMAT;
7971 		}
7972 
7973 		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
7974 		if (!sym) {
7975 			pr_warn(".maps relo #%d: symbol %zx not found\n",
7976 				i, (size_t)ELF64_R_SYM(rel->r_info));
7977 			return -LIBBPF_ERRNO__FORMAT;
7978 		}
7979 		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
7980 
7981 		pr_debug(".maps relo #%d: for %zd value %zu rel->r_offset %zu name %u ('%s')\n",
7982 			 i, (ssize_t)(rel->r_info >> 32), (size_t)sym->st_value,
7983 			 (size_t)rel->r_offset, sym->st_name, name);
7984 
7985 		for (j = 0; j < obj->nr_maps; j++) {
7986 			map = &obj->maps[j];
7987 			if (map->sec_idx != obj->efile.btf_maps_shndx)
7988 				continue;
7989 
7990 			vi = btf_var_secinfos(sec) + map->btf_var_idx;
7991 			if (vi->offset <= rel->r_offset &&
7992 			    rel->r_offset + bpf_ptr_sz <= vi->offset + vi->size)
7993 				break;
7994 		}
7995 		if (j == obj->nr_maps) {
7996 			pr_warn(".maps relo #%d: cannot find map '%s' at rel->r_offset %zu\n",
7997 				i, name, (size_t)rel->r_offset);
7998 			return -EINVAL;
7999 		}
8000 
8001 		is_map_in_map = bpf_map_type__is_map_in_map(map->def.type);
8002 		is_prog_array = map->def.type == BPF_MAP_TYPE_PROG_ARRAY;
8003 		type = is_map_in_map ? "map" : "prog";
8004 		if (is_map_in_map) {
8005 			if (sym->st_shndx != obj->efile.btf_maps_shndx) {
8006 				pr_warn(".maps relo #%d: '%s' isn't a BTF-defined map\n",
8007 					i, name);
8008 				return -LIBBPF_ERRNO__RELOC;
8009 			}
8010 			if (map->def.type == BPF_MAP_TYPE_HASH_OF_MAPS &&
8011 			    map->def.key_size != sizeof(int)) {
8012 				pr_warn(".maps relo #%d: hash-of-maps '%s' should have key size %zu.\n",
8013 					i, map->name, sizeof(int));
8014 				return -EINVAL;
8015 			}
8016 			targ_map = bpf_object__find_map_by_name(obj, name);
8017 			if (!targ_map) {
8018 				pr_warn(".maps relo #%d: '%s' isn't a valid map reference\n",
8019 					i, name);
8020 				return -ESRCH;
8021 			}
8022 		} else if (is_prog_array) {
8023 			targ_prog = bpf_object__find_program_by_name(obj, name);
8024 			if (!targ_prog) {
8025 				pr_warn(".maps relo #%d: '%s' isn't a valid program reference\n",
8026 					i, name);
8027 				return -ESRCH;
8028 			}
8029 			if (targ_prog->sec_idx != sym->st_shndx ||
8030 			    targ_prog->sec_insn_off * 8 != sym->st_value ||
8031 			    prog_is_subprog(obj, targ_prog)) {
8032 				pr_warn(".maps relo #%d: '%s' isn't an entry-point program\n",
8033 					i, name);
8034 				return -LIBBPF_ERRNO__RELOC;
8035 			}
8036 		} else {
8037 			return -EINVAL;
8038 		}
8039 
8040 		var = btf__type_by_id(obj->btf, vi->type);
8041 		def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
8042 		if (btf_vlen(def) == 0)
8043 			return -EINVAL;
8044 		member = btf_members(def) + btf_vlen(def) - 1;
8045 		mname = btf__name_by_offset(obj->btf, member->name_off);
8046 		if (strcmp(mname, "values"))
8047 			return -EINVAL;
8048 
8049 		moff = btf_member_bit_offset(def, btf_vlen(def) - 1) / 8;
8050 		if (rel->r_offset - vi->offset < moff)
8051 			return -EINVAL;
8052 
8053 		moff = rel->r_offset - vi->offset - moff;
8054 		/* here we use BPF pointer size, which is always 64 bit, as we
8055 		 * are parsing ELF that was built for BPF target
8056 		 */
8057 		if (moff % bpf_ptr_sz)
8058 			return -EINVAL;
8059 		moff /= bpf_ptr_sz;
8060 		if (moff >= map->init_slots_sz) {
8061 			new_sz = moff + 1;
8062 			tmp = libbpf_reallocarray(map->init_slots, new_sz, host_ptr_sz);
8063 			if (!tmp)
8064 				return -ENOMEM;
8065 			map->init_slots = tmp;
8066 			memset(map->init_slots + map->init_slots_sz, 0,
8067 			       (new_sz - map->init_slots_sz) * host_ptr_sz);
8068 			map->init_slots_sz = new_sz;
8069 		}
8070 		map->init_slots[moff] = is_map_in_map ? (void *)targ_map : (void *)targ_prog;
8071 
8072 		pr_debug(".maps relo #%d: map '%s' slot [%u] points to %s '%s'\n",
8073 			 i, map->name, moff, type, name);
8074 	}
8075 
8076 	return 0;
8077 }
8078 
8079 /*
8080  * Collect pointers to functions in a read-only data section. They are
8081  * R_BPF_64_ABS64 relocations against .text section, where the offset of
8082  * a static function in the section is stored in place. Relocations in data
8083  * sections were ignored before pointers to functions were supported. Those
8084  * that are something else, e.g. pointers to data, still are.
8085  */
8086 static int bpf_object__collect_rodata_relos(struct bpf_object *obj,
8087 					    Elf64_Shdr *shdr, Elf_Data *data)
8088 {
8089 	size_t sec_idx = shdr->sh_info, sym_idx;
8090 	int i, nrels = shdr->sh_size / shdr->sh_entsize;
8091 	const char *relo_sec_name;
8092 	struct func_ptr *ptrs;
8093 	Elf_Data *scn_data;
8094 	Elf64_Sym *sym;
8095 	Elf64_Rel *rel;
8096 	__u64 addend;
8097 
8098 	relo_sec_name = elf_sec_str(obj, shdr->sh_name) ?: "<?>";
8099 	scn_data = obj->efile.secs[sec_idx].data;
8100 	if (!scn_data)
8101 		return -LIBBPF_ERRNO__FORMAT;
8102 
8103 	for (i = 0; i < nrels; i++) {
8104 		rel = elf_rel_by_idx(data, i);
8105 		if (!rel) {
8106 			pr_warn("sec '%s': failed to get relo #%d\n", relo_sec_name, i);
8107 			return -LIBBPF_ERRNO__FORMAT;
8108 		}
8109 
8110 		sym_idx = ELF64_R_SYM(rel->r_info);
8111 		sym = elf_sym_by_idx(obj, sym_idx);
8112 		if (!sym) {
8113 			pr_warn("sec '%s': symbol #%zu not found for relo #%d\n",
8114 				relo_sec_name, sym_idx, i);
8115 			return -LIBBPF_ERRNO__FORMAT;
8116 		}
8117 
8118 		if (ELF64_R_TYPE(rel->r_info) != R_BPF_64_ABS64 ||
8119 		    !sym_is_subprog(sym, obj->efile.text_shndx)) {
8120 			pr_debug("sec '%s': relo #%d: not a pointer to a function, skipping...\n",
8121 				 relo_sec_name, i);
8122 			continue;
8123 		}
8124 
8125 		/* the kernel finds aligned pointers only */
8126 		if (rel->r_offset % sizeof(__u64) || rel->r_offset >= scn_data->d_size ||
8127 		    scn_data->d_size - rel->r_offset < sizeof(__u64)) {
8128 			pr_debug("sec '%s': relo #%d: unsupported offset 0x%zx, skipping...\n",
8129 				 relo_sec_name, i, (size_t)rel->r_offset);
8130 			continue;
8131 		}
8132 
8133 		memcpy(&addend, scn_data->d_buf + rel->r_offset, sizeof(addend));
8134 		if (!is_native_endianness(obj))
8135 			addend = bswap_64(addend);
8136 		if ((sym->st_value + addend) % BPF_INSN_SZ) {
8137 			pr_debug("sec '%s': relo #%d: bad pointer to a function at offset %zu+%llu, skipping...\n",
8138 				 relo_sec_name, i, (size_t)sym->st_value,
8139 				 (unsigned long long)addend);
8140 			continue;
8141 		}
8142 
8143 		ptrs = libbpf_reallocarray(obj->func_ptrs, obj->func_ptr_cnt + 1, sizeof(*ptrs));
8144 		if (!ptrs)
8145 			return -ENOMEM;
8146 		obj->func_ptrs = ptrs;
8147 
8148 		ptrs[obj->func_ptr_cnt].sec_idx = sec_idx;
8149 		ptrs[obj->func_ptr_cnt].sec_off = rel->r_offset;
8150 		ptrs[obj->func_ptr_cnt].text_off = sym->st_value + addend;
8151 		obj->func_ptr_cnt++;
8152 
8153 		pr_debug("sec '%s': relo #%d: pointer at offset %zu to a function at .text+%zu\n",
8154 			 relo_sec_name, i, (size_t)rel->r_offset, (size_t)(sym->st_value + addend));
8155 	}
8156 	return 0;
8157 }
8158 
8159 static int cmp_func_ptrs(const void *_a, const void *_b)
8160 {
8161 	const struct func_ptr *a = _a;
8162 	const struct func_ptr *b = _b;
8163 
8164 	if (a->sec_idx != b->sec_idx)
8165 		return a->sec_idx < b->sec_idx ? -1 : 1;
8166 	if (a->sec_off != b->sec_off)
8167 		return a->sec_off < b->sec_off ? -1 : 1;
8168 	return 0;
8169 }
8170 
8171 static int bpf_object__collect_relos(struct bpf_object *obj)
8172 {
8173 	int i, err;
8174 
8175 	for (i = 0; i < obj->efile.sec_cnt; i++) {
8176 		struct elf_sec_desc *sec_desc = &obj->efile.secs[i];
8177 		Elf64_Shdr *shdr;
8178 		Elf_Data *data;
8179 		int idx;
8180 
8181 		if (sec_desc->sec_type != SEC_RELO)
8182 			continue;
8183 
8184 		shdr = sec_desc->shdr;
8185 		data = sec_desc->data;
8186 		idx = shdr->sh_info;
8187 
8188 		if (shdr->sh_type != SHT_REL || idx < 0 || idx >= obj->efile.sec_cnt) {
8189 			pr_warn("internal error at %d\n", __LINE__);
8190 			return -LIBBPF_ERRNO__INTERNAL;
8191 		}
8192 
8193 		if (obj->efile.secs[idx].sec_type == SEC_RODATA)
8194 			err = bpf_object__collect_rodata_relos(obj, shdr, data);
8195 		else if (obj->efile.secs[idx].sec_type == SEC_ST_OPS)
8196 			err = bpf_object__collect_st_ops_relos(obj, shdr, data);
8197 		else if (idx == obj->efile.btf_maps_shndx)
8198 			err = bpf_object__collect_map_relos(obj, shdr, data);
8199 		else
8200 			err = bpf_object__collect_prog_relos(obj, shdr, data);
8201 		if (err)
8202 			return err;
8203 	}
8204 
8205 	/* sort by section, so that pointers in the data of a map are next to each other */
8206 	if (obj->func_ptr_cnt)
8207 		qsort(obj->func_ptrs, obj->func_ptr_cnt, sizeof(*obj->func_ptrs), cmp_func_ptrs);
8208 
8209 	for (i = 0; i < obj->nr_maps; i++) {
8210 		struct bpf_map *map = &obj->maps[i];
8211 		size_t j;
8212 
8213 		if (map->libbpf_type != LIBBPF_MAP_RODATA)
8214 			continue;
8215 		for (j = 0; j < obj->func_ptr_cnt; j++) {
8216 			if (obj->func_ptrs[j].sec_idx != map->sec_idx)
8217 				continue;
8218 			if (!map->func_ptr_cnt)
8219 				map->func_ptrs = &obj->func_ptrs[j];
8220 			map->func_ptr_cnt++;
8221 		}
8222 	}
8223 
8224 	bpf_object__sort_relos(obj);
8225 	return 0;
8226 }
8227 
8228 static bool insn_is_helper_call(struct bpf_insn *insn, enum bpf_func_id *func_id)
8229 {
8230 	if (BPF_CLASS(insn->code) == BPF_JMP &&
8231 	    BPF_OP(insn->code) == BPF_CALL &&
8232 	    BPF_SRC(insn->code) == BPF_K &&
8233 	    insn->src_reg == 0 &&
8234 	    insn->dst_reg == 0) {
8235 		    *func_id = insn->imm;
8236 		    return true;
8237 	}
8238 	return false;
8239 }
8240 
8241 static int bpf_object__sanitize_prog(struct bpf_object *obj, struct bpf_program *prog)
8242 {
8243 	struct bpf_insn *insn = prog->insns;
8244 	enum bpf_func_id func_id;
8245 	int i;
8246 
8247 	if (obj->gen_loader)
8248 		return 0;
8249 
8250 	for (i = 0; i < prog->insns_cnt; i++, insn++) {
8251 		if (!insn_is_helper_call(insn, &func_id))
8252 			continue;
8253 
8254 		/* on kernels that don't yet support
8255 		 * bpf_probe_read_{kernel,user}[_str] helpers, fall back
8256 		 * to bpf_probe_read() which works well for old kernels
8257 		 */
8258 		switch (func_id) {
8259 		case BPF_FUNC_probe_read_kernel:
8260 		case BPF_FUNC_probe_read_user:
8261 			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
8262 				insn->imm = BPF_FUNC_probe_read;
8263 			break;
8264 		case BPF_FUNC_probe_read_kernel_str:
8265 		case BPF_FUNC_probe_read_user_str:
8266 			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
8267 				insn->imm = BPF_FUNC_probe_read_str;
8268 			break;
8269 		default:
8270 			break;
8271 		}
8272 	}
8273 	return 0;
8274 }
8275 
8276 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
8277 				     int *btf_obj_fd, int *btf_type_id);
8278 
8279 static inline bool is_tracing_multi(enum bpf_attach_type type)
8280 {
8281 	return type == BPF_TRACE_FENTRY_MULTI || type == BPF_TRACE_FEXIT_MULTI ||
8282 	       type == BPF_TRACE_FSESSION_MULTI;
8283 }
8284 
8285 static const struct module_btf *find_attach_module(struct bpf_object *obj, const char *attach)
8286 {
8287 	const char *sep, *mod_name = NULL;
8288 	int i, mod_len, err;
8289 
8290 	/*
8291 	 * We expect attach string in the form of either
8292 	 * - function_pattern or
8293 	 * - <module>:function_pattern
8294 	 */
8295 	sep = strchr(attach, ':');
8296 	if (sep) {
8297 		mod_name = attach;
8298 		mod_len = sep - mod_name;
8299 	}
8300 	if (!mod_name)
8301 		return NULL;
8302 
8303 	err = load_module_btfs(obj);
8304 	if (err)
8305 		return NULL;
8306 
8307 	for (i = 0; i < obj->btf_module_cnt; i++) {
8308 		const struct module_btf *mod = &obj->btf_modules[i];
8309 
8310 		if (strncmp(mod->name, mod_name, mod_len) == 0 && mod->name[mod_len] == '\0')
8311 			return mod;
8312 	}
8313 	return NULL;
8314 }
8315 
8316 static int tracing_multi_mod_fd(struct bpf_program *prog, int *btf_obj_fd)
8317 {
8318 	const char *attach_name, *sep;
8319 	const struct module_btf *mod;
8320 
8321 	*btf_obj_fd = 0;
8322 	attach_name = strchr(prog->sec_name, '/');
8323 
8324 	/* Program with no details in spec, using kernel btf. */
8325 	if (!attach_name)
8326 		return 0;
8327 
8328 	/* Program with no module section, using kernel btf. */
8329 	sep = strchr(++attach_name, ':');
8330 	if (!sep)
8331 		return 0;
8332 
8333 	/* Program with module specified, get its btf fd. */
8334 	mod = find_attach_module(prog->obj, attach_name);
8335 	if (!mod)
8336 		return -EINVAL;
8337 
8338 	*btf_obj_fd = mod->fd;
8339 	return 0;
8340 }
8341 
8342 static int libbpf_setup_prog_flags(struct bpf_program *prog, long cookie)
8343 {
8344 	enum sec_def_flags def = cookie;
8345 
8346 	if (def & SEC_SLEEPABLE)
8347 		prog->prog_flags |= BPF_F_SLEEPABLE;
8348 
8349 	if (def & SEC_XDP_FRAGS)
8350 		prog->prog_flags |= BPF_F_XDP_HAS_FRAGS;
8351 
8352 	return 0;
8353 }
8354 
8355 /* this is called as prog->sec_def->prog_prepare_load_fn for libbpf-supported sec_defs */
8356 static int libbpf_prepare_prog_load(struct bpf_program *prog,
8357 				    struct bpf_prog_load_opts *opts, long cookie)
8358 {
8359 	enum sec_def_flags def = cookie;
8360 
8361 	/* old kernels might not support specifying expected_attach_type */
8362 	if ((def & SEC_EXP_ATTACH_OPT) && !kernel_supports(prog->obj, FEAT_EXP_ATTACH_TYPE))
8363 		opts->expected_attach_type = 0;
8364 
8365 	/* special check for usdt to use uprobe_multi link */
8366 	if ((def & SEC_USDT) && kernel_supports(prog->obj, FEAT_UPROBE_MULTI_LINK)) {
8367 		/* for BPF_TRACE_UPROBE_MULTI, user might want to query expected_attach_type
8368 		 * in prog, and expected_attach_type we set in kernel is from opts, so we
8369 		 * update both.
8370 		 */
8371 		prog->expected_attach_type = BPF_TRACE_UPROBE_MULTI;
8372 		opts->expected_attach_type = BPF_TRACE_UPROBE_MULTI;
8373 	}
8374 
8375 	if ((def & SEC_ATTACH_BTF) && !prog->attach_btf_id) {
8376 		int btf_obj_fd = 0, btf_type_id = 0, err;
8377 		const char *attach_name;
8378 
8379 		attach_name = strchr(prog->sec_name, '/');
8380 		if (!attach_name) {
8381 			/* if BPF program is annotated with just SEC("fentry")
8382 			 * (or similar) without declaratively specifying
8383 			 * target, then it is expected that target will be
8384 			 * specified with bpf_program__set_attach_target() at
8385 			 * runtime before BPF object load step. If not, then
8386 			 * there is nothing to load into the kernel as BPF
8387 			 * verifier won't be able to validate BPF program
8388 			 * correctness anyways.
8389 			 */
8390 			pr_warn("prog '%s': no BTF-based attach target is specified, use bpf_program__set_attach_target()\n",
8391 				prog->name);
8392 			return -EINVAL;
8393 		}
8394 		attach_name++; /* skip over / */
8395 
8396 		err = libbpf_find_attach_btf_id(prog, attach_name, &btf_obj_fd, &btf_type_id);
8397 		if (err)
8398 			return err;
8399 
8400 		/* cache resolved BTF FD and BTF type ID in the prog */
8401 		prog->attach_btf_obj_fd = btf_obj_fd;
8402 		prog->attach_btf_id = btf_type_id;
8403 
8404 		/* but by now libbpf common logic is not utilizing
8405 		 * prog->attach_btf_obj_fd/prog->attach_btf_id anymore because
8406 		 * this callback is called after opts were populated by
8407 		 * libbpf, so this callback has to update opts explicitly here
8408 		 */
8409 		opts->attach_btf_obj_fd = btf_obj_fd;
8410 		opts->attach_btf_id = btf_type_id;
8411 	}
8412 
8413 	if (prog->type == BPF_PROG_TYPE_TRACING && is_tracing_multi(prog->expected_attach_type)) {
8414 		int err, btf_obj_fd = 0;
8415 
8416 		err = tracing_multi_mod_fd(prog, &btf_obj_fd);
8417 		if (err < 0)
8418 			return err;
8419 
8420 		prog->attach_btf_obj_fd = btf_obj_fd;
8421 		opts->attach_btf_obj_fd = btf_obj_fd;
8422 	}
8423 
8424 	return 0;
8425 }
8426 
8427 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz);
8428 
8429 /*
8430  * Bind the arena of the object to the program about to be loaded. A program
8431  * has an arena only when an insn refers to the map, but the kernel can hand
8432  * it arena pointers all the same, as struct_ops arguments, through tagged
8433  * struct members or as kfunc return values, and the verifier rejects those
8434  * when the program has no arena to place them in. A continuous fd_array
8435  * binds every map in it, the arena takes slot 0, which is free: a kfunc insn
8436  * with offset 0 names vmlinux BTF rather than a slot.
8437  */
8438 static int bpf_object__bind_arena(struct bpf_object *obj, struct bpf_program *prog,
8439 				  struct bpf_prog_load_opts *load_attr)
8440 {
8441 	struct bpf_map *map;
8442 	int err;
8443 
8444 	if (obj->gen_loader || obj->arena_map_idx < 0 || !kernel_supports(obj, FEAT_FD_ARRAY_CNT))
8445 		return 0;
8446 	map = &obj->maps[obj->arena_map_idx];
8447 	/*
8448 	 * Nothing to bind when the arena is not created, or no longer is after
8449 	 * a failed load, when it is exclusive to another program, and nothing
8450 	 * for an offloaded program, which the kernel does not let near an
8451 	 * arena.
8452 	 */
8453 	if (!map->autocreate || map->fd < 0 || (map->excl_prog && map->excl_prog != prog) ||
8454 	    load_attr->prog_ifindex)
8455 		return 0;
8456 	/*
8457 	 * An arena exclusive to the program itself needs a kernel that checks
8458 	 * the map against the digest of the final program. Earlier kernels
8459 	 * compared a map bound through the fd_array against a digest they had
8460 	 * not computed yet and refused the load; there the program binds its
8461 	 * arena through its insns, as before.
8462 	 */
8463 	if (map->excl_prog && !kernel_supports(obj, FEAT_EXCL_MAP_FD_ARRAY_CNT))
8464 		return 0;
8465 
8466 	if (!obj->fd_array_used) {
8467 		err = libbpf_ensure_mem((void **)&obj->fd_array, &obj->fd_array_cap, sizeof(int), 1);
8468 		if (err)
8469 			return err;
8470 		obj->fd_array_used = 1;
8471 	}
8472 	obj->fd_array[0] = map->fd;
8473 	load_attr->fd_array = obj->fd_array;
8474 	/* with slot 0 filled every slot handed out is valid, so the array can go with a count */
8475 	load_attr->fd_array_cnt = obj->fd_array_used;
8476 	return 0;
8477 }
8478 
8479 static int bpf_object_load_prog(struct bpf_object *obj, struct bpf_program *prog,
8480 				struct bpf_insn *insns, int insns_cnt,
8481 				const char *license, __u32 kern_version, int *prog_fd)
8482 {
8483 	LIBBPF_OPTS(bpf_prog_load_opts, load_attr);
8484 	const char *prog_name = NULL;
8485 	size_t log_buf_size = 0;
8486 	char *log_buf = NULL, *tmp;
8487 	bool own_log_buf = true;
8488 	__u32 log_level = prog->log_level;
8489 	int ret, err;
8490 
8491 	/* Be more helpful by rejecting programs that can't be validated early
8492 	 * with more meaningful and actionable error message.
8493 	 */
8494 	switch (prog->type) {
8495 	case BPF_PROG_TYPE_UNSPEC:
8496 		/*
8497 		 * The program type must be set.  Most likely we couldn't find a proper
8498 		 * section definition at load time, and thus we didn't infer the type.
8499 		 */
8500 		pr_warn("prog '%s': missing BPF prog type, check ELF section name '%s'\n",
8501 			prog->name, prog->sec_name);
8502 		return -EINVAL;
8503 	case BPF_PROG_TYPE_STRUCT_OPS:
8504 		if (prog->attach_btf_id == 0) {
8505 			pr_warn("prog '%s': SEC(\"struct_ops\") program isn't referenced anywhere, did you forget to use it?\n",
8506 				prog->name);
8507 			return -EINVAL;
8508 		}
8509 		break;
8510 	default:
8511 		break;
8512 	}
8513 
8514 	if (!insns || !insns_cnt)
8515 		return -EINVAL;
8516 
8517 	if (kernel_supports(obj, FEAT_PROG_NAME))
8518 		prog_name = prog->name;
8519 	load_attr.attach_prog_fd = prog->attach_prog_fd;
8520 	load_attr.attach_btf_obj_fd = prog->attach_btf_obj_fd;
8521 	load_attr.attach_btf_id = prog->attach_btf_id;
8522 	load_attr.kern_version = kern_version;
8523 	load_attr.prog_ifindex = prog->prog_ifindex;
8524 	load_attr.expected_attach_type = prog->expected_attach_type;
8525 
8526 	/* specify func_info/line_info only if kernel supports them */
8527 	if (obj->btf && btf__fd(obj->btf) >= 0 && kernel_supports(obj, FEAT_BTF_FUNC)) {
8528 		load_attr.prog_btf_fd = btf__fd(obj->btf);
8529 		load_attr.func_info = prog->func_info;
8530 		load_attr.func_info_rec_size = prog->func_info_rec_size;
8531 		load_attr.func_info_cnt = prog->func_info_cnt;
8532 		load_attr.line_info = prog->line_info;
8533 		load_attr.line_info_rec_size = prog->line_info_rec_size;
8534 		load_attr.line_info_cnt = prog->line_info_cnt;
8535 	}
8536 	load_attr.log_level = log_level;
8537 	load_attr.prog_flags = prog->prog_flags;
8538 	load_attr.fd_array = obj->fd_array;
8539 	err = bpf_object__bind_arena(obj, prog, &load_attr);
8540 	if (err)
8541 		return err;
8542 
8543 	load_attr.token_fd = obj->token_fd;
8544 	if (obj->token_fd)
8545 		load_attr.prog_flags |= BPF_F_TOKEN_FD;
8546 
8547 	/* adjust load_attr if sec_def provides custom preload callback */
8548 	if (prog->sec_def && prog->sec_def->prog_prepare_load_fn) {
8549 		err = prog->sec_def->prog_prepare_load_fn(prog, &load_attr, prog->sec_def->cookie);
8550 		if (err < 0) {
8551 			pr_warn("prog '%s': failed to prepare load attributes: %s\n",
8552 				prog->name, errstr(err));
8553 			return err;
8554 		}
8555 		insns = prog->insns;
8556 		insns_cnt = prog->insns_cnt;
8557 	}
8558 
8559 	if (obj->gen_loader) {
8560 		bpf_gen__prog_load(obj->gen_loader, prog->type, prog->name,
8561 				   license, insns, insns_cnt, &load_attr,
8562 				   prog - obj->programs);
8563 		*prog_fd = -1;
8564 		return 0;
8565 	}
8566 
8567 retry_load:
8568 	/* if log_level is zero, we don't request logs initially even if
8569 	 * custom log_buf is specified; if the program load fails, then we'll
8570 	 * bump log_level to 1 and use either custom log_buf or we'll allocate
8571 	 * our own and retry the load to get details on what failed
8572 	 */
8573 	if (log_level) {
8574 		if (prog->log_buf) {
8575 			log_buf = prog->log_buf;
8576 			log_buf_size = prog->log_size;
8577 			own_log_buf = false;
8578 		} else if (obj->log_buf) {
8579 			log_buf = obj->log_buf;
8580 			log_buf_size = obj->log_size;
8581 			own_log_buf = false;
8582 		} else {
8583 			log_buf_size = max((size_t)BPF_LOG_BUF_SIZE, log_buf_size * 2);
8584 			tmp = realloc(log_buf, log_buf_size);
8585 			if (!tmp) {
8586 				ret = -ENOMEM;
8587 				goto out;
8588 			}
8589 			log_buf = tmp;
8590 			log_buf[0] = '\0';
8591 			own_log_buf = true;
8592 		}
8593 	}
8594 
8595 	load_attr.log_buf = log_buf;
8596 	load_attr.log_size = log_buf_size;
8597 	load_attr.log_level = log_level;
8598 
8599 	ret = bpf_prog_load(prog->type, prog_name, license, insns, insns_cnt, &load_attr);
8600 	if (ret >= 0) {
8601 		if (log_level && own_log_buf) {
8602 			pr_debug("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
8603 				 prog->name, log_buf);
8604 		}
8605 
8606 		if (obj->has_rodata && kernel_supports(obj, FEAT_PROG_BIND_MAP)) {
8607 			struct bpf_map *map;
8608 			int i;
8609 
8610 			for (i = 0; i < obj->nr_maps; i++) {
8611 				map = &prog->obj->maps[i];
8612 				if (map->libbpf_type != LIBBPF_MAP_RODATA)
8613 					continue;
8614 
8615 				if (bpf_prog_bind_map(ret, map->fd, NULL)) {
8616 					pr_warn("prog '%s': failed to bind map '%s': %s\n",
8617 						prog->name, map->real_name, errstr(errno));
8618 					/* Don't fail hard if can't bind rodata. */
8619 				}
8620 			}
8621 		}
8622 
8623 		*prog_fd = ret;
8624 		ret = 0;
8625 		goto out;
8626 	}
8627 
8628 	if (log_level == 0) {
8629 		log_level = 1;
8630 		goto retry_load;
8631 	}
8632 	/* On ENOSPC, increase log buffer size and retry, unless custom
8633 	 * log_buf is specified.
8634 	 * Be careful to not overflow u32, though. Kernel's log buf size limit
8635 	 * isn't part of UAPI so it can always be bumped to full 4GB. So don't
8636 	 * multiply by 2 unless we are sure we'll fit within 32 bits.
8637 	 * Currently, we'll get -EINVAL when we reach (UINT_MAX >> 2).
8638 	 */
8639 	if (own_log_buf && errno == ENOSPC && log_buf_size <= UINT_MAX / 2)
8640 		goto retry_load;
8641 
8642 	ret = -errno;
8643 
8644 	/* post-process verifier log to improve error descriptions */
8645 	fixup_verifier_log(prog, log_buf, log_buf_size);
8646 
8647 	pr_warn("prog '%s': BPF program load failed: %s\n", prog->name, errstr(errno));
8648 	pr_perm_msg(ret);
8649 
8650 	if (own_log_buf && log_buf && log_buf[0] != '\0') {
8651 		pr_warn("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
8652 			prog->name, log_buf);
8653 	}
8654 
8655 out:
8656 	if (own_log_buf)
8657 		free(log_buf);
8658 	return ret;
8659 }
8660 
8661 static char *find_prev_line(char *buf, char *cur)
8662 {
8663 	char *p;
8664 
8665 	if (cur == buf) /* end of a log buf */
8666 		return NULL;
8667 
8668 	p = cur - 1;
8669 	while (p - 1 >= buf && *(p - 1) != '\n')
8670 		p--;
8671 
8672 	return p;
8673 }
8674 
8675 static void patch_log(char *buf, size_t buf_sz, size_t log_sz,
8676 		      char *orig, size_t orig_sz, const char *patch)
8677 {
8678 	/* size of the remaining log content to the right from the to-be-replaced part */
8679 	size_t rem_sz = (buf + log_sz) - (orig + orig_sz);
8680 	size_t patch_sz = strlen(patch);
8681 
8682 	if (patch_sz != orig_sz) {
8683 		/* If patch line(s) are longer than original piece of verifier log,
8684 		 * shift log contents by (patch_sz - orig_sz) bytes to the right
8685 		 * starting from after to-be-replaced part of the log.
8686 		 *
8687 		 * If patch line(s) are shorter than original piece of verifier log,
8688 		 * shift log contents by (orig_sz - patch_sz) bytes to the left
8689 		 * starting from after to-be-replaced part of the log
8690 		 *
8691 		 * We need to be careful about not overflowing available
8692 		 * buf_sz capacity. If that's the case, we'll truncate the end
8693 		 * of the original log, as necessary.
8694 		 */
8695 		if (patch_sz > orig_sz) {
8696 			if (orig + patch_sz >= buf + buf_sz) {
8697 				/* patch is big enough to cover remaining space completely */
8698 				patch_sz -= (orig + patch_sz) - (buf + buf_sz) + 1;
8699 				rem_sz = 0;
8700 			} else if (patch_sz - orig_sz > buf_sz - log_sz) {
8701 				/* patch causes part of remaining log to be truncated */
8702 				rem_sz -= (patch_sz - orig_sz) - (buf_sz - log_sz);
8703 			}
8704 		}
8705 		/* shift remaining log to the right by calculated amount */
8706 		memmove(orig + patch_sz, orig + orig_sz, rem_sz);
8707 	}
8708 
8709 	memcpy(orig, patch, patch_sz);
8710 }
8711 
8712 static void fixup_log_failed_core_relo(struct bpf_program *prog,
8713 				       char *buf, size_t buf_sz, size_t log_sz,
8714 				       char *line1, char *line2, char *line3)
8715 {
8716 	/* Expected log for failed and not properly guarded CO-RE relocation:
8717 	 * line1 -> 123: (85) call unknown#195896080
8718 	 * line2 -> invalid func unknown#195896080
8719 	 * line3 -> <anything else or end of buffer>
8720 	 *
8721 	 * "123" is the index of the instruction that was poisoned. We extract
8722 	 * instruction index to find corresponding CO-RE relocation and
8723 	 * replace this part of the log with more relevant information about
8724 	 * failed CO-RE relocation.
8725 	 */
8726 	const struct bpf_core_relo *relo;
8727 	struct bpf_core_spec spec;
8728 	char patch[512], spec_buf[256];
8729 	int insn_idx, err, spec_len;
8730 
8731 	if (sscanf(line1, "%d: (%*d) call unknown#195896080\n", &insn_idx) != 1)
8732 		return;
8733 
8734 	relo = find_relo_core(prog, insn_idx);
8735 	if (!relo)
8736 		return;
8737 
8738 	err = bpf_core_parse_spec(prog->name, prog->obj->btf, relo, &spec);
8739 	if (err)
8740 		return;
8741 
8742 	spec_len = bpf_core_format_spec(spec_buf, sizeof(spec_buf), &spec);
8743 	snprintf(patch, sizeof(patch),
8744 		 "%d: <invalid CO-RE relocation>\n"
8745 		 "failed to resolve CO-RE relocation %s%s\n",
8746 		 insn_idx, spec_buf, spec_len >= sizeof(spec_buf) ? "..." : "");
8747 
8748 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
8749 }
8750 
8751 static void fixup_log_missing_map_load(struct bpf_program *prog,
8752 				       char *buf, size_t buf_sz, size_t log_sz,
8753 				       char *line1, char *line2, char *line3)
8754 {
8755 	/* Expected log for failed and not properly guarded map reference:
8756 	 * line1 -> 123: (85) call unknown#2001000345
8757 	 * line2 -> invalid func unknown#2001000345
8758 	 * line3 -> <anything else or end of buffer>
8759 	 *
8760 	 * "123" is the index of the instruction that was poisoned.
8761 	 * "345" in "2001000345" is a map index in obj->maps to fetch map name.
8762 	 */
8763 	struct bpf_object *obj = prog->obj;
8764 	const struct bpf_map *map;
8765 	int insn_idx, map_idx;
8766 	char patch[128];
8767 
8768 	if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &map_idx) != 2)
8769 		return;
8770 
8771 	map_idx -= POISON_LDIMM64_MAP_BASE;
8772 	if (map_idx < 0 || map_idx >= obj->nr_maps)
8773 		return;
8774 	map = &obj->maps[map_idx];
8775 
8776 	snprintf(patch, sizeof(patch),
8777 		 "%d: <invalid BPF map reference>\n"
8778 		 "BPF map '%s' is referenced but wasn't created\n",
8779 		 insn_idx, map->name);
8780 
8781 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
8782 }
8783 
8784 static void fixup_log_missing_kfunc_call(struct bpf_program *prog,
8785 					 char *buf, size_t buf_sz, size_t log_sz,
8786 					 char *line1, char *line2, char *line3)
8787 {
8788 	/* Expected log for failed and not properly guarded kfunc call:
8789 	 * line1 -> 123: (85) call unknown#2002000345
8790 	 * line2 -> invalid func unknown#2002000345
8791 	 * line3 -> <anything else or end of buffer>
8792 	 *
8793 	 * "123" is the index of the instruction that was poisoned.
8794 	 * "345" in "2002000345" is an extern index in obj->externs to fetch kfunc name.
8795 	 */
8796 	struct bpf_object *obj = prog->obj;
8797 	const struct extern_desc *ext;
8798 	int insn_idx, ext_idx;
8799 	char patch[128];
8800 
8801 	if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &ext_idx) != 2)
8802 		return;
8803 
8804 	ext_idx -= POISON_CALL_KFUNC_BASE;
8805 	if (ext_idx < 0 || ext_idx >= obj->nr_extern)
8806 		return;
8807 	ext = &obj->externs[ext_idx];
8808 
8809 	snprintf(patch, sizeof(patch),
8810 		 "%d: <invalid kfunc call>\n"
8811 		 "kfunc '%s' is referenced but wasn't resolved\n",
8812 		 insn_idx, ext->name);
8813 
8814 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
8815 }
8816 
8817 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz)
8818 {
8819 	/* look for familiar error patterns in last N lines of the log */
8820 	const size_t max_last_line_cnt = 10;
8821 	char *prev_line, *cur_line, *next_line;
8822 	size_t log_sz;
8823 	int i;
8824 
8825 	if (!buf)
8826 		return;
8827 
8828 	log_sz = strlen(buf) + 1;
8829 	next_line = buf + log_sz - 1;
8830 
8831 	for (i = 0; i < max_last_line_cnt; i++, next_line = cur_line) {
8832 		cur_line = find_prev_line(buf, next_line);
8833 		if (!cur_line)
8834 			return;
8835 
8836 		if (str_has_pfx(cur_line, "invalid func unknown#195896080\n")) {
8837 			prev_line = find_prev_line(buf, cur_line);
8838 			if (!prev_line)
8839 				continue;
8840 
8841 			/* failed CO-RE relocation case */
8842 			fixup_log_failed_core_relo(prog, buf, buf_sz, log_sz,
8843 						   prev_line, cur_line, next_line);
8844 			return;
8845 		} else if (str_has_pfx(cur_line, "invalid func unknown#"POISON_LDIMM64_MAP_PFX)) {
8846 			prev_line = find_prev_line(buf, cur_line);
8847 			if (!prev_line)
8848 				continue;
8849 
8850 			/* reference to uncreated BPF map */
8851 			fixup_log_missing_map_load(prog, buf, buf_sz, log_sz,
8852 						   prev_line, cur_line, next_line);
8853 			return;
8854 		} else if (str_has_pfx(cur_line, "invalid func unknown#"POISON_CALL_KFUNC_PFX)) {
8855 			prev_line = find_prev_line(buf, cur_line);
8856 			if (!prev_line)
8857 				continue;
8858 
8859 			/* reference to unresolved kfunc */
8860 			fixup_log_missing_kfunc_call(prog, buf, buf_sz, log_sz,
8861 						     prev_line, cur_line, next_line);
8862 			return;
8863 		}
8864 	}
8865 }
8866 
8867 static int bpf_program_record_relos(struct bpf_program *prog)
8868 {
8869 	struct bpf_object *obj = prog->obj;
8870 	int i;
8871 
8872 	for (i = 0; i < prog->nr_reloc; i++) {
8873 		struct reloc_desc *relo = &prog->reloc_desc[i];
8874 		struct extern_desc *ext = &obj->externs[relo->ext_idx];
8875 		int kind;
8876 
8877 		switch (relo->type) {
8878 		case RELO_EXTERN_LD64:
8879 			if (ext->type != EXT_KSYM)
8880 				continue;
8881 			kind = btf_is_var(btf__type_by_id(obj->btf, ext->btf_id)) ?
8882 				BTF_KIND_VAR : BTF_KIND_FUNC;
8883 			bpf_gen__record_extern(obj->gen_loader, ext->name,
8884 					       ext->is_weak, !ext->ksym.type_id,
8885 					       true, kind, relo->insn_idx);
8886 			break;
8887 		case RELO_EXTERN_CALL:
8888 			bpf_gen__record_extern(obj->gen_loader, ext->name,
8889 					       ext->is_weak, false, false, BTF_KIND_FUNC,
8890 					       relo->insn_idx);
8891 			break;
8892 		case RELO_CORE: {
8893 			struct bpf_core_relo cr = {
8894 				.insn_off = relo->insn_idx * 8,
8895 				.type_id = relo->core_relo->type_id,
8896 				.access_str_off = relo->core_relo->access_str_off,
8897 				.kind = relo->core_relo->kind,
8898 			};
8899 
8900 			bpf_gen__record_relo_core(obj->gen_loader, &cr);
8901 			break;
8902 		}
8903 		default:
8904 			continue;
8905 		}
8906 	}
8907 	return 0;
8908 }
8909 
8910 static int
8911 bpf_object__load_progs(struct bpf_object *obj, int log_level)
8912 {
8913 	struct bpf_program *prog;
8914 	size_t i;
8915 	int err;
8916 
8917 	for (i = 0; i < obj->nr_programs; i++) {
8918 		prog = &obj->programs[i];
8919 		if (prog_is_subprog(obj, prog))
8920 			continue;
8921 		if (!prog->autoload) {
8922 			pr_debug("prog '%s': skipped loading\n", prog->name);
8923 			continue;
8924 		}
8925 		prog->log_level |= log_level;
8926 
8927 		if (obj->gen_loader)
8928 			bpf_program_record_relos(prog);
8929 
8930 		err = bpf_object_load_prog(obj, prog, prog->insns, prog->insns_cnt,
8931 					   obj->license, obj->kern_version, &prog->fd);
8932 		if (err) {
8933 			pr_warn("prog '%s': failed to load: %s\n", prog->name, errstr(err));
8934 			return err;
8935 		}
8936 	}
8937 
8938 	bpf_object__free_relocs(obj);
8939 	return 0;
8940 }
8941 
8942 static int bpf_object_prepare_progs(struct bpf_object *obj)
8943 {
8944 	struct bpf_program *prog;
8945 	size_t i;
8946 	int err;
8947 
8948 	for (i = 0; i < obj->nr_programs; i++) {
8949 		prog = &obj->programs[i];
8950 		err = bpf_object__sanitize_prog(obj, prog);
8951 		if (err)
8952 			return err;
8953 	}
8954 	return 0;
8955 }
8956 
8957 static const struct bpf_sec_def *find_sec_def(const char *sec_name);
8958 
8959 static int bpf_object_init_progs(struct bpf_object *obj, const struct bpf_object_open_opts *opts)
8960 {
8961 	struct bpf_program *prog;
8962 	int err;
8963 
8964 	bpf_object__for_each_program(prog, obj) {
8965 		prog->sec_def = find_sec_def(prog->sec_name);
8966 		if (!prog->sec_def) {
8967 			/* couldn't guess, but user might manually specify */
8968 			pr_debug("prog '%s': unrecognized ELF section name '%s'\n",
8969 				prog->name, prog->sec_name);
8970 			continue;
8971 		}
8972 
8973 		prog->type = prog->sec_def->prog_type;
8974 		prog->expected_attach_type = prog->sec_def->expected_attach_type;
8975 
8976 		/* sec_def can have custom callback which should be called
8977 		 * after bpf_program is initialized to adjust its properties
8978 		 */
8979 		if (prog->sec_def->prog_setup_fn) {
8980 			err = prog->sec_def->prog_setup_fn(prog, prog->sec_def->cookie);
8981 			if (err < 0) {
8982 				pr_warn("prog '%s': failed to initialize: %s\n",
8983 					prog->name, errstr(err));
8984 				return err;
8985 			}
8986 		}
8987 	}
8988 
8989 	return 0;
8990 }
8991 
8992 static struct bpf_object *bpf_object_open(const char *path, const void *obj_buf, size_t obj_buf_sz,
8993 					  const char *obj_name,
8994 					  const struct bpf_object_open_opts *opts)
8995 {
8996 	const char *kconfig, *btf_tmp_path, *token_path;
8997 	size_t mod_allow_cnt, i, j;
8998 	const char **mod_allow;
8999 	struct bpf_object *obj;
9000 	int err;
9001 	char *log_buf;
9002 	size_t log_size;
9003 	__u32 log_level;
9004 
9005 	if (obj_buf && !obj_name)
9006 		return ERR_PTR(-EINVAL);
9007 
9008 	if (elf_version(EV_CURRENT) == EV_NONE) {
9009 		pr_warn("failed to init libelf for %s\n",
9010 			path ? : "(mem buf)");
9011 		return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
9012 	}
9013 
9014 	if (!OPTS_VALID(opts, bpf_object_open_opts))
9015 		return ERR_PTR(-EINVAL);
9016 
9017 	obj_name = OPTS_GET(opts, object_name, NULL) ?: obj_name;
9018 	if (obj_buf) {
9019 		path = obj_name;
9020 		pr_debug("loading object '%s' from buffer\n", obj_name);
9021 	} else {
9022 		pr_debug("loading object from %s\n", path);
9023 	}
9024 
9025 	log_buf = OPTS_GET(opts, kernel_log_buf, NULL);
9026 	log_size = OPTS_GET(opts, kernel_log_size, 0);
9027 	log_level = OPTS_GET(opts, kernel_log_level, 0);
9028 	if (log_size > UINT_MAX)
9029 		return ERR_PTR(-EINVAL);
9030 	if (log_size && !log_buf)
9031 		return ERR_PTR(-EINVAL);
9032 
9033 	token_path = OPTS_GET(opts, bpf_token_path, NULL);
9034 	/* if user didn't specify bpf_token_path explicitly, check if
9035 	 * LIBBPF_BPF_TOKEN_PATH envvar was set and treat it as bpf_token_path
9036 	 * option
9037 	 */
9038 	if (!token_path)
9039 		token_path = getenv("LIBBPF_BPF_TOKEN_PATH");
9040 	if (token_path && strlen(token_path) >= PATH_MAX)
9041 		return ERR_PTR(-ENAMETOOLONG);
9042 
9043 	mod_allow = OPTS_GET(opts, btf_module_allowlist, NULL);
9044 	mod_allow_cnt = OPTS_GET(opts, btf_module_allowlist_cnt, 0);
9045 
9046 	if (mod_allow_cnt > SSIZE_MAX || (!mod_allow && mod_allow_cnt > 0))
9047 		return ERR_PTR(-EINVAL);
9048 
9049 	for (i = 0; i < mod_allow_cnt; i++) {
9050 		if (!mod_allow[i] || !mod_allow[i][0])
9051 			return ERR_PTR(-EINVAL);
9052 
9053 		for (j = 0; j < i; j++) {
9054 			if (strcmp(mod_allow[i], mod_allow[j]) == 0)
9055 				return ERR_PTR(-EINVAL);
9056 		}
9057 	}
9058 
9059 	obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
9060 	if (IS_ERR(obj))
9061 		return obj;
9062 
9063 	obj->log_buf = log_buf;
9064 	obj->log_size = log_size;
9065 	obj->log_level = log_level;
9066 
9067 	if (token_path) {
9068 		obj->token_path = strdup(token_path);
9069 		if (!obj->token_path) {
9070 			err = -ENOMEM;
9071 			goto out;
9072 		}
9073 	}
9074 
9075 	btf_tmp_path = OPTS_GET(opts, btf_custom_path, NULL);
9076 	if (btf_tmp_path) {
9077 		if (strlen(btf_tmp_path) >= PATH_MAX) {
9078 			err = -ENAMETOOLONG;
9079 			goto out;
9080 		}
9081 		obj->btf_custom_path = strdup(btf_tmp_path);
9082 		if (!obj->btf_custom_path) {
9083 			err = -ENOMEM;
9084 			goto out;
9085 		}
9086 	}
9087 
9088 	kconfig = OPTS_GET(opts, kconfig, NULL);
9089 	if (kconfig) {
9090 		obj->kconfig = strdup(kconfig);
9091 		if (!obj->kconfig) {
9092 			err = -ENOMEM;
9093 			goto out;
9094 		}
9095 	}
9096 
9097 	obj->btf_module_allowlist_cnt = mod_allow ? mod_allow_cnt : -1;
9098 	if (mod_allow_cnt > 0) {
9099 		obj->btf_module_allowlist =
9100 			calloc(mod_allow_cnt, sizeof(*obj->btf_module_allowlist));
9101 		if (!obj->btf_module_allowlist) {
9102 			err = -ENOMEM;
9103 			goto out;
9104 		}
9105 
9106 		for (i = 0; i < mod_allow_cnt; i++) {
9107 			obj->btf_module_allowlist[i] = strdup(mod_allow[i]);
9108 			if (!obj->btf_module_allowlist[i]) {
9109 				err = -ENOMEM;
9110 				goto out;
9111 			}
9112 		}
9113 	}
9114 
9115 	err = bpf_object__elf_init(obj);
9116 	err = err ? : bpf_object__elf_collect(obj);
9117 	err = err ? : bpf_object__collect_externs(obj);
9118 	err = err ? : bpf_object_fixup_btf(obj);
9119 	err = err ? : bpf_object__init_maps(obj, opts);
9120 	err = err ? : bpf_object_init_progs(obj, opts);
9121 	err = err ? : bpf_object__collect_relos(obj);
9122 	if (err)
9123 		goto out;
9124 
9125 	bpf_object__elf_finish(obj);
9126 
9127 	return obj;
9128 out:
9129 	bpf_object__close(obj);
9130 	return ERR_PTR(err);
9131 }
9132 
9133 struct bpf_object *
9134 bpf_object__open_file(const char *path, const struct bpf_object_open_opts *opts)
9135 {
9136 	if (!path)
9137 		return libbpf_err_ptr(-EINVAL);
9138 
9139 	return libbpf_ptr(bpf_object_open(path, NULL, 0, NULL, opts));
9140 }
9141 
9142 struct bpf_object *bpf_object__open(const char *path)
9143 {
9144 	return bpf_object__open_file(path, NULL);
9145 }
9146 
9147 struct bpf_object *
9148 bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
9149 		     const struct bpf_object_open_opts *opts)
9150 {
9151 	char tmp_name[64];
9152 
9153 	if (!obj_buf || obj_buf_sz == 0)
9154 		return libbpf_err_ptr(-EINVAL);
9155 
9156 	/* create a (quite useless) default "name" for this memory buffer object */
9157 	snprintf(tmp_name, sizeof(tmp_name), "%lx-%zx", (unsigned long)obj_buf, obj_buf_sz);
9158 
9159 	return libbpf_ptr(bpf_object_open(NULL, obj_buf, obj_buf_sz, tmp_name, opts));
9160 }
9161 
9162 static int bpf_object_unload(struct bpf_object *obj)
9163 {
9164 	size_t i;
9165 
9166 	if (!obj)
9167 		return libbpf_err(-EINVAL);
9168 
9169 	for (i = 0; i < obj->nr_maps; i++) {
9170 		zclose(obj->maps[i].fd);
9171 		if (obj->maps[i].st_ops)
9172 			zfree(&obj->maps[i].st_ops->kern_vdata);
9173 	}
9174 
9175 	for (i = 0; i < obj->nr_programs; i++)
9176 		bpf_program__unload(&obj->programs[i]);
9177 
9178 	return 0;
9179 }
9180 
9181 static int bpf_object__sanitize_maps(struct bpf_object *obj)
9182 {
9183 	struct bpf_map *m;
9184 
9185 	bpf_object__for_each_map(m, obj) {
9186 		if (!bpf_map__is_internal(m))
9187 			continue;
9188 		if (!kernel_supports(obj, FEAT_ARRAY_MMAP))
9189 			m->def.map_flags &= ~BPF_F_MMAPABLE;
9190 	}
9191 
9192 	return 0;
9193 }
9194 
9195 typedef int (*kallsyms_cb_t)(unsigned long long sym_addr, char sym_type,
9196 			     const char *sym_name, void *ctx);
9197 
9198 static int libbpf_kallsyms_parse(kallsyms_cb_t cb, void *ctx)
9199 {
9200 	char sym_type, sym_name[500];
9201 	unsigned long long sym_addr;
9202 	int ret, err = 0;
9203 	FILE *f;
9204 
9205 	f = fopen("/proc/kallsyms", "re");
9206 	if (!f) {
9207 		err = -errno;
9208 		pr_warn("failed to open /proc/kallsyms: %s\n", errstr(err));
9209 		return err;
9210 	}
9211 
9212 	while (true) {
9213 		ret = fscanf(f, "%llx %c %499s%*[^\n]\n",
9214 			     &sym_addr, &sym_type, sym_name);
9215 		if (ret == EOF && feof(f))
9216 			break;
9217 		if (ret != 3) {
9218 			pr_warn("failed to read kallsyms entry: %d\n", ret);
9219 			err = -EINVAL;
9220 			break;
9221 		}
9222 
9223 		err = cb(sym_addr, sym_type, sym_name, ctx);
9224 		if (err)
9225 			break;
9226 	}
9227 
9228 	fclose(f);
9229 	return err;
9230 }
9231 
9232 static int kallsyms_cb(unsigned long long sym_addr, char sym_type,
9233 		       const char *sym_name, void *ctx)
9234 {
9235 	struct bpf_object *obj = ctx;
9236 	const struct btf_type *t;
9237 	struct extern_desc *ext;
9238 	const char *res;
9239 
9240 	res = strstr(sym_name, ".llvm.");
9241 	if (sym_type == 'd' && res)
9242 		ext = find_extern_by_name_with_len(obj, sym_name, res - sym_name);
9243 	else
9244 		ext = find_extern_by_name(obj, sym_name);
9245 	if (!ext || ext->type != EXT_KSYM)
9246 		return 0;
9247 
9248 	t = btf__type_by_id(obj->btf, ext->btf_id);
9249 	if (!btf_is_var(t))
9250 		return 0;
9251 
9252 	if (ext->is_set && ext->ksym.addr != sym_addr) {
9253 		pr_warn("extern (ksym) '%s': resolution is ambiguous: 0x%llx or 0x%llx\n",
9254 			sym_name, ext->ksym.addr, sym_addr);
9255 		return -EINVAL;
9256 	}
9257 	if (!ext->is_set) {
9258 		ext->is_set = true;
9259 		ext->ksym.addr = sym_addr;
9260 		pr_debug("extern (ksym) '%s': set to 0x%llx\n", sym_name, sym_addr);
9261 	}
9262 	return 0;
9263 }
9264 
9265 static int bpf_object__read_kallsyms_file(struct bpf_object *obj)
9266 {
9267 	return libbpf_kallsyms_parse(kallsyms_cb, obj);
9268 }
9269 
9270 static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
9271 			    __u16 kind, struct btf **res_btf,
9272 			    struct module_btf **res_mod_btf)
9273 {
9274 	struct module_btf *mod_btf;
9275 	struct btf *btf;
9276 	int i, id, err;
9277 
9278 	btf = obj->btf_vmlinux;
9279 	mod_btf = NULL;
9280 	id = btf__find_by_name_kind(btf, ksym_name, kind);
9281 
9282 	if (id == -ENOENT) {
9283 		err = load_module_btfs(obj);
9284 		if (err)
9285 			return err;
9286 
9287 		for (i = 0; i < obj->btf_module_cnt; i++) {
9288 			/* we assume module_btf's BTF FD is always >0 */
9289 			mod_btf = &obj->btf_modules[i];
9290 			btf = mod_btf->btf;
9291 			id = btf__find_by_name_kind_own(btf, ksym_name, kind);
9292 			if (id != -ENOENT)
9293 				break;
9294 		}
9295 	}
9296 	if (id <= 0)
9297 		return -ESRCH;
9298 
9299 	*res_btf = btf;
9300 	*res_mod_btf = mod_btf;
9301 	return id;
9302 }
9303 
9304 static int bpf_object__resolve_ksym_var_btf_id(struct bpf_object *obj,
9305 					       struct extern_desc *ext)
9306 {
9307 	const struct btf_type *targ_var, *targ_type;
9308 	__u32 targ_type_id, local_type_id;
9309 	struct module_btf *mod_btf = NULL;
9310 	const char *targ_var_name;
9311 	struct btf *btf = NULL;
9312 	int id, err;
9313 
9314 	id = find_ksym_btf_id(obj, ext->name, BTF_KIND_VAR, &btf, &mod_btf);
9315 	if (id < 0) {
9316 		if (id == -ESRCH && ext->is_weak)
9317 			return 0;
9318 		pr_warn("extern (var ksym) '%s': not found in kernel BTF\n",
9319 			ext->name);
9320 		return id;
9321 	}
9322 
9323 	/* find local type_id */
9324 	local_type_id = ext->ksym.type_id;
9325 
9326 	/* find target type_id */
9327 	targ_var = btf__type_by_id(btf, id);
9328 	targ_var_name = btf__name_by_offset(btf, targ_var->name_off);
9329 	targ_type = skip_mods_and_typedefs(btf, targ_var->type, &targ_type_id);
9330 
9331 	err = bpf_core_types_are_compat(obj->btf, local_type_id,
9332 					btf, targ_type_id);
9333 	if (err <= 0) {
9334 		const struct btf_type *local_type;
9335 		const char *targ_name, *local_name;
9336 
9337 		local_type = btf__type_by_id(obj->btf, local_type_id);
9338 		local_name = btf__name_by_offset(obj->btf, local_type->name_off);
9339 		targ_name = btf__name_by_offset(btf, targ_type->name_off);
9340 
9341 		pr_warn("extern (var ksym) '%s': incompatible types, expected [%u] %s %s, but kernel has [%u] %s %s\n",
9342 			ext->name, local_type_id,
9343 			btf_kind_str(local_type), local_name, targ_type_id,
9344 			btf_kind_str(targ_type), targ_name);
9345 		return -EINVAL;
9346 	}
9347 
9348 	ext->is_set = true;
9349 	ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
9350 	ext->ksym.kernel_btf_id = id;
9351 	pr_debug("extern (var ksym) '%s': resolved to [%d] %s %s\n",
9352 		 ext->name, id, btf_kind_str(targ_var), targ_var_name);
9353 
9354 	return 0;
9355 }
9356 
9357 static int bpf_object__resolve_ksym_func_btf_id(struct bpf_object *obj,
9358 						struct extern_desc *ext)
9359 {
9360 	int local_func_proto_id, kfunc_proto_id, kfunc_id;
9361 	struct module_btf *mod_btf = NULL;
9362 	const struct btf_type *kern_func;
9363 	struct btf *kern_btf = NULL;
9364 	int ret;
9365 
9366 	local_func_proto_id = ext->ksym.type_id;
9367 
9368 	kfunc_id = find_ksym_btf_id(obj, ext->essent_name ?: ext->name, BTF_KIND_FUNC, &kern_btf,
9369 				    &mod_btf);
9370 	if (kfunc_id < 0) {
9371 		if (kfunc_id == -ESRCH && ext->is_weak)
9372 			return 0;
9373 		pr_warn("extern (func ksym) '%s': not found in kernel or module BTFs\n",
9374 			ext->name);
9375 		return kfunc_id;
9376 	}
9377 
9378 	kern_func = btf__type_by_id(kern_btf, kfunc_id);
9379 	kfunc_proto_id = kern_func->type;
9380 
9381 	ret = bpf_core_types_are_compat(obj->btf, local_func_proto_id,
9382 					kern_btf, kfunc_proto_id);
9383 	if (ret <= 0) {
9384 		if (ext->is_weak)
9385 			return 0;
9386 
9387 		pr_warn("extern (func ksym) '%s': func_proto [%d] incompatible with %s [%d]\n",
9388 			ext->name, local_func_proto_id,
9389 			mod_btf ? mod_btf->name : "vmlinux", kfunc_proto_id);
9390 		return -EINVAL;
9391 	}
9392 
9393 	/* set index for module BTF fd in fd_array, if unset */
9394 	if (mod_btf && !mod_btf->fd_array_idx) {
9395 		/* insn->off is s16 */
9396 		if (obj->fd_array_used == INT16_MAX) {
9397 			pr_warn("extern (func ksym) '%s': module BTF fd index %d too big to fit in bpf_insn offset\n",
9398 				ext->name, mod_btf->fd_array_idx);
9399 			return -E2BIG;
9400 		}
9401 		/* Cannot use index 0 for module BTF fd */
9402 		if (!obj->fd_array_used)
9403 			obj->fd_array_used = 1;
9404 
9405 		ret = libbpf_ensure_mem((void **)&obj->fd_array, &obj->fd_array_cap, sizeof(int),
9406 					obj->fd_array_used + 1);
9407 		if (ret)
9408 			return ret;
9409 		mod_btf->fd_array_idx = obj->fd_array_used;
9410 		/* we assume module BTF FD is always >0 */
9411 		obj->fd_array[obj->fd_array_used++] = mod_btf->fd;
9412 	}
9413 
9414 	ext->is_set = true;
9415 	ext->ksym.kernel_btf_id = kfunc_id;
9416 	ext->ksym.btf_fd_idx = mod_btf ? mod_btf->fd_array_idx : 0;
9417 	/* Also set kernel_btf_obj_fd to make sure that bpf_object__relocate_data()
9418 	 * populates FD into ld_imm64 insn when it's used to point to kfunc.
9419 	 * {kernel_btf_id, btf_fd_idx} -> fixup bpf_call.
9420 	 * {kernel_btf_id, kernel_btf_obj_fd} -> fixup ld_imm64.
9421 	 */
9422 	ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
9423 	pr_debug("extern (func ksym) '%s': resolved to %s [%d]\n",
9424 		 ext->name, mod_btf ? mod_btf->name : "vmlinux", kfunc_id);
9425 
9426 	return 0;
9427 }
9428 
9429 static int bpf_object__resolve_ksyms_btf_id(struct bpf_object *obj)
9430 {
9431 	const struct btf_type *t;
9432 	struct extern_desc *ext;
9433 	int i, err;
9434 
9435 	for (i = 0; i < obj->nr_extern; i++) {
9436 		ext = &obj->externs[i];
9437 		if (ext->type != EXT_KSYM || !ext->ksym.type_id)
9438 			continue;
9439 
9440 		if (obj->gen_loader) {
9441 			ext->is_set = true;
9442 			ext->ksym.kernel_btf_obj_fd = 0;
9443 			ext->ksym.kernel_btf_id = 0;
9444 			continue;
9445 		}
9446 		t = btf__type_by_id(obj->btf, ext->btf_id);
9447 		if (btf_is_var(t))
9448 			err = bpf_object__resolve_ksym_var_btf_id(obj, ext);
9449 		else
9450 			err = bpf_object__resolve_ksym_func_btf_id(obj, ext);
9451 		if (err)
9452 			return err;
9453 	}
9454 	return 0;
9455 }
9456 
9457 static int bpf_object__resolve_externs(struct bpf_object *obj,
9458 				       const char *extra_kconfig)
9459 {
9460 	bool need_config = false, need_kallsyms = false;
9461 	bool need_vmlinux_btf = false;
9462 	struct extern_desc *ext;
9463 	void *kcfg_data = NULL;
9464 	int err, i;
9465 
9466 	if (obj->nr_extern == 0)
9467 		return 0;
9468 
9469 	if (obj->kconfig_map_idx >= 0)
9470 		kcfg_data = obj->maps[obj->kconfig_map_idx].mmaped;
9471 
9472 	for (i = 0; i < obj->nr_extern; i++) {
9473 		ext = &obj->externs[i];
9474 
9475 		if (ext->type == EXT_KSYM) {
9476 			if (ext->ksym.type_id)
9477 				need_vmlinux_btf = true;
9478 			else
9479 				need_kallsyms = true;
9480 			continue;
9481 		} else if (ext->type == EXT_KCFG) {
9482 			void *ext_ptr = kcfg_data + ext->kcfg.data_off;
9483 			__u64 value = 0;
9484 
9485 			/* Kconfig externs need actual /proc/config.gz */
9486 			if (str_has_pfx(ext->name, "CONFIG_")) {
9487 				need_config = true;
9488 				continue;
9489 			}
9490 
9491 			/* Virtual kcfg externs are customly handled by libbpf */
9492 			if (strcmp(ext->name, "LINUX_KERNEL_VERSION") == 0) {
9493 				value = get_kernel_version();
9494 				if (!value) {
9495 					pr_warn("extern (kcfg) '%s': failed to get kernel version\n", ext->name);
9496 					return -EINVAL;
9497 				}
9498 			} else if (strcmp(ext->name, "LINUX_HAS_BPF_COOKIE") == 0) {
9499 				value = kernel_supports(obj, FEAT_BPF_COOKIE);
9500 			} else if (strcmp(ext->name, "LINUX_HAS_SYSCALL_WRAPPER") == 0) {
9501 				value = kernel_supports(obj, FEAT_SYSCALL_WRAPPER);
9502 			} else if (!str_has_pfx(ext->name, "LINUX_") || !ext->is_weak) {
9503 				/* Currently libbpf supports only CONFIG_ and LINUX_ prefixed
9504 				 * __kconfig externs, where LINUX_ ones are virtual and filled out
9505 				 * customly by libbpf (their values don't come from Kconfig).
9506 				 * If LINUX_xxx variable is not recognized by libbpf, but is marked
9507 				 * __weak, it defaults to zero value, just like for CONFIG_xxx
9508 				 * externs.
9509 				 */
9510 				pr_warn("extern (kcfg) '%s': unrecognized virtual extern\n", ext->name);
9511 				return -EINVAL;
9512 			}
9513 
9514 			err = set_kcfg_value_num(ext, ext_ptr, value);
9515 			if (err)
9516 				return err;
9517 			pr_debug("extern (kcfg) '%s': set to 0x%llx\n",
9518 				 ext->name, (unsigned long long)value);
9519 		} else {
9520 			pr_warn("extern '%s': unrecognized extern kind\n", ext->name);
9521 			return -EINVAL;
9522 		}
9523 	}
9524 	if (need_config && extra_kconfig) {
9525 		err = bpf_object__read_kconfig_mem(obj, extra_kconfig, kcfg_data);
9526 		if (err)
9527 			return -EINVAL;
9528 		need_config = false;
9529 		for (i = 0; i < obj->nr_extern; i++) {
9530 			ext = &obj->externs[i];
9531 			if (ext->type == EXT_KCFG && !ext->is_set) {
9532 				need_config = true;
9533 				break;
9534 			}
9535 		}
9536 	}
9537 	if (need_config) {
9538 		err = bpf_object__read_kconfig_file(obj, kcfg_data);
9539 		if (err)
9540 			return -EINVAL;
9541 	}
9542 	if (need_kallsyms) {
9543 		err = bpf_object__read_kallsyms_file(obj);
9544 		if (err)
9545 			return -EINVAL;
9546 	}
9547 	if (need_vmlinux_btf) {
9548 		err = bpf_object__resolve_ksyms_btf_id(obj);
9549 		if (err)
9550 			return -EINVAL;
9551 	}
9552 	for (i = 0; i < obj->nr_extern; i++) {
9553 		ext = &obj->externs[i];
9554 
9555 		if (!ext->is_set && !ext->is_weak) {
9556 			pr_warn("extern '%s' (strong): not resolved\n", ext->name);
9557 			return -ESRCH;
9558 		} else if (!ext->is_set) {
9559 			pr_debug("extern '%s' (weak): not resolved, defaulting to zero\n",
9560 				 ext->name);
9561 		}
9562 	}
9563 
9564 	return 0;
9565 }
9566 
9567 static void bpf_map_prepare_vdata(const struct bpf_map *map)
9568 {
9569 	const struct btf_type *type;
9570 	struct bpf_struct_ops *st_ops;
9571 	__u32 i;
9572 
9573 	st_ops = map->st_ops;
9574 	type = btf__type_by_id(map->obj->btf, st_ops->type_id);
9575 	for (i = 0; i < btf_vlen(type); i++) {
9576 		struct bpf_program *prog = st_ops->progs[i];
9577 		void *kern_data;
9578 		int prog_fd;
9579 
9580 		if (!prog)
9581 			continue;
9582 
9583 		prog_fd = bpf_program__fd(prog);
9584 		kern_data = st_ops->kern_vdata + st_ops->kern_func_off[i];
9585 		*(unsigned long *)kern_data = prog_fd;
9586 	}
9587 }
9588 
9589 static int bpf_object_prepare_struct_ops(struct bpf_object *obj)
9590 {
9591 	struct bpf_map *map;
9592 	int i;
9593 
9594 	for (i = 0; i < obj->nr_maps; i++) {
9595 		map = &obj->maps[i];
9596 
9597 		if (!bpf_map__is_struct_ops(map))
9598 			continue;
9599 
9600 		if (!map->autocreate)
9601 			continue;
9602 
9603 		bpf_map_prepare_vdata(map);
9604 	}
9605 
9606 	return 0;
9607 }
9608 
9609 static void bpf_object_unpin(struct bpf_object *obj)
9610 {
9611 	int i;
9612 
9613 	/* unpin any maps that were auto-pinned during load */
9614 	for (i = 0; i < obj->nr_maps; i++)
9615 		if (obj->maps[i].pinned && !obj->maps[i].reused)
9616 			bpf_map__unpin(&obj->maps[i], NULL);
9617 }
9618 
9619 static void bpf_object_cleanup_btf(struct bpf_object *obj)
9620 {
9621 	int i;
9622 
9623 	/* clean up module BTFs */
9624 	for (i = 0; i < obj->btf_module_cnt; i++) {
9625 		close(obj->btf_modules[i].fd);
9626 		btf__free(obj->btf_modules[i].btf);
9627 		free(obj->btf_modules[i].name);
9628 	}
9629 	obj->btf_module_cnt = 0;
9630 	obj->btf_module_cap = 0;
9631 	obj->btf_modules_loaded = false;
9632 	zfree(&obj->btf_modules);
9633 
9634 	/* clean up vmlinux BTF */
9635 	btf__free(obj->btf_vmlinux);
9636 	obj->btf_vmlinux = NULL;
9637 }
9638 
9639 static void bpf_object_post_load_cleanup(struct bpf_object *obj)
9640 {
9641 	/* clean up fd_array, and the slots handed out with it */
9642 	zfree(&obj->fd_array);
9643 	obj->fd_array_cap = 0;
9644 	obj->fd_array_used = 0;
9645 
9646 	/* clean up BTF */
9647 	bpf_object_cleanup_btf(obj);
9648 }
9649 
9650 static int bpf_object_prepare(struct bpf_object *obj, const char *target_btf_path)
9651 {
9652 	int err;
9653 
9654 	if (obj->state >= OBJ_PREPARED) {
9655 		pr_warn("object '%s': prepare loading can't be attempted twice\n", obj->name);
9656 		return -EINVAL;
9657 	}
9658 
9659 	err = bpf_object_prepare_token(obj);
9660 	err = err ? : bpf_object__probe_loading(obj);
9661 	err = err ? : bpf_object__load_vmlinux_btf(obj, false);
9662 	err = err ? : bpf_object__resolve_externs(obj, obj->kconfig);
9663 	err = err ? : bpf_object__sanitize_maps(obj);
9664 	err = err ? : bpf_object__init_kern_struct_ops_maps(obj);
9665 	err = err ? : bpf_object_adjust_struct_ops_autoload(obj);
9666 	err = err ? : bpf_object__relocate(obj, obj->btf_custom_path ? : target_btf_path);
9667 	err = err ? : bpf_object__sanitize_and_load_btf(obj);
9668 	err = err ? : bpf_object__create_maps(obj);
9669 	err = err ? : bpf_object_prepare_progs(obj);
9670 
9671 	if (err) {
9672 		bpf_object_unpin(obj);
9673 		bpf_object_unload(obj);
9674 		obj->state = OBJ_LOADED;
9675 		return err;
9676 	}
9677 
9678 	obj->state = OBJ_PREPARED;
9679 	return 0;
9680 }
9681 
9682 static int bpf_object_load(struct bpf_object *obj, int extra_log_level, const char *target_btf_path)
9683 {
9684 	int err;
9685 
9686 	if (!obj)
9687 		return libbpf_err(-EINVAL);
9688 
9689 	if (obj->state >= OBJ_LOADED) {
9690 		pr_warn("object '%s': load can't be attempted twice\n", obj->name);
9691 		return libbpf_err(-EINVAL);
9692 	}
9693 
9694 	/* Disallow kernel loading programs of non-native endianness but
9695 	 * permit cross-endian creation of "light skeleton".
9696 	 */
9697 	if (obj->gen_loader) {
9698 		int nr_func_ptr_maps = 0, nr_progs = 0, i;
9699 		bool text_has_callx = false;
9700 
9701 		/*
9702 		 * Every program that has callx may get a copy of every map with
9703 		 * pointers to functions. Which functions a program calls is not
9704 		 * known yet. Any of them may call the ones that have callx.
9705 		 */
9706 		for (i = 0; i < obj->nr_maps; i++)
9707 			if (obj->maps[i].autocreate && obj->maps[i].func_ptr_cnt)
9708 				nr_func_ptr_maps++;
9709 		for (i = 0; i < obj->nr_programs; i++)
9710 			if (prog_is_subprog(obj, &obj->programs[i]) &&
9711 			    prog_has_callx(&obj->programs[i]))
9712 				text_has_callx = true;
9713 		for (i = 0; i < obj->nr_programs; i++)
9714 			if (obj->programs[i].autoload && !prog_is_subprog(obj, &obj->programs[i]) &&
9715 			    (text_has_callx || prog_has_callx(&obj->programs[i])))
9716 				nr_progs++;
9717 		bpf_gen__init(obj->gen_loader, obj->log_level | extra_log_level,
9718 			      obj->nr_programs, obj->nr_maps, nr_func_ptr_maps * nr_progs);
9719 	} else if (!is_native_endianness(obj)) {
9720 		pr_warn("object '%s': loading non-native endianness is unsupported\n", obj->name);
9721 		return libbpf_err(-LIBBPF_ERRNO__ENDIAN);
9722 	}
9723 
9724 	if (obj->state < OBJ_PREPARED) {
9725 		err = bpf_object_prepare(obj, target_btf_path);
9726 		if (err)
9727 			return libbpf_err(err);
9728 	}
9729 	err = bpf_object__load_progs(obj, extra_log_level);
9730 	err = err ? : bpf_object_init_prog_arrays(obj);
9731 	err = err ? : bpf_object_prepare_struct_ops(obj);
9732 
9733 	if (obj->gen_loader) {
9734 		/* reset FDs */
9735 		if (obj->btf)
9736 			btf__set_fd(obj->btf, -1);
9737 		if (!err)
9738 			err = bpf_gen__finish(obj->gen_loader, obj->nr_programs, obj->nr_maps);
9739 	}
9740 
9741 	bpf_object_post_load_cleanup(obj);
9742 	obj->state = OBJ_LOADED; /* doesn't matter if successfully or not */
9743 
9744 	if (err) {
9745 		bpf_object_unpin(obj);
9746 		bpf_object_unload(obj);
9747 		pr_warn("failed to load object '%s'\n", obj->path);
9748 		return libbpf_err(err);
9749 	}
9750 
9751 	return 0;
9752 }
9753 
9754 int bpf_object__prepare(struct bpf_object *obj)
9755 {
9756 	return libbpf_err(bpf_object_prepare(obj, NULL));
9757 }
9758 
9759 int bpf_object__load(struct bpf_object *obj)
9760 {
9761 	return bpf_object_load(obj, 0, NULL);
9762 }
9763 
9764 static int make_parent_dir(const char *path)
9765 {
9766 	char *dname, *dir;
9767 	int err = 0;
9768 
9769 	dname = strdup(path);
9770 	if (dname == NULL)
9771 		return -ENOMEM;
9772 
9773 	dir = dirname(dname);
9774 	if (mkdir(dir, 0700) && errno != EEXIST)
9775 		err = -errno;
9776 
9777 	free(dname);
9778 	if (err) {
9779 		pr_warn("failed to mkdir %s: %s\n", path, errstr(err));
9780 	}
9781 	return err;
9782 }
9783 
9784 static int check_path(const char *path)
9785 {
9786 	struct statfs st_fs;
9787 	char *dname, *dir;
9788 	int err = 0;
9789 
9790 	if (path == NULL)
9791 		return -EINVAL;
9792 
9793 	dname = strdup(path);
9794 	if (dname == NULL)
9795 		return -ENOMEM;
9796 
9797 	dir = dirname(dname);
9798 	if (statfs(dir, &st_fs)) {
9799 		pr_warn("failed to statfs %s: %s\n", dir, errstr(errno));
9800 		err = -errno;
9801 	}
9802 	free(dname);
9803 
9804 	if (!err && st_fs.f_type != BPF_FS_MAGIC) {
9805 		pr_warn("specified path %s is not on BPF FS\n", path);
9806 		err = -EINVAL;
9807 	}
9808 
9809 	return err;
9810 }
9811 
9812 int bpf_program__pin(struct bpf_program *prog, const char *path)
9813 {
9814 	int err;
9815 
9816 	if (prog->fd < 0) {
9817 		pr_warn("prog '%s': can't pin program that wasn't loaded\n", prog->name);
9818 		return libbpf_err(-EINVAL);
9819 	}
9820 
9821 	err = make_parent_dir(path);
9822 	if (err)
9823 		return libbpf_err(err);
9824 
9825 	err = check_path(path);
9826 	if (err)
9827 		return libbpf_err(err);
9828 
9829 	if (bpf_obj_pin(prog->fd, path)) {
9830 		err = -errno;
9831 		pr_warn("prog '%s': failed to pin at '%s': %s\n", prog->name, path, errstr(err));
9832 		return libbpf_err(err);
9833 	}
9834 
9835 	pr_debug("prog '%s': pinned at '%s'\n", prog->name, path);
9836 	return 0;
9837 }
9838 
9839 int bpf_program__unpin(struct bpf_program *prog, const char *path)
9840 {
9841 	int err;
9842 
9843 	if (prog->fd < 0) {
9844 		pr_warn("prog '%s': can't unpin program that wasn't loaded\n", prog->name);
9845 		return libbpf_err(-EINVAL);
9846 	}
9847 
9848 	err = check_path(path);
9849 	if (err)
9850 		return libbpf_err(err);
9851 
9852 	err = unlink(path);
9853 	if (err)
9854 		return libbpf_err(-errno);
9855 
9856 	pr_debug("prog '%s': unpinned from '%s'\n", prog->name, path);
9857 	return 0;
9858 }
9859 
9860 int bpf_map__pin(struct bpf_map *map, const char *path)
9861 {
9862 	int err;
9863 
9864 	if (map == NULL) {
9865 		pr_warn("invalid map pointer\n");
9866 		return libbpf_err(-EINVAL);
9867 	}
9868 
9869 	if (map->fd < 0) {
9870 		pr_warn("map '%s': can't pin BPF map without FD (was it created?)\n", map->name);
9871 		return libbpf_err(-EINVAL);
9872 	}
9873 
9874 	if (map->pin_path) {
9875 		if (path && strcmp(path, map->pin_path)) {
9876 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
9877 				bpf_map__name(map), map->pin_path, path);
9878 			return libbpf_err(-EINVAL);
9879 		} else if (map->pinned) {
9880 			pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
9881 				 bpf_map__name(map), map->pin_path);
9882 			return 0;
9883 		}
9884 	} else {
9885 		if (!path) {
9886 			pr_warn("missing a path to pin map '%s' at\n",
9887 				bpf_map__name(map));
9888 			return libbpf_err(-EINVAL);
9889 		} else if (map->pinned) {
9890 			pr_warn("map '%s' already pinned\n", bpf_map__name(map));
9891 			return libbpf_err(-EEXIST);
9892 		}
9893 
9894 		map->pin_path = strdup(path);
9895 		if (!map->pin_path) {
9896 			err = -errno;
9897 			goto out_err;
9898 		}
9899 	}
9900 
9901 	err = make_parent_dir(map->pin_path);
9902 	if (err)
9903 		return libbpf_err(err);
9904 
9905 	err = check_path(map->pin_path);
9906 	if (err)
9907 		return libbpf_err(err);
9908 
9909 	if (bpf_obj_pin(map->fd, map->pin_path)) {
9910 		err = -errno;
9911 		goto out_err;
9912 	}
9913 
9914 	map->pinned = true;
9915 	pr_debug("pinned map '%s'\n", map->pin_path);
9916 
9917 	return 0;
9918 
9919 out_err:
9920 	pr_warn("failed to pin map: %s\n", errstr(err));
9921 	return libbpf_err(err);
9922 }
9923 
9924 int bpf_map__unpin(struct bpf_map *map, const char *path)
9925 {
9926 	int err;
9927 
9928 	if (map == NULL) {
9929 		pr_warn("invalid map pointer\n");
9930 		return libbpf_err(-EINVAL);
9931 	}
9932 
9933 	if (map->pin_path) {
9934 		if (path && strcmp(path, map->pin_path)) {
9935 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
9936 				bpf_map__name(map), map->pin_path, path);
9937 			return libbpf_err(-EINVAL);
9938 		}
9939 		path = map->pin_path;
9940 	} else if (!path) {
9941 		pr_warn("no path to unpin map '%s' from\n",
9942 			bpf_map__name(map));
9943 		return libbpf_err(-EINVAL);
9944 	}
9945 
9946 	err = check_path(path);
9947 	if (err)
9948 		return libbpf_err(err);
9949 
9950 	err = unlink(path);
9951 	if (err != 0)
9952 		return libbpf_err(-errno);
9953 
9954 	map->pinned = false;
9955 	pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path);
9956 
9957 	return 0;
9958 }
9959 
9960 int bpf_map__set_pin_path(struct bpf_map *map, const char *path)
9961 {
9962 	char *new = NULL;
9963 
9964 	if (path) {
9965 		new = strdup(path);
9966 		if (!new)
9967 			return libbpf_err(-errno);
9968 	}
9969 
9970 	free(map->pin_path);
9971 	map->pin_path = new;
9972 	return 0;
9973 }
9974 
9975 __alias(bpf_map__pin_path)
9976 const char *bpf_map__get_pin_path(const struct bpf_map *map);
9977 
9978 const char *bpf_map__pin_path(const struct bpf_map *map)
9979 {
9980 	return map->pin_path;
9981 }
9982 
9983 bool bpf_map__is_pinned(const struct bpf_map *map)
9984 {
9985 	return map->pinned;
9986 }
9987 
9988 static void sanitize_pin_path(char *s)
9989 {
9990 	/* bpffs disallows periods in path names */
9991 	while (*s) {
9992 		if (*s == '.')
9993 			*s = '_';
9994 		s++;
9995 	}
9996 }
9997 
9998 int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
9999 {
10000 	struct bpf_map *map;
10001 	int err;
10002 
10003 	if (!obj)
10004 		return libbpf_err(-ENOENT);
10005 
10006 	if (obj->state < OBJ_PREPARED) {
10007 		pr_warn("object not yet loaded; load it first\n");
10008 		return libbpf_err(-ENOENT);
10009 	}
10010 
10011 	bpf_object__for_each_map(map, obj) {
10012 		char *pin_path = NULL;
10013 		char buf[PATH_MAX];
10014 
10015 		if (!map->autocreate)
10016 			continue;
10017 
10018 		if (path) {
10019 			err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
10020 			if (err)
10021 				goto err_unpin_maps;
10022 			sanitize_pin_path(buf);
10023 			pin_path = buf;
10024 		} else if (!map->pin_path) {
10025 			continue;
10026 		}
10027 
10028 		err = bpf_map__pin(map, pin_path);
10029 		if (err)
10030 			goto err_unpin_maps;
10031 	}
10032 
10033 	return 0;
10034 
10035 err_unpin_maps:
10036 	while ((map = bpf_object__prev_map(obj, map))) {
10037 		if (!map->pin_path)
10038 			continue;
10039 
10040 		bpf_map__unpin(map, NULL);
10041 	}
10042 
10043 	return libbpf_err(err);
10044 }
10045 
10046 int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
10047 {
10048 	struct bpf_map *map;
10049 	int err;
10050 
10051 	if (!obj)
10052 		return libbpf_err(-ENOENT);
10053 
10054 	bpf_object__for_each_map(map, obj) {
10055 		char *pin_path = NULL;
10056 		char buf[PATH_MAX];
10057 
10058 		if (path) {
10059 			err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
10060 			if (err)
10061 				return libbpf_err(err);
10062 			sanitize_pin_path(buf);
10063 			pin_path = buf;
10064 		} else if (!map->pin_path) {
10065 			continue;
10066 		}
10067 
10068 		err = bpf_map__unpin(map, pin_path);
10069 		if (err)
10070 			return libbpf_err(err);
10071 	}
10072 
10073 	return 0;
10074 }
10075 
10076 int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
10077 {
10078 	struct bpf_program *prog;
10079 	char buf[PATH_MAX];
10080 	int err;
10081 
10082 	if (!obj)
10083 		return libbpf_err(-ENOENT);
10084 
10085 	if (obj->state < OBJ_LOADED) {
10086 		pr_warn("object not yet loaded; load it first\n");
10087 		return libbpf_err(-ENOENT);
10088 	}
10089 
10090 	bpf_object__for_each_program(prog, obj) {
10091 		err = pathname_concat(buf, sizeof(buf), path, prog->name);
10092 		if (err)
10093 			goto err_unpin_programs;
10094 
10095 		err = bpf_program__pin(prog, buf);
10096 		if (err)
10097 			goto err_unpin_programs;
10098 	}
10099 
10100 	return 0;
10101 
10102 err_unpin_programs:
10103 	while ((prog = bpf_object__prev_program(obj, prog))) {
10104 		if (pathname_concat(buf, sizeof(buf), path, prog->name))
10105 			continue;
10106 
10107 		bpf_program__unpin(prog, buf);
10108 	}
10109 
10110 	return libbpf_err(err);
10111 }
10112 
10113 int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
10114 {
10115 	struct bpf_program *prog;
10116 	int err;
10117 
10118 	if (!obj)
10119 		return libbpf_err(-ENOENT);
10120 
10121 	bpf_object__for_each_program(prog, obj) {
10122 		char buf[PATH_MAX];
10123 
10124 		err = pathname_concat(buf, sizeof(buf), path, prog->name);
10125 		if (err)
10126 			return libbpf_err(err);
10127 
10128 		err = bpf_program__unpin(prog, buf);
10129 		if (err)
10130 			return libbpf_err(err);
10131 	}
10132 
10133 	return 0;
10134 }
10135 
10136 int bpf_object__pin(struct bpf_object *obj, const char *path)
10137 {
10138 	int err;
10139 
10140 	err = bpf_object__pin_maps(obj, path);
10141 	if (err)
10142 		return libbpf_err(err);
10143 
10144 	err = bpf_object__pin_programs(obj, path);
10145 	if (err) {
10146 		bpf_object__unpin_maps(obj, path);
10147 		return libbpf_err(err);
10148 	}
10149 
10150 	return 0;
10151 }
10152 
10153 int bpf_object__unpin(struct bpf_object *obj, const char *path)
10154 {
10155 	int err;
10156 
10157 	err = bpf_object__unpin_programs(obj, path);
10158 	if (err)
10159 		return libbpf_err(err);
10160 
10161 	err = bpf_object__unpin_maps(obj, path);
10162 	if (err)
10163 		return libbpf_err(err);
10164 
10165 	return 0;
10166 }
10167 
10168 static void bpf_map__destroy(struct bpf_map *map)
10169 {
10170 	if (map->inner_map) {
10171 		bpf_map__destroy(map->inner_map);
10172 		zfree(&map->inner_map);
10173 	}
10174 
10175 	zfree(&map->init_slots);
10176 	map->init_slots_sz = 0;
10177 
10178 	if (map->mmaped && map->mmaped != map->obj->arena_data)
10179 		munmap(map->mmaped, bpf_map_mmap_sz(map));
10180 	map->mmaped = NULL;
10181 
10182 	if (map->st_ops) {
10183 		zfree(&map->st_ops->data);
10184 		zfree(&map->st_ops->progs);
10185 		zfree(&map->st_ops->kern_func_off);
10186 		zfree(&map->st_ops);
10187 	}
10188 
10189 	zfree(&map->name);
10190 	zfree(&map->real_name);
10191 	zfree(&map->pin_path);
10192 
10193 	if (map->fd >= 0)
10194 		zclose(map->fd);
10195 }
10196 
10197 void bpf_object__close(struct bpf_object *obj)
10198 {
10199 	size_t i;
10200 
10201 	if (IS_ERR_OR_NULL(obj))
10202 		return;
10203 
10204 	/*
10205 	 * if user called bpf_object__prepare() without ever getting to
10206 	 * bpf_object__load(), we need to clean up stuff that is normally
10207 	 * cleaned up at the end of loading step
10208 	 */
10209 	bpf_object_post_load_cleanup(obj);
10210 
10211 	usdt_manager_free(obj->usdt_man);
10212 	obj->usdt_man = NULL;
10213 
10214 	bpf_gen__free(obj->gen_loader);
10215 	bpf_object__elf_finish(obj);
10216 	bpf_object_unload(obj);
10217 	btf__free(obj->btf);
10218 	btf__free(obj->btf_vmlinux);
10219 	btf_ext__free(obj->btf_ext);
10220 
10221 	for (i = 0; i < obj->nr_maps; i++)
10222 		bpf_map__destroy(&obj->maps[i]);
10223 
10224 	zfree(&obj->btf_custom_path);
10225 	zfree(&obj->kconfig);
10226 
10227 	for (i = 0; i < obj->nr_extern; i++) {
10228 		zfree(&obj->externs[i].name);
10229 		zfree(&obj->externs[i].essent_name);
10230 	}
10231 
10232 	zfree(&obj->externs);
10233 	obj->nr_extern = 0;
10234 
10235 	zfree(&obj->maps);
10236 	obj->nr_maps = 0;
10237 
10238 	if (obj->programs && obj->nr_programs) {
10239 		for (i = 0; i < obj->nr_programs; i++)
10240 			bpf_program__exit(&obj->programs[i]);
10241 	}
10242 	zfree(&obj->programs);
10243 
10244 	zfree(&obj->feat_cache);
10245 	zfree(&obj->token_path);
10246 	if (obj->token_fd > 0)
10247 		close(obj->token_fd);
10248 
10249 	zfree(&obj->arena_data);
10250 
10251 	zfree(&obj->jumptables_data);
10252 	obj->jumptables_data_sz = 0;
10253 
10254 	for (i = 0; i < obj->jumptable_map_cnt; i++)
10255 		close(obj->jumptable_maps[i].fd);
10256 	zfree(&obj->jumptable_maps);
10257 
10258 	for (i = 0; i < obj->func_ptr_map_cnt; i++)
10259 		if (!obj->gen_loader)
10260 			close(obj->func_ptr_maps[i].fd);
10261 	zfree(&obj->func_ptr_maps);
10262 	zfree(&obj->func_ptrs);
10263 
10264 	if (obj->btf_module_allowlist) {
10265 		for (i = 0; i < obj->btf_module_allowlist_cnt; i++)
10266 			zfree(&obj->btf_module_allowlist[i]);
10267 		zfree(&obj->btf_module_allowlist);
10268 	}
10269 
10270 	free(obj);
10271 }
10272 
10273 const char *bpf_object__name(const struct bpf_object *obj)
10274 {
10275 	return obj ? obj->name : libbpf_err_ptr(-EINVAL);
10276 }
10277 
10278 unsigned int bpf_object__kversion(const struct bpf_object *obj)
10279 {
10280 	return obj ? obj->kern_version : 0;
10281 }
10282 
10283 int bpf_object__token_fd(const struct bpf_object *obj)
10284 {
10285 	return obj->token_fd ?: -1;
10286 }
10287 
10288 struct btf *bpf_object__btf(const struct bpf_object *obj)
10289 {
10290 	return obj ? obj->btf : NULL;
10291 }
10292 
10293 int bpf_object__btf_fd(const struct bpf_object *obj)
10294 {
10295 	return obj->btf ? btf__fd(obj->btf) : -1;
10296 }
10297 
10298 int bpf_object__set_kversion(struct bpf_object *obj, __u32 kern_version)
10299 {
10300 	if (obj->state >= OBJ_LOADED)
10301 		return libbpf_err(-EINVAL);
10302 
10303 	obj->kern_version = kern_version;
10304 
10305 	return 0;
10306 }
10307 
10308 int bpf_object__gen_loader(struct bpf_object *obj, struct gen_loader_opts *opts)
10309 {
10310 	struct bpf_gen *gen;
10311 
10312 	if (!opts)
10313 		return libbpf_err(-EFAULT);
10314 	if (!OPTS_VALID(opts, gen_loader_opts))
10315 		return libbpf_err(-EINVAL);
10316 	gen = calloc(1, sizeof(*gen));
10317 	if (!gen)
10318 		return libbpf_err(-ENOMEM);
10319 	gen->opts = opts;
10320 	gen->swapped_endian = !is_native_endianness(obj);
10321 	obj->gen_loader = gen;
10322 	return 0;
10323 }
10324 
10325 static struct bpf_program *
10326 __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
10327 		    bool forward)
10328 {
10329 	size_t nr_programs = obj->nr_programs;
10330 	ssize_t idx;
10331 
10332 	if (!nr_programs)
10333 		return NULL;
10334 
10335 	if (!p)
10336 		/* Iter from the beginning */
10337 		return forward ? &obj->programs[0] :
10338 			&obj->programs[nr_programs - 1];
10339 
10340 	if (p->obj != obj) {
10341 		pr_warn("error: program handler doesn't match object\n");
10342 		return errno = EINVAL, NULL;
10343 	}
10344 
10345 	idx = (p - obj->programs) + (forward ? 1 : -1);
10346 	if (idx >= obj->nr_programs || idx < 0)
10347 		return NULL;
10348 	return &obj->programs[idx];
10349 }
10350 
10351 struct bpf_program *
10352 bpf_object__next_program(const struct bpf_object *obj, struct bpf_program *prev)
10353 {
10354 	struct bpf_program *prog = prev;
10355 
10356 	do {
10357 		prog = __bpf_program__iter(prog, obj, true);
10358 	} while (prog && prog_is_subprog(obj, prog));
10359 
10360 	return prog;
10361 }
10362 
10363 struct bpf_program *
10364 bpf_object__prev_program(const struct bpf_object *obj, struct bpf_program *next)
10365 {
10366 	struct bpf_program *prog = next;
10367 
10368 	do {
10369 		prog = __bpf_program__iter(prog, obj, false);
10370 	} while (prog && prog_is_subprog(obj, prog));
10371 
10372 	return prog;
10373 }
10374 
10375 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
10376 {
10377 	prog->prog_ifindex = ifindex;
10378 }
10379 
10380 const char *bpf_program__name(const struct bpf_program *prog)
10381 {
10382 	return prog->name;
10383 }
10384 
10385 const char *bpf_program__section_name(const struct bpf_program *prog)
10386 {
10387 	return prog->sec_name;
10388 }
10389 
10390 bool bpf_program__autoload(const struct bpf_program *prog)
10391 {
10392 	return prog->autoload;
10393 }
10394 
10395 int bpf_program__set_autoload(struct bpf_program *prog, bool autoload)
10396 {
10397 	if (prog->obj->state >= OBJ_LOADED)
10398 		return libbpf_err(-EINVAL);
10399 
10400 	prog->autoload = autoload;
10401 	return 0;
10402 }
10403 
10404 bool bpf_program__autoattach(const struct bpf_program *prog)
10405 {
10406 	return prog->autoattach;
10407 }
10408 
10409 void bpf_program__set_autoattach(struct bpf_program *prog, bool autoattach)
10410 {
10411 	prog->autoattach = autoattach;
10412 }
10413 
10414 const struct bpf_insn *bpf_program__insns(const struct bpf_program *prog)
10415 {
10416 	return prog->insns;
10417 }
10418 
10419 size_t bpf_program__insn_cnt(const struct bpf_program *prog)
10420 {
10421 	return prog->insns_cnt;
10422 }
10423 
10424 int bpf_program__set_insns(struct bpf_program *prog,
10425 			   struct bpf_insn *new_insns, size_t new_insn_cnt)
10426 {
10427 	struct bpf_insn *insns;
10428 
10429 	if (prog->obj->state >= OBJ_LOADED)
10430 		return libbpf_err(-EBUSY);
10431 
10432 	insns = libbpf_reallocarray(prog->insns, new_insn_cnt, sizeof(*insns));
10433 	/* NULL is a valid return from reallocarray if the new count is zero */
10434 	if (!insns && new_insn_cnt) {
10435 		pr_warn("prog '%s': failed to realloc prog code\n", prog->name);
10436 		return libbpf_err(-ENOMEM);
10437 	}
10438 	memcpy(insns, new_insns, new_insn_cnt * sizeof(*insns));
10439 
10440 	prog->insns = insns;
10441 	prog->insns_cnt = new_insn_cnt;
10442 	return 0;
10443 }
10444 
10445 int bpf_program__fd(const struct bpf_program *prog)
10446 {
10447 	if (!prog)
10448 		return libbpf_err(-EINVAL);
10449 
10450 	if (prog->fd < 0)
10451 		return libbpf_err(-ENOENT);
10452 
10453 	return prog->fd;
10454 }
10455 
10456 __alias(bpf_program__type)
10457 enum bpf_prog_type bpf_program__get_type(const struct bpf_program *prog);
10458 
10459 enum bpf_prog_type bpf_program__type(const struct bpf_program *prog)
10460 {
10461 	return prog->type;
10462 }
10463 
10464 static size_t custom_sec_def_cnt;
10465 static struct bpf_sec_def *custom_sec_defs;
10466 static struct bpf_sec_def custom_fallback_def;
10467 static bool has_custom_fallback_def;
10468 static int last_custom_sec_def_handler_id;
10469 
10470 int bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
10471 {
10472 	if (prog->obj->state >= OBJ_LOADED)
10473 		return libbpf_err(-EBUSY);
10474 
10475 	/* if type is not changed, do nothing */
10476 	if (prog->type == type)
10477 		return 0;
10478 
10479 	prog->type = type;
10480 
10481 	/* If a program type was changed, we need to reset associated SEC()
10482 	 * handler, as it will be invalid now. The only exception is a generic
10483 	 * fallback handler, which by definition is program type-agnostic and
10484 	 * is a catch-all custom handler, optionally set by the application,
10485 	 * so should be able to handle any type of BPF program.
10486 	 */
10487 	if (prog->sec_def != &custom_fallback_def)
10488 		prog->sec_def = NULL;
10489 	return 0;
10490 }
10491 
10492 __alias(bpf_program__expected_attach_type)
10493 enum bpf_attach_type bpf_program__get_expected_attach_type(const struct bpf_program *prog);
10494 
10495 enum bpf_attach_type bpf_program__expected_attach_type(const struct bpf_program *prog)
10496 {
10497 	return prog->expected_attach_type;
10498 }
10499 
10500 int bpf_program__set_expected_attach_type(struct bpf_program *prog,
10501 					   enum bpf_attach_type type)
10502 {
10503 	if (prog->obj->state >= OBJ_LOADED)
10504 		return libbpf_err(-EBUSY);
10505 
10506 	prog->expected_attach_type = type;
10507 	return 0;
10508 }
10509 
10510 __u32 bpf_program__flags(const struct bpf_program *prog)
10511 {
10512 	return prog->prog_flags;
10513 }
10514 
10515 int bpf_program__set_flags(struct bpf_program *prog, __u32 flags)
10516 {
10517 	if (prog->obj->state >= OBJ_LOADED)
10518 		return libbpf_err(-EBUSY);
10519 
10520 	prog->prog_flags = flags;
10521 	return 0;
10522 }
10523 
10524 int bpf_program__add_flags(struct bpf_program *prog, __u32 flags)
10525 {
10526 	return bpf_program__set_flags(prog, prog->prog_flags | flags);
10527 }
10528 
10529 int bpf_program__clear_flags(struct bpf_program *prog, __u32 flags)
10530 {
10531 	return bpf_program__set_flags(prog, prog->prog_flags & ~flags);
10532 }
10533 
10534 __u32 bpf_program__log_level(const struct bpf_program *prog)
10535 {
10536 	return prog->log_level;
10537 }
10538 
10539 int bpf_program__set_log_level(struct bpf_program *prog, __u32 log_level)
10540 {
10541 	if (prog->obj->state >= OBJ_LOADED)
10542 		return libbpf_err(-EBUSY);
10543 
10544 	prog->log_level = log_level;
10545 	return 0;
10546 }
10547 
10548 const char *bpf_program__log_buf(const struct bpf_program *prog, size_t *log_size)
10549 {
10550 	*log_size = prog->log_size;
10551 	return prog->log_buf;
10552 }
10553 
10554 int bpf_program__set_log_buf(struct bpf_program *prog, char *log_buf, size_t log_size)
10555 {
10556 	if (!!log_buf != !!log_size)
10557 		return libbpf_err(-EINVAL);
10558 	if (log_size > UINT_MAX)
10559 		return libbpf_err(-EINVAL);
10560 	if (prog->obj->state >= OBJ_LOADED)
10561 		return libbpf_err(-EBUSY);
10562 
10563 	prog->log_buf = log_buf;
10564 	prog->log_size = log_size;
10565 	return 0;
10566 }
10567 
10568 struct bpf_func_info *bpf_program__func_info(const struct bpf_program *prog)
10569 {
10570 	if (prog->func_info_rec_size != sizeof(struct bpf_func_info))
10571 		return libbpf_err_ptr(-EOPNOTSUPP);
10572 	return prog->func_info;
10573 }
10574 
10575 __u32 bpf_program__func_info_cnt(const struct bpf_program *prog)
10576 {
10577 	return prog->func_info_cnt;
10578 }
10579 
10580 struct bpf_line_info *bpf_program__line_info(const struct bpf_program *prog)
10581 {
10582 	if (prog->line_info_rec_size != sizeof(struct bpf_line_info))
10583 		return libbpf_err_ptr(-EOPNOTSUPP);
10584 	return prog->line_info;
10585 }
10586 
10587 __u32 bpf_program__line_info_cnt(const struct bpf_program *prog)
10588 {
10589 	return prog->line_info_cnt;
10590 }
10591 
10592 int bpf_program__clone(struct bpf_program *prog, const struct bpf_prog_load_opts *opts)
10593 {
10594 	LIBBPF_OPTS(bpf_prog_load_opts, attr);
10595 	struct bpf_object *obj;
10596 	const void *info;
10597 	__u32 info_cnt, info_rec_size;
10598 	int err, fd, prog_btf_fd;
10599 
10600 	if (!prog)
10601 		return libbpf_err(-EINVAL);
10602 
10603 	if (!OPTS_VALID(opts, bpf_prog_load_opts))
10604 		return libbpf_err(-EINVAL);
10605 
10606 	obj = prog->obj;
10607 	if (obj->state < OBJ_PREPARED)
10608 		return libbpf_err(-EINVAL);
10609 
10610 	/*
10611 	 * Caller-provided opts take priority; fall back to
10612 	 * prog/object defaults when the caller leaves them zero.
10613 	 */
10614 	attr.attach_prog_fd = OPTS_GET(opts, attach_prog_fd, 0) ?: prog->attach_prog_fd;
10615 	attr.prog_flags = OPTS_GET(opts, prog_flags, 0) ?: prog->prog_flags;
10616 	attr.prog_ifindex = OPTS_GET(opts, prog_ifindex, 0) ?: prog->prog_ifindex;
10617 	attr.kern_version = OPTS_GET(opts, kern_version, 0) ?: obj->kern_version;
10618 	attr.fd_array = OPTS_GET(opts, fd_array, NULL) ?: obj->fd_array;
10619 	attr.fd_array_cnt = OPTS_GET(opts, fd_array_cnt, 0);
10620 	/* the arena of the object goes with the program, as in bpf_object__load() */
10621 	if (!OPTS_GET(opts, fd_array, NULL) && !OPTS_GET(opts, fd_array_cnt, 0)) {
10622 		err = bpf_object__bind_arena(obj, prog, &attr);
10623 		if (err)
10624 			return libbpf_err(err);
10625 	}
10626 	attr.token_fd = OPTS_GET(opts, token_fd, 0) ?: obj->token_fd;
10627 	if (attr.token_fd)
10628 		attr.prog_flags |= BPF_F_TOKEN_FD;
10629 
10630 	prog_btf_fd = OPTS_GET(opts, prog_btf_fd, 0);
10631 	if (!prog_btf_fd && obj->btf)
10632 		prog_btf_fd = btf__fd(obj->btf);
10633 
10634 	/* BTF func/line info: only pass if kernel supports it */
10635 	if (kernel_supports(obj, FEAT_BTF_FUNC) && prog_btf_fd > 0) {
10636 		attr.prog_btf_fd = prog_btf_fd;
10637 
10638 		/* func_info/line_info triples: all-or-nothing from caller */
10639 		info = OPTS_GET(opts, func_info, NULL);
10640 		info_cnt = OPTS_GET(opts, func_info_cnt, 0);
10641 		info_rec_size = OPTS_GET(opts, func_info_rec_size, 0);
10642 		if (!!info != !!info_cnt || !!info != !!info_rec_size) {
10643 			pr_warn("prog '%s': func_info, func_info_cnt, and func_info_rec_size must all be specified or all omitted\n",
10644 				prog->name);
10645 			return libbpf_err(-EINVAL);
10646 		}
10647 		attr.func_info = info ?: prog->func_info;
10648 		attr.func_info_cnt = info ? info_cnt : prog->func_info_cnt;
10649 		attr.func_info_rec_size = info ? info_rec_size : prog->func_info_rec_size;
10650 
10651 		info = OPTS_GET(opts, line_info, NULL);
10652 		info_cnt = OPTS_GET(opts, line_info_cnt, 0);
10653 		info_rec_size = OPTS_GET(opts, line_info_rec_size, 0);
10654 		if (!!info != !!info_cnt || !!info != !!info_rec_size) {
10655 			pr_warn("prog '%s': line_info, line_info_cnt, and line_info_rec_size must all be specified or all omitted\n",
10656 				prog->name);
10657 			return libbpf_err(-EINVAL);
10658 		}
10659 		attr.line_info = info ?: prog->line_info;
10660 		attr.line_info_cnt = info ? info_cnt : prog->line_info_cnt;
10661 		attr.line_info_rec_size = info ? info_rec_size : prog->line_info_rec_size;
10662 	}
10663 
10664 	/* Logging is caller-controlled; no fallback to prog/obj log settings */
10665 	attr.log_buf = OPTS_GET(opts, log_buf, NULL);
10666 	attr.log_size = OPTS_GET(opts, log_size, 0);
10667 	attr.log_level = OPTS_GET(opts, log_level, 0);
10668 
10669 	/*
10670 	 * Fields below may be mutated by prog_prepare_load_fn:
10671 	 * Seed them from prog/obj defaults here;
10672 	 * Later override with caller-provided opts.
10673 	 */
10674 	attr.expected_attach_type = prog->expected_attach_type;
10675 	attr.attach_btf_id = prog->attach_btf_id;
10676 	attr.attach_btf_obj_fd = prog->attach_btf_obj_fd;
10677 
10678 	if (prog->sec_def && prog->sec_def->prog_prepare_load_fn) {
10679 		err = prog->sec_def->prog_prepare_load_fn(prog, &attr, prog->sec_def->cookie);
10680 		if (err)
10681 			return libbpf_err(err);
10682 	}
10683 
10684 	/* Re-apply caller overrides for output fields */
10685 	if (OPTS_GET(opts, expected_attach_type, 0))
10686 		attr.expected_attach_type = OPTS_GET(opts, expected_attach_type, 0);
10687 	if (OPTS_GET(opts, attach_btf_id, 0))
10688 		attr.attach_btf_id = OPTS_GET(opts, attach_btf_id, 0);
10689 	if (OPTS_GET(opts, attach_btf_obj_fd, 0))
10690 		attr.attach_btf_obj_fd = OPTS_GET(opts, attach_btf_obj_fd, 0);
10691 
10692 	/*
10693 	 * Unlike bpf_object_load_prog(), we intentionally do not call bpf_prog_bind_map()
10694 	 * for RODATA maps here to avoid mutating the object's state. Callers can bind the
10695 	 * required maps themselves using bpf_prog_bind_map().
10696 	 */
10697 	fd = bpf_prog_load(prog->type, prog->name, obj->license, prog->insns, prog->insns_cnt,
10698 			   &attr);
10699 
10700 	return libbpf_err(fd);
10701 }
10702 
10703 #define SEC_DEF(sec_pfx, ptype, atype, flags, ...) {			    \
10704 	.sec = (char *)sec_pfx,						    \
10705 	.prog_type = BPF_PROG_TYPE_##ptype,				    \
10706 	.expected_attach_type = atype,					    \
10707 	.cookie = (long)(flags),					    \
10708 	.prog_setup_fn = libbpf_setup_prog_flags,			    \
10709 	.prog_prepare_load_fn = libbpf_prepare_prog_load,		    \
10710 	__VA_ARGS__							    \
10711 }
10712 
10713 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
10714 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
10715 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link);
10716 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link);
10717 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
10718 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
10719 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link);
10720 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
10721 static int attach_kprobe_session(const struct bpf_program *prog, long cookie, struct bpf_link **link);
10722 static int attach_uprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
10723 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link);
10724 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link);
10725 static int attach_tracing_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
10726 
10727 static const struct bpf_sec_def section_defs[] = {
10728 	SEC_DEF("socket",		SOCKET_FILTER, 0, SEC_NONE),
10729 	SEC_DEF("sk_reuseport/migrate",	SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT_OR_MIGRATE, SEC_ATTACHABLE),
10730 	SEC_DEF("sk_reuseport",		SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT, SEC_ATTACHABLE),
10731 	SEC_DEF("kprobe+",		KPROBE,	0, SEC_NONE, attach_kprobe),
10732 	SEC_DEF("uprobe+",		KPROBE,	0, SEC_NONE, attach_uprobe),
10733 	SEC_DEF("uprobe.s+",		KPROBE,	0, SEC_SLEEPABLE, attach_uprobe),
10734 	SEC_DEF("kretprobe+",		KPROBE, 0, SEC_NONE, attach_kprobe),
10735 	SEC_DEF("uretprobe+",		KPROBE, 0, SEC_NONE, attach_uprobe),
10736 	SEC_DEF("uretprobe.s+",		KPROBE, 0, SEC_SLEEPABLE, attach_uprobe),
10737 	SEC_DEF("kprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
10738 	SEC_DEF("kretprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
10739 	SEC_DEF("kprobe.session+",	KPROBE,	BPF_TRACE_KPROBE_SESSION, SEC_NONE, attach_kprobe_session),
10740 	SEC_DEF("uprobe.multi+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_NONE, attach_uprobe_multi),
10741 	SEC_DEF("uretprobe.multi+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_NONE, attach_uprobe_multi),
10742 	SEC_DEF("uprobe.session+",	KPROBE,	BPF_TRACE_UPROBE_SESSION, SEC_NONE, attach_uprobe_multi),
10743 	SEC_DEF("uprobe.multi.s+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_SLEEPABLE, attach_uprobe_multi),
10744 	SEC_DEF("uretprobe.multi.s+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_SLEEPABLE, attach_uprobe_multi),
10745 	SEC_DEF("uprobe.session.s+",	KPROBE,	BPF_TRACE_UPROBE_SESSION, SEC_SLEEPABLE, attach_uprobe_multi),
10746 	SEC_DEF("ksyscall+",		KPROBE,	0, SEC_NONE, attach_ksyscall),
10747 	SEC_DEF("kretsyscall+",		KPROBE, 0, SEC_NONE, attach_ksyscall),
10748 	SEC_DEF("usdt+",		KPROBE,	0, SEC_USDT, attach_usdt),
10749 	SEC_DEF("usdt.s+",		KPROBE,	0, SEC_USDT | SEC_SLEEPABLE, attach_usdt),
10750 	SEC_DEF("tc/ingress",		SCHED_CLS, BPF_TCX_INGRESS, SEC_NONE), /* alias for tcx */
10751 	SEC_DEF("tc/egress",		SCHED_CLS, BPF_TCX_EGRESS, SEC_NONE),  /* alias for tcx */
10752 	SEC_DEF("tcx/ingress",		SCHED_CLS, BPF_TCX_INGRESS, SEC_NONE),
10753 	SEC_DEF("tcx/egress",		SCHED_CLS, BPF_TCX_EGRESS, SEC_NONE),
10754 	SEC_DEF("tc",			SCHED_CLS, 0, SEC_NONE), /* deprecated / legacy, use tcx */
10755 	SEC_DEF("classifier",		SCHED_CLS, 0, SEC_NONE), /* deprecated / legacy, use tcx */
10756 	SEC_DEF("action",		SCHED_ACT, 0, SEC_NONE), /* deprecated / legacy, use tcx */
10757 	SEC_DEF("netkit/primary",	SCHED_CLS, BPF_NETKIT_PRIMARY, SEC_NONE),
10758 	SEC_DEF("netkit/peer",		SCHED_CLS, BPF_NETKIT_PEER, SEC_NONE),
10759 	SEC_DEF("tracepoint+",		TRACEPOINT, 0, SEC_NONE, attach_tp),
10760 	SEC_DEF("tp+",			TRACEPOINT, 0, SEC_NONE, attach_tp),
10761 	SEC_DEF("tracepoint.s+",	TRACEPOINT, 0, SEC_SLEEPABLE, attach_tp),
10762 	SEC_DEF("tp.s+",		TRACEPOINT, 0, SEC_SLEEPABLE, attach_tp),
10763 	SEC_DEF("raw_tracepoint+",	RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
10764 	SEC_DEF("raw_tp+",		RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
10765 	SEC_DEF("raw_tracepoint.s+",	RAW_TRACEPOINT, 0, SEC_SLEEPABLE, attach_raw_tp),
10766 	SEC_DEF("raw_tp.s+",		RAW_TRACEPOINT, 0, SEC_SLEEPABLE, attach_raw_tp),
10767 	SEC_DEF("raw_tracepoint.w+",	RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
10768 	SEC_DEF("raw_tp.w+",		RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
10769 	SEC_DEF("tp_btf+",		TRACING, BPF_TRACE_RAW_TP, SEC_ATTACH_BTF, attach_trace),
10770 	SEC_DEF("tp_btf.s+",		TRACING, BPF_TRACE_RAW_TP, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
10771 	SEC_DEF("fentry+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF, attach_trace),
10772 	SEC_DEF("fmod_ret+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF, attach_trace),
10773 	SEC_DEF("fexit+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF, attach_trace),
10774 	SEC_DEF("fentry.s+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
10775 	SEC_DEF("fmod_ret.s+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
10776 	SEC_DEF("fexit.s+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
10777 	SEC_DEF("fsession+",		TRACING, BPF_TRACE_FSESSION, SEC_ATTACH_BTF, attach_trace),
10778 	SEC_DEF("fsession.s+",		TRACING, BPF_TRACE_FSESSION, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
10779 	SEC_DEF("fsession.multi+",	TRACING, BPF_TRACE_FSESSION_MULTI, 0, attach_tracing_multi),
10780 	SEC_DEF("fsession.multi.s+",	TRACING, BPF_TRACE_FSESSION_MULTI, SEC_SLEEPABLE, attach_tracing_multi),
10781 	SEC_DEF("fentry.multi+",	TRACING, BPF_TRACE_FENTRY_MULTI, 0, attach_tracing_multi),
10782 	SEC_DEF("fexit.multi+",		TRACING, BPF_TRACE_FEXIT_MULTI, 0, attach_tracing_multi),
10783 	SEC_DEF("fentry.multi.s+",	TRACING, BPF_TRACE_FENTRY_MULTI, SEC_SLEEPABLE, attach_tracing_multi),
10784 	SEC_DEF("fexit.multi.s+",	TRACING, BPF_TRACE_FEXIT_MULTI, SEC_SLEEPABLE, attach_tracing_multi),
10785 	SEC_DEF("freplace+",		EXT, 0, SEC_ATTACH_BTF, attach_trace),
10786 	SEC_DEF("lsm+",			LSM, BPF_LSM_MAC, SEC_ATTACH_BTF, attach_lsm),
10787 	SEC_DEF("lsm.s+",		LSM, BPF_LSM_MAC, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_lsm),
10788 	SEC_DEF("lsm_cgroup+",		LSM, BPF_LSM_CGROUP, SEC_ATTACH_BTF),
10789 	SEC_DEF("iter+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF, attach_iter),
10790 	SEC_DEF("iter.s+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_iter),
10791 	SEC_DEF("syscall",		SYSCALL, 0, SEC_SLEEPABLE),
10792 	SEC_DEF("xdp.frags/devmap",	XDP, BPF_XDP_DEVMAP, SEC_XDP_FRAGS),
10793 	SEC_DEF("xdp/devmap",		XDP, BPF_XDP_DEVMAP, SEC_ATTACHABLE),
10794 	SEC_DEF("xdp.frags/cpumap",	XDP, BPF_XDP_CPUMAP, SEC_XDP_FRAGS),
10795 	SEC_DEF("xdp/cpumap",		XDP, BPF_XDP_CPUMAP, SEC_ATTACHABLE),
10796 	SEC_DEF("xdp.frags",		XDP, BPF_XDP, SEC_XDP_FRAGS),
10797 	SEC_DEF("xdp",			XDP, BPF_XDP, SEC_ATTACHABLE_OPT),
10798 	SEC_DEF("perf_event",		PERF_EVENT, 0, SEC_NONE),
10799 	SEC_DEF("lwt_in",		LWT_IN, 0, SEC_NONE),
10800 	SEC_DEF("lwt_out",		LWT_OUT, 0, SEC_NONE),
10801 	SEC_DEF("lwt_xmit",		LWT_XMIT, 0, SEC_NONE),
10802 	SEC_DEF("lwt_seg6local",	LWT_SEG6LOCAL, 0, SEC_NONE),
10803 	SEC_DEF("sockops",		SOCK_OPS, BPF_CGROUP_SOCK_OPS, SEC_ATTACHABLE_OPT),
10804 	SEC_DEF("sk_skb/stream_parser",	SK_SKB, BPF_SK_SKB_STREAM_PARSER, SEC_ATTACHABLE_OPT),
10805 	SEC_DEF("sk_skb/stream_verdict",SK_SKB, BPF_SK_SKB_STREAM_VERDICT, SEC_ATTACHABLE_OPT),
10806 	SEC_DEF("sk_skb/verdict",	SK_SKB, BPF_SK_SKB_VERDICT, SEC_ATTACHABLE_OPT),
10807 	SEC_DEF("sk_skb",		SK_SKB, 0, SEC_NONE),
10808 	SEC_DEF("sk_msg",		SK_MSG, BPF_SK_MSG_VERDICT, SEC_ATTACHABLE_OPT),
10809 	SEC_DEF("lirc_mode2",		LIRC_MODE2, BPF_LIRC_MODE2, SEC_ATTACHABLE_OPT),
10810 	SEC_DEF("flow_dissector",	FLOW_DISSECTOR, BPF_FLOW_DISSECTOR, SEC_ATTACHABLE_OPT),
10811 	SEC_DEF("cgroup_skb/ingress",	CGROUP_SKB, BPF_CGROUP_INET_INGRESS, SEC_ATTACHABLE_OPT),
10812 	SEC_DEF("cgroup_skb/egress",	CGROUP_SKB, BPF_CGROUP_INET_EGRESS, SEC_ATTACHABLE_OPT),
10813 	SEC_DEF("cgroup/skb",		CGROUP_SKB, 0, SEC_NONE),
10814 	SEC_DEF("cgroup/sock_create",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE),
10815 	SEC_DEF("cgroup/sock_release",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_RELEASE, SEC_ATTACHABLE),
10816 	SEC_DEF("cgroup/sock",		CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE_OPT),
10817 	SEC_DEF("cgroup/post_bind4",	CGROUP_SOCK, BPF_CGROUP_INET4_POST_BIND, SEC_ATTACHABLE),
10818 	SEC_DEF("cgroup/post_bind6",	CGROUP_SOCK, BPF_CGROUP_INET6_POST_BIND, SEC_ATTACHABLE),
10819 	SEC_DEF("cgroup/bind4",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND, SEC_ATTACHABLE),
10820 	SEC_DEF("cgroup/bind6",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND, SEC_ATTACHABLE),
10821 	SEC_DEF("cgroup/connect4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT, SEC_ATTACHABLE),
10822 	SEC_DEF("cgroup/connect6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT, SEC_ATTACHABLE),
10823 	SEC_DEF("cgroup/connect_unix",	CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_CONNECT, SEC_ATTACHABLE),
10824 	SEC_DEF("cgroup/sendmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG, SEC_ATTACHABLE),
10825 	SEC_DEF("cgroup/sendmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG, SEC_ATTACHABLE),
10826 	SEC_DEF("cgroup/sendmsg_unix",	CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_SENDMSG, SEC_ATTACHABLE),
10827 	SEC_DEF("cgroup/recvmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_RECVMSG, SEC_ATTACHABLE),
10828 	SEC_DEF("cgroup/recvmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_RECVMSG, SEC_ATTACHABLE),
10829 	SEC_DEF("cgroup/recvmsg_unix",	CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_RECVMSG, SEC_ATTACHABLE),
10830 	SEC_DEF("cgroup/getpeername4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETPEERNAME, SEC_ATTACHABLE),
10831 	SEC_DEF("cgroup/getpeername6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETPEERNAME, SEC_ATTACHABLE),
10832 	SEC_DEF("cgroup/getpeername_unix", CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_GETPEERNAME, SEC_ATTACHABLE),
10833 	SEC_DEF("cgroup/getsockname4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETSOCKNAME, SEC_ATTACHABLE),
10834 	SEC_DEF("cgroup/getsockname6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETSOCKNAME, SEC_ATTACHABLE),
10835 	SEC_DEF("cgroup/getsockname_unix", CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_GETSOCKNAME, SEC_ATTACHABLE),
10836 	SEC_DEF("cgroup/sysctl",	CGROUP_SYSCTL, BPF_CGROUP_SYSCTL, SEC_ATTACHABLE),
10837 	SEC_DEF("cgroup/getsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_GETSOCKOPT, SEC_ATTACHABLE),
10838 	SEC_DEF("cgroup/setsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_SETSOCKOPT, SEC_ATTACHABLE),
10839 	SEC_DEF("cgroup/dev",		CGROUP_DEVICE, BPF_CGROUP_DEVICE, SEC_ATTACHABLE_OPT),
10840 	SEC_DEF("struct_ops+",		STRUCT_OPS, 0, SEC_NONE),
10841 	SEC_DEF("struct_ops.s+",	STRUCT_OPS, 0, SEC_SLEEPABLE),
10842 	SEC_DEF("sk_lookup",		SK_LOOKUP, BPF_SK_LOOKUP, SEC_ATTACHABLE),
10843 	SEC_DEF("netfilter",		NETFILTER, BPF_NETFILTER, SEC_NONE),
10844 };
10845 
10846 int libbpf_register_prog_handler(const char *sec,
10847 				 enum bpf_prog_type prog_type,
10848 				 enum bpf_attach_type exp_attach_type,
10849 				 const struct libbpf_prog_handler_opts *opts)
10850 {
10851 	struct bpf_sec_def *sec_def;
10852 
10853 	if (!OPTS_VALID(opts, libbpf_prog_handler_opts))
10854 		return libbpf_err(-EINVAL);
10855 
10856 	if (last_custom_sec_def_handler_id == INT_MAX) /* prevent overflow */
10857 		return libbpf_err(-E2BIG);
10858 
10859 	if (sec) {
10860 		sec_def = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt + 1,
10861 					      sizeof(*sec_def));
10862 		if (!sec_def)
10863 			return libbpf_err(-ENOMEM);
10864 
10865 		custom_sec_defs = sec_def;
10866 		sec_def = &custom_sec_defs[custom_sec_def_cnt];
10867 	} else {
10868 		if (has_custom_fallback_def)
10869 			return libbpf_err(-EBUSY);
10870 
10871 		sec_def = &custom_fallback_def;
10872 	}
10873 
10874 	sec_def->sec = sec ? strdup(sec) : NULL;
10875 	if (sec && !sec_def->sec)
10876 		return libbpf_err(-ENOMEM);
10877 
10878 	sec_def->prog_type = prog_type;
10879 	sec_def->expected_attach_type = exp_attach_type;
10880 	sec_def->cookie = OPTS_GET(opts, cookie, 0);
10881 
10882 	sec_def->prog_setup_fn = OPTS_GET(opts, prog_setup_fn, NULL);
10883 	sec_def->prog_prepare_load_fn = OPTS_GET(opts, prog_prepare_load_fn, NULL);
10884 	sec_def->prog_attach_fn = OPTS_GET(opts, prog_attach_fn, NULL);
10885 
10886 	sec_def->handler_id = ++last_custom_sec_def_handler_id;
10887 
10888 	if (sec)
10889 		custom_sec_def_cnt++;
10890 	else
10891 		has_custom_fallback_def = true;
10892 
10893 	return sec_def->handler_id;
10894 }
10895 
10896 int libbpf_unregister_prog_handler(int handler_id)
10897 {
10898 	struct bpf_sec_def *sec_defs;
10899 	int i;
10900 
10901 	if (handler_id <= 0)
10902 		return libbpf_err(-EINVAL);
10903 
10904 	if (has_custom_fallback_def && custom_fallback_def.handler_id == handler_id) {
10905 		memset(&custom_fallback_def, 0, sizeof(custom_fallback_def));
10906 		has_custom_fallback_def = false;
10907 		return 0;
10908 	}
10909 
10910 	for (i = 0; i < custom_sec_def_cnt; i++) {
10911 		if (custom_sec_defs[i].handler_id == handler_id)
10912 			break;
10913 	}
10914 
10915 	if (i == custom_sec_def_cnt)
10916 		return libbpf_err(-ENOENT);
10917 
10918 	free(custom_sec_defs[i].sec);
10919 	for (i = i + 1; i < custom_sec_def_cnt; i++)
10920 		custom_sec_defs[i - 1] = custom_sec_defs[i];
10921 	custom_sec_def_cnt--;
10922 
10923 	/* try to shrink the array, but it's ok if we couldn't */
10924 	sec_defs = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt, sizeof(*sec_defs));
10925 	/* if new count is zero, reallocarray can return a valid NULL result;
10926 	 * in this case the previous pointer will be freed, so we *have to*
10927 	 * reassign old pointer to the new value (even if it's NULL)
10928 	 */
10929 	if (sec_defs || custom_sec_def_cnt == 0)
10930 		custom_sec_defs = sec_defs;
10931 
10932 	return 0;
10933 }
10934 
10935 static bool sec_def_matches(const struct bpf_sec_def *sec_def, const char *sec_name)
10936 {
10937 	size_t len = strlen(sec_def->sec);
10938 
10939 	/* "type/" always has to have proper SEC("type/extras") form */
10940 	if (sec_def->sec[len - 1] == '/') {
10941 		if (str_has_pfx(sec_name, sec_def->sec))
10942 			return true;
10943 		return false;
10944 	}
10945 
10946 	/* "type+" means it can be either exact SEC("type") or
10947 	 * well-formed SEC("type/extras") with proper '/' separator
10948 	 */
10949 	if (sec_def->sec[len - 1] == '+') {
10950 		len--;
10951 		/* not even a prefix */
10952 		if (strncmp(sec_name, sec_def->sec, len) != 0)
10953 			return false;
10954 		/* exact match or has '/' separator */
10955 		if (sec_name[len] == '\0' || sec_name[len] == '/')
10956 			return true;
10957 		return false;
10958 	}
10959 
10960 	return strcmp(sec_name, sec_def->sec) == 0;
10961 }
10962 
10963 static const struct bpf_sec_def *find_sec_def(const char *sec_name)
10964 {
10965 	const struct bpf_sec_def *sec_def;
10966 	int i, n;
10967 
10968 	n = custom_sec_def_cnt;
10969 	for (i = 0; i < n; i++) {
10970 		sec_def = &custom_sec_defs[i];
10971 		if (sec_def_matches(sec_def, sec_name))
10972 			return sec_def;
10973 	}
10974 
10975 	n = ARRAY_SIZE(section_defs);
10976 	for (i = 0; i < n; i++) {
10977 		sec_def = &section_defs[i];
10978 		if (sec_def_matches(sec_def, sec_name))
10979 			return sec_def;
10980 	}
10981 
10982 	if (has_custom_fallback_def)
10983 		return &custom_fallback_def;
10984 
10985 	return NULL;
10986 }
10987 
10988 #define MAX_TYPE_NAME_SIZE 32
10989 
10990 static char *libbpf_get_type_names(bool attach_type)
10991 {
10992 	int i, len = ARRAY_SIZE(section_defs) * MAX_TYPE_NAME_SIZE;
10993 	char *buf;
10994 
10995 	buf = malloc(len);
10996 	if (!buf)
10997 		return NULL;
10998 
10999 	buf[0] = '\0';
11000 	/* Forge string buf with all available names */
11001 	for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
11002 		const struct bpf_sec_def *sec_def = &section_defs[i];
11003 
11004 		if (attach_type) {
11005 			if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
11006 				continue;
11007 
11008 			if (!(sec_def->cookie & SEC_ATTACHABLE))
11009 				continue;
11010 		}
11011 
11012 		if (strlen(buf) + strlen(section_defs[i].sec) + 2 > len) {
11013 			free(buf);
11014 			return NULL;
11015 		}
11016 		strcat(buf, " ");
11017 		strcat(buf, section_defs[i].sec);
11018 	}
11019 
11020 	return buf;
11021 }
11022 
11023 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
11024 			     enum bpf_attach_type *expected_attach_type)
11025 {
11026 	const struct bpf_sec_def *sec_def;
11027 	char *type_names;
11028 
11029 	if (!name)
11030 		return libbpf_err(-EINVAL);
11031 
11032 	sec_def = find_sec_def(name);
11033 	if (sec_def) {
11034 		*prog_type = sec_def->prog_type;
11035 		*expected_attach_type = sec_def->expected_attach_type;
11036 		return 0;
11037 	}
11038 
11039 	pr_debug("failed to guess program type from ELF section '%s'\n", name);
11040 	type_names = libbpf_get_type_names(false);
11041 	if (type_names != NULL) {
11042 		pr_debug("supported section(type) names are:%s\n", type_names);
11043 		free(type_names);
11044 	}
11045 
11046 	return libbpf_err(-ESRCH);
11047 }
11048 
11049 const char *libbpf_bpf_attach_type_str(enum bpf_attach_type t)
11050 {
11051 	if (t < 0 || t >= ARRAY_SIZE(attach_type_name))
11052 		return NULL;
11053 
11054 	return attach_type_name[t];
11055 }
11056 
11057 const char *libbpf_bpf_link_type_str(enum bpf_link_type t)
11058 {
11059 	if (t < 0 || t >= ARRAY_SIZE(link_type_name))
11060 		return NULL;
11061 
11062 	return link_type_name[t];
11063 }
11064 
11065 const char *libbpf_bpf_map_type_str(enum bpf_map_type t)
11066 {
11067 	if (t < 0 || t >= ARRAY_SIZE(map_type_name))
11068 		return NULL;
11069 
11070 	return map_type_name[t];
11071 }
11072 
11073 const char *libbpf_bpf_prog_type_str(enum bpf_prog_type t)
11074 {
11075 	if (t < 0 || t >= ARRAY_SIZE(prog_type_name))
11076 		return NULL;
11077 
11078 	return prog_type_name[t];
11079 }
11080 
11081 static struct bpf_map *find_struct_ops_map_by_offset(struct bpf_object *obj,
11082 						     int sec_idx,
11083 						     size_t offset)
11084 {
11085 	struct bpf_map *map;
11086 	size_t i;
11087 
11088 	for (i = 0; i < obj->nr_maps; i++) {
11089 		map = &obj->maps[i];
11090 		if (!bpf_map__is_struct_ops(map))
11091 			continue;
11092 		if (map->sec_idx == sec_idx &&
11093 		    map->sec_offset <= offset &&
11094 		    offset - map->sec_offset < map->def.value_size)
11095 			return map;
11096 	}
11097 
11098 	return NULL;
11099 }
11100 
11101 /* Collect the reloc from ELF, populate the st_ops->progs[], and update
11102  * st_ops->data for shadow type.
11103  */
11104 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
11105 					    Elf64_Shdr *shdr, Elf_Data *data)
11106 {
11107 	const struct btf_type *type;
11108 	const struct btf_member *member;
11109 	struct bpf_struct_ops *st_ops;
11110 	struct bpf_program *prog;
11111 	unsigned int shdr_idx;
11112 	const struct btf *btf;
11113 	struct bpf_map *map;
11114 	unsigned int moff, insn_idx;
11115 	const char *name;
11116 	__u32 member_idx;
11117 	Elf64_Sym *sym;
11118 	Elf64_Rel *rel;
11119 	int i, nrels;
11120 
11121 	btf = obj->btf;
11122 	nrels = shdr->sh_size / shdr->sh_entsize;
11123 	for (i = 0; i < nrels; i++) {
11124 		rel = elf_rel_by_idx(data, i);
11125 		if (!rel) {
11126 			pr_warn("struct_ops reloc: failed to get %d reloc\n", i);
11127 			return -LIBBPF_ERRNO__FORMAT;
11128 		}
11129 
11130 		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
11131 		if (!sym) {
11132 			pr_warn("struct_ops reloc: symbol %zx not found\n",
11133 				(size_t)ELF64_R_SYM(rel->r_info));
11134 			return -LIBBPF_ERRNO__FORMAT;
11135 		}
11136 
11137 		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
11138 		map = find_struct_ops_map_by_offset(obj, shdr->sh_info, rel->r_offset);
11139 		if (!map) {
11140 			pr_warn("struct_ops reloc: cannot find map at rel->r_offset %zu\n",
11141 				(size_t)rel->r_offset);
11142 			return -EINVAL;
11143 		}
11144 
11145 		moff = rel->r_offset - map->sec_offset;
11146 		shdr_idx = sym->st_shndx;
11147 		st_ops = map->st_ops;
11148 		pr_debug("struct_ops reloc %s: for %lld value %lld shdr_idx %u rel->r_offset %zu map->sec_offset %zu name %u (\'%s\')\n",
11149 			 map->name,
11150 			 (long long)(rel->r_info >> 32),
11151 			 (long long)sym->st_value,
11152 			 shdr_idx, (size_t)rel->r_offset,
11153 			 map->sec_offset, sym->st_name, name);
11154 
11155 		if (shdr_idx >= SHN_LORESERVE) {
11156 			pr_warn("struct_ops reloc %s: rel->r_offset %zu shdr_idx %u unsupported non-static function\n",
11157 				map->name, (size_t)rel->r_offset, shdr_idx);
11158 			return -LIBBPF_ERRNO__RELOC;
11159 		}
11160 		if (sym->st_value % BPF_INSN_SZ) {
11161 			pr_warn("struct_ops reloc %s: invalid target program offset %llu\n",
11162 				map->name, (unsigned long long)sym->st_value);
11163 			return -LIBBPF_ERRNO__FORMAT;
11164 		}
11165 		insn_idx = sym->st_value / BPF_INSN_SZ;
11166 
11167 		type = btf__type_by_id(btf, st_ops->type_id);
11168 		member = find_member_by_offset(type, moff * 8);
11169 		if (!member) {
11170 			pr_warn("struct_ops reloc %s: cannot find member at moff %u\n",
11171 				map->name, moff);
11172 			return -EINVAL;
11173 		}
11174 		member_idx = member - btf_members(type);
11175 		name = btf__name_by_offset(btf, member->name_off);
11176 
11177 		if (!resolve_func_ptr(btf, member->type, NULL)) {
11178 			pr_warn("struct_ops reloc %s: cannot relocate non func ptr %s\n",
11179 				map->name, name);
11180 			return -EINVAL;
11181 		}
11182 
11183 		prog = find_prog_by_sec_insn(obj, shdr_idx, insn_idx);
11184 		if (!prog) {
11185 			pr_warn("struct_ops reloc %s: cannot find prog at shdr_idx %u to relocate func ptr %s\n",
11186 				map->name, shdr_idx, name);
11187 			return -EINVAL;
11188 		}
11189 
11190 		/* prevent the use of BPF prog with invalid type */
11191 		if (prog->type != BPF_PROG_TYPE_STRUCT_OPS) {
11192 			pr_warn("struct_ops reloc %s: prog %s is not struct_ops BPF program\n",
11193 				map->name, prog->name);
11194 			return -EINVAL;
11195 		}
11196 
11197 		st_ops->progs[member_idx] = prog;
11198 
11199 		/* st_ops->data will be exposed to users, being returned by
11200 		 * bpf_map__initial_value() as a pointer to the shadow
11201 		 * type. All function pointers in the original struct type
11202 		 * should be converted to a pointer to struct bpf_program
11203 		 * in the shadow type.
11204 		 */
11205 		*((struct bpf_program **)(st_ops->data + moff)) = prog;
11206 	}
11207 
11208 	return 0;
11209 }
11210 
11211 #define BTF_TRACE_PREFIX "btf_trace_"
11212 #define BTF_LSM_PREFIX "bpf_lsm_"
11213 #define BTF_ITER_PREFIX "bpf_iter_"
11214 #define BTF_MAX_NAME_SIZE 128
11215 
11216 void btf_get_kernel_prefix_kind(enum bpf_attach_type attach_type,
11217 				const char **prefix, int *kind)
11218 {
11219 	switch (attach_type) {
11220 	case BPF_TRACE_RAW_TP:
11221 		*prefix = BTF_TRACE_PREFIX;
11222 		*kind = BTF_KIND_TYPEDEF;
11223 		break;
11224 	case BPF_LSM_MAC:
11225 	case BPF_LSM_CGROUP:
11226 		*prefix = BTF_LSM_PREFIX;
11227 		*kind = BTF_KIND_FUNC;
11228 		break;
11229 	case BPF_TRACE_ITER:
11230 		*prefix = BTF_ITER_PREFIX;
11231 		*kind = BTF_KIND_FUNC;
11232 		break;
11233 	default:
11234 		*prefix = "";
11235 		*kind = BTF_KIND_FUNC;
11236 	}
11237 }
11238 
11239 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
11240 				   const char *name, __u32 kind)
11241 {
11242 	char btf_type_name[BTF_MAX_NAME_SIZE];
11243 	int ret;
11244 
11245 	ret = snprintf(btf_type_name, sizeof(btf_type_name),
11246 		       "%s%s", prefix, name);
11247 	/* snprintf returns the number of characters written excluding the
11248 	 * terminating null. So, if >= BTF_MAX_NAME_SIZE are written, it
11249 	 * indicates truncation.
11250 	 */
11251 	if (ret < 0 || ret >= sizeof(btf_type_name))
11252 		return -ENAMETOOLONG;
11253 	return btf__find_by_name_kind(btf, btf_type_name, kind);
11254 }
11255 
11256 static inline int find_attach_btf_id(struct btf *btf, const char *name,
11257 				     enum bpf_attach_type attach_type)
11258 {
11259 	const char *prefix;
11260 	int kind;
11261 
11262 	btf_get_kernel_prefix_kind(attach_type, &prefix, &kind);
11263 	return find_btf_by_prefix_kind(btf, prefix, name, kind);
11264 }
11265 
11266 int libbpf_find_vmlinux_btf_id(const char *name,
11267 			       enum bpf_attach_type attach_type)
11268 {
11269 	struct btf *btf;
11270 	int err;
11271 
11272 	btf = btf__load_vmlinux_btf();
11273 	err = libbpf_get_error(btf);
11274 	if (err) {
11275 		pr_warn("vmlinux BTF is not found\n");
11276 		return libbpf_err(err);
11277 	}
11278 
11279 	err = find_attach_btf_id(btf, name, attach_type);
11280 	if (err <= 0)
11281 		pr_warn("%s is not found in vmlinux BTF\n", name);
11282 
11283 	btf__free(btf);
11284 	return libbpf_err(err);
11285 }
11286 
11287 static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd, int token_fd)
11288 {
11289 	struct bpf_prog_info info;
11290 	__u32 info_len = sizeof(info);
11291 	struct btf *btf;
11292 	int err;
11293 
11294 	memset(&info, 0, info_len);
11295 	err = bpf_prog_get_info_by_fd(attach_prog_fd, &info, &info_len);
11296 	if (err) {
11297 		pr_warn("failed bpf_prog_get_info_by_fd for FD %u: %s\n",
11298 			attach_prog_fd, errstr(err));
11299 		return err;
11300 	}
11301 
11302 	err = -EINVAL;
11303 	if (!info.btf_id) {
11304 		pr_warn("The target program doesn't have BTF\n");
11305 		goto out;
11306 	}
11307 	btf = btf_load_from_kernel(info.btf_id, NULL, token_fd);
11308 	err = libbpf_get_error(btf);
11309 	if (err) {
11310 		pr_warn("Failed to get BTF %u of the program: %s\n", info.btf_id, errstr(err));
11311 		goto out;
11312 	}
11313 	err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
11314 	btf__free(btf);
11315 	if (err <= 0) {
11316 		pr_warn("%s is not found in prog's BTF\n", name);
11317 		goto out;
11318 	}
11319 out:
11320 	return err;
11321 }
11322 
11323 static int find_kernel_btf_id(struct bpf_object *obj, const char *attach_name,
11324 			      enum bpf_attach_type attach_type,
11325 			      int *btf_obj_fd, int *btf_type_id)
11326 {
11327 	int ret, i, mod_len = 0;
11328 	const char *fn_name, *mod_name = NULL;
11329 
11330 	fn_name = strchr(attach_name, ':');
11331 	if (fn_name) {
11332 		mod_name = attach_name;
11333 		mod_len = fn_name - mod_name;
11334 		fn_name++;
11335 	}
11336 
11337 	if (!mod_name || strncmp(mod_name, "vmlinux", mod_len) == 0) {
11338 		ret = find_attach_btf_id(obj->btf_vmlinux,
11339 					 mod_name ? fn_name : attach_name,
11340 					 attach_type);
11341 		if (ret > 0) {
11342 			*btf_obj_fd = 0; /* vmlinux BTF */
11343 			*btf_type_id = ret;
11344 			return 0;
11345 		}
11346 		if (ret != -ENOENT)
11347 			return ret;
11348 	}
11349 
11350 	ret = load_module_btfs(obj);
11351 	if (ret)
11352 		return ret;
11353 
11354 	for (i = 0; i < obj->btf_module_cnt; i++) {
11355 		const struct module_btf *mod = &obj->btf_modules[i];
11356 
11357 		if (mod_name && strncmp(mod->name, mod_name, mod_len) != 0)
11358 			continue;
11359 
11360 		ret = find_attach_btf_id(mod->btf,
11361 					 mod_name ? fn_name : attach_name,
11362 					 attach_type);
11363 		if (ret > 0) {
11364 			*btf_obj_fd = mod->fd;
11365 			*btf_type_id = ret;
11366 			return 0;
11367 		}
11368 		if (ret == -ENOENT)
11369 			continue;
11370 
11371 		return ret;
11372 	}
11373 
11374 	return -ESRCH;
11375 }
11376 
11377 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
11378 				     int *btf_obj_fd, int *btf_type_id)
11379 {
11380 	enum bpf_attach_type attach_type = prog->expected_attach_type;
11381 	__u32 attach_prog_fd = prog->attach_prog_fd;
11382 	int err = 0;
11383 
11384 	/* BPF program's BTF ID */
11385 	if (prog->type == BPF_PROG_TYPE_EXT || attach_prog_fd) {
11386 		if (!attach_prog_fd) {
11387 			pr_warn("prog '%s': attach program FD is not set\n", prog->name);
11388 			return -EINVAL;
11389 		}
11390 		err = libbpf_find_prog_btf_id(attach_name, attach_prog_fd, prog->obj->token_fd);
11391 		if (err < 0) {
11392 			pr_warn("prog '%s': failed to find BPF program (FD %u) BTF ID for '%s': %s\n",
11393 				prog->name, attach_prog_fd, attach_name, errstr(err));
11394 			return err;
11395 		}
11396 		*btf_obj_fd = 0;
11397 		*btf_type_id = err;
11398 		return 0;
11399 	}
11400 
11401 	/* kernel/module BTF ID */
11402 	if (prog->obj->gen_loader) {
11403 		bpf_gen__record_attach_target(prog->obj->gen_loader, attach_name, attach_type);
11404 		*btf_obj_fd = 0;
11405 		*btf_type_id = 1;
11406 	} else {
11407 		err = find_kernel_btf_id(prog->obj, attach_name,
11408 					 attach_type, btf_obj_fd,
11409 					 btf_type_id);
11410 	}
11411 	if (err) {
11412 		pr_warn("prog '%s': failed to find kernel BTF type ID of '%s': %s\n",
11413 			prog->name, attach_name, errstr(err));
11414 		return err;
11415 	}
11416 	return 0;
11417 }
11418 
11419 int libbpf_attach_type_by_name(const char *name,
11420 			       enum bpf_attach_type *attach_type)
11421 {
11422 	char *type_names;
11423 	const struct bpf_sec_def *sec_def;
11424 
11425 	if (!name)
11426 		return libbpf_err(-EINVAL);
11427 
11428 	sec_def = find_sec_def(name);
11429 	if (!sec_def) {
11430 		pr_debug("failed to guess attach type based on ELF section name '%s'\n", name);
11431 		type_names = libbpf_get_type_names(true);
11432 		if (type_names != NULL) {
11433 			pr_debug("attachable section(type) names are:%s\n", type_names);
11434 			free(type_names);
11435 		}
11436 
11437 		return libbpf_err(-EINVAL);
11438 	}
11439 
11440 	if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
11441 		return libbpf_err(-EINVAL);
11442 	if (!(sec_def->cookie & SEC_ATTACHABLE))
11443 		return libbpf_err(-EINVAL);
11444 
11445 	*attach_type = sec_def->expected_attach_type;
11446 	return 0;
11447 }
11448 
11449 int bpf_map__fd(const struct bpf_map *map)
11450 {
11451 	if (!map)
11452 		return libbpf_err(-EINVAL);
11453 	if (!map_is_created(map))
11454 		return -1;
11455 	return map->fd;
11456 }
11457 
11458 static bool map_uses_real_name(const struct bpf_map *map)
11459 {
11460 	/* Since libbpf started to support custom .data.* and .rodata.* maps,
11461 	 * their user-visible name differs from kernel-visible name. Users see
11462 	 * such map's corresponding ELF section name as a map name.
11463 	 * This check distinguishes .data/.rodata from .data.* and .rodata.*
11464 	 * maps to know which name has to be returned to the user.
11465 	 * Map name of the custom .percpu.* maps might be truncated to
11466 	 * BPF_OBJ_NAME_LEN-1 chars in internal_map_name(). Hence, percpu data
11467 	 * maps must use real name for their user-visible name.
11468 	 */
11469 	if (map->libbpf_type == LIBBPF_MAP_DATA && strcmp(map->real_name, DATA_SEC) != 0)
11470 		return true;
11471 	if (map->libbpf_type == LIBBPF_MAP_RODATA && strcmp(map->real_name, RODATA_SEC) != 0)
11472 		return true;
11473 	if (map->libbpf_type == LIBBPF_MAP_PERCPU)
11474 		return true;
11475 	return false;
11476 }
11477 
11478 const char *bpf_map__name(const struct bpf_map *map)
11479 {
11480 	if (!map)
11481 		return NULL;
11482 
11483 	if (map_uses_real_name(map))
11484 		return map->real_name;
11485 
11486 	return map->name;
11487 }
11488 
11489 enum bpf_map_type bpf_map__type(const struct bpf_map *map)
11490 {
11491 	return map->def.type;
11492 }
11493 
11494 int bpf_map__set_type(struct bpf_map *map, enum bpf_map_type type)
11495 {
11496 	if (map_is_created(map))
11497 		return libbpf_err(-EBUSY);
11498 	map->def.type = type;
11499 	return 0;
11500 }
11501 
11502 __u32 bpf_map__map_flags(const struct bpf_map *map)
11503 {
11504 	return map->def.map_flags;
11505 }
11506 
11507 int bpf_map__set_map_flags(struct bpf_map *map, __u32 flags)
11508 {
11509 	if (map_is_created(map))
11510 		return libbpf_err(-EBUSY);
11511 	map->def.map_flags = flags;
11512 	return 0;
11513 }
11514 
11515 __u64 bpf_map__map_extra(const struct bpf_map *map)
11516 {
11517 	return map->map_extra;
11518 }
11519 
11520 int bpf_map__set_map_extra(struct bpf_map *map, __u64 map_extra)
11521 {
11522 	if (map_is_created(map))
11523 		return libbpf_err(-EBUSY);
11524 	map->map_extra = map_extra;
11525 	return 0;
11526 }
11527 
11528 __u32 bpf_map__numa_node(const struct bpf_map *map)
11529 {
11530 	return map->numa_node;
11531 }
11532 
11533 int bpf_map__set_numa_node(struct bpf_map *map, __u32 numa_node)
11534 {
11535 	if (map_is_created(map))
11536 		return libbpf_err(-EBUSY);
11537 	map->numa_node = numa_node;
11538 	return 0;
11539 }
11540 
11541 __u32 bpf_map__key_size(const struct bpf_map *map)
11542 {
11543 	return map->def.key_size;
11544 }
11545 
11546 int bpf_map__set_key_size(struct bpf_map *map, __u32 size)
11547 {
11548 	if (map_is_created(map))
11549 		return libbpf_err(-EBUSY);
11550 	map->def.key_size = size;
11551 	return 0;
11552 }
11553 
11554 __u32 bpf_map__value_size(const struct bpf_map *map)
11555 {
11556 	return map->def.value_size;
11557 }
11558 
11559 static int map_btf_datasec_resize(struct bpf_map *map, __u32 size)
11560 {
11561 	struct btf *btf;
11562 	struct btf_type *datasec_type, *var_type;
11563 	struct btf_var_secinfo *var;
11564 	const struct btf_type *array_type;
11565 	const struct btf_array *array;
11566 	int vlen, element_sz, new_array_id;
11567 	__u32 nr_elements;
11568 
11569 	/* check btf existence */
11570 	btf = bpf_object__btf(map->obj);
11571 	if (!btf)
11572 		return -ENOENT;
11573 
11574 	/* verify map is datasec */
11575 	datasec_type = btf_type_by_id(btf, bpf_map__btf_value_type_id(map));
11576 	if (!btf_is_datasec(datasec_type)) {
11577 		pr_warn("map '%s': cannot be resized, map value type is not a datasec\n",
11578 			bpf_map__name(map));
11579 		return -EINVAL;
11580 	}
11581 
11582 	/* verify datasec has at least one var */
11583 	vlen = btf_vlen(datasec_type);
11584 	if (vlen == 0) {
11585 		pr_warn("map '%s': cannot be resized, map value datasec is empty\n",
11586 			bpf_map__name(map));
11587 		return -EINVAL;
11588 	}
11589 
11590 	/* verify last var in the datasec is an array */
11591 	var = &btf_var_secinfos(datasec_type)[vlen - 1];
11592 	var_type = btf_type_by_id(btf, var->type);
11593 	array_type = skip_mods_and_typedefs(btf, var_type->type, NULL);
11594 	if (!btf_is_array(array_type)) {
11595 		pr_warn("map '%s': cannot be resized, last var must be an array\n",
11596 			bpf_map__name(map));
11597 		return -EINVAL;
11598 	}
11599 
11600 	/* verify request size aligns with array */
11601 	array = btf_array(array_type);
11602 	element_sz = btf__resolve_size(btf, array->type);
11603 	if (element_sz <= 0 || (size - var->offset) % element_sz != 0) {
11604 		pr_warn("map '%s': cannot be resized, element size (%d) doesn't align with new total size (%u)\n",
11605 			bpf_map__name(map), element_sz, size);
11606 		return -EINVAL;
11607 	}
11608 
11609 	/* create a new array based on the existing array, but with new length */
11610 	nr_elements = (size - var->offset) / element_sz;
11611 	new_array_id = btf__add_array(btf, array->index_type, array->type, nr_elements);
11612 	if (new_array_id < 0)
11613 		return new_array_id;
11614 
11615 	/* adding a new btf type invalidates existing pointers to btf objects,
11616 	 * so refresh pointers before proceeding
11617 	 */
11618 	datasec_type = btf_type_by_id(btf, map->btf_value_type_id);
11619 	var = &btf_var_secinfos(datasec_type)[vlen - 1];
11620 	var_type = btf_type_by_id(btf, var->type);
11621 
11622 	/* finally update btf info */
11623 	datasec_type->size = size;
11624 	var->size = size - var->offset;
11625 	var_type->type = new_array_id;
11626 
11627 	return 0;
11628 }
11629 
11630 int bpf_map__set_value_size(struct bpf_map *map, __u32 size)
11631 {
11632 	if (map_is_created(map))
11633 		return libbpf_err(-EBUSY);
11634 
11635 	if (map->mmaped) {
11636 		size_t mmap_old_sz, mmap_new_sz;
11637 		int err;
11638 
11639 		if (map->def.type != BPF_MAP_TYPE_ARRAY &&
11640 		    map->def.type != BPF_MAP_TYPE_PERCPU_ARRAY)
11641 			return libbpf_err(-EOPNOTSUPP);
11642 
11643 		mmap_old_sz = bpf_map_mmap_sz(map);
11644 		mmap_new_sz = array_map_mmap_sz(size, map->def.max_entries);
11645 		err = bpf_map_mmap_resize(map, mmap_old_sz, mmap_new_sz);
11646 		if (err) {
11647 			pr_warn("map '%s': failed to resize memory-mapped region: %s\n",
11648 				bpf_map__name(map), errstr(err));
11649 			return libbpf_err(err);
11650 		}
11651 		err = map_btf_datasec_resize(map, size);
11652 		if (err && err != -ENOENT) {
11653 			pr_warn("map '%s': failed to adjust resized BTF, clearing BTF key/value info: %s\n",
11654 				bpf_map__name(map), errstr(err));
11655 			map->btf_value_type_id = 0;
11656 			map->btf_key_type_id = 0;
11657 		}
11658 	}
11659 
11660 	map->def.value_size = size;
11661 	return 0;
11662 }
11663 
11664 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
11665 {
11666 	return map ? map->btf_key_type_id : 0;
11667 }
11668 
11669 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
11670 {
11671 	return map ? map->btf_value_type_id : 0;
11672 }
11673 
11674 int bpf_map__set_initial_value(struct bpf_map *map,
11675 			       const void *data, size_t size)
11676 {
11677 	size_t actual_sz;
11678 
11679 	if (map_is_created(map))
11680 		return libbpf_err(-EBUSY);
11681 
11682 	if (!map->mmaped || map->libbpf_type == LIBBPF_MAP_KCONFIG)
11683 		return libbpf_err(-EINVAL);
11684 
11685 	if (map->def.type == BPF_MAP_TYPE_ARENA)
11686 		actual_sz = map->obj->arena_data_sz;
11687 	else
11688 		actual_sz = map->def.value_size;
11689 	if (size != actual_sz)
11690 		return libbpf_err(-EINVAL);
11691 
11692 	memcpy(map->mmaped, data, size);
11693 	return 0;
11694 }
11695 
11696 void *bpf_map__initial_value(const struct bpf_map *map, size_t *psize)
11697 {
11698 	if (bpf_map__is_struct_ops(map)) {
11699 		if (psize)
11700 			*psize = map->def.value_size;
11701 		return map->st_ops->data;
11702 	}
11703 
11704 	if (!map->mmaped)
11705 		return NULL;
11706 
11707 	if (map->def.type == BPF_MAP_TYPE_ARENA)
11708 		*psize = map->obj->arena_data_sz;
11709 	else
11710 		*psize = map->def.value_size;
11711 
11712 	return map->mmaped;
11713 }
11714 
11715 bool bpf_map__is_internal(const struct bpf_map *map)
11716 {
11717 	return map->libbpf_type != LIBBPF_MAP_UNSPEC;
11718 }
11719 
11720 __u32 bpf_map__ifindex(const struct bpf_map *map)
11721 {
11722 	return map->map_ifindex;
11723 }
11724 
11725 int bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
11726 {
11727 	if (map_is_created(map))
11728 		return libbpf_err(-EBUSY);
11729 	map->map_ifindex = ifindex;
11730 	return 0;
11731 }
11732 
11733 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
11734 {
11735 	if (!bpf_map_type__is_map_in_map(map->def.type)) {
11736 		pr_warn("error: unsupported map type\n");
11737 		return libbpf_err(-EINVAL);
11738 	}
11739 	if (map->inner_map_fd != -1) {
11740 		pr_warn("error: inner_map_fd already specified\n");
11741 		return libbpf_err(-EINVAL);
11742 	}
11743 	if (map->inner_map) {
11744 		bpf_map__destroy(map->inner_map);
11745 		zfree(&map->inner_map);
11746 	}
11747 	map->inner_map_fd = fd;
11748 	return 0;
11749 }
11750 
11751 int bpf_map__set_exclusive_program(struct bpf_map *map, struct bpf_program *prog)
11752 {
11753 	if (map_is_created(map)) {
11754 		pr_warn("exclusive programs must be set before map creation\n");
11755 		return libbpf_err(-EINVAL);
11756 	}
11757 
11758 	if (map->obj != prog->obj) {
11759 		pr_warn("excl_prog and map must be from the same bpf object\n");
11760 		return libbpf_err(-EINVAL);
11761 	}
11762 
11763 	map->excl_prog = prog;
11764 	return 0;
11765 }
11766 
11767 struct bpf_program *bpf_map__exclusive_program(struct bpf_map *map)
11768 {
11769 	return map->excl_prog;
11770 }
11771 
11772 static struct bpf_map *
11773 __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
11774 {
11775 	ssize_t idx;
11776 	struct bpf_map *s, *e;
11777 
11778 	if (!obj || !obj->maps)
11779 		return errno = EINVAL, NULL;
11780 
11781 	s = obj->maps;
11782 	e = obj->maps + obj->nr_maps;
11783 
11784 	if ((m < s) || (m >= e)) {
11785 		pr_warn("error in %s: map handler doesn't belong to object\n",
11786 			 __func__);
11787 		return errno = EINVAL, NULL;
11788 	}
11789 
11790 	idx = (m - obj->maps) + i;
11791 	if (idx >= obj->nr_maps || idx < 0)
11792 		return NULL;
11793 	return &obj->maps[idx];
11794 }
11795 
11796 struct bpf_map *
11797 bpf_object__next_map(const struct bpf_object *obj, const struct bpf_map *prev)
11798 {
11799 	if (prev == NULL && obj != NULL)
11800 		return obj->maps;
11801 
11802 	return __bpf_map__iter(prev, obj, 1);
11803 }
11804 
11805 struct bpf_map *
11806 bpf_object__prev_map(const struct bpf_object *obj, const struct bpf_map *next)
11807 {
11808 	if (next == NULL && obj != NULL) {
11809 		if (!obj->nr_maps)
11810 			return NULL;
11811 		return obj->maps + obj->nr_maps - 1;
11812 	}
11813 
11814 	return __bpf_map__iter(next, obj, -1);
11815 }
11816 
11817 struct bpf_map *
11818 bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
11819 {
11820 	struct bpf_map *pos;
11821 
11822 	bpf_object__for_each_map(pos, obj) {
11823 		/* if it's a special internal map name (which always starts
11824 		 * with dot) then check if that special name matches the
11825 		 * real map name (ELF section name)
11826 		 */
11827 		if (name[0] == '.') {
11828 			if (pos->real_name && strcmp(pos->real_name, name) == 0)
11829 				return pos;
11830 			continue;
11831 		}
11832 		/* otherwise map name has to be an exact match */
11833 		if (map_uses_real_name(pos)) {
11834 			if (strcmp(pos->real_name, name) == 0)
11835 				return pos;
11836 			continue;
11837 		}
11838 		if (strcmp(pos->name, name) == 0)
11839 			return pos;
11840 	}
11841 	return errno = ENOENT, NULL;
11842 }
11843 
11844 int
11845 bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
11846 {
11847 	return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
11848 }
11849 
11850 static int validate_map_op(const struct bpf_map *map, size_t key_sz,
11851 			   size_t value_sz, bool check_value_sz, __u64 flags)
11852 {
11853 	if (!map_is_created(map)) /* map is not yet created */
11854 		return -ENOENT;
11855 
11856 	if (map->def.key_size != key_sz) {
11857 		pr_warn("map '%s': unexpected key size %zu provided, expected %u\n",
11858 			map->name, key_sz, map->def.key_size);
11859 		return -EINVAL;
11860 	}
11861 
11862 	if (map->fd < 0) {
11863 		pr_warn("map '%s': can't use BPF map without FD (was it created?)\n", map->name);
11864 		return -EINVAL;
11865 	}
11866 
11867 	if (!check_value_sz)
11868 		return 0;
11869 
11870 	switch (map->def.type) {
11871 	case BPF_MAP_TYPE_PERCPU_ARRAY:
11872 	case BPF_MAP_TYPE_PERCPU_HASH:
11873 	case BPF_MAP_TYPE_LRU_PERCPU_HASH:
11874 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: {
11875 		int num_cpu = libbpf_num_possible_cpus();
11876 		size_t elem_sz = roundup(map->def.value_size, 8);
11877 
11878 		if (flags & (BPF_F_CPU | BPF_F_ALL_CPUS)) {
11879 			if ((flags & BPF_F_CPU) && (flags & BPF_F_ALL_CPUS)) {
11880 				pr_warn("map '%s': BPF_F_CPU and BPF_F_ALL_CPUS are mutually exclusive\n",
11881 					map->name);
11882 				return -EINVAL;
11883 			}
11884 			if (map->def.value_size != value_sz) {
11885 				pr_warn("map '%s': unexpected value size %zu provided for either BPF_F_CPU or BPF_F_ALL_CPUS, expected %u\n",
11886 					map->name, value_sz, map->def.value_size);
11887 				return -EINVAL;
11888 			}
11889 			break;
11890 		}
11891 
11892 		if (value_sz != num_cpu * elem_sz) {
11893 			pr_warn("map '%s': unexpected value size %zu provided for per-CPU map, expected %d * %zu = %zu\n",
11894 				map->name, value_sz, num_cpu, elem_sz, num_cpu * elem_sz);
11895 			return -EINVAL;
11896 		}
11897 		break;
11898 	}
11899 	default:
11900 		if (map->def.value_size != value_sz) {
11901 			pr_warn("map '%s': unexpected value size %zu provided, expected %u\n",
11902 				map->name, value_sz, map->def.value_size);
11903 			return -EINVAL;
11904 		}
11905 		break;
11906 	}
11907 	return 0;
11908 }
11909 
11910 int bpf_map__lookup_elem(const struct bpf_map *map,
11911 			 const void *key, size_t key_sz,
11912 			 void *value, size_t value_sz, __u64 flags)
11913 {
11914 	int err;
11915 
11916 	err = validate_map_op(map, key_sz, value_sz, true, flags);
11917 	if (err)
11918 		return libbpf_err(err);
11919 
11920 	return bpf_map_lookup_elem_flags(map->fd, key, value, flags);
11921 }
11922 
11923 int bpf_map__update_elem(const struct bpf_map *map,
11924 			 const void *key, size_t key_sz,
11925 			 const void *value, size_t value_sz, __u64 flags)
11926 {
11927 	int err;
11928 
11929 	err = validate_map_op(map, key_sz, value_sz, true, flags);
11930 	if (err)
11931 		return libbpf_err(err);
11932 
11933 	return bpf_map_update_elem(map->fd, key, value, flags);
11934 }
11935 
11936 int bpf_map__delete_elem(const struct bpf_map *map,
11937 			 const void *key, size_t key_sz, __u64 flags)
11938 {
11939 	int err;
11940 
11941 	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */, flags);
11942 	if (err)
11943 		return libbpf_err(err);
11944 
11945 	return bpf_map_delete_elem_flags(map->fd, key, flags);
11946 }
11947 
11948 int bpf_map__lookup_and_delete_elem(const struct bpf_map *map,
11949 				    const void *key, size_t key_sz,
11950 				    void *value, size_t value_sz, __u64 flags)
11951 {
11952 	int err;
11953 
11954 	err = validate_map_op(map, key_sz, value_sz, true, flags);
11955 	if (err)
11956 		return libbpf_err(err);
11957 
11958 	return bpf_map_lookup_and_delete_elem_flags(map->fd, key, value, flags);
11959 }
11960 
11961 int bpf_map__get_next_key(const struct bpf_map *map,
11962 			  const void *cur_key, void *next_key, size_t key_sz)
11963 {
11964 	int err;
11965 
11966 	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */, 0);
11967 	if (err)
11968 		return libbpf_err(err);
11969 
11970 	return bpf_map_get_next_key(map->fd, cur_key, next_key);
11971 }
11972 
11973 long libbpf_get_error(const void *ptr)
11974 {
11975 	if (!IS_ERR_OR_NULL(ptr))
11976 		return 0;
11977 
11978 	if (IS_ERR(ptr))
11979 		errno = -PTR_ERR(ptr);
11980 
11981 	/* If ptr == NULL, then errno should be already set by the failing
11982 	 * API, because libbpf never returns NULL on success and it now always
11983 	 * sets errno on error. So no extra errno handling for ptr == NULL
11984 	 * case.
11985 	 */
11986 	return -errno;
11987 }
11988 
11989 /* Replace link's underlying BPF program with the new one */
11990 int bpf_link__update_program(struct bpf_link *link, struct bpf_program *prog)
11991 {
11992 	int ret;
11993 	int prog_fd = bpf_program__fd(prog);
11994 
11995 	if (prog_fd < 0) {
11996 		pr_warn("prog '%s': can't use BPF program without FD (was it loaded?)\n",
11997 			prog->name);
11998 		return libbpf_err(-EINVAL);
11999 	}
12000 
12001 	ret = bpf_link_update(bpf_link__fd(link), prog_fd, NULL);
12002 	return libbpf_err_errno(ret);
12003 }
12004 
12005 /* Release "ownership" of underlying BPF resource (typically, BPF program
12006  * attached to some BPF hook, e.g., tracepoint, kprobe, etc). Disconnected
12007  * link, when destructed through bpf_link__destroy() call won't attempt to
12008  * detach/unregisted that BPF resource. This is useful in situations where,
12009  * say, attached BPF program has to outlive userspace program that attached it
12010  * in the system. Depending on type of BPF program, though, there might be
12011  * additional steps (like pinning BPF program in BPF FS) necessary to ensure
12012  * exit of userspace program doesn't trigger automatic detachment and clean up
12013  * inside the kernel.
12014  */
12015 void bpf_link__disconnect(struct bpf_link *link)
12016 {
12017 	link->disconnected = true;
12018 }
12019 
12020 int bpf_link__destroy(struct bpf_link *link)
12021 {
12022 	int err = 0;
12023 
12024 	if (IS_ERR_OR_NULL(link))
12025 		return 0;
12026 
12027 	if (!link->disconnected && link->detach)
12028 		err = link->detach(link);
12029 	if (link->pin_path)
12030 		free(link->pin_path);
12031 	if (link->dealloc)
12032 		link->dealloc(link);
12033 	else
12034 		free(link);
12035 
12036 	return libbpf_err(err);
12037 }
12038 
12039 int bpf_link__fd(const struct bpf_link *link)
12040 {
12041 	return link->fd;
12042 }
12043 
12044 const char *bpf_link__pin_path(const struct bpf_link *link)
12045 {
12046 	return link->pin_path;
12047 }
12048 
12049 static int bpf_link__detach_fd(struct bpf_link *link)
12050 {
12051 	return libbpf_err_errno(close(link->fd));
12052 }
12053 
12054 struct bpf_link *bpf_link__open(const char *path)
12055 {
12056 	struct bpf_link *link;
12057 	int fd;
12058 
12059 	fd = bpf_obj_get(path);
12060 	if (fd < 0) {
12061 		fd = -errno;
12062 		pr_warn("failed to open link at %s: %d\n", path, fd);
12063 		return libbpf_err_ptr(fd);
12064 	}
12065 
12066 	link = calloc(1, sizeof(*link));
12067 	if (!link) {
12068 		close(fd);
12069 		return libbpf_err_ptr(-ENOMEM);
12070 	}
12071 	link->detach = &bpf_link__detach_fd;
12072 	link->fd = fd;
12073 
12074 	link->pin_path = strdup(path);
12075 	if (!link->pin_path) {
12076 		bpf_link__destroy(link);
12077 		return libbpf_err_ptr(-ENOMEM);
12078 	}
12079 
12080 	return link;
12081 }
12082 
12083 int bpf_link__detach(struct bpf_link *link)
12084 {
12085 	return bpf_link_detach(link->fd) ? -errno : 0;
12086 }
12087 
12088 int bpf_link__pin(struct bpf_link *link, const char *path)
12089 {
12090 	int err;
12091 
12092 	if (link->pin_path)
12093 		return libbpf_err(-EBUSY);
12094 	err = make_parent_dir(path);
12095 	if (err)
12096 		return libbpf_err(err);
12097 	err = check_path(path);
12098 	if (err)
12099 		return libbpf_err(err);
12100 
12101 	link->pin_path = strdup(path);
12102 	if (!link->pin_path)
12103 		return libbpf_err(-ENOMEM);
12104 
12105 	if (bpf_obj_pin(link->fd, link->pin_path)) {
12106 		err = -errno;
12107 		zfree(&link->pin_path);
12108 		return libbpf_err(err);
12109 	}
12110 
12111 	pr_debug("link fd=%d: pinned at %s\n", link->fd, link->pin_path);
12112 	return 0;
12113 }
12114 
12115 int bpf_link__unpin(struct bpf_link *link)
12116 {
12117 	int err;
12118 
12119 	if (!link->pin_path)
12120 		return libbpf_err(-EINVAL);
12121 
12122 	err = unlink(link->pin_path);
12123 	if (err != 0)
12124 		return -errno;
12125 
12126 	pr_debug("link fd=%d: unpinned from %s\n", link->fd, link->pin_path);
12127 	zfree(&link->pin_path);
12128 	return 0;
12129 }
12130 
12131 struct bpf_link_perf {
12132 	struct bpf_link link;
12133 	int perf_event_fd;
12134 	/* legacy kprobe support: keep track of probe identifier and type */
12135 	char *legacy_probe_name;
12136 	bool legacy_is_kprobe;
12137 	bool legacy_is_retprobe;
12138 };
12139 
12140 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe);
12141 static int remove_uprobe_event_legacy(const char *probe_name, bool retprobe);
12142 
12143 static int bpf_link_perf_detach(struct bpf_link *link)
12144 {
12145 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
12146 	int err = 0;
12147 
12148 	if (ioctl(perf_link->perf_event_fd, PERF_EVENT_IOC_DISABLE, 0) < 0)
12149 		err = -errno;
12150 
12151 	if (perf_link->perf_event_fd != link->fd)
12152 		close(perf_link->perf_event_fd);
12153 	close(link->fd);
12154 
12155 	/* legacy uprobe/kprobe needs to be removed after perf event fd closure */
12156 	if (perf_link->legacy_probe_name) {
12157 		if (perf_link->legacy_is_kprobe) {
12158 			err = remove_kprobe_event_legacy(perf_link->legacy_probe_name,
12159 							 perf_link->legacy_is_retprobe);
12160 		} else {
12161 			err = remove_uprobe_event_legacy(perf_link->legacy_probe_name,
12162 							 perf_link->legacy_is_retprobe);
12163 		}
12164 	}
12165 
12166 	return err;
12167 }
12168 
12169 static void bpf_link_perf_dealloc(struct bpf_link *link)
12170 {
12171 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
12172 
12173 	free(perf_link->legacy_probe_name);
12174 	free(perf_link);
12175 }
12176 
12177 struct bpf_link *bpf_program__attach_perf_event_opts(const struct bpf_program *prog, int pfd,
12178 						     const struct bpf_perf_event_opts *opts)
12179 {
12180 	struct bpf_link_perf *link;
12181 	int prog_fd, link_fd = -1, err;
12182 	bool force_ioctl_attach;
12183 
12184 	if (!OPTS_VALID(opts, bpf_perf_event_opts))
12185 		return libbpf_err_ptr(-EINVAL);
12186 
12187 	if (pfd < 0) {
12188 		pr_warn("prog '%s': invalid perf event FD %d\n",
12189 			prog->name, pfd);
12190 		return libbpf_err_ptr(-EINVAL);
12191 	}
12192 	prog_fd = bpf_program__fd(prog);
12193 	if (prog_fd < 0) {
12194 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
12195 			prog->name);
12196 		return libbpf_err_ptr(-EINVAL);
12197 	}
12198 
12199 	link = calloc(1, sizeof(*link));
12200 	if (!link)
12201 		return libbpf_err_ptr(-ENOMEM);
12202 	link->link.detach = &bpf_link_perf_detach;
12203 	link->link.dealloc = &bpf_link_perf_dealloc;
12204 	link->perf_event_fd = pfd;
12205 
12206 	force_ioctl_attach = OPTS_GET(opts, force_ioctl_attach, false);
12207 	if (kernel_supports(prog->obj, FEAT_PERF_LINK) && !force_ioctl_attach) {
12208 		DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_opts,
12209 			.perf_event.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0));
12210 
12211 		link_fd = bpf_link_create(prog_fd, pfd, BPF_PERF_EVENT, &link_opts);
12212 		if (link_fd < 0) {
12213 			err = -errno;
12214 			pr_warn("prog '%s': failed to create BPF link for perf_event FD %d: %s\n",
12215 				prog->name, pfd, errstr(err));
12216 			goto err_out;
12217 		}
12218 		link->link.fd = link_fd;
12219 	} else {
12220 		if (OPTS_GET(opts, bpf_cookie, 0)) {
12221 			pr_warn("prog '%s': user context value is not supported\n", prog->name);
12222 			err = -EOPNOTSUPP;
12223 			goto err_out;
12224 		}
12225 
12226 		if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
12227 			err = -errno;
12228 			pr_warn("prog '%s': failed to attach to perf_event FD %d: %s\n",
12229 				prog->name, pfd, errstr(err));
12230 			if (err == -EPROTO)
12231 				pr_warn("prog '%s': try add PERF_SAMPLE_CALLCHAIN to or remove exclude_callchain_[kernel|user] from pfd %d\n",
12232 					prog->name, pfd);
12233 			goto err_out;
12234 		}
12235 		link->link.fd = pfd;
12236 	}
12237 
12238 	if (!OPTS_GET(opts, dont_enable, false)) {
12239 		if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
12240 			err = -errno;
12241 			pr_warn("prog '%s': failed to enable perf_event FD %d: %s\n",
12242 				prog->name, pfd, errstr(err));
12243 			goto err_out;
12244 		}
12245 	}
12246 
12247 	return &link->link;
12248 err_out:
12249 	if (link_fd >= 0)
12250 		close(link_fd);
12251 	free(link);
12252 	return libbpf_err_ptr(err);
12253 }
12254 
12255 struct bpf_link *bpf_program__attach_perf_event(const struct bpf_program *prog, int pfd)
12256 {
12257 	return bpf_program__attach_perf_event_opts(prog, pfd, NULL);
12258 }
12259 
12260 /*
12261  * this function is expected to parse integer in the range of [0, 2^31-1] from
12262  * given file using scanf format string fmt. If actual parsed value is
12263  * negative, the result might be indistinguishable from error
12264  */
12265 static int parse_uint_from_file(const char *file, const char *fmt)
12266 {
12267 	int err, ret;
12268 	FILE *f;
12269 
12270 	f = fopen(file, "re");
12271 	if (!f) {
12272 		err = -errno;
12273 		pr_debug("failed to open '%s': %s\n", file, errstr(err));
12274 		return err;
12275 	}
12276 	err = fscanf(f, fmt, &ret);
12277 	if (err != 1) {
12278 		err = err == EOF ? -EIO : -errno;
12279 		pr_debug("failed to parse '%s': %s\n", file, errstr(err));
12280 		fclose(f);
12281 		return err;
12282 	}
12283 	fclose(f);
12284 	return ret;
12285 }
12286 
12287 static int determine_kprobe_perf_type(void)
12288 {
12289 	const char *file = "/sys/bus/event_source/devices/kprobe/type";
12290 
12291 	return parse_uint_from_file(file, "%d\n");
12292 }
12293 
12294 static int determine_uprobe_perf_type(void)
12295 {
12296 	const char *file = "/sys/bus/event_source/devices/uprobe/type";
12297 
12298 	return parse_uint_from_file(file, "%d\n");
12299 }
12300 
12301 static int determine_kprobe_retprobe_bit(void)
12302 {
12303 	const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
12304 
12305 	return parse_uint_from_file(file, "config:%d\n");
12306 }
12307 
12308 static int determine_uprobe_retprobe_bit(void)
12309 {
12310 	const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
12311 
12312 	return parse_uint_from_file(file, "config:%d\n");
12313 }
12314 
12315 #define PERF_UPROBE_REF_CTR_OFFSET_BITS 32
12316 #define PERF_UPROBE_REF_CTR_OFFSET_SHIFT 32
12317 
12318 static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
12319 				 uint64_t offset, int pid, size_t ref_ctr_off)
12320 {
12321 	const size_t attr_sz = sizeof(struct perf_event_attr);
12322 	struct perf_event_attr attr;
12323 	int type, pfd;
12324 
12325 	if ((__u64)ref_ctr_off >= (1ULL << PERF_UPROBE_REF_CTR_OFFSET_BITS))
12326 		return -EINVAL;
12327 
12328 	memset(&attr, 0, attr_sz);
12329 
12330 	type = uprobe ? determine_uprobe_perf_type()
12331 		      : determine_kprobe_perf_type();
12332 	if (type < 0) {
12333 		pr_warn("failed to determine %s perf type: %s\n",
12334 			uprobe ? "uprobe" : "kprobe",
12335 			errstr(type));
12336 		return type;
12337 	}
12338 	if (retprobe) {
12339 		int bit = uprobe ? determine_uprobe_retprobe_bit()
12340 				 : determine_kprobe_retprobe_bit();
12341 
12342 		if (bit < 0) {
12343 			pr_warn("failed to determine %s retprobe bit: %s\n",
12344 				uprobe ? "uprobe" : "kprobe",
12345 				errstr(bit));
12346 			return bit;
12347 		}
12348 		attr.config |= 1ULL << bit;
12349 	}
12350 	attr.size = attr_sz;
12351 	attr.type = type;
12352 	attr.config |= (__u64)ref_ctr_off << PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
12353 	attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
12354 	attr.config2 = offset;		 /* kprobe_addr or probe_offset */
12355 
12356 	/* pid filter is meaningful only for uprobes */
12357 	pfd = syscall(__NR_perf_event_open, &attr,
12358 		      pid < 0 ? -1 : pid /* pid */,
12359 		      pid == -1 ? 0 : -1 /* cpu */,
12360 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
12361 	return pfd >= 0 ? pfd : -errno;
12362 }
12363 
12364 static int append_to_file(const char *file, const char *fmt, ...)
12365 {
12366 	int fd, n, err = 0;
12367 	va_list ap;
12368 	char buf[1024];
12369 
12370 	va_start(ap, fmt);
12371 	n = vsnprintf(buf, sizeof(buf), fmt, ap);
12372 	va_end(ap);
12373 
12374 	if (n < 0 || n >= sizeof(buf))
12375 		return -EINVAL;
12376 
12377 	fd = open(file, O_WRONLY | O_APPEND | O_CLOEXEC, 0);
12378 	if (fd < 0)
12379 		return -errno;
12380 
12381 	if (write(fd, buf, n) < 0)
12382 		err = -errno;
12383 
12384 	close(fd);
12385 	return err;
12386 }
12387 
12388 #define DEBUGFS "/sys/kernel/debug/tracing"
12389 #define TRACEFS "/sys/kernel/tracing"
12390 
12391 static bool use_debugfs(void)
12392 {
12393 	static int has_debugfs = -1;
12394 
12395 	if (has_debugfs < 0)
12396 		has_debugfs = faccessat(AT_FDCWD, DEBUGFS, F_OK, AT_EACCESS) == 0;
12397 
12398 	return has_debugfs == 1;
12399 }
12400 
12401 static const char *tracefs_path(void)
12402 {
12403 	return use_debugfs() ? DEBUGFS : TRACEFS;
12404 }
12405 
12406 static const char *tracefs_kprobe_events(void)
12407 {
12408 	return use_debugfs() ? DEBUGFS"/kprobe_events" : TRACEFS"/kprobe_events";
12409 }
12410 
12411 static const char *tracefs_uprobe_events(void)
12412 {
12413 	return use_debugfs() ? DEBUGFS"/uprobe_events" : TRACEFS"/uprobe_events";
12414 }
12415 
12416 static const char *tracefs_available_filter_functions(void)
12417 {
12418 	return use_debugfs() ? DEBUGFS"/available_filter_functions"
12419 			     : TRACEFS"/available_filter_functions";
12420 }
12421 
12422 static const char *tracefs_available_filter_functions_addrs(void)
12423 {
12424 	return use_debugfs() ? DEBUGFS"/available_filter_functions_addrs"
12425 			     : TRACEFS"/available_filter_functions_addrs";
12426 }
12427 
12428 static void gen_probe_legacy_event_name(char *buf, size_t buf_sz,
12429 					const char *name, size_t offset)
12430 {
12431 	static int index = 0;
12432 	int i;
12433 
12434 	snprintf(buf, buf_sz, "libbpf_%d_%d_%s_0x%zx", getpid(),
12435 		 __sync_fetch_and_add(&index, 1), name, offset);
12436 
12437 	/* sanitize name in the probe name */
12438 	for (i = 0; buf[i]; i++) {
12439 		if (!isalnum(buf[i]))
12440 			buf[i] = '_';
12441 	}
12442 }
12443 
12444 static int add_kprobe_event_legacy(const char *probe_name, bool retprobe,
12445 				   const char *kfunc_name, size_t offset)
12446 {
12447 	return append_to_file(tracefs_kprobe_events(), "%c:%s/%s %s+0x%zx",
12448 			      retprobe ? 'r' : 'p',
12449 			      retprobe ? "kretprobes" : "kprobes",
12450 			      probe_name, kfunc_name, offset);
12451 }
12452 
12453 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe)
12454 {
12455 	return append_to_file(tracefs_kprobe_events(), "-:%s/%s",
12456 			      retprobe ? "kretprobes" : "kprobes", probe_name);
12457 }
12458 
12459 static int determine_kprobe_perf_type_legacy(const char *probe_name, bool retprobe)
12460 {
12461 	char file[256];
12462 
12463 	snprintf(file, sizeof(file), "%s/events/%s/%s/id",
12464 		 tracefs_path(), retprobe ? "kretprobes" : "kprobes", probe_name);
12465 
12466 	return parse_uint_from_file(file, "%d\n");
12467 }
12468 
12469 static int perf_event_kprobe_open_legacy(const char *probe_name, bool retprobe,
12470 					 const char *kfunc_name, size_t offset, int pid)
12471 {
12472 	const size_t attr_sz = sizeof(struct perf_event_attr);
12473 	struct perf_event_attr attr;
12474 	int type, pfd, err;
12475 
12476 	err = add_kprobe_event_legacy(probe_name, retprobe, kfunc_name, offset);
12477 	if (err < 0) {
12478 		pr_warn("failed to add legacy kprobe event for '%s+0x%zx': %s\n",
12479 			kfunc_name, offset,
12480 			errstr(err));
12481 		return err;
12482 	}
12483 	type = determine_kprobe_perf_type_legacy(probe_name, retprobe);
12484 	if (type < 0) {
12485 		err = type;
12486 		pr_warn("failed to determine legacy kprobe event id for '%s+0x%zx': %s\n",
12487 			kfunc_name, offset,
12488 			errstr(err));
12489 		goto err_clean_legacy;
12490 	}
12491 
12492 	memset(&attr, 0, attr_sz);
12493 	attr.size = attr_sz;
12494 	attr.config = type;
12495 	attr.type = PERF_TYPE_TRACEPOINT;
12496 
12497 	pfd = syscall(__NR_perf_event_open, &attr,
12498 		      pid < 0 ? -1 : pid, /* pid */
12499 		      pid == -1 ? 0 : -1, /* cpu */
12500 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
12501 	if (pfd < 0) {
12502 		err = -errno;
12503 		pr_warn("legacy kprobe perf_event_open() failed: %s\n",
12504 			errstr(err));
12505 		goto err_clean_legacy;
12506 	}
12507 	return pfd;
12508 
12509 err_clean_legacy:
12510 	/* Clear the newly added legacy kprobe_event */
12511 	remove_kprobe_event_legacy(probe_name, retprobe);
12512 	return err;
12513 }
12514 
12515 static const char *arch_specific_syscall_pfx(void)
12516 {
12517 #if defined(__x86_64__)
12518 	return "x64";
12519 #elif defined(__i386__)
12520 	return "ia32";
12521 #elif defined(__s390x__)
12522 	return "s390x";
12523 #elif defined(__arm__)
12524 	return "arm";
12525 #elif defined(__aarch64__)
12526 	return "arm64";
12527 #elif defined(__mips__)
12528 	return "mips";
12529 #elif defined(__riscv)
12530 	return "riscv";
12531 #elif defined(__powerpc__)
12532 	return "powerpc";
12533 #elif defined(__powerpc64__)
12534 	return "powerpc64";
12535 #else
12536 	return NULL;
12537 #endif
12538 }
12539 
12540 int probe_kern_syscall_wrapper(int token_fd)
12541 {
12542 	char syscall_name[64];
12543 	const char *ksys_pfx;
12544 
12545 	ksys_pfx = arch_specific_syscall_pfx();
12546 	if (!ksys_pfx)
12547 		return 0;
12548 
12549 	snprintf(syscall_name, sizeof(syscall_name), "__%s_sys_bpf", ksys_pfx);
12550 
12551 	if (determine_kprobe_perf_type() >= 0) {
12552 		int pfd;
12553 
12554 		pfd = perf_event_open_probe(false, false, syscall_name, 0, getpid(), 0);
12555 		if (pfd >= 0)
12556 			close(pfd);
12557 
12558 		return pfd >= 0 ? 1 : 0;
12559 	} else { /* legacy mode */
12560 		char probe_name[MAX_EVENT_NAME_LEN];
12561 
12562 		gen_probe_legacy_event_name(probe_name, sizeof(probe_name), syscall_name, 0);
12563 		if (add_kprobe_event_legacy(probe_name, false, syscall_name, 0) < 0)
12564 			return 0;
12565 
12566 		(void)remove_kprobe_event_legacy(probe_name, false);
12567 		return 1;
12568 	}
12569 }
12570 
12571 struct bpf_link *
12572 bpf_program__attach_kprobe_opts(const struct bpf_program *prog,
12573 				const char *func_name,
12574 				const struct bpf_kprobe_opts *opts)
12575 {
12576 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
12577 	enum probe_attach_mode attach_mode;
12578 	char *legacy_probe = NULL;
12579 	struct bpf_link *link;
12580 	size_t offset;
12581 	bool retprobe, legacy;
12582 	int pfd, err;
12583 
12584 	if (!OPTS_VALID(opts, bpf_kprobe_opts))
12585 		return libbpf_err_ptr(-EINVAL);
12586 
12587 	attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
12588 	retprobe = OPTS_GET(opts, retprobe, false);
12589 	offset = OPTS_GET(opts, offset, 0);
12590 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
12591 
12592 	legacy = determine_kprobe_perf_type() < 0;
12593 	switch (attach_mode) {
12594 	case PROBE_ATTACH_MODE_LEGACY:
12595 		legacy = true;
12596 		pe_opts.force_ioctl_attach = true;
12597 		break;
12598 	case PROBE_ATTACH_MODE_PERF:
12599 		if (legacy)
12600 			return libbpf_err_ptr(-ENOTSUP);
12601 		pe_opts.force_ioctl_attach = true;
12602 		break;
12603 	case PROBE_ATTACH_MODE_LINK:
12604 		if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
12605 			return libbpf_err_ptr(-ENOTSUP);
12606 		break;
12607 	case PROBE_ATTACH_MODE_DEFAULT:
12608 		break;
12609 	default:
12610 		return libbpf_err_ptr(-EINVAL);
12611 	}
12612 	if (!func_name && legacy)
12613 		return libbpf_err_ptr(-EOPNOTSUPP);
12614 
12615 	if (!legacy) {
12616 		pfd = perf_event_open_probe(false /* uprobe */, retprobe,
12617 					    func_name, offset,
12618 					    -1 /* pid */, 0 /* ref_ctr_off */);
12619 	} else {
12620 		char probe_name[MAX_EVENT_NAME_LEN];
12621 
12622 		gen_probe_legacy_event_name(probe_name, sizeof(probe_name),
12623 					    func_name, offset);
12624 
12625 		legacy_probe = strdup(probe_name);
12626 		if (!legacy_probe)
12627 			return libbpf_err_ptr(-ENOMEM);
12628 
12629 		pfd = perf_event_kprobe_open_legacy(legacy_probe, retprobe, func_name,
12630 						    offset, -1 /* pid */);
12631 	}
12632 	if (pfd < 0) {
12633 		err = pfd;
12634 		pr_warn("prog '%s': failed to create %s '%s%s0x%zx' perf event: %s\n",
12635 			prog->name, retprobe ? "kretprobe" : "kprobe",
12636 			func_name ?: "", func_name ? "+" : "",
12637 			offset, errstr(err));
12638 		goto err_out;
12639 	}
12640 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
12641 	err = libbpf_get_error(link);
12642 	if (err) {
12643 		close(pfd);
12644 		pr_warn("prog '%s': failed to attach to %s '%s%s0x%zx': %s\n",
12645 			prog->name, retprobe ? "kretprobe" : "kprobe",
12646 			func_name ?: "", func_name ? "+" : "",
12647 			offset, errstr(err));
12648 		goto err_clean_legacy;
12649 	}
12650 	if (legacy) {
12651 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
12652 
12653 		perf_link->legacy_probe_name = legacy_probe;
12654 		perf_link->legacy_is_kprobe = true;
12655 		perf_link->legacy_is_retprobe = retprobe;
12656 	}
12657 
12658 	return link;
12659 
12660 err_clean_legacy:
12661 	if (legacy)
12662 		remove_kprobe_event_legacy(legacy_probe, retprobe);
12663 err_out:
12664 	free(legacy_probe);
12665 	return libbpf_err_ptr(err);
12666 }
12667 
12668 struct bpf_link *bpf_program__attach_kprobe(const struct bpf_program *prog,
12669 					    bool retprobe,
12670 					    const char *func_name)
12671 {
12672 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts,
12673 		.retprobe = retprobe,
12674 	);
12675 
12676 	return bpf_program__attach_kprobe_opts(prog, func_name, &opts);
12677 }
12678 
12679 struct bpf_link *bpf_program__attach_ksyscall(const struct bpf_program *prog,
12680 					      const char *syscall_name,
12681 					      const struct bpf_ksyscall_opts *opts)
12682 {
12683 	LIBBPF_OPTS(bpf_kprobe_opts, kprobe_opts);
12684 	char func_name[128];
12685 
12686 	if (!OPTS_VALID(opts, bpf_ksyscall_opts))
12687 		return libbpf_err_ptr(-EINVAL);
12688 
12689 	if (kernel_supports(prog->obj, FEAT_SYSCALL_WRAPPER)) {
12690 		/* arch_specific_syscall_pfx() should never return NULL here
12691 		 * because it is guarded by kernel_supports(). However, since
12692 		 * compiler does not know that we have an explicit conditional
12693 		 * as well.
12694 		 */
12695 		snprintf(func_name, sizeof(func_name), "__%s_sys_%s",
12696 			 arch_specific_syscall_pfx() ? : "", syscall_name);
12697 	} else {
12698 		snprintf(func_name, sizeof(func_name), "__se_sys_%s", syscall_name);
12699 	}
12700 
12701 	kprobe_opts.retprobe = OPTS_GET(opts, retprobe, false);
12702 	kprobe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
12703 
12704 	return bpf_program__attach_kprobe_opts(prog, func_name, &kprobe_opts);
12705 }
12706 
12707 /* Adapted from perf/util/string.c */
12708 bool glob_match(const char *str, const char *pat)
12709 {
12710 	while (*str && *pat && *pat != '*') {
12711 		if (*pat == '?') {      /* Matches any single character */
12712 			str++;
12713 			pat++;
12714 			continue;
12715 		}
12716 		if (*str != *pat)
12717 			return false;
12718 		str++;
12719 		pat++;
12720 	}
12721 	/* Check wild card */
12722 	if (*pat == '*') {
12723 		while (*pat == '*')
12724 			pat++;
12725 		if (!*pat) /* Tail wild card matches all */
12726 			return true;
12727 		while (*str)
12728 			if (glob_match(str++, pat))
12729 				return true;
12730 	}
12731 	return !*str && !*pat;
12732 }
12733 
12734 struct kprobe_multi_resolve {
12735 	const char *pattern;
12736 	unsigned long *addrs;
12737 	size_t cap;
12738 	size_t cnt;
12739 };
12740 
12741 struct avail_kallsyms_data {
12742 	char **syms;
12743 	size_t cnt;
12744 	struct kprobe_multi_resolve *res;
12745 };
12746 
12747 static int avail_func_cmp(const void *a, const void *b)
12748 {
12749 	return strcmp(*(const char **)a, *(const char **)b);
12750 }
12751 
12752 static int avail_kallsyms_cb(unsigned long long sym_addr, char sym_type,
12753 			     const char *sym_name, void *ctx)
12754 {
12755 	struct avail_kallsyms_data *data = ctx;
12756 	struct kprobe_multi_resolve *res = data->res;
12757 	int err;
12758 
12759 	if (!glob_match(sym_name, res->pattern))
12760 		return 0;
12761 
12762 	if (!bsearch(&sym_name, data->syms, data->cnt, sizeof(*data->syms), avail_func_cmp)) {
12763 		/* Some versions of kernel strip out .llvm.<hash> suffix from
12764 		 * function names reported in available_filter_functions, but
12765 		 * don't do so for kallsyms. While this is clearly a kernel
12766 		 * bug (fixed by [0]) we try to accommodate that in libbpf to
12767 		 * make multi-kprobe usability a bit better: if no match is
12768 		 * found, we will strip .llvm. suffix and try one more time.
12769 		 *
12770 		 *   [0] fb6a421fb615 ("kallsyms: Match symbols exactly with CONFIG_LTO_CLANG")
12771 		 */
12772 		char sym_trim[256], *psym_trim = sym_trim;
12773 		const char *sym_sfx;
12774 
12775 		if (!(sym_sfx = strstr(sym_name, ".llvm.")))
12776 			return 0;
12777 
12778 		/* psym_trim vs sym_trim dance is done to avoid pointer vs array
12779 		 * coercion differences and get proper `const char **` pointer
12780 		 * which avail_func_cmp() expects
12781 		 */
12782 		snprintf(sym_trim, sizeof(sym_trim), "%.*s", (int)(sym_sfx - sym_name), sym_name);
12783 		if (!bsearch(&psym_trim, data->syms, data->cnt, sizeof(*data->syms), avail_func_cmp))
12784 			return 0;
12785 	}
12786 
12787 	err = libbpf_ensure_mem((void **)&res->addrs, &res->cap, sizeof(*res->addrs), res->cnt + 1);
12788 	if (err)
12789 		return err;
12790 
12791 	res->addrs[res->cnt++] = (unsigned long)sym_addr;
12792 	return 0;
12793 }
12794 
12795 static int libbpf_available_kallsyms_parse(struct kprobe_multi_resolve *res)
12796 {
12797 	const char *available_functions_file = tracefs_available_filter_functions();
12798 	struct avail_kallsyms_data data;
12799 	char sym_name[500];
12800 	FILE *f;
12801 	int err = 0, ret, i;
12802 	char **syms = NULL;
12803 	size_t cap = 0, cnt = 0;
12804 
12805 	f = fopen(available_functions_file, "re");
12806 	if (!f) {
12807 		err = -errno;
12808 		pr_warn("failed to open %s: %s\n", available_functions_file, errstr(err));
12809 		return err;
12810 	}
12811 
12812 	while (true) {
12813 		char *name;
12814 
12815 		ret = fscanf(f, "%499s%*[^\n]\n", sym_name);
12816 		if (ret == EOF && feof(f))
12817 			break;
12818 
12819 		if (ret != 1) {
12820 			pr_warn("failed to parse available_filter_functions entry: %d\n", ret);
12821 			err = -EINVAL;
12822 			goto cleanup;
12823 		}
12824 
12825 		if (!glob_match(sym_name, res->pattern))
12826 			continue;
12827 
12828 		err = libbpf_ensure_mem((void **)&syms, &cap, sizeof(*syms), cnt + 1);
12829 		if (err)
12830 			goto cleanup;
12831 
12832 		name = strdup(sym_name);
12833 		if (!name) {
12834 			err = -errno;
12835 			goto cleanup;
12836 		}
12837 
12838 		syms[cnt++] = name;
12839 	}
12840 
12841 	/* no entries found, bail out */
12842 	if (cnt == 0) {
12843 		err = -ENOENT;
12844 		goto cleanup;
12845 	}
12846 
12847 	/* sort available functions */
12848 	qsort(syms, cnt, sizeof(*syms), avail_func_cmp);
12849 
12850 	data.syms = syms;
12851 	data.res = res;
12852 	data.cnt = cnt;
12853 	libbpf_kallsyms_parse(avail_kallsyms_cb, &data);
12854 
12855 	if (res->cnt == 0)
12856 		err = -ENOENT;
12857 
12858 cleanup:
12859 	for (i = 0; i < cnt; i++)
12860 		free((char *)syms[i]);
12861 	free(syms);
12862 
12863 	fclose(f);
12864 	return err;
12865 }
12866 
12867 static bool has_available_filter_functions_addrs(void)
12868 {
12869 	return access(tracefs_available_filter_functions_addrs(), R_OK) != -1;
12870 }
12871 
12872 static int libbpf_available_kprobes_parse(struct kprobe_multi_resolve *res)
12873 {
12874 	const char *available_path = tracefs_available_filter_functions_addrs();
12875 	char sym_name[500];
12876 	FILE *f;
12877 	int ret, err = 0;
12878 	unsigned long long sym_addr;
12879 
12880 	f = fopen(available_path, "re");
12881 	if (!f) {
12882 		err = -errno;
12883 		pr_warn("failed to open %s: %s\n", available_path, errstr(err));
12884 		return err;
12885 	}
12886 
12887 	while (true) {
12888 		ret = fscanf(f, "%llx %499s%*[^\n]\n", &sym_addr, sym_name);
12889 		if (ret == EOF && feof(f))
12890 			break;
12891 
12892 		if (ret != 2) {
12893 			pr_warn("failed to parse available_filter_functions_addrs entry: %d\n",
12894 				ret);
12895 			err = -EINVAL;
12896 			goto cleanup;
12897 		}
12898 
12899 		if (!glob_match(sym_name, res->pattern))
12900 			continue;
12901 
12902 		err = libbpf_ensure_mem((void **)&res->addrs, &res->cap,
12903 					sizeof(*res->addrs), res->cnt + 1);
12904 		if (err)
12905 			goto cleanup;
12906 
12907 		res->addrs[res->cnt++] = (unsigned long)sym_addr;
12908 	}
12909 
12910 	if (res->cnt == 0)
12911 		err = -ENOENT;
12912 
12913 cleanup:
12914 	fclose(f);
12915 	return err;
12916 }
12917 
12918 struct bpf_link *
12919 bpf_program__attach_kprobe_multi_opts(const struct bpf_program *prog,
12920 				      const char *pattern,
12921 				      const struct bpf_kprobe_multi_opts *opts)
12922 {
12923 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
12924 	struct kprobe_multi_resolve res = {
12925 		.pattern = pattern,
12926 	};
12927 	enum bpf_attach_type attach_type;
12928 	struct bpf_link *link = NULL;
12929 	const unsigned long *addrs;
12930 	int err, link_fd, prog_fd;
12931 	bool retprobe, session, unique_match;
12932 	const __u64 *cookies;
12933 	const char **syms;
12934 	size_t cnt;
12935 
12936 	if (!OPTS_VALID(opts, bpf_kprobe_multi_opts))
12937 		return libbpf_err_ptr(-EINVAL);
12938 
12939 	prog_fd = bpf_program__fd(prog);
12940 	if (prog_fd < 0) {
12941 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
12942 			prog->name);
12943 		return libbpf_err_ptr(-EINVAL);
12944 	}
12945 
12946 	syms    = OPTS_GET(opts, syms, false);
12947 	addrs   = OPTS_GET(opts, addrs, false);
12948 	cnt     = OPTS_GET(opts, cnt, false);
12949 	cookies = OPTS_GET(opts, cookies, false);
12950 	unique_match = OPTS_GET(opts, unique_match, false);
12951 
12952 	if (!pattern && !addrs && !syms)
12953 		return libbpf_err_ptr(-EINVAL);
12954 	if (pattern && (addrs || syms || cookies || cnt))
12955 		return libbpf_err_ptr(-EINVAL);
12956 	if (!pattern && !cnt)
12957 		return libbpf_err_ptr(-EINVAL);
12958 	if (!pattern && unique_match)
12959 		return libbpf_err_ptr(-EINVAL);
12960 	if (addrs && syms)
12961 		return libbpf_err_ptr(-EINVAL);
12962 
12963 	/*
12964 	 * Exact function name (no wildcards) without unique_match:
12965 	 * bypass kallsyms parsing and pass the symbol directly to the
12966 	 * kernel via syms[] array.  When unique_match is set, fall
12967 	 * through to the slow path which detects duplicate symbols.
12968 	 */
12969 	if (pattern && !strpbrk(pattern, "*?") && !unique_match) {
12970 		syms = &pattern;
12971 		cnt = 1;
12972 	} else if (pattern) {
12973 		if (has_available_filter_functions_addrs())
12974 			err = libbpf_available_kprobes_parse(&res);
12975 		else
12976 			err = libbpf_available_kallsyms_parse(&res);
12977 		if (err)
12978 			goto error;
12979 
12980 		if (unique_match && res.cnt != 1) {
12981 			pr_warn("prog '%s': failed to find a unique match for '%s' (%zu matches)\n",
12982 				prog->name, pattern, res.cnt);
12983 			err = -EINVAL;
12984 			goto error;
12985 		}
12986 
12987 		addrs = res.addrs;
12988 		cnt = res.cnt;
12989 	}
12990 
12991 	retprobe = OPTS_GET(opts, retprobe, false);
12992 	session  = OPTS_GET(opts, session, false);
12993 
12994 	if (retprobe && session)
12995 		return libbpf_err_ptr(-EINVAL);
12996 
12997 	attach_type = session ? BPF_TRACE_KPROBE_SESSION : BPF_TRACE_KPROBE_MULTI;
12998 
12999 	lopts.kprobe_multi.syms = syms;
13000 	lopts.kprobe_multi.addrs = addrs;
13001 	lopts.kprobe_multi.cookies = cookies;
13002 	lopts.kprobe_multi.cnt = cnt;
13003 	lopts.kprobe_multi.flags = retprobe ? BPF_F_KPROBE_MULTI_RETURN : 0;
13004 
13005 	link = calloc(1, sizeof(*link));
13006 	if (!link) {
13007 		err = -ENOMEM;
13008 		goto error;
13009 	}
13010 	link->detach = &bpf_link__detach_fd;
13011 
13012 	link_fd = bpf_link_create(prog_fd, 0, attach_type, &lopts);
13013 	if (link_fd < 0) {
13014 		err = -errno;
13015 		/*
13016 		 * Normalize error code: when exact name bypasses kallsyms
13017 		 * parsing, kernel returns ESRCH from ftrace_lookup_symbols().
13018 		 * Convert to ENOENT for API consistency with the pattern
13019 		 * matching path which returns ENOENT from userspace.
13020 		 */
13021 		if (err == -ESRCH)
13022 			err = -ENOENT;
13023 		pr_warn("prog '%s': failed to attach: %s\n",
13024 			prog->name, errstr(err));
13025 		goto error;
13026 	}
13027 	link->fd = link_fd;
13028 	free(res.addrs);
13029 	return link;
13030 
13031 error:
13032 	free(link);
13033 	free(res.addrs);
13034 	return libbpf_err_ptr(err);
13035 }
13036 
13037 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
13038 {
13039 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts);
13040 	long offset = 0;
13041 	const char *func_name;
13042 	char *func;
13043 	int n;
13044 
13045 	*link = NULL;
13046 
13047 	/* no auto-attach for SEC("kprobe") and SEC("kretprobe") */
13048 	if (strcmp(prog->sec_name, "kprobe") == 0 || strcmp(prog->sec_name, "kretprobe") == 0)
13049 		return 0;
13050 
13051 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe/");
13052 	if (opts.retprobe)
13053 		func_name = prog->sec_name + sizeof("kretprobe/") - 1;
13054 	else
13055 		func_name = prog->sec_name + sizeof("kprobe/") - 1;
13056 
13057 	n = sscanf(func_name, "%m[a-zA-Z0-9_.]+%li", &func, &offset);
13058 	if (n < 1) {
13059 		pr_warn("kprobe name is invalid: %s\n", func_name);
13060 		return -EINVAL;
13061 	}
13062 
13063 	if (offset < 0) {
13064 		free(func);
13065 		pr_warn("kprobe offset must be a non-negative integer: %li\n", offset);
13066 		return -EINVAL;
13067 	}
13068 
13069 	if (opts.retprobe && offset != 0) {
13070 		free(func);
13071 		pr_warn("kretprobes do not support offset specification\n");
13072 		return -EINVAL;
13073 	}
13074 
13075 	opts.offset = offset;
13076 	*link = bpf_program__attach_kprobe_opts(prog, func, &opts);
13077 	free(func);
13078 	return libbpf_get_error(*link);
13079 }
13080 
13081 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link)
13082 {
13083 	LIBBPF_OPTS(bpf_ksyscall_opts, opts);
13084 	const char *syscall_name;
13085 
13086 	*link = NULL;
13087 
13088 	/* no auto-attach for SEC("ksyscall") and SEC("kretsyscall") */
13089 	if (strcmp(prog->sec_name, "ksyscall") == 0 || strcmp(prog->sec_name, "kretsyscall") == 0)
13090 		return 0;
13091 
13092 	opts.retprobe = str_has_pfx(prog->sec_name, "kretsyscall/");
13093 	if (opts.retprobe)
13094 		syscall_name = prog->sec_name + sizeof("kretsyscall/") - 1;
13095 	else
13096 		syscall_name = prog->sec_name + sizeof("ksyscall/") - 1;
13097 
13098 	*link = bpf_program__attach_ksyscall(prog, syscall_name, &opts);
13099 	return *link ? 0 : -errno;
13100 }
13101 
13102 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
13103 {
13104 	LIBBPF_OPTS(bpf_kprobe_multi_opts, opts);
13105 	const char *spec;
13106 	char *pattern;
13107 	int n;
13108 
13109 	*link = NULL;
13110 
13111 	/* no auto-attach for SEC("kprobe.multi") and SEC("kretprobe.multi") */
13112 	if (strcmp(prog->sec_name, "kprobe.multi") == 0 ||
13113 	    strcmp(prog->sec_name, "kretprobe.multi") == 0)
13114 		return 0;
13115 
13116 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe.multi/");
13117 	if (opts.retprobe)
13118 		spec = prog->sec_name + sizeof("kretprobe.multi/") - 1;
13119 	else
13120 		spec = prog->sec_name + sizeof("kprobe.multi/") - 1;
13121 
13122 	n = sscanf(spec, "%m[a-zA-Z0-9_.*?]", &pattern);
13123 	if (n < 1) {
13124 		pr_warn("kprobe multi pattern is invalid: %s\n", spec);
13125 		return -EINVAL;
13126 	}
13127 
13128 	*link = bpf_program__attach_kprobe_multi_opts(prog, pattern, &opts);
13129 	free(pattern);
13130 	return libbpf_get_error(*link);
13131 }
13132 
13133 static int attach_kprobe_session(const struct bpf_program *prog, long cookie,
13134 				 struct bpf_link **link)
13135 {
13136 	LIBBPF_OPTS(bpf_kprobe_multi_opts, opts, .session = true);
13137 	const char *spec;
13138 	char *pattern;
13139 	int n;
13140 
13141 	*link = NULL;
13142 
13143 	/* no auto-attach for SEC("kprobe.session") */
13144 	if (strcmp(prog->sec_name, "kprobe.session") == 0)
13145 		return 0;
13146 
13147 	spec = prog->sec_name + sizeof("kprobe.session/") - 1;
13148 	n = sscanf(spec, "%m[a-zA-Z0-9_.*?]", &pattern);
13149 	if (n < 1) {
13150 		pr_warn("kprobe session pattern is invalid: %s\n", spec);
13151 		return -EINVAL;
13152 	}
13153 
13154 	*link = bpf_program__attach_kprobe_multi_opts(prog, pattern, &opts);
13155 	free(pattern);
13156 	return *link ? 0 : -errno;
13157 }
13158 
13159 static int attach_uprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
13160 {
13161 	char *probe_type = NULL, *binary_path = NULL, *func_name = NULL;
13162 	LIBBPF_OPTS(bpf_uprobe_multi_opts, opts);
13163 	int n, ret = -EINVAL;
13164 
13165 	*link = NULL;
13166 
13167 	n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[^\n]",
13168 		   &probe_type, &binary_path, &func_name);
13169 	switch (n) {
13170 	case 1:
13171 		/* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
13172 		ret = 0;
13173 		break;
13174 	case 3:
13175 		opts.session = str_has_pfx(probe_type, "uprobe.session");
13176 		opts.retprobe = str_has_pfx(probe_type, "uretprobe.multi");
13177 
13178 		*link = bpf_program__attach_uprobe_multi(prog, -1, binary_path, func_name, &opts);
13179 		ret = libbpf_get_error(*link);
13180 		break;
13181 	default:
13182 		pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
13183 			prog->sec_name);
13184 		break;
13185 	}
13186 	free(probe_type);
13187 	free(binary_path);
13188 	free(func_name);
13189 	return ret;
13190 }
13191 
13192 #define MAX_BPF_FUNC_ARGS 12
13193 
13194 static bool btf_type_is_modifier(const struct btf_type *t)
13195 {
13196 	switch (BTF_INFO_KIND(t->info)) {
13197 	case BTF_KIND_TYPEDEF:
13198 	case BTF_KIND_VOLATILE:
13199 	case BTF_KIND_CONST:
13200 	case BTF_KIND_RESTRICT:
13201 	case BTF_KIND_TYPE_TAG:
13202 		return true;
13203 	default:
13204 		return false;
13205 	}
13206 }
13207 
13208 #define MAX_RESOLVE_DEPTH 32
13209 
13210 static int btf_get_type_size(const struct btf *btf, __u32 type_id,
13211 			     const struct btf_type **ret_type)
13212 {
13213 	const struct btf_type *t;
13214 	int i;
13215 
13216 	*ret_type = btf__type_by_id(btf, 0);
13217 	if (!type_id)
13218 		return 0;
13219 	t = btf__type_by_id(btf, type_id);
13220 	for (i = 0; i < MAX_RESOLVE_DEPTH && t && btf_type_is_modifier(t); i++)
13221 		t = btf__type_by_id(btf, t->type);
13222 	if (!t || i == MAX_RESOLVE_DEPTH)
13223 		return -EINVAL;
13224 	*ret_type = t;
13225 	if (btf_is_ptr(t))
13226 		return btf__pointer_size(btf);
13227 	if (btf_is_int(t) || btf_is_any_enum(t) || btf_is_struct(t) || btf_is_union(t))
13228 		return t->size;
13229 	return -EINVAL;
13230 }
13231 
13232 bool btf_type_is_traceable_func(const struct btf *btf, const struct btf_type *t)
13233 {
13234 	const struct btf_param *args;
13235 	const struct btf_type *proto;
13236 	__u32 i, nargs;
13237 	int ret;
13238 
13239 	if (!btf_is_func(t))
13240 		return false;
13241 	proto = btf__type_by_id(btf, t->type);
13242 	if (!proto || !btf_is_func_proto(proto))
13243 		return false;
13244 
13245 	args = (const struct btf_param *)(proto + 1);
13246 	nargs = btf_vlen(proto);
13247 	if (nargs > MAX_BPF_FUNC_ARGS)
13248 		return false;
13249 
13250 	/* No support for struct return type. */
13251 	ret = btf_get_type_size(btf, proto->type, &t);
13252 	if (ret < 0 || btf_is_struct(t) || btf_is_union(t))
13253 		return false;
13254 
13255 	for (i = 0; i < nargs; i++) {
13256 		/* No support for variable args. */
13257 		if (i == nargs - 1 && args[i].type == 0)
13258 			return false;
13259 		ret = btf_get_type_size(btf, args[i].type, &t);
13260 		/* No support of struct argument size greater than 16 bytes. */
13261 		if (ret < 0 || ret > 16)
13262 			return false;
13263 		/* No support for void argument. */
13264 		if (ret == 0)
13265 			return false;
13266 	}
13267 
13268 	return true;
13269 }
13270 
13271 static int
13272 collect_btf_func_ids_by_glob(const struct btf *btf, const char *pattern, __u32 **ids)
13273 {
13274 	__u32 type_id, nr_types = btf__type_cnt(btf);
13275 	size_t cap = 0, cnt = 0;
13276 
13277 	if (!pattern)
13278 		return -EINVAL;
13279 
13280 	for (type_id = 1; type_id < nr_types; type_id++) {
13281 		const struct btf_type *t = btf__type_by_id(btf, type_id);
13282 		const char *name;
13283 		int err;
13284 
13285 		if (btf_kind(t) != BTF_KIND_FUNC)
13286 			continue;
13287 		name = btf__name_by_offset(btf, t->name_off);
13288 		if (!name)
13289 			continue;
13290 
13291 		if (!glob_match(name, pattern))
13292 			continue;
13293 		if (!btf_type_is_traceable_func(btf, t))
13294 			continue;
13295 
13296 		err = libbpf_ensure_mem((void **) ids, &cap, sizeof(**ids), cnt + 1);
13297 		if (err) {
13298 			free(*ids);
13299 			return -ENOMEM;
13300 		}
13301 		(*ids)[cnt++] = type_id;
13302 	}
13303 
13304 	return cnt;
13305 }
13306 
13307 static int collect_func_ids_by_glob(const struct bpf_program *prog, const char *pattern, __u32 **ids)
13308 {
13309 	struct bpf_object *obj = prog->obj;
13310 	const struct module_btf *mod;
13311 	struct btf *btf = NULL;
13312 	const char *sep;
13313 	int err;
13314 
13315 	err = bpf_object__load_vmlinux_btf(obj, true);
13316 	if (err)
13317 		return err;
13318 
13319 	/* In case we have module specified, we will find its btf and use that. */
13320 	sep = strchr(pattern, ':');
13321 	if (sep) {
13322 		mod = find_attach_module(obj, pattern);
13323 		if (!mod) {
13324 			err = -EINVAL;
13325 			goto cleanup;
13326 		}
13327 		btf = mod->btf;
13328 		pattern = sep + 1;
13329 	} else {
13330 		/* Program is loaded for kernel module. */
13331 		if (prog->attach_btf_obj_fd) {
13332 			err = -EINVAL;
13333 			goto cleanup;
13334 		}
13335 		btf = obj->btf_vmlinux;
13336 	}
13337 
13338 	err = collect_btf_func_ids_by_glob(btf, pattern, ids);
13339 
13340 cleanup:
13341 	bpf_object_cleanup_btf(obj);
13342 	return err;
13343 }
13344 
13345 struct bpf_link *
13346 bpf_program__attach_tracing_multi(const struct bpf_program *prog, const char *pattern,
13347 				  const struct bpf_tracing_multi_opts *opts)
13348 {
13349 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
13350 	int prog_fd, link_fd, err, cnt;
13351 	__u32 *free_ids = NULL;
13352 	struct bpf_link *link;
13353 	const __u64 *cookies;
13354 	const __u32 *ids;
13355 
13356 	if (!OPTS_VALID(opts, bpf_tracing_multi_opts))
13357 		return libbpf_err_ptr(-EINVAL);
13358 
13359 	prog_fd = bpf_program__fd(prog);
13360 	if (prog_fd < 0) {
13361 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
13362 			prog->name);
13363 		return libbpf_err_ptr(-EINVAL);
13364 	}
13365 
13366 	cnt = OPTS_GET(opts, cnt, 0);
13367 	ids = OPTS_GET(opts, ids, NULL);
13368 	cookies = OPTS_GET(opts, cookies, NULL);
13369 
13370 	if (!!ids != !!cnt)
13371 		return libbpf_err_ptr(-EINVAL);
13372 	if (pattern && (ids || cookies))
13373 		return libbpf_err_ptr(-EINVAL);
13374 	if (!pattern && !ids)
13375 		return libbpf_err_ptr(-EINVAL);
13376 
13377 	if (pattern) {
13378 		cnt = collect_func_ids_by_glob(prog, pattern, &free_ids);
13379 		if (cnt < 0)
13380 			return libbpf_err_ptr(cnt);
13381 		if (cnt == 0)
13382 			return libbpf_err_ptr(-EINVAL);
13383 		ids = (const __u32 *) free_ids;
13384 	}
13385 
13386 	lopts.tracing_multi.ids = ids;
13387 	lopts.tracing_multi.cookies = cookies;
13388 	lopts.tracing_multi.cnt = cnt;
13389 
13390 	link = calloc(1, sizeof(*link));
13391 	if (!link) {
13392 		err = -ENOMEM;
13393 		goto error;
13394 	}
13395 	link->detach = &bpf_link__detach_fd;
13396 
13397 	link_fd = bpf_link_create(prog_fd, 0, prog->expected_attach_type, &lopts);
13398 	if (link_fd < 0) {
13399 		err = -errno;
13400 		pr_warn("prog '%s': failed to attach: %s\n", prog->name, errstr(err));
13401 		goto error;
13402 	}
13403 	link->fd = link_fd;
13404 	free(free_ids);
13405 	return link;
13406 
13407 error:
13408 	free(link);
13409 	free(free_ids);
13410 	return libbpf_err_ptr(err);
13411 }
13412 
13413 static int attach_tracing_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
13414 {
13415 	static const char *const prefixes[] = {
13416 		"fentry.multi",
13417 		"fexit.multi",
13418 		"fsession.multi",
13419 		"fentry.multi.s",
13420 		"fexit.multi.s",
13421 		"fsession.multi.s",
13422 	};
13423 	const char *spec = NULL;
13424 	char *pattern;
13425 	size_t i;
13426 	int n;
13427 
13428 	*link = NULL;
13429 
13430 	for (i = 0; i < ARRAY_SIZE(prefixes); i++) {
13431 		size_t pfx_len;
13432 
13433 		if (!str_has_pfx(prog->sec_name, prefixes[i]))
13434 			continue;
13435 
13436 		pfx_len = strlen(prefixes[i]);
13437 		/* no auto-attach case of, e.g., SEC("fentry.multi") */
13438 		if (prog->sec_name[pfx_len] == '\0')
13439 			return 0;
13440 
13441 		if (prog->sec_name[pfx_len] != '/')
13442 			continue;
13443 
13444 		spec = prog->sec_name + pfx_len + 1;
13445 		break;
13446 	}
13447 
13448 	if (!spec) {
13449 		pr_warn("prog '%s': invalid section name '%s'\n",
13450 			prog->name, prog->sec_name);
13451 		return -EINVAL;
13452 	}
13453 
13454 	n = sscanf(spec, "%m[a-zA-Z0-9_.*?:]", &pattern);
13455 	if (n < 1) {
13456 		pr_warn("tracing multi pattern is invalid: %s\n", spec);
13457 		return -EINVAL;
13458 	}
13459 
13460 	*link = bpf_program__attach_tracing_multi(prog, pattern, NULL);
13461 	free(pattern);
13462 	return libbpf_get_error(*link);
13463 }
13464 
13465 static inline int add_uprobe_event_legacy(const char *probe_name, bool retprobe,
13466 					  const char *binary_path, size_t offset)
13467 {
13468 	return append_to_file(tracefs_uprobe_events(), "%c:%s/%s %s:0x%zx",
13469 			      retprobe ? 'r' : 'p',
13470 			      retprobe ? "uretprobes" : "uprobes",
13471 			      probe_name, binary_path, offset);
13472 }
13473 
13474 static inline int remove_uprobe_event_legacy(const char *probe_name, bool retprobe)
13475 {
13476 	return append_to_file(tracefs_uprobe_events(), "-:%s/%s",
13477 			      retprobe ? "uretprobes" : "uprobes", probe_name);
13478 }
13479 
13480 static int determine_uprobe_perf_type_legacy(const char *probe_name, bool retprobe)
13481 {
13482 	char file[512];
13483 
13484 	snprintf(file, sizeof(file), "%s/events/%s/%s/id",
13485 		 tracefs_path(), retprobe ? "uretprobes" : "uprobes", probe_name);
13486 
13487 	return parse_uint_from_file(file, "%d\n");
13488 }
13489 
13490 static int perf_event_uprobe_open_legacy(const char *probe_name, bool retprobe,
13491 					 const char *binary_path, size_t offset, int pid)
13492 {
13493 	const size_t attr_sz = sizeof(struct perf_event_attr);
13494 	struct perf_event_attr attr;
13495 	int type, pfd, err;
13496 
13497 	err = add_uprobe_event_legacy(probe_name, retprobe, binary_path, offset);
13498 	if (err < 0) {
13499 		pr_warn("failed to add legacy uprobe event for %s:0x%zx: %s\n",
13500 			binary_path, (size_t)offset, errstr(err));
13501 		return err;
13502 	}
13503 	type = determine_uprobe_perf_type_legacy(probe_name, retprobe);
13504 	if (type < 0) {
13505 		err = type;
13506 		pr_warn("failed to determine legacy uprobe event id for %s:0x%zx: %s\n",
13507 			binary_path, offset, errstr(err));
13508 		goto err_clean_legacy;
13509 	}
13510 
13511 	memset(&attr, 0, attr_sz);
13512 	attr.size = attr_sz;
13513 	attr.config = type;
13514 	attr.type = PERF_TYPE_TRACEPOINT;
13515 
13516 	pfd = syscall(__NR_perf_event_open, &attr,
13517 		      pid < 0 ? -1 : pid, /* pid */
13518 		      pid == -1 ? 0 : -1, /* cpu */
13519 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
13520 	if (pfd < 0) {
13521 		err = -errno;
13522 		pr_warn("legacy uprobe perf_event_open() failed: %s\n", errstr(err));
13523 		goto err_clean_legacy;
13524 	}
13525 	return pfd;
13526 
13527 err_clean_legacy:
13528 	/* Clear the newly added legacy uprobe_event */
13529 	remove_uprobe_event_legacy(probe_name, retprobe);
13530 	return err;
13531 }
13532 
13533 /* Find offset of function name in archive specified by path. Currently
13534  * supported are .zip files that do not compress their contents, as used on
13535  * Android in the form of APKs, for example. "file_name" is the name of the ELF
13536  * file inside the archive. "func_name" matches symbol name or name@@LIB for
13537  * library functions.
13538  *
13539  * An overview of the APK format specifically provided here:
13540  * https://en.wikipedia.org/w/index.php?title=Apk_(file_format)&oldid=1139099120#Package_contents
13541  */
13542 static long elf_find_func_offset_from_archive(const char *archive_path, const char *file_name,
13543 					      const char *func_name)
13544 {
13545 	struct zip_archive *archive;
13546 	struct zip_entry entry;
13547 	long ret;
13548 	Elf *elf;
13549 
13550 	archive = zip_archive_open(archive_path);
13551 	if (IS_ERR(archive)) {
13552 		ret = PTR_ERR(archive);
13553 		pr_warn("zip: failed to open %s: %ld\n", archive_path, ret);
13554 		return ret;
13555 	}
13556 
13557 	ret = zip_archive_find_entry(archive, file_name, &entry);
13558 	if (ret) {
13559 		pr_warn("zip: could not find archive member %s in %s: %ld\n", file_name,
13560 			archive_path, ret);
13561 		goto out;
13562 	}
13563 	pr_debug("zip: found entry for %s in %s at 0x%lx\n", file_name, archive_path,
13564 		 (unsigned long)entry.data_offset);
13565 
13566 	if (entry.compression) {
13567 		pr_warn("zip: entry %s of %s is compressed and cannot be handled\n", file_name,
13568 			archive_path);
13569 		ret = -LIBBPF_ERRNO__FORMAT;
13570 		goto out;
13571 	}
13572 
13573 	elf = elf_memory((void *)entry.data, entry.data_length);
13574 	if (!elf) {
13575 		pr_warn("elf: could not read elf file %s from %s: %s\n", file_name, archive_path,
13576 			elf_errmsg(-1));
13577 		ret = -LIBBPF_ERRNO__LIBELF;
13578 		goto out;
13579 	}
13580 
13581 	ret = elf_find_func_offset(elf, file_name, func_name);
13582 	if (ret > 0) {
13583 		pr_debug("elf: symbol address match for %s of %s in %s: 0x%x + 0x%lx = 0x%lx\n",
13584 			 func_name, file_name, archive_path, entry.data_offset, (unsigned long)ret,
13585 			 (unsigned long)(ret + entry.data_offset));
13586 		ret += entry.data_offset;
13587 	}
13588 	elf_end(elf);
13589 
13590 out:
13591 	zip_archive_close(archive);
13592 	return ret;
13593 }
13594 
13595 static const char *arch_specific_lib_paths(void)
13596 {
13597 	/*
13598 	 * Based on https://packages.debian.org/sid/libc6.
13599 	 *
13600 	 * Assume that the traced program is built for the same architecture
13601 	 * as libbpf, which should cover the vast majority of cases.
13602 	 */
13603 #if defined(__x86_64__)
13604 	return "/lib/x86_64-linux-gnu";
13605 #elif defined(__i386__)
13606 	return "/lib/i386-linux-gnu";
13607 #elif defined(__s390x__)
13608 	return "/lib/s390x-linux-gnu";
13609 #elif defined(__arm__) && defined(__SOFTFP__)
13610 	return "/lib/arm-linux-gnueabi";
13611 #elif defined(__arm__) && !defined(__SOFTFP__)
13612 	return "/lib/arm-linux-gnueabihf";
13613 #elif defined(__aarch64__)
13614 	return "/lib/aarch64-linux-gnu";
13615 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 64
13616 	return "/lib/mips64el-linux-gnuabi64";
13617 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 32
13618 	return "/lib/mipsel-linux-gnu";
13619 #elif defined(__powerpc64__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
13620 	return "/lib/powerpc64le-linux-gnu";
13621 #elif defined(__sparc__) && defined(__arch64__)
13622 	return "/lib/sparc64-linux-gnu";
13623 #elif defined(__riscv) && __riscv_xlen == 64
13624 	return "/lib/riscv64-linux-gnu";
13625 #else
13626 	return NULL;
13627 #endif
13628 }
13629 
13630 /* Get full path to program/shared library. */
13631 static int resolve_full_path(const char *file, char *result, size_t result_sz)
13632 {
13633 	const char *search_paths[4] = {};
13634 	int i, perm;
13635 
13636 	if (str_has_sfx(file, ".so") || strstr(file, ".so.")) {
13637 		search_paths[0] = getenv("LD_LIBRARY_PATH");
13638 		search_paths[1] = "/usr/lib64:/usr/lib";
13639 		search_paths[2] = arch_specific_lib_paths();
13640 		search_paths[3] = "/lib64:/lib";
13641 		perm = R_OK;
13642 	} else {
13643 		search_paths[0] = getenv("PATH");
13644 		search_paths[1] = "/usr/bin:/usr/sbin";
13645 		perm = R_OK | X_OK;
13646 	}
13647 
13648 	for (i = 0; i < ARRAY_SIZE(search_paths); i++) {
13649 		const char *s;
13650 
13651 		if (!search_paths[i])
13652 			continue;
13653 		for (s = search_paths[i]; s != NULL; s = strchr(s, ':')) {
13654 			const char *next_path;
13655 			int seg_len;
13656 
13657 			if (s[0] == ':')
13658 				s++;
13659 			next_path = strchr(s, ':');
13660 			seg_len = next_path ? next_path - s : strlen(s);
13661 			if (!seg_len)
13662 				continue;
13663 			snprintf(result, result_sz, "%.*s/%s", seg_len, s, file);
13664 			/* ensure it has required permissions */
13665 			if (faccessat(AT_FDCWD, result, perm, AT_EACCESS) < 0)
13666 				continue;
13667 			pr_debug("resolved '%s' to '%s'\n", file, result);
13668 			return 0;
13669 		}
13670 	}
13671 	return -ENOENT;
13672 }
13673 
13674 struct bpf_link *
13675 bpf_program__attach_uprobe_multi(const struct bpf_program *prog,
13676 				 pid_t pid,
13677 				 const char *path,
13678 				 const char *func_pattern,
13679 				 const struct bpf_uprobe_multi_opts *opts)
13680 {
13681 	const unsigned long *ref_ctr_offsets = NULL, *offsets = NULL;
13682 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
13683 	unsigned long *resolved_offsets = NULL;
13684 	enum bpf_attach_type attach_type;
13685 	int err = 0, link_fd, prog_fd;
13686 	struct bpf_link *link = NULL;
13687 	char full_path[PATH_MAX];
13688 	bool retprobe, session;
13689 	const __u64 *cookies;
13690 	const char **syms;
13691 	size_t cnt;
13692 
13693 	if (!OPTS_VALID(opts, bpf_uprobe_multi_opts))
13694 		return libbpf_err_ptr(-EINVAL);
13695 
13696 	prog_fd = bpf_program__fd(prog);
13697 	if (prog_fd < 0) {
13698 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
13699 			prog->name);
13700 		return libbpf_err_ptr(-EINVAL);
13701 	}
13702 
13703 	syms = OPTS_GET(opts, syms, NULL);
13704 	offsets = OPTS_GET(opts, offsets, NULL);
13705 	ref_ctr_offsets = OPTS_GET(opts, ref_ctr_offsets, NULL);
13706 	cookies = OPTS_GET(opts, cookies, NULL);
13707 	cnt = OPTS_GET(opts, cnt, 0);
13708 	retprobe = OPTS_GET(opts, retprobe, false);
13709 	session  = OPTS_GET(opts, session, false);
13710 
13711 	/*
13712 	 * User can specify 2 mutually exclusive set of inputs:
13713 	 *
13714 	 * 1) use only path/func_pattern/pid arguments
13715 	 *
13716 	 * 2) use path/pid with allowed combinations of:
13717 	 *    syms/offsets/ref_ctr_offsets/cookies/cnt
13718 	 *
13719 	 *    - syms and offsets are mutually exclusive
13720 	 *    - ref_ctr_offsets and cookies are optional
13721 	 *
13722 	 * Any other usage results in error.
13723 	 */
13724 
13725 	if (!path)
13726 		return libbpf_err_ptr(-EINVAL);
13727 	if (!func_pattern && cnt == 0)
13728 		return libbpf_err_ptr(-EINVAL);
13729 
13730 	if (func_pattern) {
13731 		if (syms || offsets || ref_ctr_offsets || cookies || cnt)
13732 			return libbpf_err_ptr(-EINVAL);
13733 	} else {
13734 		if (!!syms == !!offsets)
13735 			return libbpf_err_ptr(-EINVAL);
13736 	}
13737 
13738 	if (retprobe && session)
13739 		return libbpf_err_ptr(-EINVAL);
13740 
13741 	if (func_pattern) {
13742 		if (!strchr(path, '/')) {
13743 			err = resolve_full_path(path, full_path, sizeof(full_path));
13744 			if (err) {
13745 				pr_warn("prog '%s': failed to resolve full path for '%s': %s\n",
13746 					prog->name, path, errstr(err));
13747 				return libbpf_err_ptr(err);
13748 			}
13749 			path = full_path;
13750 		}
13751 
13752 		err = elf_resolve_pattern_offsets(path, func_pattern,
13753 						  &resolved_offsets, &cnt);
13754 		if (err < 0)
13755 			return libbpf_err_ptr(err);
13756 		offsets = resolved_offsets;
13757 	} else if (syms) {
13758 		err = elf_resolve_syms_offsets(path, cnt, syms, &resolved_offsets, STT_FUNC);
13759 		if (err < 0)
13760 			return libbpf_err_ptr(err);
13761 		offsets = resolved_offsets;
13762 	}
13763 
13764 	attach_type = session ? BPF_TRACE_UPROBE_SESSION : BPF_TRACE_UPROBE_MULTI;
13765 
13766 	lopts.uprobe_multi.path = path;
13767 	lopts.uprobe_multi.offsets = offsets;
13768 	lopts.uprobe_multi.ref_ctr_offsets = ref_ctr_offsets;
13769 	lopts.uprobe_multi.cookies = cookies;
13770 	lopts.uprobe_multi.cnt = cnt;
13771 	lopts.uprobe_multi.flags = retprobe ? BPF_F_UPROBE_MULTI_RETURN : 0;
13772 
13773 	if (pid == 0)
13774 		pid = getpid();
13775 	if (pid > 0)
13776 		lopts.uprobe_multi.pid = pid;
13777 
13778 	link = calloc(1, sizeof(*link));
13779 	if (!link) {
13780 		err = -ENOMEM;
13781 		goto error;
13782 	}
13783 	link->detach = &bpf_link__detach_fd;
13784 
13785 	link_fd = bpf_link_create(prog_fd, 0, attach_type, &lopts);
13786 	if (link_fd < 0) {
13787 		err = -errno;
13788 		pr_warn("prog '%s': failed to attach multi-uprobe: %s\n",
13789 			prog->name, errstr(err));
13790 		goto error;
13791 	}
13792 	link->fd = link_fd;
13793 	free(resolved_offsets);
13794 	return link;
13795 
13796 error:
13797 	free(resolved_offsets);
13798 	free(link);
13799 	return libbpf_err_ptr(err);
13800 }
13801 
13802 LIBBPF_API struct bpf_link *
13803 bpf_program__attach_uprobe_opts(const struct bpf_program *prog, pid_t pid,
13804 				const char *binary_path, size_t func_offset,
13805 				const struct bpf_uprobe_opts *opts)
13806 {
13807 	const char *archive_path = NULL, *archive_sep = NULL;
13808 	char *legacy_probe = NULL;
13809 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
13810 	enum probe_attach_mode attach_mode;
13811 	char full_path[PATH_MAX];
13812 	struct bpf_link *link;
13813 	size_t ref_ctr_off;
13814 	int pfd, err;
13815 	bool retprobe, legacy;
13816 	const char *func_name;
13817 
13818 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
13819 		return libbpf_err_ptr(-EINVAL);
13820 
13821 	attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
13822 	retprobe = OPTS_GET(opts, retprobe, false);
13823 	ref_ctr_off = OPTS_GET(opts, ref_ctr_offset, 0);
13824 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
13825 
13826 	if (!binary_path)
13827 		return libbpf_err_ptr(-EINVAL);
13828 
13829 	/* Check if "binary_path" refers to an archive. */
13830 	archive_sep = strstr(binary_path, "!/");
13831 	if (archive_sep) {
13832 		full_path[0] = '\0';
13833 		libbpf_strlcpy(full_path, binary_path,
13834 			       min(sizeof(full_path), (size_t)(archive_sep - binary_path + 1)));
13835 		archive_path = full_path;
13836 		binary_path = archive_sep + 2;
13837 	} else if (!strchr(binary_path, '/')) {
13838 		err = resolve_full_path(binary_path, full_path, sizeof(full_path));
13839 		if (err) {
13840 			pr_warn("prog '%s': failed to resolve full path for '%s': %s\n",
13841 				prog->name, binary_path, errstr(err));
13842 			return libbpf_err_ptr(err);
13843 		}
13844 		binary_path = full_path;
13845 	}
13846 	func_name = OPTS_GET(opts, func_name, NULL);
13847 	if (func_name) {
13848 		long sym_off;
13849 
13850 		if (archive_path) {
13851 			sym_off = elf_find_func_offset_from_archive(archive_path, binary_path,
13852 								    func_name);
13853 			binary_path = archive_path;
13854 		} else {
13855 			sym_off = elf_find_func_offset_from_file(binary_path, func_name);
13856 		}
13857 		if (sym_off < 0)
13858 			return libbpf_err_ptr(sym_off);
13859 		func_offset += sym_off;
13860 	}
13861 
13862 	legacy = determine_uprobe_perf_type() < 0;
13863 	switch (attach_mode) {
13864 	case PROBE_ATTACH_MODE_LEGACY:
13865 		legacy = true;
13866 		pe_opts.force_ioctl_attach = true;
13867 		break;
13868 	case PROBE_ATTACH_MODE_PERF:
13869 		if (legacy)
13870 			return libbpf_err_ptr(-ENOTSUP);
13871 		pe_opts.force_ioctl_attach = true;
13872 		break;
13873 	case PROBE_ATTACH_MODE_LINK:
13874 		if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
13875 			return libbpf_err_ptr(-ENOTSUP);
13876 		break;
13877 	case PROBE_ATTACH_MODE_DEFAULT:
13878 		break;
13879 	default:
13880 		return libbpf_err_ptr(-EINVAL);
13881 	}
13882 
13883 	if (!legacy) {
13884 		pfd = perf_event_open_probe(true /* uprobe */, retprobe, binary_path,
13885 					    func_offset, pid, ref_ctr_off);
13886 	} else {
13887 		char probe_name[MAX_EVENT_NAME_LEN];
13888 
13889 		if (ref_ctr_off)
13890 			return libbpf_err_ptr(-EINVAL);
13891 
13892 		gen_probe_legacy_event_name(probe_name, sizeof(probe_name),
13893 					    strrchr(binary_path, '/') ? : binary_path,
13894 					    func_offset);
13895 
13896 		legacy_probe = strdup(probe_name);
13897 		if (!legacy_probe)
13898 			return libbpf_err_ptr(-ENOMEM);
13899 
13900 		pfd = perf_event_uprobe_open_legacy(legacy_probe, retprobe,
13901 						    binary_path, func_offset, pid);
13902 	}
13903 	if (pfd < 0) {
13904 		err = pfd;
13905 		pr_warn("prog '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
13906 			prog->name, retprobe ? "uretprobe" : "uprobe",
13907 			binary_path, func_offset,
13908 			errstr(err));
13909 		goto err_out;
13910 	}
13911 
13912 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
13913 	err = libbpf_get_error(link);
13914 	if (err) {
13915 		close(pfd);
13916 		pr_warn("prog '%s': failed to attach to %s '%s:0x%zx': %s\n",
13917 			prog->name, retprobe ? "uretprobe" : "uprobe",
13918 			binary_path, func_offset,
13919 			errstr(err));
13920 		goto err_clean_legacy;
13921 	}
13922 	if (legacy) {
13923 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
13924 
13925 		perf_link->legacy_probe_name = legacy_probe;
13926 		perf_link->legacy_is_kprobe = false;
13927 		perf_link->legacy_is_retprobe = retprobe;
13928 	}
13929 	return link;
13930 
13931 err_clean_legacy:
13932 	if (legacy)
13933 		remove_uprobe_event_legacy(legacy_probe, retprobe);
13934 err_out:
13935 	free(legacy_probe);
13936 	return libbpf_err_ptr(err);
13937 }
13938 
13939 /* Format of u[ret]probe section definition supporting auto-attach:
13940  * u[ret]probe/binary:function[+offset]
13941  *
13942  * binary can be an absolute/relative path or a filename; the latter is resolved to a
13943  * full binary path via bpf_program__attach_uprobe_opts.
13944  *
13945  * Specifying uprobe+ ensures we carry out strict matching; either "uprobe" must be
13946  * specified (and auto-attach is not possible) or the above format is specified for
13947  * auto-attach.
13948  */
13949 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
13950 {
13951 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts);
13952 	char *probe_type = NULL, *binary_path = NULL, *func_name = NULL, *func_off;
13953 	int n, c, ret = -EINVAL;
13954 	long offset = 0;
13955 
13956 	*link = NULL;
13957 
13958 	n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[^\n]",
13959 		   &probe_type, &binary_path, &func_name);
13960 	switch (n) {
13961 	case 1:
13962 		/* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
13963 		ret = 0;
13964 		break;
13965 	case 2:
13966 		pr_warn("prog '%s': section '%s' missing ':function[+offset]' specification\n",
13967 			prog->name, prog->sec_name);
13968 		break;
13969 	case 3:
13970 		/* check if user specifies `+offset`, if yes, this should be
13971 		 * the last part of the string, make sure sscanf read to EOL
13972 		 */
13973 		func_off = strrchr(func_name, '+');
13974 		if (func_off) {
13975 			n = sscanf(func_off, "+%li%n", &offset, &c);
13976 			if (n == 1 && *(func_off + c) == '\0')
13977 				func_off[0] = '\0';
13978 			else
13979 				offset = 0;
13980 		}
13981 		opts.retprobe = strcmp(probe_type, "uretprobe") == 0 ||
13982 				strcmp(probe_type, "uretprobe.s") == 0;
13983 		if (opts.retprobe && offset != 0) {
13984 			pr_warn("prog '%s': uretprobes do not support offset specification\n",
13985 				prog->name);
13986 			break;
13987 		}
13988 		opts.func_name = func_name;
13989 		*link = bpf_program__attach_uprobe_opts(prog, -1, binary_path, offset, &opts);
13990 		ret = libbpf_get_error(*link);
13991 		break;
13992 	default:
13993 		pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
13994 			prog->sec_name);
13995 		break;
13996 	}
13997 	free(probe_type);
13998 	free(binary_path);
13999 	free(func_name);
14000 
14001 	return ret;
14002 }
14003 
14004 struct bpf_link *bpf_program__attach_uprobe(const struct bpf_program *prog,
14005 					    bool retprobe, pid_t pid,
14006 					    const char *binary_path,
14007 					    size_t func_offset)
14008 {
14009 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts, .retprobe = retprobe);
14010 
14011 	return bpf_program__attach_uprobe_opts(prog, pid, binary_path, func_offset, &opts);
14012 }
14013 
14014 struct bpf_link *bpf_program__attach_usdt(const struct bpf_program *prog,
14015 					  pid_t pid, const char *binary_path,
14016 					  const char *usdt_provider, const char *usdt_name,
14017 					  const struct bpf_usdt_opts *opts)
14018 {
14019 	char resolved_path[512];
14020 	struct bpf_object *obj = prog->obj;
14021 	struct bpf_link *link;
14022 	__u64 usdt_cookie;
14023 	int err;
14024 
14025 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
14026 		return libbpf_err_ptr(-EINVAL);
14027 
14028 	if (bpf_program__fd(prog) < 0) {
14029 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
14030 			prog->name);
14031 		return libbpf_err_ptr(-EINVAL);
14032 	}
14033 
14034 	if (!binary_path)
14035 		return libbpf_err_ptr(-EINVAL);
14036 
14037 	if (!strchr(binary_path, '/')) {
14038 		err = resolve_full_path(binary_path, resolved_path, sizeof(resolved_path));
14039 		if (err) {
14040 			pr_warn("prog '%s': failed to resolve full path for '%s': %s\n",
14041 				prog->name, binary_path, errstr(err));
14042 			return libbpf_err_ptr(err);
14043 		}
14044 		binary_path = resolved_path;
14045 	}
14046 
14047 	/* USDT manager is instantiated lazily on first USDT attach. It will
14048 	 * be destroyed together with BPF object in bpf_object__close().
14049 	 */
14050 	if (IS_ERR(obj->usdt_man))
14051 		return libbpf_ptr(obj->usdt_man);
14052 	if (!obj->usdt_man) {
14053 		obj->usdt_man = usdt_manager_new(obj);
14054 		if (IS_ERR(obj->usdt_man))
14055 			return libbpf_ptr(obj->usdt_man);
14056 	}
14057 
14058 	usdt_cookie = OPTS_GET(opts, usdt_cookie, 0);
14059 	link = usdt_manager_attach_usdt(obj->usdt_man, prog, pid, binary_path,
14060 					usdt_provider, usdt_name, usdt_cookie);
14061 	err = libbpf_get_error(link);
14062 	if (err)
14063 		return libbpf_err_ptr(err);
14064 	return link;
14065 }
14066 
14067 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link)
14068 {
14069 	char *path = NULL, *provider = NULL, *name = NULL;
14070 	const char *sec_name;
14071 	int n, err;
14072 
14073 	sec_name = bpf_program__section_name(prog);
14074 	if (strcmp(sec_name, "usdt") == 0) {
14075 		/* no auto-attach for just SEC("usdt") */
14076 		*link = NULL;
14077 		return 0;
14078 	}
14079 
14080 	n = sscanf(sec_name, "usdt/%m[^:]:%m[^:]:%m[^:]", &path, &provider, &name);
14081 	if (n != 3) {
14082 		pr_warn("invalid section '%s', expected SEC(\"usdt/<path>:<provider>:<name>\")\n",
14083 			sec_name);
14084 		err = -EINVAL;
14085 	} else {
14086 		*link = bpf_program__attach_usdt(prog, -1 /* any process */, path,
14087 						 provider, name, NULL);
14088 		err = libbpf_get_error(*link);
14089 	}
14090 	free(path);
14091 	free(provider);
14092 	free(name);
14093 	return err;
14094 }
14095 
14096 static int determine_tracepoint_id(const char *tp_category,
14097 				   const char *tp_name)
14098 {
14099 	char file[PATH_MAX];
14100 	int ret;
14101 
14102 	ret = snprintf(file, sizeof(file), "%s/events/%s/%s/id",
14103 		       tracefs_path(), tp_category, tp_name);
14104 	if (ret < 0)
14105 		return -errno;
14106 	if (ret >= sizeof(file)) {
14107 		pr_debug("tracepoint %s/%s path is too long\n",
14108 			 tp_category, tp_name);
14109 		return -E2BIG;
14110 	}
14111 	return parse_uint_from_file(file, "%d\n");
14112 }
14113 
14114 static int perf_event_open_tracepoint(const char *tp_category,
14115 				      const char *tp_name)
14116 {
14117 	const size_t attr_sz = sizeof(struct perf_event_attr);
14118 	struct perf_event_attr attr;
14119 	int tp_id, pfd, err;
14120 
14121 	tp_id = determine_tracepoint_id(tp_category, tp_name);
14122 	if (tp_id < 0) {
14123 		pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
14124 			tp_category, tp_name,
14125 			errstr(tp_id));
14126 		return tp_id;
14127 	}
14128 
14129 	memset(&attr, 0, attr_sz);
14130 	attr.type = PERF_TYPE_TRACEPOINT;
14131 	attr.size = attr_sz;
14132 	attr.config = tp_id;
14133 
14134 	pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
14135 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
14136 	if (pfd < 0) {
14137 		err = -errno;
14138 		pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
14139 			tp_category, tp_name,
14140 			errstr(err));
14141 		return err;
14142 	}
14143 	return pfd;
14144 }
14145 
14146 struct bpf_link *bpf_program__attach_tracepoint_opts(const struct bpf_program *prog,
14147 						     const char *tp_category,
14148 						     const char *tp_name,
14149 						     const struct bpf_tracepoint_opts *opts)
14150 {
14151 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
14152 	struct bpf_link *link;
14153 	int pfd, err;
14154 
14155 	if (!OPTS_VALID(opts, bpf_tracepoint_opts))
14156 		return libbpf_err_ptr(-EINVAL);
14157 
14158 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
14159 
14160 	pfd = perf_event_open_tracepoint(tp_category, tp_name);
14161 	if (pfd < 0) {
14162 		pr_warn("prog '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
14163 			prog->name, tp_category, tp_name,
14164 			errstr(pfd));
14165 		return libbpf_err_ptr(pfd);
14166 	}
14167 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
14168 	err = libbpf_get_error(link);
14169 	if (err) {
14170 		close(pfd);
14171 		pr_warn("prog '%s': failed to attach to tracepoint '%s/%s': %s\n",
14172 			prog->name, tp_category, tp_name,
14173 			errstr(err));
14174 		return libbpf_err_ptr(err);
14175 	}
14176 	return link;
14177 }
14178 
14179 struct bpf_link *bpf_program__attach_tracepoint(const struct bpf_program *prog,
14180 						const char *tp_category,
14181 						const char *tp_name)
14182 {
14183 	return bpf_program__attach_tracepoint_opts(prog, tp_category, tp_name, NULL);
14184 }
14185 
14186 /*
14187  * Match section name against a prefix array. Returns pointer past
14188  * "prefix/" on match, empty string for bare sections (exact prefix
14189  * match), or NULL if no prefix matches.
14190  */
14191 static const char *sec_name_match_prefix(const char *sec_name,
14192 					 const char *const *prefixes,
14193 					 size_t n)
14194 {
14195 	size_t i;
14196 
14197 	for (i = 0; i < n; i++) {
14198 		size_t pfx_len;
14199 
14200 		if (!str_has_pfx(sec_name, prefixes[i]))
14201 			continue;
14202 
14203 		pfx_len = strlen(prefixes[i]);
14204 		if (sec_name[pfx_len] == '\0')
14205 			return sec_name + pfx_len;
14206 
14207 		if (sec_name[pfx_len] != '/' || sec_name[pfx_len + 1] == '\0')
14208 			continue;
14209 
14210 		return sec_name + pfx_len + 1;
14211 	}
14212 	return NULL;
14213 }
14214 
14215 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
14216 {
14217 	static const char *const prefixes[] = {
14218 		"tp.s",
14219 		"tp",
14220 		"tracepoint.s",
14221 		"tracepoint",
14222 	};
14223 	char *sec_name, *tp_cat, *tp_name;
14224 	const char *match;
14225 
14226 	*link = NULL;
14227 
14228 	match = sec_name_match_prefix(prog->sec_name, prefixes, ARRAY_SIZE(prefixes));
14229 	if (!match) {
14230 		pr_warn("prog '%s': invalid section name '%s'\n", prog->name, prog->sec_name);
14231 		return -EINVAL;
14232 	}
14233 	if (!match[0]) /* bare section name no autoattach */
14234 		return 0;
14235 
14236 	sec_name = strdup(prog->sec_name);
14237 	if (!sec_name)
14238 		return -ENOMEM;
14239 
14240 	tp_cat = sec_name + (match - prog->sec_name);
14241 	tp_name = strchr(tp_cat, '/');
14242 	if (!tp_name) {
14243 		free(sec_name);
14244 		return -EINVAL;
14245 	}
14246 	*tp_name = '\0';
14247 	tp_name++;
14248 
14249 	*link = bpf_program__attach_tracepoint(prog, tp_cat, tp_name);
14250 	free(sec_name);
14251 	return libbpf_get_error(*link);
14252 }
14253 
14254 struct bpf_link *
14255 bpf_program__attach_raw_tracepoint_opts(const struct bpf_program *prog,
14256 					const char *tp_name,
14257 					struct bpf_raw_tracepoint_opts *opts)
14258 {
14259 	LIBBPF_OPTS(bpf_raw_tp_opts, raw_opts);
14260 	struct bpf_link *link;
14261 	int prog_fd, pfd;
14262 
14263 	if (!OPTS_VALID(opts, bpf_raw_tracepoint_opts))
14264 		return libbpf_err_ptr(-EINVAL);
14265 
14266 	prog_fd = bpf_program__fd(prog);
14267 	if (prog_fd < 0) {
14268 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
14269 		return libbpf_err_ptr(-EINVAL);
14270 	}
14271 
14272 	link = calloc(1, sizeof(*link));
14273 	if (!link)
14274 		return libbpf_err_ptr(-ENOMEM);
14275 	link->detach = &bpf_link__detach_fd;
14276 
14277 	raw_opts.tp_name = tp_name;
14278 	raw_opts.cookie = OPTS_GET(opts, cookie, 0);
14279 	pfd = bpf_raw_tracepoint_open_opts(prog_fd, &raw_opts);
14280 	if (pfd < 0) {
14281 		pfd = -errno;
14282 		free(link);
14283 		pr_warn("prog '%s': failed to attach to raw tracepoint '%s': %s\n",
14284 			prog->name, tp_name, errstr(pfd));
14285 		return libbpf_err_ptr(pfd);
14286 	}
14287 	link->fd = pfd;
14288 	return link;
14289 }
14290 
14291 struct bpf_link *bpf_program__attach_raw_tracepoint(const struct bpf_program *prog,
14292 						    const char *tp_name)
14293 {
14294 	return bpf_program__attach_raw_tracepoint_opts(prog, tp_name, NULL);
14295 }
14296 
14297 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
14298 {
14299 	static const char *const prefixes[] = {
14300 		"raw_tp",
14301 		"raw_tracepoint",
14302 		"raw_tp.w",
14303 		"raw_tracepoint.w",
14304 		"raw_tp.s",
14305 		"raw_tracepoint.s",
14306 	};
14307 	const char *match;
14308 
14309 	*link = NULL;
14310 
14311 	match = sec_name_match_prefix(prog->sec_name, prefixes, ARRAY_SIZE(prefixes));
14312 	if (!match) {
14313 		pr_warn("prog '%s': invalid section name '%s'\n", prog->name, prog->sec_name);
14314 		return -EINVAL;
14315 	}
14316 	if (!match[0])
14317 		return 0;
14318 
14319 	*link = bpf_program__attach_raw_tracepoint(prog, match);
14320 	return libbpf_get_error(*link);
14321 }
14322 
14323 /* Common logic for all BPF program types that attach to a btf_id */
14324 static struct bpf_link *bpf_program__attach_btf_id(const struct bpf_program *prog,
14325 						   const struct bpf_trace_opts *opts)
14326 {
14327 	LIBBPF_OPTS(bpf_link_create_opts, link_opts);
14328 	struct bpf_link *link;
14329 	int prog_fd, pfd;
14330 
14331 	if (!OPTS_VALID(opts, bpf_trace_opts))
14332 		return libbpf_err_ptr(-EINVAL);
14333 
14334 	prog_fd = bpf_program__fd(prog);
14335 	if (prog_fd < 0) {
14336 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
14337 		return libbpf_err_ptr(-EINVAL);
14338 	}
14339 
14340 	link = calloc(1, sizeof(*link));
14341 	if (!link)
14342 		return libbpf_err_ptr(-ENOMEM);
14343 	link->detach = &bpf_link__detach_fd;
14344 
14345 	/* libbpf is smart enough to redirect to BPF_RAW_TRACEPOINT_OPEN on old kernels */
14346 	link_opts.tracing.cookie = OPTS_GET(opts, cookie, 0);
14347 	pfd = bpf_link_create(prog_fd, 0, bpf_program__expected_attach_type(prog), &link_opts);
14348 	if (pfd < 0) {
14349 		pfd = -errno;
14350 		free(link);
14351 		pr_warn("prog '%s': failed to attach: %s\n",
14352 			prog->name, errstr(pfd));
14353 		return libbpf_err_ptr(pfd);
14354 	}
14355 	link->fd = pfd;
14356 	return link;
14357 }
14358 
14359 struct bpf_link *bpf_program__attach_trace(const struct bpf_program *prog)
14360 {
14361 	return bpf_program__attach_btf_id(prog, NULL);
14362 }
14363 
14364 struct bpf_link *bpf_program__attach_trace_opts(const struct bpf_program *prog,
14365 						const struct bpf_trace_opts *opts)
14366 {
14367 	return bpf_program__attach_btf_id(prog, opts);
14368 }
14369 
14370 struct bpf_link *bpf_program__attach_lsm(const struct bpf_program *prog)
14371 {
14372 	return bpf_program__attach_btf_id(prog, NULL);
14373 }
14374 
14375 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link)
14376 {
14377 	*link = bpf_program__attach_trace(prog);
14378 	return libbpf_get_error(*link);
14379 }
14380 
14381 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link)
14382 {
14383 	*link = bpf_program__attach_lsm(prog);
14384 	return libbpf_get_error(*link);
14385 }
14386 
14387 static struct bpf_link *
14388 bpf_program_attach_fd(const struct bpf_program *prog,
14389 		      int target_fd, const char *target_name,
14390 		      const struct bpf_link_create_opts *opts)
14391 {
14392 	enum bpf_attach_type attach_type;
14393 	struct bpf_link *link;
14394 	int prog_fd, link_fd;
14395 
14396 	prog_fd = bpf_program__fd(prog);
14397 	if (prog_fd < 0) {
14398 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
14399 		return libbpf_err_ptr(-EINVAL);
14400 	}
14401 
14402 	link = calloc(1, sizeof(*link));
14403 	if (!link)
14404 		return libbpf_err_ptr(-ENOMEM);
14405 	link->detach = &bpf_link__detach_fd;
14406 
14407 	attach_type = bpf_program__expected_attach_type(prog);
14408 	link_fd = bpf_link_create(prog_fd, target_fd, attach_type, opts);
14409 	if (link_fd < 0) {
14410 		link_fd = -errno;
14411 		free(link);
14412 		pr_warn("prog '%s': failed to attach to %s: %s\n",
14413 			prog->name, target_name,
14414 			errstr(link_fd));
14415 		return libbpf_err_ptr(link_fd);
14416 	}
14417 	link->fd = link_fd;
14418 	return link;
14419 }
14420 
14421 struct bpf_link *
14422 bpf_program__attach_cgroup(const struct bpf_program *prog, int cgroup_fd)
14423 {
14424 	return bpf_program_attach_fd(prog, cgroup_fd, "cgroup", NULL);
14425 }
14426 
14427 struct bpf_link *
14428 bpf_program__attach_netns(const struct bpf_program *prog, int netns_fd)
14429 {
14430 	return bpf_program_attach_fd(prog, netns_fd, "netns", NULL);
14431 }
14432 
14433 struct bpf_link *
14434 bpf_program__attach_sockmap(const struct bpf_program *prog, int map_fd)
14435 {
14436 	return bpf_program_attach_fd(prog, map_fd, "sockmap", NULL);
14437 }
14438 
14439 struct bpf_link *bpf_program__attach_xdp(const struct bpf_program *prog, int ifindex)
14440 {
14441 	/* target_fd/target_ifindex use the same field in LINK_CREATE */
14442 	return bpf_program_attach_fd(prog, ifindex, "xdp", NULL);
14443 }
14444 
14445 struct bpf_link *
14446 bpf_program__attach_cgroup_opts(const struct bpf_program *prog, int cgroup_fd,
14447 				const struct bpf_cgroup_opts *opts)
14448 {
14449 	LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
14450 	__u32 relative_id;
14451 	int relative_fd;
14452 
14453 	if (!OPTS_VALID(opts, bpf_cgroup_opts))
14454 		return libbpf_err_ptr(-EINVAL);
14455 
14456 	relative_id = OPTS_GET(opts, relative_id, 0);
14457 	relative_fd = OPTS_GET(opts, relative_fd, 0);
14458 
14459 	if (relative_fd && relative_id) {
14460 		pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
14461 			prog->name);
14462 		return libbpf_err_ptr(-EINVAL);
14463 	}
14464 
14465 	link_create_opts.cgroup.expected_revision = OPTS_GET(opts, expected_revision, 0);
14466 	link_create_opts.cgroup.relative_fd = relative_fd;
14467 	link_create_opts.cgroup.relative_id = relative_id;
14468 	link_create_opts.flags = OPTS_GET(opts, flags, 0);
14469 
14470 	return bpf_program_attach_fd(prog, cgroup_fd, "cgroup", &link_create_opts);
14471 }
14472 
14473 struct bpf_link *
14474 bpf_program__attach_tcx(const struct bpf_program *prog, int ifindex,
14475 			const struct bpf_tcx_opts *opts)
14476 {
14477 	LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
14478 	__u32 relative_id;
14479 	int relative_fd;
14480 
14481 	if (!OPTS_VALID(opts, bpf_tcx_opts))
14482 		return libbpf_err_ptr(-EINVAL);
14483 
14484 	relative_id = OPTS_GET(opts, relative_id, 0);
14485 	relative_fd = OPTS_GET(opts, relative_fd, 0);
14486 
14487 	/* validate we don't have unexpected combinations of non-zero fields */
14488 	if (!ifindex) {
14489 		pr_warn("prog '%s': target netdevice ifindex cannot be zero\n",
14490 			prog->name);
14491 		return libbpf_err_ptr(-EINVAL);
14492 	}
14493 	if (relative_fd && relative_id) {
14494 		pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
14495 			prog->name);
14496 		return libbpf_err_ptr(-EINVAL);
14497 	}
14498 
14499 	link_create_opts.tcx.expected_revision = OPTS_GET(opts, expected_revision, 0);
14500 	link_create_opts.tcx.relative_fd = relative_fd;
14501 	link_create_opts.tcx.relative_id = relative_id;
14502 	link_create_opts.flags = OPTS_GET(opts, flags, 0);
14503 
14504 	/* target_fd/target_ifindex use the same field in LINK_CREATE */
14505 	return bpf_program_attach_fd(prog, ifindex, "tcx", &link_create_opts);
14506 }
14507 
14508 struct bpf_link *
14509 bpf_program__attach_netkit(const struct bpf_program *prog, int ifindex,
14510 			   const struct bpf_netkit_opts *opts)
14511 {
14512 	LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
14513 	__u32 relative_id;
14514 	int relative_fd;
14515 
14516 	if (!OPTS_VALID(opts, bpf_netkit_opts))
14517 		return libbpf_err_ptr(-EINVAL);
14518 
14519 	relative_id = OPTS_GET(opts, relative_id, 0);
14520 	relative_fd = OPTS_GET(opts, relative_fd, 0);
14521 
14522 	/* validate we don't have unexpected combinations of non-zero fields */
14523 	if (!ifindex) {
14524 		pr_warn("prog '%s': target netdevice ifindex cannot be zero\n",
14525 			prog->name);
14526 		return libbpf_err_ptr(-EINVAL);
14527 	}
14528 	if (relative_fd && relative_id) {
14529 		pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
14530 			prog->name);
14531 		return libbpf_err_ptr(-EINVAL);
14532 	}
14533 
14534 	link_create_opts.netkit.expected_revision = OPTS_GET(opts, expected_revision, 0);
14535 	link_create_opts.netkit.relative_fd = relative_fd;
14536 	link_create_opts.netkit.relative_id = relative_id;
14537 	link_create_opts.flags = OPTS_GET(opts, flags, 0);
14538 
14539 	return bpf_program_attach_fd(prog, ifindex, "netkit", &link_create_opts);
14540 }
14541 
14542 struct bpf_link *bpf_program__attach_freplace(const struct bpf_program *prog,
14543 					      int target_fd,
14544 					      const char *attach_func_name)
14545 {
14546 	int btf_id;
14547 
14548 	if (!!target_fd != !!attach_func_name) {
14549 		pr_warn("prog '%s': supply none or both of target_fd and attach_func_name\n",
14550 			prog->name);
14551 		return libbpf_err_ptr(-EINVAL);
14552 	}
14553 
14554 	if (prog->type != BPF_PROG_TYPE_EXT) {
14555 		pr_warn("prog '%s': only BPF_PROG_TYPE_EXT can attach as freplace\n",
14556 			prog->name);
14557 		return libbpf_err_ptr(-EINVAL);
14558 	}
14559 
14560 	if (target_fd) {
14561 		LIBBPF_OPTS(bpf_link_create_opts, target_opts);
14562 
14563 		btf_id = libbpf_find_prog_btf_id(attach_func_name, target_fd, prog->obj->token_fd);
14564 		if (btf_id < 0)
14565 			return libbpf_err_ptr(btf_id);
14566 
14567 		target_opts.target_btf_id = btf_id;
14568 
14569 		return bpf_program_attach_fd(prog, target_fd, "freplace",
14570 					     &target_opts);
14571 	} else {
14572 		/* no target, so use raw_tracepoint_open for compatibility
14573 		 * with old kernels
14574 		 */
14575 		return bpf_program__attach_trace(prog);
14576 	}
14577 }
14578 
14579 struct bpf_link *
14580 bpf_program__attach_iter(const struct bpf_program *prog,
14581 			 const struct bpf_iter_attach_opts *opts)
14582 {
14583 	DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
14584 	struct bpf_link *link;
14585 	int prog_fd, link_fd;
14586 	__u32 target_fd = 0;
14587 
14588 	if (!OPTS_VALID(opts, bpf_iter_attach_opts))
14589 		return libbpf_err_ptr(-EINVAL);
14590 
14591 	link_create_opts.iter_info = OPTS_GET(opts, link_info, (void *)0);
14592 	link_create_opts.iter_info_len = OPTS_GET(opts, link_info_len, 0);
14593 
14594 	prog_fd = bpf_program__fd(prog);
14595 	if (prog_fd < 0) {
14596 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
14597 		return libbpf_err_ptr(-EINVAL);
14598 	}
14599 
14600 	link = calloc(1, sizeof(*link));
14601 	if (!link)
14602 		return libbpf_err_ptr(-ENOMEM);
14603 	link->detach = &bpf_link__detach_fd;
14604 
14605 	link_fd = bpf_link_create(prog_fd, target_fd, BPF_TRACE_ITER,
14606 				  &link_create_opts);
14607 	if (link_fd < 0) {
14608 		link_fd = -errno;
14609 		free(link);
14610 		pr_warn("prog '%s': failed to attach to iterator: %s\n",
14611 			prog->name, errstr(link_fd));
14612 		return libbpf_err_ptr(link_fd);
14613 	}
14614 	link->fd = link_fd;
14615 	return link;
14616 }
14617 
14618 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link)
14619 {
14620 	*link = bpf_program__attach_iter(prog, NULL);
14621 	return libbpf_get_error(*link);
14622 }
14623 
14624 struct bpf_link *bpf_program__attach_netfilter(const struct bpf_program *prog,
14625 					       const struct bpf_netfilter_opts *opts)
14626 {
14627 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
14628 	struct bpf_link *link;
14629 	int prog_fd, link_fd;
14630 
14631 	if (!OPTS_VALID(opts, bpf_netfilter_opts))
14632 		return libbpf_err_ptr(-EINVAL);
14633 
14634 	prog_fd = bpf_program__fd(prog);
14635 	if (prog_fd < 0) {
14636 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
14637 		return libbpf_err_ptr(-EINVAL);
14638 	}
14639 
14640 	link = calloc(1, sizeof(*link));
14641 	if (!link)
14642 		return libbpf_err_ptr(-ENOMEM);
14643 
14644 	link->detach = &bpf_link__detach_fd;
14645 
14646 	lopts.netfilter.pf = OPTS_GET(opts, pf, 0);
14647 	lopts.netfilter.hooknum = OPTS_GET(opts, hooknum, 0);
14648 	lopts.netfilter.priority = OPTS_GET(opts, priority, 0);
14649 	lopts.netfilter.flags = OPTS_GET(opts, flags, 0);
14650 
14651 	link_fd = bpf_link_create(prog_fd, 0, BPF_NETFILTER, &lopts);
14652 	if (link_fd < 0) {
14653 		link_fd = -errno;
14654 		free(link);
14655 		pr_warn("prog '%s': failed to attach to netfilter: %s\n",
14656 			prog->name, errstr(link_fd));
14657 		return libbpf_err_ptr(link_fd);
14658 	}
14659 	link->fd = link_fd;
14660 
14661 	return link;
14662 }
14663 
14664 struct bpf_link *bpf_program__attach(const struct bpf_program *prog)
14665 {
14666 	struct bpf_link *link = NULL;
14667 	int err;
14668 
14669 	if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
14670 		return libbpf_err_ptr(-EOPNOTSUPP);
14671 
14672 	if (bpf_program__fd(prog) < 0) {
14673 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
14674 			prog->name);
14675 		return libbpf_err_ptr(-EINVAL);
14676 	}
14677 
14678 	err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, &link);
14679 	if (err)
14680 		return libbpf_err_ptr(err);
14681 
14682 	/* When calling bpf_program__attach() explicitly, auto-attach support
14683 	 * is expected to work, so NULL returned link is considered an error.
14684 	 * This is different for skeleton's attach, see comment in
14685 	 * bpf_object__attach_skeleton().
14686 	 */
14687 	if (!link)
14688 		return libbpf_err_ptr(-EOPNOTSUPP);
14689 
14690 	return link;
14691 }
14692 
14693 struct bpf_link_struct_ops {
14694 	struct bpf_link link;
14695 	int map_fd;
14696 };
14697 
14698 static int bpf_link__detach_struct_ops(struct bpf_link *link)
14699 {
14700 	struct bpf_link_struct_ops *st_link;
14701 	__u32 zero = 0;
14702 
14703 	st_link = container_of(link, struct bpf_link_struct_ops, link);
14704 
14705 	if (st_link->map_fd < 0)
14706 		/* w/o a real link */
14707 		return bpf_map_delete_elem(link->fd, &zero);
14708 
14709 	return close(link->fd);
14710 }
14711 
14712 struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map)
14713 {
14714 	struct bpf_link_struct_ops *link;
14715 	__u32 zero = 0;
14716 	int err, fd;
14717 
14718 	if (!bpf_map__is_struct_ops(map)) {
14719 		pr_warn("map '%s': can't attach non-struct_ops map\n", map->name);
14720 		return libbpf_err_ptr(-EINVAL);
14721 	}
14722 
14723 	if (map->fd < 0) {
14724 		pr_warn("map '%s': can't attach BPF map without FD (was it created?)\n", map->name);
14725 		return libbpf_err_ptr(-EINVAL);
14726 	}
14727 
14728 	link = calloc(1, sizeof(*link));
14729 	if (!link)
14730 		return libbpf_err_ptr(-EINVAL);
14731 
14732 	/* kern_vdata should be prepared during the loading phase. */
14733 	err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
14734 	/* It can be EBUSY if the map has been used to create or
14735 	 * update a link before.  We don't allow updating the value of
14736 	 * a struct_ops once it is set.  That ensures that the value
14737 	 * never changed.  So, it is safe to skip EBUSY.
14738 	 */
14739 	if (err && (!(map->def.map_flags & BPF_F_LINK) || err != -EBUSY)) {
14740 		free(link);
14741 		return libbpf_err_ptr(err);
14742 	}
14743 
14744 	link->link.detach = bpf_link__detach_struct_ops;
14745 
14746 	if (!(map->def.map_flags & BPF_F_LINK)) {
14747 		/* w/o a real link */
14748 		link->link.fd = map->fd;
14749 		link->map_fd = -1;
14750 		return &link->link;
14751 	}
14752 
14753 	fd = bpf_link_create(map->fd, 0, BPF_STRUCT_OPS, NULL);
14754 	if (fd < 0) {
14755 		free(link);
14756 		return libbpf_err_ptr(fd);
14757 	}
14758 
14759 	link->link.fd = fd;
14760 	link->map_fd = map->fd;
14761 
14762 	return &link->link;
14763 }
14764 
14765 struct bpf_link *bpf_map__attach_cgroup_opts(const struct bpf_map *map, int cgroup_fd,
14766 					     const struct bpf_cgroup_opts *opts)
14767 {
14768 	LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
14769 	struct bpf_link_struct_ops *link;
14770 	__u32 relative_id, zero = 0;
14771 	int err, fd, relative_fd;
14772 
14773 	if (!OPTS_VALID(opts, bpf_cgroup_opts))
14774 		return libbpf_err_ptr(-EINVAL);
14775 
14776 	if (!bpf_map__is_struct_ops(map)) {
14777 		pr_warn("map '%s': can't attach non-struct_ops map\n", map->name);
14778 		return libbpf_err_ptr(-EINVAL);
14779 	}
14780 
14781 	if (map->fd < 0) {
14782 		pr_warn("map '%s': can't attach BPF map without FD (was it created?)\n", map->name);
14783 		return libbpf_err_ptr(-EINVAL);
14784 	}
14785 
14786 	if (!(map->def.map_flags & BPF_F_LINK)) {
14787 		pr_warn("map '%s': can't attach to cgroup without BPF_F_LINK\n", map->name);
14788 		return libbpf_err_ptr(-EINVAL);
14789 	}
14790 
14791 	relative_id = OPTS_GET(opts, relative_id, 0);
14792 	relative_fd = OPTS_GET(opts, relative_fd, 0);
14793 
14794 	if (relative_fd && relative_id) {
14795 		pr_warn("map '%s': relative_fd and relative_id cannot be set at the same time\n",
14796 			map->name);
14797 		return libbpf_err_ptr(-EINVAL);
14798 	}
14799 
14800 	link_create_opts.cgroup.expected_revision = OPTS_GET(opts, expected_revision, 0);
14801 	link_create_opts.cgroup.relative_fd = relative_fd;
14802 	link_create_opts.cgroup.relative_id = relative_id;
14803 	link_create_opts.flags = OPTS_GET(opts, flags, 0);
14804 
14805 	link = calloc(1, sizeof(*link));
14806 	if (!link)
14807 		return libbpf_err_ptr(-ENOMEM);
14808 
14809 	err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
14810 	if (err && err != -EBUSY) {
14811 		free(link);
14812 		return libbpf_err_ptr(err);
14813 	}
14814 
14815 	link->link.detach = bpf_link__detach_struct_ops;
14816 
14817 	fd = bpf_link_create(map->fd, cgroup_fd, BPF_STRUCT_OPS, &link_create_opts);
14818 	if (fd < 0) {
14819 		free(link);
14820 		return libbpf_err_ptr(fd);
14821 	}
14822 
14823 	link->link.fd = fd;
14824 	link->map_fd = map->fd;
14825 
14826 	return &link->link;
14827 }
14828 
14829 /*
14830  * Swap the back struct_ops of a link with a new struct_ops map.
14831  */
14832 int bpf_link__update_map(struct bpf_link *link, const struct bpf_map *map)
14833 {
14834 	struct bpf_link_struct_ops *st_ops_link;
14835 	__u32 zero = 0;
14836 	int err;
14837 
14838 	if (!bpf_map__is_struct_ops(map))
14839 		return libbpf_err(-EINVAL);
14840 
14841 	if (map->fd < 0) {
14842 		pr_warn("map '%s': can't use BPF map without FD (was it created?)\n", map->name);
14843 		return libbpf_err(-EINVAL);
14844 	}
14845 
14846 	st_ops_link = container_of(link, struct bpf_link_struct_ops, link);
14847 	/* Ensure the type of a link is correct */
14848 	if (st_ops_link->map_fd < 0)
14849 		return libbpf_err(-EINVAL);
14850 
14851 	err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
14852 	/* It can be EBUSY if the map has been used to create or
14853 	 * update a link before.  We don't allow updating the value of
14854 	 * a struct_ops once it is set.  That ensures that the value
14855 	 * never changed.  So, it is safe to skip EBUSY.
14856 	 */
14857 	if (err && err != -EBUSY)
14858 		return err;
14859 
14860 	err = bpf_link_update(link->fd, map->fd, NULL);
14861 	if (err < 0)
14862 		return err;
14863 
14864 	st_ops_link->map_fd = map->fd;
14865 
14866 	return 0;
14867 }
14868 
14869 typedef enum bpf_perf_event_ret (*bpf_perf_event_print_t)(struct perf_event_header *hdr,
14870 							  void *private_data);
14871 
14872 static enum bpf_perf_event_ret
14873 perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
14874 		       void **copy_mem, size_t *copy_size,
14875 		       bpf_perf_event_print_t fn, void *private_data)
14876 {
14877 	struct perf_event_mmap_page *header = mmap_mem;
14878 	__u64 data_head = ring_buffer_read_head(header);
14879 	__u64 data_tail = header->data_tail;
14880 	void *base = ((__u8 *)header) + page_size;
14881 	int ret = LIBBPF_PERF_EVENT_CONT;
14882 	struct perf_event_header *ehdr;
14883 	size_t ehdr_size;
14884 
14885 	while (data_head != data_tail) {
14886 		ehdr = base + (data_tail & (mmap_size - 1));
14887 		ehdr_size = ehdr->size;
14888 
14889 		if (((void *)ehdr) + ehdr_size > base + mmap_size) {
14890 			void *copy_start = ehdr;
14891 			size_t len_first = base + mmap_size - copy_start;
14892 			size_t len_second = ehdr_size - len_first;
14893 
14894 			if (*copy_size < ehdr_size) {
14895 				free(*copy_mem);
14896 				*copy_mem = malloc(ehdr_size);
14897 				if (!*copy_mem) {
14898 					*copy_size = 0;
14899 					ret = LIBBPF_PERF_EVENT_ERROR;
14900 					break;
14901 				}
14902 				*copy_size = ehdr_size;
14903 			}
14904 
14905 			memcpy(*copy_mem, copy_start, len_first);
14906 			memcpy(*copy_mem + len_first, base, len_second);
14907 			ehdr = *copy_mem;
14908 		}
14909 
14910 		ret = fn(ehdr, private_data);
14911 		data_tail += ehdr_size;
14912 		if (ret != LIBBPF_PERF_EVENT_CONT)
14913 			break;
14914 	}
14915 
14916 	ring_buffer_write_tail(header, data_tail);
14917 	return libbpf_err(ret);
14918 }
14919 
14920 struct perf_buffer;
14921 
14922 struct perf_buffer_params {
14923 	struct perf_event_attr *attr;
14924 	/* if event_cb is specified, it takes precedence */
14925 	perf_buffer_event_fn event_cb;
14926 	/* sample_cb and lost_cb are higher-level common-case callbacks */
14927 	perf_buffer_sample_fn sample_cb;
14928 	perf_buffer_lost_fn lost_cb;
14929 	void *ctx;
14930 	int cpu_cnt;
14931 	int *cpus;
14932 	int *map_keys;
14933 };
14934 
14935 struct perf_cpu_buf {
14936 	struct perf_buffer *pb;
14937 	void *base; /* mmap()'ed memory */
14938 	void *buf; /* for reconstructing segmented data */
14939 	size_t buf_size;
14940 	int fd;
14941 	int cpu;
14942 	int map_key;
14943 };
14944 
14945 struct perf_buffer {
14946 	perf_buffer_event_fn event_cb;
14947 	perf_buffer_sample_fn sample_cb;
14948 	perf_buffer_lost_fn lost_cb;
14949 	void *ctx; /* passed into callbacks */
14950 
14951 	size_t page_size;
14952 	size_t mmap_size;
14953 	struct perf_cpu_buf **cpu_bufs;
14954 	struct epoll_event *events;
14955 	int cpu_cnt; /* number of allocated CPU buffers */
14956 	int epoll_fd; /* perf event FD */
14957 	int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
14958 };
14959 
14960 static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
14961 				      struct perf_cpu_buf *cpu_buf)
14962 {
14963 	if (!cpu_buf)
14964 		return;
14965 	if (cpu_buf->base &&
14966 	    munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
14967 		pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
14968 	if (cpu_buf->fd >= 0) {
14969 		ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
14970 		close(cpu_buf->fd);
14971 	}
14972 	free(cpu_buf->buf);
14973 	free(cpu_buf);
14974 }
14975 
14976 void perf_buffer__free(struct perf_buffer *pb)
14977 {
14978 	int i;
14979 
14980 	if (IS_ERR_OR_NULL(pb))
14981 		return;
14982 	if (pb->cpu_bufs) {
14983 		for (i = 0; i < pb->cpu_cnt; i++) {
14984 			struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
14985 
14986 			if (!cpu_buf)
14987 				continue;
14988 
14989 			bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
14990 			perf_buffer__free_cpu_buf(pb, cpu_buf);
14991 		}
14992 		free(pb->cpu_bufs);
14993 	}
14994 	if (pb->epoll_fd >= 0)
14995 		close(pb->epoll_fd);
14996 	free(pb->events);
14997 	free(pb);
14998 }
14999 
15000 static struct perf_cpu_buf *
15001 perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
15002 			  int cpu, int map_key)
15003 {
15004 	struct perf_cpu_buf *cpu_buf;
15005 	int err;
15006 
15007 	cpu_buf = calloc(1, sizeof(*cpu_buf));
15008 	if (!cpu_buf)
15009 		return ERR_PTR(-ENOMEM);
15010 
15011 	cpu_buf->pb = pb;
15012 	cpu_buf->cpu = cpu;
15013 	cpu_buf->map_key = map_key;
15014 
15015 	cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
15016 			      -1, PERF_FLAG_FD_CLOEXEC);
15017 	if (cpu_buf->fd < 0) {
15018 		err = -errno;
15019 		pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
15020 			cpu, errstr(err));
15021 		goto error;
15022 	}
15023 
15024 	cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
15025 			     PROT_READ | PROT_WRITE, MAP_SHARED,
15026 			     cpu_buf->fd, 0);
15027 	if (cpu_buf->base == MAP_FAILED) {
15028 		cpu_buf->base = NULL;
15029 		err = -errno;
15030 		pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
15031 			cpu, errstr(err));
15032 		goto error;
15033 	}
15034 
15035 	if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
15036 		err = -errno;
15037 		pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
15038 			cpu, errstr(err));
15039 		goto error;
15040 	}
15041 
15042 	return cpu_buf;
15043 
15044 error:
15045 	perf_buffer__free_cpu_buf(pb, cpu_buf);
15046 	return (struct perf_cpu_buf *)ERR_PTR(err);
15047 }
15048 
15049 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
15050 					      struct perf_buffer_params *p);
15051 
15052 struct perf_buffer *perf_buffer__new(int map_fd, size_t page_cnt,
15053 				     perf_buffer_sample_fn sample_cb,
15054 				     perf_buffer_lost_fn lost_cb,
15055 				     void *ctx,
15056 				     const struct perf_buffer_opts *opts)
15057 {
15058 	const size_t attr_sz = sizeof(struct perf_event_attr);
15059 	struct perf_buffer_params p = {};
15060 	struct perf_event_attr attr;
15061 	__u32 sample_period;
15062 
15063 	if (!OPTS_VALID(opts, perf_buffer_opts))
15064 		return libbpf_err_ptr(-EINVAL);
15065 
15066 	sample_period = OPTS_GET(opts, sample_period, 1);
15067 	if (!sample_period)
15068 		sample_period = 1;
15069 
15070 	memset(&attr, 0, attr_sz);
15071 	attr.size = attr_sz;
15072 	attr.config = PERF_COUNT_SW_BPF_OUTPUT;
15073 	attr.type = PERF_TYPE_SOFTWARE;
15074 	attr.sample_type = PERF_SAMPLE_RAW;
15075 	attr.wakeup_events = sample_period;
15076 
15077 	p.attr = &attr;
15078 	p.sample_cb = sample_cb;
15079 	p.lost_cb = lost_cb;
15080 	p.ctx = ctx;
15081 
15082 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
15083 }
15084 
15085 struct perf_buffer *perf_buffer__new_raw(int map_fd, size_t page_cnt,
15086 					 struct perf_event_attr *attr,
15087 					 perf_buffer_event_fn event_cb, void *ctx,
15088 					 const struct perf_buffer_raw_opts *opts)
15089 {
15090 	struct perf_buffer_params p = {};
15091 
15092 	if (!attr)
15093 		return libbpf_err_ptr(-EINVAL);
15094 
15095 	if (!OPTS_VALID(opts, perf_buffer_raw_opts))
15096 		return libbpf_err_ptr(-EINVAL);
15097 
15098 	p.attr = attr;
15099 	p.event_cb = event_cb;
15100 	p.ctx = ctx;
15101 	p.cpu_cnt = OPTS_GET(opts, cpu_cnt, 0);
15102 	p.cpus = OPTS_GET(opts, cpus, NULL);
15103 	p.map_keys = OPTS_GET(opts, map_keys, NULL);
15104 
15105 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
15106 }
15107 
15108 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
15109 					      struct perf_buffer_params *p)
15110 {
15111 	const char *online_cpus_file = "/sys/devices/system/cpu/online";
15112 	struct bpf_map_info map;
15113 	struct perf_buffer *pb;
15114 	bool *online = NULL;
15115 	__u32 map_info_len;
15116 	int err, i, j, n;
15117 
15118 	if (page_cnt == 0 || (page_cnt & (page_cnt - 1))) {
15119 		pr_warn("page count should be power of two, but is %zu\n",
15120 			page_cnt);
15121 		return ERR_PTR(-EINVAL);
15122 	}
15123 
15124 	/* best-effort sanity checks */
15125 	memset(&map, 0, sizeof(map));
15126 	map_info_len = sizeof(map);
15127 	err = bpf_map_get_info_by_fd(map_fd, &map, &map_info_len);
15128 	if (err) {
15129 		err = -errno;
15130 		/* if BPF_OBJ_GET_INFO_BY_FD is supported, will return
15131 		 * -EBADFD, -EFAULT, or -E2BIG on real error
15132 		 */
15133 		if (err != -EINVAL) {
15134 			pr_warn("failed to get map info for map FD %d: %s\n",
15135 				map_fd, errstr(err));
15136 			return ERR_PTR(err);
15137 		}
15138 		pr_debug("failed to get map info for FD %d; API not supported? Ignoring...\n",
15139 			 map_fd);
15140 	} else {
15141 		if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
15142 			pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
15143 				map.name);
15144 			return ERR_PTR(-EINVAL);
15145 		}
15146 	}
15147 
15148 	pb = calloc(1, sizeof(*pb));
15149 	if (!pb)
15150 		return ERR_PTR(-ENOMEM);
15151 
15152 	pb->event_cb = p->event_cb;
15153 	pb->sample_cb = p->sample_cb;
15154 	pb->lost_cb = p->lost_cb;
15155 	pb->ctx = p->ctx;
15156 
15157 	pb->page_size = getpagesize();
15158 	pb->mmap_size = pb->page_size * page_cnt;
15159 	pb->map_fd = map_fd;
15160 
15161 	pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
15162 	if (pb->epoll_fd < 0) {
15163 		err = -errno;
15164 		pr_warn("failed to create epoll instance: %s\n",
15165 			errstr(err));
15166 		goto error;
15167 	}
15168 
15169 	if (p->cpu_cnt > 0) {
15170 		pb->cpu_cnt = p->cpu_cnt;
15171 	} else {
15172 		pb->cpu_cnt = libbpf_num_possible_cpus();
15173 		if (pb->cpu_cnt < 0) {
15174 			err = pb->cpu_cnt;
15175 			goto error;
15176 		}
15177 		if (map.max_entries && map.max_entries < pb->cpu_cnt)
15178 			pb->cpu_cnt = map.max_entries;
15179 	}
15180 
15181 	pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
15182 	if (!pb->events) {
15183 		err = -ENOMEM;
15184 		pr_warn("failed to allocate events: out of memory\n");
15185 		goto error;
15186 	}
15187 	pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
15188 	if (!pb->cpu_bufs) {
15189 		err = -ENOMEM;
15190 		pr_warn("failed to allocate buffers: out of memory\n");
15191 		goto error;
15192 	}
15193 
15194 	err = parse_cpu_mask_file(online_cpus_file, &online, &n);
15195 	if (err) {
15196 		pr_warn("failed to get online CPU mask: %s\n", errstr(err));
15197 		goto error;
15198 	}
15199 
15200 	for (i = 0, j = 0; i < pb->cpu_cnt; i++) {
15201 		struct perf_cpu_buf *cpu_buf;
15202 		int cpu, map_key;
15203 
15204 		cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
15205 		map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
15206 
15207 		/* in case user didn't explicitly requested particular CPUs to
15208 		 * be attached to, skip offline/not present CPUs
15209 		 */
15210 		if (p->cpu_cnt <= 0 && (cpu >= n || !online[cpu]))
15211 			continue;
15212 
15213 		cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
15214 		if (IS_ERR(cpu_buf)) {
15215 			err = PTR_ERR(cpu_buf);
15216 			goto error;
15217 		}
15218 
15219 		pb->cpu_bufs[j] = cpu_buf;
15220 
15221 		err = bpf_map_update_elem(pb->map_fd, &map_key,
15222 					  &cpu_buf->fd, 0);
15223 		if (err) {
15224 			err = -errno;
15225 			pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
15226 				cpu, map_key, cpu_buf->fd,
15227 				errstr(err));
15228 			goto error;
15229 		}
15230 
15231 		pb->events[j].events = EPOLLIN;
15232 		pb->events[j].data.ptr = cpu_buf;
15233 		if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
15234 			      &pb->events[j]) < 0) {
15235 			err = -errno;
15236 			pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
15237 				cpu, cpu_buf->fd,
15238 				errstr(err));
15239 			goto error;
15240 		}
15241 		j++;
15242 	}
15243 	pb->cpu_cnt = j;
15244 	free(online);
15245 
15246 	return pb;
15247 
15248 error:
15249 	free(online);
15250 	if (pb)
15251 		perf_buffer__free(pb);
15252 	return ERR_PTR(err);
15253 }
15254 
15255 struct perf_sample_raw {
15256 	struct perf_event_header header;
15257 	uint32_t size;
15258 	char data[];
15259 };
15260 
15261 struct perf_sample_lost {
15262 	struct perf_event_header header;
15263 	uint64_t id;
15264 	uint64_t lost;
15265 	uint64_t sample_id;
15266 };
15267 
15268 static enum bpf_perf_event_ret
15269 perf_buffer__process_record(struct perf_event_header *e, void *ctx)
15270 {
15271 	struct perf_cpu_buf *cpu_buf = ctx;
15272 	struct perf_buffer *pb = cpu_buf->pb;
15273 	void *data = e;
15274 
15275 	/* user wants full control over parsing perf event */
15276 	if (pb->event_cb)
15277 		return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
15278 
15279 	switch (e->type) {
15280 	case PERF_RECORD_SAMPLE: {
15281 		struct perf_sample_raw *s = data;
15282 
15283 		if (pb->sample_cb)
15284 			pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
15285 		break;
15286 	}
15287 	case PERF_RECORD_LOST: {
15288 		struct perf_sample_lost *s = data;
15289 
15290 		if (pb->lost_cb)
15291 			pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
15292 		break;
15293 	}
15294 	default:
15295 		pr_warn("unknown perf sample type %u\n", e->type);
15296 		return LIBBPF_PERF_EVENT_ERROR;
15297 	}
15298 	return LIBBPF_PERF_EVENT_CONT;
15299 }
15300 
15301 static int perf_buffer__process_records(struct perf_buffer *pb,
15302 					struct perf_cpu_buf *cpu_buf)
15303 {
15304 	enum bpf_perf_event_ret ret;
15305 
15306 	ret = perf_event_read_simple(cpu_buf->base, pb->mmap_size,
15307 				     pb->page_size, &cpu_buf->buf,
15308 				     &cpu_buf->buf_size,
15309 				     perf_buffer__process_record, cpu_buf);
15310 	if (ret != LIBBPF_PERF_EVENT_CONT)
15311 		return ret;
15312 	return 0;
15313 }
15314 
15315 int perf_buffer__epoll_fd(const struct perf_buffer *pb)
15316 {
15317 	return pb->epoll_fd;
15318 }
15319 
15320 int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
15321 {
15322 	int i, cnt, err;
15323 
15324 	cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
15325 	if (cnt < 0)
15326 		return -errno;
15327 
15328 	for (i = 0; i < cnt; i++) {
15329 		struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
15330 
15331 		err = perf_buffer__process_records(pb, cpu_buf);
15332 		if (err) {
15333 			pr_warn("error while processing records: %s\n", errstr(err));
15334 			return libbpf_err(err);
15335 		}
15336 	}
15337 	return cnt;
15338 }
15339 
15340 /* Return number of PERF_EVENT_ARRAY map slots set up by this perf_buffer
15341  * manager.
15342  */
15343 size_t perf_buffer__buffer_cnt(const struct perf_buffer *pb)
15344 {
15345 	return pb->cpu_cnt;
15346 }
15347 
15348 /*
15349  * Return perf_event FD of a ring buffer in *buf_idx* slot of
15350  * PERF_EVENT_ARRAY BPF map. This FD can be polled for new data using
15351  * select()/poll()/epoll() Linux syscalls.
15352  */
15353 int perf_buffer__buffer_fd(const struct perf_buffer *pb, size_t buf_idx)
15354 {
15355 	struct perf_cpu_buf *cpu_buf;
15356 
15357 	if (buf_idx >= pb->cpu_cnt)
15358 		return libbpf_err(-EINVAL);
15359 
15360 	cpu_buf = pb->cpu_bufs[buf_idx];
15361 	if (!cpu_buf)
15362 		return libbpf_err(-ENOENT);
15363 
15364 	return cpu_buf->fd;
15365 }
15366 
15367 int perf_buffer__buffer(struct perf_buffer *pb, int buf_idx, void **buf, size_t *buf_size)
15368 {
15369 	struct perf_cpu_buf *cpu_buf;
15370 
15371 	if (buf_idx >= pb->cpu_cnt)
15372 		return libbpf_err(-EINVAL);
15373 
15374 	cpu_buf = pb->cpu_bufs[buf_idx];
15375 	if (!cpu_buf)
15376 		return libbpf_err(-ENOENT);
15377 
15378 	*buf = cpu_buf->base;
15379 	*buf_size = pb->mmap_size;
15380 	return 0;
15381 }
15382 
15383 /*
15384  * Consume data from perf ring buffer corresponding to slot *buf_idx* in
15385  * PERF_EVENT_ARRAY BPF map without waiting/polling. If there is no data to
15386  * consume, do nothing and return success.
15387  * Returns:
15388  *   - 0 on success;
15389  *   - <0 on failure.
15390  */
15391 int perf_buffer__consume_buffer(struct perf_buffer *pb, size_t buf_idx)
15392 {
15393 	struct perf_cpu_buf *cpu_buf;
15394 
15395 	if (buf_idx >= pb->cpu_cnt)
15396 		return libbpf_err(-EINVAL);
15397 
15398 	cpu_buf = pb->cpu_bufs[buf_idx];
15399 	if (!cpu_buf)
15400 		return libbpf_err(-ENOENT);
15401 
15402 	return perf_buffer__process_records(pb, cpu_buf);
15403 }
15404 
15405 int perf_buffer__consume(struct perf_buffer *pb)
15406 {
15407 	int i, err;
15408 
15409 	for (i = 0; i < pb->cpu_cnt; i++) {
15410 		struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
15411 
15412 		if (!cpu_buf)
15413 			continue;
15414 
15415 		err = perf_buffer__process_records(pb, cpu_buf);
15416 		if (err) {
15417 			pr_warn("perf_buffer: failed to process records in buffer #%d: %s\n",
15418 				i, errstr(err));
15419 			return libbpf_err(err);
15420 		}
15421 	}
15422 	return 0;
15423 }
15424 
15425 int bpf_program__set_attach_target(struct bpf_program *prog,
15426 				   int attach_prog_fd,
15427 				   const char *attach_func_name)
15428 {
15429 	int btf_obj_fd = 0, btf_id = 0, err;
15430 
15431 	if (!prog || attach_prog_fd < 0)
15432 		return libbpf_err(-EINVAL);
15433 
15434 	if (prog->obj->state >= OBJ_LOADED)
15435 		return libbpf_err(-EINVAL);
15436 
15437 	if (attach_prog_fd && !attach_func_name) {
15438 		/* Store attach_prog_fd. The BTF ID will be resolved later during
15439 		 * the normal object/program load phase.
15440 		 */
15441 		prog->attach_prog_fd = attach_prog_fd;
15442 		return 0;
15443 	}
15444 
15445 	if (attach_prog_fd) {
15446 		btf_id = libbpf_find_prog_btf_id(attach_func_name,
15447 						 attach_prog_fd, prog->obj->token_fd);
15448 		if (btf_id < 0)
15449 			return libbpf_err(btf_id);
15450 	} else {
15451 		if (!attach_func_name)
15452 			return libbpf_err(-EINVAL);
15453 
15454 		/* load btf_vmlinux, if not yet */
15455 		err = bpf_object__load_vmlinux_btf(prog->obj, true);
15456 		if (err)
15457 			return libbpf_err(err);
15458 		err = find_kernel_btf_id(prog->obj, attach_func_name,
15459 					 prog->expected_attach_type,
15460 					 &btf_obj_fd, &btf_id);
15461 		if (err)
15462 			return libbpf_err(err);
15463 	}
15464 
15465 	prog->attach_btf_id = btf_id;
15466 	prog->attach_btf_obj_fd = btf_obj_fd;
15467 	prog->attach_prog_fd = attach_prog_fd;
15468 	return 0;
15469 }
15470 
15471 int bpf_program__assoc_struct_ops(struct bpf_program *prog, struct bpf_map *map,
15472 				  struct bpf_prog_assoc_struct_ops_opts *opts)
15473 {
15474 	int prog_fd, map_fd;
15475 
15476 	prog_fd = bpf_program__fd(prog);
15477 	if (prog_fd < 0) {
15478 		pr_warn("prog '%s': can't associate BPF program without FD (was it loaded?)\n",
15479 			prog->name);
15480 		return libbpf_err(-EINVAL);
15481 	}
15482 
15483 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS) {
15484 		pr_warn("prog '%s': can't associate struct_ops program\n", prog->name);
15485 		return libbpf_err(-EINVAL);
15486 	}
15487 
15488 	map_fd = bpf_map__fd(map);
15489 	if (map_fd < 0) {
15490 		pr_warn("map '%s': can't associate BPF map without FD (was it created?)\n", map->name);
15491 		return libbpf_err(-EINVAL);
15492 	}
15493 
15494 	if (!bpf_map__is_struct_ops(map)) {
15495 		pr_warn("map '%s': can't associate non-struct_ops map\n", map->name);
15496 		return libbpf_err(-EINVAL);
15497 	}
15498 
15499 	return bpf_prog_assoc_struct_ops(prog_fd, map_fd, opts);
15500 }
15501 
15502 int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz)
15503 {
15504 	int err = 0, n, len, start, end = -1;
15505 	bool *tmp;
15506 
15507 	*mask = NULL;
15508 	*mask_sz = 0;
15509 
15510 	/* Each sub string separated by ',' has format \d+-\d+ or \d+ */
15511 	while (*s) {
15512 		if (*s == ',' || *s == '\n') {
15513 			s++;
15514 			continue;
15515 		}
15516 		n = sscanf(s, "%d%n-%d%n", &start, &len, &end, &len);
15517 		if (n <= 0 || n > 2) {
15518 			pr_warn("Failed to get CPU range %s: %d\n", s, n);
15519 			err = -EINVAL;
15520 			goto cleanup;
15521 		} else if (n == 1) {
15522 			end = start;
15523 		}
15524 		if (start < 0 || start > end) {
15525 			pr_warn("Invalid CPU range [%d,%d] in %s\n",
15526 				start, end, s);
15527 			err = -EINVAL;
15528 			goto cleanup;
15529 		}
15530 		tmp = realloc(*mask, end + 1);
15531 		if (!tmp) {
15532 			err = -ENOMEM;
15533 			goto cleanup;
15534 		}
15535 		*mask = tmp;
15536 		memset(tmp + *mask_sz, 0, start - *mask_sz);
15537 		memset(tmp + start, 1, end - start + 1);
15538 		*mask_sz = end + 1;
15539 		s += len;
15540 	}
15541 	if (!*mask_sz) {
15542 		pr_warn("Empty CPU range\n");
15543 		return -EINVAL;
15544 	}
15545 	return 0;
15546 cleanup:
15547 	free(*mask);
15548 	*mask = NULL;
15549 	return err;
15550 }
15551 
15552 int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz)
15553 {
15554 	int fd, err = 0, len;
15555 	char buf[128];
15556 
15557 	fd = open(fcpu, O_RDONLY | O_CLOEXEC);
15558 	if (fd < 0) {
15559 		err = -errno;
15560 		pr_warn("Failed to open cpu mask file %s: %s\n", fcpu, errstr(err));
15561 		return err;
15562 	}
15563 	len = read(fd, buf, sizeof(buf));
15564 	close(fd);
15565 	if (len <= 0) {
15566 		err = len ? -errno : -EINVAL;
15567 		pr_warn("Failed to read cpu mask from %s: %s\n", fcpu, errstr(err));
15568 		return err;
15569 	}
15570 	if (len >= sizeof(buf)) {
15571 		pr_warn("CPU mask is too big in file %s\n", fcpu);
15572 		return -E2BIG;
15573 	}
15574 	buf[len] = '\0';
15575 
15576 	return parse_cpu_mask_str(buf, mask, mask_sz);
15577 }
15578 
15579 int libbpf_num_possible_cpus(void)
15580 {
15581 	static const char *fcpu = "/sys/devices/system/cpu/possible";
15582 	static int cpus;
15583 	int err, n, i, tmp_cpus;
15584 	bool *mask;
15585 
15586 	tmp_cpus = READ_ONCE(cpus);
15587 	if (tmp_cpus > 0)
15588 		return tmp_cpus;
15589 
15590 	err = parse_cpu_mask_file(fcpu, &mask, &n);
15591 	if (err)
15592 		return libbpf_err(err);
15593 
15594 	tmp_cpus = 0;
15595 	for (i = 0; i < n; i++) {
15596 		if (mask[i])
15597 			tmp_cpus++;
15598 	}
15599 	free(mask);
15600 
15601 	WRITE_ONCE(cpus, tmp_cpus);
15602 	return tmp_cpus;
15603 }
15604 
15605 static int populate_skeleton_maps(const struct bpf_object *obj,
15606 				  struct bpf_map_skeleton *maps,
15607 				  size_t map_cnt, size_t map_skel_sz)
15608 {
15609 	int i;
15610 
15611 	for (i = 0; i < map_cnt; i++) {
15612 		struct bpf_map_skeleton *map_skel = (void *)maps + i * map_skel_sz;
15613 		struct bpf_map **map = map_skel->map;
15614 		const char *name = map_skel->name;
15615 		void **mmaped = map_skel->mmaped;
15616 
15617 		*map = bpf_object__find_map_by_name(obj, name);
15618 		if (!*map) {
15619 			pr_warn("failed to find skeleton map '%s'\n", name);
15620 			return -ESRCH;
15621 		}
15622 
15623 		/* externs shouldn't be pre-setup from user code */
15624 		if (mmaped && (*map)->libbpf_type != LIBBPF_MAP_KCONFIG)
15625 			*mmaped = (*map)->mmaped;
15626 	}
15627 	return 0;
15628 }
15629 
15630 static int populate_skeleton_progs(const struct bpf_object *obj,
15631 				   struct bpf_prog_skeleton *progs,
15632 				   size_t prog_cnt, size_t prog_skel_sz)
15633 {
15634 	int i;
15635 
15636 	for (i = 0; i < prog_cnt; i++) {
15637 		struct bpf_prog_skeleton *prog_skel = (void *)progs + i * prog_skel_sz;
15638 		struct bpf_program **prog = prog_skel->prog;
15639 		const char *name = prog_skel->name;
15640 
15641 		*prog = bpf_object__find_program_by_name(obj, name);
15642 		if (!*prog) {
15643 			pr_warn("failed to find skeleton program '%s'\n", name);
15644 			return -ESRCH;
15645 		}
15646 	}
15647 	return 0;
15648 }
15649 
15650 int bpf_object__open_skeleton(struct bpf_object_skeleton *s,
15651 			      const struct bpf_object_open_opts *opts)
15652 {
15653 	struct bpf_object *obj;
15654 	int err;
15655 
15656 	obj = bpf_object_open(NULL, s->data, s->data_sz, s->name, opts);
15657 	if (IS_ERR(obj)) {
15658 		err = PTR_ERR(obj);
15659 		pr_warn("failed to initialize skeleton BPF object '%s': %s\n",
15660 			s->name, errstr(err));
15661 		return libbpf_err(err);
15662 	}
15663 
15664 	*s->obj = obj;
15665 	err = populate_skeleton_maps(obj, s->maps, s->map_cnt, s->map_skel_sz);
15666 	if (err) {
15667 		pr_warn("failed to populate skeleton maps for '%s': %s\n", s->name, errstr(err));
15668 		return libbpf_err(err);
15669 	}
15670 
15671 	err = populate_skeleton_progs(obj, s->progs, s->prog_cnt, s->prog_skel_sz);
15672 	if (err) {
15673 		pr_warn("failed to populate skeleton progs for '%s': %s\n", s->name, errstr(err));
15674 		return libbpf_err(err);
15675 	}
15676 
15677 	return 0;
15678 }
15679 
15680 int bpf_object__open_subskeleton(struct bpf_object_subskeleton *s)
15681 {
15682 	int err, len, var_idx, i;
15683 	const char *var_name;
15684 	const struct bpf_map *map;
15685 	struct btf *btf;
15686 	__u32 map_type_id;
15687 	const struct btf_type *map_type, *var_type;
15688 	const struct bpf_var_skeleton *var_skel;
15689 	struct btf_var_secinfo *var;
15690 
15691 	if (!s->obj)
15692 		return libbpf_err(-EINVAL);
15693 
15694 	btf = bpf_object__btf(s->obj);
15695 	if (!btf) {
15696 		pr_warn("subskeletons require BTF at runtime (object %s)\n",
15697 			bpf_object__name(s->obj));
15698 		return libbpf_err(-errno);
15699 	}
15700 
15701 	err = populate_skeleton_maps(s->obj, s->maps, s->map_cnt, s->map_skel_sz);
15702 	if (err) {
15703 		pr_warn("failed to populate subskeleton maps: %s\n", errstr(err));
15704 		return libbpf_err(err);
15705 	}
15706 
15707 	err = populate_skeleton_progs(s->obj, s->progs, s->prog_cnt, s->prog_skel_sz);
15708 	if (err) {
15709 		pr_warn("failed to populate subskeleton maps: %s\n", errstr(err));
15710 		return libbpf_err(err);
15711 	}
15712 
15713 	for (var_idx = 0; var_idx < s->var_cnt; var_idx++) {
15714 		var_skel = (void *)s->vars + var_idx * s->var_skel_sz;
15715 		map = *var_skel->map;
15716 		map_type_id = bpf_map__btf_value_type_id(map);
15717 		map_type = btf__type_by_id(btf, map_type_id);
15718 
15719 		if (!btf_is_datasec(map_type)) {
15720 			pr_warn("type for map '%1$s' is not a datasec: %2$s\n",
15721 				bpf_map__name(map),
15722 				__btf_kind_str(btf_kind(map_type)));
15723 			return libbpf_err(-EINVAL);
15724 		}
15725 
15726 		len = btf_vlen(map_type);
15727 		var = btf_var_secinfos(map_type);
15728 		for (i = 0; i < len; i++, var++) {
15729 			var_type = btf__type_by_id(btf, var->type);
15730 			var_name = btf__name_by_offset(btf, var_type->name_off);
15731 			if (strcmp(var_name, var_skel->name) == 0) {
15732 				*var_skel->addr = map->mmaped + var->offset;
15733 				break;
15734 			}
15735 		}
15736 	}
15737 	return 0;
15738 }
15739 
15740 void bpf_object__destroy_subskeleton(struct bpf_object_subskeleton *s)
15741 {
15742 	if (!s)
15743 		return;
15744 	free(s->maps);
15745 	free(s->progs);
15746 	free(s->vars);
15747 	free(s);
15748 }
15749 
15750 int bpf_object__load_skeleton(struct bpf_object_skeleton *s)
15751 {
15752 	int i, err;
15753 
15754 	err = bpf_object__load(*s->obj);
15755 	if (err) {
15756 		pr_warn("failed to load BPF skeleton '%s': %s\n", s->name, errstr(err));
15757 		return libbpf_err(err);
15758 	}
15759 
15760 	for (i = 0; i < s->map_cnt; i++) {
15761 		struct bpf_map_skeleton *map_skel = (void *)s->maps + i * s->map_skel_sz;
15762 		struct bpf_map *map = *map_skel->map;
15763 
15764 		if (!map_skel->mmaped)
15765 			continue;
15766 
15767 		if (map->def.type == BPF_MAP_TYPE_ARENA)
15768 			*map_skel->mmaped = map->mmaped + map->obj->arena_data_off;
15769 		else
15770 			*map_skel->mmaped = map->mmaped;
15771 	}
15772 
15773 	return 0;
15774 }
15775 
15776 int bpf_object__attach_skeleton(struct bpf_object_skeleton *s)
15777 {
15778 	int i, err;
15779 
15780 	for (i = 0; i < s->prog_cnt; i++) {
15781 		struct bpf_prog_skeleton *prog_skel = (void *)s->progs + i * s->prog_skel_sz;
15782 		struct bpf_program *prog = *prog_skel->prog;
15783 		struct bpf_link **link = prog_skel->link;
15784 
15785 		if (!prog->autoload || !prog->autoattach)
15786 			continue;
15787 
15788 		/* auto-attaching not supported for this program */
15789 		if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
15790 			continue;
15791 
15792 		/* if user already set the link manually, don't attempt auto-attach */
15793 		if (*link)
15794 			continue;
15795 
15796 		err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, link);
15797 		if (err) {
15798 			pr_warn("prog '%s': failed to auto-attach: %s\n",
15799 				bpf_program__name(prog), errstr(err));
15800 			return libbpf_err(err);
15801 		}
15802 
15803 		/* It's possible that for some SEC() definitions auto-attach
15804 		 * is supported in some cases (e.g., if definition completely
15805 		 * specifies target information), but is not in other cases.
15806 		 * SEC("uprobe") is one such case. If user specified target
15807 		 * binary and function name, such BPF program can be
15808 		 * auto-attached. But if not, it shouldn't trigger skeleton's
15809 		 * attach to fail. It should just be skipped.
15810 		 * attach_fn signals such case with returning 0 (no error) and
15811 		 * setting link to NULL.
15812 		 */
15813 	}
15814 
15815 
15816 	for (i = 0; i < s->map_cnt; i++) {
15817 		struct bpf_map_skeleton *map_skel = (void *)s->maps + i * s->map_skel_sz;
15818 		struct bpf_map *map = *map_skel->map;
15819 		struct bpf_link **link;
15820 
15821 		if (!map->autocreate || !map->autoattach)
15822 			continue;
15823 
15824 		/* only struct_ops maps can be attached */
15825 		if (!bpf_map__is_struct_ops(map))
15826 			continue;
15827 
15828 		/* skeleton is created with earlier version of bpftool, notify user */
15829 		if (s->map_skel_sz < offsetofend(struct bpf_map_skeleton, link)) {
15830 			pr_warn("map '%s': BPF skeleton version is old, skipping map auto-attachment...\n",
15831 				bpf_map__name(map));
15832 			continue;
15833 		}
15834 
15835 		link = map_skel->link;
15836 		if (!link) {
15837 			pr_warn("map '%s': BPF map skeleton link is uninitialized\n",
15838 				bpf_map__name(map));
15839 			continue;
15840 		}
15841 
15842 		if (*link)
15843 			continue;
15844 
15845 		*link = bpf_map__attach_struct_ops(map);
15846 		if (!*link) {
15847 			err = -errno;
15848 			pr_warn("map '%s': failed to auto-attach: %s\n",
15849 				bpf_map__name(map), errstr(err));
15850 			return libbpf_err(err);
15851 		}
15852 	}
15853 
15854 	return 0;
15855 }
15856 
15857 void bpf_object__detach_skeleton(struct bpf_object_skeleton *s)
15858 {
15859 	int i;
15860 
15861 	for (i = 0; i < s->prog_cnt; i++) {
15862 		struct bpf_prog_skeleton *prog_skel = (void *)s->progs + i * s->prog_skel_sz;
15863 		struct bpf_link **link = prog_skel->link;
15864 
15865 		bpf_link__destroy(*link);
15866 		*link = NULL;
15867 	}
15868 
15869 	if (s->map_skel_sz < sizeof(struct bpf_map_skeleton))
15870 		return;
15871 
15872 	for (i = 0; i < s->map_cnt; i++) {
15873 		struct bpf_map_skeleton *map_skel = (void *)s->maps + i * s->map_skel_sz;
15874 		struct bpf_link **link = map_skel->link;
15875 
15876 		if (link) {
15877 			bpf_link__destroy(*link);
15878 			*link = NULL;
15879 		}
15880 	}
15881 }
15882 
15883 void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s)
15884 {
15885 	if (!s)
15886 		return;
15887 
15888 	bpf_object__detach_skeleton(s);
15889 	if (s->obj)
15890 		bpf_object__close(*s->obj);
15891 	free(s->maps);
15892 	free(s->progs);
15893 	free(s);
15894 }
15895