xref: /linux/tools/lib/bpf/libbpf.c (revision 73287fe228721b05690e671adbcccc6cf5435be6)
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 "str_error.h"
54 #include "libbpf_internal.h"
55 #include "hashmap.h"
56 #include "bpf_gen_internal.h"
57 #include "zip.h"
58 
59 #ifndef BPF_FS_MAGIC
60 #define BPF_FS_MAGIC		0xcafe4a11
61 #endif
62 
63 #define BPF_FS_DEFAULT_PATH "/sys/fs/bpf"
64 
65 #define BPF_INSN_SZ (sizeof(struct bpf_insn))
66 
67 /* vsprintf() in __base_pr() uses nonliteral format string. It may break
68  * compilation if user enables corresponding warning. Disable it explicitly.
69  */
70 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
71 
72 #define __printf(a, b)	__attribute__((format(printf, a, b)))
73 
74 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj);
75 static bool prog_is_subprog(const struct bpf_object *obj, const struct bpf_program *prog);
76 static int map_set_def_max_entries(struct bpf_map *map);
77 
78 static const char * const attach_type_name[] = {
79 	[BPF_CGROUP_INET_INGRESS]	= "cgroup_inet_ingress",
80 	[BPF_CGROUP_INET_EGRESS]	= "cgroup_inet_egress",
81 	[BPF_CGROUP_INET_SOCK_CREATE]	= "cgroup_inet_sock_create",
82 	[BPF_CGROUP_INET_SOCK_RELEASE]	= "cgroup_inet_sock_release",
83 	[BPF_CGROUP_SOCK_OPS]		= "cgroup_sock_ops",
84 	[BPF_CGROUP_DEVICE]		= "cgroup_device",
85 	[BPF_CGROUP_INET4_BIND]		= "cgroup_inet4_bind",
86 	[BPF_CGROUP_INET6_BIND]		= "cgroup_inet6_bind",
87 	[BPF_CGROUP_INET4_CONNECT]	= "cgroup_inet4_connect",
88 	[BPF_CGROUP_INET6_CONNECT]	= "cgroup_inet6_connect",
89 	[BPF_CGROUP_UNIX_CONNECT]       = "cgroup_unix_connect",
90 	[BPF_CGROUP_INET4_POST_BIND]	= "cgroup_inet4_post_bind",
91 	[BPF_CGROUP_INET6_POST_BIND]	= "cgroup_inet6_post_bind",
92 	[BPF_CGROUP_INET4_GETPEERNAME]	= "cgroup_inet4_getpeername",
93 	[BPF_CGROUP_INET6_GETPEERNAME]	= "cgroup_inet6_getpeername",
94 	[BPF_CGROUP_UNIX_GETPEERNAME]	= "cgroup_unix_getpeername",
95 	[BPF_CGROUP_INET4_GETSOCKNAME]	= "cgroup_inet4_getsockname",
96 	[BPF_CGROUP_INET6_GETSOCKNAME]	= "cgroup_inet6_getsockname",
97 	[BPF_CGROUP_UNIX_GETSOCKNAME]	= "cgroup_unix_getsockname",
98 	[BPF_CGROUP_UDP4_SENDMSG]	= "cgroup_udp4_sendmsg",
99 	[BPF_CGROUP_UDP6_SENDMSG]	= "cgroup_udp6_sendmsg",
100 	[BPF_CGROUP_UNIX_SENDMSG]	= "cgroup_unix_sendmsg",
101 	[BPF_CGROUP_SYSCTL]		= "cgroup_sysctl",
102 	[BPF_CGROUP_UDP4_RECVMSG]	= "cgroup_udp4_recvmsg",
103 	[BPF_CGROUP_UDP6_RECVMSG]	= "cgroup_udp6_recvmsg",
104 	[BPF_CGROUP_UNIX_RECVMSG]	= "cgroup_unix_recvmsg",
105 	[BPF_CGROUP_GETSOCKOPT]		= "cgroup_getsockopt",
106 	[BPF_CGROUP_SETSOCKOPT]		= "cgroup_setsockopt",
107 	[BPF_SK_SKB_STREAM_PARSER]	= "sk_skb_stream_parser",
108 	[BPF_SK_SKB_STREAM_VERDICT]	= "sk_skb_stream_verdict",
109 	[BPF_SK_SKB_VERDICT]		= "sk_skb_verdict",
110 	[BPF_SK_MSG_VERDICT]		= "sk_msg_verdict",
111 	[BPF_LIRC_MODE2]		= "lirc_mode2",
112 	[BPF_FLOW_DISSECTOR]		= "flow_dissector",
113 	[BPF_TRACE_RAW_TP]		= "trace_raw_tp",
114 	[BPF_TRACE_FENTRY]		= "trace_fentry",
115 	[BPF_TRACE_FEXIT]		= "trace_fexit",
116 	[BPF_MODIFY_RETURN]		= "modify_return",
117 	[BPF_LSM_MAC]			= "lsm_mac",
118 	[BPF_LSM_CGROUP]		= "lsm_cgroup",
119 	[BPF_SK_LOOKUP]			= "sk_lookup",
120 	[BPF_TRACE_ITER]		= "trace_iter",
121 	[BPF_XDP_DEVMAP]		= "xdp_devmap",
122 	[BPF_XDP_CPUMAP]		= "xdp_cpumap",
123 	[BPF_XDP]			= "xdp",
124 	[BPF_SK_REUSEPORT_SELECT]	= "sk_reuseport_select",
125 	[BPF_SK_REUSEPORT_SELECT_OR_MIGRATE]	= "sk_reuseport_select_or_migrate",
126 	[BPF_PERF_EVENT]		= "perf_event",
127 	[BPF_TRACE_KPROBE_MULTI]	= "trace_kprobe_multi",
128 	[BPF_STRUCT_OPS]		= "struct_ops",
129 	[BPF_NETFILTER]			= "netfilter",
130 	[BPF_TCX_INGRESS]		= "tcx_ingress",
131 	[BPF_TCX_EGRESS]		= "tcx_egress",
132 	[BPF_TRACE_UPROBE_MULTI]	= "trace_uprobe_multi",
133 	[BPF_NETKIT_PRIMARY]		= "netkit_primary",
134 	[BPF_NETKIT_PEER]		= "netkit_peer",
135 	[BPF_TRACE_KPROBE_SESSION]	= "trace_kprobe_session",
136 };
137 
138 static const char * const link_type_name[] = {
139 	[BPF_LINK_TYPE_UNSPEC]			= "unspec",
140 	[BPF_LINK_TYPE_RAW_TRACEPOINT]		= "raw_tracepoint",
141 	[BPF_LINK_TYPE_TRACING]			= "tracing",
142 	[BPF_LINK_TYPE_CGROUP]			= "cgroup",
143 	[BPF_LINK_TYPE_ITER]			= "iter",
144 	[BPF_LINK_TYPE_NETNS]			= "netns",
145 	[BPF_LINK_TYPE_XDP]			= "xdp",
146 	[BPF_LINK_TYPE_PERF_EVENT]		= "perf_event",
147 	[BPF_LINK_TYPE_KPROBE_MULTI]		= "kprobe_multi",
148 	[BPF_LINK_TYPE_STRUCT_OPS]		= "struct_ops",
149 	[BPF_LINK_TYPE_NETFILTER]		= "netfilter",
150 	[BPF_LINK_TYPE_TCX]			= "tcx",
151 	[BPF_LINK_TYPE_UPROBE_MULTI]		= "uprobe_multi",
152 	[BPF_LINK_TYPE_NETKIT]			= "netkit",
153 	[BPF_LINK_TYPE_SOCKMAP]			= "sockmap",
154 };
155 
156 static const char * const map_type_name[] = {
157 	[BPF_MAP_TYPE_UNSPEC]			= "unspec",
158 	[BPF_MAP_TYPE_HASH]			= "hash",
159 	[BPF_MAP_TYPE_ARRAY]			= "array",
160 	[BPF_MAP_TYPE_PROG_ARRAY]		= "prog_array",
161 	[BPF_MAP_TYPE_PERF_EVENT_ARRAY]		= "perf_event_array",
162 	[BPF_MAP_TYPE_PERCPU_HASH]		= "percpu_hash",
163 	[BPF_MAP_TYPE_PERCPU_ARRAY]		= "percpu_array",
164 	[BPF_MAP_TYPE_STACK_TRACE]		= "stack_trace",
165 	[BPF_MAP_TYPE_CGROUP_ARRAY]		= "cgroup_array",
166 	[BPF_MAP_TYPE_LRU_HASH]			= "lru_hash",
167 	[BPF_MAP_TYPE_LRU_PERCPU_HASH]		= "lru_percpu_hash",
168 	[BPF_MAP_TYPE_LPM_TRIE]			= "lpm_trie",
169 	[BPF_MAP_TYPE_ARRAY_OF_MAPS]		= "array_of_maps",
170 	[BPF_MAP_TYPE_HASH_OF_MAPS]		= "hash_of_maps",
171 	[BPF_MAP_TYPE_DEVMAP]			= "devmap",
172 	[BPF_MAP_TYPE_DEVMAP_HASH]		= "devmap_hash",
173 	[BPF_MAP_TYPE_SOCKMAP]			= "sockmap",
174 	[BPF_MAP_TYPE_CPUMAP]			= "cpumap",
175 	[BPF_MAP_TYPE_XSKMAP]			= "xskmap",
176 	[BPF_MAP_TYPE_SOCKHASH]			= "sockhash",
177 	[BPF_MAP_TYPE_CGROUP_STORAGE]		= "cgroup_storage",
178 	[BPF_MAP_TYPE_REUSEPORT_SOCKARRAY]	= "reuseport_sockarray",
179 	[BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE]	= "percpu_cgroup_storage",
180 	[BPF_MAP_TYPE_QUEUE]			= "queue",
181 	[BPF_MAP_TYPE_STACK]			= "stack",
182 	[BPF_MAP_TYPE_SK_STORAGE]		= "sk_storage",
183 	[BPF_MAP_TYPE_STRUCT_OPS]		= "struct_ops",
184 	[BPF_MAP_TYPE_RINGBUF]			= "ringbuf",
185 	[BPF_MAP_TYPE_INODE_STORAGE]		= "inode_storage",
186 	[BPF_MAP_TYPE_TASK_STORAGE]		= "task_storage",
187 	[BPF_MAP_TYPE_BLOOM_FILTER]		= "bloom_filter",
188 	[BPF_MAP_TYPE_USER_RINGBUF]             = "user_ringbuf",
189 	[BPF_MAP_TYPE_CGRP_STORAGE]		= "cgrp_storage",
190 	[BPF_MAP_TYPE_ARENA]			= "arena",
191 };
192 
193 static const char * const prog_type_name[] = {
194 	[BPF_PROG_TYPE_UNSPEC]			= "unspec",
195 	[BPF_PROG_TYPE_SOCKET_FILTER]		= "socket_filter",
196 	[BPF_PROG_TYPE_KPROBE]			= "kprobe",
197 	[BPF_PROG_TYPE_SCHED_CLS]		= "sched_cls",
198 	[BPF_PROG_TYPE_SCHED_ACT]		= "sched_act",
199 	[BPF_PROG_TYPE_TRACEPOINT]		= "tracepoint",
200 	[BPF_PROG_TYPE_XDP]			= "xdp",
201 	[BPF_PROG_TYPE_PERF_EVENT]		= "perf_event",
202 	[BPF_PROG_TYPE_CGROUP_SKB]		= "cgroup_skb",
203 	[BPF_PROG_TYPE_CGROUP_SOCK]		= "cgroup_sock",
204 	[BPF_PROG_TYPE_LWT_IN]			= "lwt_in",
205 	[BPF_PROG_TYPE_LWT_OUT]			= "lwt_out",
206 	[BPF_PROG_TYPE_LWT_XMIT]		= "lwt_xmit",
207 	[BPF_PROG_TYPE_SOCK_OPS]		= "sock_ops",
208 	[BPF_PROG_TYPE_SK_SKB]			= "sk_skb",
209 	[BPF_PROG_TYPE_CGROUP_DEVICE]		= "cgroup_device",
210 	[BPF_PROG_TYPE_SK_MSG]			= "sk_msg",
211 	[BPF_PROG_TYPE_RAW_TRACEPOINT]		= "raw_tracepoint",
212 	[BPF_PROG_TYPE_CGROUP_SOCK_ADDR]	= "cgroup_sock_addr",
213 	[BPF_PROG_TYPE_LWT_SEG6LOCAL]		= "lwt_seg6local",
214 	[BPF_PROG_TYPE_LIRC_MODE2]		= "lirc_mode2",
215 	[BPF_PROG_TYPE_SK_REUSEPORT]		= "sk_reuseport",
216 	[BPF_PROG_TYPE_FLOW_DISSECTOR]		= "flow_dissector",
217 	[BPF_PROG_TYPE_CGROUP_SYSCTL]		= "cgroup_sysctl",
218 	[BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE]	= "raw_tracepoint_writable",
219 	[BPF_PROG_TYPE_CGROUP_SOCKOPT]		= "cgroup_sockopt",
220 	[BPF_PROG_TYPE_TRACING]			= "tracing",
221 	[BPF_PROG_TYPE_STRUCT_OPS]		= "struct_ops",
222 	[BPF_PROG_TYPE_EXT]			= "ext",
223 	[BPF_PROG_TYPE_LSM]			= "lsm",
224 	[BPF_PROG_TYPE_SK_LOOKUP]		= "sk_lookup",
225 	[BPF_PROG_TYPE_SYSCALL]			= "syscall",
226 	[BPF_PROG_TYPE_NETFILTER]		= "netfilter",
227 };
228 
229 static int __base_pr(enum libbpf_print_level level, const char *format,
230 		     va_list args)
231 {
232 	const char *env_var = "LIBBPF_LOG_LEVEL";
233 	static enum libbpf_print_level min_level = LIBBPF_INFO;
234 	static bool initialized;
235 
236 	if (!initialized) {
237 		char *verbosity;
238 
239 		initialized = true;
240 		verbosity = getenv(env_var);
241 		if (verbosity) {
242 			if (strcasecmp(verbosity, "warn") == 0)
243 				min_level = LIBBPF_WARN;
244 			else if (strcasecmp(verbosity, "debug") == 0)
245 				min_level = LIBBPF_DEBUG;
246 			else if (strcasecmp(verbosity, "info") == 0)
247 				min_level = LIBBPF_INFO;
248 			else
249 				fprintf(stderr, "libbpf: unrecognized '%s' envvar value: '%s', should be one of 'warn', 'debug', or 'info'.\n",
250 					env_var, verbosity);
251 		}
252 	}
253 
254 	/* if too verbose, skip logging  */
255 	if (level > min_level)
256 		return 0;
257 
258 	return vfprintf(stderr, format, args);
259 }
260 
261 static libbpf_print_fn_t __libbpf_pr = __base_pr;
262 
263 libbpf_print_fn_t libbpf_set_print(libbpf_print_fn_t fn)
264 {
265 	libbpf_print_fn_t old_print_fn;
266 
267 	old_print_fn = __atomic_exchange_n(&__libbpf_pr, fn, __ATOMIC_RELAXED);
268 
269 	return old_print_fn;
270 }
271 
272 __printf(2, 3)
273 void libbpf_print(enum libbpf_print_level level, const char *format, ...)
274 {
275 	va_list args;
276 	int old_errno;
277 	libbpf_print_fn_t print_fn;
278 
279 	print_fn = __atomic_load_n(&__libbpf_pr, __ATOMIC_RELAXED);
280 	if (!print_fn)
281 		return;
282 
283 	old_errno = errno;
284 
285 	va_start(args, format);
286 	__libbpf_pr(level, format, args);
287 	va_end(args);
288 
289 	errno = old_errno;
290 }
291 
292 static void pr_perm_msg(int err)
293 {
294 	struct rlimit limit;
295 	char buf[100];
296 
297 	if (err != -EPERM || geteuid() != 0)
298 		return;
299 
300 	err = getrlimit(RLIMIT_MEMLOCK, &limit);
301 	if (err)
302 		return;
303 
304 	if (limit.rlim_cur == RLIM_INFINITY)
305 		return;
306 
307 	if (limit.rlim_cur < 1024)
308 		snprintf(buf, sizeof(buf), "%zu bytes", (size_t)limit.rlim_cur);
309 	else if (limit.rlim_cur < 1024*1024)
310 		snprintf(buf, sizeof(buf), "%.1f KiB", (double)limit.rlim_cur / 1024);
311 	else
312 		snprintf(buf, sizeof(buf), "%.1f MiB", (double)limit.rlim_cur / (1024*1024));
313 
314 	pr_warn("permission error while running as root; try raising 'ulimit -l'? current value: %s\n",
315 		buf);
316 }
317 
318 #define STRERR_BUFSIZE  128
319 
320 /* Copied from tools/perf/util/util.h */
321 #ifndef zfree
322 # define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
323 #endif
324 
325 #ifndef zclose
326 # define zclose(fd) ({			\
327 	int ___err = 0;			\
328 	if ((fd) >= 0)			\
329 		___err = close((fd));	\
330 	fd = -1;			\
331 	___err; })
332 #endif
333 
334 static inline __u64 ptr_to_u64(const void *ptr)
335 {
336 	return (__u64) (unsigned long) ptr;
337 }
338 
339 int libbpf_set_strict_mode(enum libbpf_strict_mode mode)
340 {
341 	/* as of v1.0 libbpf_set_strict_mode() is a no-op */
342 	return 0;
343 }
344 
345 __u32 libbpf_major_version(void)
346 {
347 	return LIBBPF_MAJOR_VERSION;
348 }
349 
350 __u32 libbpf_minor_version(void)
351 {
352 	return LIBBPF_MINOR_VERSION;
353 }
354 
355 const char *libbpf_version_string(void)
356 {
357 #define __S(X) #X
358 #define _S(X) __S(X)
359 	return  "v" _S(LIBBPF_MAJOR_VERSION) "." _S(LIBBPF_MINOR_VERSION);
360 #undef _S
361 #undef __S
362 }
363 
364 enum reloc_type {
365 	RELO_LD64,
366 	RELO_CALL,
367 	RELO_DATA,
368 	RELO_EXTERN_LD64,
369 	RELO_EXTERN_CALL,
370 	RELO_SUBPROG_ADDR,
371 	RELO_CORE,
372 };
373 
374 struct reloc_desc {
375 	enum reloc_type type;
376 	int insn_idx;
377 	union {
378 		const struct bpf_core_relo *core_relo; /* used when type == RELO_CORE */
379 		struct {
380 			int map_idx;
381 			int sym_off;
382 			int ext_idx;
383 		};
384 	};
385 };
386 
387 /* stored as sec_def->cookie for all libbpf-supported SEC()s */
388 enum sec_def_flags {
389 	SEC_NONE = 0,
390 	/* expected_attach_type is optional, if kernel doesn't support that */
391 	SEC_EXP_ATTACH_OPT = 1,
392 	/* legacy, only used by libbpf_get_type_names() and
393 	 * libbpf_attach_type_by_name(), not used by libbpf itself at all.
394 	 * This used to be associated with cgroup (and few other) BPF programs
395 	 * that were attachable through BPF_PROG_ATTACH command. Pretty
396 	 * meaningless nowadays, though.
397 	 */
398 	SEC_ATTACHABLE = 2,
399 	SEC_ATTACHABLE_OPT = SEC_ATTACHABLE | SEC_EXP_ATTACH_OPT,
400 	/* attachment target is specified through BTF ID in either kernel or
401 	 * other BPF program's BTF object
402 	 */
403 	SEC_ATTACH_BTF = 4,
404 	/* BPF program type allows sleeping/blocking in kernel */
405 	SEC_SLEEPABLE = 8,
406 	/* BPF program support non-linear XDP buffer */
407 	SEC_XDP_FRAGS = 16,
408 	/* Setup proper attach type for usdt probes. */
409 	SEC_USDT = 32,
410 };
411 
412 struct bpf_sec_def {
413 	char *sec;
414 	enum bpf_prog_type prog_type;
415 	enum bpf_attach_type expected_attach_type;
416 	long cookie;
417 	int handler_id;
418 
419 	libbpf_prog_setup_fn_t prog_setup_fn;
420 	libbpf_prog_prepare_load_fn_t prog_prepare_load_fn;
421 	libbpf_prog_attach_fn_t prog_attach_fn;
422 };
423 
424 /*
425  * bpf_prog should be a better name but it has been used in
426  * linux/filter.h.
427  */
428 struct bpf_program {
429 	char *name;
430 	char *sec_name;
431 	size_t sec_idx;
432 	const struct bpf_sec_def *sec_def;
433 	/* this program's instruction offset (in number of instructions)
434 	 * within its containing ELF section
435 	 */
436 	size_t sec_insn_off;
437 	/* number of original instructions in ELF section belonging to this
438 	 * program, not taking into account subprogram instructions possible
439 	 * appended later during relocation
440 	 */
441 	size_t sec_insn_cnt;
442 	/* Offset (in number of instructions) of the start of instruction
443 	 * belonging to this BPF program  within its containing main BPF
444 	 * program. For the entry-point (main) BPF program, this is always
445 	 * zero. For a sub-program, this gets reset before each of main BPF
446 	 * programs are processed and relocated and is used to determined
447 	 * whether sub-program was already appended to the main program, and
448 	 * if yes, at which instruction offset.
449 	 */
450 	size_t sub_insn_off;
451 
452 	/* instructions that belong to BPF program; insns[0] is located at
453 	 * sec_insn_off instruction within its ELF section in ELF file, so
454 	 * when mapping ELF file instruction index to the local instruction,
455 	 * one needs to subtract sec_insn_off; and vice versa.
456 	 */
457 	struct bpf_insn *insns;
458 	/* actual number of instruction in this BPF program's image; for
459 	 * entry-point BPF programs this includes the size of main program
460 	 * itself plus all the used sub-programs, appended at the end
461 	 */
462 	size_t insns_cnt;
463 
464 	struct reloc_desc *reloc_desc;
465 	int nr_reloc;
466 
467 	/* BPF verifier log settings */
468 	char *log_buf;
469 	size_t log_size;
470 	__u32 log_level;
471 
472 	struct bpf_object *obj;
473 
474 	int fd;
475 	bool autoload;
476 	bool autoattach;
477 	bool sym_global;
478 	bool mark_btf_static;
479 	enum bpf_prog_type type;
480 	enum bpf_attach_type expected_attach_type;
481 	int exception_cb_idx;
482 
483 	int prog_ifindex;
484 	__u32 attach_btf_obj_fd;
485 	__u32 attach_btf_id;
486 	__u32 attach_prog_fd;
487 
488 	void *func_info;
489 	__u32 func_info_rec_size;
490 	__u32 func_info_cnt;
491 
492 	void *line_info;
493 	__u32 line_info_rec_size;
494 	__u32 line_info_cnt;
495 	__u32 prog_flags;
496 };
497 
498 struct bpf_struct_ops {
499 	const char *tname;
500 	const struct btf_type *type;
501 	struct bpf_program **progs;
502 	__u32 *kern_func_off;
503 	/* e.g. struct tcp_congestion_ops in bpf_prog's btf format */
504 	void *data;
505 	/* e.g. struct bpf_struct_ops_tcp_congestion_ops in
506 	 *      btf_vmlinux's format.
507 	 * struct bpf_struct_ops_tcp_congestion_ops {
508 	 *	[... some other kernel fields ...]
509 	 *	struct tcp_congestion_ops data;
510 	 * }
511 	 * kern_vdata-size == sizeof(struct bpf_struct_ops_tcp_congestion_ops)
512 	 * bpf_map__init_kern_struct_ops() will populate the "kern_vdata"
513 	 * from "data".
514 	 */
515 	void *kern_vdata;
516 	__u32 type_id;
517 };
518 
519 #define DATA_SEC ".data"
520 #define BSS_SEC ".bss"
521 #define RODATA_SEC ".rodata"
522 #define KCONFIG_SEC ".kconfig"
523 #define KSYMS_SEC ".ksyms"
524 #define STRUCT_OPS_SEC ".struct_ops"
525 #define STRUCT_OPS_LINK_SEC ".struct_ops.link"
526 #define ARENA_SEC ".addr_space.1"
527 
528 enum libbpf_map_type {
529 	LIBBPF_MAP_UNSPEC,
530 	LIBBPF_MAP_DATA,
531 	LIBBPF_MAP_BSS,
532 	LIBBPF_MAP_RODATA,
533 	LIBBPF_MAP_KCONFIG,
534 };
535 
536 struct bpf_map_def {
537 	unsigned int type;
538 	unsigned int key_size;
539 	unsigned int value_size;
540 	unsigned int max_entries;
541 	unsigned int map_flags;
542 };
543 
544 struct bpf_map {
545 	struct bpf_object *obj;
546 	char *name;
547 	/* real_name is defined for special internal maps (.rodata*,
548 	 * .data*, .bss, .kconfig) and preserves their original ELF section
549 	 * name. This is important to be able to find corresponding BTF
550 	 * DATASEC information.
551 	 */
552 	char *real_name;
553 	int fd;
554 	int sec_idx;
555 	size_t sec_offset;
556 	int map_ifindex;
557 	int inner_map_fd;
558 	struct bpf_map_def def;
559 	__u32 numa_node;
560 	__u32 btf_var_idx;
561 	int mod_btf_fd;
562 	__u32 btf_key_type_id;
563 	__u32 btf_value_type_id;
564 	__u32 btf_vmlinux_value_type_id;
565 	enum libbpf_map_type libbpf_type;
566 	void *mmaped;
567 	struct bpf_struct_ops *st_ops;
568 	struct bpf_map *inner_map;
569 	void **init_slots;
570 	int init_slots_sz;
571 	char *pin_path;
572 	bool pinned;
573 	bool reused;
574 	bool autocreate;
575 	__u64 map_extra;
576 };
577 
578 enum extern_type {
579 	EXT_UNKNOWN,
580 	EXT_KCFG,
581 	EXT_KSYM,
582 };
583 
584 enum kcfg_type {
585 	KCFG_UNKNOWN,
586 	KCFG_CHAR,
587 	KCFG_BOOL,
588 	KCFG_INT,
589 	KCFG_TRISTATE,
590 	KCFG_CHAR_ARR,
591 };
592 
593 struct extern_desc {
594 	enum extern_type type;
595 	int sym_idx;
596 	int btf_id;
597 	int sec_btf_id;
598 	const char *name;
599 	char *essent_name;
600 	bool is_set;
601 	bool is_weak;
602 	union {
603 		struct {
604 			enum kcfg_type type;
605 			int sz;
606 			int align;
607 			int data_off;
608 			bool is_signed;
609 		} kcfg;
610 		struct {
611 			unsigned long long addr;
612 
613 			/* target btf_id of the corresponding kernel var. */
614 			int kernel_btf_obj_fd;
615 			int kernel_btf_id;
616 
617 			/* local btf_id of the ksym extern's type. */
618 			__u32 type_id;
619 			/* BTF fd index to be patched in for insn->off, this is
620 			 * 0 for vmlinux BTF, index in obj->fd_array for module
621 			 * BTF
622 			 */
623 			__s16 btf_fd_idx;
624 		} ksym;
625 	};
626 };
627 
628 struct module_btf {
629 	struct btf *btf;
630 	char *name;
631 	__u32 id;
632 	int fd;
633 	int fd_array_idx;
634 };
635 
636 enum sec_type {
637 	SEC_UNUSED = 0,
638 	SEC_RELO,
639 	SEC_BSS,
640 	SEC_DATA,
641 	SEC_RODATA,
642 	SEC_ST_OPS,
643 };
644 
645 struct elf_sec_desc {
646 	enum sec_type sec_type;
647 	Elf64_Shdr *shdr;
648 	Elf_Data *data;
649 };
650 
651 struct elf_state {
652 	int fd;
653 	const void *obj_buf;
654 	size_t obj_buf_sz;
655 	Elf *elf;
656 	Elf64_Ehdr *ehdr;
657 	Elf_Data *symbols;
658 	Elf_Data *arena_data;
659 	size_t shstrndx; /* section index for section name strings */
660 	size_t strtabidx;
661 	struct elf_sec_desc *secs;
662 	size_t sec_cnt;
663 	int btf_maps_shndx;
664 	__u32 btf_maps_sec_btf_id;
665 	int text_shndx;
666 	int symbols_shndx;
667 	bool has_st_ops;
668 	int arena_data_shndx;
669 };
670 
671 struct usdt_manager;
672 
673 struct bpf_object {
674 	char name[BPF_OBJ_NAME_LEN];
675 	char license[64];
676 	__u32 kern_version;
677 
678 	struct bpf_program *programs;
679 	size_t nr_programs;
680 	struct bpf_map *maps;
681 	size_t nr_maps;
682 	size_t maps_cap;
683 
684 	char *kconfig;
685 	struct extern_desc *externs;
686 	int nr_extern;
687 	int kconfig_map_idx;
688 
689 	bool loaded;
690 	bool has_subcalls;
691 	bool has_rodata;
692 
693 	struct bpf_gen *gen_loader;
694 
695 	/* Information when doing ELF related work. Only valid if efile.elf is not NULL */
696 	struct elf_state efile;
697 
698 	struct btf *btf;
699 	struct btf_ext *btf_ext;
700 
701 	/* Parse and load BTF vmlinux if any of the programs in the object need
702 	 * it at load time.
703 	 */
704 	struct btf *btf_vmlinux;
705 	/* Path to the custom BTF to be used for BPF CO-RE relocations as an
706 	 * override for vmlinux BTF.
707 	 */
708 	char *btf_custom_path;
709 	/* vmlinux BTF override for CO-RE relocations */
710 	struct btf *btf_vmlinux_override;
711 	/* Lazily initialized kernel module BTFs */
712 	struct module_btf *btf_modules;
713 	bool btf_modules_loaded;
714 	size_t btf_module_cnt;
715 	size_t btf_module_cap;
716 
717 	/* optional log settings passed to BPF_BTF_LOAD and BPF_PROG_LOAD commands */
718 	char *log_buf;
719 	size_t log_size;
720 	__u32 log_level;
721 
722 	int *fd_array;
723 	size_t fd_array_cap;
724 	size_t fd_array_cnt;
725 
726 	struct usdt_manager *usdt_man;
727 
728 	struct bpf_map *arena_map;
729 	void *arena_data;
730 	size_t arena_data_sz;
731 
732 	struct kern_feature_cache *feat_cache;
733 	char *token_path;
734 	int token_fd;
735 
736 	char path[];
737 };
738 
739 static const char *elf_sym_str(const struct bpf_object *obj, size_t off);
740 static const char *elf_sec_str(const struct bpf_object *obj, size_t off);
741 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx);
742 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name);
743 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn);
744 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn);
745 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn);
746 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx);
747 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx);
748 
749 void bpf_program__unload(struct bpf_program *prog)
750 {
751 	if (!prog)
752 		return;
753 
754 	zclose(prog->fd);
755 
756 	zfree(&prog->func_info);
757 	zfree(&prog->line_info);
758 }
759 
760 static void bpf_program__exit(struct bpf_program *prog)
761 {
762 	if (!prog)
763 		return;
764 
765 	bpf_program__unload(prog);
766 	zfree(&prog->name);
767 	zfree(&prog->sec_name);
768 	zfree(&prog->insns);
769 	zfree(&prog->reloc_desc);
770 
771 	prog->nr_reloc = 0;
772 	prog->insns_cnt = 0;
773 	prog->sec_idx = -1;
774 }
775 
776 static bool insn_is_subprog_call(const struct bpf_insn *insn)
777 {
778 	return BPF_CLASS(insn->code) == BPF_JMP &&
779 	       BPF_OP(insn->code) == BPF_CALL &&
780 	       BPF_SRC(insn->code) == BPF_K &&
781 	       insn->src_reg == BPF_PSEUDO_CALL &&
782 	       insn->dst_reg == 0 &&
783 	       insn->off == 0;
784 }
785 
786 static bool is_call_insn(const struct bpf_insn *insn)
787 {
788 	return insn->code == (BPF_JMP | BPF_CALL);
789 }
790 
791 static bool insn_is_pseudo_func(struct bpf_insn *insn)
792 {
793 	return is_ldimm64_insn(insn) && insn->src_reg == BPF_PSEUDO_FUNC;
794 }
795 
796 static int
797 bpf_object__init_prog(struct bpf_object *obj, struct bpf_program *prog,
798 		      const char *name, size_t sec_idx, const char *sec_name,
799 		      size_t sec_off, void *insn_data, size_t insn_data_sz)
800 {
801 	if (insn_data_sz == 0 || insn_data_sz % BPF_INSN_SZ || sec_off % BPF_INSN_SZ) {
802 		pr_warn("sec '%s': corrupted program '%s', offset %zu, size %zu\n",
803 			sec_name, name, sec_off, insn_data_sz);
804 		return -EINVAL;
805 	}
806 
807 	memset(prog, 0, sizeof(*prog));
808 	prog->obj = obj;
809 
810 	prog->sec_idx = sec_idx;
811 	prog->sec_insn_off = sec_off / BPF_INSN_SZ;
812 	prog->sec_insn_cnt = insn_data_sz / BPF_INSN_SZ;
813 	/* insns_cnt can later be increased by appending used subprograms */
814 	prog->insns_cnt = prog->sec_insn_cnt;
815 
816 	prog->type = BPF_PROG_TYPE_UNSPEC;
817 	prog->fd = -1;
818 	prog->exception_cb_idx = -1;
819 
820 	/* libbpf's convention for SEC("?abc...") is that it's just like
821 	 * SEC("abc...") but the corresponding bpf_program starts out with
822 	 * autoload set to false.
823 	 */
824 	if (sec_name[0] == '?') {
825 		prog->autoload = false;
826 		/* from now on forget there was ? in section name */
827 		sec_name++;
828 	} else {
829 		prog->autoload = true;
830 	}
831 
832 	prog->autoattach = true;
833 
834 	/* inherit object's log_level */
835 	prog->log_level = obj->log_level;
836 
837 	prog->sec_name = strdup(sec_name);
838 	if (!prog->sec_name)
839 		goto errout;
840 
841 	prog->name = strdup(name);
842 	if (!prog->name)
843 		goto errout;
844 
845 	prog->insns = malloc(insn_data_sz);
846 	if (!prog->insns)
847 		goto errout;
848 	memcpy(prog->insns, insn_data, insn_data_sz);
849 
850 	return 0;
851 errout:
852 	pr_warn("sec '%s': failed to allocate memory for prog '%s'\n", sec_name, name);
853 	bpf_program__exit(prog);
854 	return -ENOMEM;
855 }
856 
857 static int
858 bpf_object__add_programs(struct bpf_object *obj, Elf_Data *sec_data,
859 			 const char *sec_name, int sec_idx)
860 {
861 	Elf_Data *symbols = obj->efile.symbols;
862 	struct bpf_program *prog, *progs;
863 	void *data = sec_data->d_buf;
864 	size_t sec_sz = sec_data->d_size, sec_off, prog_sz, nr_syms;
865 	int nr_progs, err, i;
866 	const char *name;
867 	Elf64_Sym *sym;
868 
869 	progs = obj->programs;
870 	nr_progs = obj->nr_programs;
871 	nr_syms = symbols->d_size / sizeof(Elf64_Sym);
872 
873 	for (i = 0; i < nr_syms; i++) {
874 		sym = elf_sym_by_idx(obj, i);
875 
876 		if (sym->st_shndx != sec_idx)
877 			continue;
878 		if (ELF64_ST_TYPE(sym->st_info) != STT_FUNC)
879 			continue;
880 
881 		prog_sz = sym->st_size;
882 		sec_off = sym->st_value;
883 
884 		name = elf_sym_str(obj, sym->st_name);
885 		if (!name) {
886 			pr_warn("sec '%s': failed to get symbol name for offset %zu\n",
887 				sec_name, sec_off);
888 			return -LIBBPF_ERRNO__FORMAT;
889 		}
890 
891 		if (sec_off + prog_sz > sec_sz) {
892 			pr_warn("sec '%s': program at offset %zu crosses section boundary\n",
893 				sec_name, sec_off);
894 			return -LIBBPF_ERRNO__FORMAT;
895 		}
896 
897 		if (sec_idx != obj->efile.text_shndx && ELF64_ST_BIND(sym->st_info) == STB_LOCAL) {
898 			pr_warn("sec '%s': program '%s' is static and not supported\n", sec_name, name);
899 			return -ENOTSUP;
900 		}
901 
902 		pr_debug("sec '%s': found program '%s' at insn offset %zu (%zu bytes), code size %zu insns (%zu bytes)\n",
903 			 sec_name, name, sec_off / BPF_INSN_SZ, sec_off, prog_sz / BPF_INSN_SZ, prog_sz);
904 
905 		progs = libbpf_reallocarray(progs, nr_progs + 1, sizeof(*progs));
906 		if (!progs) {
907 			/*
908 			 * In this case the original obj->programs
909 			 * is still valid, so don't need special treat for
910 			 * bpf_close_object().
911 			 */
912 			pr_warn("sec '%s': failed to alloc memory for new program '%s'\n",
913 				sec_name, name);
914 			return -ENOMEM;
915 		}
916 		obj->programs = progs;
917 
918 		prog = &progs[nr_progs];
919 
920 		err = bpf_object__init_prog(obj, prog, name, sec_idx, sec_name,
921 					    sec_off, data + sec_off, prog_sz);
922 		if (err)
923 			return err;
924 
925 		if (ELF64_ST_BIND(sym->st_info) != STB_LOCAL)
926 			prog->sym_global = true;
927 
928 		/* if function is a global/weak symbol, but has restricted
929 		 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF FUNC
930 		 * as static to enable more permissive BPF verification mode
931 		 * with more outside context available to BPF verifier
932 		 */
933 		if (prog->sym_global && (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
934 		    || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL))
935 			prog->mark_btf_static = true;
936 
937 		nr_progs++;
938 		obj->nr_programs = nr_progs;
939 	}
940 
941 	return 0;
942 }
943 
944 static const struct btf_member *
945 find_member_by_offset(const struct btf_type *t, __u32 bit_offset)
946 {
947 	struct btf_member *m;
948 	int i;
949 
950 	for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
951 		if (btf_member_bit_offset(t, i) == bit_offset)
952 			return m;
953 	}
954 
955 	return NULL;
956 }
957 
958 static const struct btf_member *
959 find_member_by_name(const struct btf *btf, const struct btf_type *t,
960 		    const char *name)
961 {
962 	struct btf_member *m;
963 	int i;
964 
965 	for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
966 		if (!strcmp(btf__name_by_offset(btf, m->name_off), name))
967 			return m;
968 	}
969 
970 	return NULL;
971 }
972 
973 static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
974 			    __u16 kind, struct btf **res_btf,
975 			    struct module_btf **res_mod_btf);
976 
977 #define STRUCT_OPS_VALUE_PREFIX "bpf_struct_ops_"
978 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
979 				   const char *name, __u32 kind);
980 
981 static int
982 find_struct_ops_kern_types(struct bpf_object *obj, const char *tname_raw,
983 			   struct module_btf **mod_btf,
984 			   const struct btf_type **type, __u32 *type_id,
985 			   const struct btf_type **vtype, __u32 *vtype_id,
986 			   const struct btf_member **data_member)
987 {
988 	const struct btf_type *kern_type, *kern_vtype;
989 	const struct btf_member *kern_data_member;
990 	struct btf *btf;
991 	__s32 kern_vtype_id, kern_type_id;
992 	char tname[256];
993 	__u32 i;
994 
995 	snprintf(tname, sizeof(tname), "%.*s",
996 		 (int)bpf_core_essential_name_len(tname_raw), tname_raw);
997 
998 	kern_type_id = find_ksym_btf_id(obj, tname, BTF_KIND_STRUCT,
999 					&btf, mod_btf);
1000 	if (kern_type_id < 0) {
1001 		pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n",
1002 			tname);
1003 		return kern_type_id;
1004 	}
1005 	kern_type = btf__type_by_id(btf, kern_type_id);
1006 
1007 	/* Find the corresponding "map_value" type that will be used
1008 	 * in map_update(BPF_MAP_TYPE_STRUCT_OPS).  For example,
1009 	 * find "struct bpf_struct_ops_tcp_congestion_ops" from the
1010 	 * btf_vmlinux.
1011 	 */
1012 	kern_vtype_id = find_btf_by_prefix_kind(btf, STRUCT_OPS_VALUE_PREFIX,
1013 						tname, BTF_KIND_STRUCT);
1014 	if (kern_vtype_id < 0) {
1015 		pr_warn("struct_ops init_kern: struct %s%s is not found in kernel BTF\n",
1016 			STRUCT_OPS_VALUE_PREFIX, tname);
1017 		return kern_vtype_id;
1018 	}
1019 	kern_vtype = btf__type_by_id(btf, kern_vtype_id);
1020 
1021 	/* Find "struct tcp_congestion_ops" from
1022 	 * struct bpf_struct_ops_tcp_congestion_ops {
1023 	 *	[ ... ]
1024 	 *	struct tcp_congestion_ops data;
1025 	 * }
1026 	 */
1027 	kern_data_member = btf_members(kern_vtype);
1028 	for (i = 0; i < btf_vlen(kern_vtype); i++, kern_data_member++) {
1029 		if (kern_data_member->type == kern_type_id)
1030 			break;
1031 	}
1032 	if (i == btf_vlen(kern_vtype)) {
1033 		pr_warn("struct_ops init_kern: struct %s data is not found in struct %s%s\n",
1034 			tname, STRUCT_OPS_VALUE_PREFIX, tname);
1035 		return -EINVAL;
1036 	}
1037 
1038 	*type = kern_type;
1039 	*type_id = kern_type_id;
1040 	*vtype = kern_vtype;
1041 	*vtype_id = kern_vtype_id;
1042 	*data_member = kern_data_member;
1043 
1044 	return 0;
1045 }
1046 
1047 static bool bpf_map__is_struct_ops(const struct bpf_map *map)
1048 {
1049 	return map->def.type == BPF_MAP_TYPE_STRUCT_OPS;
1050 }
1051 
1052 static bool is_valid_st_ops_program(struct bpf_object *obj,
1053 				    const struct bpf_program *prog)
1054 {
1055 	int i;
1056 
1057 	for (i = 0; i < obj->nr_programs; i++) {
1058 		if (&obj->programs[i] == prog)
1059 			return prog->type == BPF_PROG_TYPE_STRUCT_OPS;
1060 	}
1061 
1062 	return false;
1063 }
1064 
1065 /* For each struct_ops program P, referenced from some struct_ops map M,
1066  * enable P.autoload if there are Ms for which M.autocreate is true,
1067  * disable P.autoload if for all Ms M.autocreate is false.
1068  * Don't change P.autoload for programs that are not referenced from any maps.
1069  */
1070 static int bpf_object_adjust_struct_ops_autoload(struct bpf_object *obj)
1071 {
1072 	struct bpf_program *prog, *slot_prog;
1073 	struct bpf_map *map;
1074 	int i, j, k, vlen;
1075 
1076 	for (i = 0; i < obj->nr_programs; ++i) {
1077 		int should_load = false;
1078 		int use_cnt = 0;
1079 
1080 		prog = &obj->programs[i];
1081 		if (prog->type != BPF_PROG_TYPE_STRUCT_OPS)
1082 			continue;
1083 
1084 		for (j = 0; j < obj->nr_maps; ++j) {
1085 			map = &obj->maps[j];
1086 			if (!bpf_map__is_struct_ops(map))
1087 				continue;
1088 
1089 			vlen = btf_vlen(map->st_ops->type);
1090 			for (k = 0; k < vlen; ++k) {
1091 				slot_prog = map->st_ops->progs[k];
1092 				if (prog != slot_prog)
1093 					continue;
1094 
1095 				use_cnt++;
1096 				if (map->autocreate)
1097 					should_load = true;
1098 			}
1099 		}
1100 		if (use_cnt)
1101 			prog->autoload = should_load;
1102 	}
1103 
1104 	return 0;
1105 }
1106 
1107 /* Init the map's fields that depend on kern_btf */
1108 static int bpf_map__init_kern_struct_ops(struct bpf_map *map)
1109 {
1110 	const struct btf_member *member, *kern_member, *kern_data_member;
1111 	const struct btf_type *type, *kern_type, *kern_vtype;
1112 	__u32 i, kern_type_id, kern_vtype_id, kern_data_off;
1113 	struct bpf_object *obj = map->obj;
1114 	const struct btf *btf = obj->btf;
1115 	struct bpf_struct_ops *st_ops;
1116 	const struct btf *kern_btf;
1117 	struct module_btf *mod_btf;
1118 	void *data, *kern_data;
1119 	const char *tname;
1120 	int err;
1121 
1122 	st_ops = map->st_ops;
1123 	type = st_ops->type;
1124 	tname = st_ops->tname;
1125 	err = find_struct_ops_kern_types(obj, tname, &mod_btf,
1126 					 &kern_type, &kern_type_id,
1127 					 &kern_vtype, &kern_vtype_id,
1128 					 &kern_data_member);
1129 	if (err)
1130 		return err;
1131 
1132 	kern_btf = mod_btf ? mod_btf->btf : obj->btf_vmlinux;
1133 
1134 	pr_debug("struct_ops init_kern %s: type_id:%u kern_type_id:%u kern_vtype_id:%u\n",
1135 		 map->name, st_ops->type_id, kern_type_id, kern_vtype_id);
1136 
1137 	map->mod_btf_fd = mod_btf ? mod_btf->fd : -1;
1138 	map->def.value_size = kern_vtype->size;
1139 	map->btf_vmlinux_value_type_id = kern_vtype_id;
1140 
1141 	st_ops->kern_vdata = calloc(1, kern_vtype->size);
1142 	if (!st_ops->kern_vdata)
1143 		return -ENOMEM;
1144 
1145 	data = st_ops->data;
1146 	kern_data_off = kern_data_member->offset / 8;
1147 	kern_data = st_ops->kern_vdata + kern_data_off;
1148 
1149 	member = btf_members(type);
1150 	for (i = 0; i < btf_vlen(type); i++, member++) {
1151 		const struct btf_type *mtype, *kern_mtype;
1152 		__u32 mtype_id, kern_mtype_id;
1153 		void *mdata, *kern_mdata;
1154 		struct bpf_program *prog;
1155 		__s64 msize, kern_msize;
1156 		__u32 moff, kern_moff;
1157 		__u32 kern_member_idx;
1158 		const char *mname;
1159 
1160 		mname = btf__name_by_offset(btf, member->name_off);
1161 		moff = member->offset / 8;
1162 		mdata = data + moff;
1163 		msize = btf__resolve_size(btf, member->type);
1164 		if (msize < 0) {
1165 			pr_warn("struct_ops init_kern %s: failed to resolve the size of member %s\n",
1166 				map->name, mname);
1167 			return msize;
1168 		}
1169 
1170 		kern_member = find_member_by_name(kern_btf, kern_type, mname);
1171 		if (!kern_member) {
1172 			if (!libbpf_is_mem_zeroed(mdata, msize)) {
1173 				pr_warn("struct_ops init_kern %s: Cannot find member %s in kernel BTF\n",
1174 					map->name, mname);
1175 				return -ENOTSUP;
1176 			}
1177 
1178 			if (st_ops->progs[i]) {
1179 				/* If we had declaratively set struct_ops callback, we need to
1180 				 * force its autoload to false, because it doesn't have
1181 				 * a chance of succeeding from POV of the current struct_ops map.
1182 				 * If this program is still referenced somewhere else, though,
1183 				 * then bpf_object_adjust_struct_ops_autoload() will update its
1184 				 * autoload accordingly.
1185 				 */
1186 				st_ops->progs[i]->autoload = false;
1187 				st_ops->progs[i] = NULL;
1188 			}
1189 
1190 			/* Skip all-zero/NULL fields if they are not present in the kernel BTF */
1191 			pr_info("struct_ops %s: member %s not found in kernel, skipping it as it's set to zero\n",
1192 				map->name, mname);
1193 			continue;
1194 		}
1195 
1196 		kern_member_idx = kern_member - btf_members(kern_type);
1197 		if (btf_member_bitfield_size(type, i) ||
1198 		    btf_member_bitfield_size(kern_type, kern_member_idx)) {
1199 			pr_warn("struct_ops init_kern %s: bitfield %s is not supported\n",
1200 				map->name, mname);
1201 			return -ENOTSUP;
1202 		}
1203 
1204 		kern_moff = kern_member->offset / 8;
1205 		kern_mdata = kern_data + kern_moff;
1206 
1207 		mtype = skip_mods_and_typedefs(btf, member->type, &mtype_id);
1208 		kern_mtype = skip_mods_and_typedefs(kern_btf, kern_member->type,
1209 						    &kern_mtype_id);
1210 		if (BTF_INFO_KIND(mtype->info) !=
1211 		    BTF_INFO_KIND(kern_mtype->info)) {
1212 			pr_warn("struct_ops init_kern %s: Unmatched member type %s %u != %u(kernel)\n",
1213 				map->name, mname, BTF_INFO_KIND(mtype->info),
1214 				BTF_INFO_KIND(kern_mtype->info));
1215 			return -ENOTSUP;
1216 		}
1217 
1218 		if (btf_is_ptr(mtype)) {
1219 			prog = *(void **)mdata;
1220 			/* just like for !kern_member case above, reset declaratively
1221 			 * set (at compile time) program's autload to false,
1222 			 * if user replaced it with another program or NULL
1223 			 */
1224 			if (st_ops->progs[i] && st_ops->progs[i] != prog)
1225 				st_ops->progs[i]->autoload = false;
1226 
1227 			/* Update the value from the shadow type */
1228 			st_ops->progs[i] = prog;
1229 			if (!prog)
1230 				continue;
1231 
1232 			if (!is_valid_st_ops_program(obj, prog)) {
1233 				pr_warn("struct_ops init_kern %s: member %s is not a struct_ops program\n",
1234 					map->name, mname);
1235 				return -ENOTSUP;
1236 			}
1237 
1238 			kern_mtype = skip_mods_and_typedefs(kern_btf,
1239 							    kern_mtype->type,
1240 							    &kern_mtype_id);
1241 
1242 			/* mtype->type must be a func_proto which was
1243 			 * guaranteed in bpf_object__collect_st_ops_relos(),
1244 			 * so only check kern_mtype for func_proto here.
1245 			 */
1246 			if (!btf_is_func_proto(kern_mtype)) {
1247 				pr_warn("struct_ops init_kern %s: kernel member %s is not a func ptr\n",
1248 					map->name, mname);
1249 				return -ENOTSUP;
1250 			}
1251 
1252 			if (mod_btf)
1253 				prog->attach_btf_obj_fd = mod_btf->fd;
1254 
1255 			/* if we haven't yet processed this BPF program, record proper
1256 			 * attach_btf_id and member_idx
1257 			 */
1258 			if (!prog->attach_btf_id) {
1259 				prog->attach_btf_id = kern_type_id;
1260 				prog->expected_attach_type = kern_member_idx;
1261 			}
1262 
1263 			/* struct_ops BPF prog can be re-used between multiple
1264 			 * .struct_ops & .struct_ops.link as long as it's the
1265 			 * same struct_ops struct definition and the same
1266 			 * function pointer field
1267 			 */
1268 			if (prog->attach_btf_id != kern_type_id) {
1269 				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",
1270 					map->name, mname, prog->name, prog->sec_name, prog->type,
1271 					prog->attach_btf_id, kern_type_id);
1272 				return -EINVAL;
1273 			}
1274 			if (prog->expected_attach_type != kern_member_idx) {
1275 				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",
1276 					map->name, mname, prog->name, prog->sec_name, prog->type,
1277 					prog->expected_attach_type, kern_member_idx);
1278 				return -EINVAL;
1279 			}
1280 
1281 			st_ops->kern_func_off[i] = kern_data_off + kern_moff;
1282 
1283 			pr_debug("struct_ops init_kern %s: func ptr %s is set to prog %s from data(+%u) to kern_data(+%u)\n",
1284 				 map->name, mname, prog->name, moff,
1285 				 kern_moff);
1286 
1287 			continue;
1288 		}
1289 
1290 		kern_msize = btf__resolve_size(kern_btf, kern_mtype_id);
1291 		if (kern_msize < 0 || msize != kern_msize) {
1292 			pr_warn("struct_ops init_kern %s: Error in size of member %s: %zd != %zd(kernel)\n",
1293 				map->name, mname, (ssize_t)msize,
1294 				(ssize_t)kern_msize);
1295 			return -ENOTSUP;
1296 		}
1297 
1298 		pr_debug("struct_ops init_kern %s: copy %s %u bytes from data(+%u) to kern_data(+%u)\n",
1299 			 map->name, mname, (unsigned int)msize,
1300 			 moff, kern_moff);
1301 		memcpy(kern_mdata, mdata, msize);
1302 	}
1303 
1304 	return 0;
1305 }
1306 
1307 static int bpf_object__init_kern_struct_ops_maps(struct bpf_object *obj)
1308 {
1309 	struct bpf_map *map;
1310 	size_t i;
1311 	int err;
1312 
1313 	for (i = 0; i < obj->nr_maps; i++) {
1314 		map = &obj->maps[i];
1315 
1316 		if (!bpf_map__is_struct_ops(map))
1317 			continue;
1318 
1319 		if (!map->autocreate)
1320 			continue;
1321 
1322 		err = bpf_map__init_kern_struct_ops(map);
1323 		if (err)
1324 			return err;
1325 	}
1326 
1327 	return 0;
1328 }
1329 
1330 static int init_struct_ops_maps(struct bpf_object *obj, const char *sec_name,
1331 				int shndx, Elf_Data *data)
1332 {
1333 	const struct btf_type *type, *datasec;
1334 	const struct btf_var_secinfo *vsi;
1335 	struct bpf_struct_ops *st_ops;
1336 	const char *tname, *var_name;
1337 	__s32 type_id, datasec_id;
1338 	const struct btf *btf;
1339 	struct bpf_map *map;
1340 	__u32 i;
1341 
1342 	if (shndx == -1)
1343 		return 0;
1344 
1345 	btf = obj->btf;
1346 	datasec_id = btf__find_by_name_kind(btf, sec_name,
1347 					    BTF_KIND_DATASEC);
1348 	if (datasec_id < 0) {
1349 		pr_warn("struct_ops init: DATASEC %s not found\n",
1350 			sec_name);
1351 		return -EINVAL;
1352 	}
1353 
1354 	datasec = btf__type_by_id(btf, datasec_id);
1355 	vsi = btf_var_secinfos(datasec);
1356 	for (i = 0; i < btf_vlen(datasec); i++, vsi++) {
1357 		type = btf__type_by_id(obj->btf, vsi->type);
1358 		var_name = btf__name_by_offset(obj->btf, type->name_off);
1359 
1360 		type_id = btf__resolve_type(obj->btf, vsi->type);
1361 		if (type_id < 0) {
1362 			pr_warn("struct_ops init: Cannot resolve var type_id %u in DATASEC %s\n",
1363 				vsi->type, sec_name);
1364 			return -EINVAL;
1365 		}
1366 
1367 		type = btf__type_by_id(obj->btf, type_id);
1368 		tname = btf__name_by_offset(obj->btf, type->name_off);
1369 		if (!tname[0]) {
1370 			pr_warn("struct_ops init: anonymous type is not supported\n");
1371 			return -ENOTSUP;
1372 		}
1373 		if (!btf_is_struct(type)) {
1374 			pr_warn("struct_ops init: %s is not a struct\n", tname);
1375 			return -EINVAL;
1376 		}
1377 
1378 		map = bpf_object__add_map(obj);
1379 		if (IS_ERR(map))
1380 			return PTR_ERR(map);
1381 
1382 		map->sec_idx = shndx;
1383 		map->sec_offset = vsi->offset;
1384 		map->name = strdup(var_name);
1385 		if (!map->name)
1386 			return -ENOMEM;
1387 		map->btf_value_type_id = type_id;
1388 
1389 		/* Follow same convention as for programs autoload:
1390 		 * SEC("?.struct_ops") means map is not created by default.
1391 		 */
1392 		if (sec_name[0] == '?') {
1393 			map->autocreate = false;
1394 			/* from now on forget there was ? in section name */
1395 			sec_name++;
1396 		}
1397 
1398 		map->def.type = BPF_MAP_TYPE_STRUCT_OPS;
1399 		map->def.key_size = sizeof(int);
1400 		map->def.value_size = type->size;
1401 		map->def.max_entries = 1;
1402 		map->def.map_flags = strcmp(sec_name, STRUCT_OPS_LINK_SEC) == 0 ? BPF_F_LINK : 0;
1403 
1404 		map->st_ops = calloc(1, sizeof(*map->st_ops));
1405 		if (!map->st_ops)
1406 			return -ENOMEM;
1407 		st_ops = map->st_ops;
1408 		st_ops->data = malloc(type->size);
1409 		st_ops->progs = calloc(btf_vlen(type), sizeof(*st_ops->progs));
1410 		st_ops->kern_func_off = malloc(btf_vlen(type) *
1411 					       sizeof(*st_ops->kern_func_off));
1412 		if (!st_ops->data || !st_ops->progs || !st_ops->kern_func_off)
1413 			return -ENOMEM;
1414 
1415 		if (vsi->offset + type->size > data->d_size) {
1416 			pr_warn("struct_ops init: var %s is beyond the end of DATASEC %s\n",
1417 				var_name, sec_name);
1418 			return -EINVAL;
1419 		}
1420 
1421 		memcpy(st_ops->data,
1422 		       data->d_buf + vsi->offset,
1423 		       type->size);
1424 		st_ops->tname = tname;
1425 		st_ops->type = type;
1426 		st_ops->type_id = type_id;
1427 
1428 		pr_debug("struct_ops init: struct %s(type_id=%u) %s found at offset %u\n",
1429 			 tname, type_id, var_name, vsi->offset);
1430 	}
1431 
1432 	return 0;
1433 }
1434 
1435 static int bpf_object_init_struct_ops(struct bpf_object *obj)
1436 {
1437 	const char *sec_name;
1438 	int sec_idx, err;
1439 
1440 	for (sec_idx = 0; sec_idx < obj->efile.sec_cnt; ++sec_idx) {
1441 		struct elf_sec_desc *desc = &obj->efile.secs[sec_idx];
1442 
1443 		if (desc->sec_type != SEC_ST_OPS)
1444 			continue;
1445 
1446 		sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1447 		if (!sec_name)
1448 			return -LIBBPF_ERRNO__FORMAT;
1449 
1450 		err = init_struct_ops_maps(obj, sec_name, sec_idx, desc->data);
1451 		if (err)
1452 			return err;
1453 	}
1454 
1455 	return 0;
1456 }
1457 
1458 static struct bpf_object *bpf_object__new(const char *path,
1459 					  const void *obj_buf,
1460 					  size_t obj_buf_sz,
1461 					  const char *obj_name)
1462 {
1463 	struct bpf_object *obj;
1464 	char *end;
1465 
1466 	obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
1467 	if (!obj) {
1468 		pr_warn("alloc memory failed for %s\n", path);
1469 		return ERR_PTR(-ENOMEM);
1470 	}
1471 
1472 	strcpy(obj->path, path);
1473 	if (obj_name) {
1474 		libbpf_strlcpy(obj->name, obj_name, sizeof(obj->name));
1475 	} else {
1476 		/* Using basename() GNU version which doesn't modify arg. */
1477 		libbpf_strlcpy(obj->name, basename((void *)path), sizeof(obj->name));
1478 		end = strchr(obj->name, '.');
1479 		if (end)
1480 			*end = 0;
1481 	}
1482 
1483 	obj->efile.fd = -1;
1484 	/*
1485 	 * Caller of this function should also call
1486 	 * bpf_object__elf_finish() after data collection to return
1487 	 * obj_buf to user. If not, we should duplicate the buffer to
1488 	 * avoid user freeing them before elf finish.
1489 	 */
1490 	obj->efile.obj_buf = obj_buf;
1491 	obj->efile.obj_buf_sz = obj_buf_sz;
1492 	obj->efile.btf_maps_shndx = -1;
1493 	obj->kconfig_map_idx = -1;
1494 
1495 	obj->kern_version = get_kernel_version();
1496 	obj->loaded = false;
1497 
1498 	return obj;
1499 }
1500 
1501 static void bpf_object__elf_finish(struct bpf_object *obj)
1502 {
1503 	if (!obj->efile.elf)
1504 		return;
1505 
1506 	elf_end(obj->efile.elf);
1507 	obj->efile.elf = NULL;
1508 	obj->efile.symbols = NULL;
1509 	obj->efile.arena_data = NULL;
1510 
1511 	zfree(&obj->efile.secs);
1512 	obj->efile.sec_cnt = 0;
1513 	zclose(obj->efile.fd);
1514 	obj->efile.obj_buf = NULL;
1515 	obj->efile.obj_buf_sz = 0;
1516 }
1517 
1518 static int bpf_object__elf_init(struct bpf_object *obj)
1519 {
1520 	Elf64_Ehdr *ehdr;
1521 	int err = 0;
1522 	Elf *elf;
1523 
1524 	if (obj->efile.elf) {
1525 		pr_warn("elf: init internal error\n");
1526 		return -LIBBPF_ERRNO__LIBELF;
1527 	}
1528 
1529 	if (obj->efile.obj_buf_sz > 0) {
1530 		/* obj_buf should have been validated by bpf_object__open_mem(). */
1531 		elf = elf_memory((char *)obj->efile.obj_buf, obj->efile.obj_buf_sz);
1532 	} else {
1533 		obj->efile.fd = open(obj->path, O_RDONLY | O_CLOEXEC);
1534 		if (obj->efile.fd < 0) {
1535 			char errmsg[STRERR_BUFSIZE], *cp;
1536 
1537 			err = -errno;
1538 			cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
1539 			pr_warn("elf: failed to open %s: %s\n", obj->path, cp);
1540 			return err;
1541 		}
1542 
1543 		elf = elf_begin(obj->efile.fd, ELF_C_READ_MMAP, NULL);
1544 	}
1545 
1546 	if (!elf) {
1547 		pr_warn("elf: failed to open %s as ELF file: %s\n", obj->path, elf_errmsg(-1));
1548 		err = -LIBBPF_ERRNO__LIBELF;
1549 		goto errout;
1550 	}
1551 
1552 	obj->efile.elf = elf;
1553 
1554 	if (elf_kind(elf) != ELF_K_ELF) {
1555 		err = -LIBBPF_ERRNO__FORMAT;
1556 		pr_warn("elf: '%s' is not a proper ELF object\n", obj->path);
1557 		goto errout;
1558 	}
1559 
1560 	if (gelf_getclass(elf) != ELFCLASS64) {
1561 		err = -LIBBPF_ERRNO__FORMAT;
1562 		pr_warn("elf: '%s' is not a 64-bit ELF object\n", obj->path);
1563 		goto errout;
1564 	}
1565 
1566 	obj->efile.ehdr = ehdr = elf64_getehdr(elf);
1567 	if (!obj->efile.ehdr) {
1568 		pr_warn("elf: failed to get ELF header from %s: %s\n", obj->path, elf_errmsg(-1));
1569 		err = -LIBBPF_ERRNO__FORMAT;
1570 		goto errout;
1571 	}
1572 
1573 	if (elf_getshdrstrndx(elf, &obj->efile.shstrndx)) {
1574 		pr_warn("elf: failed to get section names section index for %s: %s\n",
1575 			obj->path, elf_errmsg(-1));
1576 		err = -LIBBPF_ERRNO__FORMAT;
1577 		goto errout;
1578 	}
1579 
1580 	/* ELF is corrupted/truncated, avoid calling elf_strptr. */
1581 	if (!elf_rawdata(elf_getscn(elf, obj->efile.shstrndx), NULL)) {
1582 		pr_warn("elf: failed to get section names strings from %s: %s\n",
1583 			obj->path, elf_errmsg(-1));
1584 		err = -LIBBPF_ERRNO__FORMAT;
1585 		goto errout;
1586 	}
1587 
1588 	/* Old LLVM set e_machine to EM_NONE */
1589 	if (ehdr->e_type != ET_REL || (ehdr->e_machine && ehdr->e_machine != EM_BPF)) {
1590 		pr_warn("elf: %s is not a valid eBPF object file\n", obj->path);
1591 		err = -LIBBPF_ERRNO__FORMAT;
1592 		goto errout;
1593 	}
1594 
1595 	return 0;
1596 errout:
1597 	bpf_object__elf_finish(obj);
1598 	return err;
1599 }
1600 
1601 static int bpf_object__check_endianness(struct bpf_object *obj)
1602 {
1603 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1604 	if (obj->efile.ehdr->e_ident[EI_DATA] == ELFDATA2LSB)
1605 		return 0;
1606 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
1607 	if (obj->efile.ehdr->e_ident[EI_DATA] == ELFDATA2MSB)
1608 		return 0;
1609 #else
1610 # error "Unrecognized __BYTE_ORDER__"
1611 #endif
1612 	pr_warn("elf: endianness mismatch in %s.\n", obj->path);
1613 	return -LIBBPF_ERRNO__ENDIAN;
1614 }
1615 
1616 static int
1617 bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
1618 {
1619 	if (!data) {
1620 		pr_warn("invalid license section in %s\n", obj->path);
1621 		return -LIBBPF_ERRNO__FORMAT;
1622 	}
1623 	/* libbpf_strlcpy() only copies first N - 1 bytes, so size + 1 won't
1624 	 * go over allowed ELF data section buffer
1625 	 */
1626 	libbpf_strlcpy(obj->license, data, min(size + 1, sizeof(obj->license)));
1627 	pr_debug("license of %s is %s\n", obj->path, obj->license);
1628 	return 0;
1629 }
1630 
1631 static int
1632 bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
1633 {
1634 	__u32 kver;
1635 
1636 	if (!data || size != sizeof(kver)) {
1637 		pr_warn("invalid kver section in %s\n", obj->path);
1638 		return -LIBBPF_ERRNO__FORMAT;
1639 	}
1640 	memcpy(&kver, data, sizeof(kver));
1641 	obj->kern_version = kver;
1642 	pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
1643 	return 0;
1644 }
1645 
1646 static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
1647 {
1648 	if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
1649 	    type == BPF_MAP_TYPE_HASH_OF_MAPS)
1650 		return true;
1651 	return false;
1652 }
1653 
1654 static int find_elf_sec_sz(const struct bpf_object *obj, const char *name, __u32 *size)
1655 {
1656 	Elf_Data *data;
1657 	Elf_Scn *scn;
1658 
1659 	if (!name)
1660 		return -EINVAL;
1661 
1662 	scn = elf_sec_by_name(obj, name);
1663 	data = elf_sec_data(obj, scn);
1664 	if (data) {
1665 		*size = data->d_size;
1666 		return 0; /* found it */
1667 	}
1668 
1669 	return -ENOENT;
1670 }
1671 
1672 static Elf64_Sym *find_elf_var_sym(const struct bpf_object *obj, const char *name)
1673 {
1674 	Elf_Data *symbols = obj->efile.symbols;
1675 	const char *sname;
1676 	size_t si;
1677 
1678 	for (si = 0; si < symbols->d_size / sizeof(Elf64_Sym); si++) {
1679 		Elf64_Sym *sym = elf_sym_by_idx(obj, si);
1680 
1681 		if (ELF64_ST_TYPE(sym->st_info) != STT_OBJECT)
1682 			continue;
1683 
1684 		if (ELF64_ST_BIND(sym->st_info) != STB_GLOBAL &&
1685 		    ELF64_ST_BIND(sym->st_info) != STB_WEAK)
1686 			continue;
1687 
1688 		sname = elf_sym_str(obj, sym->st_name);
1689 		if (!sname) {
1690 			pr_warn("failed to get sym name string for var %s\n", name);
1691 			return ERR_PTR(-EIO);
1692 		}
1693 		if (strcmp(name, sname) == 0)
1694 			return sym;
1695 	}
1696 
1697 	return ERR_PTR(-ENOENT);
1698 }
1699 
1700 /* Some versions of Android don't provide memfd_create() in their libc
1701  * implementation, so avoid complications and just go straight to Linux
1702  * syscall.
1703  */
1704 static int sys_memfd_create(const char *name, unsigned flags)
1705 {
1706 	return syscall(__NR_memfd_create, name, flags);
1707 }
1708 
1709 #ifndef MFD_CLOEXEC
1710 #define MFD_CLOEXEC 0x0001U
1711 #endif
1712 
1713 static int create_placeholder_fd(void)
1714 {
1715 	int fd;
1716 
1717 	fd = ensure_good_fd(sys_memfd_create("libbpf-placeholder-fd", MFD_CLOEXEC));
1718 	if (fd < 0)
1719 		return -errno;
1720 	return fd;
1721 }
1722 
1723 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
1724 {
1725 	struct bpf_map *map;
1726 	int err;
1727 
1728 	err = libbpf_ensure_mem((void **)&obj->maps, &obj->maps_cap,
1729 				sizeof(*obj->maps), obj->nr_maps + 1);
1730 	if (err)
1731 		return ERR_PTR(err);
1732 
1733 	map = &obj->maps[obj->nr_maps++];
1734 	map->obj = obj;
1735 	/* Preallocate map FD without actually creating BPF map just yet.
1736 	 * These map FD "placeholders" will be reused later without changing
1737 	 * FD value when map is actually created in the kernel.
1738 	 *
1739 	 * This is useful to be able to perform BPF program relocations
1740 	 * without having to create BPF maps before that step. This allows us
1741 	 * to finalize and load BTF very late in BPF object's loading phase,
1742 	 * right before BPF maps have to be created and BPF programs have to
1743 	 * be loaded. By having these map FD placeholders we can perform all
1744 	 * the sanitizations, relocations, and any other adjustments before we
1745 	 * start creating actual BPF kernel objects (BTF, maps, progs).
1746 	 */
1747 	map->fd = create_placeholder_fd();
1748 	if (map->fd < 0)
1749 		return ERR_PTR(map->fd);
1750 	map->inner_map_fd = -1;
1751 	map->autocreate = true;
1752 
1753 	return map;
1754 }
1755 
1756 static size_t array_map_mmap_sz(unsigned int value_sz, unsigned int max_entries)
1757 {
1758 	const long page_sz = sysconf(_SC_PAGE_SIZE);
1759 	size_t map_sz;
1760 
1761 	map_sz = (size_t)roundup(value_sz, 8) * max_entries;
1762 	map_sz = roundup(map_sz, page_sz);
1763 	return map_sz;
1764 }
1765 
1766 static size_t bpf_map_mmap_sz(const struct bpf_map *map)
1767 {
1768 	const long page_sz = sysconf(_SC_PAGE_SIZE);
1769 
1770 	switch (map->def.type) {
1771 	case BPF_MAP_TYPE_ARRAY:
1772 		return array_map_mmap_sz(map->def.value_size, map->def.max_entries);
1773 	case BPF_MAP_TYPE_ARENA:
1774 		return page_sz * map->def.max_entries;
1775 	default:
1776 		return 0; /* not supported */
1777 	}
1778 }
1779 
1780 static int bpf_map_mmap_resize(struct bpf_map *map, size_t old_sz, size_t new_sz)
1781 {
1782 	void *mmaped;
1783 
1784 	if (!map->mmaped)
1785 		return -EINVAL;
1786 
1787 	if (old_sz == new_sz)
1788 		return 0;
1789 
1790 	mmaped = mmap(NULL, new_sz, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1791 	if (mmaped == MAP_FAILED)
1792 		return -errno;
1793 
1794 	memcpy(mmaped, map->mmaped, min(old_sz, new_sz));
1795 	munmap(map->mmaped, old_sz);
1796 	map->mmaped = mmaped;
1797 	return 0;
1798 }
1799 
1800 static char *internal_map_name(struct bpf_object *obj, const char *real_name)
1801 {
1802 	char map_name[BPF_OBJ_NAME_LEN], *p;
1803 	int pfx_len, sfx_len = max((size_t)7, strlen(real_name));
1804 
1805 	/* This is one of the more confusing parts of libbpf for various
1806 	 * reasons, some of which are historical. The original idea for naming
1807 	 * internal names was to include as much of BPF object name prefix as
1808 	 * possible, so that it can be distinguished from similar internal
1809 	 * maps of a different BPF object.
1810 	 * As an example, let's say we have bpf_object named 'my_object_name'
1811 	 * and internal map corresponding to '.rodata' ELF section. The final
1812 	 * map name advertised to user and to the kernel will be
1813 	 * 'my_objec.rodata', taking first 8 characters of object name and
1814 	 * entire 7 characters of '.rodata'.
1815 	 * Somewhat confusingly, if internal map ELF section name is shorter
1816 	 * than 7 characters, e.g., '.bss', we still reserve 7 characters
1817 	 * for the suffix, even though we only have 4 actual characters, and
1818 	 * resulting map will be called 'my_objec.bss', not even using all 15
1819 	 * characters allowed by the kernel. Oh well, at least the truncated
1820 	 * object name is somewhat consistent in this case. But if the map
1821 	 * name is '.kconfig', we'll still have entirety of '.kconfig' added
1822 	 * (8 chars) and thus will be left with only first 7 characters of the
1823 	 * object name ('my_obje'). Happy guessing, user, that the final map
1824 	 * name will be "my_obje.kconfig".
1825 	 * Now, with libbpf starting to support arbitrarily named .rodata.*
1826 	 * and .data.* data sections, it's possible that ELF section name is
1827 	 * longer than allowed 15 chars, so we now need to be careful to take
1828 	 * only up to 15 first characters of ELF name, taking no BPF object
1829 	 * name characters at all. So '.rodata.abracadabra' will result in
1830 	 * '.rodata.abracad' kernel and user-visible name.
1831 	 * We need to keep this convoluted logic intact for .data, .bss and
1832 	 * .rodata maps, but for new custom .data.custom and .rodata.custom
1833 	 * maps we use their ELF names as is, not prepending bpf_object name
1834 	 * in front. We still need to truncate them to 15 characters for the
1835 	 * kernel. Full name can be recovered for such maps by using DATASEC
1836 	 * BTF type associated with such map's value type, though.
1837 	 */
1838 	if (sfx_len >= BPF_OBJ_NAME_LEN)
1839 		sfx_len = BPF_OBJ_NAME_LEN - 1;
1840 
1841 	/* if there are two or more dots in map name, it's a custom dot map */
1842 	if (strchr(real_name + 1, '.') != NULL)
1843 		pfx_len = 0;
1844 	else
1845 		pfx_len = min((size_t)BPF_OBJ_NAME_LEN - sfx_len - 1, strlen(obj->name));
1846 
1847 	snprintf(map_name, sizeof(map_name), "%.*s%.*s", pfx_len, obj->name,
1848 		 sfx_len, real_name);
1849 
1850 	/* sanitise map name to characters allowed by kernel */
1851 	for (p = map_name; *p && p < map_name + sizeof(map_name); p++)
1852 		if (!isalnum(*p) && *p != '_' && *p != '.')
1853 			*p = '_';
1854 
1855 	return strdup(map_name);
1856 }
1857 
1858 static int
1859 map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map);
1860 
1861 /* Internal BPF map is mmap()'able only if at least one of corresponding
1862  * DATASEC's VARs are to be exposed through BPF skeleton. I.e., it's a GLOBAL
1863  * variable and it's not marked as __hidden (which turns it into, effectively,
1864  * a STATIC variable).
1865  */
1866 static bool map_is_mmapable(struct bpf_object *obj, struct bpf_map *map)
1867 {
1868 	const struct btf_type *t, *vt;
1869 	struct btf_var_secinfo *vsi;
1870 	int i, n;
1871 
1872 	if (!map->btf_value_type_id)
1873 		return false;
1874 
1875 	t = btf__type_by_id(obj->btf, map->btf_value_type_id);
1876 	if (!btf_is_datasec(t))
1877 		return false;
1878 
1879 	vsi = btf_var_secinfos(t);
1880 	for (i = 0, n = btf_vlen(t); i < n; i++, vsi++) {
1881 		vt = btf__type_by_id(obj->btf, vsi->type);
1882 		if (!btf_is_var(vt))
1883 			continue;
1884 
1885 		if (btf_var(vt)->linkage != BTF_VAR_STATIC)
1886 			return true;
1887 	}
1888 
1889 	return false;
1890 }
1891 
1892 static int
1893 bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
1894 			      const char *real_name, int sec_idx, void *data, size_t data_sz)
1895 {
1896 	struct bpf_map_def *def;
1897 	struct bpf_map *map;
1898 	size_t mmap_sz;
1899 	int err;
1900 
1901 	map = bpf_object__add_map(obj);
1902 	if (IS_ERR(map))
1903 		return PTR_ERR(map);
1904 
1905 	map->libbpf_type = type;
1906 	map->sec_idx = sec_idx;
1907 	map->sec_offset = 0;
1908 	map->real_name = strdup(real_name);
1909 	map->name = internal_map_name(obj, real_name);
1910 	if (!map->real_name || !map->name) {
1911 		zfree(&map->real_name);
1912 		zfree(&map->name);
1913 		return -ENOMEM;
1914 	}
1915 
1916 	def = &map->def;
1917 	def->type = BPF_MAP_TYPE_ARRAY;
1918 	def->key_size = sizeof(int);
1919 	def->value_size = data_sz;
1920 	def->max_entries = 1;
1921 	def->map_flags = type == LIBBPF_MAP_RODATA || type == LIBBPF_MAP_KCONFIG
1922 		? BPF_F_RDONLY_PROG : 0;
1923 
1924 	/* failures are fine because of maps like .rodata.str1.1 */
1925 	(void) map_fill_btf_type_info(obj, map);
1926 
1927 	if (map_is_mmapable(obj, map))
1928 		def->map_flags |= BPF_F_MMAPABLE;
1929 
1930 	pr_debug("map '%s' (global data): at sec_idx %d, offset %zu, flags %x.\n",
1931 		 map->name, map->sec_idx, map->sec_offset, def->map_flags);
1932 
1933 	mmap_sz = bpf_map_mmap_sz(map);
1934 	map->mmaped = mmap(NULL, mmap_sz, PROT_READ | PROT_WRITE,
1935 			   MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1936 	if (map->mmaped == MAP_FAILED) {
1937 		err = -errno;
1938 		map->mmaped = NULL;
1939 		pr_warn("failed to alloc map '%s' content buffer: %d\n",
1940 			map->name, err);
1941 		zfree(&map->real_name);
1942 		zfree(&map->name);
1943 		return err;
1944 	}
1945 
1946 	if (data)
1947 		memcpy(map->mmaped, data, data_sz);
1948 
1949 	pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
1950 	return 0;
1951 }
1952 
1953 static int bpf_object__init_global_data_maps(struct bpf_object *obj)
1954 {
1955 	struct elf_sec_desc *sec_desc;
1956 	const char *sec_name;
1957 	int err = 0, sec_idx;
1958 
1959 	/*
1960 	 * Populate obj->maps with libbpf internal maps.
1961 	 */
1962 	for (sec_idx = 1; sec_idx < obj->efile.sec_cnt; sec_idx++) {
1963 		sec_desc = &obj->efile.secs[sec_idx];
1964 
1965 		/* Skip recognized sections with size 0. */
1966 		if (!sec_desc->data || sec_desc->data->d_size == 0)
1967 			continue;
1968 
1969 		switch (sec_desc->sec_type) {
1970 		case SEC_DATA:
1971 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1972 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
1973 							    sec_name, sec_idx,
1974 							    sec_desc->data->d_buf,
1975 							    sec_desc->data->d_size);
1976 			break;
1977 		case SEC_RODATA:
1978 			obj->has_rodata = true;
1979 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1980 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
1981 							    sec_name, sec_idx,
1982 							    sec_desc->data->d_buf,
1983 							    sec_desc->data->d_size);
1984 			break;
1985 		case SEC_BSS:
1986 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1987 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
1988 							    sec_name, sec_idx,
1989 							    NULL,
1990 							    sec_desc->data->d_size);
1991 			break;
1992 		default:
1993 			/* skip */
1994 			break;
1995 		}
1996 		if (err)
1997 			return err;
1998 	}
1999 	return 0;
2000 }
2001 
2002 
2003 static struct extern_desc *find_extern_by_name(const struct bpf_object *obj,
2004 					       const void *name)
2005 {
2006 	int i;
2007 
2008 	for (i = 0; i < obj->nr_extern; i++) {
2009 		if (strcmp(obj->externs[i].name, name) == 0)
2010 			return &obj->externs[i];
2011 	}
2012 	return NULL;
2013 }
2014 
2015 static struct extern_desc *find_extern_by_name_with_len(const struct bpf_object *obj,
2016 							const void *name, int len)
2017 {
2018 	const char *ext_name;
2019 	int i;
2020 
2021 	for (i = 0; i < obj->nr_extern; i++) {
2022 		ext_name = obj->externs[i].name;
2023 		if (strlen(ext_name) == len && strncmp(ext_name, name, len) == 0)
2024 			return &obj->externs[i];
2025 	}
2026 	return NULL;
2027 }
2028 
2029 static int set_kcfg_value_tri(struct extern_desc *ext, void *ext_val,
2030 			      char value)
2031 {
2032 	switch (ext->kcfg.type) {
2033 	case KCFG_BOOL:
2034 		if (value == 'm') {
2035 			pr_warn("extern (kcfg) '%s': value '%c' implies tristate or char type\n",
2036 				ext->name, value);
2037 			return -EINVAL;
2038 		}
2039 		*(bool *)ext_val = value == 'y' ? true : false;
2040 		break;
2041 	case KCFG_TRISTATE:
2042 		if (value == 'y')
2043 			*(enum libbpf_tristate *)ext_val = TRI_YES;
2044 		else if (value == 'm')
2045 			*(enum libbpf_tristate *)ext_val = TRI_MODULE;
2046 		else /* value == 'n' */
2047 			*(enum libbpf_tristate *)ext_val = TRI_NO;
2048 		break;
2049 	case KCFG_CHAR:
2050 		*(char *)ext_val = value;
2051 		break;
2052 	case KCFG_UNKNOWN:
2053 	case KCFG_INT:
2054 	case KCFG_CHAR_ARR:
2055 	default:
2056 		pr_warn("extern (kcfg) '%s': value '%c' implies bool, tristate, or char type\n",
2057 			ext->name, value);
2058 		return -EINVAL;
2059 	}
2060 	ext->is_set = true;
2061 	return 0;
2062 }
2063 
2064 static int set_kcfg_value_str(struct extern_desc *ext, char *ext_val,
2065 			      const char *value)
2066 {
2067 	size_t len;
2068 
2069 	if (ext->kcfg.type != KCFG_CHAR_ARR) {
2070 		pr_warn("extern (kcfg) '%s': value '%s' implies char array type\n",
2071 			ext->name, value);
2072 		return -EINVAL;
2073 	}
2074 
2075 	len = strlen(value);
2076 	if (value[len - 1] != '"') {
2077 		pr_warn("extern (kcfg) '%s': invalid string config '%s'\n",
2078 			ext->name, value);
2079 		return -EINVAL;
2080 	}
2081 
2082 	/* strip quotes */
2083 	len -= 2;
2084 	if (len >= ext->kcfg.sz) {
2085 		pr_warn("extern (kcfg) '%s': long string '%s' of (%zu bytes) truncated to %d bytes\n",
2086 			ext->name, value, len, ext->kcfg.sz - 1);
2087 		len = ext->kcfg.sz - 1;
2088 	}
2089 	memcpy(ext_val, value + 1, len);
2090 	ext_val[len] = '\0';
2091 	ext->is_set = true;
2092 	return 0;
2093 }
2094 
2095 static int parse_u64(const char *value, __u64 *res)
2096 {
2097 	char *value_end;
2098 	int err;
2099 
2100 	errno = 0;
2101 	*res = strtoull(value, &value_end, 0);
2102 	if (errno) {
2103 		err = -errno;
2104 		pr_warn("failed to parse '%s' as integer: %d\n", value, err);
2105 		return err;
2106 	}
2107 	if (*value_end) {
2108 		pr_warn("failed to parse '%s' as integer completely\n", value);
2109 		return -EINVAL;
2110 	}
2111 	return 0;
2112 }
2113 
2114 static bool is_kcfg_value_in_range(const struct extern_desc *ext, __u64 v)
2115 {
2116 	int bit_sz = ext->kcfg.sz * 8;
2117 
2118 	if (ext->kcfg.sz == 8)
2119 		return true;
2120 
2121 	/* Validate that value stored in u64 fits in integer of `ext->sz`
2122 	 * bytes size without any loss of information. If the target integer
2123 	 * is signed, we rely on the following limits of integer type of
2124 	 * Y bits and subsequent transformation:
2125 	 *
2126 	 *     -2^(Y-1) <= X           <= 2^(Y-1) - 1
2127 	 *            0 <= X + 2^(Y-1) <= 2^Y - 1
2128 	 *            0 <= X + 2^(Y-1) <  2^Y
2129 	 *
2130 	 *  For unsigned target integer, check that all the (64 - Y) bits are
2131 	 *  zero.
2132 	 */
2133 	if (ext->kcfg.is_signed)
2134 		return v + (1ULL << (bit_sz - 1)) < (1ULL << bit_sz);
2135 	else
2136 		return (v >> bit_sz) == 0;
2137 }
2138 
2139 static int set_kcfg_value_num(struct extern_desc *ext, void *ext_val,
2140 			      __u64 value)
2141 {
2142 	if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR &&
2143 	    ext->kcfg.type != KCFG_BOOL) {
2144 		pr_warn("extern (kcfg) '%s': value '%llu' implies integer, char, or boolean type\n",
2145 			ext->name, (unsigned long long)value);
2146 		return -EINVAL;
2147 	}
2148 	if (ext->kcfg.type == KCFG_BOOL && value > 1) {
2149 		pr_warn("extern (kcfg) '%s': value '%llu' isn't boolean compatible\n",
2150 			ext->name, (unsigned long long)value);
2151 		return -EINVAL;
2152 
2153 	}
2154 	if (!is_kcfg_value_in_range(ext, value)) {
2155 		pr_warn("extern (kcfg) '%s': value '%llu' doesn't fit in %d bytes\n",
2156 			ext->name, (unsigned long long)value, ext->kcfg.sz);
2157 		return -ERANGE;
2158 	}
2159 	switch (ext->kcfg.sz) {
2160 	case 1:
2161 		*(__u8 *)ext_val = value;
2162 		break;
2163 	case 2:
2164 		*(__u16 *)ext_val = value;
2165 		break;
2166 	case 4:
2167 		*(__u32 *)ext_val = value;
2168 		break;
2169 	case 8:
2170 		*(__u64 *)ext_val = value;
2171 		break;
2172 	default:
2173 		return -EINVAL;
2174 	}
2175 	ext->is_set = true;
2176 	return 0;
2177 }
2178 
2179 static int bpf_object__process_kconfig_line(struct bpf_object *obj,
2180 					    char *buf, void *data)
2181 {
2182 	struct extern_desc *ext;
2183 	char *sep, *value;
2184 	int len, err = 0;
2185 	void *ext_val;
2186 	__u64 num;
2187 
2188 	if (!str_has_pfx(buf, "CONFIG_"))
2189 		return 0;
2190 
2191 	sep = strchr(buf, '=');
2192 	if (!sep) {
2193 		pr_warn("failed to parse '%s': no separator\n", buf);
2194 		return -EINVAL;
2195 	}
2196 
2197 	/* Trim ending '\n' */
2198 	len = strlen(buf);
2199 	if (buf[len - 1] == '\n')
2200 		buf[len - 1] = '\0';
2201 	/* Split on '=' and ensure that a value is present. */
2202 	*sep = '\0';
2203 	if (!sep[1]) {
2204 		*sep = '=';
2205 		pr_warn("failed to parse '%s': no value\n", buf);
2206 		return -EINVAL;
2207 	}
2208 
2209 	ext = find_extern_by_name(obj, buf);
2210 	if (!ext || ext->is_set)
2211 		return 0;
2212 
2213 	ext_val = data + ext->kcfg.data_off;
2214 	value = sep + 1;
2215 
2216 	switch (*value) {
2217 	case 'y': case 'n': case 'm':
2218 		err = set_kcfg_value_tri(ext, ext_val, *value);
2219 		break;
2220 	case '"':
2221 		err = set_kcfg_value_str(ext, ext_val, value);
2222 		break;
2223 	default:
2224 		/* assume integer */
2225 		err = parse_u64(value, &num);
2226 		if (err) {
2227 			pr_warn("extern (kcfg) '%s': value '%s' isn't a valid integer\n", ext->name, value);
2228 			return err;
2229 		}
2230 		if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR) {
2231 			pr_warn("extern (kcfg) '%s': value '%s' implies integer type\n", ext->name, value);
2232 			return -EINVAL;
2233 		}
2234 		err = set_kcfg_value_num(ext, ext_val, num);
2235 		break;
2236 	}
2237 	if (err)
2238 		return err;
2239 	pr_debug("extern (kcfg) '%s': set to %s\n", ext->name, value);
2240 	return 0;
2241 }
2242 
2243 static int bpf_object__read_kconfig_file(struct bpf_object *obj, void *data)
2244 {
2245 	char buf[PATH_MAX];
2246 	struct utsname uts;
2247 	int len, err = 0;
2248 	gzFile file;
2249 
2250 	uname(&uts);
2251 	len = snprintf(buf, PATH_MAX, "/boot/config-%s", uts.release);
2252 	if (len < 0)
2253 		return -EINVAL;
2254 	else if (len >= PATH_MAX)
2255 		return -ENAMETOOLONG;
2256 
2257 	/* gzopen also accepts uncompressed files. */
2258 	file = gzopen(buf, "re");
2259 	if (!file)
2260 		file = gzopen("/proc/config.gz", "re");
2261 
2262 	if (!file) {
2263 		pr_warn("failed to open system Kconfig\n");
2264 		return -ENOENT;
2265 	}
2266 
2267 	while (gzgets(file, buf, sizeof(buf))) {
2268 		err = bpf_object__process_kconfig_line(obj, buf, data);
2269 		if (err) {
2270 			pr_warn("error parsing system Kconfig line '%s': %d\n",
2271 				buf, err);
2272 			goto out;
2273 		}
2274 	}
2275 
2276 out:
2277 	gzclose(file);
2278 	return err;
2279 }
2280 
2281 static int bpf_object__read_kconfig_mem(struct bpf_object *obj,
2282 					const char *config, void *data)
2283 {
2284 	char buf[PATH_MAX];
2285 	int err = 0;
2286 	FILE *file;
2287 
2288 	file = fmemopen((void *)config, strlen(config), "r");
2289 	if (!file) {
2290 		err = -errno;
2291 		pr_warn("failed to open in-memory Kconfig: %d\n", err);
2292 		return err;
2293 	}
2294 
2295 	while (fgets(buf, sizeof(buf), file)) {
2296 		err = bpf_object__process_kconfig_line(obj, buf, data);
2297 		if (err) {
2298 			pr_warn("error parsing in-memory Kconfig line '%s': %d\n",
2299 				buf, err);
2300 			break;
2301 		}
2302 	}
2303 
2304 	fclose(file);
2305 	return err;
2306 }
2307 
2308 static int bpf_object__init_kconfig_map(struct bpf_object *obj)
2309 {
2310 	struct extern_desc *last_ext = NULL, *ext;
2311 	size_t map_sz;
2312 	int i, err;
2313 
2314 	for (i = 0; i < obj->nr_extern; i++) {
2315 		ext = &obj->externs[i];
2316 		if (ext->type == EXT_KCFG)
2317 			last_ext = ext;
2318 	}
2319 
2320 	if (!last_ext)
2321 		return 0;
2322 
2323 	map_sz = last_ext->kcfg.data_off + last_ext->kcfg.sz;
2324 	err = bpf_object__init_internal_map(obj, LIBBPF_MAP_KCONFIG,
2325 					    ".kconfig", obj->efile.symbols_shndx,
2326 					    NULL, map_sz);
2327 	if (err)
2328 		return err;
2329 
2330 	obj->kconfig_map_idx = obj->nr_maps - 1;
2331 
2332 	return 0;
2333 }
2334 
2335 const struct btf_type *
2336 skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id)
2337 {
2338 	const struct btf_type *t = btf__type_by_id(btf, id);
2339 
2340 	if (res_id)
2341 		*res_id = id;
2342 
2343 	while (btf_is_mod(t) || btf_is_typedef(t)) {
2344 		if (res_id)
2345 			*res_id = t->type;
2346 		t = btf__type_by_id(btf, t->type);
2347 	}
2348 
2349 	return t;
2350 }
2351 
2352 static const struct btf_type *
2353 resolve_func_ptr(const struct btf *btf, __u32 id, __u32 *res_id)
2354 {
2355 	const struct btf_type *t;
2356 
2357 	t = skip_mods_and_typedefs(btf, id, NULL);
2358 	if (!btf_is_ptr(t))
2359 		return NULL;
2360 
2361 	t = skip_mods_and_typedefs(btf, t->type, res_id);
2362 
2363 	return btf_is_func_proto(t) ? t : NULL;
2364 }
2365 
2366 static const char *__btf_kind_str(__u16 kind)
2367 {
2368 	switch (kind) {
2369 	case BTF_KIND_UNKN: return "void";
2370 	case BTF_KIND_INT: return "int";
2371 	case BTF_KIND_PTR: return "ptr";
2372 	case BTF_KIND_ARRAY: return "array";
2373 	case BTF_KIND_STRUCT: return "struct";
2374 	case BTF_KIND_UNION: return "union";
2375 	case BTF_KIND_ENUM: return "enum";
2376 	case BTF_KIND_FWD: return "fwd";
2377 	case BTF_KIND_TYPEDEF: return "typedef";
2378 	case BTF_KIND_VOLATILE: return "volatile";
2379 	case BTF_KIND_CONST: return "const";
2380 	case BTF_KIND_RESTRICT: return "restrict";
2381 	case BTF_KIND_FUNC: return "func";
2382 	case BTF_KIND_FUNC_PROTO: return "func_proto";
2383 	case BTF_KIND_VAR: return "var";
2384 	case BTF_KIND_DATASEC: return "datasec";
2385 	case BTF_KIND_FLOAT: return "float";
2386 	case BTF_KIND_DECL_TAG: return "decl_tag";
2387 	case BTF_KIND_TYPE_TAG: return "type_tag";
2388 	case BTF_KIND_ENUM64: return "enum64";
2389 	default: return "unknown";
2390 	}
2391 }
2392 
2393 const char *btf_kind_str(const struct btf_type *t)
2394 {
2395 	return __btf_kind_str(btf_kind(t));
2396 }
2397 
2398 /*
2399  * Fetch integer attribute of BTF map definition. Such attributes are
2400  * represented using a pointer to an array, in which dimensionality of array
2401  * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
2402  * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
2403  * type definition, while using only sizeof(void *) space in ELF data section.
2404  */
2405 static bool get_map_field_int(const char *map_name, const struct btf *btf,
2406 			      const struct btf_member *m, __u32 *res)
2407 {
2408 	const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
2409 	const char *name = btf__name_by_offset(btf, m->name_off);
2410 	const struct btf_array *arr_info;
2411 	const struct btf_type *arr_t;
2412 
2413 	if (!btf_is_ptr(t)) {
2414 		pr_warn("map '%s': attr '%s': expected PTR, got %s.\n",
2415 			map_name, name, btf_kind_str(t));
2416 		return false;
2417 	}
2418 
2419 	arr_t = btf__type_by_id(btf, t->type);
2420 	if (!arr_t) {
2421 		pr_warn("map '%s': attr '%s': type [%u] not found.\n",
2422 			map_name, name, t->type);
2423 		return false;
2424 	}
2425 	if (!btf_is_array(arr_t)) {
2426 		pr_warn("map '%s': attr '%s': expected ARRAY, got %s.\n",
2427 			map_name, name, btf_kind_str(arr_t));
2428 		return false;
2429 	}
2430 	arr_info = btf_array(arr_t);
2431 	*res = arr_info->nelems;
2432 	return true;
2433 }
2434 
2435 static bool get_map_field_long(const char *map_name, const struct btf *btf,
2436 			       const struct btf_member *m, __u64 *res)
2437 {
2438 	const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
2439 	const char *name = btf__name_by_offset(btf, m->name_off);
2440 
2441 	if (btf_is_ptr(t)) {
2442 		__u32 res32;
2443 		bool ret;
2444 
2445 		ret = get_map_field_int(map_name, btf, m, &res32);
2446 		if (ret)
2447 			*res = (__u64)res32;
2448 		return ret;
2449 	}
2450 
2451 	if (!btf_is_enum(t) && !btf_is_enum64(t)) {
2452 		pr_warn("map '%s': attr '%s': expected ENUM or ENUM64, got %s.\n",
2453 			map_name, name, btf_kind_str(t));
2454 		return false;
2455 	}
2456 
2457 	if (btf_vlen(t) != 1) {
2458 		pr_warn("map '%s': attr '%s': invalid __ulong\n",
2459 			map_name, name);
2460 		return false;
2461 	}
2462 
2463 	if (btf_is_enum(t)) {
2464 		const struct btf_enum *e = btf_enum(t);
2465 
2466 		*res = e->val;
2467 	} else {
2468 		const struct btf_enum64 *e = btf_enum64(t);
2469 
2470 		*res = btf_enum64_value(e);
2471 	}
2472 	return true;
2473 }
2474 
2475 static int pathname_concat(char *buf, size_t buf_sz, const char *path, const char *name)
2476 {
2477 	int len;
2478 
2479 	len = snprintf(buf, buf_sz, "%s/%s", path, name);
2480 	if (len < 0)
2481 		return -EINVAL;
2482 	if (len >= buf_sz)
2483 		return -ENAMETOOLONG;
2484 
2485 	return 0;
2486 }
2487 
2488 static int build_map_pin_path(struct bpf_map *map, const char *path)
2489 {
2490 	char buf[PATH_MAX];
2491 	int err;
2492 
2493 	if (!path)
2494 		path = BPF_FS_DEFAULT_PATH;
2495 
2496 	err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
2497 	if (err)
2498 		return err;
2499 
2500 	return bpf_map__set_pin_path(map, buf);
2501 }
2502 
2503 /* should match definition in bpf_helpers.h */
2504 enum libbpf_pin_type {
2505 	LIBBPF_PIN_NONE,
2506 	/* PIN_BY_NAME: pin maps by name (in /sys/fs/bpf by default) */
2507 	LIBBPF_PIN_BY_NAME,
2508 };
2509 
2510 int parse_btf_map_def(const char *map_name, struct btf *btf,
2511 		      const struct btf_type *def_t, bool strict,
2512 		      struct btf_map_def *map_def, struct btf_map_def *inner_def)
2513 {
2514 	const struct btf_type *t;
2515 	const struct btf_member *m;
2516 	bool is_inner = inner_def == NULL;
2517 	int vlen, i;
2518 
2519 	vlen = btf_vlen(def_t);
2520 	m = btf_members(def_t);
2521 	for (i = 0; i < vlen; i++, m++) {
2522 		const char *name = btf__name_by_offset(btf, m->name_off);
2523 
2524 		if (!name) {
2525 			pr_warn("map '%s': invalid field #%d.\n", map_name, i);
2526 			return -EINVAL;
2527 		}
2528 		if (strcmp(name, "type") == 0) {
2529 			if (!get_map_field_int(map_name, btf, m, &map_def->map_type))
2530 				return -EINVAL;
2531 			map_def->parts |= MAP_DEF_MAP_TYPE;
2532 		} else if (strcmp(name, "max_entries") == 0) {
2533 			if (!get_map_field_int(map_name, btf, m, &map_def->max_entries))
2534 				return -EINVAL;
2535 			map_def->parts |= MAP_DEF_MAX_ENTRIES;
2536 		} else if (strcmp(name, "map_flags") == 0) {
2537 			if (!get_map_field_int(map_name, btf, m, &map_def->map_flags))
2538 				return -EINVAL;
2539 			map_def->parts |= MAP_DEF_MAP_FLAGS;
2540 		} else if (strcmp(name, "numa_node") == 0) {
2541 			if (!get_map_field_int(map_name, btf, m, &map_def->numa_node))
2542 				return -EINVAL;
2543 			map_def->parts |= MAP_DEF_NUMA_NODE;
2544 		} else if (strcmp(name, "key_size") == 0) {
2545 			__u32 sz;
2546 
2547 			if (!get_map_field_int(map_name, btf, m, &sz))
2548 				return -EINVAL;
2549 			if (map_def->key_size && map_def->key_size != sz) {
2550 				pr_warn("map '%s': conflicting key size %u != %u.\n",
2551 					map_name, map_def->key_size, sz);
2552 				return -EINVAL;
2553 			}
2554 			map_def->key_size = sz;
2555 			map_def->parts |= MAP_DEF_KEY_SIZE;
2556 		} else if (strcmp(name, "key") == 0) {
2557 			__s64 sz;
2558 
2559 			t = btf__type_by_id(btf, m->type);
2560 			if (!t) {
2561 				pr_warn("map '%s': key type [%d] not found.\n",
2562 					map_name, m->type);
2563 				return -EINVAL;
2564 			}
2565 			if (!btf_is_ptr(t)) {
2566 				pr_warn("map '%s': key spec is not PTR: %s.\n",
2567 					map_name, btf_kind_str(t));
2568 				return -EINVAL;
2569 			}
2570 			sz = btf__resolve_size(btf, t->type);
2571 			if (sz < 0) {
2572 				pr_warn("map '%s': can't determine key size for type [%u]: %zd.\n",
2573 					map_name, t->type, (ssize_t)sz);
2574 				return sz;
2575 			}
2576 			if (map_def->key_size && map_def->key_size != sz) {
2577 				pr_warn("map '%s': conflicting key size %u != %zd.\n",
2578 					map_name, map_def->key_size, (ssize_t)sz);
2579 				return -EINVAL;
2580 			}
2581 			map_def->key_size = sz;
2582 			map_def->key_type_id = t->type;
2583 			map_def->parts |= MAP_DEF_KEY_SIZE | MAP_DEF_KEY_TYPE;
2584 		} else if (strcmp(name, "value_size") == 0) {
2585 			__u32 sz;
2586 
2587 			if (!get_map_field_int(map_name, btf, m, &sz))
2588 				return -EINVAL;
2589 			if (map_def->value_size && map_def->value_size != sz) {
2590 				pr_warn("map '%s': conflicting value size %u != %u.\n",
2591 					map_name, map_def->value_size, sz);
2592 				return -EINVAL;
2593 			}
2594 			map_def->value_size = sz;
2595 			map_def->parts |= MAP_DEF_VALUE_SIZE;
2596 		} else if (strcmp(name, "value") == 0) {
2597 			__s64 sz;
2598 
2599 			t = btf__type_by_id(btf, m->type);
2600 			if (!t) {
2601 				pr_warn("map '%s': value type [%d] not found.\n",
2602 					map_name, m->type);
2603 				return -EINVAL;
2604 			}
2605 			if (!btf_is_ptr(t)) {
2606 				pr_warn("map '%s': value spec is not PTR: %s.\n",
2607 					map_name, btf_kind_str(t));
2608 				return -EINVAL;
2609 			}
2610 			sz = btf__resolve_size(btf, t->type);
2611 			if (sz < 0) {
2612 				pr_warn("map '%s': can't determine value size for type [%u]: %zd.\n",
2613 					map_name, t->type, (ssize_t)sz);
2614 				return sz;
2615 			}
2616 			if (map_def->value_size && map_def->value_size != sz) {
2617 				pr_warn("map '%s': conflicting value size %u != %zd.\n",
2618 					map_name, map_def->value_size, (ssize_t)sz);
2619 				return -EINVAL;
2620 			}
2621 			map_def->value_size = sz;
2622 			map_def->value_type_id = t->type;
2623 			map_def->parts |= MAP_DEF_VALUE_SIZE | MAP_DEF_VALUE_TYPE;
2624 		}
2625 		else if (strcmp(name, "values") == 0) {
2626 			bool is_map_in_map = bpf_map_type__is_map_in_map(map_def->map_type);
2627 			bool is_prog_array = map_def->map_type == BPF_MAP_TYPE_PROG_ARRAY;
2628 			const char *desc = is_map_in_map ? "map-in-map inner" : "prog-array value";
2629 			char inner_map_name[128];
2630 			int err;
2631 
2632 			if (is_inner) {
2633 				pr_warn("map '%s': multi-level inner maps not supported.\n",
2634 					map_name);
2635 				return -ENOTSUP;
2636 			}
2637 			if (i != vlen - 1) {
2638 				pr_warn("map '%s': '%s' member should be last.\n",
2639 					map_name, name);
2640 				return -EINVAL;
2641 			}
2642 			if (!is_map_in_map && !is_prog_array) {
2643 				pr_warn("map '%s': should be map-in-map or prog-array.\n",
2644 					map_name);
2645 				return -ENOTSUP;
2646 			}
2647 			if (map_def->value_size && map_def->value_size != 4) {
2648 				pr_warn("map '%s': conflicting value size %u != 4.\n",
2649 					map_name, map_def->value_size);
2650 				return -EINVAL;
2651 			}
2652 			map_def->value_size = 4;
2653 			t = btf__type_by_id(btf, m->type);
2654 			if (!t) {
2655 				pr_warn("map '%s': %s type [%d] not found.\n",
2656 					map_name, desc, m->type);
2657 				return -EINVAL;
2658 			}
2659 			if (!btf_is_array(t) || btf_array(t)->nelems) {
2660 				pr_warn("map '%s': %s spec is not a zero-sized array.\n",
2661 					map_name, desc);
2662 				return -EINVAL;
2663 			}
2664 			t = skip_mods_and_typedefs(btf, btf_array(t)->type, NULL);
2665 			if (!btf_is_ptr(t)) {
2666 				pr_warn("map '%s': %s def is of unexpected kind %s.\n",
2667 					map_name, desc, btf_kind_str(t));
2668 				return -EINVAL;
2669 			}
2670 			t = skip_mods_and_typedefs(btf, t->type, NULL);
2671 			if (is_prog_array) {
2672 				if (!btf_is_func_proto(t)) {
2673 					pr_warn("map '%s': prog-array value def is of unexpected kind %s.\n",
2674 						map_name, btf_kind_str(t));
2675 					return -EINVAL;
2676 				}
2677 				continue;
2678 			}
2679 			if (!btf_is_struct(t)) {
2680 				pr_warn("map '%s': map-in-map inner def is of unexpected kind %s.\n",
2681 					map_name, btf_kind_str(t));
2682 				return -EINVAL;
2683 			}
2684 
2685 			snprintf(inner_map_name, sizeof(inner_map_name), "%s.inner", map_name);
2686 			err = parse_btf_map_def(inner_map_name, btf, t, strict, inner_def, NULL);
2687 			if (err)
2688 				return err;
2689 
2690 			map_def->parts |= MAP_DEF_INNER_MAP;
2691 		} else if (strcmp(name, "pinning") == 0) {
2692 			__u32 val;
2693 
2694 			if (is_inner) {
2695 				pr_warn("map '%s': inner def can't be pinned.\n", map_name);
2696 				return -EINVAL;
2697 			}
2698 			if (!get_map_field_int(map_name, btf, m, &val))
2699 				return -EINVAL;
2700 			if (val != LIBBPF_PIN_NONE && val != LIBBPF_PIN_BY_NAME) {
2701 				pr_warn("map '%s': invalid pinning value %u.\n",
2702 					map_name, val);
2703 				return -EINVAL;
2704 			}
2705 			map_def->pinning = val;
2706 			map_def->parts |= MAP_DEF_PINNING;
2707 		} else if (strcmp(name, "map_extra") == 0) {
2708 			__u64 map_extra;
2709 
2710 			if (!get_map_field_long(map_name, btf, m, &map_extra))
2711 				return -EINVAL;
2712 			map_def->map_extra = map_extra;
2713 			map_def->parts |= MAP_DEF_MAP_EXTRA;
2714 		} else {
2715 			if (strict) {
2716 				pr_warn("map '%s': unknown field '%s'.\n", map_name, name);
2717 				return -ENOTSUP;
2718 			}
2719 			pr_debug("map '%s': ignoring unknown field '%s'.\n", map_name, name);
2720 		}
2721 	}
2722 
2723 	if (map_def->map_type == BPF_MAP_TYPE_UNSPEC) {
2724 		pr_warn("map '%s': map type isn't specified.\n", map_name);
2725 		return -EINVAL;
2726 	}
2727 
2728 	return 0;
2729 }
2730 
2731 static size_t adjust_ringbuf_sz(size_t sz)
2732 {
2733 	__u32 page_sz = sysconf(_SC_PAGE_SIZE);
2734 	__u32 mul;
2735 
2736 	/* if user forgot to set any size, make sure they see error */
2737 	if (sz == 0)
2738 		return 0;
2739 	/* Kernel expects BPF_MAP_TYPE_RINGBUF's max_entries to be
2740 	 * a power-of-2 multiple of kernel's page size. If user diligently
2741 	 * satisified these conditions, pass the size through.
2742 	 */
2743 	if ((sz % page_sz) == 0 && is_pow_of_2(sz / page_sz))
2744 		return sz;
2745 
2746 	/* Otherwise find closest (page_sz * power_of_2) product bigger than
2747 	 * user-set size to satisfy both user size request and kernel
2748 	 * requirements and substitute correct max_entries for map creation.
2749 	 */
2750 	for (mul = 1; mul <= UINT_MAX / page_sz; mul <<= 1) {
2751 		if (mul * page_sz > sz)
2752 			return mul * page_sz;
2753 	}
2754 
2755 	/* if it's impossible to satisfy the conditions (i.e., user size is
2756 	 * very close to UINT_MAX but is not a power-of-2 multiple of
2757 	 * page_size) then just return original size and let kernel reject it
2758 	 */
2759 	return sz;
2760 }
2761 
2762 static bool map_is_ringbuf(const struct bpf_map *map)
2763 {
2764 	return map->def.type == BPF_MAP_TYPE_RINGBUF ||
2765 	       map->def.type == BPF_MAP_TYPE_USER_RINGBUF;
2766 }
2767 
2768 static void fill_map_from_def(struct bpf_map *map, const struct btf_map_def *def)
2769 {
2770 	map->def.type = def->map_type;
2771 	map->def.key_size = def->key_size;
2772 	map->def.value_size = def->value_size;
2773 	map->def.max_entries = def->max_entries;
2774 	map->def.map_flags = def->map_flags;
2775 	map->map_extra = def->map_extra;
2776 
2777 	map->numa_node = def->numa_node;
2778 	map->btf_key_type_id = def->key_type_id;
2779 	map->btf_value_type_id = def->value_type_id;
2780 
2781 	/* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
2782 	if (map_is_ringbuf(map))
2783 		map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
2784 
2785 	if (def->parts & MAP_DEF_MAP_TYPE)
2786 		pr_debug("map '%s': found type = %u.\n", map->name, def->map_type);
2787 
2788 	if (def->parts & MAP_DEF_KEY_TYPE)
2789 		pr_debug("map '%s': found key [%u], sz = %u.\n",
2790 			 map->name, def->key_type_id, def->key_size);
2791 	else if (def->parts & MAP_DEF_KEY_SIZE)
2792 		pr_debug("map '%s': found key_size = %u.\n", map->name, def->key_size);
2793 
2794 	if (def->parts & MAP_DEF_VALUE_TYPE)
2795 		pr_debug("map '%s': found value [%u], sz = %u.\n",
2796 			 map->name, def->value_type_id, def->value_size);
2797 	else if (def->parts & MAP_DEF_VALUE_SIZE)
2798 		pr_debug("map '%s': found value_size = %u.\n", map->name, def->value_size);
2799 
2800 	if (def->parts & MAP_DEF_MAX_ENTRIES)
2801 		pr_debug("map '%s': found max_entries = %u.\n", map->name, def->max_entries);
2802 	if (def->parts & MAP_DEF_MAP_FLAGS)
2803 		pr_debug("map '%s': found map_flags = 0x%x.\n", map->name, def->map_flags);
2804 	if (def->parts & MAP_DEF_MAP_EXTRA)
2805 		pr_debug("map '%s': found map_extra = 0x%llx.\n", map->name,
2806 			 (unsigned long long)def->map_extra);
2807 	if (def->parts & MAP_DEF_PINNING)
2808 		pr_debug("map '%s': found pinning = %u.\n", map->name, def->pinning);
2809 	if (def->parts & MAP_DEF_NUMA_NODE)
2810 		pr_debug("map '%s': found numa_node = %u.\n", map->name, def->numa_node);
2811 
2812 	if (def->parts & MAP_DEF_INNER_MAP)
2813 		pr_debug("map '%s': found inner map definition.\n", map->name);
2814 }
2815 
2816 static const char *btf_var_linkage_str(__u32 linkage)
2817 {
2818 	switch (linkage) {
2819 	case BTF_VAR_STATIC: return "static";
2820 	case BTF_VAR_GLOBAL_ALLOCATED: return "global";
2821 	case BTF_VAR_GLOBAL_EXTERN: return "extern";
2822 	default: return "unknown";
2823 	}
2824 }
2825 
2826 static int bpf_object__init_user_btf_map(struct bpf_object *obj,
2827 					 const struct btf_type *sec,
2828 					 int var_idx, int sec_idx,
2829 					 const Elf_Data *data, bool strict,
2830 					 const char *pin_root_path)
2831 {
2832 	struct btf_map_def map_def = {}, inner_def = {};
2833 	const struct btf_type *var, *def;
2834 	const struct btf_var_secinfo *vi;
2835 	const struct btf_var *var_extra;
2836 	const char *map_name;
2837 	struct bpf_map *map;
2838 	int err;
2839 
2840 	vi = btf_var_secinfos(sec) + var_idx;
2841 	var = btf__type_by_id(obj->btf, vi->type);
2842 	var_extra = btf_var(var);
2843 	map_name = btf__name_by_offset(obj->btf, var->name_off);
2844 
2845 	if (map_name == NULL || map_name[0] == '\0') {
2846 		pr_warn("map #%d: empty name.\n", var_idx);
2847 		return -EINVAL;
2848 	}
2849 	if ((__u64)vi->offset + vi->size > data->d_size) {
2850 		pr_warn("map '%s' BTF data is corrupted.\n", map_name);
2851 		return -EINVAL;
2852 	}
2853 	if (!btf_is_var(var)) {
2854 		pr_warn("map '%s': unexpected var kind %s.\n",
2855 			map_name, btf_kind_str(var));
2856 		return -EINVAL;
2857 	}
2858 	if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED) {
2859 		pr_warn("map '%s': unsupported map linkage %s.\n",
2860 			map_name, btf_var_linkage_str(var_extra->linkage));
2861 		return -EOPNOTSUPP;
2862 	}
2863 
2864 	def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
2865 	if (!btf_is_struct(def)) {
2866 		pr_warn("map '%s': unexpected def kind %s.\n",
2867 			map_name, btf_kind_str(var));
2868 		return -EINVAL;
2869 	}
2870 	if (def->size > vi->size) {
2871 		pr_warn("map '%s': invalid def size.\n", map_name);
2872 		return -EINVAL;
2873 	}
2874 
2875 	map = bpf_object__add_map(obj);
2876 	if (IS_ERR(map))
2877 		return PTR_ERR(map);
2878 	map->name = strdup(map_name);
2879 	if (!map->name) {
2880 		pr_warn("map '%s': failed to alloc map name.\n", map_name);
2881 		return -ENOMEM;
2882 	}
2883 	map->libbpf_type = LIBBPF_MAP_UNSPEC;
2884 	map->def.type = BPF_MAP_TYPE_UNSPEC;
2885 	map->sec_idx = sec_idx;
2886 	map->sec_offset = vi->offset;
2887 	map->btf_var_idx = var_idx;
2888 	pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
2889 		 map_name, map->sec_idx, map->sec_offset);
2890 
2891 	err = parse_btf_map_def(map->name, obj->btf, def, strict, &map_def, &inner_def);
2892 	if (err)
2893 		return err;
2894 
2895 	fill_map_from_def(map, &map_def);
2896 
2897 	if (map_def.pinning == LIBBPF_PIN_BY_NAME) {
2898 		err = build_map_pin_path(map, pin_root_path);
2899 		if (err) {
2900 			pr_warn("map '%s': couldn't build pin path.\n", map->name);
2901 			return err;
2902 		}
2903 	}
2904 
2905 	if (map_def.parts & MAP_DEF_INNER_MAP) {
2906 		map->inner_map = calloc(1, sizeof(*map->inner_map));
2907 		if (!map->inner_map)
2908 			return -ENOMEM;
2909 		map->inner_map->fd = create_placeholder_fd();
2910 		if (map->inner_map->fd < 0)
2911 			return map->inner_map->fd;
2912 		map->inner_map->sec_idx = sec_idx;
2913 		map->inner_map->name = malloc(strlen(map_name) + sizeof(".inner") + 1);
2914 		if (!map->inner_map->name)
2915 			return -ENOMEM;
2916 		sprintf(map->inner_map->name, "%s.inner", map_name);
2917 
2918 		fill_map_from_def(map->inner_map, &inner_def);
2919 	}
2920 
2921 	err = map_fill_btf_type_info(obj, map);
2922 	if (err)
2923 		return err;
2924 
2925 	return 0;
2926 }
2927 
2928 static int init_arena_map_data(struct bpf_object *obj, struct bpf_map *map,
2929 			       const char *sec_name, int sec_idx,
2930 			       void *data, size_t data_sz)
2931 {
2932 	const long page_sz = sysconf(_SC_PAGE_SIZE);
2933 	size_t mmap_sz;
2934 
2935 	mmap_sz = bpf_map_mmap_sz(obj->arena_map);
2936 	if (roundup(data_sz, page_sz) > mmap_sz) {
2937 		pr_warn("elf: sec '%s': declared ARENA map size (%zu) is too small to hold global __arena variables of size %zu\n",
2938 			sec_name, mmap_sz, data_sz);
2939 		return -E2BIG;
2940 	}
2941 
2942 	obj->arena_data = malloc(data_sz);
2943 	if (!obj->arena_data)
2944 		return -ENOMEM;
2945 	memcpy(obj->arena_data, data, data_sz);
2946 	obj->arena_data_sz = data_sz;
2947 
2948 	/* make bpf_map__init_value() work for ARENA maps */
2949 	map->mmaped = obj->arena_data;
2950 
2951 	return 0;
2952 }
2953 
2954 static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict,
2955 					  const char *pin_root_path)
2956 {
2957 	const struct btf_type *sec = NULL;
2958 	int nr_types, i, vlen, err;
2959 	const struct btf_type *t;
2960 	const char *name;
2961 	Elf_Data *data;
2962 	Elf_Scn *scn;
2963 
2964 	if (obj->efile.btf_maps_shndx < 0)
2965 		return 0;
2966 
2967 	scn = elf_sec_by_idx(obj, obj->efile.btf_maps_shndx);
2968 	data = elf_sec_data(obj, scn);
2969 	if (!scn || !data) {
2970 		pr_warn("elf: failed to get %s map definitions for %s\n",
2971 			MAPS_ELF_SEC, obj->path);
2972 		return -EINVAL;
2973 	}
2974 
2975 	nr_types = btf__type_cnt(obj->btf);
2976 	for (i = 1; i < nr_types; i++) {
2977 		t = btf__type_by_id(obj->btf, i);
2978 		if (!btf_is_datasec(t))
2979 			continue;
2980 		name = btf__name_by_offset(obj->btf, t->name_off);
2981 		if (strcmp(name, MAPS_ELF_SEC) == 0) {
2982 			sec = t;
2983 			obj->efile.btf_maps_sec_btf_id = i;
2984 			break;
2985 		}
2986 	}
2987 
2988 	if (!sec) {
2989 		pr_warn("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
2990 		return -ENOENT;
2991 	}
2992 
2993 	vlen = btf_vlen(sec);
2994 	for (i = 0; i < vlen; i++) {
2995 		err = bpf_object__init_user_btf_map(obj, sec, i,
2996 						    obj->efile.btf_maps_shndx,
2997 						    data, strict,
2998 						    pin_root_path);
2999 		if (err)
3000 			return err;
3001 	}
3002 
3003 	for (i = 0; i < obj->nr_maps; i++) {
3004 		struct bpf_map *map = &obj->maps[i];
3005 
3006 		if (map->def.type != BPF_MAP_TYPE_ARENA)
3007 			continue;
3008 
3009 		if (obj->arena_map) {
3010 			pr_warn("map '%s': only single ARENA map is supported (map '%s' is also ARENA)\n",
3011 				map->name, obj->arena_map->name);
3012 			return -EINVAL;
3013 		}
3014 		obj->arena_map = map;
3015 
3016 		if (obj->efile.arena_data) {
3017 			err = init_arena_map_data(obj, map, ARENA_SEC, obj->efile.arena_data_shndx,
3018 						  obj->efile.arena_data->d_buf,
3019 						  obj->efile.arena_data->d_size);
3020 			if (err)
3021 				return err;
3022 		}
3023 	}
3024 	if (obj->efile.arena_data && !obj->arena_map) {
3025 		pr_warn("elf: sec '%s': to use global __arena variables the ARENA map should be explicitly declared in SEC(\".maps\")\n",
3026 			ARENA_SEC);
3027 		return -ENOENT;
3028 	}
3029 
3030 	return 0;
3031 }
3032 
3033 static int bpf_object__init_maps(struct bpf_object *obj,
3034 				 const struct bpf_object_open_opts *opts)
3035 {
3036 	const char *pin_root_path;
3037 	bool strict;
3038 	int err = 0;
3039 
3040 	strict = !OPTS_GET(opts, relaxed_maps, false);
3041 	pin_root_path = OPTS_GET(opts, pin_root_path, NULL);
3042 
3043 	err = bpf_object__init_user_btf_maps(obj, strict, pin_root_path);
3044 	err = err ?: bpf_object__init_global_data_maps(obj);
3045 	err = err ?: bpf_object__init_kconfig_map(obj);
3046 	err = err ?: bpf_object_init_struct_ops(obj);
3047 
3048 	return err;
3049 }
3050 
3051 static bool section_have_execinstr(struct bpf_object *obj, int idx)
3052 {
3053 	Elf64_Shdr *sh;
3054 
3055 	sh = elf_sec_hdr(obj, elf_sec_by_idx(obj, idx));
3056 	if (!sh)
3057 		return false;
3058 
3059 	return sh->sh_flags & SHF_EXECINSTR;
3060 }
3061 
3062 static bool starts_with_qmark(const char *s)
3063 {
3064 	return s && s[0] == '?';
3065 }
3066 
3067 static bool btf_needs_sanitization(struct bpf_object *obj)
3068 {
3069 	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
3070 	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
3071 	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
3072 	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
3073 	bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
3074 	bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
3075 	bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
3076 	bool has_qmark_datasec = kernel_supports(obj, FEAT_BTF_QMARK_DATASEC);
3077 
3078 	return !has_func || !has_datasec || !has_func_global || !has_float ||
3079 	       !has_decl_tag || !has_type_tag || !has_enum64 || !has_qmark_datasec;
3080 }
3081 
3082 static int bpf_object__sanitize_btf(struct bpf_object *obj, struct btf *btf)
3083 {
3084 	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
3085 	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
3086 	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
3087 	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
3088 	bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
3089 	bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
3090 	bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
3091 	bool has_qmark_datasec = kernel_supports(obj, FEAT_BTF_QMARK_DATASEC);
3092 	int enum64_placeholder_id = 0;
3093 	struct btf_type *t;
3094 	int i, j, vlen;
3095 
3096 	for (i = 1; i < btf__type_cnt(btf); i++) {
3097 		t = (struct btf_type *)btf__type_by_id(btf, i);
3098 
3099 		if ((!has_datasec && btf_is_var(t)) || (!has_decl_tag && btf_is_decl_tag(t))) {
3100 			/* replace VAR/DECL_TAG with INT */
3101 			t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
3102 			/*
3103 			 * using size = 1 is the safest choice, 4 will be too
3104 			 * big and cause kernel BTF validation failure if
3105 			 * original variable took less than 4 bytes
3106 			 */
3107 			t->size = 1;
3108 			*(int *)(t + 1) = BTF_INT_ENC(0, 0, 8);
3109 		} else if (!has_datasec && btf_is_datasec(t)) {
3110 			/* replace DATASEC with STRUCT */
3111 			const struct btf_var_secinfo *v = btf_var_secinfos(t);
3112 			struct btf_member *m = btf_members(t);
3113 			struct btf_type *vt;
3114 			char *name;
3115 
3116 			name = (char *)btf__name_by_offset(btf, t->name_off);
3117 			while (*name) {
3118 				if (*name == '.' || *name == '?')
3119 					*name = '_';
3120 				name++;
3121 			}
3122 
3123 			vlen = btf_vlen(t);
3124 			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
3125 			for (j = 0; j < vlen; j++, v++, m++) {
3126 				/* order of field assignments is important */
3127 				m->offset = v->offset * 8;
3128 				m->type = v->type;
3129 				/* preserve variable name as member name */
3130 				vt = (void *)btf__type_by_id(btf, v->type);
3131 				m->name_off = vt->name_off;
3132 			}
3133 		} else if (!has_qmark_datasec && btf_is_datasec(t) &&
3134 			   starts_with_qmark(btf__name_by_offset(btf, t->name_off))) {
3135 			/* replace '?' prefix with '_' for DATASEC names */
3136 			char *name;
3137 
3138 			name = (char *)btf__name_by_offset(btf, t->name_off);
3139 			if (name[0] == '?')
3140 				name[0] = '_';
3141 		} else if (!has_func && btf_is_func_proto(t)) {
3142 			/* replace FUNC_PROTO with ENUM */
3143 			vlen = btf_vlen(t);
3144 			t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
3145 			t->size = sizeof(__u32); /* kernel enforced */
3146 		} else if (!has_func && btf_is_func(t)) {
3147 			/* replace FUNC with TYPEDEF */
3148 			t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
3149 		} else if (!has_func_global && btf_is_func(t)) {
3150 			/* replace BTF_FUNC_GLOBAL with BTF_FUNC_STATIC */
3151 			t->info = BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0);
3152 		} else if (!has_float && btf_is_float(t)) {
3153 			/* replace FLOAT with an equally-sized empty STRUCT;
3154 			 * since C compilers do not accept e.g. "float" as a
3155 			 * valid struct name, make it anonymous
3156 			 */
3157 			t->name_off = 0;
3158 			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, 0);
3159 		} else if (!has_type_tag && btf_is_type_tag(t)) {
3160 			/* replace TYPE_TAG with a CONST */
3161 			t->name_off = 0;
3162 			t->info = BTF_INFO_ENC(BTF_KIND_CONST, 0, 0);
3163 		} else if (!has_enum64 && btf_is_enum(t)) {
3164 			/* clear the kflag */
3165 			t->info = btf_type_info(btf_kind(t), btf_vlen(t), false);
3166 		} else if (!has_enum64 && btf_is_enum64(t)) {
3167 			/* replace ENUM64 with a union */
3168 			struct btf_member *m;
3169 
3170 			if (enum64_placeholder_id == 0) {
3171 				enum64_placeholder_id = btf__add_int(btf, "enum64_placeholder", 1, 0);
3172 				if (enum64_placeholder_id < 0)
3173 					return enum64_placeholder_id;
3174 
3175 				t = (struct btf_type *)btf__type_by_id(btf, i);
3176 			}
3177 
3178 			m = btf_members(t);
3179 			vlen = btf_vlen(t);
3180 			t->info = BTF_INFO_ENC(BTF_KIND_UNION, 0, vlen);
3181 			for (j = 0; j < vlen; j++, m++) {
3182 				m->type = enum64_placeholder_id;
3183 				m->offset = 0;
3184 			}
3185 		}
3186 	}
3187 
3188 	return 0;
3189 }
3190 
3191 static bool libbpf_needs_btf(const struct bpf_object *obj)
3192 {
3193 	return obj->efile.btf_maps_shndx >= 0 ||
3194 	       obj->efile.has_st_ops ||
3195 	       obj->nr_extern > 0;
3196 }
3197 
3198 static bool kernel_needs_btf(const struct bpf_object *obj)
3199 {
3200 	return obj->efile.has_st_ops;
3201 }
3202 
3203 static int bpf_object__init_btf(struct bpf_object *obj,
3204 				Elf_Data *btf_data,
3205 				Elf_Data *btf_ext_data)
3206 {
3207 	int err = -ENOENT;
3208 
3209 	if (btf_data) {
3210 		obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
3211 		err = libbpf_get_error(obj->btf);
3212 		if (err) {
3213 			obj->btf = NULL;
3214 			pr_warn("Error loading ELF section %s: %d.\n", BTF_ELF_SEC, err);
3215 			goto out;
3216 		}
3217 		/* enforce 8-byte pointers for BPF-targeted BTFs */
3218 		btf__set_pointer_size(obj->btf, 8);
3219 	}
3220 	if (btf_ext_data) {
3221 		struct btf_ext_info *ext_segs[3];
3222 		int seg_num, sec_num;
3223 
3224 		if (!obj->btf) {
3225 			pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
3226 				 BTF_EXT_ELF_SEC, BTF_ELF_SEC);
3227 			goto out;
3228 		}
3229 		obj->btf_ext = btf_ext__new(btf_ext_data->d_buf, btf_ext_data->d_size);
3230 		err = libbpf_get_error(obj->btf_ext);
3231 		if (err) {
3232 			pr_warn("Error loading ELF section %s: %d. Ignored and continue.\n",
3233 				BTF_EXT_ELF_SEC, err);
3234 			obj->btf_ext = NULL;
3235 			goto out;
3236 		}
3237 
3238 		/* setup .BTF.ext to ELF section mapping */
3239 		ext_segs[0] = &obj->btf_ext->func_info;
3240 		ext_segs[1] = &obj->btf_ext->line_info;
3241 		ext_segs[2] = &obj->btf_ext->core_relo_info;
3242 		for (seg_num = 0; seg_num < ARRAY_SIZE(ext_segs); seg_num++) {
3243 			struct btf_ext_info *seg = ext_segs[seg_num];
3244 			const struct btf_ext_info_sec *sec;
3245 			const char *sec_name;
3246 			Elf_Scn *scn;
3247 
3248 			if (seg->sec_cnt == 0)
3249 				continue;
3250 
3251 			seg->sec_idxs = calloc(seg->sec_cnt, sizeof(*seg->sec_idxs));
3252 			if (!seg->sec_idxs) {
3253 				err = -ENOMEM;
3254 				goto out;
3255 			}
3256 
3257 			sec_num = 0;
3258 			for_each_btf_ext_sec(seg, sec) {
3259 				/* preventively increment index to avoid doing
3260 				 * this before every continue below
3261 				 */
3262 				sec_num++;
3263 
3264 				sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
3265 				if (str_is_empty(sec_name))
3266 					continue;
3267 				scn = elf_sec_by_name(obj, sec_name);
3268 				if (!scn)
3269 					continue;
3270 
3271 				seg->sec_idxs[sec_num - 1] = elf_ndxscn(scn);
3272 			}
3273 		}
3274 	}
3275 out:
3276 	if (err && libbpf_needs_btf(obj)) {
3277 		pr_warn("BTF is required, but is missing or corrupted.\n");
3278 		return err;
3279 	}
3280 	return 0;
3281 }
3282 
3283 static int compare_vsi_off(const void *_a, const void *_b)
3284 {
3285 	const struct btf_var_secinfo *a = _a;
3286 	const struct btf_var_secinfo *b = _b;
3287 
3288 	return a->offset - b->offset;
3289 }
3290 
3291 static int btf_fixup_datasec(struct bpf_object *obj, struct btf *btf,
3292 			     struct btf_type *t)
3293 {
3294 	__u32 size = 0, i, vars = btf_vlen(t);
3295 	const char *sec_name = btf__name_by_offset(btf, t->name_off);
3296 	struct btf_var_secinfo *vsi;
3297 	bool fixup_offsets = false;
3298 	int err;
3299 
3300 	if (!sec_name) {
3301 		pr_debug("No name found in string section for DATASEC kind.\n");
3302 		return -ENOENT;
3303 	}
3304 
3305 	/* Extern-backing datasecs (.ksyms, .kconfig) have their size and
3306 	 * variable offsets set at the previous step. Further, not every
3307 	 * extern BTF VAR has corresponding ELF symbol preserved, so we skip
3308 	 * all fixups altogether for such sections and go straight to sorting
3309 	 * VARs within their DATASEC.
3310 	 */
3311 	if (strcmp(sec_name, KCONFIG_SEC) == 0 || strcmp(sec_name, KSYMS_SEC) == 0)
3312 		goto sort_vars;
3313 
3314 	/* Clang leaves DATASEC size and VAR offsets as zeroes, so we need to
3315 	 * fix this up. But BPF static linker already fixes this up and fills
3316 	 * all the sizes and offsets during static linking. So this step has
3317 	 * to be optional. But the STV_HIDDEN handling is non-optional for any
3318 	 * non-extern DATASEC, so the variable fixup loop below handles both
3319 	 * functions at the same time, paying the cost of BTF VAR <-> ELF
3320 	 * symbol matching just once.
3321 	 */
3322 	if (t->size == 0) {
3323 		err = find_elf_sec_sz(obj, sec_name, &size);
3324 		if (err || !size) {
3325 			pr_debug("sec '%s': failed to determine size from ELF: size %u, err %d\n",
3326 				 sec_name, size, err);
3327 			return -ENOENT;
3328 		}
3329 
3330 		t->size = size;
3331 		fixup_offsets = true;
3332 	}
3333 
3334 	for (i = 0, vsi = btf_var_secinfos(t); i < vars; i++, vsi++) {
3335 		const struct btf_type *t_var;
3336 		struct btf_var *var;
3337 		const char *var_name;
3338 		Elf64_Sym *sym;
3339 
3340 		t_var = btf__type_by_id(btf, vsi->type);
3341 		if (!t_var || !btf_is_var(t_var)) {
3342 			pr_debug("sec '%s': unexpected non-VAR type found\n", sec_name);
3343 			return -EINVAL;
3344 		}
3345 
3346 		var = btf_var(t_var);
3347 		if (var->linkage == BTF_VAR_STATIC || var->linkage == BTF_VAR_GLOBAL_EXTERN)
3348 			continue;
3349 
3350 		var_name = btf__name_by_offset(btf, t_var->name_off);
3351 		if (!var_name) {
3352 			pr_debug("sec '%s': failed to find name of DATASEC's member #%d\n",
3353 				 sec_name, i);
3354 			return -ENOENT;
3355 		}
3356 
3357 		sym = find_elf_var_sym(obj, var_name);
3358 		if (IS_ERR(sym)) {
3359 			pr_debug("sec '%s': failed to find ELF symbol for VAR '%s'\n",
3360 				 sec_name, var_name);
3361 			return -ENOENT;
3362 		}
3363 
3364 		if (fixup_offsets)
3365 			vsi->offset = sym->st_value;
3366 
3367 		/* if variable is a global/weak symbol, but has restricted
3368 		 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF VAR
3369 		 * as static. This follows similar logic for functions (BPF
3370 		 * subprogs) and influences libbpf's further decisions about
3371 		 * whether to make global data BPF array maps as
3372 		 * BPF_F_MMAPABLE.
3373 		 */
3374 		if (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
3375 		    || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL)
3376 			var->linkage = BTF_VAR_STATIC;
3377 	}
3378 
3379 sort_vars:
3380 	qsort(btf_var_secinfos(t), vars, sizeof(*vsi), compare_vsi_off);
3381 	return 0;
3382 }
3383 
3384 static int bpf_object_fixup_btf(struct bpf_object *obj)
3385 {
3386 	int i, n, err = 0;
3387 
3388 	if (!obj->btf)
3389 		return 0;
3390 
3391 	n = btf__type_cnt(obj->btf);
3392 	for (i = 1; i < n; i++) {
3393 		struct btf_type *t = btf_type_by_id(obj->btf, i);
3394 
3395 		/* Loader needs to fix up some of the things compiler
3396 		 * couldn't get its hands on while emitting BTF. This
3397 		 * is section size and global variable offset. We use
3398 		 * the info from the ELF itself for this purpose.
3399 		 */
3400 		if (btf_is_datasec(t)) {
3401 			err = btf_fixup_datasec(obj, obj->btf, t);
3402 			if (err)
3403 				return err;
3404 		}
3405 	}
3406 
3407 	return 0;
3408 }
3409 
3410 static bool prog_needs_vmlinux_btf(struct bpf_program *prog)
3411 {
3412 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
3413 	    prog->type == BPF_PROG_TYPE_LSM)
3414 		return true;
3415 
3416 	/* BPF_PROG_TYPE_TRACING programs which do not attach to other programs
3417 	 * also need vmlinux BTF
3418 	 */
3419 	if (prog->type == BPF_PROG_TYPE_TRACING && !prog->attach_prog_fd)
3420 		return true;
3421 
3422 	return false;
3423 }
3424 
3425 static bool map_needs_vmlinux_btf(struct bpf_map *map)
3426 {
3427 	return bpf_map__is_struct_ops(map);
3428 }
3429 
3430 static bool obj_needs_vmlinux_btf(const struct bpf_object *obj)
3431 {
3432 	struct bpf_program *prog;
3433 	struct bpf_map *map;
3434 	int i;
3435 
3436 	/* CO-RE relocations need kernel BTF, only when btf_custom_path
3437 	 * is not specified
3438 	 */
3439 	if (obj->btf_ext && obj->btf_ext->core_relo_info.len && !obj->btf_custom_path)
3440 		return true;
3441 
3442 	/* Support for typed ksyms needs kernel BTF */
3443 	for (i = 0; i < obj->nr_extern; i++) {
3444 		const struct extern_desc *ext;
3445 
3446 		ext = &obj->externs[i];
3447 		if (ext->type == EXT_KSYM && ext->ksym.type_id)
3448 			return true;
3449 	}
3450 
3451 	bpf_object__for_each_program(prog, obj) {
3452 		if (!prog->autoload)
3453 			continue;
3454 		if (prog_needs_vmlinux_btf(prog))
3455 			return true;
3456 	}
3457 
3458 	bpf_object__for_each_map(map, obj) {
3459 		if (map_needs_vmlinux_btf(map))
3460 			return true;
3461 	}
3462 
3463 	return false;
3464 }
3465 
3466 static int bpf_object__load_vmlinux_btf(struct bpf_object *obj, bool force)
3467 {
3468 	int err;
3469 
3470 	/* btf_vmlinux could be loaded earlier */
3471 	if (obj->btf_vmlinux || obj->gen_loader)
3472 		return 0;
3473 
3474 	if (!force && !obj_needs_vmlinux_btf(obj))
3475 		return 0;
3476 
3477 	obj->btf_vmlinux = btf__load_vmlinux_btf();
3478 	err = libbpf_get_error(obj->btf_vmlinux);
3479 	if (err) {
3480 		pr_warn("Error loading vmlinux BTF: %d\n", err);
3481 		obj->btf_vmlinux = NULL;
3482 		return err;
3483 	}
3484 	return 0;
3485 }
3486 
3487 static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
3488 {
3489 	struct btf *kern_btf = obj->btf;
3490 	bool btf_mandatory, sanitize;
3491 	int i, err = 0;
3492 
3493 	if (!obj->btf)
3494 		return 0;
3495 
3496 	if (!kernel_supports(obj, FEAT_BTF)) {
3497 		if (kernel_needs_btf(obj)) {
3498 			err = -EOPNOTSUPP;
3499 			goto report;
3500 		}
3501 		pr_debug("Kernel doesn't support BTF, skipping uploading it.\n");
3502 		return 0;
3503 	}
3504 
3505 	/* Even though some subprogs are global/weak, user might prefer more
3506 	 * permissive BPF verification process that BPF verifier performs for
3507 	 * static functions, taking into account more context from the caller
3508 	 * functions. In such case, they need to mark such subprogs with
3509 	 * __attribute__((visibility("hidden"))) and libbpf will adjust
3510 	 * corresponding FUNC BTF type to be marked as static and trigger more
3511 	 * involved BPF verification process.
3512 	 */
3513 	for (i = 0; i < obj->nr_programs; i++) {
3514 		struct bpf_program *prog = &obj->programs[i];
3515 		struct btf_type *t;
3516 		const char *name;
3517 		int j, n;
3518 
3519 		if (!prog->mark_btf_static || !prog_is_subprog(obj, prog))
3520 			continue;
3521 
3522 		n = btf__type_cnt(obj->btf);
3523 		for (j = 1; j < n; j++) {
3524 			t = btf_type_by_id(obj->btf, j);
3525 			if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL)
3526 				continue;
3527 
3528 			name = btf__str_by_offset(obj->btf, t->name_off);
3529 			if (strcmp(name, prog->name) != 0)
3530 				continue;
3531 
3532 			t->info = btf_type_info(BTF_KIND_FUNC, BTF_FUNC_STATIC, 0);
3533 			break;
3534 		}
3535 	}
3536 
3537 	sanitize = btf_needs_sanitization(obj);
3538 	if (sanitize) {
3539 		const void *raw_data;
3540 		__u32 sz;
3541 
3542 		/* clone BTF to sanitize a copy and leave the original intact */
3543 		raw_data = btf__raw_data(obj->btf, &sz);
3544 		kern_btf = btf__new(raw_data, sz);
3545 		err = libbpf_get_error(kern_btf);
3546 		if (err)
3547 			return err;
3548 
3549 		/* enforce 8-byte pointers for BPF-targeted BTFs */
3550 		btf__set_pointer_size(obj->btf, 8);
3551 		err = bpf_object__sanitize_btf(obj, kern_btf);
3552 		if (err)
3553 			return err;
3554 	}
3555 
3556 	if (obj->gen_loader) {
3557 		__u32 raw_size = 0;
3558 		const void *raw_data = btf__raw_data(kern_btf, &raw_size);
3559 
3560 		if (!raw_data)
3561 			return -ENOMEM;
3562 		bpf_gen__load_btf(obj->gen_loader, raw_data, raw_size);
3563 		/* Pretend to have valid FD to pass various fd >= 0 checks.
3564 		 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
3565 		 */
3566 		btf__set_fd(kern_btf, 0);
3567 	} else {
3568 		/* currently BPF_BTF_LOAD only supports log_level 1 */
3569 		err = btf_load_into_kernel(kern_btf, obj->log_buf, obj->log_size,
3570 					   obj->log_level ? 1 : 0, obj->token_fd);
3571 	}
3572 	if (sanitize) {
3573 		if (!err) {
3574 			/* move fd to libbpf's BTF */
3575 			btf__set_fd(obj->btf, btf__fd(kern_btf));
3576 			btf__set_fd(kern_btf, -1);
3577 		}
3578 		btf__free(kern_btf);
3579 	}
3580 report:
3581 	if (err) {
3582 		btf_mandatory = kernel_needs_btf(obj);
3583 		pr_warn("Error loading .BTF into kernel: %d. %s\n", err,
3584 			btf_mandatory ? "BTF is mandatory, can't proceed."
3585 				      : "BTF is optional, ignoring.");
3586 		if (!btf_mandatory)
3587 			err = 0;
3588 	}
3589 	return err;
3590 }
3591 
3592 static const char *elf_sym_str(const struct bpf_object *obj, size_t off)
3593 {
3594 	const char *name;
3595 
3596 	name = elf_strptr(obj->efile.elf, obj->efile.strtabidx, off);
3597 	if (!name) {
3598 		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3599 			off, obj->path, elf_errmsg(-1));
3600 		return NULL;
3601 	}
3602 
3603 	return name;
3604 }
3605 
3606 static const char *elf_sec_str(const struct bpf_object *obj, size_t off)
3607 {
3608 	const char *name;
3609 
3610 	name = elf_strptr(obj->efile.elf, obj->efile.shstrndx, off);
3611 	if (!name) {
3612 		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3613 			off, obj->path, elf_errmsg(-1));
3614 		return NULL;
3615 	}
3616 
3617 	return name;
3618 }
3619 
3620 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx)
3621 {
3622 	Elf_Scn *scn;
3623 
3624 	scn = elf_getscn(obj->efile.elf, idx);
3625 	if (!scn) {
3626 		pr_warn("elf: failed to get section(%zu) from %s: %s\n",
3627 			idx, obj->path, elf_errmsg(-1));
3628 		return NULL;
3629 	}
3630 	return scn;
3631 }
3632 
3633 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name)
3634 {
3635 	Elf_Scn *scn = NULL;
3636 	Elf *elf = obj->efile.elf;
3637 	const char *sec_name;
3638 
3639 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3640 		sec_name = elf_sec_name(obj, scn);
3641 		if (!sec_name)
3642 			return NULL;
3643 
3644 		if (strcmp(sec_name, name) != 0)
3645 			continue;
3646 
3647 		return scn;
3648 	}
3649 	return NULL;
3650 }
3651 
3652 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn)
3653 {
3654 	Elf64_Shdr *shdr;
3655 
3656 	if (!scn)
3657 		return NULL;
3658 
3659 	shdr = elf64_getshdr(scn);
3660 	if (!shdr) {
3661 		pr_warn("elf: failed to get section(%zu) header from %s: %s\n",
3662 			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3663 		return NULL;
3664 	}
3665 
3666 	return shdr;
3667 }
3668 
3669 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn)
3670 {
3671 	const char *name;
3672 	Elf64_Shdr *sh;
3673 
3674 	if (!scn)
3675 		return NULL;
3676 
3677 	sh = elf_sec_hdr(obj, scn);
3678 	if (!sh)
3679 		return NULL;
3680 
3681 	name = elf_sec_str(obj, sh->sh_name);
3682 	if (!name) {
3683 		pr_warn("elf: failed to get section(%zu) name from %s: %s\n",
3684 			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3685 		return NULL;
3686 	}
3687 
3688 	return name;
3689 }
3690 
3691 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn)
3692 {
3693 	Elf_Data *data;
3694 
3695 	if (!scn)
3696 		return NULL;
3697 
3698 	data = elf_getdata(scn, 0);
3699 	if (!data) {
3700 		pr_warn("elf: failed to get section(%zu) %s data from %s: %s\n",
3701 			elf_ndxscn(scn), elf_sec_name(obj, scn) ?: "<?>",
3702 			obj->path, elf_errmsg(-1));
3703 		return NULL;
3704 	}
3705 
3706 	return data;
3707 }
3708 
3709 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx)
3710 {
3711 	if (idx >= obj->efile.symbols->d_size / sizeof(Elf64_Sym))
3712 		return NULL;
3713 
3714 	return (Elf64_Sym *)obj->efile.symbols->d_buf + idx;
3715 }
3716 
3717 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx)
3718 {
3719 	if (idx >= data->d_size / sizeof(Elf64_Rel))
3720 		return NULL;
3721 
3722 	return (Elf64_Rel *)data->d_buf + idx;
3723 }
3724 
3725 static bool is_sec_name_dwarf(const char *name)
3726 {
3727 	/* approximation, but the actual list is too long */
3728 	return str_has_pfx(name, ".debug_");
3729 }
3730 
3731 static bool ignore_elf_section(Elf64_Shdr *hdr, const char *name)
3732 {
3733 	/* no special handling of .strtab */
3734 	if (hdr->sh_type == SHT_STRTAB)
3735 		return true;
3736 
3737 	/* ignore .llvm_addrsig section as well */
3738 	if (hdr->sh_type == SHT_LLVM_ADDRSIG)
3739 		return true;
3740 
3741 	/* no subprograms will lead to an empty .text section, ignore it */
3742 	if (hdr->sh_type == SHT_PROGBITS && hdr->sh_size == 0 &&
3743 	    strcmp(name, ".text") == 0)
3744 		return true;
3745 
3746 	/* DWARF sections */
3747 	if (is_sec_name_dwarf(name))
3748 		return true;
3749 
3750 	if (str_has_pfx(name, ".rel")) {
3751 		name += sizeof(".rel") - 1;
3752 		/* DWARF section relocations */
3753 		if (is_sec_name_dwarf(name))
3754 			return true;
3755 
3756 		/* .BTF and .BTF.ext don't need relocations */
3757 		if (strcmp(name, BTF_ELF_SEC) == 0 ||
3758 		    strcmp(name, BTF_EXT_ELF_SEC) == 0)
3759 			return true;
3760 	}
3761 
3762 	return false;
3763 }
3764 
3765 static int cmp_progs(const void *_a, const void *_b)
3766 {
3767 	const struct bpf_program *a = _a;
3768 	const struct bpf_program *b = _b;
3769 
3770 	if (a->sec_idx != b->sec_idx)
3771 		return a->sec_idx < b->sec_idx ? -1 : 1;
3772 
3773 	/* sec_insn_off can't be the same within the section */
3774 	return a->sec_insn_off < b->sec_insn_off ? -1 : 1;
3775 }
3776 
3777 static int bpf_object__elf_collect(struct bpf_object *obj)
3778 {
3779 	struct elf_sec_desc *sec_desc;
3780 	Elf *elf = obj->efile.elf;
3781 	Elf_Data *btf_ext_data = NULL;
3782 	Elf_Data *btf_data = NULL;
3783 	int idx = 0, err = 0;
3784 	const char *name;
3785 	Elf_Data *data;
3786 	Elf_Scn *scn;
3787 	Elf64_Shdr *sh;
3788 
3789 	/* ELF section indices are 0-based, but sec #0 is special "invalid"
3790 	 * section. Since section count retrieved by elf_getshdrnum() does
3791 	 * include sec #0, it is already the necessary size of an array to keep
3792 	 * all the sections.
3793 	 */
3794 	if (elf_getshdrnum(obj->efile.elf, &obj->efile.sec_cnt)) {
3795 		pr_warn("elf: failed to get the number of sections for %s: %s\n",
3796 			obj->path, elf_errmsg(-1));
3797 		return -LIBBPF_ERRNO__FORMAT;
3798 	}
3799 	obj->efile.secs = calloc(obj->efile.sec_cnt, sizeof(*obj->efile.secs));
3800 	if (!obj->efile.secs)
3801 		return -ENOMEM;
3802 
3803 	/* a bunch of ELF parsing functionality depends on processing symbols,
3804 	 * so do the first pass and find the symbol table
3805 	 */
3806 	scn = NULL;
3807 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3808 		sh = elf_sec_hdr(obj, scn);
3809 		if (!sh)
3810 			return -LIBBPF_ERRNO__FORMAT;
3811 
3812 		if (sh->sh_type == SHT_SYMTAB) {
3813 			if (obj->efile.symbols) {
3814 				pr_warn("elf: multiple symbol tables in %s\n", obj->path);
3815 				return -LIBBPF_ERRNO__FORMAT;
3816 			}
3817 
3818 			data = elf_sec_data(obj, scn);
3819 			if (!data)
3820 				return -LIBBPF_ERRNO__FORMAT;
3821 
3822 			idx = elf_ndxscn(scn);
3823 
3824 			obj->efile.symbols = data;
3825 			obj->efile.symbols_shndx = idx;
3826 			obj->efile.strtabidx = sh->sh_link;
3827 		}
3828 	}
3829 
3830 	if (!obj->efile.symbols) {
3831 		pr_warn("elf: couldn't find symbol table in %s, stripped object file?\n",
3832 			obj->path);
3833 		return -ENOENT;
3834 	}
3835 
3836 	scn = NULL;
3837 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3838 		idx = elf_ndxscn(scn);
3839 		sec_desc = &obj->efile.secs[idx];
3840 
3841 		sh = elf_sec_hdr(obj, scn);
3842 		if (!sh)
3843 			return -LIBBPF_ERRNO__FORMAT;
3844 
3845 		name = elf_sec_str(obj, sh->sh_name);
3846 		if (!name)
3847 			return -LIBBPF_ERRNO__FORMAT;
3848 
3849 		if (ignore_elf_section(sh, name))
3850 			continue;
3851 
3852 		data = elf_sec_data(obj, scn);
3853 		if (!data)
3854 			return -LIBBPF_ERRNO__FORMAT;
3855 
3856 		pr_debug("elf: section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
3857 			 idx, name, (unsigned long)data->d_size,
3858 			 (int)sh->sh_link, (unsigned long)sh->sh_flags,
3859 			 (int)sh->sh_type);
3860 
3861 		if (strcmp(name, "license") == 0) {
3862 			err = bpf_object__init_license(obj, data->d_buf, data->d_size);
3863 			if (err)
3864 				return err;
3865 		} else if (strcmp(name, "version") == 0) {
3866 			err = bpf_object__init_kversion(obj, data->d_buf, data->d_size);
3867 			if (err)
3868 				return err;
3869 		} else if (strcmp(name, "maps") == 0) {
3870 			pr_warn("elf: legacy map definitions in 'maps' section are not supported by libbpf v1.0+\n");
3871 			return -ENOTSUP;
3872 		} else if (strcmp(name, MAPS_ELF_SEC) == 0) {
3873 			obj->efile.btf_maps_shndx = idx;
3874 		} else if (strcmp(name, BTF_ELF_SEC) == 0) {
3875 			if (sh->sh_type != SHT_PROGBITS)
3876 				return -LIBBPF_ERRNO__FORMAT;
3877 			btf_data = data;
3878 		} else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
3879 			if (sh->sh_type != SHT_PROGBITS)
3880 				return -LIBBPF_ERRNO__FORMAT;
3881 			btf_ext_data = data;
3882 		} else if (sh->sh_type == SHT_SYMTAB) {
3883 			/* already processed during the first pass above */
3884 		} else if (sh->sh_type == SHT_PROGBITS && data->d_size > 0) {
3885 			if (sh->sh_flags & SHF_EXECINSTR) {
3886 				if (strcmp(name, ".text") == 0)
3887 					obj->efile.text_shndx = idx;
3888 				err = bpf_object__add_programs(obj, data, name, idx);
3889 				if (err)
3890 					return err;
3891 			} else if (strcmp(name, DATA_SEC) == 0 ||
3892 				   str_has_pfx(name, DATA_SEC ".")) {
3893 				sec_desc->sec_type = SEC_DATA;
3894 				sec_desc->shdr = sh;
3895 				sec_desc->data = data;
3896 			} else if (strcmp(name, RODATA_SEC) == 0 ||
3897 				   str_has_pfx(name, RODATA_SEC ".")) {
3898 				sec_desc->sec_type = SEC_RODATA;
3899 				sec_desc->shdr = sh;
3900 				sec_desc->data = data;
3901 			} else if (strcmp(name, STRUCT_OPS_SEC) == 0 ||
3902 				   strcmp(name, STRUCT_OPS_LINK_SEC) == 0 ||
3903 				   strcmp(name, "?" STRUCT_OPS_SEC) == 0 ||
3904 				   strcmp(name, "?" STRUCT_OPS_LINK_SEC) == 0) {
3905 				sec_desc->sec_type = SEC_ST_OPS;
3906 				sec_desc->shdr = sh;
3907 				sec_desc->data = data;
3908 				obj->efile.has_st_ops = true;
3909 			} else if (strcmp(name, ARENA_SEC) == 0) {
3910 				obj->efile.arena_data = data;
3911 				obj->efile.arena_data_shndx = idx;
3912 			} else {
3913 				pr_info("elf: skipping unrecognized data section(%d) %s\n",
3914 					idx, name);
3915 			}
3916 		} else if (sh->sh_type == SHT_REL) {
3917 			int targ_sec_idx = sh->sh_info; /* points to other section */
3918 
3919 			if (sh->sh_entsize != sizeof(Elf64_Rel) ||
3920 			    targ_sec_idx >= obj->efile.sec_cnt)
3921 				return -LIBBPF_ERRNO__FORMAT;
3922 
3923 			/* Only do relo for section with exec instructions */
3924 			if (!section_have_execinstr(obj, targ_sec_idx) &&
3925 			    strcmp(name, ".rel" STRUCT_OPS_SEC) &&
3926 			    strcmp(name, ".rel" STRUCT_OPS_LINK_SEC) &&
3927 			    strcmp(name, ".rel?" STRUCT_OPS_SEC) &&
3928 			    strcmp(name, ".rel?" STRUCT_OPS_LINK_SEC) &&
3929 			    strcmp(name, ".rel" MAPS_ELF_SEC)) {
3930 				pr_info("elf: skipping relo section(%d) %s for section(%d) %s\n",
3931 					idx, name, targ_sec_idx,
3932 					elf_sec_name(obj, elf_sec_by_idx(obj, targ_sec_idx)) ?: "<?>");
3933 				continue;
3934 			}
3935 
3936 			sec_desc->sec_type = SEC_RELO;
3937 			sec_desc->shdr = sh;
3938 			sec_desc->data = data;
3939 		} else if (sh->sh_type == SHT_NOBITS && (strcmp(name, BSS_SEC) == 0 ||
3940 							 str_has_pfx(name, BSS_SEC "."))) {
3941 			sec_desc->sec_type = SEC_BSS;
3942 			sec_desc->shdr = sh;
3943 			sec_desc->data = data;
3944 		} else {
3945 			pr_info("elf: skipping section(%d) %s (size %zu)\n", idx, name,
3946 				(size_t)sh->sh_size);
3947 		}
3948 	}
3949 
3950 	if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) {
3951 		pr_warn("elf: symbol strings section missing or invalid in %s\n", obj->path);
3952 		return -LIBBPF_ERRNO__FORMAT;
3953 	}
3954 
3955 	/* sort BPF programs by section name and in-section instruction offset
3956 	 * for faster search
3957 	 */
3958 	if (obj->nr_programs)
3959 		qsort(obj->programs, obj->nr_programs, sizeof(*obj->programs), cmp_progs);
3960 
3961 	return bpf_object__init_btf(obj, btf_data, btf_ext_data);
3962 }
3963 
3964 static bool sym_is_extern(const Elf64_Sym *sym)
3965 {
3966 	int bind = ELF64_ST_BIND(sym->st_info);
3967 	/* externs are symbols w/ type=NOTYPE, bind=GLOBAL|WEAK, section=UND */
3968 	return sym->st_shndx == SHN_UNDEF &&
3969 	       (bind == STB_GLOBAL || bind == STB_WEAK) &&
3970 	       ELF64_ST_TYPE(sym->st_info) == STT_NOTYPE;
3971 }
3972 
3973 static bool sym_is_subprog(const Elf64_Sym *sym, int text_shndx)
3974 {
3975 	int bind = ELF64_ST_BIND(sym->st_info);
3976 	int type = ELF64_ST_TYPE(sym->st_info);
3977 
3978 	/* in .text section */
3979 	if (sym->st_shndx != text_shndx)
3980 		return false;
3981 
3982 	/* local function */
3983 	if (bind == STB_LOCAL && type == STT_SECTION)
3984 		return true;
3985 
3986 	/* global function */
3987 	return bind == STB_GLOBAL && type == STT_FUNC;
3988 }
3989 
3990 static int find_extern_btf_id(const struct btf *btf, const char *ext_name)
3991 {
3992 	const struct btf_type *t;
3993 	const char *tname;
3994 	int i, n;
3995 
3996 	if (!btf)
3997 		return -ESRCH;
3998 
3999 	n = btf__type_cnt(btf);
4000 	for (i = 1; i < n; i++) {
4001 		t = btf__type_by_id(btf, i);
4002 
4003 		if (!btf_is_var(t) && !btf_is_func(t))
4004 			continue;
4005 
4006 		tname = btf__name_by_offset(btf, t->name_off);
4007 		if (strcmp(tname, ext_name))
4008 			continue;
4009 
4010 		if (btf_is_var(t) &&
4011 		    btf_var(t)->linkage != BTF_VAR_GLOBAL_EXTERN)
4012 			return -EINVAL;
4013 
4014 		if (btf_is_func(t) && btf_func_linkage(t) != BTF_FUNC_EXTERN)
4015 			return -EINVAL;
4016 
4017 		return i;
4018 	}
4019 
4020 	return -ENOENT;
4021 }
4022 
4023 static int find_extern_sec_btf_id(struct btf *btf, int ext_btf_id) {
4024 	const struct btf_var_secinfo *vs;
4025 	const struct btf_type *t;
4026 	int i, j, n;
4027 
4028 	if (!btf)
4029 		return -ESRCH;
4030 
4031 	n = btf__type_cnt(btf);
4032 	for (i = 1; i < n; i++) {
4033 		t = btf__type_by_id(btf, i);
4034 
4035 		if (!btf_is_datasec(t))
4036 			continue;
4037 
4038 		vs = btf_var_secinfos(t);
4039 		for (j = 0; j < btf_vlen(t); j++, vs++) {
4040 			if (vs->type == ext_btf_id)
4041 				return i;
4042 		}
4043 	}
4044 
4045 	return -ENOENT;
4046 }
4047 
4048 static enum kcfg_type find_kcfg_type(const struct btf *btf, int id,
4049 				     bool *is_signed)
4050 {
4051 	const struct btf_type *t;
4052 	const char *name;
4053 
4054 	t = skip_mods_and_typedefs(btf, id, NULL);
4055 	name = btf__name_by_offset(btf, t->name_off);
4056 
4057 	if (is_signed)
4058 		*is_signed = false;
4059 	switch (btf_kind(t)) {
4060 	case BTF_KIND_INT: {
4061 		int enc = btf_int_encoding(t);
4062 
4063 		if (enc & BTF_INT_BOOL)
4064 			return t->size == 1 ? KCFG_BOOL : KCFG_UNKNOWN;
4065 		if (is_signed)
4066 			*is_signed = enc & BTF_INT_SIGNED;
4067 		if (t->size == 1)
4068 			return KCFG_CHAR;
4069 		if (t->size < 1 || t->size > 8 || (t->size & (t->size - 1)))
4070 			return KCFG_UNKNOWN;
4071 		return KCFG_INT;
4072 	}
4073 	case BTF_KIND_ENUM:
4074 		if (t->size != 4)
4075 			return KCFG_UNKNOWN;
4076 		if (strcmp(name, "libbpf_tristate"))
4077 			return KCFG_UNKNOWN;
4078 		return KCFG_TRISTATE;
4079 	case BTF_KIND_ENUM64:
4080 		if (strcmp(name, "libbpf_tristate"))
4081 			return KCFG_UNKNOWN;
4082 		return KCFG_TRISTATE;
4083 	case BTF_KIND_ARRAY:
4084 		if (btf_array(t)->nelems == 0)
4085 			return KCFG_UNKNOWN;
4086 		if (find_kcfg_type(btf, btf_array(t)->type, NULL) != KCFG_CHAR)
4087 			return KCFG_UNKNOWN;
4088 		return KCFG_CHAR_ARR;
4089 	default:
4090 		return KCFG_UNKNOWN;
4091 	}
4092 }
4093 
4094 static int cmp_externs(const void *_a, const void *_b)
4095 {
4096 	const struct extern_desc *a = _a;
4097 	const struct extern_desc *b = _b;
4098 
4099 	if (a->type != b->type)
4100 		return a->type < b->type ? -1 : 1;
4101 
4102 	if (a->type == EXT_KCFG) {
4103 		/* descending order by alignment requirements */
4104 		if (a->kcfg.align != b->kcfg.align)
4105 			return a->kcfg.align > b->kcfg.align ? -1 : 1;
4106 		/* ascending order by size, within same alignment class */
4107 		if (a->kcfg.sz != b->kcfg.sz)
4108 			return a->kcfg.sz < b->kcfg.sz ? -1 : 1;
4109 	}
4110 
4111 	/* resolve ties by name */
4112 	return strcmp(a->name, b->name);
4113 }
4114 
4115 static int find_int_btf_id(const struct btf *btf)
4116 {
4117 	const struct btf_type *t;
4118 	int i, n;
4119 
4120 	n = btf__type_cnt(btf);
4121 	for (i = 1; i < n; i++) {
4122 		t = btf__type_by_id(btf, i);
4123 
4124 		if (btf_is_int(t) && btf_int_bits(t) == 32)
4125 			return i;
4126 	}
4127 
4128 	return 0;
4129 }
4130 
4131 static int add_dummy_ksym_var(struct btf *btf)
4132 {
4133 	int i, int_btf_id, sec_btf_id, dummy_var_btf_id;
4134 	const struct btf_var_secinfo *vs;
4135 	const struct btf_type *sec;
4136 
4137 	if (!btf)
4138 		return 0;
4139 
4140 	sec_btf_id = btf__find_by_name_kind(btf, KSYMS_SEC,
4141 					    BTF_KIND_DATASEC);
4142 	if (sec_btf_id < 0)
4143 		return 0;
4144 
4145 	sec = btf__type_by_id(btf, sec_btf_id);
4146 	vs = btf_var_secinfos(sec);
4147 	for (i = 0; i < btf_vlen(sec); i++, vs++) {
4148 		const struct btf_type *vt;
4149 
4150 		vt = btf__type_by_id(btf, vs->type);
4151 		if (btf_is_func(vt))
4152 			break;
4153 	}
4154 
4155 	/* No func in ksyms sec.  No need to add dummy var. */
4156 	if (i == btf_vlen(sec))
4157 		return 0;
4158 
4159 	int_btf_id = find_int_btf_id(btf);
4160 	dummy_var_btf_id = btf__add_var(btf,
4161 					"dummy_ksym",
4162 					BTF_VAR_GLOBAL_ALLOCATED,
4163 					int_btf_id);
4164 	if (dummy_var_btf_id < 0)
4165 		pr_warn("cannot create a dummy_ksym var\n");
4166 
4167 	return dummy_var_btf_id;
4168 }
4169 
4170 static int bpf_object__collect_externs(struct bpf_object *obj)
4171 {
4172 	struct btf_type *sec, *kcfg_sec = NULL, *ksym_sec = NULL;
4173 	const struct btf_type *t;
4174 	struct extern_desc *ext;
4175 	int i, n, off, dummy_var_btf_id;
4176 	const char *ext_name, *sec_name;
4177 	size_t ext_essent_len;
4178 	Elf_Scn *scn;
4179 	Elf64_Shdr *sh;
4180 
4181 	if (!obj->efile.symbols)
4182 		return 0;
4183 
4184 	scn = elf_sec_by_idx(obj, obj->efile.symbols_shndx);
4185 	sh = elf_sec_hdr(obj, scn);
4186 	if (!sh || sh->sh_entsize != sizeof(Elf64_Sym))
4187 		return -LIBBPF_ERRNO__FORMAT;
4188 
4189 	dummy_var_btf_id = add_dummy_ksym_var(obj->btf);
4190 	if (dummy_var_btf_id < 0)
4191 		return dummy_var_btf_id;
4192 
4193 	n = sh->sh_size / sh->sh_entsize;
4194 	pr_debug("looking for externs among %d symbols...\n", n);
4195 
4196 	for (i = 0; i < n; i++) {
4197 		Elf64_Sym *sym = elf_sym_by_idx(obj, i);
4198 
4199 		if (!sym)
4200 			return -LIBBPF_ERRNO__FORMAT;
4201 		if (!sym_is_extern(sym))
4202 			continue;
4203 		ext_name = elf_sym_str(obj, sym->st_name);
4204 		if (!ext_name || !ext_name[0])
4205 			continue;
4206 
4207 		ext = obj->externs;
4208 		ext = libbpf_reallocarray(ext, obj->nr_extern + 1, sizeof(*ext));
4209 		if (!ext)
4210 			return -ENOMEM;
4211 		obj->externs = ext;
4212 		ext = &ext[obj->nr_extern];
4213 		memset(ext, 0, sizeof(*ext));
4214 		obj->nr_extern++;
4215 
4216 		ext->btf_id = find_extern_btf_id(obj->btf, ext_name);
4217 		if (ext->btf_id <= 0) {
4218 			pr_warn("failed to find BTF for extern '%s': %d\n",
4219 				ext_name, ext->btf_id);
4220 			return ext->btf_id;
4221 		}
4222 		t = btf__type_by_id(obj->btf, ext->btf_id);
4223 		ext->name = btf__name_by_offset(obj->btf, t->name_off);
4224 		ext->sym_idx = i;
4225 		ext->is_weak = ELF64_ST_BIND(sym->st_info) == STB_WEAK;
4226 
4227 		ext_essent_len = bpf_core_essential_name_len(ext->name);
4228 		ext->essent_name = NULL;
4229 		if (ext_essent_len != strlen(ext->name)) {
4230 			ext->essent_name = strndup(ext->name, ext_essent_len);
4231 			if (!ext->essent_name)
4232 				return -ENOMEM;
4233 		}
4234 
4235 		ext->sec_btf_id = find_extern_sec_btf_id(obj->btf, ext->btf_id);
4236 		if (ext->sec_btf_id <= 0) {
4237 			pr_warn("failed to find BTF for extern '%s' [%d] section: %d\n",
4238 				ext_name, ext->btf_id, ext->sec_btf_id);
4239 			return ext->sec_btf_id;
4240 		}
4241 		sec = (void *)btf__type_by_id(obj->btf, ext->sec_btf_id);
4242 		sec_name = btf__name_by_offset(obj->btf, sec->name_off);
4243 
4244 		if (strcmp(sec_name, KCONFIG_SEC) == 0) {
4245 			if (btf_is_func(t)) {
4246 				pr_warn("extern function %s is unsupported under %s section\n",
4247 					ext->name, KCONFIG_SEC);
4248 				return -ENOTSUP;
4249 			}
4250 			kcfg_sec = sec;
4251 			ext->type = EXT_KCFG;
4252 			ext->kcfg.sz = btf__resolve_size(obj->btf, t->type);
4253 			if (ext->kcfg.sz <= 0) {
4254 				pr_warn("failed to resolve size of extern (kcfg) '%s': %d\n",
4255 					ext_name, ext->kcfg.sz);
4256 				return ext->kcfg.sz;
4257 			}
4258 			ext->kcfg.align = btf__align_of(obj->btf, t->type);
4259 			if (ext->kcfg.align <= 0) {
4260 				pr_warn("failed to determine alignment of extern (kcfg) '%s': %d\n",
4261 					ext_name, ext->kcfg.align);
4262 				return -EINVAL;
4263 			}
4264 			ext->kcfg.type = find_kcfg_type(obj->btf, t->type,
4265 							&ext->kcfg.is_signed);
4266 			if (ext->kcfg.type == KCFG_UNKNOWN) {
4267 				pr_warn("extern (kcfg) '%s': type is unsupported\n", ext_name);
4268 				return -ENOTSUP;
4269 			}
4270 		} else if (strcmp(sec_name, KSYMS_SEC) == 0) {
4271 			ksym_sec = sec;
4272 			ext->type = EXT_KSYM;
4273 			skip_mods_and_typedefs(obj->btf, t->type,
4274 					       &ext->ksym.type_id);
4275 		} else {
4276 			pr_warn("unrecognized extern section '%s'\n", sec_name);
4277 			return -ENOTSUP;
4278 		}
4279 	}
4280 	pr_debug("collected %d externs total\n", obj->nr_extern);
4281 
4282 	if (!obj->nr_extern)
4283 		return 0;
4284 
4285 	/* sort externs by type, for kcfg ones also by (align, size, name) */
4286 	qsort(obj->externs, obj->nr_extern, sizeof(*ext), cmp_externs);
4287 
4288 	/* for .ksyms section, we need to turn all externs into allocated
4289 	 * variables in BTF to pass kernel verification; we do this by
4290 	 * pretending that each extern is a 8-byte variable
4291 	 */
4292 	if (ksym_sec) {
4293 		/* find existing 4-byte integer type in BTF to use for fake
4294 		 * extern variables in DATASEC
4295 		 */
4296 		int int_btf_id = find_int_btf_id(obj->btf);
4297 		/* For extern function, a dummy_var added earlier
4298 		 * will be used to replace the vs->type and
4299 		 * its name string will be used to refill
4300 		 * the missing param's name.
4301 		 */
4302 		const struct btf_type *dummy_var;
4303 
4304 		dummy_var = btf__type_by_id(obj->btf, dummy_var_btf_id);
4305 		for (i = 0; i < obj->nr_extern; i++) {
4306 			ext = &obj->externs[i];
4307 			if (ext->type != EXT_KSYM)
4308 				continue;
4309 			pr_debug("extern (ksym) #%d: symbol %d, name %s\n",
4310 				 i, ext->sym_idx, ext->name);
4311 		}
4312 
4313 		sec = ksym_sec;
4314 		n = btf_vlen(sec);
4315 		for (i = 0, off = 0; i < n; i++, off += sizeof(int)) {
4316 			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
4317 			struct btf_type *vt;
4318 
4319 			vt = (void *)btf__type_by_id(obj->btf, vs->type);
4320 			ext_name = btf__name_by_offset(obj->btf, vt->name_off);
4321 			ext = find_extern_by_name(obj, ext_name);
4322 			if (!ext) {
4323 				pr_warn("failed to find extern definition for BTF %s '%s'\n",
4324 					btf_kind_str(vt), ext_name);
4325 				return -ESRCH;
4326 			}
4327 			if (btf_is_func(vt)) {
4328 				const struct btf_type *func_proto;
4329 				struct btf_param *param;
4330 				int j;
4331 
4332 				func_proto = btf__type_by_id(obj->btf,
4333 							     vt->type);
4334 				param = btf_params(func_proto);
4335 				/* Reuse the dummy_var string if the
4336 				 * func proto does not have param name.
4337 				 */
4338 				for (j = 0; j < btf_vlen(func_proto); j++)
4339 					if (param[j].type && !param[j].name_off)
4340 						param[j].name_off =
4341 							dummy_var->name_off;
4342 				vs->type = dummy_var_btf_id;
4343 				vt->info &= ~0xffff;
4344 				vt->info |= BTF_FUNC_GLOBAL;
4345 			} else {
4346 				btf_var(vt)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
4347 				vt->type = int_btf_id;
4348 			}
4349 			vs->offset = off;
4350 			vs->size = sizeof(int);
4351 		}
4352 		sec->size = off;
4353 	}
4354 
4355 	if (kcfg_sec) {
4356 		sec = kcfg_sec;
4357 		/* for kcfg externs calculate their offsets within a .kconfig map */
4358 		off = 0;
4359 		for (i = 0; i < obj->nr_extern; i++) {
4360 			ext = &obj->externs[i];
4361 			if (ext->type != EXT_KCFG)
4362 				continue;
4363 
4364 			ext->kcfg.data_off = roundup(off, ext->kcfg.align);
4365 			off = ext->kcfg.data_off + ext->kcfg.sz;
4366 			pr_debug("extern (kcfg) #%d: symbol %d, off %u, name %s\n",
4367 				 i, ext->sym_idx, ext->kcfg.data_off, ext->name);
4368 		}
4369 		sec->size = off;
4370 		n = btf_vlen(sec);
4371 		for (i = 0; i < n; i++) {
4372 			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
4373 
4374 			t = btf__type_by_id(obj->btf, vs->type);
4375 			ext_name = btf__name_by_offset(obj->btf, t->name_off);
4376 			ext = find_extern_by_name(obj, ext_name);
4377 			if (!ext) {
4378 				pr_warn("failed to find extern definition for BTF var '%s'\n",
4379 					ext_name);
4380 				return -ESRCH;
4381 			}
4382 			btf_var(t)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
4383 			vs->offset = ext->kcfg.data_off;
4384 		}
4385 	}
4386 	return 0;
4387 }
4388 
4389 static bool prog_is_subprog(const struct bpf_object *obj, const struct bpf_program *prog)
4390 {
4391 	return prog->sec_idx == obj->efile.text_shndx && obj->nr_programs > 1;
4392 }
4393 
4394 struct bpf_program *
4395 bpf_object__find_program_by_name(const struct bpf_object *obj,
4396 				 const char *name)
4397 {
4398 	struct bpf_program *prog;
4399 
4400 	bpf_object__for_each_program(prog, obj) {
4401 		if (prog_is_subprog(obj, prog))
4402 			continue;
4403 		if (!strcmp(prog->name, name))
4404 			return prog;
4405 	}
4406 	return errno = ENOENT, NULL;
4407 }
4408 
4409 static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
4410 				      int shndx)
4411 {
4412 	switch (obj->efile.secs[shndx].sec_type) {
4413 	case SEC_BSS:
4414 	case SEC_DATA:
4415 	case SEC_RODATA:
4416 		return true;
4417 	default:
4418 		return false;
4419 	}
4420 }
4421 
4422 static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
4423 				      int shndx)
4424 {
4425 	return shndx == obj->efile.btf_maps_shndx;
4426 }
4427 
4428 static enum libbpf_map_type
4429 bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
4430 {
4431 	if (shndx == obj->efile.symbols_shndx)
4432 		return LIBBPF_MAP_KCONFIG;
4433 
4434 	switch (obj->efile.secs[shndx].sec_type) {
4435 	case SEC_BSS:
4436 		return LIBBPF_MAP_BSS;
4437 	case SEC_DATA:
4438 		return LIBBPF_MAP_DATA;
4439 	case SEC_RODATA:
4440 		return LIBBPF_MAP_RODATA;
4441 	default:
4442 		return LIBBPF_MAP_UNSPEC;
4443 	}
4444 }
4445 
4446 static int bpf_program__record_reloc(struct bpf_program *prog,
4447 				     struct reloc_desc *reloc_desc,
4448 				     __u32 insn_idx, const char *sym_name,
4449 				     const Elf64_Sym *sym, const Elf64_Rel *rel)
4450 {
4451 	struct bpf_insn *insn = &prog->insns[insn_idx];
4452 	size_t map_idx, nr_maps = prog->obj->nr_maps;
4453 	struct bpf_object *obj = prog->obj;
4454 	__u32 shdr_idx = sym->st_shndx;
4455 	enum libbpf_map_type type;
4456 	const char *sym_sec_name;
4457 	struct bpf_map *map;
4458 
4459 	if (!is_call_insn(insn) && !is_ldimm64_insn(insn)) {
4460 		pr_warn("prog '%s': invalid relo against '%s' for insns[%d].code 0x%x\n",
4461 			prog->name, sym_name, insn_idx, insn->code);
4462 		return -LIBBPF_ERRNO__RELOC;
4463 	}
4464 
4465 	if (sym_is_extern(sym)) {
4466 		int sym_idx = ELF64_R_SYM(rel->r_info);
4467 		int i, n = obj->nr_extern;
4468 		struct extern_desc *ext;
4469 
4470 		for (i = 0; i < n; i++) {
4471 			ext = &obj->externs[i];
4472 			if (ext->sym_idx == sym_idx)
4473 				break;
4474 		}
4475 		if (i >= n) {
4476 			pr_warn("prog '%s': extern relo failed to find extern for '%s' (%d)\n",
4477 				prog->name, sym_name, sym_idx);
4478 			return -LIBBPF_ERRNO__RELOC;
4479 		}
4480 		pr_debug("prog '%s': found extern #%d '%s' (sym %d) for insn #%u\n",
4481 			 prog->name, i, ext->name, ext->sym_idx, insn_idx);
4482 		if (insn->code == (BPF_JMP | BPF_CALL))
4483 			reloc_desc->type = RELO_EXTERN_CALL;
4484 		else
4485 			reloc_desc->type = RELO_EXTERN_LD64;
4486 		reloc_desc->insn_idx = insn_idx;
4487 		reloc_desc->ext_idx = i;
4488 		return 0;
4489 	}
4490 
4491 	/* sub-program call relocation */
4492 	if (is_call_insn(insn)) {
4493 		if (insn->src_reg != BPF_PSEUDO_CALL) {
4494 			pr_warn("prog '%s': incorrect bpf_call opcode\n", prog->name);
4495 			return -LIBBPF_ERRNO__RELOC;
4496 		}
4497 		/* text_shndx can be 0, if no default "main" program exists */
4498 		if (!shdr_idx || shdr_idx != obj->efile.text_shndx) {
4499 			sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4500 			pr_warn("prog '%s': bad call relo against '%s' in section '%s'\n",
4501 				prog->name, sym_name, sym_sec_name);
4502 			return -LIBBPF_ERRNO__RELOC;
4503 		}
4504 		if (sym->st_value % BPF_INSN_SZ) {
4505 			pr_warn("prog '%s': bad call relo against '%s' at offset %zu\n",
4506 				prog->name, sym_name, (size_t)sym->st_value);
4507 			return -LIBBPF_ERRNO__RELOC;
4508 		}
4509 		reloc_desc->type = RELO_CALL;
4510 		reloc_desc->insn_idx = insn_idx;
4511 		reloc_desc->sym_off = sym->st_value;
4512 		return 0;
4513 	}
4514 
4515 	if (!shdr_idx || shdr_idx >= SHN_LORESERVE) {
4516 		pr_warn("prog '%s': invalid relo against '%s' in special section 0x%x; forgot to initialize global var?..\n",
4517 			prog->name, sym_name, shdr_idx);
4518 		return -LIBBPF_ERRNO__RELOC;
4519 	}
4520 
4521 	/* loading subprog addresses */
4522 	if (sym_is_subprog(sym, obj->efile.text_shndx)) {
4523 		/* global_func: sym->st_value = offset in the section, insn->imm = 0.
4524 		 * local_func: sym->st_value = 0, insn->imm = offset in the section.
4525 		 */
4526 		if ((sym->st_value % BPF_INSN_SZ) || (insn->imm % BPF_INSN_SZ)) {
4527 			pr_warn("prog '%s': bad subprog addr relo against '%s' at offset %zu+%d\n",
4528 				prog->name, sym_name, (size_t)sym->st_value, insn->imm);
4529 			return -LIBBPF_ERRNO__RELOC;
4530 		}
4531 
4532 		reloc_desc->type = RELO_SUBPROG_ADDR;
4533 		reloc_desc->insn_idx = insn_idx;
4534 		reloc_desc->sym_off = sym->st_value;
4535 		return 0;
4536 	}
4537 
4538 	type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
4539 	sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4540 
4541 	/* arena data relocation */
4542 	if (shdr_idx == obj->efile.arena_data_shndx) {
4543 		reloc_desc->type = RELO_DATA;
4544 		reloc_desc->insn_idx = insn_idx;
4545 		reloc_desc->map_idx = obj->arena_map - obj->maps;
4546 		reloc_desc->sym_off = sym->st_value;
4547 		return 0;
4548 	}
4549 
4550 	/* generic map reference relocation */
4551 	if (type == LIBBPF_MAP_UNSPEC) {
4552 		if (!bpf_object__shndx_is_maps(obj, shdr_idx)) {
4553 			pr_warn("prog '%s': bad map relo against '%s' in section '%s'\n",
4554 				prog->name, sym_name, sym_sec_name);
4555 			return -LIBBPF_ERRNO__RELOC;
4556 		}
4557 		for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4558 			map = &obj->maps[map_idx];
4559 			if (map->libbpf_type != type ||
4560 			    map->sec_idx != sym->st_shndx ||
4561 			    map->sec_offset != sym->st_value)
4562 				continue;
4563 			pr_debug("prog '%s': found map %zd (%s, sec %d, off %zu) for insn #%u\n",
4564 				 prog->name, map_idx, map->name, map->sec_idx,
4565 				 map->sec_offset, insn_idx);
4566 			break;
4567 		}
4568 		if (map_idx >= nr_maps) {
4569 			pr_warn("prog '%s': map relo failed to find map for section '%s', off %zu\n",
4570 				prog->name, sym_sec_name, (size_t)sym->st_value);
4571 			return -LIBBPF_ERRNO__RELOC;
4572 		}
4573 		reloc_desc->type = RELO_LD64;
4574 		reloc_desc->insn_idx = insn_idx;
4575 		reloc_desc->map_idx = map_idx;
4576 		reloc_desc->sym_off = 0; /* sym->st_value determines map_idx */
4577 		return 0;
4578 	}
4579 
4580 	/* global data map relocation */
4581 	if (!bpf_object__shndx_is_data(obj, shdr_idx)) {
4582 		pr_warn("prog '%s': bad data relo against section '%s'\n",
4583 			prog->name, sym_sec_name);
4584 		return -LIBBPF_ERRNO__RELOC;
4585 	}
4586 	for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4587 		map = &obj->maps[map_idx];
4588 		if (map->libbpf_type != type || map->sec_idx != sym->st_shndx)
4589 			continue;
4590 		pr_debug("prog '%s': found data map %zd (%s, sec %d, off %zu) for insn %u\n",
4591 			 prog->name, map_idx, map->name, map->sec_idx,
4592 			 map->sec_offset, insn_idx);
4593 		break;
4594 	}
4595 	if (map_idx >= nr_maps) {
4596 		pr_warn("prog '%s': data relo failed to find map for section '%s'\n",
4597 			prog->name, sym_sec_name);
4598 		return -LIBBPF_ERRNO__RELOC;
4599 	}
4600 
4601 	reloc_desc->type = RELO_DATA;
4602 	reloc_desc->insn_idx = insn_idx;
4603 	reloc_desc->map_idx = map_idx;
4604 	reloc_desc->sym_off = sym->st_value;
4605 	return 0;
4606 }
4607 
4608 static bool prog_contains_insn(const struct bpf_program *prog, size_t insn_idx)
4609 {
4610 	return insn_idx >= prog->sec_insn_off &&
4611 	       insn_idx < prog->sec_insn_off + prog->sec_insn_cnt;
4612 }
4613 
4614 static struct bpf_program *find_prog_by_sec_insn(const struct bpf_object *obj,
4615 						 size_t sec_idx, size_t insn_idx)
4616 {
4617 	int l = 0, r = obj->nr_programs - 1, m;
4618 	struct bpf_program *prog;
4619 
4620 	if (!obj->nr_programs)
4621 		return NULL;
4622 
4623 	while (l < r) {
4624 		m = l + (r - l + 1) / 2;
4625 		prog = &obj->programs[m];
4626 
4627 		if (prog->sec_idx < sec_idx ||
4628 		    (prog->sec_idx == sec_idx && prog->sec_insn_off <= insn_idx))
4629 			l = m;
4630 		else
4631 			r = m - 1;
4632 	}
4633 	/* matching program could be at index l, but it still might be the
4634 	 * wrong one, so we need to double check conditions for the last time
4635 	 */
4636 	prog = &obj->programs[l];
4637 	if (prog->sec_idx == sec_idx && prog_contains_insn(prog, insn_idx))
4638 		return prog;
4639 	return NULL;
4640 }
4641 
4642 static int
4643 bpf_object__collect_prog_relos(struct bpf_object *obj, Elf64_Shdr *shdr, Elf_Data *data)
4644 {
4645 	const char *relo_sec_name, *sec_name;
4646 	size_t sec_idx = shdr->sh_info, sym_idx;
4647 	struct bpf_program *prog;
4648 	struct reloc_desc *relos;
4649 	int err, i, nrels;
4650 	const char *sym_name;
4651 	__u32 insn_idx;
4652 	Elf_Scn *scn;
4653 	Elf_Data *scn_data;
4654 	Elf64_Sym *sym;
4655 	Elf64_Rel *rel;
4656 
4657 	if (sec_idx >= obj->efile.sec_cnt)
4658 		return -EINVAL;
4659 
4660 	scn = elf_sec_by_idx(obj, sec_idx);
4661 	scn_data = elf_sec_data(obj, scn);
4662 	if (!scn_data)
4663 		return -LIBBPF_ERRNO__FORMAT;
4664 
4665 	relo_sec_name = elf_sec_str(obj, shdr->sh_name);
4666 	sec_name = elf_sec_name(obj, scn);
4667 	if (!relo_sec_name || !sec_name)
4668 		return -EINVAL;
4669 
4670 	pr_debug("sec '%s': collecting relocation for section(%zu) '%s'\n",
4671 		 relo_sec_name, sec_idx, sec_name);
4672 	nrels = shdr->sh_size / shdr->sh_entsize;
4673 
4674 	for (i = 0; i < nrels; i++) {
4675 		rel = elf_rel_by_idx(data, i);
4676 		if (!rel) {
4677 			pr_warn("sec '%s': failed to get relo #%d\n", relo_sec_name, i);
4678 			return -LIBBPF_ERRNO__FORMAT;
4679 		}
4680 
4681 		sym_idx = ELF64_R_SYM(rel->r_info);
4682 		sym = elf_sym_by_idx(obj, sym_idx);
4683 		if (!sym) {
4684 			pr_warn("sec '%s': symbol #%zu not found for relo #%d\n",
4685 				relo_sec_name, sym_idx, i);
4686 			return -LIBBPF_ERRNO__FORMAT;
4687 		}
4688 
4689 		if (sym->st_shndx >= obj->efile.sec_cnt) {
4690 			pr_warn("sec '%s': corrupted symbol #%zu pointing to invalid section #%zu for relo #%d\n",
4691 				relo_sec_name, sym_idx, (size_t)sym->st_shndx, i);
4692 			return -LIBBPF_ERRNO__FORMAT;
4693 		}
4694 
4695 		if (rel->r_offset % BPF_INSN_SZ || rel->r_offset >= scn_data->d_size) {
4696 			pr_warn("sec '%s': invalid offset 0x%zx for relo #%d\n",
4697 				relo_sec_name, (size_t)rel->r_offset, i);
4698 			return -LIBBPF_ERRNO__FORMAT;
4699 		}
4700 
4701 		insn_idx = rel->r_offset / BPF_INSN_SZ;
4702 		/* relocations against static functions are recorded as
4703 		 * relocations against the section that contains a function;
4704 		 * in such case, symbol will be STT_SECTION and sym.st_name
4705 		 * will point to empty string (0), so fetch section name
4706 		 * instead
4707 		 */
4708 		if (ELF64_ST_TYPE(sym->st_info) == STT_SECTION && sym->st_name == 0)
4709 			sym_name = elf_sec_name(obj, elf_sec_by_idx(obj, sym->st_shndx));
4710 		else
4711 			sym_name = elf_sym_str(obj, sym->st_name);
4712 		sym_name = sym_name ?: "<?";
4713 
4714 		pr_debug("sec '%s': relo #%d: insn #%u against '%s'\n",
4715 			 relo_sec_name, i, insn_idx, sym_name);
4716 
4717 		prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
4718 		if (!prog) {
4719 			pr_debug("sec '%s': relo #%d: couldn't find program in section '%s' for insn #%u, probably overridden weak function, skipping...\n",
4720 				relo_sec_name, i, sec_name, insn_idx);
4721 			continue;
4722 		}
4723 
4724 		relos = libbpf_reallocarray(prog->reloc_desc,
4725 					    prog->nr_reloc + 1, sizeof(*relos));
4726 		if (!relos)
4727 			return -ENOMEM;
4728 		prog->reloc_desc = relos;
4729 
4730 		/* adjust insn_idx to local BPF program frame of reference */
4731 		insn_idx -= prog->sec_insn_off;
4732 		err = bpf_program__record_reloc(prog, &relos[prog->nr_reloc],
4733 						insn_idx, sym_name, sym, rel);
4734 		if (err)
4735 			return err;
4736 
4737 		prog->nr_reloc++;
4738 	}
4739 	return 0;
4740 }
4741 
4742 static int map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map)
4743 {
4744 	int id;
4745 
4746 	if (!obj->btf)
4747 		return -ENOENT;
4748 
4749 	/* if it's BTF-defined map, we don't need to search for type IDs.
4750 	 * For struct_ops map, it does not need btf_key_type_id and
4751 	 * btf_value_type_id.
4752 	 */
4753 	if (map->sec_idx == obj->efile.btf_maps_shndx || bpf_map__is_struct_ops(map))
4754 		return 0;
4755 
4756 	/*
4757 	 * LLVM annotates global data differently in BTF, that is,
4758 	 * only as '.data', '.bss' or '.rodata'.
4759 	 */
4760 	if (!bpf_map__is_internal(map))
4761 		return -ENOENT;
4762 
4763 	id = btf__find_by_name(obj->btf, map->real_name);
4764 	if (id < 0)
4765 		return id;
4766 
4767 	map->btf_key_type_id = 0;
4768 	map->btf_value_type_id = id;
4769 	return 0;
4770 }
4771 
4772 static int bpf_get_map_info_from_fdinfo(int fd, struct bpf_map_info *info)
4773 {
4774 	char file[PATH_MAX], buff[4096];
4775 	FILE *fp;
4776 	__u32 val;
4777 	int err;
4778 
4779 	snprintf(file, sizeof(file), "/proc/%d/fdinfo/%d", getpid(), fd);
4780 	memset(info, 0, sizeof(*info));
4781 
4782 	fp = fopen(file, "re");
4783 	if (!fp) {
4784 		err = -errno;
4785 		pr_warn("failed to open %s: %d. No procfs support?\n", file,
4786 			err);
4787 		return err;
4788 	}
4789 
4790 	while (fgets(buff, sizeof(buff), fp)) {
4791 		if (sscanf(buff, "map_type:\t%u", &val) == 1)
4792 			info->type = val;
4793 		else if (sscanf(buff, "key_size:\t%u", &val) == 1)
4794 			info->key_size = val;
4795 		else if (sscanf(buff, "value_size:\t%u", &val) == 1)
4796 			info->value_size = val;
4797 		else if (sscanf(buff, "max_entries:\t%u", &val) == 1)
4798 			info->max_entries = val;
4799 		else if (sscanf(buff, "map_flags:\t%i", &val) == 1)
4800 			info->map_flags = val;
4801 	}
4802 
4803 	fclose(fp);
4804 
4805 	return 0;
4806 }
4807 
4808 bool bpf_map__autocreate(const struct bpf_map *map)
4809 {
4810 	return map->autocreate;
4811 }
4812 
4813 int bpf_map__set_autocreate(struct bpf_map *map, bool autocreate)
4814 {
4815 	if (map->obj->loaded)
4816 		return libbpf_err(-EBUSY);
4817 
4818 	map->autocreate = autocreate;
4819 	return 0;
4820 }
4821 
4822 int bpf_map__reuse_fd(struct bpf_map *map, int fd)
4823 {
4824 	struct bpf_map_info info;
4825 	__u32 len = sizeof(info), name_len;
4826 	int new_fd, err;
4827 	char *new_name;
4828 
4829 	memset(&info, 0, len);
4830 	err = bpf_map_get_info_by_fd(fd, &info, &len);
4831 	if (err && errno == EINVAL)
4832 		err = bpf_get_map_info_from_fdinfo(fd, &info);
4833 	if (err)
4834 		return libbpf_err(err);
4835 
4836 	name_len = strlen(info.name);
4837 	if (name_len == BPF_OBJ_NAME_LEN - 1 && strncmp(map->name, info.name, name_len) == 0)
4838 		new_name = strdup(map->name);
4839 	else
4840 		new_name = strdup(info.name);
4841 
4842 	if (!new_name)
4843 		return libbpf_err(-errno);
4844 
4845 	/*
4846 	 * Like dup(), but make sure new FD is >= 3 and has O_CLOEXEC set.
4847 	 * This is similar to what we do in ensure_good_fd(), but without
4848 	 * closing original FD.
4849 	 */
4850 	new_fd = fcntl(fd, F_DUPFD_CLOEXEC, 3);
4851 	if (new_fd < 0) {
4852 		err = -errno;
4853 		goto err_free_new_name;
4854 	}
4855 
4856 	err = reuse_fd(map->fd, new_fd);
4857 	if (err)
4858 		goto err_free_new_name;
4859 
4860 	free(map->name);
4861 
4862 	map->name = new_name;
4863 	map->def.type = info.type;
4864 	map->def.key_size = info.key_size;
4865 	map->def.value_size = info.value_size;
4866 	map->def.max_entries = info.max_entries;
4867 	map->def.map_flags = info.map_flags;
4868 	map->btf_key_type_id = info.btf_key_type_id;
4869 	map->btf_value_type_id = info.btf_value_type_id;
4870 	map->reused = true;
4871 	map->map_extra = info.map_extra;
4872 
4873 	return 0;
4874 
4875 err_free_new_name:
4876 	free(new_name);
4877 	return libbpf_err(err);
4878 }
4879 
4880 __u32 bpf_map__max_entries(const struct bpf_map *map)
4881 {
4882 	return map->def.max_entries;
4883 }
4884 
4885 struct bpf_map *bpf_map__inner_map(struct bpf_map *map)
4886 {
4887 	if (!bpf_map_type__is_map_in_map(map->def.type))
4888 		return errno = EINVAL, NULL;
4889 
4890 	return map->inner_map;
4891 }
4892 
4893 int bpf_map__set_max_entries(struct bpf_map *map, __u32 max_entries)
4894 {
4895 	if (map->obj->loaded)
4896 		return libbpf_err(-EBUSY);
4897 
4898 	map->def.max_entries = max_entries;
4899 
4900 	/* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
4901 	if (map_is_ringbuf(map))
4902 		map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
4903 
4904 	return 0;
4905 }
4906 
4907 static int bpf_object_prepare_token(struct bpf_object *obj)
4908 {
4909 	const char *bpffs_path;
4910 	int bpffs_fd = -1, token_fd, err;
4911 	bool mandatory;
4912 	enum libbpf_print_level level;
4913 
4914 	/* token is explicitly prevented */
4915 	if (obj->token_path && obj->token_path[0] == '\0') {
4916 		pr_debug("object '%s': token is prevented, skipping...\n", obj->name);
4917 		return 0;
4918 	}
4919 
4920 	mandatory = obj->token_path != NULL;
4921 	level = mandatory ? LIBBPF_WARN : LIBBPF_DEBUG;
4922 
4923 	bpffs_path = obj->token_path ?: BPF_FS_DEFAULT_PATH;
4924 	bpffs_fd = open(bpffs_path, O_DIRECTORY, O_RDWR);
4925 	if (bpffs_fd < 0) {
4926 		err = -errno;
4927 		__pr(level, "object '%s': failed (%d) to open BPF FS mount at '%s'%s\n",
4928 		     obj->name, err, bpffs_path,
4929 		     mandatory ? "" : ", skipping optional step...");
4930 		return mandatory ? err : 0;
4931 	}
4932 
4933 	token_fd = bpf_token_create(bpffs_fd, 0);
4934 	close(bpffs_fd);
4935 	if (token_fd < 0) {
4936 		if (!mandatory && token_fd == -ENOENT) {
4937 			pr_debug("object '%s': BPF FS at '%s' doesn't have BPF token delegation set up, skipping...\n",
4938 				 obj->name, bpffs_path);
4939 			return 0;
4940 		}
4941 		__pr(level, "object '%s': failed (%d) to create BPF token from '%s'%s\n",
4942 		     obj->name, token_fd, bpffs_path,
4943 		     mandatory ? "" : ", skipping optional step...");
4944 		return mandatory ? token_fd : 0;
4945 	}
4946 
4947 	obj->feat_cache = calloc(1, sizeof(*obj->feat_cache));
4948 	if (!obj->feat_cache) {
4949 		close(token_fd);
4950 		return -ENOMEM;
4951 	}
4952 
4953 	obj->token_fd = token_fd;
4954 	obj->feat_cache->token_fd = token_fd;
4955 
4956 	return 0;
4957 }
4958 
4959 static int
4960 bpf_object__probe_loading(struct bpf_object *obj)
4961 {
4962 	char *cp, errmsg[STRERR_BUFSIZE];
4963 	struct bpf_insn insns[] = {
4964 		BPF_MOV64_IMM(BPF_REG_0, 0),
4965 		BPF_EXIT_INSN(),
4966 	};
4967 	int ret, insn_cnt = ARRAY_SIZE(insns);
4968 	LIBBPF_OPTS(bpf_prog_load_opts, opts,
4969 		.token_fd = obj->token_fd,
4970 		.prog_flags = obj->token_fd ? BPF_F_TOKEN_FD : 0,
4971 	);
4972 
4973 	if (obj->gen_loader)
4974 		return 0;
4975 
4976 	ret = bump_rlimit_memlock();
4977 	if (ret)
4978 		pr_warn("Failed to bump RLIMIT_MEMLOCK (err = %d), you might need to do it explicitly!\n", ret);
4979 
4980 	/* make sure basic loading works */
4981 	ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, &opts);
4982 	if (ret < 0)
4983 		ret = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, &opts);
4984 	if (ret < 0) {
4985 		ret = errno;
4986 		cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4987 		pr_warn("Error in %s():%s(%d). Couldn't load trivial BPF "
4988 			"program. Make sure your kernel supports BPF "
4989 			"(CONFIG_BPF_SYSCALL=y) and/or that RLIMIT_MEMLOCK is "
4990 			"set to big enough value.\n", __func__, cp, ret);
4991 		return -ret;
4992 	}
4993 	close(ret);
4994 
4995 	return 0;
4996 }
4997 
4998 bool kernel_supports(const struct bpf_object *obj, enum kern_feature_id feat_id)
4999 {
5000 	if (obj->gen_loader)
5001 		/* To generate loader program assume the latest kernel
5002 		 * to avoid doing extra prog_load, map_create syscalls.
5003 		 */
5004 		return true;
5005 
5006 	if (obj->token_fd)
5007 		return feat_supported(obj->feat_cache, feat_id);
5008 
5009 	return feat_supported(NULL, feat_id);
5010 }
5011 
5012 static bool map_is_reuse_compat(const struct bpf_map *map, int map_fd)
5013 {
5014 	struct bpf_map_info map_info;
5015 	char msg[STRERR_BUFSIZE];
5016 	__u32 map_info_len = sizeof(map_info);
5017 	int err;
5018 
5019 	memset(&map_info, 0, map_info_len);
5020 	err = bpf_map_get_info_by_fd(map_fd, &map_info, &map_info_len);
5021 	if (err && errno == EINVAL)
5022 		err = bpf_get_map_info_from_fdinfo(map_fd, &map_info);
5023 	if (err) {
5024 		pr_warn("failed to get map info for map FD %d: %s\n", map_fd,
5025 			libbpf_strerror_r(errno, msg, sizeof(msg)));
5026 		return false;
5027 	}
5028 
5029 	return (map_info.type == map->def.type &&
5030 		map_info.key_size == map->def.key_size &&
5031 		map_info.value_size == map->def.value_size &&
5032 		map_info.max_entries == map->def.max_entries &&
5033 		map_info.map_flags == map->def.map_flags &&
5034 		map_info.map_extra == map->map_extra);
5035 }
5036 
5037 static int
5038 bpf_object__reuse_map(struct bpf_map *map)
5039 {
5040 	char *cp, errmsg[STRERR_BUFSIZE];
5041 	int err, pin_fd;
5042 
5043 	pin_fd = bpf_obj_get(map->pin_path);
5044 	if (pin_fd < 0) {
5045 		err = -errno;
5046 		if (err == -ENOENT) {
5047 			pr_debug("found no pinned map to reuse at '%s'\n",
5048 				 map->pin_path);
5049 			return 0;
5050 		}
5051 
5052 		cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
5053 		pr_warn("couldn't retrieve pinned map '%s': %s\n",
5054 			map->pin_path, cp);
5055 		return err;
5056 	}
5057 
5058 	if (!map_is_reuse_compat(map, pin_fd)) {
5059 		pr_warn("couldn't reuse pinned map at '%s': parameter mismatch\n",
5060 			map->pin_path);
5061 		close(pin_fd);
5062 		return -EINVAL;
5063 	}
5064 
5065 	err = bpf_map__reuse_fd(map, pin_fd);
5066 	close(pin_fd);
5067 	if (err)
5068 		return err;
5069 
5070 	map->pinned = true;
5071 	pr_debug("reused pinned map at '%s'\n", map->pin_path);
5072 
5073 	return 0;
5074 }
5075 
5076 static int
5077 bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
5078 {
5079 	enum libbpf_map_type map_type = map->libbpf_type;
5080 	char *cp, errmsg[STRERR_BUFSIZE];
5081 	int err, zero = 0;
5082 
5083 	if (obj->gen_loader) {
5084 		bpf_gen__map_update_elem(obj->gen_loader, map - obj->maps,
5085 					 map->mmaped, map->def.value_size);
5086 		if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG)
5087 			bpf_gen__map_freeze(obj->gen_loader, map - obj->maps);
5088 		return 0;
5089 	}
5090 
5091 	err = bpf_map_update_elem(map->fd, &zero, map->mmaped, 0);
5092 	if (err) {
5093 		err = -errno;
5094 		cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5095 		pr_warn("Error setting initial map(%s) contents: %s\n",
5096 			map->name, cp);
5097 		return err;
5098 	}
5099 
5100 	/* Freeze .rodata and .kconfig map as read-only from syscall side. */
5101 	if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG) {
5102 		err = bpf_map_freeze(map->fd);
5103 		if (err) {
5104 			err = -errno;
5105 			cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5106 			pr_warn("Error freezing map(%s) as read-only: %s\n",
5107 				map->name, cp);
5108 			return err;
5109 		}
5110 	}
5111 	return 0;
5112 }
5113 
5114 static void bpf_map__destroy(struct bpf_map *map);
5115 
5116 static bool map_is_created(const struct bpf_map *map)
5117 {
5118 	return map->obj->loaded || map->reused;
5119 }
5120 
5121 static int bpf_object__create_map(struct bpf_object *obj, struct bpf_map *map, bool is_inner)
5122 {
5123 	LIBBPF_OPTS(bpf_map_create_opts, create_attr);
5124 	struct bpf_map_def *def = &map->def;
5125 	const char *map_name = NULL;
5126 	int err = 0, map_fd;
5127 
5128 	if (kernel_supports(obj, FEAT_PROG_NAME))
5129 		map_name = map->name;
5130 	create_attr.map_ifindex = map->map_ifindex;
5131 	create_attr.map_flags = def->map_flags;
5132 	create_attr.numa_node = map->numa_node;
5133 	create_attr.map_extra = map->map_extra;
5134 	create_attr.token_fd = obj->token_fd;
5135 	if (obj->token_fd)
5136 		create_attr.map_flags |= BPF_F_TOKEN_FD;
5137 
5138 	if (bpf_map__is_struct_ops(map)) {
5139 		create_attr.btf_vmlinux_value_type_id = map->btf_vmlinux_value_type_id;
5140 		if (map->mod_btf_fd >= 0) {
5141 			create_attr.value_type_btf_obj_fd = map->mod_btf_fd;
5142 			create_attr.map_flags |= BPF_F_VTYPE_BTF_OBJ_FD;
5143 		}
5144 	}
5145 
5146 	if (obj->btf && btf__fd(obj->btf) >= 0) {
5147 		create_attr.btf_fd = btf__fd(obj->btf);
5148 		create_attr.btf_key_type_id = map->btf_key_type_id;
5149 		create_attr.btf_value_type_id = map->btf_value_type_id;
5150 	}
5151 
5152 	if (bpf_map_type__is_map_in_map(def->type)) {
5153 		if (map->inner_map) {
5154 			err = map_set_def_max_entries(map->inner_map);
5155 			if (err)
5156 				return err;
5157 			err = bpf_object__create_map(obj, map->inner_map, true);
5158 			if (err) {
5159 				pr_warn("map '%s': failed to create inner map: %d\n",
5160 					map->name, err);
5161 				return err;
5162 			}
5163 			map->inner_map_fd = map->inner_map->fd;
5164 		}
5165 		if (map->inner_map_fd >= 0)
5166 			create_attr.inner_map_fd = map->inner_map_fd;
5167 	}
5168 
5169 	switch (def->type) {
5170 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
5171 	case BPF_MAP_TYPE_CGROUP_ARRAY:
5172 	case BPF_MAP_TYPE_STACK_TRACE:
5173 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
5174 	case BPF_MAP_TYPE_HASH_OF_MAPS:
5175 	case BPF_MAP_TYPE_DEVMAP:
5176 	case BPF_MAP_TYPE_DEVMAP_HASH:
5177 	case BPF_MAP_TYPE_CPUMAP:
5178 	case BPF_MAP_TYPE_XSKMAP:
5179 	case BPF_MAP_TYPE_SOCKMAP:
5180 	case BPF_MAP_TYPE_SOCKHASH:
5181 	case BPF_MAP_TYPE_QUEUE:
5182 	case BPF_MAP_TYPE_STACK:
5183 	case BPF_MAP_TYPE_ARENA:
5184 		create_attr.btf_fd = 0;
5185 		create_attr.btf_key_type_id = 0;
5186 		create_attr.btf_value_type_id = 0;
5187 		map->btf_key_type_id = 0;
5188 		map->btf_value_type_id = 0;
5189 		break;
5190 	case BPF_MAP_TYPE_STRUCT_OPS:
5191 		create_attr.btf_value_type_id = 0;
5192 		break;
5193 	default:
5194 		break;
5195 	}
5196 
5197 	if (obj->gen_loader) {
5198 		bpf_gen__map_create(obj->gen_loader, def->type, map_name,
5199 				    def->key_size, def->value_size, def->max_entries,
5200 				    &create_attr, is_inner ? -1 : map - obj->maps);
5201 		/* We keep pretenting we have valid FD to pass various fd >= 0
5202 		 * checks by just keeping original placeholder FDs in place.
5203 		 * See bpf_object__add_map() comment.
5204 		 * This placeholder fd will not be used with any syscall and
5205 		 * will be reset to -1 eventually.
5206 		 */
5207 		map_fd = map->fd;
5208 	} else {
5209 		map_fd = bpf_map_create(def->type, map_name,
5210 					def->key_size, def->value_size,
5211 					def->max_entries, &create_attr);
5212 	}
5213 	if (map_fd < 0 && (create_attr.btf_key_type_id || create_attr.btf_value_type_id)) {
5214 		char *cp, errmsg[STRERR_BUFSIZE];
5215 
5216 		err = -errno;
5217 		cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5218 		pr_warn("Error in bpf_create_map_xattr(%s):%s(%d). Retrying without BTF.\n",
5219 			map->name, cp, err);
5220 		create_attr.btf_fd = 0;
5221 		create_attr.btf_key_type_id = 0;
5222 		create_attr.btf_value_type_id = 0;
5223 		map->btf_key_type_id = 0;
5224 		map->btf_value_type_id = 0;
5225 		map_fd = bpf_map_create(def->type, map_name,
5226 					def->key_size, def->value_size,
5227 					def->max_entries, &create_attr);
5228 	}
5229 
5230 	if (bpf_map_type__is_map_in_map(def->type) && map->inner_map) {
5231 		if (obj->gen_loader)
5232 			map->inner_map->fd = -1;
5233 		bpf_map__destroy(map->inner_map);
5234 		zfree(&map->inner_map);
5235 	}
5236 
5237 	if (map_fd < 0)
5238 		return map_fd;
5239 
5240 	/* obj->gen_loader case, prevent reuse_fd() from closing map_fd */
5241 	if (map->fd == map_fd)
5242 		return 0;
5243 
5244 	/* Keep placeholder FD value but now point it to the BPF map object.
5245 	 * This way everything that relied on this map's FD (e.g., relocated
5246 	 * ldimm64 instructions) will stay valid and won't need adjustments.
5247 	 * map->fd stays valid but now point to what map_fd points to.
5248 	 */
5249 	return reuse_fd(map->fd, map_fd);
5250 }
5251 
5252 static int init_map_in_map_slots(struct bpf_object *obj, struct bpf_map *map)
5253 {
5254 	const struct bpf_map *targ_map;
5255 	unsigned int i;
5256 	int fd, err = 0;
5257 
5258 	for (i = 0; i < map->init_slots_sz; i++) {
5259 		if (!map->init_slots[i])
5260 			continue;
5261 
5262 		targ_map = map->init_slots[i];
5263 		fd = targ_map->fd;
5264 
5265 		if (obj->gen_loader) {
5266 			bpf_gen__populate_outer_map(obj->gen_loader,
5267 						    map - obj->maps, i,
5268 						    targ_map - obj->maps);
5269 		} else {
5270 			err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5271 		}
5272 		if (err) {
5273 			err = -errno;
5274 			pr_warn("map '%s': failed to initialize slot [%d] to map '%s' fd=%d: %d\n",
5275 				map->name, i, targ_map->name, fd, err);
5276 			return err;
5277 		}
5278 		pr_debug("map '%s': slot [%d] set to map '%s' fd=%d\n",
5279 			 map->name, i, targ_map->name, fd);
5280 	}
5281 
5282 	zfree(&map->init_slots);
5283 	map->init_slots_sz = 0;
5284 
5285 	return 0;
5286 }
5287 
5288 static int init_prog_array_slots(struct bpf_object *obj, struct bpf_map *map)
5289 {
5290 	const struct bpf_program *targ_prog;
5291 	unsigned int i;
5292 	int fd, err;
5293 
5294 	if (obj->gen_loader)
5295 		return -ENOTSUP;
5296 
5297 	for (i = 0; i < map->init_slots_sz; i++) {
5298 		if (!map->init_slots[i])
5299 			continue;
5300 
5301 		targ_prog = map->init_slots[i];
5302 		fd = bpf_program__fd(targ_prog);
5303 
5304 		err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5305 		if (err) {
5306 			err = -errno;
5307 			pr_warn("map '%s': failed to initialize slot [%d] to prog '%s' fd=%d: %d\n",
5308 				map->name, i, targ_prog->name, fd, err);
5309 			return err;
5310 		}
5311 		pr_debug("map '%s': slot [%d] set to prog '%s' fd=%d\n",
5312 			 map->name, i, targ_prog->name, fd);
5313 	}
5314 
5315 	zfree(&map->init_slots);
5316 	map->init_slots_sz = 0;
5317 
5318 	return 0;
5319 }
5320 
5321 static int bpf_object_init_prog_arrays(struct bpf_object *obj)
5322 {
5323 	struct bpf_map *map;
5324 	int i, err;
5325 
5326 	for (i = 0; i < obj->nr_maps; i++) {
5327 		map = &obj->maps[i];
5328 
5329 		if (!map->init_slots_sz || map->def.type != BPF_MAP_TYPE_PROG_ARRAY)
5330 			continue;
5331 
5332 		err = init_prog_array_slots(obj, map);
5333 		if (err < 0)
5334 			return err;
5335 	}
5336 	return 0;
5337 }
5338 
5339 static int map_set_def_max_entries(struct bpf_map *map)
5340 {
5341 	if (map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY && !map->def.max_entries) {
5342 		int nr_cpus;
5343 
5344 		nr_cpus = libbpf_num_possible_cpus();
5345 		if (nr_cpus < 0) {
5346 			pr_warn("map '%s': failed to determine number of system CPUs: %d\n",
5347 				map->name, nr_cpus);
5348 			return nr_cpus;
5349 		}
5350 		pr_debug("map '%s': setting size to %d\n", map->name, nr_cpus);
5351 		map->def.max_entries = nr_cpus;
5352 	}
5353 
5354 	return 0;
5355 }
5356 
5357 static int
5358 bpf_object__create_maps(struct bpf_object *obj)
5359 {
5360 	struct bpf_map *map;
5361 	char *cp, errmsg[STRERR_BUFSIZE];
5362 	unsigned int i, j;
5363 	int err;
5364 	bool retried;
5365 
5366 	for (i = 0; i < obj->nr_maps; i++) {
5367 		map = &obj->maps[i];
5368 
5369 		/* To support old kernels, we skip creating global data maps
5370 		 * (.rodata, .data, .kconfig, etc); later on, during program
5371 		 * loading, if we detect that at least one of the to-be-loaded
5372 		 * programs is referencing any global data map, we'll error
5373 		 * out with program name and relocation index logged.
5374 		 * This approach allows to accommodate Clang emitting
5375 		 * unnecessary .rodata.str1.1 sections for string literals,
5376 		 * but also it allows to have CO-RE applications that use
5377 		 * global variables in some of BPF programs, but not others.
5378 		 * If those global variable-using programs are not loaded at
5379 		 * runtime due to bpf_program__set_autoload(prog, false),
5380 		 * bpf_object loading will succeed just fine even on old
5381 		 * kernels.
5382 		 */
5383 		if (bpf_map__is_internal(map) && !kernel_supports(obj, FEAT_GLOBAL_DATA))
5384 			map->autocreate = false;
5385 
5386 		if (!map->autocreate) {
5387 			pr_debug("map '%s': skipped auto-creating...\n", map->name);
5388 			continue;
5389 		}
5390 
5391 		err = map_set_def_max_entries(map);
5392 		if (err)
5393 			goto err_out;
5394 
5395 		retried = false;
5396 retry:
5397 		if (map->pin_path) {
5398 			err = bpf_object__reuse_map(map);
5399 			if (err) {
5400 				pr_warn("map '%s': error reusing pinned map\n",
5401 					map->name);
5402 				goto err_out;
5403 			}
5404 			if (retried && map->fd < 0) {
5405 				pr_warn("map '%s': cannot find pinned map\n",
5406 					map->name);
5407 				err = -ENOENT;
5408 				goto err_out;
5409 			}
5410 		}
5411 
5412 		if (map->reused) {
5413 			pr_debug("map '%s': skipping creation (preset fd=%d)\n",
5414 				 map->name, map->fd);
5415 		} else {
5416 			err = bpf_object__create_map(obj, map, false);
5417 			if (err)
5418 				goto err_out;
5419 
5420 			pr_debug("map '%s': created successfully, fd=%d\n",
5421 				 map->name, map->fd);
5422 
5423 			if (bpf_map__is_internal(map)) {
5424 				err = bpf_object__populate_internal_map(obj, map);
5425 				if (err < 0)
5426 					goto err_out;
5427 			}
5428 			if (map->def.type == BPF_MAP_TYPE_ARENA) {
5429 				map->mmaped = mmap((void *)(long)map->map_extra,
5430 						   bpf_map_mmap_sz(map), PROT_READ | PROT_WRITE,
5431 						   map->map_extra ? MAP_SHARED | MAP_FIXED : MAP_SHARED,
5432 						   map->fd, 0);
5433 				if (map->mmaped == MAP_FAILED) {
5434 					err = -errno;
5435 					map->mmaped = NULL;
5436 					pr_warn("map '%s': failed to mmap arena: %d\n",
5437 						map->name, err);
5438 					return err;
5439 				}
5440 				if (obj->arena_data) {
5441 					memcpy(map->mmaped, obj->arena_data, obj->arena_data_sz);
5442 					zfree(&obj->arena_data);
5443 				}
5444 			}
5445 			if (map->init_slots_sz && map->def.type != BPF_MAP_TYPE_PROG_ARRAY) {
5446 				err = init_map_in_map_slots(obj, map);
5447 				if (err < 0)
5448 					goto err_out;
5449 			}
5450 		}
5451 
5452 		if (map->pin_path && !map->pinned) {
5453 			err = bpf_map__pin(map, NULL);
5454 			if (err) {
5455 				if (!retried && err == -EEXIST) {
5456 					retried = true;
5457 					goto retry;
5458 				}
5459 				pr_warn("map '%s': failed to auto-pin at '%s': %d\n",
5460 					map->name, map->pin_path, err);
5461 				goto err_out;
5462 			}
5463 		}
5464 	}
5465 
5466 	return 0;
5467 
5468 err_out:
5469 	cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5470 	pr_warn("map '%s': failed to create: %s(%d)\n", map->name, cp, err);
5471 	pr_perm_msg(err);
5472 	for (j = 0; j < i; j++)
5473 		zclose(obj->maps[j].fd);
5474 	return err;
5475 }
5476 
5477 static bool bpf_core_is_flavor_sep(const char *s)
5478 {
5479 	/* check X___Y name pattern, where X and Y are not underscores */
5480 	return s[0] != '_' &&				      /* X */
5481 	       s[1] == '_' && s[2] == '_' && s[3] == '_' &&   /* ___ */
5482 	       s[4] != '_';				      /* Y */
5483 }
5484 
5485 /* Given 'some_struct_name___with_flavor' return the length of a name prefix
5486  * before last triple underscore. Struct name part after last triple
5487  * underscore is ignored by BPF CO-RE relocation during relocation matching.
5488  */
5489 size_t bpf_core_essential_name_len(const char *name)
5490 {
5491 	size_t n = strlen(name);
5492 	int i;
5493 
5494 	for (i = n - 5; i >= 0; i--) {
5495 		if (bpf_core_is_flavor_sep(name + i))
5496 			return i + 1;
5497 	}
5498 	return n;
5499 }
5500 
5501 void bpf_core_free_cands(struct bpf_core_cand_list *cands)
5502 {
5503 	if (!cands)
5504 		return;
5505 
5506 	free(cands->cands);
5507 	free(cands);
5508 }
5509 
5510 int bpf_core_add_cands(struct bpf_core_cand *local_cand,
5511 		       size_t local_essent_len,
5512 		       const struct btf *targ_btf,
5513 		       const char *targ_btf_name,
5514 		       int targ_start_id,
5515 		       struct bpf_core_cand_list *cands)
5516 {
5517 	struct bpf_core_cand *new_cands, *cand;
5518 	const struct btf_type *t, *local_t;
5519 	const char *targ_name, *local_name;
5520 	size_t targ_essent_len;
5521 	int n, i;
5522 
5523 	local_t = btf__type_by_id(local_cand->btf, local_cand->id);
5524 	local_name = btf__str_by_offset(local_cand->btf, local_t->name_off);
5525 
5526 	n = btf__type_cnt(targ_btf);
5527 	for (i = targ_start_id; i < n; i++) {
5528 		t = btf__type_by_id(targ_btf, i);
5529 		if (!btf_kind_core_compat(t, local_t))
5530 			continue;
5531 
5532 		targ_name = btf__name_by_offset(targ_btf, t->name_off);
5533 		if (str_is_empty(targ_name))
5534 			continue;
5535 
5536 		targ_essent_len = bpf_core_essential_name_len(targ_name);
5537 		if (targ_essent_len != local_essent_len)
5538 			continue;
5539 
5540 		if (strncmp(local_name, targ_name, local_essent_len) != 0)
5541 			continue;
5542 
5543 		pr_debug("CO-RE relocating [%d] %s %s: found target candidate [%d] %s %s in [%s]\n",
5544 			 local_cand->id, btf_kind_str(local_t),
5545 			 local_name, i, btf_kind_str(t), targ_name,
5546 			 targ_btf_name);
5547 		new_cands = libbpf_reallocarray(cands->cands, cands->len + 1,
5548 					      sizeof(*cands->cands));
5549 		if (!new_cands)
5550 			return -ENOMEM;
5551 
5552 		cand = &new_cands[cands->len];
5553 		cand->btf = targ_btf;
5554 		cand->id = i;
5555 
5556 		cands->cands = new_cands;
5557 		cands->len++;
5558 	}
5559 	return 0;
5560 }
5561 
5562 static int load_module_btfs(struct bpf_object *obj)
5563 {
5564 	struct bpf_btf_info info;
5565 	struct module_btf *mod_btf;
5566 	struct btf *btf;
5567 	char name[64];
5568 	__u32 id = 0, len;
5569 	int err, fd;
5570 
5571 	if (obj->btf_modules_loaded)
5572 		return 0;
5573 
5574 	if (obj->gen_loader)
5575 		return 0;
5576 
5577 	/* don't do this again, even if we find no module BTFs */
5578 	obj->btf_modules_loaded = true;
5579 
5580 	/* kernel too old to support module BTFs */
5581 	if (!kernel_supports(obj, FEAT_MODULE_BTF))
5582 		return 0;
5583 
5584 	while (true) {
5585 		err = bpf_btf_get_next_id(id, &id);
5586 		if (err && errno == ENOENT)
5587 			return 0;
5588 		if (err && errno == EPERM) {
5589 			pr_debug("skipping module BTFs loading, missing privileges\n");
5590 			return 0;
5591 		}
5592 		if (err) {
5593 			err = -errno;
5594 			pr_warn("failed to iterate BTF objects: %d\n", err);
5595 			return err;
5596 		}
5597 
5598 		fd = bpf_btf_get_fd_by_id(id);
5599 		if (fd < 0) {
5600 			if (errno == ENOENT)
5601 				continue; /* expected race: BTF was unloaded */
5602 			err = -errno;
5603 			pr_warn("failed to get BTF object #%d FD: %d\n", id, err);
5604 			return err;
5605 		}
5606 
5607 		len = sizeof(info);
5608 		memset(&info, 0, sizeof(info));
5609 		info.name = ptr_to_u64(name);
5610 		info.name_len = sizeof(name);
5611 
5612 		err = bpf_btf_get_info_by_fd(fd, &info, &len);
5613 		if (err) {
5614 			err = -errno;
5615 			pr_warn("failed to get BTF object #%d info: %d\n", id, err);
5616 			goto err_out;
5617 		}
5618 
5619 		/* ignore non-module BTFs */
5620 		if (!info.kernel_btf || strcmp(name, "vmlinux") == 0) {
5621 			close(fd);
5622 			continue;
5623 		}
5624 
5625 		btf = btf_get_from_fd(fd, obj->btf_vmlinux);
5626 		err = libbpf_get_error(btf);
5627 		if (err) {
5628 			pr_warn("failed to load module [%s]'s BTF object #%d: %d\n",
5629 				name, id, err);
5630 			goto err_out;
5631 		}
5632 
5633 		err = libbpf_ensure_mem((void **)&obj->btf_modules, &obj->btf_module_cap,
5634 					sizeof(*obj->btf_modules), obj->btf_module_cnt + 1);
5635 		if (err)
5636 			goto err_out;
5637 
5638 		mod_btf = &obj->btf_modules[obj->btf_module_cnt++];
5639 
5640 		mod_btf->btf = btf;
5641 		mod_btf->id = id;
5642 		mod_btf->fd = fd;
5643 		mod_btf->name = strdup(name);
5644 		if (!mod_btf->name) {
5645 			err = -ENOMEM;
5646 			goto err_out;
5647 		}
5648 		continue;
5649 
5650 err_out:
5651 		close(fd);
5652 		return err;
5653 	}
5654 
5655 	return 0;
5656 }
5657 
5658 static struct bpf_core_cand_list *
5659 bpf_core_find_cands(struct bpf_object *obj, const struct btf *local_btf, __u32 local_type_id)
5660 {
5661 	struct bpf_core_cand local_cand = {};
5662 	struct bpf_core_cand_list *cands;
5663 	const struct btf *main_btf;
5664 	const struct btf_type *local_t;
5665 	const char *local_name;
5666 	size_t local_essent_len;
5667 	int err, i;
5668 
5669 	local_cand.btf = local_btf;
5670 	local_cand.id = local_type_id;
5671 	local_t = btf__type_by_id(local_btf, local_type_id);
5672 	if (!local_t)
5673 		return ERR_PTR(-EINVAL);
5674 
5675 	local_name = btf__name_by_offset(local_btf, local_t->name_off);
5676 	if (str_is_empty(local_name))
5677 		return ERR_PTR(-EINVAL);
5678 	local_essent_len = bpf_core_essential_name_len(local_name);
5679 
5680 	cands = calloc(1, sizeof(*cands));
5681 	if (!cands)
5682 		return ERR_PTR(-ENOMEM);
5683 
5684 	/* Attempt to find target candidates in vmlinux BTF first */
5685 	main_btf = obj->btf_vmlinux_override ?: obj->btf_vmlinux;
5686 	err = bpf_core_add_cands(&local_cand, local_essent_len, main_btf, "vmlinux", 1, cands);
5687 	if (err)
5688 		goto err_out;
5689 
5690 	/* if vmlinux BTF has any candidate, don't got for module BTFs */
5691 	if (cands->len)
5692 		return cands;
5693 
5694 	/* if vmlinux BTF was overridden, don't attempt to load module BTFs */
5695 	if (obj->btf_vmlinux_override)
5696 		return cands;
5697 
5698 	/* now look through module BTFs, trying to still find candidates */
5699 	err = load_module_btfs(obj);
5700 	if (err)
5701 		goto err_out;
5702 
5703 	for (i = 0; i < obj->btf_module_cnt; i++) {
5704 		err = bpf_core_add_cands(&local_cand, local_essent_len,
5705 					 obj->btf_modules[i].btf,
5706 					 obj->btf_modules[i].name,
5707 					 btf__type_cnt(obj->btf_vmlinux),
5708 					 cands);
5709 		if (err)
5710 			goto err_out;
5711 	}
5712 
5713 	return cands;
5714 err_out:
5715 	bpf_core_free_cands(cands);
5716 	return ERR_PTR(err);
5717 }
5718 
5719 /* Check local and target types for compatibility. This check is used for
5720  * type-based CO-RE relocations and follow slightly different rules than
5721  * field-based relocations. This function assumes that root types were already
5722  * checked for name match. Beyond that initial root-level name check, names
5723  * are completely ignored. Compatibility rules are as follows:
5724  *   - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs are considered compatible, but
5725  *     kind should match for local and target types (i.e., STRUCT is not
5726  *     compatible with UNION);
5727  *   - for ENUMs, the size is ignored;
5728  *   - for INT, size and signedness are ignored;
5729  *   - for ARRAY, dimensionality is ignored, element types are checked for
5730  *     compatibility recursively;
5731  *   - CONST/VOLATILE/RESTRICT modifiers are ignored;
5732  *   - TYPEDEFs/PTRs are compatible if types they pointing to are compatible;
5733  *   - FUNC_PROTOs are compatible if they have compatible signature: same
5734  *     number of input args and compatible return and argument types.
5735  * These rules are not set in stone and probably will be adjusted as we get
5736  * more experience with using BPF CO-RE relocations.
5737  */
5738 int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
5739 			      const struct btf *targ_btf, __u32 targ_id)
5740 {
5741 	return __bpf_core_types_are_compat(local_btf, local_id, targ_btf, targ_id, 32);
5742 }
5743 
5744 int bpf_core_types_match(const struct btf *local_btf, __u32 local_id,
5745 			 const struct btf *targ_btf, __u32 targ_id)
5746 {
5747 	return __bpf_core_types_match(local_btf, local_id, targ_btf, targ_id, false, 32);
5748 }
5749 
5750 static size_t bpf_core_hash_fn(const long key, void *ctx)
5751 {
5752 	return key;
5753 }
5754 
5755 static bool bpf_core_equal_fn(const long k1, const long k2, void *ctx)
5756 {
5757 	return k1 == k2;
5758 }
5759 
5760 static int record_relo_core(struct bpf_program *prog,
5761 			    const struct bpf_core_relo *core_relo, int insn_idx)
5762 {
5763 	struct reloc_desc *relos, *relo;
5764 
5765 	relos = libbpf_reallocarray(prog->reloc_desc,
5766 				    prog->nr_reloc + 1, sizeof(*relos));
5767 	if (!relos)
5768 		return -ENOMEM;
5769 	relo = &relos[prog->nr_reloc];
5770 	relo->type = RELO_CORE;
5771 	relo->insn_idx = insn_idx;
5772 	relo->core_relo = core_relo;
5773 	prog->reloc_desc = relos;
5774 	prog->nr_reloc++;
5775 	return 0;
5776 }
5777 
5778 static const struct bpf_core_relo *find_relo_core(struct bpf_program *prog, int insn_idx)
5779 {
5780 	struct reloc_desc *relo;
5781 	int i;
5782 
5783 	for (i = 0; i < prog->nr_reloc; i++) {
5784 		relo = &prog->reloc_desc[i];
5785 		if (relo->type != RELO_CORE || relo->insn_idx != insn_idx)
5786 			continue;
5787 
5788 		return relo->core_relo;
5789 	}
5790 
5791 	return NULL;
5792 }
5793 
5794 static int bpf_core_resolve_relo(struct bpf_program *prog,
5795 				 const struct bpf_core_relo *relo,
5796 				 int relo_idx,
5797 				 const struct btf *local_btf,
5798 				 struct hashmap *cand_cache,
5799 				 struct bpf_core_relo_res *targ_res)
5800 {
5801 	struct bpf_core_spec specs_scratch[3] = {};
5802 	struct bpf_core_cand_list *cands = NULL;
5803 	const char *prog_name = prog->name;
5804 	const struct btf_type *local_type;
5805 	const char *local_name;
5806 	__u32 local_id = relo->type_id;
5807 	int err;
5808 
5809 	local_type = btf__type_by_id(local_btf, local_id);
5810 	if (!local_type)
5811 		return -EINVAL;
5812 
5813 	local_name = btf__name_by_offset(local_btf, local_type->name_off);
5814 	if (!local_name)
5815 		return -EINVAL;
5816 
5817 	if (relo->kind != BPF_CORE_TYPE_ID_LOCAL &&
5818 	    !hashmap__find(cand_cache, local_id, &cands)) {
5819 		cands = bpf_core_find_cands(prog->obj, local_btf, local_id);
5820 		if (IS_ERR(cands)) {
5821 			pr_warn("prog '%s': relo #%d: target candidate search failed for [%d] %s %s: %ld\n",
5822 				prog_name, relo_idx, local_id, btf_kind_str(local_type),
5823 				local_name, PTR_ERR(cands));
5824 			return PTR_ERR(cands);
5825 		}
5826 		err = hashmap__set(cand_cache, local_id, cands, NULL, NULL);
5827 		if (err) {
5828 			bpf_core_free_cands(cands);
5829 			return err;
5830 		}
5831 	}
5832 
5833 	return bpf_core_calc_relo_insn(prog_name, relo, relo_idx, local_btf, cands, specs_scratch,
5834 				       targ_res);
5835 }
5836 
5837 static int
5838 bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
5839 {
5840 	const struct btf_ext_info_sec *sec;
5841 	struct bpf_core_relo_res targ_res;
5842 	const struct bpf_core_relo *rec;
5843 	const struct btf_ext_info *seg;
5844 	struct hashmap_entry *entry;
5845 	struct hashmap *cand_cache = NULL;
5846 	struct bpf_program *prog;
5847 	struct bpf_insn *insn;
5848 	const char *sec_name;
5849 	int i, err = 0, insn_idx, sec_idx, sec_num;
5850 
5851 	if (obj->btf_ext->core_relo_info.len == 0)
5852 		return 0;
5853 
5854 	if (targ_btf_path) {
5855 		obj->btf_vmlinux_override = btf__parse(targ_btf_path, NULL);
5856 		err = libbpf_get_error(obj->btf_vmlinux_override);
5857 		if (err) {
5858 			pr_warn("failed to parse target BTF: %d\n", err);
5859 			return err;
5860 		}
5861 	}
5862 
5863 	cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
5864 	if (IS_ERR(cand_cache)) {
5865 		err = PTR_ERR(cand_cache);
5866 		goto out;
5867 	}
5868 
5869 	seg = &obj->btf_ext->core_relo_info;
5870 	sec_num = 0;
5871 	for_each_btf_ext_sec(seg, sec) {
5872 		sec_idx = seg->sec_idxs[sec_num];
5873 		sec_num++;
5874 
5875 		sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
5876 		if (str_is_empty(sec_name)) {
5877 			err = -EINVAL;
5878 			goto out;
5879 		}
5880 
5881 		pr_debug("sec '%s': found %d CO-RE relocations\n", sec_name, sec->num_info);
5882 
5883 		for_each_btf_ext_rec(seg, sec, i, rec) {
5884 			if (rec->insn_off % BPF_INSN_SZ)
5885 				return -EINVAL;
5886 			insn_idx = rec->insn_off / BPF_INSN_SZ;
5887 			prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
5888 			if (!prog) {
5889 				/* When __weak subprog is "overridden" by another instance
5890 				 * of the subprog from a different object file, linker still
5891 				 * appends all the .BTF.ext info that used to belong to that
5892 				 * eliminated subprogram.
5893 				 * This is similar to what x86-64 linker does for relocations.
5894 				 * So just ignore such relocations just like we ignore
5895 				 * subprog instructions when discovering subprograms.
5896 				 */
5897 				pr_debug("sec '%s': skipping CO-RE relocation #%d for insn #%d belonging to eliminated weak subprogram\n",
5898 					 sec_name, i, insn_idx);
5899 				continue;
5900 			}
5901 			/* no need to apply CO-RE relocation if the program is
5902 			 * not going to be loaded
5903 			 */
5904 			if (!prog->autoload)
5905 				continue;
5906 
5907 			/* adjust insn_idx from section frame of reference to the local
5908 			 * program's frame of reference; (sub-)program code is not yet
5909 			 * relocated, so it's enough to just subtract in-section offset
5910 			 */
5911 			insn_idx = insn_idx - prog->sec_insn_off;
5912 			if (insn_idx >= prog->insns_cnt)
5913 				return -EINVAL;
5914 			insn = &prog->insns[insn_idx];
5915 
5916 			err = record_relo_core(prog, rec, insn_idx);
5917 			if (err) {
5918 				pr_warn("prog '%s': relo #%d: failed to record relocation: %d\n",
5919 					prog->name, i, err);
5920 				goto out;
5921 			}
5922 
5923 			if (prog->obj->gen_loader)
5924 				continue;
5925 
5926 			err = bpf_core_resolve_relo(prog, rec, i, obj->btf, cand_cache, &targ_res);
5927 			if (err) {
5928 				pr_warn("prog '%s': relo #%d: failed to relocate: %d\n",
5929 					prog->name, i, err);
5930 				goto out;
5931 			}
5932 
5933 			err = bpf_core_patch_insn(prog->name, insn, insn_idx, rec, i, &targ_res);
5934 			if (err) {
5935 				pr_warn("prog '%s': relo #%d: failed to patch insn #%u: %d\n",
5936 					prog->name, i, insn_idx, err);
5937 				goto out;
5938 			}
5939 		}
5940 	}
5941 
5942 out:
5943 	/* obj->btf_vmlinux and module BTFs are freed after object load */
5944 	btf__free(obj->btf_vmlinux_override);
5945 	obj->btf_vmlinux_override = NULL;
5946 
5947 	if (!IS_ERR_OR_NULL(cand_cache)) {
5948 		hashmap__for_each_entry(cand_cache, entry, i) {
5949 			bpf_core_free_cands(entry->pvalue);
5950 		}
5951 		hashmap__free(cand_cache);
5952 	}
5953 	return err;
5954 }
5955 
5956 /* base map load ldimm64 special constant, used also for log fixup logic */
5957 #define POISON_LDIMM64_MAP_BASE 2001000000
5958 #define POISON_LDIMM64_MAP_PFX "200100"
5959 
5960 static void poison_map_ldimm64(struct bpf_program *prog, int relo_idx,
5961 			       int insn_idx, struct bpf_insn *insn,
5962 			       int map_idx, const struct bpf_map *map)
5963 {
5964 	int i;
5965 
5966 	pr_debug("prog '%s': relo #%d: poisoning insn #%d that loads map #%d '%s'\n",
5967 		 prog->name, relo_idx, insn_idx, map_idx, map->name);
5968 
5969 	/* we turn single ldimm64 into two identical invalid calls */
5970 	for (i = 0; i < 2; i++) {
5971 		insn->code = BPF_JMP | BPF_CALL;
5972 		insn->dst_reg = 0;
5973 		insn->src_reg = 0;
5974 		insn->off = 0;
5975 		/* if this instruction is reachable (not a dead code),
5976 		 * verifier will complain with something like:
5977 		 * invalid func unknown#2001000123
5978 		 * where lower 123 is map index into obj->maps[] array
5979 		 */
5980 		insn->imm = POISON_LDIMM64_MAP_BASE + map_idx;
5981 
5982 		insn++;
5983 	}
5984 }
5985 
5986 /* unresolved kfunc call special constant, used also for log fixup logic */
5987 #define POISON_CALL_KFUNC_BASE 2002000000
5988 #define POISON_CALL_KFUNC_PFX "2002"
5989 
5990 static void poison_kfunc_call(struct bpf_program *prog, int relo_idx,
5991 			      int insn_idx, struct bpf_insn *insn,
5992 			      int ext_idx, const struct extern_desc *ext)
5993 {
5994 	pr_debug("prog '%s': relo #%d: poisoning insn #%d that calls kfunc '%s'\n",
5995 		 prog->name, relo_idx, insn_idx, ext->name);
5996 
5997 	/* we turn kfunc call into invalid helper call with identifiable constant */
5998 	insn->code = BPF_JMP | BPF_CALL;
5999 	insn->dst_reg = 0;
6000 	insn->src_reg = 0;
6001 	insn->off = 0;
6002 	/* if this instruction is reachable (not a dead code),
6003 	 * verifier will complain with something like:
6004 	 * invalid func unknown#2001000123
6005 	 * where lower 123 is extern index into obj->externs[] array
6006 	 */
6007 	insn->imm = POISON_CALL_KFUNC_BASE + ext_idx;
6008 }
6009 
6010 /* Relocate data references within program code:
6011  *  - map references;
6012  *  - global variable references;
6013  *  - extern references.
6014  */
6015 static int
6016 bpf_object__relocate_data(struct bpf_object *obj, struct bpf_program *prog)
6017 {
6018 	int i;
6019 
6020 	for (i = 0; i < prog->nr_reloc; i++) {
6021 		struct reloc_desc *relo = &prog->reloc_desc[i];
6022 		struct bpf_insn *insn = &prog->insns[relo->insn_idx];
6023 		const struct bpf_map *map;
6024 		struct extern_desc *ext;
6025 
6026 		switch (relo->type) {
6027 		case RELO_LD64:
6028 			map = &obj->maps[relo->map_idx];
6029 			if (obj->gen_loader) {
6030 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX;
6031 				insn[0].imm = relo->map_idx;
6032 			} else if (map->autocreate) {
6033 				insn[0].src_reg = BPF_PSEUDO_MAP_FD;
6034 				insn[0].imm = map->fd;
6035 			} else {
6036 				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
6037 						   relo->map_idx, map);
6038 			}
6039 			break;
6040 		case RELO_DATA:
6041 			map = &obj->maps[relo->map_idx];
6042 			insn[1].imm = insn[0].imm + relo->sym_off;
6043 			if (obj->gen_loader) {
6044 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
6045 				insn[0].imm = relo->map_idx;
6046 			} else if (map->autocreate) {
6047 				insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6048 				insn[0].imm = map->fd;
6049 			} else {
6050 				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
6051 						   relo->map_idx, map);
6052 			}
6053 			break;
6054 		case RELO_EXTERN_LD64:
6055 			ext = &obj->externs[relo->ext_idx];
6056 			if (ext->type == EXT_KCFG) {
6057 				if (obj->gen_loader) {
6058 					insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
6059 					insn[0].imm = obj->kconfig_map_idx;
6060 				} else {
6061 					insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6062 					insn[0].imm = obj->maps[obj->kconfig_map_idx].fd;
6063 				}
6064 				insn[1].imm = ext->kcfg.data_off;
6065 			} else /* EXT_KSYM */ {
6066 				if (ext->ksym.type_id && ext->is_set) { /* typed ksyms */
6067 					insn[0].src_reg = BPF_PSEUDO_BTF_ID;
6068 					insn[0].imm = ext->ksym.kernel_btf_id;
6069 					insn[1].imm = ext->ksym.kernel_btf_obj_fd;
6070 				} else { /* typeless ksyms or unresolved typed ksyms */
6071 					insn[0].imm = (__u32)ext->ksym.addr;
6072 					insn[1].imm = ext->ksym.addr >> 32;
6073 				}
6074 			}
6075 			break;
6076 		case RELO_EXTERN_CALL:
6077 			ext = &obj->externs[relo->ext_idx];
6078 			insn[0].src_reg = BPF_PSEUDO_KFUNC_CALL;
6079 			if (ext->is_set) {
6080 				insn[0].imm = ext->ksym.kernel_btf_id;
6081 				insn[0].off = ext->ksym.btf_fd_idx;
6082 			} else { /* unresolved weak kfunc call */
6083 				poison_kfunc_call(prog, i, relo->insn_idx, insn,
6084 						  relo->ext_idx, ext);
6085 			}
6086 			break;
6087 		case RELO_SUBPROG_ADDR:
6088 			if (insn[0].src_reg != BPF_PSEUDO_FUNC) {
6089 				pr_warn("prog '%s': relo #%d: bad insn\n",
6090 					prog->name, i);
6091 				return -EINVAL;
6092 			}
6093 			/* handled already */
6094 			break;
6095 		case RELO_CALL:
6096 			/* handled already */
6097 			break;
6098 		case RELO_CORE:
6099 			/* will be handled by bpf_program_record_relos() */
6100 			break;
6101 		default:
6102 			pr_warn("prog '%s': relo #%d: bad relo type %d\n",
6103 				prog->name, i, relo->type);
6104 			return -EINVAL;
6105 		}
6106 	}
6107 
6108 	return 0;
6109 }
6110 
6111 static int adjust_prog_btf_ext_info(const struct bpf_object *obj,
6112 				    const struct bpf_program *prog,
6113 				    const struct btf_ext_info *ext_info,
6114 				    void **prog_info, __u32 *prog_rec_cnt,
6115 				    __u32 *prog_rec_sz)
6116 {
6117 	void *copy_start = NULL, *copy_end = NULL;
6118 	void *rec, *rec_end, *new_prog_info;
6119 	const struct btf_ext_info_sec *sec;
6120 	size_t old_sz, new_sz;
6121 	int i, sec_num, sec_idx, off_adj;
6122 
6123 	sec_num = 0;
6124 	for_each_btf_ext_sec(ext_info, sec) {
6125 		sec_idx = ext_info->sec_idxs[sec_num];
6126 		sec_num++;
6127 		if (prog->sec_idx != sec_idx)
6128 			continue;
6129 
6130 		for_each_btf_ext_rec(ext_info, sec, i, rec) {
6131 			__u32 insn_off = *(__u32 *)rec / BPF_INSN_SZ;
6132 
6133 			if (insn_off < prog->sec_insn_off)
6134 				continue;
6135 			if (insn_off >= prog->sec_insn_off + prog->sec_insn_cnt)
6136 				break;
6137 
6138 			if (!copy_start)
6139 				copy_start = rec;
6140 			copy_end = rec + ext_info->rec_size;
6141 		}
6142 
6143 		if (!copy_start)
6144 			return -ENOENT;
6145 
6146 		/* append func/line info of a given (sub-)program to the main
6147 		 * program func/line info
6148 		 */
6149 		old_sz = (size_t)(*prog_rec_cnt) * ext_info->rec_size;
6150 		new_sz = old_sz + (copy_end - copy_start);
6151 		new_prog_info = realloc(*prog_info, new_sz);
6152 		if (!new_prog_info)
6153 			return -ENOMEM;
6154 		*prog_info = new_prog_info;
6155 		*prog_rec_cnt = new_sz / ext_info->rec_size;
6156 		memcpy(new_prog_info + old_sz, copy_start, copy_end - copy_start);
6157 
6158 		/* Kernel instruction offsets are in units of 8-byte
6159 		 * instructions, while .BTF.ext instruction offsets generated
6160 		 * by Clang are in units of bytes. So convert Clang offsets
6161 		 * into kernel offsets and adjust offset according to program
6162 		 * relocated position.
6163 		 */
6164 		off_adj = prog->sub_insn_off - prog->sec_insn_off;
6165 		rec = new_prog_info + old_sz;
6166 		rec_end = new_prog_info + new_sz;
6167 		for (; rec < rec_end; rec += ext_info->rec_size) {
6168 			__u32 *insn_off = rec;
6169 
6170 			*insn_off = *insn_off / BPF_INSN_SZ + off_adj;
6171 		}
6172 		*prog_rec_sz = ext_info->rec_size;
6173 		return 0;
6174 	}
6175 
6176 	return -ENOENT;
6177 }
6178 
6179 static int
6180 reloc_prog_func_and_line_info(const struct bpf_object *obj,
6181 			      struct bpf_program *main_prog,
6182 			      const struct bpf_program *prog)
6183 {
6184 	int err;
6185 
6186 	/* no .BTF.ext relocation if .BTF.ext is missing or kernel doesn't
6187 	 * support func/line info
6188 	 */
6189 	if (!obj->btf_ext || !kernel_supports(obj, FEAT_BTF_FUNC))
6190 		return 0;
6191 
6192 	/* only attempt func info relocation if main program's func_info
6193 	 * relocation was successful
6194 	 */
6195 	if (main_prog != prog && !main_prog->func_info)
6196 		goto line_info;
6197 
6198 	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->func_info,
6199 				       &main_prog->func_info,
6200 				       &main_prog->func_info_cnt,
6201 				       &main_prog->func_info_rec_size);
6202 	if (err) {
6203 		if (err != -ENOENT) {
6204 			pr_warn("prog '%s': error relocating .BTF.ext function info: %d\n",
6205 				prog->name, err);
6206 			return err;
6207 		}
6208 		if (main_prog->func_info) {
6209 			/*
6210 			 * Some info has already been found but has problem
6211 			 * in the last btf_ext reloc. Must have to error out.
6212 			 */
6213 			pr_warn("prog '%s': missing .BTF.ext function info.\n", prog->name);
6214 			return err;
6215 		}
6216 		/* Have problem loading the very first info. Ignore the rest. */
6217 		pr_warn("prog '%s': missing .BTF.ext function info for the main program, skipping all of .BTF.ext func info.\n",
6218 			prog->name);
6219 	}
6220 
6221 line_info:
6222 	/* don't relocate line info if main program's relocation failed */
6223 	if (main_prog != prog && !main_prog->line_info)
6224 		return 0;
6225 
6226 	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->line_info,
6227 				       &main_prog->line_info,
6228 				       &main_prog->line_info_cnt,
6229 				       &main_prog->line_info_rec_size);
6230 	if (err) {
6231 		if (err != -ENOENT) {
6232 			pr_warn("prog '%s': error relocating .BTF.ext line info: %d\n",
6233 				prog->name, err);
6234 			return err;
6235 		}
6236 		if (main_prog->line_info) {
6237 			/*
6238 			 * Some info has already been found but has problem
6239 			 * in the last btf_ext reloc. Must have to error out.
6240 			 */
6241 			pr_warn("prog '%s': missing .BTF.ext line info.\n", prog->name);
6242 			return err;
6243 		}
6244 		/* Have problem loading the very first info. Ignore the rest. */
6245 		pr_warn("prog '%s': missing .BTF.ext line info for the main program, skipping all of .BTF.ext line info.\n",
6246 			prog->name);
6247 	}
6248 	return 0;
6249 }
6250 
6251 static int cmp_relo_by_insn_idx(const void *key, const void *elem)
6252 {
6253 	size_t insn_idx = *(const size_t *)key;
6254 	const struct reloc_desc *relo = elem;
6255 
6256 	if (insn_idx == relo->insn_idx)
6257 		return 0;
6258 	return insn_idx < relo->insn_idx ? -1 : 1;
6259 }
6260 
6261 static struct reloc_desc *find_prog_insn_relo(const struct bpf_program *prog, size_t insn_idx)
6262 {
6263 	if (!prog->nr_reloc)
6264 		return NULL;
6265 	return bsearch(&insn_idx, prog->reloc_desc, prog->nr_reloc,
6266 		       sizeof(*prog->reloc_desc), cmp_relo_by_insn_idx);
6267 }
6268 
6269 static int append_subprog_relos(struct bpf_program *main_prog, struct bpf_program *subprog)
6270 {
6271 	int new_cnt = main_prog->nr_reloc + subprog->nr_reloc;
6272 	struct reloc_desc *relos;
6273 	int i;
6274 
6275 	if (main_prog == subprog)
6276 		return 0;
6277 	relos = libbpf_reallocarray(main_prog->reloc_desc, new_cnt, sizeof(*relos));
6278 	/* if new count is zero, reallocarray can return a valid NULL result;
6279 	 * in this case the previous pointer will be freed, so we *have to*
6280 	 * reassign old pointer to the new value (even if it's NULL)
6281 	 */
6282 	if (!relos && new_cnt)
6283 		return -ENOMEM;
6284 	if (subprog->nr_reloc)
6285 		memcpy(relos + main_prog->nr_reloc, subprog->reloc_desc,
6286 		       sizeof(*relos) * subprog->nr_reloc);
6287 
6288 	for (i = main_prog->nr_reloc; i < new_cnt; i++)
6289 		relos[i].insn_idx += subprog->sub_insn_off;
6290 	/* After insn_idx adjustment the 'relos' array is still sorted
6291 	 * by insn_idx and doesn't break bsearch.
6292 	 */
6293 	main_prog->reloc_desc = relos;
6294 	main_prog->nr_reloc = new_cnt;
6295 	return 0;
6296 }
6297 
6298 static int
6299 bpf_object__append_subprog_code(struct bpf_object *obj, struct bpf_program *main_prog,
6300 				struct bpf_program *subprog)
6301 {
6302        struct bpf_insn *insns;
6303        size_t new_cnt;
6304        int err;
6305 
6306        subprog->sub_insn_off = main_prog->insns_cnt;
6307 
6308        new_cnt = main_prog->insns_cnt + subprog->insns_cnt;
6309        insns = libbpf_reallocarray(main_prog->insns, new_cnt, sizeof(*insns));
6310        if (!insns) {
6311                pr_warn("prog '%s': failed to realloc prog code\n", main_prog->name);
6312                return -ENOMEM;
6313        }
6314        main_prog->insns = insns;
6315        main_prog->insns_cnt = new_cnt;
6316 
6317        memcpy(main_prog->insns + subprog->sub_insn_off, subprog->insns,
6318               subprog->insns_cnt * sizeof(*insns));
6319 
6320        pr_debug("prog '%s': added %zu insns from sub-prog '%s'\n",
6321                 main_prog->name, subprog->insns_cnt, subprog->name);
6322 
6323        /* The subprog insns are now appended. Append its relos too. */
6324        err = append_subprog_relos(main_prog, subprog);
6325        if (err)
6326                return err;
6327        return 0;
6328 }
6329 
6330 static int
6331 bpf_object__reloc_code(struct bpf_object *obj, struct bpf_program *main_prog,
6332 		       struct bpf_program *prog)
6333 {
6334 	size_t sub_insn_idx, insn_idx;
6335 	struct bpf_program *subprog;
6336 	struct reloc_desc *relo;
6337 	struct bpf_insn *insn;
6338 	int err;
6339 
6340 	err = reloc_prog_func_and_line_info(obj, main_prog, prog);
6341 	if (err)
6342 		return err;
6343 
6344 	for (insn_idx = 0; insn_idx < prog->sec_insn_cnt; insn_idx++) {
6345 		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6346 		if (!insn_is_subprog_call(insn) && !insn_is_pseudo_func(insn))
6347 			continue;
6348 
6349 		relo = find_prog_insn_relo(prog, insn_idx);
6350 		if (relo && relo->type == RELO_EXTERN_CALL)
6351 			/* kfunc relocations will be handled later
6352 			 * in bpf_object__relocate_data()
6353 			 */
6354 			continue;
6355 		if (relo && relo->type != RELO_CALL && relo->type != RELO_SUBPROG_ADDR) {
6356 			pr_warn("prog '%s': unexpected relo for insn #%zu, type %d\n",
6357 				prog->name, insn_idx, relo->type);
6358 			return -LIBBPF_ERRNO__RELOC;
6359 		}
6360 		if (relo) {
6361 			/* sub-program instruction index is a combination of
6362 			 * an offset of a symbol pointed to by relocation and
6363 			 * call instruction's imm field; for global functions,
6364 			 * call always has imm = -1, but for static functions
6365 			 * relocation is against STT_SECTION and insn->imm
6366 			 * points to a start of a static function
6367 			 *
6368 			 * for subprog addr relocation, the relo->sym_off + insn->imm is
6369 			 * the byte offset in the corresponding section.
6370 			 */
6371 			if (relo->type == RELO_CALL)
6372 				sub_insn_idx = relo->sym_off / BPF_INSN_SZ + insn->imm + 1;
6373 			else
6374 				sub_insn_idx = (relo->sym_off + insn->imm) / BPF_INSN_SZ;
6375 		} else if (insn_is_pseudo_func(insn)) {
6376 			/*
6377 			 * RELO_SUBPROG_ADDR relo is always emitted even if both
6378 			 * functions are in the same section, so it shouldn't reach here.
6379 			 */
6380 			pr_warn("prog '%s': missing subprog addr relo for insn #%zu\n",
6381 				prog->name, insn_idx);
6382 			return -LIBBPF_ERRNO__RELOC;
6383 		} else {
6384 			/* if subprogram call is to a static function within
6385 			 * the same ELF section, there won't be any relocation
6386 			 * emitted, but it also means there is no additional
6387 			 * offset necessary, insns->imm is relative to
6388 			 * instruction's original position within the section
6389 			 */
6390 			sub_insn_idx = prog->sec_insn_off + insn_idx + insn->imm + 1;
6391 		}
6392 
6393 		/* we enforce that sub-programs should be in .text section */
6394 		subprog = find_prog_by_sec_insn(obj, obj->efile.text_shndx, sub_insn_idx);
6395 		if (!subprog) {
6396 			pr_warn("prog '%s': no .text section found yet sub-program call exists\n",
6397 				prog->name);
6398 			return -LIBBPF_ERRNO__RELOC;
6399 		}
6400 
6401 		/* if it's the first call instruction calling into this
6402 		 * subprogram (meaning this subprog hasn't been processed
6403 		 * yet) within the context of current main program:
6404 		 *   - append it at the end of main program's instructions blog;
6405 		 *   - process is recursively, while current program is put on hold;
6406 		 *   - if that subprogram calls some other not yet processes
6407 		 *   subprogram, same thing will happen recursively until
6408 		 *   there are no more unprocesses subprograms left to append
6409 		 *   and relocate.
6410 		 */
6411 		if (subprog->sub_insn_off == 0) {
6412 			err = bpf_object__append_subprog_code(obj, main_prog, subprog);
6413 			if (err)
6414 				return err;
6415 			err = bpf_object__reloc_code(obj, main_prog, subprog);
6416 			if (err)
6417 				return err;
6418 		}
6419 
6420 		/* main_prog->insns memory could have been re-allocated, so
6421 		 * calculate pointer again
6422 		 */
6423 		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6424 		/* calculate correct instruction position within current main
6425 		 * prog; each main prog can have a different set of
6426 		 * subprograms appended (potentially in different order as
6427 		 * well), so position of any subprog can be different for
6428 		 * different main programs
6429 		 */
6430 		insn->imm = subprog->sub_insn_off - (prog->sub_insn_off + insn_idx) - 1;
6431 
6432 		pr_debug("prog '%s': insn #%zu relocated, imm %d points to subprog '%s' (now at %zu offset)\n",
6433 			 prog->name, insn_idx, insn->imm, subprog->name, subprog->sub_insn_off);
6434 	}
6435 
6436 	return 0;
6437 }
6438 
6439 /*
6440  * Relocate sub-program calls.
6441  *
6442  * Algorithm operates as follows. Each entry-point BPF program (referred to as
6443  * main prog) is processed separately. For each subprog (non-entry functions,
6444  * that can be called from either entry progs or other subprogs) gets their
6445  * sub_insn_off reset to zero. This serves as indicator that this subprogram
6446  * hasn't been yet appended and relocated within current main prog. Once its
6447  * relocated, sub_insn_off will point at the position within current main prog
6448  * where given subprog was appended. This will further be used to relocate all
6449  * the call instructions jumping into this subprog.
6450  *
6451  * We start with main program and process all call instructions. If the call
6452  * is into a subprog that hasn't been processed (i.e., subprog->sub_insn_off
6453  * is zero), subprog instructions are appended at the end of main program's
6454  * instruction array. Then main program is "put on hold" while we recursively
6455  * process newly appended subprogram. If that subprogram calls into another
6456  * subprogram that hasn't been appended, new subprogram is appended again to
6457  * the *main* prog's instructions (subprog's instructions are always left
6458  * untouched, as they need to be in unmodified state for subsequent main progs
6459  * and subprog instructions are always sent only as part of a main prog) and
6460  * the process continues recursively. Once all the subprogs called from a main
6461  * prog or any of its subprogs are appended (and relocated), all their
6462  * positions within finalized instructions array are known, so it's easy to
6463  * rewrite call instructions with correct relative offsets, corresponding to
6464  * desired target subprog.
6465  *
6466  * Its important to realize that some subprogs might not be called from some
6467  * main prog and any of its called/used subprogs. Those will keep their
6468  * subprog->sub_insn_off as zero at all times and won't be appended to current
6469  * main prog and won't be relocated within the context of current main prog.
6470  * They might still be used from other main progs later.
6471  *
6472  * Visually this process can be shown as below. Suppose we have two main
6473  * programs mainA and mainB and BPF object contains three subprogs: subA,
6474  * subB, and subC. mainA calls only subA, mainB calls only subC, but subA and
6475  * subC both call subB:
6476  *
6477  *        +--------+ +-------+
6478  *        |        v v       |
6479  *     +--+---+ +--+-+-+ +---+--+
6480  *     | subA | | subB | | subC |
6481  *     +--+---+ +------+ +---+--+
6482  *        ^                  ^
6483  *        |                  |
6484  *    +---+-------+   +------+----+
6485  *    |   mainA   |   |   mainB   |
6486  *    +-----------+   +-----------+
6487  *
6488  * We'll start relocating mainA, will find subA, append it and start
6489  * processing sub A recursively:
6490  *
6491  *    +-----------+------+
6492  *    |   mainA   | subA |
6493  *    +-----------+------+
6494  *
6495  * At this point we notice that subB is used from subA, so we append it and
6496  * relocate (there are no further subcalls from subB):
6497  *
6498  *    +-----------+------+------+
6499  *    |   mainA   | subA | subB |
6500  *    +-----------+------+------+
6501  *
6502  * At this point, we relocate subA calls, then go one level up and finish with
6503  * relocatin mainA calls. mainA is done.
6504  *
6505  * For mainB process is similar but results in different order. We start with
6506  * mainB and skip subA and subB, as mainB never calls them (at least
6507  * directly), but we see subC is needed, so we append and start processing it:
6508  *
6509  *    +-----------+------+
6510  *    |   mainB   | subC |
6511  *    +-----------+------+
6512  * Now we see subC needs subB, so we go back to it, append and relocate it:
6513  *
6514  *    +-----------+------+------+
6515  *    |   mainB   | subC | subB |
6516  *    +-----------+------+------+
6517  *
6518  * At this point we unwind recursion, relocate calls in subC, then in mainB.
6519  */
6520 static int
6521 bpf_object__relocate_calls(struct bpf_object *obj, struct bpf_program *prog)
6522 {
6523 	struct bpf_program *subprog;
6524 	int i, err;
6525 
6526 	/* mark all subprogs as not relocated (yet) within the context of
6527 	 * current main program
6528 	 */
6529 	for (i = 0; i < obj->nr_programs; i++) {
6530 		subprog = &obj->programs[i];
6531 		if (!prog_is_subprog(obj, subprog))
6532 			continue;
6533 
6534 		subprog->sub_insn_off = 0;
6535 	}
6536 
6537 	err = bpf_object__reloc_code(obj, prog, prog);
6538 	if (err)
6539 		return err;
6540 
6541 	return 0;
6542 }
6543 
6544 static void
6545 bpf_object__free_relocs(struct bpf_object *obj)
6546 {
6547 	struct bpf_program *prog;
6548 	int i;
6549 
6550 	/* free up relocation descriptors */
6551 	for (i = 0; i < obj->nr_programs; i++) {
6552 		prog = &obj->programs[i];
6553 		zfree(&prog->reloc_desc);
6554 		prog->nr_reloc = 0;
6555 	}
6556 }
6557 
6558 static int cmp_relocs(const void *_a, const void *_b)
6559 {
6560 	const struct reloc_desc *a = _a;
6561 	const struct reloc_desc *b = _b;
6562 
6563 	if (a->insn_idx != b->insn_idx)
6564 		return a->insn_idx < b->insn_idx ? -1 : 1;
6565 
6566 	/* no two relocations should have the same insn_idx, but ... */
6567 	if (a->type != b->type)
6568 		return a->type < b->type ? -1 : 1;
6569 
6570 	return 0;
6571 }
6572 
6573 static void bpf_object__sort_relos(struct bpf_object *obj)
6574 {
6575 	int i;
6576 
6577 	for (i = 0; i < obj->nr_programs; i++) {
6578 		struct bpf_program *p = &obj->programs[i];
6579 
6580 		if (!p->nr_reloc)
6581 			continue;
6582 
6583 		qsort(p->reloc_desc, p->nr_reloc, sizeof(*p->reloc_desc), cmp_relocs);
6584 	}
6585 }
6586 
6587 static int bpf_prog_assign_exc_cb(struct bpf_object *obj, struct bpf_program *prog)
6588 {
6589 	const char *str = "exception_callback:";
6590 	size_t pfx_len = strlen(str);
6591 	int i, j, n;
6592 
6593 	if (!obj->btf || !kernel_supports(obj, FEAT_BTF_DECL_TAG))
6594 		return 0;
6595 
6596 	n = btf__type_cnt(obj->btf);
6597 	for (i = 1; i < n; i++) {
6598 		const char *name;
6599 		struct btf_type *t;
6600 
6601 		t = btf_type_by_id(obj->btf, i);
6602 		if (!btf_is_decl_tag(t) || btf_decl_tag(t)->component_idx != -1)
6603 			continue;
6604 
6605 		name = btf__str_by_offset(obj->btf, t->name_off);
6606 		if (strncmp(name, str, pfx_len) != 0)
6607 			continue;
6608 
6609 		t = btf_type_by_id(obj->btf, t->type);
6610 		if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL) {
6611 			pr_warn("prog '%s': exception_callback:<value> decl tag not applied to the main program\n",
6612 				prog->name);
6613 			return -EINVAL;
6614 		}
6615 		if (strcmp(prog->name, btf__str_by_offset(obj->btf, t->name_off)) != 0)
6616 			continue;
6617 		/* Multiple callbacks are specified for the same prog,
6618 		 * the verifier will eventually return an error for this
6619 		 * case, hence simply skip appending a subprog.
6620 		 */
6621 		if (prog->exception_cb_idx >= 0) {
6622 			prog->exception_cb_idx = -1;
6623 			break;
6624 		}
6625 
6626 		name += pfx_len;
6627 		if (str_is_empty(name)) {
6628 			pr_warn("prog '%s': exception_callback:<value> decl tag contains empty value\n",
6629 				prog->name);
6630 			return -EINVAL;
6631 		}
6632 
6633 		for (j = 0; j < obj->nr_programs; j++) {
6634 			struct bpf_program *subprog = &obj->programs[j];
6635 
6636 			if (!prog_is_subprog(obj, subprog))
6637 				continue;
6638 			if (strcmp(name, subprog->name) != 0)
6639 				continue;
6640 			/* Enforce non-hidden, as from verifier point of
6641 			 * view it expects global functions, whereas the
6642 			 * mark_btf_static fixes up linkage as static.
6643 			 */
6644 			if (!subprog->sym_global || subprog->mark_btf_static) {
6645 				pr_warn("prog '%s': exception callback %s must be a global non-hidden function\n",
6646 					prog->name, subprog->name);
6647 				return -EINVAL;
6648 			}
6649 			/* Let's see if we already saw a static exception callback with the same name */
6650 			if (prog->exception_cb_idx >= 0) {
6651 				pr_warn("prog '%s': multiple subprogs with same name as exception callback '%s'\n",
6652 					prog->name, subprog->name);
6653 				return -EINVAL;
6654 			}
6655 			prog->exception_cb_idx = j;
6656 			break;
6657 		}
6658 
6659 		if (prog->exception_cb_idx >= 0)
6660 			continue;
6661 
6662 		pr_warn("prog '%s': cannot find exception callback '%s'\n", prog->name, name);
6663 		return -ENOENT;
6664 	}
6665 
6666 	return 0;
6667 }
6668 
6669 static struct {
6670 	enum bpf_prog_type prog_type;
6671 	const char *ctx_name;
6672 } global_ctx_map[] = {
6673 	{ BPF_PROG_TYPE_CGROUP_DEVICE,           "bpf_cgroup_dev_ctx" },
6674 	{ BPF_PROG_TYPE_CGROUP_SKB,              "__sk_buff" },
6675 	{ BPF_PROG_TYPE_CGROUP_SOCK,             "bpf_sock" },
6676 	{ BPF_PROG_TYPE_CGROUP_SOCK_ADDR,        "bpf_sock_addr" },
6677 	{ BPF_PROG_TYPE_CGROUP_SOCKOPT,          "bpf_sockopt" },
6678 	{ BPF_PROG_TYPE_CGROUP_SYSCTL,           "bpf_sysctl" },
6679 	{ BPF_PROG_TYPE_FLOW_DISSECTOR,          "__sk_buff" },
6680 	{ BPF_PROG_TYPE_KPROBE,                  "bpf_user_pt_regs_t" },
6681 	{ BPF_PROG_TYPE_LWT_IN,                  "__sk_buff" },
6682 	{ BPF_PROG_TYPE_LWT_OUT,                 "__sk_buff" },
6683 	{ BPF_PROG_TYPE_LWT_SEG6LOCAL,           "__sk_buff" },
6684 	{ BPF_PROG_TYPE_LWT_XMIT,                "__sk_buff" },
6685 	{ BPF_PROG_TYPE_NETFILTER,               "bpf_nf_ctx" },
6686 	{ BPF_PROG_TYPE_PERF_EVENT,              "bpf_perf_event_data" },
6687 	{ BPF_PROG_TYPE_RAW_TRACEPOINT,          "bpf_raw_tracepoint_args" },
6688 	{ BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE, "bpf_raw_tracepoint_args" },
6689 	{ BPF_PROG_TYPE_SCHED_ACT,               "__sk_buff" },
6690 	{ BPF_PROG_TYPE_SCHED_CLS,               "__sk_buff" },
6691 	{ BPF_PROG_TYPE_SK_LOOKUP,               "bpf_sk_lookup" },
6692 	{ BPF_PROG_TYPE_SK_MSG,                  "sk_msg_md" },
6693 	{ BPF_PROG_TYPE_SK_REUSEPORT,            "sk_reuseport_md" },
6694 	{ BPF_PROG_TYPE_SK_SKB,                  "__sk_buff" },
6695 	{ BPF_PROG_TYPE_SOCK_OPS,                "bpf_sock_ops" },
6696 	{ BPF_PROG_TYPE_SOCKET_FILTER,           "__sk_buff" },
6697 	{ BPF_PROG_TYPE_XDP,                     "xdp_md" },
6698 	/* all other program types don't have "named" context structs */
6699 };
6700 
6701 /* forward declarations for arch-specific underlying types of bpf_user_pt_regs_t typedef,
6702  * for below __builtin_types_compatible_p() checks;
6703  * with this approach we don't need any extra arch-specific #ifdef guards
6704  */
6705 struct pt_regs;
6706 struct user_pt_regs;
6707 struct user_regs_struct;
6708 
6709 static bool need_func_arg_type_fixup(const struct btf *btf, const struct bpf_program *prog,
6710 				     const char *subprog_name, int arg_idx,
6711 				     int arg_type_id, const char *ctx_name)
6712 {
6713 	const struct btf_type *t;
6714 	const char *tname;
6715 
6716 	/* check if existing parameter already matches verifier expectations */
6717 	t = skip_mods_and_typedefs(btf, arg_type_id, NULL);
6718 	if (!btf_is_ptr(t))
6719 		goto out_warn;
6720 
6721 	/* typedef bpf_user_pt_regs_t is a special PITA case, valid for kprobe
6722 	 * and perf_event programs, so check this case early on and forget
6723 	 * about it for subsequent checks
6724 	 */
6725 	while (btf_is_mod(t))
6726 		t = btf__type_by_id(btf, t->type);
6727 	if (btf_is_typedef(t) &&
6728 	    (prog->type == BPF_PROG_TYPE_KPROBE || prog->type == BPF_PROG_TYPE_PERF_EVENT)) {
6729 		tname = btf__str_by_offset(btf, t->name_off) ?: "<anon>";
6730 		if (strcmp(tname, "bpf_user_pt_regs_t") == 0)
6731 			return false; /* canonical type for kprobe/perf_event */
6732 	}
6733 
6734 	/* now we can ignore typedefs moving forward */
6735 	t = skip_mods_and_typedefs(btf, t->type, NULL);
6736 
6737 	/* if it's `void *`, definitely fix up BTF info */
6738 	if (btf_is_void(t))
6739 		return true;
6740 
6741 	/* if it's already proper canonical type, no need to fix up */
6742 	tname = btf__str_by_offset(btf, t->name_off) ?: "<anon>";
6743 	if (btf_is_struct(t) && strcmp(tname, ctx_name) == 0)
6744 		return false;
6745 
6746 	/* special cases */
6747 	switch (prog->type) {
6748 	case BPF_PROG_TYPE_KPROBE:
6749 		/* `struct pt_regs *` is expected, but we need to fix up */
6750 		if (btf_is_struct(t) && strcmp(tname, "pt_regs") == 0)
6751 			return true;
6752 		break;
6753 	case BPF_PROG_TYPE_PERF_EVENT:
6754 		if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct pt_regs) &&
6755 		    btf_is_struct(t) && strcmp(tname, "pt_regs") == 0)
6756 			return true;
6757 		if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct user_pt_regs) &&
6758 		    btf_is_struct(t) && strcmp(tname, "user_pt_regs") == 0)
6759 			return true;
6760 		if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct user_regs_struct) &&
6761 		    btf_is_struct(t) && strcmp(tname, "user_regs_struct") == 0)
6762 			return true;
6763 		break;
6764 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
6765 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
6766 		/* allow u64* as ctx */
6767 		if (btf_is_int(t) && t->size == 8)
6768 			return true;
6769 		break;
6770 	default:
6771 		break;
6772 	}
6773 
6774 out_warn:
6775 	pr_warn("prog '%s': subprog '%s' arg#%d is expected to be of `struct %s *` type\n",
6776 		prog->name, subprog_name, arg_idx, ctx_name);
6777 	return false;
6778 }
6779 
6780 static int clone_func_btf_info(struct btf *btf, int orig_fn_id, struct bpf_program *prog)
6781 {
6782 	int fn_id, fn_proto_id, ret_type_id, orig_proto_id;
6783 	int i, err, arg_cnt, fn_name_off, linkage;
6784 	struct btf_type *fn_t, *fn_proto_t, *t;
6785 	struct btf_param *p;
6786 
6787 	/* caller already validated FUNC -> FUNC_PROTO validity */
6788 	fn_t = btf_type_by_id(btf, orig_fn_id);
6789 	fn_proto_t = btf_type_by_id(btf, fn_t->type);
6790 
6791 	/* Note that each btf__add_xxx() operation invalidates
6792 	 * all btf_type and string pointers, so we need to be
6793 	 * very careful when cloning BTF types. BTF type
6794 	 * pointers have to be always refetched. And to avoid
6795 	 * problems with invalidated string pointers, we
6796 	 * add empty strings initially, then just fix up
6797 	 * name_off offsets in place. Offsets are stable for
6798 	 * existing strings, so that works out.
6799 	 */
6800 	fn_name_off = fn_t->name_off; /* we are about to invalidate fn_t */
6801 	linkage = btf_func_linkage(fn_t);
6802 	orig_proto_id = fn_t->type; /* original FUNC_PROTO ID */
6803 	ret_type_id = fn_proto_t->type; /* fn_proto_t will be invalidated */
6804 	arg_cnt = btf_vlen(fn_proto_t);
6805 
6806 	/* clone FUNC_PROTO and its params */
6807 	fn_proto_id = btf__add_func_proto(btf, ret_type_id);
6808 	if (fn_proto_id < 0)
6809 		return -EINVAL;
6810 
6811 	for (i = 0; i < arg_cnt; i++) {
6812 		int name_off;
6813 
6814 		/* copy original parameter data */
6815 		t = btf_type_by_id(btf, orig_proto_id);
6816 		p = &btf_params(t)[i];
6817 		name_off = p->name_off;
6818 
6819 		err = btf__add_func_param(btf, "", p->type);
6820 		if (err)
6821 			return err;
6822 
6823 		fn_proto_t = btf_type_by_id(btf, fn_proto_id);
6824 		p = &btf_params(fn_proto_t)[i];
6825 		p->name_off = name_off; /* use remembered str offset */
6826 	}
6827 
6828 	/* clone FUNC now, btf__add_func() enforces non-empty name, so use
6829 	 * entry program's name as a placeholder, which we replace immediately
6830 	 * with original name_off
6831 	 */
6832 	fn_id = btf__add_func(btf, prog->name, linkage, fn_proto_id);
6833 	if (fn_id < 0)
6834 		return -EINVAL;
6835 
6836 	fn_t = btf_type_by_id(btf, fn_id);
6837 	fn_t->name_off = fn_name_off; /* reuse original string */
6838 
6839 	return fn_id;
6840 }
6841 
6842 /* Check if main program or global subprog's function prototype has `arg:ctx`
6843  * argument tags, and, if necessary, substitute correct type to match what BPF
6844  * verifier would expect, taking into account specific program type. This
6845  * allows to support __arg_ctx tag transparently on old kernels that don't yet
6846  * have a native support for it in the verifier, making user's life much
6847  * easier.
6848  */
6849 static int bpf_program_fixup_func_info(struct bpf_object *obj, struct bpf_program *prog)
6850 {
6851 	const char *ctx_name = NULL, *ctx_tag = "arg:ctx", *fn_name;
6852 	struct bpf_func_info_min *func_rec;
6853 	struct btf_type *fn_t, *fn_proto_t;
6854 	struct btf *btf = obj->btf;
6855 	const struct btf_type *t;
6856 	struct btf_param *p;
6857 	int ptr_id = 0, struct_id, tag_id, orig_fn_id;
6858 	int i, n, arg_idx, arg_cnt, err, rec_idx;
6859 	int *orig_ids;
6860 
6861 	/* no .BTF.ext, no problem */
6862 	if (!obj->btf_ext || !prog->func_info)
6863 		return 0;
6864 
6865 	/* don't do any fix ups if kernel natively supports __arg_ctx */
6866 	if (kernel_supports(obj, FEAT_ARG_CTX_TAG))
6867 		return 0;
6868 
6869 	/* some BPF program types just don't have named context structs, so
6870 	 * this fallback mechanism doesn't work for them
6871 	 */
6872 	for (i = 0; i < ARRAY_SIZE(global_ctx_map); i++) {
6873 		if (global_ctx_map[i].prog_type != prog->type)
6874 			continue;
6875 		ctx_name = global_ctx_map[i].ctx_name;
6876 		break;
6877 	}
6878 	if (!ctx_name)
6879 		return 0;
6880 
6881 	/* remember original func BTF IDs to detect if we already cloned them */
6882 	orig_ids = calloc(prog->func_info_cnt, sizeof(*orig_ids));
6883 	if (!orig_ids)
6884 		return -ENOMEM;
6885 	for (i = 0; i < prog->func_info_cnt; i++) {
6886 		func_rec = prog->func_info + prog->func_info_rec_size * i;
6887 		orig_ids[i] = func_rec->type_id;
6888 	}
6889 
6890 	/* go through each DECL_TAG with "arg:ctx" and see if it points to one
6891 	 * of our subprogs; if yes and subprog is global and needs adjustment,
6892 	 * clone and adjust FUNC -> FUNC_PROTO combo
6893 	 */
6894 	for (i = 1, n = btf__type_cnt(btf); i < n; i++) {
6895 		/* only DECL_TAG with "arg:ctx" value are interesting */
6896 		t = btf__type_by_id(btf, i);
6897 		if (!btf_is_decl_tag(t))
6898 			continue;
6899 		if (strcmp(btf__str_by_offset(btf, t->name_off), ctx_tag) != 0)
6900 			continue;
6901 
6902 		/* only global funcs need adjustment, if at all */
6903 		orig_fn_id = t->type;
6904 		fn_t = btf_type_by_id(btf, orig_fn_id);
6905 		if (!btf_is_func(fn_t) || btf_func_linkage(fn_t) != BTF_FUNC_GLOBAL)
6906 			continue;
6907 
6908 		/* sanity check FUNC -> FUNC_PROTO chain, just in case */
6909 		fn_proto_t = btf_type_by_id(btf, fn_t->type);
6910 		if (!fn_proto_t || !btf_is_func_proto(fn_proto_t))
6911 			continue;
6912 
6913 		/* find corresponding func_info record */
6914 		func_rec = NULL;
6915 		for (rec_idx = 0; rec_idx < prog->func_info_cnt; rec_idx++) {
6916 			if (orig_ids[rec_idx] == t->type) {
6917 				func_rec = prog->func_info + prog->func_info_rec_size * rec_idx;
6918 				break;
6919 			}
6920 		}
6921 		/* current main program doesn't call into this subprog */
6922 		if (!func_rec)
6923 			continue;
6924 
6925 		/* some more sanity checking of DECL_TAG */
6926 		arg_cnt = btf_vlen(fn_proto_t);
6927 		arg_idx = btf_decl_tag(t)->component_idx;
6928 		if (arg_idx < 0 || arg_idx >= arg_cnt)
6929 			continue;
6930 
6931 		/* check if we should fix up argument type */
6932 		p = &btf_params(fn_proto_t)[arg_idx];
6933 		fn_name = btf__str_by_offset(btf, fn_t->name_off) ?: "<anon>";
6934 		if (!need_func_arg_type_fixup(btf, prog, fn_name, arg_idx, p->type, ctx_name))
6935 			continue;
6936 
6937 		/* clone fn/fn_proto, unless we already did it for another arg */
6938 		if (func_rec->type_id == orig_fn_id) {
6939 			int fn_id;
6940 
6941 			fn_id = clone_func_btf_info(btf, orig_fn_id, prog);
6942 			if (fn_id < 0) {
6943 				err = fn_id;
6944 				goto err_out;
6945 			}
6946 
6947 			/* point func_info record to a cloned FUNC type */
6948 			func_rec->type_id = fn_id;
6949 		}
6950 
6951 		/* create PTR -> STRUCT type chain to mark PTR_TO_CTX argument;
6952 		 * we do it just once per main BPF program, as all global
6953 		 * funcs share the same program type, so need only PTR ->
6954 		 * STRUCT type chain
6955 		 */
6956 		if (ptr_id == 0) {
6957 			struct_id = btf__add_struct(btf, ctx_name, 0);
6958 			ptr_id = btf__add_ptr(btf, struct_id);
6959 			if (ptr_id < 0 || struct_id < 0) {
6960 				err = -EINVAL;
6961 				goto err_out;
6962 			}
6963 		}
6964 
6965 		/* for completeness, clone DECL_TAG and point it to cloned param */
6966 		tag_id = btf__add_decl_tag(btf, ctx_tag, func_rec->type_id, arg_idx);
6967 		if (tag_id < 0) {
6968 			err = -EINVAL;
6969 			goto err_out;
6970 		}
6971 
6972 		/* all the BTF manipulations invalidated pointers, refetch them */
6973 		fn_t = btf_type_by_id(btf, func_rec->type_id);
6974 		fn_proto_t = btf_type_by_id(btf, fn_t->type);
6975 
6976 		/* fix up type ID pointed to by param */
6977 		p = &btf_params(fn_proto_t)[arg_idx];
6978 		p->type = ptr_id;
6979 	}
6980 
6981 	free(orig_ids);
6982 	return 0;
6983 err_out:
6984 	free(orig_ids);
6985 	return err;
6986 }
6987 
6988 static int bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
6989 {
6990 	struct bpf_program *prog;
6991 	size_t i, j;
6992 	int err;
6993 
6994 	if (obj->btf_ext) {
6995 		err = bpf_object__relocate_core(obj, targ_btf_path);
6996 		if (err) {
6997 			pr_warn("failed to perform CO-RE relocations: %d\n",
6998 				err);
6999 			return err;
7000 		}
7001 		bpf_object__sort_relos(obj);
7002 	}
7003 
7004 	/* Before relocating calls pre-process relocations and mark
7005 	 * few ld_imm64 instructions that points to subprogs.
7006 	 * Otherwise bpf_object__reloc_code() later would have to consider
7007 	 * all ld_imm64 insns as relocation candidates. That would
7008 	 * reduce relocation speed, since amount of find_prog_insn_relo()
7009 	 * would increase and most of them will fail to find a relo.
7010 	 */
7011 	for (i = 0; i < obj->nr_programs; i++) {
7012 		prog = &obj->programs[i];
7013 		for (j = 0; j < prog->nr_reloc; j++) {
7014 			struct reloc_desc *relo = &prog->reloc_desc[j];
7015 			struct bpf_insn *insn = &prog->insns[relo->insn_idx];
7016 
7017 			/* mark the insn, so it's recognized by insn_is_pseudo_func() */
7018 			if (relo->type == RELO_SUBPROG_ADDR)
7019 				insn[0].src_reg = BPF_PSEUDO_FUNC;
7020 		}
7021 	}
7022 
7023 	/* relocate subprogram calls and append used subprograms to main
7024 	 * programs; each copy of subprogram code needs to be relocated
7025 	 * differently for each main program, because its code location might
7026 	 * have changed.
7027 	 * Append subprog relos to main programs to allow data relos to be
7028 	 * processed after text is completely relocated.
7029 	 */
7030 	for (i = 0; i < obj->nr_programs; i++) {
7031 		prog = &obj->programs[i];
7032 		/* sub-program's sub-calls are relocated within the context of
7033 		 * its main program only
7034 		 */
7035 		if (prog_is_subprog(obj, prog))
7036 			continue;
7037 		if (!prog->autoload)
7038 			continue;
7039 
7040 		err = bpf_object__relocate_calls(obj, prog);
7041 		if (err) {
7042 			pr_warn("prog '%s': failed to relocate calls: %d\n",
7043 				prog->name, err);
7044 			return err;
7045 		}
7046 
7047 		err = bpf_prog_assign_exc_cb(obj, prog);
7048 		if (err)
7049 			return err;
7050 		/* Now, also append exception callback if it has not been done already. */
7051 		if (prog->exception_cb_idx >= 0) {
7052 			struct bpf_program *subprog = &obj->programs[prog->exception_cb_idx];
7053 
7054 			/* Calling exception callback directly is disallowed, which the
7055 			 * verifier will reject later. In case it was processed already,
7056 			 * we can skip this step, otherwise for all other valid cases we
7057 			 * have to append exception callback now.
7058 			 */
7059 			if (subprog->sub_insn_off == 0) {
7060 				err = bpf_object__append_subprog_code(obj, prog, subprog);
7061 				if (err)
7062 					return err;
7063 				err = bpf_object__reloc_code(obj, prog, subprog);
7064 				if (err)
7065 					return err;
7066 			}
7067 		}
7068 	}
7069 	for (i = 0; i < obj->nr_programs; i++) {
7070 		prog = &obj->programs[i];
7071 		if (prog_is_subprog(obj, prog))
7072 			continue;
7073 		if (!prog->autoload)
7074 			continue;
7075 
7076 		/* Process data relos for main programs */
7077 		err = bpf_object__relocate_data(obj, prog);
7078 		if (err) {
7079 			pr_warn("prog '%s': failed to relocate data references: %d\n",
7080 				prog->name, err);
7081 			return err;
7082 		}
7083 
7084 		/* Fix up .BTF.ext information, if necessary */
7085 		err = bpf_program_fixup_func_info(obj, prog);
7086 		if (err) {
7087 			pr_warn("prog '%s': failed to perform .BTF.ext fix ups: %d\n",
7088 				prog->name, err);
7089 			return err;
7090 		}
7091 	}
7092 
7093 	return 0;
7094 }
7095 
7096 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
7097 					    Elf64_Shdr *shdr, Elf_Data *data);
7098 
7099 static int bpf_object__collect_map_relos(struct bpf_object *obj,
7100 					 Elf64_Shdr *shdr, Elf_Data *data)
7101 {
7102 	const int bpf_ptr_sz = 8, host_ptr_sz = sizeof(void *);
7103 	int i, j, nrels, new_sz;
7104 	const struct btf_var_secinfo *vi = NULL;
7105 	const struct btf_type *sec, *var, *def;
7106 	struct bpf_map *map = NULL, *targ_map = NULL;
7107 	struct bpf_program *targ_prog = NULL;
7108 	bool is_prog_array, is_map_in_map;
7109 	const struct btf_member *member;
7110 	const char *name, *mname, *type;
7111 	unsigned int moff;
7112 	Elf64_Sym *sym;
7113 	Elf64_Rel *rel;
7114 	void *tmp;
7115 
7116 	if (!obj->efile.btf_maps_sec_btf_id || !obj->btf)
7117 		return -EINVAL;
7118 	sec = btf__type_by_id(obj->btf, obj->efile.btf_maps_sec_btf_id);
7119 	if (!sec)
7120 		return -EINVAL;
7121 
7122 	nrels = shdr->sh_size / shdr->sh_entsize;
7123 	for (i = 0; i < nrels; i++) {
7124 		rel = elf_rel_by_idx(data, i);
7125 		if (!rel) {
7126 			pr_warn(".maps relo #%d: failed to get ELF relo\n", i);
7127 			return -LIBBPF_ERRNO__FORMAT;
7128 		}
7129 
7130 		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
7131 		if (!sym) {
7132 			pr_warn(".maps relo #%d: symbol %zx not found\n",
7133 				i, (size_t)ELF64_R_SYM(rel->r_info));
7134 			return -LIBBPF_ERRNO__FORMAT;
7135 		}
7136 		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
7137 
7138 		pr_debug(".maps relo #%d: for %zd value %zd rel->r_offset %zu name %d ('%s')\n",
7139 			 i, (ssize_t)(rel->r_info >> 32), (size_t)sym->st_value,
7140 			 (size_t)rel->r_offset, sym->st_name, name);
7141 
7142 		for (j = 0; j < obj->nr_maps; j++) {
7143 			map = &obj->maps[j];
7144 			if (map->sec_idx != obj->efile.btf_maps_shndx)
7145 				continue;
7146 
7147 			vi = btf_var_secinfos(sec) + map->btf_var_idx;
7148 			if (vi->offset <= rel->r_offset &&
7149 			    rel->r_offset + bpf_ptr_sz <= vi->offset + vi->size)
7150 				break;
7151 		}
7152 		if (j == obj->nr_maps) {
7153 			pr_warn(".maps relo #%d: cannot find map '%s' at rel->r_offset %zu\n",
7154 				i, name, (size_t)rel->r_offset);
7155 			return -EINVAL;
7156 		}
7157 
7158 		is_map_in_map = bpf_map_type__is_map_in_map(map->def.type);
7159 		is_prog_array = map->def.type == BPF_MAP_TYPE_PROG_ARRAY;
7160 		type = is_map_in_map ? "map" : "prog";
7161 		if (is_map_in_map) {
7162 			if (sym->st_shndx != obj->efile.btf_maps_shndx) {
7163 				pr_warn(".maps relo #%d: '%s' isn't a BTF-defined map\n",
7164 					i, name);
7165 				return -LIBBPF_ERRNO__RELOC;
7166 			}
7167 			if (map->def.type == BPF_MAP_TYPE_HASH_OF_MAPS &&
7168 			    map->def.key_size != sizeof(int)) {
7169 				pr_warn(".maps relo #%d: hash-of-maps '%s' should have key size %zu.\n",
7170 					i, map->name, sizeof(int));
7171 				return -EINVAL;
7172 			}
7173 			targ_map = bpf_object__find_map_by_name(obj, name);
7174 			if (!targ_map) {
7175 				pr_warn(".maps relo #%d: '%s' isn't a valid map reference\n",
7176 					i, name);
7177 				return -ESRCH;
7178 			}
7179 		} else if (is_prog_array) {
7180 			targ_prog = bpf_object__find_program_by_name(obj, name);
7181 			if (!targ_prog) {
7182 				pr_warn(".maps relo #%d: '%s' isn't a valid program reference\n",
7183 					i, name);
7184 				return -ESRCH;
7185 			}
7186 			if (targ_prog->sec_idx != sym->st_shndx ||
7187 			    targ_prog->sec_insn_off * 8 != sym->st_value ||
7188 			    prog_is_subprog(obj, targ_prog)) {
7189 				pr_warn(".maps relo #%d: '%s' isn't an entry-point program\n",
7190 					i, name);
7191 				return -LIBBPF_ERRNO__RELOC;
7192 			}
7193 		} else {
7194 			return -EINVAL;
7195 		}
7196 
7197 		var = btf__type_by_id(obj->btf, vi->type);
7198 		def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
7199 		if (btf_vlen(def) == 0)
7200 			return -EINVAL;
7201 		member = btf_members(def) + btf_vlen(def) - 1;
7202 		mname = btf__name_by_offset(obj->btf, member->name_off);
7203 		if (strcmp(mname, "values"))
7204 			return -EINVAL;
7205 
7206 		moff = btf_member_bit_offset(def, btf_vlen(def) - 1) / 8;
7207 		if (rel->r_offset - vi->offset < moff)
7208 			return -EINVAL;
7209 
7210 		moff = rel->r_offset - vi->offset - moff;
7211 		/* here we use BPF pointer size, which is always 64 bit, as we
7212 		 * are parsing ELF that was built for BPF target
7213 		 */
7214 		if (moff % bpf_ptr_sz)
7215 			return -EINVAL;
7216 		moff /= bpf_ptr_sz;
7217 		if (moff >= map->init_slots_sz) {
7218 			new_sz = moff + 1;
7219 			tmp = libbpf_reallocarray(map->init_slots, new_sz, host_ptr_sz);
7220 			if (!tmp)
7221 				return -ENOMEM;
7222 			map->init_slots = tmp;
7223 			memset(map->init_slots + map->init_slots_sz, 0,
7224 			       (new_sz - map->init_slots_sz) * host_ptr_sz);
7225 			map->init_slots_sz = new_sz;
7226 		}
7227 		map->init_slots[moff] = is_map_in_map ? (void *)targ_map : (void *)targ_prog;
7228 
7229 		pr_debug(".maps relo #%d: map '%s' slot [%d] points to %s '%s'\n",
7230 			 i, map->name, moff, type, name);
7231 	}
7232 
7233 	return 0;
7234 }
7235 
7236 static int bpf_object__collect_relos(struct bpf_object *obj)
7237 {
7238 	int i, err;
7239 
7240 	for (i = 0; i < obj->efile.sec_cnt; i++) {
7241 		struct elf_sec_desc *sec_desc = &obj->efile.secs[i];
7242 		Elf64_Shdr *shdr;
7243 		Elf_Data *data;
7244 		int idx;
7245 
7246 		if (sec_desc->sec_type != SEC_RELO)
7247 			continue;
7248 
7249 		shdr = sec_desc->shdr;
7250 		data = sec_desc->data;
7251 		idx = shdr->sh_info;
7252 
7253 		if (shdr->sh_type != SHT_REL || idx < 0 || idx >= obj->efile.sec_cnt) {
7254 			pr_warn("internal error at %d\n", __LINE__);
7255 			return -LIBBPF_ERRNO__INTERNAL;
7256 		}
7257 
7258 		if (obj->efile.secs[idx].sec_type == SEC_ST_OPS)
7259 			err = bpf_object__collect_st_ops_relos(obj, shdr, data);
7260 		else if (idx == obj->efile.btf_maps_shndx)
7261 			err = bpf_object__collect_map_relos(obj, shdr, data);
7262 		else
7263 			err = bpf_object__collect_prog_relos(obj, shdr, data);
7264 		if (err)
7265 			return err;
7266 	}
7267 
7268 	bpf_object__sort_relos(obj);
7269 	return 0;
7270 }
7271 
7272 static bool insn_is_helper_call(struct bpf_insn *insn, enum bpf_func_id *func_id)
7273 {
7274 	if (BPF_CLASS(insn->code) == BPF_JMP &&
7275 	    BPF_OP(insn->code) == BPF_CALL &&
7276 	    BPF_SRC(insn->code) == BPF_K &&
7277 	    insn->src_reg == 0 &&
7278 	    insn->dst_reg == 0) {
7279 		    *func_id = insn->imm;
7280 		    return true;
7281 	}
7282 	return false;
7283 }
7284 
7285 static int bpf_object__sanitize_prog(struct bpf_object *obj, struct bpf_program *prog)
7286 {
7287 	struct bpf_insn *insn = prog->insns;
7288 	enum bpf_func_id func_id;
7289 	int i;
7290 
7291 	if (obj->gen_loader)
7292 		return 0;
7293 
7294 	for (i = 0; i < prog->insns_cnt; i++, insn++) {
7295 		if (!insn_is_helper_call(insn, &func_id))
7296 			continue;
7297 
7298 		/* on kernels that don't yet support
7299 		 * bpf_probe_read_{kernel,user}[_str] helpers, fall back
7300 		 * to bpf_probe_read() which works well for old kernels
7301 		 */
7302 		switch (func_id) {
7303 		case BPF_FUNC_probe_read_kernel:
7304 		case BPF_FUNC_probe_read_user:
7305 			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
7306 				insn->imm = BPF_FUNC_probe_read;
7307 			break;
7308 		case BPF_FUNC_probe_read_kernel_str:
7309 		case BPF_FUNC_probe_read_user_str:
7310 			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
7311 				insn->imm = BPF_FUNC_probe_read_str;
7312 			break;
7313 		default:
7314 			break;
7315 		}
7316 	}
7317 	return 0;
7318 }
7319 
7320 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
7321 				     int *btf_obj_fd, int *btf_type_id);
7322 
7323 /* this is called as prog->sec_def->prog_prepare_load_fn for libbpf-supported sec_defs */
7324 static int libbpf_prepare_prog_load(struct bpf_program *prog,
7325 				    struct bpf_prog_load_opts *opts, long cookie)
7326 {
7327 	enum sec_def_flags def = cookie;
7328 
7329 	/* old kernels might not support specifying expected_attach_type */
7330 	if ((def & SEC_EXP_ATTACH_OPT) && !kernel_supports(prog->obj, FEAT_EXP_ATTACH_TYPE))
7331 		opts->expected_attach_type = 0;
7332 
7333 	if (def & SEC_SLEEPABLE)
7334 		opts->prog_flags |= BPF_F_SLEEPABLE;
7335 
7336 	if (prog->type == BPF_PROG_TYPE_XDP && (def & SEC_XDP_FRAGS))
7337 		opts->prog_flags |= BPF_F_XDP_HAS_FRAGS;
7338 
7339 	/* special check for usdt to use uprobe_multi link */
7340 	if ((def & SEC_USDT) && kernel_supports(prog->obj, FEAT_UPROBE_MULTI_LINK))
7341 		prog->expected_attach_type = BPF_TRACE_UPROBE_MULTI;
7342 
7343 	if ((def & SEC_ATTACH_BTF) && !prog->attach_btf_id) {
7344 		int btf_obj_fd = 0, btf_type_id = 0, err;
7345 		const char *attach_name;
7346 
7347 		attach_name = strchr(prog->sec_name, '/');
7348 		if (!attach_name) {
7349 			/* if BPF program is annotated with just SEC("fentry")
7350 			 * (or similar) without declaratively specifying
7351 			 * target, then it is expected that target will be
7352 			 * specified with bpf_program__set_attach_target() at
7353 			 * runtime before BPF object load step. If not, then
7354 			 * there is nothing to load into the kernel as BPF
7355 			 * verifier won't be able to validate BPF program
7356 			 * correctness anyways.
7357 			 */
7358 			pr_warn("prog '%s': no BTF-based attach target is specified, use bpf_program__set_attach_target()\n",
7359 				prog->name);
7360 			return -EINVAL;
7361 		}
7362 		attach_name++; /* skip over / */
7363 
7364 		err = libbpf_find_attach_btf_id(prog, attach_name, &btf_obj_fd, &btf_type_id);
7365 		if (err)
7366 			return err;
7367 
7368 		/* cache resolved BTF FD and BTF type ID in the prog */
7369 		prog->attach_btf_obj_fd = btf_obj_fd;
7370 		prog->attach_btf_id = btf_type_id;
7371 
7372 		/* but by now libbpf common logic is not utilizing
7373 		 * prog->atach_btf_obj_fd/prog->attach_btf_id anymore because
7374 		 * this callback is called after opts were populated by
7375 		 * libbpf, so this callback has to update opts explicitly here
7376 		 */
7377 		opts->attach_btf_obj_fd = btf_obj_fd;
7378 		opts->attach_btf_id = btf_type_id;
7379 	}
7380 	return 0;
7381 }
7382 
7383 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz);
7384 
7385 static int bpf_object_load_prog(struct bpf_object *obj, struct bpf_program *prog,
7386 				struct bpf_insn *insns, int insns_cnt,
7387 				const char *license, __u32 kern_version, int *prog_fd)
7388 {
7389 	LIBBPF_OPTS(bpf_prog_load_opts, load_attr);
7390 	const char *prog_name = NULL;
7391 	char *cp, errmsg[STRERR_BUFSIZE];
7392 	size_t log_buf_size = 0;
7393 	char *log_buf = NULL, *tmp;
7394 	bool own_log_buf = true;
7395 	__u32 log_level = prog->log_level;
7396 	int ret, err;
7397 
7398 	/* Be more helpful by rejecting programs that can't be validated early
7399 	 * with more meaningful and actionable error message.
7400 	 */
7401 	switch (prog->type) {
7402 	case BPF_PROG_TYPE_UNSPEC:
7403 		/*
7404 		 * The program type must be set.  Most likely we couldn't find a proper
7405 		 * section definition at load time, and thus we didn't infer the type.
7406 		 */
7407 		pr_warn("prog '%s': missing BPF prog type, check ELF section name '%s'\n",
7408 			prog->name, prog->sec_name);
7409 		return -EINVAL;
7410 	case BPF_PROG_TYPE_STRUCT_OPS:
7411 		if (prog->attach_btf_id == 0) {
7412 			pr_warn("prog '%s': SEC(\"struct_ops\") program isn't referenced anywhere, did you forget to use it?\n",
7413 				prog->name);
7414 			return -EINVAL;
7415 		}
7416 		break;
7417 	default:
7418 		break;
7419 	}
7420 
7421 	if (!insns || !insns_cnt)
7422 		return -EINVAL;
7423 
7424 	if (kernel_supports(obj, FEAT_PROG_NAME))
7425 		prog_name = prog->name;
7426 	load_attr.attach_prog_fd = prog->attach_prog_fd;
7427 	load_attr.attach_btf_obj_fd = prog->attach_btf_obj_fd;
7428 	load_attr.attach_btf_id = prog->attach_btf_id;
7429 	load_attr.kern_version = kern_version;
7430 	load_attr.prog_ifindex = prog->prog_ifindex;
7431 
7432 	/* specify func_info/line_info only if kernel supports them */
7433 	if (obj->btf && btf__fd(obj->btf) >= 0 && kernel_supports(obj, FEAT_BTF_FUNC)) {
7434 		load_attr.prog_btf_fd = btf__fd(obj->btf);
7435 		load_attr.func_info = prog->func_info;
7436 		load_attr.func_info_rec_size = prog->func_info_rec_size;
7437 		load_attr.func_info_cnt = prog->func_info_cnt;
7438 		load_attr.line_info = prog->line_info;
7439 		load_attr.line_info_rec_size = prog->line_info_rec_size;
7440 		load_attr.line_info_cnt = prog->line_info_cnt;
7441 	}
7442 	load_attr.log_level = log_level;
7443 	load_attr.prog_flags = prog->prog_flags;
7444 	load_attr.fd_array = obj->fd_array;
7445 
7446 	load_attr.token_fd = obj->token_fd;
7447 	if (obj->token_fd)
7448 		load_attr.prog_flags |= BPF_F_TOKEN_FD;
7449 
7450 	/* adjust load_attr if sec_def provides custom preload callback */
7451 	if (prog->sec_def && prog->sec_def->prog_prepare_load_fn) {
7452 		err = prog->sec_def->prog_prepare_load_fn(prog, &load_attr, prog->sec_def->cookie);
7453 		if (err < 0) {
7454 			pr_warn("prog '%s': failed to prepare load attributes: %d\n",
7455 				prog->name, err);
7456 			return err;
7457 		}
7458 		insns = prog->insns;
7459 		insns_cnt = prog->insns_cnt;
7460 	}
7461 
7462 	/* allow prog_prepare_load_fn to change expected_attach_type */
7463 	load_attr.expected_attach_type = prog->expected_attach_type;
7464 
7465 	if (obj->gen_loader) {
7466 		bpf_gen__prog_load(obj->gen_loader, prog->type, prog->name,
7467 				   license, insns, insns_cnt, &load_attr,
7468 				   prog - obj->programs);
7469 		*prog_fd = -1;
7470 		return 0;
7471 	}
7472 
7473 retry_load:
7474 	/* if log_level is zero, we don't request logs initially even if
7475 	 * custom log_buf is specified; if the program load fails, then we'll
7476 	 * bump log_level to 1 and use either custom log_buf or we'll allocate
7477 	 * our own and retry the load to get details on what failed
7478 	 */
7479 	if (log_level) {
7480 		if (prog->log_buf) {
7481 			log_buf = prog->log_buf;
7482 			log_buf_size = prog->log_size;
7483 			own_log_buf = false;
7484 		} else if (obj->log_buf) {
7485 			log_buf = obj->log_buf;
7486 			log_buf_size = obj->log_size;
7487 			own_log_buf = false;
7488 		} else {
7489 			log_buf_size = max((size_t)BPF_LOG_BUF_SIZE, log_buf_size * 2);
7490 			tmp = realloc(log_buf, log_buf_size);
7491 			if (!tmp) {
7492 				ret = -ENOMEM;
7493 				goto out;
7494 			}
7495 			log_buf = tmp;
7496 			log_buf[0] = '\0';
7497 			own_log_buf = true;
7498 		}
7499 	}
7500 
7501 	load_attr.log_buf = log_buf;
7502 	load_attr.log_size = log_buf_size;
7503 	load_attr.log_level = log_level;
7504 
7505 	ret = bpf_prog_load(prog->type, prog_name, license, insns, insns_cnt, &load_attr);
7506 	if (ret >= 0) {
7507 		if (log_level && own_log_buf) {
7508 			pr_debug("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
7509 				 prog->name, log_buf);
7510 		}
7511 
7512 		if (obj->has_rodata && kernel_supports(obj, FEAT_PROG_BIND_MAP)) {
7513 			struct bpf_map *map;
7514 			int i;
7515 
7516 			for (i = 0; i < obj->nr_maps; i++) {
7517 				map = &prog->obj->maps[i];
7518 				if (map->libbpf_type != LIBBPF_MAP_RODATA)
7519 					continue;
7520 
7521 				if (bpf_prog_bind_map(ret, map->fd, NULL)) {
7522 					cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
7523 					pr_warn("prog '%s': failed to bind map '%s': %s\n",
7524 						prog->name, map->real_name, cp);
7525 					/* Don't fail hard if can't bind rodata. */
7526 				}
7527 			}
7528 		}
7529 
7530 		*prog_fd = ret;
7531 		ret = 0;
7532 		goto out;
7533 	}
7534 
7535 	if (log_level == 0) {
7536 		log_level = 1;
7537 		goto retry_load;
7538 	}
7539 	/* On ENOSPC, increase log buffer size and retry, unless custom
7540 	 * log_buf is specified.
7541 	 * Be careful to not overflow u32, though. Kernel's log buf size limit
7542 	 * isn't part of UAPI so it can always be bumped to full 4GB. So don't
7543 	 * multiply by 2 unless we are sure we'll fit within 32 bits.
7544 	 * Currently, we'll get -EINVAL when we reach (UINT_MAX >> 2).
7545 	 */
7546 	if (own_log_buf && errno == ENOSPC && log_buf_size <= UINT_MAX / 2)
7547 		goto retry_load;
7548 
7549 	ret = -errno;
7550 
7551 	/* post-process verifier log to improve error descriptions */
7552 	fixup_verifier_log(prog, log_buf, log_buf_size);
7553 
7554 	cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
7555 	pr_warn("prog '%s': BPF program load failed: %s\n", prog->name, cp);
7556 	pr_perm_msg(ret);
7557 
7558 	if (own_log_buf && log_buf && log_buf[0] != '\0') {
7559 		pr_warn("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
7560 			prog->name, log_buf);
7561 	}
7562 
7563 out:
7564 	if (own_log_buf)
7565 		free(log_buf);
7566 	return ret;
7567 }
7568 
7569 static char *find_prev_line(char *buf, char *cur)
7570 {
7571 	char *p;
7572 
7573 	if (cur == buf) /* end of a log buf */
7574 		return NULL;
7575 
7576 	p = cur - 1;
7577 	while (p - 1 >= buf && *(p - 1) != '\n')
7578 		p--;
7579 
7580 	return p;
7581 }
7582 
7583 static void patch_log(char *buf, size_t buf_sz, size_t log_sz,
7584 		      char *orig, size_t orig_sz, const char *patch)
7585 {
7586 	/* size of the remaining log content to the right from the to-be-replaced part */
7587 	size_t rem_sz = (buf + log_sz) - (orig + orig_sz);
7588 	size_t patch_sz = strlen(patch);
7589 
7590 	if (patch_sz != orig_sz) {
7591 		/* If patch line(s) are longer than original piece of verifier log,
7592 		 * shift log contents by (patch_sz - orig_sz) bytes to the right
7593 		 * starting from after to-be-replaced part of the log.
7594 		 *
7595 		 * If patch line(s) are shorter than original piece of verifier log,
7596 		 * shift log contents by (orig_sz - patch_sz) bytes to the left
7597 		 * starting from after to-be-replaced part of the log
7598 		 *
7599 		 * We need to be careful about not overflowing available
7600 		 * buf_sz capacity. If that's the case, we'll truncate the end
7601 		 * of the original log, as necessary.
7602 		 */
7603 		if (patch_sz > orig_sz) {
7604 			if (orig + patch_sz >= buf + buf_sz) {
7605 				/* patch is big enough to cover remaining space completely */
7606 				patch_sz -= (orig + patch_sz) - (buf + buf_sz) + 1;
7607 				rem_sz = 0;
7608 			} else if (patch_sz - orig_sz > buf_sz - log_sz) {
7609 				/* patch causes part of remaining log to be truncated */
7610 				rem_sz -= (patch_sz - orig_sz) - (buf_sz - log_sz);
7611 			}
7612 		}
7613 		/* shift remaining log to the right by calculated amount */
7614 		memmove(orig + patch_sz, orig + orig_sz, rem_sz);
7615 	}
7616 
7617 	memcpy(orig, patch, patch_sz);
7618 }
7619 
7620 static void fixup_log_failed_core_relo(struct bpf_program *prog,
7621 				       char *buf, size_t buf_sz, size_t log_sz,
7622 				       char *line1, char *line2, char *line3)
7623 {
7624 	/* Expected log for failed and not properly guarded CO-RE relocation:
7625 	 * line1 -> 123: (85) call unknown#195896080
7626 	 * line2 -> invalid func unknown#195896080
7627 	 * line3 -> <anything else or end of buffer>
7628 	 *
7629 	 * "123" is the index of the instruction that was poisoned. We extract
7630 	 * instruction index to find corresponding CO-RE relocation and
7631 	 * replace this part of the log with more relevant information about
7632 	 * failed CO-RE relocation.
7633 	 */
7634 	const struct bpf_core_relo *relo;
7635 	struct bpf_core_spec spec;
7636 	char patch[512], spec_buf[256];
7637 	int insn_idx, err, spec_len;
7638 
7639 	if (sscanf(line1, "%d: (%*d) call unknown#195896080\n", &insn_idx) != 1)
7640 		return;
7641 
7642 	relo = find_relo_core(prog, insn_idx);
7643 	if (!relo)
7644 		return;
7645 
7646 	err = bpf_core_parse_spec(prog->name, prog->obj->btf, relo, &spec);
7647 	if (err)
7648 		return;
7649 
7650 	spec_len = bpf_core_format_spec(spec_buf, sizeof(spec_buf), &spec);
7651 	snprintf(patch, sizeof(patch),
7652 		 "%d: <invalid CO-RE relocation>\n"
7653 		 "failed to resolve CO-RE relocation %s%s\n",
7654 		 insn_idx, spec_buf, spec_len >= sizeof(spec_buf) ? "..." : "");
7655 
7656 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7657 }
7658 
7659 static void fixup_log_missing_map_load(struct bpf_program *prog,
7660 				       char *buf, size_t buf_sz, size_t log_sz,
7661 				       char *line1, char *line2, char *line3)
7662 {
7663 	/* Expected log for failed and not properly guarded map reference:
7664 	 * line1 -> 123: (85) call unknown#2001000345
7665 	 * line2 -> invalid func unknown#2001000345
7666 	 * line3 -> <anything else or end of buffer>
7667 	 *
7668 	 * "123" is the index of the instruction that was poisoned.
7669 	 * "345" in "2001000345" is a map index in obj->maps to fetch map name.
7670 	 */
7671 	struct bpf_object *obj = prog->obj;
7672 	const struct bpf_map *map;
7673 	int insn_idx, map_idx;
7674 	char patch[128];
7675 
7676 	if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &map_idx) != 2)
7677 		return;
7678 
7679 	map_idx -= POISON_LDIMM64_MAP_BASE;
7680 	if (map_idx < 0 || map_idx >= obj->nr_maps)
7681 		return;
7682 	map = &obj->maps[map_idx];
7683 
7684 	snprintf(patch, sizeof(patch),
7685 		 "%d: <invalid BPF map reference>\n"
7686 		 "BPF map '%s' is referenced but wasn't created\n",
7687 		 insn_idx, map->name);
7688 
7689 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7690 }
7691 
7692 static void fixup_log_missing_kfunc_call(struct bpf_program *prog,
7693 					 char *buf, size_t buf_sz, size_t log_sz,
7694 					 char *line1, char *line2, char *line3)
7695 {
7696 	/* Expected log for failed and not properly guarded kfunc call:
7697 	 * line1 -> 123: (85) call unknown#2002000345
7698 	 * line2 -> invalid func unknown#2002000345
7699 	 * line3 -> <anything else or end of buffer>
7700 	 *
7701 	 * "123" is the index of the instruction that was poisoned.
7702 	 * "345" in "2002000345" is an extern index in obj->externs to fetch kfunc name.
7703 	 */
7704 	struct bpf_object *obj = prog->obj;
7705 	const struct extern_desc *ext;
7706 	int insn_idx, ext_idx;
7707 	char patch[128];
7708 
7709 	if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &ext_idx) != 2)
7710 		return;
7711 
7712 	ext_idx -= POISON_CALL_KFUNC_BASE;
7713 	if (ext_idx < 0 || ext_idx >= obj->nr_extern)
7714 		return;
7715 	ext = &obj->externs[ext_idx];
7716 
7717 	snprintf(patch, sizeof(patch),
7718 		 "%d: <invalid kfunc call>\n"
7719 		 "kfunc '%s' is referenced but wasn't resolved\n",
7720 		 insn_idx, ext->name);
7721 
7722 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7723 }
7724 
7725 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz)
7726 {
7727 	/* look for familiar error patterns in last N lines of the log */
7728 	const size_t max_last_line_cnt = 10;
7729 	char *prev_line, *cur_line, *next_line;
7730 	size_t log_sz;
7731 	int i;
7732 
7733 	if (!buf)
7734 		return;
7735 
7736 	log_sz = strlen(buf) + 1;
7737 	next_line = buf + log_sz - 1;
7738 
7739 	for (i = 0; i < max_last_line_cnt; i++, next_line = cur_line) {
7740 		cur_line = find_prev_line(buf, next_line);
7741 		if (!cur_line)
7742 			return;
7743 
7744 		if (str_has_pfx(cur_line, "invalid func unknown#195896080\n")) {
7745 			prev_line = find_prev_line(buf, cur_line);
7746 			if (!prev_line)
7747 				continue;
7748 
7749 			/* failed CO-RE relocation case */
7750 			fixup_log_failed_core_relo(prog, buf, buf_sz, log_sz,
7751 						   prev_line, cur_line, next_line);
7752 			return;
7753 		} else if (str_has_pfx(cur_line, "invalid func unknown#"POISON_LDIMM64_MAP_PFX)) {
7754 			prev_line = find_prev_line(buf, cur_line);
7755 			if (!prev_line)
7756 				continue;
7757 
7758 			/* reference to uncreated BPF map */
7759 			fixup_log_missing_map_load(prog, buf, buf_sz, log_sz,
7760 						   prev_line, cur_line, next_line);
7761 			return;
7762 		} else if (str_has_pfx(cur_line, "invalid func unknown#"POISON_CALL_KFUNC_PFX)) {
7763 			prev_line = find_prev_line(buf, cur_line);
7764 			if (!prev_line)
7765 				continue;
7766 
7767 			/* reference to unresolved kfunc */
7768 			fixup_log_missing_kfunc_call(prog, buf, buf_sz, log_sz,
7769 						     prev_line, cur_line, next_line);
7770 			return;
7771 		}
7772 	}
7773 }
7774 
7775 static int bpf_program_record_relos(struct bpf_program *prog)
7776 {
7777 	struct bpf_object *obj = prog->obj;
7778 	int i;
7779 
7780 	for (i = 0; i < prog->nr_reloc; i++) {
7781 		struct reloc_desc *relo = &prog->reloc_desc[i];
7782 		struct extern_desc *ext = &obj->externs[relo->ext_idx];
7783 		int kind;
7784 
7785 		switch (relo->type) {
7786 		case RELO_EXTERN_LD64:
7787 			if (ext->type != EXT_KSYM)
7788 				continue;
7789 			kind = btf_is_var(btf__type_by_id(obj->btf, ext->btf_id)) ?
7790 				BTF_KIND_VAR : BTF_KIND_FUNC;
7791 			bpf_gen__record_extern(obj->gen_loader, ext->name,
7792 					       ext->is_weak, !ext->ksym.type_id,
7793 					       true, kind, relo->insn_idx);
7794 			break;
7795 		case RELO_EXTERN_CALL:
7796 			bpf_gen__record_extern(obj->gen_loader, ext->name,
7797 					       ext->is_weak, false, false, BTF_KIND_FUNC,
7798 					       relo->insn_idx);
7799 			break;
7800 		case RELO_CORE: {
7801 			struct bpf_core_relo cr = {
7802 				.insn_off = relo->insn_idx * 8,
7803 				.type_id = relo->core_relo->type_id,
7804 				.access_str_off = relo->core_relo->access_str_off,
7805 				.kind = relo->core_relo->kind,
7806 			};
7807 
7808 			bpf_gen__record_relo_core(obj->gen_loader, &cr);
7809 			break;
7810 		}
7811 		default:
7812 			continue;
7813 		}
7814 	}
7815 	return 0;
7816 }
7817 
7818 static int
7819 bpf_object__load_progs(struct bpf_object *obj, int log_level)
7820 {
7821 	struct bpf_program *prog;
7822 	size_t i;
7823 	int err;
7824 
7825 	for (i = 0; i < obj->nr_programs; i++) {
7826 		prog = &obj->programs[i];
7827 		err = bpf_object__sanitize_prog(obj, prog);
7828 		if (err)
7829 			return err;
7830 	}
7831 
7832 	for (i = 0; i < obj->nr_programs; i++) {
7833 		prog = &obj->programs[i];
7834 		if (prog_is_subprog(obj, prog))
7835 			continue;
7836 		if (!prog->autoload) {
7837 			pr_debug("prog '%s': skipped loading\n", prog->name);
7838 			continue;
7839 		}
7840 		prog->log_level |= log_level;
7841 
7842 		if (obj->gen_loader)
7843 			bpf_program_record_relos(prog);
7844 
7845 		err = bpf_object_load_prog(obj, prog, prog->insns, prog->insns_cnt,
7846 					   obj->license, obj->kern_version, &prog->fd);
7847 		if (err) {
7848 			pr_warn("prog '%s': failed to load: %d\n", prog->name, err);
7849 			return err;
7850 		}
7851 	}
7852 
7853 	bpf_object__free_relocs(obj);
7854 	return 0;
7855 }
7856 
7857 static const struct bpf_sec_def *find_sec_def(const char *sec_name);
7858 
7859 static int bpf_object_init_progs(struct bpf_object *obj, const struct bpf_object_open_opts *opts)
7860 {
7861 	struct bpf_program *prog;
7862 	int err;
7863 
7864 	bpf_object__for_each_program(prog, obj) {
7865 		prog->sec_def = find_sec_def(prog->sec_name);
7866 		if (!prog->sec_def) {
7867 			/* couldn't guess, but user might manually specify */
7868 			pr_debug("prog '%s': unrecognized ELF section name '%s'\n",
7869 				prog->name, prog->sec_name);
7870 			continue;
7871 		}
7872 
7873 		prog->type = prog->sec_def->prog_type;
7874 		prog->expected_attach_type = prog->sec_def->expected_attach_type;
7875 
7876 		/* sec_def can have custom callback which should be called
7877 		 * after bpf_program is initialized to adjust its properties
7878 		 */
7879 		if (prog->sec_def->prog_setup_fn) {
7880 			err = prog->sec_def->prog_setup_fn(prog, prog->sec_def->cookie);
7881 			if (err < 0) {
7882 				pr_warn("prog '%s': failed to initialize: %d\n",
7883 					prog->name, err);
7884 				return err;
7885 			}
7886 		}
7887 	}
7888 
7889 	return 0;
7890 }
7891 
7892 static struct bpf_object *bpf_object_open(const char *path, const void *obj_buf, size_t obj_buf_sz,
7893 					  const struct bpf_object_open_opts *opts)
7894 {
7895 	const char *obj_name, *kconfig, *btf_tmp_path, *token_path;
7896 	struct bpf_object *obj;
7897 	char tmp_name[64];
7898 	int err;
7899 	char *log_buf;
7900 	size_t log_size;
7901 	__u32 log_level;
7902 
7903 	if (elf_version(EV_CURRENT) == EV_NONE) {
7904 		pr_warn("failed to init libelf for %s\n",
7905 			path ? : "(mem buf)");
7906 		return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
7907 	}
7908 
7909 	if (!OPTS_VALID(opts, bpf_object_open_opts))
7910 		return ERR_PTR(-EINVAL);
7911 
7912 	obj_name = OPTS_GET(opts, object_name, NULL);
7913 	if (obj_buf) {
7914 		if (!obj_name) {
7915 			snprintf(tmp_name, sizeof(tmp_name), "%lx-%lx",
7916 				 (unsigned long)obj_buf,
7917 				 (unsigned long)obj_buf_sz);
7918 			obj_name = tmp_name;
7919 		}
7920 		path = obj_name;
7921 		pr_debug("loading object '%s' from buffer\n", obj_name);
7922 	}
7923 
7924 	log_buf = OPTS_GET(opts, kernel_log_buf, NULL);
7925 	log_size = OPTS_GET(opts, kernel_log_size, 0);
7926 	log_level = OPTS_GET(opts, kernel_log_level, 0);
7927 	if (log_size > UINT_MAX)
7928 		return ERR_PTR(-EINVAL);
7929 	if (log_size && !log_buf)
7930 		return ERR_PTR(-EINVAL);
7931 
7932 	token_path = OPTS_GET(opts, bpf_token_path, NULL);
7933 	/* if user didn't specify bpf_token_path explicitly, check if
7934 	 * LIBBPF_BPF_TOKEN_PATH envvar was set and treat it as bpf_token_path
7935 	 * option
7936 	 */
7937 	if (!token_path)
7938 		token_path = getenv("LIBBPF_BPF_TOKEN_PATH");
7939 	if (token_path && strlen(token_path) >= PATH_MAX)
7940 		return ERR_PTR(-ENAMETOOLONG);
7941 
7942 	obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
7943 	if (IS_ERR(obj))
7944 		return obj;
7945 
7946 	obj->log_buf = log_buf;
7947 	obj->log_size = log_size;
7948 	obj->log_level = log_level;
7949 
7950 	if (token_path) {
7951 		obj->token_path = strdup(token_path);
7952 		if (!obj->token_path) {
7953 			err = -ENOMEM;
7954 			goto out;
7955 		}
7956 	}
7957 
7958 	btf_tmp_path = OPTS_GET(opts, btf_custom_path, NULL);
7959 	if (btf_tmp_path) {
7960 		if (strlen(btf_tmp_path) >= PATH_MAX) {
7961 			err = -ENAMETOOLONG;
7962 			goto out;
7963 		}
7964 		obj->btf_custom_path = strdup(btf_tmp_path);
7965 		if (!obj->btf_custom_path) {
7966 			err = -ENOMEM;
7967 			goto out;
7968 		}
7969 	}
7970 
7971 	kconfig = OPTS_GET(opts, kconfig, NULL);
7972 	if (kconfig) {
7973 		obj->kconfig = strdup(kconfig);
7974 		if (!obj->kconfig) {
7975 			err = -ENOMEM;
7976 			goto out;
7977 		}
7978 	}
7979 
7980 	err = bpf_object__elf_init(obj);
7981 	err = err ? : bpf_object__check_endianness(obj);
7982 	err = err ? : bpf_object__elf_collect(obj);
7983 	err = err ? : bpf_object__collect_externs(obj);
7984 	err = err ? : bpf_object_fixup_btf(obj);
7985 	err = err ? : bpf_object__init_maps(obj, opts);
7986 	err = err ? : bpf_object_init_progs(obj, opts);
7987 	err = err ? : bpf_object__collect_relos(obj);
7988 	if (err)
7989 		goto out;
7990 
7991 	bpf_object__elf_finish(obj);
7992 
7993 	return obj;
7994 out:
7995 	bpf_object__close(obj);
7996 	return ERR_PTR(err);
7997 }
7998 
7999 struct bpf_object *
8000 bpf_object__open_file(const char *path, const struct bpf_object_open_opts *opts)
8001 {
8002 	if (!path)
8003 		return libbpf_err_ptr(-EINVAL);
8004 
8005 	pr_debug("loading %s\n", path);
8006 
8007 	return libbpf_ptr(bpf_object_open(path, NULL, 0, opts));
8008 }
8009 
8010 struct bpf_object *bpf_object__open(const char *path)
8011 {
8012 	return bpf_object__open_file(path, NULL);
8013 }
8014 
8015 struct bpf_object *
8016 bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
8017 		     const struct bpf_object_open_opts *opts)
8018 {
8019 	if (!obj_buf || obj_buf_sz == 0)
8020 		return libbpf_err_ptr(-EINVAL);
8021 
8022 	return libbpf_ptr(bpf_object_open(NULL, obj_buf, obj_buf_sz, opts));
8023 }
8024 
8025 static int bpf_object_unload(struct bpf_object *obj)
8026 {
8027 	size_t i;
8028 
8029 	if (!obj)
8030 		return libbpf_err(-EINVAL);
8031 
8032 	for (i = 0; i < obj->nr_maps; i++) {
8033 		zclose(obj->maps[i].fd);
8034 		if (obj->maps[i].st_ops)
8035 			zfree(&obj->maps[i].st_ops->kern_vdata);
8036 	}
8037 
8038 	for (i = 0; i < obj->nr_programs; i++)
8039 		bpf_program__unload(&obj->programs[i]);
8040 
8041 	return 0;
8042 }
8043 
8044 static int bpf_object__sanitize_maps(struct bpf_object *obj)
8045 {
8046 	struct bpf_map *m;
8047 
8048 	bpf_object__for_each_map(m, obj) {
8049 		if (!bpf_map__is_internal(m))
8050 			continue;
8051 		if (!kernel_supports(obj, FEAT_ARRAY_MMAP))
8052 			m->def.map_flags &= ~BPF_F_MMAPABLE;
8053 	}
8054 
8055 	return 0;
8056 }
8057 
8058 typedef int (*kallsyms_cb_t)(unsigned long long sym_addr, char sym_type,
8059 			     const char *sym_name, void *ctx);
8060 
8061 static int libbpf_kallsyms_parse(kallsyms_cb_t cb, void *ctx)
8062 {
8063 	char sym_type, sym_name[500];
8064 	unsigned long long sym_addr;
8065 	int ret, err = 0;
8066 	FILE *f;
8067 
8068 	f = fopen("/proc/kallsyms", "re");
8069 	if (!f) {
8070 		err = -errno;
8071 		pr_warn("failed to open /proc/kallsyms: %d\n", err);
8072 		return err;
8073 	}
8074 
8075 	while (true) {
8076 		ret = fscanf(f, "%llx %c %499s%*[^\n]\n",
8077 			     &sym_addr, &sym_type, sym_name);
8078 		if (ret == EOF && feof(f))
8079 			break;
8080 		if (ret != 3) {
8081 			pr_warn("failed to read kallsyms entry: %d\n", ret);
8082 			err = -EINVAL;
8083 			break;
8084 		}
8085 
8086 		err = cb(sym_addr, sym_type, sym_name, ctx);
8087 		if (err)
8088 			break;
8089 	}
8090 
8091 	fclose(f);
8092 	return err;
8093 }
8094 
8095 static int kallsyms_cb(unsigned long long sym_addr, char sym_type,
8096 		       const char *sym_name, void *ctx)
8097 {
8098 	struct bpf_object *obj = ctx;
8099 	const struct btf_type *t;
8100 	struct extern_desc *ext;
8101 	char *res;
8102 
8103 	res = strstr(sym_name, ".llvm.");
8104 	if (sym_type == 'd' && res)
8105 		ext = find_extern_by_name_with_len(obj, sym_name, res - sym_name);
8106 	else
8107 		ext = find_extern_by_name(obj, sym_name);
8108 	if (!ext || ext->type != EXT_KSYM)
8109 		return 0;
8110 
8111 	t = btf__type_by_id(obj->btf, ext->btf_id);
8112 	if (!btf_is_var(t))
8113 		return 0;
8114 
8115 	if (ext->is_set && ext->ksym.addr != sym_addr) {
8116 		pr_warn("extern (ksym) '%s': resolution is ambiguous: 0x%llx or 0x%llx\n",
8117 			sym_name, ext->ksym.addr, sym_addr);
8118 		return -EINVAL;
8119 	}
8120 	if (!ext->is_set) {
8121 		ext->is_set = true;
8122 		ext->ksym.addr = sym_addr;
8123 		pr_debug("extern (ksym) '%s': set to 0x%llx\n", sym_name, sym_addr);
8124 	}
8125 	return 0;
8126 }
8127 
8128 static int bpf_object__read_kallsyms_file(struct bpf_object *obj)
8129 {
8130 	return libbpf_kallsyms_parse(kallsyms_cb, obj);
8131 }
8132 
8133 static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
8134 			    __u16 kind, struct btf **res_btf,
8135 			    struct module_btf **res_mod_btf)
8136 {
8137 	struct module_btf *mod_btf;
8138 	struct btf *btf;
8139 	int i, id, err;
8140 
8141 	btf = obj->btf_vmlinux;
8142 	mod_btf = NULL;
8143 	id = btf__find_by_name_kind(btf, ksym_name, kind);
8144 
8145 	if (id == -ENOENT) {
8146 		err = load_module_btfs(obj);
8147 		if (err)
8148 			return err;
8149 
8150 		for (i = 0; i < obj->btf_module_cnt; i++) {
8151 			/* we assume module_btf's BTF FD is always >0 */
8152 			mod_btf = &obj->btf_modules[i];
8153 			btf = mod_btf->btf;
8154 			id = btf__find_by_name_kind_own(btf, ksym_name, kind);
8155 			if (id != -ENOENT)
8156 				break;
8157 		}
8158 	}
8159 	if (id <= 0)
8160 		return -ESRCH;
8161 
8162 	*res_btf = btf;
8163 	*res_mod_btf = mod_btf;
8164 	return id;
8165 }
8166 
8167 static int bpf_object__resolve_ksym_var_btf_id(struct bpf_object *obj,
8168 					       struct extern_desc *ext)
8169 {
8170 	const struct btf_type *targ_var, *targ_type;
8171 	__u32 targ_type_id, local_type_id;
8172 	struct module_btf *mod_btf = NULL;
8173 	const char *targ_var_name;
8174 	struct btf *btf = NULL;
8175 	int id, err;
8176 
8177 	id = find_ksym_btf_id(obj, ext->name, BTF_KIND_VAR, &btf, &mod_btf);
8178 	if (id < 0) {
8179 		if (id == -ESRCH && ext->is_weak)
8180 			return 0;
8181 		pr_warn("extern (var ksym) '%s': not found in kernel BTF\n",
8182 			ext->name);
8183 		return id;
8184 	}
8185 
8186 	/* find local type_id */
8187 	local_type_id = ext->ksym.type_id;
8188 
8189 	/* find target type_id */
8190 	targ_var = btf__type_by_id(btf, id);
8191 	targ_var_name = btf__name_by_offset(btf, targ_var->name_off);
8192 	targ_type = skip_mods_and_typedefs(btf, targ_var->type, &targ_type_id);
8193 
8194 	err = bpf_core_types_are_compat(obj->btf, local_type_id,
8195 					btf, targ_type_id);
8196 	if (err <= 0) {
8197 		const struct btf_type *local_type;
8198 		const char *targ_name, *local_name;
8199 
8200 		local_type = btf__type_by_id(obj->btf, local_type_id);
8201 		local_name = btf__name_by_offset(obj->btf, local_type->name_off);
8202 		targ_name = btf__name_by_offset(btf, targ_type->name_off);
8203 
8204 		pr_warn("extern (var ksym) '%s': incompatible types, expected [%d] %s %s, but kernel has [%d] %s %s\n",
8205 			ext->name, local_type_id,
8206 			btf_kind_str(local_type), local_name, targ_type_id,
8207 			btf_kind_str(targ_type), targ_name);
8208 		return -EINVAL;
8209 	}
8210 
8211 	ext->is_set = true;
8212 	ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
8213 	ext->ksym.kernel_btf_id = id;
8214 	pr_debug("extern (var ksym) '%s': resolved to [%d] %s %s\n",
8215 		 ext->name, id, btf_kind_str(targ_var), targ_var_name);
8216 
8217 	return 0;
8218 }
8219 
8220 static int bpf_object__resolve_ksym_func_btf_id(struct bpf_object *obj,
8221 						struct extern_desc *ext)
8222 {
8223 	int local_func_proto_id, kfunc_proto_id, kfunc_id;
8224 	struct module_btf *mod_btf = NULL;
8225 	const struct btf_type *kern_func;
8226 	struct btf *kern_btf = NULL;
8227 	int ret;
8228 
8229 	local_func_proto_id = ext->ksym.type_id;
8230 
8231 	kfunc_id = find_ksym_btf_id(obj, ext->essent_name ?: ext->name, BTF_KIND_FUNC, &kern_btf,
8232 				    &mod_btf);
8233 	if (kfunc_id < 0) {
8234 		if (kfunc_id == -ESRCH && ext->is_weak)
8235 			return 0;
8236 		pr_warn("extern (func ksym) '%s': not found in kernel or module BTFs\n",
8237 			ext->name);
8238 		return kfunc_id;
8239 	}
8240 
8241 	kern_func = btf__type_by_id(kern_btf, kfunc_id);
8242 	kfunc_proto_id = kern_func->type;
8243 
8244 	ret = bpf_core_types_are_compat(obj->btf, local_func_proto_id,
8245 					kern_btf, kfunc_proto_id);
8246 	if (ret <= 0) {
8247 		if (ext->is_weak)
8248 			return 0;
8249 
8250 		pr_warn("extern (func ksym) '%s': func_proto [%d] incompatible with %s [%d]\n",
8251 			ext->name, local_func_proto_id,
8252 			mod_btf ? mod_btf->name : "vmlinux", kfunc_proto_id);
8253 		return -EINVAL;
8254 	}
8255 
8256 	/* set index for module BTF fd in fd_array, if unset */
8257 	if (mod_btf && !mod_btf->fd_array_idx) {
8258 		/* insn->off is s16 */
8259 		if (obj->fd_array_cnt == INT16_MAX) {
8260 			pr_warn("extern (func ksym) '%s': module BTF fd index %d too big to fit in bpf_insn offset\n",
8261 				ext->name, mod_btf->fd_array_idx);
8262 			return -E2BIG;
8263 		}
8264 		/* Cannot use index 0 for module BTF fd */
8265 		if (!obj->fd_array_cnt)
8266 			obj->fd_array_cnt = 1;
8267 
8268 		ret = libbpf_ensure_mem((void **)&obj->fd_array, &obj->fd_array_cap, sizeof(int),
8269 					obj->fd_array_cnt + 1);
8270 		if (ret)
8271 			return ret;
8272 		mod_btf->fd_array_idx = obj->fd_array_cnt;
8273 		/* we assume module BTF FD is always >0 */
8274 		obj->fd_array[obj->fd_array_cnt++] = mod_btf->fd;
8275 	}
8276 
8277 	ext->is_set = true;
8278 	ext->ksym.kernel_btf_id = kfunc_id;
8279 	ext->ksym.btf_fd_idx = mod_btf ? mod_btf->fd_array_idx : 0;
8280 	/* Also set kernel_btf_obj_fd to make sure that bpf_object__relocate_data()
8281 	 * populates FD into ld_imm64 insn when it's used to point to kfunc.
8282 	 * {kernel_btf_id, btf_fd_idx} -> fixup bpf_call.
8283 	 * {kernel_btf_id, kernel_btf_obj_fd} -> fixup ld_imm64.
8284 	 */
8285 	ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
8286 	pr_debug("extern (func ksym) '%s': resolved to %s [%d]\n",
8287 		 ext->name, mod_btf ? mod_btf->name : "vmlinux", kfunc_id);
8288 
8289 	return 0;
8290 }
8291 
8292 static int bpf_object__resolve_ksyms_btf_id(struct bpf_object *obj)
8293 {
8294 	const struct btf_type *t;
8295 	struct extern_desc *ext;
8296 	int i, err;
8297 
8298 	for (i = 0; i < obj->nr_extern; i++) {
8299 		ext = &obj->externs[i];
8300 		if (ext->type != EXT_KSYM || !ext->ksym.type_id)
8301 			continue;
8302 
8303 		if (obj->gen_loader) {
8304 			ext->is_set = true;
8305 			ext->ksym.kernel_btf_obj_fd = 0;
8306 			ext->ksym.kernel_btf_id = 0;
8307 			continue;
8308 		}
8309 		t = btf__type_by_id(obj->btf, ext->btf_id);
8310 		if (btf_is_var(t))
8311 			err = bpf_object__resolve_ksym_var_btf_id(obj, ext);
8312 		else
8313 			err = bpf_object__resolve_ksym_func_btf_id(obj, ext);
8314 		if (err)
8315 			return err;
8316 	}
8317 	return 0;
8318 }
8319 
8320 static int bpf_object__resolve_externs(struct bpf_object *obj,
8321 				       const char *extra_kconfig)
8322 {
8323 	bool need_config = false, need_kallsyms = false;
8324 	bool need_vmlinux_btf = false;
8325 	struct extern_desc *ext;
8326 	void *kcfg_data = NULL;
8327 	int err, i;
8328 
8329 	if (obj->nr_extern == 0)
8330 		return 0;
8331 
8332 	if (obj->kconfig_map_idx >= 0)
8333 		kcfg_data = obj->maps[obj->kconfig_map_idx].mmaped;
8334 
8335 	for (i = 0; i < obj->nr_extern; i++) {
8336 		ext = &obj->externs[i];
8337 
8338 		if (ext->type == EXT_KSYM) {
8339 			if (ext->ksym.type_id)
8340 				need_vmlinux_btf = true;
8341 			else
8342 				need_kallsyms = true;
8343 			continue;
8344 		} else if (ext->type == EXT_KCFG) {
8345 			void *ext_ptr = kcfg_data + ext->kcfg.data_off;
8346 			__u64 value = 0;
8347 
8348 			/* Kconfig externs need actual /proc/config.gz */
8349 			if (str_has_pfx(ext->name, "CONFIG_")) {
8350 				need_config = true;
8351 				continue;
8352 			}
8353 
8354 			/* Virtual kcfg externs are customly handled by libbpf */
8355 			if (strcmp(ext->name, "LINUX_KERNEL_VERSION") == 0) {
8356 				value = get_kernel_version();
8357 				if (!value) {
8358 					pr_warn("extern (kcfg) '%s': failed to get kernel version\n", ext->name);
8359 					return -EINVAL;
8360 				}
8361 			} else if (strcmp(ext->name, "LINUX_HAS_BPF_COOKIE") == 0) {
8362 				value = kernel_supports(obj, FEAT_BPF_COOKIE);
8363 			} else if (strcmp(ext->name, "LINUX_HAS_SYSCALL_WRAPPER") == 0) {
8364 				value = kernel_supports(obj, FEAT_SYSCALL_WRAPPER);
8365 			} else if (!str_has_pfx(ext->name, "LINUX_") || !ext->is_weak) {
8366 				/* Currently libbpf supports only CONFIG_ and LINUX_ prefixed
8367 				 * __kconfig externs, where LINUX_ ones are virtual and filled out
8368 				 * customly by libbpf (their values don't come from Kconfig).
8369 				 * If LINUX_xxx variable is not recognized by libbpf, but is marked
8370 				 * __weak, it defaults to zero value, just like for CONFIG_xxx
8371 				 * externs.
8372 				 */
8373 				pr_warn("extern (kcfg) '%s': unrecognized virtual extern\n", ext->name);
8374 				return -EINVAL;
8375 			}
8376 
8377 			err = set_kcfg_value_num(ext, ext_ptr, value);
8378 			if (err)
8379 				return err;
8380 			pr_debug("extern (kcfg) '%s': set to 0x%llx\n",
8381 				 ext->name, (long long)value);
8382 		} else {
8383 			pr_warn("extern '%s': unrecognized extern kind\n", ext->name);
8384 			return -EINVAL;
8385 		}
8386 	}
8387 	if (need_config && extra_kconfig) {
8388 		err = bpf_object__read_kconfig_mem(obj, extra_kconfig, kcfg_data);
8389 		if (err)
8390 			return -EINVAL;
8391 		need_config = false;
8392 		for (i = 0; i < obj->nr_extern; i++) {
8393 			ext = &obj->externs[i];
8394 			if (ext->type == EXT_KCFG && !ext->is_set) {
8395 				need_config = true;
8396 				break;
8397 			}
8398 		}
8399 	}
8400 	if (need_config) {
8401 		err = bpf_object__read_kconfig_file(obj, kcfg_data);
8402 		if (err)
8403 			return -EINVAL;
8404 	}
8405 	if (need_kallsyms) {
8406 		err = bpf_object__read_kallsyms_file(obj);
8407 		if (err)
8408 			return -EINVAL;
8409 	}
8410 	if (need_vmlinux_btf) {
8411 		err = bpf_object__resolve_ksyms_btf_id(obj);
8412 		if (err)
8413 			return -EINVAL;
8414 	}
8415 	for (i = 0; i < obj->nr_extern; i++) {
8416 		ext = &obj->externs[i];
8417 
8418 		if (!ext->is_set && !ext->is_weak) {
8419 			pr_warn("extern '%s' (strong): not resolved\n", ext->name);
8420 			return -ESRCH;
8421 		} else if (!ext->is_set) {
8422 			pr_debug("extern '%s' (weak): not resolved, defaulting to zero\n",
8423 				 ext->name);
8424 		}
8425 	}
8426 
8427 	return 0;
8428 }
8429 
8430 static void bpf_map_prepare_vdata(const struct bpf_map *map)
8431 {
8432 	struct bpf_struct_ops *st_ops;
8433 	__u32 i;
8434 
8435 	st_ops = map->st_ops;
8436 	for (i = 0; i < btf_vlen(st_ops->type); i++) {
8437 		struct bpf_program *prog = st_ops->progs[i];
8438 		void *kern_data;
8439 		int prog_fd;
8440 
8441 		if (!prog)
8442 			continue;
8443 
8444 		prog_fd = bpf_program__fd(prog);
8445 		kern_data = st_ops->kern_vdata + st_ops->kern_func_off[i];
8446 		*(unsigned long *)kern_data = prog_fd;
8447 	}
8448 }
8449 
8450 static int bpf_object_prepare_struct_ops(struct bpf_object *obj)
8451 {
8452 	struct bpf_map *map;
8453 	int i;
8454 
8455 	for (i = 0; i < obj->nr_maps; i++) {
8456 		map = &obj->maps[i];
8457 
8458 		if (!bpf_map__is_struct_ops(map))
8459 			continue;
8460 
8461 		if (!map->autocreate)
8462 			continue;
8463 
8464 		bpf_map_prepare_vdata(map);
8465 	}
8466 
8467 	return 0;
8468 }
8469 
8470 static int bpf_object_load(struct bpf_object *obj, int extra_log_level, const char *target_btf_path)
8471 {
8472 	int err, i;
8473 
8474 	if (!obj)
8475 		return libbpf_err(-EINVAL);
8476 
8477 	if (obj->loaded) {
8478 		pr_warn("object '%s': load can't be attempted twice\n", obj->name);
8479 		return libbpf_err(-EINVAL);
8480 	}
8481 
8482 	if (obj->gen_loader)
8483 		bpf_gen__init(obj->gen_loader, extra_log_level, obj->nr_programs, obj->nr_maps);
8484 
8485 	err = bpf_object_prepare_token(obj);
8486 	err = err ? : bpf_object__probe_loading(obj);
8487 	err = err ? : bpf_object__load_vmlinux_btf(obj, false);
8488 	err = err ? : bpf_object__resolve_externs(obj, obj->kconfig);
8489 	err = err ? : bpf_object__sanitize_maps(obj);
8490 	err = err ? : bpf_object__init_kern_struct_ops_maps(obj);
8491 	err = err ? : bpf_object_adjust_struct_ops_autoload(obj);
8492 	err = err ? : bpf_object__relocate(obj, obj->btf_custom_path ? : target_btf_path);
8493 	err = err ? : bpf_object__sanitize_and_load_btf(obj);
8494 	err = err ? : bpf_object__create_maps(obj);
8495 	err = err ? : bpf_object__load_progs(obj, extra_log_level);
8496 	err = err ? : bpf_object_init_prog_arrays(obj);
8497 	err = err ? : bpf_object_prepare_struct_ops(obj);
8498 
8499 	if (obj->gen_loader) {
8500 		/* reset FDs */
8501 		if (obj->btf)
8502 			btf__set_fd(obj->btf, -1);
8503 		if (!err)
8504 			err = bpf_gen__finish(obj->gen_loader, obj->nr_programs, obj->nr_maps);
8505 	}
8506 
8507 	/* clean up fd_array */
8508 	zfree(&obj->fd_array);
8509 
8510 	/* clean up module BTFs */
8511 	for (i = 0; i < obj->btf_module_cnt; i++) {
8512 		close(obj->btf_modules[i].fd);
8513 		btf__free(obj->btf_modules[i].btf);
8514 		free(obj->btf_modules[i].name);
8515 	}
8516 	free(obj->btf_modules);
8517 
8518 	/* clean up vmlinux BTF */
8519 	btf__free(obj->btf_vmlinux);
8520 	obj->btf_vmlinux = NULL;
8521 
8522 	obj->loaded = true; /* doesn't matter if successfully or not */
8523 
8524 	if (err)
8525 		goto out;
8526 
8527 	return 0;
8528 out:
8529 	/* unpin any maps that were auto-pinned during load */
8530 	for (i = 0; i < obj->nr_maps; i++)
8531 		if (obj->maps[i].pinned && !obj->maps[i].reused)
8532 			bpf_map__unpin(&obj->maps[i], NULL);
8533 
8534 	bpf_object_unload(obj);
8535 	pr_warn("failed to load object '%s'\n", obj->path);
8536 	return libbpf_err(err);
8537 }
8538 
8539 int bpf_object__load(struct bpf_object *obj)
8540 {
8541 	return bpf_object_load(obj, 0, NULL);
8542 }
8543 
8544 static int make_parent_dir(const char *path)
8545 {
8546 	char *cp, errmsg[STRERR_BUFSIZE];
8547 	char *dname, *dir;
8548 	int err = 0;
8549 
8550 	dname = strdup(path);
8551 	if (dname == NULL)
8552 		return -ENOMEM;
8553 
8554 	dir = dirname(dname);
8555 	if (mkdir(dir, 0700) && errno != EEXIST)
8556 		err = -errno;
8557 
8558 	free(dname);
8559 	if (err) {
8560 		cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
8561 		pr_warn("failed to mkdir %s: %s\n", path, cp);
8562 	}
8563 	return err;
8564 }
8565 
8566 static int check_path(const char *path)
8567 {
8568 	char *cp, errmsg[STRERR_BUFSIZE];
8569 	struct statfs st_fs;
8570 	char *dname, *dir;
8571 	int err = 0;
8572 
8573 	if (path == NULL)
8574 		return -EINVAL;
8575 
8576 	dname = strdup(path);
8577 	if (dname == NULL)
8578 		return -ENOMEM;
8579 
8580 	dir = dirname(dname);
8581 	if (statfs(dir, &st_fs)) {
8582 		cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
8583 		pr_warn("failed to statfs %s: %s\n", dir, cp);
8584 		err = -errno;
8585 	}
8586 	free(dname);
8587 
8588 	if (!err && st_fs.f_type != BPF_FS_MAGIC) {
8589 		pr_warn("specified path %s is not on BPF FS\n", path);
8590 		err = -EINVAL;
8591 	}
8592 
8593 	return err;
8594 }
8595 
8596 int bpf_program__pin(struct bpf_program *prog, const char *path)
8597 {
8598 	char *cp, errmsg[STRERR_BUFSIZE];
8599 	int err;
8600 
8601 	if (prog->fd < 0) {
8602 		pr_warn("prog '%s': can't pin program that wasn't loaded\n", prog->name);
8603 		return libbpf_err(-EINVAL);
8604 	}
8605 
8606 	err = make_parent_dir(path);
8607 	if (err)
8608 		return libbpf_err(err);
8609 
8610 	err = check_path(path);
8611 	if (err)
8612 		return libbpf_err(err);
8613 
8614 	if (bpf_obj_pin(prog->fd, path)) {
8615 		err = -errno;
8616 		cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
8617 		pr_warn("prog '%s': failed to pin at '%s': %s\n", prog->name, path, cp);
8618 		return libbpf_err(err);
8619 	}
8620 
8621 	pr_debug("prog '%s': pinned at '%s'\n", prog->name, path);
8622 	return 0;
8623 }
8624 
8625 int bpf_program__unpin(struct bpf_program *prog, const char *path)
8626 {
8627 	int err;
8628 
8629 	if (prog->fd < 0) {
8630 		pr_warn("prog '%s': can't unpin program that wasn't loaded\n", prog->name);
8631 		return libbpf_err(-EINVAL);
8632 	}
8633 
8634 	err = check_path(path);
8635 	if (err)
8636 		return libbpf_err(err);
8637 
8638 	err = unlink(path);
8639 	if (err)
8640 		return libbpf_err(-errno);
8641 
8642 	pr_debug("prog '%s': unpinned from '%s'\n", prog->name, path);
8643 	return 0;
8644 }
8645 
8646 int bpf_map__pin(struct bpf_map *map, const char *path)
8647 {
8648 	char *cp, errmsg[STRERR_BUFSIZE];
8649 	int err;
8650 
8651 	if (map == NULL) {
8652 		pr_warn("invalid map pointer\n");
8653 		return libbpf_err(-EINVAL);
8654 	}
8655 
8656 	if (map->fd < 0) {
8657 		pr_warn("map '%s': can't pin BPF map without FD (was it created?)\n", map->name);
8658 		return libbpf_err(-EINVAL);
8659 	}
8660 
8661 	if (map->pin_path) {
8662 		if (path && strcmp(path, map->pin_path)) {
8663 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
8664 				bpf_map__name(map), map->pin_path, path);
8665 			return libbpf_err(-EINVAL);
8666 		} else if (map->pinned) {
8667 			pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
8668 				 bpf_map__name(map), map->pin_path);
8669 			return 0;
8670 		}
8671 	} else {
8672 		if (!path) {
8673 			pr_warn("missing a path to pin map '%s' at\n",
8674 				bpf_map__name(map));
8675 			return libbpf_err(-EINVAL);
8676 		} else if (map->pinned) {
8677 			pr_warn("map '%s' already pinned\n", bpf_map__name(map));
8678 			return libbpf_err(-EEXIST);
8679 		}
8680 
8681 		map->pin_path = strdup(path);
8682 		if (!map->pin_path) {
8683 			err = -errno;
8684 			goto out_err;
8685 		}
8686 	}
8687 
8688 	err = make_parent_dir(map->pin_path);
8689 	if (err)
8690 		return libbpf_err(err);
8691 
8692 	err = check_path(map->pin_path);
8693 	if (err)
8694 		return libbpf_err(err);
8695 
8696 	if (bpf_obj_pin(map->fd, map->pin_path)) {
8697 		err = -errno;
8698 		goto out_err;
8699 	}
8700 
8701 	map->pinned = true;
8702 	pr_debug("pinned map '%s'\n", map->pin_path);
8703 
8704 	return 0;
8705 
8706 out_err:
8707 	cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
8708 	pr_warn("failed to pin map: %s\n", cp);
8709 	return libbpf_err(err);
8710 }
8711 
8712 int bpf_map__unpin(struct bpf_map *map, const char *path)
8713 {
8714 	int err;
8715 
8716 	if (map == NULL) {
8717 		pr_warn("invalid map pointer\n");
8718 		return libbpf_err(-EINVAL);
8719 	}
8720 
8721 	if (map->pin_path) {
8722 		if (path && strcmp(path, map->pin_path)) {
8723 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
8724 				bpf_map__name(map), map->pin_path, path);
8725 			return libbpf_err(-EINVAL);
8726 		}
8727 		path = map->pin_path;
8728 	} else if (!path) {
8729 		pr_warn("no path to unpin map '%s' from\n",
8730 			bpf_map__name(map));
8731 		return libbpf_err(-EINVAL);
8732 	}
8733 
8734 	err = check_path(path);
8735 	if (err)
8736 		return libbpf_err(err);
8737 
8738 	err = unlink(path);
8739 	if (err != 0)
8740 		return libbpf_err(-errno);
8741 
8742 	map->pinned = false;
8743 	pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path);
8744 
8745 	return 0;
8746 }
8747 
8748 int bpf_map__set_pin_path(struct bpf_map *map, const char *path)
8749 {
8750 	char *new = NULL;
8751 
8752 	if (path) {
8753 		new = strdup(path);
8754 		if (!new)
8755 			return libbpf_err(-errno);
8756 	}
8757 
8758 	free(map->pin_path);
8759 	map->pin_path = new;
8760 	return 0;
8761 }
8762 
8763 __alias(bpf_map__pin_path)
8764 const char *bpf_map__get_pin_path(const struct bpf_map *map);
8765 
8766 const char *bpf_map__pin_path(const struct bpf_map *map)
8767 {
8768 	return map->pin_path;
8769 }
8770 
8771 bool bpf_map__is_pinned(const struct bpf_map *map)
8772 {
8773 	return map->pinned;
8774 }
8775 
8776 static void sanitize_pin_path(char *s)
8777 {
8778 	/* bpffs disallows periods in path names */
8779 	while (*s) {
8780 		if (*s == '.')
8781 			*s = '_';
8782 		s++;
8783 	}
8784 }
8785 
8786 int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
8787 {
8788 	struct bpf_map *map;
8789 	int err;
8790 
8791 	if (!obj)
8792 		return libbpf_err(-ENOENT);
8793 
8794 	if (!obj->loaded) {
8795 		pr_warn("object not yet loaded; load it first\n");
8796 		return libbpf_err(-ENOENT);
8797 	}
8798 
8799 	bpf_object__for_each_map(map, obj) {
8800 		char *pin_path = NULL;
8801 		char buf[PATH_MAX];
8802 
8803 		if (!map->autocreate)
8804 			continue;
8805 
8806 		if (path) {
8807 			err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
8808 			if (err)
8809 				goto err_unpin_maps;
8810 			sanitize_pin_path(buf);
8811 			pin_path = buf;
8812 		} else if (!map->pin_path) {
8813 			continue;
8814 		}
8815 
8816 		err = bpf_map__pin(map, pin_path);
8817 		if (err)
8818 			goto err_unpin_maps;
8819 	}
8820 
8821 	return 0;
8822 
8823 err_unpin_maps:
8824 	while ((map = bpf_object__prev_map(obj, map))) {
8825 		if (!map->pin_path)
8826 			continue;
8827 
8828 		bpf_map__unpin(map, NULL);
8829 	}
8830 
8831 	return libbpf_err(err);
8832 }
8833 
8834 int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
8835 {
8836 	struct bpf_map *map;
8837 	int err;
8838 
8839 	if (!obj)
8840 		return libbpf_err(-ENOENT);
8841 
8842 	bpf_object__for_each_map(map, obj) {
8843 		char *pin_path = NULL;
8844 		char buf[PATH_MAX];
8845 
8846 		if (path) {
8847 			err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
8848 			if (err)
8849 				return libbpf_err(err);
8850 			sanitize_pin_path(buf);
8851 			pin_path = buf;
8852 		} else if (!map->pin_path) {
8853 			continue;
8854 		}
8855 
8856 		err = bpf_map__unpin(map, pin_path);
8857 		if (err)
8858 			return libbpf_err(err);
8859 	}
8860 
8861 	return 0;
8862 }
8863 
8864 int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
8865 {
8866 	struct bpf_program *prog;
8867 	char buf[PATH_MAX];
8868 	int err;
8869 
8870 	if (!obj)
8871 		return libbpf_err(-ENOENT);
8872 
8873 	if (!obj->loaded) {
8874 		pr_warn("object not yet loaded; load it first\n");
8875 		return libbpf_err(-ENOENT);
8876 	}
8877 
8878 	bpf_object__for_each_program(prog, obj) {
8879 		err = pathname_concat(buf, sizeof(buf), path, prog->name);
8880 		if (err)
8881 			goto err_unpin_programs;
8882 
8883 		err = bpf_program__pin(prog, buf);
8884 		if (err)
8885 			goto err_unpin_programs;
8886 	}
8887 
8888 	return 0;
8889 
8890 err_unpin_programs:
8891 	while ((prog = bpf_object__prev_program(obj, prog))) {
8892 		if (pathname_concat(buf, sizeof(buf), path, prog->name))
8893 			continue;
8894 
8895 		bpf_program__unpin(prog, buf);
8896 	}
8897 
8898 	return libbpf_err(err);
8899 }
8900 
8901 int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
8902 {
8903 	struct bpf_program *prog;
8904 	int err;
8905 
8906 	if (!obj)
8907 		return libbpf_err(-ENOENT);
8908 
8909 	bpf_object__for_each_program(prog, obj) {
8910 		char buf[PATH_MAX];
8911 
8912 		err = pathname_concat(buf, sizeof(buf), path, prog->name);
8913 		if (err)
8914 			return libbpf_err(err);
8915 
8916 		err = bpf_program__unpin(prog, buf);
8917 		if (err)
8918 			return libbpf_err(err);
8919 	}
8920 
8921 	return 0;
8922 }
8923 
8924 int bpf_object__pin(struct bpf_object *obj, const char *path)
8925 {
8926 	int err;
8927 
8928 	err = bpf_object__pin_maps(obj, path);
8929 	if (err)
8930 		return libbpf_err(err);
8931 
8932 	err = bpf_object__pin_programs(obj, path);
8933 	if (err) {
8934 		bpf_object__unpin_maps(obj, path);
8935 		return libbpf_err(err);
8936 	}
8937 
8938 	return 0;
8939 }
8940 
8941 int bpf_object__unpin(struct bpf_object *obj, const char *path)
8942 {
8943 	int err;
8944 
8945 	err = bpf_object__unpin_programs(obj, path);
8946 	if (err)
8947 		return libbpf_err(err);
8948 
8949 	err = bpf_object__unpin_maps(obj, path);
8950 	if (err)
8951 		return libbpf_err(err);
8952 
8953 	return 0;
8954 }
8955 
8956 static void bpf_map__destroy(struct bpf_map *map)
8957 {
8958 	if (map->inner_map) {
8959 		bpf_map__destroy(map->inner_map);
8960 		zfree(&map->inner_map);
8961 	}
8962 
8963 	zfree(&map->init_slots);
8964 	map->init_slots_sz = 0;
8965 
8966 	if (map->mmaped && map->mmaped != map->obj->arena_data)
8967 		munmap(map->mmaped, bpf_map_mmap_sz(map));
8968 	map->mmaped = NULL;
8969 
8970 	if (map->st_ops) {
8971 		zfree(&map->st_ops->data);
8972 		zfree(&map->st_ops->progs);
8973 		zfree(&map->st_ops->kern_func_off);
8974 		zfree(&map->st_ops);
8975 	}
8976 
8977 	zfree(&map->name);
8978 	zfree(&map->real_name);
8979 	zfree(&map->pin_path);
8980 
8981 	if (map->fd >= 0)
8982 		zclose(map->fd);
8983 }
8984 
8985 void bpf_object__close(struct bpf_object *obj)
8986 {
8987 	size_t i;
8988 
8989 	if (IS_ERR_OR_NULL(obj))
8990 		return;
8991 
8992 	usdt_manager_free(obj->usdt_man);
8993 	obj->usdt_man = NULL;
8994 
8995 	bpf_gen__free(obj->gen_loader);
8996 	bpf_object__elf_finish(obj);
8997 	bpf_object_unload(obj);
8998 	btf__free(obj->btf);
8999 	btf__free(obj->btf_vmlinux);
9000 	btf_ext__free(obj->btf_ext);
9001 
9002 	for (i = 0; i < obj->nr_maps; i++)
9003 		bpf_map__destroy(&obj->maps[i]);
9004 
9005 	zfree(&obj->btf_custom_path);
9006 	zfree(&obj->kconfig);
9007 
9008 	for (i = 0; i < obj->nr_extern; i++)
9009 		zfree(&obj->externs[i].essent_name);
9010 
9011 	zfree(&obj->externs);
9012 	obj->nr_extern = 0;
9013 
9014 	zfree(&obj->maps);
9015 	obj->nr_maps = 0;
9016 
9017 	if (obj->programs && obj->nr_programs) {
9018 		for (i = 0; i < obj->nr_programs; i++)
9019 			bpf_program__exit(&obj->programs[i]);
9020 	}
9021 	zfree(&obj->programs);
9022 
9023 	zfree(&obj->feat_cache);
9024 	zfree(&obj->token_path);
9025 	if (obj->token_fd > 0)
9026 		close(obj->token_fd);
9027 
9028 	zfree(&obj->arena_data);
9029 
9030 	free(obj);
9031 }
9032 
9033 const char *bpf_object__name(const struct bpf_object *obj)
9034 {
9035 	return obj ? obj->name : libbpf_err_ptr(-EINVAL);
9036 }
9037 
9038 unsigned int bpf_object__kversion(const struct bpf_object *obj)
9039 {
9040 	return obj ? obj->kern_version : 0;
9041 }
9042 
9043 struct btf *bpf_object__btf(const struct bpf_object *obj)
9044 {
9045 	return obj ? obj->btf : NULL;
9046 }
9047 
9048 int bpf_object__btf_fd(const struct bpf_object *obj)
9049 {
9050 	return obj->btf ? btf__fd(obj->btf) : -1;
9051 }
9052 
9053 int bpf_object__set_kversion(struct bpf_object *obj, __u32 kern_version)
9054 {
9055 	if (obj->loaded)
9056 		return libbpf_err(-EINVAL);
9057 
9058 	obj->kern_version = kern_version;
9059 
9060 	return 0;
9061 }
9062 
9063 int bpf_object__gen_loader(struct bpf_object *obj, struct gen_loader_opts *opts)
9064 {
9065 	struct bpf_gen *gen;
9066 
9067 	if (!opts)
9068 		return -EFAULT;
9069 	if (!OPTS_VALID(opts, gen_loader_opts))
9070 		return -EINVAL;
9071 	gen = calloc(sizeof(*gen), 1);
9072 	if (!gen)
9073 		return -ENOMEM;
9074 	gen->opts = opts;
9075 	obj->gen_loader = gen;
9076 	return 0;
9077 }
9078 
9079 static struct bpf_program *
9080 __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
9081 		    bool forward)
9082 {
9083 	size_t nr_programs = obj->nr_programs;
9084 	ssize_t idx;
9085 
9086 	if (!nr_programs)
9087 		return NULL;
9088 
9089 	if (!p)
9090 		/* Iter from the beginning */
9091 		return forward ? &obj->programs[0] :
9092 			&obj->programs[nr_programs - 1];
9093 
9094 	if (p->obj != obj) {
9095 		pr_warn("error: program handler doesn't match object\n");
9096 		return errno = EINVAL, NULL;
9097 	}
9098 
9099 	idx = (p - obj->programs) + (forward ? 1 : -1);
9100 	if (idx >= obj->nr_programs || idx < 0)
9101 		return NULL;
9102 	return &obj->programs[idx];
9103 }
9104 
9105 struct bpf_program *
9106 bpf_object__next_program(const struct bpf_object *obj, struct bpf_program *prev)
9107 {
9108 	struct bpf_program *prog = prev;
9109 
9110 	do {
9111 		prog = __bpf_program__iter(prog, obj, true);
9112 	} while (prog && prog_is_subprog(obj, prog));
9113 
9114 	return prog;
9115 }
9116 
9117 struct bpf_program *
9118 bpf_object__prev_program(const struct bpf_object *obj, struct bpf_program *next)
9119 {
9120 	struct bpf_program *prog = next;
9121 
9122 	do {
9123 		prog = __bpf_program__iter(prog, obj, false);
9124 	} while (prog && prog_is_subprog(obj, prog));
9125 
9126 	return prog;
9127 }
9128 
9129 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
9130 {
9131 	prog->prog_ifindex = ifindex;
9132 }
9133 
9134 const char *bpf_program__name(const struct bpf_program *prog)
9135 {
9136 	return prog->name;
9137 }
9138 
9139 const char *bpf_program__section_name(const struct bpf_program *prog)
9140 {
9141 	return prog->sec_name;
9142 }
9143 
9144 bool bpf_program__autoload(const struct bpf_program *prog)
9145 {
9146 	return prog->autoload;
9147 }
9148 
9149 int bpf_program__set_autoload(struct bpf_program *prog, bool autoload)
9150 {
9151 	if (prog->obj->loaded)
9152 		return libbpf_err(-EINVAL);
9153 
9154 	prog->autoload = autoload;
9155 	return 0;
9156 }
9157 
9158 bool bpf_program__autoattach(const struct bpf_program *prog)
9159 {
9160 	return prog->autoattach;
9161 }
9162 
9163 void bpf_program__set_autoattach(struct bpf_program *prog, bool autoattach)
9164 {
9165 	prog->autoattach = autoattach;
9166 }
9167 
9168 const struct bpf_insn *bpf_program__insns(const struct bpf_program *prog)
9169 {
9170 	return prog->insns;
9171 }
9172 
9173 size_t bpf_program__insn_cnt(const struct bpf_program *prog)
9174 {
9175 	return prog->insns_cnt;
9176 }
9177 
9178 int bpf_program__set_insns(struct bpf_program *prog,
9179 			   struct bpf_insn *new_insns, size_t new_insn_cnt)
9180 {
9181 	struct bpf_insn *insns;
9182 
9183 	if (prog->obj->loaded)
9184 		return -EBUSY;
9185 
9186 	insns = libbpf_reallocarray(prog->insns, new_insn_cnt, sizeof(*insns));
9187 	/* NULL is a valid return from reallocarray if the new count is zero */
9188 	if (!insns && new_insn_cnt) {
9189 		pr_warn("prog '%s': failed to realloc prog code\n", prog->name);
9190 		return -ENOMEM;
9191 	}
9192 	memcpy(insns, new_insns, new_insn_cnt * sizeof(*insns));
9193 
9194 	prog->insns = insns;
9195 	prog->insns_cnt = new_insn_cnt;
9196 	return 0;
9197 }
9198 
9199 int bpf_program__fd(const struct bpf_program *prog)
9200 {
9201 	if (!prog)
9202 		return libbpf_err(-EINVAL);
9203 
9204 	if (prog->fd < 0)
9205 		return libbpf_err(-ENOENT);
9206 
9207 	return prog->fd;
9208 }
9209 
9210 __alias(bpf_program__type)
9211 enum bpf_prog_type bpf_program__get_type(const struct bpf_program *prog);
9212 
9213 enum bpf_prog_type bpf_program__type(const struct bpf_program *prog)
9214 {
9215 	return prog->type;
9216 }
9217 
9218 static size_t custom_sec_def_cnt;
9219 static struct bpf_sec_def *custom_sec_defs;
9220 static struct bpf_sec_def custom_fallback_def;
9221 static bool has_custom_fallback_def;
9222 static int last_custom_sec_def_handler_id;
9223 
9224 int bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
9225 {
9226 	if (prog->obj->loaded)
9227 		return libbpf_err(-EBUSY);
9228 
9229 	/* if type is not changed, do nothing */
9230 	if (prog->type == type)
9231 		return 0;
9232 
9233 	prog->type = type;
9234 
9235 	/* If a program type was changed, we need to reset associated SEC()
9236 	 * handler, as it will be invalid now. The only exception is a generic
9237 	 * fallback handler, which by definition is program type-agnostic and
9238 	 * is a catch-all custom handler, optionally set by the application,
9239 	 * so should be able to handle any type of BPF program.
9240 	 */
9241 	if (prog->sec_def != &custom_fallback_def)
9242 		prog->sec_def = NULL;
9243 	return 0;
9244 }
9245 
9246 __alias(bpf_program__expected_attach_type)
9247 enum bpf_attach_type bpf_program__get_expected_attach_type(const struct bpf_program *prog);
9248 
9249 enum bpf_attach_type bpf_program__expected_attach_type(const struct bpf_program *prog)
9250 {
9251 	return prog->expected_attach_type;
9252 }
9253 
9254 int bpf_program__set_expected_attach_type(struct bpf_program *prog,
9255 					   enum bpf_attach_type type)
9256 {
9257 	if (prog->obj->loaded)
9258 		return libbpf_err(-EBUSY);
9259 
9260 	prog->expected_attach_type = type;
9261 	return 0;
9262 }
9263 
9264 __u32 bpf_program__flags(const struct bpf_program *prog)
9265 {
9266 	return prog->prog_flags;
9267 }
9268 
9269 int bpf_program__set_flags(struct bpf_program *prog, __u32 flags)
9270 {
9271 	if (prog->obj->loaded)
9272 		return libbpf_err(-EBUSY);
9273 
9274 	prog->prog_flags = flags;
9275 	return 0;
9276 }
9277 
9278 __u32 bpf_program__log_level(const struct bpf_program *prog)
9279 {
9280 	return prog->log_level;
9281 }
9282 
9283 int bpf_program__set_log_level(struct bpf_program *prog, __u32 log_level)
9284 {
9285 	if (prog->obj->loaded)
9286 		return libbpf_err(-EBUSY);
9287 
9288 	prog->log_level = log_level;
9289 	return 0;
9290 }
9291 
9292 const char *bpf_program__log_buf(const struct bpf_program *prog, size_t *log_size)
9293 {
9294 	*log_size = prog->log_size;
9295 	return prog->log_buf;
9296 }
9297 
9298 int bpf_program__set_log_buf(struct bpf_program *prog, char *log_buf, size_t log_size)
9299 {
9300 	if (log_size && !log_buf)
9301 		return -EINVAL;
9302 	if (prog->log_size > UINT_MAX)
9303 		return -EINVAL;
9304 	if (prog->obj->loaded)
9305 		return -EBUSY;
9306 
9307 	prog->log_buf = log_buf;
9308 	prog->log_size = log_size;
9309 	return 0;
9310 }
9311 
9312 #define SEC_DEF(sec_pfx, ptype, atype, flags, ...) {			    \
9313 	.sec = (char *)sec_pfx,						    \
9314 	.prog_type = BPF_PROG_TYPE_##ptype,				    \
9315 	.expected_attach_type = atype,					    \
9316 	.cookie = (long)(flags),					    \
9317 	.prog_prepare_load_fn = libbpf_prepare_prog_load,		    \
9318 	__VA_ARGS__							    \
9319 }
9320 
9321 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9322 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9323 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9324 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9325 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9326 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9327 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9328 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9329 static int attach_kprobe_session(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9330 static int attach_uprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9331 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9332 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9333 
9334 static const struct bpf_sec_def section_defs[] = {
9335 	SEC_DEF("socket",		SOCKET_FILTER, 0, SEC_NONE),
9336 	SEC_DEF("sk_reuseport/migrate",	SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT_OR_MIGRATE, SEC_ATTACHABLE),
9337 	SEC_DEF("sk_reuseport",		SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT, SEC_ATTACHABLE),
9338 	SEC_DEF("kprobe+",		KPROBE,	0, SEC_NONE, attach_kprobe),
9339 	SEC_DEF("uprobe+",		KPROBE,	0, SEC_NONE, attach_uprobe),
9340 	SEC_DEF("uprobe.s+",		KPROBE,	0, SEC_SLEEPABLE, attach_uprobe),
9341 	SEC_DEF("kretprobe+",		KPROBE, 0, SEC_NONE, attach_kprobe),
9342 	SEC_DEF("uretprobe+",		KPROBE, 0, SEC_NONE, attach_uprobe),
9343 	SEC_DEF("uretprobe.s+",		KPROBE, 0, SEC_SLEEPABLE, attach_uprobe),
9344 	SEC_DEF("kprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
9345 	SEC_DEF("kretprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
9346 	SEC_DEF("kprobe.session+",	KPROBE,	BPF_TRACE_KPROBE_SESSION, SEC_NONE, attach_kprobe_session),
9347 	SEC_DEF("uprobe.multi+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_NONE, attach_uprobe_multi),
9348 	SEC_DEF("uretprobe.multi+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_NONE, attach_uprobe_multi),
9349 	SEC_DEF("uprobe.multi.s+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_SLEEPABLE, attach_uprobe_multi),
9350 	SEC_DEF("uretprobe.multi.s+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_SLEEPABLE, attach_uprobe_multi),
9351 	SEC_DEF("ksyscall+",		KPROBE,	0, SEC_NONE, attach_ksyscall),
9352 	SEC_DEF("kretsyscall+",		KPROBE, 0, SEC_NONE, attach_ksyscall),
9353 	SEC_DEF("usdt+",		KPROBE,	0, SEC_USDT, attach_usdt),
9354 	SEC_DEF("usdt.s+",		KPROBE,	0, SEC_USDT | SEC_SLEEPABLE, attach_usdt),
9355 	SEC_DEF("tc/ingress",		SCHED_CLS, BPF_TCX_INGRESS, SEC_NONE), /* alias for tcx */
9356 	SEC_DEF("tc/egress",		SCHED_CLS, BPF_TCX_EGRESS, SEC_NONE),  /* alias for tcx */
9357 	SEC_DEF("tcx/ingress",		SCHED_CLS, BPF_TCX_INGRESS, SEC_NONE),
9358 	SEC_DEF("tcx/egress",		SCHED_CLS, BPF_TCX_EGRESS, SEC_NONE),
9359 	SEC_DEF("tc",			SCHED_CLS, 0, SEC_NONE), /* deprecated / legacy, use tcx */
9360 	SEC_DEF("classifier",		SCHED_CLS, 0, SEC_NONE), /* deprecated / legacy, use tcx */
9361 	SEC_DEF("action",		SCHED_ACT, 0, SEC_NONE), /* deprecated / legacy, use tcx */
9362 	SEC_DEF("netkit/primary",	SCHED_CLS, BPF_NETKIT_PRIMARY, SEC_NONE),
9363 	SEC_DEF("netkit/peer",		SCHED_CLS, BPF_NETKIT_PEER, SEC_NONE),
9364 	SEC_DEF("tracepoint+",		TRACEPOINT, 0, SEC_NONE, attach_tp),
9365 	SEC_DEF("tp+",			TRACEPOINT, 0, SEC_NONE, attach_tp),
9366 	SEC_DEF("raw_tracepoint+",	RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
9367 	SEC_DEF("raw_tp+",		RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
9368 	SEC_DEF("raw_tracepoint.w+",	RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
9369 	SEC_DEF("raw_tp.w+",		RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
9370 	SEC_DEF("tp_btf+",		TRACING, BPF_TRACE_RAW_TP, SEC_ATTACH_BTF, attach_trace),
9371 	SEC_DEF("fentry+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF, attach_trace),
9372 	SEC_DEF("fmod_ret+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF, attach_trace),
9373 	SEC_DEF("fexit+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF, attach_trace),
9374 	SEC_DEF("fentry.s+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
9375 	SEC_DEF("fmod_ret.s+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
9376 	SEC_DEF("fexit.s+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
9377 	SEC_DEF("freplace+",		EXT, 0, SEC_ATTACH_BTF, attach_trace),
9378 	SEC_DEF("lsm+",			LSM, BPF_LSM_MAC, SEC_ATTACH_BTF, attach_lsm),
9379 	SEC_DEF("lsm.s+",		LSM, BPF_LSM_MAC, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_lsm),
9380 	SEC_DEF("lsm_cgroup+",		LSM, BPF_LSM_CGROUP, SEC_ATTACH_BTF),
9381 	SEC_DEF("iter+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF, attach_iter),
9382 	SEC_DEF("iter.s+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_iter),
9383 	SEC_DEF("syscall",		SYSCALL, 0, SEC_SLEEPABLE),
9384 	SEC_DEF("xdp.frags/devmap",	XDP, BPF_XDP_DEVMAP, SEC_XDP_FRAGS),
9385 	SEC_DEF("xdp/devmap",		XDP, BPF_XDP_DEVMAP, SEC_ATTACHABLE),
9386 	SEC_DEF("xdp.frags/cpumap",	XDP, BPF_XDP_CPUMAP, SEC_XDP_FRAGS),
9387 	SEC_DEF("xdp/cpumap",		XDP, BPF_XDP_CPUMAP, SEC_ATTACHABLE),
9388 	SEC_DEF("xdp.frags",		XDP, BPF_XDP, SEC_XDP_FRAGS),
9389 	SEC_DEF("xdp",			XDP, BPF_XDP, SEC_ATTACHABLE_OPT),
9390 	SEC_DEF("perf_event",		PERF_EVENT, 0, SEC_NONE),
9391 	SEC_DEF("lwt_in",		LWT_IN, 0, SEC_NONE),
9392 	SEC_DEF("lwt_out",		LWT_OUT, 0, SEC_NONE),
9393 	SEC_DEF("lwt_xmit",		LWT_XMIT, 0, SEC_NONE),
9394 	SEC_DEF("lwt_seg6local",	LWT_SEG6LOCAL, 0, SEC_NONE),
9395 	SEC_DEF("sockops",		SOCK_OPS, BPF_CGROUP_SOCK_OPS, SEC_ATTACHABLE_OPT),
9396 	SEC_DEF("sk_skb/stream_parser",	SK_SKB, BPF_SK_SKB_STREAM_PARSER, SEC_ATTACHABLE_OPT),
9397 	SEC_DEF("sk_skb/stream_verdict",SK_SKB, BPF_SK_SKB_STREAM_VERDICT, SEC_ATTACHABLE_OPT),
9398 	SEC_DEF("sk_skb/verdict",	SK_SKB, BPF_SK_SKB_VERDICT, SEC_ATTACHABLE_OPT),
9399 	SEC_DEF("sk_skb",		SK_SKB, 0, SEC_NONE),
9400 	SEC_DEF("sk_msg",		SK_MSG, BPF_SK_MSG_VERDICT, SEC_ATTACHABLE_OPT),
9401 	SEC_DEF("lirc_mode2",		LIRC_MODE2, BPF_LIRC_MODE2, SEC_ATTACHABLE_OPT),
9402 	SEC_DEF("flow_dissector",	FLOW_DISSECTOR, BPF_FLOW_DISSECTOR, SEC_ATTACHABLE_OPT),
9403 	SEC_DEF("cgroup_skb/ingress",	CGROUP_SKB, BPF_CGROUP_INET_INGRESS, SEC_ATTACHABLE_OPT),
9404 	SEC_DEF("cgroup_skb/egress",	CGROUP_SKB, BPF_CGROUP_INET_EGRESS, SEC_ATTACHABLE_OPT),
9405 	SEC_DEF("cgroup/skb",		CGROUP_SKB, 0, SEC_NONE),
9406 	SEC_DEF("cgroup/sock_create",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE),
9407 	SEC_DEF("cgroup/sock_release",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_RELEASE, SEC_ATTACHABLE),
9408 	SEC_DEF("cgroup/sock",		CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE_OPT),
9409 	SEC_DEF("cgroup/post_bind4",	CGROUP_SOCK, BPF_CGROUP_INET4_POST_BIND, SEC_ATTACHABLE),
9410 	SEC_DEF("cgroup/post_bind6",	CGROUP_SOCK, BPF_CGROUP_INET6_POST_BIND, SEC_ATTACHABLE),
9411 	SEC_DEF("cgroup/bind4",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND, SEC_ATTACHABLE),
9412 	SEC_DEF("cgroup/bind6",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND, SEC_ATTACHABLE),
9413 	SEC_DEF("cgroup/connect4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT, SEC_ATTACHABLE),
9414 	SEC_DEF("cgroup/connect6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT, SEC_ATTACHABLE),
9415 	SEC_DEF("cgroup/connect_unix",	CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_CONNECT, SEC_ATTACHABLE),
9416 	SEC_DEF("cgroup/sendmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG, SEC_ATTACHABLE),
9417 	SEC_DEF("cgroup/sendmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG, SEC_ATTACHABLE),
9418 	SEC_DEF("cgroup/sendmsg_unix",	CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_SENDMSG, SEC_ATTACHABLE),
9419 	SEC_DEF("cgroup/recvmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_RECVMSG, SEC_ATTACHABLE),
9420 	SEC_DEF("cgroup/recvmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_RECVMSG, SEC_ATTACHABLE),
9421 	SEC_DEF("cgroup/recvmsg_unix",	CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_RECVMSG, SEC_ATTACHABLE),
9422 	SEC_DEF("cgroup/getpeername4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETPEERNAME, SEC_ATTACHABLE),
9423 	SEC_DEF("cgroup/getpeername6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETPEERNAME, SEC_ATTACHABLE),
9424 	SEC_DEF("cgroup/getpeername_unix", CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_GETPEERNAME, SEC_ATTACHABLE),
9425 	SEC_DEF("cgroup/getsockname4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETSOCKNAME, SEC_ATTACHABLE),
9426 	SEC_DEF("cgroup/getsockname6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETSOCKNAME, SEC_ATTACHABLE),
9427 	SEC_DEF("cgroup/getsockname_unix", CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_GETSOCKNAME, SEC_ATTACHABLE),
9428 	SEC_DEF("cgroup/sysctl",	CGROUP_SYSCTL, BPF_CGROUP_SYSCTL, SEC_ATTACHABLE),
9429 	SEC_DEF("cgroup/getsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_GETSOCKOPT, SEC_ATTACHABLE),
9430 	SEC_DEF("cgroup/setsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_SETSOCKOPT, SEC_ATTACHABLE),
9431 	SEC_DEF("cgroup/dev",		CGROUP_DEVICE, BPF_CGROUP_DEVICE, SEC_ATTACHABLE_OPT),
9432 	SEC_DEF("struct_ops+",		STRUCT_OPS, 0, SEC_NONE),
9433 	SEC_DEF("struct_ops.s+",	STRUCT_OPS, 0, SEC_SLEEPABLE),
9434 	SEC_DEF("sk_lookup",		SK_LOOKUP, BPF_SK_LOOKUP, SEC_ATTACHABLE),
9435 	SEC_DEF("netfilter",		NETFILTER, BPF_NETFILTER, SEC_NONE),
9436 };
9437 
9438 int libbpf_register_prog_handler(const char *sec,
9439 				 enum bpf_prog_type prog_type,
9440 				 enum bpf_attach_type exp_attach_type,
9441 				 const struct libbpf_prog_handler_opts *opts)
9442 {
9443 	struct bpf_sec_def *sec_def;
9444 
9445 	if (!OPTS_VALID(opts, libbpf_prog_handler_opts))
9446 		return libbpf_err(-EINVAL);
9447 
9448 	if (last_custom_sec_def_handler_id == INT_MAX) /* prevent overflow */
9449 		return libbpf_err(-E2BIG);
9450 
9451 	if (sec) {
9452 		sec_def = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt + 1,
9453 					      sizeof(*sec_def));
9454 		if (!sec_def)
9455 			return libbpf_err(-ENOMEM);
9456 
9457 		custom_sec_defs = sec_def;
9458 		sec_def = &custom_sec_defs[custom_sec_def_cnt];
9459 	} else {
9460 		if (has_custom_fallback_def)
9461 			return libbpf_err(-EBUSY);
9462 
9463 		sec_def = &custom_fallback_def;
9464 	}
9465 
9466 	sec_def->sec = sec ? strdup(sec) : NULL;
9467 	if (sec && !sec_def->sec)
9468 		return libbpf_err(-ENOMEM);
9469 
9470 	sec_def->prog_type = prog_type;
9471 	sec_def->expected_attach_type = exp_attach_type;
9472 	sec_def->cookie = OPTS_GET(opts, cookie, 0);
9473 
9474 	sec_def->prog_setup_fn = OPTS_GET(opts, prog_setup_fn, NULL);
9475 	sec_def->prog_prepare_load_fn = OPTS_GET(opts, prog_prepare_load_fn, NULL);
9476 	sec_def->prog_attach_fn = OPTS_GET(opts, prog_attach_fn, NULL);
9477 
9478 	sec_def->handler_id = ++last_custom_sec_def_handler_id;
9479 
9480 	if (sec)
9481 		custom_sec_def_cnt++;
9482 	else
9483 		has_custom_fallback_def = true;
9484 
9485 	return sec_def->handler_id;
9486 }
9487 
9488 int libbpf_unregister_prog_handler(int handler_id)
9489 {
9490 	struct bpf_sec_def *sec_defs;
9491 	int i;
9492 
9493 	if (handler_id <= 0)
9494 		return libbpf_err(-EINVAL);
9495 
9496 	if (has_custom_fallback_def && custom_fallback_def.handler_id == handler_id) {
9497 		memset(&custom_fallback_def, 0, sizeof(custom_fallback_def));
9498 		has_custom_fallback_def = false;
9499 		return 0;
9500 	}
9501 
9502 	for (i = 0; i < custom_sec_def_cnt; i++) {
9503 		if (custom_sec_defs[i].handler_id == handler_id)
9504 			break;
9505 	}
9506 
9507 	if (i == custom_sec_def_cnt)
9508 		return libbpf_err(-ENOENT);
9509 
9510 	free(custom_sec_defs[i].sec);
9511 	for (i = i + 1; i < custom_sec_def_cnt; i++)
9512 		custom_sec_defs[i - 1] = custom_sec_defs[i];
9513 	custom_sec_def_cnt--;
9514 
9515 	/* try to shrink the array, but it's ok if we couldn't */
9516 	sec_defs = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt, sizeof(*sec_defs));
9517 	/* if new count is zero, reallocarray can return a valid NULL result;
9518 	 * in this case the previous pointer will be freed, so we *have to*
9519 	 * reassign old pointer to the new value (even if it's NULL)
9520 	 */
9521 	if (sec_defs || custom_sec_def_cnt == 0)
9522 		custom_sec_defs = sec_defs;
9523 
9524 	return 0;
9525 }
9526 
9527 static bool sec_def_matches(const struct bpf_sec_def *sec_def, const char *sec_name)
9528 {
9529 	size_t len = strlen(sec_def->sec);
9530 
9531 	/* "type/" always has to have proper SEC("type/extras") form */
9532 	if (sec_def->sec[len - 1] == '/') {
9533 		if (str_has_pfx(sec_name, sec_def->sec))
9534 			return true;
9535 		return false;
9536 	}
9537 
9538 	/* "type+" means it can be either exact SEC("type") or
9539 	 * well-formed SEC("type/extras") with proper '/' separator
9540 	 */
9541 	if (sec_def->sec[len - 1] == '+') {
9542 		len--;
9543 		/* not even a prefix */
9544 		if (strncmp(sec_name, sec_def->sec, len) != 0)
9545 			return false;
9546 		/* exact match or has '/' separator */
9547 		if (sec_name[len] == '\0' || sec_name[len] == '/')
9548 			return true;
9549 		return false;
9550 	}
9551 
9552 	return strcmp(sec_name, sec_def->sec) == 0;
9553 }
9554 
9555 static const struct bpf_sec_def *find_sec_def(const char *sec_name)
9556 {
9557 	const struct bpf_sec_def *sec_def;
9558 	int i, n;
9559 
9560 	n = custom_sec_def_cnt;
9561 	for (i = 0; i < n; i++) {
9562 		sec_def = &custom_sec_defs[i];
9563 		if (sec_def_matches(sec_def, sec_name))
9564 			return sec_def;
9565 	}
9566 
9567 	n = ARRAY_SIZE(section_defs);
9568 	for (i = 0; i < n; i++) {
9569 		sec_def = &section_defs[i];
9570 		if (sec_def_matches(sec_def, sec_name))
9571 			return sec_def;
9572 	}
9573 
9574 	if (has_custom_fallback_def)
9575 		return &custom_fallback_def;
9576 
9577 	return NULL;
9578 }
9579 
9580 #define MAX_TYPE_NAME_SIZE 32
9581 
9582 static char *libbpf_get_type_names(bool attach_type)
9583 {
9584 	int i, len = ARRAY_SIZE(section_defs) * MAX_TYPE_NAME_SIZE;
9585 	char *buf;
9586 
9587 	buf = malloc(len);
9588 	if (!buf)
9589 		return NULL;
9590 
9591 	buf[0] = '\0';
9592 	/* Forge string buf with all available names */
9593 	for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
9594 		const struct bpf_sec_def *sec_def = &section_defs[i];
9595 
9596 		if (attach_type) {
9597 			if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
9598 				continue;
9599 
9600 			if (!(sec_def->cookie & SEC_ATTACHABLE))
9601 				continue;
9602 		}
9603 
9604 		if (strlen(buf) + strlen(section_defs[i].sec) + 2 > len) {
9605 			free(buf);
9606 			return NULL;
9607 		}
9608 		strcat(buf, " ");
9609 		strcat(buf, section_defs[i].sec);
9610 	}
9611 
9612 	return buf;
9613 }
9614 
9615 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
9616 			     enum bpf_attach_type *expected_attach_type)
9617 {
9618 	const struct bpf_sec_def *sec_def;
9619 	char *type_names;
9620 
9621 	if (!name)
9622 		return libbpf_err(-EINVAL);
9623 
9624 	sec_def = find_sec_def(name);
9625 	if (sec_def) {
9626 		*prog_type = sec_def->prog_type;
9627 		*expected_attach_type = sec_def->expected_attach_type;
9628 		return 0;
9629 	}
9630 
9631 	pr_debug("failed to guess program type from ELF section '%s'\n", name);
9632 	type_names = libbpf_get_type_names(false);
9633 	if (type_names != NULL) {
9634 		pr_debug("supported section(type) names are:%s\n", type_names);
9635 		free(type_names);
9636 	}
9637 
9638 	return libbpf_err(-ESRCH);
9639 }
9640 
9641 const char *libbpf_bpf_attach_type_str(enum bpf_attach_type t)
9642 {
9643 	if (t < 0 || t >= ARRAY_SIZE(attach_type_name))
9644 		return NULL;
9645 
9646 	return attach_type_name[t];
9647 }
9648 
9649 const char *libbpf_bpf_link_type_str(enum bpf_link_type t)
9650 {
9651 	if (t < 0 || t >= ARRAY_SIZE(link_type_name))
9652 		return NULL;
9653 
9654 	return link_type_name[t];
9655 }
9656 
9657 const char *libbpf_bpf_map_type_str(enum bpf_map_type t)
9658 {
9659 	if (t < 0 || t >= ARRAY_SIZE(map_type_name))
9660 		return NULL;
9661 
9662 	return map_type_name[t];
9663 }
9664 
9665 const char *libbpf_bpf_prog_type_str(enum bpf_prog_type t)
9666 {
9667 	if (t < 0 || t >= ARRAY_SIZE(prog_type_name))
9668 		return NULL;
9669 
9670 	return prog_type_name[t];
9671 }
9672 
9673 static struct bpf_map *find_struct_ops_map_by_offset(struct bpf_object *obj,
9674 						     int sec_idx,
9675 						     size_t offset)
9676 {
9677 	struct bpf_map *map;
9678 	size_t i;
9679 
9680 	for (i = 0; i < obj->nr_maps; i++) {
9681 		map = &obj->maps[i];
9682 		if (!bpf_map__is_struct_ops(map))
9683 			continue;
9684 		if (map->sec_idx == sec_idx &&
9685 		    map->sec_offset <= offset &&
9686 		    offset - map->sec_offset < map->def.value_size)
9687 			return map;
9688 	}
9689 
9690 	return NULL;
9691 }
9692 
9693 /* Collect the reloc from ELF, populate the st_ops->progs[], and update
9694  * st_ops->data for shadow type.
9695  */
9696 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
9697 					    Elf64_Shdr *shdr, Elf_Data *data)
9698 {
9699 	const struct btf_member *member;
9700 	struct bpf_struct_ops *st_ops;
9701 	struct bpf_program *prog;
9702 	unsigned int shdr_idx;
9703 	const struct btf *btf;
9704 	struct bpf_map *map;
9705 	unsigned int moff, insn_idx;
9706 	const char *name;
9707 	__u32 member_idx;
9708 	Elf64_Sym *sym;
9709 	Elf64_Rel *rel;
9710 	int i, nrels;
9711 
9712 	btf = obj->btf;
9713 	nrels = shdr->sh_size / shdr->sh_entsize;
9714 	for (i = 0; i < nrels; i++) {
9715 		rel = elf_rel_by_idx(data, i);
9716 		if (!rel) {
9717 			pr_warn("struct_ops reloc: failed to get %d reloc\n", i);
9718 			return -LIBBPF_ERRNO__FORMAT;
9719 		}
9720 
9721 		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
9722 		if (!sym) {
9723 			pr_warn("struct_ops reloc: symbol %zx not found\n",
9724 				(size_t)ELF64_R_SYM(rel->r_info));
9725 			return -LIBBPF_ERRNO__FORMAT;
9726 		}
9727 
9728 		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
9729 		map = find_struct_ops_map_by_offset(obj, shdr->sh_info, rel->r_offset);
9730 		if (!map) {
9731 			pr_warn("struct_ops reloc: cannot find map at rel->r_offset %zu\n",
9732 				(size_t)rel->r_offset);
9733 			return -EINVAL;
9734 		}
9735 
9736 		moff = rel->r_offset - map->sec_offset;
9737 		shdr_idx = sym->st_shndx;
9738 		st_ops = map->st_ops;
9739 		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",
9740 			 map->name,
9741 			 (long long)(rel->r_info >> 32),
9742 			 (long long)sym->st_value,
9743 			 shdr_idx, (size_t)rel->r_offset,
9744 			 map->sec_offset, sym->st_name, name);
9745 
9746 		if (shdr_idx >= SHN_LORESERVE) {
9747 			pr_warn("struct_ops reloc %s: rel->r_offset %zu shdr_idx %u unsupported non-static function\n",
9748 				map->name, (size_t)rel->r_offset, shdr_idx);
9749 			return -LIBBPF_ERRNO__RELOC;
9750 		}
9751 		if (sym->st_value % BPF_INSN_SZ) {
9752 			pr_warn("struct_ops reloc %s: invalid target program offset %llu\n",
9753 				map->name, (unsigned long long)sym->st_value);
9754 			return -LIBBPF_ERRNO__FORMAT;
9755 		}
9756 		insn_idx = sym->st_value / BPF_INSN_SZ;
9757 
9758 		member = find_member_by_offset(st_ops->type, moff * 8);
9759 		if (!member) {
9760 			pr_warn("struct_ops reloc %s: cannot find member at moff %u\n",
9761 				map->name, moff);
9762 			return -EINVAL;
9763 		}
9764 		member_idx = member - btf_members(st_ops->type);
9765 		name = btf__name_by_offset(btf, member->name_off);
9766 
9767 		if (!resolve_func_ptr(btf, member->type, NULL)) {
9768 			pr_warn("struct_ops reloc %s: cannot relocate non func ptr %s\n",
9769 				map->name, name);
9770 			return -EINVAL;
9771 		}
9772 
9773 		prog = find_prog_by_sec_insn(obj, shdr_idx, insn_idx);
9774 		if (!prog) {
9775 			pr_warn("struct_ops reloc %s: cannot find prog at shdr_idx %u to relocate func ptr %s\n",
9776 				map->name, shdr_idx, name);
9777 			return -EINVAL;
9778 		}
9779 
9780 		/* prevent the use of BPF prog with invalid type */
9781 		if (prog->type != BPF_PROG_TYPE_STRUCT_OPS) {
9782 			pr_warn("struct_ops reloc %s: prog %s is not struct_ops BPF program\n",
9783 				map->name, prog->name);
9784 			return -EINVAL;
9785 		}
9786 
9787 		st_ops->progs[member_idx] = prog;
9788 
9789 		/* st_ops->data will be exposed to users, being returned by
9790 		 * bpf_map__initial_value() as a pointer to the shadow
9791 		 * type. All function pointers in the original struct type
9792 		 * should be converted to a pointer to struct bpf_program
9793 		 * in the shadow type.
9794 		 */
9795 		*((struct bpf_program **)(st_ops->data + moff)) = prog;
9796 	}
9797 
9798 	return 0;
9799 }
9800 
9801 #define BTF_TRACE_PREFIX "btf_trace_"
9802 #define BTF_LSM_PREFIX "bpf_lsm_"
9803 #define BTF_ITER_PREFIX "bpf_iter_"
9804 #define BTF_MAX_NAME_SIZE 128
9805 
9806 void btf_get_kernel_prefix_kind(enum bpf_attach_type attach_type,
9807 				const char **prefix, int *kind)
9808 {
9809 	switch (attach_type) {
9810 	case BPF_TRACE_RAW_TP:
9811 		*prefix = BTF_TRACE_PREFIX;
9812 		*kind = BTF_KIND_TYPEDEF;
9813 		break;
9814 	case BPF_LSM_MAC:
9815 	case BPF_LSM_CGROUP:
9816 		*prefix = BTF_LSM_PREFIX;
9817 		*kind = BTF_KIND_FUNC;
9818 		break;
9819 	case BPF_TRACE_ITER:
9820 		*prefix = BTF_ITER_PREFIX;
9821 		*kind = BTF_KIND_FUNC;
9822 		break;
9823 	default:
9824 		*prefix = "";
9825 		*kind = BTF_KIND_FUNC;
9826 	}
9827 }
9828 
9829 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
9830 				   const char *name, __u32 kind)
9831 {
9832 	char btf_type_name[BTF_MAX_NAME_SIZE];
9833 	int ret;
9834 
9835 	ret = snprintf(btf_type_name, sizeof(btf_type_name),
9836 		       "%s%s", prefix, name);
9837 	/* snprintf returns the number of characters written excluding the
9838 	 * terminating null. So, if >= BTF_MAX_NAME_SIZE are written, it
9839 	 * indicates truncation.
9840 	 */
9841 	if (ret < 0 || ret >= sizeof(btf_type_name))
9842 		return -ENAMETOOLONG;
9843 	return btf__find_by_name_kind(btf, btf_type_name, kind);
9844 }
9845 
9846 static inline int find_attach_btf_id(struct btf *btf, const char *name,
9847 				     enum bpf_attach_type attach_type)
9848 {
9849 	const char *prefix;
9850 	int kind;
9851 
9852 	btf_get_kernel_prefix_kind(attach_type, &prefix, &kind);
9853 	return find_btf_by_prefix_kind(btf, prefix, name, kind);
9854 }
9855 
9856 int libbpf_find_vmlinux_btf_id(const char *name,
9857 			       enum bpf_attach_type attach_type)
9858 {
9859 	struct btf *btf;
9860 	int err;
9861 
9862 	btf = btf__load_vmlinux_btf();
9863 	err = libbpf_get_error(btf);
9864 	if (err) {
9865 		pr_warn("vmlinux BTF is not found\n");
9866 		return libbpf_err(err);
9867 	}
9868 
9869 	err = find_attach_btf_id(btf, name, attach_type);
9870 	if (err <= 0)
9871 		pr_warn("%s is not found in vmlinux BTF\n", name);
9872 
9873 	btf__free(btf);
9874 	return libbpf_err(err);
9875 }
9876 
9877 static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd)
9878 {
9879 	struct bpf_prog_info info;
9880 	__u32 info_len = sizeof(info);
9881 	struct btf *btf;
9882 	int err;
9883 
9884 	memset(&info, 0, info_len);
9885 	err = bpf_prog_get_info_by_fd(attach_prog_fd, &info, &info_len);
9886 	if (err) {
9887 		pr_warn("failed bpf_prog_get_info_by_fd for FD %d: %d\n",
9888 			attach_prog_fd, err);
9889 		return err;
9890 	}
9891 
9892 	err = -EINVAL;
9893 	if (!info.btf_id) {
9894 		pr_warn("The target program doesn't have BTF\n");
9895 		goto out;
9896 	}
9897 	btf = btf__load_from_kernel_by_id(info.btf_id);
9898 	err = libbpf_get_error(btf);
9899 	if (err) {
9900 		pr_warn("Failed to get BTF %d of the program: %d\n", info.btf_id, err);
9901 		goto out;
9902 	}
9903 	err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
9904 	btf__free(btf);
9905 	if (err <= 0) {
9906 		pr_warn("%s is not found in prog's BTF\n", name);
9907 		goto out;
9908 	}
9909 out:
9910 	return err;
9911 }
9912 
9913 static int find_kernel_btf_id(struct bpf_object *obj, const char *attach_name,
9914 			      enum bpf_attach_type attach_type,
9915 			      int *btf_obj_fd, int *btf_type_id)
9916 {
9917 	int ret, i, mod_len;
9918 	const char *fn_name, *mod_name = NULL;
9919 
9920 	fn_name = strchr(attach_name, ':');
9921 	if (fn_name) {
9922 		mod_name = attach_name;
9923 		mod_len = fn_name - mod_name;
9924 		fn_name++;
9925 	}
9926 
9927 	if (!mod_name || strncmp(mod_name, "vmlinux", mod_len) == 0) {
9928 		ret = find_attach_btf_id(obj->btf_vmlinux,
9929 					 mod_name ? fn_name : attach_name,
9930 					 attach_type);
9931 		if (ret > 0) {
9932 			*btf_obj_fd = 0; /* vmlinux BTF */
9933 			*btf_type_id = ret;
9934 			return 0;
9935 		}
9936 		if (ret != -ENOENT)
9937 			return ret;
9938 	}
9939 
9940 	ret = load_module_btfs(obj);
9941 	if (ret)
9942 		return ret;
9943 
9944 	for (i = 0; i < obj->btf_module_cnt; i++) {
9945 		const struct module_btf *mod = &obj->btf_modules[i];
9946 
9947 		if (mod_name && strncmp(mod->name, mod_name, mod_len) != 0)
9948 			continue;
9949 
9950 		ret = find_attach_btf_id(mod->btf,
9951 					 mod_name ? fn_name : attach_name,
9952 					 attach_type);
9953 		if (ret > 0) {
9954 			*btf_obj_fd = mod->fd;
9955 			*btf_type_id = ret;
9956 			return 0;
9957 		}
9958 		if (ret == -ENOENT)
9959 			continue;
9960 
9961 		return ret;
9962 	}
9963 
9964 	return -ESRCH;
9965 }
9966 
9967 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
9968 				     int *btf_obj_fd, int *btf_type_id)
9969 {
9970 	enum bpf_attach_type attach_type = prog->expected_attach_type;
9971 	__u32 attach_prog_fd = prog->attach_prog_fd;
9972 	int err = 0;
9973 
9974 	/* BPF program's BTF ID */
9975 	if (prog->type == BPF_PROG_TYPE_EXT || attach_prog_fd) {
9976 		if (!attach_prog_fd) {
9977 			pr_warn("prog '%s': attach program FD is not set\n", prog->name);
9978 			return -EINVAL;
9979 		}
9980 		err = libbpf_find_prog_btf_id(attach_name, attach_prog_fd);
9981 		if (err < 0) {
9982 			pr_warn("prog '%s': failed to find BPF program (FD %d) BTF ID for '%s': %d\n",
9983 				 prog->name, attach_prog_fd, attach_name, err);
9984 			return err;
9985 		}
9986 		*btf_obj_fd = 0;
9987 		*btf_type_id = err;
9988 		return 0;
9989 	}
9990 
9991 	/* kernel/module BTF ID */
9992 	if (prog->obj->gen_loader) {
9993 		bpf_gen__record_attach_target(prog->obj->gen_loader, attach_name, attach_type);
9994 		*btf_obj_fd = 0;
9995 		*btf_type_id = 1;
9996 	} else {
9997 		err = find_kernel_btf_id(prog->obj, attach_name,
9998 					 attach_type, btf_obj_fd,
9999 					 btf_type_id);
10000 	}
10001 	if (err) {
10002 		pr_warn("prog '%s': failed to find kernel BTF type ID of '%s': %d\n",
10003 			prog->name, attach_name, err);
10004 		return err;
10005 	}
10006 	return 0;
10007 }
10008 
10009 int libbpf_attach_type_by_name(const char *name,
10010 			       enum bpf_attach_type *attach_type)
10011 {
10012 	char *type_names;
10013 	const struct bpf_sec_def *sec_def;
10014 
10015 	if (!name)
10016 		return libbpf_err(-EINVAL);
10017 
10018 	sec_def = find_sec_def(name);
10019 	if (!sec_def) {
10020 		pr_debug("failed to guess attach type based on ELF section name '%s'\n", name);
10021 		type_names = libbpf_get_type_names(true);
10022 		if (type_names != NULL) {
10023 			pr_debug("attachable section(type) names are:%s\n", type_names);
10024 			free(type_names);
10025 		}
10026 
10027 		return libbpf_err(-EINVAL);
10028 	}
10029 
10030 	if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
10031 		return libbpf_err(-EINVAL);
10032 	if (!(sec_def->cookie & SEC_ATTACHABLE))
10033 		return libbpf_err(-EINVAL);
10034 
10035 	*attach_type = sec_def->expected_attach_type;
10036 	return 0;
10037 }
10038 
10039 int bpf_map__fd(const struct bpf_map *map)
10040 {
10041 	if (!map)
10042 		return libbpf_err(-EINVAL);
10043 	if (!map_is_created(map))
10044 		return -1;
10045 	return map->fd;
10046 }
10047 
10048 static bool map_uses_real_name(const struct bpf_map *map)
10049 {
10050 	/* Since libbpf started to support custom .data.* and .rodata.* maps,
10051 	 * their user-visible name differs from kernel-visible name. Users see
10052 	 * such map's corresponding ELF section name as a map name.
10053 	 * This check distinguishes .data/.rodata from .data.* and .rodata.*
10054 	 * maps to know which name has to be returned to the user.
10055 	 */
10056 	if (map->libbpf_type == LIBBPF_MAP_DATA && strcmp(map->real_name, DATA_SEC) != 0)
10057 		return true;
10058 	if (map->libbpf_type == LIBBPF_MAP_RODATA && strcmp(map->real_name, RODATA_SEC) != 0)
10059 		return true;
10060 	return false;
10061 }
10062 
10063 const char *bpf_map__name(const struct bpf_map *map)
10064 {
10065 	if (!map)
10066 		return NULL;
10067 
10068 	if (map_uses_real_name(map))
10069 		return map->real_name;
10070 
10071 	return map->name;
10072 }
10073 
10074 enum bpf_map_type bpf_map__type(const struct bpf_map *map)
10075 {
10076 	return map->def.type;
10077 }
10078 
10079 int bpf_map__set_type(struct bpf_map *map, enum bpf_map_type type)
10080 {
10081 	if (map_is_created(map))
10082 		return libbpf_err(-EBUSY);
10083 	map->def.type = type;
10084 	return 0;
10085 }
10086 
10087 __u32 bpf_map__map_flags(const struct bpf_map *map)
10088 {
10089 	return map->def.map_flags;
10090 }
10091 
10092 int bpf_map__set_map_flags(struct bpf_map *map, __u32 flags)
10093 {
10094 	if (map_is_created(map))
10095 		return libbpf_err(-EBUSY);
10096 	map->def.map_flags = flags;
10097 	return 0;
10098 }
10099 
10100 __u64 bpf_map__map_extra(const struct bpf_map *map)
10101 {
10102 	return map->map_extra;
10103 }
10104 
10105 int bpf_map__set_map_extra(struct bpf_map *map, __u64 map_extra)
10106 {
10107 	if (map_is_created(map))
10108 		return libbpf_err(-EBUSY);
10109 	map->map_extra = map_extra;
10110 	return 0;
10111 }
10112 
10113 __u32 bpf_map__numa_node(const struct bpf_map *map)
10114 {
10115 	return map->numa_node;
10116 }
10117 
10118 int bpf_map__set_numa_node(struct bpf_map *map, __u32 numa_node)
10119 {
10120 	if (map_is_created(map))
10121 		return libbpf_err(-EBUSY);
10122 	map->numa_node = numa_node;
10123 	return 0;
10124 }
10125 
10126 __u32 bpf_map__key_size(const struct bpf_map *map)
10127 {
10128 	return map->def.key_size;
10129 }
10130 
10131 int bpf_map__set_key_size(struct bpf_map *map, __u32 size)
10132 {
10133 	if (map_is_created(map))
10134 		return libbpf_err(-EBUSY);
10135 	map->def.key_size = size;
10136 	return 0;
10137 }
10138 
10139 __u32 bpf_map__value_size(const struct bpf_map *map)
10140 {
10141 	return map->def.value_size;
10142 }
10143 
10144 static int map_btf_datasec_resize(struct bpf_map *map, __u32 size)
10145 {
10146 	struct btf *btf;
10147 	struct btf_type *datasec_type, *var_type;
10148 	struct btf_var_secinfo *var;
10149 	const struct btf_type *array_type;
10150 	const struct btf_array *array;
10151 	int vlen, element_sz, new_array_id;
10152 	__u32 nr_elements;
10153 
10154 	/* check btf existence */
10155 	btf = bpf_object__btf(map->obj);
10156 	if (!btf)
10157 		return -ENOENT;
10158 
10159 	/* verify map is datasec */
10160 	datasec_type = btf_type_by_id(btf, bpf_map__btf_value_type_id(map));
10161 	if (!btf_is_datasec(datasec_type)) {
10162 		pr_warn("map '%s': cannot be resized, map value type is not a datasec\n",
10163 			bpf_map__name(map));
10164 		return -EINVAL;
10165 	}
10166 
10167 	/* verify datasec has at least one var */
10168 	vlen = btf_vlen(datasec_type);
10169 	if (vlen == 0) {
10170 		pr_warn("map '%s': cannot be resized, map value datasec is empty\n",
10171 			bpf_map__name(map));
10172 		return -EINVAL;
10173 	}
10174 
10175 	/* verify last var in the datasec is an array */
10176 	var = &btf_var_secinfos(datasec_type)[vlen - 1];
10177 	var_type = btf_type_by_id(btf, var->type);
10178 	array_type = skip_mods_and_typedefs(btf, var_type->type, NULL);
10179 	if (!btf_is_array(array_type)) {
10180 		pr_warn("map '%s': cannot be resized, last var must be an array\n",
10181 			bpf_map__name(map));
10182 		return -EINVAL;
10183 	}
10184 
10185 	/* verify request size aligns with array */
10186 	array = btf_array(array_type);
10187 	element_sz = btf__resolve_size(btf, array->type);
10188 	if (element_sz <= 0 || (size - var->offset) % element_sz != 0) {
10189 		pr_warn("map '%s': cannot be resized, element size (%d) doesn't align with new total size (%u)\n",
10190 			bpf_map__name(map), element_sz, size);
10191 		return -EINVAL;
10192 	}
10193 
10194 	/* create a new array based on the existing array, but with new length */
10195 	nr_elements = (size - var->offset) / element_sz;
10196 	new_array_id = btf__add_array(btf, array->index_type, array->type, nr_elements);
10197 	if (new_array_id < 0)
10198 		return new_array_id;
10199 
10200 	/* adding a new btf type invalidates existing pointers to btf objects,
10201 	 * so refresh pointers before proceeding
10202 	 */
10203 	datasec_type = btf_type_by_id(btf, map->btf_value_type_id);
10204 	var = &btf_var_secinfos(datasec_type)[vlen - 1];
10205 	var_type = btf_type_by_id(btf, var->type);
10206 
10207 	/* finally update btf info */
10208 	datasec_type->size = size;
10209 	var->size = size - var->offset;
10210 	var_type->type = new_array_id;
10211 
10212 	return 0;
10213 }
10214 
10215 int bpf_map__set_value_size(struct bpf_map *map, __u32 size)
10216 {
10217 	if (map->obj->loaded || map->reused)
10218 		return libbpf_err(-EBUSY);
10219 
10220 	if (map->mmaped) {
10221 		size_t mmap_old_sz, mmap_new_sz;
10222 		int err;
10223 
10224 		if (map->def.type != BPF_MAP_TYPE_ARRAY)
10225 			return -EOPNOTSUPP;
10226 
10227 		mmap_old_sz = bpf_map_mmap_sz(map);
10228 		mmap_new_sz = array_map_mmap_sz(size, map->def.max_entries);
10229 		err = bpf_map_mmap_resize(map, mmap_old_sz, mmap_new_sz);
10230 		if (err) {
10231 			pr_warn("map '%s': failed to resize memory-mapped region: %d\n",
10232 				bpf_map__name(map), err);
10233 			return err;
10234 		}
10235 		err = map_btf_datasec_resize(map, size);
10236 		if (err && err != -ENOENT) {
10237 			pr_warn("map '%s': failed to adjust resized BTF, clearing BTF key/value info: %d\n",
10238 				bpf_map__name(map), err);
10239 			map->btf_value_type_id = 0;
10240 			map->btf_key_type_id = 0;
10241 		}
10242 	}
10243 
10244 	map->def.value_size = size;
10245 	return 0;
10246 }
10247 
10248 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
10249 {
10250 	return map ? map->btf_key_type_id : 0;
10251 }
10252 
10253 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
10254 {
10255 	return map ? map->btf_value_type_id : 0;
10256 }
10257 
10258 int bpf_map__set_initial_value(struct bpf_map *map,
10259 			       const void *data, size_t size)
10260 {
10261 	size_t actual_sz;
10262 
10263 	if (map->obj->loaded || map->reused)
10264 		return libbpf_err(-EBUSY);
10265 
10266 	if (!map->mmaped || map->libbpf_type == LIBBPF_MAP_KCONFIG)
10267 		return libbpf_err(-EINVAL);
10268 
10269 	if (map->def.type == BPF_MAP_TYPE_ARENA)
10270 		actual_sz = map->obj->arena_data_sz;
10271 	else
10272 		actual_sz = map->def.value_size;
10273 	if (size != actual_sz)
10274 		return libbpf_err(-EINVAL);
10275 
10276 	memcpy(map->mmaped, data, size);
10277 	return 0;
10278 }
10279 
10280 void *bpf_map__initial_value(const struct bpf_map *map, size_t *psize)
10281 {
10282 	if (bpf_map__is_struct_ops(map)) {
10283 		if (psize)
10284 			*psize = map->def.value_size;
10285 		return map->st_ops->data;
10286 	}
10287 
10288 	if (!map->mmaped)
10289 		return NULL;
10290 
10291 	if (map->def.type == BPF_MAP_TYPE_ARENA)
10292 		*psize = map->obj->arena_data_sz;
10293 	else
10294 		*psize = map->def.value_size;
10295 
10296 	return map->mmaped;
10297 }
10298 
10299 bool bpf_map__is_internal(const struct bpf_map *map)
10300 {
10301 	return map->libbpf_type != LIBBPF_MAP_UNSPEC;
10302 }
10303 
10304 __u32 bpf_map__ifindex(const struct bpf_map *map)
10305 {
10306 	return map->map_ifindex;
10307 }
10308 
10309 int bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
10310 {
10311 	if (map_is_created(map))
10312 		return libbpf_err(-EBUSY);
10313 	map->map_ifindex = ifindex;
10314 	return 0;
10315 }
10316 
10317 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
10318 {
10319 	if (!bpf_map_type__is_map_in_map(map->def.type)) {
10320 		pr_warn("error: unsupported map type\n");
10321 		return libbpf_err(-EINVAL);
10322 	}
10323 	if (map->inner_map_fd != -1) {
10324 		pr_warn("error: inner_map_fd already specified\n");
10325 		return libbpf_err(-EINVAL);
10326 	}
10327 	if (map->inner_map) {
10328 		bpf_map__destroy(map->inner_map);
10329 		zfree(&map->inner_map);
10330 	}
10331 	map->inner_map_fd = fd;
10332 	return 0;
10333 }
10334 
10335 static struct bpf_map *
10336 __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
10337 {
10338 	ssize_t idx;
10339 	struct bpf_map *s, *e;
10340 
10341 	if (!obj || !obj->maps)
10342 		return errno = EINVAL, NULL;
10343 
10344 	s = obj->maps;
10345 	e = obj->maps + obj->nr_maps;
10346 
10347 	if ((m < s) || (m >= e)) {
10348 		pr_warn("error in %s: map handler doesn't belong to object\n",
10349 			 __func__);
10350 		return errno = EINVAL, NULL;
10351 	}
10352 
10353 	idx = (m - obj->maps) + i;
10354 	if (idx >= obj->nr_maps || idx < 0)
10355 		return NULL;
10356 	return &obj->maps[idx];
10357 }
10358 
10359 struct bpf_map *
10360 bpf_object__next_map(const struct bpf_object *obj, const struct bpf_map *prev)
10361 {
10362 	if (prev == NULL)
10363 		return obj->maps;
10364 
10365 	return __bpf_map__iter(prev, obj, 1);
10366 }
10367 
10368 struct bpf_map *
10369 bpf_object__prev_map(const struct bpf_object *obj, const struct bpf_map *next)
10370 {
10371 	if (next == NULL) {
10372 		if (!obj->nr_maps)
10373 			return NULL;
10374 		return obj->maps + obj->nr_maps - 1;
10375 	}
10376 
10377 	return __bpf_map__iter(next, obj, -1);
10378 }
10379 
10380 struct bpf_map *
10381 bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
10382 {
10383 	struct bpf_map *pos;
10384 
10385 	bpf_object__for_each_map(pos, obj) {
10386 		/* if it's a special internal map name (which always starts
10387 		 * with dot) then check if that special name matches the
10388 		 * real map name (ELF section name)
10389 		 */
10390 		if (name[0] == '.') {
10391 			if (pos->real_name && strcmp(pos->real_name, name) == 0)
10392 				return pos;
10393 			continue;
10394 		}
10395 		/* otherwise map name has to be an exact match */
10396 		if (map_uses_real_name(pos)) {
10397 			if (strcmp(pos->real_name, name) == 0)
10398 				return pos;
10399 			continue;
10400 		}
10401 		if (strcmp(pos->name, name) == 0)
10402 			return pos;
10403 	}
10404 	return errno = ENOENT, NULL;
10405 }
10406 
10407 int
10408 bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
10409 {
10410 	return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
10411 }
10412 
10413 static int validate_map_op(const struct bpf_map *map, size_t key_sz,
10414 			   size_t value_sz, bool check_value_sz)
10415 {
10416 	if (!map_is_created(map)) /* map is not yet created */
10417 		return -ENOENT;
10418 
10419 	if (map->def.key_size != key_sz) {
10420 		pr_warn("map '%s': unexpected key size %zu provided, expected %u\n",
10421 			map->name, key_sz, map->def.key_size);
10422 		return -EINVAL;
10423 	}
10424 
10425 	if (map->fd < 0) {
10426 		pr_warn("map '%s': can't use BPF map without FD (was it created?)\n", map->name);
10427 		return -EINVAL;
10428 	}
10429 
10430 	if (!check_value_sz)
10431 		return 0;
10432 
10433 	switch (map->def.type) {
10434 	case BPF_MAP_TYPE_PERCPU_ARRAY:
10435 	case BPF_MAP_TYPE_PERCPU_HASH:
10436 	case BPF_MAP_TYPE_LRU_PERCPU_HASH:
10437 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: {
10438 		int num_cpu = libbpf_num_possible_cpus();
10439 		size_t elem_sz = roundup(map->def.value_size, 8);
10440 
10441 		if (value_sz != num_cpu * elem_sz) {
10442 			pr_warn("map '%s': unexpected value size %zu provided for per-CPU map, expected %d * %zu = %zd\n",
10443 				map->name, value_sz, num_cpu, elem_sz, num_cpu * elem_sz);
10444 			return -EINVAL;
10445 		}
10446 		break;
10447 	}
10448 	default:
10449 		if (map->def.value_size != value_sz) {
10450 			pr_warn("map '%s': unexpected value size %zu provided, expected %u\n",
10451 				map->name, value_sz, map->def.value_size);
10452 			return -EINVAL;
10453 		}
10454 		break;
10455 	}
10456 	return 0;
10457 }
10458 
10459 int bpf_map__lookup_elem(const struct bpf_map *map,
10460 			 const void *key, size_t key_sz,
10461 			 void *value, size_t value_sz, __u64 flags)
10462 {
10463 	int err;
10464 
10465 	err = validate_map_op(map, key_sz, value_sz, true);
10466 	if (err)
10467 		return libbpf_err(err);
10468 
10469 	return bpf_map_lookup_elem_flags(map->fd, key, value, flags);
10470 }
10471 
10472 int bpf_map__update_elem(const struct bpf_map *map,
10473 			 const void *key, size_t key_sz,
10474 			 const void *value, size_t value_sz, __u64 flags)
10475 {
10476 	int err;
10477 
10478 	err = validate_map_op(map, key_sz, value_sz, true);
10479 	if (err)
10480 		return libbpf_err(err);
10481 
10482 	return bpf_map_update_elem(map->fd, key, value, flags);
10483 }
10484 
10485 int bpf_map__delete_elem(const struct bpf_map *map,
10486 			 const void *key, size_t key_sz, __u64 flags)
10487 {
10488 	int err;
10489 
10490 	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */);
10491 	if (err)
10492 		return libbpf_err(err);
10493 
10494 	return bpf_map_delete_elem_flags(map->fd, key, flags);
10495 }
10496 
10497 int bpf_map__lookup_and_delete_elem(const struct bpf_map *map,
10498 				    const void *key, size_t key_sz,
10499 				    void *value, size_t value_sz, __u64 flags)
10500 {
10501 	int err;
10502 
10503 	err = validate_map_op(map, key_sz, value_sz, true);
10504 	if (err)
10505 		return libbpf_err(err);
10506 
10507 	return bpf_map_lookup_and_delete_elem_flags(map->fd, key, value, flags);
10508 }
10509 
10510 int bpf_map__get_next_key(const struct bpf_map *map,
10511 			  const void *cur_key, void *next_key, size_t key_sz)
10512 {
10513 	int err;
10514 
10515 	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */);
10516 	if (err)
10517 		return libbpf_err(err);
10518 
10519 	return bpf_map_get_next_key(map->fd, cur_key, next_key);
10520 }
10521 
10522 long libbpf_get_error(const void *ptr)
10523 {
10524 	if (!IS_ERR_OR_NULL(ptr))
10525 		return 0;
10526 
10527 	if (IS_ERR(ptr))
10528 		errno = -PTR_ERR(ptr);
10529 
10530 	/* If ptr == NULL, then errno should be already set by the failing
10531 	 * API, because libbpf never returns NULL on success and it now always
10532 	 * sets errno on error. So no extra errno handling for ptr == NULL
10533 	 * case.
10534 	 */
10535 	return -errno;
10536 }
10537 
10538 /* Replace link's underlying BPF program with the new one */
10539 int bpf_link__update_program(struct bpf_link *link, struct bpf_program *prog)
10540 {
10541 	int ret;
10542 	int prog_fd = bpf_program__fd(prog);
10543 
10544 	if (prog_fd < 0) {
10545 		pr_warn("prog '%s': can't use BPF program without FD (was it loaded?)\n",
10546 			prog->name);
10547 		return libbpf_err(-EINVAL);
10548 	}
10549 
10550 	ret = bpf_link_update(bpf_link__fd(link), prog_fd, NULL);
10551 	return libbpf_err_errno(ret);
10552 }
10553 
10554 /* Release "ownership" of underlying BPF resource (typically, BPF program
10555  * attached to some BPF hook, e.g., tracepoint, kprobe, etc). Disconnected
10556  * link, when destructed through bpf_link__destroy() call won't attempt to
10557  * detach/unregisted that BPF resource. This is useful in situations where,
10558  * say, attached BPF program has to outlive userspace program that attached it
10559  * in the system. Depending on type of BPF program, though, there might be
10560  * additional steps (like pinning BPF program in BPF FS) necessary to ensure
10561  * exit of userspace program doesn't trigger automatic detachment and clean up
10562  * inside the kernel.
10563  */
10564 void bpf_link__disconnect(struct bpf_link *link)
10565 {
10566 	link->disconnected = true;
10567 }
10568 
10569 int bpf_link__destroy(struct bpf_link *link)
10570 {
10571 	int err = 0;
10572 
10573 	if (IS_ERR_OR_NULL(link))
10574 		return 0;
10575 
10576 	if (!link->disconnected && link->detach)
10577 		err = link->detach(link);
10578 	if (link->pin_path)
10579 		free(link->pin_path);
10580 	if (link->dealloc)
10581 		link->dealloc(link);
10582 	else
10583 		free(link);
10584 
10585 	return libbpf_err(err);
10586 }
10587 
10588 int bpf_link__fd(const struct bpf_link *link)
10589 {
10590 	return link->fd;
10591 }
10592 
10593 const char *bpf_link__pin_path(const struct bpf_link *link)
10594 {
10595 	return link->pin_path;
10596 }
10597 
10598 static int bpf_link__detach_fd(struct bpf_link *link)
10599 {
10600 	return libbpf_err_errno(close(link->fd));
10601 }
10602 
10603 struct bpf_link *bpf_link__open(const char *path)
10604 {
10605 	struct bpf_link *link;
10606 	int fd;
10607 
10608 	fd = bpf_obj_get(path);
10609 	if (fd < 0) {
10610 		fd = -errno;
10611 		pr_warn("failed to open link at %s: %d\n", path, fd);
10612 		return libbpf_err_ptr(fd);
10613 	}
10614 
10615 	link = calloc(1, sizeof(*link));
10616 	if (!link) {
10617 		close(fd);
10618 		return libbpf_err_ptr(-ENOMEM);
10619 	}
10620 	link->detach = &bpf_link__detach_fd;
10621 	link->fd = fd;
10622 
10623 	link->pin_path = strdup(path);
10624 	if (!link->pin_path) {
10625 		bpf_link__destroy(link);
10626 		return libbpf_err_ptr(-ENOMEM);
10627 	}
10628 
10629 	return link;
10630 }
10631 
10632 int bpf_link__detach(struct bpf_link *link)
10633 {
10634 	return bpf_link_detach(link->fd) ? -errno : 0;
10635 }
10636 
10637 int bpf_link__pin(struct bpf_link *link, const char *path)
10638 {
10639 	int err;
10640 
10641 	if (link->pin_path)
10642 		return libbpf_err(-EBUSY);
10643 	err = make_parent_dir(path);
10644 	if (err)
10645 		return libbpf_err(err);
10646 	err = check_path(path);
10647 	if (err)
10648 		return libbpf_err(err);
10649 
10650 	link->pin_path = strdup(path);
10651 	if (!link->pin_path)
10652 		return libbpf_err(-ENOMEM);
10653 
10654 	if (bpf_obj_pin(link->fd, link->pin_path)) {
10655 		err = -errno;
10656 		zfree(&link->pin_path);
10657 		return libbpf_err(err);
10658 	}
10659 
10660 	pr_debug("link fd=%d: pinned at %s\n", link->fd, link->pin_path);
10661 	return 0;
10662 }
10663 
10664 int bpf_link__unpin(struct bpf_link *link)
10665 {
10666 	int err;
10667 
10668 	if (!link->pin_path)
10669 		return libbpf_err(-EINVAL);
10670 
10671 	err = unlink(link->pin_path);
10672 	if (err != 0)
10673 		return -errno;
10674 
10675 	pr_debug("link fd=%d: unpinned from %s\n", link->fd, link->pin_path);
10676 	zfree(&link->pin_path);
10677 	return 0;
10678 }
10679 
10680 struct bpf_link_perf {
10681 	struct bpf_link link;
10682 	int perf_event_fd;
10683 	/* legacy kprobe support: keep track of probe identifier and type */
10684 	char *legacy_probe_name;
10685 	bool legacy_is_kprobe;
10686 	bool legacy_is_retprobe;
10687 };
10688 
10689 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe);
10690 static int remove_uprobe_event_legacy(const char *probe_name, bool retprobe);
10691 
10692 static int bpf_link_perf_detach(struct bpf_link *link)
10693 {
10694 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10695 	int err = 0;
10696 
10697 	if (ioctl(perf_link->perf_event_fd, PERF_EVENT_IOC_DISABLE, 0) < 0)
10698 		err = -errno;
10699 
10700 	if (perf_link->perf_event_fd != link->fd)
10701 		close(perf_link->perf_event_fd);
10702 	close(link->fd);
10703 
10704 	/* legacy uprobe/kprobe needs to be removed after perf event fd closure */
10705 	if (perf_link->legacy_probe_name) {
10706 		if (perf_link->legacy_is_kprobe) {
10707 			err = remove_kprobe_event_legacy(perf_link->legacy_probe_name,
10708 							 perf_link->legacy_is_retprobe);
10709 		} else {
10710 			err = remove_uprobe_event_legacy(perf_link->legacy_probe_name,
10711 							 perf_link->legacy_is_retprobe);
10712 		}
10713 	}
10714 
10715 	return err;
10716 }
10717 
10718 static void bpf_link_perf_dealloc(struct bpf_link *link)
10719 {
10720 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10721 
10722 	free(perf_link->legacy_probe_name);
10723 	free(perf_link);
10724 }
10725 
10726 struct bpf_link *bpf_program__attach_perf_event_opts(const struct bpf_program *prog, int pfd,
10727 						     const struct bpf_perf_event_opts *opts)
10728 {
10729 	char errmsg[STRERR_BUFSIZE];
10730 	struct bpf_link_perf *link;
10731 	int prog_fd, link_fd = -1, err;
10732 	bool force_ioctl_attach;
10733 
10734 	if (!OPTS_VALID(opts, bpf_perf_event_opts))
10735 		return libbpf_err_ptr(-EINVAL);
10736 
10737 	if (pfd < 0) {
10738 		pr_warn("prog '%s': invalid perf event FD %d\n",
10739 			prog->name, pfd);
10740 		return libbpf_err_ptr(-EINVAL);
10741 	}
10742 	prog_fd = bpf_program__fd(prog);
10743 	if (prog_fd < 0) {
10744 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
10745 			prog->name);
10746 		return libbpf_err_ptr(-EINVAL);
10747 	}
10748 
10749 	link = calloc(1, sizeof(*link));
10750 	if (!link)
10751 		return libbpf_err_ptr(-ENOMEM);
10752 	link->link.detach = &bpf_link_perf_detach;
10753 	link->link.dealloc = &bpf_link_perf_dealloc;
10754 	link->perf_event_fd = pfd;
10755 
10756 	force_ioctl_attach = OPTS_GET(opts, force_ioctl_attach, false);
10757 	if (kernel_supports(prog->obj, FEAT_PERF_LINK) && !force_ioctl_attach) {
10758 		DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_opts,
10759 			.perf_event.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0));
10760 
10761 		link_fd = bpf_link_create(prog_fd, pfd, BPF_PERF_EVENT, &link_opts);
10762 		if (link_fd < 0) {
10763 			err = -errno;
10764 			pr_warn("prog '%s': failed to create BPF link for perf_event FD %d: %d (%s)\n",
10765 				prog->name, pfd,
10766 				err, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10767 			goto err_out;
10768 		}
10769 		link->link.fd = link_fd;
10770 	} else {
10771 		if (OPTS_GET(opts, bpf_cookie, 0)) {
10772 			pr_warn("prog '%s': user context value is not supported\n", prog->name);
10773 			err = -EOPNOTSUPP;
10774 			goto err_out;
10775 		}
10776 
10777 		if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
10778 			err = -errno;
10779 			pr_warn("prog '%s': failed to attach to perf_event FD %d: %s\n",
10780 				prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10781 			if (err == -EPROTO)
10782 				pr_warn("prog '%s': try add PERF_SAMPLE_CALLCHAIN to or remove exclude_callchain_[kernel|user] from pfd %d\n",
10783 					prog->name, pfd);
10784 			goto err_out;
10785 		}
10786 		link->link.fd = pfd;
10787 	}
10788 	if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
10789 		err = -errno;
10790 		pr_warn("prog '%s': failed to enable perf_event FD %d: %s\n",
10791 			prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10792 		goto err_out;
10793 	}
10794 
10795 	return &link->link;
10796 err_out:
10797 	if (link_fd >= 0)
10798 		close(link_fd);
10799 	free(link);
10800 	return libbpf_err_ptr(err);
10801 }
10802 
10803 struct bpf_link *bpf_program__attach_perf_event(const struct bpf_program *prog, int pfd)
10804 {
10805 	return bpf_program__attach_perf_event_opts(prog, pfd, NULL);
10806 }
10807 
10808 /*
10809  * this function is expected to parse integer in the range of [0, 2^31-1] from
10810  * given file using scanf format string fmt. If actual parsed value is
10811  * negative, the result might be indistinguishable from error
10812  */
10813 static int parse_uint_from_file(const char *file, const char *fmt)
10814 {
10815 	char buf[STRERR_BUFSIZE];
10816 	int err, ret;
10817 	FILE *f;
10818 
10819 	f = fopen(file, "re");
10820 	if (!f) {
10821 		err = -errno;
10822 		pr_debug("failed to open '%s': %s\n", file,
10823 			 libbpf_strerror_r(err, buf, sizeof(buf)));
10824 		return err;
10825 	}
10826 	err = fscanf(f, fmt, &ret);
10827 	if (err != 1) {
10828 		err = err == EOF ? -EIO : -errno;
10829 		pr_debug("failed to parse '%s': %s\n", file,
10830 			libbpf_strerror_r(err, buf, sizeof(buf)));
10831 		fclose(f);
10832 		return err;
10833 	}
10834 	fclose(f);
10835 	return ret;
10836 }
10837 
10838 static int determine_kprobe_perf_type(void)
10839 {
10840 	const char *file = "/sys/bus/event_source/devices/kprobe/type";
10841 
10842 	return parse_uint_from_file(file, "%d\n");
10843 }
10844 
10845 static int determine_uprobe_perf_type(void)
10846 {
10847 	const char *file = "/sys/bus/event_source/devices/uprobe/type";
10848 
10849 	return parse_uint_from_file(file, "%d\n");
10850 }
10851 
10852 static int determine_kprobe_retprobe_bit(void)
10853 {
10854 	const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
10855 
10856 	return parse_uint_from_file(file, "config:%d\n");
10857 }
10858 
10859 static int determine_uprobe_retprobe_bit(void)
10860 {
10861 	const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
10862 
10863 	return parse_uint_from_file(file, "config:%d\n");
10864 }
10865 
10866 #define PERF_UPROBE_REF_CTR_OFFSET_BITS 32
10867 #define PERF_UPROBE_REF_CTR_OFFSET_SHIFT 32
10868 
10869 static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
10870 				 uint64_t offset, int pid, size_t ref_ctr_off)
10871 {
10872 	const size_t attr_sz = sizeof(struct perf_event_attr);
10873 	struct perf_event_attr attr;
10874 	char errmsg[STRERR_BUFSIZE];
10875 	int type, pfd;
10876 
10877 	if ((__u64)ref_ctr_off >= (1ULL << PERF_UPROBE_REF_CTR_OFFSET_BITS))
10878 		return -EINVAL;
10879 
10880 	memset(&attr, 0, attr_sz);
10881 
10882 	type = uprobe ? determine_uprobe_perf_type()
10883 		      : determine_kprobe_perf_type();
10884 	if (type < 0) {
10885 		pr_warn("failed to determine %s perf type: %s\n",
10886 			uprobe ? "uprobe" : "kprobe",
10887 			libbpf_strerror_r(type, errmsg, sizeof(errmsg)));
10888 		return type;
10889 	}
10890 	if (retprobe) {
10891 		int bit = uprobe ? determine_uprobe_retprobe_bit()
10892 				 : determine_kprobe_retprobe_bit();
10893 
10894 		if (bit < 0) {
10895 			pr_warn("failed to determine %s retprobe bit: %s\n",
10896 				uprobe ? "uprobe" : "kprobe",
10897 				libbpf_strerror_r(bit, errmsg, sizeof(errmsg)));
10898 			return bit;
10899 		}
10900 		attr.config |= 1 << bit;
10901 	}
10902 	attr.size = attr_sz;
10903 	attr.type = type;
10904 	attr.config |= (__u64)ref_ctr_off << PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
10905 	attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
10906 	attr.config2 = offset;		 /* kprobe_addr or probe_offset */
10907 
10908 	/* pid filter is meaningful only for uprobes */
10909 	pfd = syscall(__NR_perf_event_open, &attr,
10910 		      pid < 0 ? -1 : pid /* pid */,
10911 		      pid == -1 ? 0 : -1 /* cpu */,
10912 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
10913 	return pfd >= 0 ? pfd : -errno;
10914 }
10915 
10916 static int append_to_file(const char *file, const char *fmt, ...)
10917 {
10918 	int fd, n, err = 0;
10919 	va_list ap;
10920 	char buf[1024];
10921 
10922 	va_start(ap, fmt);
10923 	n = vsnprintf(buf, sizeof(buf), fmt, ap);
10924 	va_end(ap);
10925 
10926 	if (n < 0 || n >= sizeof(buf))
10927 		return -EINVAL;
10928 
10929 	fd = open(file, O_WRONLY | O_APPEND | O_CLOEXEC, 0);
10930 	if (fd < 0)
10931 		return -errno;
10932 
10933 	if (write(fd, buf, n) < 0)
10934 		err = -errno;
10935 
10936 	close(fd);
10937 	return err;
10938 }
10939 
10940 #define DEBUGFS "/sys/kernel/debug/tracing"
10941 #define TRACEFS "/sys/kernel/tracing"
10942 
10943 static bool use_debugfs(void)
10944 {
10945 	static int has_debugfs = -1;
10946 
10947 	if (has_debugfs < 0)
10948 		has_debugfs = faccessat(AT_FDCWD, DEBUGFS, F_OK, AT_EACCESS) == 0;
10949 
10950 	return has_debugfs == 1;
10951 }
10952 
10953 static const char *tracefs_path(void)
10954 {
10955 	return use_debugfs() ? DEBUGFS : TRACEFS;
10956 }
10957 
10958 static const char *tracefs_kprobe_events(void)
10959 {
10960 	return use_debugfs() ? DEBUGFS"/kprobe_events" : TRACEFS"/kprobe_events";
10961 }
10962 
10963 static const char *tracefs_uprobe_events(void)
10964 {
10965 	return use_debugfs() ? DEBUGFS"/uprobe_events" : TRACEFS"/uprobe_events";
10966 }
10967 
10968 static const char *tracefs_available_filter_functions(void)
10969 {
10970 	return use_debugfs() ? DEBUGFS"/available_filter_functions"
10971 			     : TRACEFS"/available_filter_functions";
10972 }
10973 
10974 static const char *tracefs_available_filter_functions_addrs(void)
10975 {
10976 	return use_debugfs() ? DEBUGFS"/available_filter_functions_addrs"
10977 			     : TRACEFS"/available_filter_functions_addrs";
10978 }
10979 
10980 static void gen_kprobe_legacy_event_name(char *buf, size_t buf_sz,
10981 					 const char *kfunc_name, size_t offset)
10982 {
10983 	static int index = 0;
10984 	int i;
10985 
10986 	snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx_%d", getpid(), kfunc_name, offset,
10987 		 __sync_fetch_and_add(&index, 1));
10988 
10989 	/* sanitize binary_path in the probe name */
10990 	for (i = 0; buf[i]; i++) {
10991 		if (!isalnum(buf[i]))
10992 			buf[i] = '_';
10993 	}
10994 }
10995 
10996 static int add_kprobe_event_legacy(const char *probe_name, bool retprobe,
10997 				   const char *kfunc_name, size_t offset)
10998 {
10999 	return append_to_file(tracefs_kprobe_events(), "%c:%s/%s %s+0x%zx",
11000 			      retprobe ? 'r' : 'p',
11001 			      retprobe ? "kretprobes" : "kprobes",
11002 			      probe_name, kfunc_name, offset);
11003 }
11004 
11005 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe)
11006 {
11007 	return append_to_file(tracefs_kprobe_events(), "-:%s/%s",
11008 			      retprobe ? "kretprobes" : "kprobes", probe_name);
11009 }
11010 
11011 static int determine_kprobe_perf_type_legacy(const char *probe_name, bool retprobe)
11012 {
11013 	char file[256];
11014 
11015 	snprintf(file, sizeof(file), "%s/events/%s/%s/id",
11016 		 tracefs_path(), retprobe ? "kretprobes" : "kprobes", probe_name);
11017 
11018 	return parse_uint_from_file(file, "%d\n");
11019 }
11020 
11021 static int perf_event_kprobe_open_legacy(const char *probe_name, bool retprobe,
11022 					 const char *kfunc_name, size_t offset, int pid)
11023 {
11024 	const size_t attr_sz = sizeof(struct perf_event_attr);
11025 	struct perf_event_attr attr;
11026 	char errmsg[STRERR_BUFSIZE];
11027 	int type, pfd, err;
11028 
11029 	err = add_kprobe_event_legacy(probe_name, retprobe, kfunc_name, offset);
11030 	if (err < 0) {
11031 		pr_warn("failed to add legacy kprobe event for '%s+0x%zx': %s\n",
11032 			kfunc_name, offset,
11033 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11034 		return err;
11035 	}
11036 	type = determine_kprobe_perf_type_legacy(probe_name, retprobe);
11037 	if (type < 0) {
11038 		err = type;
11039 		pr_warn("failed to determine legacy kprobe event id for '%s+0x%zx': %s\n",
11040 			kfunc_name, offset,
11041 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11042 		goto err_clean_legacy;
11043 	}
11044 
11045 	memset(&attr, 0, attr_sz);
11046 	attr.size = attr_sz;
11047 	attr.config = type;
11048 	attr.type = PERF_TYPE_TRACEPOINT;
11049 
11050 	pfd = syscall(__NR_perf_event_open, &attr,
11051 		      pid < 0 ? -1 : pid, /* pid */
11052 		      pid == -1 ? 0 : -1, /* cpu */
11053 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
11054 	if (pfd < 0) {
11055 		err = -errno;
11056 		pr_warn("legacy kprobe perf_event_open() failed: %s\n",
11057 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11058 		goto err_clean_legacy;
11059 	}
11060 	return pfd;
11061 
11062 err_clean_legacy:
11063 	/* Clear the newly added legacy kprobe_event */
11064 	remove_kprobe_event_legacy(probe_name, retprobe);
11065 	return err;
11066 }
11067 
11068 static const char *arch_specific_syscall_pfx(void)
11069 {
11070 #if defined(__x86_64__)
11071 	return "x64";
11072 #elif defined(__i386__)
11073 	return "ia32";
11074 #elif defined(__s390x__)
11075 	return "s390x";
11076 #elif defined(__s390__)
11077 	return "s390";
11078 #elif defined(__arm__)
11079 	return "arm";
11080 #elif defined(__aarch64__)
11081 	return "arm64";
11082 #elif defined(__mips__)
11083 	return "mips";
11084 #elif defined(__riscv)
11085 	return "riscv";
11086 #elif defined(__powerpc__)
11087 	return "powerpc";
11088 #elif defined(__powerpc64__)
11089 	return "powerpc64";
11090 #else
11091 	return NULL;
11092 #endif
11093 }
11094 
11095 int probe_kern_syscall_wrapper(int token_fd)
11096 {
11097 	char syscall_name[64];
11098 	const char *ksys_pfx;
11099 
11100 	ksys_pfx = arch_specific_syscall_pfx();
11101 	if (!ksys_pfx)
11102 		return 0;
11103 
11104 	snprintf(syscall_name, sizeof(syscall_name), "__%s_sys_bpf", ksys_pfx);
11105 
11106 	if (determine_kprobe_perf_type() >= 0) {
11107 		int pfd;
11108 
11109 		pfd = perf_event_open_probe(false, false, syscall_name, 0, getpid(), 0);
11110 		if (pfd >= 0)
11111 			close(pfd);
11112 
11113 		return pfd >= 0 ? 1 : 0;
11114 	} else { /* legacy mode */
11115 		char probe_name[128];
11116 
11117 		gen_kprobe_legacy_event_name(probe_name, sizeof(probe_name), syscall_name, 0);
11118 		if (add_kprobe_event_legacy(probe_name, false, syscall_name, 0) < 0)
11119 			return 0;
11120 
11121 		(void)remove_kprobe_event_legacy(probe_name, false);
11122 		return 1;
11123 	}
11124 }
11125 
11126 struct bpf_link *
11127 bpf_program__attach_kprobe_opts(const struct bpf_program *prog,
11128 				const char *func_name,
11129 				const struct bpf_kprobe_opts *opts)
11130 {
11131 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
11132 	enum probe_attach_mode attach_mode;
11133 	char errmsg[STRERR_BUFSIZE];
11134 	char *legacy_probe = NULL;
11135 	struct bpf_link *link;
11136 	size_t offset;
11137 	bool retprobe, legacy;
11138 	int pfd, err;
11139 
11140 	if (!OPTS_VALID(opts, bpf_kprobe_opts))
11141 		return libbpf_err_ptr(-EINVAL);
11142 
11143 	attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
11144 	retprobe = OPTS_GET(opts, retprobe, false);
11145 	offset = OPTS_GET(opts, offset, 0);
11146 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11147 
11148 	legacy = determine_kprobe_perf_type() < 0;
11149 	switch (attach_mode) {
11150 	case PROBE_ATTACH_MODE_LEGACY:
11151 		legacy = true;
11152 		pe_opts.force_ioctl_attach = true;
11153 		break;
11154 	case PROBE_ATTACH_MODE_PERF:
11155 		if (legacy)
11156 			return libbpf_err_ptr(-ENOTSUP);
11157 		pe_opts.force_ioctl_attach = true;
11158 		break;
11159 	case PROBE_ATTACH_MODE_LINK:
11160 		if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
11161 			return libbpf_err_ptr(-ENOTSUP);
11162 		break;
11163 	case PROBE_ATTACH_MODE_DEFAULT:
11164 		break;
11165 	default:
11166 		return libbpf_err_ptr(-EINVAL);
11167 	}
11168 
11169 	if (!legacy) {
11170 		pfd = perf_event_open_probe(false /* uprobe */, retprobe,
11171 					    func_name, offset,
11172 					    -1 /* pid */, 0 /* ref_ctr_off */);
11173 	} else {
11174 		char probe_name[256];
11175 
11176 		gen_kprobe_legacy_event_name(probe_name, sizeof(probe_name),
11177 					     func_name, offset);
11178 
11179 		legacy_probe = strdup(probe_name);
11180 		if (!legacy_probe)
11181 			return libbpf_err_ptr(-ENOMEM);
11182 
11183 		pfd = perf_event_kprobe_open_legacy(legacy_probe, retprobe, func_name,
11184 						    offset, -1 /* pid */);
11185 	}
11186 	if (pfd < 0) {
11187 		err = -errno;
11188 		pr_warn("prog '%s': failed to create %s '%s+0x%zx' perf event: %s\n",
11189 			prog->name, retprobe ? "kretprobe" : "kprobe",
11190 			func_name, offset,
11191 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11192 		goto err_out;
11193 	}
11194 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
11195 	err = libbpf_get_error(link);
11196 	if (err) {
11197 		close(pfd);
11198 		pr_warn("prog '%s': failed to attach to %s '%s+0x%zx': %s\n",
11199 			prog->name, retprobe ? "kretprobe" : "kprobe",
11200 			func_name, offset,
11201 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11202 		goto err_clean_legacy;
11203 	}
11204 	if (legacy) {
11205 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
11206 
11207 		perf_link->legacy_probe_name = legacy_probe;
11208 		perf_link->legacy_is_kprobe = true;
11209 		perf_link->legacy_is_retprobe = retprobe;
11210 	}
11211 
11212 	return link;
11213 
11214 err_clean_legacy:
11215 	if (legacy)
11216 		remove_kprobe_event_legacy(legacy_probe, retprobe);
11217 err_out:
11218 	free(legacy_probe);
11219 	return libbpf_err_ptr(err);
11220 }
11221 
11222 struct bpf_link *bpf_program__attach_kprobe(const struct bpf_program *prog,
11223 					    bool retprobe,
11224 					    const char *func_name)
11225 {
11226 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts,
11227 		.retprobe = retprobe,
11228 	);
11229 
11230 	return bpf_program__attach_kprobe_opts(prog, func_name, &opts);
11231 }
11232 
11233 struct bpf_link *bpf_program__attach_ksyscall(const struct bpf_program *prog,
11234 					      const char *syscall_name,
11235 					      const struct bpf_ksyscall_opts *opts)
11236 {
11237 	LIBBPF_OPTS(bpf_kprobe_opts, kprobe_opts);
11238 	char func_name[128];
11239 
11240 	if (!OPTS_VALID(opts, bpf_ksyscall_opts))
11241 		return libbpf_err_ptr(-EINVAL);
11242 
11243 	if (kernel_supports(prog->obj, FEAT_SYSCALL_WRAPPER)) {
11244 		/* arch_specific_syscall_pfx() should never return NULL here
11245 		 * because it is guarded by kernel_supports(). However, since
11246 		 * compiler does not know that we have an explicit conditional
11247 		 * as well.
11248 		 */
11249 		snprintf(func_name, sizeof(func_name), "__%s_sys_%s",
11250 			 arch_specific_syscall_pfx() ? : "", syscall_name);
11251 	} else {
11252 		snprintf(func_name, sizeof(func_name), "__se_sys_%s", syscall_name);
11253 	}
11254 
11255 	kprobe_opts.retprobe = OPTS_GET(opts, retprobe, false);
11256 	kprobe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11257 
11258 	return bpf_program__attach_kprobe_opts(prog, func_name, &kprobe_opts);
11259 }
11260 
11261 /* Adapted from perf/util/string.c */
11262 bool glob_match(const char *str, const char *pat)
11263 {
11264 	while (*str && *pat && *pat != '*') {
11265 		if (*pat == '?') {      /* Matches any single character */
11266 			str++;
11267 			pat++;
11268 			continue;
11269 		}
11270 		if (*str != *pat)
11271 			return false;
11272 		str++;
11273 		pat++;
11274 	}
11275 	/* Check wild card */
11276 	if (*pat == '*') {
11277 		while (*pat == '*')
11278 			pat++;
11279 		if (!*pat) /* Tail wild card matches all */
11280 			return true;
11281 		while (*str)
11282 			if (glob_match(str++, pat))
11283 				return true;
11284 	}
11285 	return !*str && !*pat;
11286 }
11287 
11288 struct kprobe_multi_resolve {
11289 	const char *pattern;
11290 	unsigned long *addrs;
11291 	size_t cap;
11292 	size_t cnt;
11293 };
11294 
11295 struct avail_kallsyms_data {
11296 	char **syms;
11297 	size_t cnt;
11298 	struct kprobe_multi_resolve *res;
11299 };
11300 
11301 static int avail_func_cmp(const void *a, const void *b)
11302 {
11303 	return strcmp(*(const char **)a, *(const char **)b);
11304 }
11305 
11306 static int avail_kallsyms_cb(unsigned long long sym_addr, char sym_type,
11307 			     const char *sym_name, void *ctx)
11308 {
11309 	struct avail_kallsyms_data *data = ctx;
11310 	struct kprobe_multi_resolve *res = data->res;
11311 	int err;
11312 
11313 	if (!bsearch(&sym_name, data->syms, data->cnt, sizeof(*data->syms), avail_func_cmp))
11314 		return 0;
11315 
11316 	err = libbpf_ensure_mem((void **)&res->addrs, &res->cap, sizeof(*res->addrs), res->cnt + 1);
11317 	if (err)
11318 		return err;
11319 
11320 	res->addrs[res->cnt++] = (unsigned long)sym_addr;
11321 	return 0;
11322 }
11323 
11324 static int libbpf_available_kallsyms_parse(struct kprobe_multi_resolve *res)
11325 {
11326 	const char *available_functions_file = tracefs_available_filter_functions();
11327 	struct avail_kallsyms_data data;
11328 	char sym_name[500];
11329 	FILE *f;
11330 	int err = 0, ret, i;
11331 	char **syms = NULL;
11332 	size_t cap = 0, cnt = 0;
11333 
11334 	f = fopen(available_functions_file, "re");
11335 	if (!f) {
11336 		err = -errno;
11337 		pr_warn("failed to open %s: %d\n", available_functions_file, err);
11338 		return err;
11339 	}
11340 
11341 	while (true) {
11342 		char *name;
11343 
11344 		ret = fscanf(f, "%499s%*[^\n]\n", sym_name);
11345 		if (ret == EOF && feof(f))
11346 			break;
11347 
11348 		if (ret != 1) {
11349 			pr_warn("failed to parse available_filter_functions entry: %d\n", ret);
11350 			err = -EINVAL;
11351 			goto cleanup;
11352 		}
11353 
11354 		if (!glob_match(sym_name, res->pattern))
11355 			continue;
11356 
11357 		err = libbpf_ensure_mem((void **)&syms, &cap, sizeof(*syms), cnt + 1);
11358 		if (err)
11359 			goto cleanup;
11360 
11361 		name = strdup(sym_name);
11362 		if (!name) {
11363 			err = -errno;
11364 			goto cleanup;
11365 		}
11366 
11367 		syms[cnt++] = name;
11368 	}
11369 
11370 	/* no entries found, bail out */
11371 	if (cnt == 0) {
11372 		err = -ENOENT;
11373 		goto cleanup;
11374 	}
11375 
11376 	/* sort available functions */
11377 	qsort(syms, cnt, sizeof(*syms), avail_func_cmp);
11378 
11379 	data.syms = syms;
11380 	data.res = res;
11381 	data.cnt = cnt;
11382 	libbpf_kallsyms_parse(avail_kallsyms_cb, &data);
11383 
11384 	if (res->cnt == 0)
11385 		err = -ENOENT;
11386 
11387 cleanup:
11388 	for (i = 0; i < cnt; i++)
11389 		free((char *)syms[i]);
11390 	free(syms);
11391 
11392 	fclose(f);
11393 	return err;
11394 }
11395 
11396 static bool has_available_filter_functions_addrs(void)
11397 {
11398 	return access(tracefs_available_filter_functions_addrs(), R_OK) != -1;
11399 }
11400 
11401 static int libbpf_available_kprobes_parse(struct kprobe_multi_resolve *res)
11402 {
11403 	const char *available_path = tracefs_available_filter_functions_addrs();
11404 	char sym_name[500];
11405 	FILE *f;
11406 	int ret, err = 0;
11407 	unsigned long long sym_addr;
11408 
11409 	f = fopen(available_path, "re");
11410 	if (!f) {
11411 		err = -errno;
11412 		pr_warn("failed to open %s: %d\n", available_path, err);
11413 		return err;
11414 	}
11415 
11416 	while (true) {
11417 		ret = fscanf(f, "%llx %499s%*[^\n]\n", &sym_addr, sym_name);
11418 		if (ret == EOF && feof(f))
11419 			break;
11420 
11421 		if (ret != 2) {
11422 			pr_warn("failed to parse available_filter_functions_addrs entry: %d\n",
11423 				ret);
11424 			err = -EINVAL;
11425 			goto cleanup;
11426 		}
11427 
11428 		if (!glob_match(sym_name, res->pattern))
11429 			continue;
11430 
11431 		err = libbpf_ensure_mem((void **)&res->addrs, &res->cap,
11432 					sizeof(*res->addrs), res->cnt + 1);
11433 		if (err)
11434 			goto cleanup;
11435 
11436 		res->addrs[res->cnt++] = (unsigned long)sym_addr;
11437 	}
11438 
11439 	if (res->cnt == 0)
11440 		err = -ENOENT;
11441 
11442 cleanup:
11443 	fclose(f);
11444 	return err;
11445 }
11446 
11447 struct bpf_link *
11448 bpf_program__attach_kprobe_multi_opts(const struct bpf_program *prog,
11449 				      const char *pattern,
11450 				      const struct bpf_kprobe_multi_opts *opts)
11451 {
11452 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
11453 	struct kprobe_multi_resolve res = {
11454 		.pattern = pattern,
11455 	};
11456 	enum bpf_attach_type attach_type;
11457 	struct bpf_link *link = NULL;
11458 	char errmsg[STRERR_BUFSIZE];
11459 	const unsigned long *addrs;
11460 	int err, link_fd, prog_fd;
11461 	bool retprobe, session;
11462 	const __u64 *cookies;
11463 	const char **syms;
11464 	size_t cnt;
11465 
11466 	if (!OPTS_VALID(opts, bpf_kprobe_multi_opts))
11467 		return libbpf_err_ptr(-EINVAL);
11468 
11469 	prog_fd = bpf_program__fd(prog);
11470 	if (prog_fd < 0) {
11471 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
11472 			prog->name);
11473 		return libbpf_err_ptr(-EINVAL);
11474 	}
11475 
11476 	syms    = OPTS_GET(opts, syms, false);
11477 	addrs   = OPTS_GET(opts, addrs, false);
11478 	cnt     = OPTS_GET(opts, cnt, false);
11479 	cookies = OPTS_GET(opts, cookies, false);
11480 
11481 	if (!pattern && !addrs && !syms)
11482 		return libbpf_err_ptr(-EINVAL);
11483 	if (pattern && (addrs || syms || cookies || cnt))
11484 		return libbpf_err_ptr(-EINVAL);
11485 	if (!pattern && !cnt)
11486 		return libbpf_err_ptr(-EINVAL);
11487 	if (addrs && syms)
11488 		return libbpf_err_ptr(-EINVAL);
11489 
11490 	if (pattern) {
11491 		if (has_available_filter_functions_addrs())
11492 			err = libbpf_available_kprobes_parse(&res);
11493 		else
11494 			err = libbpf_available_kallsyms_parse(&res);
11495 		if (err)
11496 			goto error;
11497 		addrs = res.addrs;
11498 		cnt = res.cnt;
11499 	}
11500 
11501 	retprobe = OPTS_GET(opts, retprobe, false);
11502 	session  = OPTS_GET(opts, session, false);
11503 
11504 	if (retprobe && session)
11505 		return libbpf_err_ptr(-EINVAL);
11506 
11507 	attach_type = session ? BPF_TRACE_KPROBE_SESSION : BPF_TRACE_KPROBE_MULTI;
11508 
11509 	lopts.kprobe_multi.syms = syms;
11510 	lopts.kprobe_multi.addrs = addrs;
11511 	lopts.kprobe_multi.cookies = cookies;
11512 	lopts.kprobe_multi.cnt = cnt;
11513 	lopts.kprobe_multi.flags = retprobe ? BPF_F_KPROBE_MULTI_RETURN : 0;
11514 
11515 	link = calloc(1, sizeof(*link));
11516 	if (!link) {
11517 		err = -ENOMEM;
11518 		goto error;
11519 	}
11520 	link->detach = &bpf_link__detach_fd;
11521 
11522 	link_fd = bpf_link_create(prog_fd, 0, attach_type, &lopts);
11523 	if (link_fd < 0) {
11524 		err = -errno;
11525 		pr_warn("prog '%s': failed to attach: %s\n",
11526 			prog->name, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11527 		goto error;
11528 	}
11529 	link->fd = link_fd;
11530 	free(res.addrs);
11531 	return link;
11532 
11533 error:
11534 	free(link);
11535 	free(res.addrs);
11536 	return libbpf_err_ptr(err);
11537 }
11538 
11539 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11540 {
11541 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts);
11542 	unsigned long offset = 0;
11543 	const char *func_name;
11544 	char *func;
11545 	int n;
11546 
11547 	*link = NULL;
11548 
11549 	/* no auto-attach for SEC("kprobe") and SEC("kretprobe") */
11550 	if (strcmp(prog->sec_name, "kprobe") == 0 || strcmp(prog->sec_name, "kretprobe") == 0)
11551 		return 0;
11552 
11553 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe/");
11554 	if (opts.retprobe)
11555 		func_name = prog->sec_name + sizeof("kretprobe/") - 1;
11556 	else
11557 		func_name = prog->sec_name + sizeof("kprobe/") - 1;
11558 
11559 	n = sscanf(func_name, "%m[a-zA-Z0-9_.]+%li", &func, &offset);
11560 	if (n < 1) {
11561 		pr_warn("kprobe name is invalid: %s\n", func_name);
11562 		return -EINVAL;
11563 	}
11564 	if (opts.retprobe && offset != 0) {
11565 		free(func);
11566 		pr_warn("kretprobes do not support offset specification\n");
11567 		return -EINVAL;
11568 	}
11569 
11570 	opts.offset = offset;
11571 	*link = bpf_program__attach_kprobe_opts(prog, func, &opts);
11572 	free(func);
11573 	return libbpf_get_error(*link);
11574 }
11575 
11576 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11577 {
11578 	LIBBPF_OPTS(bpf_ksyscall_opts, opts);
11579 	const char *syscall_name;
11580 
11581 	*link = NULL;
11582 
11583 	/* no auto-attach for SEC("ksyscall") and SEC("kretsyscall") */
11584 	if (strcmp(prog->sec_name, "ksyscall") == 0 || strcmp(prog->sec_name, "kretsyscall") == 0)
11585 		return 0;
11586 
11587 	opts.retprobe = str_has_pfx(prog->sec_name, "kretsyscall/");
11588 	if (opts.retprobe)
11589 		syscall_name = prog->sec_name + sizeof("kretsyscall/") - 1;
11590 	else
11591 		syscall_name = prog->sec_name + sizeof("ksyscall/") - 1;
11592 
11593 	*link = bpf_program__attach_ksyscall(prog, syscall_name, &opts);
11594 	return *link ? 0 : -errno;
11595 }
11596 
11597 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11598 {
11599 	LIBBPF_OPTS(bpf_kprobe_multi_opts, opts);
11600 	const char *spec;
11601 	char *pattern;
11602 	int n;
11603 
11604 	*link = NULL;
11605 
11606 	/* no auto-attach for SEC("kprobe.multi") and SEC("kretprobe.multi") */
11607 	if (strcmp(prog->sec_name, "kprobe.multi") == 0 ||
11608 	    strcmp(prog->sec_name, "kretprobe.multi") == 0)
11609 		return 0;
11610 
11611 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe.multi/");
11612 	if (opts.retprobe)
11613 		spec = prog->sec_name + sizeof("kretprobe.multi/") - 1;
11614 	else
11615 		spec = prog->sec_name + sizeof("kprobe.multi/") - 1;
11616 
11617 	n = sscanf(spec, "%m[a-zA-Z0-9_.*?]", &pattern);
11618 	if (n < 1) {
11619 		pr_warn("kprobe multi pattern is invalid: %s\n", spec);
11620 		return -EINVAL;
11621 	}
11622 
11623 	*link = bpf_program__attach_kprobe_multi_opts(prog, pattern, &opts);
11624 	free(pattern);
11625 	return libbpf_get_error(*link);
11626 }
11627 
11628 static int attach_kprobe_session(const struct bpf_program *prog, long cookie,
11629 				 struct bpf_link **link)
11630 {
11631 	LIBBPF_OPTS(bpf_kprobe_multi_opts, opts, .session = true);
11632 	const char *spec;
11633 	char *pattern;
11634 	int n;
11635 
11636 	*link = NULL;
11637 
11638 	/* no auto-attach for SEC("kprobe.session") */
11639 	if (strcmp(prog->sec_name, "kprobe.session") == 0)
11640 		return 0;
11641 
11642 	spec = prog->sec_name + sizeof("kprobe.session/") - 1;
11643 	n = sscanf(spec, "%m[a-zA-Z0-9_.*?]", &pattern);
11644 	if (n < 1) {
11645 		pr_warn("kprobe session pattern is invalid: %s\n", spec);
11646 		return -EINVAL;
11647 	}
11648 
11649 	*link = bpf_program__attach_kprobe_multi_opts(prog, pattern, &opts);
11650 	free(pattern);
11651 	return *link ? 0 : -errno;
11652 }
11653 
11654 static int attach_uprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11655 {
11656 	char *probe_type = NULL, *binary_path = NULL, *func_name = NULL;
11657 	LIBBPF_OPTS(bpf_uprobe_multi_opts, opts);
11658 	int n, ret = -EINVAL;
11659 
11660 	*link = NULL;
11661 
11662 	n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[^\n]",
11663 		   &probe_type, &binary_path, &func_name);
11664 	switch (n) {
11665 	case 1:
11666 		/* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
11667 		ret = 0;
11668 		break;
11669 	case 3:
11670 		opts.retprobe = strcmp(probe_type, "uretprobe.multi") == 0;
11671 		*link = bpf_program__attach_uprobe_multi(prog, -1, binary_path, func_name, &opts);
11672 		ret = libbpf_get_error(*link);
11673 		break;
11674 	default:
11675 		pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
11676 			prog->sec_name);
11677 		break;
11678 	}
11679 	free(probe_type);
11680 	free(binary_path);
11681 	free(func_name);
11682 	return ret;
11683 }
11684 
11685 static void gen_uprobe_legacy_event_name(char *buf, size_t buf_sz,
11686 					 const char *binary_path, uint64_t offset)
11687 {
11688 	int i;
11689 
11690 	snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx", getpid(), binary_path, (size_t)offset);
11691 
11692 	/* sanitize binary_path in the probe name */
11693 	for (i = 0; buf[i]; i++) {
11694 		if (!isalnum(buf[i]))
11695 			buf[i] = '_';
11696 	}
11697 }
11698 
11699 static inline int add_uprobe_event_legacy(const char *probe_name, bool retprobe,
11700 					  const char *binary_path, size_t offset)
11701 {
11702 	return append_to_file(tracefs_uprobe_events(), "%c:%s/%s %s:0x%zx",
11703 			      retprobe ? 'r' : 'p',
11704 			      retprobe ? "uretprobes" : "uprobes",
11705 			      probe_name, binary_path, offset);
11706 }
11707 
11708 static inline int remove_uprobe_event_legacy(const char *probe_name, bool retprobe)
11709 {
11710 	return append_to_file(tracefs_uprobe_events(), "-:%s/%s",
11711 			      retprobe ? "uretprobes" : "uprobes", probe_name);
11712 }
11713 
11714 static int determine_uprobe_perf_type_legacy(const char *probe_name, bool retprobe)
11715 {
11716 	char file[512];
11717 
11718 	snprintf(file, sizeof(file), "%s/events/%s/%s/id",
11719 		 tracefs_path(), retprobe ? "uretprobes" : "uprobes", probe_name);
11720 
11721 	return parse_uint_from_file(file, "%d\n");
11722 }
11723 
11724 static int perf_event_uprobe_open_legacy(const char *probe_name, bool retprobe,
11725 					 const char *binary_path, size_t offset, int pid)
11726 {
11727 	const size_t attr_sz = sizeof(struct perf_event_attr);
11728 	struct perf_event_attr attr;
11729 	int type, pfd, err;
11730 
11731 	err = add_uprobe_event_legacy(probe_name, retprobe, binary_path, offset);
11732 	if (err < 0) {
11733 		pr_warn("failed to add legacy uprobe event for %s:0x%zx: %d\n",
11734 			binary_path, (size_t)offset, err);
11735 		return err;
11736 	}
11737 	type = determine_uprobe_perf_type_legacy(probe_name, retprobe);
11738 	if (type < 0) {
11739 		err = type;
11740 		pr_warn("failed to determine legacy uprobe event id for %s:0x%zx: %d\n",
11741 			binary_path, offset, err);
11742 		goto err_clean_legacy;
11743 	}
11744 
11745 	memset(&attr, 0, attr_sz);
11746 	attr.size = attr_sz;
11747 	attr.config = type;
11748 	attr.type = PERF_TYPE_TRACEPOINT;
11749 
11750 	pfd = syscall(__NR_perf_event_open, &attr,
11751 		      pid < 0 ? -1 : pid, /* pid */
11752 		      pid == -1 ? 0 : -1, /* cpu */
11753 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
11754 	if (pfd < 0) {
11755 		err = -errno;
11756 		pr_warn("legacy uprobe perf_event_open() failed: %d\n", err);
11757 		goto err_clean_legacy;
11758 	}
11759 	return pfd;
11760 
11761 err_clean_legacy:
11762 	/* Clear the newly added legacy uprobe_event */
11763 	remove_uprobe_event_legacy(probe_name, retprobe);
11764 	return err;
11765 }
11766 
11767 /* Find offset of function name in archive specified by path. Currently
11768  * supported are .zip files that do not compress their contents, as used on
11769  * Android in the form of APKs, for example. "file_name" is the name of the ELF
11770  * file inside the archive. "func_name" matches symbol name or name@@LIB for
11771  * library functions.
11772  *
11773  * An overview of the APK format specifically provided here:
11774  * https://en.wikipedia.org/w/index.php?title=Apk_(file_format)&oldid=1139099120#Package_contents
11775  */
11776 static long elf_find_func_offset_from_archive(const char *archive_path, const char *file_name,
11777 					      const char *func_name)
11778 {
11779 	struct zip_archive *archive;
11780 	struct zip_entry entry;
11781 	long ret;
11782 	Elf *elf;
11783 
11784 	archive = zip_archive_open(archive_path);
11785 	if (IS_ERR(archive)) {
11786 		ret = PTR_ERR(archive);
11787 		pr_warn("zip: failed to open %s: %ld\n", archive_path, ret);
11788 		return ret;
11789 	}
11790 
11791 	ret = zip_archive_find_entry(archive, file_name, &entry);
11792 	if (ret) {
11793 		pr_warn("zip: could not find archive member %s in %s: %ld\n", file_name,
11794 			archive_path, ret);
11795 		goto out;
11796 	}
11797 	pr_debug("zip: found entry for %s in %s at 0x%lx\n", file_name, archive_path,
11798 		 (unsigned long)entry.data_offset);
11799 
11800 	if (entry.compression) {
11801 		pr_warn("zip: entry %s of %s is compressed and cannot be handled\n", file_name,
11802 			archive_path);
11803 		ret = -LIBBPF_ERRNO__FORMAT;
11804 		goto out;
11805 	}
11806 
11807 	elf = elf_memory((void *)entry.data, entry.data_length);
11808 	if (!elf) {
11809 		pr_warn("elf: could not read elf file %s from %s: %s\n", file_name, archive_path,
11810 			elf_errmsg(-1));
11811 		ret = -LIBBPF_ERRNO__LIBELF;
11812 		goto out;
11813 	}
11814 
11815 	ret = elf_find_func_offset(elf, file_name, func_name);
11816 	if (ret > 0) {
11817 		pr_debug("elf: symbol address match for %s of %s in %s: 0x%x + 0x%lx = 0x%lx\n",
11818 			 func_name, file_name, archive_path, entry.data_offset, ret,
11819 			 ret + entry.data_offset);
11820 		ret += entry.data_offset;
11821 	}
11822 	elf_end(elf);
11823 
11824 out:
11825 	zip_archive_close(archive);
11826 	return ret;
11827 }
11828 
11829 static const char *arch_specific_lib_paths(void)
11830 {
11831 	/*
11832 	 * Based on https://packages.debian.org/sid/libc6.
11833 	 *
11834 	 * Assume that the traced program is built for the same architecture
11835 	 * as libbpf, which should cover the vast majority of cases.
11836 	 */
11837 #if defined(__x86_64__)
11838 	return "/lib/x86_64-linux-gnu";
11839 #elif defined(__i386__)
11840 	return "/lib/i386-linux-gnu";
11841 #elif defined(__s390x__)
11842 	return "/lib/s390x-linux-gnu";
11843 #elif defined(__s390__)
11844 	return "/lib/s390-linux-gnu";
11845 #elif defined(__arm__) && defined(__SOFTFP__)
11846 	return "/lib/arm-linux-gnueabi";
11847 #elif defined(__arm__) && !defined(__SOFTFP__)
11848 	return "/lib/arm-linux-gnueabihf";
11849 #elif defined(__aarch64__)
11850 	return "/lib/aarch64-linux-gnu";
11851 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 64
11852 	return "/lib/mips64el-linux-gnuabi64";
11853 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 32
11854 	return "/lib/mipsel-linux-gnu";
11855 #elif defined(__powerpc64__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
11856 	return "/lib/powerpc64le-linux-gnu";
11857 #elif defined(__sparc__) && defined(__arch64__)
11858 	return "/lib/sparc64-linux-gnu";
11859 #elif defined(__riscv) && __riscv_xlen == 64
11860 	return "/lib/riscv64-linux-gnu";
11861 #else
11862 	return NULL;
11863 #endif
11864 }
11865 
11866 /* Get full path to program/shared library. */
11867 static int resolve_full_path(const char *file, char *result, size_t result_sz)
11868 {
11869 	const char *search_paths[3] = {};
11870 	int i, perm;
11871 
11872 	if (str_has_sfx(file, ".so") || strstr(file, ".so.")) {
11873 		search_paths[0] = getenv("LD_LIBRARY_PATH");
11874 		search_paths[1] = "/usr/lib64:/usr/lib";
11875 		search_paths[2] = arch_specific_lib_paths();
11876 		perm = R_OK;
11877 	} else {
11878 		search_paths[0] = getenv("PATH");
11879 		search_paths[1] = "/usr/bin:/usr/sbin";
11880 		perm = R_OK | X_OK;
11881 	}
11882 
11883 	for (i = 0; i < ARRAY_SIZE(search_paths); i++) {
11884 		const char *s;
11885 
11886 		if (!search_paths[i])
11887 			continue;
11888 		for (s = search_paths[i]; s != NULL; s = strchr(s, ':')) {
11889 			char *next_path;
11890 			int seg_len;
11891 
11892 			if (s[0] == ':')
11893 				s++;
11894 			next_path = strchr(s, ':');
11895 			seg_len = next_path ? next_path - s : strlen(s);
11896 			if (!seg_len)
11897 				continue;
11898 			snprintf(result, result_sz, "%.*s/%s", seg_len, s, file);
11899 			/* ensure it has required permissions */
11900 			if (faccessat(AT_FDCWD, result, perm, AT_EACCESS) < 0)
11901 				continue;
11902 			pr_debug("resolved '%s' to '%s'\n", file, result);
11903 			return 0;
11904 		}
11905 	}
11906 	return -ENOENT;
11907 }
11908 
11909 struct bpf_link *
11910 bpf_program__attach_uprobe_multi(const struct bpf_program *prog,
11911 				 pid_t pid,
11912 				 const char *path,
11913 				 const char *func_pattern,
11914 				 const struct bpf_uprobe_multi_opts *opts)
11915 {
11916 	const unsigned long *ref_ctr_offsets = NULL, *offsets = NULL;
11917 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
11918 	unsigned long *resolved_offsets = NULL;
11919 	int err = 0, link_fd, prog_fd;
11920 	struct bpf_link *link = NULL;
11921 	char errmsg[STRERR_BUFSIZE];
11922 	char full_path[PATH_MAX];
11923 	const __u64 *cookies;
11924 	const char **syms;
11925 	size_t cnt;
11926 
11927 	if (!OPTS_VALID(opts, bpf_uprobe_multi_opts))
11928 		return libbpf_err_ptr(-EINVAL);
11929 
11930 	prog_fd = bpf_program__fd(prog);
11931 	if (prog_fd < 0) {
11932 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
11933 			prog->name);
11934 		return libbpf_err_ptr(-EINVAL);
11935 	}
11936 
11937 	syms = OPTS_GET(opts, syms, NULL);
11938 	offsets = OPTS_GET(opts, offsets, NULL);
11939 	ref_ctr_offsets = OPTS_GET(opts, ref_ctr_offsets, NULL);
11940 	cookies = OPTS_GET(opts, cookies, NULL);
11941 	cnt = OPTS_GET(opts, cnt, 0);
11942 
11943 	/*
11944 	 * User can specify 2 mutually exclusive set of inputs:
11945 	 *
11946 	 * 1) use only path/func_pattern/pid arguments
11947 	 *
11948 	 * 2) use path/pid with allowed combinations of:
11949 	 *    syms/offsets/ref_ctr_offsets/cookies/cnt
11950 	 *
11951 	 *    - syms and offsets are mutually exclusive
11952 	 *    - ref_ctr_offsets and cookies are optional
11953 	 *
11954 	 * Any other usage results in error.
11955 	 */
11956 
11957 	if (!path)
11958 		return libbpf_err_ptr(-EINVAL);
11959 	if (!func_pattern && cnt == 0)
11960 		return libbpf_err_ptr(-EINVAL);
11961 
11962 	if (func_pattern) {
11963 		if (syms || offsets || ref_ctr_offsets || cookies || cnt)
11964 			return libbpf_err_ptr(-EINVAL);
11965 	} else {
11966 		if (!!syms == !!offsets)
11967 			return libbpf_err_ptr(-EINVAL);
11968 	}
11969 
11970 	if (func_pattern) {
11971 		if (!strchr(path, '/')) {
11972 			err = resolve_full_path(path, full_path, sizeof(full_path));
11973 			if (err) {
11974 				pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
11975 					prog->name, path, err);
11976 				return libbpf_err_ptr(err);
11977 			}
11978 			path = full_path;
11979 		}
11980 
11981 		err = elf_resolve_pattern_offsets(path, func_pattern,
11982 						  &resolved_offsets, &cnt);
11983 		if (err < 0)
11984 			return libbpf_err_ptr(err);
11985 		offsets = resolved_offsets;
11986 	} else if (syms) {
11987 		err = elf_resolve_syms_offsets(path, cnt, syms, &resolved_offsets, STT_FUNC);
11988 		if (err < 0)
11989 			return libbpf_err_ptr(err);
11990 		offsets = resolved_offsets;
11991 	}
11992 
11993 	lopts.uprobe_multi.path = path;
11994 	lopts.uprobe_multi.offsets = offsets;
11995 	lopts.uprobe_multi.ref_ctr_offsets = ref_ctr_offsets;
11996 	lopts.uprobe_multi.cookies = cookies;
11997 	lopts.uprobe_multi.cnt = cnt;
11998 	lopts.uprobe_multi.flags = OPTS_GET(opts, retprobe, false) ? BPF_F_UPROBE_MULTI_RETURN : 0;
11999 
12000 	if (pid == 0)
12001 		pid = getpid();
12002 	if (pid > 0)
12003 		lopts.uprobe_multi.pid = pid;
12004 
12005 	link = calloc(1, sizeof(*link));
12006 	if (!link) {
12007 		err = -ENOMEM;
12008 		goto error;
12009 	}
12010 	link->detach = &bpf_link__detach_fd;
12011 
12012 	link_fd = bpf_link_create(prog_fd, 0, BPF_TRACE_UPROBE_MULTI, &lopts);
12013 	if (link_fd < 0) {
12014 		err = -errno;
12015 		pr_warn("prog '%s': failed to attach multi-uprobe: %s\n",
12016 			prog->name, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
12017 		goto error;
12018 	}
12019 	link->fd = link_fd;
12020 	free(resolved_offsets);
12021 	return link;
12022 
12023 error:
12024 	free(resolved_offsets);
12025 	free(link);
12026 	return libbpf_err_ptr(err);
12027 }
12028 
12029 LIBBPF_API struct bpf_link *
12030 bpf_program__attach_uprobe_opts(const struct bpf_program *prog, pid_t pid,
12031 				const char *binary_path, size_t func_offset,
12032 				const struct bpf_uprobe_opts *opts)
12033 {
12034 	const char *archive_path = NULL, *archive_sep = NULL;
12035 	char errmsg[STRERR_BUFSIZE], *legacy_probe = NULL;
12036 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
12037 	enum probe_attach_mode attach_mode;
12038 	char full_path[PATH_MAX];
12039 	struct bpf_link *link;
12040 	size_t ref_ctr_off;
12041 	int pfd, err;
12042 	bool retprobe, legacy;
12043 	const char *func_name;
12044 
12045 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
12046 		return libbpf_err_ptr(-EINVAL);
12047 
12048 	attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
12049 	retprobe = OPTS_GET(opts, retprobe, false);
12050 	ref_ctr_off = OPTS_GET(opts, ref_ctr_offset, 0);
12051 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
12052 
12053 	if (!binary_path)
12054 		return libbpf_err_ptr(-EINVAL);
12055 
12056 	/* Check if "binary_path" refers to an archive. */
12057 	archive_sep = strstr(binary_path, "!/");
12058 	if (archive_sep) {
12059 		full_path[0] = '\0';
12060 		libbpf_strlcpy(full_path, binary_path,
12061 			       min(sizeof(full_path), (size_t)(archive_sep - binary_path + 1)));
12062 		archive_path = full_path;
12063 		binary_path = archive_sep + 2;
12064 	} else if (!strchr(binary_path, '/')) {
12065 		err = resolve_full_path(binary_path, full_path, sizeof(full_path));
12066 		if (err) {
12067 			pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
12068 				prog->name, binary_path, err);
12069 			return libbpf_err_ptr(err);
12070 		}
12071 		binary_path = full_path;
12072 	}
12073 	func_name = OPTS_GET(opts, func_name, NULL);
12074 	if (func_name) {
12075 		long sym_off;
12076 
12077 		if (archive_path) {
12078 			sym_off = elf_find_func_offset_from_archive(archive_path, binary_path,
12079 								    func_name);
12080 			binary_path = archive_path;
12081 		} else {
12082 			sym_off = elf_find_func_offset_from_file(binary_path, func_name);
12083 		}
12084 		if (sym_off < 0)
12085 			return libbpf_err_ptr(sym_off);
12086 		func_offset += sym_off;
12087 	}
12088 
12089 	legacy = determine_uprobe_perf_type() < 0;
12090 	switch (attach_mode) {
12091 	case PROBE_ATTACH_MODE_LEGACY:
12092 		legacy = true;
12093 		pe_opts.force_ioctl_attach = true;
12094 		break;
12095 	case PROBE_ATTACH_MODE_PERF:
12096 		if (legacy)
12097 			return libbpf_err_ptr(-ENOTSUP);
12098 		pe_opts.force_ioctl_attach = true;
12099 		break;
12100 	case PROBE_ATTACH_MODE_LINK:
12101 		if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
12102 			return libbpf_err_ptr(-ENOTSUP);
12103 		break;
12104 	case PROBE_ATTACH_MODE_DEFAULT:
12105 		break;
12106 	default:
12107 		return libbpf_err_ptr(-EINVAL);
12108 	}
12109 
12110 	if (!legacy) {
12111 		pfd = perf_event_open_probe(true /* uprobe */, retprobe, binary_path,
12112 					    func_offset, pid, ref_ctr_off);
12113 	} else {
12114 		char probe_name[PATH_MAX + 64];
12115 
12116 		if (ref_ctr_off)
12117 			return libbpf_err_ptr(-EINVAL);
12118 
12119 		gen_uprobe_legacy_event_name(probe_name, sizeof(probe_name),
12120 					     binary_path, func_offset);
12121 
12122 		legacy_probe = strdup(probe_name);
12123 		if (!legacy_probe)
12124 			return libbpf_err_ptr(-ENOMEM);
12125 
12126 		pfd = perf_event_uprobe_open_legacy(legacy_probe, retprobe,
12127 						    binary_path, func_offset, pid);
12128 	}
12129 	if (pfd < 0) {
12130 		err = -errno;
12131 		pr_warn("prog '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
12132 			prog->name, retprobe ? "uretprobe" : "uprobe",
12133 			binary_path, func_offset,
12134 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
12135 		goto err_out;
12136 	}
12137 
12138 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
12139 	err = libbpf_get_error(link);
12140 	if (err) {
12141 		close(pfd);
12142 		pr_warn("prog '%s': failed to attach to %s '%s:0x%zx': %s\n",
12143 			prog->name, retprobe ? "uretprobe" : "uprobe",
12144 			binary_path, func_offset,
12145 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
12146 		goto err_clean_legacy;
12147 	}
12148 	if (legacy) {
12149 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
12150 
12151 		perf_link->legacy_probe_name = legacy_probe;
12152 		perf_link->legacy_is_kprobe = false;
12153 		perf_link->legacy_is_retprobe = retprobe;
12154 	}
12155 	return link;
12156 
12157 err_clean_legacy:
12158 	if (legacy)
12159 		remove_uprobe_event_legacy(legacy_probe, retprobe);
12160 err_out:
12161 	free(legacy_probe);
12162 	return libbpf_err_ptr(err);
12163 }
12164 
12165 /* Format of u[ret]probe section definition supporting auto-attach:
12166  * u[ret]probe/binary:function[+offset]
12167  *
12168  * binary can be an absolute/relative path or a filename; the latter is resolved to a
12169  * full binary path via bpf_program__attach_uprobe_opts.
12170  *
12171  * Specifying uprobe+ ensures we carry out strict matching; either "uprobe" must be
12172  * specified (and auto-attach is not possible) or the above format is specified for
12173  * auto-attach.
12174  */
12175 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12176 {
12177 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts);
12178 	char *probe_type = NULL, *binary_path = NULL, *func_name = NULL, *func_off;
12179 	int n, c, ret = -EINVAL;
12180 	long offset = 0;
12181 
12182 	*link = NULL;
12183 
12184 	n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[^\n]",
12185 		   &probe_type, &binary_path, &func_name);
12186 	switch (n) {
12187 	case 1:
12188 		/* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
12189 		ret = 0;
12190 		break;
12191 	case 2:
12192 		pr_warn("prog '%s': section '%s' missing ':function[+offset]' specification\n",
12193 			prog->name, prog->sec_name);
12194 		break;
12195 	case 3:
12196 		/* check if user specifies `+offset`, if yes, this should be
12197 		 * the last part of the string, make sure sscanf read to EOL
12198 		 */
12199 		func_off = strrchr(func_name, '+');
12200 		if (func_off) {
12201 			n = sscanf(func_off, "+%li%n", &offset, &c);
12202 			if (n == 1 && *(func_off + c) == '\0')
12203 				func_off[0] = '\0';
12204 			else
12205 				offset = 0;
12206 		}
12207 		opts.retprobe = strcmp(probe_type, "uretprobe") == 0 ||
12208 				strcmp(probe_type, "uretprobe.s") == 0;
12209 		if (opts.retprobe && offset != 0) {
12210 			pr_warn("prog '%s': uretprobes do not support offset specification\n",
12211 				prog->name);
12212 			break;
12213 		}
12214 		opts.func_name = func_name;
12215 		*link = bpf_program__attach_uprobe_opts(prog, -1, binary_path, offset, &opts);
12216 		ret = libbpf_get_error(*link);
12217 		break;
12218 	default:
12219 		pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
12220 			prog->sec_name);
12221 		break;
12222 	}
12223 	free(probe_type);
12224 	free(binary_path);
12225 	free(func_name);
12226 
12227 	return ret;
12228 }
12229 
12230 struct bpf_link *bpf_program__attach_uprobe(const struct bpf_program *prog,
12231 					    bool retprobe, pid_t pid,
12232 					    const char *binary_path,
12233 					    size_t func_offset)
12234 {
12235 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts, .retprobe = retprobe);
12236 
12237 	return bpf_program__attach_uprobe_opts(prog, pid, binary_path, func_offset, &opts);
12238 }
12239 
12240 struct bpf_link *bpf_program__attach_usdt(const struct bpf_program *prog,
12241 					  pid_t pid, const char *binary_path,
12242 					  const char *usdt_provider, const char *usdt_name,
12243 					  const struct bpf_usdt_opts *opts)
12244 {
12245 	char resolved_path[512];
12246 	struct bpf_object *obj = prog->obj;
12247 	struct bpf_link *link;
12248 	__u64 usdt_cookie;
12249 	int err;
12250 
12251 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
12252 		return libbpf_err_ptr(-EINVAL);
12253 
12254 	if (bpf_program__fd(prog) < 0) {
12255 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
12256 			prog->name);
12257 		return libbpf_err_ptr(-EINVAL);
12258 	}
12259 
12260 	if (!binary_path)
12261 		return libbpf_err_ptr(-EINVAL);
12262 
12263 	if (!strchr(binary_path, '/')) {
12264 		err = resolve_full_path(binary_path, resolved_path, sizeof(resolved_path));
12265 		if (err) {
12266 			pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
12267 				prog->name, binary_path, err);
12268 			return libbpf_err_ptr(err);
12269 		}
12270 		binary_path = resolved_path;
12271 	}
12272 
12273 	/* USDT manager is instantiated lazily on first USDT attach. It will
12274 	 * be destroyed together with BPF object in bpf_object__close().
12275 	 */
12276 	if (IS_ERR(obj->usdt_man))
12277 		return libbpf_ptr(obj->usdt_man);
12278 	if (!obj->usdt_man) {
12279 		obj->usdt_man = usdt_manager_new(obj);
12280 		if (IS_ERR(obj->usdt_man))
12281 			return libbpf_ptr(obj->usdt_man);
12282 	}
12283 
12284 	usdt_cookie = OPTS_GET(opts, usdt_cookie, 0);
12285 	link = usdt_manager_attach_usdt(obj->usdt_man, prog, pid, binary_path,
12286 					usdt_provider, usdt_name, usdt_cookie);
12287 	err = libbpf_get_error(link);
12288 	if (err)
12289 		return libbpf_err_ptr(err);
12290 	return link;
12291 }
12292 
12293 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12294 {
12295 	char *path = NULL, *provider = NULL, *name = NULL;
12296 	const char *sec_name;
12297 	int n, err;
12298 
12299 	sec_name = bpf_program__section_name(prog);
12300 	if (strcmp(sec_name, "usdt") == 0) {
12301 		/* no auto-attach for just SEC("usdt") */
12302 		*link = NULL;
12303 		return 0;
12304 	}
12305 
12306 	n = sscanf(sec_name, "usdt/%m[^:]:%m[^:]:%m[^:]", &path, &provider, &name);
12307 	if (n != 3) {
12308 		pr_warn("invalid section '%s', expected SEC(\"usdt/<path>:<provider>:<name>\")\n",
12309 			sec_name);
12310 		err = -EINVAL;
12311 	} else {
12312 		*link = bpf_program__attach_usdt(prog, -1 /* any process */, path,
12313 						 provider, name, NULL);
12314 		err = libbpf_get_error(*link);
12315 	}
12316 	free(path);
12317 	free(provider);
12318 	free(name);
12319 	return err;
12320 }
12321 
12322 static int determine_tracepoint_id(const char *tp_category,
12323 				   const char *tp_name)
12324 {
12325 	char file[PATH_MAX];
12326 	int ret;
12327 
12328 	ret = snprintf(file, sizeof(file), "%s/events/%s/%s/id",
12329 		       tracefs_path(), tp_category, tp_name);
12330 	if (ret < 0)
12331 		return -errno;
12332 	if (ret >= sizeof(file)) {
12333 		pr_debug("tracepoint %s/%s path is too long\n",
12334 			 tp_category, tp_name);
12335 		return -E2BIG;
12336 	}
12337 	return parse_uint_from_file(file, "%d\n");
12338 }
12339 
12340 static int perf_event_open_tracepoint(const char *tp_category,
12341 				      const char *tp_name)
12342 {
12343 	const size_t attr_sz = sizeof(struct perf_event_attr);
12344 	struct perf_event_attr attr;
12345 	char errmsg[STRERR_BUFSIZE];
12346 	int tp_id, pfd, err;
12347 
12348 	tp_id = determine_tracepoint_id(tp_category, tp_name);
12349 	if (tp_id < 0) {
12350 		pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
12351 			tp_category, tp_name,
12352 			libbpf_strerror_r(tp_id, errmsg, sizeof(errmsg)));
12353 		return tp_id;
12354 	}
12355 
12356 	memset(&attr, 0, attr_sz);
12357 	attr.type = PERF_TYPE_TRACEPOINT;
12358 	attr.size = attr_sz;
12359 	attr.config = tp_id;
12360 
12361 	pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
12362 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
12363 	if (pfd < 0) {
12364 		err = -errno;
12365 		pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
12366 			tp_category, tp_name,
12367 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
12368 		return err;
12369 	}
12370 	return pfd;
12371 }
12372 
12373 struct bpf_link *bpf_program__attach_tracepoint_opts(const struct bpf_program *prog,
12374 						     const char *tp_category,
12375 						     const char *tp_name,
12376 						     const struct bpf_tracepoint_opts *opts)
12377 {
12378 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
12379 	char errmsg[STRERR_BUFSIZE];
12380 	struct bpf_link *link;
12381 	int pfd, err;
12382 
12383 	if (!OPTS_VALID(opts, bpf_tracepoint_opts))
12384 		return libbpf_err_ptr(-EINVAL);
12385 
12386 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
12387 
12388 	pfd = perf_event_open_tracepoint(tp_category, tp_name);
12389 	if (pfd < 0) {
12390 		pr_warn("prog '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
12391 			prog->name, tp_category, tp_name,
12392 			libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
12393 		return libbpf_err_ptr(pfd);
12394 	}
12395 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
12396 	err = libbpf_get_error(link);
12397 	if (err) {
12398 		close(pfd);
12399 		pr_warn("prog '%s': failed to attach to tracepoint '%s/%s': %s\n",
12400 			prog->name, tp_category, tp_name,
12401 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
12402 		return libbpf_err_ptr(err);
12403 	}
12404 	return link;
12405 }
12406 
12407 struct bpf_link *bpf_program__attach_tracepoint(const struct bpf_program *prog,
12408 						const char *tp_category,
12409 						const char *tp_name)
12410 {
12411 	return bpf_program__attach_tracepoint_opts(prog, tp_category, tp_name, NULL);
12412 }
12413 
12414 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12415 {
12416 	char *sec_name, *tp_cat, *tp_name;
12417 
12418 	*link = NULL;
12419 
12420 	/* no auto-attach for SEC("tp") or SEC("tracepoint") */
12421 	if (strcmp(prog->sec_name, "tp") == 0 || strcmp(prog->sec_name, "tracepoint") == 0)
12422 		return 0;
12423 
12424 	sec_name = strdup(prog->sec_name);
12425 	if (!sec_name)
12426 		return -ENOMEM;
12427 
12428 	/* extract "tp/<category>/<name>" or "tracepoint/<category>/<name>" */
12429 	if (str_has_pfx(prog->sec_name, "tp/"))
12430 		tp_cat = sec_name + sizeof("tp/") - 1;
12431 	else
12432 		tp_cat = sec_name + sizeof("tracepoint/") - 1;
12433 	tp_name = strchr(tp_cat, '/');
12434 	if (!tp_name) {
12435 		free(sec_name);
12436 		return -EINVAL;
12437 	}
12438 	*tp_name = '\0';
12439 	tp_name++;
12440 
12441 	*link = bpf_program__attach_tracepoint(prog, tp_cat, tp_name);
12442 	free(sec_name);
12443 	return libbpf_get_error(*link);
12444 }
12445 
12446 struct bpf_link *
12447 bpf_program__attach_raw_tracepoint_opts(const struct bpf_program *prog,
12448 					const char *tp_name,
12449 					struct bpf_raw_tracepoint_opts *opts)
12450 {
12451 	LIBBPF_OPTS(bpf_raw_tp_opts, raw_opts);
12452 	char errmsg[STRERR_BUFSIZE];
12453 	struct bpf_link *link;
12454 	int prog_fd, pfd;
12455 
12456 	if (!OPTS_VALID(opts, bpf_raw_tracepoint_opts))
12457 		return libbpf_err_ptr(-EINVAL);
12458 
12459 	prog_fd = bpf_program__fd(prog);
12460 	if (prog_fd < 0) {
12461 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12462 		return libbpf_err_ptr(-EINVAL);
12463 	}
12464 
12465 	link = calloc(1, sizeof(*link));
12466 	if (!link)
12467 		return libbpf_err_ptr(-ENOMEM);
12468 	link->detach = &bpf_link__detach_fd;
12469 
12470 	raw_opts.tp_name = tp_name;
12471 	raw_opts.cookie = OPTS_GET(opts, cookie, 0);
12472 	pfd = bpf_raw_tracepoint_open_opts(prog_fd, &raw_opts);
12473 	if (pfd < 0) {
12474 		pfd = -errno;
12475 		free(link);
12476 		pr_warn("prog '%s': failed to attach to raw tracepoint '%s': %s\n",
12477 			prog->name, tp_name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
12478 		return libbpf_err_ptr(pfd);
12479 	}
12480 	link->fd = pfd;
12481 	return link;
12482 }
12483 
12484 struct bpf_link *bpf_program__attach_raw_tracepoint(const struct bpf_program *prog,
12485 						    const char *tp_name)
12486 {
12487 	return bpf_program__attach_raw_tracepoint_opts(prog, tp_name, NULL);
12488 }
12489 
12490 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12491 {
12492 	static const char *const prefixes[] = {
12493 		"raw_tp",
12494 		"raw_tracepoint",
12495 		"raw_tp.w",
12496 		"raw_tracepoint.w",
12497 	};
12498 	size_t i;
12499 	const char *tp_name = NULL;
12500 
12501 	*link = NULL;
12502 
12503 	for (i = 0; i < ARRAY_SIZE(prefixes); i++) {
12504 		size_t pfx_len;
12505 
12506 		if (!str_has_pfx(prog->sec_name, prefixes[i]))
12507 			continue;
12508 
12509 		pfx_len = strlen(prefixes[i]);
12510 		/* no auto-attach case of, e.g., SEC("raw_tp") */
12511 		if (prog->sec_name[pfx_len] == '\0')
12512 			return 0;
12513 
12514 		if (prog->sec_name[pfx_len] != '/')
12515 			continue;
12516 
12517 		tp_name = prog->sec_name + pfx_len + 1;
12518 		break;
12519 	}
12520 
12521 	if (!tp_name) {
12522 		pr_warn("prog '%s': invalid section name '%s'\n",
12523 			prog->name, prog->sec_name);
12524 		return -EINVAL;
12525 	}
12526 
12527 	*link = bpf_program__attach_raw_tracepoint(prog, tp_name);
12528 	return libbpf_get_error(*link);
12529 }
12530 
12531 /* Common logic for all BPF program types that attach to a btf_id */
12532 static struct bpf_link *bpf_program__attach_btf_id(const struct bpf_program *prog,
12533 						   const struct bpf_trace_opts *opts)
12534 {
12535 	LIBBPF_OPTS(bpf_link_create_opts, link_opts);
12536 	char errmsg[STRERR_BUFSIZE];
12537 	struct bpf_link *link;
12538 	int prog_fd, pfd;
12539 
12540 	if (!OPTS_VALID(opts, bpf_trace_opts))
12541 		return libbpf_err_ptr(-EINVAL);
12542 
12543 	prog_fd = bpf_program__fd(prog);
12544 	if (prog_fd < 0) {
12545 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12546 		return libbpf_err_ptr(-EINVAL);
12547 	}
12548 
12549 	link = calloc(1, sizeof(*link));
12550 	if (!link)
12551 		return libbpf_err_ptr(-ENOMEM);
12552 	link->detach = &bpf_link__detach_fd;
12553 
12554 	/* libbpf is smart enough to redirect to BPF_RAW_TRACEPOINT_OPEN on old kernels */
12555 	link_opts.tracing.cookie = OPTS_GET(opts, cookie, 0);
12556 	pfd = bpf_link_create(prog_fd, 0, bpf_program__expected_attach_type(prog), &link_opts);
12557 	if (pfd < 0) {
12558 		pfd = -errno;
12559 		free(link);
12560 		pr_warn("prog '%s': failed to attach: %s\n",
12561 			prog->name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
12562 		return libbpf_err_ptr(pfd);
12563 	}
12564 	link->fd = pfd;
12565 	return link;
12566 }
12567 
12568 struct bpf_link *bpf_program__attach_trace(const struct bpf_program *prog)
12569 {
12570 	return bpf_program__attach_btf_id(prog, NULL);
12571 }
12572 
12573 struct bpf_link *bpf_program__attach_trace_opts(const struct bpf_program *prog,
12574 						const struct bpf_trace_opts *opts)
12575 {
12576 	return bpf_program__attach_btf_id(prog, opts);
12577 }
12578 
12579 struct bpf_link *bpf_program__attach_lsm(const struct bpf_program *prog)
12580 {
12581 	return bpf_program__attach_btf_id(prog, NULL);
12582 }
12583 
12584 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12585 {
12586 	*link = bpf_program__attach_trace(prog);
12587 	return libbpf_get_error(*link);
12588 }
12589 
12590 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12591 {
12592 	*link = bpf_program__attach_lsm(prog);
12593 	return libbpf_get_error(*link);
12594 }
12595 
12596 static struct bpf_link *
12597 bpf_program_attach_fd(const struct bpf_program *prog,
12598 		      int target_fd, const char *target_name,
12599 		      const struct bpf_link_create_opts *opts)
12600 {
12601 	enum bpf_attach_type attach_type;
12602 	char errmsg[STRERR_BUFSIZE];
12603 	struct bpf_link *link;
12604 	int prog_fd, link_fd;
12605 
12606 	prog_fd = bpf_program__fd(prog);
12607 	if (prog_fd < 0) {
12608 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12609 		return libbpf_err_ptr(-EINVAL);
12610 	}
12611 
12612 	link = calloc(1, sizeof(*link));
12613 	if (!link)
12614 		return libbpf_err_ptr(-ENOMEM);
12615 	link->detach = &bpf_link__detach_fd;
12616 
12617 	attach_type = bpf_program__expected_attach_type(prog);
12618 	link_fd = bpf_link_create(prog_fd, target_fd, attach_type, opts);
12619 	if (link_fd < 0) {
12620 		link_fd = -errno;
12621 		free(link);
12622 		pr_warn("prog '%s': failed to attach to %s: %s\n",
12623 			prog->name, target_name,
12624 			libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
12625 		return libbpf_err_ptr(link_fd);
12626 	}
12627 	link->fd = link_fd;
12628 	return link;
12629 }
12630 
12631 struct bpf_link *
12632 bpf_program__attach_cgroup(const struct bpf_program *prog, int cgroup_fd)
12633 {
12634 	return bpf_program_attach_fd(prog, cgroup_fd, "cgroup", NULL);
12635 }
12636 
12637 struct bpf_link *
12638 bpf_program__attach_netns(const struct bpf_program *prog, int netns_fd)
12639 {
12640 	return bpf_program_attach_fd(prog, netns_fd, "netns", NULL);
12641 }
12642 
12643 struct bpf_link *
12644 bpf_program__attach_sockmap(const struct bpf_program *prog, int map_fd)
12645 {
12646 	return bpf_program_attach_fd(prog, map_fd, "sockmap", NULL);
12647 }
12648 
12649 struct bpf_link *bpf_program__attach_xdp(const struct bpf_program *prog, int ifindex)
12650 {
12651 	/* target_fd/target_ifindex use the same field in LINK_CREATE */
12652 	return bpf_program_attach_fd(prog, ifindex, "xdp", NULL);
12653 }
12654 
12655 struct bpf_link *
12656 bpf_program__attach_tcx(const struct bpf_program *prog, int ifindex,
12657 			const struct bpf_tcx_opts *opts)
12658 {
12659 	LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
12660 	__u32 relative_id;
12661 	int relative_fd;
12662 
12663 	if (!OPTS_VALID(opts, bpf_tcx_opts))
12664 		return libbpf_err_ptr(-EINVAL);
12665 
12666 	relative_id = OPTS_GET(opts, relative_id, 0);
12667 	relative_fd = OPTS_GET(opts, relative_fd, 0);
12668 
12669 	/* validate we don't have unexpected combinations of non-zero fields */
12670 	if (!ifindex) {
12671 		pr_warn("prog '%s': target netdevice ifindex cannot be zero\n",
12672 			prog->name);
12673 		return libbpf_err_ptr(-EINVAL);
12674 	}
12675 	if (relative_fd && relative_id) {
12676 		pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
12677 			prog->name);
12678 		return libbpf_err_ptr(-EINVAL);
12679 	}
12680 
12681 	link_create_opts.tcx.expected_revision = OPTS_GET(opts, expected_revision, 0);
12682 	link_create_opts.tcx.relative_fd = relative_fd;
12683 	link_create_opts.tcx.relative_id = relative_id;
12684 	link_create_opts.flags = OPTS_GET(opts, flags, 0);
12685 
12686 	/* target_fd/target_ifindex use the same field in LINK_CREATE */
12687 	return bpf_program_attach_fd(prog, ifindex, "tcx", &link_create_opts);
12688 }
12689 
12690 struct bpf_link *
12691 bpf_program__attach_netkit(const struct bpf_program *prog, int ifindex,
12692 			   const struct bpf_netkit_opts *opts)
12693 {
12694 	LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
12695 	__u32 relative_id;
12696 	int relative_fd;
12697 
12698 	if (!OPTS_VALID(opts, bpf_netkit_opts))
12699 		return libbpf_err_ptr(-EINVAL);
12700 
12701 	relative_id = OPTS_GET(opts, relative_id, 0);
12702 	relative_fd = OPTS_GET(opts, relative_fd, 0);
12703 
12704 	/* validate we don't have unexpected combinations of non-zero fields */
12705 	if (!ifindex) {
12706 		pr_warn("prog '%s': target netdevice ifindex cannot be zero\n",
12707 			prog->name);
12708 		return libbpf_err_ptr(-EINVAL);
12709 	}
12710 	if (relative_fd && relative_id) {
12711 		pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
12712 			prog->name);
12713 		return libbpf_err_ptr(-EINVAL);
12714 	}
12715 
12716 	link_create_opts.netkit.expected_revision = OPTS_GET(opts, expected_revision, 0);
12717 	link_create_opts.netkit.relative_fd = relative_fd;
12718 	link_create_opts.netkit.relative_id = relative_id;
12719 	link_create_opts.flags = OPTS_GET(opts, flags, 0);
12720 
12721 	return bpf_program_attach_fd(prog, ifindex, "netkit", &link_create_opts);
12722 }
12723 
12724 struct bpf_link *bpf_program__attach_freplace(const struct bpf_program *prog,
12725 					      int target_fd,
12726 					      const char *attach_func_name)
12727 {
12728 	int btf_id;
12729 
12730 	if (!!target_fd != !!attach_func_name) {
12731 		pr_warn("prog '%s': supply none or both of target_fd and attach_func_name\n",
12732 			prog->name);
12733 		return libbpf_err_ptr(-EINVAL);
12734 	}
12735 
12736 	if (prog->type != BPF_PROG_TYPE_EXT) {
12737 		pr_warn("prog '%s': only BPF_PROG_TYPE_EXT can attach as freplace",
12738 			prog->name);
12739 		return libbpf_err_ptr(-EINVAL);
12740 	}
12741 
12742 	if (target_fd) {
12743 		LIBBPF_OPTS(bpf_link_create_opts, target_opts);
12744 
12745 		btf_id = libbpf_find_prog_btf_id(attach_func_name, target_fd);
12746 		if (btf_id < 0)
12747 			return libbpf_err_ptr(btf_id);
12748 
12749 		target_opts.target_btf_id = btf_id;
12750 
12751 		return bpf_program_attach_fd(prog, target_fd, "freplace",
12752 					     &target_opts);
12753 	} else {
12754 		/* no target, so use raw_tracepoint_open for compatibility
12755 		 * with old kernels
12756 		 */
12757 		return bpf_program__attach_trace(prog);
12758 	}
12759 }
12760 
12761 struct bpf_link *
12762 bpf_program__attach_iter(const struct bpf_program *prog,
12763 			 const struct bpf_iter_attach_opts *opts)
12764 {
12765 	DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
12766 	char errmsg[STRERR_BUFSIZE];
12767 	struct bpf_link *link;
12768 	int prog_fd, link_fd;
12769 	__u32 target_fd = 0;
12770 
12771 	if (!OPTS_VALID(opts, bpf_iter_attach_opts))
12772 		return libbpf_err_ptr(-EINVAL);
12773 
12774 	link_create_opts.iter_info = OPTS_GET(opts, link_info, (void *)0);
12775 	link_create_opts.iter_info_len = OPTS_GET(opts, link_info_len, 0);
12776 
12777 	prog_fd = bpf_program__fd(prog);
12778 	if (prog_fd < 0) {
12779 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12780 		return libbpf_err_ptr(-EINVAL);
12781 	}
12782 
12783 	link = calloc(1, sizeof(*link));
12784 	if (!link)
12785 		return libbpf_err_ptr(-ENOMEM);
12786 	link->detach = &bpf_link__detach_fd;
12787 
12788 	link_fd = bpf_link_create(prog_fd, target_fd, BPF_TRACE_ITER,
12789 				  &link_create_opts);
12790 	if (link_fd < 0) {
12791 		link_fd = -errno;
12792 		free(link);
12793 		pr_warn("prog '%s': failed to attach to iterator: %s\n",
12794 			prog->name, libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
12795 		return libbpf_err_ptr(link_fd);
12796 	}
12797 	link->fd = link_fd;
12798 	return link;
12799 }
12800 
12801 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12802 {
12803 	*link = bpf_program__attach_iter(prog, NULL);
12804 	return libbpf_get_error(*link);
12805 }
12806 
12807 struct bpf_link *bpf_program__attach_netfilter(const struct bpf_program *prog,
12808 					       const struct bpf_netfilter_opts *opts)
12809 {
12810 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
12811 	struct bpf_link *link;
12812 	int prog_fd, link_fd;
12813 
12814 	if (!OPTS_VALID(opts, bpf_netfilter_opts))
12815 		return libbpf_err_ptr(-EINVAL);
12816 
12817 	prog_fd = bpf_program__fd(prog);
12818 	if (prog_fd < 0) {
12819 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12820 		return libbpf_err_ptr(-EINVAL);
12821 	}
12822 
12823 	link = calloc(1, sizeof(*link));
12824 	if (!link)
12825 		return libbpf_err_ptr(-ENOMEM);
12826 
12827 	link->detach = &bpf_link__detach_fd;
12828 
12829 	lopts.netfilter.pf = OPTS_GET(opts, pf, 0);
12830 	lopts.netfilter.hooknum = OPTS_GET(opts, hooknum, 0);
12831 	lopts.netfilter.priority = OPTS_GET(opts, priority, 0);
12832 	lopts.netfilter.flags = OPTS_GET(opts, flags, 0);
12833 
12834 	link_fd = bpf_link_create(prog_fd, 0, BPF_NETFILTER, &lopts);
12835 	if (link_fd < 0) {
12836 		char errmsg[STRERR_BUFSIZE];
12837 
12838 		link_fd = -errno;
12839 		free(link);
12840 		pr_warn("prog '%s': failed to attach to netfilter: %s\n",
12841 			prog->name, libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
12842 		return libbpf_err_ptr(link_fd);
12843 	}
12844 	link->fd = link_fd;
12845 
12846 	return link;
12847 }
12848 
12849 struct bpf_link *bpf_program__attach(const struct bpf_program *prog)
12850 {
12851 	struct bpf_link *link = NULL;
12852 	int err;
12853 
12854 	if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
12855 		return libbpf_err_ptr(-EOPNOTSUPP);
12856 
12857 	if (bpf_program__fd(prog) < 0) {
12858 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
12859 			prog->name);
12860 		return libbpf_err_ptr(-EINVAL);
12861 	}
12862 
12863 	err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, &link);
12864 	if (err)
12865 		return libbpf_err_ptr(err);
12866 
12867 	/* When calling bpf_program__attach() explicitly, auto-attach support
12868 	 * is expected to work, so NULL returned link is considered an error.
12869 	 * This is different for skeleton's attach, see comment in
12870 	 * bpf_object__attach_skeleton().
12871 	 */
12872 	if (!link)
12873 		return libbpf_err_ptr(-EOPNOTSUPP);
12874 
12875 	return link;
12876 }
12877 
12878 struct bpf_link_struct_ops {
12879 	struct bpf_link link;
12880 	int map_fd;
12881 };
12882 
12883 static int bpf_link__detach_struct_ops(struct bpf_link *link)
12884 {
12885 	struct bpf_link_struct_ops *st_link;
12886 	__u32 zero = 0;
12887 
12888 	st_link = container_of(link, struct bpf_link_struct_ops, link);
12889 
12890 	if (st_link->map_fd < 0)
12891 		/* w/o a real link */
12892 		return bpf_map_delete_elem(link->fd, &zero);
12893 
12894 	return close(link->fd);
12895 }
12896 
12897 struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map)
12898 {
12899 	struct bpf_link_struct_ops *link;
12900 	__u32 zero = 0;
12901 	int err, fd;
12902 
12903 	if (!bpf_map__is_struct_ops(map))
12904 		return libbpf_err_ptr(-EINVAL);
12905 
12906 	if (map->fd < 0) {
12907 		pr_warn("map '%s': can't attach BPF map without FD (was it created?)\n", map->name);
12908 		return libbpf_err_ptr(-EINVAL);
12909 	}
12910 
12911 	link = calloc(1, sizeof(*link));
12912 	if (!link)
12913 		return libbpf_err_ptr(-EINVAL);
12914 
12915 	/* kern_vdata should be prepared during the loading phase. */
12916 	err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
12917 	/* It can be EBUSY if the map has been used to create or
12918 	 * update a link before.  We don't allow updating the value of
12919 	 * a struct_ops once it is set.  That ensures that the value
12920 	 * never changed.  So, it is safe to skip EBUSY.
12921 	 */
12922 	if (err && (!(map->def.map_flags & BPF_F_LINK) || err != -EBUSY)) {
12923 		free(link);
12924 		return libbpf_err_ptr(err);
12925 	}
12926 
12927 	link->link.detach = bpf_link__detach_struct_ops;
12928 
12929 	if (!(map->def.map_flags & BPF_F_LINK)) {
12930 		/* w/o a real link */
12931 		link->link.fd = map->fd;
12932 		link->map_fd = -1;
12933 		return &link->link;
12934 	}
12935 
12936 	fd = bpf_link_create(map->fd, 0, BPF_STRUCT_OPS, NULL);
12937 	if (fd < 0) {
12938 		free(link);
12939 		return libbpf_err_ptr(fd);
12940 	}
12941 
12942 	link->link.fd = fd;
12943 	link->map_fd = map->fd;
12944 
12945 	return &link->link;
12946 }
12947 
12948 /*
12949  * Swap the back struct_ops of a link with a new struct_ops map.
12950  */
12951 int bpf_link__update_map(struct bpf_link *link, const struct bpf_map *map)
12952 {
12953 	struct bpf_link_struct_ops *st_ops_link;
12954 	__u32 zero = 0;
12955 	int err;
12956 
12957 	if (!bpf_map__is_struct_ops(map))
12958 		return -EINVAL;
12959 
12960 	if (map->fd < 0) {
12961 		pr_warn("map '%s': can't use BPF map without FD (was it created?)\n", map->name);
12962 		return -EINVAL;
12963 	}
12964 
12965 	st_ops_link = container_of(link, struct bpf_link_struct_ops, link);
12966 	/* Ensure the type of a link is correct */
12967 	if (st_ops_link->map_fd < 0)
12968 		return -EINVAL;
12969 
12970 	err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
12971 	/* It can be EBUSY if the map has been used to create or
12972 	 * update a link before.  We don't allow updating the value of
12973 	 * a struct_ops once it is set.  That ensures that the value
12974 	 * never changed.  So, it is safe to skip EBUSY.
12975 	 */
12976 	if (err && err != -EBUSY)
12977 		return err;
12978 
12979 	err = bpf_link_update(link->fd, map->fd, NULL);
12980 	if (err < 0)
12981 		return err;
12982 
12983 	st_ops_link->map_fd = map->fd;
12984 
12985 	return 0;
12986 }
12987 
12988 typedef enum bpf_perf_event_ret (*bpf_perf_event_print_t)(struct perf_event_header *hdr,
12989 							  void *private_data);
12990 
12991 static enum bpf_perf_event_ret
12992 perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
12993 		       void **copy_mem, size_t *copy_size,
12994 		       bpf_perf_event_print_t fn, void *private_data)
12995 {
12996 	struct perf_event_mmap_page *header = mmap_mem;
12997 	__u64 data_head = ring_buffer_read_head(header);
12998 	__u64 data_tail = header->data_tail;
12999 	void *base = ((__u8 *)header) + page_size;
13000 	int ret = LIBBPF_PERF_EVENT_CONT;
13001 	struct perf_event_header *ehdr;
13002 	size_t ehdr_size;
13003 
13004 	while (data_head != data_tail) {
13005 		ehdr = base + (data_tail & (mmap_size - 1));
13006 		ehdr_size = ehdr->size;
13007 
13008 		if (((void *)ehdr) + ehdr_size > base + mmap_size) {
13009 			void *copy_start = ehdr;
13010 			size_t len_first = base + mmap_size - copy_start;
13011 			size_t len_secnd = ehdr_size - len_first;
13012 
13013 			if (*copy_size < ehdr_size) {
13014 				free(*copy_mem);
13015 				*copy_mem = malloc(ehdr_size);
13016 				if (!*copy_mem) {
13017 					*copy_size = 0;
13018 					ret = LIBBPF_PERF_EVENT_ERROR;
13019 					break;
13020 				}
13021 				*copy_size = ehdr_size;
13022 			}
13023 
13024 			memcpy(*copy_mem, copy_start, len_first);
13025 			memcpy(*copy_mem + len_first, base, len_secnd);
13026 			ehdr = *copy_mem;
13027 		}
13028 
13029 		ret = fn(ehdr, private_data);
13030 		data_tail += ehdr_size;
13031 		if (ret != LIBBPF_PERF_EVENT_CONT)
13032 			break;
13033 	}
13034 
13035 	ring_buffer_write_tail(header, data_tail);
13036 	return libbpf_err(ret);
13037 }
13038 
13039 struct perf_buffer;
13040 
13041 struct perf_buffer_params {
13042 	struct perf_event_attr *attr;
13043 	/* if event_cb is specified, it takes precendence */
13044 	perf_buffer_event_fn event_cb;
13045 	/* sample_cb and lost_cb are higher-level common-case callbacks */
13046 	perf_buffer_sample_fn sample_cb;
13047 	perf_buffer_lost_fn lost_cb;
13048 	void *ctx;
13049 	int cpu_cnt;
13050 	int *cpus;
13051 	int *map_keys;
13052 };
13053 
13054 struct perf_cpu_buf {
13055 	struct perf_buffer *pb;
13056 	void *base; /* mmap()'ed memory */
13057 	void *buf; /* for reconstructing segmented data */
13058 	size_t buf_size;
13059 	int fd;
13060 	int cpu;
13061 	int map_key;
13062 };
13063 
13064 struct perf_buffer {
13065 	perf_buffer_event_fn event_cb;
13066 	perf_buffer_sample_fn sample_cb;
13067 	perf_buffer_lost_fn lost_cb;
13068 	void *ctx; /* passed into callbacks */
13069 
13070 	size_t page_size;
13071 	size_t mmap_size;
13072 	struct perf_cpu_buf **cpu_bufs;
13073 	struct epoll_event *events;
13074 	int cpu_cnt; /* number of allocated CPU buffers */
13075 	int epoll_fd; /* perf event FD */
13076 	int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
13077 };
13078 
13079 static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
13080 				      struct perf_cpu_buf *cpu_buf)
13081 {
13082 	if (!cpu_buf)
13083 		return;
13084 	if (cpu_buf->base &&
13085 	    munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
13086 		pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
13087 	if (cpu_buf->fd >= 0) {
13088 		ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
13089 		close(cpu_buf->fd);
13090 	}
13091 	free(cpu_buf->buf);
13092 	free(cpu_buf);
13093 }
13094 
13095 void perf_buffer__free(struct perf_buffer *pb)
13096 {
13097 	int i;
13098 
13099 	if (IS_ERR_OR_NULL(pb))
13100 		return;
13101 	if (pb->cpu_bufs) {
13102 		for (i = 0; i < pb->cpu_cnt; i++) {
13103 			struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
13104 
13105 			if (!cpu_buf)
13106 				continue;
13107 
13108 			bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
13109 			perf_buffer__free_cpu_buf(pb, cpu_buf);
13110 		}
13111 		free(pb->cpu_bufs);
13112 	}
13113 	if (pb->epoll_fd >= 0)
13114 		close(pb->epoll_fd);
13115 	free(pb->events);
13116 	free(pb);
13117 }
13118 
13119 static struct perf_cpu_buf *
13120 perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
13121 			  int cpu, int map_key)
13122 {
13123 	struct perf_cpu_buf *cpu_buf;
13124 	char msg[STRERR_BUFSIZE];
13125 	int err;
13126 
13127 	cpu_buf = calloc(1, sizeof(*cpu_buf));
13128 	if (!cpu_buf)
13129 		return ERR_PTR(-ENOMEM);
13130 
13131 	cpu_buf->pb = pb;
13132 	cpu_buf->cpu = cpu;
13133 	cpu_buf->map_key = map_key;
13134 
13135 	cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
13136 			      -1, PERF_FLAG_FD_CLOEXEC);
13137 	if (cpu_buf->fd < 0) {
13138 		err = -errno;
13139 		pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
13140 			cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
13141 		goto error;
13142 	}
13143 
13144 	cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
13145 			     PROT_READ | PROT_WRITE, MAP_SHARED,
13146 			     cpu_buf->fd, 0);
13147 	if (cpu_buf->base == MAP_FAILED) {
13148 		cpu_buf->base = NULL;
13149 		err = -errno;
13150 		pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
13151 			cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
13152 		goto error;
13153 	}
13154 
13155 	if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
13156 		err = -errno;
13157 		pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
13158 			cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
13159 		goto error;
13160 	}
13161 
13162 	return cpu_buf;
13163 
13164 error:
13165 	perf_buffer__free_cpu_buf(pb, cpu_buf);
13166 	return (struct perf_cpu_buf *)ERR_PTR(err);
13167 }
13168 
13169 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
13170 					      struct perf_buffer_params *p);
13171 
13172 struct perf_buffer *perf_buffer__new(int map_fd, size_t page_cnt,
13173 				     perf_buffer_sample_fn sample_cb,
13174 				     perf_buffer_lost_fn lost_cb,
13175 				     void *ctx,
13176 				     const struct perf_buffer_opts *opts)
13177 {
13178 	const size_t attr_sz = sizeof(struct perf_event_attr);
13179 	struct perf_buffer_params p = {};
13180 	struct perf_event_attr attr;
13181 	__u32 sample_period;
13182 
13183 	if (!OPTS_VALID(opts, perf_buffer_opts))
13184 		return libbpf_err_ptr(-EINVAL);
13185 
13186 	sample_period = OPTS_GET(opts, sample_period, 1);
13187 	if (!sample_period)
13188 		sample_period = 1;
13189 
13190 	memset(&attr, 0, attr_sz);
13191 	attr.size = attr_sz;
13192 	attr.config = PERF_COUNT_SW_BPF_OUTPUT;
13193 	attr.type = PERF_TYPE_SOFTWARE;
13194 	attr.sample_type = PERF_SAMPLE_RAW;
13195 	attr.sample_period = sample_period;
13196 	attr.wakeup_events = sample_period;
13197 
13198 	p.attr = &attr;
13199 	p.sample_cb = sample_cb;
13200 	p.lost_cb = lost_cb;
13201 	p.ctx = ctx;
13202 
13203 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
13204 }
13205 
13206 struct perf_buffer *perf_buffer__new_raw(int map_fd, size_t page_cnt,
13207 					 struct perf_event_attr *attr,
13208 					 perf_buffer_event_fn event_cb, void *ctx,
13209 					 const struct perf_buffer_raw_opts *opts)
13210 {
13211 	struct perf_buffer_params p = {};
13212 
13213 	if (!attr)
13214 		return libbpf_err_ptr(-EINVAL);
13215 
13216 	if (!OPTS_VALID(opts, perf_buffer_raw_opts))
13217 		return libbpf_err_ptr(-EINVAL);
13218 
13219 	p.attr = attr;
13220 	p.event_cb = event_cb;
13221 	p.ctx = ctx;
13222 	p.cpu_cnt = OPTS_GET(opts, cpu_cnt, 0);
13223 	p.cpus = OPTS_GET(opts, cpus, NULL);
13224 	p.map_keys = OPTS_GET(opts, map_keys, NULL);
13225 
13226 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
13227 }
13228 
13229 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
13230 					      struct perf_buffer_params *p)
13231 {
13232 	const char *online_cpus_file = "/sys/devices/system/cpu/online";
13233 	struct bpf_map_info map;
13234 	char msg[STRERR_BUFSIZE];
13235 	struct perf_buffer *pb;
13236 	bool *online = NULL;
13237 	__u32 map_info_len;
13238 	int err, i, j, n;
13239 
13240 	if (page_cnt == 0 || (page_cnt & (page_cnt - 1))) {
13241 		pr_warn("page count should be power of two, but is %zu\n",
13242 			page_cnt);
13243 		return ERR_PTR(-EINVAL);
13244 	}
13245 
13246 	/* best-effort sanity checks */
13247 	memset(&map, 0, sizeof(map));
13248 	map_info_len = sizeof(map);
13249 	err = bpf_map_get_info_by_fd(map_fd, &map, &map_info_len);
13250 	if (err) {
13251 		err = -errno;
13252 		/* if BPF_OBJ_GET_INFO_BY_FD is supported, will return
13253 		 * -EBADFD, -EFAULT, or -E2BIG on real error
13254 		 */
13255 		if (err != -EINVAL) {
13256 			pr_warn("failed to get map info for map FD %d: %s\n",
13257 				map_fd, libbpf_strerror_r(err, msg, sizeof(msg)));
13258 			return ERR_PTR(err);
13259 		}
13260 		pr_debug("failed to get map info for FD %d; API not supported? Ignoring...\n",
13261 			 map_fd);
13262 	} else {
13263 		if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
13264 			pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
13265 				map.name);
13266 			return ERR_PTR(-EINVAL);
13267 		}
13268 	}
13269 
13270 	pb = calloc(1, sizeof(*pb));
13271 	if (!pb)
13272 		return ERR_PTR(-ENOMEM);
13273 
13274 	pb->event_cb = p->event_cb;
13275 	pb->sample_cb = p->sample_cb;
13276 	pb->lost_cb = p->lost_cb;
13277 	pb->ctx = p->ctx;
13278 
13279 	pb->page_size = getpagesize();
13280 	pb->mmap_size = pb->page_size * page_cnt;
13281 	pb->map_fd = map_fd;
13282 
13283 	pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
13284 	if (pb->epoll_fd < 0) {
13285 		err = -errno;
13286 		pr_warn("failed to create epoll instance: %s\n",
13287 			libbpf_strerror_r(err, msg, sizeof(msg)));
13288 		goto error;
13289 	}
13290 
13291 	if (p->cpu_cnt > 0) {
13292 		pb->cpu_cnt = p->cpu_cnt;
13293 	} else {
13294 		pb->cpu_cnt = libbpf_num_possible_cpus();
13295 		if (pb->cpu_cnt < 0) {
13296 			err = pb->cpu_cnt;
13297 			goto error;
13298 		}
13299 		if (map.max_entries && map.max_entries < pb->cpu_cnt)
13300 			pb->cpu_cnt = map.max_entries;
13301 	}
13302 
13303 	pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
13304 	if (!pb->events) {
13305 		err = -ENOMEM;
13306 		pr_warn("failed to allocate events: out of memory\n");
13307 		goto error;
13308 	}
13309 	pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
13310 	if (!pb->cpu_bufs) {
13311 		err = -ENOMEM;
13312 		pr_warn("failed to allocate buffers: out of memory\n");
13313 		goto error;
13314 	}
13315 
13316 	err = parse_cpu_mask_file(online_cpus_file, &online, &n);
13317 	if (err) {
13318 		pr_warn("failed to get online CPU mask: %d\n", err);
13319 		goto error;
13320 	}
13321 
13322 	for (i = 0, j = 0; i < pb->cpu_cnt; i++) {
13323 		struct perf_cpu_buf *cpu_buf;
13324 		int cpu, map_key;
13325 
13326 		cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
13327 		map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
13328 
13329 		/* in case user didn't explicitly requested particular CPUs to
13330 		 * be attached to, skip offline/not present CPUs
13331 		 */
13332 		if (p->cpu_cnt <= 0 && (cpu >= n || !online[cpu]))
13333 			continue;
13334 
13335 		cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
13336 		if (IS_ERR(cpu_buf)) {
13337 			err = PTR_ERR(cpu_buf);
13338 			goto error;
13339 		}
13340 
13341 		pb->cpu_bufs[j] = cpu_buf;
13342 
13343 		err = bpf_map_update_elem(pb->map_fd, &map_key,
13344 					  &cpu_buf->fd, 0);
13345 		if (err) {
13346 			err = -errno;
13347 			pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
13348 				cpu, map_key, cpu_buf->fd,
13349 				libbpf_strerror_r(err, msg, sizeof(msg)));
13350 			goto error;
13351 		}
13352 
13353 		pb->events[j].events = EPOLLIN;
13354 		pb->events[j].data.ptr = cpu_buf;
13355 		if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
13356 			      &pb->events[j]) < 0) {
13357 			err = -errno;
13358 			pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
13359 				cpu, cpu_buf->fd,
13360 				libbpf_strerror_r(err, msg, sizeof(msg)));
13361 			goto error;
13362 		}
13363 		j++;
13364 	}
13365 	pb->cpu_cnt = j;
13366 	free(online);
13367 
13368 	return pb;
13369 
13370 error:
13371 	free(online);
13372 	if (pb)
13373 		perf_buffer__free(pb);
13374 	return ERR_PTR(err);
13375 }
13376 
13377 struct perf_sample_raw {
13378 	struct perf_event_header header;
13379 	uint32_t size;
13380 	char data[];
13381 };
13382 
13383 struct perf_sample_lost {
13384 	struct perf_event_header header;
13385 	uint64_t id;
13386 	uint64_t lost;
13387 	uint64_t sample_id;
13388 };
13389 
13390 static enum bpf_perf_event_ret
13391 perf_buffer__process_record(struct perf_event_header *e, void *ctx)
13392 {
13393 	struct perf_cpu_buf *cpu_buf = ctx;
13394 	struct perf_buffer *pb = cpu_buf->pb;
13395 	void *data = e;
13396 
13397 	/* user wants full control over parsing perf event */
13398 	if (pb->event_cb)
13399 		return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
13400 
13401 	switch (e->type) {
13402 	case PERF_RECORD_SAMPLE: {
13403 		struct perf_sample_raw *s = data;
13404 
13405 		if (pb->sample_cb)
13406 			pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
13407 		break;
13408 	}
13409 	case PERF_RECORD_LOST: {
13410 		struct perf_sample_lost *s = data;
13411 
13412 		if (pb->lost_cb)
13413 			pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
13414 		break;
13415 	}
13416 	default:
13417 		pr_warn("unknown perf sample type %d\n", e->type);
13418 		return LIBBPF_PERF_EVENT_ERROR;
13419 	}
13420 	return LIBBPF_PERF_EVENT_CONT;
13421 }
13422 
13423 static int perf_buffer__process_records(struct perf_buffer *pb,
13424 					struct perf_cpu_buf *cpu_buf)
13425 {
13426 	enum bpf_perf_event_ret ret;
13427 
13428 	ret = perf_event_read_simple(cpu_buf->base, pb->mmap_size,
13429 				     pb->page_size, &cpu_buf->buf,
13430 				     &cpu_buf->buf_size,
13431 				     perf_buffer__process_record, cpu_buf);
13432 	if (ret != LIBBPF_PERF_EVENT_CONT)
13433 		return ret;
13434 	return 0;
13435 }
13436 
13437 int perf_buffer__epoll_fd(const struct perf_buffer *pb)
13438 {
13439 	return pb->epoll_fd;
13440 }
13441 
13442 int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
13443 {
13444 	int i, cnt, err;
13445 
13446 	cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
13447 	if (cnt < 0)
13448 		return -errno;
13449 
13450 	for (i = 0; i < cnt; i++) {
13451 		struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
13452 
13453 		err = perf_buffer__process_records(pb, cpu_buf);
13454 		if (err) {
13455 			pr_warn("error while processing records: %d\n", err);
13456 			return libbpf_err(err);
13457 		}
13458 	}
13459 	return cnt;
13460 }
13461 
13462 /* Return number of PERF_EVENT_ARRAY map slots set up by this perf_buffer
13463  * manager.
13464  */
13465 size_t perf_buffer__buffer_cnt(const struct perf_buffer *pb)
13466 {
13467 	return pb->cpu_cnt;
13468 }
13469 
13470 /*
13471  * Return perf_event FD of a ring buffer in *buf_idx* slot of
13472  * PERF_EVENT_ARRAY BPF map. This FD can be polled for new data using
13473  * select()/poll()/epoll() Linux syscalls.
13474  */
13475 int perf_buffer__buffer_fd(const struct perf_buffer *pb, size_t buf_idx)
13476 {
13477 	struct perf_cpu_buf *cpu_buf;
13478 
13479 	if (buf_idx >= pb->cpu_cnt)
13480 		return libbpf_err(-EINVAL);
13481 
13482 	cpu_buf = pb->cpu_bufs[buf_idx];
13483 	if (!cpu_buf)
13484 		return libbpf_err(-ENOENT);
13485 
13486 	return cpu_buf->fd;
13487 }
13488 
13489 int perf_buffer__buffer(struct perf_buffer *pb, int buf_idx, void **buf, size_t *buf_size)
13490 {
13491 	struct perf_cpu_buf *cpu_buf;
13492 
13493 	if (buf_idx >= pb->cpu_cnt)
13494 		return libbpf_err(-EINVAL);
13495 
13496 	cpu_buf = pb->cpu_bufs[buf_idx];
13497 	if (!cpu_buf)
13498 		return libbpf_err(-ENOENT);
13499 
13500 	*buf = cpu_buf->base;
13501 	*buf_size = pb->mmap_size;
13502 	return 0;
13503 }
13504 
13505 /*
13506  * Consume data from perf ring buffer corresponding to slot *buf_idx* in
13507  * PERF_EVENT_ARRAY BPF map without waiting/polling. If there is no data to
13508  * consume, do nothing and return success.
13509  * Returns:
13510  *   - 0 on success;
13511  *   - <0 on failure.
13512  */
13513 int perf_buffer__consume_buffer(struct perf_buffer *pb, size_t buf_idx)
13514 {
13515 	struct perf_cpu_buf *cpu_buf;
13516 
13517 	if (buf_idx >= pb->cpu_cnt)
13518 		return libbpf_err(-EINVAL);
13519 
13520 	cpu_buf = pb->cpu_bufs[buf_idx];
13521 	if (!cpu_buf)
13522 		return libbpf_err(-ENOENT);
13523 
13524 	return perf_buffer__process_records(pb, cpu_buf);
13525 }
13526 
13527 int perf_buffer__consume(struct perf_buffer *pb)
13528 {
13529 	int i, err;
13530 
13531 	for (i = 0; i < pb->cpu_cnt; i++) {
13532 		struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
13533 
13534 		if (!cpu_buf)
13535 			continue;
13536 
13537 		err = perf_buffer__process_records(pb, cpu_buf);
13538 		if (err) {
13539 			pr_warn("perf_buffer: failed to process records in buffer #%d: %d\n", i, err);
13540 			return libbpf_err(err);
13541 		}
13542 	}
13543 	return 0;
13544 }
13545 
13546 int bpf_program__set_attach_target(struct bpf_program *prog,
13547 				   int attach_prog_fd,
13548 				   const char *attach_func_name)
13549 {
13550 	int btf_obj_fd = 0, btf_id = 0, err;
13551 
13552 	if (!prog || attach_prog_fd < 0)
13553 		return libbpf_err(-EINVAL);
13554 
13555 	if (prog->obj->loaded)
13556 		return libbpf_err(-EINVAL);
13557 
13558 	if (attach_prog_fd && !attach_func_name) {
13559 		/* remember attach_prog_fd and let bpf_program__load() find
13560 		 * BTF ID during the program load
13561 		 */
13562 		prog->attach_prog_fd = attach_prog_fd;
13563 		return 0;
13564 	}
13565 
13566 	if (attach_prog_fd) {
13567 		btf_id = libbpf_find_prog_btf_id(attach_func_name,
13568 						 attach_prog_fd);
13569 		if (btf_id < 0)
13570 			return libbpf_err(btf_id);
13571 	} else {
13572 		if (!attach_func_name)
13573 			return libbpf_err(-EINVAL);
13574 
13575 		/* load btf_vmlinux, if not yet */
13576 		err = bpf_object__load_vmlinux_btf(prog->obj, true);
13577 		if (err)
13578 			return libbpf_err(err);
13579 		err = find_kernel_btf_id(prog->obj, attach_func_name,
13580 					 prog->expected_attach_type,
13581 					 &btf_obj_fd, &btf_id);
13582 		if (err)
13583 			return libbpf_err(err);
13584 	}
13585 
13586 	prog->attach_btf_id = btf_id;
13587 	prog->attach_btf_obj_fd = btf_obj_fd;
13588 	prog->attach_prog_fd = attach_prog_fd;
13589 	return 0;
13590 }
13591 
13592 int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz)
13593 {
13594 	int err = 0, n, len, start, end = -1;
13595 	bool *tmp;
13596 
13597 	*mask = NULL;
13598 	*mask_sz = 0;
13599 
13600 	/* Each sub string separated by ',' has format \d+-\d+ or \d+ */
13601 	while (*s) {
13602 		if (*s == ',' || *s == '\n') {
13603 			s++;
13604 			continue;
13605 		}
13606 		n = sscanf(s, "%d%n-%d%n", &start, &len, &end, &len);
13607 		if (n <= 0 || n > 2) {
13608 			pr_warn("Failed to get CPU range %s: %d\n", s, n);
13609 			err = -EINVAL;
13610 			goto cleanup;
13611 		} else if (n == 1) {
13612 			end = start;
13613 		}
13614 		if (start < 0 || start > end) {
13615 			pr_warn("Invalid CPU range [%d,%d] in %s\n",
13616 				start, end, s);
13617 			err = -EINVAL;
13618 			goto cleanup;
13619 		}
13620 		tmp = realloc(*mask, end + 1);
13621 		if (!tmp) {
13622 			err = -ENOMEM;
13623 			goto cleanup;
13624 		}
13625 		*mask = tmp;
13626 		memset(tmp + *mask_sz, 0, start - *mask_sz);
13627 		memset(tmp + start, 1, end - start + 1);
13628 		*mask_sz = end + 1;
13629 		s += len;
13630 	}
13631 	if (!*mask_sz) {
13632 		pr_warn("Empty CPU range\n");
13633 		return -EINVAL;
13634 	}
13635 	return 0;
13636 cleanup:
13637 	free(*mask);
13638 	*mask = NULL;
13639 	return err;
13640 }
13641 
13642 int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz)
13643 {
13644 	int fd, err = 0, len;
13645 	char buf[128];
13646 
13647 	fd = open(fcpu, O_RDONLY | O_CLOEXEC);
13648 	if (fd < 0) {
13649 		err = -errno;
13650 		pr_warn("Failed to open cpu mask file %s: %d\n", fcpu, err);
13651 		return err;
13652 	}
13653 	len = read(fd, buf, sizeof(buf));
13654 	close(fd);
13655 	if (len <= 0) {
13656 		err = len ? -errno : -EINVAL;
13657 		pr_warn("Failed to read cpu mask from %s: %d\n", fcpu, err);
13658 		return err;
13659 	}
13660 	if (len >= sizeof(buf)) {
13661 		pr_warn("CPU mask is too big in file %s\n", fcpu);
13662 		return -E2BIG;
13663 	}
13664 	buf[len] = '\0';
13665 
13666 	return parse_cpu_mask_str(buf, mask, mask_sz);
13667 }
13668 
13669 int libbpf_num_possible_cpus(void)
13670 {
13671 	static const char *fcpu = "/sys/devices/system/cpu/possible";
13672 	static int cpus;
13673 	int err, n, i, tmp_cpus;
13674 	bool *mask;
13675 
13676 	tmp_cpus = READ_ONCE(cpus);
13677 	if (tmp_cpus > 0)
13678 		return tmp_cpus;
13679 
13680 	err = parse_cpu_mask_file(fcpu, &mask, &n);
13681 	if (err)
13682 		return libbpf_err(err);
13683 
13684 	tmp_cpus = 0;
13685 	for (i = 0; i < n; i++) {
13686 		if (mask[i])
13687 			tmp_cpus++;
13688 	}
13689 	free(mask);
13690 
13691 	WRITE_ONCE(cpus, tmp_cpus);
13692 	return tmp_cpus;
13693 }
13694 
13695 static int populate_skeleton_maps(const struct bpf_object *obj,
13696 				  struct bpf_map_skeleton *maps,
13697 				  size_t map_cnt)
13698 {
13699 	int i;
13700 
13701 	for (i = 0; i < map_cnt; i++) {
13702 		struct bpf_map **map = maps[i].map;
13703 		const char *name = maps[i].name;
13704 		void **mmaped = maps[i].mmaped;
13705 
13706 		*map = bpf_object__find_map_by_name(obj, name);
13707 		if (!*map) {
13708 			pr_warn("failed to find skeleton map '%s'\n", name);
13709 			return -ESRCH;
13710 		}
13711 
13712 		/* externs shouldn't be pre-setup from user code */
13713 		if (mmaped && (*map)->libbpf_type != LIBBPF_MAP_KCONFIG)
13714 			*mmaped = (*map)->mmaped;
13715 	}
13716 	return 0;
13717 }
13718 
13719 static int populate_skeleton_progs(const struct bpf_object *obj,
13720 				   struct bpf_prog_skeleton *progs,
13721 				   size_t prog_cnt)
13722 {
13723 	int i;
13724 
13725 	for (i = 0; i < prog_cnt; i++) {
13726 		struct bpf_program **prog = progs[i].prog;
13727 		const char *name = progs[i].name;
13728 
13729 		*prog = bpf_object__find_program_by_name(obj, name);
13730 		if (!*prog) {
13731 			pr_warn("failed to find skeleton program '%s'\n", name);
13732 			return -ESRCH;
13733 		}
13734 	}
13735 	return 0;
13736 }
13737 
13738 int bpf_object__open_skeleton(struct bpf_object_skeleton *s,
13739 			      const struct bpf_object_open_opts *opts)
13740 {
13741 	DECLARE_LIBBPF_OPTS(bpf_object_open_opts, skel_opts,
13742 		.object_name = s->name,
13743 	);
13744 	struct bpf_object *obj;
13745 	int err;
13746 
13747 	/* Attempt to preserve opts->object_name, unless overriden by user
13748 	 * explicitly. Overwriting object name for skeletons is discouraged,
13749 	 * as it breaks global data maps, because they contain object name
13750 	 * prefix as their own map name prefix. When skeleton is generated,
13751 	 * bpftool is making an assumption that this name will stay the same.
13752 	 */
13753 	if (opts) {
13754 		memcpy(&skel_opts, opts, sizeof(*opts));
13755 		if (!opts->object_name)
13756 			skel_opts.object_name = s->name;
13757 	}
13758 
13759 	obj = bpf_object__open_mem(s->data, s->data_sz, &skel_opts);
13760 	err = libbpf_get_error(obj);
13761 	if (err) {
13762 		pr_warn("failed to initialize skeleton BPF object '%s': %d\n",
13763 			s->name, err);
13764 		return libbpf_err(err);
13765 	}
13766 
13767 	*s->obj = obj;
13768 	err = populate_skeleton_maps(obj, s->maps, s->map_cnt);
13769 	if (err) {
13770 		pr_warn("failed to populate skeleton maps for '%s': %d\n", s->name, err);
13771 		return libbpf_err(err);
13772 	}
13773 
13774 	err = populate_skeleton_progs(obj, s->progs, s->prog_cnt);
13775 	if (err) {
13776 		pr_warn("failed to populate skeleton progs for '%s': %d\n", s->name, err);
13777 		return libbpf_err(err);
13778 	}
13779 
13780 	return 0;
13781 }
13782 
13783 int bpf_object__open_subskeleton(struct bpf_object_subskeleton *s)
13784 {
13785 	int err, len, var_idx, i;
13786 	const char *var_name;
13787 	const struct bpf_map *map;
13788 	struct btf *btf;
13789 	__u32 map_type_id;
13790 	const struct btf_type *map_type, *var_type;
13791 	const struct bpf_var_skeleton *var_skel;
13792 	struct btf_var_secinfo *var;
13793 
13794 	if (!s->obj)
13795 		return libbpf_err(-EINVAL);
13796 
13797 	btf = bpf_object__btf(s->obj);
13798 	if (!btf) {
13799 		pr_warn("subskeletons require BTF at runtime (object %s)\n",
13800 			bpf_object__name(s->obj));
13801 		return libbpf_err(-errno);
13802 	}
13803 
13804 	err = populate_skeleton_maps(s->obj, s->maps, s->map_cnt);
13805 	if (err) {
13806 		pr_warn("failed to populate subskeleton maps: %d\n", err);
13807 		return libbpf_err(err);
13808 	}
13809 
13810 	err = populate_skeleton_progs(s->obj, s->progs, s->prog_cnt);
13811 	if (err) {
13812 		pr_warn("failed to populate subskeleton maps: %d\n", err);
13813 		return libbpf_err(err);
13814 	}
13815 
13816 	for (var_idx = 0; var_idx < s->var_cnt; var_idx++) {
13817 		var_skel = &s->vars[var_idx];
13818 		map = *var_skel->map;
13819 		map_type_id = bpf_map__btf_value_type_id(map);
13820 		map_type = btf__type_by_id(btf, map_type_id);
13821 
13822 		if (!btf_is_datasec(map_type)) {
13823 			pr_warn("type for map '%1$s' is not a datasec: %2$s",
13824 				bpf_map__name(map),
13825 				__btf_kind_str(btf_kind(map_type)));
13826 			return libbpf_err(-EINVAL);
13827 		}
13828 
13829 		len = btf_vlen(map_type);
13830 		var = btf_var_secinfos(map_type);
13831 		for (i = 0; i < len; i++, var++) {
13832 			var_type = btf__type_by_id(btf, var->type);
13833 			var_name = btf__name_by_offset(btf, var_type->name_off);
13834 			if (strcmp(var_name, var_skel->name) == 0) {
13835 				*var_skel->addr = map->mmaped + var->offset;
13836 				break;
13837 			}
13838 		}
13839 	}
13840 	return 0;
13841 }
13842 
13843 void bpf_object__destroy_subskeleton(struct bpf_object_subskeleton *s)
13844 {
13845 	if (!s)
13846 		return;
13847 	free(s->maps);
13848 	free(s->progs);
13849 	free(s->vars);
13850 	free(s);
13851 }
13852 
13853 int bpf_object__load_skeleton(struct bpf_object_skeleton *s)
13854 {
13855 	int i, err;
13856 
13857 	err = bpf_object__load(*s->obj);
13858 	if (err) {
13859 		pr_warn("failed to load BPF skeleton '%s': %d\n", s->name, err);
13860 		return libbpf_err(err);
13861 	}
13862 
13863 	for (i = 0; i < s->map_cnt; i++) {
13864 		struct bpf_map *map = *s->maps[i].map;
13865 		size_t mmap_sz = bpf_map_mmap_sz(map);
13866 		int prot, map_fd = map->fd;
13867 		void **mmaped = s->maps[i].mmaped;
13868 
13869 		if (!mmaped)
13870 			continue;
13871 
13872 		if (!(map->def.map_flags & BPF_F_MMAPABLE)) {
13873 			*mmaped = NULL;
13874 			continue;
13875 		}
13876 
13877 		if (map->def.type == BPF_MAP_TYPE_ARENA) {
13878 			*mmaped = map->mmaped;
13879 			continue;
13880 		}
13881 
13882 		if (map->def.map_flags & BPF_F_RDONLY_PROG)
13883 			prot = PROT_READ;
13884 		else
13885 			prot = PROT_READ | PROT_WRITE;
13886 
13887 		/* Remap anonymous mmap()-ed "map initialization image" as
13888 		 * a BPF map-backed mmap()-ed memory, but preserving the same
13889 		 * memory address. This will cause kernel to change process'
13890 		 * page table to point to a different piece of kernel memory,
13891 		 * but from userspace point of view memory address (and its
13892 		 * contents, being identical at this point) will stay the
13893 		 * same. This mapping will be released by bpf_object__close()
13894 		 * as per normal clean up procedure, so we don't need to worry
13895 		 * about it from skeleton's clean up perspective.
13896 		 */
13897 		*mmaped = mmap(map->mmaped, mmap_sz, prot, MAP_SHARED | MAP_FIXED, map_fd, 0);
13898 		if (*mmaped == MAP_FAILED) {
13899 			err = -errno;
13900 			*mmaped = NULL;
13901 			pr_warn("failed to re-mmap() map '%s': %d\n",
13902 				 bpf_map__name(map), err);
13903 			return libbpf_err(err);
13904 		}
13905 	}
13906 
13907 	return 0;
13908 }
13909 
13910 int bpf_object__attach_skeleton(struct bpf_object_skeleton *s)
13911 {
13912 	int i, err;
13913 
13914 	for (i = 0; i < s->prog_cnt; i++) {
13915 		struct bpf_program *prog = *s->progs[i].prog;
13916 		struct bpf_link **link = s->progs[i].link;
13917 
13918 		if (!prog->autoload || !prog->autoattach)
13919 			continue;
13920 
13921 		/* auto-attaching not supported for this program */
13922 		if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
13923 			continue;
13924 
13925 		/* if user already set the link manually, don't attempt auto-attach */
13926 		if (*link)
13927 			continue;
13928 
13929 		err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, link);
13930 		if (err) {
13931 			pr_warn("prog '%s': failed to auto-attach: %d\n",
13932 				bpf_program__name(prog), err);
13933 			return libbpf_err(err);
13934 		}
13935 
13936 		/* It's possible that for some SEC() definitions auto-attach
13937 		 * is supported in some cases (e.g., if definition completely
13938 		 * specifies target information), but is not in other cases.
13939 		 * SEC("uprobe") is one such case. If user specified target
13940 		 * binary and function name, such BPF program can be
13941 		 * auto-attached. But if not, it shouldn't trigger skeleton's
13942 		 * attach to fail. It should just be skipped.
13943 		 * attach_fn signals such case with returning 0 (no error) and
13944 		 * setting link to NULL.
13945 		 */
13946 	}
13947 
13948 	return 0;
13949 }
13950 
13951 void bpf_object__detach_skeleton(struct bpf_object_skeleton *s)
13952 {
13953 	int i;
13954 
13955 	for (i = 0; i < s->prog_cnt; i++) {
13956 		struct bpf_link **link = s->progs[i].link;
13957 
13958 		bpf_link__destroy(*link);
13959 		*link = NULL;
13960 	}
13961 }
13962 
13963 void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s)
13964 {
13965 	if (!s)
13966 		return;
13967 
13968 	if (s->progs)
13969 		bpf_object__detach_skeleton(s);
13970 	if (s->obj)
13971 		bpf_object__close(*s->obj);
13972 	free(s->maps);
13973 	free(s->progs);
13974 	free(s);
13975 }
13976