xref: /linux/tools/lib/bpf/libbpf.c (revision f2aa370dfe571abf51631c1ac27bb58d5d0e3466)
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 	bool mark_btf_static;
501 	enum bpf_prog_type type;
502 	enum bpf_attach_type expected_attach_type;
503 	int exception_cb_idx;
504 
505 	int prog_ifindex;
506 	__u32 attach_btf_obj_fd;
507 	__u32 attach_btf_id;
508 	__u32 attach_prog_fd;
509 
510 	void *func_info;
511 	__u32 func_info_rec_size;
512 	__u32 func_info_cnt;
513 
514 	void *line_info;
515 	__u32 line_info_rec_size;
516 	__u32 line_info_cnt;
517 	__u32 prog_flags;
518 	__u8  hash[SHA256_DIGEST_LENGTH];
519 
520 	struct bpf_light_subprog *subprogs;
521 	__u32 subprog_cnt;
522 };
523 
524 struct bpf_struct_ops {
525 	struct bpf_program **progs;
526 	__u32 *kern_func_off;
527 	/* e.g. struct tcp_congestion_ops in bpf_prog's btf format */
528 	void *data;
529 	/* e.g. struct bpf_struct_ops_tcp_congestion_ops in
530 	 *      btf_vmlinux's format.
531 	 * struct bpf_struct_ops_tcp_congestion_ops {
532 	 *	[... some other kernel fields ...]
533 	 *	struct tcp_congestion_ops data;
534 	 * }
535 	 * kern_vdata-size == sizeof(struct bpf_struct_ops_tcp_congestion_ops)
536 	 * bpf_map__init_kern_struct_ops() will populate the "kern_vdata"
537 	 * from "data".
538 	 */
539 	void *kern_vdata;
540 	__u32 type_id;
541 };
542 
543 #define DATA_SEC ".data"
544 #define BSS_SEC ".bss"
545 #define RODATA_SEC ".rodata"
546 #define KCONFIG_SEC ".kconfig"
547 #define KSYMS_SEC ".ksyms"
548 #define STRUCT_OPS_SEC ".struct_ops"
549 #define STRUCT_OPS_LINK_SEC ".struct_ops.link"
550 #define ARENA_SEC ".addr_space.1"
551 
552 enum libbpf_map_type {
553 	LIBBPF_MAP_UNSPEC,
554 	LIBBPF_MAP_DATA,
555 	LIBBPF_MAP_BSS,
556 	LIBBPF_MAP_RODATA,
557 	LIBBPF_MAP_KCONFIG,
558 };
559 
560 struct bpf_map_def {
561 	unsigned int type;
562 	unsigned int key_size;
563 	unsigned int value_size;
564 	unsigned int max_entries;
565 	unsigned int map_flags;
566 };
567 
568 struct bpf_map {
569 	struct bpf_object *obj;
570 	char *name;
571 	/* real_name is defined for special internal maps (.rodata*,
572 	 * .data*, .bss, .kconfig) and preserves their original ELF section
573 	 * name. This is important to be able to find corresponding BTF
574 	 * DATASEC information.
575 	 */
576 	char *real_name;
577 	int fd;
578 	int sec_idx;
579 	size_t sec_offset;
580 	int map_ifindex;
581 	int inner_map_fd;
582 	struct bpf_map_def def;
583 	__u32 numa_node;
584 	__u32 btf_var_idx;
585 	int mod_btf_fd;
586 	__u32 btf_key_type_id;
587 	__u32 btf_value_type_id;
588 	__u32 btf_vmlinux_value_type_id;
589 	enum libbpf_map_type libbpf_type;
590 	void *mmaped;
591 	struct bpf_struct_ops *st_ops;
592 	struct bpf_map *inner_map;
593 	void **init_slots;
594 	int init_slots_sz;
595 	char *pin_path;
596 	bool pinned;
597 	bool reused;
598 	bool autocreate;
599 	bool autoattach;
600 	__u64 map_extra;
601 	struct bpf_program *excl_prog;
602 };
603 
604 enum extern_type {
605 	EXT_UNKNOWN,
606 	EXT_KCFG,
607 	EXT_KSYM,
608 };
609 
610 enum kcfg_type {
611 	KCFG_UNKNOWN,
612 	KCFG_CHAR,
613 	KCFG_BOOL,
614 	KCFG_INT,
615 	KCFG_TRISTATE,
616 	KCFG_CHAR_ARR,
617 };
618 
619 struct extern_desc {
620 	enum extern_type type;
621 	int sym_idx;
622 	int btf_id;
623 	int sec_btf_id;
624 	char *name;
625 	char *essent_name;
626 	bool is_set;
627 	bool is_weak;
628 	union {
629 		struct {
630 			enum kcfg_type type;
631 			int sz;
632 			int align;
633 			int data_off;
634 			bool is_signed;
635 		} kcfg;
636 		struct {
637 			unsigned long long addr;
638 
639 			/* target btf_id of the corresponding kernel var. */
640 			int kernel_btf_obj_fd;
641 			int kernel_btf_id;
642 
643 			/* local btf_id of the ksym extern's type. */
644 			__u32 type_id;
645 			/* BTF fd index to be patched in for insn->off, this is
646 			 * 0 for vmlinux BTF, index in obj->fd_array for module
647 			 * BTF
648 			 */
649 			__s16 btf_fd_idx;
650 		} ksym;
651 	};
652 };
653 
654 struct module_btf {
655 	struct btf *btf;
656 	char *name;
657 	__u32 id;
658 	int fd;
659 	int fd_array_idx;
660 };
661 
662 enum sec_type {
663 	SEC_UNUSED = 0,
664 	SEC_RELO,
665 	SEC_BSS,
666 	SEC_DATA,
667 	SEC_RODATA,
668 	SEC_ST_OPS,
669 };
670 
671 struct elf_sec_desc {
672 	enum sec_type sec_type;
673 	Elf64_Shdr *shdr;
674 	Elf_Data *data;
675 };
676 
677 struct elf_state {
678 	int fd;
679 	const void *obj_buf;
680 	size_t obj_buf_sz;
681 	Elf *elf;
682 	Elf64_Ehdr *ehdr;
683 	Elf_Data *symbols;
684 	Elf_Data *arena_data;
685 	size_t shstrndx; /* section index for section name strings */
686 	size_t strtabidx;
687 	struct elf_sec_desc *secs;
688 	size_t sec_cnt;
689 	int btf_maps_shndx;
690 	__u32 btf_maps_sec_btf_id;
691 	int text_shndx;
692 	int symbols_shndx;
693 	bool has_st_ops;
694 	int arena_data_shndx;
695 	int jumptables_data_shndx;
696 };
697 
698 struct usdt_manager;
699 
700 enum bpf_object_state {
701 	OBJ_OPEN,
702 	OBJ_PREPARED,
703 	OBJ_LOADED,
704 };
705 
706 struct bpf_object {
707 	char name[BPF_OBJ_NAME_LEN];
708 	char license[64];
709 	__u32 kern_version;
710 
711 	enum bpf_object_state state;
712 	struct bpf_program *programs;
713 	size_t nr_programs;
714 	struct bpf_map *maps;
715 	size_t nr_maps;
716 	size_t maps_cap;
717 
718 	char *kconfig;
719 	struct extern_desc *externs;
720 	int nr_extern;
721 	int kconfig_map_idx;
722 
723 	bool has_subcalls;
724 	bool has_rodata;
725 
726 	struct bpf_gen *gen_loader;
727 
728 	/* Information when doing ELF related work. Only valid if efile.elf is not NULL */
729 	struct elf_state efile;
730 
731 	unsigned char byteorder;
732 
733 	struct btf *btf;
734 	struct btf_ext *btf_ext;
735 
736 	/* Parse and load BTF vmlinux if any of the programs in the object need
737 	 * it at load time.
738 	 */
739 	struct btf *btf_vmlinux;
740 	/* Path to the custom BTF to be used for BPF CO-RE relocations as an
741 	 * override for vmlinux BTF.
742 	 */
743 	char *btf_custom_path;
744 	/* vmlinux BTF override for CO-RE relocations */
745 	struct btf *btf_vmlinux_override;
746 	/* Lazily initialized kernel module BTFs */
747 	struct module_btf *btf_modules;
748 	bool btf_modules_loaded;
749 	size_t btf_module_cnt;
750 	size_t btf_module_cap;
751 
752 	/* optional log settings passed to BPF_BTF_LOAD and BPF_PROG_LOAD commands */
753 	char *log_buf;
754 	size_t log_size;
755 	__u32 log_level;
756 
757 	int *fd_array;
758 	size_t fd_array_cap;
759 	size_t fd_array_cnt;
760 
761 	struct usdt_manager *usdt_man;
762 
763 	int arena_map_idx;
764 	void *arena_data;
765 	size_t arena_data_sz;
766 	size_t arena_data_off;
767 
768 	void *jumptables_data;
769 	size_t jumptables_data_sz;
770 
771 	struct {
772 		struct bpf_program *prog;
773 		unsigned int sym_off;
774 		int fd;
775 	} *jumptable_maps;
776 	size_t jumptable_map_cnt;
777 
778 	struct kern_feature_cache *feat_cache;
779 	char *token_path;
780 	int token_fd;
781 
782 	char path[];
783 };
784 
785 static const char *elf_sym_str(const struct bpf_object *obj, size_t off);
786 static const char *elf_sec_str(const struct bpf_object *obj, size_t off);
787 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx);
788 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name);
789 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn);
790 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn);
791 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn);
792 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx);
793 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx);
794 
795 void bpf_program__unload(struct bpf_program *prog)
796 {
797 	if (!prog)
798 		return;
799 
800 	zclose(prog->fd);
801 
802 	zfree(&prog->func_info);
803 	zfree(&prog->line_info);
804 	zfree(&prog->subprogs);
805 }
806 
807 static void bpf_program__exit(struct bpf_program *prog)
808 {
809 	if (!prog)
810 		return;
811 
812 	bpf_program__unload(prog);
813 	zfree(&prog->name);
814 	zfree(&prog->sec_name);
815 	zfree(&prog->insns);
816 	zfree(&prog->reloc_desc);
817 
818 	prog->nr_reloc = 0;
819 	prog->insns_cnt = 0;
820 	prog->sec_idx = -1;
821 }
822 
823 static bool insn_is_subprog_call(const struct bpf_insn *insn)
824 {
825 	return BPF_CLASS(insn->code) == BPF_JMP &&
826 	       BPF_OP(insn->code) == BPF_CALL &&
827 	       BPF_SRC(insn->code) == BPF_K &&
828 	       insn->src_reg == BPF_PSEUDO_CALL &&
829 	       insn->dst_reg == 0 &&
830 	       insn->off == 0;
831 }
832 
833 static bool is_call_insn(const struct bpf_insn *insn)
834 {
835 	return insn->code == (BPF_JMP | BPF_CALL);
836 }
837 
838 static bool insn_is_pseudo_func(struct bpf_insn *insn)
839 {
840 	return is_ldimm64_insn(insn) && insn->src_reg == BPF_PSEUDO_FUNC;
841 }
842 
843 static int
844 bpf_object__init_prog(struct bpf_object *obj, struct bpf_program *prog,
845 		      const char *name, size_t sec_idx, const char *sec_name,
846 		      size_t sec_off, void *insn_data, size_t insn_data_sz)
847 {
848 	if (insn_data_sz == 0 || insn_data_sz % BPF_INSN_SZ || sec_off % BPF_INSN_SZ) {
849 		pr_warn("sec '%s': corrupted program '%s', offset %zu, size %zu\n",
850 			sec_name, name, sec_off, insn_data_sz);
851 		return -EINVAL;
852 	}
853 
854 	memset(prog, 0, sizeof(*prog));
855 	prog->obj = obj;
856 
857 	prog->sec_idx = sec_idx;
858 	prog->sec_insn_off = sec_off / BPF_INSN_SZ;
859 	prog->sec_insn_cnt = insn_data_sz / BPF_INSN_SZ;
860 	/* insns_cnt can later be increased by appending used subprograms */
861 	prog->insns_cnt = prog->sec_insn_cnt;
862 
863 	prog->type = BPF_PROG_TYPE_UNSPEC;
864 	prog->fd = -1;
865 	prog->exception_cb_idx = -1;
866 
867 	/* libbpf's convention for SEC("?abc...") is that it's just like
868 	 * SEC("abc...") but the corresponding bpf_program starts out with
869 	 * autoload set to false.
870 	 */
871 	if (sec_name[0] == '?') {
872 		prog->autoload = false;
873 		/* from now on forget there was ? in section name */
874 		sec_name++;
875 	} else {
876 		prog->autoload = true;
877 	}
878 
879 	prog->autoattach = true;
880 
881 	/* inherit object's log_level */
882 	prog->log_level = obj->log_level;
883 
884 	prog->sec_name = strdup(sec_name);
885 	if (!prog->sec_name)
886 		goto errout;
887 
888 	prog->name = strdup(name);
889 	if (!prog->name)
890 		goto errout;
891 
892 	prog->insns = malloc(insn_data_sz);
893 	if (!prog->insns)
894 		goto errout;
895 	memcpy(prog->insns, insn_data, insn_data_sz);
896 
897 	return 0;
898 errout:
899 	pr_warn("sec '%s': failed to allocate memory for prog '%s'\n", sec_name, name);
900 	bpf_program__exit(prog);
901 	return -ENOMEM;
902 }
903 
904 static int
905 bpf_object__add_programs(struct bpf_object *obj, Elf_Data *sec_data,
906 			 const char *sec_name, int sec_idx)
907 {
908 	Elf_Data *symbols = obj->efile.symbols;
909 	struct bpf_program *prog, *progs;
910 	void *data = sec_data->d_buf;
911 	size_t sec_sz = sec_data->d_size, sec_off, prog_sz, nr_syms;
912 	int nr_progs, err, i;
913 	const char *name;
914 	Elf64_Sym *sym;
915 
916 	progs = obj->programs;
917 	nr_progs = obj->nr_programs;
918 	nr_syms = symbols->d_size / sizeof(Elf64_Sym);
919 
920 	for (i = 0; i < nr_syms; i++) {
921 		sym = elf_sym_by_idx(obj, i);
922 
923 		if (sym->st_shndx != sec_idx)
924 			continue;
925 		if (ELF64_ST_TYPE(sym->st_info) != STT_FUNC)
926 			continue;
927 
928 		prog_sz = sym->st_size;
929 		sec_off = sym->st_value;
930 
931 		name = elf_sym_str(obj, sym->st_name);
932 		if (!name) {
933 			pr_warn("sec '%s': failed to get symbol name for offset %zu\n",
934 				sec_name, sec_off);
935 			return -LIBBPF_ERRNO__FORMAT;
936 		}
937 
938 		if (sec_off + prog_sz > sec_sz || sec_off + prog_sz < sec_off) {
939 			pr_warn("sec '%s': program at offset %zu crosses section boundary\n",
940 				sec_name, sec_off);
941 			return -LIBBPF_ERRNO__FORMAT;
942 		}
943 
944 		if (sec_idx != obj->efile.text_shndx && ELF64_ST_BIND(sym->st_info) == STB_LOCAL) {
945 			pr_warn("sec '%s': program '%s' is static and not supported\n", sec_name, name);
946 			return -ENOTSUP;
947 		}
948 
949 		pr_debug("sec '%s': found program '%s' at insn offset %zu (%zu bytes), code size %zu insns (%zu bytes)\n",
950 			 sec_name, name, sec_off / BPF_INSN_SZ, sec_off, prog_sz / BPF_INSN_SZ, prog_sz);
951 
952 		progs = libbpf_reallocarray(progs, nr_progs + 1, sizeof(*progs));
953 		if (!progs) {
954 			/*
955 			 * In this case the original obj->programs
956 			 * is still valid, so don't need special treat for
957 			 * bpf_close_object().
958 			 */
959 			pr_warn("sec '%s': failed to alloc memory for new program '%s'\n",
960 				sec_name, name);
961 			return -ENOMEM;
962 		}
963 		obj->programs = progs;
964 
965 		prog = &progs[nr_progs];
966 
967 		err = bpf_object__init_prog(obj, prog, name, sec_idx, sec_name,
968 					    sec_off, data + sec_off, prog_sz);
969 		if (err)
970 			return err;
971 
972 		if (ELF64_ST_BIND(sym->st_info) != STB_LOCAL)
973 			prog->sym_global = true;
974 
975 		/* if function is a global/weak symbol, but has restricted
976 		 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF FUNC
977 		 * as static to enable more permissive BPF verification mode
978 		 * with more outside context available to BPF verifier
979 		 */
980 		if (prog->sym_global && (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
981 		    || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL))
982 			prog->mark_btf_static = true;
983 
984 		nr_progs++;
985 		obj->nr_programs = nr_progs;
986 	}
987 
988 	return 0;
989 }
990 
991 static void bpf_object_bswap_progs(struct bpf_object *obj)
992 {
993 	struct bpf_program *prog = obj->programs;
994 	struct bpf_insn *insn;
995 	int p, i;
996 
997 	for (p = 0; p < obj->nr_programs; p++, prog++) {
998 		insn = prog->insns;
999 		for (i = 0; i < prog->insns_cnt; i++, insn++)
1000 			bpf_insn_bswap(insn);
1001 	}
1002 	pr_debug("converted %zu BPF programs to native byte order\n", obj->nr_programs);
1003 }
1004 
1005 static const struct btf_member *
1006 find_member_by_offset(const struct btf_type *t, __u32 bit_offset)
1007 {
1008 	struct btf_member *m;
1009 	int i;
1010 
1011 	for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
1012 		if (btf_member_bit_offset(t, i) == bit_offset)
1013 			return m;
1014 	}
1015 
1016 	return NULL;
1017 }
1018 
1019 static const struct btf_member *
1020 find_member_by_name(const struct btf *btf, const struct btf_type *t,
1021 		    const char *name)
1022 {
1023 	struct btf_member *m;
1024 	int i;
1025 
1026 	for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
1027 		if (!strcmp(btf__name_by_offset(btf, m->name_off), name))
1028 			return m;
1029 	}
1030 
1031 	return NULL;
1032 }
1033 
1034 static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
1035 			    __u16 kind, struct btf **res_btf,
1036 			    struct module_btf **res_mod_btf);
1037 
1038 #define STRUCT_OPS_VALUE_PREFIX "bpf_struct_ops_"
1039 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
1040 				   const char *name, __u32 kind);
1041 
1042 static int
1043 find_struct_ops_kern_types(struct bpf_object *obj, const char *tname_raw,
1044 			   struct module_btf **mod_btf,
1045 			   const struct btf_type **type, __u32 *type_id,
1046 			   const struct btf_type **vtype, __u32 *vtype_id,
1047 			   const struct btf_member **data_member)
1048 {
1049 	const struct btf_type *kern_type, *kern_vtype;
1050 	const struct btf_member *kern_data_member;
1051 	struct btf *btf = NULL;
1052 	__s32 kern_vtype_id, kern_type_id;
1053 	char tname[192], stname[256];
1054 	__u32 i;
1055 
1056 	snprintf(tname, sizeof(tname), "%.*s",
1057 		 (int)bpf_core_essential_name_len(tname_raw), tname_raw);
1058 
1059 	snprintf(stname, sizeof(stname), "%s%s", STRUCT_OPS_VALUE_PREFIX, tname);
1060 
1061 	/* Look for the corresponding "map_value" type that will be used
1062 	 * in map_update(BPF_MAP_TYPE_STRUCT_OPS) first, figure out the btf
1063 	 * and the mod_btf.
1064 	 * For example, find "struct bpf_struct_ops_tcp_congestion_ops".
1065 	 */
1066 	kern_vtype_id = find_ksym_btf_id(obj, stname, BTF_KIND_STRUCT, &btf, mod_btf);
1067 	if (kern_vtype_id < 0) {
1068 		pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n", stname);
1069 		return kern_vtype_id;
1070 	}
1071 	kern_vtype = btf__type_by_id(btf, kern_vtype_id);
1072 
1073 	kern_type_id = btf__find_by_name_kind(btf, tname, BTF_KIND_STRUCT);
1074 	if (kern_type_id < 0) {
1075 		pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n", tname);
1076 		return kern_type_id;
1077 	}
1078 	kern_type = btf__type_by_id(btf, kern_type_id);
1079 
1080 	/* Find "struct tcp_congestion_ops" from
1081 	 * struct bpf_struct_ops_tcp_congestion_ops {
1082 	 *	[ ... ]
1083 	 *	struct tcp_congestion_ops data;
1084 	 * }
1085 	 */
1086 	kern_data_member = btf_members(kern_vtype);
1087 	for (i = 0; i < btf_vlen(kern_vtype); i++, kern_data_member++) {
1088 		if (kern_data_member->type == kern_type_id)
1089 			break;
1090 	}
1091 	if (i == btf_vlen(kern_vtype)) {
1092 		pr_warn("struct_ops init_kern: struct %s data is not found in struct %s\n",
1093 			tname, stname);
1094 		return -EINVAL;
1095 	}
1096 
1097 	*type = kern_type;
1098 	*type_id = kern_type_id;
1099 	*vtype = kern_vtype;
1100 	*vtype_id = kern_vtype_id;
1101 	*data_member = kern_data_member;
1102 
1103 	return 0;
1104 }
1105 
1106 static bool bpf_map__is_struct_ops(const struct bpf_map *map)
1107 {
1108 	return map->def.type == BPF_MAP_TYPE_STRUCT_OPS;
1109 }
1110 
1111 static bool is_valid_st_ops_program(struct bpf_object *obj,
1112 				    const struct bpf_program *prog)
1113 {
1114 	int i;
1115 
1116 	for (i = 0; i < obj->nr_programs; i++) {
1117 		if (&obj->programs[i] == prog)
1118 			return prog->type == BPF_PROG_TYPE_STRUCT_OPS;
1119 	}
1120 
1121 	return false;
1122 }
1123 
1124 /* For each struct_ops program P, referenced from some struct_ops map M,
1125  * enable P.autoload if there are Ms for which M.autocreate is true,
1126  * disable P.autoload if for all Ms M.autocreate is false.
1127  * Don't change P.autoload for programs that are not referenced from any maps.
1128  */
1129 static int bpf_object_adjust_struct_ops_autoload(struct bpf_object *obj)
1130 {
1131 	struct bpf_program *prog, *slot_prog;
1132 	struct bpf_map *map;
1133 	int i, j, k, vlen;
1134 
1135 	for (i = 0; i < obj->nr_programs; ++i) {
1136 		int should_load = false;
1137 		int use_cnt = 0;
1138 
1139 		prog = &obj->programs[i];
1140 		if (prog->type != BPF_PROG_TYPE_STRUCT_OPS)
1141 			continue;
1142 
1143 		for (j = 0; j < obj->nr_maps; ++j) {
1144 			const struct btf_type *type;
1145 
1146 			map = &obj->maps[j];
1147 			if (!bpf_map__is_struct_ops(map))
1148 				continue;
1149 
1150 			type = btf__type_by_id(obj->btf, map->st_ops->type_id);
1151 			vlen = btf_vlen(type);
1152 			for (k = 0; k < vlen; ++k) {
1153 				slot_prog = map->st_ops->progs[k];
1154 				if (prog != slot_prog)
1155 					continue;
1156 
1157 				use_cnt++;
1158 				if (map->autocreate)
1159 					should_load = true;
1160 			}
1161 		}
1162 		if (use_cnt)
1163 			prog->autoload = should_load;
1164 	}
1165 
1166 	return 0;
1167 }
1168 
1169 /* Init the map's fields that depend on kern_btf */
1170 static int bpf_map__init_kern_struct_ops(struct bpf_map *map)
1171 {
1172 	const struct btf_member *member, *kern_member, *kern_data_member;
1173 	const struct btf_type *type, *kern_type, *kern_vtype;
1174 	__u32 i, kern_type_id, kern_vtype_id, kern_data_off;
1175 	struct bpf_object *obj = map->obj;
1176 	const struct btf *btf = obj->btf;
1177 	struct bpf_struct_ops *st_ops;
1178 	const struct btf *kern_btf;
1179 	struct module_btf *mod_btf = NULL;
1180 	void *data, *kern_data;
1181 	const char *tname;
1182 	int err;
1183 
1184 	st_ops = map->st_ops;
1185 	type = btf__type_by_id(btf, st_ops->type_id);
1186 	tname = btf__name_by_offset(btf, type->name_off);
1187 	err = find_struct_ops_kern_types(obj, tname, &mod_btf,
1188 					 &kern_type, &kern_type_id,
1189 					 &kern_vtype, &kern_vtype_id,
1190 					 &kern_data_member);
1191 	if (err)
1192 		return err;
1193 
1194 	kern_btf = mod_btf ? mod_btf->btf : obj->btf_vmlinux;
1195 
1196 	pr_debug("struct_ops init_kern %s: type_id:%u kern_type_id:%u kern_vtype_id:%u\n",
1197 		 map->name, st_ops->type_id, kern_type_id, kern_vtype_id);
1198 
1199 	map->mod_btf_fd = mod_btf ? mod_btf->fd : -1;
1200 	map->def.value_size = kern_vtype->size;
1201 	map->btf_vmlinux_value_type_id = kern_vtype_id;
1202 
1203 	st_ops->kern_vdata = calloc(1, kern_vtype->size);
1204 	if (!st_ops->kern_vdata)
1205 		return -ENOMEM;
1206 
1207 	data = st_ops->data;
1208 	kern_data_off = kern_data_member->offset / 8;
1209 	kern_data = st_ops->kern_vdata + kern_data_off;
1210 
1211 	member = btf_members(type);
1212 	for (i = 0; i < btf_vlen(type); i++, member++) {
1213 		const struct btf_type *mtype, *kern_mtype;
1214 		__u32 mtype_id, kern_mtype_id;
1215 		void *mdata, *kern_mdata;
1216 		struct bpf_program *prog;
1217 		__s64 msize, kern_msize;
1218 		__u32 moff, kern_moff;
1219 		__u32 kern_member_idx;
1220 		const char *mname;
1221 
1222 		mname = btf__name_by_offset(btf, member->name_off);
1223 		moff = member->offset / 8;
1224 		mdata = data + moff;
1225 		msize = btf__resolve_size(btf, member->type);
1226 		if (msize < 0) {
1227 			pr_warn("struct_ops init_kern %s: failed to resolve the size of member %s\n",
1228 				map->name, mname);
1229 			return msize;
1230 		}
1231 
1232 		kern_member = find_member_by_name(kern_btf, kern_type, mname);
1233 		if (!kern_member) {
1234 			if (!libbpf_is_mem_zeroed(mdata, msize)) {
1235 				pr_warn("struct_ops init_kern %s: Cannot find member %s in kernel BTF\n",
1236 					map->name, mname);
1237 				return -ENOTSUP;
1238 			}
1239 
1240 			if (st_ops->progs[i]) {
1241 				/* If we had declaratively set struct_ops callback, we need to
1242 				 * force its autoload to false, because it doesn't have
1243 				 * a chance of succeeding from POV of the current struct_ops map.
1244 				 * If this program is still referenced somewhere else, though,
1245 				 * then bpf_object_adjust_struct_ops_autoload() will update its
1246 				 * autoload accordingly.
1247 				 */
1248 				st_ops->progs[i]->autoload = false;
1249 				st_ops->progs[i] = NULL;
1250 			}
1251 
1252 			/* Skip all-zero/NULL fields if they are not present in the kernel BTF */
1253 			pr_info("struct_ops %s: member %s not found in kernel, skipping it as it's set to zero\n",
1254 				map->name, mname);
1255 			continue;
1256 		}
1257 
1258 		kern_member_idx = kern_member - btf_members(kern_type);
1259 		if (btf_member_bitfield_size(type, i) ||
1260 		    btf_member_bitfield_size(kern_type, kern_member_idx)) {
1261 			pr_warn("struct_ops init_kern %s: bitfield %s is not supported\n",
1262 				map->name, mname);
1263 			return -ENOTSUP;
1264 		}
1265 
1266 		kern_moff = kern_member->offset / 8;
1267 		kern_mdata = kern_data + kern_moff;
1268 
1269 		mtype = skip_mods_and_typedefs(btf, member->type, &mtype_id);
1270 		kern_mtype = skip_mods_and_typedefs(kern_btf, kern_member->type,
1271 						    &kern_mtype_id);
1272 		if (BTF_INFO_KIND(mtype->info) !=
1273 		    BTF_INFO_KIND(kern_mtype->info)) {
1274 			pr_warn("struct_ops init_kern %s: Unmatched member type %s %u != %u(kernel)\n",
1275 				map->name, mname, BTF_INFO_KIND(mtype->info),
1276 				BTF_INFO_KIND(kern_mtype->info));
1277 			return -ENOTSUP;
1278 		}
1279 
1280 		if (btf_is_ptr(mtype)) {
1281 			prog = *(void **)mdata;
1282 			/* just like for !kern_member case above, reset declaratively
1283 			 * set (at compile time) program's autload to false,
1284 			 * if user replaced it with another program or NULL
1285 			 */
1286 			if (st_ops->progs[i] && st_ops->progs[i] != prog)
1287 				st_ops->progs[i]->autoload = false;
1288 
1289 			/* Update the value from the shadow type */
1290 			st_ops->progs[i] = prog;
1291 			if (!prog)
1292 				continue;
1293 
1294 			if (!is_valid_st_ops_program(obj, prog)) {
1295 				pr_warn("struct_ops init_kern %s: member %s is not a struct_ops program\n",
1296 					map->name, mname);
1297 				return -ENOTSUP;
1298 			}
1299 
1300 			kern_mtype = skip_mods_and_typedefs(kern_btf,
1301 							    kern_mtype->type,
1302 							    &kern_mtype_id);
1303 
1304 			/* mtype->type must be a func_proto which was
1305 			 * guaranteed in bpf_object__collect_st_ops_relos(),
1306 			 * so only check kern_mtype for func_proto here.
1307 			 */
1308 			if (!btf_is_func_proto(kern_mtype)) {
1309 				pr_warn("struct_ops init_kern %s: kernel member %s is not a func ptr\n",
1310 					map->name, mname);
1311 				return -ENOTSUP;
1312 			}
1313 
1314 			if (mod_btf)
1315 				prog->attach_btf_obj_fd = mod_btf->fd;
1316 
1317 			/* if we haven't yet processed this BPF program, record proper
1318 			 * attach_btf_id and member_idx
1319 			 */
1320 			if (!prog->attach_btf_id) {
1321 				prog->attach_btf_id = kern_type_id;
1322 				prog->expected_attach_type = kern_member_idx;
1323 			}
1324 
1325 			/* struct_ops BPF prog can be re-used between multiple
1326 			 * .struct_ops & .struct_ops.link as long as it's the
1327 			 * same struct_ops struct definition and the same
1328 			 * function pointer field
1329 			 */
1330 			if (prog->attach_btf_id != kern_type_id) {
1331 				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",
1332 					map->name, mname, prog->name, prog->sec_name, prog->type,
1333 					prog->attach_btf_id, kern_type_id);
1334 				return -EINVAL;
1335 			}
1336 			if (prog->expected_attach_type != kern_member_idx) {
1337 				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",
1338 					map->name, mname, prog->name, prog->sec_name, prog->type,
1339 					prog->expected_attach_type, kern_member_idx);
1340 				return -EINVAL;
1341 			}
1342 
1343 			st_ops->kern_func_off[i] = kern_data_off + kern_moff;
1344 
1345 			pr_debug("struct_ops init_kern %s: func ptr %s is set to prog %s from data(+%u) to kern_data(+%u)\n",
1346 				 map->name, mname, prog->name, moff,
1347 				 kern_moff);
1348 
1349 			continue;
1350 		}
1351 
1352 		kern_msize = btf__resolve_size(kern_btf, kern_mtype_id);
1353 		if (kern_msize < 0 || msize != kern_msize) {
1354 			pr_warn("struct_ops init_kern %s: Error in size of member %s: %zd != %zd(kernel)\n",
1355 				map->name, mname, (ssize_t)msize,
1356 				(ssize_t)kern_msize);
1357 			return -ENOTSUP;
1358 		}
1359 
1360 		pr_debug("struct_ops init_kern %s: copy %s %u bytes from data(+%u) to kern_data(+%u)\n",
1361 			 map->name, mname, (unsigned int)msize,
1362 			 moff, kern_moff);
1363 		memcpy(kern_mdata, mdata, msize);
1364 	}
1365 
1366 	return 0;
1367 }
1368 
1369 static int bpf_object__init_kern_struct_ops_maps(struct bpf_object *obj)
1370 {
1371 	struct bpf_map *map;
1372 	size_t i;
1373 	int err;
1374 
1375 	for (i = 0; i < obj->nr_maps; i++) {
1376 		map = &obj->maps[i];
1377 
1378 		if (!bpf_map__is_struct_ops(map))
1379 			continue;
1380 
1381 		if (!map->autocreate)
1382 			continue;
1383 
1384 		err = bpf_map__init_kern_struct_ops(map);
1385 		if (err)
1386 			return err;
1387 	}
1388 
1389 	return 0;
1390 }
1391 
1392 static int init_struct_ops_maps(struct bpf_object *obj, const char *sec_name,
1393 				int shndx, Elf_Data *data)
1394 {
1395 	const struct btf_type *type, *datasec;
1396 	const struct btf_var_secinfo *vsi;
1397 	struct bpf_struct_ops *st_ops;
1398 	const char *tname, *var_name;
1399 	__s32 type_id, datasec_id;
1400 	const struct btf *btf;
1401 	struct bpf_map *map;
1402 	__u32 i;
1403 
1404 	if (shndx == -1)
1405 		return 0;
1406 
1407 	btf = obj->btf;
1408 	datasec_id = btf__find_by_name_kind(btf, sec_name,
1409 					    BTF_KIND_DATASEC);
1410 	if (datasec_id < 0) {
1411 		pr_warn("struct_ops init: DATASEC %s not found\n",
1412 			sec_name);
1413 		return -EINVAL;
1414 	}
1415 
1416 	datasec = btf__type_by_id(btf, datasec_id);
1417 	vsi = btf_var_secinfos(datasec);
1418 	for (i = 0; i < btf_vlen(datasec); i++, vsi++) {
1419 		type = btf__type_by_id(obj->btf, vsi->type);
1420 		var_name = btf__name_by_offset(obj->btf, type->name_off);
1421 
1422 		type_id = btf__resolve_type(obj->btf, vsi->type);
1423 		if (type_id < 0) {
1424 			pr_warn("struct_ops init: Cannot resolve var type_id %u in DATASEC %s\n",
1425 				vsi->type, sec_name);
1426 			return -EINVAL;
1427 		}
1428 
1429 		type = btf__type_by_id(obj->btf, type_id);
1430 		tname = btf__name_by_offset(obj->btf, type->name_off);
1431 		if (!tname[0]) {
1432 			pr_warn("struct_ops init: anonymous type is not supported\n");
1433 			return -ENOTSUP;
1434 		}
1435 		if (!btf_is_struct(type)) {
1436 			pr_warn("struct_ops init: %s is not a struct\n", tname);
1437 			return -EINVAL;
1438 		}
1439 
1440 		map = bpf_object__add_map(obj);
1441 		if (IS_ERR(map))
1442 			return PTR_ERR(map);
1443 
1444 		map->sec_idx = shndx;
1445 		map->sec_offset = vsi->offset;
1446 		map->name = strdup(var_name);
1447 		if (!map->name)
1448 			return -ENOMEM;
1449 		map->btf_value_type_id = type_id;
1450 
1451 		/* Follow same convention as for programs autoload:
1452 		 * SEC("?.struct_ops") means map is not created by default.
1453 		 */
1454 		if (sec_name[0] == '?') {
1455 			map->autocreate = false;
1456 			/* from now on forget there was ? in section name */
1457 			sec_name++;
1458 		}
1459 
1460 		map->def.type = BPF_MAP_TYPE_STRUCT_OPS;
1461 		map->def.key_size = sizeof(int);
1462 		map->def.value_size = type->size;
1463 		map->def.max_entries = 1;
1464 		map->def.map_flags = strcmp(sec_name, STRUCT_OPS_LINK_SEC) == 0 ? BPF_F_LINK : 0;
1465 		map->autoattach = true;
1466 
1467 		map->st_ops = calloc(1, sizeof(*map->st_ops));
1468 		if (!map->st_ops)
1469 			return -ENOMEM;
1470 		st_ops = map->st_ops;
1471 		st_ops->data = malloc(type->size);
1472 		st_ops->progs = calloc(btf_vlen(type), sizeof(*st_ops->progs));
1473 		st_ops->kern_func_off = malloc(btf_vlen(type) *
1474 					       sizeof(*st_ops->kern_func_off));
1475 		if (!st_ops->data || !st_ops->progs || !st_ops->kern_func_off)
1476 			return -ENOMEM;
1477 
1478 		if (vsi->offset + type->size > data->d_size) {
1479 			pr_warn("struct_ops init: var %s is beyond the end of DATASEC %s\n",
1480 				var_name, sec_name);
1481 			return -EINVAL;
1482 		}
1483 
1484 		memcpy(st_ops->data,
1485 		       data->d_buf + vsi->offset,
1486 		       type->size);
1487 		st_ops->type_id = type_id;
1488 
1489 		pr_debug("struct_ops init: struct %s(type_id=%u) %s found at offset %u\n",
1490 			 tname, type_id, var_name, vsi->offset);
1491 	}
1492 
1493 	return 0;
1494 }
1495 
1496 static int bpf_object_init_struct_ops(struct bpf_object *obj)
1497 {
1498 	const char *sec_name;
1499 	int sec_idx, err;
1500 
1501 	for (sec_idx = 0; sec_idx < obj->efile.sec_cnt; ++sec_idx) {
1502 		struct elf_sec_desc *desc = &obj->efile.secs[sec_idx];
1503 
1504 		if (desc->sec_type != SEC_ST_OPS)
1505 			continue;
1506 
1507 		sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1508 		if (!sec_name)
1509 			return -LIBBPF_ERRNO__FORMAT;
1510 
1511 		err = init_struct_ops_maps(obj, sec_name, sec_idx, desc->data);
1512 		if (err)
1513 			return err;
1514 	}
1515 
1516 	return 0;
1517 }
1518 
1519 static struct bpf_object *bpf_object__new(const char *path,
1520 					  const void *obj_buf,
1521 					  size_t obj_buf_sz,
1522 					  const char *obj_name)
1523 {
1524 	struct bpf_object *obj;
1525 	char *end;
1526 
1527 	obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
1528 	if (!obj) {
1529 		pr_warn("alloc memory failed for %s\n", path);
1530 		return ERR_PTR(-ENOMEM);
1531 	}
1532 
1533 	strcpy(obj->path, path);
1534 	if (obj_name) {
1535 		libbpf_strlcpy(obj->name, obj_name, sizeof(obj->name));
1536 	} else {
1537 		/* Using basename() GNU version which doesn't modify arg. */
1538 		libbpf_strlcpy(obj->name, basename((void *)path), sizeof(obj->name));
1539 		end = strchr(obj->name, '.');
1540 		if (end)
1541 			*end = 0;
1542 	}
1543 
1544 	obj->efile.fd = -1;
1545 	/*
1546 	 * Caller of this function should also call
1547 	 * bpf_object__elf_finish() after data collection to return
1548 	 * obj_buf to user. If not, we should duplicate the buffer to
1549 	 * avoid user freeing them before elf finish.
1550 	 */
1551 	obj->efile.obj_buf = obj_buf;
1552 	obj->efile.obj_buf_sz = obj_buf_sz;
1553 	obj->efile.btf_maps_shndx = -1;
1554 	obj->kconfig_map_idx = -1;
1555 	obj->arena_map_idx = -1;
1556 
1557 	obj->kern_version = get_kernel_version();
1558 	obj->state  = OBJ_OPEN;
1559 
1560 	return obj;
1561 }
1562 
1563 static void bpf_object__elf_finish(struct bpf_object *obj)
1564 {
1565 	if (!obj->efile.elf)
1566 		return;
1567 
1568 	elf_end(obj->efile.elf);
1569 	obj->efile.elf = NULL;
1570 	obj->efile.ehdr = NULL;
1571 	obj->efile.symbols = NULL;
1572 	obj->efile.arena_data = NULL;
1573 
1574 	zfree(&obj->efile.secs);
1575 	obj->efile.sec_cnt = 0;
1576 	zclose(obj->efile.fd);
1577 	obj->efile.obj_buf = NULL;
1578 	obj->efile.obj_buf_sz = 0;
1579 }
1580 
1581 static int bpf_object__elf_init(struct bpf_object *obj)
1582 {
1583 	Elf64_Ehdr *ehdr;
1584 	int err = 0;
1585 	Elf *elf;
1586 
1587 	if (obj->efile.elf) {
1588 		pr_warn("elf: init internal error\n");
1589 		return -LIBBPF_ERRNO__LIBELF;
1590 	}
1591 
1592 	if (obj->efile.obj_buf_sz > 0) {
1593 		/* obj_buf should have been validated by bpf_object__open_mem(). */
1594 		elf = elf_memory((char *)obj->efile.obj_buf, obj->efile.obj_buf_sz);
1595 	} else {
1596 		obj->efile.fd = open(obj->path, O_RDONLY | O_CLOEXEC);
1597 		if (obj->efile.fd < 0) {
1598 			err = -errno;
1599 			pr_warn("elf: failed to open %s: %s\n", obj->path, errstr(err));
1600 			return err;
1601 		}
1602 
1603 		elf = elf_begin(obj->efile.fd, ELF_C_READ_MMAP, NULL);
1604 	}
1605 
1606 	if (!elf) {
1607 		pr_warn("elf: failed to open %s as ELF file: %s\n", obj->path, elf_errmsg(-1));
1608 		err = -LIBBPF_ERRNO__LIBELF;
1609 		goto errout;
1610 	}
1611 
1612 	obj->efile.elf = elf;
1613 
1614 	if (elf_kind(elf) != ELF_K_ELF) {
1615 		err = -LIBBPF_ERRNO__FORMAT;
1616 		pr_warn("elf: '%s' is not a proper ELF object\n", obj->path);
1617 		goto errout;
1618 	}
1619 
1620 	if (gelf_getclass(elf) != ELFCLASS64) {
1621 		err = -LIBBPF_ERRNO__FORMAT;
1622 		pr_warn("elf: '%s' is not a 64-bit ELF object\n", obj->path);
1623 		goto errout;
1624 	}
1625 
1626 	obj->efile.ehdr = ehdr = elf64_getehdr(elf);
1627 	if (!obj->efile.ehdr) {
1628 		pr_warn("elf: failed to get ELF header from %s: %s\n", obj->path, elf_errmsg(-1));
1629 		err = -LIBBPF_ERRNO__FORMAT;
1630 		goto errout;
1631 	}
1632 
1633 	/* Validate ELF object endianness... */
1634 	if (ehdr->e_ident[EI_DATA] != ELFDATA2LSB &&
1635 	    ehdr->e_ident[EI_DATA] != ELFDATA2MSB) {
1636 		err = -LIBBPF_ERRNO__ENDIAN;
1637 		pr_warn("elf: '%s' has unknown byte order\n", obj->path);
1638 		goto errout;
1639 	}
1640 	/* and save after bpf_object_open() frees ELF data */
1641 	obj->byteorder = ehdr->e_ident[EI_DATA];
1642 
1643 	if (elf_getshdrstrndx(elf, &obj->efile.shstrndx)) {
1644 		pr_warn("elf: failed to get section names section index for %s: %s\n",
1645 			obj->path, elf_errmsg(-1));
1646 		err = -LIBBPF_ERRNO__FORMAT;
1647 		goto errout;
1648 	}
1649 
1650 	/* ELF is corrupted/truncated, avoid calling elf_strptr. */
1651 	if (!elf_rawdata(elf_getscn(elf, obj->efile.shstrndx), NULL)) {
1652 		pr_warn("elf: failed to get section names strings from %s: %s\n",
1653 			obj->path, elf_errmsg(-1));
1654 		err = -LIBBPF_ERRNO__FORMAT;
1655 		goto errout;
1656 	}
1657 
1658 	/* Old LLVM set e_machine to EM_NONE */
1659 	if (ehdr->e_type != ET_REL || (ehdr->e_machine && ehdr->e_machine != EM_BPF)) {
1660 		pr_warn("elf: %s is not a valid eBPF object file\n", obj->path);
1661 		err = -LIBBPF_ERRNO__FORMAT;
1662 		goto errout;
1663 	}
1664 
1665 	return 0;
1666 errout:
1667 	bpf_object__elf_finish(obj);
1668 	return err;
1669 }
1670 
1671 static bool is_native_endianness(struct bpf_object *obj)
1672 {
1673 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1674 	return obj->byteorder == ELFDATA2LSB;
1675 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
1676 	return obj->byteorder == ELFDATA2MSB;
1677 #else
1678 # error "Unrecognized __BYTE_ORDER__"
1679 #endif
1680 }
1681 
1682 static int
1683 bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
1684 {
1685 	if (!data) {
1686 		pr_warn("invalid license section in %s\n", obj->path);
1687 		return -LIBBPF_ERRNO__FORMAT;
1688 	}
1689 	/* libbpf_strlcpy() only copies first N - 1 bytes, so size + 1 won't
1690 	 * go over allowed ELF data section buffer
1691 	 */
1692 	libbpf_strlcpy(obj->license, data, min(size + 1, sizeof(obj->license)));
1693 	pr_debug("license of %s is %s\n", obj->path, obj->license);
1694 	return 0;
1695 }
1696 
1697 static int
1698 bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
1699 {
1700 	__u32 kver;
1701 
1702 	if (!data || size != sizeof(kver)) {
1703 		pr_warn("invalid kver section in %s\n", obj->path);
1704 		return -LIBBPF_ERRNO__FORMAT;
1705 	}
1706 	memcpy(&kver, data, sizeof(kver));
1707 	obj->kern_version = kver;
1708 	pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
1709 	return 0;
1710 }
1711 
1712 static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
1713 {
1714 	if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
1715 	    type == BPF_MAP_TYPE_HASH_OF_MAPS)
1716 		return true;
1717 	return false;
1718 }
1719 
1720 static int find_elf_sec_sz(const struct bpf_object *obj, const char *name, __u32 *size)
1721 {
1722 	Elf_Data *data;
1723 	Elf_Scn *scn;
1724 
1725 	if (!name)
1726 		return -EINVAL;
1727 
1728 	scn = elf_sec_by_name(obj, name);
1729 	data = elf_sec_data(obj, scn);
1730 	if (data) {
1731 		*size = data->d_size;
1732 		return 0; /* found it */
1733 	}
1734 
1735 	return -ENOENT;
1736 }
1737 
1738 static Elf64_Sym *find_elf_var_sym(const struct bpf_object *obj, const char *name)
1739 {
1740 	Elf_Data *symbols = obj->efile.symbols;
1741 	const char *sname;
1742 	size_t si;
1743 
1744 	for (si = 0; si < symbols->d_size / sizeof(Elf64_Sym); si++) {
1745 		Elf64_Sym *sym = elf_sym_by_idx(obj, si);
1746 
1747 		if (ELF64_ST_TYPE(sym->st_info) != STT_OBJECT)
1748 			continue;
1749 
1750 		if (ELF64_ST_BIND(sym->st_info) != STB_GLOBAL &&
1751 		    ELF64_ST_BIND(sym->st_info) != STB_WEAK)
1752 			continue;
1753 
1754 		sname = elf_sym_str(obj, sym->st_name);
1755 		if (!sname) {
1756 			pr_warn("failed to get sym name string for var %s\n", name);
1757 			return ERR_PTR(-EIO);
1758 		}
1759 		if (strcmp(name, sname) == 0)
1760 			return sym;
1761 	}
1762 
1763 	return ERR_PTR(-ENOENT);
1764 }
1765 
1766 #ifndef MFD_CLOEXEC
1767 #define MFD_CLOEXEC 0x0001U
1768 #endif
1769 #ifndef MFD_NOEXEC_SEAL
1770 #define MFD_NOEXEC_SEAL 0x0008U
1771 #endif
1772 
1773 static int create_placeholder_fd(void)
1774 {
1775 	unsigned int flags = MFD_CLOEXEC | MFD_NOEXEC_SEAL;
1776 	const char *name = "libbpf-placeholder-fd";
1777 	int fd;
1778 
1779 	fd = ensure_good_fd(sys_memfd_create(name, flags));
1780 	if (fd >= 0)
1781 		return fd;
1782 	else if (errno != EINVAL)
1783 		return -errno;
1784 
1785 	/* Possibly running on kernel without MFD_NOEXEC_SEAL */
1786 	fd = ensure_good_fd(sys_memfd_create(name, flags & ~MFD_NOEXEC_SEAL));
1787 	if (fd < 0)
1788 		return -errno;
1789 	return fd;
1790 }
1791 
1792 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
1793 {
1794 	struct bpf_map *map;
1795 	int err;
1796 
1797 	err = libbpf_ensure_mem((void **)&obj->maps, &obj->maps_cap,
1798 				sizeof(*obj->maps), obj->nr_maps + 1);
1799 	if (err)
1800 		return ERR_PTR(err);
1801 
1802 	map = &obj->maps[obj->nr_maps++];
1803 	map->obj = obj;
1804 	/* Preallocate map FD without actually creating BPF map just yet.
1805 	 * These map FD "placeholders" will be reused later without changing
1806 	 * FD value when map is actually created in the kernel.
1807 	 *
1808 	 * This is useful to be able to perform BPF program relocations
1809 	 * without having to create BPF maps before that step. This allows us
1810 	 * to finalize and load BTF very late in BPF object's loading phase,
1811 	 * right before BPF maps have to be created and BPF programs have to
1812 	 * be loaded. By having these map FD placeholders we can perform all
1813 	 * the sanitizations, relocations, and any other adjustments before we
1814 	 * start creating actual BPF kernel objects (BTF, maps, progs).
1815 	 */
1816 	map->fd = create_placeholder_fd();
1817 	if (map->fd < 0)
1818 		return ERR_PTR(map->fd);
1819 	map->inner_map_fd = -1;
1820 	map->autocreate = true;
1821 
1822 	return map;
1823 }
1824 
1825 static size_t array_map_mmap_sz(unsigned int value_sz, unsigned int max_entries)
1826 {
1827 	const long page_sz = sysconf(_SC_PAGE_SIZE);
1828 	size_t map_sz;
1829 
1830 	map_sz = (size_t)roundup(value_sz, 8) * max_entries;
1831 	map_sz = roundup(map_sz, page_sz);
1832 	return map_sz;
1833 }
1834 
1835 static size_t bpf_map_mmap_sz(const struct bpf_map *map)
1836 {
1837 	const long page_sz = sysconf(_SC_PAGE_SIZE);
1838 
1839 	switch (map->def.type) {
1840 	case BPF_MAP_TYPE_ARRAY:
1841 		return array_map_mmap_sz(map->def.value_size, map->def.max_entries);
1842 	case BPF_MAP_TYPE_ARENA:
1843 		return page_sz * map->def.max_entries;
1844 	default:
1845 		return 0; /* not supported */
1846 	}
1847 }
1848 
1849 static int bpf_map_mmap_resize(struct bpf_map *map, size_t old_sz, size_t new_sz)
1850 {
1851 	void *mmaped;
1852 
1853 	if (!map->mmaped)
1854 		return -EINVAL;
1855 
1856 	if (old_sz == new_sz)
1857 		return 0;
1858 
1859 	mmaped = mmap(NULL, new_sz, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1860 	if (mmaped == MAP_FAILED)
1861 		return -errno;
1862 
1863 	memcpy(mmaped, map->mmaped, min(old_sz, new_sz));
1864 	munmap(map->mmaped, old_sz);
1865 	map->mmaped = mmaped;
1866 	return 0;
1867 }
1868 
1869 static char *internal_map_name(struct bpf_object *obj, const char *real_name)
1870 {
1871 	char map_name[BPF_OBJ_NAME_LEN], *p;
1872 	int pfx_len, sfx_len = max((size_t)7, strlen(real_name));
1873 
1874 	/* This is one of the more confusing parts of libbpf for various
1875 	 * reasons, some of which are historical. The original idea for naming
1876 	 * internal names was to include as much of BPF object name prefix as
1877 	 * possible, so that it can be distinguished from similar internal
1878 	 * maps of a different BPF object.
1879 	 * As an example, let's say we have bpf_object named 'my_object_name'
1880 	 * and internal map corresponding to '.rodata' ELF section. The final
1881 	 * map name advertised to user and to the kernel will be
1882 	 * 'my_objec.rodata', taking first 8 characters of object name and
1883 	 * entire 7 characters of '.rodata'.
1884 	 * Somewhat confusingly, if internal map ELF section name is shorter
1885 	 * than 7 characters, e.g., '.bss', we still reserve 7 characters
1886 	 * for the suffix, even though we only have 4 actual characters, and
1887 	 * resulting map will be called 'my_objec.bss', not even using all 15
1888 	 * characters allowed by the kernel. Oh well, at least the truncated
1889 	 * object name is somewhat consistent in this case. But if the map
1890 	 * name is '.kconfig', we'll still have entirety of '.kconfig' added
1891 	 * (8 chars) and thus will be left with only first 7 characters of the
1892 	 * object name ('my_obje'). Happy guessing, user, that the final map
1893 	 * name will be "my_obje.kconfig".
1894 	 * Now, with libbpf starting to support arbitrarily named .rodata.*
1895 	 * and .data.* data sections, it's possible that ELF section name is
1896 	 * longer than allowed 15 chars, so we now need to be careful to take
1897 	 * only up to 15 first characters of ELF name, taking no BPF object
1898 	 * name characters at all. So '.rodata.abracadabra' will result in
1899 	 * '.rodata.abracad' kernel and user-visible name.
1900 	 * We need to keep this convoluted logic intact for .data, .bss and
1901 	 * .rodata maps, but for new custom .data.custom and .rodata.custom
1902 	 * maps we use their ELF names as is, not prepending bpf_object name
1903 	 * in front. We still need to truncate them to 15 characters for the
1904 	 * kernel. Full name can be recovered for such maps by using DATASEC
1905 	 * BTF type associated with such map's value type, though.
1906 	 */
1907 	if (sfx_len >= BPF_OBJ_NAME_LEN)
1908 		sfx_len = BPF_OBJ_NAME_LEN - 1;
1909 
1910 	/* if there are two or more dots in map name, it's a custom dot map */
1911 	if (strchr(real_name + 1, '.') != NULL)
1912 		pfx_len = 0;
1913 	else
1914 		pfx_len = min((size_t)BPF_OBJ_NAME_LEN - sfx_len - 1, strlen(obj->name));
1915 
1916 	snprintf(map_name, sizeof(map_name), "%.*s%.*s", pfx_len, obj->name,
1917 		 sfx_len, real_name);
1918 
1919 	/* sanities map name to characters allowed by kernel */
1920 	for (p = map_name; *p && p < map_name + sizeof(map_name); p++)
1921 		if (!isalnum(*p) && *p != '_' && *p != '.')
1922 			*p = '_';
1923 
1924 	return strdup(map_name);
1925 }
1926 
1927 static int
1928 map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map);
1929 
1930 /* Internal BPF map is mmap()'able only if at least one of corresponding
1931  * DATASEC's VARs are to be exposed through BPF skeleton. I.e., it's a GLOBAL
1932  * variable and it's not marked as __hidden (which turns it into, effectively,
1933  * a STATIC variable).
1934  */
1935 static bool map_is_mmapable(struct bpf_object *obj, struct bpf_map *map)
1936 {
1937 	const struct btf_type *t, *vt;
1938 	struct btf_var_secinfo *vsi;
1939 	int i, n;
1940 
1941 	if (!map->btf_value_type_id)
1942 		return false;
1943 
1944 	t = btf__type_by_id(obj->btf, map->btf_value_type_id);
1945 	if (!btf_is_datasec(t))
1946 		return false;
1947 
1948 	vsi = btf_var_secinfos(t);
1949 	for (i = 0, n = btf_vlen(t); i < n; i++, vsi++) {
1950 		vt = btf__type_by_id(obj->btf, vsi->type);
1951 		if (!btf_is_var(vt))
1952 			continue;
1953 
1954 		if (btf_var(vt)->linkage != BTF_VAR_STATIC)
1955 			return true;
1956 	}
1957 
1958 	return false;
1959 }
1960 
1961 static int
1962 bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
1963 			      const char *real_name, int sec_idx, void *data, size_t data_sz)
1964 {
1965 	struct bpf_map_def *def;
1966 	struct bpf_map *map;
1967 	size_t mmap_sz;
1968 	int err;
1969 
1970 	map = bpf_object__add_map(obj);
1971 	if (IS_ERR(map))
1972 		return PTR_ERR(map);
1973 
1974 	map->libbpf_type = type;
1975 	map->sec_idx = sec_idx;
1976 	map->sec_offset = 0;
1977 	map->real_name = strdup(real_name);
1978 	map->name = internal_map_name(obj, real_name);
1979 	if (!map->real_name || !map->name) {
1980 		zfree(&map->real_name);
1981 		zfree(&map->name);
1982 		return -ENOMEM;
1983 	}
1984 
1985 	def = &map->def;
1986 	def->type = BPF_MAP_TYPE_ARRAY;
1987 	def->key_size = sizeof(int);
1988 	def->value_size = data_sz;
1989 	def->max_entries = 1;
1990 	def->map_flags = type == LIBBPF_MAP_RODATA || type == LIBBPF_MAP_KCONFIG
1991 		? BPF_F_RDONLY_PROG : 0;
1992 
1993 	/* failures are fine because of maps like .rodata.str1.1 */
1994 	(void) map_fill_btf_type_info(obj, map);
1995 
1996 	if (map_is_mmapable(obj, map))
1997 		def->map_flags |= BPF_F_MMAPABLE;
1998 
1999 	pr_debug("map '%s' (global data): at sec_idx %d, offset %zu, flags %x.\n",
2000 		 map->name, map->sec_idx, map->sec_offset, def->map_flags);
2001 
2002 	mmap_sz = bpf_map_mmap_sz(map);
2003 	map->mmaped = mmap(NULL, mmap_sz, PROT_READ | PROT_WRITE,
2004 			   MAP_SHARED | MAP_ANONYMOUS, -1, 0);
2005 	if (map->mmaped == MAP_FAILED) {
2006 		err = -errno;
2007 		map->mmaped = NULL;
2008 		pr_warn("failed to alloc map '%s' content buffer: %s\n", map->name, errstr(err));
2009 		zfree(&map->real_name);
2010 		zfree(&map->name);
2011 		return err;
2012 	}
2013 
2014 	if (data)
2015 		memcpy(map->mmaped, data, data_sz);
2016 
2017 	pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
2018 	return 0;
2019 }
2020 
2021 static int bpf_object__init_global_data_maps(struct bpf_object *obj)
2022 {
2023 	struct elf_sec_desc *sec_desc;
2024 	const char *sec_name;
2025 	int err = 0, sec_idx;
2026 
2027 	/*
2028 	 * Populate obj->maps with libbpf internal maps.
2029 	 */
2030 	for (sec_idx = 1; sec_idx < obj->efile.sec_cnt; sec_idx++) {
2031 		sec_desc = &obj->efile.secs[sec_idx];
2032 
2033 		/* Skip recognized sections with size 0. */
2034 		if (!sec_desc->data || sec_desc->data->d_size == 0)
2035 			continue;
2036 
2037 		switch (sec_desc->sec_type) {
2038 		case SEC_DATA:
2039 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
2040 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
2041 							    sec_name, sec_idx,
2042 							    sec_desc->data->d_buf,
2043 							    sec_desc->data->d_size);
2044 			break;
2045 		case SEC_RODATA:
2046 			obj->has_rodata = true;
2047 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
2048 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
2049 							    sec_name, sec_idx,
2050 							    sec_desc->data->d_buf,
2051 							    sec_desc->data->d_size);
2052 			break;
2053 		case SEC_BSS:
2054 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
2055 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
2056 							    sec_name, sec_idx,
2057 							    NULL,
2058 							    sec_desc->data->d_size);
2059 			break;
2060 		default:
2061 			/* skip */
2062 			break;
2063 		}
2064 		if (err)
2065 			return err;
2066 	}
2067 	return 0;
2068 }
2069 
2070 
2071 static struct extern_desc *find_extern_by_name(const struct bpf_object *obj,
2072 					       const void *name)
2073 {
2074 	int i;
2075 
2076 	for (i = 0; i < obj->nr_extern; i++) {
2077 		if (strcmp(obj->externs[i].name, name) == 0)
2078 			return &obj->externs[i];
2079 	}
2080 	return NULL;
2081 }
2082 
2083 static struct extern_desc *find_extern_by_name_with_len(const struct bpf_object *obj,
2084 							const void *name, int len)
2085 {
2086 	const char *ext_name;
2087 	int i;
2088 
2089 	for (i = 0; i < obj->nr_extern; i++) {
2090 		ext_name = obj->externs[i].name;
2091 		if (strlen(ext_name) == len && strncmp(ext_name, name, len) == 0)
2092 			return &obj->externs[i];
2093 	}
2094 	return NULL;
2095 }
2096 
2097 static int set_kcfg_value_tri(struct extern_desc *ext, void *ext_val,
2098 			      char value)
2099 {
2100 	switch (ext->kcfg.type) {
2101 	case KCFG_BOOL:
2102 		if (value == 'm') {
2103 			pr_warn("extern (kcfg) '%s': value '%c' implies tristate or char type\n",
2104 				ext->name, value);
2105 			return -EINVAL;
2106 		}
2107 		*(bool *)ext_val = value == 'y' ? true : false;
2108 		break;
2109 	case KCFG_TRISTATE:
2110 		if (value == 'y')
2111 			*(enum libbpf_tristate *)ext_val = TRI_YES;
2112 		else if (value == 'm')
2113 			*(enum libbpf_tristate *)ext_val = TRI_MODULE;
2114 		else /* value == 'n' */
2115 			*(enum libbpf_tristate *)ext_val = TRI_NO;
2116 		break;
2117 	case KCFG_CHAR:
2118 		*(char *)ext_val = value;
2119 		break;
2120 	case KCFG_UNKNOWN:
2121 	case KCFG_INT:
2122 	case KCFG_CHAR_ARR:
2123 	default:
2124 		pr_warn("extern (kcfg) '%s': value '%c' implies bool, tristate, or char type\n",
2125 			ext->name, value);
2126 		return -EINVAL;
2127 	}
2128 	ext->is_set = true;
2129 	return 0;
2130 }
2131 
2132 static int set_kcfg_value_str(struct extern_desc *ext, char *ext_val,
2133 			      const char *value)
2134 {
2135 	size_t len;
2136 
2137 	if (ext->kcfg.type != KCFG_CHAR_ARR) {
2138 		pr_warn("extern (kcfg) '%s': value '%s' implies char array type\n",
2139 			ext->name, value);
2140 		return -EINVAL;
2141 	}
2142 
2143 	len = strlen(value);
2144 	if (len < 2 || value[len - 1] != '"') {
2145 		pr_warn("extern (kcfg) '%s': invalid string config '%s'\n",
2146 			ext->name, value);
2147 		return -EINVAL;
2148 	}
2149 
2150 	/* strip quotes */
2151 	len -= 2;
2152 	if (len >= ext->kcfg.sz) {
2153 		pr_warn("extern (kcfg) '%s': long string '%s' of (%zu bytes) truncated to %d bytes\n",
2154 			ext->name, value, len, ext->kcfg.sz - 1);
2155 		len = ext->kcfg.sz - 1;
2156 	}
2157 	memcpy(ext_val, value + 1, len);
2158 	ext_val[len] = '\0';
2159 	ext->is_set = true;
2160 	return 0;
2161 }
2162 
2163 static int parse_u64(const char *value, __u64 *res)
2164 {
2165 	char *value_end;
2166 	int err;
2167 
2168 	errno = 0;
2169 	*res = strtoull(value, &value_end, 0);
2170 	if (errno) {
2171 		err = -errno;
2172 		pr_warn("failed to parse '%s': %s\n", value, errstr(err));
2173 		return err;
2174 	}
2175 	if (*value_end) {
2176 		pr_warn("failed to parse '%s' as integer completely\n", value);
2177 		return -EINVAL;
2178 	}
2179 	return 0;
2180 }
2181 
2182 static bool is_kcfg_value_in_range(const struct extern_desc *ext, __u64 v)
2183 {
2184 	int bit_sz = ext->kcfg.sz * 8;
2185 
2186 	if (ext->kcfg.sz == 8)
2187 		return true;
2188 
2189 	/* Validate that value stored in u64 fits in integer of `ext->sz`
2190 	 * bytes size without any loss of information. If the target integer
2191 	 * is signed, we rely on the following limits of integer type of
2192 	 * Y bits and subsequent transformation:
2193 	 *
2194 	 *     -2^(Y-1) <= X           <= 2^(Y-1) - 1
2195 	 *            0 <= X + 2^(Y-1) <= 2^Y - 1
2196 	 *            0 <= X + 2^(Y-1) <  2^Y
2197 	 *
2198 	 *  For unsigned target integer, check that all the (64 - Y) bits are
2199 	 *  zero.
2200 	 */
2201 	if (ext->kcfg.is_signed)
2202 		return v + (1ULL << (bit_sz - 1)) < (1ULL << bit_sz);
2203 	else
2204 		return (v >> bit_sz) == 0;
2205 }
2206 
2207 static int set_kcfg_value_num(struct extern_desc *ext, void *ext_val,
2208 			      __u64 value)
2209 {
2210 	if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR &&
2211 	    ext->kcfg.type != KCFG_BOOL) {
2212 		pr_warn("extern (kcfg) '%s': value '%llu' implies integer, char, or boolean type\n",
2213 			ext->name, (unsigned long long)value);
2214 		return -EINVAL;
2215 	}
2216 	if (ext->kcfg.type == KCFG_BOOL && value > 1) {
2217 		pr_warn("extern (kcfg) '%s': value '%llu' isn't boolean compatible\n",
2218 			ext->name, (unsigned long long)value);
2219 		return -EINVAL;
2220 
2221 	}
2222 	if (!is_kcfg_value_in_range(ext, value)) {
2223 		pr_warn("extern (kcfg) '%s': value '%llu' doesn't fit in %d bytes\n",
2224 			ext->name, (unsigned long long)value, ext->kcfg.sz);
2225 		return -ERANGE;
2226 	}
2227 	switch (ext->kcfg.sz) {
2228 	case 1:
2229 		*(__u8 *)ext_val = value;
2230 		break;
2231 	case 2:
2232 		*(__u16 *)ext_val = value;
2233 		break;
2234 	case 4:
2235 		*(__u32 *)ext_val = value;
2236 		break;
2237 	case 8:
2238 		*(__u64 *)ext_val = value;
2239 		break;
2240 	default:
2241 		return -EINVAL;
2242 	}
2243 	ext->is_set = true;
2244 	return 0;
2245 }
2246 
2247 static int bpf_object__process_kconfig_line(struct bpf_object *obj,
2248 					    char *buf, void *data)
2249 {
2250 	struct extern_desc *ext;
2251 	char *sep, *value;
2252 	int len, err = 0;
2253 	void *ext_val;
2254 	__u64 num;
2255 
2256 	if (!str_has_pfx(buf, "CONFIG_"))
2257 		return 0;
2258 
2259 	sep = strchr(buf, '=');
2260 	if (!sep) {
2261 		pr_warn("failed to parse '%s': no separator\n", buf);
2262 		return -EINVAL;
2263 	}
2264 
2265 	/* Trim ending '\n' */
2266 	len = strlen(buf);
2267 	if (buf[len - 1] == '\n')
2268 		buf[len - 1] = '\0';
2269 	/* Split on '=' and ensure that a value is present. */
2270 	*sep = '\0';
2271 	if (!sep[1]) {
2272 		*sep = '=';
2273 		pr_warn("failed to parse '%s': no value\n", buf);
2274 		return -EINVAL;
2275 	}
2276 
2277 	ext = find_extern_by_name(obj, buf);
2278 	if (!ext || ext->is_set)
2279 		return 0;
2280 
2281 	ext_val = data + ext->kcfg.data_off;
2282 	value = sep + 1;
2283 
2284 	switch (*value) {
2285 	case 'y': case 'n': case 'm':
2286 		err = set_kcfg_value_tri(ext, ext_val, *value);
2287 		break;
2288 	case '"':
2289 		err = set_kcfg_value_str(ext, ext_val, value);
2290 		break;
2291 	default:
2292 		/* assume integer */
2293 		err = parse_u64(value, &num);
2294 		if (err) {
2295 			pr_warn("extern (kcfg) '%s': value '%s' isn't a valid integer\n", ext->name, value);
2296 			return err;
2297 		}
2298 		if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR) {
2299 			pr_warn("extern (kcfg) '%s': value '%s' implies integer type\n", ext->name, value);
2300 			return -EINVAL;
2301 		}
2302 		err = set_kcfg_value_num(ext, ext_val, num);
2303 		break;
2304 	}
2305 	if (err)
2306 		return err;
2307 	pr_debug("extern (kcfg) '%s': set to %s\n", ext->name, value);
2308 	return 0;
2309 }
2310 
2311 static int bpf_object__read_kconfig_file(struct bpf_object *obj, void *data)
2312 {
2313 	char buf[PATH_MAX];
2314 	struct utsname uts;
2315 	int len, err = 0;
2316 	gzFile file;
2317 
2318 	uname(&uts);
2319 	len = snprintf(buf, PATH_MAX, "/boot/config-%s", uts.release);
2320 	if (len < 0)
2321 		return -EINVAL;
2322 	else if (len >= PATH_MAX)
2323 		return -ENAMETOOLONG;
2324 
2325 	/* gzopen also accepts uncompressed files. */
2326 	file = gzopen(buf, "re");
2327 	if (!file)
2328 		file = gzopen("/proc/config.gz", "re");
2329 
2330 	if (!file) {
2331 		pr_warn("failed to open system Kconfig\n");
2332 		return -ENOENT;
2333 	}
2334 
2335 	while (gzgets(file, buf, sizeof(buf))) {
2336 		err = bpf_object__process_kconfig_line(obj, buf, data);
2337 		if (err) {
2338 			pr_warn("error parsing system Kconfig line '%s': %s\n",
2339 				buf, errstr(err));
2340 			goto out;
2341 		}
2342 	}
2343 
2344 out:
2345 	gzclose(file);
2346 	return err;
2347 }
2348 
2349 static int bpf_object__read_kconfig_mem(struct bpf_object *obj,
2350 					const char *config, void *data)
2351 {
2352 	char buf[PATH_MAX];
2353 	int err = 0;
2354 	FILE *file;
2355 
2356 	file = fmemopen((void *)config, strlen(config), "r");
2357 	if (!file) {
2358 		err = -errno;
2359 		pr_warn("failed to open in-memory Kconfig: %s\n", errstr(err));
2360 		return err;
2361 	}
2362 
2363 	while (fgets(buf, sizeof(buf), file)) {
2364 		err = bpf_object__process_kconfig_line(obj, buf, data);
2365 		if (err) {
2366 			pr_warn("error parsing in-memory Kconfig line '%s': %s\n",
2367 				buf, errstr(err));
2368 			break;
2369 		}
2370 	}
2371 
2372 	fclose(file);
2373 	return err;
2374 }
2375 
2376 static int bpf_object__init_kconfig_map(struct bpf_object *obj)
2377 {
2378 	struct extern_desc *last_ext = NULL, *ext;
2379 	size_t map_sz;
2380 	int i, err;
2381 
2382 	for (i = 0; i < obj->nr_extern; i++) {
2383 		ext = &obj->externs[i];
2384 		if (ext->type == EXT_KCFG)
2385 			last_ext = ext;
2386 	}
2387 
2388 	if (!last_ext)
2389 		return 0;
2390 
2391 	map_sz = last_ext->kcfg.data_off + last_ext->kcfg.sz;
2392 	err = bpf_object__init_internal_map(obj, LIBBPF_MAP_KCONFIG,
2393 					    ".kconfig", obj->efile.symbols_shndx,
2394 					    NULL, map_sz);
2395 	if (err)
2396 		return err;
2397 
2398 	obj->kconfig_map_idx = obj->nr_maps - 1;
2399 
2400 	return 0;
2401 }
2402 
2403 const struct btf_type *
2404 skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id)
2405 {
2406 	const struct btf_type *t = btf__type_by_id(btf, id);
2407 
2408 	if (res_id)
2409 		*res_id = id;
2410 
2411 	while (btf_is_mod(t) || btf_is_typedef(t)) {
2412 		if (res_id)
2413 			*res_id = t->type;
2414 		t = btf__type_by_id(btf, t->type);
2415 	}
2416 
2417 	return t;
2418 }
2419 
2420 static const struct btf_type *
2421 resolve_func_ptr(const struct btf *btf, __u32 id, __u32 *res_id)
2422 {
2423 	const struct btf_type *t;
2424 
2425 	t = skip_mods_and_typedefs(btf, id, NULL);
2426 	if (!btf_is_ptr(t))
2427 		return NULL;
2428 
2429 	t = skip_mods_and_typedefs(btf, t->type, res_id);
2430 
2431 	return btf_is_func_proto(t) ? t : NULL;
2432 }
2433 
2434 static const char *__btf_kind_str(__u16 kind)
2435 {
2436 	switch (kind) {
2437 	case BTF_KIND_UNKN: return "void";
2438 	case BTF_KIND_INT: return "int";
2439 	case BTF_KIND_PTR: return "ptr";
2440 	case BTF_KIND_ARRAY: return "array";
2441 	case BTF_KIND_STRUCT: return "struct";
2442 	case BTF_KIND_UNION: return "union";
2443 	case BTF_KIND_ENUM: return "enum";
2444 	case BTF_KIND_FWD: return "fwd";
2445 	case BTF_KIND_TYPEDEF: return "typedef";
2446 	case BTF_KIND_VOLATILE: return "volatile";
2447 	case BTF_KIND_CONST: return "const";
2448 	case BTF_KIND_RESTRICT: return "restrict";
2449 	case BTF_KIND_FUNC: return "func";
2450 	case BTF_KIND_FUNC_PROTO: return "func_proto";
2451 	case BTF_KIND_VAR: return "var";
2452 	case BTF_KIND_DATASEC: return "datasec";
2453 	case BTF_KIND_FLOAT: return "float";
2454 	case BTF_KIND_DECL_TAG: return "decl_tag";
2455 	case BTF_KIND_TYPE_TAG: return "type_tag";
2456 	case BTF_KIND_ENUM64: return "enum64";
2457 	default: return "unknown";
2458 	}
2459 }
2460 
2461 const char *btf_kind_str(const struct btf_type *t)
2462 {
2463 	return __btf_kind_str(btf_kind(t));
2464 }
2465 
2466 /*
2467  * Fetch integer attribute of BTF map definition. Such attributes are
2468  * represented using a pointer to an array, in which dimensionality of array
2469  * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
2470  * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
2471  * type definition, while using only sizeof(void *) space in ELF data section.
2472  */
2473 static bool get_map_field_int(const char *map_name, const struct btf *btf,
2474 			      const struct btf_member *m, __u32 *res)
2475 {
2476 	const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
2477 	const char *name = btf__name_by_offset(btf, m->name_off);
2478 	const struct btf_array *arr_info;
2479 	const struct btf_type *arr_t;
2480 
2481 	if (!btf_is_ptr(t)) {
2482 		pr_warn("map '%s': attr '%s': expected PTR, got %s.\n",
2483 			map_name, name, btf_kind_str(t));
2484 		return false;
2485 	}
2486 
2487 	arr_t = btf__type_by_id(btf, t->type);
2488 	if (!arr_t) {
2489 		pr_warn("map '%s': attr '%s': type [%u] not found.\n",
2490 			map_name, name, t->type);
2491 		return false;
2492 	}
2493 	if (!btf_is_array(arr_t)) {
2494 		pr_warn("map '%s': attr '%s': expected ARRAY, got %s.\n",
2495 			map_name, name, btf_kind_str(arr_t));
2496 		return false;
2497 	}
2498 	arr_info = btf_array(arr_t);
2499 	*res = arr_info->nelems;
2500 	return true;
2501 }
2502 
2503 static bool get_map_field_long(const char *map_name, const struct btf *btf,
2504 			       const struct btf_member *m, __u64 *res)
2505 {
2506 	const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
2507 	const char *name = btf__name_by_offset(btf, m->name_off);
2508 
2509 	if (btf_is_ptr(t)) {
2510 		__u32 res32;
2511 		bool ret;
2512 
2513 		ret = get_map_field_int(map_name, btf, m, &res32);
2514 		if (ret)
2515 			*res = (__u64)res32;
2516 		return ret;
2517 	}
2518 
2519 	if (!btf_is_enum(t) && !btf_is_enum64(t)) {
2520 		pr_warn("map '%s': attr '%s': expected ENUM or ENUM64, got %s.\n",
2521 			map_name, name, btf_kind_str(t));
2522 		return false;
2523 	}
2524 
2525 	if (btf_vlen(t) != 1) {
2526 		pr_warn("map '%s': attr '%s': invalid __ulong\n",
2527 			map_name, name);
2528 		return false;
2529 	}
2530 
2531 	if (btf_is_enum(t)) {
2532 		const struct btf_enum *e = btf_enum(t);
2533 
2534 		*res = e->val;
2535 	} else {
2536 		const struct btf_enum64 *e = btf_enum64(t);
2537 
2538 		*res = btf_enum64_value(e);
2539 	}
2540 	return true;
2541 }
2542 
2543 static int pathname_concat(char *buf, size_t buf_sz, const char *path, const char *name)
2544 {
2545 	int len;
2546 
2547 	len = snprintf(buf, buf_sz, "%s/%s", path, name);
2548 	if (len < 0)
2549 		return -EINVAL;
2550 	if (len >= buf_sz)
2551 		return -ENAMETOOLONG;
2552 
2553 	return 0;
2554 }
2555 
2556 static int build_map_pin_path(struct bpf_map *map, const char *path)
2557 {
2558 	char buf[PATH_MAX];
2559 	int err;
2560 
2561 	if (!path)
2562 		path = BPF_FS_DEFAULT_PATH;
2563 
2564 	err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
2565 	if (err)
2566 		return err;
2567 
2568 	return bpf_map__set_pin_path(map, buf);
2569 }
2570 
2571 /* should match definition in bpf_helpers.h */
2572 enum libbpf_pin_type {
2573 	LIBBPF_PIN_NONE,
2574 	/* PIN_BY_NAME: pin maps by name (in /sys/fs/bpf by default) */
2575 	LIBBPF_PIN_BY_NAME,
2576 };
2577 
2578 int parse_btf_map_def(const char *map_name, struct btf *btf,
2579 		      const struct btf_type *def_t, bool strict,
2580 		      struct btf_map_def *map_def, struct btf_map_def *inner_def)
2581 {
2582 	const struct btf_type *t;
2583 	const struct btf_member *m;
2584 	bool is_inner = inner_def == NULL;
2585 	int vlen, i;
2586 
2587 	vlen = btf_vlen(def_t);
2588 	m = btf_members(def_t);
2589 	for (i = 0; i < vlen; i++, m++) {
2590 		const char *name = btf__name_by_offset(btf, m->name_off);
2591 
2592 		if (!name) {
2593 			pr_warn("map '%s': invalid field #%d.\n", map_name, i);
2594 			return -EINVAL;
2595 		}
2596 		if (strcmp(name, "type") == 0) {
2597 			if (!get_map_field_int(map_name, btf, m, &map_def->map_type))
2598 				return -EINVAL;
2599 			map_def->parts |= MAP_DEF_MAP_TYPE;
2600 		} else if (strcmp(name, "max_entries") == 0) {
2601 			if (!get_map_field_int(map_name, btf, m, &map_def->max_entries))
2602 				return -EINVAL;
2603 			map_def->parts |= MAP_DEF_MAX_ENTRIES;
2604 		} else if (strcmp(name, "map_flags") == 0) {
2605 			if (!get_map_field_int(map_name, btf, m, &map_def->map_flags))
2606 				return -EINVAL;
2607 			map_def->parts |= MAP_DEF_MAP_FLAGS;
2608 		} else if (strcmp(name, "numa_node") == 0) {
2609 			if (!get_map_field_int(map_name, btf, m, &map_def->numa_node))
2610 				return -EINVAL;
2611 			map_def->parts |= MAP_DEF_NUMA_NODE;
2612 		} else if (strcmp(name, "key_size") == 0) {
2613 			__u32 sz;
2614 
2615 			if (!get_map_field_int(map_name, btf, m, &sz))
2616 				return -EINVAL;
2617 			if (map_def->key_size && map_def->key_size != sz) {
2618 				pr_warn("map '%s': conflicting key size %u != %u.\n",
2619 					map_name, map_def->key_size, sz);
2620 				return -EINVAL;
2621 			}
2622 			map_def->key_size = sz;
2623 			map_def->parts |= MAP_DEF_KEY_SIZE;
2624 		} else if (strcmp(name, "key") == 0) {
2625 			__s64 sz;
2626 
2627 			t = btf__type_by_id(btf, m->type);
2628 			if (!t) {
2629 				pr_warn("map '%s': key type [%d] not found.\n",
2630 					map_name, m->type);
2631 				return -EINVAL;
2632 			}
2633 			if (!btf_is_ptr(t)) {
2634 				pr_warn("map '%s': key spec is not PTR: %s.\n",
2635 					map_name, btf_kind_str(t));
2636 				return -EINVAL;
2637 			}
2638 			sz = btf__resolve_size(btf, t->type);
2639 			if (sz < 0) {
2640 				pr_warn("map '%s': can't determine key size for type [%u]: %zd.\n",
2641 					map_name, t->type, (ssize_t)sz);
2642 				return sz;
2643 			}
2644 			if (map_def->key_size && map_def->key_size != sz) {
2645 				pr_warn("map '%s': conflicting key size %u != %zd.\n",
2646 					map_name, map_def->key_size, (ssize_t)sz);
2647 				return -EINVAL;
2648 			}
2649 			map_def->key_size = sz;
2650 			map_def->key_type_id = t->type;
2651 			map_def->parts |= MAP_DEF_KEY_SIZE | MAP_DEF_KEY_TYPE;
2652 		} else if (strcmp(name, "value_size") == 0) {
2653 			__u32 sz;
2654 
2655 			if (!get_map_field_int(map_name, btf, m, &sz))
2656 				return -EINVAL;
2657 			if (map_def->value_size && map_def->value_size != sz) {
2658 				pr_warn("map '%s': conflicting value size %u != %u.\n",
2659 					map_name, map_def->value_size, sz);
2660 				return -EINVAL;
2661 			}
2662 			map_def->value_size = sz;
2663 			map_def->parts |= MAP_DEF_VALUE_SIZE;
2664 		} else if (strcmp(name, "value") == 0) {
2665 			__s64 sz;
2666 
2667 			t = btf__type_by_id(btf, m->type);
2668 			if (!t) {
2669 				pr_warn("map '%s': value type [%d] not found.\n",
2670 					map_name, m->type);
2671 				return -EINVAL;
2672 			}
2673 			if (!btf_is_ptr(t)) {
2674 				pr_warn("map '%s': value spec is not PTR: %s.\n",
2675 					map_name, btf_kind_str(t));
2676 				return -EINVAL;
2677 			}
2678 			sz = btf__resolve_size(btf, t->type);
2679 			if (sz < 0) {
2680 				pr_warn("map '%s': can't determine value size for type [%u]: %zd.\n",
2681 					map_name, t->type, (ssize_t)sz);
2682 				return sz;
2683 			}
2684 			if (map_def->value_size && map_def->value_size != sz) {
2685 				pr_warn("map '%s': conflicting value size %u != %zd.\n",
2686 					map_name, map_def->value_size, (ssize_t)sz);
2687 				return -EINVAL;
2688 			}
2689 			map_def->value_size = sz;
2690 			map_def->value_type_id = t->type;
2691 			map_def->parts |= MAP_DEF_VALUE_SIZE | MAP_DEF_VALUE_TYPE;
2692 		}
2693 		else if (strcmp(name, "values") == 0) {
2694 			bool is_map_in_map = bpf_map_type__is_map_in_map(map_def->map_type);
2695 			bool is_prog_array = map_def->map_type == BPF_MAP_TYPE_PROG_ARRAY;
2696 			const char *desc = is_map_in_map ? "map-in-map inner" : "prog-array value";
2697 			char inner_map_name[128];
2698 			int err;
2699 
2700 			if (is_inner) {
2701 				pr_warn("map '%s': multi-level inner maps not supported.\n",
2702 					map_name);
2703 				return -ENOTSUP;
2704 			}
2705 			if (i != vlen - 1) {
2706 				pr_warn("map '%s': '%s' member should be last.\n",
2707 					map_name, name);
2708 				return -EINVAL;
2709 			}
2710 			if (!is_map_in_map && !is_prog_array) {
2711 				pr_warn("map '%s': should be map-in-map or prog-array.\n",
2712 					map_name);
2713 				return -ENOTSUP;
2714 			}
2715 			if (map_def->value_size && map_def->value_size != 4) {
2716 				pr_warn("map '%s': conflicting value size %u != 4.\n",
2717 					map_name, map_def->value_size);
2718 				return -EINVAL;
2719 			}
2720 			map_def->value_size = 4;
2721 			t = btf__type_by_id(btf, m->type);
2722 			if (!t) {
2723 				pr_warn("map '%s': %s type [%d] not found.\n",
2724 					map_name, desc, m->type);
2725 				return -EINVAL;
2726 			}
2727 			if (!btf_is_array(t) || btf_array(t)->nelems) {
2728 				pr_warn("map '%s': %s spec is not a zero-sized array.\n",
2729 					map_name, desc);
2730 				return -EINVAL;
2731 			}
2732 			t = skip_mods_and_typedefs(btf, btf_array(t)->type, NULL);
2733 			if (!btf_is_ptr(t)) {
2734 				pr_warn("map '%s': %s def is of unexpected kind %s.\n",
2735 					map_name, desc, btf_kind_str(t));
2736 				return -EINVAL;
2737 			}
2738 			t = skip_mods_and_typedefs(btf, t->type, NULL);
2739 			if (is_prog_array) {
2740 				if (!btf_is_func_proto(t)) {
2741 					pr_warn("map '%s': prog-array value def is of unexpected kind %s.\n",
2742 						map_name, btf_kind_str(t));
2743 					return -EINVAL;
2744 				}
2745 				continue;
2746 			}
2747 			if (!btf_is_struct(t)) {
2748 				pr_warn("map '%s': map-in-map inner def is of unexpected kind %s.\n",
2749 					map_name, btf_kind_str(t));
2750 				return -EINVAL;
2751 			}
2752 
2753 			snprintf(inner_map_name, sizeof(inner_map_name), "%s.inner", map_name);
2754 			err = parse_btf_map_def(inner_map_name, btf, t, strict, inner_def, NULL);
2755 			if (err)
2756 				return err;
2757 
2758 			map_def->parts |= MAP_DEF_INNER_MAP;
2759 		} else if (strcmp(name, "pinning") == 0) {
2760 			__u32 val;
2761 
2762 			if (is_inner) {
2763 				pr_warn("map '%s': inner def can't be pinned.\n", map_name);
2764 				return -EINVAL;
2765 			}
2766 			if (!get_map_field_int(map_name, btf, m, &val))
2767 				return -EINVAL;
2768 			if (val != LIBBPF_PIN_NONE && val != LIBBPF_PIN_BY_NAME) {
2769 				pr_warn("map '%s': invalid pinning value %u.\n",
2770 					map_name, val);
2771 				return -EINVAL;
2772 			}
2773 			map_def->pinning = val;
2774 			map_def->parts |= MAP_DEF_PINNING;
2775 		} else if (strcmp(name, "map_extra") == 0) {
2776 			__u64 map_extra;
2777 
2778 			if (!get_map_field_long(map_name, btf, m, &map_extra))
2779 				return -EINVAL;
2780 			map_def->map_extra = map_extra;
2781 			map_def->parts |= MAP_DEF_MAP_EXTRA;
2782 		} else {
2783 			if (strict) {
2784 				pr_warn("map '%s': unknown field '%s'.\n", map_name, name);
2785 				return -ENOTSUP;
2786 			}
2787 			pr_debug("map '%s': ignoring unknown field '%s'.\n", map_name, name);
2788 		}
2789 	}
2790 
2791 	if (map_def->map_type == BPF_MAP_TYPE_UNSPEC) {
2792 		pr_warn("map '%s': map type isn't specified.\n", map_name);
2793 		return -EINVAL;
2794 	}
2795 
2796 	return 0;
2797 }
2798 
2799 static size_t adjust_ringbuf_sz(size_t sz)
2800 {
2801 	__u32 page_sz = sysconf(_SC_PAGE_SIZE);
2802 	__u32 mul;
2803 
2804 	/* if user forgot to set any size, make sure they see error */
2805 	if (sz == 0)
2806 		return 0;
2807 	/* Kernel expects BPF_MAP_TYPE_RINGBUF's max_entries to be
2808 	 * a power-of-2 multiple of kernel's page size. If user diligently
2809 	 * satisified these conditions, pass the size through.
2810 	 */
2811 	if ((sz % page_sz) == 0 && is_pow_of_2(sz / page_sz))
2812 		return sz;
2813 
2814 	/* Otherwise find closest (page_sz * power_of_2) product bigger than
2815 	 * user-set size to satisfy both user size request and kernel
2816 	 * requirements and substitute correct max_entries for map creation.
2817 	 */
2818 	for (mul = 1; mul <= UINT_MAX / page_sz; mul <<= 1) {
2819 		if (mul * page_sz > sz)
2820 			return mul * page_sz;
2821 	}
2822 
2823 	/* if it's impossible to satisfy the conditions (i.e., user size is
2824 	 * very close to UINT_MAX but is not a power-of-2 multiple of
2825 	 * page_size) then just return original size and let kernel reject it
2826 	 */
2827 	return sz;
2828 }
2829 
2830 static bool map_is_ringbuf(const struct bpf_map *map)
2831 {
2832 	return map->def.type == BPF_MAP_TYPE_RINGBUF ||
2833 	       map->def.type == BPF_MAP_TYPE_USER_RINGBUF;
2834 }
2835 
2836 static void fill_map_from_def(struct bpf_map *map, const struct btf_map_def *def)
2837 {
2838 	map->def.type = def->map_type;
2839 	map->def.key_size = def->key_size;
2840 	map->def.value_size = def->value_size;
2841 	map->def.max_entries = def->max_entries;
2842 	map->def.map_flags = def->map_flags;
2843 	map->map_extra = def->map_extra;
2844 
2845 	map->numa_node = def->numa_node;
2846 	map->btf_key_type_id = def->key_type_id;
2847 	map->btf_value_type_id = def->value_type_id;
2848 
2849 	/* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
2850 	if (map_is_ringbuf(map))
2851 		map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
2852 
2853 	if (def->parts & MAP_DEF_MAP_TYPE)
2854 		pr_debug("map '%s': found type = %u.\n", map->name, def->map_type);
2855 
2856 	if (def->parts & MAP_DEF_KEY_TYPE)
2857 		pr_debug("map '%s': found key [%u], sz = %u.\n",
2858 			 map->name, def->key_type_id, def->key_size);
2859 	else if (def->parts & MAP_DEF_KEY_SIZE)
2860 		pr_debug("map '%s': found key_size = %u.\n", map->name, def->key_size);
2861 
2862 	if (def->parts & MAP_DEF_VALUE_TYPE)
2863 		pr_debug("map '%s': found value [%u], sz = %u.\n",
2864 			 map->name, def->value_type_id, def->value_size);
2865 	else if (def->parts & MAP_DEF_VALUE_SIZE)
2866 		pr_debug("map '%s': found value_size = %u.\n", map->name, def->value_size);
2867 
2868 	if (def->parts & MAP_DEF_MAX_ENTRIES)
2869 		pr_debug("map '%s': found max_entries = %u.\n", map->name, def->max_entries);
2870 	if (def->parts & MAP_DEF_MAP_FLAGS)
2871 		pr_debug("map '%s': found map_flags = 0x%x.\n", map->name, def->map_flags);
2872 	if (def->parts & MAP_DEF_MAP_EXTRA)
2873 		pr_debug("map '%s': found map_extra = 0x%llx.\n", map->name,
2874 			 (unsigned long long)def->map_extra);
2875 	if (def->parts & MAP_DEF_PINNING)
2876 		pr_debug("map '%s': found pinning = %u.\n", map->name, def->pinning);
2877 	if (def->parts & MAP_DEF_NUMA_NODE)
2878 		pr_debug("map '%s': found numa_node = %u.\n", map->name, def->numa_node);
2879 
2880 	if (def->parts & MAP_DEF_INNER_MAP)
2881 		pr_debug("map '%s': found inner map definition.\n", map->name);
2882 }
2883 
2884 static const char *btf_var_linkage_str(__u32 linkage)
2885 {
2886 	switch (linkage) {
2887 	case BTF_VAR_STATIC: return "static";
2888 	case BTF_VAR_GLOBAL_ALLOCATED: return "global";
2889 	case BTF_VAR_GLOBAL_EXTERN: return "extern";
2890 	default: return "unknown";
2891 	}
2892 }
2893 
2894 static int bpf_object__init_user_btf_map(struct bpf_object *obj,
2895 					 const struct btf_type *sec,
2896 					 int var_idx, int sec_idx,
2897 					 const Elf_Data *data, bool strict,
2898 					 const char *pin_root_path)
2899 {
2900 	struct btf_map_def map_def = {}, inner_def = {};
2901 	const struct btf_type *var, *def;
2902 	const struct btf_var_secinfo *vi;
2903 	const struct btf_var *var_extra;
2904 	const char *map_name;
2905 	struct bpf_map *map;
2906 	int err;
2907 
2908 	vi = btf_var_secinfos(sec) + var_idx;
2909 	var = btf__type_by_id(obj->btf, vi->type);
2910 	var_extra = btf_var(var);
2911 	map_name = btf__name_by_offset(obj->btf, var->name_off);
2912 
2913 	if (str_is_empty(map_name)) {
2914 		pr_warn("map #%d: empty name.\n", var_idx);
2915 		return -EINVAL;
2916 	}
2917 	if ((__u64)vi->offset + vi->size > data->d_size) {
2918 		pr_warn("map '%s' BTF data is corrupted.\n", map_name);
2919 		return -EINVAL;
2920 	}
2921 	if (!btf_is_var(var)) {
2922 		pr_warn("map '%s': unexpected var kind %s.\n",
2923 			map_name, btf_kind_str(var));
2924 		return -EINVAL;
2925 	}
2926 	if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED) {
2927 		pr_warn("map '%s': unsupported map linkage %s.\n",
2928 			map_name, btf_var_linkage_str(var_extra->linkage));
2929 		return -EOPNOTSUPP;
2930 	}
2931 
2932 	def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
2933 	if (!btf_is_struct(def)) {
2934 		pr_warn("map '%s': unexpected def kind %s.\n",
2935 			map_name, btf_kind_str(var));
2936 		return -EINVAL;
2937 	}
2938 	if (def->size > vi->size) {
2939 		pr_warn("map '%s': invalid def size.\n", map_name);
2940 		return -EINVAL;
2941 	}
2942 
2943 	map = bpf_object__add_map(obj);
2944 	if (IS_ERR(map))
2945 		return PTR_ERR(map);
2946 	map->name = strdup(map_name);
2947 	if (!map->name) {
2948 		pr_warn("map '%s': failed to alloc map name.\n", map_name);
2949 		return -ENOMEM;
2950 	}
2951 	map->libbpf_type = LIBBPF_MAP_UNSPEC;
2952 	map->def.type = BPF_MAP_TYPE_UNSPEC;
2953 	map->sec_idx = sec_idx;
2954 	map->sec_offset = vi->offset;
2955 	map->btf_var_idx = var_idx;
2956 	pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
2957 		 map_name, map->sec_idx, map->sec_offset);
2958 
2959 	err = parse_btf_map_def(map->name, obj->btf, def, strict, &map_def, &inner_def);
2960 	if (err)
2961 		return err;
2962 
2963 	fill_map_from_def(map, &map_def);
2964 
2965 	if (map_def.pinning == LIBBPF_PIN_BY_NAME) {
2966 		err = build_map_pin_path(map, pin_root_path);
2967 		if (err) {
2968 			pr_warn("map '%s': couldn't build pin path.\n", map->name);
2969 			return err;
2970 		}
2971 	}
2972 
2973 	if (map_def.parts & MAP_DEF_INNER_MAP) {
2974 		map->inner_map = calloc(1, sizeof(*map->inner_map));
2975 		if (!map->inner_map)
2976 			return -ENOMEM;
2977 		map->inner_map->fd = create_placeholder_fd();
2978 		if (map->inner_map->fd < 0)
2979 			return map->inner_map->fd;
2980 		map->inner_map->sec_idx = sec_idx;
2981 		map->inner_map->name = malloc(strlen(map_name) + sizeof(".inner") + 1);
2982 		if (!map->inner_map->name)
2983 			return -ENOMEM;
2984 		sprintf(map->inner_map->name, "%s.inner", map_name);
2985 
2986 		fill_map_from_def(map->inner_map, &inner_def);
2987 	}
2988 
2989 	err = map_fill_btf_type_info(obj, map);
2990 	if (err)
2991 		return err;
2992 
2993 	return 0;
2994 }
2995 
2996 static int init_arena_map_data(struct bpf_object *obj, struct bpf_map *map,
2997 			       const char *sec_name, int sec_idx,
2998 			       void *data, size_t data_sz)
2999 {
3000 	const long page_sz = sysconf(_SC_PAGE_SIZE);
3001 	const size_t data_alloc_sz = roundup(data_sz, page_sz);
3002 	size_t mmap_sz;
3003 
3004 	mmap_sz = bpf_map_mmap_sz(map);
3005 	if (data_alloc_sz > mmap_sz) {
3006 		pr_warn("elf: sec '%s': declared ARENA map size (%zu) is too small to hold global __arena variables of size %zu\n",
3007 			sec_name, mmap_sz, data_sz);
3008 		return -E2BIG;
3009 	}
3010 
3011 	obj->arena_data = malloc(data_sz);
3012 	if (!obj->arena_data)
3013 		return -ENOMEM;
3014 	memcpy(obj->arena_data, data, data_sz);
3015 	obj->arena_data_sz = data_sz;
3016 
3017 	/* make bpf_map__init_value() work for ARENA maps */
3018 	map->mmaped = obj->arena_data;
3019 
3020 	return 0;
3021 }
3022 
3023 static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict,
3024 					  const char *pin_root_path)
3025 {
3026 	const struct btf_type *sec = NULL;
3027 	int nr_types, i, vlen, err;
3028 	const struct btf_type *t;
3029 	const char *name;
3030 	Elf_Data *data;
3031 	Elf_Scn *scn;
3032 
3033 	if (obj->efile.btf_maps_shndx < 0)
3034 		return 0;
3035 
3036 	scn = elf_sec_by_idx(obj, obj->efile.btf_maps_shndx);
3037 	data = elf_sec_data(obj, scn);
3038 	if (!data) {
3039 		pr_warn("elf: failed to get %s map definitions for %s\n",
3040 			MAPS_ELF_SEC, obj->path);
3041 		return -EINVAL;
3042 	}
3043 
3044 	nr_types = btf__type_cnt(obj->btf);
3045 	for (i = 1; i < nr_types; i++) {
3046 		t = btf__type_by_id(obj->btf, i);
3047 		if (!btf_is_datasec(t))
3048 			continue;
3049 		name = btf__name_by_offset(obj->btf, t->name_off);
3050 		if (strcmp(name, MAPS_ELF_SEC) == 0) {
3051 			sec = t;
3052 			obj->efile.btf_maps_sec_btf_id = i;
3053 			break;
3054 		}
3055 	}
3056 
3057 	if (!sec) {
3058 		pr_warn("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
3059 		return -ENOENT;
3060 	}
3061 
3062 	vlen = btf_vlen(sec);
3063 	for (i = 0; i < vlen; i++) {
3064 		err = bpf_object__init_user_btf_map(obj, sec, i,
3065 						    obj->efile.btf_maps_shndx,
3066 						    data, strict,
3067 						    pin_root_path);
3068 		if (err)
3069 			return err;
3070 	}
3071 
3072 	for (i = 0; i < obj->nr_maps; i++) {
3073 		struct bpf_map *map = &obj->maps[i];
3074 
3075 		if (map->def.type != BPF_MAP_TYPE_ARENA)
3076 			continue;
3077 
3078 		if (obj->arena_map_idx >= 0) {
3079 			pr_warn("map '%s': only single ARENA map is supported (map '%s' is also ARENA)\n",
3080 				map->name, obj->maps[obj->arena_map_idx].name);
3081 			return -EINVAL;
3082 		}
3083 		obj->arena_map_idx = i;
3084 
3085 		if (obj->efile.arena_data) {
3086 			err = init_arena_map_data(obj, map, ARENA_SEC, obj->efile.arena_data_shndx,
3087 						  obj->efile.arena_data->d_buf,
3088 						  obj->efile.arena_data->d_size);
3089 			if (err)
3090 				return err;
3091 		}
3092 	}
3093 	if (obj->efile.arena_data && obj->arena_map_idx < 0) {
3094 		pr_warn("elf: sec '%s': to use global __arena variables the ARENA map should be explicitly declared in SEC(\".maps\")\n",
3095 			ARENA_SEC);
3096 		return -ENOENT;
3097 	}
3098 
3099 	return 0;
3100 }
3101 
3102 static int bpf_object__init_maps(struct bpf_object *obj,
3103 				 const struct bpf_object_open_opts *opts)
3104 {
3105 	const char *pin_root_path;
3106 	bool strict;
3107 	int err = 0;
3108 
3109 	strict = !OPTS_GET(opts, relaxed_maps, false);
3110 	pin_root_path = OPTS_GET(opts, pin_root_path, NULL);
3111 
3112 	err = bpf_object__init_user_btf_maps(obj, strict, pin_root_path);
3113 	err = err ?: bpf_object__init_global_data_maps(obj);
3114 	err = err ?: bpf_object__init_kconfig_map(obj);
3115 	err = err ?: bpf_object_init_struct_ops(obj);
3116 
3117 	return err;
3118 }
3119 
3120 static bool section_have_execinstr(struct bpf_object *obj, int idx)
3121 {
3122 	Elf64_Shdr *sh;
3123 
3124 	sh = elf_sec_hdr(obj, elf_sec_by_idx(obj, idx));
3125 	if (!sh)
3126 		return false;
3127 
3128 	return sh->sh_flags & SHF_EXECINSTR;
3129 }
3130 
3131 static bool starts_with_qmark(const char *s)
3132 {
3133 	return s && s[0] == '?';
3134 }
3135 
3136 static bool btf_needs_sanitization(struct bpf_object *obj)
3137 {
3138 	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
3139 	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
3140 	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
3141 	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
3142 	bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
3143 	bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
3144 	bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
3145 	bool has_qmark_datasec = kernel_supports(obj, FEAT_BTF_QMARK_DATASEC);
3146 	bool has_layout = kernel_supports(obj, FEAT_BTF_LAYOUT);
3147 
3148 	return !has_func || !has_datasec || !has_func_global || !has_float ||
3149 	       !has_decl_tag || !has_type_tag || !has_enum64 || !has_qmark_datasec ||
3150 	       !has_layout;
3151 }
3152 
3153 struct btf *bpf_object__sanitize_btf(struct bpf_object *obj, struct btf *orig_btf)
3154 {
3155 	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
3156 	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
3157 	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
3158 	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
3159 	bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
3160 	bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
3161 	bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
3162 	bool has_qmark_datasec = kernel_supports(obj, FEAT_BTF_QMARK_DATASEC);
3163 	bool has_layout = kernel_supports(obj, FEAT_BTF_LAYOUT);
3164 	int enum64_placeholder_id = 0;
3165 	const struct btf_header *hdr;
3166 	struct btf *btf = NULL;
3167 	const void *raw_data;
3168 	struct btf_type *t;
3169 	int i, j, vlen;
3170 	__u32 sz;
3171 	int err;
3172 
3173 	/* clone BTF to sanitize a copy and leave the original intact */
3174 	raw_data = btf__raw_data(orig_btf, &sz);
3175 	if (!raw_data)
3176 		return ERR_PTR(-ENOMEM);
3177 	/* btf_header() gives us endian-safe header info */
3178 	hdr = btf_header(orig_btf);
3179 
3180 	if (!has_layout && hdr->hdr_len >= sizeof(struct btf_header) &&
3181 	    (hdr->layout_len != 0 || hdr->layout_off != 0)) {
3182 		const struct btf_header *old_hdr = raw_data;
3183 		struct btf_header *new_hdr;
3184 		void *new_raw_data;
3185 		__u32 new_str_off;
3186 
3187 		/*
3188 		 * Need to rewrite BTF to exclude layout information and
3189 		 * move string section to immediately after types.
3190 		 */
3191 		new_raw_data = malloc(sz);
3192 		if (!new_raw_data)
3193 			return ERR_PTR(-ENOMEM);
3194 
3195 		memcpy(new_raw_data, raw_data, sz);
3196 		new_hdr = new_raw_data;
3197 		new_hdr->layout_off = 0;
3198 		new_hdr->layout_len = 0;
3199 		new_str_off = hdr->type_off + hdr->type_len;
3200 		/* Handle swapped endian case */
3201 		if (old_hdr->magic != hdr->magic)
3202 			new_hdr->str_off = bswap_32(new_str_off);
3203 		else
3204 			new_hdr->str_off = new_str_off;
3205 
3206 		memmove(new_raw_data + hdr->hdr_len + new_str_off,
3207 			new_raw_data + hdr->hdr_len + hdr->str_off,
3208 			hdr->str_len);
3209 		sz = hdr->hdr_len + hdr->type_off + hdr->type_len + hdr->str_len;
3210 		btf = btf__new(new_raw_data, sz);
3211 		free(new_raw_data);
3212 	} else {
3213 		btf = btf__new(raw_data, sz);
3214 	}
3215 	err = libbpf_get_error(btf);
3216 	if (err)
3217 		return ERR_PTR(err);
3218 
3219 	/* enforce 8-byte pointers for BPF-targeted BTFs */
3220 	btf__set_pointer_size(btf, 8);
3221 
3222 	for (i = 1; i < btf__type_cnt(btf); i++) {
3223 		t = (struct btf_type *)btf__type_by_id(btf, i);
3224 
3225 		if ((!has_datasec && btf_is_var(t)) || (!has_decl_tag && btf_is_decl_tag(t))) {
3226 			/* replace VAR/DECL_TAG with INT */
3227 			t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
3228 			/*
3229 			 * using size = 1 is the safest choice, 4 will be too
3230 			 * big and cause kernel BTF validation failure if
3231 			 * original variable took less than 4 bytes
3232 			 */
3233 			t->size = 1;
3234 			*(int *)(t + 1) = BTF_INT_ENC(0, 0, 8);
3235 		} else if (!has_datasec && btf_is_datasec(t)) {
3236 			/* replace DATASEC with STRUCT */
3237 			const struct btf_var_secinfo *v = btf_var_secinfos(t);
3238 			struct btf_member *m = btf_members(t);
3239 			struct btf_type *vt;
3240 			char *name;
3241 
3242 			name = (char *)btf__name_by_offset(btf, t->name_off);
3243 			while (*name) {
3244 				if (*name == '.' || *name == '?')
3245 					*name = '_';
3246 				name++;
3247 			}
3248 
3249 			vlen = btf_vlen(t);
3250 			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
3251 			for (j = 0; j < vlen; j++, v++, m++) {
3252 				/* order of field assignments is important */
3253 				m->offset = v->offset * 8;
3254 				m->type = v->type;
3255 				/* preserve variable name as member name */
3256 				vt = (void *)btf__type_by_id(btf, v->type);
3257 				m->name_off = vt->name_off;
3258 			}
3259 		} else if (!has_qmark_datasec && btf_is_datasec(t) &&
3260 			   starts_with_qmark(btf__name_by_offset(btf, t->name_off))) {
3261 			/* replace '?' prefix with '_' for DATASEC names */
3262 			char *name;
3263 
3264 			name = (char *)btf__name_by_offset(btf, t->name_off);
3265 			if (name[0] == '?')
3266 				name[0] = '_';
3267 		} else if (!has_func && btf_is_func_proto(t)) {
3268 			/* replace FUNC_PROTO with ENUM */
3269 			vlen = btf_vlen(t);
3270 			t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
3271 			t->size = sizeof(__u32); /* kernel enforced */
3272 		} else if (!has_func && btf_is_func(t)) {
3273 			/* replace FUNC with TYPEDEF */
3274 			t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
3275 		} else if (!has_func_global && btf_is_func(t)) {
3276 			/* replace BTF_FUNC_GLOBAL with BTF_FUNC_STATIC */
3277 			t->info = BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0);
3278 		} else if (!has_float && btf_is_float(t)) {
3279 			/* replace FLOAT with an equally-sized empty STRUCT;
3280 			 * since C compilers do not accept e.g. "float" as a
3281 			 * valid struct name, make it anonymous
3282 			 */
3283 			t->name_off = 0;
3284 			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, 0);
3285 		} else if (!has_type_tag && btf_is_type_tag(t)) {
3286 			/* replace TYPE_TAG with a CONST */
3287 			t->name_off = 0;
3288 			t->info = BTF_INFO_ENC(BTF_KIND_CONST, 0, 0);
3289 		} else if (!has_enum64 && btf_is_enum(t)) {
3290 			/* clear the kflag */
3291 			t->info = btf_type_info(btf_kind(t), btf_vlen(t), false);
3292 		} else if (!has_enum64 && btf_is_enum64(t)) {
3293 			/* replace ENUM64 with a union */
3294 			struct btf_member *m;
3295 
3296 			if (enum64_placeholder_id == 0) {
3297 				enum64_placeholder_id = btf__add_int(btf, "enum64_placeholder", 1, 0);
3298 				if (enum64_placeholder_id < 0) {
3299 					btf__free(btf);
3300 					return ERR_PTR(enum64_placeholder_id);
3301 				}
3302 				t = (struct btf_type *)btf__type_by_id(btf, i);
3303 			}
3304 
3305 			m = btf_members(t);
3306 			vlen = btf_vlen(t);
3307 			t->info = BTF_INFO_ENC(BTF_KIND_UNION, 0, vlen);
3308 			for (j = 0; j < vlen; j++, m++) {
3309 				m->type = enum64_placeholder_id;
3310 				m->offset = 0;
3311 			}
3312 		}
3313 	}
3314 
3315 	return btf;
3316 }
3317 
3318 static bool libbpf_needs_btf(const struct bpf_object *obj)
3319 {
3320 	return obj->efile.btf_maps_shndx >= 0 ||
3321 	       obj->efile.has_st_ops ||
3322 	       obj->nr_extern > 0;
3323 }
3324 
3325 static bool kernel_needs_btf(const struct bpf_object *obj)
3326 {
3327 	return obj->efile.has_st_ops;
3328 }
3329 
3330 static int bpf_object__init_btf(struct bpf_object *obj,
3331 				Elf_Data *btf_data,
3332 				Elf_Data *btf_ext_data)
3333 {
3334 	int err = -ENOENT;
3335 
3336 	if (btf_data) {
3337 		obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
3338 		err = libbpf_get_error(obj->btf);
3339 		if (err) {
3340 			obj->btf = NULL;
3341 			pr_warn("Error loading ELF section %s: %s.\n", BTF_ELF_SEC, errstr(err));
3342 			goto out;
3343 		}
3344 		/* enforce 8-byte pointers for BPF-targeted BTFs */
3345 		btf__set_pointer_size(obj->btf, 8);
3346 	}
3347 	if (btf_ext_data) {
3348 		struct btf_ext_info *ext_segs[3];
3349 		int seg_num, sec_num;
3350 
3351 		if (!obj->btf) {
3352 			pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
3353 				 BTF_EXT_ELF_SEC, BTF_ELF_SEC);
3354 			goto out;
3355 		}
3356 		obj->btf_ext = btf_ext__new(btf_ext_data->d_buf, btf_ext_data->d_size);
3357 		err = libbpf_get_error(obj->btf_ext);
3358 		if (err) {
3359 			pr_warn("Error loading ELF section %s: %s. Ignored and continue.\n",
3360 				BTF_EXT_ELF_SEC, errstr(err));
3361 			obj->btf_ext = NULL;
3362 			goto out;
3363 		}
3364 
3365 		/* setup .BTF.ext to ELF section mapping */
3366 		ext_segs[0] = &obj->btf_ext->func_info;
3367 		ext_segs[1] = &obj->btf_ext->line_info;
3368 		ext_segs[2] = &obj->btf_ext->core_relo_info;
3369 		for (seg_num = 0; seg_num < ARRAY_SIZE(ext_segs); seg_num++) {
3370 			struct btf_ext_info *seg = ext_segs[seg_num];
3371 			const struct btf_ext_info_sec *sec;
3372 			const char *sec_name;
3373 			Elf_Scn *scn;
3374 
3375 			if (seg->sec_cnt == 0)
3376 				continue;
3377 
3378 			seg->sec_idxs = calloc(seg->sec_cnt, sizeof(*seg->sec_idxs));
3379 			if (!seg->sec_idxs) {
3380 				err = -ENOMEM;
3381 				goto out;
3382 			}
3383 
3384 			sec_num = 0;
3385 			for_each_btf_ext_sec(seg, sec) {
3386 				/* preventively increment index to avoid doing
3387 				 * this before every continue below
3388 				 */
3389 				sec_num++;
3390 
3391 				sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
3392 				if (str_is_empty(sec_name))
3393 					continue;
3394 				scn = elf_sec_by_name(obj, sec_name);
3395 				if (!scn)
3396 					continue;
3397 
3398 				seg->sec_idxs[sec_num - 1] = elf_ndxscn(scn);
3399 			}
3400 		}
3401 	}
3402 out:
3403 	if (err && libbpf_needs_btf(obj)) {
3404 		pr_warn("BTF is required, but is missing or corrupted.\n");
3405 		return err;
3406 	}
3407 	return 0;
3408 }
3409 
3410 static int compare_vsi_off(const void *_a, const void *_b)
3411 {
3412 	const struct btf_var_secinfo *a = _a;
3413 	const struct btf_var_secinfo *b = _b;
3414 
3415 	return a->offset - b->offset;
3416 }
3417 
3418 static int btf_fixup_datasec(struct bpf_object *obj, struct btf *btf,
3419 			     struct btf_type *t)
3420 {
3421 	__u32 size = 0, i, vars = btf_vlen(t);
3422 	const char *sec_name = btf__name_by_offset(btf, t->name_off);
3423 	struct btf_var_secinfo *vsi;
3424 	bool fixup_offsets = false;
3425 	int err;
3426 
3427 	if (!sec_name) {
3428 		pr_debug("No name found in string section for DATASEC kind.\n");
3429 		return -ENOENT;
3430 	}
3431 
3432 	/* Extern-backing datasecs (.ksyms, .kconfig) have their size and
3433 	 * variable offsets set at the previous step. Further, not every
3434 	 * extern BTF VAR has corresponding ELF symbol preserved, so we skip
3435 	 * all fixups altogether for such sections and go straight to sorting
3436 	 * VARs within their DATASEC.
3437 	 */
3438 	if (strcmp(sec_name, KCONFIG_SEC) == 0 || strcmp(sec_name, KSYMS_SEC) == 0)
3439 		goto sort_vars;
3440 
3441 	/* Clang leaves DATASEC size and VAR offsets as zeroes, so we need to
3442 	 * fix this up. But BPF static linker already fixes this up and fills
3443 	 * all the sizes and offsets during static linking. So this step has
3444 	 * to be optional. But the STV_HIDDEN handling is non-optional for any
3445 	 * non-extern DATASEC, so the variable fixup loop below handles both
3446 	 * functions at the same time, paying the cost of BTF VAR <-> ELF
3447 	 * symbol matching just once.
3448 	 */
3449 	if (t->size == 0) {
3450 		err = find_elf_sec_sz(obj, sec_name, &size);
3451 		if (err || !size) {
3452 			pr_debug("sec '%s': failed to determine size from ELF: size %u, err %s\n",
3453 				 sec_name, size, errstr(err));
3454 			return -ENOENT;
3455 		}
3456 
3457 		t->size = size;
3458 		fixup_offsets = true;
3459 	}
3460 
3461 	for (i = 0, vsi = btf_var_secinfos(t); i < vars; i++, vsi++) {
3462 		const struct btf_type *t_var;
3463 		struct btf_var *var;
3464 		const char *var_name;
3465 		Elf64_Sym *sym;
3466 
3467 		t_var = btf__type_by_id(btf, vsi->type);
3468 		if (!t_var || !btf_is_var(t_var)) {
3469 			pr_debug("sec '%s': unexpected non-VAR type found\n", sec_name);
3470 			return -EINVAL;
3471 		}
3472 
3473 		var = btf_var(t_var);
3474 		if (var->linkage == BTF_VAR_STATIC || var->linkage == BTF_VAR_GLOBAL_EXTERN)
3475 			continue;
3476 
3477 		var_name = btf__name_by_offset(btf, t_var->name_off);
3478 		if (!var_name) {
3479 			pr_debug("sec '%s': failed to find name of DATASEC's member #%d\n",
3480 				 sec_name, i);
3481 			return -ENOENT;
3482 		}
3483 
3484 		sym = find_elf_var_sym(obj, var_name);
3485 		if (IS_ERR(sym)) {
3486 			pr_debug("sec '%s': failed to find ELF symbol for VAR '%s'\n",
3487 				 sec_name, var_name);
3488 			return -ENOENT;
3489 		}
3490 
3491 		if (fixup_offsets)
3492 			vsi->offset = sym->st_value;
3493 
3494 		/* if variable is a global/weak symbol, but has restricted
3495 		 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF VAR
3496 		 * as static. This follows similar logic for functions (BPF
3497 		 * subprogs) and influences libbpf's further decisions about
3498 		 * whether to make global data BPF array maps as
3499 		 * BPF_F_MMAPABLE.
3500 		 */
3501 		if (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
3502 		    || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL)
3503 			var->linkage = BTF_VAR_STATIC;
3504 	}
3505 
3506 sort_vars:
3507 	qsort(btf_var_secinfos(t), vars, sizeof(*vsi), compare_vsi_off);
3508 	return 0;
3509 }
3510 
3511 static int bpf_object_fixup_btf(struct bpf_object *obj)
3512 {
3513 	int i, n, err = 0;
3514 
3515 	if (!obj->btf)
3516 		return 0;
3517 
3518 	n = btf__type_cnt(obj->btf);
3519 	for (i = 1; i < n; i++) {
3520 		struct btf_type *t = btf_type_by_id(obj->btf, i);
3521 
3522 		/* Loader needs to fix up some of the things compiler
3523 		 * couldn't get its hands on while emitting BTF. This
3524 		 * is section size and global variable offset. We use
3525 		 * the info from the ELF itself for this purpose.
3526 		 */
3527 		if (btf_is_datasec(t)) {
3528 			err = btf_fixup_datasec(obj, obj->btf, t);
3529 			if (err)
3530 				return err;
3531 		}
3532 	}
3533 
3534 	return 0;
3535 }
3536 
3537 static bool prog_needs_vmlinux_btf(struct bpf_program *prog)
3538 {
3539 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
3540 	    prog->type == BPF_PROG_TYPE_LSM)
3541 		return true;
3542 
3543 	/* BPF_PROG_TYPE_TRACING programs which do not attach to other programs
3544 	 * also need vmlinux BTF
3545 	 */
3546 	if (prog->type == BPF_PROG_TYPE_TRACING && !prog->attach_prog_fd)
3547 		return true;
3548 
3549 	return false;
3550 }
3551 
3552 static bool map_needs_vmlinux_btf(struct bpf_map *map)
3553 {
3554 	return bpf_map__is_struct_ops(map);
3555 }
3556 
3557 static bool obj_needs_vmlinux_btf(const struct bpf_object *obj)
3558 {
3559 	struct bpf_program *prog;
3560 	struct bpf_map *map;
3561 	int i;
3562 
3563 	/* CO-RE relocations need kernel BTF, only when btf_custom_path
3564 	 * is not specified
3565 	 */
3566 	if (obj->btf_ext && obj->btf_ext->core_relo_info.len && !obj->btf_custom_path)
3567 		return true;
3568 
3569 	/* Support for typed ksyms needs kernel BTF */
3570 	for (i = 0; i < obj->nr_extern; i++) {
3571 		const struct extern_desc *ext;
3572 
3573 		ext = &obj->externs[i];
3574 		if (ext->type == EXT_KSYM && ext->ksym.type_id)
3575 			return true;
3576 	}
3577 
3578 	bpf_object__for_each_program(prog, obj) {
3579 		if (!prog->autoload)
3580 			continue;
3581 		if (prog_needs_vmlinux_btf(prog))
3582 			return true;
3583 	}
3584 
3585 	bpf_object__for_each_map(map, obj) {
3586 		if (map_needs_vmlinux_btf(map))
3587 			return true;
3588 	}
3589 
3590 	return false;
3591 }
3592 
3593 static int bpf_object__load_vmlinux_btf(struct bpf_object *obj, bool force)
3594 {
3595 	int err;
3596 
3597 	/* btf_vmlinux could be loaded earlier */
3598 	if (obj->btf_vmlinux || obj->gen_loader)
3599 		return 0;
3600 
3601 	if (!force && !obj_needs_vmlinux_btf(obj))
3602 		return 0;
3603 
3604 	obj->btf_vmlinux = btf__load_vmlinux_btf();
3605 	err = libbpf_get_error(obj->btf_vmlinux);
3606 	if (err) {
3607 		pr_warn("Error loading vmlinux BTF: %s\n", errstr(err));
3608 		obj->btf_vmlinux = NULL;
3609 		return err;
3610 	}
3611 	return 0;
3612 }
3613 
3614 static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
3615 {
3616 	struct btf *kern_btf = obj->btf;
3617 	bool btf_mandatory, sanitize;
3618 	int i, err = 0;
3619 
3620 	if (!obj->btf)
3621 		return 0;
3622 
3623 	if (!kernel_supports(obj, FEAT_BTF)) {
3624 		if (kernel_needs_btf(obj)) {
3625 			err = -EOPNOTSUPP;
3626 			goto report;
3627 		}
3628 		pr_debug("Kernel doesn't support BTF, skipping uploading it.\n");
3629 		return 0;
3630 	}
3631 
3632 	/* Even though some subprogs are global/weak, user might prefer more
3633 	 * permissive BPF verification process that BPF verifier performs for
3634 	 * static functions, taking into account more context from the caller
3635 	 * functions. In such case, they need to mark such subprogs with
3636 	 * __attribute__((visibility("hidden"))) and libbpf will adjust
3637 	 * corresponding FUNC BTF type to be marked as static and trigger more
3638 	 * involved BPF verification process.
3639 	 */
3640 	for (i = 0; i < obj->nr_programs; i++) {
3641 		struct bpf_program *prog = &obj->programs[i];
3642 		struct btf_type *t;
3643 		const char *name;
3644 		int j, n;
3645 
3646 		if (!prog->mark_btf_static || !prog_is_subprog(obj, prog))
3647 			continue;
3648 
3649 		n = btf__type_cnt(obj->btf);
3650 		for (j = 1; j < n; j++) {
3651 			t = btf_type_by_id(obj->btf, j);
3652 			if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL)
3653 				continue;
3654 
3655 			name = btf__str_by_offset(obj->btf, t->name_off);
3656 			if (strcmp(name, prog->name) != 0)
3657 				continue;
3658 
3659 			t->info = btf_type_info(BTF_KIND_FUNC, BTF_FUNC_STATIC, 0);
3660 			break;
3661 		}
3662 	}
3663 
3664 	sanitize = btf_needs_sanitization(obj);
3665 	if (sanitize) {
3666 		kern_btf = bpf_object__sanitize_btf(obj, obj->btf);
3667 		if (IS_ERR(kern_btf))
3668 			return PTR_ERR(kern_btf);
3669 	}
3670 
3671 	if (obj->gen_loader) {
3672 		__u32 raw_size = 0;
3673 		const void *raw_data = btf__raw_data(kern_btf, &raw_size);
3674 
3675 		if (!raw_data)
3676 			return -ENOMEM;
3677 		bpf_gen__load_btf(obj->gen_loader, raw_data, raw_size);
3678 		/* Pretend to have valid FD to pass various fd >= 0 checks.
3679 		 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
3680 		 */
3681 		btf__set_fd(kern_btf, 0);
3682 	} else {
3683 		/* currently BPF_BTF_LOAD only supports log_level 1 */
3684 		err = btf_load_into_kernel(kern_btf, obj->log_buf, obj->log_size,
3685 					   obj->log_level ? 1 : 0, obj->token_fd);
3686 	}
3687 	if (sanitize) {
3688 		if (!err) {
3689 			/* move fd to libbpf's BTF */
3690 			btf__set_fd(obj->btf, btf__fd(kern_btf));
3691 			btf__set_fd(kern_btf, -1);
3692 		}
3693 		btf__free(kern_btf);
3694 	}
3695 report:
3696 	if (err) {
3697 		btf_mandatory = kernel_needs_btf(obj);
3698 		if (btf_mandatory) {
3699 			pr_warn("Error loading .BTF into kernel: %s. BTF is mandatory, can't proceed.\n",
3700 				errstr(err));
3701 		} else {
3702 			pr_info("Error loading .BTF into kernel: %s. BTF is optional, ignoring.\n",
3703 				errstr(err));
3704 			err = 0;
3705 		}
3706 	}
3707 	return err;
3708 }
3709 
3710 static const char *elf_sym_str(const struct bpf_object *obj, size_t off)
3711 {
3712 	const char *name;
3713 
3714 	name = elf_strptr(obj->efile.elf, obj->efile.strtabidx, off);
3715 	if (!name) {
3716 		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3717 			off, obj->path, elf_errmsg(-1));
3718 		return NULL;
3719 	}
3720 
3721 	return name;
3722 }
3723 
3724 static const char *elf_sec_str(const struct bpf_object *obj, size_t off)
3725 {
3726 	const char *name;
3727 
3728 	name = elf_strptr(obj->efile.elf, obj->efile.shstrndx, off);
3729 	if (!name) {
3730 		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3731 			off, obj->path, elf_errmsg(-1));
3732 		return NULL;
3733 	}
3734 
3735 	return name;
3736 }
3737 
3738 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx)
3739 {
3740 	Elf_Scn *scn;
3741 
3742 	scn = elf_getscn(obj->efile.elf, idx);
3743 	if (!scn) {
3744 		pr_warn("elf: failed to get section(%zu) from %s: %s\n",
3745 			idx, obj->path, elf_errmsg(-1));
3746 		return NULL;
3747 	}
3748 	return scn;
3749 }
3750 
3751 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name)
3752 {
3753 	Elf_Scn *scn = NULL;
3754 	Elf *elf = obj->efile.elf;
3755 	const char *sec_name;
3756 
3757 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3758 		sec_name = elf_sec_name(obj, scn);
3759 		if (!sec_name)
3760 			return NULL;
3761 
3762 		if (strcmp(sec_name, name) != 0)
3763 			continue;
3764 
3765 		return scn;
3766 	}
3767 	return NULL;
3768 }
3769 
3770 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn)
3771 {
3772 	Elf64_Shdr *shdr;
3773 
3774 	if (!scn)
3775 		return NULL;
3776 
3777 	shdr = elf64_getshdr(scn);
3778 	if (!shdr) {
3779 		pr_warn("elf: failed to get section(%zu) header from %s: %s\n",
3780 			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3781 		return NULL;
3782 	}
3783 
3784 	return shdr;
3785 }
3786 
3787 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn)
3788 {
3789 	const char *name;
3790 	Elf64_Shdr *sh;
3791 
3792 	if (!scn)
3793 		return NULL;
3794 
3795 	sh = elf_sec_hdr(obj, scn);
3796 	if (!sh)
3797 		return NULL;
3798 
3799 	name = elf_sec_str(obj, sh->sh_name);
3800 	if (!name) {
3801 		pr_warn("elf: failed to get section(%zu) name from %s: %s\n",
3802 			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3803 		return NULL;
3804 	}
3805 
3806 	return name;
3807 }
3808 
3809 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn)
3810 {
3811 	Elf_Data *data;
3812 
3813 	if (!scn)
3814 		return NULL;
3815 
3816 	data = elf_getdata(scn, 0);
3817 	if (!data) {
3818 		pr_warn("elf: failed to get section(%zu) %s data from %s: %s\n",
3819 			elf_ndxscn(scn), elf_sec_name(obj, scn) ?: "<?>",
3820 			obj->path, elf_errmsg(-1));
3821 		return NULL;
3822 	}
3823 
3824 	return data;
3825 }
3826 
3827 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx)
3828 {
3829 	if (idx >= obj->efile.symbols->d_size / sizeof(Elf64_Sym))
3830 		return NULL;
3831 
3832 	return (Elf64_Sym *)obj->efile.symbols->d_buf + idx;
3833 }
3834 
3835 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx)
3836 {
3837 	if (idx >= data->d_size / sizeof(Elf64_Rel))
3838 		return NULL;
3839 
3840 	return (Elf64_Rel *)data->d_buf + idx;
3841 }
3842 
3843 static bool is_sec_name_dwarf(const char *name)
3844 {
3845 	/* approximation, but the actual list is too long */
3846 	return str_has_pfx(name, ".debug_");
3847 }
3848 
3849 static bool ignore_elf_section(Elf64_Shdr *hdr, const char *name)
3850 {
3851 	/* no special handling of .strtab */
3852 	if (hdr->sh_type == SHT_STRTAB)
3853 		return true;
3854 
3855 	/* ignore .llvm_addrsig section as well */
3856 	if (hdr->sh_type == SHT_LLVM_ADDRSIG)
3857 		return true;
3858 
3859 	/* no subprograms will lead to an empty .text section, ignore it */
3860 	if (hdr->sh_type == SHT_PROGBITS && hdr->sh_size == 0 &&
3861 	    strcmp(name, ".text") == 0)
3862 		return true;
3863 
3864 	/* DWARF sections */
3865 	if (is_sec_name_dwarf(name))
3866 		return true;
3867 
3868 	if (str_has_pfx(name, ".rel")) {
3869 		name += sizeof(".rel") - 1;
3870 		/* DWARF section relocations */
3871 		if (is_sec_name_dwarf(name))
3872 			return true;
3873 
3874 		/* .BTF and .BTF.ext don't need relocations */
3875 		if (strcmp(name, BTF_ELF_SEC) == 0 ||
3876 		    strcmp(name, BTF_EXT_ELF_SEC) == 0)
3877 			return true;
3878 	}
3879 
3880 	return false;
3881 }
3882 
3883 static int cmp_progs(const void *_a, const void *_b)
3884 {
3885 	const struct bpf_program *a = _a;
3886 	const struct bpf_program *b = _b;
3887 
3888 	if (a->sec_idx != b->sec_idx)
3889 		return a->sec_idx < b->sec_idx ? -1 : 1;
3890 
3891 	/* sec_insn_off can't be the same within the section */
3892 	return a->sec_insn_off < b->sec_insn_off ? -1 : 1;
3893 }
3894 
3895 static int bpf_object__elf_collect(struct bpf_object *obj)
3896 {
3897 	struct elf_sec_desc *sec_desc;
3898 	Elf *elf = obj->efile.elf;
3899 	Elf_Data *btf_ext_data = NULL;
3900 	Elf_Data *btf_data = NULL;
3901 	int idx = 0, err = 0;
3902 	const char *name;
3903 	Elf_Data *data;
3904 	Elf_Scn *scn;
3905 	Elf64_Shdr *sh;
3906 
3907 	/* ELF section indices are 0-based, but sec #0 is special "invalid"
3908 	 * section. Since section count retrieved by elf_getshdrnum() does
3909 	 * include sec #0, it is already the necessary size of an array to keep
3910 	 * all the sections.
3911 	 */
3912 	if (elf_getshdrnum(obj->efile.elf, &obj->efile.sec_cnt)) {
3913 		pr_warn("elf: failed to get the number of sections for %s: %s\n",
3914 			obj->path, elf_errmsg(-1));
3915 		return -LIBBPF_ERRNO__FORMAT;
3916 	}
3917 	obj->efile.secs = calloc(obj->efile.sec_cnt, sizeof(*obj->efile.secs));
3918 	if (!obj->efile.secs)
3919 		return -ENOMEM;
3920 
3921 	/* a bunch of ELF parsing functionality depends on processing symbols,
3922 	 * so do the first pass and find the symbol table
3923 	 */
3924 	scn = NULL;
3925 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3926 		sh = elf_sec_hdr(obj, scn);
3927 		if (!sh)
3928 			return -LIBBPF_ERRNO__FORMAT;
3929 
3930 		if (sh->sh_type == SHT_SYMTAB) {
3931 			if (obj->efile.symbols) {
3932 				pr_warn("elf: multiple symbol tables in %s\n", obj->path);
3933 				return -LIBBPF_ERRNO__FORMAT;
3934 			}
3935 
3936 			data = elf_sec_data(obj, scn);
3937 			if (!data)
3938 				return -LIBBPF_ERRNO__FORMAT;
3939 
3940 			idx = elf_ndxscn(scn);
3941 
3942 			obj->efile.symbols = data;
3943 			obj->efile.symbols_shndx = idx;
3944 			obj->efile.strtabidx = sh->sh_link;
3945 		}
3946 	}
3947 
3948 	if (!obj->efile.symbols) {
3949 		pr_warn("elf: couldn't find symbol table in %s, stripped object file?\n",
3950 			obj->path);
3951 		return -ENOENT;
3952 	}
3953 
3954 	scn = NULL;
3955 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3956 		idx = elf_ndxscn(scn);
3957 		sec_desc = &obj->efile.secs[idx];
3958 
3959 		sh = elf_sec_hdr(obj, scn);
3960 		if (!sh)
3961 			return -LIBBPF_ERRNO__FORMAT;
3962 
3963 		name = elf_sec_str(obj, sh->sh_name);
3964 		if (!name)
3965 			return -LIBBPF_ERRNO__FORMAT;
3966 
3967 		if (ignore_elf_section(sh, name))
3968 			continue;
3969 
3970 		data = elf_sec_data(obj, scn);
3971 		if (!data)
3972 			return -LIBBPF_ERRNO__FORMAT;
3973 
3974 		pr_debug("elf: section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
3975 			 idx, name, (unsigned long)data->d_size,
3976 			 (int)sh->sh_link, (unsigned long)sh->sh_flags,
3977 			 (int)sh->sh_type);
3978 
3979 		if (strcmp(name, "license") == 0) {
3980 			err = bpf_object__init_license(obj, data->d_buf, data->d_size);
3981 			if (err)
3982 				return err;
3983 		} else if (strcmp(name, "version") == 0) {
3984 			err = bpf_object__init_kversion(obj, data->d_buf, data->d_size);
3985 			if (err)
3986 				return err;
3987 		} else if (strcmp(name, "maps") == 0) {
3988 			pr_warn("elf: legacy map definitions in 'maps' section are not supported by libbpf v1.0+\n");
3989 			return -ENOTSUP;
3990 		} else if (strcmp(name, MAPS_ELF_SEC) == 0) {
3991 			obj->efile.btf_maps_shndx = idx;
3992 		} else if (strcmp(name, BTF_ELF_SEC) == 0) {
3993 			if (sh->sh_type != SHT_PROGBITS)
3994 				return -LIBBPF_ERRNO__FORMAT;
3995 			btf_data = data;
3996 		} else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
3997 			if (sh->sh_type != SHT_PROGBITS)
3998 				return -LIBBPF_ERRNO__FORMAT;
3999 			btf_ext_data = data;
4000 		} else if (sh->sh_type == SHT_SYMTAB) {
4001 			/* already processed during the first pass above */
4002 		} else if (sh->sh_type == SHT_PROGBITS && data->d_size > 0) {
4003 			if (sh->sh_flags & SHF_EXECINSTR) {
4004 				if (strcmp(name, ".text") == 0)
4005 					obj->efile.text_shndx = idx;
4006 				err = bpf_object__add_programs(obj, data, name, idx);
4007 				if (err)
4008 					return err;
4009 			} else if (strcmp(name, DATA_SEC) == 0 ||
4010 				   str_has_pfx(name, DATA_SEC ".")) {
4011 				sec_desc->sec_type = SEC_DATA;
4012 				sec_desc->shdr = sh;
4013 				sec_desc->data = data;
4014 			} else if (strcmp(name, RODATA_SEC) == 0 ||
4015 				   str_has_pfx(name, RODATA_SEC ".")) {
4016 				sec_desc->sec_type = SEC_RODATA;
4017 				sec_desc->shdr = sh;
4018 				sec_desc->data = data;
4019 			} else if (strcmp(name, STRUCT_OPS_SEC) == 0 ||
4020 				   strcmp(name, STRUCT_OPS_LINK_SEC) == 0 ||
4021 				   strcmp(name, "?" STRUCT_OPS_SEC) == 0 ||
4022 				   strcmp(name, "?" STRUCT_OPS_LINK_SEC) == 0) {
4023 				sec_desc->sec_type = SEC_ST_OPS;
4024 				sec_desc->shdr = sh;
4025 				sec_desc->data = data;
4026 				obj->efile.has_st_ops = true;
4027 			} else if (strcmp(name, ARENA_SEC) == 0) {
4028 				obj->efile.arena_data = data;
4029 				obj->efile.arena_data_shndx = idx;
4030 			} else if (strcmp(name, JUMPTABLES_SEC) == 0) {
4031 				obj->jumptables_data = malloc(data->d_size);
4032 				if (!obj->jumptables_data)
4033 					return -ENOMEM;
4034 				memcpy(obj->jumptables_data, data->d_buf, data->d_size);
4035 				obj->jumptables_data_sz = data->d_size;
4036 				obj->efile.jumptables_data_shndx = idx;
4037 			} else {
4038 				pr_info("elf: skipping unrecognized data section(%d) %s\n",
4039 					idx, name);
4040 			}
4041 		} else if (sh->sh_type == SHT_REL) {
4042 			int targ_sec_idx = sh->sh_info; /* points to other section */
4043 
4044 			if (sh->sh_entsize != sizeof(Elf64_Rel) ||
4045 			    targ_sec_idx >= obj->efile.sec_cnt)
4046 				return -LIBBPF_ERRNO__FORMAT;
4047 
4048 			/* Only do relo for section with exec instructions */
4049 			if (!section_have_execinstr(obj, targ_sec_idx) &&
4050 			    strcmp(name, ".rel" STRUCT_OPS_SEC) &&
4051 			    strcmp(name, ".rel" STRUCT_OPS_LINK_SEC) &&
4052 			    strcmp(name, ".rel?" STRUCT_OPS_SEC) &&
4053 			    strcmp(name, ".rel?" STRUCT_OPS_LINK_SEC) &&
4054 			    strcmp(name, ".rel" MAPS_ELF_SEC)) {
4055 				pr_info("elf: skipping relo section(%d) %s for section(%d) %s\n",
4056 					idx, name, targ_sec_idx,
4057 					elf_sec_name(obj, elf_sec_by_idx(obj, targ_sec_idx)) ?: "<?>");
4058 				continue;
4059 			}
4060 
4061 			sec_desc->sec_type = SEC_RELO;
4062 			sec_desc->shdr = sh;
4063 			sec_desc->data = data;
4064 		} else if (sh->sh_type == SHT_NOBITS && (strcmp(name, BSS_SEC) == 0 ||
4065 							 str_has_pfx(name, BSS_SEC "."))) {
4066 			sec_desc->sec_type = SEC_BSS;
4067 			sec_desc->shdr = sh;
4068 			sec_desc->data = data;
4069 		} else {
4070 			pr_info("elf: skipping section(%d) %s (size %zu)\n", idx, name,
4071 				(size_t)sh->sh_size);
4072 		}
4073 	}
4074 
4075 	if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) {
4076 		pr_warn("elf: symbol strings section missing or invalid in %s\n", obj->path);
4077 		return -LIBBPF_ERRNO__FORMAT;
4078 	}
4079 
4080 	/* change BPF program insns to native endianness for introspection */
4081 	if (!is_native_endianness(obj))
4082 		bpf_object_bswap_progs(obj);
4083 
4084 	/* sort BPF programs by section name and in-section instruction offset
4085 	 * for faster search
4086 	 */
4087 	if (obj->nr_programs)
4088 		qsort(obj->programs, obj->nr_programs, sizeof(*obj->programs), cmp_progs);
4089 
4090 	return bpf_object__init_btf(obj, btf_data, btf_ext_data);
4091 }
4092 
4093 static bool sym_is_extern(const Elf64_Sym *sym)
4094 {
4095 	int bind = ELF64_ST_BIND(sym->st_info);
4096 	/* externs are symbols w/ type=NOTYPE, bind=GLOBAL|WEAK, section=UND */
4097 	return sym->st_shndx == SHN_UNDEF &&
4098 	       (bind == STB_GLOBAL || bind == STB_WEAK) &&
4099 	       ELF64_ST_TYPE(sym->st_info) == STT_NOTYPE;
4100 }
4101 
4102 static bool sym_is_subprog(const Elf64_Sym *sym, int text_shndx)
4103 {
4104 	int bind = ELF64_ST_BIND(sym->st_info);
4105 	int type = ELF64_ST_TYPE(sym->st_info);
4106 
4107 	/* in .text section */
4108 	if (sym->st_shndx != text_shndx)
4109 		return false;
4110 
4111 	/* local function */
4112 	if (bind == STB_LOCAL && type == STT_SECTION)
4113 		return true;
4114 
4115 	/* global function */
4116 	return (bind == STB_GLOBAL || bind == STB_WEAK) && type == STT_FUNC;
4117 }
4118 
4119 static int find_extern_btf_id(const struct btf *btf, const char *ext_name)
4120 {
4121 	const struct btf_type *t;
4122 	const char *tname;
4123 	int i, n;
4124 
4125 	if (!btf)
4126 		return -ESRCH;
4127 
4128 	n = btf__type_cnt(btf);
4129 	for (i = 1; i < n; i++) {
4130 		t = btf__type_by_id(btf, i);
4131 
4132 		if (!btf_is_var(t) && !btf_is_func(t))
4133 			continue;
4134 
4135 		tname = btf__name_by_offset(btf, t->name_off);
4136 		if (strcmp(tname, ext_name))
4137 			continue;
4138 
4139 		if (btf_is_var(t) &&
4140 		    btf_var(t)->linkage != BTF_VAR_GLOBAL_EXTERN)
4141 			return -EINVAL;
4142 
4143 		if (btf_is_func(t) && btf_func_linkage(t) != BTF_FUNC_EXTERN)
4144 			return -EINVAL;
4145 
4146 		return i;
4147 	}
4148 
4149 	return -ENOENT;
4150 }
4151 
4152 static int find_extern_sec_btf_id(struct btf *btf, int ext_btf_id) {
4153 	const struct btf_var_secinfo *vs;
4154 	const struct btf_type *t;
4155 	int i, j, n;
4156 
4157 	if (!btf)
4158 		return -ESRCH;
4159 
4160 	n = btf__type_cnt(btf);
4161 	for (i = 1; i < n; i++) {
4162 		t = btf__type_by_id(btf, i);
4163 
4164 		if (!btf_is_datasec(t))
4165 			continue;
4166 
4167 		vs = btf_var_secinfos(t);
4168 		for (j = 0; j < btf_vlen(t); j++, vs++) {
4169 			if (vs->type == ext_btf_id)
4170 				return i;
4171 		}
4172 	}
4173 
4174 	return -ENOENT;
4175 }
4176 
4177 static enum kcfg_type find_kcfg_type(const struct btf *btf, int id,
4178 				     bool *is_signed)
4179 {
4180 	const struct btf_type *t;
4181 	const char *name;
4182 
4183 	t = skip_mods_and_typedefs(btf, id, NULL);
4184 	name = btf__name_by_offset(btf, t->name_off);
4185 
4186 	if (is_signed)
4187 		*is_signed = false;
4188 	switch (btf_kind(t)) {
4189 	case BTF_KIND_INT: {
4190 		int enc = btf_int_encoding(t);
4191 
4192 		if (enc & BTF_INT_BOOL)
4193 			return t->size == 1 ? KCFG_BOOL : KCFG_UNKNOWN;
4194 		if (is_signed)
4195 			*is_signed = enc & BTF_INT_SIGNED;
4196 		if (t->size == 1)
4197 			return KCFG_CHAR;
4198 		if (t->size < 1 || t->size > 8 || (t->size & (t->size - 1)))
4199 			return KCFG_UNKNOWN;
4200 		return KCFG_INT;
4201 	}
4202 	case BTF_KIND_ENUM:
4203 		if (t->size != 4)
4204 			return KCFG_UNKNOWN;
4205 		if (strcmp(name, "libbpf_tristate"))
4206 			return KCFG_UNKNOWN;
4207 		return KCFG_TRISTATE;
4208 	case BTF_KIND_ENUM64:
4209 		if (strcmp(name, "libbpf_tristate"))
4210 			return KCFG_UNKNOWN;
4211 		return KCFG_TRISTATE;
4212 	case BTF_KIND_ARRAY:
4213 		if (btf_array(t)->nelems == 0)
4214 			return KCFG_UNKNOWN;
4215 		if (find_kcfg_type(btf, btf_array(t)->type, NULL) != KCFG_CHAR)
4216 			return KCFG_UNKNOWN;
4217 		return KCFG_CHAR_ARR;
4218 	default:
4219 		return KCFG_UNKNOWN;
4220 	}
4221 }
4222 
4223 static int cmp_externs(const void *_a, const void *_b)
4224 {
4225 	const struct extern_desc *a = _a;
4226 	const struct extern_desc *b = _b;
4227 
4228 	if (a->type != b->type)
4229 		return a->type < b->type ? -1 : 1;
4230 
4231 	if (a->type == EXT_KCFG) {
4232 		/* descending order by alignment requirements */
4233 		if (a->kcfg.align != b->kcfg.align)
4234 			return a->kcfg.align > b->kcfg.align ? -1 : 1;
4235 		/* ascending order by size, within same alignment class */
4236 		if (a->kcfg.sz != b->kcfg.sz)
4237 			return a->kcfg.sz < b->kcfg.sz ? -1 : 1;
4238 	}
4239 
4240 	/* resolve ties by name */
4241 	return strcmp(a->name, b->name);
4242 }
4243 
4244 static int find_int_btf_id(const struct btf *btf)
4245 {
4246 	const struct btf_type *t;
4247 	int i, n;
4248 
4249 	n = btf__type_cnt(btf);
4250 	for (i = 1; i < n; i++) {
4251 		t = btf__type_by_id(btf, i);
4252 
4253 		if (btf_is_int(t) && btf_int_bits(t) == 32)
4254 			return i;
4255 	}
4256 
4257 	return 0;
4258 }
4259 
4260 static int add_dummy_ksym_var(struct btf *btf)
4261 {
4262 	int i, int_btf_id, sec_btf_id, dummy_var_btf_id;
4263 	const struct btf_var_secinfo *vs;
4264 	const struct btf_type *sec;
4265 
4266 	if (!btf)
4267 		return 0;
4268 
4269 	sec_btf_id = btf__find_by_name_kind(btf, KSYMS_SEC,
4270 					    BTF_KIND_DATASEC);
4271 	if (sec_btf_id < 0)
4272 		return 0;
4273 
4274 	sec = btf__type_by_id(btf, sec_btf_id);
4275 	vs = btf_var_secinfos(sec);
4276 	for (i = 0; i < btf_vlen(sec); i++, vs++) {
4277 		const struct btf_type *vt;
4278 
4279 		vt = btf__type_by_id(btf, vs->type);
4280 		if (btf_is_func(vt))
4281 			break;
4282 	}
4283 
4284 	/* No func in ksyms sec.  No need to add dummy var. */
4285 	if (i == btf_vlen(sec))
4286 		return 0;
4287 
4288 	int_btf_id = find_int_btf_id(btf);
4289 	dummy_var_btf_id = btf__add_var(btf,
4290 					"dummy_ksym",
4291 					BTF_VAR_GLOBAL_ALLOCATED,
4292 					int_btf_id);
4293 	if (dummy_var_btf_id < 0)
4294 		pr_warn("cannot create a dummy_ksym var\n");
4295 
4296 	return dummy_var_btf_id;
4297 }
4298 
4299 static int bpf_object__collect_externs(struct bpf_object *obj)
4300 {
4301 	struct btf_type *sec, *kcfg_sec = NULL, *ksym_sec = NULL;
4302 	const struct btf_type *t;
4303 	struct extern_desc *ext;
4304 	int i, n, off, dummy_var_btf_id;
4305 	const char *ext_name, *sec_name;
4306 	size_t ext_essent_len;
4307 	Elf_Scn *scn;
4308 	Elf64_Shdr *sh;
4309 
4310 	if (!obj->efile.symbols)
4311 		return 0;
4312 
4313 	scn = elf_sec_by_idx(obj, obj->efile.symbols_shndx);
4314 	sh = elf_sec_hdr(obj, scn);
4315 	if (!sh || sh->sh_entsize != sizeof(Elf64_Sym))
4316 		return -LIBBPF_ERRNO__FORMAT;
4317 
4318 	dummy_var_btf_id = add_dummy_ksym_var(obj->btf);
4319 	if (dummy_var_btf_id < 0)
4320 		return dummy_var_btf_id;
4321 
4322 	n = sh->sh_size / sh->sh_entsize;
4323 	pr_debug("looking for externs among %d symbols...\n", n);
4324 
4325 	for (i = 0; i < n; i++) {
4326 		Elf64_Sym *sym = elf_sym_by_idx(obj, i);
4327 
4328 		if (!sym)
4329 			return -LIBBPF_ERRNO__FORMAT;
4330 		if (!sym_is_extern(sym))
4331 			continue;
4332 		ext_name = elf_sym_str(obj, sym->st_name);
4333 		if (str_is_empty(ext_name))
4334 			continue;
4335 
4336 		ext = obj->externs;
4337 		ext = libbpf_reallocarray(ext, obj->nr_extern + 1, sizeof(*ext));
4338 		if (!ext)
4339 			return -ENOMEM;
4340 		obj->externs = ext;
4341 		ext = &ext[obj->nr_extern];
4342 		memset(ext, 0, sizeof(*ext));
4343 		obj->nr_extern++;
4344 
4345 		ext->btf_id = find_extern_btf_id(obj->btf, ext_name);
4346 		if (ext->btf_id <= 0) {
4347 			pr_warn("failed to find BTF for extern '%s': %d\n",
4348 				ext_name, ext->btf_id);
4349 			return ext->btf_id;
4350 		}
4351 		t = btf__type_by_id(obj->btf, ext->btf_id);
4352 		ext->name = strdup(btf__name_by_offset(obj->btf, t->name_off));
4353 		if (!ext->name)
4354 			return -ENOMEM;
4355 		ext->sym_idx = i;
4356 		ext->is_weak = ELF64_ST_BIND(sym->st_info) == STB_WEAK;
4357 
4358 		ext_essent_len = bpf_core_essential_name_len(ext->name);
4359 		ext->essent_name = NULL;
4360 		if (ext_essent_len != strlen(ext->name)) {
4361 			ext->essent_name = strndup(ext->name, ext_essent_len);
4362 			if (!ext->essent_name)
4363 				return -ENOMEM;
4364 		}
4365 
4366 		ext->sec_btf_id = find_extern_sec_btf_id(obj->btf, ext->btf_id);
4367 		if (ext->sec_btf_id <= 0) {
4368 			pr_warn("failed to find BTF for extern '%s' [%d] section: %d\n",
4369 				ext_name, ext->btf_id, ext->sec_btf_id);
4370 			return ext->sec_btf_id;
4371 		}
4372 		sec = (void *)btf__type_by_id(obj->btf, ext->sec_btf_id);
4373 		sec_name = btf__name_by_offset(obj->btf, sec->name_off);
4374 
4375 		if (strcmp(sec_name, KCONFIG_SEC) == 0) {
4376 			if (btf_is_func(t)) {
4377 				pr_warn("extern function %s is unsupported under %s section\n",
4378 					ext->name, KCONFIG_SEC);
4379 				return -ENOTSUP;
4380 			}
4381 			kcfg_sec = sec;
4382 			ext->type = EXT_KCFG;
4383 			ext->kcfg.sz = btf__resolve_size(obj->btf, t->type);
4384 			if (ext->kcfg.sz <= 0) {
4385 				pr_warn("failed to resolve size of extern (kcfg) '%s': %d\n",
4386 					ext_name, ext->kcfg.sz);
4387 				return ext->kcfg.sz;
4388 			}
4389 			ext->kcfg.align = btf__align_of(obj->btf, t->type);
4390 			if (ext->kcfg.align <= 0) {
4391 				pr_warn("failed to determine alignment of extern (kcfg) '%s': %d\n",
4392 					ext_name, ext->kcfg.align);
4393 				return -EINVAL;
4394 			}
4395 			ext->kcfg.type = find_kcfg_type(obj->btf, t->type,
4396 							&ext->kcfg.is_signed);
4397 			if (ext->kcfg.type == KCFG_UNKNOWN) {
4398 				pr_warn("extern (kcfg) '%s': type is unsupported\n", ext_name);
4399 				return -ENOTSUP;
4400 			}
4401 		} else if (strcmp(sec_name, KSYMS_SEC) == 0) {
4402 			ksym_sec = sec;
4403 			ext->type = EXT_KSYM;
4404 			skip_mods_and_typedefs(obj->btf, t->type,
4405 					       &ext->ksym.type_id);
4406 		} else {
4407 			pr_warn("unrecognized extern section '%s'\n", sec_name);
4408 			return -ENOTSUP;
4409 		}
4410 	}
4411 	pr_debug("collected %d externs total\n", obj->nr_extern);
4412 
4413 	if (!obj->nr_extern)
4414 		return 0;
4415 
4416 	/* sort externs by type, for kcfg ones also by (align, size, name) */
4417 	qsort(obj->externs, obj->nr_extern, sizeof(*ext), cmp_externs);
4418 
4419 	/* for .ksyms section, we need to turn all externs into allocated
4420 	 * variables in BTF to pass kernel verification; we do this by
4421 	 * pretending that each extern is a 8-byte variable
4422 	 */
4423 	if (ksym_sec) {
4424 		/* find existing 4-byte integer type in BTF to use for fake
4425 		 * extern variables in DATASEC
4426 		 */
4427 		int int_btf_id = find_int_btf_id(obj->btf);
4428 		/* For extern function, a dummy_var added earlier
4429 		 * will be used to replace the vs->type and
4430 		 * its name string will be used to refill
4431 		 * the missing param's name.
4432 		 */
4433 		const struct btf_type *dummy_var;
4434 
4435 		dummy_var = btf__type_by_id(obj->btf, dummy_var_btf_id);
4436 		for (i = 0; i < obj->nr_extern; i++) {
4437 			ext = &obj->externs[i];
4438 			if (ext->type != EXT_KSYM)
4439 				continue;
4440 			pr_debug("extern (ksym) #%d: symbol %d, name %s\n",
4441 				 i, ext->sym_idx, ext->name);
4442 		}
4443 
4444 		sec = ksym_sec;
4445 		n = btf_vlen(sec);
4446 		for (i = 0, off = 0; i < n; i++, off += sizeof(int)) {
4447 			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
4448 			struct btf_type *vt;
4449 
4450 			vt = (void *)btf__type_by_id(obj->btf, vs->type);
4451 			ext_name = btf__name_by_offset(obj->btf, vt->name_off);
4452 			ext = find_extern_by_name(obj, ext_name);
4453 			if (!ext) {
4454 				pr_warn("failed to find extern definition for BTF %s '%s'\n",
4455 					btf_kind_str(vt), ext_name);
4456 				return -ESRCH;
4457 			}
4458 			if (btf_is_func(vt)) {
4459 				const struct btf_type *func_proto;
4460 				struct btf_param *param;
4461 				int j;
4462 
4463 				func_proto = btf__type_by_id(obj->btf,
4464 							     vt->type);
4465 				param = btf_params(func_proto);
4466 				/* Reuse the dummy_var string if the
4467 				 * func proto does not have param name.
4468 				 */
4469 				for (j = 0; j < btf_vlen(func_proto); j++)
4470 					if (param[j].type && !param[j].name_off)
4471 						param[j].name_off =
4472 							dummy_var->name_off;
4473 				vs->type = dummy_var_btf_id;
4474 				vt->info &= ~0xffff;
4475 				vt->info |= BTF_FUNC_GLOBAL;
4476 			} else {
4477 				btf_var(vt)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
4478 				vt->type = int_btf_id;
4479 			}
4480 			vs->offset = off;
4481 			vs->size = sizeof(int);
4482 		}
4483 		sec->size = off;
4484 	}
4485 
4486 	if (kcfg_sec) {
4487 		sec = kcfg_sec;
4488 		/* for kcfg externs calculate their offsets within a .kconfig map */
4489 		off = 0;
4490 		for (i = 0; i < obj->nr_extern; i++) {
4491 			ext = &obj->externs[i];
4492 			if (ext->type != EXT_KCFG)
4493 				continue;
4494 
4495 			ext->kcfg.data_off = roundup(off, ext->kcfg.align);
4496 			off = ext->kcfg.data_off + ext->kcfg.sz;
4497 			pr_debug("extern (kcfg) #%d: symbol %d, off %u, name %s\n",
4498 				 i, ext->sym_idx, ext->kcfg.data_off, ext->name);
4499 		}
4500 		sec->size = off;
4501 		n = btf_vlen(sec);
4502 		for (i = 0; i < n; i++) {
4503 			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
4504 
4505 			t = btf__type_by_id(obj->btf, vs->type);
4506 			ext_name = btf__name_by_offset(obj->btf, t->name_off);
4507 			ext = find_extern_by_name(obj, ext_name);
4508 			if (!ext) {
4509 				pr_warn("failed to find extern definition for BTF var '%s'\n",
4510 					ext_name);
4511 				return -ESRCH;
4512 			}
4513 			btf_var(t)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
4514 			vs->offset = ext->kcfg.data_off;
4515 		}
4516 	}
4517 	return 0;
4518 }
4519 
4520 static bool prog_is_subprog(const struct bpf_object *obj, const struct bpf_program *prog)
4521 {
4522 	return prog->sec_idx == obj->efile.text_shndx;
4523 }
4524 
4525 struct bpf_program *
4526 bpf_object__find_program_by_name(const struct bpf_object *obj,
4527 				 const char *name)
4528 {
4529 	struct bpf_program *prog;
4530 
4531 	bpf_object__for_each_program(prog, obj) {
4532 		if (prog_is_subprog(obj, prog))
4533 			continue;
4534 		if (!strcmp(prog->name, name))
4535 			return prog;
4536 	}
4537 	return errno = ENOENT, NULL;
4538 }
4539 
4540 static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
4541 				      int shndx)
4542 {
4543 	switch (obj->efile.secs[shndx].sec_type) {
4544 	case SEC_BSS:
4545 	case SEC_DATA:
4546 	case SEC_RODATA:
4547 		return true;
4548 	default:
4549 		return false;
4550 	}
4551 }
4552 
4553 static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
4554 				      int shndx)
4555 {
4556 	return shndx == obj->efile.btf_maps_shndx;
4557 }
4558 
4559 static enum libbpf_map_type
4560 bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
4561 {
4562 	if (shndx == obj->efile.symbols_shndx)
4563 		return LIBBPF_MAP_KCONFIG;
4564 
4565 	switch (obj->efile.secs[shndx].sec_type) {
4566 	case SEC_BSS:
4567 		return LIBBPF_MAP_BSS;
4568 	case SEC_DATA:
4569 		return LIBBPF_MAP_DATA;
4570 	case SEC_RODATA:
4571 		return LIBBPF_MAP_RODATA;
4572 	default:
4573 		return LIBBPF_MAP_UNSPEC;
4574 	}
4575 }
4576 
4577 static int bpf_prog_compute_hash(struct bpf_program *prog)
4578 {
4579 	struct bpf_insn *purged;
4580 	int i, err = 0;
4581 
4582 	purged = calloc(prog->insns_cnt, BPF_INSN_SZ);
4583 	if (!purged)
4584 		return -ENOMEM;
4585 
4586 	/* If relocations have been done, the map_fd needs to be
4587 	 * discarded for the digest calculation.
4588 	 */
4589 	for (i = 0; i < prog->insns_cnt; i++) {
4590 		purged[i] = prog->insns[i];
4591 		if (purged[i].code == (BPF_LD | BPF_IMM | BPF_DW) &&
4592 		    (purged[i].src_reg == BPF_PSEUDO_MAP_FD ||
4593 		     purged[i].src_reg == BPF_PSEUDO_MAP_VALUE)) {
4594 			purged[i].imm = 0;
4595 			i++;
4596 			if (i >= prog->insns_cnt ||
4597 			    prog->insns[i].code != 0 ||
4598 			    prog->insns[i].dst_reg != 0 ||
4599 			    prog->insns[i].src_reg != 0 ||
4600 			    prog->insns[i].off != 0) {
4601 				err = -EINVAL;
4602 				goto out;
4603 			}
4604 			purged[i] = prog->insns[i];
4605 			purged[i].imm = 0;
4606 		}
4607 	}
4608 	libbpf_sha256(purged, prog->insns_cnt * sizeof(struct bpf_insn),
4609 		      prog->hash);
4610 out:
4611 	free(purged);
4612 	return err;
4613 }
4614 
4615 static int bpf_program__record_reloc(struct bpf_program *prog,
4616 				     struct reloc_desc *reloc_desc,
4617 				     __u32 insn_idx, const char *sym_name,
4618 				     const Elf64_Sym *sym, const Elf64_Rel *rel)
4619 {
4620 	struct bpf_insn *insn = &prog->insns[insn_idx];
4621 	size_t map_idx, nr_maps = prog->obj->nr_maps;
4622 	struct bpf_object *obj = prog->obj;
4623 	__u32 shdr_idx = sym->st_shndx;
4624 	enum libbpf_map_type type;
4625 	const char *sym_sec_name;
4626 	struct bpf_map *map;
4627 
4628 	if (!is_call_insn(insn) && !is_ldimm64_insn(insn)) {
4629 		pr_warn("prog '%s': invalid relo against '%s' for insns[%d].code 0x%x\n",
4630 			prog->name, sym_name, insn_idx, insn->code);
4631 		return -LIBBPF_ERRNO__RELOC;
4632 	}
4633 
4634 	if (sym_is_extern(sym)) {
4635 		int sym_idx = ELF64_R_SYM(rel->r_info);
4636 		int i, n = obj->nr_extern;
4637 		struct extern_desc *ext;
4638 
4639 		for (i = 0; i < n; i++) {
4640 			ext = &obj->externs[i];
4641 			if (ext->sym_idx == sym_idx)
4642 				break;
4643 		}
4644 		if (i >= n) {
4645 			pr_warn("prog '%s': extern relo failed to find extern for '%s' (%d)\n",
4646 				prog->name, sym_name, sym_idx);
4647 			return -LIBBPF_ERRNO__RELOC;
4648 		}
4649 		pr_debug("prog '%s': found extern #%d '%s' (sym %d) for insn #%u\n",
4650 			 prog->name, i, ext->name, ext->sym_idx, insn_idx);
4651 		if (insn->code == (BPF_JMP | BPF_CALL))
4652 			reloc_desc->type = RELO_EXTERN_CALL;
4653 		else
4654 			reloc_desc->type = RELO_EXTERN_LD64;
4655 		reloc_desc->insn_idx = insn_idx;
4656 		reloc_desc->ext_idx = i;
4657 		return 0;
4658 	}
4659 
4660 	/* sub-program call relocation */
4661 	if (is_call_insn(insn)) {
4662 		if (insn->src_reg != BPF_PSEUDO_CALL) {
4663 			pr_warn("prog '%s': incorrect bpf_call opcode\n", prog->name);
4664 			return -LIBBPF_ERRNO__RELOC;
4665 		}
4666 		/* text_shndx can be 0, if no default "main" program exists */
4667 		if (!shdr_idx || shdr_idx != obj->efile.text_shndx) {
4668 			sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4669 			pr_warn("prog '%s': bad call relo against '%s' in section '%s'\n",
4670 				prog->name, sym_name, sym_sec_name);
4671 			return -LIBBPF_ERRNO__RELOC;
4672 		}
4673 		if (sym->st_value % BPF_INSN_SZ) {
4674 			pr_warn("prog '%s': bad call relo against '%s' at offset %zu\n",
4675 				prog->name, sym_name, (size_t)sym->st_value);
4676 			return -LIBBPF_ERRNO__RELOC;
4677 		}
4678 		reloc_desc->type = RELO_CALL;
4679 		reloc_desc->insn_idx = insn_idx;
4680 		reloc_desc->sym_off = sym->st_value;
4681 		return 0;
4682 	}
4683 
4684 	if (!shdr_idx || shdr_idx >= SHN_LORESERVE) {
4685 		pr_warn("prog '%s': invalid relo against '%s' in special section 0x%x; forgot to initialize global var?..\n",
4686 			prog->name, sym_name, shdr_idx);
4687 		return -LIBBPF_ERRNO__RELOC;
4688 	}
4689 
4690 	/* loading subprog addresses */
4691 	if (sym_is_subprog(sym, obj->efile.text_shndx)) {
4692 		/* global_func: sym->st_value = offset in the section, insn->imm = 0.
4693 		 * local_func: sym->st_value = 0, insn->imm = offset in the section.
4694 		 */
4695 		if ((sym->st_value % BPF_INSN_SZ) || (insn->imm % BPF_INSN_SZ)) {
4696 			pr_warn("prog '%s': bad subprog addr relo against '%s' at offset %zu+%d\n",
4697 				prog->name, sym_name, (size_t)sym->st_value, insn->imm);
4698 			return -LIBBPF_ERRNO__RELOC;
4699 		}
4700 
4701 		reloc_desc->type = RELO_SUBPROG_ADDR;
4702 		reloc_desc->insn_idx = insn_idx;
4703 		reloc_desc->sym_off = sym->st_value;
4704 		return 0;
4705 	}
4706 
4707 	type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
4708 	sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4709 
4710 	/* arena data relocation */
4711 	if (shdr_idx == obj->efile.arena_data_shndx) {
4712 		if (obj->arena_map_idx < 0) {
4713 			pr_warn("prog '%s': bad arena data relocation at insn %u, no arena maps defined\n",
4714 				prog->name, insn_idx);
4715 			return -LIBBPF_ERRNO__RELOC;
4716 		}
4717 		reloc_desc->type = RELO_DATA;
4718 		reloc_desc->insn_idx = insn_idx;
4719 		reloc_desc->map_idx = obj->arena_map_idx;
4720 		reloc_desc->sym_off = sym->st_value;
4721 
4722 		map = &obj->maps[obj->arena_map_idx];
4723 		pr_debug("prog '%s': found arena map %d (%s, sec %d, off %zu) for insn %u\n",
4724 			 prog->name, obj->arena_map_idx, map->name, map->sec_idx,
4725 			 map->sec_offset, insn_idx);
4726 		return 0;
4727 	}
4728 
4729 	/* jump table data relocation */
4730 	if (shdr_idx == obj->efile.jumptables_data_shndx) {
4731 		reloc_desc->type = RELO_INSN_ARRAY;
4732 		reloc_desc->insn_idx = insn_idx;
4733 		reloc_desc->map_idx = -1;
4734 		reloc_desc->sym_off = sym->st_value;
4735 		reloc_desc->sym_size = sym->st_size;
4736 		return 0;
4737 	}
4738 
4739 	/* generic map reference relocation */
4740 	if (type == LIBBPF_MAP_UNSPEC) {
4741 		if (!bpf_object__shndx_is_maps(obj, shdr_idx)) {
4742 			pr_warn("prog '%s': bad map relo against '%s' in section '%s'\n",
4743 				prog->name, sym_name, sym_sec_name);
4744 			return -LIBBPF_ERRNO__RELOC;
4745 		}
4746 		for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4747 			map = &obj->maps[map_idx];
4748 			if (map->libbpf_type != type ||
4749 			    map->sec_idx != sym->st_shndx ||
4750 			    map->sec_offset != sym->st_value)
4751 				continue;
4752 			pr_debug("prog '%s': found map %zd (%s, sec %d, off %zu) for insn #%u\n",
4753 				 prog->name, map_idx, map->name, map->sec_idx,
4754 				 map->sec_offset, insn_idx);
4755 			break;
4756 		}
4757 		if (map_idx >= nr_maps) {
4758 			pr_warn("prog '%s': map relo failed to find map for section '%s', off %zu\n",
4759 				prog->name, sym_sec_name, (size_t)sym->st_value);
4760 			return -LIBBPF_ERRNO__RELOC;
4761 		}
4762 		reloc_desc->type = RELO_LD64;
4763 		reloc_desc->insn_idx = insn_idx;
4764 		reloc_desc->map_idx = map_idx;
4765 		reloc_desc->sym_off = 0; /* sym->st_value determines map_idx */
4766 		return 0;
4767 	}
4768 
4769 	/* global data map relocation */
4770 	if (!bpf_object__shndx_is_data(obj, shdr_idx)) {
4771 		pr_warn("prog '%s': bad data relo against section '%s'\n",
4772 			prog->name, sym_sec_name);
4773 		return -LIBBPF_ERRNO__RELOC;
4774 	}
4775 	for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4776 		map = &obj->maps[map_idx];
4777 		if (map->libbpf_type != type || map->sec_idx != sym->st_shndx)
4778 			continue;
4779 		pr_debug("prog '%s': found data map %zd (%s, sec %d, off %zu) for insn %u\n",
4780 			 prog->name, map_idx, map->name, map->sec_idx,
4781 			 map->sec_offset, insn_idx);
4782 		break;
4783 	}
4784 	if (map_idx >= nr_maps) {
4785 		pr_warn("prog '%s': data relo failed to find map for section '%s'\n",
4786 			prog->name, sym_sec_name);
4787 		return -LIBBPF_ERRNO__RELOC;
4788 	}
4789 
4790 	reloc_desc->type = RELO_DATA;
4791 	reloc_desc->insn_idx = insn_idx;
4792 	reloc_desc->map_idx = map_idx;
4793 	reloc_desc->sym_off = sym->st_value;
4794 	return 0;
4795 }
4796 
4797 static bool prog_contains_insn(const struct bpf_program *prog, size_t insn_idx)
4798 {
4799 	return insn_idx >= prog->sec_insn_off &&
4800 	       insn_idx < prog->sec_insn_off + prog->sec_insn_cnt;
4801 }
4802 
4803 static struct bpf_program *find_prog_by_sec_insn(const struct bpf_object *obj,
4804 						 size_t sec_idx, size_t insn_idx)
4805 {
4806 	int l = 0, r = obj->nr_programs - 1, m;
4807 	struct bpf_program *prog;
4808 
4809 	if (!obj->nr_programs)
4810 		return NULL;
4811 
4812 	while (l < r) {
4813 		m = l + (r - l + 1) / 2;
4814 		prog = &obj->programs[m];
4815 
4816 		if (prog->sec_idx < sec_idx ||
4817 		    (prog->sec_idx == sec_idx && prog->sec_insn_off <= insn_idx))
4818 			l = m;
4819 		else
4820 			r = m - 1;
4821 	}
4822 	/* matching program could be at index l, but it still might be the
4823 	 * wrong one, so we need to double check conditions for the last time
4824 	 */
4825 	prog = &obj->programs[l];
4826 	if (prog->sec_idx == sec_idx && prog_contains_insn(prog, insn_idx))
4827 		return prog;
4828 	return NULL;
4829 }
4830 
4831 static int
4832 bpf_object__collect_prog_relos(struct bpf_object *obj, Elf64_Shdr *shdr, Elf_Data *data)
4833 {
4834 	const char *relo_sec_name, *sec_name;
4835 	size_t sec_idx = shdr->sh_info, sym_idx;
4836 	struct bpf_program *prog;
4837 	struct reloc_desc *relos;
4838 	int err, i, nrels;
4839 	const char *sym_name;
4840 	__u32 insn_idx;
4841 	Elf_Scn *scn;
4842 	Elf_Data *scn_data;
4843 	Elf64_Sym *sym;
4844 	Elf64_Rel *rel;
4845 
4846 	if (sec_idx >= obj->efile.sec_cnt)
4847 		return -EINVAL;
4848 
4849 	scn = elf_sec_by_idx(obj, sec_idx);
4850 	scn_data = elf_sec_data(obj, scn);
4851 	if (!scn_data)
4852 		return -LIBBPF_ERRNO__FORMAT;
4853 
4854 	relo_sec_name = elf_sec_str(obj, shdr->sh_name);
4855 	sec_name = elf_sec_name(obj, scn);
4856 	if (!relo_sec_name || !sec_name)
4857 		return -EINVAL;
4858 
4859 	pr_debug("sec '%s': collecting relocation for section(%zu) '%s'\n",
4860 		 relo_sec_name, sec_idx, sec_name);
4861 	nrels = shdr->sh_size / shdr->sh_entsize;
4862 
4863 	for (i = 0; i < nrels; i++) {
4864 		rel = elf_rel_by_idx(data, i);
4865 		if (!rel) {
4866 			pr_warn("sec '%s': failed to get relo #%d\n", relo_sec_name, i);
4867 			return -LIBBPF_ERRNO__FORMAT;
4868 		}
4869 
4870 		sym_idx = ELF64_R_SYM(rel->r_info);
4871 		sym = elf_sym_by_idx(obj, sym_idx);
4872 		if (!sym) {
4873 			pr_warn("sec '%s': symbol #%zu not found for relo #%d\n",
4874 				relo_sec_name, sym_idx, i);
4875 			return -LIBBPF_ERRNO__FORMAT;
4876 		}
4877 
4878 		if (sym->st_shndx >= obj->efile.sec_cnt) {
4879 			pr_warn("sec '%s': corrupted symbol #%zu pointing to invalid section #%zu for relo #%d\n",
4880 				relo_sec_name, sym_idx, (size_t)sym->st_shndx, i);
4881 			return -LIBBPF_ERRNO__FORMAT;
4882 		}
4883 
4884 		if (rel->r_offset % BPF_INSN_SZ || rel->r_offset >= scn_data->d_size) {
4885 			pr_warn("sec '%s': invalid offset 0x%zx for relo #%d\n",
4886 				relo_sec_name, (size_t)rel->r_offset, i);
4887 			return -LIBBPF_ERRNO__FORMAT;
4888 		}
4889 
4890 		insn_idx = rel->r_offset / BPF_INSN_SZ;
4891 		/* relocations against static functions are recorded as
4892 		 * relocations against the section that contains a function;
4893 		 * in such case, symbol will be STT_SECTION and sym.st_name
4894 		 * will point to empty string (0), so fetch section name
4895 		 * instead
4896 		 */
4897 		if (ELF64_ST_TYPE(sym->st_info) == STT_SECTION && sym->st_name == 0)
4898 			sym_name = elf_sec_name(obj, elf_sec_by_idx(obj, sym->st_shndx));
4899 		else
4900 			sym_name = elf_sym_str(obj, sym->st_name);
4901 		sym_name = sym_name ?: "<?";
4902 
4903 		pr_debug("sec '%s': relo #%d: insn #%u against '%s'\n",
4904 			 relo_sec_name, i, insn_idx, sym_name);
4905 
4906 		prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
4907 		if (!prog) {
4908 			pr_debug("sec '%s': relo #%d: couldn't find program in section '%s' for insn #%u, probably overridden weak function, skipping...\n",
4909 				relo_sec_name, i, sec_name, insn_idx);
4910 			continue;
4911 		}
4912 
4913 		relos = libbpf_reallocarray(prog->reloc_desc,
4914 					    prog->nr_reloc + 1, sizeof(*relos));
4915 		if (!relos)
4916 			return -ENOMEM;
4917 		prog->reloc_desc = relos;
4918 
4919 		/* adjust insn_idx to local BPF program frame of reference */
4920 		insn_idx -= prog->sec_insn_off;
4921 		err = bpf_program__record_reloc(prog, &relos[prog->nr_reloc],
4922 						insn_idx, sym_name, sym, rel);
4923 		if (err)
4924 			return err;
4925 
4926 		prog->nr_reloc++;
4927 	}
4928 	return 0;
4929 }
4930 
4931 static int map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map)
4932 {
4933 	int id;
4934 
4935 	if (!obj->btf)
4936 		return -ENOENT;
4937 
4938 	/* if it's BTF-defined map, we don't need to search for type IDs.
4939 	 * For struct_ops map, it does not need btf_key_type_id and
4940 	 * btf_value_type_id.
4941 	 */
4942 	if (map->sec_idx == obj->efile.btf_maps_shndx || bpf_map__is_struct_ops(map))
4943 		return 0;
4944 
4945 	/*
4946 	 * LLVM annotates global data differently in BTF, that is,
4947 	 * only as '.data', '.bss' or '.rodata'.
4948 	 */
4949 	if (!bpf_map__is_internal(map))
4950 		return -ENOENT;
4951 
4952 	id = btf__find_by_name(obj->btf, map->real_name);
4953 	if (id < 0)
4954 		return id;
4955 
4956 	map->btf_key_type_id = 0;
4957 	map->btf_value_type_id = id;
4958 	return 0;
4959 }
4960 
4961 static int bpf_get_map_info_from_fdinfo(int fd, struct bpf_map_info *info)
4962 {
4963 	char file[PATH_MAX], buff[4096];
4964 	FILE *fp;
4965 	__u32 val;
4966 	int err;
4967 
4968 	snprintf(file, sizeof(file), "/proc/%d/fdinfo/%d", getpid(), fd);
4969 	memset(info, 0, sizeof(*info));
4970 
4971 	fp = fopen(file, "re");
4972 	if (!fp) {
4973 		err = -errno;
4974 		pr_warn("failed to open %s: %s. No procfs support?\n", file,
4975 			errstr(err));
4976 		return err;
4977 	}
4978 
4979 	while (fgets(buff, sizeof(buff), fp)) {
4980 		if (sscanf(buff, "map_type:\t%u", &val) == 1)
4981 			info->type = val;
4982 		else if (sscanf(buff, "key_size:\t%u", &val) == 1)
4983 			info->key_size = val;
4984 		else if (sscanf(buff, "value_size:\t%u", &val) == 1)
4985 			info->value_size = val;
4986 		else if (sscanf(buff, "max_entries:\t%u", &val) == 1)
4987 			info->max_entries = val;
4988 		else if (sscanf(buff, "map_flags:\t%i", &val) == 1)
4989 			info->map_flags = val;
4990 	}
4991 
4992 	fclose(fp);
4993 
4994 	return 0;
4995 }
4996 
4997 static bool map_is_created(const struct bpf_map *map)
4998 {
4999 	return map->obj->state >= OBJ_PREPARED || map->reused;
5000 }
5001 
5002 bool bpf_map__autocreate(const struct bpf_map *map)
5003 {
5004 	return map->autocreate;
5005 }
5006 
5007 int bpf_map__set_autocreate(struct bpf_map *map, bool autocreate)
5008 {
5009 	if (map_is_created(map))
5010 		return libbpf_err(-EBUSY);
5011 
5012 	map->autocreate = autocreate;
5013 	return 0;
5014 }
5015 
5016 int bpf_map__set_autoattach(struct bpf_map *map, bool autoattach)
5017 {
5018 	if (!bpf_map__is_struct_ops(map))
5019 		return libbpf_err(-EINVAL);
5020 
5021 	map->autoattach = autoattach;
5022 	return 0;
5023 }
5024 
5025 bool bpf_map__autoattach(const struct bpf_map *map)
5026 {
5027 	return map->autoattach;
5028 }
5029 
5030 int bpf_map__reuse_fd(struct bpf_map *map, int fd)
5031 {
5032 	struct bpf_map_info info;
5033 	__u32 len = sizeof(info), name_len;
5034 	int new_fd, err;
5035 	char *new_name;
5036 
5037 	memset(&info, 0, len);
5038 	err = bpf_map_get_info_by_fd(fd, &info, &len);
5039 	if (err && errno == EINVAL)
5040 		err = bpf_get_map_info_from_fdinfo(fd, &info);
5041 	if (err)
5042 		return libbpf_err(err);
5043 
5044 	name_len = strlen(info.name);
5045 	if (name_len == BPF_OBJ_NAME_LEN - 1 && strncmp(map->name, info.name, name_len) == 0)
5046 		new_name = strdup(map->name);
5047 	else
5048 		new_name = strdup(info.name);
5049 
5050 	if (!new_name)
5051 		return libbpf_err(-errno);
5052 
5053 	/*
5054 	 * Like dup(), but make sure new FD is >= 3 and has O_CLOEXEC set.
5055 	 * This is similar to what we do in ensure_good_fd(), but without
5056 	 * closing original FD.
5057 	 */
5058 	new_fd = fcntl(fd, F_DUPFD_CLOEXEC, 3);
5059 	if (new_fd < 0) {
5060 		err = -errno;
5061 		goto err_free_new_name;
5062 	}
5063 
5064 	err = reuse_fd(map->fd, new_fd);
5065 	if (err)
5066 		goto err_free_new_name;
5067 
5068 	free(map->name);
5069 
5070 	map->name = new_name;
5071 	map->def.type = info.type;
5072 	map->def.key_size = info.key_size;
5073 	map->def.value_size = info.value_size;
5074 	map->def.max_entries = info.max_entries;
5075 	map->def.map_flags = info.map_flags;
5076 	map->btf_key_type_id = info.btf_key_type_id;
5077 	map->btf_value_type_id = info.btf_value_type_id;
5078 	map->reused = true;
5079 	map->map_extra = info.map_extra;
5080 
5081 	return 0;
5082 
5083 err_free_new_name:
5084 	free(new_name);
5085 	return libbpf_err(err);
5086 }
5087 
5088 __u32 bpf_map__max_entries(const struct bpf_map *map)
5089 {
5090 	return map->def.max_entries;
5091 }
5092 
5093 struct bpf_map *bpf_map__inner_map(struct bpf_map *map)
5094 {
5095 	if (!bpf_map_type__is_map_in_map(map->def.type))
5096 		return errno = EINVAL, NULL;
5097 
5098 	return map->inner_map;
5099 }
5100 
5101 int bpf_map__set_max_entries(struct bpf_map *map, __u32 max_entries)
5102 {
5103 	if (map_is_created(map))
5104 		return libbpf_err(-EBUSY);
5105 
5106 	map->def.max_entries = max_entries;
5107 
5108 	/* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
5109 	if (map_is_ringbuf(map))
5110 		map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
5111 
5112 	return 0;
5113 }
5114 
5115 static int bpf_object_prepare_token(struct bpf_object *obj)
5116 {
5117 	const char *bpffs_path;
5118 	int bpffs_fd = -1, token_fd, err;
5119 	bool mandatory;
5120 	enum libbpf_print_level level;
5121 
5122 	/* token is explicitly prevented */
5123 	if (obj->token_path && obj->token_path[0] == '\0') {
5124 		pr_debug("object '%s': token is prevented, skipping...\n", obj->name);
5125 		return 0;
5126 	}
5127 
5128 	mandatory = obj->token_path != NULL;
5129 	level = mandatory ? LIBBPF_WARN : LIBBPF_DEBUG;
5130 
5131 	bpffs_path = obj->token_path ?: BPF_FS_DEFAULT_PATH;
5132 	bpffs_fd = open(bpffs_path, O_DIRECTORY, O_RDWR);
5133 	if (bpffs_fd < 0) {
5134 		err = -errno;
5135 		__pr(level, "object '%s': failed (%s) to open BPF FS mount at '%s'%s\n",
5136 		     obj->name, errstr(err), bpffs_path,
5137 		     mandatory ? "" : ", skipping optional step...");
5138 		return mandatory ? err : 0;
5139 	}
5140 
5141 	token_fd = bpf_token_create(bpffs_fd, 0);
5142 	close(bpffs_fd);
5143 	if (token_fd < 0) {
5144 		if (!mandatory && token_fd == -ENOENT) {
5145 			pr_debug("object '%s': BPF FS at '%s' doesn't have BPF token delegation set up, skipping...\n",
5146 				 obj->name, bpffs_path);
5147 			return 0;
5148 		}
5149 		__pr(level, "object '%s': failed (%d) to create BPF token from '%s'%s\n",
5150 		     obj->name, token_fd, bpffs_path,
5151 		     mandatory ? "" : ", skipping optional step...");
5152 		return mandatory ? token_fd : 0;
5153 	}
5154 
5155 	obj->feat_cache = calloc(1, sizeof(*obj->feat_cache));
5156 	if (!obj->feat_cache) {
5157 		close(token_fd);
5158 		return -ENOMEM;
5159 	}
5160 
5161 	obj->token_fd = token_fd;
5162 	obj->feat_cache->token_fd = token_fd;
5163 
5164 	return 0;
5165 }
5166 
5167 static int
5168 bpf_object__probe_loading(struct bpf_object *obj)
5169 {
5170 	struct bpf_insn insns[] = {
5171 		BPF_MOV64_IMM(BPF_REG_0, 0),
5172 		BPF_EXIT_INSN(),
5173 	};
5174 	int ret, insn_cnt = ARRAY_SIZE(insns);
5175 	LIBBPF_OPTS(bpf_prog_load_opts, opts,
5176 		.token_fd = obj->token_fd,
5177 		.prog_flags = obj->token_fd ? BPF_F_TOKEN_FD : 0,
5178 	);
5179 
5180 	if (obj->gen_loader)
5181 		return 0;
5182 
5183 	ret = bump_rlimit_memlock();
5184 	if (ret)
5185 		pr_warn("Failed to bump RLIMIT_MEMLOCK (err = %s), you might need to do it explicitly!\n",
5186 			errstr(ret));
5187 
5188 	/* make sure basic loading works */
5189 	ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, &opts);
5190 	if (ret < 0)
5191 		ret = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, &opts);
5192 	if (ret < 0) {
5193 		ret = errno;
5194 		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",
5195 			__func__, errstr(ret));
5196 		return -ret;
5197 	}
5198 	close(ret);
5199 
5200 	return 0;
5201 }
5202 
5203 bool kernel_supports(const struct bpf_object *obj, enum kern_feature_id feat_id)
5204 {
5205 	if (obj->gen_loader)
5206 		/* To generate loader program assume the latest kernel
5207 		 * to avoid doing extra prog_load, map_create syscalls.
5208 		 */
5209 		return true;
5210 
5211 	if (obj->feat_cache)
5212 		return feat_supported(obj->feat_cache, feat_id);
5213 
5214 	return feat_supported(NULL, feat_id);
5215 }
5216 
5217 /* Used in testing to simulate missing features. */
5218 void bpf_object_set_feat_cache(struct bpf_object *obj, struct kern_feature_cache *cache)
5219 {
5220 	if (obj->feat_cache)
5221 		free(obj->feat_cache);
5222 	obj->feat_cache = cache;
5223 }
5224 
5225 static bool map_is_reuse_compat(const struct bpf_map *map, int map_fd)
5226 {
5227 	struct bpf_map_info map_info;
5228 	__u32 map_info_len = sizeof(map_info);
5229 	int err;
5230 
5231 	memset(&map_info, 0, map_info_len);
5232 	err = bpf_map_get_info_by_fd(map_fd, &map_info, &map_info_len);
5233 	if (err && errno == EINVAL)
5234 		err = bpf_get_map_info_from_fdinfo(map_fd, &map_info);
5235 	if (err) {
5236 		pr_warn("failed to get map info for map FD %d: %s\n", map_fd,
5237 			errstr(err));
5238 		return false;
5239 	}
5240 
5241 	/*
5242 	 * bpf_get_map_info_by_fd() for DEVMAP will always return flags with
5243 	 * BPF_F_RDONLY_PROG set, but it generally is not set at map creation time.
5244 	 * Thus, ignore the BPF_F_RDONLY_PROG flag in the flags returned from
5245 	 * bpf_get_map_info_by_fd() when checking for compatibility with an
5246 	 * existing DEVMAP.
5247 	 */
5248 	if (map->def.type == BPF_MAP_TYPE_DEVMAP || map->def.type == BPF_MAP_TYPE_DEVMAP_HASH)
5249 		map_info.map_flags &= ~BPF_F_RDONLY_PROG;
5250 
5251 	return (map_info.type == map->def.type &&
5252 		map_info.key_size == map->def.key_size &&
5253 		map_info.value_size == map->def.value_size &&
5254 		map_info.max_entries == map->def.max_entries &&
5255 		map_info.map_flags == map->def.map_flags &&
5256 		map_info.map_extra == map->map_extra);
5257 }
5258 
5259 static int
5260 bpf_object__reuse_map(struct bpf_map *map)
5261 {
5262 	int err, pin_fd;
5263 
5264 	pin_fd = bpf_obj_get(map->pin_path);
5265 	if (pin_fd < 0) {
5266 		err = -errno;
5267 		if (err == -ENOENT) {
5268 			pr_debug("found no pinned map to reuse at '%s'\n",
5269 				 map->pin_path);
5270 			return 0;
5271 		}
5272 
5273 		pr_warn("couldn't retrieve pinned map '%s': %s\n",
5274 			map->pin_path, errstr(err));
5275 		return err;
5276 	}
5277 
5278 	if (!map_is_reuse_compat(map, pin_fd)) {
5279 		pr_warn("couldn't reuse pinned map at '%s': parameter mismatch\n",
5280 			map->pin_path);
5281 		close(pin_fd);
5282 		return -EINVAL;
5283 	}
5284 
5285 	err = bpf_map__reuse_fd(map, pin_fd);
5286 	close(pin_fd);
5287 	if (err)
5288 		return err;
5289 
5290 	map->pinned = true;
5291 	pr_debug("reused pinned map at '%s'\n", map->pin_path);
5292 
5293 	return 0;
5294 }
5295 
5296 static int
5297 bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
5298 {
5299 	enum libbpf_map_type map_type = map->libbpf_type;
5300 	int err, zero = 0;
5301 	size_t mmap_sz;
5302 
5303 	if (obj->gen_loader) {
5304 		bpf_gen__map_update_elem(obj->gen_loader, map - obj->maps,
5305 					 map->mmaped, map->def.value_size);
5306 		if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG)
5307 			bpf_gen__map_freeze(obj->gen_loader, map - obj->maps);
5308 		return 0;
5309 	}
5310 
5311 	err = bpf_map_update_elem(map->fd, &zero, map->mmaped, 0);
5312 	if (err) {
5313 		err = -errno;
5314 		pr_warn("map '%s': failed to set initial contents: %s\n",
5315 			bpf_map__name(map), errstr(err));
5316 		return err;
5317 	}
5318 
5319 	/* Freeze .rodata and .kconfig map as read-only from syscall side. */
5320 	if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG) {
5321 		err = bpf_map_freeze(map->fd);
5322 		if (err) {
5323 			err = -errno;
5324 			pr_warn("map '%s': failed to freeze as read-only: %s\n",
5325 				bpf_map__name(map), errstr(err));
5326 			return err;
5327 		}
5328 	}
5329 
5330 	/* Remap anonymous mmap()-ed "map initialization image" as
5331 	 * a BPF map-backed mmap()-ed memory, but preserving the same
5332 	 * memory address. This will cause kernel to change process'
5333 	 * page table to point to a different piece of kernel memory,
5334 	 * but from userspace point of view memory address (and its
5335 	 * contents, being identical at this point) will stay the
5336 	 * same. This mapping will be released by bpf_object__close()
5337 	 * as per normal clean up procedure.
5338 	 */
5339 	mmap_sz = bpf_map_mmap_sz(map);
5340 	if (map->def.map_flags & BPF_F_MMAPABLE) {
5341 		void *mmaped;
5342 		int prot;
5343 
5344 		if (map->def.map_flags & BPF_F_RDONLY_PROG)
5345 			prot = PROT_READ;
5346 		else
5347 			prot = PROT_READ | PROT_WRITE;
5348 		mmaped = mmap(map->mmaped, mmap_sz, prot, MAP_SHARED | MAP_FIXED, map->fd, 0);
5349 		if (mmaped == MAP_FAILED) {
5350 			err = -errno;
5351 			pr_warn("map '%s': failed to re-mmap() contents: %s\n",
5352 				bpf_map__name(map), errstr(err));
5353 			return err;
5354 		}
5355 		map->mmaped = mmaped;
5356 	} else if (map->mmaped) {
5357 		munmap(map->mmaped, mmap_sz);
5358 		map->mmaped = NULL;
5359 	}
5360 
5361 	return 0;
5362 }
5363 
5364 static void bpf_map__destroy(struct bpf_map *map);
5365 
5366 static int bpf_object__create_map(struct bpf_object *obj, struct bpf_map *map, bool is_inner)
5367 {
5368 	LIBBPF_OPTS(bpf_map_create_opts, create_attr);
5369 	struct bpf_map_def *def = &map->def;
5370 	const char *map_name = NULL;
5371 	int err = 0, map_fd;
5372 
5373 	if (kernel_supports(obj, FEAT_PROG_NAME))
5374 		map_name = map->name;
5375 	create_attr.map_ifindex = map->map_ifindex;
5376 	create_attr.map_flags = def->map_flags;
5377 	create_attr.numa_node = map->numa_node;
5378 	create_attr.map_extra = map->map_extra;
5379 	create_attr.token_fd = obj->token_fd;
5380 	if (obj->token_fd)
5381 		create_attr.map_flags |= BPF_F_TOKEN_FD;
5382 	if (map->excl_prog) {
5383 		err = bpf_prog_compute_hash(map->excl_prog);
5384 		if (err)
5385 			return err;
5386 
5387 		create_attr.excl_prog_hash = map->excl_prog->hash;
5388 		create_attr.excl_prog_hash_size = SHA256_DIGEST_LENGTH;
5389 	}
5390 
5391 	if (bpf_map__is_struct_ops(map)) {
5392 		create_attr.btf_vmlinux_value_type_id = map->btf_vmlinux_value_type_id;
5393 		if (map->mod_btf_fd >= 0) {
5394 			create_attr.value_type_btf_obj_fd = map->mod_btf_fd;
5395 			create_attr.map_flags |= BPF_F_VTYPE_BTF_OBJ_FD;
5396 		}
5397 	}
5398 
5399 	if (obj->btf && btf__fd(obj->btf) >= 0) {
5400 		create_attr.btf_fd = btf__fd(obj->btf);
5401 		create_attr.btf_key_type_id = map->btf_key_type_id;
5402 		create_attr.btf_value_type_id = map->btf_value_type_id;
5403 	}
5404 
5405 	if (bpf_map_type__is_map_in_map(def->type)) {
5406 		if (map->inner_map) {
5407 			err = map_set_def_max_entries(map->inner_map);
5408 			if (err)
5409 				return err;
5410 			err = bpf_object__create_map(obj, map->inner_map, true);
5411 			if (err) {
5412 				pr_warn("map '%s': failed to create inner map: %s\n",
5413 					map->name, errstr(err));
5414 				return err;
5415 			}
5416 			map->inner_map_fd = map->inner_map->fd;
5417 		}
5418 		if (map->inner_map_fd >= 0)
5419 			create_attr.inner_map_fd = map->inner_map_fd;
5420 	}
5421 
5422 	switch (def->type) {
5423 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
5424 	case BPF_MAP_TYPE_CGROUP_ARRAY:
5425 	case BPF_MAP_TYPE_STACK_TRACE:
5426 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
5427 	case BPF_MAP_TYPE_HASH_OF_MAPS:
5428 	case BPF_MAP_TYPE_DEVMAP:
5429 	case BPF_MAP_TYPE_DEVMAP_HASH:
5430 	case BPF_MAP_TYPE_CPUMAP:
5431 	case BPF_MAP_TYPE_XSKMAP:
5432 	case BPF_MAP_TYPE_SOCKMAP:
5433 	case BPF_MAP_TYPE_SOCKHASH:
5434 	case BPF_MAP_TYPE_QUEUE:
5435 	case BPF_MAP_TYPE_STACK:
5436 	case BPF_MAP_TYPE_ARENA:
5437 		create_attr.btf_fd = 0;
5438 		create_attr.btf_key_type_id = 0;
5439 		create_attr.btf_value_type_id = 0;
5440 		map->btf_key_type_id = 0;
5441 		map->btf_value_type_id = 0;
5442 		break;
5443 	case BPF_MAP_TYPE_STRUCT_OPS:
5444 		create_attr.btf_value_type_id = 0;
5445 		break;
5446 	default:
5447 		break;
5448 	}
5449 
5450 	if (obj->gen_loader) {
5451 		bpf_gen__map_create(obj->gen_loader, def->type, map_name,
5452 				    def->key_size, def->value_size, def->max_entries,
5453 				    &create_attr, is_inner ? -1 : map - obj->maps);
5454 		/* We keep pretenting we have valid FD to pass various fd >= 0
5455 		 * checks by just keeping original placeholder FDs in place.
5456 		 * See bpf_object__add_map() comment.
5457 		 * This placeholder fd will not be used with any syscall and
5458 		 * will be reset to -1 eventually.
5459 		 */
5460 		map_fd = map->fd;
5461 	} else {
5462 		map_fd = bpf_map_create(def->type, map_name,
5463 					def->key_size, def->value_size,
5464 					def->max_entries, &create_attr);
5465 	}
5466 	if (map_fd < 0 && (create_attr.btf_key_type_id || create_attr.btf_value_type_id)) {
5467 		err = -errno;
5468 		pr_warn("Error in bpf_create_map_xattr(%s): %s. Retrying without BTF.\n",
5469 			map->name, errstr(err));
5470 		create_attr.btf_fd = 0;
5471 		create_attr.btf_key_type_id = 0;
5472 		create_attr.btf_value_type_id = 0;
5473 		map->btf_key_type_id = 0;
5474 		map->btf_value_type_id = 0;
5475 		map_fd = bpf_map_create(def->type, map_name,
5476 					def->key_size, def->value_size,
5477 					def->max_entries, &create_attr);
5478 	}
5479 
5480 	if (bpf_map_type__is_map_in_map(def->type) && map->inner_map) {
5481 		if (obj->gen_loader)
5482 			map->inner_map->fd = -1;
5483 		bpf_map__destroy(map->inner_map);
5484 		zfree(&map->inner_map);
5485 	}
5486 
5487 	if (map_fd < 0)
5488 		return map_fd;
5489 
5490 	/* obj->gen_loader case, prevent reuse_fd() from closing map_fd */
5491 	if (map->fd == map_fd)
5492 		return 0;
5493 
5494 	/* Keep placeholder FD value but now point it to the BPF map object.
5495 	 * This way everything that relied on this map's FD (e.g., relocated
5496 	 * ldimm64 instructions) will stay valid and won't need adjustments.
5497 	 * map->fd stays valid but now point to what map_fd points to.
5498 	 */
5499 	return reuse_fd(map->fd, map_fd);
5500 }
5501 
5502 static int init_map_in_map_slots(struct bpf_object *obj, struct bpf_map *map)
5503 {
5504 	const struct bpf_map *targ_map;
5505 	unsigned int i;
5506 	int fd, err = 0;
5507 
5508 	for (i = 0; i < map->init_slots_sz; i++) {
5509 		if (!map->init_slots[i])
5510 			continue;
5511 
5512 		targ_map = map->init_slots[i];
5513 		fd = targ_map->fd;
5514 
5515 		if (obj->gen_loader) {
5516 			bpf_gen__populate_outer_map(obj->gen_loader,
5517 						    map - obj->maps, i,
5518 						    targ_map - obj->maps);
5519 		} else {
5520 			err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5521 		}
5522 		if (err) {
5523 			err = -errno;
5524 			pr_warn("map '%s': failed to initialize slot [%d] to map '%s' fd=%d: %s\n",
5525 				map->name, i, targ_map->name, fd, errstr(err));
5526 			return err;
5527 		}
5528 		pr_debug("map '%s': slot [%d] set to map '%s' fd=%d\n",
5529 			 map->name, i, targ_map->name, fd);
5530 	}
5531 
5532 	zfree(&map->init_slots);
5533 	map->init_slots_sz = 0;
5534 
5535 	return 0;
5536 }
5537 
5538 static int init_prog_array_slots(struct bpf_object *obj, struct bpf_map *map)
5539 {
5540 	const struct bpf_program *targ_prog;
5541 	unsigned int i;
5542 	int fd, err;
5543 
5544 	if (obj->gen_loader)
5545 		return -ENOTSUP;
5546 
5547 	for (i = 0; i < map->init_slots_sz; i++) {
5548 		if (!map->init_slots[i])
5549 			continue;
5550 
5551 		targ_prog = map->init_slots[i];
5552 		fd = bpf_program__fd(targ_prog);
5553 
5554 		err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5555 		if (err) {
5556 			err = -errno;
5557 			pr_warn("map '%s': failed to initialize slot [%d] to prog '%s' fd=%d: %s\n",
5558 				map->name, i, targ_prog->name, fd, errstr(err));
5559 			return err;
5560 		}
5561 		pr_debug("map '%s': slot [%d] set to prog '%s' fd=%d\n",
5562 			 map->name, i, targ_prog->name, fd);
5563 	}
5564 
5565 	zfree(&map->init_slots);
5566 	map->init_slots_sz = 0;
5567 
5568 	return 0;
5569 }
5570 
5571 static int bpf_object_init_prog_arrays(struct bpf_object *obj)
5572 {
5573 	struct bpf_map *map;
5574 	int i, err;
5575 
5576 	for (i = 0; i < obj->nr_maps; i++) {
5577 		map = &obj->maps[i];
5578 
5579 		if (!map->init_slots_sz || map->def.type != BPF_MAP_TYPE_PROG_ARRAY)
5580 			continue;
5581 
5582 		err = init_prog_array_slots(obj, map);
5583 		if (err < 0)
5584 			return err;
5585 	}
5586 	return 0;
5587 }
5588 
5589 static int map_set_def_max_entries(struct bpf_map *map)
5590 {
5591 	if (map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY && !map->def.max_entries) {
5592 		int nr_cpus;
5593 
5594 		nr_cpus = libbpf_num_possible_cpus();
5595 		if (nr_cpus < 0) {
5596 			pr_warn("map '%s': failed to determine number of system CPUs: %d\n",
5597 				map->name, nr_cpus);
5598 			return nr_cpus;
5599 		}
5600 		pr_debug("map '%s': setting size to %d\n", map->name, nr_cpus);
5601 		map->def.max_entries = nr_cpus;
5602 	}
5603 
5604 	return 0;
5605 }
5606 
5607 static int
5608 bpf_object__create_maps(struct bpf_object *obj)
5609 {
5610 	struct bpf_map *map;
5611 	unsigned int i, j;
5612 	int err;
5613 	bool retried;
5614 
5615 	for (i = 0; i < obj->nr_maps; i++) {
5616 		map = &obj->maps[i];
5617 
5618 		/* To support old kernels, we skip creating global data maps
5619 		 * (.rodata, .data, .kconfig, etc); later on, during program
5620 		 * loading, if we detect that at least one of the to-be-loaded
5621 		 * programs is referencing any global data map, we'll error
5622 		 * out with program name and relocation index logged.
5623 		 * This approach allows to accommodate Clang emitting
5624 		 * unnecessary .rodata.str1.1 sections for string literals,
5625 		 * but also it allows to have CO-RE applications that use
5626 		 * global variables in some of BPF programs, but not others.
5627 		 * If those global variable-using programs are not loaded at
5628 		 * runtime due to bpf_program__set_autoload(prog, false),
5629 		 * bpf_object loading will succeed just fine even on old
5630 		 * kernels.
5631 		 */
5632 		if (bpf_map__is_internal(map) && !kernel_supports(obj, FEAT_GLOBAL_DATA))
5633 			map->autocreate = false;
5634 
5635 		if (!map->autocreate) {
5636 			pr_debug("map '%s': skipped auto-creating...\n", map->name);
5637 			continue;
5638 		}
5639 
5640 		err = map_set_def_max_entries(map);
5641 		if (err)
5642 			goto err_out;
5643 
5644 		retried = false;
5645 retry:
5646 		if (map->pin_path) {
5647 			err = bpf_object__reuse_map(map);
5648 			if (err) {
5649 				pr_warn("map '%s': error reusing pinned map\n",
5650 					map->name);
5651 				goto err_out;
5652 			}
5653 			if (retried && map->fd < 0) {
5654 				pr_warn("map '%s': cannot find pinned map\n",
5655 					map->name);
5656 				err = -ENOENT;
5657 				goto err_out;
5658 			}
5659 		}
5660 
5661 		if (map->reused) {
5662 			pr_debug("map '%s': skipping creation (preset fd=%d)\n",
5663 				 map->name, map->fd);
5664 		} else {
5665 			err = bpf_object__create_map(obj, map, false);
5666 			if (err)
5667 				goto err_out;
5668 
5669 			pr_debug("map '%s': created successfully, fd=%d\n",
5670 				 map->name, map->fd);
5671 
5672 			if (bpf_map__is_internal(map)) {
5673 				err = bpf_object__populate_internal_map(obj, map);
5674 				if (err < 0)
5675 					goto err_out;
5676 			} else if (map->def.type == BPF_MAP_TYPE_ARENA) {
5677 				map->mmaped = mmap((void *)(long)map->map_extra,
5678 						   bpf_map_mmap_sz(map), PROT_READ | PROT_WRITE,
5679 						   map->map_extra ? MAP_SHARED | MAP_FIXED : MAP_SHARED,
5680 						   map->fd, 0);
5681 				if (map->mmaped == MAP_FAILED) {
5682 					err = -errno;
5683 					map->mmaped = NULL;
5684 					pr_warn("map '%s': failed to mmap arena: %s\n",
5685 						map->name, errstr(err));
5686 					return err;
5687 				}
5688 				if (obj->arena_data) {
5689 					memcpy(map->mmaped + obj->arena_data_off, obj->arena_data,
5690 						obj->arena_data_sz);
5691 					zfree(&obj->arena_data);
5692 				}
5693 			}
5694 			if (map->init_slots_sz && map->def.type != BPF_MAP_TYPE_PROG_ARRAY) {
5695 				err = init_map_in_map_slots(obj, map);
5696 				if (err < 0)
5697 					goto err_out;
5698 			}
5699 		}
5700 
5701 		if (map->pin_path && !map->pinned) {
5702 			err = bpf_map__pin(map, NULL);
5703 			if (err) {
5704 				if (!retried && err == -EEXIST) {
5705 					retried = true;
5706 					goto retry;
5707 				}
5708 				pr_warn("map '%s': failed to auto-pin at '%s': %s\n",
5709 					map->name, map->pin_path, errstr(err));
5710 				goto err_out;
5711 			}
5712 		}
5713 	}
5714 
5715 	return 0;
5716 
5717 err_out:
5718 	pr_warn("map '%s': failed to create: %s\n", map->name, errstr(err));
5719 	pr_perm_msg(err);
5720 	for (j = 0; j < i; j++)
5721 		zclose(obj->maps[j].fd);
5722 	return err;
5723 }
5724 
5725 static bool bpf_core_is_flavor_sep(const char *s)
5726 {
5727 	/* check X___Y name pattern, where X and Y are not underscores */
5728 	return s[0] != '_' &&				      /* X */
5729 	       s[1] == '_' && s[2] == '_' && s[3] == '_' &&   /* ___ */
5730 	       s[4] != '_';				      /* Y */
5731 }
5732 
5733 /* Given 'some_struct_name___with_flavor' return the length of a name prefix
5734  * before last triple underscore. Struct name part after last triple
5735  * underscore is ignored by BPF CO-RE relocation during relocation matching.
5736  */
5737 size_t bpf_core_essential_name_len(const char *name)
5738 {
5739 	size_t n = strlen(name);
5740 	int i;
5741 
5742 	for (i = n - 5; i >= 0; i--) {
5743 		if (bpf_core_is_flavor_sep(name + i))
5744 			return i + 1;
5745 	}
5746 	return n;
5747 }
5748 
5749 void bpf_core_free_cands(struct bpf_core_cand_list *cands)
5750 {
5751 	if (!cands)
5752 		return;
5753 
5754 	free(cands->cands);
5755 	free(cands);
5756 }
5757 
5758 int bpf_core_add_cands(struct bpf_core_cand *local_cand,
5759 		       size_t local_essent_len,
5760 		       const struct btf *targ_btf,
5761 		       const char *targ_btf_name,
5762 		       int targ_start_id,
5763 		       struct bpf_core_cand_list *cands)
5764 {
5765 	struct bpf_core_cand *new_cands, *cand;
5766 	const struct btf_type *t, *local_t;
5767 	const char *targ_name, *local_name;
5768 	size_t targ_essent_len;
5769 	int n, i;
5770 
5771 	local_t = btf__type_by_id(local_cand->btf, local_cand->id);
5772 	local_name = btf__str_by_offset(local_cand->btf, local_t->name_off);
5773 
5774 	n = btf__type_cnt(targ_btf);
5775 	for (i = targ_start_id; i < n; i++) {
5776 		t = btf__type_by_id(targ_btf, i);
5777 		if (!btf_kind_core_compat(t, local_t))
5778 			continue;
5779 
5780 		targ_name = btf__name_by_offset(targ_btf, t->name_off);
5781 		if (str_is_empty(targ_name))
5782 			continue;
5783 
5784 		targ_essent_len = bpf_core_essential_name_len(targ_name);
5785 		if (targ_essent_len != local_essent_len)
5786 			continue;
5787 
5788 		if (strncmp(local_name, targ_name, local_essent_len) != 0)
5789 			continue;
5790 
5791 		pr_debug("CO-RE relocating [%d] %s %s: found target candidate [%d] %s %s in [%s]\n",
5792 			 local_cand->id, btf_kind_str(local_t),
5793 			 local_name, i, btf_kind_str(t), targ_name,
5794 			 targ_btf_name);
5795 		new_cands = libbpf_reallocarray(cands->cands, cands->len + 1,
5796 					      sizeof(*cands->cands));
5797 		if (!new_cands)
5798 			return -ENOMEM;
5799 
5800 		cand = &new_cands[cands->len];
5801 		cand->btf = targ_btf;
5802 		cand->id = i;
5803 
5804 		cands->cands = new_cands;
5805 		cands->len++;
5806 	}
5807 	return 0;
5808 }
5809 
5810 static int load_module_btfs(struct bpf_object *obj)
5811 {
5812 	struct bpf_btf_info info;
5813 	struct module_btf *mod_btf;
5814 	struct btf *btf;
5815 	char name[64];
5816 	__u32 id = 0, len;
5817 	int err, fd;
5818 
5819 	if (obj->btf_modules_loaded)
5820 		return 0;
5821 
5822 	if (obj->gen_loader)
5823 		return 0;
5824 
5825 	/* don't do this again, even if we find no module BTFs */
5826 	obj->btf_modules_loaded = true;
5827 
5828 	/* kernel too old to support module BTFs */
5829 	if (!kernel_supports(obj, FEAT_MODULE_BTF))
5830 		return 0;
5831 
5832 	while (true) {
5833 		err = bpf_btf_get_next_id(id, &id);
5834 		if (err && errno == ENOENT)
5835 			return 0;
5836 		if (err && errno == EPERM) {
5837 			pr_debug("skipping module BTFs loading, missing privileges\n");
5838 			return 0;
5839 		}
5840 		if (err) {
5841 			err = -errno;
5842 			pr_warn("failed to iterate BTF objects: %s\n", errstr(err));
5843 			return err;
5844 		}
5845 
5846 		fd = bpf_btf_get_fd_by_id(id);
5847 		if (fd < 0) {
5848 			if (errno == ENOENT)
5849 				continue; /* expected race: BTF was unloaded */
5850 			err = -errno;
5851 			pr_warn("failed to get BTF object #%d FD: %s\n", id, errstr(err));
5852 			return err;
5853 		}
5854 
5855 		len = sizeof(info);
5856 		memset(&info, 0, sizeof(info));
5857 		info.name = ptr_to_u64(name);
5858 		info.name_len = sizeof(name);
5859 
5860 		btf = NULL;
5861 		err = bpf_btf_get_info_by_fd(fd, &info, &len);
5862 		if (err) {
5863 			err = -errno;
5864 			pr_warn("failed to get BTF object #%d info: %s\n", id, errstr(err));
5865 			break;
5866 		}
5867 
5868 		/* ignore non-module BTFs */
5869 		if (!info.kernel_btf || strcmp(name, "vmlinux") == 0) {
5870 			close(fd);
5871 			continue;
5872 		}
5873 
5874 		btf = btf_get_from_fd(fd, obj->btf_vmlinux);
5875 		err = libbpf_get_error(btf);
5876 		if (err) {
5877 			pr_warn("failed to load module [%s]'s BTF object #%d: %s\n",
5878 				name, id, errstr(err));
5879 			break;
5880 		}
5881 
5882 		err = libbpf_ensure_mem((void **)&obj->btf_modules, &obj->btf_module_cap,
5883 					sizeof(*obj->btf_modules), obj->btf_module_cnt + 1);
5884 		if (err)
5885 			break;
5886 
5887 		mod_btf = &obj->btf_modules[obj->btf_module_cnt];
5888 
5889 		mod_btf->btf = btf;
5890 		mod_btf->id = id;
5891 		mod_btf->fd = fd;
5892 		mod_btf->name = strdup(name);
5893 		if (!mod_btf->name) {
5894 			err = -ENOMEM;
5895 			break;
5896 		}
5897 		obj->btf_module_cnt++;
5898 	}
5899 
5900 	if (err) {
5901 		btf__free(btf);
5902 		close(fd);
5903 	}
5904 	return err;
5905 }
5906 
5907 static struct bpf_core_cand_list *
5908 bpf_core_find_cands(struct bpf_object *obj, const struct btf *local_btf, __u32 local_type_id)
5909 {
5910 	struct bpf_core_cand local_cand = {};
5911 	struct bpf_core_cand_list *cands;
5912 	const struct btf *main_btf;
5913 	const struct btf_type *local_t;
5914 	const char *local_name;
5915 	size_t local_essent_len;
5916 	int err, i;
5917 
5918 	local_cand.btf = local_btf;
5919 	local_cand.id = local_type_id;
5920 	local_t = btf__type_by_id(local_btf, local_type_id);
5921 	if (!local_t)
5922 		return ERR_PTR(-EINVAL);
5923 
5924 	local_name = btf__name_by_offset(local_btf, local_t->name_off);
5925 	if (str_is_empty(local_name))
5926 		return ERR_PTR(-EINVAL);
5927 	local_essent_len = bpf_core_essential_name_len(local_name);
5928 
5929 	cands = calloc(1, sizeof(*cands));
5930 	if (!cands)
5931 		return ERR_PTR(-ENOMEM);
5932 
5933 	/* Attempt to find target candidates in vmlinux BTF first */
5934 	main_btf = obj->btf_vmlinux_override ?: obj->btf_vmlinux;
5935 	err = bpf_core_add_cands(&local_cand, local_essent_len, main_btf, "vmlinux", 1, cands);
5936 	if (err)
5937 		goto err_out;
5938 
5939 	/* if vmlinux BTF has any candidate, don't got for module BTFs */
5940 	if (cands->len)
5941 		return cands;
5942 
5943 	/* if vmlinux BTF was overridden, don't attempt to load module BTFs */
5944 	if (obj->btf_vmlinux_override)
5945 		return cands;
5946 
5947 	/* now look through module BTFs, trying to still find candidates */
5948 	err = load_module_btfs(obj);
5949 	if (err)
5950 		goto err_out;
5951 
5952 	for (i = 0; i < obj->btf_module_cnt; i++) {
5953 		err = bpf_core_add_cands(&local_cand, local_essent_len,
5954 					 obj->btf_modules[i].btf,
5955 					 obj->btf_modules[i].name,
5956 					 btf__type_cnt(obj->btf_vmlinux),
5957 					 cands);
5958 		if (err)
5959 			goto err_out;
5960 	}
5961 
5962 	return cands;
5963 err_out:
5964 	bpf_core_free_cands(cands);
5965 	return ERR_PTR(err);
5966 }
5967 
5968 /* Check local and target types for compatibility. This check is used for
5969  * type-based CO-RE relocations and follow slightly different rules than
5970  * field-based relocations. This function assumes that root types were already
5971  * checked for name match. Beyond that initial root-level name check, names
5972  * are completely ignored. Compatibility rules are as follows:
5973  *   - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs are considered compatible, but
5974  *     kind should match for local and target types (i.e., STRUCT is not
5975  *     compatible with UNION);
5976  *   - for ENUMs, the size is ignored;
5977  *   - for INT, size and signedness are ignored;
5978  *   - for ARRAY, dimensionality is ignored, element types are checked for
5979  *     compatibility recursively;
5980  *   - CONST/VOLATILE/RESTRICT modifiers are ignored;
5981  *   - TYPEDEFs/PTRs are compatible if types they pointing to are compatible;
5982  *   - FUNC_PROTOs are compatible if they have compatible signature: same
5983  *     number of input args and compatible return and argument types.
5984  * These rules are not set in stone and probably will be adjusted as we get
5985  * more experience with using BPF CO-RE relocations.
5986  */
5987 int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
5988 			      const struct btf *targ_btf, __u32 targ_id)
5989 {
5990 	return __bpf_core_types_are_compat(local_btf, local_id, targ_btf, targ_id, 32);
5991 }
5992 
5993 int bpf_core_types_match(const struct btf *local_btf, __u32 local_id,
5994 			 const struct btf *targ_btf, __u32 targ_id)
5995 {
5996 	return __bpf_core_types_match(local_btf, local_id, targ_btf, targ_id, false, 32);
5997 }
5998 
5999 static size_t bpf_core_hash_fn(const long key, void *ctx)
6000 {
6001 	return key;
6002 }
6003 
6004 static bool bpf_core_equal_fn(const long k1, const long k2, void *ctx)
6005 {
6006 	return k1 == k2;
6007 }
6008 
6009 static int record_relo_core(struct bpf_program *prog,
6010 			    const struct bpf_core_relo *core_relo, int insn_idx)
6011 {
6012 	struct reloc_desc *relos, *relo;
6013 
6014 	relos = libbpf_reallocarray(prog->reloc_desc,
6015 				    prog->nr_reloc + 1, sizeof(*relos));
6016 	if (!relos)
6017 		return -ENOMEM;
6018 	relo = &relos[prog->nr_reloc];
6019 	relo->type = RELO_CORE;
6020 	relo->insn_idx = insn_idx;
6021 	relo->core_relo = core_relo;
6022 	prog->reloc_desc = relos;
6023 	prog->nr_reloc++;
6024 	return 0;
6025 }
6026 
6027 static const struct bpf_core_relo *find_relo_core(struct bpf_program *prog, int insn_idx)
6028 {
6029 	struct reloc_desc *relo;
6030 	int i;
6031 
6032 	for (i = 0; i < prog->nr_reloc; i++) {
6033 		relo = &prog->reloc_desc[i];
6034 		if (relo->type != RELO_CORE || relo->insn_idx != insn_idx)
6035 			continue;
6036 
6037 		return relo->core_relo;
6038 	}
6039 
6040 	return NULL;
6041 }
6042 
6043 static int bpf_core_resolve_relo(struct bpf_program *prog,
6044 				 const struct bpf_core_relo *relo,
6045 				 int relo_idx,
6046 				 const struct btf *local_btf,
6047 				 struct hashmap *cand_cache,
6048 				 struct bpf_core_relo_res *targ_res)
6049 {
6050 	struct bpf_core_spec specs_scratch[3] = {};
6051 	struct bpf_core_cand_list *cands = NULL;
6052 	const char *prog_name = prog->name;
6053 	const struct btf_type *local_type;
6054 	const char *local_name;
6055 	__u32 local_id = relo->type_id;
6056 	int err;
6057 
6058 	local_type = btf__type_by_id(local_btf, local_id);
6059 	if (!local_type)
6060 		return -EINVAL;
6061 
6062 	local_name = btf__name_by_offset(local_btf, local_type->name_off);
6063 	if (!local_name)
6064 		return -EINVAL;
6065 
6066 	if (relo->kind != BPF_CORE_TYPE_ID_LOCAL &&
6067 	    !hashmap__find(cand_cache, local_id, &cands)) {
6068 		cands = bpf_core_find_cands(prog->obj, local_btf, local_id);
6069 		if (IS_ERR(cands)) {
6070 			pr_warn("prog '%s': relo #%d: target candidate search failed for [%d] %s %s: %ld\n",
6071 				prog_name, relo_idx, local_id, btf_kind_str(local_type),
6072 				local_name, PTR_ERR(cands));
6073 			return PTR_ERR(cands);
6074 		}
6075 		err = hashmap__set(cand_cache, local_id, cands, NULL, NULL);
6076 		if (err) {
6077 			bpf_core_free_cands(cands);
6078 			return err;
6079 		}
6080 	}
6081 
6082 	return bpf_core_calc_relo_insn(prog_name, relo, relo_idx, local_btf, cands, specs_scratch,
6083 				       targ_res);
6084 }
6085 
6086 static int
6087 bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
6088 {
6089 	const struct btf_ext_info_sec *sec;
6090 	struct bpf_core_relo_res targ_res;
6091 	const struct bpf_core_relo *rec;
6092 	const struct btf_ext_info *seg;
6093 	struct hashmap_entry *entry;
6094 	struct hashmap *cand_cache = NULL;
6095 	struct bpf_program *prog;
6096 	struct bpf_insn *insn;
6097 	const char *sec_name;
6098 	int i, err = 0, insn_idx, sec_idx, sec_num;
6099 
6100 	if (obj->btf_ext->core_relo_info.len == 0)
6101 		return 0;
6102 
6103 	if (targ_btf_path) {
6104 		obj->btf_vmlinux_override = btf__parse(targ_btf_path, NULL);
6105 		err = libbpf_get_error(obj->btf_vmlinux_override);
6106 		if (err) {
6107 			pr_warn("failed to parse target BTF: %s\n", errstr(err));
6108 			return err;
6109 		}
6110 	}
6111 
6112 	cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
6113 	if (IS_ERR(cand_cache)) {
6114 		err = PTR_ERR(cand_cache);
6115 		goto out;
6116 	}
6117 
6118 	seg = &obj->btf_ext->core_relo_info;
6119 	sec_num = 0;
6120 	for_each_btf_ext_sec(seg, sec) {
6121 		sec_idx = seg->sec_idxs[sec_num];
6122 		sec_num++;
6123 
6124 		sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
6125 		if (str_is_empty(sec_name)) {
6126 			err = -EINVAL;
6127 			goto out;
6128 		}
6129 
6130 		pr_debug("sec '%s': found %d CO-RE relocations\n", sec_name, sec->num_info);
6131 
6132 		for_each_btf_ext_rec(seg, sec, i, rec) {
6133 			if (rec->insn_off % BPF_INSN_SZ)
6134 				return -EINVAL;
6135 			insn_idx = rec->insn_off / BPF_INSN_SZ;
6136 			prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
6137 			if (!prog) {
6138 				/* When __weak subprog is "overridden" by another instance
6139 				 * of the subprog from a different object file, linker still
6140 				 * appends all the .BTF.ext info that used to belong to that
6141 				 * eliminated subprogram.
6142 				 * This is similar to what x86-64 linker does for relocations.
6143 				 * So just ignore such relocations just like we ignore
6144 				 * subprog instructions when discovering subprograms.
6145 				 */
6146 				pr_debug("sec '%s': skipping CO-RE relocation #%d for insn #%d belonging to eliminated weak subprogram\n",
6147 					 sec_name, i, insn_idx);
6148 				continue;
6149 			}
6150 			/* no need to apply CO-RE relocation if the program is
6151 			 * not going to be loaded
6152 			 */
6153 			if (!prog->autoload)
6154 				continue;
6155 
6156 			/* adjust insn_idx from section frame of reference to the local
6157 			 * program's frame of reference; (sub-)program code is not yet
6158 			 * relocated, so it's enough to just subtract in-section offset
6159 			 */
6160 			insn_idx = insn_idx - prog->sec_insn_off;
6161 			if (insn_idx >= prog->insns_cnt)
6162 				return -EINVAL;
6163 			insn = &prog->insns[insn_idx];
6164 
6165 			err = record_relo_core(prog, rec, insn_idx);
6166 			if (err) {
6167 				pr_warn("prog '%s': relo #%d: failed to record relocation: %s\n",
6168 					prog->name, i, errstr(err));
6169 				goto out;
6170 			}
6171 
6172 			if (prog->obj->gen_loader)
6173 				continue;
6174 
6175 			err = bpf_core_resolve_relo(prog, rec, i, obj->btf, cand_cache, &targ_res);
6176 			if (err) {
6177 				pr_warn("prog '%s': relo #%d: failed to relocate: %s\n",
6178 					prog->name, i, errstr(err));
6179 				goto out;
6180 			}
6181 
6182 			err = bpf_core_patch_insn(prog->name, insn, insn_idx, rec, i, &targ_res);
6183 			if (err) {
6184 				pr_warn("prog '%s': relo #%d: failed to patch insn #%u: %s\n",
6185 					prog->name, i, insn_idx, errstr(err));
6186 				goto out;
6187 			}
6188 		}
6189 	}
6190 
6191 out:
6192 	/* obj->btf_vmlinux and module BTFs are freed after object load */
6193 	btf__free(obj->btf_vmlinux_override);
6194 	obj->btf_vmlinux_override = NULL;
6195 
6196 	if (!IS_ERR_OR_NULL(cand_cache)) {
6197 		hashmap__for_each_entry(cand_cache, entry, i) {
6198 			bpf_core_free_cands(entry->pvalue);
6199 		}
6200 		hashmap__free(cand_cache);
6201 	}
6202 	return err;
6203 }
6204 
6205 /* base map load ldimm64 special constant, used also for log fixup logic */
6206 #define POISON_LDIMM64_MAP_BASE 2001000000
6207 #define POISON_LDIMM64_MAP_PFX "200100"
6208 
6209 static void poison_map_ldimm64(struct bpf_program *prog, int relo_idx,
6210 			       int insn_idx, struct bpf_insn *insn,
6211 			       int map_idx, const struct bpf_map *map)
6212 {
6213 	int i;
6214 
6215 	pr_debug("prog '%s': relo #%d: poisoning insn #%d that loads map #%d '%s'\n",
6216 		 prog->name, relo_idx, insn_idx, map_idx, map->name);
6217 
6218 	/* we turn single ldimm64 into two identical invalid calls */
6219 	for (i = 0; i < 2; i++) {
6220 		insn->code = BPF_JMP | BPF_CALL;
6221 		insn->dst_reg = 0;
6222 		insn->src_reg = 0;
6223 		insn->off = 0;
6224 		/* if this instruction is reachable (not a dead code),
6225 		 * verifier will complain with something like:
6226 		 * invalid func unknown#2001000123
6227 		 * where lower 123 is map index into obj->maps[] array
6228 		 */
6229 		insn->imm = POISON_LDIMM64_MAP_BASE + map_idx;
6230 
6231 		insn++;
6232 	}
6233 }
6234 
6235 /* unresolved kfunc call special constant, used also for log fixup logic */
6236 #define POISON_CALL_KFUNC_BASE 2002000000
6237 #define POISON_CALL_KFUNC_PFX "2002"
6238 
6239 static void poison_kfunc_call(struct bpf_program *prog, int relo_idx,
6240 			      int insn_idx, struct bpf_insn *insn,
6241 			      int ext_idx, const struct extern_desc *ext)
6242 {
6243 	pr_debug("prog '%s': relo #%d: poisoning insn #%d that calls kfunc '%s'\n",
6244 		 prog->name, relo_idx, insn_idx, ext->name);
6245 
6246 	/* we turn kfunc call into invalid helper call with identifiable constant */
6247 	insn->code = BPF_JMP | BPF_CALL;
6248 	insn->dst_reg = 0;
6249 	insn->src_reg = 0;
6250 	insn->off = 0;
6251 	/* if this instruction is reachable (not a dead code),
6252 	 * verifier will complain with something like:
6253 	 * invalid func unknown#2001000123
6254 	 * where lower 123 is extern index into obj->externs[] array
6255 	 */
6256 	insn->imm = POISON_CALL_KFUNC_BASE + ext_idx;
6257 }
6258 
6259 static int find_jt_map(struct bpf_object *obj, struct bpf_program *prog, unsigned int sym_off)
6260 {
6261 	size_t i;
6262 
6263 	for (i = 0; i < obj->jumptable_map_cnt; i++) {
6264 		/*
6265 		 * This might happen that same offset is used for two different
6266 		 * programs (as jump tables can be the same). However, for
6267 		 * different programs different maps should be created.
6268 		 */
6269 		if (obj->jumptable_maps[i].sym_off == sym_off &&
6270 		    obj->jumptable_maps[i].prog == prog)
6271 			return obj->jumptable_maps[i].fd;
6272 	}
6273 
6274 	return -ENOENT;
6275 }
6276 
6277 static int add_jt_map(struct bpf_object *obj, struct bpf_program *prog, unsigned int sym_off, int map_fd)
6278 {
6279 	size_t cnt = obj->jumptable_map_cnt;
6280 	size_t size = sizeof(obj->jumptable_maps[0]);
6281 	void *tmp;
6282 
6283 	tmp = libbpf_reallocarray(obj->jumptable_maps, cnt + 1, size);
6284 	if (!tmp)
6285 		return -ENOMEM;
6286 
6287 	obj->jumptable_maps = tmp;
6288 	obj->jumptable_maps[cnt].prog = prog;
6289 	obj->jumptable_maps[cnt].sym_off = sym_off;
6290 	obj->jumptable_maps[cnt].fd = map_fd;
6291 	obj->jumptable_map_cnt++;
6292 
6293 	return 0;
6294 }
6295 
6296 static int find_subprog_idx(struct bpf_program *prog, int insn_idx)
6297 {
6298 	int i;
6299 
6300 	for (i = prog->subprog_cnt - 1; i >= 0; i--) {
6301 		if (insn_idx >= prog->subprogs[i].sub_insn_off)
6302 			return i;
6303 	}
6304 
6305 	return -1;
6306 }
6307 
6308 static int create_jt_map(struct bpf_object *obj, struct bpf_program *prog, struct reloc_desc *relo)
6309 {
6310 	const __u32 jt_entry_size = 8;
6311 	unsigned int sym_off = relo->sym_off;
6312 	int jt_size = relo->sym_size;
6313 	__u32 max_entries = jt_size / jt_entry_size;
6314 	__u32 value_size = sizeof(struct bpf_insn_array_value);
6315 	struct bpf_insn_array_value val = {};
6316 	int subprog_idx;
6317 	int map_fd, err;
6318 	__u64 insn_off;
6319 	__u64 *jt;
6320 	__u32 i;
6321 
6322 	map_fd = find_jt_map(obj, prog, sym_off);
6323 	if (map_fd >= 0)
6324 		return map_fd;
6325 
6326 	if (sym_off % jt_entry_size) {
6327 		pr_warn("map '.jumptables': jumptable start %u should be multiple of %u\n",
6328 			sym_off, jt_entry_size);
6329 		return -EINVAL;
6330 	}
6331 
6332 	if (jt_size % jt_entry_size) {
6333 		pr_warn("map '.jumptables': jumptable size %d should be multiple of %u\n",
6334 			jt_size, jt_entry_size);
6335 		return -EINVAL;
6336 	}
6337 
6338 	map_fd = bpf_map_create(BPF_MAP_TYPE_INSN_ARRAY, ".jumptables",
6339 				4, value_size, max_entries, NULL);
6340 	if (map_fd < 0)
6341 		return map_fd;
6342 
6343 	if (!obj->jumptables_data) {
6344 		pr_warn("map '.jumptables': ELF file is missing jump table data\n");
6345 		err = -EINVAL;
6346 		goto err_close;
6347 	}
6348 	if (sym_off + jt_size > obj->jumptables_data_sz) {
6349 		pr_warn("map '.jumptables': jumptables_data size is %zd, trying to access %d\n",
6350 			obj->jumptables_data_sz, sym_off + jt_size);
6351 		err = -EINVAL;
6352 		goto err_close;
6353 	}
6354 
6355 	subprog_idx = -1; /* main program */
6356 	if (relo->insn_idx < 0 || relo->insn_idx >= prog->insns_cnt) {
6357 		pr_warn("map '.jumptables': invalid instruction index %d\n", relo->insn_idx);
6358 		err = -EINVAL;
6359 		goto err_close;
6360 	}
6361 	if (prog->subprogs)
6362 		subprog_idx = find_subprog_idx(prog, relo->insn_idx);
6363 
6364 	jt = (__u64 *)(obj->jumptables_data + sym_off);
6365 	for (i = 0; i < max_entries; i++) {
6366 		/*
6367 		 * The offset should be made to be relative to the beginning of
6368 		 * the main function, not the subfunction.
6369 		 */
6370 		insn_off = jt[i]/sizeof(struct bpf_insn);
6371 		if (subprog_idx >= 0) {
6372 			insn_off -= prog->subprogs[subprog_idx].sec_insn_off;
6373 			insn_off += prog->subprogs[subprog_idx].sub_insn_off;
6374 		} else {
6375 			insn_off -= prog->sec_insn_off;
6376 		}
6377 
6378 		/*
6379 		 * LLVM-generated jump tables contain u64 records, however
6380 		 * should contain values that fit in u32.
6381 		 */
6382 		if (insn_off > UINT32_MAX) {
6383 			pr_warn("map '.jumptables': invalid jump table value 0x%llx at offset %u\n",
6384 				(long long)jt[i], sym_off + i * jt_entry_size);
6385 			err = -EINVAL;
6386 			goto err_close;
6387 		}
6388 
6389 		val.orig_off = insn_off;
6390 		err = bpf_map_update_elem(map_fd, &i, &val, 0);
6391 		if (err)
6392 			goto err_close;
6393 	}
6394 
6395 	err = bpf_map_freeze(map_fd);
6396 	if (err)
6397 		goto err_close;
6398 
6399 	err = add_jt_map(obj, prog, sym_off, map_fd);
6400 	if (err)
6401 		goto err_close;
6402 
6403 	return map_fd;
6404 
6405 err_close:
6406 	close(map_fd);
6407 	return err;
6408 }
6409 
6410 /* Relocate data references within program code:
6411  *  - map references;
6412  *  - global variable references;
6413  *  - extern references.
6414  */
6415 static int
6416 bpf_object__relocate_data(struct bpf_object *obj, struct bpf_program *prog)
6417 {
6418 	int i;
6419 
6420 	for (i = 0; i < prog->nr_reloc; i++) {
6421 		struct reloc_desc *relo = &prog->reloc_desc[i];
6422 		struct bpf_insn *insn = &prog->insns[relo->insn_idx];
6423 		const struct bpf_map *map;
6424 		struct extern_desc *ext;
6425 
6426 		switch (relo->type) {
6427 		case RELO_LD64:
6428 			map = &obj->maps[relo->map_idx];
6429 			if (obj->gen_loader) {
6430 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX;
6431 				insn[0].imm = relo->map_idx;
6432 			} else if (map->autocreate) {
6433 				insn[0].src_reg = BPF_PSEUDO_MAP_FD;
6434 				insn[0].imm = map->fd;
6435 			} else {
6436 				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
6437 						   relo->map_idx, map);
6438 			}
6439 			break;
6440 		case RELO_DATA:
6441 			map = &obj->maps[relo->map_idx];
6442 			insn[1].imm = insn[0].imm + relo->sym_off;
6443 
6444 			if (relo->map_idx == obj->arena_map_idx)
6445 				insn[1].imm += obj->arena_data_off;
6446 
6447 			if (obj->gen_loader) {
6448 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
6449 				insn[0].imm = relo->map_idx;
6450 			} else if (map->autocreate) {
6451 				insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6452 				insn[0].imm = map->fd;
6453 			} else {
6454 				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
6455 						   relo->map_idx, map);
6456 			}
6457 			break;
6458 		case RELO_EXTERN_LD64:
6459 			ext = &obj->externs[relo->ext_idx];
6460 			if (ext->type == EXT_KCFG) {
6461 				if (obj->gen_loader) {
6462 					insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
6463 					insn[0].imm = obj->kconfig_map_idx;
6464 				} else {
6465 					insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6466 					insn[0].imm = obj->maps[obj->kconfig_map_idx].fd;
6467 				}
6468 				insn[1].imm = ext->kcfg.data_off;
6469 			} else /* EXT_KSYM */ {
6470 				if (ext->ksym.type_id && ext->is_set) { /* typed ksyms */
6471 					insn[0].src_reg = BPF_PSEUDO_BTF_ID;
6472 					insn[0].imm = ext->ksym.kernel_btf_id;
6473 					insn[1].imm = ext->ksym.kernel_btf_obj_fd;
6474 				} else { /* typeless ksyms or unresolved typed ksyms */
6475 					insn[0].imm = (__u32)ext->ksym.addr;
6476 					insn[1].imm = ext->ksym.addr >> 32;
6477 				}
6478 			}
6479 			break;
6480 		case RELO_EXTERN_CALL:
6481 			ext = &obj->externs[relo->ext_idx];
6482 			insn[0].src_reg = BPF_PSEUDO_KFUNC_CALL;
6483 			if (ext->is_set) {
6484 				insn[0].imm = ext->ksym.kernel_btf_id;
6485 				insn[0].off = ext->ksym.btf_fd_idx;
6486 			} else { /* unresolved weak kfunc call */
6487 				poison_kfunc_call(prog, i, relo->insn_idx, insn,
6488 						  relo->ext_idx, ext);
6489 			}
6490 			break;
6491 		case RELO_SUBPROG_ADDR:
6492 			if (insn[0].src_reg != BPF_PSEUDO_FUNC) {
6493 				pr_warn("prog '%s': relo #%d: bad insn\n",
6494 					prog->name, i);
6495 				return -EINVAL;
6496 			}
6497 			/* handled already */
6498 			break;
6499 		case RELO_CALL:
6500 			/* handled already */
6501 			break;
6502 		case RELO_CORE:
6503 			/* will be handled by bpf_program_record_relos() */
6504 			break;
6505 		case RELO_INSN_ARRAY: {
6506 			int map_fd;
6507 
6508 			map_fd = create_jt_map(obj, prog, relo);
6509 			if (map_fd < 0) {
6510 				pr_warn("prog '%s': relo #%d: can't create jump table: sym_off %u\n",
6511 					prog->name, i, relo->sym_off);
6512 				return map_fd;
6513 			}
6514 			insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6515 			insn->imm = map_fd;
6516 			insn->off = 0;
6517 		}
6518 			break;
6519 		default:
6520 			pr_warn("prog '%s': relo #%d: bad relo type %d\n",
6521 				prog->name, i, relo->type);
6522 			return -EINVAL;
6523 		}
6524 	}
6525 
6526 	return 0;
6527 }
6528 
6529 static int adjust_prog_btf_ext_info(const struct bpf_object *obj,
6530 				    const struct bpf_program *prog,
6531 				    const struct btf_ext_info *ext_info,
6532 				    void **prog_info, __u32 *prog_rec_cnt,
6533 				    __u32 *prog_rec_sz)
6534 {
6535 	void *copy_start = NULL, *copy_end = NULL;
6536 	void *rec, *rec_end, *new_prog_info;
6537 	const struct btf_ext_info_sec *sec;
6538 	size_t old_sz, new_sz;
6539 	int i, sec_num, sec_idx, off_adj;
6540 
6541 	sec_num = 0;
6542 	for_each_btf_ext_sec(ext_info, sec) {
6543 		sec_idx = ext_info->sec_idxs[sec_num];
6544 		sec_num++;
6545 		if (prog->sec_idx != sec_idx)
6546 			continue;
6547 
6548 		for_each_btf_ext_rec(ext_info, sec, i, rec) {
6549 			__u32 insn_off = *(__u32 *)rec / BPF_INSN_SZ;
6550 
6551 			if (insn_off < prog->sec_insn_off)
6552 				continue;
6553 			if (insn_off >= prog->sec_insn_off + prog->sec_insn_cnt)
6554 				break;
6555 
6556 			if (!copy_start)
6557 				copy_start = rec;
6558 			copy_end = rec + ext_info->rec_size;
6559 		}
6560 
6561 		if (!copy_start)
6562 			return -ENOENT;
6563 
6564 		/* append func/line info of a given (sub-)program to the main
6565 		 * program func/line info
6566 		 */
6567 		old_sz = (size_t)(*prog_rec_cnt) * ext_info->rec_size;
6568 		new_sz = old_sz + (copy_end - copy_start);
6569 		new_prog_info = realloc(*prog_info, new_sz);
6570 		if (!new_prog_info)
6571 			return -ENOMEM;
6572 		*prog_info = new_prog_info;
6573 		*prog_rec_cnt = new_sz / ext_info->rec_size;
6574 		memcpy(new_prog_info + old_sz, copy_start, copy_end - copy_start);
6575 
6576 		/* Kernel instruction offsets are in units of 8-byte
6577 		 * instructions, while .BTF.ext instruction offsets generated
6578 		 * by Clang are in units of bytes. So convert Clang offsets
6579 		 * into kernel offsets and adjust offset according to program
6580 		 * relocated position.
6581 		 */
6582 		off_adj = prog->sub_insn_off - prog->sec_insn_off;
6583 		rec = new_prog_info + old_sz;
6584 		rec_end = new_prog_info + new_sz;
6585 		for (; rec < rec_end; rec += ext_info->rec_size) {
6586 			__u32 *insn_off = rec;
6587 
6588 			*insn_off = *insn_off / BPF_INSN_SZ + off_adj;
6589 		}
6590 		*prog_rec_sz = ext_info->rec_size;
6591 		return 0;
6592 	}
6593 
6594 	return -ENOENT;
6595 }
6596 
6597 static int
6598 reloc_prog_func_and_line_info(const struct bpf_object *obj,
6599 			      struct bpf_program *main_prog,
6600 			      const struct bpf_program *prog)
6601 {
6602 	int err;
6603 
6604 	/* no .BTF.ext relocation if .BTF.ext is missing or kernel doesn't
6605 	 * support func/line info
6606 	 */
6607 	if (!obj->btf_ext || !kernel_supports(obj, FEAT_BTF_FUNC))
6608 		return 0;
6609 
6610 	/* only attempt func info relocation if main program's func_info
6611 	 * relocation was successful
6612 	 */
6613 	if (main_prog != prog && !main_prog->func_info)
6614 		goto line_info;
6615 
6616 	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->func_info,
6617 				       &main_prog->func_info,
6618 				       &main_prog->func_info_cnt,
6619 				       &main_prog->func_info_rec_size);
6620 	if (err) {
6621 		if (err != -ENOENT) {
6622 			pr_warn("prog '%s': error relocating .BTF.ext function info: %s\n",
6623 				prog->name, errstr(err));
6624 			return err;
6625 		}
6626 		if (main_prog->func_info) {
6627 			/*
6628 			 * Some info has already been found but has problem
6629 			 * in the last btf_ext reloc. Must have to error out.
6630 			 */
6631 			pr_warn("prog '%s': missing .BTF.ext function info.\n", prog->name);
6632 			return err;
6633 		}
6634 		/* Have problem loading the very first info. Ignore the rest. */
6635 		pr_warn("prog '%s': missing .BTF.ext function info for the main program, skipping all of .BTF.ext func info.\n",
6636 			prog->name);
6637 	}
6638 
6639 line_info:
6640 	/* don't relocate line info if main program's relocation failed */
6641 	if (main_prog != prog && !main_prog->line_info)
6642 		return 0;
6643 
6644 	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->line_info,
6645 				       &main_prog->line_info,
6646 				       &main_prog->line_info_cnt,
6647 				       &main_prog->line_info_rec_size);
6648 	if (err) {
6649 		if (err != -ENOENT) {
6650 			pr_warn("prog '%s': error relocating .BTF.ext line info: %s\n",
6651 				prog->name, errstr(err));
6652 			return err;
6653 		}
6654 		if (main_prog->line_info) {
6655 			/*
6656 			 * Some info has already been found but has problem
6657 			 * in the last btf_ext reloc. Must have to error out.
6658 			 */
6659 			pr_warn("prog '%s': missing .BTF.ext line info.\n", prog->name);
6660 			return err;
6661 		}
6662 		/* Have problem loading the very first info. Ignore the rest. */
6663 		pr_warn("prog '%s': missing .BTF.ext line info for the main program, skipping all of .BTF.ext line info.\n",
6664 			prog->name);
6665 	}
6666 	return 0;
6667 }
6668 
6669 static int cmp_relo_by_insn_idx(const void *key, const void *elem)
6670 {
6671 	size_t insn_idx = *(const size_t *)key;
6672 	const struct reloc_desc *relo = elem;
6673 
6674 	if (insn_idx == relo->insn_idx)
6675 		return 0;
6676 	return insn_idx < relo->insn_idx ? -1 : 1;
6677 }
6678 
6679 static struct reloc_desc *find_prog_insn_relo(const struct bpf_program *prog, size_t insn_idx)
6680 {
6681 	if (!prog->nr_reloc)
6682 		return NULL;
6683 	return bsearch(&insn_idx, prog->reloc_desc, prog->nr_reloc,
6684 		       sizeof(*prog->reloc_desc), cmp_relo_by_insn_idx);
6685 }
6686 
6687 static int append_subprog_relos(struct bpf_program *main_prog, struct bpf_program *subprog)
6688 {
6689 	int new_cnt = main_prog->nr_reloc + subprog->nr_reloc;
6690 	struct reloc_desc *relos;
6691 	int i;
6692 
6693 	if (main_prog == subprog)
6694 		return 0;
6695 	relos = libbpf_reallocarray(main_prog->reloc_desc, new_cnt, sizeof(*relos));
6696 	/* if new count is zero, reallocarray can return a valid NULL result;
6697 	 * in this case the previous pointer will be freed, so we *have to*
6698 	 * reassign old pointer to the new value (even if it's NULL)
6699 	 */
6700 	if (!relos && new_cnt)
6701 		return -ENOMEM;
6702 	if (subprog->nr_reloc)
6703 		memcpy(relos + main_prog->nr_reloc, subprog->reloc_desc,
6704 		       sizeof(*relos) * subprog->nr_reloc);
6705 
6706 	for (i = main_prog->nr_reloc; i < new_cnt; i++)
6707 		relos[i].insn_idx += subprog->sub_insn_off;
6708 	/* After insn_idx adjustment the 'relos' array is still sorted
6709 	 * by insn_idx and doesn't break bsearch.
6710 	 */
6711 	main_prog->reloc_desc = relos;
6712 	main_prog->nr_reloc = new_cnt;
6713 	return 0;
6714 }
6715 
6716 static int save_subprog_offsets(struct bpf_program *main_prog, struct bpf_program *subprog)
6717 {
6718 	size_t size = sizeof(main_prog->subprogs[0]);
6719 	int cnt = main_prog->subprog_cnt;
6720 	void *tmp;
6721 
6722 	tmp = libbpf_reallocarray(main_prog->subprogs, cnt + 1, size);
6723 	if (!tmp)
6724 		return -ENOMEM;
6725 
6726 	main_prog->subprogs = tmp;
6727 	main_prog->subprogs[cnt].sec_insn_off = subprog->sec_insn_off;
6728 	main_prog->subprogs[cnt].sub_insn_off = subprog->sub_insn_off;
6729 	main_prog->subprog_cnt++;
6730 
6731 	return 0;
6732 }
6733 
6734 static int
6735 bpf_object__append_subprog_code(struct bpf_object *obj, struct bpf_program *main_prog,
6736 				struct bpf_program *subprog)
6737 {
6738 	struct bpf_insn *insns;
6739 	size_t new_cnt;
6740 	int err;
6741 
6742 	subprog->sub_insn_off = main_prog->insns_cnt;
6743 
6744 	new_cnt = main_prog->insns_cnt + subprog->insns_cnt;
6745 	insns = libbpf_reallocarray(main_prog->insns, new_cnt, sizeof(*insns));
6746 	if (!insns) {
6747 		pr_warn("prog '%s': failed to realloc prog code\n", main_prog->name);
6748 		return -ENOMEM;
6749 	}
6750 	main_prog->insns = insns;
6751 	main_prog->insns_cnt = new_cnt;
6752 
6753 	memcpy(main_prog->insns + subprog->sub_insn_off, subprog->insns,
6754 	       subprog->insns_cnt * sizeof(*insns));
6755 
6756 	pr_debug("prog '%s': added %zu insns from sub-prog '%s'\n",
6757 		 main_prog->name, subprog->insns_cnt, subprog->name);
6758 
6759 	/* The subprog insns are now appended. Append its relos too. */
6760 	err = append_subprog_relos(main_prog, subprog);
6761 	if (err)
6762 		return err;
6763 
6764 	err = save_subprog_offsets(main_prog, subprog);
6765 	if (err) {
6766 		pr_warn("prog '%s': failed to add subprog offsets: %s\n",
6767 			main_prog->name, errstr(err));
6768 		return err;
6769 	}
6770 
6771 	return 0;
6772 }
6773 
6774 static int
6775 bpf_object__reloc_code(struct bpf_object *obj, struct bpf_program *main_prog,
6776 		       struct bpf_program *prog)
6777 {
6778 	size_t sub_insn_idx, insn_idx;
6779 	struct bpf_program *subprog;
6780 	struct reloc_desc *relo;
6781 	struct bpf_insn *insn;
6782 	int err;
6783 
6784 	err = reloc_prog_func_and_line_info(obj, main_prog, prog);
6785 	if (err)
6786 		return err;
6787 
6788 	for (insn_idx = 0; insn_idx < prog->sec_insn_cnt; insn_idx++) {
6789 		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6790 		if (!insn_is_subprog_call(insn) && !insn_is_pseudo_func(insn))
6791 			continue;
6792 
6793 		relo = find_prog_insn_relo(prog, insn_idx);
6794 		if (relo && relo->type == RELO_EXTERN_CALL)
6795 			/* kfunc relocations will be handled later
6796 			 * in bpf_object__relocate_data()
6797 			 */
6798 			continue;
6799 		if (relo && relo->type != RELO_CALL && relo->type != RELO_SUBPROG_ADDR) {
6800 			pr_warn("prog '%s': unexpected relo for insn #%zu, type %d\n",
6801 				prog->name, insn_idx, relo->type);
6802 			return -LIBBPF_ERRNO__RELOC;
6803 		}
6804 		if (relo) {
6805 			/* sub-program instruction index is a combination of
6806 			 * an offset of a symbol pointed to by relocation and
6807 			 * call instruction's imm field; for global functions,
6808 			 * call always has imm = -1, but for static functions
6809 			 * relocation is against STT_SECTION and insn->imm
6810 			 * points to a start of a static function
6811 			 *
6812 			 * for subprog addr relocation, the relo->sym_off + insn->imm is
6813 			 * the byte offset in the corresponding section.
6814 			 */
6815 			if (relo->type == RELO_CALL)
6816 				sub_insn_idx = relo->sym_off / BPF_INSN_SZ + insn->imm + 1;
6817 			else
6818 				sub_insn_idx = (relo->sym_off + insn->imm) / BPF_INSN_SZ;
6819 		} else if (insn_is_pseudo_func(insn)) {
6820 			/*
6821 			 * RELO_SUBPROG_ADDR relo is always emitted even if both
6822 			 * functions are in the same section, so it shouldn't reach here.
6823 			 */
6824 			pr_warn("prog '%s': missing subprog addr relo for insn #%zu\n",
6825 				prog->name, insn_idx);
6826 			return -LIBBPF_ERRNO__RELOC;
6827 		} else {
6828 			/* if subprogram call is to a static function within
6829 			 * the same ELF section, there won't be any relocation
6830 			 * emitted, but it also means there is no additional
6831 			 * offset necessary, insns->imm is relative to
6832 			 * instruction's original position within the section
6833 			 */
6834 			sub_insn_idx = prog->sec_insn_off + insn_idx + insn->imm + 1;
6835 		}
6836 
6837 		/* we enforce that sub-programs should be in .text section */
6838 		subprog = find_prog_by_sec_insn(obj, obj->efile.text_shndx, sub_insn_idx);
6839 		if (!subprog) {
6840 			pr_warn("prog '%s': no .text section found yet sub-program call exists\n",
6841 				prog->name);
6842 			return -LIBBPF_ERRNO__RELOC;
6843 		}
6844 
6845 		/* if it's the first call instruction calling into this
6846 		 * subprogram (meaning this subprog hasn't been processed
6847 		 * yet) within the context of current main program:
6848 		 *   - append it at the end of main program's instructions blog;
6849 		 *   - process is recursively, while current program is put on hold;
6850 		 *   - if that subprogram calls some other not yet processes
6851 		 *   subprogram, same thing will happen recursively until
6852 		 *   there are no more unprocesses subprograms left to append
6853 		 *   and relocate.
6854 		 */
6855 		if (subprog->sub_insn_off == 0) {
6856 			err = bpf_object__append_subprog_code(obj, main_prog, subprog);
6857 			if (err)
6858 				return err;
6859 			err = bpf_object__reloc_code(obj, main_prog, subprog);
6860 			if (err)
6861 				return err;
6862 		}
6863 
6864 		/* main_prog->insns memory could have been re-allocated, so
6865 		 * calculate pointer again
6866 		 */
6867 		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6868 		/* calculate correct instruction position within current main
6869 		 * prog; each main prog can have a different set of
6870 		 * subprograms appended (potentially in different order as
6871 		 * well), so position of any subprog can be different for
6872 		 * different main programs
6873 		 */
6874 		insn->imm = subprog->sub_insn_off - (prog->sub_insn_off + insn_idx) - 1;
6875 
6876 		pr_debug("prog '%s': insn #%zu relocated, imm %d points to subprog '%s' (now at %zu offset)\n",
6877 			 prog->name, insn_idx, insn->imm, subprog->name, subprog->sub_insn_off);
6878 	}
6879 
6880 	return 0;
6881 }
6882 
6883 /*
6884  * Relocate sub-program calls.
6885  *
6886  * Algorithm operates as follows. Each entry-point BPF program (referred to as
6887  * main prog) is processed separately. For each subprog (non-entry functions,
6888  * that can be called from either entry progs or other subprogs) gets their
6889  * sub_insn_off reset to zero. This serves as indicator that this subprogram
6890  * hasn't been yet appended and relocated within current main prog. Once its
6891  * relocated, sub_insn_off will point at the position within current main prog
6892  * where given subprog was appended. This will further be used to relocate all
6893  * the call instructions jumping into this subprog.
6894  *
6895  * We start with main program and process all call instructions. If the call
6896  * is into a subprog that hasn't been processed (i.e., subprog->sub_insn_off
6897  * is zero), subprog instructions are appended at the end of main program's
6898  * instruction array. Then main program is "put on hold" while we recursively
6899  * process newly appended subprogram. If that subprogram calls into another
6900  * subprogram that hasn't been appended, new subprogram is appended again to
6901  * the *main* prog's instructions (subprog's instructions are always left
6902  * untouched, as they need to be in unmodified state for subsequent main progs
6903  * and subprog instructions are always sent only as part of a main prog) and
6904  * the process continues recursively. Once all the subprogs called from a main
6905  * prog or any of its subprogs are appended (and relocated), all their
6906  * positions within finalized instructions array are known, so it's easy to
6907  * rewrite call instructions with correct relative offsets, corresponding to
6908  * desired target subprog.
6909  *
6910  * Its important to realize that some subprogs might not be called from some
6911  * main prog and any of its called/used subprogs. Those will keep their
6912  * subprog->sub_insn_off as zero at all times and won't be appended to current
6913  * main prog and won't be relocated within the context of current main prog.
6914  * They might still be used from other main progs later.
6915  *
6916  * Visually this process can be shown as below. Suppose we have two main
6917  * programs mainA and mainB and BPF object contains three subprogs: subA,
6918  * subB, and subC. mainA calls only subA, mainB calls only subC, but subA and
6919  * subC both call subB:
6920  *
6921  *        +--------+ +-------+
6922  *        |        v v       |
6923  *     +--+---+ +--+-+-+ +---+--+
6924  *     | subA | | subB | | subC |
6925  *     +--+---+ +------+ +---+--+
6926  *        ^                  ^
6927  *        |                  |
6928  *    +---+-------+   +------+----+
6929  *    |   mainA   |   |   mainB   |
6930  *    +-----------+   +-----------+
6931  *
6932  * We'll start relocating mainA, will find subA, append it and start
6933  * processing sub A recursively:
6934  *
6935  *    +-----------+------+
6936  *    |   mainA   | subA |
6937  *    +-----------+------+
6938  *
6939  * At this point we notice that subB is used from subA, so we append it and
6940  * relocate (there are no further subcalls from subB):
6941  *
6942  *    +-----------+------+------+
6943  *    |   mainA   | subA | subB |
6944  *    +-----------+------+------+
6945  *
6946  * At this point, we relocate subA calls, then go one level up and finish with
6947  * relocatin mainA calls. mainA is done.
6948  *
6949  * For mainB process is similar but results in different order. We start with
6950  * mainB and skip subA and subB, as mainB never calls them (at least
6951  * directly), but we see subC is needed, so we append and start processing it:
6952  *
6953  *    +-----------+------+
6954  *    |   mainB   | subC |
6955  *    +-----------+------+
6956  * Now we see subC needs subB, so we go back to it, append and relocate it:
6957  *
6958  *    +-----------+------+------+
6959  *    |   mainB   | subC | subB |
6960  *    +-----------+------+------+
6961  *
6962  * At this point we unwind recursion, relocate calls in subC, then in mainB.
6963  */
6964 static int
6965 bpf_object__relocate_calls(struct bpf_object *obj, struct bpf_program *prog)
6966 {
6967 	struct bpf_program *subprog;
6968 	int i, err;
6969 
6970 	/* mark all subprogs as not relocated (yet) within the context of
6971 	 * current main program
6972 	 */
6973 	for (i = 0; i < obj->nr_programs; i++) {
6974 		subprog = &obj->programs[i];
6975 		if (!prog_is_subprog(obj, subprog))
6976 			continue;
6977 
6978 		subprog->sub_insn_off = 0;
6979 	}
6980 
6981 	err = bpf_object__reloc_code(obj, prog, prog);
6982 	if (err)
6983 		return err;
6984 
6985 	return 0;
6986 }
6987 
6988 static void
6989 bpf_object__free_relocs(struct bpf_object *obj)
6990 {
6991 	struct bpf_program *prog;
6992 	int i;
6993 
6994 	/* free up relocation descriptors */
6995 	for (i = 0; i < obj->nr_programs; i++) {
6996 		prog = &obj->programs[i];
6997 		zfree(&prog->reloc_desc);
6998 		prog->nr_reloc = 0;
6999 	}
7000 }
7001 
7002 static int cmp_relocs(const void *_a, const void *_b)
7003 {
7004 	const struct reloc_desc *a = _a;
7005 	const struct reloc_desc *b = _b;
7006 
7007 	if (a->insn_idx != b->insn_idx)
7008 		return a->insn_idx < b->insn_idx ? -1 : 1;
7009 
7010 	/* no two relocations should have the same insn_idx, but ... */
7011 	if (a->type != b->type)
7012 		return a->type < b->type ? -1 : 1;
7013 
7014 	return 0;
7015 }
7016 
7017 static void bpf_object__sort_relos(struct bpf_object *obj)
7018 {
7019 	int i;
7020 
7021 	for (i = 0; i < obj->nr_programs; i++) {
7022 		struct bpf_program *p = &obj->programs[i];
7023 
7024 		if (!p->nr_reloc)
7025 			continue;
7026 
7027 		qsort(p->reloc_desc, p->nr_reloc, sizeof(*p->reloc_desc), cmp_relocs);
7028 	}
7029 }
7030 
7031 static int bpf_prog_assign_exc_cb(struct bpf_object *obj, struct bpf_program *prog)
7032 {
7033 	const char *str = "exception_callback:";
7034 	size_t pfx_len = strlen(str);
7035 	int i, j, n;
7036 
7037 	if (!obj->btf || !kernel_supports(obj, FEAT_BTF_DECL_TAG))
7038 		return 0;
7039 
7040 	n = btf__type_cnt(obj->btf);
7041 	for (i = 1; i < n; i++) {
7042 		const char *name;
7043 		struct btf_type *t;
7044 
7045 		t = btf_type_by_id(obj->btf, i);
7046 		if (!btf_is_decl_tag(t) || btf_decl_tag(t)->component_idx != -1)
7047 			continue;
7048 
7049 		name = btf__str_by_offset(obj->btf, t->name_off);
7050 		if (strncmp(name, str, pfx_len) != 0)
7051 			continue;
7052 
7053 		t = btf_type_by_id(obj->btf, t->type);
7054 		if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL) {
7055 			pr_warn("prog '%s': exception_callback:<value> decl tag not applied to the main program\n",
7056 				prog->name);
7057 			return -EINVAL;
7058 		}
7059 		if (strcmp(prog->name, btf__str_by_offset(obj->btf, t->name_off)) != 0)
7060 			continue;
7061 		/* Multiple callbacks are specified for the same prog,
7062 		 * the verifier will eventually return an error for this
7063 		 * case, hence simply skip appending a subprog.
7064 		 */
7065 		if (prog->exception_cb_idx >= 0) {
7066 			prog->exception_cb_idx = -1;
7067 			break;
7068 		}
7069 
7070 		name += pfx_len;
7071 		if (str_is_empty(name)) {
7072 			pr_warn("prog '%s': exception_callback:<value> decl tag contains empty value\n",
7073 				prog->name);
7074 			return -EINVAL;
7075 		}
7076 
7077 		for (j = 0; j < obj->nr_programs; j++) {
7078 			struct bpf_program *subprog = &obj->programs[j];
7079 
7080 			if (!prog_is_subprog(obj, subprog))
7081 				continue;
7082 			if (strcmp(name, subprog->name) != 0)
7083 				continue;
7084 			/* Enforce non-hidden, as from verifier point of
7085 			 * view it expects global functions, whereas the
7086 			 * mark_btf_static fixes up linkage as static.
7087 			 */
7088 			if (!subprog->sym_global || subprog->mark_btf_static) {
7089 				pr_warn("prog '%s': exception callback %s must be a global non-hidden function\n",
7090 					prog->name, subprog->name);
7091 				return -EINVAL;
7092 			}
7093 			/* Let's see if we already saw a static exception callback with the same name */
7094 			if (prog->exception_cb_idx >= 0) {
7095 				pr_warn("prog '%s': multiple subprogs with same name as exception callback '%s'\n",
7096 					prog->name, subprog->name);
7097 				return -EINVAL;
7098 			}
7099 			prog->exception_cb_idx = j;
7100 			break;
7101 		}
7102 
7103 		if (prog->exception_cb_idx >= 0)
7104 			continue;
7105 
7106 		pr_warn("prog '%s': cannot find exception callback '%s'\n", prog->name, name);
7107 		return -ENOENT;
7108 	}
7109 
7110 	return 0;
7111 }
7112 
7113 static struct {
7114 	enum bpf_prog_type prog_type;
7115 	const char *ctx_name;
7116 } global_ctx_map[] = {
7117 	{ BPF_PROG_TYPE_CGROUP_DEVICE,           "bpf_cgroup_dev_ctx" },
7118 	{ BPF_PROG_TYPE_CGROUP_SKB,              "__sk_buff" },
7119 	{ BPF_PROG_TYPE_CGROUP_SOCK,             "bpf_sock" },
7120 	{ BPF_PROG_TYPE_CGROUP_SOCK_ADDR,        "bpf_sock_addr" },
7121 	{ BPF_PROG_TYPE_CGROUP_SOCKOPT,          "bpf_sockopt" },
7122 	{ BPF_PROG_TYPE_CGROUP_SYSCTL,           "bpf_sysctl" },
7123 	{ BPF_PROG_TYPE_FLOW_DISSECTOR,          "__sk_buff" },
7124 	{ BPF_PROG_TYPE_KPROBE,                  "bpf_user_pt_regs_t" },
7125 	{ BPF_PROG_TYPE_LWT_IN,                  "__sk_buff" },
7126 	{ BPF_PROG_TYPE_LWT_OUT,                 "__sk_buff" },
7127 	{ BPF_PROG_TYPE_LWT_SEG6LOCAL,           "__sk_buff" },
7128 	{ BPF_PROG_TYPE_LWT_XMIT,                "__sk_buff" },
7129 	{ BPF_PROG_TYPE_NETFILTER,               "bpf_nf_ctx" },
7130 	{ BPF_PROG_TYPE_PERF_EVENT,              "bpf_perf_event_data" },
7131 	{ BPF_PROG_TYPE_RAW_TRACEPOINT,          "bpf_raw_tracepoint_args" },
7132 	{ BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE, "bpf_raw_tracepoint_args" },
7133 	{ BPF_PROG_TYPE_SCHED_ACT,               "__sk_buff" },
7134 	{ BPF_PROG_TYPE_SCHED_CLS,               "__sk_buff" },
7135 	{ BPF_PROG_TYPE_SK_LOOKUP,               "bpf_sk_lookup" },
7136 	{ BPF_PROG_TYPE_SK_MSG,                  "sk_msg_md" },
7137 	{ BPF_PROG_TYPE_SK_REUSEPORT,            "sk_reuseport_md" },
7138 	{ BPF_PROG_TYPE_SK_SKB,                  "__sk_buff" },
7139 	{ BPF_PROG_TYPE_SOCK_OPS,                "bpf_sock_ops" },
7140 	{ BPF_PROG_TYPE_SOCKET_FILTER,           "__sk_buff" },
7141 	{ BPF_PROG_TYPE_XDP,                     "xdp_md" },
7142 	/* all other program types don't have "named" context structs */
7143 };
7144 
7145 /* forward declarations for arch-specific underlying types of bpf_user_pt_regs_t typedef,
7146  * for below __builtin_types_compatible_p() checks;
7147  * with this approach we don't need any extra arch-specific #ifdef guards
7148  */
7149 struct pt_regs;
7150 struct user_pt_regs;
7151 struct user_regs_struct;
7152 
7153 static bool need_func_arg_type_fixup(const struct btf *btf, const struct bpf_program *prog,
7154 				     const char *subprog_name, int arg_idx,
7155 				     int arg_type_id, const char *ctx_name)
7156 {
7157 	const struct btf_type *t;
7158 	const char *tname;
7159 
7160 	/* check if existing parameter already matches verifier expectations */
7161 	t = skip_mods_and_typedefs(btf, arg_type_id, NULL);
7162 	if (!btf_is_ptr(t))
7163 		goto out_warn;
7164 
7165 	/* typedef bpf_user_pt_regs_t is a special PITA case, valid for kprobe
7166 	 * and perf_event programs, so check this case early on and forget
7167 	 * about it for subsequent checks
7168 	 */
7169 	while (btf_is_mod(t))
7170 		t = btf__type_by_id(btf, t->type);
7171 	if (btf_is_typedef(t) &&
7172 	    (prog->type == BPF_PROG_TYPE_KPROBE || prog->type == BPF_PROG_TYPE_PERF_EVENT)) {
7173 		tname = btf__str_by_offset(btf, t->name_off) ?: "<anon>";
7174 		if (strcmp(tname, "bpf_user_pt_regs_t") == 0)
7175 			return false; /* canonical type for kprobe/perf_event */
7176 	}
7177 
7178 	/* now we can ignore typedefs moving forward */
7179 	t = skip_mods_and_typedefs(btf, t->type, NULL);
7180 
7181 	/* if it's `void *`, definitely fix up BTF info */
7182 	if (btf_is_void(t))
7183 		return true;
7184 
7185 	/* if it's already proper canonical type, no need to fix up */
7186 	tname = btf__str_by_offset(btf, t->name_off) ?: "<anon>";
7187 	if (btf_is_struct(t) && strcmp(tname, ctx_name) == 0)
7188 		return false;
7189 
7190 	/* special cases */
7191 	switch (prog->type) {
7192 	case BPF_PROG_TYPE_KPROBE:
7193 		/* `struct pt_regs *` is expected, but we need to fix up */
7194 		if (btf_is_struct(t) && strcmp(tname, "pt_regs") == 0)
7195 			return true;
7196 		break;
7197 	case BPF_PROG_TYPE_PERF_EVENT:
7198 		if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct pt_regs) &&
7199 		    btf_is_struct(t) && strcmp(tname, "pt_regs") == 0)
7200 			return true;
7201 		if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct user_pt_regs) &&
7202 		    btf_is_struct(t) && strcmp(tname, "user_pt_regs") == 0)
7203 			return true;
7204 		if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct user_regs_struct) &&
7205 		    btf_is_struct(t) && strcmp(tname, "user_regs_struct") == 0)
7206 			return true;
7207 		break;
7208 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
7209 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
7210 		/* allow u64* as ctx */
7211 		if (btf_is_int(t) && t->size == 8)
7212 			return true;
7213 		break;
7214 	default:
7215 		break;
7216 	}
7217 
7218 out_warn:
7219 	pr_warn("prog '%s': subprog '%s' arg#%d is expected to be of `struct %s *` type\n",
7220 		prog->name, subprog_name, arg_idx, ctx_name);
7221 	return false;
7222 }
7223 
7224 static int clone_func_btf_info(struct btf *btf, int orig_fn_id, struct bpf_program *prog)
7225 {
7226 	int fn_id, fn_proto_id, ret_type_id, orig_proto_id;
7227 	int i, err, arg_cnt, fn_name_off, linkage;
7228 	struct btf_type *fn_t, *fn_proto_t, *t;
7229 	struct btf_param *p;
7230 
7231 	/* caller already validated FUNC -> FUNC_PROTO validity */
7232 	fn_t = btf_type_by_id(btf, orig_fn_id);
7233 	fn_proto_t = btf_type_by_id(btf, fn_t->type);
7234 
7235 	/* Note that each btf__add_xxx() operation invalidates
7236 	 * all btf_type and string pointers, so we need to be
7237 	 * very careful when cloning BTF types. BTF type
7238 	 * pointers have to be always refetched. And to avoid
7239 	 * problems with invalidated string pointers, we
7240 	 * add empty strings initially, then just fix up
7241 	 * name_off offsets in place. Offsets are stable for
7242 	 * existing strings, so that works out.
7243 	 */
7244 	fn_name_off = fn_t->name_off; /* we are about to invalidate fn_t */
7245 	linkage = btf_func_linkage(fn_t);
7246 	orig_proto_id = fn_t->type; /* original FUNC_PROTO ID */
7247 	ret_type_id = fn_proto_t->type; /* fn_proto_t will be invalidated */
7248 	arg_cnt = btf_vlen(fn_proto_t);
7249 
7250 	/* clone FUNC_PROTO and its params */
7251 	fn_proto_id = btf__add_func_proto(btf, ret_type_id);
7252 	if (fn_proto_id < 0)
7253 		return -EINVAL;
7254 
7255 	for (i = 0; i < arg_cnt; i++) {
7256 		int name_off;
7257 
7258 		/* copy original parameter data */
7259 		t = btf_type_by_id(btf, orig_proto_id);
7260 		p = &btf_params(t)[i];
7261 		name_off = p->name_off;
7262 
7263 		err = btf__add_func_param(btf, "", p->type);
7264 		if (err)
7265 			return err;
7266 
7267 		fn_proto_t = btf_type_by_id(btf, fn_proto_id);
7268 		p = &btf_params(fn_proto_t)[i];
7269 		p->name_off = name_off; /* use remembered str offset */
7270 	}
7271 
7272 	/* clone FUNC now, btf__add_func() enforces non-empty name, so use
7273 	 * entry program's name as a placeholder, which we replace immediately
7274 	 * with original name_off
7275 	 */
7276 	fn_id = btf__add_func(btf, prog->name, linkage, fn_proto_id);
7277 	if (fn_id < 0)
7278 		return -EINVAL;
7279 
7280 	fn_t = btf_type_by_id(btf, fn_id);
7281 	fn_t->name_off = fn_name_off; /* reuse original string */
7282 
7283 	return fn_id;
7284 }
7285 
7286 /* Check if main program or global subprog's function prototype has `arg:ctx`
7287  * argument tags, and, if necessary, substitute correct type to match what BPF
7288  * verifier would expect, taking into account specific program type. This
7289  * allows to support __arg_ctx tag transparently on old kernels that don't yet
7290  * have a native support for it in the verifier, making user's life much
7291  * easier.
7292  */
7293 static int bpf_program_fixup_func_info(struct bpf_object *obj, struct bpf_program *prog)
7294 {
7295 	const char *ctx_name = NULL, *ctx_tag = "arg:ctx", *fn_name;
7296 	struct bpf_func_info_min *func_rec;
7297 	struct btf_type *fn_t, *fn_proto_t;
7298 	struct btf *btf = obj->btf;
7299 	const struct btf_type *t;
7300 	struct btf_param *p;
7301 	int ptr_id = 0, struct_id, tag_id, orig_fn_id;
7302 	int i, n, arg_idx, arg_cnt, err, rec_idx;
7303 	int *orig_ids;
7304 
7305 	/* no .BTF.ext, no problem */
7306 	if (!obj->btf_ext || !prog->func_info)
7307 		return 0;
7308 
7309 	/* don't do any fix ups if kernel natively supports __arg_ctx */
7310 	if (kernel_supports(obj, FEAT_ARG_CTX_TAG))
7311 		return 0;
7312 
7313 	/* some BPF program types just don't have named context structs, so
7314 	 * this fallback mechanism doesn't work for them
7315 	 */
7316 	for (i = 0; i < ARRAY_SIZE(global_ctx_map); i++) {
7317 		if (global_ctx_map[i].prog_type != prog->type)
7318 			continue;
7319 		ctx_name = global_ctx_map[i].ctx_name;
7320 		break;
7321 	}
7322 	if (!ctx_name)
7323 		return 0;
7324 
7325 	/* remember original func BTF IDs to detect if we already cloned them */
7326 	orig_ids = calloc(prog->func_info_cnt, sizeof(*orig_ids));
7327 	if (!orig_ids)
7328 		return -ENOMEM;
7329 	for (i = 0; i < prog->func_info_cnt; i++) {
7330 		func_rec = prog->func_info + prog->func_info_rec_size * i;
7331 		orig_ids[i] = func_rec->type_id;
7332 	}
7333 
7334 	/* go through each DECL_TAG with "arg:ctx" and see if it points to one
7335 	 * of our subprogs; if yes and subprog is global and needs adjustment,
7336 	 * clone and adjust FUNC -> FUNC_PROTO combo
7337 	 */
7338 	for (i = 1, n = btf__type_cnt(btf); i < n; i++) {
7339 		/* only DECL_TAG with "arg:ctx" value are interesting */
7340 		t = btf__type_by_id(btf, i);
7341 		if (!btf_is_decl_tag(t))
7342 			continue;
7343 		if (strcmp(btf__str_by_offset(btf, t->name_off), ctx_tag) != 0)
7344 			continue;
7345 
7346 		/* only global funcs need adjustment, if at all */
7347 		orig_fn_id = t->type;
7348 		fn_t = btf_type_by_id(btf, orig_fn_id);
7349 		if (!btf_is_func(fn_t) || btf_func_linkage(fn_t) != BTF_FUNC_GLOBAL)
7350 			continue;
7351 
7352 		/* sanity check FUNC -> FUNC_PROTO chain, just in case */
7353 		fn_proto_t = btf_type_by_id(btf, fn_t->type);
7354 		if (!fn_proto_t || !btf_is_func_proto(fn_proto_t))
7355 			continue;
7356 
7357 		/* find corresponding func_info record */
7358 		func_rec = NULL;
7359 		for (rec_idx = 0; rec_idx < prog->func_info_cnt; rec_idx++) {
7360 			if (orig_ids[rec_idx] == t->type) {
7361 				func_rec = prog->func_info + prog->func_info_rec_size * rec_idx;
7362 				break;
7363 			}
7364 		}
7365 		/* current main program doesn't call into this subprog */
7366 		if (!func_rec)
7367 			continue;
7368 
7369 		/* some more sanity checking of DECL_TAG */
7370 		arg_cnt = btf_vlen(fn_proto_t);
7371 		arg_idx = btf_decl_tag(t)->component_idx;
7372 		if (arg_idx < 0 || arg_idx >= arg_cnt)
7373 			continue;
7374 
7375 		/* check if we should fix up argument type */
7376 		p = &btf_params(fn_proto_t)[arg_idx];
7377 		fn_name = btf__str_by_offset(btf, fn_t->name_off) ?: "<anon>";
7378 		if (!need_func_arg_type_fixup(btf, prog, fn_name, arg_idx, p->type, ctx_name))
7379 			continue;
7380 
7381 		/* clone fn/fn_proto, unless we already did it for another arg */
7382 		if (func_rec->type_id == orig_fn_id) {
7383 			int fn_id;
7384 
7385 			fn_id = clone_func_btf_info(btf, orig_fn_id, prog);
7386 			if (fn_id < 0) {
7387 				err = fn_id;
7388 				goto err_out;
7389 			}
7390 
7391 			/* point func_info record to a cloned FUNC type */
7392 			func_rec->type_id = fn_id;
7393 		}
7394 
7395 		/* create PTR -> STRUCT type chain to mark PTR_TO_CTX argument;
7396 		 * we do it just once per main BPF program, as all global
7397 		 * funcs share the same program type, so need only PTR ->
7398 		 * STRUCT type chain
7399 		 */
7400 		if (ptr_id == 0) {
7401 			struct_id = btf__add_struct(btf, ctx_name, 0);
7402 			ptr_id = btf__add_ptr(btf, struct_id);
7403 			if (ptr_id < 0 || struct_id < 0) {
7404 				err = -EINVAL;
7405 				goto err_out;
7406 			}
7407 		}
7408 
7409 		/* for completeness, clone DECL_TAG and point it to cloned param */
7410 		tag_id = btf__add_decl_tag(btf, ctx_tag, func_rec->type_id, arg_idx);
7411 		if (tag_id < 0) {
7412 			err = -EINVAL;
7413 			goto err_out;
7414 		}
7415 
7416 		/* all the BTF manipulations invalidated pointers, refetch them */
7417 		fn_t = btf_type_by_id(btf, func_rec->type_id);
7418 		fn_proto_t = btf_type_by_id(btf, fn_t->type);
7419 
7420 		/* fix up type ID pointed to by param */
7421 		p = &btf_params(fn_proto_t)[arg_idx];
7422 		p->type = ptr_id;
7423 	}
7424 
7425 	free(orig_ids);
7426 	return 0;
7427 err_out:
7428 	free(orig_ids);
7429 	return err;
7430 }
7431 
7432 static int bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
7433 {
7434 	struct bpf_program *prog;
7435 	size_t i, j;
7436 	int err;
7437 
7438 	if (obj->btf_ext) {
7439 		err = bpf_object__relocate_core(obj, targ_btf_path);
7440 		if (err) {
7441 			pr_warn("failed to perform CO-RE relocations: %s\n",
7442 				errstr(err));
7443 			return err;
7444 		}
7445 		bpf_object__sort_relos(obj);
7446 	}
7447 
7448 	/* place globals at the end of the arena (if supported) */
7449 	if (obj->arena_map_idx >= 0 && kernel_supports(obj, FEAT_LDIMM64_FULL_RANGE_OFF)) {
7450 		struct bpf_map *arena_map = &obj->maps[obj->arena_map_idx];
7451 
7452 		obj->arena_data_off = bpf_map_mmap_sz(arena_map) -
7453 				      roundup(obj->arena_data_sz, sysconf(_SC_PAGE_SIZE));
7454 	}
7455 
7456 	/* Before relocating calls pre-process relocations and mark
7457 	 * few ld_imm64 instructions that points to subprogs.
7458 	 * Otherwise bpf_object__reloc_code() later would have to consider
7459 	 * all ld_imm64 insns as relocation candidates. That would
7460 	 * reduce relocation speed, since amount of find_prog_insn_relo()
7461 	 * would increase and most of them will fail to find a relo.
7462 	 */
7463 	for (i = 0; i < obj->nr_programs; i++) {
7464 		prog = &obj->programs[i];
7465 		for (j = 0; j < prog->nr_reloc; j++) {
7466 			struct reloc_desc *relo = &prog->reloc_desc[j];
7467 			struct bpf_insn *insn = &prog->insns[relo->insn_idx];
7468 
7469 			/* mark the insn, so it's recognized by insn_is_pseudo_func() */
7470 			if (relo->type == RELO_SUBPROG_ADDR)
7471 				insn[0].src_reg = BPF_PSEUDO_FUNC;
7472 		}
7473 	}
7474 
7475 	/* relocate subprogram calls and append used subprograms to main
7476 	 * programs; each copy of subprogram code needs to be relocated
7477 	 * differently for each main program, because its code location might
7478 	 * have changed.
7479 	 * Append subprog relos to main programs to allow data relos to be
7480 	 * processed after text is completely relocated.
7481 	 */
7482 	for (i = 0; i < obj->nr_programs; i++) {
7483 		prog = &obj->programs[i];
7484 		/* sub-program's sub-calls are relocated within the context of
7485 		 * its main program only
7486 		 */
7487 		if (prog_is_subprog(obj, prog))
7488 			continue;
7489 		if (!prog->autoload)
7490 			continue;
7491 
7492 		err = bpf_object__relocate_calls(obj, prog);
7493 		if (err) {
7494 			pr_warn("prog '%s': failed to relocate calls: %s\n",
7495 				prog->name, errstr(err));
7496 			return err;
7497 		}
7498 
7499 		err = bpf_prog_assign_exc_cb(obj, prog);
7500 		if (err)
7501 			return err;
7502 		/* Now, also append exception callback if it has not been done already. */
7503 		if (prog->exception_cb_idx >= 0) {
7504 			struct bpf_program *subprog = &obj->programs[prog->exception_cb_idx];
7505 
7506 			/* Calling exception callback directly is disallowed, which the
7507 			 * verifier will reject later. In case it was processed already,
7508 			 * we can skip this step, otherwise for all other valid cases we
7509 			 * have to append exception callback now.
7510 			 */
7511 			if (subprog->sub_insn_off == 0) {
7512 				err = bpf_object__append_subprog_code(obj, prog, subprog);
7513 				if (err)
7514 					return err;
7515 				err = bpf_object__reloc_code(obj, prog, subprog);
7516 				if (err)
7517 					return err;
7518 			}
7519 		}
7520 	}
7521 	for (i = 0; i < obj->nr_programs; i++) {
7522 		prog = &obj->programs[i];
7523 		if (prog_is_subprog(obj, prog))
7524 			continue;
7525 		if (!prog->autoload)
7526 			continue;
7527 
7528 		/* Process data relos for main programs */
7529 		err = bpf_object__relocate_data(obj, prog);
7530 		if (err) {
7531 			pr_warn("prog '%s': failed to relocate data references: %s\n",
7532 				prog->name, errstr(err));
7533 			return err;
7534 		}
7535 
7536 		/* Fix up .BTF.ext information, if necessary */
7537 		err = bpf_program_fixup_func_info(obj, prog);
7538 		if (err) {
7539 			pr_warn("prog '%s': failed to perform .BTF.ext fix ups: %s\n",
7540 				prog->name, errstr(err));
7541 			return err;
7542 		}
7543 	}
7544 
7545 	return 0;
7546 }
7547 
7548 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
7549 					    Elf64_Shdr *shdr, Elf_Data *data);
7550 
7551 static int bpf_object__collect_map_relos(struct bpf_object *obj,
7552 					 Elf64_Shdr *shdr, Elf_Data *data)
7553 {
7554 	const int bpf_ptr_sz = 8, host_ptr_sz = sizeof(void *);
7555 	int i, j, nrels, new_sz;
7556 	const struct btf_var_secinfo *vi = NULL;
7557 	const struct btf_type *sec, *var, *def;
7558 	struct bpf_map *map = NULL, *targ_map = NULL;
7559 	struct bpf_program *targ_prog = NULL;
7560 	bool is_prog_array, is_map_in_map;
7561 	const struct btf_member *member;
7562 	const char *name, *mname, *type;
7563 	unsigned int moff;
7564 	Elf64_Sym *sym;
7565 	Elf64_Rel *rel;
7566 	void *tmp;
7567 
7568 	if (!obj->efile.btf_maps_sec_btf_id || !obj->btf)
7569 		return -EINVAL;
7570 	sec = btf__type_by_id(obj->btf, obj->efile.btf_maps_sec_btf_id);
7571 	if (!sec)
7572 		return -EINVAL;
7573 
7574 	nrels = shdr->sh_size / shdr->sh_entsize;
7575 	for (i = 0; i < nrels; i++) {
7576 		rel = elf_rel_by_idx(data, i);
7577 		if (!rel) {
7578 			pr_warn(".maps relo #%d: failed to get ELF relo\n", i);
7579 			return -LIBBPF_ERRNO__FORMAT;
7580 		}
7581 
7582 		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
7583 		if (!sym) {
7584 			pr_warn(".maps relo #%d: symbol %zx not found\n",
7585 				i, (size_t)ELF64_R_SYM(rel->r_info));
7586 			return -LIBBPF_ERRNO__FORMAT;
7587 		}
7588 		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
7589 
7590 		pr_debug(".maps relo #%d: for %zd value %zd rel->r_offset %zu name %d ('%s')\n",
7591 			 i, (ssize_t)(rel->r_info >> 32), (size_t)sym->st_value,
7592 			 (size_t)rel->r_offset, sym->st_name, name);
7593 
7594 		for (j = 0; j < obj->nr_maps; j++) {
7595 			map = &obj->maps[j];
7596 			if (map->sec_idx != obj->efile.btf_maps_shndx)
7597 				continue;
7598 
7599 			vi = btf_var_secinfos(sec) + map->btf_var_idx;
7600 			if (vi->offset <= rel->r_offset &&
7601 			    rel->r_offset + bpf_ptr_sz <= vi->offset + vi->size)
7602 				break;
7603 		}
7604 		if (j == obj->nr_maps) {
7605 			pr_warn(".maps relo #%d: cannot find map '%s' at rel->r_offset %zu\n",
7606 				i, name, (size_t)rel->r_offset);
7607 			return -EINVAL;
7608 		}
7609 
7610 		is_map_in_map = bpf_map_type__is_map_in_map(map->def.type);
7611 		is_prog_array = map->def.type == BPF_MAP_TYPE_PROG_ARRAY;
7612 		type = is_map_in_map ? "map" : "prog";
7613 		if (is_map_in_map) {
7614 			if (sym->st_shndx != obj->efile.btf_maps_shndx) {
7615 				pr_warn(".maps relo #%d: '%s' isn't a BTF-defined map\n",
7616 					i, name);
7617 				return -LIBBPF_ERRNO__RELOC;
7618 			}
7619 			if (map->def.type == BPF_MAP_TYPE_HASH_OF_MAPS &&
7620 			    map->def.key_size != sizeof(int)) {
7621 				pr_warn(".maps relo #%d: hash-of-maps '%s' should have key size %zu.\n",
7622 					i, map->name, sizeof(int));
7623 				return -EINVAL;
7624 			}
7625 			targ_map = bpf_object__find_map_by_name(obj, name);
7626 			if (!targ_map) {
7627 				pr_warn(".maps relo #%d: '%s' isn't a valid map reference\n",
7628 					i, name);
7629 				return -ESRCH;
7630 			}
7631 		} else if (is_prog_array) {
7632 			targ_prog = bpf_object__find_program_by_name(obj, name);
7633 			if (!targ_prog) {
7634 				pr_warn(".maps relo #%d: '%s' isn't a valid program reference\n",
7635 					i, name);
7636 				return -ESRCH;
7637 			}
7638 			if (targ_prog->sec_idx != sym->st_shndx ||
7639 			    targ_prog->sec_insn_off * 8 != sym->st_value ||
7640 			    prog_is_subprog(obj, targ_prog)) {
7641 				pr_warn(".maps relo #%d: '%s' isn't an entry-point program\n",
7642 					i, name);
7643 				return -LIBBPF_ERRNO__RELOC;
7644 			}
7645 		} else {
7646 			return -EINVAL;
7647 		}
7648 
7649 		var = btf__type_by_id(obj->btf, vi->type);
7650 		def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
7651 		if (btf_vlen(def) == 0)
7652 			return -EINVAL;
7653 		member = btf_members(def) + btf_vlen(def) - 1;
7654 		mname = btf__name_by_offset(obj->btf, member->name_off);
7655 		if (strcmp(mname, "values"))
7656 			return -EINVAL;
7657 
7658 		moff = btf_member_bit_offset(def, btf_vlen(def) - 1) / 8;
7659 		if (rel->r_offset - vi->offset < moff)
7660 			return -EINVAL;
7661 
7662 		moff = rel->r_offset - vi->offset - moff;
7663 		/* here we use BPF pointer size, which is always 64 bit, as we
7664 		 * are parsing ELF that was built for BPF target
7665 		 */
7666 		if (moff % bpf_ptr_sz)
7667 			return -EINVAL;
7668 		moff /= bpf_ptr_sz;
7669 		if (moff >= map->init_slots_sz) {
7670 			new_sz = moff + 1;
7671 			tmp = libbpf_reallocarray(map->init_slots, new_sz, host_ptr_sz);
7672 			if (!tmp)
7673 				return -ENOMEM;
7674 			map->init_slots = tmp;
7675 			memset(map->init_slots + map->init_slots_sz, 0,
7676 			       (new_sz - map->init_slots_sz) * host_ptr_sz);
7677 			map->init_slots_sz = new_sz;
7678 		}
7679 		map->init_slots[moff] = is_map_in_map ? (void *)targ_map : (void *)targ_prog;
7680 
7681 		pr_debug(".maps relo #%d: map '%s' slot [%d] points to %s '%s'\n",
7682 			 i, map->name, moff, type, name);
7683 	}
7684 
7685 	return 0;
7686 }
7687 
7688 static int bpf_object__collect_relos(struct bpf_object *obj)
7689 {
7690 	int i, err;
7691 
7692 	for (i = 0; i < obj->efile.sec_cnt; i++) {
7693 		struct elf_sec_desc *sec_desc = &obj->efile.secs[i];
7694 		Elf64_Shdr *shdr;
7695 		Elf_Data *data;
7696 		int idx;
7697 
7698 		if (sec_desc->sec_type != SEC_RELO)
7699 			continue;
7700 
7701 		shdr = sec_desc->shdr;
7702 		data = sec_desc->data;
7703 		idx = shdr->sh_info;
7704 
7705 		if (shdr->sh_type != SHT_REL || idx < 0 || idx >= obj->efile.sec_cnt) {
7706 			pr_warn("internal error at %d\n", __LINE__);
7707 			return -LIBBPF_ERRNO__INTERNAL;
7708 		}
7709 
7710 		if (obj->efile.secs[idx].sec_type == SEC_ST_OPS)
7711 			err = bpf_object__collect_st_ops_relos(obj, shdr, data);
7712 		else if (idx == obj->efile.btf_maps_shndx)
7713 			err = bpf_object__collect_map_relos(obj, shdr, data);
7714 		else
7715 			err = bpf_object__collect_prog_relos(obj, shdr, data);
7716 		if (err)
7717 			return err;
7718 	}
7719 
7720 	bpf_object__sort_relos(obj);
7721 	return 0;
7722 }
7723 
7724 static bool insn_is_helper_call(struct bpf_insn *insn, enum bpf_func_id *func_id)
7725 {
7726 	if (BPF_CLASS(insn->code) == BPF_JMP &&
7727 	    BPF_OP(insn->code) == BPF_CALL &&
7728 	    BPF_SRC(insn->code) == BPF_K &&
7729 	    insn->src_reg == 0 &&
7730 	    insn->dst_reg == 0) {
7731 		    *func_id = insn->imm;
7732 		    return true;
7733 	}
7734 	return false;
7735 }
7736 
7737 static int bpf_object__sanitize_prog(struct bpf_object *obj, struct bpf_program *prog)
7738 {
7739 	struct bpf_insn *insn = prog->insns;
7740 	enum bpf_func_id func_id;
7741 	int i;
7742 
7743 	if (obj->gen_loader)
7744 		return 0;
7745 
7746 	for (i = 0; i < prog->insns_cnt; i++, insn++) {
7747 		if (!insn_is_helper_call(insn, &func_id))
7748 			continue;
7749 
7750 		/* on kernels that don't yet support
7751 		 * bpf_probe_read_{kernel,user}[_str] helpers, fall back
7752 		 * to bpf_probe_read() which works well for old kernels
7753 		 */
7754 		switch (func_id) {
7755 		case BPF_FUNC_probe_read_kernel:
7756 		case BPF_FUNC_probe_read_user:
7757 			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
7758 				insn->imm = BPF_FUNC_probe_read;
7759 			break;
7760 		case BPF_FUNC_probe_read_kernel_str:
7761 		case BPF_FUNC_probe_read_user_str:
7762 			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
7763 				insn->imm = BPF_FUNC_probe_read_str;
7764 			break;
7765 		default:
7766 			break;
7767 		}
7768 	}
7769 	return 0;
7770 }
7771 
7772 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
7773 				     int *btf_obj_fd, int *btf_type_id);
7774 
7775 static inline bool is_tracing_multi(enum bpf_attach_type type)
7776 {
7777 	return type == BPF_TRACE_FENTRY_MULTI || type == BPF_TRACE_FEXIT_MULTI ||
7778 	       type == BPF_TRACE_FSESSION_MULTI;
7779 }
7780 
7781 static const struct module_btf *find_attach_module(struct bpf_object *obj, const char *attach)
7782 {
7783 	const char *sep, *mod_name = NULL;
7784 	int i, mod_len, err;
7785 
7786 	/*
7787 	 * We expect attach string in the form of either
7788 	 * - function_pattern or
7789 	 * - <module>:function_pattern
7790 	 */
7791 	sep = strchr(attach, ':');
7792 	if (sep) {
7793 		mod_name = attach;
7794 		mod_len = sep - mod_name;
7795 	}
7796 	if (!mod_name)
7797 		return NULL;
7798 
7799 	err = load_module_btfs(obj);
7800 	if (err)
7801 		return NULL;
7802 
7803 	for (i = 0; i < obj->btf_module_cnt; i++) {
7804 		const struct module_btf *mod = &obj->btf_modules[i];
7805 
7806 		if (strncmp(mod->name, mod_name, mod_len) == 0 && mod->name[mod_len] == '\0')
7807 			return mod;
7808 	}
7809 	return NULL;
7810 }
7811 
7812 static int tracing_multi_mod_fd(struct bpf_program *prog, int *btf_obj_fd)
7813 {
7814 	const char *attach_name, *sep;
7815 	const struct module_btf *mod;
7816 
7817 	*btf_obj_fd = 0;
7818 	attach_name = strchr(prog->sec_name, '/');
7819 
7820 	/* Program with no details in spec, using kernel btf. */
7821 	if (!attach_name)
7822 		return 0;
7823 
7824 	/* Program with no module section, using kernel btf. */
7825 	sep = strchr(++attach_name, ':');
7826 	if (!sep)
7827 		return 0;
7828 
7829 	/* Program with module specified, get its btf fd. */
7830 	mod = find_attach_module(prog->obj, attach_name);
7831 	if (!mod)
7832 		return -EINVAL;
7833 
7834 	*btf_obj_fd = mod->fd;
7835 	return 0;
7836 }
7837 
7838 /* this is called as prog->sec_def->prog_prepare_load_fn for libbpf-supported sec_defs */
7839 static int libbpf_prepare_prog_load(struct bpf_program *prog,
7840 				    struct bpf_prog_load_opts *opts, long cookie)
7841 {
7842 	enum sec_def_flags def = cookie;
7843 
7844 	/* old kernels might not support specifying expected_attach_type */
7845 	if ((def & SEC_EXP_ATTACH_OPT) && !kernel_supports(prog->obj, FEAT_EXP_ATTACH_TYPE))
7846 		opts->expected_attach_type = 0;
7847 
7848 	if (def & SEC_SLEEPABLE)
7849 		opts->prog_flags |= BPF_F_SLEEPABLE;
7850 
7851 	if (prog->type == BPF_PROG_TYPE_XDP && (def & SEC_XDP_FRAGS))
7852 		opts->prog_flags |= BPF_F_XDP_HAS_FRAGS;
7853 
7854 	/* special check for usdt to use uprobe_multi link */
7855 	if ((def & SEC_USDT) && kernel_supports(prog->obj, FEAT_UPROBE_MULTI_LINK)) {
7856 		/* for BPF_TRACE_UPROBE_MULTI, user might want to query expected_attach_type
7857 		 * in prog, and expected_attach_type we set in kernel is from opts, so we
7858 		 * update both.
7859 		 */
7860 		prog->expected_attach_type = BPF_TRACE_UPROBE_MULTI;
7861 		opts->expected_attach_type = BPF_TRACE_UPROBE_MULTI;
7862 	}
7863 
7864 	if ((def & SEC_ATTACH_BTF) && !prog->attach_btf_id) {
7865 		int btf_obj_fd = 0, btf_type_id = 0, err;
7866 		const char *attach_name;
7867 
7868 		attach_name = strchr(prog->sec_name, '/');
7869 		if (!attach_name) {
7870 			/* if BPF program is annotated with just SEC("fentry")
7871 			 * (or similar) without declaratively specifying
7872 			 * target, then it is expected that target will be
7873 			 * specified with bpf_program__set_attach_target() at
7874 			 * runtime before BPF object load step. If not, then
7875 			 * there is nothing to load into the kernel as BPF
7876 			 * verifier won't be able to validate BPF program
7877 			 * correctness anyways.
7878 			 */
7879 			pr_warn("prog '%s': no BTF-based attach target is specified, use bpf_program__set_attach_target()\n",
7880 				prog->name);
7881 			return -EINVAL;
7882 		}
7883 		attach_name++; /* skip over / */
7884 
7885 		err = libbpf_find_attach_btf_id(prog, attach_name, &btf_obj_fd, &btf_type_id);
7886 		if (err)
7887 			return err;
7888 
7889 		/* cache resolved BTF FD and BTF type ID in the prog */
7890 		prog->attach_btf_obj_fd = btf_obj_fd;
7891 		prog->attach_btf_id = btf_type_id;
7892 
7893 		/* but by now libbpf common logic is not utilizing
7894 		 * prog->atach_btf_obj_fd/prog->attach_btf_id anymore because
7895 		 * this callback is called after opts were populated by
7896 		 * libbpf, so this callback has to update opts explicitly here
7897 		 */
7898 		opts->attach_btf_obj_fd = btf_obj_fd;
7899 		opts->attach_btf_id = btf_type_id;
7900 	}
7901 
7902 	if (is_tracing_multi(prog->expected_attach_type)) {
7903 		int err, btf_obj_fd = 0;
7904 
7905 		err = tracing_multi_mod_fd(prog, &btf_obj_fd);
7906 		if (err < 0)
7907 			return err;
7908 
7909 		prog->attach_btf_obj_fd = btf_obj_fd;
7910 		opts->attach_btf_obj_fd = btf_obj_fd;
7911 	}
7912 
7913 	return 0;
7914 }
7915 
7916 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz);
7917 
7918 static int bpf_object_load_prog(struct bpf_object *obj, struct bpf_program *prog,
7919 				struct bpf_insn *insns, int insns_cnt,
7920 				const char *license, __u32 kern_version, int *prog_fd)
7921 {
7922 	LIBBPF_OPTS(bpf_prog_load_opts, load_attr);
7923 	const char *prog_name = NULL;
7924 	size_t log_buf_size = 0;
7925 	char *log_buf = NULL, *tmp;
7926 	bool own_log_buf = true;
7927 	__u32 log_level = prog->log_level;
7928 	int ret, err;
7929 
7930 	/* Be more helpful by rejecting programs that can't be validated early
7931 	 * with more meaningful and actionable error message.
7932 	 */
7933 	switch (prog->type) {
7934 	case BPF_PROG_TYPE_UNSPEC:
7935 		/*
7936 		 * The program type must be set.  Most likely we couldn't find a proper
7937 		 * section definition at load time, and thus we didn't infer the type.
7938 		 */
7939 		pr_warn("prog '%s': missing BPF prog type, check ELF section name '%s'\n",
7940 			prog->name, prog->sec_name);
7941 		return -EINVAL;
7942 	case BPF_PROG_TYPE_STRUCT_OPS:
7943 		if (prog->attach_btf_id == 0) {
7944 			pr_warn("prog '%s': SEC(\"struct_ops\") program isn't referenced anywhere, did you forget to use it?\n",
7945 				prog->name);
7946 			return -EINVAL;
7947 		}
7948 		break;
7949 	default:
7950 		break;
7951 	}
7952 
7953 	if (!insns || !insns_cnt)
7954 		return -EINVAL;
7955 
7956 	if (kernel_supports(obj, FEAT_PROG_NAME))
7957 		prog_name = prog->name;
7958 	load_attr.attach_prog_fd = prog->attach_prog_fd;
7959 	load_attr.attach_btf_obj_fd = prog->attach_btf_obj_fd;
7960 	load_attr.attach_btf_id = prog->attach_btf_id;
7961 	load_attr.kern_version = kern_version;
7962 	load_attr.prog_ifindex = prog->prog_ifindex;
7963 	load_attr.expected_attach_type = prog->expected_attach_type;
7964 
7965 	/* specify func_info/line_info only if kernel supports them */
7966 	if (obj->btf && btf__fd(obj->btf) >= 0 && kernel_supports(obj, FEAT_BTF_FUNC)) {
7967 		load_attr.prog_btf_fd = btf__fd(obj->btf);
7968 		load_attr.func_info = prog->func_info;
7969 		load_attr.func_info_rec_size = prog->func_info_rec_size;
7970 		load_attr.func_info_cnt = prog->func_info_cnt;
7971 		load_attr.line_info = prog->line_info;
7972 		load_attr.line_info_rec_size = prog->line_info_rec_size;
7973 		load_attr.line_info_cnt = prog->line_info_cnt;
7974 	}
7975 	load_attr.log_level = log_level;
7976 	load_attr.prog_flags = prog->prog_flags;
7977 	load_attr.fd_array = obj->fd_array;
7978 
7979 	load_attr.token_fd = obj->token_fd;
7980 	if (obj->token_fd)
7981 		load_attr.prog_flags |= BPF_F_TOKEN_FD;
7982 
7983 	/* adjust load_attr if sec_def provides custom preload callback */
7984 	if (prog->sec_def && prog->sec_def->prog_prepare_load_fn) {
7985 		err = prog->sec_def->prog_prepare_load_fn(prog, &load_attr, prog->sec_def->cookie);
7986 		if (err < 0) {
7987 			pr_warn("prog '%s': failed to prepare load attributes: %s\n",
7988 				prog->name, errstr(err));
7989 			return err;
7990 		}
7991 		insns = prog->insns;
7992 		insns_cnt = prog->insns_cnt;
7993 	}
7994 
7995 	if (obj->gen_loader) {
7996 		bpf_gen__prog_load(obj->gen_loader, prog->type, prog->name,
7997 				   license, insns, insns_cnt, &load_attr,
7998 				   prog - obj->programs);
7999 		*prog_fd = -1;
8000 		return 0;
8001 	}
8002 
8003 retry_load:
8004 	/* if log_level is zero, we don't request logs initially even if
8005 	 * custom log_buf is specified; if the program load fails, then we'll
8006 	 * bump log_level to 1 and use either custom log_buf or we'll allocate
8007 	 * our own and retry the load to get details on what failed
8008 	 */
8009 	if (log_level) {
8010 		if (prog->log_buf) {
8011 			log_buf = prog->log_buf;
8012 			log_buf_size = prog->log_size;
8013 			own_log_buf = false;
8014 		} else if (obj->log_buf) {
8015 			log_buf = obj->log_buf;
8016 			log_buf_size = obj->log_size;
8017 			own_log_buf = false;
8018 		} else {
8019 			log_buf_size = max((size_t)BPF_LOG_BUF_SIZE, log_buf_size * 2);
8020 			tmp = realloc(log_buf, log_buf_size);
8021 			if (!tmp) {
8022 				ret = -ENOMEM;
8023 				goto out;
8024 			}
8025 			log_buf = tmp;
8026 			log_buf[0] = '\0';
8027 			own_log_buf = true;
8028 		}
8029 	}
8030 
8031 	load_attr.log_buf = log_buf;
8032 	load_attr.log_size = log_buf_size;
8033 	load_attr.log_level = log_level;
8034 
8035 	ret = bpf_prog_load(prog->type, prog_name, license, insns, insns_cnt, &load_attr);
8036 	if (ret >= 0) {
8037 		if (log_level && own_log_buf) {
8038 			pr_debug("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
8039 				 prog->name, log_buf);
8040 		}
8041 
8042 		if (obj->has_rodata && kernel_supports(obj, FEAT_PROG_BIND_MAP)) {
8043 			struct bpf_map *map;
8044 			int i;
8045 
8046 			for (i = 0; i < obj->nr_maps; i++) {
8047 				map = &prog->obj->maps[i];
8048 				if (map->libbpf_type != LIBBPF_MAP_RODATA)
8049 					continue;
8050 
8051 				if (bpf_prog_bind_map(ret, map->fd, NULL)) {
8052 					pr_warn("prog '%s': failed to bind map '%s': %s\n",
8053 						prog->name, map->real_name, errstr(errno));
8054 					/* Don't fail hard if can't bind rodata. */
8055 				}
8056 			}
8057 		}
8058 
8059 		*prog_fd = ret;
8060 		ret = 0;
8061 		goto out;
8062 	}
8063 
8064 	if (log_level == 0) {
8065 		log_level = 1;
8066 		goto retry_load;
8067 	}
8068 	/* On ENOSPC, increase log buffer size and retry, unless custom
8069 	 * log_buf is specified.
8070 	 * Be careful to not overflow u32, though. Kernel's log buf size limit
8071 	 * isn't part of UAPI so it can always be bumped to full 4GB. So don't
8072 	 * multiply by 2 unless we are sure we'll fit within 32 bits.
8073 	 * Currently, we'll get -EINVAL when we reach (UINT_MAX >> 2).
8074 	 */
8075 	if (own_log_buf && errno == ENOSPC && log_buf_size <= UINT_MAX / 2)
8076 		goto retry_load;
8077 
8078 	ret = -errno;
8079 
8080 	/* post-process verifier log to improve error descriptions */
8081 	fixup_verifier_log(prog, log_buf, log_buf_size);
8082 
8083 	pr_warn("prog '%s': BPF program load failed: %s\n", prog->name, errstr(errno));
8084 	pr_perm_msg(ret);
8085 
8086 	if (own_log_buf && log_buf && log_buf[0] != '\0') {
8087 		pr_warn("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
8088 			prog->name, log_buf);
8089 	}
8090 
8091 out:
8092 	if (own_log_buf)
8093 		free(log_buf);
8094 	return ret;
8095 }
8096 
8097 static char *find_prev_line(char *buf, char *cur)
8098 {
8099 	char *p;
8100 
8101 	if (cur == buf) /* end of a log buf */
8102 		return NULL;
8103 
8104 	p = cur - 1;
8105 	while (p - 1 >= buf && *(p - 1) != '\n')
8106 		p--;
8107 
8108 	return p;
8109 }
8110 
8111 static void patch_log(char *buf, size_t buf_sz, size_t log_sz,
8112 		      char *orig, size_t orig_sz, const char *patch)
8113 {
8114 	/* size of the remaining log content to the right from the to-be-replaced part */
8115 	size_t rem_sz = (buf + log_sz) - (orig + orig_sz);
8116 	size_t patch_sz = strlen(patch);
8117 
8118 	if (patch_sz != orig_sz) {
8119 		/* If patch line(s) are longer than original piece of verifier log,
8120 		 * shift log contents by (patch_sz - orig_sz) bytes to the right
8121 		 * starting from after to-be-replaced part of the log.
8122 		 *
8123 		 * If patch line(s) are shorter than original piece of verifier log,
8124 		 * shift log contents by (orig_sz - patch_sz) bytes to the left
8125 		 * starting from after to-be-replaced part of the log
8126 		 *
8127 		 * We need to be careful about not overflowing available
8128 		 * buf_sz capacity. If that's the case, we'll truncate the end
8129 		 * of the original log, as necessary.
8130 		 */
8131 		if (patch_sz > orig_sz) {
8132 			if (orig + patch_sz >= buf + buf_sz) {
8133 				/* patch is big enough to cover remaining space completely */
8134 				patch_sz -= (orig + patch_sz) - (buf + buf_sz) + 1;
8135 				rem_sz = 0;
8136 			} else if (patch_sz - orig_sz > buf_sz - log_sz) {
8137 				/* patch causes part of remaining log to be truncated */
8138 				rem_sz -= (patch_sz - orig_sz) - (buf_sz - log_sz);
8139 			}
8140 		}
8141 		/* shift remaining log to the right by calculated amount */
8142 		memmove(orig + patch_sz, orig + orig_sz, rem_sz);
8143 	}
8144 
8145 	memcpy(orig, patch, patch_sz);
8146 }
8147 
8148 static void fixup_log_failed_core_relo(struct bpf_program *prog,
8149 				       char *buf, size_t buf_sz, size_t log_sz,
8150 				       char *line1, char *line2, char *line3)
8151 {
8152 	/* Expected log for failed and not properly guarded CO-RE relocation:
8153 	 * line1 -> 123: (85) call unknown#195896080
8154 	 * line2 -> invalid func unknown#195896080
8155 	 * line3 -> <anything else or end of buffer>
8156 	 *
8157 	 * "123" is the index of the instruction that was poisoned. We extract
8158 	 * instruction index to find corresponding CO-RE relocation and
8159 	 * replace this part of the log with more relevant information about
8160 	 * failed CO-RE relocation.
8161 	 */
8162 	const struct bpf_core_relo *relo;
8163 	struct bpf_core_spec spec;
8164 	char patch[512], spec_buf[256];
8165 	int insn_idx, err, spec_len;
8166 
8167 	if (sscanf(line1, "%d: (%*d) call unknown#195896080\n", &insn_idx) != 1)
8168 		return;
8169 
8170 	relo = find_relo_core(prog, insn_idx);
8171 	if (!relo)
8172 		return;
8173 
8174 	err = bpf_core_parse_spec(prog->name, prog->obj->btf, relo, &spec);
8175 	if (err)
8176 		return;
8177 
8178 	spec_len = bpf_core_format_spec(spec_buf, sizeof(spec_buf), &spec);
8179 	snprintf(patch, sizeof(patch),
8180 		 "%d: <invalid CO-RE relocation>\n"
8181 		 "failed to resolve CO-RE relocation %s%s\n",
8182 		 insn_idx, spec_buf, spec_len >= sizeof(spec_buf) ? "..." : "");
8183 
8184 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
8185 }
8186 
8187 static void fixup_log_missing_map_load(struct bpf_program *prog,
8188 				       char *buf, size_t buf_sz, size_t log_sz,
8189 				       char *line1, char *line2, char *line3)
8190 {
8191 	/* Expected log for failed and not properly guarded map reference:
8192 	 * line1 -> 123: (85) call unknown#2001000345
8193 	 * line2 -> invalid func unknown#2001000345
8194 	 * line3 -> <anything else or end of buffer>
8195 	 *
8196 	 * "123" is the index of the instruction that was poisoned.
8197 	 * "345" in "2001000345" is a map index in obj->maps to fetch map name.
8198 	 */
8199 	struct bpf_object *obj = prog->obj;
8200 	const struct bpf_map *map;
8201 	int insn_idx, map_idx;
8202 	char patch[128];
8203 
8204 	if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &map_idx) != 2)
8205 		return;
8206 
8207 	map_idx -= POISON_LDIMM64_MAP_BASE;
8208 	if (map_idx < 0 || map_idx >= obj->nr_maps)
8209 		return;
8210 	map = &obj->maps[map_idx];
8211 
8212 	snprintf(patch, sizeof(patch),
8213 		 "%d: <invalid BPF map reference>\n"
8214 		 "BPF map '%s' is referenced but wasn't created\n",
8215 		 insn_idx, map->name);
8216 
8217 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
8218 }
8219 
8220 static void fixup_log_missing_kfunc_call(struct bpf_program *prog,
8221 					 char *buf, size_t buf_sz, size_t log_sz,
8222 					 char *line1, char *line2, char *line3)
8223 {
8224 	/* Expected log for failed and not properly guarded kfunc call:
8225 	 * line1 -> 123: (85) call unknown#2002000345
8226 	 * line2 -> invalid func unknown#2002000345
8227 	 * line3 -> <anything else or end of buffer>
8228 	 *
8229 	 * "123" is the index of the instruction that was poisoned.
8230 	 * "345" in "2002000345" is an extern index in obj->externs to fetch kfunc name.
8231 	 */
8232 	struct bpf_object *obj = prog->obj;
8233 	const struct extern_desc *ext;
8234 	int insn_idx, ext_idx;
8235 	char patch[128];
8236 
8237 	if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &ext_idx) != 2)
8238 		return;
8239 
8240 	ext_idx -= POISON_CALL_KFUNC_BASE;
8241 	if (ext_idx < 0 || ext_idx >= obj->nr_extern)
8242 		return;
8243 	ext = &obj->externs[ext_idx];
8244 
8245 	snprintf(patch, sizeof(patch),
8246 		 "%d: <invalid kfunc call>\n"
8247 		 "kfunc '%s' is referenced but wasn't resolved\n",
8248 		 insn_idx, ext->name);
8249 
8250 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
8251 }
8252 
8253 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz)
8254 {
8255 	/* look for familiar error patterns in last N lines of the log */
8256 	const size_t max_last_line_cnt = 10;
8257 	char *prev_line, *cur_line, *next_line;
8258 	size_t log_sz;
8259 	int i;
8260 
8261 	if (!buf)
8262 		return;
8263 
8264 	log_sz = strlen(buf) + 1;
8265 	next_line = buf + log_sz - 1;
8266 
8267 	for (i = 0; i < max_last_line_cnt; i++, next_line = cur_line) {
8268 		cur_line = find_prev_line(buf, next_line);
8269 		if (!cur_line)
8270 			return;
8271 
8272 		if (str_has_pfx(cur_line, "invalid func unknown#195896080\n")) {
8273 			prev_line = find_prev_line(buf, cur_line);
8274 			if (!prev_line)
8275 				continue;
8276 
8277 			/* failed CO-RE relocation case */
8278 			fixup_log_failed_core_relo(prog, buf, buf_sz, log_sz,
8279 						   prev_line, cur_line, next_line);
8280 			return;
8281 		} else if (str_has_pfx(cur_line, "invalid func unknown#"POISON_LDIMM64_MAP_PFX)) {
8282 			prev_line = find_prev_line(buf, cur_line);
8283 			if (!prev_line)
8284 				continue;
8285 
8286 			/* reference to uncreated BPF map */
8287 			fixup_log_missing_map_load(prog, buf, buf_sz, log_sz,
8288 						   prev_line, cur_line, next_line);
8289 			return;
8290 		} else if (str_has_pfx(cur_line, "invalid func unknown#"POISON_CALL_KFUNC_PFX)) {
8291 			prev_line = find_prev_line(buf, cur_line);
8292 			if (!prev_line)
8293 				continue;
8294 
8295 			/* reference to unresolved kfunc */
8296 			fixup_log_missing_kfunc_call(prog, buf, buf_sz, log_sz,
8297 						     prev_line, cur_line, next_line);
8298 			return;
8299 		}
8300 	}
8301 }
8302 
8303 static int bpf_program_record_relos(struct bpf_program *prog)
8304 {
8305 	struct bpf_object *obj = prog->obj;
8306 	int i;
8307 
8308 	for (i = 0; i < prog->nr_reloc; i++) {
8309 		struct reloc_desc *relo = &prog->reloc_desc[i];
8310 		struct extern_desc *ext = &obj->externs[relo->ext_idx];
8311 		int kind;
8312 
8313 		switch (relo->type) {
8314 		case RELO_EXTERN_LD64:
8315 			if (ext->type != EXT_KSYM)
8316 				continue;
8317 			kind = btf_is_var(btf__type_by_id(obj->btf, ext->btf_id)) ?
8318 				BTF_KIND_VAR : BTF_KIND_FUNC;
8319 			bpf_gen__record_extern(obj->gen_loader, ext->name,
8320 					       ext->is_weak, !ext->ksym.type_id,
8321 					       true, kind, relo->insn_idx);
8322 			break;
8323 		case RELO_EXTERN_CALL:
8324 			bpf_gen__record_extern(obj->gen_loader, ext->name,
8325 					       ext->is_weak, false, false, BTF_KIND_FUNC,
8326 					       relo->insn_idx);
8327 			break;
8328 		case RELO_CORE: {
8329 			struct bpf_core_relo cr = {
8330 				.insn_off = relo->insn_idx * 8,
8331 				.type_id = relo->core_relo->type_id,
8332 				.access_str_off = relo->core_relo->access_str_off,
8333 				.kind = relo->core_relo->kind,
8334 			};
8335 
8336 			bpf_gen__record_relo_core(obj->gen_loader, &cr);
8337 			break;
8338 		}
8339 		default:
8340 			continue;
8341 		}
8342 	}
8343 	return 0;
8344 }
8345 
8346 static int
8347 bpf_object__load_progs(struct bpf_object *obj, int log_level)
8348 {
8349 	struct bpf_program *prog;
8350 	size_t i;
8351 	int err;
8352 
8353 	for (i = 0; i < obj->nr_programs; i++) {
8354 		prog = &obj->programs[i];
8355 		if (prog_is_subprog(obj, prog))
8356 			continue;
8357 		if (!prog->autoload) {
8358 			pr_debug("prog '%s': skipped loading\n", prog->name);
8359 			continue;
8360 		}
8361 		prog->log_level |= log_level;
8362 
8363 		if (obj->gen_loader)
8364 			bpf_program_record_relos(prog);
8365 
8366 		err = bpf_object_load_prog(obj, prog, prog->insns, prog->insns_cnt,
8367 					   obj->license, obj->kern_version, &prog->fd);
8368 		if (err) {
8369 			pr_warn("prog '%s': failed to load: %s\n", prog->name, errstr(err));
8370 			return err;
8371 		}
8372 	}
8373 
8374 	bpf_object__free_relocs(obj);
8375 	return 0;
8376 }
8377 
8378 static int bpf_object_prepare_progs(struct bpf_object *obj)
8379 {
8380 	struct bpf_program *prog;
8381 	size_t i;
8382 	int err;
8383 
8384 	for (i = 0; i < obj->nr_programs; i++) {
8385 		prog = &obj->programs[i];
8386 		err = bpf_object__sanitize_prog(obj, prog);
8387 		if (err)
8388 			return err;
8389 	}
8390 	return 0;
8391 }
8392 
8393 static const struct bpf_sec_def *find_sec_def(const char *sec_name);
8394 
8395 static int bpf_object_init_progs(struct bpf_object *obj, const struct bpf_object_open_opts *opts)
8396 {
8397 	struct bpf_program *prog;
8398 	int err;
8399 
8400 	bpf_object__for_each_program(prog, obj) {
8401 		prog->sec_def = find_sec_def(prog->sec_name);
8402 		if (!prog->sec_def) {
8403 			/* couldn't guess, but user might manually specify */
8404 			pr_debug("prog '%s': unrecognized ELF section name '%s'\n",
8405 				prog->name, prog->sec_name);
8406 			continue;
8407 		}
8408 
8409 		prog->type = prog->sec_def->prog_type;
8410 		prog->expected_attach_type = prog->sec_def->expected_attach_type;
8411 
8412 		/* sec_def can have custom callback which should be called
8413 		 * after bpf_program is initialized to adjust its properties
8414 		 */
8415 		if (prog->sec_def->prog_setup_fn) {
8416 			err = prog->sec_def->prog_setup_fn(prog, prog->sec_def->cookie);
8417 			if (err < 0) {
8418 				pr_warn("prog '%s': failed to initialize: %s\n",
8419 					prog->name, errstr(err));
8420 				return err;
8421 			}
8422 		}
8423 	}
8424 
8425 	return 0;
8426 }
8427 
8428 static struct bpf_object *bpf_object_open(const char *path, const void *obj_buf, size_t obj_buf_sz,
8429 					  const char *obj_name,
8430 					  const struct bpf_object_open_opts *opts)
8431 {
8432 	const char *kconfig, *btf_tmp_path, *token_path;
8433 	struct bpf_object *obj;
8434 	int err;
8435 	char *log_buf;
8436 	size_t log_size;
8437 	__u32 log_level;
8438 
8439 	if (obj_buf && !obj_name)
8440 		return ERR_PTR(-EINVAL);
8441 
8442 	if (elf_version(EV_CURRENT) == EV_NONE) {
8443 		pr_warn("failed to init libelf for %s\n",
8444 			path ? : "(mem buf)");
8445 		return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
8446 	}
8447 
8448 	if (!OPTS_VALID(opts, bpf_object_open_opts))
8449 		return ERR_PTR(-EINVAL);
8450 
8451 	obj_name = OPTS_GET(opts, object_name, NULL) ?: obj_name;
8452 	if (obj_buf) {
8453 		path = obj_name;
8454 		pr_debug("loading object '%s' from buffer\n", obj_name);
8455 	} else {
8456 		pr_debug("loading object from %s\n", path);
8457 	}
8458 
8459 	log_buf = OPTS_GET(opts, kernel_log_buf, NULL);
8460 	log_size = OPTS_GET(opts, kernel_log_size, 0);
8461 	log_level = OPTS_GET(opts, kernel_log_level, 0);
8462 	if (log_size > UINT_MAX)
8463 		return ERR_PTR(-EINVAL);
8464 	if (log_size && !log_buf)
8465 		return ERR_PTR(-EINVAL);
8466 
8467 	token_path = OPTS_GET(opts, bpf_token_path, NULL);
8468 	/* if user didn't specify bpf_token_path explicitly, check if
8469 	 * LIBBPF_BPF_TOKEN_PATH envvar was set and treat it as bpf_token_path
8470 	 * option
8471 	 */
8472 	if (!token_path)
8473 		token_path = getenv("LIBBPF_BPF_TOKEN_PATH");
8474 	if (token_path && strlen(token_path) >= PATH_MAX)
8475 		return ERR_PTR(-ENAMETOOLONG);
8476 
8477 	obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
8478 	if (IS_ERR(obj))
8479 		return obj;
8480 
8481 	obj->log_buf = log_buf;
8482 	obj->log_size = log_size;
8483 	obj->log_level = log_level;
8484 
8485 	if (token_path) {
8486 		obj->token_path = strdup(token_path);
8487 		if (!obj->token_path) {
8488 			err = -ENOMEM;
8489 			goto out;
8490 		}
8491 	}
8492 
8493 	btf_tmp_path = OPTS_GET(opts, btf_custom_path, NULL);
8494 	if (btf_tmp_path) {
8495 		if (strlen(btf_tmp_path) >= PATH_MAX) {
8496 			err = -ENAMETOOLONG;
8497 			goto out;
8498 		}
8499 		obj->btf_custom_path = strdup(btf_tmp_path);
8500 		if (!obj->btf_custom_path) {
8501 			err = -ENOMEM;
8502 			goto out;
8503 		}
8504 	}
8505 
8506 	kconfig = OPTS_GET(opts, kconfig, NULL);
8507 	if (kconfig) {
8508 		obj->kconfig = strdup(kconfig);
8509 		if (!obj->kconfig) {
8510 			err = -ENOMEM;
8511 			goto out;
8512 		}
8513 	}
8514 
8515 	err = bpf_object__elf_init(obj);
8516 	err = err ? : bpf_object__elf_collect(obj);
8517 	err = err ? : bpf_object__collect_externs(obj);
8518 	err = err ? : bpf_object_fixup_btf(obj);
8519 	err = err ? : bpf_object__init_maps(obj, opts);
8520 	err = err ? : bpf_object_init_progs(obj, opts);
8521 	err = err ? : bpf_object__collect_relos(obj);
8522 	if (err)
8523 		goto out;
8524 
8525 	bpf_object__elf_finish(obj);
8526 
8527 	return obj;
8528 out:
8529 	bpf_object__close(obj);
8530 	return ERR_PTR(err);
8531 }
8532 
8533 struct bpf_object *
8534 bpf_object__open_file(const char *path, const struct bpf_object_open_opts *opts)
8535 {
8536 	if (!path)
8537 		return libbpf_err_ptr(-EINVAL);
8538 
8539 	return libbpf_ptr(bpf_object_open(path, NULL, 0, NULL, opts));
8540 }
8541 
8542 struct bpf_object *bpf_object__open(const char *path)
8543 {
8544 	return bpf_object__open_file(path, NULL);
8545 }
8546 
8547 struct bpf_object *
8548 bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
8549 		     const struct bpf_object_open_opts *opts)
8550 {
8551 	char tmp_name[64];
8552 
8553 	if (!obj_buf || obj_buf_sz == 0)
8554 		return libbpf_err_ptr(-EINVAL);
8555 
8556 	/* create a (quite useless) default "name" for this memory buffer object */
8557 	snprintf(tmp_name, sizeof(tmp_name), "%lx-%zx", (unsigned long)obj_buf, obj_buf_sz);
8558 
8559 	return libbpf_ptr(bpf_object_open(NULL, obj_buf, obj_buf_sz, tmp_name, opts));
8560 }
8561 
8562 static int bpf_object_unload(struct bpf_object *obj)
8563 {
8564 	size_t i;
8565 
8566 	if (!obj)
8567 		return libbpf_err(-EINVAL);
8568 
8569 	for (i = 0; i < obj->nr_maps; i++) {
8570 		zclose(obj->maps[i].fd);
8571 		if (obj->maps[i].st_ops)
8572 			zfree(&obj->maps[i].st_ops->kern_vdata);
8573 	}
8574 
8575 	for (i = 0; i < obj->nr_programs; i++)
8576 		bpf_program__unload(&obj->programs[i]);
8577 
8578 	return 0;
8579 }
8580 
8581 static int bpf_object__sanitize_maps(struct bpf_object *obj)
8582 {
8583 	struct bpf_map *m;
8584 
8585 	bpf_object__for_each_map(m, obj) {
8586 		if (!bpf_map__is_internal(m))
8587 			continue;
8588 		if (!kernel_supports(obj, FEAT_ARRAY_MMAP))
8589 			m->def.map_flags &= ~BPF_F_MMAPABLE;
8590 	}
8591 
8592 	return 0;
8593 }
8594 
8595 typedef int (*kallsyms_cb_t)(unsigned long long sym_addr, char sym_type,
8596 			     const char *sym_name, void *ctx);
8597 
8598 static int libbpf_kallsyms_parse(kallsyms_cb_t cb, void *ctx)
8599 {
8600 	char sym_type, sym_name[500];
8601 	unsigned long long sym_addr;
8602 	int ret, err = 0;
8603 	FILE *f;
8604 
8605 	f = fopen("/proc/kallsyms", "re");
8606 	if (!f) {
8607 		err = -errno;
8608 		pr_warn("failed to open /proc/kallsyms: %s\n", errstr(err));
8609 		return err;
8610 	}
8611 
8612 	while (true) {
8613 		ret = fscanf(f, "%llx %c %499s%*[^\n]\n",
8614 			     &sym_addr, &sym_type, sym_name);
8615 		if (ret == EOF && feof(f))
8616 			break;
8617 		if (ret != 3) {
8618 			pr_warn("failed to read kallsyms entry: %d\n", ret);
8619 			err = -EINVAL;
8620 			break;
8621 		}
8622 
8623 		err = cb(sym_addr, sym_type, sym_name, ctx);
8624 		if (err)
8625 			break;
8626 	}
8627 
8628 	fclose(f);
8629 	return err;
8630 }
8631 
8632 static int kallsyms_cb(unsigned long long sym_addr, char sym_type,
8633 		       const char *sym_name, void *ctx)
8634 {
8635 	struct bpf_object *obj = ctx;
8636 	const struct btf_type *t;
8637 	struct extern_desc *ext;
8638 	const char *res;
8639 
8640 	res = strstr(sym_name, ".llvm.");
8641 	if (sym_type == 'd' && res)
8642 		ext = find_extern_by_name_with_len(obj, sym_name, res - sym_name);
8643 	else
8644 		ext = find_extern_by_name(obj, sym_name);
8645 	if (!ext || ext->type != EXT_KSYM)
8646 		return 0;
8647 
8648 	t = btf__type_by_id(obj->btf, ext->btf_id);
8649 	if (!btf_is_var(t))
8650 		return 0;
8651 
8652 	if (ext->is_set && ext->ksym.addr != sym_addr) {
8653 		pr_warn("extern (ksym) '%s': resolution is ambiguous: 0x%llx or 0x%llx\n",
8654 			sym_name, ext->ksym.addr, sym_addr);
8655 		return -EINVAL;
8656 	}
8657 	if (!ext->is_set) {
8658 		ext->is_set = true;
8659 		ext->ksym.addr = sym_addr;
8660 		pr_debug("extern (ksym) '%s': set to 0x%llx\n", sym_name, sym_addr);
8661 	}
8662 	return 0;
8663 }
8664 
8665 static int bpf_object__read_kallsyms_file(struct bpf_object *obj)
8666 {
8667 	return libbpf_kallsyms_parse(kallsyms_cb, obj);
8668 }
8669 
8670 static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
8671 			    __u16 kind, struct btf **res_btf,
8672 			    struct module_btf **res_mod_btf)
8673 {
8674 	struct module_btf *mod_btf;
8675 	struct btf *btf;
8676 	int i, id, err;
8677 
8678 	btf = obj->btf_vmlinux;
8679 	mod_btf = NULL;
8680 	id = btf__find_by_name_kind(btf, ksym_name, kind);
8681 
8682 	if (id == -ENOENT) {
8683 		err = load_module_btfs(obj);
8684 		if (err)
8685 			return err;
8686 
8687 		for (i = 0; i < obj->btf_module_cnt; i++) {
8688 			/* we assume module_btf's BTF FD is always >0 */
8689 			mod_btf = &obj->btf_modules[i];
8690 			btf = mod_btf->btf;
8691 			id = btf__find_by_name_kind_own(btf, ksym_name, kind);
8692 			if (id != -ENOENT)
8693 				break;
8694 		}
8695 	}
8696 	if (id <= 0)
8697 		return -ESRCH;
8698 
8699 	*res_btf = btf;
8700 	*res_mod_btf = mod_btf;
8701 	return id;
8702 }
8703 
8704 static int bpf_object__resolve_ksym_var_btf_id(struct bpf_object *obj,
8705 					       struct extern_desc *ext)
8706 {
8707 	const struct btf_type *targ_var, *targ_type;
8708 	__u32 targ_type_id, local_type_id;
8709 	struct module_btf *mod_btf = NULL;
8710 	const char *targ_var_name;
8711 	struct btf *btf = NULL;
8712 	int id, err;
8713 
8714 	id = find_ksym_btf_id(obj, ext->name, BTF_KIND_VAR, &btf, &mod_btf);
8715 	if (id < 0) {
8716 		if (id == -ESRCH && ext->is_weak)
8717 			return 0;
8718 		pr_warn("extern (var ksym) '%s': not found in kernel BTF\n",
8719 			ext->name);
8720 		return id;
8721 	}
8722 
8723 	/* find local type_id */
8724 	local_type_id = ext->ksym.type_id;
8725 
8726 	/* find target type_id */
8727 	targ_var = btf__type_by_id(btf, id);
8728 	targ_var_name = btf__name_by_offset(btf, targ_var->name_off);
8729 	targ_type = skip_mods_and_typedefs(btf, targ_var->type, &targ_type_id);
8730 
8731 	err = bpf_core_types_are_compat(obj->btf, local_type_id,
8732 					btf, targ_type_id);
8733 	if (err <= 0) {
8734 		const struct btf_type *local_type;
8735 		const char *targ_name, *local_name;
8736 
8737 		local_type = btf__type_by_id(obj->btf, local_type_id);
8738 		local_name = btf__name_by_offset(obj->btf, local_type->name_off);
8739 		targ_name = btf__name_by_offset(btf, targ_type->name_off);
8740 
8741 		pr_warn("extern (var ksym) '%s': incompatible types, expected [%d] %s %s, but kernel has [%d] %s %s\n",
8742 			ext->name, local_type_id,
8743 			btf_kind_str(local_type), local_name, targ_type_id,
8744 			btf_kind_str(targ_type), targ_name);
8745 		return -EINVAL;
8746 	}
8747 
8748 	ext->is_set = true;
8749 	ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
8750 	ext->ksym.kernel_btf_id = id;
8751 	pr_debug("extern (var ksym) '%s': resolved to [%d] %s %s\n",
8752 		 ext->name, id, btf_kind_str(targ_var), targ_var_name);
8753 
8754 	return 0;
8755 }
8756 
8757 static int bpf_object__resolve_ksym_func_btf_id(struct bpf_object *obj,
8758 						struct extern_desc *ext)
8759 {
8760 	int local_func_proto_id, kfunc_proto_id, kfunc_id;
8761 	struct module_btf *mod_btf = NULL;
8762 	const struct btf_type *kern_func;
8763 	struct btf *kern_btf = NULL;
8764 	int ret;
8765 
8766 	local_func_proto_id = ext->ksym.type_id;
8767 
8768 	kfunc_id = find_ksym_btf_id(obj, ext->essent_name ?: ext->name, BTF_KIND_FUNC, &kern_btf,
8769 				    &mod_btf);
8770 	if (kfunc_id < 0) {
8771 		if (kfunc_id == -ESRCH && ext->is_weak)
8772 			return 0;
8773 		pr_warn("extern (func ksym) '%s': not found in kernel or module BTFs\n",
8774 			ext->name);
8775 		return kfunc_id;
8776 	}
8777 
8778 	kern_func = btf__type_by_id(kern_btf, kfunc_id);
8779 	kfunc_proto_id = kern_func->type;
8780 
8781 	ret = bpf_core_types_are_compat(obj->btf, local_func_proto_id,
8782 					kern_btf, kfunc_proto_id);
8783 	if (ret <= 0) {
8784 		if (ext->is_weak)
8785 			return 0;
8786 
8787 		pr_warn("extern (func ksym) '%s': func_proto [%d] incompatible with %s [%d]\n",
8788 			ext->name, local_func_proto_id,
8789 			mod_btf ? mod_btf->name : "vmlinux", kfunc_proto_id);
8790 		return -EINVAL;
8791 	}
8792 
8793 	/* set index for module BTF fd in fd_array, if unset */
8794 	if (mod_btf && !mod_btf->fd_array_idx) {
8795 		/* insn->off is s16 */
8796 		if (obj->fd_array_cnt == INT16_MAX) {
8797 			pr_warn("extern (func ksym) '%s': module BTF fd index %d too big to fit in bpf_insn offset\n",
8798 				ext->name, mod_btf->fd_array_idx);
8799 			return -E2BIG;
8800 		}
8801 		/* Cannot use index 0 for module BTF fd */
8802 		if (!obj->fd_array_cnt)
8803 			obj->fd_array_cnt = 1;
8804 
8805 		ret = libbpf_ensure_mem((void **)&obj->fd_array, &obj->fd_array_cap, sizeof(int),
8806 					obj->fd_array_cnt + 1);
8807 		if (ret)
8808 			return ret;
8809 		mod_btf->fd_array_idx = obj->fd_array_cnt;
8810 		/* we assume module BTF FD is always >0 */
8811 		obj->fd_array[obj->fd_array_cnt++] = mod_btf->fd;
8812 	}
8813 
8814 	ext->is_set = true;
8815 	ext->ksym.kernel_btf_id = kfunc_id;
8816 	ext->ksym.btf_fd_idx = mod_btf ? mod_btf->fd_array_idx : 0;
8817 	/* Also set kernel_btf_obj_fd to make sure that bpf_object__relocate_data()
8818 	 * populates FD into ld_imm64 insn when it's used to point to kfunc.
8819 	 * {kernel_btf_id, btf_fd_idx} -> fixup bpf_call.
8820 	 * {kernel_btf_id, kernel_btf_obj_fd} -> fixup ld_imm64.
8821 	 */
8822 	ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
8823 	pr_debug("extern (func ksym) '%s': resolved to %s [%d]\n",
8824 		 ext->name, mod_btf ? mod_btf->name : "vmlinux", kfunc_id);
8825 
8826 	return 0;
8827 }
8828 
8829 static int bpf_object__resolve_ksyms_btf_id(struct bpf_object *obj)
8830 {
8831 	const struct btf_type *t;
8832 	struct extern_desc *ext;
8833 	int i, err;
8834 
8835 	for (i = 0; i < obj->nr_extern; i++) {
8836 		ext = &obj->externs[i];
8837 		if (ext->type != EXT_KSYM || !ext->ksym.type_id)
8838 			continue;
8839 
8840 		if (obj->gen_loader) {
8841 			ext->is_set = true;
8842 			ext->ksym.kernel_btf_obj_fd = 0;
8843 			ext->ksym.kernel_btf_id = 0;
8844 			continue;
8845 		}
8846 		t = btf__type_by_id(obj->btf, ext->btf_id);
8847 		if (btf_is_var(t))
8848 			err = bpf_object__resolve_ksym_var_btf_id(obj, ext);
8849 		else
8850 			err = bpf_object__resolve_ksym_func_btf_id(obj, ext);
8851 		if (err)
8852 			return err;
8853 	}
8854 	return 0;
8855 }
8856 
8857 static int bpf_object__resolve_externs(struct bpf_object *obj,
8858 				       const char *extra_kconfig)
8859 {
8860 	bool need_config = false, need_kallsyms = false;
8861 	bool need_vmlinux_btf = false;
8862 	struct extern_desc *ext;
8863 	void *kcfg_data = NULL;
8864 	int err, i;
8865 
8866 	if (obj->nr_extern == 0)
8867 		return 0;
8868 
8869 	if (obj->kconfig_map_idx >= 0)
8870 		kcfg_data = obj->maps[obj->kconfig_map_idx].mmaped;
8871 
8872 	for (i = 0; i < obj->nr_extern; i++) {
8873 		ext = &obj->externs[i];
8874 
8875 		if (ext->type == EXT_KSYM) {
8876 			if (ext->ksym.type_id)
8877 				need_vmlinux_btf = true;
8878 			else
8879 				need_kallsyms = true;
8880 			continue;
8881 		} else if (ext->type == EXT_KCFG) {
8882 			void *ext_ptr = kcfg_data + ext->kcfg.data_off;
8883 			__u64 value = 0;
8884 
8885 			/* Kconfig externs need actual /proc/config.gz */
8886 			if (str_has_pfx(ext->name, "CONFIG_")) {
8887 				need_config = true;
8888 				continue;
8889 			}
8890 
8891 			/* Virtual kcfg externs are customly handled by libbpf */
8892 			if (strcmp(ext->name, "LINUX_KERNEL_VERSION") == 0) {
8893 				value = get_kernel_version();
8894 				if (!value) {
8895 					pr_warn("extern (kcfg) '%s': failed to get kernel version\n", ext->name);
8896 					return -EINVAL;
8897 				}
8898 			} else if (strcmp(ext->name, "LINUX_HAS_BPF_COOKIE") == 0) {
8899 				value = kernel_supports(obj, FEAT_BPF_COOKIE);
8900 			} else if (strcmp(ext->name, "LINUX_HAS_SYSCALL_WRAPPER") == 0) {
8901 				value = kernel_supports(obj, FEAT_SYSCALL_WRAPPER);
8902 			} else if (!str_has_pfx(ext->name, "LINUX_") || !ext->is_weak) {
8903 				/* Currently libbpf supports only CONFIG_ and LINUX_ prefixed
8904 				 * __kconfig externs, where LINUX_ ones are virtual and filled out
8905 				 * customly by libbpf (their values don't come from Kconfig).
8906 				 * If LINUX_xxx variable is not recognized by libbpf, but is marked
8907 				 * __weak, it defaults to zero value, just like for CONFIG_xxx
8908 				 * externs.
8909 				 */
8910 				pr_warn("extern (kcfg) '%s': unrecognized virtual extern\n", ext->name);
8911 				return -EINVAL;
8912 			}
8913 
8914 			err = set_kcfg_value_num(ext, ext_ptr, value);
8915 			if (err)
8916 				return err;
8917 			pr_debug("extern (kcfg) '%s': set to 0x%llx\n",
8918 				 ext->name, (long long)value);
8919 		} else {
8920 			pr_warn("extern '%s': unrecognized extern kind\n", ext->name);
8921 			return -EINVAL;
8922 		}
8923 	}
8924 	if (need_config && extra_kconfig) {
8925 		err = bpf_object__read_kconfig_mem(obj, extra_kconfig, kcfg_data);
8926 		if (err)
8927 			return -EINVAL;
8928 		need_config = false;
8929 		for (i = 0; i < obj->nr_extern; i++) {
8930 			ext = &obj->externs[i];
8931 			if (ext->type == EXT_KCFG && !ext->is_set) {
8932 				need_config = true;
8933 				break;
8934 			}
8935 		}
8936 	}
8937 	if (need_config) {
8938 		err = bpf_object__read_kconfig_file(obj, kcfg_data);
8939 		if (err)
8940 			return -EINVAL;
8941 	}
8942 	if (need_kallsyms) {
8943 		err = bpf_object__read_kallsyms_file(obj);
8944 		if (err)
8945 			return -EINVAL;
8946 	}
8947 	if (need_vmlinux_btf) {
8948 		err = bpf_object__resolve_ksyms_btf_id(obj);
8949 		if (err)
8950 			return -EINVAL;
8951 	}
8952 	for (i = 0; i < obj->nr_extern; i++) {
8953 		ext = &obj->externs[i];
8954 
8955 		if (!ext->is_set && !ext->is_weak) {
8956 			pr_warn("extern '%s' (strong): not resolved\n", ext->name);
8957 			return -ESRCH;
8958 		} else if (!ext->is_set) {
8959 			pr_debug("extern '%s' (weak): not resolved, defaulting to zero\n",
8960 				 ext->name);
8961 		}
8962 	}
8963 
8964 	return 0;
8965 }
8966 
8967 static void bpf_map_prepare_vdata(const struct bpf_map *map)
8968 {
8969 	const struct btf_type *type;
8970 	struct bpf_struct_ops *st_ops;
8971 	__u32 i;
8972 
8973 	st_ops = map->st_ops;
8974 	type = btf__type_by_id(map->obj->btf, st_ops->type_id);
8975 	for (i = 0; i < btf_vlen(type); i++) {
8976 		struct bpf_program *prog = st_ops->progs[i];
8977 		void *kern_data;
8978 		int prog_fd;
8979 
8980 		if (!prog)
8981 			continue;
8982 
8983 		prog_fd = bpf_program__fd(prog);
8984 		kern_data = st_ops->kern_vdata + st_ops->kern_func_off[i];
8985 		*(unsigned long *)kern_data = prog_fd;
8986 	}
8987 }
8988 
8989 static int bpf_object_prepare_struct_ops(struct bpf_object *obj)
8990 {
8991 	struct bpf_map *map;
8992 	int i;
8993 
8994 	for (i = 0; i < obj->nr_maps; i++) {
8995 		map = &obj->maps[i];
8996 
8997 		if (!bpf_map__is_struct_ops(map))
8998 			continue;
8999 
9000 		if (!map->autocreate)
9001 			continue;
9002 
9003 		bpf_map_prepare_vdata(map);
9004 	}
9005 
9006 	return 0;
9007 }
9008 
9009 static void bpf_object_unpin(struct bpf_object *obj)
9010 {
9011 	int i;
9012 
9013 	/* unpin any maps that were auto-pinned during load */
9014 	for (i = 0; i < obj->nr_maps; i++)
9015 		if (obj->maps[i].pinned && !obj->maps[i].reused)
9016 			bpf_map__unpin(&obj->maps[i], NULL);
9017 }
9018 
9019 static void bpf_object_cleanup_btf(struct bpf_object *obj)
9020 {
9021 	int i;
9022 
9023 	/* clean up module BTFs */
9024 	for (i = 0; i < obj->btf_module_cnt; i++) {
9025 		close(obj->btf_modules[i].fd);
9026 		btf__free(obj->btf_modules[i].btf);
9027 		free(obj->btf_modules[i].name);
9028 	}
9029 	obj->btf_module_cnt = 0;
9030 	obj->btf_module_cap = 0;
9031 	obj->btf_modules_loaded = false;
9032 	zfree(&obj->btf_modules);
9033 
9034 	/* clean up vmlinux BTF */
9035 	btf__free(obj->btf_vmlinux);
9036 	obj->btf_vmlinux = NULL;
9037 }
9038 
9039 static void bpf_object_post_load_cleanup(struct bpf_object *obj)
9040 {
9041 	/* clean up fd_array */
9042 	zfree(&obj->fd_array);
9043 
9044 	/* clean up BTF */
9045 	bpf_object_cleanup_btf(obj);
9046 }
9047 
9048 static int bpf_object_prepare(struct bpf_object *obj, const char *target_btf_path)
9049 {
9050 	int err;
9051 
9052 	if (obj->state >= OBJ_PREPARED) {
9053 		pr_warn("object '%s': prepare loading can't be attempted twice\n", obj->name);
9054 		return -EINVAL;
9055 	}
9056 
9057 	err = bpf_object_prepare_token(obj);
9058 	err = err ? : bpf_object__probe_loading(obj);
9059 	err = err ? : bpf_object__load_vmlinux_btf(obj, false);
9060 	err = err ? : bpf_object__resolve_externs(obj, obj->kconfig);
9061 	err = err ? : bpf_object__sanitize_maps(obj);
9062 	err = err ? : bpf_object__init_kern_struct_ops_maps(obj);
9063 	err = err ? : bpf_object_adjust_struct_ops_autoload(obj);
9064 	err = err ? : bpf_object__relocate(obj, obj->btf_custom_path ? : target_btf_path);
9065 	err = err ? : bpf_object__sanitize_and_load_btf(obj);
9066 	err = err ? : bpf_object__create_maps(obj);
9067 	err = err ? : bpf_object_prepare_progs(obj);
9068 
9069 	if (err) {
9070 		bpf_object_unpin(obj);
9071 		bpf_object_unload(obj);
9072 		obj->state = OBJ_LOADED;
9073 		return err;
9074 	}
9075 
9076 	obj->state = OBJ_PREPARED;
9077 	return 0;
9078 }
9079 
9080 static int bpf_object_load(struct bpf_object *obj, int extra_log_level, const char *target_btf_path)
9081 {
9082 	int err;
9083 
9084 	if (!obj)
9085 		return libbpf_err(-EINVAL);
9086 
9087 	if (obj->state >= OBJ_LOADED) {
9088 		pr_warn("object '%s': load can't be attempted twice\n", obj->name);
9089 		return libbpf_err(-EINVAL);
9090 	}
9091 
9092 	/* Disallow kernel loading programs of non-native endianness but
9093 	 * permit cross-endian creation of "light skeleton".
9094 	 */
9095 	if (obj->gen_loader) {
9096 		bpf_gen__init(obj->gen_loader, extra_log_level, obj->nr_programs, obj->nr_maps);
9097 	} else if (!is_native_endianness(obj)) {
9098 		pr_warn("object '%s': loading non-native endianness is unsupported\n", obj->name);
9099 		return libbpf_err(-LIBBPF_ERRNO__ENDIAN);
9100 	}
9101 
9102 	if (obj->state < OBJ_PREPARED) {
9103 		err = bpf_object_prepare(obj, target_btf_path);
9104 		if (err)
9105 			return libbpf_err(err);
9106 	}
9107 	err = bpf_object__load_progs(obj, extra_log_level);
9108 	err = err ? : bpf_object_init_prog_arrays(obj);
9109 	err = err ? : bpf_object_prepare_struct_ops(obj);
9110 
9111 	if (obj->gen_loader) {
9112 		/* reset FDs */
9113 		if (obj->btf)
9114 			btf__set_fd(obj->btf, -1);
9115 		if (!err)
9116 			err = bpf_gen__finish(obj->gen_loader, obj->nr_programs, obj->nr_maps);
9117 	}
9118 
9119 	bpf_object_post_load_cleanup(obj);
9120 	obj->state = OBJ_LOADED; /* doesn't matter if successfully or not */
9121 
9122 	if (err) {
9123 		bpf_object_unpin(obj);
9124 		bpf_object_unload(obj);
9125 		pr_warn("failed to load object '%s'\n", obj->path);
9126 		return libbpf_err(err);
9127 	}
9128 
9129 	return 0;
9130 }
9131 
9132 int bpf_object__prepare(struct bpf_object *obj)
9133 {
9134 	return libbpf_err(bpf_object_prepare(obj, NULL));
9135 }
9136 
9137 int bpf_object__load(struct bpf_object *obj)
9138 {
9139 	return bpf_object_load(obj, 0, NULL);
9140 }
9141 
9142 static int make_parent_dir(const char *path)
9143 {
9144 	char *dname, *dir;
9145 	int err = 0;
9146 
9147 	dname = strdup(path);
9148 	if (dname == NULL)
9149 		return -ENOMEM;
9150 
9151 	dir = dirname(dname);
9152 	if (mkdir(dir, 0700) && errno != EEXIST)
9153 		err = -errno;
9154 
9155 	free(dname);
9156 	if (err) {
9157 		pr_warn("failed to mkdir %s: %s\n", path, errstr(err));
9158 	}
9159 	return err;
9160 }
9161 
9162 static int check_path(const char *path)
9163 {
9164 	struct statfs st_fs;
9165 	char *dname, *dir;
9166 	int err = 0;
9167 
9168 	if (path == NULL)
9169 		return -EINVAL;
9170 
9171 	dname = strdup(path);
9172 	if (dname == NULL)
9173 		return -ENOMEM;
9174 
9175 	dir = dirname(dname);
9176 	if (statfs(dir, &st_fs)) {
9177 		pr_warn("failed to statfs %s: %s\n", dir, errstr(errno));
9178 		err = -errno;
9179 	}
9180 	free(dname);
9181 
9182 	if (!err && st_fs.f_type != BPF_FS_MAGIC) {
9183 		pr_warn("specified path %s is not on BPF FS\n", path);
9184 		err = -EINVAL;
9185 	}
9186 
9187 	return err;
9188 }
9189 
9190 int bpf_program__pin(struct bpf_program *prog, const char *path)
9191 {
9192 	int err;
9193 
9194 	if (prog->fd < 0) {
9195 		pr_warn("prog '%s': can't pin program that wasn't loaded\n", prog->name);
9196 		return libbpf_err(-EINVAL);
9197 	}
9198 
9199 	err = make_parent_dir(path);
9200 	if (err)
9201 		return libbpf_err(err);
9202 
9203 	err = check_path(path);
9204 	if (err)
9205 		return libbpf_err(err);
9206 
9207 	if (bpf_obj_pin(prog->fd, path)) {
9208 		err = -errno;
9209 		pr_warn("prog '%s': failed to pin at '%s': %s\n", prog->name, path, errstr(err));
9210 		return libbpf_err(err);
9211 	}
9212 
9213 	pr_debug("prog '%s': pinned at '%s'\n", prog->name, path);
9214 	return 0;
9215 }
9216 
9217 int bpf_program__unpin(struct bpf_program *prog, const char *path)
9218 {
9219 	int err;
9220 
9221 	if (prog->fd < 0) {
9222 		pr_warn("prog '%s': can't unpin program that wasn't loaded\n", prog->name);
9223 		return libbpf_err(-EINVAL);
9224 	}
9225 
9226 	err = check_path(path);
9227 	if (err)
9228 		return libbpf_err(err);
9229 
9230 	err = unlink(path);
9231 	if (err)
9232 		return libbpf_err(-errno);
9233 
9234 	pr_debug("prog '%s': unpinned from '%s'\n", prog->name, path);
9235 	return 0;
9236 }
9237 
9238 int bpf_map__pin(struct bpf_map *map, const char *path)
9239 {
9240 	int err;
9241 
9242 	if (map == NULL) {
9243 		pr_warn("invalid map pointer\n");
9244 		return libbpf_err(-EINVAL);
9245 	}
9246 
9247 	if (map->fd < 0) {
9248 		pr_warn("map '%s': can't pin BPF map without FD (was it created?)\n", map->name);
9249 		return libbpf_err(-EINVAL);
9250 	}
9251 
9252 	if (map->pin_path) {
9253 		if (path && strcmp(path, map->pin_path)) {
9254 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
9255 				bpf_map__name(map), map->pin_path, path);
9256 			return libbpf_err(-EINVAL);
9257 		} else if (map->pinned) {
9258 			pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
9259 				 bpf_map__name(map), map->pin_path);
9260 			return 0;
9261 		}
9262 	} else {
9263 		if (!path) {
9264 			pr_warn("missing a path to pin map '%s' at\n",
9265 				bpf_map__name(map));
9266 			return libbpf_err(-EINVAL);
9267 		} else if (map->pinned) {
9268 			pr_warn("map '%s' already pinned\n", bpf_map__name(map));
9269 			return libbpf_err(-EEXIST);
9270 		}
9271 
9272 		map->pin_path = strdup(path);
9273 		if (!map->pin_path) {
9274 			err = -errno;
9275 			goto out_err;
9276 		}
9277 	}
9278 
9279 	err = make_parent_dir(map->pin_path);
9280 	if (err)
9281 		return libbpf_err(err);
9282 
9283 	err = check_path(map->pin_path);
9284 	if (err)
9285 		return libbpf_err(err);
9286 
9287 	if (bpf_obj_pin(map->fd, map->pin_path)) {
9288 		err = -errno;
9289 		goto out_err;
9290 	}
9291 
9292 	map->pinned = true;
9293 	pr_debug("pinned map '%s'\n", map->pin_path);
9294 
9295 	return 0;
9296 
9297 out_err:
9298 	pr_warn("failed to pin map: %s\n", errstr(err));
9299 	return libbpf_err(err);
9300 }
9301 
9302 int bpf_map__unpin(struct bpf_map *map, const char *path)
9303 {
9304 	int err;
9305 
9306 	if (map == NULL) {
9307 		pr_warn("invalid map pointer\n");
9308 		return libbpf_err(-EINVAL);
9309 	}
9310 
9311 	if (map->pin_path) {
9312 		if (path && strcmp(path, map->pin_path)) {
9313 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
9314 				bpf_map__name(map), map->pin_path, path);
9315 			return libbpf_err(-EINVAL);
9316 		}
9317 		path = map->pin_path;
9318 	} else if (!path) {
9319 		pr_warn("no path to unpin map '%s' from\n",
9320 			bpf_map__name(map));
9321 		return libbpf_err(-EINVAL);
9322 	}
9323 
9324 	err = check_path(path);
9325 	if (err)
9326 		return libbpf_err(err);
9327 
9328 	err = unlink(path);
9329 	if (err != 0)
9330 		return libbpf_err(-errno);
9331 
9332 	map->pinned = false;
9333 	pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path);
9334 
9335 	return 0;
9336 }
9337 
9338 int bpf_map__set_pin_path(struct bpf_map *map, const char *path)
9339 {
9340 	char *new = NULL;
9341 
9342 	if (path) {
9343 		new = strdup(path);
9344 		if (!new)
9345 			return libbpf_err(-errno);
9346 	}
9347 
9348 	free(map->pin_path);
9349 	map->pin_path = new;
9350 	return 0;
9351 }
9352 
9353 __alias(bpf_map__pin_path)
9354 const char *bpf_map__get_pin_path(const struct bpf_map *map);
9355 
9356 const char *bpf_map__pin_path(const struct bpf_map *map)
9357 {
9358 	return map->pin_path;
9359 }
9360 
9361 bool bpf_map__is_pinned(const struct bpf_map *map)
9362 {
9363 	return map->pinned;
9364 }
9365 
9366 static void sanitize_pin_path(char *s)
9367 {
9368 	/* bpffs disallows periods in path names */
9369 	while (*s) {
9370 		if (*s == '.')
9371 			*s = '_';
9372 		s++;
9373 	}
9374 }
9375 
9376 int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
9377 {
9378 	struct bpf_map *map;
9379 	int err;
9380 
9381 	if (!obj)
9382 		return libbpf_err(-ENOENT);
9383 
9384 	if (obj->state < OBJ_PREPARED) {
9385 		pr_warn("object not yet loaded; load it first\n");
9386 		return libbpf_err(-ENOENT);
9387 	}
9388 
9389 	bpf_object__for_each_map(map, obj) {
9390 		char *pin_path = NULL;
9391 		char buf[PATH_MAX];
9392 
9393 		if (!map->autocreate)
9394 			continue;
9395 
9396 		if (path) {
9397 			err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
9398 			if (err)
9399 				goto err_unpin_maps;
9400 			sanitize_pin_path(buf);
9401 			pin_path = buf;
9402 		} else if (!map->pin_path) {
9403 			continue;
9404 		}
9405 
9406 		err = bpf_map__pin(map, pin_path);
9407 		if (err)
9408 			goto err_unpin_maps;
9409 	}
9410 
9411 	return 0;
9412 
9413 err_unpin_maps:
9414 	while ((map = bpf_object__prev_map(obj, map))) {
9415 		if (!map->pin_path)
9416 			continue;
9417 
9418 		bpf_map__unpin(map, NULL);
9419 	}
9420 
9421 	return libbpf_err(err);
9422 }
9423 
9424 int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
9425 {
9426 	struct bpf_map *map;
9427 	int err;
9428 
9429 	if (!obj)
9430 		return libbpf_err(-ENOENT);
9431 
9432 	bpf_object__for_each_map(map, obj) {
9433 		char *pin_path = NULL;
9434 		char buf[PATH_MAX];
9435 
9436 		if (path) {
9437 			err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
9438 			if (err)
9439 				return libbpf_err(err);
9440 			sanitize_pin_path(buf);
9441 			pin_path = buf;
9442 		} else if (!map->pin_path) {
9443 			continue;
9444 		}
9445 
9446 		err = bpf_map__unpin(map, pin_path);
9447 		if (err)
9448 			return libbpf_err(err);
9449 	}
9450 
9451 	return 0;
9452 }
9453 
9454 int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
9455 {
9456 	struct bpf_program *prog;
9457 	char buf[PATH_MAX];
9458 	int err;
9459 
9460 	if (!obj)
9461 		return libbpf_err(-ENOENT);
9462 
9463 	if (obj->state < OBJ_LOADED) {
9464 		pr_warn("object not yet loaded; load it first\n");
9465 		return libbpf_err(-ENOENT);
9466 	}
9467 
9468 	bpf_object__for_each_program(prog, obj) {
9469 		err = pathname_concat(buf, sizeof(buf), path, prog->name);
9470 		if (err)
9471 			goto err_unpin_programs;
9472 
9473 		err = bpf_program__pin(prog, buf);
9474 		if (err)
9475 			goto err_unpin_programs;
9476 	}
9477 
9478 	return 0;
9479 
9480 err_unpin_programs:
9481 	while ((prog = bpf_object__prev_program(obj, prog))) {
9482 		if (pathname_concat(buf, sizeof(buf), path, prog->name))
9483 			continue;
9484 
9485 		bpf_program__unpin(prog, buf);
9486 	}
9487 
9488 	return libbpf_err(err);
9489 }
9490 
9491 int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
9492 {
9493 	struct bpf_program *prog;
9494 	int err;
9495 
9496 	if (!obj)
9497 		return libbpf_err(-ENOENT);
9498 
9499 	bpf_object__for_each_program(prog, obj) {
9500 		char buf[PATH_MAX];
9501 
9502 		err = pathname_concat(buf, sizeof(buf), path, prog->name);
9503 		if (err)
9504 			return libbpf_err(err);
9505 
9506 		err = bpf_program__unpin(prog, buf);
9507 		if (err)
9508 			return libbpf_err(err);
9509 	}
9510 
9511 	return 0;
9512 }
9513 
9514 int bpf_object__pin(struct bpf_object *obj, const char *path)
9515 {
9516 	int err;
9517 
9518 	err = bpf_object__pin_maps(obj, path);
9519 	if (err)
9520 		return libbpf_err(err);
9521 
9522 	err = bpf_object__pin_programs(obj, path);
9523 	if (err) {
9524 		bpf_object__unpin_maps(obj, path);
9525 		return libbpf_err(err);
9526 	}
9527 
9528 	return 0;
9529 }
9530 
9531 int bpf_object__unpin(struct bpf_object *obj, const char *path)
9532 {
9533 	int err;
9534 
9535 	err = bpf_object__unpin_programs(obj, path);
9536 	if (err)
9537 		return libbpf_err(err);
9538 
9539 	err = bpf_object__unpin_maps(obj, path);
9540 	if (err)
9541 		return libbpf_err(err);
9542 
9543 	return 0;
9544 }
9545 
9546 static void bpf_map__destroy(struct bpf_map *map)
9547 {
9548 	if (map->inner_map) {
9549 		bpf_map__destroy(map->inner_map);
9550 		zfree(&map->inner_map);
9551 	}
9552 
9553 	zfree(&map->init_slots);
9554 	map->init_slots_sz = 0;
9555 
9556 	if (map->mmaped && map->mmaped != map->obj->arena_data)
9557 		munmap(map->mmaped, bpf_map_mmap_sz(map));
9558 	map->mmaped = NULL;
9559 
9560 	if (map->st_ops) {
9561 		zfree(&map->st_ops->data);
9562 		zfree(&map->st_ops->progs);
9563 		zfree(&map->st_ops->kern_func_off);
9564 		zfree(&map->st_ops);
9565 	}
9566 
9567 	zfree(&map->name);
9568 	zfree(&map->real_name);
9569 	zfree(&map->pin_path);
9570 
9571 	if (map->fd >= 0)
9572 		zclose(map->fd);
9573 }
9574 
9575 void bpf_object__close(struct bpf_object *obj)
9576 {
9577 	size_t i;
9578 
9579 	if (IS_ERR_OR_NULL(obj))
9580 		return;
9581 
9582 	/*
9583 	 * if user called bpf_object__prepare() without ever getting to
9584 	 * bpf_object__load(), we need to clean up stuff that is normally
9585 	 * cleaned up at the end of loading step
9586 	 */
9587 	bpf_object_post_load_cleanup(obj);
9588 
9589 	usdt_manager_free(obj->usdt_man);
9590 	obj->usdt_man = NULL;
9591 
9592 	bpf_gen__free(obj->gen_loader);
9593 	bpf_object__elf_finish(obj);
9594 	bpf_object_unload(obj);
9595 	btf__free(obj->btf);
9596 	btf__free(obj->btf_vmlinux);
9597 	btf_ext__free(obj->btf_ext);
9598 
9599 	for (i = 0; i < obj->nr_maps; i++)
9600 		bpf_map__destroy(&obj->maps[i]);
9601 
9602 	zfree(&obj->btf_custom_path);
9603 	zfree(&obj->kconfig);
9604 
9605 	for (i = 0; i < obj->nr_extern; i++) {
9606 		zfree(&obj->externs[i].name);
9607 		zfree(&obj->externs[i].essent_name);
9608 	}
9609 
9610 	zfree(&obj->externs);
9611 	obj->nr_extern = 0;
9612 
9613 	zfree(&obj->maps);
9614 	obj->nr_maps = 0;
9615 
9616 	if (obj->programs && obj->nr_programs) {
9617 		for (i = 0; i < obj->nr_programs; i++)
9618 			bpf_program__exit(&obj->programs[i]);
9619 	}
9620 	zfree(&obj->programs);
9621 
9622 	zfree(&obj->feat_cache);
9623 	zfree(&obj->token_path);
9624 	if (obj->token_fd > 0)
9625 		close(obj->token_fd);
9626 
9627 	zfree(&obj->arena_data);
9628 
9629 	zfree(&obj->jumptables_data);
9630 	obj->jumptables_data_sz = 0;
9631 
9632 	for (i = 0; i < obj->jumptable_map_cnt; i++)
9633 		close(obj->jumptable_maps[i].fd);
9634 	zfree(&obj->jumptable_maps);
9635 
9636 	free(obj);
9637 }
9638 
9639 const char *bpf_object__name(const struct bpf_object *obj)
9640 {
9641 	return obj ? obj->name : libbpf_err_ptr(-EINVAL);
9642 }
9643 
9644 unsigned int bpf_object__kversion(const struct bpf_object *obj)
9645 {
9646 	return obj ? obj->kern_version : 0;
9647 }
9648 
9649 int bpf_object__token_fd(const struct bpf_object *obj)
9650 {
9651 	return obj->token_fd ?: -1;
9652 }
9653 
9654 struct btf *bpf_object__btf(const struct bpf_object *obj)
9655 {
9656 	return obj ? obj->btf : NULL;
9657 }
9658 
9659 int bpf_object__btf_fd(const struct bpf_object *obj)
9660 {
9661 	return obj->btf ? btf__fd(obj->btf) : -1;
9662 }
9663 
9664 int bpf_object__set_kversion(struct bpf_object *obj, __u32 kern_version)
9665 {
9666 	if (obj->state >= OBJ_LOADED)
9667 		return libbpf_err(-EINVAL);
9668 
9669 	obj->kern_version = kern_version;
9670 
9671 	return 0;
9672 }
9673 
9674 int bpf_object__gen_loader(struct bpf_object *obj, struct gen_loader_opts *opts)
9675 {
9676 	struct bpf_gen *gen;
9677 
9678 	if (!opts)
9679 		return libbpf_err(-EFAULT);
9680 	if (!OPTS_VALID(opts, gen_loader_opts))
9681 		return libbpf_err(-EINVAL);
9682 	gen = calloc(1, sizeof(*gen));
9683 	if (!gen)
9684 		return libbpf_err(-ENOMEM);
9685 	gen->opts = opts;
9686 	gen->swapped_endian = !is_native_endianness(obj);
9687 	obj->gen_loader = gen;
9688 	return 0;
9689 }
9690 
9691 static struct bpf_program *
9692 __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
9693 		    bool forward)
9694 {
9695 	size_t nr_programs = obj->nr_programs;
9696 	ssize_t idx;
9697 
9698 	if (!nr_programs)
9699 		return NULL;
9700 
9701 	if (!p)
9702 		/* Iter from the beginning */
9703 		return forward ? &obj->programs[0] :
9704 			&obj->programs[nr_programs - 1];
9705 
9706 	if (p->obj != obj) {
9707 		pr_warn("error: program handler doesn't match object\n");
9708 		return errno = EINVAL, NULL;
9709 	}
9710 
9711 	idx = (p - obj->programs) + (forward ? 1 : -1);
9712 	if (idx >= obj->nr_programs || idx < 0)
9713 		return NULL;
9714 	return &obj->programs[idx];
9715 }
9716 
9717 struct bpf_program *
9718 bpf_object__next_program(const struct bpf_object *obj, struct bpf_program *prev)
9719 {
9720 	struct bpf_program *prog = prev;
9721 
9722 	do {
9723 		prog = __bpf_program__iter(prog, obj, true);
9724 	} while (prog && prog_is_subprog(obj, prog));
9725 
9726 	return prog;
9727 }
9728 
9729 struct bpf_program *
9730 bpf_object__prev_program(const struct bpf_object *obj, struct bpf_program *next)
9731 {
9732 	struct bpf_program *prog = next;
9733 
9734 	do {
9735 		prog = __bpf_program__iter(prog, obj, false);
9736 	} while (prog && prog_is_subprog(obj, prog));
9737 
9738 	return prog;
9739 }
9740 
9741 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
9742 {
9743 	prog->prog_ifindex = ifindex;
9744 }
9745 
9746 const char *bpf_program__name(const struct bpf_program *prog)
9747 {
9748 	return prog->name;
9749 }
9750 
9751 const char *bpf_program__section_name(const struct bpf_program *prog)
9752 {
9753 	return prog->sec_name;
9754 }
9755 
9756 bool bpf_program__autoload(const struct bpf_program *prog)
9757 {
9758 	return prog->autoload;
9759 }
9760 
9761 int bpf_program__set_autoload(struct bpf_program *prog, bool autoload)
9762 {
9763 	if (prog->obj->state >= OBJ_LOADED)
9764 		return libbpf_err(-EINVAL);
9765 
9766 	prog->autoload = autoload;
9767 	return 0;
9768 }
9769 
9770 bool bpf_program__autoattach(const struct bpf_program *prog)
9771 {
9772 	return prog->autoattach;
9773 }
9774 
9775 void bpf_program__set_autoattach(struct bpf_program *prog, bool autoattach)
9776 {
9777 	prog->autoattach = autoattach;
9778 }
9779 
9780 const struct bpf_insn *bpf_program__insns(const struct bpf_program *prog)
9781 {
9782 	return prog->insns;
9783 }
9784 
9785 size_t bpf_program__insn_cnt(const struct bpf_program *prog)
9786 {
9787 	return prog->insns_cnt;
9788 }
9789 
9790 int bpf_program__set_insns(struct bpf_program *prog,
9791 			   struct bpf_insn *new_insns, size_t new_insn_cnt)
9792 {
9793 	struct bpf_insn *insns;
9794 
9795 	if (prog->obj->state >= OBJ_LOADED)
9796 		return libbpf_err(-EBUSY);
9797 
9798 	insns = libbpf_reallocarray(prog->insns, new_insn_cnt, sizeof(*insns));
9799 	/* NULL is a valid return from reallocarray if the new count is zero */
9800 	if (!insns && new_insn_cnt) {
9801 		pr_warn("prog '%s': failed to realloc prog code\n", prog->name);
9802 		return libbpf_err(-ENOMEM);
9803 	}
9804 	memcpy(insns, new_insns, new_insn_cnt * sizeof(*insns));
9805 
9806 	prog->insns = insns;
9807 	prog->insns_cnt = new_insn_cnt;
9808 	return 0;
9809 }
9810 
9811 int bpf_program__fd(const struct bpf_program *prog)
9812 {
9813 	if (!prog)
9814 		return libbpf_err(-EINVAL);
9815 
9816 	if (prog->fd < 0)
9817 		return libbpf_err(-ENOENT);
9818 
9819 	return prog->fd;
9820 }
9821 
9822 __alias(bpf_program__type)
9823 enum bpf_prog_type bpf_program__get_type(const struct bpf_program *prog);
9824 
9825 enum bpf_prog_type bpf_program__type(const struct bpf_program *prog)
9826 {
9827 	return prog->type;
9828 }
9829 
9830 static size_t custom_sec_def_cnt;
9831 static struct bpf_sec_def *custom_sec_defs;
9832 static struct bpf_sec_def custom_fallback_def;
9833 static bool has_custom_fallback_def;
9834 static int last_custom_sec_def_handler_id;
9835 
9836 int bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
9837 {
9838 	if (prog->obj->state >= OBJ_LOADED)
9839 		return libbpf_err(-EBUSY);
9840 
9841 	/* if type is not changed, do nothing */
9842 	if (prog->type == type)
9843 		return 0;
9844 
9845 	prog->type = type;
9846 
9847 	/* If a program type was changed, we need to reset associated SEC()
9848 	 * handler, as it will be invalid now. The only exception is a generic
9849 	 * fallback handler, which by definition is program type-agnostic and
9850 	 * is a catch-all custom handler, optionally set by the application,
9851 	 * so should be able to handle any type of BPF program.
9852 	 */
9853 	if (prog->sec_def != &custom_fallback_def)
9854 		prog->sec_def = NULL;
9855 	return 0;
9856 }
9857 
9858 __alias(bpf_program__expected_attach_type)
9859 enum bpf_attach_type bpf_program__get_expected_attach_type(const struct bpf_program *prog);
9860 
9861 enum bpf_attach_type bpf_program__expected_attach_type(const struct bpf_program *prog)
9862 {
9863 	return prog->expected_attach_type;
9864 }
9865 
9866 int bpf_program__set_expected_attach_type(struct bpf_program *prog,
9867 					   enum bpf_attach_type type)
9868 {
9869 	if (prog->obj->state >= OBJ_LOADED)
9870 		return libbpf_err(-EBUSY);
9871 
9872 	prog->expected_attach_type = type;
9873 	return 0;
9874 }
9875 
9876 __u32 bpf_program__flags(const struct bpf_program *prog)
9877 {
9878 	return prog->prog_flags;
9879 }
9880 
9881 int bpf_program__set_flags(struct bpf_program *prog, __u32 flags)
9882 {
9883 	if (prog->obj->state >= OBJ_LOADED)
9884 		return libbpf_err(-EBUSY);
9885 
9886 	prog->prog_flags = flags;
9887 	return 0;
9888 }
9889 
9890 __u32 bpf_program__log_level(const struct bpf_program *prog)
9891 {
9892 	return prog->log_level;
9893 }
9894 
9895 int bpf_program__set_log_level(struct bpf_program *prog, __u32 log_level)
9896 {
9897 	if (prog->obj->state >= OBJ_LOADED)
9898 		return libbpf_err(-EBUSY);
9899 
9900 	prog->log_level = log_level;
9901 	return 0;
9902 }
9903 
9904 const char *bpf_program__log_buf(const struct bpf_program *prog, size_t *log_size)
9905 {
9906 	*log_size = prog->log_size;
9907 	return prog->log_buf;
9908 }
9909 
9910 int bpf_program__set_log_buf(struct bpf_program *prog, char *log_buf, size_t log_size)
9911 {
9912 	if (log_size && !log_buf)
9913 		return libbpf_err(-EINVAL);
9914 	if (prog->log_size > UINT_MAX)
9915 		return libbpf_err(-EINVAL);
9916 	if (prog->obj->state >= OBJ_LOADED)
9917 		return libbpf_err(-EBUSY);
9918 
9919 	prog->log_buf = log_buf;
9920 	prog->log_size = log_size;
9921 	return 0;
9922 }
9923 
9924 struct bpf_func_info *bpf_program__func_info(const struct bpf_program *prog)
9925 {
9926 	if (prog->func_info_rec_size != sizeof(struct bpf_func_info))
9927 		return libbpf_err_ptr(-EOPNOTSUPP);
9928 	return prog->func_info;
9929 }
9930 
9931 __u32 bpf_program__func_info_cnt(const struct bpf_program *prog)
9932 {
9933 	return prog->func_info_cnt;
9934 }
9935 
9936 struct bpf_line_info *bpf_program__line_info(const struct bpf_program *prog)
9937 {
9938 	if (prog->line_info_rec_size != sizeof(struct bpf_line_info))
9939 		return libbpf_err_ptr(-EOPNOTSUPP);
9940 	return prog->line_info;
9941 }
9942 
9943 __u32 bpf_program__line_info_cnt(const struct bpf_program *prog)
9944 {
9945 	return prog->line_info_cnt;
9946 }
9947 
9948 int bpf_program__clone(struct bpf_program *prog, const struct bpf_prog_load_opts *opts)
9949 {
9950 	LIBBPF_OPTS(bpf_prog_load_opts, attr);
9951 	struct bpf_object *obj;
9952 	const void *info;
9953 	__u32 info_cnt, info_rec_size;
9954 	int err, fd, prog_btf_fd;
9955 
9956 	if (!prog)
9957 		return libbpf_err(-EINVAL);
9958 
9959 	if (!OPTS_VALID(opts, bpf_prog_load_opts))
9960 		return libbpf_err(-EINVAL);
9961 
9962 	obj = prog->obj;
9963 	if (obj->state < OBJ_PREPARED)
9964 		return libbpf_err(-EINVAL);
9965 
9966 	/*
9967 	 * Caller-provided opts take priority; fall back to
9968 	 * prog/object defaults when the caller leaves them zero.
9969 	 */
9970 	attr.attach_prog_fd = OPTS_GET(opts, attach_prog_fd, 0) ?: prog->attach_prog_fd;
9971 	attr.prog_flags = OPTS_GET(opts, prog_flags, 0) ?: prog->prog_flags;
9972 	attr.prog_ifindex = OPTS_GET(opts, prog_ifindex, 0) ?: prog->prog_ifindex;
9973 	attr.kern_version = OPTS_GET(opts, kern_version, 0) ?: obj->kern_version;
9974 	attr.fd_array = OPTS_GET(opts, fd_array, NULL) ?: obj->fd_array;
9975 	attr.fd_array_cnt = OPTS_GET(opts, fd_array_cnt, 0) ?: obj->fd_array_cnt;
9976 	attr.token_fd = OPTS_GET(opts, token_fd, 0) ?: obj->token_fd;
9977 	if (attr.token_fd)
9978 		attr.prog_flags |= BPF_F_TOKEN_FD;
9979 
9980 	prog_btf_fd = OPTS_GET(opts, prog_btf_fd, 0);
9981 	if (!prog_btf_fd && obj->btf)
9982 		prog_btf_fd = btf__fd(obj->btf);
9983 
9984 	/* BTF func/line info: only pass if kernel supports it */
9985 	if (kernel_supports(obj, FEAT_BTF_FUNC) && prog_btf_fd > 0) {
9986 		attr.prog_btf_fd = prog_btf_fd;
9987 
9988 		/* func_info/line_info triples: all-or-nothing from caller */
9989 		info = OPTS_GET(opts, func_info, NULL);
9990 		info_cnt = OPTS_GET(opts, func_info_cnt, 0);
9991 		info_rec_size = OPTS_GET(opts, func_info_rec_size, 0);
9992 		if (!!info != !!info_cnt || !!info != !!info_rec_size) {
9993 			pr_warn("prog '%s': func_info, func_info_cnt, and func_info_rec_size must all be specified or all omitted\n",
9994 				prog->name);
9995 			return libbpf_err(-EINVAL);
9996 		}
9997 		attr.func_info = info ?: prog->func_info;
9998 		attr.func_info_cnt = info ? info_cnt : prog->func_info_cnt;
9999 		attr.func_info_rec_size = info ? info_rec_size : prog->func_info_rec_size;
10000 
10001 		info = OPTS_GET(opts, line_info, NULL);
10002 		info_cnt = OPTS_GET(opts, line_info_cnt, 0);
10003 		info_rec_size = OPTS_GET(opts, line_info_rec_size, 0);
10004 		if (!!info != !!info_cnt || !!info != !!info_rec_size) {
10005 			pr_warn("prog '%s': line_info, line_info_cnt, and line_info_rec_size must all be specified or all omitted\n",
10006 				prog->name);
10007 			return libbpf_err(-EINVAL);
10008 		}
10009 		attr.line_info = info ?: prog->line_info;
10010 		attr.line_info_cnt = info ? info_cnt : prog->line_info_cnt;
10011 		attr.line_info_rec_size = info ? info_rec_size : prog->line_info_rec_size;
10012 	}
10013 
10014 	/* Logging is caller-controlled; no fallback to prog/obj log settings */
10015 	attr.log_buf = OPTS_GET(opts, log_buf, NULL);
10016 	attr.log_size = OPTS_GET(opts, log_size, 0);
10017 	attr.log_level = OPTS_GET(opts, log_level, 0);
10018 
10019 	/*
10020 	 * Fields below may be mutated by prog_prepare_load_fn:
10021 	 * Seed them from prog/obj defaults here;
10022 	 * Later override with caller-provided opts.
10023 	 */
10024 	attr.expected_attach_type = prog->expected_attach_type;
10025 	attr.attach_btf_id = prog->attach_btf_id;
10026 	attr.attach_btf_obj_fd = prog->attach_btf_obj_fd;
10027 
10028 	if (prog->sec_def && prog->sec_def->prog_prepare_load_fn) {
10029 		err = prog->sec_def->prog_prepare_load_fn(prog, &attr, prog->sec_def->cookie);
10030 		if (err)
10031 			return libbpf_err(err);
10032 	}
10033 
10034 	/* Re-apply caller overrides for output fields */
10035 	if (OPTS_GET(opts, expected_attach_type, 0))
10036 		attr.expected_attach_type = OPTS_GET(opts, expected_attach_type, 0);
10037 	if (OPTS_GET(opts, attach_btf_id, 0))
10038 		attr.attach_btf_id = OPTS_GET(opts, attach_btf_id, 0);
10039 	if (OPTS_GET(opts, attach_btf_obj_fd, 0))
10040 		attr.attach_btf_obj_fd = OPTS_GET(opts, attach_btf_obj_fd, 0);
10041 
10042 	/*
10043 	 * Unlike bpf_object_load_prog(), we intentionally do not call bpf_prog_bind_map()
10044 	 * for RODATA maps here to avoid mutating the object's state. Callers can bind the
10045 	 * required maps themselves using bpf_prog_bind_map().
10046 	 */
10047 	fd = bpf_prog_load(prog->type, prog->name, obj->license, prog->insns, prog->insns_cnt,
10048 			   &attr);
10049 
10050 	return libbpf_err(fd);
10051 }
10052 
10053 #define SEC_DEF(sec_pfx, ptype, atype, flags, ...) {			    \
10054 	.sec = (char *)sec_pfx,						    \
10055 	.prog_type = BPF_PROG_TYPE_##ptype,				    \
10056 	.expected_attach_type = atype,					    \
10057 	.cookie = (long)(flags),					    \
10058 	.prog_prepare_load_fn = libbpf_prepare_prog_load,		    \
10059 	__VA_ARGS__							    \
10060 }
10061 
10062 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
10063 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
10064 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link);
10065 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link);
10066 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
10067 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
10068 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link);
10069 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
10070 static int attach_kprobe_session(const struct bpf_program *prog, long cookie, struct bpf_link **link);
10071 static int attach_uprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
10072 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link);
10073 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link);
10074 static int attach_tracing_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
10075 
10076 static const struct bpf_sec_def section_defs[] = {
10077 	SEC_DEF("socket",		SOCKET_FILTER, 0, SEC_NONE),
10078 	SEC_DEF("sk_reuseport/migrate",	SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT_OR_MIGRATE, SEC_ATTACHABLE),
10079 	SEC_DEF("sk_reuseport",		SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT, SEC_ATTACHABLE),
10080 	SEC_DEF("kprobe+",		KPROBE,	0, SEC_NONE, attach_kprobe),
10081 	SEC_DEF("uprobe+",		KPROBE,	0, SEC_NONE, attach_uprobe),
10082 	SEC_DEF("uprobe.s+",		KPROBE,	0, SEC_SLEEPABLE, attach_uprobe),
10083 	SEC_DEF("kretprobe+",		KPROBE, 0, SEC_NONE, attach_kprobe),
10084 	SEC_DEF("uretprobe+",		KPROBE, 0, SEC_NONE, attach_uprobe),
10085 	SEC_DEF("uretprobe.s+",		KPROBE, 0, SEC_SLEEPABLE, attach_uprobe),
10086 	SEC_DEF("kprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
10087 	SEC_DEF("kretprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
10088 	SEC_DEF("kprobe.session+",	KPROBE,	BPF_TRACE_KPROBE_SESSION, SEC_NONE, attach_kprobe_session),
10089 	SEC_DEF("uprobe.multi+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_NONE, attach_uprobe_multi),
10090 	SEC_DEF("uretprobe.multi+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_NONE, attach_uprobe_multi),
10091 	SEC_DEF("uprobe.session+",	KPROBE,	BPF_TRACE_UPROBE_SESSION, SEC_NONE, attach_uprobe_multi),
10092 	SEC_DEF("uprobe.multi.s+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_SLEEPABLE, attach_uprobe_multi),
10093 	SEC_DEF("uretprobe.multi.s+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_SLEEPABLE, attach_uprobe_multi),
10094 	SEC_DEF("uprobe.session.s+",	KPROBE,	BPF_TRACE_UPROBE_SESSION, SEC_SLEEPABLE, attach_uprobe_multi),
10095 	SEC_DEF("ksyscall+",		KPROBE,	0, SEC_NONE, attach_ksyscall),
10096 	SEC_DEF("kretsyscall+",		KPROBE, 0, SEC_NONE, attach_ksyscall),
10097 	SEC_DEF("usdt+",		KPROBE,	0, SEC_USDT, attach_usdt),
10098 	SEC_DEF("usdt.s+",		KPROBE,	0, SEC_USDT | SEC_SLEEPABLE, attach_usdt),
10099 	SEC_DEF("tc/ingress",		SCHED_CLS, BPF_TCX_INGRESS, SEC_NONE), /* alias for tcx */
10100 	SEC_DEF("tc/egress",		SCHED_CLS, BPF_TCX_EGRESS, SEC_NONE),  /* alias for tcx */
10101 	SEC_DEF("tcx/ingress",		SCHED_CLS, BPF_TCX_INGRESS, SEC_NONE),
10102 	SEC_DEF("tcx/egress",		SCHED_CLS, BPF_TCX_EGRESS, SEC_NONE),
10103 	SEC_DEF("tc",			SCHED_CLS, 0, SEC_NONE), /* deprecated / legacy, use tcx */
10104 	SEC_DEF("classifier",		SCHED_CLS, 0, SEC_NONE), /* deprecated / legacy, use tcx */
10105 	SEC_DEF("action",		SCHED_ACT, 0, SEC_NONE), /* deprecated / legacy, use tcx */
10106 	SEC_DEF("netkit/primary",	SCHED_CLS, BPF_NETKIT_PRIMARY, SEC_NONE),
10107 	SEC_DEF("netkit/peer",		SCHED_CLS, BPF_NETKIT_PEER, SEC_NONE),
10108 	SEC_DEF("tracepoint+",		TRACEPOINT, 0, SEC_NONE, attach_tp),
10109 	SEC_DEF("tp+",			TRACEPOINT, 0, SEC_NONE, attach_tp),
10110 	SEC_DEF("tracepoint.s+",	TRACEPOINT, 0, SEC_SLEEPABLE, attach_tp),
10111 	SEC_DEF("tp.s+",		TRACEPOINT, 0, SEC_SLEEPABLE, attach_tp),
10112 	SEC_DEF("raw_tracepoint+",	RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
10113 	SEC_DEF("raw_tp+",		RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
10114 	SEC_DEF("raw_tracepoint.s+",	RAW_TRACEPOINT, 0, SEC_SLEEPABLE, attach_raw_tp),
10115 	SEC_DEF("raw_tp.s+",		RAW_TRACEPOINT, 0, SEC_SLEEPABLE, attach_raw_tp),
10116 	SEC_DEF("raw_tracepoint.w+",	RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
10117 	SEC_DEF("raw_tp.w+",		RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
10118 	SEC_DEF("tp_btf+",		TRACING, BPF_TRACE_RAW_TP, SEC_ATTACH_BTF, attach_trace),
10119 	SEC_DEF("tp_btf.s+",		TRACING, BPF_TRACE_RAW_TP, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
10120 	SEC_DEF("fentry+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF, attach_trace),
10121 	SEC_DEF("fmod_ret+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF, attach_trace),
10122 	SEC_DEF("fexit+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF, attach_trace),
10123 	SEC_DEF("fentry.s+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
10124 	SEC_DEF("fmod_ret.s+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
10125 	SEC_DEF("fexit.s+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
10126 	SEC_DEF("fsession+",		TRACING, BPF_TRACE_FSESSION, SEC_ATTACH_BTF, attach_trace),
10127 	SEC_DEF("fsession.s+",		TRACING, BPF_TRACE_FSESSION, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
10128 	SEC_DEF("fsession.multi+",	TRACING, BPF_TRACE_FSESSION_MULTI, 0, attach_tracing_multi),
10129 	SEC_DEF("fsession.multi.s+",	TRACING, BPF_TRACE_FSESSION_MULTI, SEC_SLEEPABLE, attach_tracing_multi),
10130 	SEC_DEF("fentry.multi+",	TRACING, BPF_TRACE_FENTRY_MULTI, 0, attach_tracing_multi),
10131 	SEC_DEF("fexit.multi+",		TRACING, BPF_TRACE_FEXIT_MULTI, 0, attach_tracing_multi),
10132 	SEC_DEF("fentry.multi.s+",	TRACING, BPF_TRACE_FENTRY_MULTI, SEC_SLEEPABLE, attach_tracing_multi),
10133 	SEC_DEF("fexit.multi.s+",	TRACING, BPF_TRACE_FEXIT_MULTI, SEC_SLEEPABLE, attach_tracing_multi),
10134 	SEC_DEF("freplace+",		EXT, 0, SEC_ATTACH_BTF, attach_trace),
10135 	SEC_DEF("lsm+",			LSM, BPF_LSM_MAC, SEC_ATTACH_BTF, attach_lsm),
10136 	SEC_DEF("lsm.s+",		LSM, BPF_LSM_MAC, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_lsm),
10137 	SEC_DEF("lsm_cgroup+",		LSM, BPF_LSM_CGROUP, SEC_ATTACH_BTF),
10138 	SEC_DEF("iter+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF, attach_iter),
10139 	SEC_DEF("iter.s+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_iter),
10140 	SEC_DEF("syscall",		SYSCALL, 0, SEC_SLEEPABLE),
10141 	SEC_DEF("xdp.frags/devmap",	XDP, BPF_XDP_DEVMAP, SEC_XDP_FRAGS),
10142 	SEC_DEF("xdp/devmap",		XDP, BPF_XDP_DEVMAP, SEC_ATTACHABLE),
10143 	SEC_DEF("xdp.frags/cpumap",	XDP, BPF_XDP_CPUMAP, SEC_XDP_FRAGS),
10144 	SEC_DEF("xdp/cpumap",		XDP, BPF_XDP_CPUMAP, SEC_ATTACHABLE),
10145 	SEC_DEF("xdp.frags",		XDP, BPF_XDP, SEC_XDP_FRAGS),
10146 	SEC_DEF("xdp",			XDP, BPF_XDP, SEC_ATTACHABLE_OPT),
10147 	SEC_DEF("perf_event",		PERF_EVENT, 0, SEC_NONE),
10148 	SEC_DEF("lwt_in",		LWT_IN, 0, SEC_NONE),
10149 	SEC_DEF("lwt_out",		LWT_OUT, 0, SEC_NONE),
10150 	SEC_DEF("lwt_xmit",		LWT_XMIT, 0, SEC_NONE),
10151 	SEC_DEF("lwt_seg6local",	LWT_SEG6LOCAL, 0, SEC_NONE),
10152 	SEC_DEF("sockops",		SOCK_OPS, BPF_CGROUP_SOCK_OPS, SEC_ATTACHABLE_OPT),
10153 	SEC_DEF("sk_skb/stream_parser",	SK_SKB, BPF_SK_SKB_STREAM_PARSER, SEC_ATTACHABLE_OPT),
10154 	SEC_DEF("sk_skb/stream_verdict",SK_SKB, BPF_SK_SKB_STREAM_VERDICT, SEC_ATTACHABLE_OPT),
10155 	SEC_DEF("sk_skb/verdict",	SK_SKB, BPF_SK_SKB_VERDICT, SEC_ATTACHABLE_OPT),
10156 	SEC_DEF("sk_skb",		SK_SKB, 0, SEC_NONE),
10157 	SEC_DEF("sk_msg",		SK_MSG, BPF_SK_MSG_VERDICT, SEC_ATTACHABLE_OPT),
10158 	SEC_DEF("lirc_mode2",		LIRC_MODE2, BPF_LIRC_MODE2, SEC_ATTACHABLE_OPT),
10159 	SEC_DEF("flow_dissector",	FLOW_DISSECTOR, BPF_FLOW_DISSECTOR, SEC_ATTACHABLE_OPT),
10160 	SEC_DEF("cgroup_skb/ingress",	CGROUP_SKB, BPF_CGROUP_INET_INGRESS, SEC_ATTACHABLE_OPT),
10161 	SEC_DEF("cgroup_skb/egress",	CGROUP_SKB, BPF_CGROUP_INET_EGRESS, SEC_ATTACHABLE_OPT),
10162 	SEC_DEF("cgroup/skb",		CGROUP_SKB, 0, SEC_NONE),
10163 	SEC_DEF("cgroup/sock_create",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE),
10164 	SEC_DEF("cgroup/sock_release",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_RELEASE, SEC_ATTACHABLE),
10165 	SEC_DEF("cgroup/sock",		CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE_OPT),
10166 	SEC_DEF("cgroup/post_bind4",	CGROUP_SOCK, BPF_CGROUP_INET4_POST_BIND, SEC_ATTACHABLE),
10167 	SEC_DEF("cgroup/post_bind6",	CGROUP_SOCK, BPF_CGROUP_INET6_POST_BIND, SEC_ATTACHABLE),
10168 	SEC_DEF("cgroup/bind4",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND, SEC_ATTACHABLE),
10169 	SEC_DEF("cgroup/bind6",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND, SEC_ATTACHABLE),
10170 	SEC_DEF("cgroup/connect4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT, SEC_ATTACHABLE),
10171 	SEC_DEF("cgroup/connect6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT, SEC_ATTACHABLE),
10172 	SEC_DEF("cgroup/connect_unix",	CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_CONNECT, SEC_ATTACHABLE),
10173 	SEC_DEF("cgroup/sendmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG, SEC_ATTACHABLE),
10174 	SEC_DEF("cgroup/sendmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG, SEC_ATTACHABLE),
10175 	SEC_DEF("cgroup/sendmsg_unix",	CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_SENDMSG, SEC_ATTACHABLE),
10176 	SEC_DEF("cgroup/recvmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_RECVMSG, SEC_ATTACHABLE),
10177 	SEC_DEF("cgroup/recvmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_RECVMSG, SEC_ATTACHABLE),
10178 	SEC_DEF("cgroup/recvmsg_unix",	CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_RECVMSG, SEC_ATTACHABLE),
10179 	SEC_DEF("cgroup/getpeername4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETPEERNAME, SEC_ATTACHABLE),
10180 	SEC_DEF("cgroup/getpeername6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETPEERNAME, SEC_ATTACHABLE),
10181 	SEC_DEF("cgroup/getpeername_unix", CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_GETPEERNAME, SEC_ATTACHABLE),
10182 	SEC_DEF("cgroup/getsockname4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETSOCKNAME, SEC_ATTACHABLE),
10183 	SEC_DEF("cgroup/getsockname6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETSOCKNAME, SEC_ATTACHABLE),
10184 	SEC_DEF("cgroup/getsockname_unix", CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_GETSOCKNAME, SEC_ATTACHABLE),
10185 	SEC_DEF("cgroup/sysctl",	CGROUP_SYSCTL, BPF_CGROUP_SYSCTL, SEC_ATTACHABLE),
10186 	SEC_DEF("cgroup/getsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_GETSOCKOPT, SEC_ATTACHABLE),
10187 	SEC_DEF("cgroup/setsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_SETSOCKOPT, SEC_ATTACHABLE),
10188 	SEC_DEF("cgroup/dev",		CGROUP_DEVICE, BPF_CGROUP_DEVICE, SEC_ATTACHABLE_OPT),
10189 	SEC_DEF("struct_ops+",		STRUCT_OPS, 0, SEC_NONE),
10190 	SEC_DEF("struct_ops.s+",	STRUCT_OPS, 0, SEC_SLEEPABLE),
10191 	SEC_DEF("sk_lookup",		SK_LOOKUP, BPF_SK_LOOKUP, SEC_ATTACHABLE),
10192 	SEC_DEF("netfilter",		NETFILTER, BPF_NETFILTER, SEC_NONE),
10193 };
10194 
10195 int libbpf_register_prog_handler(const char *sec,
10196 				 enum bpf_prog_type prog_type,
10197 				 enum bpf_attach_type exp_attach_type,
10198 				 const struct libbpf_prog_handler_opts *opts)
10199 {
10200 	struct bpf_sec_def *sec_def;
10201 
10202 	if (!OPTS_VALID(opts, libbpf_prog_handler_opts))
10203 		return libbpf_err(-EINVAL);
10204 
10205 	if (last_custom_sec_def_handler_id == INT_MAX) /* prevent overflow */
10206 		return libbpf_err(-E2BIG);
10207 
10208 	if (sec) {
10209 		sec_def = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt + 1,
10210 					      sizeof(*sec_def));
10211 		if (!sec_def)
10212 			return libbpf_err(-ENOMEM);
10213 
10214 		custom_sec_defs = sec_def;
10215 		sec_def = &custom_sec_defs[custom_sec_def_cnt];
10216 	} else {
10217 		if (has_custom_fallback_def)
10218 			return libbpf_err(-EBUSY);
10219 
10220 		sec_def = &custom_fallback_def;
10221 	}
10222 
10223 	sec_def->sec = sec ? strdup(sec) : NULL;
10224 	if (sec && !sec_def->sec)
10225 		return libbpf_err(-ENOMEM);
10226 
10227 	sec_def->prog_type = prog_type;
10228 	sec_def->expected_attach_type = exp_attach_type;
10229 	sec_def->cookie = OPTS_GET(opts, cookie, 0);
10230 
10231 	sec_def->prog_setup_fn = OPTS_GET(opts, prog_setup_fn, NULL);
10232 	sec_def->prog_prepare_load_fn = OPTS_GET(opts, prog_prepare_load_fn, NULL);
10233 	sec_def->prog_attach_fn = OPTS_GET(opts, prog_attach_fn, NULL);
10234 
10235 	sec_def->handler_id = ++last_custom_sec_def_handler_id;
10236 
10237 	if (sec)
10238 		custom_sec_def_cnt++;
10239 	else
10240 		has_custom_fallback_def = true;
10241 
10242 	return sec_def->handler_id;
10243 }
10244 
10245 int libbpf_unregister_prog_handler(int handler_id)
10246 {
10247 	struct bpf_sec_def *sec_defs;
10248 	int i;
10249 
10250 	if (handler_id <= 0)
10251 		return libbpf_err(-EINVAL);
10252 
10253 	if (has_custom_fallback_def && custom_fallback_def.handler_id == handler_id) {
10254 		memset(&custom_fallback_def, 0, sizeof(custom_fallback_def));
10255 		has_custom_fallback_def = false;
10256 		return 0;
10257 	}
10258 
10259 	for (i = 0; i < custom_sec_def_cnt; i++) {
10260 		if (custom_sec_defs[i].handler_id == handler_id)
10261 			break;
10262 	}
10263 
10264 	if (i == custom_sec_def_cnt)
10265 		return libbpf_err(-ENOENT);
10266 
10267 	free(custom_sec_defs[i].sec);
10268 	for (i = i + 1; i < custom_sec_def_cnt; i++)
10269 		custom_sec_defs[i - 1] = custom_sec_defs[i];
10270 	custom_sec_def_cnt--;
10271 
10272 	/* try to shrink the array, but it's ok if we couldn't */
10273 	sec_defs = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt, sizeof(*sec_defs));
10274 	/* if new count is zero, reallocarray can return a valid NULL result;
10275 	 * in this case the previous pointer will be freed, so we *have to*
10276 	 * reassign old pointer to the new value (even if it's NULL)
10277 	 */
10278 	if (sec_defs || custom_sec_def_cnt == 0)
10279 		custom_sec_defs = sec_defs;
10280 
10281 	return 0;
10282 }
10283 
10284 static bool sec_def_matches(const struct bpf_sec_def *sec_def, const char *sec_name)
10285 {
10286 	size_t len = strlen(sec_def->sec);
10287 
10288 	/* "type/" always has to have proper SEC("type/extras") form */
10289 	if (sec_def->sec[len - 1] == '/') {
10290 		if (str_has_pfx(sec_name, sec_def->sec))
10291 			return true;
10292 		return false;
10293 	}
10294 
10295 	/* "type+" means it can be either exact SEC("type") or
10296 	 * well-formed SEC("type/extras") with proper '/' separator
10297 	 */
10298 	if (sec_def->sec[len - 1] == '+') {
10299 		len--;
10300 		/* not even a prefix */
10301 		if (strncmp(sec_name, sec_def->sec, len) != 0)
10302 			return false;
10303 		/* exact match or has '/' separator */
10304 		if (sec_name[len] == '\0' || sec_name[len] == '/')
10305 			return true;
10306 		return false;
10307 	}
10308 
10309 	return strcmp(sec_name, sec_def->sec) == 0;
10310 }
10311 
10312 static const struct bpf_sec_def *find_sec_def(const char *sec_name)
10313 {
10314 	const struct bpf_sec_def *sec_def;
10315 	int i, n;
10316 
10317 	n = custom_sec_def_cnt;
10318 	for (i = 0; i < n; i++) {
10319 		sec_def = &custom_sec_defs[i];
10320 		if (sec_def_matches(sec_def, sec_name))
10321 			return sec_def;
10322 	}
10323 
10324 	n = ARRAY_SIZE(section_defs);
10325 	for (i = 0; i < n; i++) {
10326 		sec_def = &section_defs[i];
10327 		if (sec_def_matches(sec_def, sec_name))
10328 			return sec_def;
10329 	}
10330 
10331 	if (has_custom_fallback_def)
10332 		return &custom_fallback_def;
10333 
10334 	return NULL;
10335 }
10336 
10337 #define MAX_TYPE_NAME_SIZE 32
10338 
10339 static char *libbpf_get_type_names(bool attach_type)
10340 {
10341 	int i, len = ARRAY_SIZE(section_defs) * MAX_TYPE_NAME_SIZE;
10342 	char *buf;
10343 
10344 	buf = malloc(len);
10345 	if (!buf)
10346 		return NULL;
10347 
10348 	buf[0] = '\0';
10349 	/* Forge string buf with all available names */
10350 	for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
10351 		const struct bpf_sec_def *sec_def = &section_defs[i];
10352 
10353 		if (attach_type) {
10354 			if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
10355 				continue;
10356 
10357 			if (!(sec_def->cookie & SEC_ATTACHABLE))
10358 				continue;
10359 		}
10360 
10361 		if (strlen(buf) + strlen(section_defs[i].sec) + 2 > len) {
10362 			free(buf);
10363 			return NULL;
10364 		}
10365 		strcat(buf, " ");
10366 		strcat(buf, section_defs[i].sec);
10367 	}
10368 
10369 	return buf;
10370 }
10371 
10372 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
10373 			     enum bpf_attach_type *expected_attach_type)
10374 {
10375 	const struct bpf_sec_def *sec_def;
10376 	char *type_names;
10377 
10378 	if (!name)
10379 		return libbpf_err(-EINVAL);
10380 
10381 	sec_def = find_sec_def(name);
10382 	if (sec_def) {
10383 		*prog_type = sec_def->prog_type;
10384 		*expected_attach_type = sec_def->expected_attach_type;
10385 		return 0;
10386 	}
10387 
10388 	pr_debug("failed to guess program type from ELF section '%s'\n", name);
10389 	type_names = libbpf_get_type_names(false);
10390 	if (type_names != NULL) {
10391 		pr_debug("supported section(type) names are:%s\n", type_names);
10392 		free(type_names);
10393 	}
10394 
10395 	return libbpf_err(-ESRCH);
10396 }
10397 
10398 const char *libbpf_bpf_attach_type_str(enum bpf_attach_type t)
10399 {
10400 	if (t < 0 || t >= ARRAY_SIZE(attach_type_name))
10401 		return NULL;
10402 
10403 	return attach_type_name[t];
10404 }
10405 
10406 const char *libbpf_bpf_link_type_str(enum bpf_link_type t)
10407 {
10408 	if (t < 0 || t >= ARRAY_SIZE(link_type_name))
10409 		return NULL;
10410 
10411 	return link_type_name[t];
10412 }
10413 
10414 const char *libbpf_bpf_map_type_str(enum bpf_map_type t)
10415 {
10416 	if (t < 0 || t >= ARRAY_SIZE(map_type_name))
10417 		return NULL;
10418 
10419 	return map_type_name[t];
10420 }
10421 
10422 const char *libbpf_bpf_prog_type_str(enum bpf_prog_type t)
10423 {
10424 	if (t < 0 || t >= ARRAY_SIZE(prog_type_name))
10425 		return NULL;
10426 
10427 	return prog_type_name[t];
10428 }
10429 
10430 static struct bpf_map *find_struct_ops_map_by_offset(struct bpf_object *obj,
10431 						     int sec_idx,
10432 						     size_t offset)
10433 {
10434 	struct bpf_map *map;
10435 	size_t i;
10436 
10437 	for (i = 0; i < obj->nr_maps; i++) {
10438 		map = &obj->maps[i];
10439 		if (!bpf_map__is_struct_ops(map))
10440 			continue;
10441 		if (map->sec_idx == sec_idx &&
10442 		    map->sec_offset <= offset &&
10443 		    offset - map->sec_offset < map->def.value_size)
10444 			return map;
10445 	}
10446 
10447 	return NULL;
10448 }
10449 
10450 /* Collect the reloc from ELF, populate the st_ops->progs[], and update
10451  * st_ops->data for shadow type.
10452  */
10453 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
10454 					    Elf64_Shdr *shdr, Elf_Data *data)
10455 {
10456 	const struct btf_type *type;
10457 	const struct btf_member *member;
10458 	struct bpf_struct_ops *st_ops;
10459 	struct bpf_program *prog;
10460 	unsigned int shdr_idx;
10461 	const struct btf *btf;
10462 	struct bpf_map *map;
10463 	unsigned int moff, insn_idx;
10464 	const char *name;
10465 	__u32 member_idx;
10466 	Elf64_Sym *sym;
10467 	Elf64_Rel *rel;
10468 	int i, nrels;
10469 
10470 	btf = obj->btf;
10471 	nrels = shdr->sh_size / shdr->sh_entsize;
10472 	for (i = 0; i < nrels; i++) {
10473 		rel = elf_rel_by_idx(data, i);
10474 		if (!rel) {
10475 			pr_warn("struct_ops reloc: failed to get %d reloc\n", i);
10476 			return -LIBBPF_ERRNO__FORMAT;
10477 		}
10478 
10479 		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
10480 		if (!sym) {
10481 			pr_warn("struct_ops reloc: symbol %zx not found\n",
10482 				(size_t)ELF64_R_SYM(rel->r_info));
10483 			return -LIBBPF_ERRNO__FORMAT;
10484 		}
10485 
10486 		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
10487 		map = find_struct_ops_map_by_offset(obj, shdr->sh_info, rel->r_offset);
10488 		if (!map) {
10489 			pr_warn("struct_ops reloc: cannot find map at rel->r_offset %zu\n",
10490 				(size_t)rel->r_offset);
10491 			return -EINVAL;
10492 		}
10493 
10494 		moff = rel->r_offset - map->sec_offset;
10495 		shdr_idx = sym->st_shndx;
10496 		st_ops = map->st_ops;
10497 		pr_debug("struct_ops reloc %s: for %lld value %lld shdr_idx %u rel->r_offset %zu map->sec_offset %zu name %d (\'%s\')\n",
10498 			 map->name,
10499 			 (long long)(rel->r_info >> 32),
10500 			 (long long)sym->st_value,
10501 			 shdr_idx, (size_t)rel->r_offset,
10502 			 map->sec_offset, sym->st_name, name);
10503 
10504 		if (shdr_idx >= SHN_LORESERVE) {
10505 			pr_warn("struct_ops reloc %s: rel->r_offset %zu shdr_idx %u unsupported non-static function\n",
10506 				map->name, (size_t)rel->r_offset, shdr_idx);
10507 			return -LIBBPF_ERRNO__RELOC;
10508 		}
10509 		if (sym->st_value % BPF_INSN_SZ) {
10510 			pr_warn("struct_ops reloc %s: invalid target program offset %llu\n",
10511 				map->name, (unsigned long long)sym->st_value);
10512 			return -LIBBPF_ERRNO__FORMAT;
10513 		}
10514 		insn_idx = sym->st_value / BPF_INSN_SZ;
10515 
10516 		type = btf__type_by_id(btf, st_ops->type_id);
10517 		member = find_member_by_offset(type, moff * 8);
10518 		if (!member) {
10519 			pr_warn("struct_ops reloc %s: cannot find member at moff %u\n",
10520 				map->name, moff);
10521 			return -EINVAL;
10522 		}
10523 		member_idx = member - btf_members(type);
10524 		name = btf__name_by_offset(btf, member->name_off);
10525 
10526 		if (!resolve_func_ptr(btf, member->type, NULL)) {
10527 			pr_warn("struct_ops reloc %s: cannot relocate non func ptr %s\n",
10528 				map->name, name);
10529 			return -EINVAL;
10530 		}
10531 
10532 		prog = find_prog_by_sec_insn(obj, shdr_idx, insn_idx);
10533 		if (!prog) {
10534 			pr_warn("struct_ops reloc %s: cannot find prog at shdr_idx %u to relocate func ptr %s\n",
10535 				map->name, shdr_idx, name);
10536 			return -EINVAL;
10537 		}
10538 
10539 		/* prevent the use of BPF prog with invalid type */
10540 		if (prog->type != BPF_PROG_TYPE_STRUCT_OPS) {
10541 			pr_warn("struct_ops reloc %s: prog %s is not struct_ops BPF program\n",
10542 				map->name, prog->name);
10543 			return -EINVAL;
10544 		}
10545 
10546 		st_ops->progs[member_idx] = prog;
10547 
10548 		/* st_ops->data will be exposed to users, being returned by
10549 		 * bpf_map__initial_value() as a pointer to the shadow
10550 		 * type. All function pointers in the original struct type
10551 		 * should be converted to a pointer to struct bpf_program
10552 		 * in the shadow type.
10553 		 */
10554 		*((struct bpf_program **)(st_ops->data + moff)) = prog;
10555 	}
10556 
10557 	return 0;
10558 }
10559 
10560 #define BTF_TRACE_PREFIX "btf_trace_"
10561 #define BTF_LSM_PREFIX "bpf_lsm_"
10562 #define BTF_ITER_PREFIX "bpf_iter_"
10563 #define BTF_MAX_NAME_SIZE 128
10564 
10565 void btf_get_kernel_prefix_kind(enum bpf_attach_type attach_type,
10566 				const char **prefix, int *kind)
10567 {
10568 	switch (attach_type) {
10569 	case BPF_TRACE_RAW_TP:
10570 		*prefix = BTF_TRACE_PREFIX;
10571 		*kind = BTF_KIND_TYPEDEF;
10572 		break;
10573 	case BPF_LSM_MAC:
10574 	case BPF_LSM_CGROUP:
10575 		*prefix = BTF_LSM_PREFIX;
10576 		*kind = BTF_KIND_FUNC;
10577 		break;
10578 	case BPF_TRACE_ITER:
10579 		*prefix = BTF_ITER_PREFIX;
10580 		*kind = BTF_KIND_FUNC;
10581 		break;
10582 	default:
10583 		*prefix = "";
10584 		*kind = BTF_KIND_FUNC;
10585 	}
10586 }
10587 
10588 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
10589 				   const char *name, __u32 kind)
10590 {
10591 	char btf_type_name[BTF_MAX_NAME_SIZE];
10592 	int ret;
10593 
10594 	ret = snprintf(btf_type_name, sizeof(btf_type_name),
10595 		       "%s%s", prefix, name);
10596 	/* snprintf returns the number of characters written excluding the
10597 	 * terminating null. So, if >= BTF_MAX_NAME_SIZE are written, it
10598 	 * indicates truncation.
10599 	 */
10600 	if (ret < 0 || ret >= sizeof(btf_type_name))
10601 		return -ENAMETOOLONG;
10602 	return btf__find_by_name_kind(btf, btf_type_name, kind);
10603 }
10604 
10605 static inline int find_attach_btf_id(struct btf *btf, const char *name,
10606 				     enum bpf_attach_type attach_type)
10607 {
10608 	const char *prefix;
10609 	int kind;
10610 
10611 	btf_get_kernel_prefix_kind(attach_type, &prefix, &kind);
10612 	return find_btf_by_prefix_kind(btf, prefix, name, kind);
10613 }
10614 
10615 int libbpf_find_vmlinux_btf_id(const char *name,
10616 			       enum bpf_attach_type attach_type)
10617 {
10618 	struct btf *btf;
10619 	int err;
10620 
10621 	btf = btf__load_vmlinux_btf();
10622 	err = libbpf_get_error(btf);
10623 	if (err) {
10624 		pr_warn("vmlinux BTF is not found\n");
10625 		return libbpf_err(err);
10626 	}
10627 
10628 	err = find_attach_btf_id(btf, name, attach_type);
10629 	if (err <= 0)
10630 		pr_warn("%s is not found in vmlinux BTF\n", name);
10631 
10632 	btf__free(btf);
10633 	return libbpf_err(err);
10634 }
10635 
10636 static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd, int token_fd)
10637 {
10638 	struct bpf_prog_info info;
10639 	__u32 info_len = sizeof(info);
10640 	struct btf *btf;
10641 	int err;
10642 
10643 	memset(&info, 0, info_len);
10644 	err = bpf_prog_get_info_by_fd(attach_prog_fd, &info, &info_len);
10645 	if (err) {
10646 		pr_warn("failed bpf_prog_get_info_by_fd for FD %d: %s\n",
10647 			attach_prog_fd, errstr(err));
10648 		return err;
10649 	}
10650 
10651 	err = -EINVAL;
10652 	if (!info.btf_id) {
10653 		pr_warn("The target program doesn't have BTF\n");
10654 		goto out;
10655 	}
10656 	btf = btf_load_from_kernel(info.btf_id, NULL, token_fd);
10657 	err = libbpf_get_error(btf);
10658 	if (err) {
10659 		pr_warn("Failed to get BTF %d of the program: %s\n", info.btf_id, errstr(err));
10660 		goto out;
10661 	}
10662 	err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
10663 	btf__free(btf);
10664 	if (err <= 0) {
10665 		pr_warn("%s is not found in prog's BTF\n", name);
10666 		goto out;
10667 	}
10668 out:
10669 	return err;
10670 }
10671 
10672 static int find_kernel_btf_id(struct bpf_object *obj, const char *attach_name,
10673 			      enum bpf_attach_type attach_type,
10674 			      int *btf_obj_fd, int *btf_type_id)
10675 {
10676 	int ret, i, mod_len = 0;
10677 	const char *fn_name, *mod_name = NULL;
10678 
10679 	fn_name = strchr(attach_name, ':');
10680 	if (fn_name) {
10681 		mod_name = attach_name;
10682 		mod_len = fn_name - mod_name;
10683 		fn_name++;
10684 	}
10685 
10686 	if (!mod_name || strncmp(mod_name, "vmlinux", mod_len) == 0) {
10687 		ret = find_attach_btf_id(obj->btf_vmlinux,
10688 					 mod_name ? fn_name : attach_name,
10689 					 attach_type);
10690 		if (ret > 0) {
10691 			*btf_obj_fd = 0; /* vmlinux BTF */
10692 			*btf_type_id = ret;
10693 			return 0;
10694 		}
10695 		if (ret != -ENOENT)
10696 			return ret;
10697 	}
10698 
10699 	ret = load_module_btfs(obj);
10700 	if (ret)
10701 		return ret;
10702 
10703 	for (i = 0; i < obj->btf_module_cnt; i++) {
10704 		const struct module_btf *mod = &obj->btf_modules[i];
10705 
10706 		if (mod_name && strncmp(mod->name, mod_name, mod_len) != 0)
10707 			continue;
10708 
10709 		ret = find_attach_btf_id(mod->btf,
10710 					 mod_name ? fn_name : attach_name,
10711 					 attach_type);
10712 		if (ret > 0) {
10713 			*btf_obj_fd = mod->fd;
10714 			*btf_type_id = ret;
10715 			return 0;
10716 		}
10717 		if (ret == -ENOENT)
10718 			continue;
10719 
10720 		return ret;
10721 	}
10722 
10723 	return -ESRCH;
10724 }
10725 
10726 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
10727 				     int *btf_obj_fd, int *btf_type_id)
10728 {
10729 	enum bpf_attach_type attach_type = prog->expected_attach_type;
10730 	__u32 attach_prog_fd = prog->attach_prog_fd;
10731 	int err = 0;
10732 
10733 	/* BPF program's BTF ID */
10734 	if (prog->type == BPF_PROG_TYPE_EXT || attach_prog_fd) {
10735 		if (!attach_prog_fd) {
10736 			pr_warn("prog '%s': attach program FD is not set\n", prog->name);
10737 			return -EINVAL;
10738 		}
10739 		err = libbpf_find_prog_btf_id(attach_name, attach_prog_fd, prog->obj->token_fd);
10740 		if (err < 0) {
10741 			pr_warn("prog '%s': failed to find BPF program (FD %d) BTF ID for '%s': %s\n",
10742 				prog->name, attach_prog_fd, attach_name, errstr(err));
10743 			return err;
10744 		}
10745 		*btf_obj_fd = 0;
10746 		*btf_type_id = err;
10747 		return 0;
10748 	}
10749 
10750 	/* kernel/module BTF ID */
10751 	if (prog->obj->gen_loader) {
10752 		bpf_gen__record_attach_target(prog->obj->gen_loader, attach_name, attach_type);
10753 		*btf_obj_fd = 0;
10754 		*btf_type_id = 1;
10755 	} else {
10756 		err = find_kernel_btf_id(prog->obj, attach_name,
10757 					 attach_type, btf_obj_fd,
10758 					 btf_type_id);
10759 	}
10760 	if (err) {
10761 		pr_warn("prog '%s': failed to find kernel BTF type ID of '%s': %s\n",
10762 			prog->name, attach_name, errstr(err));
10763 		return err;
10764 	}
10765 	return 0;
10766 }
10767 
10768 int libbpf_attach_type_by_name(const char *name,
10769 			       enum bpf_attach_type *attach_type)
10770 {
10771 	char *type_names;
10772 	const struct bpf_sec_def *sec_def;
10773 
10774 	if (!name)
10775 		return libbpf_err(-EINVAL);
10776 
10777 	sec_def = find_sec_def(name);
10778 	if (!sec_def) {
10779 		pr_debug("failed to guess attach type based on ELF section name '%s'\n", name);
10780 		type_names = libbpf_get_type_names(true);
10781 		if (type_names != NULL) {
10782 			pr_debug("attachable section(type) names are:%s\n", type_names);
10783 			free(type_names);
10784 		}
10785 
10786 		return libbpf_err(-EINVAL);
10787 	}
10788 
10789 	if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
10790 		return libbpf_err(-EINVAL);
10791 	if (!(sec_def->cookie & SEC_ATTACHABLE))
10792 		return libbpf_err(-EINVAL);
10793 
10794 	*attach_type = sec_def->expected_attach_type;
10795 	return 0;
10796 }
10797 
10798 int bpf_map__fd(const struct bpf_map *map)
10799 {
10800 	if (!map)
10801 		return libbpf_err(-EINVAL);
10802 	if (!map_is_created(map))
10803 		return -1;
10804 	return map->fd;
10805 }
10806 
10807 static bool map_uses_real_name(const struct bpf_map *map)
10808 {
10809 	/* Since libbpf started to support custom .data.* and .rodata.* maps,
10810 	 * their user-visible name differs from kernel-visible name. Users see
10811 	 * such map's corresponding ELF section name as a map name.
10812 	 * This check distinguishes .data/.rodata from .data.* and .rodata.*
10813 	 * maps to know which name has to be returned to the user.
10814 	 */
10815 	if (map->libbpf_type == LIBBPF_MAP_DATA && strcmp(map->real_name, DATA_SEC) != 0)
10816 		return true;
10817 	if (map->libbpf_type == LIBBPF_MAP_RODATA && strcmp(map->real_name, RODATA_SEC) != 0)
10818 		return true;
10819 	return false;
10820 }
10821 
10822 const char *bpf_map__name(const struct bpf_map *map)
10823 {
10824 	if (!map)
10825 		return NULL;
10826 
10827 	if (map_uses_real_name(map))
10828 		return map->real_name;
10829 
10830 	return map->name;
10831 }
10832 
10833 enum bpf_map_type bpf_map__type(const struct bpf_map *map)
10834 {
10835 	return map->def.type;
10836 }
10837 
10838 int bpf_map__set_type(struct bpf_map *map, enum bpf_map_type type)
10839 {
10840 	if (map_is_created(map))
10841 		return libbpf_err(-EBUSY);
10842 	map->def.type = type;
10843 	return 0;
10844 }
10845 
10846 __u32 bpf_map__map_flags(const struct bpf_map *map)
10847 {
10848 	return map->def.map_flags;
10849 }
10850 
10851 int bpf_map__set_map_flags(struct bpf_map *map, __u32 flags)
10852 {
10853 	if (map_is_created(map))
10854 		return libbpf_err(-EBUSY);
10855 	map->def.map_flags = flags;
10856 	return 0;
10857 }
10858 
10859 __u64 bpf_map__map_extra(const struct bpf_map *map)
10860 {
10861 	return map->map_extra;
10862 }
10863 
10864 int bpf_map__set_map_extra(struct bpf_map *map, __u64 map_extra)
10865 {
10866 	if (map_is_created(map))
10867 		return libbpf_err(-EBUSY);
10868 	map->map_extra = map_extra;
10869 	return 0;
10870 }
10871 
10872 __u32 bpf_map__numa_node(const struct bpf_map *map)
10873 {
10874 	return map->numa_node;
10875 }
10876 
10877 int bpf_map__set_numa_node(struct bpf_map *map, __u32 numa_node)
10878 {
10879 	if (map_is_created(map))
10880 		return libbpf_err(-EBUSY);
10881 	map->numa_node = numa_node;
10882 	return 0;
10883 }
10884 
10885 __u32 bpf_map__key_size(const struct bpf_map *map)
10886 {
10887 	return map->def.key_size;
10888 }
10889 
10890 int bpf_map__set_key_size(struct bpf_map *map, __u32 size)
10891 {
10892 	if (map_is_created(map))
10893 		return libbpf_err(-EBUSY);
10894 	map->def.key_size = size;
10895 	return 0;
10896 }
10897 
10898 __u32 bpf_map__value_size(const struct bpf_map *map)
10899 {
10900 	return map->def.value_size;
10901 }
10902 
10903 static int map_btf_datasec_resize(struct bpf_map *map, __u32 size)
10904 {
10905 	struct btf *btf;
10906 	struct btf_type *datasec_type, *var_type;
10907 	struct btf_var_secinfo *var;
10908 	const struct btf_type *array_type;
10909 	const struct btf_array *array;
10910 	int vlen, element_sz, new_array_id;
10911 	__u32 nr_elements;
10912 
10913 	/* check btf existence */
10914 	btf = bpf_object__btf(map->obj);
10915 	if (!btf)
10916 		return -ENOENT;
10917 
10918 	/* verify map is datasec */
10919 	datasec_type = btf_type_by_id(btf, bpf_map__btf_value_type_id(map));
10920 	if (!btf_is_datasec(datasec_type)) {
10921 		pr_warn("map '%s': cannot be resized, map value type is not a datasec\n",
10922 			bpf_map__name(map));
10923 		return -EINVAL;
10924 	}
10925 
10926 	/* verify datasec has at least one var */
10927 	vlen = btf_vlen(datasec_type);
10928 	if (vlen == 0) {
10929 		pr_warn("map '%s': cannot be resized, map value datasec is empty\n",
10930 			bpf_map__name(map));
10931 		return -EINVAL;
10932 	}
10933 
10934 	/* verify last var in the datasec is an array */
10935 	var = &btf_var_secinfos(datasec_type)[vlen - 1];
10936 	var_type = btf_type_by_id(btf, var->type);
10937 	array_type = skip_mods_and_typedefs(btf, var_type->type, NULL);
10938 	if (!btf_is_array(array_type)) {
10939 		pr_warn("map '%s': cannot be resized, last var must be an array\n",
10940 			bpf_map__name(map));
10941 		return -EINVAL;
10942 	}
10943 
10944 	/* verify request size aligns with array */
10945 	array = btf_array(array_type);
10946 	element_sz = btf__resolve_size(btf, array->type);
10947 	if (element_sz <= 0 || (size - var->offset) % element_sz != 0) {
10948 		pr_warn("map '%s': cannot be resized, element size (%d) doesn't align with new total size (%u)\n",
10949 			bpf_map__name(map), element_sz, size);
10950 		return -EINVAL;
10951 	}
10952 
10953 	/* create a new array based on the existing array, but with new length */
10954 	nr_elements = (size - var->offset) / element_sz;
10955 	new_array_id = btf__add_array(btf, array->index_type, array->type, nr_elements);
10956 	if (new_array_id < 0)
10957 		return new_array_id;
10958 
10959 	/* adding a new btf type invalidates existing pointers to btf objects,
10960 	 * so refresh pointers before proceeding
10961 	 */
10962 	datasec_type = btf_type_by_id(btf, map->btf_value_type_id);
10963 	var = &btf_var_secinfos(datasec_type)[vlen - 1];
10964 	var_type = btf_type_by_id(btf, var->type);
10965 
10966 	/* finally update btf info */
10967 	datasec_type->size = size;
10968 	var->size = size - var->offset;
10969 	var_type->type = new_array_id;
10970 
10971 	return 0;
10972 }
10973 
10974 int bpf_map__set_value_size(struct bpf_map *map, __u32 size)
10975 {
10976 	if (map_is_created(map))
10977 		return libbpf_err(-EBUSY);
10978 
10979 	if (map->mmaped) {
10980 		size_t mmap_old_sz, mmap_new_sz;
10981 		int err;
10982 
10983 		if (map->def.type != BPF_MAP_TYPE_ARRAY)
10984 			return libbpf_err(-EOPNOTSUPP);
10985 
10986 		mmap_old_sz = bpf_map_mmap_sz(map);
10987 		mmap_new_sz = array_map_mmap_sz(size, map->def.max_entries);
10988 		err = bpf_map_mmap_resize(map, mmap_old_sz, mmap_new_sz);
10989 		if (err) {
10990 			pr_warn("map '%s': failed to resize memory-mapped region: %s\n",
10991 				bpf_map__name(map), errstr(err));
10992 			return libbpf_err(err);
10993 		}
10994 		err = map_btf_datasec_resize(map, size);
10995 		if (err && err != -ENOENT) {
10996 			pr_warn("map '%s': failed to adjust resized BTF, clearing BTF key/value info: %s\n",
10997 				bpf_map__name(map), errstr(err));
10998 			map->btf_value_type_id = 0;
10999 			map->btf_key_type_id = 0;
11000 		}
11001 	}
11002 
11003 	map->def.value_size = size;
11004 	return 0;
11005 }
11006 
11007 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
11008 {
11009 	return map ? map->btf_key_type_id : 0;
11010 }
11011 
11012 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
11013 {
11014 	return map ? map->btf_value_type_id : 0;
11015 }
11016 
11017 int bpf_map__set_initial_value(struct bpf_map *map,
11018 			       const void *data, size_t size)
11019 {
11020 	size_t actual_sz;
11021 
11022 	if (map_is_created(map))
11023 		return libbpf_err(-EBUSY);
11024 
11025 	if (!map->mmaped || map->libbpf_type == LIBBPF_MAP_KCONFIG)
11026 		return libbpf_err(-EINVAL);
11027 
11028 	if (map->def.type == BPF_MAP_TYPE_ARENA)
11029 		actual_sz = map->obj->arena_data_sz;
11030 	else
11031 		actual_sz = map->def.value_size;
11032 	if (size != actual_sz)
11033 		return libbpf_err(-EINVAL);
11034 
11035 	memcpy(map->mmaped, data, size);
11036 	return 0;
11037 }
11038 
11039 void *bpf_map__initial_value(const struct bpf_map *map, size_t *psize)
11040 {
11041 	if (bpf_map__is_struct_ops(map)) {
11042 		if (psize)
11043 			*psize = map->def.value_size;
11044 		return map->st_ops->data;
11045 	}
11046 
11047 	if (!map->mmaped)
11048 		return NULL;
11049 
11050 	if (map->def.type == BPF_MAP_TYPE_ARENA)
11051 		*psize = map->obj->arena_data_sz;
11052 	else
11053 		*psize = map->def.value_size;
11054 
11055 	return map->mmaped;
11056 }
11057 
11058 bool bpf_map__is_internal(const struct bpf_map *map)
11059 {
11060 	return map->libbpf_type != LIBBPF_MAP_UNSPEC;
11061 }
11062 
11063 __u32 bpf_map__ifindex(const struct bpf_map *map)
11064 {
11065 	return map->map_ifindex;
11066 }
11067 
11068 int bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
11069 {
11070 	if (map_is_created(map))
11071 		return libbpf_err(-EBUSY);
11072 	map->map_ifindex = ifindex;
11073 	return 0;
11074 }
11075 
11076 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
11077 {
11078 	if (!bpf_map_type__is_map_in_map(map->def.type)) {
11079 		pr_warn("error: unsupported map type\n");
11080 		return libbpf_err(-EINVAL);
11081 	}
11082 	if (map->inner_map_fd != -1) {
11083 		pr_warn("error: inner_map_fd already specified\n");
11084 		return libbpf_err(-EINVAL);
11085 	}
11086 	if (map->inner_map) {
11087 		bpf_map__destroy(map->inner_map);
11088 		zfree(&map->inner_map);
11089 	}
11090 	map->inner_map_fd = fd;
11091 	return 0;
11092 }
11093 
11094 int bpf_map__set_exclusive_program(struct bpf_map *map, struct bpf_program *prog)
11095 {
11096 	if (map_is_created(map)) {
11097 		pr_warn("exclusive programs must be set before map creation\n");
11098 		return libbpf_err(-EINVAL);
11099 	}
11100 
11101 	if (map->obj != prog->obj) {
11102 		pr_warn("excl_prog and map must be from the same bpf object\n");
11103 		return libbpf_err(-EINVAL);
11104 	}
11105 
11106 	map->excl_prog = prog;
11107 	return 0;
11108 }
11109 
11110 struct bpf_program *bpf_map__exclusive_program(struct bpf_map *map)
11111 {
11112 	return map->excl_prog;
11113 }
11114 
11115 static struct bpf_map *
11116 __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
11117 {
11118 	ssize_t idx;
11119 	struct bpf_map *s, *e;
11120 
11121 	if (!obj || !obj->maps)
11122 		return errno = EINVAL, NULL;
11123 
11124 	s = obj->maps;
11125 	e = obj->maps + obj->nr_maps;
11126 
11127 	if ((m < s) || (m >= e)) {
11128 		pr_warn("error in %s: map handler doesn't belong to object\n",
11129 			 __func__);
11130 		return errno = EINVAL, NULL;
11131 	}
11132 
11133 	idx = (m - obj->maps) + i;
11134 	if (idx >= obj->nr_maps || idx < 0)
11135 		return NULL;
11136 	return &obj->maps[idx];
11137 }
11138 
11139 struct bpf_map *
11140 bpf_object__next_map(const struct bpf_object *obj, const struct bpf_map *prev)
11141 {
11142 	if (prev == NULL && obj != NULL)
11143 		return obj->maps;
11144 
11145 	return __bpf_map__iter(prev, obj, 1);
11146 }
11147 
11148 struct bpf_map *
11149 bpf_object__prev_map(const struct bpf_object *obj, const struct bpf_map *next)
11150 {
11151 	if (next == NULL && obj != NULL) {
11152 		if (!obj->nr_maps)
11153 			return NULL;
11154 		return obj->maps + obj->nr_maps - 1;
11155 	}
11156 
11157 	return __bpf_map__iter(next, obj, -1);
11158 }
11159 
11160 struct bpf_map *
11161 bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
11162 {
11163 	struct bpf_map *pos;
11164 
11165 	bpf_object__for_each_map(pos, obj) {
11166 		/* if it's a special internal map name (which always starts
11167 		 * with dot) then check if that special name matches the
11168 		 * real map name (ELF section name)
11169 		 */
11170 		if (name[0] == '.') {
11171 			if (pos->real_name && strcmp(pos->real_name, name) == 0)
11172 				return pos;
11173 			continue;
11174 		}
11175 		/* otherwise map name has to be an exact match */
11176 		if (map_uses_real_name(pos)) {
11177 			if (strcmp(pos->real_name, name) == 0)
11178 				return pos;
11179 			continue;
11180 		}
11181 		if (strcmp(pos->name, name) == 0)
11182 			return pos;
11183 	}
11184 	return errno = ENOENT, NULL;
11185 }
11186 
11187 int
11188 bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
11189 {
11190 	return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
11191 }
11192 
11193 static int validate_map_op(const struct bpf_map *map, size_t key_sz,
11194 			   size_t value_sz, bool check_value_sz, __u64 flags)
11195 {
11196 	if (!map_is_created(map)) /* map is not yet created */
11197 		return -ENOENT;
11198 
11199 	if (map->def.key_size != key_sz) {
11200 		pr_warn("map '%s': unexpected key size %zu provided, expected %u\n",
11201 			map->name, key_sz, map->def.key_size);
11202 		return -EINVAL;
11203 	}
11204 
11205 	if (map->fd < 0) {
11206 		pr_warn("map '%s': can't use BPF map without FD (was it created?)\n", map->name);
11207 		return -EINVAL;
11208 	}
11209 
11210 	if (!check_value_sz)
11211 		return 0;
11212 
11213 	switch (map->def.type) {
11214 	case BPF_MAP_TYPE_PERCPU_ARRAY:
11215 	case BPF_MAP_TYPE_PERCPU_HASH:
11216 	case BPF_MAP_TYPE_LRU_PERCPU_HASH:
11217 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: {
11218 		int num_cpu = libbpf_num_possible_cpus();
11219 		size_t elem_sz = roundup(map->def.value_size, 8);
11220 
11221 		if (flags & (BPF_F_CPU | BPF_F_ALL_CPUS)) {
11222 			if ((flags & BPF_F_CPU) && (flags & BPF_F_ALL_CPUS)) {
11223 				pr_warn("map '%s': BPF_F_CPU and BPF_F_ALL_CPUS are mutually exclusive\n",
11224 					map->name);
11225 				return -EINVAL;
11226 			}
11227 			if (map->def.value_size != value_sz) {
11228 				pr_warn("map '%s': unexpected value size %zu provided for either BPF_F_CPU or BPF_F_ALL_CPUS, expected %u\n",
11229 					map->name, value_sz, map->def.value_size);
11230 				return -EINVAL;
11231 			}
11232 			break;
11233 		}
11234 
11235 		if (value_sz != num_cpu * elem_sz) {
11236 			pr_warn("map '%s': unexpected value size %zu provided for per-CPU map, expected %d * %zu = %zd\n",
11237 				map->name, value_sz, num_cpu, elem_sz, num_cpu * elem_sz);
11238 			return -EINVAL;
11239 		}
11240 		break;
11241 	}
11242 	default:
11243 		if (map->def.value_size != value_sz) {
11244 			pr_warn("map '%s': unexpected value size %zu provided, expected %u\n",
11245 				map->name, value_sz, map->def.value_size);
11246 			return -EINVAL;
11247 		}
11248 		break;
11249 	}
11250 	return 0;
11251 }
11252 
11253 int bpf_map__lookup_elem(const struct bpf_map *map,
11254 			 const void *key, size_t key_sz,
11255 			 void *value, size_t value_sz, __u64 flags)
11256 {
11257 	int err;
11258 
11259 	err = validate_map_op(map, key_sz, value_sz, true, flags);
11260 	if (err)
11261 		return libbpf_err(err);
11262 
11263 	return bpf_map_lookup_elem_flags(map->fd, key, value, flags);
11264 }
11265 
11266 int bpf_map__update_elem(const struct bpf_map *map,
11267 			 const void *key, size_t key_sz,
11268 			 const void *value, size_t value_sz, __u64 flags)
11269 {
11270 	int err;
11271 
11272 	err = validate_map_op(map, key_sz, value_sz, true, flags);
11273 	if (err)
11274 		return libbpf_err(err);
11275 
11276 	return bpf_map_update_elem(map->fd, key, value, flags);
11277 }
11278 
11279 int bpf_map__delete_elem(const struct bpf_map *map,
11280 			 const void *key, size_t key_sz, __u64 flags)
11281 {
11282 	int err;
11283 
11284 	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */, flags);
11285 	if (err)
11286 		return libbpf_err(err);
11287 
11288 	return bpf_map_delete_elem_flags(map->fd, key, flags);
11289 }
11290 
11291 int bpf_map__lookup_and_delete_elem(const struct bpf_map *map,
11292 				    const void *key, size_t key_sz,
11293 				    void *value, size_t value_sz, __u64 flags)
11294 {
11295 	int err;
11296 
11297 	err = validate_map_op(map, key_sz, value_sz, true, flags);
11298 	if (err)
11299 		return libbpf_err(err);
11300 
11301 	return bpf_map_lookup_and_delete_elem_flags(map->fd, key, value, flags);
11302 }
11303 
11304 int bpf_map__get_next_key(const struct bpf_map *map,
11305 			  const void *cur_key, void *next_key, size_t key_sz)
11306 {
11307 	int err;
11308 
11309 	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */, 0);
11310 	if (err)
11311 		return libbpf_err(err);
11312 
11313 	return bpf_map_get_next_key(map->fd, cur_key, next_key);
11314 }
11315 
11316 long libbpf_get_error(const void *ptr)
11317 {
11318 	if (!IS_ERR_OR_NULL(ptr))
11319 		return 0;
11320 
11321 	if (IS_ERR(ptr))
11322 		errno = -PTR_ERR(ptr);
11323 
11324 	/* If ptr == NULL, then errno should be already set by the failing
11325 	 * API, because libbpf never returns NULL on success and it now always
11326 	 * sets errno on error. So no extra errno handling for ptr == NULL
11327 	 * case.
11328 	 */
11329 	return -errno;
11330 }
11331 
11332 /* Replace link's underlying BPF program with the new one */
11333 int bpf_link__update_program(struct bpf_link *link, struct bpf_program *prog)
11334 {
11335 	int ret;
11336 	int prog_fd = bpf_program__fd(prog);
11337 
11338 	if (prog_fd < 0) {
11339 		pr_warn("prog '%s': can't use BPF program without FD (was it loaded?)\n",
11340 			prog->name);
11341 		return libbpf_err(-EINVAL);
11342 	}
11343 
11344 	ret = bpf_link_update(bpf_link__fd(link), prog_fd, NULL);
11345 	return libbpf_err_errno(ret);
11346 }
11347 
11348 /* Release "ownership" of underlying BPF resource (typically, BPF program
11349  * attached to some BPF hook, e.g., tracepoint, kprobe, etc). Disconnected
11350  * link, when destructed through bpf_link__destroy() call won't attempt to
11351  * detach/unregisted that BPF resource. This is useful in situations where,
11352  * say, attached BPF program has to outlive userspace program that attached it
11353  * in the system. Depending on type of BPF program, though, there might be
11354  * additional steps (like pinning BPF program in BPF FS) necessary to ensure
11355  * exit of userspace program doesn't trigger automatic detachment and clean up
11356  * inside the kernel.
11357  */
11358 void bpf_link__disconnect(struct bpf_link *link)
11359 {
11360 	link->disconnected = true;
11361 }
11362 
11363 int bpf_link__destroy(struct bpf_link *link)
11364 {
11365 	int err = 0;
11366 
11367 	if (IS_ERR_OR_NULL(link))
11368 		return 0;
11369 
11370 	if (!link->disconnected && link->detach)
11371 		err = link->detach(link);
11372 	if (link->pin_path)
11373 		free(link->pin_path);
11374 	if (link->dealloc)
11375 		link->dealloc(link);
11376 	else
11377 		free(link);
11378 
11379 	return libbpf_err(err);
11380 }
11381 
11382 int bpf_link__fd(const struct bpf_link *link)
11383 {
11384 	return link->fd;
11385 }
11386 
11387 const char *bpf_link__pin_path(const struct bpf_link *link)
11388 {
11389 	return link->pin_path;
11390 }
11391 
11392 static int bpf_link__detach_fd(struct bpf_link *link)
11393 {
11394 	return libbpf_err_errno(close(link->fd));
11395 }
11396 
11397 struct bpf_link *bpf_link__open(const char *path)
11398 {
11399 	struct bpf_link *link;
11400 	int fd;
11401 
11402 	fd = bpf_obj_get(path);
11403 	if (fd < 0) {
11404 		fd = -errno;
11405 		pr_warn("failed to open link at %s: %d\n", path, fd);
11406 		return libbpf_err_ptr(fd);
11407 	}
11408 
11409 	link = calloc(1, sizeof(*link));
11410 	if (!link) {
11411 		close(fd);
11412 		return libbpf_err_ptr(-ENOMEM);
11413 	}
11414 	link->detach = &bpf_link__detach_fd;
11415 	link->fd = fd;
11416 
11417 	link->pin_path = strdup(path);
11418 	if (!link->pin_path) {
11419 		bpf_link__destroy(link);
11420 		return libbpf_err_ptr(-ENOMEM);
11421 	}
11422 
11423 	return link;
11424 }
11425 
11426 int bpf_link__detach(struct bpf_link *link)
11427 {
11428 	return bpf_link_detach(link->fd) ? -errno : 0;
11429 }
11430 
11431 int bpf_link__pin(struct bpf_link *link, const char *path)
11432 {
11433 	int err;
11434 
11435 	if (link->pin_path)
11436 		return libbpf_err(-EBUSY);
11437 	err = make_parent_dir(path);
11438 	if (err)
11439 		return libbpf_err(err);
11440 	err = check_path(path);
11441 	if (err)
11442 		return libbpf_err(err);
11443 
11444 	link->pin_path = strdup(path);
11445 	if (!link->pin_path)
11446 		return libbpf_err(-ENOMEM);
11447 
11448 	if (bpf_obj_pin(link->fd, link->pin_path)) {
11449 		err = -errno;
11450 		zfree(&link->pin_path);
11451 		return libbpf_err(err);
11452 	}
11453 
11454 	pr_debug("link fd=%d: pinned at %s\n", link->fd, link->pin_path);
11455 	return 0;
11456 }
11457 
11458 int bpf_link__unpin(struct bpf_link *link)
11459 {
11460 	int err;
11461 
11462 	if (!link->pin_path)
11463 		return libbpf_err(-EINVAL);
11464 
11465 	err = unlink(link->pin_path);
11466 	if (err != 0)
11467 		return -errno;
11468 
11469 	pr_debug("link fd=%d: unpinned from %s\n", link->fd, link->pin_path);
11470 	zfree(&link->pin_path);
11471 	return 0;
11472 }
11473 
11474 struct bpf_link_perf {
11475 	struct bpf_link link;
11476 	int perf_event_fd;
11477 	/* legacy kprobe support: keep track of probe identifier and type */
11478 	char *legacy_probe_name;
11479 	bool legacy_is_kprobe;
11480 	bool legacy_is_retprobe;
11481 };
11482 
11483 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe);
11484 static int remove_uprobe_event_legacy(const char *probe_name, bool retprobe);
11485 
11486 static int bpf_link_perf_detach(struct bpf_link *link)
11487 {
11488 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
11489 	int err = 0;
11490 
11491 	if (ioctl(perf_link->perf_event_fd, PERF_EVENT_IOC_DISABLE, 0) < 0)
11492 		err = -errno;
11493 
11494 	if (perf_link->perf_event_fd != link->fd)
11495 		close(perf_link->perf_event_fd);
11496 	close(link->fd);
11497 
11498 	/* legacy uprobe/kprobe needs to be removed after perf event fd closure */
11499 	if (perf_link->legacy_probe_name) {
11500 		if (perf_link->legacy_is_kprobe) {
11501 			err = remove_kprobe_event_legacy(perf_link->legacy_probe_name,
11502 							 perf_link->legacy_is_retprobe);
11503 		} else {
11504 			err = remove_uprobe_event_legacy(perf_link->legacy_probe_name,
11505 							 perf_link->legacy_is_retprobe);
11506 		}
11507 	}
11508 
11509 	return err;
11510 }
11511 
11512 static void bpf_link_perf_dealloc(struct bpf_link *link)
11513 {
11514 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
11515 
11516 	free(perf_link->legacy_probe_name);
11517 	free(perf_link);
11518 }
11519 
11520 struct bpf_link *bpf_program__attach_perf_event_opts(const struct bpf_program *prog, int pfd,
11521 						     const struct bpf_perf_event_opts *opts)
11522 {
11523 	struct bpf_link_perf *link;
11524 	int prog_fd, link_fd = -1, err;
11525 	bool force_ioctl_attach;
11526 
11527 	if (!OPTS_VALID(opts, bpf_perf_event_opts))
11528 		return libbpf_err_ptr(-EINVAL);
11529 
11530 	if (pfd < 0) {
11531 		pr_warn("prog '%s': invalid perf event FD %d\n",
11532 			prog->name, pfd);
11533 		return libbpf_err_ptr(-EINVAL);
11534 	}
11535 	prog_fd = bpf_program__fd(prog);
11536 	if (prog_fd < 0) {
11537 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
11538 			prog->name);
11539 		return libbpf_err_ptr(-EINVAL);
11540 	}
11541 
11542 	link = calloc(1, sizeof(*link));
11543 	if (!link)
11544 		return libbpf_err_ptr(-ENOMEM);
11545 	link->link.detach = &bpf_link_perf_detach;
11546 	link->link.dealloc = &bpf_link_perf_dealloc;
11547 	link->perf_event_fd = pfd;
11548 
11549 	force_ioctl_attach = OPTS_GET(opts, force_ioctl_attach, false);
11550 	if (kernel_supports(prog->obj, FEAT_PERF_LINK) && !force_ioctl_attach) {
11551 		DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_opts,
11552 			.perf_event.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0));
11553 
11554 		link_fd = bpf_link_create(prog_fd, pfd, BPF_PERF_EVENT, &link_opts);
11555 		if (link_fd < 0) {
11556 			err = -errno;
11557 			pr_warn("prog '%s': failed to create BPF link for perf_event FD %d: %s\n",
11558 				prog->name, pfd, errstr(err));
11559 			goto err_out;
11560 		}
11561 		link->link.fd = link_fd;
11562 	} else {
11563 		if (OPTS_GET(opts, bpf_cookie, 0)) {
11564 			pr_warn("prog '%s': user context value is not supported\n", prog->name);
11565 			err = -EOPNOTSUPP;
11566 			goto err_out;
11567 		}
11568 
11569 		if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
11570 			err = -errno;
11571 			pr_warn("prog '%s': failed to attach to perf_event FD %d: %s\n",
11572 				prog->name, pfd, errstr(err));
11573 			if (err == -EPROTO)
11574 				pr_warn("prog '%s': try add PERF_SAMPLE_CALLCHAIN to or remove exclude_callchain_[kernel|user] from pfd %d\n",
11575 					prog->name, pfd);
11576 			goto err_out;
11577 		}
11578 		link->link.fd = pfd;
11579 	}
11580 
11581 	if (!OPTS_GET(opts, dont_enable, false)) {
11582 		if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
11583 			err = -errno;
11584 			pr_warn("prog '%s': failed to enable perf_event FD %d: %s\n",
11585 				prog->name, pfd, errstr(err));
11586 			goto err_out;
11587 		}
11588 	}
11589 
11590 	return &link->link;
11591 err_out:
11592 	if (link_fd >= 0)
11593 		close(link_fd);
11594 	free(link);
11595 	return libbpf_err_ptr(err);
11596 }
11597 
11598 struct bpf_link *bpf_program__attach_perf_event(const struct bpf_program *prog, int pfd)
11599 {
11600 	return bpf_program__attach_perf_event_opts(prog, pfd, NULL);
11601 }
11602 
11603 /*
11604  * this function is expected to parse integer in the range of [0, 2^31-1] from
11605  * given file using scanf format string fmt. If actual parsed value is
11606  * negative, the result might be indistinguishable from error
11607  */
11608 static int parse_uint_from_file(const char *file, const char *fmt)
11609 {
11610 	int err, ret;
11611 	FILE *f;
11612 
11613 	f = fopen(file, "re");
11614 	if (!f) {
11615 		err = -errno;
11616 		pr_debug("failed to open '%s': %s\n", file, errstr(err));
11617 		return err;
11618 	}
11619 	err = fscanf(f, fmt, &ret);
11620 	if (err != 1) {
11621 		err = err == EOF ? -EIO : -errno;
11622 		pr_debug("failed to parse '%s': %s\n", file, errstr(err));
11623 		fclose(f);
11624 		return err;
11625 	}
11626 	fclose(f);
11627 	return ret;
11628 }
11629 
11630 static int determine_kprobe_perf_type(void)
11631 {
11632 	const char *file = "/sys/bus/event_source/devices/kprobe/type";
11633 
11634 	return parse_uint_from_file(file, "%d\n");
11635 }
11636 
11637 static int determine_uprobe_perf_type(void)
11638 {
11639 	const char *file = "/sys/bus/event_source/devices/uprobe/type";
11640 
11641 	return parse_uint_from_file(file, "%d\n");
11642 }
11643 
11644 static int determine_kprobe_retprobe_bit(void)
11645 {
11646 	const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
11647 
11648 	return parse_uint_from_file(file, "config:%d\n");
11649 }
11650 
11651 static int determine_uprobe_retprobe_bit(void)
11652 {
11653 	const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
11654 
11655 	return parse_uint_from_file(file, "config:%d\n");
11656 }
11657 
11658 #define PERF_UPROBE_REF_CTR_OFFSET_BITS 32
11659 #define PERF_UPROBE_REF_CTR_OFFSET_SHIFT 32
11660 
11661 static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
11662 				 uint64_t offset, int pid, size_t ref_ctr_off)
11663 {
11664 	const size_t attr_sz = sizeof(struct perf_event_attr);
11665 	struct perf_event_attr attr;
11666 	int type, pfd;
11667 
11668 	if ((__u64)ref_ctr_off >= (1ULL << PERF_UPROBE_REF_CTR_OFFSET_BITS))
11669 		return -EINVAL;
11670 
11671 	memset(&attr, 0, attr_sz);
11672 
11673 	type = uprobe ? determine_uprobe_perf_type()
11674 		      : determine_kprobe_perf_type();
11675 	if (type < 0) {
11676 		pr_warn("failed to determine %s perf type: %s\n",
11677 			uprobe ? "uprobe" : "kprobe",
11678 			errstr(type));
11679 		return type;
11680 	}
11681 	if (retprobe) {
11682 		int bit = uprobe ? determine_uprobe_retprobe_bit()
11683 				 : determine_kprobe_retprobe_bit();
11684 
11685 		if (bit < 0) {
11686 			pr_warn("failed to determine %s retprobe bit: %s\n",
11687 				uprobe ? "uprobe" : "kprobe",
11688 				errstr(bit));
11689 			return bit;
11690 		}
11691 		attr.config |= 1 << bit;
11692 	}
11693 	attr.size = attr_sz;
11694 	attr.type = type;
11695 	attr.config |= (__u64)ref_ctr_off << PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
11696 	attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
11697 	attr.config2 = offset;		 /* kprobe_addr or probe_offset */
11698 
11699 	/* pid filter is meaningful only for uprobes */
11700 	pfd = syscall(__NR_perf_event_open, &attr,
11701 		      pid < 0 ? -1 : pid /* pid */,
11702 		      pid == -1 ? 0 : -1 /* cpu */,
11703 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
11704 	return pfd >= 0 ? pfd : -errno;
11705 }
11706 
11707 static int append_to_file(const char *file, const char *fmt, ...)
11708 {
11709 	int fd, n, err = 0;
11710 	va_list ap;
11711 	char buf[1024];
11712 
11713 	va_start(ap, fmt);
11714 	n = vsnprintf(buf, sizeof(buf), fmt, ap);
11715 	va_end(ap);
11716 
11717 	if (n < 0 || n >= sizeof(buf))
11718 		return -EINVAL;
11719 
11720 	fd = open(file, O_WRONLY | O_APPEND | O_CLOEXEC, 0);
11721 	if (fd < 0)
11722 		return -errno;
11723 
11724 	if (write(fd, buf, n) < 0)
11725 		err = -errno;
11726 
11727 	close(fd);
11728 	return err;
11729 }
11730 
11731 #define DEBUGFS "/sys/kernel/debug/tracing"
11732 #define TRACEFS "/sys/kernel/tracing"
11733 
11734 static bool use_debugfs(void)
11735 {
11736 	static int has_debugfs = -1;
11737 
11738 	if (has_debugfs < 0)
11739 		has_debugfs = faccessat(AT_FDCWD, DEBUGFS, F_OK, AT_EACCESS) == 0;
11740 
11741 	return has_debugfs == 1;
11742 }
11743 
11744 static const char *tracefs_path(void)
11745 {
11746 	return use_debugfs() ? DEBUGFS : TRACEFS;
11747 }
11748 
11749 static const char *tracefs_kprobe_events(void)
11750 {
11751 	return use_debugfs() ? DEBUGFS"/kprobe_events" : TRACEFS"/kprobe_events";
11752 }
11753 
11754 static const char *tracefs_uprobe_events(void)
11755 {
11756 	return use_debugfs() ? DEBUGFS"/uprobe_events" : TRACEFS"/uprobe_events";
11757 }
11758 
11759 static const char *tracefs_available_filter_functions(void)
11760 {
11761 	return use_debugfs() ? DEBUGFS"/available_filter_functions"
11762 			     : TRACEFS"/available_filter_functions";
11763 }
11764 
11765 static const char *tracefs_available_filter_functions_addrs(void)
11766 {
11767 	return use_debugfs() ? DEBUGFS"/available_filter_functions_addrs"
11768 			     : TRACEFS"/available_filter_functions_addrs";
11769 }
11770 
11771 static void gen_probe_legacy_event_name(char *buf, size_t buf_sz,
11772 					const char *name, size_t offset)
11773 {
11774 	static int index = 0;
11775 	int i;
11776 
11777 	snprintf(buf, buf_sz, "libbpf_%u_%d_%s_0x%zx", getpid(),
11778 		 __sync_fetch_and_add(&index, 1), name, offset);
11779 
11780 	/* sanitize name in the probe name */
11781 	for (i = 0; buf[i]; i++) {
11782 		if (!isalnum(buf[i]))
11783 			buf[i] = '_';
11784 	}
11785 }
11786 
11787 static int add_kprobe_event_legacy(const char *probe_name, bool retprobe,
11788 				   const char *kfunc_name, size_t offset)
11789 {
11790 	return append_to_file(tracefs_kprobe_events(), "%c:%s/%s %s+0x%zx",
11791 			      retprobe ? 'r' : 'p',
11792 			      retprobe ? "kretprobes" : "kprobes",
11793 			      probe_name, kfunc_name, offset);
11794 }
11795 
11796 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe)
11797 {
11798 	return append_to_file(tracefs_kprobe_events(), "-:%s/%s",
11799 			      retprobe ? "kretprobes" : "kprobes", probe_name);
11800 }
11801 
11802 static int determine_kprobe_perf_type_legacy(const char *probe_name, bool retprobe)
11803 {
11804 	char file[256];
11805 
11806 	snprintf(file, sizeof(file), "%s/events/%s/%s/id",
11807 		 tracefs_path(), retprobe ? "kretprobes" : "kprobes", probe_name);
11808 
11809 	return parse_uint_from_file(file, "%d\n");
11810 }
11811 
11812 static int perf_event_kprobe_open_legacy(const char *probe_name, bool retprobe,
11813 					 const char *kfunc_name, size_t offset, int pid)
11814 {
11815 	const size_t attr_sz = sizeof(struct perf_event_attr);
11816 	struct perf_event_attr attr;
11817 	int type, pfd, err;
11818 
11819 	err = add_kprobe_event_legacy(probe_name, retprobe, kfunc_name, offset);
11820 	if (err < 0) {
11821 		pr_warn("failed to add legacy kprobe event for '%s+0x%zx': %s\n",
11822 			kfunc_name, offset,
11823 			errstr(err));
11824 		return err;
11825 	}
11826 	type = determine_kprobe_perf_type_legacy(probe_name, retprobe);
11827 	if (type < 0) {
11828 		err = type;
11829 		pr_warn("failed to determine legacy kprobe event id for '%s+0x%zx': %s\n",
11830 			kfunc_name, offset,
11831 			errstr(err));
11832 		goto err_clean_legacy;
11833 	}
11834 
11835 	memset(&attr, 0, attr_sz);
11836 	attr.size = attr_sz;
11837 	attr.config = type;
11838 	attr.type = PERF_TYPE_TRACEPOINT;
11839 
11840 	pfd = syscall(__NR_perf_event_open, &attr,
11841 		      pid < 0 ? -1 : pid, /* pid */
11842 		      pid == -1 ? 0 : -1, /* cpu */
11843 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
11844 	if (pfd < 0) {
11845 		err = -errno;
11846 		pr_warn("legacy kprobe perf_event_open() failed: %s\n",
11847 			errstr(err));
11848 		goto err_clean_legacy;
11849 	}
11850 	return pfd;
11851 
11852 err_clean_legacy:
11853 	/* Clear the newly added legacy kprobe_event */
11854 	remove_kprobe_event_legacy(probe_name, retprobe);
11855 	return err;
11856 }
11857 
11858 static const char *arch_specific_syscall_pfx(void)
11859 {
11860 #if defined(__x86_64__)
11861 	return "x64";
11862 #elif defined(__i386__)
11863 	return "ia32";
11864 #elif defined(__s390x__)
11865 	return "s390x";
11866 #elif defined(__arm__)
11867 	return "arm";
11868 #elif defined(__aarch64__)
11869 	return "arm64";
11870 #elif defined(__mips__)
11871 	return "mips";
11872 #elif defined(__riscv)
11873 	return "riscv";
11874 #elif defined(__powerpc__)
11875 	return "powerpc";
11876 #elif defined(__powerpc64__)
11877 	return "powerpc64";
11878 #else
11879 	return NULL;
11880 #endif
11881 }
11882 
11883 int probe_kern_syscall_wrapper(int token_fd)
11884 {
11885 	char syscall_name[64];
11886 	const char *ksys_pfx;
11887 
11888 	ksys_pfx = arch_specific_syscall_pfx();
11889 	if (!ksys_pfx)
11890 		return 0;
11891 
11892 	snprintf(syscall_name, sizeof(syscall_name), "__%s_sys_bpf", ksys_pfx);
11893 
11894 	if (determine_kprobe_perf_type() >= 0) {
11895 		int pfd;
11896 
11897 		pfd = perf_event_open_probe(false, false, syscall_name, 0, getpid(), 0);
11898 		if (pfd >= 0)
11899 			close(pfd);
11900 
11901 		return pfd >= 0 ? 1 : 0;
11902 	} else { /* legacy mode */
11903 		char probe_name[MAX_EVENT_NAME_LEN];
11904 
11905 		gen_probe_legacy_event_name(probe_name, sizeof(probe_name), syscall_name, 0);
11906 		if (add_kprobe_event_legacy(probe_name, false, syscall_name, 0) < 0)
11907 			return 0;
11908 
11909 		(void)remove_kprobe_event_legacy(probe_name, false);
11910 		return 1;
11911 	}
11912 }
11913 
11914 struct bpf_link *
11915 bpf_program__attach_kprobe_opts(const struct bpf_program *prog,
11916 				const char *func_name,
11917 				const struct bpf_kprobe_opts *opts)
11918 {
11919 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
11920 	enum probe_attach_mode attach_mode;
11921 	char *legacy_probe = NULL;
11922 	struct bpf_link *link;
11923 	size_t offset;
11924 	bool retprobe, legacy;
11925 	int pfd, err;
11926 
11927 	if (!OPTS_VALID(opts, bpf_kprobe_opts))
11928 		return libbpf_err_ptr(-EINVAL);
11929 
11930 	attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
11931 	retprobe = OPTS_GET(opts, retprobe, false);
11932 	offset = OPTS_GET(opts, offset, 0);
11933 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11934 
11935 	legacy = determine_kprobe_perf_type() < 0;
11936 	switch (attach_mode) {
11937 	case PROBE_ATTACH_MODE_LEGACY:
11938 		legacy = true;
11939 		pe_opts.force_ioctl_attach = true;
11940 		break;
11941 	case PROBE_ATTACH_MODE_PERF:
11942 		if (legacy)
11943 			return libbpf_err_ptr(-ENOTSUP);
11944 		pe_opts.force_ioctl_attach = true;
11945 		break;
11946 	case PROBE_ATTACH_MODE_LINK:
11947 		if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
11948 			return libbpf_err_ptr(-ENOTSUP);
11949 		break;
11950 	case PROBE_ATTACH_MODE_DEFAULT:
11951 		break;
11952 	default:
11953 		return libbpf_err_ptr(-EINVAL);
11954 	}
11955 	if (!func_name && legacy)
11956 		return libbpf_err_ptr(-EOPNOTSUPP);
11957 
11958 	if (!legacy) {
11959 		pfd = perf_event_open_probe(false /* uprobe */, retprobe,
11960 					    func_name, offset,
11961 					    -1 /* pid */, 0 /* ref_ctr_off */);
11962 	} else {
11963 		char probe_name[MAX_EVENT_NAME_LEN];
11964 
11965 		gen_probe_legacy_event_name(probe_name, sizeof(probe_name),
11966 					    func_name, offset);
11967 
11968 		legacy_probe = strdup(probe_name);
11969 		if (!legacy_probe)
11970 			return libbpf_err_ptr(-ENOMEM);
11971 
11972 		pfd = perf_event_kprobe_open_legacy(legacy_probe, retprobe, func_name,
11973 						    offset, -1 /* pid */);
11974 	}
11975 	if (pfd < 0) {
11976 		err = pfd;
11977 		pr_warn("prog '%s': failed to create %s '%s%s0x%zx' perf event: %s\n",
11978 			prog->name, retprobe ? "kretprobe" : "kprobe",
11979 			func_name ?: "", func_name ? "+" : "",
11980 			offset, errstr(err));
11981 		goto err_out;
11982 	}
11983 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
11984 	err = libbpf_get_error(link);
11985 	if (err) {
11986 		close(pfd);
11987 		pr_warn("prog '%s': failed to attach to %s '%s%s0x%zx': %s\n",
11988 			prog->name, retprobe ? "kretprobe" : "kprobe",
11989 			func_name ?: "", func_name ? "+" : "",
11990 			offset, errstr(err));
11991 		goto err_clean_legacy;
11992 	}
11993 	if (legacy) {
11994 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
11995 
11996 		perf_link->legacy_probe_name = legacy_probe;
11997 		perf_link->legacy_is_kprobe = true;
11998 		perf_link->legacy_is_retprobe = retprobe;
11999 	}
12000 
12001 	return link;
12002 
12003 err_clean_legacy:
12004 	if (legacy)
12005 		remove_kprobe_event_legacy(legacy_probe, retprobe);
12006 err_out:
12007 	free(legacy_probe);
12008 	return libbpf_err_ptr(err);
12009 }
12010 
12011 struct bpf_link *bpf_program__attach_kprobe(const struct bpf_program *prog,
12012 					    bool retprobe,
12013 					    const char *func_name)
12014 {
12015 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts,
12016 		.retprobe = retprobe,
12017 	);
12018 
12019 	return bpf_program__attach_kprobe_opts(prog, func_name, &opts);
12020 }
12021 
12022 struct bpf_link *bpf_program__attach_ksyscall(const struct bpf_program *prog,
12023 					      const char *syscall_name,
12024 					      const struct bpf_ksyscall_opts *opts)
12025 {
12026 	LIBBPF_OPTS(bpf_kprobe_opts, kprobe_opts);
12027 	char func_name[128];
12028 
12029 	if (!OPTS_VALID(opts, bpf_ksyscall_opts))
12030 		return libbpf_err_ptr(-EINVAL);
12031 
12032 	if (kernel_supports(prog->obj, FEAT_SYSCALL_WRAPPER)) {
12033 		/* arch_specific_syscall_pfx() should never return NULL here
12034 		 * because it is guarded by kernel_supports(). However, since
12035 		 * compiler does not know that we have an explicit conditional
12036 		 * as well.
12037 		 */
12038 		snprintf(func_name, sizeof(func_name), "__%s_sys_%s",
12039 			 arch_specific_syscall_pfx() ? : "", syscall_name);
12040 	} else {
12041 		snprintf(func_name, sizeof(func_name), "__se_sys_%s", syscall_name);
12042 	}
12043 
12044 	kprobe_opts.retprobe = OPTS_GET(opts, retprobe, false);
12045 	kprobe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
12046 
12047 	return bpf_program__attach_kprobe_opts(prog, func_name, &kprobe_opts);
12048 }
12049 
12050 /* Adapted from perf/util/string.c */
12051 bool glob_match(const char *str, const char *pat)
12052 {
12053 	while (*str && *pat && *pat != '*') {
12054 		if (*pat == '?') {      /* Matches any single character */
12055 			str++;
12056 			pat++;
12057 			continue;
12058 		}
12059 		if (*str != *pat)
12060 			return false;
12061 		str++;
12062 		pat++;
12063 	}
12064 	/* Check wild card */
12065 	if (*pat == '*') {
12066 		while (*pat == '*')
12067 			pat++;
12068 		if (!*pat) /* Tail wild card matches all */
12069 			return true;
12070 		while (*str)
12071 			if (glob_match(str++, pat))
12072 				return true;
12073 	}
12074 	return !*str && !*pat;
12075 }
12076 
12077 struct kprobe_multi_resolve {
12078 	const char *pattern;
12079 	unsigned long *addrs;
12080 	size_t cap;
12081 	size_t cnt;
12082 };
12083 
12084 struct avail_kallsyms_data {
12085 	char **syms;
12086 	size_t cnt;
12087 	struct kprobe_multi_resolve *res;
12088 };
12089 
12090 static int avail_func_cmp(const void *a, const void *b)
12091 {
12092 	return strcmp(*(const char **)a, *(const char **)b);
12093 }
12094 
12095 static int avail_kallsyms_cb(unsigned long long sym_addr, char sym_type,
12096 			     const char *sym_name, void *ctx)
12097 {
12098 	struct avail_kallsyms_data *data = ctx;
12099 	struct kprobe_multi_resolve *res = data->res;
12100 	int err;
12101 
12102 	if (!glob_match(sym_name, res->pattern))
12103 		return 0;
12104 
12105 	if (!bsearch(&sym_name, data->syms, data->cnt, sizeof(*data->syms), avail_func_cmp)) {
12106 		/* Some versions of kernel strip out .llvm.<hash> suffix from
12107 		 * function names reported in available_filter_functions, but
12108 		 * don't do so for kallsyms. While this is clearly a kernel
12109 		 * bug (fixed by [0]) we try to accommodate that in libbpf to
12110 		 * make multi-kprobe usability a bit better: if no match is
12111 		 * found, we will strip .llvm. suffix and try one more time.
12112 		 *
12113 		 *   [0] fb6a421fb615 ("kallsyms: Match symbols exactly with CONFIG_LTO_CLANG")
12114 		 */
12115 		char sym_trim[256], *psym_trim = sym_trim;
12116 		const char *sym_sfx;
12117 
12118 		if (!(sym_sfx = strstr(sym_name, ".llvm.")))
12119 			return 0;
12120 
12121 		/* psym_trim vs sym_trim dance is done to avoid pointer vs array
12122 		 * coercion differences and get proper `const char **` pointer
12123 		 * which avail_func_cmp() expects
12124 		 */
12125 		snprintf(sym_trim, sizeof(sym_trim), "%.*s", (int)(sym_sfx - sym_name), sym_name);
12126 		if (!bsearch(&psym_trim, data->syms, data->cnt, sizeof(*data->syms), avail_func_cmp))
12127 			return 0;
12128 	}
12129 
12130 	err = libbpf_ensure_mem((void **)&res->addrs, &res->cap, sizeof(*res->addrs), res->cnt + 1);
12131 	if (err)
12132 		return err;
12133 
12134 	res->addrs[res->cnt++] = (unsigned long)sym_addr;
12135 	return 0;
12136 }
12137 
12138 static int libbpf_available_kallsyms_parse(struct kprobe_multi_resolve *res)
12139 {
12140 	const char *available_functions_file = tracefs_available_filter_functions();
12141 	struct avail_kallsyms_data data;
12142 	char sym_name[500];
12143 	FILE *f;
12144 	int err = 0, ret, i;
12145 	char **syms = NULL;
12146 	size_t cap = 0, cnt = 0;
12147 
12148 	f = fopen(available_functions_file, "re");
12149 	if (!f) {
12150 		err = -errno;
12151 		pr_warn("failed to open %s: %s\n", available_functions_file, errstr(err));
12152 		return err;
12153 	}
12154 
12155 	while (true) {
12156 		char *name;
12157 
12158 		ret = fscanf(f, "%499s%*[^\n]\n", sym_name);
12159 		if (ret == EOF && feof(f))
12160 			break;
12161 
12162 		if (ret != 1) {
12163 			pr_warn("failed to parse available_filter_functions entry: %d\n", ret);
12164 			err = -EINVAL;
12165 			goto cleanup;
12166 		}
12167 
12168 		if (!glob_match(sym_name, res->pattern))
12169 			continue;
12170 
12171 		err = libbpf_ensure_mem((void **)&syms, &cap, sizeof(*syms), cnt + 1);
12172 		if (err)
12173 			goto cleanup;
12174 
12175 		name = strdup(sym_name);
12176 		if (!name) {
12177 			err = -errno;
12178 			goto cleanup;
12179 		}
12180 
12181 		syms[cnt++] = name;
12182 	}
12183 
12184 	/* no entries found, bail out */
12185 	if (cnt == 0) {
12186 		err = -ENOENT;
12187 		goto cleanup;
12188 	}
12189 
12190 	/* sort available functions */
12191 	qsort(syms, cnt, sizeof(*syms), avail_func_cmp);
12192 
12193 	data.syms = syms;
12194 	data.res = res;
12195 	data.cnt = cnt;
12196 	libbpf_kallsyms_parse(avail_kallsyms_cb, &data);
12197 
12198 	if (res->cnt == 0)
12199 		err = -ENOENT;
12200 
12201 cleanup:
12202 	for (i = 0; i < cnt; i++)
12203 		free((char *)syms[i]);
12204 	free(syms);
12205 
12206 	fclose(f);
12207 	return err;
12208 }
12209 
12210 static bool has_available_filter_functions_addrs(void)
12211 {
12212 	return access(tracefs_available_filter_functions_addrs(), R_OK) != -1;
12213 }
12214 
12215 static int libbpf_available_kprobes_parse(struct kprobe_multi_resolve *res)
12216 {
12217 	const char *available_path = tracefs_available_filter_functions_addrs();
12218 	char sym_name[500];
12219 	FILE *f;
12220 	int ret, err = 0;
12221 	unsigned long long sym_addr;
12222 
12223 	f = fopen(available_path, "re");
12224 	if (!f) {
12225 		err = -errno;
12226 		pr_warn("failed to open %s: %s\n", available_path, errstr(err));
12227 		return err;
12228 	}
12229 
12230 	while (true) {
12231 		ret = fscanf(f, "%llx %499s%*[^\n]\n", &sym_addr, sym_name);
12232 		if (ret == EOF && feof(f))
12233 			break;
12234 
12235 		if (ret != 2) {
12236 			pr_warn("failed to parse available_filter_functions_addrs entry: %d\n",
12237 				ret);
12238 			err = -EINVAL;
12239 			goto cleanup;
12240 		}
12241 
12242 		if (!glob_match(sym_name, res->pattern))
12243 			continue;
12244 
12245 		err = libbpf_ensure_mem((void **)&res->addrs, &res->cap,
12246 					sizeof(*res->addrs), res->cnt + 1);
12247 		if (err)
12248 			goto cleanup;
12249 
12250 		res->addrs[res->cnt++] = (unsigned long)sym_addr;
12251 	}
12252 
12253 	if (res->cnt == 0)
12254 		err = -ENOENT;
12255 
12256 cleanup:
12257 	fclose(f);
12258 	return err;
12259 }
12260 
12261 struct bpf_link *
12262 bpf_program__attach_kprobe_multi_opts(const struct bpf_program *prog,
12263 				      const char *pattern,
12264 				      const struct bpf_kprobe_multi_opts *opts)
12265 {
12266 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
12267 	struct kprobe_multi_resolve res = {
12268 		.pattern = pattern,
12269 	};
12270 	enum bpf_attach_type attach_type;
12271 	struct bpf_link *link = NULL;
12272 	const unsigned long *addrs;
12273 	int err, link_fd, prog_fd;
12274 	bool retprobe, session, unique_match;
12275 	const __u64 *cookies;
12276 	const char **syms;
12277 	size_t cnt;
12278 
12279 	if (!OPTS_VALID(opts, bpf_kprobe_multi_opts))
12280 		return libbpf_err_ptr(-EINVAL);
12281 
12282 	prog_fd = bpf_program__fd(prog);
12283 	if (prog_fd < 0) {
12284 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
12285 			prog->name);
12286 		return libbpf_err_ptr(-EINVAL);
12287 	}
12288 
12289 	syms    = OPTS_GET(opts, syms, false);
12290 	addrs   = OPTS_GET(opts, addrs, false);
12291 	cnt     = OPTS_GET(opts, cnt, false);
12292 	cookies = OPTS_GET(opts, cookies, false);
12293 	unique_match = OPTS_GET(opts, unique_match, false);
12294 
12295 	if (!pattern && !addrs && !syms)
12296 		return libbpf_err_ptr(-EINVAL);
12297 	if (pattern && (addrs || syms || cookies || cnt))
12298 		return libbpf_err_ptr(-EINVAL);
12299 	if (!pattern && !cnt)
12300 		return libbpf_err_ptr(-EINVAL);
12301 	if (!pattern && unique_match)
12302 		return libbpf_err_ptr(-EINVAL);
12303 	if (addrs && syms)
12304 		return libbpf_err_ptr(-EINVAL);
12305 
12306 	/*
12307 	 * Exact function name (no wildcards) without unique_match:
12308 	 * bypass kallsyms parsing and pass the symbol directly to the
12309 	 * kernel via syms[] array.  When unique_match is set, fall
12310 	 * through to the slow path which detects duplicate symbols.
12311 	 */
12312 	if (pattern && !strpbrk(pattern, "*?") && !unique_match) {
12313 		syms = &pattern;
12314 		cnt = 1;
12315 	} else if (pattern) {
12316 		if (has_available_filter_functions_addrs())
12317 			err = libbpf_available_kprobes_parse(&res);
12318 		else
12319 			err = libbpf_available_kallsyms_parse(&res);
12320 		if (err)
12321 			goto error;
12322 
12323 		if (unique_match && res.cnt != 1) {
12324 			pr_warn("prog '%s': failed to find a unique match for '%s' (%zu matches)\n",
12325 				prog->name, pattern, res.cnt);
12326 			err = -EINVAL;
12327 			goto error;
12328 		}
12329 
12330 		addrs = res.addrs;
12331 		cnt = res.cnt;
12332 	}
12333 
12334 	retprobe = OPTS_GET(opts, retprobe, false);
12335 	session  = OPTS_GET(opts, session, false);
12336 
12337 	if (retprobe && session)
12338 		return libbpf_err_ptr(-EINVAL);
12339 
12340 	attach_type = session ? BPF_TRACE_KPROBE_SESSION : BPF_TRACE_KPROBE_MULTI;
12341 
12342 	lopts.kprobe_multi.syms = syms;
12343 	lopts.kprobe_multi.addrs = addrs;
12344 	lopts.kprobe_multi.cookies = cookies;
12345 	lopts.kprobe_multi.cnt = cnt;
12346 	lopts.kprobe_multi.flags = retprobe ? BPF_F_KPROBE_MULTI_RETURN : 0;
12347 
12348 	link = calloc(1, sizeof(*link));
12349 	if (!link) {
12350 		err = -ENOMEM;
12351 		goto error;
12352 	}
12353 	link->detach = &bpf_link__detach_fd;
12354 
12355 	link_fd = bpf_link_create(prog_fd, 0, attach_type, &lopts);
12356 	if (link_fd < 0) {
12357 		err = -errno;
12358 		/*
12359 		 * Normalize error code: when exact name bypasses kallsyms
12360 		 * parsing, kernel returns ESRCH from ftrace_lookup_symbols().
12361 		 * Convert to ENOENT for API consistency with the pattern
12362 		 * matching path which returns ENOENT from userspace.
12363 		 */
12364 		if (err == -ESRCH)
12365 			err = -ENOENT;
12366 		pr_warn("prog '%s': failed to attach: %s\n",
12367 			prog->name, errstr(err));
12368 		goto error;
12369 	}
12370 	link->fd = link_fd;
12371 	free(res.addrs);
12372 	return link;
12373 
12374 error:
12375 	free(link);
12376 	free(res.addrs);
12377 	return libbpf_err_ptr(err);
12378 }
12379 
12380 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12381 {
12382 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts);
12383 	long offset = 0;
12384 	const char *func_name;
12385 	char *func;
12386 	int n;
12387 
12388 	*link = NULL;
12389 
12390 	/* no auto-attach for SEC("kprobe") and SEC("kretprobe") */
12391 	if (strcmp(prog->sec_name, "kprobe") == 0 || strcmp(prog->sec_name, "kretprobe") == 0)
12392 		return 0;
12393 
12394 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe/");
12395 	if (opts.retprobe)
12396 		func_name = prog->sec_name + sizeof("kretprobe/") - 1;
12397 	else
12398 		func_name = prog->sec_name + sizeof("kprobe/") - 1;
12399 
12400 	n = sscanf(func_name, "%m[a-zA-Z0-9_.]+%li", &func, &offset);
12401 	if (n < 1) {
12402 		pr_warn("kprobe name is invalid: %s\n", func_name);
12403 		return -EINVAL;
12404 	}
12405 
12406 	if (offset < 0) {
12407 		free(func);
12408 		pr_warn("kprobe offset must be a non-negative integer: %li\n", offset);
12409 		return -EINVAL;
12410 	}
12411 
12412 	if (opts.retprobe && offset != 0) {
12413 		free(func);
12414 		pr_warn("kretprobes do not support offset specification\n");
12415 		return -EINVAL;
12416 	}
12417 
12418 	opts.offset = offset;
12419 	*link = bpf_program__attach_kprobe_opts(prog, func, &opts);
12420 	free(func);
12421 	return libbpf_get_error(*link);
12422 }
12423 
12424 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12425 {
12426 	LIBBPF_OPTS(bpf_ksyscall_opts, opts);
12427 	const char *syscall_name;
12428 
12429 	*link = NULL;
12430 
12431 	/* no auto-attach for SEC("ksyscall") and SEC("kretsyscall") */
12432 	if (strcmp(prog->sec_name, "ksyscall") == 0 || strcmp(prog->sec_name, "kretsyscall") == 0)
12433 		return 0;
12434 
12435 	opts.retprobe = str_has_pfx(prog->sec_name, "kretsyscall/");
12436 	if (opts.retprobe)
12437 		syscall_name = prog->sec_name + sizeof("kretsyscall/") - 1;
12438 	else
12439 		syscall_name = prog->sec_name + sizeof("ksyscall/") - 1;
12440 
12441 	*link = bpf_program__attach_ksyscall(prog, syscall_name, &opts);
12442 	return *link ? 0 : -errno;
12443 }
12444 
12445 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12446 {
12447 	LIBBPF_OPTS(bpf_kprobe_multi_opts, opts);
12448 	const char *spec;
12449 	char *pattern;
12450 	int n;
12451 
12452 	*link = NULL;
12453 
12454 	/* no auto-attach for SEC("kprobe.multi") and SEC("kretprobe.multi") */
12455 	if (strcmp(prog->sec_name, "kprobe.multi") == 0 ||
12456 	    strcmp(prog->sec_name, "kretprobe.multi") == 0)
12457 		return 0;
12458 
12459 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe.multi/");
12460 	if (opts.retprobe)
12461 		spec = prog->sec_name + sizeof("kretprobe.multi/") - 1;
12462 	else
12463 		spec = prog->sec_name + sizeof("kprobe.multi/") - 1;
12464 
12465 	n = sscanf(spec, "%m[a-zA-Z0-9_.*?]", &pattern);
12466 	if (n < 1) {
12467 		pr_warn("kprobe multi pattern is invalid: %s\n", spec);
12468 		return -EINVAL;
12469 	}
12470 
12471 	*link = bpf_program__attach_kprobe_multi_opts(prog, pattern, &opts);
12472 	free(pattern);
12473 	return libbpf_get_error(*link);
12474 }
12475 
12476 static int attach_kprobe_session(const struct bpf_program *prog, long cookie,
12477 				 struct bpf_link **link)
12478 {
12479 	LIBBPF_OPTS(bpf_kprobe_multi_opts, opts, .session = true);
12480 	const char *spec;
12481 	char *pattern;
12482 	int n;
12483 
12484 	*link = NULL;
12485 
12486 	/* no auto-attach for SEC("kprobe.session") */
12487 	if (strcmp(prog->sec_name, "kprobe.session") == 0)
12488 		return 0;
12489 
12490 	spec = prog->sec_name + sizeof("kprobe.session/") - 1;
12491 	n = sscanf(spec, "%m[a-zA-Z0-9_.*?]", &pattern);
12492 	if (n < 1) {
12493 		pr_warn("kprobe session pattern is invalid: %s\n", spec);
12494 		return -EINVAL;
12495 	}
12496 
12497 	*link = bpf_program__attach_kprobe_multi_opts(prog, pattern, &opts);
12498 	free(pattern);
12499 	return *link ? 0 : -errno;
12500 }
12501 
12502 static int attach_uprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12503 {
12504 	char *probe_type = NULL, *binary_path = NULL, *func_name = NULL;
12505 	LIBBPF_OPTS(bpf_uprobe_multi_opts, opts);
12506 	int n, ret = -EINVAL;
12507 
12508 	*link = NULL;
12509 
12510 	n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[^\n]",
12511 		   &probe_type, &binary_path, &func_name);
12512 	switch (n) {
12513 	case 1:
12514 		/* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
12515 		ret = 0;
12516 		break;
12517 	case 3:
12518 		opts.session = str_has_pfx(probe_type, "uprobe.session");
12519 		opts.retprobe = str_has_pfx(probe_type, "uretprobe.multi");
12520 
12521 		*link = bpf_program__attach_uprobe_multi(prog, -1, binary_path, func_name, &opts);
12522 		ret = libbpf_get_error(*link);
12523 		break;
12524 	default:
12525 		pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
12526 			prog->sec_name);
12527 		break;
12528 	}
12529 	free(probe_type);
12530 	free(binary_path);
12531 	free(func_name);
12532 	return ret;
12533 }
12534 
12535 #define MAX_BPF_FUNC_ARGS 12
12536 
12537 static bool btf_type_is_modifier(const struct btf_type *t)
12538 {
12539 	switch (BTF_INFO_KIND(t->info)) {
12540 	case BTF_KIND_TYPEDEF:
12541 	case BTF_KIND_VOLATILE:
12542 	case BTF_KIND_CONST:
12543 	case BTF_KIND_RESTRICT:
12544 	case BTF_KIND_TYPE_TAG:
12545 		return true;
12546 	default:
12547 		return false;
12548 	}
12549 }
12550 
12551 #define MAX_RESOLVE_DEPTH 32
12552 
12553 static int btf_get_type_size(const struct btf *btf, __u32 type_id,
12554 			     const struct btf_type **ret_type)
12555 {
12556 	const struct btf_type *t;
12557 	int i;
12558 
12559 	*ret_type = btf__type_by_id(btf, 0);
12560 	if (!type_id)
12561 		return 0;
12562 	t = btf__type_by_id(btf, type_id);
12563 	for (i = 0; i < MAX_RESOLVE_DEPTH && t && btf_type_is_modifier(t); i++)
12564 		t = btf__type_by_id(btf, t->type);
12565 	if (!t || i == MAX_RESOLVE_DEPTH)
12566 		return -EINVAL;
12567 	*ret_type = t;
12568 	if (btf_is_ptr(t))
12569 		return btf__pointer_size(btf);
12570 	if (btf_is_int(t) || btf_is_any_enum(t) || btf_is_struct(t) || btf_is_union(t))
12571 		return t->size;
12572 	return -EINVAL;
12573 }
12574 
12575 bool btf_type_is_traceable_func(const struct btf *btf, const struct btf_type *t)
12576 {
12577 	const struct btf_param *args;
12578 	const struct btf_type *proto;
12579 	__u32 i, nargs;
12580 	int ret;
12581 
12582 	if (!btf_is_func(t))
12583 		return false;
12584 	proto = btf__type_by_id(btf, t->type);
12585 	if (!proto || !btf_is_func_proto(proto))
12586 		return false;
12587 
12588 	args = (const struct btf_param *)(proto + 1);
12589 	nargs = btf_vlen(proto);
12590 	if (nargs > MAX_BPF_FUNC_ARGS)
12591 		return false;
12592 
12593 	/* No support for struct return type. */
12594 	ret = btf_get_type_size(btf, proto->type, &t);
12595 	if (ret < 0 || btf_is_struct(t) || btf_is_union(t))
12596 		return false;
12597 
12598 	for (i = 0; i < nargs; i++) {
12599 		/* No support for variable args. */
12600 		if (i == nargs - 1 && args[i].type == 0)
12601 			return false;
12602 		ret = btf_get_type_size(btf, args[i].type, &t);
12603 		/* No support of struct argument size greater than 16 bytes. */
12604 		if (ret < 0 || ret > 16)
12605 			return false;
12606 		/* No support for void argument. */
12607 		if (ret == 0)
12608 			return false;
12609 	}
12610 
12611 	return true;
12612 }
12613 
12614 static int
12615 collect_btf_func_ids_by_glob(const struct btf *btf, const char *pattern, __u32 **ids)
12616 {
12617 	__u32 type_id, nr_types = btf__type_cnt(btf);
12618 	size_t cap = 0, cnt = 0;
12619 
12620 	if (!pattern)
12621 		return -EINVAL;
12622 
12623 	for (type_id = 1; type_id < nr_types; type_id++) {
12624 		const struct btf_type *t = btf__type_by_id(btf, type_id);
12625 		const char *name;
12626 		int err;
12627 
12628 		if (btf_kind(t) != BTF_KIND_FUNC)
12629 			continue;
12630 		name = btf__name_by_offset(btf, t->name_off);
12631 		if (!name)
12632 			continue;
12633 
12634 		if (!glob_match(name, pattern))
12635 			continue;
12636 		if (!btf_type_is_traceable_func(btf, t))
12637 			continue;
12638 
12639 		err = libbpf_ensure_mem((void **) ids, &cap, sizeof(**ids), cnt + 1);
12640 		if (err) {
12641 			free(*ids);
12642 			return -ENOMEM;
12643 		}
12644 		(*ids)[cnt++] = type_id;
12645 	}
12646 
12647 	return cnt;
12648 }
12649 
12650 static int collect_func_ids_by_glob(const struct bpf_program *prog, const char *pattern, __u32 **ids)
12651 {
12652 	struct bpf_object *obj = prog->obj;
12653 	const struct module_btf *mod;
12654 	struct btf *btf = NULL;
12655 	const char *sep;
12656 	int err;
12657 
12658 	err = bpf_object__load_vmlinux_btf(obj, true);
12659 	if (err)
12660 		return err;
12661 
12662 	/* In case we have module specified, we will find its btf and use that. */
12663 	sep = strchr(pattern, ':');
12664 	if (sep) {
12665 		mod = find_attach_module(obj, pattern);
12666 		if (!mod) {
12667 			err = -EINVAL;
12668 			goto cleanup;
12669 		}
12670 		btf = mod->btf;
12671 		pattern = sep + 1;
12672 	} else {
12673 		/* Program is loaded for kernel module. */
12674 		if (prog->attach_btf_obj_fd) {
12675 			err = -EINVAL;
12676 			goto cleanup;
12677 		}
12678 		btf = obj->btf_vmlinux;
12679 	}
12680 
12681 	err = collect_btf_func_ids_by_glob(btf, pattern, ids);
12682 
12683 cleanup:
12684 	bpf_object_cleanup_btf(obj);
12685 	return err;
12686 }
12687 
12688 struct bpf_link *
12689 bpf_program__attach_tracing_multi(const struct bpf_program *prog, const char *pattern,
12690 				  const struct bpf_tracing_multi_opts *opts)
12691 {
12692 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
12693 	int prog_fd, link_fd, err, cnt;
12694 	__u32 *free_ids = NULL;
12695 	struct bpf_link *link;
12696 	const __u64 *cookies;
12697 	const __u32 *ids;
12698 
12699 	if (!OPTS_VALID(opts, bpf_tracing_multi_opts))
12700 		return libbpf_err_ptr(-EINVAL);
12701 
12702 	prog_fd = bpf_program__fd(prog);
12703 	if (prog_fd < 0) {
12704 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
12705 			prog->name);
12706 		return libbpf_err_ptr(-EINVAL);
12707 	}
12708 
12709 	cnt = OPTS_GET(opts, cnt, 0);
12710 	ids = OPTS_GET(opts, ids, NULL);
12711 	cookies = OPTS_GET(opts, cookies, NULL);
12712 
12713 	if (!!ids != !!cnt)
12714 		return libbpf_err_ptr(-EINVAL);
12715 	if (pattern && (ids || cookies))
12716 		return libbpf_err_ptr(-EINVAL);
12717 	if (!pattern && !ids)
12718 		return libbpf_err_ptr(-EINVAL);
12719 
12720 	if (pattern) {
12721 		cnt = collect_func_ids_by_glob(prog, pattern, &free_ids);
12722 		if (cnt < 0)
12723 			return libbpf_err_ptr(cnt);
12724 		if (cnt == 0)
12725 			return libbpf_err_ptr(-EINVAL);
12726 		ids = (const __u32 *) free_ids;
12727 	}
12728 
12729 	lopts.tracing_multi.ids = ids;
12730 	lopts.tracing_multi.cookies = cookies;
12731 	lopts.tracing_multi.cnt = cnt;
12732 
12733 	link = calloc(1, sizeof(*link));
12734 	if (!link) {
12735 		err = -ENOMEM;
12736 		goto error;
12737 	}
12738 	link->detach = &bpf_link__detach_fd;
12739 
12740 	link_fd = bpf_link_create(prog_fd, 0, prog->expected_attach_type, &lopts);
12741 	if (link_fd < 0) {
12742 		err = -errno;
12743 		pr_warn("prog '%s': failed to attach: %s\n", prog->name, errstr(err));
12744 		goto error;
12745 	}
12746 	link->fd = link_fd;
12747 	free(free_ids);
12748 	return link;
12749 
12750 error:
12751 	free(link);
12752 	free(free_ids);
12753 	return libbpf_err_ptr(err);
12754 }
12755 
12756 static int attach_tracing_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12757 {
12758 	static const char *const prefixes[] = {
12759 		"fentry.multi",
12760 		"fexit.multi",
12761 		"fsession.multi",
12762 		"fentry.multi.s",
12763 		"fexit.multi.s",
12764 		"fsession.multi.s",
12765 	};
12766 	const char *spec = NULL;
12767 	char *pattern;
12768 	size_t i;
12769 	int n;
12770 
12771 	*link = NULL;
12772 
12773 	for (i = 0; i < ARRAY_SIZE(prefixes); i++) {
12774 		size_t pfx_len;
12775 
12776 		if (!str_has_pfx(prog->sec_name, prefixes[i]))
12777 			continue;
12778 
12779 		pfx_len = strlen(prefixes[i]);
12780 		/* no auto-attach case of, e.g., SEC("fentry.multi") */
12781 		if (prog->sec_name[pfx_len] == '\0')
12782 			return 0;
12783 
12784 		if (prog->sec_name[pfx_len] != '/')
12785 			continue;
12786 
12787 		spec = prog->sec_name + pfx_len + 1;
12788 		break;
12789 	}
12790 
12791 	if (!spec) {
12792 		pr_warn("prog '%s': invalid section name '%s'\n",
12793 			prog->name, prog->sec_name);
12794 		return -EINVAL;
12795 	}
12796 
12797 	n = sscanf(spec, "%m[a-zA-Z0-9_.*?:]", &pattern);
12798 	if (n < 1) {
12799 		pr_warn("tracing multi pattern is invalid: %s\n", spec);
12800 		return -EINVAL;
12801 	}
12802 
12803 	*link = bpf_program__attach_tracing_multi(prog, pattern, NULL);
12804 	free(pattern);
12805 	return libbpf_get_error(*link);
12806 }
12807 
12808 static inline int add_uprobe_event_legacy(const char *probe_name, bool retprobe,
12809 					  const char *binary_path, size_t offset)
12810 {
12811 	return append_to_file(tracefs_uprobe_events(), "%c:%s/%s %s:0x%zx",
12812 			      retprobe ? 'r' : 'p',
12813 			      retprobe ? "uretprobes" : "uprobes",
12814 			      probe_name, binary_path, offset);
12815 }
12816 
12817 static inline int remove_uprobe_event_legacy(const char *probe_name, bool retprobe)
12818 {
12819 	return append_to_file(tracefs_uprobe_events(), "-:%s/%s",
12820 			      retprobe ? "uretprobes" : "uprobes", probe_name);
12821 }
12822 
12823 static int determine_uprobe_perf_type_legacy(const char *probe_name, bool retprobe)
12824 {
12825 	char file[512];
12826 
12827 	snprintf(file, sizeof(file), "%s/events/%s/%s/id",
12828 		 tracefs_path(), retprobe ? "uretprobes" : "uprobes", probe_name);
12829 
12830 	return parse_uint_from_file(file, "%d\n");
12831 }
12832 
12833 static int perf_event_uprobe_open_legacy(const char *probe_name, bool retprobe,
12834 					 const char *binary_path, size_t offset, int pid)
12835 {
12836 	const size_t attr_sz = sizeof(struct perf_event_attr);
12837 	struct perf_event_attr attr;
12838 	int type, pfd, err;
12839 
12840 	err = add_uprobe_event_legacy(probe_name, retprobe, binary_path, offset);
12841 	if (err < 0) {
12842 		pr_warn("failed to add legacy uprobe event for %s:0x%zx: %s\n",
12843 			binary_path, (size_t)offset, errstr(err));
12844 		return err;
12845 	}
12846 	type = determine_uprobe_perf_type_legacy(probe_name, retprobe);
12847 	if (type < 0) {
12848 		err = type;
12849 		pr_warn("failed to determine legacy uprobe event id for %s:0x%zx: %s\n",
12850 			binary_path, offset, errstr(err));
12851 		goto err_clean_legacy;
12852 	}
12853 
12854 	memset(&attr, 0, attr_sz);
12855 	attr.size = attr_sz;
12856 	attr.config = type;
12857 	attr.type = PERF_TYPE_TRACEPOINT;
12858 
12859 	pfd = syscall(__NR_perf_event_open, &attr,
12860 		      pid < 0 ? -1 : pid, /* pid */
12861 		      pid == -1 ? 0 : -1, /* cpu */
12862 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
12863 	if (pfd < 0) {
12864 		err = -errno;
12865 		pr_warn("legacy uprobe perf_event_open() failed: %s\n", errstr(err));
12866 		goto err_clean_legacy;
12867 	}
12868 	return pfd;
12869 
12870 err_clean_legacy:
12871 	/* Clear the newly added legacy uprobe_event */
12872 	remove_uprobe_event_legacy(probe_name, retprobe);
12873 	return err;
12874 }
12875 
12876 /* Find offset of function name in archive specified by path. Currently
12877  * supported are .zip files that do not compress their contents, as used on
12878  * Android in the form of APKs, for example. "file_name" is the name of the ELF
12879  * file inside the archive. "func_name" matches symbol name or name@@LIB for
12880  * library functions.
12881  *
12882  * An overview of the APK format specifically provided here:
12883  * https://en.wikipedia.org/w/index.php?title=Apk_(file_format)&oldid=1139099120#Package_contents
12884  */
12885 static long elf_find_func_offset_from_archive(const char *archive_path, const char *file_name,
12886 					      const char *func_name)
12887 {
12888 	struct zip_archive *archive;
12889 	struct zip_entry entry;
12890 	long ret;
12891 	Elf *elf;
12892 
12893 	archive = zip_archive_open(archive_path);
12894 	if (IS_ERR(archive)) {
12895 		ret = PTR_ERR(archive);
12896 		pr_warn("zip: failed to open %s: %ld\n", archive_path, ret);
12897 		return ret;
12898 	}
12899 
12900 	ret = zip_archive_find_entry(archive, file_name, &entry);
12901 	if (ret) {
12902 		pr_warn("zip: could not find archive member %s in %s: %ld\n", file_name,
12903 			archive_path, ret);
12904 		goto out;
12905 	}
12906 	pr_debug("zip: found entry for %s in %s at 0x%lx\n", file_name, archive_path,
12907 		 (unsigned long)entry.data_offset);
12908 
12909 	if (entry.compression) {
12910 		pr_warn("zip: entry %s of %s is compressed and cannot be handled\n", file_name,
12911 			archive_path);
12912 		ret = -LIBBPF_ERRNO__FORMAT;
12913 		goto out;
12914 	}
12915 
12916 	elf = elf_memory((void *)entry.data, entry.data_length);
12917 	if (!elf) {
12918 		pr_warn("elf: could not read elf file %s from %s: %s\n", file_name, archive_path,
12919 			elf_errmsg(-1));
12920 		ret = -LIBBPF_ERRNO__LIBELF;
12921 		goto out;
12922 	}
12923 
12924 	ret = elf_find_func_offset(elf, file_name, func_name);
12925 	if (ret > 0) {
12926 		pr_debug("elf: symbol address match for %s of %s in %s: 0x%x + 0x%lx = 0x%lx\n",
12927 			 func_name, file_name, archive_path, entry.data_offset, ret,
12928 			 ret + entry.data_offset);
12929 		ret += entry.data_offset;
12930 	}
12931 	elf_end(elf);
12932 
12933 out:
12934 	zip_archive_close(archive);
12935 	return ret;
12936 }
12937 
12938 static const char *arch_specific_lib_paths(void)
12939 {
12940 	/*
12941 	 * Based on https://packages.debian.org/sid/libc6.
12942 	 *
12943 	 * Assume that the traced program is built for the same architecture
12944 	 * as libbpf, which should cover the vast majority of cases.
12945 	 */
12946 #if defined(__x86_64__)
12947 	return "/lib/x86_64-linux-gnu";
12948 #elif defined(__i386__)
12949 	return "/lib/i386-linux-gnu";
12950 #elif defined(__s390x__)
12951 	return "/lib/s390x-linux-gnu";
12952 #elif defined(__arm__) && defined(__SOFTFP__)
12953 	return "/lib/arm-linux-gnueabi";
12954 #elif defined(__arm__) && !defined(__SOFTFP__)
12955 	return "/lib/arm-linux-gnueabihf";
12956 #elif defined(__aarch64__)
12957 	return "/lib/aarch64-linux-gnu";
12958 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 64
12959 	return "/lib/mips64el-linux-gnuabi64";
12960 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 32
12961 	return "/lib/mipsel-linux-gnu";
12962 #elif defined(__powerpc64__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
12963 	return "/lib/powerpc64le-linux-gnu";
12964 #elif defined(__sparc__) && defined(__arch64__)
12965 	return "/lib/sparc64-linux-gnu";
12966 #elif defined(__riscv) && __riscv_xlen == 64
12967 	return "/lib/riscv64-linux-gnu";
12968 #else
12969 	return NULL;
12970 #endif
12971 }
12972 
12973 /* Get full path to program/shared library. */
12974 static int resolve_full_path(const char *file, char *result, size_t result_sz)
12975 {
12976 	const char *search_paths[3] = {};
12977 	int i, perm;
12978 
12979 	if (str_has_sfx(file, ".so") || strstr(file, ".so.")) {
12980 		search_paths[0] = getenv("LD_LIBRARY_PATH");
12981 		search_paths[1] = "/usr/lib64:/usr/lib";
12982 		search_paths[2] = arch_specific_lib_paths();
12983 		perm = R_OK;
12984 	} else {
12985 		search_paths[0] = getenv("PATH");
12986 		search_paths[1] = "/usr/bin:/usr/sbin";
12987 		perm = R_OK | X_OK;
12988 	}
12989 
12990 	for (i = 0; i < ARRAY_SIZE(search_paths); i++) {
12991 		const char *s;
12992 
12993 		if (!search_paths[i])
12994 			continue;
12995 		for (s = search_paths[i]; s != NULL; s = strchr(s, ':')) {
12996 			const char *next_path;
12997 			int seg_len;
12998 
12999 			if (s[0] == ':')
13000 				s++;
13001 			next_path = strchr(s, ':');
13002 			seg_len = next_path ? next_path - s : strlen(s);
13003 			if (!seg_len)
13004 				continue;
13005 			snprintf(result, result_sz, "%.*s/%s", seg_len, s, file);
13006 			/* ensure it has required permissions */
13007 			if (faccessat(AT_FDCWD, result, perm, AT_EACCESS) < 0)
13008 				continue;
13009 			pr_debug("resolved '%s' to '%s'\n", file, result);
13010 			return 0;
13011 		}
13012 	}
13013 	return -ENOENT;
13014 }
13015 
13016 struct bpf_link *
13017 bpf_program__attach_uprobe_multi(const struct bpf_program *prog,
13018 				 pid_t pid,
13019 				 const char *path,
13020 				 const char *func_pattern,
13021 				 const struct bpf_uprobe_multi_opts *opts)
13022 {
13023 	const unsigned long *ref_ctr_offsets = NULL, *offsets = NULL;
13024 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
13025 	unsigned long *resolved_offsets = NULL;
13026 	enum bpf_attach_type attach_type;
13027 	int err = 0, link_fd, prog_fd;
13028 	struct bpf_link *link = NULL;
13029 	char full_path[PATH_MAX];
13030 	bool retprobe, session;
13031 	const __u64 *cookies;
13032 	const char **syms;
13033 	size_t cnt;
13034 
13035 	if (!OPTS_VALID(opts, bpf_uprobe_multi_opts))
13036 		return libbpf_err_ptr(-EINVAL);
13037 
13038 	prog_fd = bpf_program__fd(prog);
13039 	if (prog_fd < 0) {
13040 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
13041 			prog->name);
13042 		return libbpf_err_ptr(-EINVAL);
13043 	}
13044 
13045 	syms = OPTS_GET(opts, syms, NULL);
13046 	offsets = OPTS_GET(opts, offsets, NULL);
13047 	ref_ctr_offsets = OPTS_GET(opts, ref_ctr_offsets, NULL);
13048 	cookies = OPTS_GET(opts, cookies, NULL);
13049 	cnt = OPTS_GET(opts, cnt, 0);
13050 	retprobe = OPTS_GET(opts, retprobe, false);
13051 	session  = OPTS_GET(opts, session, false);
13052 
13053 	/*
13054 	 * User can specify 2 mutually exclusive set of inputs:
13055 	 *
13056 	 * 1) use only path/func_pattern/pid arguments
13057 	 *
13058 	 * 2) use path/pid with allowed combinations of:
13059 	 *    syms/offsets/ref_ctr_offsets/cookies/cnt
13060 	 *
13061 	 *    - syms and offsets are mutually exclusive
13062 	 *    - ref_ctr_offsets and cookies are optional
13063 	 *
13064 	 * Any other usage results in error.
13065 	 */
13066 
13067 	if (!path)
13068 		return libbpf_err_ptr(-EINVAL);
13069 	if (!func_pattern && cnt == 0)
13070 		return libbpf_err_ptr(-EINVAL);
13071 
13072 	if (func_pattern) {
13073 		if (syms || offsets || ref_ctr_offsets || cookies || cnt)
13074 			return libbpf_err_ptr(-EINVAL);
13075 	} else {
13076 		if (!!syms == !!offsets)
13077 			return libbpf_err_ptr(-EINVAL);
13078 	}
13079 
13080 	if (retprobe && session)
13081 		return libbpf_err_ptr(-EINVAL);
13082 
13083 	if (func_pattern) {
13084 		if (!strchr(path, '/')) {
13085 			err = resolve_full_path(path, full_path, sizeof(full_path));
13086 			if (err) {
13087 				pr_warn("prog '%s': failed to resolve full path for '%s': %s\n",
13088 					prog->name, path, errstr(err));
13089 				return libbpf_err_ptr(err);
13090 			}
13091 			path = full_path;
13092 		}
13093 
13094 		err = elf_resolve_pattern_offsets(path, func_pattern,
13095 						  &resolved_offsets, &cnt);
13096 		if (err < 0)
13097 			return libbpf_err_ptr(err);
13098 		offsets = resolved_offsets;
13099 	} else if (syms) {
13100 		err = elf_resolve_syms_offsets(path, cnt, syms, &resolved_offsets, STT_FUNC);
13101 		if (err < 0)
13102 			return libbpf_err_ptr(err);
13103 		offsets = resolved_offsets;
13104 	}
13105 
13106 	attach_type = session ? BPF_TRACE_UPROBE_SESSION : BPF_TRACE_UPROBE_MULTI;
13107 
13108 	lopts.uprobe_multi.path = path;
13109 	lopts.uprobe_multi.offsets = offsets;
13110 	lopts.uprobe_multi.ref_ctr_offsets = ref_ctr_offsets;
13111 	lopts.uprobe_multi.cookies = cookies;
13112 	lopts.uprobe_multi.cnt = cnt;
13113 	lopts.uprobe_multi.flags = retprobe ? BPF_F_UPROBE_MULTI_RETURN : 0;
13114 
13115 	if (pid == 0)
13116 		pid = getpid();
13117 	if (pid > 0)
13118 		lopts.uprobe_multi.pid = pid;
13119 
13120 	link = calloc(1, sizeof(*link));
13121 	if (!link) {
13122 		err = -ENOMEM;
13123 		goto error;
13124 	}
13125 	link->detach = &bpf_link__detach_fd;
13126 
13127 	link_fd = bpf_link_create(prog_fd, 0, attach_type, &lopts);
13128 	if (link_fd < 0) {
13129 		err = -errno;
13130 		pr_warn("prog '%s': failed to attach multi-uprobe: %s\n",
13131 			prog->name, errstr(err));
13132 		goto error;
13133 	}
13134 	link->fd = link_fd;
13135 	free(resolved_offsets);
13136 	return link;
13137 
13138 error:
13139 	free(resolved_offsets);
13140 	free(link);
13141 	return libbpf_err_ptr(err);
13142 }
13143 
13144 LIBBPF_API struct bpf_link *
13145 bpf_program__attach_uprobe_opts(const struct bpf_program *prog, pid_t pid,
13146 				const char *binary_path, size_t func_offset,
13147 				const struct bpf_uprobe_opts *opts)
13148 {
13149 	const char *archive_path = NULL, *archive_sep = NULL;
13150 	char *legacy_probe = NULL;
13151 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
13152 	enum probe_attach_mode attach_mode;
13153 	char full_path[PATH_MAX];
13154 	struct bpf_link *link;
13155 	size_t ref_ctr_off;
13156 	int pfd, err;
13157 	bool retprobe, legacy;
13158 	const char *func_name;
13159 
13160 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
13161 		return libbpf_err_ptr(-EINVAL);
13162 
13163 	attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
13164 	retprobe = OPTS_GET(opts, retprobe, false);
13165 	ref_ctr_off = OPTS_GET(opts, ref_ctr_offset, 0);
13166 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
13167 
13168 	if (!binary_path)
13169 		return libbpf_err_ptr(-EINVAL);
13170 
13171 	/* Check if "binary_path" refers to an archive. */
13172 	archive_sep = strstr(binary_path, "!/");
13173 	if (archive_sep) {
13174 		full_path[0] = '\0';
13175 		libbpf_strlcpy(full_path, binary_path,
13176 			       min(sizeof(full_path), (size_t)(archive_sep - binary_path + 1)));
13177 		archive_path = full_path;
13178 		binary_path = archive_sep + 2;
13179 	} else if (!strchr(binary_path, '/')) {
13180 		err = resolve_full_path(binary_path, full_path, sizeof(full_path));
13181 		if (err) {
13182 			pr_warn("prog '%s': failed to resolve full path for '%s': %s\n",
13183 				prog->name, binary_path, errstr(err));
13184 			return libbpf_err_ptr(err);
13185 		}
13186 		binary_path = full_path;
13187 	}
13188 	func_name = OPTS_GET(opts, func_name, NULL);
13189 	if (func_name) {
13190 		long sym_off;
13191 
13192 		if (archive_path) {
13193 			sym_off = elf_find_func_offset_from_archive(archive_path, binary_path,
13194 								    func_name);
13195 			binary_path = archive_path;
13196 		} else {
13197 			sym_off = elf_find_func_offset_from_file(binary_path, func_name);
13198 		}
13199 		if (sym_off < 0)
13200 			return libbpf_err_ptr(sym_off);
13201 		func_offset += sym_off;
13202 	}
13203 
13204 	legacy = determine_uprobe_perf_type() < 0;
13205 	switch (attach_mode) {
13206 	case PROBE_ATTACH_MODE_LEGACY:
13207 		legacy = true;
13208 		pe_opts.force_ioctl_attach = true;
13209 		break;
13210 	case PROBE_ATTACH_MODE_PERF:
13211 		if (legacy)
13212 			return libbpf_err_ptr(-ENOTSUP);
13213 		pe_opts.force_ioctl_attach = true;
13214 		break;
13215 	case PROBE_ATTACH_MODE_LINK:
13216 		if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
13217 			return libbpf_err_ptr(-ENOTSUP);
13218 		break;
13219 	case PROBE_ATTACH_MODE_DEFAULT:
13220 		break;
13221 	default:
13222 		return libbpf_err_ptr(-EINVAL);
13223 	}
13224 
13225 	if (!legacy) {
13226 		pfd = perf_event_open_probe(true /* uprobe */, retprobe, binary_path,
13227 					    func_offset, pid, ref_ctr_off);
13228 	} else {
13229 		char probe_name[MAX_EVENT_NAME_LEN];
13230 
13231 		if (ref_ctr_off)
13232 			return libbpf_err_ptr(-EINVAL);
13233 
13234 		gen_probe_legacy_event_name(probe_name, sizeof(probe_name),
13235 					    strrchr(binary_path, '/') ? : binary_path,
13236 					    func_offset);
13237 
13238 		legacy_probe = strdup(probe_name);
13239 		if (!legacy_probe)
13240 			return libbpf_err_ptr(-ENOMEM);
13241 
13242 		pfd = perf_event_uprobe_open_legacy(legacy_probe, retprobe,
13243 						    binary_path, func_offset, pid);
13244 	}
13245 	if (pfd < 0) {
13246 		err = pfd;
13247 		pr_warn("prog '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
13248 			prog->name, retprobe ? "uretprobe" : "uprobe",
13249 			binary_path, func_offset,
13250 			errstr(err));
13251 		goto err_out;
13252 	}
13253 
13254 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
13255 	err = libbpf_get_error(link);
13256 	if (err) {
13257 		close(pfd);
13258 		pr_warn("prog '%s': failed to attach to %s '%s:0x%zx': %s\n",
13259 			prog->name, retprobe ? "uretprobe" : "uprobe",
13260 			binary_path, func_offset,
13261 			errstr(err));
13262 		goto err_clean_legacy;
13263 	}
13264 	if (legacy) {
13265 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
13266 
13267 		perf_link->legacy_probe_name = legacy_probe;
13268 		perf_link->legacy_is_kprobe = false;
13269 		perf_link->legacy_is_retprobe = retprobe;
13270 	}
13271 	return link;
13272 
13273 err_clean_legacy:
13274 	if (legacy)
13275 		remove_uprobe_event_legacy(legacy_probe, retprobe);
13276 err_out:
13277 	free(legacy_probe);
13278 	return libbpf_err_ptr(err);
13279 }
13280 
13281 /* Format of u[ret]probe section definition supporting auto-attach:
13282  * u[ret]probe/binary:function[+offset]
13283  *
13284  * binary can be an absolute/relative path or a filename; the latter is resolved to a
13285  * full binary path via bpf_program__attach_uprobe_opts.
13286  *
13287  * Specifying uprobe+ ensures we carry out strict matching; either "uprobe" must be
13288  * specified (and auto-attach is not possible) or the above format is specified for
13289  * auto-attach.
13290  */
13291 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
13292 {
13293 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts);
13294 	char *probe_type = NULL, *binary_path = NULL, *func_name = NULL, *func_off;
13295 	int n, c, ret = -EINVAL;
13296 	long offset = 0;
13297 
13298 	*link = NULL;
13299 
13300 	n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[^\n]",
13301 		   &probe_type, &binary_path, &func_name);
13302 	switch (n) {
13303 	case 1:
13304 		/* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
13305 		ret = 0;
13306 		break;
13307 	case 2:
13308 		pr_warn("prog '%s': section '%s' missing ':function[+offset]' specification\n",
13309 			prog->name, prog->sec_name);
13310 		break;
13311 	case 3:
13312 		/* check if user specifies `+offset`, if yes, this should be
13313 		 * the last part of the string, make sure sscanf read to EOL
13314 		 */
13315 		func_off = strrchr(func_name, '+');
13316 		if (func_off) {
13317 			n = sscanf(func_off, "+%li%n", &offset, &c);
13318 			if (n == 1 && *(func_off + c) == '\0')
13319 				func_off[0] = '\0';
13320 			else
13321 				offset = 0;
13322 		}
13323 		opts.retprobe = strcmp(probe_type, "uretprobe") == 0 ||
13324 				strcmp(probe_type, "uretprobe.s") == 0;
13325 		if (opts.retprobe && offset != 0) {
13326 			pr_warn("prog '%s': uretprobes do not support offset specification\n",
13327 				prog->name);
13328 			break;
13329 		}
13330 		opts.func_name = func_name;
13331 		*link = bpf_program__attach_uprobe_opts(prog, -1, binary_path, offset, &opts);
13332 		ret = libbpf_get_error(*link);
13333 		break;
13334 	default:
13335 		pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
13336 			prog->sec_name);
13337 		break;
13338 	}
13339 	free(probe_type);
13340 	free(binary_path);
13341 	free(func_name);
13342 
13343 	return ret;
13344 }
13345 
13346 struct bpf_link *bpf_program__attach_uprobe(const struct bpf_program *prog,
13347 					    bool retprobe, pid_t pid,
13348 					    const char *binary_path,
13349 					    size_t func_offset)
13350 {
13351 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts, .retprobe = retprobe);
13352 
13353 	return bpf_program__attach_uprobe_opts(prog, pid, binary_path, func_offset, &opts);
13354 }
13355 
13356 struct bpf_link *bpf_program__attach_usdt(const struct bpf_program *prog,
13357 					  pid_t pid, const char *binary_path,
13358 					  const char *usdt_provider, const char *usdt_name,
13359 					  const struct bpf_usdt_opts *opts)
13360 {
13361 	char resolved_path[512];
13362 	struct bpf_object *obj = prog->obj;
13363 	struct bpf_link *link;
13364 	__u64 usdt_cookie;
13365 	int err;
13366 
13367 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
13368 		return libbpf_err_ptr(-EINVAL);
13369 
13370 	if (bpf_program__fd(prog) < 0) {
13371 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
13372 			prog->name);
13373 		return libbpf_err_ptr(-EINVAL);
13374 	}
13375 
13376 	if (!binary_path)
13377 		return libbpf_err_ptr(-EINVAL);
13378 
13379 	if (!strchr(binary_path, '/')) {
13380 		err = resolve_full_path(binary_path, resolved_path, sizeof(resolved_path));
13381 		if (err) {
13382 			pr_warn("prog '%s': failed to resolve full path for '%s': %s\n",
13383 				prog->name, binary_path, errstr(err));
13384 			return libbpf_err_ptr(err);
13385 		}
13386 		binary_path = resolved_path;
13387 	}
13388 
13389 	/* USDT manager is instantiated lazily on first USDT attach. It will
13390 	 * be destroyed together with BPF object in bpf_object__close().
13391 	 */
13392 	if (IS_ERR(obj->usdt_man))
13393 		return libbpf_ptr(obj->usdt_man);
13394 	if (!obj->usdt_man) {
13395 		obj->usdt_man = usdt_manager_new(obj);
13396 		if (IS_ERR(obj->usdt_man))
13397 			return libbpf_ptr(obj->usdt_man);
13398 	}
13399 
13400 	usdt_cookie = OPTS_GET(opts, usdt_cookie, 0);
13401 	link = usdt_manager_attach_usdt(obj->usdt_man, prog, pid, binary_path,
13402 					usdt_provider, usdt_name, usdt_cookie);
13403 	err = libbpf_get_error(link);
13404 	if (err)
13405 		return libbpf_err_ptr(err);
13406 	return link;
13407 }
13408 
13409 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link)
13410 {
13411 	char *path = NULL, *provider = NULL, *name = NULL;
13412 	const char *sec_name;
13413 	int n, err;
13414 
13415 	sec_name = bpf_program__section_name(prog);
13416 	if (strcmp(sec_name, "usdt") == 0) {
13417 		/* no auto-attach for just SEC("usdt") */
13418 		*link = NULL;
13419 		return 0;
13420 	}
13421 
13422 	n = sscanf(sec_name, "usdt/%m[^:]:%m[^:]:%m[^:]", &path, &provider, &name);
13423 	if (n != 3) {
13424 		pr_warn("invalid section '%s', expected SEC(\"usdt/<path>:<provider>:<name>\")\n",
13425 			sec_name);
13426 		err = -EINVAL;
13427 	} else {
13428 		*link = bpf_program__attach_usdt(prog, -1 /* any process */, path,
13429 						 provider, name, NULL);
13430 		err = libbpf_get_error(*link);
13431 	}
13432 	free(path);
13433 	free(provider);
13434 	free(name);
13435 	return err;
13436 }
13437 
13438 static int determine_tracepoint_id(const char *tp_category,
13439 				   const char *tp_name)
13440 {
13441 	char file[PATH_MAX];
13442 	int ret;
13443 
13444 	ret = snprintf(file, sizeof(file), "%s/events/%s/%s/id",
13445 		       tracefs_path(), tp_category, tp_name);
13446 	if (ret < 0)
13447 		return -errno;
13448 	if (ret >= sizeof(file)) {
13449 		pr_debug("tracepoint %s/%s path is too long\n",
13450 			 tp_category, tp_name);
13451 		return -E2BIG;
13452 	}
13453 	return parse_uint_from_file(file, "%d\n");
13454 }
13455 
13456 static int perf_event_open_tracepoint(const char *tp_category,
13457 				      const char *tp_name)
13458 {
13459 	const size_t attr_sz = sizeof(struct perf_event_attr);
13460 	struct perf_event_attr attr;
13461 	int tp_id, pfd, err;
13462 
13463 	tp_id = determine_tracepoint_id(tp_category, tp_name);
13464 	if (tp_id < 0) {
13465 		pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
13466 			tp_category, tp_name,
13467 			errstr(tp_id));
13468 		return tp_id;
13469 	}
13470 
13471 	memset(&attr, 0, attr_sz);
13472 	attr.type = PERF_TYPE_TRACEPOINT;
13473 	attr.size = attr_sz;
13474 	attr.config = tp_id;
13475 
13476 	pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
13477 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
13478 	if (pfd < 0) {
13479 		err = -errno;
13480 		pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
13481 			tp_category, tp_name,
13482 			errstr(err));
13483 		return err;
13484 	}
13485 	return pfd;
13486 }
13487 
13488 struct bpf_link *bpf_program__attach_tracepoint_opts(const struct bpf_program *prog,
13489 						     const char *tp_category,
13490 						     const char *tp_name,
13491 						     const struct bpf_tracepoint_opts *opts)
13492 {
13493 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
13494 	struct bpf_link *link;
13495 	int pfd, err;
13496 
13497 	if (!OPTS_VALID(opts, bpf_tracepoint_opts))
13498 		return libbpf_err_ptr(-EINVAL);
13499 
13500 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
13501 
13502 	pfd = perf_event_open_tracepoint(tp_category, tp_name);
13503 	if (pfd < 0) {
13504 		pr_warn("prog '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
13505 			prog->name, tp_category, tp_name,
13506 			errstr(pfd));
13507 		return libbpf_err_ptr(pfd);
13508 	}
13509 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
13510 	err = libbpf_get_error(link);
13511 	if (err) {
13512 		close(pfd);
13513 		pr_warn("prog '%s': failed to attach to tracepoint '%s/%s': %s\n",
13514 			prog->name, tp_category, tp_name,
13515 			errstr(err));
13516 		return libbpf_err_ptr(err);
13517 	}
13518 	return link;
13519 }
13520 
13521 struct bpf_link *bpf_program__attach_tracepoint(const struct bpf_program *prog,
13522 						const char *tp_category,
13523 						const char *tp_name)
13524 {
13525 	return bpf_program__attach_tracepoint_opts(prog, tp_category, tp_name, NULL);
13526 }
13527 
13528 /*
13529  * Match section name against a prefix array. Returns pointer past
13530  * "prefix/" on match, empty string for bare sections (exact prefix
13531  * match), or NULL if no prefix matches.
13532  */
13533 static const char *sec_name_match_prefix(const char *sec_name,
13534 					 const char *const *prefixes,
13535 					 size_t n)
13536 {
13537 	size_t i;
13538 
13539 	for (i = 0; i < n; i++) {
13540 		size_t pfx_len;
13541 
13542 		if (!str_has_pfx(sec_name, prefixes[i]))
13543 			continue;
13544 
13545 		pfx_len = strlen(prefixes[i]);
13546 		if (sec_name[pfx_len] == '\0')
13547 			return sec_name + pfx_len;
13548 
13549 		if (sec_name[pfx_len] != '/' || sec_name[pfx_len + 1] == '\0')
13550 			continue;
13551 
13552 		return sec_name + pfx_len + 1;
13553 	}
13554 	return NULL;
13555 }
13556 
13557 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
13558 {
13559 	static const char *const prefixes[] = {
13560 		"tp.s",
13561 		"tp",
13562 		"tracepoint.s",
13563 		"tracepoint",
13564 	};
13565 	char *sec_name, *tp_cat, *tp_name;
13566 	const char *match;
13567 
13568 	*link = NULL;
13569 
13570 	match = sec_name_match_prefix(prog->sec_name, prefixes, ARRAY_SIZE(prefixes));
13571 	if (!match) {
13572 		pr_warn("prog '%s': invalid section name '%s'\n", prog->name, prog->sec_name);
13573 		return -EINVAL;
13574 	}
13575 	if (!match[0]) /* bare section name no autoattach */
13576 		return 0;
13577 
13578 	sec_name = strdup(prog->sec_name);
13579 	if (!sec_name)
13580 		return -ENOMEM;
13581 
13582 	tp_cat = sec_name + (match - prog->sec_name);
13583 	tp_name = strchr(tp_cat, '/');
13584 	if (!tp_name) {
13585 		free(sec_name);
13586 		return -EINVAL;
13587 	}
13588 	*tp_name = '\0';
13589 	tp_name++;
13590 
13591 	*link = bpf_program__attach_tracepoint(prog, tp_cat, tp_name);
13592 	free(sec_name);
13593 	return libbpf_get_error(*link);
13594 }
13595 
13596 struct bpf_link *
13597 bpf_program__attach_raw_tracepoint_opts(const struct bpf_program *prog,
13598 					const char *tp_name,
13599 					struct bpf_raw_tracepoint_opts *opts)
13600 {
13601 	LIBBPF_OPTS(bpf_raw_tp_opts, raw_opts);
13602 	struct bpf_link *link;
13603 	int prog_fd, pfd;
13604 
13605 	if (!OPTS_VALID(opts, bpf_raw_tracepoint_opts))
13606 		return libbpf_err_ptr(-EINVAL);
13607 
13608 	prog_fd = bpf_program__fd(prog);
13609 	if (prog_fd < 0) {
13610 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
13611 		return libbpf_err_ptr(-EINVAL);
13612 	}
13613 
13614 	link = calloc(1, sizeof(*link));
13615 	if (!link)
13616 		return libbpf_err_ptr(-ENOMEM);
13617 	link->detach = &bpf_link__detach_fd;
13618 
13619 	raw_opts.tp_name = tp_name;
13620 	raw_opts.cookie = OPTS_GET(opts, cookie, 0);
13621 	pfd = bpf_raw_tracepoint_open_opts(prog_fd, &raw_opts);
13622 	if (pfd < 0) {
13623 		pfd = -errno;
13624 		free(link);
13625 		pr_warn("prog '%s': failed to attach to raw tracepoint '%s': %s\n",
13626 			prog->name, tp_name, errstr(pfd));
13627 		return libbpf_err_ptr(pfd);
13628 	}
13629 	link->fd = pfd;
13630 	return link;
13631 }
13632 
13633 struct bpf_link *bpf_program__attach_raw_tracepoint(const struct bpf_program *prog,
13634 						    const char *tp_name)
13635 {
13636 	return bpf_program__attach_raw_tracepoint_opts(prog, tp_name, NULL);
13637 }
13638 
13639 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
13640 {
13641 	static const char *const prefixes[] = {
13642 		"raw_tp",
13643 		"raw_tracepoint",
13644 		"raw_tp.w",
13645 		"raw_tracepoint.w",
13646 		"raw_tp.s",
13647 		"raw_tracepoint.s",
13648 	};
13649 	const char *match;
13650 
13651 	*link = NULL;
13652 
13653 	match = sec_name_match_prefix(prog->sec_name, prefixes, ARRAY_SIZE(prefixes));
13654 	if (!match) {
13655 		pr_warn("prog '%s': invalid section name '%s'\n", prog->name, prog->sec_name);
13656 		return -EINVAL;
13657 	}
13658 	if (!match[0])
13659 		return 0;
13660 
13661 	*link = bpf_program__attach_raw_tracepoint(prog, match);
13662 	return libbpf_get_error(*link);
13663 }
13664 
13665 /* Common logic for all BPF program types that attach to a btf_id */
13666 static struct bpf_link *bpf_program__attach_btf_id(const struct bpf_program *prog,
13667 						   const struct bpf_trace_opts *opts)
13668 {
13669 	LIBBPF_OPTS(bpf_link_create_opts, link_opts);
13670 	struct bpf_link *link;
13671 	int prog_fd, pfd;
13672 
13673 	if (!OPTS_VALID(opts, bpf_trace_opts))
13674 		return libbpf_err_ptr(-EINVAL);
13675 
13676 	prog_fd = bpf_program__fd(prog);
13677 	if (prog_fd < 0) {
13678 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
13679 		return libbpf_err_ptr(-EINVAL);
13680 	}
13681 
13682 	link = calloc(1, sizeof(*link));
13683 	if (!link)
13684 		return libbpf_err_ptr(-ENOMEM);
13685 	link->detach = &bpf_link__detach_fd;
13686 
13687 	/* libbpf is smart enough to redirect to BPF_RAW_TRACEPOINT_OPEN on old kernels */
13688 	link_opts.tracing.cookie = OPTS_GET(opts, cookie, 0);
13689 	pfd = bpf_link_create(prog_fd, 0, bpf_program__expected_attach_type(prog), &link_opts);
13690 	if (pfd < 0) {
13691 		pfd = -errno;
13692 		free(link);
13693 		pr_warn("prog '%s': failed to attach: %s\n",
13694 			prog->name, errstr(pfd));
13695 		return libbpf_err_ptr(pfd);
13696 	}
13697 	link->fd = pfd;
13698 	return link;
13699 }
13700 
13701 struct bpf_link *bpf_program__attach_trace(const struct bpf_program *prog)
13702 {
13703 	return bpf_program__attach_btf_id(prog, NULL);
13704 }
13705 
13706 struct bpf_link *bpf_program__attach_trace_opts(const struct bpf_program *prog,
13707 						const struct bpf_trace_opts *opts)
13708 {
13709 	return bpf_program__attach_btf_id(prog, opts);
13710 }
13711 
13712 struct bpf_link *bpf_program__attach_lsm(const struct bpf_program *prog)
13713 {
13714 	return bpf_program__attach_btf_id(prog, NULL);
13715 }
13716 
13717 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link)
13718 {
13719 	*link = bpf_program__attach_trace(prog);
13720 	return libbpf_get_error(*link);
13721 }
13722 
13723 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link)
13724 {
13725 	*link = bpf_program__attach_lsm(prog);
13726 	return libbpf_get_error(*link);
13727 }
13728 
13729 static struct bpf_link *
13730 bpf_program_attach_fd(const struct bpf_program *prog,
13731 		      int target_fd, const char *target_name,
13732 		      const struct bpf_link_create_opts *opts)
13733 {
13734 	enum bpf_attach_type attach_type;
13735 	struct bpf_link *link;
13736 	int prog_fd, link_fd;
13737 
13738 	prog_fd = bpf_program__fd(prog);
13739 	if (prog_fd < 0) {
13740 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
13741 		return libbpf_err_ptr(-EINVAL);
13742 	}
13743 
13744 	link = calloc(1, sizeof(*link));
13745 	if (!link)
13746 		return libbpf_err_ptr(-ENOMEM);
13747 	link->detach = &bpf_link__detach_fd;
13748 
13749 	attach_type = bpf_program__expected_attach_type(prog);
13750 	link_fd = bpf_link_create(prog_fd, target_fd, attach_type, opts);
13751 	if (link_fd < 0) {
13752 		link_fd = -errno;
13753 		free(link);
13754 		pr_warn("prog '%s': failed to attach to %s: %s\n",
13755 			prog->name, target_name,
13756 			errstr(link_fd));
13757 		return libbpf_err_ptr(link_fd);
13758 	}
13759 	link->fd = link_fd;
13760 	return link;
13761 }
13762 
13763 struct bpf_link *
13764 bpf_program__attach_cgroup(const struct bpf_program *prog, int cgroup_fd)
13765 {
13766 	return bpf_program_attach_fd(prog, cgroup_fd, "cgroup", NULL);
13767 }
13768 
13769 struct bpf_link *
13770 bpf_program__attach_netns(const struct bpf_program *prog, int netns_fd)
13771 {
13772 	return bpf_program_attach_fd(prog, netns_fd, "netns", NULL);
13773 }
13774 
13775 struct bpf_link *
13776 bpf_program__attach_sockmap(const struct bpf_program *prog, int map_fd)
13777 {
13778 	return bpf_program_attach_fd(prog, map_fd, "sockmap", NULL);
13779 }
13780 
13781 struct bpf_link *bpf_program__attach_xdp(const struct bpf_program *prog, int ifindex)
13782 {
13783 	/* target_fd/target_ifindex use the same field in LINK_CREATE */
13784 	return bpf_program_attach_fd(prog, ifindex, "xdp", NULL);
13785 }
13786 
13787 struct bpf_link *
13788 bpf_program__attach_cgroup_opts(const struct bpf_program *prog, int cgroup_fd,
13789 				const struct bpf_cgroup_opts *opts)
13790 {
13791 	LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
13792 	__u32 relative_id;
13793 	int relative_fd;
13794 
13795 	if (!OPTS_VALID(opts, bpf_cgroup_opts))
13796 		return libbpf_err_ptr(-EINVAL);
13797 
13798 	relative_id = OPTS_GET(opts, relative_id, 0);
13799 	relative_fd = OPTS_GET(opts, relative_fd, 0);
13800 
13801 	if (relative_fd && relative_id) {
13802 		pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
13803 			prog->name);
13804 		return libbpf_err_ptr(-EINVAL);
13805 	}
13806 
13807 	link_create_opts.cgroup.expected_revision = OPTS_GET(opts, expected_revision, 0);
13808 	link_create_opts.cgroup.relative_fd = relative_fd;
13809 	link_create_opts.cgroup.relative_id = relative_id;
13810 	link_create_opts.flags = OPTS_GET(opts, flags, 0);
13811 
13812 	return bpf_program_attach_fd(prog, cgroup_fd, "cgroup", &link_create_opts);
13813 }
13814 
13815 struct bpf_link *
13816 bpf_program__attach_tcx(const struct bpf_program *prog, int ifindex,
13817 			const struct bpf_tcx_opts *opts)
13818 {
13819 	LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
13820 	__u32 relative_id;
13821 	int relative_fd;
13822 
13823 	if (!OPTS_VALID(opts, bpf_tcx_opts))
13824 		return libbpf_err_ptr(-EINVAL);
13825 
13826 	relative_id = OPTS_GET(opts, relative_id, 0);
13827 	relative_fd = OPTS_GET(opts, relative_fd, 0);
13828 
13829 	/* validate we don't have unexpected combinations of non-zero fields */
13830 	if (!ifindex) {
13831 		pr_warn("prog '%s': target netdevice ifindex cannot be zero\n",
13832 			prog->name);
13833 		return libbpf_err_ptr(-EINVAL);
13834 	}
13835 	if (relative_fd && relative_id) {
13836 		pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
13837 			prog->name);
13838 		return libbpf_err_ptr(-EINVAL);
13839 	}
13840 
13841 	link_create_opts.tcx.expected_revision = OPTS_GET(opts, expected_revision, 0);
13842 	link_create_opts.tcx.relative_fd = relative_fd;
13843 	link_create_opts.tcx.relative_id = relative_id;
13844 	link_create_opts.flags = OPTS_GET(opts, flags, 0);
13845 
13846 	/* target_fd/target_ifindex use the same field in LINK_CREATE */
13847 	return bpf_program_attach_fd(prog, ifindex, "tcx", &link_create_opts);
13848 }
13849 
13850 struct bpf_link *
13851 bpf_program__attach_netkit(const struct bpf_program *prog, int ifindex,
13852 			   const struct bpf_netkit_opts *opts)
13853 {
13854 	LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
13855 	__u32 relative_id;
13856 	int relative_fd;
13857 
13858 	if (!OPTS_VALID(opts, bpf_netkit_opts))
13859 		return libbpf_err_ptr(-EINVAL);
13860 
13861 	relative_id = OPTS_GET(opts, relative_id, 0);
13862 	relative_fd = OPTS_GET(opts, relative_fd, 0);
13863 
13864 	/* validate we don't have unexpected combinations of non-zero fields */
13865 	if (!ifindex) {
13866 		pr_warn("prog '%s': target netdevice ifindex cannot be zero\n",
13867 			prog->name);
13868 		return libbpf_err_ptr(-EINVAL);
13869 	}
13870 	if (relative_fd && relative_id) {
13871 		pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
13872 			prog->name);
13873 		return libbpf_err_ptr(-EINVAL);
13874 	}
13875 
13876 	link_create_opts.netkit.expected_revision = OPTS_GET(opts, expected_revision, 0);
13877 	link_create_opts.netkit.relative_fd = relative_fd;
13878 	link_create_opts.netkit.relative_id = relative_id;
13879 	link_create_opts.flags = OPTS_GET(opts, flags, 0);
13880 
13881 	return bpf_program_attach_fd(prog, ifindex, "netkit", &link_create_opts);
13882 }
13883 
13884 struct bpf_link *bpf_program__attach_freplace(const struct bpf_program *prog,
13885 					      int target_fd,
13886 					      const char *attach_func_name)
13887 {
13888 	int btf_id;
13889 
13890 	if (!!target_fd != !!attach_func_name) {
13891 		pr_warn("prog '%s': supply none or both of target_fd and attach_func_name\n",
13892 			prog->name);
13893 		return libbpf_err_ptr(-EINVAL);
13894 	}
13895 
13896 	if (prog->type != BPF_PROG_TYPE_EXT) {
13897 		pr_warn("prog '%s': only BPF_PROG_TYPE_EXT can attach as freplace\n",
13898 			prog->name);
13899 		return libbpf_err_ptr(-EINVAL);
13900 	}
13901 
13902 	if (target_fd) {
13903 		LIBBPF_OPTS(bpf_link_create_opts, target_opts);
13904 
13905 		btf_id = libbpf_find_prog_btf_id(attach_func_name, target_fd, prog->obj->token_fd);
13906 		if (btf_id < 0)
13907 			return libbpf_err_ptr(btf_id);
13908 
13909 		target_opts.target_btf_id = btf_id;
13910 
13911 		return bpf_program_attach_fd(prog, target_fd, "freplace",
13912 					     &target_opts);
13913 	} else {
13914 		/* no target, so use raw_tracepoint_open for compatibility
13915 		 * with old kernels
13916 		 */
13917 		return bpf_program__attach_trace(prog);
13918 	}
13919 }
13920 
13921 struct bpf_link *
13922 bpf_program__attach_iter(const struct bpf_program *prog,
13923 			 const struct bpf_iter_attach_opts *opts)
13924 {
13925 	DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
13926 	struct bpf_link *link;
13927 	int prog_fd, link_fd;
13928 	__u32 target_fd = 0;
13929 
13930 	if (!OPTS_VALID(opts, bpf_iter_attach_opts))
13931 		return libbpf_err_ptr(-EINVAL);
13932 
13933 	link_create_opts.iter_info = OPTS_GET(opts, link_info, (void *)0);
13934 	link_create_opts.iter_info_len = OPTS_GET(opts, link_info_len, 0);
13935 
13936 	prog_fd = bpf_program__fd(prog);
13937 	if (prog_fd < 0) {
13938 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
13939 		return libbpf_err_ptr(-EINVAL);
13940 	}
13941 
13942 	link = calloc(1, sizeof(*link));
13943 	if (!link)
13944 		return libbpf_err_ptr(-ENOMEM);
13945 	link->detach = &bpf_link__detach_fd;
13946 
13947 	link_fd = bpf_link_create(prog_fd, target_fd, BPF_TRACE_ITER,
13948 				  &link_create_opts);
13949 	if (link_fd < 0) {
13950 		link_fd = -errno;
13951 		free(link);
13952 		pr_warn("prog '%s': failed to attach to iterator: %s\n",
13953 			prog->name, errstr(link_fd));
13954 		return libbpf_err_ptr(link_fd);
13955 	}
13956 	link->fd = link_fd;
13957 	return link;
13958 }
13959 
13960 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link)
13961 {
13962 	*link = bpf_program__attach_iter(prog, NULL);
13963 	return libbpf_get_error(*link);
13964 }
13965 
13966 struct bpf_link *bpf_program__attach_netfilter(const struct bpf_program *prog,
13967 					       const struct bpf_netfilter_opts *opts)
13968 {
13969 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
13970 	struct bpf_link *link;
13971 	int prog_fd, link_fd;
13972 
13973 	if (!OPTS_VALID(opts, bpf_netfilter_opts))
13974 		return libbpf_err_ptr(-EINVAL);
13975 
13976 	prog_fd = bpf_program__fd(prog);
13977 	if (prog_fd < 0) {
13978 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
13979 		return libbpf_err_ptr(-EINVAL);
13980 	}
13981 
13982 	link = calloc(1, sizeof(*link));
13983 	if (!link)
13984 		return libbpf_err_ptr(-ENOMEM);
13985 
13986 	link->detach = &bpf_link__detach_fd;
13987 
13988 	lopts.netfilter.pf = OPTS_GET(opts, pf, 0);
13989 	lopts.netfilter.hooknum = OPTS_GET(opts, hooknum, 0);
13990 	lopts.netfilter.priority = OPTS_GET(opts, priority, 0);
13991 	lopts.netfilter.flags = OPTS_GET(opts, flags, 0);
13992 
13993 	link_fd = bpf_link_create(prog_fd, 0, BPF_NETFILTER, &lopts);
13994 	if (link_fd < 0) {
13995 		link_fd = -errno;
13996 		free(link);
13997 		pr_warn("prog '%s': failed to attach to netfilter: %s\n",
13998 			prog->name, errstr(link_fd));
13999 		return libbpf_err_ptr(link_fd);
14000 	}
14001 	link->fd = link_fd;
14002 
14003 	return link;
14004 }
14005 
14006 struct bpf_link *bpf_program__attach(const struct bpf_program *prog)
14007 {
14008 	struct bpf_link *link = NULL;
14009 	int err;
14010 
14011 	if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
14012 		return libbpf_err_ptr(-EOPNOTSUPP);
14013 
14014 	if (bpf_program__fd(prog) < 0) {
14015 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
14016 			prog->name);
14017 		return libbpf_err_ptr(-EINVAL);
14018 	}
14019 
14020 	err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, &link);
14021 	if (err)
14022 		return libbpf_err_ptr(err);
14023 
14024 	/* When calling bpf_program__attach() explicitly, auto-attach support
14025 	 * is expected to work, so NULL returned link is considered an error.
14026 	 * This is different for skeleton's attach, see comment in
14027 	 * bpf_object__attach_skeleton().
14028 	 */
14029 	if (!link)
14030 		return libbpf_err_ptr(-EOPNOTSUPP);
14031 
14032 	return link;
14033 }
14034 
14035 struct bpf_link_struct_ops {
14036 	struct bpf_link link;
14037 	int map_fd;
14038 };
14039 
14040 static int bpf_link__detach_struct_ops(struct bpf_link *link)
14041 {
14042 	struct bpf_link_struct_ops *st_link;
14043 	__u32 zero = 0;
14044 
14045 	st_link = container_of(link, struct bpf_link_struct_ops, link);
14046 
14047 	if (st_link->map_fd < 0)
14048 		/* w/o a real link */
14049 		return bpf_map_delete_elem(link->fd, &zero);
14050 
14051 	return close(link->fd);
14052 }
14053 
14054 struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map)
14055 {
14056 	struct bpf_link_struct_ops *link;
14057 	__u32 zero = 0;
14058 	int err, fd;
14059 
14060 	if (!bpf_map__is_struct_ops(map)) {
14061 		pr_warn("map '%s': can't attach non-struct_ops map\n", map->name);
14062 		return libbpf_err_ptr(-EINVAL);
14063 	}
14064 
14065 	if (map->fd < 0) {
14066 		pr_warn("map '%s': can't attach BPF map without FD (was it created?)\n", map->name);
14067 		return libbpf_err_ptr(-EINVAL);
14068 	}
14069 
14070 	link = calloc(1, sizeof(*link));
14071 	if (!link)
14072 		return libbpf_err_ptr(-EINVAL);
14073 
14074 	/* kern_vdata should be prepared during the loading phase. */
14075 	err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
14076 	/* It can be EBUSY if the map has been used to create or
14077 	 * update a link before.  We don't allow updating the value of
14078 	 * a struct_ops once it is set.  That ensures that the value
14079 	 * never changed.  So, it is safe to skip EBUSY.
14080 	 */
14081 	if (err && (!(map->def.map_flags & BPF_F_LINK) || err != -EBUSY)) {
14082 		free(link);
14083 		return libbpf_err_ptr(err);
14084 	}
14085 
14086 	link->link.detach = bpf_link__detach_struct_ops;
14087 
14088 	if (!(map->def.map_flags & BPF_F_LINK)) {
14089 		/* w/o a real link */
14090 		link->link.fd = map->fd;
14091 		link->map_fd = -1;
14092 		return &link->link;
14093 	}
14094 
14095 	fd = bpf_link_create(map->fd, 0, BPF_STRUCT_OPS, NULL);
14096 	if (fd < 0) {
14097 		free(link);
14098 		return libbpf_err_ptr(fd);
14099 	}
14100 
14101 	link->link.fd = fd;
14102 	link->map_fd = map->fd;
14103 
14104 	return &link->link;
14105 }
14106 
14107 /*
14108  * Swap the back struct_ops of a link with a new struct_ops map.
14109  */
14110 int bpf_link__update_map(struct bpf_link *link, const struct bpf_map *map)
14111 {
14112 	struct bpf_link_struct_ops *st_ops_link;
14113 	__u32 zero = 0;
14114 	int err;
14115 
14116 	if (!bpf_map__is_struct_ops(map))
14117 		return libbpf_err(-EINVAL);
14118 
14119 	if (map->fd < 0) {
14120 		pr_warn("map '%s': can't use BPF map without FD (was it created?)\n", map->name);
14121 		return libbpf_err(-EINVAL);
14122 	}
14123 
14124 	st_ops_link = container_of(link, struct bpf_link_struct_ops, link);
14125 	/* Ensure the type of a link is correct */
14126 	if (st_ops_link->map_fd < 0)
14127 		return libbpf_err(-EINVAL);
14128 
14129 	err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
14130 	/* It can be EBUSY if the map has been used to create or
14131 	 * update a link before.  We don't allow updating the value of
14132 	 * a struct_ops once it is set.  That ensures that the value
14133 	 * never changed.  So, it is safe to skip EBUSY.
14134 	 */
14135 	if (err && err != -EBUSY)
14136 		return err;
14137 
14138 	err = bpf_link_update(link->fd, map->fd, NULL);
14139 	if (err < 0)
14140 		return err;
14141 
14142 	st_ops_link->map_fd = map->fd;
14143 
14144 	return 0;
14145 }
14146 
14147 typedef enum bpf_perf_event_ret (*bpf_perf_event_print_t)(struct perf_event_header *hdr,
14148 							  void *private_data);
14149 
14150 static enum bpf_perf_event_ret
14151 perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
14152 		       void **copy_mem, size_t *copy_size,
14153 		       bpf_perf_event_print_t fn, void *private_data)
14154 {
14155 	struct perf_event_mmap_page *header = mmap_mem;
14156 	__u64 data_head = ring_buffer_read_head(header);
14157 	__u64 data_tail = header->data_tail;
14158 	void *base = ((__u8 *)header) + page_size;
14159 	int ret = LIBBPF_PERF_EVENT_CONT;
14160 	struct perf_event_header *ehdr;
14161 	size_t ehdr_size;
14162 
14163 	while (data_head != data_tail) {
14164 		ehdr = base + (data_tail & (mmap_size - 1));
14165 		ehdr_size = ehdr->size;
14166 
14167 		if (((void *)ehdr) + ehdr_size > base + mmap_size) {
14168 			void *copy_start = ehdr;
14169 			size_t len_first = base + mmap_size - copy_start;
14170 			size_t len_secnd = ehdr_size - len_first;
14171 
14172 			if (*copy_size < ehdr_size) {
14173 				free(*copy_mem);
14174 				*copy_mem = malloc(ehdr_size);
14175 				if (!*copy_mem) {
14176 					*copy_size = 0;
14177 					ret = LIBBPF_PERF_EVENT_ERROR;
14178 					break;
14179 				}
14180 				*copy_size = ehdr_size;
14181 			}
14182 
14183 			memcpy(*copy_mem, copy_start, len_first);
14184 			memcpy(*copy_mem + len_first, base, len_secnd);
14185 			ehdr = *copy_mem;
14186 		}
14187 
14188 		ret = fn(ehdr, private_data);
14189 		data_tail += ehdr_size;
14190 		if (ret != LIBBPF_PERF_EVENT_CONT)
14191 			break;
14192 	}
14193 
14194 	ring_buffer_write_tail(header, data_tail);
14195 	return libbpf_err(ret);
14196 }
14197 
14198 struct perf_buffer;
14199 
14200 struct perf_buffer_params {
14201 	struct perf_event_attr *attr;
14202 	/* if event_cb is specified, it takes precendence */
14203 	perf_buffer_event_fn event_cb;
14204 	/* sample_cb and lost_cb are higher-level common-case callbacks */
14205 	perf_buffer_sample_fn sample_cb;
14206 	perf_buffer_lost_fn lost_cb;
14207 	void *ctx;
14208 	int cpu_cnt;
14209 	int *cpus;
14210 	int *map_keys;
14211 };
14212 
14213 struct perf_cpu_buf {
14214 	struct perf_buffer *pb;
14215 	void *base; /* mmap()'ed memory */
14216 	void *buf; /* for reconstructing segmented data */
14217 	size_t buf_size;
14218 	int fd;
14219 	int cpu;
14220 	int map_key;
14221 };
14222 
14223 struct perf_buffer {
14224 	perf_buffer_event_fn event_cb;
14225 	perf_buffer_sample_fn sample_cb;
14226 	perf_buffer_lost_fn lost_cb;
14227 	void *ctx; /* passed into callbacks */
14228 
14229 	size_t page_size;
14230 	size_t mmap_size;
14231 	struct perf_cpu_buf **cpu_bufs;
14232 	struct epoll_event *events;
14233 	int cpu_cnt; /* number of allocated CPU buffers */
14234 	int epoll_fd; /* perf event FD */
14235 	int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
14236 };
14237 
14238 static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
14239 				      struct perf_cpu_buf *cpu_buf)
14240 {
14241 	if (!cpu_buf)
14242 		return;
14243 	if (cpu_buf->base &&
14244 	    munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
14245 		pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
14246 	if (cpu_buf->fd >= 0) {
14247 		ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
14248 		close(cpu_buf->fd);
14249 	}
14250 	free(cpu_buf->buf);
14251 	free(cpu_buf);
14252 }
14253 
14254 void perf_buffer__free(struct perf_buffer *pb)
14255 {
14256 	int i;
14257 
14258 	if (IS_ERR_OR_NULL(pb))
14259 		return;
14260 	if (pb->cpu_bufs) {
14261 		for (i = 0; i < pb->cpu_cnt; i++) {
14262 			struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
14263 
14264 			if (!cpu_buf)
14265 				continue;
14266 
14267 			bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
14268 			perf_buffer__free_cpu_buf(pb, cpu_buf);
14269 		}
14270 		free(pb->cpu_bufs);
14271 	}
14272 	if (pb->epoll_fd >= 0)
14273 		close(pb->epoll_fd);
14274 	free(pb->events);
14275 	free(pb);
14276 }
14277 
14278 static struct perf_cpu_buf *
14279 perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
14280 			  int cpu, int map_key)
14281 {
14282 	struct perf_cpu_buf *cpu_buf;
14283 	int err;
14284 
14285 	cpu_buf = calloc(1, sizeof(*cpu_buf));
14286 	if (!cpu_buf)
14287 		return ERR_PTR(-ENOMEM);
14288 
14289 	cpu_buf->pb = pb;
14290 	cpu_buf->cpu = cpu;
14291 	cpu_buf->map_key = map_key;
14292 
14293 	cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
14294 			      -1, PERF_FLAG_FD_CLOEXEC);
14295 	if (cpu_buf->fd < 0) {
14296 		err = -errno;
14297 		pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
14298 			cpu, errstr(err));
14299 		goto error;
14300 	}
14301 
14302 	cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
14303 			     PROT_READ | PROT_WRITE, MAP_SHARED,
14304 			     cpu_buf->fd, 0);
14305 	if (cpu_buf->base == MAP_FAILED) {
14306 		cpu_buf->base = NULL;
14307 		err = -errno;
14308 		pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
14309 			cpu, errstr(err));
14310 		goto error;
14311 	}
14312 
14313 	if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
14314 		err = -errno;
14315 		pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
14316 			cpu, errstr(err));
14317 		goto error;
14318 	}
14319 
14320 	return cpu_buf;
14321 
14322 error:
14323 	perf_buffer__free_cpu_buf(pb, cpu_buf);
14324 	return (struct perf_cpu_buf *)ERR_PTR(err);
14325 }
14326 
14327 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
14328 					      struct perf_buffer_params *p);
14329 
14330 struct perf_buffer *perf_buffer__new(int map_fd, size_t page_cnt,
14331 				     perf_buffer_sample_fn sample_cb,
14332 				     perf_buffer_lost_fn lost_cb,
14333 				     void *ctx,
14334 				     const struct perf_buffer_opts *opts)
14335 {
14336 	const size_t attr_sz = sizeof(struct perf_event_attr);
14337 	struct perf_buffer_params p = {};
14338 	struct perf_event_attr attr;
14339 	__u32 sample_period;
14340 
14341 	if (!OPTS_VALID(opts, perf_buffer_opts))
14342 		return libbpf_err_ptr(-EINVAL);
14343 
14344 	sample_period = OPTS_GET(opts, sample_period, 1);
14345 	if (!sample_period)
14346 		sample_period = 1;
14347 
14348 	memset(&attr, 0, attr_sz);
14349 	attr.size = attr_sz;
14350 	attr.config = PERF_COUNT_SW_BPF_OUTPUT;
14351 	attr.type = PERF_TYPE_SOFTWARE;
14352 	attr.sample_type = PERF_SAMPLE_RAW;
14353 	attr.wakeup_events = sample_period;
14354 
14355 	p.attr = &attr;
14356 	p.sample_cb = sample_cb;
14357 	p.lost_cb = lost_cb;
14358 	p.ctx = ctx;
14359 
14360 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
14361 }
14362 
14363 struct perf_buffer *perf_buffer__new_raw(int map_fd, size_t page_cnt,
14364 					 struct perf_event_attr *attr,
14365 					 perf_buffer_event_fn event_cb, void *ctx,
14366 					 const struct perf_buffer_raw_opts *opts)
14367 {
14368 	struct perf_buffer_params p = {};
14369 
14370 	if (!attr)
14371 		return libbpf_err_ptr(-EINVAL);
14372 
14373 	if (!OPTS_VALID(opts, perf_buffer_raw_opts))
14374 		return libbpf_err_ptr(-EINVAL);
14375 
14376 	p.attr = attr;
14377 	p.event_cb = event_cb;
14378 	p.ctx = ctx;
14379 	p.cpu_cnt = OPTS_GET(opts, cpu_cnt, 0);
14380 	p.cpus = OPTS_GET(opts, cpus, NULL);
14381 	p.map_keys = OPTS_GET(opts, map_keys, NULL);
14382 
14383 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
14384 }
14385 
14386 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
14387 					      struct perf_buffer_params *p)
14388 {
14389 	const char *online_cpus_file = "/sys/devices/system/cpu/online";
14390 	struct bpf_map_info map;
14391 	struct perf_buffer *pb;
14392 	bool *online = NULL;
14393 	__u32 map_info_len;
14394 	int err, i, j, n;
14395 
14396 	if (page_cnt == 0 || (page_cnt & (page_cnt - 1))) {
14397 		pr_warn("page count should be power of two, but is %zu\n",
14398 			page_cnt);
14399 		return ERR_PTR(-EINVAL);
14400 	}
14401 
14402 	/* best-effort sanity checks */
14403 	memset(&map, 0, sizeof(map));
14404 	map_info_len = sizeof(map);
14405 	err = bpf_map_get_info_by_fd(map_fd, &map, &map_info_len);
14406 	if (err) {
14407 		err = -errno;
14408 		/* if BPF_OBJ_GET_INFO_BY_FD is supported, will return
14409 		 * -EBADFD, -EFAULT, or -E2BIG on real error
14410 		 */
14411 		if (err != -EINVAL) {
14412 			pr_warn("failed to get map info for map FD %d: %s\n",
14413 				map_fd, errstr(err));
14414 			return ERR_PTR(err);
14415 		}
14416 		pr_debug("failed to get map info for FD %d; API not supported? Ignoring...\n",
14417 			 map_fd);
14418 	} else {
14419 		if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
14420 			pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
14421 				map.name);
14422 			return ERR_PTR(-EINVAL);
14423 		}
14424 	}
14425 
14426 	pb = calloc(1, sizeof(*pb));
14427 	if (!pb)
14428 		return ERR_PTR(-ENOMEM);
14429 
14430 	pb->event_cb = p->event_cb;
14431 	pb->sample_cb = p->sample_cb;
14432 	pb->lost_cb = p->lost_cb;
14433 	pb->ctx = p->ctx;
14434 
14435 	pb->page_size = getpagesize();
14436 	pb->mmap_size = pb->page_size * page_cnt;
14437 	pb->map_fd = map_fd;
14438 
14439 	pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
14440 	if (pb->epoll_fd < 0) {
14441 		err = -errno;
14442 		pr_warn("failed to create epoll instance: %s\n",
14443 			errstr(err));
14444 		goto error;
14445 	}
14446 
14447 	if (p->cpu_cnt > 0) {
14448 		pb->cpu_cnt = p->cpu_cnt;
14449 	} else {
14450 		pb->cpu_cnt = libbpf_num_possible_cpus();
14451 		if (pb->cpu_cnt < 0) {
14452 			err = pb->cpu_cnt;
14453 			goto error;
14454 		}
14455 		if (map.max_entries && map.max_entries < pb->cpu_cnt)
14456 			pb->cpu_cnt = map.max_entries;
14457 	}
14458 
14459 	pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
14460 	if (!pb->events) {
14461 		err = -ENOMEM;
14462 		pr_warn("failed to allocate events: out of memory\n");
14463 		goto error;
14464 	}
14465 	pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
14466 	if (!pb->cpu_bufs) {
14467 		err = -ENOMEM;
14468 		pr_warn("failed to allocate buffers: out of memory\n");
14469 		goto error;
14470 	}
14471 
14472 	err = parse_cpu_mask_file(online_cpus_file, &online, &n);
14473 	if (err) {
14474 		pr_warn("failed to get online CPU mask: %s\n", errstr(err));
14475 		goto error;
14476 	}
14477 
14478 	for (i = 0, j = 0; i < pb->cpu_cnt; i++) {
14479 		struct perf_cpu_buf *cpu_buf;
14480 		int cpu, map_key;
14481 
14482 		cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
14483 		map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
14484 
14485 		/* in case user didn't explicitly requested particular CPUs to
14486 		 * be attached to, skip offline/not present CPUs
14487 		 */
14488 		if (p->cpu_cnt <= 0 && (cpu >= n || !online[cpu]))
14489 			continue;
14490 
14491 		cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
14492 		if (IS_ERR(cpu_buf)) {
14493 			err = PTR_ERR(cpu_buf);
14494 			goto error;
14495 		}
14496 
14497 		pb->cpu_bufs[j] = cpu_buf;
14498 
14499 		err = bpf_map_update_elem(pb->map_fd, &map_key,
14500 					  &cpu_buf->fd, 0);
14501 		if (err) {
14502 			err = -errno;
14503 			pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
14504 				cpu, map_key, cpu_buf->fd,
14505 				errstr(err));
14506 			goto error;
14507 		}
14508 
14509 		pb->events[j].events = EPOLLIN;
14510 		pb->events[j].data.ptr = cpu_buf;
14511 		if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
14512 			      &pb->events[j]) < 0) {
14513 			err = -errno;
14514 			pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
14515 				cpu, cpu_buf->fd,
14516 				errstr(err));
14517 			goto error;
14518 		}
14519 		j++;
14520 	}
14521 	pb->cpu_cnt = j;
14522 	free(online);
14523 
14524 	return pb;
14525 
14526 error:
14527 	free(online);
14528 	if (pb)
14529 		perf_buffer__free(pb);
14530 	return ERR_PTR(err);
14531 }
14532 
14533 struct perf_sample_raw {
14534 	struct perf_event_header header;
14535 	uint32_t size;
14536 	char data[];
14537 };
14538 
14539 struct perf_sample_lost {
14540 	struct perf_event_header header;
14541 	uint64_t id;
14542 	uint64_t lost;
14543 	uint64_t sample_id;
14544 };
14545 
14546 static enum bpf_perf_event_ret
14547 perf_buffer__process_record(struct perf_event_header *e, void *ctx)
14548 {
14549 	struct perf_cpu_buf *cpu_buf = ctx;
14550 	struct perf_buffer *pb = cpu_buf->pb;
14551 	void *data = e;
14552 
14553 	/* user wants full control over parsing perf event */
14554 	if (pb->event_cb)
14555 		return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
14556 
14557 	switch (e->type) {
14558 	case PERF_RECORD_SAMPLE: {
14559 		struct perf_sample_raw *s = data;
14560 
14561 		if (pb->sample_cb)
14562 			pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
14563 		break;
14564 	}
14565 	case PERF_RECORD_LOST: {
14566 		struct perf_sample_lost *s = data;
14567 
14568 		if (pb->lost_cb)
14569 			pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
14570 		break;
14571 	}
14572 	default:
14573 		pr_warn("unknown perf sample type %d\n", e->type);
14574 		return LIBBPF_PERF_EVENT_ERROR;
14575 	}
14576 	return LIBBPF_PERF_EVENT_CONT;
14577 }
14578 
14579 static int perf_buffer__process_records(struct perf_buffer *pb,
14580 					struct perf_cpu_buf *cpu_buf)
14581 {
14582 	enum bpf_perf_event_ret ret;
14583 
14584 	ret = perf_event_read_simple(cpu_buf->base, pb->mmap_size,
14585 				     pb->page_size, &cpu_buf->buf,
14586 				     &cpu_buf->buf_size,
14587 				     perf_buffer__process_record, cpu_buf);
14588 	if (ret != LIBBPF_PERF_EVENT_CONT)
14589 		return ret;
14590 	return 0;
14591 }
14592 
14593 int perf_buffer__epoll_fd(const struct perf_buffer *pb)
14594 {
14595 	return pb->epoll_fd;
14596 }
14597 
14598 int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
14599 {
14600 	int i, cnt, err;
14601 
14602 	cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
14603 	if (cnt < 0)
14604 		return -errno;
14605 
14606 	for (i = 0; i < cnt; i++) {
14607 		struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
14608 
14609 		err = perf_buffer__process_records(pb, cpu_buf);
14610 		if (err) {
14611 			pr_warn("error while processing records: %s\n", errstr(err));
14612 			return libbpf_err(err);
14613 		}
14614 	}
14615 	return cnt;
14616 }
14617 
14618 /* Return number of PERF_EVENT_ARRAY map slots set up by this perf_buffer
14619  * manager.
14620  */
14621 size_t perf_buffer__buffer_cnt(const struct perf_buffer *pb)
14622 {
14623 	return pb->cpu_cnt;
14624 }
14625 
14626 /*
14627  * Return perf_event FD of a ring buffer in *buf_idx* slot of
14628  * PERF_EVENT_ARRAY BPF map. This FD can be polled for new data using
14629  * select()/poll()/epoll() Linux syscalls.
14630  */
14631 int perf_buffer__buffer_fd(const struct perf_buffer *pb, size_t buf_idx)
14632 {
14633 	struct perf_cpu_buf *cpu_buf;
14634 
14635 	if (buf_idx >= pb->cpu_cnt)
14636 		return libbpf_err(-EINVAL);
14637 
14638 	cpu_buf = pb->cpu_bufs[buf_idx];
14639 	if (!cpu_buf)
14640 		return libbpf_err(-ENOENT);
14641 
14642 	return cpu_buf->fd;
14643 }
14644 
14645 int perf_buffer__buffer(struct perf_buffer *pb, int buf_idx, void **buf, size_t *buf_size)
14646 {
14647 	struct perf_cpu_buf *cpu_buf;
14648 
14649 	if (buf_idx >= pb->cpu_cnt)
14650 		return libbpf_err(-EINVAL);
14651 
14652 	cpu_buf = pb->cpu_bufs[buf_idx];
14653 	if (!cpu_buf)
14654 		return libbpf_err(-ENOENT);
14655 
14656 	*buf = cpu_buf->base;
14657 	*buf_size = pb->mmap_size;
14658 	return 0;
14659 }
14660 
14661 /*
14662  * Consume data from perf ring buffer corresponding to slot *buf_idx* in
14663  * PERF_EVENT_ARRAY BPF map without waiting/polling. If there is no data to
14664  * consume, do nothing and return success.
14665  * Returns:
14666  *   - 0 on success;
14667  *   - <0 on failure.
14668  */
14669 int perf_buffer__consume_buffer(struct perf_buffer *pb, size_t buf_idx)
14670 {
14671 	struct perf_cpu_buf *cpu_buf;
14672 
14673 	if (buf_idx >= pb->cpu_cnt)
14674 		return libbpf_err(-EINVAL);
14675 
14676 	cpu_buf = pb->cpu_bufs[buf_idx];
14677 	if (!cpu_buf)
14678 		return libbpf_err(-ENOENT);
14679 
14680 	return perf_buffer__process_records(pb, cpu_buf);
14681 }
14682 
14683 int perf_buffer__consume(struct perf_buffer *pb)
14684 {
14685 	int i, err;
14686 
14687 	for (i = 0; i < pb->cpu_cnt; i++) {
14688 		struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
14689 
14690 		if (!cpu_buf)
14691 			continue;
14692 
14693 		err = perf_buffer__process_records(pb, cpu_buf);
14694 		if (err) {
14695 			pr_warn("perf_buffer: failed to process records in buffer #%d: %s\n",
14696 				i, errstr(err));
14697 			return libbpf_err(err);
14698 		}
14699 	}
14700 	return 0;
14701 }
14702 
14703 int bpf_program__set_attach_target(struct bpf_program *prog,
14704 				   int attach_prog_fd,
14705 				   const char *attach_func_name)
14706 {
14707 	int btf_obj_fd = 0, btf_id = 0, err;
14708 
14709 	if (!prog || attach_prog_fd < 0)
14710 		return libbpf_err(-EINVAL);
14711 
14712 	if (prog->obj->state >= OBJ_LOADED)
14713 		return libbpf_err(-EINVAL);
14714 
14715 	if (attach_prog_fd && !attach_func_name) {
14716 		/* Store attach_prog_fd. The BTF ID will be resolved later during
14717 		 * the normal object/program load phase.
14718 		 */
14719 		prog->attach_prog_fd = attach_prog_fd;
14720 		return 0;
14721 	}
14722 
14723 	if (attach_prog_fd) {
14724 		btf_id = libbpf_find_prog_btf_id(attach_func_name,
14725 						 attach_prog_fd, prog->obj->token_fd);
14726 		if (btf_id < 0)
14727 			return libbpf_err(btf_id);
14728 	} else {
14729 		if (!attach_func_name)
14730 			return libbpf_err(-EINVAL);
14731 
14732 		/* load btf_vmlinux, if not yet */
14733 		err = bpf_object__load_vmlinux_btf(prog->obj, true);
14734 		if (err)
14735 			return libbpf_err(err);
14736 		err = find_kernel_btf_id(prog->obj, attach_func_name,
14737 					 prog->expected_attach_type,
14738 					 &btf_obj_fd, &btf_id);
14739 		if (err)
14740 			return libbpf_err(err);
14741 	}
14742 
14743 	prog->attach_btf_id = btf_id;
14744 	prog->attach_btf_obj_fd = btf_obj_fd;
14745 	prog->attach_prog_fd = attach_prog_fd;
14746 	return 0;
14747 }
14748 
14749 int bpf_program__assoc_struct_ops(struct bpf_program *prog, struct bpf_map *map,
14750 				  struct bpf_prog_assoc_struct_ops_opts *opts)
14751 {
14752 	int prog_fd, map_fd;
14753 
14754 	prog_fd = bpf_program__fd(prog);
14755 	if (prog_fd < 0) {
14756 		pr_warn("prog '%s': can't associate BPF program without FD (was it loaded?)\n",
14757 			prog->name);
14758 		return libbpf_err(-EINVAL);
14759 	}
14760 
14761 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS) {
14762 		pr_warn("prog '%s': can't associate struct_ops program\n", prog->name);
14763 		return libbpf_err(-EINVAL);
14764 	}
14765 
14766 	map_fd = bpf_map__fd(map);
14767 	if (map_fd < 0) {
14768 		pr_warn("map '%s': can't associate BPF map without FD (was it created?)\n", map->name);
14769 		return libbpf_err(-EINVAL);
14770 	}
14771 
14772 	if (!bpf_map__is_struct_ops(map)) {
14773 		pr_warn("map '%s': can't associate non-struct_ops map\n", map->name);
14774 		return libbpf_err(-EINVAL);
14775 	}
14776 
14777 	return bpf_prog_assoc_struct_ops(prog_fd, map_fd, opts);
14778 }
14779 
14780 int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz)
14781 {
14782 	int err = 0, n, len, start, end = -1;
14783 	bool *tmp;
14784 
14785 	*mask = NULL;
14786 	*mask_sz = 0;
14787 
14788 	/* Each sub string separated by ',' has format \d+-\d+ or \d+ */
14789 	while (*s) {
14790 		if (*s == ',' || *s == '\n') {
14791 			s++;
14792 			continue;
14793 		}
14794 		n = sscanf(s, "%d%n-%d%n", &start, &len, &end, &len);
14795 		if (n <= 0 || n > 2) {
14796 			pr_warn("Failed to get CPU range %s: %d\n", s, n);
14797 			err = -EINVAL;
14798 			goto cleanup;
14799 		} else if (n == 1) {
14800 			end = start;
14801 		}
14802 		if (start < 0 || start > end) {
14803 			pr_warn("Invalid CPU range [%d,%d] in %s\n",
14804 				start, end, s);
14805 			err = -EINVAL;
14806 			goto cleanup;
14807 		}
14808 		tmp = realloc(*mask, end + 1);
14809 		if (!tmp) {
14810 			err = -ENOMEM;
14811 			goto cleanup;
14812 		}
14813 		*mask = tmp;
14814 		memset(tmp + *mask_sz, 0, start - *mask_sz);
14815 		memset(tmp + start, 1, end - start + 1);
14816 		*mask_sz = end + 1;
14817 		s += len;
14818 	}
14819 	if (!*mask_sz) {
14820 		pr_warn("Empty CPU range\n");
14821 		return -EINVAL;
14822 	}
14823 	return 0;
14824 cleanup:
14825 	free(*mask);
14826 	*mask = NULL;
14827 	return err;
14828 }
14829 
14830 int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz)
14831 {
14832 	int fd, err = 0, len;
14833 	char buf[128];
14834 
14835 	fd = open(fcpu, O_RDONLY | O_CLOEXEC);
14836 	if (fd < 0) {
14837 		err = -errno;
14838 		pr_warn("Failed to open cpu mask file %s: %s\n", fcpu, errstr(err));
14839 		return err;
14840 	}
14841 	len = read(fd, buf, sizeof(buf));
14842 	close(fd);
14843 	if (len <= 0) {
14844 		err = len ? -errno : -EINVAL;
14845 		pr_warn("Failed to read cpu mask from %s: %s\n", fcpu, errstr(err));
14846 		return err;
14847 	}
14848 	if (len >= sizeof(buf)) {
14849 		pr_warn("CPU mask is too big in file %s\n", fcpu);
14850 		return -E2BIG;
14851 	}
14852 	buf[len] = '\0';
14853 
14854 	return parse_cpu_mask_str(buf, mask, mask_sz);
14855 }
14856 
14857 int libbpf_num_possible_cpus(void)
14858 {
14859 	static const char *fcpu = "/sys/devices/system/cpu/possible";
14860 	static int cpus;
14861 	int err, n, i, tmp_cpus;
14862 	bool *mask;
14863 
14864 	tmp_cpus = READ_ONCE(cpus);
14865 	if (tmp_cpus > 0)
14866 		return tmp_cpus;
14867 
14868 	err = parse_cpu_mask_file(fcpu, &mask, &n);
14869 	if (err)
14870 		return libbpf_err(err);
14871 
14872 	tmp_cpus = 0;
14873 	for (i = 0; i < n; i++) {
14874 		if (mask[i])
14875 			tmp_cpus++;
14876 	}
14877 	free(mask);
14878 
14879 	WRITE_ONCE(cpus, tmp_cpus);
14880 	return tmp_cpus;
14881 }
14882 
14883 static int populate_skeleton_maps(const struct bpf_object *obj,
14884 				  struct bpf_map_skeleton *maps,
14885 				  size_t map_cnt, size_t map_skel_sz)
14886 {
14887 	int i;
14888 
14889 	for (i = 0; i < map_cnt; i++) {
14890 		struct bpf_map_skeleton *map_skel = (void *)maps + i * map_skel_sz;
14891 		struct bpf_map **map = map_skel->map;
14892 		const char *name = map_skel->name;
14893 		void **mmaped = map_skel->mmaped;
14894 
14895 		*map = bpf_object__find_map_by_name(obj, name);
14896 		if (!*map) {
14897 			pr_warn("failed to find skeleton map '%s'\n", name);
14898 			return -ESRCH;
14899 		}
14900 
14901 		/* externs shouldn't be pre-setup from user code */
14902 		if (mmaped && (*map)->libbpf_type != LIBBPF_MAP_KCONFIG)
14903 			*mmaped = (*map)->mmaped;
14904 	}
14905 	return 0;
14906 }
14907 
14908 static int populate_skeleton_progs(const struct bpf_object *obj,
14909 				   struct bpf_prog_skeleton *progs,
14910 				   size_t prog_cnt, size_t prog_skel_sz)
14911 {
14912 	int i;
14913 
14914 	for (i = 0; i < prog_cnt; i++) {
14915 		struct bpf_prog_skeleton *prog_skel = (void *)progs + i * prog_skel_sz;
14916 		struct bpf_program **prog = prog_skel->prog;
14917 		const char *name = prog_skel->name;
14918 
14919 		*prog = bpf_object__find_program_by_name(obj, name);
14920 		if (!*prog) {
14921 			pr_warn("failed to find skeleton program '%s'\n", name);
14922 			return -ESRCH;
14923 		}
14924 	}
14925 	return 0;
14926 }
14927 
14928 int bpf_object__open_skeleton(struct bpf_object_skeleton *s,
14929 			      const struct bpf_object_open_opts *opts)
14930 {
14931 	struct bpf_object *obj;
14932 	int err;
14933 
14934 	obj = bpf_object_open(NULL, s->data, s->data_sz, s->name, opts);
14935 	if (IS_ERR(obj)) {
14936 		err = PTR_ERR(obj);
14937 		pr_warn("failed to initialize skeleton BPF object '%s': %s\n",
14938 			s->name, errstr(err));
14939 		return libbpf_err(err);
14940 	}
14941 
14942 	*s->obj = obj;
14943 	err = populate_skeleton_maps(obj, s->maps, s->map_cnt, s->map_skel_sz);
14944 	if (err) {
14945 		pr_warn("failed to populate skeleton maps for '%s': %s\n", s->name, errstr(err));
14946 		return libbpf_err(err);
14947 	}
14948 
14949 	err = populate_skeleton_progs(obj, s->progs, s->prog_cnt, s->prog_skel_sz);
14950 	if (err) {
14951 		pr_warn("failed to populate skeleton progs for '%s': %s\n", s->name, errstr(err));
14952 		return libbpf_err(err);
14953 	}
14954 
14955 	return 0;
14956 }
14957 
14958 int bpf_object__open_subskeleton(struct bpf_object_subskeleton *s)
14959 {
14960 	int err, len, var_idx, i;
14961 	const char *var_name;
14962 	const struct bpf_map *map;
14963 	struct btf *btf;
14964 	__u32 map_type_id;
14965 	const struct btf_type *map_type, *var_type;
14966 	const struct bpf_var_skeleton *var_skel;
14967 	struct btf_var_secinfo *var;
14968 
14969 	if (!s->obj)
14970 		return libbpf_err(-EINVAL);
14971 
14972 	btf = bpf_object__btf(s->obj);
14973 	if (!btf) {
14974 		pr_warn("subskeletons require BTF at runtime (object %s)\n",
14975 			bpf_object__name(s->obj));
14976 		return libbpf_err(-errno);
14977 	}
14978 
14979 	err = populate_skeleton_maps(s->obj, s->maps, s->map_cnt, s->map_skel_sz);
14980 	if (err) {
14981 		pr_warn("failed to populate subskeleton maps: %s\n", errstr(err));
14982 		return libbpf_err(err);
14983 	}
14984 
14985 	err = populate_skeleton_progs(s->obj, s->progs, s->prog_cnt, s->prog_skel_sz);
14986 	if (err) {
14987 		pr_warn("failed to populate subskeleton maps: %s\n", errstr(err));
14988 		return libbpf_err(err);
14989 	}
14990 
14991 	for (var_idx = 0; var_idx < s->var_cnt; var_idx++) {
14992 		var_skel = (void *)s->vars + var_idx * s->var_skel_sz;
14993 		map = *var_skel->map;
14994 		map_type_id = bpf_map__btf_value_type_id(map);
14995 		map_type = btf__type_by_id(btf, map_type_id);
14996 
14997 		if (!btf_is_datasec(map_type)) {
14998 			pr_warn("type for map '%1$s' is not a datasec: %2$s\n",
14999 				bpf_map__name(map),
15000 				__btf_kind_str(btf_kind(map_type)));
15001 			return libbpf_err(-EINVAL);
15002 		}
15003 
15004 		len = btf_vlen(map_type);
15005 		var = btf_var_secinfos(map_type);
15006 		for (i = 0; i < len; i++, var++) {
15007 			var_type = btf__type_by_id(btf, var->type);
15008 			var_name = btf__name_by_offset(btf, var_type->name_off);
15009 			if (strcmp(var_name, var_skel->name) == 0) {
15010 				*var_skel->addr = map->mmaped + var->offset;
15011 				break;
15012 			}
15013 		}
15014 	}
15015 	return 0;
15016 }
15017 
15018 void bpf_object__destroy_subskeleton(struct bpf_object_subskeleton *s)
15019 {
15020 	if (!s)
15021 		return;
15022 	free(s->maps);
15023 	free(s->progs);
15024 	free(s->vars);
15025 	free(s);
15026 }
15027 
15028 int bpf_object__load_skeleton(struct bpf_object_skeleton *s)
15029 {
15030 	int i, err;
15031 
15032 	err = bpf_object__load(*s->obj);
15033 	if (err) {
15034 		pr_warn("failed to load BPF skeleton '%s': %s\n", s->name, errstr(err));
15035 		return libbpf_err(err);
15036 	}
15037 
15038 	for (i = 0; i < s->map_cnt; i++) {
15039 		struct bpf_map_skeleton *map_skel = (void *)s->maps + i * s->map_skel_sz;
15040 		struct bpf_map *map = *map_skel->map;
15041 
15042 		if (!map_skel->mmaped)
15043 			continue;
15044 
15045 		if (map->def.type == BPF_MAP_TYPE_ARENA)
15046 			*map_skel->mmaped = map->mmaped + map->obj->arena_data_off;
15047 		else
15048 			*map_skel->mmaped = map->mmaped;
15049 	}
15050 
15051 	return 0;
15052 }
15053 
15054 int bpf_object__attach_skeleton(struct bpf_object_skeleton *s)
15055 {
15056 	int i, err;
15057 
15058 	for (i = 0; i < s->prog_cnt; i++) {
15059 		struct bpf_prog_skeleton *prog_skel = (void *)s->progs + i * s->prog_skel_sz;
15060 		struct bpf_program *prog = *prog_skel->prog;
15061 		struct bpf_link **link = prog_skel->link;
15062 
15063 		if (!prog->autoload || !prog->autoattach)
15064 			continue;
15065 
15066 		/* auto-attaching not supported for this program */
15067 		if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
15068 			continue;
15069 
15070 		/* if user already set the link manually, don't attempt auto-attach */
15071 		if (*link)
15072 			continue;
15073 
15074 		err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, link);
15075 		if (err) {
15076 			pr_warn("prog '%s': failed to auto-attach: %s\n",
15077 				bpf_program__name(prog), errstr(err));
15078 			return libbpf_err(err);
15079 		}
15080 
15081 		/* It's possible that for some SEC() definitions auto-attach
15082 		 * is supported in some cases (e.g., if definition completely
15083 		 * specifies target information), but is not in other cases.
15084 		 * SEC("uprobe") is one such case. If user specified target
15085 		 * binary and function name, such BPF program can be
15086 		 * auto-attached. But if not, it shouldn't trigger skeleton's
15087 		 * attach to fail. It should just be skipped.
15088 		 * attach_fn signals such case with returning 0 (no error) and
15089 		 * setting link to NULL.
15090 		 */
15091 	}
15092 
15093 
15094 	for (i = 0; i < s->map_cnt; i++) {
15095 		struct bpf_map_skeleton *map_skel = (void *)s->maps + i * s->map_skel_sz;
15096 		struct bpf_map *map = *map_skel->map;
15097 		struct bpf_link **link;
15098 
15099 		if (!map->autocreate || !map->autoattach)
15100 			continue;
15101 
15102 		/* only struct_ops maps can be attached */
15103 		if (!bpf_map__is_struct_ops(map))
15104 			continue;
15105 
15106 		/* skeleton is created with earlier version of bpftool, notify user */
15107 		if (s->map_skel_sz < offsetofend(struct bpf_map_skeleton, link)) {
15108 			pr_warn("map '%s': BPF skeleton version is old, skipping map auto-attachment...\n",
15109 				bpf_map__name(map));
15110 			continue;
15111 		}
15112 
15113 		link = map_skel->link;
15114 		if (!link) {
15115 			pr_warn("map '%s': BPF map skeleton link is uninitialized\n",
15116 				bpf_map__name(map));
15117 			continue;
15118 		}
15119 
15120 		if (*link)
15121 			continue;
15122 
15123 		*link = bpf_map__attach_struct_ops(map);
15124 		if (!*link) {
15125 			err = -errno;
15126 			pr_warn("map '%s': failed to auto-attach: %s\n",
15127 				bpf_map__name(map), errstr(err));
15128 			return libbpf_err(err);
15129 		}
15130 	}
15131 
15132 	return 0;
15133 }
15134 
15135 void bpf_object__detach_skeleton(struct bpf_object_skeleton *s)
15136 {
15137 	int i;
15138 
15139 	for (i = 0; i < s->prog_cnt; i++) {
15140 		struct bpf_prog_skeleton *prog_skel = (void *)s->progs + i * s->prog_skel_sz;
15141 		struct bpf_link **link = prog_skel->link;
15142 
15143 		bpf_link__destroy(*link);
15144 		*link = NULL;
15145 	}
15146 
15147 	if (s->map_skel_sz < sizeof(struct bpf_map_skeleton))
15148 		return;
15149 
15150 	for (i = 0; i < s->map_cnt; i++) {
15151 		struct bpf_map_skeleton *map_skel = (void *)s->maps + i * s->map_skel_sz;
15152 		struct bpf_link **link = map_skel->link;
15153 
15154 		if (link) {
15155 			bpf_link__destroy(*link);
15156 			*link = NULL;
15157 		}
15158 	}
15159 }
15160 
15161 void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s)
15162 {
15163 	if (!s)
15164 		return;
15165 
15166 	bpf_object__detach_skeleton(s);
15167 	if (s->obj)
15168 		bpf_object__close(*s->obj);
15169 	free(s->maps);
15170 	free(s->progs);
15171 	free(s);
15172 }
15173