xref: /linux/tools/lib/bpf/libbpf.c (revision d786aba32000f20a58bb79c2e3ae326e4fb377a1)
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 	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 	int arena_map_idx;
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 	obj->arena_map_idx = -1;
1521 
1522 	obj->kern_version = get_kernel_version();
1523 	obj->state  = OBJ_OPEN;
1524 
1525 	return obj;
1526 }
1527 
1528 static void bpf_object__elf_finish(struct bpf_object *obj)
1529 {
1530 	if (!obj->efile.elf)
1531 		return;
1532 
1533 	elf_end(obj->efile.elf);
1534 	obj->efile.elf = NULL;
1535 	obj->efile.ehdr = NULL;
1536 	obj->efile.symbols = NULL;
1537 	obj->efile.arena_data = NULL;
1538 
1539 	zfree(&obj->efile.secs);
1540 	obj->efile.sec_cnt = 0;
1541 	zclose(obj->efile.fd);
1542 	obj->efile.obj_buf = NULL;
1543 	obj->efile.obj_buf_sz = 0;
1544 }
1545 
1546 static int bpf_object__elf_init(struct bpf_object *obj)
1547 {
1548 	Elf64_Ehdr *ehdr;
1549 	int err = 0;
1550 	Elf *elf;
1551 
1552 	if (obj->efile.elf) {
1553 		pr_warn("elf: init internal error\n");
1554 		return -LIBBPF_ERRNO__LIBELF;
1555 	}
1556 
1557 	if (obj->efile.obj_buf_sz > 0) {
1558 		/* obj_buf should have been validated by bpf_object__open_mem(). */
1559 		elf = elf_memory((char *)obj->efile.obj_buf, obj->efile.obj_buf_sz);
1560 	} else {
1561 		obj->efile.fd = open(obj->path, O_RDONLY | O_CLOEXEC);
1562 		if (obj->efile.fd < 0) {
1563 			err = -errno;
1564 			pr_warn("elf: failed to open %s: %s\n", obj->path, errstr(err));
1565 			return err;
1566 		}
1567 
1568 		elf = elf_begin(obj->efile.fd, ELF_C_READ_MMAP, NULL);
1569 	}
1570 
1571 	if (!elf) {
1572 		pr_warn("elf: failed to open %s as ELF file: %s\n", obj->path, elf_errmsg(-1));
1573 		err = -LIBBPF_ERRNO__LIBELF;
1574 		goto errout;
1575 	}
1576 
1577 	obj->efile.elf = elf;
1578 
1579 	if (elf_kind(elf) != ELF_K_ELF) {
1580 		err = -LIBBPF_ERRNO__FORMAT;
1581 		pr_warn("elf: '%s' is not a proper ELF object\n", obj->path);
1582 		goto errout;
1583 	}
1584 
1585 	if (gelf_getclass(elf) != ELFCLASS64) {
1586 		err = -LIBBPF_ERRNO__FORMAT;
1587 		pr_warn("elf: '%s' is not a 64-bit ELF object\n", obj->path);
1588 		goto errout;
1589 	}
1590 
1591 	obj->efile.ehdr = ehdr = elf64_getehdr(elf);
1592 	if (!obj->efile.ehdr) {
1593 		pr_warn("elf: failed to get ELF header from %s: %s\n", obj->path, elf_errmsg(-1));
1594 		err = -LIBBPF_ERRNO__FORMAT;
1595 		goto errout;
1596 	}
1597 
1598 	/* Validate ELF object endianness... */
1599 	if (ehdr->e_ident[EI_DATA] != ELFDATA2LSB &&
1600 	    ehdr->e_ident[EI_DATA] != ELFDATA2MSB) {
1601 		err = -LIBBPF_ERRNO__ENDIAN;
1602 		pr_warn("elf: '%s' has unknown byte order\n", obj->path);
1603 		goto errout;
1604 	}
1605 	/* and save after bpf_object_open() frees ELF data */
1606 	obj->byteorder = ehdr->e_ident[EI_DATA];
1607 
1608 	if (elf_getshdrstrndx(elf, &obj->efile.shstrndx)) {
1609 		pr_warn("elf: failed to get section names section index for %s: %s\n",
1610 			obj->path, elf_errmsg(-1));
1611 		err = -LIBBPF_ERRNO__FORMAT;
1612 		goto errout;
1613 	}
1614 
1615 	/* ELF is corrupted/truncated, avoid calling elf_strptr. */
1616 	if (!elf_rawdata(elf_getscn(elf, obj->efile.shstrndx), NULL)) {
1617 		pr_warn("elf: failed to get section names strings from %s: %s\n",
1618 			obj->path, elf_errmsg(-1));
1619 		err = -LIBBPF_ERRNO__FORMAT;
1620 		goto errout;
1621 	}
1622 
1623 	/* Old LLVM set e_machine to EM_NONE */
1624 	if (ehdr->e_type != ET_REL || (ehdr->e_machine && ehdr->e_machine != EM_BPF)) {
1625 		pr_warn("elf: %s is not a valid eBPF object file\n", obj->path);
1626 		err = -LIBBPF_ERRNO__FORMAT;
1627 		goto errout;
1628 	}
1629 
1630 	return 0;
1631 errout:
1632 	bpf_object__elf_finish(obj);
1633 	return err;
1634 }
1635 
1636 static bool is_native_endianness(struct bpf_object *obj)
1637 {
1638 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1639 	return obj->byteorder == ELFDATA2LSB;
1640 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
1641 	return obj->byteorder == ELFDATA2MSB;
1642 #else
1643 # error "Unrecognized __BYTE_ORDER__"
1644 #endif
1645 }
1646 
1647 static int
1648 bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
1649 {
1650 	if (!data) {
1651 		pr_warn("invalid license section in %s\n", obj->path);
1652 		return -LIBBPF_ERRNO__FORMAT;
1653 	}
1654 	/* libbpf_strlcpy() only copies first N - 1 bytes, so size + 1 won't
1655 	 * go over allowed ELF data section buffer
1656 	 */
1657 	libbpf_strlcpy(obj->license, data, min(size + 1, sizeof(obj->license)));
1658 	pr_debug("license of %s is %s\n", obj->path, obj->license);
1659 	return 0;
1660 }
1661 
1662 static int
1663 bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
1664 {
1665 	__u32 kver;
1666 
1667 	if (!data || size != sizeof(kver)) {
1668 		pr_warn("invalid kver section in %s\n", obj->path);
1669 		return -LIBBPF_ERRNO__FORMAT;
1670 	}
1671 	memcpy(&kver, data, sizeof(kver));
1672 	obj->kern_version = kver;
1673 	pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
1674 	return 0;
1675 }
1676 
1677 static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
1678 {
1679 	if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
1680 	    type == BPF_MAP_TYPE_HASH_OF_MAPS)
1681 		return true;
1682 	return false;
1683 }
1684 
1685 static int find_elf_sec_sz(const struct bpf_object *obj, const char *name, __u32 *size)
1686 {
1687 	Elf_Data *data;
1688 	Elf_Scn *scn;
1689 
1690 	if (!name)
1691 		return -EINVAL;
1692 
1693 	scn = elf_sec_by_name(obj, name);
1694 	data = elf_sec_data(obj, scn);
1695 	if (data) {
1696 		*size = data->d_size;
1697 		return 0; /* found it */
1698 	}
1699 
1700 	return -ENOENT;
1701 }
1702 
1703 static Elf64_Sym *find_elf_var_sym(const struct bpf_object *obj, const char *name)
1704 {
1705 	Elf_Data *symbols = obj->efile.symbols;
1706 	const char *sname;
1707 	size_t si;
1708 
1709 	for (si = 0; si < symbols->d_size / sizeof(Elf64_Sym); si++) {
1710 		Elf64_Sym *sym = elf_sym_by_idx(obj, si);
1711 
1712 		if (ELF64_ST_TYPE(sym->st_info) != STT_OBJECT)
1713 			continue;
1714 
1715 		if (ELF64_ST_BIND(sym->st_info) != STB_GLOBAL &&
1716 		    ELF64_ST_BIND(sym->st_info) != STB_WEAK)
1717 			continue;
1718 
1719 		sname = elf_sym_str(obj, sym->st_name);
1720 		if (!sname) {
1721 			pr_warn("failed to get sym name string for var %s\n", name);
1722 			return ERR_PTR(-EIO);
1723 		}
1724 		if (strcmp(name, sname) == 0)
1725 			return sym;
1726 	}
1727 
1728 	return ERR_PTR(-ENOENT);
1729 }
1730 
1731 #ifndef MFD_CLOEXEC
1732 #define MFD_CLOEXEC 0x0001U
1733 #endif
1734 #ifndef MFD_NOEXEC_SEAL
1735 #define MFD_NOEXEC_SEAL 0x0008U
1736 #endif
1737 
1738 static int create_placeholder_fd(void)
1739 {
1740 	unsigned int flags = MFD_CLOEXEC | MFD_NOEXEC_SEAL;
1741 	const char *name = "libbpf-placeholder-fd";
1742 	int fd;
1743 
1744 	fd = ensure_good_fd(sys_memfd_create(name, flags));
1745 	if (fd >= 0)
1746 		return fd;
1747 	else if (errno != EINVAL)
1748 		return -errno;
1749 
1750 	/* Possibly running on kernel without MFD_NOEXEC_SEAL */
1751 	fd = ensure_good_fd(sys_memfd_create(name, flags & ~MFD_NOEXEC_SEAL));
1752 	if (fd < 0)
1753 		return -errno;
1754 	return fd;
1755 }
1756 
1757 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
1758 {
1759 	struct bpf_map *map;
1760 	int err;
1761 
1762 	err = libbpf_ensure_mem((void **)&obj->maps, &obj->maps_cap,
1763 				sizeof(*obj->maps), obj->nr_maps + 1);
1764 	if (err)
1765 		return ERR_PTR(err);
1766 
1767 	map = &obj->maps[obj->nr_maps++];
1768 	map->obj = obj;
1769 	/* Preallocate map FD without actually creating BPF map just yet.
1770 	 * These map FD "placeholders" will be reused later without changing
1771 	 * FD value when map is actually created in the kernel.
1772 	 *
1773 	 * This is useful to be able to perform BPF program relocations
1774 	 * without having to create BPF maps before that step. This allows us
1775 	 * to finalize and load BTF very late in BPF object's loading phase,
1776 	 * right before BPF maps have to be created and BPF programs have to
1777 	 * be loaded. By having these map FD placeholders we can perform all
1778 	 * the sanitizations, relocations, and any other adjustments before we
1779 	 * start creating actual BPF kernel objects (BTF, maps, progs).
1780 	 */
1781 	map->fd = create_placeholder_fd();
1782 	if (map->fd < 0)
1783 		return ERR_PTR(map->fd);
1784 	map->inner_map_fd = -1;
1785 	map->autocreate = true;
1786 
1787 	return map;
1788 }
1789 
1790 static size_t array_map_mmap_sz(unsigned int value_sz, unsigned int max_entries)
1791 {
1792 	const long page_sz = sysconf(_SC_PAGE_SIZE);
1793 	size_t map_sz;
1794 
1795 	map_sz = (size_t)roundup(value_sz, 8) * max_entries;
1796 	map_sz = roundup(map_sz, page_sz);
1797 	return map_sz;
1798 }
1799 
1800 static size_t bpf_map_mmap_sz(const struct bpf_map *map)
1801 {
1802 	const long page_sz = sysconf(_SC_PAGE_SIZE);
1803 
1804 	switch (map->def.type) {
1805 	case BPF_MAP_TYPE_ARRAY:
1806 		return array_map_mmap_sz(map->def.value_size, map->def.max_entries);
1807 	case BPF_MAP_TYPE_ARENA:
1808 		return page_sz * map->def.max_entries;
1809 	default:
1810 		return 0; /* not supported */
1811 	}
1812 }
1813 
1814 static int bpf_map_mmap_resize(struct bpf_map *map, size_t old_sz, size_t new_sz)
1815 {
1816 	void *mmaped;
1817 
1818 	if (!map->mmaped)
1819 		return -EINVAL;
1820 
1821 	if (old_sz == new_sz)
1822 		return 0;
1823 
1824 	mmaped = mmap(NULL, new_sz, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1825 	if (mmaped == MAP_FAILED)
1826 		return -errno;
1827 
1828 	memcpy(mmaped, map->mmaped, min(old_sz, new_sz));
1829 	munmap(map->mmaped, old_sz);
1830 	map->mmaped = mmaped;
1831 	return 0;
1832 }
1833 
1834 static char *internal_map_name(struct bpf_object *obj, const char *real_name)
1835 {
1836 	char map_name[BPF_OBJ_NAME_LEN], *p;
1837 	int pfx_len, sfx_len = max((size_t)7, strlen(real_name));
1838 
1839 	/* This is one of the more confusing parts of libbpf for various
1840 	 * reasons, some of which are historical. The original idea for naming
1841 	 * internal names was to include as much of BPF object name prefix as
1842 	 * possible, so that it can be distinguished from similar internal
1843 	 * maps of a different BPF object.
1844 	 * As an example, let's say we have bpf_object named 'my_object_name'
1845 	 * and internal map corresponding to '.rodata' ELF section. The final
1846 	 * map name advertised to user and to the kernel will be
1847 	 * 'my_objec.rodata', taking first 8 characters of object name and
1848 	 * entire 7 characters of '.rodata'.
1849 	 * Somewhat confusingly, if internal map ELF section name is shorter
1850 	 * than 7 characters, e.g., '.bss', we still reserve 7 characters
1851 	 * for the suffix, even though we only have 4 actual characters, and
1852 	 * resulting map will be called 'my_objec.bss', not even using all 15
1853 	 * characters allowed by the kernel. Oh well, at least the truncated
1854 	 * object name is somewhat consistent in this case. But if the map
1855 	 * name is '.kconfig', we'll still have entirety of '.kconfig' added
1856 	 * (8 chars) and thus will be left with only first 7 characters of the
1857 	 * object name ('my_obje'). Happy guessing, user, that the final map
1858 	 * name will be "my_obje.kconfig".
1859 	 * Now, with libbpf starting to support arbitrarily named .rodata.*
1860 	 * and .data.* data sections, it's possible that ELF section name is
1861 	 * longer than allowed 15 chars, so we now need to be careful to take
1862 	 * only up to 15 first characters of ELF name, taking no BPF object
1863 	 * name characters at all. So '.rodata.abracadabra' will result in
1864 	 * '.rodata.abracad' kernel and user-visible name.
1865 	 * We need to keep this convoluted logic intact for .data, .bss and
1866 	 * .rodata maps, but for new custom .data.custom and .rodata.custom
1867 	 * maps we use their ELF names as is, not prepending bpf_object name
1868 	 * in front. We still need to truncate them to 15 characters for the
1869 	 * kernel. Full name can be recovered for such maps by using DATASEC
1870 	 * BTF type associated with such map's value type, though.
1871 	 */
1872 	if (sfx_len >= BPF_OBJ_NAME_LEN)
1873 		sfx_len = BPF_OBJ_NAME_LEN - 1;
1874 
1875 	/* if there are two or more dots in map name, it's a custom dot map */
1876 	if (strchr(real_name + 1, '.') != NULL)
1877 		pfx_len = 0;
1878 	else
1879 		pfx_len = min((size_t)BPF_OBJ_NAME_LEN - sfx_len - 1, strlen(obj->name));
1880 
1881 	snprintf(map_name, sizeof(map_name), "%.*s%.*s", pfx_len, obj->name,
1882 		 sfx_len, real_name);
1883 
1884 	/* sanities map name to characters allowed by kernel */
1885 	for (p = map_name; *p && p < map_name + sizeof(map_name); p++)
1886 		if (!isalnum(*p) && *p != '_' && *p != '.')
1887 			*p = '_';
1888 
1889 	return strdup(map_name);
1890 }
1891 
1892 static int
1893 map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map);
1894 
1895 /* Internal BPF map is mmap()'able only if at least one of corresponding
1896  * DATASEC's VARs are to be exposed through BPF skeleton. I.e., it's a GLOBAL
1897  * variable and it's not marked as __hidden (which turns it into, effectively,
1898  * a STATIC variable).
1899  */
1900 static bool map_is_mmapable(struct bpf_object *obj, struct bpf_map *map)
1901 {
1902 	const struct btf_type *t, *vt;
1903 	struct btf_var_secinfo *vsi;
1904 	int i, n;
1905 
1906 	if (!map->btf_value_type_id)
1907 		return false;
1908 
1909 	t = btf__type_by_id(obj->btf, map->btf_value_type_id);
1910 	if (!btf_is_datasec(t))
1911 		return false;
1912 
1913 	vsi = btf_var_secinfos(t);
1914 	for (i = 0, n = btf_vlen(t); i < n; i++, vsi++) {
1915 		vt = btf__type_by_id(obj->btf, vsi->type);
1916 		if (!btf_is_var(vt))
1917 			continue;
1918 
1919 		if (btf_var(vt)->linkage != BTF_VAR_STATIC)
1920 			return true;
1921 	}
1922 
1923 	return false;
1924 }
1925 
1926 static int
1927 bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
1928 			      const char *real_name, int sec_idx, void *data, size_t data_sz)
1929 {
1930 	struct bpf_map_def *def;
1931 	struct bpf_map *map;
1932 	size_t mmap_sz;
1933 	int err;
1934 
1935 	map = bpf_object__add_map(obj);
1936 	if (IS_ERR(map))
1937 		return PTR_ERR(map);
1938 
1939 	map->libbpf_type = type;
1940 	map->sec_idx = sec_idx;
1941 	map->sec_offset = 0;
1942 	map->real_name = strdup(real_name);
1943 	map->name = internal_map_name(obj, real_name);
1944 	if (!map->real_name || !map->name) {
1945 		zfree(&map->real_name);
1946 		zfree(&map->name);
1947 		return -ENOMEM;
1948 	}
1949 
1950 	def = &map->def;
1951 	def->type = BPF_MAP_TYPE_ARRAY;
1952 	def->key_size = sizeof(int);
1953 	def->value_size = data_sz;
1954 	def->max_entries = 1;
1955 	def->map_flags = type == LIBBPF_MAP_RODATA || type == LIBBPF_MAP_KCONFIG
1956 		? BPF_F_RDONLY_PROG : 0;
1957 
1958 	/* failures are fine because of maps like .rodata.str1.1 */
1959 	(void) map_fill_btf_type_info(obj, map);
1960 
1961 	if (map_is_mmapable(obj, map))
1962 		def->map_flags |= BPF_F_MMAPABLE;
1963 
1964 	pr_debug("map '%s' (global data): at sec_idx %d, offset %zu, flags %x.\n",
1965 		 map->name, map->sec_idx, map->sec_offset, def->map_flags);
1966 
1967 	mmap_sz = bpf_map_mmap_sz(map);
1968 	map->mmaped = mmap(NULL, mmap_sz, PROT_READ | PROT_WRITE,
1969 			   MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1970 	if (map->mmaped == MAP_FAILED) {
1971 		err = -errno;
1972 		map->mmaped = NULL;
1973 		pr_warn("failed to alloc map '%s' content buffer: %s\n", map->name, errstr(err));
1974 		zfree(&map->real_name);
1975 		zfree(&map->name);
1976 		return err;
1977 	}
1978 
1979 	if (data)
1980 		memcpy(map->mmaped, data, data_sz);
1981 
1982 	pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
1983 	return 0;
1984 }
1985 
1986 static int bpf_object__init_global_data_maps(struct bpf_object *obj)
1987 {
1988 	struct elf_sec_desc *sec_desc;
1989 	const char *sec_name;
1990 	int err = 0, sec_idx;
1991 
1992 	/*
1993 	 * Populate obj->maps with libbpf internal maps.
1994 	 */
1995 	for (sec_idx = 1; sec_idx < obj->efile.sec_cnt; sec_idx++) {
1996 		sec_desc = &obj->efile.secs[sec_idx];
1997 
1998 		/* Skip recognized sections with size 0. */
1999 		if (!sec_desc->data || sec_desc->data->d_size == 0)
2000 			continue;
2001 
2002 		switch (sec_desc->sec_type) {
2003 		case SEC_DATA:
2004 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
2005 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
2006 							    sec_name, sec_idx,
2007 							    sec_desc->data->d_buf,
2008 							    sec_desc->data->d_size);
2009 			break;
2010 		case SEC_RODATA:
2011 			obj->has_rodata = true;
2012 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
2013 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
2014 							    sec_name, sec_idx,
2015 							    sec_desc->data->d_buf,
2016 							    sec_desc->data->d_size);
2017 			break;
2018 		case SEC_BSS:
2019 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
2020 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
2021 							    sec_name, sec_idx,
2022 							    NULL,
2023 							    sec_desc->data->d_size);
2024 			break;
2025 		default:
2026 			/* skip */
2027 			break;
2028 		}
2029 		if (err)
2030 			return err;
2031 	}
2032 	return 0;
2033 }
2034 
2035 
2036 static struct extern_desc *find_extern_by_name(const struct bpf_object *obj,
2037 					       const void *name)
2038 {
2039 	int i;
2040 
2041 	for (i = 0; i < obj->nr_extern; i++) {
2042 		if (strcmp(obj->externs[i].name, name) == 0)
2043 			return &obj->externs[i];
2044 	}
2045 	return NULL;
2046 }
2047 
2048 static struct extern_desc *find_extern_by_name_with_len(const struct bpf_object *obj,
2049 							const void *name, int len)
2050 {
2051 	const char *ext_name;
2052 	int i;
2053 
2054 	for (i = 0; i < obj->nr_extern; i++) {
2055 		ext_name = obj->externs[i].name;
2056 		if (strlen(ext_name) == len && strncmp(ext_name, name, len) == 0)
2057 			return &obj->externs[i];
2058 	}
2059 	return NULL;
2060 }
2061 
2062 static int set_kcfg_value_tri(struct extern_desc *ext, void *ext_val,
2063 			      char value)
2064 {
2065 	switch (ext->kcfg.type) {
2066 	case KCFG_BOOL:
2067 		if (value == 'm') {
2068 			pr_warn("extern (kcfg) '%s': value '%c' implies tristate or char type\n",
2069 				ext->name, value);
2070 			return -EINVAL;
2071 		}
2072 		*(bool *)ext_val = value == 'y' ? true : false;
2073 		break;
2074 	case KCFG_TRISTATE:
2075 		if (value == 'y')
2076 			*(enum libbpf_tristate *)ext_val = TRI_YES;
2077 		else if (value == 'm')
2078 			*(enum libbpf_tristate *)ext_val = TRI_MODULE;
2079 		else /* value == 'n' */
2080 			*(enum libbpf_tristate *)ext_val = TRI_NO;
2081 		break;
2082 	case KCFG_CHAR:
2083 		*(char *)ext_val = value;
2084 		break;
2085 	case KCFG_UNKNOWN:
2086 	case KCFG_INT:
2087 	case KCFG_CHAR_ARR:
2088 	default:
2089 		pr_warn("extern (kcfg) '%s': value '%c' implies bool, tristate, or char type\n",
2090 			ext->name, value);
2091 		return -EINVAL;
2092 	}
2093 	ext->is_set = true;
2094 	return 0;
2095 }
2096 
2097 static int set_kcfg_value_str(struct extern_desc *ext, char *ext_val,
2098 			      const char *value)
2099 {
2100 	size_t len;
2101 
2102 	if (ext->kcfg.type != KCFG_CHAR_ARR) {
2103 		pr_warn("extern (kcfg) '%s': value '%s' implies char array type\n",
2104 			ext->name, value);
2105 		return -EINVAL;
2106 	}
2107 
2108 	len = strlen(value);
2109 	if (len < 2 || value[len - 1] != '"') {
2110 		pr_warn("extern (kcfg) '%s': invalid string config '%s'\n",
2111 			ext->name, value);
2112 		return -EINVAL;
2113 	}
2114 
2115 	/* strip quotes */
2116 	len -= 2;
2117 	if (len >= ext->kcfg.sz) {
2118 		pr_warn("extern (kcfg) '%s': long string '%s' of (%zu bytes) truncated to %d bytes\n",
2119 			ext->name, value, len, ext->kcfg.sz - 1);
2120 		len = ext->kcfg.sz - 1;
2121 	}
2122 	memcpy(ext_val, value + 1, len);
2123 	ext_val[len] = '\0';
2124 	ext->is_set = true;
2125 	return 0;
2126 }
2127 
2128 static int parse_u64(const char *value, __u64 *res)
2129 {
2130 	char *value_end;
2131 	int err;
2132 
2133 	errno = 0;
2134 	*res = strtoull(value, &value_end, 0);
2135 	if (errno) {
2136 		err = -errno;
2137 		pr_warn("failed to parse '%s': %s\n", value, errstr(err));
2138 		return err;
2139 	}
2140 	if (*value_end) {
2141 		pr_warn("failed to parse '%s' as integer completely\n", value);
2142 		return -EINVAL;
2143 	}
2144 	return 0;
2145 }
2146 
2147 static bool is_kcfg_value_in_range(const struct extern_desc *ext, __u64 v)
2148 {
2149 	int bit_sz = ext->kcfg.sz * 8;
2150 
2151 	if (ext->kcfg.sz == 8)
2152 		return true;
2153 
2154 	/* Validate that value stored in u64 fits in integer of `ext->sz`
2155 	 * bytes size without any loss of information. If the target integer
2156 	 * is signed, we rely on the following limits of integer type of
2157 	 * Y bits and subsequent transformation:
2158 	 *
2159 	 *     -2^(Y-1) <= X           <= 2^(Y-1) - 1
2160 	 *            0 <= X + 2^(Y-1) <= 2^Y - 1
2161 	 *            0 <= X + 2^(Y-1) <  2^Y
2162 	 *
2163 	 *  For unsigned target integer, check that all the (64 - Y) bits are
2164 	 *  zero.
2165 	 */
2166 	if (ext->kcfg.is_signed)
2167 		return v + (1ULL << (bit_sz - 1)) < (1ULL << bit_sz);
2168 	else
2169 		return (v >> bit_sz) == 0;
2170 }
2171 
2172 static int set_kcfg_value_num(struct extern_desc *ext, void *ext_val,
2173 			      __u64 value)
2174 {
2175 	if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR &&
2176 	    ext->kcfg.type != KCFG_BOOL) {
2177 		pr_warn("extern (kcfg) '%s': value '%llu' implies integer, char, or boolean type\n",
2178 			ext->name, (unsigned long long)value);
2179 		return -EINVAL;
2180 	}
2181 	if (ext->kcfg.type == KCFG_BOOL && value > 1) {
2182 		pr_warn("extern (kcfg) '%s': value '%llu' isn't boolean compatible\n",
2183 			ext->name, (unsigned long long)value);
2184 		return -EINVAL;
2185 
2186 	}
2187 	if (!is_kcfg_value_in_range(ext, value)) {
2188 		pr_warn("extern (kcfg) '%s': value '%llu' doesn't fit in %d bytes\n",
2189 			ext->name, (unsigned long long)value, ext->kcfg.sz);
2190 		return -ERANGE;
2191 	}
2192 	switch (ext->kcfg.sz) {
2193 	case 1:
2194 		*(__u8 *)ext_val = value;
2195 		break;
2196 	case 2:
2197 		*(__u16 *)ext_val = value;
2198 		break;
2199 	case 4:
2200 		*(__u32 *)ext_val = value;
2201 		break;
2202 	case 8:
2203 		*(__u64 *)ext_val = value;
2204 		break;
2205 	default:
2206 		return -EINVAL;
2207 	}
2208 	ext->is_set = true;
2209 	return 0;
2210 }
2211 
2212 static int bpf_object__process_kconfig_line(struct bpf_object *obj,
2213 					    char *buf, void *data)
2214 {
2215 	struct extern_desc *ext;
2216 	char *sep, *value;
2217 	int len, err = 0;
2218 	void *ext_val;
2219 	__u64 num;
2220 
2221 	if (!str_has_pfx(buf, "CONFIG_"))
2222 		return 0;
2223 
2224 	sep = strchr(buf, '=');
2225 	if (!sep) {
2226 		pr_warn("failed to parse '%s': no separator\n", buf);
2227 		return -EINVAL;
2228 	}
2229 
2230 	/* Trim ending '\n' */
2231 	len = strlen(buf);
2232 	if (buf[len - 1] == '\n')
2233 		buf[len - 1] = '\0';
2234 	/* Split on '=' and ensure that a value is present. */
2235 	*sep = '\0';
2236 	if (!sep[1]) {
2237 		*sep = '=';
2238 		pr_warn("failed to parse '%s': no value\n", buf);
2239 		return -EINVAL;
2240 	}
2241 
2242 	ext = find_extern_by_name(obj, buf);
2243 	if (!ext || ext->is_set)
2244 		return 0;
2245 
2246 	ext_val = data + ext->kcfg.data_off;
2247 	value = sep + 1;
2248 
2249 	switch (*value) {
2250 	case 'y': case 'n': case 'm':
2251 		err = set_kcfg_value_tri(ext, ext_val, *value);
2252 		break;
2253 	case '"':
2254 		err = set_kcfg_value_str(ext, ext_val, value);
2255 		break;
2256 	default:
2257 		/* assume integer */
2258 		err = parse_u64(value, &num);
2259 		if (err) {
2260 			pr_warn("extern (kcfg) '%s': value '%s' isn't a valid integer\n", ext->name, value);
2261 			return err;
2262 		}
2263 		if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR) {
2264 			pr_warn("extern (kcfg) '%s': value '%s' implies integer type\n", ext->name, value);
2265 			return -EINVAL;
2266 		}
2267 		err = set_kcfg_value_num(ext, ext_val, num);
2268 		break;
2269 	}
2270 	if (err)
2271 		return err;
2272 	pr_debug("extern (kcfg) '%s': set to %s\n", ext->name, value);
2273 	return 0;
2274 }
2275 
2276 static int bpf_object__read_kconfig_file(struct bpf_object *obj, void *data)
2277 {
2278 	char buf[PATH_MAX];
2279 	struct utsname uts;
2280 	int len, err = 0;
2281 	gzFile file;
2282 
2283 	uname(&uts);
2284 	len = snprintf(buf, PATH_MAX, "/boot/config-%s", uts.release);
2285 	if (len < 0)
2286 		return -EINVAL;
2287 	else if (len >= PATH_MAX)
2288 		return -ENAMETOOLONG;
2289 
2290 	/* gzopen also accepts uncompressed files. */
2291 	file = gzopen(buf, "re");
2292 	if (!file)
2293 		file = gzopen("/proc/config.gz", "re");
2294 
2295 	if (!file) {
2296 		pr_warn("failed to open system Kconfig\n");
2297 		return -ENOENT;
2298 	}
2299 
2300 	while (gzgets(file, buf, sizeof(buf))) {
2301 		err = bpf_object__process_kconfig_line(obj, buf, data);
2302 		if (err) {
2303 			pr_warn("error parsing system Kconfig line '%s': %s\n",
2304 				buf, errstr(err));
2305 			goto out;
2306 		}
2307 	}
2308 
2309 out:
2310 	gzclose(file);
2311 	return err;
2312 }
2313 
2314 static int bpf_object__read_kconfig_mem(struct bpf_object *obj,
2315 					const char *config, void *data)
2316 {
2317 	char buf[PATH_MAX];
2318 	int err = 0;
2319 	FILE *file;
2320 
2321 	file = fmemopen((void *)config, strlen(config), "r");
2322 	if (!file) {
2323 		err = -errno;
2324 		pr_warn("failed to open in-memory Kconfig: %s\n", errstr(err));
2325 		return err;
2326 	}
2327 
2328 	while (fgets(buf, sizeof(buf), file)) {
2329 		err = bpf_object__process_kconfig_line(obj, buf, data);
2330 		if (err) {
2331 			pr_warn("error parsing in-memory Kconfig line '%s': %s\n",
2332 				buf, errstr(err));
2333 			break;
2334 		}
2335 	}
2336 
2337 	fclose(file);
2338 	return err;
2339 }
2340 
2341 static int bpf_object__init_kconfig_map(struct bpf_object *obj)
2342 {
2343 	struct extern_desc *last_ext = NULL, *ext;
2344 	size_t map_sz;
2345 	int i, err;
2346 
2347 	for (i = 0; i < obj->nr_extern; i++) {
2348 		ext = &obj->externs[i];
2349 		if (ext->type == EXT_KCFG)
2350 			last_ext = ext;
2351 	}
2352 
2353 	if (!last_ext)
2354 		return 0;
2355 
2356 	map_sz = last_ext->kcfg.data_off + last_ext->kcfg.sz;
2357 	err = bpf_object__init_internal_map(obj, LIBBPF_MAP_KCONFIG,
2358 					    ".kconfig", obj->efile.symbols_shndx,
2359 					    NULL, map_sz);
2360 	if (err)
2361 		return err;
2362 
2363 	obj->kconfig_map_idx = obj->nr_maps - 1;
2364 
2365 	return 0;
2366 }
2367 
2368 const struct btf_type *
2369 skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id)
2370 {
2371 	const struct btf_type *t = btf__type_by_id(btf, id);
2372 
2373 	if (res_id)
2374 		*res_id = id;
2375 
2376 	while (btf_is_mod(t) || btf_is_typedef(t)) {
2377 		if (res_id)
2378 			*res_id = t->type;
2379 		t = btf__type_by_id(btf, t->type);
2380 	}
2381 
2382 	return t;
2383 }
2384 
2385 static const struct btf_type *
2386 resolve_func_ptr(const struct btf *btf, __u32 id, __u32 *res_id)
2387 {
2388 	const struct btf_type *t;
2389 
2390 	t = skip_mods_and_typedefs(btf, id, NULL);
2391 	if (!btf_is_ptr(t))
2392 		return NULL;
2393 
2394 	t = skip_mods_and_typedefs(btf, t->type, res_id);
2395 
2396 	return btf_is_func_proto(t) ? t : NULL;
2397 }
2398 
2399 static const char *__btf_kind_str(__u16 kind)
2400 {
2401 	switch (kind) {
2402 	case BTF_KIND_UNKN: return "void";
2403 	case BTF_KIND_INT: return "int";
2404 	case BTF_KIND_PTR: return "ptr";
2405 	case BTF_KIND_ARRAY: return "array";
2406 	case BTF_KIND_STRUCT: return "struct";
2407 	case BTF_KIND_UNION: return "union";
2408 	case BTF_KIND_ENUM: return "enum";
2409 	case BTF_KIND_FWD: return "fwd";
2410 	case BTF_KIND_TYPEDEF: return "typedef";
2411 	case BTF_KIND_VOLATILE: return "volatile";
2412 	case BTF_KIND_CONST: return "const";
2413 	case BTF_KIND_RESTRICT: return "restrict";
2414 	case BTF_KIND_FUNC: return "func";
2415 	case BTF_KIND_FUNC_PROTO: return "func_proto";
2416 	case BTF_KIND_VAR: return "var";
2417 	case BTF_KIND_DATASEC: return "datasec";
2418 	case BTF_KIND_FLOAT: return "float";
2419 	case BTF_KIND_DECL_TAG: return "decl_tag";
2420 	case BTF_KIND_TYPE_TAG: return "type_tag";
2421 	case BTF_KIND_ENUM64: return "enum64";
2422 	default: return "unknown";
2423 	}
2424 }
2425 
2426 const char *btf_kind_str(const struct btf_type *t)
2427 {
2428 	return __btf_kind_str(btf_kind(t));
2429 }
2430 
2431 /*
2432  * Fetch integer attribute of BTF map definition. Such attributes are
2433  * represented using a pointer to an array, in which dimensionality of array
2434  * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
2435  * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
2436  * type definition, while using only sizeof(void *) space in ELF data section.
2437  */
2438 static bool get_map_field_int(const char *map_name, const struct btf *btf,
2439 			      const struct btf_member *m, __u32 *res)
2440 {
2441 	const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
2442 	const char *name = btf__name_by_offset(btf, m->name_off);
2443 	const struct btf_array *arr_info;
2444 	const struct btf_type *arr_t;
2445 
2446 	if (!btf_is_ptr(t)) {
2447 		pr_warn("map '%s': attr '%s': expected PTR, got %s.\n",
2448 			map_name, name, btf_kind_str(t));
2449 		return false;
2450 	}
2451 
2452 	arr_t = btf__type_by_id(btf, t->type);
2453 	if (!arr_t) {
2454 		pr_warn("map '%s': attr '%s': type [%u] not found.\n",
2455 			map_name, name, t->type);
2456 		return false;
2457 	}
2458 	if (!btf_is_array(arr_t)) {
2459 		pr_warn("map '%s': attr '%s': expected ARRAY, got %s.\n",
2460 			map_name, name, btf_kind_str(arr_t));
2461 		return false;
2462 	}
2463 	arr_info = btf_array(arr_t);
2464 	*res = arr_info->nelems;
2465 	return true;
2466 }
2467 
2468 static bool get_map_field_long(const char *map_name, const struct btf *btf,
2469 			       const struct btf_member *m, __u64 *res)
2470 {
2471 	const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
2472 	const char *name = btf__name_by_offset(btf, m->name_off);
2473 
2474 	if (btf_is_ptr(t)) {
2475 		__u32 res32;
2476 		bool ret;
2477 
2478 		ret = get_map_field_int(map_name, btf, m, &res32);
2479 		if (ret)
2480 			*res = (__u64)res32;
2481 		return ret;
2482 	}
2483 
2484 	if (!btf_is_enum(t) && !btf_is_enum64(t)) {
2485 		pr_warn("map '%s': attr '%s': expected ENUM or ENUM64, got %s.\n",
2486 			map_name, name, btf_kind_str(t));
2487 		return false;
2488 	}
2489 
2490 	if (btf_vlen(t) != 1) {
2491 		pr_warn("map '%s': attr '%s': invalid __ulong\n",
2492 			map_name, name);
2493 		return false;
2494 	}
2495 
2496 	if (btf_is_enum(t)) {
2497 		const struct btf_enum *e = btf_enum(t);
2498 
2499 		*res = e->val;
2500 	} else {
2501 		const struct btf_enum64 *e = btf_enum64(t);
2502 
2503 		*res = btf_enum64_value(e);
2504 	}
2505 	return true;
2506 }
2507 
2508 static int pathname_concat(char *buf, size_t buf_sz, const char *path, const char *name)
2509 {
2510 	int len;
2511 
2512 	len = snprintf(buf, buf_sz, "%s/%s", path, name);
2513 	if (len < 0)
2514 		return -EINVAL;
2515 	if (len >= buf_sz)
2516 		return -ENAMETOOLONG;
2517 
2518 	return 0;
2519 }
2520 
2521 static int build_map_pin_path(struct bpf_map *map, const char *path)
2522 {
2523 	char buf[PATH_MAX];
2524 	int err;
2525 
2526 	if (!path)
2527 		path = BPF_FS_DEFAULT_PATH;
2528 
2529 	err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
2530 	if (err)
2531 		return err;
2532 
2533 	return bpf_map__set_pin_path(map, buf);
2534 }
2535 
2536 /* should match definition in bpf_helpers.h */
2537 enum libbpf_pin_type {
2538 	LIBBPF_PIN_NONE,
2539 	/* PIN_BY_NAME: pin maps by name (in /sys/fs/bpf by default) */
2540 	LIBBPF_PIN_BY_NAME,
2541 };
2542 
2543 int parse_btf_map_def(const char *map_name, struct btf *btf,
2544 		      const struct btf_type *def_t, bool strict,
2545 		      struct btf_map_def *map_def, struct btf_map_def *inner_def)
2546 {
2547 	const struct btf_type *t;
2548 	const struct btf_member *m;
2549 	bool is_inner = inner_def == NULL;
2550 	int vlen, i;
2551 
2552 	vlen = btf_vlen(def_t);
2553 	m = btf_members(def_t);
2554 	for (i = 0; i < vlen; i++, m++) {
2555 		const char *name = btf__name_by_offset(btf, m->name_off);
2556 
2557 		if (!name) {
2558 			pr_warn("map '%s': invalid field #%d.\n", map_name, i);
2559 			return -EINVAL;
2560 		}
2561 		if (strcmp(name, "type") == 0) {
2562 			if (!get_map_field_int(map_name, btf, m, &map_def->map_type))
2563 				return -EINVAL;
2564 			map_def->parts |= MAP_DEF_MAP_TYPE;
2565 		} else if (strcmp(name, "max_entries") == 0) {
2566 			if (!get_map_field_int(map_name, btf, m, &map_def->max_entries))
2567 				return -EINVAL;
2568 			map_def->parts |= MAP_DEF_MAX_ENTRIES;
2569 		} else if (strcmp(name, "map_flags") == 0) {
2570 			if (!get_map_field_int(map_name, btf, m, &map_def->map_flags))
2571 				return -EINVAL;
2572 			map_def->parts |= MAP_DEF_MAP_FLAGS;
2573 		} else if (strcmp(name, "numa_node") == 0) {
2574 			if (!get_map_field_int(map_name, btf, m, &map_def->numa_node))
2575 				return -EINVAL;
2576 			map_def->parts |= MAP_DEF_NUMA_NODE;
2577 		} else if (strcmp(name, "key_size") == 0) {
2578 			__u32 sz;
2579 
2580 			if (!get_map_field_int(map_name, btf, m, &sz))
2581 				return -EINVAL;
2582 			if (map_def->key_size && map_def->key_size != sz) {
2583 				pr_warn("map '%s': conflicting key size %u != %u.\n",
2584 					map_name, map_def->key_size, sz);
2585 				return -EINVAL;
2586 			}
2587 			map_def->key_size = sz;
2588 			map_def->parts |= MAP_DEF_KEY_SIZE;
2589 		} else if (strcmp(name, "key") == 0) {
2590 			__s64 sz;
2591 
2592 			t = btf__type_by_id(btf, m->type);
2593 			if (!t) {
2594 				pr_warn("map '%s': key type [%d] not found.\n",
2595 					map_name, m->type);
2596 				return -EINVAL;
2597 			}
2598 			if (!btf_is_ptr(t)) {
2599 				pr_warn("map '%s': key spec is not PTR: %s.\n",
2600 					map_name, btf_kind_str(t));
2601 				return -EINVAL;
2602 			}
2603 			sz = btf__resolve_size(btf, t->type);
2604 			if (sz < 0) {
2605 				pr_warn("map '%s': can't determine key size for type [%u]: %zd.\n",
2606 					map_name, t->type, (ssize_t)sz);
2607 				return sz;
2608 			}
2609 			if (map_def->key_size && map_def->key_size != sz) {
2610 				pr_warn("map '%s': conflicting key size %u != %zd.\n",
2611 					map_name, map_def->key_size, (ssize_t)sz);
2612 				return -EINVAL;
2613 			}
2614 			map_def->key_size = sz;
2615 			map_def->key_type_id = t->type;
2616 			map_def->parts |= MAP_DEF_KEY_SIZE | MAP_DEF_KEY_TYPE;
2617 		} else if (strcmp(name, "value_size") == 0) {
2618 			__u32 sz;
2619 
2620 			if (!get_map_field_int(map_name, btf, m, &sz))
2621 				return -EINVAL;
2622 			if (map_def->value_size && map_def->value_size != sz) {
2623 				pr_warn("map '%s': conflicting value size %u != %u.\n",
2624 					map_name, map_def->value_size, sz);
2625 				return -EINVAL;
2626 			}
2627 			map_def->value_size = sz;
2628 			map_def->parts |= MAP_DEF_VALUE_SIZE;
2629 		} else if (strcmp(name, "value") == 0) {
2630 			__s64 sz;
2631 
2632 			t = btf__type_by_id(btf, m->type);
2633 			if (!t) {
2634 				pr_warn("map '%s': value type [%d] not found.\n",
2635 					map_name, m->type);
2636 				return -EINVAL;
2637 			}
2638 			if (!btf_is_ptr(t)) {
2639 				pr_warn("map '%s': value spec is not PTR: %s.\n",
2640 					map_name, btf_kind_str(t));
2641 				return -EINVAL;
2642 			}
2643 			sz = btf__resolve_size(btf, t->type);
2644 			if (sz < 0) {
2645 				pr_warn("map '%s': can't determine value size for type [%u]: %zd.\n",
2646 					map_name, t->type, (ssize_t)sz);
2647 				return sz;
2648 			}
2649 			if (map_def->value_size && map_def->value_size != sz) {
2650 				pr_warn("map '%s': conflicting value size %u != %zd.\n",
2651 					map_name, map_def->value_size, (ssize_t)sz);
2652 				return -EINVAL;
2653 			}
2654 			map_def->value_size = sz;
2655 			map_def->value_type_id = t->type;
2656 			map_def->parts |= MAP_DEF_VALUE_SIZE | MAP_DEF_VALUE_TYPE;
2657 		}
2658 		else if (strcmp(name, "values") == 0) {
2659 			bool is_map_in_map = bpf_map_type__is_map_in_map(map_def->map_type);
2660 			bool is_prog_array = map_def->map_type == BPF_MAP_TYPE_PROG_ARRAY;
2661 			const char *desc = is_map_in_map ? "map-in-map inner" : "prog-array value";
2662 			char inner_map_name[128];
2663 			int err;
2664 
2665 			if (is_inner) {
2666 				pr_warn("map '%s': multi-level inner maps not supported.\n",
2667 					map_name);
2668 				return -ENOTSUP;
2669 			}
2670 			if (i != vlen - 1) {
2671 				pr_warn("map '%s': '%s' member should be last.\n",
2672 					map_name, name);
2673 				return -EINVAL;
2674 			}
2675 			if (!is_map_in_map && !is_prog_array) {
2676 				pr_warn("map '%s': should be map-in-map or prog-array.\n",
2677 					map_name);
2678 				return -ENOTSUP;
2679 			}
2680 			if (map_def->value_size && map_def->value_size != 4) {
2681 				pr_warn("map '%s': conflicting value size %u != 4.\n",
2682 					map_name, map_def->value_size);
2683 				return -EINVAL;
2684 			}
2685 			map_def->value_size = 4;
2686 			t = btf__type_by_id(btf, m->type);
2687 			if (!t) {
2688 				pr_warn("map '%s': %s type [%d] not found.\n",
2689 					map_name, desc, m->type);
2690 				return -EINVAL;
2691 			}
2692 			if (!btf_is_array(t) || btf_array(t)->nelems) {
2693 				pr_warn("map '%s': %s spec is not a zero-sized array.\n",
2694 					map_name, desc);
2695 				return -EINVAL;
2696 			}
2697 			t = skip_mods_and_typedefs(btf, btf_array(t)->type, NULL);
2698 			if (!btf_is_ptr(t)) {
2699 				pr_warn("map '%s': %s def is of unexpected kind %s.\n",
2700 					map_name, desc, btf_kind_str(t));
2701 				return -EINVAL;
2702 			}
2703 			t = skip_mods_and_typedefs(btf, t->type, NULL);
2704 			if (is_prog_array) {
2705 				if (!btf_is_func_proto(t)) {
2706 					pr_warn("map '%s': prog-array value def is of unexpected kind %s.\n",
2707 						map_name, btf_kind_str(t));
2708 					return -EINVAL;
2709 				}
2710 				continue;
2711 			}
2712 			if (!btf_is_struct(t)) {
2713 				pr_warn("map '%s': map-in-map inner def is of unexpected kind %s.\n",
2714 					map_name, btf_kind_str(t));
2715 				return -EINVAL;
2716 			}
2717 
2718 			snprintf(inner_map_name, sizeof(inner_map_name), "%s.inner", map_name);
2719 			err = parse_btf_map_def(inner_map_name, btf, t, strict, inner_def, NULL);
2720 			if (err)
2721 				return err;
2722 
2723 			map_def->parts |= MAP_DEF_INNER_MAP;
2724 		} else if (strcmp(name, "pinning") == 0) {
2725 			__u32 val;
2726 
2727 			if (is_inner) {
2728 				pr_warn("map '%s': inner def can't be pinned.\n", map_name);
2729 				return -EINVAL;
2730 			}
2731 			if (!get_map_field_int(map_name, btf, m, &val))
2732 				return -EINVAL;
2733 			if (val != LIBBPF_PIN_NONE && val != LIBBPF_PIN_BY_NAME) {
2734 				pr_warn("map '%s': invalid pinning value %u.\n",
2735 					map_name, val);
2736 				return -EINVAL;
2737 			}
2738 			map_def->pinning = val;
2739 			map_def->parts |= MAP_DEF_PINNING;
2740 		} else if (strcmp(name, "map_extra") == 0) {
2741 			__u64 map_extra;
2742 
2743 			if (!get_map_field_long(map_name, btf, m, &map_extra))
2744 				return -EINVAL;
2745 			map_def->map_extra = map_extra;
2746 			map_def->parts |= MAP_DEF_MAP_EXTRA;
2747 		} else {
2748 			if (strict) {
2749 				pr_warn("map '%s': unknown field '%s'.\n", map_name, name);
2750 				return -ENOTSUP;
2751 			}
2752 			pr_debug("map '%s': ignoring unknown field '%s'.\n", map_name, name);
2753 		}
2754 	}
2755 
2756 	if (map_def->map_type == BPF_MAP_TYPE_UNSPEC) {
2757 		pr_warn("map '%s': map type isn't specified.\n", map_name);
2758 		return -EINVAL;
2759 	}
2760 
2761 	return 0;
2762 }
2763 
2764 static size_t adjust_ringbuf_sz(size_t sz)
2765 {
2766 	__u32 page_sz = sysconf(_SC_PAGE_SIZE);
2767 	__u32 mul;
2768 
2769 	/* if user forgot to set any size, make sure they see error */
2770 	if (sz == 0)
2771 		return 0;
2772 	/* Kernel expects BPF_MAP_TYPE_RINGBUF's max_entries to be
2773 	 * a power-of-2 multiple of kernel's page size. If user diligently
2774 	 * satisified these conditions, pass the size through.
2775 	 */
2776 	if ((sz % page_sz) == 0 && is_pow_of_2(sz / page_sz))
2777 		return sz;
2778 
2779 	/* Otherwise find closest (page_sz * power_of_2) product bigger than
2780 	 * user-set size to satisfy both user size request and kernel
2781 	 * requirements and substitute correct max_entries for map creation.
2782 	 */
2783 	for (mul = 1; mul <= UINT_MAX / page_sz; mul <<= 1) {
2784 		if (mul * page_sz > sz)
2785 			return mul * page_sz;
2786 	}
2787 
2788 	/* if it's impossible to satisfy the conditions (i.e., user size is
2789 	 * very close to UINT_MAX but is not a power-of-2 multiple of
2790 	 * page_size) then just return original size and let kernel reject it
2791 	 */
2792 	return sz;
2793 }
2794 
2795 static bool map_is_ringbuf(const struct bpf_map *map)
2796 {
2797 	return map->def.type == BPF_MAP_TYPE_RINGBUF ||
2798 	       map->def.type == BPF_MAP_TYPE_USER_RINGBUF;
2799 }
2800 
2801 static void fill_map_from_def(struct bpf_map *map, const struct btf_map_def *def)
2802 {
2803 	map->def.type = def->map_type;
2804 	map->def.key_size = def->key_size;
2805 	map->def.value_size = def->value_size;
2806 	map->def.max_entries = def->max_entries;
2807 	map->def.map_flags = def->map_flags;
2808 	map->map_extra = def->map_extra;
2809 
2810 	map->numa_node = def->numa_node;
2811 	map->btf_key_type_id = def->key_type_id;
2812 	map->btf_value_type_id = def->value_type_id;
2813 
2814 	/* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
2815 	if (map_is_ringbuf(map))
2816 		map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
2817 
2818 	if (def->parts & MAP_DEF_MAP_TYPE)
2819 		pr_debug("map '%s': found type = %u.\n", map->name, def->map_type);
2820 
2821 	if (def->parts & MAP_DEF_KEY_TYPE)
2822 		pr_debug("map '%s': found key [%u], sz = %u.\n",
2823 			 map->name, def->key_type_id, def->key_size);
2824 	else if (def->parts & MAP_DEF_KEY_SIZE)
2825 		pr_debug("map '%s': found key_size = %u.\n", map->name, def->key_size);
2826 
2827 	if (def->parts & MAP_DEF_VALUE_TYPE)
2828 		pr_debug("map '%s': found value [%u], sz = %u.\n",
2829 			 map->name, def->value_type_id, def->value_size);
2830 	else if (def->parts & MAP_DEF_VALUE_SIZE)
2831 		pr_debug("map '%s': found value_size = %u.\n", map->name, def->value_size);
2832 
2833 	if (def->parts & MAP_DEF_MAX_ENTRIES)
2834 		pr_debug("map '%s': found max_entries = %u.\n", map->name, def->max_entries);
2835 	if (def->parts & MAP_DEF_MAP_FLAGS)
2836 		pr_debug("map '%s': found map_flags = 0x%x.\n", map->name, def->map_flags);
2837 	if (def->parts & MAP_DEF_MAP_EXTRA)
2838 		pr_debug("map '%s': found map_extra = 0x%llx.\n", map->name,
2839 			 (unsigned long long)def->map_extra);
2840 	if (def->parts & MAP_DEF_PINNING)
2841 		pr_debug("map '%s': found pinning = %u.\n", map->name, def->pinning);
2842 	if (def->parts & MAP_DEF_NUMA_NODE)
2843 		pr_debug("map '%s': found numa_node = %u.\n", map->name, def->numa_node);
2844 
2845 	if (def->parts & MAP_DEF_INNER_MAP)
2846 		pr_debug("map '%s': found inner map definition.\n", map->name);
2847 }
2848 
2849 static const char *btf_var_linkage_str(__u32 linkage)
2850 {
2851 	switch (linkage) {
2852 	case BTF_VAR_STATIC: return "static";
2853 	case BTF_VAR_GLOBAL_ALLOCATED: return "global";
2854 	case BTF_VAR_GLOBAL_EXTERN: return "extern";
2855 	default: return "unknown";
2856 	}
2857 }
2858 
2859 static int bpf_object__init_user_btf_map(struct bpf_object *obj,
2860 					 const struct btf_type *sec,
2861 					 int var_idx, int sec_idx,
2862 					 const Elf_Data *data, bool strict,
2863 					 const char *pin_root_path)
2864 {
2865 	struct btf_map_def map_def = {}, inner_def = {};
2866 	const struct btf_type *var, *def;
2867 	const struct btf_var_secinfo *vi;
2868 	const struct btf_var *var_extra;
2869 	const char *map_name;
2870 	struct bpf_map *map;
2871 	int err;
2872 
2873 	vi = btf_var_secinfos(sec) + var_idx;
2874 	var = btf__type_by_id(obj->btf, vi->type);
2875 	var_extra = btf_var(var);
2876 	map_name = btf__name_by_offset(obj->btf, var->name_off);
2877 
2878 	if (map_name == NULL || map_name[0] == '\0') {
2879 		pr_warn("map #%d: empty name.\n", var_idx);
2880 		return -EINVAL;
2881 	}
2882 	if ((__u64)vi->offset + vi->size > data->d_size) {
2883 		pr_warn("map '%s' BTF data is corrupted.\n", map_name);
2884 		return -EINVAL;
2885 	}
2886 	if (!btf_is_var(var)) {
2887 		pr_warn("map '%s': unexpected var kind %s.\n",
2888 			map_name, btf_kind_str(var));
2889 		return -EINVAL;
2890 	}
2891 	if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED) {
2892 		pr_warn("map '%s': unsupported map linkage %s.\n",
2893 			map_name, btf_var_linkage_str(var_extra->linkage));
2894 		return -EOPNOTSUPP;
2895 	}
2896 
2897 	def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
2898 	if (!btf_is_struct(def)) {
2899 		pr_warn("map '%s': unexpected def kind %s.\n",
2900 			map_name, btf_kind_str(var));
2901 		return -EINVAL;
2902 	}
2903 	if (def->size > vi->size) {
2904 		pr_warn("map '%s': invalid def size.\n", map_name);
2905 		return -EINVAL;
2906 	}
2907 
2908 	map = bpf_object__add_map(obj);
2909 	if (IS_ERR(map))
2910 		return PTR_ERR(map);
2911 	map->name = strdup(map_name);
2912 	if (!map->name) {
2913 		pr_warn("map '%s': failed to alloc map name.\n", map_name);
2914 		return -ENOMEM;
2915 	}
2916 	map->libbpf_type = LIBBPF_MAP_UNSPEC;
2917 	map->def.type = BPF_MAP_TYPE_UNSPEC;
2918 	map->sec_idx = sec_idx;
2919 	map->sec_offset = vi->offset;
2920 	map->btf_var_idx = var_idx;
2921 	pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
2922 		 map_name, map->sec_idx, map->sec_offset);
2923 
2924 	err = parse_btf_map_def(map->name, obj->btf, def, strict, &map_def, &inner_def);
2925 	if (err)
2926 		return err;
2927 
2928 	fill_map_from_def(map, &map_def);
2929 
2930 	if (map_def.pinning == LIBBPF_PIN_BY_NAME) {
2931 		err = build_map_pin_path(map, pin_root_path);
2932 		if (err) {
2933 			pr_warn("map '%s': couldn't build pin path.\n", map->name);
2934 			return err;
2935 		}
2936 	}
2937 
2938 	if (map_def.parts & MAP_DEF_INNER_MAP) {
2939 		map->inner_map = calloc(1, sizeof(*map->inner_map));
2940 		if (!map->inner_map)
2941 			return -ENOMEM;
2942 		map->inner_map->fd = create_placeholder_fd();
2943 		if (map->inner_map->fd < 0)
2944 			return map->inner_map->fd;
2945 		map->inner_map->sec_idx = sec_idx;
2946 		map->inner_map->name = malloc(strlen(map_name) + sizeof(".inner") + 1);
2947 		if (!map->inner_map->name)
2948 			return -ENOMEM;
2949 		sprintf(map->inner_map->name, "%s.inner", map_name);
2950 
2951 		fill_map_from_def(map->inner_map, &inner_def);
2952 	}
2953 
2954 	err = map_fill_btf_type_info(obj, map);
2955 	if (err)
2956 		return err;
2957 
2958 	return 0;
2959 }
2960 
2961 static int init_arena_map_data(struct bpf_object *obj, struct bpf_map *map,
2962 			       const char *sec_name, int sec_idx,
2963 			       void *data, size_t data_sz)
2964 {
2965 	const long page_sz = sysconf(_SC_PAGE_SIZE);
2966 	size_t mmap_sz;
2967 
2968 	mmap_sz = bpf_map_mmap_sz(map);
2969 	if (roundup(data_sz, page_sz) > mmap_sz) {
2970 		pr_warn("elf: sec '%s': declared ARENA map size (%zu) is too small to hold global __arena variables of size %zu\n",
2971 			sec_name, mmap_sz, data_sz);
2972 		return -E2BIG;
2973 	}
2974 
2975 	obj->arena_data = malloc(data_sz);
2976 	if (!obj->arena_data)
2977 		return -ENOMEM;
2978 	memcpy(obj->arena_data, data, data_sz);
2979 	obj->arena_data_sz = data_sz;
2980 
2981 	/* make bpf_map__init_value() work for ARENA maps */
2982 	map->mmaped = obj->arena_data;
2983 
2984 	return 0;
2985 }
2986 
2987 static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict,
2988 					  const char *pin_root_path)
2989 {
2990 	const struct btf_type *sec = NULL;
2991 	int nr_types, i, vlen, err;
2992 	const struct btf_type *t;
2993 	const char *name;
2994 	Elf_Data *data;
2995 	Elf_Scn *scn;
2996 
2997 	if (obj->efile.btf_maps_shndx < 0)
2998 		return 0;
2999 
3000 	scn = elf_sec_by_idx(obj, obj->efile.btf_maps_shndx);
3001 	data = elf_sec_data(obj, scn);
3002 	if (!scn || !data) {
3003 		pr_warn("elf: failed to get %s map definitions for %s\n",
3004 			MAPS_ELF_SEC, obj->path);
3005 		return -EINVAL;
3006 	}
3007 
3008 	nr_types = btf__type_cnt(obj->btf);
3009 	for (i = 1; i < nr_types; i++) {
3010 		t = btf__type_by_id(obj->btf, i);
3011 		if (!btf_is_datasec(t))
3012 			continue;
3013 		name = btf__name_by_offset(obj->btf, t->name_off);
3014 		if (strcmp(name, MAPS_ELF_SEC) == 0) {
3015 			sec = t;
3016 			obj->efile.btf_maps_sec_btf_id = i;
3017 			break;
3018 		}
3019 	}
3020 
3021 	if (!sec) {
3022 		pr_warn("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
3023 		return -ENOENT;
3024 	}
3025 
3026 	vlen = btf_vlen(sec);
3027 	for (i = 0; i < vlen; i++) {
3028 		err = bpf_object__init_user_btf_map(obj, sec, i,
3029 						    obj->efile.btf_maps_shndx,
3030 						    data, strict,
3031 						    pin_root_path);
3032 		if (err)
3033 			return err;
3034 	}
3035 
3036 	for (i = 0; i < obj->nr_maps; i++) {
3037 		struct bpf_map *map = &obj->maps[i];
3038 
3039 		if (map->def.type != BPF_MAP_TYPE_ARENA)
3040 			continue;
3041 
3042 		if (obj->arena_map_idx >= 0) {
3043 			pr_warn("map '%s': only single ARENA map is supported (map '%s' is also ARENA)\n",
3044 				map->name, obj->maps[obj->arena_map_idx].name);
3045 			return -EINVAL;
3046 		}
3047 		obj->arena_map_idx = i;
3048 
3049 		if (obj->efile.arena_data) {
3050 			err = init_arena_map_data(obj, map, ARENA_SEC, obj->efile.arena_data_shndx,
3051 						  obj->efile.arena_data->d_buf,
3052 						  obj->efile.arena_data->d_size);
3053 			if (err)
3054 				return err;
3055 		}
3056 	}
3057 	if (obj->efile.arena_data && obj->arena_map_idx < 0) {
3058 		pr_warn("elf: sec '%s': to use global __arena variables the ARENA map should be explicitly declared in SEC(\".maps\")\n",
3059 			ARENA_SEC);
3060 		return -ENOENT;
3061 	}
3062 
3063 	return 0;
3064 }
3065 
3066 static int bpf_object__init_maps(struct bpf_object *obj,
3067 				 const struct bpf_object_open_opts *opts)
3068 {
3069 	const char *pin_root_path;
3070 	bool strict;
3071 	int err = 0;
3072 
3073 	strict = !OPTS_GET(opts, relaxed_maps, false);
3074 	pin_root_path = OPTS_GET(opts, pin_root_path, NULL);
3075 
3076 	err = bpf_object__init_user_btf_maps(obj, strict, pin_root_path);
3077 	err = err ?: bpf_object__init_global_data_maps(obj);
3078 	err = err ?: bpf_object__init_kconfig_map(obj);
3079 	err = err ?: bpf_object_init_struct_ops(obj);
3080 
3081 	return err;
3082 }
3083 
3084 static bool section_have_execinstr(struct bpf_object *obj, int idx)
3085 {
3086 	Elf64_Shdr *sh;
3087 
3088 	sh = elf_sec_hdr(obj, elf_sec_by_idx(obj, idx));
3089 	if (!sh)
3090 		return false;
3091 
3092 	return sh->sh_flags & SHF_EXECINSTR;
3093 }
3094 
3095 static bool starts_with_qmark(const char *s)
3096 {
3097 	return s && s[0] == '?';
3098 }
3099 
3100 static bool btf_needs_sanitization(struct bpf_object *obj)
3101 {
3102 	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
3103 	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
3104 	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
3105 	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
3106 	bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
3107 	bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
3108 	bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
3109 	bool has_qmark_datasec = kernel_supports(obj, FEAT_BTF_QMARK_DATASEC);
3110 
3111 	return !has_func || !has_datasec || !has_func_global || !has_float ||
3112 	       !has_decl_tag || !has_type_tag || !has_enum64 || !has_qmark_datasec;
3113 }
3114 
3115 static int bpf_object__sanitize_btf(struct bpf_object *obj, struct btf *btf)
3116 {
3117 	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
3118 	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
3119 	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
3120 	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
3121 	bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
3122 	bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
3123 	bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
3124 	bool has_qmark_datasec = kernel_supports(obj, FEAT_BTF_QMARK_DATASEC);
3125 	int enum64_placeholder_id = 0;
3126 	struct btf_type *t;
3127 	int i, j, vlen;
3128 
3129 	for (i = 1; i < btf__type_cnt(btf); i++) {
3130 		t = (struct btf_type *)btf__type_by_id(btf, i);
3131 
3132 		if ((!has_datasec && btf_is_var(t)) || (!has_decl_tag && btf_is_decl_tag(t))) {
3133 			/* replace VAR/DECL_TAG with INT */
3134 			t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
3135 			/*
3136 			 * using size = 1 is the safest choice, 4 will be too
3137 			 * big and cause kernel BTF validation failure if
3138 			 * original variable took less than 4 bytes
3139 			 */
3140 			t->size = 1;
3141 			*(int *)(t + 1) = BTF_INT_ENC(0, 0, 8);
3142 		} else if (!has_datasec && btf_is_datasec(t)) {
3143 			/* replace DATASEC with STRUCT */
3144 			const struct btf_var_secinfo *v = btf_var_secinfos(t);
3145 			struct btf_member *m = btf_members(t);
3146 			struct btf_type *vt;
3147 			char *name;
3148 
3149 			name = (char *)btf__name_by_offset(btf, t->name_off);
3150 			while (*name) {
3151 				if (*name == '.' || *name == '?')
3152 					*name = '_';
3153 				name++;
3154 			}
3155 
3156 			vlen = btf_vlen(t);
3157 			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
3158 			for (j = 0; j < vlen; j++, v++, m++) {
3159 				/* order of field assignments is important */
3160 				m->offset = v->offset * 8;
3161 				m->type = v->type;
3162 				/* preserve variable name as member name */
3163 				vt = (void *)btf__type_by_id(btf, v->type);
3164 				m->name_off = vt->name_off;
3165 			}
3166 		} else if (!has_qmark_datasec && btf_is_datasec(t) &&
3167 			   starts_with_qmark(btf__name_by_offset(btf, t->name_off))) {
3168 			/* replace '?' prefix with '_' for DATASEC names */
3169 			char *name;
3170 
3171 			name = (char *)btf__name_by_offset(btf, t->name_off);
3172 			if (name[0] == '?')
3173 				name[0] = '_';
3174 		} else if (!has_func && btf_is_func_proto(t)) {
3175 			/* replace FUNC_PROTO with ENUM */
3176 			vlen = btf_vlen(t);
3177 			t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
3178 			t->size = sizeof(__u32); /* kernel enforced */
3179 		} else if (!has_func && btf_is_func(t)) {
3180 			/* replace FUNC with TYPEDEF */
3181 			t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
3182 		} else if (!has_func_global && btf_is_func(t)) {
3183 			/* replace BTF_FUNC_GLOBAL with BTF_FUNC_STATIC */
3184 			t->info = BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0);
3185 		} else if (!has_float && btf_is_float(t)) {
3186 			/* replace FLOAT with an equally-sized empty STRUCT;
3187 			 * since C compilers do not accept e.g. "float" as a
3188 			 * valid struct name, make it anonymous
3189 			 */
3190 			t->name_off = 0;
3191 			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, 0);
3192 		} else if (!has_type_tag && btf_is_type_tag(t)) {
3193 			/* replace TYPE_TAG with a CONST */
3194 			t->name_off = 0;
3195 			t->info = BTF_INFO_ENC(BTF_KIND_CONST, 0, 0);
3196 		} else if (!has_enum64 && btf_is_enum(t)) {
3197 			/* clear the kflag */
3198 			t->info = btf_type_info(btf_kind(t), btf_vlen(t), false);
3199 		} else if (!has_enum64 && btf_is_enum64(t)) {
3200 			/* replace ENUM64 with a union */
3201 			struct btf_member *m;
3202 
3203 			if (enum64_placeholder_id == 0) {
3204 				enum64_placeholder_id = btf__add_int(btf, "enum64_placeholder", 1, 0);
3205 				if (enum64_placeholder_id < 0)
3206 					return enum64_placeholder_id;
3207 
3208 				t = (struct btf_type *)btf__type_by_id(btf, i);
3209 			}
3210 
3211 			m = btf_members(t);
3212 			vlen = btf_vlen(t);
3213 			t->info = BTF_INFO_ENC(BTF_KIND_UNION, 0, vlen);
3214 			for (j = 0; j < vlen; j++, m++) {
3215 				m->type = enum64_placeholder_id;
3216 				m->offset = 0;
3217 			}
3218 		}
3219 	}
3220 
3221 	return 0;
3222 }
3223 
3224 static bool libbpf_needs_btf(const struct bpf_object *obj)
3225 {
3226 	return obj->efile.btf_maps_shndx >= 0 ||
3227 	       obj->efile.has_st_ops ||
3228 	       obj->nr_extern > 0;
3229 }
3230 
3231 static bool kernel_needs_btf(const struct bpf_object *obj)
3232 {
3233 	return obj->efile.has_st_ops;
3234 }
3235 
3236 static int bpf_object__init_btf(struct bpf_object *obj,
3237 				Elf_Data *btf_data,
3238 				Elf_Data *btf_ext_data)
3239 {
3240 	int err = -ENOENT;
3241 
3242 	if (btf_data) {
3243 		obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
3244 		err = libbpf_get_error(obj->btf);
3245 		if (err) {
3246 			obj->btf = NULL;
3247 			pr_warn("Error loading ELF section %s: %s.\n", BTF_ELF_SEC, errstr(err));
3248 			goto out;
3249 		}
3250 		/* enforce 8-byte pointers for BPF-targeted BTFs */
3251 		btf__set_pointer_size(obj->btf, 8);
3252 	}
3253 	if (btf_ext_data) {
3254 		struct btf_ext_info *ext_segs[3];
3255 		int seg_num, sec_num;
3256 
3257 		if (!obj->btf) {
3258 			pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
3259 				 BTF_EXT_ELF_SEC, BTF_ELF_SEC);
3260 			goto out;
3261 		}
3262 		obj->btf_ext = btf_ext__new(btf_ext_data->d_buf, btf_ext_data->d_size);
3263 		err = libbpf_get_error(obj->btf_ext);
3264 		if (err) {
3265 			pr_warn("Error loading ELF section %s: %s. Ignored and continue.\n",
3266 				BTF_EXT_ELF_SEC, errstr(err));
3267 			obj->btf_ext = NULL;
3268 			goto out;
3269 		}
3270 
3271 		/* setup .BTF.ext to ELF section mapping */
3272 		ext_segs[0] = &obj->btf_ext->func_info;
3273 		ext_segs[1] = &obj->btf_ext->line_info;
3274 		ext_segs[2] = &obj->btf_ext->core_relo_info;
3275 		for (seg_num = 0; seg_num < ARRAY_SIZE(ext_segs); seg_num++) {
3276 			struct btf_ext_info *seg = ext_segs[seg_num];
3277 			const struct btf_ext_info_sec *sec;
3278 			const char *sec_name;
3279 			Elf_Scn *scn;
3280 
3281 			if (seg->sec_cnt == 0)
3282 				continue;
3283 
3284 			seg->sec_idxs = calloc(seg->sec_cnt, sizeof(*seg->sec_idxs));
3285 			if (!seg->sec_idxs) {
3286 				err = -ENOMEM;
3287 				goto out;
3288 			}
3289 
3290 			sec_num = 0;
3291 			for_each_btf_ext_sec(seg, sec) {
3292 				/* preventively increment index to avoid doing
3293 				 * this before every continue below
3294 				 */
3295 				sec_num++;
3296 
3297 				sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
3298 				if (str_is_empty(sec_name))
3299 					continue;
3300 				scn = elf_sec_by_name(obj, sec_name);
3301 				if (!scn)
3302 					continue;
3303 
3304 				seg->sec_idxs[sec_num - 1] = elf_ndxscn(scn);
3305 			}
3306 		}
3307 	}
3308 out:
3309 	if (err && libbpf_needs_btf(obj)) {
3310 		pr_warn("BTF is required, but is missing or corrupted.\n");
3311 		return err;
3312 	}
3313 	return 0;
3314 }
3315 
3316 static int compare_vsi_off(const void *_a, const void *_b)
3317 {
3318 	const struct btf_var_secinfo *a = _a;
3319 	const struct btf_var_secinfo *b = _b;
3320 
3321 	return a->offset - b->offset;
3322 }
3323 
3324 static int btf_fixup_datasec(struct bpf_object *obj, struct btf *btf,
3325 			     struct btf_type *t)
3326 {
3327 	__u32 size = 0, i, vars = btf_vlen(t);
3328 	const char *sec_name = btf__name_by_offset(btf, t->name_off);
3329 	struct btf_var_secinfo *vsi;
3330 	bool fixup_offsets = false;
3331 	int err;
3332 
3333 	if (!sec_name) {
3334 		pr_debug("No name found in string section for DATASEC kind.\n");
3335 		return -ENOENT;
3336 	}
3337 
3338 	/* Extern-backing datasecs (.ksyms, .kconfig) have their size and
3339 	 * variable offsets set at the previous step. Further, not every
3340 	 * extern BTF VAR has corresponding ELF symbol preserved, so we skip
3341 	 * all fixups altogether for such sections and go straight to sorting
3342 	 * VARs within their DATASEC.
3343 	 */
3344 	if (strcmp(sec_name, KCONFIG_SEC) == 0 || strcmp(sec_name, KSYMS_SEC) == 0)
3345 		goto sort_vars;
3346 
3347 	/* Clang leaves DATASEC size and VAR offsets as zeroes, so we need to
3348 	 * fix this up. But BPF static linker already fixes this up and fills
3349 	 * all the sizes and offsets during static linking. So this step has
3350 	 * to be optional. But the STV_HIDDEN handling is non-optional for any
3351 	 * non-extern DATASEC, so the variable fixup loop below handles both
3352 	 * functions at the same time, paying the cost of BTF VAR <-> ELF
3353 	 * symbol matching just once.
3354 	 */
3355 	if (t->size == 0) {
3356 		err = find_elf_sec_sz(obj, sec_name, &size);
3357 		if (err || !size) {
3358 			pr_debug("sec '%s': failed to determine size from ELF: size %u, err %s\n",
3359 				 sec_name, size, errstr(err));
3360 			return -ENOENT;
3361 		}
3362 
3363 		t->size = size;
3364 		fixup_offsets = true;
3365 	}
3366 
3367 	for (i = 0, vsi = btf_var_secinfos(t); i < vars; i++, vsi++) {
3368 		const struct btf_type *t_var;
3369 		struct btf_var *var;
3370 		const char *var_name;
3371 		Elf64_Sym *sym;
3372 
3373 		t_var = btf__type_by_id(btf, vsi->type);
3374 		if (!t_var || !btf_is_var(t_var)) {
3375 			pr_debug("sec '%s': unexpected non-VAR type found\n", sec_name);
3376 			return -EINVAL;
3377 		}
3378 
3379 		var = btf_var(t_var);
3380 		if (var->linkage == BTF_VAR_STATIC || var->linkage == BTF_VAR_GLOBAL_EXTERN)
3381 			continue;
3382 
3383 		var_name = btf__name_by_offset(btf, t_var->name_off);
3384 		if (!var_name) {
3385 			pr_debug("sec '%s': failed to find name of DATASEC's member #%d\n",
3386 				 sec_name, i);
3387 			return -ENOENT;
3388 		}
3389 
3390 		sym = find_elf_var_sym(obj, var_name);
3391 		if (IS_ERR(sym)) {
3392 			pr_debug("sec '%s': failed to find ELF symbol for VAR '%s'\n",
3393 				 sec_name, var_name);
3394 			return -ENOENT;
3395 		}
3396 
3397 		if (fixup_offsets)
3398 			vsi->offset = sym->st_value;
3399 
3400 		/* if variable is a global/weak symbol, but has restricted
3401 		 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF VAR
3402 		 * as static. This follows similar logic for functions (BPF
3403 		 * subprogs) and influences libbpf's further decisions about
3404 		 * whether to make global data BPF array maps as
3405 		 * BPF_F_MMAPABLE.
3406 		 */
3407 		if (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
3408 		    || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL)
3409 			var->linkage = BTF_VAR_STATIC;
3410 	}
3411 
3412 sort_vars:
3413 	qsort(btf_var_secinfos(t), vars, sizeof(*vsi), compare_vsi_off);
3414 	return 0;
3415 }
3416 
3417 static int bpf_object_fixup_btf(struct bpf_object *obj)
3418 {
3419 	int i, n, err = 0;
3420 
3421 	if (!obj->btf)
3422 		return 0;
3423 
3424 	n = btf__type_cnt(obj->btf);
3425 	for (i = 1; i < n; i++) {
3426 		struct btf_type *t = btf_type_by_id(obj->btf, i);
3427 
3428 		/* Loader needs to fix up some of the things compiler
3429 		 * couldn't get its hands on while emitting BTF. This
3430 		 * is section size and global variable offset. We use
3431 		 * the info from the ELF itself for this purpose.
3432 		 */
3433 		if (btf_is_datasec(t)) {
3434 			err = btf_fixup_datasec(obj, obj->btf, t);
3435 			if (err)
3436 				return err;
3437 		}
3438 	}
3439 
3440 	return 0;
3441 }
3442 
3443 static bool prog_needs_vmlinux_btf(struct bpf_program *prog)
3444 {
3445 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
3446 	    prog->type == BPF_PROG_TYPE_LSM)
3447 		return true;
3448 
3449 	/* BPF_PROG_TYPE_TRACING programs which do not attach to other programs
3450 	 * also need vmlinux BTF
3451 	 */
3452 	if (prog->type == BPF_PROG_TYPE_TRACING && !prog->attach_prog_fd)
3453 		return true;
3454 
3455 	return false;
3456 }
3457 
3458 static bool map_needs_vmlinux_btf(struct bpf_map *map)
3459 {
3460 	return bpf_map__is_struct_ops(map);
3461 }
3462 
3463 static bool obj_needs_vmlinux_btf(const struct bpf_object *obj)
3464 {
3465 	struct bpf_program *prog;
3466 	struct bpf_map *map;
3467 	int i;
3468 
3469 	/* CO-RE relocations need kernel BTF, only when btf_custom_path
3470 	 * is not specified
3471 	 */
3472 	if (obj->btf_ext && obj->btf_ext->core_relo_info.len && !obj->btf_custom_path)
3473 		return true;
3474 
3475 	/* Support for typed ksyms needs kernel BTF */
3476 	for (i = 0; i < obj->nr_extern; i++) {
3477 		const struct extern_desc *ext;
3478 
3479 		ext = &obj->externs[i];
3480 		if (ext->type == EXT_KSYM && ext->ksym.type_id)
3481 			return true;
3482 	}
3483 
3484 	bpf_object__for_each_program(prog, obj) {
3485 		if (!prog->autoload)
3486 			continue;
3487 		if (prog_needs_vmlinux_btf(prog))
3488 			return true;
3489 	}
3490 
3491 	bpf_object__for_each_map(map, obj) {
3492 		if (map_needs_vmlinux_btf(map))
3493 			return true;
3494 	}
3495 
3496 	return false;
3497 }
3498 
3499 static int bpf_object__load_vmlinux_btf(struct bpf_object *obj, bool force)
3500 {
3501 	int err;
3502 
3503 	/* btf_vmlinux could be loaded earlier */
3504 	if (obj->btf_vmlinux || obj->gen_loader)
3505 		return 0;
3506 
3507 	if (!force && !obj_needs_vmlinux_btf(obj))
3508 		return 0;
3509 
3510 	obj->btf_vmlinux = btf__load_vmlinux_btf();
3511 	err = libbpf_get_error(obj->btf_vmlinux);
3512 	if (err) {
3513 		pr_warn("Error loading vmlinux BTF: %s\n", errstr(err));
3514 		obj->btf_vmlinux = NULL;
3515 		return err;
3516 	}
3517 	return 0;
3518 }
3519 
3520 static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
3521 {
3522 	struct btf *kern_btf = obj->btf;
3523 	bool btf_mandatory, sanitize;
3524 	int i, err = 0;
3525 
3526 	if (!obj->btf)
3527 		return 0;
3528 
3529 	if (!kernel_supports(obj, FEAT_BTF)) {
3530 		if (kernel_needs_btf(obj)) {
3531 			err = -EOPNOTSUPP;
3532 			goto report;
3533 		}
3534 		pr_debug("Kernel doesn't support BTF, skipping uploading it.\n");
3535 		return 0;
3536 	}
3537 
3538 	/* Even though some subprogs are global/weak, user might prefer more
3539 	 * permissive BPF verification process that BPF verifier performs for
3540 	 * static functions, taking into account more context from the caller
3541 	 * functions. In such case, they need to mark such subprogs with
3542 	 * __attribute__((visibility("hidden"))) and libbpf will adjust
3543 	 * corresponding FUNC BTF type to be marked as static and trigger more
3544 	 * involved BPF verification process.
3545 	 */
3546 	for (i = 0; i < obj->nr_programs; i++) {
3547 		struct bpf_program *prog = &obj->programs[i];
3548 		struct btf_type *t;
3549 		const char *name;
3550 		int j, n;
3551 
3552 		if (!prog->mark_btf_static || !prog_is_subprog(obj, prog))
3553 			continue;
3554 
3555 		n = btf__type_cnt(obj->btf);
3556 		for (j = 1; j < n; j++) {
3557 			t = btf_type_by_id(obj->btf, j);
3558 			if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL)
3559 				continue;
3560 
3561 			name = btf__str_by_offset(obj->btf, t->name_off);
3562 			if (strcmp(name, prog->name) != 0)
3563 				continue;
3564 
3565 			t->info = btf_type_info(BTF_KIND_FUNC, BTF_FUNC_STATIC, 0);
3566 			break;
3567 		}
3568 	}
3569 
3570 	sanitize = btf_needs_sanitization(obj);
3571 	if (sanitize) {
3572 		const void *raw_data;
3573 		__u32 sz;
3574 
3575 		/* clone BTF to sanitize a copy and leave the original intact */
3576 		raw_data = btf__raw_data(obj->btf, &sz);
3577 		kern_btf = btf__new(raw_data, sz);
3578 		err = libbpf_get_error(kern_btf);
3579 		if (err)
3580 			return err;
3581 
3582 		/* enforce 8-byte pointers for BPF-targeted BTFs */
3583 		btf__set_pointer_size(obj->btf, 8);
3584 		err = bpf_object__sanitize_btf(obj, kern_btf);
3585 		if (err)
3586 			return err;
3587 	}
3588 
3589 	if (obj->gen_loader) {
3590 		__u32 raw_size = 0;
3591 		const void *raw_data = btf__raw_data(kern_btf, &raw_size);
3592 
3593 		if (!raw_data)
3594 			return -ENOMEM;
3595 		bpf_gen__load_btf(obj->gen_loader, raw_data, raw_size);
3596 		/* Pretend to have valid FD to pass various fd >= 0 checks.
3597 		 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
3598 		 */
3599 		btf__set_fd(kern_btf, 0);
3600 	} else {
3601 		/* currently BPF_BTF_LOAD only supports log_level 1 */
3602 		err = btf_load_into_kernel(kern_btf, obj->log_buf, obj->log_size,
3603 					   obj->log_level ? 1 : 0, obj->token_fd);
3604 	}
3605 	if (sanitize) {
3606 		if (!err) {
3607 			/* move fd to libbpf's BTF */
3608 			btf__set_fd(obj->btf, btf__fd(kern_btf));
3609 			btf__set_fd(kern_btf, -1);
3610 		}
3611 		btf__free(kern_btf);
3612 	}
3613 report:
3614 	if (err) {
3615 		btf_mandatory = kernel_needs_btf(obj);
3616 		if (btf_mandatory) {
3617 			pr_warn("Error loading .BTF into kernel: %s. BTF is mandatory, can't proceed.\n",
3618 				errstr(err));
3619 		} else {
3620 			pr_info("Error loading .BTF into kernel: %s. BTF is optional, ignoring.\n",
3621 				errstr(err));
3622 			err = 0;
3623 		}
3624 	}
3625 	return err;
3626 }
3627 
3628 static const char *elf_sym_str(const struct bpf_object *obj, size_t off)
3629 {
3630 	const char *name;
3631 
3632 	name = elf_strptr(obj->efile.elf, obj->efile.strtabidx, off);
3633 	if (!name) {
3634 		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3635 			off, obj->path, elf_errmsg(-1));
3636 		return NULL;
3637 	}
3638 
3639 	return name;
3640 }
3641 
3642 static const char *elf_sec_str(const struct bpf_object *obj, size_t off)
3643 {
3644 	const char *name;
3645 
3646 	name = elf_strptr(obj->efile.elf, obj->efile.shstrndx, off);
3647 	if (!name) {
3648 		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3649 			off, obj->path, elf_errmsg(-1));
3650 		return NULL;
3651 	}
3652 
3653 	return name;
3654 }
3655 
3656 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx)
3657 {
3658 	Elf_Scn *scn;
3659 
3660 	scn = elf_getscn(obj->efile.elf, idx);
3661 	if (!scn) {
3662 		pr_warn("elf: failed to get section(%zu) from %s: %s\n",
3663 			idx, obj->path, elf_errmsg(-1));
3664 		return NULL;
3665 	}
3666 	return scn;
3667 }
3668 
3669 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name)
3670 {
3671 	Elf_Scn *scn = NULL;
3672 	Elf *elf = obj->efile.elf;
3673 	const char *sec_name;
3674 
3675 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3676 		sec_name = elf_sec_name(obj, scn);
3677 		if (!sec_name)
3678 			return NULL;
3679 
3680 		if (strcmp(sec_name, name) != 0)
3681 			continue;
3682 
3683 		return scn;
3684 	}
3685 	return NULL;
3686 }
3687 
3688 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn)
3689 {
3690 	Elf64_Shdr *shdr;
3691 
3692 	if (!scn)
3693 		return NULL;
3694 
3695 	shdr = elf64_getshdr(scn);
3696 	if (!shdr) {
3697 		pr_warn("elf: failed to get section(%zu) header from %s: %s\n",
3698 			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3699 		return NULL;
3700 	}
3701 
3702 	return shdr;
3703 }
3704 
3705 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn)
3706 {
3707 	const char *name;
3708 	Elf64_Shdr *sh;
3709 
3710 	if (!scn)
3711 		return NULL;
3712 
3713 	sh = elf_sec_hdr(obj, scn);
3714 	if (!sh)
3715 		return NULL;
3716 
3717 	name = elf_sec_str(obj, sh->sh_name);
3718 	if (!name) {
3719 		pr_warn("elf: failed to get section(%zu) name from %s: %s\n",
3720 			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3721 		return NULL;
3722 	}
3723 
3724 	return name;
3725 }
3726 
3727 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn)
3728 {
3729 	Elf_Data *data;
3730 
3731 	if (!scn)
3732 		return NULL;
3733 
3734 	data = elf_getdata(scn, 0);
3735 	if (!data) {
3736 		pr_warn("elf: failed to get section(%zu) %s data from %s: %s\n",
3737 			elf_ndxscn(scn), elf_sec_name(obj, scn) ?: "<?>",
3738 			obj->path, elf_errmsg(-1));
3739 		return NULL;
3740 	}
3741 
3742 	return data;
3743 }
3744 
3745 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx)
3746 {
3747 	if (idx >= obj->efile.symbols->d_size / sizeof(Elf64_Sym))
3748 		return NULL;
3749 
3750 	return (Elf64_Sym *)obj->efile.symbols->d_buf + idx;
3751 }
3752 
3753 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx)
3754 {
3755 	if (idx >= data->d_size / sizeof(Elf64_Rel))
3756 		return NULL;
3757 
3758 	return (Elf64_Rel *)data->d_buf + idx;
3759 }
3760 
3761 static bool is_sec_name_dwarf(const char *name)
3762 {
3763 	/* approximation, but the actual list is too long */
3764 	return str_has_pfx(name, ".debug_");
3765 }
3766 
3767 static bool ignore_elf_section(Elf64_Shdr *hdr, const char *name)
3768 {
3769 	/* no special handling of .strtab */
3770 	if (hdr->sh_type == SHT_STRTAB)
3771 		return true;
3772 
3773 	/* ignore .llvm_addrsig section as well */
3774 	if (hdr->sh_type == SHT_LLVM_ADDRSIG)
3775 		return true;
3776 
3777 	/* no subprograms will lead to an empty .text section, ignore it */
3778 	if (hdr->sh_type == SHT_PROGBITS && hdr->sh_size == 0 &&
3779 	    strcmp(name, ".text") == 0)
3780 		return true;
3781 
3782 	/* DWARF sections */
3783 	if (is_sec_name_dwarf(name))
3784 		return true;
3785 
3786 	if (str_has_pfx(name, ".rel")) {
3787 		name += sizeof(".rel") - 1;
3788 		/* DWARF section relocations */
3789 		if (is_sec_name_dwarf(name))
3790 			return true;
3791 
3792 		/* .BTF and .BTF.ext don't need relocations */
3793 		if (strcmp(name, BTF_ELF_SEC) == 0 ||
3794 		    strcmp(name, BTF_EXT_ELF_SEC) == 0)
3795 			return true;
3796 	}
3797 
3798 	return false;
3799 }
3800 
3801 static int cmp_progs(const void *_a, const void *_b)
3802 {
3803 	const struct bpf_program *a = _a;
3804 	const struct bpf_program *b = _b;
3805 
3806 	if (a->sec_idx != b->sec_idx)
3807 		return a->sec_idx < b->sec_idx ? -1 : 1;
3808 
3809 	/* sec_insn_off can't be the same within the section */
3810 	return a->sec_insn_off < b->sec_insn_off ? -1 : 1;
3811 }
3812 
3813 static int bpf_object__elf_collect(struct bpf_object *obj)
3814 {
3815 	struct elf_sec_desc *sec_desc;
3816 	Elf *elf = obj->efile.elf;
3817 	Elf_Data *btf_ext_data = NULL;
3818 	Elf_Data *btf_data = NULL;
3819 	int idx = 0, err = 0;
3820 	const char *name;
3821 	Elf_Data *data;
3822 	Elf_Scn *scn;
3823 	Elf64_Shdr *sh;
3824 
3825 	/* ELF section indices are 0-based, but sec #0 is special "invalid"
3826 	 * section. Since section count retrieved by elf_getshdrnum() does
3827 	 * include sec #0, it is already the necessary size of an array to keep
3828 	 * all the sections.
3829 	 */
3830 	if (elf_getshdrnum(obj->efile.elf, &obj->efile.sec_cnt)) {
3831 		pr_warn("elf: failed to get the number of sections for %s: %s\n",
3832 			obj->path, elf_errmsg(-1));
3833 		return -LIBBPF_ERRNO__FORMAT;
3834 	}
3835 	obj->efile.secs = calloc(obj->efile.sec_cnt, sizeof(*obj->efile.secs));
3836 	if (!obj->efile.secs)
3837 		return -ENOMEM;
3838 
3839 	/* a bunch of ELF parsing functionality depends on processing symbols,
3840 	 * so do the first pass and find the symbol table
3841 	 */
3842 	scn = NULL;
3843 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3844 		sh = elf_sec_hdr(obj, scn);
3845 		if (!sh)
3846 			return -LIBBPF_ERRNO__FORMAT;
3847 
3848 		if (sh->sh_type == SHT_SYMTAB) {
3849 			if (obj->efile.symbols) {
3850 				pr_warn("elf: multiple symbol tables in %s\n", obj->path);
3851 				return -LIBBPF_ERRNO__FORMAT;
3852 			}
3853 
3854 			data = elf_sec_data(obj, scn);
3855 			if (!data)
3856 				return -LIBBPF_ERRNO__FORMAT;
3857 
3858 			idx = elf_ndxscn(scn);
3859 
3860 			obj->efile.symbols = data;
3861 			obj->efile.symbols_shndx = idx;
3862 			obj->efile.strtabidx = sh->sh_link;
3863 		}
3864 	}
3865 
3866 	if (!obj->efile.symbols) {
3867 		pr_warn("elf: couldn't find symbol table in %s, stripped object file?\n",
3868 			obj->path);
3869 		return -ENOENT;
3870 	}
3871 
3872 	scn = NULL;
3873 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3874 		idx = elf_ndxscn(scn);
3875 		sec_desc = &obj->efile.secs[idx];
3876 
3877 		sh = elf_sec_hdr(obj, scn);
3878 		if (!sh)
3879 			return -LIBBPF_ERRNO__FORMAT;
3880 
3881 		name = elf_sec_str(obj, sh->sh_name);
3882 		if (!name)
3883 			return -LIBBPF_ERRNO__FORMAT;
3884 
3885 		if (ignore_elf_section(sh, name))
3886 			continue;
3887 
3888 		data = elf_sec_data(obj, scn);
3889 		if (!data)
3890 			return -LIBBPF_ERRNO__FORMAT;
3891 
3892 		pr_debug("elf: section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
3893 			 idx, name, (unsigned long)data->d_size,
3894 			 (int)sh->sh_link, (unsigned long)sh->sh_flags,
3895 			 (int)sh->sh_type);
3896 
3897 		if (strcmp(name, "license") == 0) {
3898 			err = bpf_object__init_license(obj, data->d_buf, data->d_size);
3899 			if (err)
3900 				return err;
3901 		} else if (strcmp(name, "version") == 0) {
3902 			err = bpf_object__init_kversion(obj, data->d_buf, data->d_size);
3903 			if (err)
3904 				return err;
3905 		} else if (strcmp(name, "maps") == 0) {
3906 			pr_warn("elf: legacy map definitions in 'maps' section are not supported by libbpf v1.0+\n");
3907 			return -ENOTSUP;
3908 		} else if (strcmp(name, MAPS_ELF_SEC) == 0) {
3909 			obj->efile.btf_maps_shndx = idx;
3910 		} else if (strcmp(name, BTF_ELF_SEC) == 0) {
3911 			if (sh->sh_type != SHT_PROGBITS)
3912 				return -LIBBPF_ERRNO__FORMAT;
3913 			btf_data = data;
3914 		} else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
3915 			if (sh->sh_type != SHT_PROGBITS)
3916 				return -LIBBPF_ERRNO__FORMAT;
3917 			btf_ext_data = data;
3918 		} else if (sh->sh_type == SHT_SYMTAB) {
3919 			/* already processed during the first pass above */
3920 		} else if (sh->sh_type == SHT_PROGBITS && data->d_size > 0) {
3921 			if (sh->sh_flags & SHF_EXECINSTR) {
3922 				if (strcmp(name, ".text") == 0)
3923 					obj->efile.text_shndx = idx;
3924 				err = bpf_object__add_programs(obj, data, name, idx);
3925 				if (err)
3926 					return err;
3927 			} else if (strcmp(name, DATA_SEC) == 0 ||
3928 				   str_has_pfx(name, DATA_SEC ".")) {
3929 				sec_desc->sec_type = SEC_DATA;
3930 				sec_desc->shdr = sh;
3931 				sec_desc->data = data;
3932 			} else if (strcmp(name, RODATA_SEC) == 0 ||
3933 				   str_has_pfx(name, RODATA_SEC ".")) {
3934 				sec_desc->sec_type = SEC_RODATA;
3935 				sec_desc->shdr = sh;
3936 				sec_desc->data = data;
3937 			} else if (strcmp(name, STRUCT_OPS_SEC) == 0 ||
3938 				   strcmp(name, STRUCT_OPS_LINK_SEC) == 0 ||
3939 				   strcmp(name, "?" STRUCT_OPS_SEC) == 0 ||
3940 				   strcmp(name, "?" STRUCT_OPS_LINK_SEC) == 0) {
3941 				sec_desc->sec_type = SEC_ST_OPS;
3942 				sec_desc->shdr = sh;
3943 				sec_desc->data = data;
3944 				obj->efile.has_st_ops = true;
3945 			} else if (strcmp(name, ARENA_SEC) == 0) {
3946 				obj->efile.arena_data = data;
3947 				obj->efile.arena_data_shndx = idx;
3948 			} else {
3949 				pr_info("elf: skipping unrecognized data section(%d) %s\n",
3950 					idx, name);
3951 			}
3952 		} else if (sh->sh_type == SHT_REL) {
3953 			int targ_sec_idx = sh->sh_info; /* points to other section */
3954 
3955 			if (sh->sh_entsize != sizeof(Elf64_Rel) ||
3956 			    targ_sec_idx >= obj->efile.sec_cnt)
3957 				return -LIBBPF_ERRNO__FORMAT;
3958 
3959 			/* Only do relo for section with exec instructions */
3960 			if (!section_have_execinstr(obj, targ_sec_idx) &&
3961 			    strcmp(name, ".rel" STRUCT_OPS_SEC) &&
3962 			    strcmp(name, ".rel" STRUCT_OPS_LINK_SEC) &&
3963 			    strcmp(name, ".rel?" STRUCT_OPS_SEC) &&
3964 			    strcmp(name, ".rel?" STRUCT_OPS_LINK_SEC) &&
3965 			    strcmp(name, ".rel" MAPS_ELF_SEC)) {
3966 				pr_info("elf: skipping relo section(%d) %s for section(%d) %s\n",
3967 					idx, name, targ_sec_idx,
3968 					elf_sec_name(obj, elf_sec_by_idx(obj, targ_sec_idx)) ?: "<?>");
3969 				continue;
3970 			}
3971 
3972 			sec_desc->sec_type = SEC_RELO;
3973 			sec_desc->shdr = sh;
3974 			sec_desc->data = data;
3975 		} else if (sh->sh_type == SHT_NOBITS && (strcmp(name, BSS_SEC) == 0 ||
3976 							 str_has_pfx(name, BSS_SEC "."))) {
3977 			sec_desc->sec_type = SEC_BSS;
3978 			sec_desc->shdr = sh;
3979 			sec_desc->data = data;
3980 		} else {
3981 			pr_info("elf: skipping section(%d) %s (size %zu)\n", idx, name,
3982 				(size_t)sh->sh_size);
3983 		}
3984 	}
3985 
3986 	if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) {
3987 		pr_warn("elf: symbol strings section missing or invalid in %s\n", obj->path);
3988 		return -LIBBPF_ERRNO__FORMAT;
3989 	}
3990 
3991 	/* change BPF program insns to native endianness for introspection */
3992 	if (!is_native_endianness(obj))
3993 		bpf_object_bswap_progs(obj);
3994 
3995 	/* sort BPF programs by section name and in-section instruction offset
3996 	 * for faster search
3997 	 */
3998 	if (obj->nr_programs)
3999 		qsort(obj->programs, obj->nr_programs, sizeof(*obj->programs), cmp_progs);
4000 
4001 	return bpf_object__init_btf(obj, btf_data, btf_ext_data);
4002 }
4003 
4004 static bool sym_is_extern(const Elf64_Sym *sym)
4005 {
4006 	int bind = ELF64_ST_BIND(sym->st_info);
4007 	/* externs are symbols w/ type=NOTYPE, bind=GLOBAL|WEAK, section=UND */
4008 	return sym->st_shndx == SHN_UNDEF &&
4009 	       (bind == STB_GLOBAL || bind == STB_WEAK) &&
4010 	       ELF64_ST_TYPE(sym->st_info) == STT_NOTYPE;
4011 }
4012 
4013 static bool sym_is_subprog(const Elf64_Sym *sym, int text_shndx)
4014 {
4015 	int bind = ELF64_ST_BIND(sym->st_info);
4016 	int type = ELF64_ST_TYPE(sym->st_info);
4017 
4018 	/* in .text section */
4019 	if (sym->st_shndx != text_shndx)
4020 		return false;
4021 
4022 	/* local function */
4023 	if (bind == STB_LOCAL && type == STT_SECTION)
4024 		return true;
4025 
4026 	/* global function */
4027 	return (bind == STB_GLOBAL || bind == STB_WEAK) && type == STT_FUNC;
4028 }
4029 
4030 static int find_extern_btf_id(const struct btf *btf, const char *ext_name)
4031 {
4032 	const struct btf_type *t;
4033 	const char *tname;
4034 	int i, n;
4035 
4036 	if (!btf)
4037 		return -ESRCH;
4038 
4039 	n = btf__type_cnt(btf);
4040 	for (i = 1; i < n; i++) {
4041 		t = btf__type_by_id(btf, i);
4042 
4043 		if (!btf_is_var(t) && !btf_is_func(t))
4044 			continue;
4045 
4046 		tname = btf__name_by_offset(btf, t->name_off);
4047 		if (strcmp(tname, ext_name))
4048 			continue;
4049 
4050 		if (btf_is_var(t) &&
4051 		    btf_var(t)->linkage != BTF_VAR_GLOBAL_EXTERN)
4052 			return -EINVAL;
4053 
4054 		if (btf_is_func(t) && btf_func_linkage(t) != BTF_FUNC_EXTERN)
4055 			return -EINVAL;
4056 
4057 		return i;
4058 	}
4059 
4060 	return -ENOENT;
4061 }
4062 
4063 static int find_extern_sec_btf_id(struct btf *btf, int ext_btf_id) {
4064 	const struct btf_var_secinfo *vs;
4065 	const struct btf_type *t;
4066 	int i, j, n;
4067 
4068 	if (!btf)
4069 		return -ESRCH;
4070 
4071 	n = btf__type_cnt(btf);
4072 	for (i = 1; i < n; i++) {
4073 		t = btf__type_by_id(btf, i);
4074 
4075 		if (!btf_is_datasec(t))
4076 			continue;
4077 
4078 		vs = btf_var_secinfos(t);
4079 		for (j = 0; j < btf_vlen(t); j++, vs++) {
4080 			if (vs->type == ext_btf_id)
4081 				return i;
4082 		}
4083 	}
4084 
4085 	return -ENOENT;
4086 }
4087 
4088 static enum kcfg_type find_kcfg_type(const struct btf *btf, int id,
4089 				     bool *is_signed)
4090 {
4091 	const struct btf_type *t;
4092 	const char *name;
4093 
4094 	t = skip_mods_and_typedefs(btf, id, NULL);
4095 	name = btf__name_by_offset(btf, t->name_off);
4096 
4097 	if (is_signed)
4098 		*is_signed = false;
4099 	switch (btf_kind(t)) {
4100 	case BTF_KIND_INT: {
4101 		int enc = btf_int_encoding(t);
4102 
4103 		if (enc & BTF_INT_BOOL)
4104 			return t->size == 1 ? KCFG_BOOL : KCFG_UNKNOWN;
4105 		if (is_signed)
4106 			*is_signed = enc & BTF_INT_SIGNED;
4107 		if (t->size == 1)
4108 			return KCFG_CHAR;
4109 		if (t->size < 1 || t->size > 8 || (t->size & (t->size - 1)))
4110 			return KCFG_UNKNOWN;
4111 		return KCFG_INT;
4112 	}
4113 	case BTF_KIND_ENUM:
4114 		if (t->size != 4)
4115 			return KCFG_UNKNOWN;
4116 		if (strcmp(name, "libbpf_tristate"))
4117 			return KCFG_UNKNOWN;
4118 		return KCFG_TRISTATE;
4119 	case BTF_KIND_ENUM64:
4120 		if (strcmp(name, "libbpf_tristate"))
4121 			return KCFG_UNKNOWN;
4122 		return KCFG_TRISTATE;
4123 	case BTF_KIND_ARRAY:
4124 		if (btf_array(t)->nelems == 0)
4125 			return KCFG_UNKNOWN;
4126 		if (find_kcfg_type(btf, btf_array(t)->type, NULL) != KCFG_CHAR)
4127 			return KCFG_UNKNOWN;
4128 		return KCFG_CHAR_ARR;
4129 	default:
4130 		return KCFG_UNKNOWN;
4131 	}
4132 }
4133 
4134 static int cmp_externs(const void *_a, const void *_b)
4135 {
4136 	const struct extern_desc *a = _a;
4137 	const struct extern_desc *b = _b;
4138 
4139 	if (a->type != b->type)
4140 		return a->type < b->type ? -1 : 1;
4141 
4142 	if (a->type == EXT_KCFG) {
4143 		/* descending order by alignment requirements */
4144 		if (a->kcfg.align != b->kcfg.align)
4145 			return a->kcfg.align > b->kcfg.align ? -1 : 1;
4146 		/* ascending order by size, within same alignment class */
4147 		if (a->kcfg.sz != b->kcfg.sz)
4148 			return a->kcfg.sz < b->kcfg.sz ? -1 : 1;
4149 	}
4150 
4151 	/* resolve ties by name */
4152 	return strcmp(a->name, b->name);
4153 }
4154 
4155 static int find_int_btf_id(const struct btf *btf)
4156 {
4157 	const struct btf_type *t;
4158 	int i, n;
4159 
4160 	n = btf__type_cnt(btf);
4161 	for (i = 1; i < n; i++) {
4162 		t = btf__type_by_id(btf, i);
4163 
4164 		if (btf_is_int(t) && btf_int_bits(t) == 32)
4165 			return i;
4166 	}
4167 
4168 	return 0;
4169 }
4170 
4171 static int add_dummy_ksym_var(struct btf *btf)
4172 {
4173 	int i, int_btf_id, sec_btf_id, dummy_var_btf_id;
4174 	const struct btf_var_secinfo *vs;
4175 	const struct btf_type *sec;
4176 
4177 	if (!btf)
4178 		return 0;
4179 
4180 	sec_btf_id = btf__find_by_name_kind(btf, KSYMS_SEC,
4181 					    BTF_KIND_DATASEC);
4182 	if (sec_btf_id < 0)
4183 		return 0;
4184 
4185 	sec = btf__type_by_id(btf, sec_btf_id);
4186 	vs = btf_var_secinfos(sec);
4187 	for (i = 0; i < btf_vlen(sec); i++, vs++) {
4188 		const struct btf_type *vt;
4189 
4190 		vt = btf__type_by_id(btf, vs->type);
4191 		if (btf_is_func(vt))
4192 			break;
4193 	}
4194 
4195 	/* No func in ksyms sec.  No need to add dummy var. */
4196 	if (i == btf_vlen(sec))
4197 		return 0;
4198 
4199 	int_btf_id = find_int_btf_id(btf);
4200 	dummy_var_btf_id = btf__add_var(btf,
4201 					"dummy_ksym",
4202 					BTF_VAR_GLOBAL_ALLOCATED,
4203 					int_btf_id);
4204 	if (dummy_var_btf_id < 0)
4205 		pr_warn("cannot create a dummy_ksym var\n");
4206 
4207 	return dummy_var_btf_id;
4208 }
4209 
4210 static int bpf_object__collect_externs(struct bpf_object *obj)
4211 {
4212 	struct btf_type *sec, *kcfg_sec = NULL, *ksym_sec = NULL;
4213 	const struct btf_type *t;
4214 	struct extern_desc *ext;
4215 	int i, n, off, dummy_var_btf_id;
4216 	const char *ext_name, *sec_name;
4217 	size_t ext_essent_len;
4218 	Elf_Scn *scn;
4219 	Elf64_Shdr *sh;
4220 
4221 	if (!obj->efile.symbols)
4222 		return 0;
4223 
4224 	scn = elf_sec_by_idx(obj, obj->efile.symbols_shndx);
4225 	sh = elf_sec_hdr(obj, scn);
4226 	if (!sh || sh->sh_entsize != sizeof(Elf64_Sym))
4227 		return -LIBBPF_ERRNO__FORMAT;
4228 
4229 	dummy_var_btf_id = add_dummy_ksym_var(obj->btf);
4230 	if (dummy_var_btf_id < 0)
4231 		return dummy_var_btf_id;
4232 
4233 	n = sh->sh_size / sh->sh_entsize;
4234 	pr_debug("looking for externs among %d symbols...\n", n);
4235 
4236 	for (i = 0; i < n; i++) {
4237 		Elf64_Sym *sym = elf_sym_by_idx(obj, i);
4238 
4239 		if (!sym)
4240 			return -LIBBPF_ERRNO__FORMAT;
4241 		if (!sym_is_extern(sym))
4242 			continue;
4243 		ext_name = elf_sym_str(obj, sym->st_name);
4244 		if (!ext_name || !ext_name[0])
4245 			continue;
4246 
4247 		ext = obj->externs;
4248 		ext = libbpf_reallocarray(ext, obj->nr_extern + 1, sizeof(*ext));
4249 		if (!ext)
4250 			return -ENOMEM;
4251 		obj->externs = ext;
4252 		ext = &ext[obj->nr_extern];
4253 		memset(ext, 0, sizeof(*ext));
4254 		obj->nr_extern++;
4255 
4256 		ext->btf_id = find_extern_btf_id(obj->btf, ext_name);
4257 		if (ext->btf_id <= 0) {
4258 			pr_warn("failed to find BTF for extern '%s': %d\n",
4259 				ext_name, ext->btf_id);
4260 			return ext->btf_id;
4261 		}
4262 		t = btf__type_by_id(obj->btf, ext->btf_id);
4263 		ext->name = strdup(btf__name_by_offset(obj->btf, t->name_off));
4264 		if (!ext->name)
4265 			return -ENOMEM;
4266 		ext->sym_idx = i;
4267 		ext->is_weak = ELF64_ST_BIND(sym->st_info) == STB_WEAK;
4268 
4269 		ext_essent_len = bpf_core_essential_name_len(ext->name);
4270 		ext->essent_name = NULL;
4271 		if (ext_essent_len != strlen(ext->name)) {
4272 			ext->essent_name = strndup(ext->name, ext_essent_len);
4273 			if (!ext->essent_name)
4274 				return -ENOMEM;
4275 		}
4276 
4277 		ext->sec_btf_id = find_extern_sec_btf_id(obj->btf, ext->btf_id);
4278 		if (ext->sec_btf_id <= 0) {
4279 			pr_warn("failed to find BTF for extern '%s' [%d] section: %d\n",
4280 				ext_name, ext->btf_id, ext->sec_btf_id);
4281 			return ext->sec_btf_id;
4282 		}
4283 		sec = (void *)btf__type_by_id(obj->btf, ext->sec_btf_id);
4284 		sec_name = btf__name_by_offset(obj->btf, sec->name_off);
4285 
4286 		if (strcmp(sec_name, KCONFIG_SEC) == 0) {
4287 			if (btf_is_func(t)) {
4288 				pr_warn("extern function %s is unsupported under %s section\n",
4289 					ext->name, KCONFIG_SEC);
4290 				return -ENOTSUP;
4291 			}
4292 			kcfg_sec = sec;
4293 			ext->type = EXT_KCFG;
4294 			ext->kcfg.sz = btf__resolve_size(obj->btf, t->type);
4295 			if (ext->kcfg.sz <= 0) {
4296 				pr_warn("failed to resolve size of extern (kcfg) '%s': %d\n",
4297 					ext_name, ext->kcfg.sz);
4298 				return ext->kcfg.sz;
4299 			}
4300 			ext->kcfg.align = btf__align_of(obj->btf, t->type);
4301 			if (ext->kcfg.align <= 0) {
4302 				pr_warn("failed to determine alignment of extern (kcfg) '%s': %d\n",
4303 					ext_name, ext->kcfg.align);
4304 				return -EINVAL;
4305 			}
4306 			ext->kcfg.type = find_kcfg_type(obj->btf, t->type,
4307 							&ext->kcfg.is_signed);
4308 			if (ext->kcfg.type == KCFG_UNKNOWN) {
4309 				pr_warn("extern (kcfg) '%s': type is unsupported\n", ext_name);
4310 				return -ENOTSUP;
4311 			}
4312 		} else if (strcmp(sec_name, KSYMS_SEC) == 0) {
4313 			ksym_sec = sec;
4314 			ext->type = EXT_KSYM;
4315 			skip_mods_and_typedefs(obj->btf, t->type,
4316 					       &ext->ksym.type_id);
4317 		} else {
4318 			pr_warn("unrecognized extern section '%s'\n", sec_name);
4319 			return -ENOTSUP;
4320 		}
4321 	}
4322 	pr_debug("collected %d externs total\n", obj->nr_extern);
4323 
4324 	if (!obj->nr_extern)
4325 		return 0;
4326 
4327 	/* sort externs by type, for kcfg ones also by (align, size, name) */
4328 	qsort(obj->externs, obj->nr_extern, sizeof(*ext), cmp_externs);
4329 
4330 	/* for .ksyms section, we need to turn all externs into allocated
4331 	 * variables in BTF to pass kernel verification; we do this by
4332 	 * pretending that each extern is a 8-byte variable
4333 	 */
4334 	if (ksym_sec) {
4335 		/* find existing 4-byte integer type in BTF to use for fake
4336 		 * extern variables in DATASEC
4337 		 */
4338 		int int_btf_id = find_int_btf_id(obj->btf);
4339 		/* For extern function, a dummy_var added earlier
4340 		 * will be used to replace the vs->type and
4341 		 * its name string will be used to refill
4342 		 * the missing param's name.
4343 		 */
4344 		const struct btf_type *dummy_var;
4345 
4346 		dummy_var = btf__type_by_id(obj->btf, dummy_var_btf_id);
4347 		for (i = 0; i < obj->nr_extern; i++) {
4348 			ext = &obj->externs[i];
4349 			if (ext->type != EXT_KSYM)
4350 				continue;
4351 			pr_debug("extern (ksym) #%d: symbol %d, name %s\n",
4352 				 i, ext->sym_idx, ext->name);
4353 		}
4354 
4355 		sec = ksym_sec;
4356 		n = btf_vlen(sec);
4357 		for (i = 0, off = 0; i < n; i++, off += sizeof(int)) {
4358 			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
4359 			struct btf_type *vt;
4360 
4361 			vt = (void *)btf__type_by_id(obj->btf, vs->type);
4362 			ext_name = btf__name_by_offset(obj->btf, vt->name_off);
4363 			ext = find_extern_by_name(obj, ext_name);
4364 			if (!ext) {
4365 				pr_warn("failed to find extern definition for BTF %s '%s'\n",
4366 					btf_kind_str(vt), ext_name);
4367 				return -ESRCH;
4368 			}
4369 			if (btf_is_func(vt)) {
4370 				const struct btf_type *func_proto;
4371 				struct btf_param *param;
4372 				int j;
4373 
4374 				func_proto = btf__type_by_id(obj->btf,
4375 							     vt->type);
4376 				param = btf_params(func_proto);
4377 				/* Reuse the dummy_var string if the
4378 				 * func proto does not have param name.
4379 				 */
4380 				for (j = 0; j < btf_vlen(func_proto); j++)
4381 					if (param[j].type && !param[j].name_off)
4382 						param[j].name_off =
4383 							dummy_var->name_off;
4384 				vs->type = dummy_var_btf_id;
4385 				vt->info &= ~0xffff;
4386 				vt->info |= BTF_FUNC_GLOBAL;
4387 			} else {
4388 				btf_var(vt)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
4389 				vt->type = int_btf_id;
4390 			}
4391 			vs->offset = off;
4392 			vs->size = sizeof(int);
4393 		}
4394 		sec->size = off;
4395 	}
4396 
4397 	if (kcfg_sec) {
4398 		sec = kcfg_sec;
4399 		/* for kcfg externs calculate their offsets within a .kconfig map */
4400 		off = 0;
4401 		for (i = 0; i < obj->nr_extern; i++) {
4402 			ext = &obj->externs[i];
4403 			if (ext->type != EXT_KCFG)
4404 				continue;
4405 
4406 			ext->kcfg.data_off = roundup(off, ext->kcfg.align);
4407 			off = ext->kcfg.data_off + ext->kcfg.sz;
4408 			pr_debug("extern (kcfg) #%d: symbol %d, off %u, name %s\n",
4409 				 i, ext->sym_idx, ext->kcfg.data_off, ext->name);
4410 		}
4411 		sec->size = off;
4412 		n = btf_vlen(sec);
4413 		for (i = 0; i < n; i++) {
4414 			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
4415 
4416 			t = btf__type_by_id(obj->btf, vs->type);
4417 			ext_name = btf__name_by_offset(obj->btf, t->name_off);
4418 			ext = find_extern_by_name(obj, ext_name);
4419 			if (!ext) {
4420 				pr_warn("failed to find extern definition for BTF var '%s'\n",
4421 					ext_name);
4422 				return -ESRCH;
4423 			}
4424 			btf_var(t)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
4425 			vs->offset = ext->kcfg.data_off;
4426 		}
4427 	}
4428 	return 0;
4429 }
4430 
4431 static bool prog_is_subprog(const struct bpf_object *obj, const struct bpf_program *prog)
4432 {
4433 	return prog->sec_idx == obj->efile.text_shndx;
4434 }
4435 
4436 struct bpf_program *
4437 bpf_object__find_program_by_name(const struct bpf_object *obj,
4438 				 const char *name)
4439 {
4440 	struct bpf_program *prog;
4441 
4442 	bpf_object__for_each_program(prog, obj) {
4443 		if (prog_is_subprog(obj, prog))
4444 			continue;
4445 		if (!strcmp(prog->name, name))
4446 			return prog;
4447 	}
4448 	return errno = ENOENT, NULL;
4449 }
4450 
4451 static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
4452 				      int shndx)
4453 {
4454 	switch (obj->efile.secs[shndx].sec_type) {
4455 	case SEC_BSS:
4456 	case SEC_DATA:
4457 	case SEC_RODATA:
4458 		return true;
4459 	default:
4460 		return false;
4461 	}
4462 }
4463 
4464 static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
4465 				      int shndx)
4466 {
4467 	return shndx == obj->efile.btf_maps_shndx;
4468 }
4469 
4470 static enum libbpf_map_type
4471 bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
4472 {
4473 	if (shndx == obj->efile.symbols_shndx)
4474 		return LIBBPF_MAP_KCONFIG;
4475 
4476 	switch (obj->efile.secs[shndx].sec_type) {
4477 	case SEC_BSS:
4478 		return LIBBPF_MAP_BSS;
4479 	case SEC_DATA:
4480 		return LIBBPF_MAP_DATA;
4481 	case SEC_RODATA:
4482 		return LIBBPF_MAP_RODATA;
4483 	default:
4484 		return LIBBPF_MAP_UNSPEC;
4485 	}
4486 }
4487 
4488 static int bpf_program__record_reloc(struct bpf_program *prog,
4489 				     struct reloc_desc *reloc_desc,
4490 				     __u32 insn_idx, const char *sym_name,
4491 				     const Elf64_Sym *sym, const Elf64_Rel *rel)
4492 {
4493 	struct bpf_insn *insn = &prog->insns[insn_idx];
4494 	size_t map_idx, nr_maps = prog->obj->nr_maps;
4495 	struct bpf_object *obj = prog->obj;
4496 	__u32 shdr_idx = sym->st_shndx;
4497 	enum libbpf_map_type type;
4498 	const char *sym_sec_name;
4499 	struct bpf_map *map;
4500 
4501 	if (!is_call_insn(insn) && !is_ldimm64_insn(insn)) {
4502 		pr_warn("prog '%s': invalid relo against '%s' for insns[%d].code 0x%x\n",
4503 			prog->name, sym_name, insn_idx, insn->code);
4504 		return -LIBBPF_ERRNO__RELOC;
4505 	}
4506 
4507 	if (sym_is_extern(sym)) {
4508 		int sym_idx = ELF64_R_SYM(rel->r_info);
4509 		int i, n = obj->nr_extern;
4510 		struct extern_desc *ext;
4511 
4512 		for (i = 0; i < n; i++) {
4513 			ext = &obj->externs[i];
4514 			if (ext->sym_idx == sym_idx)
4515 				break;
4516 		}
4517 		if (i >= n) {
4518 			pr_warn("prog '%s': extern relo failed to find extern for '%s' (%d)\n",
4519 				prog->name, sym_name, sym_idx);
4520 			return -LIBBPF_ERRNO__RELOC;
4521 		}
4522 		pr_debug("prog '%s': found extern #%d '%s' (sym %d) for insn #%u\n",
4523 			 prog->name, i, ext->name, ext->sym_idx, insn_idx);
4524 		if (insn->code == (BPF_JMP | BPF_CALL))
4525 			reloc_desc->type = RELO_EXTERN_CALL;
4526 		else
4527 			reloc_desc->type = RELO_EXTERN_LD64;
4528 		reloc_desc->insn_idx = insn_idx;
4529 		reloc_desc->ext_idx = i;
4530 		return 0;
4531 	}
4532 
4533 	/* sub-program call relocation */
4534 	if (is_call_insn(insn)) {
4535 		if (insn->src_reg != BPF_PSEUDO_CALL) {
4536 			pr_warn("prog '%s': incorrect bpf_call opcode\n", prog->name);
4537 			return -LIBBPF_ERRNO__RELOC;
4538 		}
4539 		/* text_shndx can be 0, if no default "main" program exists */
4540 		if (!shdr_idx || shdr_idx != obj->efile.text_shndx) {
4541 			sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4542 			pr_warn("prog '%s': bad call relo against '%s' in section '%s'\n",
4543 				prog->name, sym_name, sym_sec_name);
4544 			return -LIBBPF_ERRNO__RELOC;
4545 		}
4546 		if (sym->st_value % BPF_INSN_SZ) {
4547 			pr_warn("prog '%s': bad call relo against '%s' at offset %zu\n",
4548 				prog->name, sym_name, (size_t)sym->st_value);
4549 			return -LIBBPF_ERRNO__RELOC;
4550 		}
4551 		reloc_desc->type = RELO_CALL;
4552 		reloc_desc->insn_idx = insn_idx;
4553 		reloc_desc->sym_off = sym->st_value;
4554 		return 0;
4555 	}
4556 
4557 	if (!shdr_idx || shdr_idx >= SHN_LORESERVE) {
4558 		pr_warn("prog '%s': invalid relo against '%s' in special section 0x%x; forgot to initialize global var?..\n",
4559 			prog->name, sym_name, shdr_idx);
4560 		return -LIBBPF_ERRNO__RELOC;
4561 	}
4562 
4563 	/* loading subprog addresses */
4564 	if (sym_is_subprog(sym, obj->efile.text_shndx)) {
4565 		/* global_func: sym->st_value = offset in the section, insn->imm = 0.
4566 		 * local_func: sym->st_value = 0, insn->imm = offset in the section.
4567 		 */
4568 		if ((sym->st_value % BPF_INSN_SZ) || (insn->imm % BPF_INSN_SZ)) {
4569 			pr_warn("prog '%s': bad subprog addr relo against '%s' at offset %zu+%d\n",
4570 				prog->name, sym_name, (size_t)sym->st_value, insn->imm);
4571 			return -LIBBPF_ERRNO__RELOC;
4572 		}
4573 
4574 		reloc_desc->type = RELO_SUBPROG_ADDR;
4575 		reloc_desc->insn_idx = insn_idx;
4576 		reloc_desc->sym_off = sym->st_value;
4577 		return 0;
4578 	}
4579 
4580 	type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
4581 	sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4582 
4583 	/* arena data relocation */
4584 	if (shdr_idx == obj->efile.arena_data_shndx) {
4585 		reloc_desc->type = RELO_DATA;
4586 		reloc_desc->insn_idx = insn_idx;
4587 		reloc_desc->map_idx = obj->arena_map_idx;
4588 		reloc_desc->sym_off = sym->st_value;
4589 
4590 		map = &obj->maps[obj->arena_map_idx];
4591 		pr_debug("prog '%s': found arena map %d (%s, sec %d, off %zu) for insn %u\n",
4592 			 prog->name, obj->arena_map_idx, map->name, map->sec_idx,
4593 			 map->sec_offset, insn_idx);
4594 		return 0;
4595 	}
4596 
4597 	/* generic map reference relocation */
4598 	if (type == LIBBPF_MAP_UNSPEC) {
4599 		if (!bpf_object__shndx_is_maps(obj, shdr_idx)) {
4600 			pr_warn("prog '%s': bad map relo against '%s' in section '%s'\n",
4601 				prog->name, sym_name, sym_sec_name);
4602 			return -LIBBPF_ERRNO__RELOC;
4603 		}
4604 		for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4605 			map = &obj->maps[map_idx];
4606 			if (map->libbpf_type != type ||
4607 			    map->sec_idx != sym->st_shndx ||
4608 			    map->sec_offset != sym->st_value)
4609 				continue;
4610 			pr_debug("prog '%s': found map %zd (%s, sec %d, off %zu) for insn #%u\n",
4611 				 prog->name, map_idx, map->name, map->sec_idx,
4612 				 map->sec_offset, insn_idx);
4613 			break;
4614 		}
4615 		if (map_idx >= nr_maps) {
4616 			pr_warn("prog '%s': map relo failed to find map for section '%s', off %zu\n",
4617 				prog->name, sym_sec_name, (size_t)sym->st_value);
4618 			return -LIBBPF_ERRNO__RELOC;
4619 		}
4620 		reloc_desc->type = RELO_LD64;
4621 		reloc_desc->insn_idx = insn_idx;
4622 		reloc_desc->map_idx = map_idx;
4623 		reloc_desc->sym_off = 0; /* sym->st_value determines map_idx */
4624 		return 0;
4625 	}
4626 
4627 	/* global data map relocation */
4628 	if (!bpf_object__shndx_is_data(obj, shdr_idx)) {
4629 		pr_warn("prog '%s': bad data relo against section '%s'\n",
4630 			prog->name, sym_sec_name);
4631 		return -LIBBPF_ERRNO__RELOC;
4632 	}
4633 	for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4634 		map = &obj->maps[map_idx];
4635 		if (map->libbpf_type != type || map->sec_idx != sym->st_shndx)
4636 			continue;
4637 		pr_debug("prog '%s': found data map %zd (%s, sec %d, off %zu) for insn %u\n",
4638 			 prog->name, map_idx, map->name, map->sec_idx,
4639 			 map->sec_offset, insn_idx);
4640 		break;
4641 	}
4642 	if (map_idx >= nr_maps) {
4643 		pr_warn("prog '%s': data relo failed to find map for section '%s'\n",
4644 			prog->name, sym_sec_name);
4645 		return -LIBBPF_ERRNO__RELOC;
4646 	}
4647 
4648 	reloc_desc->type = RELO_DATA;
4649 	reloc_desc->insn_idx = insn_idx;
4650 	reloc_desc->map_idx = map_idx;
4651 	reloc_desc->sym_off = sym->st_value;
4652 	return 0;
4653 }
4654 
4655 static bool prog_contains_insn(const struct bpf_program *prog, size_t insn_idx)
4656 {
4657 	return insn_idx >= prog->sec_insn_off &&
4658 	       insn_idx < prog->sec_insn_off + prog->sec_insn_cnt;
4659 }
4660 
4661 static struct bpf_program *find_prog_by_sec_insn(const struct bpf_object *obj,
4662 						 size_t sec_idx, size_t insn_idx)
4663 {
4664 	int l = 0, r = obj->nr_programs - 1, m;
4665 	struct bpf_program *prog;
4666 
4667 	if (!obj->nr_programs)
4668 		return NULL;
4669 
4670 	while (l < r) {
4671 		m = l + (r - l + 1) / 2;
4672 		prog = &obj->programs[m];
4673 
4674 		if (prog->sec_idx < sec_idx ||
4675 		    (prog->sec_idx == sec_idx && prog->sec_insn_off <= insn_idx))
4676 			l = m;
4677 		else
4678 			r = m - 1;
4679 	}
4680 	/* matching program could be at index l, but it still might be the
4681 	 * wrong one, so we need to double check conditions for the last time
4682 	 */
4683 	prog = &obj->programs[l];
4684 	if (prog->sec_idx == sec_idx && prog_contains_insn(prog, insn_idx))
4685 		return prog;
4686 	return NULL;
4687 }
4688 
4689 static int
4690 bpf_object__collect_prog_relos(struct bpf_object *obj, Elf64_Shdr *shdr, Elf_Data *data)
4691 {
4692 	const char *relo_sec_name, *sec_name;
4693 	size_t sec_idx = shdr->sh_info, sym_idx;
4694 	struct bpf_program *prog;
4695 	struct reloc_desc *relos;
4696 	int err, i, nrels;
4697 	const char *sym_name;
4698 	__u32 insn_idx;
4699 	Elf_Scn *scn;
4700 	Elf_Data *scn_data;
4701 	Elf64_Sym *sym;
4702 	Elf64_Rel *rel;
4703 
4704 	if (sec_idx >= obj->efile.sec_cnt)
4705 		return -EINVAL;
4706 
4707 	scn = elf_sec_by_idx(obj, sec_idx);
4708 	scn_data = elf_sec_data(obj, scn);
4709 	if (!scn_data)
4710 		return -LIBBPF_ERRNO__FORMAT;
4711 
4712 	relo_sec_name = elf_sec_str(obj, shdr->sh_name);
4713 	sec_name = elf_sec_name(obj, scn);
4714 	if (!relo_sec_name || !sec_name)
4715 		return -EINVAL;
4716 
4717 	pr_debug("sec '%s': collecting relocation for section(%zu) '%s'\n",
4718 		 relo_sec_name, sec_idx, sec_name);
4719 	nrels = shdr->sh_size / shdr->sh_entsize;
4720 
4721 	for (i = 0; i < nrels; i++) {
4722 		rel = elf_rel_by_idx(data, i);
4723 		if (!rel) {
4724 			pr_warn("sec '%s': failed to get relo #%d\n", relo_sec_name, i);
4725 			return -LIBBPF_ERRNO__FORMAT;
4726 		}
4727 
4728 		sym_idx = ELF64_R_SYM(rel->r_info);
4729 		sym = elf_sym_by_idx(obj, sym_idx);
4730 		if (!sym) {
4731 			pr_warn("sec '%s': symbol #%zu not found for relo #%d\n",
4732 				relo_sec_name, sym_idx, i);
4733 			return -LIBBPF_ERRNO__FORMAT;
4734 		}
4735 
4736 		if (sym->st_shndx >= obj->efile.sec_cnt) {
4737 			pr_warn("sec '%s': corrupted symbol #%zu pointing to invalid section #%zu for relo #%d\n",
4738 				relo_sec_name, sym_idx, (size_t)sym->st_shndx, i);
4739 			return -LIBBPF_ERRNO__FORMAT;
4740 		}
4741 
4742 		if (rel->r_offset % BPF_INSN_SZ || rel->r_offset >= scn_data->d_size) {
4743 			pr_warn("sec '%s': invalid offset 0x%zx for relo #%d\n",
4744 				relo_sec_name, (size_t)rel->r_offset, i);
4745 			return -LIBBPF_ERRNO__FORMAT;
4746 		}
4747 
4748 		insn_idx = rel->r_offset / BPF_INSN_SZ;
4749 		/* relocations against static functions are recorded as
4750 		 * relocations against the section that contains a function;
4751 		 * in such case, symbol will be STT_SECTION and sym.st_name
4752 		 * will point to empty string (0), so fetch section name
4753 		 * instead
4754 		 */
4755 		if (ELF64_ST_TYPE(sym->st_info) == STT_SECTION && sym->st_name == 0)
4756 			sym_name = elf_sec_name(obj, elf_sec_by_idx(obj, sym->st_shndx));
4757 		else
4758 			sym_name = elf_sym_str(obj, sym->st_name);
4759 		sym_name = sym_name ?: "<?";
4760 
4761 		pr_debug("sec '%s': relo #%d: insn #%u against '%s'\n",
4762 			 relo_sec_name, i, insn_idx, sym_name);
4763 
4764 		prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
4765 		if (!prog) {
4766 			pr_debug("sec '%s': relo #%d: couldn't find program in section '%s' for insn #%u, probably overridden weak function, skipping...\n",
4767 				relo_sec_name, i, sec_name, insn_idx);
4768 			continue;
4769 		}
4770 
4771 		relos = libbpf_reallocarray(prog->reloc_desc,
4772 					    prog->nr_reloc + 1, sizeof(*relos));
4773 		if (!relos)
4774 			return -ENOMEM;
4775 		prog->reloc_desc = relos;
4776 
4777 		/* adjust insn_idx to local BPF program frame of reference */
4778 		insn_idx -= prog->sec_insn_off;
4779 		err = bpf_program__record_reloc(prog, &relos[prog->nr_reloc],
4780 						insn_idx, sym_name, sym, rel);
4781 		if (err)
4782 			return err;
4783 
4784 		prog->nr_reloc++;
4785 	}
4786 	return 0;
4787 }
4788 
4789 static int map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map)
4790 {
4791 	int id;
4792 
4793 	if (!obj->btf)
4794 		return -ENOENT;
4795 
4796 	/* if it's BTF-defined map, we don't need to search for type IDs.
4797 	 * For struct_ops map, it does not need btf_key_type_id and
4798 	 * btf_value_type_id.
4799 	 */
4800 	if (map->sec_idx == obj->efile.btf_maps_shndx || bpf_map__is_struct_ops(map))
4801 		return 0;
4802 
4803 	/*
4804 	 * LLVM annotates global data differently in BTF, that is,
4805 	 * only as '.data', '.bss' or '.rodata'.
4806 	 */
4807 	if (!bpf_map__is_internal(map))
4808 		return -ENOENT;
4809 
4810 	id = btf__find_by_name(obj->btf, map->real_name);
4811 	if (id < 0)
4812 		return id;
4813 
4814 	map->btf_key_type_id = 0;
4815 	map->btf_value_type_id = id;
4816 	return 0;
4817 }
4818 
4819 static int bpf_get_map_info_from_fdinfo(int fd, struct bpf_map_info *info)
4820 {
4821 	char file[PATH_MAX], buff[4096];
4822 	FILE *fp;
4823 	__u32 val;
4824 	int err;
4825 
4826 	snprintf(file, sizeof(file), "/proc/%d/fdinfo/%d", getpid(), fd);
4827 	memset(info, 0, sizeof(*info));
4828 
4829 	fp = fopen(file, "re");
4830 	if (!fp) {
4831 		err = -errno;
4832 		pr_warn("failed to open %s: %s. No procfs support?\n", file,
4833 			errstr(err));
4834 		return err;
4835 	}
4836 
4837 	while (fgets(buff, sizeof(buff), fp)) {
4838 		if (sscanf(buff, "map_type:\t%u", &val) == 1)
4839 			info->type = val;
4840 		else if (sscanf(buff, "key_size:\t%u", &val) == 1)
4841 			info->key_size = val;
4842 		else if (sscanf(buff, "value_size:\t%u", &val) == 1)
4843 			info->value_size = val;
4844 		else if (sscanf(buff, "max_entries:\t%u", &val) == 1)
4845 			info->max_entries = val;
4846 		else if (sscanf(buff, "map_flags:\t%i", &val) == 1)
4847 			info->map_flags = val;
4848 	}
4849 
4850 	fclose(fp);
4851 
4852 	return 0;
4853 }
4854 
4855 static bool map_is_created(const struct bpf_map *map)
4856 {
4857 	return map->obj->state >= OBJ_PREPARED || map->reused;
4858 }
4859 
4860 bool bpf_map__autocreate(const struct bpf_map *map)
4861 {
4862 	return map->autocreate;
4863 }
4864 
4865 int bpf_map__set_autocreate(struct bpf_map *map, bool autocreate)
4866 {
4867 	if (map_is_created(map))
4868 		return libbpf_err(-EBUSY);
4869 
4870 	map->autocreate = autocreate;
4871 	return 0;
4872 }
4873 
4874 int bpf_map__set_autoattach(struct bpf_map *map, bool autoattach)
4875 {
4876 	if (!bpf_map__is_struct_ops(map))
4877 		return libbpf_err(-EINVAL);
4878 
4879 	map->autoattach = autoattach;
4880 	return 0;
4881 }
4882 
4883 bool bpf_map__autoattach(const struct bpf_map *map)
4884 {
4885 	return map->autoattach;
4886 }
4887 
4888 int bpf_map__reuse_fd(struct bpf_map *map, int fd)
4889 {
4890 	struct bpf_map_info info;
4891 	__u32 len = sizeof(info), name_len;
4892 	int new_fd, err;
4893 	char *new_name;
4894 
4895 	memset(&info, 0, len);
4896 	err = bpf_map_get_info_by_fd(fd, &info, &len);
4897 	if (err && errno == EINVAL)
4898 		err = bpf_get_map_info_from_fdinfo(fd, &info);
4899 	if (err)
4900 		return libbpf_err(err);
4901 
4902 	name_len = strlen(info.name);
4903 	if (name_len == BPF_OBJ_NAME_LEN - 1 && strncmp(map->name, info.name, name_len) == 0)
4904 		new_name = strdup(map->name);
4905 	else
4906 		new_name = strdup(info.name);
4907 
4908 	if (!new_name)
4909 		return libbpf_err(-errno);
4910 
4911 	/*
4912 	 * Like dup(), but make sure new FD is >= 3 and has O_CLOEXEC set.
4913 	 * This is similar to what we do in ensure_good_fd(), but without
4914 	 * closing original FD.
4915 	 */
4916 	new_fd = fcntl(fd, F_DUPFD_CLOEXEC, 3);
4917 	if (new_fd < 0) {
4918 		err = -errno;
4919 		goto err_free_new_name;
4920 	}
4921 
4922 	err = reuse_fd(map->fd, new_fd);
4923 	if (err)
4924 		goto err_free_new_name;
4925 
4926 	free(map->name);
4927 
4928 	map->name = new_name;
4929 	map->def.type = info.type;
4930 	map->def.key_size = info.key_size;
4931 	map->def.value_size = info.value_size;
4932 	map->def.max_entries = info.max_entries;
4933 	map->def.map_flags = info.map_flags;
4934 	map->btf_key_type_id = info.btf_key_type_id;
4935 	map->btf_value_type_id = info.btf_value_type_id;
4936 	map->reused = true;
4937 	map->map_extra = info.map_extra;
4938 
4939 	return 0;
4940 
4941 err_free_new_name:
4942 	free(new_name);
4943 	return libbpf_err(err);
4944 }
4945 
4946 __u32 bpf_map__max_entries(const struct bpf_map *map)
4947 {
4948 	return map->def.max_entries;
4949 }
4950 
4951 struct bpf_map *bpf_map__inner_map(struct bpf_map *map)
4952 {
4953 	if (!bpf_map_type__is_map_in_map(map->def.type))
4954 		return errno = EINVAL, NULL;
4955 
4956 	return map->inner_map;
4957 }
4958 
4959 int bpf_map__set_max_entries(struct bpf_map *map, __u32 max_entries)
4960 {
4961 	if (map_is_created(map))
4962 		return libbpf_err(-EBUSY);
4963 
4964 	map->def.max_entries = max_entries;
4965 
4966 	/* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
4967 	if (map_is_ringbuf(map))
4968 		map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
4969 
4970 	return 0;
4971 }
4972 
4973 static int bpf_object_prepare_token(struct bpf_object *obj)
4974 {
4975 	const char *bpffs_path;
4976 	int bpffs_fd = -1, token_fd, err;
4977 	bool mandatory;
4978 	enum libbpf_print_level level;
4979 
4980 	/* token is explicitly prevented */
4981 	if (obj->token_path && obj->token_path[0] == '\0') {
4982 		pr_debug("object '%s': token is prevented, skipping...\n", obj->name);
4983 		return 0;
4984 	}
4985 
4986 	mandatory = obj->token_path != NULL;
4987 	level = mandatory ? LIBBPF_WARN : LIBBPF_DEBUG;
4988 
4989 	bpffs_path = obj->token_path ?: BPF_FS_DEFAULT_PATH;
4990 	bpffs_fd = open(bpffs_path, O_DIRECTORY, O_RDWR);
4991 	if (bpffs_fd < 0) {
4992 		err = -errno;
4993 		__pr(level, "object '%s': failed (%s) to open BPF FS mount at '%s'%s\n",
4994 		     obj->name, errstr(err), bpffs_path,
4995 		     mandatory ? "" : ", skipping optional step...");
4996 		return mandatory ? err : 0;
4997 	}
4998 
4999 	token_fd = bpf_token_create(bpffs_fd, 0);
5000 	close(bpffs_fd);
5001 	if (token_fd < 0) {
5002 		if (!mandatory && token_fd == -ENOENT) {
5003 			pr_debug("object '%s': BPF FS at '%s' doesn't have BPF token delegation set up, skipping...\n",
5004 				 obj->name, bpffs_path);
5005 			return 0;
5006 		}
5007 		__pr(level, "object '%s': failed (%d) to create BPF token from '%s'%s\n",
5008 		     obj->name, token_fd, bpffs_path,
5009 		     mandatory ? "" : ", skipping optional step...");
5010 		return mandatory ? token_fd : 0;
5011 	}
5012 
5013 	obj->feat_cache = calloc(1, sizeof(*obj->feat_cache));
5014 	if (!obj->feat_cache) {
5015 		close(token_fd);
5016 		return -ENOMEM;
5017 	}
5018 
5019 	obj->token_fd = token_fd;
5020 	obj->feat_cache->token_fd = token_fd;
5021 
5022 	return 0;
5023 }
5024 
5025 static int
5026 bpf_object__probe_loading(struct bpf_object *obj)
5027 {
5028 	struct bpf_insn insns[] = {
5029 		BPF_MOV64_IMM(BPF_REG_0, 0),
5030 		BPF_EXIT_INSN(),
5031 	};
5032 	int ret, insn_cnt = ARRAY_SIZE(insns);
5033 	LIBBPF_OPTS(bpf_prog_load_opts, opts,
5034 		.token_fd = obj->token_fd,
5035 		.prog_flags = obj->token_fd ? BPF_F_TOKEN_FD : 0,
5036 	);
5037 
5038 	if (obj->gen_loader)
5039 		return 0;
5040 
5041 	ret = bump_rlimit_memlock();
5042 	if (ret)
5043 		pr_warn("Failed to bump RLIMIT_MEMLOCK (err = %s), you might need to do it explicitly!\n",
5044 			errstr(ret));
5045 
5046 	/* make sure basic loading works */
5047 	ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, &opts);
5048 	if (ret < 0)
5049 		ret = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, &opts);
5050 	if (ret < 0) {
5051 		ret = errno;
5052 		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",
5053 			__func__, errstr(ret));
5054 		return -ret;
5055 	}
5056 	close(ret);
5057 
5058 	return 0;
5059 }
5060 
5061 bool kernel_supports(const struct bpf_object *obj, enum kern_feature_id feat_id)
5062 {
5063 	if (obj->gen_loader)
5064 		/* To generate loader program assume the latest kernel
5065 		 * to avoid doing extra prog_load, map_create syscalls.
5066 		 */
5067 		return true;
5068 
5069 	if (obj->token_fd)
5070 		return feat_supported(obj->feat_cache, feat_id);
5071 
5072 	return feat_supported(NULL, feat_id);
5073 }
5074 
5075 static bool map_is_reuse_compat(const struct bpf_map *map, int map_fd)
5076 {
5077 	struct bpf_map_info map_info;
5078 	__u32 map_info_len = sizeof(map_info);
5079 	int err;
5080 
5081 	memset(&map_info, 0, map_info_len);
5082 	err = bpf_map_get_info_by_fd(map_fd, &map_info, &map_info_len);
5083 	if (err && errno == EINVAL)
5084 		err = bpf_get_map_info_from_fdinfo(map_fd, &map_info);
5085 	if (err) {
5086 		pr_warn("failed to get map info for map FD %d: %s\n", map_fd,
5087 			errstr(err));
5088 		return false;
5089 	}
5090 
5091 	return (map_info.type == map->def.type &&
5092 		map_info.key_size == map->def.key_size &&
5093 		map_info.value_size == map->def.value_size &&
5094 		map_info.max_entries == map->def.max_entries &&
5095 		map_info.map_flags == map->def.map_flags &&
5096 		map_info.map_extra == map->map_extra);
5097 }
5098 
5099 static int
5100 bpf_object__reuse_map(struct bpf_map *map)
5101 {
5102 	int err, pin_fd;
5103 
5104 	pin_fd = bpf_obj_get(map->pin_path);
5105 	if (pin_fd < 0) {
5106 		err = -errno;
5107 		if (err == -ENOENT) {
5108 			pr_debug("found no pinned map to reuse at '%s'\n",
5109 				 map->pin_path);
5110 			return 0;
5111 		}
5112 
5113 		pr_warn("couldn't retrieve pinned map '%s': %s\n",
5114 			map->pin_path, errstr(err));
5115 		return err;
5116 	}
5117 
5118 	if (!map_is_reuse_compat(map, pin_fd)) {
5119 		pr_warn("couldn't reuse pinned map at '%s': parameter mismatch\n",
5120 			map->pin_path);
5121 		close(pin_fd);
5122 		return -EINVAL;
5123 	}
5124 
5125 	err = bpf_map__reuse_fd(map, pin_fd);
5126 	close(pin_fd);
5127 	if (err)
5128 		return err;
5129 
5130 	map->pinned = true;
5131 	pr_debug("reused pinned map at '%s'\n", map->pin_path);
5132 
5133 	return 0;
5134 }
5135 
5136 static int
5137 bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
5138 {
5139 	enum libbpf_map_type map_type = map->libbpf_type;
5140 	int err, zero = 0;
5141 	size_t mmap_sz;
5142 
5143 	if (obj->gen_loader) {
5144 		bpf_gen__map_update_elem(obj->gen_loader, map - obj->maps,
5145 					 map->mmaped, map->def.value_size);
5146 		if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG)
5147 			bpf_gen__map_freeze(obj->gen_loader, map - obj->maps);
5148 		return 0;
5149 	}
5150 
5151 	err = bpf_map_update_elem(map->fd, &zero, map->mmaped, 0);
5152 	if (err) {
5153 		err = -errno;
5154 		pr_warn("map '%s': failed to set initial contents: %s\n",
5155 			bpf_map__name(map), errstr(err));
5156 		return err;
5157 	}
5158 
5159 	/* Freeze .rodata and .kconfig map as read-only from syscall side. */
5160 	if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG) {
5161 		err = bpf_map_freeze(map->fd);
5162 		if (err) {
5163 			err = -errno;
5164 			pr_warn("map '%s': failed to freeze as read-only: %s\n",
5165 				bpf_map__name(map), errstr(err));
5166 			return err;
5167 		}
5168 	}
5169 
5170 	/* Remap anonymous mmap()-ed "map initialization image" as
5171 	 * a BPF map-backed mmap()-ed memory, but preserving the same
5172 	 * memory address. This will cause kernel to change process'
5173 	 * page table to point to a different piece of kernel memory,
5174 	 * but from userspace point of view memory address (and its
5175 	 * contents, being identical at this point) will stay the
5176 	 * same. This mapping will be released by bpf_object__close()
5177 	 * as per normal clean up procedure.
5178 	 */
5179 	mmap_sz = bpf_map_mmap_sz(map);
5180 	if (map->def.map_flags & BPF_F_MMAPABLE) {
5181 		void *mmaped;
5182 		int prot;
5183 
5184 		if (map->def.map_flags & BPF_F_RDONLY_PROG)
5185 			prot = PROT_READ;
5186 		else
5187 			prot = PROT_READ | PROT_WRITE;
5188 		mmaped = mmap(map->mmaped, mmap_sz, prot, MAP_SHARED | MAP_FIXED, map->fd, 0);
5189 		if (mmaped == MAP_FAILED) {
5190 			err = -errno;
5191 			pr_warn("map '%s': failed to re-mmap() contents: %s\n",
5192 				bpf_map__name(map), errstr(err));
5193 			return err;
5194 		}
5195 		map->mmaped = mmaped;
5196 	} else if (map->mmaped) {
5197 		munmap(map->mmaped, mmap_sz);
5198 		map->mmaped = NULL;
5199 	}
5200 
5201 	return 0;
5202 }
5203 
5204 static void bpf_map__destroy(struct bpf_map *map);
5205 
5206 static int bpf_object__create_map(struct bpf_object *obj, struct bpf_map *map, bool is_inner)
5207 {
5208 	LIBBPF_OPTS(bpf_map_create_opts, create_attr);
5209 	struct bpf_map_def *def = &map->def;
5210 	const char *map_name = NULL;
5211 	int err = 0, map_fd;
5212 
5213 	if (kernel_supports(obj, FEAT_PROG_NAME))
5214 		map_name = map->name;
5215 	create_attr.map_ifindex = map->map_ifindex;
5216 	create_attr.map_flags = def->map_flags;
5217 	create_attr.numa_node = map->numa_node;
5218 	create_attr.map_extra = map->map_extra;
5219 	create_attr.token_fd = obj->token_fd;
5220 	if (obj->token_fd)
5221 		create_attr.map_flags |= BPF_F_TOKEN_FD;
5222 
5223 	if (bpf_map__is_struct_ops(map)) {
5224 		create_attr.btf_vmlinux_value_type_id = map->btf_vmlinux_value_type_id;
5225 		if (map->mod_btf_fd >= 0) {
5226 			create_attr.value_type_btf_obj_fd = map->mod_btf_fd;
5227 			create_attr.map_flags |= BPF_F_VTYPE_BTF_OBJ_FD;
5228 		}
5229 	}
5230 
5231 	if (obj->btf && btf__fd(obj->btf) >= 0) {
5232 		create_attr.btf_fd = btf__fd(obj->btf);
5233 		create_attr.btf_key_type_id = map->btf_key_type_id;
5234 		create_attr.btf_value_type_id = map->btf_value_type_id;
5235 	}
5236 
5237 	if (bpf_map_type__is_map_in_map(def->type)) {
5238 		if (map->inner_map) {
5239 			err = map_set_def_max_entries(map->inner_map);
5240 			if (err)
5241 				return err;
5242 			err = bpf_object__create_map(obj, map->inner_map, true);
5243 			if (err) {
5244 				pr_warn("map '%s': failed to create inner map: %s\n",
5245 					map->name, errstr(err));
5246 				return err;
5247 			}
5248 			map->inner_map_fd = map->inner_map->fd;
5249 		}
5250 		if (map->inner_map_fd >= 0)
5251 			create_attr.inner_map_fd = map->inner_map_fd;
5252 	}
5253 
5254 	switch (def->type) {
5255 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
5256 	case BPF_MAP_TYPE_CGROUP_ARRAY:
5257 	case BPF_MAP_TYPE_STACK_TRACE:
5258 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
5259 	case BPF_MAP_TYPE_HASH_OF_MAPS:
5260 	case BPF_MAP_TYPE_DEVMAP:
5261 	case BPF_MAP_TYPE_DEVMAP_HASH:
5262 	case BPF_MAP_TYPE_CPUMAP:
5263 	case BPF_MAP_TYPE_XSKMAP:
5264 	case BPF_MAP_TYPE_SOCKMAP:
5265 	case BPF_MAP_TYPE_SOCKHASH:
5266 	case BPF_MAP_TYPE_QUEUE:
5267 	case BPF_MAP_TYPE_STACK:
5268 	case BPF_MAP_TYPE_ARENA:
5269 		create_attr.btf_fd = 0;
5270 		create_attr.btf_key_type_id = 0;
5271 		create_attr.btf_value_type_id = 0;
5272 		map->btf_key_type_id = 0;
5273 		map->btf_value_type_id = 0;
5274 		break;
5275 	case BPF_MAP_TYPE_STRUCT_OPS:
5276 		create_attr.btf_value_type_id = 0;
5277 		break;
5278 	default:
5279 		break;
5280 	}
5281 
5282 	if (obj->gen_loader) {
5283 		bpf_gen__map_create(obj->gen_loader, def->type, map_name,
5284 				    def->key_size, def->value_size, def->max_entries,
5285 				    &create_attr, is_inner ? -1 : map - obj->maps);
5286 		/* We keep pretenting we have valid FD to pass various fd >= 0
5287 		 * checks by just keeping original placeholder FDs in place.
5288 		 * See bpf_object__add_map() comment.
5289 		 * This placeholder fd will not be used with any syscall and
5290 		 * will be reset to -1 eventually.
5291 		 */
5292 		map_fd = map->fd;
5293 	} else {
5294 		map_fd = bpf_map_create(def->type, map_name,
5295 					def->key_size, def->value_size,
5296 					def->max_entries, &create_attr);
5297 	}
5298 	if (map_fd < 0 && (create_attr.btf_key_type_id || create_attr.btf_value_type_id)) {
5299 		err = -errno;
5300 		pr_warn("Error in bpf_create_map_xattr(%s): %s. Retrying without BTF.\n",
5301 			map->name, errstr(err));
5302 		create_attr.btf_fd = 0;
5303 		create_attr.btf_key_type_id = 0;
5304 		create_attr.btf_value_type_id = 0;
5305 		map->btf_key_type_id = 0;
5306 		map->btf_value_type_id = 0;
5307 		map_fd = bpf_map_create(def->type, map_name,
5308 					def->key_size, def->value_size,
5309 					def->max_entries, &create_attr);
5310 	}
5311 
5312 	if (bpf_map_type__is_map_in_map(def->type) && map->inner_map) {
5313 		if (obj->gen_loader)
5314 			map->inner_map->fd = -1;
5315 		bpf_map__destroy(map->inner_map);
5316 		zfree(&map->inner_map);
5317 	}
5318 
5319 	if (map_fd < 0)
5320 		return map_fd;
5321 
5322 	/* obj->gen_loader case, prevent reuse_fd() from closing map_fd */
5323 	if (map->fd == map_fd)
5324 		return 0;
5325 
5326 	/* Keep placeholder FD value but now point it to the BPF map object.
5327 	 * This way everything that relied on this map's FD (e.g., relocated
5328 	 * ldimm64 instructions) will stay valid and won't need adjustments.
5329 	 * map->fd stays valid but now point to what map_fd points to.
5330 	 */
5331 	return reuse_fd(map->fd, map_fd);
5332 }
5333 
5334 static int init_map_in_map_slots(struct bpf_object *obj, struct bpf_map *map)
5335 {
5336 	const struct bpf_map *targ_map;
5337 	unsigned int i;
5338 	int fd, err = 0;
5339 
5340 	for (i = 0; i < map->init_slots_sz; i++) {
5341 		if (!map->init_slots[i])
5342 			continue;
5343 
5344 		targ_map = map->init_slots[i];
5345 		fd = targ_map->fd;
5346 
5347 		if (obj->gen_loader) {
5348 			bpf_gen__populate_outer_map(obj->gen_loader,
5349 						    map - obj->maps, i,
5350 						    targ_map - obj->maps);
5351 		} else {
5352 			err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5353 		}
5354 		if (err) {
5355 			err = -errno;
5356 			pr_warn("map '%s': failed to initialize slot [%d] to map '%s' fd=%d: %s\n",
5357 				map->name, i, targ_map->name, fd, errstr(err));
5358 			return err;
5359 		}
5360 		pr_debug("map '%s': slot [%d] set to map '%s' fd=%d\n",
5361 			 map->name, i, targ_map->name, fd);
5362 	}
5363 
5364 	zfree(&map->init_slots);
5365 	map->init_slots_sz = 0;
5366 
5367 	return 0;
5368 }
5369 
5370 static int init_prog_array_slots(struct bpf_object *obj, struct bpf_map *map)
5371 {
5372 	const struct bpf_program *targ_prog;
5373 	unsigned int i;
5374 	int fd, err;
5375 
5376 	if (obj->gen_loader)
5377 		return -ENOTSUP;
5378 
5379 	for (i = 0; i < map->init_slots_sz; i++) {
5380 		if (!map->init_slots[i])
5381 			continue;
5382 
5383 		targ_prog = map->init_slots[i];
5384 		fd = bpf_program__fd(targ_prog);
5385 
5386 		err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5387 		if (err) {
5388 			err = -errno;
5389 			pr_warn("map '%s': failed to initialize slot [%d] to prog '%s' fd=%d: %s\n",
5390 				map->name, i, targ_prog->name, fd, errstr(err));
5391 			return err;
5392 		}
5393 		pr_debug("map '%s': slot [%d] set to prog '%s' fd=%d\n",
5394 			 map->name, i, targ_prog->name, fd);
5395 	}
5396 
5397 	zfree(&map->init_slots);
5398 	map->init_slots_sz = 0;
5399 
5400 	return 0;
5401 }
5402 
5403 static int bpf_object_init_prog_arrays(struct bpf_object *obj)
5404 {
5405 	struct bpf_map *map;
5406 	int i, err;
5407 
5408 	for (i = 0; i < obj->nr_maps; i++) {
5409 		map = &obj->maps[i];
5410 
5411 		if (!map->init_slots_sz || map->def.type != BPF_MAP_TYPE_PROG_ARRAY)
5412 			continue;
5413 
5414 		err = init_prog_array_slots(obj, map);
5415 		if (err < 0)
5416 			return err;
5417 	}
5418 	return 0;
5419 }
5420 
5421 static int map_set_def_max_entries(struct bpf_map *map)
5422 {
5423 	if (map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY && !map->def.max_entries) {
5424 		int nr_cpus;
5425 
5426 		nr_cpus = libbpf_num_possible_cpus();
5427 		if (nr_cpus < 0) {
5428 			pr_warn("map '%s': failed to determine number of system CPUs: %d\n",
5429 				map->name, nr_cpus);
5430 			return nr_cpus;
5431 		}
5432 		pr_debug("map '%s': setting size to %d\n", map->name, nr_cpus);
5433 		map->def.max_entries = nr_cpus;
5434 	}
5435 
5436 	return 0;
5437 }
5438 
5439 static int
5440 bpf_object__create_maps(struct bpf_object *obj)
5441 {
5442 	struct bpf_map *map;
5443 	unsigned int i, j;
5444 	int err;
5445 	bool retried;
5446 
5447 	for (i = 0; i < obj->nr_maps; i++) {
5448 		map = &obj->maps[i];
5449 
5450 		/* To support old kernels, we skip creating global data maps
5451 		 * (.rodata, .data, .kconfig, etc); later on, during program
5452 		 * loading, if we detect that at least one of the to-be-loaded
5453 		 * programs is referencing any global data map, we'll error
5454 		 * out with program name and relocation index logged.
5455 		 * This approach allows to accommodate Clang emitting
5456 		 * unnecessary .rodata.str1.1 sections for string literals,
5457 		 * but also it allows to have CO-RE applications that use
5458 		 * global variables in some of BPF programs, but not others.
5459 		 * If those global variable-using programs are not loaded at
5460 		 * runtime due to bpf_program__set_autoload(prog, false),
5461 		 * bpf_object loading will succeed just fine even on old
5462 		 * kernels.
5463 		 */
5464 		if (bpf_map__is_internal(map) && !kernel_supports(obj, FEAT_GLOBAL_DATA))
5465 			map->autocreate = false;
5466 
5467 		if (!map->autocreate) {
5468 			pr_debug("map '%s': skipped auto-creating...\n", map->name);
5469 			continue;
5470 		}
5471 
5472 		err = map_set_def_max_entries(map);
5473 		if (err)
5474 			goto err_out;
5475 
5476 		retried = false;
5477 retry:
5478 		if (map->pin_path) {
5479 			err = bpf_object__reuse_map(map);
5480 			if (err) {
5481 				pr_warn("map '%s': error reusing pinned map\n",
5482 					map->name);
5483 				goto err_out;
5484 			}
5485 			if (retried && map->fd < 0) {
5486 				pr_warn("map '%s': cannot find pinned map\n",
5487 					map->name);
5488 				err = -ENOENT;
5489 				goto err_out;
5490 			}
5491 		}
5492 
5493 		if (map->reused) {
5494 			pr_debug("map '%s': skipping creation (preset fd=%d)\n",
5495 				 map->name, map->fd);
5496 		} else {
5497 			err = bpf_object__create_map(obj, map, false);
5498 			if (err)
5499 				goto err_out;
5500 
5501 			pr_debug("map '%s': created successfully, fd=%d\n",
5502 				 map->name, map->fd);
5503 
5504 			if (bpf_map__is_internal(map)) {
5505 				err = bpf_object__populate_internal_map(obj, map);
5506 				if (err < 0)
5507 					goto err_out;
5508 			} else if (map->def.type == BPF_MAP_TYPE_ARENA) {
5509 				map->mmaped = mmap((void *)(long)map->map_extra,
5510 						   bpf_map_mmap_sz(map), PROT_READ | PROT_WRITE,
5511 						   map->map_extra ? MAP_SHARED | MAP_FIXED : MAP_SHARED,
5512 						   map->fd, 0);
5513 				if (map->mmaped == MAP_FAILED) {
5514 					err = -errno;
5515 					map->mmaped = NULL;
5516 					pr_warn("map '%s': failed to mmap arena: %s\n",
5517 						map->name, errstr(err));
5518 					return err;
5519 				}
5520 				if (obj->arena_data) {
5521 					memcpy(map->mmaped, obj->arena_data, obj->arena_data_sz);
5522 					zfree(&obj->arena_data);
5523 				}
5524 			}
5525 			if (map->init_slots_sz && map->def.type != BPF_MAP_TYPE_PROG_ARRAY) {
5526 				err = init_map_in_map_slots(obj, map);
5527 				if (err < 0)
5528 					goto err_out;
5529 			}
5530 		}
5531 
5532 		if (map->pin_path && !map->pinned) {
5533 			err = bpf_map__pin(map, NULL);
5534 			if (err) {
5535 				if (!retried && err == -EEXIST) {
5536 					retried = true;
5537 					goto retry;
5538 				}
5539 				pr_warn("map '%s': failed to auto-pin at '%s': %s\n",
5540 					map->name, map->pin_path, errstr(err));
5541 				goto err_out;
5542 			}
5543 		}
5544 	}
5545 
5546 	return 0;
5547 
5548 err_out:
5549 	pr_warn("map '%s': failed to create: %s\n", map->name, errstr(err));
5550 	pr_perm_msg(err);
5551 	for (j = 0; j < i; j++)
5552 		zclose(obj->maps[j].fd);
5553 	return err;
5554 }
5555 
5556 static bool bpf_core_is_flavor_sep(const char *s)
5557 {
5558 	/* check X___Y name pattern, where X and Y are not underscores */
5559 	return s[0] != '_' &&				      /* X */
5560 	       s[1] == '_' && s[2] == '_' && s[3] == '_' &&   /* ___ */
5561 	       s[4] != '_';				      /* Y */
5562 }
5563 
5564 /* Given 'some_struct_name___with_flavor' return the length of a name prefix
5565  * before last triple underscore. Struct name part after last triple
5566  * underscore is ignored by BPF CO-RE relocation during relocation matching.
5567  */
5568 size_t bpf_core_essential_name_len(const char *name)
5569 {
5570 	size_t n = strlen(name);
5571 	int i;
5572 
5573 	for (i = n - 5; i >= 0; i--) {
5574 		if (bpf_core_is_flavor_sep(name + i))
5575 			return i + 1;
5576 	}
5577 	return n;
5578 }
5579 
5580 void bpf_core_free_cands(struct bpf_core_cand_list *cands)
5581 {
5582 	if (!cands)
5583 		return;
5584 
5585 	free(cands->cands);
5586 	free(cands);
5587 }
5588 
5589 int bpf_core_add_cands(struct bpf_core_cand *local_cand,
5590 		       size_t local_essent_len,
5591 		       const struct btf *targ_btf,
5592 		       const char *targ_btf_name,
5593 		       int targ_start_id,
5594 		       struct bpf_core_cand_list *cands)
5595 {
5596 	struct bpf_core_cand *new_cands, *cand;
5597 	const struct btf_type *t, *local_t;
5598 	const char *targ_name, *local_name;
5599 	size_t targ_essent_len;
5600 	int n, i;
5601 
5602 	local_t = btf__type_by_id(local_cand->btf, local_cand->id);
5603 	local_name = btf__str_by_offset(local_cand->btf, local_t->name_off);
5604 
5605 	n = btf__type_cnt(targ_btf);
5606 	for (i = targ_start_id; i < n; i++) {
5607 		t = btf__type_by_id(targ_btf, i);
5608 		if (!btf_kind_core_compat(t, local_t))
5609 			continue;
5610 
5611 		targ_name = btf__name_by_offset(targ_btf, t->name_off);
5612 		if (str_is_empty(targ_name))
5613 			continue;
5614 
5615 		targ_essent_len = bpf_core_essential_name_len(targ_name);
5616 		if (targ_essent_len != local_essent_len)
5617 			continue;
5618 
5619 		if (strncmp(local_name, targ_name, local_essent_len) != 0)
5620 			continue;
5621 
5622 		pr_debug("CO-RE relocating [%d] %s %s: found target candidate [%d] %s %s in [%s]\n",
5623 			 local_cand->id, btf_kind_str(local_t),
5624 			 local_name, i, btf_kind_str(t), targ_name,
5625 			 targ_btf_name);
5626 		new_cands = libbpf_reallocarray(cands->cands, cands->len + 1,
5627 					      sizeof(*cands->cands));
5628 		if (!new_cands)
5629 			return -ENOMEM;
5630 
5631 		cand = &new_cands[cands->len];
5632 		cand->btf = targ_btf;
5633 		cand->id = i;
5634 
5635 		cands->cands = new_cands;
5636 		cands->len++;
5637 	}
5638 	return 0;
5639 }
5640 
5641 static int load_module_btfs(struct bpf_object *obj)
5642 {
5643 	struct bpf_btf_info info;
5644 	struct module_btf *mod_btf;
5645 	struct btf *btf;
5646 	char name[64];
5647 	__u32 id = 0, len;
5648 	int err, fd;
5649 
5650 	if (obj->btf_modules_loaded)
5651 		return 0;
5652 
5653 	if (obj->gen_loader)
5654 		return 0;
5655 
5656 	/* don't do this again, even if we find no module BTFs */
5657 	obj->btf_modules_loaded = true;
5658 
5659 	/* kernel too old to support module BTFs */
5660 	if (!kernel_supports(obj, FEAT_MODULE_BTF))
5661 		return 0;
5662 
5663 	while (true) {
5664 		err = bpf_btf_get_next_id(id, &id);
5665 		if (err && errno == ENOENT)
5666 			return 0;
5667 		if (err && errno == EPERM) {
5668 			pr_debug("skipping module BTFs loading, missing privileges\n");
5669 			return 0;
5670 		}
5671 		if (err) {
5672 			err = -errno;
5673 			pr_warn("failed to iterate BTF objects: %s\n", errstr(err));
5674 			return err;
5675 		}
5676 
5677 		fd = bpf_btf_get_fd_by_id(id);
5678 		if (fd < 0) {
5679 			if (errno == ENOENT)
5680 				continue; /* expected race: BTF was unloaded */
5681 			err = -errno;
5682 			pr_warn("failed to get BTF object #%d FD: %s\n", id, errstr(err));
5683 			return err;
5684 		}
5685 
5686 		len = sizeof(info);
5687 		memset(&info, 0, sizeof(info));
5688 		info.name = ptr_to_u64(name);
5689 		info.name_len = sizeof(name);
5690 
5691 		err = bpf_btf_get_info_by_fd(fd, &info, &len);
5692 		if (err) {
5693 			err = -errno;
5694 			pr_warn("failed to get BTF object #%d info: %s\n", id, errstr(err));
5695 			goto err_out;
5696 		}
5697 
5698 		/* ignore non-module BTFs */
5699 		if (!info.kernel_btf || strcmp(name, "vmlinux") == 0) {
5700 			close(fd);
5701 			continue;
5702 		}
5703 
5704 		btf = btf_get_from_fd(fd, obj->btf_vmlinux);
5705 		err = libbpf_get_error(btf);
5706 		if (err) {
5707 			pr_warn("failed to load module [%s]'s BTF object #%d: %s\n",
5708 				name, id, errstr(err));
5709 			goto err_out;
5710 		}
5711 
5712 		err = libbpf_ensure_mem((void **)&obj->btf_modules, &obj->btf_module_cap,
5713 					sizeof(*obj->btf_modules), obj->btf_module_cnt + 1);
5714 		if (err)
5715 			goto err_out;
5716 
5717 		mod_btf = &obj->btf_modules[obj->btf_module_cnt++];
5718 
5719 		mod_btf->btf = btf;
5720 		mod_btf->id = id;
5721 		mod_btf->fd = fd;
5722 		mod_btf->name = strdup(name);
5723 		if (!mod_btf->name) {
5724 			err = -ENOMEM;
5725 			goto err_out;
5726 		}
5727 		continue;
5728 
5729 err_out:
5730 		close(fd);
5731 		return err;
5732 	}
5733 
5734 	return 0;
5735 }
5736 
5737 static struct bpf_core_cand_list *
5738 bpf_core_find_cands(struct bpf_object *obj, const struct btf *local_btf, __u32 local_type_id)
5739 {
5740 	struct bpf_core_cand local_cand = {};
5741 	struct bpf_core_cand_list *cands;
5742 	const struct btf *main_btf;
5743 	const struct btf_type *local_t;
5744 	const char *local_name;
5745 	size_t local_essent_len;
5746 	int err, i;
5747 
5748 	local_cand.btf = local_btf;
5749 	local_cand.id = local_type_id;
5750 	local_t = btf__type_by_id(local_btf, local_type_id);
5751 	if (!local_t)
5752 		return ERR_PTR(-EINVAL);
5753 
5754 	local_name = btf__name_by_offset(local_btf, local_t->name_off);
5755 	if (str_is_empty(local_name))
5756 		return ERR_PTR(-EINVAL);
5757 	local_essent_len = bpf_core_essential_name_len(local_name);
5758 
5759 	cands = calloc(1, sizeof(*cands));
5760 	if (!cands)
5761 		return ERR_PTR(-ENOMEM);
5762 
5763 	/* Attempt to find target candidates in vmlinux BTF first */
5764 	main_btf = obj->btf_vmlinux_override ?: obj->btf_vmlinux;
5765 	err = bpf_core_add_cands(&local_cand, local_essent_len, main_btf, "vmlinux", 1, cands);
5766 	if (err)
5767 		goto err_out;
5768 
5769 	/* if vmlinux BTF has any candidate, don't got for module BTFs */
5770 	if (cands->len)
5771 		return cands;
5772 
5773 	/* if vmlinux BTF was overridden, don't attempt to load module BTFs */
5774 	if (obj->btf_vmlinux_override)
5775 		return cands;
5776 
5777 	/* now look through module BTFs, trying to still find candidates */
5778 	err = load_module_btfs(obj);
5779 	if (err)
5780 		goto err_out;
5781 
5782 	for (i = 0; i < obj->btf_module_cnt; i++) {
5783 		err = bpf_core_add_cands(&local_cand, local_essent_len,
5784 					 obj->btf_modules[i].btf,
5785 					 obj->btf_modules[i].name,
5786 					 btf__type_cnt(obj->btf_vmlinux),
5787 					 cands);
5788 		if (err)
5789 			goto err_out;
5790 	}
5791 
5792 	return cands;
5793 err_out:
5794 	bpf_core_free_cands(cands);
5795 	return ERR_PTR(err);
5796 }
5797 
5798 /* Check local and target types for compatibility. This check is used for
5799  * type-based CO-RE relocations and follow slightly different rules than
5800  * field-based relocations. This function assumes that root types were already
5801  * checked for name match. Beyond that initial root-level name check, names
5802  * are completely ignored. Compatibility rules are as follows:
5803  *   - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs are considered compatible, but
5804  *     kind should match for local and target types (i.e., STRUCT is not
5805  *     compatible with UNION);
5806  *   - for ENUMs, the size is ignored;
5807  *   - for INT, size and signedness are ignored;
5808  *   - for ARRAY, dimensionality is ignored, element types are checked for
5809  *     compatibility recursively;
5810  *   - CONST/VOLATILE/RESTRICT modifiers are ignored;
5811  *   - TYPEDEFs/PTRs are compatible if types they pointing to are compatible;
5812  *   - FUNC_PROTOs are compatible if they have compatible signature: same
5813  *     number of input args and compatible return and argument types.
5814  * These rules are not set in stone and probably will be adjusted as we get
5815  * more experience with using BPF CO-RE relocations.
5816  */
5817 int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
5818 			      const struct btf *targ_btf, __u32 targ_id)
5819 {
5820 	return __bpf_core_types_are_compat(local_btf, local_id, targ_btf, targ_id, 32);
5821 }
5822 
5823 int bpf_core_types_match(const struct btf *local_btf, __u32 local_id,
5824 			 const struct btf *targ_btf, __u32 targ_id)
5825 {
5826 	return __bpf_core_types_match(local_btf, local_id, targ_btf, targ_id, false, 32);
5827 }
5828 
5829 static size_t bpf_core_hash_fn(const long key, void *ctx)
5830 {
5831 	return key;
5832 }
5833 
5834 static bool bpf_core_equal_fn(const long k1, const long k2, void *ctx)
5835 {
5836 	return k1 == k2;
5837 }
5838 
5839 static int record_relo_core(struct bpf_program *prog,
5840 			    const struct bpf_core_relo *core_relo, int insn_idx)
5841 {
5842 	struct reloc_desc *relos, *relo;
5843 
5844 	relos = libbpf_reallocarray(prog->reloc_desc,
5845 				    prog->nr_reloc + 1, sizeof(*relos));
5846 	if (!relos)
5847 		return -ENOMEM;
5848 	relo = &relos[prog->nr_reloc];
5849 	relo->type = RELO_CORE;
5850 	relo->insn_idx = insn_idx;
5851 	relo->core_relo = core_relo;
5852 	prog->reloc_desc = relos;
5853 	prog->nr_reloc++;
5854 	return 0;
5855 }
5856 
5857 static const struct bpf_core_relo *find_relo_core(struct bpf_program *prog, int insn_idx)
5858 {
5859 	struct reloc_desc *relo;
5860 	int i;
5861 
5862 	for (i = 0; i < prog->nr_reloc; i++) {
5863 		relo = &prog->reloc_desc[i];
5864 		if (relo->type != RELO_CORE || relo->insn_idx != insn_idx)
5865 			continue;
5866 
5867 		return relo->core_relo;
5868 	}
5869 
5870 	return NULL;
5871 }
5872 
5873 static int bpf_core_resolve_relo(struct bpf_program *prog,
5874 				 const struct bpf_core_relo *relo,
5875 				 int relo_idx,
5876 				 const struct btf *local_btf,
5877 				 struct hashmap *cand_cache,
5878 				 struct bpf_core_relo_res *targ_res)
5879 {
5880 	struct bpf_core_spec specs_scratch[3] = {};
5881 	struct bpf_core_cand_list *cands = NULL;
5882 	const char *prog_name = prog->name;
5883 	const struct btf_type *local_type;
5884 	const char *local_name;
5885 	__u32 local_id = relo->type_id;
5886 	int err;
5887 
5888 	local_type = btf__type_by_id(local_btf, local_id);
5889 	if (!local_type)
5890 		return -EINVAL;
5891 
5892 	local_name = btf__name_by_offset(local_btf, local_type->name_off);
5893 	if (!local_name)
5894 		return -EINVAL;
5895 
5896 	if (relo->kind != BPF_CORE_TYPE_ID_LOCAL &&
5897 	    !hashmap__find(cand_cache, local_id, &cands)) {
5898 		cands = bpf_core_find_cands(prog->obj, local_btf, local_id);
5899 		if (IS_ERR(cands)) {
5900 			pr_warn("prog '%s': relo #%d: target candidate search failed for [%d] %s %s: %ld\n",
5901 				prog_name, relo_idx, local_id, btf_kind_str(local_type),
5902 				local_name, PTR_ERR(cands));
5903 			return PTR_ERR(cands);
5904 		}
5905 		err = hashmap__set(cand_cache, local_id, cands, NULL, NULL);
5906 		if (err) {
5907 			bpf_core_free_cands(cands);
5908 			return err;
5909 		}
5910 	}
5911 
5912 	return bpf_core_calc_relo_insn(prog_name, relo, relo_idx, local_btf, cands, specs_scratch,
5913 				       targ_res);
5914 }
5915 
5916 static int
5917 bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
5918 {
5919 	const struct btf_ext_info_sec *sec;
5920 	struct bpf_core_relo_res targ_res;
5921 	const struct bpf_core_relo *rec;
5922 	const struct btf_ext_info *seg;
5923 	struct hashmap_entry *entry;
5924 	struct hashmap *cand_cache = NULL;
5925 	struct bpf_program *prog;
5926 	struct bpf_insn *insn;
5927 	const char *sec_name;
5928 	int i, err = 0, insn_idx, sec_idx, sec_num;
5929 
5930 	if (obj->btf_ext->core_relo_info.len == 0)
5931 		return 0;
5932 
5933 	if (targ_btf_path) {
5934 		obj->btf_vmlinux_override = btf__parse(targ_btf_path, NULL);
5935 		err = libbpf_get_error(obj->btf_vmlinux_override);
5936 		if (err) {
5937 			pr_warn("failed to parse target BTF: %s\n", errstr(err));
5938 			return err;
5939 		}
5940 	}
5941 
5942 	cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
5943 	if (IS_ERR(cand_cache)) {
5944 		err = PTR_ERR(cand_cache);
5945 		goto out;
5946 	}
5947 
5948 	seg = &obj->btf_ext->core_relo_info;
5949 	sec_num = 0;
5950 	for_each_btf_ext_sec(seg, sec) {
5951 		sec_idx = seg->sec_idxs[sec_num];
5952 		sec_num++;
5953 
5954 		sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
5955 		if (str_is_empty(sec_name)) {
5956 			err = -EINVAL;
5957 			goto out;
5958 		}
5959 
5960 		pr_debug("sec '%s': found %d CO-RE relocations\n", sec_name, sec->num_info);
5961 
5962 		for_each_btf_ext_rec(seg, sec, i, rec) {
5963 			if (rec->insn_off % BPF_INSN_SZ)
5964 				return -EINVAL;
5965 			insn_idx = rec->insn_off / BPF_INSN_SZ;
5966 			prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
5967 			if (!prog) {
5968 				/* When __weak subprog is "overridden" by another instance
5969 				 * of the subprog from a different object file, linker still
5970 				 * appends all the .BTF.ext info that used to belong to that
5971 				 * eliminated subprogram.
5972 				 * This is similar to what x86-64 linker does for relocations.
5973 				 * So just ignore such relocations just like we ignore
5974 				 * subprog instructions when discovering subprograms.
5975 				 */
5976 				pr_debug("sec '%s': skipping CO-RE relocation #%d for insn #%d belonging to eliminated weak subprogram\n",
5977 					 sec_name, i, insn_idx);
5978 				continue;
5979 			}
5980 			/* no need to apply CO-RE relocation if the program is
5981 			 * not going to be loaded
5982 			 */
5983 			if (!prog->autoload)
5984 				continue;
5985 
5986 			/* adjust insn_idx from section frame of reference to the local
5987 			 * program's frame of reference; (sub-)program code is not yet
5988 			 * relocated, so it's enough to just subtract in-section offset
5989 			 */
5990 			insn_idx = insn_idx - prog->sec_insn_off;
5991 			if (insn_idx >= prog->insns_cnt)
5992 				return -EINVAL;
5993 			insn = &prog->insns[insn_idx];
5994 
5995 			err = record_relo_core(prog, rec, insn_idx);
5996 			if (err) {
5997 				pr_warn("prog '%s': relo #%d: failed to record relocation: %s\n",
5998 					prog->name, i, errstr(err));
5999 				goto out;
6000 			}
6001 
6002 			if (prog->obj->gen_loader)
6003 				continue;
6004 
6005 			err = bpf_core_resolve_relo(prog, rec, i, obj->btf, cand_cache, &targ_res);
6006 			if (err) {
6007 				pr_warn("prog '%s': relo #%d: failed to relocate: %s\n",
6008 					prog->name, i, errstr(err));
6009 				goto out;
6010 			}
6011 
6012 			err = bpf_core_patch_insn(prog->name, insn, insn_idx, rec, i, &targ_res);
6013 			if (err) {
6014 				pr_warn("prog '%s': relo #%d: failed to patch insn #%u: %s\n",
6015 					prog->name, i, insn_idx, errstr(err));
6016 				goto out;
6017 			}
6018 		}
6019 	}
6020 
6021 out:
6022 	/* obj->btf_vmlinux and module BTFs are freed after object load */
6023 	btf__free(obj->btf_vmlinux_override);
6024 	obj->btf_vmlinux_override = NULL;
6025 
6026 	if (!IS_ERR_OR_NULL(cand_cache)) {
6027 		hashmap__for_each_entry(cand_cache, entry, i) {
6028 			bpf_core_free_cands(entry->pvalue);
6029 		}
6030 		hashmap__free(cand_cache);
6031 	}
6032 	return err;
6033 }
6034 
6035 /* base map load ldimm64 special constant, used also for log fixup logic */
6036 #define POISON_LDIMM64_MAP_BASE 2001000000
6037 #define POISON_LDIMM64_MAP_PFX "200100"
6038 
6039 static void poison_map_ldimm64(struct bpf_program *prog, int relo_idx,
6040 			       int insn_idx, struct bpf_insn *insn,
6041 			       int map_idx, const struct bpf_map *map)
6042 {
6043 	int i;
6044 
6045 	pr_debug("prog '%s': relo #%d: poisoning insn #%d that loads map #%d '%s'\n",
6046 		 prog->name, relo_idx, insn_idx, map_idx, map->name);
6047 
6048 	/* we turn single ldimm64 into two identical invalid calls */
6049 	for (i = 0; i < 2; i++) {
6050 		insn->code = BPF_JMP | BPF_CALL;
6051 		insn->dst_reg = 0;
6052 		insn->src_reg = 0;
6053 		insn->off = 0;
6054 		/* if this instruction is reachable (not a dead code),
6055 		 * verifier will complain with something like:
6056 		 * invalid func unknown#2001000123
6057 		 * where lower 123 is map index into obj->maps[] array
6058 		 */
6059 		insn->imm = POISON_LDIMM64_MAP_BASE + map_idx;
6060 
6061 		insn++;
6062 	}
6063 }
6064 
6065 /* unresolved kfunc call special constant, used also for log fixup logic */
6066 #define POISON_CALL_KFUNC_BASE 2002000000
6067 #define POISON_CALL_KFUNC_PFX "2002"
6068 
6069 static void poison_kfunc_call(struct bpf_program *prog, int relo_idx,
6070 			      int insn_idx, struct bpf_insn *insn,
6071 			      int ext_idx, const struct extern_desc *ext)
6072 {
6073 	pr_debug("prog '%s': relo #%d: poisoning insn #%d that calls kfunc '%s'\n",
6074 		 prog->name, relo_idx, insn_idx, ext->name);
6075 
6076 	/* we turn kfunc call into invalid helper call with identifiable constant */
6077 	insn->code = BPF_JMP | BPF_CALL;
6078 	insn->dst_reg = 0;
6079 	insn->src_reg = 0;
6080 	insn->off = 0;
6081 	/* if this instruction is reachable (not a dead code),
6082 	 * verifier will complain with something like:
6083 	 * invalid func unknown#2001000123
6084 	 * where lower 123 is extern index into obj->externs[] array
6085 	 */
6086 	insn->imm = POISON_CALL_KFUNC_BASE + ext_idx;
6087 }
6088 
6089 /* Relocate data references within program code:
6090  *  - map references;
6091  *  - global variable references;
6092  *  - extern references.
6093  */
6094 static int
6095 bpf_object__relocate_data(struct bpf_object *obj, struct bpf_program *prog)
6096 {
6097 	int i;
6098 
6099 	for (i = 0; i < prog->nr_reloc; i++) {
6100 		struct reloc_desc *relo = &prog->reloc_desc[i];
6101 		struct bpf_insn *insn = &prog->insns[relo->insn_idx];
6102 		const struct bpf_map *map;
6103 		struct extern_desc *ext;
6104 
6105 		switch (relo->type) {
6106 		case RELO_LD64:
6107 			map = &obj->maps[relo->map_idx];
6108 			if (obj->gen_loader) {
6109 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX;
6110 				insn[0].imm = relo->map_idx;
6111 			} else if (map->autocreate) {
6112 				insn[0].src_reg = BPF_PSEUDO_MAP_FD;
6113 				insn[0].imm = map->fd;
6114 			} else {
6115 				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
6116 						   relo->map_idx, map);
6117 			}
6118 			break;
6119 		case RELO_DATA:
6120 			map = &obj->maps[relo->map_idx];
6121 			insn[1].imm = insn[0].imm + relo->sym_off;
6122 			if (obj->gen_loader) {
6123 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
6124 				insn[0].imm = relo->map_idx;
6125 			} else if (map->autocreate) {
6126 				insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6127 				insn[0].imm = map->fd;
6128 			} else {
6129 				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
6130 						   relo->map_idx, map);
6131 			}
6132 			break;
6133 		case RELO_EXTERN_LD64:
6134 			ext = &obj->externs[relo->ext_idx];
6135 			if (ext->type == EXT_KCFG) {
6136 				if (obj->gen_loader) {
6137 					insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
6138 					insn[0].imm = obj->kconfig_map_idx;
6139 				} else {
6140 					insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6141 					insn[0].imm = obj->maps[obj->kconfig_map_idx].fd;
6142 				}
6143 				insn[1].imm = ext->kcfg.data_off;
6144 			} else /* EXT_KSYM */ {
6145 				if (ext->ksym.type_id && ext->is_set) { /* typed ksyms */
6146 					insn[0].src_reg = BPF_PSEUDO_BTF_ID;
6147 					insn[0].imm = ext->ksym.kernel_btf_id;
6148 					insn[1].imm = ext->ksym.kernel_btf_obj_fd;
6149 				} else { /* typeless ksyms or unresolved typed ksyms */
6150 					insn[0].imm = (__u32)ext->ksym.addr;
6151 					insn[1].imm = ext->ksym.addr >> 32;
6152 				}
6153 			}
6154 			break;
6155 		case RELO_EXTERN_CALL:
6156 			ext = &obj->externs[relo->ext_idx];
6157 			insn[0].src_reg = BPF_PSEUDO_KFUNC_CALL;
6158 			if (ext->is_set) {
6159 				insn[0].imm = ext->ksym.kernel_btf_id;
6160 				insn[0].off = ext->ksym.btf_fd_idx;
6161 			} else { /* unresolved weak kfunc call */
6162 				poison_kfunc_call(prog, i, relo->insn_idx, insn,
6163 						  relo->ext_idx, ext);
6164 			}
6165 			break;
6166 		case RELO_SUBPROG_ADDR:
6167 			if (insn[0].src_reg != BPF_PSEUDO_FUNC) {
6168 				pr_warn("prog '%s': relo #%d: bad insn\n",
6169 					prog->name, i);
6170 				return -EINVAL;
6171 			}
6172 			/* handled already */
6173 			break;
6174 		case RELO_CALL:
6175 			/* handled already */
6176 			break;
6177 		case RELO_CORE:
6178 			/* will be handled by bpf_program_record_relos() */
6179 			break;
6180 		default:
6181 			pr_warn("prog '%s': relo #%d: bad relo type %d\n",
6182 				prog->name, i, relo->type);
6183 			return -EINVAL;
6184 		}
6185 	}
6186 
6187 	return 0;
6188 }
6189 
6190 static int adjust_prog_btf_ext_info(const struct bpf_object *obj,
6191 				    const struct bpf_program *prog,
6192 				    const struct btf_ext_info *ext_info,
6193 				    void **prog_info, __u32 *prog_rec_cnt,
6194 				    __u32 *prog_rec_sz)
6195 {
6196 	void *copy_start = NULL, *copy_end = NULL;
6197 	void *rec, *rec_end, *new_prog_info;
6198 	const struct btf_ext_info_sec *sec;
6199 	size_t old_sz, new_sz;
6200 	int i, sec_num, sec_idx, off_adj;
6201 
6202 	sec_num = 0;
6203 	for_each_btf_ext_sec(ext_info, sec) {
6204 		sec_idx = ext_info->sec_idxs[sec_num];
6205 		sec_num++;
6206 		if (prog->sec_idx != sec_idx)
6207 			continue;
6208 
6209 		for_each_btf_ext_rec(ext_info, sec, i, rec) {
6210 			__u32 insn_off = *(__u32 *)rec / BPF_INSN_SZ;
6211 
6212 			if (insn_off < prog->sec_insn_off)
6213 				continue;
6214 			if (insn_off >= prog->sec_insn_off + prog->sec_insn_cnt)
6215 				break;
6216 
6217 			if (!copy_start)
6218 				copy_start = rec;
6219 			copy_end = rec + ext_info->rec_size;
6220 		}
6221 
6222 		if (!copy_start)
6223 			return -ENOENT;
6224 
6225 		/* append func/line info of a given (sub-)program to the main
6226 		 * program func/line info
6227 		 */
6228 		old_sz = (size_t)(*prog_rec_cnt) * ext_info->rec_size;
6229 		new_sz = old_sz + (copy_end - copy_start);
6230 		new_prog_info = realloc(*prog_info, new_sz);
6231 		if (!new_prog_info)
6232 			return -ENOMEM;
6233 		*prog_info = new_prog_info;
6234 		*prog_rec_cnt = new_sz / ext_info->rec_size;
6235 		memcpy(new_prog_info + old_sz, copy_start, copy_end - copy_start);
6236 
6237 		/* Kernel instruction offsets are in units of 8-byte
6238 		 * instructions, while .BTF.ext instruction offsets generated
6239 		 * by Clang are in units of bytes. So convert Clang offsets
6240 		 * into kernel offsets and adjust offset according to program
6241 		 * relocated position.
6242 		 */
6243 		off_adj = prog->sub_insn_off - prog->sec_insn_off;
6244 		rec = new_prog_info + old_sz;
6245 		rec_end = new_prog_info + new_sz;
6246 		for (; rec < rec_end; rec += ext_info->rec_size) {
6247 			__u32 *insn_off = rec;
6248 
6249 			*insn_off = *insn_off / BPF_INSN_SZ + off_adj;
6250 		}
6251 		*prog_rec_sz = ext_info->rec_size;
6252 		return 0;
6253 	}
6254 
6255 	return -ENOENT;
6256 }
6257 
6258 static int
6259 reloc_prog_func_and_line_info(const struct bpf_object *obj,
6260 			      struct bpf_program *main_prog,
6261 			      const struct bpf_program *prog)
6262 {
6263 	int err;
6264 
6265 	/* no .BTF.ext relocation if .BTF.ext is missing or kernel doesn't
6266 	 * support func/line info
6267 	 */
6268 	if (!obj->btf_ext || !kernel_supports(obj, FEAT_BTF_FUNC))
6269 		return 0;
6270 
6271 	/* only attempt func info relocation if main program's func_info
6272 	 * relocation was successful
6273 	 */
6274 	if (main_prog != prog && !main_prog->func_info)
6275 		goto line_info;
6276 
6277 	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->func_info,
6278 				       &main_prog->func_info,
6279 				       &main_prog->func_info_cnt,
6280 				       &main_prog->func_info_rec_size);
6281 	if (err) {
6282 		if (err != -ENOENT) {
6283 			pr_warn("prog '%s': error relocating .BTF.ext function info: %s\n",
6284 				prog->name, errstr(err));
6285 			return err;
6286 		}
6287 		if (main_prog->func_info) {
6288 			/*
6289 			 * Some info has already been found but has problem
6290 			 * in the last btf_ext reloc. Must have to error out.
6291 			 */
6292 			pr_warn("prog '%s': missing .BTF.ext function info.\n", prog->name);
6293 			return err;
6294 		}
6295 		/* Have problem loading the very first info. Ignore the rest. */
6296 		pr_warn("prog '%s': missing .BTF.ext function info for the main program, skipping all of .BTF.ext func info.\n",
6297 			prog->name);
6298 	}
6299 
6300 line_info:
6301 	/* don't relocate line info if main program's relocation failed */
6302 	if (main_prog != prog && !main_prog->line_info)
6303 		return 0;
6304 
6305 	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->line_info,
6306 				       &main_prog->line_info,
6307 				       &main_prog->line_info_cnt,
6308 				       &main_prog->line_info_rec_size);
6309 	if (err) {
6310 		if (err != -ENOENT) {
6311 			pr_warn("prog '%s': error relocating .BTF.ext line info: %s\n",
6312 				prog->name, errstr(err));
6313 			return err;
6314 		}
6315 		if (main_prog->line_info) {
6316 			/*
6317 			 * Some info has already been found but has problem
6318 			 * in the last btf_ext reloc. Must have to error out.
6319 			 */
6320 			pr_warn("prog '%s': missing .BTF.ext line info.\n", prog->name);
6321 			return err;
6322 		}
6323 		/* Have problem loading the very first info. Ignore the rest. */
6324 		pr_warn("prog '%s': missing .BTF.ext line info for the main program, skipping all of .BTF.ext line info.\n",
6325 			prog->name);
6326 	}
6327 	return 0;
6328 }
6329 
6330 static int cmp_relo_by_insn_idx(const void *key, const void *elem)
6331 {
6332 	size_t insn_idx = *(const size_t *)key;
6333 	const struct reloc_desc *relo = elem;
6334 
6335 	if (insn_idx == relo->insn_idx)
6336 		return 0;
6337 	return insn_idx < relo->insn_idx ? -1 : 1;
6338 }
6339 
6340 static struct reloc_desc *find_prog_insn_relo(const struct bpf_program *prog, size_t insn_idx)
6341 {
6342 	if (!prog->nr_reloc)
6343 		return NULL;
6344 	return bsearch(&insn_idx, prog->reloc_desc, prog->nr_reloc,
6345 		       sizeof(*prog->reloc_desc), cmp_relo_by_insn_idx);
6346 }
6347 
6348 static int append_subprog_relos(struct bpf_program *main_prog, struct bpf_program *subprog)
6349 {
6350 	int new_cnt = main_prog->nr_reloc + subprog->nr_reloc;
6351 	struct reloc_desc *relos;
6352 	int i;
6353 
6354 	if (main_prog == subprog)
6355 		return 0;
6356 	relos = libbpf_reallocarray(main_prog->reloc_desc, new_cnt, sizeof(*relos));
6357 	/* if new count is zero, reallocarray can return a valid NULL result;
6358 	 * in this case the previous pointer will be freed, so we *have to*
6359 	 * reassign old pointer to the new value (even if it's NULL)
6360 	 */
6361 	if (!relos && new_cnt)
6362 		return -ENOMEM;
6363 	if (subprog->nr_reloc)
6364 		memcpy(relos + main_prog->nr_reloc, subprog->reloc_desc,
6365 		       sizeof(*relos) * subprog->nr_reloc);
6366 
6367 	for (i = main_prog->nr_reloc; i < new_cnt; i++)
6368 		relos[i].insn_idx += subprog->sub_insn_off;
6369 	/* After insn_idx adjustment the 'relos' array is still sorted
6370 	 * by insn_idx and doesn't break bsearch.
6371 	 */
6372 	main_prog->reloc_desc = relos;
6373 	main_prog->nr_reloc = new_cnt;
6374 	return 0;
6375 }
6376 
6377 static int
6378 bpf_object__append_subprog_code(struct bpf_object *obj, struct bpf_program *main_prog,
6379 				struct bpf_program *subprog)
6380 {
6381        struct bpf_insn *insns;
6382        size_t new_cnt;
6383        int err;
6384 
6385        subprog->sub_insn_off = main_prog->insns_cnt;
6386 
6387        new_cnt = main_prog->insns_cnt + subprog->insns_cnt;
6388        insns = libbpf_reallocarray(main_prog->insns, new_cnt, sizeof(*insns));
6389        if (!insns) {
6390                pr_warn("prog '%s': failed to realloc prog code\n", main_prog->name);
6391                return -ENOMEM;
6392        }
6393        main_prog->insns = insns;
6394        main_prog->insns_cnt = new_cnt;
6395 
6396        memcpy(main_prog->insns + subprog->sub_insn_off, subprog->insns,
6397               subprog->insns_cnt * sizeof(*insns));
6398 
6399        pr_debug("prog '%s': added %zu insns from sub-prog '%s'\n",
6400                 main_prog->name, subprog->insns_cnt, subprog->name);
6401 
6402        /* The subprog insns are now appended. Append its relos too. */
6403        err = append_subprog_relos(main_prog, subprog);
6404        if (err)
6405                return err;
6406        return 0;
6407 }
6408 
6409 static int
6410 bpf_object__reloc_code(struct bpf_object *obj, struct bpf_program *main_prog,
6411 		       struct bpf_program *prog)
6412 {
6413 	size_t sub_insn_idx, insn_idx;
6414 	struct bpf_program *subprog;
6415 	struct reloc_desc *relo;
6416 	struct bpf_insn *insn;
6417 	int err;
6418 
6419 	err = reloc_prog_func_and_line_info(obj, main_prog, prog);
6420 	if (err)
6421 		return err;
6422 
6423 	for (insn_idx = 0; insn_idx < prog->sec_insn_cnt; insn_idx++) {
6424 		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6425 		if (!insn_is_subprog_call(insn) && !insn_is_pseudo_func(insn))
6426 			continue;
6427 
6428 		relo = find_prog_insn_relo(prog, insn_idx);
6429 		if (relo && relo->type == RELO_EXTERN_CALL)
6430 			/* kfunc relocations will be handled later
6431 			 * in bpf_object__relocate_data()
6432 			 */
6433 			continue;
6434 		if (relo && relo->type != RELO_CALL && relo->type != RELO_SUBPROG_ADDR) {
6435 			pr_warn("prog '%s': unexpected relo for insn #%zu, type %d\n",
6436 				prog->name, insn_idx, relo->type);
6437 			return -LIBBPF_ERRNO__RELOC;
6438 		}
6439 		if (relo) {
6440 			/* sub-program instruction index is a combination of
6441 			 * an offset of a symbol pointed to by relocation and
6442 			 * call instruction's imm field; for global functions,
6443 			 * call always has imm = -1, but for static functions
6444 			 * relocation is against STT_SECTION and insn->imm
6445 			 * points to a start of a static function
6446 			 *
6447 			 * for subprog addr relocation, the relo->sym_off + insn->imm is
6448 			 * the byte offset in the corresponding section.
6449 			 */
6450 			if (relo->type == RELO_CALL)
6451 				sub_insn_idx = relo->sym_off / BPF_INSN_SZ + insn->imm + 1;
6452 			else
6453 				sub_insn_idx = (relo->sym_off + insn->imm) / BPF_INSN_SZ;
6454 		} else if (insn_is_pseudo_func(insn)) {
6455 			/*
6456 			 * RELO_SUBPROG_ADDR relo is always emitted even if both
6457 			 * functions are in the same section, so it shouldn't reach here.
6458 			 */
6459 			pr_warn("prog '%s': missing subprog addr relo for insn #%zu\n",
6460 				prog->name, insn_idx);
6461 			return -LIBBPF_ERRNO__RELOC;
6462 		} else {
6463 			/* if subprogram call is to a static function within
6464 			 * the same ELF section, there won't be any relocation
6465 			 * emitted, but it also means there is no additional
6466 			 * offset necessary, insns->imm is relative to
6467 			 * instruction's original position within the section
6468 			 */
6469 			sub_insn_idx = prog->sec_insn_off + insn_idx + insn->imm + 1;
6470 		}
6471 
6472 		/* we enforce that sub-programs should be in .text section */
6473 		subprog = find_prog_by_sec_insn(obj, obj->efile.text_shndx, sub_insn_idx);
6474 		if (!subprog) {
6475 			pr_warn("prog '%s': no .text section found yet sub-program call exists\n",
6476 				prog->name);
6477 			return -LIBBPF_ERRNO__RELOC;
6478 		}
6479 
6480 		/* if it's the first call instruction calling into this
6481 		 * subprogram (meaning this subprog hasn't been processed
6482 		 * yet) within the context of current main program:
6483 		 *   - append it at the end of main program's instructions blog;
6484 		 *   - process is recursively, while current program is put on hold;
6485 		 *   - if that subprogram calls some other not yet processes
6486 		 *   subprogram, same thing will happen recursively until
6487 		 *   there are no more unprocesses subprograms left to append
6488 		 *   and relocate.
6489 		 */
6490 		if (subprog->sub_insn_off == 0) {
6491 			err = bpf_object__append_subprog_code(obj, main_prog, subprog);
6492 			if (err)
6493 				return err;
6494 			err = bpf_object__reloc_code(obj, main_prog, subprog);
6495 			if (err)
6496 				return err;
6497 		}
6498 
6499 		/* main_prog->insns memory could have been re-allocated, so
6500 		 * calculate pointer again
6501 		 */
6502 		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6503 		/* calculate correct instruction position within current main
6504 		 * prog; each main prog can have a different set of
6505 		 * subprograms appended (potentially in different order as
6506 		 * well), so position of any subprog can be different for
6507 		 * different main programs
6508 		 */
6509 		insn->imm = subprog->sub_insn_off - (prog->sub_insn_off + insn_idx) - 1;
6510 
6511 		pr_debug("prog '%s': insn #%zu relocated, imm %d points to subprog '%s' (now at %zu offset)\n",
6512 			 prog->name, insn_idx, insn->imm, subprog->name, subprog->sub_insn_off);
6513 	}
6514 
6515 	return 0;
6516 }
6517 
6518 /*
6519  * Relocate sub-program calls.
6520  *
6521  * Algorithm operates as follows. Each entry-point BPF program (referred to as
6522  * main prog) is processed separately. For each subprog (non-entry functions,
6523  * that can be called from either entry progs or other subprogs) gets their
6524  * sub_insn_off reset to zero. This serves as indicator that this subprogram
6525  * hasn't been yet appended and relocated within current main prog. Once its
6526  * relocated, sub_insn_off will point at the position within current main prog
6527  * where given subprog was appended. This will further be used to relocate all
6528  * the call instructions jumping into this subprog.
6529  *
6530  * We start with main program and process all call instructions. If the call
6531  * is into a subprog that hasn't been processed (i.e., subprog->sub_insn_off
6532  * is zero), subprog instructions are appended at the end of main program's
6533  * instruction array. Then main program is "put on hold" while we recursively
6534  * process newly appended subprogram. If that subprogram calls into another
6535  * subprogram that hasn't been appended, new subprogram is appended again to
6536  * the *main* prog's instructions (subprog's instructions are always left
6537  * untouched, as they need to be in unmodified state for subsequent main progs
6538  * and subprog instructions are always sent only as part of a main prog) and
6539  * the process continues recursively. Once all the subprogs called from a main
6540  * prog or any of its subprogs are appended (and relocated), all their
6541  * positions within finalized instructions array are known, so it's easy to
6542  * rewrite call instructions with correct relative offsets, corresponding to
6543  * desired target subprog.
6544  *
6545  * Its important to realize that some subprogs might not be called from some
6546  * main prog and any of its called/used subprogs. Those will keep their
6547  * subprog->sub_insn_off as zero at all times and won't be appended to current
6548  * main prog and won't be relocated within the context of current main prog.
6549  * They might still be used from other main progs later.
6550  *
6551  * Visually this process can be shown as below. Suppose we have two main
6552  * programs mainA and mainB and BPF object contains three subprogs: subA,
6553  * subB, and subC. mainA calls only subA, mainB calls only subC, but subA and
6554  * subC both call subB:
6555  *
6556  *        +--------+ +-------+
6557  *        |        v v       |
6558  *     +--+---+ +--+-+-+ +---+--+
6559  *     | subA | | subB | | subC |
6560  *     +--+---+ +------+ +---+--+
6561  *        ^                  ^
6562  *        |                  |
6563  *    +---+-------+   +------+----+
6564  *    |   mainA   |   |   mainB   |
6565  *    +-----------+   +-----------+
6566  *
6567  * We'll start relocating mainA, will find subA, append it and start
6568  * processing sub A recursively:
6569  *
6570  *    +-----------+------+
6571  *    |   mainA   | subA |
6572  *    +-----------+------+
6573  *
6574  * At this point we notice that subB is used from subA, so we append it and
6575  * relocate (there are no further subcalls from subB):
6576  *
6577  *    +-----------+------+------+
6578  *    |   mainA   | subA | subB |
6579  *    +-----------+------+------+
6580  *
6581  * At this point, we relocate subA calls, then go one level up and finish with
6582  * relocatin mainA calls. mainA is done.
6583  *
6584  * For mainB process is similar but results in different order. We start with
6585  * mainB and skip subA and subB, as mainB never calls them (at least
6586  * directly), but we see subC is needed, so we append and start processing it:
6587  *
6588  *    +-----------+------+
6589  *    |   mainB   | subC |
6590  *    +-----------+------+
6591  * Now we see subC needs subB, so we go back to it, append and relocate it:
6592  *
6593  *    +-----------+------+------+
6594  *    |   mainB   | subC | subB |
6595  *    +-----------+------+------+
6596  *
6597  * At this point we unwind recursion, relocate calls in subC, then in mainB.
6598  */
6599 static int
6600 bpf_object__relocate_calls(struct bpf_object *obj, struct bpf_program *prog)
6601 {
6602 	struct bpf_program *subprog;
6603 	int i, err;
6604 
6605 	/* mark all subprogs as not relocated (yet) within the context of
6606 	 * current main program
6607 	 */
6608 	for (i = 0; i < obj->nr_programs; i++) {
6609 		subprog = &obj->programs[i];
6610 		if (!prog_is_subprog(obj, subprog))
6611 			continue;
6612 
6613 		subprog->sub_insn_off = 0;
6614 	}
6615 
6616 	err = bpf_object__reloc_code(obj, prog, prog);
6617 	if (err)
6618 		return err;
6619 
6620 	return 0;
6621 }
6622 
6623 static void
6624 bpf_object__free_relocs(struct bpf_object *obj)
6625 {
6626 	struct bpf_program *prog;
6627 	int i;
6628 
6629 	/* free up relocation descriptors */
6630 	for (i = 0; i < obj->nr_programs; i++) {
6631 		prog = &obj->programs[i];
6632 		zfree(&prog->reloc_desc);
6633 		prog->nr_reloc = 0;
6634 	}
6635 }
6636 
6637 static int cmp_relocs(const void *_a, const void *_b)
6638 {
6639 	const struct reloc_desc *a = _a;
6640 	const struct reloc_desc *b = _b;
6641 
6642 	if (a->insn_idx != b->insn_idx)
6643 		return a->insn_idx < b->insn_idx ? -1 : 1;
6644 
6645 	/* no two relocations should have the same insn_idx, but ... */
6646 	if (a->type != b->type)
6647 		return a->type < b->type ? -1 : 1;
6648 
6649 	return 0;
6650 }
6651 
6652 static void bpf_object__sort_relos(struct bpf_object *obj)
6653 {
6654 	int i;
6655 
6656 	for (i = 0; i < obj->nr_programs; i++) {
6657 		struct bpf_program *p = &obj->programs[i];
6658 
6659 		if (!p->nr_reloc)
6660 			continue;
6661 
6662 		qsort(p->reloc_desc, p->nr_reloc, sizeof(*p->reloc_desc), cmp_relocs);
6663 	}
6664 }
6665 
6666 static int bpf_prog_assign_exc_cb(struct bpf_object *obj, struct bpf_program *prog)
6667 {
6668 	const char *str = "exception_callback:";
6669 	size_t pfx_len = strlen(str);
6670 	int i, j, n;
6671 
6672 	if (!obj->btf || !kernel_supports(obj, FEAT_BTF_DECL_TAG))
6673 		return 0;
6674 
6675 	n = btf__type_cnt(obj->btf);
6676 	for (i = 1; i < n; i++) {
6677 		const char *name;
6678 		struct btf_type *t;
6679 
6680 		t = btf_type_by_id(obj->btf, i);
6681 		if (!btf_is_decl_tag(t) || btf_decl_tag(t)->component_idx != -1)
6682 			continue;
6683 
6684 		name = btf__str_by_offset(obj->btf, t->name_off);
6685 		if (strncmp(name, str, pfx_len) != 0)
6686 			continue;
6687 
6688 		t = btf_type_by_id(obj->btf, t->type);
6689 		if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL) {
6690 			pr_warn("prog '%s': exception_callback:<value> decl tag not applied to the main program\n",
6691 				prog->name);
6692 			return -EINVAL;
6693 		}
6694 		if (strcmp(prog->name, btf__str_by_offset(obj->btf, t->name_off)) != 0)
6695 			continue;
6696 		/* Multiple callbacks are specified for the same prog,
6697 		 * the verifier will eventually return an error for this
6698 		 * case, hence simply skip appending a subprog.
6699 		 */
6700 		if (prog->exception_cb_idx >= 0) {
6701 			prog->exception_cb_idx = -1;
6702 			break;
6703 		}
6704 
6705 		name += pfx_len;
6706 		if (str_is_empty(name)) {
6707 			pr_warn("prog '%s': exception_callback:<value> decl tag contains empty value\n",
6708 				prog->name);
6709 			return -EINVAL;
6710 		}
6711 
6712 		for (j = 0; j < obj->nr_programs; j++) {
6713 			struct bpf_program *subprog = &obj->programs[j];
6714 
6715 			if (!prog_is_subprog(obj, subprog))
6716 				continue;
6717 			if (strcmp(name, subprog->name) != 0)
6718 				continue;
6719 			/* Enforce non-hidden, as from verifier point of
6720 			 * view it expects global functions, whereas the
6721 			 * mark_btf_static fixes up linkage as static.
6722 			 */
6723 			if (!subprog->sym_global || subprog->mark_btf_static) {
6724 				pr_warn("prog '%s': exception callback %s must be a global non-hidden function\n",
6725 					prog->name, subprog->name);
6726 				return -EINVAL;
6727 			}
6728 			/* Let's see if we already saw a static exception callback with the same name */
6729 			if (prog->exception_cb_idx >= 0) {
6730 				pr_warn("prog '%s': multiple subprogs with same name as exception callback '%s'\n",
6731 					prog->name, subprog->name);
6732 				return -EINVAL;
6733 			}
6734 			prog->exception_cb_idx = j;
6735 			break;
6736 		}
6737 
6738 		if (prog->exception_cb_idx >= 0)
6739 			continue;
6740 
6741 		pr_warn("prog '%s': cannot find exception callback '%s'\n", prog->name, name);
6742 		return -ENOENT;
6743 	}
6744 
6745 	return 0;
6746 }
6747 
6748 static struct {
6749 	enum bpf_prog_type prog_type;
6750 	const char *ctx_name;
6751 } global_ctx_map[] = {
6752 	{ BPF_PROG_TYPE_CGROUP_DEVICE,           "bpf_cgroup_dev_ctx" },
6753 	{ BPF_PROG_TYPE_CGROUP_SKB,              "__sk_buff" },
6754 	{ BPF_PROG_TYPE_CGROUP_SOCK,             "bpf_sock" },
6755 	{ BPF_PROG_TYPE_CGROUP_SOCK_ADDR,        "bpf_sock_addr" },
6756 	{ BPF_PROG_TYPE_CGROUP_SOCKOPT,          "bpf_sockopt" },
6757 	{ BPF_PROG_TYPE_CGROUP_SYSCTL,           "bpf_sysctl" },
6758 	{ BPF_PROG_TYPE_FLOW_DISSECTOR,          "__sk_buff" },
6759 	{ BPF_PROG_TYPE_KPROBE,                  "bpf_user_pt_regs_t" },
6760 	{ BPF_PROG_TYPE_LWT_IN,                  "__sk_buff" },
6761 	{ BPF_PROG_TYPE_LWT_OUT,                 "__sk_buff" },
6762 	{ BPF_PROG_TYPE_LWT_SEG6LOCAL,           "__sk_buff" },
6763 	{ BPF_PROG_TYPE_LWT_XMIT,                "__sk_buff" },
6764 	{ BPF_PROG_TYPE_NETFILTER,               "bpf_nf_ctx" },
6765 	{ BPF_PROG_TYPE_PERF_EVENT,              "bpf_perf_event_data" },
6766 	{ BPF_PROG_TYPE_RAW_TRACEPOINT,          "bpf_raw_tracepoint_args" },
6767 	{ BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE, "bpf_raw_tracepoint_args" },
6768 	{ BPF_PROG_TYPE_SCHED_ACT,               "__sk_buff" },
6769 	{ BPF_PROG_TYPE_SCHED_CLS,               "__sk_buff" },
6770 	{ BPF_PROG_TYPE_SK_LOOKUP,               "bpf_sk_lookup" },
6771 	{ BPF_PROG_TYPE_SK_MSG,                  "sk_msg_md" },
6772 	{ BPF_PROG_TYPE_SK_REUSEPORT,            "sk_reuseport_md" },
6773 	{ BPF_PROG_TYPE_SK_SKB,                  "__sk_buff" },
6774 	{ BPF_PROG_TYPE_SOCK_OPS,                "bpf_sock_ops" },
6775 	{ BPF_PROG_TYPE_SOCKET_FILTER,           "__sk_buff" },
6776 	{ BPF_PROG_TYPE_XDP,                     "xdp_md" },
6777 	/* all other program types don't have "named" context structs */
6778 };
6779 
6780 /* forward declarations for arch-specific underlying types of bpf_user_pt_regs_t typedef,
6781  * for below __builtin_types_compatible_p() checks;
6782  * with this approach we don't need any extra arch-specific #ifdef guards
6783  */
6784 struct pt_regs;
6785 struct user_pt_regs;
6786 struct user_regs_struct;
6787 
6788 static bool need_func_arg_type_fixup(const struct btf *btf, const struct bpf_program *prog,
6789 				     const char *subprog_name, int arg_idx,
6790 				     int arg_type_id, const char *ctx_name)
6791 {
6792 	const struct btf_type *t;
6793 	const char *tname;
6794 
6795 	/* check if existing parameter already matches verifier expectations */
6796 	t = skip_mods_and_typedefs(btf, arg_type_id, NULL);
6797 	if (!btf_is_ptr(t))
6798 		goto out_warn;
6799 
6800 	/* typedef bpf_user_pt_regs_t is a special PITA case, valid for kprobe
6801 	 * and perf_event programs, so check this case early on and forget
6802 	 * about it for subsequent checks
6803 	 */
6804 	while (btf_is_mod(t))
6805 		t = btf__type_by_id(btf, t->type);
6806 	if (btf_is_typedef(t) &&
6807 	    (prog->type == BPF_PROG_TYPE_KPROBE || prog->type == BPF_PROG_TYPE_PERF_EVENT)) {
6808 		tname = btf__str_by_offset(btf, t->name_off) ?: "<anon>";
6809 		if (strcmp(tname, "bpf_user_pt_regs_t") == 0)
6810 			return false; /* canonical type for kprobe/perf_event */
6811 	}
6812 
6813 	/* now we can ignore typedefs moving forward */
6814 	t = skip_mods_and_typedefs(btf, t->type, NULL);
6815 
6816 	/* if it's `void *`, definitely fix up BTF info */
6817 	if (btf_is_void(t))
6818 		return true;
6819 
6820 	/* if it's already proper canonical type, no need to fix up */
6821 	tname = btf__str_by_offset(btf, t->name_off) ?: "<anon>";
6822 	if (btf_is_struct(t) && strcmp(tname, ctx_name) == 0)
6823 		return false;
6824 
6825 	/* special cases */
6826 	switch (prog->type) {
6827 	case BPF_PROG_TYPE_KPROBE:
6828 		/* `struct pt_regs *` is expected, but we need to fix up */
6829 		if (btf_is_struct(t) && strcmp(tname, "pt_regs") == 0)
6830 			return true;
6831 		break;
6832 	case BPF_PROG_TYPE_PERF_EVENT:
6833 		if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct pt_regs) &&
6834 		    btf_is_struct(t) && strcmp(tname, "pt_regs") == 0)
6835 			return true;
6836 		if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct user_pt_regs) &&
6837 		    btf_is_struct(t) && strcmp(tname, "user_pt_regs") == 0)
6838 			return true;
6839 		if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct user_regs_struct) &&
6840 		    btf_is_struct(t) && strcmp(tname, "user_regs_struct") == 0)
6841 			return true;
6842 		break;
6843 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
6844 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
6845 		/* allow u64* as ctx */
6846 		if (btf_is_int(t) && t->size == 8)
6847 			return true;
6848 		break;
6849 	default:
6850 		break;
6851 	}
6852 
6853 out_warn:
6854 	pr_warn("prog '%s': subprog '%s' arg#%d is expected to be of `struct %s *` type\n",
6855 		prog->name, subprog_name, arg_idx, ctx_name);
6856 	return false;
6857 }
6858 
6859 static int clone_func_btf_info(struct btf *btf, int orig_fn_id, struct bpf_program *prog)
6860 {
6861 	int fn_id, fn_proto_id, ret_type_id, orig_proto_id;
6862 	int i, err, arg_cnt, fn_name_off, linkage;
6863 	struct btf_type *fn_t, *fn_proto_t, *t;
6864 	struct btf_param *p;
6865 
6866 	/* caller already validated FUNC -> FUNC_PROTO validity */
6867 	fn_t = btf_type_by_id(btf, orig_fn_id);
6868 	fn_proto_t = btf_type_by_id(btf, fn_t->type);
6869 
6870 	/* Note that each btf__add_xxx() operation invalidates
6871 	 * all btf_type and string pointers, so we need to be
6872 	 * very careful when cloning BTF types. BTF type
6873 	 * pointers have to be always refetched. And to avoid
6874 	 * problems with invalidated string pointers, we
6875 	 * add empty strings initially, then just fix up
6876 	 * name_off offsets in place. Offsets are stable for
6877 	 * existing strings, so that works out.
6878 	 */
6879 	fn_name_off = fn_t->name_off; /* we are about to invalidate fn_t */
6880 	linkage = btf_func_linkage(fn_t);
6881 	orig_proto_id = fn_t->type; /* original FUNC_PROTO ID */
6882 	ret_type_id = fn_proto_t->type; /* fn_proto_t will be invalidated */
6883 	arg_cnt = btf_vlen(fn_proto_t);
6884 
6885 	/* clone FUNC_PROTO and its params */
6886 	fn_proto_id = btf__add_func_proto(btf, ret_type_id);
6887 	if (fn_proto_id < 0)
6888 		return -EINVAL;
6889 
6890 	for (i = 0; i < arg_cnt; i++) {
6891 		int name_off;
6892 
6893 		/* copy original parameter data */
6894 		t = btf_type_by_id(btf, orig_proto_id);
6895 		p = &btf_params(t)[i];
6896 		name_off = p->name_off;
6897 
6898 		err = btf__add_func_param(btf, "", p->type);
6899 		if (err)
6900 			return err;
6901 
6902 		fn_proto_t = btf_type_by_id(btf, fn_proto_id);
6903 		p = &btf_params(fn_proto_t)[i];
6904 		p->name_off = name_off; /* use remembered str offset */
6905 	}
6906 
6907 	/* clone FUNC now, btf__add_func() enforces non-empty name, so use
6908 	 * entry program's name as a placeholder, which we replace immediately
6909 	 * with original name_off
6910 	 */
6911 	fn_id = btf__add_func(btf, prog->name, linkage, fn_proto_id);
6912 	if (fn_id < 0)
6913 		return -EINVAL;
6914 
6915 	fn_t = btf_type_by_id(btf, fn_id);
6916 	fn_t->name_off = fn_name_off; /* reuse original string */
6917 
6918 	return fn_id;
6919 }
6920 
6921 /* Check if main program or global subprog's function prototype has `arg:ctx`
6922  * argument tags, and, if necessary, substitute correct type to match what BPF
6923  * verifier would expect, taking into account specific program type. This
6924  * allows to support __arg_ctx tag transparently on old kernels that don't yet
6925  * have a native support for it in the verifier, making user's life much
6926  * easier.
6927  */
6928 static int bpf_program_fixup_func_info(struct bpf_object *obj, struct bpf_program *prog)
6929 {
6930 	const char *ctx_name = NULL, *ctx_tag = "arg:ctx", *fn_name;
6931 	struct bpf_func_info_min *func_rec;
6932 	struct btf_type *fn_t, *fn_proto_t;
6933 	struct btf *btf = obj->btf;
6934 	const struct btf_type *t;
6935 	struct btf_param *p;
6936 	int ptr_id = 0, struct_id, tag_id, orig_fn_id;
6937 	int i, n, arg_idx, arg_cnt, err, rec_idx;
6938 	int *orig_ids;
6939 
6940 	/* no .BTF.ext, no problem */
6941 	if (!obj->btf_ext || !prog->func_info)
6942 		return 0;
6943 
6944 	/* don't do any fix ups if kernel natively supports __arg_ctx */
6945 	if (kernel_supports(obj, FEAT_ARG_CTX_TAG))
6946 		return 0;
6947 
6948 	/* some BPF program types just don't have named context structs, so
6949 	 * this fallback mechanism doesn't work for them
6950 	 */
6951 	for (i = 0; i < ARRAY_SIZE(global_ctx_map); i++) {
6952 		if (global_ctx_map[i].prog_type != prog->type)
6953 			continue;
6954 		ctx_name = global_ctx_map[i].ctx_name;
6955 		break;
6956 	}
6957 	if (!ctx_name)
6958 		return 0;
6959 
6960 	/* remember original func BTF IDs to detect if we already cloned them */
6961 	orig_ids = calloc(prog->func_info_cnt, sizeof(*orig_ids));
6962 	if (!orig_ids)
6963 		return -ENOMEM;
6964 	for (i = 0; i < prog->func_info_cnt; i++) {
6965 		func_rec = prog->func_info + prog->func_info_rec_size * i;
6966 		orig_ids[i] = func_rec->type_id;
6967 	}
6968 
6969 	/* go through each DECL_TAG with "arg:ctx" and see if it points to one
6970 	 * of our subprogs; if yes and subprog is global and needs adjustment,
6971 	 * clone and adjust FUNC -> FUNC_PROTO combo
6972 	 */
6973 	for (i = 1, n = btf__type_cnt(btf); i < n; i++) {
6974 		/* only DECL_TAG with "arg:ctx" value are interesting */
6975 		t = btf__type_by_id(btf, i);
6976 		if (!btf_is_decl_tag(t))
6977 			continue;
6978 		if (strcmp(btf__str_by_offset(btf, t->name_off), ctx_tag) != 0)
6979 			continue;
6980 
6981 		/* only global funcs need adjustment, if at all */
6982 		orig_fn_id = t->type;
6983 		fn_t = btf_type_by_id(btf, orig_fn_id);
6984 		if (!btf_is_func(fn_t) || btf_func_linkage(fn_t) != BTF_FUNC_GLOBAL)
6985 			continue;
6986 
6987 		/* sanity check FUNC -> FUNC_PROTO chain, just in case */
6988 		fn_proto_t = btf_type_by_id(btf, fn_t->type);
6989 		if (!fn_proto_t || !btf_is_func_proto(fn_proto_t))
6990 			continue;
6991 
6992 		/* find corresponding func_info record */
6993 		func_rec = NULL;
6994 		for (rec_idx = 0; rec_idx < prog->func_info_cnt; rec_idx++) {
6995 			if (orig_ids[rec_idx] == t->type) {
6996 				func_rec = prog->func_info + prog->func_info_rec_size * rec_idx;
6997 				break;
6998 			}
6999 		}
7000 		/* current main program doesn't call into this subprog */
7001 		if (!func_rec)
7002 			continue;
7003 
7004 		/* some more sanity checking of DECL_TAG */
7005 		arg_cnt = btf_vlen(fn_proto_t);
7006 		arg_idx = btf_decl_tag(t)->component_idx;
7007 		if (arg_idx < 0 || arg_idx >= arg_cnt)
7008 			continue;
7009 
7010 		/* check if we should fix up argument type */
7011 		p = &btf_params(fn_proto_t)[arg_idx];
7012 		fn_name = btf__str_by_offset(btf, fn_t->name_off) ?: "<anon>";
7013 		if (!need_func_arg_type_fixup(btf, prog, fn_name, arg_idx, p->type, ctx_name))
7014 			continue;
7015 
7016 		/* clone fn/fn_proto, unless we already did it for another arg */
7017 		if (func_rec->type_id == orig_fn_id) {
7018 			int fn_id;
7019 
7020 			fn_id = clone_func_btf_info(btf, orig_fn_id, prog);
7021 			if (fn_id < 0) {
7022 				err = fn_id;
7023 				goto err_out;
7024 			}
7025 
7026 			/* point func_info record to a cloned FUNC type */
7027 			func_rec->type_id = fn_id;
7028 		}
7029 
7030 		/* create PTR -> STRUCT type chain to mark PTR_TO_CTX argument;
7031 		 * we do it just once per main BPF program, as all global
7032 		 * funcs share the same program type, so need only PTR ->
7033 		 * STRUCT type chain
7034 		 */
7035 		if (ptr_id == 0) {
7036 			struct_id = btf__add_struct(btf, ctx_name, 0);
7037 			ptr_id = btf__add_ptr(btf, struct_id);
7038 			if (ptr_id < 0 || struct_id < 0) {
7039 				err = -EINVAL;
7040 				goto err_out;
7041 			}
7042 		}
7043 
7044 		/* for completeness, clone DECL_TAG and point it to cloned param */
7045 		tag_id = btf__add_decl_tag(btf, ctx_tag, func_rec->type_id, arg_idx);
7046 		if (tag_id < 0) {
7047 			err = -EINVAL;
7048 			goto err_out;
7049 		}
7050 
7051 		/* all the BTF manipulations invalidated pointers, refetch them */
7052 		fn_t = btf_type_by_id(btf, func_rec->type_id);
7053 		fn_proto_t = btf_type_by_id(btf, fn_t->type);
7054 
7055 		/* fix up type ID pointed to by param */
7056 		p = &btf_params(fn_proto_t)[arg_idx];
7057 		p->type = ptr_id;
7058 	}
7059 
7060 	free(orig_ids);
7061 	return 0;
7062 err_out:
7063 	free(orig_ids);
7064 	return err;
7065 }
7066 
7067 static int bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
7068 {
7069 	struct bpf_program *prog;
7070 	size_t i, j;
7071 	int err;
7072 
7073 	if (obj->btf_ext) {
7074 		err = bpf_object__relocate_core(obj, targ_btf_path);
7075 		if (err) {
7076 			pr_warn("failed to perform CO-RE relocations: %s\n",
7077 				errstr(err));
7078 			return err;
7079 		}
7080 		bpf_object__sort_relos(obj);
7081 	}
7082 
7083 	/* Before relocating calls pre-process relocations and mark
7084 	 * few ld_imm64 instructions that points to subprogs.
7085 	 * Otherwise bpf_object__reloc_code() later would have to consider
7086 	 * all ld_imm64 insns as relocation candidates. That would
7087 	 * reduce relocation speed, since amount of find_prog_insn_relo()
7088 	 * would increase and most of them will fail to find a relo.
7089 	 */
7090 	for (i = 0; i < obj->nr_programs; i++) {
7091 		prog = &obj->programs[i];
7092 		for (j = 0; j < prog->nr_reloc; j++) {
7093 			struct reloc_desc *relo = &prog->reloc_desc[j];
7094 			struct bpf_insn *insn = &prog->insns[relo->insn_idx];
7095 
7096 			/* mark the insn, so it's recognized by insn_is_pseudo_func() */
7097 			if (relo->type == RELO_SUBPROG_ADDR)
7098 				insn[0].src_reg = BPF_PSEUDO_FUNC;
7099 		}
7100 	}
7101 
7102 	/* relocate subprogram calls and append used subprograms to main
7103 	 * programs; each copy of subprogram code needs to be relocated
7104 	 * differently for each main program, because its code location might
7105 	 * have changed.
7106 	 * Append subprog relos to main programs to allow data relos to be
7107 	 * processed after text is completely relocated.
7108 	 */
7109 	for (i = 0; i < obj->nr_programs; i++) {
7110 		prog = &obj->programs[i];
7111 		/* sub-program's sub-calls are relocated within the context of
7112 		 * its main program only
7113 		 */
7114 		if (prog_is_subprog(obj, prog))
7115 			continue;
7116 		if (!prog->autoload)
7117 			continue;
7118 
7119 		err = bpf_object__relocate_calls(obj, prog);
7120 		if (err) {
7121 			pr_warn("prog '%s': failed to relocate calls: %s\n",
7122 				prog->name, errstr(err));
7123 			return err;
7124 		}
7125 
7126 		err = bpf_prog_assign_exc_cb(obj, prog);
7127 		if (err)
7128 			return err;
7129 		/* Now, also append exception callback if it has not been done already. */
7130 		if (prog->exception_cb_idx >= 0) {
7131 			struct bpf_program *subprog = &obj->programs[prog->exception_cb_idx];
7132 
7133 			/* Calling exception callback directly is disallowed, which the
7134 			 * verifier will reject later. In case it was processed already,
7135 			 * we can skip this step, otherwise for all other valid cases we
7136 			 * have to append exception callback now.
7137 			 */
7138 			if (subprog->sub_insn_off == 0) {
7139 				err = bpf_object__append_subprog_code(obj, prog, subprog);
7140 				if (err)
7141 					return err;
7142 				err = bpf_object__reloc_code(obj, prog, subprog);
7143 				if (err)
7144 					return err;
7145 			}
7146 		}
7147 	}
7148 	for (i = 0; i < obj->nr_programs; i++) {
7149 		prog = &obj->programs[i];
7150 		if (prog_is_subprog(obj, prog))
7151 			continue;
7152 		if (!prog->autoload)
7153 			continue;
7154 
7155 		/* Process data relos for main programs */
7156 		err = bpf_object__relocate_data(obj, prog);
7157 		if (err) {
7158 			pr_warn("prog '%s': failed to relocate data references: %s\n",
7159 				prog->name, errstr(err));
7160 			return err;
7161 		}
7162 
7163 		/* Fix up .BTF.ext information, if necessary */
7164 		err = bpf_program_fixup_func_info(obj, prog);
7165 		if (err) {
7166 			pr_warn("prog '%s': failed to perform .BTF.ext fix ups: %s\n",
7167 				prog->name, errstr(err));
7168 			return err;
7169 		}
7170 	}
7171 
7172 	return 0;
7173 }
7174 
7175 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
7176 					    Elf64_Shdr *shdr, Elf_Data *data);
7177 
7178 static int bpf_object__collect_map_relos(struct bpf_object *obj,
7179 					 Elf64_Shdr *shdr, Elf_Data *data)
7180 {
7181 	const int bpf_ptr_sz = 8, host_ptr_sz = sizeof(void *);
7182 	int i, j, nrels, new_sz;
7183 	const struct btf_var_secinfo *vi = NULL;
7184 	const struct btf_type *sec, *var, *def;
7185 	struct bpf_map *map = NULL, *targ_map = NULL;
7186 	struct bpf_program *targ_prog = NULL;
7187 	bool is_prog_array, is_map_in_map;
7188 	const struct btf_member *member;
7189 	const char *name, *mname, *type;
7190 	unsigned int moff;
7191 	Elf64_Sym *sym;
7192 	Elf64_Rel *rel;
7193 	void *tmp;
7194 
7195 	if (!obj->efile.btf_maps_sec_btf_id || !obj->btf)
7196 		return -EINVAL;
7197 	sec = btf__type_by_id(obj->btf, obj->efile.btf_maps_sec_btf_id);
7198 	if (!sec)
7199 		return -EINVAL;
7200 
7201 	nrels = shdr->sh_size / shdr->sh_entsize;
7202 	for (i = 0; i < nrels; i++) {
7203 		rel = elf_rel_by_idx(data, i);
7204 		if (!rel) {
7205 			pr_warn(".maps relo #%d: failed to get ELF relo\n", i);
7206 			return -LIBBPF_ERRNO__FORMAT;
7207 		}
7208 
7209 		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
7210 		if (!sym) {
7211 			pr_warn(".maps relo #%d: symbol %zx not found\n",
7212 				i, (size_t)ELF64_R_SYM(rel->r_info));
7213 			return -LIBBPF_ERRNO__FORMAT;
7214 		}
7215 		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
7216 
7217 		pr_debug(".maps relo #%d: for %zd value %zd rel->r_offset %zu name %d ('%s')\n",
7218 			 i, (ssize_t)(rel->r_info >> 32), (size_t)sym->st_value,
7219 			 (size_t)rel->r_offset, sym->st_name, name);
7220 
7221 		for (j = 0; j < obj->nr_maps; j++) {
7222 			map = &obj->maps[j];
7223 			if (map->sec_idx != obj->efile.btf_maps_shndx)
7224 				continue;
7225 
7226 			vi = btf_var_secinfos(sec) + map->btf_var_idx;
7227 			if (vi->offset <= rel->r_offset &&
7228 			    rel->r_offset + bpf_ptr_sz <= vi->offset + vi->size)
7229 				break;
7230 		}
7231 		if (j == obj->nr_maps) {
7232 			pr_warn(".maps relo #%d: cannot find map '%s' at rel->r_offset %zu\n",
7233 				i, name, (size_t)rel->r_offset);
7234 			return -EINVAL;
7235 		}
7236 
7237 		is_map_in_map = bpf_map_type__is_map_in_map(map->def.type);
7238 		is_prog_array = map->def.type == BPF_MAP_TYPE_PROG_ARRAY;
7239 		type = is_map_in_map ? "map" : "prog";
7240 		if (is_map_in_map) {
7241 			if (sym->st_shndx != obj->efile.btf_maps_shndx) {
7242 				pr_warn(".maps relo #%d: '%s' isn't a BTF-defined map\n",
7243 					i, name);
7244 				return -LIBBPF_ERRNO__RELOC;
7245 			}
7246 			if (map->def.type == BPF_MAP_TYPE_HASH_OF_MAPS &&
7247 			    map->def.key_size != sizeof(int)) {
7248 				pr_warn(".maps relo #%d: hash-of-maps '%s' should have key size %zu.\n",
7249 					i, map->name, sizeof(int));
7250 				return -EINVAL;
7251 			}
7252 			targ_map = bpf_object__find_map_by_name(obj, name);
7253 			if (!targ_map) {
7254 				pr_warn(".maps relo #%d: '%s' isn't a valid map reference\n",
7255 					i, name);
7256 				return -ESRCH;
7257 			}
7258 		} else if (is_prog_array) {
7259 			targ_prog = bpf_object__find_program_by_name(obj, name);
7260 			if (!targ_prog) {
7261 				pr_warn(".maps relo #%d: '%s' isn't a valid program reference\n",
7262 					i, name);
7263 				return -ESRCH;
7264 			}
7265 			if (targ_prog->sec_idx != sym->st_shndx ||
7266 			    targ_prog->sec_insn_off * 8 != sym->st_value ||
7267 			    prog_is_subprog(obj, targ_prog)) {
7268 				pr_warn(".maps relo #%d: '%s' isn't an entry-point program\n",
7269 					i, name);
7270 				return -LIBBPF_ERRNO__RELOC;
7271 			}
7272 		} else {
7273 			return -EINVAL;
7274 		}
7275 
7276 		var = btf__type_by_id(obj->btf, vi->type);
7277 		def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
7278 		if (btf_vlen(def) == 0)
7279 			return -EINVAL;
7280 		member = btf_members(def) + btf_vlen(def) - 1;
7281 		mname = btf__name_by_offset(obj->btf, member->name_off);
7282 		if (strcmp(mname, "values"))
7283 			return -EINVAL;
7284 
7285 		moff = btf_member_bit_offset(def, btf_vlen(def) - 1) / 8;
7286 		if (rel->r_offset - vi->offset < moff)
7287 			return -EINVAL;
7288 
7289 		moff = rel->r_offset - vi->offset - moff;
7290 		/* here we use BPF pointer size, which is always 64 bit, as we
7291 		 * are parsing ELF that was built for BPF target
7292 		 */
7293 		if (moff % bpf_ptr_sz)
7294 			return -EINVAL;
7295 		moff /= bpf_ptr_sz;
7296 		if (moff >= map->init_slots_sz) {
7297 			new_sz = moff + 1;
7298 			tmp = libbpf_reallocarray(map->init_slots, new_sz, host_ptr_sz);
7299 			if (!tmp)
7300 				return -ENOMEM;
7301 			map->init_slots = tmp;
7302 			memset(map->init_slots + map->init_slots_sz, 0,
7303 			       (new_sz - map->init_slots_sz) * host_ptr_sz);
7304 			map->init_slots_sz = new_sz;
7305 		}
7306 		map->init_slots[moff] = is_map_in_map ? (void *)targ_map : (void *)targ_prog;
7307 
7308 		pr_debug(".maps relo #%d: map '%s' slot [%d] points to %s '%s'\n",
7309 			 i, map->name, moff, type, name);
7310 	}
7311 
7312 	return 0;
7313 }
7314 
7315 static int bpf_object__collect_relos(struct bpf_object *obj)
7316 {
7317 	int i, err;
7318 
7319 	for (i = 0; i < obj->efile.sec_cnt; i++) {
7320 		struct elf_sec_desc *sec_desc = &obj->efile.secs[i];
7321 		Elf64_Shdr *shdr;
7322 		Elf_Data *data;
7323 		int idx;
7324 
7325 		if (sec_desc->sec_type != SEC_RELO)
7326 			continue;
7327 
7328 		shdr = sec_desc->shdr;
7329 		data = sec_desc->data;
7330 		idx = shdr->sh_info;
7331 
7332 		if (shdr->sh_type != SHT_REL || idx < 0 || idx >= obj->efile.sec_cnt) {
7333 			pr_warn("internal error at %d\n", __LINE__);
7334 			return -LIBBPF_ERRNO__INTERNAL;
7335 		}
7336 
7337 		if (obj->efile.secs[idx].sec_type == SEC_ST_OPS)
7338 			err = bpf_object__collect_st_ops_relos(obj, shdr, data);
7339 		else if (idx == obj->efile.btf_maps_shndx)
7340 			err = bpf_object__collect_map_relos(obj, shdr, data);
7341 		else
7342 			err = bpf_object__collect_prog_relos(obj, shdr, data);
7343 		if (err)
7344 			return err;
7345 	}
7346 
7347 	bpf_object__sort_relos(obj);
7348 	return 0;
7349 }
7350 
7351 static bool insn_is_helper_call(struct bpf_insn *insn, enum bpf_func_id *func_id)
7352 {
7353 	if (BPF_CLASS(insn->code) == BPF_JMP &&
7354 	    BPF_OP(insn->code) == BPF_CALL &&
7355 	    BPF_SRC(insn->code) == BPF_K &&
7356 	    insn->src_reg == 0 &&
7357 	    insn->dst_reg == 0) {
7358 		    *func_id = insn->imm;
7359 		    return true;
7360 	}
7361 	return false;
7362 }
7363 
7364 static int bpf_object__sanitize_prog(struct bpf_object *obj, struct bpf_program *prog)
7365 {
7366 	struct bpf_insn *insn = prog->insns;
7367 	enum bpf_func_id func_id;
7368 	int i;
7369 
7370 	if (obj->gen_loader)
7371 		return 0;
7372 
7373 	for (i = 0; i < prog->insns_cnt; i++, insn++) {
7374 		if (!insn_is_helper_call(insn, &func_id))
7375 			continue;
7376 
7377 		/* on kernels that don't yet support
7378 		 * bpf_probe_read_{kernel,user}[_str] helpers, fall back
7379 		 * to bpf_probe_read() which works well for old kernels
7380 		 */
7381 		switch (func_id) {
7382 		case BPF_FUNC_probe_read_kernel:
7383 		case BPF_FUNC_probe_read_user:
7384 			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
7385 				insn->imm = BPF_FUNC_probe_read;
7386 			break;
7387 		case BPF_FUNC_probe_read_kernel_str:
7388 		case BPF_FUNC_probe_read_user_str:
7389 			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
7390 				insn->imm = BPF_FUNC_probe_read_str;
7391 			break;
7392 		default:
7393 			break;
7394 		}
7395 	}
7396 	return 0;
7397 }
7398 
7399 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
7400 				     int *btf_obj_fd, int *btf_type_id);
7401 
7402 /* this is called as prog->sec_def->prog_prepare_load_fn for libbpf-supported sec_defs */
7403 static int libbpf_prepare_prog_load(struct bpf_program *prog,
7404 				    struct bpf_prog_load_opts *opts, long cookie)
7405 {
7406 	enum sec_def_flags def = cookie;
7407 
7408 	/* old kernels might not support specifying expected_attach_type */
7409 	if ((def & SEC_EXP_ATTACH_OPT) && !kernel_supports(prog->obj, FEAT_EXP_ATTACH_TYPE))
7410 		opts->expected_attach_type = 0;
7411 
7412 	if (def & SEC_SLEEPABLE)
7413 		opts->prog_flags |= BPF_F_SLEEPABLE;
7414 
7415 	if (prog->type == BPF_PROG_TYPE_XDP && (def & SEC_XDP_FRAGS))
7416 		opts->prog_flags |= BPF_F_XDP_HAS_FRAGS;
7417 
7418 	/* special check for usdt to use uprobe_multi link */
7419 	if ((def & SEC_USDT) && kernel_supports(prog->obj, FEAT_UPROBE_MULTI_LINK)) {
7420 		/* for BPF_TRACE_UPROBE_MULTI, user might want to query expected_attach_type
7421 		 * in prog, and expected_attach_type we set in kernel is from opts, so we
7422 		 * update both.
7423 		 */
7424 		prog->expected_attach_type = BPF_TRACE_UPROBE_MULTI;
7425 		opts->expected_attach_type = BPF_TRACE_UPROBE_MULTI;
7426 	}
7427 
7428 	if ((def & SEC_ATTACH_BTF) && !prog->attach_btf_id) {
7429 		int btf_obj_fd = 0, btf_type_id = 0, err;
7430 		const char *attach_name;
7431 
7432 		attach_name = strchr(prog->sec_name, '/');
7433 		if (!attach_name) {
7434 			/* if BPF program is annotated with just SEC("fentry")
7435 			 * (or similar) without declaratively specifying
7436 			 * target, then it is expected that target will be
7437 			 * specified with bpf_program__set_attach_target() at
7438 			 * runtime before BPF object load step. If not, then
7439 			 * there is nothing to load into the kernel as BPF
7440 			 * verifier won't be able to validate BPF program
7441 			 * correctness anyways.
7442 			 */
7443 			pr_warn("prog '%s': no BTF-based attach target is specified, use bpf_program__set_attach_target()\n",
7444 				prog->name);
7445 			return -EINVAL;
7446 		}
7447 		attach_name++; /* skip over / */
7448 
7449 		err = libbpf_find_attach_btf_id(prog, attach_name, &btf_obj_fd, &btf_type_id);
7450 		if (err)
7451 			return err;
7452 
7453 		/* cache resolved BTF FD and BTF type ID in the prog */
7454 		prog->attach_btf_obj_fd = btf_obj_fd;
7455 		prog->attach_btf_id = btf_type_id;
7456 
7457 		/* but by now libbpf common logic is not utilizing
7458 		 * prog->atach_btf_obj_fd/prog->attach_btf_id anymore because
7459 		 * this callback is called after opts were populated by
7460 		 * libbpf, so this callback has to update opts explicitly here
7461 		 */
7462 		opts->attach_btf_obj_fd = btf_obj_fd;
7463 		opts->attach_btf_id = btf_type_id;
7464 	}
7465 	return 0;
7466 }
7467 
7468 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz);
7469 
7470 static int bpf_object_load_prog(struct bpf_object *obj, struct bpf_program *prog,
7471 				struct bpf_insn *insns, int insns_cnt,
7472 				const char *license, __u32 kern_version, int *prog_fd)
7473 {
7474 	LIBBPF_OPTS(bpf_prog_load_opts, load_attr);
7475 	const char *prog_name = NULL;
7476 	size_t log_buf_size = 0;
7477 	char *log_buf = NULL, *tmp;
7478 	bool own_log_buf = true;
7479 	__u32 log_level = prog->log_level;
7480 	int ret, err;
7481 
7482 	/* Be more helpful by rejecting programs that can't be validated early
7483 	 * with more meaningful and actionable error message.
7484 	 */
7485 	switch (prog->type) {
7486 	case BPF_PROG_TYPE_UNSPEC:
7487 		/*
7488 		 * The program type must be set.  Most likely we couldn't find a proper
7489 		 * section definition at load time, and thus we didn't infer the type.
7490 		 */
7491 		pr_warn("prog '%s': missing BPF prog type, check ELF section name '%s'\n",
7492 			prog->name, prog->sec_name);
7493 		return -EINVAL;
7494 	case BPF_PROG_TYPE_STRUCT_OPS:
7495 		if (prog->attach_btf_id == 0) {
7496 			pr_warn("prog '%s': SEC(\"struct_ops\") program isn't referenced anywhere, did you forget to use it?\n",
7497 				prog->name);
7498 			return -EINVAL;
7499 		}
7500 		break;
7501 	default:
7502 		break;
7503 	}
7504 
7505 	if (!insns || !insns_cnt)
7506 		return -EINVAL;
7507 
7508 	if (kernel_supports(obj, FEAT_PROG_NAME))
7509 		prog_name = prog->name;
7510 	load_attr.attach_prog_fd = prog->attach_prog_fd;
7511 	load_attr.attach_btf_obj_fd = prog->attach_btf_obj_fd;
7512 	load_attr.attach_btf_id = prog->attach_btf_id;
7513 	load_attr.kern_version = kern_version;
7514 	load_attr.prog_ifindex = prog->prog_ifindex;
7515 	load_attr.expected_attach_type = prog->expected_attach_type;
7516 
7517 	/* specify func_info/line_info only if kernel supports them */
7518 	if (obj->btf && btf__fd(obj->btf) >= 0 && kernel_supports(obj, FEAT_BTF_FUNC)) {
7519 		load_attr.prog_btf_fd = btf__fd(obj->btf);
7520 		load_attr.func_info = prog->func_info;
7521 		load_attr.func_info_rec_size = prog->func_info_rec_size;
7522 		load_attr.func_info_cnt = prog->func_info_cnt;
7523 		load_attr.line_info = prog->line_info;
7524 		load_attr.line_info_rec_size = prog->line_info_rec_size;
7525 		load_attr.line_info_cnt = prog->line_info_cnt;
7526 	}
7527 	load_attr.log_level = log_level;
7528 	load_attr.prog_flags = prog->prog_flags;
7529 	load_attr.fd_array = obj->fd_array;
7530 
7531 	load_attr.token_fd = obj->token_fd;
7532 	if (obj->token_fd)
7533 		load_attr.prog_flags |= BPF_F_TOKEN_FD;
7534 
7535 	/* adjust load_attr if sec_def provides custom preload callback */
7536 	if (prog->sec_def && prog->sec_def->prog_prepare_load_fn) {
7537 		err = prog->sec_def->prog_prepare_load_fn(prog, &load_attr, prog->sec_def->cookie);
7538 		if (err < 0) {
7539 			pr_warn("prog '%s': failed to prepare load attributes: %s\n",
7540 				prog->name, errstr(err));
7541 			return err;
7542 		}
7543 		insns = prog->insns;
7544 		insns_cnt = prog->insns_cnt;
7545 	}
7546 
7547 	if (obj->gen_loader) {
7548 		bpf_gen__prog_load(obj->gen_loader, prog->type, prog->name,
7549 				   license, insns, insns_cnt, &load_attr,
7550 				   prog - obj->programs);
7551 		*prog_fd = -1;
7552 		return 0;
7553 	}
7554 
7555 retry_load:
7556 	/* if log_level is zero, we don't request logs initially even if
7557 	 * custom log_buf is specified; if the program load fails, then we'll
7558 	 * bump log_level to 1 and use either custom log_buf or we'll allocate
7559 	 * our own and retry the load to get details on what failed
7560 	 */
7561 	if (log_level) {
7562 		if (prog->log_buf) {
7563 			log_buf = prog->log_buf;
7564 			log_buf_size = prog->log_size;
7565 			own_log_buf = false;
7566 		} else if (obj->log_buf) {
7567 			log_buf = obj->log_buf;
7568 			log_buf_size = obj->log_size;
7569 			own_log_buf = false;
7570 		} else {
7571 			log_buf_size = max((size_t)BPF_LOG_BUF_SIZE, log_buf_size * 2);
7572 			tmp = realloc(log_buf, log_buf_size);
7573 			if (!tmp) {
7574 				ret = -ENOMEM;
7575 				goto out;
7576 			}
7577 			log_buf = tmp;
7578 			log_buf[0] = '\0';
7579 			own_log_buf = true;
7580 		}
7581 	}
7582 
7583 	load_attr.log_buf = log_buf;
7584 	load_attr.log_size = log_buf_size;
7585 	load_attr.log_level = log_level;
7586 
7587 	ret = bpf_prog_load(prog->type, prog_name, license, insns, insns_cnt, &load_attr);
7588 	if (ret >= 0) {
7589 		if (log_level && own_log_buf) {
7590 			pr_debug("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
7591 				 prog->name, log_buf);
7592 		}
7593 
7594 		if (obj->has_rodata && kernel_supports(obj, FEAT_PROG_BIND_MAP)) {
7595 			struct bpf_map *map;
7596 			int i;
7597 
7598 			for (i = 0; i < obj->nr_maps; i++) {
7599 				map = &prog->obj->maps[i];
7600 				if (map->libbpf_type != LIBBPF_MAP_RODATA)
7601 					continue;
7602 
7603 				if (bpf_prog_bind_map(ret, map->fd, NULL)) {
7604 					pr_warn("prog '%s': failed to bind map '%s': %s\n",
7605 						prog->name, map->real_name, errstr(errno));
7606 					/* Don't fail hard if can't bind rodata. */
7607 				}
7608 			}
7609 		}
7610 
7611 		*prog_fd = ret;
7612 		ret = 0;
7613 		goto out;
7614 	}
7615 
7616 	if (log_level == 0) {
7617 		log_level = 1;
7618 		goto retry_load;
7619 	}
7620 	/* On ENOSPC, increase log buffer size and retry, unless custom
7621 	 * log_buf is specified.
7622 	 * Be careful to not overflow u32, though. Kernel's log buf size limit
7623 	 * isn't part of UAPI so it can always be bumped to full 4GB. So don't
7624 	 * multiply by 2 unless we are sure we'll fit within 32 bits.
7625 	 * Currently, we'll get -EINVAL when we reach (UINT_MAX >> 2).
7626 	 */
7627 	if (own_log_buf && errno == ENOSPC && log_buf_size <= UINT_MAX / 2)
7628 		goto retry_load;
7629 
7630 	ret = -errno;
7631 
7632 	/* post-process verifier log to improve error descriptions */
7633 	fixup_verifier_log(prog, log_buf, log_buf_size);
7634 
7635 	pr_warn("prog '%s': BPF program load failed: %s\n", prog->name, errstr(errno));
7636 	pr_perm_msg(ret);
7637 
7638 	if (own_log_buf && log_buf && log_buf[0] != '\0') {
7639 		pr_warn("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
7640 			prog->name, log_buf);
7641 	}
7642 
7643 out:
7644 	if (own_log_buf)
7645 		free(log_buf);
7646 	return ret;
7647 }
7648 
7649 static char *find_prev_line(char *buf, char *cur)
7650 {
7651 	char *p;
7652 
7653 	if (cur == buf) /* end of a log buf */
7654 		return NULL;
7655 
7656 	p = cur - 1;
7657 	while (p - 1 >= buf && *(p - 1) != '\n')
7658 		p--;
7659 
7660 	return p;
7661 }
7662 
7663 static void patch_log(char *buf, size_t buf_sz, size_t log_sz,
7664 		      char *orig, size_t orig_sz, const char *patch)
7665 {
7666 	/* size of the remaining log content to the right from the to-be-replaced part */
7667 	size_t rem_sz = (buf + log_sz) - (orig + orig_sz);
7668 	size_t patch_sz = strlen(patch);
7669 
7670 	if (patch_sz != orig_sz) {
7671 		/* If patch line(s) are longer than original piece of verifier log,
7672 		 * shift log contents by (patch_sz - orig_sz) bytes to the right
7673 		 * starting from after to-be-replaced part of the log.
7674 		 *
7675 		 * If patch line(s) are shorter than original piece of verifier log,
7676 		 * shift log contents by (orig_sz - patch_sz) bytes to the left
7677 		 * starting from after to-be-replaced part of the log
7678 		 *
7679 		 * We need to be careful about not overflowing available
7680 		 * buf_sz capacity. If that's the case, we'll truncate the end
7681 		 * of the original log, as necessary.
7682 		 */
7683 		if (patch_sz > orig_sz) {
7684 			if (orig + patch_sz >= buf + buf_sz) {
7685 				/* patch is big enough to cover remaining space completely */
7686 				patch_sz -= (orig + patch_sz) - (buf + buf_sz) + 1;
7687 				rem_sz = 0;
7688 			} else if (patch_sz - orig_sz > buf_sz - log_sz) {
7689 				/* patch causes part of remaining log to be truncated */
7690 				rem_sz -= (patch_sz - orig_sz) - (buf_sz - log_sz);
7691 			}
7692 		}
7693 		/* shift remaining log to the right by calculated amount */
7694 		memmove(orig + patch_sz, orig + orig_sz, rem_sz);
7695 	}
7696 
7697 	memcpy(orig, patch, patch_sz);
7698 }
7699 
7700 static void fixup_log_failed_core_relo(struct bpf_program *prog,
7701 				       char *buf, size_t buf_sz, size_t log_sz,
7702 				       char *line1, char *line2, char *line3)
7703 {
7704 	/* Expected log for failed and not properly guarded CO-RE relocation:
7705 	 * line1 -> 123: (85) call unknown#195896080
7706 	 * line2 -> invalid func unknown#195896080
7707 	 * line3 -> <anything else or end of buffer>
7708 	 *
7709 	 * "123" is the index of the instruction that was poisoned. We extract
7710 	 * instruction index to find corresponding CO-RE relocation and
7711 	 * replace this part of the log with more relevant information about
7712 	 * failed CO-RE relocation.
7713 	 */
7714 	const struct bpf_core_relo *relo;
7715 	struct bpf_core_spec spec;
7716 	char patch[512], spec_buf[256];
7717 	int insn_idx, err, spec_len;
7718 
7719 	if (sscanf(line1, "%d: (%*d) call unknown#195896080\n", &insn_idx) != 1)
7720 		return;
7721 
7722 	relo = find_relo_core(prog, insn_idx);
7723 	if (!relo)
7724 		return;
7725 
7726 	err = bpf_core_parse_spec(prog->name, prog->obj->btf, relo, &spec);
7727 	if (err)
7728 		return;
7729 
7730 	spec_len = bpf_core_format_spec(spec_buf, sizeof(spec_buf), &spec);
7731 	snprintf(patch, sizeof(patch),
7732 		 "%d: <invalid CO-RE relocation>\n"
7733 		 "failed to resolve CO-RE relocation %s%s\n",
7734 		 insn_idx, spec_buf, spec_len >= sizeof(spec_buf) ? "..." : "");
7735 
7736 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7737 }
7738 
7739 static void fixup_log_missing_map_load(struct bpf_program *prog,
7740 				       char *buf, size_t buf_sz, size_t log_sz,
7741 				       char *line1, char *line2, char *line3)
7742 {
7743 	/* Expected log for failed and not properly guarded map reference:
7744 	 * line1 -> 123: (85) call unknown#2001000345
7745 	 * line2 -> invalid func unknown#2001000345
7746 	 * line3 -> <anything else or end of buffer>
7747 	 *
7748 	 * "123" is the index of the instruction that was poisoned.
7749 	 * "345" in "2001000345" is a map index in obj->maps to fetch map name.
7750 	 */
7751 	struct bpf_object *obj = prog->obj;
7752 	const struct bpf_map *map;
7753 	int insn_idx, map_idx;
7754 	char patch[128];
7755 
7756 	if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &map_idx) != 2)
7757 		return;
7758 
7759 	map_idx -= POISON_LDIMM64_MAP_BASE;
7760 	if (map_idx < 0 || map_idx >= obj->nr_maps)
7761 		return;
7762 	map = &obj->maps[map_idx];
7763 
7764 	snprintf(patch, sizeof(patch),
7765 		 "%d: <invalid BPF map reference>\n"
7766 		 "BPF map '%s' is referenced but wasn't created\n",
7767 		 insn_idx, map->name);
7768 
7769 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7770 }
7771 
7772 static void fixup_log_missing_kfunc_call(struct bpf_program *prog,
7773 					 char *buf, size_t buf_sz, size_t log_sz,
7774 					 char *line1, char *line2, char *line3)
7775 {
7776 	/* Expected log for failed and not properly guarded kfunc call:
7777 	 * line1 -> 123: (85) call unknown#2002000345
7778 	 * line2 -> invalid func unknown#2002000345
7779 	 * line3 -> <anything else or end of buffer>
7780 	 *
7781 	 * "123" is the index of the instruction that was poisoned.
7782 	 * "345" in "2002000345" is an extern index in obj->externs to fetch kfunc name.
7783 	 */
7784 	struct bpf_object *obj = prog->obj;
7785 	const struct extern_desc *ext;
7786 	int insn_idx, ext_idx;
7787 	char patch[128];
7788 
7789 	if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &ext_idx) != 2)
7790 		return;
7791 
7792 	ext_idx -= POISON_CALL_KFUNC_BASE;
7793 	if (ext_idx < 0 || ext_idx >= obj->nr_extern)
7794 		return;
7795 	ext = &obj->externs[ext_idx];
7796 
7797 	snprintf(patch, sizeof(patch),
7798 		 "%d: <invalid kfunc call>\n"
7799 		 "kfunc '%s' is referenced but wasn't resolved\n",
7800 		 insn_idx, ext->name);
7801 
7802 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7803 }
7804 
7805 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz)
7806 {
7807 	/* look for familiar error patterns in last N lines of the log */
7808 	const size_t max_last_line_cnt = 10;
7809 	char *prev_line, *cur_line, *next_line;
7810 	size_t log_sz;
7811 	int i;
7812 
7813 	if (!buf)
7814 		return;
7815 
7816 	log_sz = strlen(buf) + 1;
7817 	next_line = buf + log_sz - 1;
7818 
7819 	for (i = 0; i < max_last_line_cnt; i++, next_line = cur_line) {
7820 		cur_line = find_prev_line(buf, next_line);
7821 		if (!cur_line)
7822 			return;
7823 
7824 		if (str_has_pfx(cur_line, "invalid func unknown#195896080\n")) {
7825 			prev_line = find_prev_line(buf, cur_line);
7826 			if (!prev_line)
7827 				continue;
7828 
7829 			/* failed CO-RE relocation case */
7830 			fixup_log_failed_core_relo(prog, buf, buf_sz, log_sz,
7831 						   prev_line, cur_line, next_line);
7832 			return;
7833 		} else if (str_has_pfx(cur_line, "invalid func unknown#"POISON_LDIMM64_MAP_PFX)) {
7834 			prev_line = find_prev_line(buf, cur_line);
7835 			if (!prev_line)
7836 				continue;
7837 
7838 			/* reference to uncreated BPF map */
7839 			fixup_log_missing_map_load(prog, buf, buf_sz, log_sz,
7840 						   prev_line, cur_line, next_line);
7841 			return;
7842 		} else if (str_has_pfx(cur_line, "invalid func unknown#"POISON_CALL_KFUNC_PFX)) {
7843 			prev_line = find_prev_line(buf, cur_line);
7844 			if (!prev_line)
7845 				continue;
7846 
7847 			/* reference to unresolved kfunc */
7848 			fixup_log_missing_kfunc_call(prog, buf, buf_sz, log_sz,
7849 						     prev_line, cur_line, next_line);
7850 			return;
7851 		}
7852 	}
7853 }
7854 
7855 static int bpf_program_record_relos(struct bpf_program *prog)
7856 {
7857 	struct bpf_object *obj = prog->obj;
7858 	int i;
7859 
7860 	for (i = 0; i < prog->nr_reloc; i++) {
7861 		struct reloc_desc *relo = &prog->reloc_desc[i];
7862 		struct extern_desc *ext = &obj->externs[relo->ext_idx];
7863 		int kind;
7864 
7865 		switch (relo->type) {
7866 		case RELO_EXTERN_LD64:
7867 			if (ext->type != EXT_KSYM)
7868 				continue;
7869 			kind = btf_is_var(btf__type_by_id(obj->btf, ext->btf_id)) ?
7870 				BTF_KIND_VAR : BTF_KIND_FUNC;
7871 			bpf_gen__record_extern(obj->gen_loader, ext->name,
7872 					       ext->is_weak, !ext->ksym.type_id,
7873 					       true, kind, relo->insn_idx);
7874 			break;
7875 		case RELO_EXTERN_CALL:
7876 			bpf_gen__record_extern(obj->gen_loader, ext->name,
7877 					       ext->is_weak, false, false, BTF_KIND_FUNC,
7878 					       relo->insn_idx);
7879 			break;
7880 		case RELO_CORE: {
7881 			struct bpf_core_relo cr = {
7882 				.insn_off = relo->insn_idx * 8,
7883 				.type_id = relo->core_relo->type_id,
7884 				.access_str_off = relo->core_relo->access_str_off,
7885 				.kind = relo->core_relo->kind,
7886 			};
7887 
7888 			bpf_gen__record_relo_core(obj->gen_loader, &cr);
7889 			break;
7890 		}
7891 		default:
7892 			continue;
7893 		}
7894 	}
7895 	return 0;
7896 }
7897 
7898 static int
7899 bpf_object__load_progs(struct bpf_object *obj, int log_level)
7900 {
7901 	struct bpf_program *prog;
7902 	size_t i;
7903 	int err;
7904 
7905 	for (i = 0; i < obj->nr_programs; i++) {
7906 		prog = &obj->programs[i];
7907 		if (prog_is_subprog(obj, prog))
7908 			continue;
7909 		if (!prog->autoload) {
7910 			pr_debug("prog '%s': skipped loading\n", prog->name);
7911 			continue;
7912 		}
7913 		prog->log_level |= log_level;
7914 
7915 		if (obj->gen_loader)
7916 			bpf_program_record_relos(prog);
7917 
7918 		err = bpf_object_load_prog(obj, prog, prog->insns, prog->insns_cnt,
7919 					   obj->license, obj->kern_version, &prog->fd);
7920 		if (err) {
7921 			pr_warn("prog '%s': failed to load: %s\n", prog->name, errstr(err));
7922 			return err;
7923 		}
7924 	}
7925 
7926 	bpf_object__free_relocs(obj);
7927 	return 0;
7928 }
7929 
7930 static int bpf_object_prepare_progs(struct bpf_object *obj)
7931 {
7932 	struct bpf_program *prog;
7933 	size_t i;
7934 	int err;
7935 
7936 	for (i = 0; i < obj->nr_programs; i++) {
7937 		prog = &obj->programs[i];
7938 		err = bpf_object__sanitize_prog(obj, prog);
7939 		if (err)
7940 			return err;
7941 	}
7942 	return 0;
7943 }
7944 
7945 static const struct bpf_sec_def *find_sec_def(const char *sec_name);
7946 
7947 static int bpf_object_init_progs(struct bpf_object *obj, const struct bpf_object_open_opts *opts)
7948 {
7949 	struct bpf_program *prog;
7950 	int err;
7951 
7952 	bpf_object__for_each_program(prog, obj) {
7953 		prog->sec_def = find_sec_def(prog->sec_name);
7954 		if (!prog->sec_def) {
7955 			/* couldn't guess, but user might manually specify */
7956 			pr_debug("prog '%s': unrecognized ELF section name '%s'\n",
7957 				prog->name, prog->sec_name);
7958 			continue;
7959 		}
7960 
7961 		prog->type = prog->sec_def->prog_type;
7962 		prog->expected_attach_type = prog->sec_def->expected_attach_type;
7963 
7964 		/* sec_def can have custom callback which should be called
7965 		 * after bpf_program is initialized to adjust its properties
7966 		 */
7967 		if (prog->sec_def->prog_setup_fn) {
7968 			err = prog->sec_def->prog_setup_fn(prog, prog->sec_def->cookie);
7969 			if (err < 0) {
7970 				pr_warn("prog '%s': failed to initialize: %s\n",
7971 					prog->name, errstr(err));
7972 				return err;
7973 			}
7974 		}
7975 	}
7976 
7977 	return 0;
7978 }
7979 
7980 static struct bpf_object *bpf_object_open(const char *path, const void *obj_buf, size_t obj_buf_sz,
7981 					  const char *obj_name,
7982 					  const struct bpf_object_open_opts *opts)
7983 {
7984 	const char *kconfig, *btf_tmp_path, *token_path;
7985 	struct bpf_object *obj;
7986 	int err;
7987 	char *log_buf;
7988 	size_t log_size;
7989 	__u32 log_level;
7990 
7991 	if (obj_buf && !obj_name)
7992 		return ERR_PTR(-EINVAL);
7993 
7994 	if (elf_version(EV_CURRENT) == EV_NONE) {
7995 		pr_warn("failed to init libelf for %s\n",
7996 			path ? : "(mem buf)");
7997 		return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
7998 	}
7999 
8000 	if (!OPTS_VALID(opts, bpf_object_open_opts))
8001 		return ERR_PTR(-EINVAL);
8002 
8003 	obj_name = OPTS_GET(opts, object_name, NULL) ?: obj_name;
8004 	if (obj_buf) {
8005 		path = obj_name;
8006 		pr_debug("loading object '%s' from buffer\n", obj_name);
8007 	} else {
8008 		pr_debug("loading object from %s\n", path);
8009 	}
8010 
8011 	log_buf = OPTS_GET(opts, kernel_log_buf, NULL);
8012 	log_size = OPTS_GET(opts, kernel_log_size, 0);
8013 	log_level = OPTS_GET(opts, kernel_log_level, 0);
8014 	if (log_size > UINT_MAX)
8015 		return ERR_PTR(-EINVAL);
8016 	if (log_size && !log_buf)
8017 		return ERR_PTR(-EINVAL);
8018 
8019 	token_path = OPTS_GET(opts, bpf_token_path, NULL);
8020 	/* if user didn't specify bpf_token_path explicitly, check if
8021 	 * LIBBPF_BPF_TOKEN_PATH envvar was set and treat it as bpf_token_path
8022 	 * option
8023 	 */
8024 	if (!token_path)
8025 		token_path = getenv("LIBBPF_BPF_TOKEN_PATH");
8026 	if (token_path && strlen(token_path) >= PATH_MAX)
8027 		return ERR_PTR(-ENAMETOOLONG);
8028 
8029 	obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
8030 	if (IS_ERR(obj))
8031 		return obj;
8032 
8033 	obj->log_buf = log_buf;
8034 	obj->log_size = log_size;
8035 	obj->log_level = log_level;
8036 
8037 	if (token_path) {
8038 		obj->token_path = strdup(token_path);
8039 		if (!obj->token_path) {
8040 			err = -ENOMEM;
8041 			goto out;
8042 		}
8043 	}
8044 
8045 	btf_tmp_path = OPTS_GET(opts, btf_custom_path, NULL);
8046 	if (btf_tmp_path) {
8047 		if (strlen(btf_tmp_path) >= PATH_MAX) {
8048 			err = -ENAMETOOLONG;
8049 			goto out;
8050 		}
8051 		obj->btf_custom_path = strdup(btf_tmp_path);
8052 		if (!obj->btf_custom_path) {
8053 			err = -ENOMEM;
8054 			goto out;
8055 		}
8056 	}
8057 
8058 	kconfig = OPTS_GET(opts, kconfig, NULL);
8059 	if (kconfig) {
8060 		obj->kconfig = strdup(kconfig);
8061 		if (!obj->kconfig) {
8062 			err = -ENOMEM;
8063 			goto out;
8064 		}
8065 	}
8066 
8067 	err = bpf_object__elf_init(obj);
8068 	err = err ? : bpf_object__elf_collect(obj);
8069 	err = err ? : bpf_object__collect_externs(obj);
8070 	err = err ? : bpf_object_fixup_btf(obj);
8071 	err = err ? : bpf_object__init_maps(obj, opts);
8072 	err = err ? : bpf_object_init_progs(obj, opts);
8073 	err = err ? : bpf_object__collect_relos(obj);
8074 	if (err)
8075 		goto out;
8076 
8077 	bpf_object__elf_finish(obj);
8078 
8079 	return obj;
8080 out:
8081 	bpf_object__close(obj);
8082 	return ERR_PTR(err);
8083 }
8084 
8085 struct bpf_object *
8086 bpf_object__open_file(const char *path, const struct bpf_object_open_opts *opts)
8087 {
8088 	if (!path)
8089 		return libbpf_err_ptr(-EINVAL);
8090 
8091 	return libbpf_ptr(bpf_object_open(path, NULL, 0, NULL, opts));
8092 }
8093 
8094 struct bpf_object *bpf_object__open(const char *path)
8095 {
8096 	return bpf_object__open_file(path, NULL);
8097 }
8098 
8099 struct bpf_object *
8100 bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
8101 		     const struct bpf_object_open_opts *opts)
8102 {
8103 	char tmp_name[64];
8104 
8105 	if (!obj_buf || obj_buf_sz == 0)
8106 		return libbpf_err_ptr(-EINVAL);
8107 
8108 	/* create a (quite useless) default "name" for this memory buffer object */
8109 	snprintf(tmp_name, sizeof(tmp_name), "%lx-%zx", (unsigned long)obj_buf, obj_buf_sz);
8110 
8111 	return libbpf_ptr(bpf_object_open(NULL, obj_buf, obj_buf_sz, tmp_name, opts));
8112 }
8113 
8114 static int bpf_object_unload(struct bpf_object *obj)
8115 {
8116 	size_t i;
8117 
8118 	if (!obj)
8119 		return libbpf_err(-EINVAL);
8120 
8121 	for (i = 0; i < obj->nr_maps; i++) {
8122 		zclose(obj->maps[i].fd);
8123 		if (obj->maps[i].st_ops)
8124 			zfree(&obj->maps[i].st_ops->kern_vdata);
8125 	}
8126 
8127 	for (i = 0; i < obj->nr_programs; i++)
8128 		bpf_program__unload(&obj->programs[i]);
8129 
8130 	return 0;
8131 }
8132 
8133 static int bpf_object__sanitize_maps(struct bpf_object *obj)
8134 {
8135 	struct bpf_map *m;
8136 
8137 	bpf_object__for_each_map(m, obj) {
8138 		if (!bpf_map__is_internal(m))
8139 			continue;
8140 		if (!kernel_supports(obj, FEAT_ARRAY_MMAP))
8141 			m->def.map_flags &= ~BPF_F_MMAPABLE;
8142 	}
8143 
8144 	return 0;
8145 }
8146 
8147 typedef int (*kallsyms_cb_t)(unsigned long long sym_addr, char sym_type,
8148 			     const char *sym_name, void *ctx);
8149 
8150 static int libbpf_kallsyms_parse(kallsyms_cb_t cb, void *ctx)
8151 {
8152 	char sym_type, sym_name[500];
8153 	unsigned long long sym_addr;
8154 	int ret, err = 0;
8155 	FILE *f;
8156 
8157 	f = fopen("/proc/kallsyms", "re");
8158 	if (!f) {
8159 		err = -errno;
8160 		pr_warn("failed to open /proc/kallsyms: %s\n", errstr(err));
8161 		return err;
8162 	}
8163 
8164 	while (true) {
8165 		ret = fscanf(f, "%llx %c %499s%*[^\n]\n",
8166 			     &sym_addr, &sym_type, sym_name);
8167 		if (ret == EOF && feof(f))
8168 			break;
8169 		if (ret != 3) {
8170 			pr_warn("failed to read kallsyms entry: %d\n", ret);
8171 			err = -EINVAL;
8172 			break;
8173 		}
8174 
8175 		err = cb(sym_addr, sym_type, sym_name, ctx);
8176 		if (err)
8177 			break;
8178 	}
8179 
8180 	fclose(f);
8181 	return err;
8182 }
8183 
8184 static int kallsyms_cb(unsigned long long sym_addr, char sym_type,
8185 		       const char *sym_name, void *ctx)
8186 {
8187 	struct bpf_object *obj = ctx;
8188 	const struct btf_type *t;
8189 	struct extern_desc *ext;
8190 	char *res;
8191 
8192 	res = strstr(sym_name, ".llvm.");
8193 	if (sym_type == 'd' && res)
8194 		ext = find_extern_by_name_with_len(obj, sym_name, res - sym_name);
8195 	else
8196 		ext = find_extern_by_name(obj, sym_name);
8197 	if (!ext || ext->type != EXT_KSYM)
8198 		return 0;
8199 
8200 	t = btf__type_by_id(obj->btf, ext->btf_id);
8201 	if (!btf_is_var(t))
8202 		return 0;
8203 
8204 	if (ext->is_set && ext->ksym.addr != sym_addr) {
8205 		pr_warn("extern (ksym) '%s': resolution is ambiguous: 0x%llx or 0x%llx\n",
8206 			sym_name, ext->ksym.addr, sym_addr);
8207 		return -EINVAL;
8208 	}
8209 	if (!ext->is_set) {
8210 		ext->is_set = true;
8211 		ext->ksym.addr = sym_addr;
8212 		pr_debug("extern (ksym) '%s': set to 0x%llx\n", sym_name, sym_addr);
8213 	}
8214 	return 0;
8215 }
8216 
8217 static int bpf_object__read_kallsyms_file(struct bpf_object *obj)
8218 {
8219 	return libbpf_kallsyms_parse(kallsyms_cb, obj);
8220 }
8221 
8222 static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
8223 			    __u16 kind, struct btf **res_btf,
8224 			    struct module_btf **res_mod_btf)
8225 {
8226 	struct module_btf *mod_btf;
8227 	struct btf *btf;
8228 	int i, id, err;
8229 
8230 	btf = obj->btf_vmlinux;
8231 	mod_btf = NULL;
8232 	id = btf__find_by_name_kind(btf, ksym_name, kind);
8233 
8234 	if (id == -ENOENT) {
8235 		err = load_module_btfs(obj);
8236 		if (err)
8237 			return err;
8238 
8239 		for (i = 0; i < obj->btf_module_cnt; i++) {
8240 			/* we assume module_btf's BTF FD is always >0 */
8241 			mod_btf = &obj->btf_modules[i];
8242 			btf = mod_btf->btf;
8243 			id = btf__find_by_name_kind_own(btf, ksym_name, kind);
8244 			if (id != -ENOENT)
8245 				break;
8246 		}
8247 	}
8248 	if (id <= 0)
8249 		return -ESRCH;
8250 
8251 	*res_btf = btf;
8252 	*res_mod_btf = mod_btf;
8253 	return id;
8254 }
8255 
8256 static int bpf_object__resolve_ksym_var_btf_id(struct bpf_object *obj,
8257 					       struct extern_desc *ext)
8258 {
8259 	const struct btf_type *targ_var, *targ_type;
8260 	__u32 targ_type_id, local_type_id;
8261 	struct module_btf *mod_btf = NULL;
8262 	const char *targ_var_name;
8263 	struct btf *btf = NULL;
8264 	int id, err;
8265 
8266 	id = find_ksym_btf_id(obj, ext->name, BTF_KIND_VAR, &btf, &mod_btf);
8267 	if (id < 0) {
8268 		if (id == -ESRCH && ext->is_weak)
8269 			return 0;
8270 		pr_warn("extern (var ksym) '%s': not found in kernel BTF\n",
8271 			ext->name);
8272 		return id;
8273 	}
8274 
8275 	/* find local type_id */
8276 	local_type_id = ext->ksym.type_id;
8277 
8278 	/* find target type_id */
8279 	targ_var = btf__type_by_id(btf, id);
8280 	targ_var_name = btf__name_by_offset(btf, targ_var->name_off);
8281 	targ_type = skip_mods_and_typedefs(btf, targ_var->type, &targ_type_id);
8282 
8283 	err = bpf_core_types_are_compat(obj->btf, local_type_id,
8284 					btf, targ_type_id);
8285 	if (err <= 0) {
8286 		const struct btf_type *local_type;
8287 		const char *targ_name, *local_name;
8288 
8289 		local_type = btf__type_by_id(obj->btf, local_type_id);
8290 		local_name = btf__name_by_offset(obj->btf, local_type->name_off);
8291 		targ_name = btf__name_by_offset(btf, targ_type->name_off);
8292 
8293 		pr_warn("extern (var ksym) '%s': incompatible types, expected [%d] %s %s, but kernel has [%d] %s %s\n",
8294 			ext->name, local_type_id,
8295 			btf_kind_str(local_type), local_name, targ_type_id,
8296 			btf_kind_str(targ_type), targ_name);
8297 		return -EINVAL;
8298 	}
8299 
8300 	ext->is_set = true;
8301 	ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
8302 	ext->ksym.kernel_btf_id = id;
8303 	pr_debug("extern (var ksym) '%s': resolved to [%d] %s %s\n",
8304 		 ext->name, id, btf_kind_str(targ_var), targ_var_name);
8305 
8306 	return 0;
8307 }
8308 
8309 static int bpf_object__resolve_ksym_func_btf_id(struct bpf_object *obj,
8310 						struct extern_desc *ext)
8311 {
8312 	int local_func_proto_id, kfunc_proto_id, kfunc_id;
8313 	struct module_btf *mod_btf = NULL;
8314 	const struct btf_type *kern_func;
8315 	struct btf *kern_btf = NULL;
8316 	int ret;
8317 
8318 	local_func_proto_id = ext->ksym.type_id;
8319 
8320 	kfunc_id = find_ksym_btf_id(obj, ext->essent_name ?: ext->name, BTF_KIND_FUNC, &kern_btf,
8321 				    &mod_btf);
8322 	if (kfunc_id < 0) {
8323 		if (kfunc_id == -ESRCH && ext->is_weak)
8324 			return 0;
8325 		pr_warn("extern (func ksym) '%s': not found in kernel or module BTFs\n",
8326 			ext->name);
8327 		return kfunc_id;
8328 	}
8329 
8330 	kern_func = btf__type_by_id(kern_btf, kfunc_id);
8331 	kfunc_proto_id = kern_func->type;
8332 
8333 	ret = bpf_core_types_are_compat(obj->btf, local_func_proto_id,
8334 					kern_btf, kfunc_proto_id);
8335 	if (ret <= 0) {
8336 		if (ext->is_weak)
8337 			return 0;
8338 
8339 		pr_warn("extern (func ksym) '%s': func_proto [%d] incompatible with %s [%d]\n",
8340 			ext->name, local_func_proto_id,
8341 			mod_btf ? mod_btf->name : "vmlinux", kfunc_proto_id);
8342 		return -EINVAL;
8343 	}
8344 
8345 	/* set index for module BTF fd in fd_array, if unset */
8346 	if (mod_btf && !mod_btf->fd_array_idx) {
8347 		/* insn->off is s16 */
8348 		if (obj->fd_array_cnt == INT16_MAX) {
8349 			pr_warn("extern (func ksym) '%s': module BTF fd index %d too big to fit in bpf_insn offset\n",
8350 				ext->name, mod_btf->fd_array_idx);
8351 			return -E2BIG;
8352 		}
8353 		/* Cannot use index 0 for module BTF fd */
8354 		if (!obj->fd_array_cnt)
8355 			obj->fd_array_cnt = 1;
8356 
8357 		ret = libbpf_ensure_mem((void **)&obj->fd_array, &obj->fd_array_cap, sizeof(int),
8358 					obj->fd_array_cnt + 1);
8359 		if (ret)
8360 			return ret;
8361 		mod_btf->fd_array_idx = obj->fd_array_cnt;
8362 		/* we assume module BTF FD is always >0 */
8363 		obj->fd_array[obj->fd_array_cnt++] = mod_btf->fd;
8364 	}
8365 
8366 	ext->is_set = true;
8367 	ext->ksym.kernel_btf_id = kfunc_id;
8368 	ext->ksym.btf_fd_idx = mod_btf ? mod_btf->fd_array_idx : 0;
8369 	/* Also set kernel_btf_obj_fd to make sure that bpf_object__relocate_data()
8370 	 * populates FD into ld_imm64 insn when it's used to point to kfunc.
8371 	 * {kernel_btf_id, btf_fd_idx} -> fixup bpf_call.
8372 	 * {kernel_btf_id, kernel_btf_obj_fd} -> fixup ld_imm64.
8373 	 */
8374 	ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
8375 	pr_debug("extern (func ksym) '%s': resolved to %s [%d]\n",
8376 		 ext->name, mod_btf ? mod_btf->name : "vmlinux", kfunc_id);
8377 
8378 	return 0;
8379 }
8380 
8381 static int bpf_object__resolve_ksyms_btf_id(struct bpf_object *obj)
8382 {
8383 	const struct btf_type *t;
8384 	struct extern_desc *ext;
8385 	int i, err;
8386 
8387 	for (i = 0; i < obj->nr_extern; i++) {
8388 		ext = &obj->externs[i];
8389 		if (ext->type != EXT_KSYM || !ext->ksym.type_id)
8390 			continue;
8391 
8392 		if (obj->gen_loader) {
8393 			ext->is_set = true;
8394 			ext->ksym.kernel_btf_obj_fd = 0;
8395 			ext->ksym.kernel_btf_id = 0;
8396 			continue;
8397 		}
8398 		t = btf__type_by_id(obj->btf, ext->btf_id);
8399 		if (btf_is_var(t))
8400 			err = bpf_object__resolve_ksym_var_btf_id(obj, ext);
8401 		else
8402 			err = bpf_object__resolve_ksym_func_btf_id(obj, ext);
8403 		if (err)
8404 			return err;
8405 	}
8406 	return 0;
8407 }
8408 
8409 static int bpf_object__resolve_externs(struct bpf_object *obj,
8410 				       const char *extra_kconfig)
8411 {
8412 	bool need_config = false, need_kallsyms = false;
8413 	bool need_vmlinux_btf = false;
8414 	struct extern_desc *ext;
8415 	void *kcfg_data = NULL;
8416 	int err, i;
8417 
8418 	if (obj->nr_extern == 0)
8419 		return 0;
8420 
8421 	if (obj->kconfig_map_idx >= 0)
8422 		kcfg_data = obj->maps[obj->kconfig_map_idx].mmaped;
8423 
8424 	for (i = 0; i < obj->nr_extern; i++) {
8425 		ext = &obj->externs[i];
8426 
8427 		if (ext->type == EXT_KSYM) {
8428 			if (ext->ksym.type_id)
8429 				need_vmlinux_btf = true;
8430 			else
8431 				need_kallsyms = true;
8432 			continue;
8433 		} else if (ext->type == EXT_KCFG) {
8434 			void *ext_ptr = kcfg_data + ext->kcfg.data_off;
8435 			__u64 value = 0;
8436 
8437 			/* Kconfig externs need actual /proc/config.gz */
8438 			if (str_has_pfx(ext->name, "CONFIG_")) {
8439 				need_config = true;
8440 				continue;
8441 			}
8442 
8443 			/* Virtual kcfg externs are customly handled by libbpf */
8444 			if (strcmp(ext->name, "LINUX_KERNEL_VERSION") == 0) {
8445 				value = get_kernel_version();
8446 				if (!value) {
8447 					pr_warn("extern (kcfg) '%s': failed to get kernel version\n", ext->name);
8448 					return -EINVAL;
8449 				}
8450 			} else if (strcmp(ext->name, "LINUX_HAS_BPF_COOKIE") == 0) {
8451 				value = kernel_supports(obj, FEAT_BPF_COOKIE);
8452 			} else if (strcmp(ext->name, "LINUX_HAS_SYSCALL_WRAPPER") == 0) {
8453 				value = kernel_supports(obj, FEAT_SYSCALL_WRAPPER);
8454 			} else if (!str_has_pfx(ext->name, "LINUX_") || !ext->is_weak) {
8455 				/* Currently libbpf supports only CONFIG_ and LINUX_ prefixed
8456 				 * __kconfig externs, where LINUX_ ones are virtual and filled out
8457 				 * customly by libbpf (their values don't come from Kconfig).
8458 				 * If LINUX_xxx variable is not recognized by libbpf, but is marked
8459 				 * __weak, it defaults to zero value, just like for CONFIG_xxx
8460 				 * externs.
8461 				 */
8462 				pr_warn("extern (kcfg) '%s': unrecognized virtual extern\n", ext->name);
8463 				return -EINVAL;
8464 			}
8465 
8466 			err = set_kcfg_value_num(ext, ext_ptr, value);
8467 			if (err)
8468 				return err;
8469 			pr_debug("extern (kcfg) '%s': set to 0x%llx\n",
8470 				 ext->name, (long long)value);
8471 		} else {
8472 			pr_warn("extern '%s': unrecognized extern kind\n", ext->name);
8473 			return -EINVAL;
8474 		}
8475 	}
8476 	if (need_config && extra_kconfig) {
8477 		err = bpf_object__read_kconfig_mem(obj, extra_kconfig, kcfg_data);
8478 		if (err)
8479 			return -EINVAL;
8480 		need_config = false;
8481 		for (i = 0; i < obj->nr_extern; i++) {
8482 			ext = &obj->externs[i];
8483 			if (ext->type == EXT_KCFG && !ext->is_set) {
8484 				need_config = true;
8485 				break;
8486 			}
8487 		}
8488 	}
8489 	if (need_config) {
8490 		err = bpf_object__read_kconfig_file(obj, kcfg_data);
8491 		if (err)
8492 			return -EINVAL;
8493 	}
8494 	if (need_kallsyms) {
8495 		err = bpf_object__read_kallsyms_file(obj);
8496 		if (err)
8497 			return -EINVAL;
8498 	}
8499 	if (need_vmlinux_btf) {
8500 		err = bpf_object__resolve_ksyms_btf_id(obj);
8501 		if (err)
8502 			return -EINVAL;
8503 	}
8504 	for (i = 0; i < obj->nr_extern; i++) {
8505 		ext = &obj->externs[i];
8506 
8507 		if (!ext->is_set && !ext->is_weak) {
8508 			pr_warn("extern '%s' (strong): not resolved\n", ext->name);
8509 			return -ESRCH;
8510 		} else if (!ext->is_set) {
8511 			pr_debug("extern '%s' (weak): not resolved, defaulting to zero\n",
8512 				 ext->name);
8513 		}
8514 	}
8515 
8516 	return 0;
8517 }
8518 
8519 static void bpf_map_prepare_vdata(const struct bpf_map *map)
8520 {
8521 	const struct btf_type *type;
8522 	struct bpf_struct_ops *st_ops;
8523 	__u32 i;
8524 
8525 	st_ops = map->st_ops;
8526 	type = btf__type_by_id(map->obj->btf, st_ops->type_id);
8527 	for (i = 0; i < btf_vlen(type); i++) {
8528 		struct bpf_program *prog = st_ops->progs[i];
8529 		void *kern_data;
8530 		int prog_fd;
8531 
8532 		if (!prog)
8533 			continue;
8534 
8535 		prog_fd = bpf_program__fd(prog);
8536 		kern_data = st_ops->kern_vdata + st_ops->kern_func_off[i];
8537 		*(unsigned long *)kern_data = prog_fd;
8538 	}
8539 }
8540 
8541 static int bpf_object_prepare_struct_ops(struct bpf_object *obj)
8542 {
8543 	struct bpf_map *map;
8544 	int i;
8545 
8546 	for (i = 0; i < obj->nr_maps; i++) {
8547 		map = &obj->maps[i];
8548 
8549 		if (!bpf_map__is_struct_ops(map))
8550 			continue;
8551 
8552 		if (!map->autocreate)
8553 			continue;
8554 
8555 		bpf_map_prepare_vdata(map);
8556 	}
8557 
8558 	return 0;
8559 }
8560 
8561 static void bpf_object_unpin(struct bpf_object *obj)
8562 {
8563 	int i;
8564 
8565 	/* unpin any maps that were auto-pinned during load */
8566 	for (i = 0; i < obj->nr_maps; i++)
8567 		if (obj->maps[i].pinned && !obj->maps[i].reused)
8568 			bpf_map__unpin(&obj->maps[i], NULL);
8569 }
8570 
8571 static void bpf_object_post_load_cleanup(struct bpf_object *obj)
8572 {
8573 	int i;
8574 
8575 	/* clean up fd_array */
8576 	zfree(&obj->fd_array);
8577 
8578 	/* clean up module BTFs */
8579 	for (i = 0; i < obj->btf_module_cnt; i++) {
8580 		close(obj->btf_modules[i].fd);
8581 		btf__free(obj->btf_modules[i].btf);
8582 		free(obj->btf_modules[i].name);
8583 	}
8584 	obj->btf_module_cnt = 0;
8585 	zfree(&obj->btf_modules);
8586 
8587 	/* clean up vmlinux BTF */
8588 	btf__free(obj->btf_vmlinux);
8589 	obj->btf_vmlinux = NULL;
8590 }
8591 
8592 static int bpf_object_prepare(struct bpf_object *obj, const char *target_btf_path)
8593 {
8594 	int err;
8595 
8596 	if (obj->state >= OBJ_PREPARED) {
8597 		pr_warn("object '%s': prepare loading can't be attempted twice\n", obj->name);
8598 		return -EINVAL;
8599 	}
8600 
8601 	err = bpf_object_prepare_token(obj);
8602 	err = err ? : bpf_object__probe_loading(obj);
8603 	err = err ? : bpf_object__load_vmlinux_btf(obj, false);
8604 	err = err ? : bpf_object__resolve_externs(obj, obj->kconfig);
8605 	err = err ? : bpf_object__sanitize_maps(obj);
8606 	err = err ? : bpf_object__init_kern_struct_ops_maps(obj);
8607 	err = err ? : bpf_object_adjust_struct_ops_autoload(obj);
8608 	err = err ? : bpf_object__relocate(obj, obj->btf_custom_path ? : target_btf_path);
8609 	err = err ? : bpf_object__sanitize_and_load_btf(obj);
8610 	err = err ? : bpf_object__create_maps(obj);
8611 	err = err ? : bpf_object_prepare_progs(obj);
8612 
8613 	if (err) {
8614 		bpf_object_unpin(obj);
8615 		bpf_object_unload(obj);
8616 		obj->state = OBJ_LOADED;
8617 		return err;
8618 	}
8619 
8620 	obj->state = OBJ_PREPARED;
8621 	return 0;
8622 }
8623 
8624 static int bpf_object_load(struct bpf_object *obj, int extra_log_level, const char *target_btf_path)
8625 {
8626 	int err;
8627 
8628 	if (!obj)
8629 		return libbpf_err(-EINVAL);
8630 
8631 	if (obj->state >= OBJ_LOADED) {
8632 		pr_warn("object '%s': load can't be attempted twice\n", obj->name);
8633 		return libbpf_err(-EINVAL);
8634 	}
8635 
8636 	/* Disallow kernel loading programs of non-native endianness but
8637 	 * permit cross-endian creation of "light skeleton".
8638 	 */
8639 	if (obj->gen_loader) {
8640 		bpf_gen__init(obj->gen_loader, extra_log_level, obj->nr_programs, obj->nr_maps);
8641 	} else if (!is_native_endianness(obj)) {
8642 		pr_warn("object '%s': loading non-native endianness is unsupported\n", obj->name);
8643 		return libbpf_err(-LIBBPF_ERRNO__ENDIAN);
8644 	}
8645 
8646 	if (obj->state < OBJ_PREPARED) {
8647 		err = bpf_object_prepare(obj, target_btf_path);
8648 		if (err)
8649 			return libbpf_err(err);
8650 	}
8651 	err = bpf_object__load_progs(obj, extra_log_level);
8652 	err = err ? : bpf_object_init_prog_arrays(obj);
8653 	err = err ? : bpf_object_prepare_struct_ops(obj);
8654 
8655 	if (obj->gen_loader) {
8656 		/* reset FDs */
8657 		if (obj->btf)
8658 			btf__set_fd(obj->btf, -1);
8659 		if (!err)
8660 			err = bpf_gen__finish(obj->gen_loader, obj->nr_programs, obj->nr_maps);
8661 	}
8662 
8663 	bpf_object_post_load_cleanup(obj);
8664 	obj->state = OBJ_LOADED; /* doesn't matter if successfully or not */
8665 
8666 	if (err) {
8667 		bpf_object_unpin(obj);
8668 		bpf_object_unload(obj);
8669 		pr_warn("failed to load object '%s'\n", obj->path);
8670 		return libbpf_err(err);
8671 	}
8672 
8673 	return 0;
8674 }
8675 
8676 int bpf_object__prepare(struct bpf_object *obj)
8677 {
8678 	return libbpf_err(bpf_object_prepare(obj, NULL));
8679 }
8680 
8681 int bpf_object__load(struct bpf_object *obj)
8682 {
8683 	return bpf_object_load(obj, 0, NULL);
8684 }
8685 
8686 static int make_parent_dir(const char *path)
8687 {
8688 	char *dname, *dir;
8689 	int err = 0;
8690 
8691 	dname = strdup(path);
8692 	if (dname == NULL)
8693 		return -ENOMEM;
8694 
8695 	dir = dirname(dname);
8696 	if (mkdir(dir, 0700) && errno != EEXIST)
8697 		err = -errno;
8698 
8699 	free(dname);
8700 	if (err) {
8701 		pr_warn("failed to mkdir %s: %s\n", path, errstr(err));
8702 	}
8703 	return err;
8704 }
8705 
8706 static int check_path(const char *path)
8707 {
8708 	struct statfs st_fs;
8709 	char *dname, *dir;
8710 	int err = 0;
8711 
8712 	if (path == NULL)
8713 		return -EINVAL;
8714 
8715 	dname = strdup(path);
8716 	if (dname == NULL)
8717 		return -ENOMEM;
8718 
8719 	dir = dirname(dname);
8720 	if (statfs(dir, &st_fs)) {
8721 		pr_warn("failed to statfs %s: %s\n", dir, errstr(errno));
8722 		err = -errno;
8723 	}
8724 	free(dname);
8725 
8726 	if (!err && st_fs.f_type != BPF_FS_MAGIC) {
8727 		pr_warn("specified path %s is not on BPF FS\n", path);
8728 		err = -EINVAL;
8729 	}
8730 
8731 	return err;
8732 }
8733 
8734 int bpf_program__pin(struct bpf_program *prog, const char *path)
8735 {
8736 	int err;
8737 
8738 	if (prog->fd < 0) {
8739 		pr_warn("prog '%s': can't pin program that wasn't loaded\n", prog->name);
8740 		return libbpf_err(-EINVAL);
8741 	}
8742 
8743 	err = make_parent_dir(path);
8744 	if (err)
8745 		return libbpf_err(err);
8746 
8747 	err = check_path(path);
8748 	if (err)
8749 		return libbpf_err(err);
8750 
8751 	if (bpf_obj_pin(prog->fd, path)) {
8752 		err = -errno;
8753 		pr_warn("prog '%s': failed to pin at '%s': %s\n", prog->name, path, errstr(err));
8754 		return libbpf_err(err);
8755 	}
8756 
8757 	pr_debug("prog '%s': pinned at '%s'\n", prog->name, path);
8758 	return 0;
8759 }
8760 
8761 int bpf_program__unpin(struct bpf_program *prog, const char *path)
8762 {
8763 	int err;
8764 
8765 	if (prog->fd < 0) {
8766 		pr_warn("prog '%s': can't unpin program that wasn't loaded\n", prog->name);
8767 		return libbpf_err(-EINVAL);
8768 	}
8769 
8770 	err = check_path(path);
8771 	if (err)
8772 		return libbpf_err(err);
8773 
8774 	err = unlink(path);
8775 	if (err)
8776 		return libbpf_err(-errno);
8777 
8778 	pr_debug("prog '%s': unpinned from '%s'\n", prog->name, path);
8779 	return 0;
8780 }
8781 
8782 int bpf_map__pin(struct bpf_map *map, const char *path)
8783 {
8784 	int err;
8785 
8786 	if (map == NULL) {
8787 		pr_warn("invalid map pointer\n");
8788 		return libbpf_err(-EINVAL);
8789 	}
8790 
8791 	if (map->fd < 0) {
8792 		pr_warn("map '%s': can't pin BPF map without FD (was it created?)\n", map->name);
8793 		return libbpf_err(-EINVAL);
8794 	}
8795 
8796 	if (map->pin_path) {
8797 		if (path && strcmp(path, map->pin_path)) {
8798 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
8799 				bpf_map__name(map), map->pin_path, path);
8800 			return libbpf_err(-EINVAL);
8801 		} else if (map->pinned) {
8802 			pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
8803 				 bpf_map__name(map), map->pin_path);
8804 			return 0;
8805 		}
8806 	} else {
8807 		if (!path) {
8808 			pr_warn("missing a path to pin map '%s' at\n",
8809 				bpf_map__name(map));
8810 			return libbpf_err(-EINVAL);
8811 		} else if (map->pinned) {
8812 			pr_warn("map '%s' already pinned\n", bpf_map__name(map));
8813 			return libbpf_err(-EEXIST);
8814 		}
8815 
8816 		map->pin_path = strdup(path);
8817 		if (!map->pin_path) {
8818 			err = -errno;
8819 			goto out_err;
8820 		}
8821 	}
8822 
8823 	err = make_parent_dir(map->pin_path);
8824 	if (err)
8825 		return libbpf_err(err);
8826 
8827 	err = check_path(map->pin_path);
8828 	if (err)
8829 		return libbpf_err(err);
8830 
8831 	if (bpf_obj_pin(map->fd, map->pin_path)) {
8832 		err = -errno;
8833 		goto out_err;
8834 	}
8835 
8836 	map->pinned = true;
8837 	pr_debug("pinned map '%s'\n", map->pin_path);
8838 
8839 	return 0;
8840 
8841 out_err:
8842 	pr_warn("failed to pin map: %s\n", errstr(err));
8843 	return libbpf_err(err);
8844 }
8845 
8846 int bpf_map__unpin(struct bpf_map *map, const char *path)
8847 {
8848 	int err;
8849 
8850 	if (map == NULL) {
8851 		pr_warn("invalid map pointer\n");
8852 		return libbpf_err(-EINVAL);
8853 	}
8854 
8855 	if (map->pin_path) {
8856 		if (path && strcmp(path, map->pin_path)) {
8857 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
8858 				bpf_map__name(map), map->pin_path, path);
8859 			return libbpf_err(-EINVAL);
8860 		}
8861 		path = map->pin_path;
8862 	} else if (!path) {
8863 		pr_warn("no path to unpin map '%s' from\n",
8864 			bpf_map__name(map));
8865 		return libbpf_err(-EINVAL);
8866 	}
8867 
8868 	err = check_path(path);
8869 	if (err)
8870 		return libbpf_err(err);
8871 
8872 	err = unlink(path);
8873 	if (err != 0)
8874 		return libbpf_err(-errno);
8875 
8876 	map->pinned = false;
8877 	pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path);
8878 
8879 	return 0;
8880 }
8881 
8882 int bpf_map__set_pin_path(struct bpf_map *map, const char *path)
8883 {
8884 	char *new = NULL;
8885 
8886 	if (path) {
8887 		new = strdup(path);
8888 		if (!new)
8889 			return libbpf_err(-errno);
8890 	}
8891 
8892 	free(map->pin_path);
8893 	map->pin_path = new;
8894 	return 0;
8895 }
8896 
8897 __alias(bpf_map__pin_path)
8898 const char *bpf_map__get_pin_path(const struct bpf_map *map);
8899 
8900 const char *bpf_map__pin_path(const struct bpf_map *map)
8901 {
8902 	return map->pin_path;
8903 }
8904 
8905 bool bpf_map__is_pinned(const struct bpf_map *map)
8906 {
8907 	return map->pinned;
8908 }
8909 
8910 static void sanitize_pin_path(char *s)
8911 {
8912 	/* bpffs disallows periods in path names */
8913 	while (*s) {
8914 		if (*s == '.')
8915 			*s = '_';
8916 		s++;
8917 	}
8918 }
8919 
8920 int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
8921 {
8922 	struct bpf_map *map;
8923 	int err;
8924 
8925 	if (!obj)
8926 		return libbpf_err(-ENOENT);
8927 
8928 	if (obj->state < OBJ_PREPARED) {
8929 		pr_warn("object not yet loaded; load it first\n");
8930 		return libbpf_err(-ENOENT);
8931 	}
8932 
8933 	bpf_object__for_each_map(map, obj) {
8934 		char *pin_path = NULL;
8935 		char buf[PATH_MAX];
8936 
8937 		if (!map->autocreate)
8938 			continue;
8939 
8940 		if (path) {
8941 			err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
8942 			if (err)
8943 				goto err_unpin_maps;
8944 			sanitize_pin_path(buf);
8945 			pin_path = buf;
8946 		} else if (!map->pin_path) {
8947 			continue;
8948 		}
8949 
8950 		err = bpf_map__pin(map, pin_path);
8951 		if (err)
8952 			goto err_unpin_maps;
8953 	}
8954 
8955 	return 0;
8956 
8957 err_unpin_maps:
8958 	while ((map = bpf_object__prev_map(obj, map))) {
8959 		if (!map->pin_path)
8960 			continue;
8961 
8962 		bpf_map__unpin(map, NULL);
8963 	}
8964 
8965 	return libbpf_err(err);
8966 }
8967 
8968 int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
8969 {
8970 	struct bpf_map *map;
8971 	int err;
8972 
8973 	if (!obj)
8974 		return libbpf_err(-ENOENT);
8975 
8976 	bpf_object__for_each_map(map, obj) {
8977 		char *pin_path = NULL;
8978 		char buf[PATH_MAX];
8979 
8980 		if (path) {
8981 			err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
8982 			if (err)
8983 				return libbpf_err(err);
8984 			sanitize_pin_path(buf);
8985 			pin_path = buf;
8986 		} else if (!map->pin_path) {
8987 			continue;
8988 		}
8989 
8990 		err = bpf_map__unpin(map, pin_path);
8991 		if (err)
8992 			return libbpf_err(err);
8993 	}
8994 
8995 	return 0;
8996 }
8997 
8998 int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
8999 {
9000 	struct bpf_program *prog;
9001 	char buf[PATH_MAX];
9002 	int err;
9003 
9004 	if (!obj)
9005 		return libbpf_err(-ENOENT);
9006 
9007 	if (obj->state < OBJ_LOADED) {
9008 		pr_warn("object not yet loaded; load it first\n");
9009 		return libbpf_err(-ENOENT);
9010 	}
9011 
9012 	bpf_object__for_each_program(prog, obj) {
9013 		err = pathname_concat(buf, sizeof(buf), path, prog->name);
9014 		if (err)
9015 			goto err_unpin_programs;
9016 
9017 		err = bpf_program__pin(prog, buf);
9018 		if (err)
9019 			goto err_unpin_programs;
9020 	}
9021 
9022 	return 0;
9023 
9024 err_unpin_programs:
9025 	while ((prog = bpf_object__prev_program(obj, prog))) {
9026 		if (pathname_concat(buf, sizeof(buf), path, prog->name))
9027 			continue;
9028 
9029 		bpf_program__unpin(prog, buf);
9030 	}
9031 
9032 	return libbpf_err(err);
9033 }
9034 
9035 int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
9036 {
9037 	struct bpf_program *prog;
9038 	int err;
9039 
9040 	if (!obj)
9041 		return libbpf_err(-ENOENT);
9042 
9043 	bpf_object__for_each_program(prog, obj) {
9044 		char buf[PATH_MAX];
9045 
9046 		err = pathname_concat(buf, sizeof(buf), path, prog->name);
9047 		if (err)
9048 			return libbpf_err(err);
9049 
9050 		err = bpf_program__unpin(prog, buf);
9051 		if (err)
9052 			return libbpf_err(err);
9053 	}
9054 
9055 	return 0;
9056 }
9057 
9058 int bpf_object__pin(struct bpf_object *obj, const char *path)
9059 {
9060 	int err;
9061 
9062 	err = bpf_object__pin_maps(obj, path);
9063 	if (err)
9064 		return libbpf_err(err);
9065 
9066 	err = bpf_object__pin_programs(obj, path);
9067 	if (err) {
9068 		bpf_object__unpin_maps(obj, path);
9069 		return libbpf_err(err);
9070 	}
9071 
9072 	return 0;
9073 }
9074 
9075 int bpf_object__unpin(struct bpf_object *obj, const char *path)
9076 {
9077 	int err;
9078 
9079 	err = bpf_object__unpin_programs(obj, path);
9080 	if (err)
9081 		return libbpf_err(err);
9082 
9083 	err = bpf_object__unpin_maps(obj, path);
9084 	if (err)
9085 		return libbpf_err(err);
9086 
9087 	return 0;
9088 }
9089 
9090 static void bpf_map__destroy(struct bpf_map *map)
9091 {
9092 	if (map->inner_map) {
9093 		bpf_map__destroy(map->inner_map);
9094 		zfree(&map->inner_map);
9095 	}
9096 
9097 	zfree(&map->init_slots);
9098 	map->init_slots_sz = 0;
9099 
9100 	if (map->mmaped && map->mmaped != map->obj->arena_data)
9101 		munmap(map->mmaped, bpf_map_mmap_sz(map));
9102 	map->mmaped = NULL;
9103 
9104 	if (map->st_ops) {
9105 		zfree(&map->st_ops->data);
9106 		zfree(&map->st_ops->progs);
9107 		zfree(&map->st_ops->kern_func_off);
9108 		zfree(&map->st_ops);
9109 	}
9110 
9111 	zfree(&map->name);
9112 	zfree(&map->real_name);
9113 	zfree(&map->pin_path);
9114 
9115 	if (map->fd >= 0)
9116 		zclose(map->fd);
9117 }
9118 
9119 void bpf_object__close(struct bpf_object *obj)
9120 {
9121 	size_t i;
9122 
9123 	if (IS_ERR_OR_NULL(obj))
9124 		return;
9125 
9126 	/*
9127 	 * if user called bpf_object__prepare() without ever getting to
9128 	 * bpf_object__load(), we need to clean up stuff that is normally
9129 	 * cleaned up at the end of loading step
9130 	 */
9131 	bpf_object_post_load_cleanup(obj);
9132 
9133 	usdt_manager_free(obj->usdt_man);
9134 	obj->usdt_man = NULL;
9135 
9136 	bpf_gen__free(obj->gen_loader);
9137 	bpf_object__elf_finish(obj);
9138 	bpf_object_unload(obj);
9139 	btf__free(obj->btf);
9140 	btf__free(obj->btf_vmlinux);
9141 	btf_ext__free(obj->btf_ext);
9142 
9143 	for (i = 0; i < obj->nr_maps; i++)
9144 		bpf_map__destroy(&obj->maps[i]);
9145 
9146 	zfree(&obj->btf_custom_path);
9147 	zfree(&obj->kconfig);
9148 
9149 	for (i = 0; i < obj->nr_extern; i++) {
9150 		zfree(&obj->externs[i].name);
9151 		zfree(&obj->externs[i].essent_name);
9152 	}
9153 
9154 	zfree(&obj->externs);
9155 	obj->nr_extern = 0;
9156 
9157 	zfree(&obj->maps);
9158 	obj->nr_maps = 0;
9159 
9160 	if (obj->programs && obj->nr_programs) {
9161 		for (i = 0; i < obj->nr_programs; i++)
9162 			bpf_program__exit(&obj->programs[i]);
9163 	}
9164 	zfree(&obj->programs);
9165 
9166 	zfree(&obj->feat_cache);
9167 	zfree(&obj->token_path);
9168 	if (obj->token_fd > 0)
9169 		close(obj->token_fd);
9170 
9171 	zfree(&obj->arena_data);
9172 
9173 	free(obj);
9174 }
9175 
9176 const char *bpf_object__name(const struct bpf_object *obj)
9177 {
9178 	return obj ? obj->name : libbpf_err_ptr(-EINVAL);
9179 }
9180 
9181 unsigned int bpf_object__kversion(const struct bpf_object *obj)
9182 {
9183 	return obj ? obj->kern_version : 0;
9184 }
9185 
9186 int bpf_object__token_fd(const struct bpf_object *obj)
9187 {
9188 	return obj->token_fd ?: -1;
9189 }
9190 
9191 struct btf *bpf_object__btf(const struct bpf_object *obj)
9192 {
9193 	return obj ? obj->btf : NULL;
9194 }
9195 
9196 int bpf_object__btf_fd(const struct bpf_object *obj)
9197 {
9198 	return obj->btf ? btf__fd(obj->btf) : -1;
9199 }
9200 
9201 int bpf_object__set_kversion(struct bpf_object *obj, __u32 kern_version)
9202 {
9203 	if (obj->state >= OBJ_LOADED)
9204 		return libbpf_err(-EINVAL);
9205 
9206 	obj->kern_version = kern_version;
9207 
9208 	return 0;
9209 }
9210 
9211 int bpf_object__gen_loader(struct bpf_object *obj, struct gen_loader_opts *opts)
9212 {
9213 	struct bpf_gen *gen;
9214 
9215 	if (!opts)
9216 		return libbpf_err(-EFAULT);
9217 	if (!OPTS_VALID(opts, gen_loader_opts))
9218 		return libbpf_err(-EINVAL);
9219 	gen = calloc(sizeof(*gen), 1);
9220 	if (!gen)
9221 		return libbpf_err(-ENOMEM);
9222 	gen->opts = opts;
9223 	gen->swapped_endian = !is_native_endianness(obj);
9224 	obj->gen_loader = gen;
9225 	return 0;
9226 }
9227 
9228 static struct bpf_program *
9229 __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
9230 		    bool forward)
9231 {
9232 	size_t nr_programs = obj->nr_programs;
9233 	ssize_t idx;
9234 
9235 	if (!nr_programs)
9236 		return NULL;
9237 
9238 	if (!p)
9239 		/* Iter from the beginning */
9240 		return forward ? &obj->programs[0] :
9241 			&obj->programs[nr_programs - 1];
9242 
9243 	if (p->obj != obj) {
9244 		pr_warn("error: program handler doesn't match object\n");
9245 		return errno = EINVAL, NULL;
9246 	}
9247 
9248 	idx = (p - obj->programs) + (forward ? 1 : -1);
9249 	if (idx >= obj->nr_programs || idx < 0)
9250 		return NULL;
9251 	return &obj->programs[idx];
9252 }
9253 
9254 struct bpf_program *
9255 bpf_object__next_program(const struct bpf_object *obj, struct bpf_program *prev)
9256 {
9257 	struct bpf_program *prog = prev;
9258 
9259 	do {
9260 		prog = __bpf_program__iter(prog, obj, true);
9261 	} while (prog && prog_is_subprog(obj, prog));
9262 
9263 	return prog;
9264 }
9265 
9266 struct bpf_program *
9267 bpf_object__prev_program(const struct bpf_object *obj, struct bpf_program *next)
9268 {
9269 	struct bpf_program *prog = next;
9270 
9271 	do {
9272 		prog = __bpf_program__iter(prog, obj, false);
9273 	} while (prog && prog_is_subprog(obj, prog));
9274 
9275 	return prog;
9276 }
9277 
9278 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
9279 {
9280 	prog->prog_ifindex = ifindex;
9281 }
9282 
9283 const char *bpf_program__name(const struct bpf_program *prog)
9284 {
9285 	return prog->name;
9286 }
9287 
9288 const char *bpf_program__section_name(const struct bpf_program *prog)
9289 {
9290 	return prog->sec_name;
9291 }
9292 
9293 bool bpf_program__autoload(const struct bpf_program *prog)
9294 {
9295 	return prog->autoload;
9296 }
9297 
9298 int bpf_program__set_autoload(struct bpf_program *prog, bool autoload)
9299 {
9300 	if (prog->obj->state >= OBJ_LOADED)
9301 		return libbpf_err(-EINVAL);
9302 
9303 	prog->autoload = autoload;
9304 	return 0;
9305 }
9306 
9307 bool bpf_program__autoattach(const struct bpf_program *prog)
9308 {
9309 	return prog->autoattach;
9310 }
9311 
9312 void bpf_program__set_autoattach(struct bpf_program *prog, bool autoattach)
9313 {
9314 	prog->autoattach = autoattach;
9315 }
9316 
9317 const struct bpf_insn *bpf_program__insns(const struct bpf_program *prog)
9318 {
9319 	return prog->insns;
9320 }
9321 
9322 size_t bpf_program__insn_cnt(const struct bpf_program *prog)
9323 {
9324 	return prog->insns_cnt;
9325 }
9326 
9327 int bpf_program__set_insns(struct bpf_program *prog,
9328 			   struct bpf_insn *new_insns, size_t new_insn_cnt)
9329 {
9330 	struct bpf_insn *insns;
9331 
9332 	if (prog->obj->state >= OBJ_LOADED)
9333 		return libbpf_err(-EBUSY);
9334 
9335 	insns = libbpf_reallocarray(prog->insns, new_insn_cnt, sizeof(*insns));
9336 	/* NULL is a valid return from reallocarray if the new count is zero */
9337 	if (!insns && new_insn_cnt) {
9338 		pr_warn("prog '%s': failed to realloc prog code\n", prog->name);
9339 		return libbpf_err(-ENOMEM);
9340 	}
9341 	memcpy(insns, new_insns, new_insn_cnt * sizeof(*insns));
9342 
9343 	prog->insns = insns;
9344 	prog->insns_cnt = new_insn_cnt;
9345 	return 0;
9346 }
9347 
9348 int bpf_program__fd(const struct bpf_program *prog)
9349 {
9350 	if (!prog)
9351 		return libbpf_err(-EINVAL);
9352 
9353 	if (prog->fd < 0)
9354 		return libbpf_err(-ENOENT);
9355 
9356 	return prog->fd;
9357 }
9358 
9359 __alias(bpf_program__type)
9360 enum bpf_prog_type bpf_program__get_type(const struct bpf_program *prog);
9361 
9362 enum bpf_prog_type bpf_program__type(const struct bpf_program *prog)
9363 {
9364 	return prog->type;
9365 }
9366 
9367 static size_t custom_sec_def_cnt;
9368 static struct bpf_sec_def *custom_sec_defs;
9369 static struct bpf_sec_def custom_fallback_def;
9370 static bool has_custom_fallback_def;
9371 static int last_custom_sec_def_handler_id;
9372 
9373 int bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
9374 {
9375 	if (prog->obj->state >= OBJ_LOADED)
9376 		return libbpf_err(-EBUSY);
9377 
9378 	/* if type is not changed, do nothing */
9379 	if (prog->type == type)
9380 		return 0;
9381 
9382 	prog->type = type;
9383 
9384 	/* If a program type was changed, we need to reset associated SEC()
9385 	 * handler, as it will be invalid now. The only exception is a generic
9386 	 * fallback handler, which by definition is program type-agnostic and
9387 	 * is a catch-all custom handler, optionally set by the application,
9388 	 * so should be able to handle any type of BPF program.
9389 	 */
9390 	if (prog->sec_def != &custom_fallback_def)
9391 		prog->sec_def = NULL;
9392 	return 0;
9393 }
9394 
9395 __alias(bpf_program__expected_attach_type)
9396 enum bpf_attach_type bpf_program__get_expected_attach_type(const struct bpf_program *prog);
9397 
9398 enum bpf_attach_type bpf_program__expected_attach_type(const struct bpf_program *prog)
9399 {
9400 	return prog->expected_attach_type;
9401 }
9402 
9403 int bpf_program__set_expected_attach_type(struct bpf_program *prog,
9404 					   enum bpf_attach_type type)
9405 {
9406 	if (prog->obj->state >= OBJ_LOADED)
9407 		return libbpf_err(-EBUSY);
9408 
9409 	prog->expected_attach_type = type;
9410 	return 0;
9411 }
9412 
9413 __u32 bpf_program__flags(const struct bpf_program *prog)
9414 {
9415 	return prog->prog_flags;
9416 }
9417 
9418 int bpf_program__set_flags(struct bpf_program *prog, __u32 flags)
9419 {
9420 	if (prog->obj->state >= OBJ_LOADED)
9421 		return libbpf_err(-EBUSY);
9422 
9423 	prog->prog_flags = flags;
9424 	return 0;
9425 }
9426 
9427 __u32 bpf_program__log_level(const struct bpf_program *prog)
9428 {
9429 	return prog->log_level;
9430 }
9431 
9432 int bpf_program__set_log_level(struct bpf_program *prog, __u32 log_level)
9433 {
9434 	if (prog->obj->state >= OBJ_LOADED)
9435 		return libbpf_err(-EBUSY);
9436 
9437 	prog->log_level = log_level;
9438 	return 0;
9439 }
9440 
9441 const char *bpf_program__log_buf(const struct bpf_program *prog, size_t *log_size)
9442 {
9443 	*log_size = prog->log_size;
9444 	return prog->log_buf;
9445 }
9446 
9447 int bpf_program__set_log_buf(struct bpf_program *prog, char *log_buf, size_t log_size)
9448 {
9449 	if (log_size && !log_buf)
9450 		return libbpf_err(-EINVAL);
9451 	if (prog->log_size > UINT_MAX)
9452 		return libbpf_err(-EINVAL);
9453 	if (prog->obj->state >= OBJ_LOADED)
9454 		return libbpf_err(-EBUSY);
9455 
9456 	prog->log_buf = log_buf;
9457 	prog->log_size = log_size;
9458 	return 0;
9459 }
9460 
9461 struct bpf_func_info *bpf_program__func_info(const struct bpf_program *prog)
9462 {
9463 	if (prog->func_info_rec_size != sizeof(struct bpf_func_info))
9464 		return libbpf_err_ptr(-EOPNOTSUPP);
9465 	return prog->func_info;
9466 }
9467 
9468 __u32 bpf_program__func_info_cnt(const struct bpf_program *prog)
9469 {
9470 	return prog->func_info_cnt;
9471 }
9472 
9473 struct bpf_line_info *bpf_program__line_info(const struct bpf_program *prog)
9474 {
9475 	if (prog->line_info_rec_size != sizeof(struct bpf_line_info))
9476 		return libbpf_err_ptr(-EOPNOTSUPP);
9477 	return prog->line_info;
9478 }
9479 
9480 __u32 bpf_program__line_info_cnt(const struct bpf_program *prog)
9481 {
9482 	return prog->line_info_cnt;
9483 }
9484 
9485 #define SEC_DEF(sec_pfx, ptype, atype, flags, ...) {			    \
9486 	.sec = (char *)sec_pfx,						    \
9487 	.prog_type = BPF_PROG_TYPE_##ptype,				    \
9488 	.expected_attach_type = atype,					    \
9489 	.cookie = (long)(flags),					    \
9490 	.prog_prepare_load_fn = libbpf_prepare_prog_load,		    \
9491 	__VA_ARGS__							    \
9492 }
9493 
9494 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9495 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9496 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9497 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9498 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9499 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9500 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9501 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9502 static int attach_kprobe_session(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9503 static int attach_uprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9504 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9505 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9506 
9507 static const struct bpf_sec_def section_defs[] = {
9508 	SEC_DEF("socket",		SOCKET_FILTER, 0, SEC_NONE),
9509 	SEC_DEF("sk_reuseport/migrate",	SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT_OR_MIGRATE, SEC_ATTACHABLE),
9510 	SEC_DEF("sk_reuseport",		SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT, SEC_ATTACHABLE),
9511 	SEC_DEF("kprobe+",		KPROBE,	0, SEC_NONE, attach_kprobe),
9512 	SEC_DEF("uprobe+",		KPROBE,	0, SEC_NONE, attach_uprobe),
9513 	SEC_DEF("uprobe.s+",		KPROBE,	0, SEC_SLEEPABLE, attach_uprobe),
9514 	SEC_DEF("kretprobe+",		KPROBE, 0, SEC_NONE, attach_kprobe),
9515 	SEC_DEF("uretprobe+",		KPROBE, 0, SEC_NONE, attach_uprobe),
9516 	SEC_DEF("uretprobe.s+",		KPROBE, 0, SEC_SLEEPABLE, attach_uprobe),
9517 	SEC_DEF("kprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
9518 	SEC_DEF("kretprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
9519 	SEC_DEF("kprobe.session+",	KPROBE,	BPF_TRACE_KPROBE_SESSION, SEC_NONE, attach_kprobe_session),
9520 	SEC_DEF("uprobe.multi+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_NONE, attach_uprobe_multi),
9521 	SEC_DEF("uretprobe.multi+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_NONE, attach_uprobe_multi),
9522 	SEC_DEF("uprobe.session+",	KPROBE,	BPF_TRACE_UPROBE_SESSION, SEC_NONE, attach_uprobe_multi),
9523 	SEC_DEF("uprobe.multi.s+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_SLEEPABLE, attach_uprobe_multi),
9524 	SEC_DEF("uretprobe.multi.s+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_SLEEPABLE, attach_uprobe_multi),
9525 	SEC_DEF("uprobe.session.s+",	KPROBE,	BPF_TRACE_UPROBE_SESSION, SEC_SLEEPABLE, attach_uprobe_multi),
9526 	SEC_DEF("ksyscall+",		KPROBE,	0, SEC_NONE, attach_ksyscall),
9527 	SEC_DEF("kretsyscall+",		KPROBE, 0, SEC_NONE, attach_ksyscall),
9528 	SEC_DEF("usdt+",		KPROBE,	0, SEC_USDT, attach_usdt),
9529 	SEC_DEF("usdt.s+",		KPROBE,	0, SEC_USDT | SEC_SLEEPABLE, attach_usdt),
9530 	SEC_DEF("tc/ingress",		SCHED_CLS, BPF_TCX_INGRESS, SEC_NONE), /* alias for tcx */
9531 	SEC_DEF("tc/egress",		SCHED_CLS, BPF_TCX_EGRESS, SEC_NONE),  /* alias for tcx */
9532 	SEC_DEF("tcx/ingress",		SCHED_CLS, BPF_TCX_INGRESS, SEC_NONE),
9533 	SEC_DEF("tcx/egress",		SCHED_CLS, BPF_TCX_EGRESS, SEC_NONE),
9534 	SEC_DEF("tc",			SCHED_CLS, 0, SEC_NONE), /* deprecated / legacy, use tcx */
9535 	SEC_DEF("classifier",		SCHED_CLS, 0, SEC_NONE), /* deprecated / legacy, use tcx */
9536 	SEC_DEF("action",		SCHED_ACT, 0, SEC_NONE), /* deprecated / legacy, use tcx */
9537 	SEC_DEF("netkit/primary",	SCHED_CLS, BPF_NETKIT_PRIMARY, SEC_NONE),
9538 	SEC_DEF("netkit/peer",		SCHED_CLS, BPF_NETKIT_PEER, SEC_NONE),
9539 	SEC_DEF("tracepoint+",		TRACEPOINT, 0, SEC_NONE, attach_tp),
9540 	SEC_DEF("tp+",			TRACEPOINT, 0, SEC_NONE, attach_tp),
9541 	SEC_DEF("raw_tracepoint+",	RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
9542 	SEC_DEF("raw_tp+",		RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
9543 	SEC_DEF("raw_tracepoint.w+",	RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
9544 	SEC_DEF("raw_tp.w+",		RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
9545 	SEC_DEF("tp_btf+",		TRACING, BPF_TRACE_RAW_TP, SEC_ATTACH_BTF, attach_trace),
9546 	SEC_DEF("fentry+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF, attach_trace),
9547 	SEC_DEF("fmod_ret+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF, attach_trace),
9548 	SEC_DEF("fexit+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF, attach_trace),
9549 	SEC_DEF("fentry.s+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
9550 	SEC_DEF("fmod_ret.s+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
9551 	SEC_DEF("fexit.s+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
9552 	SEC_DEF("freplace+",		EXT, 0, SEC_ATTACH_BTF, attach_trace),
9553 	SEC_DEF("lsm+",			LSM, BPF_LSM_MAC, SEC_ATTACH_BTF, attach_lsm),
9554 	SEC_DEF("lsm.s+",		LSM, BPF_LSM_MAC, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_lsm),
9555 	SEC_DEF("lsm_cgroup+",		LSM, BPF_LSM_CGROUP, SEC_ATTACH_BTF),
9556 	SEC_DEF("iter+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF, attach_iter),
9557 	SEC_DEF("iter.s+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_iter),
9558 	SEC_DEF("syscall",		SYSCALL, 0, SEC_SLEEPABLE),
9559 	SEC_DEF("xdp.frags/devmap",	XDP, BPF_XDP_DEVMAP, SEC_XDP_FRAGS),
9560 	SEC_DEF("xdp/devmap",		XDP, BPF_XDP_DEVMAP, SEC_ATTACHABLE),
9561 	SEC_DEF("xdp.frags/cpumap",	XDP, BPF_XDP_CPUMAP, SEC_XDP_FRAGS),
9562 	SEC_DEF("xdp/cpumap",		XDP, BPF_XDP_CPUMAP, SEC_ATTACHABLE),
9563 	SEC_DEF("xdp.frags",		XDP, BPF_XDP, SEC_XDP_FRAGS),
9564 	SEC_DEF("xdp",			XDP, BPF_XDP, SEC_ATTACHABLE_OPT),
9565 	SEC_DEF("perf_event",		PERF_EVENT, 0, SEC_NONE),
9566 	SEC_DEF("lwt_in",		LWT_IN, 0, SEC_NONE),
9567 	SEC_DEF("lwt_out",		LWT_OUT, 0, SEC_NONE),
9568 	SEC_DEF("lwt_xmit",		LWT_XMIT, 0, SEC_NONE),
9569 	SEC_DEF("lwt_seg6local",	LWT_SEG6LOCAL, 0, SEC_NONE),
9570 	SEC_DEF("sockops",		SOCK_OPS, BPF_CGROUP_SOCK_OPS, SEC_ATTACHABLE_OPT),
9571 	SEC_DEF("sk_skb/stream_parser",	SK_SKB, BPF_SK_SKB_STREAM_PARSER, SEC_ATTACHABLE_OPT),
9572 	SEC_DEF("sk_skb/stream_verdict",SK_SKB, BPF_SK_SKB_STREAM_VERDICT, SEC_ATTACHABLE_OPT),
9573 	SEC_DEF("sk_skb/verdict",	SK_SKB, BPF_SK_SKB_VERDICT, SEC_ATTACHABLE_OPT),
9574 	SEC_DEF("sk_skb",		SK_SKB, 0, SEC_NONE),
9575 	SEC_DEF("sk_msg",		SK_MSG, BPF_SK_MSG_VERDICT, SEC_ATTACHABLE_OPT),
9576 	SEC_DEF("lirc_mode2",		LIRC_MODE2, BPF_LIRC_MODE2, SEC_ATTACHABLE_OPT),
9577 	SEC_DEF("flow_dissector",	FLOW_DISSECTOR, BPF_FLOW_DISSECTOR, SEC_ATTACHABLE_OPT),
9578 	SEC_DEF("cgroup_skb/ingress",	CGROUP_SKB, BPF_CGROUP_INET_INGRESS, SEC_ATTACHABLE_OPT),
9579 	SEC_DEF("cgroup_skb/egress",	CGROUP_SKB, BPF_CGROUP_INET_EGRESS, SEC_ATTACHABLE_OPT),
9580 	SEC_DEF("cgroup/skb",		CGROUP_SKB, 0, SEC_NONE),
9581 	SEC_DEF("cgroup/sock_create",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE),
9582 	SEC_DEF("cgroup/sock_release",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_RELEASE, SEC_ATTACHABLE),
9583 	SEC_DEF("cgroup/sock",		CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE_OPT),
9584 	SEC_DEF("cgroup/post_bind4",	CGROUP_SOCK, BPF_CGROUP_INET4_POST_BIND, SEC_ATTACHABLE),
9585 	SEC_DEF("cgroup/post_bind6",	CGROUP_SOCK, BPF_CGROUP_INET6_POST_BIND, SEC_ATTACHABLE),
9586 	SEC_DEF("cgroup/bind4",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND, SEC_ATTACHABLE),
9587 	SEC_DEF("cgroup/bind6",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND, SEC_ATTACHABLE),
9588 	SEC_DEF("cgroup/connect4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT, SEC_ATTACHABLE),
9589 	SEC_DEF("cgroup/connect6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT, SEC_ATTACHABLE),
9590 	SEC_DEF("cgroup/connect_unix",	CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_CONNECT, SEC_ATTACHABLE),
9591 	SEC_DEF("cgroup/sendmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG, SEC_ATTACHABLE),
9592 	SEC_DEF("cgroup/sendmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG, SEC_ATTACHABLE),
9593 	SEC_DEF("cgroup/sendmsg_unix",	CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_SENDMSG, SEC_ATTACHABLE),
9594 	SEC_DEF("cgroup/recvmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_RECVMSG, SEC_ATTACHABLE),
9595 	SEC_DEF("cgroup/recvmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_RECVMSG, SEC_ATTACHABLE),
9596 	SEC_DEF("cgroup/recvmsg_unix",	CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_RECVMSG, SEC_ATTACHABLE),
9597 	SEC_DEF("cgroup/getpeername4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETPEERNAME, SEC_ATTACHABLE),
9598 	SEC_DEF("cgroup/getpeername6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETPEERNAME, SEC_ATTACHABLE),
9599 	SEC_DEF("cgroup/getpeername_unix", CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_GETPEERNAME, SEC_ATTACHABLE),
9600 	SEC_DEF("cgroup/getsockname4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETSOCKNAME, SEC_ATTACHABLE),
9601 	SEC_DEF("cgroup/getsockname6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETSOCKNAME, SEC_ATTACHABLE),
9602 	SEC_DEF("cgroup/getsockname_unix", CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_GETSOCKNAME, SEC_ATTACHABLE),
9603 	SEC_DEF("cgroup/sysctl",	CGROUP_SYSCTL, BPF_CGROUP_SYSCTL, SEC_ATTACHABLE),
9604 	SEC_DEF("cgroup/getsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_GETSOCKOPT, SEC_ATTACHABLE),
9605 	SEC_DEF("cgroup/setsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_SETSOCKOPT, SEC_ATTACHABLE),
9606 	SEC_DEF("cgroup/dev",		CGROUP_DEVICE, BPF_CGROUP_DEVICE, SEC_ATTACHABLE_OPT),
9607 	SEC_DEF("struct_ops+",		STRUCT_OPS, 0, SEC_NONE),
9608 	SEC_DEF("struct_ops.s+",	STRUCT_OPS, 0, SEC_SLEEPABLE),
9609 	SEC_DEF("sk_lookup",		SK_LOOKUP, BPF_SK_LOOKUP, SEC_ATTACHABLE),
9610 	SEC_DEF("netfilter",		NETFILTER, BPF_NETFILTER, SEC_NONE),
9611 };
9612 
9613 int libbpf_register_prog_handler(const char *sec,
9614 				 enum bpf_prog_type prog_type,
9615 				 enum bpf_attach_type exp_attach_type,
9616 				 const struct libbpf_prog_handler_opts *opts)
9617 {
9618 	struct bpf_sec_def *sec_def;
9619 
9620 	if (!OPTS_VALID(opts, libbpf_prog_handler_opts))
9621 		return libbpf_err(-EINVAL);
9622 
9623 	if (last_custom_sec_def_handler_id == INT_MAX) /* prevent overflow */
9624 		return libbpf_err(-E2BIG);
9625 
9626 	if (sec) {
9627 		sec_def = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt + 1,
9628 					      sizeof(*sec_def));
9629 		if (!sec_def)
9630 			return libbpf_err(-ENOMEM);
9631 
9632 		custom_sec_defs = sec_def;
9633 		sec_def = &custom_sec_defs[custom_sec_def_cnt];
9634 	} else {
9635 		if (has_custom_fallback_def)
9636 			return libbpf_err(-EBUSY);
9637 
9638 		sec_def = &custom_fallback_def;
9639 	}
9640 
9641 	sec_def->sec = sec ? strdup(sec) : NULL;
9642 	if (sec && !sec_def->sec)
9643 		return libbpf_err(-ENOMEM);
9644 
9645 	sec_def->prog_type = prog_type;
9646 	sec_def->expected_attach_type = exp_attach_type;
9647 	sec_def->cookie = OPTS_GET(opts, cookie, 0);
9648 
9649 	sec_def->prog_setup_fn = OPTS_GET(opts, prog_setup_fn, NULL);
9650 	sec_def->prog_prepare_load_fn = OPTS_GET(opts, prog_prepare_load_fn, NULL);
9651 	sec_def->prog_attach_fn = OPTS_GET(opts, prog_attach_fn, NULL);
9652 
9653 	sec_def->handler_id = ++last_custom_sec_def_handler_id;
9654 
9655 	if (sec)
9656 		custom_sec_def_cnt++;
9657 	else
9658 		has_custom_fallback_def = true;
9659 
9660 	return sec_def->handler_id;
9661 }
9662 
9663 int libbpf_unregister_prog_handler(int handler_id)
9664 {
9665 	struct bpf_sec_def *sec_defs;
9666 	int i;
9667 
9668 	if (handler_id <= 0)
9669 		return libbpf_err(-EINVAL);
9670 
9671 	if (has_custom_fallback_def && custom_fallback_def.handler_id == handler_id) {
9672 		memset(&custom_fallback_def, 0, sizeof(custom_fallback_def));
9673 		has_custom_fallback_def = false;
9674 		return 0;
9675 	}
9676 
9677 	for (i = 0; i < custom_sec_def_cnt; i++) {
9678 		if (custom_sec_defs[i].handler_id == handler_id)
9679 			break;
9680 	}
9681 
9682 	if (i == custom_sec_def_cnt)
9683 		return libbpf_err(-ENOENT);
9684 
9685 	free(custom_sec_defs[i].sec);
9686 	for (i = i + 1; i < custom_sec_def_cnt; i++)
9687 		custom_sec_defs[i - 1] = custom_sec_defs[i];
9688 	custom_sec_def_cnt--;
9689 
9690 	/* try to shrink the array, but it's ok if we couldn't */
9691 	sec_defs = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt, sizeof(*sec_defs));
9692 	/* if new count is zero, reallocarray can return a valid NULL result;
9693 	 * in this case the previous pointer will be freed, so we *have to*
9694 	 * reassign old pointer to the new value (even if it's NULL)
9695 	 */
9696 	if (sec_defs || custom_sec_def_cnt == 0)
9697 		custom_sec_defs = sec_defs;
9698 
9699 	return 0;
9700 }
9701 
9702 static bool sec_def_matches(const struct bpf_sec_def *sec_def, const char *sec_name)
9703 {
9704 	size_t len = strlen(sec_def->sec);
9705 
9706 	/* "type/" always has to have proper SEC("type/extras") form */
9707 	if (sec_def->sec[len - 1] == '/') {
9708 		if (str_has_pfx(sec_name, sec_def->sec))
9709 			return true;
9710 		return false;
9711 	}
9712 
9713 	/* "type+" means it can be either exact SEC("type") or
9714 	 * well-formed SEC("type/extras") with proper '/' separator
9715 	 */
9716 	if (sec_def->sec[len - 1] == '+') {
9717 		len--;
9718 		/* not even a prefix */
9719 		if (strncmp(sec_name, sec_def->sec, len) != 0)
9720 			return false;
9721 		/* exact match or has '/' separator */
9722 		if (sec_name[len] == '\0' || sec_name[len] == '/')
9723 			return true;
9724 		return false;
9725 	}
9726 
9727 	return strcmp(sec_name, sec_def->sec) == 0;
9728 }
9729 
9730 static const struct bpf_sec_def *find_sec_def(const char *sec_name)
9731 {
9732 	const struct bpf_sec_def *sec_def;
9733 	int i, n;
9734 
9735 	n = custom_sec_def_cnt;
9736 	for (i = 0; i < n; i++) {
9737 		sec_def = &custom_sec_defs[i];
9738 		if (sec_def_matches(sec_def, sec_name))
9739 			return sec_def;
9740 	}
9741 
9742 	n = ARRAY_SIZE(section_defs);
9743 	for (i = 0; i < n; i++) {
9744 		sec_def = &section_defs[i];
9745 		if (sec_def_matches(sec_def, sec_name))
9746 			return sec_def;
9747 	}
9748 
9749 	if (has_custom_fallback_def)
9750 		return &custom_fallback_def;
9751 
9752 	return NULL;
9753 }
9754 
9755 #define MAX_TYPE_NAME_SIZE 32
9756 
9757 static char *libbpf_get_type_names(bool attach_type)
9758 {
9759 	int i, len = ARRAY_SIZE(section_defs) * MAX_TYPE_NAME_SIZE;
9760 	char *buf;
9761 
9762 	buf = malloc(len);
9763 	if (!buf)
9764 		return NULL;
9765 
9766 	buf[0] = '\0';
9767 	/* Forge string buf with all available names */
9768 	for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
9769 		const struct bpf_sec_def *sec_def = &section_defs[i];
9770 
9771 		if (attach_type) {
9772 			if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
9773 				continue;
9774 
9775 			if (!(sec_def->cookie & SEC_ATTACHABLE))
9776 				continue;
9777 		}
9778 
9779 		if (strlen(buf) + strlen(section_defs[i].sec) + 2 > len) {
9780 			free(buf);
9781 			return NULL;
9782 		}
9783 		strcat(buf, " ");
9784 		strcat(buf, section_defs[i].sec);
9785 	}
9786 
9787 	return buf;
9788 }
9789 
9790 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
9791 			     enum bpf_attach_type *expected_attach_type)
9792 {
9793 	const struct bpf_sec_def *sec_def;
9794 	char *type_names;
9795 
9796 	if (!name)
9797 		return libbpf_err(-EINVAL);
9798 
9799 	sec_def = find_sec_def(name);
9800 	if (sec_def) {
9801 		*prog_type = sec_def->prog_type;
9802 		*expected_attach_type = sec_def->expected_attach_type;
9803 		return 0;
9804 	}
9805 
9806 	pr_debug("failed to guess program type from ELF section '%s'\n", name);
9807 	type_names = libbpf_get_type_names(false);
9808 	if (type_names != NULL) {
9809 		pr_debug("supported section(type) names are:%s\n", type_names);
9810 		free(type_names);
9811 	}
9812 
9813 	return libbpf_err(-ESRCH);
9814 }
9815 
9816 const char *libbpf_bpf_attach_type_str(enum bpf_attach_type t)
9817 {
9818 	if (t < 0 || t >= ARRAY_SIZE(attach_type_name))
9819 		return NULL;
9820 
9821 	return attach_type_name[t];
9822 }
9823 
9824 const char *libbpf_bpf_link_type_str(enum bpf_link_type t)
9825 {
9826 	if (t < 0 || t >= ARRAY_SIZE(link_type_name))
9827 		return NULL;
9828 
9829 	return link_type_name[t];
9830 }
9831 
9832 const char *libbpf_bpf_map_type_str(enum bpf_map_type t)
9833 {
9834 	if (t < 0 || t >= ARRAY_SIZE(map_type_name))
9835 		return NULL;
9836 
9837 	return map_type_name[t];
9838 }
9839 
9840 const char *libbpf_bpf_prog_type_str(enum bpf_prog_type t)
9841 {
9842 	if (t < 0 || t >= ARRAY_SIZE(prog_type_name))
9843 		return NULL;
9844 
9845 	return prog_type_name[t];
9846 }
9847 
9848 static struct bpf_map *find_struct_ops_map_by_offset(struct bpf_object *obj,
9849 						     int sec_idx,
9850 						     size_t offset)
9851 {
9852 	struct bpf_map *map;
9853 	size_t i;
9854 
9855 	for (i = 0; i < obj->nr_maps; i++) {
9856 		map = &obj->maps[i];
9857 		if (!bpf_map__is_struct_ops(map))
9858 			continue;
9859 		if (map->sec_idx == sec_idx &&
9860 		    map->sec_offset <= offset &&
9861 		    offset - map->sec_offset < map->def.value_size)
9862 			return map;
9863 	}
9864 
9865 	return NULL;
9866 }
9867 
9868 /* Collect the reloc from ELF, populate the st_ops->progs[], and update
9869  * st_ops->data for shadow type.
9870  */
9871 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
9872 					    Elf64_Shdr *shdr, Elf_Data *data)
9873 {
9874 	const struct btf_type *type;
9875 	const struct btf_member *member;
9876 	struct bpf_struct_ops *st_ops;
9877 	struct bpf_program *prog;
9878 	unsigned int shdr_idx;
9879 	const struct btf *btf;
9880 	struct bpf_map *map;
9881 	unsigned int moff, insn_idx;
9882 	const char *name;
9883 	__u32 member_idx;
9884 	Elf64_Sym *sym;
9885 	Elf64_Rel *rel;
9886 	int i, nrels;
9887 
9888 	btf = obj->btf;
9889 	nrels = shdr->sh_size / shdr->sh_entsize;
9890 	for (i = 0; i < nrels; i++) {
9891 		rel = elf_rel_by_idx(data, i);
9892 		if (!rel) {
9893 			pr_warn("struct_ops reloc: failed to get %d reloc\n", i);
9894 			return -LIBBPF_ERRNO__FORMAT;
9895 		}
9896 
9897 		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
9898 		if (!sym) {
9899 			pr_warn("struct_ops reloc: symbol %zx not found\n",
9900 				(size_t)ELF64_R_SYM(rel->r_info));
9901 			return -LIBBPF_ERRNO__FORMAT;
9902 		}
9903 
9904 		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
9905 		map = find_struct_ops_map_by_offset(obj, shdr->sh_info, rel->r_offset);
9906 		if (!map) {
9907 			pr_warn("struct_ops reloc: cannot find map at rel->r_offset %zu\n",
9908 				(size_t)rel->r_offset);
9909 			return -EINVAL;
9910 		}
9911 
9912 		moff = rel->r_offset - map->sec_offset;
9913 		shdr_idx = sym->st_shndx;
9914 		st_ops = map->st_ops;
9915 		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",
9916 			 map->name,
9917 			 (long long)(rel->r_info >> 32),
9918 			 (long long)sym->st_value,
9919 			 shdr_idx, (size_t)rel->r_offset,
9920 			 map->sec_offset, sym->st_name, name);
9921 
9922 		if (shdr_idx >= SHN_LORESERVE) {
9923 			pr_warn("struct_ops reloc %s: rel->r_offset %zu shdr_idx %u unsupported non-static function\n",
9924 				map->name, (size_t)rel->r_offset, shdr_idx);
9925 			return -LIBBPF_ERRNO__RELOC;
9926 		}
9927 		if (sym->st_value % BPF_INSN_SZ) {
9928 			pr_warn("struct_ops reloc %s: invalid target program offset %llu\n",
9929 				map->name, (unsigned long long)sym->st_value);
9930 			return -LIBBPF_ERRNO__FORMAT;
9931 		}
9932 		insn_idx = sym->st_value / BPF_INSN_SZ;
9933 
9934 		type = btf__type_by_id(btf, st_ops->type_id);
9935 		member = find_member_by_offset(type, moff * 8);
9936 		if (!member) {
9937 			pr_warn("struct_ops reloc %s: cannot find member at moff %u\n",
9938 				map->name, moff);
9939 			return -EINVAL;
9940 		}
9941 		member_idx = member - btf_members(type);
9942 		name = btf__name_by_offset(btf, member->name_off);
9943 
9944 		if (!resolve_func_ptr(btf, member->type, NULL)) {
9945 			pr_warn("struct_ops reloc %s: cannot relocate non func ptr %s\n",
9946 				map->name, name);
9947 			return -EINVAL;
9948 		}
9949 
9950 		prog = find_prog_by_sec_insn(obj, shdr_idx, insn_idx);
9951 		if (!prog) {
9952 			pr_warn("struct_ops reloc %s: cannot find prog at shdr_idx %u to relocate func ptr %s\n",
9953 				map->name, shdr_idx, name);
9954 			return -EINVAL;
9955 		}
9956 
9957 		/* prevent the use of BPF prog with invalid type */
9958 		if (prog->type != BPF_PROG_TYPE_STRUCT_OPS) {
9959 			pr_warn("struct_ops reloc %s: prog %s is not struct_ops BPF program\n",
9960 				map->name, prog->name);
9961 			return -EINVAL;
9962 		}
9963 
9964 		st_ops->progs[member_idx] = prog;
9965 
9966 		/* st_ops->data will be exposed to users, being returned by
9967 		 * bpf_map__initial_value() as a pointer to the shadow
9968 		 * type. All function pointers in the original struct type
9969 		 * should be converted to a pointer to struct bpf_program
9970 		 * in the shadow type.
9971 		 */
9972 		*((struct bpf_program **)(st_ops->data + moff)) = prog;
9973 	}
9974 
9975 	return 0;
9976 }
9977 
9978 #define BTF_TRACE_PREFIX "btf_trace_"
9979 #define BTF_LSM_PREFIX "bpf_lsm_"
9980 #define BTF_ITER_PREFIX "bpf_iter_"
9981 #define BTF_MAX_NAME_SIZE 128
9982 
9983 void btf_get_kernel_prefix_kind(enum bpf_attach_type attach_type,
9984 				const char **prefix, int *kind)
9985 {
9986 	switch (attach_type) {
9987 	case BPF_TRACE_RAW_TP:
9988 		*prefix = BTF_TRACE_PREFIX;
9989 		*kind = BTF_KIND_TYPEDEF;
9990 		break;
9991 	case BPF_LSM_MAC:
9992 	case BPF_LSM_CGROUP:
9993 		*prefix = BTF_LSM_PREFIX;
9994 		*kind = BTF_KIND_FUNC;
9995 		break;
9996 	case BPF_TRACE_ITER:
9997 		*prefix = BTF_ITER_PREFIX;
9998 		*kind = BTF_KIND_FUNC;
9999 		break;
10000 	default:
10001 		*prefix = "";
10002 		*kind = BTF_KIND_FUNC;
10003 	}
10004 }
10005 
10006 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
10007 				   const char *name, __u32 kind)
10008 {
10009 	char btf_type_name[BTF_MAX_NAME_SIZE];
10010 	int ret;
10011 
10012 	ret = snprintf(btf_type_name, sizeof(btf_type_name),
10013 		       "%s%s", prefix, name);
10014 	/* snprintf returns the number of characters written excluding the
10015 	 * terminating null. So, if >= BTF_MAX_NAME_SIZE are written, it
10016 	 * indicates truncation.
10017 	 */
10018 	if (ret < 0 || ret >= sizeof(btf_type_name))
10019 		return -ENAMETOOLONG;
10020 	return btf__find_by_name_kind(btf, btf_type_name, kind);
10021 }
10022 
10023 static inline int find_attach_btf_id(struct btf *btf, const char *name,
10024 				     enum bpf_attach_type attach_type)
10025 {
10026 	const char *prefix;
10027 	int kind;
10028 
10029 	btf_get_kernel_prefix_kind(attach_type, &prefix, &kind);
10030 	return find_btf_by_prefix_kind(btf, prefix, name, kind);
10031 }
10032 
10033 int libbpf_find_vmlinux_btf_id(const char *name,
10034 			       enum bpf_attach_type attach_type)
10035 {
10036 	struct btf *btf;
10037 	int err;
10038 
10039 	btf = btf__load_vmlinux_btf();
10040 	err = libbpf_get_error(btf);
10041 	if (err) {
10042 		pr_warn("vmlinux BTF is not found\n");
10043 		return libbpf_err(err);
10044 	}
10045 
10046 	err = find_attach_btf_id(btf, name, attach_type);
10047 	if (err <= 0)
10048 		pr_warn("%s is not found in vmlinux BTF\n", name);
10049 
10050 	btf__free(btf);
10051 	return libbpf_err(err);
10052 }
10053 
10054 static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd, int token_fd)
10055 {
10056 	struct bpf_prog_info info;
10057 	__u32 info_len = sizeof(info);
10058 	struct btf *btf;
10059 	int err;
10060 
10061 	memset(&info, 0, info_len);
10062 	err = bpf_prog_get_info_by_fd(attach_prog_fd, &info, &info_len);
10063 	if (err) {
10064 		pr_warn("failed bpf_prog_get_info_by_fd for FD %d: %s\n",
10065 			attach_prog_fd, errstr(err));
10066 		return err;
10067 	}
10068 
10069 	err = -EINVAL;
10070 	if (!info.btf_id) {
10071 		pr_warn("The target program doesn't have BTF\n");
10072 		goto out;
10073 	}
10074 	btf = btf_load_from_kernel(info.btf_id, NULL, token_fd);
10075 	err = libbpf_get_error(btf);
10076 	if (err) {
10077 		pr_warn("Failed to get BTF %d of the program: %s\n", info.btf_id, errstr(err));
10078 		goto out;
10079 	}
10080 	err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
10081 	btf__free(btf);
10082 	if (err <= 0) {
10083 		pr_warn("%s is not found in prog's BTF\n", name);
10084 		goto out;
10085 	}
10086 out:
10087 	return err;
10088 }
10089 
10090 static int find_kernel_btf_id(struct bpf_object *obj, const char *attach_name,
10091 			      enum bpf_attach_type attach_type,
10092 			      int *btf_obj_fd, int *btf_type_id)
10093 {
10094 	int ret, i, mod_len;
10095 	const char *fn_name, *mod_name = NULL;
10096 
10097 	fn_name = strchr(attach_name, ':');
10098 	if (fn_name) {
10099 		mod_name = attach_name;
10100 		mod_len = fn_name - mod_name;
10101 		fn_name++;
10102 	}
10103 
10104 	if (!mod_name || strncmp(mod_name, "vmlinux", mod_len) == 0) {
10105 		ret = find_attach_btf_id(obj->btf_vmlinux,
10106 					 mod_name ? fn_name : attach_name,
10107 					 attach_type);
10108 		if (ret > 0) {
10109 			*btf_obj_fd = 0; /* vmlinux BTF */
10110 			*btf_type_id = ret;
10111 			return 0;
10112 		}
10113 		if (ret != -ENOENT)
10114 			return ret;
10115 	}
10116 
10117 	ret = load_module_btfs(obj);
10118 	if (ret)
10119 		return ret;
10120 
10121 	for (i = 0; i < obj->btf_module_cnt; i++) {
10122 		const struct module_btf *mod = &obj->btf_modules[i];
10123 
10124 		if (mod_name && strncmp(mod->name, mod_name, mod_len) != 0)
10125 			continue;
10126 
10127 		ret = find_attach_btf_id(mod->btf,
10128 					 mod_name ? fn_name : attach_name,
10129 					 attach_type);
10130 		if (ret > 0) {
10131 			*btf_obj_fd = mod->fd;
10132 			*btf_type_id = ret;
10133 			return 0;
10134 		}
10135 		if (ret == -ENOENT)
10136 			continue;
10137 
10138 		return ret;
10139 	}
10140 
10141 	return -ESRCH;
10142 }
10143 
10144 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
10145 				     int *btf_obj_fd, int *btf_type_id)
10146 {
10147 	enum bpf_attach_type attach_type = prog->expected_attach_type;
10148 	__u32 attach_prog_fd = prog->attach_prog_fd;
10149 	int err = 0;
10150 
10151 	/* BPF program's BTF ID */
10152 	if (prog->type == BPF_PROG_TYPE_EXT || attach_prog_fd) {
10153 		if (!attach_prog_fd) {
10154 			pr_warn("prog '%s': attach program FD is not set\n", prog->name);
10155 			return -EINVAL;
10156 		}
10157 		err = libbpf_find_prog_btf_id(attach_name, attach_prog_fd, prog->obj->token_fd);
10158 		if (err < 0) {
10159 			pr_warn("prog '%s': failed to find BPF program (FD %d) BTF ID for '%s': %s\n",
10160 				prog->name, attach_prog_fd, attach_name, errstr(err));
10161 			return err;
10162 		}
10163 		*btf_obj_fd = 0;
10164 		*btf_type_id = err;
10165 		return 0;
10166 	}
10167 
10168 	/* kernel/module BTF ID */
10169 	if (prog->obj->gen_loader) {
10170 		bpf_gen__record_attach_target(prog->obj->gen_loader, attach_name, attach_type);
10171 		*btf_obj_fd = 0;
10172 		*btf_type_id = 1;
10173 	} else {
10174 		err = find_kernel_btf_id(prog->obj, attach_name,
10175 					 attach_type, btf_obj_fd,
10176 					 btf_type_id);
10177 	}
10178 	if (err) {
10179 		pr_warn("prog '%s': failed to find kernel BTF type ID of '%s': %s\n",
10180 			prog->name, attach_name, errstr(err));
10181 		return err;
10182 	}
10183 	return 0;
10184 }
10185 
10186 int libbpf_attach_type_by_name(const char *name,
10187 			       enum bpf_attach_type *attach_type)
10188 {
10189 	char *type_names;
10190 	const struct bpf_sec_def *sec_def;
10191 
10192 	if (!name)
10193 		return libbpf_err(-EINVAL);
10194 
10195 	sec_def = find_sec_def(name);
10196 	if (!sec_def) {
10197 		pr_debug("failed to guess attach type based on ELF section name '%s'\n", name);
10198 		type_names = libbpf_get_type_names(true);
10199 		if (type_names != NULL) {
10200 			pr_debug("attachable section(type) names are:%s\n", type_names);
10201 			free(type_names);
10202 		}
10203 
10204 		return libbpf_err(-EINVAL);
10205 	}
10206 
10207 	if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
10208 		return libbpf_err(-EINVAL);
10209 	if (!(sec_def->cookie & SEC_ATTACHABLE))
10210 		return libbpf_err(-EINVAL);
10211 
10212 	*attach_type = sec_def->expected_attach_type;
10213 	return 0;
10214 }
10215 
10216 int bpf_map__fd(const struct bpf_map *map)
10217 {
10218 	if (!map)
10219 		return libbpf_err(-EINVAL);
10220 	if (!map_is_created(map))
10221 		return -1;
10222 	return map->fd;
10223 }
10224 
10225 static bool map_uses_real_name(const struct bpf_map *map)
10226 {
10227 	/* Since libbpf started to support custom .data.* and .rodata.* maps,
10228 	 * their user-visible name differs from kernel-visible name. Users see
10229 	 * such map's corresponding ELF section name as a map name.
10230 	 * This check distinguishes .data/.rodata from .data.* and .rodata.*
10231 	 * maps to know which name has to be returned to the user.
10232 	 */
10233 	if (map->libbpf_type == LIBBPF_MAP_DATA && strcmp(map->real_name, DATA_SEC) != 0)
10234 		return true;
10235 	if (map->libbpf_type == LIBBPF_MAP_RODATA && strcmp(map->real_name, RODATA_SEC) != 0)
10236 		return true;
10237 	return false;
10238 }
10239 
10240 const char *bpf_map__name(const struct bpf_map *map)
10241 {
10242 	if (!map)
10243 		return NULL;
10244 
10245 	if (map_uses_real_name(map))
10246 		return map->real_name;
10247 
10248 	return map->name;
10249 }
10250 
10251 enum bpf_map_type bpf_map__type(const struct bpf_map *map)
10252 {
10253 	return map->def.type;
10254 }
10255 
10256 int bpf_map__set_type(struct bpf_map *map, enum bpf_map_type type)
10257 {
10258 	if (map_is_created(map))
10259 		return libbpf_err(-EBUSY);
10260 	map->def.type = type;
10261 	return 0;
10262 }
10263 
10264 __u32 bpf_map__map_flags(const struct bpf_map *map)
10265 {
10266 	return map->def.map_flags;
10267 }
10268 
10269 int bpf_map__set_map_flags(struct bpf_map *map, __u32 flags)
10270 {
10271 	if (map_is_created(map))
10272 		return libbpf_err(-EBUSY);
10273 	map->def.map_flags = flags;
10274 	return 0;
10275 }
10276 
10277 __u64 bpf_map__map_extra(const struct bpf_map *map)
10278 {
10279 	return map->map_extra;
10280 }
10281 
10282 int bpf_map__set_map_extra(struct bpf_map *map, __u64 map_extra)
10283 {
10284 	if (map_is_created(map))
10285 		return libbpf_err(-EBUSY);
10286 	map->map_extra = map_extra;
10287 	return 0;
10288 }
10289 
10290 __u32 bpf_map__numa_node(const struct bpf_map *map)
10291 {
10292 	return map->numa_node;
10293 }
10294 
10295 int bpf_map__set_numa_node(struct bpf_map *map, __u32 numa_node)
10296 {
10297 	if (map_is_created(map))
10298 		return libbpf_err(-EBUSY);
10299 	map->numa_node = numa_node;
10300 	return 0;
10301 }
10302 
10303 __u32 bpf_map__key_size(const struct bpf_map *map)
10304 {
10305 	return map->def.key_size;
10306 }
10307 
10308 int bpf_map__set_key_size(struct bpf_map *map, __u32 size)
10309 {
10310 	if (map_is_created(map))
10311 		return libbpf_err(-EBUSY);
10312 	map->def.key_size = size;
10313 	return 0;
10314 }
10315 
10316 __u32 bpf_map__value_size(const struct bpf_map *map)
10317 {
10318 	return map->def.value_size;
10319 }
10320 
10321 static int map_btf_datasec_resize(struct bpf_map *map, __u32 size)
10322 {
10323 	struct btf *btf;
10324 	struct btf_type *datasec_type, *var_type;
10325 	struct btf_var_secinfo *var;
10326 	const struct btf_type *array_type;
10327 	const struct btf_array *array;
10328 	int vlen, element_sz, new_array_id;
10329 	__u32 nr_elements;
10330 
10331 	/* check btf existence */
10332 	btf = bpf_object__btf(map->obj);
10333 	if (!btf)
10334 		return -ENOENT;
10335 
10336 	/* verify map is datasec */
10337 	datasec_type = btf_type_by_id(btf, bpf_map__btf_value_type_id(map));
10338 	if (!btf_is_datasec(datasec_type)) {
10339 		pr_warn("map '%s': cannot be resized, map value type is not a datasec\n",
10340 			bpf_map__name(map));
10341 		return -EINVAL;
10342 	}
10343 
10344 	/* verify datasec has at least one var */
10345 	vlen = btf_vlen(datasec_type);
10346 	if (vlen == 0) {
10347 		pr_warn("map '%s': cannot be resized, map value datasec is empty\n",
10348 			bpf_map__name(map));
10349 		return -EINVAL;
10350 	}
10351 
10352 	/* verify last var in the datasec is an array */
10353 	var = &btf_var_secinfos(datasec_type)[vlen - 1];
10354 	var_type = btf_type_by_id(btf, var->type);
10355 	array_type = skip_mods_and_typedefs(btf, var_type->type, NULL);
10356 	if (!btf_is_array(array_type)) {
10357 		pr_warn("map '%s': cannot be resized, last var must be an array\n",
10358 			bpf_map__name(map));
10359 		return -EINVAL;
10360 	}
10361 
10362 	/* verify request size aligns with array */
10363 	array = btf_array(array_type);
10364 	element_sz = btf__resolve_size(btf, array->type);
10365 	if (element_sz <= 0 || (size - var->offset) % element_sz != 0) {
10366 		pr_warn("map '%s': cannot be resized, element size (%d) doesn't align with new total size (%u)\n",
10367 			bpf_map__name(map), element_sz, size);
10368 		return -EINVAL;
10369 	}
10370 
10371 	/* create a new array based on the existing array, but with new length */
10372 	nr_elements = (size - var->offset) / element_sz;
10373 	new_array_id = btf__add_array(btf, array->index_type, array->type, nr_elements);
10374 	if (new_array_id < 0)
10375 		return new_array_id;
10376 
10377 	/* adding a new btf type invalidates existing pointers to btf objects,
10378 	 * so refresh pointers before proceeding
10379 	 */
10380 	datasec_type = btf_type_by_id(btf, map->btf_value_type_id);
10381 	var = &btf_var_secinfos(datasec_type)[vlen - 1];
10382 	var_type = btf_type_by_id(btf, var->type);
10383 
10384 	/* finally update btf info */
10385 	datasec_type->size = size;
10386 	var->size = size - var->offset;
10387 	var_type->type = new_array_id;
10388 
10389 	return 0;
10390 }
10391 
10392 int bpf_map__set_value_size(struct bpf_map *map, __u32 size)
10393 {
10394 	if (map_is_created(map))
10395 		return libbpf_err(-EBUSY);
10396 
10397 	if (map->mmaped) {
10398 		size_t mmap_old_sz, mmap_new_sz;
10399 		int err;
10400 
10401 		if (map->def.type != BPF_MAP_TYPE_ARRAY)
10402 			return libbpf_err(-EOPNOTSUPP);
10403 
10404 		mmap_old_sz = bpf_map_mmap_sz(map);
10405 		mmap_new_sz = array_map_mmap_sz(size, map->def.max_entries);
10406 		err = bpf_map_mmap_resize(map, mmap_old_sz, mmap_new_sz);
10407 		if (err) {
10408 			pr_warn("map '%s': failed to resize memory-mapped region: %s\n",
10409 				bpf_map__name(map), errstr(err));
10410 			return libbpf_err(err);
10411 		}
10412 		err = map_btf_datasec_resize(map, size);
10413 		if (err && err != -ENOENT) {
10414 			pr_warn("map '%s': failed to adjust resized BTF, clearing BTF key/value info: %s\n",
10415 				bpf_map__name(map), errstr(err));
10416 			map->btf_value_type_id = 0;
10417 			map->btf_key_type_id = 0;
10418 		}
10419 	}
10420 
10421 	map->def.value_size = size;
10422 	return 0;
10423 }
10424 
10425 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
10426 {
10427 	return map ? map->btf_key_type_id : 0;
10428 }
10429 
10430 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
10431 {
10432 	return map ? map->btf_value_type_id : 0;
10433 }
10434 
10435 int bpf_map__set_initial_value(struct bpf_map *map,
10436 			       const void *data, size_t size)
10437 {
10438 	size_t actual_sz;
10439 
10440 	if (map_is_created(map))
10441 		return libbpf_err(-EBUSY);
10442 
10443 	if (!map->mmaped || map->libbpf_type == LIBBPF_MAP_KCONFIG)
10444 		return libbpf_err(-EINVAL);
10445 
10446 	if (map->def.type == BPF_MAP_TYPE_ARENA)
10447 		actual_sz = map->obj->arena_data_sz;
10448 	else
10449 		actual_sz = map->def.value_size;
10450 	if (size != actual_sz)
10451 		return libbpf_err(-EINVAL);
10452 
10453 	memcpy(map->mmaped, data, size);
10454 	return 0;
10455 }
10456 
10457 void *bpf_map__initial_value(const struct bpf_map *map, size_t *psize)
10458 {
10459 	if (bpf_map__is_struct_ops(map)) {
10460 		if (psize)
10461 			*psize = map->def.value_size;
10462 		return map->st_ops->data;
10463 	}
10464 
10465 	if (!map->mmaped)
10466 		return NULL;
10467 
10468 	if (map->def.type == BPF_MAP_TYPE_ARENA)
10469 		*psize = map->obj->arena_data_sz;
10470 	else
10471 		*psize = map->def.value_size;
10472 
10473 	return map->mmaped;
10474 }
10475 
10476 bool bpf_map__is_internal(const struct bpf_map *map)
10477 {
10478 	return map->libbpf_type != LIBBPF_MAP_UNSPEC;
10479 }
10480 
10481 __u32 bpf_map__ifindex(const struct bpf_map *map)
10482 {
10483 	return map->map_ifindex;
10484 }
10485 
10486 int bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
10487 {
10488 	if (map_is_created(map))
10489 		return libbpf_err(-EBUSY);
10490 	map->map_ifindex = ifindex;
10491 	return 0;
10492 }
10493 
10494 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
10495 {
10496 	if (!bpf_map_type__is_map_in_map(map->def.type)) {
10497 		pr_warn("error: unsupported map type\n");
10498 		return libbpf_err(-EINVAL);
10499 	}
10500 	if (map->inner_map_fd != -1) {
10501 		pr_warn("error: inner_map_fd already specified\n");
10502 		return libbpf_err(-EINVAL);
10503 	}
10504 	if (map->inner_map) {
10505 		bpf_map__destroy(map->inner_map);
10506 		zfree(&map->inner_map);
10507 	}
10508 	map->inner_map_fd = fd;
10509 	return 0;
10510 }
10511 
10512 static struct bpf_map *
10513 __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
10514 {
10515 	ssize_t idx;
10516 	struct bpf_map *s, *e;
10517 
10518 	if (!obj || !obj->maps)
10519 		return errno = EINVAL, NULL;
10520 
10521 	s = obj->maps;
10522 	e = obj->maps + obj->nr_maps;
10523 
10524 	if ((m < s) || (m >= e)) {
10525 		pr_warn("error in %s: map handler doesn't belong to object\n",
10526 			 __func__);
10527 		return errno = EINVAL, NULL;
10528 	}
10529 
10530 	idx = (m - obj->maps) + i;
10531 	if (idx >= obj->nr_maps || idx < 0)
10532 		return NULL;
10533 	return &obj->maps[idx];
10534 }
10535 
10536 struct bpf_map *
10537 bpf_object__next_map(const struct bpf_object *obj, const struct bpf_map *prev)
10538 {
10539 	if (prev == NULL && obj != NULL)
10540 		return obj->maps;
10541 
10542 	return __bpf_map__iter(prev, obj, 1);
10543 }
10544 
10545 struct bpf_map *
10546 bpf_object__prev_map(const struct bpf_object *obj, const struct bpf_map *next)
10547 {
10548 	if (next == NULL && obj != NULL) {
10549 		if (!obj->nr_maps)
10550 			return NULL;
10551 		return obj->maps + obj->nr_maps - 1;
10552 	}
10553 
10554 	return __bpf_map__iter(next, obj, -1);
10555 }
10556 
10557 struct bpf_map *
10558 bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
10559 {
10560 	struct bpf_map *pos;
10561 
10562 	bpf_object__for_each_map(pos, obj) {
10563 		/* if it's a special internal map name (which always starts
10564 		 * with dot) then check if that special name matches the
10565 		 * real map name (ELF section name)
10566 		 */
10567 		if (name[0] == '.') {
10568 			if (pos->real_name && strcmp(pos->real_name, name) == 0)
10569 				return pos;
10570 			continue;
10571 		}
10572 		/* otherwise map name has to be an exact match */
10573 		if (map_uses_real_name(pos)) {
10574 			if (strcmp(pos->real_name, name) == 0)
10575 				return pos;
10576 			continue;
10577 		}
10578 		if (strcmp(pos->name, name) == 0)
10579 			return pos;
10580 	}
10581 	return errno = ENOENT, NULL;
10582 }
10583 
10584 int
10585 bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
10586 {
10587 	return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
10588 }
10589 
10590 static int validate_map_op(const struct bpf_map *map, size_t key_sz,
10591 			   size_t value_sz, bool check_value_sz)
10592 {
10593 	if (!map_is_created(map)) /* map is not yet created */
10594 		return -ENOENT;
10595 
10596 	if (map->def.key_size != key_sz) {
10597 		pr_warn("map '%s': unexpected key size %zu provided, expected %u\n",
10598 			map->name, key_sz, map->def.key_size);
10599 		return -EINVAL;
10600 	}
10601 
10602 	if (map->fd < 0) {
10603 		pr_warn("map '%s': can't use BPF map without FD (was it created?)\n", map->name);
10604 		return -EINVAL;
10605 	}
10606 
10607 	if (!check_value_sz)
10608 		return 0;
10609 
10610 	switch (map->def.type) {
10611 	case BPF_MAP_TYPE_PERCPU_ARRAY:
10612 	case BPF_MAP_TYPE_PERCPU_HASH:
10613 	case BPF_MAP_TYPE_LRU_PERCPU_HASH:
10614 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: {
10615 		int num_cpu = libbpf_num_possible_cpus();
10616 		size_t elem_sz = roundup(map->def.value_size, 8);
10617 
10618 		if (value_sz != num_cpu * elem_sz) {
10619 			pr_warn("map '%s': unexpected value size %zu provided for per-CPU map, expected %d * %zu = %zd\n",
10620 				map->name, value_sz, num_cpu, elem_sz, num_cpu * elem_sz);
10621 			return -EINVAL;
10622 		}
10623 		break;
10624 	}
10625 	default:
10626 		if (map->def.value_size != value_sz) {
10627 			pr_warn("map '%s': unexpected value size %zu provided, expected %u\n",
10628 				map->name, value_sz, map->def.value_size);
10629 			return -EINVAL;
10630 		}
10631 		break;
10632 	}
10633 	return 0;
10634 }
10635 
10636 int bpf_map__lookup_elem(const struct bpf_map *map,
10637 			 const void *key, size_t key_sz,
10638 			 void *value, size_t value_sz, __u64 flags)
10639 {
10640 	int err;
10641 
10642 	err = validate_map_op(map, key_sz, value_sz, true);
10643 	if (err)
10644 		return libbpf_err(err);
10645 
10646 	return bpf_map_lookup_elem_flags(map->fd, key, value, flags);
10647 }
10648 
10649 int bpf_map__update_elem(const struct bpf_map *map,
10650 			 const void *key, size_t key_sz,
10651 			 const void *value, size_t value_sz, __u64 flags)
10652 {
10653 	int err;
10654 
10655 	err = validate_map_op(map, key_sz, value_sz, true);
10656 	if (err)
10657 		return libbpf_err(err);
10658 
10659 	return bpf_map_update_elem(map->fd, key, value, flags);
10660 }
10661 
10662 int bpf_map__delete_elem(const struct bpf_map *map,
10663 			 const void *key, size_t key_sz, __u64 flags)
10664 {
10665 	int err;
10666 
10667 	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */);
10668 	if (err)
10669 		return libbpf_err(err);
10670 
10671 	return bpf_map_delete_elem_flags(map->fd, key, flags);
10672 }
10673 
10674 int bpf_map__lookup_and_delete_elem(const struct bpf_map *map,
10675 				    const void *key, size_t key_sz,
10676 				    void *value, size_t value_sz, __u64 flags)
10677 {
10678 	int err;
10679 
10680 	err = validate_map_op(map, key_sz, value_sz, true);
10681 	if (err)
10682 		return libbpf_err(err);
10683 
10684 	return bpf_map_lookup_and_delete_elem_flags(map->fd, key, value, flags);
10685 }
10686 
10687 int bpf_map__get_next_key(const struct bpf_map *map,
10688 			  const void *cur_key, void *next_key, size_t key_sz)
10689 {
10690 	int err;
10691 
10692 	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */);
10693 	if (err)
10694 		return libbpf_err(err);
10695 
10696 	return bpf_map_get_next_key(map->fd, cur_key, next_key);
10697 }
10698 
10699 long libbpf_get_error(const void *ptr)
10700 {
10701 	if (!IS_ERR_OR_NULL(ptr))
10702 		return 0;
10703 
10704 	if (IS_ERR(ptr))
10705 		errno = -PTR_ERR(ptr);
10706 
10707 	/* If ptr == NULL, then errno should be already set by the failing
10708 	 * API, because libbpf never returns NULL on success and it now always
10709 	 * sets errno on error. So no extra errno handling for ptr == NULL
10710 	 * case.
10711 	 */
10712 	return -errno;
10713 }
10714 
10715 /* Replace link's underlying BPF program with the new one */
10716 int bpf_link__update_program(struct bpf_link *link, struct bpf_program *prog)
10717 {
10718 	int ret;
10719 	int prog_fd = bpf_program__fd(prog);
10720 
10721 	if (prog_fd < 0) {
10722 		pr_warn("prog '%s': can't use BPF program without FD (was it loaded?)\n",
10723 			prog->name);
10724 		return libbpf_err(-EINVAL);
10725 	}
10726 
10727 	ret = bpf_link_update(bpf_link__fd(link), prog_fd, NULL);
10728 	return libbpf_err_errno(ret);
10729 }
10730 
10731 /* Release "ownership" of underlying BPF resource (typically, BPF program
10732  * attached to some BPF hook, e.g., tracepoint, kprobe, etc). Disconnected
10733  * link, when destructed through bpf_link__destroy() call won't attempt to
10734  * detach/unregisted that BPF resource. This is useful in situations where,
10735  * say, attached BPF program has to outlive userspace program that attached it
10736  * in the system. Depending on type of BPF program, though, there might be
10737  * additional steps (like pinning BPF program in BPF FS) necessary to ensure
10738  * exit of userspace program doesn't trigger automatic detachment and clean up
10739  * inside the kernel.
10740  */
10741 void bpf_link__disconnect(struct bpf_link *link)
10742 {
10743 	link->disconnected = true;
10744 }
10745 
10746 int bpf_link__destroy(struct bpf_link *link)
10747 {
10748 	int err = 0;
10749 
10750 	if (IS_ERR_OR_NULL(link))
10751 		return 0;
10752 
10753 	if (!link->disconnected && link->detach)
10754 		err = link->detach(link);
10755 	if (link->pin_path)
10756 		free(link->pin_path);
10757 	if (link->dealloc)
10758 		link->dealloc(link);
10759 	else
10760 		free(link);
10761 
10762 	return libbpf_err(err);
10763 }
10764 
10765 int bpf_link__fd(const struct bpf_link *link)
10766 {
10767 	return link->fd;
10768 }
10769 
10770 const char *bpf_link__pin_path(const struct bpf_link *link)
10771 {
10772 	return link->pin_path;
10773 }
10774 
10775 static int bpf_link__detach_fd(struct bpf_link *link)
10776 {
10777 	return libbpf_err_errno(close(link->fd));
10778 }
10779 
10780 struct bpf_link *bpf_link__open(const char *path)
10781 {
10782 	struct bpf_link *link;
10783 	int fd;
10784 
10785 	fd = bpf_obj_get(path);
10786 	if (fd < 0) {
10787 		fd = -errno;
10788 		pr_warn("failed to open link at %s: %d\n", path, fd);
10789 		return libbpf_err_ptr(fd);
10790 	}
10791 
10792 	link = calloc(1, sizeof(*link));
10793 	if (!link) {
10794 		close(fd);
10795 		return libbpf_err_ptr(-ENOMEM);
10796 	}
10797 	link->detach = &bpf_link__detach_fd;
10798 	link->fd = fd;
10799 
10800 	link->pin_path = strdup(path);
10801 	if (!link->pin_path) {
10802 		bpf_link__destroy(link);
10803 		return libbpf_err_ptr(-ENOMEM);
10804 	}
10805 
10806 	return link;
10807 }
10808 
10809 int bpf_link__detach(struct bpf_link *link)
10810 {
10811 	return bpf_link_detach(link->fd) ? -errno : 0;
10812 }
10813 
10814 int bpf_link__pin(struct bpf_link *link, const char *path)
10815 {
10816 	int err;
10817 
10818 	if (link->pin_path)
10819 		return libbpf_err(-EBUSY);
10820 	err = make_parent_dir(path);
10821 	if (err)
10822 		return libbpf_err(err);
10823 	err = check_path(path);
10824 	if (err)
10825 		return libbpf_err(err);
10826 
10827 	link->pin_path = strdup(path);
10828 	if (!link->pin_path)
10829 		return libbpf_err(-ENOMEM);
10830 
10831 	if (bpf_obj_pin(link->fd, link->pin_path)) {
10832 		err = -errno;
10833 		zfree(&link->pin_path);
10834 		return libbpf_err(err);
10835 	}
10836 
10837 	pr_debug("link fd=%d: pinned at %s\n", link->fd, link->pin_path);
10838 	return 0;
10839 }
10840 
10841 int bpf_link__unpin(struct bpf_link *link)
10842 {
10843 	int err;
10844 
10845 	if (!link->pin_path)
10846 		return libbpf_err(-EINVAL);
10847 
10848 	err = unlink(link->pin_path);
10849 	if (err != 0)
10850 		return -errno;
10851 
10852 	pr_debug("link fd=%d: unpinned from %s\n", link->fd, link->pin_path);
10853 	zfree(&link->pin_path);
10854 	return 0;
10855 }
10856 
10857 struct bpf_link_perf {
10858 	struct bpf_link link;
10859 	int perf_event_fd;
10860 	/* legacy kprobe support: keep track of probe identifier and type */
10861 	char *legacy_probe_name;
10862 	bool legacy_is_kprobe;
10863 	bool legacy_is_retprobe;
10864 };
10865 
10866 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe);
10867 static int remove_uprobe_event_legacy(const char *probe_name, bool retprobe);
10868 
10869 static int bpf_link_perf_detach(struct bpf_link *link)
10870 {
10871 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10872 	int err = 0;
10873 
10874 	if (ioctl(perf_link->perf_event_fd, PERF_EVENT_IOC_DISABLE, 0) < 0)
10875 		err = -errno;
10876 
10877 	if (perf_link->perf_event_fd != link->fd)
10878 		close(perf_link->perf_event_fd);
10879 	close(link->fd);
10880 
10881 	/* legacy uprobe/kprobe needs to be removed after perf event fd closure */
10882 	if (perf_link->legacy_probe_name) {
10883 		if (perf_link->legacy_is_kprobe) {
10884 			err = remove_kprobe_event_legacy(perf_link->legacy_probe_name,
10885 							 perf_link->legacy_is_retprobe);
10886 		} else {
10887 			err = remove_uprobe_event_legacy(perf_link->legacy_probe_name,
10888 							 perf_link->legacy_is_retprobe);
10889 		}
10890 	}
10891 
10892 	return err;
10893 }
10894 
10895 static void bpf_link_perf_dealloc(struct bpf_link *link)
10896 {
10897 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10898 
10899 	free(perf_link->legacy_probe_name);
10900 	free(perf_link);
10901 }
10902 
10903 struct bpf_link *bpf_program__attach_perf_event_opts(const struct bpf_program *prog, int pfd,
10904 						     const struct bpf_perf_event_opts *opts)
10905 {
10906 	struct bpf_link_perf *link;
10907 	int prog_fd, link_fd = -1, err;
10908 	bool force_ioctl_attach;
10909 
10910 	if (!OPTS_VALID(opts, bpf_perf_event_opts))
10911 		return libbpf_err_ptr(-EINVAL);
10912 
10913 	if (pfd < 0) {
10914 		pr_warn("prog '%s': invalid perf event FD %d\n",
10915 			prog->name, pfd);
10916 		return libbpf_err_ptr(-EINVAL);
10917 	}
10918 	prog_fd = bpf_program__fd(prog);
10919 	if (prog_fd < 0) {
10920 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
10921 			prog->name);
10922 		return libbpf_err_ptr(-EINVAL);
10923 	}
10924 
10925 	link = calloc(1, sizeof(*link));
10926 	if (!link)
10927 		return libbpf_err_ptr(-ENOMEM);
10928 	link->link.detach = &bpf_link_perf_detach;
10929 	link->link.dealloc = &bpf_link_perf_dealloc;
10930 	link->perf_event_fd = pfd;
10931 
10932 	force_ioctl_attach = OPTS_GET(opts, force_ioctl_attach, false);
10933 	if (kernel_supports(prog->obj, FEAT_PERF_LINK) && !force_ioctl_attach) {
10934 		DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_opts,
10935 			.perf_event.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0));
10936 
10937 		link_fd = bpf_link_create(prog_fd, pfd, BPF_PERF_EVENT, &link_opts);
10938 		if (link_fd < 0) {
10939 			err = -errno;
10940 			pr_warn("prog '%s': failed to create BPF link for perf_event FD %d: %s\n",
10941 				prog->name, pfd, errstr(err));
10942 			goto err_out;
10943 		}
10944 		link->link.fd = link_fd;
10945 	} else {
10946 		if (OPTS_GET(opts, bpf_cookie, 0)) {
10947 			pr_warn("prog '%s': user context value is not supported\n", prog->name);
10948 			err = -EOPNOTSUPP;
10949 			goto err_out;
10950 		}
10951 
10952 		if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
10953 			err = -errno;
10954 			pr_warn("prog '%s': failed to attach to perf_event FD %d: %s\n",
10955 				prog->name, pfd, errstr(err));
10956 			if (err == -EPROTO)
10957 				pr_warn("prog '%s': try add PERF_SAMPLE_CALLCHAIN to or remove exclude_callchain_[kernel|user] from pfd %d\n",
10958 					prog->name, pfd);
10959 			goto err_out;
10960 		}
10961 		link->link.fd = pfd;
10962 	}
10963 	if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
10964 		err = -errno;
10965 		pr_warn("prog '%s': failed to enable perf_event FD %d: %s\n",
10966 			prog->name, pfd, errstr(err));
10967 		goto err_out;
10968 	}
10969 
10970 	return &link->link;
10971 err_out:
10972 	if (link_fd >= 0)
10973 		close(link_fd);
10974 	free(link);
10975 	return libbpf_err_ptr(err);
10976 }
10977 
10978 struct bpf_link *bpf_program__attach_perf_event(const struct bpf_program *prog, int pfd)
10979 {
10980 	return bpf_program__attach_perf_event_opts(prog, pfd, NULL);
10981 }
10982 
10983 /*
10984  * this function is expected to parse integer in the range of [0, 2^31-1] from
10985  * given file using scanf format string fmt. If actual parsed value is
10986  * negative, the result might be indistinguishable from error
10987  */
10988 static int parse_uint_from_file(const char *file, const char *fmt)
10989 {
10990 	int err, ret;
10991 	FILE *f;
10992 
10993 	f = fopen(file, "re");
10994 	if (!f) {
10995 		err = -errno;
10996 		pr_debug("failed to open '%s': %s\n", file, errstr(err));
10997 		return err;
10998 	}
10999 	err = fscanf(f, fmt, &ret);
11000 	if (err != 1) {
11001 		err = err == EOF ? -EIO : -errno;
11002 		pr_debug("failed to parse '%s': %s\n", file, errstr(err));
11003 		fclose(f);
11004 		return err;
11005 	}
11006 	fclose(f);
11007 	return ret;
11008 }
11009 
11010 static int determine_kprobe_perf_type(void)
11011 {
11012 	const char *file = "/sys/bus/event_source/devices/kprobe/type";
11013 
11014 	return parse_uint_from_file(file, "%d\n");
11015 }
11016 
11017 static int determine_uprobe_perf_type(void)
11018 {
11019 	const char *file = "/sys/bus/event_source/devices/uprobe/type";
11020 
11021 	return parse_uint_from_file(file, "%d\n");
11022 }
11023 
11024 static int determine_kprobe_retprobe_bit(void)
11025 {
11026 	const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
11027 
11028 	return parse_uint_from_file(file, "config:%d\n");
11029 }
11030 
11031 static int determine_uprobe_retprobe_bit(void)
11032 {
11033 	const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
11034 
11035 	return parse_uint_from_file(file, "config:%d\n");
11036 }
11037 
11038 #define PERF_UPROBE_REF_CTR_OFFSET_BITS 32
11039 #define PERF_UPROBE_REF_CTR_OFFSET_SHIFT 32
11040 
11041 static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
11042 				 uint64_t offset, int pid, size_t ref_ctr_off)
11043 {
11044 	const size_t attr_sz = sizeof(struct perf_event_attr);
11045 	struct perf_event_attr attr;
11046 	int type, pfd;
11047 
11048 	if ((__u64)ref_ctr_off >= (1ULL << PERF_UPROBE_REF_CTR_OFFSET_BITS))
11049 		return -EINVAL;
11050 
11051 	memset(&attr, 0, attr_sz);
11052 
11053 	type = uprobe ? determine_uprobe_perf_type()
11054 		      : determine_kprobe_perf_type();
11055 	if (type < 0) {
11056 		pr_warn("failed to determine %s perf type: %s\n",
11057 			uprobe ? "uprobe" : "kprobe",
11058 			errstr(type));
11059 		return type;
11060 	}
11061 	if (retprobe) {
11062 		int bit = uprobe ? determine_uprobe_retprobe_bit()
11063 				 : determine_kprobe_retprobe_bit();
11064 
11065 		if (bit < 0) {
11066 			pr_warn("failed to determine %s retprobe bit: %s\n",
11067 				uprobe ? "uprobe" : "kprobe",
11068 				errstr(bit));
11069 			return bit;
11070 		}
11071 		attr.config |= 1 << bit;
11072 	}
11073 	attr.size = attr_sz;
11074 	attr.type = type;
11075 	attr.config |= (__u64)ref_ctr_off << PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
11076 	attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
11077 	attr.config2 = offset;		 /* kprobe_addr or probe_offset */
11078 
11079 	/* pid filter is meaningful only for uprobes */
11080 	pfd = syscall(__NR_perf_event_open, &attr,
11081 		      pid < 0 ? -1 : pid /* pid */,
11082 		      pid == -1 ? 0 : -1 /* cpu */,
11083 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
11084 	return pfd >= 0 ? pfd : -errno;
11085 }
11086 
11087 static int append_to_file(const char *file, const char *fmt, ...)
11088 {
11089 	int fd, n, err = 0;
11090 	va_list ap;
11091 	char buf[1024];
11092 
11093 	va_start(ap, fmt);
11094 	n = vsnprintf(buf, sizeof(buf), fmt, ap);
11095 	va_end(ap);
11096 
11097 	if (n < 0 || n >= sizeof(buf))
11098 		return -EINVAL;
11099 
11100 	fd = open(file, O_WRONLY | O_APPEND | O_CLOEXEC, 0);
11101 	if (fd < 0)
11102 		return -errno;
11103 
11104 	if (write(fd, buf, n) < 0)
11105 		err = -errno;
11106 
11107 	close(fd);
11108 	return err;
11109 }
11110 
11111 #define DEBUGFS "/sys/kernel/debug/tracing"
11112 #define TRACEFS "/sys/kernel/tracing"
11113 
11114 static bool use_debugfs(void)
11115 {
11116 	static int has_debugfs = -1;
11117 
11118 	if (has_debugfs < 0)
11119 		has_debugfs = faccessat(AT_FDCWD, DEBUGFS, F_OK, AT_EACCESS) == 0;
11120 
11121 	return has_debugfs == 1;
11122 }
11123 
11124 static const char *tracefs_path(void)
11125 {
11126 	return use_debugfs() ? DEBUGFS : TRACEFS;
11127 }
11128 
11129 static const char *tracefs_kprobe_events(void)
11130 {
11131 	return use_debugfs() ? DEBUGFS"/kprobe_events" : TRACEFS"/kprobe_events";
11132 }
11133 
11134 static const char *tracefs_uprobe_events(void)
11135 {
11136 	return use_debugfs() ? DEBUGFS"/uprobe_events" : TRACEFS"/uprobe_events";
11137 }
11138 
11139 static const char *tracefs_available_filter_functions(void)
11140 {
11141 	return use_debugfs() ? DEBUGFS"/available_filter_functions"
11142 			     : TRACEFS"/available_filter_functions";
11143 }
11144 
11145 static const char *tracefs_available_filter_functions_addrs(void)
11146 {
11147 	return use_debugfs() ? DEBUGFS"/available_filter_functions_addrs"
11148 			     : TRACEFS"/available_filter_functions_addrs";
11149 }
11150 
11151 static void gen_probe_legacy_event_name(char *buf, size_t buf_sz,
11152 					const char *name, size_t offset)
11153 {
11154 	static int index = 0;
11155 	int i;
11156 
11157 	snprintf(buf, buf_sz, "libbpf_%u_%d_%s_0x%zx", getpid(),
11158 		 __sync_fetch_and_add(&index, 1), name, offset);
11159 
11160 	/* sanitize name in the probe name */
11161 	for (i = 0; buf[i]; i++) {
11162 		if (!isalnum(buf[i]))
11163 			buf[i] = '_';
11164 	}
11165 }
11166 
11167 static int add_kprobe_event_legacy(const char *probe_name, bool retprobe,
11168 				   const char *kfunc_name, size_t offset)
11169 {
11170 	return append_to_file(tracefs_kprobe_events(), "%c:%s/%s %s+0x%zx",
11171 			      retprobe ? 'r' : 'p',
11172 			      retprobe ? "kretprobes" : "kprobes",
11173 			      probe_name, kfunc_name, offset);
11174 }
11175 
11176 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe)
11177 {
11178 	return append_to_file(tracefs_kprobe_events(), "-:%s/%s",
11179 			      retprobe ? "kretprobes" : "kprobes", probe_name);
11180 }
11181 
11182 static int determine_kprobe_perf_type_legacy(const char *probe_name, bool retprobe)
11183 {
11184 	char file[256];
11185 
11186 	snprintf(file, sizeof(file), "%s/events/%s/%s/id",
11187 		 tracefs_path(), retprobe ? "kretprobes" : "kprobes", probe_name);
11188 
11189 	return parse_uint_from_file(file, "%d\n");
11190 }
11191 
11192 static int perf_event_kprobe_open_legacy(const char *probe_name, bool retprobe,
11193 					 const char *kfunc_name, size_t offset, int pid)
11194 {
11195 	const size_t attr_sz = sizeof(struct perf_event_attr);
11196 	struct perf_event_attr attr;
11197 	int type, pfd, err;
11198 
11199 	err = add_kprobe_event_legacy(probe_name, retprobe, kfunc_name, offset);
11200 	if (err < 0) {
11201 		pr_warn("failed to add legacy kprobe event for '%s+0x%zx': %s\n",
11202 			kfunc_name, offset,
11203 			errstr(err));
11204 		return err;
11205 	}
11206 	type = determine_kprobe_perf_type_legacy(probe_name, retprobe);
11207 	if (type < 0) {
11208 		err = type;
11209 		pr_warn("failed to determine legacy kprobe event id for '%s+0x%zx': %s\n",
11210 			kfunc_name, offset,
11211 			errstr(err));
11212 		goto err_clean_legacy;
11213 	}
11214 
11215 	memset(&attr, 0, attr_sz);
11216 	attr.size = attr_sz;
11217 	attr.config = type;
11218 	attr.type = PERF_TYPE_TRACEPOINT;
11219 
11220 	pfd = syscall(__NR_perf_event_open, &attr,
11221 		      pid < 0 ? -1 : pid, /* pid */
11222 		      pid == -1 ? 0 : -1, /* cpu */
11223 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
11224 	if (pfd < 0) {
11225 		err = -errno;
11226 		pr_warn("legacy kprobe perf_event_open() failed: %s\n",
11227 			errstr(err));
11228 		goto err_clean_legacy;
11229 	}
11230 	return pfd;
11231 
11232 err_clean_legacy:
11233 	/* Clear the newly added legacy kprobe_event */
11234 	remove_kprobe_event_legacy(probe_name, retprobe);
11235 	return err;
11236 }
11237 
11238 static const char *arch_specific_syscall_pfx(void)
11239 {
11240 #if defined(__x86_64__)
11241 	return "x64";
11242 #elif defined(__i386__)
11243 	return "ia32";
11244 #elif defined(__s390x__)
11245 	return "s390x";
11246 #elif defined(__s390__)
11247 	return "s390";
11248 #elif defined(__arm__)
11249 	return "arm";
11250 #elif defined(__aarch64__)
11251 	return "arm64";
11252 #elif defined(__mips__)
11253 	return "mips";
11254 #elif defined(__riscv)
11255 	return "riscv";
11256 #elif defined(__powerpc__)
11257 	return "powerpc";
11258 #elif defined(__powerpc64__)
11259 	return "powerpc64";
11260 #else
11261 	return NULL;
11262 #endif
11263 }
11264 
11265 int probe_kern_syscall_wrapper(int token_fd)
11266 {
11267 	char syscall_name[64];
11268 	const char *ksys_pfx;
11269 
11270 	ksys_pfx = arch_specific_syscall_pfx();
11271 	if (!ksys_pfx)
11272 		return 0;
11273 
11274 	snprintf(syscall_name, sizeof(syscall_name), "__%s_sys_bpf", ksys_pfx);
11275 
11276 	if (determine_kprobe_perf_type() >= 0) {
11277 		int pfd;
11278 
11279 		pfd = perf_event_open_probe(false, false, syscall_name, 0, getpid(), 0);
11280 		if (pfd >= 0)
11281 			close(pfd);
11282 
11283 		return pfd >= 0 ? 1 : 0;
11284 	} else { /* legacy mode */
11285 		char probe_name[MAX_EVENT_NAME_LEN];
11286 
11287 		gen_probe_legacy_event_name(probe_name, sizeof(probe_name), syscall_name, 0);
11288 		if (add_kprobe_event_legacy(probe_name, false, syscall_name, 0) < 0)
11289 			return 0;
11290 
11291 		(void)remove_kprobe_event_legacy(probe_name, false);
11292 		return 1;
11293 	}
11294 }
11295 
11296 struct bpf_link *
11297 bpf_program__attach_kprobe_opts(const struct bpf_program *prog,
11298 				const char *func_name,
11299 				const struct bpf_kprobe_opts *opts)
11300 {
11301 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
11302 	enum probe_attach_mode attach_mode;
11303 	char *legacy_probe = NULL;
11304 	struct bpf_link *link;
11305 	size_t offset;
11306 	bool retprobe, legacy;
11307 	int pfd, err;
11308 
11309 	if (!OPTS_VALID(opts, bpf_kprobe_opts))
11310 		return libbpf_err_ptr(-EINVAL);
11311 
11312 	attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
11313 	retprobe = OPTS_GET(opts, retprobe, false);
11314 	offset = OPTS_GET(opts, offset, 0);
11315 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11316 
11317 	legacy = determine_kprobe_perf_type() < 0;
11318 	switch (attach_mode) {
11319 	case PROBE_ATTACH_MODE_LEGACY:
11320 		legacy = true;
11321 		pe_opts.force_ioctl_attach = true;
11322 		break;
11323 	case PROBE_ATTACH_MODE_PERF:
11324 		if (legacy)
11325 			return libbpf_err_ptr(-ENOTSUP);
11326 		pe_opts.force_ioctl_attach = true;
11327 		break;
11328 	case PROBE_ATTACH_MODE_LINK:
11329 		if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
11330 			return libbpf_err_ptr(-ENOTSUP);
11331 		break;
11332 	case PROBE_ATTACH_MODE_DEFAULT:
11333 		break;
11334 	default:
11335 		return libbpf_err_ptr(-EINVAL);
11336 	}
11337 
11338 	if (!legacy) {
11339 		pfd = perf_event_open_probe(false /* uprobe */, retprobe,
11340 					    func_name, offset,
11341 					    -1 /* pid */, 0 /* ref_ctr_off */);
11342 	} else {
11343 		char probe_name[MAX_EVENT_NAME_LEN];
11344 
11345 		gen_probe_legacy_event_name(probe_name, sizeof(probe_name),
11346 					    func_name, offset);
11347 
11348 		legacy_probe = strdup(probe_name);
11349 		if (!legacy_probe)
11350 			return libbpf_err_ptr(-ENOMEM);
11351 
11352 		pfd = perf_event_kprobe_open_legacy(legacy_probe, retprobe, func_name,
11353 						    offset, -1 /* pid */);
11354 	}
11355 	if (pfd < 0) {
11356 		err = -errno;
11357 		pr_warn("prog '%s': failed to create %s '%s+0x%zx' perf event: %s\n",
11358 			prog->name, retprobe ? "kretprobe" : "kprobe",
11359 			func_name, offset,
11360 			errstr(err));
11361 		goto err_out;
11362 	}
11363 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
11364 	err = libbpf_get_error(link);
11365 	if (err) {
11366 		close(pfd);
11367 		pr_warn("prog '%s': failed to attach to %s '%s+0x%zx': %s\n",
11368 			prog->name, retprobe ? "kretprobe" : "kprobe",
11369 			func_name, offset,
11370 			errstr(err));
11371 		goto err_clean_legacy;
11372 	}
11373 	if (legacy) {
11374 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
11375 
11376 		perf_link->legacy_probe_name = legacy_probe;
11377 		perf_link->legacy_is_kprobe = true;
11378 		perf_link->legacy_is_retprobe = retprobe;
11379 	}
11380 
11381 	return link;
11382 
11383 err_clean_legacy:
11384 	if (legacy)
11385 		remove_kprobe_event_legacy(legacy_probe, retprobe);
11386 err_out:
11387 	free(legacy_probe);
11388 	return libbpf_err_ptr(err);
11389 }
11390 
11391 struct bpf_link *bpf_program__attach_kprobe(const struct bpf_program *prog,
11392 					    bool retprobe,
11393 					    const char *func_name)
11394 {
11395 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts,
11396 		.retprobe = retprobe,
11397 	);
11398 
11399 	return bpf_program__attach_kprobe_opts(prog, func_name, &opts);
11400 }
11401 
11402 struct bpf_link *bpf_program__attach_ksyscall(const struct bpf_program *prog,
11403 					      const char *syscall_name,
11404 					      const struct bpf_ksyscall_opts *opts)
11405 {
11406 	LIBBPF_OPTS(bpf_kprobe_opts, kprobe_opts);
11407 	char func_name[128];
11408 
11409 	if (!OPTS_VALID(opts, bpf_ksyscall_opts))
11410 		return libbpf_err_ptr(-EINVAL);
11411 
11412 	if (kernel_supports(prog->obj, FEAT_SYSCALL_WRAPPER)) {
11413 		/* arch_specific_syscall_pfx() should never return NULL here
11414 		 * because it is guarded by kernel_supports(). However, since
11415 		 * compiler does not know that we have an explicit conditional
11416 		 * as well.
11417 		 */
11418 		snprintf(func_name, sizeof(func_name), "__%s_sys_%s",
11419 			 arch_specific_syscall_pfx() ? : "", syscall_name);
11420 	} else {
11421 		snprintf(func_name, sizeof(func_name), "__se_sys_%s", syscall_name);
11422 	}
11423 
11424 	kprobe_opts.retprobe = OPTS_GET(opts, retprobe, false);
11425 	kprobe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11426 
11427 	return bpf_program__attach_kprobe_opts(prog, func_name, &kprobe_opts);
11428 }
11429 
11430 /* Adapted from perf/util/string.c */
11431 bool glob_match(const char *str, const char *pat)
11432 {
11433 	while (*str && *pat && *pat != '*') {
11434 		if (*pat == '?') {      /* Matches any single character */
11435 			str++;
11436 			pat++;
11437 			continue;
11438 		}
11439 		if (*str != *pat)
11440 			return false;
11441 		str++;
11442 		pat++;
11443 	}
11444 	/* Check wild card */
11445 	if (*pat == '*') {
11446 		while (*pat == '*')
11447 			pat++;
11448 		if (!*pat) /* Tail wild card matches all */
11449 			return true;
11450 		while (*str)
11451 			if (glob_match(str++, pat))
11452 				return true;
11453 	}
11454 	return !*str && !*pat;
11455 }
11456 
11457 struct kprobe_multi_resolve {
11458 	const char *pattern;
11459 	unsigned long *addrs;
11460 	size_t cap;
11461 	size_t cnt;
11462 };
11463 
11464 struct avail_kallsyms_data {
11465 	char **syms;
11466 	size_t cnt;
11467 	struct kprobe_multi_resolve *res;
11468 };
11469 
11470 static int avail_func_cmp(const void *a, const void *b)
11471 {
11472 	return strcmp(*(const char **)a, *(const char **)b);
11473 }
11474 
11475 static int avail_kallsyms_cb(unsigned long long sym_addr, char sym_type,
11476 			     const char *sym_name, void *ctx)
11477 {
11478 	struct avail_kallsyms_data *data = ctx;
11479 	struct kprobe_multi_resolve *res = data->res;
11480 	int err;
11481 
11482 	if (!glob_match(sym_name, res->pattern))
11483 		return 0;
11484 
11485 	if (!bsearch(&sym_name, data->syms, data->cnt, sizeof(*data->syms), avail_func_cmp)) {
11486 		/* Some versions of kernel strip out .llvm.<hash> suffix from
11487 		 * function names reported in available_filter_functions, but
11488 		 * don't do so for kallsyms. While this is clearly a kernel
11489 		 * bug (fixed by [0]) we try to accommodate that in libbpf to
11490 		 * make multi-kprobe usability a bit better: if no match is
11491 		 * found, we will strip .llvm. suffix and try one more time.
11492 		 *
11493 		 *   [0] fb6a421fb615 ("kallsyms: Match symbols exactly with CONFIG_LTO_CLANG")
11494 		 */
11495 		char sym_trim[256], *psym_trim = sym_trim, *sym_sfx;
11496 
11497 		if (!(sym_sfx = strstr(sym_name, ".llvm.")))
11498 			return 0;
11499 
11500 		/* psym_trim vs sym_trim dance is done to avoid pointer vs array
11501 		 * coercion differences and get proper `const char **` pointer
11502 		 * which avail_func_cmp() expects
11503 		 */
11504 		snprintf(sym_trim, sizeof(sym_trim), "%.*s", (int)(sym_sfx - sym_name), sym_name);
11505 		if (!bsearch(&psym_trim, data->syms, data->cnt, sizeof(*data->syms), avail_func_cmp))
11506 			return 0;
11507 	}
11508 
11509 	err = libbpf_ensure_mem((void **)&res->addrs, &res->cap, sizeof(*res->addrs), res->cnt + 1);
11510 	if (err)
11511 		return err;
11512 
11513 	res->addrs[res->cnt++] = (unsigned long)sym_addr;
11514 	return 0;
11515 }
11516 
11517 static int libbpf_available_kallsyms_parse(struct kprobe_multi_resolve *res)
11518 {
11519 	const char *available_functions_file = tracefs_available_filter_functions();
11520 	struct avail_kallsyms_data data;
11521 	char sym_name[500];
11522 	FILE *f;
11523 	int err = 0, ret, i;
11524 	char **syms = NULL;
11525 	size_t cap = 0, cnt = 0;
11526 
11527 	f = fopen(available_functions_file, "re");
11528 	if (!f) {
11529 		err = -errno;
11530 		pr_warn("failed to open %s: %s\n", available_functions_file, errstr(err));
11531 		return err;
11532 	}
11533 
11534 	while (true) {
11535 		char *name;
11536 
11537 		ret = fscanf(f, "%499s%*[^\n]\n", sym_name);
11538 		if (ret == EOF && feof(f))
11539 			break;
11540 
11541 		if (ret != 1) {
11542 			pr_warn("failed to parse available_filter_functions entry: %d\n", ret);
11543 			err = -EINVAL;
11544 			goto cleanup;
11545 		}
11546 
11547 		if (!glob_match(sym_name, res->pattern))
11548 			continue;
11549 
11550 		err = libbpf_ensure_mem((void **)&syms, &cap, sizeof(*syms), cnt + 1);
11551 		if (err)
11552 			goto cleanup;
11553 
11554 		name = strdup(sym_name);
11555 		if (!name) {
11556 			err = -errno;
11557 			goto cleanup;
11558 		}
11559 
11560 		syms[cnt++] = name;
11561 	}
11562 
11563 	/* no entries found, bail out */
11564 	if (cnt == 0) {
11565 		err = -ENOENT;
11566 		goto cleanup;
11567 	}
11568 
11569 	/* sort available functions */
11570 	qsort(syms, cnt, sizeof(*syms), avail_func_cmp);
11571 
11572 	data.syms = syms;
11573 	data.res = res;
11574 	data.cnt = cnt;
11575 	libbpf_kallsyms_parse(avail_kallsyms_cb, &data);
11576 
11577 	if (res->cnt == 0)
11578 		err = -ENOENT;
11579 
11580 cleanup:
11581 	for (i = 0; i < cnt; i++)
11582 		free((char *)syms[i]);
11583 	free(syms);
11584 
11585 	fclose(f);
11586 	return err;
11587 }
11588 
11589 static bool has_available_filter_functions_addrs(void)
11590 {
11591 	return access(tracefs_available_filter_functions_addrs(), R_OK) != -1;
11592 }
11593 
11594 static int libbpf_available_kprobes_parse(struct kprobe_multi_resolve *res)
11595 {
11596 	const char *available_path = tracefs_available_filter_functions_addrs();
11597 	char sym_name[500];
11598 	FILE *f;
11599 	int ret, err = 0;
11600 	unsigned long long sym_addr;
11601 
11602 	f = fopen(available_path, "re");
11603 	if (!f) {
11604 		err = -errno;
11605 		pr_warn("failed to open %s: %s\n", available_path, errstr(err));
11606 		return err;
11607 	}
11608 
11609 	while (true) {
11610 		ret = fscanf(f, "%llx %499s%*[^\n]\n", &sym_addr, sym_name);
11611 		if (ret == EOF && feof(f))
11612 			break;
11613 
11614 		if (ret != 2) {
11615 			pr_warn("failed to parse available_filter_functions_addrs entry: %d\n",
11616 				ret);
11617 			err = -EINVAL;
11618 			goto cleanup;
11619 		}
11620 
11621 		if (!glob_match(sym_name, res->pattern))
11622 			continue;
11623 
11624 		err = libbpf_ensure_mem((void **)&res->addrs, &res->cap,
11625 					sizeof(*res->addrs), res->cnt + 1);
11626 		if (err)
11627 			goto cleanup;
11628 
11629 		res->addrs[res->cnt++] = (unsigned long)sym_addr;
11630 	}
11631 
11632 	if (res->cnt == 0)
11633 		err = -ENOENT;
11634 
11635 cleanup:
11636 	fclose(f);
11637 	return err;
11638 }
11639 
11640 struct bpf_link *
11641 bpf_program__attach_kprobe_multi_opts(const struct bpf_program *prog,
11642 				      const char *pattern,
11643 				      const struct bpf_kprobe_multi_opts *opts)
11644 {
11645 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
11646 	struct kprobe_multi_resolve res = {
11647 		.pattern = pattern,
11648 	};
11649 	enum bpf_attach_type attach_type;
11650 	struct bpf_link *link = NULL;
11651 	const unsigned long *addrs;
11652 	int err, link_fd, prog_fd;
11653 	bool retprobe, session, unique_match;
11654 	const __u64 *cookies;
11655 	const char **syms;
11656 	size_t cnt;
11657 
11658 	if (!OPTS_VALID(opts, bpf_kprobe_multi_opts))
11659 		return libbpf_err_ptr(-EINVAL);
11660 
11661 	prog_fd = bpf_program__fd(prog);
11662 	if (prog_fd < 0) {
11663 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
11664 			prog->name);
11665 		return libbpf_err_ptr(-EINVAL);
11666 	}
11667 
11668 	syms    = OPTS_GET(opts, syms, false);
11669 	addrs   = OPTS_GET(opts, addrs, false);
11670 	cnt     = OPTS_GET(opts, cnt, false);
11671 	cookies = OPTS_GET(opts, cookies, false);
11672 	unique_match = OPTS_GET(opts, unique_match, false);
11673 
11674 	if (!pattern && !addrs && !syms)
11675 		return libbpf_err_ptr(-EINVAL);
11676 	if (pattern && (addrs || syms || cookies || cnt))
11677 		return libbpf_err_ptr(-EINVAL);
11678 	if (!pattern && !cnt)
11679 		return libbpf_err_ptr(-EINVAL);
11680 	if (!pattern && unique_match)
11681 		return libbpf_err_ptr(-EINVAL);
11682 	if (addrs && syms)
11683 		return libbpf_err_ptr(-EINVAL);
11684 
11685 	if (pattern) {
11686 		if (has_available_filter_functions_addrs())
11687 			err = libbpf_available_kprobes_parse(&res);
11688 		else
11689 			err = libbpf_available_kallsyms_parse(&res);
11690 		if (err)
11691 			goto error;
11692 
11693 		if (unique_match && res.cnt != 1) {
11694 			pr_warn("prog '%s': failed to find a unique match for '%s' (%zu matches)\n",
11695 				prog->name, pattern, res.cnt);
11696 			err = -EINVAL;
11697 			goto error;
11698 		}
11699 
11700 		addrs = res.addrs;
11701 		cnt = res.cnt;
11702 	}
11703 
11704 	retprobe = OPTS_GET(opts, retprobe, false);
11705 	session  = OPTS_GET(opts, session, false);
11706 
11707 	if (retprobe && session)
11708 		return libbpf_err_ptr(-EINVAL);
11709 
11710 	attach_type = session ? BPF_TRACE_KPROBE_SESSION : BPF_TRACE_KPROBE_MULTI;
11711 
11712 	lopts.kprobe_multi.syms = syms;
11713 	lopts.kprobe_multi.addrs = addrs;
11714 	lopts.kprobe_multi.cookies = cookies;
11715 	lopts.kprobe_multi.cnt = cnt;
11716 	lopts.kprobe_multi.flags = retprobe ? BPF_F_KPROBE_MULTI_RETURN : 0;
11717 
11718 	link = calloc(1, sizeof(*link));
11719 	if (!link) {
11720 		err = -ENOMEM;
11721 		goto error;
11722 	}
11723 	link->detach = &bpf_link__detach_fd;
11724 
11725 	link_fd = bpf_link_create(prog_fd, 0, attach_type, &lopts);
11726 	if (link_fd < 0) {
11727 		err = -errno;
11728 		pr_warn("prog '%s': failed to attach: %s\n",
11729 			prog->name, errstr(err));
11730 		goto error;
11731 	}
11732 	link->fd = link_fd;
11733 	free(res.addrs);
11734 	return link;
11735 
11736 error:
11737 	free(link);
11738 	free(res.addrs);
11739 	return libbpf_err_ptr(err);
11740 }
11741 
11742 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11743 {
11744 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts);
11745 	unsigned long offset = 0;
11746 	const char *func_name;
11747 	char *func;
11748 	int n;
11749 
11750 	*link = NULL;
11751 
11752 	/* no auto-attach for SEC("kprobe") and SEC("kretprobe") */
11753 	if (strcmp(prog->sec_name, "kprobe") == 0 || strcmp(prog->sec_name, "kretprobe") == 0)
11754 		return 0;
11755 
11756 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe/");
11757 	if (opts.retprobe)
11758 		func_name = prog->sec_name + sizeof("kretprobe/") - 1;
11759 	else
11760 		func_name = prog->sec_name + sizeof("kprobe/") - 1;
11761 
11762 	n = sscanf(func_name, "%m[a-zA-Z0-9_.]+%li", &func, &offset);
11763 	if (n < 1) {
11764 		pr_warn("kprobe name is invalid: %s\n", func_name);
11765 		return -EINVAL;
11766 	}
11767 	if (opts.retprobe && offset != 0) {
11768 		free(func);
11769 		pr_warn("kretprobes do not support offset specification\n");
11770 		return -EINVAL;
11771 	}
11772 
11773 	opts.offset = offset;
11774 	*link = bpf_program__attach_kprobe_opts(prog, func, &opts);
11775 	free(func);
11776 	return libbpf_get_error(*link);
11777 }
11778 
11779 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11780 {
11781 	LIBBPF_OPTS(bpf_ksyscall_opts, opts);
11782 	const char *syscall_name;
11783 
11784 	*link = NULL;
11785 
11786 	/* no auto-attach for SEC("ksyscall") and SEC("kretsyscall") */
11787 	if (strcmp(prog->sec_name, "ksyscall") == 0 || strcmp(prog->sec_name, "kretsyscall") == 0)
11788 		return 0;
11789 
11790 	opts.retprobe = str_has_pfx(prog->sec_name, "kretsyscall/");
11791 	if (opts.retprobe)
11792 		syscall_name = prog->sec_name + sizeof("kretsyscall/") - 1;
11793 	else
11794 		syscall_name = prog->sec_name + sizeof("ksyscall/") - 1;
11795 
11796 	*link = bpf_program__attach_ksyscall(prog, syscall_name, &opts);
11797 	return *link ? 0 : -errno;
11798 }
11799 
11800 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11801 {
11802 	LIBBPF_OPTS(bpf_kprobe_multi_opts, opts);
11803 	const char *spec;
11804 	char *pattern;
11805 	int n;
11806 
11807 	*link = NULL;
11808 
11809 	/* no auto-attach for SEC("kprobe.multi") and SEC("kretprobe.multi") */
11810 	if (strcmp(prog->sec_name, "kprobe.multi") == 0 ||
11811 	    strcmp(prog->sec_name, "kretprobe.multi") == 0)
11812 		return 0;
11813 
11814 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe.multi/");
11815 	if (opts.retprobe)
11816 		spec = prog->sec_name + sizeof("kretprobe.multi/") - 1;
11817 	else
11818 		spec = prog->sec_name + sizeof("kprobe.multi/") - 1;
11819 
11820 	n = sscanf(spec, "%m[a-zA-Z0-9_.*?]", &pattern);
11821 	if (n < 1) {
11822 		pr_warn("kprobe multi pattern is invalid: %s\n", spec);
11823 		return -EINVAL;
11824 	}
11825 
11826 	*link = bpf_program__attach_kprobe_multi_opts(prog, pattern, &opts);
11827 	free(pattern);
11828 	return libbpf_get_error(*link);
11829 }
11830 
11831 static int attach_kprobe_session(const struct bpf_program *prog, long cookie,
11832 				 struct bpf_link **link)
11833 {
11834 	LIBBPF_OPTS(bpf_kprobe_multi_opts, opts, .session = true);
11835 	const char *spec;
11836 	char *pattern;
11837 	int n;
11838 
11839 	*link = NULL;
11840 
11841 	/* no auto-attach for SEC("kprobe.session") */
11842 	if (strcmp(prog->sec_name, "kprobe.session") == 0)
11843 		return 0;
11844 
11845 	spec = prog->sec_name + sizeof("kprobe.session/") - 1;
11846 	n = sscanf(spec, "%m[a-zA-Z0-9_.*?]", &pattern);
11847 	if (n < 1) {
11848 		pr_warn("kprobe session pattern is invalid: %s\n", spec);
11849 		return -EINVAL;
11850 	}
11851 
11852 	*link = bpf_program__attach_kprobe_multi_opts(prog, pattern, &opts);
11853 	free(pattern);
11854 	return *link ? 0 : -errno;
11855 }
11856 
11857 static int attach_uprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11858 {
11859 	char *probe_type = NULL, *binary_path = NULL, *func_name = NULL;
11860 	LIBBPF_OPTS(bpf_uprobe_multi_opts, opts);
11861 	int n, ret = -EINVAL;
11862 
11863 	*link = NULL;
11864 
11865 	n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[^\n]",
11866 		   &probe_type, &binary_path, &func_name);
11867 	switch (n) {
11868 	case 1:
11869 		/* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
11870 		ret = 0;
11871 		break;
11872 	case 3:
11873 		opts.session = str_has_pfx(probe_type, "uprobe.session");
11874 		opts.retprobe = str_has_pfx(probe_type, "uretprobe.multi");
11875 
11876 		*link = bpf_program__attach_uprobe_multi(prog, -1, binary_path, func_name, &opts);
11877 		ret = libbpf_get_error(*link);
11878 		break;
11879 	default:
11880 		pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
11881 			prog->sec_name);
11882 		break;
11883 	}
11884 	free(probe_type);
11885 	free(binary_path);
11886 	free(func_name);
11887 	return ret;
11888 }
11889 
11890 static inline int add_uprobe_event_legacy(const char *probe_name, bool retprobe,
11891 					  const char *binary_path, size_t offset)
11892 {
11893 	return append_to_file(tracefs_uprobe_events(), "%c:%s/%s %s:0x%zx",
11894 			      retprobe ? 'r' : 'p',
11895 			      retprobe ? "uretprobes" : "uprobes",
11896 			      probe_name, binary_path, offset);
11897 }
11898 
11899 static inline int remove_uprobe_event_legacy(const char *probe_name, bool retprobe)
11900 {
11901 	return append_to_file(tracefs_uprobe_events(), "-:%s/%s",
11902 			      retprobe ? "uretprobes" : "uprobes", probe_name);
11903 }
11904 
11905 static int determine_uprobe_perf_type_legacy(const char *probe_name, bool retprobe)
11906 {
11907 	char file[512];
11908 
11909 	snprintf(file, sizeof(file), "%s/events/%s/%s/id",
11910 		 tracefs_path(), retprobe ? "uretprobes" : "uprobes", probe_name);
11911 
11912 	return parse_uint_from_file(file, "%d\n");
11913 }
11914 
11915 static int perf_event_uprobe_open_legacy(const char *probe_name, bool retprobe,
11916 					 const char *binary_path, size_t offset, int pid)
11917 {
11918 	const size_t attr_sz = sizeof(struct perf_event_attr);
11919 	struct perf_event_attr attr;
11920 	int type, pfd, err;
11921 
11922 	err = add_uprobe_event_legacy(probe_name, retprobe, binary_path, offset);
11923 	if (err < 0) {
11924 		pr_warn("failed to add legacy uprobe event for %s:0x%zx: %s\n",
11925 			binary_path, (size_t)offset, errstr(err));
11926 		return err;
11927 	}
11928 	type = determine_uprobe_perf_type_legacy(probe_name, retprobe);
11929 	if (type < 0) {
11930 		err = type;
11931 		pr_warn("failed to determine legacy uprobe event id for %s:0x%zx: %s\n",
11932 			binary_path, offset, errstr(err));
11933 		goto err_clean_legacy;
11934 	}
11935 
11936 	memset(&attr, 0, attr_sz);
11937 	attr.size = attr_sz;
11938 	attr.config = type;
11939 	attr.type = PERF_TYPE_TRACEPOINT;
11940 
11941 	pfd = syscall(__NR_perf_event_open, &attr,
11942 		      pid < 0 ? -1 : pid, /* pid */
11943 		      pid == -1 ? 0 : -1, /* cpu */
11944 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
11945 	if (pfd < 0) {
11946 		err = -errno;
11947 		pr_warn("legacy uprobe perf_event_open() failed: %s\n", errstr(err));
11948 		goto err_clean_legacy;
11949 	}
11950 	return pfd;
11951 
11952 err_clean_legacy:
11953 	/* Clear the newly added legacy uprobe_event */
11954 	remove_uprobe_event_legacy(probe_name, retprobe);
11955 	return err;
11956 }
11957 
11958 /* Find offset of function name in archive specified by path. Currently
11959  * supported are .zip files that do not compress their contents, as used on
11960  * Android in the form of APKs, for example. "file_name" is the name of the ELF
11961  * file inside the archive. "func_name" matches symbol name or name@@LIB for
11962  * library functions.
11963  *
11964  * An overview of the APK format specifically provided here:
11965  * https://en.wikipedia.org/w/index.php?title=Apk_(file_format)&oldid=1139099120#Package_contents
11966  */
11967 static long elf_find_func_offset_from_archive(const char *archive_path, const char *file_name,
11968 					      const char *func_name)
11969 {
11970 	struct zip_archive *archive;
11971 	struct zip_entry entry;
11972 	long ret;
11973 	Elf *elf;
11974 
11975 	archive = zip_archive_open(archive_path);
11976 	if (IS_ERR(archive)) {
11977 		ret = PTR_ERR(archive);
11978 		pr_warn("zip: failed to open %s: %ld\n", archive_path, ret);
11979 		return ret;
11980 	}
11981 
11982 	ret = zip_archive_find_entry(archive, file_name, &entry);
11983 	if (ret) {
11984 		pr_warn("zip: could not find archive member %s in %s: %ld\n", file_name,
11985 			archive_path, ret);
11986 		goto out;
11987 	}
11988 	pr_debug("zip: found entry for %s in %s at 0x%lx\n", file_name, archive_path,
11989 		 (unsigned long)entry.data_offset);
11990 
11991 	if (entry.compression) {
11992 		pr_warn("zip: entry %s of %s is compressed and cannot be handled\n", file_name,
11993 			archive_path);
11994 		ret = -LIBBPF_ERRNO__FORMAT;
11995 		goto out;
11996 	}
11997 
11998 	elf = elf_memory((void *)entry.data, entry.data_length);
11999 	if (!elf) {
12000 		pr_warn("elf: could not read elf file %s from %s: %s\n", file_name, archive_path,
12001 			elf_errmsg(-1));
12002 		ret = -LIBBPF_ERRNO__LIBELF;
12003 		goto out;
12004 	}
12005 
12006 	ret = elf_find_func_offset(elf, file_name, func_name);
12007 	if (ret > 0) {
12008 		pr_debug("elf: symbol address match for %s of %s in %s: 0x%x + 0x%lx = 0x%lx\n",
12009 			 func_name, file_name, archive_path, entry.data_offset, ret,
12010 			 ret + entry.data_offset);
12011 		ret += entry.data_offset;
12012 	}
12013 	elf_end(elf);
12014 
12015 out:
12016 	zip_archive_close(archive);
12017 	return ret;
12018 }
12019 
12020 static const char *arch_specific_lib_paths(void)
12021 {
12022 	/*
12023 	 * Based on https://packages.debian.org/sid/libc6.
12024 	 *
12025 	 * Assume that the traced program is built for the same architecture
12026 	 * as libbpf, which should cover the vast majority of cases.
12027 	 */
12028 #if defined(__x86_64__)
12029 	return "/lib/x86_64-linux-gnu";
12030 #elif defined(__i386__)
12031 	return "/lib/i386-linux-gnu";
12032 #elif defined(__s390x__)
12033 	return "/lib/s390x-linux-gnu";
12034 #elif defined(__s390__)
12035 	return "/lib/s390-linux-gnu";
12036 #elif defined(__arm__) && defined(__SOFTFP__)
12037 	return "/lib/arm-linux-gnueabi";
12038 #elif defined(__arm__) && !defined(__SOFTFP__)
12039 	return "/lib/arm-linux-gnueabihf";
12040 #elif defined(__aarch64__)
12041 	return "/lib/aarch64-linux-gnu";
12042 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 64
12043 	return "/lib/mips64el-linux-gnuabi64";
12044 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 32
12045 	return "/lib/mipsel-linux-gnu";
12046 #elif defined(__powerpc64__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
12047 	return "/lib/powerpc64le-linux-gnu";
12048 #elif defined(__sparc__) && defined(__arch64__)
12049 	return "/lib/sparc64-linux-gnu";
12050 #elif defined(__riscv) && __riscv_xlen == 64
12051 	return "/lib/riscv64-linux-gnu";
12052 #else
12053 	return NULL;
12054 #endif
12055 }
12056 
12057 /* Get full path to program/shared library. */
12058 static int resolve_full_path(const char *file, char *result, size_t result_sz)
12059 {
12060 	const char *search_paths[3] = {};
12061 	int i, perm;
12062 
12063 	if (str_has_sfx(file, ".so") || strstr(file, ".so.")) {
12064 		search_paths[0] = getenv("LD_LIBRARY_PATH");
12065 		search_paths[1] = "/usr/lib64:/usr/lib";
12066 		search_paths[2] = arch_specific_lib_paths();
12067 		perm = R_OK;
12068 	} else {
12069 		search_paths[0] = getenv("PATH");
12070 		search_paths[1] = "/usr/bin:/usr/sbin";
12071 		perm = R_OK | X_OK;
12072 	}
12073 
12074 	for (i = 0; i < ARRAY_SIZE(search_paths); i++) {
12075 		const char *s;
12076 
12077 		if (!search_paths[i])
12078 			continue;
12079 		for (s = search_paths[i]; s != NULL; s = strchr(s, ':')) {
12080 			char *next_path;
12081 			int seg_len;
12082 
12083 			if (s[0] == ':')
12084 				s++;
12085 			next_path = strchr(s, ':');
12086 			seg_len = next_path ? next_path - s : strlen(s);
12087 			if (!seg_len)
12088 				continue;
12089 			snprintf(result, result_sz, "%.*s/%s", seg_len, s, file);
12090 			/* ensure it has required permissions */
12091 			if (faccessat(AT_FDCWD, result, perm, AT_EACCESS) < 0)
12092 				continue;
12093 			pr_debug("resolved '%s' to '%s'\n", file, result);
12094 			return 0;
12095 		}
12096 	}
12097 	return -ENOENT;
12098 }
12099 
12100 struct bpf_link *
12101 bpf_program__attach_uprobe_multi(const struct bpf_program *prog,
12102 				 pid_t pid,
12103 				 const char *path,
12104 				 const char *func_pattern,
12105 				 const struct bpf_uprobe_multi_opts *opts)
12106 {
12107 	const unsigned long *ref_ctr_offsets = NULL, *offsets = NULL;
12108 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
12109 	unsigned long *resolved_offsets = NULL;
12110 	enum bpf_attach_type attach_type;
12111 	int err = 0, link_fd, prog_fd;
12112 	struct bpf_link *link = NULL;
12113 	char full_path[PATH_MAX];
12114 	bool retprobe, session;
12115 	const __u64 *cookies;
12116 	const char **syms;
12117 	size_t cnt;
12118 
12119 	if (!OPTS_VALID(opts, bpf_uprobe_multi_opts))
12120 		return libbpf_err_ptr(-EINVAL);
12121 
12122 	prog_fd = bpf_program__fd(prog);
12123 	if (prog_fd < 0) {
12124 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
12125 			prog->name);
12126 		return libbpf_err_ptr(-EINVAL);
12127 	}
12128 
12129 	syms = OPTS_GET(opts, syms, NULL);
12130 	offsets = OPTS_GET(opts, offsets, NULL);
12131 	ref_ctr_offsets = OPTS_GET(opts, ref_ctr_offsets, NULL);
12132 	cookies = OPTS_GET(opts, cookies, NULL);
12133 	cnt = OPTS_GET(opts, cnt, 0);
12134 	retprobe = OPTS_GET(opts, retprobe, false);
12135 	session  = OPTS_GET(opts, session, false);
12136 
12137 	/*
12138 	 * User can specify 2 mutually exclusive set of inputs:
12139 	 *
12140 	 * 1) use only path/func_pattern/pid arguments
12141 	 *
12142 	 * 2) use path/pid with allowed combinations of:
12143 	 *    syms/offsets/ref_ctr_offsets/cookies/cnt
12144 	 *
12145 	 *    - syms and offsets are mutually exclusive
12146 	 *    - ref_ctr_offsets and cookies are optional
12147 	 *
12148 	 * Any other usage results in error.
12149 	 */
12150 
12151 	if (!path)
12152 		return libbpf_err_ptr(-EINVAL);
12153 	if (!func_pattern && cnt == 0)
12154 		return libbpf_err_ptr(-EINVAL);
12155 
12156 	if (func_pattern) {
12157 		if (syms || offsets || ref_ctr_offsets || cookies || cnt)
12158 			return libbpf_err_ptr(-EINVAL);
12159 	} else {
12160 		if (!!syms == !!offsets)
12161 			return libbpf_err_ptr(-EINVAL);
12162 	}
12163 
12164 	if (retprobe && session)
12165 		return libbpf_err_ptr(-EINVAL);
12166 
12167 	if (func_pattern) {
12168 		if (!strchr(path, '/')) {
12169 			err = resolve_full_path(path, full_path, sizeof(full_path));
12170 			if (err) {
12171 				pr_warn("prog '%s': failed to resolve full path for '%s': %s\n",
12172 					prog->name, path, errstr(err));
12173 				return libbpf_err_ptr(err);
12174 			}
12175 			path = full_path;
12176 		}
12177 
12178 		err = elf_resolve_pattern_offsets(path, func_pattern,
12179 						  &resolved_offsets, &cnt);
12180 		if (err < 0)
12181 			return libbpf_err_ptr(err);
12182 		offsets = resolved_offsets;
12183 	} else if (syms) {
12184 		err = elf_resolve_syms_offsets(path, cnt, syms, &resolved_offsets, STT_FUNC);
12185 		if (err < 0)
12186 			return libbpf_err_ptr(err);
12187 		offsets = resolved_offsets;
12188 	}
12189 
12190 	attach_type = session ? BPF_TRACE_UPROBE_SESSION : BPF_TRACE_UPROBE_MULTI;
12191 
12192 	lopts.uprobe_multi.path = path;
12193 	lopts.uprobe_multi.offsets = offsets;
12194 	lopts.uprobe_multi.ref_ctr_offsets = ref_ctr_offsets;
12195 	lopts.uprobe_multi.cookies = cookies;
12196 	lopts.uprobe_multi.cnt = cnt;
12197 	lopts.uprobe_multi.flags = retprobe ? BPF_F_UPROBE_MULTI_RETURN : 0;
12198 
12199 	if (pid == 0)
12200 		pid = getpid();
12201 	if (pid > 0)
12202 		lopts.uprobe_multi.pid = pid;
12203 
12204 	link = calloc(1, sizeof(*link));
12205 	if (!link) {
12206 		err = -ENOMEM;
12207 		goto error;
12208 	}
12209 	link->detach = &bpf_link__detach_fd;
12210 
12211 	link_fd = bpf_link_create(prog_fd, 0, attach_type, &lopts);
12212 	if (link_fd < 0) {
12213 		err = -errno;
12214 		pr_warn("prog '%s': failed to attach multi-uprobe: %s\n",
12215 			prog->name, errstr(err));
12216 		goto error;
12217 	}
12218 	link->fd = link_fd;
12219 	free(resolved_offsets);
12220 	return link;
12221 
12222 error:
12223 	free(resolved_offsets);
12224 	free(link);
12225 	return libbpf_err_ptr(err);
12226 }
12227 
12228 LIBBPF_API struct bpf_link *
12229 bpf_program__attach_uprobe_opts(const struct bpf_program *prog, pid_t pid,
12230 				const char *binary_path, size_t func_offset,
12231 				const struct bpf_uprobe_opts *opts)
12232 {
12233 	const char *archive_path = NULL, *archive_sep = NULL;
12234 	char *legacy_probe = NULL;
12235 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
12236 	enum probe_attach_mode attach_mode;
12237 	char full_path[PATH_MAX];
12238 	struct bpf_link *link;
12239 	size_t ref_ctr_off;
12240 	int pfd, err;
12241 	bool retprobe, legacy;
12242 	const char *func_name;
12243 
12244 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
12245 		return libbpf_err_ptr(-EINVAL);
12246 
12247 	attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
12248 	retprobe = OPTS_GET(opts, retprobe, false);
12249 	ref_ctr_off = OPTS_GET(opts, ref_ctr_offset, 0);
12250 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
12251 
12252 	if (!binary_path)
12253 		return libbpf_err_ptr(-EINVAL);
12254 
12255 	/* Check if "binary_path" refers to an archive. */
12256 	archive_sep = strstr(binary_path, "!/");
12257 	if (archive_sep) {
12258 		full_path[0] = '\0';
12259 		libbpf_strlcpy(full_path, binary_path,
12260 			       min(sizeof(full_path), (size_t)(archive_sep - binary_path + 1)));
12261 		archive_path = full_path;
12262 		binary_path = archive_sep + 2;
12263 	} else if (!strchr(binary_path, '/')) {
12264 		err = resolve_full_path(binary_path, full_path, sizeof(full_path));
12265 		if (err) {
12266 			pr_warn("prog '%s': failed to resolve full path for '%s': %s\n",
12267 				prog->name, binary_path, errstr(err));
12268 			return libbpf_err_ptr(err);
12269 		}
12270 		binary_path = full_path;
12271 	}
12272 	func_name = OPTS_GET(opts, func_name, NULL);
12273 	if (func_name) {
12274 		long sym_off;
12275 
12276 		if (archive_path) {
12277 			sym_off = elf_find_func_offset_from_archive(archive_path, binary_path,
12278 								    func_name);
12279 			binary_path = archive_path;
12280 		} else {
12281 			sym_off = elf_find_func_offset_from_file(binary_path, func_name);
12282 		}
12283 		if (sym_off < 0)
12284 			return libbpf_err_ptr(sym_off);
12285 		func_offset += sym_off;
12286 	}
12287 
12288 	legacy = determine_uprobe_perf_type() < 0;
12289 	switch (attach_mode) {
12290 	case PROBE_ATTACH_MODE_LEGACY:
12291 		legacy = true;
12292 		pe_opts.force_ioctl_attach = true;
12293 		break;
12294 	case PROBE_ATTACH_MODE_PERF:
12295 		if (legacy)
12296 			return libbpf_err_ptr(-ENOTSUP);
12297 		pe_opts.force_ioctl_attach = true;
12298 		break;
12299 	case PROBE_ATTACH_MODE_LINK:
12300 		if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
12301 			return libbpf_err_ptr(-ENOTSUP);
12302 		break;
12303 	case PROBE_ATTACH_MODE_DEFAULT:
12304 		break;
12305 	default:
12306 		return libbpf_err_ptr(-EINVAL);
12307 	}
12308 
12309 	if (!legacy) {
12310 		pfd = perf_event_open_probe(true /* uprobe */, retprobe, binary_path,
12311 					    func_offset, pid, ref_ctr_off);
12312 	} else {
12313 		char probe_name[MAX_EVENT_NAME_LEN];
12314 
12315 		if (ref_ctr_off)
12316 			return libbpf_err_ptr(-EINVAL);
12317 
12318 		gen_probe_legacy_event_name(probe_name, sizeof(probe_name),
12319 					    strrchr(binary_path, '/') ? : binary_path,
12320 					    func_offset);
12321 
12322 		legacy_probe = strdup(probe_name);
12323 		if (!legacy_probe)
12324 			return libbpf_err_ptr(-ENOMEM);
12325 
12326 		pfd = perf_event_uprobe_open_legacy(legacy_probe, retprobe,
12327 						    binary_path, func_offset, pid);
12328 	}
12329 	if (pfd < 0) {
12330 		err = -errno;
12331 		pr_warn("prog '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
12332 			prog->name, retprobe ? "uretprobe" : "uprobe",
12333 			binary_path, func_offset,
12334 			errstr(err));
12335 		goto err_out;
12336 	}
12337 
12338 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
12339 	err = libbpf_get_error(link);
12340 	if (err) {
12341 		close(pfd);
12342 		pr_warn("prog '%s': failed to attach to %s '%s:0x%zx': %s\n",
12343 			prog->name, retprobe ? "uretprobe" : "uprobe",
12344 			binary_path, func_offset,
12345 			errstr(err));
12346 		goto err_clean_legacy;
12347 	}
12348 	if (legacy) {
12349 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
12350 
12351 		perf_link->legacy_probe_name = legacy_probe;
12352 		perf_link->legacy_is_kprobe = false;
12353 		perf_link->legacy_is_retprobe = retprobe;
12354 	}
12355 	return link;
12356 
12357 err_clean_legacy:
12358 	if (legacy)
12359 		remove_uprobe_event_legacy(legacy_probe, retprobe);
12360 err_out:
12361 	free(legacy_probe);
12362 	return libbpf_err_ptr(err);
12363 }
12364 
12365 /* Format of u[ret]probe section definition supporting auto-attach:
12366  * u[ret]probe/binary:function[+offset]
12367  *
12368  * binary can be an absolute/relative path or a filename; the latter is resolved to a
12369  * full binary path via bpf_program__attach_uprobe_opts.
12370  *
12371  * Specifying uprobe+ ensures we carry out strict matching; either "uprobe" must be
12372  * specified (and auto-attach is not possible) or the above format is specified for
12373  * auto-attach.
12374  */
12375 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12376 {
12377 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts);
12378 	char *probe_type = NULL, *binary_path = NULL, *func_name = NULL, *func_off;
12379 	int n, c, ret = -EINVAL;
12380 	long offset = 0;
12381 
12382 	*link = NULL;
12383 
12384 	n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[^\n]",
12385 		   &probe_type, &binary_path, &func_name);
12386 	switch (n) {
12387 	case 1:
12388 		/* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
12389 		ret = 0;
12390 		break;
12391 	case 2:
12392 		pr_warn("prog '%s': section '%s' missing ':function[+offset]' specification\n",
12393 			prog->name, prog->sec_name);
12394 		break;
12395 	case 3:
12396 		/* check if user specifies `+offset`, if yes, this should be
12397 		 * the last part of the string, make sure sscanf read to EOL
12398 		 */
12399 		func_off = strrchr(func_name, '+');
12400 		if (func_off) {
12401 			n = sscanf(func_off, "+%li%n", &offset, &c);
12402 			if (n == 1 && *(func_off + c) == '\0')
12403 				func_off[0] = '\0';
12404 			else
12405 				offset = 0;
12406 		}
12407 		opts.retprobe = strcmp(probe_type, "uretprobe") == 0 ||
12408 				strcmp(probe_type, "uretprobe.s") == 0;
12409 		if (opts.retprobe && offset != 0) {
12410 			pr_warn("prog '%s': uretprobes do not support offset specification\n",
12411 				prog->name);
12412 			break;
12413 		}
12414 		opts.func_name = func_name;
12415 		*link = bpf_program__attach_uprobe_opts(prog, -1, binary_path, offset, &opts);
12416 		ret = libbpf_get_error(*link);
12417 		break;
12418 	default:
12419 		pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
12420 			prog->sec_name);
12421 		break;
12422 	}
12423 	free(probe_type);
12424 	free(binary_path);
12425 	free(func_name);
12426 
12427 	return ret;
12428 }
12429 
12430 struct bpf_link *bpf_program__attach_uprobe(const struct bpf_program *prog,
12431 					    bool retprobe, pid_t pid,
12432 					    const char *binary_path,
12433 					    size_t func_offset)
12434 {
12435 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts, .retprobe = retprobe);
12436 
12437 	return bpf_program__attach_uprobe_opts(prog, pid, binary_path, func_offset, &opts);
12438 }
12439 
12440 struct bpf_link *bpf_program__attach_usdt(const struct bpf_program *prog,
12441 					  pid_t pid, const char *binary_path,
12442 					  const char *usdt_provider, const char *usdt_name,
12443 					  const struct bpf_usdt_opts *opts)
12444 {
12445 	char resolved_path[512];
12446 	struct bpf_object *obj = prog->obj;
12447 	struct bpf_link *link;
12448 	__u64 usdt_cookie;
12449 	int err;
12450 
12451 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
12452 		return libbpf_err_ptr(-EINVAL);
12453 
12454 	if (bpf_program__fd(prog) < 0) {
12455 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
12456 			prog->name);
12457 		return libbpf_err_ptr(-EINVAL);
12458 	}
12459 
12460 	if (!binary_path)
12461 		return libbpf_err_ptr(-EINVAL);
12462 
12463 	if (!strchr(binary_path, '/')) {
12464 		err = resolve_full_path(binary_path, resolved_path, sizeof(resolved_path));
12465 		if (err) {
12466 			pr_warn("prog '%s': failed to resolve full path for '%s': %s\n",
12467 				prog->name, binary_path, errstr(err));
12468 			return libbpf_err_ptr(err);
12469 		}
12470 		binary_path = resolved_path;
12471 	}
12472 
12473 	/* USDT manager is instantiated lazily on first USDT attach. It will
12474 	 * be destroyed together with BPF object in bpf_object__close().
12475 	 */
12476 	if (IS_ERR(obj->usdt_man))
12477 		return libbpf_ptr(obj->usdt_man);
12478 	if (!obj->usdt_man) {
12479 		obj->usdt_man = usdt_manager_new(obj);
12480 		if (IS_ERR(obj->usdt_man))
12481 			return libbpf_ptr(obj->usdt_man);
12482 	}
12483 
12484 	usdt_cookie = OPTS_GET(opts, usdt_cookie, 0);
12485 	link = usdt_manager_attach_usdt(obj->usdt_man, prog, pid, binary_path,
12486 					usdt_provider, usdt_name, usdt_cookie);
12487 	err = libbpf_get_error(link);
12488 	if (err)
12489 		return libbpf_err_ptr(err);
12490 	return link;
12491 }
12492 
12493 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12494 {
12495 	char *path = NULL, *provider = NULL, *name = NULL;
12496 	const char *sec_name;
12497 	int n, err;
12498 
12499 	sec_name = bpf_program__section_name(prog);
12500 	if (strcmp(sec_name, "usdt") == 0) {
12501 		/* no auto-attach for just SEC("usdt") */
12502 		*link = NULL;
12503 		return 0;
12504 	}
12505 
12506 	n = sscanf(sec_name, "usdt/%m[^:]:%m[^:]:%m[^:]", &path, &provider, &name);
12507 	if (n != 3) {
12508 		pr_warn("invalid section '%s', expected SEC(\"usdt/<path>:<provider>:<name>\")\n",
12509 			sec_name);
12510 		err = -EINVAL;
12511 	} else {
12512 		*link = bpf_program__attach_usdt(prog, -1 /* any process */, path,
12513 						 provider, name, NULL);
12514 		err = libbpf_get_error(*link);
12515 	}
12516 	free(path);
12517 	free(provider);
12518 	free(name);
12519 	return err;
12520 }
12521 
12522 static int determine_tracepoint_id(const char *tp_category,
12523 				   const char *tp_name)
12524 {
12525 	char file[PATH_MAX];
12526 	int ret;
12527 
12528 	ret = snprintf(file, sizeof(file), "%s/events/%s/%s/id",
12529 		       tracefs_path(), tp_category, tp_name);
12530 	if (ret < 0)
12531 		return -errno;
12532 	if (ret >= sizeof(file)) {
12533 		pr_debug("tracepoint %s/%s path is too long\n",
12534 			 tp_category, tp_name);
12535 		return -E2BIG;
12536 	}
12537 	return parse_uint_from_file(file, "%d\n");
12538 }
12539 
12540 static int perf_event_open_tracepoint(const char *tp_category,
12541 				      const char *tp_name)
12542 {
12543 	const size_t attr_sz = sizeof(struct perf_event_attr);
12544 	struct perf_event_attr attr;
12545 	int tp_id, pfd, err;
12546 
12547 	tp_id = determine_tracepoint_id(tp_category, tp_name);
12548 	if (tp_id < 0) {
12549 		pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
12550 			tp_category, tp_name,
12551 			errstr(tp_id));
12552 		return tp_id;
12553 	}
12554 
12555 	memset(&attr, 0, attr_sz);
12556 	attr.type = PERF_TYPE_TRACEPOINT;
12557 	attr.size = attr_sz;
12558 	attr.config = tp_id;
12559 
12560 	pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
12561 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
12562 	if (pfd < 0) {
12563 		err = -errno;
12564 		pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
12565 			tp_category, tp_name,
12566 			errstr(err));
12567 		return err;
12568 	}
12569 	return pfd;
12570 }
12571 
12572 struct bpf_link *bpf_program__attach_tracepoint_opts(const struct bpf_program *prog,
12573 						     const char *tp_category,
12574 						     const char *tp_name,
12575 						     const struct bpf_tracepoint_opts *opts)
12576 {
12577 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
12578 	struct bpf_link *link;
12579 	int pfd, err;
12580 
12581 	if (!OPTS_VALID(opts, bpf_tracepoint_opts))
12582 		return libbpf_err_ptr(-EINVAL);
12583 
12584 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
12585 
12586 	pfd = perf_event_open_tracepoint(tp_category, tp_name);
12587 	if (pfd < 0) {
12588 		pr_warn("prog '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
12589 			prog->name, tp_category, tp_name,
12590 			errstr(pfd));
12591 		return libbpf_err_ptr(pfd);
12592 	}
12593 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
12594 	err = libbpf_get_error(link);
12595 	if (err) {
12596 		close(pfd);
12597 		pr_warn("prog '%s': failed to attach to tracepoint '%s/%s': %s\n",
12598 			prog->name, tp_category, tp_name,
12599 			errstr(err));
12600 		return libbpf_err_ptr(err);
12601 	}
12602 	return link;
12603 }
12604 
12605 struct bpf_link *bpf_program__attach_tracepoint(const struct bpf_program *prog,
12606 						const char *tp_category,
12607 						const char *tp_name)
12608 {
12609 	return bpf_program__attach_tracepoint_opts(prog, tp_category, tp_name, NULL);
12610 }
12611 
12612 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12613 {
12614 	char *sec_name, *tp_cat, *tp_name;
12615 
12616 	*link = NULL;
12617 
12618 	/* no auto-attach for SEC("tp") or SEC("tracepoint") */
12619 	if (strcmp(prog->sec_name, "tp") == 0 || strcmp(prog->sec_name, "tracepoint") == 0)
12620 		return 0;
12621 
12622 	sec_name = strdup(prog->sec_name);
12623 	if (!sec_name)
12624 		return -ENOMEM;
12625 
12626 	/* extract "tp/<category>/<name>" or "tracepoint/<category>/<name>" */
12627 	if (str_has_pfx(prog->sec_name, "tp/"))
12628 		tp_cat = sec_name + sizeof("tp/") - 1;
12629 	else
12630 		tp_cat = sec_name + sizeof("tracepoint/") - 1;
12631 	tp_name = strchr(tp_cat, '/');
12632 	if (!tp_name) {
12633 		free(sec_name);
12634 		return -EINVAL;
12635 	}
12636 	*tp_name = '\0';
12637 	tp_name++;
12638 
12639 	*link = bpf_program__attach_tracepoint(prog, tp_cat, tp_name);
12640 	free(sec_name);
12641 	return libbpf_get_error(*link);
12642 }
12643 
12644 struct bpf_link *
12645 bpf_program__attach_raw_tracepoint_opts(const struct bpf_program *prog,
12646 					const char *tp_name,
12647 					struct bpf_raw_tracepoint_opts *opts)
12648 {
12649 	LIBBPF_OPTS(bpf_raw_tp_opts, raw_opts);
12650 	struct bpf_link *link;
12651 	int prog_fd, pfd;
12652 
12653 	if (!OPTS_VALID(opts, bpf_raw_tracepoint_opts))
12654 		return libbpf_err_ptr(-EINVAL);
12655 
12656 	prog_fd = bpf_program__fd(prog);
12657 	if (prog_fd < 0) {
12658 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12659 		return libbpf_err_ptr(-EINVAL);
12660 	}
12661 
12662 	link = calloc(1, sizeof(*link));
12663 	if (!link)
12664 		return libbpf_err_ptr(-ENOMEM);
12665 	link->detach = &bpf_link__detach_fd;
12666 
12667 	raw_opts.tp_name = tp_name;
12668 	raw_opts.cookie = OPTS_GET(opts, cookie, 0);
12669 	pfd = bpf_raw_tracepoint_open_opts(prog_fd, &raw_opts);
12670 	if (pfd < 0) {
12671 		pfd = -errno;
12672 		free(link);
12673 		pr_warn("prog '%s': failed to attach to raw tracepoint '%s': %s\n",
12674 			prog->name, tp_name, errstr(pfd));
12675 		return libbpf_err_ptr(pfd);
12676 	}
12677 	link->fd = pfd;
12678 	return link;
12679 }
12680 
12681 struct bpf_link *bpf_program__attach_raw_tracepoint(const struct bpf_program *prog,
12682 						    const char *tp_name)
12683 {
12684 	return bpf_program__attach_raw_tracepoint_opts(prog, tp_name, NULL);
12685 }
12686 
12687 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12688 {
12689 	static const char *const prefixes[] = {
12690 		"raw_tp",
12691 		"raw_tracepoint",
12692 		"raw_tp.w",
12693 		"raw_tracepoint.w",
12694 	};
12695 	size_t i;
12696 	const char *tp_name = NULL;
12697 
12698 	*link = NULL;
12699 
12700 	for (i = 0; i < ARRAY_SIZE(prefixes); i++) {
12701 		size_t pfx_len;
12702 
12703 		if (!str_has_pfx(prog->sec_name, prefixes[i]))
12704 			continue;
12705 
12706 		pfx_len = strlen(prefixes[i]);
12707 		/* no auto-attach case of, e.g., SEC("raw_tp") */
12708 		if (prog->sec_name[pfx_len] == '\0')
12709 			return 0;
12710 
12711 		if (prog->sec_name[pfx_len] != '/')
12712 			continue;
12713 
12714 		tp_name = prog->sec_name + pfx_len + 1;
12715 		break;
12716 	}
12717 
12718 	if (!tp_name) {
12719 		pr_warn("prog '%s': invalid section name '%s'\n",
12720 			prog->name, prog->sec_name);
12721 		return -EINVAL;
12722 	}
12723 
12724 	*link = bpf_program__attach_raw_tracepoint(prog, tp_name);
12725 	return libbpf_get_error(*link);
12726 }
12727 
12728 /* Common logic for all BPF program types that attach to a btf_id */
12729 static struct bpf_link *bpf_program__attach_btf_id(const struct bpf_program *prog,
12730 						   const struct bpf_trace_opts *opts)
12731 {
12732 	LIBBPF_OPTS(bpf_link_create_opts, link_opts);
12733 	struct bpf_link *link;
12734 	int prog_fd, pfd;
12735 
12736 	if (!OPTS_VALID(opts, bpf_trace_opts))
12737 		return libbpf_err_ptr(-EINVAL);
12738 
12739 	prog_fd = bpf_program__fd(prog);
12740 	if (prog_fd < 0) {
12741 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12742 		return libbpf_err_ptr(-EINVAL);
12743 	}
12744 
12745 	link = calloc(1, sizeof(*link));
12746 	if (!link)
12747 		return libbpf_err_ptr(-ENOMEM);
12748 	link->detach = &bpf_link__detach_fd;
12749 
12750 	/* libbpf is smart enough to redirect to BPF_RAW_TRACEPOINT_OPEN on old kernels */
12751 	link_opts.tracing.cookie = OPTS_GET(opts, cookie, 0);
12752 	pfd = bpf_link_create(prog_fd, 0, bpf_program__expected_attach_type(prog), &link_opts);
12753 	if (pfd < 0) {
12754 		pfd = -errno;
12755 		free(link);
12756 		pr_warn("prog '%s': failed to attach: %s\n",
12757 			prog->name, errstr(pfd));
12758 		return libbpf_err_ptr(pfd);
12759 	}
12760 	link->fd = pfd;
12761 	return link;
12762 }
12763 
12764 struct bpf_link *bpf_program__attach_trace(const struct bpf_program *prog)
12765 {
12766 	return bpf_program__attach_btf_id(prog, NULL);
12767 }
12768 
12769 struct bpf_link *bpf_program__attach_trace_opts(const struct bpf_program *prog,
12770 						const struct bpf_trace_opts *opts)
12771 {
12772 	return bpf_program__attach_btf_id(prog, opts);
12773 }
12774 
12775 struct bpf_link *bpf_program__attach_lsm(const struct bpf_program *prog)
12776 {
12777 	return bpf_program__attach_btf_id(prog, NULL);
12778 }
12779 
12780 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12781 {
12782 	*link = bpf_program__attach_trace(prog);
12783 	return libbpf_get_error(*link);
12784 }
12785 
12786 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12787 {
12788 	*link = bpf_program__attach_lsm(prog);
12789 	return libbpf_get_error(*link);
12790 }
12791 
12792 static struct bpf_link *
12793 bpf_program_attach_fd(const struct bpf_program *prog,
12794 		      int target_fd, const char *target_name,
12795 		      const struct bpf_link_create_opts *opts)
12796 {
12797 	enum bpf_attach_type attach_type;
12798 	struct bpf_link *link;
12799 	int prog_fd, link_fd;
12800 
12801 	prog_fd = bpf_program__fd(prog);
12802 	if (prog_fd < 0) {
12803 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12804 		return libbpf_err_ptr(-EINVAL);
12805 	}
12806 
12807 	link = calloc(1, sizeof(*link));
12808 	if (!link)
12809 		return libbpf_err_ptr(-ENOMEM);
12810 	link->detach = &bpf_link__detach_fd;
12811 
12812 	attach_type = bpf_program__expected_attach_type(prog);
12813 	link_fd = bpf_link_create(prog_fd, target_fd, attach_type, opts);
12814 	if (link_fd < 0) {
12815 		link_fd = -errno;
12816 		free(link);
12817 		pr_warn("prog '%s': failed to attach to %s: %s\n",
12818 			prog->name, target_name,
12819 			errstr(link_fd));
12820 		return libbpf_err_ptr(link_fd);
12821 	}
12822 	link->fd = link_fd;
12823 	return link;
12824 }
12825 
12826 struct bpf_link *
12827 bpf_program__attach_cgroup(const struct bpf_program *prog, int cgroup_fd)
12828 {
12829 	return bpf_program_attach_fd(prog, cgroup_fd, "cgroup", NULL);
12830 }
12831 
12832 struct bpf_link *
12833 bpf_program__attach_netns(const struct bpf_program *prog, int netns_fd)
12834 {
12835 	return bpf_program_attach_fd(prog, netns_fd, "netns", NULL);
12836 }
12837 
12838 struct bpf_link *
12839 bpf_program__attach_sockmap(const struct bpf_program *prog, int map_fd)
12840 {
12841 	return bpf_program_attach_fd(prog, map_fd, "sockmap", NULL);
12842 }
12843 
12844 struct bpf_link *bpf_program__attach_xdp(const struct bpf_program *prog, int ifindex)
12845 {
12846 	/* target_fd/target_ifindex use the same field in LINK_CREATE */
12847 	return bpf_program_attach_fd(prog, ifindex, "xdp", NULL);
12848 }
12849 
12850 struct bpf_link *
12851 bpf_program__attach_tcx(const struct bpf_program *prog, int ifindex,
12852 			const struct bpf_tcx_opts *opts)
12853 {
12854 	LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
12855 	__u32 relative_id;
12856 	int relative_fd;
12857 
12858 	if (!OPTS_VALID(opts, bpf_tcx_opts))
12859 		return libbpf_err_ptr(-EINVAL);
12860 
12861 	relative_id = OPTS_GET(opts, relative_id, 0);
12862 	relative_fd = OPTS_GET(opts, relative_fd, 0);
12863 
12864 	/* validate we don't have unexpected combinations of non-zero fields */
12865 	if (!ifindex) {
12866 		pr_warn("prog '%s': target netdevice ifindex cannot be zero\n",
12867 			prog->name);
12868 		return libbpf_err_ptr(-EINVAL);
12869 	}
12870 	if (relative_fd && relative_id) {
12871 		pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
12872 			prog->name);
12873 		return libbpf_err_ptr(-EINVAL);
12874 	}
12875 
12876 	link_create_opts.tcx.expected_revision = OPTS_GET(opts, expected_revision, 0);
12877 	link_create_opts.tcx.relative_fd = relative_fd;
12878 	link_create_opts.tcx.relative_id = relative_id;
12879 	link_create_opts.flags = OPTS_GET(opts, flags, 0);
12880 
12881 	/* target_fd/target_ifindex use the same field in LINK_CREATE */
12882 	return bpf_program_attach_fd(prog, ifindex, "tcx", &link_create_opts);
12883 }
12884 
12885 struct bpf_link *
12886 bpf_program__attach_netkit(const struct bpf_program *prog, int ifindex,
12887 			   const struct bpf_netkit_opts *opts)
12888 {
12889 	LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
12890 	__u32 relative_id;
12891 	int relative_fd;
12892 
12893 	if (!OPTS_VALID(opts, bpf_netkit_opts))
12894 		return libbpf_err_ptr(-EINVAL);
12895 
12896 	relative_id = OPTS_GET(opts, relative_id, 0);
12897 	relative_fd = OPTS_GET(opts, relative_fd, 0);
12898 
12899 	/* validate we don't have unexpected combinations of non-zero fields */
12900 	if (!ifindex) {
12901 		pr_warn("prog '%s': target netdevice ifindex cannot be zero\n",
12902 			prog->name);
12903 		return libbpf_err_ptr(-EINVAL);
12904 	}
12905 	if (relative_fd && relative_id) {
12906 		pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
12907 			prog->name);
12908 		return libbpf_err_ptr(-EINVAL);
12909 	}
12910 
12911 	link_create_opts.netkit.expected_revision = OPTS_GET(opts, expected_revision, 0);
12912 	link_create_opts.netkit.relative_fd = relative_fd;
12913 	link_create_opts.netkit.relative_id = relative_id;
12914 	link_create_opts.flags = OPTS_GET(opts, flags, 0);
12915 
12916 	return bpf_program_attach_fd(prog, ifindex, "netkit", &link_create_opts);
12917 }
12918 
12919 struct bpf_link *bpf_program__attach_freplace(const struct bpf_program *prog,
12920 					      int target_fd,
12921 					      const char *attach_func_name)
12922 {
12923 	int btf_id;
12924 
12925 	if (!!target_fd != !!attach_func_name) {
12926 		pr_warn("prog '%s': supply none or both of target_fd and attach_func_name\n",
12927 			prog->name);
12928 		return libbpf_err_ptr(-EINVAL);
12929 	}
12930 
12931 	if (prog->type != BPF_PROG_TYPE_EXT) {
12932 		pr_warn("prog '%s': only BPF_PROG_TYPE_EXT can attach as freplace\n",
12933 			prog->name);
12934 		return libbpf_err_ptr(-EINVAL);
12935 	}
12936 
12937 	if (target_fd) {
12938 		LIBBPF_OPTS(bpf_link_create_opts, target_opts);
12939 
12940 		btf_id = libbpf_find_prog_btf_id(attach_func_name, target_fd, prog->obj->token_fd);
12941 		if (btf_id < 0)
12942 			return libbpf_err_ptr(btf_id);
12943 
12944 		target_opts.target_btf_id = btf_id;
12945 
12946 		return bpf_program_attach_fd(prog, target_fd, "freplace",
12947 					     &target_opts);
12948 	} else {
12949 		/* no target, so use raw_tracepoint_open for compatibility
12950 		 * with old kernels
12951 		 */
12952 		return bpf_program__attach_trace(prog);
12953 	}
12954 }
12955 
12956 struct bpf_link *
12957 bpf_program__attach_iter(const struct bpf_program *prog,
12958 			 const struct bpf_iter_attach_opts *opts)
12959 {
12960 	DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
12961 	struct bpf_link *link;
12962 	int prog_fd, link_fd;
12963 	__u32 target_fd = 0;
12964 
12965 	if (!OPTS_VALID(opts, bpf_iter_attach_opts))
12966 		return libbpf_err_ptr(-EINVAL);
12967 
12968 	link_create_opts.iter_info = OPTS_GET(opts, link_info, (void *)0);
12969 	link_create_opts.iter_info_len = OPTS_GET(opts, link_info_len, 0);
12970 
12971 	prog_fd = bpf_program__fd(prog);
12972 	if (prog_fd < 0) {
12973 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12974 		return libbpf_err_ptr(-EINVAL);
12975 	}
12976 
12977 	link = calloc(1, sizeof(*link));
12978 	if (!link)
12979 		return libbpf_err_ptr(-ENOMEM);
12980 	link->detach = &bpf_link__detach_fd;
12981 
12982 	link_fd = bpf_link_create(prog_fd, target_fd, BPF_TRACE_ITER,
12983 				  &link_create_opts);
12984 	if (link_fd < 0) {
12985 		link_fd = -errno;
12986 		free(link);
12987 		pr_warn("prog '%s': failed to attach to iterator: %s\n",
12988 			prog->name, errstr(link_fd));
12989 		return libbpf_err_ptr(link_fd);
12990 	}
12991 	link->fd = link_fd;
12992 	return link;
12993 }
12994 
12995 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12996 {
12997 	*link = bpf_program__attach_iter(prog, NULL);
12998 	return libbpf_get_error(*link);
12999 }
13000 
13001 struct bpf_link *bpf_program__attach_netfilter(const struct bpf_program *prog,
13002 					       const struct bpf_netfilter_opts *opts)
13003 {
13004 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
13005 	struct bpf_link *link;
13006 	int prog_fd, link_fd;
13007 
13008 	if (!OPTS_VALID(opts, bpf_netfilter_opts))
13009 		return libbpf_err_ptr(-EINVAL);
13010 
13011 	prog_fd = bpf_program__fd(prog);
13012 	if (prog_fd < 0) {
13013 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
13014 		return libbpf_err_ptr(-EINVAL);
13015 	}
13016 
13017 	link = calloc(1, sizeof(*link));
13018 	if (!link)
13019 		return libbpf_err_ptr(-ENOMEM);
13020 
13021 	link->detach = &bpf_link__detach_fd;
13022 
13023 	lopts.netfilter.pf = OPTS_GET(opts, pf, 0);
13024 	lopts.netfilter.hooknum = OPTS_GET(opts, hooknum, 0);
13025 	lopts.netfilter.priority = OPTS_GET(opts, priority, 0);
13026 	lopts.netfilter.flags = OPTS_GET(opts, flags, 0);
13027 
13028 	link_fd = bpf_link_create(prog_fd, 0, BPF_NETFILTER, &lopts);
13029 	if (link_fd < 0) {
13030 		link_fd = -errno;
13031 		free(link);
13032 		pr_warn("prog '%s': failed to attach to netfilter: %s\n",
13033 			prog->name, errstr(link_fd));
13034 		return libbpf_err_ptr(link_fd);
13035 	}
13036 	link->fd = link_fd;
13037 
13038 	return link;
13039 }
13040 
13041 struct bpf_link *bpf_program__attach(const struct bpf_program *prog)
13042 {
13043 	struct bpf_link *link = NULL;
13044 	int err;
13045 
13046 	if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
13047 		return libbpf_err_ptr(-EOPNOTSUPP);
13048 
13049 	if (bpf_program__fd(prog) < 0) {
13050 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
13051 			prog->name);
13052 		return libbpf_err_ptr(-EINVAL);
13053 	}
13054 
13055 	err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, &link);
13056 	if (err)
13057 		return libbpf_err_ptr(err);
13058 
13059 	/* When calling bpf_program__attach() explicitly, auto-attach support
13060 	 * is expected to work, so NULL returned link is considered an error.
13061 	 * This is different for skeleton's attach, see comment in
13062 	 * bpf_object__attach_skeleton().
13063 	 */
13064 	if (!link)
13065 		return libbpf_err_ptr(-EOPNOTSUPP);
13066 
13067 	return link;
13068 }
13069 
13070 struct bpf_link_struct_ops {
13071 	struct bpf_link link;
13072 	int map_fd;
13073 };
13074 
13075 static int bpf_link__detach_struct_ops(struct bpf_link *link)
13076 {
13077 	struct bpf_link_struct_ops *st_link;
13078 	__u32 zero = 0;
13079 
13080 	st_link = container_of(link, struct bpf_link_struct_ops, link);
13081 
13082 	if (st_link->map_fd < 0)
13083 		/* w/o a real link */
13084 		return bpf_map_delete_elem(link->fd, &zero);
13085 
13086 	return close(link->fd);
13087 }
13088 
13089 struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map)
13090 {
13091 	struct bpf_link_struct_ops *link;
13092 	__u32 zero = 0;
13093 	int err, fd;
13094 
13095 	if (!bpf_map__is_struct_ops(map)) {
13096 		pr_warn("map '%s': can't attach non-struct_ops map\n", map->name);
13097 		return libbpf_err_ptr(-EINVAL);
13098 	}
13099 
13100 	if (map->fd < 0) {
13101 		pr_warn("map '%s': can't attach BPF map without FD (was it created?)\n", map->name);
13102 		return libbpf_err_ptr(-EINVAL);
13103 	}
13104 
13105 	link = calloc(1, sizeof(*link));
13106 	if (!link)
13107 		return libbpf_err_ptr(-EINVAL);
13108 
13109 	/* kern_vdata should be prepared during the loading phase. */
13110 	err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
13111 	/* It can be EBUSY if the map has been used to create or
13112 	 * update a link before.  We don't allow updating the value of
13113 	 * a struct_ops once it is set.  That ensures that the value
13114 	 * never changed.  So, it is safe to skip EBUSY.
13115 	 */
13116 	if (err && (!(map->def.map_flags & BPF_F_LINK) || err != -EBUSY)) {
13117 		free(link);
13118 		return libbpf_err_ptr(err);
13119 	}
13120 
13121 	link->link.detach = bpf_link__detach_struct_ops;
13122 
13123 	if (!(map->def.map_flags & BPF_F_LINK)) {
13124 		/* w/o a real link */
13125 		link->link.fd = map->fd;
13126 		link->map_fd = -1;
13127 		return &link->link;
13128 	}
13129 
13130 	fd = bpf_link_create(map->fd, 0, BPF_STRUCT_OPS, NULL);
13131 	if (fd < 0) {
13132 		free(link);
13133 		return libbpf_err_ptr(fd);
13134 	}
13135 
13136 	link->link.fd = fd;
13137 	link->map_fd = map->fd;
13138 
13139 	return &link->link;
13140 }
13141 
13142 /*
13143  * Swap the back struct_ops of a link with a new struct_ops map.
13144  */
13145 int bpf_link__update_map(struct bpf_link *link, const struct bpf_map *map)
13146 {
13147 	struct bpf_link_struct_ops *st_ops_link;
13148 	__u32 zero = 0;
13149 	int err;
13150 
13151 	if (!bpf_map__is_struct_ops(map))
13152 		return libbpf_err(-EINVAL);
13153 
13154 	if (map->fd < 0) {
13155 		pr_warn("map '%s': can't use BPF map without FD (was it created?)\n", map->name);
13156 		return libbpf_err(-EINVAL);
13157 	}
13158 
13159 	st_ops_link = container_of(link, struct bpf_link_struct_ops, link);
13160 	/* Ensure the type of a link is correct */
13161 	if (st_ops_link->map_fd < 0)
13162 		return libbpf_err(-EINVAL);
13163 
13164 	err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
13165 	/* It can be EBUSY if the map has been used to create or
13166 	 * update a link before.  We don't allow updating the value of
13167 	 * a struct_ops once it is set.  That ensures that the value
13168 	 * never changed.  So, it is safe to skip EBUSY.
13169 	 */
13170 	if (err && err != -EBUSY)
13171 		return err;
13172 
13173 	err = bpf_link_update(link->fd, map->fd, NULL);
13174 	if (err < 0)
13175 		return err;
13176 
13177 	st_ops_link->map_fd = map->fd;
13178 
13179 	return 0;
13180 }
13181 
13182 typedef enum bpf_perf_event_ret (*bpf_perf_event_print_t)(struct perf_event_header *hdr,
13183 							  void *private_data);
13184 
13185 static enum bpf_perf_event_ret
13186 perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
13187 		       void **copy_mem, size_t *copy_size,
13188 		       bpf_perf_event_print_t fn, void *private_data)
13189 {
13190 	struct perf_event_mmap_page *header = mmap_mem;
13191 	__u64 data_head = ring_buffer_read_head(header);
13192 	__u64 data_tail = header->data_tail;
13193 	void *base = ((__u8 *)header) + page_size;
13194 	int ret = LIBBPF_PERF_EVENT_CONT;
13195 	struct perf_event_header *ehdr;
13196 	size_t ehdr_size;
13197 
13198 	while (data_head != data_tail) {
13199 		ehdr = base + (data_tail & (mmap_size - 1));
13200 		ehdr_size = ehdr->size;
13201 
13202 		if (((void *)ehdr) + ehdr_size > base + mmap_size) {
13203 			void *copy_start = ehdr;
13204 			size_t len_first = base + mmap_size - copy_start;
13205 			size_t len_secnd = ehdr_size - len_first;
13206 
13207 			if (*copy_size < ehdr_size) {
13208 				free(*copy_mem);
13209 				*copy_mem = malloc(ehdr_size);
13210 				if (!*copy_mem) {
13211 					*copy_size = 0;
13212 					ret = LIBBPF_PERF_EVENT_ERROR;
13213 					break;
13214 				}
13215 				*copy_size = ehdr_size;
13216 			}
13217 
13218 			memcpy(*copy_mem, copy_start, len_first);
13219 			memcpy(*copy_mem + len_first, base, len_secnd);
13220 			ehdr = *copy_mem;
13221 		}
13222 
13223 		ret = fn(ehdr, private_data);
13224 		data_tail += ehdr_size;
13225 		if (ret != LIBBPF_PERF_EVENT_CONT)
13226 			break;
13227 	}
13228 
13229 	ring_buffer_write_tail(header, data_tail);
13230 	return libbpf_err(ret);
13231 }
13232 
13233 struct perf_buffer;
13234 
13235 struct perf_buffer_params {
13236 	struct perf_event_attr *attr;
13237 	/* if event_cb is specified, it takes precendence */
13238 	perf_buffer_event_fn event_cb;
13239 	/* sample_cb and lost_cb are higher-level common-case callbacks */
13240 	perf_buffer_sample_fn sample_cb;
13241 	perf_buffer_lost_fn lost_cb;
13242 	void *ctx;
13243 	int cpu_cnt;
13244 	int *cpus;
13245 	int *map_keys;
13246 };
13247 
13248 struct perf_cpu_buf {
13249 	struct perf_buffer *pb;
13250 	void *base; /* mmap()'ed memory */
13251 	void *buf; /* for reconstructing segmented data */
13252 	size_t buf_size;
13253 	int fd;
13254 	int cpu;
13255 	int map_key;
13256 };
13257 
13258 struct perf_buffer {
13259 	perf_buffer_event_fn event_cb;
13260 	perf_buffer_sample_fn sample_cb;
13261 	perf_buffer_lost_fn lost_cb;
13262 	void *ctx; /* passed into callbacks */
13263 
13264 	size_t page_size;
13265 	size_t mmap_size;
13266 	struct perf_cpu_buf **cpu_bufs;
13267 	struct epoll_event *events;
13268 	int cpu_cnt; /* number of allocated CPU buffers */
13269 	int epoll_fd; /* perf event FD */
13270 	int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
13271 };
13272 
13273 static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
13274 				      struct perf_cpu_buf *cpu_buf)
13275 {
13276 	if (!cpu_buf)
13277 		return;
13278 	if (cpu_buf->base &&
13279 	    munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
13280 		pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
13281 	if (cpu_buf->fd >= 0) {
13282 		ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
13283 		close(cpu_buf->fd);
13284 	}
13285 	free(cpu_buf->buf);
13286 	free(cpu_buf);
13287 }
13288 
13289 void perf_buffer__free(struct perf_buffer *pb)
13290 {
13291 	int i;
13292 
13293 	if (IS_ERR_OR_NULL(pb))
13294 		return;
13295 	if (pb->cpu_bufs) {
13296 		for (i = 0; i < pb->cpu_cnt; i++) {
13297 			struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
13298 
13299 			if (!cpu_buf)
13300 				continue;
13301 
13302 			bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
13303 			perf_buffer__free_cpu_buf(pb, cpu_buf);
13304 		}
13305 		free(pb->cpu_bufs);
13306 	}
13307 	if (pb->epoll_fd >= 0)
13308 		close(pb->epoll_fd);
13309 	free(pb->events);
13310 	free(pb);
13311 }
13312 
13313 static struct perf_cpu_buf *
13314 perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
13315 			  int cpu, int map_key)
13316 {
13317 	struct perf_cpu_buf *cpu_buf;
13318 	int err;
13319 
13320 	cpu_buf = calloc(1, sizeof(*cpu_buf));
13321 	if (!cpu_buf)
13322 		return ERR_PTR(-ENOMEM);
13323 
13324 	cpu_buf->pb = pb;
13325 	cpu_buf->cpu = cpu;
13326 	cpu_buf->map_key = map_key;
13327 
13328 	cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
13329 			      -1, PERF_FLAG_FD_CLOEXEC);
13330 	if (cpu_buf->fd < 0) {
13331 		err = -errno;
13332 		pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
13333 			cpu, errstr(err));
13334 		goto error;
13335 	}
13336 
13337 	cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
13338 			     PROT_READ | PROT_WRITE, MAP_SHARED,
13339 			     cpu_buf->fd, 0);
13340 	if (cpu_buf->base == MAP_FAILED) {
13341 		cpu_buf->base = NULL;
13342 		err = -errno;
13343 		pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
13344 			cpu, errstr(err));
13345 		goto error;
13346 	}
13347 
13348 	if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
13349 		err = -errno;
13350 		pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
13351 			cpu, errstr(err));
13352 		goto error;
13353 	}
13354 
13355 	return cpu_buf;
13356 
13357 error:
13358 	perf_buffer__free_cpu_buf(pb, cpu_buf);
13359 	return (struct perf_cpu_buf *)ERR_PTR(err);
13360 }
13361 
13362 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
13363 					      struct perf_buffer_params *p);
13364 
13365 struct perf_buffer *perf_buffer__new(int map_fd, size_t page_cnt,
13366 				     perf_buffer_sample_fn sample_cb,
13367 				     perf_buffer_lost_fn lost_cb,
13368 				     void *ctx,
13369 				     const struct perf_buffer_opts *opts)
13370 {
13371 	const size_t attr_sz = sizeof(struct perf_event_attr);
13372 	struct perf_buffer_params p = {};
13373 	struct perf_event_attr attr;
13374 	__u32 sample_period;
13375 
13376 	if (!OPTS_VALID(opts, perf_buffer_opts))
13377 		return libbpf_err_ptr(-EINVAL);
13378 
13379 	sample_period = OPTS_GET(opts, sample_period, 1);
13380 	if (!sample_period)
13381 		sample_period = 1;
13382 
13383 	memset(&attr, 0, attr_sz);
13384 	attr.size = attr_sz;
13385 	attr.config = PERF_COUNT_SW_BPF_OUTPUT;
13386 	attr.type = PERF_TYPE_SOFTWARE;
13387 	attr.sample_type = PERF_SAMPLE_RAW;
13388 	attr.wakeup_events = sample_period;
13389 
13390 	p.attr = &attr;
13391 	p.sample_cb = sample_cb;
13392 	p.lost_cb = lost_cb;
13393 	p.ctx = ctx;
13394 
13395 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
13396 }
13397 
13398 struct perf_buffer *perf_buffer__new_raw(int map_fd, size_t page_cnt,
13399 					 struct perf_event_attr *attr,
13400 					 perf_buffer_event_fn event_cb, void *ctx,
13401 					 const struct perf_buffer_raw_opts *opts)
13402 {
13403 	struct perf_buffer_params p = {};
13404 
13405 	if (!attr)
13406 		return libbpf_err_ptr(-EINVAL);
13407 
13408 	if (!OPTS_VALID(opts, perf_buffer_raw_opts))
13409 		return libbpf_err_ptr(-EINVAL);
13410 
13411 	p.attr = attr;
13412 	p.event_cb = event_cb;
13413 	p.ctx = ctx;
13414 	p.cpu_cnt = OPTS_GET(opts, cpu_cnt, 0);
13415 	p.cpus = OPTS_GET(opts, cpus, NULL);
13416 	p.map_keys = OPTS_GET(opts, map_keys, NULL);
13417 
13418 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
13419 }
13420 
13421 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
13422 					      struct perf_buffer_params *p)
13423 {
13424 	const char *online_cpus_file = "/sys/devices/system/cpu/online";
13425 	struct bpf_map_info map;
13426 	struct perf_buffer *pb;
13427 	bool *online = NULL;
13428 	__u32 map_info_len;
13429 	int err, i, j, n;
13430 
13431 	if (page_cnt == 0 || (page_cnt & (page_cnt - 1))) {
13432 		pr_warn("page count should be power of two, but is %zu\n",
13433 			page_cnt);
13434 		return ERR_PTR(-EINVAL);
13435 	}
13436 
13437 	/* best-effort sanity checks */
13438 	memset(&map, 0, sizeof(map));
13439 	map_info_len = sizeof(map);
13440 	err = bpf_map_get_info_by_fd(map_fd, &map, &map_info_len);
13441 	if (err) {
13442 		err = -errno;
13443 		/* if BPF_OBJ_GET_INFO_BY_FD is supported, will return
13444 		 * -EBADFD, -EFAULT, or -E2BIG on real error
13445 		 */
13446 		if (err != -EINVAL) {
13447 			pr_warn("failed to get map info for map FD %d: %s\n",
13448 				map_fd, errstr(err));
13449 			return ERR_PTR(err);
13450 		}
13451 		pr_debug("failed to get map info for FD %d; API not supported? Ignoring...\n",
13452 			 map_fd);
13453 	} else {
13454 		if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
13455 			pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
13456 				map.name);
13457 			return ERR_PTR(-EINVAL);
13458 		}
13459 	}
13460 
13461 	pb = calloc(1, sizeof(*pb));
13462 	if (!pb)
13463 		return ERR_PTR(-ENOMEM);
13464 
13465 	pb->event_cb = p->event_cb;
13466 	pb->sample_cb = p->sample_cb;
13467 	pb->lost_cb = p->lost_cb;
13468 	pb->ctx = p->ctx;
13469 
13470 	pb->page_size = getpagesize();
13471 	pb->mmap_size = pb->page_size * page_cnt;
13472 	pb->map_fd = map_fd;
13473 
13474 	pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
13475 	if (pb->epoll_fd < 0) {
13476 		err = -errno;
13477 		pr_warn("failed to create epoll instance: %s\n",
13478 			errstr(err));
13479 		goto error;
13480 	}
13481 
13482 	if (p->cpu_cnt > 0) {
13483 		pb->cpu_cnt = p->cpu_cnt;
13484 	} else {
13485 		pb->cpu_cnt = libbpf_num_possible_cpus();
13486 		if (pb->cpu_cnt < 0) {
13487 			err = pb->cpu_cnt;
13488 			goto error;
13489 		}
13490 		if (map.max_entries && map.max_entries < pb->cpu_cnt)
13491 			pb->cpu_cnt = map.max_entries;
13492 	}
13493 
13494 	pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
13495 	if (!pb->events) {
13496 		err = -ENOMEM;
13497 		pr_warn("failed to allocate events: out of memory\n");
13498 		goto error;
13499 	}
13500 	pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
13501 	if (!pb->cpu_bufs) {
13502 		err = -ENOMEM;
13503 		pr_warn("failed to allocate buffers: out of memory\n");
13504 		goto error;
13505 	}
13506 
13507 	err = parse_cpu_mask_file(online_cpus_file, &online, &n);
13508 	if (err) {
13509 		pr_warn("failed to get online CPU mask: %s\n", errstr(err));
13510 		goto error;
13511 	}
13512 
13513 	for (i = 0, j = 0; i < pb->cpu_cnt; i++) {
13514 		struct perf_cpu_buf *cpu_buf;
13515 		int cpu, map_key;
13516 
13517 		cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
13518 		map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
13519 
13520 		/* in case user didn't explicitly requested particular CPUs to
13521 		 * be attached to, skip offline/not present CPUs
13522 		 */
13523 		if (p->cpu_cnt <= 0 && (cpu >= n || !online[cpu]))
13524 			continue;
13525 
13526 		cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
13527 		if (IS_ERR(cpu_buf)) {
13528 			err = PTR_ERR(cpu_buf);
13529 			goto error;
13530 		}
13531 
13532 		pb->cpu_bufs[j] = cpu_buf;
13533 
13534 		err = bpf_map_update_elem(pb->map_fd, &map_key,
13535 					  &cpu_buf->fd, 0);
13536 		if (err) {
13537 			err = -errno;
13538 			pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
13539 				cpu, map_key, cpu_buf->fd,
13540 				errstr(err));
13541 			goto error;
13542 		}
13543 
13544 		pb->events[j].events = EPOLLIN;
13545 		pb->events[j].data.ptr = cpu_buf;
13546 		if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
13547 			      &pb->events[j]) < 0) {
13548 			err = -errno;
13549 			pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
13550 				cpu, cpu_buf->fd,
13551 				errstr(err));
13552 			goto error;
13553 		}
13554 		j++;
13555 	}
13556 	pb->cpu_cnt = j;
13557 	free(online);
13558 
13559 	return pb;
13560 
13561 error:
13562 	free(online);
13563 	if (pb)
13564 		perf_buffer__free(pb);
13565 	return ERR_PTR(err);
13566 }
13567 
13568 struct perf_sample_raw {
13569 	struct perf_event_header header;
13570 	uint32_t size;
13571 	char data[];
13572 };
13573 
13574 struct perf_sample_lost {
13575 	struct perf_event_header header;
13576 	uint64_t id;
13577 	uint64_t lost;
13578 	uint64_t sample_id;
13579 };
13580 
13581 static enum bpf_perf_event_ret
13582 perf_buffer__process_record(struct perf_event_header *e, void *ctx)
13583 {
13584 	struct perf_cpu_buf *cpu_buf = ctx;
13585 	struct perf_buffer *pb = cpu_buf->pb;
13586 	void *data = e;
13587 
13588 	/* user wants full control over parsing perf event */
13589 	if (pb->event_cb)
13590 		return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
13591 
13592 	switch (e->type) {
13593 	case PERF_RECORD_SAMPLE: {
13594 		struct perf_sample_raw *s = data;
13595 
13596 		if (pb->sample_cb)
13597 			pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
13598 		break;
13599 	}
13600 	case PERF_RECORD_LOST: {
13601 		struct perf_sample_lost *s = data;
13602 
13603 		if (pb->lost_cb)
13604 			pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
13605 		break;
13606 	}
13607 	default:
13608 		pr_warn("unknown perf sample type %d\n", e->type);
13609 		return LIBBPF_PERF_EVENT_ERROR;
13610 	}
13611 	return LIBBPF_PERF_EVENT_CONT;
13612 }
13613 
13614 static int perf_buffer__process_records(struct perf_buffer *pb,
13615 					struct perf_cpu_buf *cpu_buf)
13616 {
13617 	enum bpf_perf_event_ret ret;
13618 
13619 	ret = perf_event_read_simple(cpu_buf->base, pb->mmap_size,
13620 				     pb->page_size, &cpu_buf->buf,
13621 				     &cpu_buf->buf_size,
13622 				     perf_buffer__process_record, cpu_buf);
13623 	if (ret != LIBBPF_PERF_EVENT_CONT)
13624 		return ret;
13625 	return 0;
13626 }
13627 
13628 int perf_buffer__epoll_fd(const struct perf_buffer *pb)
13629 {
13630 	return pb->epoll_fd;
13631 }
13632 
13633 int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
13634 {
13635 	int i, cnt, err;
13636 
13637 	cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
13638 	if (cnt < 0)
13639 		return -errno;
13640 
13641 	for (i = 0; i < cnt; i++) {
13642 		struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
13643 
13644 		err = perf_buffer__process_records(pb, cpu_buf);
13645 		if (err) {
13646 			pr_warn("error while processing records: %s\n", errstr(err));
13647 			return libbpf_err(err);
13648 		}
13649 	}
13650 	return cnt;
13651 }
13652 
13653 /* Return number of PERF_EVENT_ARRAY map slots set up by this perf_buffer
13654  * manager.
13655  */
13656 size_t perf_buffer__buffer_cnt(const struct perf_buffer *pb)
13657 {
13658 	return pb->cpu_cnt;
13659 }
13660 
13661 /*
13662  * Return perf_event FD of a ring buffer in *buf_idx* slot of
13663  * PERF_EVENT_ARRAY BPF map. This FD can be polled for new data using
13664  * select()/poll()/epoll() Linux syscalls.
13665  */
13666 int perf_buffer__buffer_fd(const struct perf_buffer *pb, size_t buf_idx)
13667 {
13668 	struct perf_cpu_buf *cpu_buf;
13669 
13670 	if (buf_idx >= pb->cpu_cnt)
13671 		return libbpf_err(-EINVAL);
13672 
13673 	cpu_buf = pb->cpu_bufs[buf_idx];
13674 	if (!cpu_buf)
13675 		return libbpf_err(-ENOENT);
13676 
13677 	return cpu_buf->fd;
13678 }
13679 
13680 int perf_buffer__buffer(struct perf_buffer *pb, int buf_idx, void **buf, size_t *buf_size)
13681 {
13682 	struct perf_cpu_buf *cpu_buf;
13683 
13684 	if (buf_idx >= pb->cpu_cnt)
13685 		return libbpf_err(-EINVAL);
13686 
13687 	cpu_buf = pb->cpu_bufs[buf_idx];
13688 	if (!cpu_buf)
13689 		return libbpf_err(-ENOENT);
13690 
13691 	*buf = cpu_buf->base;
13692 	*buf_size = pb->mmap_size;
13693 	return 0;
13694 }
13695 
13696 /*
13697  * Consume data from perf ring buffer corresponding to slot *buf_idx* in
13698  * PERF_EVENT_ARRAY BPF map without waiting/polling. If there is no data to
13699  * consume, do nothing and return success.
13700  * Returns:
13701  *   - 0 on success;
13702  *   - <0 on failure.
13703  */
13704 int perf_buffer__consume_buffer(struct perf_buffer *pb, size_t buf_idx)
13705 {
13706 	struct perf_cpu_buf *cpu_buf;
13707 
13708 	if (buf_idx >= pb->cpu_cnt)
13709 		return libbpf_err(-EINVAL);
13710 
13711 	cpu_buf = pb->cpu_bufs[buf_idx];
13712 	if (!cpu_buf)
13713 		return libbpf_err(-ENOENT);
13714 
13715 	return perf_buffer__process_records(pb, cpu_buf);
13716 }
13717 
13718 int perf_buffer__consume(struct perf_buffer *pb)
13719 {
13720 	int i, err;
13721 
13722 	for (i = 0; i < pb->cpu_cnt; i++) {
13723 		struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
13724 
13725 		if (!cpu_buf)
13726 			continue;
13727 
13728 		err = perf_buffer__process_records(pb, cpu_buf);
13729 		if (err) {
13730 			pr_warn("perf_buffer: failed to process records in buffer #%d: %s\n",
13731 				i, errstr(err));
13732 			return libbpf_err(err);
13733 		}
13734 	}
13735 	return 0;
13736 }
13737 
13738 int bpf_program__set_attach_target(struct bpf_program *prog,
13739 				   int attach_prog_fd,
13740 				   const char *attach_func_name)
13741 {
13742 	int btf_obj_fd = 0, btf_id = 0, err;
13743 
13744 	if (!prog || attach_prog_fd < 0)
13745 		return libbpf_err(-EINVAL);
13746 
13747 	if (prog->obj->state >= OBJ_LOADED)
13748 		return libbpf_err(-EINVAL);
13749 
13750 	if (attach_prog_fd && !attach_func_name) {
13751 		/* remember attach_prog_fd and let bpf_program__load() find
13752 		 * BTF ID during the program load
13753 		 */
13754 		prog->attach_prog_fd = attach_prog_fd;
13755 		return 0;
13756 	}
13757 
13758 	if (attach_prog_fd) {
13759 		btf_id = libbpf_find_prog_btf_id(attach_func_name,
13760 						 attach_prog_fd, prog->obj->token_fd);
13761 		if (btf_id < 0)
13762 			return libbpf_err(btf_id);
13763 	} else {
13764 		if (!attach_func_name)
13765 			return libbpf_err(-EINVAL);
13766 
13767 		/* load btf_vmlinux, if not yet */
13768 		err = bpf_object__load_vmlinux_btf(prog->obj, true);
13769 		if (err)
13770 			return libbpf_err(err);
13771 		err = find_kernel_btf_id(prog->obj, attach_func_name,
13772 					 prog->expected_attach_type,
13773 					 &btf_obj_fd, &btf_id);
13774 		if (err)
13775 			return libbpf_err(err);
13776 	}
13777 
13778 	prog->attach_btf_id = btf_id;
13779 	prog->attach_btf_obj_fd = btf_obj_fd;
13780 	prog->attach_prog_fd = attach_prog_fd;
13781 	return 0;
13782 }
13783 
13784 int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz)
13785 {
13786 	int err = 0, n, len, start, end = -1;
13787 	bool *tmp;
13788 
13789 	*mask = NULL;
13790 	*mask_sz = 0;
13791 
13792 	/* Each sub string separated by ',' has format \d+-\d+ or \d+ */
13793 	while (*s) {
13794 		if (*s == ',' || *s == '\n') {
13795 			s++;
13796 			continue;
13797 		}
13798 		n = sscanf(s, "%d%n-%d%n", &start, &len, &end, &len);
13799 		if (n <= 0 || n > 2) {
13800 			pr_warn("Failed to get CPU range %s: %d\n", s, n);
13801 			err = -EINVAL;
13802 			goto cleanup;
13803 		} else if (n == 1) {
13804 			end = start;
13805 		}
13806 		if (start < 0 || start > end) {
13807 			pr_warn("Invalid CPU range [%d,%d] in %s\n",
13808 				start, end, s);
13809 			err = -EINVAL;
13810 			goto cleanup;
13811 		}
13812 		tmp = realloc(*mask, end + 1);
13813 		if (!tmp) {
13814 			err = -ENOMEM;
13815 			goto cleanup;
13816 		}
13817 		*mask = tmp;
13818 		memset(tmp + *mask_sz, 0, start - *mask_sz);
13819 		memset(tmp + start, 1, end - start + 1);
13820 		*mask_sz = end + 1;
13821 		s += len;
13822 	}
13823 	if (!*mask_sz) {
13824 		pr_warn("Empty CPU range\n");
13825 		return -EINVAL;
13826 	}
13827 	return 0;
13828 cleanup:
13829 	free(*mask);
13830 	*mask = NULL;
13831 	return err;
13832 }
13833 
13834 int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz)
13835 {
13836 	int fd, err = 0, len;
13837 	char buf[128];
13838 
13839 	fd = open(fcpu, O_RDONLY | O_CLOEXEC);
13840 	if (fd < 0) {
13841 		err = -errno;
13842 		pr_warn("Failed to open cpu mask file %s: %s\n", fcpu, errstr(err));
13843 		return err;
13844 	}
13845 	len = read(fd, buf, sizeof(buf));
13846 	close(fd);
13847 	if (len <= 0) {
13848 		err = len ? -errno : -EINVAL;
13849 		pr_warn("Failed to read cpu mask from %s: %s\n", fcpu, errstr(err));
13850 		return err;
13851 	}
13852 	if (len >= sizeof(buf)) {
13853 		pr_warn("CPU mask is too big in file %s\n", fcpu);
13854 		return -E2BIG;
13855 	}
13856 	buf[len] = '\0';
13857 
13858 	return parse_cpu_mask_str(buf, mask, mask_sz);
13859 }
13860 
13861 int libbpf_num_possible_cpus(void)
13862 {
13863 	static const char *fcpu = "/sys/devices/system/cpu/possible";
13864 	static int cpus;
13865 	int err, n, i, tmp_cpus;
13866 	bool *mask;
13867 
13868 	tmp_cpus = READ_ONCE(cpus);
13869 	if (tmp_cpus > 0)
13870 		return tmp_cpus;
13871 
13872 	err = parse_cpu_mask_file(fcpu, &mask, &n);
13873 	if (err)
13874 		return libbpf_err(err);
13875 
13876 	tmp_cpus = 0;
13877 	for (i = 0; i < n; i++) {
13878 		if (mask[i])
13879 			tmp_cpus++;
13880 	}
13881 	free(mask);
13882 
13883 	WRITE_ONCE(cpus, tmp_cpus);
13884 	return tmp_cpus;
13885 }
13886 
13887 static int populate_skeleton_maps(const struct bpf_object *obj,
13888 				  struct bpf_map_skeleton *maps,
13889 				  size_t map_cnt, size_t map_skel_sz)
13890 {
13891 	int i;
13892 
13893 	for (i = 0; i < map_cnt; i++) {
13894 		struct bpf_map_skeleton *map_skel = (void *)maps + i * map_skel_sz;
13895 		struct bpf_map **map = map_skel->map;
13896 		const char *name = map_skel->name;
13897 		void **mmaped = map_skel->mmaped;
13898 
13899 		*map = bpf_object__find_map_by_name(obj, name);
13900 		if (!*map) {
13901 			pr_warn("failed to find skeleton map '%s'\n", name);
13902 			return -ESRCH;
13903 		}
13904 
13905 		/* externs shouldn't be pre-setup from user code */
13906 		if (mmaped && (*map)->libbpf_type != LIBBPF_MAP_KCONFIG)
13907 			*mmaped = (*map)->mmaped;
13908 	}
13909 	return 0;
13910 }
13911 
13912 static int populate_skeleton_progs(const struct bpf_object *obj,
13913 				   struct bpf_prog_skeleton *progs,
13914 				   size_t prog_cnt, size_t prog_skel_sz)
13915 {
13916 	int i;
13917 
13918 	for (i = 0; i < prog_cnt; i++) {
13919 		struct bpf_prog_skeleton *prog_skel = (void *)progs + i * prog_skel_sz;
13920 		struct bpf_program **prog = prog_skel->prog;
13921 		const char *name = prog_skel->name;
13922 
13923 		*prog = bpf_object__find_program_by_name(obj, name);
13924 		if (!*prog) {
13925 			pr_warn("failed to find skeleton program '%s'\n", name);
13926 			return -ESRCH;
13927 		}
13928 	}
13929 	return 0;
13930 }
13931 
13932 int bpf_object__open_skeleton(struct bpf_object_skeleton *s,
13933 			      const struct bpf_object_open_opts *opts)
13934 {
13935 	struct bpf_object *obj;
13936 	int err;
13937 
13938 	obj = bpf_object_open(NULL, s->data, s->data_sz, s->name, opts);
13939 	if (IS_ERR(obj)) {
13940 		err = PTR_ERR(obj);
13941 		pr_warn("failed to initialize skeleton BPF object '%s': %s\n",
13942 			s->name, errstr(err));
13943 		return libbpf_err(err);
13944 	}
13945 
13946 	*s->obj = obj;
13947 	err = populate_skeleton_maps(obj, s->maps, s->map_cnt, s->map_skel_sz);
13948 	if (err) {
13949 		pr_warn("failed to populate skeleton maps for '%s': %s\n", s->name, errstr(err));
13950 		return libbpf_err(err);
13951 	}
13952 
13953 	err = populate_skeleton_progs(obj, s->progs, s->prog_cnt, s->prog_skel_sz);
13954 	if (err) {
13955 		pr_warn("failed to populate skeleton progs for '%s': %s\n", s->name, errstr(err));
13956 		return libbpf_err(err);
13957 	}
13958 
13959 	return 0;
13960 }
13961 
13962 int bpf_object__open_subskeleton(struct bpf_object_subskeleton *s)
13963 {
13964 	int err, len, var_idx, i;
13965 	const char *var_name;
13966 	const struct bpf_map *map;
13967 	struct btf *btf;
13968 	__u32 map_type_id;
13969 	const struct btf_type *map_type, *var_type;
13970 	const struct bpf_var_skeleton *var_skel;
13971 	struct btf_var_secinfo *var;
13972 
13973 	if (!s->obj)
13974 		return libbpf_err(-EINVAL);
13975 
13976 	btf = bpf_object__btf(s->obj);
13977 	if (!btf) {
13978 		pr_warn("subskeletons require BTF at runtime (object %s)\n",
13979 			bpf_object__name(s->obj));
13980 		return libbpf_err(-errno);
13981 	}
13982 
13983 	err = populate_skeleton_maps(s->obj, s->maps, s->map_cnt, s->map_skel_sz);
13984 	if (err) {
13985 		pr_warn("failed to populate subskeleton maps: %s\n", errstr(err));
13986 		return libbpf_err(err);
13987 	}
13988 
13989 	err = populate_skeleton_progs(s->obj, s->progs, s->prog_cnt, s->prog_skel_sz);
13990 	if (err) {
13991 		pr_warn("failed to populate subskeleton maps: %s\n", errstr(err));
13992 		return libbpf_err(err);
13993 	}
13994 
13995 	for (var_idx = 0; var_idx < s->var_cnt; var_idx++) {
13996 		var_skel = (void *)s->vars + var_idx * s->var_skel_sz;
13997 		map = *var_skel->map;
13998 		map_type_id = bpf_map__btf_value_type_id(map);
13999 		map_type = btf__type_by_id(btf, map_type_id);
14000 
14001 		if (!btf_is_datasec(map_type)) {
14002 			pr_warn("type for map '%1$s' is not a datasec: %2$s\n",
14003 				bpf_map__name(map),
14004 				__btf_kind_str(btf_kind(map_type)));
14005 			return libbpf_err(-EINVAL);
14006 		}
14007 
14008 		len = btf_vlen(map_type);
14009 		var = btf_var_secinfos(map_type);
14010 		for (i = 0; i < len; i++, var++) {
14011 			var_type = btf__type_by_id(btf, var->type);
14012 			var_name = btf__name_by_offset(btf, var_type->name_off);
14013 			if (strcmp(var_name, var_skel->name) == 0) {
14014 				*var_skel->addr = map->mmaped + var->offset;
14015 				break;
14016 			}
14017 		}
14018 	}
14019 	return 0;
14020 }
14021 
14022 void bpf_object__destroy_subskeleton(struct bpf_object_subskeleton *s)
14023 {
14024 	if (!s)
14025 		return;
14026 	free(s->maps);
14027 	free(s->progs);
14028 	free(s->vars);
14029 	free(s);
14030 }
14031 
14032 int bpf_object__load_skeleton(struct bpf_object_skeleton *s)
14033 {
14034 	int i, err;
14035 
14036 	err = bpf_object__load(*s->obj);
14037 	if (err) {
14038 		pr_warn("failed to load BPF skeleton '%s': %s\n", s->name, errstr(err));
14039 		return libbpf_err(err);
14040 	}
14041 
14042 	for (i = 0; i < s->map_cnt; i++) {
14043 		struct bpf_map_skeleton *map_skel = (void *)s->maps + i * s->map_skel_sz;
14044 		struct bpf_map *map = *map_skel->map;
14045 
14046 		if (!map_skel->mmaped)
14047 			continue;
14048 
14049 		*map_skel->mmaped = map->mmaped;
14050 	}
14051 
14052 	return 0;
14053 }
14054 
14055 int bpf_object__attach_skeleton(struct bpf_object_skeleton *s)
14056 {
14057 	int i, err;
14058 
14059 	for (i = 0; i < s->prog_cnt; i++) {
14060 		struct bpf_prog_skeleton *prog_skel = (void *)s->progs + i * s->prog_skel_sz;
14061 		struct bpf_program *prog = *prog_skel->prog;
14062 		struct bpf_link **link = prog_skel->link;
14063 
14064 		if (!prog->autoload || !prog->autoattach)
14065 			continue;
14066 
14067 		/* auto-attaching not supported for this program */
14068 		if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
14069 			continue;
14070 
14071 		/* if user already set the link manually, don't attempt auto-attach */
14072 		if (*link)
14073 			continue;
14074 
14075 		err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, link);
14076 		if (err) {
14077 			pr_warn("prog '%s': failed to auto-attach: %s\n",
14078 				bpf_program__name(prog), errstr(err));
14079 			return libbpf_err(err);
14080 		}
14081 
14082 		/* It's possible that for some SEC() definitions auto-attach
14083 		 * is supported in some cases (e.g., if definition completely
14084 		 * specifies target information), but is not in other cases.
14085 		 * SEC("uprobe") is one such case. If user specified target
14086 		 * binary and function name, such BPF program can be
14087 		 * auto-attached. But if not, it shouldn't trigger skeleton's
14088 		 * attach to fail. It should just be skipped.
14089 		 * attach_fn signals such case with returning 0 (no error) and
14090 		 * setting link to NULL.
14091 		 */
14092 	}
14093 
14094 
14095 	for (i = 0; i < s->map_cnt; i++) {
14096 		struct bpf_map_skeleton *map_skel = (void *)s->maps + i * s->map_skel_sz;
14097 		struct bpf_map *map = *map_skel->map;
14098 		struct bpf_link **link;
14099 
14100 		if (!map->autocreate || !map->autoattach)
14101 			continue;
14102 
14103 		/* only struct_ops maps can be attached */
14104 		if (!bpf_map__is_struct_ops(map))
14105 			continue;
14106 
14107 		/* skeleton is created with earlier version of bpftool, notify user */
14108 		if (s->map_skel_sz < offsetofend(struct bpf_map_skeleton, link)) {
14109 			pr_warn("map '%s': BPF skeleton version is old, skipping map auto-attachment...\n",
14110 				bpf_map__name(map));
14111 			continue;
14112 		}
14113 
14114 		link = map_skel->link;
14115 		if (!link) {
14116 			pr_warn("map '%s': BPF map skeleton link is uninitialized\n",
14117 				bpf_map__name(map));
14118 			continue;
14119 		}
14120 
14121 		if (*link)
14122 			continue;
14123 
14124 		*link = bpf_map__attach_struct_ops(map);
14125 		if (!*link) {
14126 			err = -errno;
14127 			pr_warn("map '%s': failed to auto-attach: %s\n",
14128 				bpf_map__name(map), errstr(err));
14129 			return libbpf_err(err);
14130 		}
14131 	}
14132 
14133 	return 0;
14134 }
14135 
14136 void bpf_object__detach_skeleton(struct bpf_object_skeleton *s)
14137 {
14138 	int i;
14139 
14140 	for (i = 0; i < s->prog_cnt; i++) {
14141 		struct bpf_prog_skeleton *prog_skel = (void *)s->progs + i * s->prog_skel_sz;
14142 		struct bpf_link **link = prog_skel->link;
14143 
14144 		bpf_link__destroy(*link);
14145 		*link = NULL;
14146 	}
14147 
14148 	if (s->map_skel_sz < sizeof(struct bpf_map_skeleton))
14149 		return;
14150 
14151 	for (i = 0; i < s->map_cnt; i++) {
14152 		struct bpf_map_skeleton *map_skel = (void *)s->maps + i * s->map_skel_sz;
14153 		struct bpf_link **link = map_skel->link;
14154 
14155 		if (link) {
14156 			bpf_link__destroy(*link);
14157 			*link = NULL;
14158 		}
14159 	}
14160 }
14161 
14162 void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s)
14163 {
14164 	if (!s)
14165 		return;
14166 
14167 	bpf_object__detach_skeleton(s);
14168 	if (s->obj)
14169 		bpf_object__close(*s->obj);
14170 	free(s->maps);
14171 	free(s->progs);
14172 	free(s);
14173 }
14174