xref: /linux/tools/lib/bpf/libbpf.c (revision 5b0678b2f9b96fa44c9a47655428fe1706fdf9a7)
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 	__u32 i;
1458 
1459 	if (shndx == -1)
1460 		return 0;
1461 
1462 	btf = obj->btf;
1463 	datasec_id = btf__find_by_name_kind(btf, sec_name,
1464 					    BTF_KIND_DATASEC);
1465 	if (datasec_id < 0) {
1466 		pr_warn("struct_ops init: DATASEC %s not found\n",
1467 			sec_name);
1468 		return -EINVAL;
1469 	}
1470 
1471 	datasec = btf__type_by_id(btf, datasec_id);
1472 	vsi = btf_var_secinfos(datasec);
1473 	for (i = 0; i < btf_vlen(datasec); i++, vsi++) {
1474 		type = btf__type_by_id(obj->btf, vsi->type);
1475 		var_name = btf__name_by_offset(obj->btf, type->name_off);
1476 
1477 		type_id = btf__resolve_type(obj->btf, vsi->type);
1478 		if (type_id < 0) {
1479 			pr_warn("struct_ops init: Cannot resolve var type_id %u in DATASEC %s\n",
1480 				vsi->type, sec_name);
1481 			return -EINVAL;
1482 		}
1483 
1484 		type = btf__type_by_id(obj->btf, type_id);
1485 		tname = btf__name_by_offset(obj->btf, type->name_off);
1486 		if (!tname[0]) {
1487 			pr_warn("struct_ops init: anonymous type is not supported\n");
1488 			return -ENOTSUP;
1489 		}
1490 		if (!btf_is_struct(type)) {
1491 			pr_warn("struct_ops init: %s is not a struct\n", tname);
1492 			return -EINVAL;
1493 		}
1494 
1495 		map = bpf_object__add_map(obj);
1496 		if (IS_ERR(map))
1497 			return PTR_ERR(map);
1498 
1499 		map->sec_idx = shndx;
1500 		map->sec_offset = vsi->offset;
1501 		map->name = strdup(var_name);
1502 		if (!map->name)
1503 			return -ENOMEM;
1504 		map->btf_value_type_id = type_id;
1505 
1506 		/* Follow same convention as for programs autoload:
1507 		 * SEC("?.struct_ops") means map is not created by default.
1508 		 */
1509 		if (sec_name[0] == '?') {
1510 			map->autocreate = false;
1511 			/* from now on forget there was ? in section name */
1512 			sec_name++;
1513 		}
1514 
1515 		map->def.type = BPF_MAP_TYPE_STRUCT_OPS;
1516 		map->def.key_size = sizeof(int);
1517 		map->def.value_size = type->size;
1518 		map->def.max_entries = 1;
1519 		map->def.map_flags = strcmp(sec_name, STRUCT_OPS_LINK_SEC) == 0 ? BPF_F_LINK : 0;
1520 		map->autoattach = true;
1521 
1522 		map->st_ops = calloc(1, sizeof(*map->st_ops));
1523 		if (!map->st_ops)
1524 			return -ENOMEM;
1525 		st_ops = map->st_ops;
1526 		st_ops->data = malloc(type->size);
1527 		st_ops->progs = calloc(btf_vlen(type), sizeof(*st_ops->progs));
1528 		st_ops->kern_func_off = malloc(btf_vlen(type) *
1529 					       sizeof(*st_ops->kern_func_off));
1530 		if (!st_ops->data || !st_ops->progs || !st_ops->kern_func_off)
1531 			return -ENOMEM;
1532 
1533 		if (vsi->offset + type->size > data->d_size) {
1534 			pr_warn("struct_ops init: var %s is beyond the end of DATASEC %s\n",
1535 				var_name, sec_name);
1536 			return -EINVAL;
1537 		}
1538 
1539 		memcpy(st_ops->data,
1540 		       data->d_buf + vsi->offset,
1541 		       type->size);
1542 		st_ops->type_id = type_id;
1543 
1544 		pr_debug("struct_ops init: struct %s(type_id=%d) %s found at offset %u\n",
1545 			 tname, type_id, var_name, vsi->offset);
1546 	}
1547 
1548 	return 0;
1549 }
1550 
1551 static int bpf_object_init_struct_ops(struct bpf_object *obj)
1552 {
1553 	const char *sec_name;
1554 	int sec_idx, err;
1555 
1556 	for (sec_idx = 0; sec_idx < obj->efile.sec_cnt; ++sec_idx) {
1557 		struct elf_sec_desc *desc = &obj->efile.secs[sec_idx];
1558 
1559 		if (desc->sec_type != SEC_ST_OPS)
1560 			continue;
1561 
1562 		sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1563 		if (!sec_name)
1564 			return -LIBBPF_ERRNO__FORMAT;
1565 
1566 		err = init_struct_ops_maps(obj, sec_name, sec_idx, desc->data);
1567 		if (err)
1568 			return err;
1569 	}
1570 
1571 	return 0;
1572 }
1573 
1574 static struct bpf_object *bpf_object__new(const char *path,
1575 					  const void *obj_buf,
1576 					  size_t obj_buf_sz,
1577 					  const char *obj_name)
1578 {
1579 	struct bpf_object *obj;
1580 	char *end;
1581 
1582 	obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
1583 	if (!obj) {
1584 		pr_warn("alloc memory failed for %s\n", path);
1585 		return ERR_PTR(-ENOMEM);
1586 	}
1587 
1588 	strcpy(obj->path, path);
1589 	if (obj_name) {
1590 		libbpf_strlcpy(obj->name, obj_name, sizeof(obj->name));
1591 	} else {
1592 		/* Using basename() GNU version which doesn't modify arg. */
1593 		libbpf_strlcpy(obj->name, basename((void *)path), sizeof(obj->name));
1594 		end = strchr(obj->name, '.');
1595 		if (end)
1596 			*end = 0;
1597 	}
1598 
1599 	obj->efile.fd = -1;
1600 	/*
1601 	 * Caller of this function should also call
1602 	 * bpf_object__elf_finish() after data collection to return
1603 	 * obj_buf to user. If not, we should duplicate the buffer to
1604 	 * avoid user freeing them before elf finish.
1605 	 */
1606 	obj->efile.obj_buf = obj_buf;
1607 	obj->efile.obj_buf_sz = obj_buf_sz;
1608 	obj->efile.btf_maps_shndx = -1;
1609 	obj->kconfig_map_idx = -1;
1610 	obj->arena_map_idx = -1;
1611 
1612 	obj->kern_version = get_kernel_version();
1613 	obj->state  = OBJ_OPEN;
1614 
1615 	return obj;
1616 }
1617 
1618 static void bpf_object__elf_finish(struct bpf_object *obj)
1619 {
1620 	if (!obj->efile.elf)
1621 		return;
1622 
1623 	elf_end(obj->efile.elf);
1624 	obj->efile.elf = NULL;
1625 	obj->efile.ehdr = NULL;
1626 	obj->efile.symbols = NULL;
1627 	obj->efile.arena_data = NULL;
1628 
1629 	zfree(&obj->efile.secs);
1630 	obj->efile.sec_cnt = 0;
1631 	zclose(obj->efile.fd);
1632 	obj->efile.obj_buf = NULL;
1633 	obj->efile.obj_buf_sz = 0;
1634 }
1635 
1636 static int bpf_object__elf_init(struct bpf_object *obj)
1637 {
1638 	Elf64_Ehdr *ehdr;
1639 	int err = 0;
1640 	Elf *elf;
1641 
1642 	if (obj->efile.elf) {
1643 		pr_warn("elf: init internal error\n");
1644 		return -LIBBPF_ERRNO__LIBELF;
1645 	}
1646 
1647 	if (obj->efile.obj_buf_sz > 0) {
1648 		/* obj_buf should have been validated by bpf_object__open_mem(). */
1649 		elf = elf_memory((char *)obj->efile.obj_buf, obj->efile.obj_buf_sz);
1650 	} else {
1651 		obj->efile.fd = open(obj->path, O_RDONLY | O_CLOEXEC);
1652 		if (obj->efile.fd < 0) {
1653 			err = -errno;
1654 			pr_warn("elf: failed to open %s: %s\n", obj->path, errstr(err));
1655 			return err;
1656 		}
1657 
1658 		elf = elf_begin(obj->efile.fd, ELF_C_READ_MMAP, NULL);
1659 	}
1660 
1661 	if (!elf) {
1662 		pr_warn("elf: failed to open %s as ELF file: %s\n", obj->path, elf_errmsg(-1));
1663 		err = -LIBBPF_ERRNO__LIBELF;
1664 		goto errout;
1665 	}
1666 
1667 	obj->efile.elf = elf;
1668 
1669 	if (elf_kind(elf) != ELF_K_ELF) {
1670 		err = -LIBBPF_ERRNO__FORMAT;
1671 		pr_warn("elf: '%s' is not a proper ELF object\n", obj->path);
1672 		goto errout;
1673 	}
1674 
1675 	if (gelf_getclass(elf) != ELFCLASS64) {
1676 		err = -LIBBPF_ERRNO__FORMAT;
1677 		pr_warn("elf: '%s' is not a 64-bit ELF object\n", obj->path);
1678 		goto errout;
1679 	}
1680 
1681 	obj->efile.ehdr = ehdr = elf64_getehdr(elf);
1682 	if (!obj->efile.ehdr) {
1683 		pr_warn("elf: failed to get ELF header from %s: %s\n", obj->path, elf_errmsg(-1));
1684 		err = -LIBBPF_ERRNO__FORMAT;
1685 		goto errout;
1686 	}
1687 
1688 	/* Validate ELF object endianness... */
1689 	if (ehdr->e_ident[EI_DATA] != ELFDATA2LSB &&
1690 	    ehdr->e_ident[EI_DATA] != ELFDATA2MSB) {
1691 		err = -LIBBPF_ERRNO__ENDIAN;
1692 		pr_warn("elf: '%s' has unknown byte order\n", obj->path);
1693 		goto errout;
1694 	}
1695 	/* and save after bpf_object_open() frees ELF data */
1696 	obj->byteorder = ehdr->e_ident[EI_DATA];
1697 
1698 	if (elf_getshdrstrndx(elf, &obj->efile.shstrndx)) {
1699 		pr_warn("elf: failed to get section names section index for %s: %s\n",
1700 			obj->path, elf_errmsg(-1));
1701 		err = -LIBBPF_ERRNO__FORMAT;
1702 		goto errout;
1703 	}
1704 
1705 	/* ELF is corrupted/truncated, avoid calling elf_strptr. */
1706 	if (!elf_rawdata(elf_getscn(elf, obj->efile.shstrndx), NULL)) {
1707 		pr_warn("elf: failed to get section names strings from %s: %s\n",
1708 			obj->path, elf_errmsg(-1));
1709 		err = -LIBBPF_ERRNO__FORMAT;
1710 		goto errout;
1711 	}
1712 
1713 	/* Old LLVM set e_machine to EM_NONE */
1714 	if (ehdr->e_type != ET_REL || (ehdr->e_machine && ehdr->e_machine != EM_BPF)) {
1715 		pr_warn("elf: %s is not a valid eBPF object file\n", obj->path);
1716 		err = -LIBBPF_ERRNO__FORMAT;
1717 		goto errout;
1718 	}
1719 
1720 	return 0;
1721 errout:
1722 	bpf_object__elf_finish(obj);
1723 	return err;
1724 }
1725 
1726 static bool is_native_endianness(struct bpf_object *obj)
1727 {
1728 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1729 	return obj->byteorder == ELFDATA2LSB;
1730 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
1731 	return obj->byteorder == ELFDATA2MSB;
1732 #else
1733 # error "Unrecognized __BYTE_ORDER__"
1734 #endif
1735 }
1736 
1737 static int
1738 bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
1739 {
1740 	if (!data) {
1741 		pr_warn("invalid license section in %s\n", obj->path);
1742 		return -LIBBPF_ERRNO__FORMAT;
1743 	}
1744 	/* libbpf_strlcpy() only copies first N - 1 bytes, so size + 1 won't
1745 	 * go over allowed ELF data section buffer
1746 	 */
1747 	libbpf_strlcpy(obj->license, data, min(size + 1, sizeof(obj->license)));
1748 	pr_debug("license of %s is %s\n", obj->path, obj->license);
1749 	return 0;
1750 }
1751 
1752 static int
1753 bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
1754 {
1755 	__u32 kver;
1756 
1757 	if (!data || size != sizeof(kver)) {
1758 		pr_warn("invalid kver section in %s\n", obj->path);
1759 		return -LIBBPF_ERRNO__FORMAT;
1760 	}
1761 	memcpy(&kver, data, sizeof(kver));
1762 	obj->kern_version = kver;
1763 	pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
1764 	return 0;
1765 }
1766 
1767 static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
1768 {
1769 	if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
1770 	    type == BPF_MAP_TYPE_HASH_OF_MAPS)
1771 		return true;
1772 	return false;
1773 }
1774 
1775 static int find_elf_sec_sz(const struct bpf_object *obj, const char *name, __u32 *size)
1776 {
1777 	Elf_Data *data;
1778 	Elf_Scn *scn;
1779 
1780 	if (!name)
1781 		return -EINVAL;
1782 
1783 	scn = elf_sec_by_name(obj, name);
1784 	data = elf_sec_data(obj, scn);
1785 	if (data) {
1786 		*size = data->d_size;
1787 		return 0; /* found it */
1788 	}
1789 
1790 	return -ENOENT;
1791 }
1792 
1793 static Elf64_Sym *find_elf_var_sym(const struct bpf_object *obj, const char *name)
1794 {
1795 	Elf_Data *symbols = obj->efile.symbols;
1796 	const char *sname;
1797 	size_t si;
1798 
1799 	for (si = 0; si < symbols->d_size / sizeof(Elf64_Sym); si++) {
1800 		Elf64_Sym *sym = elf_sym_by_idx(obj, si);
1801 
1802 		if (ELF64_ST_TYPE(sym->st_info) != STT_OBJECT)
1803 			continue;
1804 
1805 		if (ELF64_ST_BIND(sym->st_info) != STB_GLOBAL &&
1806 		    ELF64_ST_BIND(sym->st_info) != STB_WEAK)
1807 			continue;
1808 
1809 		sname = elf_sym_str(obj, sym->st_name);
1810 		if (!sname) {
1811 			pr_warn("failed to get sym name string for var %s\n", name);
1812 			return ERR_PTR(-EIO);
1813 		}
1814 		if (strcmp(name, sname) == 0)
1815 			return sym;
1816 	}
1817 
1818 	return ERR_PTR(-ENOENT);
1819 }
1820 
1821 #ifndef MFD_CLOEXEC
1822 #define MFD_CLOEXEC 0x0001U
1823 #endif
1824 #ifndef MFD_NOEXEC_SEAL
1825 #define MFD_NOEXEC_SEAL 0x0008U
1826 #endif
1827 
1828 static int create_placeholder_fd(void)
1829 {
1830 	unsigned int flags = MFD_CLOEXEC | MFD_NOEXEC_SEAL;
1831 	const char *name = "libbpf-placeholder-fd";
1832 	int fd;
1833 
1834 	fd = ensure_good_fd(sys_memfd_create(name, flags));
1835 	if (fd >= 0)
1836 		return fd;
1837 	else if (errno != EINVAL)
1838 		return -errno;
1839 
1840 	/* Possibly running on kernel without MFD_NOEXEC_SEAL */
1841 	fd = ensure_good_fd(sys_memfd_create(name, flags & ~MFD_NOEXEC_SEAL));
1842 	if (fd < 0)
1843 		return -errno;
1844 	return fd;
1845 }
1846 
1847 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
1848 {
1849 	struct bpf_map *map;
1850 	int err;
1851 
1852 	err = libbpf_ensure_mem((void **)&obj->maps, &obj->maps_cap,
1853 				sizeof(*obj->maps), obj->nr_maps + 1);
1854 	if (err)
1855 		return ERR_PTR(err);
1856 
1857 	map = &obj->maps[obj->nr_maps++];
1858 	map->obj = obj;
1859 	/* Preallocate map FD without actually creating BPF map just yet.
1860 	 * These map FD "placeholders" will be reused later without changing
1861 	 * FD value when map is actually created in the kernel.
1862 	 *
1863 	 * This is useful to be able to perform BPF program relocations
1864 	 * without having to create BPF maps before that step. This allows us
1865 	 * to finalize and load BTF very late in BPF object's loading phase,
1866 	 * right before BPF maps have to be created and BPF programs have to
1867 	 * be loaded. By having these map FD placeholders we can perform all
1868 	 * the sanitizations, relocations, and any other adjustments before we
1869 	 * start creating actual BPF kernel objects (BTF, maps, progs).
1870 	 */
1871 	map->fd = create_placeholder_fd();
1872 	if (map->fd < 0)
1873 		return ERR_PTR(map->fd);
1874 	map->inner_map_fd = -1;
1875 	map->autocreate = true;
1876 
1877 	return map;
1878 }
1879 
1880 static size_t array_map_mmap_sz(unsigned int value_sz, unsigned int max_entries)
1881 {
1882 	const long page_sz = sysconf(_SC_PAGE_SIZE);
1883 	size_t map_sz;
1884 
1885 	map_sz = (size_t)roundup(value_sz, 8) * max_entries;
1886 	map_sz = roundup(map_sz, page_sz);
1887 	return map_sz;
1888 }
1889 
1890 static size_t bpf_map_mmap_sz(const struct bpf_map *map)
1891 {
1892 	const long page_sz = sysconf(_SC_PAGE_SIZE);
1893 
1894 	switch (map->def.type) {
1895 	case BPF_MAP_TYPE_ARRAY:
1896 	case BPF_MAP_TYPE_PERCPU_ARRAY:
1897 		return array_map_mmap_sz(map->def.value_size, map->def.max_entries);
1898 	case BPF_MAP_TYPE_ARENA:
1899 		return page_sz * map->def.max_entries;
1900 	default:
1901 		return 0; /* not supported */
1902 	}
1903 }
1904 
1905 static int bpf_map_mmap_resize(struct bpf_map *map, size_t old_sz, size_t new_sz)
1906 {
1907 	void *mmaped;
1908 
1909 	if (!map->mmaped)
1910 		return -EINVAL;
1911 
1912 	if (old_sz == new_sz)
1913 		return 0;
1914 
1915 	mmaped = mmap(NULL, new_sz, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1916 	if (mmaped == MAP_FAILED)
1917 		return -errno;
1918 
1919 	memcpy(mmaped, map->mmaped, min(old_sz, new_sz));
1920 	munmap(map->mmaped, old_sz);
1921 	map->mmaped = mmaped;
1922 	return 0;
1923 }
1924 
1925 static char *internal_map_name(struct bpf_object *obj, const char *real_name,
1926 			       enum libbpf_map_type type)
1927 {
1928 	char map_name[BPF_OBJ_NAME_LEN], *p;
1929 	int pfx_len, sfx_len = max((size_t)7, strlen(real_name));
1930 
1931 	/* This is one of the more confusing parts of libbpf for various
1932 	 * reasons, some of which are historical. The original idea for naming
1933 	 * internal names was to include as much of BPF object name prefix as
1934 	 * possible, so that it can be distinguished from similar internal
1935 	 * maps of a different BPF object.
1936 	 * As an example, let's say we have bpf_object named 'my_object_name'
1937 	 * and internal map corresponding to '.rodata' ELF section. The final
1938 	 * map name advertised to user and to the kernel will be
1939 	 * 'my_objec.rodata', taking first 8 characters of object name and
1940 	 * entire 7 characters of '.rodata'.
1941 	 * Somewhat confusingly, if internal map ELF section name is shorter
1942 	 * than 7 characters, e.g., '.bss', we still reserve 7 characters
1943 	 * for the suffix, even though we only have 4 actual characters, and
1944 	 * resulting map will be called 'my_objec.bss', not even using all 15
1945 	 * characters allowed by the kernel. Oh well, at least the truncated
1946 	 * object name is somewhat consistent in this case. But if the map
1947 	 * name is '.kconfig', we'll still have entirety of '.kconfig' added
1948 	 * (8 chars) and thus will be left with only first 7 characters of the
1949 	 * object name ('my_obje'). Happy guessing, user, that the final map
1950 	 * name will be "my_obje.kconfig".
1951 	 * Now, with libbpf starting to support arbitrarily named .rodata.*
1952 	 * and .data.* data sections, it's possible that ELF section name is
1953 	 * longer than allowed 15 chars, so we now need to be careful to take
1954 	 * only up to 15 first characters of ELF name, taking no BPF object
1955 	 * name characters at all. So '.rodata.abracadabra' will result in
1956 	 * '.rodata.abracad' kernel and user-visible name.
1957 	 * We need to keep this convoluted logic intact for .data, .bss and
1958 	 * .rodata maps, but for new custom .data.custom and .rodata.custom
1959 	 * maps we use their ELF names as is, not prepending bpf_object name
1960 	 * in front. We still need to truncate them to 15 characters for the
1961 	 * kernel. Full name can be recovered for such maps by using DATASEC
1962 	 * BTF type associated with such map's value type, though.
1963 	 */
1964 	if (sfx_len >= BPF_OBJ_NAME_LEN)
1965 		sfx_len = BPF_OBJ_NAME_LEN - 1;
1966 
1967 	/*
1968 	 * Don't prefix the bpf_object name if this is a custom dot map
1969 	 * (containing two or more dots) or a percpu data map.
1970 	 */
1971 	if (strchr(real_name + 1, '.') != NULL || type == LIBBPF_MAP_PERCPU)
1972 		pfx_len = 0;
1973 	else
1974 		pfx_len = min((size_t)BPF_OBJ_NAME_LEN - sfx_len - 1, strlen(obj->name));
1975 
1976 	snprintf(map_name, sizeof(map_name), "%.*s%.*s", pfx_len, obj->name,
1977 		 sfx_len, real_name);
1978 
1979 	/* sanities map name to characters allowed by kernel */
1980 	for (p = map_name; *p && p < map_name + sizeof(map_name); p++)
1981 		if (!isalnum(*p) && *p != '_' && *p != '.')
1982 			*p = '_';
1983 
1984 	return strdup(map_name);
1985 }
1986 
1987 static int
1988 map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map);
1989 
1990 /* Internal BPF map is mmap()'able only if at least one of corresponding
1991  * DATASEC's VARs are to be exposed through BPF skeleton. I.e., it's a GLOBAL
1992  * variable and it's not marked as __hidden (which turns it into, effectively,
1993  * a STATIC variable).
1994  */
1995 static bool map_is_mmapable(struct bpf_object *obj, struct bpf_map *map)
1996 {
1997 	const struct btf_type *t, *vt;
1998 	struct btf_var_secinfo *vsi;
1999 	int i, n;
2000 
2001 	if (!map->btf_value_type_id)
2002 		return false;
2003 
2004 	/*
2005 	 * The internal PERCPU maps are not mmapable because the underlying
2006 	 * percpu_array maps do not have mmap support.
2007 	 */
2008 	if (map->libbpf_type == LIBBPF_MAP_PERCPU)
2009 		return false;
2010 
2011 	t = btf__type_by_id(obj->btf, map->btf_value_type_id);
2012 	if (!btf_is_datasec(t))
2013 		return false;
2014 
2015 	vsi = btf_var_secinfos(t);
2016 	for (i = 0, n = btf_vlen(t); i < n; i++, vsi++) {
2017 		vt = btf__type_by_id(obj->btf, vsi->type);
2018 		if (!btf_is_var(vt))
2019 			continue;
2020 
2021 		if (btf_var(vt)->linkage != BTF_VAR_STATIC)
2022 			return true;
2023 	}
2024 
2025 	return false;
2026 }
2027 
2028 static int
2029 bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
2030 			      const char *real_name, int sec_idx, void *data, size_t data_sz)
2031 {
2032 	bool is_percpu = type == LIBBPF_MAP_PERCPU;
2033 	struct bpf_map_def *def;
2034 	struct bpf_map *map;
2035 	size_t mmap_sz;
2036 	int err;
2037 
2038 	map = bpf_object__add_map(obj);
2039 	if (IS_ERR(map))
2040 		return PTR_ERR(map);
2041 
2042 	map->libbpf_type = type;
2043 	map->sec_idx = sec_idx;
2044 	map->sec_offset = 0;
2045 	map->real_name = strdup(real_name);
2046 	map->name = internal_map_name(obj, real_name, type);
2047 	if (!map->real_name || !map->name) {
2048 		zfree(&map->real_name);
2049 		zfree(&map->name);
2050 		return -ENOMEM;
2051 	}
2052 
2053 	def = &map->def;
2054 	def->type = is_percpu ? BPF_MAP_TYPE_PERCPU_ARRAY : BPF_MAP_TYPE_ARRAY;
2055 	def->key_size = sizeof(int);
2056 	def->value_size = data_sz;
2057 	def->max_entries = 1;
2058 	def->map_flags = type == LIBBPF_MAP_RODATA || type == LIBBPF_MAP_KCONFIG
2059 		? BPF_F_RDONLY_PROG : 0;
2060 
2061 	/* failures are fine because of maps like .rodata.str1.1 */
2062 	(void) map_fill_btf_type_info(obj, map);
2063 
2064 	if (map_is_mmapable(obj, map))
2065 		def->map_flags |= BPF_F_MMAPABLE;
2066 
2067 	pr_debug("map '%s' (global %sdata): at sec_idx %d, offset %zu, flags %x.\n",
2068 		 map->name, is_percpu ? "percpu " : "", map->sec_idx,
2069 		 map->sec_offset, def->map_flags);
2070 
2071 	mmap_sz = bpf_map_mmap_sz(map);
2072 	map->mmaped = mmap(NULL, mmap_sz, PROT_READ | PROT_WRITE,
2073 			   MAP_SHARED | MAP_ANONYMOUS, -1, 0);
2074 	if (map->mmaped == MAP_FAILED) {
2075 		err = -errno;
2076 		map->mmaped = NULL;
2077 		pr_warn("failed to alloc map '%s' content buffer: %s\n", map->name, errstr(err));
2078 		zfree(&map->real_name);
2079 		zfree(&map->name);
2080 		return err;
2081 	}
2082 
2083 	if (data)
2084 		memcpy(map->mmaped, data, data_sz);
2085 
2086 	pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
2087 	return 0;
2088 }
2089 
2090 static int bpf_object__init_global_data_maps(struct bpf_object *obj)
2091 {
2092 	struct elf_sec_desc *sec_desc;
2093 	const char *sec_name;
2094 	int err = 0, sec_idx;
2095 
2096 	/*
2097 	 * Populate obj->maps with libbpf internal maps.
2098 	 */
2099 	for (sec_idx = 1; sec_idx < obj->efile.sec_cnt; sec_idx++) {
2100 		sec_desc = &obj->efile.secs[sec_idx];
2101 
2102 		/* Skip recognized sections with size 0. */
2103 		if (!sec_desc->data || sec_desc->data->d_size == 0)
2104 			continue;
2105 
2106 		switch (sec_desc->sec_type) {
2107 		case SEC_DATA:
2108 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
2109 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
2110 							    sec_name, sec_idx,
2111 							    sec_desc->data->d_buf,
2112 							    sec_desc->data->d_size);
2113 			break;
2114 		case SEC_RODATA:
2115 			obj->has_rodata = true;
2116 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
2117 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
2118 							    sec_name, sec_idx,
2119 							    sec_desc->data->d_buf,
2120 							    sec_desc->data->d_size);
2121 			break;
2122 		case SEC_BSS:
2123 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
2124 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
2125 							    sec_name, sec_idx,
2126 							    NULL,
2127 							    sec_desc->data->d_size);
2128 			break;
2129 		case SEC_PERCPU:
2130 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
2131 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_PERCPU,
2132 							    sec_name, sec_idx,
2133 							    sec_desc->data->d_buf,
2134 							    sec_desc->data->d_size);
2135 			break;
2136 		default:
2137 			/* skip */
2138 			break;
2139 		}
2140 		if (err)
2141 			return err;
2142 	}
2143 	return 0;
2144 }
2145 
2146 
2147 static struct extern_desc *find_extern_by_name(const struct bpf_object *obj,
2148 					       const void *name)
2149 {
2150 	int i;
2151 
2152 	for (i = 0; i < obj->nr_extern; i++) {
2153 		if (strcmp(obj->externs[i].name, name) == 0)
2154 			return &obj->externs[i];
2155 	}
2156 	return NULL;
2157 }
2158 
2159 static struct extern_desc *find_extern_by_name_with_len(const struct bpf_object *obj,
2160 							const void *name, int len)
2161 {
2162 	const char *ext_name;
2163 	int i;
2164 
2165 	for (i = 0; i < obj->nr_extern; i++) {
2166 		ext_name = obj->externs[i].name;
2167 		if (strlen(ext_name) == len && strncmp(ext_name, name, len) == 0)
2168 			return &obj->externs[i];
2169 	}
2170 	return NULL;
2171 }
2172 
2173 static int set_kcfg_value_tri(struct extern_desc *ext, void *ext_val,
2174 			      char value)
2175 {
2176 	switch (ext->kcfg.type) {
2177 	case KCFG_BOOL:
2178 		if (value == 'm') {
2179 			pr_warn("extern (kcfg) '%s': value '%c' implies tristate or char type\n",
2180 				ext->name, value);
2181 			return -EINVAL;
2182 		}
2183 		*(bool *)ext_val = value == 'y' ? true : false;
2184 		break;
2185 	case KCFG_TRISTATE:
2186 		if (value == 'y')
2187 			*(enum libbpf_tristate *)ext_val = TRI_YES;
2188 		else if (value == 'm')
2189 			*(enum libbpf_tristate *)ext_val = TRI_MODULE;
2190 		else /* value == 'n' */
2191 			*(enum libbpf_tristate *)ext_val = TRI_NO;
2192 		break;
2193 	case KCFG_CHAR:
2194 		*(char *)ext_val = value;
2195 		break;
2196 	case KCFG_UNKNOWN:
2197 	case KCFG_INT:
2198 	case KCFG_CHAR_ARR:
2199 	default:
2200 		pr_warn("extern (kcfg) '%s': value '%c' implies bool, tristate, or char type\n",
2201 			ext->name, value);
2202 		return -EINVAL;
2203 	}
2204 	ext->is_set = true;
2205 	return 0;
2206 }
2207 
2208 static int set_kcfg_value_str(struct extern_desc *ext, char *ext_val,
2209 			      const char *value)
2210 {
2211 	size_t len;
2212 
2213 	if (ext->kcfg.type != KCFG_CHAR_ARR) {
2214 		pr_warn("extern (kcfg) '%s': value '%s' implies char array type\n",
2215 			ext->name, value);
2216 		return -EINVAL;
2217 	}
2218 
2219 	len = strlen(value);
2220 	if (len < 2 || value[len - 1] != '"') {
2221 		pr_warn("extern (kcfg) '%s': invalid string config '%s'\n",
2222 			ext->name, value);
2223 		return -EINVAL;
2224 	}
2225 
2226 	/* strip quotes */
2227 	len -= 2;
2228 	if (len >= ext->kcfg.sz) {
2229 		pr_warn("extern (kcfg) '%s': long string '%s' of (%zu bytes) truncated to %d bytes\n",
2230 			ext->name, value, len, ext->kcfg.sz - 1);
2231 		len = ext->kcfg.sz - 1;
2232 	}
2233 	memcpy(ext_val, value + 1, len);
2234 	ext_val[len] = '\0';
2235 	ext->is_set = true;
2236 	return 0;
2237 }
2238 
2239 static int parse_u64(const char *value, __u64 *res)
2240 {
2241 	char *value_end;
2242 	int err;
2243 
2244 	errno = 0;
2245 	*res = strtoull(value, &value_end, 0);
2246 	if (errno) {
2247 		err = -errno;
2248 		pr_warn("failed to parse '%s': %s\n", value, errstr(err));
2249 		return err;
2250 	}
2251 	if (*value_end) {
2252 		pr_warn("failed to parse '%s' as integer completely\n", value);
2253 		return -EINVAL;
2254 	}
2255 	return 0;
2256 }
2257 
2258 static bool is_kcfg_value_in_range(const struct extern_desc *ext, __u64 v)
2259 {
2260 	int bit_sz = ext->kcfg.sz * 8;
2261 
2262 	if (ext->kcfg.sz == 8)
2263 		return true;
2264 
2265 	/* Validate that value stored in u64 fits in integer of `ext->sz`
2266 	 * bytes size without any loss of information. If the target integer
2267 	 * is signed, we rely on the following limits of integer type of
2268 	 * Y bits and subsequent transformation:
2269 	 *
2270 	 *     -2^(Y-1) <= X           <= 2^(Y-1) - 1
2271 	 *            0 <= X + 2^(Y-1) <= 2^Y - 1
2272 	 *            0 <= X + 2^(Y-1) <  2^Y
2273 	 *
2274 	 *  For unsigned target integer, check that all the (64 - Y) bits are
2275 	 *  zero.
2276 	 */
2277 	if (ext->kcfg.is_signed)
2278 		return v + (1ULL << (bit_sz - 1)) < (1ULL << bit_sz);
2279 	else
2280 		return (v >> bit_sz) == 0;
2281 }
2282 
2283 static int set_kcfg_value_num(struct extern_desc *ext, void *ext_val,
2284 			      __u64 value)
2285 {
2286 	if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR &&
2287 	    ext->kcfg.type != KCFG_BOOL) {
2288 		pr_warn("extern (kcfg) '%s': value '%llu' implies integer, char, or boolean type\n",
2289 			ext->name, (unsigned long long)value);
2290 		return -EINVAL;
2291 	}
2292 	if (ext->kcfg.type == KCFG_BOOL && value > 1) {
2293 		pr_warn("extern (kcfg) '%s': value '%llu' isn't boolean compatible\n",
2294 			ext->name, (unsigned long long)value);
2295 		return -EINVAL;
2296 
2297 	}
2298 	if (!is_kcfg_value_in_range(ext, value)) {
2299 		pr_warn("extern (kcfg) '%s': value '%llu' doesn't fit in %d bytes\n",
2300 			ext->name, (unsigned long long)value, ext->kcfg.sz);
2301 		return -ERANGE;
2302 	}
2303 	switch (ext->kcfg.sz) {
2304 	case 1:
2305 		*(__u8 *)ext_val = value;
2306 		break;
2307 	case 2:
2308 		*(__u16 *)ext_val = value;
2309 		break;
2310 	case 4:
2311 		*(__u32 *)ext_val = value;
2312 		break;
2313 	case 8:
2314 		*(__u64 *)ext_val = value;
2315 		break;
2316 	default:
2317 		return -EINVAL;
2318 	}
2319 	ext->is_set = true;
2320 	return 0;
2321 }
2322 
2323 static int bpf_object__process_kconfig_line(struct bpf_object *obj,
2324 					    char *buf, void *data)
2325 {
2326 	struct extern_desc *ext;
2327 	char *sep, *value;
2328 	int len, err = 0;
2329 	void *ext_val;
2330 	__u64 num;
2331 
2332 	if (!str_has_pfx(buf, "CONFIG_"))
2333 		return 0;
2334 
2335 	sep = strchr(buf, '=');
2336 	if (!sep) {
2337 		pr_warn("failed to parse '%s': no separator\n", buf);
2338 		return -EINVAL;
2339 	}
2340 
2341 	/* Trim ending '\n' */
2342 	len = strlen(buf);
2343 	if (buf[len - 1] == '\n')
2344 		buf[len - 1] = '\0';
2345 	/* Split on '=' and ensure that a value is present. */
2346 	*sep = '\0';
2347 	if (!sep[1]) {
2348 		*sep = '=';
2349 		pr_warn("failed to parse '%s': no value\n", buf);
2350 		return -EINVAL;
2351 	}
2352 
2353 	ext = find_extern_by_name(obj, buf);
2354 	if (!ext || ext->is_set)
2355 		return 0;
2356 
2357 	ext_val = data + ext->kcfg.data_off;
2358 	value = sep + 1;
2359 
2360 	switch (*value) {
2361 	case 'y': case 'n': case 'm':
2362 		err = set_kcfg_value_tri(ext, ext_val, *value);
2363 		break;
2364 	case '"':
2365 		err = set_kcfg_value_str(ext, ext_val, value);
2366 		break;
2367 	default:
2368 		/* assume integer */
2369 		err = parse_u64(value, &num);
2370 		if (err) {
2371 			pr_warn("extern (kcfg) '%s': value '%s' isn't a valid integer\n", ext->name, value);
2372 			return err;
2373 		}
2374 		if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR) {
2375 			pr_warn("extern (kcfg) '%s': value '%s' implies integer type\n", ext->name, value);
2376 			return -EINVAL;
2377 		}
2378 		err = set_kcfg_value_num(ext, ext_val, num);
2379 		break;
2380 	}
2381 	if (err)
2382 		return err;
2383 	pr_debug("extern (kcfg) '%s': set to %s\n", ext->name, value);
2384 	return 0;
2385 }
2386 
2387 static int bpf_object__read_kconfig_file(struct bpf_object *obj, void *data)
2388 {
2389 	char buf[PATH_MAX];
2390 	struct utsname uts;
2391 	int len, err = 0;
2392 	gzFile file;
2393 
2394 	uname(&uts);
2395 	len = snprintf(buf, PATH_MAX, "/boot/config-%s", uts.release);
2396 	if (len < 0)
2397 		return -EINVAL;
2398 	else if (len >= PATH_MAX)
2399 		return -ENAMETOOLONG;
2400 
2401 	/* gzopen also accepts uncompressed files. */
2402 	file = gzopen(buf, "re");
2403 	if (!file)
2404 		file = gzopen("/proc/config.gz", "re");
2405 
2406 	if (!file) {
2407 		pr_warn("failed to open system Kconfig\n");
2408 		return -ENOENT;
2409 	}
2410 
2411 	while (gzgets(file, buf, sizeof(buf))) {
2412 		err = bpf_object__process_kconfig_line(obj, buf, data);
2413 		if (err) {
2414 			pr_warn("error parsing system Kconfig line '%s': %s\n",
2415 				buf, errstr(err));
2416 			goto out;
2417 		}
2418 	}
2419 
2420 out:
2421 	gzclose(file);
2422 	return err;
2423 }
2424 
2425 static int bpf_object__read_kconfig_mem(struct bpf_object *obj,
2426 					const char *config, void *data)
2427 {
2428 	char buf[PATH_MAX];
2429 	int err = 0;
2430 	FILE *file;
2431 
2432 	file = fmemopen((void *)config, strlen(config), "r");
2433 	if (!file) {
2434 		err = -errno;
2435 		pr_warn("failed to open in-memory Kconfig: %s\n", errstr(err));
2436 		return err;
2437 	}
2438 
2439 	while (fgets(buf, sizeof(buf), file)) {
2440 		err = bpf_object__process_kconfig_line(obj, buf, data);
2441 		if (err) {
2442 			pr_warn("error parsing in-memory Kconfig line '%s': %s\n",
2443 				buf, errstr(err));
2444 			break;
2445 		}
2446 	}
2447 
2448 	fclose(file);
2449 	return err;
2450 }
2451 
2452 static int bpf_object__init_kconfig_map(struct bpf_object *obj)
2453 {
2454 	struct extern_desc *last_ext = NULL, *ext;
2455 	size_t map_sz;
2456 	int i, err;
2457 
2458 	for (i = 0; i < obj->nr_extern; i++) {
2459 		ext = &obj->externs[i];
2460 		if (ext->type == EXT_KCFG)
2461 			last_ext = ext;
2462 	}
2463 
2464 	if (!last_ext)
2465 		return 0;
2466 
2467 	map_sz = last_ext->kcfg.data_off + last_ext->kcfg.sz;
2468 	err = bpf_object__init_internal_map(obj, LIBBPF_MAP_KCONFIG,
2469 					    ".kconfig", obj->efile.symbols_shndx,
2470 					    NULL, map_sz);
2471 	if (err)
2472 		return err;
2473 
2474 	obj->kconfig_map_idx = obj->nr_maps - 1;
2475 
2476 	return 0;
2477 }
2478 
2479 const struct btf_type *
2480 skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id)
2481 {
2482 	const struct btf_type *t = btf__type_by_id(btf, id);
2483 
2484 	if (res_id)
2485 		*res_id = id;
2486 
2487 	while (btf_is_mod(t) || btf_is_typedef(t)) {
2488 		if (res_id)
2489 			*res_id = t->type;
2490 		t = btf__type_by_id(btf, t->type);
2491 	}
2492 
2493 	return t;
2494 }
2495 
2496 static const struct btf_type *
2497 resolve_func_ptr(const struct btf *btf, __u32 id, __u32 *res_id)
2498 {
2499 	const struct btf_type *t;
2500 
2501 	t = skip_mods_and_typedefs(btf, id, NULL);
2502 	if (!btf_is_ptr(t))
2503 		return NULL;
2504 
2505 	t = skip_mods_and_typedefs(btf, t->type, res_id);
2506 
2507 	return btf_is_func_proto(t) ? t : NULL;
2508 }
2509 
2510 static const char *__btf_kind_str(__u16 kind)
2511 {
2512 	switch (kind) {
2513 	case BTF_KIND_UNKN: return "void";
2514 	case BTF_KIND_INT: return "int";
2515 	case BTF_KIND_PTR: return "ptr";
2516 	case BTF_KIND_ARRAY: return "array";
2517 	case BTF_KIND_STRUCT: return "struct";
2518 	case BTF_KIND_UNION: return "union";
2519 	case BTF_KIND_ENUM: return "enum";
2520 	case BTF_KIND_FWD: return "fwd";
2521 	case BTF_KIND_TYPEDEF: return "typedef";
2522 	case BTF_KIND_VOLATILE: return "volatile";
2523 	case BTF_KIND_CONST: return "const";
2524 	case BTF_KIND_RESTRICT: return "restrict";
2525 	case BTF_KIND_FUNC: return "func";
2526 	case BTF_KIND_FUNC_PROTO: return "func_proto";
2527 	case BTF_KIND_VAR: return "var";
2528 	case BTF_KIND_DATASEC: return "datasec";
2529 	case BTF_KIND_FLOAT: return "float";
2530 	case BTF_KIND_DECL_TAG: return "decl_tag";
2531 	case BTF_KIND_TYPE_TAG: return "type_tag";
2532 	case BTF_KIND_ENUM64: return "enum64";
2533 	case BTF_KIND_LOC_PARAM: return "loc_param";
2534 	case BTF_KIND_LOC_PROTO: return "loc_proto";
2535 	case BTF_KIND_LOCSEC: return "locsec";
2536 	default: return "unknown";
2537 	}
2538 }
2539 
2540 const char *btf_kind_str(const struct btf_type *t)
2541 {
2542 	return __btf_kind_str(btf_kind(t));
2543 }
2544 
2545 /*
2546  * Fetch integer attribute of BTF map definition. Such attributes are
2547  * represented using a pointer to an array, in which dimensionality of array
2548  * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
2549  * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
2550  * type definition, while using only sizeof(void *) space in ELF data section.
2551  */
2552 static bool get_map_field_int(const char *map_name, const struct btf *btf,
2553 			      const struct btf_member *m, __u32 *res)
2554 {
2555 	const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
2556 	const char *name = btf__name_by_offset(btf, m->name_off);
2557 	const struct btf_array *arr_info;
2558 	const struct btf_type *arr_t;
2559 
2560 	if (!btf_is_ptr(t)) {
2561 		pr_warn("map '%s': attr '%s': expected PTR, got %s.\n",
2562 			map_name, name, btf_kind_str(t));
2563 		return false;
2564 	}
2565 
2566 	arr_t = btf__type_by_id(btf, t->type);
2567 	if (!arr_t) {
2568 		pr_warn("map '%s': attr '%s': type [%u] not found.\n",
2569 			map_name, name, t->type);
2570 		return false;
2571 	}
2572 	if (!btf_is_array(arr_t)) {
2573 		pr_warn("map '%s': attr '%s': expected ARRAY, got %s.\n",
2574 			map_name, name, btf_kind_str(arr_t));
2575 		return false;
2576 	}
2577 	arr_info = btf_array(arr_t);
2578 	*res = arr_info->nelems;
2579 	return true;
2580 }
2581 
2582 static bool get_map_field_long(const char *map_name, const struct btf *btf,
2583 			       const struct btf_member *m, __u64 *res)
2584 {
2585 	const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
2586 	const char *name = btf__name_by_offset(btf, m->name_off);
2587 
2588 	if (btf_is_ptr(t)) {
2589 		__u32 res32;
2590 		bool ret;
2591 
2592 		ret = get_map_field_int(map_name, btf, m, &res32);
2593 		if (ret)
2594 			*res = (__u64)res32;
2595 		return ret;
2596 	}
2597 
2598 	if (!btf_is_enum(t) && !btf_is_enum64(t)) {
2599 		pr_warn("map '%s': attr '%s': expected ENUM or ENUM64, got %s.\n",
2600 			map_name, name, btf_kind_str(t));
2601 		return false;
2602 	}
2603 
2604 	if (btf_vlen(t) != 1) {
2605 		pr_warn("map '%s': attr '%s': invalid __ulong\n",
2606 			map_name, name);
2607 		return false;
2608 	}
2609 
2610 	if (btf_is_enum(t)) {
2611 		const struct btf_enum *e = btf_enum(t);
2612 
2613 		*res = e->val;
2614 	} else {
2615 		const struct btf_enum64 *e = btf_enum64(t);
2616 
2617 		*res = btf_enum64_value(e);
2618 	}
2619 	return true;
2620 }
2621 
2622 static int pathname_concat(char *buf, size_t buf_sz, const char *path, const char *name)
2623 {
2624 	int len;
2625 
2626 	len = snprintf(buf, buf_sz, "%s/%s", path, name);
2627 	if (len < 0)
2628 		return -EINVAL;
2629 	if (len >= buf_sz)
2630 		return -ENAMETOOLONG;
2631 
2632 	return 0;
2633 }
2634 
2635 static int build_map_pin_path(struct bpf_map *map, const char *path)
2636 {
2637 	char buf[PATH_MAX];
2638 	int err;
2639 
2640 	if (!path)
2641 		path = BPF_FS_DEFAULT_PATH;
2642 
2643 	err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
2644 	if (err)
2645 		return err;
2646 
2647 	return bpf_map__set_pin_path(map, buf);
2648 }
2649 
2650 /* should match definition in bpf_helpers.h */
2651 enum libbpf_pin_type {
2652 	LIBBPF_PIN_NONE,
2653 	/* PIN_BY_NAME: pin maps by name (in /sys/fs/bpf by default) */
2654 	LIBBPF_PIN_BY_NAME,
2655 };
2656 
2657 int parse_btf_map_def(const char *map_name, struct btf *btf,
2658 		      const struct btf_type *def_t, bool strict,
2659 		      struct btf_map_def *map_def, struct btf_map_def *inner_def)
2660 {
2661 	const struct btf_type *t;
2662 	const struct btf_member *m;
2663 	bool is_inner = inner_def == NULL;
2664 	int vlen, i;
2665 
2666 	vlen = btf_vlen(def_t);
2667 	m = btf_members(def_t);
2668 	for (i = 0; i < vlen; i++, m++) {
2669 		const char *name = btf__name_by_offset(btf, m->name_off);
2670 
2671 		if (!name) {
2672 			pr_warn("map '%s': invalid field #%d.\n", map_name, i);
2673 			return -EINVAL;
2674 		}
2675 		if (strcmp(name, "type") == 0) {
2676 			if (!get_map_field_int(map_name, btf, m, &map_def->map_type))
2677 				return -EINVAL;
2678 			map_def->parts |= MAP_DEF_MAP_TYPE;
2679 		} else if (strcmp(name, "max_entries") == 0) {
2680 			if (!get_map_field_int(map_name, btf, m, &map_def->max_entries))
2681 				return -EINVAL;
2682 			map_def->parts |= MAP_DEF_MAX_ENTRIES;
2683 		} else if (strcmp(name, "map_flags") == 0) {
2684 			if (!get_map_field_int(map_name, btf, m, &map_def->map_flags))
2685 				return -EINVAL;
2686 			map_def->parts |= MAP_DEF_MAP_FLAGS;
2687 		} else if (strcmp(name, "numa_node") == 0) {
2688 			if (!get_map_field_int(map_name, btf, m, &map_def->numa_node))
2689 				return -EINVAL;
2690 			map_def->parts |= MAP_DEF_NUMA_NODE;
2691 		} else if (strcmp(name, "key_size") == 0) {
2692 			__u32 sz;
2693 
2694 			if (!get_map_field_int(map_name, btf, m, &sz))
2695 				return -EINVAL;
2696 			if (map_def->key_size && map_def->key_size != sz) {
2697 				pr_warn("map '%s': conflicting key size %u != %u.\n",
2698 					map_name, map_def->key_size, sz);
2699 				return -EINVAL;
2700 			}
2701 			map_def->key_size = sz;
2702 			map_def->parts |= MAP_DEF_KEY_SIZE;
2703 		} else if (strcmp(name, "key") == 0) {
2704 			__s64 sz;
2705 
2706 			t = btf__type_by_id(btf, m->type);
2707 			if (!t) {
2708 				pr_warn("map '%s': key type [%u] not found.\n",
2709 					map_name, m->type);
2710 				return -EINVAL;
2711 			}
2712 			if (!btf_is_ptr(t)) {
2713 				pr_warn("map '%s': key spec is not PTR: %s.\n",
2714 					map_name, btf_kind_str(t));
2715 				return -EINVAL;
2716 			}
2717 			sz = btf__resolve_size(btf, t->type);
2718 			if (sz < 0) {
2719 				pr_warn("map '%s': can't determine key size for type [%u]: %zd.\n",
2720 					map_name, t->type, (ssize_t)sz);
2721 				return sz;
2722 			}
2723 			if (map_def->key_size && map_def->key_size != sz) {
2724 				pr_warn("map '%s': conflicting key size %u != %zd.\n",
2725 					map_name, map_def->key_size, (ssize_t)sz);
2726 				return -EINVAL;
2727 			}
2728 			map_def->key_size = sz;
2729 			map_def->key_type_id = t->type;
2730 			map_def->parts |= MAP_DEF_KEY_SIZE | MAP_DEF_KEY_TYPE;
2731 		} else if (strcmp(name, "value_size") == 0) {
2732 			__u32 sz;
2733 
2734 			if (!get_map_field_int(map_name, btf, m, &sz))
2735 				return -EINVAL;
2736 			if (map_def->value_size && map_def->value_size != sz) {
2737 				pr_warn("map '%s': conflicting value size %u != %u.\n",
2738 					map_name, map_def->value_size, sz);
2739 				return -EINVAL;
2740 			}
2741 			map_def->value_size = sz;
2742 			map_def->parts |= MAP_DEF_VALUE_SIZE;
2743 		} else if (strcmp(name, "value") == 0) {
2744 			__s64 sz;
2745 
2746 			t = btf__type_by_id(btf, m->type);
2747 			if (!t) {
2748 				pr_warn("map '%s': value type [%u] not found.\n",
2749 					map_name, m->type);
2750 				return -EINVAL;
2751 			}
2752 			if (!btf_is_ptr(t)) {
2753 				pr_warn("map '%s': value spec is not PTR: %s.\n",
2754 					map_name, btf_kind_str(t));
2755 				return -EINVAL;
2756 			}
2757 			sz = btf__resolve_size(btf, t->type);
2758 			if (sz < 0) {
2759 				pr_warn("map '%s': can't determine value size for type [%u]: %zd.\n",
2760 					map_name, t->type, (ssize_t)sz);
2761 				return sz;
2762 			}
2763 			if (map_def->value_size && map_def->value_size != sz) {
2764 				pr_warn("map '%s': conflicting value size %u != %zd.\n",
2765 					map_name, map_def->value_size, (ssize_t)sz);
2766 				return -EINVAL;
2767 			}
2768 			map_def->value_size = sz;
2769 			map_def->value_type_id = t->type;
2770 			map_def->parts |= MAP_DEF_VALUE_SIZE | MAP_DEF_VALUE_TYPE;
2771 		}
2772 		else if (strcmp(name, "values") == 0) {
2773 			bool is_map_in_map = bpf_map_type__is_map_in_map(map_def->map_type);
2774 			bool is_prog_array = map_def->map_type == BPF_MAP_TYPE_PROG_ARRAY;
2775 			const char *desc = is_map_in_map ? "map-in-map inner" : "prog-array value";
2776 			char inner_map_name[128];
2777 			int err;
2778 
2779 			if (is_inner) {
2780 				pr_warn("map '%s': multi-level inner maps not supported.\n",
2781 					map_name);
2782 				return -ENOTSUP;
2783 			}
2784 			if (i != vlen - 1) {
2785 				pr_warn("map '%s': '%s' member should be last.\n",
2786 					map_name, name);
2787 				return -EINVAL;
2788 			}
2789 			if (!is_map_in_map && !is_prog_array) {
2790 				pr_warn("map '%s': should be map-in-map or prog-array.\n",
2791 					map_name);
2792 				return -ENOTSUP;
2793 			}
2794 			if (map_def->value_size && map_def->value_size != 4) {
2795 				pr_warn("map '%s': conflicting value size %u != 4.\n",
2796 					map_name, map_def->value_size);
2797 				return -EINVAL;
2798 			}
2799 			map_def->value_size = 4;
2800 			t = btf__type_by_id(btf, m->type);
2801 			if (!t) {
2802 				pr_warn("map '%s': %s type [%u] not found.\n",
2803 					map_name, desc, m->type);
2804 				return -EINVAL;
2805 			}
2806 			if (!btf_is_array(t) || btf_array(t)->nelems) {
2807 				pr_warn("map '%s': %s spec is not a zero-sized array.\n",
2808 					map_name, desc);
2809 				return -EINVAL;
2810 			}
2811 			t = skip_mods_and_typedefs(btf, btf_array(t)->type, NULL);
2812 			if (!btf_is_ptr(t)) {
2813 				pr_warn("map '%s': %s def is of unexpected kind %s.\n",
2814 					map_name, desc, btf_kind_str(t));
2815 				return -EINVAL;
2816 			}
2817 			t = skip_mods_and_typedefs(btf, t->type, NULL);
2818 			if (is_prog_array) {
2819 				if (!btf_is_func_proto(t)) {
2820 					pr_warn("map '%s': prog-array value def is of unexpected kind %s.\n",
2821 						map_name, btf_kind_str(t));
2822 					return -EINVAL;
2823 				}
2824 				continue;
2825 			}
2826 			if (!btf_is_struct(t)) {
2827 				pr_warn("map '%s': map-in-map inner def is of unexpected kind %s.\n",
2828 					map_name, btf_kind_str(t));
2829 				return -EINVAL;
2830 			}
2831 
2832 			snprintf(inner_map_name, sizeof(inner_map_name), "%s.inner", map_name);
2833 			err = parse_btf_map_def(inner_map_name, btf, t, strict, inner_def, NULL);
2834 			if (err)
2835 				return err;
2836 
2837 			map_def->parts |= MAP_DEF_INNER_MAP;
2838 		} else if (strcmp(name, "pinning") == 0) {
2839 			__u32 val;
2840 
2841 			if (is_inner) {
2842 				pr_warn("map '%s': inner def can't be pinned.\n", map_name);
2843 				return -EINVAL;
2844 			}
2845 			if (!get_map_field_int(map_name, btf, m, &val))
2846 				return -EINVAL;
2847 			if (val != LIBBPF_PIN_NONE && val != LIBBPF_PIN_BY_NAME) {
2848 				pr_warn("map '%s': invalid pinning value %u.\n",
2849 					map_name, val);
2850 				return -EINVAL;
2851 			}
2852 			map_def->pinning = val;
2853 			map_def->parts |= MAP_DEF_PINNING;
2854 		} else if (strcmp(name, "map_extra") == 0) {
2855 			__u64 map_extra;
2856 
2857 			if (!get_map_field_long(map_name, btf, m, &map_extra))
2858 				return -EINVAL;
2859 			map_def->map_extra = map_extra;
2860 			map_def->parts |= MAP_DEF_MAP_EXTRA;
2861 		} else {
2862 			if (strict) {
2863 				pr_warn("map '%s': unknown field '%s'.\n", map_name, name);
2864 				return -ENOTSUP;
2865 			}
2866 			pr_debug("map '%s': ignoring unknown field '%s'.\n", map_name, name);
2867 		}
2868 	}
2869 
2870 	if (map_def->map_type == BPF_MAP_TYPE_UNSPEC) {
2871 		pr_warn("map '%s': map type isn't specified.\n", map_name);
2872 		return -EINVAL;
2873 	}
2874 
2875 	return 0;
2876 }
2877 
2878 static size_t adjust_ringbuf_sz(size_t sz)
2879 {
2880 	__u32 page_sz = sysconf(_SC_PAGE_SIZE);
2881 	__u32 mul;
2882 
2883 	/* if user forgot to set any size, make sure they see error */
2884 	if (sz == 0)
2885 		return 0;
2886 	/* Kernel expects BPF_MAP_TYPE_RINGBUF's max_entries to be
2887 	 * a power-of-2 multiple of kernel's page size. If user diligently
2888 	 * satisfied these conditions, pass the size through.
2889 	 */
2890 	if ((sz % page_sz) == 0 && is_pow_of_2(sz / page_sz))
2891 		return sz;
2892 
2893 	/* Otherwise find closest (page_sz * power_of_2) product bigger than
2894 	 * user-set size to satisfy both user size request and kernel
2895 	 * requirements and substitute correct max_entries for map creation.
2896 	 */
2897 	for (mul = 1; mul <= UINT_MAX / page_sz; mul <<= 1) {
2898 		if (mul * page_sz > sz)
2899 			return mul * page_sz;
2900 	}
2901 
2902 	/* if it's impossible to satisfy the conditions (i.e., user size is
2903 	 * very close to UINT_MAX but is not a power-of-2 multiple of
2904 	 * page_size) then just return original size and let kernel reject it
2905 	 */
2906 	return sz;
2907 }
2908 
2909 static bool map_is_ringbuf(const struct bpf_map *map)
2910 {
2911 	return map->def.type == BPF_MAP_TYPE_RINGBUF ||
2912 	       map->def.type == BPF_MAP_TYPE_USER_RINGBUF;
2913 }
2914 
2915 static void fill_map_from_def(struct bpf_map *map, const struct btf_map_def *def)
2916 {
2917 	map->def.type = def->map_type;
2918 	map->def.key_size = def->key_size;
2919 	map->def.value_size = def->value_size;
2920 	map->def.max_entries = def->max_entries;
2921 	map->def.map_flags = def->map_flags;
2922 	map->map_extra = def->map_extra;
2923 
2924 	map->numa_node = def->numa_node;
2925 	map->btf_key_type_id = def->key_type_id;
2926 	map->btf_value_type_id = def->value_type_id;
2927 
2928 	/* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
2929 	if (map_is_ringbuf(map))
2930 		map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
2931 
2932 	if (def->parts & MAP_DEF_MAP_TYPE)
2933 		pr_debug("map '%s': found type = %u.\n", map->name, def->map_type);
2934 
2935 	if (def->parts & MAP_DEF_KEY_TYPE)
2936 		pr_debug("map '%s': found key [%u], sz = %u.\n",
2937 			 map->name, def->key_type_id, def->key_size);
2938 	else if (def->parts & MAP_DEF_KEY_SIZE)
2939 		pr_debug("map '%s': found key_size = %u.\n", map->name, def->key_size);
2940 
2941 	if (def->parts & MAP_DEF_VALUE_TYPE)
2942 		pr_debug("map '%s': found value [%u], sz = %u.\n",
2943 			 map->name, def->value_type_id, def->value_size);
2944 	else if (def->parts & MAP_DEF_VALUE_SIZE)
2945 		pr_debug("map '%s': found value_size = %u.\n", map->name, def->value_size);
2946 
2947 	if (def->parts & MAP_DEF_MAX_ENTRIES)
2948 		pr_debug("map '%s': found max_entries = %u.\n", map->name, def->max_entries);
2949 	if (def->parts & MAP_DEF_MAP_FLAGS)
2950 		pr_debug("map '%s': found map_flags = 0x%x.\n", map->name, def->map_flags);
2951 	if (def->parts & MAP_DEF_MAP_EXTRA)
2952 		pr_debug("map '%s': found map_extra = 0x%llx.\n", map->name,
2953 			 (unsigned long long)def->map_extra);
2954 	if (def->parts & MAP_DEF_PINNING)
2955 		pr_debug("map '%s': found pinning = %u.\n", map->name, def->pinning);
2956 	if (def->parts & MAP_DEF_NUMA_NODE)
2957 		pr_debug("map '%s': found numa_node = %u.\n", map->name, def->numa_node);
2958 
2959 	if (def->parts & MAP_DEF_INNER_MAP)
2960 		pr_debug("map '%s': found inner map definition.\n", map->name);
2961 }
2962 
2963 static const char *btf_var_linkage_str(__u32 linkage)
2964 {
2965 	switch (linkage) {
2966 	case BTF_VAR_STATIC: return "static";
2967 	case BTF_VAR_GLOBAL_ALLOCATED: return "global";
2968 	case BTF_VAR_GLOBAL_EXTERN: return "extern";
2969 	default: return "unknown";
2970 	}
2971 }
2972 
2973 static int bpf_object__init_user_btf_map(struct bpf_object *obj,
2974 					 const struct btf_type *sec,
2975 					 int var_idx, int sec_idx,
2976 					 const Elf_Data *data, bool strict,
2977 					 const char *pin_root_path)
2978 {
2979 	struct btf_map_def map_def = {}, inner_def = {};
2980 	const struct btf_type *var, *def;
2981 	const struct btf_var_secinfo *vi;
2982 	const struct btf_var *var_extra;
2983 	const char *map_name;
2984 	struct bpf_map *map;
2985 	int err;
2986 
2987 	vi = btf_var_secinfos(sec) + var_idx;
2988 	var = btf__type_by_id(obj->btf, vi->type);
2989 	var_extra = btf_var(var);
2990 	map_name = btf__name_by_offset(obj->btf, var->name_off);
2991 
2992 	if (str_is_empty(map_name)) {
2993 		pr_warn("map #%d: empty name.\n", var_idx);
2994 		return -EINVAL;
2995 	}
2996 	if ((__u64)vi->offset + vi->size > data->d_size) {
2997 		pr_warn("map '%s' BTF data is corrupted.\n", map_name);
2998 		return -EINVAL;
2999 	}
3000 	if (!btf_is_var(var)) {
3001 		pr_warn("map '%s': unexpected var kind %s.\n",
3002 			map_name, btf_kind_str(var));
3003 		return -EINVAL;
3004 	}
3005 	if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED) {
3006 		pr_warn("map '%s': unsupported map linkage %s.\n",
3007 			map_name, btf_var_linkage_str(var_extra->linkage));
3008 		return -EOPNOTSUPP;
3009 	}
3010 
3011 	def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
3012 	if (!btf_is_struct(def)) {
3013 		pr_warn("map '%s': unexpected def kind %s.\n",
3014 			map_name, btf_kind_str(var));
3015 		return -EINVAL;
3016 	}
3017 	if (def->size > vi->size) {
3018 		pr_warn("map '%s': invalid def size.\n", map_name);
3019 		return -EINVAL;
3020 	}
3021 
3022 	map = bpf_object__add_map(obj);
3023 	if (IS_ERR(map))
3024 		return PTR_ERR(map);
3025 	map->name = strdup(map_name);
3026 	if (!map->name) {
3027 		pr_warn("map '%s': failed to alloc map name.\n", map_name);
3028 		return -ENOMEM;
3029 	}
3030 	map->libbpf_type = LIBBPF_MAP_UNSPEC;
3031 	map->def.type = BPF_MAP_TYPE_UNSPEC;
3032 	map->sec_idx = sec_idx;
3033 	map->sec_offset = vi->offset;
3034 	map->btf_var_idx = var_idx;
3035 	pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
3036 		 map_name, map->sec_idx, map->sec_offset);
3037 
3038 	err = parse_btf_map_def(map->name, obj->btf, def, strict, &map_def, &inner_def);
3039 	if (err)
3040 		return err;
3041 
3042 	fill_map_from_def(map, &map_def);
3043 
3044 	if (map_def.pinning == LIBBPF_PIN_BY_NAME) {
3045 		err = build_map_pin_path(map, pin_root_path);
3046 		if (err) {
3047 			pr_warn("map '%s': couldn't build pin path.\n", map->name);
3048 			return err;
3049 		}
3050 	}
3051 
3052 	if (map_def.parts & MAP_DEF_INNER_MAP) {
3053 		map->inner_map = calloc(1, sizeof(*map->inner_map));
3054 		if (!map->inner_map)
3055 			return -ENOMEM;
3056 		map->inner_map->fd = create_placeholder_fd();
3057 		if (map->inner_map->fd < 0)
3058 			return map->inner_map->fd;
3059 		map->inner_map->sec_idx = sec_idx;
3060 		map->inner_map->name = malloc(strlen(map_name) + sizeof(".inner") + 1);
3061 		if (!map->inner_map->name)
3062 			return -ENOMEM;
3063 		sprintf(map->inner_map->name, "%s.inner", map_name);
3064 
3065 		fill_map_from_def(map->inner_map, &inner_def);
3066 	}
3067 
3068 	err = map_fill_btf_type_info(obj, map);
3069 	if (err)
3070 		return err;
3071 
3072 	return 0;
3073 }
3074 
3075 static int init_arena_map_data(struct bpf_object *obj, struct bpf_map *map,
3076 			       void *data, size_t data_sz)
3077 {
3078 	obj->arena_data = malloc(data_sz);
3079 	if (!obj->arena_data)
3080 		return -ENOMEM;
3081 	memcpy(obj->arena_data, data, data_sz);
3082 	obj->arena_data_sz = data_sz;
3083 
3084 	/* make bpf_map__init_value() work for ARENA maps */
3085 	map->mmaped = obj->arena_data;
3086 
3087 	return 0;
3088 }
3089 
3090 static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict,
3091 					  const char *pin_root_path)
3092 {
3093 	const struct btf_type *sec = NULL;
3094 	int nr_types, i, vlen, err;
3095 	const struct btf_type *t;
3096 	const char *name;
3097 	Elf_Data *data;
3098 	Elf_Scn *scn;
3099 
3100 	if (obj->efile.btf_maps_shndx < 0)
3101 		return 0;
3102 
3103 	scn = elf_sec_by_idx(obj, obj->efile.btf_maps_shndx);
3104 	data = elf_sec_data(obj, scn);
3105 	if (!data) {
3106 		pr_warn("elf: failed to get %s map definitions for %s\n",
3107 			MAPS_ELF_SEC, obj->path);
3108 		return -EINVAL;
3109 	}
3110 
3111 	nr_types = btf__type_cnt(obj->btf);
3112 	for (i = 1; i < nr_types; i++) {
3113 		t = btf__type_by_id(obj->btf, i);
3114 		if (!btf_is_datasec(t))
3115 			continue;
3116 		name = btf__name_by_offset(obj->btf, t->name_off);
3117 		if (strcmp(name, MAPS_ELF_SEC) == 0) {
3118 			sec = t;
3119 			obj->efile.btf_maps_sec_btf_id = i;
3120 			break;
3121 		}
3122 	}
3123 
3124 	if (!sec) {
3125 		pr_warn("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
3126 		return -ENOENT;
3127 	}
3128 
3129 	vlen = btf_vlen(sec);
3130 	for (i = 0; i < vlen; i++) {
3131 		err = bpf_object__init_user_btf_map(obj, sec, i,
3132 						    obj->efile.btf_maps_shndx,
3133 						    data, strict,
3134 						    pin_root_path);
3135 		if (err)
3136 			return err;
3137 	}
3138 
3139 	for (i = 0; i < obj->nr_maps; i++) {
3140 		struct bpf_map *map = &obj->maps[i];
3141 
3142 		if (map->def.type != BPF_MAP_TYPE_ARENA)
3143 			continue;
3144 
3145 		if (obj->arena_map_idx >= 0) {
3146 			pr_warn("map '%s': only single ARENA map is supported (map '%s' is also ARENA)\n",
3147 				map->name, obj->maps[obj->arena_map_idx].name);
3148 			return -EINVAL;
3149 		}
3150 		obj->arena_map_idx = i;
3151 
3152 		if (obj->efile.arena_data) {
3153 			err = init_arena_map_data(obj, map, obj->efile.arena_data->d_buf,
3154 						  obj->efile.arena_data->d_size);
3155 			if (err)
3156 				return err;
3157 		}
3158 	}
3159 	if (obj->efile.arena_data && obj->arena_map_idx < 0) {
3160 		pr_warn("elf: sec '%s': to use global __arena variables the ARENA map should be explicitly declared in SEC(\".maps\")\n",
3161 			ARENA_SEC);
3162 		return -ENOENT;
3163 	}
3164 
3165 	return 0;
3166 }
3167 
3168 static int bpf_object__init_maps(struct bpf_object *obj,
3169 				 const struct bpf_object_open_opts *opts)
3170 {
3171 	const char *pin_root_path;
3172 	bool strict;
3173 	int err = 0;
3174 
3175 	strict = !OPTS_GET(opts, relaxed_maps, false);
3176 	pin_root_path = OPTS_GET(opts, pin_root_path, NULL);
3177 
3178 	err = bpf_object__init_user_btf_maps(obj, strict, pin_root_path);
3179 	err = err ?: bpf_object__init_global_data_maps(obj);
3180 	err = err ?: bpf_object__init_kconfig_map(obj);
3181 	err = err ?: bpf_object_init_struct_ops(obj);
3182 
3183 	return err;
3184 }
3185 
3186 static bool section_have_execinstr(struct bpf_object *obj, int idx)
3187 {
3188 	Elf64_Shdr *sh;
3189 
3190 	sh = elf_sec_hdr(obj, elf_sec_by_idx(obj, idx));
3191 	if (!sh)
3192 		return false;
3193 
3194 	return sh->sh_flags & SHF_EXECINSTR;
3195 }
3196 
3197 static bool starts_with_qmark(const char *s)
3198 {
3199 	return s && s[0] == '?';
3200 }
3201 
3202 static bool btf_needs_sanitization(struct bpf_object *obj)
3203 {
3204 	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
3205 	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
3206 	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
3207 	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
3208 	bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
3209 	bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
3210 	bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
3211 	bool has_qmark_datasec = kernel_supports(obj, FEAT_BTF_QMARK_DATASEC);
3212 	bool has_layout = kernel_supports(obj, FEAT_BTF_LAYOUT);
3213 
3214 	return !has_func || !has_datasec || !has_func_global || !has_float ||
3215 	       !has_decl_tag || !has_type_tag || !has_enum64 || !has_qmark_datasec ||
3216 	       !has_layout;
3217 }
3218 
3219 struct btf *bpf_object__sanitize_btf(struct bpf_object *obj, struct btf *orig_btf)
3220 {
3221 	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
3222 	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
3223 	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
3224 	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
3225 	bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
3226 	bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
3227 	bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
3228 	bool has_qmark_datasec = kernel_supports(obj, FEAT_BTF_QMARK_DATASEC);
3229 	bool has_layout = kernel_supports(obj, FEAT_BTF_LAYOUT);
3230 	int enum64_placeholder_id = 0;
3231 	const struct btf_header *hdr;
3232 	struct btf *btf = NULL;
3233 	const void *raw_data;
3234 	struct btf_type *t;
3235 	int i, j, vlen;
3236 	__u32 sz;
3237 	int err;
3238 
3239 	/* clone BTF to sanitize a copy and leave the original intact */
3240 	raw_data = btf__raw_data(orig_btf, &sz);
3241 	if (!raw_data)
3242 		return ERR_PTR(-ENOMEM);
3243 	/* btf_header() gives us endian-safe header info */
3244 	hdr = btf_header(orig_btf);
3245 
3246 	if (!has_layout && hdr->hdr_len >= sizeof(struct btf_header) &&
3247 	    (hdr->layout_len != 0 || hdr->layout_off != 0)) {
3248 		const struct btf_header *old_hdr = raw_data;
3249 		struct btf_header *new_hdr;
3250 		void *new_raw_data;
3251 		__u32 new_str_off;
3252 
3253 		/*
3254 		 * Need to rewrite BTF to exclude layout information and
3255 		 * move string section to immediately after types.
3256 		 */
3257 		new_raw_data = malloc(sz);
3258 		if (!new_raw_data)
3259 			return ERR_PTR(-ENOMEM);
3260 
3261 		memcpy(new_raw_data, raw_data, sz);
3262 		new_hdr = new_raw_data;
3263 		new_hdr->layout_off = 0;
3264 		new_hdr->layout_len = 0;
3265 		new_str_off = hdr->type_off + hdr->type_len;
3266 		/* Handle swapped endian case */
3267 		if (old_hdr->magic != hdr->magic)
3268 			new_hdr->str_off = bswap_32(new_str_off);
3269 		else
3270 			new_hdr->str_off = new_str_off;
3271 
3272 		memmove(new_raw_data + hdr->hdr_len + new_str_off,
3273 			new_raw_data + hdr->hdr_len + hdr->str_off,
3274 			hdr->str_len);
3275 		sz = hdr->hdr_len + hdr->type_off + hdr->type_len + hdr->str_len;
3276 		btf = btf__new(new_raw_data, sz);
3277 		free(new_raw_data);
3278 	} else {
3279 		btf = btf__new(raw_data, sz);
3280 	}
3281 	err = libbpf_get_error(btf);
3282 	if (err)
3283 		return ERR_PTR(err);
3284 
3285 	/* enforce 8-byte pointers for BPF-targeted BTFs */
3286 	btf__set_pointer_size(btf, 8);
3287 
3288 	for (i = 1; i < btf__type_cnt(btf); i++) {
3289 		t = (struct btf_type *)btf__type_by_id(btf, i);
3290 
3291 		if ((!has_datasec && btf_is_var(t)) || (!has_decl_tag && btf_is_decl_tag(t))) {
3292 			/* replace VAR/DECL_TAG with INT */
3293 			t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
3294 			/*
3295 			 * using size = 1 is the safest choice, 4 will be too
3296 			 * big and cause kernel BTF validation failure if
3297 			 * original variable took less than 4 bytes
3298 			 */
3299 			t->size = 1;
3300 			*(int *)(t + 1) = BTF_INT_ENC(0, 0, 8);
3301 		} else if (!has_datasec && btf_is_datasec(t)) {
3302 			/* replace DATASEC with STRUCT */
3303 			const struct btf_var_secinfo *v = btf_var_secinfos(t);
3304 			struct btf_member *m = btf_members(t);
3305 			struct btf_type *vt;
3306 			char *name;
3307 
3308 			name = (char *)btf__name_by_offset(btf, t->name_off);
3309 			while (*name) {
3310 				if (*name == '.' || *name == '?')
3311 					*name = '_';
3312 				name++;
3313 			}
3314 
3315 			vlen = btf_vlen(t);
3316 			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
3317 			for (j = 0; j < vlen; j++, v++, m++) {
3318 				/* order of field assignments is important */
3319 				m->offset = v->offset * 8;
3320 				m->type = v->type;
3321 				/* preserve variable name as member name */
3322 				vt = (void *)btf__type_by_id(btf, v->type);
3323 				m->name_off = vt->name_off;
3324 			}
3325 		} else if (!has_qmark_datasec && btf_is_datasec(t) &&
3326 			   starts_with_qmark(btf__name_by_offset(btf, t->name_off))) {
3327 			/* replace '?' prefix with '_' for DATASEC names */
3328 			char *name;
3329 
3330 			name = (char *)btf__name_by_offset(btf, t->name_off);
3331 			if (name[0] == '?')
3332 				name[0] = '_';
3333 		} else if (!has_func && btf_is_func_proto(t)) {
3334 			/* replace FUNC_PROTO with ENUM */
3335 			vlen = btf_vlen(t);
3336 			t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
3337 			t->size = sizeof(__u32); /* kernel enforced */
3338 		} else if (!has_func && btf_is_func(t)) {
3339 			/* replace FUNC with TYPEDEF */
3340 			t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
3341 		} else if (!has_func_global && btf_is_func(t)) {
3342 			/* replace BTF_FUNC_GLOBAL with BTF_FUNC_STATIC */
3343 			t->info = BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0);
3344 		} else if (!has_float && btf_is_float(t)) {
3345 			/* replace FLOAT with an equally-sized empty STRUCT;
3346 			 * since C compilers do not accept e.g. "float" as a
3347 			 * valid struct name, make it anonymous
3348 			 */
3349 			t->name_off = 0;
3350 			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, 0);
3351 		} else if (!has_type_tag && btf_is_type_tag(t)) {
3352 			/* replace TYPE_TAG with a CONST */
3353 			t->name_off = 0;
3354 			t->info = BTF_INFO_ENC(BTF_KIND_CONST, 0, 0);
3355 		} else if (!has_enum64 && btf_is_enum(t)) {
3356 			/* clear the kflag */
3357 			t->info = btf_type_info(btf_kind(t), btf_vlen(t), false);
3358 		} else if (!has_enum64 && btf_is_enum64(t)) {
3359 			/* replace ENUM64 with a union */
3360 			struct btf_member *m;
3361 
3362 			if (enum64_placeholder_id == 0) {
3363 				enum64_placeholder_id = btf__add_int(btf, "enum64_placeholder", 1, 0);
3364 				if (enum64_placeholder_id < 0) {
3365 					btf__free(btf);
3366 					return ERR_PTR(enum64_placeholder_id);
3367 				}
3368 				t = (struct btf_type *)btf__type_by_id(btf, i);
3369 			}
3370 
3371 			m = btf_members(t);
3372 			vlen = btf_vlen(t);
3373 			t->info = BTF_INFO_ENC(BTF_KIND_UNION, 0, vlen);
3374 			for (j = 0; j < vlen; j++, m++) {
3375 				m->type = enum64_placeholder_id;
3376 				m->offset = 0;
3377 			}
3378 		}
3379 	}
3380 
3381 	return btf;
3382 }
3383 
3384 static bool libbpf_needs_btf(const struct bpf_object *obj)
3385 {
3386 	return obj->efile.btf_maps_shndx >= 0 ||
3387 	       obj->efile.has_st_ops ||
3388 	       obj->nr_extern > 0;
3389 }
3390 
3391 static bool kernel_needs_btf(const struct bpf_object *obj)
3392 {
3393 	return obj->efile.has_st_ops;
3394 }
3395 
3396 static int bpf_object__init_btf(struct bpf_object *obj,
3397 				Elf_Data *btf_data,
3398 				Elf_Data *btf_ext_data)
3399 {
3400 	int err = -ENOENT;
3401 
3402 	if (btf_data) {
3403 		obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
3404 		err = libbpf_get_error(obj->btf);
3405 		if (err) {
3406 			obj->btf = NULL;
3407 			pr_warn("Error loading ELF section %s: %s.\n", BTF_ELF_SEC, errstr(err));
3408 			goto out;
3409 		}
3410 		/* enforce 8-byte pointers for BPF-targeted BTFs */
3411 		btf__set_pointer_size(obj->btf, 8);
3412 	}
3413 	if (btf_ext_data) {
3414 		struct btf_ext_info *ext_segs[3];
3415 		int seg_num, sec_num;
3416 
3417 		if (!obj->btf) {
3418 			pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
3419 				 BTF_EXT_ELF_SEC, BTF_ELF_SEC);
3420 			goto out;
3421 		}
3422 		obj->btf_ext = btf_ext__new(btf_ext_data->d_buf, btf_ext_data->d_size);
3423 		err = libbpf_get_error(obj->btf_ext);
3424 		if (err) {
3425 			pr_warn("Error loading ELF section %s: %s. Ignored and continue.\n",
3426 				BTF_EXT_ELF_SEC, errstr(err));
3427 			obj->btf_ext = NULL;
3428 			goto out;
3429 		}
3430 
3431 		/* setup .BTF.ext to ELF section mapping */
3432 		ext_segs[0] = &obj->btf_ext->func_info;
3433 		ext_segs[1] = &obj->btf_ext->line_info;
3434 		ext_segs[2] = &obj->btf_ext->core_relo_info;
3435 		for (seg_num = 0; seg_num < ARRAY_SIZE(ext_segs); seg_num++) {
3436 			struct btf_ext_info *seg = ext_segs[seg_num];
3437 			const struct btf_ext_info_sec *sec;
3438 			const char *sec_name;
3439 			Elf_Scn *scn;
3440 
3441 			if (seg->sec_cnt == 0)
3442 				continue;
3443 
3444 			seg->sec_idxs = calloc(seg->sec_cnt, sizeof(*seg->sec_idxs));
3445 			if (!seg->sec_idxs) {
3446 				err = -ENOMEM;
3447 				goto out;
3448 			}
3449 
3450 			sec_num = 0;
3451 			for_each_btf_ext_sec(seg, sec) {
3452 				/* preventively increment index to avoid doing
3453 				 * this before every continue below
3454 				 */
3455 				sec_num++;
3456 
3457 				sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
3458 				if (str_is_empty(sec_name))
3459 					continue;
3460 				scn = elf_sec_by_name(obj, sec_name);
3461 				if (!scn)
3462 					continue;
3463 
3464 				seg->sec_idxs[sec_num - 1] = elf_ndxscn(scn);
3465 			}
3466 		}
3467 	}
3468 out:
3469 	if (err && libbpf_needs_btf(obj)) {
3470 		pr_warn("BTF is required, but is missing or corrupted.\n");
3471 		return err;
3472 	}
3473 	return 0;
3474 }
3475 
3476 static int compare_vsi_off(const void *_a, const void *_b)
3477 {
3478 	const struct btf_var_secinfo *a = _a;
3479 	const struct btf_var_secinfo *b = _b;
3480 
3481 	return a->offset - b->offset;
3482 }
3483 
3484 static int btf_fixup_datasec(struct bpf_object *obj, struct btf *btf,
3485 			     struct btf_type *t)
3486 {
3487 	__u32 size = 0, i, vars = btf_vlen(t);
3488 	const char *sec_name = btf__name_by_offset(btf, t->name_off);
3489 	struct btf_var_secinfo *vsi;
3490 	bool fixup_offsets = false;
3491 	int err;
3492 
3493 	if (!sec_name) {
3494 		pr_debug("No name found in string section for DATASEC kind.\n");
3495 		return -ENOENT;
3496 	}
3497 
3498 	/* Extern-backing datasecs (.ksyms, .kconfig) have their size and
3499 	 * variable offsets set at the previous step. Further, not every
3500 	 * extern BTF VAR has corresponding ELF symbol preserved, so we skip
3501 	 * all fixups altogether for such sections and go straight to sorting
3502 	 * VARs within their DATASEC.
3503 	 */
3504 	if (strcmp(sec_name, KCONFIG_SEC) == 0 || strcmp(sec_name, KSYMS_SEC) == 0)
3505 		goto sort_vars;
3506 
3507 	/* Clang leaves DATASEC size and VAR offsets as zeroes, so we need to
3508 	 * fix this up. But BPF static linker already fixes this up and fills
3509 	 * all the sizes and offsets during static linking. So this step has
3510 	 * to be optional. But the STV_HIDDEN handling is non-optional for any
3511 	 * non-extern DATASEC, so the variable fixup loop below handles both
3512 	 * functions at the same time, paying the cost of BTF VAR <-> ELF
3513 	 * symbol matching just once.
3514 	 */
3515 	if (t->size == 0) {
3516 		err = find_elf_sec_sz(obj, sec_name, &size);
3517 		if (err || !size) {
3518 			pr_debug("sec '%s': failed to determine size from ELF: size %u, err %s\n",
3519 				 sec_name, size, errstr(err));
3520 			return -ENOENT;
3521 		}
3522 
3523 		t->size = size;
3524 		fixup_offsets = true;
3525 	}
3526 
3527 	for (i = 0, vsi = btf_var_secinfos(t); i < vars; i++, vsi++) {
3528 		const struct btf_type *t_var;
3529 		struct btf_var *var;
3530 		const char *var_name;
3531 		Elf64_Sym *sym;
3532 
3533 		t_var = btf__type_by_id(btf, vsi->type);
3534 		if (!t_var || !btf_is_var(t_var)) {
3535 			pr_debug("sec '%s': unexpected non-VAR type found\n", sec_name);
3536 			return -EINVAL;
3537 		}
3538 
3539 		var = btf_var(t_var);
3540 		if (var->linkage == BTF_VAR_STATIC || var->linkage == BTF_VAR_GLOBAL_EXTERN)
3541 			continue;
3542 
3543 		var_name = btf__name_by_offset(btf, t_var->name_off);
3544 		if (!var_name) {
3545 			pr_debug("sec '%s': failed to find name of DATASEC's member #%u\n",
3546 				 sec_name, i);
3547 			return -ENOENT;
3548 		}
3549 
3550 		sym = find_elf_var_sym(obj, var_name);
3551 		if (IS_ERR(sym)) {
3552 			pr_debug("sec '%s': failed to find ELF symbol for VAR '%s'\n",
3553 				 sec_name, var_name);
3554 			return -ENOENT;
3555 		}
3556 
3557 		if (fixup_offsets)
3558 			vsi->offset = sym->st_value;
3559 
3560 		/* if variable is a global/weak symbol, but has restricted
3561 		 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF VAR
3562 		 * as static. This follows similar logic for functions (BPF
3563 		 * subprogs) and influences libbpf's further decisions about
3564 		 * whether to make global data BPF array maps as
3565 		 * BPF_F_MMAPABLE.
3566 		 */
3567 		if (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
3568 		    || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL)
3569 			var->linkage = BTF_VAR_STATIC;
3570 	}
3571 
3572 sort_vars:
3573 	qsort(btf_var_secinfos(t), vars, sizeof(*vsi), compare_vsi_off);
3574 	return 0;
3575 }
3576 
3577 static int bpf_object_fixup_btf(struct bpf_object *obj)
3578 {
3579 	int i, n, err = 0;
3580 
3581 	if (!obj->btf)
3582 		return 0;
3583 
3584 	n = btf__type_cnt(obj->btf);
3585 	for (i = 1; i < n; i++) {
3586 		struct btf_type *t = btf_type_by_id(obj->btf, i);
3587 
3588 		/* Loader needs to fix up some of the things compiler
3589 		 * couldn't get its hands on while emitting BTF. This
3590 		 * is section size and global variable offset. We use
3591 		 * the info from the ELF itself for this purpose.
3592 		 */
3593 		if (btf_is_datasec(t)) {
3594 			err = btf_fixup_datasec(obj, obj->btf, t);
3595 			if (err)
3596 				return err;
3597 		}
3598 	}
3599 
3600 	return 0;
3601 }
3602 
3603 static bool prog_needs_vmlinux_btf(struct bpf_program *prog)
3604 {
3605 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
3606 	    prog->type == BPF_PROG_TYPE_LSM)
3607 		return true;
3608 
3609 	/* BPF_PROG_TYPE_TRACING programs which do not attach to other programs
3610 	 * also need vmlinux BTF
3611 	 */
3612 	if (prog->type == BPF_PROG_TYPE_TRACING && !prog->attach_prog_fd)
3613 		return true;
3614 
3615 	return false;
3616 }
3617 
3618 static bool map_needs_vmlinux_btf(struct bpf_map *map)
3619 {
3620 	return bpf_map__is_struct_ops(map);
3621 }
3622 
3623 static bool obj_needs_vmlinux_btf(const struct bpf_object *obj)
3624 {
3625 	struct bpf_program *prog;
3626 	struct bpf_map *map;
3627 	int i;
3628 
3629 	/* CO-RE relocations need kernel BTF, only when btf_custom_path
3630 	 * is not specified
3631 	 */
3632 	if (obj->btf_ext && obj->btf_ext->core_relo_info.len && !obj->btf_custom_path)
3633 		return true;
3634 
3635 	/* Support for typed ksyms needs kernel BTF */
3636 	for (i = 0; i < obj->nr_extern; i++) {
3637 		const struct extern_desc *ext;
3638 
3639 		ext = &obj->externs[i];
3640 		if (ext->type == EXT_KSYM && ext->ksym.type_id)
3641 			return true;
3642 	}
3643 
3644 	bpf_object__for_each_program(prog, obj) {
3645 		if (!prog->autoload)
3646 			continue;
3647 		if (prog_needs_vmlinux_btf(prog))
3648 			return true;
3649 	}
3650 
3651 	bpf_object__for_each_map(map, obj) {
3652 		if (map_needs_vmlinux_btf(map))
3653 			return true;
3654 	}
3655 
3656 	return false;
3657 }
3658 
3659 static int bpf_object__load_vmlinux_btf(struct bpf_object *obj, bool force)
3660 {
3661 	int err;
3662 
3663 	/* btf_vmlinux could be loaded earlier */
3664 	if (obj->btf_vmlinux || obj->gen_loader)
3665 		return 0;
3666 
3667 	if (!force && !obj_needs_vmlinux_btf(obj))
3668 		return 0;
3669 
3670 	obj->btf_vmlinux = btf__load_vmlinux_btf();
3671 	err = libbpf_get_error(obj->btf_vmlinux);
3672 	if (err) {
3673 		pr_warn("Error loading vmlinux BTF: %s\n", errstr(err));
3674 		obj->btf_vmlinux = NULL;
3675 		return err;
3676 	}
3677 	return 0;
3678 }
3679 
3680 static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
3681 {
3682 	struct btf *kern_btf = obj->btf;
3683 	bool btf_mandatory, sanitize;
3684 	int i, err = 0;
3685 
3686 	if (!obj->btf)
3687 		return 0;
3688 
3689 	if (!kernel_supports(obj, FEAT_BTF)) {
3690 		if (kernel_needs_btf(obj)) {
3691 			err = -EOPNOTSUPP;
3692 			goto report;
3693 		}
3694 		pr_debug("Kernel doesn't support BTF, skipping uploading it.\n");
3695 		return 0;
3696 	}
3697 
3698 	/* Even though some subprogs are global/weak, user might prefer more
3699 	 * permissive BPF verification process that BPF verifier performs for
3700 	 * static functions, taking into account more context from the caller
3701 	 * functions. In such case, they need to mark such subprogs with
3702 	 * __attribute__((visibility("hidden"))) and libbpf will adjust
3703 	 * corresponding FUNC BTF type to be marked as static and trigger more
3704 	 * involved BPF verification process.
3705 	 */
3706 	for (i = 0; i < obj->nr_programs; i++) {
3707 		struct bpf_program *prog = &obj->programs[i];
3708 		struct btf_type *t;
3709 		const char *name;
3710 		int j, n;
3711 
3712 		if (!prog->mark_btf_static || !prog_is_subprog(obj, prog))
3713 			continue;
3714 
3715 		n = btf__type_cnt(obj->btf);
3716 		for (j = 1; j < n; j++) {
3717 			t = btf_type_by_id(obj->btf, j);
3718 			if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL)
3719 				continue;
3720 
3721 			name = btf__str_by_offset(obj->btf, t->name_off);
3722 			if (strcmp(name, prog->name) != 0)
3723 				continue;
3724 
3725 			t->info = btf_type_info(BTF_KIND_FUNC, BTF_FUNC_STATIC, 0);
3726 			break;
3727 		}
3728 	}
3729 
3730 	sanitize = btf_needs_sanitization(obj);
3731 	if (sanitize) {
3732 		kern_btf = bpf_object__sanitize_btf(obj, obj->btf);
3733 		if (IS_ERR(kern_btf))
3734 			return PTR_ERR(kern_btf);
3735 	}
3736 
3737 	if (obj->gen_loader) {
3738 		__u32 raw_size = 0;
3739 		const void *raw_data = btf__raw_data(kern_btf, &raw_size);
3740 
3741 		if (!raw_data)
3742 			return -ENOMEM;
3743 		bpf_gen__load_btf(obj->gen_loader, raw_data, raw_size);
3744 		/* Pretend to have valid FD to pass various fd >= 0 checks.
3745 		 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
3746 		 */
3747 		btf__set_fd(kern_btf, 0);
3748 	} else {
3749 		/* currently BPF_BTF_LOAD only supports log_level 1 */
3750 		err = btf_load_into_kernel(kern_btf, obj->log_buf, obj->log_size,
3751 					   obj->log_level ? 1 : 0, obj->token_fd);
3752 	}
3753 	if (sanitize) {
3754 		if (!err) {
3755 			/* move fd to libbpf's BTF */
3756 			btf__set_fd(obj->btf, btf__fd(kern_btf));
3757 			btf__set_fd(kern_btf, -1);
3758 		}
3759 		btf__free(kern_btf);
3760 	}
3761 report:
3762 	if (err) {
3763 		btf_mandatory = kernel_needs_btf(obj);
3764 		if (btf_mandatory) {
3765 			pr_warn("Error loading .BTF into kernel: %s. BTF is mandatory, can't proceed.\n",
3766 				errstr(err));
3767 		} else {
3768 			pr_info("Error loading .BTF into kernel: %s. BTF is optional, ignoring.\n",
3769 				errstr(err));
3770 			err = 0;
3771 		}
3772 	}
3773 	return err;
3774 }
3775 
3776 static const char *elf_sym_str(const struct bpf_object *obj, size_t off)
3777 {
3778 	const char *name;
3779 
3780 	name = elf_strptr(obj->efile.elf, obj->efile.strtabidx, off);
3781 	if (!name) {
3782 		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3783 			off, obj->path, elf_errmsg(-1));
3784 		return NULL;
3785 	}
3786 
3787 	return name;
3788 }
3789 
3790 static const char *elf_sec_str(const struct bpf_object *obj, size_t off)
3791 {
3792 	const char *name;
3793 
3794 	name = elf_strptr(obj->efile.elf, obj->efile.shstrndx, off);
3795 	if (!name) {
3796 		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3797 			off, obj->path, elf_errmsg(-1));
3798 		return NULL;
3799 	}
3800 
3801 	return name;
3802 }
3803 
3804 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx)
3805 {
3806 	Elf_Scn *scn;
3807 
3808 	scn = elf_getscn(obj->efile.elf, idx);
3809 	if (!scn) {
3810 		pr_warn("elf: failed to get section(%zu) from %s: %s\n",
3811 			idx, obj->path, elf_errmsg(-1));
3812 		return NULL;
3813 	}
3814 	return scn;
3815 }
3816 
3817 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name)
3818 {
3819 	Elf_Scn *scn = NULL;
3820 	Elf *elf = obj->efile.elf;
3821 	const char *sec_name;
3822 
3823 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3824 		sec_name = elf_sec_name(obj, scn);
3825 		if (!sec_name)
3826 			return NULL;
3827 
3828 		if (strcmp(sec_name, name) != 0)
3829 			continue;
3830 
3831 		return scn;
3832 	}
3833 	return NULL;
3834 }
3835 
3836 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn)
3837 {
3838 	Elf64_Shdr *shdr;
3839 
3840 	if (!scn)
3841 		return NULL;
3842 
3843 	shdr = elf64_getshdr(scn);
3844 	if (!shdr) {
3845 		pr_warn("elf: failed to get section(%zu) header from %s: %s\n",
3846 			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3847 		return NULL;
3848 	}
3849 
3850 	return shdr;
3851 }
3852 
3853 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn)
3854 {
3855 	const char *name;
3856 	Elf64_Shdr *sh;
3857 
3858 	if (!scn)
3859 		return NULL;
3860 
3861 	sh = elf_sec_hdr(obj, scn);
3862 	if (!sh)
3863 		return NULL;
3864 
3865 	name = elf_sec_str(obj, sh->sh_name);
3866 	if (!name) {
3867 		pr_warn("elf: failed to get section(%zu) name from %s: %s\n",
3868 			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3869 		return NULL;
3870 	}
3871 
3872 	return name;
3873 }
3874 
3875 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn)
3876 {
3877 	Elf_Data *data;
3878 
3879 	if (!scn)
3880 		return NULL;
3881 
3882 	data = elf_getdata(scn, 0);
3883 	if (!data) {
3884 		pr_warn("elf: failed to get section(%zu) %s data from %s: %s\n",
3885 			elf_ndxscn(scn), elf_sec_name(obj, scn) ?: "<?>",
3886 			obj->path, elf_errmsg(-1));
3887 		return NULL;
3888 	}
3889 
3890 	return data;
3891 }
3892 
3893 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx)
3894 {
3895 	if (idx >= obj->efile.symbols->d_size / sizeof(Elf64_Sym))
3896 		return NULL;
3897 
3898 	return (Elf64_Sym *)obj->efile.symbols->d_buf + idx;
3899 }
3900 
3901 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx)
3902 {
3903 	if (idx >= data->d_size / sizeof(Elf64_Rel))
3904 		return NULL;
3905 
3906 	return (Elf64_Rel *)data->d_buf + idx;
3907 }
3908 
3909 static bool is_sec_name_dwarf(const char *name)
3910 {
3911 	/* approximation, but the actual list is too long */
3912 	return str_has_pfx(name, ".debug_");
3913 }
3914 
3915 static bool ignore_elf_section(Elf64_Shdr *hdr, const char *name)
3916 {
3917 	/* no special handling of .strtab */
3918 	if (hdr->sh_type == SHT_STRTAB)
3919 		return true;
3920 
3921 	/* ignore .llvm_addrsig section as well */
3922 	if (hdr->sh_type == SHT_LLVM_ADDRSIG)
3923 		return true;
3924 
3925 	/* no subprograms will lead to an empty .text section, ignore it */
3926 	if (hdr->sh_type == SHT_PROGBITS && hdr->sh_size == 0 &&
3927 	    strcmp(name, ".text") == 0)
3928 		return true;
3929 
3930 	/* DWARF sections */
3931 	if (is_sec_name_dwarf(name))
3932 		return true;
3933 
3934 	if (str_has_pfx(name, ".rel")) {
3935 		name += sizeof(".rel") - 1;
3936 		/* DWARF section relocations */
3937 		if (is_sec_name_dwarf(name))
3938 			return true;
3939 
3940 		/* .BTF and .BTF.ext don't need relocations */
3941 		if (strcmp(name, BTF_ELF_SEC) == 0 ||
3942 		    strcmp(name, BTF_EXT_ELF_SEC) == 0)
3943 			return true;
3944 	}
3945 
3946 	return false;
3947 }
3948 
3949 static int cmp_progs(const void *_a, const void *_b)
3950 {
3951 	const struct bpf_program *a = _a;
3952 	const struct bpf_program *b = _b;
3953 
3954 	if (a->sec_idx != b->sec_idx)
3955 		return a->sec_idx < b->sec_idx ? -1 : 1;
3956 
3957 	/* sec_insn_off can't be the same within the section */
3958 	return a->sec_insn_off < b->sec_insn_off ? -1 : 1;
3959 }
3960 
3961 static int bpf_object__elf_collect(struct bpf_object *obj)
3962 {
3963 	struct elf_sec_desc *sec_desc;
3964 	Elf *elf = obj->efile.elf;
3965 	Elf_Data *btf_ext_data = NULL;
3966 	Elf_Data *btf_data = NULL;
3967 	int idx = 0, err = 0;
3968 	const char *name;
3969 	Elf_Data *data;
3970 	Elf_Scn *scn;
3971 	Elf64_Shdr *sh;
3972 
3973 	/* ELF section indices are 0-based, but sec #0 is special "invalid"
3974 	 * section. Since section count retrieved by elf_getshdrnum() does
3975 	 * include sec #0, it is already the necessary size of an array to keep
3976 	 * all the sections.
3977 	 */
3978 	if (elf_getshdrnum(obj->efile.elf, &obj->efile.sec_cnt)) {
3979 		pr_warn("elf: failed to get the number of sections for %s: %s\n",
3980 			obj->path, elf_errmsg(-1));
3981 		return -LIBBPF_ERRNO__FORMAT;
3982 	}
3983 	obj->efile.secs = calloc(obj->efile.sec_cnt, sizeof(*obj->efile.secs));
3984 	if (!obj->efile.secs)
3985 		return -ENOMEM;
3986 
3987 	/* a bunch of ELF parsing functionality depends on processing symbols,
3988 	 * so do the first pass and find the symbol table
3989 	 */
3990 	scn = NULL;
3991 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3992 		sh = elf_sec_hdr(obj, scn);
3993 		if (!sh)
3994 			return -LIBBPF_ERRNO__FORMAT;
3995 
3996 		if (sh->sh_type == SHT_SYMTAB) {
3997 			if (obj->efile.symbols) {
3998 				pr_warn("elf: multiple symbol tables in %s\n", obj->path);
3999 				return -LIBBPF_ERRNO__FORMAT;
4000 			}
4001 
4002 			data = elf_sec_data(obj, scn);
4003 			if (!data)
4004 				return -LIBBPF_ERRNO__FORMAT;
4005 
4006 			idx = elf_ndxscn(scn);
4007 
4008 			obj->efile.symbols = data;
4009 			obj->efile.symbols_shndx = idx;
4010 			obj->efile.strtabidx = sh->sh_link;
4011 		}
4012 	}
4013 
4014 	if (!obj->efile.symbols) {
4015 		pr_warn("elf: couldn't find symbol table in %s, stripped object file?\n",
4016 			obj->path);
4017 		return -ENOENT;
4018 	}
4019 
4020 	scn = NULL;
4021 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
4022 		idx = elf_ndxscn(scn);
4023 		sec_desc = &obj->efile.secs[idx];
4024 
4025 		sh = elf_sec_hdr(obj, scn);
4026 		if (!sh)
4027 			return -LIBBPF_ERRNO__FORMAT;
4028 
4029 		name = elf_sec_str(obj, sh->sh_name);
4030 		if (!name)
4031 			return -LIBBPF_ERRNO__FORMAT;
4032 
4033 		if (ignore_elf_section(sh, name))
4034 			continue;
4035 
4036 		data = elf_sec_data(obj, scn);
4037 		if (!data)
4038 			return -LIBBPF_ERRNO__FORMAT;
4039 
4040 		pr_debug("elf: section(%d) %s, size %lu, link %d, flags %lx, type=%d\n",
4041 			 idx, name, (unsigned long)data->d_size,
4042 			 (int)sh->sh_link, (unsigned long)sh->sh_flags,
4043 			 (int)sh->sh_type);
4044 
4045 		if (strcmp(name, "license") == 0) {
4046 			err = bpf_object__init_license(obj, data->d_buf, data->d_size);
4047 			if (err)
4048 				return err;
4049 		} else if (strcmp(name, "version") == 0) {
4050 			err = bpf_object__init_kversion(obj, data->d_buf, data->d_size);
4051 			if (err)
4052 				return err;
4053 		} else if (strcmp(name, "maps") == 0) {
4054 			pr_warn("elf: legacy map definitions in 'maps' section are not supported by libbpf v1.0+\n");
4055 			return -ENOTSUP;
4056 		} else if (strcmp(name, MAPS_ELF_SEC) == 0) {
4057 			obj->efile.btf_maps_shndx = idx;
4058 		} else if (strcmp(name, BTF_ELF_SEC) == 0) {
4059 			if (sh->sh_type != SHT_PROGBITS)
4060 				return -LIBBPF_ERRNO__FORMAT;
4061 			btf_data = data;
4062 		} else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
4063 			if (sh->sh_type != SHT_PROGBITS)
4064 				return -LIBBPF_ERRNO__FORMAT;
4065 			btf_ext_data = data;
4066 		} else if (sh->sh_type == SHT_SYMTAB) {
4067 			/* already processed during the first pass above */
4068 		} else if (sh->sh_type == SHT_PROGBITS && data->d_size > 0) {
4069 			if (sh->sh_flags & SHF_EXECINSTR) {
4070 				if (strcmp(name, ".text") == 0)
4071 					obj->efile.text_shndx = idx;
4072 				err = bpf_object__add_programs(obj, data, name, idx);
4073 				if (err)
4074 					return err;
4075 			} else if (strcmp(name, DATA_REL_RO_SEC) == 0 ||
4076 				   str_has_pfx(name, DATA_REL_RO_SEC ".")) {
4077 				/*
4078 				 * Constants with pointers in them, e.g. vtables,
4079 				 * that position independent code keeps here to
4080 				 * have them relocated. There is nothing that
4081 				 * writes to it after that.
4082 				 */
4083 				sec_desc->sec_type = SEC_RODATA;
4084 				sec_desc->shdr = sh;
4085 				sec_desc->data = data;
4086 			} else if (strcmp(name, DATA_SEC) == 0 ||
4087 				   str_has_pfx(name, DATA_SEC ".")) {
4088 				sec_desc->sec_type = SEC_DATA;
4089 				sec_desc->shdr = sh;
4090 				sec_desc->data = data;
4091 			} else if (strcmp(name, RODATA_SEC) == 0 ||
4092 				   str_has_pfx(name, RODATA_SEC ".")) {
4093 				sec_desc->sec_type = SEC_RODATA;
4094 				sec_desc->shdr = sh;
4095 				sec_desc->data = data;
4096 			} else if (strcmp(name, PERCPU_SEC) == 0 ||
4097 				   str_has_pfx(name, PERCPU_SEC ".")) {
4098 				sec_desc->sec_type = SEC_PERCPU;
4099 				sec_desc->shdr = sh;
4100 				sec_desc->data = data;
4101 			} else if (strcmp(name, STRUCT_OPS_SEC) == 0 ||
4102 				   strcmp(name, STRUCT_OPS_LINK_SEC) == 0 ||
4103 				   strcmp(name, "?" STRUCT_OPS_SEC) == 0 ||
4104 				   strcmp(name, "?" STRUCT_OPS_LINK_SEC) == 0) {
4105 				sec_desc->sec_type = SEC_ST_OPS;
4106 				sec_desc->shdr = sh;
4107 				sec_desc->data = data;
4108 				obj->efile.has_st_ops = true;
4109 			} else if (strcmp(name, ARENA_SEC) == 0) {
4110 				obj->efile.arena_data = data;
4111 				obj->efile.arena_data_shndx = idx;
4112 			} else if (strcmp(name, JUMPTABLES_SEC) == 0) {
4113 				obj->jumptables_data = malloc(data->d_size);
4114 				if (!obj->jumptables_data)
4115 					return -ENOMEM;
4116 				memcpy(obj->jumptables_data, data->d_buf, data->d_size);
4117 				obj->jumptables_data_sz = data->d_size;
4118 				obj->efile.jumptables_data_shndx = idx;
4119 			} else {
4120 				pr_info("elf: skipping unrecognized data section(%d) %s\n",
4121 					idx, name);
4122 			}
4123 		} else if (sh->sh_type == SHT_REL) {
4124 			int targ_sec_idx = sh->sh_info; /* points to other section */
4125 
4126 			if (sh->sh_entsize != sizeof(Elf64_Rel) ||
4127 			    targ_sec_idx >= obj->efile.sec_cnt)
4128 				return -LIBBPF_ERRNO__FORMAT;
4129 
4130 			/*
4131 			 * Only do relo for section with exec instructions,
4132 			 * struct_ops, maps, and read-only data that might
4133 			 * have pointers to functions.
4134 			 */
4135 			if (!section_have_execinstr(obj, targ_sec_idx) &&
4136 			    strcmp(name, ".rel" RODATA_SEC) &&
4137 			    !str_has_pfx(name, ".rel" RODATA_SEC ".") &&
4138 			    strcmp(name, ".rel" DATA_REL_RO_SEC) &&
4139 			    !str_has_pfx(name, ".rel" DATA_REL_RO_SEC ".") &&
4140 			    strcmp(name, ".rel" STRUCT_OPS_SEC) &&
4141 			    strcmp(name, ".rel" STRUCT_OPS_LINK_SEC) &&
4142 			    strcmp(name, ".rel?" STRUCT_OPS_SEC) &&
4143 			    strcmp(name, ".rel?" STRUCT_OPS_LINK_SEC) &&
4144 			    strcmp(name, ".rel" MAPS_ELF_SEC)) {
4145 				pr_info("elf: skipping relo section(%d) %s for section(%d) %s\n",
4146 					idx, name, targ_sec_idx,
4147 					elf_sec_name(obj, elf_sec_by_idx(obj, targ_sec_idx)) ?: "<?>");
4148 				continue;
4149 			}
4150 
4151 			sec_desc->sec_type = SEC_RELO;
4152 			sec_desc->shdr = sh;
4153 			sec_desc->data = data;
4154 		} else if (sh->sh_type == SHT_NOBITS && (strcmp(name, BSS_SEC) == 0 ||
4155 							 str_has_pfx(name, BSS_SEC "."))) {
4156 			sec_desc->sec_type = SEC_BSS;
4157 			sec_desc->shdr = sh;
4158 			sec_desc->data = data;
4159 		} else {
4160 			pr_info("elf: skipping section(%d) %s (size %zu)\n", idx, name,
4161 				(size_t)sh->sh_size);
4162 		}
4163 	}
4164 
4165 	if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) {
4166 		pr_warn("elf: symbol strings section missing or invalid in %s\n", obj->path);
4167 		return -LIBBPF_ERRNO__FORMAT;
4168 	}
4169 
4170 	/* change BPF program insns to native endianness for introspection */
4171 	if (!is_native_endianness(obj))
4172 		bpf_object_bswap_progs(obj);
4173 
4174 	/* sort BPF programs by section name and in-section instruction offset
4175 	 * for faster search
4176 	 */
4177 	if (obj->nr_programs)
4178 		qsort(obj->programs, obj->nr_programs, sizeof(*obj->programs), cmp_progs);
4179 
4180 	return bpf_object__init_btf(obj, btf_data, btf_ext_data);
4181 }
4182 
4183 static bool sym_is_extern(const Elf64_Sym *sym)
4184 {
4185 	int bind = ELF64_ST_BIND(sym->st_info);
4186 	/* externs are symbols w/ type=NOTYPE, bind=GLOBAL|WEAK, section=UND */
4187 	return sym->st_shndx == SHN_UNDEF &&
4188 	       (bind == STB_GLOBAL || bind == STB_WEAK) &&
4189 	       ELF64_ST_TYPE(sym->st_info) == STT_NOTYPE;
4190 }
4191 
4192 static bool sym_is_subprog(const Elf64_Sym *sym, int text_shndx)
4193 {
4194 	int bind = ELF64_ST_BIND(sym->st_info);
4195 	int type = ELF64_ST_TYPE(sym->st_info);
4196 
4197 	/* in .text section */
4198 	if (sym->st_shndx != text_shndx)
4199 		return false;
4200 
4201 	/* local function */
4202 	if (bind == STB_LOCAL && type == STT_SECTION)
4203 		return true;
4204 
4205 	/* global function */
4206 	return (bind == STB_GLOBAL || bind == STB_WEAK) && type == STT_FUNC;
4207 }
4208 
4209 static int find_extern_btf_id(const struct btf *btf, const char *ext_name)
4210 {
4211 	const struct btf_type *t;
4212 	const char *tname;
4213 	int i, n;
4214 
4215 	if (!btf)
4216 		return -ESRCH;
4217 
4218 	n = btf__type_cnt(btf);
4219 	for (i = 1; i < n; i++) {
4220 		t = btf__type_by_id(btf, i);
4221 
4222 		if (!btf_is_var(t) && !btf_is_func(t))
4223 			continue;
4224 
4225 		tname = btf__name_by_offset(btf, t->name_off);
4226 		if (strcmp(tname, ext_name))
4227 			continue;
4228 
4229 		if (btf_is_var(t) &&
4230 		    btf_var(t)->linkage != BTF_VAR_GLOBAL_EXTERN)
4231 			return -EINVAL;
4232 
4233 		if (btf_is_func(t) && btf_func_linkage(t) != BTF_FUNC_EXTERN)
4234 			return -EINVAL;
4235 
4236 		return i;
4237 	}
4238 
4239 	return -ENOENT;
4240 }
4241 
4242 static int find_extern_sec_btf_id(struct btf *btf, int ext_btf_id) {
4243 	const struct btf_var_secinfo *vs;
4244 	const struct btf_type *t;
4245 	int i, j, n;
4246 
4247 	if (!btf)
4248 		return -ESRCH;
4249 
4250 	n = btf__type_cnt(btf);
4251 	for (i = 1; i < n; i++) {
4252 		t = btf__type_by_id(btf, i);
4253 
4254 		if (!btf_is_datasec(t))
4255 			continue;
4256 
4257 		vs = btf_var_secinfos(t);
4258 		for (j = 0; j < btf_vlen(t); j++, vs++) {
4259 			if (vs->type == ext_btf_id)
4260 				return i;
4261 		}
4262 	}
4263 
4264 	return -ENOENT;
4265 }
4266 
4267 static enum kcfg_type find_kcfg_type(const struct btf *btf, int id,
4268 				     bool *is_signed)
4269 {
4270 	const struct btf_type *t;
4271 	const char *name;
4272 
4273 	t = skip_mods_and_typedefs(btf, id, NULL);
4274 	name = btf__name_by_offset(btf, t->name_off);
4275 
4276 	if (is_signed)
4277 		*is_signed = false;
4278 	switch (btf_kind(t)) {
4279 	case BTF_KIND_INT: {
4280 		int enc = btf_int_encoding(t);
4281 
4282 		if (enc & BTF_INT_BOOL)
4283 			return t->size == 1 ? KCFG_BOOL : KCFG_UNKNOWN;
4284 		if (is_signed)
4285 			*is_signed = enc & BTF_INT_SIGNED;
4286 		if (t->size == 1)
4287 			return KCFG_CHAR;
4288 		if (t->size < 1 || t->size > 8 || (t->size & (t->size - 1)))
4289 			return KCFG_UNKNOWN;
4290 		return KCFG_INT;
4291 	}
4292 	case BTF_KIND_ENUM:
4293 		if (t->size != 4)
4294 			return KCFG_UNKNOWN;
4295 		if (strcmp(name, "libbpf_tristate"))
4296 			return KCFG_UNKNOWN;
4297 		return KCFG_TRISTATE;
4298 	case BTF_KIND_ENUM64:
4299 		if (strcmp(name, "libbpf_tristate"))
4300 			return KCFG_UNKNOWN;
4301 		return KCFG_TRISTATE;
4302 	case BTF_KIND_ARRAY:
4303 		if (btf_array(t)->nelems == 0)
4304 			return KCFG_UNKNOWN;
4305 		if (find_kcfg_type(btf, btf_array(t)->type, NULL) != KCFG_CHAR)
4306 			return KCFG_UNKNOWN;
4307 		return KCFG_CHAR_ARR;
4308 	default:
4309 		return KCFG_UNKNOWN;
4310 	}
4311 }
4312 
4313 static int cmp_externs(const void *_a, const void *_b)
4314 {
4315 	const struct extern_desc *a = _a;
4316 	const struct extern_desc *b = _b;
4317 
4318 	if (a->type != b->type)
4319 		return a->type < b->type ? -1 : 1;
4320 
4321 	if (a->type == EXT_KCFG) {
4322 		/* descending order by alignment requirements */
4323 		if (a->kcfg.align != b->kcfg.align)
4324 			return a->kcfg.align > b->kcfg.align ? -1 : 1;
4325 		/* ascending order by size, within same alignment class */
4326 		if (a->kcfg.sz != b->kcfg.sz)
4327 			return a->kcfg.sz < b->kcfg.sz ? -1 : 1;
4328 	}
4329 
4330 	/* resolve ties by name */
4331 	return strcmp(a->name, b->name);
4332 }
4333 
4334 static int find_int_btf_id(const struct btf *btf)
4335 {
4336 	const struct btf_type *t;
4337 	int i, n;
4338 
4339 	n = btf__type_cnt(btf);
4340 	for (i = 1; i < n; i++) {
4341 		t = btf__type_by_id(btf, i);
4342 
4343 		if (btf_is_int(t) && btf_int_bits(t) == 32)
4344 			return i;
4345 	}
4346 
4347 	return 0;
4348 }
4349 
4350 static int add_dummy_ksym_var(struct btf *btf)
4351 {
4352 	int i, int_btf_id, sec_btf_id, dummy_var_btf_id;
4353 	const struct btf_var_secinfo *vs;
4354 	const struct btf_type *sec;
4355 
4356 	if (!btf)
4357 		return 0;
4358 
4359 	sec_btf_id = btf__find_by_name_kind(btf, KSYMS_SEC,
4360 					    BTF_KIND_DATASEC);
4361 	if (sec_btf_id < 0)
4362 		return 0;
4363 
4364 	sec = btf__type_by_id(btf, sec_btf_id);
4365 	vs = btf_var_secinfos(sec);
4366 	for (i = 0; i < btf_vlen(sec); i++, vs++) {
4367 		const struct btf_type *vt;
4368 
4369 		vt = btf__type_by_id(btf, vs->type);
4370 		if (btf_is_func(vt))
4371 			break;
4372 	}
4373 
4374 	/* No func in ksyms sec.  No need to add dummy var. */
4375 	if (i == btf_vlen(sec))
4376 		return 0;
4377 
4378 	int_btf_id = find_int_btf_id(btf);
4379 	dummy_var_btf_id = btf__add_var(btf,
4380 					"dummy_ksym",
4381 					BTF_VAR_GLOBAL_ALLOCATED,
4382 					int_btf_id);
4383 	if (dummy_var_btf_id < 0)
4384 		pr_warn("cannot create a dummy_ksym var\n");
4385 
4386 	return dummy_var_btf_id;
4387 }
4388 
4389 static int bpf_object__collect_externs(struct bpf_object *obj)
4390 {
4391 	struct btf_type *sec, *kcfg_sec = NULL, *ksym_sec = NULL;
4392 	const struct btf_type *t;
4393 	struct extern_desc *ext;
4394 	int i, n, off, dummy_var_btf_id;
4395 	const char *ext_name, *sec_name;
4396 	size_t ext_essent_len;
4397 	Elf_Scn *scn;
4398 	Elf64_Shdr *sh;
4399 
4400 	if (!obj->efile.symbols)
4401 		return 0;
4402 
4403 	scn = elf_sec_by_idx(obj, obj->efile.symbols_shndx);
4404 	sh = elf_sec_hdr(obj, scn);
4405 	if (!sh || sh->sh_entsize != sizeof(Elf64_Sym))
4406 		return -LIBBPF_ERRNO__FORMAT;
4407 
4408 	dummy_var_btf_id = add_dummy_ksym_var(obj->btf);
4409 	if (dummy_var_btf_id < 0)
4410 		return dummy_var_btf_id;
4411 
4412 	n = sh->sh_size / sh->sh_entsize;
4413 	pr_debug("looking for externs among %d symbols...\n", n);
4414 
4415 	for (i = 0; i < n; i++) {
4416 		Elf64_Sym *sym = elf_sym_by_idx(obj, i);
4417 
4418 		if (!sym)
4419 			return -LIBBPF_ERRNO__FORMAT;
4420 		if (!sym_is_extern(sym))
4421 			continue;
4422 		ext_name = elf_sym_str(obj, sym->st_name);
4423 		if (str_is_empty(ext_name))
4424 			continue;
4425 
4426 		ext = obj->externs;
4427 		ext = libbpf_reallocarray(ext, obj->nr_extern + 1, sizeof(*ext));
4428 		if (!ext)
4429 			return -ENOMEM;
4430 		obj->externs = ext;
4431 		ext = &ext[obj->nr_extern];
4432 		memset(ext, 0, sizeof(*ext));
4433 		obj->nr_extern++;
4434 
4435 		ext->btf_id = find_extern_btf_id(obj->btf, ext_name);
4436 		if (ext->btf_id <= 0) {
4437 			pr_warn("failed to find BTF for extern '%s': %d\n",
4438 				ext_name, ext->btf_id);
4439 			return ext->btf_id;
4440 		}
4441 		t = btf__type_by_id(obj->btf, ext->btf_id);
4442 		ext->name = strdup(btf__name_by_offset(obj->btf, t->name_off));
4443 		if (!ext->name)
4444 			return -ENOMEM;
4445 		ext->sym_idx = i;
4446 		ext->is_weak = ELF64_ST_BIND(sym->st_info) == STB_WEAK;
4447 
4448 		ext_essent_len = bpf_core_essential_name_len(ext->name);
4449 		ext->essent_name = NULL;
4450 		if (ext_essent_len != strlen(ext->name)) {
4451 			ext->essent_name = strndup(ext->name, ext_essent_len);
4452 			if (!ext->essent_name)
4453 				return -ENOMEM;
4454 		}
4455 
4456 		ext->sec_btf_id = find_extern_sec_btf_id(obj->btf, ext->btf_id);
4457 		if (ext->sec_btf_id <= 0) {
4458 			pr_warn("failed to find BTF for extern '%s' [%d] section: %d\n",
4459 				ext_name, ext->btf_id, ext->sec_btf_id);
4460 			return ext->sec_btf_id;
4461 		}
4462 		sec = (void *)btf__type_by_id(obj->btf, ext->sec_btf_id);
4463 		sec_name = btf__name_by_offset(obj->btf, sec->name_off);
4464 
4465 		if (strcmp(sec_name, KCONFIG_SEC) == 0) {
4466 			if (btf_is_func(t)) {
4467 				pr_warn("extern function %s is unsupported under %s section\n",
4468 					ext->name, KCONFIG_SEC);
4469 				return -ENOTSUP;
4470 			}
4471 			kcfg_sec = sec;
4472 			ext->type = EXT_KCFG;
4473 			ext->kcfg.sz = btf__resolve_size(obj->btf, t->type);
4474 			if (ext->kcfg.sz <= 0) {
4475 				pr_warn("failed to resolve size of extern (kcfg) '%s': %d\n",
4476 					ext_name, ext->kcfg.sz);
4477 				return ext->kcfg.sz;
4478 			}
4479 			ext->kcfg.align = btf__align_of(obj->btf, t->type);
4480 			if (ext->kcfg.align <= 0) {
4481 				pr_warn("failed to determine alignment of extern (kcfg) '%s': %d\n",
4482 					ext_name, ext->kcfg.align);
4483 				return -EINVAL;
4484 			}
4485 			ext->kcfg.type = find_kcfg_type(obj->btf, t->type,
4486 							&ext->kcfg.is_signed);
4487 			if (ext->kcfg.type == KCFG_UNKNOWN) {
4488 				pr_warn("extern (kcfg) '%s': type is unsupported\n", ext_name);
4489 				return -ENOTSUP;
4490 			}
4491 		} else if (strcmp(sec_name, KSYMS_SEC) == 0) {
4492 			ksym_sec = sec;
4493 			ext->type = EXT_KSYM;
4494 			skip_mods_and_typedefs(obj->btf, t->type,
4495 					       &ext->ksym.type_id);
4496 		} else {
4497 			pr_warn("unrecognized extern section '%s'\n", sec_name);
4498 			return -ENOTSUP;
4499 		}
4500 	}
4501 	pr_debug("collected %d externs total\n", obj->nr_extern);
4502 
4503 	if (!obj->nr_extern)
4504 		return 0;
4505 
4506 	/* sort externs by type, for kcfg ones also by (align, size, name) */
4507 	qsort(obj->externs, obj->nr_extern, sizeof(*ext), cmp_externs);
4508 
4509 	/* for .ksyms section, we need to turn all externs into allocated
4510 	 * variables in BTF to pass kernel verification; we do this by
4511 	 * pretending that each extern is a 8-byte variable
4512 	 */
4513 	if (ksym_sec) {
4514 		/* find existing 4-byte integer type in BTF to use for fake
4515 		 * extern variables in DATASEC
4516 		 */
4517 		int int_btf_id = find_int_btf_id(obj->btf);
4518 		/* For extern function, a dummy_var added earlier
4519 		 * will be used to replace the vs->type and
4520 		 * its name string will be used to refill
4521 		 * the missing param's name.
4522 		 */
4523 		const struct btf_type *dummy_var;
4524 
4525 		dummy_var = btf__type_by_id(obj->btf, dummy_var_btf_id);
4526 		for (i = 0; i < obj->nr_extern; i++) {
4527 			ext = &obj->externs[i];
4528 			if (ext->type != EXT_KSYM)
4529 				continue;
4530 			pr_debug("extern (ksym) #%d: symbol %d, name %s\n",
4531 				 i, ext->sym_idx, ext->name);
4532 		}
4533 
4534 		sec = ksym_sec;
4535 		n = btf_vlen(sec);
4536 		for (i = 0, off = 0; i < n; i++, off += sizeof(int)) {
4537 			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
4538 			struct btf_type *vt;
4539 
4540 			vt = (void *)btf__type_by_id(obj->btf, vs->type);
4541 			ext_name = btf__name_by_offset(obj->btf, vt->name_off);
4542 			ext = find_extern_by_name(obj, ext_name);
4543 			if (!ext) {
4544 				pr_warn("failed to find extern definition for BTF %s '%s'\n",
4545 					btf_kind_str(vt), ext_name);
4546 				return -ESRCH;
4547 			}
4548 			if (btf_is_func(vt)) {
4549 				const struct btf_type *func_proto;
4550 				struct btf_param *param;
4551 				int j;
4552 
4553 				func_proto = btf__type_by_id(obj->btf,
4554 							     vt->type);
4555 				param = btf_params(func_proto);
4556 				/* Reuse the dummy_var string if the
4557 				 * func proto does not have param name.
4558 				 */
4559 				for (j = 0; j < btf_vlen(func_proto); j++)
4560 					if (param[j].type && !param[j].name_off)
4561 						param[j].name_off =
4562 							dummy_var->name_off;
4563 				vs->type = dummy_var_btf_id;
4564 				vt->info &= ~0xffff;
4565 				vt->info |= BTF_FUNC_GLOBAL;
4566 			} else {
4567 				btf_var(vt)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
4568 				vt->type = int_btf_id;
4569 			}
4570 			vs->offset = off;
4571 			vs->size = sizeof(int);
4572 		}
4573 		sec->size = off;
4574 	}
4575 
4576 	if (kcfg_sec) {
4577 		sec = kcfg_sec;
4578 		/* for kcfg externs calculate their offsets within a .kconfig map */
4579 		off = 0;
4580 		for (i = 0; i < obj->nr_extern; i++) {
4581 			ext = &obj->externs[i];
4582 			if (ext->type != EXT_KCFG)
4583 				continue;
4584 
4585 			ext->kcfg.data_off = roundup(off, ext->kcfg.align);
4586 			off = ext->kcfg.data_off + ext->kcfg.sz;
4587 			pr_debug("extern (kcfg) #%d: symbol %d, off %d, name %s\n",
4588 				 i, ext->sym_idx, ext->kcfg.data_off, ext->name);
4589 		}
4590 		sec->size = off;
4591 		n = btf_vlen(sec);
4592 		for (i = 0; i < n; i++) {
4593 			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
4594 
4595 			t = btf__type_by_id(obj->btf, vs->type);
4596 			ext_name = btf__name_by_offset(obj->btf, t->name_off);
4597 			ext = find_extern_by_name(obj, ext_name);
4598 			if (!ext) {
4599 				pr_warn("failed to find extern definition for BTF var '%s'\n",
4600 					ext_name);
4601 				return -ESRCH;
4602 			}
4603 			btf_var(t)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
4604 			vs->offset = ext->kcfg.data_off;
4605 		}
4606 	}
4607 	return 0;
4608 }
4609 
4610 static bool prog_is_subprog(const struct bpf_object *obj, const struct bpf_program *prog)
4611 {
4612 	return prog->sec_idx == obj->efile.text_shndx;
4613 }
4614 
4615 struct bpf_program *
4616 bpf_object__find_program_by_name(const struct bpf_object *obj,
4617 				 const char *name)
4618 {
4619 	struct bpf_program *prog;
4620 
4621 	bpf_object__for_each_program(prog, obj) {
4622 		if (prog_is_subprog(obj, prog))
4623 			continue;
4624 		if (!strcmp(prog->name, name))
4625 			return prog;
4626 	}
4627 	return errno = ENOENT, NULL;
4628 }
4629 
4630 static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
4631 				      int shndx)
4632 {
4633 	switch (obj->efile.secs[shndx].sec_type) {
4634 	case SEC_BSS:
4635 	case SEC_DATA:
4636 	case SEC_RODATA:
4637 	case SEC_PERCPU:
4638 		return true;
4639 	default:
4640 		return false;
4641 	}
4642 }
4643 
4644 static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
4645 				      int shndx)
4646 {
4647 	return shndx == obj->efile.btf_maps_shndx;
4648 }
4649 
4650 static enum libbpf_map_type
4651 bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
4652 {
4653 	if (shndx == obj->efile.symbols_shndx)
4654 		return LIBBPF_MAP_KCONFIG;
4655 
4656 	switch (obj->efile.secs[shndx].sec_type) {
4657 	case SEC_BSS:
4658 		return LIBBPF_MAP_BSS;
4659 	case SEC_DATA:
4660 		return LIBBPF_MAP_DATA;
4661 	case SEC_RODATA:
4662 		return LIBBPF_MAP_RODATA;
4663 	case SEC_PERCPU:
4664 		return LIBBPF_MAP_PERCPU;
4665 	default:
4666 		return LIBBPF_MAP_UNSPEC;
4667 	}
4668 }
4669 
4670 static int bpf_prog_compute_hash(struct bpf_program *prog)
4671 {
4672 	struct bpf_insn *purged;
4673 	int i, err = 0;
4674 
4675 	purged = calloc(prog->insns_cnt, BPF_INSN_SZ);
4676 	if (!purged)
4677 		return -ENOMEM;
4678 
4679 	/* If relocations have been done, the map_fd needs to be
4680 	 * discarded for the digest calculation.
4681 	 */
4682 	for (i = 0; i < prog->insns_cnt; i++) {
4683 		purged[i] = prog->insns[i];
4684 		if (purged[i].code == (BPF_LD | BPF_IMM | BPF_DW) &&
4685 		    (purged[i].src_reg == BPF_PSEUDO_MAP_FD ||
4686 		     purged[i].src_reg == BPF_PSEUDO_MAP_VALUE)) {
4687 			purged[i].imm = 0;
4688 			i++;
4689 			if (i >= prog->insns_cnt ||
4690 			    prog->insns[i].code != 0 ||
4691 			    prog->insns[i].dst_reg != 0 ||
4692 			    prog->insns[i].src_reg != 0 ||
4693 			    prog->insns[i].off != 0) {
4694 				err = -EINVAL;
4695 				goto out;
4696 			}
4697 			purged[i] = prog->insns[i];
4698 			purged[i].imm = 0;
4699 		}
4700 	}
4701 	libbpf_sha256(purged, prog->insns_cnt * sizeof(struct bpf_insn),
4702 		      prog->hash);
4703 out:
4704 	free(purged);
4705 	return err;
4706 }
4707 
4708 static int bpf_program__record_reloc(struct bpf_program *prog,
4709 				     struct reloc_desc *reloc_desc,
4710 				     __u32 insn_idx, const char *sym_name,
4711 				     const Elf64_Sym *sym, const Elf64_Rel *rel)
4712 {
4713 	struct bpf_insn *insn = &prog->insns[insn_idx];
4714 	size_t map_idx, nr_maps = prog->obj->nr_maps;
4715 	struct bpf_object *obj = prog->obj;
4716 	__u32 shdr_idx = sym->st_shndx;
4717 	enum libbpf_map_type type;
4718 	const char *sym_sec_name;
4719 	struct bpf_map *map;
4720 
4721 	if (!is_call_insn(insn) && !is_ldimm64_insn(insn)) {
4722 		pr_warn("prog '%s': invalid relo against '%s' for insns[%u].code 0x%x\n",
4723 			prog->name, sym_name, insn_idx, insn->code);
4724 		return -LIBBPF_ERRNO__RELOC;
4725 	}
4726 
4727 	if (sym_is_extern(sym)) {
4728 		int sym_idx = ELF64_R_SYM(rel->r_info);
4729 		int i, n = obj->nr_extern;
4730 		struct extern_desc *ext;
4731 
4732 		for (i = 0; i < n; i++) {
4733 			ext = &obj->externs[i];
4734 			if (ext->sym_idx == sym_idx)
4735 				break;
4736 		}
4737 		if (i >= n) {
4738 			pr_warn("prog '%s': extern relo failed to find extern for '%s' (%d)\n",
4739 				prog->name, sym_name, sym_idx);
4740 			return -LIBBPF_ERRNO__RELOC;
4741 		}
4742 		pr_debug("prog '%s': found extern #%d '%s' (sym %d) for insn #%u\n",
4743 			 prog->name, i, ext->name, ext->sym_idx, insn_idx);
4744 		if (insn->code == (BPF_JMP | BPF_CALL))
4745 			reloc_desc->type = RELO_EXTERN_CALL;
4746 		else
4747 			reloc_desc->type = RELO_EXTERN_LD64;
4748 		reloc_desc->insn_idx = insn_idx;
4749 		reloc_desc->ext_idx = i;
4750 		return 0;
4751 	}
4752 
4753 	/* sub-program call relocation */
4754 	if (is_call_insn(insn)) {
4755 		if (insn->src_reg != BPF_PSEUDO_CALL) {
4756 			pr_warn("prog '%s': incorrect bpf_call opcode\n", prog->name);
4757 			return -LIBBPF_ERRNO__RELOC;
4758 		}
4759 		/* text_shndx can be 0, if no default "main" program exists */
4760 		if (!shdr_idx || shdr_idx != obj->efile.text_shndx) {
4761 			sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4762 			pr_warn("prog '%s': bad call relo against '%s' in section '%s'\n",
4763 				prog->name, sym_name, sym_sec_name);
4764 			return -LIBBPF_ERRNO__RELOC;
4765 		}
4766 		if (sym->st_value % BPF_INSN_SZ) {
4767 			pr_warn("prog '%s': bad call relo against '%s' at offset %zu\n",
4768 				prog->name, sym_name, (size_t)sym->st_value);
4769 			return -LIBBPF_ERRNO__RELOC;
4770 		}
4771 		reloc_desc->type = RELO_CALL;
4772 		reloc_desc->insn_idx = insn_idx;
4773 		reloc_desc->sym_off = sym->st_value;
4774 		return 0;
4775 	}
4776 
4777 	if (!shdr_idx || shdr_idx >= SHN_LORESERVE) {
4778 		pr_warn("prog '%s': invalid relo against '%s' in special section 0x%x; forgot to initialize global var?..\n",
4779 			prog->name, sym_name, shdr_idx);
4780 		return -LIBBPF_ERRNO__RELOC;
4781 	}
4782 
4783 	/* loading subprog addresses */
4784 	if (sym_is_subprog(sym, obj->efile.text_shndx)) {
4785 		/* global_func: sym->st_value = offset in the section, insn->imm = 0.
4786 		 * local_func: sym->st_value = 0, insn->imm = offset in the section.
4787 		 */
4788 		if ((sym->st_value % BPF_INSN_SZ) || (insn->imm % BPF_INSN_SZ)) {
4789 			pr_warn("prog '%s': bad subprog addr relo against '%s' at offset %zu+%d\n",
4790 				prog->name, sym_name, (size_t)sym->st_value, insn->imm);
4791 			return -LIBBPF_ERRNO__RELOC;
4792 		}
4793 
4794 		reloc_desc->type = RELO_SUBPROG_ADDR;
4795 		reloc_desc->insn_idx = insn_idx;
4796 		reloc_desc->sym_off = sym->st_value;
4797 		return 0;
4798 	}
4799 
4800 	type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
4801 	sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4802 
4803 	/* arena data relocation */
4804 	if (shdr_idx == obj->efile.arena_data_shndx) {
4805 		if (obj->arena_map_idx < 0) {
4806 			pr_warn("prog '%s': bad arena data relocation at insn %u, no arena maps defined\n",
4807 				prog->name, insn_idx);
4808 			return -LIBBPF_ERRNO__RELOC;
4809 		}
4810 		reloc_desc->type = RELO_DATA;
4811 		reloc_desc->insn_idx = insn_idx;
4812 		reloc_desc->map_idx = obj->arena_map_idx;
4813 		reloc_desc->sym_off = sym->st_value;
4814 
4815 		map = &obj->maps[obj->arena_map_idx];
4816 		pr_debug("prog '%s': found arena map %d (%s, sec %d, off %zu) for insn %u\n",
4817 			 prog->name, obj->arena_map_idx, map->name, map->sec_idx,
4818 			 map->sec_offset, insn_idx);
4819 		return 0;
4820 	}
4821 
4822 	/* jump table data relocation */
4823 	if (shdr_idx == obj->efile.jumptables_data_shndx) {
4824 		reloc_desc->type = RELO_INSN_ARRAY;
4825 		reloc_desc->insn_idx = insn_idx;
4826 		reloc_desc->map_idx = -1;
4827 		reloc_desc->sym_off = sym->st_value;
4828 		reloc_desc->sym_size = sym->st_size;
4829 		return 0;
4830 	}
4831 
4832 	/* generic map reference relocation */
4833 	if (type == LIBBPF_MAP_UNSPEC) {
4834 		if (!bpf_object__shndx_is_maps(obj, shdr_idx)) {
4835 			pr_warn("prog '%s': bad map relo against '%s' in section '%s'\n",
4836 				prog->name, sym_name, sym_sec_name);
4837 			return -LIBBPF_ERRNO__RELOC;
4838 		}
4839 		for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4840 			map = &obj->maps[map_idx];
4841 			if (map->libbpf_type != type ||
4842 			    map->sec_idx != sym->st_shndx ||
4843 			    map->sec_offset != sym->st_value)
4844 				continue;
4845 			pr_debug("prog '%s': found map %zu (%s, sec %d, off %zu) for insn #%u\n",
4846 				 prog->name, map_idx, map->name, map->sec_idx,
4847 				 map->sec_offset, insn_idx);
4848 			break;
4849 		}
4850 		if (map_idx >= nr_maps) {
4851 			pr_warn("prog '%s': map relo failed to find map for section '%s', off %zu\n",
4852 				prog->name, sym_sec_name, (size_t)sym->st_value);
4853 			return -LIBBPF_ERRNO__RELOC;
4854 		}
4855 		reloc_desc->type = RELO_LD64;
4856 		reloc_desc->insn_idx = insn_idx;
4857 		reloc_desc->map_idx = map_idx;
4858 		reloc_desc->sym_off = 0; /* sym->st_value determines map_idx */
4859 		return 0;
4860 	}
4861 
4862 	/* global data map relocation */
4863 	if (!bpf_object__shndx_is_data(obj, shdr_idx)) {
4864 		pr_warn("prog '%s': bad data relo against section '%s'\n",
4865 			prog->name, sym_sec_name);
4866 		return -LIBBPF_ERRNO__RELOC;
4867 	}
4868 	for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4869 		map = &obj->maps[map_idx];
4870 		if (map->libbpf_type != type || map->sec_idx != sym->st_shndx)
4871 			continue;
4872 		pr_debug("prog '%s': found data map %zu (%s, sec %d, off %zu) for insn %u\n",
4873 			 prog->name, map_idx, map->name, map->sec_idx,
4874 			 map->sec_offset, insn_idx);
4875 		break;
4876 	}
4877 	if (map_idx >= nr_maps) {
4878 		pr_warn("prog '%s': data relo failed to find map for section '%s'\n",
4879 			prog->name, sym_sec_name);
4880 		return -LIBBPF_ERRNO__RELOC;
4881 	}
4882 
4883 	reloc_desc->type = RELO_DATA;
4884 	reloc_desc->insn_idx = insn_idx;
4885 	reloc_desc->map_idx = map_idx;
4886 	reloc_desc->sym_off = sym->st_value;
4887 	return 0;
4888 }
4889 
4890 static bool prog_contains_insn(const struct bpf_program *prog, size_t insn_idx)
4891 {
4892 	return insn_idx >= prog->sec_insn_off &&
4893 	       insn_idx < prog->sec_insn_off + prog->sec_insn_cnt;
4894 }
4895 
4896 static struct bpf_program *find_prog_by_sec_insn(const struct bpf_object *obj,
4897 						 size_t sec_idx, size_t insn_idx)
4898 {
4899 	int l = 0, r = obj->nr_programs - 1, m;
4900 	struct bpf_program *prog;
4901 
4902 	if (!obj->nr_programs)
4903 		return NULL;
4904 
4905 	while (l < r) {
4906 		m = l + (r - l + 1) / 2;
4907 		prog = &obj->programs[m];
4908 
4909 		if (prog->sec_idx < sec_idx ||
4910 		    (prog->sec_idx == sec_idx && prog->sec_insn_off <= insn_idx))
4911 			l = m;
4912 		else
4913 			r = m - 1;
4914 	}
4915 	/* matching program could be at index l, but it still might be the
4916 	 * wrong one, so we need to double check conditions for the last time
4917 	 */
4918 	prog = &obj->programs[l];
4919 	if (prog->sec_idx == sec_idx && prog_contains_insn(prog, insn_idx))
4920 		return prog;
4921 	return NULL;
4922 }
4923 
4924 static int
4925 bpf_object__collect_prog_relos(struct bpf_object *obj, Elf64_Shdr *shdr, Elf_Data *data)
4926 {
4927 	const char *relo_sec_name, *sec_name;
4928 	size_t sec_idx = shdr->sh_info, sym_idx;
4929 	struct bpf_program *prog;
4930 	struct reloc_desc *relos;
4931 	int err, i, nrels;
4932 	const char *sym_name;
4933 	__u32 insn_idx;
4934 	Elf_Scn *scn;
4935 	Elf_Data *scn_data;
4936 	Elf64_Sym *sym;
4937 	Elf64_Rel *rel;
4938 
4939 	if (sec_idx >= obj->efile.sec_cnt)
4940 		return -EINVAL;
4941 
4942 	scn = elf_sec_by_idx(obj, sec_idx);
4943 	scn_data = elf_sec_data(obj, scn);
4944 	if (!scn_data)
4945 		return -LIBBPF_ERRNO__FORMAT;
4946 
4947 	relo_sec_name = elf_sec_str(obj, shdr->sh_name);
4948 	sec_name = elf_sec_name(obj, scn);
4949 	if (!relo_sec_name || !sec_name)
4950 		return -EINVAL;
4951 
4952 	pr_debug("sec '%s': collecting relocation for section(%zu) '%s'\n",
4953 		 relo_sec_name, sec_idx, sec_name);
4954 	nrels = shdr->sh_size / shdr->sh_entsize;
4955 
4956 	for (i = 0; i < nrels; i++) {
4957 		rel = elf_rel_by_idx(data, i);
4958 		if (!rel) {
4959 			pr_warn("sec '%s': failed to get relo #%d\n", relo_sec_name, i);
4960 			return -LIBBPF_ERRNO__FORMAT;
4961 		}
4962 
4963 		sym_idx = ELF64_R_SYM(rel->r_info);
4964 		sym = elf_sym_by_idx(obj, sym_idx);
4965 		if (!sym) {
4966 			pr_warn("sec '%s': symbol #%zu not found for relo #%d\n",
4967 				relo_sec_name, sym_idx, i);
4968 			return -LIBBPF_ERRNO__FORMAT;
4969 		}
4970 
4971 		if (sym->st_shndx >= obj->efile.sec_cnt) {
4972 			pr_warn("sec '%s': corrupted symbol #%zu pointing to invalid section #%zu for relo #%d\n",
4973 				relo_sec_name, sym_idx, (size_t)sym->st_shndx, i);
4974 			return -LIBBPF_ERRNO__FORMAT;
4975 		}
4976 
4977 		if (rel->r_offset % BPF_INSN_SZ || rel->r_offset >= scn_data->d_size) {
4978 			pr_warn("sec '%s': invalid offset 0x%zx for relo #%d\n",
4979 				relo_sec_name, (size_t)rel->r_offset, i);
4980 			return -LIBBPF_ERRNO__FORMAT;
4981 		}
4982 
4983 		insn_idx = rel->r_offset / BPF_INSN_SZ;
4984 		/* relocations against static functions are recorded as
4985 		 * relocations against the section that contains a function;
4986 		 * in such case, symbol will be STT_SECTION and sym.st_name
4987 		 * will point to empty string (0), so fetch section name
4988 		 * instead
4989 		 */
4990 		if (ELF64_ST_TYPE(sym->st_info) == STT_SECTION && sym->st_name == 0)
4991 			sym_name = elf_sec_name(obj, elf_sec_by_idx(obj, sym->st_shndx));
4992 		else
4993 			sym_name = elf_sym_str(obj, sym->st_name);
4994 		sym_name = sym_name ?: "<?";
4995 
4996 		pr_debug("sec '%s': relo #%d: insn #%u against '%s'\n",
4997 			 relo_sec_name, i, insn_idx, sym_name);
4998 
4999 		prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
5000 		if (!prog) {
5001 			pr_debug("sec '%s': relo #%d: couldn't find program in section '%s' for insn #%u, probably overridden weak function, skipping...\n",
5002 				relo_sec_name, i, sec_name, insn_idx);
5003 			continue;
5004 		}
5005 
5006 		relos = libbpf_reallocarray(prog->reloc_desc,
5007 					    prog->nr_reloc + 1, sizeof(*relos));
5008 		if (!relos)
5009 			return -ENOMEM;
5010 		prog->reloc_desc = relos;
5011 
5012 		/* adjust insn_idx to local BPF program frame of reference */
5013 		insn_idx -= prog->sec_insn_off;
5014 		err = bpf_program__record_reloc(prog, &relos[prog->nr_reloc],
5015 						insn_idx, sym_name, sym, rel);
5016 		if (err)
5017 			return err;
5018 
5019 		prog->nr_reloc++;
5020 	}
5021 	return 0;
5022 }
5023 
5024 static int map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map)
5025 {
5026 	int id;
5027 
5028 	if (!obj->btf)
5029 		return -ENOENT;
5030 
5031 	/* if it's BTF-defined map, we don't need to search for type IDs.
5032 	 * For struct_ops map, it does not need btf_key_type_id and
5033 	 * btf_value_type_id.
5034 	 */
5035 	if (map->sec_idx == obj->efile.btf_maps_shndx || bpf_map__is_struct_ops(map))
5036 		return 0;
5037 
5038 	/*
5039 	 * LLVM annotates global data differently in BTF, that is,
5040 	 * only as '.data', '.bss', '.percpu' or '.rodata'.
5041 	 */
5042 	if (!bpf_map__is_internal(map))
5043 		return -ENOENT;
5044 
5045 	id = btf__find_by_name(obj->btf, map->real_name);
5046 	if (id < 0)
5047 		return id;
5048 
5049 	map->btf_key_type_id = 0;
5050 	map->btf_value_type_id = id;
5051 	return 0;
5052 }
5053 
5054 static int bpf_get_map_info_from_fdinfo(int fd, struct bpf_map_info *info)
5055 {
5056 	char file[PATH_MAX], buff[4096];
5057 	FILE *fp;
5058 	__u32 val;
5059 	int err;
5060 
5061 	snprintf(file, sizeof(file), "/proc/%d/fdinfo/%d", getpid(), fd);
5062 	memset(info, 0, sizeof(*info));
5063 
5064 	fp = fopen(file, "re");
5065 	if (!fp) {
5066 		err = -errno;
5067 		pr_warn("failed to open %s: %s. No procfs support?\n", file,
5068 			errstr(err));
5069 		return err;
5070 	}
5071 
5072 	while (fgets(buff, sizeof(buff), fp)) {
5073 		if (sscanf(buff, "map_type:\t%u", &val) == 1)
5074 			info->type = val;
5075 		else if (sscanf(buff, "key_size:\t%u", &val) == 1)
5076 			info->key_size = val;
5077 		else if (sscanf(buff, "value_size:\t%u", &val) == 1)
5078 			info->value_size = val;
5079 		else if (sscanf(buff, "max_entries:\t%u", &val) == 1)
5080 			info->max_entries = val;
5081 		else if (sscanf(buff, "map_flags:\t%x", &val) == 1)
5082 			info->map_flags = val;
5083 	}
5084 
5085 	fclose(fp);
5086 
5087 	return 0;
5088 }
5089 
5090 static bool map_is_created(const struct bpf_map *map)
5091 {
5092 	return map->obj->state >= OBJ_PREPARED || map->reused;
5093 }
5094 
5095 bool bpf_map__autocreate(const struct bpf_map *map)
5096 {
5097 	return map->autocreate;
5098 }
5099 
5100 int bpf_map__set_autocreate(struct bpf_map *map, bool autocreate)
5101 {
5102 	if (map_is_created(map))
5103 		return libbpf_err(-EBUSY);
5104 
5105 	map->autocreate = autocreate;
5106 	return 0;
5107 }
5108 
5109 int bpf_map__set_autoattach(struct bpf_map *map, bool autoattach)
5110 {
5111 	if (!bpf_map__is_struct_ops(map))
5112 		return libbpf_err(-EINVAL);
5113 
5114 	map->autoattach = autoattach;
5115 	return 0;
5116 }
5117 
5118 bool bpf_map__autoattach(const struct bpf_map *map)
5119 {
5120 	return map->autoattach;
5121 }
5122 
5123 int bpf_map__reuse_fd(struct bpf_map *map, int fd)
5124 {
5125 	struct bpf_map_info info;
5126 	__u32 len = sizeof(info), name_len;
5127 	int new_fd, err;
5128 	char *new_name;
5129 
5130 	memset(&info, 0, len);
5131 	err = bpf_map_get_info_by_fd(fd, &info, &len);
5132 	if (err && errno == EINVAL)
5133 		err = bpf_get_map_info_from_fdinfo(fd, &info);
5134 	if (err)
5135 		return libbpf_err(err);
5136 
5137 	name_len = strlen(info.name);
5138 	if (name_len == BPF_OBJ_NAME_LEN - 1 && strncmp(map->name, info.name, name_len) == 0)
5139 		new_name = strdup(map->name);
5140 	else
5141 		new_name = strdup(info.name);
5142 
5143 	if (!new_name)
5144 		return libbpf_err(-errno);
5145 
5146 	/*
5147 	 * Like dup(), but make sure new FD is >= 3 and has O_CLOEXEC set.
5148 	 * This is similar to what we do in ensure_good_fd(), but without
5149 	 * closing original FD.
5150 	 */
5151 	new_fd = fcntl(fd, F_DUPFD_CLOEXEC, 3);
5152 	if (new_fd < 0) {
5153 		err = -errno;
5154 		goto err_free_new_name;
5155 	}
5156 
5157 	err = reuse_fd(map->fd, new_fd);
5158 	if (err)
5159 		goto err_free_new_name;
5160 
5161 	free(map->name);
5162 
5163 	map->name = new_name;
5164 	map->def.type = info.type;
5165 	map->def.key_size = info.key_size;
5166 	map->def.value_size = info.value_size;
5167 	map->def.max_entries = info.max_entries;
5168 	map->def.map_flags = info.map_flags;
5169 	map->btf_key_type_id = info.btf_key_type_id;
5170 	map->btf_value_type_id = info.btf_value_type_id;
5171 	map->reused = true;
5172 	map->map_extra = info.map_extra;
5173 
5174 	return 0;
5175 
5176 err_free_new_name:
5177 	free(new_name);
5178 	return libbpf_err(err);
5179 }
5180 
5181 __u32 bpf_map__max_entries(const struct bpf_map *map)
5182 {
5183 	return map->def.max_entries;
5184 }
5185 
5186 struct bpf_map *bpf_map__inner_map(struct bpf_map *map)
5187 {
5188 	if (!bpf_map_type__is_map_in_map(map->def.type))
5189 		return errno = EINVAL, NULL;
5190 
5191 	return map->inner_map;
5192 }
5193 
5194 int bpf_map__set_max_entries(struct bpf_map *map, __u32 max_entries)
5195 {
5196 	if (map_is_created(map))
5197 		return libbpf_err(-EBUSY);
5198 
5199 	map->def.max_entries = max_entries;
5200 
5201 	/* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
5202 	if (map_is_ringbuf(map))
5203 		map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
5204 
5205 	return 0;
5206 }
5207 
5208 static int bpf_object_prepare_token(struct bpf_object *obj)
5209 {
5210 	const char *bpffs_path;
5211 	int bpffs_fd = -1, token_fd, err;
5212 	bool mandatory;
5213 	enum libbpf_print_level level;
5214 
5215 	/* token is explicitly prevented */
5216 	if (obj->token_path && obj->token_path[0] == '\0') {
5217 		pr_debug("object '%s': token is prevented, skipping...\n", obj->name);
5218 		return 0;
5219 	}
5220 
5221 	mandatory = obj->token_path != NULL;
5222 	level = mandatory ? LIBBPF_WARN : LIBBPF_DEBUG;
5223 
5224 	bpffs_path = obj->token_path ?: BPF_FS_DEFAULT_PATH;
5225 	bpffs_fd = open(bpffs_path, O_DIRECTORY, O_RDWR);
5226 	if (bpffs_fd < 0) {
5227 		err = -errno;
5228 		__pr(level, "object '%s': failed (%s) to open BPF FS mount at '%s'%s\n",
5229 		     obj->name, errstr(err), bpffs_path,
5230 		     mandatory ? "" : ", skipping optional step...");
5231 		return mandatory ? err : 0;
5232 	}
5233 
5234 	token_fd = bpf_token_create(bpffs_fd, 0);
5235 	close(bpffs_fd);
5236 	if (token_fd < 0) {
5237 		if (!mandatory && token_fd == -ENOENT) {
5238 			pr_debug("object '%s': BPF FS at '%s' doesn't have BPF token delegation set up, skipping...\n",
5239 				 obj->name, bpffs_path);
5240 			return 0;
5241 		}
5242 		__pr(level, "object '%s': failed (%d) to create BPF token from '%s'%s\n",
5243 		     obj->name, token_fd, bpffs_path,
5244 		     mandatory ? "" : ", skipping optional step...");
5245 		return mandatory ? token_fd : 0;
5246 	}
5247 
5248 	obj->feat_cache = calloc(1, sizeof(*obj->feat_cache));
5249 	if (!obj->feat_cache) {
5250 		close(token_fd);
5251 		return -ENOMEM;
5252 	}
5253 
5254 	obj->token_fd = token_fd;
5255 	obj->feat_cache->token_fd = token_fd;
5256 
5257 	return 0;
5258 }
5259 
5260 static int
5261 bpf_object__probe_loading(struct bpf_object *obj)
5262 {
5263 	struct bpf_insn insns[] = {
5264 		BPF_MOV64_IMM(BPF_REG_0, 0),
5265 		BPF_EXIT_INSN(),
5266 	};
5267 	int ret, insn_cnt = ARRAY_SIZE(insns);
5268 
5269 	if (obj->gen_loader || obj->token_fd)
5270 		return 0;
5271 
5272 	ret = bump_rlimit_memlock();
5273 	if (ret)
5274 		pr_warn("Failed to bump RLIMIT_MEMLOCK (err = %s), you might need to do it explicitly!\n",
5275 			errstr(ret));
5276 
5277 	/* make sure basic loading works */
5278 	ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
5279 	if (ret < 0)
5280 		ret = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, NULL);
5281 	if (ret < 0) {
5282 		ret = errno;
5283 		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",
5284 			__func__, errstr(ret));
5285 		return -ret;
5286 	}
5287 	close(ret);
5288 
5289 	return 0;
5290 }
5291 
5292 bool kernel_supports(const struct bpf_object *obj, enum kern_feature_id feat_id)
5293 {
5294 	if (obj->gen_loader)
5295 		/* To generate loader program assume the latest kernel
5296 		 * to avoid doing extra prog_load, map_create syscalls.
5297 		 */
5298 		return true;
5299 
5300 	if (obj->feat_cache)
5301 		return feat_supported(obj->feat_cache, feat_id);
5302 
5303 	return feat_supported(NULL, feat_id);
5304 }
5305 
5306 /* Used in testing to simulate missing features. */
5307 void bpf_object_set_feat_cache(struct bpf_object *obj, struct kern_feature_cache *cache)
5308 {
5309 	if (obj->feat_cache)
5310 		free(obj->feat_cache);
5311 	obj->feat_cache = cache;
5312 }
5313 
5314 static bool map_is_reuse_compat(const struct bpf_map *map, int map_fd)
5315 {
5316 	struct bpf_map_info map_info;
5317 	__u32 map_info_len = sizeof(map_info);
5318 	int err;
5319 
5320 	memset(&map_info, 0, map_info_len);
5321 	err = bpf_map_get_info_by_fd(map_fd, &map_info, &map_info_len);
5322 	if (err && errno == EINVAL)
5323 		err = bpf_get_map_info_from_fdinfo(map_fd, &map_info);
5324 	if (err) {
5325 		pr_warn("failed to get map info for map FD %d: %s\n", map_fd,
5326 			errstr(err));
5327 		return false;
5328 	}
5329 
5330 	/*
5331 	 * bpf_get_map_info_by_fd() for DEVMAP will always return flags with
5332 	 * BPF_F_RDONLY_PROG set, but it generally is not set at map creation time.
5333 	 * Thus, ignore the BPF_F_RDONLY_PROG flag in the flags returned from
5334 	 * bpf_get_map_info_by_fd() when checking for compatibility with an
5335 	 * existing DEVMAP.
5336 	 */
5337 	if (map->def.type == BPF_MAP_TYPE_DEVMAP || map->def.type == BPF_MAP_TYPE_DEVMAP_HASH)
5338 		map_info.map_flags &= ~BPF_F_RDONLY_PROG;
5339 
5340 	return (map_info.type == map->def.type &&
5341 		map_info.key_size == map->def.key_size &&
5342 		map_info.value_size == map->def.value_size &&
5343 		map_info.max_entries == map->def.max_entries &&
5344 		map_info.map_flags == map->def.map_flags &&
5345 		map_info.map_extra == map->map_extra);
5346 }
5347 
5348 static int
5349 bpf_object__reuse_map(struct bpf_map *map)
5350 {
5351 	int err, pin_fd;
5352 
5353 	pin_fd = bpf_obj_get(map->pin_path);
5354 	if (pin_fd < 0) {
5355 		err = -errno;
5356 		if (err == -ENOENT) {
5357 			pr_debug("found no pinned map to reuse at '%s'\n",
5358 				 map->pin_path);
5359 			return 0;
5360 		}
5361 
5362 		pr_warn("couldn't retrieve pinned map '%s': %s\n",
5363 			map->pin_path, errstr(err));
5364 		return err;
5365 	}
5366 
5367 	if (!map_is_reuse_compat(map, pin_fd)) {
5368 		pr_warn("couldn't reuse pinned map at '%s': parameter mismatch\n",
5369 			map->pin_path);
5370 		close(pin_fd);
5371 		return -EINVAL;
5372 	}
5373 
5374 	err = bpf_map__reuse_fd(map, pin_fd);
5375 	close(pin_fd);
5376 	if (err)
5377 		return err;
5378 
5379 	map->pinned = true;
5380 	pr_debug("reused pinned map at '%s'\n", map->pin_path);
5381 
5382 	return 0;
5383 }
5384 
5385 static int
5386 bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
5387 {
5388 	enum libbpf_map_type map_type = map->libbpf_type;
5389 	bool is_percpu = map_type == LIBBPF_MAP_PERCPU;
5390 	const __u64 update_flags = is_percpu ? BPF_F_ALL_CPUS : 0;
5391 	int err, zero = 0;
5392 	size_t mmap_sz;
5393 
5394 	if (obj->gen_loader) {
5395 		bpf_gen__map_update_elem(obj->gen_loader, map - obj->maps,
5396 					 map->mmaped, map->def.value_size, update_flags);
5397 		if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG)
5398 			bpf_gen__map_freeze(obj->gen_loader, map - obj->maps);
5399 		return 0;
5400 	}
5401 
5402 	err = bpf_map_update_elem(map->fd, &zero, map->mmaped, update_flags);
5403 	if (err) {
5404 		err = -errno;
5405 		pr_warn("map '%s': failed to set initial contents: %s\n",
5406 			bpf_map__name(map), errstr(err));
5407 		return err;
5408 	}
5409 
5410 	/* Freeze .rodata and .kconfig map as read-only from syscall side. */
5411 	if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG) {
5412 		err = bpf_map_freeze(map->fd);
5413 		if (err) {
5414 			err = -errno;
5415 			pr_warn("map '%s': failed to freeze as read-only: %s\n",
5416 				bpf_map__name(map), errstr(err));
5417 			return err;
5418 		}
5419 	}
5420 
5421 	/* Remap anonymous mmap()-ed "map initialization image" as
5422 	 * a BPF map-backed mmap()-ed memory, but preserving the same
5423 	 * memory address. This will cause kernel to change process'
5424 	 * page table to point to a different piece of kernel memory,
5425 	 * but from userspace point of view memory address (and its
5426 	 * contents, being identical at this point) will stay the
5427 	 * same. This mapping will be released by bpf_object__close()
5428 	 * as per normal clean up procedure.
5429 	 */
5430 	mmap_sz = bpf_map_mmap_sz(map);
5431 	if (map->def.map_flags & BPF_F_MMAPABLE) {
5432 		void *mmaped;
5433 		int prot;
5434 
5435 		if (map->def.map_flags & BPF_F_RDONLY_PROG)
5436 			prot = PROT_READ;
5437 		else
5438 			prot = PROT_READ | PROT_WRITE;
5439 		mmaped = mmap(map->mmaped, mmap_sz, prot, MAP_SHARED | MAP_FIXED, map->fd, 0);
5440 		if (mmaped == MAP_FAILED) {
5441 			err = -errno;
5442 			pr_warn("map '%s': failed to re-mmap() contents: %s\n",
5443 				bpf_map__name(map), errstr(err));
5444 			return err;
5445 		}
5446 		map->mmaped = mmaped;
5447 	} else if (is_percpu) {
5448 		if (mprotect(map->mmaped, mmap_sz, PROT_READ)) {
5449 			err = -errno;
5450 			pr_warn("map '%s': failed to mprotect() contents: %s\n",
5451 				bpf_map__name(map), errstr(err));
5452 			return err;
5453 		}
5454 	} else if (map->mmaped) {
5455 		munmap(map->mmaped, mmap_sz);
5456 		map->mmaped = NULL;
5457 	}
5458 
5459 	return 0;
5460 }
5461 
5462 static void bpf_map__destroy(struct bpf_map *map);
5463 
5464 static int bpf_object__create_map(struct bpf_object *obj, struct bpf_map *map, bool is_inner)
5465 {
5466 	LIBBPF_OPTS(bpf_map_create_opts, create_attr);
5467 	struct bpf_map_def *def = &map->def;
5468 	const char *map_name = NULL;
5469 	int err = 0, map_fd;
5470 
5471 	if (kernel_supports(obj, FEAT_PROG_NAME))
5472 		map_name = map->name;
5473 	create_attr.map_ifindex = map->map_ifindex;
5474 	create_attr.map_flags = def->map_flags;
5475 	create_attr.numa_node = map->numa_node;
5476 	create_attr.map_extra = map->map_extra;
5477 	create_attr.token_fd = obj->token_fd;
5478 	if (obj->token_fd)
5479 		create_attr.map_flags |= BPF_F_TOKEN_FD;
5480 	if (map->excl_prog) {
5481 		err = bpf_prog_compute_hash(map->excl_prog);
5482 		if (err)
5483 			return err;
5484 
5485 		create_attr.excl_prog_hash = map->excl_prog->hash;
5486 		create_attr.excl_prog_hash_size = SHA256_DIGEST_LENGTH;
5487 	}
5488 
5489 	if (bpf_map__is_struct_ops(map)) {
5490 		create_attr.btf_vmlinux_value_type_id = map->btf_vmlinux_value_type_id;
5491 		if (map->mod_btf_fd >= 0) {
5492 			create_attr.value_type_btf_obj_fd = map->mod_btf_fd;
5493 			create_attr.map_flags |= BPF_F_VTYPE_BTF_OBJ_FD;
5494 		}
5495 	}
5496 
5497 	if (obj->btf && btf__fd(obj->btf) >= 0) {
5498 		create_attr.btf_fd = btf__fd(obj->btf);
5499 		create_attr.btf_key_type_id = map->btf_key_type_id;
5500 		create_attr.btf_value_type_id = map->btf_value_type_id;
5501 	}
5502 
5503 	if (bpf_map_type__is_map_in_map(def->type)) {
5504 		if (map->inner_map) {
5505 			err = map_set_def_max_entries(map->inner_map);
5506 			if (err)
5507 				return err;
5508 			err = bpf_object__create_map(obj, map->inner_map, true);
5509 			if (err) {
5510 				pr_warn("map '%s': failed to create inner map: %s\n",
5511 					map->name, errstr(err));
5512 				return err;
5513 			}
5514 			map->inner_map_fd = map->inner_map->fd;
5515 		}
5516 		if (map->inner_map_fd >= 0)
5517 			create_attr.inner_map_fd = map->inner_map_fd;
5518 	}
5519 
5520 	switch (def->type) {
5521 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
5522 	case BPF_MAP_TYPE_CGROUP_ARRAY:
5523 	case BPF_MAP_TYPE_STACK_TRACE:
5524 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
5525 	case BPF_MAP_TYPE_HASH_OF_MAPS:
5526 	case BPF_MAP_TYPE_DEVMAP:
5527 	case BPF_MAP_TYPE_DEVMAP_HASH:
5528 	case BPF_MAP_TYPE_CPUMAP:
5529 	case BPF_MAP_TYPE_XSKMAP:
5530 	case BPF_MAP_TYPE_SOCKMAP:
5531 	case BPF_MAP_TYPE_SOCKHASH:
5532 	case BPF_MAP_TYPE_QUEUE:
5533 	case BPF_MAP_TYPE_STACK:
5534 	case BPF_MAP_TYPE_ARENA:
5535 		create_attr.btf_fd = 0;
5536 		create_attr.btf_key_type_id = 0;
5537 		create_attr.btf_value_type_id = 0;
5538 		map->btf_key_type_id = 0;
5539 		map->btf_value_type_id = 0;
5540 		break;
5541 	case BPF_MAP_TYPE_STRUCT_OPS:
5542 		create_attr.btf_value_type_id = 0;
5543 		break;
5544 	default:
5545 		break;
5546 	}
5547 
5548 	if (obj->gen_loader) {
5549 		bpf_gen__map_create(obj->gen_loader, def->type, map_name,
5550 				    def->key_size, def->value_size, def->max_entries,
5551 				    &create_attr, is_inner ? -1 : map - obj->maps);
5552 		/* We keep pretenting we have valid FD to pass various fd >= 0
5553 		 * checks by just keeping original placeholder FDs in place.
5554 		 * See bpf_object__add_map() comment.
5555 		 * This placeholder fd will not be used with any syscall and
5556 		 * will be reset to -1 eventually.
5557 		 */
5558 		map_fd = map->fd;
5559 	} else {
5560 		map_fd = bpf_map_create(def->type, map_name,
5561 					def->key_size, def->value_size,
5562 					def->max_entries, &create_attr);
5563 	}
5564 	if (map_fd < 0 && (create_attr.btf_key_type_id || create_attr.btf_value_type_id)) {
5565 		err = -errno;
5566 		pr_warn("Error in bpf_create_map_xattr(%s): %s. Retrying without BTF.\n",
5567 			map->name, errstr(err));
5568 		create_attr.btf_fd = 0;
5569 		create_attr.btf_key_type_id = 0;
5570 		create_attr.btf_value_type_id = 0;
5571 		map->btf_key_type_id = 0;
5572 		map->btf_value_type_id = 0;
5573 		map_fd = bpf_map_create(def->type, map_name,
5574 					def->key_size, def->value_size,
5575 					def->max_entries, &create_attr);
5576 	}
5577 
5578 	if (bpf_map_type__is_map_in_map(def->type) && map->inner_map) {
5579 		if (obj->gen_loader)
5580 			map->inner_map->fd = -1;
5581 		bpf_map__destroy(map->inner_map);
5582 		zfree(&map->inner_map);
5583 	}
5584 
5585 	if (map_fd < 0)
5586 		return map_fd;
5587 
5588 	/* obj->gen_loader case, prevent reuse_fd() from closing map_fd */
5589 	if (map->fd == map_fd)
5590 		return 0;
5591 
5592 	/* Keep placeholder FD value but now point it to the BPF map object.
5593 	 * This way everything that relied on this map's FD (e.g., relocated
5594 	 * ldimm64 instructions) will stay valid and won't need adjustments.
5595 	 * map->fd stays valid but now point to what map_fd points to.
5596 	 */
5597 	return reuse_fd(map->fd, map_fd);
5598 }
5599 
5600 static int init_map_in_map_slots(struct bpf_object *obj, struct bpf_map *map)
5601 {
5602 	const struct bpf_map *targ_map;
5603 	unsigned int i;
5604 	int fd, err = 0;
5605 
5606 	for (i = 0; i < map->init_slots_sz; i++) {
5607 		if (!map->init_slots[i])
5608 			continue;
5609 
5610 		targ_map = map->init_slots[i];
5611 		fd = targ_map->fd;
5612 
5613 		if (obj->gen_loader) {
5614 			bpf_gen__populate_outer_map(obj->gen_loader,
5615 						    map - obj->maps, i,
5616 						    targ_map - obj->maps);
5617 		} else {
5618 			err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5619 		}
5620 		if (err) {
5621 			err = -errno;
5622 			pr_warn("map '%s': failed to initialize slot [%u] to map '%s' fd=%d: %s\n",
5623 				map->name, i, targ_map->name, fd, errstr(err));
5624 			return err;
5625 		}
5626 		pr_debug("map '%s': slot [%u] set to map '%s' fd=%d\n",
5627 			 map->name, i, targ_map->name, fd);
5628 	}
5629 
5630 	zfree(&map->init_slots);
5631 	map->init_slots_sz = 0;
5632 
5633 	return 0;
5634 }
5635 
5636 static int init_prog_array_slots(struct bpf_object *obj, struct bpf_map *map)
5637 {
5638 	const struct bpf_program *targ_prog;
5639 	unsigned int i;
5640 	int fd, err;
5641 
5642 	if (obj->gen_loader)
5643 		return -ENOTSUP;
5644 
5645 	for (i = 0; i < map->init_slots_sz; i++) {
5646 		if (!map->init_slots[i])
5647 			continue;
5648 
5649 		targ_prog = map->init_slots[i];
5650 		fd = bpf_program__fd(targ_prog);
5651 
5652 		err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5653 		if (err) {
5654 			err = -errno;
5655 			pr_warn("map '%s': failed to initialize slot [%u] to prog '%s' fd=%d: %s\n",
5656 				map->name, i, targ_prog->name, fd, errstr(err));
5657 			return err;
5658 		}
5659 		pr_debug("map '%s': slot [%u] set to prog '%s' fd=%d\n",
5660 			 map->name, i, targ_prog->name, fd);
5661 	}
5662 
5663 	zfree(&map->init_slots);
5664 	map->init_slots_sz = 0;
5665 
5666 	return 0;
5667 }
5668 
5669 static int bpf_object_init_prog_arrays(struct bpf_object *obj)
5670 {
5671 	struct bpf_map *map;
5672 	int i, err;
5673 
5674 	for (i = 0; i < obj->nr_maps; i++) {
5675 		map = &obj->maps[i];
5676 
5677 		if (!map->init_slots_sz || map->def.type != BPF_MAP_TYPE_PROG_ARRAY)
5678 			continue;
5679 
5680 		err = init_prog_array_slots(obj, map);
5681 		if (err < 0)
5682 			return err;
5683 	}
5684 	return 0;
5685 }
5686 
5687 static int map_set_def_max_entries(struct bpf_map *map)
5688 {
5689 	if (map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY && !map->def.max_entries) {
5690 		int nr_cpus;
5691 
5692 		nr_cpus = libbpf_num_possible_cpus();
5693 		if (nr_cpus < 0) {
5694 			pr_warn("map '%s': failed to determine number of system CPUs: %d\n",
5695 				map->name, nr_cpus);
5696 			return nr_cpus;
5697 		}
5698 		pr_debug("map '%s': setting size to %d\n", map->name, nr_cpus);
5699 		map->def.max_entries = nr_cpus;
5700 	}
5701 
5702 	return 0;
5703 }
5704 
5705 static int
5706 bpf_object__create_maps(struct bpf_object *obj)
5707 {
5708 	struct bpf_map *map;
5709 	unsigned int i, j;
5710 	int err;
5711 	bool retried;
5712 
5713 	for (i = 0; i < obj->nr_maps; i++) {
5714 		map = &obj->maps[i];
5715 
5716 		/* To support old kernels, we skip creating global data maps
5717 		 * (.rodata, .data, .kconfig, etc); later on, during program
5718 		 * loading, if we detect that at least one of the to-be-loaded
5719 		 * programs is referencing any global data map, we'll error
5720 		 * out with program name and relocation index logged.
5721 		 * This approach allows to accommodate Clang emitting
5722 		 * unnecessary .rodata.str1.1 sections for string literals,
5723 		 * but also it allows to have CO-RE applications that use
5724 		 * global variables in some of BPF programs, but not others.
5725 		 * If those global variable-using programs are not loaded at
5726 		 * runtime due to bpf_program__set_autoload(prog, false),
5727 		 * bpf_object loading will succeed just fine even on old
5728 		 * kernels.
5729 		 * Same skipping applies to percpu data.
5730 		 */
5731 		if (bpf_map__is_internal(map)) {
5732 			bool is_percpu = map->libbpf_type == LIBBPF_MAP_PERCPU;
5733 			enum kern_feature_id feat_id;
5734 
5735 			feat_id = is_percpu ? FEAT_PERCPU_DATA : FEAT_GLOBAL_DATA;
5736 			if (!kernel_supports(obj, feat_id))
5737 				map->autocreate = false;
5738 		}
5739 
5740 		if (!map->autocreate) {
5741 			pr_debug("map '%s': skipped auto-creating...\n", map->name);
5742 			continue;
5743 		}
5744 
5745 		err = map_set_def_max_entries(map);
5746 		if (err)
5747 			goto err_out;
5748 
5749 		retried = false;
5750 retry:
5751 		if (map->pin_path) {
5752 			err = bpf_object__reuse_map(map);
5753 			if (err) {
5754 				pr_warn("map '%s': error reusing pinned map\n",
5755 					map->name);
5756 				goto err_out;
5757 			}
5758 			if (retried && map->fd < 0) {
5759 				pr_warn("map '%s': cannot find pinned map\n",
5760 					map->name);
5761 				err = -ENOENT;
5762 				goto err_out;
5763 			}
5764 		}
5765 
5766 		if (map->reused) {
5767 			pr_debug("map '%s': skipping creation (preset fd=%d)\n",
5768 				 map->name, map->fd);
5769 		} else {
5770 			err = bpf_object__create_map(obj, map, false);
5771 			if (err)
5772 				goto err_out;
5773 
5774 			pr_debug("map '%s': created successfully, fd=%d\n",
5775 				 map->name, map->fd);
5776 
5777 			if (bpf_map__is_internal(map)) {
5778 				err = bpf_object__populate_internal_map(obj, map);
5779 				if (err < 0)
5780 					goto err_out;
5781 			} else if (map->def.type == BPF_MAP_TYPE_ARENA) {
5782 				map->mmaped = mmap((void *)(long)map->map_extra,
5783 						   bpf_map_mmap_sz(map), PROT_READ | PROT_WRITE,
5784 						   map->map_extra ? MAP_SHARED | MAP_FIXED : MAP_SHARED,
5785 						   map->fd, 0);
5786 				if (map->mmaped == MAP_FAILED) {
5787 					err = -errno;
5788 					map->mmaped = NULL;
5789 					pr_warn("map '%s': failed to mmap arena: %s\n",
5790 						map->name, errstr(err));
5791 					return err;
5792 				}
5793 				if (obj->arena_data) {
5794 					memcpy(map->mmaped + obj->arena_data_off, obj->arena_data,
5795 						obj->arena_data_sz);
5796 					zfree(&obj->arena_data);
5797 				}
5798 			}
5799 			if (map->init_slots_sz && map->def.type != BPF_MAP_TYPE_PROG_ARRAY) {
5800 				err = init_map_in_map_slots(obj, map);
5801 				if (err < 0)
5802 					goto err_out;
5803 			}
5804 		}
5805 
5806 		if (map->pin_path && !map->pinned) {
5807 			err = bpf_map__pin(map, NULL);
5808 			if (err) {
5809 				if (!retried && err == -EEXIST) {
5810 					retried = true;
5811 					goto retry;
5812 				}
5813 				pr_warn("map '%s': failed to auto-pin at '%s': %s\n",
5814 					map->name, map->pin_path, errstr(err));
5815 				goto err_out;
5816 			}
5817 		}
5818 	}
5819 
5820 	return 0;
5821 
5822 err_out:
5823 	pr_warn("map '%s': failed to create: %s\n", map->name, errstr(err));
5824 	pr_perm_msg(err);
5825 	for (j = 0; j < i; j++)
5826 		zclose(obj->maps[j].fd);
5827 	return err;
5828 }
5829 
5830 static bool bpf_core_is_flavor_sep(const char *s)
5831 {
5832 	/* check X___Y name pattern, where X and Y are not underscores */
5833 	return s[0] != '_' &&				      /* X */
5834 	       s[1] == '_' && s[2] == '_' && s[3] == '_' &&   /* ___ */
5835 	       s[4] != '_';				      /* Y */
5836 }
5837 
5838 /* Given 'some_struct_name___with_flavor' return the length of a name prefix
5839  * before last triple underscore. Struct name part after last triple
5840  * underscore is ignored by BPF CO-RE relocation during relocation matching.
5841  */
5842 size_t bpf_core_essential_name_len(const char *name)
5843 {
5844 	size_t n = strlen(name);
5845 	int i;
5846 
5847 	for (i = n - 5; i >= 0; i--) {
5848 		if (bpf_core_is_flavor_sep(name + i))
5849 			return i + 1;
5850 	}
5851 	return n;
5852 }
5853 
5854 void bpf_core_free_cands(struct bpf_core_cand_list *cands)
5855 {
5856 	if (!cands)
5857 		return;
5858 
5859 	free(cands->cands);
5860 	free(cands);
5861 }
5862 
5863 int bpf_core_add_cands(struct bpf_core_cand *local_cand,
5864 		       size_t local_essent_len,
5865 		       const struct btf *targ_btf,
5866 		       const char *targ_btf_name,
5867 		       int targ_start_id,
5868 		       struct bpf_core_cand_list *cands)
5869 {
5870 	struct bpf_core_cand *new_cands, *cand;
5871 	const struct btf_type *t, *local_t;
5872 	const char *targ_name, *local_name;
5873 	size_t targ_essent_len;
5874 	int n, i;
5875 
5876 	local_t = btf__type_by_id(local_cand->btf, local_cand->id);
5877 	local_name = btf__str_by_offset(local_cand->btf, local_t->name_off);
5878 
5879 	n = btf__type_cnt(targ_btf);
5880 	for (i = targ_start_id; i < n; i++) {
5881 		t = btf__type_by_id(targ_btf, i);
5882 		if (!btf_kind_core_compat(t, local_t))
5883 			continue;
5884 
5885 		targ_name = btf__name_by_offset(targ_btf, t->name_off);
5886 		if (str_is_empty(targ_name))
5887 			continue;
5888 
5889 		targ_essent_len = bpf_core_essential_name_len(targ_name);
5890 		if (targ_essent_len != local_essent_len)
5891 			continue;
5892 
5893 		if (strncmp(local_name, targ_name, local_essent_len) != 0)
5894 			continue;
5895 
5896 		pr_debug("CO-RE relocating [%u] %s %s: found target candidate [%d] %s %s in [%s]\n",
5897 			 local_cand->id, btf_kind_str(local_t),
5898 			 local_name, i, btf_kind_str(t), targ_name,
5899 			 targ_btf_name);
5900 		new_cands = libbpf_reallocarray(cands->cands, cands->len + 1,
5901 					      sizeof(*cands->cands));
5902 		if (!new_cands)
5903 			return -ENOMEM;
5904 
5905 		cand = &new_cands[cands->len];
5906 		cand->btf = targ_btf;
5907 		cand->id = i;
5908 
5909 		cands->cands = new_cands;
5910 		cands->len++;
5911 	}
5912 	return 0;
5913 }
5914 
5915 static bool is_btf_mod_allowed(const struct bpf_object *obj, const char *name)
5916 {
5917 	ssize_t i;
5918 
5919 	if (obj->btf_module_allowlist_cnt < 0)
5920 		return true;
5921 
5922 	for (i = 0; i < obj->btf_module_allowlist_cnt; i++) {
5923 		if (strcmp(obj->btf_module_allowlist[i], name) == 0)
5924 			return true;
5925 	}
5926 
5927 	return false;
5928 }
5929 
5930 static int load_module_btfs(struct bpf_object *obj)
5931 {
5932 	struct bpf_btf_info info;
5933 	struct module_btf *mod_btf;
5934 	struct btf *btf;
5935 	char name[64];
5936 	__u32 id = 0, len;
5937 	int err, fd;
5938 
5939 	if (obj->btf_modules_loaded)
5940 		return 0;
5941 
5942 	if (obj->gen_loader)
5943 		return 0;
5944 
5945 	/* don't do this again, even if we find no module BTFs */
5946 	obj->btf_modules_loaded = true;
5947 
5948 	/* kernel too old to support module BTFs */
5949 	if (!kernel_supports(obj, FEAT_MODULE_BTF))
5950 		return 0;
5951 
5952 	if (obj->btf_module_allowlist_cnt == 0)
5953 		return 0;
5954 
5955 	while (true) {
5956 		err = bpf_btf_get_next_id(id, &id);
5957 		if (err && errno == ENOENT)
5958 			return 0;
5959 		if (err && errno == EPERM) {
5960 			pr_debug("skipping module BTFs loading, missing privileges\n");
5961 			return 0;
5962 		}
5963 		if (err) {
5964 			err = -errno;
5965 			pr_warn("failed to iterate BTF objects: %s\n", errstr(err));
5966 			return err;
5967 		}
5968 
5969 		fd = bpf_btf_get_fd_by_id(id);
5970 		if (fd < 0) {
5971 			if (errno == ENOENT)
5972 				continue; /* expected race: BTF was unloaded */
5973 			err = -errno;
5974 			pr_warn("failed to get BTF object #%u FD: %s\n", id, errstr(err));
5975 			return err;
5976 		}
5977 
5978 		len = sizeof(info);
5979 		memset(&info, 0, sizeof(info));
5980 		info.name = ptr_to_u64(name);
5981 		info.name_len = sizeof(name);
5982 
5983 		btf = NULL;
5984 		err = bpf_btf_get_info_by_fd(fd, &info, &len);
5985 		if (err) {
5986 			err = -errno;
5987 			pr_warn("failed to get BTF object #%u info: %s\n", id, errstr(err));
5988 			break;
5989 		}
5990 
5991 		/* ignore non-module BTFs */
5992 		if (!info.kernel_btf || strcmp(name, "vmlinux") == 0) {
5993 			close(fd);
5994 			continue;
5995 		}
5996 
5997 		if (!is_btf_mod_allowed(obj, name)) {
5998 			close(fd);
5999 			continue;
6000 		}
6001 
6002 		btf = btf_get_from_fd(fd, obj->btf_vmlinux);
6003 		err = libbpf_get_error(btf);
6004 		if (err) {
6005 			pr_warn("failed to load module [%s]'s BTF object #%u: %s\n",
6006 				name, id, errstr(err));
6007 			break;
6008 		}
6009 
6010 		err = libbpf_ensure_mem((void **)&obj->btf_modules, &obj->btf_module_cap,
6011 					sizeof(*obj->btf_modules), obj->btf_module_cnt + 1);
6012 		if (err)
6013 			break;
6014 
6015 		mod_btf = &obj->btf_modules[obj->btf_module_cnt];
6016 
6017 		mod_btf->btf = btf;
6018 		mod_btf->id = id;
6019 		mod_btf->fd = fd;
6020 		mod_btf->name = strdup(name);
6021 		if (!mod_btf->name) {
6022 			err = -ENOMEM;
6023 			break;
6024 		}
6025 		obj->btf_module_cnt++;
6026 
6027 		if (obj->btf_module_allowlist_cnt == obj->btf_module_cnt)
6028 			break;
6029 	}
6030 
6031 	if (err) {
6032 		btf__free(btf);
6033 		close(fd);
6034 	}
6035 	return err;
6036 }
6037 
6038 static struct bpf_core_cand_list *
6039 bpf_core_find_cands(struct bpf_object *obj, const struct btf *local_btf, __u32 local_type_id)
6040 {
6041 	struct bpf_core_cand local_cand = {};
6042 	struct bpf_core_cand_list *cands;
6043 	const struct btf *main_btf;
6044 	const struct btf_type *local_t;
6045 	const char *local_name;
6046 	size_t local_essent_len;
6047 	int err, i;
6048 
6049 	local_cand.btf = local_btf;
6050 	local_cand.id = local_type_id;
6051 	local_t = btf__type_by_id(local_btf, local_type_id);
6052 	if (!local_t)
6053 		return ERR_PTR(-EINVAL);
6054 
6055 	local_name = btf__name_by_offset(local_btf, local_t->name_off);
6056 	if (str_is_empty(local_name))
6057 		return ERR_PTR(-EINVAL);
6058 	local_essent_len = bpf_core_essential_name_len(local_name);
6059 
6060 	cands = calloc(1, sizeof(*cands));
6061 	if (!cands)
6062 		return ERR_PTR(-ENOMEM);
6063 
6064 	/* Attempt to find target candidates in vmlinux BTF first */
6065 	main_btf = obj->btf_vmlinux_override ?: obj->btf_vmlinux;
6066 	err = bpf_core_add_cands(&local_cand, local_essent_len, main_btf, "vmlinux", 1, cands);
6067 	if (err)
6068 		goto err_out;
6069 
6070 	/* if vmlinux BTF has any candidate, don't got for module BTFs */
6071 	if (cands->len)
6072 		return cands;
6073 
6074 	/* if vmlinux BTF was overridden, don't attempt to load module BTFs */
6075 	if (obj->btf_vmlinux_override)
6076 		return cands;
6077 
6078 	/* now look through module BTFs, trying to still find candidates */
6079 	err = load_module_btfs(obj);
6080 	if (err)
6081 		goto err_out;
6082 
6083 	for (i = 0; i < obj->btf_module_cnt; i++) {
6084 		err = bpf_core_add_cands(&local_cand, local_essent_len,
6085 					 obj->btf_modules[i].btf,
6086 					 obj->btf_modules[i].name,
6087 					 btf__type_cnt(obj->btf_vmlinux),
6088 					 cands);
6089 		if (err)
6090 			goto err_out;
6091 	}
6092 
6093 	return cands;
6094 err_out:
6095 	bpf_core_free_cands(cands);
6096 	return ERR_PTR(err);
6097 }
6098 
6099 /* Check local and target types for compatibility. This check is used for
6100  * type-based CO-RE relocations and follow slightly different rules than
6101  * field-based relocations. This function assumes that root types were already
6102  * checked for name match. Beyond that initial root-level name check, names
6103  * are completely ignored. Compatibility rules are as follows:
6104  *   - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs are considered compatible, but
6105  *     kind should match for local and target types (i.e., STRUCT is not
6106  *     compatible with UNION);
6107  *   - for ENUMs, the size is ignored;
6108  *   - for INT, size and signedness are ignored;
6109  *   - for ARRAY, dimensionality is ignored, element types are checked for
6110  *     compatibility recursively;
6111  *   - CONST/VOLATILE/RESTRICT modifiers are ignored;
6112  *   - TYPEDEFs/PTRs are compatible if types they pointing to are compatible;
6113  *   - FUNC_PROTOs are compatible if they have compatible signature: same
6114  *     number of input args and compatible return and argument types.
6115  * These rules are not set in stone and probably will be adjusted as we get
6116  * more experience with using BPF CO-RE relocations.
6117  */
6118 int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
6119 			      const struct btf *targ_btf, __u32 targ_id)
6120 {
6121 	return __bpf_core_types_are_compat(local_btf, local_id, targ_btf, targ_id, 32);
6122 }
6123 
6124 int bpf_core_types_match(const struct btf *local_btf, __u32 local_id,
6125 			 const struct btf *targ_btf, __u32 targ_id)
6126 {
6127 	return __bpf_core_types_match(local_btf, local_id, targ_btf, targ_id, false, 32);
6128 }
6129 
6130 static size_t bpf_core_hash_fn(const long key, void *ctx)
6131 {
6132 	return key;
6133 }
6134 
6135 static bool bpf_core_equal_fn(const long k1, const long k2, void *ctx)
6136 {
6137 	return k1 == k2;
6138 }
6139 
6140 static int record_relo_core(struct bpf_program *prog,
6141 			    const struct bpf_core_relo *core_relo, int insn_idx)
6142 {
6143 	struct reloc_desc *relos, *relo;
6144 
6145 	relos = libbpf_reallocarray(prog->reloc_desc,
6146 				    prog->nr_reloc + 1, sizeof(*relos));
6147 	if (!relos)
6148 		return -ENOMEM;
6149 	relo = &relos[prog->nr_reloc];
6150 	relo->type = RELO_CORE;
6151 	relo->insn_idx = insn_idx;
6152 	relo->core_relo = core_relo;
6153 	prog->reloc_desc = relos;
6154 	prog->nr_reloc++;
6155 	return 0;
6156 }
6157 
6158 static const struct bpf_core_relo *find_relo_core(struct bpf_program *prog, int insn_idx)
6159 {
6160 	struct reloc_desc *relo;
6161 	int i;
6162 
6163 	for (i = 0; i < prog->nr_reloc; i++) {
6164 		relo = &prog->reloc_desc[i];
6165 		if (relo->type != RELO_CORE || relo->insn_idx != insn_idx)
6166 			continue;
6167 
6168 		return relo->core_relo;
6169 	}
6170 
6171 	return NULL;
6172 }
6173 
6174 static int bpf_core_resolve_relo(struct bpf_program *prog,
6175 				 const struct bpf_core_relo *relo,
6176 				 int relo_idx,
6177 				 const struct btf *local_btf,
6178 				 struct hashmap *cand_cache,
6179 				 struct bpf_core_relo_res *targ_res)
6180 {
6181 	struct bpf_core_spec specs_scratch[3] = {};
6182 	struct bpf_core_cand_list *cands = NULL;
6183 	const char *prog_name = prog->name;
6184 	const struct btf_type *local_type;
6185 	const char *local_name;
6186 	__u32 local_id = relo->type_id;
6187 	int err;
6188 
6189 	local_type = btf__type_by_id(local_btf, local_id);
6190 	if (!local_type)
6191 		return -EINVAL;
6192 
6193 	local_name = btf__name_by_offset(local_btf, local_type->name_off);
6194 	if (!local_name)
6195 		return -EINVAL;
6196 
6197 	if (relo->kind != BPF_CORE_TYPE_ID_LOCAL &&
6198 	    !hashmap__find(cand_cache, local_id, &cands)) {
6199 		cands = bpf_core_find_cands(prog->obj, local_btf, local_id);
6200 		if (IS_ERR(cands)) {
6201 			pr_warn("prog '%s': relo #%d: target candidate search failed for [%u] %s %s: %ld\n",
6202 				prog_name, relo_idx, local_id, btf_kind_str(local_type),
6203 				local_name, PTR_ERR(cands));
6204 			return PTR_ERR(cands);
6205 		}
6206 		err = hashmap__set(cand_cache, local_id, cands, NULL, NULL);
6207 		if (err) {
6208 			bpf_core_free_cands(cands);
6209 			return err;
6210 		}
6211 	}
6212 
6213 	return bpf_core_calc_relo_insn(prog_name, relo, relo_idx, local_btf, cands, specs_scratch,
6214 				       targ_res);
6215 }
6216 
6217 static int
6218 bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
6219 {
6220 	const struct btf_ext_info_sec *sec;
6221 	struct bpf_core_relo_res targ_res;
6222 	const struct bpf_core_relo *rec;
6223 	const struct btf_ext_info *seg;
6224 	struct hashmap_entry *entry;
6225 	struct hashmap *cand_cache = NULL;
6226 	struct bpf_program *prog;
6227 	struct bpf_insn *insn;
6228 	const char *sec_name;
6229 	int i, err = 0, insn_idx, sec_idx, sec_num;
6230 
6231 	if (obj->btf_ext->core_relo_info.len == 0)
6232 		return 0;
6233 
6234 	if (targ_btf_path) {
6235 		obj->btf_vmlinux_override = btf__parse(targ_btf_path, NULL);
6236 		err = libbpf_get_error(obj->btf_vmlinux_override);
6237 		if (err) {
6238 			pr_warn("failed to parse target BTF: %s\n", errstr(err));
6239 			return err;
6240 		}
6241 	}
6242 
6243 	cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
6244 	if (IS_ERR(cand_cache)) {
6245 		err = PTR_ERR(cand_cache);
6246 		goto out;
6247 	}
6248 
6249 	seg = &obj->btf_ext->core_relo_info;
6250 	sec_num = 0;
6251 	for_each_btf_ext_sec(seg, sec) {
6252 		sec_idx = seg->sec_idxs[sec_num];
6253 		sec_num++;
6254 
6255 		sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
6256 		if (str_is_empty(sec_name)) {
6257 			err = -EINVAL;
6258 			goto out;
6259 		}
6260 
6261 		pr_debug("sec '%s': found %u CO-RE relocations\n", sec_name, sec->num_info);
6262 
6263 		for_each_btf_ext_rec(seg, sec, i, rec) {
6264 			if (rec->insn_off % BPF_INSN_SZ) {
6265 				err = -EINVAL;
6266 				goto out;
6267 			}
6268 
6269 			insn_idx = rec->insn_off / BPF_INSN_SZ;
6270 			prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
6271 			if (!prog) {
6272 				/* When __weak subprog is "overridden" by another instance
6273 				 * of the subprog from a different object file, linker still
6274 				 * appends all the .BTF.ext info that used to belong to that
6275 				 * eliminated subprogram.
6276 				 * This is similar to what x86-64 linker does for relocations.
6277 				 * So just ignore such relocations just like we ignore
6278 				 * subprog instructions when discovering subprograms.
6279 				 */
6280 				pr_debug("sec '%s': skipping CO-RE relocation #%d for insn #%d belonging to eliminated weak subprogram\n",
6281 					 sec_name, i, insn_idx);
6282 				continue;
6283 			}
6284 			/* no need to apply CO-RE relocation if the program is
6285 			 * not going to be loaded
6286 			 */
6287 			if (!prog->autoload)
6288 				continue;
6289 
6290 			/* adjust insn_idx from section frame of reference to the local
6291 			 * program's frame of reference; (sub-)program code is not yet
6292 			 * relocated, so it's enough to just subtract in-section offset
6293 			 */
6294 			insn_idx = insn_idx - prog->sec_insn_off;
6295 			if (insn_idx >= prog->insns_cnt) {
6296 				err = -EINVAL;
6297 				goto out;
6298 			}
6299 			insn = &prog->insns[insn_idx];
6300 
6301 			if (is_ldimm64_insn(insn) && (size_t)insn_idx + 1 >= prog->insns_cnt) {
6302 				pr_warn("prog '%s': relo #%d: insn #%d (LDIMM64) is truncated\n",
6303 					prog->name, i, insn_idx);
6304 				err = -EINVAL;
6305 				goto out;
6306 			}
6307 
6308 			err = record_relo_core(prog, rec, insn_idx);
6309 			if (err) {
6310 				pr_warn("prog '%s': relo #%d: failed to record relocation: %s\n",
6311 					prog->name, i, errstr(err));
6312 				goto out;
6313 			}
6314 
6315 			if (prog->obj->gen_loader)
6316 				continue;
6317 
6318 			err = bpf_core_resolve_relo(prog, rec, i, obj->btf, cand_cache, &targ_res);
6319 			if (err) {
6320 				pr_warn("prog '%s': relo #%d: failed to relocate: %s\n",
6321 					prog->name, i, errstr(err));
6322 				goto out;
6323 			}
6324 
6325 			err = bpf_core_patch_insn(prog->name, insn, insn_idx, rec, i, &targ_res);
6326 			if (err) {
6327 				pr_warn("prog '%s': relo #%d: failed to patch insn #%d: %s\n",
6328 					prog->name, i, insn_idx, errstr(err));
6329 				goto out;
6330 			}
6331 		}
6332 	}
6333 
6334 out:
6335 	/* obj->btf_vmlinux and module BTFs are freed after object load */
6336 	btf__free(obj->btf_vmlinux_override);
6337 	obj->btf_vmlinux_override = NULL;
6338 
6339 	if (!IS_ERR_OR_NULL(cand_cache)) {
6340 		hashmap__for_each_entry(cand_cache, entry, i) {
6341 			bpf_core_free_cands(entry->pvalue);
6342 		}
6343 		hashmap__free(cand_cache);
6344 	}
6345 	return err;
6346 }
6347 
6348 /* base map load ldimm64 special constant, used also for log fixup logic */
6349 #define POISON_LDIMM64_MAP_BASE 2001000000
6350 #define POISON_LDIMM64_MAP_PFX "200100"
6351 
6352 static void poison_map_ldimm64(struct bpf_program *prog, int relo_idx,
6353 			       int insn_idx, struct bpf_insn *insn,
6354 			       int map_idx, const struct bpf_map *map)
6355 {
6356 	int i;
6357 
6358 	pr_debug("prog '%s': relo #%d: poisoning insn #%d that loads map #%d '%s'\n",
6359 		 prog->name, relo_idx, insn_idx, map_idx, map->name);
6360 
6361 	/* we turn single ldimm64 into two identical invalid calls */
6362 	for (i = 0; i < 2; i++) {
6363 		insn->code = BPF_JMP | BPF_CALL;
6364 		insn->dst_reg = 0;
6365 		insn->src_reg = 0;
6366 		insn->off = 0;
6367 		/* if this instruction is reachable (not a dead code),
6368 		 * verifier will complain with something like:
6369 		 * invalid func unknown#2001000123
6370 		 * where lower 123 is map index into obj->maps[] array
6371 		 */
6372 		insn->imm = POISON_LDIMM64_MAP_BASE + map_idx;
6373 
6374 		insn++;
6375 	}
6376 }
6377 
6378 /* unresolved kfunc call special constant, used also for log fixup logic */
6379 #define POISON_CALL_KFUNC_BASE 2002000000
6380 #define POISON_CALL_KFUNC_PFX "2002"
6381 
6382 static void poison_kfunc_call(struct bpf_program *prog, int relo_idx,
6383 			      int insn_idx, struct bpf_insn *insn,
6384 			      int ext_idx, const struct extern_desc *ext)
6385 {
6386 	pr_debug("prog '%s': relo #%d: poisoning insn #%d that calls kfunc '%s'\n",
6387 		 prog->name, relo_idx, insn_idx, ext->name);
6388 
6389 	/* we turn kfunc call into invalid helper call with identifiable constant */
6390 	insn->code = BPF_JMP | BPF_CALL;
6391 	insn->dst_reg = 0;
6392 	insn->src_reg = 0;
6393 	insn->off = 0;
6394 	/* if this instruction is reachable (not a dead code),
6395 	 * verifier will complain with something like:
6396 	 * invalid func unknown#2001000123
6397 	 * where lower 123 is extern index into obj->externs[] array
6398 	 */
6399 	insn->imm = POISON_CALL_KFUNC_BASE + ext_idx;
6400 }
6401 
6402 static int find_jt_map(struct bpf_object *obj, struct bpf_program *prog, unsigned int sym_off)
6403 {
6404 	size_t i;
6405 
6406 	for (i = 0; i < obj->jumptable_map_cnt; i++) {
6407 		/*
6408 		 * This might happen that same offset is used for two different
6409 		 * programs (as jump tables can be the same). However, for
6410 		 * different programs different maps should be created.
6411 		 */
6412 		if (obj->jumptable_maps[i].sym_off == sym_off &&
6413 		    obj->jumptable_maps[i].prog == prog)
6414 			return obj->jumptable_maps[i].fd;
6415 	}
6416 
6417 	return -ENOENT;
6418 }
6419 
6420 static int add_jt_map(struct bpf_object *obj, struct bpf_program *prog, unsigned int sym_off, int map_fd)
6421 {
6422 	size_t cnt = obj->jumptable_map_cnt;
6423 	size_t size = sizeof(obj->jumptable_maps[0]);
6424 	void *tmp;
6425 
6426 	tmp = libbpf_reallocarray(obj->jumptable_maps, cnt + 1, size);
6427 	if (!tmp)
6428 		return -ENOMEM;
6429 
6430 	obj->jumptable_maps = tmp;
6431 	obj->jumptable_maps[cnt].prog = prog;
6432 	obj->jumptable_maps[cnt].sym_off = sym_off;
6433 	obj->jumptable_maps[cnt].fd = map_fd;
6434 	obj->jumptable_map_cnt++;
6435 
6436 	return 0;
6437 }
6438 
6439 static int find_subprog_idx(struct bpf_program *prog, int insn_idx)
6440 {
6441 	int i;
6442 
6443 	for (i = prog->subprog_cnt - 1; i >= 0; i--) {
6444 		if (insn_idx >= prog->subprogs[i].sub_insn_off)
6445 			return i;
6446 	}
6447 
6448 	return -1;
6449 }
6450 
6451 static int create_jt_map(struct bpf_object *obj, struct bpf_program *prog, struct reloc_desc *relo)
6452 {
6453 	const __u32 jt_entry_size = 8;
6454 	unsigned int sym_off = relo->sym_off;
6455 	int jt_size = relo->sym_size;
6456 	__u32 max_entries = jt_size / jt_entry_size;
6457 	__u32 value_size = sizeof(struct bpf_insn_array_value);
6458 	struct bpf_insn_array_value val = {};
6459 	int subprog_idx;
6460 	int map_fd, err;
6461 	__u64 insn_off;
6462 	__u64 *jt;
6463 	__u32 i;
6464 
6465 	map_fd = find_jt_map(obj, prog, sym_off);
6466 	if (map_fd >= 0)
6467 		return map_fd;
6468 
6469 	if (sym_off % jt_entry_size) {
6470 		pr_warn("map '.jumptables': jumptable start %u should be multiple of %u\n",
6471 			sym_off, jt_entry_size);
6472 		return -EINVAL;
6473 	}
6474 
6475 	if (jt_size % jt_entry_size) {
6476 		pr_warn("map '.jumptables': jumptable size %d should be multiple of %u\n",
6477 			jt_size, jt_entry_size);
6478 		return -EINVAL;
6479 	}
6480 
6481 	map_fd = bpf_map_create(BPF_MAP_TYPE_INSN_ARRAY, ".jumptables",
6482 				4, value_size, max_entries, NULL);
6483 	if (map_fd < 0)
6484 		return map_fd;
6485 
6486 	if (!obj->jumptables_data) {
6487 		pr_warn("map '.jumptables': ELF file is missing jump table data\n");
6488 		err = -EINVAL;
6489 		goto err_close;
6490 	}
6491 	if (sym_off + jt_size > obj->jumptables_data_sz) {
6492 		pr_warn("map '.jumptables': jumptables_data size is %zu, trying to access %u\n",
6493 			obj->jumptables_data_sz, sym_off + jt_size);
6494 		err = -EINVAL;
6495 		goto err_close;
6496 	}
6497 
6498 	subprog_idx = -1; /* main program */
6499 	if (relo->insn_idx < 0 || relo->insn_idx >= prog->insns_cnt) {
6500 		pr_warn("map '.jumptables': invalid instruction index %d\n", relo->insn_idx);
6501 		err = -EINVAL;
6502 		goto err_close;
6503 	}
6504 	if (prog->subprogs)
6505 		subprog_idx = find_subprog_idx(prog, relo->insn_idx);
6506 
6507 	jt = (__u64 *)(obj->jumptables_data + sym_off);
6508 	for (i = 0; i < max_entries; i++) {
6509 		/*
6510 		 * The offset should be made to be relative to the beginning of
6511 		 * the main function, not the subfunction.
6512 		 */
6513 		insn_off = jt[i]/sizeof(struct bpf_insn);
6514 		if (subprog_idx >= 0) {
6515 			insn_off -= prog->subprogs[subprog_idx].sec_insn_off;
6516 			insn_off += prog->subprogs[subprog_idx].sub_insn_off;
6517 		} else {
6518 			insn_off -= prog->sec_insn_off;
6519 		}
6520 
6521 		/*
6522 		 * LLVM-generated jump tables contain u64 records, however
6523 		 * should contain values that fit in u32.
6524 		 */
6525 		if (insn_off > UINT32_MAX) {
6526 			pr_warn("map '.jumptables': invalid jump table value 0x%llx at offset %u\n",
6527 				(unsigned long long)jt[i], sym_off + i * jt_entry_size);
6528 			err = -EINVAL;
6529 			goto err_close;
6530 		}
6531 
6532 		val.orig_off = insn_off;
6533 		err = bpf_map_update_elem(map_fd, &i, &val, 0);
6534 		if (err)
6535 			goto err_close;
6536 	}
6537 
6538 	err = bpf_map_freeze(map_fd);
6539 	if (err)
6540 		goto err_close;
6541 
6542 	err = add_jt_map(obj, prog, sym_off, map_fd);
6543 	if (err)
6544 		goto err_close;
6545 
6546 	return map_fd;
6547 
6548 err_close:
6549 	close(map_fd);
6550 	return err;
6551 }
6552 
6553 /*
6554  * The kernel recognizes a pointer to a function in a frozen read-only map by
6555  * its value: the offset in bytes of the function in the program. It makes
6556  * callx work for tables of functions, structures of operations and vtables,
6557  * where pointers are mixed with other data. Functions have different offsets
6558  * in different programs, so create a copy of the map for the program.
6559  * The kernel replaces the offsets with the addresses of the functions when it
6560  * loads the program, which has to be the only user of the map.
6561  */
6562 static int create_func_ptr_map(struct bpf_object *obj, struct bpf_program *prog, int map_idx)
6563 {
6564 	LIBBPF_OPTS(bpf_map_create_opts, opts, .map_flags = BPF_F_RDONLY_PROG);
6565 	struct bpf_map *map = &obj->maps[map_idx];
6566 	__u32 value_size = map->def.value_size;
6567 	size_t i, j, cnt, sec_insn_off;
6568 	struct func_ptr *ptrs;
6569 	int map_fd, err, zero = 0;
6570 	__u64 val;
6571 	void *data, *tmp;
6572 
6573 	for (i = 0; i < obj->func_ptr_map_cnt; i++)
6574 		if (obj->func_ptr_maps[i].prog == prog &&
6575 		    obj->func_ptr_maps[i].map_idx == map_idx)
6576 			return obj->func_ptr_maps[i].fd;
6577 
6578 	/* the map is not created yet, what it's going to have is in mmaped */
6579 	if (!map->mmaped)
6580 		return -EINVAL;
6581 
6582 	data = malloc(value_size);
6583 	if (!data)
6584 		return -ENOMEM;
6585 	memcpy(data, map->mmaped, value_size);
6586 
6587 	ptrs = map->func_ptrs;
6588 	cnt = map->func_ptr_cnt;
6589 	for (i = 0; i < cnt; i++) {
6590 		if (ptrs[i].sec_off + sizeof(val) > value_size) {
6591 			err = -LIBBPF_ERRNO__FORMAT;
6592 			goto err_free;
6593 		}
6594 		/*
6595 		 * Static functions were appended by bpf_object__append_func_ptrs_code().
6596 		 * A global function is in the program only if the code refers to it.
6597 		 */
6598 		sec_insn_off = ptrs[i].text_off / BPF_INSN_SZ;
6599 		for (j = 0; j < prog->subprog_cnt; j++)
6600 			if (prog->subprogs[j].sec_insn_off == sec_insn_off)
6601 				break;
6602 		if (j == prog->subprog_cnt) {
6603 			pr_debug("prog '%s': map '%s': no function for the pointer at offset %zu, it's NULL\n",
6604 				 prog->name, map->name, ptrs[i].sec_off);
6605 			val = 0;
6606 		} else {
6607 			val = (__u64)prog->subprogs[j].sub_insn_off * BPF_INSN_SZ;
6608 		}
6609 		/* light skeleton can be generated for a target of another endianness */
6610 		if (!is_native_endianness(obj))
6611 			val = bswap_64(val);
6612 		memcpy(data + ptrs[i].sec_off, &val, sizeof(val));
6613 	}
6614 
6615 	/*
6616 	 * The kernel takes any aligned 64-bit value that is equal to the offset
6617 	 * of a function for a pointer. Tell when it's going to get it wrong.
6618 	 */
6619 	for (i = 0, j = 0; i + sizeof(val) <= value_size; i += sizeof(val)) {
6620 		__u32 k;
6621 
6622 		while (j < cnt && ptrs[j].sec_off < i)
6623 			j++;
6624 		if (j < cnt && ptrs[j].sec_off == i)
6625 			continue;
6626 		memcpy(&val, data + i, sizeof(val));
6627 		if (!is_native_endianness(obj))
6628 			val = bswap_64(val);
6629 		if (!val || val % BPF_INSN_SZ)
6630 			continue;
6631 		for (k = 0; k < prog->subprog_cnt; k++) {
6632 			if ((__u64)prog->subprogs[k].sub_insn_off * BPF_INSN_SZ != val)
6633 				continue;
6634 			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",
6635 				prog->name, map->name, (unsigned long long)val, i);
6636 			break;
6637 		}
6638 	}
6639 
6640 	if (obj->gen_loader) {
6641 		__u32 *ptr_offs = calloc(cnt, sizeof(*ptr_offs));
6642 		__u64 *ptr_vals = calloc(cnt, sizeof(*ptr_vals));
6643 
6644 		if (!ptr_offs || !ptr_vals) {
6645 			free(ptr_offs);
6646 			free(ptr_vals);
6647 			err = -ENOMEM;
6648 			goto err_free;
6649 		}
6650 		for (i = 0; i < cnt; i++) {
6651 			ptr_offs[i] = ptrs[i].sec_off;
6652 			memcpy(&ptr_vals[i], data + ptrs[i].sec_off, sizeof(val));
6653 			if (!is_native_endianness(obj))
6654 				ptr_vals[i] = bswap_64(ptr_vals[i]);
6655 		}
6656 		/* it's an index in fd_array of the loader, not an fd */
6657 		map_fd = bpf_gen__func_ptr_map_create(obj->gen_loader, map->name, map_idx, data,
6658 						      value_size, ptr_offs, ptr_vals, cnt);
6659 		free(ptr_offs);
6660 		free(ptr_vals);
6661 		goto done;
6662 	}
6663 
6664 	opts.token_fd = obj->token_fd;
6665 	if (obj->token_fd)
6666 		opts.map_flags |= BPF_F_TOKEN_FD;
6667 
6668 	map_fd = bpf_map_create(BPF_MAP_TYPE_ARRAY, map->name, sizeof(int), value_size, 1, &opts);
6669 	if (map_fd < 0) {
6670 		err = map_fd;
6671 		goto err_free;
6672 	}
6673 
6674 	err = bpf_map_update_elem(map_fd, &zero, data, 0);
6675 	if (!err)
6676 		err = bpf_map_freeze(map_fd);
6677 	if (err) {
6678 		err = -errno;
6679 		goto err_close;
6680 	}
6681 done:
6682 
6683 	tmp = libbpf_reallocarray(obj->func_ptr_maps, obj->func_ptr_map_cnt + 1,
6684 				  sizeof(*obj->func_ptr_maps));
6685 	if (!tmp) {
6686 		err = -ENOMEM;
6687 		goto err_close;
6688 	}
6689 	obj->func_ptr_maps = tmp;
6690 	obj->func_ptr_maps[obj->func_ptr_map_cnt].prog = prog;
6691 	obj->func_ptr_maps[obj->func_ptr_map_cnt].map_idx = map_idx;
6692 	obj->func_ptr_maps[obj->func_ptr_map_cnt].fd = map_fd;
6693 	obj->func_ptr_map_cnt++;
6694 
6695 	pr_debug("prog '%s': created a copy of map '%s' with %zu pointers to functions\n",
6696 		 prog->name, map->name, cnt);
6697 	free(data);
6698 	return map_fd;
6699 
6700 err_close:
6701 	if (!obj->gen_loader)
6702 		close(map_fd);
6703 err_free:
6704 	free(data);
6705 	return err;
6706 }
6707 
6708 /* Relocate data references within program code:
6709  *  - map references;
6710  *  - global variable references;
6711  *  - extern references.
6712  */
6713 static int
6714 bpf_object__relocate_data(struct bpf_object *obj, struct bpf_program *prog)
6715 {
6716 	int i;
6717 
6718 	for (i = 0; i < prog->nr_reloc; i++) {
6719 		struct reloc_desc *relo = &prog->reloc_desc[i];
6720 		struct bpf_insn *insn = &prog->insns[relo->insn_idx];
6721 		const struct bpf_map *map;
6722 		struct extern_desc *ext;
6723 
6724 		switch (relo->type) {
6725 		case RELO_LD64:
6726 			map = &obj->maps[relo->map_idx];
6727 			if (obj->gen_loader) {
6728 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX;
6729 				insn[0].imm = relo->map_idx;
6730 			} else if (map->autocreate) {
6731 				insn[0].src_reg = BPF_PSEUDO_MAP_FD;
6732 				insn[0].imm = map->fd;
6733 			} else {
6734 				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
6735 						   relo->map_idx, map);
6736 			}
6737 			break;
6738 		case RELO_DATA:
6739 			map = &obj->maps[relo->map_idx];
6740 			insn[1].imm = insn[0].imm + relo->sym_off;
6741 
6742 			if (relo->map_idx == obj->arena_map_idx)
6743 				insn[1].imm += obj->arena_data_off;
6744 
6745 			if (map->autocreate && map->func_ptr_cnt && prog->has_callx) {
6746 				int map_fd;
6747 
6748 				/* the program gets its own map with pointers to its functions */
6749 				map_fd = create_func_ptr_map(obj, prog, relo->map_idx);
6750 				if (map_fd < 0) {
6751 					pr_warn("prog '%s': relo #%d: can't create a copy of map '%s' with pointers to functions\n",
6752 						prog->name, i, map->name);
6753 					return map_fd;
6754 				}
6755 				insn[0].src_reg = obj->gen_loader ? BPF_PSEUDO_MAP_IDX_VALUE :
6756 								    BPF_PSEUDO_MAP_VALUE;
6757 				insn[0].imm = map_fd;
6758 			} else if (obj->gen_loader) {
6759 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
6760 				insn[0].imm = relo->map_idx;
6761 			} else if (map->autocreate) {
6762 				insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6763 				insn[0].imm = map->fd;
6764 			} else {
6765 				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
6766 						   relo->map_idx, map);
6767 			}
6768 			break;
6769 		case RELO_EXTERN_LD64:
6770 			ext = &obj->externs[relo->ext_idx];
6771 			if (ext->type == EXT_KCFG) {
6772 				if (obj->gen_loader) {
6773 					insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
6774 					insn[0].imm = obj->kconfig_map_idx;
6775 				} else {
6776 					insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6777 					insn[0].imm = obj->maps[obj->kconfig_map_idx].fd;
6778 				}
6779 				insn[1].imm = ext->kcfg.data_off;
6780 			} else /* EXT_KSYM */ {
6781 				if (ext->ksym.type_id && ext->is_set) { /* typed ksyms */
6782 					insn[0].src_reg = BPF_PSEUDO_BTF_ID;
6783 					insn[0].imm = ext->ksym.kernel_btf_id;
6784 					insn[1].imm = ext->ksym.kernel_btf_obj_fd;
6785 				} else { /* typeless ksyms or unresolved typed ksyms */
6786 					insn[0].imm = (__u32)ext->ksym.addr;
6787 					insn[1].imm = ext->ksym.addr >> 32;
6788 				}
6789 			}
6790 			break;
6791 		case RELO_EXTERN_CALL:
6792 			ext = &obj->externs[relo->ext_idx];
6793 			insn[0].src_reg = BPF_PSEUDO_KFUNC_CALL;
6794 			if (ext->is_set) {
6795 				insn[0].imm = ext->ksym.kernel_btf_id;
6796 				insn[0].off = ext->ksym.btf_fd_idx;
6797 			} else { /* unresolved weak kfunc call */
6798 				poison_kfunc_call(prog, i, relo->insn_idx, insn,
6799 						  relo->ext_idx, ext);
6800 			}
6801 			break;
6802 		case RELO_SUBPROG_ADDR:
6803 			if (insn[0].src_reg != BPF_PSEUDO_FUNC) {
6804 				pr_warn("prog '%s': relo #%d: bad insn\n",
6805 					prog->name, i);
6806 				return -EINVAL;
6807 			}
6808 			/* handled already */
6809 			break;
6810 		case RELO_CALL:
6811 			/* handled already */
6812 			break;
6813 		case RELO_CORE:
6814 			/* will be handled by bpf_program_record_relos() */
6815 			break;
6816 		case RELO_INSN_ARRAY: {
6817 			int map_fd;
6818 
6819 			map_fd = create_jt_map(obj, prog, relo);
6820 			if (map_fd < 0) {
6821 				pr_warn("prog '%s': relo #%d: can't create jump table: sym_off %u\n",
6822 					prog->name, i, relo->sym_off);
6823 				return map_fd;
6824 			}
6825 			insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6826 			insn->imm = map_fd;
6827 			insn->off = 0;
6828 		}
6829 			break;
6830 		default:
6831 			pr_warn("prog '%s': relo #%d: bad relo type %u\n",
6832 				prog->name, i, relo->type);
6833 			return -EINVAL;
6834 		}
6835 	}
6836 
6837 	return 0;
6838 }
6839 
6840 static int adjust_prog_btf_ext_info(const struct bpf_object *obj,
6841 				    const struct bpf_program *prog,
6842 				    const struct btf_ext_info *ext_info,
6843 				    void **prog_info, __u32 *prog_rec_cnt,
6844 				    __u32 *prog_rec_sz)
6845 {
6846 	void *copy_start = NULL, *copy_end = NULL;
6847 	void *rec, *rec_end, *new_prog_info;
6848 	const struct btf_ext_info_sec *sec;
6849 	size_t old_sz, new_sz;
6850 	int i, sec_num, sec_idx, off_adj;
6851 
6852 	sec_num = 0;
6853 	for_each_btf_ext_sec(ext_info, sec) {
6854 		sec_idx = ext_info->sec_idxs[sec_num];
6855 		sec_num++;
6856 		if (prog->sec_idx != sec_idx)
6857 			continue;
6858 
6859 		for_each_btf_ext_rec(ext_info, sec, i, rec) {
6860 			__u32 insn_off = *(__u32 *)rec / BPF_INSN_SZ;
6861 
6862 			if (insn_off < prog->sec_insn_off)
6863 				continue;
6864 			if (insn_off >= prog->sec_insn_off + prog->sec_insn_cnt)
6865 				break;
6866 
6867 			if (!copy_start)
6868 				copy_start = rec;
6869 			copy_end = rec + ext_info->rec_size;
6870 		}
6871 
6872 		if (!copy_start)
6873 			return -ENOENT;
6874 
6875 		/* append func/line info of a given (sub-)program to the main
6876 		 * program func/line info
6877 		 */
6878 		old_sz = (size_t)(*prog_rec_cnt) * ext_info->rec_size;
6879 		new_sz = old_sz + (copy_end - copy_start);
6880 		new_prog_info = realloc(*prog_info, new_sz);
6881 		if (!new_prog_info)
6882 			return -ENOMEM;
6883 		*prog_info = new_prog_info;
6884 		*prog_rec_cnt = new_sz / ext_info->rec_size;
6885 		memcpy(new_prog_info + old_sz, copy_start, copy_end - copy_start);
6886 
6887 		/* Kernel instruction offsets are in units of 8-byte
6888 		 * instructions, while .BTF.ext instruction offsets generated
6889 		 * by Clang are in units of bytes. So convert Clang offsets
6890 		 * into kernel offsets and adjust offset according to program
6891 		 * relocated position.
6892 		 */
6893 		off_adj = prog->sub_insn_off - prog->sec_insn_off;
6894 		rec = new_prog_info + old_sz;
6895 		rec_end = new_prog_info + new_sz;
6896 		for (; rec < rec_end; rec += ext_info->rec_size) {
6897 			__u32 *insn_off = rec;
6898 
6899 			*insn_off = *insn_off / BPF_INSN_SZ + off_adj;
6900 		}
6901 		*prog_rec_sz = ext_info->rec_size;
6902 		return 0;
6903 	}
6904 
6905 	return -ENOENT;
6906 }
6907 
6908 static int
6909 reloc_prog_func_and_line_info(const struct bpf_object *obj,
6910 			      struct bpf_program *main_prog,
6911 			      const struct bpf_program *prog)
6912 {
6913 	int err;
6914 
6915 	/* no .BTF.ext relocation if .BTF.ext is missing or kernel doesn't
6916 	 * support func/line info
6917 	 */
6918 	if (!obj->btf_ext || !kernel_supports(obj, FEAT_BTF_FUNC))
6919 		return 0;
6920 
6921 	/* only attempt func info relocation if main program's func_info
6922 	 * relocation was successful
6923 	 */
6924 	if (main_prog != prog && !main_prog->func_info)
6925 		goto line_info;
6926 
6927 	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->func_info,
6928 				       &main_prog->func_info,
6929 				       &main_prog->func_info_cnt,
6930 				       &main_prog->func_info_rec_size);
6931 	if (err) {
6932 		if (err != -ENOENT) {
6933 			pr_warn("prog '%s': error relocating .BTF.ext function info: %s\n",
6934 				prog->name, errstr(err));
6935 			return err;
6936 		}
6937 		if (main_prog->func_info) {
6938 			/*
6939 			 * Some info has already been found but has problem
6940 			 * in the last btf_ext reloc. Must have to error out.
6941 			 */
6942 			pr_warn("prog '%s': missing .BTF.ext function info.\n", prog->name);
6943 			return err;
6944 		}
6945 		/* Have problem loading the very first info. Ignore the rest. */
6946 		pr_warn("prog '%s': missing .BTF.ext function info for the main program, skipping all of .BTF.ext func info.\n",
6947 			prog->name);
6948 	}
6949 
6950 line_info:
6951 	/* don't relocate line info if main program's relocation failed */
6952 	if (main_prog != prog && !main_prog->line_info)
6953 		return 0;
6954 
6955 	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->line_info,
6956 				       &main_prog->line_info,
6957 				       &main_prog->line_info_cnt,
6958 				       &main_prog->line_info_rec_size);
6959 	if (err) {
6960 		if (err != -ENOENT) {
6961 			pr_warn("prog '%s': error relocating .BTF.ext line info: %s\n",
6962 				prog->name, errstr(err));
6963 			return err;
6964 		}
6965 		if (main_prog->line_info) {
6966 			/*
6967 			 * Some info has already been found but has problem
6968 			 * in the last btf_ext reloc. Must have to error out.
6969 			 */
6970 			pr_warn("prog '%s': missing .BTF.ext line info.\n", prog->name);
6971 			return err;
6972 		}
6973 		/* Have problem loading the very first info. Ignore the rest. */
6974 		pr_warn("prog '%s': missing .BTF.ext line info for the main program, skipping all of .BTF.ext line info.\n",
6975 			prog->name);
6976 	}
6977 	return 0;
6978 }
6979 
6980 static int cmp_relo_by_insn_idx(const void *key, const void *elem)
6981 {
6982 	size_t insn_idx = *(const size_t *)key;
6983 	const struct reloc_desc *relo = elem;
6984 
6985 	if (insn_idx == relo->insn_idx)
6986 		return 0;
6987 	return insn_idx < relo->insn_idx ? -1 : 1;
6988 }
6989 
6990 static struct reloc_desc *find_prog_insn_relo(const struct bpf_program *prog, size_t insn_idx)
6991 {
6992 	if (!prog->nr_reloc)
6993 		return NULL;
6994 	return bsearch(&insn_idx, prog->reloc_desc, prog->nr_reloc,
6995 		       sizeof(*prog->reloc_desc), cmp_relo_by_insn_idx);
6996 }
6997 
6998 static int append_subprog_relos(struct bpf_program *main_prog, struct bpf_program *subprog)
6999 {
7000 	int new_cnt = main_prog->nr_reloc + subprog->nr_reloc;
7001 	struct reloc_desc *relos;
7002 	int i;
7003 
7004 	if (main_prog == subprog)
7005 		return 0;
7006 	relos = libbpf_reallocarray(main_prog->reloc_desc, new_cnt, sizeof(*relos));
7007 	/* if new count is zero, reallocarray can return a valid NULL result;
7008 	 * in this case the previous pointer will be freed, so we *have to*
7009 	 * reassign old pointer to the new value (even if it's NULL)
7010 	 */
7011 	if (!relos && new_cnt)
7012 		return -ENOMEM;
7013 	if (subprog->nr_reloc)
7014 		memcpy(relos + main_prog->nr_reloc, subprog->reloc_desc,
7015 		       sizeof(*relos) * subprog->nr_reloc);
7016 
7017 	for (i = main_prog->nr_reloc; i < new_cnt; i++)
7018 		relos[i].insn_idx += subprog->sub_insn_off;
7019 	/* After insn_idx adjustment the 'relos' array is still sorted
7020 	 * by insn_idx and doesn't break bsearch.
7021 	 */
7022 	main_prog->reloc_desc = relos;
7023 	main_prog->nr_reloc = new_cnt;
7024 	return 0;
7025 }
7026 
7027 static int save_subprog_offsets(struct bpf_program *main_prog, struct bpf_program *subprog)
7028 {
7029 	size_t size = sizeof(main_prog->subprogs[0]);
7030 	int cnt = main_prog->subprog_cnt;
7031 	void *tmp;
7032 
7033 	tmp = libbpf_reallocarray(main_prog->subprogs, cnt + 1, size);
7034 	if (!tmp)
7035 		return -ENOMEM;
7036 
7037 	main_prog->subprogs = tmp;
7038 	main_prog->subprogs[cnt].sec_insn_off = subprog->sec_insn_off;
7039 	main_prog->subprogs[cnt].sub_insn_off = subprog->sub_insn_off;
7040 	main_prog->subprog_cnt++;
7041 
7042 	return 0;
7043 }
7044 
7045 static int
7046 bpf_object__append_subprog_code(struct bpf_object *obj, struct bpf_program *main_prog,
7047 				struct bpf_program *subprog)
7048 {
7049 	struct bpf_insn *insns;
7050 	size_t new_cnt;
7051 	int err;
7052 
7053 	subprog->sub_insn_off = main_prog->insns_cnt;
7054 
7055 	new_cnt = main_prog->insns_cnt + subprog->insns_cnt;
7056 	insns = libbpf_reallocarray(main_prog->insns, new_cnt, sizeof(*insns));
7057 	if (!insns) {
7058 		pr_warn("prog '%s': failed to realloc prog code\n", main_prog->name);
7059 		return -ENOMEM;
7060 	}
7061 	main_prog->insns = insns;
7062 	main_prog->insns_cnt = new_cnt;
7063 
7064 	memcpy(main_prog->insns + subprog->sub_insn_off, subprog->insns,
7065 	       subprog->insns_cnt * sizeof(*insns));
7066 
7067 	pr_debug("prog '%s': added %zu insns from sub-prog '%s'\n",
7068 		 main_prog->name, subprog->insns_cnt, subprog->name);
7069 
7070 	/* The subprog insns are now appended. Append its relos too. */
7071 	err = append_subprog_relos(main_prog, subprog);
7072 	if (err)
7073 		return err;
7074 
7075 	err = save_subprog_offsets(main_prog, subprog);
7076 	if (err) {
7077 		pr_warn("prog '%s': failed to add subprog offsets: %s\n",
7078 			main_prog->name, errstr(err));
7079 		return err;
7080 	}
7081 
7082 	return 0;
7083 }
7084 
7085 static int
7086 bpf_object__reloc_code(struct bpf_object *obj, struct bpf_program *main_prog,
7087 		       struct bpf_program *prog)
7088 {
7089 	size_t sub_insn_idx, insn_idx;
7090 	struct bpf_program *subprog;
7091 	struct reloc_desc *relo;
7092 	struct bpf_insn *insn;
7093 	int err;
7094 
7095 	err = reloc_prog_func_and_line_info(obj, main_prog, prog);
7096 	if (err)
7097 		return err;
7098 
7099 	for (insn_idx = 0; insn_idx < prog->sec_insn_cnt; insn_idx++) {
7100 		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
7101 		if (!insn_is_subprog_call(insn) && !insn_is_pseudo_func(insn))
7102 			continue;
7103 
7104 		relo = find_prog_insn_relo(prog, insn_idx);
7105 		if (relo && relo->type == RELO_EXTERN_CALL)
7106 			/* kfunc relocations will be handled later
7107 			 * in bpf_object__relocate_data()
7108 			 */
7109 			continue;
7110 		if (relo && relo->type != RELO_CALL && relo->type != RELO_SUBPROG_ADDR) {
7111 			pr_warn("prog '%s': unexpected relo for insn #%zu, type %u\n",
7112 				prog->name, insn_idx, relo->type);
7113 			return -LIBBPF_ERRNO__RELOC;
7114 		}
7115 		if (relo) {
7116 			/* sub-program instruction index is a combination of
7117 			 * an offset of a symbol pointed to by relocation and
7118 			 * call instruction's imm field; for global functions,
7119 			 * call always has imm = -1, but for static functions
7120 			 * relocation is against STT_SECTION and insn->imm
7121 			 * points to a start of a static function
7122 			 *
7123 			 * for subprog addr relocation, the relo->sym_off + insn->imm is
7124 			 * the byte offset in the corresponding section.
7125 			 */
7126 			if (relo->type == RELO_CALL)
7127 				sub_insn_idx = relo->sym_off / BPF_INSN_SZ + insn->imm + 1;
7128 			else
7129 				sub_insn_idx = (relo->sym_off + insn->imm) / BPF_INSN_SZ;
7130 		} else if (insn_is_pseudo_func(insn)) {
7131 			/*
7132 			 * RELO_SUBPROG_ADDR relo is always emitted even if both
7133 			 * functions are in the same section, so it shouldn't reach here.
7134 			 */
7135 			pr_warn("prog '%s': missing subprog addr relo for insn #%zu\n",
7136 				prog->name, insn_idx);
7137 			return -LIBBPF_ERRNO__RELOC;
7138 		} else {
7139 			/* if subprogram call is to a static function within
7140 			 * the same ELF section, there won't be any relocation
7141 			 * emitted, but it also means there is no additional
7142 			 * offset necessary, insns->imm is relative to
7143 			 * instruction's original position within the section
7144 			 */
7145 			sub_insn_idx = prog->sec_insn_off + insn_idx + insn->imm + 1;
7146 		}
7147 
7148 		/* we enforce that sub-programs should be in .text section */
7149 		subprog = find_prog_by_sec_insn(obj, obj->efile.text_shndx, sub_insn_idx);
7150 		if (!subprog) {
7151 			pr_warn("prog '%s': no .text section found yet sub-program call exists\n",
7152 				prog->name);
7153 			return -LIBBPF_ERRNO__RELOC;
7154 		}
7155 
7156 		/* if it's the first call instruction calling into this
7157 		 * subprogram (meaning this subprog hasn't been processed
7158 		 * yet) within the context of current main program:
7159 		 *   - append it at the end of main program's instructions blog;
7160 		 *   - process is recursively, while current program is put on hold;
7161 		 *   - if that subprogram calls some other not yet processes
7162 		 *   subprogram, same thing will happen recursively until
7163 		 *   there are no more unprocesses subprograms left to append
7164 		 *   and relocate.
7165 		 */
7166 		if (subprog->sub_insn_off == 0) {
7167 			err = bpf_object__append_subprog_code(obj, main_prog, subprog);
7168 			if (err)
7169 				return err;
7170 			err = bpf_object__reloc_code(obj, main_prog, subprog);
7171 			if (err)
7172 				return err;
7173 		}
7174 
7175 		/* main_prog->insns memory could have been re-allocated, so
7176 		 * calculate pointer again
7177 		 */
7178 		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
7179 		/* calculate correct instruction position within current main
7180 		 * prog; each main prog can have a different set of
7181 		 * subprograms appended (potentially in different order as
7182 		 * well), so position of any subprog can be different for
7183 		 * different main programs
7184 		 */
7185 		insn->imm = subprog->sub_insn_off - (prog->sub_insn_off + insn_idx) - 1;
7186 
7187 		pr_debug("prog '%s': insn #%zu relocated, imm %d points to subprog '%s' (now at %zu offset)\n",
7188 			 prog->name, insn_idx, insn->imm, subprog->name, subprog->sub_insn_off);
7189 	}
7190 
7191 	return 0;
7192 }
7193 
7194 /* Append to the main program all functions that the data of the map points to */
7195 static int
7196 bpf_object__append_func_ptrs_code(struct bpf_object *obj, struct bpf_program *main_prog,
7197 				  const struct bpf_map *map)
7198 {
7199 	struct bpf_program *subprog;
7200 	size_t i, cnt, sec_insn_off;
7201 	struct func_ptr *ptrs;
7202 	int err;
7203 
7204 	ptrs = map->func_ptrs;
7205 	cnt = map->func_ptr_cnt;
7206 	for (i = 0; i < cnt; i++) {
7207 		sec_insn_off = ptrs[i].text_off / BPF_INSN_SZ;
7208 		subprog = find_prog_by_sec_insn(obj, obj->efile.text_shndx, sec_insn_off);
7209 		if (!subprog || subprog->sec_insn_off != sec_insn_off) {
7210 			pr_warn("prog '%s': map '%s': no function at .text+%zu for the pointer at offset %zu\n",
7211 				main_prog->name, map->name, ptrs[i].text_off, ptrs[i].sec_off);
7212 			return -LIBBPF_ERRNO__RELOC;
7213 		}
7214 
7215 		/*
7216 		 * callx can't call global functions. Don't add one to the
7217 		 * program only because the data points to it.
7218 		 */
7219 		if (subprog->sym_global)
7220 			continue;
7221 
7222 		/* see the comment in bpf_object__reloc_code() */
7223 		if (subprog->sub_insn_off == 0) {
7224 			err = bpf_object__append_subprog_code(obj, main_prog, subprog);
7225 			if (err)
7226 				return err;
7227 			err = bpf_object__reloc_code(obj, main_prog, subprog);
7228 			if (err)
7229 				return err;
7230 		}
7231 	}
7232 	return 0;
7233 }
7234 
7235 /*
7236  * The program that has callx might call any function that the data it refers
7237  * to points to. Append them. Programs that don't have callx can't call them
7238  * and the kernel doesn't look for pointers to functions in their data.
7239  */
7240 static int
7241 bpf_object__append_func_ptrs(struct bpf_object *obj, struct bpf_program *prog)
7242 {
7243 	size_t i;
7244 	int err;
7245 
7246 	prog->has_callx = prog_has_callx(prog);
7247 	if (!prog->has_callx)
7248 		return 0;
7249 
7250 	/* relocations of the functions that are appended are appended too */
7251 	for (i = 0; i < prog->nr_reloc; i++) {
7252 		struct reloc_desc *relo = &prog->reloc_desc[i];
7253 
7254 		if (relo->type != RELO_DATA || !obj->maps[relo->map_idx].func_ptr_cnt)
7255 			continue;
7256 		err = bpf_object__append_func_ptrs_code(obj, prog, &obj->maps[relo->map_idx]);
7257 		if (err)
7258 			return err;
7259 	}
7260 	return 0;
7261 }
7262 
7263 /*
7264  * Relocate sub-program calls.
7265  *
7266  * Algorithm operates as follows. Each entry-point BPF program (referred to as
7267  * main prog) is processed separately. For each subprog (non-entry functions,
7268  * that can be called from either entry progs or other subprogs) gets their
7269  * sub_insn_off reset to zero. This serves as indicator that this subprogram
7270  * hasn't been yet appended and relocated within current main prog. Once its
7271  * relocated, sub_insn_off will point at the position within current main prog
7272  * where given subprog was appended. This will further be used to relocate all
7273  * the call instructions jumping into this subprog.
7274  *
7275  * We start with main program and process all call instructions. If the call
7276  * is into a subprog that hasn't been processed (i.e., subprog->sub_insn_off
7277  * is zero), subprog instructions are appended at the end of main program's
7278  * instruction array. Then main program is "put on hold" while we recursively
7279  * process newly appended subprogram. If that subprogram calls into another
7280  * subprogram that hasn't been appended, new subprogram is appended again to
7281  * the *main* prog's instructions (subprog's instructions are always left
7282  * untouched, as they need to be in unmodified state for subsequent main progs
7283  * and subprog instructions are always sent only as part of a main prog) and
7284  * the process continues recursively. Once all the subprogs called from a main
7285  * prog or any of its subprogs are appended (and relocated), all their
7286  * positions within finalized instructions array are known, so it's easy to
7287  * rewrite call instructions with correct relative offsets, corresponding to
7288  * desired target subprog.
7289  *
7290  * Its important to realize that some subprogs might not be called from some
7291  * main prog and any of its called/used subprogs. Those will keep their
7292  * subprog->sub_insn_off as zero at all times and won't be appended to current
7293  * main prog and won't be relocated within the context of current main prog.
7294  * They might still be used from other main progs later.
7295  *
7296  * Visually this process can be shown as below. Suppose we have two main
7297  * programs mainA and mainB and BPF object contains three subprogs: subA,
7298  * subB, and subC. mainA calls only subA, mainB calls only subC, but subA and
7299  * subC both call subB:
7300  *
7301  *        +--------+ +-------+
7302  *        |        v v       |
7303  *     +--+---+ +--+-+-+ +---+--+
7304  *     | subA | | subB | | subC |
7305  *     +--+---+ +------+ +---+--+
7306  *        ^                  ^
7307  *        |                  |
7308  *    +---+-------+   +------+----+
7309  *    |   mainA   |   |   mainB   |
7310  *    +-----------+   +-----------+
7311  *
7312  * We'll start relocating mainA, will find subA, append it and start
7313  * processing sub A recursively:
7314  *
7315  *    +-----------+------+
7316  *    |   mainA   | subA |
7317  *    +-----------+------+
7318  *
7319  * At this point we notice that subB is used from subA, so we append it and
7320  * relocate (there are no further subcalls from subB):
7321  *
7322  *    +-----------+------+------+
7323  *    |   mainA   | subA | subB |
7324  *    +-----------+------+------+
7325  *
7326  * At this point, we relocate subA calls, then go one level up and finish with
7327  * relocation mainA calls. mainA is done.
7328  *
7329  * For mainB process is similar but results in different order. We start with
7330  * mainB and skip subA and subB, as mainB never calls them (at least
7331  * directly), but we see subC is needed, so we append and start processing it:
7332  *
7333  *    +-----------+------+
7334  *    |   mainB   | subC |
7335  *    +-----------+------+
7336  * Now we see subC needs subB, so we go back to it, append and relocate it:
7337  *
7338  *    +-----------+------+------+
7339  *    |   mainB   | subC | subB |
7340  *    +-----------+------+------+
7341  *
7342  * At this point we unwind recursion, relocate calls in subC, then in mainB.
7343  */
7344 static int
7345 bpf_object__relocate_calls(struct bpf_object *obj, struct bpf_program *prog)
7346 {
7347 	struct bpf_program *subprog;
7348 	int i, err;
7349 
7350 	/* mark all subprogs as not relocated (yet) within the context of
7351 	 * current main program
7352 	 */
7353 	for (i = 0; i < obj->nr_programs; i++) {
7354 		subprog = &obj->programs[i];
7355 		if (!prog_is_subprog(obj, subprog))
7356 			continue;
7357 
7358 		subprog->sub_insn_off = 0;
7359 	}
7360 
7361 	err = bpf_object__reloc_code(obj, prog, prog);
7362 	if (err)
7363 		return err;
7364 
7365 	return bpf_object__append_func_ptrs(obj, prog);
7366 }
7367 
7368 static void
7369 bpf_object__free_relocs(struct bpf_object *obj)
7370 {
7371 	struct bpf_program *prog;
7372 	int i;
7373 
7374 	/* free up relocation descriptors */
7375 	for (i = 0; i < obj->nr_programs; i++) {
7376 		prog = &obj->programs[i];
7377 		zfree(&prog->reloc_desc);
7378 		prog->nr_reloc = 0;
7379 	}
7380 }
7381 
7382 static int cmp_relocs(const void *_a, const void *_b)
7383 {
7384 	const struct reloc_desc *a = _a;
7385 	const struct reloc_desc *b = _b;
7386 
7387 	if (a->insn_idx != b->insn_idx)
7388 		return a->insn_idx < b->insn_idx ? -1 : 1;
7389 
7390 	/* no two relocations should have the same insn_idx, but ... */
7391 	if (a->type != b->type)
7392 		return a->type < b->type ? -1 : 1;
7393 
7394 	return 0;
7395 }
7396 
7397 static void bpf_object__sort_relos(struct bpf_object *obj)
7398 {
7399 	int i;
7400 
7401 	for (i = 0; i < obj->nr_programs; i++) {
7402 		struct bpf_program *p = &obj->programs[i];
7403 
7404 		if (!p->nr_reloc)
7405 			continue;
7406 
7407 		qsort(p->reloc_desc, p->nr_reloc, sizeof(*p->reloc_desc), cmp_relocs);
7408 	}
7409 }
7410 
7411 static int bpf_prog_assign_exc_cb(struct bpf_object *obj, struct bpf_program *prog)
7412 {
7413 	const char *str = "exception_callback:";
7414 	size_t pfx_len = strlen(str);
7415 	int i, j, n;
7416 
7417 	if (!obj->btf || !kernel_supports(obj, FEAT_BTF_DECL_TAG))
7418 		return 0;
7419 
7420 	n = btf__type_cnt(obj->btf);
7421 	for (i = 1; i < n; i++) {
7422 		const char *name;
7423 		struct btf_type *t;
7424 
7425 		t = btf_type_by_id(obj->btf, i);
7426 		if (!btf_is_decl_tag(t) || btf_decl_tag(t)->component_idx != -1)
7427 			continue;
7428 
7429 		name = btf__str_by_offset(obj->btf, t->name_off);
7430 		if (strncmp(name, str, pfx_len) != 0)
7431 			continue;
7432 
7433 		t = btf_type_by_id(obj->btf, t->type);
7434 		if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL) {
7435 			pr_warn("prog '%s': exception_callback:<value> decl tag not applied to the main program\n",
7436 				prog->name);
7437 			return -EINVAL;
7438 		}
7439 		if (strcmp(prog->name, btf__str_by_offset(obj->btf, t->name_off)) != 0)
7440 			continue;
7441 		/* Multiple callbacks are specified for the same prog,
7442 		 * the verifier will eventually return an error for this
7443 		 * case, hence simply skip appending a subprog.
7444 		 */
7445 		if (prog->exception_cb_idx >= 0) {
7446 			prog->exception_cb_idx = -1;
7447 			break;
7448 		}
7449 
7450 		name += pfx_len;
7451 		if (str_is_empty(name)) {
7452 			pr_warn("prog '%s': exception_callback:<value> decl tag contains empty value\n",
7453 				prog->name);
7454 			return -EINVAL;
7455 		}
7456 
7457 		for (j = 0; j < obj->nr_programs; j++) {
7458 			struct bpf_program *subprog = &obj->programs[j];
7459 
7460 			if (!prog_is_subprog(obj, subprog))
7461 				continue;
7462 			if (strcmp(name, subprog->name) != 0)
7463 				continue;
7464 			/* Enforce non-hidden, as from verifier point of
7465 			 * view it expects global functions, whereas the
7466 			 * mark_btf_static fixes up linkage as static.
7467 			 */
7468 			if (!subprog->sym_global || subprog->mark_btf_static) {
7469 				pr_warn("prog '%s': exception callback %s must be a global non-hidden function\n",
7470 					prog->name, subprog->name);
7471 				return -EINVAL;
7472 			}
7473 			/* Let's see if we already saw a static exception callback with the same name */
7474 			if (prog->exception_cb_idx >= 0) {
7475 				pr_warn("prog '%s': multiple subprogs with same name as exception callback '%s'\n",
7476 					prog->name, subprog->name);
7477 				return -EINVAL;
7478 			}
7479 			prog->exception_cb_idx = j;
7480 			break;
7481 		}
7482 
7483 		if (prog->exception_cb_idx >= 0)
7484 			continue;
7485 
7486 		pr_warn("prog '%s': cannot find exception callback '%s'\n", prog->name, name);
7487 		return -ENOENT;
7488 	}
7489 
7490 	return 0;
7491 }
7492 
7493 static struct {
7494 	enum bpf_prog_type prog_type;
7495 	const char *ctx_name;
7496 } global_ctx_map[] = {
7497 	{ BPF_PROG_TYPE_CGROUP_DEVICE,           "bpf_cgroup_dev_ctx" },
7498 	{ BPF_PROG_TYPE_CGROUP_SKB,              "__sk_buff" },
7499 	{ BPF_PROG_TYPE_CGROUP_SOCK,             "bpf_sock" },
7500 	{ BPF_PROG_TYPE_CGROUP_SOCK_ADDR,        "bpf_sock_addr" },
7501 	{ BPF_PROG_TYPE_CGROUP_SOCKOPT,          "bpf_sockopt" },
7502 	{ BPF_PROG_TYPE_CGROUP_SYSCTL,           "bpf_sysctl" },
7503 	{ BPF_PROG_TYPE_FLOW_DISSECTOR,          "__sk_buff" },
7504 	{ BPF_PROG_TYPE_KPROBE,                  "bpf_user_pt_regs_t" },
7505 	{ BPF_PROG_TYPE_LWT_IN,                  "__sk_buff" },
7506 	{ BPF_PROG_TYPE_LWT_OUT,                 "__sk_buff" },
7507 	{ BPF_PROG_TYPE_LWT_SEG6LOCAL,           "__sk_buff" },
7508 	{ BPF_PROG_TYPE_LWT_XMIT,                "__sk_buff" },
7509 	{ BPF_PROG_TYPE_NETFILTER,               "bpf_nf_ctx" },
7510 	{ BPF_PROG_TYPE_PERF_EVENT,              "bpf_perf_event_data" },
7511 	{ BPF_PROG_TYPE_RAW_TRACEPOINT,          "bpf_raw_tracepoint_args" },
7512 	{ BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE, "bpf_raw_tracepoint_args" },
7513 	{ BPF_PROG_TYPE_SCHED_ACT,               "__sk_buff" },
7514 	{ BPF_PROG_TYPE_SCHED_CLS,               "__sk_buff" },
7515 	{ BPF_PROG_TYPE_SK_LOOKUP,               "bpf_sk_lookup" },
7516 	{ BPF_PROG_TYPE_SK_MSG,                  "sk_msg_md" },
7517 	{ BPF_PROG_TYPE_SK_REUSEPORT,            "sk_reuseport_md" },
7518 	{ BPF_PROG_TYPE_SK_SKB,                  "__sk_buff" },
7519 	{ BPF_PROG_TYPE_SOCK_OPS,                "bpf_sock_ops" },
7520 	{ BPF_PROG_TYPE_SOCKET_FILTER,           "__sk_buff" },
7521 	{ BPF_PROG_TYPE_XDP,                     "xdp_md" },
7522 	/* all other program types don't have "named" context structs */
7523 };
7524 
7525 /* forward declarations for arch-specific underlying types of bpf_user_pt_regs_t typedef,
7526  * for below __builtin_types_compatible_p() checks;
7527  * with this approach we don't need any extra arch-specific #ifdef guards
7528  */
7529 struct pt_regs;
7530 struct user_pt_regs;
7531 struct user_regs_struct;
7532 
7533 static bool need_func_arg_type_fixup(const struct btf *btf, const struct bpf_program *prog,
7534 				     const char *subprog_name, int arg_idx,
7535 				     int arg_type_id, const char *ctx_name)
7536 {
7537 	const struct btf_type *t;
7538 	const char *tname;
7539 
7540 	/* check if existing parameter already matches verifier expectations */
7541 	t = skip_mods_and_typedefs(btf, arg_type_id, NULL);
7542 	if (!btf_is_ptr(t))
7543 		goto out_warn;
7544 
7545 	/* typedef bpf_user_pt_regs_t is a special PITA case, valid for kprobe
7546 	 * and perf_event programs, so check this case early on and forget
7547 	 * about it for subsequent checks
7548 	 */
7549 	while (btf_is_mod(t))
7550 		t = btf__type_by_id(btf, t->type);
7551 	if (btf_is_typedef(t) &&
7552 	    (prog->type == BPF_PROG_TYPE_KPROBE || prog->type == BPF_PROG_TYPE_PERF_EVENT)) {
7553 		tname = btf__str_by_offset(btf, t->name_off) ?: "<anon>";
7554 		if (strcmp(tname, "bpf_user_pt_regs_t") == 0)
7555 			return false; /* canonical type for kprobe/perf_event */
7556 	}
7557 
7558 	/* now we can ignore typedefs moving forward */
7559 	t = skip_mods_and_typedefs(btf, t->type, NULL);
7560 
7561 	/* if it's `void *`, definitely fix up BTF info */
7562 	if (btf_is_void(t))
7563 		return true;
7564 
7565 	/* if it's already proper canonical type, no need to fix up */
7566 	tname = btf__str_by_offset(btf, t->name_off) ?: "<anon>";
7567 	if (btf_is_struct(t) && strcmp(tname, ctx_name) == 0)
7568 		return false;
7569 
7570 	/* special cases */
7571 	switch (prog->type) {
7572 	case BPF_PROG_TYPE_KPROBE:
7573 		/* `struct pt_regs *` is expected, but we need to fix up */
7574 		if (btf_is_struct(t) && strcmp(tname, "pt_regs") == 0)
7575 			return true;
7576 		break;
7577 	case BPF_PROG_TYPE_PERF_EVENT:
7578 		if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct pt_regs) &&
7579 		    btf_is_struct(t) && strcmp(tname, "pt_regs") == 0)
7580 			return true;
7581 		if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct user_pt_regs) &&
7582 		    btf_is_struct(t) && strcmp(tname, "user_pt_regs") == 0)
7583 			return true;
7584 		if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct user_regs_struct) &&
7585 		    btf_is_struct(t) && strcmp(tname, "user_regs_struct") == 0)
7586 			return true;
7587 		break;
7588 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
7589 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
7590 		/* allow u64* as ctx */
7591 		if (btf_is_int(t) && t->size == 8)
7592 			return true;
7593 		break;
7594 	default:
7595 		break;
7596 	}
7597 
7598 out_warn:
7599 	pr_warn("prog '%s': subprog '%s' arg#%d is expected to be of `struct %s *` type\n",
7600 		prog->name, subprog_name, arg_idx, ctx_name);
7601 	return false;
7602 }
7603 
7604 static int clone_func_btf_info(struct btf *btf, int orig_fn_id, struct bpf_program *prog)
7605 {
7606 	int fn_id, fn_proto_id, ret_type_id, orig_proto_id;
7607 	int i, err, arg_cnt, fn_name_off, linkage;
7608 	struct btf_type *fn_t, *fn_proto_t, *t;
7609 	struct btf_param *p;
7610 
7611 	/* caller already validated FUNC -> FUNC_PROTO validity */
7612 	fn_t = btf_type_by_id(btf, orig_fn_id);
7613 	fn_proto_t = btf_type_by_id(btf, fn_t->type);
7614 
7615 	/* Note that each btf__add_xxx() operation invalidates
7616 	 * all btf_type and string pointers, so we need to be
7617 	 * very careful when cloning BTF types. BTF type
7618 	 * pointers have to be always refetched. And to avoid
7619 	 * problems with invalidated string pointers, we
7620 	 * add empty strings initially, then just fix up
7621 	 * name_off offsets in place. Offsets are stable for
7622 	 * existing strings, so that works out.
7623 	 */
7624 	fn_name_off = fn_t->name_off; /* we are about to invalidate fn_t */
7625 	linkage = btf_func_linkage(fn_t);
7626 	orig_proto_id = fn_t->type; /* original FUNC_PROTO ID */
7627 	ret_type_id = fn_proto_t->type; /* fn_proto_t will be invalidated */
7628 	arg_cnt = btf_vlen(fn_proto_t);
7629 
7630 	/* clone FUNC_PROTO and its params */
7631 	fn_proto_id = btf__add_func_proto(btf, ret_type_id);
7632 	if (fn_proto_id < 0)
7633 		return -EINVAL;
7634 
7635 	for (i = 0; i < arg_cnt; i++) {
7636 		int name_off;
7637 
7638 		/* copy original parameter data */
7639 		t = btf_type_by_id(btf, orig_proto_id);
7640 		p = &btf_params(t)[i];
7641 		name_off = p->name_off;
7642 
7643 		err = btf__add_func_param(btf, "", p->type);
7644 		if (err)
7645 			return err;
7646 
7647 		fn_proto_t = btf_type_by_id(btf, fn_proto_id);
7648 		p = &btf_params(fn_proto_t)[i];
7649 		p->name_off = name_off; /* use remembered str offset */
7650 	}
7651 
7652 	/* clone FUNC now, btf__add_func() enforces non-empty name, so use
7653 	 * entry program's name as a placeholder, which we replace immediately
7654 	 * with original name_off
7655 	 */
7656 	fn_id = btf__add_func(btf, prog->name, linkage, fn_proto_id);
7657 	if (fn_id < 0)
7658 		return -EINVAL;
7659 
7660 	fn_t = btf_type_by_id(btf, fn_id);
7661 	fn_t->name_off = fn_name_off; /* reuse original string */
7662 
7663 	return fn_id;
7664 }
7665 
7666 /* Check if main program or global subprog's function prototype has `arg:ctx`
7667  * argument tags, and, if necessary, substitute correct type to match what BPF
7668  * verifier would expect, taking into account specific program type. This
7669  * allows to support __arg_ctx tag transparently on old kernels that don't yet
7670  * have a native support for it in the verifier, making user's life much
7671  * easier.
7672  */
7673 static int bpf_program_fixup_func_info(struct bpf_object *obj, struct bpf_program *prog)
7674 {
7675 	const char *ctx_name = NULL, *ctx_tag = "arg:ctx", *fn_name;
7676 	struct bpf_func_info_min *func_rec;
7677 	struct btf_type *fn_t, *fn_proto_t;
7678 	struct btf *btf = obj->btf;
7679 	const struct btf_type *t;
7680 	struct btf_param *p;
7681 	int ptr_id = 0, struct_id, tag_id, orig_fn_id;
7682 	int i, n, arg_idx, arg_cnt, err, rec_idx;
7683 	int *orig_ids;
7684 
7685 	/* no .BTF.ext, no problem */
7686 	if (!obj->btf_ext || !prog->func_info)
7687 		return 0;
7688 
7689 	/* don't do any fix ups if kernel natively supports __arg_ctx */
7690 	if (kernel_supports(obj, FEAT_ARG_CTX_TAG))
7691 		return 0;
7692 
7693 	/* some BPF program types just don't have named context structs, so
7694 	 * this fallback mechanism doesn't work for them
7695 	 */
7696 	for (i = 0; i < ARRAY_SIZE(global_ctx_map); i++) {
7697 		if (global_ctx_map[i].prog_type != prog->type)
7698 			continue;
7699 		ctx_name = global_ctx_map[i].ctx_name;
7700 		break;
7701 	}
7702 	if (!ctx_name)
7703 		return 0;
7704 
7705 	/* remember original func BTF IDs to detect if we already cloned them */
7706 	orig_ids = calloc(prog->func_info_cnt, sizeof(*orig_ids));
7707 	if (!orig_ids)
7708 		return -ENOMEM;
7709 	for (i = 0; i < prog->func_info_cnt; i++) {
7710 		func_rec = prog->func_info + prog->func_info_rec_size * i;
7711 		orig_ids[i] = func_rec->type_id;
7712 	}
7713 
7714 	/* go through each DECL_TAG with "arg:ctx" and see if it points to one
7715 	 * of our subprogs; if yes and subprog is global and needs adjustment,
7716 	 * clone and adjust FUNC -> FUNC_PROTO combo
7717 	 */
7718 	for (i = 1, n = btf__type_cnt(btf); i < n; i++) {
7719 		/* only DECL_TAG with "arg:ctx" value are interesting */
7720 		t = btf__type_by_id(btf, i);
7721 		if (!btf_is_decl_tag(t))
7722 			continue;
7723 		if (strcmp(btf__str_by_offset(btf, t->name_off), ctx_tag) != 0)
7724 			continue;
7725 
7726 		/* only global funcs need adjustment, if at all */
7727 		orig_fn_id = t->type;
7728 		fn_t = btf_type_by_id(btf, orig_fn_id);
7729 		if (!btf_is_func(fn_t) || btf_func_linkage(fn_t) != BTF_FUNC_GLOBAL)
7730 			continue;
7731 
7732 		/* sanity check FUNC -> FUNC_PROTO chain, just in case */
7733 		fn_proto_t = btf_type_by_id(btf, fn_t->type);
7734 		if (!fn_proto_t || !btf_is_func_proto(fn_proto_t))
7735 			continue;
7736 
7737 		/* find corresponding func_info record */
7738 		func_rec = NULL;
7739 		for (rec_idx = 0; rec_idx < prog->func_info_cnt; rec_idx++) {
7740 			if (orig_ids[rec_idx] == t->type) {
7741 				func_rec = prog->func_info + prog->func_info_rec_size * rec_idx;
7742 				break;
7743 			}
7744 		}
7745 		/* current main program doesn't call into this subprog */
7746 		if (!func_rec)
7747 			continue;
7748 
7749 		/* some more sanity checking of DECL_TAG */
7750 		arg_cnt = btf_vlen(fn_proto_t);
7751 		arg_idx = btf_decl_tag(t)->component_idx;
7752 		if (arg_idx < 0 || arg_idx >= arg_cnt)
7753 			continue;
7754 
7755 		/* check if we should fix up argument type */
7756 		p = &btf_params(fn_proto_t)[arg_idx];
7757 		fn_name = btf__str_by_offset(btf, fn_t->name_off) ?: "<anon>";
7758 		if (!need_func_arg_type_fixup(btf, prog, fn_name, arg_idx, p->type, ctx_name))
7759 			continue;
7760 
7761 		/* clone fn/fn_proto, unless we already did it for another arg */
7762 		if (func_rec->type_id == orig_fn_id) {
7763 			int fn_id;
7764 
7765 			fn_id = clone_func_btf_info(btf, orig_fn_id, prog);
7766 			if (fn_id < 0) {
7767 				err = fn_id;
7768 				goto err_out;
7769 			}
7770 
7771 			/* point func_info record to a cloned FUNC type */
7772 			func_rec->type_id = fn_id;
7773 		}
7774 
7775 		/* create PTR -> STRUCT type chain to mark PTR_TO_CTX argument;
7776 		 * we do it just once per main BPF program, as all global
7777 		 * funcs share the same program type, so need only PTR ->
7778 		 * STRUCT type chain
7779 		 */
7780 		if (ptr_id == 0) {
7781 			struct_id = btf__add_struct(btf, ctx_name, 0);
7782 			ptr_id = btf__add_ptr(btf, struct_id);
7783 			if (ptr_id < 0 || struct_id < 0) {
7784 				err = -EINVAL;
7785 				goto err_out;
7786 			}
7787 		}
7788 
7789 		/* for completeness, clone DECL_TAG and point it to cloned param */
7790 		tag_id = btf__add_decl_tag(btf, ctx_tag, func_rec->type_id, arg_idx);
7791 		if (tag_id < 0) {
7792 			err = -EINVAL;
7793 			goto err_out;
7794 		}
7795 
7796 		/* all the BTF manipulations invalidated pointers, refetch them */
7797 		fn_t = btf_type_by_id(btf, func_rec->type_id);
7798 		fn_proto_t = btf_type_by_id(btf, fn_t->type);
7799 
7800 		/* fix up type ID pointed to by param */
7801 		p = &btf_params(fn_proto_t)[arg_idx];
7802 		p->type = ptr_id;
7803 	}
7804 
7805 	free(orig_ids);
7806 	return 0;
7807 err_out:
7808 	free(orig_ids);
7809 	return err;
7810 }
7811 
7812 static int bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
7813 {
7814 	struct bpf_program *prog;
7815 	size_t i, j;
7816 	int err;
7817 
7818 	if (obj->btf_ext) {
7819 		err = bpf_object__relocate_core(obj, targ_btf_path);
7820 		if (err) {
7821 			pr_warn("failed to perform CO-RE relocations: %s\n",
7822 				errstr(err));
7823 			return err;
7824 		}
7825 		bpf_object__sort_relos(obj);
7826 	}
7827 
7828 	if (obj->arena_map_idx >= 0) {
7829 		struct bpf_map *arena_map = &obj->maps[obj->arena_map_idx];
7830 		size_t data_sz = roundup(obj->arena_data_sz, sysconf(_SC_PAGE_SIZE));
7831 		size_t mmap_sz = bpf_map_mmap_sz(arena_map);
7832 
7833 		if (data_sz > mmap_sz) {
7834 			pr_warn("map '%s': declared ARENA map size (%zu) is too small to hold global __arena variables of size %zu\n",
7835 				arena_map->name, mmap_sz, obj->arena_data_sz);
7836 			return -E2BIG;
7837 		}
7838 
7839 		/* place globals at the end of the arena (if supported) */
7840 		if (kernel_supports(obj, FEAT_LDIMM64_FULL_RANGE_OFF))
7841 			obj->arena_data_off = mmap_sz - data_sz;
7842 	}
7843 
7844 	/* Before relocating calls pre-process relocations and mark
7845 	 * few ld_imm64 instructions that points to subprogs.
7846 	 * Otherwise bpf_object__reloc_code() later would have to consider
7847 	 * all ld_imm64 insns as relocation candidates. That would
7848 	 * reduce relocation speed, since amount of find_prog_insn_relo()
7849 	 * would increase and most of them will fail to find a relo.
7850 	 */
7851 	for (i = 0; i < obj->nr_programs; i++) {
7852 		prog = &obj->programs[i];
7853 		for (j = 0; j < prog->nr_reloc; j++) {
7854 			struct reloc_desc *relo = &prog->reloc_desc[j];
7855 			struct bpf_insn *insn = &prog->insns[relo->insn_idx];
7856 
7857 			/* mark the insn, so it's recognized by insn_is_pseudo_func() */
7858 			if (relo->type == RELO_SUBPROG_ADDR)
7859 				insn[0].src_reg = BPF_PSEUDO_FUNC;
7860 		}
7861 	}
7862 
7863 	/* relocate subprogram calls and append used subprograms to main
7864 	 * programs; each copy of subprogram code needs to be relocated
7865 	 * differently for each main program, because its code location might
7866 	 * have changed.
7867 	 * Append subprog relos to main programs to allow data relos to be
7868 	 * processed after text is completely relocated.
7869 	 */
7870 	for (i = 0; i < obj->nr_programs; i++) {
7871 		prog = &obj->programs[i];
7872 		/* sub-program's sub-calls are relocated within the context of
7873 		 * its main program only
7874 		 */
7875 		if (prog_is_subprog(obj, prog))
7876 			continue;
7877 		if (!prog->autoload)
7878 			continue;
7879 
7880 		err = bpf_object__relocate_calls(obj, prog);
7881 		if (err) {
7882 			pr_warn("prog '%s': failed to relocate calls: %s\n",
7883 				prog->name, errstr(err));
7884 			return err;
7885 		}
7886 
7887 		err = bpf_prog_assign_exc_cb(obj, prog);
7888 		if (err)
7889 			return err;
7890 		/* Now, also append exception callback if it has not been done already. */
7891 		if (prog->exception_cb_idx >= 0) {
7892 			struct bpf_program *subprog = &obj->programs[prog->exception_cb_idx];
7893 
7894 			/* Calling exception callback directly is disallowed, which the
7895 			 * verifier will reject later. In case it was processed already,
7896 			 * we can skip this step, otherwise for all other valid cases we
7897 			 * have to append exception callback now.
7898 			 */
7899 			if (subprog->sub_insn_off == 0) {
7900 				err = bpf_object__append_subprog_code(obj, prog, subprog);
7901 				if (err)
7902 					return err;
7903 				err = bpf_object__reloc_code(obj, prog, subprog);
7904 				if (err)
7905 					return err;
7906 			}
7907 		}
7908 	}
7909 	for (i = 0; i < obj->nr_programs; i++) {
7910 		prog = &obj->programs[i];
7911 		if (prog_is_subprog(obj, prog))
7912 			continue;
7913 		if (!prog->autoload)
7914 			continue;
7915 
7916 		/* Process data relos for main programs */
7917 		err = bpf_object__relocate_data(obj, prog);
7918 		if (err) {
7919 			pr_warn("prog '%s': failed to relocate data references: %s\n",
7920 				prog->name, errstr(err));
7921 			return err;
7922 		}
7923 
7924 		/* Fix up .BTF.ext information, if necessary */
7925 		err = bpf_program_fixup_func_info(obj, prog);
7926 		if (err) {
7927 			pr_warn("prog '%s': failed to perform .BTF.ext fix ups: %s\n",
7928 				prog->name, errstr(err));
7929 			return err;
7930 		}
7931 	}
7932 
7933 	return 0;
7934 }
7935 
7936 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
7937 					    Elf64_Shdr *shdr, Elf_Data *data);
7938 
7939 static int bpf_object__collect_map_relos(struct bpf_object *obj,
7940 					 Elf64_Shdr *shdr, Elf_Data *data)
7941 {
7942 	const int bpf_ptr_sz = 8, host_ptr_sz = sizeof(void *);
7943 	int i, j, nrels, new_sz;
7944 	const struct btf_var_secinfo *vi = NULL;
7945 	const struct btf_type *sec, *var, *def;
7946 	struct bpf_map *map = NULL, *targ_map = NULL;
7947 	struct bpf_program *targ_prog = NULL;
7948 	bool is_prog_array, is_map_in_map;
7949 	const struct btf_member *member;
7950 	const char *name, *mname, *type;
7951 	unsigned int moff;
7952 	Elf64_Sym *sym;
7953 	Elf64_Rel *rel;
7954 	void *tmp;
7955 
7956 	if (!obj->efile.btf_maps_sec_btf_id || !obj->btf)
7957 		return -EINVAL;
7958 	sec = btf__type_by_id(obj->btf, obj->efile.btf_maps_sec_btf_id);
7959 	if (!sec)
7960 		return -EINVAL;
7961 
7962 	nrels = shdr->sh_size / shdr->sh_entsize;
7963 	for (i = 0; i < nrels; i++) {
7964 		rel = elf_rel_by_idx(data, i);
7965 		if (!rel) {
7966 			pr_warn(".maps relo #%d: failed to get ELF relo\n", i);
7967 			return -LIBBPF_ERRNO__FORMAT;
7968 		}
7969 
7970 		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
7971 		if (!sym) {
7972 			pr_warn(".maps relo #%d: symbol %zx not found\n",
7973 				i, (size_t)ELF64_R_SYM(rel->r_info));
7974 			return -LIBBPF_ERRNO__FORMAT;
7975 		}
7976 		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
7977 
7978 		pr_debug(".maps relo #%d: for %zd value %zu rel->r_offset %zu name %u ('%s')\n",
7979 			 i, (ssize_t)(rel->r_info >> 32), (size_t)sym->st_value,
7980 			 (size_t)rel->r_offset, sym->st_name, name);
7981 
7982 		for (j = 0; j < obj->nr_maps; j++) {
7983 			map = &obj->maps[j];
7984 			if (map->sec_idx != obj->efile.btf_maps_shndx)
7985 				continue;
7986 
7987 			vi = btf_var_secinfos(sec) + map->btf_var_idx;
7988 			if (vi->offset <= rel->r_offset &&
7989 			    rel->r_offset + bpf_ptr_sz <= vi->offset + vi->size)
7990 				break;
7991 		}
7992 		if (j == obj->nr_maps) {
7993 			pr_warn(".maps relo #%d: cannot find map '%s' at rel->r_offset %zu\n",
7994 				i, name, (size_t)rel->r_offset);
7995 			return -EINVAL;
7996 		}
7997 
7998 		is_map_in_map = bpf_map_type__is_map_in_map(map->def.type);
7999 		is_prog_array = map->def.type == BPF_MAP_TYPE_PROG_ARRAY;
8000 		type = is_map_in_map ? "map" : "prog";
8001 		if (is_map_in_map) {
8002 			if (sym->st_shndx != obj->efile.btf_maps_shndx) {
8003 				pr_warn(".maps relo #%d: '%s' isn't a BTF-defined map\n",
8004 					i, name);
8005 				return -LIBBPF_ERRNO__RELOC;
8006 			}
8007 			if (map->def.type == BPF_MAP_TYPE_HASH_OF_MAPS &&
8008 			    map->def.key_size != sizeof(int)) {
8009 				pr_warn(".maps relo #%d: hash-of-maps '%s' should have key size %zu.\n",
8010 					i, map->name, sizeof(int));
8011 				return -EINVAL;
8012 			}
8013 			targ_map = bpf_object__find_map_by_name(obj, name);
8014 			if (!targ_map) {
8015 				pr_warn(".maps relo #%d: '%s' isn't a valid map reference\n",
8016 					i, name);
8017 				return -ESRCH;
8018 			}
8019 		} else if (is_prog_array) {
8020 			targ_prog = bpf_object__find_program_by_name(obj, name);
8021 			if (!targ_prog) {
8022 				pr_warn(".maps relo #%d: '%s' isn't a valid program reference\n",
8023 					i, name);
8024 				return -ESRCH;
8025 			}
8026 			if (targ_prog->sec_idx != sym->st_shndx ||
8027 			    targ_prog->sec_insn_off * 8 != sym->st_value ||
8028 			    prog_is_subprog(obj, targ_prog)) {
8029 				pr_warn(".maps relo #%d: '%s' isn't an entry-point program\n",
8030 					i, name);
8031 				return -LIBBPF_ERRNO__RELOC;
8032 			}
8033 		} else {
8034 			return -EINVAL;
8035 		}
8036 
8037 		var = btf__type_by_id(obj->btf, vi->type);
8038 		def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
8039 		if (btf_vlen(def) == 0)
8040 			return -EINVAL;
8041 		member = btf_members(def) + btf_vlen(def) - 1;
8042 		mname = btf__name_by_offset(obj->btf, member->name_off);
8043 		if (strcmp(mname, "values"))
8044 			return -EINVAL;
8045 
8046 		moff = btf_member_bit_offset(def, btf_vlen(def) - 1) / 8;
8047 		if (rel->r_offset - vi->offset < moff)
8048 			return -EINVAL;
8049 
8050 		moff = rel->r_offset - vi->offset - moff;
8051 		/* here we use BPF pointer size, which is always 64 bit, as we
8052 		 * are parsing ELF that was built for BPF target
8053 		 */
8054 		if (moff % bpf_ptr_sz)
8055 			return -EINVAL;
8056 		moff /= bpf_ptr_sz;
8057 		if (moff >= map->init_slots_sz) {
8058 			new_sz = moff + 1;
8059 			tmp = libbpf_reallocarray(map->init_slots, new_sz, host_ptr_sz);
8060 			if (!tmp)
8061 				return -ENOMEM;
8062 			map->init_slots = tmp;
8063 			memset(map->init_slots + map->init_slots_sz, 0,
8064 			       (new_sz - map->init_slots_sz) * host_ptr_sz);
8065 			map->init_slots_sz = new_sz;
8066 		}
8067 		map->init_slots[moff] = is_map_in_map ? (void *)targ_map : (void *)targ_prog;
8068 
8069 		pr_debug(".maps relo #%d: map '%s' slot [%u] points to %s '%s'\n",
8070 			 i, map->name, moff, type, name);
8071 	}
8072 
8073 	return 0;
8074 }
8075 
8076 /*
8077  * Collect pointers to functions in a read-only data section. They are
8078  * R_BPF_64_ABS64 relocations against .text section, where the offset of
8079  * a static function in the section is stored in place. Relocations in data
8080  * sections were ignored before pointers to functions were supported. Those
8081  * that are something else, e.g. pointers to data, still are.
8082  */
8083 static int bpf_object__collect_rodata_relos(struct bpf_object *obj,
8084 					    Elf64_Shdr *shdr, Elf_Data *data)
8085 {
8086 	size_t sec_idx = shdr->sh_info, sym_idx;
8087 	int i, nrels = shdr->sh_size / shdr->sh_entsize;
8088 	const char *relo_sec_name;
8089 	struct func_ptr *ptrs;
8090 	Elf_Data *scn_data;
8091 	Elf64_Sym *sym;
8092 	Elf64_Rel *rel;
8093 	__u64 addend;
8094 
8095 	relo_sec_name = elf_sec_str(obj, shdr->sh_name) ?: "<?>";
8096 	scn_data = obj->efile.secs[sec_idx].data;
8097 	if (!scn_data)
8098 		return -LIBBPF_ERRNO__FORMAT;
8099 
8100 	for (i = 0; i < nrels; i++) {
8101 		rel = elf_rel_by_idx(data, i);
8102 		if (!rel) {
8103 			pr_warn("sec '%s': failed to get relo #%d\n", relo_sec_name, i);
8104 			return -LIBBPF_ERRNO__FORMAT;
8105 		}
8106 
8107 		sym_idx = ELF64_R_SYM(rel->r_info);
8108 		sym = elf_sym_by_idx(obj, sym_idx);
8109 		if (!sym) {
8110 			pr_warn("sec '%s': symbol #%zu not found for relo #%d\n",
8111 				relo_sec_name, sym_idx, i);
8112 			return -LIBBPF_ERRNO__FORMAT;
8113 		}
8114 
8115 		if (ELF64_R_TYPE(rel->r_info) != R_BPF_64_ABS64 ||
8116 		    !sym_is_subprog(sym, obj->efile.text_shndx)) {
8117 			pr_debug("sec '%s': relo #%d: not a pointer to a function, skipping...\n",
8118 				 relo_sec_name, i);
8119 			continue;
8120 		}
8121 
8122 		/* the kernel finds aligned pointers only */
8123 		if (rel->r_offset % sizeof(__u64) || rel->r_offset >= scn_data->d_size ||
8124 		    scn_data->d_size - rel->r_offset < sizeof(__u64)) {
8125 			pr_debug("sec '%s': relo #%d: unsupported offset 0x%zx, skipping...\n",
8126 				 relo_sec_name, i, (size_t)rel->r_offset);
8127 			continue;
8128 		}
8129 
8130 		memcpy(&addend, scn_data->d_buf + rel->r_offset, sizeof(addend));
8131 		if (!is_native_endianness(obj))
8132 			addend = bswap_64(addend);
8133 		if ((sym->st_value + addend) % BPF_INSN_SZ) {
8134 			pr_debug("sec '%s': relo #%d: bad pointer to a function at offset %zu+%llu, skipping...\n",
8135 				 relo_sec_name, i, (size_t)sym->st_value,
8136 				 (unsigned long long)addend);
8137 			continue;
8138 		}
8139 
8140 		ptrs = libbpf_reallocarray(obj->func_ptrs, obj->func_ptr_cnt + 1, sizeof(*ptrs));
8141 		if (!ptrs)
8142 			return -ENOMEM;
8143 		obj->func_ptrs = ptrs;
8144 
8145 		ptrs[obj->func_ptr_cnt].sec_idx = sec_idx;
8146 		ptrs[obj->func_ptr_cnt].sec_off = rel->r_offset;
8147 		ptrs[obj->func_ptr_cnt].text_off = sym->st_value + addend;
8148 		obj->func_ptr_cnt++;
8149 
8150 		pr_debug("sec '%s': relo #%d: pointer at offset %zu to a function at .text+%zu\n",
8151 			 relo_sec_name, i, (size_t)rel->r_offset, (size_t)(sym->st_value + addend));
8152 	}
8153 	return 0;
8154 }
8155 
8156 static int cmp_func_ptrs(const void *_a, const void *_b)
8157 {
8158 	const struct func_ptr *a = _a;
8159 	const struct func_ptr *b = _b;
8160 
8161 	if (a->sec_idx != b->sec_idx)
8162 		return a->sec_idx < b->sec_idx ? -1 : 1;
8163 	if (a->sec_off != b->sec_off)
8164 		return a->sec_off < b->sec_off ? -1 : 1;
8165 	return 0;
8166 }
8167 
8168 static int bpf_object__collect_relos(struct bpf_object *obj)
8169 {
8170 	int i, err;
8171 
8172 	for (i = 0; i < obj->efile.sec_cnt; i++) {
8173 		struct elf_sec_desc *sec_desc = &obj->efile.secs[i];
8174 		Elf64_Shdr *shdr;
8175 		Elf_Data *data;
8176 		int idx;
8177 
8178 		if (sec_desc->sec_type != SEC_RELO)
8179 			continue;
8180 
8181 		shdr = sec_desc->shdr;
8182 		data = sec_desc->data;
8183 		idx = shdr->sh_info;
8184 
8185 		if (shdr->sh_type != SHT_REL || idx < 0 || idx >= obj->efile.sec_cnt) {
8186 			pr_warn("internal error at %d\n", __LINE__);
8187 			return -LIBBPF_ERRNO__INTERNAL;
8188 		}
8189 
8190 		if (obj->efile.secs[idx].sec_type == SEC_RODATA)
8191 			err = bpf_object__collect_rodata_relos(obj, shdr, data);
8192 		else if (obj->efile.secs[idx].sec_type == SEC_ST_OPS)
8193 			err = bpf_object__collect_st_ops_relos(obj, shdr, data);
8194 		else if (idx == obj->efile.btf_maps_shndx)
8195 			err = bpf_object__collect_map_relos(obj, shdr, data);
8196 		else
8197 			err = bpf_object__collect_prog_relos(obj, shdr, data);
8198 		if (err)
8199 			return err;
8200 	}
8201 
8202 	/* sort by section, so that pointers in the data of a map are next to each other */
8203 	if (obj->func_ptr_cnt)
8204 		qsort(obj->func_ptrs, obj->func_ptr_cnt, sizeof(*obj->func_ptrs), cmp_func_ptrs);
8205 
8206 	for (i = 0; i < obj->nr_maps; i++) {
8207 		struct bpf_map *map = &obj->maps[i];
8208 		size_t j;
8209 
8210 		if (map->libbpf_type != LIBBPF_MAP_RODATA)
8211 			continue;
8212 		for (j = 0; j < obj->func_ptr_cnt; j++) {
8213 			if (obj->func_ptrs[j].sec_idx != map->sec_idx)
8214 				continue;
8215 			if (!map->func_ptr_cnt)
8216 				map->func_ptrs = &obj->func_ptrs[j];
8217 			map->func_ptr_cnt++;
8218 		}
8219 	}
8220 
8221 	bpf_object__sort_relos(obj);
8222 	return 0;
8223 }
8224 
8225 static bool insn_is_helper_call(struct bpf_insn *insn, enum bpf_func_id *func_id)
8226 {
8227 	if (BPF_CLASS(insn->code) == BPF_JMP &&
8228 	    BPF_OP(insn->code) == BPF_CALL &&
8229 	    BPF_SRC(insn->code) == BPF_K &&
8230 	    insn->src_reg == 0 &&
8231 	    insn->dst_reg == 0) {
8232 		    *func_id = insn->imm;
8233 		    return true;
8234 	}
8235 	return false;
8236 }
8237 
8238 static int bpf_object__sanitize_prog(struct bpf_object *obj, struct bpf_program *prog)
8239 {
8240 	struct bpf_insn *insn = prog->insns;
8241 	enum bpf_func_id func_id;
8242 	int i;
8243 
8244 	if (obj->gen_loader)
8245 		return 0;
8246 
8247 	for (i = 0; i < prog->insns_cnt; i++, insn++) {
8248 		if (!insn_is_helper_call(insn, &func_id))
8249 			continue;
8250 
8251 		/* on kernels that don't yet support
8252 		 * bpf_probe_read_{kernel,user}[_str] helpers, fall back
8253 		 * to bpf_probe_read() which works well for old kernels
8254 		 */
8255 		switch (func_id) {
8256 		case BPF_FUNC_probe_read_kernel:
8257 		case BPF_FUNC_probe_read_user:
8258 			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
8259 				insn->imm = BPF_FUNC_probe_read;
8260 			break;
8261 		case BPF_FUNC_probe_read_kernel_str:
8262 		case BPF_FUNC_probe_read_user_str:
8263 			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
8264 				insn->imm = BPF_FUNC_probe_read_str;
8265 			break;
8266 		default:
8267 			break;
8268 		}
8269 	}
8270 	return 0;
8271 }
8272 
8273 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
8274 				     int *btf_obj_fd, int *btf_type_id);
8275 
8276 static inline bool is_tracing_multi(enum bpf_attach_type type)
8277 {
8278 	return type == BPF_TRACE_FENTRY_MULTI || type == BPF_TRACE_FEXIT_MULTI ||
8279 	       type == BPF_TRACE_FSESSION_MULTI;
8280 }
8281 
8282 static const struct module_btf *find_attach_module(struct bpf_object *obj, const char *attach)
8283 {
8284 	const char *sep, *mod_name = NULL;
8285 	int i, mod_len, err;
8286 
8287 	/*
8288 	 * We expect attach string in the form of either
8289 	 * - function_pattern or
8290 	 * - <module>:function_pattern
8291 	 */
8292 	sep = strchr(attach, ':');
8293 	if (sep) {
8294 		mod_name = attach;
8295 		mod_len = sep - mod_name;
8296 	}
8297 	if (!mod_name)
8298 		return NULL;
8299 
8300 	err = load_module_btfs(obj);
8301 	if (err)
8302 		return NULL;
8303 
8304 	for (i = 0; i < obj->btf_module_cnt; i++) {
8305 		const struct module_btf *mod = &obj->btf_modules[i];
8306 
8307 		if (strncmp(mod->name, mod_name, mod_len) == 0 && mod->name[mod_len] == '\0')
8308 			return mod;
8309 	}
8310 	return NULL;
8311 }
8312 
8313 static int tracing_multi_mod_fd(struct bpf_program *prog, int *btf_obj_fd)
8314 {
8315 	const char *attach_name, *sep;
8316 	const struct module_btf *mod;
8317 
8318 	*btf_obj_fd = 0;
8319 	attach_name = strchr(prog->sec_name, '/');
8320 
8321 	/* Program with no details in spec, using kernel btf. */
8322 	if (!attach_name)
8323 		return 0;
8324 
8325 	/* Program with no module section, using kernel btf. */
8326 	sep = strchr(++attach_name, ':');
8327 	if (!sep)
8328 		return 0;
8329 
8330 	/* Program with module specified, get its btf fd. */
8331 	mod = find_attach_module(prog->obj, attach_name);
8332 	if (!mod)
8333 		return -EINVAL;
8334 
8335 	*btf_obj_fd = mod->fd;
8336 	return 0;
8337 }
8338 
8339 static int libbpf_setup_prog_flags(struct bpf_program *prog, long cookie)
8340 {
8341 	enum sec_def_flags def = cookie;
8342 
8343 	if (def & SEC_SLEEPABLE)
8344 		prog->prog_flags |= BPF_F_SLEEPABLE;
8345 
8346 	if (def & SEC_XDP_FRAGS)
8347 		prog->prog_flags |= BPF_F_XDP_HAS_FRAGS;
8348 
8349 	return 0;
8350 }
8351 
8352 /* this is called as prog->sec_def->prog_prepare_load_fn for libbpf-supported sec_defs */
8353 static int libbpf_prepare_prog_load(struct bpf_program *prog,
8354 				    struct bpf_prog_load_opts *opts, long cookie)
8355 {
8356 	enum sec_def_flags def = cookie;
8357 
8358 	/* old kernels might not support specifying expected_attach_type */
8359 	if ((def & SEC_EXP_ATTACH_OPT) && !kernel_supports(prog->obj, FEAT_EXP_ATTACH_TYPE))
8360 		opts->expected_attach_type = 0;
8361 
8362 	/* special check for usdt to use uprobe_multi link */
8363 	if ((def & SEC_USDT) && kernel_supports(prog->obj, FEAT_UPROBE_MULTI_LINK)) {
8364 		/* for BPF_TRACE_UPROBE_MULTI, user might want to query expected_attach_type
8365 		 * in prog, and expected_attach_type we set in kernel is from opts, so we
8366 		 * update both.
8367 		 */
8368 		prog->expected_attach_type = BPF_TRACE_UPROBE_MULTI;
8369 		opts->expected_attach_type = BPF_TRACE_UPROBE_MULTI;
8370 	}
8371 
8372 	if ((def & SEC_ATTACH_BTF) && !prog->attach_btf_id) {
8373 		int btf_obj_fd = 0, btf_type_id = 0, err;
8374 		const char *attach_name;
8375 
8376 		attach_name = strchr(prog->sec_name, '/');
8377 		if (!attach_name) {
8378 			/* if BPF program is annotated with just SEC("fentry")
8379 			 * (or similar) without declaratively specifying
8380 			 * target, then it is expected that target will be
8381 			 * specified with bpf_program__set_attach_target() at
8382 			 * runtime before BPF object load step. If not, then
8383 			 * there is nothing to load into the kernel as BPF
8384 			 * verifier won't be able to validate BPF program
8385 			 * correctness anyways.
8386 			 */
8387 			pr_warn("prog '%s': no BTF-based attach target is specified, use bpf_program__set_attach_target()\n",
8388 				prog->name);
8389 			return -EINVAL;
8390 		}
8391 		attach_name++; /* skip over / */
8392 
8393 		err = libbpf_find_attach_btf_id(prog, attach_name, &btf_obj_fd, &btf_type_id);
8394 		if (err)
8395 			return err;
8396 
8397 		/* cache resolved BTF FD and BTF type ID in the prog */
8398 		prog->attach_btf_obj_fd = btf_obj_fd;
8399 		prog->attach_btf_id = btf_type_id;
8400 
8401 		/* but by now libbpf common logic is not utilizing
8402 		 * prog->attach_btf_obj_fd/prog->attach_btf_id anymore because
8403 		 * this callback is called after opts were populated by
8404 		 * libbpf, so this callback has to update opts explicitly here
8405 		 */
8406 		opts->attach_btf_obj_fd = btf_obj_fd;
8407 		opts->attach_btf_id = btf_type_id;
8408 	}
8409 
8410 	if (is_tracing_multi(prog->expected_attach_type)) {
8411 		int err, btf_obj_fd = 0;
8412 
8413 		err = tracing_multi_mod_fd(prog, &btf_obj_fd);
8414 		if (err < 0)
8415 			return err;
8416 
8417 		prog->attach_btf_obj_fd = btf_obj_fd;
8418 		opts->attach_btf_obj_fd = btf_obj_fd;
8419 	}
8420 
8421 	return 0;
8422 }
8423 
8424 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz);
8425 
8426 /*
8427  * Bind the arena of the object to the program about to be loaded. A program
8428  * has an arena only when an insn refers to the map, but the kernel can hand
8429  * it arena pointers all the same, as struct_ops arguments, through tagged
8430  * struct members or as kfunc return values, and the verifier rejects those
8431  * when the program has no arena to place them in. A continuous fd_array
8432  * binds every map in it, the arena takes slot 0, which is free: a kfunc insn
8433  * with offset 0 names vmlinux BTF rather than a slot.
8434  */
8435 static int bpf_object__bind_arena(struct bpf_object *obj, struct bpf_program *prog,
8436 				  struct bpf_prog_load_opts *load_attr)
8437 {
8438 	struct bpf_map *map;
8439 	int err;
8440 
8441 	if (obj->gen_loader || obj->arena_map_idx < 0 || !kernel_supports(obj, FEAT_FD_ARRAY_CNT))
8442 		return 0;
8443 	map = &obj->maps[obj->arena_map_idx];
8444 	/*
8445 	 * Nothing to bind when the arena is not created, or no longer is after
8446 	 * a failed load, when it is exclusive to another program, and nothing
8447 	 * for an offloaded program, which the kernel does not let near an
8448 	 * arena.
8449 	 */
8450 	if (!map->autocreate || map->fd < 0 || (map->excl_prog && map->excl_prog != prog) ||
8451 	    load_attr->prog_ifindex)
8452 		return 0;
8453 	/*
8454 	 * An arena exclusive to the program itself needs a kernel that checks
8455 	 * the map against the digest of the final program. Earlier kernels
8456 	 * compared a map bound through the fd_array against a digest they had
8457 	 * not computed yet and refused the load; there the program binds its
8458 	 * arena through its insns, as before.
8459 	 */
8460 	if (map->excl_prog && !kernel_supports(obj, FEAT_EXCL_MAP_FD_ARRAY_CNT))
8461 		return 0;
8462 
8463 	if (!obj->fd_array_used) {
8464 		err = libbpf_ensure_mem((void **)&obj->fd_array, &obj->fd_array_cap, sizeof(int), 1);
8465 		if (err)
8466 			return err;
8467 		obj->fd_array_used = 1;
8468 	}
8469 	obj->fd_array[0] = map->fd;
8470 	load_attr->fd_array = obj->fd_array;
8471 	/* with slot 0 filled every slot handed out is valid, so the array can go with a count */
8472 	load_attr->fd_array_cnt = obj->fd_array_used;
8473 	return 0;
8474 }
8475 
8476 static int bpf_object_load_prog(struct bpf_object *obj, struct bpf_program *prog,
8477 				struct bpf_insn *insns, int insns_cnt,
8478 				const char *license, __u32 kern_version, int *prog_fd)
8479 {
8480 	LIBBPF_OPTS(bpf_prog_load_opts, load_attr);
8481 	const char *prog_name = NULL;
8482 	size_t log_buf_size = 0;
8483 	char *log_buf = NULL, *tmp;
8484 	bool own_log_buf = true;
8485 	__u32 log_level = prog->log_level;
8486 	int ret, err;
8487 
8488 	/* Be more helpful by rejecting programs that can't be validated early
8489 	 * with more meaningful and actionable error message.
8490 	 */
8491 	switch (prog->type) {
8492 	case BPF_PROG_TYPE_UNSPEC:
8493 		/*
8494 		 * The program type must be set.  Most likely we couldn't find a proper
8495 		 * section definition at load time, and thus we didn't infer the type.
8496 		 */
8497 		pr_warn("prog '%s': missing BPF prog type, check ELF section name '%s'\n",
8498 			prog->name, prog->sec_name);
8499 		return -EINVAL;
8500 	case BPF_PROG_TYPE_STRUCT_OPS:
8501 		if (prog->attach_btf_id == 0) {
8502 			pr_warn("prog '%s': SEC(\"struct_ops\") program isn't referenced anywhere, did you forget to use it?\n",
8503 				prog->name);
8504 			return -EINVAL;
8505 		}
8506 		break;
8507 	default:
8508 		break;
8509 	}
8510 
8511 	if (!insns || !insns_cnt)
8512 		return -EINVAL;
8513 
8514 	if (kernel_supports(obj, FEAT_PROG_NAME))
8515 		prog_name = prog->name;
8516 	load_attr.attach_prog_fd = prog->attach_prog_fd;
8517 	load_attr.attach_btf_obj_fd = prog->attach_btf_obj_fd;
8518 	load_attr.attach_btf_id = prog->attach_btf_id;
8519 	load_attr.kern_version = kern_version;
8520 	load_attr.prog_ifindex = prog->prog_ifindex;
8521 	load_attr.expected_attach_type = prog->expected_attach_type;
8522 
8523 	/* specify func_info/line_info only if kernel supports them */
8524 	if (obj->btf && btf__fd(obj->btf) >= 0 && kernel_supports(obj, FEAT_BTF_FUNC)) {
8525 		load_attr.prog_btf_fd = btf__fd(obj->btf);
8526 		load_attr.func_info = prog->func_info;
8527 		load_attr.func_info_rec_size = prog->func_info_rec_size;
8528 		load_attr.func_info_cnt = prog->func_info_cnt;
8529 		load_attr.line_info = prog->line_info;
8530 		load_attr.line_info_rec_size = prog->line_info_rec_size;
8531 		load_attr.line_info_cnt = prog->line_info_cnt;
8532 	}
8533 	load_attr.log_level = log_level;
8534 	load_attr.prog_flags = prog->prog_flags;
8535 	load_attr.fd_array = obj->fd_array;
8536 	err = bpf_object__bind_arena(obj, prog, &load_attr);
8537 	if (err)
8538 		return err;
8539 
8540 	load_attr.token_fd = obj->token_fd;
8541 	if (obj->token_fd)
8542 		load_attr.prog_flags |= BPF_F_TOKEN_FD;
8543 
8544 	/* adjust load_attr if sec_def provides custom preload callback */
8545 	if (prog->sec_def && prog->sec_def->prog_prepare_load_fn) {
8546 		err = prog->sec_def->prog_prepare_load_fn(prog, &load_attr, prog->sec_def->cookie);
8547 		if (err < 0) {
8548 			pr_warn("prog '%s': failed to prepare load attributes: %s\n",
8549 				prog->name, errstr(err));
8550 			return err;
8551 		}
8552 		insns = prog->insns;
8553 		insns_cnt = prog->insns_cnt;
8554 	}
8555 
8556 	if (obj->gen_loader) {
8557 		bpf_gen__prog_load(obj->gen_loader, prog->type, prog->name,
8558 				   license, insns, insns_cnt, &load_attr,
8559 				   prog - obj->programs);
8560 		*prog_fd = -1;
8561 		return 0;
8562 	}
8563 
8564 retry_load:
8565 	/* if log_level is zero, we don't request logs initially even if
8566 	 * custom log_buf is specified; if the program load fails, then we'll
8567 	 * bump log_level to 1 and use either custom log_buf or we'll allocate
8568 	 * our own and retry the load to get details on what failed
8569 	 */
8570 	if (log_level) {
8571 		if (prog->log_buf) {
8572 			log_buf = prog->log_buf;
8573 			log_buf_size = prog->log_size;
8574 			own_log_buf = false;
8575 		} else if (obj->log_buf) {
8576 			log_buf = obj->log_buf;
8577 			log_buf_size = obj->log_size;
8578 			own_log_buf = false;
8579 		} else {
8580 			log_buf_size = max((size_t)BPF_LOG_BUF_SIZE, log_buf_size * 2);
8581 			tmp = realloc(log_buf, log_buf_size);
8582 			if (!tmp) {
8583 				ret = -ENOMEM;
8584 				goto out;
8585 			}
8586 			log_buf = tmp;
8587 			log_buf[0] = '\0';
8588 			own_log_buf = true;
8589 		}
8590 	}
8591 
8592 	load_attr.log_buf = log_buf;
8593 	load_attr.log_size = log_buf_size;
8594 	load_attr.log_level = log_level;
8595 
8596 	ret = bpf_prog_load(prog->type, prog_name, license, insns, insns_cnt, &load_attr);
8597 	if (ret >= 0) {
8598 		if (log_level && own_log_buf) {
8599 			pr_debug("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
8600 				 prog->name, log_buf);
8601 		}
8602 
8603 		if (obj->has_rodata && kernel_supports(obj, FEAT_PROG_BIND_MAP)) {
8604 			struct bpf_map *map;
8605 			int i;
8606 
8607 			for (i = 0; i < obj->nr_maps; i++) {
8608 				map = &prog->obj->maps[i];
8609 				if (map->libbpf_type != LIBBPF_MAP_RODATA)
8610 					continue;
8611 
8612 				if (bpf_prog_bind_map(ret, map->fd, NULL)) {
8613 					pr_warn("prog '%s': failed to bind map '%s': %s\n",
8614 						prog->name, map->real_name, errstr(errno));
8615 					/* Don't fail hard if can't bind rodata. */
8616 				}
8617 			}
8618 		}
8619 
8620 		*prog_fd = ret;
8621 		ret = 0;
8622 		goto out;
8623 	}
8624 
8625 	if (log_level == 0) {
8626 		log_level = 1;
8627 		goto retry_load;
8628 	}
8629 	/* On ENOSPC, increase log buffer size and retry, unless custom
8630 	 * log_buf is specified.
8631 	 * Be careful to not overflow u32, though. Kernel's log buf size limit
8632 	 * isn't part of UAPI so it can always be bumped to full 4GB. So don't
8633 	 * multiply by 2 unless we are sure we'll fit within 32 bits.
8634 	 * Currently, we'll get -EINVAL when we reach (UINT_MAX >> 2).
8635 	 */
8636 	if (own_log_buf && errno == ENOSPC && log_buf_size <= UINT_MAX / 2)
8637 		goto retry_load;
8638 
8639 	ret = -errno;
8640 
8641 	/* post-process verifier log to improve error descriptions */
8642 	fixup_verifier_log(prog, log_buf, log_buf_size);
8643 
8644 	pr_warn("prog '%s': BPF program load failed: %s\n", prog->name, errstr(errno));
8645 	pr_perm_msg(ret);
8646 
8647 	if (own_log_buf && log_buf && log_buf[0] != '\0') {
8648 		pr_warn("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
8649 			prog->name, log_buf);
8650 	}
8651 
8652 out:
8653 	if (own_log_buf)
8654 		free(log_buf);
8655 	return ret;
8656 }
8657 
8658 static char *find_prev_line(char *buf, char *cur)
8659 {
8660 	char *p;
8661 
8662 	if (cur == buf) /* end of a log buf */
8663 		return NULL;
8664 
8665 	p = cur - 1;
8666 	while (p - 1 >= buf && *(p - 1) != '\n')
8667 		p--;
8668 
8669 	return p;
8670 }
8671 
8672 static void patch_log(char *buf, size_t buf_sz, size_t log_sz,
8673 		      char *orig, size_t orig_sz, const char *patch)
8674 {
8675 	/* size of the remaining log content to the right from the to-be-replaced part */
8676 	size_t rem_sz = (buf + log_sz) - (orig + orig_sz);
8677 	size_t patch_sz = strlen(patch);
8678 
8679 	if (patch_sz != orig_sz) {
8680 		/* If patch line(s) are longer than original piece of verifier log,
8681 		 * shift log contents by (patch_sz - orig_sz) bytes to the right
8682 		 * starting from after to-be-replaced part of the log.
8683 		 *
8684 		 * If patch line(s) are shorter than original piece of verifier log,
8685 		 * shift log contents by (orig_sz - patch_sz) bytes to the left
8686 		 * starting from after to-be-replaced part of the log
8687 		 *
8688 		 * We need to be careful about not overflowing available
8689 		 * buf_sz capacity. If that's the case, we'll truncate the end
8690 		 * of the original log, as necessary.
8691 		 */
8692 		if (patch_sz > orig_sz) {
8693 			if (orig + patch_sz >= buf + buf_sz) {
8694 				/* patch is big enough to cover remaining space completely */
8695 				patch_sz -= (orig + patch_sz) - (buf + buf_sz) + 1;
8696 				rem_sz = 0;
8697 			} else if (patch_sz - orig_sz > buf_sz - log_sz) {
8698 				/* patch causes part of remaining log to be truncated */
8699 				rem_sz -= (patch_sz - orig_sz) - (buf_sz - log_sz);
8700 			}
8701 		}
8702 		/* shift remaining log to the right by calculated amount */
8703 		memmove(orig + patch_sz, orig + orig_sz, rem_sz);
8704 	}
8705 
8706 	memcpy(orig, patch, patch_sz);
8707 }
8708 
8709 static void fixup_log_failed_core_relo(struct bpf_program *prog,
8710 				       char *buf, size_t buf_sz, size_t log_sz,
8711 				       char *line1, char *line2, char *line3)
8712 {
8713 	/* Expected log for failed and not properly guarded CO-RE relocation:
8714 	 * line1 -> 123: (85) call unknown#195896080
8715 	 * line2 -> invalid func unknown#195896080
8716 	 * line3 -> <anything else or end of buffer>
8717 	 *
8718 	 * "123" is the index of the instruction that was poisoned. We extract
8719 	 * instruction index to find corresponding CO-RE relocation and
8720 	 * replace this part of the log with more relevant information about
8721 	 * failed CO-RE relocation.
8722 	 */
8723 	const struct bpf_core_relo *relo;
8724 	struct bpf_core_spec spec;
8725 	char patch[512], spec_buf[256];
8726 	int insn_idx, err, spec_len;
8727 
8728 	if (sscanf(line1, "%d: (%*d) call unknown#195896080\n", &insn_idx) != 1)
8729 		return;
8730 
8731 	relo = find_relo_core(prog, insn_idx);
8732 	if (!relo)
8733 		return;
8734 
8735 	err = bpf_core_parse_spec(prog->name, prog->obj->btf, relo, &spec);
8736 	if (err)
8737 		return;
8738 
8739 	spec_len = bpf_core_format_spec(spec_buf, sizeof(spec_buf), &spec);
8740 	snprintf(patch, sizeof(patch),
8741 		 "%d: <invalid CO-RE relocation>\n"
8742 		 "failed to resolve CO-RE relocation %s%s\n",
8743 		 insn_idx, spec_buf, spec_len >= sizeof(spec_buf) ? "..." : "");
8744 
8745 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
8746 }
8747 
8748 static void fixup_log_missing_map_load(struct bpf_program *prog,
8749 				       char *buf, size_t buf_sz, size_t log_sz,
8750 				       char *line1, char *line2, char *line3)
8751 {
8752 	/* Expected log for failed and not properly guarded map reference:
8753 	 * line1 -> 123: (85) call unknown#2001000345
8754 	 * line2 -> invalid func unknown#2001000345
8755 	 * line3 -> <anything else or end of buffer>
8756 	 *
8757 	 * "123" is the index of the instruction that was poisoned.
8758 	 * "345" in "2001000345" is a map index in obj->maps to fetch map name.
8759 	 */
8760 	struct bpf_object *obj = prog->obj;
8761 	const struct bpf_map *map;
8762 	int insn_idx, map_idx;
8763 	char patch[128];
8764 
8765 	if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &map_idx) != 2)
8766 		return;
8767 
8768 	map_idx -= POISON_LDIMM64_MAP_BASE;
8769 	if (map_idx < 0 || map_idx >= obj->nr_maps)
8770 		return;
8771 	map = &obj->maps[map_idx];
8772 
8773 	snprintf(patch, sizeof(patch),
8774 		 "%d: <invalid BPF map reference>\n"
8775 		 "BPF map '%s' is referenced but wasn't created\n",
8776 		 insn_idx, map->name);
8777 
8778 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
8779 }
8780 
8781 static void fixup_log_missing_kfunc_call(struct bpf_program *prog,
8782 					 char *buf, size_t buf_sz, size_t log_sz,
8783 					 char *line1, char *line2, char *line3)
8784 {
8785 	/* Expected log for failed and not properly guarded kfunc call:
8786 	 * line1 -> 123: (85) call unknown#2002000345
8787 	 * line2 -> invalid func unknown#2002000345
8788 	 * line3 -> <anything else or end of buffer>
8789 	 *
8790 	 * "123" is the index of the instruction that was poisoned.
8791 	 * "345" in "2002000345" is an extern index in obj->externs to fetch kfunc name.
8792 	 */
8793 	struct bpf_object *obj = prog->obj;
8794 	const struct extern_desc *ext;
8795 	int insn_idx, ext_idx;
8796 	char patch[128];
8797 
8798 	if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &ext_idx) != 2)
8799 		return;
8800 
8801 	ext_idx -= POISON_CALL_KFUNC_BASE;
8802 	if (ext_idx < 0 || ext_idx >= obj->nr_extern)
8803 		return;
8804 	ext = &obj->externs[ext_idx];
8805 
8806 	snprintf(patch, sizeof(patch),
8807 		 "%d: <invalid kfunc call>\n"
8808 		 "kfunc '%s' is referenced but wasn't resolved\n",
8809 		 insn_idx, ext->name);
8810 
8811 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
8812 }
8813 
8814 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz)
8815 {
8816 	/* look for familiar error patterns in last N lines of the log */
8817 	const size_t max_last_line_cnt = 10;
8818 	char *prev_line, *cur_line, *next_line;
8819 	size_t log_sz;
8820 	int i;
8821 
8822 	if (!buf)
8823 		return;
8824 
8825 	log_sz = strlen(buf) + 1;
8826 	next_line = buf + log_sz - 1;
8827 
8828 	for (i = 0; i < max_last_line_cnt; i++, next_line = cur_line) {
8829 		cur_line = find_prev_line(buf, next_line);
8830 		if (!cur_line)
8831 			return;
8832 
8833 		if (str_has_pfx(cur_line, "invalid func unknown#195896080\n")) {
8834 			prev_line = find_prev_line(buf, cur_line);
8835 			if (!prev_line)
8836 				continue;
8837 
8838 			/* failed CO-RE relocation case */
8839 			fixup_log_failed_core_relo(prog, buf, buf_sz, log_sz,
8840 						   prev_line, cur_line, next_line);
8841 			return;
8842 		} else if (str_has_pfx(cur_line, "invalid func unknown#"POISON_LDIMM64_MAP_PFX)) {
8843 			prev_line = find_prev_line(buf, cur_line);
8844 			if (!prev_line)
8845 				continue;
8846 
8847 			/* reference to uncreated BPF map */
8848 			fixup_log_missing_map_load(prog, buf, buf_sz, log_sz,
8849 						   prev_line, cur_line, next_line);
8850 			return;
8851 		} else if (str_has_pfx(cur_line, "invalid func unknown#"POISON_CALL_KFUNC_PFX)) {
8852 			prev_line = find_prev_line(buf, cur_line);
8853 			if (!prev_line)
8854 				continue;
8855 
8856 			/* reference to unresolved kfunc */
8857 			fixup_log_missing_kfunc_call(prog, buf, buf_sz, log_sz,
8858 						     prev_line, cur_line, next_line);
8859 			return;
8860 		}
8861 	}
8862 }
8863 
8864 static int bpf_program_record_relos(struct bpf_program *prog)
8865 {
8866 	struct bpf_object *obj = prog->obj;
8867 	int i;
8868 
8869 	for (i = 0; i < prog->nr_reloc; i++) {
8870 		struct reloc_desc *relo = &prog->reloc_desc[i];
8871 		struct extern_desc *ext = &obj->externs[relo->ext_idx];
8872 		int kind;
8873 
8874 		switch (relo->type) {
8875 		case RELO_EXTERN_LD64:
8876 			if (ext->type != EXT_KSYM)
8877 				continue;
8878 			kind = btf_is_var(btf__type_by_id(obj->btf, ext->btf_id)) ?
8879 				BTF_KIND_VAR : BTF_KIND_FUNC;
8880 			bpf_gen__record_extern(obj->gen_loader, ext->name,
8881 					       ext->is_weak, !ext->ksym.type_id,
8882 					       true, kind, relo->insn_idx);
8883 			break;
8884 		case RELO_EXTERN_CALL:
8885 			bpf_gen__record_extern(obj->gen_loader, ext->name,
8886 					       ext->is_weak, false, false, BTF_KIND_FUNC,
8887 					       relo->insn_idx);
8888 			break;
8889 		case RELO_CORE: {
8890 			struct bpf_core_relo cr = {
8891 				.insn_off = relo->insn_idx * 8,
8892 				.type_id = relo->core_relo->type_id,
8893 				.access_str_off = relo->core_relo->access_str_off,
8894 				.kind = relo->core_relo->kind,
8895 			};
8896 
8897 			bpf_gen__record_relo_core(obj->gen_loader, &cr);
8898 			break;
8899 		}
8900 		default:
8901 			continue;
8902 		}
8903 	}
8904 	return 0;
8905 }
8906 
8907 static int
8908 bpf_object__load_progs(struct bpf_object *obj, int log_level)
8909 {
8910 	struct bpf_program *prog;
8911 	size_t i;
8912 	int err;
8913 
8914 	for (i = 0; i < obj->nr_programs; i++) {
8915 		prog = &obj->programs[i];
8916 		if (prog_is_subprog(obj, prog))
8917 			continue;
8918 		if (!prog->autoload) {
8919 			pr_debug("prog '%s': skipped loading\n", prog->name);
8920 			continue;
8921 		}
8922 		prog->log_level |= log_level;
8923 
8924 		if (obj->gen_loader)
8925 			bpf_program_record_relos(prog);
8926 
8927 		err = bpf_object_load_prog(obj, prog, prog->insns, prog->insns_cnt,
8928 					   obj->license, obj->kern_version, &prog->fd);
8929 		if (err) {
8930 			pr_warn("prog '%s': failed to load: %s\n", prog->name, errstr(err));
8931 			return err;
8932 		}
8933 	}
8934 
8935 	bpf_object__free_relocs(obj);
8936 	return 0;
8937 }
8938 
8939 static int bpf_object_prepare_progs(struct bpf_object *obj)
8940 {
8941 	struct bpf_program *prog;
8942 	size_t i;
8943 	int err;
8944 
8945 	for (i = 0; i < obj->nr_programs; i++) {
8946 		prog = &obj->programs[i];
8947 		err = bpf_object__sanitize_prog(obj, prog);
8948 		if (err)
8949 			return err;
8950 	}
8951 	return 0;
8952 }
8953 
8954 static const struct bpf_sec_def *find_sec_def(const char *sec_name);
8955 
8956 static int bpf_object_init_progs(struct bpf_object *obj, const struct bpf_object_open_opts *opts)
8957 {
8958 	struct bpf_program *prog;
8959 	int err;
8960 
8961 	bpf_object__for_each_program(prog, obj) {
8962 		prog->sec_def = find_sec_def(prog->sec_name);
8963 		if (!prog->sec_def) {
8964 			/* couldn't guess, but user might manually specify */
8965 			pr_debug("prog '%s': unrecognized ELF section name '%s'\n",
8966 				prog->name, prog->sec_name);
8967 			continue;
8968 		}
8969 
8970 		prog->type = prog->sec_def->prog_type;
8971 		prog->expected_attach_type = prog->sec_def->expected_attach_type;
8972 
8973 		/* sec_def can have custom callback which should be called
8974 		 * after bpf_program is initialized to adjust its properties
8975 		 */
8976 		if (prog->sec_def->prog_setup_fn) {
8977 			err = prog->sec_def->prog_setup_fn(prog, prog->sec_def->cookie);
8978 			if (err < 0) {
8979 				pr_warn("prog '%s': failed to initialize: %s\n",
8980 					prog->name, errstr(err));
8981 				return err;
8982 			}
8983 		}
8984 	}
8985 
8986 	return 0;
8987 }
8988 
8989 static struct bpf_object *bpf_object_open(const char *path, const void *obj_buf, size_t obj_buf_sz,
8990 					  const char *obj_name,
8991 					  const struct bpf_object_open_opts *opts)
8992 {
8993 	const char *kconfig, *btf_tmp_path, *token_path;
8994 	size_t mod_allow_cnt, i, j;
8995 	const char **mod_allow;
8996 	struct bpf_object *obj;
8997 	int err;
8998 	char *log_buf;
8999 	size_t log_size;
9000 	__u32 log_level;
9001 
9002 	if (obj_buf && !obj_name)
9003 		return ERR_PTR(-EINVAL);
9004 
9005 	if (elf_version(EV_CURRENT) == EV_NONE) {
9006 		pr_warn("failed to init libelf for %s\n",
9007 			path ? : "(mem buf)");
9008 		return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
9009 	}
9010 
9011 	if (!OPTS_VALID(opts, bpf_object_open_opts))
9012 		return ERR_PTR(-EINVAL);
9013 
9014 	obj_name = OPTS_GET(opts, object_name, NULL) ?: obj_name;
9015 	if (obj_buf) {
9016 		path = obj_name;
9017 		pr_debug("loading object '%s' from buffer\n", obj_name);
9018 	} else {
9019 		pr_debug("loading object from %s\n", path);
9020 	}
9021 
9022 	log_buf = OPTS_GET(opts, kernel_log_buf, NULL);
9023 	log_size = OPTS_GET(opts, kernel_log_size, 0);
9024 	log_level = OPTS_GET(opts, kernel_log_level, 0);
9025 	if (log_size > UINT_MAX)
9026 		return ERR_PTR(-EINVAL);
9027 	if (log_size && !log_buf)
9028 		return ERR_PTR(-EINVAL);
9029 
9030 	token_path = OPTS_GET(opts, bpf_token_path, NULL);
9031 	/* if user didn't specify bpf_token_path explicitly, check if
9032 	 * LIBBPF_BPF_TOKEN_PATH envvar was set and treat it as bpf_token_path
9033 	 * option
9034 	 */
9035 	if (!token_path)
9036 		token_path = getenv("LIBBPF_BPF_TOKEN_PATH");
9037 	if (token_path && strlen(token_path) >= PATH_MAX)
9038 		return ERR_PTR(-ENAMETOOLONG);
9039 
9040 	mod_allow = OPTS_GET(opts, btf_module_allowlist, NULL);
9041 	mod_allow_cnt = OPTS_GET(opts, btf_module_allowlist_cnt, 0);
9042 
9043 	if (mod_allow_cnt > SSIZE_MAX || (!mod_allow && mod_allow_cnt > 0))
9044 		return ERR_PTR(-EINVAL);
9045 
9046 	for (i = 0; i < mod_allow_cnt; i++) {
9047 		if (!mod_allow[i] || !mod_allow[i][0])
9048 			return ERR_PTR(-EINVAL);
9049 
9050 		for (j = 0; j < i; j++) {
9051 			if (strcmp(mod_allow[i], mod_allow[j]) == 0)
9052 				return ERR_PTR(-EINVAL);
9053 		}
9054 	}
9055 
9056 	obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
9057 	if (IS_ERR(obj))
9058 		return obj;
9059 
9060 	obj->log_buf = log_buf;
9061 	obj->log_size = log_size;
9062 	obj->log_level = log_level;
9063 
9064 	if (token_path) {
9065 		obj->token_path = strdup(token_path);
9066 		if (!obj->token_path) {
9067 			err = -ENOMEM;
9068 			goto out;
9069 		}
9070 	}
9071 
9072 	btf_tmp_path = OPTS_GET(opts, btf_custom_path, NULL);
9073 	if (btf_tmp_path) {
9074 		if (strlen(btf_tmp_path) >= PATH_MAX) {
9075 			err = -ENAMETOOLONG;
9076 			goto out;
9077 		}
9078 		obj->btf_custom_path = strdup(btf_tmp_path);
9079 		if (!obj->btf_custom_path) {
9080 			err = -ENOMEM;
9081 			goto out;
9082 		}
9083 	}
9084 
9085 	kconfig = OPTS_GET(opts, kconfig, NULL);
9086 	if (kconfig) {
9087 		obj->kconfig = strdup(kconfig);
9088 		if (!obj->kconfig) {
9089 			err = -ENOMEM;
9090 			goto out;
9091 		}
9092 	}
9093 
9094 	obj->btf_module_allowlist_cnt = mod_allow ? mod_allow_cnt : -1;
9095 	if (mod_allow_cnt > 0) {
9096 		obj->btf_module_allowlist =
9097 			calloc(mod_allow_cnt, sizeof(*obj->btf_module_allowlist));
9098 		if (!obj->btf_module_allowlist) {
9099 			err = -ENOMEM;
9100 			goto out;
9101 		}
9102 
9103 		for (i = 0; i < mod_allow_cnt; i++) {
9104 			obj->btf_module_allowlist[i] = strdup(mod_allow[i]);
9105 			if (!obj->btf_module_allowlist[i]) {
9106 				err = -ENOMEM;
9107 				goto out;
9108 			}
9109 		}
9110 	}
9111 
9112 	err = bpf_object__elf_init(obj);
9113 	err = err ? : bpf_object__elf_collect(obj);
9114 	err = err ? : bpf_object__collect_externs(obj);
9115 	err = err ? : bpf_object_fixup_btf(obj);
9116 	err = err ? : bpf_object__init_maps(obj, opts);
9117 	err = err ? : bpf_object_init_progs(obj, opts);
9118 	err = err ? : bpf_object__collect_relos(obj);
9119 	if (err)
9120 		goto out;
9121 
9122 	bpf_object__elf_finish(obj);
9123 
9124 	return obj;
9125 out:
9126 	bpf_object__close(obj);
9127 	return ERR_PTR(err);
9128 }
9129 
9130 struct bpf_object *
9131 bpf_object__open_file(const char *path, const struct bpf_object_open_opts *opts)
9132 {
9133 	if (!path)
9134 		return libbpf_err_ptr(-EINVAL);
9135 
9136 	return libbpf_ptr(bpf_object_open(path, NULL, 0, NULL, opts));
9137 }
9138 
9139 struct bpf_object *bpf_object__open(const char *path)
9140 {
9141 	return bpf_object__open_file(path, NULL);
9142 }
9143 
9144 struct bpf_object *
9145 bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
9146 		     const struct bpf_object_open_opts *opts)
9147 {
9148 	char tmp_name[64];
9149 
9150 	if (!obj_buf || obj_buf_sz == 0)
9151 		return libbpf_err_ptr(-EINVAL);
9152 
9153 	/* create a (quite useless) default "name" for this memory buffer object */
9154 	snprintf(tmp_name, sizeof(tmp_name), "%lx-%zx", (unsigned long)obj_buf, obj_buf_sz);
9155 
9156 	return libbpf_ptr(bpf_object_open(NULL, obj_buf, obj_buf_sz, tmp_name, opts));
9157 }
9158 
9159 static int bpf_object_unload(struct bpf_object *obj)
9160 {
9161 	size_t i;
9162 
9163 	if (!obj)
9164 		return libbpf_err(-EINVAL);
9165 
9166 	for (i = 0; i < obj->nr_maps; i++) {
9167 		zclose(obj->maps[i].fd);
9168 		if (obj->maps[i].st_ops)
9169 			zfree(&obj->maps[i].st_ops->kern_vdata);
9170 	}
9171 
9172 	for (i = 0; i < obj->nr_programs; i++)
9173 		bpf_program__unload(&obj->programs[i]);
9174 
9175 	return 0;
9176 }
9177 
9178 static int bpf_object__sanitize_maps(struct bpf_object *obj)
9179 {
9180 	struct bpf_map *m;
9181 
9182 	bpf_object__for_each_map(m, obj) {
9183 		if (!bpf_map__is_internal(m))
9184 			continue;
9185 		if (!kernel_supports(obj, FEAT_ARRAY_MMAP))
9186 			m->def.map_flags &= ~BPF_F_MMAPABLE;
9187 	}
9188 
9189 	return 0;
9190 }
9191 
9192 typedef int (*kallsyms_cb_t)(unsigned long long sym_addr, char sym_type,
9193 			     const char *sym_name, void *ctx);
9194 
9195 static int libbpf_kallsyms_parse(kallsyms_cb_t cb, void *ctx)
9196 {
9197 	char sym_type, sym_name[500];
9198 	unsigned long long sym_addr;
9199 	int ret, err = 0;
9200 	FILE *f;
9201 
9202 	f = fopen("/proc/kallsyms", "re");
9203 	if (!f) {
9204 		err = -errno;
9205 		pr_warn("failed to open /proc/kallsyms: %s\n", errstr(err));
9206 		return err;
9207 	}
9208 
9209 	while (true) {
9210 		ret = fscanf(f, "%llx %c %499s%*[^\n]\n",
9211 			     &sym_addr, &sym_type, sym_name);
9212 		if (ret == EOF && feof(f))
9213 			break;
9214 		if (ret != 3) {
9215 			pr_warn("failed to read kallsyms entry: %d\n", ret);
9216 			err = -EINVAL;
9217 			break;
9218 		}
9219 
9220 		err = cb(sym_addr, sym_type, sym_name, ctx);
9221 		if (err)
9222 			break;
9223 	}
9224 
9225 	fclose(f);
9226 	return err;
9227 }
9228 
9229 static int kallsyms_cb(unsigned long long sym_addr, char sym_type,
9230 		       const char *sym_name, void *ctx)
9231 {
9232 	struct bpf_object *obj = ctx;
9233 	const struct btf_type *t;
9234 	struct extern_desc *ext;
9235 	const char *res;
9236 
9237 	res = strstr(sym_name, ".llvm.");
9238 	if (sym_type == 'd' && res)
9239 		ext = find_extern_by_name_with_len(obj, sym_name, res - sym_name);
9240 	else
9241 		ext = find_extern_by_name(obj, sym_name);
9242 	if (!ext || ext->type != EXT_KSYM)
9243 		return 0;
9244 
9245 	t = btf__type_by_id(obj->btf, ext->btf_id);
9246 	if (!btf_is_var(t))
9247 		return 0;
9248 
9249 	if (ext->is_set && ext->ksym.addr != sym_addr) {
9250 		pr_warn("extern (ksym) '%s': resolution is ambiguous: 0x%llx or 0x%llx\n",
9251 			sym_name, ext->ksym.addr, sym_addr);
9252 		return -EINVAL;
9253 	}
9254 	if (!ext->is_set) {
9255 		ext->is_set = true;
9256 		ext->ksym.addr = sym_addr;
9257 		pr_debug("extern (ksym) '%s': set to 0x%llx\n", sym_name, sym_addr);
9258 	}
9259 	return 0;
9260 }
9261 
9262 static int bpf_object__read_kallsyms_file(struct bpf_object *obj)
9263 {
9264 	return libbpf_kallsyms_parse(kallsyms_cb, obj);
9265 }
9266 
9267 static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
9268 			    __u16 kind, struct btf **res_btf,
9269 			    struct module_btf **res_mod_btf)
9270 {
9271 	struct module_btf *mod_btf;
9272 	struct btf *btf;
9273 	int i, id, err;
9274 
9275 	btf = obj->btf_vmlinux;
9276 	mod_btf = NULL;
9277 	id = btf__find_by_name_kind(btf, ksym_name, kind);
9278 
9279 	if (id == -ENOENT) {
9280 		err = load_module_btfs(obj);
9281 		if (err)
9282 			return err;
9283 
9284 		for (i = 0; i < obj->btf_module_cnt; i++) {
9285 			/* we assume module_btf's BTF FD is always >0 */
9286 			mod_btf = &obj->btf_modules[i];
9287 			btf = mod_btf->btf;
9288 			id = btf__find_by_name_kind_own(btf, ksym_name, kind);
9289 			if (id != -ENOENT)
9290 				break;
9291 		}
9292 	}
9293 	if (id <= 0)
9294 		return -ESRCH;
9295 
9296 	*res_btf = btf;
9297 	*res_mod_btf = mod_btf;
9298 	return id;
9299 }
9300 
9301 static int bpf_object__resolve_ksym_var_btf_id(struct bpf_object *obj,
9302 					       struct extern_desc *ext)
9303 {
9304 	const struct btf_type *targ_var, *targ_type;
9305 	__u32 targ_type_id, local_type_id;
9306 	struct module_btf *mod_btf = NULL;
9307 	const char *targ_var_name;
9308 	struct btf *btf = NULL;
9309 	int id, err;
9310 
9311 	id = find_ksym_btf_id(obj, ext->name, BTF_KIND_VAR, &btf, &mod_btf);
9312 	if (id < 0) {
9313 		if (id == -ESRCH && ext->is_weak)
9314 			return 0;
9315 		pr_warn("extern (var ksym) '%s': not found in kernel BTF\n",
9316 			ext->name);
9317 		return id;
9318 	}
9319 
9320 	/* find local type_id */
9321 	local_type_id = ext->ksym.type_id;
9322 
9323 	/* find target type_id */
9324 	targ_var = btf__type_by_id(btf, id);
9325 	targ_var_name = btf__name_by_offset(btf, targ_var->name_off);
9326 	targ_type = skip_mods_and_typedefs(btf, targ_var->type, &targ_type_id);
9327 
9328 	err = bpf_core_types_are_compat(obj->btf, local_type_id,
9329 					btf, targ_type_id);
9330 	if (err <= 0) {
9331 		const struct btf_type *local_type;
9332 		const char *targ_name, *local_name;
9333 
9334 		local_type = btf__type_by_id(obj->btf, local_type_id);
9335 		local_name = btf__name_by_offset(obj->btf, local_type->name_off);
9336 		targ_name = btf__name_by_offset(btf, targ_type->name_off);
9337 
9338 		pr_warn("extern (var ksym) '%s': incompatible types, expected [%u] %s %s, but kernel has [%u] %s %s\n",
9339 			ext->name, local_type_id,
9340 			btf_kind_str(local_type), local_name, targ_type_id,
9341 			btf_kind_str(targ_type), targ_name);
9342 		return -EINVAL;
9343 	}
9344 
9345 	ext->is_set = true;
9346 	ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
9347 	ext->ksym.kernel_btf_id = id;
9348 	pr_debug("extern (var ksym) '%s': resolved to [%d] %s %s\n",
9349 		 ext->name, id, btf_kind_str(targ_var), targ_var_name);
9350 
9351 	return 0;
9352 }
9353 
9354 static int bpf_object__resolve_ksym_func_btf_id(struct bpf_object *obj,
9355 						struct extern_desc *ext)
9356 {
9357 	int local_func_proto_id, kfunc_proto_id, kfunc_id;
9358 	struct module_btf *mod_btf = NULL;
9359 	const struct btf_type *kern_func;
9360 	struct btf *kern_btf = NULL;
9361 	int ret;
9362 
9363 	local_func_proto_id = ext->ksym.type_id;
9364 
9365 	kfunc_id = find_ksym_btf_id(obj, ext->essent_name ?: ext->name, BTF_KIND_FUNC, &kern_btf,
9366 				    &mod_btf);
9367 	if (kfunc_id < 0) {
9368 		if (kfunc_id == -ESRCH && ext->is_weak)
9369 			return 0;
9370 		pr_warn("extern (func ksym) '%s': not found in kernel or module BTFs\n",
9371 			ext->name);
9372 		return kfunc_id;
9373 	}
9374 
9375 	kern_func = btf__type_by_id(kern_btf, kfunc_id);
9376 	kfunc_proto_id = kern_func->type;
9377 
9378 	ret = bpf_core_types_are_compat(obj->btf, local_func_proto_id,
9379 					kern_btf, kfunc_proto_id);
9380 	if (ret <= 0) {
9381 		if (ext->is_weak)
9382 			return 0;
9383 
9384 		pr_warn("extern (func ksym) '%s': func_proto [%d] incompatible with %s [%d]\n",
9385 			ext->name, local_func_proto_id,
9386 			mod_btf ? mod_btf->name : "vmlinux", kfunc_proto_id);
9387 		return -EINVAL;
9388 	}
9389 
9390 	/* set index for module BTF fd in fd_array, if unset */
9391 	if (mod_btf && !mod_btf->fd_array_idx) {
9392 		/* insn->off is s16 */
9393 		if (obj->fd_array_used == INT16_MAX) {
9394 			pr_warn("extern (func ksym) '%s': module BTF fd index %d too big to fit in bpf_insn offset\n",
9395 				ext->name, mod_btf->fd_array_idx);
9396 			return -E2BIG;
9397 		}
9398 		/* Cannot use index 0 for module BTF fd */
9399 		if (!obj->fd_array_used)
9400 			obj->fd_array_used = 1;
9401 
9402 		ret = libbpf_ensure_mem((void **)&obj->fd_array, &obj->fd_array_cap, sizeof(int),
9403 					obj->fd_array_used + 1);
9404 		if (ret)
9405 			return ret;
9406 		mod_btf->fd_array_idx = obj->fd_array_used;
9407 		/* we assume module BTF FD is always >0 */
9408 		obj->fd_array[obj->fd_array_used++] = mod_btf->fd;
9409 	}
9410 
9411 	ext->is_set = true;
9412 	ext->ksym.kernel_btf_id = kfunc_id;
9413 	ext->ksym.btf_fd_idx = mod_btf ? mod_btf->fd_array_idx : 0;
9414 	/* Also set kernel_btf_obj_fd to make sure that bpf_object__relocate_data()
9415 	 * populates FD into ld_imm64 insn when it's used to point to kfunc.
9416 	 * {kernel_btf_id, btf_fd_idx} -> fixup bpf_call.
9417 	 * {kernel_btf_id, kernel_btf_obj_fd} -> fixup ld_imm64.
9418 	 */
9419 	ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
9420 	pr_debug("extern (func ksym) '%s': resolved to %s [%d]\n",
9421 		 ext->name, mod_btf ? mod_btf->name : "vmlinux", kfunc_id);
9422 
9423 	return 0;
9424 }
9425 
9426 static int bpf_object__resolve_ksyms_btf_id(struct bpf_object *obj)
9427 {
9428 	const struct btf_type *t;
9429 	struct extern_desc *ext;
9430 	int i, err;
9431 
9432 	for (i = 0; i < obj->nr_extern; i++) {
9433 		ext = &obj->externs[i];
9434 		if (ext->type != EXT_KSYM || !ext->ksym.type_id)
9435 			continue;
9436 
9437 		if (obj->gen_loader) {
9438 			ext->is_set = true;
9439 			ext->ksym.kernel_btf_obj_fd = 0;
9440 			ext->ksym.kernel_btf_id = 0;
9441 			continue;
9442 		}
9443 		t = btf__type_by_id(obj->btf, ext->btf_id);
9444 		if (btf_is_var(t))
9445 			err = bpf_object__resolve_ksym_var_btf_id(obj, ext);
9446 		else
9447 			err = bpf_object__resolve_ksym_func_btf_id(obj, ext);
9448 		if (err)
9449 			return err;
9450 	}
9451 	return 0;
9452 }
9453 
9454 static int bpf_object__resolve_externs(struct bpf_object *obj,
9455 				       const char *extra_kconfig)
9456 {
9457 	bool need_config = false, need_kallsyms = false;
9458 	bool need_vmlinux_btf = false;
9459 	struct extern_desc *ext;
9460 	void *kcfg_data = NULL;
9461 	int err, i;
9462 
9463 	if (obj->nr_extern == 0)
9464 		return 0;
9465 
9466 	if (obj->kconfig_map_idx >= 0)
9467 		kcfg_data = obj->maps[obj->kconfig_map_idx].mmaped;
9468 
9469 	for (i = 0; i < obj->nr_extern; i++) {
9470 		ext = &obj->externs[i];
9471 
9472 		if (ext->type == EXT_KSYM) {
9473 			if (ext->ksym.type_id)
9474 				need_vmlinux_btf = true;
9475 			else
9476 				need_kallsyms = true;
9477 			continue;
9478 		} else if (ext->type == EXT_KCFG) {
9479 			void *ext_ptr = kcfg_data + ext->kcfg.data_off;
9480 			__u64 value = 0;
9481 
9482 			/* Kconfig externs need actual /proc/config.gz */
9483 			if (str_has_pfx(ext->name, "CONFIG_")) {
9484 				need_config = true;
9485 				continue;
9486 			}
9487 
9488 			/* Virtual kcfg externs are customly handled by libbpf */
9489 			if (strcmp(ext->name, "LINUX_KERNEL_VERSION") == 0) {
9490 				value = get_kernel_version();
9491 				if (!value) {
9492 					pr_warn("extern (kcfg) '%s': failed to get kernel version\n", ext->name);
9493 					return -EINVAL;
9494 				}
9495 			} else if (strcmp(ext->name, "LINUX_HAS_BPF_COOKIE") == 0) {
9496 				value = kernel_supports(obj, FEAT_BPF_COOKIE);
9497 			} else if (strcmp(ext->name, "LINUX_HAS_SYSCALL_WRAPPER") == 0) {
9498 				value = kernel_supports(obj, FEAT_SYSCALL_WRAPPER);
9499 			} else if (!str_has_pfx(ext->name, "LINUX_") || !ext->is_weak) {
9500 				/* Currently libbpf supports only CONFIG_ and LINUX_ prefixed
9501 				 * __kconfig externs, where LINUX_ ones are virtual and filled out
9502 				 * customly by libbpf (their values don't come from Kconfig).
9503 				 * If LINUX_xxx variable is not recognized by libbpf, but is marked
9504 				 * __weak, it defaults to zero value, just like for CONFIG_xxx
9505 				 * externs.
9506 				 */
9507 				pr_warn("extern (kcfg) '%s': unrecognized virtual extern\n", ext->name);
9508 				return -EINVAL;
9509 			}
9510 
9511 			err = set_kcfg_value_num(ext, ext_ptr, value);
9512 			if (err)
9513 				return err;
9514 			pr_debug("extern (kcfg) '%s': set to 0x%llx\n",
9515 				 ext->name, (unsigned long long)value);
9516 		} else {
9517 			pr_warn("extern '%s': unrecognized extern kind\n", ext->name);
9518 			return -EINVAL;
9519 		}
9520 	}
9521 	if (need_config && extra_kconfig) {
9522 		err = bpf_object__read_kconfig_mem(obj, extra_kconfig, kcfg_data);
9523 		if (err)
9524 			return -EINVAL;
9525 		need_config = false;
9526 		for (i = 0; i < obj->nr_extern; i++) {
9527 			ext = &obj->externs[i];
9528 			if (ext->type == EXT_KCFG && !ext->is_set) {
9529 				need_config = true;
9530 				break;
9531 			}
9532 		}
9533 	}
9534 	if (need_config) {
9535 		err = bpf_object__read_kconfig_file(obj, kcfg_data);
9536 		if (err)
9537 			return -EINVAL;
9538 	}
9539 	if (need_kallsyms) {
9540 		err = bpf_object__read_kallsyms_file(obj);
9541 		if (err)
9542 			return -EINVAL;
9543 	}
9544 	if (need_vmlinux_btf) {
9545 		err = bpf_object__resolve_ksyms_btf_id(obj);
9546 		if (err)
9547 			return -EINVAL;
9548 	}
9549 	for (i = 0; i < obj->nr_extern; i++) {
9550 		ext = &obj->externs[i];
9551 
9552 		if (!ext->is_set && !ext->is_weak) {
9553 			pr_warn("extern '%s' (strong): not resolved\n", ext->name);
9554 			return -ESRCH;
9555 		} else if (!ext->is_set) {
9556 			pr_debug("extern '%s' (weak): not resolved, defaulting to zero\n",
9557 				 ext->name);
9558 		}
9559 	}
9560 
9561 	return 0;
9562 }
9563 
9564 static void bpf_map_prepare_vdata(const struct bpf_map *map)
9565 {
9566 	const struct btf_type *type;
9567 	struct bpf_struct_ops *st_ops;
9568 	__u32 i;
9569 
9570 	st_ops = map->st_ops;
9571 	type = btf__type_by_id(map->obj->btf, st_ops->type_id);
9572 	for (i = 0; i < btf_vlen(type); i++) {
9573 		struct bpf_program *prog = st_ops->progs[i];
9574 		void *kern_data;
9575 		int prog_fd;
9576 
9577 		if (!prog)
9578 			continue;
9579 
9580 		prog_fd = bpf_program__fd(prog);
9581 		kern_data = st_ops->kern_vdata + st_ops->kern_func_off[i];
9582 		*(unsigned long *)kern_data = prog_fd;
9583 	}
9584 }
9585 
9586 static int bpf_object_prepare_struct_ops(struct bpf_object *obj)
9587 {
9588 	struct bpf_map *map;
9589 	int i;
9590 
9591 	for (i = 0; i < obj->nr_maps; i++) {
9592 		map = &obj->maps[i];
9593 
9594 		if (!bpf_map__is_struct_ops(map))
9595 			continue;
9596 
9597 		if (!map->autocreate)
9598 			continue;
9599 
9600 		bpf_map_prepare_vdata(map);
9601 	}
9602 
9603 	return 0;
9604 }
9605 
9606 static void bpf_object_unpin(struct bpf_object *obj)
9607 {
9608 	int i;
9609 
9610 	/* unpin any maps that were auto-pinned during load */
9611 	for (i = 0; i < obj->nr_maps; i++)
9612 		if (obj->maps[i].pinned && !obj->maps[i].reused)
9613 			bpf_map__unpin(&obj->maps[i], NULL);
9614 }
9615 
9616 static void bpf_object_cleanup_btf(struct bpf_object *obj)
9617 {
9618 	int i;
9619 
9620 	/* clean up module BTFs */
9621 	for (i = 0; i < obj->btf_module_cnt; i++) {
9622 		close(obj->btf_modules[i].fd);
9623 		btf__free(obj->btf_modules[i].btf);
9624 		free(obj->btf_modules[i].name);
9625 	}
9626 	obj->btf_module_cnt = 0;
9627 	obj->btf_module_cap = 0;
9628 	obj->btf_modules_loaded = false;
9629 	zfree(&obj->btf_modules);
9630 
9631 	/* clean up vmlinux BTF */
9632 	btf__free(obj->btf_vmlinux);
9633 	obj->btf_vmlinux = NULL;
9634 }
9635 
9636 static void bpf_object_post_load_cleanup(struct bpf_object *obj)
9637 {
9638 	/* clean up fd_array, and the slots handed out with it */
9639 	zfree(&obj->fd_array);
9640 	obj->fd_array_cap = 0;
9641 	obj->fd_array_used = 0;
9642 
9643 	/* clean up BTF */
9644 	bpf_object_cleanup_btf(obj);
9645 }
9646 
9647 static int bpf_object_prepare(struct bpf_object *obj, const char *target_btf_path)
9648 {
9649 	int err;
9650 
9651 	if (obj->state >= OBJ_PREPARED) {
9652 		pr_warn("object '%s': prepare loading can't be attempted twice\n", obj->name);
9653 		return -EINVAL;
9654 	}
9655 
9656 	err = bpf_object_prepare_token(obj);
9657 	err = err ? : bpf_object__probe_loading(obj);
9658 	err = err ? : bpf_object__load_vmlinux_btf(obj, false);
9659 	err = err ? : bpf_object__resolve_externs(obj, obj->kconfig);
9660 	err = err ? : bpf_object__sanitize_maps(obj);
9661 	err = err ? : bpf_object__init_kern_struct_ops_maps(obj);
9662 	err = err ? : bpf_object_adjust_struct_ops_autoload(obj);
9663 	err = err ? : bpf_object__relocate(obj, obj->btf_custom_path ? : target_btf_path);
9664 	err = err ? : bpf_object__sanitize_and_load_btf(obj);
9665 	err = err ? : bpf_object__create_maps(obj);
9666 	err = err ? : bpf_object_prepare_progs(obj);
9667 
9668 	if (err) {
9669 		bpf_object_unpin(obj);
9670 		bpf_object_unload(obj);
9671 		obj->state = OBJ_LOADED;
9672 		return err;
9673 	}
9674 
9675 	obj->state = OBJ_PREPARED;
9676 	return 0;
9677 }
9678 
9679 static int bpf_object_load(struct bpf_object *obj, int extra_log_level, const char *target_btf_path)
9680 {
9681 	int err;
9682 
9683 	if (!obj)
9684 		return libbpf_err(-EINVAL);
9685 
9686 	if (obj->state >= OBJ_LOADED) {
9687 		pr_warn("object '%s': load can't be attempted twice\n", obj->name);
9688 		return libbpf_err(-EINVAL);
9689 	}
9690 
9691 	/* Disallow kernel loading programs of non-native endianness but
9692 	 * permit cross-endian creation of "light skeleton".
9693 	 */
9694 	if (obj->gen_loader) {
9695 		int nr_func_ptr_maps = 0, nr_progs = 0, i;
9696 		bool text_has_callx = false;
9697 
9698 		/*
9699 		 * Every program that has callx may get a copy of every map with
9700 		 * pointers to functions. Which functions a program calls is not
9701 		 * known yet. Any of them may call the ones that have callx.
9702 		 */
9703 		for (i = 0; i < obj->nr_maps; i++)
9704 			if (obj->maps[i].autocreate && obj->maps[i].func_ptr_cnt)
9705 				nr_func_ptr_maps++;
9706 		for (i = 0; i < obj->nr_programs; i++)
9707 			if (prog_is_subprog(obj, &obj->programs[i]) &&
9708 			    prog_has_callx(&obj->programs[i]))
9709 				text_has_callx = true;
9710 		for (i = 0; i < obj->nr_programs; i++)
9711 			if (obj->programs[i].autoload && !prog_is_subprog(obj, &obj->programs[i]) &&
9712 			    (text_has_callx || prog_has_callx(&obj->programs[i])))
9713 				nr_progs++;
9714 		bpf_gen__init(obj->gen_loader, obj->log_level | extra_log_level,
9715 			      obj->nr_programs, obj->nr_maps, nr_func_ptr_maps * nr_progs);
9716 	} else if (!is_native_endianness(obj)) {
9717 		pr_warn("object '%s': loading non-native endianness is unsupported\n", obj->name);
9718 		return libbpf_err(-LIBBPF_ERRNO__ENDIAN);
9719 	}
9720 
9721 	if (obj->state < OBJ_PREPARED) {
9722 		err = bpf_object_prepare(obj, target_btf_path);
9723 		if (err)
9724 			return libbpf_err(err);
9725 	}
9726 	err = bpf_object__load_progs(obj, extra_log_level);
9727 	err = err ? : bpf_object_init_prog_arrays(obj);
9728 	err = err ? : bpf_object_prepare_struct_ops(obj);
9729 
9730 	if (obj->gen_loader) {
9731 		/* reset FDs */
9732 		if (obj->btf)
9733 			btf__set_fd(obj->btf, -1);
9734 		if (!err)
9735 			err = bpf_gen__finish(obj->gen_loader, obj->nr_programs, obj->nr_maps);
9736 	}
9737 
9738 	bpf_object_post_load_cleanup(obj);
9739 	obj->state = OBJ_LOADED; /* doesn't matter if successfully or not */
9740 
9741 	if (err) {
9742 		bpf_object_unpin(obj);
9743 		bpf_object_unload(obj);
9744 		pr_warn("failed to load object '%s'\n", obj->path);
9745 		return libbpf_err(err);
9746 	}
9747 
9748 	return 0;
9749 }
9750 
9751 int bpf_object__prepare(struct bpf_object *obj)
9752 {
9753 	return libbpf_err(bpf_object_prepare(obj, NULL));
9754 }
9755 
9756 int bpf_object__load(struct bpf_object *obj)
9757 {
9758 	return bpf_object_load(obj, 0, NULL);
9759 }
9760 
9761 static int make_parent_dir(const char *path)
9762 {
9763 	char *dname, *dir;
9764 	int err = 0;
9765 
9766 	dname = strdup(path);
9767 	if (dname == NULL)
9768 		return -ENOMEM;
9769 
9770 	dir = dirname(dname);
9771 	if (mkdir(dir, 0700) && errno != EEXIST)
9772 		err = -errno;
9773 
9774 	free(dname);
9775 	if (err) {
9776 		pr_warn("failed to mkdir %s: %s\n", path, errstr(err));
9777 	}
9778 	return err;
9779 }
9780 
9781 static int check_path(const char *path)
9782 {
9783 	struct statfs st_fs;
9784 	char *dname, *dir;
9785 	int err = 0;
9786 
9787 	if (path == NULL)
9788 		return -EINVAL;
9789 
9790 	dname = strdup(path);
9791 	if (dname == NULL)
9792 		return -ENOMEM;
9793 
9794 	dir = dirname(dname);
9795 	if (statfs(dir, &st_fs)) {
9796 		pr_warn("failed to statfs %s: %s\n", dir, errstr(errno));
9797 		err = -errno;
9798 	}
9799 	free(dname);
9800 
9801 	if (!err && st_fs.f_type != BPF_FS_MAGIC) {
9802 		pr_warn("specified path %s is not on BPF FS\n", path);
9803 		err = -EINVAL;
9804 	}
9805 
9806 	return err;
9807 }
9808 
9809 int bpf_program__pin(struct bpf_program *prog, const char *path)
9810 {
9811 	int err;
9812 
9813 	if (prog->fd < 0) {
9814 		pr_warn("prog '%s': can't pin program that wasn't loaded\n", prog->name);
9815 		return libbpf_err(-EINVAL);
9816 	}
9817 
9818 	err = make_parent_dir(path);
9819 	if (err)
9820 		return libbpf_err(err);
9821 
9822 	err = check_path(path);
9823 	if (err)
9824 		return libbpf_err(err);
9825 
9826 	if (bpf_obj_pin(prog->fd, path)) {
9827 		err = -errno;
9828 		pr_warn("prog '%s': failed to pin at '%s': %s\n", prog->name, path, errstr(err));
9829 		return libbpf_err(err);
9830 	}
9831 
9832 	pr_debug("prog '%s': pinned at '%s'\n", prog->name, path);
9833 	return 0;
9834 }
9835 
9836 int bpf_program__unpin(struct bpf_program *prog, const char *path)
9837 {
9838 	int err;
9839 
9840 	if (prog->fd < 0) {
9841 		pr_warn("prog '%s': can't unpin program that wasn't loaded\n", prog->name);
9842 		return libbpf_err(-EINVAL);
9843 	}
9844 
9845 	err = check_path(path);
9846 	if (err)
9847 		return libbpf_err(err);
9848 
9849 	err = unlink(path);
9850 	if (err)
9851 		return libbpf_err(-errno);
9852 
9853 	pr_debug("prog '%s': unpinned from '%s'\n", prog->name, path);
9854 	return 0;
9855 }
9856 
9857 int bpf_map__pin(struct bpf_map *map, const char *path)
9858 {
9859 	int err;
9860 
9861 	if (map == NULL) {
9862 		pr_warn("invalid map pointer\n");
9863 		return libbpf_err(-EINVAL);
9864 	}
9865 
9866 	if (map->fd < 0) {
9867 		pr_warn("map '%s': can't pin BPF map without FD (was it created?)\n", map->name);
9868 		return libbpf_err(-EINVAL);
9869 	}
9870 
9871 	if (map->pin_path) {
9872 		if (path && strcmp(path, map->pin_path)) {
9873 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
9874 				bpf_map__name(map), map->pin_path, path);
9875 			return libbpf_err(-EINVAL);
9876 		} else if (map->pinned) {
9877 			pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
9878 				 bpf_map__name(map), map->pin_path);
9879 			return 0;
9880 		}
9881 	} else {
9882 		if (!path) {
9883 			pr_warn("missing a path to pin map '%s' at\n",
9884 				bpf_map__name(map));
9885 			return libbpf_err(-EINVAL);
9886 		} else if (map->pinned) {
9887 			pr_warn("map '%s' already pinned\n", bpf_map__name(map));
9888 			return libbpf_err(-EEXIST);
9889 		}
9890 
9891 		map->pin_path = strdup(path);
9892 		if (!map->pin_path) {
9893 			err = -errno;
9894 			goto out_err;
9895 		}
9896 	}
9897 
9898 	err = make_parent_dir(map->pin_path);
9899 	if (err)
9900 		return libbpf_err(err);
9901 
9902 	err = check_path(map->pin_path);
9903 	if (err)
9904 		return libbpf_err(err);
9905 
9906 	if (bpf_obj_pin(map->fd, map->pin_path)) {
9907 		err = -errno;
9908 		goto out_err;
9909 	}
9910 
9911 	map->pinned = true;
9912 	pr_debug("pinned map '%s'\n", map->pin_path);
9913 
9914 	return 0;
9915 
9916 out_err:
9917 	pr_warn("failed to pin map: %s\n", errstr(err));
9918 	return libbpf_err(err);
9919 }
9920 
9921 int bpf_map__unpin(struct bpf_map *map, const char *path)
9922 {
9923 	int err;
9924 
9925 	if (map == NULL) {
9926 		pr_warn("invalid map pointer\n");
9927 		return libbpf_err(-EINVAL);
9928 	}
9929 
9930 	if (map->pin_path) {
9931 		if (path && strcmp(path, map->pin_path)) {
9932 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
9933 				bpf_map__name(map), map->pin_path, path);
9934 			return libbpf_err(-EINVAL);
9935 		}
9936 		path = map->pin_path;
9937 	} else if (!path) {
9938 		pr_warn("no path to unpin map '%s' from\n",
9939 			bpf_map__name(map));
9940 		return libbpf_err(-EINVAL);
9941 	}
9942 
9943 	err = check_path(path);
9944 	if (err)
9945 		return libbpf_err(err);
9946 
9947 	err = unlink(path);
9948 	if (err != 0)
9949 		return libbpf_err(-errno);
9950 
9951 	map->pinned = false;
9952 	pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path);
9953 
9954 	return 0;
9955 }
9956 
9957 int bpf_map__set_pin_path(struct bpf_map *map, const char *path)
9958 {
9959 	char *new = NULL;
9960 
9961 	if (path) {
9962 		new = strdup(path);
9963 		if (!new)
9964 			return libbpf_err(-errno);
9965 	}
9966 
9967 	free(map->pin_path);
9968 	map->pin_path = new;
9969 	return 0;
9970 }
9971 
9972 __alias(bpf_map__pin_path)
9973 const char *bpf_map__get_pin_path(const struct bpf_map *map);
9974 
9975 const char *bpf_map__pin_path(const struct bpf_map *map)
9976 {
9977 	return map->pin_path;
9978 }
9979 
9980 bool bpf_map__is_pinned(const struct bpf_map *map)
9981 {
9982 	return map->pinned;
9983 }
9984 
9985 static void sanitize_pin_path(char *s)
9986 {
9987 	/* bpffs disallows periods in path names */
9988 	while (*s) {
9989 		if (*s == '.')
9990 			*s = '_';
9991 		s++;
9992 	}
9993 }
9994 
9995 int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
9996 {
9997 	struct bpf_map *map;
9998 	int err;
9999 
10000 	if (!obj)
10001 		return libbpf_err(-ENOENT);
10002 
10003 	if (obj->state < OBJ_PREPARED) {
10004 		pr_warn("object not yet loaded; load it first\n");
10005 		return libbpf_err(-ENOENT);
10006 	}
10007 
10008 	bpf_object__for_each_map(map, obj) {
10009 		char *pin_path = NULL;
10010 		char buf[PATH_MAX];
10011 
10012 		if (!map->autocreate)
10013 			continue;
10014 
10015 		if (path) {
10016 			err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
10017 			if (err)
10018 				goto err_unpin_maps;
10019 			sanitize_pin_path(buf);
10020 			pin_path = buf;
10021 		} else if (!map->pin_path) {
10022 			continue;
10023 		}
10024 
10025 		err = bpf_map__pin(map, pin_path);
10026 		if (err)
10027 			goto err_unpin_maps;
10028 	}
10029 
10030 	return 0;
10031 
10032 err_unpin_maps:
10033 	while ((map = bpf_object__prev_map(obj, map))) {
10034 		if (!map->pin_path)
10035 			continue;
10036 
10037 		bpf_map__unpin(map, NULL);
10038 	}
10039 
10040 	return libbpf_err(err);
10041 }
10042 
10043 int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
10044 {
10045 	struct bpf_map *map;
10046 	int err;
10047 
10048 	if (!obj)
10049 		return libbpf_err(-ENOENT);
10050 
10051 	bpf_object__for_each_map(map, obj) {
10052 		char *pin_path = NULL;
10053 		char buf[PATH_MAX];
10054 
10055 		if (path) {
10056 			err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
10057 			if (err)
10058 				return libbpf_err(err);
10059 			sanitize_pin_path(buf);
10060 			pin_path = buf;
10061 		} else if (!map->pin_path) {
10062 			continue;
10063 		}
10064 
10065 		err = bpf_map__unpin(map, pin_path);
10066 		if (err)
10067 			return libbpf_err(err);
10068 	}
10069 
10070 	return 0;
10071 }
10072 
10073 int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
10074 {
10075 	struct bpf_program *prog;
10076 	char buf[PATH_MAX];
10077 	int err;
10078 
10079 	if (!obj)
10080 		return libbpf_err(-ENOENT);
10081 
10082 	if (obj->state < OBJ_LOADED) {
10083 		pr_warn("object not yet loaded; load it first\n");
10084 		return libbpf_err(-ENOENT);
10085 	}
10086 
10087 	bpf_object__for_each_program(prog, obj) {
10088 		err = pathname_concat(buf, sizeof(buf), path, prog->name);
10089 		if (err)
10090 			goto err_unpin_programs;
10091 
10092 		err = bpf_program__pin(prog, buf);
10093 		if (err)
10094 			goto err_unpin_programs;
10095 	}
10096 
10097 	return 0;
10098 
10099 err_unpin_programs:
10100 	while ((prog = bpf_object__prev_program(obj, prog))) {
10101 		if (pathname_concat(buf, sizeof(buf), path, prog->name))
10102 			continue;
10103 
10104 		bpf_program__unpin(prog, buf);
10105 	}
10106 
10107 	return libbpf_err(err);
10108 }
10109 
10110 int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
10111 {
10112 	struct bpf_program *prog;
10113 	int err;
10114 
10115 	if (!obj)
10116 		return libbpf_err(-ENOENT);
10117 
10118 	bpf_object__for_each_program(prog, obj) {
10119 		char buf[PATH_MAX];
10120 
10121 		err = pathname_concat(buf, sizeof(buf), path, prog->name);
10122 		if (err)
10123 			return libbpf_err(err);
10124 
10125 		err = bpf_program__unpin(prog, buf);
10126 		if (err)
10127 			return libbpf_err(err);
10128 	}
10129 
10130 	return 0;
10131 }
10132 
10133 int bpf_object__pin(struct bpf_object *obj, const char *path)
10134 {
10135 	int err;
10136 
10137 	err = bpf_object__pin_maps(obj, path);
10138 	if (err)
10139 		return libbpf_err(err);
10140 
10141 	err = bpf_object__pin_programs(obj, path);
10142 	if (err) {
10143 		bpf_object__unpin_maps(obj, path);
10144 		return libbpf_err(err);
10145 	}
10146 
10147 	return 0;
10148 }
10149 
10150 int bpf_object__unpin(struct bpf_object *obj, const char *path)
10151 {
10152 	int err;
10153 
10154 	err = bpf_object__unpin_programs(obj, path);
10155 	if (err)
10156 		return libbpf_err(err);
10157 
10158 	err = bpf_object__unpin_maps(obj, path);
10159 	if (err)
10160 		return libbpf_err(err);
10161 
10162 	return 0;
10163 }
10164 
10165 static void bpf_map__destroy(struct bpf_map *map)
10166 {
10167 	if (map->inner_map) {
10168 		bpf_map__destroy(map->inner_map);
10169 		zfree(&map->inner_map);
10170 	}
10171 
10172 	zfree(&map->init_slots);
10173 	map->init_slots_sz = 0;
10174 
10175 	if (map->mmaped && map->mmaped != map->obj->arena_data)
10176 		munmap(map->mmaped, bpf_map_mmap_sz(map));
10177 	map->mmaped = NULL;
10178 
10179 	if (map->st_ops) {
10180 		zfree(&map->st_ops->data);
10181 		zfree(&map->st_ops->progs);
10182 		zfree(&map->st_ops->kern_func_off);
10183 		zfree(&map->st_ops);
10184 	}
10185 
10186 	zfree(&map->name);
10187 	zfree(&map->real_name);
10188 	zfree(&map->pin_path);
10189 
10190 	if (map->fd >= 0)
10191 		zclose(map->fd);
10192 }
10193 
10194 void bpf_object__close(struct bpf_object *obj)
10195 {
10196 	size_t i;
10197 
10198 	if (IS_ERR_OR_NULL(obj))
10199 		return;
10200 
10201 	/*
10202 	 * if user called bpf_object__prepare() without ever getting to
10203 	 * bpf_object__load(), we need to clean up stuff that is normally
10204 	 * cleaned up at the end of loading step
10205 	 */
10206 	bpf_object_post_load_cleanup(obj);
10207 
10208 	usdt_manager_free(obj->usdt_man);
10209 	obj->usdt_man = NULL;
10210 
10211 	bpf_gen__free(obj->gen_loader);
10212 	bpf_object__elf_finish(obj);
10213 	bpf_object_unload(obj);
10214 	btf__free(obj->btf);
10215 	btf__free(obj->btf_vmlinux);
10216 	btf_ext__free(obj->btf_ext);
10217 
10218 	for (i = 0; i < obj->nr_maps; i++)
10219 		bpf_map__destroy(&obj->maps[i]);
10220 
10221 	zfree(&obj->btf_custom_path);
10222 	zfree(&obj->kconfig);
10223 
10224 	for (i = 0; i < obj->nr_extern; i++) {
10225 		zfree(&obj->externs[i].name);
10226 		zfree(&obj->externs[i].essent_name);
10227 	}
10228 
10229 	zfree(&obj->externs);
10230 	obj->nr_extern = 0;
10231 
10232 	zfree(&obj->maps);
10233 	obj->nr_maps = 0;
10234 
10235 	if (obj->programs && obj->nr_programs) {
10236 		for (i = 0; i < obj->nr_programs; i++)
10237 			bpf_program__exit(&obj->programs[i]);
10238 	}
10239 	zfree(&obj->programs);
10240 
10241 	zfree(&obj->feat_cache);
10242 	zfree(&obj->token_path);
10243 	if (obj->token_fd > 0)
10244 		close(obj->token_fd);
10245 
10246 	zfree(&obj->arena_data);
10247 
10248 	zfree(&obj->jumptables_data);
10249 	obj->jumptables_data_sz = 0;
10250 
10251 	for (i = 0; i < obj->jumptable_map_cnt; i++)
10252 		close(obj->jumptable_maps[i].fd);
10253 	zfree(&obj->jumptable_maps);
10254 
10255 	for (i = 0; i < obj->func_ptr_map_cnt; i++)
10256 		if (!obj->gen_loader)
10257 			close(obj->func_ptr_maps[i].fd);
10258 	zfree(&obj->func_ptr_maps);
10259 	zfree(&obj->func_ptrs);
10260 
10261 	if (obj->btf_module_allowlist) {
10262 		for (i = 0; i < obj->btf_module_allowlist_cnt; i++)
10263 			zfree(&obj->btf_module_allowlist[i]);
10264 		zfree(&obj->btf_module_allowlist);
10265 	}
10266 
10267 	free(obj);
10268 }
10269 
10270 const char *bpf_object__name(const struct bpf_object *obj)
10271 {
10272 	return obj ? obj->name : libbpf_err_ptr(-EINVAL);
10273 }
10274 
10275 unsigned int bpf_object__kversion(const struct bpf_object *obj)
10276 {
10277 	return obj ? obj->kern_version : 0;
10278 }
10279 
10280 int bpf_object__token_fd(const struct bpf_object *obj)
10281 {
10282 	return obj->token_fd ?: -1;
10283 }
10284 
10285 struct btf *bpf_object__btf(const struct bpf_object *obj)
10286 {
10287 	return obj ? obj->btf : NULL;
10288 }
10289 
10290 int bpf_object__btf_fd(const struct bpf_object *obj)
10291 {
10292 	return obj->btf ? btf__fd(obj->btf) : -1;
10293 }
10294 
10295 int bpf_object__set_kversion(struct bpf_object *obj, __u32 kern_version)
10296 {
10297 	if (obj->state >= OBJ_LOADED)
10298 		return libbpf_err(-EINVAL);
10299 
10300 	obj->kern_version = kern_version;
10301 
10302 	return 0;
10303 }
10304 
10305 int bpf_object__gen_loader(struct bpf_object *obj, struct gen_loader_opts *opts)
10306 {
10307 	struct bpf_gen *gen;
10308 
10309 	if (!opts)
10310 		return libbpf_err(-EFAULT);
10311 	if (!OPTS_VALID(opts, gen_loader_opts))
10312 		return libbpf_err(-EINVAL);
10313 	gen = calloc(1, sizeof(*gen));
10314 	if (!gen)
10315 		return libbpf_err(-ENOMEM);
10316 	gen->opts = opts;
10317 	gen->swapped_endian = !is_native_endianness(obj);
10318 	obj->gen_loader = gen;
10319 	return 0;
10320 }
10321 
10322 static struct bpf_program *
10323 __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
10324 		    bool forward)
10325 {
10326 	size_t nr_programs = obj->nr_programs;
10327 	ssize_t idx;
10328 
10329 	if (!nr_programs)
10330 		return NULL;
10331 
10332 	if (!p)
10333 		/* Iter from the beginning */
10334 		return forward ? &obj->programs[0] :
10335 			&obj->programs[nr_programs - 1];
10336 
10337 	if (p->obj != obj) {
10338 		pr_warn("error: program handler doesn't match object\n");
10339 		return errno = EINVAL, NULL;
10340 	}
10341 
10342 	idx = (p - obj->programs) + (forward ? 1 : -1);
10343 	if (idx >= obj->nr_programs || idx < 0)
10344 		return NULL;
10345 	return &obj->programs[idx];
10346 }
10347 
10348 struct bpf_program *
10349 bpf_object__next_program(const struct bpf_object *obj, struct bpf_program *prev)
10350 {
10351 	struct bpf_program *prog = prev;
10352 
10353 	do {
10354 		prog = __bpf_program__iter(prog, obj, true);
10355 	} while (prog && prog_is_subprog(obj, prog));
10356 
10357 	return prog;
10358 }
10359 
10360 struct bpf_program *
10361 bpf_object__prev_program(const struct bpf_object *obj, struct bpf_program *next)
10362 {
10363 	struct bpf_program *prog = next;
10364 
10365 	do {
10366 		prog = __bpf_program__iter(prog, obj, false);
10367 	} while (prog && prog_is_subprog(obj, prog));
10368 
10369 	return prog;
10370 }
10371 
10372 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
10373 {
10374 	prog->prog_ifindex = ifindex;
10375 }
10376 
10377 const char *bpf_program__name(const struct bpf_program *prog)
10378 {
10379 	return prog->name;
10380 }
10381 
10382 const char *bpf_program__section_name(const struct bpf_program *prog)
10383 {
10384 	return prog->sec_name;
10385 }
10386 
10387 bool bpf_program__autoload(const struct bpf_program *prog)
10388 {
10389 	return prog->autoload;
10390 }
10391 
10392 int bpf_program__set_autoload(struct bpf_program *prog, bool autoload)
10393 {
10394 	if (prog->obj->state >= OBJ_LOADED)
10395 		return libbpf_err(-EINVAL);
10396 
10397 	prog->autoload = autoload;
10398 	return 0;
10399 }
10400 
10401 bool bpf_program__autoattach(const struct bpf_program *prog)
10402 {
10403 	return prog->autoattach;
10404 }
10405 
10406 void bpf_program__set_autoattach(struct bpf_program *prog, bool autoattach)
10407 {
10408 	prog->autoattach = autoattach;
10409 }
10410 
10411 const struct bpf_insn *bpf_program__insns(const struct bpf_program *prog)
10412 {
10413 	return prog->insns;
10414 }
10415 
10416 size_t bpf_program__insn_cnt(const struct bpf_program *prog)
10417 {
10418 	return prog->insns_cnt;
10419 }
10420 
10421 int bpf_program__set_insns(struct bpf_program *prog,
10422 			   struct bpf_insn *new_insns, size_t new_insn_cnt)
10423 {
10424 	struct bpf_insn *insns;
10425 
10426 	if (prog->obj->state >= OBJ_LOADED)
10427 		return libbpf_err(-EBUSY);
10428 
10429 	insns = libbpf_reallocarray(prog->insns, new_insn_cnt, sizeof(*insns));
10430 	/* NULL is a valid return from reallocarray if the new count is zero */
10431 	if (!insns && new_insn_cnt) {
10432 		pr_warn("prog '%s': failed to realloc prog code\n", prog->name);
10433 		return libbpf_err(-ENOMEM);
10434 	}
10435 	memcpy(insns, new_insns, new_insn_cnt * sizeof(*insns));
10436 
10437 	prog->insns = insns;
10438 	prog->insns_cnt = new_insn_cnt;
10439 	return 0;
10440 }
10441 
10442 int bpf_program__fd(const struct bpf_program *prog)
10443 {
10444 	if (!prog)
10445 		return libbpf_err(-EINVAL);
10446 
10447 	if (prog->fd < 0)
10448 		return libbpf_err(-ENOENT);
10449 
10450 	return prog->fd;
10451 }
10452 
10453 __alias(bpf_program__type)
10454 enum bpf_prog_type bpf_program__get_type(const struct bpf_program *prog);
10455 
10456 enum bpf_prog_type bpf_program__type(const struct bpf_program *prog)
10457 {
10458 	return prog->type;
10459 }
10460 
10461 static size_t custom_sec_def_cnt;
10462 static struct bpf_sec_def *custom_sec_defs;
10463 static struct bpf_sec_def custom_fallback_def;
10464 static bool has_custom_fallback_def;
10465 static int last_custom_sec_def_handler_id;
10466 
10467 int bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
10468 {
10469 	if (prog->obj->state >= OBJ_LOADED)
10470 		return libbpf_err(-EBUSY);
10471 
10472 	/* if type is not changed, do nothing */
10473 	if (prog->type == type)
10474 		return 0;
10475 
10476 	prog->type = type;
10477 
10478 	/* If a program type was changed, we need to reset associated SEC()
10479 	 * handler, as it will be invalid now. The only exception is a generic
10480 	 * fallback handler, which by definition is program type-agnostic and
10481 	 * is a catch-all custom handler, optionally set by the application,
10482 	 * so should be able to handle any type of BPF program.
10483 	 */
10484 	if (prog->sec_def != &custom_fallback_def)
10485 		prog->sec_def = NULL;
10486 	return 0;
10487 }
10488 
10489 __alias(bpf_program__expected_attach_type)
10490 enum bpf_attach_type bpf_program__get_expected_attach_type(const struct bpf_program *prog);
10491 
10492 enum bpf_attach_type bpf_program__expected_attach_type(const struct bpf_program *prog)
10493 {
10494 	return prog->expected_attach_type;
10495 }
10496 
10497 int bpf_program__set_expected_attach_type(struct bpf_program *prog,
10498 					   enum bpf_attach_type type)
10499 {
10500 	if (prog->obj->state >= OBJ_LOADED)
10501 		return libbpf_err(-EBUSY);
10502 
10503 	prog->expected_attach_type = type;
10504 	return 0;
10505 }
10506 
10507 __u32 bpf_program__flags(const struct bpf_program *prog)
10508 {
10509 	return prog->prog_flags;
10510 }
10511 
10512 int bpf_program__set_flags(struct bpf_program *prog, __u32 flags)
10513 {
10514 	if (prog->obj->state >= OBJ_LOADED)
10515 		return libbpf_err(-EBUSY);
10516 
10517 	prog->prog_flags = flags;
10518 	return 0;
10519 }
10520 
10521 int bpf_program__add_flags(struct bpf_program *prog, __u32 flags)
10522 {
10523 	return bpf_program__set_flags(prog, prog->prog_flags | flags);
10524 }
10525 
10526 int bpf_program__clear_flags(struct bpf_program *prog, __u32 flags)
10527 {
10528 	return bpf_program__set_flags(prog, prog->prog_flags & ~flags);
10529 }
10530 
10531 __u32 bpf_program__log_level(const struct bpf_program *prog)
10532 {
10533 	return prog->log_level;
10534 }
10535 
10536 int bpf_program__set_log_level(struct bpf_program *prog, __u32 log_level)
10537 {
10538 	if (prog->obj->state >= OBJ_LOADED)
10539 		return libbpf_err(-EBUSY);
10540 
10541 	prog->log_level = log_level;
10542 	return 0;
10543 }
10544 
10545 const char *bpf_program__log_buf(const struct bpf_program *prog, size_t *log_size)
10546 {
10547 	*log_size = prog->log_size;
10548 	return prog->log_buf;
10549 }
10550 
10551 int bpf_program__set_log_buf(struct bpf_program *prog, char *log_buf, size_t log_size)
10552 {
10553 	if (!!log_buf != !!log_size)
10554 		return libbpf_err(-EINVAL);
10555 	if (log_size > UINT_MAX)
10556 		return libbpf_err(-EINVAL);
10557 	if (prog->obj->state >= OBJ_LOADED)
10558 		return libbpf_err(-EBUSY);
10559 
10560 	prog->log_buf = log_buf;
10561 	prog->log_size = log_size;
10562 	return 0;
10563 }
10564 
10565 struct bpf_func_info *bpf_program__func_info(const struct bpf_program *prog)
10566 {
10567 	if (prog->func_info_rec_size != sizeof(struct bpf_func_info))
10568 		return libbpf_err_ptr(-EOPNOTSUPP);
10569 	return prog->func_info;
10570 }
10571 
10572 __u32 bpf_program__func_info_cnt(const struct bpf_program *prog)
10573 {
10574 	return prog->func_info_cnt;
10575 }
10576 
10577 struct bpf_line_info *bpf_program__line_info(const struct bpf_program *prog)
10578 {
10579 	if (prog->line_info_rec_size != sizeof(struct bpf_line_info))
10580 		return libbpf_err_ptr(-EOPNOTSUPP);
10581 	return prog->line_info;
10582 }
10583 
10584 __u32 bpf_program__line_info_cnt(const struct bpf_program *prog)
10585 {
10586 	return prog->line_info_cnt;
10587 }
10588 
10589 int bpf_program__clone(struct bpf_program *prog, const struct bpf_prog_load_opts *opts)
10590 {
10591 	LIBBPF_OPTS(bpf_prog_load_opts, attr);
10592 	struct bpf_object *obj;
10593 	const void *info;
10594 	__u32 info_cnt, info_rec_size;
10595 	int err, fd, prog_btf_fd;
10596 
10597 	if (!prog)
10598 		return libbpf_err(-EINVAL);
10599 
10600 	if (!OPTS_VALID(opts, bpf_prog_load_opts))
10601 		return libbpf_err(-EINVAL);
10602 
10603 	obj = prog->obj;
10604 	if (obj->state < OBJ_PREPARED)
10605 		return libbpf_err(-EINVAL);
10606 
10607 	/*
10608 	 * Caller-provided opts take priority; fall back to
10609 	 * prog/object defaults when the caller leaves them zero.
10610 	 */
10611 	attr.attach_prog_fd = OPTS_GET(opts, attach_prog_fd, 0) ?: prog->attach_prog_fd;
10612 	attr.prog_flags = OPTS_GET(opts, prog_flags, 0) ?: prog->prog_flags;
10613 	attr.prog_ifindex = OPTS_GET(opts, prog_ifindex, 0) ?: prog->prog_ifindex;
10614 	attr.kern_version = OPTS_GET(opts, kern_version, 0) ?: obj->kern_version;
10615 	attr.fd_array = OPTS_GET(opts, fd_array, NULL) ?: obj->fd_array;
10616 	attr.fd_array_cnt = OPTS_GET(opts, fd_array_cnt, 0);
10617 	/* the arena of the object goes with the program, as in bpf_object__load() */
10618 	if (!OPTS_GET(opts, fd_array, NULL) && !OPTS_GET(opts, fd_array_cnt, 0)) {
10619 		err = bpf_object__bind_arena(obj, prog, &attr);
10620 		if (err)
10621 			return libbpf_err(err);
10622 	}
10623 	attr.token_fd = OPTS_GET(opts, token_fd, 0) ?: obj->token_fd;
10624 	if (attr.token_fd)
10625 		attr.prog_flags |= BPF_F_TOKEN_FD;
10626 
10627 	prog_btf_fd = OPTS_GET(opts, prog_btf_fd, 0);
10628 	if (!prog_btf_fd && obj->btf)
10629 		prog_btf_fd = btf__fd(obj->btf);
10630 
10631 	/* BTF func/line info: only pass if kernel supports it */
10632 	if (kernel_supports(obj, FEAT_BTF_FUNC) && prog_btf_fd > 0) {
10633 		attr.prog_btf_fd = prog_btf_fd;
10634 
10635 		/* func_info/line_info triples: all-or-nothing from caller */
10636 		info = OPTS_GET(opts, func_info, NULL);
10637 		info_cnt = OPTS_GET(opts, func_info_cnt, 0);
10638 		info_rec_size = OPTS_GET(opts, func_info_rec_size, 0);
10639 		if (!!info != !!info_cnt || !!info != !!info_rec_size) {
10640 			pr_warn("prog '%s': func_info, func_info_cnt, and func_info_rec_size must all be specified or all omitted\n",
10641 				prog->name);
10642 			return libbpf_err(-EINVAL);
10643 		}
10644 		attr.func_info = info ?: prog->func_info;
10645 		attr.func_info_cnt = info ? info_cnt : prog->func_info_cnt;
10646 		attr.func_info_rec_size = info ? info_rec_size : prog->func_info_rec_size;
10647 
10648 		info = OPTS_GET(opts, line_info, NULL);
10649 		info_cnt = OPTS_GET(opts, line_info_cnt, 0);
10650 		info_rec_size = OPTS_GET(opts, line_info_rec_size, 0);
10651 		if (!!info != !!info_cnt || !!info != !!info_rec_size) {
10652 			pr_warn("prog '%s': line_info, line_info_cnt, and line_info_rec_size must all be specified or all omitted\n",
10653 				prog->name);
10654 			return libbpf_err(-EINVAL);
10655 		}
10656 		attr.line_info = info ?: prog->line_info;
10657 		attr.line_info_cnt = info ? info_cnt : prog->line_info_cnt;
10658 		attr.line_info_rec_size = info ? info_rec_size : prog->line_info_rec_size;
10659 	}
10660 
10661 	/* Logging is caller-controlled; no fallback to prog/obj log settings */
10662 	attr.log_buf = OPTS_GET(opts, log_buf, NULL);
10663 	attr.log_size = OPTS_GET(opts, log_size, 0);
10664 	attr.log_level = OPTS_GET(opts, log_level, 0);
10665 
10666 	/*
10667 	 * Fields below may be mutated by prog_prepare_load_fn:
10668 	 * Seed them from prog/obj defaults here;
10669 	 * Later override with caller-provided opts.
10670 	 */
10671 	attr.expected_attach_type = prog->expected_attach_type;
10672 	attr.attach_btf_id = prog->attach_btf_id;
10673 	attr.attach_btf_obj_fd = prog->attach_btf_obj_fd;
10674 
10675 	if (prog->sec_def && prog->sec_def->prog_prepare_load_fn) {
10676 		err = prog->sec_def->prog_prepare_load_fn(prog, &attr, prog->sec_def->cookie);
10677 		if (err)
10678 			return libbpf_err(err);
10679 	}
10680 
10681 	/* Re-apply caller overrides for output fields */
10682 	if (OPTS_GET(opts, expected_attach_type, 0))
10683 		attr.expected_attach_type = OPTS_GET(opts, expected_attach_type, 0);
10684 	if (OPTS_GET(opts, attach_btf_id, 0))
10685 		attr.attach_btf_id = OPTS_GET(opts, attach_btf_id, 0);
10686 	if (OPTS_GET(opts, attach_btf_obj_fd, 0))
10687 		attr.attach_btf_obj_fd = OPTS_GET(opts, attach_btf_obj_fd, 0);
10688 
10689 	/*
10690 	 * Unlike bpf_object_load_prog(), we intentionally do not call bpf_prog_bind_map()
10691 	 * for RODATA maps here to avoid mutating the object's state. Callers can bind the
10692 	 * required maps themselves using bpf_prog_bind_map().
10693 	 */
10694 	fd = bpf_prog_load(prog->type, prog->name, obj->license, prog->insns, prog->insns_cnt,
10695 			   &attr);
10696 
10697 	return libbpf_err(fd);
10698 }
10699 
10700 #define SEC_DEF(sec_pfx, ptype, atype, flags, ...) {			    \
10701 	.sec = (char *)sec_pfx,						    \
10702 	.prog_type = BPF_PROG_TYPE_##ptype,				    \
10703 	.expected_attach_type = atype,					    \
10704 	.cookie = (long)(flags),					    \
10705 	.prog_setup_fn = libbpf_setup_prog_flags,			    \
10706 	.prog_prepare_load_fn = libbpf_prepare_prog_load,		    \
10707 	__VA_ARGS__							    \
10708 }
10709 
10710 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
10711 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
10712 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link);
10713 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link);
10714 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
10715 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
10716 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link);
10717 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
10718 static int attach_kprobe_session(const struct bpf_program *prog, long cookie, struct bpf_link **link);
10719 static int attach_uprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
10720 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link);
10721 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link);
10722 static int attach_tracing_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
10723 
10724 static const struct bpf_sec_def section_defs[] = {
10725 	SEC_DEF("socket",		SOCKET_FILTER, 0, SEC_NONE),
10726 	SEC_DEF("sk_reuseport/migrate",	SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT_OR_MIGRATE, SEC_ATTACHABLE),
10727 	SEC_DEF("sk_reuseport",		SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT, SEC_ATTACHABLE),
10728 	SEC_DEF("kprobe+",		KPROBE,	0, SEC_NONE, attach_kprobe),
10729 	SEC_DEF("uprobe+",		KPROBE,	0, SEC_NONE, attach_uprobe),
10730 	SEC_DEF("uprobe.s+",		KPROBE,	0, SEC_SLEEPABLE, attach_uprobe),
10731 	SEC_DEF("kretprobe+",		KPROBE, 0, SEC_NONE, attach_kprobe),
10732 	SEC_DEF("uretprobe+",		KPROBE, 0, SEC_NONE, attach_uprobe),
10733 	SEC_DEF("uretprobe.s+",		KPROBE, 0, SEC_SLEEPABLE, attach_uprobe),
10734 	SEC_DEF("kprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
10735 	SEC_DEF("kretprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
10736 	SEC_DEF("kprobe.session+",	KPROBE,	BPF_TRACE_KPROBE_SESSION, SEC_NONE, attach_kprobe_session),
10737 	SEC_DEF("uprobe.multi+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_NONE, attach_uprobe_multi),
10738 	SEC_DEF("uretprobe.multi+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_NONE, attach_uprobe_multi),
10739 	SEC_DEF("uprobe.session+",	KPROBE,	BPF_TRACE_UPROBE_SESSION, SEC_NONE, attach_uprobe_multi),
10740 	SEC_DEF("uprobe.multi.s+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_SLEEPABLE, attach_uprobe_multi),
10741 	SEC_DEF("uretprobe.multi.s+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_SLEEPABLE, attach_uprobe_multi),
10742 	SEC_DEF("uprobe.session.s+",	KPROBE,	BPF_TRACE_UPROBE_SESSION, SEC_SLEEPABLE, attach_uprobe_multi),
10743 	SEC_DEF("ksyscall+",		KPROBE,	0, SEC_NONE, attach_ksyscall),
10744 	SEC_DEF("kretsyscall+",		KPROBE, 0, SEC_NONE, attach_ksyscall),
10745 	SEC_DEF("usdt+",		KPROBE,	0, SEC_USDT, attach_usdt),
10746 	SEC_DEF("usdt.s+",		KPROBE,	0, SEC_USDT | SEC_SLEEPABLE, attach_usdt),
10747 	SEC_DEF("tc/ingress",		SCHED_CLS, BPF_TCX_INGRESS, SEC_NONE), /* alias for tcx */
10748 	SEC_DEF("tc/egress",		SCHED_CLS, BPF_TCX_EGRESS, SEC_NONE),  /* alias for tcx */
10749 	SEC_DEF("tcx/ingress",		SCHED_CLS, BPF_TCX_INGRESS, SEC_NONE),
10750 	SEC_DEF("tcx/egress",		SCHED_CLS, BPF_TCX_EGRESS, SEC_NONE),
10751 	SEC_DEF("tc",			SCHED_CLS, 0, SEC_NONE), /* deprecated / legacy, use tcx */
10752 	SEC_DEF("classifier",		SCHED_CLS, 0, SEC_NONE), /* deprecated / legacy, use tcx */
10753 	SEC_DEF("action",		SCHED_ACT, 0, SEC_NONE), /* deprecated / legacy, use tcx */
10754 	SEC_DEF("netkit/primary",	SCHED_CLS, BPF_NETKIT_PRIMARY, SEC_NONE),
10755 	SEC_DEF("netkit/peer",		SCHED_CLS, BPF_NETKIT_PEER, SEC_NONE),
10756 	SEC_DEF("tracepoint+",		TRACEPOINT, 0, SEC_NONE, attach_tp),
10757 	SEC_DEF("tp+",			TRACEPOINT, 0, SEC_NONE, attach_tp),
10758 	SEC_DEF("tracepoint.s+",	TRACEPOINT, 0, SEC_SLEEPABLE, attach_tp),
10759 	SEC_DEF("tp.s+",		TRACEPOINT, 0, SEC_SLEEPABLE, attach_tp),
10760 	SEC_DEF("raw_tracepoint+",	RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
10761 	SEC_DEF("raw_tp+",		RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
10762 	SEC_DEF("raw_tracepoint.s+",	RAW_TRACEPOINT, 0, SEC_SLEEPABLE, attach_raw_tp),
10763 	SEC_DEF("raw_tp.s+",		RAW_TRACEPOINT, 0, SEC_SLEEPABLE, attach_raw_tp),
10764 	SEC_DEF("raw_tracepoint.w+",	RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
10765 	SEC_DEF("raw_tp.w+",		RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
10766 	SEC_DEF("tp_btf+",		TRACING, BPF_TRACE_RAW_TP, SEC_ATTACH_BTF, attach_trace),
10767 	SEC_DEF("tp_btf.s+",		TRACING, BPF_TRACE_RAW_TP, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
10768 	SEC_DEF("fentry+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF, attach_trace),
10769 	SEC_DEF("fmod_ret+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF, attach_trace),
10770 	SEC_DEF("fexit+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF, attach_trace),
10771 	SEC_DEF("fentry.s+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
10772 	SEC_DEF("fmod_ret.s+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
10773 	SEC_DEF("fexit.s+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
10774 	SEC_DEF("fsession+",		TRACING, BPF_TRACE_FSESSION, SEC_ATTACH_BTF, attach_trace),
10775 	SEC_DEF("fsession.s+",		TRACING, BPF_TRACE_FSESSION, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
10776 	SEC_DEF("fsession.multi+",	TRACING, BPF_TRACE_FSESSION_MULTI, 0, attach_tracing_multi),
10777 	SEC_DEF("fsession.multi.s+",	TRACING, BPF_TRACE_FSESSION_MULTI, SEC_SLEEPABLE, attach_tracing_multi),
10778 	SEC_DEF("fentry.multi+",	TRACING, BPF_TRACE_FENTRY_MULTI, 0, attach_tracing_multi),
10779 	SEC_DEF("fexit.multi+",		TRACING, BPF_TRACE_FEXIT_MULTI, 0, attach_tracing_multi),
10780 	SEC_DEF("fentry.multi.s+",	TRACING, BPF_TRACE_FENTRY_MULTI, SEC_SLEEPABLE, attach_tracing_multi),
10781 	SEC_DEF("fexit.multi.s+",	TRACING, BPF_TRACE_FEXIT_MULTI, SEC_SLEEPABLE, attach_tracing_multi),
10782 	SEC_DEF("freplace+",		EXT, 0, SEC_ATTACH_BTF, attach_trace),
10783 	SEC_DEF("lsm+",			LSM, BPF_LSM_MAC, SEC_ATTACH_BTF, attach_lsm),
10784 	SEC_DEF("lsm.s+",		LSM, BPF_LSM_MAC, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_lsm),
10785 	SEC_DEF("lsm_cgroup+",		LSM, BPF_LSM_CGROUP, SEC_ATTACH_BTF),
10786 	SEC_DEF("iter+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF, attach_iter),
10787 	SEC_DEF("iter.s+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_iter),
10788 	SEC_DEF("syscall",		SYSCALL, 0, SEC_SLEEPABLE),
10789 	SEC_DEF("xdp.frags/devmap",	XDP, BPF_XDP_DEVMAP, SEC_XDP_FRAGS),
10790 	SEC_DEF("xdp/devmap",		XDP, BPF_XDP_DEVMAP, SEC_ATTACHABLE),
10791 	SEC_DEF("xdp.frags/cpumap",	XDP, BPF_XDP_CPUMAP, SEC_XDP_FRAGS),
10792 	SEC_DEF("xdp/cpumap",		XDP, BPF_XDP_CPUMAP, SEC_ATTACHABLE),
10793 	SEC_DEF("xdp.frags",		XDP, BPF_XDP, SEC_XDP_FRAGS),
10794 	SEC_DEF("xdp",			XDP, BPF_XDP, SEC_ATTACHABLE_OPT),
10795 	SEC_DEF("perf_event",		PERF_EVENT, 0, SEC_NONE),
10796 	SEC_DEF("lwt_in",		LWT_IN, 0, SEC_NONE),
10797 	SEC_DEF("lwt_out",		LWT_OUT, 0, SEC_NONE),
10798 	SEC_DEF("lwt_xmit",		LWT_XMIT, 0, SEC_NONE),
10799 	SEC_DEF("lwt_seg6local",	LWT_SEG6LOCAL, 0, SEC_NONE),
10800 	SEC_DEF("sockops",		SOCK_OPS, BPF_CGROUP_SOCK_OPS, SEC_ATTACHABLE_OPT),
10801 	SEC_DEF("sk_skb/stream_parser",	SK_SKB, BPF_SK_SKB_STREAM_PARSER, SEC_ATTACHABLE_OPT),
10802 	SEC_DEF("sk_skb/stream_verdict",SK_SKB, BPF_SK_SKB_STREAM_VERDICT, SEC_ATTACHABLE_OPT),
10803 	SEC_DEF("sk_skb/verdict",	SK_SKB, BPF_SK_SKB_VERDICT, SEC_ATTACHABLE_OPT),
10804 	SEC_DEF("sk_skb",		SK_SKB, 0, SEC_NONE),
10805 	SEC_DEF("sk_msg",		SK_MSG, BPF_SK_MSG_VERDICT, SEC_ATTACHABLE_OPT),
10806 	SEC_DEF("lirc_mode2",		LIRC_MODE2, BPF_LIRC_MODE2, SEC_ATTACHABLE_OPT),
10807 	SEC_DEF("flow_dissector",	FLOW_DISSECTOR, BPF_FLOW_DISSECTOR, SEC_ATTACHABLE_OPT),
10808 	SEC_DEF("cgroup_skb/ingress",	CGROUP_SKB, BPF_CGROUP_INET_INGRESS, SEC_ATTACHABLE_OPT),
10809 	SEC_DEF("cgroup_skb/egress",	CGROUP_SKB, BPF_CGROUP_INET_EGRESS, SEC_ATTACHABLE_OPT),
10810 	SEC_DEF("cgroup/skb",		CGROUP_SKB, 0, SEC_NONE),
10811 	SEC_DEF("cgroup/sock_create",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE),
10812 	SEC_DEF("cgroup/sock_release",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_RELEASE, SEC_ATTACHABLE),
10813 	SEC_DEF("cgroup/sock",		CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE_OPT),
10814 	SEC_DEF("cgroup/post_bind4",	CGROUP_SOCK, BPF_CGROUP_INET4_POST_BIND, SEC_ATTACHABLE),
10815 	SEC_DEF("cgroup/post_bind6",	CGROUP_SOCK, BPF_CGROUP_INET6_POST_BIND, SEC_ATTACHABLE),
10816 	SEC_DEF("cgroup/bind4",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND, SEC_ATTACHABLE),
10817 	SEC_DEF("cgroup/bind6",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND, SEC_ATTACHABLE),
10818 	SEC_DEF("cgroup/connect4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT, SEC_ATTACHABLE),
10819 	SEC_DEF("cgroup/connect6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT, SEC_ATTACHABLE),
10820 	SEC_DEF("cgroup/connect_unix",	CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_CONNECT, SEC_ATTACHABLE),
10821 	SEC_DEF("cgroup/sendmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG, SEC_ATTACHABLE),
10822 	SEC_DEF("cgroup/sendmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG, SEC_ATTACHABLE),
10823 	SEC_DEF("cgroup/sendmsg_unix",	CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_SENDMSG, SEC_ATTACHABLE),
10824 	SEC_DEF("cgroup/recvmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_RECVMSG, SEC_ATTACHABLE),
10825 	SEC_DEF("cgroup/recvmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_RECVMSG, SEC_ATTACHABLE),
10826 	SEC_DEF("cgroup/recvmsg_unix",	CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_RECVMSG, SEC_ATTACHABLE),
10827 	SEC_DEF("cgroup/getpeername4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETPEERNAME, SEC_ATTACHABLE),
10828 	SEC_DEF("cgroup/getpeername6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETPEERNAME, SEC_ATTACHABLE),
10829 	SEC_DEF("cgroup/getpeername_unix", CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_GETPEERNAME, SEC_ATTACHABLE),
10830 	SEC_DEF("cgroup/getsockname4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETSOCKNAME, SEC_ATTACHABLE),
10831 	SEC_DEF("cgroup/getsockname6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETSOCKNAME, SEC_ATTACHABLE),
10832 	SEC_DEF("cgroup/getsockname_unix", CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_GETSOCKNAME, SEC_ATTACHABLE),
10833 	SEC_DEF("cgroup/sysctl",	CGROUP_SYSCTL, BPF_CGROUP_SYSCTL, SEC_ATTACHABLE),
10834 	SEC_DEF("cgroup/getsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_GETSOCKOPT, SEC_ATTACHABLE),
10835 	SEC_DEF("cgroup/setsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_SETSOCKOPT, SEC_ATTACHABLE),
10836 	SEC_DEF("cgroup/dev",		CGROUP_DEVICE, BPF_CGROUP_DEVICE, SEC_ATTACHABLE_OPT),
10837 	SEC_DEF("struct_ops+",		STRUCT_OPS, 0, SEC_NONE),
10838 	SEC_DEF("struct_ops.s+",	STRUCT_OPS, 0, SEC_SLEEPABLE),
10839 	SEC_DEF("sk_lookup",		SK_LOOKUP, BPF_SK_LOOKUP, SEC_ATTACHABLE),
10840 	SEC_DEF("netfilter",		NETFILTER, BPF_NETFILTER, SEC_NONE),
10841 };
10842 
10843 int libbpf_register_prog_handler(const char *sec,
10844 				 enum bpf_prog_type prog_type,
10845 				 enum bpf_attach_type exp_attach_type,
10846 				 const struct libbpf_prog_handler_opts *opts)
10847 {
10848 	struct bpf_sec_def *sec_def;
10849 
10850 	if (!OPTS_VALID(opts, libbpf_prog_handler_opts))
10851 		return libbpf_err(-EINVAL);
10852 
10853 	if (last_custom_sec_def_handler_id == INT_MAX) /* prevent overflow */
10854 		return libbpf_err(-E2BIG);
10855 
10856 	if (sec) {
10857 		sec_def = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt + 1,
10858 					      sizeof(*sec_def));
10859 		if (!sec_def)
10860 			return libbpf_err(-ENOMEM);
10861 
10862 		custom_sec_defs = sec_def;
10863 		sec_def = &custom_sec_defs[custom_sec_def_cnt];
10864 	} else {
10865 		if (has_custom_fallback_def)
10866 			return libbpf_err(-EBUSY);
10867 
10868 		sec_def = &custom_fallback_def;
10869 	}
10870 
10871 	sec_def->sec = sec ? strdup(sec) : NULL;
10872 	if (sec && !sec_def->sec)
10873 		return libbpf_err(-ENOMEM);
10874 
10875 	sec_def->prog_type = prog_type;
10876 	sec_def->expected_attach_type = exp_attach_type;
10877 	sec_def->cookie = OPTS_GET(opts, cookie, 0);
10878 
10879 	sec_def->prog_setup_fn = OPTS_GET(opts, prog_setup_fn, NULL);
10880 	sec_def->prog_prepare_load_fn = OPTS_GET(opts, prog_prepare_load_fn, NULL);
10881 	sec_def->prog_attach_fn = OPTS_GET(opts, prog_attach_fn, NULL);
10882 
10883 	sec_def->handler_id = ++last_custom_sec_def_handler_id;
10884 
10885 	if (sec)
10886 		custom_sec_def_cnt++;
10887 	else
10888 		has_custom_fallback_def = true;
10889 
10890 	return sec_def->handler_id;
10891 }
10892 
10893 int libbpf_unregister_prog_handler(int handler_id)
10894 {
10895 	struct bpf_sec_def *sec_defs;
10896 	int i;
10897 
10898 	if (handler_id <= 0)
10899 		return libbpf_err(-EINVAL);
10900 
10901 	if (has_custom_fallback_def && custom_fallback_def.handler_id == handler_id) {
10902 		memset(&custom_fallback_def, 0, sizeof(custom_fallback_def));
10903 		has_custom_fallback_def = false;
10904 		return 0;
10905 	}
10906 
10907 	for (i = 0; i < custom_sec_def_cnt; i++) {
10908 		if (custom_sec_defs[i].handler_id == handler_id)
10909 			break;
10910 	}
10911 
10912 	if (i == custom_sec_def_cnt)
10913 		return libbpf_err(-ENOENT);
10914 
10915 	free(custom_sec_defs[i].sec);
10916 	for (i = i + 1; i < custom_sec_def_cnt; i++)
10917 		custom_sec_defs[i - 1] = custom_sec_defs[i];
10918 	custom_sec_def_cnt--;
10919 
10920 	/* try to shrink the array, but it's ok if we couldn't */
10921 	sec_defs = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt, sizeof(*sec_defs));
10922 	/* if new count is zero, reallocarray can return a valid NULL result;
10923 	 * in this case the previous pointer will be freed, so we *have to*
10924 	 * reassign old pointer to the new value (even if it's NULL)
10925 	 */
10926 	if (sec_defs || custom_sec_def_cnt == 0)
10927 		custom_sec_defs = sec_defs;
10928 
10929 	return 0;
10930 }
10931 
10932 static bool sec_def_matches(const struct bpf_sec_def *sec_def, const char *sec_name)
10933 {
10934 	size_t len = strlen(sec_def->sec);
10935 
10936 	/* "type/" always has to have proper SEC("type/extras") form */
10937 	if (sec_def->sec[len - 1] == '/') {
10938 		if (str_has_pfx(sec_name, sec_def->sec))
10939 			return true;
10940 		return false;
10941 	}
10942 
10943 	/* "type+" means it can be either exact SEC("type") or
10944 	 * well-formed SEC("type/extras") with proper '/' separator
10945 	 */
10946 	if (sec_def->sec[len - 1] == '+') {
10947 		len--;
10948 		/* not even a prefix */
10949 		if (strncmp(sec_name, sec_def->sec, len) != 0)
10950 			return false;
10951 		/* exact match or has '/' separator */
10952 		if (sec_name[len] == '\0' || sec_name[len] == '/')
10953 			return true;
10954 		return false;
10955 	}
10956 
10957 	return strcmp(sec_name, sec_def->sec) == 0;
10958 }
10959 
10960 static const struct bpf_sec_def *find_sec_def(const char *sec_name)
10961 {
10962 	const struct bpf_sec_def *sec_def;
10963 	int i, n;
10964 
10965 	n = custom_sec_def_cnt;
10966 	for (i = 0; i < n; i++) {
10967 		sec_def = &custom_sec_defs[i];
10968 		if (sec_def_matches(sec_def, sec_name))
10969 			return sec_def;
10970 	}
10971 
10972 	n = ARRAY_SIZE(section_defs);
10973 	for (i = 0; i < n; i++) {
10974 		sec_def = &section_defs[i];
10975 		if (sec_def_matches(sec_def, sec_name))
10976 			return sec_def;
10977 	}
10978 
10979 	if (has_custom_fallback_def)
10980 		return &custom_fallback_def;
10981 
10982 	return NULL;
10983 }
10984 
10985 #define MAX_TYPE_NAME_SIZE 32
10986 
10987 static char *libbpf_get_type_names(bool attach_type)
10988 {
10989 	int i, len = ARRAY_SIZE(section_defs) * MAX_TYPE_NAME_SIZE;
10990 	char *buf;
10991 
10992 	buf = malloc(len);
10993 	if (!buf)
10994 		return NULL;
10995 
10996 	buf[0] = '\0';
10997 	/* Forge string buf with all available names */
10998 	for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
10999 		const struct bpf_sec_def *sec_def = &section_defs[i];
11000 
11001 		if (attach_type) {
11002 			if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
11003 				continue;
11004 
11005 			if (!(sec_def->cookie & SEC_ATTACHABLE))
11006 				continue;
11007 		}
11008 
11009 		if (strlen(buf) + strlen(section_defs[i].sec) + 2 > len) {
11010 			free(buf);
11011 			return NULL;
11012 		}
11013 		strcat(buf, " ");
11014 		strcat(buf, section_defs[i].sec);
11015 	}
11016 
11017 	return buf;
11018 }
11019 
11020 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
11021 			     enum bpf_attach_type *expected_attach_type)
11022 {
11023 	const struct bpf_sec_def *sec_def;
11024 	char *type_names;
11025 
11026 	if (!name)
11027 		return libbpf_err(-EINVAL);
11028 
11029 	sec_def = find_sec_def(name);
11030 	if (sec_def) {
11031 		*prog_type = sec_def->prog_type;
11032 		*expected_attach_type = sec_def->expected_attach_type;
11033 		return 0;
11034 	}
11035 
11036 	pr_debug("failed to guess program type from ELF section '%s'\n", name);
11037 	type_names = libbpf_get_type_names(false);
11038 	if (type_names != NULL) {
11039 		pr_debug("supported section(type) names are:%s\n", type_names);
11040 		free(type_names);
11041 	}
11042 
11043 	return libbpf_err(-ESRCH);
11044 }
11045 
11046 const char *libbpf_bpf_attach_type_str(enum bpf_attach_type t)
11047 {
11048 	if (t < 0 || t >= ARRAY_SIZE(attach_type_name))
11049 		return NULL;
11050 
11051 	return attach_type_name[t];
11052 }
11053 
11054 const char *libbpf_bpf_link_type_str(enum bpf_link_type t)
11055 {
11056 	if (t < 0 || t >= ARRAY_SIZE(link_type_name))
11057 		return NULL;
11058 
11059 	return link_type_name[t];
11060 }
11061 
11062 const char *libbpf_bpf_map_type_str(enum bpf_map_type t)
11063 {
11064 	if (t < 0 || t >= ARRAY_SIZE(map_type_name))
11065 		return NULL;
11066 
11067 	return map_type_name[t];
11068 }
11069 
11070 const char *libbpf_bpf_prog_type_str(enum bpf_prog_type t)
11071 {
11072 	if (t < 0 || t >= ARRAY_SIZE(prog_type_name))
11073 		return NULL;
11074 
11075 	return prog_type_name[t];
11076 }
11077 
11078 static struct bpf_map *find_struct_ops_map_by_offset(struct bpf_object *obj,
11079 						     int sec_idx,
11080 						     size_t offset)
11081 {
11082 	struct bpf_map *map;
11083 	size_t i;
11084 
11085 	for (i = 0; i < obj->nr_maps; i++) {
11086 		map = &obj->maps[i];
11087 		if (!bpf_map__is_struct_ops(map))
11088 			continue;
11089 		if (map->sec_idx == sec_idx &&
11090 		    map->sec_offset <= offset &&
11091 		    offset - map->sec_offset < map->def.value_size)
11092 			return map;
11093 	}
11094 
11095 	return NULL;
11096 }
11097 
11098 /* Collect the reloc from ELF, populate the st_ops->progs[], and update
11099  * st_ops->data for shadow type.
11100  */
11101 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
11102 					    Elf64_Shdr *shdr, Elf_Data *data)
11103 {
11104 	const struct btf_type *type;
11105 	const struct btf_member *member;
11106 	struct bpf_struct_ops *st_ops;
11107 	struct bpf_program *prog;
11108 	unsigned int shdr_idx;
11109 	const struct btf *btf;
11110 	struct bpf_map *map;
11111 	unsigned int moff, insn_idx;
11112 	const char *name;
11113 	__u32 member_idx;
11114 	Elf64_Sym *sym;
11115 	Elf64_Rel *rel;
11116 	int i, nrels;
11117 
11118 	btf = obj->btf;
11119 	nrels = shdr->sh_size / shdr->sh_entsize;
11120 	for (i = 0; i < nrels; i++) {
11121 		rel = elf_rel_by_idx(data, i);
11122 		if (!rel) {
11123 			pr_warn("struct_ops reloc: failed to get %d reloc\n", i);
11124 			return -LIBBPF_ERRNO__FORMAT;
11125 		}
11126 
11127 		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
11128 		if (!sym) {
11129 			pr_warn("struct_ops reloc: symbol %zx not found\n",
11130 				(size_t)ELF64_R_SYM(rel->r_info));
11131 			return -LIBBPF_ERRNO__FORMAT;
11132 		}
11133 
11134 		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
11135 		map = find_struct_ops_map_by_offset(obj, shdr->sh_info, rel->r_offset);
11136 		if (!map) {
11137 			pr_warn("struct_ops reloc: cannot find map at rel->r_offset %zu\n",
11138 				(size_t)rel->r_offset);
11139 			return -EINVAL;
11140 		}
11141 
11142 		moff = rel->r_offset - map->sec_offset;
11143 		shdr_idx = sym->st_shndx;
11144 		st_ops = map->st_ops;
11145 		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",
11146 			 map->name,
11147 			 (long long)(rel->r_info >> 32),
11148 			 (long long)sym->st_value,
11149 			 shdr_idx, (size_t)rel->r_offset,
11150 			 map->sec_offset, sym->st_name, name);
11151 
11152 		if (shdr_idx >= SHN_LORESERVE) {
11153 			pr_warn("struct_ops reloc %s: rel->r_offset %zu shdr_idx %u unsupported non-static function\n",
11154 				map->name, (size_t)rel->r_offset, shdr_idx);
11155 			return -LIBBPF_ERRNO__RELOC;
11156 		}
11157 		if (sym->st_value % BPF_INSN_SZ) {
11158 			pr_warn("struct_ops reloc %s: invalid target program offset %llu\n",
11159 				map->name, (unsigned long long)sym->st_value);
11160 			return -LIBBPF_ERRNO__FORMAT;
11161 		}
11162 		insn_idx = sym->st_value / BPF_INSN_SZ;
11163 
11164 		type = btf__type_by_id(btf, st_ops->type_id);
11165 		member = find_member_by_offset(type, moff * 8);
11166 		if (!member) {
11167 			pr_warn("struct_ops reloc %s: cannot find member at moff %u\n",
11168 				map->name, moff);
11169 			return -EINVAL;
11170 		}
11171 		member_idx = member - btf_members(type);
11172 		name = btf__name_by_offset(btf, member->name_off);
11173 
11174 		if (!resolve_func_ptr(btf, member->type, NULL)) {
11175 			pr_warn("struct_ops reloc %s: cannot relocate non func ptr %s\n",
11176 				map->name, name);
11177 			return -EINVAL;
11178 		}
11179 
11180 		prog = find_prog_by_sec_insn(obj, shdr_idx, insn_idx);
11181 		if (!prog) {
11182 			pr_warn("struct_ops reloc %s: cannot find prog at shdr_idx %u to relocate func ptr %s\n",
11183 				map->name, shdr_idx, name);
11184 			return -EINVAL;
11185 		}
11186 
11187 		/* prevent the use of BPF prog with invalid type */
11188 		if (prog->type != BPF_PROG_TYPE_STRUCT_OPS) {
11189 			pr_warn("struct_ops reloc %s: prog %s is not struct_ops BPF program\n",
11190 				map->name, prog->name);
11191 			return -EINVAL;
11192 		}
11193 
11194 		st_ops->progs[member_idx] = prog;
11195 
11196 		/* st_ops->data will be exposed to users, being returned by
11197 		 * bpf_map__initial_value() as a pointer to the shadow
11198 		 * type. All function pointers in the original struct type
11199 		 * should be converted to a pointer to struct bpf_program
11200 		 * in the shadow type.
11201 		 */
11202 		*((struct bpf_program **)(st_ops->data + moff)) = prog;
11203 	}
11204 
11205 	return 0;
11206 }
11207 
11208 #define BTF_TRACE_PREFIX "btf_trace_"
11209 #define BTF_LSM_PREFIX "bpf_lsm_"
11210 #define BTF_ITER_PREFIX "bpf_iter_"
11211 #define BTF_MAX_NAME_SIZE 128
11212 
11213 void btf_get_kernel_prefix_kind(enum bpf_attach_type attach_type,
11214 				const char **prefix, int *kind)
11215 {
11216 	switch (attach_type) {
11217 	case BPF_TRACE_RAW_TP:
11218 		*prefix = BTF_TRACE_PREFIX;
11219 		*kind = BTF_KIND_TYPEDEF;
11220 		break;
11221 	case BPF_LSM_MAC:
11222 	case BPF_LSM_CGROUP:
11223 		*prefix = BTF_LSM_PREFIX;
11224 		*kind = BTF_KIND_FUNC;
11225 		break;
11226 	case BPF_TRACE_ITER:
11227 		*prefix = BTF_ITER_PREFIX;
11228 		*kind = BTF_KIND_FUNC;
11229 		break;
11230 	default:
11231 		*prefix = "";
11232 		*kind = BTF_KIND_FUNC;
11233 	}
11234 }
11235 
11236 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
11237 				   const char *name, __u32 kind)
11238 {
11239 	char btf_type_name[BTF_MAX_NAME_SIZE];
11240 	int ret;
11241 
11242 	ret = snprintf(btf_type_name, sizeof(btf_type_name),
11243 		       "%s%s", prefix, name);
11244 	/* snprintf returns the number of characters written excluding the
11245 	 * terminating null. So, if >= BTF_MAX_NAME_SIZE are written, it
11246 	 * indicates truncation.
11247 	 */
11248 	if (ret < 0 || ret >= sizeof(btf_type_name))
11249 		return -ENAMETOOLONG;
11250 	return btf__find_by_name_kind(btf, btf_type_name, kind);
11251 }
11252 
11253 static inline int find_attach_btf_id(struct btf *btf, const char *name,
11254 				     enum bpf_attach_type attach_type)
11255 {
11256 	const char *prefix;
11257 	int kind;
11258 
11259 	btf_get_kernel_prefix_kind(attach_type, &prefix, &kind);
11260 	return find_btf_by_prefix_kind(btf, prefix, name, kind);
11261 }
11262 
11263 int libbpf_find_vmlinux_btf_id(const char *name,
11264 			       enum bpf_attach_type attach_type)
11265 {
11266 	struct btf *btf;
11267 	int err;
11268 
11269 	btf = btf__load_vmlinux_btf();
11270 	err = libbpf_get_error(btf);
11271 	if (err) {
11272 		pr_warn("vmlinux BTF is not found\n");
11273 		return libbpf_err(err);
11274 	}
11275 
11276 	err = find_attach_btf_id(btf, name, attach_type);
11277 	if (err <= 0)
11278 		pr_warn("%s is not found in vmlinux BTF\n", name);
11279 
11280 	btf__free(btf);
11281 	return libbpf_err(err);
11282 }
11283 
11284 static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd, int token_fd)
11285 {
11286 	struct bpf_prog_info info;
11287 	__u32 info_len = sizeof(info);
11288 	struct btf *btf;
11289 	int err;
11290 
11291 	memset(&info, 0, info_len);
11292 	err = bpf_prog_get_info_by_fd(attach_prog_fd, &info, &info_len);
11293 	if (err) {
11294 		pr_warn("failed bpf_prog_get_info_by_fd for FD %u: %s\n",
11295 			attach_prog_fd, errstr(err));
11296 		return err;
11297 	}
11298 
11299 	err = -EINVAL;
11300 	if (!info.btf_id) {
11301 		pr_warn("The target program doesn't have BTF\n");
11302 		goto out;
11303 	}
11304 	btf = btf_load_from_kernel(info.btf_id, NULL, token_fd);
11305 	err = libbpf_get_error(btf);
11306 	if (err) {
11307 		pr_warn("Failed to get BTF %u of the program: %s\n", info.btf_id, errstr(err));
11308 		goto out;
11309 	}
11310 	err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
11311 	btf__free(btf);
11312 	if (err <= 0) {
11313 		pr_warn("%s is not found in prog's BTF\n", name);
11314 		goto out;
11315 	}
11316 out:
11317 	return err;
11318 }
11319 
11320 static int find_kernel_btf_id(struct bpf_object *obj, const char *attach_name,
11321 			      enum bpf_attach_type attach_type,
11322 			      int *btf_obj_fd, int *btf_type_id)
11323 {
11324 	int ret, i, mod_len = 0;
11325 	const char *fn_name, *mod_name = NULL;
11326 
11327 	fn_name = strchr(attach_name, ':');
11328 	if (fn_name) {
11329 		mod_name = attach_name;
11330 		mod_len = fn_name - mod_name;
11331 		fn_name++;
11332 	}
11333 
11334 	if (!mod_name || strncmp(mod_name, "vmlinux", mod_len) == 0) {
11335 		ret = find_attach_btf_id(obj->btf_vmlinux,
11336 					 mod_name ? fn_name : attach_name,
11337 					 attach_type);
11338 		if (ret > 0) {
11339 			*btf_obj_fd = 0; /* vmlinux BTF */
11340 			*btf_type_id = ret;
11341 			return 0;
11342 		}
11343 		if (ret != -ENOENT)
11344 			return ret;
11345 	}
11346 
11347 	ret = load_module_btfs(obj);
11348 	if (ret)
11349 		return ret;
11350 
11351 	for (i = 0; i < obj->btf_module_cnt; i++) {
11352 		const struct module_btf *mod = &obj->btf_modules[i];
11353 
11354 		if (mod_name && strncmp(mod->name, mod_name, mod_len) != 0)
11355 			continue;
11356 
11357 		ret = find_attach_btf_id(mod->btf,
11358 					 mod_name ? fn_name : attach_name,
11359 					 attach_type);
11360 		if (ret > 0) {
11361 			*btf_obj_fd = mod->fd;
11362 			*btf_type_id = ret;
11363 			return 0;
11364 		}
11365 		if (ret == -ENOENT)
11366 			continue;
11367 
11368 		return ret;
11369 	}
11370 
11371 	return -ESRCH;
11372 }
11373 
11374 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
11375 				     int *btf_obj_fd, int *btf_type_id)
11376 {
11377 	enum bpf_attach_type attach_type = prog->expected_attach_type;
11378 	__u32 attach_prog_fd = prog->attach_prog_fd;
11379 	int err = 0;
11380 
11381 	/* BPF program's BTF ID */
11382 	if (prog->type == BPF_PROG_TYPE_EXT || attach_prog_fd) {
11383 		if (!attach_prog_fd) {
11384 			pr_warn("prog '%s': attach program FD is not set\n", prog->name);
11385 			return -EINVAL;
11386 		}
11387 		err = libbpf_find_prog_btf_id(attach_name, attach_prog_fd, prog->obj->token_fd);
11388 		if (err < 0) {
11389 			pr_warn("prog '%s': failed to find BPF program (FD %u) BTF ID for '%s': %s\n",
11390 				prog->name, attach_prog_fd, attach_name, errstr(err));
11391 			return err;
11392 		}
11393 		*btf_obj_fd = 0;
11394 		*btf_type_id = err;
11395 		return 0;
11396 	}
11397 
11398 	/* kernel/module BTF ID */
11399 	if (prog->obj->gen_loader) {
11400 		bpf_gen__record_attach_target(prog->obj->gen_loader, attach_name, attach_type);
11401 		*btf_obj_fd = 0;
11402 		*btf_type_id = 1;
11403 	} else {
11404 		err = find_kernel_btf_id(prog->obj, attach_name,
11405 					 attach_type, btf_obj_fd,
11406 					 btf_type_id);
11407 	}
11408 	if (err) {
11409 		pr_warn("prog '%s': failed to find kernel BTF type ID of '%s': %s\n",
11410 			prog->name, attach_name, errstr(err));
11411 		return err;
11412 	}
11413 	return 0;
11414 }
11415 
11416 int libbpf_attach_type_by_name(const char *name,
11417 			       enum bpf_attach_type *attach_type)
11418 {
11419 	char *type_names;
11420 	const struct bpf_sec_def *sec_def;
11421 
11422 	if (!name)
11423 		return libbpf_err(-EINVAL);
11424 
11425 	sec_def = find_sec_def(name);
11426 	if (!sec_def) {
11427 		pr_debug("failed to guess attach type based on ELF section name '%s'\n", name);
11428 		type_names = libbpf_get_type_names(true);
11429 		if (type_names != NULL) {
11430 			pr_debug("attachable section(type) names are:%s\n", type_names);
11431 			free(type_names);
11432 		}
11433 
11434 		return libbpf_err(-EINVAL);
11435 	}
11436 
11437 	if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
11438 		return libbpf_err(-EINVAL);
11439 	if (!(sec_def->cookie & SEC_ATTACHABLE))
11440 		return libbpf_err(-EINVAL);
11441 
11442 	*attach_type = sec_def->expected_attach_type;
11443 	return 0;
11444 }
11445 
11446 int bpf_map__fd(const struct bpf_map *map)
11447 {
11448 	if (!map)
11449 		return libbpf_err(-EINVAL);
11450 	if (!map_is_created(map))
11451 		return -1;
11452 	return map->fd;
11453 }
11454 
11455 static bool map_uses_real_name(const struct bpf_map *map)
11456 {
11457 	/* Since libbpf started to support custom .data.* and .rodata.* maps,
11458 	 * their user-visible name differs from kernel-visible name. Users see
11459 	 * such map's corresponding ELF section name as a map name.
11460 	 * This check distinguishes .data/.rodata from .data.* and .rodata.*
11461 	 * maps to know which name has to be returned to the user.
11462 	 * Map name of the custom .percpu.* maps might be truncated to
11463 	 * BPF_OBJ_NAME_LEN-1 chars in internal_map_name(). Hence, percpu data
11464 	 * maps must use real name for their user-visible name.
11465 	 */
11466 	if (map->libbpf_type == LIBBPF_MAP_DATA && strcmp(map->real_name, DATA_SEC) != 0)
11467 		return true;
11468 	if (map->libbpf_type == LIBBPF_MAP_RODATA && strcmp(map->real_name, RODATA_SEC) != 0)
11469 		return true;
11470 	if (map->libbpf_type == LIBBPF_MAP_PERCPU)
11471 		return true;
11472 	return false;
11473 }
11474 
11475 const char *bpf_map__name(const struct bpf_map *map)
11476 {
11477 	if (!map)
11478 		return NULL;
11479 
11480 	if (map_uses_real_name(map))
11481 		return map->real_name;
11482 
11483 	return map->name;
11484 }
11485 
11486 enum bpf_map_type bpf_map__type(const struct bpf_map *map)
11487 {
11488 	return map->def.type;
11489 }
11490 
11491 int bpf_map__set_type(struct bpf_map *map, enum bpf_map_type type)
11492 {
11493 	if (map_is_created(map))
11494 		return libbpf_err(-EBUSY);
11495 	map->def.type = type;
11496 	return 0;
11497 }
11498 
11499 __u32 bpf_map__map_flags(const struct bpf_map *map)
11500 {
11501 	return map->def.map_flags;
11502 }
11503 
11504 int bpf_map__set_map_flags(struct bpf_map *map, __u32 flags)
11505 {
11506 	if (map_is_created(map))
11507 		return libbpf_err(-EBUSY);
11508 	map->def.map_flags = flags;
11509 	return 0;
11510 }
11511 
11512 __u64 bpf_map__map_extra(const struct bpf_map *map)
11513 {
11514 	return map->map_extra;
11515 }
11516 
11517 int bpf_map__set_map_extra(struct bpf_map *map, __u64 map_extra)
11518 {
11519 	if (map_is_created(map))
11520 		return libbpf_err(-EBUSY);
11521 	map->map_extra = map_extra;
11522 	return 0;
11523 }
11524 
11525 __u32 bpf_map__numa_node(const struct bpf_map *map)
11526 {
11527 	return map->numa_node;
11528 }
11529 
11530 int bpf_map__set_numa_node(struct bpf_map *map, __u32 numa_node)
11531 {
11532 	if (map_is_created(map))
11533 		return libbpf_err(-EBUSY);
11534 	map->numa_node = numa_node;
11535 	return 0;
11536 }
11537 
11538 __u32 bpf_map__key_size(const struct bpf_map *map)
11539 {
11540 	return map->def.key_size;
11541 }
11542 
11543 int bpf_map__set_key_size(struct bpf_map *map, __u32 size)
11544 {
11545 	if (map_is_created(map))
11546 		return libbpf_err(-EBUSY);
11547 	map->def.key_size = size;
11548 	return 0;
11549 }
11550 
11551 __u32 bpf_map__value_size(const struct bpf_map *map)
11552 {
11553 	return map->def.value_size;
11554 }
11555 
11556 static int map_btf_datasec_resize(struct bpf_map *map, __u32 size)
11557 {
11558 	struct btf *btf;
11559 	struct btf_type *datasec_type, *var_type;
11560 	struct btf_var_secinfo *var;
11561 	const struct btf_type *array_type;
11562 	const struct btf_array *array;
11563 	int vlen, element_sz, new_array_id;
11564 	__u32 nr_elements;
11565 
11566 	/* check btf existence */
11567 	btf = bpf_object__btf(map->obj);
11568 	if (!btf)
11569 		return -ENOENT;
11570 
11571 	/* verify map is datasec */
11572 	datasec_type = btf_type_by_id(btf, bpf_map__btf_value_type_id(map));
11573 	if (!btf_is_datasec(datasec_type)) {
11574 		pr_warn("map '%s': cannot be resized, map value type is not a datasec\n",
11575 			bpf_map__name(map));
11576 		return -EINVAL;
11577 	}
11578 
11579 	/* verify datasec has at least one var */
11580 	vlen = btf_vlen(datasec_type);
11581 	if (vlen == 0) {
11582 		pr_warn("map '%s': cannot be resized, map value datasec is empty\n",
11583 			bpf_map__name(map));
11584 		return -EINVAL;
11585 	}
11586 
11587 	/* verify last var in the datasec is an array */
11588 	var = &btf_var_secinfos(datasec_type)[vlen - 1];
11589 	var_type = btf_type_by_id(btf, var->type);
11590 	array_type = skip_mods_and_typedefs(btf, var_type->type, NULL);
11591 	if (!btf_is_array(array_type)) {
11592 		pr_warn("map '%s': cannot be resized, last var must be an array\n",
11593 			bpf_map__name(map));
11594 		return -EINVAL;
11595 	}
11596 
11597 	/* verify request size aligns with array */
11598 	array = btf_array(array_type);
11599 	element_sz = btf__resolve_size(btf, array->type);
11600 	if (element_sz <= 0 || (size - var->offset) % element_sz != 0) {
11601 		pr_warn("map '%s': cannot be resized, element size (%d) doesn't align with new total size (%u)\n",
11602 			bpf_map__name(map), element_sz, size);
11603 		return -EINVAL;
11604 	}
11605 
11606 	/* create a new array based on the existing array, but with new length */
11607 	nr_elements = (size - var->offset) / element_sz;
11608 	new_array_id = btf__add_array(btf, array->index_type, array->type, nr_elements);
11609 	if (new_array_id < 0)
11610 		return new_array_id;
11611 
11612 	/* adding a new btf type invalidates existing pointers to btf objects,
11613 	 * so refresh pointers before proceeding
11614 	 */
11615 	datasec_type = btf_type_by_id(btf, map->btf_value_type_id);
11616 	var = &btf_var_secinfos(datasec_type)[vlen - 1];
11617 	var_type = btf_type_by_id(btf, var->type);
11618 
11619 	/* finally update btf info */
11620 	datasec_type->size = size;
11621 	var->size = size - var->offset;
11622 	var_type->type = new_array_id;
11623 
11624 	return 0;
11625 }
11626 
11627 int bpf_map__set_value_size(struct bpf_map *map, __u32 size)
11628 {
11629 	if (map_is_created(map))
11630 		return libbpf_err(-EBUSY);
11631 
11632 	if (map->mmaped) {
11633 		size_t mmap_old_sz, mmap_new_sz;
11634 		int err;
11635 
11636 		if (map->def.type != BPF_MAP_TYPE_ARRAY &&
11637 		    map->def.type != BPF_MAP_TYPE_PERCPU_ARRAY)
11638 			return libbpf_err(-EOPNOTSUPP);
11639 
11640 		mmap_old_sz = bpf_map_mmap_sz(map);
11641 		mmap_new_sz = array_map_mmap_sz(size, map->def.max_entries);
11642 		err = bpf_map_mmap_resize(map, mmap_old_sz, mmap_new_sz);
11643 		if (err) {
11644 			pr_warn("map '%s': failed to resize memory-mapped region: %s\n",
11645 				bpf_map__name(map), errstr(err));
11646 			return libbpf_err(err);
11647 		}
11648 		err = map_btf_datasec_resize(map, size);
11649 		if (err && err != -ENOENT) {
11650 			pr_warn("map '%s': failed to adjust resized BTF, clearing BTF key/value info: %s\n",
11651 				bpf_map__name(map), errstr(err));
11652 			map->btf_value_type_id = 0;
11653 			map->btf_key_type_id = 0;
11654 		}
11655 	}
11656 
11657 	map->def.value_size = size;
11658 	return 0;
11659 }
11660 
11661 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
11662 {
11663 	return map ? map->btf_key_type_id : 0;
11664 }
11665 
11666 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
11667 {
11668 	return map ? map->btf_value_type_id : 0;
11669 }
11670 
11671 int bpf_map__set_initial_value(struct bpf_map *map,
11672 			       const void *data, size_t size)
11673 {
11674 	size_t actual_sz;
11675 
11676 	if (map_is_created(map))
11677 		return libbpf_err(-EBUSY);
11678 
11679 	if (!map->mmaped || map->libbpf_type == LIBBPF_MAP_KCONFIG)
11680 		return libbpf_err(-EINVAL);
11681 
11682 	if (map->def.type == BPF_MAP_TYPE_ARENA)
11683 		actual_sz = map->obj->arena_data_sz;
11684 	else
11685 		actual_sz = map->def.value_size;
11686 	if (size != actual_sz)
11687 		return libbpf_err(-EINVAL);
11688 
11689 	memcpy(map->mmaped, data, size);
11690 	return 0;
11691 }
11692 
11693 void *bpf_map__initial_value(const struct bpf_map *map, size_t *psize)
11694 {
11695 	if (bpf_map__is_struct_ops(map)) {
11696 		if (psize)
11697 			*psize = map->def.value_size;
11698 		return map->st_ops->data;
11699 	}
11700 
11701 	if (!map->mmaped)
11702 		return NULL;
11703 
11704 	if (map->def.type == BPF_MAP_TYPE_ARENA)
11705 		*psize = map->obj->arena_data_sz;
11706 	else
11707 		*psize = map->def.value_size;
11708 
11709 	return map->mmaped;
11710 }
11711 
11712 bool bpf_map__is_internal(const struct bpf_map *map)
11713 {
11714 	return map->libbpf_type != LIBBPF_MAP_UNSPEC;
11715 }
11716 
11717 __u32 bpf_map__ifindex(const struct bpf_map *map)
11718 {
11719 	return map->map_ifindex;
11720 }
11721 
11722 int bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
11723 {
11724 	if (map_is_created(map))
11725 		return libbpf_err(-EBUSY);
11726 	map->map_ifindex = ifindex;
11727 	return 0;
11728 }
11729 
11730 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
11731 {
11732 	if (!bpf_map_type__is_map_in_map(map->def.type)) {
11733 		pr_warn("error: unsupported map type\n");
11734 		return libbpf_err(-EINVAL);
11735 	}
11736 	if (map->inner_map_fd != -1) {
11737 		pr_warn("error: inner_map_fd already specified\n");
11738 		return libbpf_err(-EINVAL);
11739 	}
11740 	if (map->inner_map) {
11741 		bpf_map__destroy(map->inner_map);
11742 		zfree(&map->inner_map);
11743 	}
11744 	map->inner_map_fd = fd;
11745 	return 0;
11746 }
11747 
11748 int bpf_map__set_exclusive_program(struct bpf_map *map, struct bpf_program *prog)
11749 {
11750 	if (map_is_created(map)) {
11751 		pr_warn("exclusive programs must be set before map creation\n");
11752 		return libbpf_err(-EINVAL);
11753 	}
11754 
11755 	if (map->obj != prog->obj) {
11756 		pr_warn("excl_prog and map must be from the same bpf object\n");
11757 		return libbpf_err(-EINVAL);
11758 	}
11759 
11760 	map->excl_prog = prog;
11761 	return 0;
11762 }
11763 
11764 struct bpf_program *bpf_map__exclusive_program(struct bpf_map *map)
11765 {
11766 	return map->excl_prog;
11767 }
11768 
11769 static struct bpf_map *
11770 __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
11771 {
11772 	ssize_t idx;
11773 	struct bpf_map *s, *e;
11774 
11775 	if (!obj || !obj->maps)
11776 		return errno = EINVAL, NULL;
11777 
11778 	s = obj->maps;
11779 	e = obj->maps + obj->nr_maps;
11780 
11781 	if ((m < s) || (m >= e)) {
11782 		pr_warn("error in %s: map handler doesn't belong to object\n",
11783 			 __func__);
11784 		return errno = EINVAL, NULL;
11785 	}
11786 
11787 	idx = (m - obj->maps) + i;
11788 	if (idx >= obj->nr_maps || idx < 0)
11789 		return NULL;
11790 	return &obj->maps[idx];
11791 }
11792 
11793 struct bpf_map *
11794 bpf_object__next_map(const struct bpf_object *obj, const struct bpf_map *prev)
11795 {
11796 	if (prev == NULL && obj != NULL)
11797 		return obj->maps;
11798 
11799 	return __bpf_map__iter(prev, obj, 1);
11800 }
11801 
11802 struct bpf_map *
11803 bpf_object__prev_map(const struct bpf_object *obj, const struct bpf_map *next)
11804 {
11805 	if (next == NULL && obj != NULL) {
11806 		if (!obj->nr_maps)
11807 			return NULL;
11808 		return obj->maps + obj->nr_maps - 1;
11809 	}
11810 
11811 	return __bpf_map__iter(next, obj, -1);
11812 }
11813 
11814 struct bpf_map *
11815 bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
11816 {
11817 	struct bpf_map *pos;
11818 
11819 	bpf_object__for_each_map(pos, obj) {
11820 		/* if it's a special internal map name (which always starts
11821 		 * with dot) then check if that special name matches the
11822 		 * real map name (ELF section name)
11823 		 */
11824 		if (name[0] == '.') {
11825 			if (pos->real_name && strcmp(pos->real_name, name) == 0)
11826 				return pos;
11827 			continue;
11828 		}
11829 		/* otherwise map name has to be an exact match */
11830 		if (map_uses_real_name(pos)) {
11831 			if (strcmp(pos->real_name, name) == 0)
11832 				return pos;
11833 			continue;
11834 		}
11835 		if (strcmp(pos->name, name) == 0)
11836 			return pos;
11837 	}
11838 	return errno = ENOENT, NULL;
11839 }
11840 
11841 int
11842 bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
11843 {
11844 	return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
11845 }
11846 
11847 static int validate_map_op(const struct bpf_map *map, size_t key_sz,
11848 			   size_t value_sz, bool check_value_sz, __u64 flags)
11849 {
11850 	if (!map_is_created(map)) /* map is not yet created */
11851 		return -ENOENT;
11852 
11853 	if (map->def.key_size != key_sz) {
11854 		pr_warn("map '%s': unexpected key size %zu provided, expected %u\n",
11855 			map->name, key_sz, map->def.key_size);
11856 		return -EINVAL;
11857 	}
11858 
11859 	if (map->fd < 0) {
11860 		pr_warn("map '%s': can't use BPF map without FD (was it created?)\n", map->name);
11861 		return -EINVAL;
11862 	}
11863 
11864 	if (!check_value_sz)
11865 		return 0;
11866 
11867 	switch (map->def.type) {
11868 	case BPF_MAP_TYPE_PERCPU_ARRAY:
11869 	case BPF_MAP_TYPE_PERCPU_HASH:
11870 	case BPF_MAP_TYPE_LRU_PERCPU_HASH:
11871 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: {
11872 		int num_cpu = libbpf_num_possible_cpus();
11873 		size_t elem_sz = roundup(map->def.value_size, 8);
11874 
11875 		if (flags & (BPF_F_CPU | BPF_F_ALL_CPUS)) {
11876 			if ((flags & BPF_F_CPU) && (flags & BPF_F_ALL_CPUS)) {
11877 				pr_warn("map '%s': BPF_F_CPU and BPF_F_ALL_CPUS are mutually exclusive\n",
11878 					map->name);
11879 				return -EINVAL;
11880 			}
11881 			if (map->def.value_size != value_sz) {
11882 				pr_warn("map '%s': unexpected value size %zu provided for either BPF_F_CPU or BPF_F_ALL_CPUS, expected %u\n",
11883 					map->name, value_sz, map->def.value_size);
11884 				return -EINVAL;
11885 			}
11886 			break;
11887 		}
11888 
11889 		if (value_sz != num_cpu * elem_sz) {
11890 			pr_warn("map '%s': unexpected value size %zu provided for per-CPU map, expected %d * %zu = %zu\n",
11891 				map->name, value_sz, num_cpu, elem_sz, num_cpu * elem_sz);
11892 			return -EINVAL;
11893 		}
11894 		break;
11895 	}
11896 	default:
11897 		if (map->def.value_size != value_sz) {
11898 			pr_warn("map '%s': unexpected value size %zu provided, expected %u\n",
11899 				map->name, value_sz, map->def.value_size);
11900 			return -EINVAL;
11901 		}
11902 		break;
11903 	}
11904 	return 0;
11905 }
11906 
11907 int bpf_map__lookup_elem(const struct bpf_map *map,
11908 			 const void *key, size_t key_sz,
11909 			 void *value, size_t value_sz, __u64 flags)
11910 {
11911 	int err;
11912 
11913 	err = validate_map_op(map, key_sz, value_sz, true, flags);
11914 	if (err)
11915 		return libbpf_err(err);
11916 
11917 	return bpf_map_lookup_elem_flags(map->fd, key, value, flags);
11918 }
11919 
11920 int bpf_map__update_elem(const struct bpf_map *map,
11921 			 const void *key, size_t key_sz,
11922 			 const void *value, size_t value_sz, __u64 flags)
11923 {
11924 	int err;
11925 
11926 	err = validate_map_op(map, key_sz, value_sz, true, flags);
11927 	if (err)
11928 		return libbpf_err(err);
11929 
11930 	return bpf_map_update_elem(map->fd, key, value, flags);
11931 }
11932 
11933 int bpf_map__delete_elem(const struct bpf_map *map,
11934 			 const void *key, size_t key_sz, __u64 flags)
11935 {
11936 	int err;
11937 
11938 	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */, flags);
11939 	if (err)
11940 		return libbpf_err(err);
11941 
11942 	return bpf_map_delete_elem_flags(map->fd, key, flags);
11943 }
11944 
11945 int bpf_map__lookup_and_delete_elem(const struct bpf_map *map,
11946 				    const void *key, size_t key_sz,
11947 				    void *value, size_t value_sz, __u64 flags)
11948 {
11949 	int err;
11950 
11951 	err = validate_map_op(map, key_sz, value_sz, true, flags);
11952 	if (err)
11953 		return libbpf_err(err);
11954 
11955 	return bpf_map_lookup_and_delete_elem_flags(map->fd, key, value, flags);
11956 }
11957 
11958 int bpf_map__get_next_key(const struct bpf_map *map,
11959 			  const void *cur_key, void *next_key, size_t key_sz)
11960 {
11961 	int err;
11962 
11963 	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */, 0);
11964 	if (err)
11965 		return libbpf_err(err);
11966 
11967 	return bpf_map_get_next_key(map->fd, cur_key, next_key);
11968 }
11969 
11970 long libbpf_get_error(const void *ptr)
11971 {
11972 	if (!IS_ERR_OR_NULL(ptr))
11973 		return 0;
11974 
11975 	if (IS_ERR(ptr))
11976 		errno = -PTR_ERR(ptr);
11977 
11978 	/* If ptr == NULL, then errno should be already set by the failing
11979 	 * API, because libbpf never returns NULL on success and it now always
11980 	 * sets errno on error. So no extra errno handling for ptr == NULL
11981 	 * case.
11982 	 */
11983 	return -errno;
11984 }
11985 
11986 /* Replace link's underlying BPF program with the new one */
11987 int bpf_link__update_program(struct bpf_link *link, struct bpf_program *prog)
11988 {
11989 	int ret;
11990 	int prog_fd = bpf_program__fd(prog);
11991 
11992 	if (prog_fd < 0) {
11993 		pr_warn("prog '%s': can't use BPF program without FD (was it loaded?)\n",
11994 			prog->name);
11995 		return libbpf_err(-EINVAL);
11996 	}
11997 
11998 	ret = bpf_link_update(bpf_link__fd(link), prog_fd, NULL);
11999 	return libbpf_err_errno(ret);
12000 }
12001 
12002 /* Release "ownership" of underlying BPF resource (typically, BPF program
12003  * attached to some BPF hook, e.g., tracepoint, kprobe, etc). Disconnected
12004  * link, when destructed through bpf_link__destroy() call won't attempt to
12005  * detach/unregisted that BPF resource. This is useful in situations where,
12006  * say, attached BPF program has to outlive userspace program that attached it
12007  * in the system. Depending on type of BPF program, though, there might be
12008  * additional steps (like pinning BPF program in BPF FS) necessary to ensure
12009  * exit of userspace program doesn't trigger automatic detachment and clean up
12010  * inside the kernel.
12011  */
12012 void bpf_link__disconnect(struct bpf_link *link)
12013 {
12014 	link->disconnected = true;
12015 }
12016 
12017 int bpf_link__destroy(struct bpf_link *link)
12018 {
12019 	int err = 0;
12020 
12021 	if (IS_ERR_OR_NULL(link))
12022 		return 0;
12023 
12024 	if (!link->disconnected && link->detach)
12025 		err = link->detach(link);
12026 	if (link->pin_path)
12027 		free(link->pin_path);
12028 	if (link->dealloc)
12029 		link->dealloc(link);
12030 	else
12031 		free(link);
12032 
12033 	return libbpf_err(err);
12034 }
12035 
12036 int bpf_link__fd(const struct bpf_link *link)
12037 {
12038 	return link->fd;
12039 }
12040 
12041 const char *bpf_link__pin_path(const struct bpf_link *link)
12042 {
12043 	return link->pin_path;
12044 }
12045 
12046 static int bpf_link__detach_fd(struct bpf_link *link)
12047 {
12048 	return libbpf_err_errno(close(link->fd));
12049 }
12050 
12051 struct bpf_link *bpf_link__open(const char *path)
12052 {
12053 	struct bpf_link *link;
12054 	int fd;
12055 
12056 	fd = bpf_obj_get(path);
12057 	if (fd < 0) {
12058 		fd = -errno;
12059 		pr_warn("failed to open link at %s: %d\n", path, fd);
12060 		return libbpf_err_ptr(fd);
12061 	}
12062 
12063 	link = calloc(1, sizeof(*link));
12064 	if (!link) {
12065 		close(fd);
12066 		return libbpf_err_ptr(-ENOMEM);
12067 	}
12068 	link->detach = &bpf_link__detach_fd;
12069 	link->fd = fd;
12070 
12071 	link->pin_path = strdup(path);
12072 	if (!link->pin_path) {
12073 		bpf_link__destroy(link);
12074 		return libbpf_err_ptr(-ENOMEM);
12075 	}
12076 
12077 	return link;
12078 }
12079 
12080 int bpf_link__detach(struct bpf_link *link)
12081 {
12082 	return bpf_link_detach(link->fd) ? -errno : 0;
12083 }
12084 
12085 int bpf_link__pin(struct bpf_link *link, const char *path)
12086 {
12087 	int err;
12088 
12089 	if (link->pin_path)
12090 		return libbpf_err(-EBUSY);
12091 	err = make_parent_dir(path);
12092 	if (err)
12093 		return libbpf_err(err);
12094 	err = check_path(path);
12095 	if (err)
12096 		return libbpf_err(err);
12097 
12098 	link->pin_path = strdup(path);
12099 	if (!link->pin_path)
12100 		return libbpf_err(-ENOMEM);
12101 
12102 	if (bpf_obj_pin(link->fd, link->pin_path)) {
12103 		err = -errno;
12104 		zfree(&link->pin_path);
12105 		return libbpf_err(err);
12106 	}
12107 
12108 	pr_debug("link fd=%d: pinned at %s\n", link->fd, link->pin_path);
12109 	return 0;
12110 }
12111 
12112 int bpf_link__unpin(struct bpf_link *link)
12113 {
12114 	int err;
12115 
12116 	if (!link->pin_path)
12117 		return libbpf_err(-EINVAL);
12118 
12119 	err = unlink(link->pin_path);
12120 	if (err != 0)
12121 		return -errno;
12122 
12123 	pr_debug("link fd=%d: unpinned from %s\n", link->fd, link->pin_path);
12124 	zfree(&link->pin_path);
12125 	return 0;
12126 }
12127 
12128 struct bpf_link_perf {
12129 	struct bpf_link link;
12130 	int perf_event_fd;
12131 	/* legacy kprobe support: keep track of probe identifier and type */
12132 	char *legacy_probe_name;
12133 	bool legacy_is_kprobe;
12134 	bool legacy_is_retprobe;
12135 };
12136 
12137 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe);
12138 static int remove_uprobe_event_legacy(const char *probe_name, bool retprobe);
12139 
12140 static int bpf_link_perf_detach(struct bpf_link *link)
12141 {
12142 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
12143 	int err = 0;
12144 
12145 	if (ioctl(perf_link->perf_event_fd, PERF_EVENT_IOC_DISABLE, 0) < 0)
12146 		err = -errno;
12147 
12148 	if (perf_link->perf_event_fd != link->fd)
12149 		close(perf_link->perf_event_fd);
12150 	close(link->fd);
12151 
12152 	/* legacy uprobe/kprobe needs to be removed after perf event fd closure */
12153 	if (perf_link->legacy_probe_name) {
12154 		if (perf_link->legacy_is_kprobe) {
12155 			err = remove_kprobe_event_legacy(perf_link->legacy_probe_name,
12156 							 perf_link->legacy_is_retprobe);
12157 		} else {
12158 			err = remove_uprobe_event_legacy(perf_link->legacy_probe_name,
12159 							 perf_link->legacy_is_retprobe);
12160 		}
12161 	}
12162 
12163 	return err;
12164 }
12165 
12166 static void bpf_link_perf_dealloc(struct bpf_link *link)
12167 {
12168 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
12169 
12170 	free(perf_link->legacy_probe_name);
12171 	free(perf_link);
12172 }
12173 
12174 struct bpf_link *bpf_program__attach_perf_event_opts(const struct bpf_program *prog, int pfd,
12175 						     const struct bpf_perf_event_opts *opts)
12176 {
12177 	struct bpf_link_perf *link;
12178 	int prog_fd, link_fd = -1, err;
12179 	bool force_ioctl_attach;
12180 
12181 	if (!OPTS_VALID(opts, bpf_perf_event_opts))
12182 		return libbpf_err_ptr(-EINVAL);
12183 
12184 	if (pfd < 0) {
12185 		pr_warn("prog '%s': invalid perf event FD %d\n",
12186 			prog->name, pfd);
12187 		return libbpf_err_ptr(-EINVAL);
12188 	}
12189 	prog_fd = bpf_program__fd(prog);
12190 	if (prog_fd < 0) {
12191 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
12192 			prog->name);
12193 		return libbpf_err_ptr(-EINVAL);
12194 	}
12195 
12196 	link = calloc(1, sizeof(*link));
12197 	if (!link)
12198 		return libbpf_err_ptr(-ENOMEM);
12199 	link->link.detach = &bpf_link_perf_detach;
12200 	link->link.dealloc = &bpf_link_perf_dealloc;
12201 	link->perf_event_fd = pfd;
12202 
12203 	force_ioctl_attach = OPTS_GET(opts, force_ioctl_attach, false);
12204 	if (kernel_supports(prog->obj, FEAT_PERF_LINK) && !force_ioctl_attach) {
12205 		DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_opts,
12206 			.perf_event.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0));
12207 
12208 		link_fd = bpf_link_create(prog_fd, pfd, BPF_PERF_EVENT, &link_opts);
12209 		if (link_fd < 0) {
12210 			err = -errno;
12211 			pr_warn("prog '%s': failed to create BPF link for perf_event FD %d: %s\n",
12212 				prog->name, pfd, errstr(err));
12213 			goto err_out;
12214 		}
12215 		link->link.fd = link_fd;
12216 	} else {
12217 		if (OPTS_GET(opts, bpf_cookie, 0)) {
12218 			pr_warn("prog '%s': user context value is not supported\n", prog->name);
12219 			err = -EOPNOTSUPP;
12220 			goto err_out;
12221 		}
12222 
12223 		if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
12224 			err = -errno;
12225 			pr_warn("prog '%s': failed to attach to perf_event FD %d: %s\n",
12226 				prog->name, pfd, errstr(err));
12227 			if (err == -EPROTO)
12228 				pr_warn("prog '%s': try add PERF_SAMPLE_CALLCHAIN to or remove exclude_callchain_[kernel|user] from pfd %d\n",
12229 					prog->name, pfd);
12230 			goto err_out;
12231 		}
12232 		link->link.fd = pfd;
12233 	}
12234 
12235 	if (!OPTS_GET(opts, dont_enable, false)) {
12236 		if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
12237 			err = -errno;
12238 			pr_warn("prog '%s': failed to enable perf_event FD %d: %s\n",
12239 				prog->name, pfd, errstr(err));
12240 			goto err_out;
12241 		}
12242 	}
12243 
12244 	return &link->link;
12245 err_out:
12246 	if (link_fd >= 0)
12247 		close(link_fd);
12248 	free(link);
12249 	return libbpf_err_ptr(err);
12250 }
12251 
12252 struct bpf_link *bpf_program__attach_perf_event(const struct bpf_program *prog, int pfd)
12253 {
12254 	return bpf_program__attach_perf_event_opts(prog, pfd, NULL);
12255 }
12256 
12257 /*
12258  * this function is expected to parse integer in the range of [0, 2^31-1] from
12259  * given file using scanf format string fmt. If actual parsed value is
12260  * negative, the result might be indistinguishable from error
12261  */
12262 static int parse_uint_from_file(const char *file, const char *fmt)
12263 {
12264 	int err, ret;
12265 	FILE *f;
12266 
12267 	f = fopen(file, "re");
12268 	if (!f) {
12269 		err = -errno;
12270 		pr_debug("failed to open '%s': %s\n", file, errstr(err));
12271 		return err;
12272 	}
12273 	err = fscanf(f, fmt, &ret);
12274 	if (err != 1) {
12275 		err = err == EOF ? -EIO : -errno;
12276 		pr_debug("failed to parse '%s': %s\n", file, errstr(err));
12277 		fclose(f);
12278 		return err;
12279 	}
12280 	fclose(f);
12281 	return ret;
12282 }
12283 
12284 static int determine_kprobe_perf_type(void)
12285 {
12286 	const char *file = "/sys/bus/event_source/devices/kprobe/type";
12287 
12288 	return parse_uint_from_file(file, "%d\n");
12289 }
12290 
12291 static int determine_uprobe_perf_type(void)
12292 {
12293 	const char *file = "/sys/bus/event_source/devices/uprobe/type";
12294 
12295 	return parse_uint_from_file(file, "%d\n");
12296 }
12297 
12298 static int determine_kprobe_retprobe_bit(void)
12299 {
12300 	const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
12301 
12302 	return parse_uint_from_file(file, "config:%d\n");
12303 }
12304 
12305 static int determine_uprobe_retprobe_bit(void)
12306 {
12307 	const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
12308 
12309 	return parse_uint_from_file(file, "config:%d\n");
12310 }
12311 
12312 #define PERF_UPROBE_REF_CTR_OFFSET_BITS 32
12313 #define PERF_UPROBE_REF_CTR_OFFSET_SHIFT 32
12314 
12315 static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
12316 				 uint64_t offset, int pid, size_t ref_ctr_off)
12317 {
12318 	const size_t attr_sz = sizeof(struct perf_event_attr);
12319 	struct perf_event_attr attr;
12320 	int type, pfd;
12321 
12322 	if ((__u64)ref_ctr_off >= (1ULL << PERF_UPROBE_REF_CTR_OFFSET_BITS))
12323 		return -EINVAL;
12324 
12325 	memset(&attr, 0, attr_sz);
12326 
12327 	type = uprobe ? determine_uprobe_perf_type()
12328 		      : determine_kprobe_perf_type();
12329 	if (type < 0) {
12330 		pr_warn("failed to determine %s perf type: %s\n",
12331 			uprobe ? "uprobe" : "kprobe",
12332 			errstr(type));
12333 		return type;
12334 	}
12335 	if (retprobe) {
12336 		int bit = uprobe ? determine_uprobe_retprobe_bit()
12337 				 : determine_kprobe_retprobe_bit();
12338 
12339 		if (bit < 0) {
12340 			pr_warn("failed to determine %s retprobe bit: %s\n",
12341 				uprobe ? "uprobe" : "kprobe",
12342 				errstr(bit));
12343 			return bit;
12344 		}
12345 		attr.config |= 1ULL << bit;
12346 	}
12347 	attr.size = attr_sz;
12348 	attr.type = type;
12349 	attr.config |= (__u64)ref_ctr_off << PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
12350 	attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
12351 	attr.config2 = offset;		 /* kprobe_addr or probe_offset */
12352 
12353 	/* pid filter is meaningful only for uprobes */
12354 	pfd = syscall(__NR_perf_event_open, &attr,
12355 		      pid < 0 ? -1 : pid /* pid */,
12356 		      pid == -1 ? 0 : -1 /* cpu */,
12357 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
12358 	return pfd >= 0 ? pfd : -errno;
12359 }
12360 
12361 static int append_to_file(const char *file, const char *fmt, ...)
12362 {
12363 	int fd, n, err = 0;
12364 	va_list ap;
12365 	char buf[1024];
12366 
12367 	va_start(ap, fmt);
12368 	n = vsnprintf(buf, sizeof(buf), fmt, ap);
12369 	va_end(ap);
12370 
12371 	if (n < 0 || n >= sizeof(buf))
12372 		return -EINVAL;
12373 
12374 	fd = open(file, O_WRONLY | O_APPEND | O_CLOEXEC, 0);
12375 	if (fd < 0)
12376 		return -errno;
12377 
12378 	if (write(fd, buf, n) < 0)
12379 		err = -errno;
12380 
12381 	close(fd);
12382 	return err;
12383 }
12384 
12385 #define DEBUGFS "/sys/kernel/debug/tracing"
12386 #define TRACEFS "/sys/kernel/tracing"
12387 
12388 static bool use_debugfs(void)
12389 {
12390 	static int has_debugfs = -1;
12391 
12392 	if (has_debugfs < 0)
12393 		has_debugfs = faccessat(AT_FDCWD, DEBUGFS, F_OK, AT_EACCESS) == 0;
12394 
12395 	return has_debugfs == 1;
12396 }
12397 
12398 static const char *tracefs_path(void)
12399 {
12400 	return use_debugfs() ? DEBUGFS : TRACEFS;
12401 }
12402 
12403 static const char *tracefs_kprobe_events(void)
12404 {
12405 	return use_debugfs() ? DEBUGFS"/kprobe_events" : TRACEFS"/kprobe_events";
12406 }
12407 
12408 static const char *tracefs_uprobe_events(void)
12409 {
12410 	return use_debugfs() ? DEBUGFS"/uprobe_events" : TRACEFS"/uprobe_events";
12411 }
12412 
12413 static const char *tracefs_available_filter_functions(void)
12414 {
12415 	return use_debugfs() ? DEBUGFS"/available_filter_functions"
12416 			     : TRACEFS"/available_filter_functions";
12417 }
12418 
12419 static const char *tracefs_available_filter_functions_addrs(void)
12420 {
12421 	return use_debugfs() ? DEBUGFS"/available_filter_functions_addrs"
12422 			     : TRACEFS"/available_filter_functions_addrs";
12423 }
12424 
12425 static void gen_probe_legacy_event_name(char *buf, size_t buf_sz,
12426 					const char *name, size_t offset)
12427 {
12428 	static int index = 0;
12429 	int i;
12430 
12431 	snprintf(buf, buf_sz, "libbpf_%d_%d_%s_0x%zx", getpid(),
12432 		 __sync_fetch_and_add(&index, 1), name, offset);
12433 
12434 	/* sanitize name in the probe name */
12435 	for (i = 0; buf[i]; i++) {
12436 		if (!isalnum(buf[i]))
12437 			buf[i] = '_';
12438 	}
12439 }
12440 
12441 static int add_kprobe_event_legacy(const char *probe_name, bool retprobe,
12442 				   const char *kfunc_name, size_t offset)
12443 {
12444 	return append_to_file(tracefs_kprobe_events(), "%c:%s/%s %s+0x%zx",
12445 			      retprobe ? 'r' : 'p',
12446 			      retprobe ? "kretprobes" : "kprobes",
12447 			      probe_name, kfunc_name, offset);
12448 }
12449 
12450 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe)
12451 {
12452 	return append_to_file(tracefs_kprobe_events(), "-:%s/%s",
12453 			      retprobe ? "kretprobes" : "kprobes", probe_name);
12454 }
12455 
12456 static int determine_kprobe_perf_type_legacy(const char *probe_name, bool retprobe)
12457 {
12458 	char file[256];
12459 
12460 	snprintf(file, sizeof(file), "%s/events/%s/%s/id",
12461 		 tracefs_path(), retprobe ? "kretprobes" : "kprobes", probe_name);
12462 
12463 	return parse_uint_from_file(file, "%d\n");
12464 }
12465 
12466 static int perf_event_kprobe_open_legacy(const char *probe_name, bool retprobe,
12467 					 const char *kfunc_name, size_t offset, int pid)
12468 {
12469 	const size_t attr_sz = sizeof(struct perf_event_attr);
12470 	struct perf_event_attr attr;
12471 	int type, pfd, err;
12472 
12473 	err = add_kprobe_event_legacy(probe_name, retprobe, kfunc_name, offset);
12474 	if (err < 0) {
12475 		pr_warn("failed to add legacy kprobe event for '%s+0x%zx': %s\n",
12476 			kfunc_name, offset,
12477 			errstr(err));
12478 		return err;
12479 	}
12480 	type = determine_kprobe_perf_type_legacy(probe_name, retprobe);
12481 	if (type < 0) {
12482 		err = type;
12483 		pr_warn("failed to determine legacy kprobe event id for '%s+0x%zx': %s\n",
12484 			kfunc_name, offset,
12485 			errstr(err));
12486 		goto err_clean_legacy;
12487 	}
12488 
12489 	memset(&attr, 0, attr_sz);
12490 	attr.size = attr_sz;
12491 	attr.config = type;
12492 	attr.type = PERF_TYPE_TRACEPOINT;
12493 
12494 	pfd = syscall(__NR_perf_event_open, &attr,
12495 		      pid < 0 ? -1 : pid, /* pid */
12496 		      pid == -1 ? 0 : -1, /* cpu */
12497 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
12498 	if (pfd < 0) {
12499 		err = -errno;
12500 		pr_warn("legacy kprobe perf_event_open() failed: %s\n",
12501 			errstr(err));
12502 		goto err_clean_legacy;
12503 	}
12504 	return pfd;
12505 
12506 err_clean_legacy:
12507 	/* Clear the newly added legacy kprobe_event */
12508 	remove_kprobe_event_legacy(probe_name, retprobe);
12509 	return err;
12510 }
12511 
12512 static const char *arch_specific_syscall_pfx(void)
12513 {
12514 #if defined(__x86_64__)
12515 	return "x64";
12516 #elif defined(__i386__)
12517 	return "ia32";
12518 #elif defined(__s390x__)
12519 	return "s390x";
12520 #elif defined(__arm__)
12521 	return "arm";
12522 #elif defined(__aarch64__)
12523 	return "arm64";
12524 #elif defined(__mips__)
12525 	return "mips";
12526 #elif defined(__riscv)
12527 	return "riscv";
12528 #elif defined(__powerpc__)
12529 	return "powerpc";
12530 #elif defined(__powerpc64__)
12531 	return "powerpc64";
12532 #else
12533 	return NULL;
12534 #endif
12535 }
12536 
12537 int probe_kern_syscall_wrapper(int token_fd)
12538 {
12539 	char syscall_name[64];
12540 	const char *ksys_pfx;
12541 
12542 	ksys_pfx = arch_specific_syscall_pfx();
12543 	if (!ksys_pfx)
12544 		return 0;
12545 
12546 	snprintf(syscall_name, sizeof(syscall_name), "__%s_sys_bpf", ksys_pfx);
12547 
12548 	if (determine_kprobe_perf_type() >= 0) {
12549 		int pfd;
12550 
12551 		pfd = perf_event_open_probe(false, false, syscall_name, 0, getpid(), 0);
12552 		if (pfd >= 0)
12553 			close(pfd);
12554 
12555 		return pfd >= 0 ? 1 : 0;
12556 	} else { /* legacy mode */
12557 		char probe_name[MAX_EVENT_NAME_LEN];
12558 
12559 		gen_probe_legacy_event_name(probe_name, sizeof(probe_name), syscall_name, 0);
12560 		if (add_kprobe_event_legacy(probe_name, false, syscall_name, 0) < 0)
12561 			return 0;
12562 
12563 		(void)remove_kprobe_event_legacy(probe_name, false);
12564 		return 1;
12565 	}
12566 }
12567 
12568 struct bpf_link *
12569 bpf_program__attach_kprobe_opts(const struct bpf_program *prog,
12570 				const char *func_name,
12571 				const struct bpf_kprobe_opts *opts)
12572 {
12573 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
12574 	enum probe_attach_mode attach_mode;
12575 	char *legacy_probe = NULL;
12576 	struct bpf_link *link;
12577 	size_t offset;
12578 	bool retprobe, legacy;
12579 	int pfd, err;
12580 
12581 	if (!OPTS_VALID(opts, bpf_kprobe_opts))
12582 		return libbpf_err_ptr(-EINVAL);
12583 
12584 	attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
12585 	retprobe = OPTS_GET(opts, retprobe, false);
12586 	offset = OPTS_GET(opts, offset, 0);
12587 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
12588 
12589 	legacy = determine_kprobe_perf_type() < 0;
12590 	switch (attach_mode) {
12591 	case PROBE_ATTACH_MODE_LEGACY:
12592 		legacy = true;
12593 		pe_opts.force_ioctl_attach = true;
12594 		break;
12595 	case PROBE_ATTACH_MODE_PERF:
12596 		if (legacy)
12597 			return libbpf_err_ptr(-ENOTSUP);
12598 		pe_opts.force_ioctl_attach = true;
12599 		break;
12600 	case PROBE_ATTACH_MODE_LINK:
12601 		if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
12602 			return libbpf_err_ptr(-ENOTSUP);
12603 		break;
12604 	case PROBE_ATTACH_MODE_DEFAULT:
12605 		break;
12606 	default:
12607 		return libbpf_err_ptr(-EINVAL);
12608 	}
12609 	if (!func_name && legacy)
12610 		return libbpf_err_ptr(-EOPNOTSUPP);
12611 
12612 	if (!legacy) {
12613 		pfd = perf_event_open_probe(false /* uprobe */, retprobe,
12614 					    func_name, offset,
12615 					    -1 /* pid */, 0 /* ref_ctr_off */);
12616 	} else {
12617 		char probe_name[MAX_EVENT_NAME_LEN];
12618 
12619 		gen_probe_legacy_event_name(probe_name, sizeof(probe_name),
12620 					    func_name, offset);
12621 
12622 		legacy_probe = strdup(probe_name);
12623 		if (!legacy_probe)
12624 			return libbpf_err_ptr(-ENOMEM);
12625 
12626 		pfd = perf_event_kprobe_open_legacy(legacy_probe, retprobe, func_name,
12627 						    offset, -1 /* pid */);
12628 	}
12629 	if (pfd < 0) {
12630 		err = pfd;
12631 		pr_warn("prog '%s': failed to create %s '%s%s0x%zx' perf event: %s\n",
12632 			prog->name, retprobe ? "kretprobe" : "kprobe",
12633 			func_name ?: "", func_name ? "+" : "",
12634 			offset, errstr(err));
12635 		goto err_out;
12636 	}
12637 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
12638 	err = libbpf_get_error(link);
12639 	if (err) {
12640 		close(pfd);
12641 		pr_warn("prog '%s': failed to attach to %s '%s%s0x%zx': %s\n",
12642 			prog->name, retprobe ? "kretprobe" : "kprobe",
12643 			func_name ?: "", func_name ? "+" : "",
12644 			offset, errstr(err));
12645 		goto err_clean_legacy;
12646 	}
12647 	if (legacy) {
12648 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
12649 
12650 		perf_link->legacy_probe_name = legacy_probe;
12651 		perf_link->legacy_is_kprobe = true;
12652 		perf_link->legacy_is_retprobe = retprobe;
12653 	}
12654 
12655 	return link;
12656 
12657 err_clean_legacy:
12658 	if (legacy)
12659 		remove_kprobe_event_legacy(legacy_probe, retprobe);
12660 err_out:
12661 	free(legacy_probe);
12662 	return libbpf_err_ptr(err);
12663 }
12664 
12665 struct bpf_link *bpf_program__attach_kprobe(const struct bpf_program *prog,
12666 					    bool retprobe,
12667 					    const char *func_name)
12668 {
12669 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts,
12670 		.retprobe = retprobe,
12671 	);
12672 
12673 	return bpf_program__attach_kprobe_opts(prog, func_name, &opts);
12674 }
12675 
12676 struct bpf_link *bpf_program__attach_ksyscall(const struct bpf_program *prog,
12677 					      const char *syscall_name,
12678 					      const struct bpf_ksyscall_opts *opts)
12679 {
12680 	LIBBPF_OPTS(bpf_kprobe_opts, kprobe_opts);
12681 	char func_name[128];
12682 
12683 	if (!OPTS_VALID(opts, bpf_ksyscall_opts))
12684 		return libbpf_err_ptr(-EINVAL);
12685 
12686 	if (kernel_supports(prog->obj, FEAT_SYSCALL_WRAPPER)) {
12687 		/* arch_specific_syscall_pfx() should never return NULL here
12688 		 * because it is guarded by kernel_supports(). However, since
12689 		 * compiler does not know that we have an explicit conditional
12690 		 * as well.
12691 		 */
12692 		snprintf(func_name, sizeof(func_name), "__%s_sys_%s",
12693 			 arch_specific_syscall_pfx() ? : "", syscall_name);
12694 	} else {
12695 		snprintf(func_name, sizeof(func_name), "__se_sys_%s", syscall_name);
12696 	}
12697 
12698 	kprobe_opts.retprobe = OPTS_GET(opts, retprobe, false);
12699 	kprobe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
12700 
12701 	return bpf_program__attach_kprobe_opts(prog, func_name, &kprobe_opts);
12702 }
12703 
12704 /* Adapted from perf/util/string.c */
12705 bool glob_match(const char *str, const char *pat)
12706 {
12707 	while (*str && *pat && *pat != '*') {
12708 		if (*pat == '?') {      /* Matches any single character */
12709 			str++;
12710 			pat++;
12711 			continue;
12712 		}
12713 		if (*str != *pat)
12714 			return false;
12715 		str++;
12716 		pat++;
12717 	}
12718 	/* Check wild card */
12719 	if (*pat == '*') {
12720 		while (*pat == '*')
12721 			pat++;
12722 		if (!*pat) /* Tail wild card matches all */
12723 			return true;
12724 		while (*str)
12725 			if (glob_match(str++, pat))
12726 				return true;
12727 	}
12728 	return !*str && !*pat;
12729 }
12730 
12731 struct kprobe_multi_resolve {
12732 	const char *pattern;
12733 	unsigned long *addrs;
12734 	size_t cap;
12735 	size_t cnt;
12736 };
12737 
12738 struct avail_kallsyms_data {
12739 	char **syms;
12740 	size_t cnt;
12741 	struct kprobe_multi_resolve *res;
12742 };
12743 
12744 static int avail_func_cmp(const void *a, const void *b)
12745 {
12746 	return strcmp(*(const char **)a, *(const char **)b);
12747 }
12748 
12749 static int avail_kallsyms_cb(unsigned long long sym_addr, char sym_type,
12750 			     const char *sym_name, void *ctx)
12751 {
12752 	struct avail_kallsyms_data *data = ctx;
12753 	struct kprobe_multi_resolve *res = data->res;
12754 	int err;
12755 
12756 	if (!glob_match(sym_name, res->pattern))
12757 		return 0;
12758 
12759 	if (!bsearch(&sym_name, data->syms, data->cnt, sizeof(*data->syms), avail_func_cmp)) {
12760 		/* Some versions of kernel strip out .llvm.<hash> suffix from
12761 		 * function names reported in available_filter_functions, but
12762 		 * don't do so for kallsyms. While this is clearly a kernel
12763 		 * bug (fixed by [0]) we try to accommodate that in libbpf to
12764 		 * make multi-kprobe usability a bit better: if no match is
12765 		 * found, we will strip .llvm. suffix and try one more time.
12766 		 *
12767 		 *   [0] fb6a421fb615 ("kallsyms: Match symbols exactly with CONFIG_LTO_CLANG")
12768 		 */
12769 		char sym_trim[256], *psym_trim = sym_trim;
12770 		const char *sym_sfx;
12771 
12772 		if (!(sym_sfx = strstr(sym_name, ".llvm.")))
12773 			return 0;
12774 
12775 		/* psym_trim vs sym_trim dance is done to avoid pointer vs array
12776 		 * coercion differences and get proper `const char **` pointer
12777 		 * which avail_func_cmp() expects
12778 		 */
12779 		snprintf(sym_trim, sizeof(sym_trim), "%.*s", (int)(sym_sfx - sym_name), sym_name);
12780 		if (!bsearch(&psym_trim, data->syms, data->cnt, sizeof(*data->syms), avail_func_cmp))
12781 			return 0;
12782 	}
12783 
12784 	err = libbpf_ensure_mem((void **)&res->addrs, &res->cap, sizeof(*res->addrs), res->cnt + 1);
12785 	if (err)
12786 		return err;
12787 
12788 	res->addrs[res->cnt++] = (unsigned long)sym_addr;
12789 	return 0;
12790 }
12791 
12792 static int libbpf_available_kallsyms_parse(struct kprobe_multi_resolve *res)
12793 {
12794 	const char *available_functions_file = tracefs_available_filter_functions();
12795 	struct avail_kallsyms_data data;
12796 	char sym_name[500];
12797 	FILE *f;
12798 	int err = 0, ret, i;
12799 	char **syms = NULL;
12800 	size_t cap = 0, cnt = 0;
12801 
12802 	f = fopen(available_functions_file, "re");
12803 	if (!f) {
12804 		err = -errno;
12805 		pr_warn("failed to open %s: %s\n", available_functions_file, errstr(err));
12806 		return err;
12807 	}
12808 
12809 	while (true) {
12810 		char *name;
12811 
12812 		ret = fscanf(f, "%499s%*[^\n]\n", sym_name);
12813 		if (ret == EOF && feof(f))
12814 			break;
12815 
12816 		if (ret != 1) {
12817 			pr_warn("failed to parse available_filter_functions entry: %d\n", ret);
12818 			err = -EINVAL;
12819 			goto cleanup;
12820 		}
12821 
12822 		if (!glob_match(sym_name, res->pattern))
12823 			continue;
12824 
12825 		err = libbpf_ensure_mem((void **)&syms, &cap, sizeof(*syms), cnt + 1);
12826 		if (err)
12827 			goto cleanup;
12828 
12829 		name = strdup(sym_name);
12830 		if (!name) {
12831 			err = -errno;
12832 			goto cleanup;
12833 		}
12834 
12835 		syms[cnt++] = name;
12836 	}
12837 
12838 	/* no entries found, bail out */
12839 	if (cnt == 0) {
12840 		err = -ENOENT;
12841 		goto cleanup;
12842 	}
12843 
12844 	/* sort available functions */
12845 	qsort(syms, cnt, sizeof(*syms), avail_func_cmp);
12846 
12847 	data.syms = syms;
12848 	data.res = res;
12849 	data.cnt = cnt;
12850 	libbpf_kallsyms_parse(avail_kallsyms_cb, &data);
12851 
12852 	if (res->cnt == 0)
12853 		err = -ENOENT;
12854 
12855 cleanup:
12856 	for (i = 0; i < cnt; i++)
12857 		free((char *)syms[i]);
12858 	free(syms);
12859 
12860 	fclose(f);
12861 	return err;
12862 }
12863 
12864 static bool has_available_filter_functions_addrs(void)
12865 {
12866 	return access(tracefs_available_filter_functions_addrs(), R_OK) != -1;
12867 }
12868 
12869 static int libbpf_available_kprobes_parse(struct kprobe_multi_resolve *res)
12870 {
12871 	const char *available_path = tracefs_available_filter_functions_addrs();
12872 	char sym_name[500];
12873 	FILE *f;
12874 	int ret, err = 0;
12875 	unsigned long long sym_addr;
12876 
12877 	f = fopen(available_path, "re");
12878 	if (!f) {
12879 		err = -errno;
12880 		pr_warn("failed to open %s: %s\n", available_path, errstr(err));
12881 		return err;
12882 	}
12883 
12884 	while (true) {
12885 		ret = fscanf(f, "%llx %499s%*[^\n]\n", &sym_addr, sym_name);
12886 		if (ret == EOF && feof(f))
12887 			break;
12888 
12889 		if (ret != 2) {
12890 			pr_warn("failed to parse available_filter_functions_addrs entry: %d\n",
12891 				ret);
12892 			err = -EINVAL;
12893 			goto cleanup;
12894 		}
12895 
12896 		if (!glob_match(sym_name, res->pattern))
12897 			continue;
12898 
12899 		err = libbpf_ensure_mem((void **)&res->addrs, &res->cap,
12900 					sizeof(*res->addrs), res->cnt + 1);
12901 		if (err)
12902 			goto cleanup;
12903 
12904 		res->addrs[res->cnt++] = (unsigned long)sym_addr;
12905 	}
12906 
12907 	if (res->cnt == 0)
12908 		err = -ENOENT;
12909 
12910 cleanup:
12911 	fclose(f);
12912 	return err;
12913 }
12914 
12915 struct bpf_link *
12916 bpf_program__attach_kprobe_multi_opts(const struct bpf_program *prog,
12917 				      const char *pattern,
12918 				      const struct bpf_kprobe_multi_opts *opts)
12919 {
12920 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
12921 	struct kprobe_multi_resolve res = {
12922 		.pattern = pattern,
12923 	};
12924 	enum bpf_attach_type attach_type;
12925 	struct bpf_link *link = NULL;
12926 	const unsigned long *addrs;
12927 	int err, link_fd, prog_fd;
12928 	bool retprobe, session, unique_match;
12929 	const __u64 *cookies;
12930 	const char **syms;
12931 	size_t cnt;
12932 
12933 	if (!OPTS_VALID(opts, bpf_kprobe_multi_opts))
12934 		return libbpf_err_ptr(-EINVAL);
12935 
12936 	prog_fd = bpf_program__fd(prog);
12937 	if (prog_fd < 0) {
12938 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
12939 			prog->name);
12940 		return libbpf_err_ptr(-EINVAL);
12941 	}
12942 
12943 	syms    = OPTS_GET(opts, syms, false);
12944 	addrs   = OPTS_GET(opts, addrs, false);
12945 	cnt     = OPTS_GET(opts, cnt, false);
12946 	cookies = OPTS_GET(opts, cookies, false);
12947 	unique_match = OPTS_GET(opts, unique_match, false);
12948 
12949 	if (!pattern && !addrs && !syms)
12950 		return libbpf_err_ptr(-EINVAL);
12951 	if (pattern && (addrs || syms || cookies || cnt))
12952 		return libbpf_err_ptr(-EINVAL);
12953 	if (!pattern && !cnt)
12954 		return libbpf_err_ptr(-EINVAL);
12955 	if (!pattern && unique_match)
12956 		return libbpf_err_ptr(-EINVAL);
12957 	if (addrs && syms)
12958 		return libbpf_err_ptr(-EINVAL);
12959 
12960 	/*
12961 	 * Exact function name (no wildcards) without unique_match:
12962 	 * bypass kallsyms parsing and pass the symbol directly to the
12963 	 * kernel via syms[] array.  When unique_match is set, fall
12964 	 * through to the slow path which detects duplicate symbols.
12965 	 */
12966 	if (pattern && !strpbrk(pattern, "*?") && !unique_match) {
12967 		syms = &pattern;
12968 		cnt = 1;
12969 	} else if (pattern) {
12970 		if (has_available_filter_functions_addrs())
12971 			err = libbpf_available_kprobes_parse(&res);
12972 		else
12973 			err = libbpf_available_kallsyms_parse(&res);
12974 		if (err)
12975 			goto error;
12976 
12977 		if (unique_match && res.cnt != 1) {
12978 			pr_warn("prog '%s': failed to find a unique match for '%s' (%zu matches)\n",
12979 				prog->name, pattern, res.cnt);
12980 			err = -EINVAL;
12981 			goto error;
12982 		}
12983 
12984 		addrs = res.addrs;
12985 		cnt = res.cnt;
12986 	}
12987 
12988 	retprobe = OPTS_GET(opts, retprobe, false);
12989 	session  = OPTS_GET(opts, session, false);
12990 
12991 	if (retprobe && session)
12992 		return libbpf_err_ptr(-EINVAL);
12993 
12994 	attach_type = session ? BPF_TRACE_KPROBE_SESSION : BPF_TRACE_KPROBE_MULTI;
12995 
12996 	lopts.kprobe_multi.syms = syms;
12997 	lopts.kprobe_multi.addrs = addrs;
12998 	lopts.kprobe_multi.cookies = cookies;
12999 	lopts.kprobe_multi.cnt = cnt;
13000 	lopts.kprobe_multi.flags = retprobe ? BPF_F_KPROBE_MULTI_RETURN : 0;
13001 
13002 	link = calloc(1, sizeof(*link));
13003 	if (!link) {
13004 		err = -ENOMEM;
13005 		goto error;
13006 	}
13007 	link->detach = &bpf_link__detach_fd;
13008 
13009 	link_fd = bpf_link_create(prog_fd, 0, attach_type, &lopts);
13010 	if (link_fd < 0) {
13011 		err = -errno;
13012 		/*
13013 		 * Normalize error code: when exact name bypasses kallsyms
13014 		 * parsing, kernel returns ESRCH from ftrace_lookup_symbols().
13015 		 * Convert to ENOENT for API consistency with the pattern
13016 		 * matching path which returns ENOENT from userspace.
13017 		 */
13018 		if (err == -ESRCH)
13019 			err = -ENOENT;
13020 		pr_warn("prog '%s': failed to attach: %s\n",
13021 			prog->name, errstr(err));
13022 		goto error;
13023 	}
13024 	link->fd = link_fd;
13025 	free(res.addrs);
13026 	return link;
13027 
13028 error:
13029 	free(link);
13030 	free(res.addrs);
13031 	return libbpf_err_ptr(err);
13032 }
13033 
13034 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
13035 {
13036 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts);
13037 	long offset = 0;
13038 	const char *func_name;
13039 	char *func;
13040 	int n;
13041 
13042 	*link = NULL;
13043 
13044 	/* no auto-attach for SEC("kprobe") and SEC("kretprobe") */
13045 	if (strcmp(prog->sec_name, "kprobe") == 0 || strcmp(prog->sec_name, "kretprobe") == 0)
13046 		return 0;
13047 
13048 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe/");
13049 	if (opts.retprobe)
13050 		func_name = prog->sec_name + sizeof("kretprobe/") - 1;
13051 	else
13052 		func_name = prog->sec_name + sizeof("kprobe/") - 1;
13053 
13054 	n = sscanf(func_name, "%m[a-zA-Z0-9_.]+%li", &func, &offset);
13055 	if (n < 1) {
13056 		pr_warn("kprobe name is invalid: %s\n", func_name);
13057 		return -EINVAL;
13058 	}
13059 
13060 	if (offset < 0) {
13061 		free(func);
13062 		pr_warn("kprobe offset must be a non-negative integer: %li\n", offset);
13063 		return -EINVAL;
13064 	}
13065 
13066 	if (opts.retprobe && offset != 0) {
13067 		free(func);
13068 		pr_warn("kretprobes do not support offset specification\n");
13069 		return -EINVAL;
13070 	}
13071 
13072 	opts.offset = offset;
13073 	*link = bpf_program__attach_kprobe_opts(prog, func, &opts);
13074 	free(func);
13075 	return libbpf_get_error(*link);
13076 }
13077 
13078 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link)
13079 {
13080 	LIBBPF_OPTS(bpf_ksyscall_opts, opts);
13081 	const char *syscall_name;
13082 
13083 	*link = NULL;
13084 
13085 	/* no auto-attach for SEC("ksyscall") and SEC("kretsyscall") */
13086 	if (strcmp(prog->sec_name, "ksyscall") == 0 || strcmp(prog->sec_name, "kretsyscall") == 0)
13087 		return 0;
13088 
13089 	opts.retprobe = str_has_pfx(prog->sec_name, "kretsyscall/");
13090 	if (opts.retprobe)
13091 		syscall_name = prog->sec_name + sizeof("kretsyscall/") - 1;
13092 	else
13093 		syscall_name = prog->sec_name + sizeof("ksyscall/") - 1;
13094 
13095 	*link = bpf_program__attach_ksyscall(prog, syscall_name, &opts);
13096 	return *link ? 0 : -errno;
13097 }
13098 
13099 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
13100 {
13101 	LIBBPF_OPTS(bpf_kprobe_multi_opts, opts);
13102 	const char *spec;
13103 	char *pattern;
13104 	int n;
13105 
13106 	*link = NULL;
13107 
13108 	/* no auto-attach for SEC("kprobe.multi") and SEC("kretprobe.multi") */
13109 	if (strcmp(prog->sec_name, "kprobe.multi") == 0 ||
13110 	    strcmp(prog->sec_name, "kretprobe.multi") == 0)
13111 		return 0;
13112 
13113 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe.multi/");
13114 	if (opts.retprobe)
13115 		spec = prog->sec_name + sizeof("kretprobe.multi/") - 1;
13116 	else
13117 		spec = prog->sec_name + sizeof("kprobe.multi/") - 1;
13118 
13119 	n = sscanf(spec, "%m[a-zA-Z0-9_.*?]", &pattern);
13120 	if (n < 1) {
13121 		pr_warn("kprobe multi pattern is invalid: %s\n", spec);
13122 		return -EINVAL;
13123 	}
13124 
13125 	*link = bpf_program__attach_kprobe_multi_opts(prog, pattern, &opts);
13126 	free(pattern);
13127 	return libbpf_get_error(*link);
13128 }
13129 
13130 static int attach_kprobe_session(const struct bpf_program *prog, long cookie,
13131 				 struct bpf_link **link)
13132 {
13133 	LIBBPF_OPTS(bpf_kprobe_multi_opts, opts, .session = true);
13134 	const char *spec;
13135 	char *pattern;
13136 	int n;
13137 
13138 	*link = NULL;
13139 
13140 	/* no auto-attach for SEC("kprobe.session") */
13141 	if (strcmp(prog->sec_name, "kprobe.session") == 0)
13142 		return 0;
13143 
13144 	spec = prog->sec_name + sizeof("kprobe.session/") - 1;
13145 	n = sscanf(spec, "%m[a-zA-Z0-9_.*?]", &pattern);
13146 	if (n < 1) {
13147 		pr_warn("kprobe session pattern is invalid: %s\n", spec);
13148 		return -EINVAL;
13149 	}
13150 
13151 	*link = bpf_program__attach_kprobe_multi_opts(prog, pattern, &opts);
13152 	free(pattern);
13153 	return *link ? 0 : -errno;
13154 }
13155 
13156 static int attach_uprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
13157 {
13158 	char *probe_type = NULL, *binary_path = NULL, *func_name = NULL;
13159 	LIBBPF_OPTS(bpf_uprobe_multi_opts, opts);
13160 	int n, ret = -EINVAL;
13161 
13162 	*link = NULL;
13163 
13164 	n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[^\n]",
13165 		   &probe_type, &binary_path, &func_name);
13166 	switch (n) {
13167 	case 1:
13168 		/* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
13169 		ret = 0;
13170 		break;
13171 	case 3:
13172 		opts.session = str_has_pfx(probe_type, "uprobe.session");
13173 		opts.retprobe = str_has_pfx(probe_type, "uretprobe.multi");
13174 
13175 		*link = bpf_program__attach_uprobe_multi(prog, -1, binary_path, func_name, &opts);
13176 		ret = libbpf_get_error(*link);
13177 		break;
13178 	default:
13179 		pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
13180 			prog->sec_name);
13181 		break;
13182 	}
13183 	free(probe_type);
13184 	free(binary_path);
13185 	free(func_name);
13186 	return ret;
13187 }
13188 
13189 #define MAX_BPF_FUNC_ARGS 12
13190 
13191 static bool btf_type_is_modifier(const struct btf_type *t)
13192 {
13193 	switch (BTF_INFO_KIND(t->info)) {
13194 	case BTF_KIND_TYPEDEF:
13195 	case BTF_KIND_VOLATILE:
13196 	case BTF_KIND_CONST:
13197 	case BTF_KIND_RESTRICT:
13198 	case BTF_KIND_TYPE_TAG:
13199 		return true;
13200 	default:
13201 		return false;
13202 	}
13203 }
13204 
13205 #define MAX_RESOLVE_DEPTH 32
13206 
13207 static int btf_get_type_size(const struct btf *btf, __u32 type_id,
13208 			     const struct btf_type **ret_type)
13209 {
13210 	const struct btf_type *t;
13211 	int i;
13212 
13213 	*ret_type = btf__type_by_id(btf, 0);
13214 	if (!type_id)
13215 		return 0;
13216 	t = btf__type_by_id(btf, type_id);
13217 	for (i = 0; i < MAX_RESOLVE_DEPTH && t && btf_type_is_modifier(t); i++)
13218 		t = btf__type_by_id(btf, t->type);
13219 	if (!t || i == MAX_RESOLVE_DEPTH)
13220 		return -EINVAL;
13221 	*ret_type = t;
13222 	if (btf_is_ptr(t))
13223 		return btf__pointer_size(btf);
13224 	if (btf_is_int(t) || btf_is_any_enum(t) || btf_is_struct(t) || btf_is_union(t))
13225 		return t->size;
13226 	return -EINVAL;
13227 }
13228 
13229 bool btf_type_is_traceable_func(const struct btf *btf, const struct btf_type *t)
13230 {
13231 	const struct btf_param *args;
13232 	const struct btf_type *proto;
13233 	__u32 i, nargs;
13234 	int ret;
13235 
13236 	if (!btf_is_func(t))
13237 		return false;
13238 	proto = btf__type_by_id(btf, t->type);
13239 	if (!proto || !btf_is_func_proto(proto))
13240 		return false;
13241 
13242 	args = (const struct btf_param *)(proto + 1);
13243 	nargs = btf_vlen(proto);
13244 	if (nargs > MAX_BPF_FUNC_ARGS)
13245 		return false;
13246 
13247 	/* No support for struct return type. */
13248 	ret = btf_get_type_size(btf, proto->type, &t);
13249 	if (ret < 0 || btf_is_struct(t) || btf_is_union(t))
13250 		return false;
13251 
13252 	for (i = 0; i < nargs; i++) {
13253 		/* No support for variable args. */
13254 		if (i == nargs - 1 && args[i].type == 0)
13255 			return false;
13256 		ret = btf_get_type_size(btf, args[i].type, &t);
13257 		/* No support of struct argument size greater than 16 bytes. */
13258 		if (ret < 0 || ret > 16)
13259 			return false;
13260 		/* No support for void argument. */
13261 		if (ret == 0)
13262 			return false;
13263 	}
13264 
13265 	return true;
13266 }
13267 
13268 static int
13269 collect_btf_func_ids_by_glob(const struct btf *btf, const char *pattern, __u32 **ids)
13270 {
13271 	__u32 type_id, nr_types = btf__type_cnt(btf);
13272 	size_t cap = 0, cnt = 0;
13273 
13274 	if (!pattern)
13275 		return -EINVAL;
13276 
13277 	for (type_id = 1; type_id < nr_types; type_id++) {
13278 		const struct btf_type *t = btf__type_by_id(btf, type_id);
13279 		const char *name;
13280 		int err;
13281 
13282 		if (btf_kind(t) != BTF_KIND_FUNC)
13283 			continue;
13284 		name = btf__name_by_offset(btf, t->name_off);
13285 		if (!name)
13286 			continue;
13287 
13288 		if (!glob_match(name, pattern))
13289 			continue;
13290 		if (!btf_type_is_traceable_func(btf, t))
13291 			continue;
13292 
13293 		err = libbpf_ensure_mem((void **) ids, &cap, sizeof(**ids), cnt + 1);
13294 		if (err) {
13295 			free(*ids);
13296 			return -ENOMEM;
13297 		}
13298 		(*ids)[cnt++] = type_id;
13299 	}
13300 
13301 	return cnt;
13302 }
13303 
13304 static int collect_func_ids_by_glob(const struct bpf_program *prog, const char *pattern, __u32 **ids)
13305 {
13306 	struct bpf_object *obj = prog->obj;
13307 	const struct module_btf *mod;
13308 	struct btf *btf = NULL;
13309 	const char *sep;
13310 	int err;
13311 
13312 	err = bpf_object__load_vmlinux_btf(obj, true);
13313 	if (err)
13314 		return err;
13315 
13316 	/* In case we have module specified, we will find its btf and use that. */
13317 	sep = strchr(pattern, ':');
13318 	if (sep) {
13319 		mod = find_attach_module(obj, pattern);
13320 		if (!mod) {
13321 			err = -EINVAL;
13322 			goto cleanup;
13323 		}
13324 		btf = mod->btf;
13325 		pattern = sep + 1;
13326 	} else {
13327 		/* Program is loaded for kernel module. */
13328 		if (prog->attach_btf_obj_fd) {
13329 			err = -EINVAL;
13330 			goto cleanup;
13331 		}
13332 		btf = obj->btf_vmlinux;
13333 	}
13334 
13335 	err = collect_btf_func_ids_by_glob(btf, pattern, ids);
13336 
13337 cleanup:
13338 	bpf_object_cleanup_btf(obj);
13339 	return err;
13340 }
13341 
13342 struct bpf_link *
13343 bpf_program__attach_tracing_multi(const struct bpf_program *prog, const char *pattern,
13344 				  const struct bpf_tracing_multi_opts *opts)
13345 {
13346 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
13347 	int prog_fd, link_fd, err, cnt;
13348 	__u32 *free_ids = NULL;
13349 	struct bpf_link *link;
13350 	const __u64 *cookies;
13351 	const __u32 *ids;
13352 
13353 	if (!OPTS_VALID(opts, bpf_tracing_multi_opts))
13354 		return libbpf_err_ptr(-EINVAL);
13355 
13356 	prog_fd = bpf_program__fd(prog);
13357 	if (prog_fd < 0) {
13358 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
13359 			prog->name);
13360 		return libbpf_err_ptr(-EINVAL);
13361 	}
13362 
13363 	cnt = OPTS_GET(opts, cnt, 0);
13364 	ids = OPTS_GET(opts, ids, NULL);
13365 	cookies = OPTS_GET(opts, cookies, NULL);
13366 
13367 	if (!!ids != !!cnt)
13368 		return libbpf_err_ptr(-EINVAL);
13369 	if (pattern && (ids || cookies))
13370 		return libbpf_err_ptr(-EINVAL);
13371 	if (!pattern && !ids)
13372 		return libbpf_err_ptr(-EINVAL);
13373 
13374 	if (pattern) {
13375 		cnt = collect_func_ids_by_glob(prog, pattern, &free_ids);
13376 		if (cnt < 0)
13377 			return libbpf_err_ptr(cnt);
13378 		if (cnt == 0)
13379 			return libbpf_err_ptr(-EINVAL);
13380 		ids = (const __u32 *) free_ids;
13381 	}
13382 
13383 	lopts.tracing_multi.ids = ids;
13384 	lopts.tracing_multi.cookies = cookies;
13385 	lopts.tracing_multi.cnt = cnt;
13386 
13387 	link = calloc(1, sizeof(*link));
13388 	if (!link) {
13389 		err = -ENOMEM;
13390 		goto error;
13391 	}
13392 	link->detach = &bpf_link__detach_fd;
13393 
13394 	link_fd = bpf_link_create(prog_fd, 0, prog->expected_attach_type, &lopts);
13395 	if (link_fd < 0) {
13396 		err = -errno;
13397 		pr_warn("prog '%s': failed to attach: %s\n", prog->name, errstr(err));
13398 		goto error;
13399 	}
13400 	link->fd = link_fd;
13401 	free(free_ids);
13402 	return link;
13403 
13404 error:
13405 	free(link);
13406 	free(free_ids);
13407 	return libbpf_err_ptr(err);
13408 }
13409 
13410 static int attach_tracing_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
13411 {
13412 	static const char *const prefixes[] = {
13413 		"fentry.multi",
13414 		"fexit.multi",
13415 		"fsession.multi",
13416 		"fentry.multi.s",
13417 		"fexit.multi.s",
13418 		"fsession.multi.s",
13419 	};
13420 	const char *spec = NULL;
13421 	char *pattern;
13422 	size_t i;
13423 	int n;
13424 
13425 	*link = NULL;
13426 
13427 	for (i = 0; i < ARRAY_SIZE(prefixes); i++) {
13428 		size_t pfx_len;
13429 
13430 		if (!str_has_pfx(prog->sec_name, prefixes[i]))
13431 			continue;
13432 
13433 		pfx_len = strlen(prefixes[i]);
13434 		/* no auto-attach case of, e.g., SEC("fentry.multi") */
13435 		if (prog->sec_name[pfx_len] == '\0')
13436 			return 0;
13437 
13438 		if (prog->sec_name[pfx_len] != '/')
13439 			continue;
13440 
13441 		spec = prog->sec_name + pfx_len + 1;
13442 		break;
13443 	}
13444 
13445 	if (!spec) {
13446 		pr_warn("prog '%s': invalid section name '%s'\n",
13447 			prog->name, prog->sec_name);
13448 		return -EINVAL;
13449 	}
13450 
13451 	n = sscanf(spec, "%m[a-zA-Z0-9_.*?:]", &pattern);
13452 	if (n < 1) {
13453 		pr_warn("tracing multi pattern is invalid: %s\n", spec);
13454 		return -EINVAL;
13455 	}
13456 
13457 	*link = bpf_program__attach_tracing_multi(prog, pattern, NULL);
13458 	free(pattern);
13459 	return libbpf_get_error(*link);
13460 }
13461 
13462 static inline int add_uprobe_event_legacy(const char *probe_name, bool retprobe,
13463 					  const char *binary_path, size_t offset)
13464 {
13465 	return append_to_file(tracefs_uprobe_events(), "%c:%s/%s %s:0x%zx",
13466 			      retprobe ? 'r' : 'p',
13467 			      retprobe ? "uretprobes" : "uprobes",
13468 			      probe_name, binary_path, offset);
13469 }
13470 
13471 static inline int remove_uprobe_event_legacy(const char *probe_name, bool retprobe)
13472 {
13473 	return append_to_file(tracefs_uprobe_events(), "-:%s/%s",
13474 			      retprobe ? "uretprobes" : "uprobes", probe_name);
13475 }
13476 
13477 static int determine_uprobe_perf_type_legacy(const char *probe_name, bool retprobe)
13478 {
13479 	char file[512];
13480 
13481 	snprintf(file, sizeof(file), "%s/events/%s/%s/id",
13482 		 tracefs_path(), retprobe ? "uretprobes" : "uprobes", probe_name);
13483 
13484 	return parse_uint_from_file(file, "%d\n");
13485 }
13486 
13487 static int perf_event_uprobe_open_legacy(const char *probe_name, bool retprobe,
13488 					 const char *binary_path, size_t offset, int pid)
13489 {
13490 	const size_t attr_sz = sizeof(struct perf_event_attr);
13491 	struct perf_event_attr attr;
13492 	int type, pfd, err;
13493 
13494 	err = add_uprobe_event_legacy(probe_name, retprobe, binary_path, offset);
13495 	if (err < 0) {
13496 		pr_warn("failed to add legacy uprobe event for %s:0x%zx: %s\n",
13497 			binary_path, (size_t)offset, errstr(err));
13498 		return err;
13499 	}
13500 	type = determine_uprobe_perf_type_legacy(probe_name, retprobe);
13501 	if (type < 0) {
13502 		err = type;
13503 		pr_warn("failed to determine legacy uprobe event id for %s:0x%zx: %s\n",
13504 			binary_path, offset, errstr(err));
13505 		goto err_clean_legacy;
13506 	}
13507 
13508 	memset(&attr, 0, attr_sz);
13509 	attr.size = attr_sz;
13510 	attr.config = type;
13511 	attr.type = PERF_TYPE_TRACEPOINT;
13512 
13513 	pfd = syscall(__NR_perf_event_open, &attr,
13514 		      pid < 0 ? -1 : pid, /* pid */
13515 		      pid == -1 ? 0 : -1, /* cpu */
13516 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
13517 	if (pfd < 0) {
13518 		err = -errno;
13519 		pr_warn("legacy uprobe perf_event_open() failed: %s\n", errstr(err));
13520 		goto err_clean_legacy;
13521 	}
13522 	return pfd;
13523 
13524 err_clean_legacy:
13525 	/* Clear the newly added legacy uprobe_event */
13526 	remove_uprobe_event_legacy(probe_name, retprobe);
13527 	return err;
13528 }
13529 
13530 /* Find offset of function name in archive specified by path. Currently
13531  * supported are .zip files that do not compress their contents, as used on
13532  * Android in the form of APKs, for example. "file_name" is the name of the ELF
13533  * file inside the archive. "func_name" matches symbol name or name@@LIB for
13534  * library functions.
13535  *
13536  * An overview of the APK format specifically provided here:
13537  * https://en.wikipedia.org/w/index.php?title=Apk_(file_format)&oldid=1139099120#Package_contents
13538  */
13539 static long elf_find_func_offset_from_archive(const char *archive_path, const char *file_name,
13540 					      const char *func_name)
13541 {
13542 	struct zip_archive *archive;
13543 	struct zip_entry entry;
13544 	long ret;
13545 	Elf *elf;
13546 
13547 	archive = zip_archive_open(archive_path);
13548 	if (IS_ERR(archive)) {
13549 		ret = PTR_ERR(archive);
13550 		pr_warn("zip: failed to open %s: %ld\n", archive_path, ret);
13551 		return ret;
13552 	}
13553 
13554 	ret = zip_archive_find_entry(archive, file_name, &entry);
13555 	if (ret) {
13556 		pr_warn("zip: could not find archive member %s in %s: %ld\n", file_name,
13557 			archive_path, ret);
13558 		goto out;
13559 	}
13560 	pr_debug("zip: found entry for %s in %s at 0x%lx\n", file_name, archive_path,
13561 		 (unsigned long)entry.data_offset);
13562 
13563 	if (entry.compression) {
13564 		pr_warn("zip: entry %s of %s is compressed and cannot be handled\n", file_name,
13565 			archive_path);
13566 		ret = -LIBBPF_ERRNO__FORMAT;
13567 		goto out;
13568 	}
13569 
13570 	elf = elf_memory((void *)entry.data, entry.data_length);
13571 	if (!elf) {
13572 		pr_warn("elf: could not read elf file %s from %s: %s\n", file_name, archive_path,
13573 			elf_errmsg(-1));
13574 		ret = -LIBBPF_ERRNO__LIBELF;
13575 		goto out;
13576 	}
13577 
13578 	ret = elf_find_func_offset(elf, file_name, func_name);
13579 	if (ret > 0) {
13580 		pr_debug("elf: symbol address match for %s of %s in %s: 0x%x + 0x%lx = 0x%lx\n",
13581 			 func_name, file_name, archive_path, entry.data_offset, (unsigned long)ret,
13582 			 (unsigned long)(ret + entry.data_offset));
13583 		ret += entry.data_offset;
13584 	}
13585 	elf_end(elf);
13586 
13587 out:
13588 	zip_archive_close(archive);
13589 	return ret;
13590 }
13591 
13592 static const char *arch_specific_lib_paths(void)
13593 {
13594 	/*
13595 	 * Based on https://packages.debian.org/sid/libc6.
13596 	 *
13597 	 * Assume that the traced program is built for the same architecture
13598 	 * as libbpf, which should cover the vast majority of cases.
13599 	 */
13600 #if defined(__x86_64__)
13601 	return "/lib/x86_64-linux-gnu";
13602 #elif defined(__i386__)
13603 	return "/lib/i386-linux-gnu";
13604 #elif defined(__s390x__)
13605 	return "/lib/s390x-linux-gnu";
13606 #elif defined(__arm__) && defined(__SOFTFP__)
13607 	return "/lib/arm-linux-gnueabi";
13608 #elif defined(__arm__) && !defined(__SOFTFP__)
13609 	return "/lib/arm-linux-gnueabihf";
13610 #elif defined(__aarch64__)
13611 	return "/lib/aarch64-linux-gnu";
13612 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 64
13613 	return "/lib/mips64el-linux-gnuabi64";
13614 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 32
13615 	return "/lib/mipsel-linux-gnu";
13616 #elif defined(__powerpc64__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
13617 	return "/lib/powerpc64le-linux-gnu";
13618 #elif defined(__sparc__) && defined(__arch64__)
13619 	return "/lib/sparc64-linux-gnu";
13620 #elif defined(__riscv) && __riscv_xlen == 64
13621 	return "/lib/riscv64-linux-gnu";
13622 #else
13623 	return NULL;
13624 #endif
13625 }
13626 
13627 /* Get full path to program/shared library. */
13628 static int resolve_full_path(const char *file, char *result, size_t result_sz)
13629 {
13630 	const char *search_paths[4] = {};
13631 	int i, perm;
13632 
13633 	if (str_has_sfx(file, ".so") || strstr(file, ".so.")) {
13634 		search_paths[0] = getenv("LD_LIBRARY_PATH");
13635 		search_paths[1] = "/usr/lib64:/usr/lib";
13636 		search_paths[2] = arch_specific_lib_paths();
13637 		search_paths[3] = "/lib64:/lib";
13638 		perm = R_OK;
13639 	} else {
13640 		search_paths[0] = getenv("PATH");
13641 		search_paths[1] = "/usr/bin:/usr/sbin";
13642 		perm = R_OK | X_OK;
13643 	}
13644 
13645 	for (i = 0; i < ARRAY_SIZE(search_paths); i++) {
13646 		const char *s;
13647 
13648 		if (!search_paths[i])
13649 			continue;
13650 		for (s = search_paths[i]; s != NULL; s = strchr(s, ':')) {
13651 			const char *next_path;
13652 			int seg_len;
13653 
13654 			if (s[0] == ':')
13655 				s++;
13656 			next_path = strchr(s, ':');
13657 			seg_len = next_path ? next_path - s : strlen(s);
13658 			if (!seg_len)
13659 				continue;
13660 			snprintf(result, result_sz, "%.*s/%s", seg_len, s, file);
13661 			/* ensure it has required permissions */
13662 			if (faccessat(AT_FDCWD, result, perm, AT_EACCESS) < 0)
13663 				continue;
13664 			pr_debug("resolved '%s' to '%s'\n", file, result);
13665 			return 0;
13666 		}
13667 	}
13668 	return -ENOENT;
13669 }
13670 
13671 struct bpf_link *
13672 bpf_program__attach_uprobe_multi(const struct bpf_program *prog,
13673 				 pid_t pid,
13674 				 const char *path,
13675 				 const char *func_pattern,
13676 				 const struct bpf_uprobe_multi_opts *opts)
13677 {
13678 	const unsigned long *ref_ctr_offsets = NULL, *offsets = NULL;
13679 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
13680 	unsigned long *resolved_offsets = NULL;
13681 	enum bpf_attach_type attach_type;
13682 	int err = 0, link_fd, prog_fd;
13683 	struct bpf_link *link = NULL;
13684 	char full_path[PATH_MAX];
13685 	bool retprobe, session;
13686 	const __u64 *cookies;
13687 	const char **syms;
13688 	size_t cnt;
13689 
13690 	if (!OPTS_VALID(opts, bpf_uprobe_multi_opts))
13691 		return libbpf_err_ptr(-EINVAL);
13692 
13693 	prog_fd = bpf_program__fd(prog);
13694 	if (prog_fd < 0) {
13695 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
13696 			prog->name);
13697 		return libbpf_err_ptr(-EINVAL);
13698 	}
13699 
13700 	syms = OPTS_GET(opts, syms, NULL);
13701 	offsets = OPTS_GET(opts, offsets, NULL);
13702 	ref_ctr_offsets = OPTS_GET(opts, ref_ctr_offsets, NULL);
13703 	cookies = OPTS_GET(opts, cookies, NULL);
13704 	cnt = OPTS_GET(opts, cnt, 0);
13705 	retprobe = OPTS_GET(opts, retprobe, false);
13706 	session  = OPTS_GET(opts, session, false);
13707 
13708 	/*
13709 	 * User can specify 2 mutually exclusive set of inputs:
13710 	 *
13711 	 * 1) use only path/func_pattern/pid arguments
13712 	 *
13713 	 * 2) use path/pid with allowed combinations of:
13714 	 *    syms/offsets/ref_ctr_offsets/cookies/cnt
13715 	 *
13716 	 *    - syms and offsets are mutually exclusive
13717 	 *    - ref_ctr_offsets and cookies are optional
13718 	 *
13719 	 * Any other usage results in error.
13720 	 */
13721 
13722 	if (!path)
13723 		return libbpf_err_ptr(-EINVAL);
13724 	if (!func_pattern && cnt == 0)
13725 		return libbpf_err_ptr(-EINVAL);
13726 
13727 	if (func_pattern) {
13728 		if (syms || offsets || ref_ctr_offsets || cookies || cnt)
13729 			return libbpf_err_ptr(-EINVAL);
13730 	} else {
13731 		if (!!syms == !!offsets)
13732 			return libbpf_err_ptr(-EINVAL);
13733 	}
13734 
13735 	if (retprobe && session)
13736 		return libbpf_err_ptr(-EINVAL);
13737 
13738 	if (func_pattern) {
13739 		if (!strchr(path, '/')) {
13740 			err = resolve_full_path(path, full_path, sizeof(full_path));
13741 			if (err) {
13742 				pr_warn("prog '%s': failed to resolve full path for '%s': %s\n",
13743 					prog->name, path, errstr(err));
13744 				return libbpf_err_ptr(err);
13745 			}
13746 			path = full_path;
13747 		}
13748 
13749 		err = elf_resolve_pattern_offsets(path, func_pattern,
13750 						  &resolved_offsets, &cnt);
13751 		if (err < 0)
13752 			return libbpf_err_ptr(err);
13753 		offsets = resolved_offsets;
13754 	} else if (syms) {
13755 		err = elf_resolve_syms_offsets(path, cnt, syms, &resolved_offsets, STT_FUNC);
13756 		if (err < 0)
13757 			return libbpf_err_ptr(err);
13758 		offsets = resolved_offsets;
13759 	}
13760 
13761 	attach_type = session ? BPF_TRACE_UPROBE_SESSION : BPF_TRACE_UPROBE_MULTI;
13762 
13763 	lopts.uprobe_multi.path = path;
13764 	lopts.uprobe_multi.offsets = offsets;
13765 	lopts.uprobe_multi.ref_ctr_offsets = ref_ctr_offsets;
13766 	lopts.uprobe_multi.cookies = cookies;
13767 	lopts.uprobe_multi.cnt = cnt;
13768 	lopts.uprobe_multi.flags = retprobe ? BPF_F_UPROBE_MULTI_RETURN : 0;
13769 
13770 	if (pid == 0)
13771 		pid = getpid();
13772 	if (pid > 0)
13773 		lopts.uprobe_multi.pid = pid;
13774 
13775 	link = calloc(1, sizeof(*link));
13776 	if (!link) {
13777 		err = -ENOMEM;
13778 		goto error;
13779 	}
13780 	link->detach = &bpf_link__detach_fd;
13781 
13782 	link_fd = bpf_link_create(prog_fd, 0, attach_type, &lopts);
13783 	if (link_fd < 0) {
13784 		err = -errno;
13785 		pr_warn("prog '%s': failed to attach multi-uprobe: %s\n",
13786 			prog->name, errstr(err));
13787 		goto error;
13788 	}
13789 	link->fd = link_fd;
13790 	free(resolved_offsets);
13791 	return link;
13792 
13793 error:
13794 	free(resolved_offsets);
13795 	free(link);
13796 	return libbpf_err_ptr(err);
13797 }
13798 
13799 LIBBPF_API struct bpf_link *
13800 bpf_program__attach_uprobe_opts(const struct bpf_program *prog, pid_t pid,
13801 				const char *binary_path, size_t func_offset,
13802 				const struct bpf_uprobe_opts *opts)
13803 {
13804 	const char *archive_path = NULL, *archive_sep = NULL;
13805 	char *legacy_probe = NULL;
13806 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
13807 	enum probe_attach_mode attach_mode;
13808 	char full_path[PATH_MAX];
13809 	struct bpf_link *link;
13810 	size_t ref_ctr_off;
13811 	int pfd, err;
13812 	bool retprobe, legacy;
13813 	const char *func_name;
13814 
13815 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
13816 		return libbpf_err_ptr(-EINVAL);
13817 
13818 	attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
13819 	retprobe = OPTS_GET(opts, retprobe, false);
13820 	ref_ctr_off = OPTS_GET(opts, ref_ctr_offset, 0);
13821 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
13822 
13823 	if (!binary_path)
13824 		return libbpf_err_ptr(-EINVAL);
13825 
13826 	/* Check if "binary_path" refers to an archive. */
13827 	archive_sep = strstr(binary_path, "!/");
13828 	if (archive_sep) {
13829 		full_path[0] = '\0';
13830 		libbpf_strlcpy(full_path, binary_path,
13831 			       min(sizeof(full_path), (size_t)(archive_sep - binary_path + 1)));
13832 		archive_path = full_path;
13833 		binary_path = archive_sep + 2;
13834 	} else if (!strchr(binary_path, '/')) {
13835 		err = resolve_full_path(binary_path, full_path, sizeof(full_path));
13836 		if (err) {
13837 			pr_warn("prog '%s': failed to resolve full path for '%s': %s\n",
13838 				prog->name, binary_path, errstr(err));
13839 			return libbpf_err_ptr(err);
13840 		}
13841 		binary_path = full_path;
13842 	}
13843 	func_name = OPTS_GET(opts, func_name, NULL);
13844 	if (func_name) {
13845 		long sym_off;
13846 
13847 		if (archive_path) {
13848 			sym_off = elf_find_func_offset_from_archive(archive_path, binary_path,
13849 								    func_name);
13850 			binary_path = archive_path;
13851 		} else {
13852 			sym_off = elf_find_func_offset_from_file(binary_path, func_name);
13853 		}
13854 		if (sym_off < 0)
13855 			return libbpf_err_ptr(sym_off);
13856 		func_offset += sym_off;
13857 	}
13858 
13859 	legacy = determine_uprobe_perf_type() < 0;
13860 	switch (attach_mode) {
13861 	case PROBE_ATTACH_MODE_LEGACY:
13862 		legacy = true;
13863 		pe_opts.force_ioctl_attach = true;
13864 		break;
13865 	case PROBE_ATTACH_MODE_PERF:
13866 		if (legacy)
13867 			return libbpf_err_ptr(-ENOTSUP);
13868 		pe_opts.force_ioctl_attach = true;
13869 		break;
13870 	case PROBE_ATTACH_MODE_LINK:
13871 		if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
13872 			return libbpf_err_ptr(-ENOTSUP);
13873 		break;
13874 	case PROBE_ATTACH_MODE_DEFAULT:
13875 		break;
13876 	default:
13877 		return libbpf_err_ptr(-EINVAL);
13878 	}
13879 
13880 	if (!legacy) {
13881 		pfd = perf_event_open_probe(true /* uprobe */, retprobe, binary_path,
13882 					    func_offset, pid, ref_ctr_off);
13883 	} else {
13884 		char probe_name[MAX_EVENT_NAME_LEN];
13885 
13886 		if (ref_ctr_off)
13887 			return libbpf_err_ptr(-EINVAL);
13888 
13889 		gen_probe_legacy_event_name(probe_name, sizeof(probe_name),
13890 					    strrchr(binary_path, '/') ? : binary_path,
13891 					    func_offset);
13892 
13893 		legacy_probe = strdup(probe_name);
13894 		if (!legacy_probe)
13895 			return libbpf_err_ptr(-ENOMEM);
13896 
13897 		pfd = perf_event_uprobe_open_legacy(legacy_probe, retprobe,
13898 						    binary_path, func_offset, pid);
13899 	}
13900 	if (pfd < 0) {
13901 		err = pfd;
13902 		pr_warn("prog '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
13903 			prog->name, retprobe ? "uretprobe" : "uprobe",
13904 			binary_path, func_offset,
13905 			errstr(err));
13906 		goto err_out;
13907 	}
13908 
13909 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
13910 	err = libbpf_get_error(link);
13911 	if (err) {
13912 		close(pfd);
13913 		pr_warn("prog '%s': failed to attach to %s '%s:0x%zx': %s\n",
13914 			prog->name, retprobe ? "uretprobe" : "uprobe",
13915 			binary_path, func_offset,
13916 			errstr(err));
13917 		goto err_clean_legacy;
13918 	}
13919 	if (legacy) {
13920 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
13921 
13922 		perf_link->legacy_probe_name = legacy_probe;
13923 		perf_link->legacy_is_kprobe = false;
13924 		perf_link->legacy_is_retprobe = retprobe;
13925 	}
13926 	return link;
13927 
13928 err_clean_legacy:
13929 	if (legacy)
13930 		remove_uprobe_event_legacy(legacy_probe, retprobe);
13931 err_out:
13932 	free(legacy_probe);
13933 	return libbpf_err_ptr(err);
13934 }
13935 
13936 /* Format of u[ret]probe section definition supporting auto-attach:
13937  * u[ret]probe/binary:function[+offset]
13938  *
13939  * binary can be an absolute/relative path or a filename; the latter is resolved to a
13940  * full binary path via bpf_program__attach_uprobe_opts.
13941  *
13942  * Specifying uprobe+ ensures we carry out strict matching; either "uprobe" must be
13943  * specified (and auto-attach is not possible) or the above format is specified for
13944  * auto-attach.
13945  */
13946 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
13947 {
13948 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts);
13949 	char *probe_type = NULL, *binary_path = NULL, *func_name = NULL, *func_off;
13950 	int n, c, ret = -EINVAL;
13951 	long offset = 0;
13952 
13953 	*link = NULL;
13954 
13955 	n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[^\n]",
13956 		   &probe_type, &binary_path, &func_name);
13957 	switch (n) {
13958 	case 1:
13959 		/* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
13960 		ret = 0;
13961 		break;
13962 	case 2:
13963 		pr_warn("prog '%s': section '%s' missing ':function[+offset]' specification\n",
13964 			prog->name, prog->sec_name);
13965 		break;
13966 	case 3:
13967 		/* check if user specifies `+offset`, if yes, this should be
13968 		 * the last part of the string, make sure sscanf read to EOL
13969 		 */
13970 		func_off = strrchr(func_name, '+');
13971 		if (func_off) {
13972 			n = sscanf(func_off, "+%li%n", &offset, &c);
13973 			if (n == 1 && *(func_off + c) == '\0')
13974 				func_off[0] = '\0';
13975 			else
13976 				offset = 0;
13977 		}
13978 		opts.retprobe = strcmp(probe_type, "uretprobe") == 0 ||
13979 				strcmp(probe_type, "uretprobe.s") == 0;
13980 		if (opts.retprobe && offset != 0) {
13981 			pr_warn("prog '%s': uretprobes do not support offset specification\n",
13982 				prog->name);
13983 			break;
13984 		}
13985 		opts.func_name = func_name;
13986 		*link = bpf_program__attach_uprobe_opts(prog, -1, binary_path, offset, &opts);
13987 		ret = libbpf_get_error(*link);
13988 		break;
13989 	default:
13990 		pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
13991 			prog->sec_name);
13992 		break;
13993 	}
13994 	free(probe_type);
13995 	free(binary_path);
13996 	free(func_name);
13997 
13998 	return ret;
13999 }
14000 
14001 struct bpf_link *bpf_program__attach_uprobe(const struct bpf_program *prog,
14002 					    bool retprobe, pid_t pid,
14003 					    const char *binary_path,
14004 					    size_t func_offset)
14005 {
14006 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts, .retprobe = retprobe);
14007 
14008 	return bpf_program__attach_uprobe_opts(prog, pid, binary_path, func_offset, &opts);
14009 }
14010 
14011 struct bpf_link *bpf_program__attach_usdt(const struct bpf_program *prog,
14012 					  pid_t pid, const char *binary_path,
14013 					  const char *usdt_provider, const char *usdt_name,
14014 					  const struct bpf_usdt_opts *opts)
14015 {
14016 	char resolved_path[512];
14017 	struct bpf_object *obj = prog->obj;
14018 	struct bpf_link *link;
14019 	__u64 usdt_cookie;
14020 	int err;
14021 
14022 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
14023 		return libbpf_err_ptr(-EINVAL);
14024 
14025 	if (bpf_program__fd(prog) < 0) {
14026 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
14027 			prog->name);
14028 		return libbpf_err_ptr(-EINVAL);
14029 	}
14030 
14031 	if (!binary_path)
14032 		return libbpf_err_ptr(-EINVAL);
14033 
14034 	if (!strchr(binary_path, '/')) {
14035 		err = resolve_full_path(binary_path, resolved_path, sizeof(resolved_path));
14036 		if (err) {
14037 			pr_warn("prog '%s': failed to resolve full path for '%s': %s\n",
14038 				prog->name, binary_path, errstr(err));
14039 			return libbpf_err_ptr(err);
14040 		}
14041 		binary_path = resolved_path;
14042 	}
14043 
14044 	/* USDT manager is instantiated lazily on first USDT attach. It will
14045 	 * be destroyed together with BPF object in bpf_object__close().
14046 	 */
14047 	if (IS_ERR(obj->usdt_man))
14048 		return libbpf_ptr(obj->usdt_man);
14049 	if (!obj->usdt_man) {
14050 		obj->usdt_man = usdt_manager_new(obj);
14051 		if (IS_ERR(obj->usdt_man))
14052 			return libbpf_ptr(obj->usdt_man);
14053 	}
14054 
14055 	usdt_cookie = OPTS_GET(opts, usdt_cookie, 0);
14056 	link = usdt_manager_attach_usdt(obj->usdt_man, prog, pid, binary_path,
14057 					usdt_provider, usdt_name, usdt_cookie);
14058 	err = libbpf_get_error(link);
14059 	if (err)
14060 		return libbpf_err_ptr(err);
14061 	return link;
14062 }
14063 
14064 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link)
14065 {
14066 	char *path = NULL, *provider = NULL, *name = NULL;
14067 	const char *sec_name;
14068 	int n, err;
14069 
14070 	sec_name = bpf_program__section_name(prog);
14071 	if (strcmp(sec_name, "usdt") == 0) {
14072 		/* no auto-attach for just SEC("usdt") */
14073 		*link = NULL;
14074 		return 0;
14075 	}
14076 
14077 	n = sscanf(sec_name, "usdt/%m[^:]:%m[^:]:%m[^:]", &path, &provider, &name);
14078 	if (n != 3) {
14079 		pr_warn("invalid section '%s', expected SEC(\"usdt/<path>:<provider>:<name>\")\n",
14080 			sec_name);
14081 		err = -EINVAL;
14082 	} else {
14083 		*link = bpf_program__attach_usdt(prog, -1 /* any process */, path,
14084 						 provider, name, NULL);
14085 		err = libbpf_get_error(*link);
14086 	}
14087 	free(path);
14088 	free(provider);
14089 	free(name);
14090 	return err;
14091 }
14092 
14093 static int determine_tracepoint_id(const char *tp_category,
14094 				   const char *tp_name)
14095 {
14096 	char file[PATH_MAX];
14097 	int ret;
14098 
14099 	ret = snprintf(file, sizeof(file), "%s/events/%s/%s/id",
14100 		       tracefs_path(), tp_category, tp_name);
14101 	if (ret < 0)
14102 		return -errno;
14103 	if (ret >= sizeof(file)) {
14104 		pr_debug("tracepoint %s/%s path is too long\n",
14105 			 tp_category, tp_name);
14106 		return -E2BIG;
14107 	}
14108 	return parse_uint_from_file(file, "%d\n");
14109 }
14110 
14111 static int perf_event_open_tracepoint(const char *tp_category,
14112 				      const char *tp_name)
14113 {
14114 	const size_t attr_sz = sizeof(struct perf_event_attr);
14115 	struct perf_event_attr attr;
14116 	int tp_id, pfd, err;
14117 
14118 	tp_id = determine_tracepoint_id(tp_category, tp_name);
14119 	if (tp_id < 0) {
14120 		pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
14121 			tp_category, tp_name,
14122 			errstr(tp_id));
14123 		return tp_id;
14124 	}
14125 
14126 	memset(&attr, 0, attr_sz);
14127 	attr.type = PERF_TYPE_TRACEPOINT;
14128 	attr.size = attr_sz;
14129 	attr.config = tp_id;
14130 
14131 	pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
14132 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
14133 	if (pfd < 0) {
14134 		err = -errno;
14135 		pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
14136 			tp_category, tp_name,
14137 			errstr(err));
14138 		return err;
14139 	}
14140 	return pfd;
14141 }
14142 
14143 struct bpf_link *bpf_program__attach_tracepoint_opts(const struct bpf_program *prog,
14144 						     const char *tp_category,
14145 						     const char *tp_name,
14146 						     const struct bpf_tracepoint_opts *opts)
14147 {
14148 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
14149 	struct bpf_link *link;
14150 	int pfd, err;
14151 
14152 	if (!OPTS_VALID(opts, bpf_tracepoint_opts))
14153 		return libbpf_err_ptr(-EINVAL);
14154 
14155 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
14156 
14157 	pfd = perf_event_open_tracepoint(tp_category, tp_name);
14158 	if (pfd < 0) {
14159 		pr_warn("prog '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
14160 			prog->name, tp_category, tp_name,
14161 			errstr(pfd));
14162 		return libbpf_err_ptr(pfd);
14163 	}
14164 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
14165 	err = libbpf_get_error(link);
14166 	if (err) {
14167 		close(pfd);
14168 		pr_warn("prog '%s': failed to attach to tracepoint '%s/%s': %s\n",
14169 			prog->name, tp_category, tp_name,
14170 			errstr(err));
14171 		return libbpf_err_ptr(err);
14172 	}
14173 	return link;
14174 }
14175 
14176 struct bpf_link *bpf_program__attach_tracepoint(const struct bpf_program *prog,
14177 						const char *tp_category,
14178 						const char *tp_name)
14179 {
14180 	return bpf_program__attach_tracepoint_opts(prog, tp_category, tp_name, NULL);
14181 }
14182 
14183 /*
14184  * Match section name against a prefix array. Returns pointer past
14185  * "prefix/" on match, empty string for bare sections (exact prefix
14186  * match), or NULL if no prefix matches.
14187  */
14188 static const char *sec_name_match_prefix(const char *sec_name,
14189 					 const char *const *prefixes,
14190 					 size_t n)
14191 {
14192 	size_t i;
14193 
14194 	for (i = 0; i < n; i++) {
14195 		size_t pfx_len;
14196 
14197 		if (!str_has_pfx(sec_name, prefixes[i]))
14198 			continue;
14199 
14200 		pfx_len = strlen(prefixes[i]);
14201 		if (sec_name[pfx_len] == '\0')
14202 			return sec_name + pfx_len;
14203 
14204 		if (sec_name[pfx_len] != '/' || sec_name[pfx_len + 1] == '\0')
14205 			continue;
14206 
14207 		return sec_name + pfx_len + 1;
14208 	}
14209 	return NULL;
14210 }
14211 
14212 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
14213 {
14214 	static const char *const prefixes[] = {
14215 		"tp.s",
14216 		"tp",
14217 		"tracepoint.s",
14218 		"tracepoint",
14219 	};
14220 	char *sec_name, *tp_cat, *tp_name;
14221 	const char *match;
14222 
14223 	*link = NULL;
14224 
14225 	match = sec_name_match_prefix(prog->sec_name, prefixes, ARRAY_SIZE(prefixes));
14226 	if (!match) {
14227 		pr_warn("prog '%s': invalid section name '%s'\n", prog->name, prog->sec_name);
14228 		return -EINVAL;
14229 	}
14230 	if (!match[0]) /* bare section name no autoattach */
14231 		return 0;
14232 
14233 	sec_name = strdup(prog->sec_name);
14234 	if (!sec_name)
14235 		return -ENOMEM;
14236 
14237 	tp_cat = sec_name + (match - prog->sec_name);
14238 	tp_name = strchr(tp_cat, '/');
14239 	if (!tp_name) {
14240 		free(sec_name);
14241 		return -EINVAL;
14242 	}
14243 	*tp_name = '\0';
14244 	tp_name++;
14245 
14246 	*link = bpf_program__attach_tracepoint(prog, tp_cat, tp_name);
14247 	free(sec_name);
14248 	return libbpf_get_error(*link);
14249 }
14250 
14251 struct bpf_link *
14252 bpf_program__attach_raw_tracepoint_opts(const struct bpf_program *prog,
14253 					const char *tp_name,
14254 					struct bpf_raw_tracepoint_opts *opts)
14255 {
14256 	LIBBPF_OPTS(bpf_raw_tp_opts, raw_opts);
14257 	struct bpf_link *link;
14258 	int prog_fd, pfd;
14259 
14260 	if (!OPTS_VALID(opts, bpf_raw_tracepoint_opts))
14261 		return libbpf_err_ptr(-EINVAL);
14262 
14263 	prog_fd = bpf_program__fd(prog);
14264 	if (prog_fd < 0) {
14265 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
14266 		return libbpf_err_ptr(-EINVAL);
14267 	}
14268 
14269 	link = calloc(1, sizeof(*link));
14270 	if (!link)
14271 		return libbpf_err_ptr(-ENOMEM);
14272 	link->detach = &bpf_link__detach_fd;
14273 
14274 	raw_opts.tp_name = tp_name;
14275 	raw_opts.cookie = OPTS_GET(opts, cookie, 0);
14276 	pfd = bpf_raw_tracepoint_open_opts(prog_fd, &raw_opts);
14277 	if (pfd < 0) {
14278 		pfd = -errno;
14279 		free(link);
14280 		pr_warn("prog '%s': failed to attach to raw tracepoint '%s': %s\n",
14281 			prog->name, tp_name, errstr(pfd));
14282 		return libbpf_err_ptr(pfd);
14283 	}
14284 	link->fd = pfd;
14285 	return link;
14286 }
14287 
14288 struct bpf_link *bpf_program__attach_raw_tracepoint(const struct bpf_program *prog,
14289 						    const char *tp_name)
14290 {
14291 	return bpf_program__attach_raw_tracepoint_opts(prog, tp_name, NULL);
14292 }
14293 
14294 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
14295 {
14296 	static const char *const prefixes[] = {
14297 		"raw_tp",
14298 		"raw_tracepoint",
14299 		"raw_tp.w",
14300 		"raw_tracepoint.w",
14301 		"raw_tp.s",
14302 		"raw_tracepoint.s",
14303 	};
14304 	const char *match;
14305 
14306 	*link = NULL;
14307 
14308 	match = sec_name_match_prefix(prog->sec_name, prefixes, ARRAY_SIZE(prefixes));
14309 	if (!match) {
14310 		pr_warn("prog '%s': invalid section name '%s'\n", prog->name, prog->sec_name);
14311 		return -EINVAL;
14312 	}
14313 	if (!match[0])
14314 		return 0;
14315 
14316 	*link = bpf_program__attach_raw_tracepoint(prog, match);
14317 	return libbpf_get_error(*link);
14318 }
14319 
14320 /* Common logic for all BPF program types that attach to a btf_id */
14321 static struct bpf_link *bpf_program__attach_btf_id(const struct bpf_program *prog,
14322 						   const struct bpf_trace_opts *opts)
14323 {
14324 	LIBBPF_OPTS(bpf_link_create_opts, link_opts);
14325 	struct bpf_link *link;
14326 	int prog_fd, pfd;
14327 
14328 	if (!OPTS_VALID(opts, bpf_trace_opts))
14329 		return libbpf_err_ptr(-EINVAL);
14330 
14331 	prog_fd = bpf_program__fd(prog);
14332 	if (prog_fd < 0) {
14333 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
14334 		return libbpf_err_ptr(-EINVAL);
14335 	}
14336 
14337 	link = calloc(1, sizeof(*link));
14338 	if (!link)
14339 		return libbpf_err_ptr(-ENOMEM);
14340 	link->detach = &bpf_link__detach_fd;
14341 
14342 	/* libbpf is smart enough to redirect to BPF_RAW_TRACEPOINT_OPEN on old kernels */
14343 	link_opts.tracing.cookie = OPTS_GET(opts, cookie, 0);
14344 	pfd = bpf_link_create(prog_fd, 0, bpf_program__expected_attach_type(prog), &link_opts);
14345 	if (pfd < 0) {
14346 		pfd = -errno;
14347 		free(link);
14348 		pr_warn("prog '%s': failed to attach: %s\n",
14349 			prog->name, errstr(pfd));
14350 		return libbpf_err_ptr(pfd);
14351 	}
14352 	link->fd = pfd;
14353 	return link;
14354 }
14355 
14356 struct bpf_link *bpf_program__attach_trace(const struct bpf_program *prog)
14357 {
14358 	return bpf_program__attach_btf_id(prog, NULL);
14359 }
14360 
14361 struct bpf_link *bpf_program__attach_trace_opts(const struct bpf_program *prog,
14362 						const struct bpf_trace_opts *opts)
14363 {
14364 	return bpf_program__attach_btf_id(prog, opts);
14365 }
14366 
14367 struct bpf_link *bpf_program__attach_lsm(const struct bpf_program *prog)
14368 {
14369 	return bpf_program__attach_btf_id(prog, NULL);
14370 }
14371 
14372 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link)
14373 {
14374 	*link = bpf_program__attach_trace(prog);
14375 	return libbpf_get_error(*link);
14376 }
14377 
14378 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link)
14379 {
14380 	*link = bpf_program__attach_lsm(prog);
14381 	return libbpf_get_error(*link);
14382 }
14383 
14384 static struct bpf_link *
14385 bpf_program_attach_fd(const struct bpf_program *prog,
14386 		      int target_fd, const char *target_name,
14387 		      const struct bpf_link_create_opts *opts)
14388 {
14389 	enum bpf_attach_type attach_type;
14390 	struct bpf_link *link;
14391 	int prog_fd, link_fd;
14392 
14393 	prog_fd = bpf_program__fd(prog);
14394 	if (prog_fd < 0) {
14395 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
14396 		return libbpf_err_ptr(-EINVAL);
14397 	}
14398 
14399 	link = calloc(1, sizeof(*link));
14400 	if (!link)
14401 		return libbpf_err_ptr(-ENOMEM);
14402 	link->detach = &bpf_link__detach_fd;
14403 
14404 	attach_type = bpf_program__expected_attach_type(prog);
14405 	link_fd = bpf_link_create(prog_fd, target_fd, attach_type, opts);
14406 	if (link_fd < 0) {
14407 		link_fd = -errno;
14408 		free(link);
14409 		pr_warn("prog '%s': failed to attach to %s: %s\n",
14410 			prog->name, target_name,
14411 			errstr(link_fd));
14412 		return libbpf_err_ptr(link_fd);
14413 	}
14414 	link->fd = link_fd;
14415 	return link;
14416 }
14417 
14418 struct bpf_link *
14419 bpf_program__attach_cgroup(const struct bpf_program *prog, int cgroup_fd)
14420 {
14421 	return bpf_program_attach_fd(prog, cgroup_fd, "cgroup", NULL);
14422 }
14423 
14424 struct bpf_link *
14425 bpf_program__attach_netns(const struct bpf_program *prog, int netns_fd)
14426 {
14427 	return bpf_program_attach_fd(prog, netns_fd, "netns", NULL);
14428 }
14429 
14430 struct bpf_link *
14431 bpf_program__attach_sockmap(const struct bpf_program *prog, int map_fd)
14432 {
14433 	return bpf_program_attach_fd(prog, map_fd, "sockmap", NULL);
14434 }
14435 
14436 struct bpf_link *bpf_program__attach_xdp(const struct bpf_program *prog, int ifindex)
14437 {
14438 	/* target_fd/target_ifindex use the same field in LINK_CREATE */
14439 	return bpf_program_attach_fd(prog, ifindex, "xdp", NULL);
14440 }
14441 
14442 struct bpf_link *
14443 bpf_program__attach_cgroup_opts(const struct bpf_program *prog, int cgroup_fd,
14444 				const struct bpf_cgroup_opts *opts)
14445 {
14446 	LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
14447 	__u32 relative_id;
14448 	int relative_fd;
14449 
14450 	if (!OPTS_VALID(opts, bpf_cgroup_opts))
14451 		return libbpf_err_ptr(-EINVAL);
14452 
14453 	relative_id = OPTS_GET(opts, relative_id, 0);
14454 	relative_fd = OPTS_GET(opts, relative_fd, 0);
14455 
14456 	if (relative_fd && relative_id) {
14457 		pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
14458 			prog->name);
14459 		return libbpf_err_ptr(-EINVAL);
14460 	}
14461 
14462 	link_create_opts.cgroup.expected_revision = OPTS_GET(opts, expected_revision, 0);
14463 	link_create_opts.cgroup.relative_fd = relative_fd;
14464 	link_create_opts.cgroup.relative_id = relative_id;
14465 	link_create_opts.flags = OPTS_GET(opts, flags, 0);
14466 
14467 	return bpf_program_attach_fd(prog, cgroup_fd, "cgroup", &link_create_opts);
14468 }
14469 
14470 struct bpf_link *
14471 bpf_program__attach_tcx(const struct bpf_program *prog, int ifindex,
14472 			const struct bpf_tcx_opts *opts)
14473 {
14474 	LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
14475 	__u32 relative_id;
14476 	int relative_fd;
14477 
14478 	if (!OPTS_VALID(opts, bpf_tcx_opts))
14479 		return libbpf_err_ptr(-EINVAL);
14480 
14481 	relative_id = OPTS_GET(opts, relative_id, 0);
14482 	relative_fd = OPTS_GET(opts, relative_fd, 0);
14483 
14484 	/* validate we don't have unexpected combinations of non-zero fields */
14485 	if (!ifindex) {
14486 		pr_warn("prog '%s': target netdevice ifindex cannot be zero\n",
14487 			prog->name);
14488 		return libbpf_err_ptr(-EINVAL);
14489 	}
14490 	if (relative_fd && relative_id) {
14491 		pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
14492 			prog->name);
14493 		return libbpf_err_ptr(-EINVAL);
14494 	}
14495 
14496 	link_create_opts.tcx.expected_revision = OPTS_GET(opts, expected_revision, 0);
14497 	link_create_opts.tcx.relative_fd = relative_fd;
14498 	link_create_opts.tcx.relative_id = relative_id;
14499 	link_create_opts.flags = OPTS_GET(opts, flags, 0);
14500 
14501 	/* target_fd/target_ifindex use the same field in LINK_CREATE */
14502 	return bpf_program_attach_fd(prog, ifindex, "tcx", &link_create_opts);
14503 }
14504 
14505 struct bpf_link *
14506 bpf_program__attach_netkit(const struct bpf_program *prog, int ifindex,
14507 			   const struct bpf_netkit_opts *opts)
14508 {
14509 	LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
14510 	__u32 relative_id;
14511 	int relative_fd;
14512 
14513 	if (!OPTS_VALID(opts, bpf_netkit_opts))
14514 		return libbpf_err_ptr(-EINVAL);
14515 
14516 	relative_id = OPTS_GET(opts, relative_id, 0);
14517 	relative_fd = OPTS_GET(opts, relative_fd, 0);
14518 
14519 	/* validate we don't have unexpected combinations of non-zero fields */
14520 	if (!ifindex) {
14521 		pr_warn("prog '%s': target netdevice ifindex cannot be zero\n",
14522 			prog->name);
14523 		return libbpf_err_ptr(-EINVAL);
14524 	}
14525 	if (relative_fd && relative_id) {
14526 		pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
14527 			prog->name);
14528 		return libbpf_err_ptr(-EINVAL);
14529 	}
14530 
14531 	link_create_opts.netkit.expected_revision = OPTS_GET(opts, expected_revision, 0);
14532 	link_create_opts.netkit.relative_fd = relative_fd;
14533 	link_create_opts.netkit.relative_id = relative_id;
14534 	link_create_opts.flags = OPTS_GET(opts, flags, 0);
14535 
14536 	return bpf_program_attach_fd(prog, ifindex, "netkit", &link_create_opts);
14537 }
14538 
14539 struct bpf_link *bpf_program__attach_freplace(const struct bpf_program *prog,
14540 					      int target_fd,
14541 					      const char *attach_func_name)
14542 {
14543 	int btf_id;
14544 
14545 	if (!!target_fd != !!attach_func_name) {
14546 		pr_warn("prog '%s': supply none or both of target_fd and attach_func_name\n",
14547 			prog->name);
14548 		return libbpf_err_ptr(-EINVAL);
14549 	}
14550 
14551 	if (prog->type != BPF_PROG_TYPE_EXT) {
14552 		pr_warn("prog '%s': only BPF_PROG_TYPE_EXT can attach as freplace\n",
14553 			prog->name);
14554 		return libbpf_err_ptr(-EINVAL);
14555 	}
14556 
14557 	if (target_fd) {
14558 		LIBBPF_OPTS(bpf_link_create_opts, target_opts);
14559 
14560 		btf_id = libbpf_find_prog_btf_id(attach_func_name, target_fd, prog->obj->token_fd);
14561 		if (btf_id < 0)
14562 			return libbpf_err_ptr(btf_id);
14563 
14564 		target_opts.target_btf_id = btf_id;
14565 
14566 		return bpf_program_attach_fd(prog, target_fd, "freplace",
14567 					     &target_opts);
14568 	} else {
14569 		/* no target, so use raw_tracepoint_open for compatibility
14570 		 * with old kernels
14571 		 */
14572 		return bpf_program__attach_trace(prog);
14573 	}
14574 }
14575 
14576 struct bpf_link *
14577 bpf_program__attach_iter(const struct bpf_program *prog,
14578 			 const struct bpf_iter_attach_opts *opts)
14579 {
14580 	DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
14581 	struct bpf_link *link;
14582 	int prog_fd, link_fd;
14583 	__u32 target_fd = 0;
14584 
14585 	if (!OPTS_VALID(opts, bpf_iter_attach_opts))
14586 		return libbpf_err_ptr(-EINVAL);
14587 
14588 	link_create_opts.iter_info = OPTS_GET(opts, link_info, (void *)0);
14589 	link_create_opts.iter_info_len = OPTS_GET(opts, link_info_len, 0);
14590 
14591 	prog_fd = bpf_program__fd(prog);
14592 	if (prog_fd < 0) {
14593 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
14594 		return libbpf_err_ptr(-EINVAL);
14595 	}
14596 
14597 	link = calloc(1, sizeof(*link));
14598 	if (!link)
14599 		return libbpf_err_ptr(-ENOMEM);
14600 	link->detach = &bpf_link__detach_fd;
14601 
14602 	link_fd = bpf_link_create(prog_fd, target_fd, BPF_TRACE_ITER,
14603 				  &link_create_opts);
14604 	if (link_fd < 0) {
14605 		link_fd = -errno;
14606 		free(link);
14607 		pr_warn("prog '%s': failed to attach to iterator: %s\n",
14608 			prog->name, errstr(link_fd));
14609 		return libbpf_err_ptr(link_fd);
14610 	}
14611 	link->fd = link_fd;
14612 	return link;
14613 }
14614 
14615 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link)
14616 {
14617 	*link = bpf_program__attach_iter(prog, NULL);
14618 	return libbpf_get_error(*link);
14619 }
14620 
14621 struct bpf_link *bpf_program__attach_netfilter(const struct bpf_program *prog,
14622 					       const struct bpf_netfilter_opts *opts)
14623 {
14624 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
14625 	struct bpf_link *link;
14626 	int prog_fd, link_fd;
14627 
14628 	if (!OPTS_VALID(opts, bpf_netfilter_opts))
14629 		return libbpf_err_ptr(-EINVAL);
14630 
14631 	prog_fd = bpf_program__fd(prog);
14632 	if (prog_fd < 0) {
14633 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
14634 		return libbpf_err_ptr(-EINVAL);
14635 	}
14636 
14637 	link = calloc(1, sizeof(*link));
14638 	if (!link)
14639 		return libbpf_err_ptr(-ENOMEM);
14640 
14641 	link->detach = &bpf_link__detach_fd;
14642 
14643 	lopts.netfilter.pf = OPTS_GET(opts, pf, 0);
14644 	lopts.netfilter.hooknum = OPTS_GET(opts, hooknum, 0);
14645 	lopts.netfilter.priority = OPTS_GET(opts, priority, 0);
14646 	lopts.netfilter.flags = OPTS_GET(opts, flags, 0);
14647 
14648 	link_fd = bpf_link_create(prog_fd, 0, BPF_NETFILTER, &lopts);
14649 	if (link_fd < 0) {
14650 		link_fd = -errno;
14651 		free(link);
14652 		pr_warn("prog '%s': failed to attach to netfilter: %s\n",
14653 			prog->name, errstr(link_fd));
14654 		return libbpf_err_ptr(link_fd);
14655 	}
14656 	link->fd = link_fd;
14657 
14658 	return link;
14659 }
14660 
14661 struct bpf_link *bpf_program__attach(const struct bpf_program *prog)
14662 {
14663 	struct bpf_link *link = NULL;
14664 	int err;
14665 
14666 	if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
14667 		return libbpf_err_ptr(-EOPNOTSUPP);
14668 
14669 	if (bpf_program__fd(prog) < 0) {
14670 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
14671 			prog->name);
14672 		return libbpf_err_ptr(-EINVAL);
14673 	}
14674 
14675 	err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, &link);
14676 	if (err)
14677 		return libbpf_err_ptr(err);
14678 
14679 	/* When calling bpf_program__attach() explicitly, auto-attach support
14680 	 * is expected to work, so NULL returned link is considered an error.
14681 	 * This is different for skeleton's attach, see comment in
14682 	 * bpf_object__attach_skeleton().
14683 	 */
14684 	if (!link)
14685 		return libbpf_err_ptr(-EOPNOTSUPP);
14686 
14687 	return link;
14688 }
14689 
14690 struct bpf_link_struct_ops {
14691 	struct bpf_link link;
14692 	int map_fd;
14693 };
14694 
14695 static int bpf_link__detach_struct_ops(struct bpf_link *link)
14696 {
14697 	struct bpf_link_struct_ops *st_link;
14698 	__u32 zero = 0;
14699 
14700 	st_link = container_of(link, struct bpf_link_struct_ops, link);
14701 
14702 	if (st_link->map_fd < 0)
14703 		/* w/o a real link */
14704 		return bpf_map_delete_elem(link->fd, &zero);
14705 
14706 	return close(link->fd);
14707 }
14708 
14709 struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map)
14710 {
14711 	struct bpf_link_struct_ops *link;
14712 	__u32 zero = 0;
14713 	int err, fd;
14714 
14715 	if (!bpf_map__is_struct_ops(map)) {
14716 		pr_warn("map '%s': can't attach non-struct_ops map\n", map->name);
14717 		return libbpf_err_ptr(-EINVAL);
14718 	}
14719 
14720 	if (map->fd < 0) {
14721 		pr_warn("map '%s': can't attach BPF map without FD (was it created?)\n", map->name);
14722 		return libbpf_err_ptr(-EINVAL);
14723 	}
14724 
14725 	link = calloc(1, sizeof(*link));
14726 	if (!link)
14727 		return libbpf_err_ptr(-EINVAL);
14728 
14729 	/* kern_vdata should be prepared during the loading phase. */
14730 	err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
14731 	/* It can be EBUSY if the map has been used to create or
14732 	 * update a link before.  We don't allow updating the value of
14733 	 * a struct_ops once it is set.  That ensures that the value
14734 	 * never changed.  So, it is safe to skip EBUSY.
14735 	 */
14736 	if (err && (!(map->def.map_flags & BPF_F_LINK) || err != -EBUSY)) {
14737 		free(link);
14738 		return libbpf_err_ptr(err);
14739 	}
14740 
14741 	link->link.detach = bpf_link__detach_struct_ops;
14742 
14743 	if (!(map->def.map_flags & BPF_F_LINK)) {
14744 		/* w/o a real link */
14745 		link->link.fd = map->fd;
14746 		link->map_fd = -1;
14747 		return &link->link;
14748 	}
14749 
14750 	fd = bpf_link_create(map->fd, 0, BPF_STRUCT_OPS, NULL);
14751 	if (fd < 0) {
14752 		free(link);
14753 		return libbpf_err_ptr(fd);
14754 	}
14755 
14756 	link->link.fd = fd;
14757 	link->map_fd = map->fd;
14758 
14759 	return &link->link;
14760 }
14761 
14762 struct bpf_link *bpf_map__attach_cgroup_opts(const struct bpf_map *map, int cgroup_fd,
14763 					     const struct bpf_cgroup_opts *opts)
14764 {
14765 	LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
14766 	struct bpf_link_struct_ops *link;
14767 	__u32 relative_id, zero = 0;
14768 	int err, fd, relative_fd;
14769 
14770 	if (!OPTS_VALID(opts, bpf_cgroup_opts))
14771 		return libbpf_err_ptr(-EINVAL);
14772 
14773 	if (!bpf_map__is_struct_ops(map)) {
14774 		pr_warn("map '%s': can't attach non-struct_ops map\n", map->name);
14775 		return libbpf_err_ptr(-EINVAL);
14776 	}
14777 
14778 	if (map->fd < 0) {
14779 		pr_warn("map '%s': can't attach BPF map without FD (was it created?)\n", map->name);
14780 		return libbpf_err_ptr(-EINVAL);
14781 	}
14782 
14783 	if (!(map->def.map_flags & BPF_F_LINK)) {
14784 		pr_warn("map '%s': can't attach to cgroup without BPF_F_LINK\n", map->name);
14785 		return libbpf_err_ptr(-EINVAL);
14786 	}
14787 
14788 	relative_id = OPTS_GET(opts, relative_id, 0);
14789 	relative_fd = OPTS_GET(opts, relative_fd, 0);
14790 
14791 	if (relative_fd && relative_id) {
14792 		pr_warn("map '%s': relative_fd and relative_id cannot be set at the same time\n",
14793 			map->name);
14794 		return libbpf_err_ptr(-EINVAL);
14795 	}
14796 
14797 	link_create_opts.cgroup.expected_revision = OPTS_GET(opts, expected_revision, 0);
14798 	link_create_opts.cgroup.relative_fd = relative_fd;
14799 	link_create_opts.cgroup.relative_id = relative_id;
14800 	link_create_opts.flags = OPTS_GET(opts, flags, 0);
14801 
14802 	link = calloc(1, sizeof(*link));
14803 	if (!link)
14804 		return libbpf_err_ptr(-ENOMEM);
14805 
14806 	err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
14807 	if (err && err != -EBUSY) {
14808 		free(link);
14809 		return libbpf_err_ptr(err);
14810 	}
14811 
14812 	link->link.detach = bpf_link__detach_struct_ops;
14813 
14814 	fd = bpf_link_create(map->fd, cgroup_fd, BPF_STRUCT_OPS, &link_create_opts);
14815 	if (fd < 0) {
14816 		free(link);
14817 		return libbpf_err_ptr(fd);
14818 	}
14819 
14820 	link->link.fd = fd;
14821 	link->map_fd = map->fd;
14822 
14823 	return &link->link;
14824 }
14825 
14826 /*
14827  * Swap the back struct_ops of a link with a new struct_ops map.
14828  */
14829 int bpf_link__update_map(struct bpf_link *link, const struct bpf_map *map)
14830 {
14831 	struct bpf_link_struct_ops *st_ops_link;
14832 	__u32 zero = 0;
14833 	int err;
14834 
14835 	if (!bpf_map__is_struct_ops(map))
14836 		return libbpf_err(-EINVAL);
14837 
14838 	if (map->fd < 0) {
14839 		pr_warn("map '%s': can't use BPF map without FD (was it created?)\n", map->name);
14840 		return libbpf_err(-EINVAL);
14841 	}
14842 
14843 	st_ops_link = container_of(link, struct bpf_link_struct_ops, link);
14844 	/* Ensure the type of a link is correct */
14845 	if (st_ops_link->map_fd < 0)
14846 		return libbpf_err(-EINVAL);
14847 
14848 	err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
14849 	/* It can be EBUSY if the map has been used to create or
14850 	 * update a link before.  We don't allow updating the value of
14851 	 * a struct_ops once it is set.  That ensures that the value
14852 	 * never changed.  So, it is safe to skip EBUSY.
14853 	 */
14854 	if (err && err != -EBUSY)
14855 		return err;
14856 
14857 	err = bpf_link_update(link->fd, map->fd, NULL);
14858 	if (err < 0)
14859 		return err;
14860 
14861 	st_ops_link->map_fd = map->fd;
14862 
14863 	return 0;
14864 }
14865 
14866 typedef enum bpf_perf_event_ret (*bpf_perf_event_print_t)(struct perf_event_header *hdr,
14867 							  void *private_data);
14868 
14869 static enum bpf_perf_event_ret
14870 perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
14871 		       void **copy_mem, size_t *copy_size,
14872 		       bpf_perf_event_print_t fn, void *private_data)
14873 {
14874 	struct perf_event_mmap_page *header = mmap_mem;
14875 	__u64 data_head = ring_buffer_read_head(header);
14876 	__u64 data_tail = header->data_tail;
14877 	void *base = ((__u8 *)header) + page_size;
14878 	int ret = LIBBPF_PERF_EVENT_CONT;
14879 	struct perf_event_header *ehdr;
14880 	size_t ehdr_size;
14881 
14882 	while (data_head != data_tail) {
14883 		ehdr = base + (data_tail & (mmap_size - 1));
14884 		ehdr_size = ehdr->size;
14885 
14886 		if (((void *)ehdr) + ehdr_size > base + mmap_size) {
14887 			void *copy_start = ehdr;
14888 			size_t len_first = base + mmap_size - copy_start;
14889 			size_t len_second = ehdr_size - len_first;
14890 
14891 			if (*copy_size < ehdr_size) {
14892 				free(*copy_mem);
14893 				*copy_mem = malloc(ehdr_size);
14894 				if (!*copy_mem) {
14895 					*copy_size = 0;
14896 					ret = LIBBPF_PERF_EVENT_ERROR;
14897 					break;
14898 				}
14899 				*copy_size = ehdr_size;
14900 			}
14901 
14902 			memcpy(*copy_mem, copy_start, len_first);
14903 			memcpy(*copy_mem + len_first, base, len_second);
14904 			ehdr = *copy_mem;
14905 		}
14906 
14907 		ret = fn(ehdr, private_data);
14908 		data_tail += ehdr_size;
14909 		if (ret != LIBBPF_PERF_EVENT_CONT)
14910 			break;
14911 	}
14912 
14913 	ring_buffer_write_tail(header, data_tail);
14914 	return libbpf_err(ret);
14915 }
14916 
14917 struct perf_buffer;
14918 
14919 struct perf_buffer_params {
14920 	struct perf_event_attr *attr;
14921 	/* if event_cb is specified, it takes precedence */
14922 	perf_buffer_event_fn event_cb;
14923 	/* sample_cb and lost_cb are higher-level common-case callbacks */
14924 	perf_buffer_sample_fn sample_cb;
14925 	perf_buffer_lost_fn lost_cb;
14926 	void *ctx;
14927 	int cpu_cnt;
14928 	int *cpus;
14929 	int *map_keys;
14930 };
14931 
14932 struct perf_cpu_buf {
14933 	struct perf_buffer *pb;
14934 	void *base; /* mmap()'ed memory */
14935 	void *buf; /* for reconstructing segmented data */
14936 	size_t buf_size;
14937 	int fd;
14938 	int cpu;
14939 	int map_key;
14940 };
14941 
14942 struct perf_buffer {
14943 	perf_buffer_event_fn event_cb;
14944 	perf_buffer_sample_fn sample_cb;
14945 	perf_buffer_lost_fn lost_cb;
14946 	void *ctx; /* passed into callbacks */
14947 
14948 	size_t page_size;
14949 	size_t mmap_size;
14950 	struct perf_cpu_buf **cpu_bufs;
14951 	struct epoll_event *events;
14952 	int cpu_cnt; /* number of allocated CPU buffers */
14953 	int epoll_fd; /* perf event FD */
14954 	int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
14955 };
14956 
14957 static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
14958 				      struct perf_cpu_buf *cpu_buf)
14959 {
14960 	if (!cpu_buf)
14961 		return;
14962 	if (cpu_buf->base &&
14963 	    munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
14964 		pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
14965 	if (cpu_buf->fd >= 0) {
14966 		ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
14967 		close(cpu_buf->fd);
14968 	}
14969 	free(cpu_buf->buf);
14970 	free(cpu_buf);
14971 }
14972 
14973 void perf_buffer__free(struct perf_buffer *pb)
14974 {
14975 	int i;
14976 
14977 	if (IS_ERR_OR_NULL(pb))
14978 		return;
14979 	if (pb->cpu_bufs) {
14980 		for (i = 0; i < pb->cpu_cnt; i++) {
14981 			struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
14982 
14983 			if (!cpu_buf)
14984 				continue;
14985 
14986 			bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
14987 			perf_buffer__free_cpu_buf(pb, cpu_buf);
14988 		}
14989 		free(pb->cpu_bufs);
14990 	}
14991 	if (pb->epoll_fd >= 0)
14992 		close(pb->epoll_fd);
14993 	free(pb->events);
14994 	free(pb);
14995 }
14996 
14997 static struct perf_cpu_buf *
14998 perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
14999 			  int cpu, int map_key)
15000 {
15001 	struct perf_cpu_buf *cpu_buf;
15002 	int err;
15003 
15004 	cpu_buf = calloc(1, sizeof(*cpu_buf));
15005 	if (!cpu_buf)
15006 		return ERR_PTR(-ENOMEM);
15007 
15008 	cpu_buf->pb = pb;
15009 	cpu_buf->cpu = cpu;
15010 	cpu_buf->map_key = map_key;
15011 
15012 	cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
15013 			      -1, PERF_FLAG_FD_CLOEXEC);
15014 	if (cpu_buf->fd < 0) {
15015 		err = -errno;
15016 		pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
15017 			cpu, errstr(err));
15018 		goto error;
15019 	}
15020 
15021 	cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
15022 			     PROT_READ | PROT_WRITE, MAP_SHARED,
15023 			     cpu_buf->fd, 0);
15024 	if (cpu_buf->base == MAP_FAILED) {
15025 		cpu_buf->base = NULL;
15026 		err = -errno;
15027 		pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
15028 			cpu, errstr(err));
15029 		goto error;
15030 	}
15031 
15032 	if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
15033 		err = -errno;
15034 		pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
15035 			cpu, errstr(err));
15036 		goto error;
15037 	}
15038 
15039 	return cpu_buf;
15040 
15041 error:
15042 	perf_buffer__free_cpu_buf(pb, cpu_buf);
15043 	return (struct perf_cpu_buf *)ERR_PTR(err);
15044 }
15045 
15046 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
15047 					      struct perf_buffer_params *p);
15048 
15049 struct perf_buffer *perf_buffer__new(int map_fd, size_t page_cnt,
15050 				     perf_buffer_sample_fn sample_cb,
15051 				     perf_buffer_lost_fn lost_cb,
15052 				     void *ctx,
15053 				     const struct perf_buffer_opts *opts)
15054 {
15055 	const size_t attr_sz = sizeof(struct perf_event_attr);
15056 	struct perf_buffer_params p = {};
15057 	struct perf_event_attr attr;
15058 	__u32 sample_period;
15059 
15060 	if (!OPTS_VALID(opts, perf_buffer_opts))
15061 		return libbpf_err_ptr(-EINVAL);
15062 
15063 	sample_period = OPTS_GET(opts, sample_period, 1);
15064 	if (!sample_period)
15065 		sample_period = 1;
15066 
15067 	memset(&attr, 0, attr_sz);
15068 	attr.size = attr_sz;
15069 	attr.config = PERF_COUNT_SW_BPF_OUTPUT;
15070 	attr.type = PERF_TYPE_SOFTWARE;
15071 	attr.sample_type = PERF_SAMPLE_RAW;
15072 	attr.wakeup_events = sample_period;
15073 
15074 	p.attr = &attr;
15075 	p.sample_cb = sample_cb;
15076 	p.lost_cb = lost_cb;
15077 	p.ctx = ctx;
15078 
15079 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
15080 }
15081 
15082 struct perf_buffer *perf_buffer__new_raw(int map_fd, size_t page_cnt,
15083 					 struct perf_event_attr *attr,
15084 					 perf_buffer_event_fn event_cb, void *ctx,
15085 					 const struct perf_buffer_raw_opts *opts)
15086 {
15087 	struct perf_buffer_params p = {};
15088 
15089 	if (!attr)
15090 		return libbpf_err_ptr(-EINVAL);
15091 
15092 	if (!OPTS_VALID(opts, perf_buffer_raw_opts))
15093 		return libbpf_err_ptr(-EINVAL);
15094 
15095 	p.attr = attr;
15096 	p.event_cb = event_cb;
15097 	p.ctx = ctx;
15098 	p.cpu_cnt = OPTS_GET(opts, cpu_cnt, 0);
15099 	p.cpus = OPTS_GET(opts, cpus, NULL);
15100 	p.map_keys = OPTS_GET(opts, map_keys, NULL);
15101 
15102 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
15103 }
15104 
15105 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
15106 					      struct perf_buffer_params *p)
15107 {
15108 	const char *online_cpus_file = "/sys/devices/system/cpu/online";
15109 	struct bpf_map_info map;
15110 	struct perf_buffer *pb;
15111 	bool *online = NULL;
15112 	__u32 map_info_len;
15113 	int err, i, j, n;
15114 
15115 	if (page_cnt == 0 || (page_cnt & (page_cnt - 1))) {
15116 		pr_warn("page count should be power of two, but is %zu\n",
15117 			page_cnt);
15118 		return ERR_PTR(-EINVAL);
15119 	}
15120 
15121 	/* best-effort sanity checks */
15122 	memset(&map, 0, sizeof(map));
15123 	map_info_len = sizeof(map);
15124 	err = bpf_map_get_info_by_fd(map_fd, &map, &map_info_len);
15125 	if (err) {
15126 		err = -errno;
15127 		/* if BPF_OBJ_GET_INFO_BY_FD is supported, will return
15128 		 * -EBADFD, -EFAULT, or -E2BIG on real error
15129 		 */
15130 		if (err != -EINVAL) {
15131 			pr_warn("failed to get map info for map FD %d: %s\n",
15132 				map_fd, errstr(err));
15133 			return ERR_PTR(err);
15134 		}
15135 		pr_debug("failed to get map info for FD %d; API not supported? Ignoring...\n",
15136 			 map_fd);
15137 	} else {
15138 		if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
15139 			pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
15140 				map.name);
15141 			return ERR_PTR(-EINVAL);
15142 		}
15143 	}
15144 
15145 	pb = calloc(1, sizeof(*pb));
15146 	if (!pb)
15147 		return ERR_PTR(-ENOMEM);
15148 
15149 	pb->event_cb = p->event_cb;
15150 	pb->sample_cb = p->sample_cb;
15151 	pb->lost_cb = p->lost_cb;
15152 	pb->ctx = p->ctx;
15153 
15154 	pb->page_size = getpagesize();
15155 	pb->mmap_size = pb->page_size * page_cnt;
15156 	pb->map_fd = map_fd;
15157 
15158 	pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
15159 	if (pb->epoll_fd < 0) {
15160 		err = -errno;
15161 		pr_warn("failed to create epoll instance: %s\n",
15162 			errstr(err));
15163 		goto error;
15164 	}
15165 
15166 	if (p->cpu_cnt > 0) {
15167 		pb->cpu_cnt = p->cpu_cnt;
15168 	} else {
15169 		pb->cpu_cnt = libbpf_num_possible_cpus();
15170 		if (pb->cpu_cnt < 0) {
15171 			err = pb->cpu_cnt;
15172 			goto error;
15173 		}
15174 		if (map.max_entries && map.max_entries < pb->cpu_cnt)
15175 			pb->cpu_cnt = map.max_entries;
15176 	}
15177 
15178 	pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
15179 	if (!pb->events) {
15180 		err = -ENOMEM;
15181 		pr_warn("failed to allocate events: out of memory\n");
15182 		goto error;
15183 	}
15184 	pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
15185 	if (!pb->cpu_bufs) {
15186 		err = -ENOMEM;
15187 		pr_warn("failed to allocate buffers: out of memory\n");
15188 		goto error;
15189 	}
15190 
15191 	err = parse_cpu_mask_file(online_cpus_file, &online, &n);
15192 	if (err) {
15193 		pr_warn("failed to get online CPU mask: %s\n", errstr(err));
15194 		goto error;
15195 	}
15196 
15197 	for (i = 0, j = 0; i < pb->cpu_cnt; i++) {
15198 		struct perf_cpu_buf *cpu_buf;
15199 		int cpu, map_key;
15200 
15201 		cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
15202 		map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
15203 
15204 		/* in case user didn't explicitly requested particular CPUs to
15205 		 * be attached to, skip offline/not present CPUs
15206 		 */
15207 		if (p->cpu_cnt <= 0 && (cpu >= n || !online[cpu]))
15208 			continue;
15209 
15210 		cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
15211 		if (IS_ERR(cpu_buf)) {
15212 			err = PTR_ERR(cpu_buf);
15213 			goto error;
15214 		}
15215 
15216 		pb->cpu_bufs[j] = cpu_buf;
15217 
15218 		err = bpf_map_update_elem(pb->map_fd, &map_key,
15219 					  &cpu_buf->fd, 0);
15220 		if (err) {
15221 			err = -errno;
15222 			pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
15223 				cpu, map_key, cpu_buf->fd,
15224 				errstr(err));
15225 			goto error;
15226 		}
15227 
15228 		pb->events[j].events = EPOLLIN;
15229 		pb->events[j].data.ptr = cpu_buf;
15230 		if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
15231 			      &pb->events[j]) < 0) {
15232 			err = -errno;
15233 			pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
15234 				cpu, cpu_buf->fd,
15235 				errstr(err));
15236 			goto error;
15237 		}
15238 		j++;
15239 	}
15240 	pb->cpu_cnt = j;
15241 	free(online);
15242 
15243 	return pb;
15244 
15245 error:
15246 	free(online);
15247 	if (pb)
15248 		perf_buffer__free(pb);
15249 	return ERR_PTR(err);
15250 }
15251 
15252 struct perf_sample_raw {
15253 	struct perf_event_header header;
15254 	uint32_t size;
15255 	char data[];
15256 };
15257 
15258 struct perf_sample_lost {
15259 	struct perf_event_header header;
15260 	uint64_t id;
15261 	uint64_t lost;
15262 	uint64_t sample_id;
15263 };
15264 
15265 static enum bpf_perf_event_ret
15266 perf_buffer__process_record(struct perf_event_header *e, void *ctx)
15267 {
15268 	struct perf_cpu_buf *cpu_buf = ctx;
15269 	struct perf_buffer *pb = cpu_buf->pb;
15270 	void *data = e;
15271 
15272 	/* user wants full control over parsing perf event */
15273 	if (pb->event_cb)
15274 		return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
15275 
15276 	switch (e->type) {
15277 	case PERF_RECORD_SAMPLE: {
15278 		struct perf_sample_raw *s = data;
15279 
15280 		if (pb->sample_cb)
15281 			pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
15282 		break;
15283 	}
15284 	case PERF_RECORD_LOST: {
15285 		struct perf_sample_lost *s = data;
15286 
15287 		if (pb->lost_cb)
15288 			pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
15289 		break;
15290 	}
15291 	default:
15292 		pr_warn("unknown perf sample type %u\n", e->type);
15293 		return LIBBPF_PERF_EVENT_ERROR;
15294 	}
15295 	return LIBBPF_PERF_EVENT_CONT;
15296 }
15297 
15298 static int perf_buffer__process_records(struct perf_buffer *pb,
15299 					struct perf_cpu_buf *cpu_buf)
15300 {
15301 	enum bpf_perf_event_ret ret;
15302 
15303 	ret = perf_event_read_simple(cpu_buf->base, pb->mmap_size,
15304 				     pb->page_size, &cpu_buf->buf,
15305 				     &cpu_buf->buf_size,
15306 				     perf_buffer__process_record, cpu_buf);
15307 	if (ret != LIBBPF_PERF_EVENT_CONT)
15308 		return ret;
15309 	return 0;
15310 }
15311 
15312 int perf_buffer__epoll_fd(const struct perf_buffer *pb)
15313 {
15314 	return pb->epoll_fd;
15315 }
15316 
15317 int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
15318 {
15319 	int i, cnt, err;
15320 
15321 	cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
15322 	if (cnt < 0)
15323 		return -errno;
15324 
15325 	for (i = 0; i < cnt; i++) {
15326 		struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
15327 
15328 		err = perf_buffer__process_records(pb, cpu_buf);
15329 		if (err) {
15330 			pr_warn("error while processing records: %s\n", errstr(err));
15331 			return libbpf_err(err);
15332 		}
15333 	}
15334 	return cnt;
15335 }
15336 
15337 /* Return number of PERF_EVENT_ARRAY map slots set up by this perf_buffer
15338  * manager.
15339  */
15340 size_t perf_buffer__buffer_cnt(const struct perf_buffer *pb)
15341 {
15342 	return pb->cpu_cnt;
15343 }
15344 
15345 /*
15346  * Return perf_event FD of a ring buffer in *buf_idx* slot of
15347  * PERF_EVENT_ARRAY BPF map. This FD can be polled for new data using
15348  * select()/poll()/epoll() Linux syscalls.
15349  */
15350 int perf_buffer__buffer_fd(const struct perf_buffer *pb, size_t buf_idx)
15351 {
15352 	struct perf_cpu_buf *cpu_buf;
15353 
15354 	if (buf_idx >= pb->cpu_cnt)
15355 		return libbpf_err(-EINVAL);
15356 
15357 	cpu_buf = pb->cpu_bufs[buf_idx];
15358 	if (!cpu_buf)
15359 		return libbpf_err(-ENOENT);
15360 
15361 	return cpu_buf->fd;
15362 }
15363 
15364 int perf_buffer__buffer(struct perf_buffer *pb, int buf_idx, void **buf, size_t *buf_size)
15365 {
15366 	struct perf_cpu_buf *cpu_buf;
15367 
15368 	if (buf_idx >= pb->cpu_cnt)
15369 		return libbpf_err(-EINVAL);
15370 
15371 	cpu_buf = pb->cpu_bufs[buf_idx];
15372 	if (!cpu_buf)
15373 		return libbpf_err(-ENOENT);
15374 
15375 	*buf = cpu_buf->base;
15376 	*buf_size = pb->mmap_size;
15377 	return 0;
15378 }
15379 
15380 /*
15381  * Consume data from perf ring buffer corresponding to slot *buf_idx* in
15382  * PERF_EVENT_ARRAY BPF map without waiting/polling. If there is no data to
15383  * consume, do nothing and return success.
15384  * Returns:
15385  *   - 0 on success;
15386  *   - <0 on failure.
15387  */
15388 int perf_buffer__consume_buffer(struct perf_buffer *pb, size_t buf_idx)
15389 {
15390 	struct perf_cpu_buf *cpu_buf;
15391 
15392 	if (buf_idx >= pb->cpu_cnt)
15393 		return libbpf_err(-EINVAL);
15394 
15395 	cpu_buf = pb->cpu_bufs[buf_idx];
15396 	if (!cpu_buf)
15397 		return libbpf_err(-ENOENT);
15398 
15399 	return perf_buffer__process_records(pb, cpu_buf);
15400 }
15401 
15402 int perf_buffer__consume(struct perf_buffer *pb)
15403 {
15404 	int i, err;
15405 
15406 	for (i = 0; i < pb->cpu_cnt; i++) {
15407 		struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
15408 
15409 		if (!cpu_buf)
15410 			continue;
15411 
15412 		err = perf_buffer__process_records(pb, cpu_buf);
15413 		if (err) {
15414 			pr_warn("perf_buffer: failed to process records in buffer #%d: %s\n",
15415 				i, errstr(err));
15416 			return libbpf_err(err);
15417 		}
15418 	}
15419 	return 0;
15420 }
15421 
15422 int bpf_program__set_attach_target(struct bpf_program *prog,
15423 				   int attach_prog_fd,
15424 				   const char *attach_func_name)
15425 {
15426 	int btf_obj_fd = 0, btf_id = 0, err;
15427 
15428 	if (!prog || attach_prog_fd < 0)
15429 		return libbpf_err(-EINVAL);
15430 
15431 	if (prog->obj->state >= OBJ_LOADED)
15432 		return libbpf_err(-EINVAL);
15433 
15434 	if (attach_prog_fd && !attach_func_name) {
15435 		/* Store attach_prog_fd. The BTF ID will be resolved later during
15436 		 * the normal object/program load phase.
15437 		 */
15438 		prog->attach_prog_fd = attach_prog_fd;
15439 		return 0;
15440 	}
15441 
15442 	if (attach_prog_fd) {
15443 		btf_id = libbpf_find_prog_btf_id(attach_func_name,
15444 						 attach_prog_fd, prog->obj->token_fd);
15445 		if (btf_id < 0)
15446 			return libbpf_err(btf_id);
15447 	} else {
15448 		if (!attach_func_name)
15449 			return libbpf_err(-EINVAL);
15450 
15451 		/* load btf_vmlinux, if not yet */
15452 		err = bpf_object__load_vmlinux_btf(prog->obj, true);
15453 		if (err)
15454 			return libbpf_err(err);
15455 		err = find_kernel_btf_id(prog->obj, attach_func_name,
15456 					 prog->expected_attach_type,
15457 					 &btf_obj_fd, &btf_id);
15458 		if (err)
15459 			return libbpf_err(err);
15460 	}
15461 
15462 	prog->attach_btf_id = btf_id;
15463 	prog->attach_btf_obj_fd = btf_obj_fd;
15464 	prog->attach_prog_fd = attach_prog_fd;
15465 	return 0;
15466 }
15467 
15468 int bpf_program__assoc_struct_ops(struct bpf_program *prog, struct bpf_map *map,
15469 				  struct bpf_prog_assoc_struct_ops_opts *opts)
15470 {
15471 	int prog_fd, map_fd;
15472 
15473 	prog_fd = bpf_program__fd(prog);
15474 	if (prog_fd < 0) {
15475 		pr_warn("prog '%s': can't associate BPF program without FD (was it loaded?)\n",
15476 			prog->name);
15477 		return libbpf_err(-EINVAL);
15478 	}
15479 
15480 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS) {
15481 		pr_warn("prog '%s': can't associate struct_ops program\n", prog->name);
15482 		return libbpf_err(-EINVAL);
15483 	}
15484 
15485 	map_fd = bpf_map__fd(map);
15486 	if (map_fd < 0) {
15487 		pr_warn("map '%s': can't associate BPF map without FD (was it created?)\n", map->name);
15488 		return libbpf_err(-EINVAL);
15489 	}
15490 
15491 	if (!bpf_map__is_struct_ops(map)) {
15492 		pr_warn("map '%s': can't associate non-struct_ops map\n", map->name);
15493 		return libbpf_err(-EINVAL);
15494 	}
15495 
15496 	return bpf_prog_assoc_struct_ops(prog_fd, map_fd, opts);
15497 }
15498 
15499 int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz)
15500 {
15501 	int err = 0, n, len, start, end = -1;
15502 	bool *tmp;
15503 
15504 	*mask = NULL;
15505 	*mask_sz = 0;
15506 
15507 	/* Each sub string separated by ',' has format \d+-\d+ or \d+ */
15508 	while (*s) {
15509 		if (*s == ',' || *s == '\n') {
15510 			s++;
15511 			continue;
15512 		}
15513 		n = sscanf(s, "%d%n-%d%n", &start, &len, &end, &len);
15514 		if (n <= 0 || n > 2) {
15515 			pr_warn("Failed to get CPU range %s: %d\n", s, n);
15516 			err = -EINVAL;
15517 			goto cleanup;
15518 		} else if (n == 1) {
15519 			end = start;
15520 		}
15521 		if (start < 0 || start > end) {
15522 			pr_warn("Invalid CPU range [%d,%d] in %s\n",
15523 				start, end, s);
15524 			err = -EINVAL;
15525 			goto cleanup;
15526 		}
15527 		tmp = realloc(*mask, end + 1);
15528 		if (!tmp) {
15529 			err = -ENOMEM;
15530 			goto cleanup;
15531 		}
15532 		*mask = tmp;
15533 		memset(tmp + *mask_sz, 0, start - *mask_sz);
15534 		memset(tmp + start, 1, end - start + 1);
15535 		*mask_sz = end + 1;
15536 		s += len;
15537 	}
15538 	if (!*mask_sz) {
15539 		pr_warn("Empty CPU range\n");
15540 		return -EINVAL;
15541 	}
15542 	return 0;
15543 cleanup:
15544 	free(*mask);
15545 	*mask = NULL;
15546 	return err;
15547 }
15548 
15549 int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz)
15550 {
15551 	int fd, err = 0, len;
15552 	char buf[128];
15553 
15554 	fd = open(fcpu, O_RDONLY | O_CLOEXEC);
15555 	if (fd < 0) {
15556 		err = -errno;
15557 		pr_warn("Failed to open cpu mask file %s: %s\n", fcpu, errstr(err));
15558 		return err;
15559 	}
15560 	len = read(fd, buf, sizeof(buf));
15561 	close(fd);
15562 	if (len <= 0) {
15563 		err = len ? -errno : -EINVAL;
15564 		pr_warn("Failed to read cpu mask from %s: %s\n", fcpu, errstr(err));
15565 		return err;
15566 	}
15567 	if (len >= sizeof(buf)) {
15568 		pr_warn("CPU mask is too big in file %s\n", fcpu);
15569 		return -E2BIG;
15570 	}
15571 	buf[len] = '\0';
15572 
15573 	return parse_cpu_mask_str(buf, mask, mask_sz);
15574 }
15575 
15576 int libbpf_num_possible_cpus(void)
15577 {
15578 	static const char *fcpu = "/sys/devices/system/cpu/possible";
15579 	static int cpus;
15580 	int err, n, i, tmp_cpus;
15581 	bool *mask;
15582 
15583 	tmp_cpus = READ_ONCE(cpus);
15584 	if (tmp_cpus > 0)
15585 		return tmp_cpus;
15586 
15587 	err = parse_cpu_mask_file(fcpu, &mask, &n);
15588 	if (err)
15589 		return libbpf_err(err);
15590 
15591 	tmp_cpus = 0;
15592 	for (i = 0; i < n; i++) {
15593 		if (mask[i])
15594 			tmp_cpus++;
15595 	}
15596 	free(mask);
15597 
15598 	WRITE_ONCE(cpus, tmp_cpus);
15599 	return tmp_cpus;
15600 }
15601 
15602 static int populate_skeleton_maps(const struct bpf_object *obj,
15603 				  struct bpf_map_skeleton *maps,
15604 				  size_t map_cnt, size_t map_skel_sz)
15605 {
15606 	int i;
15607 
15608 	for (i = 0; i < map_cnt; i++) {
15609 		struct bpf_map_skeleton *map_skel = (void *)maps + i * map_skel_sz;
15610 		struct bpf_map **map = map_skel->map;
15611 		const char *name = map_skel->name;
15612 		void **mmaped = map_skel->mmaped;
15613 
15614 		*map = bpf_object__find_map_by_name(obj, name);
15615 		if (!*map) {
15616 			pr_warn("failed to find skeleton map '%s'\n", name);
15617 			return -ESRCH;
15618 		}
15619 
15620 		/* externs shouldn't be pre-setup from user code */
15621 		if (mmaped && (*map)->libbpf_type != LIBBPF_MAP_KCONFIG)
15622 			*mmaped = (*map)->mmaped;
15623 	}
15624 	return 0;
15625 }
15626 
15627 static int populate_skeleton_progs(const struct bpf_object *obj,
15628 				   struct bpf_prog_skeleton *progs,
15629 				   size_t prog_cnt, size_t prog_skel_sz)
15630 {
15631 	int i;
15632 
15633 	for (i = 0; i < prog_cnt; i++) {
15634 		struct bpf_prog_skeleton *prog_skel = (void *)progs + i * prog_skel_sz;
15635 		struct bpf_program **prog = prog_skel->prog;
15636 		const char *name = prog_skel->name;
15637 
15638 		*prog = bpf_object__find_program_by_name(obj, name);
15639 		if (!*prog) {
15640 			pr_warn("failed to find skeleton program '%s'\n", name);
15641 			return -ESRCH;
15642 		}
15643 	}
15644 	return 0;
15645 }
15646 
15647 int bpf_object__open_skeleton(struct bpf_object_skeleton *s,
15648 			      const struct bpf_object_open_opts *opts)
15649 {
15650 	struct bpf_object *obj;
15651 	int err;
15652 
15653 	obj = bpf_object_open(NULL, s->data, s->data_sz, s->name, opts);
15654 	if (IS_ERR(obj)) {
15655 		err = PTR_ERR(obj);
15656 		pr_warn("failed to initialize skeleton BPF object '%s': %s\n",
15657 			s->name, errstr(err));
15658 		return libbpf_err(err);
15659 	}
15660 
15661 	*s->obj = obj;
15662 	err = populate_skeleton_maps(obj, s->maps, s->map_cnt, s->map_skel_sz);
15663 	if (err) {
15664 		pr_warn("failed to populate skeleton maps for '%s': %s\n", s->name, errstr(err));
15665 		return libbpf_err(err);
15666 	}
15667 
15668 	err = populate_skeleton_progs(obj, s->progs, s->prog_cnt, s->prog_skel_sz);
15669 	if (err) {
15670 		pr_warn("failed to populate skeleton progs for '%s': %s\n", s->name, errstr(err));
15671 		return libbpf_err(err);
15672 	}
15673 
15674 	return 0;
15675 }
15676 
15677 int bpf_object__open_subskeleton(struct bpf_object_subskeleton *s)
15678 {
15679 	int err, len, var_idx, i;
15680 	const char *var_name;
15681 	const struct bpf_map *map;
15682 	struct btf *btf;
15683 	__u32 map_type_id;
15684 	const struct btf_type *map_type, *var_type;
15685 	const struct bpf_var_skeleton *var_skel;
15686 	struct btf_var_secinfo *var;
15687 
15688 	if (!s->obj)
15689 		return libbpf_err(-EINVAL);
15690 
15691 	btf = bpf_object__btf(s->obj);
15692 	if (!btf) {
15693 		pr_warn("subskeletons require BTF at runtime (object %s)\n",
15694 			bpf_object__name(s->obj));
15695 		return libbpf_err(-errno);
15696 	}
15697 
15698 	err = populate_skeleton_maps(s->obj, s->maps, s->map_cnt, s->map_skel_sz);
15699 	if (err) {
15700 		pr_warn("failed to populate subskeleton maps: %s\n", errstr(err));
15701 		return libbpf_err(err);
15702 	}
15703 
15704 	err = populate_skeleton_progs(s->obj, s->progs, s->prog_cnt, s->prog_skel_sz);
15705 	if (err) {
15706 		pr_warn("failed to populate subskeleton maps: %s\n", errstr(err));
15707 		return libbpf_err(err);
15708 	}
15709 
15710 	for (var_idx = 0; var_idx < s->var_cnt; var_idx++) {
15711 		var_skel = (void *)s->vars + var_idx * s->var_skel_sz;
15712 		map = *var_skel->map;
15713 		map_type_id = bpf_map__btf_value_type_id(map);
15714 		map_type = btf__type_by_id(btf, map_type_id);
15715 
15716 		if (!btf_is_datasec(map_type)) {
15717 			pr_warn("type for map '%1$s' is not a datasec: %2$s\n",
15718 				bpf_map__name(map),
15719 				__btf_kind_str(btf_kind(map_type)));
15720 			return libbpf_err(-EINVAL);
15721 		}
15722 
15723 		len = btf_vlen(map_type);
15724 		var = btf_var_secinfos(map_type);
15725 		for (i = 0; i < len; i++, var++) {
15726 			var_type = btf__type_by_id(btf, var->type);
15727 			var_name = btf__name_by_offset(btf, var_type->name_off);
15728 			if (strcmp(var_name, var_skel->name) == 0) {
15729 				*var_skel->addr = map->mmaped + var->offset;
15730 				break;
15731 			}
15732 		}
15733 	}
15734 	return 0;
15735 }
15736 
15737 void bpf_object__destroy_subskeleton(struct bpf_object_subskeleton *s)
15738 {
15739 	if (!s)
15740 		return;
15741 	free(s->maps);
15742 	free(s->progs);
15743 	free(s->vars);
15744 	free(s);
15745 }
15746 
15747 int bpf_object__load_skeleton(struct bpf_object_skeleton *s)
15748 {
15749 	int i, err;
15750 
15751 	err = bpf_object__load(*s->obj);
15752 	if (err) {
15753 		pr_warn("failed to load BPF skeleton '%s': %s\n", s->name, errstr(err));
15754 		return libbpf_err(err);
15755 	}
15756 
15757 	for (i = 0; i < s->map_cnt; i++) {
15758 		struct bpf_map_skeleton *map_skel = (void *)s->maps + i * s->map_skel_sz;
15759 		struct bpf_map *map = *map_skel->map;
15760 
15761 		if (!map_skel->mmaped)
15762 			continue;
15763 
15764 		if (map->def.type == BPF_MAP_TYPE_ARENA)
15765 			*map_skel->mmaped = map->mmaped + map->obj->arena_data_off;
15766 		else
15767 			*map_skel->mmaped = map->mmaped;
15768 	}
15769 
15770 	return 0;
15771 }
15772 
15773 int bpf_object__attach_skeleton(struct bpf_object_skeleton *s)
15774 {
15775 	int i, err;
15776 
15777 	for (i = 0; i < s->prog_cnt; i++) {
15778 		struct bpf_prog_skeleton *prog_skel = (void *)s->progs + i * s->prog_skel_sz;
15779 		struct bpf_program *prog = *prog_skel->prog;
15780 		struct bpf_link **link = prog_skel->link;
15781 
15782 		if (!prog->autoload || !prog->autoattach)
15783 			continue;
15784 
15785 		/* auto-attaching not supported for this program */
15786 		if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
15787 			continue;
15788 
15789 		/* if user already set the link manually, don't attempt auto-attach */
15790 		if (*link)
15791 			continue;
15792 
15793 		err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, link);
15794 		if (err) {
15795 			pr_warn("prog '%s': failed to auto-attach: %s\n",
15796 				bpf_program__name(prog), errstr(err));
15797 			return libbpf_err(err);
15798 		}
15799 
15800 		/* It's possible that for some SEC() definitions auto-attach
15801 		 * is supported in some cases (e.g., if definition completely
15802 		 * specifies target information), but is not in other cases.
15803 		 * SEC("uprobe") is one such case. If user specified target
15804 		 * binary and function name, such BPF program can be
15805 		 * auto-attached. But if not, it shouldn't trigger skeleton's
15806 		 * attach to fail. It should just be skipped.
15807 		 * attach_fn signals such case with returning 0 (no error) and
15808 		 * setting link to NULL.
15809 		 */
15810 	}
15811 
15812 
15813 	for (i = 0; i < s->map_cnt; i++) {
15814 		struct bpf_map_skeleton *map_skel = (void *)s->maps + i * s->map_skel_sz;
15815 		struct bpf_map *map = *map_skel->map;
15816 		struct bpf_link **link;
15817 
15818 		if (!map->autocreate || !map->autoattach)
15819 			continue;
15820 
15821 		/* only struct_ops maps can be attached */
15822 		if (!bpf_map__is_struct_ops(map))
15823 			continue;
15824 
15825 		/* skeleton is created with earlier version of bpftool, notify user */
15826 		if (s->map_skel_sz < offsetofend(struct bpf_map_skeleton, link)) {
15827 			pr_warn("map '%s': BPF skeleton version is old, skipping map auto-attachment...\n",
15828 				bpf_map__name(map));
15829 			continue;
15830 		}
15831 
15832 		link = map_skel->link;
15833 		if (!link) {
15834 			pr_warn("map '%s': BPF map skeleton link is uninitialized\n",
15835 				bpf_map__name(map));
15836 			continue;
15837 		}
15838 
15839 		if (*link)
15840 			continue;
15841 
15842 		*link = bpf_map__attach_struct_ops(map);
15843 		if (!*link) {
15844 			err = -errno;
15845 			pr_warn("map '%s': failed to auto-attach: %s\n",
15846 				bpf_map__name(map), errstr(err));
15847 			return libbpf_err(err);
15848 		}
15849 	}
15850 
15851 	return 0;
15852 }
15853 
15854 void bpf_object__detach_skeleton(struct bpf_object_skeleton *s)
15855 {
15856 	int i;
15857 
15858 	for (i = 0; i < s->prog_cnt; i++) {
15859 		struct bpf_prog_skeleton *prog_skel = (void *)s->progs + i * s->prog_skel_sz;
15860 		struct bpf_link **link = prog_skel->link;
15861 
15862 		bpf_link__destroy(*link);
15863 		*link = NULL;
15864 	}
15865 
15866 	if (s->map_skel_sz < sizeof(struct bpf_map_skeleton))
15867 		return;
15868 
15869 	for (i = 0; i < s->map_cnt; i++) {
15870 		struct bpf_map_skeleton *map_skel = (void *)s->maps + i * s->map_skel_sz;
15871 		struct bpf_link **link = map_skel->link;
15872 
15873 		if (link) {
15874 			bpf_link__destroy(*link);
15875 			*link = NULL;
15876 		}
15877 	}
15878 }
15879 
15880 void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s)
15881 {
15882 	if (!s)
15883 		return;
15884 
15885 	bpf_object__detach_skeleton(s);
15886 	if (s->obj)
15887 		bpf_object__close(*s->obj);
15888 	free(s->maps);
15889 	free(s->progs);
15890 	free(s);
15891 }
15892