xref: /linux/tools/lib/bpf/libbpf.c (revision fcab107abe1ab5be9dbe874baa722372da8f4f73)
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 MAX_EVENT_NAME_LEN	64
64 
65 #define BPF_FS_DEFAULT_PATH "/sys/fs/bpf"
66 
67 #define BPF_INSN_SZ (sizeof(struct bpf_insn))
68 
69 /* vsprintf() in __base_pr() uses nonliteral format string. It may break
70  * compilation if user enables corresponding warning. Disable it explicitly.
71  */
72 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
73 
74 #define __printf(a, b)	__attribute__((format(printf, a, b)))
75 
76 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj);
77 static bool prog_is_subprog(const struct bpf_object *obj, const struct bpf_program *prog);
78 static int map_set_def_max_entries(struct bpf_map *map);
79 
80 static const char * const attach_type_name[] = {
81 	[BPF_CGROUP_INET_INGRESS]	= "cgroup_inet_ingress",
82 	[BPF_CGROUP_INET_EGRESS]	= "cgroup_inet_egress",
83 	[BPF_CGROUP_INET_SOCK_CREATE]	= "cgroup_inet_sock_create",
84 	[BPF_CGROUP_INET_SOCK_RELEASE]	= "cgroup_inet_sock_release",
85 	[BPF_CGROUP_SOCK_OPS]		= "cgroup_sock_ops",
86 	[BPF_CGROUP_DEVICE]		= "cgroup_device",
87 	[BPF_CGROUP_INET4_BIND]		= "cgroup_inet4_bind",
88 	[BPF_CGROUP_INET6_BIND]		= "cgroup_inet6_bind",
89 	[BPF_CGROUP_INET4_CONNECT]	= "cgroup_inet4_connect",
90 	[BPF_CGROUP_INET6_CONNECT]	= "cgroup_inet6_connect",
91 	[BPF_CGROUP_UNIX_CONNECT]       = "cgroup_unix_connect",
92 	[BPF_CGROUP_INET4_POST_BIND]	= "cgroup_inet4_post_bind",
93 	[BPF_CGROUP_INET6_POST_BIND]	= "cgroup_inet6_post_bind",
94 	[BPF_CGROUP_INET4_GETPEERNAME]	= "cgroup_inet4_getpeername",
95 	[BPF_CGROUP_INET6_GETPEERNAME]	= "cgroup_inet6_getpeername",
96 	[BPF_CGROUP_UNIX_GETPEERNAME]	= "cgroup_unix_getpeername",
97 	[BPF_CGROUP_INET4_GETSOCKNAME]	= "cgroup_inet4_getsockname",
98 	[BPF_CGROUP_INET6_GETSOCKNAME]	= "cgroup_inet6_getsockname",
99 	[BPF_CGROUP_UNIX_GETSOCKNAME]	= "cgroup_unix_getsockname",
100 	[BPF_CGROUP_UDP4_SENDMSG]	= "cgroup_udp4_sendmsg",
101 	[BPF_CGROUP_UDP6_SENDMSG]	= "cgroup_udp6_sendmsg",
102 	[BPF_CGROUP_UNIX_SENDMSG]	= "cgroup_unix_sendmsg",
103 	[BPF_CGROUP_SYSCTL]		= "cgroup_sysctl",
104 	[BPF_CGROUP_UDP4_RECVMSG]	= "cgroup_udp4_recvmsg",
105 	[BPF_CGROUP_UDP6_RECVMSG]	= "cgroup_udp6_recvmsg",
106 	[BPF_CGROUP_UNIX_RECVMSG]	= "cgroup_unix_recvmsg",
107 	[BPF_CGROUP_GETSOCKOPT]		= "cgroup_getsockopt",
108 	[BPF_CGROUP_SETSOCKOPT]		= "cgroup_setsockopt",
109 	[BPF_SK_SKB_STREAM_PARSER]	= "sk_skb_stream_parser",
110 	[BPF_SK_SKB_STREAM_VERDICT]	= "sk_skb_stream_verdict",
111 	[BPF_SK_SKB_VERDICT]		= "sk_skb_verdict",
112 	[BPF_SK_MSG_VERDICT]		= "sk_msg_verdict",
113 	[BPF_LIRC_MODE2]		= "lirc_mode2",
114 	[BPF_FLOW_DISSECTOR]		= "flow_dissector",
115 	[BPF_TRACE_RAW_TP]		= "trace_raw_tp",
116 	[BPF_TRACE_FENTRY]		= "trace_fentry",
117 	[BPF_TRACE_FEXIT]		= "trace_fexit",
118 	[BPF_MODIFY_RETURN]		= "modify_return",
119 	[BPF_LSM_MAC]			= "lsm_mac",
120 	[BPF_LSM_CGROUP]		= "lsm_cgroup",
121 	[BPF_SK_LOOKUP]			= "sk_lookup",
122 	[BPF_TRACE_ITER]		= "trace_iter",
123 	[BPF_XDP_DEVMAP]		= "xdp_devmap",
124 	[BPF_XDP_CPUMAP]		= "xdp_cpumap",
125 	[BPF_XDP]			= "xdp",
126 	[BPF_SK_REUSEPORT_SELECT]	= "sk_reuseport_select",
127 	[BPF_SK_REUSEPORT_SELECT_OR_MIGRATE]	= "sk_reuseport_select_or_migrate",
128 	[BPF_PERF_EVENT]		= "perf_event",
129 	[BPF_TRACE_KPROBE_MULTI]	= "trace_kprobe_multi",
130 	[BPF_STRUCT_OPS]		= "struct_ops",
131 	[BPF_NETFILTER]			= "netfilter",
132 	[BPF_TCX_INGRESS]		= "tcx_ingress",
133 	[BPF_TCX_EGRESS]		= "tcx_egress",
134 	[BPF_TRACE_UPROBE_MULTI]	= "trace_uprobe_multi",
135 	[BPF_NETKIT_PRIMARY]		= "netkit_primary",
136 	[BPF_NETKIT_PEER]		= "netkit_peer",
137 	[BPF_TRACE_KPROBE_SESSION]	= "trace_kprobe_session",
138 	[BPF_TRACE_UPROBE_SESSION]	= "trace_uprobe_session",
139 };
140 
141 static const char * const link_type_name[] = {
142 	[BPF_LINK_TYPE_UNSPEC]			= "unspec",
143 	[BPF_LINK_TYPE_RAW_TRACEPOINT]		= "raw_tracepoint",
144 	[BPF_LINK_TYPE_TRACING]			= "tracing",
145 	[BPF_LINK_TYPE_CGROUP]			= "cgroup",
146 	[BPF_LINK_TYPE_ITER]			= "iter",
147 	[BPF_LINK_TYPE_NETNS]			= "netns",
148 	[BPF_LINK_TYPE_XDP]			= "xdp",
149 	[BPF_LINK_TYPE_PERF_EVENT]		= "perf_event",
150 	[BPF_LINK_TYPE_KPROBE_MULTI]		= "kprobe_multi",
151 	[BPF_LINK_TYPE_STRUCT_OPS]		= "struct_ops",
152 	[BPF_LINK_TYPE_NETFILTER]		= "netfilter",
153 	[BPF_LINK_TYPE_TCX]			= "tcx",
154 	[BPF_LINK_TYPE_UPROBE_MULTI]		= "uprobe_multi",
155 	[BPF_LINK_TYPE_NETKIT]			= "netkit",
156 	[BPF_LINK_TYPE_SOCKMAP]			= "sockmap",
157 };
158 
159 static const char * const map_type_name[] = {
160 	[BPF_MAP_TYPE_UNSPEC]			= "unspec",
161 	[BPF_MAP_TYPE_HASH]			= "hash",
162 	[BPF_MAP_TYPE_ARRAY]			= "array",
163 	[BPF_MAP_TYPE_PROG_ARRAY]		= "prog_array",
164 	[BPF_MAP_TYPE_PERF_EVENT_ARRAY]		= "perf_event_array",
165 	[BPF_MAP_TYPE_PERCPU_HASH]		= "percpu_hash",
166 	[BPF_MAP_TYPE_PERCPU_ARRAY]		= "percpu_array",
167 	[BPF_MAP_TYPE_STACK_TRACE]		= "stack_trace",
168 	[BPF_MAP_TYPE_CGROUP_ARRAY]		= "cgroup_array",
169 	[BPF_MAP_TYPE_LRU_HASH]			= "lru_hash",
170 	[BPF_MAP_TYPE_LRU_PERCPU_HASH]		= "lru_percpu_hash",
171 	[BPF_MAP_TYPE_LPM_TRIE]			= "lpm_trie",
172 	[BPF_MAP_TYPE_ARRAY_OF_MAPS]		= "array_of_maps",
173 	[BPF_MAP_TYPE_HASH_OF_MAPS]		= "hash_of_maps",
174 	[BPF_MAP_TYPE_DEVMAP]			= "devmap",
175 	[BPF_MAP_TYPE_DEVMAP_HASH]		= "devmap_hash",
176 	[BPF_MAP_TYPE_SOCKMAP]			= "sockmap",
177 	[BPF_MAP_TYPE_CPUMAP]			= "cpumap",
178 	[BPF_MAP_TYPE_XSKMAP]			= "xskmap",
179 	[BPF_MAP_TYPE_SOCKHASH]			= "sockhash",
180 	[BPF_MAP_TYPE_CGROUP_STORAGE]		= "cgroup_storage",
181 	[BPF_MAP_TYPE_REUSEPORT_SOCKARRAY]	= "reuseport_sockarray",
182 	[BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE]	= "percpu_cgroup_storage",
183 	[BPF_MAP_TYPE_QUEUE]			= "queue",
184 	[BPF_MAP_TYPE_STACK]			= "stack",
185 	[BPF_MAP_TYPE_SK_STORAGE]		= "sk_storage",
186 	[BPF_MAP_TYPE_STRUCT_OPS]		= "struct_ops",
187 	[BPF_MAP_TYPE_RINGBUF]			= "ringbuf",
188 	[BPF_MAP_TYPE_INODE_STORAGE]		= "inode_storage",
189 	[BPF_MAP_TYPE_TASK_STORAGE]		= "task_storage",
190 	[BPF_MAP_TYPE_BLOOM_FILTER]		= "bloom_filter",
191 	[BPF_MAP_TYPE_USER_RINGBUF]             = "user_ringbuf",
192 	[BPF_MAP_TYPE_CGRP_STORAGE]		= "cgrp_storage",
193 	[BPF_MAP_TYPE_ARENA]			= "arena",
194 };
195 
196 static const char * const prog_type_name[] = {
197 	[BPF_PROG_TYPE_UNSPEC]			= "unspec",
198 	[BPF_PROG_TYPE_SOCKET_FILTER]		= "socket_filter",
199 	[BPF_PROG_TYPE_KPROBE]			= "kprobe",
200 	[BPF_PROG_TYPE_SCHED_CLS]		= "sched_cls",
201 	[BPF_PROG_TYPE_SCHED_ACT]		= "sched_act",
202 	[BPF_PROG_TYPE_TRACEPOINT]		= "tracepoint",
203 	[BPF_PROG_TYPE_XDP]			= "xdp",
204 	[BPF_PROG_TYPE_PERF_EVENT]		= "perf_event",
205 	[BPF_PROG_TYPE_CGROUP_SKB]		= "cgroup_skb",
206 	[BPF_PROG_TYPE_CGROUP_SOCK]		= "cgroup_sock",
207 	[BPF_PROG_TYPE_LWT_IN]			= "lwt_in",
208 	[BPF_PROG_TYPE_LWT_OUT]			= "lwt_out",
209 	[BPF_PROG_TYPE_LWT_XMIT]		= "lwt_xmit",
210 	[BPF_PROG_TYPE_SOCK_OPS]		= "sock_ops",
211 	[BPF_PROG_TYPE_SK_SKB]			= "sk_skb",
212 	[BPF_PROG_TYPE_CGROUP_DEVICE]		= "cgroup_device",
213 	[BPF_PROG_TYPE_SK_MSG]			= "sk_msg",
214 	[BPF_PROG_TYPE_RAW_TRACEPOINT]		= "raw_tracepoint",
215 	[BPF_PROG_TYPE_CGROUP_SOCK_ADDR]	= "cgroup_sock_addr",
216 	[BPF_PROG_TYPE_LWT_SEG6LOCAL]		= "lwt_seg6local",
217 	[BPF_PROG_TYPE_LIRC_MODE2]		= "lirc_mode2",
218 	[BPF_PROG_TYPE_SK_REUSEPORT]		= "sk_reuseport",
219 	[BPF_PROG_TYPE_FLOW_DISSECTOR]		= "flow_dissector",
220 	[BPF_PROG_TYPE_CGROUP_SYSCTL]		= "cgroup_sysctl",
221 	[BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE]	= "raw_tracepoint_writable",
222 	[BPF_PROG_TYPE_CGROUP_SOCKOPT]		= "cgroup_sockopt",
223 	[BPF_PROG_TYPE_TRACING]			= "tracing",
224 	[BPF_PROG_TYPE_STRUCT_OPS]		= "struct_ops",
225 	[BPF_PROG_TYPE_EXT]			= "ext",
226 	[BPF_PROG_TYPE_LSM]			= "lsm",
227 	[BPF_PROG_TYPE_SK_LOOKUP]		= "sk_lookup",
228 	[BPF_PROG_TYPE_SYSCALL]			= "syscall",
229 	[BPF_PROG_TYPE_NETFILTER]		= "netfilter",
230 };
231 
232 static int __base_pr(enum libbpf_print_level level, const char *format,
233 		     va_list args)
234 {
235 	const char *env_var = "LIBBPF_LOG_LEVEL";
236 	static enum libbpf_print_level min_level = LIBBPF_INFO;
237 	static bool initialized;
238 
239 	if (!initialized) {
240 		char *verbosity;
241 
242 		initialized = true;
243 		verbosity = getenv(env_var);
244 		if (verbosity) {
245 			if (strcasecmp(verbosity, "warn") == 0)
246 				min_level = LIBBPF_WARN;
247 			else if (strcasecmp(verbosity, "debug") == 0)
248 				min_level = LIBBPF_DEBUG;
249 			else if (strcasecmp(verbosity, "info") == 0)
250 				min_level = LIBBPF_INFO;
251 			else
252 				fprintf(stderr, "libbpf: unrecognized '%s' envvar value: '%s', should be one of 'warn', 'debug', or 'info'.\n",
253 					env_var, verbosity);
254 		}
255 	}
256 
257 	/* if too verbose, skip logging  */
258 	if (level > min_level)
259 		return 0;
260 
261 	return vfprintf(stderr, format, args);
262 }
263 
264 static libbpf_print_fn_t __libbpf_pr = __base_pr;
265 
266 libbpf_print_fn_t libbpf_set_print(libbpf_print_fn_t fn)
267 {
268 	libbpf_print_fn_t old_print_fn;
269 
270 	old_print_fn = __atomic_exchange_n(&__libbpf_pr, fn, __ATOMIC_RELAXED);
271 
272 	return old_print_fn;
273 }
274 
275 __printf(2, 3)
276 void libbpf_print(enum libbpf_print_level level, const char *format, ...)
277 {
278 	va_list args;
279 	int old_errno;
280 	libbpf_print_fn_t print_fn;
281 
282 	print_fn = __atomic_load_n(&__libbpf_pr, __ATOMIC_RELAXED);
283 	if (!print_fn)
284 		return;
285 
286 	old_errno = errno;
287 
288 	va_start(args, format);
289 	print_fn(level, format, args);
290 	va_end(args);
291 
292 	errno = old_errno;
293 }
294 
295 static void pr_perm_msg(int err)
296 {
297 	struct rlimit limit;
298 	char buf[100];
299 
300 	if (err != -EPERM || geteuid() != 0)
301 		return;
302 
303 	err = getrlimit(RLIMIT_MEMLOCK, &limit);
304 	if (err)
305 		return;
306 
307 	if (limit.rlim_cur == RLIM_INFINITY)
308 		return;
309 
310 	if (limit.rlim_cur < 1024)
311 		snprintf(buf, sizeof(buf), "%zu bytes", (size_t)limit.rlim_cur);
312 	else if (limit.rlim_cur < 1024*1024)
313 		snprintf(buf, sizeof(buf), "%.1f KiB", (double)limit.rlim_cur / 1024);
314 	else
315 		snprintf(buf, sizeof(buf), "%.1f MiB", (double)limit.rlim_cur / (1024*1024));
316 
317 	pr_warn("permission error while running as root; try raising 'ulimit -l'? current value: %s\n",
318 		buf);
319 }
320 
321 #define STRERR_BUFSIZE  128
322 
323 /* Copied from tools/perf/util/util.h */
324 #ifndef zfree
325 # define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
326 #endif
327 
328 #ifndef zclose
329 # define zclose(fd) ({			\
330 	int ___err = 0;			\
331 	if ((fd) >= 0)			\
332 		___err = close((fd));	\
333 	fd = -1;			\
334 	___err; })
335 #endif
336 
337 static inline __u64 ptr_to_u64(const void *ptr)
338 {
339 	return (__u64) (unsigned long) ptr;
340 }
341 
342 int libbpf_set_strict_mode(enum libbpf_strict_mode mode)
343 {
344 	/* as of v1.0 libbpf_set_strict_mode() is a no-op */
345 	return 0;
346 }
347 
348 __u32 libbpf_major_version(void)
349 {
350 	return LIBBPF_MAJOR_VERSION;
351 }
352 
353 __u32 libbpf_minor_version(void)
354 {
355 	return LIBBPF_MINOR_VERSION;
356 }
357 
358 const char *libbpf_version_string(void)
359 {
360 #define __S(X) #X
361 #define _S(X) __S(X)
362 	return  "v" _S(LIBBPF_MAJOR_VERSION) "." _S(LIBBPF_MINOR_VERSION);
363 #undef _S
364 #undef __S
365 }
366 
367 enum reloc_type {
368 	RELO_LD64,
369 	RELO_CALL,
370 	RELO_DATA,
371 	RELO_EXTERN_LD64,
372 	RELO_EXTERN_CALL,
373 	RELO_SUBPROG_ADDR,
374 	RELO_CORE,
375 };
376 
377 struct reloc_desc {
378 	enum reloc_type type;
379 	int insn_idx;
380 	union {
381 		const struct bpf_core_relo *core_relo; /* used when type == RELO_CORE */
382 		struct {
383 			int map_idx;
384 			int sym_off;
385 			int ext_idx;
386 		};
387 	};
388 };
389 
390 /* stored as sec_def->cookie for all libbpf-supported SEC()s */
391 enum sec_def_flags {
392 	SEC_NONE = 0,
393 	/* expected_attach_type is optional, if kernel doesn't support that */
394 	SEC_EXP_ATTACH_OPT = 1,
395 	/* legacy, only used by libbpf_get_type_names() and
396 	 * libbpf_attach_type_by_name(), not used by libbpf itself at all.
397 	 * This used to be associated with cgroup (and few other) BPF programs
398 	 * that were attachable through BPF_PROG_ATTACH command. Pretty
399 	 * meaningless nowadays, though.
400 	 */
401 	SEC_ATTACHABLE = 2,
402 	SEC_ATTACHABLE_OPT = SEC_ATTACHABLE | SEC_EXP_ATTACH_OPT,
403 	/* attachment target is specified through BTF ID in either kernel or
404 	 * other BPF program's BTF object
405 	 */
406 	SEC_ATTACH_BTF = 4,
407 	/* BPF program type allows sleeping/blocking in kernel */
408 	SEC_SLEEPABLE = 8,
409 	/* BPF program support non-linear XDP buffer */
410 	SEC_XDP_FRAGS = 16,
411 	/* Setup proper attach type for usdt probes. */
412 	SEC_USDT = 32,
413 };
414 
415 struct bpf_sec_def {
416 	char *sec;
417 	enum bpf_prog_type prog_type;
418 	enum bpf_attach_type expected_attach_type;
419 	long cookie;
420 	int handler_id;
421 
422 	libbpf_prog_setup_fn_t prog_setup_fn;
423 	libbpf_prog_prepare_load_fn_t prog_prepare_load_fn;
424 	libbpf_prog_attach_fn_t prog_attach_fn;
425 };
426 
427 /*
428  * bpf_prog should be a better name but it has been used in
429  * linux/filter.h.
430  */
431 struct bpf_program {
432 	char *name;
433 	char *sec_name;
434 	size_t sec_idx;
435 	const struct bpf_sec_def *sec_def;
436 	/* this program's instruction offset (in number of instructions)
437 	 * within its containing ELF section
438 	 */
439 	size_t sec_insn_off;
440 	/* number of original instructions in ELF section belonging to this
441 	 * program, not taking into account subprogram instructions possible
442 	 * appended later during relocation
443 	 */
444 	size_t sec_insn_cnt;
445 	/* Offset (in number of instructions) of the start of instruction
446 	 * belonging to this BPF program  within its containing main BPF
447 	 * program. For the entry-point (main) BPF program, this is always
448 	 * zero. For a sub-program, this gets reset before each of main BPF
449 	 * programs are processed and relocated and is used to determined
450 	 * whether sub-program was already appended to the main program, and
451 	 * if yes, at which instruction offset.
452 	 */
453 	size_t sub_insn_off;
454 
455 	/* instructions that belong to BPF program; insns[0] is located at
456 	 * sec_insn_off instruction within its ELF section in ELF file, so
457 	 * when mapping ELF file instruction index to the local instruction,
458 	 * one needs to subtract sec_insn_off; and vice versa.
459 	 */
460 	struct bpf_insn *insns;
461 	/* actual number of instruction in this BPF program's image; for
462 	 * entry-point BPF programs this includes the size of main program
463 	 * itself plus all the used sub-programs, appended at the end
464 	 */
465 	size_t insns_cnt;
466 
467 	struct reloc_desc *reloc_desc;
468 	int nr_reloc;
469 
470 	/* BPF verifier log settings */
471 	char *log_buf;
472 	size_t log_size;
473 	__u32 log_level;
474 
475 	struct bpf_object *obj;
476 
477 	int fd;
478 	bool autoload;
479 	bool autoattach;
480 	bool sym_global;
481 	bool mark_btf_static;
482 	enum bpf_prog_type type;
483 	enum bpf_attach_type expected_attach_type;
484 	int exception_cb_idx;
485 
486 	int prog_ifindex;
487 	__u32 attach_btf_obj_fd;
488 	__u32 attach_btf_id;
489 	__u32 attach_prog_fd;
490 
491 	void *func_info;
492 	__u32 func_info_rec_size;
493 	__u32 func_info_cnt;
494 
495 	void *line_info;
496 	__u32 line_info_rec_size;
497 	__u32 line_info_cnt;
498 	__u32 prog_flags;
499 };
500 
501 struct bpf_struct_ops {
502 	struct bpf_program **progs;
503 	__u32 *kern_func_off;
504 	/* e.g. struct tcp_congestion_ops in bpf_prog's btf format */
505 	void *data;
506 	/* e.g. struct bpf_struct_ops_tcp_congestion_ops in
507 	 *      btf_vmlinux's format.
508 	 * struct bpf_struct_ops_tcp_congestion_ops {
509 	 *	[... some other kernel fields ...]
510 	 *	struct tcp_congestion_ops data;
511 	 * }
512 	 * kern_vdata-size == sizeof(struct bpf_struct_ops_tcp_congestion_ops)
513 	 * bpf_map__init_kern_struct_ops() will populate the "kern_vdata"
514 	 * from "data".
515 	 */
516 	void *kern_vdata;
517 	__u32 type_id;
518 };
519 
520 #define DATA_SEC ".data"
521 #define BSS_SEC ".bss"
522 #define RODATA_SEC ".rodata"
523 #define KCONFIG_SEC ".kconfig"
524 #define KSYMS_SEC ".ksyms"
525 #define STRUCT_OPS_SEC ".struct_ops"
526 #define STRUCT_OPS_LINK_SEC ".struct_ops.link"
527 #define ARENA_SEC ".addr_space.1"
528 
529 enum libbpf_map_type {
530 	LIBBPF_MAP_UNSPEC,
531 	LIBBPF_MAP_DATA,
532 	LIBBPF_MAP_BSS,
533 	LIBBPF_MAP_RODATA,
534 	LIBBPF_MAP_KCONFIG,
535 };
536 
537 struct bpf_map_def {
538 	unsigned int type;
539 	unsigned int key_size;
540 	unsigned int value_size;
541 	unsigned int max_entries;
542 	unsigned int map_flags;
543 };
544 
545 struct bpf_map {
546 	struct bpf_object *obj;
547 	char *name;
548 	/* real_name is defined for special internal maps (.rodata*,
549 	 * .data*, .bss, .kconfig) and preserves their original ELF section
550 	 * name. This is important to be able to find corresponding BTF
551 	 * DATASEC information.
552 	 */
553 	char *real_name;
554 	int fd;
555 	int sec_idx;
556 	size_t sec_offset;
557 	int map_ifindex;
558 	int inner_map_fd;
559 	struct bpf_map_def def;
560 	__u32 numa_node;
561 	__u32 btf_var_idx;
562 	int mod_btf_fd;
563 	__u32 btf_key_type_id;
564 	__u32 btf_value_type_id;
565 	__u32 btf_vmlinux_value_type_id;
566 	enum libbpf_map_type libbpf_type;
567 	void *mmaped;
568 	struct bpf_struct_ops *st_ops;
569 	struct bpf_map *inner_map;
570 	void **init_slots;
571 	int init_slots_sz;
572 	char *pin_path;
573 	bool pinned;
574 	bool reused;
575 	bool autocreate;
576 	bool autoattach;
577 	__u64 map_extra;
578 };
579 
580 enum extern_type {
581 	EXT_UNKNOWN,
582 	EXT_KCFG,
583 	EXT_KSYM,
584 };
585 
586 enum kcfg_type {
587 	KCFG_UNKNOWN,
588 	KCFG_CHAR,
589 	KCFG_BOOL,
590 	KCFG_INT,
591 	KCFG_TRISTATE,
592 	KCFG_CHAR_ARR,
593 };
594 
595 struct extern_desc {
596 	enum extern_type type;
597 	int sym_idx;
598 	int btf_id;
599 	int sec_btf_id;
600 	const char *name;
601 	char *essent_name;
602 	bool is_set;
603 	bool is_weak;
604 	union {
605 		struct {
606 			enum kcfg_type type;
607 			int sz;
608 			int align;
609 			int data_off;
610 			bool is_signed;
611 		} kcfg;
612 		struct {
613 			unsigned long long addr;
614 
615 			/* target btf_id of the corresponding kernel var. */
616 			int kernel_btf_obj_fd;
617 			int kernel_btf_id;
618 
619 			/* local btf_id of the ksym extern's type. */
620 			__u32 type_id;
621 			/* BTF fd index to be patched in for insn->off, this is
622 			 * 0 for vmlinux BTF, index in obj->fd_array for module
623 			 * BTF
624 			 */
625 			__s16 btf_fd_idx;
626 		} ksym;
627 	};
628 };
629 
630 struct module_btf {
631 	struct btf *btf;
632 	char *name;
633 	__u32 id;
634 	int fd;
635 	int fd_array_idx;
636 };
637 
638 enum sec_type {
639 	SEC_UNUSED = 0,
640 	SEC_RELO,
641 	SEC_BSS,
642 	SEC_DATA,
643 	SEC_RODATA,
644 	SEC_ST_OPS,
645 };
646 
647 struct elf_sec_desc {
648 	enum sec_type sec_type;
649 	Elf64_Shdr *shdr;
650 	Elf_Data *data;
651 };
652 
653 struct elf_state {
654 	int fd;
655 	const void *obj_buf;
656 	size_t obj_buf_sz;
657 	Elf *elf;
658 	Elf64_Ehdr *ehdr;
659 	Elf_Data *symbols;
660 	Elf_Data *arena_data;
661 	size_t shstrndx; /* section index for section name strings */
662 	size_t strtabidx;
663 	struct elf_sec_desc *secs;
664 	size_t sec_cnt;
665 	int btf_maps_shndx;
666 	__u32 btf_maps_sec_btf_id;
667 	int text_shndx;
668 	int symbols_shndx;
669 	bool has_st_ops;
670 	int arena_data_shndx;
671 };
672 
673 struct usdt_manager;
674 
675 enum bpf_object_state {
676 	OBJ_OPEN,
677 	OBJ_PREPARED,
678 	OBJ_LOADED,
679 };
680 
681 struct bpf_object {
682 	char name[BPF_OBJ_NAME_LEN];
683 	char license[64];
684 	__u32 kern_version;
685 
686 	enum bpf_object_state state;
687 	struct bpf_program *programs;
688 	size_t nr_programs;
689 	struct bpf_map *maps;
690 	size_t nr_maps;
691 	size_t maps_cap;
692 
693 	char *kconfig;
694 	struct extern_desc *externs;
695 	int nr_extern;
696 	int kconfig_map_idx;
697 
698 	bool has_subcalls;
699 	bool has_rodata;
700 
701 	struct bpf_gen *gen_loader;
702 
703 	/* Information when doing ELF related work. Only valid if efile.elf is not NULL */
704 	struct elf_state efile;
705 
706 	unsigned char byteorder;
707 
708 	struct btf *btf;
709 	struct btf_ext *btf_ext;
710 
711 	/* Parse and load BTF vmlinux if any of the programs in the object need
712 	 * it at load time.
713 	 */
714 	struct btf *btf_vmlinux;
715 	/* Path to the custom BTF to be used for BPF CO-RE relocations as an
716 	 * override for vmlinux BTF.
717 	 */
718 	char *btf_custom_path;
719 	/* vmlinux BTF override for CO-RE relocations */
720 	struct btf *btf_vmlinux_override;
721 	/* Lazily initialized kernel module BTFs */
722 	struct module_btf *btf_modules;
723 	bool btf_modules_loaded;
724 	size_t btf_module_cnt;
725 	size_t btf_module_cap;
726 
727 	/* optional log settings passed to BPF_BTF_LOAD and BPF_PROG_LOAD commands */
728 	char *log_buf;
729 	size_t log_size;
730 	__u32 log_level;
731 
732 	int *fd_array;
733 	size_t fd_array_cap;
734 	size_t fd_array_cnt;
735 
736 	struct usdt_manager *usdt_man;
737 
738 	struct bpf_map *arena_map;
739 	void *arena_data;
740 	size_t arena_data_sz;
741 
742 	struct kern_feature_cache *feat_cache;
743 	char *token_path;
744 	int token_fd;
745 
746 	char path[];
747 };
748 
749 static const char *elf_sym_str(const struct bpf_object *obj, size_t off);
750 static const char *elf_sec_str(const struct bpf_object *obj, size_t off);
751 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx);
752 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name);
753 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn);
754 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn);
755 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn);
756 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx);
757 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx);
758 
759 void bpf_program__unload(struct bpf_program *prog)
760 {
761 	if (!prog)
762 		return;
763 
764 	zclose(prog->fd);
765 
766 	zfree(&prog->func_info);
767 	zfree(&prog->line_info);
768 }
769 
770 static void bpf_program__exit(struct bpf_program *prog)
771 {
772 	if (!prog)
773 		return;
774 
775 	bpf_program__unload(prog);
776 	zfree(&prog->name);
777 	zfree(&prog->sec_name);
778 	zfree(&prog->insns);
779 	zfree(&prog->reloc_desc);
780 
781 	prog->nr_reloc = 0;
782 	prog->insns_cnt = 0;
783 	prog->sec_idx = -1;
784 }
785 
786 static bool insn_is_subprog_call(const struct bpf_insn *insn)
787 {
788 	return BPF_CLASS(insn->code) == BPF_JMP &&
789 	       BPF_OP(insn->code) == BPF_CALL &&
790 	       BPF_SRC(insn->code) == BPF_K &&
791 	       insn->src_reg == BPF_PSEUDO_CALL &&
792 	       insn->dst_reg == 0 &&
793 	       insn->off == 0;
794 }
795 
796 static bool is_call_insn(const struct bpf_insn *insn)
797 {
798 	return insn->code == (BPF_JMP | BPF_CALL);
799 }
800 
801 static bool insn_is_pseudo_func(struct bpf_insn *insn)
802 {
803 	return is_ldimm64_insn(insn) && insn->src_reg == BPF_PSEUDO_FUNC;
804 }
805 
806 static int
807 bpf_object__init_prog(struct bpf_object *obj, struct bpf_program *prog,
808 		      const char *name, size_t sec_idx, const char *sec_name,
809 		      size_t sec_off, void *insn_data, size_t insn_data_sz)
810 {
811 	if (insn_data_sz == 0 || insn_data_sz % BPF_INSN_SZ || sec_off % BPF_INSN_SZ) {
812 		pr_warn("sec '%s': corrupted program '%s', offset %zu, size %zu\n",
813 			sec_name, name, sec_off, insn_data_sz);
814 		return -EINVAL;
815 	}
816 
817 	memset(prog, 0, sizeof(*prog));
818 	prog->obj = obj;
819 
820 	prog->sec_idx = sec_idx;
821 	prog->sec_insn_off = sec_off / BPF_INSN_SZ;
822 	prog->sec_insn_cnt = insn_data_sz / BPF_INSN_SZ;
823 	/* insns_cnt can later be increased by appending used subprograms */
824 	prog->insns_cnt = prog->sec_insn_cnt;
825 
826 	prog->type = BPF_PROG_TYPE_UNSPEC;
827 	prog->fd = -1;
828 	prog->exception_cb_idx = -1;
829 
830 	/* libbpf's convention for SEC("?abc...") is that it's just like
831 	 * SEC("abc...") but the corresponding bpf_program starts out with
832 	 * autoload set to false.
833 	 */
834 	if (sec_name[0] == '?') {
835 		prog->autoload = false;
836 		/* from now on forget there was ? in section name */
837 		sec_name++;
838 	} else {
839 		prog->autoload = true;
840 	}
841 
842 	prog->autoattach = true;
843 
844 	/* inherit object's log_level */
845 	prog->log_level = obj->log_level;
846 
847 	prog->sec_name = strdup(sec_name);
848 	if (!prog->sec_name)
849 		goto errout;
850 
851 	prog->name = strdup(name);
852 	if (!prog->name)
853 		goto errout;
854 
855 	prog->insns = malloc(insn_data_sz);
856 	if (!prog->insns)
857 		goto errout;
858 	memcpy(prog->insns, insn_data, insn_data_sz);
859 
860 	return 0;
861 errout:
862 	pr_warn("sec '%s': failed to allocate memory for prog '%s'\n", sec_name, name);
863 	bpf_program__exit(prog);
864 	return -ENOMEM;
865 }
866 
867 static int
868 bpf_object__add_programs(struct bpf_object *obj, Elf_Data *sec_data,
869 			 const char *sec_name, int sec_idx)
870 {
871 	Elf_Data *symbols = obj->efile.symbols;
872 	struct bpf_program *prog, *progs;
873 	void *data = sec_data->d_buf;
874 	size_t sec_sz = sec_data->d_size, sec_off, prog_sz, nr_syms;
875 	int nr_progs, err, i;
876 	const char *name;
877 	Elf64_Sym *sym;
878 
879 	progs = obj->programs;
880 	nr_progs = obj->nr_programs;
881 	nr_syms = symbols->d_size / sizeof(Elf64_Sym);
882 
883 	for (i = 0; i < nr_syms; i++) {
884 		sym = elf_sym_by_idx(obj, i);
885 
886 		if (sym->st_shndx != sec_idx)
887 			continue;
888 		if (ELF64_ST_TYPE(sym->st_info) != STT_FUNC)
889 			continue;
890 
891 		prog_sz = sym->st_size;
892 		sec_off = sym->st_value;
893 
894 		name = elf_sym_str(obj, sym->st_name);
895 		if (!name) {
896 			pr_warn("sec '%s': failed to get symbol name for offset %zu\n",
897 				sec_name, sec_off);
898 			return -LIBBPF_ERRNO__FORMAT;
899 		}
900 
901 		if (sec_off + prog_sz > sec_sz || sec_off + prog_sz < sec_off) {
902 			pr_warn("sec '%s': program at offset %zu crosses section boundary\n",
903 				sec_name, sec_off);
904 			return -LIBBPF_ERRNO__FORMAT;
905 		}
906 
907 		if (sec_idx != obj->efile.text_shndx && ELF64_ST_BIND(sym->st_info) == STB_LOCAL) {
908 			pr_warn("sec '%s': program '%s' is static and not supported\n", sec_name, name);
909 			return -ENOTSUP;
910 		}
911 
912 		pr_debug("sec '%s': found program '%s' at insn offset %zu (%zu bytes), code size %zu insns (%zu bytes)\n",
913 			 sec_name, name, sec_off / BPF_INSN_SZ, sec_off, prog_sz / BPF_INSN_SZ, prog_sz);
914 
915 		progs = libbpf_reallocarray(progs, nr_progs + 1, sizeof(*progs));
916 		if (!progs) {
917 			/*
918 			 * In this case the original obj->programs
919 			 * is still valid, so don't need special treat for
920 			 * bpf_close_object().
921 			 */
922 			pr_warn("sec '%s': failed to alloc memory for new program '%s'\n",
923 				sec_name, name);
924 			return -ENOMEM;
925 		}
926 		obj->programs = progs;
927 
928 		prog = &progs[nr_progs];
929 
930 		err = bpf_object__init_prog(obj, prog, name, sec_idx, sec_name,
931 					    sec_off, data + sec_off, prog_sz);
932 		if (err)
933 			return err;
934 
935 		if (ELF64_ST_BIND(sym->st_info) != STB_LOCAL)
936 			prog->sym_global = true;
937 
938 		/* if function is a global/weak symbol, but has restricted
939 		 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF FUNC
940 		 * as static to enable more permissive BPF verification mode
941 		 * with more outside context available to BPF verifier
942 		 */
943 		if (prog->sym_global && (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
944 		    || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL))
945 			prog->mark_btf_static = true;
946 
947 		nr_progs++;
948 		obj->nr_programs = nr_progs;
949 	}
950 
951 	return 0;
952 }
953 
954 static void bpf_object_bswap_progs(struct bpf_object *obj)
955 {
956 	struct bpf_program *prog = obj->programs;
957 	struct bpf_insn *insn;
958 	int p, i;
959 
960 	for (p = 0; p < obj->nr_programs; p++, prog++) {
961 		insn = prog->insns;
962 		for (i = 0; i < prog->insns_cnt; i++, insn++)
963 			bpf_insn_bswap(insn);
964 	}
965 	pr_debug("converted %zu BPF programs to native byte order\n", obj->nr_programs);
966 }
967 
968 static const struct btf_member *
969 find_member_by_offset(const struct btf_type *t, __u32 bit_offset)
970 {
971 	struct btf_member *m;
972 	int i;
973 
974 	for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
975 		if (btf_member_bit_offset(t, i) == bit_offset)
976 			return m;
977 	}
978 
979 	return NULL;
980 }
981 
982 static const struct btf_member *
983 find_member_by_name(const struct btf *btf, const struct btf_type *t,
984 		    const char *name)
985 {
986 	struct btf_member *m;
987 	int i;
988 
989 	for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
990 		if (!strcmp(btf__name_by_offset(btf, m->name_off), name))
991 			return m;
992 	}
993 
994 	return NULL;
995 }
996 
997 static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
998 			    __u16 kind, struct btf **res_btf,
999 			    struct module_btf **res_mod_btf);
1000 
1001 #define STRUCT_OPS_VALUE_PREFIX "bpf_struct_ops_"
1002 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
1003 				   const char *name, __u32 kind);
1004 
1005 static int
1006 find_struct_ops_kern_types(struct bpf_object *obj, const char *tname_raw,
1007 			   struct module_btf **mod_btf,
1008 			   const struct btf_type **type, __u32 *type_id,
1009 			   const struct btf_type **vtype, __u32 *vtype_id,
1010 			   const struct btf_member **data_member)
1011 {
1012 	const struct btf_type *kern_type, *kern_vtype;
1013 	const struct btf_member *kern_data_member;
1014 	struct btf *btf = NULL;
1015 	__s32 kern_vtype_id, kern_type_id;
1016 	char tname[256];
1017 	__u32 i;
1018 
1019 	snprintf(tname, sizeof(tname), "%.*s",
1020 		 (int)bpf_core_essential_name_len(tname_raw), tname_raw);
1021 
1022 	kern_type_id = find_ksym_btf_id(obj, tname, BTF_KIND_STRUCT,
1023 					&btf, mod_btf);
1024 	if (kern_type_id < 0) {
1025 		pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n",
1026 			tname);
1027 		return kern_type_id;
1028 	}
1029 	kern_type = btf__type_by_id(btf, kern_type_id);
1030 
1031 	/* Find the corresponding "map_value" type that will be used
1032 	 * in map_update(BPF_MAP_TYPE_STRUCT_OPS).  For example,
1033 	 * find "struct bpf_struct_ops_tcp_congestion_ops" from the
1034 	 * btf_vmlinux.
1035 	 */
1036 	kern_vtype_id = find_btf_by_prefix_kind(btf, STRUCT_OPS_VALUE_PREFIX,
1037 						tname, BTF_KIND_STRUCT);
1038 	if (kern_vtype_id < 0) {
1039 		pr_warn("struct_ops init_kern: struct %s%s is not found in kernel BTF\n",
1040 			STRUCT_OPS_VALUE_PREFIX, tname);
1041 		return kern_vtype_id;
1042 	}
1043 	kern_vtype = btf__type_by_id(btf, kern_vtype_id);
1044 
1045 	/* Find "struct tcp_congestion_ops" from
1046 	 * struct bpf_struct_ops_tcp_congestion_ops {
1047 	 *	[ ... ]
1048 	 *	struct tcp_congestion_ops data;
1049 	 * }
1050 	 */
1051 	kern_data_member = btf_members(kern_vtype);
1052 	for (i = 0; i < btf_vlen(kern_vtype); i++, kern_data_member++) {
1053 		if (kern_data_member->type == kern_type_id)
1054 			break;
1055 	}
1056 	if (i == btf_vlen(kern_vtype)) {
1057 		pr_warn("struct_ops init_kern: struct %s data is not found in struct %s%s\n",
1058 			tname, STRUCT_OPS_VALUE_PREFIX, tname);
1059 		return -EINVAL;
1060 	}
1061 
1062 	*type = kern_type;
1063 	*type_id = kern_type_id;
1064 	*vtype = kern_vtype;
1065 	*vtype_id = kern_vtype_id;
1066 	*data_member = kern_data_member;
1067 
1068 	return 0;
1069 }
1070 
1071 static bool bpf_map__is_struct_ops(const struct bpf_map *map)
1072 {
1073 	return map->def.type == BPF_MAP_TYPE_STRUCT_OPS;
1074 }
1075 
1076 static bool is_valid_st_ops_program(struct bpf_object *obj,
1077 				    const struct bpf_program *prog)
1078 {
1079 	int i;
1080 
1081 	for (i = 0; i < obj->nr_programs; i++) {
1082 		if (&obj->programs[i] == prog)
1083 			return prog->type == BPF_PROG_TYPE_STRUCT_OPS;
1084 	}
1085 
1086 	return false;
1087 }
1088 
1089 /* For each struct_ops program P, referenced from some struct_ops map M,
1090  * enable P.autoload if there are Ms for which M.autocreate is true,
1091  * disable P.autoload if for all Ms M.autocreate is false.
1092  * Don't change P.autoload for programs that are not referenced from any maps.
1093  */
1094 static int bpf_object_adjust_struct_ops_autoload(struct bpf_object *obj)
1095 {
1096 	struct bpf_program *prog, *slot_prog;
1097 	struct bpf_map *map;
1098 	int i, j, k, vlen;
1099 
1100 	for (i = 0; i < obj->nr_programs; ++i) {
1101 		int should_load = false;
1102 		int use_cnt = 0;
1103 
1104 		prog = &obj->programs[i];
1105 		if (prog->type != BPF_PROG_TYPE_STRUCT_OPS)
1106 			continue;
1107 
1108 		for (j = 0; j < obj->nr_maps; ++j) {
1109 			const struct btf_type *type;
1110 
1111 			map = &obj->maps[j];
1112 			if (!bpf_map__is_struct_ops(map))
1113 				continue;
1114 
1115 			type = btf__type_by_id(obj->btf, map->st_ops->type_id);
1116 			vlen = btf_vlen(type);
1117 			for (k = 0; k < vlen; ++k) {
1118 				slot_prog = map->st_ops->progs[k];
1119 				if (prog != slot_prog)
1120 					continue;
1121 
1122 				use_cnt++;
1123 				if (map->autocreate)
1124 					should_load = true;
1125 			}
1126 		}
1127 		if (use_cnt)
1128 			prog->autoload = should_load;
1129 	}
1130 
1131 	return 0;
1132 }
1133 
1134 /* Init the map's fields that depend on kern_btf */
1135 static int bpf_map__init_kern_struct_ops(struct bpf_map *map)
1136 {
1137 	const struct btf_member *member, *kern_member, *kern_data_member;
1138 	const struct btf_type *type, *kern_type, *kern_vtype;
1139 	__u32 i, kern_type_id, kern_vtype_id, kern_data_off;
1140 	struct bpf_object *obj = map->obj;
1141 	const struct btf *btf = obj->btf;
1142 	struct bpf_struct_ops *st_ops;
1143 	const struct btf *kern_btf;
1144 	struct module_btf *mod_btf = NULL;
1145 	void *data, *kern_data;
1146 	const char *tname;
1147 	int err;
1148 
1149 	st_ops = map->st_ops;
1150 	type = btf__type_by_id(btf, st_ops->type_id);
1151 	tname = btf__name_by_offset(btf, type->name_off);
1152 	err = find_struct_ops_kern_types(obj, tname, &mod_btf,
1153 					 &kern_type, &kern_type_id,
1154 					 &kern_vtype, &kern_vtype_id,
1155 					 &kern_data_member);
1156 	if (err)
1157 		return err;
1158 
1159 	kern_btf = mod_btf ? mod_btf->btf : obj->btf_vmlinux;
1160 
1161 	pr_debug("struct_ops init_kern %s: type_id:%u kern_type_id:%u kern_vtype_id:%u\n",
1162 		 map->name, st_ops->type_id, kern_type_id, kern_vtype_id);
1163 
1164 	map->mod_btf_fd = mod_btf ? mod_btf->fd : -1;
1165 	map->def.value_size = kern_vtype->size;
1166 	map->btf_vmlinux_value_type_id = kern_vtype_id;
1167 
1168 	st_ops->kern_vdata = calloc(1, kern_vtype->size);
1169 	if (!st_ops->kern_vdata)
1170 		return -ENOMEM;
1171 
1172 	data = st_ops->data;
1173 	kern_data_off = kern_data_member->offset / 8;
1174 	kern_data = st_ops->kern_vdata + kern_data_off;
1175 
1176 	member = btf_members(type);
1177 	for (i = 0; i < btf_vlen(type); i++, member++) {
1178 		const struct btf_type *mtype, *kern_mtype;
1179 		__u32 mtype_id, kern_mtype_id;
1180 		void *mdata, *kern_mdata;
1181 		struct bpf_program *prog;
1182 		__s64 msize, kern_msize;
1183 		__u32 moff, kern_moff;
1184 		__u32 kern_member_idx;
1185 		const char *mname;
1186 
1187 		mname = btf__name_by_offset(btf, member->name_off);
1188 		moff = member->offset / 8;
1189 		mdata = data + moff;
1190 		msize = btf__resolve_size(btf, member->type);
1191 		if (msize < 0) {
1192 			pr_warn("struct_ops init_kern %s: failed to resolve the size of member %s\n",
1193 				map->name, mname);
1194 			return msize;
1195 		}
1196 
1197 		kern_member = find_member_by_name(kern_btf, kern_type, mname);
1198 		if (!kern_member) {
1199 			if (!libbpf_is_mem_zeroed(mdata, msize)) {
1200 				pr_warn("struct_ops init_kern %s: Cannot find member %s in kernel BTF\n",
1201 					map->name, mname);
1202 				return -ENOTSUP;
1203 			}
1204 
1205 			if (st_ops->progs[i]) {
1206 				/* If we had declaratively set struct_ops callback, we need to
1207 				 * force its autoload to false, because it doesn't have
1208 				 * a chance of succeeding from POV of the current struct_ops map.
1209 				 * If this program is still referenced somewhere else, though,
1210 				 * then bpf_object_adjust_struct_ops_autoload() will update its
1211 				 * autoload accordingly.
1212 				 */
1213 				st_ops->progs[i]->autoload = false;
1214 				st_ops->progs[i] = NULL;
1215 			}
1216 
1217 			/* Skip all-zero/NULL fields if they are not present in the kernel BTF */
1218 			pr_info("struct_ops %s: member %s not found in kernel, skipping it as it's set to zero\n",
1219 				map->name, mname);
1220 			continue;
1221 		}
1222 
1223 		kern_member_idx = kern_member - btf_members(kern_type);
1224 		if (btf_member_bitfield_size(type, i) ||
1225 		    btf_member_bitfield_size(kern_type, kern_member_idx)) {
1226 			pr_warn("struct_ops init_kern %s: bitfield %s is not supported\n",
1227 				map->name, mname);
1228 			return -ENOTSUP;
1229 		}
1230 
1231 		kern_moff = kern_member->offset / 8;
1232 		kern_mdata = kern_data + kern_moff;
1233 
1234 		mtype = skip_mods_and_typedefs(btf, member->type, &mtype_id);
1235 		kern_mtype = skip_mods_and_typedefs(kern_btf, kern_member->type,
1236 						    &kern_mtype_id);
1237 		if (BTF_INFO_KIND(mtype->info) !=
1238 		    BTF_INFO_KIND(kern_mtype->info)) {
1239 			pr_warn("struct_ops init_kern %s: Unmatched member type %s %u != %u(kernel)\n",
1240 				map->name, mname, BTF_INFO_KIND(mtype->info),
1241 				BTF_INFO_KIND(kern_mtype->info));
1242 			return -ENOTSUP;
1243 		}
1244 
1245 		if (btf_is_ptr(mtype)) {
1246 			prog = *(void **)mdata;
1247 			/* just like for !kern_member case above, reset declaratively
1248 			 * set (at compile time) program's autload to false,
1249 			 * if user replaced it with another program or NULL
1250 			 */
1251 			if (st_ops->progs[i] && st_ops->progs[i] != prog)
1252 				st_ops->progs[i]->autoload = false;
1253 
1254 			/* Update the value from the shadow type */
1255 			st_ops->progs[i] = prog;
1256 			if (!prog)
1257 				continue;
1258 
1259 			if (!is_valid_st_ops_program(obj, prog)) {
1260 				pr_warn("struct_ops init_kern %s: member %s is not a struct_ops program\n",
1261 					map->name, mname);
1262 				return -ENOTSUP;
1263 			}
1264 
1265 			kern_mtype = skip_mods_and_typedefs(kern_btf,
1266 							    kern_mtype->type,
1267 							    &kern_mtype_id);
1268 
1269 			/* mtype->type must be a func_proto which was
1270 			 * guaranteed in bpf_object__collect_st_ops_relos(),
1271 			 * so only check kern_mtype for func_proto here.
1272 			 */
1273 			if (!btf_is_func_proto(kern_mtype)) {
1274 				pr_warn("struct_ops init_kern %s: kernel member %s is not a func ptr\n",
1275 					map->name, mname);
1276 				return -ENOTSUP;
1277 			}
1278 
1279 			if (mod_btf)
1280 				prog->attach_btf_obj_fd = mod_btf->fd;
1281 
1282 			/* if we haven't yet processed this BPF program, record proper
1283 			 * attach_btf_id and member_idx
1284 			 */
1285 			if (!prog->attach_btf_id) {
1286 				prog->attach_btf_id = kern_type_id;
1287 				prog->expected_attach_type = kern_member_idx;
1288 			}
1289 
1290 			/* struct_ops BPF prog can be re-used between multiple
1291 			 * .struct_ops & .struct_ops.link as long as it's the
1292 			 * same struct_ops struct definition and the same
1293 			 * function pointer field
1294 			 */
1295 			if (prog->attach_btf_id != kern_type_id) {
1296 				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",
1297 					map->name, mname, prog->name, prog->sec_name, prog->type,
1298 					prog->attach_btf_id, kern_type_id);
1299 				return -EINVAL;
1300 			}
1301 			if (prog->expected_attach_type != kern_member_idx) {
1302 				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",
1303 					map->name, mname, prog->name, prog->sec_name, prog->type,
1304 					prog->expected_attach_type, kern_member_idx);
1305 				return -EINVAL;
1306 			}
1307 
1308 			st_ops->kern_func_off[i] = kern_data_off + kern_moff;
1309 
1310 			pr_debug("struct_ops init_kern %s: func ptr %s is set to prog %s from data(+%u) to kern_data(+%u)\n",
1311 				 map->name, mname, prog->name, moff,
1312 				 kern_moff);
1313 
1314 			continue;
1315 		}
1316 
1317 		kern_msize = btf__resolve_size(kern_btf, kern_mtype_id);
1318 		if (kern_msize < 0 || msize != kern_msize) {
1319 			pr_warn("struct_ops init_kern %s: Error in size of member %s: %zd != %zd(kernel)\n",
1320 				map->name, mname, (ssize_t)msize,
1321 				(ssize_t)kern_msize);
1322 			return -ENOTSUP;
1323 		}
1324 
1325 		pr_debug("struct_ops init_kern %s: copy %s %u bytes from data(+%u) to kern_data(+%u)\n",
1326 			 map->name, mname, (unsigned int)msize,
1327 			 moff, kern_moff);
1328 		memcpy(kern_mdata, mdata, msize);
1329 	}
1330 
1331 	return 0;
1332 }
1333 
1334 static int bpf_object__init_kern_struct_ops_maps(struct bpf_object *obj)
1335 {
1336 	struct bpf_map *map;
1337 	size_t i;
1338 	int err;
1339 
1340 	for (i = 0; i < obj->nr_maps; i++) {
1341 		map = &obj->maps[i];
1342 
1343 		if (!bpf_map__is_struct_ops(map))
1344 			continue;
1345 
1346 		if (!map->autocreate)
1347 			continue;
1348 
1349 		err = bpf_map__init_kern_struct_ops(map);
1350 		if (err)
1351 			return err;
1352 	}
1353 
1354 	return 0;
1355 }
1356 
1357 static int init_struct_ops_maps(struct bpf_object *obj, const char *sec_name,
1358 				int shndx, Elf_Data *data)
1359 {
1360 	const struct btf_type *type, *datasec;
1361 	const struct btf_var_secinfo *vsi;
1362 	struct bpf_struct_ops *st_ops;
1363 	const char *tname, *var_name;
1364 	__s32 type_id, datasec_id;
1365 	const struct btf *btf;
1366 	struct bpf_map *map;
1367 	__u32 i;
1368 
1369 	if (shndx == -1)
1370 		return 0;
1371 
1372 	btf = obj->btf;
1373 	datasec_id = btf__find_by_name_kind(btf, sec_name,
1374 					    BTF_KIND_DATASEC);
1375 	if (datasec_id < 0) {
1376 		pr_warn("struct_ops init: DATASEC %s not found\n",
1377 			sec_name);
1378 		return -EINVAL;
1379 	}
1380 
1381 	datasec = btf__type_by_id(btf, datasec_id);
1382 	vsi = btf_var_secinfos(datasec);
1383 	for (i = 0; i < btf_vlen(datasec); i++, vsi++) {
1384 		type = btf__type_by_id(obj->btf, vsi->type);
1385 		var_name = btf__name_by_offset(obj->btf, type->name_off);
1386 
1387 		type_id = btf__resolve_type(obj->btf, vsi->type);
1388 		if (type_id < 0) {
1389 			pr_warn("struct_ops init: Cannot resolve var type_id %u in DATASEC %s\n",
1390 				vsi->type, sec_name);
1391 			return -EINVAL;
1392 		}
1393 
1394 		type = btf__type_by_id(obj->btf, type_id);
1395 		tname = btf__name_by_offset(obj->btf, type->name_off);
1396 		if (!tname[0]) {
1397 			pr_warn("struct_ops init: anonymous type is not supported\n");
1398 			return -ENOTSUP;
1399 		}
1400 		if (!btf_is_struct(type)) {
1401 			pr_warn("struct_ops init: %s is not a struct\n", tname);
1402 			return -EINVAL;
1403 		}
1404 
1405 		map = bpf_object__add_map(obj);
1406 		if (IS_ERR(map))
1407 			return PTR_ERR(map);
1408 
1409 		map->sec_idx = shndx;
1410 		map->sec_offset = vsi->offset;
1411 		map->name = strdup(var_name);
1412 		if (!map->name)
1413 			return -ENOMEM;
1414 		map->btf_value_type_id = type_id;
1415 
1416 		/* Follow same convention as for programs autoload:
1417 		 * SEC("?.struct_ops") means map is not created by default.
1418 		 */
1419 		if (sec_name[0] == '?') {
1420 			map->autocreate = false;
1421 			/* from now on forget there was ? in section name */
1422 			sec_name++;
1423 		}
1424 
1425 		map->def.type = BPF_MAP_TYPE_STRUCT_OPS;
1426 		map->def.key_size = sizeof(int);
1427 		map->def.value_size = type->size;
1428 		map->def.max_entries = 1;
1429 		map->def.map_flags = strcmp(sec_name, STRUCT_OPS_LINK_SEC) == 0 ? BPF_F_LINK : 0;
1430 		map->autoattach = true;
1431 
1432 		map->st_ops = calloc(1, sizeof(*map->st_ops));
1433 		if (!map->st_ops)
1434 			return -ENOMEM;
1435 		st_ops = map->st_ops;
1436 		st_ops->data = malloc(type->size);
1437 		st_ops->progs = calloc(btf_vlen(type), sizeof(*st_ops->progs));
1438 		st_ops->kern_func_off = malloc(btf_vlen(type) *
1439 					       sizeof(*st_ops->kern_func_off));
1440 		if (!st_ops->data || !st_ops->progs || !st_ops->kern_func_off)
1441 			return -ENOMEM;
1442 
1443 		if (vsi->offset + type->size > data->d_size) {
1444 			pr_warn("struct_ops init: var %s is beyond the end of DATASEC %s\n",
1445 				var_name, sec_name);
1446 			return -EINVAL;
1447 		}
1448 
1449 		memcpy(st_ops->data,
1450 		       data->d_buf + vsi->offset,
1451 		       type->size);
1452 		st_ops->type_id = type_id;
1453 
1454 		pr_debug("struct_ops init: struct %s(type_id=%u) %s found at offset %u\n",
1455 			 tname, type_id, var_name, vsi->offset);
1456 	}
1457 
1458 	return 0;
1459 }
1460 
1461 static int bpf_object_init_struct_ops(struct bpf_object *obj)
1462 {
1463 	const char *sec_name;
1464 	int sec_idx, err;
1465 
1466 	for (sec_idx = 0; sec_idx < obj->efile.sec_cnt; ++sec_idx) {
1467 		struct elf_sec_desc *desc = &obj->efile.secs[sec_idx];
1468 
1469 		if (desc->sec_type != SEC_ST_OPS)
1470 			continue;
1471 
1472 		sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1473 		if (!sec_name)
1474 			return -LIBBPF_ERRNO__FORMAT;
1475 
1476 		err = init_struct_ops_maps(obj, sec_name, sec_idx, desc->data);
1477 		if (err)
1478 			return err;
1479 	}
1480 
1481 	return 0;
1482 }
1483 
1484 static struct bpf_object *bpf_object__new(const char *path,
1485 					  const void *obj_buf,
1486 					  size_t obj_buf_sz,
1487 					  const char *obj_name)
1488 {
1489 	struct bpf_object *obj;
1490 	char *end;
1491 
1492 	obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
1493 	if (!obj) {
1494 		pr_warn("alloc memory failed for %s\n", path);
1495 		return ERR_PTR(-ENOMEM);
1496 	}
1497 
1498 	strcpy(obj->path, path);
1499 	if (obj_name) {
1500 		libbpf_strlcpy(obj->name, obj_name, sizeof(obj->name));
1501 	} else {
1502 		/* Using basename() GNU version which doesn't modify arg. */
1503 		libbpf_strlcpy(obj->name, basename((void *)path), sizeof(obj->name));
1504 		end = strchr(obj->name, '.');
1505 		if (end)
1506 			*end = 0;
1507 	}
1508 
1509 	obj->efile.fd = -1;
1510 	/*
1511 	 * Caller of this function should also call
1512 	 * bpf_object__elf_finish() after data collection to return
1513 	 * obj_buf to user. If not, we should duplicate the buffer to
1514 	 * avoid user freeing them before elf finish.
1515 	 */
1516 	obj->efile.obj_buf = obj_buf;
1517 	obj->efile.obj_buf_sz = obj_buf_sz;
1518 	obj->efile.btf_maps_shndx = -1;
1519 	obj->kconfig_map_idx = -1;
1520 
1521 	obj->kern_version = get_kernel_version();
1522 	obj->state  = OBJ_OPEN;
1523 
1524 	return obj;
1525 }
1526 
1527 static void bpf_object__elf_finish(struct bpf_object *obj)
1528 {
1529 	if (!obj->efile.elf)
1530 		return;
1531 
1532 	elf_end(obj->efile.elf);
1533 	obj->efile.elf = NULL;
1534 	obj->efile.ehdr = NULL;
1535 	obj->efile.symbols = NULL;
1536 	obj->efile.arena_data = NULL;
1537 
1538 	zfree(&obj->efile.secs);
1539 	obj->efile.sec_cnt = 0;
1540 	zclose(obj->efile.fd);
1541 	obj->efile.obj_buf = NULL;
1542 	obj->efile.obj_buf_sz = 0;
1543 }
1544 
1545 static int bpf_object__elf_init(struct bpf_object *obj)
1546 {
1547 	Elf64_Ehdr *ehdr;
1548 	int err = 0;
1549 	Elf *elf;
1550 
1551 	if (obj->efile.elf) {
1552 		pr_warn("elf: init internal error\n");
1553 		return -LIBBPF_ERRNO__LIBELF;
1554 	}
1555 
1556 	if (obj->efile.obj_buf_sz > 0) {
1557 		/* obj_buf should have been validated by bpf_object__open_mem(). */
1558 		elf = elf_memory((char *)obj->efile.obj_buf, obj->efile.obj_buf_sz);
1559 	} else {
1560 		obj->efile.fd = open(obj->path, O_RDONLY | O_CLOEXEC);
1561 		if (obj->efile.fd < 0) {
1562 			err = -errno;
1563 			pr_warn("elf: failed to open %s: %s\n", obj->path, errstr(err));
1564 			return err;
1565 		}
1566 
1567 		elf = elf_begin(obj->efile.fd, ELF_C_READ_MMAP, NULL);
1568 	}
1569 
1570 	if (!elf) {
1571 		pr_warn("elf: failed to open %s as ELF file: %s\n", obj->path, elf_errmsg(-1));
1572 		err = -LIBBPF_ERRNO__LIBELF;
1573 		goto errout;
1574 	}
1575 
1576 	obj->efile.elf = elf;
1577 
1578 	if (elf_kind(elf) != ELF_K_ELF) {
1579 		err = -LIBBPF_ERRNO__FORMAT;
1580 		pr_warn("elf: '%s' is not a proper ELF object\n", obj->path);
1581 		goto errout;
1582 	}
1583 
1584 	if (gelf_getclass(elf) != ELFCLASS64) {
1585 		err = -LIBBPF_ERRNO__FORMAT;
1586 		pr_warn("elf: '%s' is not a 64-bit ELF object\n", obj->path);
1587 		goto errout;
1588 	}
1589 
1590 	obj->efile.ehdr = ehdr = elf64_getehdr(elf);
1591 	if (!obj->efile.ehdr) {
1592 		pr_warn("elf: failed to get ELF header from %s: %s\n", obj->path, elf_errmsg(-1));
1593 		err = -LIBBPF_ERRNO__FORMAT;
1594 		goto errout;
1595 	}
1596 
1597 	/* Validate ELF object endianness... */
1598 	if (ehdr->e_ident[EI_DATA] != ELFDATA2LSB &&
1599 	    ehdr->e_ident[EI_DATA] != ELFDATA2MSB) {
1600 		err = -LIBBPF_ERRNO__ENDIAN;
1601 		pr_warn("elf: '%s' has unknown byte order\n", obj->path);
1602 		goto errout;
1603 	}
1604 	/* and save after bpf_object_open() frees ELF data */
1605 	obj->byteorder = ehdr->e_ident[EI_DATA];
1606 
1607 	if (elf_getshdrstrndx(elf, &obj->efile.shstrndx)) {
1608 		pr_warn("elf: failed to get section names section index for %s: %s\n",
1609 			obj->path, elf_errmsg(-1));
1610 		err = -LIBBPF_ERRNO__FORMAT;
1611 		goto errout;
1612 	}
1613 
1614 	/* ELF is corrupted/truncated, avoid calling elf_strptr. */
1615 	if (!elf_rawdata(elf_getscn(elf, obj->efile.shstrndx), NULL)) {
1616 		pr_warn("elf: failed to get section names strings from %s: %s\n",
1617 			obj->path, elf_errmsg(-1));
1618 		err = -LIBBPF_ERRNO__FORMAT;
1619 		goto errout;
1620 	}
1621 
1622 	/* Old LLVM set e_machine to EM_NONE */
1623 	if (ehdr->e_type != ET_REL || (ehdr->e_machine && ehdr->e_machine != EM_BPF)) {
1624 		pr_warn("elf: %s is not a valid eBPF object file\n", obj->path);
1625 		err = -LIBBPF_ERRNO__FORMAT;
1626 		goto errout;
1627 	}
1628 
1629 	return 0;
1630 errout:
1631 	bpf_object__elf_finish(obj);
1632 	return err;
1633 }
1634 
1635 static bool is_native_endianness(struct bpf_object *obj)
1636 {
1637 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1638 	return obj->byteorder == ELFDATA2LSB;
1639 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
1640 	return obj->byteorder == ELFDATA2MSB;
1641 #else
1642 # error "Unrecognized __BYTE_ORDER__"
1643 #endif
1644 }
1645 
1646 static int
1647 bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
1648 {
1649 	if (!data) {
1650 		pr_warn("invalid license section in %s\n", obj->path);
1651 		return -LIBBPF_ERRNO__FORMAT;
1652 	}
1653 	/* libbpf_strlcpy() only copies first N - 1 bytes, so size + 1 won't
1654 	 * go over allowed ELF data section buffer
1655 	 */
1656 	libbpf_strlcpy(obj->license, data, min(size + 1, sizeof(obj->license)));
1657 	pr_debug("license of %s is %s\n", obj->path, obj->license);
1658 	return 0;
1659 }
1660 
1661 static int
1662 bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
1663 {
1664 	__u32 kver;
1665 
1666 	if (!data || size != sizeof(kver)) {
1667 		pr_warn("invalid kver section in %s\n", obj->path);
1668 		return -LIBBPF_ERRNO__FORMAT;
1669 	}
1670 	memcpy(&kver, data, sizeof(kver));
1671 	obj->kern_version = kver;
1672 	pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
1673 	return 0;
1674 }
1675 
1676 static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
1677 {
1678 	if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
1679 	    type == BPF_MAP_TYPE_HASH_OF_MAPS)
1680 		return true;
1681 	return false;
1682 }
1683 
1684 static int find_elf_sec_sz(const struct bpf_object *obj, const char *name, __u32 *size)
1685 {
1686 	Elf_Data *data;
1687 	Elf_Scn *scn;
1688 
1689 	if (!name)
1690 		return -EINVAL;
1691 
1692 	scn = elf_sec_by_name(obj, name);
1693 	data = elf_sec_data(obj, scn);
1694 	if (data) {
1695 		*size = data->d_size;
1696 		return 0; /* found it */
1697 	}
1698 
1699 	return -ENOENT;
1700 }
1701 
1702 static Elf64_Sym *find_elf_var_sym(const struct bpf_object *obj, const char *name)
1703 {
1704 	Elf_Data *symbols = obj->efile.symbols;
1705 	const char *sname;
1706 	size_t si;
1707 
1708 	for (si = 0; si < symbols->d_size / sizeof(Elf64_Sym); si++) {
1709 		Elf64_Sym *sym = elf_sym_by_idx(obj, si);
1710 
1711 		if (ELF64_ST_TYPE(sym->st_info) != STT_OBJECT)
1712 			continue;
1713 
1714 		if (ELF64_ST_BIND(sym->st_info) != STB_GLOBAL &&
1715 		    ELF64_ST_BIND(sym->st_info) != STB_WEAK)
1716 			continue;
1717 
1718 		sname = elf_sym_str(obj, sym->st_name);
1719 		if (!sname) {
1720 			pr_warn("failed to get sym name string for var %s\n", name);
1721 			return ERR_PTR(-EIO);
1722 		}
1723 		if (strcmp(name, sname) == 0)
1724 			return sym;
1725 	}
1726 
1727 	return ERR_PTR(-ENOENT);
1728 }
1729 
1730 #ifndef MFD_CLOEXEC
1731 #define MFD_CLOEXEC 0x0001U
1732 #endif
1733 #ifndef MFD_NOEXEC_SEAL
1734 #define MFD_NOEXEC_SEAL 0x0008U
1735 #endif
1736 
1737 static int create_placeholder_fd(void)
1738 {
1739 	unsigned int flags = MFD_CLOEXEC | MFD_NOEXEC_SEAL;
1740 	const char *name = "libbpf-placeholder-fd";
1741 	int fd;
1742 
1743 	fd = ensure_good_fd(sys_memfd_create(name, flags));
1744 	if (fd >= 0)
1745 		return fd;
1746 	else if (errno != EINVAL)
1747 		return -errno;
1748 
1749 	/* Possibly running on kernel without MFD_NOEXEC_SEAL */
1750 	fd = ensure_good_fd(sys_memfd_create(name, flags & ~MFD_NOEXEC_SEAL));
1751 	if (fd < 0)
1752 		return -errno;
1753 	return fd;
1754 }
1755 
1756 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
1757 {
1758 	struct bpf_map *map;
1759 	int err;
1760 
1761 	err = libbpf_ensure_mem((void **)&obj->maps, &obj->maps_cap,
1762 				sizeof(*obj->maps), obj->nr_maps + 1);
1763 	if (err)
1764 		return ERR_PTR(err);
1765 
1766 	map = &obj->maps[obj->nr_maps++];
1767 	map->obj = obj;
1768 	/* Preallocate map FD without actually creating BPF map just yet.
1769 	 * These map FD "placeholders" will be reused later without changing
1770 	 * FD value when map is actually created in the kernel.
1771 	 *
1772 	 * This is useful to be able to perform BPF program relocations
1773 	 * without having to create BPF maps before that step. This allows us
1774 	 * to finalize and load BTF very late in BPF object's loading phase,
1775 	 * right before BPF maps have to be created and BPF programs have to
1776 	 * be loaded. By having these map FD placeholders we can perform all
1777 	 * the sanitizations, relocations, and any other adjustments before we
1778 	 * start creating actual BPF kernel objects (BTF, maps, progs).
1779 	 */
1780 	map->fd = create_placeholder_fd();
1781 	if (map->fd < 0)
1782 		return ERR_PTR(map->fd);
1783 	map->inner_map_fd = -1;
1784 	map->autocreate = true;
1785 
1786 	return map;
1787 }
1788 
1789 static size_t array_map_mmap_sz(unsigned int value_sz, unsigned int max_entries)
1790 {
1791 	const long page_sz = sysconf(_SC_PAGE_SIZE);
1792 	size_t map_sz;
1793 
1794 	map_sz = (size_t)roundup(value_sz, 8) * max_entries;
1795 	map_sz = roundup(map_sz, page_sz);
1796 	return map_sz;
1797 }
1798 
1799 static size_t bpf_map_mmap_sz(const struct bpf_map *map)
1800 {
1801 	const long page_sz = sysconf(_SC_PAGE_SIZE);
1802 
1803 	switch (map->def.type) {
1804 	case BPF_MAP_TYPE_ARRAY:
1805 		return array_map_mmap_sz(map->def.value_size, map->def.max_entries);
1806 	case BPF_MAP_TYPE_ARENA:
1807 		return page_sz * map->def.max_entries;
1808 	default:
1809 		return 0; /* not supported */
1810 	}
1811 }
1812 
1813 static int bpf_map_mmap_resize(struct bpf_map *map, size_t old_sz, size_t new_sz)
1814 {
1815 	void *mmaped;
1816 
1817 	if (!map->mmaped)
1818 		return -EINVAL;
1819 
1820 	if (old_sz == new_sz)
1821 		return 0;
1822 
1823 	mmaped = mmap(NULL, new_sz, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1824 	if (mmaped == MAP_FAILED)
1825 		return -errno;
1826 
1827 	memcpy(mmaped, map->mmaped, min(old_sz, new_sz));
1828 	munmap(map->mmaped, old_sz);
1829 	map->mmaped = mmaped;
1830 	return 0;
1831 }
1832 
1833 static char *internal_map_name(struct bpf_object *obj, const char *real_name)
1834 {
1835 	char map_name[BPF_OBJ_NAME_LEN], *p;
1836 	int pfx_len, sfx_len = max((size_t)7, strlen(real_name));
1837 
1838 	/* This is one of the more confusing parts of libbpf for various
1839 	 * reasons, some of which are historical. The original idea for naming
1840 	 * internal names was to include as much of BPF object name prefix as
1841 	 * possible, so that it can be distinguished from similar internal
1842 	 * maps of a different BPF object.
1843 	 * As an example, let's say we have bpf_object named 'my_object_name'
1844 	 * and internal map corresponding to '.rodata' ELF section. The final
1845 	 * map name advertised to user and to the kernel will be
1846 	 * 'my_objec.rodata', taking first 8 characters of object name and
1847 	 * entire 7 characters of '.rodata'.
1848 	 * Somewhat confusingly, if internal map ELF section name is shorter
1849 	 * than 7 characters, e.g., '.bss', we still reserve 7 characters
1850 	 * for the suffix, even though we only have 4 actual characters, and
1851 	 * resulting map will be called 'my_objec.bss', not even using all 15
1852 	 * characters allowed by the kernel. Oh well, at least the truncated
1853 	 * object name is somewhat consistent in this case. But if the map
1854 	 * name is '.kconfig', we'll still have entirety of '.kconfig' added
1855 	 * (8 chars) and thus will be left with only first 7 characters of the
1856 	 * object name ('my_obje'). Happy guessing, user, that the final map
1857 	 * name will be "my_obje.kconfig".
1858 	 * Now, with libbpf starting to support arbitrarily named .rodata.*
1859 	 * and .data.* data sections, it's possible that ELF section name is
1860 	 * longer than allowed 15 chars, so we now need to be careful to take
1861 	 * only up to 15 first characters of ELF name, taking no BPF object
1862 	 * name characters at all. So '.rodata.abracadabra' will result in
1863 	 * '.rodata.abracad' kernel and user-visible name.
1864 	 * We need to keep this convoluted logic intact for .data, .bss and
1865 	 * .rodata maps, but for new custom .data.custom and .rodata.custom
1866 	 * maps we use their ELF names as is, not prepending bpf_object name
1867 	 * in front. We still need to truncate them to 15 characters for the
1868 	 * kernel. Full name can be recovered for such maps by using DATASEC
1869 	 * BTF type associated with such map's value type, though.
1870 	 */
1871 	if (sfx_len >= BPF_OBJ_NAME_LEN)
1872 		sfx_len = BPF_OBJ_NAME_LEN - 1;
1873 
1874 	/* if there are two or more dots in map name, it's a custom dot map */
1875 	if (strchr(real_name + 1, '.') != NULL)
1876 		pfx_len = 0;
1877 	else
1878 		pfx_len = min((size_t)BPF_OBJ_NAME_LEN - sfx_len - 1, strlen(obj->name));
1879 
1880 	snprintf(map_name, sizeof(map_name), "%.*s%.*s", pfx_len, obj->name,
1881 		 sfx_len, real_name);
1882 
1883 	/* sanities map name to characters allowed by kernel */
1884 	for (p = map_name; *p && p < map_name + sizeof(map_name); p++)
1885 		if (!isalnum(*p) && *p != '_' && *p != '.')
1886 			*p = '_';
1887 
1888 	return strdup(map_name);
1889 }
1890 
1891 static int
1892 map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map);
1893 
1894 /* Internal BPF map is mmap()'able only if at least one of corresponding
1895  * DATASEC's VARs are to be exposed through BPF skeleton. I.e., it's a GLOBAL
1896  * variable and it's not marked as __hidden (which turns it into, effectively,
1897  * a STATIC variable).
1898  */
1899 static bool map_is_mmapable(struct bpf_object *obj, struct bpf_map *map)
1900 {
1901 	const struct btf_type *t, *vt;
1902 	struct btf_var_secinfo *vsi;
1903 	int i, n;
1904 
1905 	if (!map->btf_value_type_id)
1906 		return false;
1907 
1908 	t = btf__type_by_id(obj->btf, map->btf_value_type_id);
1909 	if (!btf_is_datasec(t))
1910 		return false;
1911 
1912 	vsi = btf_var_secinfos(t);
1913 	for (i = 0, n = btf_vlen(t); i < n; i++, vsi++) {
1914 		vt = btf__type_by_id(obj->btf, vsi->type);
1915 		if (!btf_is_var(vt))
1916 			continue;
1917 
1918 		if (btf_var(vt)->linkage != BTF_VAR_STATIC)
1919 			return true;
1920 	}
1921 
1922 	return false;
1923 }
1924 
1925 static int
1926 bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
1927 			      const char *real_name, int sec_idx, void *data, size_t data_sz)
1928 {
1929 	struct bpf_map_def *def;
1930 	struct bpf_map *map;
1931 	size_t mmap_sz;
1932 	int err;
1933 
1934 	map = bpf_object__add_map(obj);
1935 	if (IS_ERR(map))
1936 		return PTR_ERR(map);
1937 
1938 	map->libbpf_type = type;
1939 	map->sec_idx = sec_idx;
1940 	map->sec_offset = 0;
1941 	map->real_name = strdup(real_name);
1942 	map->name = internal_map_name(obj, real_name);
1943 	if (!map->real_name || !map->name) {
1944 		zfree(&map->real_name);
1945 		zfree(&map->name);
1946 		return -ENOMEM;
1947 	}
1948 
1949 	def = &map->def;
1950 	def->type = BPF_MAP_TYPE_ARRAY;
1951 	def->key_size = sizeof(int);
1952 	def->value_size = data_sz;
1953 	def->max_entries = 1;
1954 	def->map_flags = type == LIBBPF_MAP_RODATA || type == LIBBPF_MAP_KCONFIG
1955 		? BPF_F_RDONLY_PROG : 0;
1956 
1957 	/* failures are fine because of maps like .rodata.str1.1 */
1958 	(void) map_fill_btf_type_info(obj, map);
1959 
1960 	if (map_is_mmapable(obj, map))
1961 		def->map_flags |= BPF_F_MMAPABLE;
1962 
1963 	pr_debug("map '%s' (global data): at sec_idx %d, offset %zu, flags %x.\n",
1964 		 map->name, map->sec_idx, map->sec_offset, def->map_flags);
1965 
1966 	mmap_sz = bpf_map_mmap_sz(map);
1967 	map->mmaped = mmap(NULL, mmap_sz, PROT_READ | PROT_WRITE,
1968 			   MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1969 	if (map->mmaped == MAP_FAILED) {
1970 		err = -errno;
1971 		map->mmaped = NULL;
1972 		pr_warn("failed to alloc map '%s' content buffer: %s\n", map->name, errstr(err));
1973 		zfree(&map->real_name);
1974 		zfree(&map->name);
1975 		return err;
1976 	}
1977 
1978 	if (data)
1979 		memcpy(map->mmaped, data, data_sz);
1980 
1981 	pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
1982 	return 0;
1983 }
1984 
1985 static int bpf_object__init_global_data_maps(struct bpf_object *obj)
1986 {
1987 	struct elf_sec_desc *sec_desc;
1988 	const char *sec_name;
1989 	int err = 0, sec_idx;
1990 
1991 	/*
1992 	 * Populate obj->maps with libbpf internal maps.
1993 	 */
1994 	for (sec_idx = 1; sec_idx < obj->efile.sec_cnt; sec_idx++) {
1995 		sec_desc = &obj->efile.secs[sec_idx];
1996 
1997 		/* Skip recognized sections with size 0. */
1998 		if (!sec_desc->data || sec_desc->data->d_size == 0)
1999 			continue;
2000 
2001 		switch (sec_desc->sec_type) {
2002 		case SEC_DATA:
2003 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
2004 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
2005 							    sec_name, sec_idx,
2006 							    sec_desc->data->d_buf,
2007 							    sec_desc->data->d_size);
2008 			break;
2009 		case SEC_RODATA:
2010 			obj->has_rodata = true;
2011 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
2012 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
2013 							    sec_name, sec_idx,
2014 							    sec_desc->data->d_buf,
2015 							    sec_desc->data->d_size);
2016 			break;
2017 		case SEC_BSS:
2018 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
2019 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
2020 							    sec_name, sec_idx,
2021 							    NULL,
2022 							    sec_desc->data->d_size);
2023 			break;
2024 		default:
2025 			/* skip */
2026 			break;
2027 		}
2028 		if (err)
2029 			return err;
2030 	}
2031 	return 0;
2032 }
2033 
2034 
2035 static struct extern_desc *find_extern_by_name(const struct bpf_object *obj,
2036 					       const void *name)
2037 {
2038 	int i;
2039 
2040 	for (i = 0; i < obj->nr_extern; i++) {
2041 		if (strcmp(obj->externs[i].name, name) == 0)
2042 			return &obj->externs[i];
2043 	}
2044 	return NULL;
2045 }
2046 
2047 static struct extern_desc *find_extern_by_name_with_len(const struct bpf_object *obj,
2048 							const void *name, int len)
2049 {
2050 	const char *ext_name;
2051 	int i;
2052 
2053 	for (i = 0; i < obj->nr_extern; i++) {
2054 		ext_name = obj->externs[i].name;
2055 		if (strlen(ext_name) == len && strncmp(ext_name, name, len) == 0)
2056 			return &obj->externs[i];
2057 	}
2058 	return NULL;
2059 }
2060 
2061 static int set_kcfg_value_tri(struct extern_desc *ext, void *ext_val,
2062 			      char value)
2063 {
2064 	switch (ext->kcfg.type) {
2065 	case KCFG_BOOL:
2066 		if (value == 'm') {
2067 			pr_warn("extern (kcfg) '%s': value '%c' implies tristate or char type\n",
2068 				ext->name, value);
2069 			return -EINVAL;
2070 		}
2071 		*(bool *)ext_val = value == 'y' ? true : false;
2072 		break;
2073 	case KCFG_TRISTATE:
2074 		if (value == 'y')
2075 			*(enum libbpf_tristate *)ext_val = TRI_YES;
2076 		else if (value == 'm')
2077 			*(enum libbpf_tristate *)ext_val = TRI_MODULE;
2078 		else /* value == 'n' */
2079 			*(enum libbpf_tristate *)ext_val = TRI_NO;
2080 		break;
2081 	case KCFG_CHAR:
2082 		*(char *)ext_val = value;
2083 		break;
2084 	case KCFG_UNKNOWN:
2085 	case KCFG_INT:
2086 	case KCFG_CHAR_ARR:
2087 	default:
2088 		pr_warn("extern (kcfg) '%s': value '%c' implies bool, tristate, or char type\n",
2089 			ext->name, value);
2090 		return -EINVAL;
2091 	}
2092 	ext->is_set = true;
2093 	return 0;
2094 }
2095 
2096 static int set_kcfg_value_str(struct extern_desc *ext, char *ext_val,
2097 			      const char *value)
2098 {
2099 	size_t len;
2100 
2101 	if (ext->kcfg.type != KCFG_CHAR_ARR) {
2102 		pr_warn("extern (kcfg) '%s': value '%s' implies char array type\n",
2103 			ext->name, value);
2104 		return -EINVAL;
2105 	}
2106 
2107 	len = strlen(value);
2108 	if (len < 2 || value[len - 1] != '"') {
2109 		pr_warn("extern (kcfg) '%s': invalid string config '%s'\n",
2110 			ext->name, value);
2111 		return -EINVAL;
2112 	}
2113 
2114 	/* strip quotes */
2115 	len -= 2;
2116 	if (len >= ext->kcfg.sz) {
2117 		pr_warn("extern (kcfg) '%s': long string '%s' of (%zu bytes) truncated to %d bytes\n",
2118 			ext->name, value, len, ext->kcfg.sz - 1);
2119 		len = ext->kcfg.sz - 1;
2120 	}
2121 	memcpy(ext_val, value + 1, len);
2122 	ext_val[len] = '\0';
2123 	ext->is_set = true;
2124 	return 0;
2125 }
2126 
2127 static int parse_u64(const char *value, __u64 *res)
2128 {
2129 	char *value_end;
2130 	int err;
2131 
2132 	errno = 0;
2133 	*res = strtoull(value, &value_end, 0);
2134 	if (errno) {
2135 		err = -errno;
2136 		pr_warn("failed to parse '%s': %s\n", value, errstr(err));
2137 		return err;
2138 	}
2139 	if (*value_end) {
2140 		pr_warn("failed to parse '%s' as integer completely\n", value);
2141 		return -EINVAL;
2142 	}
2143 	return 0;
2144 }
2145 
2146 static bool is_kcfg_value_in_range(const struct extern_desc *ext, __u64 v)
2147 {
2148 	int bit_sz = ext->kcfg.sz * 8;
2149 
2150 	if (ext->kcfg.sz == 8)
2151 		return true;
2152 
2153 	/* Validate that value stored in u64 fits in integer of `ext->sz`
2154 	 * bytes size without any loss of information. If the target integer
2155 	 * is signed, we rely on the following limits of integer type of
2156 	 * Y bits and subsequent transformation:
2157 	 *
2158 	 *     -2^(Y-1) <= X           <= 2^(Y-1) - 1
2159 	 *            0 <= X + 2^(Y-1) <= 2^Y - 1
2160 	 *            0 <= X + 2^(Y-1) <  2^Y
2161 	 *
2162 	 *  For unsigned target integer, check that all the (64 - Y) bits are
2163 	 *  zero.
2164 	 */
2165 	if (ext->kcfg.is_signed)
2166 		return v + (1ULL << (bit_sz - 1)) < (1ULL << bit_sz);
2167 	else
2168 		return (v >> bit_sz) == 0;
2169 }
2170 
2171 static int set_kcfg_value_num(struct extern_desc *ext, void *ext_val,
2172 			      __u64 value)
2173 {
2174 	if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR &&
2175 	    ext->kcfg.type != KCFG_BOOL) {
2176 		pr_warn("extern (kcfg) '%s': value '%llu' implies integer, char, or boolean type\n",
2177 			ext->name, (unsigned long long)value);
2178 		return -EINVAL;
2179 	}
2180 	if (ext->kcfg.type == KCFG_BOOL && value > 1) {
2181 		pr_warn("extern (kcfg) '%s': value '%llu' isn't boolean compatible\n",
2182 			ext->name, (unsigned long long)value);
2183 		return -EINVAL;
2184 
2185 	}
2186 	if (!is_kcfg_value_in_range(ext, value)) {
2187 		pr_warn("extern (kcfg) '%s': value '%llu' doesn't fit in %d bytes\n",
2188 			ext->name, (unsigned long long)value, ext->kcfg.sz);
2189 		return -ERANGE;
2190 	}
2191 	switch (ext->kcfg.sz) {
2192 	case 1:
2193 		*(__u8 *)ext_val = value;
2194 		break;
2195 	case 2:
2196 		*(__u16 *)ext_val = value;
2197 		break;
2198 	case 4:
2199 		*(__u32 *)ext_val = value;
2200 		break;
2201 	case 8:
2202 		*(__u64 *)ext_val = value;
2203 		break;
2204 	default:
2205 		return -EINVAL;
2206 	}
2207 	ext->is_set = true;
2208 	return 0;
2209 }
2210 
2211 static int bpf_object__process_kconfig_line(struct bpf_object *obj,
2212 					    char *buf, void *data)
2213 {
2214 	struct extern_desc *ext;
2215 	char *sep, *value;
2216 	int len, err = 0;
2217 	void *ext_val;
2218 	__u64 num;
2219 
2220 	if (!str_has_pfx(buf, "CONFIG_"))
2221 		return 0;
2222 
2223 	sep = strchr(buf, '=');
2224 	if (!sep) {
2225 		pr_warn("failed to parse '%s': no separator\n", buf);
2226 		return -EINVAL;
2227 	}
2228 
2229 	/* Trim ending '\n' */
2230 	len = strlen(buf);
2231 	if (buf[len - 1] == '\n')
2232 		buf[len - 1] = '\0';
2233 	/* Split on '=' and ensure that a value is present. */
2234 	*sep = '\0';
2235 	if (!sep[1]) {
2236 		*sep = '=';
2237 		pr_warn("failed to parse '%s': no value\n", buf);
2238 		return -EINVAL;
2239 	}
2240 
2241 	ext = find_extern_by_name(obj, buf);
2242 	if (!ext || ext->is_set)
2243 		return 0;
2244 
2245 	ext_val = data + ext->kcfg.data_off;
2246 	value = sep + 1;
2247 
2248 	switch (*value) {
2249 	case 'y': case 'n': case 'm':
2250 		err = set_kcfg_value_tri(ext, ext_val, *value);
2251 		break;
2252 	case '"':
2253 		err = set_kcfg_value_str(ext, ext_val, value);
2254 		break;
2255 	default:
2256 		/* assume integer */
2257 		err = parse_u64(value, &num);
2258 		if (err) {
2259 			pr_warn("extern (kcfg) '%s': value '%s' isn't a valid integer\n", ext->name, value);
2260 			return err;
2261 		}
2262 		if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR) {
2263 			pr_warn("extern (kcfg) '%s': value '%s' implies integer type\n", ext->name, value);
2264 			return -EINVAL;
2265 		}
2266 		err = set_kcfg_value_num(ext, ext_val, num);
2267 		break;
2268 	}
2269 	if (err)
2270 		return err;
2271 	pr_debug("extern (kcfg) '%s': set to %s\n", ext->name, value);
2272 	return 0;
2273 }
2274 
2275 static int bpf_object__read_kconfig_file(struct bpf_object *obj, void *data)
2276 {
2277 	char buf[PATH_MAX];
2278 	struct utsname uts;
2279 	int len, err = 0;
2280 	gzFile file;
2281 
2282 	uname(&uts);
2283 	len = snprintf(buf, PATH_MAX, "/boot/config-%s", uts.release);
2284 	if (len < 0)
2285 		return -EINVAL;
2286 	else if (len >= PATH_MAX)
2287 		return -ENAMETOOLONG;
2288 
2289 	/* gzopen also accepts uncompressed files. */
2290 	file = gzopen(buf, "re");
2291 	if (!file)
2292 		file = gzopen("/proc/config.gz", "re");
2293 
2294 	if (!file) {
2295 		pr_warn("failed to open system Kconfig\n");
2296 		return -ENOENT;
2297 	}
2298 
2299 	while (gzgets(file, buf, sizeof(buf))) {
2300 		err = bpf_object__process_kconfig_line(obj, buf, data);
2301 		if (err) {
2302 			pr_warn("error parsing system Kconfig line '%s': %s\n",
2303 				buf, errstr(err));
2304 			goto out;
2305 		}
2306 	}
2307 
2308 out:
2309 	gzclose(file);
2310 	return err;
2311 }
2312 
2313 static int bpf_object__read_kconfig_mem(struct bpf_object *obj,
2314 					const char *config, void *data)
2315 {
2316 	char buf[PATH_MAX];
2317 	int err = 0;
2318 	FILE *file;
2319 
2320 	file = fmemopen((void *)config, strlen(config), "r");
2321 	if (!file) {
2322 		err = -errno;
2323 		pr_warn("failed to open in-memory Kconfig: %s\n", errstr(err));
2324 		return err;
2325 	}
2326 
2327 	while (fgets(buf, sizeof(buf), file)) {
2328 		err = bpf_object__process_kconfig_line(obj, buf, data);
2329 		if (err) {
2330 			pr_warn("error parsing in-memory Kconfig line '%s': %s\n",
2331 				buf, errstr(err));
2332 			break;
2333 		}
2334 	}
2335 
2336 	fclose(file);
2337 	return err;
2338 }
2339 
2340 static int bpf_object__init_kconfig_map(struct bpf_object *obj)
2341 {
2342 	struct extern_desc *last_ext = NULL, *ext;
2343 	size_t map_sz;
2344 	int i, err;
2345 
2346 	for (i = 0; i < obj->nr_extern; i++) {
2347 		ext = &obj->externs[i];
2348 		if (ext->type == EXT_KCFG)
2349 			last_ext = ext;
2350 	}
2351 
2352 	if (!last_ext)
2353 		return 0;
2354 
2355 	map_sz = last_ext->kcfg.data_off + last_ext->kcfg.sz;
2356 	err = bpf_object__init_internal_map(obj, LIBBPF_MAP_KCONFIG,
2357 					    ".kconfig", obj->efile.symbols_shndx,
2358 					    NULL, map_sz);
2359 	if (err)
2360 		return err;
2361 
2362 	obj->kconfig_map_idx = obj->nr_maps - 1;
2363 
2364 	return 0;
2365 }
2366 
2367 const struct btf_type *
2368 skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id)
2369 {
2370 	const struct btf_type *t = btf__type_by_id(btf, id);
2371 
2372 	if (res_id)
2373 		*res_id = id;
2374 
2375 	while (btf_is_mod(t) || btf_is_typedef(t)) {
2376 		if (res_id)
2377 			*res_id = t->type;
2378 		t = btf__type_by_id(btf, t->type);
2379 	}
2380 
2381 	return t;
2382 }
2383 
2384 static const struct btf_type *
2385 resolve_func_ptr(const struct btf *btf, __u32 id, __u32 *res_id)
2386 {
2387 	const struct btf_type *t;
2388 
2389 	t = skip_mods_and_typedefs(btf, id, NULL);
2390 	if (!btf_is_ptr(t))
2391 		return NULL;
2392 
2393 	t = skip_mods_and_typedefs(btf, t->type, res_id);
2394 
2395 	return btf_is_func_proto(t) ? t : NULL;
2396 }
2397 
2398 static const char *__btf_kind_str(__u16 kind)
2399 {
2400 	switch (kind) {
2401 	case BTF_KIND_UNKN: return "void";
2402 	case BTF_KIND_INT: return "int";
2403 	case BTF_KIND_PTR: return "ptr";
2404 	case BTF_KIND_ARRAY: return "array";
2405 	case BTF_KIND_STRUCT: return "struct";
2406 	case BTF_KIND_UNION: return "union";
2407 	case BTF_KIND_ENUM: return "enum";
2408 	case BTF_KIND_FWD: return "fwd";
2409 	case BTF_KIND_TYPEDEF: return "typedef";
2410 	case BTF_KIND_VOLATILE: return "volatile";
2411 	case BTF_KIND_CONST: return "const";
2412 	case BTF_KIND_RESTRICT: return "restrict";
2413 	case BTF_KIND_FUNC: return "func";
2414 	case BTF_KIND_FUNC_PROTO: return "func_proto";
2415 	case BTF_KIND_VAR: return "var";
2416 	case BTF_KIND_DATASEC: return "datasec";
2417 	case BTF_KIND_FLOAT: return "float";
2418 	case BTF_KIND_DECL_TAG: return "decl_tag";
2419 	case BTF_KIND_TYPE_TAG: return "type_tag";
2420 	case BTF_KIND_ENUM64: return "enum64";
2421 	default: return "unknown";
2422 	}
2423 }
2424 
2425 const char *btf_kind_str(const struct btf_type *t)
2426 {
2427 	return __btf_kind_str(btf_kind(t));
2428 }
2429 
2430 /*
2431  * Fetch integer attribute of BTF map definition. Such attributes are
2432  * represented using a pointer to an array, in which dimensionality of array
2433  * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
2434  * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
2435  * type definition, while using only sizeof(void *) space in ELF data section.
2436  */
2437 static bool get_map_field_int(const char *map_name, const struct btf *btf,
2438 			      const struct btf_member *m, __u32 *res)
2439 {
2440 	const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
2441 	const char *name = btf__name_by_offset(btf, m->name_off);
2442 	const struct btf_array *arr_info;
2443 	const struct btf_type *arr_t;
2444 
2445 	if (!btf_is_ptr(t)) {
2446 		pr_warn("map '%s': attr '%s': expected PTR, got %s.\n",
2447 			map_name, name, btf_kind_str(t));
2448 		return false;
2449 	}
2450 
2451 	arr_t = btf__type_by_id(btf, t->type);
2452 	if (!arr_t) {
2453 		pr_warn("map '%s': attr '%s': type [%u] not found.\n",
2454 			map_name, name, t->type);
2455 		return false;
2456 	}
2457 	if (!btf_is_array(arr_t)) {
2458 		pr_warn("map '%s': attr '%s': expected ARRAY, got %s.\n",
2459 			map_name, name, btf_kind_str(arr_t));
2460 		return false;
2461 	}
2462 	arr_info = btf_array(arr_t);
2463 	*res = arr_info->nelems;
2464 	return true;
2465 }
2466 
2467 static bool get_map_field_long(const char *map_name, const struct btf *btf,
2468 			       const struct btf_member *m, __u64 *res)
2469 {
2470 	const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
2471 	const char *name = btf__name_by_offset(btf, m->name_off);
2472 
2473 	if (btf_is_ptr(t)) {
2474 		__u32 res32;
2475 		bool ret;
2476 
2477 		ret = get_map_field_int(map_name, btf, m, &res32);
2478 		if (ret)
2479 			*res = (__u64)res32;
2480 		return ret;
2481 	}
2482 
2483 	if (!btf_is_enum(t) && !btf_is_enum64(t)) {
2484 		pr_warn("map '%s': attr '%s': expected ENUM or ENUM64, got %s.\n",
2485 			map_name, name, btf_kind_str(t));
2486 		return false;
2487 	}
2488 
2489 	if (btf_vlen(t) != 1) {
2490 		pr_warn("map '%s': attr '%s': invalid __ulong\n",
2491 			map_name, name);
2492 		return false;
2493 	}
2494 
2495 	if (btf_is_enum(t)) {
2496 		const struct btf_enum *e = btf_enum(t);
2497 
2498 		*res = e->val;
2499 	} else {
2500 		const struct btf_enum64 *e = btf_enum64(t);
2501 
2502 		*res = btf_enum64_value(e);
2503 	}
2504 	return true;
2505 }
2506 
2507 static int pathname_concat(char *buf, size_t buf_sz, const char *path, const char *name)
2508 {
2509 	int len;
2510 
2511 	len = snprintf(buf, buf_sz, "%s/%s", path, name);
2512 	if (len < 0)
2513 		return -EINVAL;
2514 	if (len >= buf_sz)
2515 		return -ENAMETOOLONG;
2516 
2517 	return 0;
2518 }
2519 
2520 static int build_map_pin_path(struct bpf_map *map, const char *path)
2521 {
2522 	char buf[PATH_MAX];
2523 	int err;
2524 
2525 	if (!path)
2526 		path = BPF_FS_DEFAULT_PATH;
2527 
2528 	err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
2529 	if (err)
2530 		return err;
2531 
2532 	return bpf_map__set_pin_path(map, buf);
2533 }
2534 
2535 /* should match definition in bpf_helpers.h */
2536 enum libbpf_pin_type {
2537 	LIBBPF_PIN_NONE,
2538 	/* PIN_BY_NAME: pin maps by name (in /sys/fs/bpf by default) */
2539 	LIBBPF_PIN_BY_NAME,
2540 };
2541 
2542 int parse_btf_map_def(const char *map_name, struct btf *btf,
2543 		      const struct btf_type *def_t, bool strict,
2544 		      struct btf_map_def *map_def, struct btf_map_def *inner_def)
2545 {
2546 	const struct btf_type *t;
2547 	const struct btf_member *m;
2548 	bool is_inner = inner_def == NULL;
2549 	int vlen, i;
2550 
2551 	vlen = btf_vlen(def_t);
2552 	m = btf_members(def_t);
2553 	for (i = 0; i < vlen; i++, m++) {
2554 		const char *name = btf__name_by_offset(btf, m->name_off);
2555 
2556 		if (!name) {
2557 			pr_warn("map '%s': invalid field #%d.\n", map_name, i);
2558 			return -EINVAL;
2559 		}
2560 		if (strcmp(name, "type") == 0) {
2561 			if (!get_map_field_int(map_name, btf, m, &map_def->map_type))
2562 				return -EINVAL;
2563 			map_def->parts |= MAP_DEF_MAP_TYPE;
2564 		} else if (strcmp(name, "max_entries") == 0) {
2565 			if (!get_map_field_int(map_name, btf, m, &map_def->max_entries))
2566 				return -EINVAL;
2567 			map_def->parts |= MAP_DEF_MAX_ENTRIES;
2568 		} else if (strcmp(name, "map_flags") == 0) {
2569 			if (!get_map_field_int(map_name, btf, m, &map_def->map_flags))
2570 				return -EINVAL;
2571 			map_def->parts |= MAP_DEF_MAP_FLAGS;
2572 		} else if (strcmp(name, "numa_node") == 0) {
2573 			if (!get_map_field_int(map_name, btf, m, &map_def->numa_node))
2574 				return -EINVAL;
2575 			map_def->parts |= MAP_DEF_NUMA_NODE;
2576 		} else if (strcmp(name, "key_size") == 0) {
2577 			__u32 sz;
2578 
2579 			if (!get_map_field_int(map_name, btf, m, &sz))
2580 				return -EINVAL;
2581 			if (map_def->key_size && map_def->key_size != sz) {
2582 				pr_warn("map '%s': conflicting key size %u != %u.\n",
2583 					map_name, map_def->key_size, sz);
2584 				return -EINVAL;
2585 			}
2586 			map_def->key_size = sz;
2587 			map_def->parts |= MAP_DEF_KEY_SIZE;
2588 		} else if (strcmp(name, "key") == 0) {
2589 			__s64 sz;
2590 
2591 			t = btf__type_by_id(btf, m->type);
2592 			if (!t) {
2593 				pr_warn("map '%s': key type [%d] not found.\n",
2594 					map_name, m->type);
2595 				return -EINVAL;
2596 			}
2597 			if (!btf_is_ptr(t)) {
2598 				pr_warn("map '%s': key spec is not PTR: %s.\n",
2599 					map_name, btf_kind_str(t));
2600 				return -EINVAL;
2601 			}
2602 			sz = btf__resolve_size(btf, t->type);
2603 			if (sz < 0) {
2604 				pr_warn("map '%s': can't determine key size for type [%u]: %zd.\n",
2605 					map_name, t->type, (ssize_t)sz);
2606 				return sz;
2607 			}
2608 			if (map_def->key_size && map_def->key_size != sz) {
2609 				pr_warn("map '%s': conflicting key size %u != %zd.\n",
2610 					map_name, map_def->key_size, (ssize_t)sz);
2611 				return -EINVAL;
2612 			}
2613 			map_def->key_size = sz;
2614 			map_def->key_type_id = t->type;
2615 			map_def->parts |= MAP_DEF_KEY_SIZE | MAP_DEF_KEY_TYPE;
2616 		} else if (strcmp(name, "value_size") == 0) {
2617 			__u32 sz;
2618 
2619 			if (!get_map_field_int(map_name, btf, m, &sz))
2620 				return -EINVAL;
2621 			if (map_def->value_size && map_def->value_size != sz) {
2622 				pr_warn("map '%s': conflicting value size %u != %u.\n",
2623 					map_name, map_def->value_size, sz);
2624 				return -EINVAL;
2625 			}
2626 			map_def->value_size = sz;
2627 			map_def->parts |= MAP_DEF_VALUE_SIZE;
2628 		} else if (strcmp(name, "value") == 0) {
2629 			__s64 sz;
2630 
2631 			t = btf__type_by_id(btf, m->type);
2632 			if (!t) {
2633 				pr_warn("map '%s': value type [%d] not found.\n",
2634 					map_name, m->type);
2635 				return -EINVAL;
2636 			}
2637 			if (!btf_is_ptr(t)) {
2638 				pr_warn("map '%s': value spec is not PTR: %s.\n",
2639 					map_name, btf_kind_str(t));
2640 				return -EINVAL;
2641 			}
2642 			sz = btf__resolve_size(btf, t->type);
2643 			if (sz < 0) {
2644 				pr_warn("map '%s': can't determine value size for type [%u]: %zd.\n",
2645 					map_name, t->type, (ssize_t)sz);
2646 				return sz;
2647 			}
2648 			if (map_def->value_size && map_def->value_size != sz) {
2649 				pr_warn("map '%s': conflicting value size %u != %zd.\n",
2650 					map_name, map_def->value_size, (ssize_t)sz);
2651 				return -EINVAL;
2652 			}
2653 			map_def->value_size = sz;
2654 			map_def->value_type_id = t->type;
2655 			map_def->parts |= MAP_DEF_VALUE_SIZE | MAP_DEF_VALUE_TYPE;
2656 		}
2657 		else if (strcmp(name, "values") == 0) {
2658 			bool is_map_in_map = bpf_map_type__is_map_in_map(map_def->map_type);
2659 			bool is_prog_array = map_def->map_type == BPF_MAP_TYPE_PROG_ARRAY;
2660 			const char *desc = is_map_in_map ? "map-in-map inner" : "prog-array value";
2661 			char inner_map_name[128];
2662 			int err;
2663 
2664 			if (is_inner) {
2665 				pr_warn("map '%s': multi-level inner maps not supported.\n",
2666 					map_name);
2667 				return -ENOTSUP;
2668 			}
2669 			if (i != vlen - 1) {
2670 				pr_warn("map '%s': '%s' member should be last.\n",
2671 					map_name, name);
2672 				return -EINVAL;
2673 			}
2674 			if (!is_map_in_map && !is_prog_array) {
2675 				pr_warn("map '%s': should be map-in-map or prog-array.\n",
2676 					map_name);
2677 				return -ENOTSUP;
2678 			}
2679 			if (map_def->value_size && map_def->value_size != 4) {
2680 				pr_warn("map '%s': conflicting value size %u != 4.\n",
2681 					map_name, map_def->value_size);
2682 				return -EINVAL;
2683 			}
2684 			map_def->value_size = 4;
2685 			t = btf__type_by_id(btf, m->type);
2686 			if (!t) {
2687 				pr_warn("map '%s': %s type [%d] not found.\n",
2688 					map_name, desc, m->type);
2689 				return -EINVAL;
2690 			}
2691 			if (!btf_is_array(t) || btf_array(t)->nelems) {
2692 				pr_warn("map '%s': %s spec is not a zero-sized array.\n",
2693 					map_name, desc);
2694 				return -EINVAL;
2695 			}
2696 			t = skip_mods_and_typedefs(btf, btf_array(t)->type, NULL);
2697 			if (!btf_is_ptr(t)) {
2698 				pr_warn("map '%s': %s def is of unexpected kind %s.\n",
2699 					map_name, desc, btf_kind_str(t));
2700 				return -EINVAL;
2701 			}
2702 			t = skip_mods_and_typedefs(btf, t->type, NULL);
2703 			if (is_prog_array) {
2704 				if (!btf_is_func_proto(t)) {
2705 					pr_warn("map '%s': prog-array value def is of unexpected kind %s.\n",
2706 						map_name, btf_kind_str(t));
2707 					return -EINVAL;
2708 				}
2709 				continue;
2710 			}
2711 			if (!btf_is_struct(t)) {
2712 				pr_warn("map '%s': map-in-map inner def is of unexpected kind %s.\n",
2713 					map_name, btf_kind_str(t));
2714 				return -EINVAL;
2715 			}
2716 
2717 			snprintf(inner_map_name, sizeof(inner_map_name), "%s.inner", map_name);
2718 			err = parse_btf_map_def(inner_map_name, btf, t, strict, inner_def, NULL);
2719 			if (err)
2720 				return err;
2721 
2722 			map_def->parts |= MAP_DEF_INNER_MAP;
2723 		} else if (strcmp(name, "pinning") == 0) {
2724 			__u32 val;
2725 
2726 			if (is_inner) {
2727 				pr_warn("map '%s': inner def can't be pinned.\n", map_name);
2728 				return -EINVAL;
2729 			}
2730 			if (!get_map_field_int(map_name, btf, m, &val))
2731 				return -EINVAL;
2732 			if (val != LIBBPF_PIN_NONE && val != LIBBPF_PIN_BY_NAME) {
2733 				pr_warn("map '%s': invalid pinning value %u.\n",
2734 					map_name, val);
2735 				return -EINVAL;
2736 			}
2737 			map_def->pinning = val;
2738 			map_def->parts |= MAP_DEF_PINNING;
2739 		} else if (strcmp(name, "map_extra") == 0) {
2740 			__u64 map_extra;
2741 
2742 			if (!get_map_field_long(map_name, btf, m, &map_extra))
2743 				return -EINVAL;
2744 			map_def->map_extra = map_extra;
2745 			map_def->parts |= MAP_DEF_MAP_EXTRA;
2746 		} else {
2747 			if (strict) {
2748 				pr_warn("map '%s': unknown field '%s'.\n", map_name, name);
2749 				return -ENOTSUP;
2750 			}
2751 			pr_debug("map '%s': ignoring unknown field '%s'.\n", map_name, name);
2752 		}
2753 	}
2754 
2755 	if (map_def->map_type == BPF_MAP_TYPE_UNSPEC) {
2756 		pr_warn("map '%s': map type isn't specified.\n", map_name);
2757 		return -EINVAL;
2758 	}
2759 
2760 	return 0;
2761 }
2762 
2763 static size_t adjust_ringbuf_sz(size_t sz)
2764 {
2765 	__u32 page_sz = sysconf(_SC_PAGE_SIZE);
2766 	__u32 mul;
2767 
2768 	/* if user forgot to set any size, make sure they see error */
2769 	if (sz == 0)
2770 		return 0;
2771 	/* Kernel expects BPF_MAP_TYPE_RINGBUF's max_entries to be
2772 	 * a power-of-2 multiple of kernel's page size. If user diligently
2773 	 * satisified these conditions, pass the size through.
2774 	 */
2775 	if ((sz % page_sz) == 0 && is_pow_of_2(sz / page_sz))
2776 		return sz;
2777 
2778 	/* Otherwise find closest (page_sz * power_of_2) product bigger than
2779 	 * user-set size to satisfy both user size request and kernel
2780 	 * requirements and substitute correct max_entries for map creation.
2781 	 */
2782 	for (mul = 1; mul <= UINT_MAX / page_sz; mul <<= 1) {
2783 		if (mul * page_sz > sz)
2784 			return mul * page_sz;
2785 	}
2786 
2787 	/* if it's impossible to satisfy the conditions (i.e., user size is
2788 	 * very close to UINT_MAX but is not a power-of-2 multiple of
2789 	 * page_size) then just return original size and let kernel reject it
2790 	 */
2791 	return sz;
2792 }
2793 
2794 static bool map_is_ringbuf(const struct bpf_map *map)
2795 {
2796 	return map->def.type == BPF_MAP_TYPE_RINGBUF ||
2797 	       map->def.type == BPF_MAP_TYPE_USER_RINGBUF;
2798 }
2799 
2800 static void fill_map_from_def(struct bpf_map *map, const struct btf_map_def *def)
2801 {
2802 	map->def.type = def->map_type;
2803 	map->def.key_size = def->key_size;
2804 	map->def.value_size = def->value_size;
2805 	map->def.max_entries = def->max_entries;
2806 	map->def.map_flags = def->map_flags;
2807 	map->map_extra = def->map_extra;
2808 
2809 	map->numa_node = def->numa_node;
2810 	map->btf_key_type_id = def->key_type_id;
2811 	map->btf_value_type_id = def->value_type_id;
2812 
2813 	/* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
2814 	if (map_is_ringbuf(map))
2815 		map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
2816 
2817 	if (def->parts & MAP_DEF_MAP_TYPE)
2818 		pr_debug("map '%s': found type = %u.\n", map->name, def->map_type);
2819 
2820 	if (def->parts & MAP_DEF_KEY_TYPE)
2821 		pr_debug("map '%s': found key [%u], sz = %u.\n",
2822 			 map->name, def->key_type_id, def->key_size);
2823 	else if (def->parts & MAP_DEF_KEY_SIZE)
2824 		pr_debug("map '%s': found key_size = %u.\n", map->name, def->key_size);
2825 
2826 	if (def->parts & MAP_DEF_VALUE_TYPE)
2827 		pr_debug("map '%s': found value [%u], sz = %u.\n",
2828 			 map->name, def->value_type_id, def->value_size);
2829 	else if (def->parts & MAP_DEF_VALUE_SIZE)
2830 		pr_debug("map '%s': found value_size = %u.\n", map->name, def->value_size);
2831 
2832 	if (def->parts & MAP_DEF_MAX_ENTRIES)
2833 		pr_debug("map '%s': found max_entries = %u.\n", map->name, def->max_entries);
2834 	if (def->parts & MAP_DEF_MAP_FLAGS)
2835 		pr_debug("map '%s': found map_flags = 0x%x.\n", map->name, def->map_flags);
2836 	if (def->parts & MAP_DEF_MAP_EXTRA)
2837 		pr_debug("map '%s': found map_extra = 0x%llx.\n", map->name,
2838 			 (unsigned long long)def->map_extra);
2839 	if (def->parts & MAP_DEF_PINNING)
2840 		pr_debug("map '%s': found pinning = %u.\n", map->name, def->pinning);
2841 	if (def->parts & MAP_DEF_NUMA_NODE)
2842 		pr_debug("map '%s': found numa_node = %u.\n", map->name, def->numa_node);
2843 
2844 	if (def->parts & MAP_DEF_INNER_MAP)
2845 		pr_debug("map '%s': found inner map definition.\n", map->name);
2846 }
2847 
2848 static const char *btf_var_linkage_str(__u32 linkage)
2849 {
2850 	switch (linkage) {
2851 	case BTF_VAR_STATIC: return "static";
2852 	case BTF_VAR_GLOBAL_ALLOCATED: return "global";
2853 	case BTF_VAR_GLOBAL_EXTERN: return "extern";
2854 	default: return "unknown";
2855 	}
2856 }
2857 
2858 static int bpf_object__init_user_btf_map(struct bpf_object *obj,
2859 					 const struct btf_type *sec,
2860 					 int var_idx, int sec_idx,
2861 					 const Elf_Data *data, bool strict,
2862 					 const char *pin_root_path)
2863 {
2864 	struct btf_map_def map_def = {}, inner_def = {};
2865 	const struct btf_type *var, *def;
2866 	const struct btf_var_secinfo *vi;
2867 	const struct btf_var *var_extra;
2868 	const char *map_name;
2869 	struct bpf_map *map;
2870 	int err;
2871 
2872 	vi = btf_var_secinfos(sec) + var_idx;
2873 	var = btf__type_by_id(obj->btf, vi->type);
2874 	var_extra = btf_var(var);
2875 	map_name = btf__name_by_offset(obj->btf, var->name_off);
2876 
2877 	if (map_name == NULL || map_name[0] == '\0') {
2878 		pr_warn("map #%d: empty name.\n", var_idx);
2879 		return -EINVAL;
2880 	}
2881 	if ((__u64)vi->offset + vi->size > data->d_size) {
2882 		pr_warn("map '%s' BTF data is corrupted.\n", map_name);
2883 		return -EINVAL;
2884 	}
2885 	if (!btf_is_var(var)) {
2886 		pr_warn("map '%s': unexpected var kind %s.\n",
2887 			map_name, btf_kind_str(var));
2888 		return -EINVAL;
2889 	}
2890 	if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED) {
2891 		pr_warn("map '%s': unsupported map linkage %s.\n",
2892 			map_name, btf_var_linkage_str(var_extra->linkage));
2893 		return -EOPNOTSUPP;
2894 	}
2895 
2896 	def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
2897 	if (!btf_is_struct(def)) {
2898 		pr_warn("map '%s': unexpected def kind %s.\n",
2899 			map_name, btf_kind_str(var));
2900 		return -EINVAL;
2901 	}
2902 	if (def->size > vi->size) {
2903 		pr_warn("map '%s': invalid def size.\n", map_name);
2904 		return -EINVAL;
2905 	}
2906 
2907 	map = bpf_object__add_map(obj);
2908 	if (IS_ERR(map))
2909 		return PTR_ERR(map);
2910 	map->name = strdup(map_name);
2911 	if (!map->name) {
2912 		pr_warn("map '%s': failed to alloc map name.\n", map_name);
2913 		return -ENOMEM;
2914 	}
2915 	map->libbpf_type = LIBBPF_MAP_UNSPEC;
2916 	map->def.type = BPF_MAP_TYPE_UNSPEC;
2917 	map->sec_idx = sec_idx;
2918 	map->sec_offset = vi->offset;
2919 	map->btf_var_idx = var_idx;
2920 	pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
2921 		 map_name, map->sec_idx, map->sec_offset);
2922 
2923 	err = parse_btf_map_def(map->name, obj->btf, def, strict, &map_def, &inner_def);
2924 	if (err)
2925 		return err;
2926 
2927 	fill_map_from_def(map, &map_def);
2928 
2929 	if (map_def.pinning == LIBBPF_PIN_BY_NAME) {
2930 		err = build_map_pin_path(map, pin_root_path);
2931 		if (err) {
2932 			pr_warn("map '%s': couldn't build pin path.\n", map->name);
2933 			return err;
2934 		}
2935 	}
2936 
2937 	if (map_def.parts & MAP_DEF_INNER_MAP) {
2938 		map->inner_map = calloc(1, sizeof(*map->inner_map));
2939 		if (!map->inner_map)
2940 			return -ENOMEM;
2941 		map->inner_map->fd = create_placeholder_fd();
2942 		if (map->inner_map->fd < 0)
2943 			return map->inner_map->fd;
2944 		map->inner_map->sec_idx = sec_idx;
2945 		map->inner_map->name = malloc(strlen(map_name) + sizeof(".inner") + 1);
2946 		if (!map->inner_map->name)
2947 			return -ENOMEM;
2948 		sprintf(map->inner_map->name, "%s.inner", map_name);
2949 
2950 		fill_map_from_def(map->inner_map, &inner_def);
2951 	}
2952 
2953 	err = map_fill_btf_type_info(obj, map);
2954 	if (err)
2955 		return err;
2956 
2957 	return 0;
2958 }
2959 
2960 static int init_arena_map_data(struct bpf_object *obj, struct bpf_map *map,
2961 			       const char *sec_name, int sec_idx,
2962 			       void *data, size_t data_sz)
2963 {
2964 	const long page_sz = sysconf(_SC_PAGE_SIZE);
2965 	size_t mmap_sz;
2966 
2967 	mmap_sz = bpf_map_mmap_sz(obj->arena_map);
2968 	if (roundup(data_sz, page_sz) > mmap_sz) {
2969 		pr_warn("elf: sec '%s': declared ARENA map size (%zu) is too small to hold global __arena variables of size %zu\n",
2970 			sec_name, mmap_sz, data_sz);
2971 		return -E2BIG;
2972 	}
2973 
2974 	obj->arena_data = malloc(data_sz);
2975 	if (!obj->arena_data)
2976 		return -ENOMEM;
2977 	memcpy(obj->arena_data, data, data_sz);
2978 	obj->arena_data_sz = data_sz;
2979 
2980 	/* make bpf_map__init_value() work for ARENA maps */
2981 	map->mmaped = obj->arena_data;
2982 
2983 	return 0;
2984 }
2985 
2986 static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict,
2987 					  const char *pin_root_path)
2988 {
2989 	const struct btf_type *sec = NULL;
2990 	int nr_types, i, vlen, err;
2991 	const struct btf_type *t;
2992 	const char *name;
2993 	Elf_Data *data;
2994 	Elf_Scn *scn;
2995 
2996 	if (obj->efile.btf_maps_shndx < 0)
2997 		return 0;
2998 
2999 	scn = elf_sec_by_idx(obj, obj->efile.btf_maps_shndx);
3000 	data = elf_sec_data(obj, scn);
3001 	if (!scn || !data) {
3002 		pr_warn("elf: failed to get %s map definitions for %s\n",
3003 			MAPS_ELF_SEC, obj->path);
3004 		return -EINVAL;
3005 	}
3006 
3007 	nr_types = btf__type_cnt(obj->btf);
3008 	for (i = 1; i < nr_types; i++) {
3009 		t = btf__type_by_id(obj->btf, i);
3010 		if (!btf_is_datasec(t))
3011 			continue;
3012 		name = btf__name_by_offset(obj->btf, t->name_off);
3013 		if (strcmp(name, MAPS_ELF_SEC) == 0) {
3014 			sec = t;
3015 			obj->efile.btf_maps_sec_btf_id = i;
3016 			break;
3017 		}
3018 	}
3019 
3020 	if (!sec) {
3021 		pr_warn("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
3022 		return -ENOENT;
3023 	}
3024 
3025 	vlen = btf_vlen(sec);
3026 	for (i = 0; i < vlen; i++) {
3027 		err = bpf_object__init_user_btf_map(obj, sec, i,
3028 						    obj->efile.btf_maps_shndx,
3029 						    data, strict,
3030 						    pin_root_path);
3031 		if (err)
3032 			return err;
3033 	}
3034 
3035 	for (i = 0; i < obj->nr_maps; i++) {
3036 		struct bpf_map *map = &obj->maps[i];
3037 
3038 		if (map->def.type != BPF_MAP_TYPE_ARENA)
3039 			continue;
3040 
3041 		if (obj->arena_map) {
3042 			pr_warn("map '%s': only single ARENA map is supported (map '%s' is also ARENA)\n",
3043 				map->name, obj->arena_map->name);
3044 			return -EINVAL;
3045 		}
3046 		obj->arena_map = map;
3047 
3048 		if (obj->efile.arena_data) {
3049 			err = init_arena_map_data(obj, map, ARENA_SEC, obj->efile.arena_data_shndx,
3050 						  obj->efile.arena_data->d_buf,
3051 						  obj->efile.arena_data->d_size);
3052 			if (err)
3053 				return err;
3054 		}
3055 	}
3056 	if (obj->efile.arena_data && !obj->arena_map) {
3057 		pr_warn("elf: sec '%s': to use global __arena variables the ARENA map should be explicitly declared in SEC(\".maps\")\n",
3058 			ARENA_SEC);
3059 		return -ENOENT;
3060 	}
3061 
3062 	return 0;
3063 }
3064 
3065 static int bpf_object__init_maps(struct bpf_object *obj,
3066 				 const struct bpf_object_open_opts *opts)
3067 {
3068 	const char *pin_root_path;
3069 	bool strict;
3070 	int err = 0;
3071 
3072 	strict = !OPTS_GET(opts, relaxed_maps, false);
3073 	pin_root_path = OPTS_GET(opts, pin_root_path, NULL);
3074 
3075 	err = bpf_object__init_user_btf_maps(obj, strict, pin_root_path);
3076 	err = err ?: bpf_object__init_global_data_maps(obj);
3077 	err = err ?: bpf_object__init_kconfig_map(obj);
3078 	err = err ?: bpf_object_init_struct_ops(obj);
3079 
3080 	return err;
3081 }
3082 
3083 static bool section_have_execinstr(struct bpf_object *obj, int idx)
3084 {
3085 	Elf64_Shdr *sh;
3086 
3087 	sh = elf_sec_hdr(obj, elf_sec_by_idx(obj, idx));
3088 	if (!sh)
3089 		return false;
3090 
3091 	return sh->sh_flags & SHF_EXECINSTR;
3092 }
3093 
3094 static bool starts_with_qmark(const char *s)
3095 {
3096 	return s && s[0] == '?';
3097 }
3098 
3099 static bool btf_needs_sanitization(struct bpf_object *obj)
3100 {
3101 	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
3102 	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
3103 	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
3104 	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
3105 	bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
3106 	bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
3107 	bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
3108 	bool has_qmark_datasec = kernel_supports(obj, FEAT_BTF_QMARK_DATASEC);
3109 
3110 	return !has_func || !has_datasec || !has_func_global || !has_float ||
3111 	       !has_decl_tag || !has_type_tag || !has_enum64 || !has_qmark_datasec;
3112 }
3113 
3114 static int bpf_object__sanitize_btf(struct bpf_object *obj, struct btf *btf)
3115 {
3116 	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
3117 	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
3118 	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
3119 	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
3120 	bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
3121 	bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
3122 	bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
3123 	bool has_qmark_datasec = kernel_supports(obj, FEAT_BTF_QMARK_DATASEC);
3124 	int enum64_placeholder_id = 0;
3125 	struct btf_type *t;
3126 	int i, j, vlen;
3127 
3128 	for (i = 1; i < btf__type_cnt(btf); i++) {
3129 		t = (struct btf_type *)btf__type_by_id(btf, i);
3130 
3131 		if ((!has_datasec && btf_is_var(t)) || (!has_decl_tag && btf_is_decl_tag(t))) {
3132 			/* replace VAR/DECL_TAG with INT */
3133 			t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
3134 			/*
3135 			 * using size = 1 is the safest choice, 4 will be too
3136 			 * big and cause kernel BTF validation failure if
3137 			 * original variable took less than 4 bytes
3138 			 */
3139 			t->size = 1;
3140 			*(int *)(t + 1) = BTF_INT_ENC(0, 0, 8);
3141 		} else if (!has_datasec && btf_is_datasec(t)) {
3142 			/* replace DATASEC with STRUCT */
3143 			const struct btf_var_secinfo *v = btf_var_secinfos(t);
3144 			struct btf_member *m = btf_members(t);
3145 			struct btf_type *vt;
3146 			char *name;
3147 
3148 			name = (char *)btf__name_by_offset(btf, t->name_off);
3149 			while (*name) {
3150 				if (*name == '.' || *name == '?')
3151 					*name = '_';
3152 				name++;
3153 			}
3154 
3155 			vlen = btf_vlen(t);
3156 			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
3157 			for (j = 0; j < vlen; j++, v++, m++) {
3158 				/* order of field assignments is important */
3159 				m->offset = v->offset * 8;
3160 				m->type = v->type;
3161 				/* preserve variable name as member name */
3162 				vt = (void *)btf__type_by_id(btf, v->type);
3163 				m->name_off = vt->name_off;
3164 			}
3165 		} else if (!has_qmark_datasec && btf_is_datasec(t) &&
3166 			   starts_with_qmark(btf__name_by_offset(btf, t->name_off))) {
3167 			/* replace '?' prefix with '_' for DATASEC names */
3168 			char *name;
3169 
3170 			name = (char *)btf__name_by_offset(btf, t->name_off);
3171 			if (name[0] == '?')
3172 				name[0] = '_';
3173 		} else if (!has_func && btf_is_func_proto(t)) {
3174 			/* replace FUNC_PROTO with ENUM */
3175 			vlen = btf_vlen(t);
3176 			t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
3177 			t->size = sizeof(__u32); /* kernel enforced */
3178 		} else if (!has_func && btf_is_func(t)) {
3179 			/* replace FUNC with TYPEDEF */
3180 			t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
3181 		} else if (!has_func_global && btf_is_func(t)) {
3182 			/* replace BTF_FUNC_GLOBAL with BTF_FUNC_STATIC */
3183 			t->info = BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0);
3184 		} else if (!has_float && btf_is_float(t)) {
3185 			/* replace FLOAT with an equally-sized empty STRUCT;
3186 			 * since C compilers do not accept e.g. "float" as a
3187 			 * valid struct name, make it anonymous
3188 			 */
3189 			t->name_off = 0;
3190 			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, 0);
3191 		} else if (!has_type_tag && btf_is_type_tag(t)) {
3192 			/* replace TYPE_TAG with a CONST */
3193 			t->name_off = 0;
3194 			t->info = BTF_INFO_ENC(BTF_KIND_CONST, 0, 0);
3195 		} else if (!has_enum64 && btf_is_enum(t)) {
3196 			/* clear the kflag */
3197 			t->info = btf_type_info(btf_kind(t), btf_vlen(t), false);
3198 		} else if (!has_enum64 && btf_is_enum64(t)) {
3199 			/* replace ENUM64 with a union */
3200 			struct btf_member *m;
3201 
3202 			if (enum64_placeholder_id == 0) {
3203 				enum64_placeholder_id = btf__add_int(btf, "enum64_placeholder", 1, 0);
3204 				if (enum64_placeholder_id < 0)
3205 					return enum64_placeholder_id;
3206 
3207 				t = (struct btf_type *)btf__type_by_id(btf, i);
3208 			}
3209 
3210 			m = btf_members(t);
3211 			vlen = btf_vlen(t);
3212 			t->info = BTF_INFO_ENC(BTF_KIND_UNION, 0, vlen);
3213 			for (j = 0; j < vlen; j++, m++) {
3214 				m->type = enum64_placeholder_id;
3215 				m->offset = 0;
3216 			}
3217 		}
3218 	}
3219 
3220 	return 0;
3221 }
3222 
3223 static bool libbpf_needs_btf(const struct bpf_object *obj)
3224 {
3225 	return obj->efile.btf_maps_shndx >= 0 ||
3226 	       obj->efile.has_st_ops ||
3227 	       obj->nr_extern > 0;
3228 }
3229 
3230 static bool kernel_needs_btf(const struct bpf_object *obj)
3231 {
3232 	return obj->efile.has_st_ops;
3233 }
3234 
3235 static int bpf_object__init_btf(struct bpf_object *obj,
3236 				Elf_Data *btf_data,
3237 				Elf_Data *btf_ext_data)
3238 {
3239 	int err = -ENOENT;
3240 
3241 	if (btf_data) {
3242 		obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
3243 		err = libbpf_get_error(obj->btf);
3244 		if (err) {
3245 			obj->btf = NULL;
3246 			pr_warn("Error loading ELF section %s: %s.\n", BTF_ELF_SEC, errstr(err));
3247 			goto out;
3248 		}
3249 		/* enforce 8-byte pointers for BPF-targeted BTFs */
3250 		btf__set_pointer_size(obj->btf, 8);
3251 	}
3252 	if (btf_ext_data) {
3253 		struct btf_ext_info *ext_segs[3];
3254 		int seg_num, sec_num;
3255 
3256 		if (!obj->btf) {
3257 			pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
3258 				 BTF_EXT_ELF_SEC, BTF_ELF_SEC);
3259 			goto out;
3260 		}
3261 		obj->btf_ext = btf_ext__new(btf_ext_data->d_buf, btf_ext_data->d_size);
3262 		err = libbpf_get_error(obj->btf_ext);
3263 		if (err) {
3264 			pr_warn("Error loading ELF section %s: %s. Ignored and continue.\n",
3265 				BTF_EXT_ELF_SEC, errstr(err));
3266 			obj->btf_ext = NULL;
3267 			goto out;
3268 		}
3269 
3270 		/* setup .BTF.ext to ELF section mapping */
3271 		ext_segs[0] = &obj->btf_ext->func_info;
3272 		ext_segs[1] = &obj->btf_ext->line_info;
3273 		ext_segs[2] = &obj->btf_ext->core_relo_info;
3274 		for (seg_num = 0; seg_num < ARRAY_SIZE(ext_segs); seg_num++) {
3275 			struct btf_ext_info *seg = ext_segs[seg_num];
3276 			const struct btf_ext_info_sec *sec;
3277 			const char *sec_name;
3278 			Elf_Scn *scn;
3279 
3280 			if (seg->sec_cnt == 0)
3281 				continue;
3282 
3283 			seg->sec_idxs = calloc(seg->sec_cnt, sizeof(*seg->sec_idxs));
3284 			if (!seg->sec_idxs) {
3285 				err = -ENOMEM;
3286 				goto out;
3287 			}
3288 
3289 			sec_num = 0;
3290 			for_each_btf_ext_sec(seg, sec) {
3291 				/* preventively increment index to avoid doing
3292 				 * this before every continue below
3293 				 */
3294 				sec_num++;
3295 
3296 				sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
3297 				if (str_is_empty(sec_name))
3298 					continue;
3299 				scn = elf_sec_by_name(obj, sec_name);
3300 				if (!scn)
3301 					continue;
3302 
3303 				seg->sec_idxs[sec_num - 1] = elf_ndxscn(scn);
3304 			}
3305 		}
3306 	}
3307 out:
3308 	if (err && libbpf_needs_btf(obj)) {
3309 		pr_warn("BTF is required, but is missing or corrupted.\n");
3310 		return err;
3311 	}
3312 	return 0;
3313 }
3314 
3315 static int compare_vsi_off(const void *_a, const void *_b)
3316 {
3317 	const struct btf_var_secinfo *a = _a;
3318 	const struct btf_var_secinfo *b = _b;
3319 
3320 	return a->offset - b->offset;
3321 }
3322 
3323 static int btf_fixup_datasec(struct bpf_object *obj, struct btf *btf,
3324 			     struct btf_type *t)
3325 {
3326 	__u32 size = 0, i, vars = btf_vlen(t);
3327 	const char *sec_name = btf__name_by_offset(btf, t->name_off);
3328 	struct btf_var_secinfo *vsi;
3329 	bool fixup_offsets = false;
3330 	int err;
3331 
3332 	if (!sec_name) {
3333 		pr_debug("No name found in string section for DATASEC kind.\n");
3334 		return -ENOENT;
3335 	}
3336 
3337 	/* Extern-backing datasecs (.ksyms, .kconfig) have their size and
3338 	 * variable offsets set at the previous step. Further, not every
3339 	 * extern BTF VAR has corresponding ELF symbol preserved, so we skip
3340 	 * all fixups altogether for such sections and go straight to sorting
3341 	 * VARs within their DATASEC.
3342 	 */
3343 	if (strcmp(sec_name, KCONFIG_SEC) == 0 || strcmp(sec_name, KSYMS_SEC) == 0)
3344 		goto sort_vars;
3345 
3346 	/* Clang leaves DATASEC size and VAR offsets as zeroes, so we need to
3347 	 * fix this up. But BPF static linker already fixes this up and fills
3348 	 * all the sizes and offsets during static linking. So this step has
3349 	 * to be optional. But the STV_HIDDEN handling is non-optional for any
3350 	 * non-extern DATASEC, so the variable fixup loop below handles both
3351 	 * functions at the same time, paying the cost of BTF VAR <-> ELF
3352 	 * symbol matching just once.
3353 	 */
3354 	if (t->size == 0) {
3355 		err = find_elf_sec_sz(obj, sec_name, &size);
3356 		if (err || !size) {
3357 			pr_debug("sec '%s': failed to determine size from ELF: size %u, err %s\n",
3358 				 sec_name, size, errstr(err));
3359 			return -ENOENT;
3360 		}
3361 
3362 		t->size = size;
3363 		fixup_offsets = true;
3364 	}
3365 
3366 	for (i = 0, vsi = btf_var_secinfos(t); i < vars; i++, vsi++) {
3367 		const struct btf_type *t_var;
3368 		struct btf_var *var;
3369 		const char *var_name;
3370 		Elf64_Sym *sym;
3371 
3372 		t_var = btf__type_by_id(btf, vsi->type);
3373 		if (!t_var || !btf_is_var(t_var)) {
3374 			pr_debug("sec '%s': unexpected non-VAR type found\n", sec_name);
3375 			return -EINVAL;
3376 		}
3377 
3378 		var = btf_var(t_var);
3379 		if (var->linkage == BTF_VAR_STATIC || var->linkage == BTF_VAR_GLOBAL_EXTERN)
3380 			continue;
3381 
3382 		var_name = btf__name_by_offset(btf, t_var->name_off);
3383 		if (!var_name) {
3384 			pr_debug("sec '%s': failed to find name of DATASEC's member #%d\n",
3385 				 sec_name, i);
3386 			return -ENOENT;
3387 		}
3388 
3389 		sym = find_elf_var_sym(obj, var_name);
3390 		if (IS_ERR(sym)) {
3391 			pr_debug("sec '%s': failed to find ELF symbol for VAR '%s'\n",
3392 				 sec_name, var_name);
3393 			return -ENOENT;
3394 		}
3395 
3396 		if (fixup_offsets)
3397 			vsi->offset = sym->st_value;
3398 
3399 		/* if variable is a global/weak symbol, but has restricted
3400 		 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF VAR
3401 		 * as static. This follows similar logic for functions (BPF
3402 		 * subprogs) and influences libbpf's further decisions about
3403 		 * whether to make global data BPF array maps as
3404 		 * BPF_F_MMAPABLE.
3405 		 */
3406 		if (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
3407 		    || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL)
3408 			var->linkage = BTF_VAR_STATIC;
3409 	}
3410 
3411 sort_vars:
3412 	qsort(btf_var_secinfos(t), vars, sizeof(*vsi), compare_vsi_off);
3413 	return 0;
3414 }
3415 
3416 static int bpf_object_fixup_btf(struct bpf_object *obj)
3417 {
3418 	int i, n, err = 0;
3419 
3420 	if (!obj->btf)
3421 		return 0;
3422 
3423 	n = btf__type_cnt(obj->btf);
3424 	for (i = 1; i < n; i++) {
3425 		struct btf_type *t = btf_type_by_id(obj->btf, i);
3426 
3427 		/* Loader needs to fix up some of the things compiler
3428 		 * couldn't get its hands on while emitting BTF. This
3429 		 * is section size and global variable offset. We use
3430 		 * the info from the ELF itself for this purpose.
3431 		 */
3432 		if (btf_is_datasec(t)) {
3433 			err = btf_fixup_datasec(obj, obj->btf, t);
3434 			if (err)
3435 				return err;
3436 		}
3437 	}
3438 
3439 	return 0;
3440 }
3441 
3442 static bool prog_needs_vmlinux_btf(struct bpf_program *prog)
3443 {
3444 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
3445 	    prog->type == BPF_PROG_TYPE_LSM)
3446 		return true;
3447 
3448 	/* BPF_PROG_TYPE_TRACING programs which do not attach to other programs
3449 	 * also need vmlinux BTF
3450 	 */
3451 	if (prog->type == BPF_PROG_TYPE_TRACING && !prog->attach_prog_fd)
3452 		return true;
3453 
3454 	return false;
3455 }
3456 
3457 static bool map_needs_vmlinux_btf(struct bpf_map *map)
3458 {
3459 	return bpf_map__is_struct_ops(map);
3460 }
3461 
3462 static bool obj_needs_vmlinux_btf(const struct bpf_object *obj)
3463 {
3464 	struct bpf_program *prog;
3465 	struct bpf_map *map;
3466 	int i;
3467 
3468 	/* CO-RE relocations need kernel BTF, only when btf_custom_path
3469 	 * is not specified
3470 	 */
3471 	if (obj->btf_ext && obj->btf_ext->core_relo_info.len && !obj->btf_custom_path)
3472 		return true;
3473 
3474 	/* Support for typed ksyms needs kernel BTF */
3475 	for (i = 0; i < obj->nr_extern; i++) {
3476 		const struct extern_desc *ext;
3477 
3478 		ext = &obj->externs[i];
3479 		if (ext->type == EXT_KSYM && ext->ksym.type_id)
3480 			return true;
3481 	}
3482 
3483 	bpf_object__for_each_program(prog, obj) {
3484 		if (!prog->autoload)
3485 			continue;
3486 		if (prog_needs_vmlinux_btf(prog))
3487 			return true;
3488 	}
3489 
3490 	bpf_object__for_each_map(map, obj) {
3491 		if (map_needs_vmlinux_btf(map))
3492 			return true;
3493 	}
3494 
3495 	return false;
3496 }
3497 
3498 static int bpf_object__load_vmlinux_btf(struct bpf_object *obj, bool force)
3499 {
3500 	int err;
3501 
3502 	/* btf_vmlinux could be loaded earlier */
3503 	if (obj->btf_vmlinux || obj->gen_loader)
3504 		return 0;
3505 
3506 	if (!force && !obj_needs_vmlinux_btf(obj))
3507 		return 0;
3508 
3509 	obj->btf_vmlinux = btf__load_vmlinux_btf();
3510 	err = libbpf_get_error(obj->btf_vmlinux);
3511 	if (err) {
3512 		pr_warn("Error loading vmlinux BTF: %s\n", errstr(err));
3513 		obj->btf_vmlinux = NULL;
3514 		return err;
3515 	}
3516 	return 0;
3517 }
3518 
3519 static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
3520 {
3521 	struct btf *kern_btf = obj->btf;
3522 	bool btf_mandatory, sanitize;
3523 	int i, err = 0;
3524 
3525 	if (!obj->btf)
3526 		return 0;
3527 
3528 	if (!kernel_supports(obj, FEAT_BTF)) {
3529 		if (kernel_needs_btf(obj)) {
3530 			err = -EOPNOTSUPP;
3531 			goto report;
3532 		}
3533 		pr_debug("Kernel doesn't support BTF, skipping uploading it.\n");
3534 		return 0;
3535 	}
3536 
3537 	/* Even though some subprogs are global/weak, user might prefer more
3538 	 * permissive BPF verification process that BPF verifier performs for
3539 	 * static functions, taking into account more context from the caller
3540 	 * functions. In such case, they need to mark such subprogs with
3541 	 * __attribute__((visibility("hidden"))) and libbpf will adjust
3542 	 * corresponding FUNC BTF type to be marked as static and trigger more
3543 	 * involved BPF verification process.
3544 	 */
3545 	for (i = 0; i < obj->nr_programs; i++) {
3546 		struct bpf_program *prog = &obj->programs[i];
3547 		struct btf_type *t;
3548 		const char *name;
3549 		int j, n;
3550 
3551 		if (!prog->mark_btf_static || !prog_is_subprog(obj, prog))
3552 			continue;
3553 
3554 		n = btf__type_cnt(obj->btf);
3555 		for (j = 1; j < n; j++) {
3556 			t = btf_type_by_id(obj->btf, j);
3557 			if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL)
3558 				continue;
3559 
3560 			name = btf__str_by_offset(obj->btf, t->name_off);
3561 			if (strcmp(name, prog->name) != 0)
3562 				continue;
3563 
3564 			t->info = btf_type_info(BTF_KIND_FUNC, BTF_FUNC_STATIC, 0);
3565 			break;
3566 		}
3567 	}
3568 
3569 	sanitize = btf_needs_sanitization(obj);
3570 	if (sanitize) {
3571 		const void *raw_data;
3572 		__u32 sz;
3573 
3574 		/* clone BTF to sanitize a copy and leave the original intact */
3575 		raw_data = btf__raw_data(obj->btf, &sz);
3576 		kern_btf = btf__new(raw_data, sz);
3577 		err = libbpf_get_error(kern_btf);
3578 		if (err)
3579 			return err;
3580 
3581 		/* enforce 8-byte pointers for BPF-targeted BTFs */
3582 		btf__set_pointer_size(obj->btf, 8);
3583 		err = bpf_object__sanitize_btf(obj, kern_btf);
3584 		if (err)
3585 			return err;
3586 	}
3587 
3588 	if (obj->gen_loader) {
3589 		__u32 raw_size = 0;
3590 		const void *raw_data = btf__raw_data(kern_btf, &raw_size);
3591 
3592 		if (!raw_data)
3593 			return -ENOMEM;
3594 		bpf_gen__load_btf(obj->gen_loader, raw_data, raw_size);
3595 		/* Pretend to have valid FD to pass various fd >= 0 checks.
3596 		 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
3597 		 */
3598 		btf__set_fd(kern_btf, 0);
3599 	} else {
3600 		/* currently BPF_BTF_LOAD only supports log_level 1 */
3601 		err = btf_load_into_kernel(kern_btf, obj->log_buf, obj->log_size,
3602 					   obj->log_level ? 1 : 0, obj->token_fd);
3603 	}
3604 	if (sanitize) {
3605 		if (!err) {
3606 			/* move fd to libbpf's BTF */
3607 			btf__set_fd(obj->btf, btf__fd(kern_btf));
3608 			btf__set_fd(kern_btf, -1);
3609 		}
3610 		btf__free(kern_btf);
3611 	}
3612 report:
3613 	if (err) {
3614 		btf_mandatory = kernel_needs_btf(obj);
3615 		if (btf_mandatory) {
3616 			pr_warn("Error loading .BTF into kernel: %s. BTF is mandatory, can't proceed.\n",
3617 				errstr(err));
3618 		} else {
3619 			pr_info("Error loading .BTF into kernel: %s. BTF is optional, ignoring.\n",
3620 				errstr(err));
3621 			err = 0;
3622 		}
3623 	}
3624 	return err;
3625 }
3626 
3627 static const char *elf_sym_str(const struct bpf_object *obj, size_t off)
3628 {
3629 	const char *name;
3630 
3631 	name = elf_strptr(obj->efile.elf, obj->efile.strtabidx, off);
3632 	if (!name) {
3633 		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3634 			off, obj->path, elf_errmsg(-1));
3635 		return NULL;
3636 	}
3637 
3638 	return name;
3639 }
3640 
3641 static const char *elf_sec_str(const struct bpf_object *obj, size_t off)
3642 {
3643 	const char *name;
3644 
3645 	name = elf_strptr(obj->efile.elf, obj->efile.shstrndx, off);
3646 	if (!name) {
3647 		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3648 			off, obj->path, elf_errmsg(-1));
3649 		return NULL;
3650 	}
3651 
3652 	return name;
3653 }
3654 
3655 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx)
3656 {
3657 	Elf_Scn *scn;
3658 
3659 	scn = elf_getscn(obj->efile.elf, idx);
3660 	if (!scn) {
3661 		pr_warn("elf: failed to get section(%zu) from %s: %s\n",
3662 			idx, obj->path, elf_errmsg(-1));
3663 		return NULL;
3664 	}
3665 	return scn;
3666 }
3667 
3668 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name)
3669 {
3670 	Elf_Scn *scn = NULL;
3671 	Elf *elf = obj->efile.elf;
3672 	const char *sec_name;
3673 
3674 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3675 		sec_name = elf_sec_name(obj, scn);
3676 		if (!sec_name)
3677 			return NULL;
3678 
3679 		if (strcmp(sec_name, name) != 0)
3680 			continue;
3681 
3682 		return scn;
3683 	}
3684 	return NULL;
3685 }
3686 
3687 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn)
3688 {
3689 	Elf64_Shdr *shdr;
3690 
3691 	if (!scn)
3692 		return NULL;
3693 
3694 	shdr = elf64_getshdr(scn);
3695 	if (!shdr) {
3696 		pr_warn("elf: failed to get section(%zu) header from %s: %s\n",
3697 			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3698 		return NULL;
3699 	}
3700 
3701 	return shdr;
3702 }
3703 
3704 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn)
3705 {
3706 	const char *name;
3707 	Elf64_Shdr *sh;
3708 
3709 	if (!scn)
3710 		return NULL;
3711 
3712 	sh = elf_sec_hdr(obj, scn);
3713 	if (!sh)
3714 		return NULL;
3715 
3716 	name = elf_sec_str(obj, sh->sh_name);
3717 	if (!name) {
3718 		pr_warn("elf: failed to get section(%zu) name from %s: %s\n",
3719 			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3720 		return NULL;
3721 	}
3722 
3723 	return name;
3724 }
3725 
3726 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn)
3727 {
3728 	Elf_Data *data;
3729 
3730 	if (!scn)
3731 		return NULL;
3732 
3733 	data = elf_getdata(scn, 0);
3734 	if (!data) {
3735 		pr_warn("elf: failed to get section(%zu) %s data from %s: %s\n",
3736 			elf_ndxscn(scn), elf_sec_name(obj, scn) ?: "<?>",
3737 			obj->path, elf_errmsg(-1));
3738 		return NULL;
3739 	}
3740 
3741 	return data;
3742 }
3743 
3744 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx)
3745 {
3746 	if (idx >= obj->efile.symbols->d_size / sizeof(Elf64_Sym))
3747 		return NULL;
3748 
3749 	return (Elf64_Sym *)obj->efile.symbols->d_buf + idx;
3750 }
3751 
3752 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx)
3753 {
3754 	if (idx >= data->d_size / sizeof(Elf64_Rel))
3755 		return NULL;
3756 
3757 	return (Elf64_Rel *)data->d_buf + idx;
3758 }
3759 
3760 static bool is_sec_name_dwarf(const char *name)
3761 {
3762 	/* approximation, but the actual list is too long */
3763 	return str_has_pfx(name, ".debug_");
3764 }
3765 
3766 static bool ignore_elf_section(Elf64_Shdr *hdr, const char *name)
3767 {
3768 	/* no special handling of .strtab */
3769 	if (hdr->sh_type == SHT_STRTAB)
3770 		return true;
3771 
3772 	/* ignore .llvm_addrsig section as well */
3773 	if (hdr->sh_type == SHT_LLVM_ADDRSIG)
3774 		return true;
3775 
3776 	/* no subprograms will lead to an empty .text section, ignore it */
3777 	if (hdr->sh_type == SHT_PROGBITS && hdr->sh_size == 0 &&
3778 	    strcmp(name, ".text") == 0)
3779 		return true;
3780 
3781 	/* DWARF sections */
3782 	if (is_sec_name_dwarf(name))
3783 		return true;
3784 
3785 	if (str_has_pfx(name, ".rel")) {
3786 		name += sizeof(".rel") - 1;
3787 		/* DWARF section relocations */
3788 		if (is_sec_name_dwarf(name))
3789 			return true;
3790 
3791 		/* .BTF and .BTF.ext don't need relocations */
3792 		if (strcmp(name, BTF_ELF_SEC) == 0 ||
3793 		    strcmp(name, BTF_EXT_ELF_SEC) == 0)
3794 			return true;
3795 	}
3796 
3797 	return false;
3798 }
3799 
3800 static int cmp_progs(const void *_a, const void *_b)
3801 {
3802 	const struct bpf_program *a = _a;
3803 	const struct bpf_program *b = _b;
3804 
3805 	if (a->sec_idx != b->sec_idx)
3806 		return a->sec_idx < b->sec_idx ? -1 : 1;
3807 
3808 	/* sec_insn_off can't be the same within the section */
3809 	return a->sec_insn_off < b->sec_insn_off ? -1 : 1;
3810 }
3811 
3812 static int bpf_object__elf_collect(struct bpf_object *obj)
3813 {
3814 	struct elf_sec_desc *sec_desc;
3815 	Elf *elf = obj->efile.elf;
3816 	Elf_Data *btf_ext_data = NULL;
3817 	Elf_Data *btf_data = NULL;
3818 	int idx = 0, err = 0;
3819 	const char *name;
3820 	Elf_Data *data;
3821 	Elf_Scn *scn;
3822 	Elf64_Shdr *sh;
3823 
3824 	/* ELF section indices are 0-based, but sec #0 is special "invalid"
3825 	 * section. Since section count retrieved by elf_getshdrnum() does
3826 	 * include sec #0, it is already the necessary size of an array to keep
3827 	 * all the sections.
3828 	 */
3829 	if (elf_getshdrnum(obj->efile.elf, &obj->efile.sec_cnt)) {
3830 		pr_warn("elf: failed to get the number of sections for %s: %s\n",
3831 			obj->path, elf_errmsg(-1));
3832 		return -LIBBPF_ERRNO__FORMAT;
3833 	}
3834 	obj->efile.secs = calloc(obj->efile.sec_cnt, sizeof(*obj->efile.secs));
3835 	if (!obj->efile.secs)
3836 		return -ENOMEM;
3837 
3838 	/* a bunch of ELF parsing functionality depends on processing symbols,
3839 	 * so do the first pass and find the symbol table
3840 	 */
3841 	scn = NULL;
3842 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3843 		sh = elf_sec_hdr(obj, scn);
3844 		if (!sh)
3845 			return -LIBBPF_ERRNO__FORMAT;
3846 
3847 		if (sh->sh_type == SHT_SYMTAB) {
3848 			if (obj->efile.symbols) {
3849 				pr_warn("elf: multiple symbol tables in %s\n", obj->path);
3850 				return -LIBBPF_ERRNO__FORMAT;
3851 			}
3852 
3853 			data = elf_sec_data(obj, scn);
3854 			if (!data)
3855 				return -LIBBPF_ERRNO__FORMAT;
3856 
3857 			idx = elf_ndxscn(scn);
3858 
3859 			obj->efile.symbols = data;
3860 			obj->efile.symbols_shndx = idx;
3861 			obj->efile.strtabidx = sh->sh_link;
3862 		}
3863 	}
3864 
3865 	if (!obj->efile.symbols) {
3866 		pr_warn("elf: couldn't find symbol table in %s, stripped object file?\n",
3867 			obj->path);
3868 		return -ENOENT;
3869 	}
3870 
3871 	scn = NULL;
3872 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3873 		idx = elf_ndxscn(scn);
3874 		sec_desc = &obj->efile.secs[idx];
3875 
3876 		sh = elf_sec_hdr(obj, scn);
3877 		if (!sh)
3878 			return -LIBBPF_ERRNO__FORMAT;
3879 
3880 		name = elf_sec_str(obj, sh->sh_name);
3881 		if (!name)
3882 			return -LIBBPF_ERRNO__FORMAT;
3883 
3884 		if (ignore_elf_section(sh, name))
3885 			continue;
3886 
3887 		data = elf_sec_data(obj, scn);
3888 		if (!data)
3889 			return -LIBBPF_ERRNO__FORMAT;
3890 
3891 		pr_debug("elf: section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
3892 			 idx, name, (unsigned long)data->d_size,
3893 			 (int)sh->sh_link, (unsigned long)sh->sh_flags,
3894 			 (int)sh->sh_type);
3895 
3896 		if (strcmp(name, "license") == 0) {
3897 			err = bpf_object__init_license(obj, data->d_buf, data->d_size);
3898 			if (err)
3899 				return err;
3900 		} else if (strcmp(name, "version") == 0) {
3901 			err = bpf_object__init_kversion(obj, data->d_buf, data->d_size);
3902 			if (err)
3903 				return err;
3904 		} else if (strcmp(name, "maps") == 0) {
3905 			pr_warn("elf: legacy map definitions in 'maps' section are not supported by libbpf v1.0+\n");
3906 			return -ENOTSUP;
3907 		} else if (strcmp(name, MAPS_ELF_SEC) == 0) {
3908 			obj->efile.btf_maps_shndx = idx;
3909 		} else if (strcmp(name, BTF_ELF_SEC) == 0) {
3910 			if (sh->sh_type != SHT_PROGBITS)
3911 				return -LIBBPF_ERRNO__FORMAT;
3912 			btf_data = data;
3913 		} else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
3914 			if (sh->sh_type != SHT_PROGBITS)
3915 				return -LIBBPF_ERRNO__FORMAT;
3916 			btf_ext_data = data;
3917 		} else if (sh->sh_type == SHT_SYMTAB) {
3918 			/* already processed during the first pass above */
3919 		} else if (sh->sh_type == SHT_PROGBITS && data->d_size > 0) {
3920 			if (sh->sh_flags & SHF_EXECINSTR) {
3921 				if (strcmp(name, ".text") == 0)
3922 					obj->efile.text_shndx = idx;
3923 				err = bpf_object__add_programs(obj, data, name, idx);
3924 				if (err)
3925 					return err;
3926 			} else if (strcmp(name, DATA_SEC) == 0 ||
3927 				   str_has_pfx(name, DATA_SEC ".")) {
3928 				sec_desc->sec_type = SEC_DATA;
3929 				sec_desc->shdr = sh;
3930 				sec_desc->data = data;
3931 			} else if (strcmp(name, RODATA_SEC) == 0 ||
3932 				   str_has_pfx(name, RODATA_SEC ".")) {
3933 				sec_desc->sec_type = SEC_RODATA;
3934 				sec_desc->shdr = sh;
3935 				sec_desc->data = data;
3936 			} else if (strcmp(name, STRUCT_OPS_SEC) == 0 ||
3937 				   strcmp(name, STRUCT_OPS_LINK_SEC) == 0 ||
3938 				   strcmp(name, "?" STRUCT_OPS_SEC) == 0 ||
3939 				   strcmp(name, "?" STRUCT_OPS_LINK_SEC) == 0) {
3940 				sec_desc->sec_type = SEC_ST_OPS;
3941 				sec_desc->shdr = sh;
3942 				sec_desc->data = data;
3943 				obj->efile.has_st_ops = true;
3944 			} else if (strcmp(name, ARENA_SEC) == 0) {
3945 				obj->efile.arena_data = data;
3946 				obj->efile.arena_data_shndx = idx;
3947 			} else {
3948 				pr_info("elf: skipping unrecognized data section(%d) %s\n",
3949 					idx, name);
3950 			}
3951 		} else if (sh->sh_type == SHT_REL) {
3952 			int targ_sec_idx = sh->sh_info; /* points to other section */
3953 
3954 			if (sh->sh_entsize != sizeof(Elf64_Rel) ||
3955 			    targ_sec_idx >= obj->efile.sec_cnt)
3956 				return -LIBBPF_ERRNO__FORMAT;
3957 
3958 			/* Only do relo for section with exec instructions */
3959 			if (!section_have_execinstr(obj, targ_sec_idx) &&
3960 			    strcmp(name, ".rel" STRUCT_OPS_SEC) &&
3961 			    strcmp(name, ".rel" STRUCT_OPS_LINK_SEC) &&
3962 			    strcmp(name, ".rel?" STRUCT_OPS_SEC) &&
3963 			    strcmp(name, ".rel?" STRUCT_OPS_LINK_SEC) &&
3964 			    strcmp(name, ".rel" MAPS_ELF_SEC)) {
3965 				pr_info("elf: skipping relo section(%d) %s for section(%d) %s\n",
3966 					idx, name, targ_sec_idx,
3967 					elf_sec_name(obj, elf_sec_by_idx(obj, targ_sec_idx)) ?: "<?>");
3968 				continue;
3969 			}
3970 
3971 			sec_desc->sec_type = SEC_RELO;
3972 			sec_desc->shdr = sh;
3973 			sec_desc->data = data;
3974 		} else if (sh->sh_type == SHT_NOBITS && (strcmp(name, BSS_SEC) == 0 ||
3975 							 str_has_pfx(name, BSS_SEC "."))) {
3976 			sec_desc->sec_type = SEC_BSS;
3977 			sec_desc->shdr = sh;
3978 			sec_desc->data = data;
3979 		} else {
3980 			pr_info("elf: skipping section(%d) %s (size %zu)\n", idx, name,
3981 				(size_t)sh->sh_size);
3982 		}
3983 	}
3984 
3985 	if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) {
3986 		pr_warn("elf: symbol strings section missing or invalid in %s\n", obj->path);
3987 		return -LIBBPF_ERRNO__FORMAT;
3988 	}
3989 
3990 	/* change BPF program insns to native endianness for introspection */
3991 	if (!is_native_endianness(obj))
3992 		bpf_object_bswap_progs(obj);
3993 
3994 	/* sort BPF programs by section name and in-section instruction offset
3995 	 * for faster search
3996 	 */
3997 	if (obj->nr_programs)
3998 		qsort(obj->programs, obj->nr_programs, sizeof(*obj->programs), cmp_progs);
3999 
4000 	return bpf_object__init_btf(obj, btf_data, btf_ext_data);
4001 }
4002 
4003 static bool sym_is_extern(const Elf64_Sym *sym)
4004 {
4005 	int bind = ELF64_ST_BIND(sym->st_info);
4006 	/* externs are symbols w/ type=NOTYPE, bind=GLOBAL|WEAK, section=UND */
4007 	return sym->st_shndx == SHN_UNDEF &&
4008 	       (bind == STB_GLOBAL || bind == STB_WEAK) &&
4009 	       ELF64_ST_TYPE(sym->st_info) == STT_NOTYPE;
4010 }
4011 
4012 static bool sym_is_subprog(const Elf64_Sym *sym, int text_shndx)
4013 {
4014 	int bind = ELF64_ST_BIND(sym->st_info);
4015 	int type = ELF64_ST_TYPE(sym->st_info);
4016 
4017 	/* in .text section */
4018 	if (sym->st_shndx != text_shndx)
4019 		return false;
4020 
4021 	/* local function */
4022 	if (bind == STB_LOCAL && type == STT_SECTION)
4023 		return true;
4024 
4025 	/* global function */
4026 	return (bind == STB_GLOBAL || bind == STB_WEAK) && type == STT_FUNC;
4027 }
4028 
4029 static int find_extern_btf_id(const struct btf *btf, const char *ext_name)
4030 {
4031 	const struct btf_type *t;
4032 	const char *tname;
4033 	int i, n;
4034 
4035 	if (!btf)
4036 		return -ESRCH;
4037 
4038 	n = btf__type_cnt(btf);
4039 	for (i = 1; i < n; i++) {
4040 		t = btf__type_by_id(btf, i);
4041 
4042 		if (!btf_is_var(t) && !btf_is_func(t))
4043 			continue;
4044 
4045 		tname = btf__name_by_offset(btf, t->name_off);
4046 		if (strcmp(tname, ext_name))
4047 			continue;
4048 
4049 		if (btf_is_var(t) &&
4050 		    btf_var(t)->linkage != BTF_VAR_GLOBAL_EXTERN)
4051 			return -EINVAL;
4052 
4053 		if (btf_is_func(t) && btf_func_linkage(t) != BTF_FUNC_EXTERN)
4054 			return -EINVAL;
4055 
4056 		return i;
4057 	}
4058 
4059 	return -ENOENT;
4060 }
4061 
4062 static int find_extern_sec_btf_id(struct btf *btf, int ext_btf_id) {
4063 	const struct btf_var_secinfo *vs;
4064 	const struct btf_type *t;
4065 	int i, j, n;
4066 
4067 	if (!btf)
4068 		return -ESRCH;
4069 
4070 	n = btf__type_cnt(btf);
4071 	for (i = 1; i < n; i++) {
4072 		t = btf__type_by_id(btf, i);
4073 
4074 		if (!btf_is_datasec(t))
4075 			continue;
4076 
4077 		vs = btf_var_secinfos(t);
4078 		for (j = 0; j < btf_vlen(t); j++, vs++) {
4079 			if (vs->type == ext_btf_id)
4080 				return i;
4081 		}
4082 	}
4083 
4084 	return -ENOENT;
4085 }
4086 
4087 static enum kcfg_type find_kcfg_type(const struct btf *btf, int id,
4088 				     bool *is_signed)
4089 {
4090 	const struct btf_type *t;
4091 	const char *name;
4092 
4093 	t = skip_mods_and_typedefs(btf, id, NULL);
4094 	name = btf__name_by_offset(btf, t->name_off);
4095 
4096 	if (is_signed)
4097 		*is_signed = false;
4098 	switch (btf_kind(t)) {
4099 	case BTF_KIND_INT: {
4100 		int enc = btf_int_encoding(t);
4101 
4102 		if (enc & BTF_INT_BOOL)
4103 			return t->size == 1 ? KCFG_BOOL : KCFG_UNKNOWN;
4104 		if (is_signed)
4105 			*is_signed = enc & BTF_INT_SIGNED;
4106 		if (t->size == 1)
4107 			return KCFG_CHAR;
4108 		if (t->size < 1 || t->size > 8 || (t->size & (t->size - 1)))
4109 			return KCFG_UNKNOWN;
4110 		return KCFG_INT;
4111 	}
4112 	case BTF_KIND_ENUM:
4113 		if (t->size != 4)
4114 			return KCFG_UNKNOWN;
4115 		if (strcmp(name, "libbpf_tristate"))
4116 			return KCFG_UNKNOWN;
4117 		return KCFG_TRISTATE;
4118 	case BTF_KIND_ENUM64:
4119 		if (strcmp(name, "libbpf_tristate"))
4120 			return KCFG_UNKNOWN;
4121 		return KCFG_TRISTATE;
4122 	case BTF_KIND_ARRAY:
4123 		if (btf_array(t)->nelems == 0)
4124 			return KCFG_UNKNOWN;
4125 		if (find_kcfg_type(btf, btf_array(t)->type, NULL) != KCFG_CHAR)
4126 			return KCFG_UNKNOWN;
4127 		return KCFG_CHAR_ARR;
4128 	default:
4129 		return KCFG_UNKNOWN;
4130 	}
4131 }
4132 
4133 static int cmp_externs(const void *_a, const void *_b)
4134 {
4135 	const struct extern_desc *a = _a;
4136 	const struct extern_desc *b = _b;
4137 
4138 	if (a->type != b->type)
4139 		return a->type < b->type ? -1 : 1;
4140 
4141 	if (a->type == EXT_KCFG) {
4142 		/* descending order by alignment requirements */
4143 		if (a->kcfg.align != b->kcfg.align)
4144 			return a->kcfg.align > b->kcfg.align ? -1 : 1;
4145 		/* ascending order by size, within same alignment class */
4146 		if (a->kcfg.sz != b->kcfg.sz)
4147 			return a->kcfg.sz < b->kcfg.sz ? -1 : 1;
4148 	}
4149 
4150 	/* resolve ties by name */
4151 	return strcmp(a->name, b->name);
4152 }
4153 
4154 static int find_int_btf_id(const struct btf *btf)
4155 {
4156 	const struct btf_type *t;
4157 	int i, n;
4158 
4159 	n = btf__type_cnt(btf);
4160 	for (i = 1; i < n; i++) {
4161 		t = btf__type_by_id(btf, i);
4162 
4163 		if (btf_is_int(t) && btf_int_bits(t) == 32)
4164 			return i;
4165 	}
4166 
4167 	return 0;
4168 }
4169 
4170 static int add_dummy_ksym_var(struct btf *btf)
4171 {
4172 	int i, int_btf_id, sec_btf_id, dummy_var_btf_id;
4173 	const struct btf_var_secinfo *vs;
4174 	const struct btf_type *sec;
4175 
4176 	if (!btf)
4177 		return 0;
4178 
4179 	sec_btf_id = btf__find_by_name_kind(btf, KSYMS_SEC,
4180 					    BTF_KIND_DATASEC);
4181 	if (sec_btf_id < 0)
4182 		return 0;
4183 
4184 	sec = btf__type_by_id(btf, sec_btf_id);
4185 	vs = btf_var_secinfos(sec);
4186 	for (i = 0; i < btf_vlen(sec); i++, vs++) {
4187 		const struct btf_type *vt;
4188 
4189 		vt = btf__type_by_id(btf, vs->type);
4190 		if (btf_is_func(vt))
4191 			break;
4192 	}
4193 
4194 	/* No func in ksyms sec.  No need to add dummy var. */
4195 	if (i == btf_vlen(sec))
4196 		return 0;
4197 
4198 	int_btf_id = find_int_btf_id(btf);
4199 	dummy_var_btf_id = btf__add_var(btf,
4200 					"dummy_ksym",
4201 					BTF_VAR_GLOBAL_ALLOCATED,
4202 					int_btf_id);
4203 	if (dummy_var_btf_id < 0)
4204 		pr_warn("cannot create a dummy_ksym var\n");
4205 
4206 	return dummy_var_btf_id;
4207 }
4208 
4209 static int bpf_object__collect_externs(struct bpf_object *obj)
4210 {
4211 	struct btf_type *sec, *kcfg_sec = NULL, *ksym_sec = NULL;
4212 	const struct btf_type *t;
4213 	struct extern_desc *ext;
4214 	int i, n, off, dummy_var_btf_id;
4215 	const char *ext_name, *sec_name;
4216 	size_t ext_essent_len;
4217 	Elf_Scn *scn;
4218 	Elf64_Shdr *sh;
4219 
4220 	if (!obj->efile.symbols)
4221 		return 0;
4222 
4223 	scn = elf_sec_by_idx(obj, obj->efile.symbols_shndx);
4224 	sh = elf_sec_hdr(obj, scn);
4225 	if (!sh || sh->sh_entsize != sizeof(Elf64_Sym))
4226 		return -LIBBPF_ERRNO__FORMAT;
4227 
4228 	dummy_var_btf_id = add_dummy_ksym_var(obj->btf);
4229 	if (dummy_var_btf_id < 0)
4230 		return dummy_var_btf_id;
4231 
4232 	n = sh->sh_size / sh->sh_entsize;
4233 	pr_debug("looking for externs among %d symbols...\n", n);
4234 
4235 	for (i = 0; i < n; i++) {
4236 		Elf64_Sym *sym = elf_sym_by_idx(obj, i);
4237 
4238 		if (!sym)
4239 			return -LIBBPF_ERRNO__FORMAT;
4240 		if (!sym_is_extern(sym))
4241 			continue;
4242 		ext_name = elf_sym_str(obj, sym->st_name);
4243 		if (!ext_name || !ext_name[0])
4244 			continue;
4245 
4246 		ext = obj->externs;
4247 		ext = libbpf_reallocarray(ext, obj->nr_extern + 1, sizeof(*ext));
4248 		if (!ext)
4249 			return -ENOMEM;
4250 		obj->externs = ext;
4251 		ext = &ext[obj->nr_extern];
4252 		memset(ext, 0, sizeof(*ext));
4253 		obj->nr_extern++;
4254 
4255 		ext->btf_id = find_extern_btf_id(obj->btf, ext_name);
4256 		if (ext->btf_id <= 0) {
4257 			pr_warn("failed to find BTF for extern '%s': %d\n",
4258 				ext_name, ext->btf_id);
4259 			return ext->btf_id;
4260 		}
4261 		t = btf__type_by_id(obj->btf, ext->btf_id);
4262 		ext->name = btf__name_by_offset(obj->btf, t->name_off);
4263 		ext->sym_idx = i;
4264 		ext->is_weak = ELF64_ST_BIND(sym->st_info) == STB_WEAK;
4265 
4266 		ext_essent_len = bpf_core_essential_name_len(ext->name);
4267 		ext->essent_name = NULL;
4268 		if (ext_essent_len != strlen(ext->name)) {
4269 			ext->essent_name = strndup(ext->name, ext_essent_len);
4270 			if (!ext->essent_name)
4271 				return -ENOMEM;
4272 		}
4273 
4274 		ext->sec_btf_id = find_extern_sec_btf_id(obj->btf, ext->btf_id);
4275 		if (ext->sec_btf_id <= 0) {
4276 			pr_warn("failed to find BTF for extern '%s' [%d] section: %d\n",
4277 				ext_name, ext->btf_id, ext->sec_btf_id);
4278 			return ext->sec_btf_id;
4279 		}
4280 		sec = (void *)btf__type_by_id(obj->btf, ext->sec_btf_id);
4281 		sec_name = btf__name_by_offset(obj->btf, sec->name_off);
4282 
4283 		if (strcmp(sec_name, KCONFIG_SEC) == 0) {
4284 			if (btf_is_func(t)) {
4285 				pr_warn("extern function %s is unsupported under %s section\n",
4286 					ext->name, KCONFIG_SEC);
4287 				return -ENOTSUP;
4288 			}
4289 			kcfg_sec = sec;
4290 			ext->type = EXT_KCFG;
4291 			ext->kcfg.sz = btf__resolve_size(obj->btf, t->type);
4292 			if (ext->kcfg.sz <= 0) {
4293 				pr_warn("failed to resolve size of extern (kcfg) '%s': %d\n",
4294 					ext_name, ext->kcfg.sz);
4295 				return ext->kcfg.sz;
4296 			}
4297 			ext->kcfg.align = btf__align_of(obj->btf, t->type);
4298 			if (ext->kcfg.align <= 0) {
4299 				pr_warn("failed to determine alignment of extern (kcfg) '%s': %d\n",
4300 					ext_name, ext->kcfg.align);
4301 				return -EINVAL;
4302 			}
4303 			ext->kcfg.type = find_kcfg_type(obj->btf, t->type,
4304 							&ext->kcfg.is_signed);
4305 			if (ext->kcfg.type == KCFG_UNKNOWN) {
4306 				pr_warn("extern (kcfg) '%s': type is unsupported\n", ext_name);
4307 				return -ENOTSUP;
4308 			}
4309 		} else if (strcmp(sec_name, KSYMS_SEC) == 0) {
4310 			ksym_sec = sec;
4311 			ext->type = EXT_KSYM;
4312 			skip_mods_and_typedefs(obj->btf, t->type,
4313 					       &ext->ksym.type_id);
4314 		} else {
4315 			pr_warn("unrecognized extern section '%s'\n", sec_name);
4316 			return -ENOTSUP;
4317 		}
4318 	}
4319 	pr_debug("collected %d externs total\n", obj->nr_extern);
4320 
4321 	if (!obj->nr_extern)
4322 		return 0;
4323 
4324 	/* sort externs by type, for kcfg ones also by (align, size, name) */
4325 	qsort(obj->externs, obj->nr_extern, sizeof(*ext), cmp_externs);
4326 
4327 	/* for .ksyms section, we need to turn all externs into allocated
4328 	 * variables in BTF to pass kernel verification; we do this by
4329 	 * pretending that each extern is a 8-byte variable
4330 	 */
4331 	if (ksym_sec) {
4332 		/* find existing 4-byte integer type in BTF to use for fake
4333 		 * extern variables in DATASEC
4334 		 */
4335 		int int_btf_id = find_int_btf_id(obj->btf);
4336 		/* For extern function, a dummy_var added earlier
4337 		 * will be used to replace the vs->type and
4338 		 * its name string will be used to refill
4339 		 * the missing param's name.
4340 		 */
4341 		const struct btf_type *dummy_var;
4342 
4343 		dummy_var = btf__type_by_id(obj->btf, dummy_var_btf_id);
4344 		for (i = 0; i < obj->nr_extern; i++) {
4345 			ext = &obj->externs[i];
4346 			if (ext->type != EXT_KSYM)
4347 				continue;
4348 			pr_debug("extern (ksym) #%d: symbol %d, name %s\n",
4349 				 i, ext->sym_idx, ext->name);
4350 		}
4351 
4352 		sec = ksym_sec;
4353 		n = btf_vlen(sec);
4354 		for (i = 0, off = 0; i < n; i++, off += sizeof(int)) {
4355 			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
4356 			struct btf_type *vt;
4357 
4358 			vt = (void *)btf__type_by_id(obj->btf, vs->type);
4359 			ext_name = btf__name_by_offset(obj->btf, vt->name_off);
4360 			ext = find_extern_by_name(obj, ext_name);
4361 			if (!ext) {
4362 				pr_warn("failed to find extern definition for BTF %s '%s'\n",
4363 					btf_kind_str(vt), ext_name);
4364 				return -ESRCH;
4365 			}
4366 			if (btf_is_func(vt)) {
4367 				const struct btf_type *func_proto;
4368 				struct btf_param *param;
4369 				int j;
4370 
4371 				func_proto = btf__type_by_id(obj->btf,
4372 							     vt->type);
4373 				param = btf_params(func_proto);
4374 				/* Reuse the dummy_var string if the
4375 				 * func proto does not have param name.
4376 				 */
4377 				for (j = 0; j < btf_vlen(func_proto); j++)
4378 					if (param[j].type && !param[j].name_off)
4379 						param[j].name_off =
4380 							dummy_var->name_off;
4381 				vs->type = dummy_var_btf_id;
4382 				vt->info &= ~0xffff;
4383 				vt->info |= BTF_FUNC_GLOBAL;
4384 			} else {
4385 				btf_var(vt)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
4386 				vt->type = int_btf_id;
4387 			}
4388 			vs->offset = off;
4389 			vs->size = sizeof(int);
4390 		}
4391 		sec->size = off;
4392 	}
4393 
4394 	if (kcfg_sec) {
4395 		sec = kcfg_sec;
4396 		/* for kcfg externs calculate their offsets within a .kconfig map */
4397 		off = 0;
4398 		for (i = 0; i < obj->nr_extern; i++) {
4399 			ext = &obj->externs[i];
4400 			if (ext->type != EXT_KCFG)
4401 				continue;
4402 
4403 			ext->kcfg.data_off = roundup(off, ext->kcfg.align);
4404 			off = ext->kcfg.data_off + ext->kcfg.sz;
4405 			pr_debug("extern (kcfg) #%d: symbol %d, off %u, name %s\n",
4406 				 i, ext->sym_idx, ext->kcfg.data_off, ext->name);
4407 		}
4408 		sec->size = off;
4409 		n = btf_vlen(sec);
4410 		for (i = 0; i < n; i++) {
4411 			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
4412 
4413 			t = btf__type_by_id(obj->btf, vs->type);
4414 			ext_name = btf__name_by_offset(obj->btf, t->name_off);
4415 			ext = find_extern_by_name(obj, ext_name);
4416 			if (!ext) {
4417 				pr_warn("failed to find extern definition for BTF var '%s'\n",
4418 					ext_name);
4419 				return -ESRCH;
4420 			}
4421 			btf_var(t)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
4422 			vs->offset = ext->kcfg.data_off;
4423 		}
4424 	}
4425 	return 0;
4426 }
4427 
4428 static bool prog_is_subprog(const struct bpf_object *obj, const struct bpf_program *prog)
4429 {
4430 	return prog->sec_idx == obj->efile.text_shndx;
4431 }
4432 
4433 struct bpf_program *
4434 bpf_object__find_program_by_name(const struct bpf_object *obj,
4435 				 const char *name)
4436 {
4437 	struct bpf_program *prog;
4438 
4439 	bpf_object__for_each_program(prog, obj) {
4440 		if (prog_is_subprog(obj, prog))
4441 			continue;
4442 		if (!strcmp(prog->name, name))
4443 			return prog;
4444 	}
4445 	return errno = ENOENT, NULL;
4446 }
4447 
4448 static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
4449 				      int shndx)
4450 {
4451 	switch (obj->efile.secs[shndx].sec_type) {
4452 	case SEC_BSS:
4453 	case SEC_DATA:
4454 	case SEC_RODATA:
4455 		return true;
4456 	default:
4457 		return false;
4458 	}
4459 }
4460 
4461 static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
4462 				      int shndx)
4463 {
4464 	return shndx == obj->efile.btf_maps_shndx;
4465 }
4466 
4467 static enum libbpf_map_type
4468 bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
4469 {
4470 	if (shndx == obj->efile.symbols_shndx)
4471 		return LIBBPF_MAP_KCONFIG;
4472 
4473 	switch (obj->efile.secs[shndx].sec_type) {
4474 	case SEC_BSS:
4475 		return LIBBPF_MAP_BSS;
4476 	case SEC_DATA:
4477 		return LIBBPF_MAP_DATA;
4478 	case SEC_RODATA:
4479 		return LIBBPF_MAP_RODATA;
4480 	default:
4481 		return LIBBPF_MAP_UNSPEC;
4482 	}
4483 }
4484 
4485 static int bpf_program__record_reloc(struct bpf_program *prog,
4486 				     struct reloc_desc *reloc_desc,
4487 				     __u32 insn_idx, const char *sym_name,
4488 				     const Elf64_Sym *sym, const Elf64_Rel *rel)
4489 {
4490 	struct bpf_insn *insn = &prog->insns[insn_idx];
4491 	size_t map_idx, nr_maps = prog->obj->nr_maps;
4492 	struct bpf_object *obj = prog->obj;
4493 	__u32 shdr_idx = sym->st_shndx;
4494 	enum libbpf_map_type type;
4495 	const char *sym_sec_name;
4496 	struct bpf_map *map;
4497 
4498 	if (!is_call_insn(insn) && !is_ldimm64_insn(insn)) {
4499 		pr_warn("prog '%s': invalid relo against '%s' for insns[%d].code 0x%x\n",
4500 			prog->name, sym_name, insn_idx, insn->code);
4501 		return -LIBBPF_ERRNO__RELOC;
4502 	}
4503 
4504 	if (sym_is_extern(sym)) {
4505 		int sym_idx = ELF64_R_SYM(rel->r_info);
4506 		int i, n = obj->nr_extern;
4507 		struct extern_desc *ext;
4508 
4509 		for (i = 0; i < n; i++) {
4510 			ext = &obj->externs[i];
4511 			if (ext->sym_idx == sym_idx)
4512 				break;
4513 		}
4514 		if (i >= n) {
4515 			pr_warn("prog '%s': extern relo failed to find extern for '%s' (%d)\n",
4516 				prog->name, sym_name, sym_idx);
4517 			return -LIBBPF_ERRNO__RELOC;
4518 		}
4519 		pr_debug("prog '%s': found extern #%d '%s' (sym %d) for insn #%u\n",
4520 			 prog->name, i, ext->name, ext->sym_idx, insn_idx);
4521 		if (insn->code == (BPF_JMP | BPF_CALL))
4522 			reloc_desc->type = RELO_EXTERN_CALL;
4523 		else
4524 			reloc_desc->type = RELO_EXTERN_LD64;
4525 		reloc_desc->insn_idx = insn_idx;
4526 		reloc_desc->ext_idx = i;
4527 		return 0;
4528 	}
4529 
4530 	/* sub-program call relocation */
4531 	if (is_call_insn(insn)) {
4532 		if (insn->src_reg != BPF_PSEUDO_CALL) {
4533 			pr_warn("prog '%s': incorrect bpf_call opcode\n", prog->name);
4534 			return -LIBBPF_ERRNO__RELOC;
4535 		}
4536 		/* text_shndx can be 0, if no default "main" program exists */
4537 		if (!shdr_idx || shdr_idx != obj->efile.text_shndx) {
4538 			sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4539 			pr_warn("prog '%s': bad call relo against '%s' in section '%s'\n",
4540 				prog->name, sym_name, sym_sec_name);
4541 			return -LIBBPF_ERRNO__RELOC;
4542 		}
4543 		if (sym->st_value % BPF_INSN_SZ) {
4544 			pr_warn("prog '%s': bad call relo against '%s' at offset %zu\n",
4545 				prog->name, sym_name, (size_t)sym->st_value);
4546 			return -LIBBPF_ERRNO__RELOC;
4547 		}
4548 		reloc_desc->type = RELO_CALL;
4549 		reloc_desc->insn_idx = insn_idx;
4550 		reloc_desc->sym_off = sym->st_value;
4551 		return 0;
4552 	}
4553 
4554 	if (!shdr_idx || shdr_idx >= SHN_LORESERVE) {
4555 		pr_warn("prog '%s': invalid relo against '%s' in special section 0x%x; forgot to initialize global var?..\n",
4556 			prog->name, sym_name, shdr_idx);
4557 		return -LIBBPF_ERRNO__RELOC;
4558 	}
4559 
4560 	/* loading subprog addresses */
4561 	if (sym_is_subprog(sym, obj->efile.text_shndx)) {
4562 		/* global_func: sym->st_value = offset in the section, insn->imm = 0.
4563 		 * local_func: sym->st_value = 0, insn->imm = offset in the section.
4564 		 */
4565 		if ((sym->st_value % BPF_INSN_SZ) || (insn->imm % BPF_INSN_SZ)) {
4566 			pr_warn("prog '%s': bad subprog addr relo against '%s' at offset %zu+%d\n",
4567 				prog->name, sym_name, (size_t)sym->st_value, insn->imm);
4568 			return -LIBBPF_ERRNO__RELOC;
4569 		}
4570 
4571 		reloc_desc->type = RELO_SUBPROG_ADDR;
4572 		reloc_desc->insn_idx = insn_idx;
4573 		reloc_desc->sym_off = sym->st_value;
4574 		return 0;
4575 	}
4576 
4577 	type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
4578 	sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4579 
4580 	/* arena data relocation */
4581 	if (shdr_idx == obj->efile.arena_data_shndx) {
4582 		reloc_desc->type = RELO_DATA;
4583 		reloc_desc->insn_idx = insn_idx;
4584 		reloc_desc->map_idx = obj->arena_map - obj->maps;
4585 		reloc_desc->sym_off = sym->st_value;
4586 		return 0;
4587 	}
4588 
4589 	/* generic map reference relocation */
4590 	if (type == LIBBPF_MAP_UNSPEC) {
4591 		if (!bpf_object__shndx_is_maps(obj, shdr_idx)) {
4592 			pr_warn("prog '%s': bad map relo against '%s' in section '%s'\n",
4593 				prog->name, sym_name, sym_sec_name);
4594 			return -LIBBPF_ERRNO__RELOC;
4595 		}
4596 		for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4597 			map = &obj->maps[map_idx];
4598 			if (map->libbpf_type != type ||
4599 			    map->sec_idx != sym->st_shndx ||
4600 			    map->sec_offset != sym->st_value)
4601 				continue;
4602 			pr_debug("prog '%s': found map %zd (%s, sec %d, off %zu) for insn #%u\n",
4603 				 prog->name, map_idx, map->name, map->sec_idx,
4604 				 map->sec_offset, insn_idx);
4605 			break;
4606 		}
4607 		if (map_idx >= nr_maps) {
4608 			pr_warn("prog '%s': map relo failed to find map for section '%s', off %zu\n",
4609 				prog->name, sym_sec_name, (size_t)sym->st_value);
4610 			return -LIBBPF_ERRNO__RELOC;
4611 		}
4612 		reloc_desc->type = RELO_LD64;
4613 		reloc_desc->insn_idx = insn_idx;
4614 		reloc_desc->map_idx = map_idx;
4615 		reloc_desc->sym_off = 0; /* sym->st_value determines map_idx */
4616 		return 0;
4617 	}
4618 
4619 	/* global data map relocation */
4620 	if (!bpf_object__shndx_is_data(obj, shdr_idx)) {
4621 		pr_warn("prog '%s': bad data relo against section '%s'\n",
4622 			prog->name, sym_sec_name);
4623 		return -LIBBPF_ERRNO__RELOC;
4624 	}
4625 	for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4626 		map = &obj->maps[map_idx];
4627 		if (map->libbpf_type != type || map->sec_idx != sym->st_shndx)
4628 			continue;
4629 		pr_debug("prog '%s': found data map %zd (%s, sec %d, off %zu) for insn %u\n",
4630 			 prog->name, map_idx, map->name, map->sec_idx,
4631 			 map->sec_offset, insn_idx);
4632 		break;
4633 	}
4634 	if (map_idx >= nr_maps) {
4635 		pr_warn("prog '%s': data relo failed to find map for section '%s'\n",
4636 			prog->name, sym_sec_name);
4637 		return -LIBBPF_ERRNO__RELOC;
4638 	}
4639 
4640 	reloc_desc->type = RELO_DATA;
4641 	reloc_desc->insn_idx = insn_idx;
4642 	reloc_desc->map_idx = map_idx;
4643 	reloc_desc->sym_off = sym->st_value;
4644 	return 0;
4645 }
4646 
4647 static bool prog_contains_insn(const struct bpf_program *prog, size_t insn_idx)
4648 {
4649 	return insn_idx >= prog->sec_insn_off &&
4650 	       insn_idx < prog->sec_insn_off + prog->sec_insn_cnt;
4651 }
4652 
4653 static struct bpf_program *find_prog_by_sec_insn(const struct bpf_object *obj,
4654 						 size_t sec_idx, size_t insn_idx)
4655 {
4656 	int l = 0, r = obj->nr_programs - 1, m;
4657 	struct bpf_program *prog;
4658 
4659 	if (!obj->nr_programs)
4660 		return NULL;
4661 
4662 	while (l < r) {
4663 		m = l + (r - l + 1) / 2;
4664 		prog = &obj->programs[m];
4665 
4666 		if (prog->sec_idx < sec_idx ||
4667 		    (prog->sec_idx == sec_idx && prog->sec_insn_off <= insn_idx))
4668 			l = m;
4669 		else
4670 			r = m - 1;
4671 	}
4672 	/* matching program could be at index l, but it still might be the
4673 	 * wrong one, so we need to double check conditions for the last time
4674 	 */
4675 	prog = &obj->programs[l];
4676 	if (prog->sec_idx == sec_idx && prog_contains_insn(prog, insn_idx))
4677 		return prog;
4678 	return NULL;
4679 }
4680 
4681 static int
4682 bpf_object__collect_prog_relos(struct bpf_object *obj, Elf64_Shdr *shdr, Elf_Data *data)
4683 {
4684 	const char *relo_sec_name, *sec_name;
4685 	size_t sec_idx = shdr->sh_info, sym_idx;
4686 	struct bpf_program *prog;
4687 	struct reloc_desc *relos;
4688 	int err, i, nrels;
4689 	const char *sym_name;
4690 	__u32 insn_idx;
4691 	Elf_Scn *scn;
4692 	Elf_Data *scn_data;
4693 	Elf64_Sym *sym;
4694 	Elf64_Rel *rel;
4695 
4696 	if (sec_idx >= obj->efile.sec_cnt)
4697 		return -EINVAL;
4698 
4699 	scn = elf_sec_by_idx(obj, sec_idx);
4700 	scn_data = elf_sec_data(obj, scn);
4701 	if (!scn_data)
4702 		return -LIBBPF_ERRNO__FORMAT;
4703 
4704 	relo_sec_name = elf_sec_str(obj, shdr->sh_name);
4705 	sec_name = elf_sec_name(obj, scn);
4706 	if (!relo_sec_name || !sec_name)
4707 		return -EINVAL;
4708 
4709 	pr_debug("sec '%s': collecting relocation for section(%zu) '%s'\n",
4710 		 relo_sec_name, sec_idx, sec_name);
4711 	nrels = shdr->sh_size / shdr->sh_entsize;
4712 
4713 	for (i = 0; i < nrels; i++) {
4714 		rel = elf_rel_by_idx(data, i);
4715 		if (!rel) {
4716 			pr_warn("sec '%s': failed to get relo #%d\n", relo_sec_name, i);
4717 			return -LIBBPF_ERRNO__FORMAT;
4718 		}
4719 
4720 		sym_idx = ELF64_R_SYM(rel->r_info);
4721 		sym = elf_sym_by_idx(obj, sym_idx);
4722 		if (!sym) {
4723 			pr_warn("sec '%s': symbol #%zu not found for relo #%d\n",
4724 				relo_sec_name, sym_idx, i);
4725 			return -LIBBPF_ERRNO__FORMAT;
4726 		}
4727 
4728 		if (sym->st_shndx >= obj->efile.sec_cnt) {
4729 			pr_warn("sec '%s': corrupted symbol #%zu pointing to invalid section #%zu for relo #%d\n",
4730 				relo_sec_name, sym_idx, (size_t)sym->st_shndx, i);
4731 			return -LIBBPF_ERRNO__FORMAT;
4732 		}
4733 
4734 		if (rel->r_offset % BPF_INSN_SZ || rel->r_offset >= scn_data->d_size) {
4735 			pr_warn("sec '%s': invalid offset 0x%zx for relo #%d\n",
4736 				relo_sec_name, (size_t)rel->r_offset, i);
4737 			return -LIBBPF_ERRNO__FORMAT;
4738 		}
4739 
4740 		insn_idx = rel->r_offset / BPF_INSN_SZ;
4741 		/* relocations against static functions are recorded as
4742 		 * relocations against the section that contains a function;
4743 		 * in such case, symbol will be STT_SECTION and sym.st_name
4744 		 * will point to empty string (0), so fetch section name
4745 		 * instead
4746 		 */
4747 		if (ELF64_ST_TYPE(sym->st_info) == STT_SECTION && sym->st_name == 0)
4748 			sym_name = elf_sec_name(obj, elf_sec_by_idx(obj, sym->st_shndx));
4749 		else
4750 			sym_name = elf_sym_str(obj, sym->st_name);
4751 		sym_name = sym_name ?: "<?";
4752 
4753 		pr_debug("sec '%s': relo #%d: insn #%u against '%s'\n",
4754 			 relo_sec_name, i, insn_idx, sym_name);
4755 
4756 		prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
4757 		if (!prog) {
4758 			pr_debug("sec '%s': relo #%d: couldn't find program in section '%s' for insn #%u, probably overridden weak function, skipping...\n",
4759 				relo_sec_name, i, sec_name, insn_idx);
4760 			continue;
4761 		}
4762 
4763 		relos = libbpf_reallocarray(prog->reloc_desc,
4764 					    prog->nr_reloc + 1, sizeof(*relos));
4765 		if (!relos)
4766 			return -ENOMEM;
4767 		prog->reloc_desc = relos;
4768 
4769 		/* adjust insn_idx to local BPF program frame of reference */
4770 		insn_idx -= prog->sec_insn_off;
4771 		err = bpf_program__record_reloc(prog, &relos[prog->nr_reloc],
4772 						insn_idx, sym_name, sym, rel);
4773 		if (err)
4774 			return err;
4775 
4776 		prog->nr_reloc++;
4777 	}
4778 	return 0;
4779 }
4780 
4781 static int map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map)
4782 {
4783 	int id;
4784 
4785 	if (!obj->btf)
4786 		return -ENOENT;
4787 
4788 	/* if it's BTF-defined map, we don't need to search for type IDs.
4789 	 * For struct_ops map, it does not need btf_key_type_id and
4790 	 * btf_value_type_id.
4791 	 */
4792 	if (map->sec_idx == obj->efile.btf_maps_shndx || bpf_map__is_struct_ops(map))
4793 		return 0;
4794 
4795 	/*
4796 	 * LLVM annotates global data differently in BTF, that is,
4797 	 * only as '.data', '.bss' or '.rodata'.
4798 	 */
4799 	if (!bpf_map__is_internal(map))
4800 		return -ENOENT;
4801 
4802 	id = btf__find_by_name(obj->btf, map->real_name);
4803 	if (id < 0)
4804 		return id;
4805 
4806 	map->btf_key_type_id = 0;
4807 	map->btf_value_type_id = id;
4808 	return 0;
4809 }
4810 
4811 static int bpf_get_map_info_from_fdinfo(int fd, struct bpf_map_info *info)
4812 {
4813 	char file[PATH_MAX], buff[4096];
4814 	FILE *fp;
4815 	__u32 val;
4816 	int err;
4817 
4818 	snprintf(file, sizeof(file), "/proc/%d/fdinfo/%d", getpid(), fd);
4819 	memset(info, 0, sizeof(*info));
4820 
4821 	fp = fopen(file, "re");
4822 	if (!fp) {
4823 		err = -errno;
4824 		pr_warn("failed to open %s: %s. No procfs support?\n", file,
4825 			errstr(err));
4826 		return err;
4827 	}
4828 
4829 	while (fgets(buff, sizeof(buff), fp)) {
4830 		if (sscanf(buff, "map_type:\t%u", &val) == 1)
4831 			info->type = val;
4832 		else if (sscanf(buff, "key_size:\t%u", &val) == 1)
4833 			info->key_size = val;
4834 		else if (sscanf(buff, "value_size:\t%u", &val) == 1)
4835 			info->value_size = val;
4836 		else if (sscanf(buff, "max_entries:\t%u", &val) == 1)
4837 			info->max_entries = val;
4838 		else if (sscanf(buff, "map_flags:\t%i", &val) == 1)
4839 			info->map_flags = val;
4840 	}
4841 
4842 	fclose(fp);
4843 
4844 	return 0;
4845 }
4846 
4847 static bool map_is_created(const struct bpf_map *map)
4848 {
4849 	return map->obj->state >= OBJ_PREPARED || map->reused;
4850 }
4851 
4852 bool bpf_map__autocreate(const struct bpf_map *map)
4853 {
4854 	return map->autocreate;
4855 }
4856 
4857 int bpf_map__set_autocreate(struct bpf_map *map, bool autocreate)
4858 {
4859 	if (map_is_created(map))
4860 		return libbpf_err(-EBUSY);
4861 
4862 	map->autocreate = autocreate;
4863 	return 0;
4864 }
4865 
4866 int bpf_map__set_autoattach(struct bpf_map *map, bool autoattach)
4867 {
4868 	if (!bpf_map__is_struct_ops(map))
4869 		return libbpf_err(-EINVAL);
4870 
4871 	map->autoattach = autoattach;
4872 	return 0;
4873 }
4874 
4875 bool bpf_map__autoattach(const struct bpf_map *map)
4876 {
4877 	return map->autoattach;
4878 }
4879 
4880 int bpf_map__reuse_fd(struct bpf_map *map, int fd)
4881 {
4882 	struct bpf_map_info info;
4883 	__u32 len = sizeof(info), name_len;
4884 	int new_fd, err;
4885 	char *new_name;
4886 
4887 	memset(&info, 0, len);
4888 	err = bpf_map_get_info_by_fd(fd, &info, &len);
4889 	if (err && errno == EINVAL)
4890 		err = bpf_get_map_info_from_fdinfo(fd, &info);
4891 	if (err)
4892 		return libbpf_err(err);
4893 
4894 	name_len = strlen(info.name);
4895 	if (name_len == BPF_OBJ_NAME_LEN - 1 && strncmp(map->name, info.name, name_len) == 0)
4896 		new_name = strdup(map->name);
4897 	else
4898 		new_name = strdup(info.name);
4899 
4900 	if (!new_name)
4901 		return libbpf_err(-errno);
4902 
4903 	/*
4904 	 * Like dup(), but make sure new FD is >= 3 and has O_CLOEXEC set.
4905 	 * This is similar to what we do in ensure_good_fd(), but without
4906 	 * closing original FD.
4907 	 */
4908 	new_fd = fcntl(fd, F_DUPFD_CLOEXEC, 3);
4909 	if (new_fd < 0) {
4910 		err = -errno;
4911 		goto err_free_new_name;
4912 	}
4913 
4914 	err = reuse_fd(map->fd, new_fd);
4915 	if (err)
4916 		goto err_free_new_name;
4917 
4918 	free(map->name);
4919 
4920 	map->name = new_name;
4921 	map->def.type = info.type;
4922 	map->def.key_size = info.key_size;
4923 	map->def.value_size = info.value_size;
4924 	map->def.max_entries = info.max_entries;
4925 	map->def.map_flags = info.map_flags;
4926 	map->btf_key_type_id = info.btf_key_type_id;
4927 	map->btf_value_type_id = info.btf_value_type_id;
4928 	map->reused = true;
4929 	map->map_extra = info.map_extra;
4930 
4931 	return 0;
4932 
4933 err_free_new_name:
4934 	free(new_name);
4935 	return libbpf_err(err);
4936 }
4937 
4938 __u32 bpf_map__max_entries(const struct bpf_map *map)
4939 {
4940 	return map->def.max_entries;
4941 }
4942 
4943 struct bpf_map *bpf_map__inner_map(struct bpf_map *map)
4944 {
4945 	if (!bpf_map_type__is_map_in_map(map->def.type))
4946 		return errno = EINVAL, NULL;
4947 
4948 	return map->inner_map;
4949 }
4950 
4951 int bpf_map__set_max_entries(struct bpf_map *map, __u32 max_entries)
4952 {
4953 	if (map_is_created(map))
4954 		return libbpf_err(-EBUSY);
4955 
4956 	map->def.max_entries = max_entries;
4957 
4958 	/* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
4959 	if (map_is_ringbuf(map))
4960 		map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
4961 
4962 	return 0;
4963 }
4964 
4965 static int bpf_object_prepare_token(struct bpf_object *obj)
4966 {
4967 	const char *bpffs_path;
4968 	int bpffs_fd = -1, token_fd, err;
4969 	bool mandatory;
4970 	enum libbpf_print_level level;
4971 
4972 	/* token is explicitly prevented */
4973 	if (obj->token_path && obj->token_path[0] == '\0') {
4974 		pr_debug("object '%s': token is prevented, skipping...\n", obj->name);
4975 		return 0;
4976 	}
4977 
4978 	mandatory = obj->token_path != NULL;
4979 	level = mandatory ? LIBBPF_WARN : LIBBPF_DEBUG;
4980 
4981 	bpffs_path = obj->token_path ?: BPF_FS_DEFAULT_PATH;
4982 	bpffs_fd = open(bpffs_path, O_DIRECTORY, O_RDWR);
4983 	if (bpffs_fd < 0) {
4984 		err = -errno;
4985 		__pr(level, "object '%s': failed (%s) to open BPF FS mount at '%s'%s\n",
4986 		     obj->name, errstr(err), bpffs_path,
4987 		     mandatory ? "" : ", skipping optional step...");
4988 		return mandatory ? err : 0;
4989 	}
4990 
4991 	token_fd = bpf_token_create(bpffs_fd, 0);
4992 	close(bpffs_fd);
4993 	if (token_fd < 0) {
4994 		if (!mandatory && token_fd == -ENOENT) {
4995 			pr_debug("object '%s': BPF FS at '%s' doesn't have BPF token delegation set up, skipping...\n",
4996 				 obj->name, bpffs_path);
4997 			return 0;
4998 		}
4999 		__pr(level, "object '%s': failed (%d) to create BPF token from '%s'%s\n",
5000 		     obj->name, token_fd, bpffs_path,
5001 		     mandatory ? "" : ", skipping optional step...");
5002 		return mandatory ? token_fd : 0;
5003 	}
5004 
5005 	obj->feat_cache = calloc(1, sizeof(*obj->feat_cache));
5006 	if (!obj->feat_cache) {
5007 		close(token_fd);
5008 		return -ENOMEM;
5009 	}
5010 
5011 	obj->token_fd = token_fd;
5012 	obj->feat_cache->token_fd = token_fd;
5013 
5014 	return 0;
5015 }
5016 
5017 static int
5018 bpf_object__probe_loading(struct bpf_object *obj)
5019 {
5020 	struct bpf_insn insns[] = {
5021 		BPF_MOV64_IMM(BPF_REG_0, 0),
5022 		BPF_EXIT_INSN(),
5023 	};
5024 	int ret, insn_cnt = ARRAY_SIZE(insns);
5025 	LIBBPF_OPTS(bpf_prog_load_opts, opts,
5026 		.token_fd = obj->token_fd,
5027 		.prog_flags = obj->token_fd ? BPF_F_TOKEN_FD : 0,
5028 	);
5029 
5030 	if (obj->gen_loader)
5031 		return 0;
5032 
5033 	ret = bump_rlimit_memlock();
5034 	if (ret)
5035 		pr_warn("Failed to bump RLIMIT_MEMLOCK (err = %s), you might need to do it explicitly!\n",
5036 			errstr(ret));
5037 
5038 	/* make sure basic loading works */
5039 	ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, &opts);
5040 	if (ret < 0)
5041 		ret = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, &opts);
5042 	if (ret < 0) {
5043 		ret = errno;
5044 		pr_warn("Error in %s(): %s. Couldn't load trivial BPF program. Make sure your kernel supports BPF (CONFIG_BPF_SYSCALL=y) and/or that RLIMIT_MEMLOCK is set to big enough value.\n",
5045 			__func__, errstr(ret));
5046 		return -ret;
5047 	}
5048 	close(ret);
5049 
5050 	return 0;
5051 }
5052 
5053 bool kernel_supports(const struct bpf_object *obj, enum kern_feature_id feat_id)
5054 {
5055 	if (obj->gen_loader)
5056 		/* To generate loader program assume the latest kernel
5057 		 * to avoid doing extra prog_load, map_create syscalls.
5058 		 */
5059 		return true;
5060 
5061 	if (obj->token_fd)
5062 		return feat_supported(obj->feat_cache, feat_id);
5063 
5064 	return feat_supported(NULL, feat_id);
5065 }
5066 
5067 static bool map_is_reuse_compat(const struct bpf_map *map, int map_fd)
5068 {
5069 	struct bpf_map_info map_info;
5070 	__u32 map_info_len = sizeof(map_info);
5071 	int err;
5072 
5073 	memset(&map_info, 0, map_info_len);
5074 	err = bpf_map_get_info_by_fd(map_fd, &map_info, &map_info_len);
5075 	if (err && errno == EINVAL)
5076 		err = bpf_get_map_info_from_fdinfo(map_fd, &map_info);
5077 	if (err) {
5078 		pr_warn("failed to get map info for map FD %d: %s\n", map_fd,
5079 			errstr(err));
5080 		return false;
5081 	}
5082 
5083 	return (map_info.type == map->def.type &&
5084 		map_info.key_size == map->def.key_size &&
5085 		map_info.value_size == map->def.value_size &&
5086 		map_info.max_entries == map->def.max_entries &&
5087 		map_info.map_flags == map->def.map_flags &&
5088 		map_info.map_extra == map->map_extra);
5089 }
5090 
5091 static int
5092 bpf_object__reuse_map(struct bpf_map *map)
5093 {
5094 	int err, pin_fd;
5095 
5096 	pin_fd = bpf_obj_get(map->pin_path);
5097 	if (pin_fd < 0) {
5098 		err = -errno;
5099 		if (err == -ENOENT) {
5100 			pr_debug("found no pinned map to reuse at '%s'\n",
5101 				 map->pin_path);
5102 			return 0;
5103 		}
5104 
5105 		pr_warn("couldn't retrieve pinned map '%s': %s\n",
5106 			map->pin_path, errstr(err));
5107 		return err;
5108 	}
5109 
5110 	if (!map_is_reuse_compat(map, pin_fd)) {
5111 		pr_warn("couldn't reuse pinned map at '%s': parameter mismatch\n",
5112 			map->pin_path);
5113 		close(pin_fd);
5114 		return -EINVAL;
5115 	}
5116 
5117 	err = bpf_map__reuse_fd(map, pin_fd);
5118 	close(pin_fd);
5119 	if (err)
5120 		return err;
5121 
5122 	map->pinned = true;
5123 	pr_debug("reused pinned map at '%s'\n", map->pin_path);
5124 
5125 	return 0;
5126 }
5127 
5128 static int
5129 bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
5130 {
5131 	enum libbpf_map_type map_type = map->libbpf_type;
5132 	int err, zero = 0;
5133 	size_t mmap_sz;
5134 
5135 	if (obj->gen_loader) {
5136 		bpf_gen__map_update_elem(obj->gen_loader, map - obj->maps,
5137 					 map->mmaped, map->def.value_size);
5138 		if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG)
5139 			bpf_gen__map_freeze(obj->gen_loader, map - obj->maps);
5140 		return 0;
5141 	}
5142 
5143 	err = bpf_map_update_elem(map->fd, &zero, map->mmaped, 0);
5144 	if (err) {
5145 		err = -errno;
5146 		pr_warn("map '%s': failed to set initial contents: %s\n",
5147 			bpf_map__name(map), errstr(err));
5148 		return err;
5149 	}
5150 
5151 	/* Freeze .rodata and .kconfig map as read-only from syscall side. */
5152 	if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG) {
5153 		err = bpf_map_freeze(map->fd);
5154 		if (err) {
5155 			err = -errno;
5156 			pr_warn("map '%s': failed to freeze as read-only: %s\n",
5157 				bpf_map__name(map), errstr(err));
5158 			return err;
5159 		}
5160 	}
5161 
5162 	/* Remap anonymous mmap()-ed "map initialization image" as
5163 	 * a BPF map-backed mmap()-ed memory, but preserving the same
5164 	 * memory address. This will cause kernel to change process'
5165 	 * page table to point to a different piece of kernel memory,
5166 	 * but from userspace point of view memory address (and its
5167 	 * contents, being identical at this point) will stay the
5168 	 * same. This mapping will be released by bpf_object__close()
5169 	 * as per normal clean up procedure.
5170 	 */
5171 	mmap_sz = bpf_map_mmap_sz(map);
5172 	if (map->def.map_flags & BPF_F_MMAPABLE) {
5173 		void *mmaped;
5174 		int prot;
5175 
5176 		if (map->def.map_flags & BPF_F_RDONLY_PROG)
5177 			prot = PROT_READ;
5178 		else
5179 			prot = PROT_READ | PROT_WRITE;
5180 		mmaped = mmap(map->mmaped, mmap_sz, prot, MAP_SHARED | MAP_FIXED, map->fd, 0);
5181 		if (mmaped == MAP_FAILED) {
5182 			err = -errno;
5183 			pr_warn("map '%s': failed to re-mmap() contents: %s\n",
5184 				bpf_map__name(map), errstr(err));
5185 			return err;
5186 		}
5187 		map->mmaped = mmaped;
5188 	} else if (map->mmaped) {
5189 		munmap(map->mmaped, mmap_sz);
5190 		map->mmaped = NULL;
5191 	}
5192 
5193 	return 0;
5194 }
5195 
5196 static void bpf_map__destroy(struct bpf_map *map);
5197 
5198 static int bpf_object__create_map(struct bpf_object *obj, struct bpf_map *map, bool is_inner)
5199 {
5200 	LIBBPF_OPTS(bpf_map_create_opts, create_attr);
5201 	struct bpf_map_def *def = &map->def;
5202 	const char *map_name = NULL;
5203 	int err = 0, map_fd;
5204 
5205 	if (kernel_supports(obj, FEAT_PROG_NAME))
5206 		map_name = map->name;
5207 	create_attr.map_ifindex = map->map_ifindex;
5208 	create_attr.map_flags = def->map_flags;
5209 	create_attr.numa_node = map->numa_node;
5210 	create_attr.map_extra = map->map_extra;
5211 	create_attr.token_fd = obj->token_fd;
5212 	if (obj->token_fd)
5213 		create_attr.map_flags |= BPF_F_TOKEN_FD;
5214 
5215 	if (bpf_map__is_struct_ops(map)) {
5216 		create_attr.btf_vmlinux_value_type_id = map->btf_vmlinux_value_type_id;
5217 		if (map->mod_btf_fd >= 0) {
5218 			create_attr.value_type_btf_obj_fd = map->mod_btf_fd;
5219 			create_attr.map_flags |= BPF_F_VTYPE_BTF_OBJ_FD;
5220 		}
5221 	}
5222 
5223 	if (obj->btf && btf__fd(obj->btf) >= 0) {
5224 		create_attr.btf_fd = btf__fd(obj->btf);
5225 		create_attr.btf_key_type_id = map->btf_key_type_id;
5226 		create_attr.btf_value_type_id = map->btf_value_type_id;
5227 	}
5228 
5229 	if (bpf_map_type__is_map_in_map(def->type)) {
5230 		if (map->inner_map) {
5231 			err = map_set_def_max_entries(map->inner_map);
5232 			if (err)
5233 				return err;
5234 			err = bpf_object__create_map(obj, map->inner_map, true);
5235 			if (err) {
5236 				pr_warn("map '%s': failed to create inner map: %s\n",
5237 					map->name, errstr(err));
5238 				return err;
5239 			}
5240 			map->inner_map_fd = map->inner_map->fd;
5241 		}
5242 		if (map->inner_map_fd >= 0)
5243 			create_attr.inner_map_fd = map->inner_map_fd;
5244 	}
5245 
5246 	switch (def->type) {
5247 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
5248 	case BPF_MAP_TYPE_CGROUP_ARRAY:
5249 	case BPF_MAP_TYPE_STACK_TRACE:
5250 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
5251 	case BPF_MAP_TYPE_HASH_OF_MAPS:
5252 	case BPF_MAP_TYPE_DEVMAP:
5253 	case BPF_MAP_TYPE_DEVMAP_HASH:
5254 	case BPF_MAP_TYPE_CPUMAP:
5255 	case BPF_MAP_TYPE_XSKMAP:
5256 	case BPF_MAP_TYPE_SOCKMAP:
5257 	case BPF_MAP_TYPE_SOCKHASH:
5258 	case BPF_MAP_TYPE_QUEUE:
5259 	case BPF_MAP_TYPE_STACK:
5260 	case BPF_MAP_TYPE_ARENA:
5261 		create_attr.btf_fd = 0;
5262 		create_attr.btf_key_type_id = 0;
5263 		create_attr.btf_value_type_id = 0;
5264 		map->btf_key_type_id = 0;
5265 		map->btf_value_type_id = 0;
5266 		break;
5267 	case BPF_MAP_TYPE_STRUCT_OPS:
5268 		create_attr.btf_value_type_id = 0;
5269 		break;
5270 	default:
5271 		break;
5272 	}
5273 
5274 	if (obj->gen_loader) {
5275 		bpf_gen__map_create(obj->gen_loader, def->type, map_name,
5276 				    def->key_size, def->value_size, def->max_entries,
5277 				    &create_attr, is_inner ? -1 : map - obj->maps);
5278 		/* We keep pretenting we have valid FD to pass various fd >= 0
5279 		 * checks by just keeping original placeholder FDs in place.
5280 		 * See bpf_object__add_map() comment.
5281 		 * This placeholder fd will not be used with any syscall and
5282 		 * will be reset to -1 eventually.
5283 		 */
5284 		map_fd = map->fd;
5285 	} else {
5286 		map_fd = bpf_map_create(def->type, map_name,
5287 					def->key_size, def->value_size,
5288 					def->max_entries, &create_attr);
5289 	}
5290 	if (map_fd < 0 && (create_attr.btf_key_type_id || create_attr.btf_value_type_id)) {
5291 		err = -errno;
5292 		pr_warn("Error in bpf_create_map_xattr(%s): %s. Retrying without BTF.\n",
5293 			map->name, errstr(err));
5294 		create_attr.btf_fd = 0;
5295 		create_attr.btf_key_type_id = 0;
5296 		create_attr.btf_value_type_id = 0;
5297 		map->btf_key_type_id = 0;
5298 		map->btf_value_type_id = 0;
5299 		map_fd = bpf_map_create(def->type, map_name,
5300 					def->key_size, def->value_size,
5301 					def->max_entries, &create_attr);
5302 	}
5303 
5304 	if (bpf_map_type__is_map_in_map(def->type) && map->inner_map) {
5305 		if (obj->gen_loader)
5306 			map->inner_map->fd = -1;
5307 		bpf_map__destroy(map->inner_map);
5308 		zfree(&map->inner_map);
5309 	}
5310 
5311 	if (map_fd < 0)
5312 		return map_fd;
5313 
5314 	/* obj->gen_loader case, prevent reuse_fd() from closing map_fd */
5315 	if (map->fd == map_fd)
5316 		return 0;
5317 
5318 	/* Keep placeholder FD value but now point it to the BPF map object.
5319 	 * This way everything that relied on this map's FD (e.g., relocated
5320 	 * ldimm64 instructions) will stay valid and won't need adjustments.
5321 	 * map->fd stays valid but now point to what map_fd points to.
5322 	 */
5323 	return reuse_fd(map->fd, map_fd);
5324 }
5325 
5326 static int init_map_in_map_slots(struct bpf_object *obj, struct bpf_map *map)
5327 {
5328 	const struct bpf_map *targ_map;
5329 	unsigned int i;
5330 	int fd, err = 0;
5331 
5332 	for (i = 0; i < map->init_slots_sz; i++) {
5333 		if (!map->init_slots[i])
5334 			continue;
5335 
5336 		targ_map = map->init_slots[i];
5337 		fd = targ_map->fd;
5338 
5339 		if (obj->gen_loader) {
5340 			bpf_gen__populate_outer_map(obj->gen_loader,
5341 						    map - obj->maps, i,
5342 						    targ_map - obj->maps);
5343 		} else {
5344 			err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5345 		}
5346 		if (err) {
5347 			err = -errno;
5348 			pr_warn("map '%s': failed to initialize slot [%d] to map '%s' fd=%d: %s\n",
5349 				map->name, i, targ_map->name, fd, errstr(err));
5350 			return err;
5351 		}
5352 		pr_debug("map '%s': slot [%d] set to map '%s' fd=%d\n",
5353 			 map->name, i, targ_map->name, fd);
5354 	}
5355 
5356 	zfree(&map->init_slots);
5357 	map->init_slots_sz = 0;
5358 
5359 	return 0;
5360 }
5361 
5362 static int init_prog_array_slots(struct bpf_object *obj, struct bpf_map *map)
5363 {
5364 	const struct bpf_program *targ_prog;
5365 	unsigned int i;
5366 	int fd, err;
5367 
5368 	if (obj->gen_loader)
5369 		return -ENOTSUP;
5370 
5371 	for (i = 0; i < map->init_slots_sz; i++) {
5372 		if (!map->init_slots[i])
5373 			continue;
5374 
5375 		targ_prog = map->init_slots[i];
5376 		fd = bpf_program__fd(targ_prog);
5377 
5378 		err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5379 		if (err) {
5380 			err = -errno;
5381 			pr_warn("map '%s': failed to initialize slot [%d] to prog '%s' fd=%d: %s\n",
5382 				map->name, i, targ_prog->name, fd, errstr(err));
5383 			return err;
5384 		}
5385 		pr_debug("map '%s': slot [%d] set to prog '%s' fd=%d\n",
5386 			 map->name, i, targ_prog->name, fd);
5387 	}
5388 
5389 	zfree(&map->init_slots);
5390 	map->init_slots_sz = 0;
5391 
5392 	return 0;
5393 }
5394 
5395 static int bpf_object_init_prog_arrays(struct bpf_object *obj)
5396 {
5397 	struct bpf_map *map;
5398 	int i, err;
5399 
5400 	for (i = 0; i < obj->nr_maps; i++) {
5401 		map = &obj->maps[i];
5402 
5403 		if (!map->init_slots_sz || map->def.type != BPF_MAP_TYPE_PROG_ARRAY)
5404 			continue;
5405 
5406 		err = init_prog_array_slots(obj, map);
5407 		if (err < 0)
5408 			return err;
5409 	}
5410 	return 0;
5411 }
5412 
5413 static int map_set_def_max_entries(struct bpf_map *map)
5414 {
5415 	if (map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY && !map->def.max_entries) {
5416 		int nr_cpus;
5417 
5418 		nr_cpus = libbpf_num_possible_cpus();
5419 		if (nr_cpus < 0) {
5420 			pr_warn("map '%s': failed to determine number of system CPUs: %d\n",
5421 				map->name, nr_cpus);
5422 			return nr_cpus;
5423 		}
5424 		pr_debug("map '%s': setting size to %d\n", map->name, nr_cpus);
5425 		map->def.max_entries = nr_cpus;
5426 	}
5427 
5428 	return 0;
5429 }
5430 
5431 static int
5432 bpf_object__create_maps(struct bpf_object *obj)
5433 {
5434 	struct bpf_map *map;
5435 	unsigned int i, j;
5436 	int err;
5437 	bool retried;
5438 
5439 	for (i = 0; i < obj->nr_maps; i++) {
5440 		map = &obj->maps[i];
5441 
5442 		/* To support old kernels, we skip creating global data maps
5443 		 * (.rodata, .data, .kconfig, etc); later on, during program
5444 		 * loading, if we detect that at least one of the to-be-loaded
5445 		 * programs is referencing any global data map, we'll error
5446 		 * out with program name and relocation index logged.
5447 		 * This approach allows to accommodate Clang emitting
5448 		 * unnecessary .rodata.str1.1 sections for string literals,
5449 		 * but also it allows to have CO-RE applications that use
5450 		 * global variables in some of BPF programs, but not others.
5451 		 * If those global variable-using programs are not loaded at
5452 		 * runtime due to bpf_program__set_autoload(prog, false),
5453 		 * bpf_object loading will succeed just fine even on old
5454 		 * kernels.
5455 		 */
5456 		if (bpf_map__is_internal(map) && !kernel_supports(obj, FEAT_GLOBAL_DATA))
5457 			map->autocreate = false;
5458 
5459 		if (!map->autocreate) {
5460 			pr_debug("map '%s': skipped auto-creating...\n", map->name);
5461 			continue;
5462 		}
5463 
5464 		err = map_set_def_max_entries(map);
5465 		if (err)
5466 			goto err_out;
5467 
5468 		retried = false;
5469 retry:
5470 		if (map->pin_path) {
5471 			err = bpf_object__reuse_map(map);
5472 			if (err) {
5473 				pr_warn("map '%s': error reusing pinned map\n",
5474 					map->name);
5475 				goto err_out;
5476 			}
5477 			if (retried && map->fd < 0) {
5478 				pr_warn("map '%s': cannot find pinned map\n",
5479 					map->name);
5480 				err = -ENOENT;
5481 				goto err_out;
5482 			}
5483 		}
5484 
5485 		if (map->reused) {
5486 			pr_debug("map '%s': skipping creation (preset fd=%d)\n",
5487 				 map->name, map->fd);
5488 		} else {
5489 			err = bpf_object__create_map(obj, map, false);
5490 			if (err)
5491 				goto err_out;
5492 
5493 			pr_debug("map '%s': created successfully, fd=%d\n",
5494 				 map->name, map->fd);
5495 
5496 			if (bpf_map__is_internal(map)) {
5497 				err = bpf_object__populate_internal_map(obj, map);
5498 				if (err < 0)
5499 					goto err_out;
5500 			} else if (map->def.type == BPF_MAP_TYPE_ARENA) {
5501 				map->mmaped = mmap((void *)(long)map->map_extra,
5502 						   bpf_map_mmap_sz(map), PROT_READ | PROT_WRITE,
5503 						   map->map_extra ? MAP_SHARED | MAP_FIXED : MAP_SHARED,
5504 						   map->fd, 0);
5505 				if (map->mmaped == MAP_FAILED) {
5506 					err = -errno;
5507 					map->mmaped = NULL;
5508 					pr_warn("map '%s': failed to mmap arena: %s\n",
5509 						map->name, errstr(err));
5510 					return err;
5511 				}
5512 				if (obj->arena_data) {
5513 					memcpy(map->mmaped, obj->arena_data, obj->arena_data_sz);
5514 					zfree(&obj->arena_data);
5515 				}
5516 			}
5517 			if (map->init_slots_sz && map->def.type != BPF_MAP_TYPE_PROG_ARRAY) {
5518 				err = init_map_in_map_slots(obj, map);
5519 				if (err < 0)
5520 					goto err_out;
5521 			}
5522 		}
5523 
5524 		if (map->pin_path && !map->pinned) {
5525 			err = bpf_map__pin(map, NULL);
5526 			if (err) {
5527 				if (!retried && err == -EEXIST) {
5528 					retried = true;
5529 					goto retry;
5530 				}
5531 				pr_warn("map '%s': failed to auto-pin at '%s': %s\n",
5532 					map->name, map->pin_path, errstr(err));
5533 				goto err_out;
5534 			}
5535 		}
5536 	}
5537 
5538 	return 0;
5539 
5540 err_out:
5541 	pr_warn("map '%s': failed to create: %s\n", map->name, errstr(err));
5542 	pr_perm_msg(err);
5543 	for (j = 0; j < i; j++)
5544 		zclose(obj->maps[j].fd);
5545 	return err;
5546 }
5547 
5548 static bool bpf_core_is_flavor_sep(const char *s)
5549 {
5550 	/* check X___Y name pattern, where X and Y are not underscores */
5551 	return s[0] != '_' &&				      /* X */
5552 	       s[1] == '_' && s[2] == '_' && s[3] == '_' &&   /* ___ */
5553 	       s[4] != '_';				      /* Y */
5554 }
5555 
5556 /* Given 'some_struct_name___with_flavor' return the length of a name prefix
5557  * before last triple underscore. Struct name part after last triple
5558  * underscore is ignored by BPF CO-RE relocation during relocation matching.
5559  */
5560 size_t bpf_core_essential_name_len(const char *name)
5561 {
5562 	size_t n = strlen(name);
5563 	int i;
5564 
5565 	for (i = n - 5; i >= 0; i--) {
5566 		if (bpf_core_is_flavor_sep(name + i))
5567 			return i + 1;
5568 	}
5569 	return n;
5570 }
5571 
5572 void bpf_core_free_cands(struct bpf_core_cand_list *cands)
5573 {
5574 	if (!cands)
5575 		return;
5576 
5577 	free(cands->cands);
5578 	free(cands);
5579 }
5580 
5581 int bpf_core_add_cands(struct bpf_core_cand *local_cand,
5582 		       size_t local_essent_len,
5583 		       const struct btf *targ_btf,
5584 		       const char *targ_btf_name,
5585 		       int targ_start_id,
5586 		       struct bpf_core_cand_list *cands)
5587 {
5588 	struct bpf_core_cand *new_cands, *cand;
5589 	const struct btf_type *t, *local_t;
5590 	const char *targ_name, *local_name;
5591 	size_t targ_essent_len;
5592 	int n, i;
5593 
5594 	local_t = btf__type_by_id(local_cand->btf, local_cand->id);
5595 	local_name = btf__str_by_offset(local_cand->btf, local_t->name_off);
5596 
5597 	n = btf__type_cnt(targ_btf);
5598 	for (i = targ_start_id; i < n; i++) {
5599 		t = btf__type_by_id(targ_btf, i);
5600 		if (!btf_kind_core_compat(t, local_t))
5601 			continue;
5602 
5603 		targ_name = btf__name_by_offset(targ_btf, t->name_off);
5604 		if (str_is_empty(targ_name))
5605 			continue;
5606 
5607 		targ_essent_len = bpf_core_essential_name_len(targ_name);
5608 		if (targ_essent_len != local_essent_len)
5609 			continue;
5610 
5611 		if (strncmp(local_name, targ_name, local_essent_len) != 0)
5612 			continue;
5613 
5614 		pr_debug("CO-RE relocating [%d] %s %s: found target candidate [%d] %s %s in [%s]\n",
5615 			 local_cand->id, btf_kind_str(local_t),
5616 			 local_name, i, btf_kind_str(t), targ_name,
5617 			 targ_btf_name);
5618 		new_cands = libbpf_reallocarray(cands->cands, cands->len + 1,
5619 					      sizeof(*cands->cands));
5620 		if (!new_cands)
5621 			return -ENOMEM;
5622 
5623 		cand = &new_cands[cands->len];
5624 		cand->btf = targ_btf;
5625 		cand->id = i;
5626 
5627 		cands->cands = new_cands;
5628 		cands->len++;
5629 	}
5630 	return 0;
5631 }
5632 
5633 static int load_module_btfs(struct bpf_object *obj)
5634 {
5635 	struct bpf_btf_info info;
5636 	struct module_btf *mod_btf;
5637 	struct btf *btf;
5638 	char name[64];
5639 	__u32 id = 0, len;
5640 	int err, fd;
5641 
5642 	if (obj->btf_modules_loaded)
5643 		return 0;
5644 
5645 	if (obj->gen_loader)
5646 		return 0;
5647 
5648 	/* don't do this again, even if we find no module BTFs */
5649 	obj->btf_modules_loaded = true;
5650 
5651 	/* kernel too old to support module BTFs */
5652 	if (!kernel_supports(obj, FEAT_MODULE_BTF))
5653 		return 0;
5654 
5655 	while (true) {
5656 		err = bpf_btf_get_next_id(id, &id);
5657 		if (err && errno == ENOENT)
5658 			return 0;
5659 		if (err && errno == EPERM) {
5660 			pr_debug("skipping module BTFs loading, missing privileges\n");
5661 			return 0;
5662 		}
5663 		if (err) {
5664 			err = -errno;
5665 			pr_warn("failed to iterate BTF objects: %s\n", errstr(err));
5666 			return err;
5667 		}
5668 
5669 		fd = bpf_btf_get_fd_by_id(id);
5670 		if (fd < 0) {
5671 			if (errno == ENOENT)
5672 				continue; /* expected race: BTF was unloaded */
5673 			err = -errno;
5674 			pr_warn("failed to get BTF object #%d FD: %s\n", id, errstr(err));
5675 			return err;
5676 		}
5677 
5678 		len = sizeof(info);
5679 		memset(&info, 0, sizeof(info));
5680 		info.name = ptr_to_u64(name);
5681 		info.name_len = sizeof(name);
5682 
5683 		err = bpf_btf_get_info_by_fd(fd, &info, &len);
5684 		if (err) {
5685 			err = -errno;
5686 			pr_warn("failed to get BTF object #%d info: %s\n", id, errstr(err));
5687 			goto err_out;
5688 		}
5689 
5690 		/* ignore non-module BTFs */
5691 		if (!info.kernel_btf || strcmp(name, "vmlinux") == 0) {
5692 			close(fd);
5693 			continue;
5694 		}
5695 
5696 		btf = btf_get_from_fd(fd, obj->btf_vmlinux);
5697 		err = libbpf_get_error(btf);
5698 		if (err) {
5699 			pr_warn("failed to load module [%s]'s BTF object #%d: %s\n",
5700 				name, id, errstr(err));
5701 			goto err_out;
5702 		}
5703 
5704 		err = libbpf_ensure_mem((void **)&obj->btf_modules, &obj->btf_module_cap,
5705 					sizeof(*obj->btf_modules), obj->btf_module_cnt + 1);
5706 		if (err)
5707 			goto err_out;
5708 
5709 		mod_btf = &obj->btf_modules[obj->btf_module_cnt++];
5710 
5711 		mod_btf->btf = btf;
5712 		mod_btf->id = id;
5713 		mod_btf->fd = fd;
5714 		mod_btf->name = strdup(name);
5715 		if (!mod_btf->name) {
5716 			err = -ENOMEM;
5717 			goto err_out;
5718 		}
5719 		continue;
5720 
5721 err_out:
5722 		close(fd);
5723 		return err;
5724 	}
5725 
5726 	return 0;
5727 }
5728 
5729 static struct bpf_core_cand_list *
5730 bpf_core_find_cands(struct bpf_object *obj, const struct btf *local_btf, __u32 local_type_id)
5731 {
5732 	struct bpf_core_cand local_cand = {};
5733 	struct bpf_core_cand_list *cands;
5734 	const struct btf *main_btf;
5735 	const struct btf_type *local_t;
5736 	const char *local_name;
5737 	size_t local_essent_len;
5738 	int err, i;
5739 
5740 	local_cand.btf = local_btf;
5741 	local_cand.id = local_type_id;
5742 	local_t = btf__type_by_id(local_btf, local_type_id);
5743 	if (!local_t)
5744 		return ERR_PTR(-EINVAL);
5745 
5746 	local_name = btf__name_by_offset(local_btf, local_t->name_off);
5747 	if (str_is_empty(local_name))
5748 		return ERR_PTR(-EINVAL);
5749 	local_essent_len = bpf_core_essential_name_len(local_name);
5750 
5751 	cands = calloc(1, sizeof(*cands));
5752 	if (!cands)
5753 		return ERR_PTR(-ENOMEM);
5754 
5755 	/* Attempt to find target candidates in vmlinux BTF first */
5756 	main_btf = obj->btf_vmlinux_override ?: obj->btf_vmlinux;
5757 	err = bpf_core_add_cands(&local_cand, local_essent_len, main_btf, "vmlinux", 1, cands);
5758 	if (err)
5759 		goto err_out;
5760 
5761 	/* if vmlinux BTF has any candidate, don't got for module BTFs */
5762 	if (cands->len)
5763 		return cands;
5764 
5765 	/* if vmlinux BTF was overridden, don't attempt to load module BTFs */
5766 	if (obj->btf_vmlinux_override)
5767 		return cands;
5768 
5769 	/* now look through module BTFs, trying to still find candidates */
5770 	err = load_module_btfs(obj);
5771 	if (err)
5772 		goto err_out;
5773 
5774 	for (i = 0; i < obj->btf_module_cnt; i++) {
5775 		err = bpf_core_add_cands(&local_cand, local_essent_len,
5776 					 obj->btf_modules[i].btf,
5777 					 obj->btf_modules[i].name,
5778 					 btf__type_cnt(obj->btf_vmlinux),
5779 					 cands);
5780 		if (err)
5781 			goto err_out;
5782 	}
5783 
5784 	return cands;
5785 err_out:
5786 	bpf_core_free_cands(cands);
5787 	return ERR_PTR(err);
5788 }
5789 
5790 /* Check local and target types for compatibility. This check is used for
5791  * type-based CO-RE relocations and follow slightly different rules than
5792  * field-based relocations. This function assumes that root types were already
5793  * checked for name match. Beyond that initial root-level name check, names
5794  * are completely ignored. Compatibility rules are as follows:
5795  *   - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs are considered compatible, but
5796  *     kind should match for local and target types (i.e., STRUCT is not
5797  *     compatible with UNION);
5798  *   - for ENUMs, the size is ignored;
5799  *   - for INT, size and signedness are ignored;
5800  *   - for ARRAY, dimensionality is ignored, element types are checked for
5801  *     compatibility recursively;
5802  *   - CONST/VOLATILE/RESTRICT modifiers are ignored;
5803  *   - TYPEDEFs/PTRs are compatible if types they pointing to are compatible;
5804  *   - FUNC_PROTOs are compatible if they have compatible signature: same
5805  *     number of input args and compatible return and argument types.
5806  * These rules are not set in stone and probably will be adjusted as we get
5807  * more experience with using BPF CO-RE relocations.
5808  */
5809 int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
5810 			      const struct btf *targ_btf, __u32 targ_id)
5811 {
5812 	return __bpf_core_types_are_compat(local_btf, local_id, targ_btf, targ_id, 32);
5813 }
5814 
5815 int bpf_core_types_match(const struct btf *local_btf, __u32 local_id,
5816 			 const struct btf *targ_btf, __u32 targ_id)
5817 {
5818 	return __bpf_core_types_match(local_btf, local_id, targ_btf, targ_id, false, 32);
5819 }
5820 
5821 static size_t bpf_core_hash_fn(const long key, void *ctx)
5822 {
5823 	return key;
5824 }
5825 
5826 static bool bpf_core_equal_fn(const long k1, const long k2, void *ctx)
5827 {
5828 	return k1 == k2;
5829 }
5830 
5831 static int record_relo_core(struct bpf_program *prog,
5832 			    const struct bpf_core_relo *core_relo, int insn_idx)
5833 {
5834 	struct reloc_desc *relos, *relo;
5835 
5836 	relos = libbpf_reallocarray(prog->reloc_desc,
5837 				    prog->nr_reloc + 1, sizeof(*relos));
5838 	if (!relos)
5839 		return -ENOMEM;
5840 	relo = &relos[prog->nr_reloc];
5841 	relo->type = RELO_CORE;
5842 	relo->insn_idx = insn_idx;
5843 	relo->core_relo = core_relo;
5844 	prog->reloc_desc = relos;
5845 	prog->nr_reloc++;
5846 	return 0;
5847 }
5848 
5849 static const struct bpf_core_relo *find_relo_core(struct bpf_program *prog, int insn_idx)
5850 {
5851 	struct reloc_desc *relo;
5852 	int i;
5853 
5854 	for (i = 0; i < prog->nr_reloc; i++) {
5855 		relo = &prog->reloc_desc[i];
5856 		if (relo->type != RELO_CORE || relo->insn_idx != insn_idx)
5857 			continue;
5858 
5859 		return relo->core_relo;
5860 	}
5861 
5862 	return NULL;
5863 }
5864 
5865 static int bpf_core_resolve_relo(struct bpf_program *prog,
5866 				 const struct bpf_core_relo *relo,
5867 				 int relo_idx,
5868 				 const struct btf *local_btf,
5869 				 struct hashmap *cand_cache,
5870 				 struct bpf_core_relo_res *targ_res)
5871 {
5872 	struct bpf_core_spec specs_scratch[3] = {};
5873 	struct bpf_core_cand_list *cands = NULL;
5874 	const char *prog_name = prog->name;
5875 	const struct btf_type *local_type;
5876 	const char *local_name;
5877 	__u32 local_id = relo->type_id;
5878 	int err;
5879 
5880 	local_type = btf__type_by_id(local_btf, local_id);
5881 	if (!local_type)
5882 		return -EINVAL;
5883 
5884 	local_name = btf__name_by_offset(local_btf, local_type->name_off);
5885 	if (!local_name)
5886 		return -EINVAL;
5887 
5888 	if (relo->kind != BPF_CORE_TYPE_ID_LOCAL &&
5889 	    !hashmap__find(cand_cache, local_id, &cands)) {
5890 		cands = bpf_core_find_cands(prog->obj, local_btf, local_id);
5891 		if (IS_ERR(cands)) {
5892 			pr_warn("prog '%s': relo #%d: target candidate search failed for [%d] %s %s: %ld\n",
5893 				prog_name, relo_idx, local_id, btf_kind_str(local_type),
5894 				local_name, PTR_ERR(cands));
5895 			return PTR_ERR(cands);
5896 		}
5897 		err = hashmap__set(cand_cache, local_id, cands, NULL, NULL);
5898 		if (err) {
5899 			bpf_core_free_cands(cands);
5900 			return err;
5901 		}
5902 	}
5903 
5904 	return bpf_core_calc_relo_insn(prog_name, relo, relo_idx, local_btf, cands, specs_scratch,
5905 				       targ_res);
5906 }
5907 
5908 static int
5909 bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
5910 {
5911 	const struct btf_ext_info_sec *sec;
5912 	struct bpf_core_relo_res targ_res;
5913 	const struct bpf_core_relo *rec;
5914 	const struct btf_ext_info *seg;
5915 	struct hashmap_entry *entry;
5916 	struct hashmap *cand_cache = NULL;
5917 	struct bpf_program *prog;
5918 	struct bpf_insn *insn;
5919 	const char *sec_name;
5920 	int i, err = 0, insn_idx, sec_idx, sec_num;
5921 
5922 	if (obj->btf_ext->core_relo_info.len == 0)
5923 		return 0;
5924 
5925 	if (targ_btf_path) {
5926 		obj->btf_vmlinux_override = btf__parse(targ_btf_path, NULL);
5927 		err = libbpf_get_error(obj->btf_vmlinux_override);
5928 		if (err) {
5929 			pr_warn("failed to parse target BTF: %s\n", errstr(err));
5930 			return err;
5931 		}
5932 	}
5933 
5934 	cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
5935 	if (IS_ERR(cand_cache)) {
5936 		err = PTR_ERR(cand_cache);
5937 		goto out;
5938 	}
5939 
5940 	seg = &obj->btf_ext->core_relo_info;
5941 	sec_num = 0;
5942 	for_each_btf_ext_sec(seg, sec) {
5943 		sec_idx = seg->sec_idxs[sec_num];
5944 		sec_num++;
5945 
5946 		sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
5947 		if (str_is_empty(sec_name)) {
5948 			err = -EINVAL;
5949 			goto out;
5950 		}
5951 
5952 		pr_debug("sec '%s': found %d CO-RE relocations\n", sec_name, sec->num_info);
5953 
5954 		for_each_btf_ext_rec(seg, sec, i, rec) {
5955 			if (rec->insn_off % BPF_INSN_SZ)
5956 				return -EINVAL;
5957 			insn_idx = rec->insn_off / BPF_INSN_SZ;
5958 			prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
5959 			if (!prog) {
5960 				/* When __weak subprog is "overridden" by another instance
5961 				 * of the subprog from a different object file, linker still
5962 				 * appends all the .BTF.ext info that used to belong to that
5963 				 * eliminated subprogram.
5964 				 * This is similar to what x86-64 linker does for relocations.
5965 				 * So just ignore such relocations just like we ignore
5966 				 * subprog instructions when discovering subprograms.
5967 				 */
5968 				pr_debug("sec '%s': skipping CO-RE relocation #%d for insn #%d belonging to eliminated weak subprogram\n",
5969 					 sec_name, i, insn_idx);
5970 				continue;
5971 			}
5972 			/* no need to apply CO-RE relocation if the program is
5973 			 * not going to be loaded
5974 			 */
5975 			if (!prog->autoload)
5976 				continue;
5977 
5978 			/* adjust insn_idx from section frame of reference to the local
5979 			 * program's frame of reference; (sub-)program code is not yet
5980 			 * relocated, so it's enough to just subtract in-section offset
5981 			 */
5982 			insn_idx = insn_idx - prog->sec_insn_off;
5983 			if (insn_idx >= prog->insns_cnt)
5984 				return -EINVAL;
5985 			insn = &prog->insns[insn_idx];
5986 
5987 			err = record_relo_core(prog, rec, insn_idx);
5988 			if (err) {
5989 				pr_warn("prog '%s': relo #%d: failed to record relocation: %s\n",
5990 					prog->name, i, errstr(err));
5991 				goto out;
5992 			}
5993 
5994 			if (prog->obj->gen_loader)
5995 				continue;
5996 
5997 			err = bpf_core_resolve_relo(prog, rec, i, obj->btf, cand_cache, &targ_res);
5998 			if (err) {
5999 				pr_warn("prog '%s': relo #%d: failed to relocate: %s\n",
6000 					prog->name, i, errstr(err));
6001 				goto out;
6002 			}
6003 
6004 			err = bpf_core_patch_insn(prog->name, insn, insn_idx, rec, i, &targ_res);
6005 			if (err) {
6006 				pr_warn("prog '%s': relo #%d: failed to patch insn #%u: %s\n",
6007 					prog->name, i, insn_idx, errstr(err));
6008 				goto out;
6009 			}
6010 		}
6011 	}
6012 
6013 out:
6014 	/* obj->btf_vmlinux and module BTFs are freed after object load */
6015 	btf__free(obj->btf_vmlinux_override);
6016 	obj->btf_vmlinux_override = NULL;
6017 
6018 	if (!IS_ERR_OR_NULL(cand_cache)) {
6019 		hashmap__for_each_entry(cand_cache, entry, i) {
6020 			bpf_core_free_cands(entry->pvalue);
6021 		}
6022 		hashmap__free(cand_cache);
6023 	}
6024 	return err;
6025 }
6026 
6027 /* base map load ldimm64 special constant, used also for log fixup logic */
6028 #define POISON_LDIMM64_MAP_BASE 2001000000
6029 #define POISON_LDIMM64_MAP_PFX "200100"
6030 
6031 static void poison_map_ldimm64(struct bpf_program *prog, int relo_idx,
6032 			       int insn_idx, struct bpf_insn *insn,
6033 			       int map_idx, const struct bpf_map *map)
6034 {
6035 	int i;
6036 
6037 	pr_debug("prog '%s': relo #%d: poisoning insn #%d that loads map #%d '%s'\n",
6038 		 prog->name, relo_idx, insn_idx, map_idx, map->name);
6039 
6040 	/* we turn single ldimm64 into two identical invalid calls */
6041 	for (i = 0; i < 2; i++) {
6042 		insn->code = BPF_JMP | BPF_CALL;
6043 		insn->dst_reg = 0;
6044 		insn->src_reg = 0;
6045 		insn->off = 0;
6046 		/* if this instruction is reachable (not a dead code),
6047 		 * verifier will complain with something like:
6048 		 * invalid func unknown#2001000123
6049 		 * where lower 123 is map index into obj->maps[] array
6050 		 */
6051 		insn->imm = POISON_LDIMM64_MAP_BASE + map_idx;
6052 
6053 		insn++;
6054 	}
6055 }
6056 
6057 /* unresolved kfunc call special constant, used also for log fixup logic */
6058 #define POISON_CALL_KFUNC_BASE 2002000000
6059 #define POISON_CALL_KFUNC_PFX "2002"
6060 
6061 static void poison_kfunc_call(struct bpf_program *prog, int relo_idx,
6062 			      int insn_idx, struct bpf_insn *insn,
6063 			      int ext_idx, const struct extern_desc *ext)
6064 {
6065 	pr_debug("prog '%s': relo #%d: poisoning insn #%d that calls kfunc '%s'\n",
6066 		 prog->name, relo_idx, insn_idx, ext->name);
6067 
6068 	/* we turn kfunc call into invalid helper call with identifiable constant */
6069 	insn->code = BPF_JMP | BPF_CALL;
6070 	insn->dst_reg = 0;
6071 	insn->src_reg = 0;
6072 	insn->off = 0;
6073 	/* if this instruction is reachable (not a dead code),
6074 	 * verifier will complain with something like:
6075 	 * invalid func unknown#2001000123
6076 	 * where lower 123 is extern index into obj->externs[] array
6077 	 */
6078 	insn->imm = POISON_CALL_KFUNC_BASE + ext_idx;
6079 }
6080 
6081 /* Relocate data references within program code:
6082  *  - map references;
6083  *  - global variable references;
6084  *  - extern references.
6085  */
6086 static int
6087 bpf_object__relocate_data(struct bpf_object *obj, struct bpf_program *prog)
6088 {
6089 	int i;
6090 
6091 	for (i = 0; i < prog->nr_reloc; i++) {
6092 		struct reloc_desc *relo = &prog->reloc_desc[i];
6093 		struct bpf_insn *insn = &prog->insns[relo->insn_idx];
6094 		const struct bpf_map *map;
6095 		struct extern_desc *ext;
6096 
6097 		switch (relo->type) {
6098 		case RELO_LD64:
6099 			map = &obj->maps[relo->map_idx];
6100 			if (obj->gen_loader) {
6101 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX;
6102 				insn[0].imm = relo->map_idx;
6103 			} else if (map->autocreate) {
6104 				insn[0].src_reg = BPF_PSEUDO_MAP_FD;
6105 				insn[0].imm = map->fd;
6106 			} else {
6107 				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
6108 						   relo->map_idx, map);
6109 			}
6110 			break;
6111 		case RELO_DATA:
6112 			map = &obj->maps[relo->map_idx];
6113 			insn[1].imm = insn[0].imm + relo->sym_off;
6114 			if (obj->gen_loader) {
6115 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
6116 				insn[0].imm = relo->map_idx;
6117 			} else if (map->autocreate) {
6118 				insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6119 				insn[0].imm = map->fd;
6120 			} else {
6121 				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
6122 						   relo->map_idx, map);
6123 			}
6124 			break;
6125 		case RELO_EXTERN_LD64:
6126 			ext = &obj->externs[relo->ext_idx];
6127 			if (ext->type == EXT_KCFG) {
6128 				if (obj->gen_loader) {
6129 					insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
6130 					insn[0].imm = obj->kconfig_map_idx;
6131 				} else {
6132 					insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6133 					insn[0].imm = obj->maps[obj->kconfig_map_idx].fd;
6134 				}
6135 				insn[1].imm = ext->kcfg.data_off;
6136 			} else /* EXT_KSYM */ {
6137 				if (ext->ksym.type_id && ext->is_set) { /* typed ksyms */
6138 					insn[0].src_reg = BPF_PSEUDO_BTF_ID;
6139 					insn[0].imm = ext->ksym.kernel_btf_id;
6140 					insn[1].imm = ext->ksym.kernel_btf_obj_fd;
6141 				} else { /* typeless ksyms or unresolved typed ksyms */
6142 					insn[0].imm = (__u32)ext->ksym.addr;
6143 					insn[1].imm = ext->ksym.addr >> 32;
6144 				}
6145 			}
6146 			break;
6147 		case RELO_EXTERN_CALL:
6148 			ext = &obj->externs[relo->ext_idx];
6149 			insn[0].src_reg = BPF_PSEUDO_KFUNC_CALL;
6150 			if (ext->is_set) {
6151 				insn[0].imm = ext->ksym.kernel_btf_id;
6152 				insn[0].off = ext->ksym.btf_fd_idx;
6153 			} else { /* unresolved weak kfunc call */
6154 				poison_kfunc_call(prog, i, relo->insn_idx, insn,
6155 						  relo->ext_idx, ext);
6156 			}
6157 			break;
6158 		case RELO_SUBPROG_ADDR:
6159 			if (insn[0].src_reg != BPF_PSEUDO_FUNC) {
6160 				pr_warn("prog '%s': relo #%d: bad insn\n",
6161 					prog->name, i);
6162 				return -EINVAL;
6163 			}
6164 			/* handled already */
6165 			break;
6166 		case RELO_CALL:
6167 			/* handled already */
6168 			break;
6169 		case RELO_CORE:
6170 			/* will be handled by bpf_program_record_relos() */
6171 			break;
6172 		default:
6173 			pr_warn("prog '%s': relo #%d: bad relo type %d\n",
6174 				prog->name, i, relo->type);
6175 			return -EINVAL;
6176 		}
6177 	}
6178 
6179 	return 0;
6180 }
6181 
6182 static int adjust_prog_btf_ext_info(const struct bpf_object *obj,
6183 				    const struct bpf_program *prog,
6184 				    const struct btf_ext_info *ext_info,
6185 				    void **prog_info, __u32 *prog_rec_cnt,
6186 				    __u32 *prog_rec_sz)
6187 {
6188 	void *copy_start = NULL, *copy_end = NULL;
6189 	void *rec, *rec_end, *new_prog_info;
6190 	const struct btf_ext_info_sec *sec;
6191 	size_t old_sz, new_sz;
6192 	int i, sec_num, sec_idx, off_adj;
6193 
6194 	sec_num = 0;
6195 	for_each_btf_ext_sec(ext_info, sec) {
6196 		sec_idx = ext_info->sec_idxs[sec_num];
6197 		sec_num++;
6198 		if (prog->sec_idx != sec_idx)
6199 			continue;
6200 
6201 		for_each_btf_ext_rec(ext_info, sec, i, rec) {
6202 			__u32 insn_off = *(__u32 *)rec / BPF_INSN_SZ;
6203 
6204 			if (insn_off < prog->sec_insn_off)
6205 				continue;
6206 			if (insn_off >= prog->sec_insn_off + prog->sec_insn_cnt)
6207 				break;
6208 
6209 			if (!copy_start)
6210 				copy_start = rec;
6211 			copy_end = rec + ext_info->rec_size;
6212 		}
6213 
6214 		if (!copy_start)
6215 			return -ENOENT;
6216 
6217 		/* append func/line info of a given (sub-)program to the main
6218 		 * program func/line info
6219 		 */
6220 		old_sz = (size_t)(*prog_rec_cnt) * ext_info->rec_size;
6221 		new_sz = old_sz + (copy_end - copy_start);
6222 		new_prog_info = realloc(*prog_info, new_sz);
6223 		if (!new_prog_info)
6224 			return -ENOMEM;
6225 		*prog_info = new_prog_info;
6226 		*prog_rec_cnt = new_sz / ext_info->rec_size;
6227 		memcpy(new_prog_info + old_sz, copy_start, copy_end - copy_start);
6228 
6229 		/* Kernel instruction offsets are in units of 8-byte
6230 		 * instructions, while .BTF.ext instruction offsets generated
6231 		 * by Clang are in units of bytes. So convert Clang offsets
6232 		 * into kernel offsets and adjust offset according to program
6233 		 * relocated position.
6234 		 */
6235 		off_adj = prog->sub_insn_off - prog->sec_insn_off;
6236 		rec = new_prog_info + old_sz;
6237 		rec_end = new_prog_info + new_sz;
6238 		for (; rec < rec_end; rec += ext_info->rec_size) {
6239 			__u32 *insn_off = rec;
6240 
6241 			*insn_off = *insn_off / BPF_INSN_SZ + off_adj;
6242 		}
6243 		*prog_rec_sz = ext_info->rec_size;
6244 		return 0;
6245 	}
6246 
6247 	return -ENOENT;
6248 }
6249 
6250 static int
6251 reloc_prog_func_and_line_info(const struct bpf_object *obj,
6252 			      struct bpf_program *main_prog,
6253 			      const struct bpf_program *prog)
6254 {
6255 	int err;
6256 
6257 	/* no .BTF.ext relocation if .BTF.ext is missing or kernel doesn't
6258 	 * support func/line info
6259 	 */
6260 	if (!obj->btf_ext || !kernel_supports(obj, FEAT_BTF_FUNC))
6261 		return 0;
6262 
6263 	/* only attempt func info relocation if main program's func_info
6264 	 * relocation was successful
6265 	 */
6266 	if (main_prog != prog && !main_prog->func_info)
6267 		goto line_info;
6268 
6269 	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->func_info,
6270 				       &main_prog->func_info,
6271 				       &main_prog->func_info_cnt,
6272 				       &main_prog->func_info_rec_size);
6273 	if (err) {
6274 		if (err != -ENOENT) {
6275 			pr_warn("prog '%s': error relocating .BTF.ext function info: %s\n",
6276 				prog->name, errstr(err));
6277 			return err;
6278 		}
6279 		if (main_prog->func_info) {
6280 			/*
6281 			 * Some info has already been found but has problem
6282 			 * in the last btf_ext reloc. Must have to error out.
6283 			 */
6284 			pr_warn("prog '%s': missing .BTF.ext function info.\n", prog->name);
6285 			return err;
6286 		}
6287 		/* Have problem loading the very first info. Ignore the rest. */
6288 		pr_warn("prog '%s': missing .BTF.ext function info for the main program, skipping all of .BTF.ext func info.\n",
6289 			prog->name);
6290 	}
6291 
6292 line_info:
6293 	/* don't relocate line info if main program's relocation failed */
6294 	if (main_prog != prog && !main_prog->line_info)
6295 		return 0;
6296 
6297 	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->line_info,
6298 				       &main_prog->line_info,
6299 				       &main_prog->line_info_cnt,
6300 				       &main_prog->line_info_rec_size);
6301 	if (err) {
6302 		if (err != -ENOENT) {
6303 			pr_warn("prog '%s': error relocating .BTF.ext line info: %s\n",
6304 				prog->name, errstr(err));
6305 			return err;
6306 		}
6307 		if (main_prog->line_info) {
6308 			/*
6309 			 * Some info has already been found but has problem
6310 			 * in the last btf_ext reloc. Must have to error out.
6311 			 */
6312 			pr_warn("prog '%s': missing .BTF.ext line info.\n", prog->name);
6313 			return err;
6314 		}
6315 		/* Have problem loading the very first info. Ignore the rest. */
6316 		pr_warn("prog '%s': missing .BTF.ext line info for the main program, skipping all of .BTF.ext line info.\n",
6317 			prog->name);
6318 	}
6319 	return 0;
6320 }
6321 
6322 static int cmp_relo_by_insn_idx(const void *key, const void *elem)
6323 {
6324 	size_t insn_idx = *(const size_t *)key;
6325 	const struct reloc_desc *relo = elem;
6326 
6327 	if (insn_idx == relo->insn_idx)
6328 		return 0;
6329 	return insn_idx < relo->insn_idx ? -1 : 1;
6330 }
6331 
6332 static struct reloc_desc *find_prog_insn_relo(const struct bpf_program *prog, size_t insn_idx)
6333 {
6334 	if (!prog->nr_reloc)
6335 		return NULL;
6336 	return bsearch(&insn_idx, prog->reloc_desc, prog->nr_reloc,
6337 		       sizeof(*prog->reloc_desc), cmp_relo_by_insn_idx);
6338 }
6339 
6340 static int append_subprog_relos(struct bpf_program *main_prog, struct bpf_program *subprog)
6341 {
6342 	int new_cnt = main_prog->nr_reloc + subprog->nr_reloc;
6343 	struct reloc_desc *relos;
6344 	int i;
6345 
6346 	if (main_prog == subprog)
6347 		return 0;
6348 	relos = libbpf_reallocarray(main_prog->reloc_desc, new_cnt, sizeof(*relos));
6349 	/* if new count is zero, reallocarray can return a valid NULL result;
6350 	 * in this case the previous pointer will be freed, so we *have to*
6351 	 * reassign old pointer to the new value (even if it's NULL)
6352 	 */
6353 	if (!relos && new_cnt)
6354 		return -ENOMEM;
6355 	if (subprog->nr_reloc)
6356 		memcpy(relos + main_prog->nr_reloc, subprog->reloc_desc,
6357 		       sizeof(*relos) * subprog->nr_reloc);
6358 
6359 	for (i = main_prog->nr_reloc; i < new_cnt; i++)
6360 		relos[i].insn_idx += subprog->sub_insn_off;
6361 	/* After insn_idx adjustment the 'relos' array is still sorted
6362 	 * by insn_idx and doesn't break bsearch.
6363 	 */
6364 	main_prog->reloc_desc = relos;
6365 	main_prog->nr_reloc = new_cnt;
6366 	return 0;
6367 }
6368 
6369 static int
6370 bpf_object__append_subprog_code(struct bpf_object *obj, struct bpf_program *main_prog,
6371 				struct bpf_program *subprog)
6372 {
6373        struct bpf_insn *insns;
6374        size_t new_cnt;
6375        int err;
6376 
6377        subprog->sub_insn_off = main_prog->insns_cnt;
6378 
6379        new_cnt = main_prog->insns_cnt + subprog->insns_cnt;
6380        insns = libbpf_reallocarray(main_prog->insns, new_cnt, sizeof(*insns));
6381        if (!insns) {
6382                pr_warn("prog '%s': failed to realloc prog code\n", main_prog->name);
6383                return -ENOMEM;
6384        }
6385        main_prog->insns = insns;
6386        main_prog->insns_cnt = new_cnt;
6387 
6388        memcpy(main_prog->insns + subprog->sub_insn_off, subprog->insns,
6389               subprog->insns_cnt * sizeof(*insns));
6390 
6391        pr_debug("prog '%s': added %zu insns from sub-prog '%s'\n",
6392                 main_prog->name, subprog->insns_cnt, subprog->name);
6393 
6394        /* The subprog insns are now appended. Append its relos too. */
6395        err = append_subprog_relos(main_prog, subprog);
6396        if (err)
6397                return err;
6398        return 0;
6399 }
6400 
6401 static int
6402 bpf_object__reloc_code(struct bpf_object *obj, struct bpf_program *main_prog,
6403 		       struct bpf_program *prog)
6404 {
6405 	size_t sub_insn_idx, insn_idx;
6406 	struct bpf_program *subprog;
6407 	struct reloc_desc *relo;
6408 	struct bpf_insn *insn;
6409 	int err;
6410 
6411 	err = reloc_prog_func_and_line_info(obj, main_prog, prog);
6412 	if (err)
6413 		return err;
6414 
6415 	for (insn_idx = 0; insn_idx < prog->sec_insn_cnt; insn_idx++) {
6416 		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6417 		if (!insn_is_subprog_call(insn) && !insn_is_pseudo_func(insn))
6418 			continue;
6419 
6420 		relo = find_prog_insn_relo(prog, insn_idx);
6421 		if (relo && relo->type == RELO_EXTERN_CALL)
6422 			/* kfunc relocations will be handled later
6423 			 * in bpf_object__relocate_data()
6424 			 */
6425 			continue;
6426 		if (relo && relo->type != RELO_CALL && relo->type != RELO_SUBPROG_ADDR) {
6427 			pr_warn("prog '%s': unexpected relo for insn #%zu, type %d\n",
6428 				prog->name, insn_idx, relo->type);
6429 			return -LIBBPF_ERRNO__RELOC;
6430 		}
6431 		if (relo) {
6432 			/* sub-program instruction index is a combination of
6433 			 * an offset of a symbol pointed to by relocation and
6434 			 * call instruction's imm field; for global functions,
6435 			 * call always has imm = -1, but for static functions
6436 			 * relocation is against STT_SECTION and insn->imm
6437 			 * points to a start of a static function
6438 			 *
6439 			 * for subprog addr relocation, the relo->sym_off + insn->imm is
6440 			 * the byte offset in the corresponding section.
6441 			 */
6442 			if (relo->type == RELO_CALL)
6443 				sub_insn_idx = relo->sym_off / BPF_INSN_SZ + insn->imm + 1;
6444 			else
6445 				sub_insn_idx = (relo->sym_off + insn->imm) / BPF_INSN_SZ;
6446 		} else if (insn_is_pseudo_func(insn)) {
6447 			/*
6448 			 * RELO_SUBPROG_ADDR relo is always emitted even if both
6449 			 * functions are in the same section, so it shouldn't reach here.
6450 			 */
6451 			pr_warn("prog '%s': missing subprog addr relo for insn #%zu\n",
6452 				prog->name, insn_idx);
6453 			return -LIBBPF_ERRNO__RELOC;
6454 		} else {
6455 			/* if subprogram call is to a static function within
6456 			 * the same ELF section, there won't be any relocation
6457 			 * emitted, but it also means there is no additional
6458 			 * offset necessary, insns->imm is relative to
6459 			 * instruction's original position within the section
6460 			 */
6461 			sub_insn_idx = prog->sec_insn_off + insn_idx + insn->imm + 1;
6462 		}
6463 
6464 		/* we enforce that sub-programs should be in .text section */
6465 		subprog = find_prog_by_sec_insn(obj, obj->efile.text_shndx, sub_insn_idx);
6466 		if (!subprog) {
6467 			pr_warn("prog '%s': no .text section found yet sub-program call exists\n",
6468 				prog->name);
6469 			return -LIBBPF_ERRNO__RELOC;
6470 		}
6471 
6472 		/* if it's the first call instruction calling into this
6473 		 * subprogram (meaning this subprog hasn't been processed
6474 		 * yet) within the context of current main program:
6475 		 *   - append it at the end of main program's instructions blog;
6476 		 *   - process is recursively, while current program is put on hold;
6477 		 *   - if that subprogram calls some other not yet processes
6478 		 *   subprogram, same thing will happen recursively until
6479 		 *   there are no more unprocesses subprograms left to append
6480 		 *   and relocate.
6481 		 */
6482 		if (subprog->sub_insn_off == 0) {
6483 			err = bpf_object__append_subprog_code(obj, main_prog, subprog);
6484 			if (err)
6485 				return err;
6486 			err = bpf_object__reloc_code(obj, main_prog, subprog);
6487 			if (err)
6488 				return err;
6489 		}
6490 
6491 		/* main_prog->insns memory could have been re-allocated, so
6492 		 * calculate pointer again
6493 		 */
6494 		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6495 		/* calculate correct instruction position within current main
6496 		 * prog; each main prog can have a different set of
6497 		 * subprograms appended (potentially in different order as
6498 		 * well), so position of any subprog can be different for
6499 		 * different main programs
6500 		 */
6501 		insn->imm = subprog->sub_insn_off - (prog->sub_insn_off + insn_idx) - 1;
6502 
6503 		pr_debug("prog '%s': insn #%zu relocated, imm %d points to subprog '%s' (now at %zu offset)\n",
6504 			 prog->name, insn_idx, insn->imm, subprog->name, subprog->sub_insn_off);
6505 	}
6506 
6507 	return 0;
6508 }
6509 
6510 /*
6511  * Relocate sub-program calls.
6512  *
6513  * Algorithm operates as follows. Each entry-point BPF program (referred to as
6514  * main prog) is processed separately. For each subprog (non-entry functions,
6515  * that can be called from either entry progs or other subprogs) gets their
6516  * sub_insn_off reset to zero. This serves as indicator that this subprogram
6517  * hasn't been yet appended and relocated within current main prog. Once its
6518  * relocated, sub_insn_off will point at the position within current main prog
6519  * where given subprog was appended. This will further be used to relocate all
6520  * the call instructions jumping into this subprog.
6521  *
6522  * We start with main program and process all call instructions. If the call
6523  * is into a subprog that hasn't been processed (i.e., subprog->sub_insn_off
6524  * is zero), subprog instructions are appended at the end of main program's
6525  * instruction array. Then main program is "put on hold" while we recursively
6526  * process newly appended subprogram. If that subprogram calls into another
6527  * subprogram that hasn't been appended, new subprogram is appended again to
6528  * the *main* prog's instructions (subprog's instructions are always left
6529  * untouched, as they need to be in unmodified state for subsequent main progs
6530  * and subprog instructions are always sent only as part of a main prog) and
6531  * the process continues recursively. Once all the subprogs called from a main
6532  * prog or any of its subprogs are appended (and relocated), all their
6533  * positions within finalized instructions array are known, so it's easy to
6534  * rewrite call instructions with correct relative offsets, corresponding to
6535  * desired target subprog.
6536  *
6537  * Its important to realize that some subprogs might not be called from some
6538  * main prog and any of its called/used subprogs. Those will keep their
6539  * subprog->sub_insn_off as zero at all times and won't be appended to current
6540  * main prog and won't be relocated within the context of current main prog.
6541  * They might still be used from other main progs later.
6542  *
6543  * Visually this process can be shown as below. Suppose we have two main
6544  * programs mainA and mainB and BPF object contains three subprogs: subA,
6545  * subB, and subC. mainA calls only subA, mainB calls only subC, but subA and
6546  * subC both call subB:
6547  *
6548  *        +--------+ +-------+
6549  *        |        v v       |
6550  *     +--+---+ +--+-+-+ +---+--+
6551  *     | subA | | subB | | subC |
6552  *     +--+---+ +------+ +---+--+
6553  *        ^                  ^
6554  *        |                  |
6555  *    +---+-------+   +------+----+
6556  *    |   mainA   |   |   mainB   |
6557  *    +-----------+   +-----------+
6558  *
6559  * We'll start relocating mainA, will find subA, append it and start
6560  * processing sub A recursively:
6561  *
6562  *    +-----------+------+
6563  *    |   mainA   | subA |
6564  *    +-----------+------+
6565  *
6566  * At this point we notice that subB is used from subA, so we append it and
6567  * relocate (there are no further subcalls from subB):
6568  *
6569  *    +-----------+------+------+
6570  *    |   mainA   | subA | subB |
6571  *    +-----------+------+------+
6572  *
6573  * At this point, we relocate subA calls, then go one level up and finish with
6574  * relocatin mainA calls. mainA is done.
6575  *
6576  * For mainB process is similar but results in different order. We start with
6577  * mainB and skip subA and subB, as mainB never calls them (at least
6578  * directly), but we see subC is needed, so we append and start processing it:
6579  *
6580  *    +-----------+------+
6581  *    |   mainB   | subC |
6582  *    +-----------+------+
6583  * Now we see subC needs subB, so we go back to it, append and relocate it:
6584  *
6585  *    +-----------+------+------+
6586  *    |   mainB   | subC | subB |
6587  *    +-----------+------+------+
6588  *
6589  * At this point we unwind recursion, relocate calls in subC, then in mainB.
6590  */
6591 static int
6592 bpf_object__relocate_calls(struct bpf_object *obj, struct bpf_program *prog)
6593 {
6594 	struct bpf_program *subprog;
6595 	int i, err;
6596 
6597 	/* mark all subprogs as not relocated (yet) within the context of
6598 	 * current main program
6599 	 */
6600 	for (i = 0; i < obj->nr_programs; i++) {
6601 		subprog = &obj->programs[i];
6602 		if (!prog_is_subprog(obj, subprog))
6603 			continue;
6604 
6605 		subprog->sub_insn_off = 0;
6606 	}
6607 
6608 	err = bpf_object__reloc_code(obj, prog, prog);
6609 	if (err)
6610 		return err;
6611 
6612 	return 0;
6613 }
6614 
6615 static void
6616 bpf_object__free_relocs(struct bpf_object *obj)
6617 {
6618 	struct bpf_program *prog;
6619 	int i;
6620 
6621 	/* free up relocation descriptors */
6622 	for (i = 0; i < obj->nr_programs; i++) {
6623 		prog = &obj->programs[i];
6624 		zfree(&prog->reloc_desc);
6625 		prog->nr_reloc = 0;
6626 	}
6627 }
6628 
6629 static int cmp_relocs(const void *_a, const void *_b)
6630 {
6631 	const struct reloc_desc *a = _a;
6632 	const struct reloc_desc *b = _b;
6633 
6634 	if (a->insn_idx != b->insn_idx)
6635 		return a->insn_idx < b->insn_idx ? -1 : 1;
6636 
6637 	/* no two relocations should have the same insn_idx, but ... */
6638 	if (a->type != b->type)
6639 		return a->type < b->type ? -1 : 1;
6640 
6641 	return 0;
6642 }
6643 
6644 static void bpf_object__sort_relos(struct bpf_object *obj)
6645 {
6646 	int i;
6647 
6648 	for (i = 0; i < obj->nr_programs; i++) {
6649 		struct bpf_program *p = &obj->programs[i];
6650 
6651 		if (!p->nr_reloc)
6652 			continue;
6653 
6654 		qsort(p->reloc_desc, p->nr_reloc, sizeof(*p->reloc_desc), cmp_relocs);
6655 	}
6656 }
6657 
6658 static int bpf_prog_assign_exc_cb(struct bpf_object *obj, struct bpf_program *prog)
6659 {
6660 	const char *str = "exception_callback:";
6661 	size_t pfx_len = strlen(str);
6662 	int i, j, n;
6663 
6664 	if (!obj->btf || !kernel_supports(obj, FEAT_BTF_DECL_TAG))
6665 		return 0;
6666 
6667 	n = btf__type_cnt(obj->btf);
6668 	for (i = 1; i < n; i++) {
6669 		const char *name;
6670 		struct btf_type *t;
6671 
6672 		t = btf_type_by_id(obj->btf, i);
6673 		if (!btf_is_decl_tag(t) || btf_decl_tag(t)->component_idx != -1)
6674 			continue;
6675 
6676 		name = btf__str_by_offset(obj->btf, t->name_off);
6677 		if (strncmp(name, str, pfx_len) != 0)
6678 			continue;
6679 
6680 		t = btf_type_by_id(obj->btf, t->type);
6681 		if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL) {
6682 			pr_warn("prog '%s': exception_callback:<value> decl tag not applied to the main program\n",
6683 				prog->name);
6684 			return -EINVAL;
6685 		}
6686 		if (strcmp(prog->name, btf__str_by_offset(obj->btf, t->name_off)) != 0)
6687 			continue;
6688 		/* Multiple callbacks are specified for the same prog,
6689 		 * the verifier will eventually return an error for this
6690 		 * case, hence simply skip appending a subprog.
6691 		 */
6692 		if (prog->exception_cb_idx >= 0) {
6693 			prog->exception_cb_idx = -1;
6694 			break;
6695 		}
6696 
6697 		name += pfx_len;
6698 		if (str_is_empty(name)) {
6699 			pr_warn("prog '%s': exception_callback:<value> decl tag contains empty value\n",
6700 				prog->name);
6701 			return -EINVAL;
6702 		}
6703 
6704 		for (j = 0; j < obj->nr_programs; j++) {
6705 			struct bpf_program *subprog = &obj->programs[j];
6706 
6707 			if (!prog_is_subprog(obj, subprog))
6708 				continue;
6709 			if (strcmp(name, subprog->name) != 0)
6710 				continue;
6711 			/* Enforce non-hidden, as from verifier point of
6712 			 * view it expects global functions, whereas the
6713 			 * mark_btf_static fixes up linkage as static.
6714 			 */
6715 			if (!subprog->sym_global || subprog->mark_btf_static) {
6716 				pr_warn("prog '%s': exception callback %s must be a global non-hidden function\n",
6717 					prog->name, subprog->name);
6718 				return -EINVAL;
6719 			}
6720 			/* Let's see if we already saw a static exception callback with the same name */
6721 			if (prog->exception_cb_idx >= 0) {
6722 				pr_warn("prog '%s': multiple subprogs with same name as exception callback '%s'\n",
6723 					prog->name, subprog->name);
6724 				return -EINVAL;
6725 			}
6726 			prog->exception_cb_idx = j;
6727 			break;
6728 		}
6729 
6730 		if (prog->exception_cb_idx >= 0)
6731 			continue;
6732 
6733 		pr_warn("prog '%s': cannot find exception callback '%s'\n", prog->name, name);
6734 		return -ENOENT;
6735 	}
6736 
6737 	return 0;
6738 }
6739 
6740 static struct {
6741 	enum bpf_prog_type prog_type;
6742 	const char *ctx_name;
6743 } global_ctx_map[] = {
6744 	{ BPF_PROG_TYPE_CGROUP_DEVICE,           "bpf_cgroup_dev_ctx" },
6745 	{ BPF_PROG_TYPE_CGROUP_SKB,              "__sk_buff" },
6746 	{ BPF_PROG_TYPE_CGROUP_SOCK,             "bpf_sock" },
6747 	{ BPF_PROG_TYPE_CGROUP_SOCK_ADDR,        "bpf_sock_addr" },
6748 	{ BPF_PROG_TYPE_CGROUP_SOCKOPT,          "bpf_sockopt" },
6749 	{ BPF_PROG_TYPE_CGROUP_SYSCTL,           "bpf_sysctl" },
6750 	{ BPF_PROG_TYPE_FLOW_DISSECTOR,          "__sk_buff" },
6751 	{ BPF_PROG_TYPE_KPROBE,                  "bpf_user_pt_regs_t" },
6752 	{ BPF_PROG_TYPE_LWT_IN,                  "__sk_buff" },
6753 	{ BPF_PROG_TYPE_LWT_OUT,                 "__sk_buff" },
6754 	{ BPF_PROG_TYPE_LWT_SEG6LOCAL,           "__sk_buff" },
6755 	{ BPF_PROG_TYPE_LWT_XMIT,                "__sk_buff" },
6756 	{ BPF_PROG_TYPE_NETFILTER,               "bpf_nf_ctx" },
6757 	{ BPF_PROG_TYPE_PERF_EVENT,              "bpf_perf_event_data" },
6758 	{ BPF_PROG_TYPE_RAW_TRACEPOINT,          "bpf_raw_tracepoint_args" },
6759 	{ BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE, "bpf_raw_tracepoint_args" },
6760 	{ BPF_PROG_TYPE_SCHED_ACT,               "__sk_buff" },
6761 	{ BPF_PROG_TYPE_SCHED_CLS,               "__sk_buff" },
6762 	{ BPF_PROG_TYPE_SK_LOOKUP,               "bpf_sk_lookup" },
6763 	{ BPF_PROG_TYPE_SK_MSG,                  "sk_msg_md" },
6764 	{ BPF_PROG_TYPE_SK_REUSEPORT,            "sk_reuseport_md" },
6765 	{ BPF_PROG_TYPE_SK_SKB,                  "__sk_buff" },
6766 	{ BPF_PROG_TYPE_SOCK_OPS,                "bpf_sock_ops" },
6767 	{ BPF_PROG_TYPE_SOCKET_FILTER,           "__sk_buff" },
6768 	{ BPF_PROG_TYPE_XDP,                     "xdp_md" },
6769 	/* all other program types don't have "named" context structs */
6770 };
6771 
6772 /* forward declarations for arch-specific underlying types of bpf_user_pt_regs_t typedef,
6773  * for below __builtin_types_compatible_p() checks;
6774  * with this approach we don't need any extra arch-specific #ifdef guards
6775  */
6776 struct pt_regs;
6777 struct user_pt_regs;
6778 struct user_regs_struct;
6779 
6780 static bool need_func_arg_type_fixup(const struct btf *btf, const struct bpf_program *prog,
6781 				     const char *subprog_name, int arg_idx,
6782 				     int arg_type_id, const char *ctx_name)
6783 {
6784 	const struct btf_type *t;
6785 	const char *tname;
6786 
6787 	/* check if existing parameter already matches verifier expectations */
6788 	t = skip_mods_and_typedefs(btf, arg_type_id, NULL);
6789 	if (!btf_is_ptr(t))
6790 		goto out_warn;
6791 
6792 	/* typedef bpf_user_pt_regs_t is a special PITA case, valid for kprobe
6793 	 * and perf_event programs, so check this case early on and forget
6794 	 * about it for subsequent checks
6795 	 */
6796 	while (btf_is_mod(t))
6797 		t = btf__type_by_id(btf, t->type);
6798 	if (btf_is_typedef(t) &&
6799 	    (prog->type == BPF_PROG_TYPE_KPROBE || prog->type == BPF_PROG_TYPE_PERF_EVENT)) {
6800 		tname = btf__str_by_offset(btf, t->name_off) ?: "<anon>";
6801 		if (strcmp(tname, "bpf_user_pt_regs_t") == 0)
6802 			return false; /* canonical type for kprobe/perf_event */
6803 	}
6804 
6805 	/* now we can ignore typedefs moving forward */
6806 	t = skip_mods_and_typedefs(btf, t->type, NULL);
6807 
6808 	/* if it's `void *`, definitely fix up BTF info */
6809 	if (btf_is_void(t))
6810 		return true;
6811 
6812 	/* if it's already proper canonical type, no need to fix up */
6813 	tname = btf__str_by_offset(btf, t->name_off) ?: "<anon>";
6814 	if (btf_is_struct(t) && strcmp(tname, ctx_name) == 0)
6815 		return false;
6816 
6817 	/* special cases */
6818 	switch (prog->type) {
6819 	case BPF_PROG_TYPE_KPROBE:
6820 		/* `struct pt_regs *` is expected, but we need to fix up */
6821 		if (btf_is_struct(t) && strcmp(tname, "pt_regs") == 0)
6822 			return true;
6823 		break;
6824 	case BPF_PROG_TYPE_PERF_EVENT:
6825 		if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct pt_regs) &&
6826 		    btf_is_struct(t) && strcmp(tname, "pt_regs") == 0)
6827 			return true;
6828 		if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct user_pt_regs) &&
6829 		    btf_is_struct(t) && strcmp(tname, "user_pt_regs") == 0)
6830 			return true;
6831 		if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct user_regs_struct) &&
6832 		    btf_is_struct(t) && strcmp(tname, "user_regs_struct") == 0)
6833 			return true;
6834 		break;
6835 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
6836 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
6837 		/* allow u64* as ctx */
6838 		if (btf_is_int(t) && t->size == 8)
6839 			return true;
6840 		break;
6841 	default:
6842 		break;
6843 	}
6844 
6845 out_warn:
6846 	pr_warn("prog '%s': subprog '%s' arg#%d is expected to be of `struct %s *` type\n",
6847 		prog->name, subprog_name, arg_idx, ctx_name);
6848 	return false;
6849 }
6850 
6851 static int clone_func_btf_info(struct btf *btf, int orig_fn_id, struct bpf_program *prog)
6852 {
6853 	int fn_id, fn_proto_id, ret_type_id, orig_proto_id;
6854 	int i, err, arg_cnt, fn_name_off, linkage;
6855 	struct btf_type *fn_t, *fn_proto_t, *t;
6856 	struct btf_param *p;
6857 
6858 	/* caller already validated FUNC -> FUNC_PROTO validity */
6859 	fn_t = btf_type_by_id(btf, orig_fn_id);
6860 	fn_proto_t = btf_type_by_id(btf, fn_t->type);
6861 
6862 	/* Note that each btf__add_xxx() operation invalidates
6863 	 * all btf_type and string pointers, so we need to be
6864 	 * very careful when cloning BTF types. BTF type
6865 	 * pointers have to be always refetched. And to avoid
6866 	 * problems with invalidated string pointers, we
6867 	 * add empty strings initially, then just fix up
6868 	 * name_off offsets in place. Offsets are stable for
6869 	 * existing strings, so that works out.
6870 	 */
6871 	fn_name_off = fn_t->name_off; /* we are about to invalidate fn_t */
6872 	linkage = btf_func_linkage(fn_t);
6873 	orig_proto_id = fn_t->type; /* original FUNC_PROTO ID */
6874 	ret_type_id = fn_proto_t->type; /* fn_proto_t will be invalidated */
6875 	arg_cnt = btf_vlen(fn_proto_t);
6876 
6877 	/* clone FUNC_PROTO and its params */
6878 	fn_proto_id = btf__add_func_proto(btf, ret_type_id);
6879 	if (fn_proto_id < 0)
6880 		return -EINVAL;
6881 
6882 	for (i = 0; i < arg_cnt; i++) {
6883 		int name_off;
6884 
6885 		/* copy original parameter data */
6886 		t = btf_type_by_id(btf, orig_proto_id);
6887 		p = &btf_params(t)[i];
6888 		name_off = p->name_off;
6889 
6890 		err = btf__add_func_param(btf, "", p->type);
6891 		if (err)
6892 			return err;
6893 
6894 		fn_proto_t = btf_type_by_id(btf, fn_proto_id);
6895 		p = &btf_params(fn_proto_t)[i];
6896 		p->name_off = name_off; /* use remembered str offset */
6897 	}
6898 
6899 	/* clone FUNC now, btf__add_func() enforces non-empty name, so use
6900 	 * entry program's name as a placeholder, which we replace immediately
6901 	 * with original name_off
6902 	 */
6903 	fn_id = btf__add_func(btf, prog->name, linkage, fn_proto_id);
6904 	if (fn_id < 0)
6905 		return -EINVAL;
6906 
6907 	fn_t = btf_type_by_id(btf, fn_id);
6908 	fn_t->name_off = fn_name_off; /* reuse original string */
6909 
6910 	return fn_id;
6911 }
6912 
6913 /* Check if main program or global subprog's function prototype has `arg:ctx`
6914  * argument tags, and, if necessary, substitute correct type to match what BPF
6915  * verifier would expect, taking into account specific program type. This
6916  * allows to support __arg_ctx tag transparently on old kernels that don't yet
6917  * have a native support for it in the verifier, making user's life much
6918  * easier.
6919  */
6920 static int bpf_program_fixup_func_info(struct bpf_object *obj, struct bpf_program *prog)
6921 {
6922 	const char *ctx_name = NULL, *ctx_tag = "arg:ctx", *fn_name;
6923 	struct bpf_func_info_min *func_rec;
6924 	struct btf_type *fn_t, *fn_proto_t;
6925 	struct btf *btf = obj->btf;
6926 	const struct btf_type *t;
6927 	struct btf_param *p;
6928 	int ptr_id = 0, struct_id, tag_id, orig_fn_id;
6929 	int i, n, arg_idx, arg_cnt, err, rec_idx;
6930 	int *orig_ids;
6931 
6932 	/* no .BTF.ext, no problem */
6933 	if (!obj->btf_ext || !prog->func_info)
6934 		return 0;
6935 
6936 	/* don't do any fix ups if kernel natively supports __arg_ctx */
6937 	if (kernel_supports(obj, FEAT_ARG_CTX_TAG))
6938 		return 0;
6939 
6940 	/* some BPF program types just don't have named context structs, so
6941 	 * this fallback mechanism doesn't work for them
6942 	 */
6943 	for (i = 0; i < ARRAY_SIZE(global_ctx_map); i++) {
6944 		if (global_ctx_map[i].prog_type != prog->type)
6945 			continue;
6946 		ctx_name = global_ctx_map[i].ctx_name;
6947 		break;
6948 	}
6949 	if (!ctx_name)
6950 		return 0;
6951 
6952 	/* remember original func BTF IDs to detect if we already cloned them */
6953 	orig_ids = calloc(prog->func_info_cnt, sizeof(*orig_ids));
6954 	if (!orig_ids)
6955 		return -ENOMEM;
6956 	for (i = 0; i < prog->func_info_cnt; i++) {
6957 		func_rec = prog->func_info + prog->func_info_rec_size * i;
6958 		orig_ids[i] = func_rec->type_id;
6959 	}
6960 
6961 	/* go through each DECL_TAG with "arg:ctx" and see if it points to one
6962 	 * of our subprogs; if yes and subprog is global and needs adjustment,
6963 	 * clone and adjust FUNC -> FUNC_PROTO combo
6964 	 */
6965 	for (i = 1, n = btf__type_cnt(btf); i < n; i++) {
6966 		/* only DECL_TAG with "arg:ctx" value are interesting */
6967 		t = btf__type_by_id(btf, i);
6968 		if (!btf_is_decl_tag(t))
6969 			continue;
6970 		if (strcmp(btf__str_by_offset(btf, t->name_off), ctx_tag) != 0)
6971 			continue;
6972 
6973 		/* only global funcs need adjustment, if at all */
6974 		orig_fn_id = t->type;
6975 		fn_t = btf_type_by_id(btf, orig_fn_id);
6976 		if (!btf_is_func(fn_t) || btf_func_linkage(fn_t) != BTF_FUNC_GLOBAL)
6977 			continue;
6978 
6979 		/* sanity check FUNC -> FUNC_PROTO chain, just in case */
6980 		fn_proto_t = btf_type_by_id(btf, fn_t->type);
6981 		if (!fn_proto_t || !btf_is_func_proto(fn_proto_t))
6982 			continue;
6983 
6984 		/* find corresponding func_info record */
6985 		func_rec = NULL;
6986 		for (rec_idx = 0; rec_idx < prog->func_info_cnt; rec_idx++) {
6987 			if (orig_ids[rec_idx] == t->type) {
6988 				func_rec = prog->func_info + prog->func_info_rec_size * rec_idx;
6989 				break;
6990 			}
6991 		}
6992 		/* current main program doesn't call into this subprog */
6993 		if (!func_rec)
6994 			continue;
6995 
6996 		/* some more sanity checking of DECL_TAG */
6997 		arg_cnt = btf_vlen(fn_proto_t);
6998 		arg_idx = btf_decl_tag(t)->component_idx;
6999 		if (arg_idx < 0 || arg_idx >= arg_cnt)
7000 			continue;
7001 
7002 		/* check if we should fix up argument type */
7003 		p = &btf_params(fn_proto_t)[arg_idx];
7004 		fn_name = btf__str_by_offset(btf, fn_t->name_off) ?: "<anon>";
7005 		if (!need_func_arg_type_fixup(btf, prog, fn_name, arg_idx, p->type, ctx_name))
7006 			continue;
7007 
7008 		/* clone fn/fn_proto, unless we already did it for another arg */
7009 		if (func_rec->type_id == orig_fn_id) {
7010 			int fn_id;
7011 
7012 			fn_id = clone_func_btf_info(btf, orig_fn_id, prog);
7013 			if (fn_id < 0) {
7014 				err = fn_id;
7015 				goto err_out;
7016 			}
7017 
7018 			/* point func_info record to a cloned FUNC type */
7019 			func_rec->type_id = fn_id;
7020 		}
7021 
7022 		/* create PTR -> STRUCT type chain to mark PTR_TO_CTX argument;
7023 		 * we do it just once per main BPF program, as all global
7024 		 * funcs share the same program type, so need only PTR ->
7025 		 * STRUCT type chain
7026 		 */
7027 		if (ptr_id == 0) {
7028 			struct_id = btf__add_struct(btf, ctx_name, 0);
7029 			ptr_id = btf__add_ptr(btf, struct_id);
7030 			if (ptr_id < 0 || struct_id < 0) {
7031 				err = -EINVAL;
7032 				goto err_out;
7033 			}
7034 		}
7035 
7036 		/* for completeness, clone DECL_TAG and point it to cloned param */
7037 		tag_id = btf__add_decl_tag(btf, ctx_tag, func_rec->type_id, arg_idx);
7038 		if (tag_id < 0) {
7039 			err = -EINVAL;
7040 			goto err_out;
7041 		}
7042 
7043 		/* all the BTF manipulations invalidated pointers, refetch them */
7044 		fn_t = btf_type_by_id(btf, func_rec->type_id);
7045 		fn_proto_t = btf_type_by_id(btf, fn_t->type);
7046 
7047 		/* fix up type ID pointed to by param */
7048 		p = &btf_params(fn_proto_t)[arg_idx];
7049 		p->type = ptr_id;
7050 	}
7051 
7052 	free(orig_ids);
7053 	return 0;
7054 err_out:
7055 	free(orig_ids);
7056 	return err;
7057 }
7058 
7059 static int bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
7060 {
7061 	struct bpf_program *prog;
7062 	size_t i, j;
7063 	int err;
7064 
7065 	if (obj->btf_ext) {
7066 		err = bpf_object__relocate_core(obj, targ_btf_path);
7067 		if (err) {
7068 			pr_warn("failed to perform CO-RE relocations: %s\n",
7069 				errstr(err));
7070 			return err;
7071 		}
7072 		bpf_object__sort_relos(obj);
7073 	}
7074 
7075 	/* Before relocating calls pre-process relocations and mark
7076 	 * few ld_imm64 instructions that points to subprogs.
7077 	 * Otherwise bpf_object__reloc_code() later would have to consider
7078 	 * all ld_imm64 insns as relocation candidates. That would
7079 	 * reduce relocation speed, since amount of find_prog_insn_relo()
7080 	 * would increase and most of them will fail to find a relo.
7081 	 */
7082 	for (i = 0; i < obj->nr_programs; i++) {
7083 		prog = &obj->programs[i];
7084 		for (j = 0; j < prog->nr_reloc; j++) {
7085 			struct reloc_desc *relo = &prog->reloc_desc[j];
7086 			struct bpf_insn *insn = &prog->insns[relo->insn_idx];
7087 
7088 			/* mark the insn, so it's recognized by insn_is_pseudo_func() */
7089 			if (relo->type == RELO_SUBPROG_ADDR)
7090 				insn[0].src_reg = BPF_PSEUDO_FUNC;
7091 		}
7092 	}
7093 
7094 	/* relocate subprogram calls and append used subprograms to main
7095 	 * programs; each copy of subprogram code needs to be relocated
7096 	 * differently for each main program, because its code location might
7097 	 * have changed.
7098 	 * Append subprog relos to main programs to allow data relos to be
7099 	 * processed after text is completely relocated.
7100 	 */
7101 	for (i = 0; i < obj->nr_programs; i++) {
7102 		prog = &obj->programs[i];
7103 		/* sub-program's sub-calls are relocated within the context of
7104 		 * its main program only
7105 		 */
7106 		if (prog_is_subprog(obj, prog))
7107 			continue;
7108 		if (!prog->autoload)
7109 			continue;
7110 
7111 		err = bpf_object__relocate_calls(obj, prog);
7112 		if (err) {
7113 			pr_warn("prog '%s': failed to relocate calls: %s\n",
7114 				prog->name, errstr(err));
7115 			return err;
7116 		}
7117 
7118 		err = bpf_prog_assign_exc_cb(obj, prog);
7119 		if (err)
7120 			return err;
7121 		/* Now, also append exception callback if it has not been done already. */
7122 		if (prog->exception_cb_idx >= 0) {
7123 			struct bpf_program *subprog = &obj->programs[prog->exception_cb_idx];
7124 
7125 			/* Calling exception callback directly is disallowed, which the
7126 			 * verifier will reject later. In case it was processed already,
7127 			 * we can skip this step, otherwise for all other valid cases we
7128 			 * have to append exception callback now.
7129 			 */
7130 			if (subprog->sub_insn_off == 0) {
7131 				err = bpf_object__append_subprog_code(obj, prog, subprog);
7132 				if (err)
7133 					return err;
7134 				err = bpf_object__reloc_code(obj, prog, subprog);
7135 				if (err)
7136 					return err;
7137 			}
7138 		}
7139 	}
7140 	for (i = 0; i < obj->nr_programs; i++) {
7141 		prog = &obj->programs[i];
7142 		if (prog_is_subprog(obj, prog))
7143 			continue;
7144 		if (!prog->autoload)
7145 			continue;
7146 
7147 		/* Process data relos for main programs */
7148 		err = bpf_object__relocate_data(obj, prog);
7149 		if (err) {
7150 			pr_warn("prog '%s': failed to relocate data references: %s\n",
7151 				prog->name, errstr(err));
7152 			return err;
7153 		}
7154 
7155 		/* Fix up .BTF.ext information, if necessary */
7156 		err = bpf_program_fixup_func_info(obj, prog);
7157 		if (err) {
7158 			pr_warn("prog '%s': failed to perform .BTF.ext fix ups: %s\n",
7159 				prog->name, errstr(err));
7160 			return err;
7161 		}
7162 	}
7163 
7164 	return 0;
7165 }
7166 
7167 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
7168 					    Elf64_Shdr *shdr, Elf_Data *data);
7169 
7170 static int bpf_object__collect_map_relos(struct bpf_object *obj,
7171 					 Elf64_Shdr *shdr, Elf_Data *data)
7172 {
7173 	const int bpf_ptr_sz = 8, host_ptr_sz = sizeof(void *);
7174 	int i, j, nrels, new_sz;
7175 	const struct btf_var_secinfo *vi = NULL;
7176 	const struct btf_type *sec, *var, *def;
7177 	struct bpf_map *map = NULL, *targ_map = NULL;
7178 	struct bpf_program *targ_prog = NULL;
7179 	bool is_prog_array, is_map_in_map;
7180 	const struct btf_member *member;
7181 	const char *name, *mname, *type;
7182 	unsigned int moff;
7183 	Elf64_Sym *sym;
7184 	Elf64_Rel *rel;
7185 	void *tmp;
7186 
7187 	if (!obj->efile.btf_maps_sec_btf_id || !obj->btf)
7188 		return -EINVAL;
7189 	sec = btf__type_by_id(obj->btf, obj->efile.btf_maps_sec_btf_id);
7190 	if (!sec)
7191 		return -EINVAL;
7192 
7193 	nrels = shdr->sh_size / shdr->sh_entsize;
7194 	for (i = 0; i < nrels; i++) {
7195 		rel = elf_rel_by_idx(data, i);
7196 		if (!rel) {
7197 			pr_warn(".maps relo #%d: failed to get ELF relo\n", i);
7198 			return -LIBBPF_ERRNO__FORMAT;
7199 		}
7200 
7201 		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
7202 		if (!sym) {
7203 			pr_warn(".maps relo #%d: symbol %zx not found\n",
7204 				i, (size_t)ELF64_R_SYM(rel->r_info));
7205 			return -LIBBPF_ERRNO__FORMAT;
7206 		}
7207 		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
7208 
7209 		pr_debug(".maps relo #%d: for %zd value %zd rel->r_offset %zu name %d ('%s')\n",
7210 			 i, (ssize_t)(rel->r_info >> 32), (size_t)sym->st_value,
7211 			 (size_t)rel->r_offset, sym->st_name, name);
7212 
7213 		for (j = 0; j < obj->nr_maps; j++) {
7214 			map = &obj->maps[j];
7215 			if (map->sec_idx != obj->efile.btf_maps_shndx)
7216 				continue;
7217 
7218 			vi = btf_var_secinfos(sec) + map->btf_var_idx;
7219 			if (vi->offset <= rel->r_offset &&
7220 			    rel->r_offset + bpf_ptr_sz <= vi->offset + vi->size)
7221 				break;
7222 		}
7223 		if (j == obj->nr_maps) {
7224 			pr_warn(".maps relo #%d: cannot find map '%s' at rel->r_offset %zu\n",
7225 				i, name, (size_t)rel->r_offset);
7226 			return -EINVAL;
7227 		}
7228 
7229 		is_map_in_map = bpf_map_type__is_map_in_map(map->def.type);
7230 		is_prog_array = map->def.type == BPF_MAP_TYPE_PROG_ARRAY;
7231 		type = is_map_in_map ? "map" : "prog";
7232 		if (is_map_in_map) {
7233 			if (sym->st_shndx != obj->efile.btf_maps_shndx) {
7234 				pr_warn(".maps relo #%d: '%s' isn't a BTF-defined map\n",
7235 					i, name);
7236 				return -LIBBPF_ERRNO__RELOC;
7237 			}
7238 			if (map->def.type == BPF_MAP_TYPE_HASH_OF_MAPS &&
7239 			    map->def.key_size != sizeof(int)) {
7240 				pr_warn(".maps relo #%d: hash-of-maps '%s' should have key size %zu.\n",
7241 					i, map->name, sizeof(int));
7242 				return -EINVAL;
7243 			}
7244 			targ_map = bpf_object__find_map_by_name(obj, name);
7245 			if (!targ_map) {
7246 				pr_warn(".maps relo #%d: '%s' isn't a valid map reference\n",
7247 					i, name);
7248 				return -ESRCH;
7249 			}
7250 		} else if (is_prog_array) {
7251 			targ_prog = bpf_object__find_program_by_name(obj, name);
7252 			if (!targ_prog) {
7253 				pr_warn(".maps relo #%d: '%s' isn't a valid program reference\n",
7254 					i, name);
7255 				return -ESRCH;
7256 			}
7257 			if (targ_prog->sec_idx != sym->st_shndx ||
7258 			    targ_prog->sec_insn_off * 8 != sym->st_value ||
7259 			    prog_is_subprog(obj, targ_prog)) {
7260 				pr_warn(".maps relo #%d: '%s' isn't an entry-point program\n",
7261 					i, name);
7262 				return -LIBBPF_ERRNO__RELOC;
7263 			}
7264 		} else {
7265 			return -EINVAL;
7266 		}
7267 
7268 		var = btf__type_by_id(obj->btf, vi->type);
7269 		def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
7270 		if (btf_vlen(def) == 0)
7271 			return -EINVAL;
7272 		member = btf_members(def) + btf_vlen(def) - 1;
7273 		mname = btf__name_by_offset(obj->btf, member->name_off);
7274 		if (strcmp(mname, "values"))
7275 			return -EINVAL;
7276 
7277 		moff = btf_member_bit_offset(def, btf_vlen(def) - 1) / 8;
7278 		if (rel->r_offset - vi->offset < moff)
7279 			return -EINVAL;
7280 
7281 		moff = rel->r_offset - vi->offset - moff;
7282 		/* here we use BPF pointer size, which is always 64 bit, as we
7283 		 * are parsing ELF that was built for BPF target
7284 		 */
7285 		if (moff % bpf_ptr_sz)
7286 			return -EINVAL;
7287 		moff /= bpf_ptr_sz;
7288 		if (moff >= map->init_slots_sz) {
7289 			new_sz = moff + 1;
7290 			tmp = libbpf_reallocarray(map->init_slots, new_sz, host_ptr_sz);
7291 			if (!tmp)
7292 				return -ENOMEM;
7293 			map->init_slots = tmp;
7294 			memset(map->init_slots + map->init_slots_sz, 0,
7295 			       (new_sz - map->init_slots_sz) * host_ptr_sz);
7296 			map->init_slots_sz = new_sz;
7297 		}
7298 		map->init_slots[moff] = is_map_in_map ? (void *)targ_map : (void *)targ_prog;
7299 
7300 		pr_debug(".maps relo #%d: map '%s' slot [%d] points to %s '%s'\n",
7301 			 i, map->name, moff, type, name);
7302 	}
7303 
7304 	return 0;
7305 }
7306 
7307 static int bpf_object__collect_relos(struct bpf_object *obj)
7308 {
7309 	int i, err;
7310 
7311 	for (i = 0; i < obj->efile.sec_cnt; i++) {
7312 		struct elf_sec_desc *sec_desc = &obj->efile.secs[i];
7313 		Elf64_Shdr *shdr;
7314 		Elf_Data *data;
7315 		int idx;
7316 
7317 		if (sec_desc->sec_type != SEC_RELO)
7318 			continue;
7319 
7320 		shdr = sec_desc->shdr;
7321 		data = sec_desc->data;
7322 		idx = shdr->sh_info;
7323 
7324 		if (shdr->sh_type != SHT_REL || idx < 0 || idx >= obj->efile.sec_cnt) {
7325 			pr_warn("internal error at %d\n", __LINE__);
7326 			return -LIBBPF_ERRNO__INTERNAL;
7327 		}
7328 
7329 		if (obj->efile.secs[idx].sec_type == SEC_ST_OPS)
7330 			err = bpf_object__collect_st_ops_relos(obj, shdr, data);
7331 		else if (idx == obj->efile.btf_maps_shndx)
7332 			err = bpf_object__collect_map_relos(obj, shdr, data);
7333 		else
7334 			err = bpf_object__collect_prog_relos(obj, shdr, data);
7335 		if (err)
7336 			return err;
7337 	}
7338 
7339 	bpf_object__sort_relos(obj);
7340 	return 0;
7341 }
7342 
7343 static bool insn_is_helper_call(struct bpf_insn *insn, enum bpf_func_id *func_id)
7344 {
7345 	if (BPF_CLASS(insn->code) == BPF_JMP &&
7346 	    BPF_OP(insn->code) == BPF_CALL &&
7347 	    BPF_SRC(insn->code) == BPF_K &&
7348 	    insn->src_reg == 0 &&
7349 	    insn->dst_reg == 0) {
7350 		    *func_id = insn->imm;
7351 		    return true;
7352 	}
7353 	return false;
7354 }
7355 
7356 static int bpf_object__sanitize_prog(struct bpf_object *obj, struct bpf_program *prog)
7357 {
7358 	struct bpf_insn *insn = prog->insns;
7359 	enum bpf_func_id func_id;
7360 	int i;
7361 
7362 	if (obj->gen_loader)
7363 		return 0;
7364 
7365 	for (i = 0; i < prog->insns_cnt; i++, insn++) {
7366 		if (!insn_is_helper_call(insn, &func_id))
7367 			continue;
7368 
7369 		/* on kernels that don't yet support
7370 		 * bpf_probe_read_{kernel,user}[_str] helpers, fall back
7371 		 * to bpf_probe_read() which works well for old kernels
7372 		 */
7373 		switch (func_id) {
7374 		case BPF_FUNC_probe_read_kernel:
7375 		case BPF_FUNC_probe_read_user:
7376 			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
7377 				insn->imm = BPF_FUNC_probe_read;
7378 			break;
7379 		case BPF_FUNC_probe_read_kernel_str:
7380 		case BPF_FUNC_probe_read_user_str:
7381 			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
7382 				insn->imm = BPF_FUNC_probe_read_str;
7383 			break;
7384 		default:
7385 			break;
7386 		}
7387 	}
7388 	return 0;
7389 }
7390 
7391 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
7392 				     int *btf_obj_fd, int *btf_type_id);
7393 
7394 /* this is called as prog->sec_def->prog_prepare_load_fn for libbpf-supported sec_defs */
7395 static int libbpf_prepare_prog_load(struct bpf_program *prog,
7396 				    struct bpf_prog_load_opts *opts, long cookie)
7397 {
7398 	enum sec_def_flags def = cookie;
7399 
7400 	/* old kernels might not support specifying expected_attach_type */
7401 	if ((def & SEC_EXP_ATTACH_OPT) && !kernel_supports(prog->obj, FEAT_EXP_ATTACH_TYPE))
7402 		opts->expected_attach_type = 0;
7403 
7404 	if (def & SEC_SLEEPABLE)
7405 		opts->prog_flags |= BPF_F_SLEEPABLE;
7406 
7407 	if (prog->type == BPF_PROG_TYPE_XDP && (def & SEC_XDP_FRAGS))
7408 		opts->prog_flags |= BPF_F_XDP_HAS_FRAGS;
7409 
7410 	/* special check for usdt to use uprobe_multi link */
7411 	if ((def & SEC_USDT) && kernel_supports(prog->obj, FEAT_UPROBE_MULTI_LINK)) {
7412 		/* for BPF_TRACE_UPROBE_MULTI, user might want to query expected_attach_type
7413 		 * in prog, and expected_attach_type we set in kernel is from opts, so we
7414 		 * update both.
7415 		 */
7416 		prog->expected_attach_type = BPF_TRACE_UPROBE_MULTI;
7417 		opts->expected_attach_type = BPF_TRACE_UPROBE_MULTI;
7418 	}
7419 
7420 	if ((def & SEC_ATTACH_BTF) && !prog->attach_btf_id) {
7421 		int btf_obj_fd = 0, btf_type_id = 0, err;
7422 		const char *attach_name;
7423 
7424 		attach_name = strchr(prog->sec_name, '/');
7425 		if (!attach_name) {
7426 			/* if BPF program is annotated with just SEC("fentry")
7427 			 * (or similar) without declaratively specifying
7428 			 * target, then it is expected that target will be
7429 			 * specified with bpf_program__set_attach_target() at
7430 			 * runtime before BPF object load step. If not, then
7431 			 * there is nothing to load into the kernel as BPF
7432 			 * verifier won't be able to validate BPF program
7433 			 * correctness anyways.
7434 			 */
7435 			pr_warn("prog '%s': no BTF-based attach target is specified, use bpf_program__set_attach_target()\n",
7436 				prog->name);
7437 			return -EINVAL;
7438 		}
7439 		attach_name++; /* skip over / */
7440 
7441 		err = libbpf_find_attach_btf_id(prog, attach_name, &btf_obj_fd, &btf_type_id);
7442 		if (err)
7443 			return err;
7444 
7445 		/* cache resolved BTF FD and BTF type ID in the prog */
7446 		prog->attach_btf_obj_fd = btf_obj_fd;
7447 		prog->attach_btf_id = btf_type_id;
7448 
7449 		/* but by now libbpf common logic is not utilizing
7450 		 * prog->atach_btf_obj_fd/prog->attach_btf_id anymore because
7451 		 * this callback is called after opts were populated by
7452 		 * libbpf, so this callback has to update opts explicitly here
7453 		 */
7454 		opts->attach_btf_obj_fd = btf_obj_fd;
7455 		opts->attach_btf_id = btf_type_id;
7456 	}
7457 	return 0;
7458 }
7459 
7460 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz);
7461 
7462 static int bpf_object_load_prog(struct bpf_object *obj, struct bpf_program *prog,
7463 				struct bpf_insn *insns, int insns_cnt,
7464 				const char *license, __u32 kern_version, int *prog_fd)
7465 {
7466 	LIBBPF_OPTS(bpf_prog_load_opts, load_attr);
7467 	const char *prog_name = NULL;
7468 	size_t log_buf_size = 0;
7469 	char *log_buf = NULL, *tmp;
7470 	bool own_log_buf = true;
7471 	__u32 log_level = prog->log_level;
7472 	int ret, err;
7473 
7474 	/* Be more helpful by rejecting programs that can't be validated early
7475 	 * with more meaningful and actionable error message.
7476 	 */
7477 	switch (prog->type) {
7478 	case BPF_PROG_TYPE_UNSPEC:
7479 		/*
7480 		 * The program type must be set.  Most likely we couldn't find a proper
7481 		 * section definition at load time, and thus we didn't infer the type.
7482 		 */
7483 		pr_warn("prog '%s': missing BPF prog type, check ELF section name '%s'\n",
7484 			prog->name, prog->sec_name);
7485 		return -EINVAL;
7486 	case BPF_PROG_TYPE_STRUCT_OPS:
7487 		if (prog->attach_btf_id == 0) {
7488 			pr_warn("prog '%s': SEC(\"struct_ops\") program isn't referenced anywhere, did you forget to use it?\n",
7489 				prog->name);
7490 			return -EINVAL;
7491 		}
7492 		break;
7493 	default:
7494 		break;
7495 	}
7496 
7497 	if (!insns || !insns_cnt)
7498 		return -EINVAL;
7499 
7500 	if (kernel_supports(obj, FEAT_PROG_NAME))
7501 		prog_name = prog->name;
7502 	load_attr.attach_prog_fd = prog->attach_prog_fd;
7503 	load_attr.attach_btf_obj_fd = prog->attach_btf_obj_fd;
7504 	load_attr.attach_btf_id = prog->attach_btf_id;
7505 	load_attr.kern_version = kern_version;
7506 	load_attr.prog_ifindex = prog->prog_ifindex;
7507 	load_attr.expected_attach_type = prog->expected_attach_type;
7508 
7509 	/* specify func_info/line_info only if kernel supports them */
7510 	if (obj->btf && btf__fd(obj->btf) >= 0 && kernel_supports(obj, FEAT_BTF_FUNC)) {
7511 		load_attr.prog_btf_fd = btf__fd(obj->btf);
7512 		load_attr.func_info = prog->func_info;
7513 		load_attr.func_info_rec_size = prog->func_info_rec_size;
7514 		load_attr.func_info_cnt = prog->func_info_cnt;
7515 		load_attr.line_info = prog->line_info;
7516 		load_attr.line_info_rec_size = prog->line_info_rec_size;
7517 		load_attr.line_info_cnt = prog->line_info_cnt;
7518 	}
7519 	load_attr.log_level = log_level;
7520 	load_attr.prog_flags = prog->prog_flags;
7521 	load_attr.fd_array = obj->fd_array;
7522 
7523 	load_attr.token_fd = obj->token_fd;
7524 	if (obj->token_fd)
7525 		load_attr.prog_flags |= BPF_F_TOKEN_FD;
7526 
7527 	/* adjust load_attr if sec_def provides custom preload callback */
7528 	if (prog->sec_def && prog->sec_def->prog_prepare_load_fn) {
7529 		err = prog->sec_def->prog_prepare_load_fn(prog, &load_attr, prog->sec_def->cookie);
7530 		if (err < 0) {
7531 			pr_warn("prog '%s': failed to prepare load attributes: %s\n",
7532 				prog->name, errstr(err));
7533 			return err;
7534 		}
7535 		insns = prog->insns;
7536 		insns_cnt = prog->insns_cnt;
7537 	}
7538 
7539 	if (obj->gen_loader) {
7540 		bpf_gen__prog_load(obj->gen_loader, prog->type, prog->name,
7541 				   license, insns, insns_cnt, &load_attr,
7542 				   prog - obj->programs);
7543 		*prog_fd = -1;
7544 		return 0;
7545 	}
7546 
7547 retry_load:
7548 	/* if log_level is zero, we don't request logs initially even if
7549 	 * custom log_buf is specified; if the program load fails, then we'll
7550 	 * bump log_level to 1 and use either custom log_buf or we'll allocate
7551 	 * our own and retry the load to get details on what failed
7552 	 */
7553 	if (log_level) {
7554 		if (prog->log_buf) {
7555 			log_buf = prog->log_buf;
7556 			log_buf_size = prog->log_size;
7557 			own_log_buf = false;
7558 		} else if (obj->log_buf) {
7559 			log_buf = obj->log_buf;
7560 			log_buf_size = obj->log_size;
7561 			own_log_buf = false;
7562 		} else {
7563 			log_buf_size = max((size_t)BPF_LOG_BUF_SIZE, log_buf_size * 2);
7564 			tmp = realloc(log_buf, log_buf_size);
7565 			if (!tmp) {
7566 				ret = -ENOMEM;
7567 				goto out;
7568 			}
7569 			log_buf = tmp;
7570 			log_buf[0] = '\0';
7571 			own_log_buf = true;
7572 		}
7573 	}
7574 
7575 	load_attr.log_buf = log_buf;
7576 	load_attr.log_size = log_buf_size;
7577 	load_attr.log_level = log_level;
7578 
7579 	ret = bpf_prog_load(prog->type, prog_name, license, insns, insns_cnt, &load_attr);
7580 	if (ret >= 0) {
7581 		if (log_level && own_log_buf) {
7582 			pr_debug("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
7583 				 prog->name, log_buf);
7584 		}
7585 
7586 		if (obj->has_rodata && kernel_supports(obj, FEAT_PROG_BIND_MAP)) {
7587 			struct bpf_map *map;
7588 			int i;
7589 
7590 			for (i = 0; i < obj->nr_maps; i++) {
7591 				map = &prog->obj->maps[i];
7592 				if (map->libbpf_type != LIBBPF_MAP_RODATA)
7593 					continue;
7594 
7595 				if (bpf_prog_bind_map(ret, map->fd, NULL)) {
7596 					pr_warn("prog '%s': failed to bind map '%s': %s\n",
7597 						prog->name, map->real_name, errstr(errno));
7598 					/* Don't fail hard if can't bind rodata. */
7599 				}
7600 			}
7601 		}
7602 
7603 		*prog_fd = ret;
7604 		ret = 0;
7605 		goto out;
7606 	}
7607 
7608 	if (log_level == 0) {
7609 		log_level = 1;
7610 		goto retry_load;
7611 	}
7612 	/* On ENOSPC, increase log buffer size and retry, unless custom
7613 	 * log_buf is specified.
7614 	 * Be careful to not overflow u32, though. Kernel's log buf size limit
7615 	 * isn't part of UAPI so it can always be bumped to full 4GB. So don't
7616 	 * multiply by 2 unless we are sure we'll fit within 32 bits.
7617 	 * Currently, we'll get -EINVAL when we reach (UINT_MAX >> 2).
7618 	 */
7619 	if (own_log_buf && errno == ENOSPC && log_buf_size <= UINT_MAX / 2)
7620 		goto retry_load;
7621 
7622 	ret = -errno;
7623 
7624 	/* post-process verifier log to improve error descriptions */
7625 	fixup_verifier_log(prog, log_buf, log_buf_size);
7626 
7627 	pr_warn("prog '%s': BPF program load failed: %s\n", prog->name, errstr(errno));
7628 	pr_perm_msg(ret);
7629 
7630 	if (own_log_buf && log_buf && log_buf[0] != '\0') {
7631 		pr_warn("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
7632 			prog->name, log_buf);
7633 	}
7634 
7635 out:
7636 	if (own_log_buf)
7637 		free(log_buf);
7638 	return ret;
7639 }
7640 
7641 static char *find_prev_line(char *buf, char *cur)
7642 {
7643 	char *p;
7644 
7645 	if (cur == buf) /* end of a log buf */
7646 		return NULL;
7647 
7648 	p = cur - 1;
7649 	while (p - 1 >= buf && *(p - 1) != '\n')
7650 		p--;
7651 
7652 	return p;
7653 }
7654 
7655 static void patch_log(char *buf, size_t buf_sz, size_t log_sz,
7656 		      char *orig, size_t orig_sz, const char *patch)
7657 {
7658 	/* size of the remaining log content to the right from the to-be-replaced part */
7659 	size_t rem_sz = (buf + log_sz) - (orig + orig_sz);
7660 	size_t patch_sz = strlen(patch);
7661 
7662 	if (patch_sz != orig_sz) {
7663 		/* If patch line(s) are longer than original piece of verifier log,
7664 		 * shift log contents by (patch_sz - orig_sz) bytes to the right
7665 		 * starting from after to-be-replaced part of the log.
7666 		 *
7667 		 * If patch line(s) are shorter than original piece of verifier log,
7668 		 * shift log contents by (orig_sz - patch_sz) bytes to the left
7669 		 * starting from after to-be-replaced part of the log
7670 		 *
7671 		 * We need to be careful about not overflowing available
7672 		 * buf_sz capacity. If that's the case, we'll truncate the end
7673 		 * of the original log, as necessary.
7674 		 */
7675 		if (patch_sz > orig_sz) {
7676 			if (orig + patch_sz >= buf + buf_sz) {
7677 				/* patch is big enough to cover remaining space completely */
7678 				patch_sz -= (orig + patch_sz) - (buf + buf_sz) + 1;
7679 				rem_sz = 0;
7680 			} else if (patch_sz - orig_sz > buf_sz - log_sz) {
7681 				/* patch causes part of remaining log to be truncated */
7682 				rem_sz -= (patch_sz - orig_sz) - (buf_sz - log_sz);
7683 			}
7684 		}
7685 		/* shift remaining log to the right by calculated amount */
7686 		memmove(orig + patch_sz, orig + orig_sz, rem_sz);
7687 	}
7688 
7689 	memcpy(orig, patch, patch_sz);
7690 }
7691 
7692 static void fixup_log_failed_core_relo(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 CO-RE relocation:
7697 	 * line1 -> 123: (85) call unknown#195896080
7698 	 * line2 -> invalid func unknown#195896080
7699 	 * line3 -> <anything else or end of buffer>
7700 	 *
7701 	 * "123" is the index of the instruction that was poisoned. We extract
7702 	 * instruction index to find corresponding CO-RE relocation and
7703 	 * replace this part of the log with more relevant information about
7704 	 * failed CO-RE relocation.
7705 	 */
7706 	const struct bpf_core_relo *relo;
7707 	struct bpf_core_spec spec;
7708 	char patch[512], spec_buf[256];
7709 	int insn_idx, err, spec_len;
7710 
7711 	if (sscanf(line1, "%d: (%*d) call unknown#195896080\n", &insn_idx) != 1)
7712 		return;
7713 
7714 	relo = find_relo_core(prog, insn_idx);
7715 	if (!relo)
7716 		return;
7717 
7718 	err = bpf_core_parse_spec(prog->name, prog->obj->btf, relo, &spec);
7719 	if (err)
7720 		return;
7721 
7722 	spec_len = bpf_core_format_spec(spec_buf, sizeof(spec_buf), &spec);
7723 	snprintf(patch, sizeof(patch),
7724 		 "%d: <invalid CO-RE relocation>\n"
7725 		 "failed to resolve CO-RE relocation %s%s\n",
7726 		 insn_idx, spec_buf, spec_len >= sizeof(spec_buf) ? "..." : "");
7727 
7728 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7729 }
7730 
7731 static void fixup_log_missing_map_load(struct bpf_program *prog,
7732 				       char *buf, size_t buf_sz, size_t log_sz,
7733 				       char *line1, char *line2, char *line3)
7734 {
7735 	/* Expected log for failed and not properly guarded map reference:
7736 	 * line1 -> 123: (85) call unknown#2001000345
7737 	 * line2 -> invalid func unknown#2001000345
7738 	 * line3 -> <anything else or end of buffer>
7739 	 *
7740 	 * "123" is the index of the instruction that was poisoned.
7741 	 * "345" in "2001000345" is a map index in obj->maps to fetch map name.
7742 	 */
7743 	struct bpf_object *obj = prog->obj;
7744 	const struct bpf_map *map;
7745 	int insn_idx, map_idx;
7746 	char patch[128];
7747 
7748 	if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &map_idx) != 2)
7749 		return;
7750 
7751 	map_idx -= POISON_LDIMM64_MAP_BASE;
7752 	if (map_idx < 0 || map_idx >= obj->nr_maps)
7753 		return;
7754 	map = &obj->maps[map_idx];
7755 
7756 	snprintf(patch, sizeof(patch),
7757 		 "%d: <invalid BPF map reference>\n"
7758 		 "BPF map '%s' is referenced but wasn't created\n",
7759 		 insn_idx, map->name);
7760 
7761 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7762 }
7763 
7764 static void fixup_log_missing_kfunc_call(struct bpf_program *prog,
7765 					 char *buf, size_t buf_sz, size_t log_sz,
7766 					 char *line1, char *line2, char *line3)
7767 {
7768 	/* Expected log for failed and not properly guarded kfunc call:
7769 	 * line1 -> 123: (85) call unknown#2002000345
7770 	 * line2 -> invalid func unknown#2002000345
7771 	 * line3 -> <anything else or end of buffer>
7772 	 *
7773 	 * "123" is the index of the instruction that was poisoned.
7774 	 * "345" in "2002000345" is an extern index in obj->externs to fetch kfunc name.
7775 	 */
7776 	struct bpf_object *obj = prog->obj;
7777 	const struct extern_desc *ext;
7778 	int insn_idx, ext_idx;
7779 	char patch[128];
7780 
7781 	if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &ext_idx) != 2)
7782 		return;
7783 
7784 	ext_idx -= POISON_CALL_KFUNC_BASE;
7785 	if (ext_idx < 0 || ext_idx >= obj->nr_extern)
7786 		return;
7787 	ext = &obj->externs[ext_idx];
7788 
7789 	snprintf(patch, sizeof(patch),
7790 		 "%d: <invalid kfunc call>\n"
7791 		 "kfunc '%s' is referenced but wasn't resolved\n",
7792 		 insn_idx, ext->name);
7793 
7794 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7795 }
7796 
7797 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz)
7798 {
7799 	/* look for familiar error patterns in last N lines of the log */
7800 	const size_t max_last_line_cnt = 10;
7801 	char *prev_line, *cur_line, *next_line;
7802 	size_t log_sz;
7803 	int i;
7804 
7805 	if (!buf)
7806 		return;
7807 
7808 	log_sz = strlen(buf) + 1;
7809 	next_line = buf + log_sz - 1;
7810 
7811 	for (i = 0; i < max_last_line_cnt; i++, next_line = cur_line) {
7812 		cur_line = find_prev_line(buf, next_line);
7813 		if (!cur_line)
7814 			return;
7815 
7816 		if (str_has_pfx(cur_line, "invalid func unknown#195896080\n")) {
7817 			prev_line = find_prev_line(buf, cur_line);
7818 			if (!prev_line)
7819 				continue;
7820 
7821 			/* failed CO-RE relocation case */
7822 			fixup_log_failed_core_relo(prog, buf, buf_sz, log_sz,
7823 						   prev_line, cur_line, next_line);
7824 			return;
7825 		} else if (str_has_pfx(cur_line, "invalid func unknown#"POISON_LDIMM64_MAP_PFX)) {
7826 			prev_line = find_prev_line(buf, cur_line);
7827 			if (!prev_line)
7828 				continue;
7829 
7830 			/* reference to uncreated BPF map */
7831 			fixup_log_missing_map_load(prog, buf, buf_sz, log_sz,
7832 						   prev_line, cur_line, next_line);
7833 			return;
7834 		} else if (str_has_pfx(cur_line, "invalid func unknown#"POISON_CALL_KFUNC_PFX)) {
7835 			prev_line = find_prev_line(buf, cur_line);
7836 			if (!prev_line)
7837 				continue;
7838 
7839 			/* reference to unresolved kfunc */
7840 			fixup_log_missing_kfunc_call(prog, buf, buf_sz, log_sz,
7841 						     prev_line, cur_line, next_line);
7842 			return;
7843 		}
7844 	}
7845 }
7846 
7847 static int bpf_program_record_relos(struct bpf_program *prog)
7848 {
7849 	struct bpf_object *obj = prog->obj;
7850 	int i;
7851 
7852 	for (i = 0; i < prog->nr_reloc; i++) {
7853 		struct reloc_desc *relo = &prog->reloc_desc[i];
7854 		struct extern_desc *ext = &obj->externs[relo->ext_idx];
7855 		int kind;
7856 
7857 		switch (relo->type) {
7858 		case RELO_EXTERN_LD64:
7859 			if (ext->type != EXT_KSYM)
7860 				continue;
7861 			kind = btf_is_var(btf__type_by_id(obj->btf, ext->btf_id)) ?
7862 				BTF_KIND_VAR : BTF_KIND_FUNC;
7863 			bpf_gen__record_extern(obj->gen_loader, ext->name,
7864 					       ext->is_weak, !ext->ksym.type_id,
7865 					       true, kind, relo->insn_idx);
7866 			break;
7867 		case RELO_EXTERN_CALL:
7868 			bpf_gen__record_extern(obj->gen_loader, ext->name,
7869 					       ext->is_weak, false, false, BTF_KIND_FUNC,
7870 					       relo->insn_idx);
7871 			break;
7872 		case RELO_CORE: {
7873 			struct bpf_core_relo cr = {
7874 				.insn_off = relo->insn_idx * 8,
7875 				.type_id = relo->core_relo->type_id,
7876 				.access_str_off = relo->core_relo->access_str_off,
7877 				.kind = relo->core_relo->kind,
7878 			};
7879 
7880 			bpf_gen__record_relo_core(obj->gen_loader, &cr);
7881 			break;
7882 		}
7883 		default:
7884 			continue;
7885 		}
7886 	}
7887 	return 0;
7888 }
7889 
7890 static int
7891 bpf_object__load_progs(struct bpf_object *obj, int log_level)
7892 {
7893 	struct bpf_program *prog;
7894 	size_t i;
7895 	int err;
7896 
7897 	for (i = 0; i < obj->nr_programs; i++) {
7898 		prog = &obj->programs[i];
7899 		if (prog_is_subprog(obj, prog))
7900 			continue;
7901 		if (!prog->autoload) {
7902 			pr_debug("prog '%s': skipped loading\n", prog->name);
7903 			continue;
7904 		}
7905 		prog->log_level |= log_level;
7906 
7907 		if (obj->gen_loader)
7908 			bpf_program_record_relos(prog);
7909 
7910 		err = bpf_object_load_prog(obj, prog, prog->insns, prog->insns_cnt,
7911 					   obj->license, obj->kern_version, &prog->fd);
7912 		if (err) {
7913 			pr_warn("prog '%s': failed to load: %s\n", prog->name, errstr(err));
7914 			return err;
7915 		}
7916 	}
7917 
7918 	bpf_object__free_relocs(obj);
7919 	return 0;
7920 }
7921 
7922 static int bpf_object_prepare_progs(struct bpf_object *obj)
7923 {
7924 	struct bpf_program *prog;
7925 	size_t i;
7926 	int err;
7927 
7928 	for (i = 0; i < obj->nr_programs; i++) {
7929 		prog = &obj->programs[i];
7930 		err = bpf_object__sanitize_prog(obj, prog);
7931 		if (err)
7932 			return err;
7933 	}
7934 	return 0;
7935 }
7936 
7937 static const struct bpf_sec_def *find_sec_def(const char *sec_name);
7938 
7939 static int bpf_object_init_progs(struct bpf_object *obj, const struct bpf_object_open_opts *opts)
7940 {
7941 	struct bpf_program *prog;
7942 	int err;
7943 
7944 	bpf_object__for_each_program(prog, obj) {
7945 		prog->sec_def = find_sec_def(prog->sec_name);
7946 		if (!prog->sec_def) {
7947 			/* couldn't guess, but user might manually specify */
7948 			pr_debug("prog '%s': unrecognized ELF section name '%s'\n",
7949 				prog->name, prog->sec_name);
7950 			continue;
7951 		}
7952 
7953 		prog->type = prog->sec_def->prog_type;
7954 		prog->expected_attach_type = prog->sec_def->expected_attach_type;
7955 
7956 		/* sec_def can have custom callback which should be called
7957 		 * after bpf_program is initialized to adjust its properties
7958 		 */
7959 		if (prog->sec_def->prog_setup_fn) {
7960 			err = prog->sec_def->prog_setup_fn(prog, prog->sec_def->cookie);
7961 			if (err < 0) {
7962 				pr_warn("prog '%s': failed to initialize: %s\n",
7963 					prog->name, errstr(err));
7964 				return err;
7965 			}
7966 		}
7967 	}
7968 
7969 	return 0;
7970 }
7971 
7972 static struct bpf_object *bpf_object_open(const char *path, const void *obj_buf, size_t obj_buf_sz,
7973 					  const char *obj_name,
7974 					  const struct bpf_object_open_opts *opts)
7975 {
7976 	const char *kconfig, *btf_tmp_path, *token_path;
7977 	struct bpf_object *obj;
7978 	int err;
7979 	char *log_buf;
7980 	size_t log_size;
7981 	__u32 log_level;
7982 
7983 	if (obj_buf && !obj_name)
7984 		return ERR_PTR(-EINVAL);
7985 
7986 	if (elf_version(EV_CURRENT) == EV_NONE) {
7987 		pr_warn("failed to init libelf for %s\n",
7988 			path ? : "(mem buf)");
7989 		return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
7990 	}
7991 
7992 	if (!OPTS_VALID(opts, bpf_object_open_opts))
7993 		return ERR_PTR(-EINVAL);
7994 
7995 	obj_name = OPTS_GET(opts, object_name, NULL) ?: obj_name;
7996 	if (obj_buf) {
7997 		path = obj_name;
7998 		pr_debug("loading object '%s' from buffer\n", obj_name);
7999 	} else {
8000 		pr_debug("loading object from %s\n", path);
8001 	}
8002 
8003 	log_buf = OPTS_GET(opts, kernel_log_buf, NULL);
8004 	log_size = OPTS_GET(opts, kernel_log_size, 0);
8005 	log_level = OPTS_GET(opts, kernel_log_level, 0);
8006 	if (log_size > UINT_MAX)
8007 		return ERR_PTR(-EINVAL);
8008 	if (log_size && !log_buf)
8009 		return ERR_PTR(-EINVAL);
8010 
8011 	token_path = OPTS_GET(opts, bpf_token_path, NULL);
8012 	/* if user didn't specify bpf_token_path explicitly, check if
8013 	 * LIBBPF_BPF_TOKEN_PATH envvar was set and treat it as bpf_token_path
8014 	 * option
8015 	 */
8016 	if (!token_path)
8017 		token_path = getenv("LIBBPF_BPF_TOKEN_PATH");
8018 	if (token_path && strlen(token_path) >= PATH_MAX)
8019 		return ERR_PTR(-ENAMETOOLONG);
8020 
8021 	obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
8022 	if (IS_ERR(obj))
8023 		return obj;
8024 
8025 	obj->log_buf = log_buf;
8026 	obj->log_size = log_size;
8027 	obj->log_level = log_level;
8028 
8029 	if (token_path) {
8030 		obj->token_path = strdup(token_path);
8031 		if (!obj->token_path) {
8032 			err = -ENOMEM;
8033 			goto out;
8034 		}
8035 	}
8036 
8037 	btf_tmp_path = OPTS_GET(opts, btf_custom_path, NULL);
8038 	if (btf_tmp_path) {
8039 		if (strlen(btf_tmp_path) >= PATH_MAX) {
8040 			err = -ENAMETOOLONG;
8041 			goto out;
8042 		}
8043 		obj->btf_custom_path = strdup(btf_tmp_path);
8044 		if (!obj->btf_custom_path) {
8045 			err = -ENOMEM;
8046 			goto out;
8047 		}
8048 	}
8049 
8050 	kconfig = OPTS_GET(opts, kconfig, NULL);
8051 	if (kconfig) {
8052 		obj->kconfig = strdup(kconfig);
8053 		if (!obj->kconfig) {
8054 			err = -ENOMEM;
8055 			goto out;
8056 		}
8057 	}
8058 
8059 	err = bpf_object__elf_init(obj);
8060 	err = err ? : bpf_object__elf_collect(obj);
8061 	err = err ? : bpf_object__collect_externs(obj);
8062 	err = err ? : bpf_object_fixup_btf(obj);
8063 	err = err ? : bpf_object__init_maps(obj, opts);
8064 	err = err ? : bpf_object_init_progs(obj, opts);
8065 	err = err ? : bpf_object__collect_relos(obj);
8066 	if (err)
8067 		goto out;
8068 
8069 	bpf_object__elf_finish(obj);
8070 
8071 	return obj;
8072 out:
8073 	bpf_object__close(obj);
8074 	return ERR_PTR(err);
8075 }
8076 
8077 struct bpf_object *
8078 bpf_object__open_file(const char *path, const struct bpf_object_open_opts *opts)
8079 {
8080 	if (!path)
8081 		return libbpf_err_ptr(-EINVAL);
8082 
8083 	return libbpf_ptr(bpf_object_open(path, NULL, 0, NULL, opts));
8084 }
8085 
8086 struct bpf_object *bpf_object__open(const char *path)
8087 {
8088 	return bpf_object__open_file(path, NULL);
8089 }
8090 
8091 struct bpf_object *
8092 bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
8093 		     const struct bpf_object_open_opts *opts)
8094 {
8095 	char tmp_name[64];
8096 
8097 	if (!obj_buf || obj_buf_sz == 0)
8098 		return libbpf_err_ptr(-EINVAL);
8099 
8100 	/* create a (quite useless) default "name" for this memory buffer object */
8101 	snprintf(tmp_name, sizeof(tmp_name), "%lx-%zx", (unsigned long)obj_buf, obj_buf_sz);
8102 
8103 	return libbpf_ptr(bpf_object_open(NULL, obj_buf, obj_buf_sz, tmp_name, opts));
8104 }
8105 
8106 static int bpf_object_unload(struct bpf_object *obj)
8107 {
8108 	size_t i;
8109 
8110 	if (!obj)
8111 		return libbpf_err(-EINVAL);
8112 
8113 	for (i = 0; i < obj->nr_maps; i++) {
8114 		zclose(obj->maps[i].fd);
8115 		if (obj->maps[i].st_ops)
8116 			zfree(&obj->maps[i].st_ops->kern_vdata);
8117 	}
8118 
8119 	for (i = 0; i < obj->nr_programs; i++)
8120 		bpf_program__unload(&obj->programs[i]);
8121 
8122 	return 0;
8123 }
8124 
8125 static int bpf_object__sanitize_maps(struct bpf_object *obj)
8126 {
8127 	struct bpf_map *m;
8128 
8129 	bpf_object__for_each_map(m, obj) {
8130 		if (!bpf_map__is_internal(m))
8131 			continue;
8132 		if (!kernel_supports(obj, FEAT_ARRAY_MMAP))
8133 			m->def.map_flags &= ~BPF_F_MMAPABLE;
8134 	}
8135 
8136 	return 0;
8137 }
8138 
8139 typedef int (*kallsyms_cb_t)(unsigned long long sym_addr, char sym_type,
8140 			     const char *sym_name, void *ctx);
8141 
8142 static int libbpf_kallsyms_parse(kallsyms_cb_t cb, void *ctx)
8143 {
8144 	char sym_type, sym_name[500];
8145 	unsigned long long sym_addr;
8146 	int ret, err = 0;
8147 	FILE *f;
8148 
8149 	f = fopen("/proc/kallsyms", "re");
8150 	if (!f) {
8151 		err = -errno;
8152 		pr_warn("failed to open /proc/kallsyms: %s\n", errstr(err));
8153 		return err;
8154 	}
8155 
8156 	while (true) {
8157 		ret = fscanf(f, "%llx %c %499s%*[^\n]\n",
8158 			     &sym_addr, &sym_type, sym_name);
8159 		if (ret == EOF && feof(f))
8160 			break;
8161 		if (ret != 3) {
8162 			pr_warn("failed to read kallsyms entry: %d\n", ret);
8163 			err = -EINVAL;
8164 			break;
8165 		}
8166 
8167 		err = cb(sym_addr, sym_type, sym_name, ctx);
8168 		if (err)
8169 			break;
8170 	}
8171 
8172 	fclose(f);
8173 	return err;
8174 }
8175 
8176 static int kallsyms_cb(unsigned long long sym_addr, char sym_type,
8177 		       const char *sym_name, void *ctx)
8178 {
8179 	struct bpf_object *obj = ctx;
8180 	const struct btf_type *t;
8181 	struct extern_desc *ext;
8182 	char *res;
8183 
8184 	res = strstr(sym_name, ".llvm.");
8185 	if (sym_type == 'd' && res)
8186 		ext = find_extern_by_name_with_len(obj, sym_name, res - sym_name);
8187 	else
8188 		ext = find_extern_by_name(obj, sym_name);
8189 	if (!ext || ext->type != EXT_KSYM)
8190 		return 0;
8191 
8192 	t = btf__type_by_id(obj->btf, ext->btf_id);
8193 	if (!btf_is_var(t))
8194 		return 0;
8195 
8196 	if (ext->is_set && ext->ksym.addr != sym_addr) {
8197 		pr_warn("extern (ksym) '%s': resolution is ambiguous: 0x%llx or 0x%llx\n",
8198 			sym_name, ext->ksym.addr, sym_addr);
8199 		return -EINVAL;
8200 	}
8201 	if (!ext->is_set) {
8202 		ext->is_set = true;
8203 		ext->ksym.addr = sym_addr;
8204 		pr_debug("extern (ksym) '%s': set to 0x%llx\n", sym_name, sym_addr);
8205 	}
8206 	return 0;
8207 }
8208 
8209 static int bpf_object__read_kallsyms_file(struct bpf_object *obj)
8210 {
8211 	return libbpf_kallsyms_parse(kallsyms_cb, obj);
8212 }
8213 
8214 static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
8215 			    __u16 kind, struct btf **res_btf,
8216 			    struct module_btf **res_mod_btf)
8217 {
8218 	struct module_btf *mod_btf;
8219 	struct btf *btf;
8220 	int i, id, err;
8221 
8222 	btf = obj->btf_vmlinux;
8223 	mod_btf = NULL;
8224 	id = btf__find_by_name_kind(btf, ksym_name, kind);
8225 
8226 	if (id == -ENOENT) {
8227 		err = load_module_btfs(obj);
8228 		if (err)
8229 			return err;
8230 
8231 		for (i = 0; i < obj->btf_module_cnt; i++) {
8232 			/* we assume module_btf's BTF FD is always >0 */
8233 			mod_btf = &obj->btf_modules[i];
8234 			btf = mod_btf->btf;
8235 			id = btf__find_by_name_kind_own(btf, ksym_name, kind);
8236 			if (id != -ENOENT)
8237 				break;
8238 		}
8239 	}
8240 	if (id <= 0)
8241 		return -ESRCH;
8242 
8243 	*res_btf = btf;
8244 	*res_mod_btf = mod_btf;
8245 	return id;
8246 }
8247 
8248 static int bpf_object__resolve_ksym_var_btf_id(struct bpf_object *obj,
8249 					       struct extern_desc *ext)
8250 {
8251 	const struct btf_type *targ_var, *targ_type;
8252 	__u32 targ_type_id, local_type_id;
8253 	struct module_btf *mod_btf = NULL;
8254 	const char *targ_var_name;
8255 	struct btf *btf = NULL;
8256 	int id, err;
8257 
8258 	id = find_ksym_btf_id(obj, ext->name, BTF_KIND_VAR, &btf, &mod_btf);
8259 	if (id < 0) {
8260 		if (id == -ESRCH && ext->is_weak)
8261 			return 0;
8262 		pr_warn("extern (var ksym) '%s': not found in kernel BTF\n",
8263 			ext->name);
8264 		return id;
8265 	}
8266 
8267 	/* find local type_id */
8268 	local_type_id = ext->ksym.type_id;
8269 
8270 	/* find target type_id */
8271 	targ_var = btf__type_by_id(btf, id);
8272 	targ_var_name = btf__name_by_offset(btf, targ_var->name_off);
8273 	targ_type = skip_mods_and_typedefs(btf, targ_var->type, &targ_type_id);
8274 
8275 	err = bpf_core_types_are_compat(obj->btf, local_type_id,
8276 					btf, targ_type_id);
8277 	if (err <= 0) {
8278 		const struct btf_type *local_type;
8279 		const char *targ_name, *local_name;
8280 
8281 		local_type = btf__type_by_id(obj->btf, local_type_id);
8282 		local_name = btf__name_by_offset(obj->btf, local_type->name_off);
8283 		targ_name = btf__name_by_offset(btf, targ_type->name_off);
8284 
8285 		pr_warn("extern (var ksym) '%s': incompatible types, expected [%d] %s %s, but kernel has [%d] %s %s\n",
8286 			ext->name, local_type_id,
8287 			btf_kind_str(local_type), local_name, targ_type_id,
8288 			btf_kind_str(targ_type), targ_name);
8289 		return -EINVAL;
8290 	}
8291 
8292 	ext->is_set = true;
8293 	ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
8294 	ext->ksym.kernel_btf_id = id;
8295 	pr_debug("extern (var ksym) '%s': resolved to [%d] %s %s\n",
8296 		 ext->name, id, btf_kind_str(targ_var), targ_var_name);
8297 
8298 	return 0;
8299 }
8300 
8301 static int bpf_object__resolve_ksym_func_btf_id(struct bpf_object *obj,
8302 						struct extern_desc *ext)
8303 {
8304 	int local_func_proto_id, kfunc_proto_id, kfunc_id;
8305 	struct module_btf *mod_btf = NULL;
8306 	const struct btf_type *kern_func;
8307 	struct btf *kern_btf = NULL;
8308 	int ret;
8309 
8310 	local_func_proto_id = ext->ksym.type_id;
8311 
8312 	kfunc_id = find_ksym_btf_id(obj, ext->essent_name ?: ext->name, BTF_KIND_FUNC, &kern_btf,
8313 				    &mod_btf);
8314 	if (kfunc_id < 0) {
8315 		if (kfunc_id == -ESRCH && ext->is_weak)
8316 			return 0;
8317 		pr_warn("extern (func ksym) '%s': not found in kernel or module BTFs\n",
8318 			ext->name);
8319 		return kfunc_id;
8320 	}
8321 
8322 	kern_func = btf__type_by_id(kern_btf, kfunc_id);
8323 	kfunc_proto_id = kern_func->type;
8324 
8325 	ret = bpf_core_types_are_compat(obj->btf, local_func_proto_id,
8326 					kern_btf, kfunc_proto_id);
8327 	if (ret <= 0) {
8328 		if (ext->is_weak)
8329 			return 0;
8330 
8331 		pr_warn("extern (func ksym) '%s': func_proto [%d] incompatible with %s [%d]\n",
8332 			ext->name, local_func_proto_id,
8333 			mod_btf ? mod_btf->name : "vmlinux", kfunc_proto_id);
8334 		return -EINVAL;
8335 	}
8336 
8337 	/* set index for module BTF fd in fd_array, if unset */
8338 	if (mod_btf && !mod_btf->fd_array_idx) {
8339 		/* insn->off is s16 */
8340 		if (obj->fd_array_cnt == INT16_MAX) {
8341 			pr_warn("extern (func ksym) '%s': module BTF fd index %d too big to fit in bpf_insn offset\n",
8342 				ext->name, mod_btf->fd_array_idx);
8343 			return -E2BIG;
8344 		}
8345 		/* Cannot use index 0 for module BTF fd */
8346 		if (!obj->fd_array_cnt)
8347 			obj->fd_array_cnt = 1;
8348 
8349 		ret = libbpf_ensure_mem((void **)&obj->fd_array, &obj->fd_array_cap, sizeof(int),
8350 					obj->fd_array_cnt + 1);
8351 		if (ret)
8352 			return ret;
8353 		mod_btf->fd_array_idx = obj->fd_array_cnt;
8354 		/* we assume module BTF FD is always >0 */
8355 		obj->fd_array[obj->fd_array_cnt++] = mod_btf->fd;
8356 	}
8357 
8358 	ext->is_set = true;
8359 	ext->ksym.kernel_btf_id = kfunc_id;
8360 	ext->ksym.btf_fd_idx = mod_btf ? mod_btf->fd_array_idx : 0;
8361 	/* Also set kernel_btf_obj_fd to make sure that bpf_object__relocate_data()
8362 	 * populates FD into ld_imm64 insn when it's used to point to kfunc.
8363 	 * {kernel_btf_id, btf_fd_idx} -> fixup bpf_call.
8364 	 * {kernel_btf_id, kernel_btf_obj_fd} -> fixup ld_imm64.
8365 	 */
8366 	ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
8367 	pr_debug("extern (func ksym) '%s': resolved to %s [%d]\n",
8368 		 ext->name, mod_btf ? mod_btf->name : "vmlinux", kfunc_id);
8369 
8370 	return 0;
8371 }
8372 
8373 static int bpf_object__resolve_ksyms_btf_id(struct bpf_object *obj)
8374 {
8375 	const struct btf_type *t;
8376 	struct extern_desc *ext;
8377 	int i, err;
8378 
8379 	for (i = 0; i < obj->nr_extern; i++) {
8380 		ext = &obj->externs[i];
8381 		if (ext->type != EXT_KSYM || !ext->ksym.type_id)
8382 			continue;
8383 
8384 		if (obj->gen_loader) {
8385 			ext->is_set = true;
8386 			ext->ksym.kernel_btf_obj_fd = 0;
8387 			ext->ksym.kernel_btf_id = 0;
8388 			continue;
8389 		}
8390 		t = btf__type_by_id(obj->btf, ext->btf_id);
8391 		if (btf_is_var(t))
8392 			err = bpf_object__resolve_ksym_var_btf_id(obj, ext);
8393 		else
8394 			err = bpf_object__resolve_ksym_func_btf_id(obj, ext);
8395 		if (err)
8396 			return err;
8397 	}
8398 	return 0;
8399 }
8400 
8401 static int bpf_object__resolve_externs(struct bpf_object *obj,
8402 				       const char *extra_kconfig)
8403 {
8404 	bool need_config = false, need_kallsyms = false;
8405 	bool need_vmlinux_btf = false;
8406 	struct extern_desc *ext;
8407 	void *kcfg_data = NULL;
8408 	int err, i;
8409 
8410 	if (obj->nr_extern == 0)
8411 		return 0;
8412 
8413 	if (obj->kconfig_map_idx >= 0)
8414 		kcfg_data = obj->maps[obj->kconfig_map_idx].mmaped;
8415 
8416 	for (i = 0; i < obj->nr_extern; i++) {
8417 		ext = &obj->externs[i];
8418 
8419 		if (ext->type == EXT_KSYM) {
8420 			if (ext->ksym.type_id)
8421 				need_vmlinux_btf = true;
8422 			else
8423 				need_kallsyms = true;
8424 			continue;
8425 		} else if (ext->type == EXT_KCFG) {
8426 			void *ext_ptr = kcfg_data + ext->kcfg.data_off;
8427 			__u64 value = 0;
8428 
8429 			/* Kconfig externs need actual /proc/config.gz */
8430 			if (str_has_pfx(ext->name, "CONFIG_")) {
8431 				need_config = true;
8432 				continue;
8433 			}
8434 
8435 			/* Virtual kcfg externs are customly handled by libbpf */
8436 			if (strcmp(ext->name, "LINUX_KERNEL_VERSION") == 0) {
8437 				value = get_kernel_version();
8438 				if (!value) {
8439 					pr_warn("extern (kcfg) '%s': failed to get kernel version\n", ext->name);
8440 					return -EINVAL;
8441 				}
8442 			} else if (strcmp(ext->name, "LINUX_HAS_BPF_COOKIE") == 0) {
8443 				value = kernel_supports(obj, FEAT_BPF_COOKIE);
8444 			} else if (strcmp(ext->name, "LINUX_HAS_SYSCALL_WRAPPER") == 0) {
8445 				value = kernel_supports(obj, FEAT_SYSCALL_WRAPPER);
8446 			} else if (!str_has_pfx(ext->name, "LINUX_") || !ext->is_weak) {
8447 				/* Currently libbpf supports only CONFIG_ and LINUX_ prefixed
8448 				 * __kconfig externs, where LINUX_ ones are virtual and filled out
8449 				 * customly by libbpf (their values don't come from Kconfig).
8450 				 * If LINUX_xxx variable is not recognized by libbpf, but is marked
8451 				 * __weak, it defaults to zero value, just like for CONFIG_xxx
8452 				 * externs.
8453 				 */
8454 				pr_warn("extern (kcfg) '%s': unrecognized virtual extern\n", ext->name);
8455 				return -EINVAL;
8456 			}
8457 
8458 			err = set_kcfg_value_num(ext, ext_ptr, value);
8459 			if (err)
8460 				return err;
8461 			pr_debug("extern (kcfg) '%s': set to 0x%llx\n",
8462 				 ext->name, (long long)value);
8463 		} else {
8464 			pr_warn("extern '%s': unrecognized extern kind\n", ext->name);
8465 			return -EINVAL;
8466 		}
8467 	}
8468 	if (need_config && extra_kconfig) {
8469 		err = bpf_object__read_kconfig_mem(obj, extra_kconfig, kcfg_data);
8470 		if (err)
8471 			return -EINVAL;
8472 		need_config = false;
8473 		for (i = 0; i < obj->nr_extern; i++) {
8474 			ext = &obj->externs[i];
8475 			if (ext->type == EXT_KCFG && !ext->is_set) {
8476 				need_config = true;
8477 				break;
8478 			}
8479 		}
8480 	}
8481 	if (need_config) {
8482 		err = bpf_object__read_kconfig_file(obj, kcfg_data);
8483 		if (err)
8484 			return -EINVAL;
8485 	}
8486 	if (need_kallsyms) {
8487 		err = bpf_object__read_kallsyms_file(obj);
8488 		if (err)
8489 			return -EINVAL;
8490 	}
8491 	if (need_vmlinux_btf) {
8492 		err = bpf_object__resolve_ksyms_btf_id(obj);
8493 		if (err)
8494 			return -EINVAL;
8495 	}
8496 	for (i = 0; i < obj->nr_extern; i++) {
8497 		ext = &obj->externs[i];
8498 
8499 		if (!ext->is_set && !ext->is_weak) {
8500 			pr_warn("extern '%s' (strong): not resolved\n", ext->name);
8501 			return -ESRCH;
8502 		} else if (!ext->is_set) {
8503 			pr_debug("extern '%s' (weak): not resolved, defaulting to zero\n",
8504 				 ext->name);
8505 		}
8506 	}
8507 
8508 	return 0;
8509 }
8510 
8511 static void bpf_map_prepare_vdata(const struct bpf_map *map)
8512 {
8513 	const struct btf_type *type;
8514 	struct bpf_struct_ops *st_ops;
8515 	__u32 i;
8516 
8517 	st_ops = map->st_ops;
8518 	type = btf__type_by_id(map->obj->btf, st_ops->type_id);
8519 	for (i = 0; i < btf_vlen(type); i++) {
8520 		struct bpf_program *prog = st_ops->progs[i];
8521 		void *kern_data;
8522 		int prog_fd;
8523 
8524 		if (!prog)
8525 			continue;
8526 
8527 		prog_fd = bpf_program__fd(prog);
8528 		kern_data = st_ops->kern_vdata + st_ops->kern_func_off[i];
8529 		*(unsigned long *)kern_data = prog_fd;
8530 	}
8531 }
8532 
8533 static int bpf_object_prepare_struct_ops(struct bpf_object *obj)
8534 {
8535 	struct bpf_map *map;
8536 	int i;
8537 
8538 	for (i = 0; i < obj->nr_maps; i++) {
8539 		map = &obj->maps[i];
8540 
8541 		if (!bpf_map__is_struct_ops(map))
8542 			continue;
8543 
8544 		if (!map->autocreate)
8545 			continue;
8546 
8547 		bpf_map_prepare_vdata(map);
8548 	}
8549 
8550 	return 0;
8551 }
8552 
8553 static void bpf_object_unpin(struct bpf_object *obj)
8554 {
8555 	int i;
8556 
8557 	/* unpin any maps that were auto-pinned during load */
8558 	for (i = 0; i < obj->nr_maps; i++)
8559 		if (obj->maps[i].pinned && !obj->maps[i].reused)
8560 			bpf_map__unpin(&obj->maps[i], NULL);
8561 }
8562 
8563 static void bpf_object_post_load_cleanup(struct bpf_object *obj)
8564 {
8565 	int i;
8566 
8567 	/* clean up fd_array */
8568 	zfree(&obj->fd_array);
8569 
8570 	/* clean up module BTFs */
8571 	for (i = 0; i < obj->btf_module_cnt; i++) {
8572 		close(obj->btf_modules[i].fd);
8573 		btf__free(obj->btf_modules[i].btf);
8574 		free(obj->btf_modules[i].name);
8575 	}
8576 	obj->btf_module_cnt = 0;
8577 	zfree(&obj->btf_modules);
8578 
8579 	/* clean up vmlinux BTF */
8580 	btf__free(obj->btf_vmlinux);
8581 	obj->btf_vmlinux = NULL;
8582 }
8583 
8584 static int bpf_object_prepare(struct bpf_object *obj, const char *target_btf_path)
8585 {
8586 	int err;
8587 
8588 	if (obj->state >= OBJ_PREPARED) {
8589 		pr_warn("object '%s': prepare loading can't be attempted twice\n", obj->name);
8590 		return -EINVAL;
8591 	}
8592 
8593 	err = bpf_object_prepare_token(obj);
8594 	err = err ? : bpf_object__probe_loading(obj);
8595 	err = err ? : bpf_object__load_vmlinux_btf(obj, false);
8596 	err = err ? : bpf_object__resolve_externs(obj, obj->kconfig);
8597 	err = err ? : bpf_object__sanitize_maps(obj);
8598 	err = err ? : bpf_object__init_kern_struct_ops_maps(obj);
8599 	err = err ? : bpf_object_adjust_struct_ops_autoload(obj);
8600 	err = err ? : bpf_object__relocate(obj, obj->btf_custom_path ? : target_btf_path);
8601 	err = err ? : bpf_object__sanitize_and_load_btf(obj);
8602 	err = err ? : bpf_object__create_maps(obj);
8603 	err = err ? : bpf_object_prepare_progs(obj);
8604 
8605 	if (err) {
8606 		bpf_object_unpin(obj);
8607 		bpf_object_unload(obj);
8608 		obj->state = OBJ_LOADED;
8609 		return err;
8610 	}
8611 
8612 	obj->state = OBJ_PREPARED;
8613 	return 0;
8614 }
8615 
8616 static int bpf_object_load(struct bpf_object *obj, int extra_log_level, const char *target_btf_path)
8617 {
8618 	int err;
8619 
8620 	if (!obj)
8621 		return libbpf_err(-EINVAL);
8622 
8623 	if (obj->state >= OBJ_LOADED) {
8624 		pr_warn("object '%s': load can't be attempted twice\n", obj->name);
8625 		return libbpf_err(-EINVAL);
8626 	}
8627 
8628 	/* Disallow kernel loading programs of non-native endianness but
8629 	 * permit cross-endian creation of "light skeleton".
8630 	 */
8631 	if (obj->gen_loader) {
8632 		bpf_gen__init(obj->gen_loader, extra_log_level, obj->nr_programs, obj->nr_maps);
8633 	} else if (!is_native_endianness(obj)) {
8634 		pr_warn("object '%s': loading non-native endianness is unsupported\n", obj->name);
8635 		return libbpf_err(-LIBBPF_ERRNO__ENDIAN);
8636 	}
8637 
8638 	if (obj->state < OBJ_PREPARED) {
8639 		err = bpf_object_prepare(obj, target_btf_path);
8640 		if (err)
8641 			return libbpf_err(err);
8642 	}
8643 	err = bpf_object__load_progs(obj, extra_log_level);
8644 	err = err ? : bpf_object_init_prog_arrays(obj);
8645 	err = err ? : bpf_object_prepare_struct_ops(obj);
8646 
8647 	if (obj->gen_loader) {
8648 		/* reset FDs */
8649 		if (obj->btf)
8650 			btf__set_fd(obj->btf, -1);
8651 		if (!err)
8652 			err = bpf_gen__finish(obj->gen_loader, obj->nr_programs, obj->nr_maps);
8653 	}
8654 
8655 	bpf_object_post_load_cleanup(obj);
8656 	obj->state = OBJ_LOADED; /* doesn't matter if successfully or not */
8657 
8658 	if (err) {
8659 		bpf_object_unpin(obj);
8660 		bpf_object_unload(obj);
8661 		pr_warn("failed to load object '%s'\n", obj->path);
8662 		return libbpf_err(err);
8663 	}
8664 
8665 	return 0;
8666 }
8667 
8668 int bpf_object__prepare(struct bpf_object *obj)
8669 {
8670 	return libbpf_err(bpf_object_prepare(obj, NULL));
8671 }
8672 
8673 int bpf_object__load(struct bpf_object *obj)
8674 {
8675 	return bpf_object_load(obj, 0, NULL);
8676 }
8677 
8678 static int make_parent_dir(const char *path)
8679 {
8680 	char *dname, *dir;
8681 	int err = 0;
8682 
8683 	dname = strdup(path);
8684 	if (dname == NULL)
8685 		return -ENOMEM;
8686 
8687 	dir = dirname(dname);
8688 	if (mkdir(dir, 0700) && errno != EEXIST)
8689 		err = -errno;
8690 
8691 	free(dname);
8692 	if (err) {
8693 		pr_warn("failed to mkdir %s: %s\n", path, errstr(err));
8694 	}
8695 	return err;
8696 }
8697 
8698 static int check_path(const char *path)
8699 {
8700 	struct statfs st_fs;
8701 	char *dname, *dir;
8702 	int err = 0;
8703 
8704 	if (path == NULL)
8705 		return -EINVAL;
8706 
8707 	dname = strdup(path);
8708 	if (dname == NULL)
8709 		return -ENOMEM;
8710 
8711 	dir = dirname(dname);
8712 	if (statfs(dir, &st_fs)) {
8713 		pr_warn("failed to statfs %s: %s\n", dir, errstr(errno));
8714 		err = -errno;
8715 	}
8716 	free(dname);
8717 
8718 	if (!err && st_fs.f_type != BPF_FS_MAGIC) {
8719 		pr_warn("specified path %s is not on BPF FS\n", path);
8720 		err = -EINVAL;
8721 	}
8722 
8723 	return err;
8724 }
8725 
8726 int bpf_program__pin(struct bpf_program *prog, const char *path)
8727 {
8728 	int err;
8729 
8730 	if (prog->fd < 0) {
8731 		pr_warn("prog '%s': can't pin program that wasn't loaded\n", prog->name);
8732 		return libbpf_err(-EINVAL);
8733 	}
8734 
8735 	err = make_parent_dir(path);
8736 	if (err)
8737 		return libbpf_err(err);
8738 
8739 	err = check_path(path);
8740 	if (err)
8741 		return libbpf_err(err);
8742 
8743 	if (bpf_obj_pin(prog->fd, path)) {
8744 		err = -errno;
8745 		pr_warn("prog '%s': failed to pin at '%s': %s\n", prog->name, path, errstr(err));
8746 		return libbpf_err(err);
8747 	}
8748 
8749 	pr_debug("prog '%s': pinned at '%s'\n", prog->name, path);
8750 	return 0;
8751 }
8752 
8753 int bpf_program__unpin(struct bpf_program *prog, const char *path)
8754 {
8755 	int err;
8756 
8757 	if (prog->fd < 0) {
8758 		pr_warn("prog '%s': can't unpin program that wasn't loaded\n", prog->name);
8759 		return libbpf_err(-EINVAL);
8760 	}
8761 
8762 	err = check_path(path);
8763 	if (err)
8764 		return libbpf_err(err);
8765 
8766 	err = unlink(path);
8767 	if (err)
8768 		return libbpf_err(-errno);
8769 
8770 	pr_debug("prog '%s': unpinned from '%s'\n", prog->name, path);
8771 	return 0;
8772 }
8773 
8774 int bpf_map__pin(struct bpf_map *map, const char *path)
8775 {
8776 	int err;
8777 
8778 	if (map == NULL) {
8779 		pr_warn("invalid map pointer\n");
8780 		return libbpf_err(-EINVAL);
8781 	}
8782 
8783 	if (map->fd < 0) {
8784 		pr_warn("map '%s': can't pin BPF map without FD (was it created?)\n", map->name);
8785 		return libbpf_err(-EINVAL);
8786 	}
8787 
8788 	if (map->pin_path) {
8789 		if (path && strcmp(path, map->pin_path)) {
8790 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
8791 				bpf_map__name(map), map->pin_path, path);
8792 			return libbpf_err(-EINVAL);
8793 		} else if (map->pinned) {
8794 			pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
8795 				 bpf_map__name(map), map->pin_path);
8796 			return 0;
8797 		}
8798 	} else {
8799 		if (!path) {
8800 			pr_warn("missing a path to pin map '%s' at\n",
8801 				bpf_map__name(map));
8802 			return libbpf_err(-EINVAL);
8803 		} else if (map->pinned) {
8804 			pr_warn("map '%s' already pinned\n", bpf_map__name(map));
8805 			return libbpf_err(-EEXIST);
8806 		}
8807 
8808 		map->pin_path = strdup(path);
8809 		if (!map->pin_path) {
8810 			err = -errno;
8811 			goto out_err;
8812 		}
8813 	}
8814 
8815 	err = make_parent_dir(map->pin_path);
8816 	if (err)
8817 		return libbpf_err(err);
8818 
8819 	err = check_path(map->pin_path);
8820 	if (err)
8821 		return libbpf_err(err);
8822 
8823 	if (bpf_obj_pin(map->fd, map->pin_path)) {
8824 		err = -errno;
8825 		goto out_err;
8826 	}
8827 
8828 	map->pinned = true;
8829 	pr_debug("pinned map '%s'\n", map->pin_path);
8830 
8831 	return 0;
8832 
8833 out_err:
8834 	pr_warn("failed to pin map: %s\n", errstr(err));
8835 	return libbpf_err(err);
8836 }
8837 
8838 int bpf_map__unpin(struct bpf_map *map, const char *path)
8839 {
8840 	int err;
8841 
8842 	if (map == NULL) {
8843 		pr_warn("invalid map pointer\n");
8844 		return libbpf_err(-EINVAL);
8845 	}
8846 
8847 	if (map->pin_path) {
8848 		if (path && strcmp(path, map->pin_path)) {
8849 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
8850 				bpf_map__name(map), map->pin_path, path);
8851 			return libbpf_err(-EINVAL);
8852 		}
8853 		path = map->pin_path;
8854 	} else if (!path) {
8855 		pr_warn("no path to unpin map '%s' from\n",
8856 			bpf_map__name(map));
8857 		return libbpf_err(-EINVAL);
8858 	}
8859 
8860 	err = check_path(path);
8861 	if (err)
8862 		return libbpf_err(err);
8863 
8864 	err = unlink(path);
8865 	if (err != 0)
8866 		return libbpf_err(-errno);
8867 
8868 	map->pinned = false;
8869 	pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path);
8870 
8871 	return 0;
8872 }
8873 
8874 int bpf_map__set_pin_path(struct bpf_map *map, const char *path)
8875 {
8876 	char *new = NULL;
8877 
8878 	if (path) {
8879 		new = strdup(path);
8880 		if (!new)
8881 			return libbpf_err(-errno);
8882 	}
8883 
8884 	free(map->pin_path);
8885 	map->pin_path = new;
8886 	return 0;
8887 }
8888 
8889 __alias(bpf_map__pin_path)
8890 const char *bpf_map__get_pin_path(const struct bpf_map *map);
8891 
8892 const char *bpf_map__pin_path(const struct bpf_map *map)
8893 {
8894 	return map->pin_path;
8895 }
8896 
8897 bool bpf_map__is_pinned(const struct bpf_map *map)
8898 {
8899 	return map->pinned;
8900 }
8901 
8902 static void sanitize_pin_path(char *s)
8903 {
8904 	/* bpffs disallows periods in path names */
8905 	while (*s) {
8906 		if (*s == '.')
8907 			*s = '_';
8908 		s++;
8909 	}
8910 }
8911 
8912 int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
8913 {
8914 	struct bpf_map *map;
8915 	int err;
8916 
8917 	if (!obj)
8918 		return libbpf_err(-ENOENT);
8919 
8920 	if (obj->state < OBJ_PREPARED) {
8921 		pr_warn("object not yet loaded; load it first\n");
8922 		return libbpf_err(-ENOENT);
8923 	}
8924 
8925 	bpf_object__for_each_map(map, obj) {
8926 		char *pin_path = NULL;
8927 		char buf[PATH_MAX];
8928 
8929 		if (!map->autocreate)
8930 			continue;
8931 
8932 		if (path) {
8933 			err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
8934 			if (err)
8935 				goto err_unpin_maps;
8936 			sanitize_pin_path(buf);
8937 			pin_path = buf;
8938 		} else if (!map->pin_path) {
8939 			continue;
8940 		}
8941 
8942 		err = bpf_map__pin(map, pin_path);
8943 		if (err)
8944 			goto err_unpin_maps;
8945 	}
8946 
8947 	return 0;
8948 
8949 err_unpin_maps:
8950 	while ((map = bpf_object__prev_map(obj, map))) {
8951 		if (!map->pin_path)
8952 			continue;
8953 
8954 		bpf_map__unpin(map, NULL);
8955 	}
8956 
8957 	return libbpf_err(err);
8958 }
8959 
8960 int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
8961 {
8962 	struct bpf_map *map;
8963 	int err;
8964 
8965 	if (!obj)
8966 		return libbpf_err(-ENOENT);
8967 
8968 	bpf_object__for_each_map(map, obj) {
8969 		char *pin_path = NULL;
8970 		char buf[PATH_MAX];
8971 
8972 		if (path) {
8973 			err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
8974 			if (err)
8975 				return libbpf_err(err);
8976 			sanitize_pin_path(buf);
8977 			pin_path = buf;
8978 		} else if (!map->pin_path) {
8979 			continue;
8980 		}
8981 
8982 		err = bpf_map__unpin(map, pin_path);
8983 		if (err)
8984 			return libbpf_err(err);
8985 	}
8986 
8987 	return 0;
8988 }
8989 
8990 int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
8991 {
8992 	struct bpf_program *prog;
8993 	char buf[PATH_MAX];
8994 	int err;
8995 
8996 	if (!obj)
8997 		return libbpf_err(-ENOENT);
8998 
8999 	if (obj->state < OBJ_LOADED) {
9000 		pr_warn("object not yet loaded; load it first\n");
9001 		return libbpf_err(-ENOENT);
9002 	}
9003 
9004 	bpf_object__for_each_program(prog, obj) {
9005 		err = pathname_concat(buf, sizeof(buf), path, prog->name);
9006 		if (err)
9007 			goto err_unpin_programs;
9008 
9009 		err = bpf_program__pin(prog, buf);
9010 		if (err)
9011 			goto err_unpin_programs;
9012 	}
9013 
9014 	return 0;
9015 
9016 err_unpin_programs:
9017 	while ((prog = bpf_object__prev_program(obj, prog))) {
9018 		if (pathname_concat(buf, sizeof(buf), path, prog->name))
9019 			continue;
9020 
9021 		bpf_program__unpin(prog, buf);
9022 	}
9023 
9024 	return libbpf_err(err);
9025 }
9026 
9027 int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
9028 {
9029 	struct bpf_program *prog;
9030 	int err;
9031 
9032 	if (!obj)
9033 		return libbpf_err(-ENOENT);
9034 
9035 	bpf_object__for_each_program(prog, obj) {
9036 		char buf[PATH_MAX];
9037 
9038 		err = pathname_concat(buf, sizeof(buf), path, prog->name);
9039 		if (err)
9040 			return libbpf_err(err);
9041 
9042 		err = bpf_program__unpin(prog, buf);
9043 		if (err)
9044 			return libbpf_err(err);
9045 	}
9046 
9047 	return 0;
9048 }
9049 
9050 int bpf_object__pin(struct bpf_object *obj, const char *path)
9051 {
9052 	int err;
9053 
9054 	err = bpf_object__pin_maps(obj, path);
9055 	if (err)
9056 		return libbpf_err(err);
9057 
9058 	err = bpf_object__pin_programs(obj, path);
9059 	if (err) {
9060 		bpf_object__unpin_maps(obj, path);
9061 		return libbpf_err(err);
9062 	}
9063 
9064 	return 0;
9065 }
9066 
9067 int bpf_object__unpin(struct bpf_object *obj, const char *path)
9068 {
9069 	int err;
9070 
9071 	err = bpf_object__unpin_programs(obj, path);
9072 	if (err)
9073 		return libbpf_err(err);
9074 
9075 	err = bpf_object__unpin_maps(obj, path);
9076 	if (err)
9077 		return libbpf_err(err);
9078 
9079 	return 0;
9080 }
9081 
9082 static void bpf_map__destroy(struct bpf_map *map)
9083 {
9084 	if (map->inner_map) {
9085 		bpf_map__destroy(map->inner_map);
9086 		zfree(&map->inner_map);
9087 	}
9088 
9089 	zfree(&map->init_slots);
9090 	map->init_slots_sz = 0;
9091 
9092 	if (map->mmaped && map->mmaped != map->obj->arena_data)
9093 		munmap(map->mmaped, bpf_map_mmap_sz(map));
9094 	map->mmaped = NULL;
9095 
9096 	if (map->st_ops) {
9097 		zfree(&map->st_ops->data);
9098 		zfree(&map->st_ops->progs);
9099 		zfree(&map->st_ops->kern_func_off);
9100 		zfree(&map->st_ops);
9101 	}
9102 
9103 	zfree(&map->name);
9104 	zfree(&map->real_name);
9105 	zfree(&map->pin_path);
9106 
9107 	if (map->fd >= 0)
9108 		zclose(map->fd);
9109 }
9110 
9111 void bpf_object__close(struct bpf_object *obj)
9112 {
9113 	size_t i;
9114 
9115 	if (IS_ERR_OR_NULL(obj))
9116 		return;
9117 
9118 	/*
9119 	 * if user called bpf_object__prepare() without ever getting to
9120 	 * bpf_object__load(), we need to clean up stuff that is normally
9121 	 * cleaned up at the end of loading step
9122 	 */
9123 	bpf_object_post_load_cleanup(obj);
9124 
9125 	usdt_manager_free(obj->usdt_man);
9126 	obj->usdt_man = NULL;
9127 
9128 	bpf_gen__free(obj->gen_loader);
9129 	bpf_object__elf_finish(obj);
9130 	bpf_object_unload(obj);
9131 	btf__free(obj->btf);
9132 	btf__free(obj->btf_vmlinux);
9133 	btf_ext__free(obj->btf_ext);
9134 
9135 	for (i = 0; i < obj->nr_maps; i++)
9136 		bpf_map__destroy(&obj->maps[i]);
9137 
9138 	zfree(&obj->btf_custom_path);
9139 	zfree(&obj->kconfig);
9140 
9141 	for (i = 0; i < obj->nr_extern; i++)
9142 		zfree(&obj->externs[i].essent_name);
9143 
9144 	zfree(&obj->externs);
9145 	obj->nr_extern = 0;
9146 
9147 	zfree(&obj->maps);
9148 	obj->nr_maps = 0;
9149 
9150 	if (obj->programs && obj->nr_programs) {
9151 		for (i = 0; i < obj->nr_programs; i++)
9152 			bpf_program__exit(&obj->programs[i]);
9153 	}
9154 	zfree(&obj->programs);
9155 
9156 	zfree(&obj->feat_cache);
9157 	zfree(&obj->token_path);
9158 	if (obj->token_fd > 0)
9159 		close(obj->token_fd);
9160 
9161 	zfree(&obj->arena_data);
9162 
9163 	free(obj);
9164 }
9165 
9166 const char *bpf_object__name(const struct bpf_object *obj)
9167 {
9168 	return obj ? obj->name : libbpf_err_ptr(-EINVAL);
9169 }
9170 
9171 unsigned int bpf_object__kversion(const struct bpf_object *obj)
9172 {
9173 	return obj ? obj->kern_version : 0;
9174 }
9175 
9176 int bpf_object__token_fd(const struct bpf_object *obj)
9177 {
9178 	return obj->token_fd ?: -1;
9179 }
9180 
9181 struct btf *bpf_object__btf(const struct bpf_object *obj)
9182 {
9183 	return obj ? obj->btf : NULL;
9184 }
9185 
9186 int bpf_object__btf_fd(const struct bpf_object *obj)
9187 {
9188 	return obj->btf ? btf__fd(obj->btf) : -1;
9189 }
9190 
9191 int bpf_object__set_kversion(struct bpf_object *obj, __u32 kern_version)
9192 {
9193 	if (obj->state >= OBJ_LOADED)
9194 		return libbpf_err(-EINVAL);
9195 
9196 	obj->kern_version = kern_version;
9197 
9198 	return 0;
9199 }
9200 
9201 int bpf_object__gen_loader(struct bpf_object *obj, struct gen_loader_opts *opts)
9202 {
9203 	struct bpf_gen *gen;
9204 
9205 	if (!opts)
9206 		return libbpf_err(-EFAULT);
9207 	if (!OPTS_VALID(opts, gen_loader_opts))
9208 		return libbpf_err(-EINVAL);
9209 	gen = calloc(sizeof(*gen), 1);
9210 	if (!gen)
9211 		return libbpf_err(-ENOMEM);
9212 	gen->opts = opts;
9213 	gen->swapped_endian = !is_native_endianness(obj);
9214 	obj->gen_loader = gen;
9215 	return 0;
9216 }
9217 
9218 static struct bpf_program *
9219 __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
9220 		    bool forward)
9221 {
9222 	size_t nr_programs = obj->nr_programs;
9223 	ssize_t idx;
9224 
9225 	if (!nr_programs)
9226 		return NULL;
9227 
9228 	if (!p)
9229 		/* Iter from the beginning */
9230 		return forward ? &obj->programs[0] :
9231 			&obj->programs[nr_programs - 1];
9232 
9233 	if (p->obj != obj) {
9234 		pr_warn("error: program handler doesn't match object\n");
9235 		return errno = EINVAL, NULL;
9236 	}
9237 
9238 	idx = (p - obj->programs) + (forward ? 1 : -1);
9239 	if (idx >= obj->nr_programs || idx < 0)
9240 		return NULL;
9241 	return &obj->programs[idx];
9242 }
9243 
9244 struct bpf_program *
9245 bpf_object__next_program(const struct bpf_object *obj, struct bpf_program *prev)
9246 {
9247 	struct bpf_program *prog = prev;
9248 
9249 	do {
9250 		prog = __bpf_program__iter(prog, obj, true);
9251 	} while (prog && prog_is_subprog(obj, prog));
9252 
9253 	return prog;
9254 }
9255 
9256 struct bpf_program *
9257 bpf_object__prev_program(const struct bpf_object *obj, struct bpf_program *next)
9258 {
9259 	struct bpf_program *prog = next;
9260 
9261 	do {
9262 		prog = __bpf_program__iter(prog, obj, false);
9263 	} while (prog && prog_is_subprog(obj, prog));
9264 
9265 	return prog;
9266 }
9267 
9268 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
9269 {
9270 	prog->prog_ifindex = ifindex;
9271 }
9272 
9273 const char *bpf_program__name(const struct bpf_program *prog)
9274 {
9275 	return prog->name;
9276 }
9277 
9278 const char *bpf_program__section_name(const struct bpf_program *prog)
9279 {
9280 	return prog->sec_name;
9281 }
9282 
9283 bool bpf_program__autoload(const struct bpf_program *prog)
9284 {
9285 	return prog->autoload;
9286 }
9287 
9288 int bpf_program__set_autoload(struct bpf_program *prog, bool autoload)
9289 {
9290 	if (prog->obj->state >= OBJ_LOADED)
9291 		return libbpf_err(-EINVAL);
9292 
9293 	prog->autoload = autoload;
9294 	return 0;
9295 }
9296 
9297 bool bpf_program__autoattach(const struct bpf_program *prog)
9298 {
9299 	return prog->autoattach;
9300 }
9301 
9302 void bpf_program__set_autoattach(struct bpf_program *prog, bool autoattach)
9303 {
9304 	prog->autoattach = autoattach;
9305 }
9306 
9307 const struct bpf_insn *bpf_program__insns(const struct bpf_program *prog)
9308 {
9309 	return prog->insns;
9310 }
9311 
9312 size_t bpf_program__insn_cnt(const struct bpf_program *prog)
9313 {
9314 	return prog->insns_cnt;
9315 }
9316 
9317 int bpf_program__set_insns(struct bpf_program *prog,
9318 			   struct bpf_insn *new_insns, size_t new_insn_cnt)
9319 {
9320 	struct bpf_insn *insns;
9321 
9322 	if (prog->obj->state >= OBJ_LOADED)
9323 		return libbpf_err(-EBUSY);
9324 
9325 	insns = libbpf_reallocarray(prog->insns, new_insn_cnt, sizeof(*insns));
9326 	/* NULL is a valid return from reallocarray if the new count is zero */
9327 	if (!insns && new_insn_cnt) {
9328 		pr_warn("prog '%s': failed to realloc prog code\n", prog->name);
9329 		return libbpf_err(-ENOMEM);
9330 	}
9331 	memcpy(insns, new_insns, new_insn_cnt * sizeof(*insns));
9332 
9333 	prog->insns = insns;
9334 	prog->insns_cnt = new_insn_cnt;
9335 	return 0;
9336 }
9337 
9338 int bpf_program__fd(const struct bpf_program *prog)
9339 {
9340 	if (!prog)
9341 		return libbpf_err(-EINVAL);
9342 
9343 	if (prog->fd < 0)
9344 		return libbpf_err(-ENOENT);
9345 
9346 	return prog->fd;
9347 }
9348 
9349 __alias(bpf_program__type)
9350 enum bpf_prog_type bpf_program__get_type(const struct bpf_program *prog);
9351 
9352 enum bpf_prog_type bpf_program__type(const struct bpf_program *prog)
9353 {
9354 	return prog->type;
9355 }
9356 
9357 static size_t custom_sec_def_cnt;
9358 static struct bpf_sec_def *custom_sec_defs;
9359 static struct bpf_sec_def custom_fallback_def;
9360 static bool has_custom_fallback_def;
9361 static int last_custom_sec_def_handler_id;
9362 
9363 int bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
9364 {
9365 	if (prog->obj->state >= OBJ_LOADED)
9366 		return libbpf_err(-EBUSY);
9367 
9368 	/* if type is not changed, do nothing */
9369 	if (prog->type == type)
9370 		return 0;
9371 
9372 	prog->type = type;
9373 
9374 	/* If a program type was changed, we need to reset associated SEC()
9375 	 * handler, as it will be invalid now. The only exception is a generic
9376 	 * fallback handler, which by definition is program type-agnostic and
9377 	 * is a catch-all custom handler, optionally set by the application,
9378 	 * so should be able to handle any type of BPF program.
9379 	 */
9380 	if (prog->sec_def != &custom_fallback_def)
9381 		prog->sec_def = NULL;
9382 	return 0;
9383 }
9384 
9385 __alias(bpf_program__expected_attach_type)
9386 enum bpf_attach_type bpf_program__get_expected_attach_type(const struct bpf_program *prog);
9387 
9388 enum bpf_attach_type bpf_program__expected_attach_type(const struct bpf_program *prog)
9389 {
9390 	return prog->expected_attach_type;
9391 }
9392 
9393 int bpf_program__set_expected_attach_type(struct bpf_program *prog,
9394 					   enum bpf_attach_type type)
9395 {
9396 	if (prog->obj->state >= OBJ_LOADED)
9397 		return libbpf_err(-EBUSY);
9398 
9399 	prog->expected_attach_type = type;
9400 	return 0;
9401 }
9402 
9403 __u32 bpf_program__flags(const struct bpf_program *prog)
9404 {
9405 	return prog->prog_flags;
9406 }
9407 
9408 int bpf_program__set_flags(struct bpf_program *prog, __u32 flags)
9409 {
9410 	if (prog->obj->state >= OBJ_LOADED)
9411 		return libbpf_err(-EBUSY);
9412 
9413 	prog->prog_flags = flags;
9414 	return 0;
9415 }
9416 
9417 __u32 bpf_program__log_level(const struct bpf_program *prog)
9418 {
9419 	return prog->log_level;
9420 }
9421 
9422 int bpf_program__set_log_level(struct bpf_program *prog, __u32 log_level)
9423 {
9424 	if (prog->obj->state >= OBJ_LOADED)
9425 		return libbpf_err(-EBUSY);
9426 
9427 	prog->log_level = log_level;
9428 	return 0;
9429 }
9430 
9431 const char *bpf_program__log_buf(const struct bpf_program *prog, size_t *log_size)
9432 {
9433 	*log_size = prog->log_size;
9434 	return prog->log_buf;
9435 }
9436 
9437 int bpf_program__set_log_buf(struct bpf_program *prog, char *log_buf, size_t log_size)
9438 {
9439 	if (log_size && !log_buf)
9440 		return libbpf_err(-EINVAL);
9441 	if (prog->log_size > UINT_MAX)
9442 		return libbpf_err(-EINVAL);
9443 	if (prog->obj->state >= OBJ_LOADED)
9444 		return libbpf_err(-EBUSY);
9445 
9446 	prog->log_buf = log_buf;
9447 	prog->log_size = log_size;
9448 	return 0;
9449 }
9450 
9451 struct bpf_func_info *bpf_program__func_info(const struct bpf_program *prog)
9452 {
9453 	if (prog->func_info_rec_size != sizeof(struct bpf_func_info))
9454 		return libbpf_err_ptr(-EOPNOTSUPP);
9455 	return prog->func_info;
9456 }
9457 
9458 __u32 bpf_program__func_info_cnt(const struct bpf_program *prog)
9459 {
9460 	return prog->func_info_cnt;
9461 }
9462 
9463 struct bpf_line_info *bpf_program__line_info(const struct bpf_program *prog)
9464 {
9465 	if (prog->line_info_rec_size != sizeof(struct bpf_line_info))
9466 		return libbpf_err_ptr(-EOPNOTSUPP);
9467 	return prog->line_info;
9468 }
9469 
9470 __u32 bpf_program__line_info_cnt(const struct bpf_program *prog)
9471 {
9472 	return prog->line_info_cnt;
9473 }
9474 
9475 #define SEC_DEF(sec_pfx, ptype, atype, flags, ...) {			    \
9476 	.sec = (char *)sec_pfx,						    \
9477 	.prog_type = BPF_PROG_TYPE_##ptype,				    \
9478 	.expected_attach_type = atype,					    \
9479 	.cookie = (long)(flags),					    \
9480 	.prog_prepare_load_fn = libbpf_prepare_prog_load,		    \
9481 	__VA_ARGS__							    \
9482 }
9483 
9484 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9485 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9486 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9487 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9488 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9489 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9490 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9491 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9492 static int attach_kprobe_session(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9493 static int attach_uprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9494 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9495 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9496 
9497 static const struct bpf_sec_def section_defs[] = {
9498 	SEC_DEF("socket",		SOCKET_FILTER, 0, SEC_NONE),
9499 	SEC_DEF("sk_reuseport/migrate",	SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT_OR_MIGRATE, SEC_ATTACHABLE),
9500 	SEC_DEF("sk_reuseport",		SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT, SEC_ATTACHABLE),
9501 	SEC_DEF("kprobe+",		KPROBE,	0, SEC_NONE, attach_kprobe),
9502 	SEC_DEF("uprobe+",		KPROBE,	0, SEC_NONE, attach_uprobe),
9503 	SEC_DEF("uprobe.s+",		KPROBE,	0, SEC_SLEEPABLE, attach_uprobe),
9504 	SEC_DEF("kretprobe+",		KPROBE, 0, SEC_NONE, attach_kprobe),
9505 	SEC_DEF("uretprobe+",		KPROBE, 0, SEC_NONE, attach_uprobe),
9506 	SEC_DEF("uretprobe.s+",		KPROBE, 0, SEC_SLEEPABLE, attach_uprobe),
9507 	SEC_DEF("kprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
9508 	SEC_DEF("kretprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
9509 	SEC_DEF("kprobe.session+",	KPROBE,	BPF_TRACE_KPROBE_SESSION, SEC_NONE, attach_kprobe_session),
9510 	SEC_DEF("uprobe.multi+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_NONE, attach_uprobe_multi),
9511 	SEC_DEF("uretprobe.multi+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_NONE, attach_uprobe_multi),
9512 	SEC_DEF("uprobe.session+",	KPROBE,	BPF_TRACE_UPROBE_SESSION, SEC_NONE, attach_uprobe_multi),
9513 	SEC_DEF("uprobe.multi.s+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_SLEEPABLE, attach_uprobe_multi),
9514 	SEC_DEF("uretprobe.multi.s+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_SLEEPABLE, attach_uprobe_multi),
9515 	SEC_DEF("uprobe.session.s+",	KPROBE,	BPF_TRACE_UPROBE_SESSION, SEC_SLEEPABLE, attach_uprobe_multi),
9516 	SEC_DEF("ksyscall+",		KPROBE,	0, SEC_NONE, attach_ksyscall),
9517 	SEC_DEF("kretsyscall+",		KPROBE, 0, SEC_NONE, attach_ksyscall),
9518 	SEC_DEF("usdt+",		KPROBE,	0, SEC_USDT, attach_usdt),
9519 	SEC_DEF("usdt.s+",		KPROBE,	0, SEC_USDT | SEC_SLEEPABLE, attach_usdt),
9520 	SEC_DEF("tc/ingress",		SCHED_CLS, BPF_TCX_INGRESS, SEC_NONE), /* alias for tcx */
9521 	SEC_DEF("tc/egress",		SCHED_CLS, BPF_TCX_EGRESS, SEC_NONE),  /* alias for tcx */
9522 	SEC_DEF("tcx/ingress",		SCHED_CLS, BPF_TCX_INGRESS, SEC_NONE),
9523 	SEC_DEF("tcx/egress",		SCHED_CLS, BPF_TCX_EGRESS, SEC_NONE),
9524 	SEC_DEF("tc",			SCHED_CLS, 0, SEC_NONE), /* deprecated / legacy, use tcx */
9525 	SEC_DEF("classifier",		SCHED_CLS, 0, SEC_NONE), /* deprecated / legacy, use tcx */
9526 	SEC_DEF("action",		SCHED_ACT, 0, SEC_NONE), /* deprecated / legacy, use tcx */
9527 	SEC_DEF("netkit/primary",	SCHED_CLS, BPF_NETKIT_PRIMARY, SEC_NONE),
9528 	SEC_DEF("netkit/peer",		SCHED_CLS, BPF_NETKIT_PEER, SEC_NONE),
9529 	SEC_DEF("tracepoint+",		TRACEPOINT, 0, SEC_NONE, attach_tp),
9530 	SEC_DEF("tp+",			TRACEPOINT, 0, SEC_NONE, attach_tp),
9531 	SEC_DEF("raw_tracepoint+",	RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
9532 	SEC_DEF("raw_tp+",		RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
9533 	SEC_DEF("raw_tracepoint.w+",	RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
9534 	SEC_DEF("raw_tp.w+",		RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
9535 	SEC_DEF("tp_btf+",		TRACING, BPF_TRACE_RAW_TP, SEC_ATTACH_BTF, attach_trace),
9536 	SEC_DEF("fentry+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF, attach_trace),
9537 	SEC_DEF("fmod_ret+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF, attach_trace),
9538 	SEC_DEF("fexit+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF, attach_trace),
9539 	SEC_DEF("fentry.s+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
9540 	SEC_DEF("fmod_ret.s+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
9541 	SEC_DEF("fexit.s+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
9542 	SEC_DEF("freplace+",		EXT, 0, SEC_ATTACH_BTF, attach_trace),
9543 	SEC_DEF("lsm+",			LSM, BPF_LSM_MAC, SEC_ATTACH_BTF, attach_lsm),
9544 	SEC_DEF("lsm.s+",		LSM, BPF_LSM_MAC, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_lsm),
9545 	SEC_DEF("lsm_cgroup+",		LSM, BPF_LSM_CGROUP, SEC_ATTACH_BTF),
9546 	SEC_DEF("iter+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF, attach_iter),
9547 	SEC_DEF("iter.s+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_iter),
9548 	SEC_DEF("syscall",		SYSCALL, 0, SEC_SLEEPABLE),
9549 	SEC_DEF("xdp.frags/devmap",	XDP, BPF_XDP_DEVMAP, SEC_XDP_FRAGS),
9550 	SEC_DEF("xdp/devmap",		XDP, BPF_XDP_DEVMAP, SEC_ATTACHABLE),
9551 	SEC_DEF("xdp.frags/cpumap",	XDP, BPF_XDP_CPUMAP, SEC_XDP_FRAGS),
9552 	SEC_DEF("xdp/cpumap",		XDP, BPF_XDP_CPUMAP, SEC_ATTACHABLE),
9553 	SEC_DEF("xdp.frags",		XDP, BPF_XDP, SEC_XDP_FRAGS),
9554 	SEC_DEF("xdp",			XDP, BPF_XDP, SEC_ATTACHABLE_OPT),
9555 	SEC_DEF("perf_event",		PERF_EVENT, 0, SEC_NONE),
9556 	SEC_DEF("lwt_in",		LWT_IN, 0, SEC_NONE),
9557 	SEC_DEF("lwt_out",		LWT_OUT, 0, SEC_NONE),
9558 	SEC_DEF("lwt_xmit",		LWT_XMIT, 0, SEC_NONE),
9559 	SEC_DEF("lwt_seg6local",	LWT_SEG6LOCAL, 0, SEC_NONE),
9560 	SEC_DEF("sockops",		SOCK_OPS, BPF_CGROUP_SOCK_OPS, SEC_ATTACHABLE_OPT),
9561 	SEC_DEF("sk_skb/stream_parser",	SK_SKB, BPF_SK_SKB_STREAM_PARSER, SEC_ATTACHABLE_OPT),
9562 	SEC_DEF("sk_skb/stream_verdict",SK_SKB, BPF_SK_SKB_STREAM_VERDICT, SEC_ATTACHABLE_OPT),
9563 	SEC_DEF("sk_skb/verdict",	SK_SKB, BPF_SK_SKB_VERDICT, SEC_ATTACHABLE_OPT),
9564 	SEC_DEF("sk_skb",		SK_SKB, 0, SEC_NONE),
9565 	SEC_DEF("sk_msg",		SK_MSG, BPF_SK_MSG_VERDICT, SEC_ATTACHABLE_OPT),
9566 	SEC_DEF("lirc_mode2",		LIRC_MODE2, BPF_LIRC_MODE2, SEC_ATTACHABLE_OPT),
9567 	SEC_DEF("flow_dissector",	FLOW_DISSECTOR, BPF_FLOW_DISSECTOR, SEC_ATTACHABLE_OPT),
9568 	SEC_DEF("cgroup_skb/ingress",	CGROUP_SKB, BPF_CGROUP_INET_INGRESS, SEC_ATTACHABLE_OPT),
9569 	SEC_DEF("cgroup_skb/egress",	CGROUP_SKB, BPF_CGROUP_INET_EGRESS, SEC_ATTACHABLE_OPT),
9570 	SEC_DEF("cgroup/skb",		CGROUP_SKB, 0, SEC_NONE),
9571 	SEC_DEF("cgroup/sock_create",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE),
9572 	SEC_DEF("cgroup/sock_release",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_RELEASE, SEC_ATTACHABLE),
9573 	SEC_DEF("cgroup/sock",		CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE_OPT),
9574 	SEC_DEF("cgroup/post_bind4",	CGROUP_SOCK, BPF_CGROUP_INET4_POST_BIND, SEC_ATTACHABLE),
9575 	SEC_DEF("cgroup/post_bind6",	CGROUP_SOCK, BPF_CGROUP_INET6_POST_BIND, SEC_ATTACHABLE),
9576 	SEC_DEF("cgroup/bind4",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND, SEC_ATTACHABLE),
9577 	SEC_DEF("cgroup/bind6",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND, SEC_ATTACHABLE),
9578 	SEC_DEF("cgroup/connect4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT, SEC_ATTACHABLE),
9579 	SEC_DEF("cgroup/connect6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT, SEC_ATTACHABLE),
9580 	SEC_DEF("cgroup/connect_unix",	CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_CONNECT, SEC_ATTACHABLE),
9581 	SEC_DEF("cgroup/sendmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG, SEC_ATTACHABLE),
9582 	SEC_DEF("cgroup/sendmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG, SEC_ATTACHABLE),
9583 	SEC_DEF("cgroup/sendmsg_unix",	CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_SENDMSG, SEC_ATTACHABLE),
9584 	SEC_DEF("cgroup/recvmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_RECVMSG, SEC_ATTACHABLE),
9585 	SEC_DEF("cgroup/recvmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_RECVMSG, SEC_ATTACHABLE),
9586 	SEC_DEF("cgroup/recvmsg_unix",	CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_RECVMSG, SEC_ATTACHABLE),
9587 	SEC_DEF("cgroup/getpeername4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETPEERNAME, SEC_ATTACHABLE),
9588 	SEC_DEF("cgroup/getpeername6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETPEERNAME, SEC_ATTACHABLE),
9589 	SEC_DEF("cgroup/getpeername_unix", CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_GETPEERNAME, SEC_ATTACHABLE),
9590 	SEC_DEF("cgroup/getsockname4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETSOCKNAME, SEC_ATTACHABLE),
9591 	SEC_DEF("cgroup/getsockname6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETSOCKNAME, SEC_ATTACHABLE),
9592 	SEC_DEF("cgroup/getsockname_unix", CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_GETSOCKNAME, SEC_ATTACHABLE),
9593 	SEC_DEF("cgroup/sysctl",	CGROUP_SYSCTL, BPF_CGROUP_SYSCTL, SEC_ATTACHABLE),
9594 	SEC_DEF("cgroup/getsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_GETSOCKOPT, SEC_ATTACHABLE),
9595 	SEC_DEF("cgroup/setsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_SETSOCKOPT, SEC_ATTACHABLE),
9596 	SEC_DEF("cgroup/dev",		CGROUP_DEVICE, BPF_CGROUP_DEVICE, SEC_ATTACHABLE_OPT),
9597 	SEC_DEF("struct_ops+",		STRUCT_OPS, 0, SEC_NONE),
9598 	SEC_DEF("struct_ops.s+",	STRUCT_OPS, 0, SEC_SLEEPABLE),
9599 	SEC_DEF("sk_lookup",		SK_LOOKUP, BPF_SK_LOOKUP, SEC_ATTACHABLE),
9600 	SEC_DEF("netfilter",		NETFILTER, BPF_NETFILTER, SEC_NONE),
9601 };
9602 
9603 int libbpf_register_prog_handler(const char *sec,
9604 				 enum bpf_prog_type prog_type,
9605 				 enum bpf_attach_type exp_attach_type,
9606 				 const struct libbpf_prog_handler_opts *opts)
9607 {
9608 	struct bpf_sec_def *sec_def;
9609 
9610 	if (!OPTS_VALID(opts, libbpf_prog_handler_opts))
9611 		return libbpf_err(-EINVAL);
9612 
9613 	if (last_custom_sec_def_handler_id == INT_MAX) /* prevent overflow */
9614 		return libbpf_err(-E2BIG);
9615 
9616 	if (sec) {
9617 		sec_def = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt + 1,
9618 					      sizeof(*sec_def));
9619 		if (!sec_def)
9620 			return libbpf_err(-ENOMEM);
9621 
9622 		custom_sec_defs = sec_def;
9623 		sec_def = &custom_sec_defs[custom_sec_def_cnt];
9624 	} else {
9625 		if (has_custom_fallback_def)
9626 			return libbpf_err(-EBUSY);
9627 
9628 		sec_def = &custom_fallback_def;
9629 	}
9630 
9631 	sec_def->sec = sec ? strdup(sec) : NULL;
9632 	if (sec && !sec_def->sec)
9633 		return libbpf_err(-ENOMEM);
9634 
9635 	sec_def->prog_type = prog_type;
9636 	sec_def->expected_attach_type = exp_attach_type;
9637 	sec_def->cookie = OPTS_GET(opts, cookie, 0);
9638 
9639 	sec_def->prog_setup_fn = OPTS_GET(opts, prog_setup_fn, NULL);
9640 	sec_def->prog_prepare_load_fn = OPTS_GET(opts, prog_prepare_load_fn, NULL);
9641 	sec_def->prog_attach_fn = OPTS_GET(opts, prog_attach_fn, NULL);
9642 
9643 	sec_def->handler_id = ++last_custom_sec_def_handler_id;
9644 
9645 	if (sec)
9646 		custom_sec_def_cnt++;
9647 	else
9648 		has_custom_fallback_def = true;
9649 
9650 	return sec_def->handler_id;
9651 }
9652 
9653 int libbpf_unregister_prog_handler(int handler_id)
9654 {
9655 	struct bpf_sec_def *sec_defs;
9656 	int i;
9657 
9658 	if (handler_id <= 0)
9659 		return libbpf_err(-EINVAL);
9660 
9661 	if (has_custom_fallback_def && custom_fallback_def.handler_id == handler_id) {
9662 		memset(&custom_fallback_def, 0, sizeof(custom_fallback_def));
9663 		has_custom_fallback_def = false;
9664 		return 0;
9665 	}
9666 
9667 	for (i = 0; i < custom_sec_def_cnt; i++) {
9668 		if (custom_sec_defs[i].handler_id == handler_id)
9669 			break;
9670 	}
9671 
9672 	if (i == custom_sec_def_cnt)
9673 		return libbpf_err(-ENOENT);
9674 
9675 	free(custom_sec_defs[i].sec);
9676 	for (i = i + 1; i < custom_sec_def_cnt; i++)
9677 		custom_sec_defs[i - 1] = custom_sec_defs[i];
9678 	custom_sec_def_cnt--;
9679 
9680 	/* try to shrink the array, but it's ok if we couldn't */
9681 	sec_defs = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt, sizeof(*sec_defs));
9682 	/* if new count is zero, reallocarray can return a valid NULL result;
9683 	 * in this case the previous pointer will be freed, so we *have to*
9684 	 * reassign old pointer to the new value (even if it's NULL)
9685 	 */
9686 	if (sec_defs || custom_sec_def_cnt == 0)
9687 		custom_sec_defs = sec_defs;
9688 
9689 	return 0;
9690 }
9691 
9692 static bool sec_def_matches(const struct bpf_sec_def *sec_def, const char *sec_name)
9693 {
9694 	size_t len = strlen(sec_def->sec);
9695 
9696 	/* "type/" always has to have proper SEC("type/extras") form */
9697 	if (sec_def->sec[len - 1] == '/') {
9698 		if (str_has_pfx(sec_name, sec_def->sec))
9699 			return true;
9700 		return false;
9701 	}
9702 
9703 	/* "type+" means it can be either exact SEC("type") or
9704 	 * well-formed SEC("type/extras") with proper '/' separator
9705 	 */
9706 	if (sec_def->sec[len - 1] == '+') {
9707 		len--;
9708 		/* not even a prefix */
9709 		if (strncmp(sec_name, sec_def->sec, len) != 0)
9710 			return false;
9711 		/* exact match or has '/' separator */
9712 		if (sec_name[len] == '\0' || sec_name[len] == '/')
9713 			return true;
9714 		return false;
9715 	}
9716 
9717 	return strcmp(sec_name, sec_def->sec) == 0;
9718 }
9719 
9720 static const struct bpf_sec_def *find_sec_def(const char *sec_name)
9721 {
9722 	const struct bpf_sec_def *sec_def;
9723 	int i, n;
9724 
9725 	n = custom_sec_def_cnt;
9726 	for (i = 0; i < n; i++) {
9727 		sec_def = &custom_sec_defs[i];
9728 		if (sec_def_matches(sec_def, sec_name))
9729 			return sec_def;
9730 	}
9731 
9732 	n = ARRAY_SIZE(section_defs);
9733 	for (i = 0; i < n; i++) {
9734 		sec_def = &section_defs[i];
9735 		if (sec_def_matches(sec_def, sec_name))
9736 			return sec_def;
9737 	}
9738 
9739 	if (has_custom_fallback_def)
9740 		return &custom_fallback_def;
9741 
9742 	return NULL;
9743 }
9744 
9745 #define MAX_TYPE_NAME_SIZE 32
9746 
9747 static char *libbpf_get_type_names(bool attach_type)
9748 {
9749 	int i, len = ARRAY_SIZE(section_defs) * MAX_TYPE_NAME_SIZE;
9750 	char *buf;
9751 
9752 	buf = malloc(len);
9753 	if (!buf)
9754 		return NULL;
9755 
9756 	buf[0] = '\0';
9757 	/* Forge string buf with all available names */
9758 	for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
9759 		const struct bpf_sec_def *sec_def = &section_defs[i];
9760 
9761 		if (attach_type) {
9762 			if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
9763 				continue;
9764 
9765 			if (!(sec_def->cookie & SEC_ATTACHABLE))
9766 				continue;
9767 		}
9768 
9769 		if (strlen(buf) + strlen(section_defs[i].sec) + 2 > len) {
9770 			free(buf);
9771 			return NULL;
9772 		}
9773 		strcat(buf, " ");
9774 		strcat(buf, section_defs[i].sec);
9775 	}
9776 
9777 	return buf;
9778 }
9779 
9780 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
9781 			     enum bpf_attach_type *expected_attach_type)
9782 {
9783 	const struct bpf_sec_def *sec_def;
9784 	char *type_names;
9785 
9786 	if (!name)
9787 		return libbpf_err(-EINVAL);
9788 
9789 	sec_def = find_sec_def(name);
9790 	if (sec_def) {
9791 		*prog_type = sec_def->prog_type;
9792 		*expected_attach_type = sec_def->expected_attach_type;
9793 		return 0;
9794 	}
9795 
9796 	pr_debug("failed to guess program type from ELF section '%s'\n", name);
9797 	type_names = libbpf_get_type_names(false);
9798 	if (type_names != NULL) {
9799 		pr_debug("supported section(type) names are:%s\n", type_names);
9800 		free(type_names);
9801 	}
9802 
9803 	return libbpf_err(-ESRCH);
9804 }
9805 
9806 const char *libbpf_bpf_attach_type_str(enum bpf_attach_type t)
9807 {
9808 	if (t < 0 || t >= ARRAY_SIZE(attach_type_name))
9809 		return NULL;
9810 
9811 	return attach_type_name[t];
9812 }
9813 
9814 const char *libbpf_bpf_link_type_str(enum bpf_link_type t)
9815 {
9816 	if (t < 0 || t >= ARRAY_SIZE(link_type_name))
9817 		return NULL;
9818 
9819 	return link_type_name[t];
9820 }
9821 
9822 const char *libbpf_bpf_map_type_str(enum bpf_map_type t)
9823 {
9824 	if (t < 0 || t >= ARRAY_SIZE(map_type_name))
9825 		return NULL;
9826 
9827 	return map_type_name[t];
9828 }
9829 
9830 const char *libbpf_bpf_prog_type_str(enum bpf_prog_type t)
9831 {
9832 	if (t < 0 || t >= ARRAY_SIZE(prog_type_name))
9833 		return NULL;
9834 
9835 	return prog_type_name[t];
9836 }
9837 
9838 static struct bpf_map *find_struct_ops_map_by_offset(struct bpf_object *obj,
9839 						     int sec_idx,
9840 						     size_t offset)
9841 {
9842 	struct bpf_map *map;
9843 	size_t i;
9844 
9845 	for (i = 0; i < obj->nr_maps; i++) {
9846 		map = &obj->maps[i];
9847 		if (!bpf_map__is_struct_ops(map))
9848 			continue;
9849 		if (map->sec_idx == sec_idx &&
9850 		    map->sec_offset <= offset &&
9851 		    offset - map->sec_offset < map->def.value_size)
9852 			return map;
9853 	}
9854 
9855 	return NULL;
9856 }
9857 
9858 /* Collect the reloc from ELF, populate the st_ops->progs[], and update
9859  * st_ops->data for shadow type.
9860  */
9861 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
9862 					    Elf64_Shdr *shdr, Elf_Data *data)
9863 {
9864 	const struct btf_type *type;
9865 	const struct btf_member *member;
9866 	struct bpf_struct_ops *st_ops;
9867 	struct bpf_program *prog;
9868 	unsigned int shdr_idx;
9869 	const struct btf *btf;
9870 	struct bpf_map *map;
9871 	unsigned int moff, insn_idx;
9872 	const char *name;
9873 	__u32 member_idx;
9874 	Elf64_Sym *sym;
9875 	Elf64_Rel *rel;
9876 	int i, nrels;
9877 
9878 	btf = obj->btf;
9879 	nrels = shdr->sh_size / shdr->sh_entsize;
9880 	for (i = 0; i < nrels; i++) {
9881 		rel = elf_rel_by_idx(data, i);
9882 		if (!rel) {
9883 			pr_warn("struct_ops reloc: failed to get %d reloc\n", i);
9884 			return -LIBBPF_ERRNO__FORMAT;
9885 		}
9886 
9887 		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
9888 		if (!sym) {
9889 			pr_warn("struct_ops reloc: symbol %zx not found\n",
9890 				(size_t)ELF64_R_SYM(rel->r_info));
9891 			return -LIBBPF_ERRNO__FORMAT;
9892 		}
9893 
9894 		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
9895 		map = find_struct_ops_map_by_offset(obj, shdr->sh_info, rel->r_offset);
9896 		if (!map) {
9897 			pr_warn("struct_ops reloc: cannot find map at rel->r_offset %zu\n",
9898 				(size_t)rel->r_offset);
9899 			return -EINVAL;
9900 		}
9901 
9902 		moff = rel->r_offset - map->sec_offset;
9903 		shdr_idx = sym->st_shndx;
9904 		st_ops = map->st_ops;
9905 		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",
9906 			 map->name,
9907 			 (long long)(rel->r_info >> 32),
9908 			 (long long)sym->st_value,
9909 			 shdr_idx, (size_t)rel->r_offset,
9910 			 map->sec_offset, sym->st_name, name);
9911 
9912 		if (shdr_idx >= SHN_LORESERVE) {
9913 			pr_warn("struct_ops reloc %s: rel->r_offset %zu shdr_idx %u unsupported non-static function\n",
9914 				map->name, (size_t)rel->r_offset, shdr_idx);
9915 			return -LIBBPF_ERRNO__RELOC;
9916 		}
9917 		if (sym->st_value % BPF_INSN_SZ) {
9918 			pr_warn("struct_ops reloc %s: invalid target program offset %llu\n",
9919 				map->name, (unsigned long long)sym->st_value);
9920 			return -LIBBPF_ERRNO__FORMAT;
9921 		}
9922 		insn_idx = sym->st_value / BPF_INSN_SZ;
9923 
9924 		type = btf__type_by_id(btf, st_ops->type_id);
9925 		member = find_member_by_offset(type, moff * 8);
9926 		if (!member) {
9927 			pr_warn("struct_ops reloc %s: cannot find member at moff %u\n",
9928 				map->name, moff);
9929 			return -EINVAL;
9930 		}
9931 		member_idx = member - btf_members(type);
9932 		name = btf__name_by_offset(btf, member->name_off);
9933 
9934 		if (!resolve_func_ptr(btf, member->type, NULL)) {
9935 			pr_warn("struct_ops reloc %s: cannot relocate non func ptr %s\n",
9936 				map->name, name);
9937 			return -EINVAL;
9938 		}
9939 
9940 		prog = find_prog_by_sec_insn(obj, shdr_idx, insn_idx);
9941 		if (!prog) {
9942 			pr_warn("struct_ops reloc %s: cannot find prog at shdr_idx %u to relocate func ptr %s\n",
9943 				map->name, shdr_idx, name);
9944 			return -EINVAL;
9945 		}
9946 
9947 		/* prevent the use of BPF prog with invalid type */
9948 		if (prog->type != BPF_PROG_TYPE_STRUCT_OPS) {
9949 			pr_warn("struct_ops reloc %s: prog %s is not struct_ops BPF program\n",
9950 				map->name, prog->name);
9951 			return -EINVAL;
9952 		}
9953 
9954 		st_ops->progs[member_idx] = prog;
9955 
9956 		/* st_ops->data will be exposed to users, being returned by
9957 		 * bpf_map__initial_value() as a pointer to the shadow
9958 		 * type. All function pointers in the original struct type
9959 		 * should be converted to a pointer to struct bpf_program
9960 		 * in the shadow type.
9961 		 */
9962 		*((struct bpf_program **)(st_ops->data + moff)) = prog;
9963 	}
9964 
9965 	return 0;
9966 }
9967 
9968 #define BTF_TRACE_PREFIX "btf_trace_"
9969 #define BTF_LSM_PREFIX "bpf_lsm_"
9970 #define BTF_ITER_PREFIX "bpf_iter_"
9971 #define BTF_MAX_NAME_SIZE 128
9972 
9973 void btf_get_kernel_prefix_kind(enum bpf_attach_type attach_type,
9974 				const char **prefix, int *kind)
9975 {
9976 	switch (attach_type) {
9977 	case BPF_TRACE_RAW_TP:
9978 		*prefix = BTF_TRACE_PREFIX;
9979 		*kind = BTF_KIND_TYPEDEF;
9980 		break;
9981 	case BPF_LSM_MAC:
9982 	case BPF_LSM_CGROUP:
9983 		*prefix = BTF_LSM_PREFIX;
9984 		*kind = BTF_KIND_FUNC;
9985 		break;
9986 	case BPF_TRACE_ITER:
9987 		*prefix = BTF_ITER_PREFIX;
9988 		*kind = BTF_KIND_FUNC;
9989 		break;
9990 	default:
9991 		*prefix = "";
9992 		*kind = BTF_KIND_FUNC;
9993 	}
9994 }
9995 
9996 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
9997 				   const char *name, __u32 kind)
9998 {
9999 	char btf_type_name[BTF_MAX_NAME_SIZE];
10000 	int ret;
10001 
10002 	ret = snprintf(btf_type_name, sizeof(btf_type_name),
10003 		       "%s%s", prefix, name);
10004 	/* snprintf returns the number of characters written excluding the
10005 	 * terminating null. So, if >= BTF_MAX_NAME_SIZE are written, it
10006 	 * indicates truncation.
10007 	 */
10008 	if (ret < 0 || ret >= sizeof(btf_type_name))
10009 		return -ENAMETOOLONG;
10010 	return btf__find_by_name_kind(btf, btf_type_name, kind);
10011 }
10012 
10013 static inline int find_attach_btf_id(struct btf *btf, const char *name,
10014 				     enum bpf_attach_type attach_type)
10015 {
10016 	const char *prefix;
10017 	int kind;
10018 
10019 	btf_get_kernel_prefix_kind(attach_type, &prefix, &kind);
10020 	return find_btf_by_prefix_kind(btf, prefix, name, kind);
10021 }
10022 
10023 int libbpf_find_vmlinux_btf_id(const char *name,
10024 			       enum bpf_attach_type attach_type)
10025 {
10026 	struct btf *btf;
10027 	int err;
10028 
10029 	btf = btf__load_vmlinux_btf();
10030 	err = libbpf_get_error(btf);
10031 	if (err) {
10032 		pr_warn("vmlinux BTF is not found\n");
10033 		return libbpf_err(err);
10034 	}
10035 
10036 	err = find_attach_btf_id(btf, name, attach_type);
10037 	if (err <= 0)
10038 		pr_warn("%s is not found in vmlinux BTF\n", name);
10039 
10040 	btf__free(btf);
10041 	return libbpf_err(err);
10042 }
10043 
10044 static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd, int token_fd)
10045 {
10046 	struct bpf_prog_info info;
10047 	__u32 info_len = sizeof(info);
10048 	struct btf *btf;
10049 	int err;
10050 
10051 	memset(&info, 0, info_len);
10052 	err = bpf_prog_get_info_by_fd(attach_prog_fd, &info, &info_len);
10053 	if (err) {
10054 		pr_warn("failed bpf_prog_get_info_by_fd for FD %d: %s\n",
10055 			attach_prog_fd, errstr(err));
10056 		return err;
10057 	}
10058 
10059 	err = -EINVAL;
10060 	if (!info.btf_id) {
10061 		pr_warn("The target program doesn't have BTF\n");
10062 		goto out;
10063 	}
10064 	btf = btf_load_from_kernel(info.btf_id, NULL, token_fd);
10065 	err = libbpf_get_error(btf);
10066 	if (err) {
10067 		pr_warn("Failed to get BTF %d of the program: %s\n", info.btf_id, errstr(err));
10068 		goto out;
10069 	}
10070 	err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
10071 	btf__free(btf);
10072 	if (err <= 0) {
10073 		pr_warn("%s is not found in prog's BTF\n", name);
10074 		goto out;
10075 	}
10076 out:
10077 	return err;
10078 }
10079 
10080 static int find_kernel_btf_id(struct bpf_object *obj, const char *attach_name,
10081 			      enum bpf_attach_type attach_type,
10082 			      int *btf_obj_fd, int *btf_type_id)
10083 {
10084 	int ret, i, mod_len;
10085 	const char *fn_name, *mod_name = NULL;
10086 
10087 	fn_name = strchr(attach_name, ':');
10088 	if (fn_name) {
10089 		mod_name = attach_name;
10090 		mod_len = fn_name - mod_name;
10091 		fn_name++;
10092 	}
10093 
10094 	if (!mod_name || strncmp(mod_name, "vmlinux", mod_len) == 0) {
10095 		ret = find_attach_btf_id(obj->btf_vmlinux,
10096 					 mod_name ? fn_name : attach_name,
10097 					 attach_type);
10098 		if (ret > 0) {
10099 			*btf_obj_fd = 0; /* vmlinux BTF */
10100 			*btf_type_id = ret;
10101 			return 0;
10102 		}
10103 		if (ret != -ENOENT)
10104 			return ret;
10105 	}
10106 
10107 	ret = load_module_btfs(obj);
10108 	if (ret)
10109 		return ret;
10110 
10111 	for (i = 0; i < obj->btf_module_cnt; i++) {
10112 		const struct module_btf *mod = &obj->btf_modules[i];
10113 
10114 		if (mod_name && strncmp(mod->name, mod_name, mod_len) != 0)
10115 			continue;
10116 
10117 		ret = find_attach_btf_id(mod->btf,
10118 					 mod_name ? fn_name : attach_name,
10119 					 attach_type);
10120 		if (ret > 0) {
10121 			*btf_obj_fd = mod->fd;
10122 			*btf_type_id = ret;
10123 			return 0;
10124 		}
10125 		if (ret == -ENOENT)
10126 			continue;
10127 
10128 		return ret;
10129 	}
10130 
10131 	return -ESRCH;
10132 }
10133 
10134 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
10135 				     int *btf_obj_fd, int *btf_type_id)
10136 {
10137 	enum bpf_attach_type attach_type = prog->expected_attach_type;
10138 	__u32 attach_prog_fd = prog->attach_prog_fd;
10139 	int err = 0;
10140 
10141 	/* BPF program's BTF ID */
10142 	if (prog->type == BPF_PROG_TYPE_EXT || attach_prog_fd) {
10143 		if (!attach_prog_fd) {
10144 			pr_warn("prog '%s': attach program FD is not set\n", prog->name);
10145 			return -EINVAL;
10146 		}
10147 		err = libbpf_find_prog_btf_id(attach_name, attach_prog_fd, prog->obj->token_fd);
10148 		if (err < 0) {
10149 			pr_warn("prog '%s': failed to find BPF program (FD %d) BTF ID for '%s': %s\n",
10150 				prog->name, attach_prog_fd, attach_name, errstr(err));
10151 			return err;
10152 		}
10153 		*btf_obj_fd = 0;
10154 		*btf_type_id = err;
10155 		return 0;
10156 	}
10157 
10158 	/* kernel/module BTF ID */
10159 	if (prog->obj->gen_loader) {
10160 		bpf_gen__record_attach_target(prog->obj->gen_loader, attach_name, attach_type);
10161 		*btf_obj_fd = 0;
10162 		*btf_type_id = 1;
10163 	} else {
10164 		err = find_kernel_btf_id(prog->obj, attach_name,
10165 					 attach_type, btf_obj_fd,
10166 					 btf_type_id);
10167 	}
10168 	if (err) {
10169 		pr_warn("prog '%s': failed to find kernel BTF type ID of '%s': %s\n",
10170 			prog->name, attach_name, errstr(err));
10171 		return err;
10172 	}
10173 	return 0;
10174 }
10175 
10176 int libbpf_attach_type_by_name(const char *name,
10177 			       enum bpf_attach_type *attach_type)
10178 {
10179 	char *type_names;
10180 	const struct bpf_sec_def *sec_def;
10181 
10182 	if (!name)
10183 		return libbpf_err(-EINVAL);
10184 
10185 	sec_def = find_sec_def(name);
10186 	if (!sec_def) {
10187 		pr_debug("failed to guess attach type based on ELF section name '%s'\n", name);
10188 		type_names = libbpf_get_type_names(true);
10189 		if (type_names != NULL) {
10190 			pr_debug("attachable section(type) names are:%s\n", type_names);
10191 			free(type_names);
10192 		}
10193 
10194 		return libbpf_err(-EINVAL);
10195 	}
10196 
10197 	if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
10198 		return libbpf_err(-EINVAL);
10199 	if (!(sec_def->cookie & SEC_ATTACHABLE))
10200 		return libbpf_err(-EINVAL);
10201 
10202 	*attach_type = sec_def->expected_attach_type;
10203 	return 0;
10204 }
10205 
10206 int bpf_map__fd(const struct bpf_map *map)
10207 {
10208 	if (!map)
10209 		return libbpf_err(-EINVAL);
10210 	if (!map_is_created(map))
10211 		return -1;
10212 	return map->fd;
10213 }
10214 
10215 static bool map_uses_real_name(const struct bpf_map *map)
10216 {
10217 	/* Since libbpf started to support custom .data.* and .rodata.* maps,
10218 	 * their user-visible name differs from kernel-visible name. Users see
10219 	 * such map's corresponding ELF section name as a map name.
10220 	 * This check distinguishes .data/.rodata from .data.* and .rodata.*
10221 	 * maps to know which name has to be returned to the user.
10222 	 */
10223 	if (map->libbpf_type == LIBBPF_MAP_DATA && strcmp(map->real_name, DATA_SEC) != 0)
10224 		return true;
10225 	if (map->libbpf_type == LIBBPF_MAP_RODATA && strcmp(map->real_name, RODATA_SEC) != 0)
10226 		return true;
10227 	return false;
10228 }
10229 
10230 const char *bpf_map__name(const struct bpf_map *map)
10231 {
10232 	if (!map)
10233 		return NULL;
10234 
10235 	if (map_uses_real_name(map))
10236 		return map->real_name;
10237 
10238 	return map->name;
10239 }
10240 
10241 enum bpf_map_type bpf_map__type(const struct bpf_map *map)
10242 {
10243 	return map->def.type;
10244 }
10245 
10246 int bpf_map__set_type(struct bpf_map *map, enum bpf_map_type type)
10247 {
10248 	if (map_is_created(map))
10249 		return libbpf_err(-EBUSY);
10250 	map->def.type = type;
10251 	return 0;
10252 }
10253 
10254 __u32 bpf_map__map_flags(const struct bpf_map *map)
10255 {
10256 	return map->def.map_flags;
10257 }
10258 
10259 int bpf_map__set_map_flags(struct bpf_map *map, __u32 flags)
10260 {
10261 	if (map_is_created(map))
10262 		return libbpf_err(-EBUSY);
10263 	map->def.map_flags = flags;
10264 	return 0;
10265 }
10266 
10267 __u64 bpf_map__map_extra(const struct bpf_map *map)
10268 {
10269 	return map->map_extra;
10270 }
10271 
10272 int bpf_map__set_map_extra(struct bpf_map *map, __u64 map_extra)
10273 {
10274 	if (map_is_created(map))
10275 		return libbpf_err(-EBUSY);
10276 	map->map_extra = map_extra;
10277 	return 0;
10278 }
10279 
10280 __u32 bpf_map__numa_node(const struct bpf_map *map)
10281 {
10282 	return map->numa_node;
10283 }
10284 
10285 int bpf_map__set_numa_node(struct bpf_map *map, __u32 numa_node)
10286 {
10287 	if (map_is_created(map))
10288 		return libbpf_err(-EBUSY);
10289 	map->numa_node = numa_node;
10290 	return 0;
10291 }
10292 
10293 __u32 bpf_map__key_size(const struct bpf_map *map)
10294 {
10295 	return map->def.key_size;
10296 }
10297 
10298 int bpf_map__set_key_size(struct bpf_map *map, __u32 size)
10299 {
10300 	if (map_is_created(map))
10301 		return libbpf_err(-EBUSY);
10302 	map->def.key_size = size;
10303 	return 0;
10304 }
10305 
10306 __u32 bpf_map__value_size(const struct bpf_map *map)
10307 {
10308 	return map->def.value_size;
10309 }
10310 
10311 static int map_btf_datasec_resize(struct bpf_map *map, __u32 size)
10312 {
10313 	struct btf *btf;
10314 	struct btf_type *datasec_type, *var_type;
10315 	struct btf_var_secinfo *var;
10316 	const struct btf_type *array_type;
10317 	const struct btf_array *array;
10318 	int vlen, element_sz, new_array_id;
10319 	__u32 nr_elements;
10320 
10321 	/* check btf existence */
10322 	btf = bpf_object__btf(map->obj);
10323 	if (!btf)
10324 		return -ENOENT;
10325 
10326 	/* verify map is datasec */
10327 	datasec_type = btf_type_by_id(btf, bpf_map__btf_value_type_id(map));
10328 	if (!btf_is_datasec(datasec_type)) {
10329 		pr_warn("map '%s': cannot be resized, map value type is not a datasec\n",
10330 			bpf_map__name(map));
10331 		return -EINVAL;
10332 	}
10333 
10334 	/* verify datasec has at least one var */
10335 	vlen = btf_vlen(datasec_type);
10336 	if (vlen == 0) {
10337 		pr_warn("map '%s': cannot be resized, map value datasec is empty\n",
10338 			bpf_map__name(map));
10339 		return -EINVAL;
10340 	}
10341 
10342 	/* verify last var in the datasec is an array */
10343 	var = &btf_var_secinfos(datasec_type)[vlen - 1];
10344 	var_type = btf_type_by_id(btf, var->type);
10345 	array_type = skip_mods_and_typedefs(btf, var_type->type, NULL);
10346 	if (!btf_is_array(array_type)) {
10347 		pr_warn("map '%s': cannot be resized, last var must be an array\n",
10348 			bpf_map__name(map));
10349 		return -EINVAL;
10350 	}
10351 
10352 	/* verify request size aligns with array */
10353 	array = btf_array(array_type);
10354 	element_sz = btf__resolve_size(btf, array->type);
10355 	if (element_sz <= 0 || (size - var->offset) % element_sz != 0) {
10356 		pr_warn("map '%s': cannot be resized, element size (%d) doesn't align with new total size (%u)\n",
10357 			bpf_map__name(map), element_sz, size);
10358 		return -EINVAL;
10359 	}
10360 
10361 	/* create a new array based on the existing array, but with new length */
10362 	nr_elements = (size - var->offset) / element_sz;
10363 	new_array_id = btf__add_array(btf, array->index_type, array->type, nr_elements);
10364 	if (new_array_id < 0)
10365 		return new_array_id;
10366 
10367 	/* adding a new btf type invalidates existing pointers to btf objects,
10368 	 * so refresh pointers before proceeding
10369 	 */
10370 	datasec_type = btf_type_by_id(btf, map->btf_value_type_id);
10371 	var = &btf_var_secinfos(datasec_type)[vlen - 1];
10372 	var_type = btf_type_by_id(btf, var->type);
10373 
10374 	/* finally update btf info */
10375 	datasec_type->size = size;
10376 	var->size = size - var->offset;
10377 	var_type->type = new_array_id;
10378 
10379 	return 0;
10380 }
10381 
10382 int bpf_map__set_value_size(struct bpf_map *map, __u32 size)
10383 {
10384 	if (map_is_created(map))
10385 		return libbpf_err(-EBUSY);
10386 
10387 	if (map->mmaped) {
10388 		size_t mmap_old_sz, mmap_new_sz;
10389 		int err;
10390 
10391 		if (map->def.type != BPF_MAP_TYPE_ARRAY)
10392 			return libbpf_err(-EOPNOTSUPP);
10393 
10394 		mmap_old_sz = bpf_map_mmap_sz(map);
10395 		mmap_new_sz = array_map_mmap_sz(size, map->def.max_entries);
10396 		err = bpf_map_mmap_resize(map, mmap_old_sz, mmap_new_sz);
10397 		if (err) {
10398 			pr_warn("map '%s': failed to resize memory-mapped region: %s\n",
10399 				bpf_map__name(map), errstr(err));
10400 			return libbpf_err(err);
10401 		}
10402 		err = map_btf_datasec_resize(map, size);
10403 		if (err && err != -ENOENT) {
10404 			pr_warn("map '%s': failed to adjust resized BTF, clearing BTF key/value info: %s\n",
10405 				bpf_map__name(map), errstr(err));
10406 			map->btf_value_type_id = 0;
10407 			map->btf_key_type_id = 0;
10408 		}
10409 	}
10410 
10411 	map->def.value_size = size;
10412 	return 0;
10413 }
10414 
10415 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
10416 {
10417 	return map ? map->btf_key_type_id : 0;
10418 }
10419 
10420 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
10421 {
10422 	return map ? map->btf_value_type_id : 0;
10423 }
10424 
10425 int bpf_map__set_initial_value(struct bpf_map *map,
10426 			       const void *data, size_t size)
10427 {
10428 	size_t actual_sz;
10429 
10430 	if (map_is_created(map))
10431 		return libbpf_err(-EBUSY);
10432 
10433 	if (!map->mmaped || map->libbpf_type == LIBBPF_MAP_KCONFIG)
10434 		return libbpf_err(-EINVAL);
10435 
10436 	if (map->def.type == BPF_MAP_TYPE_ARENA)
10437 		actual_sz = map->obj->arena_data_sz;
10438 	else
10439 		actual_sz = map->def.value_size;
10440 	if (size != actual_sz)
10441 		return libbpf_err(-EINVAL);
10442 
10443 	memcpy(map->mmaped, data, size);
10444 	return 0;
10445 }
10446 
10447 void *bpf_map__initial_value(const struct bpf_map *map, size_t *psize)
10448 {
10449 	if (bpf_map__is_struct_ops(map)) {
10450 		if (psize)
10451 			*psize = map->def.value_size;
10452 		return map->st_ops->data;
10453 	}
10454 
10455 	if (!map->mmaped)
10456 		return NULL;
10457 
10458 	if (map->def.type == BPF_MAP_TYPE_ARENA)
10459 		*psize = map->obj->arena_data_sz;
10460 	else
10461 		*psize = map->def.value_size;
10462 
10463 	return map->mmaped;
10464 }
10465 
10466 bool bpf_map__is_internal(const struct bpf_map *map)
10467 {
10468 	return map->libbpf_type != LIBBPF_MAP_UNSPEC;
10469 }
10470 
10471 __u32 bpf_map__ifindex(const struct bpf_map *map)
10472 {
10473 	return map->map_ifindex;
10474 }
10475 
10476 int bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
10477 {
10478 	if (map_is_created(map))
10479 		return libbpf_err(-EBUSY);
10480 	map->map_ifindex = ifindex;
10481 	return 0;
10482 }
10483 
10484 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
10485 {
10486 	if (!bpf_map_type__is_map_in_map(map->def.type)) {
10487 		pr_warn("error: unsupported map type\n");
10488 		return libbpf_err(-EINVAL);
10489 	}
10490 	if (map->inner_map_fd != -1) {
10491 		pr_warn("error: inner_map_fd already specified\n");
10492 		return libbpf_err(-EINVAL);
10493 	}
10494 	if (map->inner_map) {
10495 		bpf_map__destroy(map->inner_map);
10496 		zfree(&map->inner_map);
10497 	}
10498 	map->inner_map_fd = fd;
10499 	return 0;
10500 }
10501 
10502 static struct bpf_map *
10503 __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
10504 {
10505 	ssize_t idx;
10506 	struct bpf_map *s, *e;
10507 
10508 	if (!obj || !obj->maps)
10509 		return errno = EINVAL, NULL;
10510 
10511 	s = obj->maps;
10512 	e = obj->maps + obj->nr_maps;
10513 
10514 	if ((m < s) || (m >= e)) {
10515 		pr_warn("error in %s: map handler doesn't belong to object\n",
10516 			 __func__);
10517 		return errno = EINVAL, NULL;
10518 	}
10519 
10520 	idx = (m - obj->maps) + i;
10521 	if (idx >= obj->nr_maps || idx < 0)
10522 		return NULL;
10523 	return &obj->maps[idx];
10524 }
10525 
10526 struct bpf_map *
10527 bpf_object__next_map(const struct bpf_object *obj, const struct bpf_map *prev)
10528 {
10529 	if (prev == NULL && obj != NULL)
10530 		return obj->maps;
10531 
10532 	return __bpf_map__iter(prev, obj, 1);
10533 }
10534 
10535 struct bpf_map *
10536 bpf_object__prev_map(const struct bpf_object *obj, const struct bpf_map *next)
10537 {
10538 	if (next == NULL && obj != NULL) {
10539 		if (!obj->nr_maps)
10540 			return NULL;
10541 		return obj->maps + obj->nr_maps - 1;
10542 	}
10543 
10544 	return __bpf_map__iter(next, obj, -1);
10545 }
10546 
10547 struct bpf_map *
10548 bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
10549 {
10550 	struct bpf_map *pos;
10551 
10552 	bpf_object__for_each_map(pos, obj) {
10553 		/* if it's a special internal map name (which always starts
10554 		 * with dot) then check if that special name matches the
10555 		 * real map name (ELF section name)
10556 		 */
10557 		if (name[0] == '.') {
10558 			if (pos->real_name && strcmp(pos->real_name, name) == 0)
10559 				return pos;
10560 			continue;
10561 		}
10562 		/* otherwise map name has to be an exact match */
10563 		if (map_uses_real_name(pos)) {
10564 			if (strcmp(pos->real_name, name) == 0)
10565 				return pos;
10566 			continue;
10567 		}
10568 		if (strcmp(pos->name, name) == 0)
10569 			return pos;
10570 	}
10571 	return errno = ENOENT, NULL;
10572 }
10573 
10574 int
10575 bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
10576 {
10577 	return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
10578 }
10579 
10580 static int validate_map_op(const struct bpf_map *map, size_t key_sz,
10581 			   size_t value_sz, bool check_value_sz)
10582 {
10583 	if (!map_is_created(map)) /* map is not yet created */
10584 		return -ENOENT;
10585 
10586 	if (map->def.key_size != key_sz) {
10587 		pr_warn("map '%s': unexpected key size %zu provided, expected %u\n",
10588 			map->name, key_sz, map->def.key_size);
10589 		return -EINVAL;
10590 	}
10591 
10592 	if (map->fd < 0) {
10593 		pr_warn("map '%s': can't use BPF map without FD (was it created?)\n", map->name);
10594 		return -EINVAL;
10595 	}
10596 
10597 	if (!check_value_sz)
10598 		return 0;
10599 
10600 	switch (map->def.type) {
10601 	case BPF_MAP_TYPE_PERCPU_ARRAY:
10602 	case BPF_MAP_TYPE_PERCPU_HASH:
10603 	case BPF_MAP_TYPE_LRU_PERCPU_HASH:
10604 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: {
10605 		int num_cpu = libbpf_num_possible_cpus();
10606 		size_t elem_sz = roundup(map->def.value_size, 8);
10607 
10608 		if (value_sz != num_cpu * elem_sz) {
10609 			pr_warn("map '%s': unexpected value size %zu provided for per-CPU map, expected %d * %zu = %zd\n",
10610 				map->name, value_sz, num_cpu, elem_sz, num_cpu * elem_sz);
10611 			return -EINVAL;
10612 		}
10613 		break;
10614 	}
10615 	default:
10616 		if (map->def.value_size != value_sz) {
10617 			pr_warn("map '%s': unexpected value size %zu provided, expected %u\n",
10618 				map->name, value_sz, map->def.value_size);
10619 			return -EINVAL;
10620 		}
10621 		break;
10622 	}
10623 	return 0;
10624 }
10625 
10626 int bpf_map__lookup_elem(const struct bpf_map *map,
10627 			 const void *key, size_t key_sz,
10628 			 void *value, size_t value_sz, __u64 flags)
10629 {
10630 	int err;
10631 
10632 	err = validate_map_op(map, key_sz, value_sz, true);
10633 	if (err)
10634 		return libbpf_err(err);
10635 
10636 	return bpf_map_lookup_elem_flags(map->fd, key, value, flags);
10637 }
10638 
10639 int bpf_map__update_elem(const struct bpf_map *map,
10640 			 const void *key, size_t key_sz,
10641 			 const void *value, size_t value_sz, __u64 flags)
10642 {
10643 	int err;
10644 
10645 	err = validate_map_op(map, key_sz, value_sz, true);
10646 	if (err)
10647 		return libbpf_err(err);
10648 
10649 	return bpf_map_update_elem(map->fd, key, value, flags);
10650 }
10651 
10652 int bpf_map__delete_elem(const struct bpf_map *map,
10653 			 const void *key, size_t key_sz, __u64 flags)
10654 {
10655 	int err;
10656 
10657 	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */);
10658 	if (err)
10659 		return libbpf_err(err);
10660 
10661 	return bpf_map_delete_elem_flags(map->fd, key, flags);
10662 }
10663 
10664 int bpf_map__lookup_and_delete_elem(const struct bpf_map *map,
10665 				    const void *key, size_t key_sz,
10666 				    void *value, size_t value_sz, __u64 flags)
10667 {
10668 	int err;
10669 
10670 	err = validate_map_op(map, key_sz, value_sz, true);
10671 	if (err)
10672 		return libbpf_err(err);
10673 
10674 	return bpf_map_lookup_and_delete_elem_flags(map->fd, key, value, flags);
10675 }
10676 
10677 int bpf_map__get_next_key(const struct bpf_map *map,
10678 			  const void *cur_key, void *next_key, size_t key_sz)
10679 {
10680 	int err;
10681 
10682 	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */);
10683 	if (err)
10684 		return libbpf_err(err);
10685 
10686 	return bpf_map_get_next_key(map->fd, cur_key, next_key);
10687 }
10688 
10689 long libbpf_get_error(const void *ptr)
10690 {
10691 	if (!IS_ERR_OR_NULL(ptr))
10692 		return 0;
10693 
10694 	if (IS_ERR(ptr))
10695 		errno = -PTR_ERR(ptr);
10696 
10697 	/* If ptr == NULL, then errno should be already set by the failing
10698 	 * API, because libbpf never returns NULL on success and it now always
10699 	 * sets errno on error. So no extra errno handling for ptr == NULL
10700 	 * case.
10701 	 */
10702 	return -errno;
10703 }
10704 
10705 /* Replace link's underlying BPF program with the new one */
10706 int bpf_link__update_program(struct bpf_link *link, struct bpf_program *prog)
10707 {
10708 	int ret;
10709 	int prog_fd = bpf_program__fd(prog);
10710 
10711 	if (prog_fd < 0) {
10712 		pr_warn("prog '%s': can't use BPF program without FD (was it loaded?)\n",
10713 			prog->name);
10714 		return libbpf_err(-EINVAL);
10715 	}
10716 
10717 	ret = bpf_link_update(bpf_link__fd(link), prog_fd, NULL);
10718 	return libbpf_err_errno(ret);
10719 }
10720 
10721 /* Release "ownership" of underlying BPF resource (typically, BPF program
10722  * attached to some BPF hook, e.g., tracepoint, kprobe, etc). Disconnected
10723  * link, when destructed through bpf_link__destroy() call won't attempt to
10724  * detach/unregisted that BPF resource. This is useful in situations where,
10725  * say, attached BPF program has to outlive userspace program that attached it
10726  * in the system. Depending on type of BPF program, though, there might be
10727  * additional steps (like pinning BPF program in BPF FS) necessary to ensure
10728  * exit of userspace program doesn't trigger automatic detachment and clean up
10729  * inside the kernel.
10730  */
10731 void bpf_link__disconnect(struct bpf_link *link)
10732 {
10733 	link->disconnected = true;
10734 }
10735 
10736 int bpf_link__destroy(struct bpf_link *link)
10737 {
10738 	int err = 0;
10739 
10740 	if (IS_ERR_OR_NULL(link))
10741 		return 0;
10742 
10743 	if (!link->disconnected && link->detach)
10744 		err = link->detach(link);
10745 	if (link->pin_path)
10746 		free(link->pin_path);
10747 	if (link->dealloc)
10748 		link->dealloc(link);
10749 	else
10750 		free(link);
10751 
10752 	return libbpf_err(err);
10753 }
10754 
10755 int bpf_link__fd(const struct bpf_link *link)
10756 {
10757 	return link->fd;
10758 }
10759 
10760 const char *bpf_link__pin_path(const struct bpf_link *link)
10761 {
10762 	return link->pin_path;
10763 }
10764 
10765 static int bpf_link__detach_fd(struct bpf_link *link)
10766 {
10767 	return libbpf_err_errno(close(link->fd));
10768 }
10769 
10770 struct bpf_link *bpf_link__open(const char *path)
10771 {
10772 	struct bpf_link *link;
10773 	int fd;
10774 
10775 	fd = bpf_obj_get(path);
10776 	if (fd < 0) {
10777 		fd = -errno;
10778 		pr_warn("failed to open link at %s: %d\n", path, fd);
10779 		return libbpf_err_ptr(fd);
10780 	}
10781 
10782 	link = calloc(1, sizeof(*link));
10783 	if (!link) {
10784 		close(fd);
10785 		return libbpf_err_ptr(-ENOMEM);
10786 	}
10787 	link->detach = &bpf_link__detach_fd;
10788 	link->fd = fd;
10789 
10790 	link->pin_path = strdup(path);
10791 	if (!link->pin_path) {
10792 		bpf_link__destroy(link);
10793 		return libbpf_err_ptr(-ENOMEM);
10794 	}
10795 
10796 	return link;
10797 }
10798 
10799 int bpf_link__detach(struct bpf_link *link)
10800 {
10801 	return bpf_link_detach(link->fd) ? -errno : 0;
10802 }
10803 
10804 int bpf_link__pin(struct bpf_link *link, const char *path)
10805 {
10806 	int err;
10807 
10808 	if (link->pin_path)
10809 		return libbpf_err(-EBUSY);
10810 	err = make_parent_dir(path);
10811 	if (err)
10812 		return libbpf_err(err);
10813 	err = check_path(path);
10814 	if (err)
10815 		return libbpf_err(err);
10816 
10817 	link->pin_path = strdup(path);
10818 	if (!link->pin_path)
10819 		return libbpf_err(-ENOMEM);
10820 
10821 	if (bpf_obj_pin(link->fd, link->pin_path)) {
10822 		err = -errno;
10823 		zfree(&link->pin_path);
10824 		return libbpf_err(err);
10825 	}
10826 
10827 	pr_debug("link fd=%d: pinned at %s\n", link->fd, link->pin_path);
10828 	return 0;
10829 }
10830 
10831 int bpf_link__unpin(struct bpf_link *link)
10832 {
10833 	int err;
10834 
10835 	if (!link->pin_path)
10836 		return libbpf_err(-EINVAL);
10837 
10838 	err = unlink(link->pin_path);
10839 	if (err != 0)
10840 		return -errno;
10841 
10842 	pr_debug("link fd=%d: unpinned from %s\n", link->fd, link->pin_path);
10843 	zfree(&link->pin_path);
10844 	return 0;
10845 }
10846 
10847 struct bpf_link_perf {
10848 	struct bpf_link link;
10849 	int perf_event_fd;
10850 	/* legacy kprobe support: keep track of probe identifier and type */
10851 	char *legacy_probe_name;
10852 	bool legacy_is_kprobe;
10853 	bool legacy_is_retprobe;
10854 };
10855 
10856 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe);
10857 static int remove_uprobe_event_legacy(const char *probe_name, bool retprobe);
10858 
10859 static int bpf_link_perf_detach(struct bpf_link *link)
10860 {
10861 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10862 	int err = 0;
10863 
10864 	if (ioctl(perf_link->perf_event_fd, PERF_EVENT_IOC_DISABLE, 0) < 0)
10865 		err = -errno;
10866 
10867 	if (perf_link->perf_event_fd != link->fd)
10868 		close(perf_link->perf_event_fd);
10869 	close(link->fd);
10870 
10871 	/* legacy uprobe/kprobe needs to be removed after perf event fd closure */
10872 	if (perf_link->legacy_probe_name) {
10873 		if (perf_link->legacy_is_kprobe) {
10874 			err = remove_kprobe_event_legacy(perf_link->legacy_probe_name,
10875 							 perf_link->legacy_is_retprobe);
10876 		} else {
10877 			err = remove_uprobe_event_legacy(perf_link->legacy_probe_name,
10878 							 perf_link->legacy_is_retprobe);
10879 		}
10880 	}
10881 
10882 	return err;
10883 }
10884 
10885 static void bpf_link_perf_dealloc(struct bpf_link *link)
10886 {
10887 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10888 
10889 	free(perf_link->legacy_probe_name);
10890 	free(perf_link);
10891 }
10892 
10893 struct bpf_link *bpf_program__attach_perf_event_opts(const struct bpf_program *prog, int pfd,
10894 						     const struct bpf_perf_event_opts *opts)
10895 {
10896 	struct bpf_link_perf *link;
10897 	int prog_fd, link_fd = -1, err;
10898 	bool force_ioctl_attach;
10899 
10900 	if (!OPTS_VALID(opts, bpf_perf_event_opts))
10901 		return libbpf_err_ptr(-EINVAL);
10902 
10903 	if (pfd < 0) {
10904 		pr_warn("prog '%s': invalid perf event FD %d\n",
10905 			prog->name, pfd);
10906 		return libbpf_err_ptr(-EINVAL);
10907 	}
10908 	prog_fd = bpf_program__fd(prog);
10909 	if (prog_fd < 0) {
10910 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
10911 			prog->name);
10912 		return libbpf_err_ptr(-EINVAL);
10913 	}
10914 
10915 	link = calloc(1, sizeof(*link));
10916 	if (!link)
10917 		return libbpf_err_ptr(-ENOMEM);
10918 	link->link.detach = &bpf_link_perf_detach;
10919 	link->link.dealloc = &bpf_link_perf_dealloc;
10920 	link->perf_event_fd = pfd;
10921 
10922 	force_ioctl_attach = OPTS_GET(opts, force_ioctl_attach, false);
10923 	if (kernel_supports(prog->obj, FEAT_PERF_LINK) && !force_ioctl_attach) {
10924 		DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_opts,
10925 			.perf_event.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0));
10926 
10927 		link_fd = bpf_link_create(prog_fd, pfd, BPF_PERF_EVENT, &link_opts);
10928 		if (link_fd < 0) {
10929 			err = -errno;
10930 			pr_warn("prog '%s': failed to create BPF link for perf_event FD %d: %s\n",
10931 				prog->name, pfd, errstr(err));
10932 			goto err_out;
10933 		}
10934 		link->link.fd = link_fd;
10935 	} else {
10936 		if (OPTS_GET(opts, bpf_cookie, 0)) {
10937 			pr_warn("prog '%s': user context value is not supported\n", prog->name);
10938 			err = -EOPNOTSUPP;
10939 			goto err_out;
10940 		}
10941 
10942 		if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
10943 			err = -errno;
10944 			pr_warn("prog '%s': failed to attach to perf_event FD %d: %s\n",
10945 				prog->name, pfd, errstr(err));
10946 			if (err == -EPROTO)
10947 				pr_warn("prog '%s': try add PERF_SAMPLE_CALLCHAIN to or remove exclude_callchain_[kernel|user] from pfd %d\n",
10948 					prog->name, pfd);
10949 			goto err_out;
10950 		}
10951 		link->link.fd = pfd;
10952 	}
10953 	if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
10954 		err = -errno;
10955 		pr_warn("prog '%s': failed to enable perf_event FD %d: %s\n",
10956 			prog->name, pfd, errstr(err));
10957 		goto err_out;
10958 	}
10959 
10960 	return &link->link;
10961 err_out:
10962 	if (link_fd >= 0)
10963 		close(link_fd);
10964 	free(link);
10965 	return libbpf_err_ptr(err);
10966 }
10967 
10968 struct bpf_link *bpf_program__attach_perf_event(const struct bpf_program *prog, int pfd)
10969 {
10970 	return bpf_program__attach_perf_event_opts(prog, pfd, NULL);
10971 }
10972 
10973 /*
10974  * this function is expected to parse integer in the range of [0, 2^31-1] from
10975  * given file using scanf format string fmt. If actual parsed value is
10976  * negative, the result might be indistinguishable from error
10977  */
10978 static int parse_uint_from_file(const char *file, const char *fmt)
10979 {
10980 	int err, ret;
10981 	FILE *f;
10982 
10983 	f = fopen(file, "re");
10984 	if (!f) {
10985 		err = -errno;
10986 		pr_debug("failed to open '%s': %s\n", file, errstr(err));
10987 		return err;
10988 	}
10989 	err = fscanf(f, fmt, &ret);
10990 	if (err != 1) {
10991 		err = err == EOF ? -EIO : -errno;
10992 		pr_debug("failed to parse '%s': %s\n", file, errstr(err));
10993 		fclose(f);
10994 		return err;
10995 	}
10996 	fclose(f);
10997 	return ret;
10998 }
10999 
11000 static int determine_kprobe_perf_type(void)
11001 {
11002 	const char *file = "/sys/bus/event_source/devices/kprobe/type";
11003 
11004 	return parse_uint_from_file(file, "%d\n");
11005 }
11006 
11007 static int determine_uprobe_perf_type(void)
11008 {
11009 	const char *file = "/sys/bus/event_source/devices/uprobe/type";
11010 
11011 	return parse_uint_from_file(file, "%d\n");
11012 }
11013 
11014 static int determine_kprobe_retprobe_bit(void)
11015 {
11016 	const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
11017 
11018 	return parse_uint_from_file(file, "config:%d\n");
11019 }
11020 
11021 static int determine_uprobe_retprobe_bit(void)
11022 {
11023 	const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
11024 
11025 	return parse_uint_from_file(file, "config:%d\n");
11026 }
11027 
11028 #define PERF_UPROBE_REF_CTR_OFFSET_BITS 32
11029 #define PERF_UPROBE_REF_CTR_OFFSET_SHIFT 32
11030 
11031 static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
11032 				 uint64_t offset, int pid, size_t ref_ctr_off)
11033 {
11034 	const size_t attr_sz = sizeof(struct perf_event_attr);
11035 	struct perf_event_attr attr;
11036 	int type, pfd;
11037 
11038 	if ((__u64)ref_ctr_off >= (1ULL << PERF_UPROBE_REF_CTR_OFFSET_BITS))
11039 		return -EINVAL;
11040 
11041 	memset(&attr, 0, attr_sz);
11042 
11043 	type = uprobe ? determine_uprobe_perf_type()
11044 		      : determine_kprobe_perf_type();
11045 	if (type < 0) {
11046 		pr_warn("failed to determine %s perf type: %s\n",
11047 			uprobe ? "uprobe" : "kprobe",
11048 			errstr(type));
11049 		return type;
11050 	}
11051 	if (retprobe) {
11052 		int bit = uprobe ? determine_uprobe_retprobe_bit()
11053 				 : determine_kprobe_retprobe_bit();
11054 
11055 		if (bit < 0) {
11056 			pr_warn("failed to determine %s retprobe bit: %s\n",
11057 				uprobe ? "uprobe" : "kprobe",
11058 				errstr(bit));
11059 			return bit;
11060 		}
11061 		attr.config |= 1 << bit;
11062 	}
11063 	attr.size = attr_sz;
11064 	attr.type = type;
11065 	attr.config |= (__u64)ref_ctr_off << PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
11066 	attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
11067 	attr.config2 = offset;		 /* kprobe_addr or probe_offset */
11068 
11069 	/* pid filter is meaningful only for uprobes */
11070 	pfd = syscall(__NR_perf_event_open, &attr,
11071 		      pid < 0 ? -1 : pid /* pid */,
11072 		      pid == -1 ? 0 : -1 /* cpu */,
11073 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
11074 	return pfd >= 0 ? pfd : -errno;
11075 }
11076 
11077 static int append_to_file(const char *file, const char *fmt, ...)
11078 {
11079 	int fd, n, err = 0;
11080 	va_list ap;
11081 	char buf[1024];
11082 
11083 	va_start(ap, fmt);
11084 	n = vsnprintf(buf, sizeof(buf), fmt, ap);
11085 	va_end(ap);
11086 
11087 	if (n < 0 || n >= sizeof(buf))
11088 		return -EINVAL;
11089 
11090 	fd = open(file, O_WRONLY | O_APPEND | O_CLOEXEC, 0);
11091 	if (fd < 0)
11092 		return -errno;
11093 
11094 	if (write(fd, buf, n) < 0)
11095 		err = -errno;
11096 
11097 	close(fd);
11098 	return err;
11099 }
11100 
11101 #define DEBUGFS "/sys/kernel/debug/tracing"
11102 #define TRACEFS "/sys/kernel/tracing"
11103 
11104 static bool use_debugfs(void)
11105 {
11106 	static int has_debugfs = -1;
11107 
11108 	if (has_debugfs < 0)
11109 		has_debugfs = faccessat(AT_FDCWD, DEBUGFS, F_OK, AT_EACCESS) == 0;
11110 
11111 	return has_debugfs == 1;
11112 }
11113 
11114 static const char *tracefs_path(void)
11115 {
11116 	return use_debugfs() ? DEBUGFS : TRACEFS;
11117 }
11118 
11119 static const char *tracefs_kprobe_events(void)
11120 {
11121 	return use_debugfs() ? DEBUGFS"/kprobe_events" : TRACEFS"/kprobe_events";
11122 }
11123 
11124 static const char *tracefs_uprobe_events(void)
11125 {
11126 	return use_debugfs() ? DEBUGFS"/uprobe_events" : TRACEFS"/uprobe_events";
11127 }
11128 
11129 static const char *tracefs_available_filter_functions(void)
11130 {
11131 	return use_debugfs() ? DEBUGFS"/available_filter_functions"
11132 			     : TRACEFS"/available_filter_functions";
11133 }
11134 
11135 static const char *tracefs_available_filter_functions_addrs(void)
11136 {
11137 	return use_debugfs() ? DEBUGFS"/available_filter_functions_addrs"
11138 			     : TRACEFS"/available_filter_functions_addrs";
11139 }
11140 
11141 static void gen_probe_legacy_event_name(char *buf, size_t buf_sz,
11142 					const char *name, size_t offset)
11143 {
11144 	static int index = 0;
11145 	int i;
11146 
11147 	snprintf(buf, buf_sz, "libbpf_%u_%d_%s_0x%zx", getpid(),
11148 		 __sync_fetch_and_add(&index, 1), name, offset);
11149 
11150 	/* sanitize name in the probe name */
11151 	for (i = 0; buf[i]; i++) {
11152 		if (!isalnum(buf[i]))
11153 			buf[i] = '_';
11154 	}
11155 }
11156 
11157 static int add_kprobe_event_legacy(const char *probe_name, bool retprobe,
11158 				   const char *kfunc_name, size_t offset)
11159 {
11160 	return append_to_file(tracefs_kprobe_events(), "%c:%s/%s %s+0x%zx",
11161 			      retprobe ? 'r' : 'p',
11162 			      retprobe ? "kretprobes" : "kprobes",
11163 			      probe_name, kfunc_name, offset);
11164 }
11165 
11166 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe)
11167 {
11168 	return append_to_file(tracefs_kprobe_events(), "-:%s/%s",
11169 			      retprobe ? "kretprobes" : "kprobes", probe_name);
11170 }
11171 
11172 static int determine_kprobe_perf_type_legacy(const char *probe_name, bool retprobe)
11173 {
11174 	char file[256];
11175 
11176 	snprintf(file, sizeof(file), "%s/events/%s/%s/id",
11177 		 tracefs_path(), retprobe ? "kretprobes" : "kprobes", probe_name);
11178 
11179 	return parse_uint_from_file(file, "%d\n");
11180 }
11181 
11182 static int perf_event_kprobe_open_legacy(const char *probe_name, bool retprobe,
11183 					 const char *kfunc_name, size_t offset, int pid)
11184 {
11185 	const size_t attr_sz = sizeof(struct perf_event_attr);
11186 	struct perf_event_attr attr;
11187 	int type, pfd, err;
11188 
11189 	err = add_kprobe_event_legacy(probe_name, retprobe, kfunc_name, offset);
11190 	if (err < 0) {
11191 		pr_warn("failed to add legacy kprobe event for '%s+0x%zx': %s\n",
11192 			kfunc_name, offset,
11193 			errstr(err));
11194 		return err;
11195 	}
11196 	type = determine_kprobe_perf_type_legacy(probe_name, retprobe);
11197 	if (type < 0) {
11198 		err = type;
11199 		pr_warn("failed to determine legacy kprobe event id for '%s+0x%zx': %s\n",
11200 			kfunc_name, offset,
11201 			errstr(err));
11202 		goto err_clean_legacy;
11203 	}
11204 
11205 	memset(&attr, 0, attr_sz);
11206 	attr.size = attr_sz;
11207 	attr.config = type;
11208 	attr.type = PERF_TYPE_TRACEPOINT;
11209 
11210 	pfd = syscall(__NR_perf_event_open, &attr,
11211 		      pid < 0 ? -1 : pid, /* pid */
11212 		      pid == -1 ? 0 : -1, /* cpu */
11213 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
11214 	if (pfd < 0) {
11215 		err = -errno;
11216 		pr_warn("legacy kprobe perf_event_open() failed: %s\n",
11217 			errstr(err));
11218 		goto err_clean_legacy;
11219 	}
11220 	return pfd;
11221 
11222 err_clean_legacy:
11223 	/* Clear the newly added legacy kprobe_event */
11224 	remove_kprobe_event_legacy(probe_name, retprobe);
11225 	return err;
11226 }
11227 
11228 static const char *arch_specific_syscall_pfx(void)
11229 {
11230 #if defined(__x86_64__)
11231 	return "x64";
11232 #elif defined(__i386__)
11233 	return "ia32";
11234 #elif defined(__s390x__)
11235 	return "s390x";
11236 #elif defined(__s390__)
11237 	return "s390";
11238 #elif defined(__arm__)
11239 	return "arm";
11240 #elif defined(__aarch64__)
11241 	return "arm64";
11242 #elif defined(__mips__)
11243 	return "mips";
11244 #elif defined(__riscv)
11245 	return "riscv";
11246 #elif defined(__powerpc__)
11247 	return "powerpc";
11248 #elif defined(__powerpc64__)
11249 	return "powerpc64";
11250 #else
11251 	return NULL;
11252 #endif
11253 }
11254 
11255 int probe_kern_syscall_wrapper(int token_fd)
11256 {
11257 	char syscall_name[64];
11258 	const char *ksys_pfx;
11259 
11260 	ksys_pfx = arch_specific_syscall_pfx();
11261 	if (!ksys_pfx)
11262 		return 0;
11263 
11264 	snprintf(syscall_name, sizeof(syscall_name), "__%s_sys_bpf", ksys_pfx);
11265 
11266 	if (determine_kprobe_perf_type() >= 0) {
11267 		int pfd;
11268 
11269 		pfd = perf_event_open_probe(false, false, syscall_name, 0, getpid(), 0);
11270 		if (pfd >= 0)
11271 			close(pfd);
11272 
11273 		return pfd >= 0 ? 1 : 0;
11274 	} else { /* legacy mode */
11275 		char probe_name[MAX_EVENT_NAME_LEN];
11276 
11277 		gen_probe_legacy_event_name(probe_name, sizeof(probe_name), syscall_name, 0);
11278 		if (add_kprobe_event_legacy(probe_name, false, syscall_name, 0) < 0)
11279 			return 0;
11280 
11281 		(void)remove_kprobe_event_legacy(probe_name, false);
11282 		return 1;
11283 	}
11284 }
11285 
11286 struct bpf_link *
11287 bpf_program__attach_kprobe_opts(const struct bpf_program *prog,
11288 				const char *func_name,
11289 				const struct bpf_kprobe_opts *opts)
11290 {
11291 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
11292 	enum probe_attach_mode attach_mode;
11293 	char *legacy_probe = NULL;
11294 	struct bpf_link *link;
11295 	size_t offset;
11296 	bool retprobe, legacy;
11297 	int pfd, err;
11298 
11299 	if (!OPTS_VALID(opts, bpf_kprobe_opts))
11300 		return libbpf_err_ptr(-EINVAL);
11301 
11302 	attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
11303 	retprobe = OPTS_GET(opts, retprobe, false);
11304 	offset = OPTS_GET(opts, offset, 0);
11305 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11306 
11307 	legacy = determine_kprobe_perf_type() < 0;
11308 	switch (attach_mode) {
11309 	case PROBE_ATTACH_MODE_LEGACY:
11310 		legacy = true;
11311 		pe_opts.force_ioctl_attach = true;
11312 		break;
11313 	case PROBE_ATTACH_MODE_PERF:
11314 		if (legacy)
11315 			return libbpf_err_ptr(-ENOTSUP);
11316 		pe_opts.force_ioctl_attach = true;
11317 		break;
11318 	case PROBE_ATTACH_MODE_LINK:
11319 		if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
11320 			return libbpf_err_ptr(-ENOTSUP);
11321 		break;
11322 	case PROBE_ATTACH_MODE_DEFAULT:
11323 		break;
11324 	default:
11325 		return libbpf_err_ptr(-EINVAL);
11326 	}
11327 
11328 	if (!legacy) {
11329 		pfd = perf_event_open_probe(false /* uprobe */, retprobe,
11330 					    func_name, offset,
11331 					    -1 /* pid */, 0 /* ref_ctr_off */);
11332 	} else {
11333 		char probe_name[MAX_EVENT_NAME_LEN];
11334 
11335 		gen_probe_legacy_event_name(probe_name, sizeof(probe_name),
11336 					    func_name, offset);
11337 
11338 		legacy_probe = strdup(probe_name);
11339 		if (!legacy_probe)
11340 			return libbpf_err_ptr(-ENOMEM);
11341 
11342 		pfd = perf_event_kprobe_open_legacy(legacy_probe, retprobe, func_name,
11343 						    offset, -1 /* pid */);
11344 	}
11345 	if (pfd < 0) {
11346 		err = -errno;
11347 		pr_warn("prog '%s': failed to create %s '%s+0x%zx' perf event: %s\n",
11348 			prog->name, retprobe ? "kretprobe" : "kprobe",
11349 			func_name, offset,
11350 			errstr(err));
11351 		goto err_out;
11352 	}
11353 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
11354 	err = libbpf_get_error(link);
11355 	if (err) {
11356 		close(pfd);
11357 		pr_warn("prog '%s': failed to attach to %s '%s+0x%zx': %s\n",
11358 			prog->name, retprobe ? "kretprobe" : "kprobe",
11359 			func_name, offset,
11360 			errstr(err));
11361 		goto err_clean_legacy;
11362 	}
11363 	if (legacy) {
11364 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
11365 
11366 		perf_link->legacy_probe_name = legacy_probe;
11367 		perf_link->legacy_is_kprobe = true;
11368 		perf_link->legacy_is_retprobe = retprobe;
11369 	}
11370 
11371 	return link;
11372 
11373 err_clean_legacy:
11374 	if (legacy)
11375 		remove_kprobe_event_legacy(legacy_probe, retprobe);
11376 err_out:
11377 	free(legacy_probe);
11378 	return libbpf_err_ptr(err);
11379 }
11380 
11381 struct bpf_link *bpf_program__attach_kprobe(const struct bpf_program *prog,
11382 					    bool retprobe,
11383 					    const char *func_name)
11384 {
11385 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts,
11386 		.retprobe = retprobe,
11387 	);
11388 
11389 	return bpf_program__attach_kprobe_opts(prog, func_name, &opts);
11390 }
11391 
11392 struct bpf_link *bpf_program__attach_ksyscall(const struct bpf_program *prog,
11393 					      const char *syscall_name,
11394 					      const struct bpf_ksyscall_opts *opts)
11395 {
11396 	LIBBPF_OPTS(bpf_kprobe_opts, kprobe_opts);
11397 	char func_name[128];
11398 
11399 	if (!OPTS_VALID(opts, bpf_ksyscall_opts))
11400 		return libbpf_err_ptr(-EINVAL);
11401 
11402 	if (kernel_supports(prog->obj, FEAT_SYSCALL_WRAPPER)) {
11403 		/* arch_specific_syscall_pfx() should never return NULL here
11404 		 * because it is guarded by kernel_supports(). However, since
11405 		 * compiler does not know that we have an explicit conditional
11406 		 * as well.
11407 		 */
11408 		snprintf(func_name, sizeof(func_name), "__%s_sys_%s",
11409 			 arch_specific_syscall_pfx() ? : "", syscall_name);
11410 	} else {
11411 		snprintf(func_name, sizeof(func_name), "__se_sys_%s", syscall_name);
11412 	}
11413 
11414 	kprobe_opts.retprobe = OPTS_GET(opts, retprobe, false);
11415 	kprobe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11416 
11417 	return bpf_program__attach_kprobe_opts(prog, func_name, &kprobe_opts);
11418 }
11419 
11420 /* Adapted from perf/util/string.c */
11421 bool glob_match(const char *str, const char *pat)
11422 {
11423 	while (*str && *pat && *pat != '*') {
11424 		if (*pat == '?') {      /* Matches any single character */
11425 			str++;
11426 			pat++;
11427 			continue;
11428 		}
11429 		if (*str != *pat)
11430 			return false;
11431 		str++;
11432 		pat++;
11433 	}
11434 	/* Check wild card */
11435 	if (*pat == '*') {
11436 		while (*pat == '*')
11437 			pat++;
11438 		if (!*pat) /* Tail wild card matches all */
11439 			return true;
11440 		while (*str)
11441 			if (glob_match(str++, pat))
11442 				return true;
11443 	}
11444 	return !*str && !*pat;
11445 }
11446 
11447 struct kprobe_multi_resolve {
11448 	const char *pattern;
11449 	unsigned long *addrs;
11450 	size_t cap;
11451 	size_t cnt;
11452 };
11453 
11454 struct avail_kallsyms_data {
11455 	char **syms;
11456 	size_t cnt;
11457 	struct kprobe_multi_resolve *res;
11458 };
11459 
11460 static int avail_func_cmp(const void *a, const void *b)
11461 {
11462 	return strcmp(*(const char **)a, *(const char **)b);
11463 }
11464 
11465 static int avail_kallsyms_cb(unsigned long long sym_addr, char sym_type,
11466 			     const char *sym_name, void *ctx)
11467 {
11468 	struct avail_kallsyms_data *data = ctx;
11469 	struct kprobe_multi_resolve *res = data->res;
11470 	int err;
11471 
11472 	if (!glob_match(sym_name, res->pattern))
11473 		return 0;
11474 
11475 	if (!bsearch(&sym_name, data->syms, data->cnt, sizeof(*data->syms), avail_func_cmp)) {
11476 		/* Some versions of kernel strip out .llvm.<hash> suffix from
11477 		 * function names reported in available_filter_functions, but
11478 		 * don't do so for kallsyms. While this is clearly a kernel
11479 		 * bug (fixed by [0]) we try to accommodate that in libbpf to
11480 		 * make multi-kprobe usability a bit better: if no match is
11481 		 * found, we will strip .llvm. suffix and try one more time.
11482 		 *
11483 		 *   [0] fb6a421fb615 ("kallsyms: Match symbols exactly with CONFIG_LTO_CLANG")
11484 		 */
11485 		char sym_trim[256], *psym_trim = sym_trim, *sym_sfx;
11486 
11487 		if (!(sym_sfx = strstr(sym_name, ".llvm.")))
11488 			return 0;
11489 
11490 		/* psym_trim vs sym_trim dance is done to avoid pointer vs array
11491 		 * coercion differences and get proper `const char **` pointer
11492 		 * which avail_func_cmp() expects
11493 		 */
11494 		snprintf(sym_trim, sizeof(sym_trim), "%.*s", (int)(sym_sfx - sym_name), sym_name);
11495 		if (!bsearch(&psym_trim, data->syms, data->cnt, sizeof(*data->syms), avail_func_cmp))
11496 			return 0;
11497 	}
11498 
11499 	err = libbpf_ensure_mem((void **)&res->addrs, &res->cap, sizeof(*res->addrs), res->cnt + 1);
11500 	if (err)
11501 		return err;
11502 
11503 	res->addrs[res->cnt++] = (unsigned long)sym_addr;
11504 	return 0;
11505 }
11506 
11507 static int libbpf_available_kallsyms_parse(struct kprobe_multi_resolve *res)
11508 {
11509 	const char *available_functions_file = tracefs_available_filter_functions();
11510 	struct avail_kallsyms_data data;
11511 	char sym_name[500];
11512 	FILE *f;
11513 	int err = 0, ret, i;
11514 	char **syms = NULL;
11515 	size_t cap = 0, cnt = 0;
11516 
11517 	f = fopen(available_functions_file, "re");
11518 	if (!f) {
11519 		err = -errno;
11520 		pr_warn("failed to open %s: %s\n", available_functions_file, errstr(err));
11521 		return err;
11522 	}
11523 
11524 	while (true) {
11525 		char *name;
11526 
11527 		ret = fscanf(f, "%499s%*[^\n]\n", sym_name);
11528 		if (ret == EOF && feof(f))
11529 			break;
11530 
11531 		if (ret != 1) {
11532 			pr_warn("failed to parse available_filter_functions entry: %d\n", ret);
11533 			err = -EINVAL;
11534 			goto cleanup;
11535 		}
11536 
11537 		if (!glob_match(sym_name, res->pattern))
11538 			continue;
11539 
11540 		err = libbpf_ensure_mem((void **)&syms, &cap, sizeof(*syms), cnt + 1);
11541 		if (err)
11542 			goto cleanup;
11543 
11544 		name = strdup(sym_name);
11545 		if (!name) {
11546 			err = -errno;
11547 			goto cleanup;
11548 		}
11549 
11550 		syms[cnt++] = name;
11551 	}
11552 
11553 	/* no entries found, bail out */
11554 	if (cnt == 0) {
11555 		err = -ENOENT;
11556 		goto cleanup;
11557 	}
11558 
11559 	/* sort available functions */
11560 	qsort(syms, cnt, sizeof(*syms), avail_func_cmp);
11561 
11562 	data.syms = syms;
11563 	data.res = res;
11564 	data.cnt = cnt;
11565 	libbpf_kallsyms_parse(avail_kallsyms_cb, &data);
11566 
11567 	if (res->cnt == 0)
11568 		err = -ENOENT;
11569 
11570 cleanup:
11571 	for (i = 0; i < cnt; i++)
11572 		free((char *)syms[i]);
11573 	free(syms);
11574 
11575 	fclose(f);
11576 	return err;
11577 }
11578 
11579 static bool has_available_filter_functions_addrs(void)
11580 {
11581 	return access(tracefs_available_filter_functions_addrs(), R_OK) != -1;
11582 }
11583 
11584 static int libbpf_available_kprobes_parse(struct kprobe_multi_resolve *res)
11585 {
11586 	const char *available_path = tracefs_available_filter_functions_addrs();
11587 	char sym_name[500];
11588 	FILE *f;
11589 	int ret, err = 0;
11590 	unsigned long long sym_addr;
11591 
11592 	f = fopen(available_path, "re");
11593 	if (!f) {
11594 		err = -errno;
11595 		pr_warn("failed to open %s: %s\n", available_path, errstr(err));
11596 		return err;
11597 	}
11598 
11599 	while (true) {
11600 		ret = fscanf(f, "%llx %499s%*[^\n]\n", &sym_addr, sym_name);
11601 		if (ret == EOF && feof(f))
11602 			break;
11603 
11604 		if (ret != 2) {
11605 			pr_warn("failed to parse available_filter_functions_addrs entry: %d\n",
11606 				ret);
11607 			err = -EINVAL;
11608 			goto cleanup;
11609 		}
11610 
11611 		if (!glob_match(sym_name, res->pattern))
11612 			continue;
11613 
11614 		err = libbpf_ensure_mem((void **)&res->addrs, &res->cap,
11615 					sizeof(*res->addrs), res->cnt + 1);
11616 		if (err)
11617 			goto cleanup;
11618 
11619 		res->addrs[res->cnt++] = (unsigned long)sym_addr;
11620 	}
11621 
11622 	if (res->cnt == 0)
11623 		err = -ENOENT;
11624 
11625 cleanup:
11626 	fclose(f);
11627 	return err;
11628 }
11629 
11630 struct bpf_link *
11631 bpf_program__attach_kprobe_multi_opts(const struct bpf_program *prog,
11632 				      const char *pattern,
11633 				      const struct bpf_kprobe_multi_opts *opts)
11634 {
11635 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
11636 	struct kprobe_multi_resolve res = {
11637 		.pattern = pattern,
11638 	};
11639 	enum bpf_attach_type attach_type;
11640 	struct bpf_link *link = NULL;
11641 	const unsigned long *addrs;
11642 	int err, link_fd, prog_fd;
11643 	bool retprobe, session, unique_match;
11644 	const __u64 *cookies;
11645 	const char **syms;
11646 	size_t cnt;
11647 
11648 	if (!OPTS_VALID(opts, bpf_kprobe_multi_opts))
11649 		return libbpf_err_ptr(-EINVAL);
11650 
11651 	prog_fd = bpf_program__fd(prog);
11652 	if (prog_fd < 0) {
11653 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
11654 			prog->name);
11655 		return libbpf_err_ptr(-EINVAL);
11656 	}
11657 
11658 	syms    = OPTS_GET(opts, syms, false);
11659 	addrs   = OPTS_GET(opts, addrs, false);
11660 	cnt     = OPTS_GET(opts, cnt, false);
11661 	cookies = OPTS_GET(opts, cookies, false);
11662 	unique_match = OPTS_GET(opts, unique_match, false);
11663 
11664 	if (!pattern && !addrs && !syms)
11665 		return libbpf_err_ptr(-EINVAL);
11666 	if (pattern && (addrs || syms || cookies || cnt))
11667 		return libbpf_err_ptr(-EINVAL);
11668 	if (!pattern && !cnt)
11669 		return libbpf_err_ptr(-EINVAL);
11670 	if (!pattern && unique_match)
11671 		return libbpf_err_ptr(-EINVAL);
11672 	if (addrs && syms)
11673 		return libbpf_err_ptr(-EINVAL);
11674 
11675 	if (pattern) {
11676 		if (has_available_filter_functions_addrs())
11677 			err = libbpf_available_kprobes_parse(&res);
11678 		else
11679 			err = libbpf_available_kallsyms_parse(&res);
11680 		if (err)
11681 			goto error;
11682 
11683 		if (unique_match && res.cnt != 1) {
11684 			pr_warn("prog '%s': failed to find a unique match for '%s' (%zu matches)\n",
11685 				prog->name, pattern, res.cnt);
11686 			err = -EINVAL;
11687 			goto error;
11688 		}
11689 
11690 		addrs = res.addrs;
11691 		cnt = res.cnt;
11692 	}
11693 
11694 	retprobe = OPTS_GET(opts, retprobe, false);
11695 	session  = OPTS_GET(opts, session, false);
11696 
11697 	if (retprobe && session)
11698 		return libbpf_err_ptr(-EINVAL);
11699 
11700 	attach_type = session ? BPF_TRACE_KPROBE_SESSION : BPF_TRACE_KPROBE_MULTI;
11701 
11702 	lopts.kprobe_multi.syms = syms;
11703 	lopts.kprobe_multi.addrs = addrs;
11704 	lopts.kprobe_multi.cookies = cookies;
11705 	lopts.kprobe_multi.cnt = cnt;
11706 	lopts.kprobe_multi.flags = retprobe ? BPF_F_KPROBE_MULTI_RETURN : 0;
11707 
11708 	link = calloc(1, sizeof(*link));
11709 	if (!link) {
11710 		err = -ENOMEM;
11711 		goto error;
11712 	}
11713 	link->detach = &bpf_link__detach_fd;
11714 
11715 	link_fd = bpf_link_create(prog_fd, 0, attach_type, &lopts);
11716 	if (link_fd < 0) {
11717 		err = -errno;
11718 		pr_warn("prog '%s': failed to attach: %s\n",
11719 			prog->name, errstr(err));
11720 		goto error;
11721 	}
11722 	link->fd = link_fd;
11723 	free(res.addrs);
11724 	return link;
11725 
11726 error:
11727 	free(link);
11728 	free(res.addrs);
11729 	return libbpf_err_ptr(err);
11730 }
11731 
11732 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11733 {
11734 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts);
11735 	unsigned long offset = 0;
11736 	const char *func_name;
11737 	char *func;
11738 	int n;
11739 
11740 	*link = NULL;
11741 
11742 	/* no auto-attach for SEC("kprobe") and SEC("kretprobe") */
11743 	if (strcmp(prog->sec_name, "kprobe") == 0 || strcmp(prog->sec_name, "kretprobe") == 0)
11744 		return 0;
11745 
11746 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe/");
11747 	if (opts.retprobe)
11748 		func_name = prog->sec_name + sizeof("kretprobe/") - 1;
11749 	else
11750 		func_name = prog->sec_name + sizeof("kprobe/") - 1;
11751 
11752 	n = sscanf(func_name, "%m[a-zA-Z0-9_.]+%li", &func, &offset);
11753 	if (n < 1) {
11754 		pr_warn("kprobe name is invalid: %s\n", func_name);
11755 		return -EINVAL;
11756 	}
11757 	if (opts.retprobe && offset != 0) {
11758 		free(func);
11759 		pr_warn("kretprobes do not support offset specification\n");
11760 		return -EINVAL;
11761 	}
11762 
11763 	opts.offset = offset;
11764 	*link = bpf_program__attach_kprobe_opts(prog, func, &opts);
11765 	free(func);
11766 	return libbpf_get_error(*link);
11767 }
11768 
11769 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11770 {
11771 	LIBBPF_OPTS(bpf_ksyscall_opts, opts);
11772 	const char *syscall_name;
11773 
11774 	*link = NULL;
11775 
11776 	/* no auto-attach for SEC("ksyscall") and SEC("kretsyscall") */
11777 	if (strcmp(prog->sec_name, "ksyscall") == 0 || strcmp(prog->sec_name, "kretsyscall") == 0)
11778 		return 0;
11779 
11780 	opts.retprobe = str_has_pfx(prog->sec_name, "kretsyscall/");
11781 	if (opts.retprobe)
11782 		syscall_name = prog->sec_name + sizeof("kretsyscall/") - 1;
11783 	else
11784 		syscall_name = prog->sec_name + sizeof("ksyscall/") - 1;
11785 
11786 	*link = bpf_program__attach_ksyscall(prog, syscall_name, &opts);
11787 	return *link ? 0 : -errno;
11788 }
11789 
11790 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11791 {
11792 	LIBBPF_OPTS(bpf_kprobe_multi_opts, opts);
11793 	const char *spec;
11794 	char *pattern;
11795 	int n;
11796 
11797 	*link = NULL;
11798 
11799 	/* no auto-attach for SEC("kprobe.multi") and SEC("kretprobe.multi") */
11800 	if (strcmp(prog->sec_name, "kprobe.multi") == 0 ||
11801 	    strcmp(prog->sec_name, "kretprobe.multi") == 0)
11802 		return 0;
11803 
11804 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe.multi/");
11805 	if (opts.retprobe)
11806 		spec = prog->sec_name + sizeof("kretprobe.multi/") - 1;
11807 	else
11808 		spec = prog->sec_name + sizeof("kprobe.multi/") - 1;
11809 
11810 	n = sscanf(spec, "%m[a-zA-Z0-9_.*?]", &pattern);
11811 	if (n < 1) {
11812 		pr_warn("kprobe multi pattern is invalid: %s\n", spec);
11813 		return -EINVAL;
11814 	}
11815 
11816 	*link = bpf_program__attach_kprobe_multi_opts(prog, pattern, &opts);
11817 	free(pattern);
11818 	return libbpf_get_error(*link);
11819 }
11820 
11821 static int attach_kprobe_session(const struct bpf_program *prog, long cookie,
11822 				 struct bpf_link **link)
11823 {
11824 	LIBBPF_OPTS(bpf_kprobe_multi_opts, opts, .session = true);
11825 	const char *spec;
11826 	char *pattern;
11827 	int n;
11828 
11829 	*link = NULL;
11830 
11831 	/* no auto-attach for SEC("kprobe.session") */
11832 	if (strcmp(prog->sec_name, "kprobe.session") == 0)
11833 		return 0;
11834 
11835 	spec = prog->sec_name + sizeof("kprobe.session/") - 1;
11836 	n = sscanf(spec, "%m[a-zA-Z0-9_.*?]", &pattern);
11837 	if (n < 1) {
11838 		pr_warn("kprobe session pattern is invalid: %s\n", spec);
11839 		return -EINVAL;
11840 	}
11841 
11842 	*link = bpf_program__attach_kprobe_multi_opts(prog, pattern, &opts);
11843 	free(pattern);
11844 	return *link ? 0 : -errno;
11845 }
11846 
11847 static int attach_uprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11848 {
11849 	char *probe_type = NULL, *binary_path = NULL, *func_name = NULL;
11850 	LIBBPF_OPTS(bpf_uprobe_multi_opts, opts);
11851 	int n, ret = -EINVAL;
11852 
11853 	*link = NULL;
11854 
11855 	n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[^\n]",
11856 		   &probe_type, &binary_path, &func_name);
11857 	switch (n) {
11858 	case 1:
11859 		/* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
11860 		ret = 0;
11861 		break;
11862 	case 3:
11863 		opts.session = str_has_pfx(probe_type, "uprobe.session");
11864 		opts.retprobe = str_has_pfx(probe_type, "uretprobe.multi");
11865 
11866 		*link = bpf_program__attach_uprobe_multi(prog, -1, binary_path, func_name, &opts);
11867 		ret = libbpf_get_error(*link);
11868 		break;
11869 	default:
11870 		pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
11871 			prog->sec_name);
11872 		break;
11873 	}
11874 	free(probe_type);
11875 	free(binary_path);
11876 	free(func_name);
11877 	return ret;
11878 }
11879 
11880 static inline int add_uprobe_event_legacy(const char *probe_name, bool retprobe,
11881 					  const char *binary_path, size_t offset)
11882 {
11883 	return append_to_file(tracefs_uprobe_events(), "%c:%s/%s %s:0x%zx",
11884 			      retprobe ? 'r' : 'p',
11885 			      retprobe ? "uretprobes" : "uprobes",
11886 			      probe_name, binary_path, offset);
11887 }
11888 
11889 static inline int remove_uprobe_event_legacy(const char *probe_name, bool retprobe)
11890 {
11891 	return append_to_file(tracefs_uprobe_events(), "-:%s/%s",
11892 			      retprobe ? "uretprobes" : "uprobes", probe_name);
11893 }
11894 
11895 static int determine_uprobe_perf_type_legacy(const char *probe_name, bool retprobe)
11896 {
11897 	char file[512];
11898 
11899 	snprintf(file, sizeof(file), "%s/events/%s/%s/id",
11900 		 tracefs_path(), retprobe ? "uretprobes" : "uprobes", probe_name);
11901 
11902 	return parse_uint_from_file(file, "%d\n");
11903 }
11904 
11905 static int perf_event_uprobe_open_legacy(const char *probe_name, bool retprobe,
11906 					 const char *binary_path, size_t offset, int pid)
11907 {
11908 	const size_t attr_sz = sizeof(struct perf_event_attr);
11909 	struct perf_event_attr attr;
11910 	int type, pfd, err;
11911 
11912 	err = add_uprobe_event_legacy(probe_name, retprobe, binary_path, offset);
11913 	if (err < 0) {
11914 		pr_warn("failed to add legacy uprobe event for %s:0x%zx: %s\n",
11915 			binary_path, (size_t)offset, errstr(err));
11916 		return err;
11917 	}
11918 	type = determine_uprobe_perf_type_legacy(probe_name, retprobe);
11919 	if (type < 0) {
11920 		err = type;
11921 		pr_warn("failed to determine legacy uprobe event id for %s:0x%zx: %s\n",
11922 			binary_path, offset, errstr(err));
11923 		goto err_clean_legacy;
11924 	}
11925 
11926 	memset(&attr, 0, attr_sz);
11927 	attr.size = attr_sz;
11928 	attr.config = type;
11929 	attr.type = PERF_TYPE_TRACEPOINT;
11930 
11931 	pfd = syscall(__NR_perf_event_open, &attr,
11932 		      pid < 0 ? -1 : pid, /* pid */
11933 		      pid == -1 ? 0 : -1, /* cpu */
11934 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
11935 	if (pfd < 0) {
11936 		err = -errno;
11937 		pr_warn("legacy uprobe perf_event_open() failed: %s\n", errstr(err));
11938 		goto err_clean_legacy;
11939 	}
11940 	return pfd;
11941 
11942 err_clean_legacy:
11943 	/* Clear the newly added legacy uprobe_event */
11944 	remove_uprobe_event_legacy(probe_name, retprobe);
11945 	return err;
11946 }
11947 
11948 /* Find offset of function name in archive specified by path. Currently
11949  * supported are .zip files that do not compress their contents, as used on
11950  * Android in the form of APKs, for example. "file_name" is the name of the ELF
11951  * file inside the archive. "func_name" matches symbol name or name@@LIB for
11952  * library functions.
11953  *
11954  * An overview of the APK format specifically provided here:
11955  * https://en.wikipedia.org/w/index.php?title=Apk_(file_format)&oldid=1139099120#Package_contents
11956  */
11957 static long elf_find_func_offset_from_archive(const char *archive_path, const char *file_name,
11958 					      const char *func_name)
11959 {
11960 	struct zip_archive *archive;
11961 	struct zip_entry entry;
11962 	long ret;
11963 	Elf *elf;
11964 
11965 	archive = zip_archive_open(archive_path);
11966 	if (IS_ERR(archive)) {
11967 		ret = PTR_ERR(archive);
11968 		pr_warn("zip: failed to open %s: %ld\n", archive_path, ret);
11969 		return ret;
11970 	}
11971 
11972 	ret = zip_archive_find_entry(archive, file_name, &entry);
11973 	if (ret) {
11974 		pr_warn("zip: could not find archive member %s in %s: %ld\n", file_name,
11975 			archive_path, ret);
11976 		goto out;
11977 	}
11978 	pr_debug("zip: found entry for %s in %s at 0x%lx\n", file_name, archive_path,
11979 		 (unsigned long)entry.data_offset);
11980 
11981 	if (entry.compression) {
11982 		pr_warn("zip: entry %s of %s is compressed and cannot be handled\n", file_name,
11983 			archive_path);
11984 		ret = -LIBBPF_ERRNO__FORMAT;
11985 		goto out;
11986 	}
11987 
11988 	elf = elf_memory((void *)entry.data, entry.data_length);
11989 	if (!elf) {
11990 		pr_warn("elf: could not read elf file %s from %s: %s\n", file_name, archive_path,
11991 			elf_errmsg(-1));
11992 		ret = -LIBBPF_ERRNO__LIBELF;
11993 		goto out;
11994 	}
11995 
11996 	ret = elf_find_func_offset(elf, file_name, func_name);
11997 	if (ret > 0) {
11998 		pr_debug("elf: symbol address match for %s of %s in %s: 0x%x + 0x%lx = 0x%lx\n",
11999 			 func_name, file_name, archive_path, entry.data_offset, ret,
12000 			 ret + entry.data_offset);
12001 		ret += entry.data_offset;
12002 	}
12003 	elf_end(elf);
12004 
12005 out:
12006 	zip_archive_close(archive);
12007 	return ret;
12008 }
12009 
12010 static const char *arch_specific_lib_paths(void)
12011 {
12012 	/*
12013 	 * Based on https://packages.debian.org/sid/libc6.
12014 	 *
12015 	 * Assume that the traced program is built for the same architecture
12016 	 * as libbpf, which should cover the vast majority of cases.
12017 	 */
12018 #if defined(__x86_64__)
12019 	return "/lib/x86_64-linux-gnu";
12020 #elif defined(__i386__)
12021 	return "/lib/i386-linux-gnu";
12022 #elif defined(__s390x__)
12023 	return "/lib/s390x-linux-gnu";
12024 #elif defined(__s390__)
12025 	return "/lib/s390-linux-gnu";
12026 #elif defined(__arm__) && defined(__SOFTFP__)
12027 	return "/lib/arm-linux-gnueabi";
12028 #elif defined(__arm__) && !defined(__SOFTFP__)
12029 	return "/lib/arm-linux-gnueabihf";
12030 #elif defined(__aarch64__)
12031 	return "/lib/aarch64-linux-gnu";
12032 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 64
12033 	return "/lib/mips64el-linux-gnuabi64";
12034 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 32
12035 	return "/lib/mipsel-linux-gnu";
12036 #elif defined(__powerpc64__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
12037 	return "/lib/powerpc64le-linux-gnu";
12038 #elif defined(__sparc__) && defined(__arch64__)
12039 	return "/lib/sparc64-linux-gnu";
12040 #elif defined(__riscv) && __riscv_xlen == 64
12041 	return "/lib/riscv64-linux-gnu";
12042 #else
12043 	return NULL;
12044 #endif
12045 }
12046 
12047 /* Get full path to program/shared library. */
12048 static int resolve_full_path(const char *file, char *result, size_t result_sz)
12049 {
12050 	const char *search_paths[3] = {};
12051 	int i, perm;
12052 
12053 	if (str_has_sfx(file, ".so") || strstr(file, ".so.")) {
12054 		search_paths[0] = getenv("LD_LIBRARY_PATH");
12055 		search_paths[1] = "/usr/lib64:/usr/lib";
12056 		search_paths[2] = arch_specific_lib_paths();
12057 		perm = R_OK;
12058 	} else {
12059 		search_paths[0] = getenv("PATH");
12060 		search_paths[1] = "/usr/bin:/usr/sbin";
12061 		perm = R_OK | X_OK;
12062 	}
12063 
12064 	for (i = 0; i < ARRAY_SIZE(search_paths); i++) {
12065 		const char *s;
12066 
12067 		if (!search_paths[i])
12068 			continue;
12069 		for (s = search_paths[i]; s != NULL; s = strchr(s, ':')) {
12070 			char *next_path;
12071 			int seg_len;
12072 
12073 			if (s[0] == ':')
12074 				s++;
12075 			next_path = strchr(s, ':');
12076 			seg_len = next_path ? next_path - s : strlen(s);
12077 			if (!seg_len)
12078 				continue;
12079 			snprintf(result, result_sz, "%.*s/%s", seg_len, s, file);
12080 			/* ensure it has required permissions */
12081 			if (faccessat(AT_FDCWD, result, perm, AT_EACCESS) < 0)
12082 				continue;
12083 			pr_debug("resolved '%s' to '%s'\n", file, result);
12084 			return 0;
12085 		}
12086 	}
12087 	return -ENOENT;
12088 }
12089 
12090 struct bpf_link *
12091 bpf_program__attach_uprobe_multi(const struct bpf_program *prog,
12092 				 pid_t pid,
12093 				 const char *path,
12094 				 const char *func_pattern,
12095 				 const struct bpf_uprobe_multi_opts *opts)
12096 {
12097 	const unsigned long *ref_ctr_offsets = NULL, *offsets = NULL;
12098 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
12099 	unsigned long *resolved_offsets = NULL;
12100 	enum bpf_attach_type attach_type;
12101 	int err = 0, link_fd, prog_fd;
12102 	struct bpf_link *link = NULL;
12103 	char full_path[PATH_MAX];
12104 	bool retprobe, session;
12105 	const __u64 *cookies;
12106 	const char **syms;
12107 	size_t cnt;
12108 
12109 	if (!OPTS_VALID(opts, bpf_uprobe_multi_opts))
12110 		return libbpf_err_ptr(-EINVAL);
12111 
12112 	prog_fd = bpf_program__fd(prog);
12113 	if (prog_fd < 0) {
12114 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
12115 			prog->name);
12116 		return libbpf_err_ptr(-EINVAL);
12117 	}
12118 
12119 	syms = OPTS_GET(opts, syms, NULL);
12120 	offsets = OPTS_GET(opts, offsets, NULL);
12121 	ref_ctr_offsets = OPTS_GET(opts, ref_ctr_offsets, NULL);
12122 	cookies = OPTS_GET(opts, cookies, NULL);
12123 	cnt = OPTS_GET(opts, cnt, 0);
12124 	retprobe = OPTS_GET(opts, retprobe, false);
12125 	session  = OPTS_GET(opts, session, false);
12126 
12127 	/*
12128 	 * User can specify 2 mutually exclusive set of inputs:
12129 	 *
12130 	 * 1) use only path/func_pattern/pid arguments
12131 	 *
12132 	 * 2) use path/pid with allowed combinations of:
12133 	 *    syms/offsets/ref_ctr_offsets/cookies/cnt
12134 	 *
12135 	 *    - syms and offsets are mutually exclusive
12136 	 *    - ref_ctr_offsets and cookies are optional
12137 	 *
12138 	 * Any other usage results in error.
12139 	 */
12140 
12141 	if (!path)
12142 		return libbpf_err_ptr(-EINVAL);
12143 	if (!func_pattern && cnt == 0)
12144 		return libbpf_err_ptr(-EINVAL);
12145 
12146 	if (func_pattern) {
12147 		if (syms || offsets || ref_ctr_offsets || cookies || cnt)
12148 			return libbpf_err_ptr(-EINVAL);
12149 	} else {
12150 		if (!!syms == !!offsets)
12151 			return libbpf_err_ptr(-EINVAL);
12152 	}
12153 
12154 	if (retprobe && session)
12155 		return libbpf_err_ptr(-EINVAL);
12156 
12157 	if (func_pattern) {
12158 		if (!strchr(path, '/')) {
12159 			err = resolve_full_path(path, full_path, sizeof(full_path));
12160 			if (err) {
12161 				pr_warn("prog '%s': failed to resolve full path for '%s': %s\n",
12162 					prog->name, path, errstr(err));
12163 				return libbpf_err_ptr(err);
12164 			}
12165 			path = full_path;
12166 		}
12167 
12168 		err = elf_resolve_pattern_offsets(path, func_pattern,
12169 						  &resolved_offsets, &cnt);
12170 		if (err < 0)
12171 			return libbpf_err_ptr(err);
12172 		offsets = resolved_offsets;
12173 	} else if (syms) {
12174 		err = elf_resolve_syms_offsets(path, cnt, syms, &resolved_offsets, STT_FUNC);
12175 		if (err < 0)
12176 			return libbpf_err_ptr(err);
12177 		offsets = resolved_offsets;
12178 	}
12179 
12180 	attach_type = session ? BPF_TRACE_UPROBE_SESSION : BPF_TRACE_UPROBE_MULTI;
12181 
12182 	lopts.uprobe_multi.path = path;
12183 	lopts.uprobe_multi.offsets = offsets;
12184 	lopts.uprobe_multi.ref_ctr_offsets = ref_ctr_offsets;
12185 	lopts.uprobe_multi.cookies = cookies;
12186 	lopts.uprobe_multi.cnt = cnt;
12187 	lopts.uprobe_multi.flags = retprobe ? BPF_F_UPROBE_MULTI_RETURN : 0;
12188 
12189 	if (pid == 0)
12190 		pid = getpid();
12191 	if (pid > 0)
12192 		lopts.uprobe_multi.pid = pid;
12193 
12194 	link = calloc(1, sizeof(*link));
12195 	if (!link) {
12196 		err = -ENOMEM;
12197 		goto error;
12198 	}
12199 	link->detach = &bpf_link__detach_fd;
12200 
12201 	link_fd = bpf_link_create(prog_fd, 0, attach_type, &lopts);
12202 	if (link_fd < 0) {
12203 		err = -errno;
12204 		pr_warn("prog '%s': failed to attach multi-uprobe: %s\n",
12205 			prog->name, errstr(err));
12206 		goto error;
12207 	}
12208 	link->fd = link_fd;
12209 	free(resolved_offsets);
12210 	return link;
12211 
12212 error:
12213 	free(resolved_offsets);
12214 	free(link);
12215 	return libbpf_err_ptr(err);
12216 }
12217 
12218 LIBBPF_API struct bpf_link *
12219 bpf_program__attach_uprobe_opts(const struct bpf_program *prog, pid_t pid,
12220 				const char *binary_path, size_t func_offset,
12221 				const struct bpf_uprobe_opts *opts)
12222 {
12223 	const char *archive_path = NULL, *archive_sep = NULL;
12224 	char *legacy_probe = NULL;
12225 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
12226 	enum probe_attach_mode attach_mode;
12227 	char full_path[PATH_MAX];
12228 	struct bpf_link *link;
12229 	size_t ref_ctr_off;
12230 	int pfd, err;
12231 	bool retprobe, legacy;
12232 	const char *func_name;
12233 
12234 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
12235 		return libbpf_err_ptr(-EINVAL);
12236 
12237 	attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
12238 	retprobe = OPTS_GET(opts, retprobe, false);
12239 	ref_ctr_off = OPTS_GET(opts, ref_ctr_offset, 0);
12240 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
12241 
12242 	if (!binary_path)
12243 		return libbpf_err_ptr(-EINVAL);
12244 
12245 	/* Check if "binary_path" refers to an archive. */
12246 	archive_sep = strstr(binary_path, "!/");
12247 	if (archive_sep) {
12248 		full_path[0] = '\0';
12249 		libbpf_strlcpy(full_path, binary_path,
12250 			       min(sizeof(full_path), (size_t)(archive_sep - binary_path + 1)));
12251 		archive_path = full_path;
12252 		binary_path = archive_sep + 2;
12253 	} else if (!strchr(binary_path, '/')) {
12254 		err = resolve_full_path(binary_path, full_path, sizeof(full_path));
12255 		if (err) {
12256 			pr_warn("prog '%s': failed to resolve full path for '%s': %s\n",
12257 				prog->name, binary_path, errstr(err));
12258 			return libbpf_err_ptr(err);
12259 		}
12260 		binary_path = full_path;
12261 	}
12262 	func_name = OPTS_GET(opts, func_name, NULL);
12263 	if (func_name) {
12264 		long sym_off;
12265 
12266 		if (archive_path) {
12267 			sym_off = elf_find_func_offset_from_archive(archive_path, binary_path,
12268 								    func_name);
12269 			binary_path = archive_path;
12270 		} else {
12271 			sym_off = elf_find_func_offset_from_file(binary_path, func_name);
12272 		}
12273 		if (sym_off < 0)
12274 			return libbpf_err_ptr(sym_off);
12275 		func_offset += sym_off;
12276 	}
12277 
12278 	legacy = determine_uprobe_perf_type() < 0;
12279 	switch (attach_mode) {
12280 	case PROBE_ATTACH_MODE_LEGACY:
12281 		legacy = true;
12282 		pe_opts.force_ioctl_attach = true;
12283 		break;
12284 	case PROBE_ATTACH_MODE_PERF:
12285 		if (legacy)
12286 			return libbpf_err_ptr(-ENOTSUP);
12287 		pe_opts.force_ioctl_attach = true;
12288 		break;
12289 	case PROBE_ATTACH_MODE_LINK:
12290 		if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
12291 			return libbpf_err_ptr(-ENOTSUP);
12292 		break;
12293 	case PROBE_ATTACH_MODE_DEFAULT:
12294 		break;
12295 	default:
12296 		return libbpf_err_ptr(-EINVAL);
12297 	}
12298 
12299 	if (!legacy) {
12300 		pfd = perf_event_open_probe(true /* uprobe */, retprobe, binary_path,
12301 					    func_offset, pid, ref_ctr_off);
12302 	} else {
12303 		char probe_name[MAX_EVENT_NAME_LEN];
12304 
12305 		if (ref_ctr_off)
12306 			return libbpf_err_ptr(-EINVAL);
12307 
12308 		gen_probe_legacy_event_name(probe_name, sizeof(probe_name),
12309 					    strrchr(binary_path, '/') ? : binary_path,
12310 					    func_offset);
12311 
12312 		legacy_probe = strdup(probe_name);
12313 		if (!legacy_probe)
12314 			return libbpf_err_ptr(-ENOMEM);
12315 
12316 		pfd = perf_event_uprobe_open_legacy(legacy_probe, retprobe,
12317 						    binary_path, func_offset, pid);
12318 	}
12319 	if (pfd < 0) {
12320 		err = -errno;
12321 		pr_warn("prog '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
12322 			prog->name, retprobe ? "uretprobe" : "uprobe",
12323 			binary_path, func_offset,
12324 			errstr(err));
12325 		goto err_out;
12326 	}
12327 
12328 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
12329 	err = libbpf_get_error(link);
12330 	if (err) {
12331 		close(pfd);
12332 		pr_warn("prog '%s': failed to attach to %s '%s:0x%zx': %s\n",
12333 			prog->name, retprobe ? "uretprobe" : "uprobe",
12334 			binary_path, func_offset,
12335 			errstr(err));
12336 		goto err_clean_legacy;
12337 	}
12338 	if (legacy) {
12339 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
12340 
12341 		perf_link->legacy_probe_name = legacy_probe;
12342 		perf_link->legacy_is_kprobe = false;
12343 		perf_link->legacy_is_retprobe = retprobe;
12344 	}
12345 	return link;
12346 
12347 err_clean_legacy:
12348 	if (legacy)
12349 		remove_uprobe_event_legacy(legacy_probe, retprobe);
12350 err_out:
12351 	free(legacy_probe);
12352 	return libbpf_err_ptr(err);
12353 }
12354 
12355 /* Format of u[ret]probe section definition supporting auto-attach:
12356  * u[ret]probe/binary:function[+offset]
12357  *
12358  * binary can be an absolute/relative path or a filename; the latter is resolved to a
12359  * full binary path via bpf_program__attach_uprobe_opts.
12360  *
12361  * Specifying uprobe+ ensures we carry out strict matching; either "uprobe" must be
12362  * specified (and auto-attach is not possible) or the above format is specified for
12363  * auto-attach.
12364  */
12365 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12366 {
12367 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts);
12368 	char *probe_type = NULL, *binary_path = NULL, *func_name = NULL, *func_off;
12369 	int n, c, ret = -EINVAL;
12370 	long offset = 0;
12371 
12372 	*link = NULL;
12373 
12374 	n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[^\n]",
12375 		   &probe_type, &binary_path, &func_name);
12376 	switch (n) {
12377 	case 1:
12378 		/* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
12379 		ret = 0;
12380 		break;
12381 	case 2:
12382 		pr_warn("prog '%s': section '%s' missing ':function[+offset]' specification\n",
12383 			prog->name, prog->sec_name);
12384 		break;
12385 	case 3:
12386 		/* check if user specifies `+offset`, if yes, this should be
12387 		 * the last part of the string, make sure sscanf read to EOL
12388 		 */
12389 		func_off = strrchr(func_name, '+');
12390 		if (func_off) {
12391 			n = sscanf(func_off, "+%li%n", &offset, &c);
12392 			if (n == 1 && *(func_off + c) == '\0')
12393 				func_off[0] = '\0';
12394 			else
12395 				offset = 0;
12396 		}
12397 		opts.retprobe = strcmp(probe_type, "uretprobe") == 0 ||
12398 				strcmp(probe_type, "uretprobe.s") == 0;
12399 		if (opts.retprobe && offset != 0) {
12400 			pr_warn("prog '%s': uretprobes do not support offset specification\n",
12401 				prog->name);
12402 			break;
12403 		}
12404 		opts.func_name = func_name;
12405 		*link = bpf_program__attach_uprobe_opts(prog, -1, binary_path, offset, &opts);
12406 		ret = libbpf_get_error(*link);
12407 		break;
12408 	default:
12409 		pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
12410 			prog->sec_name);
12411 		break;
12412 	}
12413 	free(probe_type);
12414 	free(binary_path);
12415 	free(func_name);
12416 
12417 	return ret;
12418 }
12419 
12420 struct bpf_link *bpf_program__attach_uprobe(const struct bpf_program *prog,
12421 					    bool retprobe, pid_t pid,
12422 					    const char *binary_path,
12423 					    size_t func_offset)
12424 {
12425 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts, .retprobe = retprobe);
12426 
12427 	return bpf_program__attach_uprobe_opts(prog, pid, binary_path, func_offset, &opts);
12428 }
12429 
12430 struct bpf_link *bpf_program__attach_usdt(const struct bpf_program *prog,
12431 					  pid_t pid, const char *binary_path,
12432 					  const char *usdt_provider, const char *usdt_name,
12433 					  const struct bpf_usdt_opts *opts)
12434 {
12435 	char resolved_path[512];
12436 	struct bpf_object *obj = prog->obj;
12437 	struct bpf_link *link;
12438 	__u64 usdt_cookie;
12439 	int err;
12440 
12441 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
12442 		return libbpf_err_ptr(-EINVAL);
12443 
12444 	if (bpf_program__fd(prog) < 0) {
12445 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
12446 			prog->name);
12447 		return libbpf_err_ptr(-EINVAL);
12448 	}
12449 
12450 	if (!binary_path)
12451 		return libbpf_err_ptr(-EINVAL);
12452 
12453 	if (!strchr(binary_path, '/')) {
12454 		err = resolve_full_path(binary_path, resolved_path, sizeof(resolved_path));
12455 		if (err) {
12456 			pr_warn("prog '%s': failed to resolve full path for '%s': %s\n",
12457 				prog->name, binary_path, errstr(err));
12458 			return libbpf_err_ptr(err);
12459 		}
12460 		binary_path = resolved_path;
12461 	}
12462 
12463 	/* USDT manager is instantiated lazily on first USDT attach. It will
12464 	 * be destroyed together with BPF object in bpf_object__close().
12465 	 */
12466 	if (IS_ERR(obj->usdt_man))
12467 		return libbpf_ptr(obj->usdt_man);
12468 	if (!obj->usdt_man) {
12469 		obj->usdt_man = usdt_manager_new(obj);
12470 		if (IS_ERR(obj->usdt_man))
12471 			return libbpf_ptr(obj->usdt_man);
12472 	}
12473 
12474 	usdt_cookie = OPTS_GET(opts, usdt_cookie, 0);
12475 	link = usdt_manager_attach_usdt(obj->usdt_man, prog, pid, binary_path,
12476 					usdt_provider, usdt_name, usdt_cookie);
12477 	err = libbpf_get_error(link);
12478 	if (err)
12479 		return libbpf_err_ptr(err);
12480 	return link;
12481 }
12482 
12483 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12484 {
12485 	char *path = NULL, *provider = NULL, *name = NULL;
12486 	const char *sec_name;
12487 	int n, err;
12488 
12489 	sec_name = bpf_program__section_name(prog);
12490 	if (strcmp(sec_name, "usdt") == 0) {
12491 		/* no auto-attach for just SEC("usdt") */
12492 		*link = NULL;
12493 		return 0;
12494 	}
12495 
12496 	n = sscanf(sec_name, "usdt/%m[^:]:%m[^:]:%m[^:]", &path, &provider, &name);
12497 	if (n != 3) {
12498 		pr_warn("invalid section '%s', expected SEC(\"usdt/<path>:<provider>:<name>\")\n",
12499 			sec_name);
12500 		err = -EINVAL;
12501 	} else {
12502 		*link = bpf_program__attach_usdt(prog, -1 /* any process */, path,
12503 						 provider, name, NULL);
12504 		err = libbpf_get_error(*link);
12505 	}
12506 	free(path);
12507 	free(provider);
12508 	free(name);
12509 	return err;
12510 }
12511 
12512 static int determine_tracepoint_id(const char *tp_category,
12513 				   const char *tp_name)
12514 {
12515 	char file[PATH_MAX];
12516 	int ret;
12517 
12518 	ret = snprintf(file, sizeof(file), "%s/events/%s/%s/id",
12519 		       tracefs_path(), tp_category, tp_name);
12520 	if (ret < 0)
12521 		return -errno;
12522 	if (ret >= sizeof(file)) {
12523 		pr_debug("tracepoint %s/%s path is too long\n",
12524 			 tp_category, tp_name);
12525 		return -E2BIG;
12526 	}
12527 	return parse_uint_from_file(file, "%d\n");
12528 }
12529 
12530 static int perf_event_open_tracepoint(const char *tp_category,
12531 				      const char *tp_name)
12532 {
12533 	const size_t attr_sz = sizeof(struct perf_event_attr);
12534 	struct perf_event_attr attr;
12535 	int tp_id, pfd, err;
12536 
12537 	tp_id = determine_tracepoint_id(tp_category, tp_name);
12538 	if (tp_id < 0) {
12539 		pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
12540 			tp_category, tp_name,
12541 			errstr(tp_id));
12542 		return tp_id;
12543 	}
12544 
12545 	memset(&attr, 0, attr_sz);
12546 	attr.type = PERF_TYPE_TRACEPOINT;
12547 	attr.size = attr_sz;
12548 	attr.config = tp_id;
12549 
12550 	pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
12551 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
12552 	if (pfd < 0) {
12553 		err = -errno;
12554 		pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
12555 			tp_category, tp_name,
12556 			errstr(err));
12557 		return err;
12558 	}
12559 	return pfd;
12560 }
12561 
12562 struct bpf_link *bpf_program__attach_tracepoint_opts(const struct bpf_program *prog,
12563 						     const char *tp_category,
12564 						     const char *tp_name,
12565 						     const struct bpf_tracepoint_opts *opts)
12566 {
12567 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
12568 	struct bpf_link *link;
12569 	int pfd, err;
12570 
12571 	if (!OPTS_VALID(opts, bpf_tracepoint_opts))
12572 		return libbpf_err_ptr(-EINVAL);
12573 
12574 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
12575 
12576 	pfd = perf_event_open_tracepoint(tp_category, tp_name);
12577 	if (pfd < 0) {
12578 		pr_warn("prog '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
12579 			prog->name, tp_category, tp_name,
12580 			errstr(pfd));
12581 		return libbpf_err_ptr(pfd);
12582 	}
12583 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
12584 	err = libbpf_get_error(link);
12585 	if (err) {
12586 		close(pfd);
12587 		pr_warn("prog '%s': failed to attach to tracepoint '%s/%s': %s\n",
12588 			prog->name, tp_category, tp_name,
12589 			errstr(err));
12590 		return libbpf_err_ptr(err);
12591 	}
12592 	return link;
12593 }
12594 
12595 struct bpf_link *bpf_program__attach_tracepoint(const struct bpf_program *prog,
12596 						const char *tp_category,
12597 						const char *tp_name)
12598 {
12599 	return bpf_program__attach_tracepoint_opts(prog, tp_category, tp_name, NULL);
12600 }
12601 
12602 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12603 {
12604 	char *sec_name, *tp_cat, *tp_name;
12605 
12606 	*link = NULL;
12607 
12608 	/* no auto-attach for SEC("tp") or SEC("tracepoint") */
12609 	if (strcmp(prog->sec_name, "tp") == 0 || strcmp(prog->sec_name, "tracepoint") == 0)
12610 		return 0;
12611 
12612 	sec_name = strdup(prog->sec_name);
12613 	if (!sec_name)
12614 		return -ENOMEM;
12615 
12616 	/* extract "tp/<category>/<name>" or "tracepoint/<category>/<name>" */
12617 	if (str_has_pfx(prog->sec_name, "tp/"))
12618 		tp_cat = sec_name + sizeof("tp/") - 1;
12619 	else
12620 		tp_cat = sec_name + sizeof("tracepoint/") - 1;
12621 	tp_name = strchr(tp_cat, '/');
12622 	if (!tp_name) {
12623 		free(sec_name);
12624 		return -EINVAL;
12625 	}
12626 	*tp_name = '\0';
12627 	tp_name++;
12628 
12629 	*link = bpf_program__attach_tracepoint(prog, tp_cat, tp_name);
12630 	free(sec_name);
12631 	return libbpf_get_error(*link);
12632 }
12633 
12634 struct bpf_link *
12635 bpf_program__attach_raw_tracepoint_opts(const struct bpf_program *prog,
12636 					const char *tp_name,
12637 					struct bpf_raw_tracepoint_opts *opts)
12638 {
12639 	LIBBPF_OPTS(bpf_raw_tp_opts, raw_opts);
12640 	struct bpf_link *link;
12641 	int prog_fd, pfd;
12642 
12643 	if (!OPTS_VALID(opts, bpf_raw_tracepoint_opts))
12644 		return libbpf_err_ptr(-EINVAL);
12645 
12646 	prog_fd = bpf_program__fd(prog);
12647 	if (prog_fd < 0) {
12648 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12649 		return libbpf_err_ptr(-EINVAL);
12650 	}
12651 
12652 	link = calloc(1, sizeof(*link));
12653 	if (!link)
12654 		return libbpf_err_ptr(-ENOMEM);
12655 	link->detach = &bpf_link__detach_fd;
12656 
12657 	raw_opts.tp_name = tp_name;
12658 	raw_opts.cookie = OPTS_GET(opts, cookie, 0);
12659 	pfd = bpf_raw_tracepoint_open_opts(prog_fd, &raw_opts);
12660 	if (pfd < 0) {
12661 		pfd = -errno;
12662 		free(link);
12663 		pr_warn("prog '%s': failed to attach to raw tracepoint '%s': %s\n",
12664 			prog->name, tp_name, errstr(pfd));
12665 		return libbpf_err_ptr(pfd);
12666 	}
12667 	link->fd = pfd;
12668 	return link;
12669 }
12670 
12671 struct bpf_link *bpf_program__attach_raw_tracepoint(const struct bpf_program *prog,
12672 						    const char *tp_name)
12673 {
12674 	return bpf_program__attach_raw_tracepoint_opts(prog, tp_name, NULL);
12675 }
12676 
12677 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12678 {
12679 	static const char *const prefixes[] = {
12680 		"raw_tp",
12681 		"raw_tracepoint",
12682 		"raw_tp.w",
12683 		"raw_tracepoint.w",
12684 	};
12685 	size_t i;
12686 	const char *tp_name = NULL;
12687 
12688 	*link = NULL;
12689 
12690 	for (i = 0; i < ARRAY_SIZE(prefixes); i++) {
12691 		size_t pfx_len;
12692 
12693 		if (!str_has_pfx(prog->sec_name, prefixes[i]))
12694 			continue;
12695 
12696 		pfx_len = strlen(prefixes[i]);
12697 		/* no auto-attach case of, e.g., SEC("raw_tp") */
12698 		if (prog->sec_name[pfx_len] == '\0')
12699 			return 0;
12700 
12701 		if (prog->sec_name[pfx_len] != '/')
12702 			continue;
12703 
12704 		tp_name = prog->sec_name + pfx_len + 1;
12705 		break;
12706 	}
12707 
12708 	if (!tp_name) {
12709 		pr_warn("prog '%s': invalid section name '%s'\n",
12710 			prog->name, prog->sec_name);
12711 		return -EINVAL;
12712 	}
12713 
12714 	*link = bpf_program__attach_raw_tracepoint(prog, tp_name);
12715 	return libbpf_get_error(*link);
12716 }
12717 
12718 /* Common logic for all BPF program types that attach to a btf_id */
12719 static struct bpf_link *bpf_program__attach_btf_id(const struct bpf_program *prog,
12720 						   const struct bpf_trace_opts *opts)
12721 {
12722 	LIBBPF_OPTS(bpf_link_create_opts, link_opts);
12723 	struct bpf_link *link;
12724 	int prog_fd, pfd;
12725 
12726 	if (!OPTS_VALID(opts, bpf_trace_opts))
12727 		return libbpf_err_ptr(-EINVAL);
12728 
12729 	prog_fd = bpf_program__fd(prog);
12730 	if (prog_fd < 0) {
12731 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12732 		return libbpf_err_ptr(-EINVAL);
12733 	}
12734 
12735 	link = calloc(1, sizeof(*link));
12736 	if (!link)
12737 		return libbpf_err_ptr(-ENOMEM);
12738 	link->detach = &bpf_link__detach_fd;
12739 
12740 	/* libbpf is smart enough to redirect to BPF_RAW_TRACEPOINT_OPEN on old kernels */
12741 	link_opts.tracing.cookie = OPTS_GET(opts, cookie, 0);
12742 	pfd = bpf_link_create(prog_fd, 0, bpf_program__expected_attach_type(prog), &link_opts);
12743 	if (pfd < 0) {
12744 		pfd = -errno;
12745 		free(link);
12746 		pr_warn("prog '%s': failed to attach: %s\n",
12747 			prog->name, errstr(pfd));
12748 		return libbpf_err_ptr(pfd);
12749 	}
12750 	link->fd = pfd;
12751 	return link;
12752 }
12753 
12754 struct bpf_link *bpf_program__attach_trace(const struct bpf_program *prog)
12755 {
12756 	return bpf_program__attach_btf_id(prog, NULL);
12757 }
12758 
12759 struct bpf_link *bpf_program__attach_trace_opts(const struct bpf_program *prog,
12760 						const struct bpf_trace_opts *opts)
12761 {
12762 	return bpf_program__attach_btf_id(prog, opts);
12763 }
12764 
12765 struct bpf_link *bpf_program__attach_lsm(const struct bpf_program *prog)
12766 {
12767 	return bpf_program__attach_btf_id(prog, NULL);
12768 }
12769 
12770 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12771 {
12772 	*link = bpf_program__attach_trace(prog);
12773 	return libbpf_get_error(*link);
12774 }
12775 
12776 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12777 {
12778 	*link = bpf_program__attach_lsm(prog);
12779 	return libbpf_get_error(*link);
12780 }
12781 
12782 static struct bpf_link *
12783 bpf_program_attach_fd(const struct bpf_program *prog,
12784 		      int target_fd, const char *target_name,
12785 		      const struct bpf_link_create_opts *opts)
12786 {
12787 	enum bpf_attach_type attach_type;
12788 	struct bpf_link *link;
12789 	int prog_fd, link_fd;
12790 
12791 	prog_fd = bpf_program__fd(prog);
12792 	if (prog_fd < 0) {
12793 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12794 		return libbpf_err_ptr(-EINVAL);
12795 	}
12796 
12797 	link = calloc(1, sizeof(*link));
12798 	if (!link)
12799 		return libbpf_err_ptr(-ENOMEM);
12800 	link->detach = &bpf_link__detach_fd;
12801 
12802 	attach_type = bpf_program__expected_attach_type(prog);
12803 	link_fd = bpf_link_create(prog_fd, target_fd, attach_type, opts);
12804 	if (link_fd < 0) {
12805 		link_fd = -errno;
12806 		free(link);
12807 		pr_warn("prog '%s': failed to attach to %s: %s\n",
12808 			prog->name, target_name,
12809 			errstr(link_fd));
12810 		return libbpf_err_ptr(link_fd);
12811 	}
12812 	link->fd = link_fd;
12813 	return link;
12814 }
12815 
12816 struct bpf_link *
12817 bpf_program__attach_cgroup(const struct bpf_program *prog, int cgroup_fd)
12818 {
12819 	return bpf_program_attach_fd(prog, cgroup_fd, "cgroup", NULL);
12820 }
12821 
12822 struct bpf_link *
12823 bpf_program__attach_netns(const struct bpf_program *prog, int netns_fd)
12824 {
12825 	return bpf_program_attach_fd(prog, netns_fd, "netns", NULL);
12826 }
12827 
12828 struct bpf_link *
12829 bpf_program__attach_sockmap(const struct bpf_program *prog, int map_fd)
12830 {
12831 	return bpf_program_attach_fd(prog, map_fd, "sockmap", NULL);
12832 }
12833 
12834 struct bpf_link *bpf_program__attach_xdp(const struct bpf_program *prog, int ifindex)
12835 {
12836 	/* target_fd/target_ifindex use the same field in LINK_CREATE */
12837 	return bpf_program_attach_fd(prog, ifindex, "xdp", NULL);
12838 }
12839 
12840 struct bpf_link *
12841 bpf_program__attach_tcx(const struct bpf_program *prog, int ifindex,
12842 			const struct bpf_tcx_opts *opts)
12843 {
12844 	LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
12845 	__u32 relative_id;
12846 	int relative_fd;
12847 
12848 	if (!OPTS_VALID(opts, bpf_tcx_opts))
12849 		return libbpf_err_ptr(-EINVAL);
12850 
12851 	relative_id = OPTS_GET(opts, relative_id, 0);
12852 	relative_fd = OPTS_GET(opts, relative_fd, 0);
12853 
12854 	/* validate we don't have unexpected combinations of non-zero fields */
12855 	if (!ifindex) {
12856 		pr_warn("prog '%s': target netdevice ifindex cannot be zero\n",
12857 			prog->name);
12858 		return libbpf_err_ptr(-EINVAL);
12859 	}
12860 	if (relative_fd && relative_id) {
12861 		pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
12862 			prog->name);
12863 		return libbpf_err_ptr(-EINVAL);
12864 	}
12865 
12866 	link_create_opts.tcx.expected_revision = OPTS_GET(opts, expected_revision, 0);
12867 	link_create_opts.tcx.relative_fd = relative_fd;
12868 	link_create_opts.tcx.relative_id = relative_id;
12869 	link_create_opts.flags = OPTS_GET(opts, flags, 0);
12870 
12871 	/* target_fd/target_ifindex use the same field in LINK_CREATE */
12872 	return bpf_program_attach_fd(prog, ifindex, "tcx", &link_create_opts);
12873 }
12874 
12875 struct bpf_link *
12876 bpf_program__attach_netkit(const struct bpf_program *prog, int ifindex,
12877 			   const struct bpf_netkit_opts *opts)
12878 {
12879 	LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
12880 	__u32 relative_id;
12881 	int relative_fd;
12882 
12883 	if (!OPTS_VALID(opts, bpf_netkit_opts))
12884 		return libbpf_err_ptr(-EINVAL);
12885 
12886 	relative_id = OPTS_GET(opts, relative_id, 0);
12887 	relative_fd = OPTS_GET(opts, relative_fd, 0);
12888 
12889 	/* validate we don't have unexpected combinations of non-zero fields */
12890 	if (!ifindex) {
12891 		pr_warn("prog '%s': target netdevice ifindex cannot be zero\n",
12892 			prog->name);
12893 		return libbpf_err_ptr(-EINVAL);
12894 	}
12895 	if (relative_fd && relative_id) {
12896 		pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
12897 			prog->name);
12898 		return libbpf_err_ptr(-EINVAL);
12899 	}
12900 
12901 	link_create_opts.netkit.expected_revision = OPTS_GET(opts, expected_revision, 0);
12902 	link_create_opts.netkit.relative_fd = relative_fd;
12903 	link_create_opts.netkit.relative_id = relative_id;
12904 	link_create_opts.flags = OPTS_GET(opts, flags, 0);
12905 
12906 	return bpf_program_attach_fd(prog, ifindex, "netkit", &link_create_opts);
12907 }
12908 
12909 struct bpf_link *bpf_program__attach_freplace(const struct bpf_program *prog,
12910 					      int target_fd,
12911 					      const char *attach_func_name)
12912 {
12913 	int btf_id;
12914 
12915 	if (!!target_fd != !!attach_func_name) {
12916 		pr_warn("prog '%s': supply none or both of target_fd and attach_func_name\n",
12917 			prog->name);
12918 		return libbpf_err_ptr(-EINVAL);
12919 	}
12920 
12921 	if (prog->type != BPF_PROG_TYPE_EXT) {
12922 		pr_warn("prog '%s': only BPF_PROG_TYPE_EXT can attach as freplace\n",
12923 			prog->name);
12924 		return libbpf_err_ptr(-EINVAL);
12925 	}
12926 
12927 	if (target_fd) {
12928 		LIBBPF_OPTS(bpf_link_create_opts, target_opts);
12929 
12930 		btf_id = libbpf_find_prog_btf_id(attach_func_name, target_fd, prog->obj->token_fd);
12931 		if (btf_id < 0)
12932 			return libbpf_err_ptr(btf_id);
12933 
12934 		target_opts.target_btf_id = btf_id;
12935 
12936 		return bpf_program_attach_fd(prog, target_fd, "freplace",
12937 					     &target_opts);
12938 	} else {
12939 		/* no target, so use raw_tracepoint_open for compatibility
12940 		 * with old kernels
12941 		 */
12942 		return bpf_program__attach_trace(prog);
12943 	}
12944 }
12945 
12946 struct bpf_link *
12947 bpf_program__attach_iter(const struct bpf_program *prog,
12948 			 const struct bpf_iter_attach_opts *opts)
12949 {
12950 	DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
12951 	struct bpf_link *link;
12952 	int prog_fd, link_fd;
12953 	__u32 target_fd = 0;
12954 
12955 	if (!OPTS_VALID(opts, bpf_iter_attach_opts))
12956 		return libbpf_err_ptr(-EINVAL);
12957 
12958 	link_create_opts.iter_info = OPTS_GET(opts, link_info, (void *)0);
12959 	link_create_opts.iter_info_len = OPTS_GET(opts, link_info_len, 0);
12960 
12961 	prog_fd = bpf_program__fd(prog);
12962 	if (prog_fd < 0) {
12963 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12964 		return libbpf_err_ptr(-EINVAL);
12965 	}
12966 
12967 	link = calloc(1, sizeof(*link));
12968 	if (!link)
12969 		return libbpf_err_ptr(-ENOMEM);
12970 	link->detach = &bpf_link__detach_fd;
12971 
12972 	link_fd = bpf_link_create(prog_fd, target_fd, BPF_TRACE_ITER,
12973 				  &link_create_opts);
12974 	if (link_fd < 0) {
12975 		link_fd = -errno;
12976 		free(link);
12977 		pr_warn("prog '%s': failed to attach to iterator: %s\n",
12978 			prog->name, errstr(link_fd));
12979 		return libbpf_err_ptr(link_fd);
12980 	}
12981 	link->fd = link_fd;
12982 	return link;
12983 }
12984 
12985 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12986 {
12987 	*link = bpf_program__attach_iter(prog, NULL);
12988 	return libbpf_get_error(*link);
12989 }
12990 
12991 struct bpf_link *bpf_program__attach_netfilter(const struct bpf_program *prog,
12992 					       const struct bpf_netfilter_opts *opts)
12993 {
12994 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
12995 	struct bpf_link *link;
12996 	int prog_fd, link_fd;
12997 
12998 	if (!OPTS_VALID(opts, bpf_netfilter_opts))
12999 		return libbpf_err_ptr(-EINVAL);
13000 
13001 	prog_fd = bpf_program__fd(prog);
13002 	if (prog_fd < 0) {
13003 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
13004 		return libbpf_err_ptr(-EINVAL);
13005 	}
13006 
13007 	link = calloc(1, sizeof(*link));
13008 	if (!link)
13009 		return libbpf_err_ptr(-ENOMEM);
13010 
13011 	link->detach = &bpf_link__detach_fd;
13012 
13013 	lopts.netfilter.pf = OPTS_GET(opts, pf, 0);
13014 	lopts.netfilter.hooknum = OPTS_GET(opts, hooknum, 0);
13015 	lopts.netfilter.priority = OPTS_GET(opts, priority, 0);
13016 	lopts.netfilter.flags = OPTS_GET(opts, flags, 0);
13017 
13018 	link_fd = bpf_link_create(prog_fd, 0, BPF_NETFILTER, &lopts);
13019 	if (link_fd < 0) {
13020 		link_fd = -errno;
13021 		free(link);
13022 		pr_warn("prog '%s': failed to attach to netfilter: %s\n",
13023 			prog->name, errstr(link_fd));
13024 		return libbpf_err_ptr(link_fd);
13025 	}
13026 	link->fd = link_fd;
13027 
13028 	return link;
13029 }
13030 
13031 struct bpf_link *bpf_program__attach(const struct bpf_program *prog)
13032 {
13033 	struct bpf_link *link = NULL;
13034 	int err;
13035 
13036 	if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
13037 		return libbpf_err_ptr(-EOPNOTSUPP);
13038 
13039 	if (bpf_program__fd(prog) < 0) {
13040 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
13041 			prog->name);
13042 		return libbpf_err_ptr(-EINVAL);
13043 	}
13044 
13045 	err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, &link);
13046 	if (err)
13047 		return libbpf_err_ptr(err);
13048 
13049 	/* When calling bpf_program__attach() explicitly, auto-attach support
13050 	 * is expected to work, so NULL returned link is considered an error.
13051 	 * This is different for skeleton's attach, see comment in
13052 	 * bpf_object__attach_skeleton().
13053 	 */
13054 	if (!link)
13055 		return libbpf_err_ptr(-EOPNOTSUPP);
13056 
13057 	return link;
13058 }
13059 
13060 struct bpf_link_struct_ops {
13061 	struct bpf_link link;
13062 	int map_fd;
13063 };
13064 
13065 static int bpf_link__detach_struct_ops(struct bpf_link *link)
13066 {
13067 	struct bpf_link_struct_ops *st_link;
13068 	__u32 zero = 0;
13069 
13070 	st_link = container_of(link, struct bpf_link_struct_ops, link);
13071 
13072 	if (st_link->map_fd < 0)
13073 		/* w/o a real link */
13074 		return bpf_map_delete_elem(link->fd, &zero);
13075 
13076 	return close(link->fd);
13077 }
13078 
13079 struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map)
13080 {
13081 	struct bpf_link_struct_ops *link;
13082 	__u32 zero = 0;
13083 	int err, fd;
13084 
13085 	if (!bpf_map__is_struct_ops(map)) {
13086 		pr_warn("map '%s': can't attach non-struct_ops map\n", map->name);
13087 		return libbpf_err_ptr(-EINVAL);
13088 	}
13089 
13090 	if (map->fd < 0) {
13091 		pr_warn("map '%s': can't attach BPF map without FD (was it created?)\n", map->name);
13092 		return libbpf_err_ptr(-EINVAL);
13093 	}
13094 
13095 	link = calloc(1, sizeof(*link));
13096 	if (!link)
13097 		return libbpf_err_ptr(-EINVAL);
13098 
13099 	/* kern_vdata should be prepared during the loading phase. */
13100 	err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
13101 	/* It can be EBUSY if the map has been used to create or
13102 	 * update a link before.  We don't allow updating the value of
13103 	 * a struct_ops once it is set.  That ensures that the value
13104 	 * never changed.  So, it is safe to skip EBUSY.
13105 	 */
13106 	if (err && (!(map->def.map_flags & BPF_F_LINK) || err != -EBUSY)) {
13107 		free(link);
13108 		return libbpf_err_ptr(err);
13109 	}
13110 
13111 	link->link.detach = bpf_link__detach_struct_ops;
13112 
13113 	if (!(map->def.map_flags & BPF_F_LINK)) {
13114 		/* w/o a real link */
13115 		link->link.fd = map->fd;
13116 		link->map_fd = -1;
13117 		return &link->link;
13118 	}
13119 
13120 	fd = bpf_link_create(map->fd, 0, BPF_STRUCT_OPS, NULL);
13121 	if (fd < 0) {
13122 		free(link);
13123 		return libbpf_err_ptr(fd);
13124 	}
13125 
13126 	link->link.fd = fd;
13127 	link->map_fd = map->fd;
13128 
13129 	return &link->link;
13130 }
13131 
13132 /*
13133  * Swap the back struct_ops of a link with a new struct_ops map.
13134  */
13135 int bpf_link__update_map(struct bpf_link *link, const struct bpf_map *map)
13136 {
13137 	struct bpf_link_struct_ops *st_ops_link;
13138 	__u32 zero = 0;
13139 	int err;
13140 
13141 	if (!bpf_map__is_struct_ops(map))
13142 		return libbpf_err(-EINVAL);
13143 
13144 	if (map->fd < 0) {
13145 		pr_warn("map '%s': can't use BPF map without FD (was it created?)\n", map->name);
13146 		return libbpf_err(-EINVAL);
13147 	}
13148 
13149 	st_ops_link = container_of(link, struct bpf_link_struct_ops, link);
13150 	/* Ensure the type of a link is correct */
13151 	if (st_ops_link->map_fd < 0)
13152 		return libbpf_err(-EINVAL);
13153 
13154 	err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
13155 	/* It can be EBUSY if the map has been used to create or
13156 	 * update a link before.  We don't allow updating the value of
13157 	 * a struct_ops once it is set.  That ensures that the value
13158 	 * never changed.  So, it is safe to skip EBUSY.
13159 	 */
13160 	if (err && err != -EBUSY)
13161 		return err;
13162 
13163 	err = bpf_link_update(link->fd, map->fd, NULL);
13164 	if (err < 0)
13165 		return err;
13166 
13167 	st_ops_link->map_fd = map->fd;
13168 
13169 	return 0;
13170 }
13171 
13172 typedef enum bpf_perf_event_ret (*bpf_perf_event_print_t)(struct perf_event_header *hdr,
13173 							  void *private_data);
13174 
13175 static enum bpf_perf_event_ret
13176 perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
13177 		       void **copy_mem, size_t *copy_size,
13178 		       bpf_perf_event_print_t fn, void *private_data)
13179 {
13180 	struct perf_event_mmap_page *header = mmap_mem;
13181 	__u64 data_head = ring_buffer_read_head(header);
13182 	__u64 data_tail = header->data_tail;
13183 	void *base = ((__u8 *)header) + page_size;
13184 	int ret = LIBBPF_PERF_EVENT_CONT;
13185 	struct perf_event_header *ehdr;
13186 	size_t ehdr_size;
13187 
13188 	while (data_head != data_tail) {
13189 		ehdr = base + (data_tail & (mmap_size - 1));
13190 		ehdr_size = ehdr->size;
13191 
13192 		if (((void *)ehdr) + ehdr_size > base + mmap_size) {
13193 			void *copy_start = ehdr;
13194 			size_t len_first = base + mmap_size - copy_start;
13195 			size_t len_secnd = ehdr_size - len_first;
13196 
13197 			if (*copy_size < ehdr_size) {
13198 				free(*copy_mem);
13199 				*copy_mem = malloc(ehdr_size);
13200 				if (!*copy_mem) {
13201 					*copy_size = 0;
13202 					ret = LIBBPF_PERF_EVENT_ERROR;
13203 					break;
13204 				}
13205 				*copy_size = ehdr_size;
13206 			}
13207 
13208 			memcpy(*copy_mem, copy_start, len_first);
13209 			memcpy(*copy_mem + len_first, base, len_secnd);
13210 			ehdr = *copy_mem;
13211 		}
13212 
13213 		ret = fn(ehdr, private_data);
13214 		data_tail += ehdr_size;
13215 		if (ret != LIBBPF_PERF_EVENT_CONT)
13216 			break;
13217 	}
13218 
13219 	ring_buffer_write_tail(header, data_tail);
13220 	return libbpf_err(ret);
13221 }
13222 
13223 struct perf_buffer;
13224 
13225 struct perf_buffer_params {
13226 	struct perf_event_attr *attr;
13227 	/* if event_cb is specified, it takes precendence */
13228 	perf_buffer_event_fn event_cb;
13229 	/* sample_cb and lost_cb are higher-level common-case callbacks */
13230 	perf_buffer_sample_fn sample_cb;
13231 	perf_buffer_lost_fn lost_cb;
13232 	void *ctx;
13233 	int cpu_cnt;
13234 	int *cpus;
13235 	int *map_keys;
13236 };
13237 
13238 struct perf_cpu_buf {
13239 	struct perf_buffer *pb;
13240 	void *base; /* mmap()'ed memory */
13241 	void *buf; /* for reconstructing segmented data */
13242 	size_t buf_size;
13243 	int fd;
13244 	int cpu;
13245 	int map_key;
13246 };
13247 
13248 struct perf_buffer {
13249 	perf_buffer_event_fn event_cb;
13250 	perf_buffer_sample_fn sample_cb;
13251 	perf_buffer_lost_fn lost_cb;
13252 	void *ctx; /* passed into callbacks */
13253 
13254 	size_t page_size;
13255 	size_t mmap_size;
13256 	struct perf_cpu_buf **cpu_bufs;
13257 	struct epoll_event *events;
13258 	int cpu_cnt; /* number of allocated CPU buffers */
13259 	int epoll_fd; /* perf event FD */
13260 	int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
13261 };
13262 
13263 static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
13264 				      struct perf_cpu_buf *cpu_buf)
13265 {
13266 	if (!cpu_buf)
13267 		return;
13268 	if (cpu_buf->base &&
13269 	    munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
13270 		pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
13271 	if (cpu_buf->fd >= 0) {
13272 		ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
13273 		close(cpu_buf->fd);
13274 	}
13275 	free(cpu_buf->buf);
13276 	free(cpu_buf);
13277 }
13278 
13279 void perf_buffer__free(struct perf_buffer *pb)
13280 {
13281 	int i;
13282 
13283 	if (IS_ERR_OR_NULL(pb))
13284 		return;
13285 	if (pb->cpu_bufs) {
13286 		for (i = 0; i < pb->cpu_cnt; i++) {
13287 			struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
13288 
13289 			if (!cpu_buf)
13290 				continue;
13291 
13292 			bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
13293 			perf_buffer__free_cpu_buf(pb, cpu_buf);
13294 		}
13295 		free(pb->cpu_bufs);
13296 	}
13297 	if (pb->epoll_fd >= 0)
13298 		close(pb->epoll_fd);
13299 	free(pb->events);
13300 	free(pb);
13301 }
13302 
13303 static struct perf_cpu_buf *
13304 perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
13305 			  int cpu, int map_key)
13306 {
13307 	struct perf_cpu_buf *cpu_buf;
13308 	int err;
13309 
13310 	cpu_buf = calloc(1, sizeof(*cpu_buf));
13311 	if (!cpu_buf)
13312 		return ERR_PTR(-ENOMEM);
13313 
13314 	cpu_buf->pb = pb;
13315 	cpu_buf->cpu = cpu;
13316 	cpu_buf->map_key = map_key;
13317 
13318 	cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
13319 			      -1, PERF_FLAG_FD_CLOEXEC);
13320 	if (cpu_buf->fd < 0) {
13321 		err = -errno;
13322 		pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
13323 			cpu, errstr(err));
13324 		goto error;
13325 	}
13326 
13327 	cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
13328 			     PROT_READ | PROT_WRITE, MAP_SHARED,
13329 			     cpu_buf->fd, 0);
13330 	if (cpu_buf->base == MAP_FAILED) {
13331 		cpu_buf->base = NULL;
13332 		err = -errno;
13333 		pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
13334 			cpu, errstr(err));
13335 		goto error;
13336 	}
13337 
13338 	if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
13339 		err = -errno;
13340 		pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
13341 			cpu, errstr(err));
13342 		goto error;
13343 	}
13344 
13345 	return cpu_buf;
13346 
13347 error:
13348 	perf_buffer__free_cpu_buf(pb, cpu_buf);
13349 	return (struct perf_cpu_buf *)ERR_PTR(err);
13350 }
13351 
13352 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
13353 					      struct perf_buffer_params *p);
13354 
13355 struct perf_buffer *perf_buffer__new(int map_fd, size_t page_cnt,
13356 				     perf_buffer_sample_fn sample_cb,
13357 				     perf_buffer_lost_fn lost_cb,
13358 				     void *ctx,
13359 				     const struct perf_buffer_opts *opts)
13360 {
13361 	const size_t attr_sz = sizeof(struct perf_event_attr);
13362 	struct perf_buffer_params p = {};
13363 	struct perf_event_attr attr;
13364 	__u32 sample_period;
13365 
13366 	if (!OPTS_VALID(opts, perf_buffer_opts))
13367 		return libbpf_err_ptr(-EINVAL);
13368 
13369 	sample_period = OPTS_GET(opts, sample_period, 1);
13370 	if (!sample_period)
13371 		sample_period = 1;
13372 
13373 	memset(&attr, 0, attr_sz);
13374 	attr.size = attr_sz;
13375 	attr.config = PERF_COUNT_SW_BPF_OUTPUT;
13376 	attr.type = PERF_TYPE_SOFTWARE;
13377 	attr.sample_type = PERF_SAMPLE_RAW;
13378 	attr.wakeup_events = sample_period;
13379 
13380 	p.attr = &attr;
13381 	p.sample_cb = sample_cb;
13382 	p.lost_cb = lost_cb;
13383 	p.ctx = ctx;
13384 
13385 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
13386 }
13387 
13388 struct perf_buffer *perf_buffer__new_raw(int map_fd, size_t page_cnt,
13389 					 struct perf_event_attr *attr,
13390 					 perf_buffer_event_fn event_cb, void *ctx,
13391 					 const struct perf_buffer_raw_opts *opts)
13392 {
13393 	struct perf_buffer_params p = {};
13394 
13395 	if (!attr)
13396 		return libbpf_err_ptr(-EINVAL);
13397 
13398 	if (!OPTS_VALID(opts, perf_buffer_raw_opts))
13399 		return libbpf_err_ptr(-EINVAL);
13400 
13401 	p.attr = attr;
13402 	p.event_cb = event_cb;
13403 	p.ctx = ctx;
13404 	p.cpu_cnt = OPTS_GET(opts, cpu_cnt, 0);
13405 	p.cpus = OPTS_GET(opts, cpus, NULL);
13406 	p.map_keys = OPTS_GET(opts, map_keys, NULL);
13407 
13408 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
13409 }
13410 
13411 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
13412 					      struct perf_buffer_params *p)
13413 {
13414 	const char *online_cpus_file = "/sys/devices/system/cpu/online";
13415 	struct bpf_map_info map;
13416 	struct perf_buffer *pb;
13417 	bool *online = NULL;
13418 	__u32 map_info_len;
13419 	int err, i, j, n;
13420 
13421 	if (page_cnt == 0 || (page_cnt & (page_cnt - 1))) {
13422 		pr_warn("page count should be power of two, but is %zu\n",
13423 			page_cnt);
13424 		return ERR_PTR(-EINVAL);
13425 	}
13426 
13427 	/* best-effort sanity checks */
13428 	memset(&map, 0, sizeof(map));
13429 	map_info_len = sizeof(map);
13430 	err = bpf_map_get_info_by_fd(map_fd, &map, &map_info_len);
13431 	if (err) {
13432 		err = -errno;
13433 		/* if BPF_OBJ_GET_INFO_BY_FD is supported, will return
13434 		 * -EBADFD, -EFAULT, or -E2BIG on real error
13435 		 */
13436 		if (err != -EINVAL) {
13437 			pr_warn("failed to get map info for map FD %d: %s\n",
13438 				map_fd, errstr(err));
13439 			return ERR_PTR(err);
13440 		}
13441 		pr_debug("failed to get map info for FD %d; API not supported? Ignoring...\n",
13442 			 map_fd);
13443 	} else {
13444 		if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
13445 			pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
13446 				map.name);
13447 			return ERR_PTR(-EINVAL);
13448 		}
13449 	}
13450 
13451 	pb = calloc(1, sizeof(*pb));
13452 	if (!pb)
13453 		return ERR_PTR(-ENOMEM);
13454 
13455 	pb->event_cb = p->event_cb;
13456 	pb->sample_cb = p->sample_cb;
13457 	pb->lost_cb = p->lost_cb;
13458 	pb->ctx = p->ctx;
13459 
13460 	pb->page_size = getpagesize();
13461 	pb->mmap_size = pb->page_size * page_cnt;
13462 	pb->map_fd = map_fd;
13463 
13464 	pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
13465 	if (pb->epoll_fd < 0) {
13466 		err = -errno;
13467 		pr_warn("failed to create epoll instance: %s\n",
13468 			errstr(err));
13469 		goto error;
13470 	}
13471 
13472 	if (p->cpu_cnt > 0) {
13473 		pb->cpu_cnt = p->cpu_cnt;
13474 	} else {
13475 		pb->cpu_cnt = libbpf_num_possible_cpus();
13476 		if (pb->cpu_cnt < 0) {
13477 			err = pb->cpu_cnt;
13478 			goto error;
13479 		}
13480 		if (map.max_entries && map.max_entries < pb->cpu_cnt)
13481 			pb->cpu_cnt = map.max_entries;
13482 	}
13483 
13484 	pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
13485 	if (!pb->events) {
13486 		err = -ENOMEM;
13487 		pr_warn("failed to allocate events: out of memory\n");
13488 		goto error;
13489 	}
13490 	pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
13491 	if (!pb->cpu_bufs) {
13492 		err = -ENOMEM;
13493 		pr_warn("failed to allocate buffers: out of memory\n");
13494 		goto error;
13495 	}
13496 
13497 	err = parse_cpu_mask_file(online_cpus_file, &online, &n);
13498 	if (err) {
13499 		pr_warn("failed to get online CPU mask: %s\n", errstr(err));
13500 		goto error;
13501 	}
13502 
13503 	for (i = 0, j = 0; i < pb->cpu_cnt; i++) {
13504 		struct perf_cpu_buf *cpu_buf;
13505 		int cpu, map_key;
13506 
13507 		cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
13508 		map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
13509 
13510 		/* in case user didn't explicitly requested particular CPUs to
13511 		 * be attached to, skip offline/not present CPUs
13512 		 */
13513 		if (p->cpu_cnt <= 0 && (cpu >= n || !online[cpu]))
13514 			continue;
13515 
13516 		cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
13517 		if (IS_ERR(cpu_buf)) {
13518 			err = PTR_ERR(cpu_buf);
13519 			goto error;
13520 		}
13521 
13522 		pb->cpu_bufs[j] = cpu_buf;
13523 
13524 		err = bpf_map_update_elem(pb->map_fd, &map_key,
13525 					  &cpu_buf->fd, 0);
13526 		if (err) {
13527 			err = -errno;
13528 			pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
13529 				cpu, map_key, cpu_buf->fd,
13530 				errstr(err));
13531 			goto error;
13532 		}
13533 
13534 		pb->events[j].events = EPOLLIN;
13535 		pb->events[j].data.ptr = cpu_buf;
13536 		if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
13537 			      &pb->events[j]) < 0) {
13538 			err = -errno;
13539 			pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
13540 				cpu, cpu_buf->fd,
13541 				errstr(err));
13542 			goto error;
13543 		}
13544 		j++;
13545 	}
13546 	pb->cpu_cnt = j;
13547 	free(online);
13548 
13549 	return pb;
13550 
13551 error:
13552 	free(online);
13553 	if (pb)
13554 		perf_buffer__free(pb);
13555 	return ERR_PTR(err);
13556 }
13557 
13558 struct perf_sample_raw {
13559 	struct perf_event_header header;
13560 	uint32_t size;
13561 	char data[];
13562 };
13563 
13564 struct perf_sample_lost {
13565 	struct perf_event_header header;
13566 	uint64_t id;
13567 	uint64_t lost;
13568 	uint64_t sample_id;
13569 };
13570 
13571 static enum bpf_perf_event_ret
13572 perf_buffer__process_record(struct perf_event_header *e, void *ctx)
13573 {
13574 	struct perf_cpu_buf *cpu_buf = ctx;
13575 	struct perf_buffer *pb = cpu_buf->pb;
13576 	void *data = e;
13577 
13578 	/* user wants full control over parsing perf event */
13579 	if (pb->event_cb)
13580 		return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
13581 
13582 	switch (e->type) {
13583 	case PERF_RECORD_SAMPLE: {
13584 		struct perf_sample_raw *s = data;
13585 
13586 		if (pb->sample_cb)
13587 			pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
13588 		break;
13589 	}
13590 	case PERF_RECORD_LOST: {
13591 		struct perf_sample_lost *s = data;
13592 
13593 		if (pb->lost_cb)
13594 			pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
13595 		break;
13596 	}
13597 	default:
13598 		pr_warn("unknown perf sample type %d\n", e->type);
13599 		return LIBBPF_PERF_EVENT_ERROR;
13600 	}
13601 	return LIBBPF_PERF_EVENT_CONT;
13602 }
13603 
13604 static int perf_buffer__process_records(struct perf_buffer *pb,
13605 					struct perf_cpu_buf *cpu_buf)
13606 {
13607 	enum bpf_perf_event_ret ret;
13608 
13609 	ret = perf_event_read_simple(cpu_buf->base, pb->mmap_size,
13610 				     pb->page_size, &cpu_buf->buf,
13611 				     &cpu_buf->buf_size,
13612 				     perf_buffer__process_record, cpu_buf);
13613 	if (ret != LIBBPF_PERF_EVENT_CONT)
13614 		return ret;
13615 	return 0;
13616 }
13617 
13618 int perf_buffer__epoll_fd(const struct perf_buffer *pb)
13619 {
13620 	return pb->epoll_fd;
13621 }
13622 
13623 int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
13624 {
13625 	int i, cnt, err;
13626 
13627 	cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
13628 	if (cnt < 0)
13629 		return -errno;
13630 
13631 	for (i = 0; i < cnt; i++) {
13632 		struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
13633 
13634 		err = perf_buffer__process_records(pb, cpu_buf);
13635 		if (err) {
13636 			pr_warn("error while processing records: %s\n", errstr(err));
13637 			return libbpf_err(err);
13638 		}
13639 	}
13640 	return cnt;
13641 }
13642 
13643 /* Return number of PERF_EVENT_ARRAY map slots set up by this perf_buffer
13644  * manager.
13645  */
13646 size_t perf_buffer__buffer_cnt(const struct perf_buffer *pb)
13647 {
13648 	return pb->cpu_cnt;
13649 }
13650 
13651 /*
13652  * Return perf_event FD of a ring buffer in *buf_idx* slot of
13653  * PERF_EVENT_ARRAY BPF map. This FD can be polled for new data using
13654  * select()/poll()/epoll() Linux syscalls.
13655  */
13656 int perf_buffer__buffer_fd(const struct perf_buffer *pb, size_t buf_idx)
13657 {
13658 	struct perf_cpu_buf *cpu_buf;
13659 
13660 	if (buf_idx >= pb->cpu_cnt)
13661 		return libbpf_err(-EINVAL);
13662 
13663 	cpu_buf = pb->cpu_bufs[buf_idx];
13664 	if (!cpu_buf)
13665 		return libbpf_err(-ENOENT);
13666 
13667 	return cpu_buf->fd;
13668 }
13669 
13670 int perf_buffer__buffer(struct perf_buffer *pb, int buf_idx, void **buf, size_t *buf_size)
13671 {
13672 	struct perf_cpu_buf *cpu_buf;
13673 
13674 	if (buf_idx >= pb->cpu_cnt)
13675 		return libbpf_err(-EINVAL);
13676 
13677 	cpu_buf = pb->cpu_bufs[buf_idx];
13678 	if (!cpu_buf)
13679 		return libbpf_err(-ENOENT);
13680 
13681 	*buf = cpu_buf->base;
13682 	*buf_size = pb->mmap_size;
13683 	return 0;
13684 }
13685 
13686 /*
13687  * Consume data from perf ring buffer corresponding to slot *buf_idx* in
13688  * PERF_EVENT_ARRAY BPF map without waiting/polling. If there is no data to
13689  * consume, do nothing and return success.
13690  * Returns:
13691  *   - 0 on success;
13692  *   - <0 on failure.
13693  */
13694 int perf_buffer__consume_buffer(struct perf_buffer *pb, size_t buf_idx)
13695 {
13696 	struct perf_cpu_buf *cpu_buf;
13697 
13698 	if (buf_idx >= pb->cpu_cnt)
13699 		return libbpf_err(-EINVAL);
13700 
13701 	cpu_buf = pb->cpu_bufs[buf_idx];
13702 	if (!cpu_buf)
13703 		return libbpf_err(-ENOENT);
13704 
13705 	return perf_buffer__process_records(pb, cpu_buf);
13706 }
13707 
13708 int perf_buffer__consume(struct perf_buffer *pb)
13709 {
13710 	int i, err;
13711 
13712 	for (i = 0; i < pb->cpu_cnt; i++) {
13713 		struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
13714 
13715 		if (!cpu_buf)
13716 			continue;
13717 
13718 		err = perf_buffer__process_records(pb, cpu_buf);
13719 		if (err) {
13720 			pr_warn("perf_buffer: failed to process records in buffer #%d: %s\n",
13721 				i, errstr(err));
13722 			return libbpf_err(err);
13723 		}
13724 	}
13725 	return 0;
13726 }
13727 
13728 int bpf_program__set_attach_target(struct bpf_program *prog,
13729 				   int attach_prog_fd,
13730 				   const char *attach_func_name)
13731 {
13732 	int btf_obj_fd = 0, btf_id = 0, err;
13733 
13734 	if (!prog || attach_prog_fd < 0)
13735 		return libbpf_err(-EINVAL);
13736 
13737 	if (prog->obj->state >= OBJ_LOADED)
13738 		return libbpf_err(-EINVAL);
13739 
13740 	if (attach_prog_fd && !attach_func_name) {
13741 		/* remember attach_prog_fd and let bpf_program__load() find
13742 		 * BTF ID during the program load
13743 		 */
13744 		prog->attach_prog_fd = attach_prog_fd;
13745 		return 0;
13746 	}
13747 
13748 	if (attach_prog_fd) {
13749 		btf_id = libbpf_find_prog_btf_id(attach_func_name,
13750 						 attach_prog_fd, prog->obj->token_fd);
13751 		if (btf_id < 0)
13752 			return libbpf_err(btf_id);
13753 	} else {
13754 		if (!attach_func_name)
13755 			return libbpf_err(-EINVAL);
13756 
13757 		/* load btf_vmlinux, if not yet */
13758 		err = bpf_object__load_vmlinux_btf(prog->obj, true);
13759 		if (err)
13760 			return libbpf_err(err);
13761 		err = find_kernel_btf_id(prog->obj, attach_func_name,
13762 					 prog->expected_attach_type,
13763 					 &btf_obj_fd, &btf_id);
13764 		if (err)
13765 			return libbpf_err(err);
13766 	}
13767 
13768 	prog->attach_btf_id = btf_id;
13769 	prog->attach_btf_obj_fd = btf_obj_fd;
13770 	prog->attach_prog_fd = attach_prog_fd;
13771 	return 0;
13772 }
13773 
13774 int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz)
13775 {
13776 	int err = 0, n, len, start, end = -1;
13777 	bool *tmp;
13778 
13779 	*mask = NULL;
13780 	*mask_sz = 0;
13781 
13782 	/* Each sub string separated by ',' has format \d+-\d+ or \d+ */
13783 	while (*s) {
13784 		if (*s == ',' || *s == '\n') {
13785 			s++;
13786 			continue;
13787 		}
13788 		n = sscanf(s, "%d%n-%d%n", &start, &len, &end, &len);
13789 		if (n <= 0 || n > 2) {
13790 			pr_warn("Failed to get CPU range %s: %d\n", s, n);
13791 			err = -EINVAL;
13792 			goto cleanup;
13793 		} else if (n == 1) {
13794 			end = start;
13795 		}
13796 		if (start < 0 || start > end) {
13797 			pr_warn("Invalid CPU range [%d,%d] in %s\n",
13798 				start, end, s);
13799 			err = -EINVAL;
13800 			goto cleanup;
13801 		}
13802 		tmp = realloc(*mask, end + 1);
13803 		if (!tmp) {
13804 			err = -ENOMEM;
13805 			goto cleanup;
13806 		}
13807 		*mask = tmp;
13808 		memset(tmp + *mask_sz, 0, start - *mask_sz);
13809 		memset(tmp + start, 1, end - start + 1);
13810 		*mask_sz = end + 1;
13811 		s += len;
13812 	}
13813 	if (!*mask_sz) {
13814 		pr_warn("Empty CPU range\n");
13815 		return -EINVAL;
13816 	}
13817 	return 0;
13818 cleanup:
13819 	free(*mask);
13820 	*mask = NULL;
13821 	return err;
13822 }
13823 
13824 int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz)
13825 {
13826 	int fd, err = 0, len;
13827 	char buf[128];
13828 
13829 	fd = open(fcpu, O_RDONLY | O_CLOEXEC);
13830 	if (fd < 0) {
13831 		err = -errno;
13832 		pr_warn("Failed to open cpu mask file %s: %s\n", fcpu, errstr(err));
13833 		return err;
13834 	}
13835 	len = read(fd, buf, sizeof(buf));
13836 	close(fd);
13837 	if (len <= 0) {
13838 		err = len ? -errno : -EINVAL;
13839 		pr_warn("Failed to read cpu mask from %s: %s\n", fcpu, errstr(err));
13840 		return err;
13841 	}
13842 	if (len >= sizeof(buf)) {
13843 		pr_warn("CPU mask is too big in file %s\n", fcpu);
13844 		return -E2BIG;
13845 	}
13846 	buf[len] = '\0';
13847 
13848 	return parse_cpu_mask_str(buf, mask, mask_sz);
13849 }
13850 
13851 int libbpf_num_possible_cpus(void)
13852 {
13853 	static const char *fcpu = "/sys/devices/system/cpu/possible";
13854 	static int cpus;
13855 	int err, n, i, tmp_cpus;
13856 	bool *mask;
13857 
13858 	tmp_cpus = READ_ONCE(cpus);
13859 	if (tmp_cpus > 0)
13860 		return tmp_cpus;
13861 
13862 	err = parse_cpu_mask_file(fcpu, &mask, &n);
13863 	if (err)
13864 		return libbpf_err(err);
13865 
13866 	tmp_cpus = 0;
13867 	for (i = 0; i < n; i++) {
13868 		if (mask[i])
13869 			tmp_cpus++;
13870 	}
13871 	free(mask);
13872 
13873 	WRITE_ONCE(cpus, tmp_cpus);
13874 	return tmp_cpus;
13875 }
13876 
13877 static int populate_skeleton_maps(const struct bpf_object *obj,
13878 				  struct bpf_map_skeleton *maps,
13879 				  size_t map_cnt, size_t map_skel_sz)
13880 {
13881 	int i;
13882 
13883 	for (i = 0; i < map_cnt; i++) {
13884 		struct bpf_map_skeleton *map_skel = (void *)maps + i * map_skel_sz;
13885 		struct bpf_map **map = map_skel->map;
13886 		const char *name = map_skel->name;
13887 		void **mmaped = map_skel->mmaped;
13888 
13889 		*map = bpf_object__find_map_by_name(obj, name);
13890 		if (!*map) {
13891 			pr_warn("failed to find skeleton map '%s'\n", name);
13892 			return -ESRCH;
13893 		}
13894 
13895 		/* externs shouldn't be pre-setup from user code */
13896 		if (mmaped && (*map)->libbpf_type != LIBBPF_MAP_KCONFIG)
13897 			*mmaped = (*map)->mmaped;
13898 	}
13899 	return 0;
13900 }
13901 
13902 static int populate_skeleton_progs(const struct bpf_object *obj,
13903 				   struct bpf_prog_skeleton *progs,
13904 				   size_t prog_cnt, size_t prog_skel_sz)
13905 {
13906 	int i;
13907 
13908 	for (i = 0; i < prog_cnt; i++) {
13909 		struct bpf_prog_skeleton *prog_skel = (void *)progs + i * prog_skel_sz;
13910 		struct bpf_program **prog = prog_skel->prog;
13911 		const char *name = prog_skel->name;
13912 
13913 		*prog = bpf_object__find_program_by_name(obj, name);
13914 		if (!*prog) {
13915 			pr_warn("failed to find skeleton program '%s'\n", name);
13916 			return -ESRCH;
13917 		}
13918 	}
13919 	return 0;
13920 }
13921 
13922 int bpf_object__open_skeleton(struct bpf_object_skeleton *s,
13923 			      const struct bpf_object_open_opts *opts)
13924 {
13925 	struct bpf_object *obj;
13926 	int err;
13927 
13928 	obj = bpf_object_open(NULL, s->data, s->data_sz, s->name, opts);
13929 	if (IS_ERR(obj)) {
13930 		err = PTR_ERR(obj);
13931 		pr_warn("failed to initialize skeleton BPF object '%s': %s\n",
13932 			s->name, errstr(err));
13933 		return libbpf_err(err);
13934 	}
13935 
13936 	*s->obj = obj;
13937 	err = populate_skeleton_maps(obj, s->maps, s->map_cnt, s->map_skel_sz);
13938 	if (err) {
13939 		pr_warn("failed to populate skeleton maps for '%s': %s\n", s->name, errstr(err));
13940 		return libbpf_err(err);
13941 	}
13942 
13943 	err = populate_skeleton_progs(obj, s->progs, s->prog_cnt, s->prog_skel_sz);
13944 	if (err) {
13945 		pr_warn("failed to populate skeleton progs for '%s': %s\n", s->name, errstr(err));
13946 		return libbpf_err(err);
13947 	}
13948 
13949 	return 0;
13950 }
13951 
13952 int bpf_object__open_subskeleton(struct bpf_object_subskeleton *s)
13953 {
13954 	int err, len, var_idx, i;
13955 	const char *var_name;
13956 	const struct bpf_map *map;
13957 	struct btf *btf;
13958 	__u32 map_type_id;
13959 	const struct btf_type *map_type, *var_type;
13960 	const struct bpf_var_skeleton *var_skel;
13961 	struct btf_var_secinfo *var;
13962 
13963 	if (!s->obj)
13964 		return libbpf_err(-EINVAL);
13965 
13966 	btf = bpf_object__btf(s->obj);
13967 	if (!btf) {
13968 		pr_warn("subskeletons require BTF at runtime (object %s)\n",
13969 			bpf_object__name(s->obj));
13970 		return libbpf_err(-errno);
13971 	}
13972 
13973 	err = populate_skeleton_maps(s->obj, s->maps, s->map_cnt, s->map_skel_sz);
13974 	if (err) {
13975 		pr_warn("failed to populate subskeleton maps: %s\n", errstr(err));
13976 		return libbpf_err(err);
13977 	}
13978 
13979 	err = populate_skeleton_progs(s->obj, s->progs, s->prog_cnt, s->prog_skel_sz);
13980 	if (err) {
13981 		pr_warn("failed to populate subskeleton maps: %s\n", errstr(err));
13982 		return libbpf_err(err);
13983 	}
13984 
13985 	for (var_idx = 0; var_idx < s->var_cnt; var_idx++) {
13986 		var_skel = (void *)s->vars + var_idx * s->var_skel_sz;
13987 		map = *var_skel->map;
13988 		map_type_id = bpf_map__btf_value_type_id(map);
13989 		map_type = btf__type_by_id(btf, map_type_id);
13990 
13991 		if (!btf_is_datasec(map_type)) {
13992 			pr_warn("type for map '%1$s' is not a datasec: %2$s\n",
13993 				bpf_map__name(map),
13994 				__btf_kind_str(btf_kind(map_type)));
13995 			return libbpf_err(-EINVAL);
13996 		}
13997 
13998 		len = btf_vlen(map_type);
13999 		var = btf_var_secinfos(map_type);
14000 		for (i = 0; i < len; i++, var++) {
14001 			var_type = btf__type_by_id(btf, var->type);
14002 			var_name = btf__name_by_offset(btf, var_type->name_off);
14003 			if (strcmp(var_name, var_skel->name) == 0) {
14004 				*var_skel->addr = map->mmaped + var->offset;
14005 				break;
14006 			}
14007 		}
14008 	}
14009 	return 0;
14010 }
14011 
14012 void bpf_object__destroy_subskeleton(struct bpf_object_subskeleton *s)
14013 {
14014 	if (!s)
14015 		return;
14016 	free(s->maps);
14017 	free(s->progs);
14018 	free(s->vars);
14019 	free(s);
14020 }
14021 
14022 int bpf_object__load_skeleton(struct bpf_object_skeleton *s)
14023 {
14024 	int i, err;
14025 
14026 	err = bpf_object__load(*s->obj);
14027 	if (err) {
14028 		pr_warn("failed to load BPF skeleton '%s': %s\n", s->name, errstr(err));
14029 		return libbpf_err(err);
14030 	}
14031 
14032 	for (i = 0; i < s->map_cnt; i++) {
14033 		struct bpf_map_skeleton *map_skel = (void *)s->maps + i * s->map_skel_sz;
14034 		struct bpf_map *map = *map_skel->map;
14035 
14036 		if (!map_skel->mmaped)
14037 			continue;
14038 
14039 		*map_skel->mmaped = map->mmaped;
14040 	}
14041 
14042 	return 0;
14043 }
14044 
14045 int bpf_object__attach_skeleton(struct bpf_object_skeleton *s)
14046 {
14047 	int i, err;
14048 
14049 	for (i = 0; i < s->prog_cnt; i++) {
14050 		struct bpf_prog_skeleton *prog_skel = (void *)s->progs + i * s->prog_skel_sz;
14051 		struct bpf_program *prog = *prog_skel->prog;
14052 		struct bpf_link **link = prog_skel->link;
14053 
14054 		if (!prog->autoload || !prog->autoattach)
14055 			continue;
14056 
14057 		/* auto-attaching not supported for this program */
14058 		if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
14059 			continue;
14060 
14061 		/* if user already set the link manually, don't attempt auto-attach */
14062 		if (*link)
14063 			continue;
14064 
14065 		err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, link);
14066 		if (err) {
14067 			pr_warn("prog '%s': failed to auto-attach: %s\n",
14068 				bpf_program__name(prog), errstr(err));
14069 			return libbpf_err(err);
14070 		}
14071 
14072 		/* It's possible that for some SEC() definitions auto-attach
14073 		 * is supported in some cases (e.g., if definition completely
14074 		 * specifies target information), but is not in other cases.
14075 		 * SEC("uprobe") is one such case. If user specified target
14076 		 * binary and function name, such BPF program can be
14077 		 * auto-attached. But if not, it shouldn't trigger skeleton's
14078 		 * attach to fail. It should just be skipped.
14079 		 * attach_fn signals such case with returning 0 (no error) and
14080 		 * setting link to NULL.
14081 		 */
14082 	}
14083 
14084 
14085 	for (i = 0; i < s->map_cnt; i++) {
14086 		struct bpf_map_skeleton *map_skel = (void *)s->maps + i * s->map_skel_sz;
14087 		struct bpf_map *map = *map_skel->map;
14088 		struct bpf_link **link;
14089 
14090 		if (!map->autocreate || !map->autoattach)
14091 			continue;
14092 
14093 		/* only struct_ops maps can be attached */
14094 		if (!bpf_map__is_struct_ops(map))
14095 			continue;
14096 
14097 		/* skeleton is created with earlier version of bpftool, notify user */
14098 		if (s->map_skel_sz < offsetofend(struct bpf_map_skeleton, link)) {
14099 			pr_warn("map '%s': BPF skeleton version is old, skipping map auto-attachment...\n",
14100 				bpf_map__name(map));
14101 			continue;
14102 		}
14103 
14104 		link = map_skel->link;
14105 		if (!link) {
14106 			pr_warn("map '%s': BPF map skeleton link is uninitialized\n",
14107 				bpf_map__name(map));
14108 			continue;
14109 		}
14110 
14111 		if (*link)
14112 			continue;
14113 
14114 		*link = bpf_map__attach_struct_ops(map);
14115 		if (!*link) {
14116 			err = -errno;
14117 			pr_warn("map '%s': failed to auto-attach: %s\n",
14118 				bpf_map__name(map), errstr(err));
14119 			return libbpf_err(err);
14120 		}
14121 	}
14122 
14123 	return 0;
14124 }
14125 
14126 void bpf_object__detach_skeleton(struct bpf_object_skeleton *s)
14127 {
14128 	int i;
14129 
14130 	for (i = 0; i < s->prog_cnt; i++) {
14131 		struct bpf_prog_skeleton *prog_skel = (void *)s->progs + i * s->prog_skel_sz;
14132 		struct bpf_link **link = prog_skel->link;
14133 
14134 		bpf_link__destroy(*link);
14135 		*link = NULL;
14136 	}
14137 
14138 	if (s->map_skel_sz < sizeof(struct bpf_map_skeleton))
14139 		return;
14140 
14141 	for (i = 0; i < s->map_cnt; i++) {
14142 		struct bpf_map_skeleton *map_skel = (void *)s->maps + i * s->map_skel_sz;
14143 		struct bpf_link **link = map_skel->link;
14144 
14145 		if (link) {
14146 			bpf_link__destroy(*link);
14147 			*link = NULL;
14148 		}
14149 	}
14150 }
14151 
14152 void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s)
14153 {
14154 	if (!s)
14155 		return;
14156 
14157 	bpf_object__detach_skeleton(s);
14158 	if (s->obj)
14159 		bpf_object__close(*s->obj);
14160 	free(s->maps);
14161 	free(s->progs);
14162 	free(s);
14163 }
14164