xref: /linux/tools/lib/bpf/libbpf.c (revision 5d87e96a4971760c83e554c1d3ca99986d4f9b47)
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 		if (obj->arena_map_idx < 0) {
4586 			pr_warn("prog '%s': bad arena data relocation at insn %u, no arena maps defined\n",
4587 				prog->name, insn_idx);
4588 			return -LIBBPF_ERRNO__RELOC;
4589 		}
4590 		reloc_desc->type = RELO_DATA;
4591 		reloc_desc->insn_idx = insn_idx;
4592 		reloc_desc->map_idx = obj->arena_map_idx;
4593 		reloc_desc->sym_off = sym->st_value;
4594 
4595 		map = &obj->maps[obj->arena_map_idx];
4596 		pr_debug("prog '%s': found arena map %d (%s, sec %d, off %zu) for insn %u\n",
4597 			 prog->name, obj->arena_map_idx, map->name, map->sec_idx,
4598 			 map->sec_offset, insn_idx);
4599 		return 0;
4600 	}
4601 
4602 	/* generic map reference relocation */
4603 	if (type == LIBBPF_MAP_UNSPEC) {
4604 		if (!bpf_object__shndx_is_maps(obj, shdr_idx)) {
4605 			pr_warn("prog '%s': bad map relo against '%s' in section '%s'\n",
4606 				prog->name, sym_name, sym_sec_name);
4607 			return -LIBBPF_ERRNO__RELOC;
4608 		}
4609 		for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4610 			map = &obj->maps[map_idx];
4611 			if (map->libbpf_type != type ||
4612 			    map->sec_idx != sym->st_shndx ||
4613 			    map->sec_offset != sym->st_value)
4614 				continue;
4615 			pr_debug("prog '%s': found map %zd (%s, sec %d, off %zu) for insn #%u\n",
4616 				 prog->name, map_idx, map->name, map->sec_idx,
4617 				 map->sec_offset, insn_idx);
4618 			break;
4619 		}
4620 		if (map_idx >= nr_maps) {
4621 			pr_warn("prog '%s': map relo failed to find map for section '%s', off %zu\n",
4622 				prog->name, sym_sec_name, (size_t)sym->st_value);
4623 			return -LIBBPF_ERRNO__RELOC;
4624 		}
4625 		reloc_desc->type = RELO_LD64;
4626 		reloc_desc->insn_idx = insn_idx;
4627 		reloc_desc->map_idx = map_idx;
4628 		reloc_desc->sym_off = 0; /* sym->st_value determines map_idx */
4629 		return 0;
4630 	}
4631 
4632 	/* global data map relocation */
4633 	if (!bpf_object__shndx_is_data(obj, shdr_idx)) {
4634 		pr_warn("prog '%s': bad data relo against section '%s'\n",
4635 			prog->name, sym_sec_name);
4636 		return -LIBBPF_ERRNO__RELOC;
4637 	}
4638 	for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4639 		map = &obj->maps[map_idx];
4640 		if (map->libbpf_type != type || map->sec_idx != sym->st_shndx)
4641 			continue;
4642 		pr_debug("prog '%s': found data map %zd (%s, sec %d, off %zu) for insn %u\n",
4643 			 prog->name, map_idx, map->name, map->sec_idx,
4644 			 map->sec_offset, insn_idx);
4645 		break;
4646 	}
4647 	if (map_idx >= nr_maps) {
4648 		pr_warn("prog '%s': data relo failed to find map for section '%s'\n",
4649 			prog->name, sym_sec_name);
4650 		return -LIBBPF_ERRNO__RELOC;
4651 	}
4652 
4653 	reloc_desc->type = RELO_DATA;
4654 	reloc_desc->insn_idx = insn_idx;
4655 	reloc_desc->map_idx = map_idx;
4656 	reloc_desc->sym_off = sym->st_value;
4657 	return 0;
4658 }
4659 
4660 static bool prog_contains_insn(const struct bpf_program *prog, size_t insn_idx)
4661 {
4662 	return insn_idx >= prog->sec_insn_off &&
4663 	       insn_idx < prog->sec_insn_off + prog->sec_insn_cnt;
4664 }
4665 
4666 static struct bpf_program *find_prog_by_sec_insn(const struct bpf_object *obj,
4667 						 size_t sec_idx, size_t insn_idx)
4668 {
4669 	int l = 0, r = obj->nr_programs - 1, m;
4670 	struct bpf_program *prog;
4671 
4672 	if (!obj->nr_programs)
4673 		return NULL;
4674 
4675 	while (l < r) {
4676 		m = l + (r - l + 1) / 2;
4677 		prog = &obj->programs[m];
4678 
4679 		if (prog->sec_idx < sec_idx ||
4680 		    (prog->sec_idx == sec_idx && prog->sec_insn_off <= insn_idx))
4681 			l = m;
4682 		else
4683 			r = m - 1;
4684 	}
4685 	/* matching program could be at index l, but it still might be the
4686 	 * wrong one, so we need to double check conditions for the last time
4687 	 */
4688 	prog = &obj->programs[l];
4689 	if (prog->sec_idx == sec_idx && prog_contains_insn(prog, insn_idx))
4690 		return prog;
4691 	return NULL;
4692 }
4693 
4694 static int
4695 bpf_object__collect_prog_relos(struct bpf_object *obj, Elf64_Shdr *shdr, Elf_Data *data)
4696 {
4697 	const char *relo_sec_name, *sec_name;
4698 	size_t sec_idx = shdr->sh_info, sym_idx;
4699 	struct bpf_program *prog;
4700 	struct reloc_desc *relos;
4701 	int err, i, nrels;
4702 	const char *sym_name;
4703 	__u32 insn_idx;
4704 	Elf_Scn *scn;
4705 	Elf_Data *scn_data;
4706 	Elf64_Sym *sym;
4707 	Elf64_Rel *rel;
4708 
4709 	if (sec_idx >= obj->efile.sec_cnt)
4710 		return -EINVAL;
4711 
4712 	scn = elf_sec_by_idx(obj, sec_idx);
4713 	scn_data = elf_sec_data(obj, scn);
4714 	if (!scn_data)
4715 		return -LIBBPF_ERRNO__FORMAT;
4716 
4717 	relo_sec_name = elf_sec_str(obj, shdr->sh_name);
4718 	sec_name = elf_sec_name(obj, scn);
4719 	if (!relo_sec_name || !sec_name)
4720 		return -EINVAL;
4721 
4722 	pr_debug("sec '%s': collecting relocation for section(%zu) '%s'\n",
4723 		 relo_sec_name, sec_idx, sec_name);
4724 	nrels = shdr->sh_size / shdr->sh_entsize;
4725 
4726 	for (i = 0; i < nrels; i++) {
4727 		rel = elf_rel_by_idx(data, i);
4728 		if (!rel) {
4729 			pr_warn("sec '%s': failed to get relo #%d\n", relo_sec_name, i);
4730 			return -LIBBPF_ERRNO__FORMAT;
4731 		}
4732 
4733 		sym_idx = ELF64_R_SYM(rel->r_info);
4734 		sym = elf_sym_by_idx(obj, sym_idx);
4735 		if (!sym) {
4736 			pr_warn("sec '%s': symbol #%zu not found for relo #%d\n",
4737 				relo_sec_name, sym_idx, i);
4738 			return -LIBBPF_ERRNO__FORMAT;
4739 		}
4740 
4741 		if (sym->st_shndx >= obj->efile.sec_cnt) {
4742 			pr_warn("sec '%s': corrupted symbol #%zu pointing to invalid section #%zu for relo #%d\n",
4743 				relo_sec_name, sym_idx, (size_t)sym->st_shndx, i);
4744 			return -LIBBPF_ERRNO__FORMAT;
4745 		}
4746 
4747 		if (rel->r_offset % BPF_INSN_SZ || rel->r_offset >= scn_data->d_size) {
4748 			pr_warn("sec '%s': invalid offset 0x%zx for relo #%d\n",
4749 				relo_sec_name, (size_t)rel->r_offset, i);
4750 			return -LIBBPF_ERRNO__FORMAT;
4751 		}
4752 
4753 		insn_idx = rel->r_offset / BPF_INSN_SZ;
4754 		/* relocations against static functions are recorded as
4755 		 * relocations against the section that contains a function;
4756 		 * in such case, symbol will be STT_SECTION and sym.st_name
4757 		 * will point to empty string (0), so fetch section name
4758 		 * instead
4759 		 */
4760 		if (ELF64_ST_TYPE(sym->st_info) == STT_SECTION && sym->st_name == 0)
4761 			sym_name = elf_sec_name(obj, elf_sec_by_idx(obj, sym->st_shndx));
4762 		else
4763 			sym_name = elf_sym_str(obj, sym->st_name);
4764 		sym_name = sym_name ?: "<?";
4765 
4766 		pr_debug("sec '%s': relo #%d: insn #%u against '%s'\n",
4767 			 relo_sec_name, i, insn_idx, sym_name);
4768 
4769 		prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
4770 		if (!prog) {
4771 			pr_debug("sec '%s': relo #%d: couldn't find program in section '%s' for insn #%u, probably overridden weak function, skipping...\n",
4772 				relo_sec_name, i, sec_name, insn_idx);
4773 			continue;
4774 		}
4775 
4776 		relos = libbpf_reallocarray(prog->reloc_desc,
4777 					    prog->nr_reloc + 1, sizeof(*relos));
4778 		if (!relos)
4779 			return -ENOMEM;
4780 		prog->reloc_desc = relos;
4781 
4782 		/* adjust insn_idx to local BPF program frame of reference */
4783 		insn_idx -= prog->sec_insn_off;
4784 		err = bpf_program__record_reloc(prog, &relos[prog->nr_reloc],
4785 						insn_idx, sym_name, sym, rel);
4786 		if (err)
4787 			return err;
4788 
4789 		prog->nr_reloc++;
4790 	}
4791 	return 0;
4792 }
4793 
4794 static int map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map)
4795 {
4796 	int id;
4797 
4798 	if (!obj->btf)
4799 		return -ENOENT;
4800 
4801 	/* if it's BTF-defined map, we don't need to search for type IDs.
4802 	 * For struct_ops map, it does not need btf_key_type_id and
4803 	 * btf_value_type_id.
4804 	 */
4805 	if (map->sec_idx == obj->efile.btf_maps_shndx || bpf_map__is_struct_ops(map))
4806 		return 0;
4807 
4808 	/*
4809 	 * LLVM annotates global data differently in BTF, that is,
4810 	 * only as '.data', '.bss' or '.rodata'.
4811 	 */
4812 	if (!bpf_map__is_internal(map))
4813 		return -ENOENT;
4814 
4815 	id = btf__find_by_name(obj->btf, map->real_name);
4816 	if (id < 0)
4817 		return id;
4818 
4819 	map->btf_key_type_id = 0;
4820 	map->btf_value_type_id = id;
4821 	return 0;
4822 }
4823 
4824 static int bpf_get_map_info_from_fdinfo(int fd, struct bpf_map_info *info)
4825 {
4826 	char file[PATH_MAX], buff[4096];
4827 	FILE *fp;
4828 	__u32 val;
4829 	int err;
4830 
4831 	snprintf(file, sizeof(file), "/proc/%d/fdinfo/%d", getpid(), fd);
4832 	memset(info, 0, sizeof(*info));
4833 
4834 	fp = fopen(file, "re");
4835 	if (!fp) {
4836 		err = -errno;
4837 		pr_warn("failed to open %s: %s. No procfs support?\n", file,
4838 			errstr(err));
4839 		return err;
4840 	}
4841 
4842 	while (fgets(buff, sizeof(buff), fp)) {
4843 		if (sscanf(buff, "map_type:\t%u", &val) == 1)
4844 			info->type = val;
4845 		else if (sscanf(buff, "key_size:\t%u", &val) == 1)
4846 			info->key_size = val;
4847 		else if (sscanf(buff, "value_size:\t%u", &val) == 1)
4848 			info->value_size = val;
4849 		else if (sscanf(buff, "max_entries:\t%u", &val) == 1)
4850 			info->max_entries = val;
4851 		else if (sscanf(buff, "map_flags:\t%i", &val) == 1)
4852 			info->map_flags = val;
4853 	}
4854 
4855 	fclose(fp);
4856 
4857 	return 0;
4858 }
4859 
4860 static bool map_is_created(const struct bpf_map *map)
4861 {
4862 	return map->obj->state >= OBJ_PREPARED || map->reused;
4863 }
4864 
4865 bool bpf_map__autocreate(const struct bpf_map *map)
4866 {
4867 	return map->autocreate;
4868 }
4869 
4870 int bpf_map__set_autocreate(struct bpf_map *map, bool autocreate)
4871 {
4872 	if (map_is_created(map))
4873 		return libbpf_err(-EBUSY);
4874 
4875 	map->autocreate = autocreate;
4876 	return 0;
4877 }
4878 
4879 int bpf_map__set_autoattach(struct bpf_map *map, bool autoattach)
4880 {
4881 	if (!bpf_map__is_struct_ops(map))
4882 		return libbpf_err(-EINVAL);
4883 
4884 	map->autoattach = autoattach;
4885 	return 0;
4886 }
4887 
4888 bool bpf_map__autoattach(const struct bpf_map *map)
4889 {
4890 	return map->autoattach;
4891 }
4892 
4893 int bpf_map__reuse_fd(struct bpf_map *map, int fd)
4894 {
4895 	struct bpf_map_info info;
4896 	__u32 len = sizeof(info), name_len;
4897 	int new_fd, err;
4898 	char *new_name;
4899 
4900 	memset(&info, 0, len);
4901 	err = bpf_map_get_info_by_fd(fd, &info, &len);
4902 	if (err && errno == EINVAL)
4903 		err = bpf_get_map_info_from_fdinfo(fd, &info);
4904 	if (err)
4905 		return libbpf_err(err);
4906 
4907 	name_len = strlen(info.name);
4908 	if (name_len == BPF_OBJ_NAME_LEN - 1 && strncmp(map->name, info.name, name_len) == 0)
4909 		new_name = strdup(map->name);
4910 	else
4911 		new_name = strdup(info.name);
4912 
4913 	if (!new_name)
4914 		return libbpf_err(-errno);
4915 
4916 	/*
4917 	 * Like dup(), but make sure new FD is >= 3 and has O_CLOEXEC set.
4918 	 * This is similar to what we do in ensure_good_fd(), but without
4919 	 * closing original FD.
4920 	 */
4921 	new_fd = fcntl(fd, F_DUPFD_CLOEXEC, 3);
4922 	if (new_fd < 0) {
4923 		err = -errno;
4924 		goto err_free_new_name;
4925 	}
4926 
4927 	err = reuse_fd(map->fd, new_fd);
4928 	if (err)
4929 		goto err_free_new_name;
4930 
4931 	free(map->name);
4932 
4933 	map->name = new_name;
4934 	map->def.type = info.type;
4935 	map->def.key_size = info.key_size;
4936 	map->def.value_size = info.value_size;
4937 	map->def.max_entries = info.max_entries;
4938 	map->def.map_flags = info.map_flags;
4939 	map->btf_key_type_id = info.btf_key_type_id;
4940 	map->btf_value_type_id = info.btf_value_type_id;
4941 	map->reused = true;
4942 	map->map_extra = info.map_extra;
4943 
4944 	return 0;
4945 
4946 err_free_new_name:
4947 	free(new_name);
4948 	return libbpf_err(err);
4949 }
4950 
4951 __u32 bpf_map__max_entries(const struct bpf_map *map)
4952 {
4953 	return map->def.max_entries;
4954 }
4955 
4956 struct bpf_map *bpf_map__inner_map(struct bpf_map *map)
4957 {
4958 	if (!bpf_map_type__is_map_in_map(map->def.type))
4959 		return errno = EINVAL, NULL;
4960 
4961 	return map->inner_map;
4962 }
4963 
4964 int bpf_map__set_max_entries(struct bpf_map *map, __u32 max_entries)
4965 {
4966 	if (map_is_created(map))
4967 		return libbpf_err(-EBUSY);
4968 
4969 	map->def.max_entries = max_entries;
4970 
4971 	/* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
4972 	if (map_is_ringbuf(map))
4973 		map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
4974 
4975 	return 0;
4976 }
4977 
4978 static int bpf_object_prepare_token(struct bpf_object *obj)
4979 {
4980 	const char *bpffs_path;
4981 	int bpffs_fd = -1, token_fd, err;
4982 	bool mandatory;
4983 	enum libbpf_print_level level;
4984 
4985 	/* token is explicitly prevented */
4986 	if (obj->token_path && obj->token_path[0] == '\0') {
4987 		pr_debug("object '%s': token is prevented, skipping...\n", obj->name);
4988 		return 0;
4989 	}
4990 
4991 	mandatory = obj->token_path != NULL;
4992 	level = mandatory ? LIBBPF_WARN : LIBBPF_DEBUG;
4993 
4994 	bpffs_path = obj->token_path ?: BPF_FS_DEFAULT_PATH;
4995 	bpffs_fd = open(bpffs_path, O_DIRECTORY, O_RDWR);
4996 	if (bpffs_fd < 0) {
4997 		err = -errno;
4998 		__pr(level, "object '%s': failed (%s) to open BPF FS mount at '%s'%s\n",
4999 		     obj->name, errstr(err), bpffs_path,
5000 		     mandatory ? "" : ", skipping optional step...");
5001 		return mandatory ? err : 0;
5002 	}
5003 
5004 	token_fd = bpf_token_create(bpffs_fd, 0);
5005 	close(bpffs_fd);
5006 	if (token_fd < 0) {
5007 		if (!mandatory && token_fd == -ENOENT) {
5008 			pr_debug("object '%s': BPF FS at '%s' doesn't have BPF token delegation set up, skipping...\n",
5009 				 obj->name, bpffs_path);
5010 			return 0;
5011 		}
5012 		__pr(level, "object '%s': failed (%d) to create BPF token from '%s'%s\n",
5013 		     obj->name, token_fd, bpffs_path,
5014 		     mandatory ? "" : ", skipping optional step...");
5015 		return mandatory ? token_fd : 0;
5016 	}
5017 
5018 	obj->feat_cache = calloc(1, sizeof(*obj->feat_cache));
5019 	if (!obj->feat_cache) {
5020 		close(token_fd);
5021 		return -ENOMEM;
5022 	}
5023 
5024 	obj->token_fd = token_fd;
5025 	obj->feat_cache->token_fd = token_fd;
5026 
5027 	return 0;
5028 }
5029 
5030 static int
5031 bpf_object__probe_loading(struct bpf_object *obj)
5032 {
5033 	struct bpf_insn insns[] = {
5034 		BPF_MOV64_IMM(BPF_REG_0, 0),
5035 		BPF_EXIT_INSN(),
5036 	};
5037 	int ret, insn_cnt = ARRAY_SIZE(insns);
5038 	LIBBPF_OPTS(bpf_prog_load_opts, opts,
5039 		.token_fd = obj->token_fd,
5040 		.prog_flags = obj->token_fd ? BPF_F_TOKEN_FD : 0,
5041 	);
5042 
5043 	if (obj->gen_loader)
5044 		return 0;
5045 
5046 	ret = bump_rlimit_memlock();
5047 	if (ret)
5048 		pr_warn("Failed to bump RLIMIT_MEMLOCK (err = %s), you might need to do it explicitly!\n",
5049 			errstr(ret));
5050 
5051 	/* make sure basic loading works */
5052 	ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, &opts);
5053 	if (ret < 0)
5054 		ret = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, &opts);
5055 	if (ret < 0) {
5056 		ret = errno;
5057 		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",
5058 			__func__, errstr(ret));
5059 		return -ret;
5060 	}
5061 	close(ret);
5062 
5063 	return 0;
5064 }
5065 
5066 bool kernel_supports(const struct bpf_object *obj, enum kern_feature_id feat_id)
5067 {
5068 	if (obj->gen_loader)
5069 		/* To generate loader program assume the latest kernel
5070 		 * to avoid doing extra prog_load, map_create syscalls.
5071 		 */
5072 		return true;
5073 
5074 	if (obj->token_fd)
5075 		return feat_supported(obj->feat_cache, feat_id);
5076 
5077 	return feat_supported(NULL, feat_id);
5078 }
5079 
5080 static bool map_is_reuse_compat(const struct bpf_map *map, int map_fd)
5081 {
5082 	struct bpf_map_info map_info;
5083 	__u32 map_info_len = sizeof(map_info);
5084 	int err;
5085 
5086 	memset(&map_info, 0, map_info_len);
5087 	err = bpf_map_get_info_by_fd(map_fd, &map_info, &map_info_len);
5088 	if (err && errno == EINVAL)
5089 		err = bpf_get_map_info_from_fdinfo(map_fd, &map_info);
5090 	if (err) {
5091 		pr_warn("failed to get map info for map FD %d: %s\n", map_fd,
5092 			errstr(err));
5093 		return false;
5094 	}
5095 
5096 	/*
5097 	 * bpf_get_map_info_by_fd() for DEVMAP will always return flags with
5098 	 * BPF_F_RDONLY_PROG set, but it generally is not set at map creation time.
5099 	 * Thus, ignore the BPF_F_RDONLY_PROG flag in the flags returned from
5100 	 * bpf_get_map_info_by_fd() when checking for compatibility with an
5101 	 * existing DEVMAP.
5102 	 */
5103 	if (map->def.type == BPF_MAP_TYPE_DEVMAP || map->def.type == BPF_MAP_TYPE_DEVMAP_HASH)
5104 		map_info.map_flags &= ~BPF_F_RDONLY_PROG;
5105 
5106 	return (map_info.type == map->def.type &&
5107 		map_info.key_size == map->def.key_size &&
5108 		map_info.value_size == map->def.value_size &&
5109 		map_info.max_entries == map->def.max_entries &&
5110 		map_info.map_flags == map->def.map_flags &&
5111 		map_info.map_extra == map->map_extra);
5112 }
5113 
5114 static int
5115 bpf_object__reuse_map(struct bpf_map *map)
5116 {
5117 	int err, pin_fd;
5118 
5119 	pin_fd = bpf_obj_get(map->pin_path);
5120 	if (pin_fd < 0) {
5121 		err = -errno;
5122 		if (err == -ENOENT) {
5123 			pr_debug("found no pinned map to reuse at '%s'\n",
5124 				 map->pin_path);
5125 			return 0;
5126 		}
5127 
5128 		pr_warn("couldn't retrieve pinned map '%s': %s\n",
5129 			map->pin_path, errstr(err));
5130 		return err;
5131 	}
5132 
5133 	if (!map_is_reuse_compat(map, pin_fd)) {
5134 		pr_warn("couldn't reuse pinned map at '%s': parameter mismatch\n",
5135 			map->pin_path);
5136 		close(pin_fd);
5137 		return -EINVAL;
5138 	}
5139 
5140 	err = bpf_map__reuse_fd(map, pin_fd);
5141 	close(pin_fd);
5142 	if (err)
5143 		return err;
5144 
5145 	map->pinned = true;
5146 	pr_debug("reused pinned map at '%s'\n", map->pin_path);
5147 
5148 	return 0;
5149 }
5150 
5151 static int
5152 bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
5153 {
5154 	enum libbpf_map_type map_type = map->libbpf_type;
5155 	int err, zero = 0;
5156 	size_t mmap_sz;
5157 
5158 	if (obj->gen_loader) {
5159 		bpf_gen__map_update_elem(obj->gen_loader, map - obj->maps,
5160 					 map->mmaped, map->def.value_size);
5161 		if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG)
5162 			bpf_gen__map_freeze(obj->gen_loader, map - obj->maps);
5163 		return 0;
5164 	}
5165 
5166 	err = bpf_map_update_elem(map->fd, &zero, map->mmaped, 0);
5167 	if (err) {
5168 		err = -errno;
5169 		pr_warn("map '%s': failed to set initial contents: %s\n",
5170 			bpf_map__name(map), errstr(err));
5171 		return err;
5172 	}
5173 
5174 	/* Freeze .rodata and .kconfig map as read-only from syscall side. */
5175 	if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG) {
5176 		err = bpf_map_freeze(map->fd);
5177 		if (err) {
5178 			err = -errno;
5179 			pr_warn("map '%s': failed to freeze as read-only: %s\n",
5180 				bpf_map__name(map), errstr(err));
5181 			return err;
5182 		}
5183 	}
5184 
5185 	/* Remap anonymous mmap()-ed "map initialization image" as
5186 	 * a BPF map-backed mmap()-ed memory, but preserving the same
5187 	 * memory address. This will cause kernel to change process'
5188 	 * page table to point to a different piece of kernel memory,
5189 	 * but from userspace point of view memory address (and its
5190 	 * contents, being identical at this point) will stay the
5191 	 * same. This mapping will be released by bpf_object__close()
5192 	 * as per normal clean up procedure.
5193 	 */
5194 	mmap_sz = bpf_map_mmap_sz(map);
5195 	if (map->def.map_flags & BPF_F_MMAPABLE) {
5196 		void *mmaped;
5197 		int prot;
5198 
5199 		if (map->def.map_flags & BPF_F_RDONLY_PROG)
5200 			prot = PROT_READ;
5201 		else
5202 			prot = PROT_READ | PROT_WRITE;
5203 		mmaped = mmap(map->mmaped, mmap_sz, prot, MAP_SHARED | MAP_FIXED, map->fd, 0);
5204 		if (mmaped == MAP_FAILED) {
5205 			err = -errno;
5206 			pr_warn("map '%s': failed to re-mmap() contents: %s\n",
5207 				bpf_map__name(map), errstr(err));
5208 			return err;
5209 		}
5210 		map->mmaped = mmaped;
5211 	} else if (map->mmaped) {
5212 		munmap(map->mmaped, mmap_sz);
5213 		map->mmaped = NULL;
5214 	}
5215 
5216 	return 0;
5217 }
5218 
5219 static void bpf_map__destroy(struct bpf_map *map);
5220 
5221 static int bpf_object__create_map(struct bpf_object *obj, struct bpf_map *map, bool is_inner)
5222 {
5223 	LIBBPF_OPTS(bpf_map_create_opts, create_attr);
5224 	struct bpf_map_def *def = &map->def;
5225 	const char *map_name = NULL;
5226 	int err = 0, map_fd;
5227 
5228 	if (kernel_supports(obj, FEAT_PROG_NAME))
5229 		map_name = map->name;
5230 	create_attr.map_ifindex = map->map_ifindex;
5231 	create_attr.map_flags = def->map_flags;
5232 	create_attr.numa_node = map->numa_node;
5233 	create_attr.map_extra = map->map_extra;
5234 	create_attr.token_fd = obj->token_fd;
5235 	if (obj->token_fd)
5236 		create_attr.map_flags |= BPF_F_TOKEN_FD;
5237 
5238 	if (bpf_map__is_struct_ops(map)) {
5239 		create_attr.btf_vmlinux_value_type_id = map->btf_vmlinux_value_type_id;
5240 		if (map->mod_btf_fd >= 0) {
5241 			create_attr.value_type_btf_obj_fd = map->mod_btf_fd;
5242 			create_attr.map_flags |= BPF_F_VTYPE_BTF_OBJ_FD;
5243 		}
5244 	}
5245 
5246 	if (obj->btf && btf__fd(obj->btf) >= 0) {
5247 		create_attr.btf_fd = btf__fd(obj->btf);
5248 		create_attr.btf_key_type_id = map->btf_key_type_id;
5249 		create_attr.btf_value_type_id = map->btf_value_type_id;
5250 	}
5251 
5252 	if (bpf_map_type__is_map_in_map(def->type)) {
5253 		if (map->inner_map) {
5254 			err = map_set_def_max_entries(map->inner_map);
5255 			if (err)
5256 				return err;
5257 			err = bpf_object__create_map(obj, map->inner_map, true);
5258 			if (err) {
5259 				pr_warn("map '%s': failed to create inner map: %s\n",
5260 					map->name, errstr(err));
5261 				return err;
5262 			}
5263 			map->inner_map_fd = map->inner_map->fd;
5264 		}
5265 		if (map->inner_map_fd >= 0)
5266 			create_attr.inner_map_fd = map->inner_map_fd;
5267 	}
5268 
5269 	switch (def->type) {
5270 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
5271 	case BPF_MAP_TYPE_CGROUP_ARRAY:
5272 	case BPF_MAP_TYPE_STACK_TRACE:
5273 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
5274 	case BPF_MAP_TYPE_HASH_OF_MAPS:
5275 	case BPF_MAP_TYPE_DEVMAP:
5276 	case BPF_MAP_TYPE_DEVMAP_HASH:
5277 	case BPF_MAP_TYPE_CPUMAP:
5278 	case BPF_MAP_TYPE_XSKMAP:
5279 	case BPF_MAP_TYPE_SOCKMAP:
5280 	case BPF_MAP_TYPE_SOCKHASH:
5281 	case BPF_MAP_TYPE_QUEUE:
5282 	case BPF_MAP_TYPE_STACK:
5283 	case BPF_MAP_TYPE_ARENA:
5284 		create_attr.btf_fd = 0;
5285 		create_attr.btf_key_type_id = 0;
5286 		create_attr.btf_value_type_id = 0;
5287 		map->btf_key_type_id = 0;
5288 		map->btf_value_type_id = 0;
5289 		break;
5290 	case BPF_MAP_TYPE_STRUCT_OPS:
5291 		create_attr.btf_value_type_id = 0;
5292 		break;
5293 	default:
5294 		break;
5295 	}
5296 
5297 	if (obj->gen_loader) {
5298 		bpf_gen__map_create(obj->gen_loader, def->type, map_name,
5299 				    def->key_size, def->value_size, def->max_entries,
5300 				    &create_attr, is_inner ? -1 : map - obj->maps);
5301 		/* We keep pretenting we have valid FD to pass various fd >= 0
5302 		 * checks by just keeping original placeholder FDs in place.
5303 		 * See bpf_object__add_map() comment.
5304 		 * This placeholder fd will not be used with any syscall and
5305 		 * will be reset to -1 eventually.
5306 		 */
5307 		map_fd = map->fd;
5308 	} else {
5309 		map_fd = bpf_map_create(def->type, map_name,
5310 					def->key_size, def->value_size,
5311 					def->max_entries, &create_attr);
5312 	}
5313 	if (map_fd < 0 && (create_attr.btf_key_type_id || create_attr.btf_value_type_id)) {
5314 		err = -errno;
5315 		pr_warn("Error in bpf_create_map_xattr(%s): %s. Retrying without BTF.\n",
5316 			map->name, errstr(err));
5317 		create_attr.btf_fd = 0;
5318 		create_attr.btf_key_type_id = 0;
5319 		create_attr.btf_value_type_id = 0;
5320 		map->btf_key_type_id = 0;
5321 		map->btf_value_type_id = 0;
5322 		map_fd = bpf_map_create(def->type, map_name,
5323 					def->key_size, def->value_size,
5324 					def->max_entries, &create_attr);
5325 	}
5326 
5327 	if (bpf_map_type__is_map_in_map(def->type) && map->inner_map) {
5328 		if (obj->gen_loader)
5329 			map->inner_map->fd = -1;
5330 		bpf_map__destroy(map->inner_map);
5331 		zfree(&map->inner_map);
5332 	}
5333 
5334 	if (map_fd < 0)
5335 		return map_fd;
5336 
5337 	/* obj->gen_loader case, prevent reuse_fd() from closing map_fd */
5338 	if (map->fd == map_fd)
5339 		return 0;
5340 
5341 	/* Keep placeholder FD value but now point it to the BPF map object.
5342 	 * This way everything that relied on this map's FD (e.g., relocated
5343 	 * ldimm64 instructions) will stay valid and won't need adjustments.
5344 	 * map->fd stays valid but now point to what map_fd points to.
5345 	 */
5346 	return reuse_fd(map->fd, map_fd);
5347 }
5348 
5349 static int init_map_in_map_slots(struct bpf_object *obj, struct bpf_map *map)
5350 {
5351 	const struct bpf_map *targ_map;
5352 	unsigned int i;
5353 	int fd, err = 0;
5354 
5355 	for (i = 0; i < map->init_slots_sz; i++) {
5356 		if (!map->init_slots[i])
5357 			continue;
5358 
5359 		targ_map = map->init_slots[i];
5360 		fd = targ_map->fd;
5361 
5362 		if (obj->gen_loader) {
5363 			bpf_gen__populate_outer_map(obj->gen_loader,
5364 						    map - obj->maps, i,
5365 						    targ_map - obj->maps);
5366 		} else {
5367 			err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5368 		}
5369 		if (err) {
5370 			err = -errno;
5371 			pr_warn("map '%s': failed to initialize slot [%d] to map '%s' fd=%d: %s\n",
5372 				map->name, i, targ_map->name, fd, errstr(err));
5373 			return err;
5374 		}
5375 		pr_debug("map '%s': slot [%d] set to map '%s' fd=%d\n",
5376 			 map->name, i, targ_map->name, fd);
5377 	}
5378 
5379 	zfree(&map->init_slots);
5380 	map->init_slots_sz = 0;
5381 
5382 	return 0;
5383 }
5384 
5385 static int init_prog_array_slots(struct bpf_object *obj, struct bpf_map *map)
5386 {
5387 	const struct bpf_program *targ_prog;
5388 	unsigned int i;
5389 	int fd, err;
5390 
5391 	if (obj->gen_loader)
5392 		return -ENOTSUP;
5393 
5394 	for (i = 0; i < map->init_slots_sz; i++) {
5395 		if (!map->init_slots[i])
5396 			continue;
5397 
5398 		targ_prog = map->init_slots[i];
5399 		fd = bpf_program__fd(targ_prog);
5400 
5401 		err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5402 		if (err) {
5403 			err = -errno;
5404 			pr_warn("map '%s': failed to initialize slot [%d] to prog '%s' fd=%d: %s\n",
5405 				map->name, i, targ_prog->name, fd, errstr(err));
5406 			return err;
5407 		}
5408 		pr_debug("map '%s': slot [%d] set to prog '%s' fd=%d\n",
5409 			 map->name, i, targ_prog->name, fd);
5410 	}
5411 
5412 	zfree(&map->init_slots);
5413 	map->init_slots_sz = 0;
5414 
5415 	return 0;
5416 }
5417 
5418 static int bpf_object_init_prog_arrays(struct bpf_object *obj)
5419 {
5420 	struct bpf_map *map;
5421 	int i, err;
5422 
5423 	for (i = 0; i < obj->nr_maps; i++) {
5424 		map = &obj->maps[i];
5425 
5426 		if (!map->init_slots_sz || map->def.type != BPF_MAP_TYPE_PROG_ARRAY)
5427 			continue;
5428 
5429 		err = init_prog_array_slots(obj, map);
5430 		if (err < 0)
5431 			return err;
5432 	}
5433 	return 0;
5434 }
5435 
5436 static int map_set_def_max_entries(struct bpf_map *map)
5437 {
5438 	if (map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY && !map->def.max_entries) {
5439 		int nr_cpus;
5440 
5441 		nr_cpus = libbpf_num_possible_cpus();
5442 		if (nr_cpus < 0) {
5443 			pr_warn("map '%s': failed to determine number of system CPUs: %d\n",
5444 				map->name, nr_cpus);
5445 			return nr_cpus;
5446 		}
5447 		pr_debug("map '%s': setting size to %d\n", map->name, nr_cpus);
5448 		map->def.max_entries = nr_cpus;
5449 	}
5450 
5451 	return 0;
5452 }
5453 
5454 static int
5455 bpf_object__create_maps(struct bpf_object *obj)
5456 {
5457 	struct bpf_map *map;
5458 	unsigned int i, j;
5459 	int err;
5460 	bool retried;
5461 
5462 	for (i = 0; i < obj->nr_maps; i++) {
5463 		map = &obj->maps[i];
5464 
5465 		/* To support old kernels, we skip creating global data maps
5466 		 * (.rodata, .data, .kconfig, etc); later on, during program
5467 		 * loading, if we detect that at least one of the to-be-loaded
5468 		 * programs is referencing any global data map, we'll error
5469 		 * out with program name and relocation index logged.
5470 		 * This approach allows to accommodate Clang emitting
5471 		 * unnecessary .rodata.str1.1 sections for string literals,
5472 		 * but also it allows to have CO-RE applications that use
5473 		 * global variables in some of BPF programs, but not others.
5474 		 * If those global variable-using programs are not loaded at
5475 		 * runtime due to bpf_program__set_autoload(prog, false),
5476 		 * bpf_object loading will succeed just fine even on old
5477 		 * kernels.
5478 		 */
5479 		if (bpf_map__is_internal(map) && !kernel_supports(obj, FEAT_GLOBAL_DATA))
5480 			map->autocreate = false;
5481 
5482 		if (!map->autocreate) {
5483 			pr_debug("map '%s': skipped auto-creating...\n", map->name);
5484 			continue;
5485 		}
5486 
5487 		err = map_set_def_max_entries(map);
5488 		if (err)
5489 			goto err_out;
5490 
5491 		retried = false;
5492 retry:
5493 		if (map->pin_path) {
5494 			err = bpf_object__reuse_map(map);
5495 			if (err) {
5496 				pr_warn("map '%s': error reusing pinned map\n",
5497 					map->name);
5498 				goto err_out;
5499 			}
5500 			if (retried && map->fd < 0) {
5501 				pr_warn("map '%s': cannot find pinned map\n",
5502 					map->name);
5503 				err = -ENOENT;
5504 				goto err_out;
5505 			}
5506 		}
5507 
5508 		if (map->reused) {
5509 			pr_debug("map '%s': skipping creation (preset fd=%d)\n",
5510 				 map->name, map->fd);
5511 		} else {
5512 			err = bpf_object__create_map(obj, map, false);
5513 			if (err)
5514 				goto err_out;
5515 
5516 			pr_debug("map '%s': created successfully, fd=%d\n",
5517 				 map->name, map->fd);
5518 
5519 			if (bpf_map__is_internal(map)) {
5520 				err = bpf_object__populate_internal_map(obj, map);
5521 				if (err < 0)
5522 					goto err_out;
5523 			} else if (map->def.type == BPF_MAP_TYPE_ARENA) {
5524 				map->mmaped = mmap((void *)(long)map->map_extra,
5525 						   bpf_map_mmap_sz(map), PROT_READ | PROT_WRITE,
5526 						   map->map_extra ? MAP_SHARED | MAP_FIXED : MAP_SHARED,
5527 						   map->fd, 0);
5528 				if (map->mmaped == MAP_FAILED) {
5529 					err = -errno;
5530 					map->mmaped = NULL;
5531 					pr_warn("map '%s': failed to mmap arena: %s\n",
5532 						map->name, errstr(err));
5533 					return err;
5534 				}
5535 				if (obj->arena_data) {
5536 					memcpy(map->mmaped, obj->arena_data, obj->arena_data_sz);
5537 					zfree(&obj->arena_data);
5538 				}
5539 			}
5540 			if (map->init_slots_sz && map->def.type != BPF_MAP_TYPE_PROG_ARRAY) {
5541 				err = init_map_in_map_slots(obj, map);
5542 				if (err < 0)
5543 					goto err_out;
5544 			}
5545 		}
5546 
5547 		if (map->pin_path && !map->pinned) {
5548 			err = bpf_map__pin(map, NULL);
5549 			if (err) {
5550 				if (!retried && err == -EEXIST) {
5551 					retried = true;
5552 					goto retry;
5553 				}
5554 				pr_warn("map '%s': failed to auto-pin at '%s': %s\n",
5555 					map->name, map->pin_path, errstr(err));
5556 				goto err_out;
5557 			}
5558 		}
5559 	}
5560 
5561 	return 0;
5562 
5563 err_out:
5564 	pr_warn("map '%s': failed to create: %s\n", map->name, errstr(err));
5565 	pr_perm_msg(err);
5566 	for (j = 0; j < i; j++)
5567 		zclose(obj->maps[j].fd);
5568 	return err;
5569 }
5570 
5571 static bool bpf_core_is_flavor_sep(const char *s)
5572 {
5573 	/* check X___Y name pattern, where X and Y are not underscores */
5574 	return s[0] != '_' &&				      /* X */
5575 	       s[1] == '_' && s[2] == '_' && s[3] == '_' &&   /* ___ */
5576 	       s[4] != '_';				      /* Y */
5577 }
5578 
5579 /* Given 'some_struct_name___with_flavor' return the length of a name prefix
5580  * before last triple underscore. Struct name part after last triple
5581  * underscore is ignored by BPF CO-RE relocation during relocation matching.
5582  */
5583 size_t bpf_core_essential_name_len(const char *name)
5584 {
5585 	size_t n = strlen(name);
5586 	int i;
5587 
5588 	for (i = n - 5; i >= 0; i--) {
5589 		if (bpf_core_is_flavor_sep(name + i))
5590 			return i + 1;
5591 	}
5592 	return n;
5593 }
5594 
5595 void bpf_core_free_cands(struct bpf_core_cand_list *cands)
5596 {
5597 	if (!cands)
5598 		return;
5599 
5600 	free(cands->cands);
5601 	free(cands);
5602 }
5603 
5604 int bpf_core_add_cands(struct bpf_core_cand *local_cand,
5605 		       size_t local_essent_len,
5606 		       const struct btf *targ_btf,
5607 		       const char *targ_btf_name,
5608 		       int targ_start_id,
5609 		       struct bpf_core_cand_list *cands)
5610 {
5611 	struct bpf_core_cand *new_cands, *cand;
5612 	const struct btf_type *t, *local_t;
5613 	const char *targ_name, *local_name;
5614 	size_t targ_essent_len;
5615 	int n, i;
5616 
5617 	local_t = btf__type_by_id(local_cand->btf, local_cand->id);
5618 	local_name = btf__str_by_offset(local_cand->btf, local_t->name_off);
5619 
5620 	n = btf__type_cnt(targ_btf);
5621 	for (i = targ_start_id; i < n; i++) {
5622 		t = btf__type_by_id(targ_btf, i);
5623 		if (!btf_kind_core_compat(t, local_t))
5624 			continue;
5625 
5626 		targ_name = btf__name_by_offset(targ_btf, t->name_off);
5627 		if (str_is_empty(targ_name))
5628 			continue;
5629 
5630 		targ_essent_len = bpf_core_essential_name_len(targ_name);
5631 		if (targ_essent_len != local_essent_len)
5632 			continue;
5633 
5634 		if (strncmp(local_name, targ_name, local_essent_len) != 0)
5635 			continue;
5636 
5637 		pr_debug("CO-RE relocating [%d] %s %s: found target candidate [%d] %s %s in [%s]\n",
5638 			 local_cand->id, btf_kind_str(local_t),
5639 			 local_name, i, btf_kind_str(t), targ_name,
5640 			 targ_btf_name);
5641 		new_cands = libbpf_reallocarray(cands->cands, cands->len + 1,
5642 					      sizeof(*cands->cands));
5643 		if (!new_cands)
5644 			return -ENOMEM;
5645 
5646 		cand = &new_cands[cands->len];
5647 		cand->btf = targ_btf;
5648 		cand->id = i;
5649 
5650 		cands->cands = new_cands;
5651 		cands->len++;
5652 	}
5653 	return 0;
5654 }
5655 
5656 static int load_module_btfs(struct bpf_object *obj)
5657 {
5658 	struct bpf_btf_info info;
5659 	struct module_btf *mod_btf;
5660 	struct btf *btf;
5661 	char name[64];
5662 	__u32 id = 0, len;
5663 	int err, fd;
5664 
5665 	if (obj->btf_modules_loaded)
5666 		return 0;
5667 
5668 	if (obj->gen_loader)
5669 		return 0;
5670 
5671 	/* don't do this again, even if we find no module BTFs */
5672 	obj->btf_modules_loaded = true;
5673 
5674 	/* kernel too old to support module BTFs */
5675 	if (!kernel_supports(obj, FEAT_MODULE_BTF))
5676 		return 0;
5677 
5678 	while (true) {
5679 		err = bpf_btf_get_next_id(id, &id);
5680 		if (err && errno == ENOENT)
5681 			return 0;
5682 		if (err && errno == EPERM) {
5683 			pr_debug("skipping module BTFs loading, missing privileges\n");
5684 			return 0;
5685 		}
5686 		if (err) {
5687 			err = -errno;
5688 			pr_warn("failed to iterate BTF objects: %s\n", errstr(err));
5689 			return err;
5690 		}
5691 
5692 		fd = bpf_btf_get_fd_by_id(id);
5693 		if (fd < 0) {
5694 			if (errno == ENOENT)
5695 				continue; /* expected race: BTF was unloaded */
5696 			err = -errno;
5697 			pr_warn("failed to get BTF object #%d FD: %s\n", id, errstr(err));
5698 			return err;
5699 		}
5700 
5701 		len = sizeof(info);
5702 		memset(&info, 0, sizeof(info));
5703 		info.name = ptr_to_u64(name);
5704 		info.name_len = sizeof(name);
5705 
5706 		err = bpf_btf_get_info_by_fd(fd, &info, &len);
5707 		if (err) {
5708 			err = -errno;
5709 			pr_warn("failed to get BTF object #%d info: %s\n", id, errstr(err));
5710 			goto err_out;
5711 		}
5712 
5713 		/* ignore non-module BTFs */
5714 		if (!info.kernel_btf || strcmp(name, "vmlinux") == 0) {
5715 			close(fd);
5716 			continue;
5717 		}
5718 
5719 		btf = btf_get_from_fd(fd, obj->btf_vmlinux);
5720 		err = libbpf_get_error(btf);
5721 		if (err) {
5722 			pr_warn("failed to load module [%s]'s BTF object #%d: %s\n",
5723 				name, id, errstr(err));
5724 			goto err_out;
5725 		}
5726 
5727 		err = libbpf_ensure_mem((void **)&obj->btf_modules, &obj->btf_module_cap,
5728 					sizeof(*obj->btf_modules), obj->btf_module_cnt + 1);
5729 		if (err)
5730 			goto err_out;
5731 
5732 		mod_btf = &obj->btf_modules[obj->btf_module_cnt++];
5733 
5734 		mod_btf->btf = btf;
5735 		mod_btf->id = id;
5736 		mod_btf->fd = fd;
5737 		mod_btf->name = strdup(name);
5738 		if (!mod_btf->name) {
5739 			err = -ENOMEM;
5740 			goto err_out;
5741 		}
5742 		continue;
5743 
5744 err_out:
5745 		close(fd);
5746 		return err;
5747 	}
5748 
5749 	return 0;
5750 }
5751 
5752 static struct bpf_core_cand_list *
5753 bpf_core_find_cands(struct bpf_object *obj, const struct btf *local_btf, __u32 local_type_id)
5754 {
5755 	struct bpf_core_cand local_cand = {};
5756 	struct bpf_core_cand_list *cands;
5757 	const struct btf *main_btf;
5758 	const struct btf_type *local_t;
5759 	const char *local_name;
5760 	size_t local_essent_len;
5761 	int err, i;
5762 
5763 	local_cand.btf = local_btf;
5764 	local_cand.id = local_type_id;
5765 	local_t = btf__type_by_id(local_btf, local_type_id);
5766 	if (!local_t)
5767 		return ERR_PTR(-EINVAL);
5768 
5769 	local_name = btf__name_by_offset(local_btf, local_t->name_off);
5770 	if (str_is_empty(local_name))
5771 		return ERR_PTR(-EINVAL);
5772 	local_essent_len = bpf_core_essential_name_len(local_name);
5773 
5774 	cands = calloc(1, sizeof(*cands));
5775 	if (!cands)
5776 		return ERR_PTR(-ENOMEM);
5777 
5778 	/* Attempt to find target candidates in vmlinux BTF first */
5779 	main_btf = obj->btf_vmlinux_override ?: obj->btf_vmlinux;
5780 	err = bpf_core_add_cands(&local_cand, local_essent_len, main_btf, "vmlinux", 1, cands);
5781 	if (err)
5782 		goto err_out;
5783 
5784 	/* if vmlinux BTF has any candidate, don't got for module BTFs */
5785 	if (cands->len)
5786 		return cands;
5787 
5788 	/* if vmlinux BTF was overridden, don't attempt to load module BTFs */
5789 	if (obj->btf_vmlinux_override)
5790 		return cands;
5791 
5792 	/* now look through module BTFs, trying to still find candidates */
5793 	err = load_module_btfs(obj);
5794 	if (err)
5795 		goto err_out;
5796 
5797 	for (i = 0; i < obj->btf_module_cnt; i++) {
5798 		err = bpf_core_add_cands(&local_cand, local_essent_len,
5799 					 obj->btf_modules[i].btf,
5800 					 obj->btf_modules[i].name,
5801 					 btf__type_cnt(obj->btf_vmlinux),
5802 					 cands);
5803 		if (err)
5804 			goto err_out;
5805 	}
5806 
5807 	return cands;
5808 err_out:
5809 	bpf_core_free_cands(cands);
5810 	return ERR_PTR(err);
5811 }
5812 
5813 /* Check local and target types for compatibility. This check is used for
5814  * type-based CO-RE relocations and follow slightly different rules than
5815  * field-based relocations. This function assumes that root types were already
5816  * checked for name match. Beyond that initial root-level name check, names
5817  * are completely ignored. Compatibility rules are as follows:
5818  *   - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs are considered compatible, but
5819  *     kind should match for local and target types (i.e., STRUCT is not
5820  *     compatible with UNION);
5821  *   - for ENUMs, the size is ignored;
5822  *   - for INT, size and signedness are ignored;
5823  *   - for ARRAY, dimensionality is ignored, element types are checked for
5824  *     compatibility recursively;
5825  *   - CONST/VOLATILE/RESTRICT modifiers are ignored;
5826  *   - TYPEDEFs/PTRs are compatible if types they pointing to are compatible;
5827  *   - FUNC_PROTOs are compatible if they have compatible signature: same
5828  *     number of input args and compatible return and argument types.
5829  * These rules are not set in stone and probably will be adjusted as we get
5830  * more experience with using BPF CO-RE relocations.
5831  */
5832 int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
5833 			      const struct btf *targ_btf, __u32 targ_id)
5834 {
5835 	return __bpf_core_types_are_compat(local_btf, local_id, targ_btf, targ_id, 32);
5836 }
5837 
5838 int bpf_core_types_match(const struct btf *local_btf, __u32 local_id,
5839 			 const struct btf *targ_btf, __u32 targ_id)
5840 {
5841 	return __bpf_core_types_match(local_btf, local_id, targ_btf, targ_id, false, 32);
5842 }
5843 
5844 static size_t bpf_core_hash_fn(const long key, void *ctx)
5845 {
5846 	return key;
5847 }
5848 
5849 static bool bpf_core_equal_fn(const long k1, const long k2, void *ctx)
5850 {
5851 	return k1 == k2;
5852 }
5853 
5854 static int record_relo_core(struct bpf_program *prog,
5855 			    const struct bpf_core_relo *core_relo, int insn_idx)
5856 {
5857 	struct reloc_desc *relos, *relo;
5858 
5859 	relos = libbpf_reallocarray(prog->reloc_desc,
5860 				    prog->nr_reloc + 1, sizeof(*relos));
5861 	if (!relos)
5862 		return -ENOMEM;
5863 	relo = &relos[prog->nr_reloc];
5864 	relo->type = RELO_CORE;
5865 	relo->insn_idx = insn_idx;
5866 	relo->core_relo = core_relo;
5867 	prog->reloc_desc = relos;
5868 	prog->nr_reloc++;
5869 	return 0;
5870 }
5871 
5872 static const struct bpf_core_relo *find_relo_core(struct bpf_program *prog, int insn_idx)
5873 {
5874 	struct reloc_desc *relo;
5875 	int i;
5876 
5877 	for (i = 0; i < prog->nr_reloc; i++) {
5878 		relo = &prog->reloc_desc[i];
5879 		if (relo->type != RELO_CORE || relo->insn_idx != insn_idx)
5880 			continue;
5881 
5882 		return relo->core_relo;
5883 	}
5884 
5885 	return NULL;
5886 }
5887 
5888 static int bpf_core_resolve_relo(struct bpf_program *prog,
5889 				 const struct bpf_core_relo *relo,
5890 				 int relo_idx,
5891 				 const struct btf *local_btf,
5892 				 struct hashmap *cand_cache,
5893 				 struct bpf_core_relo_res *targ_res)
5894 {
5895 	struct bpf_core_spec specs_scratch[3] = {};
5896 	struct bpf_core_cand_list *cands = NULL;
5897 	const char *prog_name = prog->name;
5898 	const struct btf_type *local_type;
5899 	const char *local_name;
5900 	__u32 local_id = relo->type_id;
5901 	int err;
5902 
5903 	local_type = btf__type_by_id(local_btf, local_id);
5904 	if (!local_type)
5905 		return -EINVAL;
5906 
5907 	local_name = btf__name_by_offset(local_btf, local_type->name_off);
5908 	if (!local_name)
5909 		return -EINVAL;
5910 
5911 	if (relo->kind != BPF_CORE_TYPE_ID_LOCAL &&
5912 	    !hashmap__find(cand_cache, local_id, &cands)) {
5913 		cands = bpf_core_find_cands(prog->obj, local_btf, local_id);
5914 		if (IS_ERR(cands)) {
5915 			pr_warn("prog '%s': relo #%d: target candidate search failed for [%d] %s %s: %ld\n",
5916 				prog_name, relo_idx, local_id, btf_kind_str(local_type),
5917 				local_name, PTR_ERR(cands));
5918 			return PTR_ERR(cands);
5919 		}
5920 		err = hashmap__set(cand_cache, local_id, cands, NULL, NULL);
5921 		if (err) {
5922 			bpf_core_free_cands(cands);
5923 			return err;
5924 		}
5925 	}
5926 
5927 	return bpf_core_calc_relo_insn(prog_name, relo, relo_idx, local_btf, cands, specs_scratch,
5928 				       targ_res);
5929 }
5930 
5931 static int
5932 bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
5933 {
5934 	const struct btf_ext_info_sec *sec;
5935 	struct bpf_core_relo_res targ_res;
5936 	const struct bpf_core_relo *rec;
5937 	const struct btf_ext_info *seg;
5938 	struct hashmap_entry *entry;
5939 	struct hashmap *cand_cache = NULL;
5940 	struct bpf_program *prog;
5941 	struct bpf_insn *insn;
5942 	const char *sec_name;
5943 	int i, err = 0, insn_idx, sec_idx, sec_num;
5944 
5945 	if (obj->btf_ext->core_relo_info.len == 0)
5946 		return 0;
5947 
5948 	if (targ_btf_path) {
5949 		obj->btf_vmlinux_override = btf__parse(targ_btf_path, NULL);
5950 		err = libbpf_get_error(obj->btf_vmlinux_override);
5951 		if (err) {
5952 			pr_warn("failed to parse target BTF: %s\n", errstr(err));
5953 			return err;
5954 		}
5955 	}
5956 
5957 	cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
5958 	if (IS_ERR(cand_cache)) {
5959 		err = PTR_ERR(cand_cache);
5960 		goto out;
5961 	}
5962 
5963 	seg = &obj->btf_ext->core_relo_info;
5964 	sec_num = 0;
5965 	for_each_btf_ext_sec(seg, sec) {
5966 		sec_idx = seg->sec_idxs[sec_num];
5967 		sec_num++;
5968 
5969 		sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
5970 		if (str_is_empty(sec_name)) {
5971 			err = -EINVAL;
5972 			goto out;
5973 		}
5974 
5975 		pr_debug("sec '%s': found %d CO-RE relocations\n", sec_name, sec->num_info);
5976 
5977 		for_each_btf_ext_rec(seg, sec, i, rec) {
5978 			if (rec->insn_off % BPF_INSN_SZ)
5979 				return -EINVAL;
5980 			insn_idx = rec->insn_off / BPF_INSN_SZ;
5981 			prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
5982 			if (!prog) {
5983 				/* When __weak subprog is "overridden" by another instance
5984 				 * of the subprog from a different object file, linker still
5985 				 * appends all the .BTF.ext info that used to belong to that
5986 				 * eliminated subprogram.
5987 				 * This is similar to what x86-64 linker does for relocations.
5988 				 * So just ignore such relocations just like we ignore
5989 				 * subprog instructions when discovering subprograms.
5990 				 */
5991 				pr_debug("sec '%s': skipping CO-RE relocation #%d for insn #%d belonging to eliminated weak subprogram\n",
5992 					 sec_name, i, insn_idx);
5993 				continue;
5994 			}
5995 			/* no need to apply CO-RE relocation if the program is
5996 			 * not going to be loaded
5997 			 */
5998 			if (!prog->autoload)
5999 				continue;
6000 
6001 			/* adjust insn_idx from section frame of reference to the local
6002 			 * program's frame of reference; (sub-)program code is not yet
6003 			 * relocated, so it's enough to just subtract in-section offset
6004 			 */
6005 			insn_idx = insn_idx - prog->sec_insn_off;
6006 			if (insn_idx >= prog->insns_cnt)
6007 				return -EINVAL;
6008 			insn = &prog->insns[insn_idx];
6009 
6010 			err = record_relo_core(prog, rec, insn_idx);
6011 			if (err) {
6012 				pr_warn("prog '%s': relo #%d: failed to record relocation: %s\n",
6013 					prog->name, i, errstr(err));
6014 				goto out;
6015 			}
6016 
6017 			if (prog->obj->gen_loader)
6018 				continue;
6019 
6020 			err = bpf_core_resolve_relo(prog, rec, i, obj->btf, cand_cache, &targ_res);
6021 			if (err) {
6022 				pr_warn("prog '%s': relo #%d: failed to relocate: %s\n",
6023 					prog->name, i, errstr(err));
6024 				goto out;
6025 			}
6026 
6027 			err = bpf_core_patch_insn(prog->name, insn, insn_idx, rec, i, &targ_res);
6028 			if (err) {
6029 				pr_warn("prog '%s': relo #%d: failed to patch insn #%u: %s\n",
6030 					prog->name, i, insn_idx, errstr(err));
6031 				goto out;
6032 			}
6033 		}
6034 	}
6035 
6036 out:
6037 	/* obj->btf_vmlinux and module BTFs are freed after object load */
6038 	btf__free(obj->btf_vmlinux_override);
6039 	obj->btf_vmlinux_override = NULL;
6040 
6041 	if (!IS_ERR_OR_NULL(cand_cache)) {
6042 		hashmap__for_each_entry(cand_cache, entry, i) {
6043 			bpf_core_free_cands(entry->pvalue);
6044 		}
6045 		hashmap__free(cand_cache);
6046 	}
6047 	return err;
6048 }
6049 
6050 /* base map load ldimm64 special constant, used also for log fixup logic */
6051 #define POISON_LDIMM64_MAP_BASE 2001000000
6052 #define POISON_LDIMM64_MAP_PFX "200100"
6053 
6054 static void poison_map_ldimm64(struct bpf_program *prog, int relo_idx,
6055 			       int insn_idx, struct bpf_insn *insn,
6056 			       int map_idx, const struct bpf_map *map)
6057 {
6058 	int i;
6059 
6060 	pr_debug("prog '%s': relo #%d: poisoning insn #%d that loads map #%d '%s'\n",
6061 		 prog->name, relo_idx, insn_idx, map_idx, map->name);
6062 
6063 	/* we turn single ldimm64 into two identical invalid calls */
6064 	for (i = 0; i < 2; i++) {
6065 		insn->code = BPF_JMP | BPF_CALL;
6066 		insn->dst_reg = 0;
6067 		insn->src_reg = 0;
6068 		insn->off = 0;
6069 		/* if this instruction is reachable (not a dead code),
6070 		 * verifier will complain with something like:
6071 		 * invalid func unknown#2001000123
6072 		 * where lower 123 is map index into obj->maps[] array
6073 		 */
6074 		insn->imm = POISON_LDIMM64_MAP_BASE + map_idx;
6075 
6076 		insn++;
6077 	}
6078 }
6079 
6080 /* unresolved kfunc call special constant, used also for log fixup logic */
6081 #define POISON_CALL_KFUNC_BASE 2002000000
6082 #define POISON_CALL_KFUNC_PFX "2002"
6083 
6084 static void poison_kfunc_call(struct bpf_program *prog, int relo_idx,
6085 			      int insn_idx, struct bpf_insn *insn,
6086 			      int ext_idx, const struct extern_desc *ext)
6087 {
6088 	pr_debug("prog '%s': relo #%d: poisoning insn #%d that calls kfunc '%s'\n",
6089 		 prog->name, relo_idx, insn_idx, ext->name);
6090 
6091 	/* we turn kfunc call into invalid helper call with identifiable constant */
6092 	insn->code = BPF_JMP | BPF_CALL;
6093 	insn->dst_reg = 0;
6094 	insn->src_reg = 0;
6095 	insn->off = 0;
6096 	/* if this instruction is reachable (not a dead code),
6097 	 * verifier will complain with something like:
6098 	 * invalid func unknown#2001000123
6099 	 * where lower 123 is extern index into obj->externs[] array
6100 	 */
6101 	insn->imm = POISON_CALL_KFUNC_BASE + ext_idx;
6102 }
6103 
6104 /* Relocate data references within program code:
6105  *  - map references;
6106  *  - global variable references;
6107  *  - extern references.
6108  */
6109 static int
6110 bpf_object__relocate_data(struct bpf_object *obj, struct bpf_program *prog)
6111 {
6112 	int i;
6113 
6114 	for (i = 0; i < prog->nr_reloc; i++) {
6115 		struct reloc_desc *relo = &prog->reloc_desc[i];
6116 		struct bpf_insn *insn = &prog->insns[relo->insn_idx];
6117 		const struct bpf_map *map;
6118 		struct extern_desc *ext;
6119 
6120 		switch (relo->type) {
6121 		case RELO_LD64:
6122 			map = &obj->maps[relo->map_idx];
6123 			if (obj->gen_loader) {
6124 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX;
6125 				insn[0].imm = relo->map_idx;
6126 			} else if (map->autocreate) {
6127 				insn[0].src_reg = BPF_PSEUDO_MAP_FD;
6128 				insn[0].imm = map->fd;
6129 			} else {
6130 				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
6131 						   relo->map_idx, map);
6132 			}
6133 			break;
6134 		case RELO_DATA:
6135 			map = &obj->maps[relo->map_idx];
6136 			insn[1].imm = insn[0].imm + relo->sym_off;
6137 			if (obj->gen_loader) {
6138 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
6139 				insn[0].imm = relo->map_idx;
6140 			} else if (map->autocreate) {
6141 				insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6142 				insn[0].imm = map->fd;
6143 			} else {
6144 				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
6145 						   relo->map_idx, map);
6146 			}
6147 			break;
6148 		case RELO_EXTERN_LD64:
6149 			ext = &obj->externs[relo->ext_idx];
6150 			if (ext->type == EXT_KCFG) {
6151 				if (obj->gen_loader) {
6152 					insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
6153 					insn[0].imm = obj->kconfig_map_idx;
6154 				} else {
6155 					insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6156 					insn[0].imm = obj->maps[obj->kconfig_map_idx].fd;
6157 				}
6158 				insn[1].imm = ext->kcfg.data_off;
6159 			} else /* EXT_KSYM */ {
6160 				if (ext->ksym.type_id && ext->is_set) { /* typed ksyms */
6161 					insn[0].src_reg = BPF_PSEUDO_BTF_ID;
6162 					insn[0].imm = ext->ksym.kernel_btf_id;
6163 					insn[1].imm = ext->ksym.kernel_btf_obj_fd;
6164 				} else { /* typeless ksyms or unresolved typed ksyms */
6165 					insn[0].imm = (__u32)ext->ksym.addr;
6166 					insn[1].imm = ext->ksym.addr >> 32;
6167 				}
6168 			}
6169 			break;
6170 		case RELO_EXTERN_CALL:
6171 			ext = &obj->externs[relo->ext_idx];
6172 			insn[0].src_reg = BPF_PSEUDO_KFUNC_CALL;
6173 			if (ext->is_set) {
6174 				insn[0].imm = ext->ksym.kernel_btf_id;
6175 				insn[0].off = ext->ksym.btf_fd_idx;
6176 			} else { /* unresolved weak kfunc call */
6177 				poison_kfunc_call(prog, i, relo->insn_idx, insn,
6178 						  relo->ext_idx, ext);
6179 			}
6180 			break;
6181 		case RELO_SUBPROG_ADDR:
6182 			if (insn[0].src_reg != BPF_PSEUDO_FUNC) {
6183 				pr_warn("prog '%s': relo #%d: bad insn\n",
6184 					prog->name, i);
6185 				return -EINVAL;
6186 			}
6187 			/* handled already */
6188 			break;
6189 		case RELO_CALL:
6190 			/* handled already */
6191 			break;
6192 		case RELO_CORE:
6193 			/* will be handled by bpf_program_record_relos() */
6194 			break;
6195 		default:
6196 			pr_warn("prog '%s': relo #%d: bad relo type %d\n",
6197 				prog->name, i, relo->type);
6198 			return -EINVAL;
6199 		}
6200 	}
6201 
6202 	return 0;
6203 }
6204 
6205 static int adjust_prog_btf_ext_info(const struct bpf_object *obj,
6206 				    const struct bpf_program *prog,
6207 				    const struct btf_ext_info *ext_info,
6208 				    void **prog_info, __u32 *prog_rec_cnt,
6209 				    __u32 *prog_rec_sz)
6210 {
6211 	void *copy_start = NULL, *copy_end = NULL;
6212 	void *rec, *rec_end, *new_prog_info;
6213 	const struct btf_ext_info_sec *sec;
6214 	size_t old_sz, new_sz;
6215 	int i, sec_num, sec_idx, off_adj;
6216 
6217 	sec_num = 0;
6218 	for_each_btf_ext_sec(ext_info, sec) {
6219 		sec_idx = ext_info->sec_idxs[sec_num];
6220 		sec_num++;
6221 		if (prog->sec_idx != sec_idx)
6222 			continue;
6223 
6224 		for_each_btf_ext_rec(ext_info, sec, i, rec) {
6225 			__u32 insn_off = *(__u32 *)rec / BPF_INSN_SZ;
6226 
6227 			if (insn_off < prog->sec_insn_off)
6228 				continue;
6229 			if (insn_off >= prog->sec_insn_off + prog->sec_insn_cnt)
6230 				break;
6231 
6232 			if (!copy_start)
6233 				copy_start = rec;
6234 			copy_end = rec + ext_info->rec_size;
6235 		}
6236 
6237 		if (!copy_start)
6238 			return -ENOENT;
6239 
6240 		/* append func/line info of a given (sub-)program to the main
6241 		 * program func/line info
6242 		 */
6243 		old_sz = (size_t)(*prog_rec_cnt) * ext_info->rec_size;
6244 		new_sz = old_sz + (copy_end - copy_start);
6245 		new_prog_info = realloc(*prog_info, new_sz);
6246 		if (!new_prog_info)
6247 			return -ENOMEM;
6248 		*prog_info = new_prog_info;
6249 		*prog_rec_cnt = new_sz / ext_info->rec_size;
6250 		memcpy(new_prog_info + old_sz, copy_start, copy_end - copy_start);
6251 
6252 		/* Kernel instruction offsets are in units of 8-byte
6253 		 * instructions, while .BTF.ext instruction offsets generated
6254 		 * by Clang are in units of bytes. So convert Clang offsets
6255 		 * into kernel offsets and adjust offset according to program
6256 		 * relocated position.
6257 		 */
6258 		off_adj = prog->sub_insn_off - prog->sec_insn_off;
6259 		rec = new_prog_info + old_sz;
6260 		rec_end = new_prog_info + new_sz;
6261 		for (; rec < rec_end; rec += ext_info->rec_size) {
6262 			__u32 *insn_off = rec;
6263 
6264 			*insn_off = *insn_off / BPF_INSN_SZ + off_adj;
6265 		}
6266 		*prog_rec_sz = ext_info->rec_size;
6267 		return 0;
6268 	}
6269 
6270 	return -ENOENT;
6271 }
6272 
6273 static int
6274 reloc_prog_func_and_line_info(const struct bpf_object *obj,
6275 			      struct bpf_program *main_prog,
6276 			      const struct bpf_program *prog)
6277 {
6278 	int err;
6279 
6280 	/* no .BTF.ext relocation if .BTF.ext is missing or kernel doesn't
6281 	 * support func/line info
6282 	 */
6283 	if (!obj->btf_ext || !kernel_supports(obj, FEAT_BTF_FUNC))
6284 		return 0;
6285 
6286 	/* only attempt func info relocation if main program's func_info
6287 	 * relocation was successful
6288 	 */
6289 	if (main_prog != prog && !main_prog->func_info)
6290 		goto line_info;
6291 
6292 	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->func_info,
6293 				       &main_prog->func_info,
6294 				       &main_prog->func_info_cnt,
6295 				       &main_prog->func_info_rec_size);
6296 	if (err) {
6297 		if (err != -ENOENT) {
6298 			pr_warn("prog '%s': error relocating .BTF.ext function info: %s\n",
6299 				prog->name, errstr(err));
6300 			return err;
6301 		}
6302 		if (main_prog->func_info) {
6303 			/*
6304 			 * Some info has already been found but has problem
6305 			 * in the last btf_ext reloc. Must have to error out.
6306 			 */
6307 			pr_warn("prog '%s': missing .BTF.ext function info.\n", prog->name);
6308 			return err;
6309 		}
6310 		/* Have problem loading the very first info. Ignore the rest. */
6311 		pr_warn("prog '%s': missing .BTF.ext function info for the main program, skipping all of .BTF.ext func info.\n",
6312 			prog->name);
6313 	}
6314 
6315 line_info:
6316 	/* don't relocate line info if main program's relocation failed */
6317 	if (main_prog != prog && !main_prog->line_info)
6318 		return 0;
6319 
6320 	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->line_info,
6321 				       &main_prog->line_info,
6322 				       &main_prog->line_info_cnt,
6323 				       &main_prog->line_info_rec_size);
6324 	if (err) {
6325 		if (err != -ENOENT) {
6326 			pr_warn("prog '%s': error relocating .BTF.ext line info: %s\n",
6327 				prog->name, errstr(err));
6328 			return err;
6329 		}
6330 		if (main_prog->line_info) {
6331 			/*
6332 			 * Some info has already been found but has problem
6333 			 * in the last btf_ext reloc. Must have to error out.
6334 			 */
6335 			pr_warn("prog '%s': missing .BTF.ext line info.\n", prog->name);
6336 			return err;
6337 		}
6338 		/* Have problem loading the very first info. Ignore the rest. */
6339 		pr_warn("prog '%s': missing .BTF.ext line info for the main program, skipping all of .BTF.ext line info.\n",
6340 			prog->name);
6341 	}
6342 	return 0;
6343 }
6344 
6345 static int cmp_relo_by_insn_idx(const void *key, const void *elem)
6346 {
6347 	size_t insn_idx = *(const size_t *)key;
6348 	const struct reloc_desc *relo = elem;
6349 
6350 	if (insn_idx == relo->insn_idx)
6351 		return 0;
6352 	return insn_idx < relo->insn_idx ? -1 : 1;
6353 }
6354 
6355 static struct reloc_desc *find_prog_insn_relo(const struct bpf_program *prog, size_t insn_idx)
6356 {
6357 	if (!prog->nr_reloc)
6358 		return NULL;
6359 	return bsearch(&insn_idx, prog->reloc_desc, prog->nr_reloc,
6360 		       sizeof(*prog->reloc_desc), cmp_relo_by_insn_idx);
6361 }
6362 
6363 static int append_subprog_relos(struct bpf_program *main_prog, struct bpf_program *subprog)
6364 {
6365 	int new_cnt = main_prog->nr_reloc + subprog->nr_reloc;
6366 	struct reloc_desc *relos;
6367 	int i;
6368 
6369 	if (main_prog == subprog)
6370 		return 0;
6371 	relos = libbpf_reallocarray(main_prog->reloc_desc, new_cnt, sizeof(*relos));
6372 	/* if new count is zero, reallocarray can return a valid NULL result;
6373 	 * in this case the previous pointer will be freed, so we *have to*
6374 	 * reassign old pointer to the new value (even if it's NULL)
6375 	 */
6376 	if (!relos && new_cnt)
6377 		return -ENOMEM;
6378 	if (subprog->nr_reloc)
6379 		memcpy(relos + main_prog->nr_reloc, subprog->reloc_desc,
6380 		       sizeof(*relos) * subprog->nr_reloc);
6381 
6382 	for (i = main_prog->nr_reloc; i < new_cnt; i++)
6383 		relos[i].insn_idx += subprog->sub_insn_off;
6384 	/* After insn_idx adjustment the 'relos' array is still sorted
6385 	 * by insn_idx and doesn't break bsearch.
6386 	 */
6387 	main_prog->reloc_desc = relos;
6388 	main_prog->nr_reloc = new_cnt;
6389 	return 0;
6390 }
6391 
6392 static int
6393 bpf_object__append_subprog_code(struct bpf_object *obj, struct bpf_program *main_prog,
6394 				struct bpf_program *subprog)
6395 {
6396        struct bpf_insn *insns;
6397        size_t new_cnt;
6398        int err;
6399 
6400        subprog->sub_insn_off = main_prog->insns_cnt;
6401 
6402        new_cnt = main_prog->insns_cnt + subprog->insns_cnt;
6403        insns = libbpf_reallocarray(main_prog->insns, new_cnt, sizeof(*insns));
6404        if (!insns) {
6405                pr_warn("prog '%s': failed to realloc prog code\n", main_prog->name);
6406                return -ENOMEM;
6407        }
6408        main_prog->insns = insns;
6409        main_prog->insns_cnt = new_cnt;
6410 
6411        memcpy(main_prog->insns + subprog->sub_insn_off, subprog->insns,
6412               subprog->insns_cnt * sizeof(*insns));
6413 
6414        pr_debug("prog '%s': added %zu insns from sub-prog '%s'\n",
6415                 main_prog->name, subprog->insns_cnt, subprog->name);
6416 
6417        /* The subprog insns are now appended. Append its relos too. */
6418        err = append_subprog_relos(main_prog, subprog);
6419        if (err)
6420                return err;
6421        return 0;
6422 }
6423 
6424 static int
6425 bpf_object__reloc_code(struct bpf_object *obj, struct bpf_program *main_prog,
6426 		       struct bpf_program *prog)
6427 {
6428 	size_t sub_insn_idx, insn_idx;
6429 	struct bpf_program *subprog;
6430 	struct reloc_desc *relo;
6431 	struct bpf_insn *insn;
6432 	int err;
6433 
6434 	err = reloc_prog_func_and_line_info(obj, main_prog, prog);
6435 	if (err)
6436 		return err;
6437 
6438 	for (insn_idx = 0; insn_idx < prog->sec_insn_cnt; insn_idx++) {
6439 		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6440 		if (!insn_is_subprog_call(insn) && !insn_is_pseudo_func(insn))
6441 			continue;
6442 
6443 		relo = find_prog_insn_relo(prog, insn_idx);
6444 		if (relo && relo->type == RELO_EXTERN_CALL)
6445 			/* kfunc relocations will be handled later
6446 			 * in bpf_object__relocate_data()
6447 			 */
6448 			continue;
6449 		if (relo && relo->type != RELO_CALL && relo->type != RELO_SUBPROG_ADDR) {
6450 			pr_warn("prog '%s': unexpected relo for insn #%zu, type %d\n",
6451 				prog->name, insn_idx, relo->type);
6452 			return -LIBBPF_ERRNO__RELOC;
6453 		}
6454 		if (relo) {
6455 			/* sub-program instruction index is a combination of
6456 			 * an offset of a symbol pointed to by relocation and
6457 			 * call instruction's imm field; for global functions,
6458 			 * call always has imm = -1, but for static functions
6459 			 * relocation is against STT_SECTION and insn->imm
6460 			 * points to a start of a static function
6461 			 *
6462 			 * for subprog addr relocation, the relo->sym_off + insn->imm is
6463 			 * the byte offset in the corresponding section.
6464 			 */
6465 			if (relo->type == RELO_CALL)
6466 				sub_insn_idx = relo->sym_off / BPF_INSN_SZ + insn->imm + 1;
6467 			else
6468 				sub_insn_idx = (relo->sym_off + insn->imm) / BPF_INSN_SZ;
6469 		} else if (insn_is_pseudo_func(insn)) {
6470 			/*
6471 			 * RELO_SUBPROG_ADDR relo is always emitted even if both
6472 			 * functions are in the same section, so it shouldn't reach here.
6473 			 */
6474 			pr_warn("prog '%s': missing subprog addr relo for insn #%zu\n",
6475 				prog->name, insn_idx);
6476 			return -LIBBPF_ERRNO__RELOC;
6477 		} else {
6478 			/* if subprogram call is to a static function within
6479 			 * the same ELF section, there won't be any relocation
6480 			 * emitted, but it also means there is no additional
6481 			 * offset necessary, insns->imm is relative to
6482 			 * instruction's original position within the section
6483 			 */
6484 			sub_insn_idx = prog->sec_insn_off + insn_idx + insn->imm + 1;
6485 		}
6486 
6487 		/* we enforce that sub-programs should be in .text section */
6488 		subprog = find_prog_by_sec_insn(obj, obj->efile.text_shndx, sub_insn_idx);
6489 		if (!subprog) {
6490 			pr_warn("prog '%s': no .text section found yet sub-program call exists\n",
6491 				prog->name);
6492 			return -LIBBPF_ERRNO__RELOC;
6493 		}
6494 
6495 		/* if it's the first call instruction calling into this
6496 		 * subprogram (meaning this subprog hasn't been processed
6497 		 * yet) within the context of current main program:
6498 		 *   - append it at the end of main program's instructions blog;
6499 		 *   - process is recursively, while current program is put on hold;
6500 		 *   - if that subprogram calls some other not yet processes
6501 		 *   subprogram, same thing will happen recursively until
6502 		 *   there are no more unprocesses subprograms left to append
6503 		 *   and relocate.
6504 		 */
6505 		if (subprog->sub_insn_off == 0) {
6506 			err = bpf_object__append_subprog_code(obj, main_prog, subprog);
6507 			if (err)
6508 				return err;
6509 			err = bpf_object__reloc_code(obj, main_prog, subprog);
6510 			if (err)
6511 				return err;
6512 		}
6513 
6514 		/* main_prog->insns memory could have been re-allocated, so
6515 		 * calculate pointer again
6516 		 */
6517 		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6518 		/* calculate correct instruction position within current main
6519 		 * prog; each main prog can have a different set of
6520 		 * subprograms appended (potentially in different order as
6521 		 * well), so position of any subprog can be different for
6522 		 * different main programs
6523 		 */
6524 		insn->imm = subprog->sub_insn_off - (prog->sub_insn_off + insn_idx) - 1;
6525 
6526 		pr_debug("prog '%s': insn #%zu relocated, imm %d points to subprog '%s' (now at %zu offset)\n",
6527 			 prog->name, insn_idx, insn->imm, subprog->name, subprog->sub_insn_off);
6528 	}
6529 
6530 	return 0;
6531 }
6532 
6533 /*
6534  * Relocate sub-program calls.
6535  *
6536  * Algorithm operates as follows. Each entry-point BPF program (referred to as
6537  * main prog) is processed separately. For each subprog (non-entry functions,
6538  * that can be called from either entry progs or other subprogs) gets their
6539  * sub_insn_off reset to zero. This serves as indicator that this subprogram
6540  * hasn't been yet appended and relocated within current main prog. Once its
6541  * relocated, sub_insn_off will point at the position within current main prog
6542  * where given subprog was appended. This will further be used to relocate all
6543  * the call instructions jumping into this subprog.
6544  *
6545  * We start with main program and process all call instructions. If the call
6546  * is into a subprog that hasn't been processed (i.e., subprog->sub_insn_off
6547  * is zero), subprog instructions are appended at the end of main program's
6548  * instruction array. Then main program is "put on hold" while we recursively
6549  * process newly appended subprogram. If that subprogram calls into another
6550  * subprogram that hasn't been appended, new subprogram is appended again to
6551  * the *main* prog's instructions (subprog's instructions are always left
6552  * untouched, as they need to be in unmodified state for subsequent main progs
6553  * and subprog instructions are always sent only as part of a main prog) and
6554  * the process continues recursively. Once all the subprogs called from a main
6555  * prog or any of its subprogs are appended (and relocated), all their
6556  * positions within finalized instructions array are known, so it's easy to
6557  * rewrite call instructions with correct relative offsets, corresponding to
6558  * desired target subprog.
6559  *
6560  * Its important to realize that some subprogs might not be called from some
6561  * main prog and any of its called/used subprogs. Those will keep their
6562  * subprog->sub_insn_off as zero at all times and won't be appended to current
6563  * main prog and won't be relocated within the context of current main prog.
6564  * They might still be used from other main progs later.
6565  *
6566  * Visually this process can be shown as below. Suppose we have two main
6567  * programs mainA and mainB and BPF object contains three subprogs: subA,
6568  * subB, and subC. mainA calls only subA, mainB calls only subC, but subA and
6569  * subC both call subB:
6570  *
6571  *        +--------+ +-------+
6572  *        |        v v       |
6573  *     +--+---+ +--+-+-+ +---+--+
6574  *     | subA | | subB | | subC |
6575  *     +--+---+ +------+ +---+--+
6576  *        ^                  ^
6577  *        |                  |
6578  *    +---+-------+   +------+----+
6579  *    |   mainA   |   |   mainB   |
6580  *    +-----------+   +-----------+
6581  *
6582  * We'll start relocating mainA, will find subA, append it and start
6583  * processing sub A recursively:
6584  *
6585  *    +-----------+------+
6586  *    |   mainA   | subA |
6587  *    +-----------+------+
6588  *
6589  * At this point we notice that subB is used from subA, so we append it and
6590  * relocate (there are no further subcalls from subB):
6591  *
6592  *    +-----------+------+------+
6593  *    |   mainA   | subA | subB |
6594  *    +-----------+------+------+
6595  *
6596  * At this point, we relocate subA calls, then go one level up and finish with
6597  * relocatin mainA calls. mainA is done.
6598  *
6599  * For mainB process is similar but results in different order. We start with
6600  * mainB and skip subA and subB, as mainB never calls them (at least
6601  * directly), but we see subC is needed, so we append and start processing it:
6602  *
6603  *    +-----------+------+
6604  *    |   mainB   | subC |
6605  *    +-----------+------+
6606  * Now we see subC needs subB, so we go back to it, append and relocate it:
6607  *
6608  *    +-----------+------+------+
6609  *    |   mainB   | subC | subB |
6610  *    +-----------+------+------+
6611  *
6612  * At this point we unwind recursion, relocate calls in subC, then in mainB.
6613  */
6614 static int
6615 bpf_object__relocate_calls(struct bpf_object *obj, struct bpf_program *prog)
6616 {
6617 	struct bpf_program *subprog;
6618 	int i, err;
6619 
6620 	/* mark all subprogs as not relocated (yet) within the context of
6621 	 * current main program
6622 	 */
6623 	for (i = 0; i < obj->nr_programs; i++) {
6624 		subprog = &obj->programs[i];
6625 		if (!prog_is_subprog(obj, subprog))
6626 			continue;
6627 
6628 		subprog->sub_insn_off = 0;
6629 	}
6630 
6631 	err = bpf_object__reloc_code(obj, prog, prog);
6632 	if (err)
6633 		return err;
6634 
6635 	return 0;
6636 }
6637 
6638 static void
6639 bpf_object__free_relocs(struct bpf_object *obj)
6640 {
6641 	struct bpf_program *prog;
6642 	int i;
6643 
6644 	/* free up relocation descriptors */
6645 	for (i = 0; i < obj->nr_programs; i++) {
6646 		prog = &obj->programs[i];
6647 		zfree(&prog->reloc_desc);
6648 		prog->nr_reloc = 0;
6649 	}
6650 }
6651 
6652 static int cmp_relocs(const void *_a, const void *_b)
6653 {
6654 	const struct reloc_desc *a = _a;
6655 	const struct reloc_desc *b = _b;
6656 
6657 	if (a->insn_idx != b->insn_idx)
6658 		return a->insn_idx < b->insn_idx ? -1 : 1;
6659 
6660 	/* no two relocations should have the same insn_idx, but ... */
6661 	if (a->type != b->type)
6662 		return a->type < b->type ? -1 : 1;
6663 
6664 	return 0;
6665 }
6666 
6667 static void bpf_object__sort_relos(struct bpf_object *obj)
6668 {
6669 	int i;
6670 
6671 	for (i = 0; i < obj->nr_programs; i++) {
6672 		struct bpf_program *p = &obj->programs[i];
6673 
6674 		if (!p->nr_reloc)
6675 			continue;
6676 
6677 		qsort(p->reloc_desc, p->nr_reloc, sizeof(*p->reloc_desc), cmp_relocs);
6678 	}
6679 }
6680 
6681 static int bpf_prog_assign_exc_cb(struct bpf_object *obj, struct bpf_program *prog)
6682 {
6683 	const char *str = "exception_callback:";
6684 	size_t pfx_len = strlen(str);
6685 	int i, j, n;
6686 
6687 	if (!obj->btf || !kernel_supports(obj, FEAT_BTF_DECL_TAG))
6688 		return 0;
6689 
6690 	n = btf__type_cnt(obj->btf);
6691 	for (i = 1; i < n; i++) {
6692 		const char *name;
6693 		struct btf_type *t;
6694 
6695 		t = btf_type_by_id(obj->btf, i);
6696 		if (!btf_is_decl_tag(t) || btf_decl_tag(t)->component_idx != -1)
6697 			continue;
6698 
6699 		name = btf__str_by_offset(obj->btf, t->name_off);
6700 		if (strncmp(name, str, pfx_len) != 0)
6701 			continue;
6702 
6703 		t = btf_type_by_id(obj->btf, t->type);
6704 		if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL) {
6705 			pr_warn("prog '%s': exception_callback:<value> decl tag not applied to the main program\n",
6706 				prog->name);
6707 			return -EINVAL;
6708 		}
6709 		if (strcmp(prog->name, btf__str_by_offset(obj->btf, t->name_off)) != 0)
6710 			continue;
6711 		/* Multiple callbacks are specified for the same prog,
6712 		 * the verifier will eventually return an error for this
6713 		 * case, hence simply skip appending a subprog.
6714 		 */
6715 		if (prog->exception_cb_idx >= 0) {
6716 			prog->exception_cb_idx = -1;
6717 			break;
6718 		}
6719 
6720 		name += pfx_len;
6721 		if (str_is_empty(name)) {
6722 			pr_warn("prog '%s': exception_callback:<value> decl tag contains empty value\n",
6723 				prog->name);
6724 			return -EINVAL;
6725 		}
6726 
6727 		for (j = 0; j < obj->nr_programs; j++) {
6728 			struct bpf_program *subprog = &obj->programs[j];
6729 
6730 			if (!prog_is_subprog(obj, subprog))
6731 				continue;
6732 			if (strcmp(name, subprog->name) != 0)
6733 				continue;
6734 			/* Enforce non-hidden, as from verifier point of
6735 			 * view it expects global functions, whereas the
6736 			 * mark_btf_static fixes up linkage as static.
6737 			 */
6738 			if (!subprog->sym_global || subprog->mark_btf_static) {
6739 				pr_warn("prog '%s': exception callback %s must be a global non-hidden function\n",
6740 					prog->name, subprog->name);
6741 				return -EINVAL;
6742 			}
6743 			/* Let's see if we already saw a static exception callback with the same name */
6744 			if (prog->exception_cb_idx >= 0) {
6745 				pr_warn("prog '%s': multiple subprogs with same name as exception callback '%s'\n",
6746 					prog->name, subprog->name);
6747 				return -EINVAL;
6748 			}
6749 			prog->exception_cb_idx = j;
6750 			break;
6751 		}
6752 
6753 		if (prog->exception_cb_idx >= 0)
6754 			continue;
6755 
6756 		pr_warn("prog '%s': cannot find exception callback '%s'\n", prog->name, name);
6757 		return -ENOENT;
6758 	}
6759 
6760 	return 0;
6761 }
6762 
6763 static struct {
6764 	enum bpf_prog_type prog_type;
6765 	const char *ctx_name;
6766 } global_ctx_map[] = {
6767 	{ BPF_PROG_TYPE_CGROUP_DEVICE,           "bpf_cgroup_dev_ctx" },
6768 	{ BPF_PROG_TYPE_CGROUP_SKB,              "__sk_buff" },
6769 	{ BPF_PROG_TYPE_CGROUP_SOCK,             "bpf_sock" },
6770 	{ BPF_PROG_TYPE_CGROUP_SOCK_ADDR,        "bpf_sock_addr" },
6771 	{ BPF_PROG_TYPE_CGROUP_SOCKOPT,          "bpf_sockopt" },
6772 	{ BPF_PROG_TYPE_CGROUP_SYSCTL,           "bpf_sysctl" },
6773 	{ BPF_PROG_TYPE_FLOW_DISSECTOR,          "__sk_buff" },
6774 	{ BPF_PROG_TYPE_KPROBE,                  "bpf_user_pt_regs_t" },
6775 	{ BPF_PROG_TYPE_LWT_IN,                  "__sk_buff" },
6776 	{ BPF_PROG_TYPE_LWT_OUT,                 "__sk_buff" },
6777 	{ BPF_PROG_TYPE_LWT_SEG6LOCAL,           "__sk_buff" },
6778 	{ BPF_PROG_TYPE_LWT_XMIT,                "__sk_buff" },
6779 	{ BPF_PROG_TYPE_NETFILTER,               "bpf_nf_ctx" },
6780 	{ BPF_PROG_TYPE_PERF_EVENT,              "bpf_perf_event_data" },
6781 	{ BPF_PROG_TYPE_RAW_TRACEPOINT,          "bpf_raw_tracepoint_args" },
6782 	{ BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE, "bpf_raw_tracepoint_args" },
6783 	{ BPF_PROG_TYPE_SCHED_ACT,               "__sk_buff" },
6784 	{ BPF_PROG_TYPE_SCHED_CLS,               "__sk_buff" },
6785 	{ BPF_PROG_TYPE_SK_LOOKUP,               "bpf_sk_lookup" },
6786 	{ BPF_PROG_TYPE_SK_MSG,                  "sk_msg_md" },
6787 	{ BPF_PROG_TYPE_SK_REUSEPORT,            "sk_reuseport_md" },
6788 	{ BPF_PROG_TYPE_SK_SKB,                  "__sk_buff" },
6789 	{ BPF_PROG_TYPE_SOCK_OPS,                "bpf_sock_ops" },
6790 	{ BPF_PROG_TYPE_SOCKET_FILTER,           "__sk_buff" },
6791 	{ BPF_PROG_TYPE_XDP,                     "xdp_md" },
6792 	/* all other program types don't have "named" context structs */
6793 };
6794 
6795 /* forward declarations for arch-specific underlying types of bpf_user_pt_regs_t typedef,
6796  * for below __builtin_types_compatible_p() checks;
6797  * with this approach we don't need any extra arch-specific #ifdef guards
6798  */
6799 struct pt_regs;
6800 struct user_pt_regs;
6801 struct user_regs_struct;
6802 
6803 static bool need_func_arg_type_fixup(const struct btf *btf, const struct bpf_program *prog,
6804 				     const char *subprog_name, int arg_idx,
6805 				     int arg_type_id, const char *ctx_name)
6806 {
6807 	const struct btf_type *t;
6808 	const char *tname;
6809 
6810 	/* check if existing parameter already matches verifier expectations */
6811 	t = skip_mods_and_typedefs(btf, arg_type_id, NULL);
6812 	if (!btf_is_ptr(t))
6813 		goto out_warn;
6814 
6815 	/* typedef bpf_user_pt_regs_t is a special PITA case, valid for kprobe
6816 	 * and perf_event programs, so check this case early on and forget
6817 	 * about it for subsequent checks
6818 	 */
6819 	while (btf_is_mod(t))
6820 		t = btf__type_by_id(btf, t->type);
6821 	if (btf_is_typedef(t) &&
6822 	    (prog->type == BPF_PROG_TYPE_KPROBE || prog->type == BPF_PROG_TYPE_PERF_EVENT)) {
6823 		tname = btf__str_by_offset(btf, t->name_off) ?: "<anon>";
6824 		if (strcmp(tname, "bpf_user_pt_regs_t") == 0)
6825 			return false; /* canonical type for kprobe/perf_event */
6826 	}
6827 
6828 	/* now we can ignore typedefs moving forward */
6829 	t = skip_mods_and_typedefs(btf, t->type, NULL);
6830 
6831 	/* if it's `void *`, definitely fix up BTF info */
6832 	if (btf_is_void(t))
6833 		return true;
6834 
6835 	/* if it's already proper canonical type, no need to fix up */
6836 	tname = btf__str_by_offset(btf, t->name_off) ?: "<anon>";
6837 	if (btf_is_struct(t) && strcmp(tname, ctx_name) == 0)
6838 		return false;
6839 
6840 	/* special cases */
6841 	switch (prog->type) {
6842 	case BPF_PROG_TYPE_KPROBE:
6843 		/* `struct pt_regs *` is expected, but we need to fix up */
6844 		if (btf_is_struct(t) && strcmp(tname, "pt_regs") == 0)
6845 			return true;
6846 		break;
6847 	case BPF_PROG_TYPE_PERF_EVENT:
6848 		if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct pt_regs) &&
6849 		    btf_is_struct(t) && strcmp(tname, "pt_regs") == 0)
6850 			return true;
6851 		if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct user_pt_regs) &&
6852 		    btf_is_struct(t) && strcmp(tname, "user_pt_regs") == 0)
6853 			return true;
6854 		if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct user_regs_struct) &&
6855 		    btf_is_struct(t) && strcmp(tname, "user_regs_struct") == 0)
6856 			return true;
6857 		break;
6858 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
6859 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
6860 		/* allow u64* as ctx */
6861 		if (btf_is_int(t) && t->size == 8)
6862 			return true;
6863 		break;
6864 	default:
6865 		break;
6866 	}
6867 
6868 out_warn:
6869 	pr_warn("prog '%s': subprog '%s' arg#%d is expected to be of `struct %s *` type\n",
6870 		prog->name, subprog_name, arg_idx, ctx_name);
6871 	return false;
6872 }
6873 
6874 static int clone_func_btf_info(struct btf *btf, int orig_fn_id, struct bpf_program *prog)
6875 {
6876 	int fn_id, fn_proto_id, ret_type_id, orig_proto_id;
6877 	int i, err, arg_cnt, fn_name_off, linkage;
6878 	struct btf_type *fn_t, *fn_proto_t, *t;
6879 	struct btf_param *p;
6880 
6881 	/* caller already validated FUNC -> FUNC_PROTO validity */
6882 	fn_t = btf_type_by_id(btf, orig_fn_id);
6883 	fn_proto_t = btf_type_by_id(btf, fn_t->type);
6884 
6885 	/* Note that each btf__add_xxx() operation invalidates
6886 	 * all btf_type and string pointers, so we need to be
6887 	 * very careful when cloning BTF types. BTF type
6888 	 * pointers have to be always refetched. And to avoid
6889 	 * problems with invalidated string pointers, we
6890 	 * add empty strings initially, then just fix up
6891 	 * name_off offsets in place. Offsets are stable for
6892 	 * existing strings, so that works out.
6893 	 */
6894 	fn_name_off = fn_t->name_off; /* we are about to invalidate fn_t */
6895 	linkage = btf_func_linkage(fn_t);
6896 	orig_proto_id = fn_t->type; /* original FUNC_PROTO ID */
6897 	ret_type_id = fn_proto_t->type; /* fn_proto_t will be invalidated */
6898 	arg_cnt = btf_vlen(fn_proto_t);
6899 
6900 	/* clone FUNC_PROTO and its params */
6901 	fn_proto_id = btf__add_func_proto(btf, ret_type_id);
6902 	if (fn_proto_id < 0)
6903 		return -EINVAL;
6904 
6905 	for (i = 0; i < arg_cnt; i++) {
6906 		int name_off;
6907 
6908 		/* copy original parameter data */
6909 		t = btf_type_by_id(btf, orig_proto_id);
6910 		p = &btf_params(t)[i];
6911 		name_off = p->name_off;
6912 
6913 		err = btf__add_func_param(btf, "", p->type);
6914 		if (err)
6915 			return err;
6916 
6917 		fn_proto_t = btf_type_by_id(btf, fn_proto_id);
6918 		p = &btf_params(fn_proto_t)[i];
6919 		p->name_off = name_off; /* use remembered str offset */
6920 	}
6921 
6922 	/* clone FUNC now, btf__add_func() enforces non-empty name, so use
6923 	 * entry program's name as a placeholder, which we replace immediately
6924 	 * with original name_off
6925 	 */
6926 	fn_id = btf__add_func(btf, prog->name, linkage, fn_proto_id);
6927 	if (fn_id < 0)
6928 		return -EINVAL;
6929 
6930 	fn_t = btf_type_by_id(btf, fn_id);
6931 	fn_t->name_off = fn_name_off; /* reuse original string */
6932 
6933 	return fn_id;
6934 }
6935 
6936 /* Check if main program or global subprog's function prototype has `arg:ctx`
6937  * argument tags, and, if necessary, substitute correct type to match what BPF
6938  * verifier would expect, taking into account specific program type. This
6939  * allows to support __arg_ctx tag transparently on old kernels that don't yet
6940  * have a native support for it in the verifier, making user's life much
6941  * easier.
6942  */
6943 static int bpf_program_fixup_func_info(struct bpf_object *obj, struct bpf_program *prog)
6944 {
6945 	const char *ctx_name = NULL, *ctx_tag = "arg:ctx", *fn_name;
6946 	struct bpf_func_info_min *func_rec;
6947 	struct btf_type *fn_t, *fn_proto_t;
6948 	struct btf *btf = obj->btf;
6949 	const struct btf_type *t;
6950 	struct btf_param *p;
6951 	int ptr_id = 0, struct_id, tag_id, orig_fn_id;
6952 	int i, n, arg_idx, arg_cnt, err, rec_idx;
6953 	int *orig_ids;
6954 
6955 	/* no .BTF.ext, no problem */
6956 	if (!obj->btf_ext || !prog->func_info)
6957 		return 0;
6958 
6959 	/* don't do any fix ups if kernel natively supports __arg_ctx */
6960 	if (kernel_supports(obj, FEAT_ARG_CTX_TAG))
6961 		return 0;
6962 
6963 	/* some BPF program types just don't have named context structs, so
6964 	 * this fallback mechanism doesn't work for them
6965 	 */
6966 	for (i = 0; i < ARRAY_SIZE(global_ctx_map); i++) {
6967 		if (global_ctx_map[i].prog_type != prog->type)
6968 			continue;
6969 		ctx_name = global_ctx_map[i].ctx_name;
6970 		break;
6971 	}
6972 	if (!ctx_name)
6973 		return 0;
6974 
6975 	/* remember original func BTF IDs to detect if we already cloned them */
6976 	orig_ids = calloc(prog->func_info_cnt, sizeof(*orig_ids));
6977 	if (!orig_ids)
6978 		return -ENOMEM;
6979 	for (i = 0; i < prog->func_info_cnt; i++) {
6980 		func_rec = prog->func_info + prog->func_info_rec_size * i;
6981 		orig_ids[i] = func_rec->type_id;
6982 	}
6983 
6984 	/* go through each DECL_TAG with "arg:ctx" and see if it points to one
6985 	 * of our subprogs; if yes and subprog is global and needs adjustment,
6986 	 * clone and adjust FUNC -> FUNC_PROTO combo
6987 	 */
6988 	for (i = 1, n = btf__type_cnt(btf); i < n; i++) {
6989 		/* only DECL_TAG with "arg:ctx" value are interesting */
6990 		t = btf__type_by_id(btf, i);
6991 		if (!btf_is_decl_tag(t))
6992 			continue;
6993 		if (strcmp(btf__str_by_offset(btf, t->name_off), ctx_tag) != 0)
6994 			continue;
6995 
6996 		/* only global funcs need adjustment, if at all */
6997 		orig_fn_id = t->type;
6998 		fn_t = btf_type_by_id(btf, orig_fn_id);
6999 		if (!btf_is_func(fn_t) || btf_func_linkage(fn_t) != BTF_FUNC_GLOBAL)
7000 			continue;
7001 
7002 		/* sanity check FUNC -> FUNC_PROTO chain, just in case */
7003 		fn_proto_t = btf_type_by_id(btf, fn_t->type);
7004 		if (!fn_proto_t || !btf_is_func_proto(fn_proto_t))
7005 			continue;
7006 
7007 		/* find corresponding func_info record */
7008 		func_rec = NULL;
7009 		for (rec_idx = 0; rec_idx < prog->func_info_cnt; rec_idx++) {
7010 			if (orig_ids[rec_idx] == t->type) {
7011 				func_rec = prog->func_info + prog->func_info_rec_size * rec_idx;
7012 				break;
7013 			}
7014 		}
7015 		/* current main program doesn't call into this subprog */
7016 		if (!func_rec)
7017 			continue;
7018 
7019 		/* some more sanity checking of DECL_TAG */
7020 		arg_cnt = btf_vlen(fn_proto_t);
7021 		arg_idx = btf_decl_tag(t)->component_idx;
7022 		if (arg_idx < 0 || arg_idx >= arg_cnt)
7023 			continue;
7024 
7025 		/* check if we should fix up argument type */
7026 		p = &btf_params(fn_proto_t)[arg_idx];
7027 		fn_name = btf__str_by_offset(btf, fn_t->name_off) ?: "<anon>";
7028 		if (!need_func_arg_type_fixup(btf, prog, fn_name, arg_idx, p->type, ctx_name))
7029 			continue;
7030 
7031 		/* clone fn/fn_proto, unless we already did it for another arg */
7032 		if (func_rec->type_id == orig_fn_id) {
7033 			int fn_id;
7034 
7035 			fn_id = clone_func_btf_info(btf, orig_fn_id, prog);
7036 			if (fn_id < 0) {
7037 				err = fn_id;
7038 				goto err_out;
7039 			}
7040 
7041 			/* point func_info record to a cloned FUNC type */
7042 			func_rec->type_id = fn_id;
7043 		}
7044 
7045 		/* create PTR -> STRUCT type chain to mark PTR_TO_CTX argument;
7046 		 * we do it just once per main BPF program, as all global
7047 		 * funcs share the same program type, so need only PTR ->
7048 		 * STRUCT type chain
7049 		 */
7050 		if (ptr_id == 0) {
7051 			struct_id = btf__add_struct(btf, ctx_name, 0);
7052 			ptr_id = btf__add_ptr(btf, struct_id);
7053 			if (ptr_id < 0 || struct_id < 0) {
7054 				err = -EINVAL;
7055 				goto err_out;
7056 			}
7057 		}
7058 
7059 		/* for completeness, clone DECL_TAG and point it to cloned param */
7060 		tag_id = btf__add_decl_tag(btf, ctx_tag, func_rec->type_id, arg_idx);
7061 		if (tag_id < 0) {
7062 			err = -EINVAL;
7063 			goto err_out;
7064 		}
7065 
7066 		/* all the BTF manipulations invalidated pointers, refetch them */
7067 		fn_t = btf_type_by_id(btf, func_rec->type_id);
7068 		fn_proto_t = btf_type_by_id(btf, fn_t->type);
7069 
7070 		/* fix up type ID pointed to by param */
7071 		p = &btf_params(fn_proto_t)[arg_idx];
7072 		p->type = ptr_id;
7073 	}
7074 
7075 	free(orig_ids);
7076 	return 0;
7077 err_out:
7078 	free(orig_ids);
7079 	return err;
7080 }
7081 
7082 static int bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
7083 {
7084 	struct bpf_program *prog;
7085 	size_t i, j;
7086 	int err;
7087 
7088 	if (obj->btf_ext) {
7089 		err = bpf_object__relocate_core(obj, targ_btf_path);
7090 		if (err) {
7091 			pr_warn("failed to perform CO-RE relocations: %s\n",
7092 				errstr(err));
7093 			return err;
7094 		}
7095 		bpf_object__sort_relos(obj);
7096 	}
7097 
7098 	/* Before relocating calls pre-process relocations and mark
7099 	 * few ld_imm64 instructions that points to subprogs.
7100 	 * Otherwise bpf_object__reloc_code() later would have to consider
7101 	 * all ld_imm64 insns as relocation candidates. That would
7102 	 * reduce relocation speed, since amount of find_prog_insn_relo()
7103 	 * would increase and most of them will fail to find a relo.
7104 	 */
7105 	for (i = 0; i < obj->nr_programs; i++) {
7106 		prog = &obj->programs[i];
7107 		for (j = 0; j < prog->nr_reloc; j++) {
7108 			struct reloc_desc *relo = &prog->reloc_desc[j];
7109 			struct bpf_insn *insn = &prog->insns[relo->insn_idx];
7110 
7111 			/* mark the insn, so it's recognized by insn_is_pseudo_func() */
7112 			if (relo->type == RELO_SUBPROG_ADDR)
7113 				insn[0].src_reg = BPF_PSEUDO_FUNC;
7114 		}
7115 	}
7116 
7117 	/* relocate subprogram calls and append used subprograms to main
7118 	 * programs; each copy of subprogram code needs to be relocated
7119 	 * differently for each main program, because its code location might
7120 	 * have changed.
7121 	 * Append subprog relos to main programs to allow data relos to be
7122 	 * processed after text is completely relocated.
7123 	 */
7124 	for (i = 0; i < obj->nr_programs; i++) {
7125 		prog = &obj->programs[i];
7126 		/* sub-program's sub-calls are relocated within the context of
7127 		 * its main program only
7128 		 */
7129 		if (prog_is_subprog(obj, prog))
7130 			continue;
7131 		if (!prog->autoload)
7132 			continue;
7133 
7134 		err = bpf_object__relocate_calls(obj, prog);
7135 		if (err) {
7136 			pr_warn("prog '%s': failed to relocate calls: %s\n",
7137 				prog->name, errstr(err));
7138 			return err;
7139 		}
7140 
7141 		err = bpf_prog_assign_exc_cb(obj, prog);
7142 		if (err)
7143 			return err;
7144 		/* Now, also append exception callback if it has not been done already. */
7145 		if (prog->exception_cb_idx >= 0) {
7146 			struct bpf_program *subprog = &obj->programs[prog->exception_cb_idx];
7147 
7148 			/* Calling exception callback directly is disallowed, which the
7149 			 * verifier will reject later. In case it was processed already,
7150 			 * we can skip this step, otherwise for all other valid cases we
7151 			 * have to append exception callback now.
7152 			 */
7153 			if (subprog->sub_insn_off == 0) {
7154 				err = bpf_object__append_subprog_code(obj, prog, subprog);
7155 				if (err)
7156 					return err;
7157 				err = bpf_object__reloc_code(obj, prog, subprog);
7158 				if (err)
7159 					return err;
7160 			}
7161 		}
7162 	}
7163 	for (i = 0; i < obj->nr_programs; i++) {
7164 		prog = &obj->programs[i];
7165 		if (prog_is_subprog(obj, prog))
7166 			continue;
7167 		if (!prog->autoload)
7168 			continue;
7169 
7170 		/* Process data relos for main programs */
7171 		err = bpf_object__relocate_data(obj, prog);
7172 		if (err) {
7173 			pr_warn("prog '%s': failed to relocate data references: %s\n",
7174 				prog->name, errstr(err));
7175 			return err;
7176 		}
7177 
7178 		/* Fix up .BTF.ext information, if necessary */
7179 		err = bpf_program_fixup_func_info(obj, prog);
7180 		if (err) {
7181 			pr_warn("prog '%s': failed to perform .BTF.ext fix ups: %s\n",
7182 				prog->name, errstr(err));
7183 			return err;
7184 		}
7185 	}
7186 
7187 	return 0;
7188 }
7189 
7190 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
7191 					    Elf64_Shdr *shdr, Elf_Data *data);
7192 
7193 static int bpf_object__collect_map_relos(struct bpf_object *obj,
7194 					 Elf64_Shdr *shdr, Elf_Data *data)
7195 {
7196 	const int bpf_ptr_sz = 8, host_ptr_sz = sizeof(void *);
7197 	int i, j, nrels, new_sz;
7198 	const struct btf_var_secinfo *vi = NULL;
7199 	const struct btf_type *sec, *var, *def;
7200 	struct bpf_map *map = NULL, *targ_map = NULL;
7201 	struct bpf_program *targ_prog = NULL;
7202 	bool is_prog_array, is_map_in_map;
7203 	const struct btf_member *member;
7204 	const char *name, *mname, *type;
7205 	unsigned int moff;
7206 	Elf64_Sym *sym;
7207 	Elf64_Rel *rel;
7208 	void *tmp;
7209 
7210 	if (!obj->efile.btf_maps_sec_btf_id || !obj->btf)
7211 		return -EINVAL;
7212 	sec = btf__type_by_id(obj->btf, obj->efile.btf_maps_sec_btf_id);
7213 	if (!sec)
7214 		return -EINVAL;
7215 
7216 	nrels = shdr->sh_size / shdr->sh_entsize;
7217 	for (i = 0; i < nrels; i++) {
7218 		rel = elf_rel_by_idx(data, i);
7219 		if (!rel) {
7220 			pr_warn(".maps relo #%d: failed to get ELF relo\n", i);
7221 			return -LIBBPF_ERRNO__FORMAT;
7222 		}
7223 
7224 		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
7225 		if (!sym) {
7226 			pr_warn(".maps relo #%d: symbol %zx not found\n",
7227 				i, (size_t)ELF64_R_SYM(rel->r_info));
7228 			return -LIBBPF_ERRNO__FORMAT;
7229 		}
7230 		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
7231 
7232 		pr_debug(".maps relo #%d: for %zd value %zd rel->r_offset %zu name %d ('%s')\n",
7233 			 i, (ssize_t)(rel->r_info >> 32), (size_t)sym->st_value,
7234 			 (size_t)rel->r_offset, sym->st_name, name);
7235 
7236 		for (j = 0; j < obj->nr_maps; j++) {
7237 			map = &obj->maps[j];
7238 			if (map->sec_idx != obj->efile.btf_maps_shndx)
7239 				continue;
7240 
7241 			vi = btf_var_secinfos(sec) + map->btf_var_idx;
7242 			if (vi->offset <= rel->r_offset &&
7243 			    rel->r_offset + bpf_ptr_sz <= vi->offset + vi->size)
7244 				break;
7245 		}
7246 		if (j == obj->nr_maps) {
7247 			pr_warn(".maps relo #%d: cannot find map '%s' at rel->r_offset %zu\n",
7248 				i, name, (size_t)rel->r_offset);
7249 			return -EINVAL;
7250 		}
7251 
7252 		is_map_in_map = bpf_map_type__is_map_in_map(map->def.type);
7253 		is_prog_array = map->def.type == BPF_MAP_TYPE_PROG_ARRAY;
7254 		type = is_map_in_map ? "map" : "prog";
7255 		if (is_map_in_map) {
7256 			if (sym->st_shndx != obj->efile.btf_maps_shndx) {
7257 				pr_warn(".maps relo #%d: '%s' isn't a BTF-defined map\n",
7258 					i, name);
7259 				return -LIBBPF_ERRNO__RELOC;
7260 			}
7261 			if (map->def.type == BPF_MAP_TYPE_HASH_OF_MAPS &&
7262 			    map->def.key_size != sizeof(int)) {
7263 				pr_warn(".maps relo #%d: hash-of-maps '%s' should have key size %zu.\n",
7264 					i, map->name, sizeof(int));
7265 				return -EINVAL;
7266 			}
7267 			targ_map = bpf_object__find_map_by_name(obj, name);
7268 			if (!targ_map) {
7269 				pr_warn(".maps relo #%d: '%s' isn't a valid map reference\n",
7270 					i, name);
7271 				return -ESRCH;
7272 			}
7273 		} else if (is_prog_array) {
7274 			targ_prog = bpf_object__find_program_by_name(obj, name);
7275 			if (!targ_prog) {
7276 				pr_warn(".maps relo #%d: '%s' isn't a valid program reference\n",
7277 					i, name);
7278 				return -ESRCH;
7279 			}
7280 			if (targ_prog->sec_idx != sym->st_shndx ||
7281 			    targ_prog->sec_insn_off * 8 != sym->st_value ||
7282 			    prog_is_subprog(obj, targ_prog)) {
7283 				pr_warn(".maps relo #%d: '%s' isn't an entry-point program\n",
7284 					i, name);
7285 				return -LIBBPF_ERRNO__RELOC;
7286 			}
7287 		} else {
7288 			return -EINVAL;
7289 		}
7290 
7291 		var = btf__type_by_id(obj->btf, vi->type);
7292 		def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
7293 		if (btf_vlen(def) == 0)
7294 			return -EINVAL;
7295 		member = btf_members(def) + btf_vlen(def) - 1;
7296 		mname = btf__name_by_offset(obj->btf, member->name_off);
7297 		if (strcmp(mname, "values"))
7298 			return -EINVAL;
7299 
7300 		moff = btf_member_bit_offset(def, btf_vlen(def) - 1) / 8;
7301 		if (rel->r_offset - vi->offset < moff)
7302 			return -EINVAL;
7303 
7304 		moff = rel->r_offset - vi->offset - moff;
7305 		/* here we use BPF pointer size, which is always 64 bit, as we
7306 		 * are parsing ELF that was built for BPF target
7307 		 */
7308 		if (moff % bpf_ptr_sz)
7309 			return -EINVAL;
7310 		moff /= bpf_ptr_sz;
7311 		if (moff >= map->init_slots_sz) {
7312 			new_sz = moff + 1;
7313 			tmp = libbpf_reallocarray(map->init_slots, new_sz, host_ptr_sz);
7314 			if (!tmp)
7315 				return -ENOMEM;
7316 			map->init_slots = tmp;
7317 			memset(map->init_slots + map->init_slots_sz, 0,
7318 			       (new_sz - map->init_slots_sz) * host_ptr_sz);
7319 			map->init_slots_sz = new_sz;
7320 		}
7321 		map->init_slots[moff] = is_map_in_map ? (void *)targ_map : (void *)targ_prog;
7322 
7323 		pr_debug(".maps relo #%d: map '%s' slot [%d] points to %s '%s'\n",
7324 			 i, map->name, moff, type, name);
7325 	}
7326 
7327 	return 0;
7328 }
7329 
7330 static int bpf_object__collect_relos(struct bpf_object *obj)
7331 {
7332 	int i, err;
7333 
7334 	for (i = 0; i < obj->efile.sec_cnt; i++) {
7335 		struct elf_sec_desc *sec_desc = &obj->efile.secs[i];
7336 		Elf64_Shdr *shdr;
7337 		Elf_Data *data;
7338 		int idx;
7339 
7340 		if (sec_desc->sec_type != SEC_RELO)
7341 			continue;
7342 
7343 		shdr = sec_desc->shdr;
7344 		data = sec_desc->data;
7345 		idx = shdr->sh_info;
7346 
7347 		if (shdr->sh_type != SHT_REL || idx < 0 || idx >= obj->efile.sec_cnt) {
7348 			pr_warn("internal error at %d\n", __LINE__);
7349 			return -LIBBPF_ERRNO__INTERNAL;
7350 		}
7351 
7352 		if (obj->efile.secs[idx].sec_type == SEC_ST_OPS)
7353 			err = bpf_object__collect_st_ops_relos(obj, shdr, data);
7354 		else if (idx == obj->efile.btf_maps_shndx)
7355 			err = bpf_object__collect_map_relos(obj, shdr, data);
7356 		else
7357 			err = bpf_object__collect_prog_relos(obj, shdr, data);
7358 		if (err)
7359 			return err;
7360 	}
7361 
7362 	bpf_object__sort_relos(obj);
7363 	return 0;
7364 }
7365 
7366 static bool insn_is_helper_call(struct bpf_insn *insn, enum bpf_func_id *func_id)
7367 {
7368 	if (BPF_CLASS(insn->code) == BPF_JMP &&
7369 	    BPF_OP(insn->code) == BPF_CALL &&
7370 	    BPF_SRC(insn->code) == BPF_K &&
7371 	    insn->src_reg == 0 &&
7372 	    insn->dst_reg == 0) {
7373 		    *func_id = insn->imm;
7374 		    return true;
7375 	}
7376 	return false;
7377 }
7378 
7379 static int bpf_object__sanitize_prog(struct bpf_object *obj, struct bpf_program *prog)
7380 {
7381 	struct bpf_insn *insn = prog->insns;
7382 	enum bpf_func_id func_id;
7383 	int i;
7384 
7385 	if (obj->gen_loader)
7386 		return 0;
7387 
7388 	for (i = 0; i < prog->insns_cnt; i++, insn++) {
7389 		if (!insn_is_helper_call(insn, &func_id))
7390 			continue;
7391 
7392 		/* on kernels that don't yet support
7393 		 * bpf_probe_read_{kernel,user}[_str] helpers, fall back
7394 		 * to bpf_probe_read() which works well for old kernels
7395 		 */
7396 		switch (func_id) {
7397 		case BPF_FUNC_probe_read_kernel:
7398 		case BPF_FUNC_probe_read_user:
7399 			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
7400 				insn->imm = BPF_FUNC_probe_read;
7401 			break;
7402 		case BPF_FUNC_probe_read_kernel_str:
7403 		case BPF_FUNC_probe_read_user_str:
7404 			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
7405 				insn->imm = BPF_FUNC_probe_read_str;
7406 			break;
7407 		default:
7408 			break;
7409 		}
7410 	}
7411 	return 0;
7412 }
7413 
7414 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
7415 				     int *btf_obj_fd, int *btf_type_id);
7416 
7417 /* this is called as prog->sec_def->prog_prepare_load_fn for libbpf-supported sec_defs */
7418 static int libbpf_prepare_prog_load(struct bpf_program *prog,
7419 				    struct bpf_prog_load_opts *opts, long cookie)
7420 {
7421 	enum sec_def_flags def = cookie;
7422 
7423 	/* old kernels might not support specifying expected_attach_type */
7424 	if ((def & SEC_EXP_ATTACH_OPT) && !kernel_supports(prog->obj, FEAT_EXP_ATTACH_TYPE))
7425 		opts->expected_attach_type = 0;
7426 
7427 	if (def & SEC_SLEEPABLE)
7428 		opts->prog_flags |= BPF_F_SLEEPABLE;
7429 
7430 	if (prog->type == BPF_PROG_TYPE_XDP && (def & SEC_XDP_FRAGS))
7431 		opts->prog_flags |= BPF_F_XDP_HAS_FRAGS;
7432 
7433 	/* special check for usdt to use uprobe_multi link */
7434 	if ((def & SEC_USDT) && kernel_supports(prog->obj, FEAT_UPROBE_MULTI_LINK)) {
7435 		/* for BPF_TRACE_UPROBE_MULTI, user might want to query expected_attach_type
7436 		 * in prog, and expected_attach_type we set in kernel is from opts, so we
7437 		 * update both.
7438 		 */
7439 		prog->expected_attach_type = BPF_TRACE_UPROBE_MULTI;
7440 		opts->expected_attach_type = BPF_TRACE_UPROBE_MULTI;
7441 	}
7442 
7443 	if ((def & SEC_ATTACH_BTF) && !prog->attach_btf_id) {
7444 		int btf_obj_fd = 0, btf_type_id = 0, err;
7445 		const char *attach_name;
7446 
7447 		attach_name = strchr(prog->sec_name, '/');
7448 		if (!attach_name) {
7449 			/* if BPF program is annotated with just SEC("fentry")
7450 			 * (or similar) without declaratively specifying
7451 			 * target, then it is expected that target will be
7452 			 * specified with bpf_program__set_attach_target() at
7453 			 * runtime before BPF object load step. If not, then
7454 			 * there is nothing to load into the kernel as BPF
7455 			 * verifier won't be able to validate BPF program
7456 			 * correctness anyways.
7457 			 */
7458 			pr_warn("prog '%s': no BTF-based attach target is specified, use bpf_program__set_attach_target()\n",
7459 				prog->name);
7460 			return -EINVAL;
7461 		}
7462 		attach_name++; /* skip over / */
7463 
7464 		err = libbpf_find_attach_btf_id(prog, attach_name, &btf_obj_fd, &btf_type_id);
7465 		if (err)
7466 			return err;
7467 
7468 		/* cache resolved BTF FD and BTF type ID in the prog */
7469 		prog->attach_btf_obj_fd = btf_obj_fd;
7470 		prog->attach_btf_id = btf_type_id;
7471 
7472 		/* but by now libbpf common logic is not utilizing
7473 		 * prog->atach_btf_obj_fd/prog->attach_btf_id anymore because
7474 		 * this callback is called after opts were populated by
7475 		 * libbpf, so this callback has to update opts explicitly here
7476 		 */
7477 		opts->attach_btf_obj_fd = btf_obj_fd;
7478 		opts->attach_btf_id = btf_type_id;
7479 	}
7480 	return 0;
7481 }
7482 
7483 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz);
7484 
7485 static int bpf_object_load_prog(struct bpf_object *obj, struct bpf_program *prog,
7486 				struct bpf_insn *insns, int insns_cnt,
7487 				const char *license, __u32 kern_version, int *prog_fd)
7488 {
7489 	LIBBPF_OPTS(bpf_prog_load_opts, load_attr);
7490 	const char *prog_name = NULL;
7491 	size_t log_buf_size = 0;
7492 	char *log_buf = NULL, *tmp;
7493 	bool own_log_buf = true;
7494 	__u32 log_level = prog->log_level;
7495 	int ret, err;
7496 
7497 	/* Be more helpful by rejecting programs that can't be validated early
7498 	 * with more meaningful and actionable error message.
7499 	 */
7500 	switch (prog->type) {
7501 	case BPF_PROG_TYPE_UNSPEC:
7502 		/*
7503 		 * The program type must be set.  Most likely we couldn't find a proper
7504 		 * section definition at load time, and thus we didn't infer the type.
7505 		 */
7506 		pr_warn("prog '%s': missing BPF prog type, check ELF section name '%s'\n",
7507 			prog->name, prog->sec_name);
7508 		return -EINVAL;
7509 	case BPF_PROG_TYPE_STRUCT_OPS:
7510 		if (prog->attach_btf_id == 0) {
7511 			pr_warn("prog '%s': SEC(\"struct_ops\") program isn't referenced anywhere, did you forget to use it?\n",
7512 				prog->name);
7513 			return -EINVAL;
7514 		}
7515 		break;
7516 	default:
7517 		break;
7518 	}
7519 
7520 	if (!insns || !insns_cnt)
7521 		return -EINVAL;
7522 
7523 	if (kernel_supports(obj, FEAT_PROG_NAME))
7524 		prog_name = prog->name;
7525 	load_attr.attach_prog_fd = prog->attach_prog_fd;
7526 	load_attr.attach_btf_obj_fd = prog->attach_btf_obj_fd;
7527 	load_attr.attach_btf_id = prog->attach_btf_id;
7528 	load_attr.kern_version = kern_version;
7529 	load_attr.prog_ifindex = prog->prog_ifindex;
7530 	load_attr.expected_attach_type = prog->expected_attach_type;
7531 
7532 	/* specify func_info/line_info only if kernel supports them */
7533 	if (obj->btf && btf__fd(obj->btf) >= 0 && kernel_supports(obj, FEAT_BTF_FUNC)) {
7534 		load_attr.prog_btf_fd = btf__fd(obj->btf);
7535 		load_attr.func_info = prog->func_info;
7536 		load_attr.func_info_rec_size = prog->func_info_rec_size;
7537 		load_attr.func_info_cnt = prog->func_info_cnt;
7538 		load_attr.line_info = prog->line_info;
7539 		load_attr.line_info_rec_size = prog->line_info_rec_size;
7540 		load_attr.line_info_cnt = prog->line_info_cnt;
7541 	}
7542 	load_attr.log_level = log_level;
7543 	load_attr.prog_flags = prog->prog_flags;
7544 	load_attr.fd_array = obj->fd_array;
7545 
7546 	load_attr.token_fd = obj->token_fd;
7547 	if (obj->token_fd)
7548 		load_attr.prog_flags |= BPF_F_TOKEN_FD;
7549 
7550 	/* adjust load_attr if sec_def provides custom preload callback */
7551 	if (prog->sec_def && prog->sec_def->prog_prepare_load_fn) {
7552 		err = prog->sec_def->prog_prepare_load_fn(prog, &load_attr, prog->sec_def->cookie);
7553 		if (err < 0) {
7554 			pr_warn("prog '%s': failed to prepare load attributes: %s\n",
7555 				prog->name, errstr(err));
7556 			return err;
7557 		}
7558 		insns = prog->insns;
7559 		insns_cnt = prog->insns_cnt;
7560 	}
7561 
7562 	if (obj->gen_loader) {
7563 		bpf_gen__prog_load(obj->gen_loader, prog->type, prog->name,
7564 				   license, insns, insns_cnt, &load_attr,
7565 				   prog - obj->programs);
7566 		*prog_fd = -1;
7567 		return 0;
7568 	}
7569 
7570 retry_load:
7571 	/* if log_level is zero, we don't request logs initially even if
7572 	 * custom log_buf is specified; if the program load fails, then we'll
7573 	 * bump log_level to 1 and use either custom log_buf or we'll allocate
7574 	 * our own and retry the load to get details on what failed
7575 	 */
7576 	if (log_level) {
7577 		if (prog->log_buf) {
7578 			log_buf = prog->log_buf;
7579 			log_buf_size = prog->log_size;
7580 			own_log_buf = false;
7581 		} else if (obj->log_buf) {
7582 			log_buf = obj->log_buf;
7583 			log_buf_size = obj->log_size;
7584 			own_log_buf = false;
7585 		} else {
7586 			log_buf_size = max((size_t)BPF_LOG_BUF_SIZE, log_buf_size * 2);
7587 			tmp = realloc(log_buf, log_buf_size);
7588 			if (!tmp) {
7589 				ret = -ENOMEM;
7590 				goto out;
7591 			}
7592 			log_buf = tmp;
7593 			log_buf[0] = '\0';
7594 			own_log_buf = true;
7595 		}
7596 	}
7597 
7598 	load_attr.log_buf = log_buf;
7599 	load_attr.log_size = log_buf_size;
7600 	load_attr.log_level = log_level;
7601 
7602 	ret = bpf_prog_load(prog->type, prog_name, license, insns, insns_cnt, &load_attr);
7603 	if (ret >= 0) {
7604 		if (log_level && own_log_buf) {
7605 			pr_debug("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
7606 				 prog->name, log_buf);
7607 		}
7608 
7609 		if (obj->has_rodata && kernel_supports(obj, FEAT_PROG_BIND_MAP)) {
7610 			struct bpf_map *map;
7611 			int i;
7612 
7613 			for (i = 0; i < obj->nr_maps; i++) {
7614 				map = &prog->obj->maps[i];
7615 				if (map->libbpf_type != LIBBPF_MAP_RODATA)
7616 					continue;
7617 
7618 				if (bpf_prog_bind_map(ret, map->fd, NULL)) {
7619 					pr_warn("prog '%s': failed to bind map '%s': %s\n",
7620 						prog->name, map->real_name, errstr(errno));
7621 					/* Don't fail hard if can't bind rodata. */
7622 				}
7623 			}
7624 		}
7625 
7626 		*prog_fd = ret;
7627 		ret = 0;
7628 		goto out;
7629 	}
7630 
7631 	if (log_level == 0) {
7632 		log_level = 1;
7633 		goto retry_load;
7634 	}
7635 	/* On ENOSPC, increase log buffer size and retry, unless custom
7636 	 * log_buf is specified.
7637 	 * Be careful to not overflow u32, though. Kernel's log buf size limit
7638 	 * isn't part of UAPI so it can always be bumped to full 4GB. So don't
7639 	 * multiply by 2 unless we are sure we'll fit within 32 bits.
7640 	 * Currently, we'll get -EINVAL when we reach (UINT_MAX >> 2).
7641 	 */
7642 	if (own_log_buf && errno == ENOSPC && log_buf_size <= UINT_MAX / 2)
7643 		goto retry_load;
7644 
7645 	ret = -errno;
7646 
7647 	/* post-process verifier log to improve error descriptions */
7648 	fixup_verifier_log(prog, log_buf, log_buf_size);
7649 
7650 	pr_warn("prog '%s': BPF program load failed: %s\n", prog->name, errstr(errno));
7651 	pr_perm_msg(ret);
7652 
7653 	if (own_log_buf && log_buf && log_buf[0] != '\0') {
7654 		pr_warn("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
7655 			prog->name, log_buf);
7656 	}
7657 
7658 out:
7659 	if (own_log_buf)
7660 		free(log_buf);
7661 	return ret;
7662 }
7663 
7664 static char *find_prev_line(char *buf, char *cur)
7665 {
7666 	char *p;
7667 
7668 	if (cur == buf) /* end of a log buf */
7669 		return NULL;
7670 
7671 	p = cur - 1;
7672 	while (p - 1 >= buf && *(p - 1) != '\n')
7673 		p--;
7674 
7675 	return p;
7676 }
7677 
7678 static void patch_log(char *buf, size_t buf_sz, size_t log_sz,
7679 		      char *orig, size_t orig_sz, const char *patch)
7680 {
7681 	/* size of the remaining log content to the right from the to-be-replaced part */
7682 	size_t rem_sz = (buf + log_sz) - (orig + orig_sz);
7683 	size_t patch_sz = strlen(patch);
7684 
7685 	if (patch_sz != orig_sz) {
7686 		/* If patch line(s) are longer than original piece of verifier log,
7687 		 * shift log contents by (patch_sz - orig_sz) bytes to the right
7688 		 * starting from after to-be-replaced part of the log.
7689 		 *
7690 		 * If patch line(s) are shorter than original piece of verifier log,
7691 		 * shift log contents by (orig_sz - patch_sz) bytes to the left
7692 		 * starting from after to-be-replaced part of the log
7693 		 *
7694 		 * We need to be careful about not overflowing available
7695 		 * buf_sz capacity. If that's the case, we'll truncate the end
7696 		 * of the original log, as necessary.
7697 		 */
7698 		if (patch_sz > orig_sz) {
7699 			if (orig + patch_sz >= buf + buf_sz) {
7700 				/* patch is big enough to cover remaining space completely */
7701 				patch_sz -= (orig + patch_sz) - (buf + buf_sz) + 1;
7702 				rem_sz = 0;
7703 			} else if (patch_sz - orig_sz > buf_sz - log_sz) {
7704 				/* patch causes part of remaining log to be truncated */
7705 				rem_sz -= (patch_sz - orig_sz) - (buf_sz - log_sz);
7706 			}
7707 		}
7708 		/* shift remaining log to the right by calculated amount */
7709 		memmove(orig + patch_sz, orig + orig_sz, rem_sz);
7710 	}
7711 
7712 	memcpy(orig, patch, patch_sz);
7713 }
7714 
7715 static void fixup_log_failed_core_relo(struct bpf_program *prog,
7716 				       char *buf, size_t buf_sz, size_t log_sz,
7717 				       char *line1, char *line2, char *line3)
7718 {
7719 	/* Expected log for failed and not properly guarded CO-RE relocation:
7720 	 * line1 -> 123: (85) call unknown#195896080
7721 	 * line2 -> invalid func unknown#195896080
7722 	 * line3 -> <anything else or end of buffer>
7723 	 *
7724 	 * "123" is the index of the instruction that was poisoned. We extract
7725 	 * instruction index to find corresponding CO-RE relocation and
7726 	 * replace this part of the log with more relevant information about
7727 	 * failed CO-RE relocation.
7728 	 */
7729 	const struct bpf_core_relo *relo;
7730 	struct bpf_core_spec spec;
7731 	char patch[512], spec_buf[256];
7732 	int insn_idx, err, spec_len;
7733 
7734 	if (sscanf(line1, "%d: (%*d) call unknown#195896080\n", &insn_idx) != 1)
7735 		return;
7736 
7737 	relo = find_relo_core(prog, insn_idx);
7738 	if (!relo)
7739 		return;
7740 
7741 	err = bpf_core_parse_spec(prog->name, prog->obj->btf, relo, &spec);
7742 	if (err)
7743 		return;
7744 
7745 	spec_len = bpf_core_format_spec(spec_buf, sizeof(spec_buf), &spec);
7746 	snprintf(patch, sizeof(patch),
7747 		 "%d: <invalid CO-RE relocation>\n"
7748 		 "failed to resolve CO-RE relocation %s%s\n",
7749 		 insn_idx, spec_buf, spec_len >= sizeof(spec_buf) ? "..." : "");
7750 
7751 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7752 }
7753 
7754 static void fixup_log_missing_map_load(struct bpf_program *prog,
7755 				       char *buf, size_t buf_sz, size_t log_sz,
7756 				       char *line1, char *line2, char *line3)
7757 {
7758 	/* Expected log for failed and not properly guarded map reference:
7759 	 * line1 -> 123: (85) call unknown#2001000345
7760 	 * line2 -> invalid func unknown#2001000345
7761 	 * line3 -> <anything else or end of buffer>
7762 	 *
7763 	 * "123" is the index of the instruction that was poisoned.
7764 	 * "345" in "2001000345" is a map index in obj->maps to fetch map name.
7765 	 */
7766 	struct bpf_object *obj = prog->obj;
7767 	const struct bpf_map *map;
7768 	int insn_idx, map_idx;
7769 	char patch[128];
7770 
7771 	if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &map_idx) != 2)
7772 		return;
7773 
7774 	map_idx -= POISON_LDIMM64_MAP_BASE;
7775 	if (map_idx < 0 || map_idx >= obj->nr_maps)
7776 		return;
7777 	map = &obj->maps[map_idx];
7778 
7779 	snprintf(patch, sizeof(patch),
7780 		 "%d: <invalid BPF map reference>\n"
7781 		 "BPF map '%s' is referenced but wasn't created\n",
7782 		 insn_idx, map->name);
7783 
7784 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7785 }
7786 
7787 static void fixup_log_missing_kfunc_call(struct bpf_program *prog,
7788 					 char *buf, size_t buf_sz, size_t log_sz,
7789 					 char *line1, char *line2, char *line3)
7790 {
7791 	/* Expected log for failed and not properly guarded kfunc call:
7792 	 * line1 -> 123: (85) call unknown#2002000345
7793 	 * line2 -> invalid func unknown#2002000345
7794 	 * line3 -> <anything else or end of buffer>
7795 	 *
7796 	 * "123" is the index of the instruction that was poisoned.
7797 	 * "345" in "2002000345" is an extern index in obj->externs to fetch kfunc name.
7798 	 */
7799 	struct bpf_object *obj = prog->obj;
7800 	const struct extern_desc *ext;
7801 	int insn_idx, ext_idx;
7802 	char patch[128];
7803 
7804 	if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &ext_idx) != 2)
7805 		return;
7806 
7807 	ext_idx -= POISON_CALL_KFUNC_BASE;
7808 	if (ext_idx < 0 || ext_idx >= obj->nr_extern)
7809 		return;
7810 	ext = &obj->externs[ext_idx];
7811 
7812 	snprintf(patch, sizeof(patch),
7813 		 "%d: <invalid kfunc call>\n"
7814 		 "kfunc '%s' is referenced but wasn't resolved\n",
7815 		 insn_idx, ext->name);
7816 
7817 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7818 }
7819 
7820 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz)
7821 {
7822 	/* look for familiar error patterns in last N lines of the log */
7823 	const size_t max_last_line_cnt = 10;
7824 	char *prev_line, *cur_line, *next_line;
7825 	size_t log_sz;
7826 	int i;
7827 
7828 	if (!buf)
7829 		return;
7830 
7831 	log_sz = strlen(buf) + 1;
7832 	next_line = buf + log_sz - 1;
7833 
7834 	for (i = 0; i < max_last_line_cnt; i++, next_line = cur_line) {
7835 		cur_line = find_prev_line(buf, next_line);
7836 		if (!cur_line)
7837 			return;
7838 
7839 		if (str_has_pfx(cur_line, "invalid func unknown#195896080\n")) {
7840 			prev_line = find_prev_line(buf, cur_line);
7841 			if (!prev_line)
7842 				continue;
7843 
7844 			/* failed CO-RE relocation case */
7845 			fixup_log_failed_core_relo(prog, buf, buf_sz, log_sz,
7846 						   prev_line, cur_line, next_line);
7847 			return;
7848 		} else if (str_has_pfx(cur_line, "invalid func unknown#"POISON_LDIMM64_MAP_PFX)) {
7849 			prev_line = find_prev_line(buf, cur_line);
7850 			if (!prev_line)
7851 				continue;
7852 
7853 			/* reference to uncreated BPF map */
7854 			fixup_log_missing_map_load(prog, buf, buf_sz, log_sz,
7855 						   prev_line, cur_line, next_line);
7856 			return;
7857 		} else if (str_has_pfx(cur_line, "invalid func unknown#"POISON_CALL_KFUNC_PFX)) {
7858 			prev_line = find_prev_line(buf, cur_line);
7859 			if (!prev_line)
7860 				continue;
7861 
7862 			/* reference to unresolved kfunc */
7863 			fixup_log_missing_kfunc_call(prog, buf, buf_sz, log_sz,
7864 						     prev_line, cur_line, next_line);
7865 			return;
7866 		}
7867 	}
7868 }
7869 
7870 static int bpf_program_record_relos(struct bpf_program *prog)
7871 {
7872 	struct bpf_object *obj = prog->obj;
7873 	int i;
7874 
7875 	for (i = 0; i < prog->nr_reloc; i++) {
7876 		struct reloc_desc *relo = &prog->reloc_desc[i];
7877 		struct extern_desc *ext = &obj->externs[relo->ext_idx];
7878 		int kind;
7879 
7880 		switch (relo->type) {
7881 		case RELO_EXTERN_LD64:
7882 			if (ext->type != EXT_KSYM)
7883 				continue;
7884 			kind = btf_is_var(btf__type_by_id(obj->btf, ext->btf_id)) ?
7885 				BTF_KIND_VAR : BTF_KIND_FUNC;
7886 			bpf_gen__record_extern(obj->gen_loader, ext->name,
7887 					       ext->is_weak, !ext->ksym.type_id,
7888 					       true, kind, relo->insn_idx);
7889 			break;
7890 		case RELO_EXTERN_CALL:
7891 			bpf_gen__record_extern(obj->gen_loader, ext->name,
7892 					       ext->is_weak, false, false, BTF_KIND_FUNC,
7893 					       relo->insn_idx);
7894 			break;
7895 		case RELO_CORE: {
7896 			struct bpf_core_relo cr = {
7897 				.insn_off = relo->insn_idx * 8,
7898 				.type_id = relo->core_relo->type_id,
7899 				.access_str_off = relo->core_relo->access_str_off,
7900 				.kind = relo->core_relo->kind,
7901 			};
7902 
7903 			bpf_gen__record_relo_core(obj->gen_loader, &cr);
7904 			break;
7905 		}
7906 		default:
7907 			continue;
7908 		}
7909 	}
7910 	return 0;
7911 }
7912 
7913 static int
7914 bpf_object__load_progs(struct bpf_object *obj, int log_level)
7915 {
7916 	struct bpf_program *prog;
7917 	size_t i;
7918 	int err;
7919 
7920 	for (i = 0; i < obj->nr_programs; i++) {
7921 		prog = &obj->programs[i];
7922 		if (prog_is_subprog(obj, prog))
7923 			continue;
7924 		if (!prog->autoload) {
7925 			pr_debug("prog '%s': skipped loading\n", prog->name);
7926 			continue;
7927 		}
7928 		prog->log_level |= log_level;
7929 
7930 		if (obj->gen_loader)
7931 			bpf_program_record_relos(prog);
7932 
7933 		err = bpf_object_load_prog(obj, prog, prog->insns, prog->insns_cnt,
7934 					   obj->license, obj->kern_version, &prog->fd);
7935 		if (err) {
7936 			pr_warn("prog '%s': failed to load: %s\n", prog->name, errstr(err));
7937 			return err;
7938 		}
7939 	}
7940 
7941 	bpf_object__free_relocs(obj);
7942 	return 0;
7943 }
7944 
7945 static int bpf_object_prepare_progs(struct bpf_object *obj)
7946 {
7947 	struct bpf_program *prog;
7948 	size_t i;
7949 	int err;
7950 
7951 	for (i = 0; i < obj->nr_programs; i++) {
7952 		prog = &obj->programs[i];
7953 		err = bpf_object__sanitize_prog(obj, prog);
7954 		if (err)
7955 			return err;
7956 	}
7957 	return 0;
7958 }
7959 
7960 static const struct bpf_sec_def *find_sec_def(const char *sec_name);
7961 
7962 static int bpf_object_init_progs(struct bpf_object *obj, const struct bpf_object_open_opts *opts)
7963 {
7964 	struct bpf_program *prog;
7965 	int err;
7966 
7967 	bpf_object__for_each_program(prog, obj) {
7968 		prog->sec_def = find_sec_def(prog->sec_name);
7969 		if (!prog->sec_def) {
7970 			/* couldn't guess, but user might manually specify */
7971 			pr_debug("prog '%s': unrecognized ELF section name '%s'\n",
7972 				prog->name, prog->sec_name);
7973 			continue;
7974 		}
7975 
7976 		prog->type = prog->sec_def->prog_type;
7977 		prog->expected_attach_type = prog->sec_def->expected_attach_type;
7978 
7979 		/* sec_def can have custom callback which should be called
7980 		 * after bpf_program is initialized to adjust its properties
7981 		 */
7982 		if (prog->sec_def->prog_setup_fn) {
7983 			err = prog->sec_def->prog_setup_fn(prog, prog->sec_def->cookie);
7984 			if (err < 0) {
7985 				pr_warn("prog '%s': failed to initialize: %s\n",
7986 					prog->name, errstr(err));
7987 				return err;
7988 			}
7989 		}
7990 	}
7991 
7992 	return 0;
7993 }
7994 
7995 static struct bpf_object *bpf_object_open(const char *path, const void *obj_buf, size_t obj_buf_sz,
7996 					  const char *obj_name,
7997 					  const struct bpf_object_open_opts *opts)
7998 {
7999 	const char *kconfig, *btf_tmp_path, *token_path;
8000 	struct bpf_object *obj;
8001 	int err;
8002 	char *log_buf;
8003 	size_t log_size;
8004 	__u32 log_level;
8005 
8006 	if (obj_buf && !obj_name)
8007 		return ERR_PTR(-EINVAL);
8008 
8009 	if (elf_version(EV_CURRENT) == EV_NONE) {
8010 		pr_warn("failed to init libelf for %s\n",
8011 			path ? : "(mem buf)");
8012 		return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
8013 	}
8014 
8015 	if (!OPTS_VALID(opts, bpf_object_open_opts))
8016 		return ERR_PTR(-EINVAL);
8017 
8018 	obj_name = OPTS_GET(opts, object_name, NULL) ?: obj_name;
8019 	if (obj_buf) {
8020 		path = obj_name;
8021 		pr_debug("loading object '%s' from buffer\n", obj_name);
8022 	} else {
8023 		pr_debug("loading object from %s\n", path);
8024 	}
8025 
8026 	log_buf = OPTS_GET(opts, kernel_log_buf, NULL);
8027 	log_size = OPTS_GET(opts, kernel_log_size, 0);
8028 	log_level = OPTS_GET(opts, kernel_log_level, 0);
8029 	if (log_size > UINT_MAX)
8030 		return ERR_PTR(-EINVAL);
8031 	if (log_size && !log_buf)
8032 		return ERR_PTR(-EINVAL);
8033 
8034 	token_path = OPTS_GET(opts, bpf_token_path, NULL);
8035 	/* if user didn't specify bpf_token_path explicitly, check if
8036 	 * LIBBPF_BPF_TOKEN_PATH envvar was set and treat it as bpf_token_path
8037 	 * option
8038 	 */
8039 	if (!token_path)
8040 		token_path = getenv("LIBBPF_BPF_TOKEN_PATH");
8041 	if (token_path && strlen(token_path) >= PATH_MAX)
8042 		return ERR_PTR(-ENAMETOOLONG);
8043 
8044 	obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
8045 	if (IS_ERR(obj))
8046 		return obj;
8047 
8048 	obj->log_buf = log_buf;
8049 	obj->log_size = log_size;
8050 	obj->log_level = log_level;
8051 
8052 	if (token_path) {
8053 		obj->token_path = strdup(token_path);
8054 		if (!obj->token_path) {
8055 			err = -ENOMEM;
8056 			goto out;
8057 		}
8058 	}
8059 
8060 	btf_tmp_path = OPTS_GET(opts, btf_custom_path, NULL);
8061 	if (btf_tmp_path) {
8062 		if (strlen(btf_tmp_path) >= PATH_MAX) {
8063 			err = -ENAMETOOLONG;
8064 			goto out;
8065 		}
8066 		obj->btf_custom_path = strdup(btf_tmp_path);
8067 		if (!obj->btf_custom_path) {
8068 			err = -ENOMEM;
8069 			goto out;
8070 		}
8071 	}
8072 
8073 	kconfig = OPTS_GET(opts, kconfig, NULL);
8074 	if (kconfig) {
8075 		obj->kconfig = strdup(kconfig);
8076 		if (!obj->kconfig) {
8077 			err = -ENOMEM;
8078 			goto out;
8079 		}
8080 	}
8081 
8082 	err = bpf_object__elf_init(obj);
8083 	err = err ? : bpf_object__elf_collect(obj);
8084 	err = err ? : bpf_object__collect_externs(obj);
8085 	err = err ? : bpf_object_fixup_btf(obj);
8086 	err = err ? : bpf_object__init_maps(obj, opts);
8087 	err = err ? : bpf_object_init_progs(obj, opts);
8088 	err = err ? : bpf_object__collect_relos(obj);
8089 	if (err)
8090 		goto out;
8091 
8092 	bpf_object__elf_finish(obj);
8093 
8094 	return obj;
8095 out:
8096 	bpf_object__close(obj);
8097 	return ERR_PTR(err);
8098 }
8099 
8100 struct bpf_object *
8101 bpf_object__open_file(const char *path, const struct bpf_object_open_opts *opts)
8102 {
8103 	if (!path)
8104 		return libbpf_err_ptr(-EINVAL);
8105 
8106 	return libbpf_ptr(bpf_object_open(path, NULL, 0, NULL, opts));
8107 }
8108 
8109 struct bpf_object *bpf_object__open(const char *path)
8110 {
8111 	return bpf_object__open_file(path, NULL);
8112 }
8113 
8114 struct bpf_object *
8115 bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
8116 		     const struct bpf_object_open_opts *opts)
8117 {
8118 	char tmp_name[64];
8119 
8120 	if (!obj_buf || obj_buf_sz == 0)
8121 		return libbpf_err_ptr(-EINVAL);
8122 
8123 	/* create a (quite useless) default "name" for this memory buffer object */
8124 	snprintf(tmp_name, sizeof(tmp_name), "%lx-%zx", (unsigned long)obj_buf, obj_buf_sz);
8125 
8126 	return libbpf_ptr(bpf_object_open(NULL, obj_buf, obj_buf_sz, tmp_name, opts));
8127 }
8128 
8129 static int bpf_object_unload(struct bpf_object *obj)
8130 {
8131 	size_t i;
8132 
8133 	if (!obj)
8134 		return libbpf_err(-EINVAL);
8135 
8136 	for (i = 0; i < obj->nr_maps; i++) {
8137 		zclose(obj->maps[i].fd);
8138 		if (obj->maps[i].st_ops)
8139 			zfree(&obj->maps[i].st_ops->kern_vdata);
8140 	}
8141 
8142 	for (i = 0; i < obj->nr_programs; i++)
8143 		bpf_program__unload(&obj->programs[i]);
8144 
8145 	return 0;
8146 }
8147 
8148 static int bpf_object__sanitize_maps(struct bpf_object *obj)
8149 {
8150 	struct bpf_map *m;
8151 
8152 	bpf_object__for_each_map(m, obj) {
8153 		if (!bpf_map__is_internal(m))
8154 			continue;
8155 		if (!kernel_supports(obj, FEAT_ARRAY_MMAP))
8156 			m->def.map_flags &= ~BPF_F_MMAPABLE;
8157 	}
8158 
8159 	return 0;
8160 }
8161 
8162 typedef int (*kallsyms_cb_t)(unsigned long long sym_addr, char sym_type,
8163 			     const char *sym_name, void *ctx);
8164 
8165 static int libbpf_kallsyms_parse(kallsyms_cb_t cb, void *ctx)
8166 {
8167 	char sym_type, sym_name[500];
8168 	unsigned long long sym_addr;
8169 	int ret, err = 0;
8170 	FILE *f;
8171 
8172 	f = fopen("/proc/kallsyms", "re");
8173 	if (!f) {
8174 		err = -errno;
8175 		pr_warn("failed to open /proc/kallsyms: %s\n", errstr(err));
8176 		return err;
8177 	}
8178 
8179 	while (true) {
8180 		ret = fscanf(f, "%llx %c %499s%*[^\n]\n",
8181 			     &sym_addr, &sym_type, sym_name);
8182 		if (ret == EOF && feof(f))
8183 			break;
8184 		if (ret != 3) {
8185 			pr_warn("failed to read kallsyms entry: %d\n", ret);
8186 			err = -EINVAL;
8187 			break;
8188 		}
8189 
8190 		err = cb(sym_addr, sym_type, sym_name, ctx);
8191 		if (err)
8192 			break;
8193 	}
8194 
8195 	fclose(f);
8196 	return err;
8197 }
8198 
8199 static int kallsyms_cb(unsigned long long sym_addr, char sym_type,
8200 		       const char *sym_name, void *ctx)
8201 {
8202 	struct bpf_object *obj = ctx;
8203 	const struct btf_type *t;
8204 	struct extern_desc *ext;
8205 	char *res;
8206 
8207 	res = strstr(sym_name, ".llvm.");
8208 	if (sym_type == 'd' && res)
8209 		ext = find_extern_by_name_with_len(obj, sym_name, res - sym_name);
8210 	else
8211 		ext = find_extern_by_name(obj, sym_name);
8212 	if (!ext || ext->type != EXT_KSYM)
8213 		return 0;
8214 
8215 	t = btf__type_by_id(obj->btf, ext->btf_id);
8216 	if (!btf_is_var(t))
8217 		return 0;
8218 
8219 	if (ext->is_set && ext->ksym.addr != sym_addr) {
8220 		pr_warn("extern (ksym) '%s': resolution is ambiguous: 0x%llx or 0x%llx\n",
8221 			sym_name, ext->ksym.addr, sym_addr);
8222 		return -EINVAL;
8223 	}
8224 	if (!ext->is_set) {
8225 		ext->is_set = true;
8226 		ext->ksym.addr = sym_addr;
8227 		pr_debug("extern (ksym) '%s': set to 0x%llx\n", sym_name, sym_addr);
8228 	}
8229 	return 0;
8230 }
8231 
8232 static int bpf_object__read_kallsyms_file(struct bpf_object *obj)
8233 {
8234 	return libbpf_kallsyms_parse(kallsyms_cb, obj);
8235 }
8236 
8237 static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
8238 			    __u16 kind, struct btf **res_btf,
8239 			    struct module_btf **res_mod_btf)
8240 {
8241 	struct module_btf *mod_btf;
8242 	struct btf *btf;
8243 	int i, id, err;
8244 
8245 	btf = obj->btf_vmlinux;
8246 	mod_btf = NULL;
8247 	id = btf__find_by_name_kind(btf, ksym_name, kind);
8248 
8249 	if (id == -ENOENT) {
8250 		err = load_module_btfs(obj);
8251 		if (err)
8252 			return err;
8253 
8254 		for (i = 0; i < obj->btf_module_cnt; i++) {
8255 			/* we assume module_btf's BTF FD is always >0 */
8256 			mod_btf = &obj->btf_modules[i];
8257 			btf = mod_btf->btf;
8258 			id = btf__find_by_name_kind_own(btf, ksym_name, kind);
8259 			if (id != -ENOENT)
8260 				break;
8261 		}
8262 	}
8263 	if (id <= 0)
8264 		return -ESRCH;
8265 
8266 	*res_btf = btf;
8267 	*res_mod_btf = mod_btf;
8268 	return id;
8269 }
8270 
8271 static int bpf_object__resolve_ksym_var_btf_id(struct bpf_object *obj,
8272 					       struct extern_desc *ext)
8273 {
8274 	const struct btf_type *targ_var, *targ_type;
8275 	__u32 targ_type_id, local_type_id;
8276 	struct module_btf *mod_btf = NULL;
8277 	const char *targ_var_name;
8278 	struct btf *btf = NULL;
8279 	int id, err;
8280 
8281 	id = find_ksym_btf_id(obj, ext->name, BTF_KIND_VAR, &btf, &mod_btf);
8282 	if (id < 0) {
8283 		if (id == -ESRCH && ext->is_weak)
8284 			return 0;
8285 		pr_warn("extern (var ksym) '%s': not found in kernel BTF\n",
8286 			ext->name);
8287 		return id;
8288 	}
8289 
8290 	/* find local type_id */
8291 	local_type_id = ext->ksym.type_id;
8292 
8293 	/* find target type_id */
8294 	targ_var = btf__type_by_id(btf, id);
8295 	targ_var_name = btf__name_by_offset(btf, targ_var->name_off);
8296 	targ_type = skip_mods_and_typedefs(btf, targ_var->type, &targ_type_id);
8297 
8298 	err = bpf_core_types_are_compat(obj->btf, local_type_id,
8299 					btf, targ_type_id);
8300 	if (err <= 0) {
8301 		const struct btf_type *local_type;
8302 		const char *targ_name, *local_name;
8303 
8304 		local_type = btf__type_by_id(obj->btf, local_type_id);
8305 		local_name = btf__name_by_offset(obj->btf, local_type->name_off);
8306 		targ_name = btf__name_by_offset(btf, targ_type->name_off);
8307 
8308 		pr_warn("extern (var ksym) '%s': incompatible types, expected [%d] %s %s, but kernel has [%d] %s %s\n",
8309 			ext->name, local_type_id,
8310 			btf_kind_str(local_type), local_name, targ_type_id,
8311 			btf_kind_str(targ_type), targ_name);
8312 		return -EINVAL;
8313 	}
8314 
8315 	ext->is_set = true;
8316 	ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
8317 	ext->ksym.kernel_btf_id = id;
8318 	pr_debug("extern (var ksym) '%s': resolved to [%d] %s %s\n",
8319 		 ext->name, id, btf_kind_str(targ_var), targ_var_name);
8320 
8321 	return 0;
8322 }
8323 
8324 static int bpf_object__resolve_ksym_func_btf_id(struct bpf_object *obj,
8325 						struct extern_desc *ext)
8326 {
8327 	int local_func_proto_id, kfunc_proto_id, kfunc_id;
8328 	struct module_btf *mod_btf = NULL;
8329 	const struct btf_type *kern_func;
8330 	struct btf *kern_btf = NULL;
8331 	int ret;
8332 
8333 	local_func_proto_id = ext->ksym.type_id;
8334 
8335 	kfunc_id = find_ksym_btf_id(obj, ext->essent_name ?: ext->name, BTF_KIND_FUNC, &kern_btf,
8336 				    &mod_btf);
8337 	if (kfunc_id < 0) {
8338 		if (kfunc_id == -ESRCH && ext->is_weak)
8339 			return 0;
8340 		pr_warn("extern (func ksym) '%s': not found in kernel or module BTFs\n",
8341 			ext->name);
8342 		return kfunc_id;
8343 	}
8344 
8345 	kern_func = btf__type_by_id(kern_btf, kfunc_id);
8346 	kfunc_proto_id = kern_func->type;
8347 
8348 	ret = bpf_core_types_are_compat(obj->btf, local_func_proto_id,
8349 					kern_btf, kfunc_proto_id);
8350 	if (ret <= 0) {
8351 		if (ext->is_weak)
8352 			return 0;
8353 
8354 		pr_warn("extern (func ksym) '%s': func_proto [%d] incompatible with %s [%d]\n",
8355 			ext->name, local_func_proto_id,
8356 			mod_btf ? mod_btf->name : "vmlinux", kfunc_proto_id);
8357 		return -EINVAL;
8358 	}
8359 
8360 	/* set index for module BTF fd in fd_array, if unset */
8361 	if (mod_btf && !mod_btf->fd_array_idx) {
8362 		/* insn->off is s16 */
8363 		if (obj->fd_array_cnt == INT16_MAX) {
8364 			pr_warn("extern (func ksym) '%s': module BTF fd index %d too big to fit in bpf_insn offset\n",
8365 				ext->name, mod_btf->fd_array_idx);
8366 			return -E2BIG;
8367 		}
8368 		/* Cannot use index 0 for module BTF fd */
8369 		if (!obj->fd_array_cnt)
8370 			obj->fd_array_cnt = 1;
8371 
8372 		ret = libbpf_ensure_mem((void **)&obj->fd_array, &obj->fd_array_cap, sizeof(int),
8373 					obj->fd_array_cnt + 1);
8374 		if (ret)
8375 			return ret;
8376 		mod_btf->fd_array_idx = obj->fd_array_cnt;
8377 		/* we assume module BTF FD is always >0 */
8378 		obj->fd_array[obj->fd_array_cnt++] = mod_btf->fd;
8379 	}
8380 
8381 	ext->is_set = true;
8382 	ext->ksym.kernel_btf_id = kfunc_id;
8383 	ext->ksym.btf_fd_idx = mod_btf ? mod_btf->fd_array_idx : 0;
8384 	/* Also set kernel_btf_obj_fd to make sure that bpf_object__relocate_data()
8385 	 * populates FD into ld_imm64 insn when it's used to point to kfunc.
8386 	 * {kernel_btf_id, btf_fd_idx} -> fixup bpf_call.
8387 	 * {kernel_btf_id, kernel_btf_obj_fd} -> fixup ld_imm64.
8388 	 */
8389 	ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
8390 	pr_debug("extern (func ksym) '%s': resolved to %s [%d]\n",
8391 		 ext->name, mod_btf ? mod_btf->name : "vmlinux", kfunc_id);
8392 
8393 	return 0;
8394 }
8395 
8396 static int bpf_object__resolve_ksyms_btf_id(struct bpf_object *obj)
8397 {
8398 	const struct btf_type *t;
8399 	struct extern_desc *ext;
8400 	int i, err;
8401 
8402 	for (i = 0; i < obj->nr_extern; i++) {
8403 		ext = &obj->externs[i];
8404 		if (ext->type != EXT_KSYM || !ext->ksym.type_id)
8405 			continue;
8406 
8407 		if (obj->gen_loader) {
8408 			ext->is_set = true;
8409 			ext->ksym.kernel_btf_obj_fd = 0;
8410 			ext->ksym.kernel_btf_id = 0;
8411 			continue;
8412 		}
8413 		t = btf__type_by_id(obj->btf, ext->btf_id);
8414 		if (btf_is_var(t))
8415 			err = bpf_object__resolve_ksym_var_btf_id(obj, ext);
8416 		else
8417 			err = bpf_object__resolve_ksym_func_btf_id(obj, ext);
8418 		if (err)
8419 			return err;
8420 	}
8421 	return 0;
8422 }
8423 
8424 static int bpf_object__resolve_externs(struct bpf_object *obj,
8425 				       const char *extra_kconfig)
8426 {
8427 	bool need_config = false, need_kallsyms = false;
8428 	bool need_vmlinux_btf = false;
8429 	struct extern_desc *ext;
8430 	void *kcfg_data = NULL;
8431 	int err, i;
8432 
8433 	if (obj->nr_extern == 0)
8434 		return 0;
8435 
8436 	if (obj->kconfig_map_idx >= 0)
8437 		kcfg_data = obj->maps[obj->kconfig_map_idx].mmaped;
8438 
8439 	for (i = 0; i < obj->nr_extern; i++) {
8440 		ext = &obj->externs[i];
8441 
8442 		if (ext->type == EXT_KSYM) {
8443 			if (ext->ksym.type_id)
8444 				need_vmlinux_btf = true;
8445 			else
8446 				need_kallsyms = true;
8447 			continue;
8448 		} else if (ext->type == EXT_KCFG) {
8449 			void *ext_ptr = kcfg_data + ext->kcfg.data_off;
8450 			__u64 value = 0;
8451 
8452 			/* Kconfig externs need actual /proc/config.gz */
8453 			if (str_has_pfx(ext->name, "CONFIG_")) {
8454 				need_config = true;
8455 				continue;
8456 			}
8457 
8458 			/* Virtual kcfg externs are customly handled by libbpf */
8459 			if (strcmp(ext->name, "LINUX_KERNEL_VERSION") == 0) {
8460 				value = get_kernel_version();
8461 				if (!value) {
8462 					pr_warn("extern (kcfg) '%s': failed to get kernel version\n", ext->name);
8463 					return -EINVAL;
8464 				}
8465 			} else if (strcmp(ext->name, "LINUX_HAS_BPF_COOKIE") == 0) {
8466 				value = kernel_supports(obj, FEAT_BPF_COOKIE);
8467 			} else if (strcmp(ext->name, "LINUX_HAS_SYSCALL_WRAPPER") == 0) {
8468 				value = kernel_supports(obj, FEAT_SYSCALL_WRAPPER);
8469 			} else if (!str_has_pfx(ext->name, "LINUX_") || !ext->is_weak) {
8470 				/* Currently libbpf supports only CONFIG_ and LINUX_ prefixed
8471 				 * __kconfig externs, where LINUX_ ones are virtual and filled out
8472 				 * customly by libbpf (their values don't come from Kconfig).
8473 				 * If LINUX_xxx variable is not recognized by libbpf, but is marked
8474 				 * __weak, it defaults to zero value, just like for CONFIG_xxx
8475 				 * externs.
8476 				 */
8477 				pr_warn("extern (kcfg) '%s': unrecognized virtual extern\n", ext->name);
8478 				return -EINVAL;
8479 			}
8480 
8481 			err = set_kcfg_value_num(ext, ext_ptr, value);
8482 			if (err)
8483 				return err;
8484 			pr_debug("extern (kcfg) '%s': set to 0x%llx\n",
8485 				 ext->name, (long long)value);
8486 		} else {
8487 			pr_warn("extern '%s': unrecognized extern kind\n", ext->name);
8488 			return -EINVAL;
8489 		}
8490 	}
8491 	if (need_config && extra_kconfig) {
8492 		err = bpf_object__read_kconfig_mem(obj, extra_kconfig, kcfg_data);
8493 		if (err)
8494 			return -EINVAL;
8495 		need_config = false;
8496 		for (i = 0; i < obj->nr_extern; i++) {
8497 			ext = &obj->externs[i];
8498 			if (ext->type == EXT_KCFG && !ext->is_set) {
8499 				need_config = true;
8500 				break;
8501 			}
8502 		}
8503 	}
8504 	if (need_config) {
8505 		err = bpf_object__read_kconfig_file(obj, kcfg_data);
8506 		if (err)
8507 			return -EINVAL;
8508 	}
8509 	if (need_kallsyms) {
8510 		err = bpf_object__read_kallsyms_file(obj);
8511 		if (err)
8512 			return -EINVAL;
8513 	}
8514 	if (need_vmlinux_btf) {
8515 		err = bpf_object__resolve_ksyms_btf_id(obj);
8516 		if (err)
8517 			return -EINVAL;
8518 	}
8519 	for (i = 0; i < obj->nr_extern; i++) {
8520 		ext = &obj->externs[i];
8521 
8522 		if (!ext->is_set && !ext->is_weak) {
8523 			pr_warn("extern '%s' (strong): not resolved\n", ext->name);
8524 			return -ESRCH;
8525 		} else if (!ext->is_set) {
8526 			pr_debug("extern '%s' (weak): not resolved, defaulting to zero\n",
8527 				 ext->name);
8528 		}
8529 	}
8530 
8531 	return 0;
8532 }
8533 
8534 static void bpf_map_prepare_vdata(const struct bpf_map *map)
8535 {
8536 	const struct btf_type *type;
8537 	struct bpf_struct_ops *st_ops;
8538 	__u32 i;
8539 
8540 	st_ops = map->st_ops;
8541 	type = btf__type_by_id(map->obj->btf, st_ops->type_id);
8542 	for (i = 0; i < btf_vlen(type); i++) {
8543 		struct bpf_program *prog = st_ops->progs[i];
8544 		void *kern_data;
8545 		int prog_fd;
8546 
8547 		if (!prog)
8548 			continue;
8549 
8550 		prog_fd = bpf_program__fd(prog);
8551 		kern_data = st_ops->kern_vdata + st_ops->kern_func_off[i];
8552 		*(unsigned long *)kern_data = prog_fd;
8553 	}
8554 }
8555 
8556 static int bpf_object_prepare_struct_ops(struct bpf_object *obj)
8557 {
8558 	struct bpf_map *map;
8559 	int i;
8560 
8561 	for (i = 0; i < obj->nr_maps; i++) {
8562 		map = &obj->maps[i];
8563 
8564 		if (!bpf_map__is_struct_ops(map))
8565 			continue;
8566 
8567 		if (!map->autocreate)
8568 			continue;
8569 
8570 		bpf_map_prepare_vdata(map);
8571 	}
8572 
8573 	return 0;
8574 }
8575 
8576 static void bpf_object_unpin(struct bpf_object *obj)
8577 {
8578 	int i;
8579 
8580 	/* unpin any maps that were auto-pinned during load */
8581 	for (i = 0; i < obj->nr_maps; i++)
8582 		if (obj->maps[i].pinned && !obj->maps[i].reused)
8583 			bpf_map__unpin(&obj->maps[i], NULL);
8584 }
8585 
8586 static void bpf_object_post_load_cleanup(struct bpf_object *obj)
8587 {
8588 	int i;
8589 
8590 	/* clean up fd_array */
8591 	zfree(&obj->fd_array);
8592 
8593 	/* clean up module BTFs */
8594 	for (i = 0; i < obj->btf_module_cnt; i++) {
8595 		close(obj->btf_modules[i].fd);
8596 		btf__free(obj->btf_modules[i].btf);
8597 		free(obj->btf_modules[i].name);
8598 	}
8599 	obj->btf_module_cnt = 0;
8600 	zfree(&obj->btf_modules);
8601 
8602 	/* clean up vmlinux BTF */
8603 	btf__free(obj->btf_vmlinux);
8604 	obj->btf_vmlinux = NULL;
8605 }
8606 
8607 static int bpf_object_prepare(struct bpf_object *obj, const char *target_btf_path)
8608 {
8609 	int err;
8610 
8611 	if (obj->state >= OBJ_PREPARED) {
8612 		pr_warn("object '%s': prepare loading can't be attempted twice\n", obj->name);
8613 		return -EINVAL;
8614 	}
8615 
8616 	err = bpf_object_prepare_token(obj);
8617 	err = err ? : bpf_object__probe_loading(obj);
8618 	err = err ? : bpf_object__load_vmlinux_btf(obj, false);
8619 	err = err ? : bpf_object__resolve_externs(obj, obj->kconfig);
8620 	err = err ? : bpf_object__sanitize_maps(obj);
8621 	err = err ? : bpf_object__init_kern_struct_ops_maps(obj);
8622 	err = err ? : bpf_object_adjust_struct_ops_autoload(obj);
8623 	err = err ? : bpf_object__relocate(obj, obj->btf_custom_path ? : target_btf_path);
8624 	err = err ? : bpf_object__sanitize_and_load_btf(obj);
8625 	err = err ? : bpf_object__create_maps(obj);
8626 	err = err ? : bpf_object_prepare_progs(obj);
8627 
8628 	if (err) {
8629 		bpf_object_unpin(obj);
8630 		bpf_object_unload(obj);
8631 		obj->state = OBJ_LOADED;
8632 		return err;
8633 	}
8634 
8635 	obj->state = OBJ_PREPARED;
8636 	return 0;
8637 }
8638 
8639 static int bpf_object_load(struct bpf_object *obj, int extra_log_level, const char *target_btf_path)
8640 {
8641 	int err;
8642 
8643 	if (!obj)
8644 		return libbpf_err(-EINVAL);
8645 
8646 	if (obj->state >= OBJ_LOADED) {
8647 		pr_warn("object '%s': load can't be attempted twice\n", obj->name);
8648 		return libbpf_err(-EINVAL);
8649 	}
8650 
8651 	/* Disallow kernel loading programs of non-native endianness but
8652 	 * permit cross-endian creation of "light skeleton".
8653 	 */
8654 	if (obj->gen_loader) {
8655 		bpf_gen__init(obj->gen_loader, extra_log_level, obj->nr_programs, obj->nr_maps);
8656 	} else if (!is_native_endianness(obj)) {
8657 		pr_warn("object '%s': loading non-native endianness is unsupported\n", obj->name);
8658 		return libbpf_err(-LIBBPF_ERRNO__ENDIAN);
8659 	}
8660 
8661 	if (obj->state < OBJ_PREPARED) {
8662 		err = bpf_object_prepare(obj, target_btf_path);
8663 		if (err)
8664 			return libbpf_err(err);
8665 	}
8666 	err = bpf_object__load_progs(obj, extra_log_level);
8667 	err = err ? : bpf_object_init_prog_arrays(obj);
8668 	err = err ? : bpf_object_prepare_struct_ops(obj);
8669 
8670 	if (obj->gen_loader) {
8671 		/* reset FDs */
8672 		if (obj->btf)
8673 			btf__set_fd(obj->btf, -1);
8674 		if (!err)
8675 			err = bpf_gen__finish(obj->gen_loader, obj->nr_programs, obj->nr_maps);
8676 	}
8677 
8678 	bpf_object_post_load_cleanup(obj);
8679 	obj->state = OBJ_LOADED; /* doesn't matter if successfully or not */
8680 
8681 	if (err) {
8682 		bpf_object_unpin(obj);
8683 		bpf_object_unload(obj);
8684 		pr_warn("failed to load object '%s'\n", obj->path);
8685 		return libbpf_err(err);
8686 	}
8687 
8688 	return 0;
8689 }
8690 
8691 int bpf_object__prepare(struct bpf_object *obj)
8692 {
8693 	return libbpf_err(bpf_object_prepare(obj, NULL));
8694 }
8695 
8696 int bpf_object__load(struct bpf_object *obj)
8697 {
8698 	return bpf_object_load(obj, 0, NULL);
8699 }
8700 
8701 static int make_parent_dir(const char *path)
8702 {
8703 	char *dname, *dir;
8704 	int err = 0;
8705 
8706 	dname = strdup(path);
8707 	if (dname == NULL)
8708 		return -ENOMEM;
8709 
8710 	dir = dirname(dname);
8711 	if (mkdir(dir, 0700) && errno != EEXIST)
8712 		err = -errno;
8713 
8714 	free(dname);
8715 	if (err) {
8716 		pr_warn("failed to mkdir %s: %s\n", path, errstr(err));
8717 	}
8718 	return err;
8719 }
8720 
8721 static int check_path(const char *path)
8722 {
8723 	struct statfs st_fs;
8724 	char *dname, *dir;
8725 	int err = 0;
8726 
8727 	if (path == NULL)
8728 		return -EINVAL;
8729 
8730 	dname = strdup(path);
8731 	if (dname == NULL)
8732 		return -ENOMEM;
8733 
8734 	dir = dirname(dname);
8735 	if (statfs(dir, &st_fs)) {
8736 		pr_warn("failed to statfs %s: %s\n", dir, errstr(errno));
8737 		err = -errno;
8738 	}
8739 	free(dname);
8740 
8741 	if (!err && st_fs.f_type != BPF_FS_MAGIC) {
8742 		pr_warn("specified path %s is not on BPF FS\n", path);
8743 		err = -EINVAL;
8744 	}
8745 
8746 	return err;
8747 }
8748 
8749 int bpf_program__pin(struct bpf_program *prog, const char *path)
8750 {
8751 	int err;
8752 
8753 	if (prog->fd < 0) {
8754 		pr_warn("prog '%s': can't pin program that wasn't loaded\n", prog->name);
8755 		return libbpf_err(-EINVAL);
8756 	}
8757 
8758 	err = make_parent_dir(path);
8759 	if (err)
8760 		return libbpf_err(err);
8761 
8762 	err = check_path(path);
8763 	if (err)
8764 		return libbpf_err(err);
8765 
8766 	if (bpf_obj_pin(prog->fd, path)) {
8767 		err = -errno;
8768 		pr_warn("prog '%s': failed to pin at '%s': %s\n", prog->name, path, errstr(err));
8769 		return libbpf_err(err);
8770 	}
8771 
8772 	pr_debug("prog '%s': pinned at '%s'\n", prog->name, path);
8773 	return 0;
8774 }
8775 
8776 int bpf_program__unpin(struct bpf_program *prog, const char *path)
8777 {
8778 	int err;
8779 
8780 	if (prog->fd < 0) {
8781 		pr_warn("prog '%s': can't unpin program that wasn't loaded\n", prog->name);
8782 		return libbpf_err(-EINVAL);
8783 	}
8784 
8785 	err = check_path(path);
8786 	if (err)
8787 		return libbpf_err(err);
8788 
8789 	err = unlink(path);
8790 	if (err)
8791 		return libbpf_err(-errno);
8792 
8793 	pr_debug("prog '%s': unpinned from '%s'\n", prog->name, path);
8794 	return 0;
8795 }
8796 
8797 int bpf_map__pin(struct bpf_map *map, const char *path)
8798 {
8799 	int err;
8800 
8801 	if (map == NULL) {
8802 		pr_warn("invalid map pointer\n");
8803 		return libbpf_err(-EINVAL);
8804 	}
8805 
8806 	if (map->fd < 0) {
8807 		pr_warn("map '%s': can't pin BPF map without FD (was it created?)\n", map->name);
8808 		return libbpf_err(-EINVAL);
8809 	}
8810 
8811 	if (map->pin_path) {
8812 		if (path && strcmp(path, map->pin_path)) {
8813 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
8814 				bpf_map__name(map), map->pin_path, path);
8815 			return libbpf_err(-EINVAL);
8816 		} else if (map->pinned) {
8817 			pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
8818 				 bpf_map__name(map), map->pin_path);
8819 			return 0;
8820 		}
8821 	} else {
8822 		if (!path) {
8823 			pr_warn("missing a path to pin map '%s' at\n",
8824 				bpf_map__name(map));
8825 			return libbpf_err(-EINVAL);
8826 		} else if (map->pinned) {
8827 			pr_warn("map '%s' already pinned\n", bpf_map__name(map));
8828 			return libbpf_err(-EEXIST);
8829 		}
8830 
8831 		map->pin_path = strdup(path);
8832 		if (!map->pin_path) {
8833 			err = -errno;
8834 			goto out_err;
8835 		}
8836 	}
8837 
8838 	err = make_parent_dir(map->pin_path);
8839 	if (err)
8840 		return libbpf_err(err);
8841 
8842 	err = check_path(map->pin_path);
8843 	if (err)
8844 		return libbpf_err(err);
8845 
8846 	if (bpf_obj_pin(map->fd, map->pin_path)) {
8847 		err = -errno;
8848 		goto out_err;
8849 	}
8850 
8851 	map->pinned = true;
8852 	pr_debug("pinned map '%s'\n", map->pin_path);
8853 
8854 	return 0;
8855 
8856 out_err:
8857 	pr_warn("failed to pin map: %s\n", errstr(err));
8858 	return libbpf_err(err);
8859 }
8860 
8861 int bpf_map__unpin(struct bpf_map *map, const char *path)
8862 {
8863 	int err;
8864 
8865 	if (map == NULL) {
8866 		pr_warn("invalid map pointer\n");
8867 		return libbpf_err(-EINVAL);
8868 	}
8869 
8870 	if (map->pin_path) {
8871 		if (path && strcmp(path, map->pin_path)) {
8872 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
8873 				bpf_map__name(map), map->pin_path, path);
8874 			return libbpf_err(-EINVAL);
8875 		}
8876 		path = map->pin_path;
8877 	} else if (!path) {
8878 		pr_warn("no path to unpin map '%s' from\n",
8879 			bpf_map__name(map));
8880 		return libbpf_err(-EINVAL);
8881 	}
8882 
8883 	err = check_path(path);
8884 	if (err)
8885 		return libbpf_err(err);
8886 
8887 	err = unlink(path);
8888 	if (err != 0)
8889 		return libbpf_err(-errno);
8890 
8891 	map->pinned = false;
8892 	pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path);
8893 
8894 	return 0;
8895 }
8896 
8897 int bpf_map__set_pin_path(struct bpf_map *map, const char *path)
8898 {
8899 	char *new = NULL;
8900 
8901 	if (path) {
8902 		new = strdup(path);
8903 		if (!new)
8904 			return libbpf_err(-errno);
8905 	}
8906 
8907 	free(map->pin_path);
8908 	map->pin_path = new;
8909 	return 0;
8910 }
8911 
8912 __alias(bpf_map__pin_path)
8913 const char *bpf_map__get_pin_path(const struct bpf_map *map);
8914 
8915 const char *bpf_map__pin_path(const struct bpf_map *map)
8916 {
8917 	return map->pin_path;
8918 }
8919 
8920 bool bpf_map__is_pinned(const struct bpf_map *map)
8921 {
8922 	return map->pinned;
8923 }
8924 
8925 static void sanitize_pin_path(char *s)
8926 {
8927 	/* bpffs disallows periods in path names */
8928 	while (*s) {
8929 		if (*s == '.')
8930 			*s = '_';
8931 		s++;
8932 	}
8933 }
8934 
8935 int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
8936 {
8937 	struct bpf_map *map;
8938 	int err;
8939 
8940 	if (!obj)
8941 		return libbpf_err(-ENOENT);
8942 
8943 	if (obj->state < OBJ_PREPARED) {
8944 		pr_warn("object not yet loaded; load it first\n");
8945 		return libbpf_err(-ENOENT);
8946 	}
8947 
8948 	bpf_object__for_each_map(map, obj) {
8949 		char *pin_path = NULL;
8950 		char buf[PATH_MAX];
8951 
8952 		if (!map->autocreate)
8953 			continue;
8954 
8955 		if (path) {
8956 			err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
8957 			if (err)
8958 				goto err_unpin_maps;
8959 			sanitize_pin_path(buf);
8960 			pin_path = buf;
8961 		} else if (!map->pin_path) {
8962 			continue;
8963 		}
8964 
8965 		err = bpf_map__pin(map, pin_path);
8966 		if (err)
8967 			goto err_unpin_maps;
8968 	}
8969 
8970 	return 0;
8971 
8972 err_unpin_maps:
8973 	while ((map = bpf_object__prev_map(obj, map))) {
8974 		if (!map->pin_path)
8975 			continue;
8976 
8977 		bpf_map__unpin(map, NULL);
8978 	}
8979 
8980 	return libbpf_err(err);
8981 }
8982 
8983 int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
8984 {
8985 	struct bpf_map *map;
8986 	int err;
8987 
8988 	if (!obj)
8989 		return libbpf_err(-ENOENT);
8990 
8991 	bpf_object__for_each_map(map, obj) {
8992 		char *pin_path = NULL;
8993 		char buf[PATH_MAX];
8994 
8995 		if (path) {
8996 			err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
8997 			if (err)
8998 				return libbpf_err(err);
8999 			sanitize_pin_path(buf);
9000 			pin_path = buf;
9001 		} else if (!map->pin_path) {
9002 			continue;
9003 		}
9004 
9005 		err = bpf_map__unpin(map, pin_path);
9006 		if (err)
9007 			return libbpf_err(err);
9008 	}
9009 
9010 	return 0;
9011 }
9012 
9013 int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
9014 {
9015 	struct bpf_program *prog;
9016 	char buf[PATH_MAX];
9017 	int err;
9018 
9019 	if (!obj)
9020 		return libbpf_err(-ENOENT);
9021 
9022 	if (obj->state < OBJ_LOADED) {
9023 		pr_warn("object not yet loaded; load it first\n");
9024 		return libbpf_err(-ENOENT);
9025 	}
9026 
9027 	bpf_object__for_each_program(prog, obj) {
9028 		err = pathname_concat(buf, sizeof(buf), path, prog->name);
9029 		if (err)
9030 			goto err_unpin_programs;
9031 
9032 		err = bpf_program__pin(prog, buf);
9033 		if (err)
9034 			goto err_unpin_programs;
9035 	}
9036 
9037 	return 0;
9038 
9039 err_unpin_programs:
9040 	while ((prog = bpf_object__prev_program(obj, prog))) {
9041 		if (pathname_concat(buf, sizeof(buf), path, prog->name))
9042 			continue;
9043 
9044 		bpf_program__unpin(prog, buf);
9045 	}
9046 
9047 	return libbpf_err(err);
9048 }
9049 
9050 int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
9051 {
9052 	struct bpf_program *prog;
9053 	int err;
9054 
9055 	if (!obj)
9056 		return libbpf_err(-ENOENT);
9057 
9058 	bpf_object__for_each_program(prog, obj) {
9059 		char buf[PATH_MAX];
9060 
9061 		err = pathname_concat(buf, sizeof(buf), path, prog->name);
9062 		if (err)
9063 			return libbpf_err(err);
9064 
9065 		err = bpf_program__unpin(prog, buf);
9066 		if (err)
9067 			return libbpf_err(err);
9068 	}
9069 
9070 	return 0;
9071 }
9072 
9073 int bpf_object__pin(struct bpf_object *obj, const char *path)
9074 {
9075 	int err;
9076 
9077 	err = bpf_object__pin_maps(obj, path);
9078 	if (err)
9079 		return libbpf_err(err);
9080 
9081 	err = bpf_object__pin_programs(obj, path);
9082 	if (err) {
9083 		bpf_object__unpin_maps(obj, path);
9084 		return libbpf_err(err);
9085 	}
9086 
9087 	return 0;
9088 }
9089 
9090 int bpf_object__unpin(struct bpf_object *obj, const char *path)
9091 {
9092 	int err;
9093 
9094 	err = bpf_object__unpin_programs(obj, path);
9095 	if (err)
9096 		return libbpf_err(err);
9097 
9098 	err = bpf_object__unpin_maps(obj, path);
9099 	if (err)
9100 		return libbpf_err(err);
9101 
9102 	return 0;
9103 }
9104 
9105 static void bpf_map__destroy(struct bpf_map *map)
9106 {
9107 	if (map->inner_map) {
9108 		bpf_map__destroy(map->inner_map);
9109 		zfree(&map->inner_map);
9110 	}
9111 
9112 	zfree(&map->init_slots);
9113 	map->init_slots_sz = 0;
9114 
9115 	if (map->mmaped && map->mmaped != map->obj->arena_data)
9116 		munmap(map->mmaped, bpf_map_mmap_sz(map));
9117 	map->mmaped = NULL;
9118 
9119 	if (map->st_ops) {
9120 		zfree(&map->st_ops->data);
9121 		zfree(&map->st_ops->progs);
9122 		zfree(&map->st_ops->kern_func_off);
9123 		zfree(&map->st_ops);
9124 	}
9125 
9126 	zfree(&map->name);
9127 	zfree(&map->real_name);
9128 	zfree(&map->pin_path);
9129 
9130 	if (map->fd >= 0)
9131 		zclose(map->fd);
9132 }
9133 
9134 void bpf_object__close(struct bpf_object *obj)
9135 {
9136 	size_t i;
9137 
9138 	if (IS_ERR_OR_NULL(obj))
9139 		return;
9140 
9141 	/*
9142 	 * if user called bpf_object__prepare() without ever getting to
9143 	 * bpf_object__load(), we need to clean up stuff that is normally
9144 	 * cleaned up at the end of loading step
9145 	 */
9146 	bpf_object_post_load_cleanup(obj);
9147 
9148 	usdt_manager_free(obj->usdt_man);
9149 	obj->usdt_man = NULL;
9150 
9151 	bpf_gen__free(obj->gen_loader);
9152 	bpf_object__elf_finish(obj);
9153 	bpf_object_unload(obj);
9154 	btf__free(obj->btf);
9155 	btf__free(obj->btf_vmlinux);
9156 	btf_ext__free(obj->btf_ext);
9157 
9158 	for (i = 0; i < obj->nr_maps; i++)
9159 		bpf_map__destroy(&obj->maps[i]);
9160 
9161 	zfree(&obj->btf_custom_path);
9162 	zfree(&obj->kconfig);
9163 
9164 	for (i = 0; i < obj->nr_extern; i++) {
9165 		zfree(&obj->externs[i].name);
9166 		zfree(&obj->externs[i].essent_name);
9167 	}
9168 
9169 	zfree(&obj->externs);
9170 	obj->nr_extern = 0;
9171 
9172 	zfree(&obj->maps);
9173 	obj->nr_maps = 0;
9174 
9175 	if (obj->programs && obj->nr_programs) {
9176 		for (i = 0; i < obj->nr_programs; i++)
9177 			bpf_program__exit(&obj->programs[i]);
9178 	}
9179 	zfree(&obj->programs);
9180 
9181 	zfree(&obj->feat_cache);
9182 	zfree(&obj->token_path);
9183 	if (obj->token_fd > 0)
9184 		close(obj->token_fd);
9185 
9186 	zfree(&obj->arena_data);
9187 
9188 	free(obj);
9189 }
9190 
9191 const char *bpf_object__name(const struct bpf_object *obj)
9192 {
9193 	return obj ? obj->name : libbpf_err_ptr(-EINVAL);
9194 }
9195 
9196 unsigned int bpf_object__kversion(const struct bpf_object *obj)
9197 {
9198 	return obj ? obj->kern_version : 0;
9199 }
9200 
9201 int bpf_object__token_fd(const struct bpf_object *obj)
9202 {
9203 	return obj->token_fd ?: -1;
9204 }
9205 
9206 struct btf *bpf_object__btf(const struct bpf_object *obj)
9207 {
9208 	return obj ? obj->btf : NULL;
9209 }
9210 
9211 int bpf_object__btf_fd(const struct bpf_object *obj)
9212 {
9213 	return obj->btf ? btf__fd(obj->btf) : -1;
9214 }
9215 
9216 int bpf_object__set_kversion(struct bpf_object *obj, __u32 kern_version)
9217 {
9218 	if (obj->state >= OBJ_LOADED)
9219 		return libbpf_err(-EINVAL);
9220 
9221 	obj->kern_version = kern_version;
9222 
9223 	return 0;
9224 }
9225 
9226 int bpf_object__gen_loader(struct bpf_object *obj, struct gen_loader_opts *opts)
9227 {
9228 	struct bpf_gen *gen;
9229 
9230 	if (!opts)
9231 		return libbpf_err(-EFAULT);
9232 	if (!OPTS_VALID(opts, gen_loader_opts))
9233 		return libbpf_err(-EINVAL);
9234 	gen = calloc(1, sizeof(*gen));
9235 	if (!gen)
9236 		return libbpf_err(-ENOMEM);
9237 	gen->opts = opts;
9238 	gen->swapped_endian = !is_native_endianness(obj);
9239 	obj->gen_loader = gen;
9240 	return 0;
9241 }
9242 
9243 static struct bpf_program *
9244 __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
9245 		    bool forward)
9246 {
9247 	size_t nr_programs = obj->nr_programs;
9248 	ssize_t idx;
9249 
9250 	if (!nr_programs)
9251 		return NULL;
9252 
9253 	if (!p)
9254 		/* Iter from the beginning */
9255 		return forward ? &obj->programs[0] :
9256 			&obj->programs[nr_programs - 1];
9257 
9258 	if (p->obj != obj) {
9259 		pr_warn("error: program handler doesn't match object\n");
9260 		return errno = EINVAL, NULL;
9261 	}
9262 
9263 	idx = (p - obj->programs) + (forward ? 1 : -1);
9264 	if (idx >= obj->nr_programs || idx < 0)
9265 		return NULL;
9266 	return &obj->programs[idx];
9267 }
9268 
9269 struct bpf_program *
9270 bpf_object__next_program(const struct bpf_object *obj, struct bpf_program *prev)
9271 {
9272 	struct bpf_program *prog = prev;
9273 
9274 	do {
9275 		prog = __bpf_program__iter(prog, obj, true);
9276 	} while (prog && prog_is_subprog(obj, prog));
9277 
9278 	return prog;
9279 }
9280 
9281 struct bpf_program *
9282 bpf_object__prev_program(const struct bpf_object *obj, struct bpf_program *next)
9283 {
9284 	struct bpf_program *prog = next;
9285 
9286 	do {
9287 		prog = __bpf_program__iter(prog, obj, false);
9288 	} while (prog && prog_is_subprog(obj, prog));
9289 
9290 	return prog;
9291 }
9292 
9293 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
9294 {
9295 	prog->prog_ifindex = ifindex;
9296 }
9297 
9298 const char *bpf_program__name(const struct bpf_program *prog)
9299 {
9300 	return prog->name;
9301 }
9302 
9303 const char *bpf_program__section_name(const struct bpf_program *prog)
9304 {
9305 	return prog->sec_name;
9306 }
9307 
9308 bool bpf_program__autoload(const struct bpf_program *prog)
9309 {
9310 	return prog->autoload;
9311 }
9312 
9313 int bpf_program__set_autoload(struct bpf_program *prog, bool autoload)
9314 {
9315 	if (prog->obj->state >= OBJ_LOADED)
9316 		return libbpf_err(-EINVAL);
9317 
9318 	prog->autoload = autoload;
9319 	return 0;
9320 }
9321 
9322 bool bpf_program__autoattach(const struct bpf_program *prog)
9323 {
9324 	return prog->autoattach;
9325 }
9326 
9327 void bpf_program__set_autoattach(struct bpf_program *prog, bool autoattach)
9328 {
9329 	prog->autoattach = autoattach;
9330 }
9331 
9332 const struct bpf_insn *bpf_program__insns(const struct bpf_program *prog)
9333 {
9334 	return prog->insns;
9335 }
9336 
9337 size_t bpf_program__insn_cnt(const struct bpf_program *prog)
9338 {
9339 	return prog->insns_cnt;
9340 }
9341 
9342 int bpf_program__set_insns(struct bpf_program *prog,
9343 			   struct bpf_insn *new_insns, size_t new_insn_cnt)
9344 {
9345 	struct bpf_insn *insns;
9346 
9347 	if (prog->obj->state >= OBJ_LOADED)
9348 		return libbpf_err(-EBUSY);
9349 
9350 	insns = libbpf_reallocarray(prog->insns, new_insn_cnt, sizeof(*insns));
9351 	/* NULL is a valid return from reallocarray if the new count is zero */
9352 	if (!insns && new_insn_cnt) {
9353 		pr_warn("prog '%s': failed to realloc prog code\n", prog->name);
9354 		return libbpf_err(-ENOMEM);
9355 	}
9356 	memcpy(insns, new_insns, new_insn_cnt * sizeof(*insns));
9357 
9358 	prog->insns = insns;
9359 	prog->insns_cnt = new_insn_cnt;
9360 	return 0;
9361 }
9362 
9363 int bpf_program__fd(const struct bpf_program *prog)
9364 {
9365 	if (!prog)
9366 		return libbpf_err(-EINVAL);
9367 
9368 	if (prog->fd < 0)
9369 		return libbpf_err(-ENOENT);
9370 
9371 	return prog->fd;
9372 }
9373 
9374 __alias(bpf_program__type)
9375 enum bpf_prog_type bpf_program__get_type(const struct bpf_program *prog);
9376 
9377 enum bpf_prog_type bpf_program__type(const struct bpf_program *prog)
9378 {
9379 	return prog->type;
9380 }
9381 
9382 static size_t custom_sec_def_cnt;
9383 static struct bpf_sec_def *custom_sec_defs;
9384 static struct bpf_sec_def custom_fallback_def;
9385 static bool has_custom_fallback_def;
9386 static int last_custom_sec_def_handler_id;
9387 
9388 int bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
9389 {
9390 	if (prog->obj->state >= OBJ_LOADED)
9391 		return libbpf_err(-EBUSY);
9392 
9393 	/* if type is not changed, do nothing */
9394 	if (prog->type == type)
9395 		return 0;
9396 
9397 	prog->type = type;
9398 
9399 	/* If a program type was changed, we need to reset associated SEC()
9400 	 * handler, as it will be invalid now. The only exception is a generic
9401 	 * fallback handler, which by definition is program type-agnostic and
9402 	 * is a catch-all custom handler, optionally set by the application,
9403 	 * so should be able to handle any type of BPF program.
9404 	 */
9405 	if (prog->sec_def != &custom_fallback_def)
9406 		prog->sec_def = NULL;
9407 	return 0;
9408 }
9409 
9410 __alias(bpf_program__expected_attach_type)
9411 enum bpf_attach_type bpf_program__get_expected_attach_type(const struct bpf_program *prog);
9412 
9413 enum bpf_attach_type bpf_program__expected_attach_type(const struct bpf_program *prog)
9414 {
9415 	return prog->expected_attach_type;
9416 }
9417 
9418 int bpf_program__set_expected_attach_type(struct bpf_program *prog,
9419 					   enum bpf_attach_type type)
9420 {
9421 	if (prog->obj->state >= OBJ_LOADED)
9422 		return libbpf_err(-EBUSY);
9423 
9424 	prog->expected_attach_type = type;
9425 	return 0;
9426 }
9427 
9428 __u32 bpf_program__flags(const struct bpf_program *prog)
9429 {
9430 	return prog->prog_flags;
9431 }
9432 
9433 int bpf_program__set_flags(struct bpf_program *prog, __u32 flags)
9434 {
9435 	if (prog->obj->state >= OBJ_LOADED)
9436 		return libbpf_err(-EBUSY);
9437 
9438 	prog->prog_flags = flags;
9439 	return 0;
9440 }
9441 
9442 __u32 bpf_program__log_level(const struct bpf_program *prog)
9443 {
9444 	return prog->log_level;
9445 }
9446 
9447 int bpf_program__set_log_level(struct bpf_program *prog, __u32 log_level)
9448 {
9449 	if (prog->obj->state >= OBJ_LOADED)
9450 		return libbpf_err(-EBUSY);
9451 
9452 	prog->log_level = log_level;
9453 	return 0;
9454 }
9455 
9456 const char *bpf_program__log_buf(const struct bpf_program *prog, size_t *log_size)
9457 {
9458 	*log_size = prog->log_size;
9459 	return prog->log_buf;
9460 }
9461 
9462 int bpf_program__set_log_buf(struct bpf_program *prog, char *log_buf, size_t log_size)
9463 {
9464 	if (log_size && !log_buf)
9465 		return libbpf_err(-EINVAL);
9466 	if (prog->log_size > UINT_MAX)
9467 		return libbpf_err(-EINVAL);
9468 	if (prog->obj->state >= OBJ_LOADED)
9469 		return libbpf_err(-EBUSY);
9470 
9471 	prog->log_buf = log_buf;
9472 	prog->log_size = log_size;
9473 	return 0;
9474 }
9475 
9476 struct bpf_func_info *bpf_program__func_info(const struct bpf_program *prog)
9477 {
9478 	if (prog->func_info_rec_size != sizeof(struct bpf_func_info))
9479 		return libbpf_err_ptr(-EOPNOTSUPP);
9480 	return prog->func_info;
9481 }
9482 
9483 __u32 bpf_program__func_info_cnt(const struct bpf_program *prog)
9484 {
9485 	return prog->func_info_cnt;
9486 }
9487 
9488 struct bpf_line_info *bpf_program__line_info(const struct bpf_program *prog)
9489 {
9490 	if (prog->line_info_rec_size != sizeof(struct bpf_line_info))
9491 		return libbpf_err_ptr(-EOPNOTSUPP);
9492 	return prog->line_info;
9493 }
9494 
9495 __u32 bpf_program__line_info_cnt(const struct bpf_program *prog)
9496 {
9497 	return prog->line_info_cnt;
9498 }
9499 
9500 #define SEC_DEF(sec_pfx, ptype, atype, flags, ...) {			    \
9501 	.sec = (char *)sec_pfx,						    \
9502 	.prog_type = BPF_PROG_TYPE_##ptype,				    \
9503 	.expected_attach_type = atype,					    \
9504 	.cookie = (long)(flags),					    \
9505 	.prog_prepare_load_fn = libbpf_prepare_prog_load,		    \
9506 	__VA_ARGS__							    \
9507 }
9508 
9509 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9510 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9511 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9512 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9513 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9514 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9515 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9516 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9517 static int attach_kprobe_session(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9518 static int attach_uprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9519 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9520 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9521 
9522 static const struct bpf_sec_def section_defs[] = {
9523 	SEC_DEF("socket",		SOCKET_FILTER, 0, SEC_NONE),
9524 	SEC_DEF("sk_reuseport/migrate",	SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT_OR_MIGRATE, SEC_ATTACHABLE),
9525 	SEC_DEF("sk_reuseport",		SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT, SEC_ATTACHABLE),
9526 	SEC_DEF("kprobe+",		KPROBE,	0, SEC_NONE, attach_kprobe),
9527 	SEC_DEF("uprobe+",		KPROBE,	0, SEC_NONE, attach_uprobe),
9528 	SEC_DEF("uprobe.s+",		KPROBE,	0, SEC_SLEEPABLE, attach_uprobe),
9529 	SEC_DEF("kretprobe+",		KPROBE, 0, SEC_NONE, attach_kprobe),
9530 	SEC_DEF("uretprobe+",		KPROBE, 0, SEC_NONE, attach_uprobe),
9531 	SEC_DEF("uretprobe.s+",		KPROBE, 0, SEC_SLEEPABLE, attach_uprobe),
9532 	SEC_DEF("kprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
9533 	SEC_DEF("kretprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
9534 	SEC_DEF("kprobe.session+",	KPROBE,	BPF_TRACE_KPROBE_SESSION, SEC_NONE, attach_kprobe_session),
9535 	SEC_DEF("uprobe.multi+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_NONE, attach_uprobe_multi),
9536 	SEC_DEF("uretprobe.multi+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_NONE, attach_uprobe_multi),
9537 	SEC_DEF("uprobe.session+",	KPROBE,	BPF_TRACE_UPROBE_SESSION, SEC_NONE, attach_uprobe_multi),
9538 	SEC_DEF("uprobe.multi.s+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_SLEEPABLE, attach_uprobe_multi),
9539 	SEC_DEF("uretprobe.multi.s+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_SLEEPABLE, attach_uprobe_multi),
9540 	SEC_DEF("uprobe.session.s+",	KPROBE,	BPF_TRACE_UPROBE_SESSION, SEC_SLEEPABLE, attach_uprobe_multi),
9541 	SEC_DEF("ksyscall+",		KPROBE,	0, SEC_NONE, attach_ksyscall),
9542 	SEC_DEF("kretsyscall+",		KPROBE, 0, SEC_NONE, attach_ksyscall),
9543 	SEC_DEF("usdt+",		KPROBE,	0, SEC_USDT, attach_usdt),
9544 	SEC_DEF("usdt.s+",		KPROBE,	0, SEC_USDT | SEC_SLEEPABLE, attach_usdt),
9545 	SEC_DEF("tc/ingress",		SCHED_CLS, BPF_TCX_INGRESS, SEC_NONE), /* alias for tcx */
9546 	SEC_DEF("tc/egress",		SCHED_CLS, BPF_TCX_EGRESS, SEC_NONE),  /* alias for tcx */
9547 	SEC_DEF("tcx/ingress",		SCHED_CLS, BPF_TCX_INGRESS, SEC_NONE),
9548 	SEC_DEF("tcx/egress",		SCHED_CLS, BPF_TCX_EGRESS, SEC_NONE),
9549 	SEC_DEF("tc",			SCHED_CLS, 0, SEC_NONE), /* deprecated / legacy, use tcx */
9550 	SEC_DEF("classifier",		SCHED_CLS, 0, SEC_NONE), /* deprecated / legacy, use tcx */
9551 	SEC_DEF("action",		SCHED_ACT, 0, SEC_NONE), /* deprecated / legacy, use tcx */
9552 	SEC_DEF("netkit/primary",	SCHED_CLS, BPF_NETKIT_PRIMARY, SEC_NONE),
9553 	SEC_DEF("netkit/peer",		SCHED_CLS, BPF_NETKIT_PEER, SEC_NONE),
9554 	SEC_DEF("tracepoint+",		TRACEPOINT, 0, SEC_NONE, attach_tp),
9555 	SEC_DEF("tp+",			TRACEPOINT, 0, SEC_NONE, attach_tp),
9556 	SEC_DEF("raw_tracepoint+",	RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
9557 	SEC_DEF("raw_tp+",		RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
9558 	SEC_DEF("raw_tracepoint.w+",	RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
9559 	SEC_DEF("raw_tp.w+",		RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
9560 	SEC_DEF("tp_btf+",		TRACING, BPF_TRACE_RAW_TP, SEC_ATTACH_BTF, attach_trace),
9561 	SEC_DEF("fentry+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF, attach_trace),
9562 	SEC_DEF("fmod_ret+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF, attach_trace),
9563 	SEC_DEF("fexit+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF, attach_trace),
9564 	SEC_DEF("fentry.s+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
9565 	SEC_DEF("fmod_ret.s+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
9566 	SEC_DEF("fexit.s+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
9567 	SEC_DEF("freplace+",		EXT, 0, SEC_ATTACH_BTF, attach_trace),
9568 	SEC_DEF("lsm+",			LSM, BPF_LSM_MAC, SEC_ATTACH_BTF, attach_lsm),
9569 	SEC_DEF("lsm.s+",		LSM, BPF_LSM_MAC, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_lsm),
9570 	SEC_DEF("lsm_cgroup+",		LSM, BPF_LSM_CGROUP, SEC_ATTACH_BTF),
9571 	SEC_DEF("iter+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF, attach_iter),
9572 	SEC_DEF("iter.s+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_iter),
9573 	SEC_DEF("syscall",		SYSCALL, 0, SEC_SLEEPABLE),
9574 	SEC_DEF("xdp.frags/devmap",	XDP, BPF_XDP_DEVMAP, SEC_XDP_FRAGS),
9575 	SEC_DEF("xdp/devmap",		XDP, BPF_XDP_DEVMAP, SEC_ATTACHABLE),
9576 	SEC_DEF("xdp.frags/cpumap",	XDP, BPF_XDP_CPUMAP, SEC_XDP_FRAGS),
9577 	SEC_DEF("xdp/cpumap",		XDP, BPF_XDP_CPUMAP, SEC_ATTACHABLE),
9578 	SEC_DEF("xdp.frags",		XDP, BPF_XDP, SEC_XDP_FRAGS),
9579 	SEC_DEF("xdp",			XDP, BPF_XDP, SEC_ATTACHABLE_OPT),
9580 	SEC_DEF("perf_event",		PERF_EVENT, 0, SEC_NONE),
9581 	SEC_DEF("lwt_in",		LWT_IN, 0, SEC_NONE),
9582 	SEC_DEF("lwt_out",		LWT_OUT, 0, SEC_NONE),
9583 	SEC_DEF("lwt_xmit",		LWT_XMIT, 0, SEC_NONE),
9584 	SEC_DEF("lwt_seg6local",	LWT_SEG6LOCAL, 0, SEC_NONE),
9585 	SEC_DEF("sockops",		SOCK_OPS, BPF_CGROUP_SOCK_OPS, SEC_ATTACHABLE_OPT),
9586 	SEC_DEF("sk_skb/stream_parser",	SK_SKB, BPF_SK_SKB_STREAM_PARSER, SEC_ATTACHABLE_OPT),
9587 	SEC_DEF("sk_skb/stream_verdict",SK_SKB, BPF_SK_SKB_STREAM_VERDICT, SEC_ATTACHABLE_OPT),
9588 	SEC_DEF("sk_skb/verdict",	SK_SKB, BPF_SK_SKB_VERDICT, SEC_ATTACHABLE_OPT),
9589 	SEC_DEF("sk_skb",		SK_SKB, 0, SEC_NONE),
9590 	SEC_DEF("sk_msg",		SK_MSG, BPF_SK_MSG_VERDICT, SEC_ATTACHABLE_OPT),
9591 	SEC_DEF("lirc_mode2",		LIRC_MODE2, BPF_LIRC_MODE2, SEC_ATTACHABLE_OPT),
9592 	SEC_DEF("flow_dissector",	FLOW_DISSECTOR, BPF_FLOW_DISSECTOR, SEC_ATTACHABLE_OPT),
9593 	SEC_DEF("cgroup_skb/ingress",	CGROUP_SKB, BPF_CGROUP_INET_INGRESS, SEC_ATTACHABLE_OPT),
9594 	SEC_DEF("cgroup_skb/egress",	CGROUP_SKB, BPF_CGROUP_INET_EGRESS, SEC_ATTACHABLE_OPT),
9595 	SEC_DEF("cgroup/skb",		CGROUP_SKB, 0, SEC_NONE),
9596 	SEC_DEF("cgroup/sock_create",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE),
9597 	SEC_DEF("cgroup/sock_release",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_RELEASE, SEC_ATTACHABLE),
9598 	SEC_DEF("cgroup/sock",		CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE_OPT),
9599 	SEC_DEF("cgroup/post_bind4",	CGROUP_SOCK, BPF_CGROUP_INET4_POST_BIND, SEC_ATTACHABLE),
9600 	SEC_DEF("cgroup/post_bind6",	CGROUP_SOCK, BPF_CGROUP_INET6_POST_BIND, SEC_ATTACHABLE),
9601 	SEC_DEF("cgroup/bind4",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND, SEC_ATTACHABLE),
9602 	SEC_DEF("cgroup/bind6",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND, SEC_ATTACHABLE),
9603 	SEC_DEF("cgroup/connect4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT, SEC_ATTACHABLE),
9604 	SEC_DEF("cgroup/connect6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT, SEC_ATTACHABLE),
9605 	SEC_DEF("cgroup/connect_unix",	CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_CONNECT, SEC_ATTACHABLE),
9606 	SEC_DEF("cgroup/sendmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG, SEC_ATTACHABLE),
9607 	SEC_DEF("cgroup/sendmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG, SEC_ATTACHABLE),
9608 	SEC_DEF("cgroup/sendmsg_unix",	CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_SENDMSG, SEC_ATTACHABLE),
9609 	SEC_DEF("cgroup/recvmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_RECVMSG, SEC_ATTACHABLE),
9610 	SEC_DEF("cgroup/recvmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_RECVMSG, SEC_ATTACHABLE),
9611 	SEC_DEF("cgroup/recvmsg_unix",	CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_RECVMSG, SEC_ATTACHABLE),
9612 	SEC_DEF("cgroup/getpeername4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETPEERNAME, SEC_ATTACHABLE),
9613 	SEC_DEF("cgroup/getpeername6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETPEERNAME, SEC_ATTACHABLE),
9614 	SEC_DEF("cgroup/getpeername_unix", CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_GETPEERNAME, SEC_ATTACHABLE),
9615 	SEC_DEF("cgroup/getsockname4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETSOCKNAME, SEC_ATTACHABLE),
9616 	SEC_DEF("cgroup/getsockname6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETSOCKNAME, SEC_ATTACHABLE),
9617 	SEC_DEF("cgroup/getsockname_unix", CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_GETSOCKNAME, SEC_ATTACHABLE),
9618 	SEC_DEF("cgroup/sysctl",	CGROUP_SYSCTL, BPF_CGROUP_SYSCTL, SEC_ATTACHABLE),
9619 	SEC_DEF("cgroup/getsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_GETSOCKOPT, SEC_ATTACHABLE),
9620 	SEC_DEF("cgroup/setsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_SETSOCKOPT, SEC_ATTACHABLE),
9621 	SEC_DEF("cgroup/dev",		CGROUP_DEVICE, BPF_CGROUP_DEVICE, SEC_ATTACHABLE_OPT),
9622 	SEC_DEF("struct_ops+",		STRUCT_OPS, 0, SEC_NONE),
9623 	SEC_DEF("struct_ops.s+",	STRUCT_OPS, 0, SEC_SLEEPABLE),
9624 	SEC_DEF("sk_lookup",		SK_LOOKUP, BPF_SK_LOOKUP, SEC_ATTACHABLE),
9625 	SEC_DEF("netfilter",		NETFILTER, BPF_NETFILTER, SEC_NONE),
9626 };
9627 
9628 int libbpf_register_prog_handler(const char *sec,
9629 				 enum bpf_prog_type prog_type,
9630 				 enum bpf_attach_type exp_attach_type,
9631 				 const struct libbpf_prog_handler_opts *opts)
9632 {
9633 	struct bpf_sec_def *sec_def;
9634 
9635 	if (!OPTS_VALID(opts, libbpf_prog_handler_opts))
9636 		return libbpf_err(-EINVAL);
9637 
9638 	if (last_custom_sec_def_handler_id == INT_MAX) /* prevent overflow */
9639 		return libbpf_err(-E2BIG);
9640 
9641 	if (sec) {
9642 		sec_def = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt + 1,
9643 					      sizeof(*sec_def));
9644 		if (!sec_def)
9645 			return libbpf_err(-ENOMEM);
9646 
9647 		custom_sec_defs = sec_def;
9648 		sec_def = &custom_sec_defs[custom_sec_def_cnt];
9649 	} else {
9650 		if (has_custom_fallback_def)
9651 			return libbpf_err(-EBUSY);
9652 
9653 		sec_def = &custom_fallback_def;
9654 	}
9655 
9656 	sec_def->sec = sec ? strdup(sec) : NULL;
9657 	if (sec && !sec_def->sec)
9658 		return libbpf_err(-ENOMEM);
9659 
9660 	sec_def->prog_type = prog_type;
9661 	sec_def->expected_attach_type = exp_attach_type;
9662 	sec_def->cookie = OPTS_GET(opts, cookie, 0);
9663 
9664 	sec_def->prog_setup_fn = OPTS_GET(opts, prog_setup_fn, NULL);
9665 	sec_def->prog_prepare_load_fn = OPTS_GET(opts, prog_prepare_load_fn, NULL);
9666 	sec_def->prog_attach_fn = OPTS_GET(opts, prog_attach_fn, NULL);
9667 
9668 	sec_def->handler_id = ++last_custom_sec_def_handler_id;
9669 
9670 	if (sec)
9671 		custom_sec_def_cnt++;
9672 	else
9673 		has_custom_fallback_def = true;
9674 
9675 	return sec_def->handler_id;
9676 }
9677 
9678 int libbpf_unregister_prog_handler(int handler_id)
9679 {
9680 	struct bpf_sec_def *sec_defs;
9681 	int i;
9682 
9683 	if (handler_id <= 0)
9684 		return libbpf_err(-EINVAL);
9685 
9686 	if (has_custom_fallback_def && custom_fallback_def.handler_id == handler_id) {
9687 		memset(&custom_fallback_def, 0, sizeof(custom_fallback_def));
9688 		has_custom_fallback_def = false;
9689 		return 0;
9690 	}
9691 
9692 	for (i = 0; i < custom_sec_def_cnt; i++) {
9693 		if (custom_sec_defs[i].handler_id == handler_id)
9694 			break;
9695 	}
9696 
9697 	if (i == custom_sec_def_cnt)
9698 		return libbpf_err(-ENOENT);
9699 
9700 	free(custom_sec_defs[i].sec);
9701 	for (i = i + 1; i < custom_sec_def_cnt; i++)
9702 		custom_sec_defs[i - 1] = custom_sec_defs[i];
9703 	custom_sec_def_cnt--;
9704 
9705 	/* try to shrink the array, but it's ok if we couldn't */
9706 	sec_defs = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt, sizeof(*sec_defs));
9707 	/* if new count is zero, reallocarray can return a valid NULL result;
9708 	 * in this case the previous pointer will be freed, so we *have to*
9709 	 * reassign old pointer to the new value (even if it's NULL)
9710 	 */
9711 	if (sec_defs || custom_sec_def_cnt == 0)
9712 		custom_sec_defs = sec_defs;
9713 
9714 	return 0;
9715 }
9716 
9717 static bool sec_def_matches(const struct bpf_sec_def *sec_def, const char *sec_name)
9718 {
9719 	size_t len = strlen(sec_def->sec);
9720 
9721 	/* "type/" always has to have proper SEC("type/extras") form */
9722 	if (sec_def->sec[len - 1] == '/') {
9723 		if (str_has_pfx(sec_name, sec_def->sec))
9724 			return true;
9725 		return false;
9726 	}
9727 
9728 	/* "type+" means it can be either exact SEC("type") or
9729 	 * well-formed SEC("type/extras") with proper '/' separator
9730 	 */
9731 	if (sec_def->sec[len - 1] == '+') {
9732 		len--;
9733 		/* not even a prefix */
9734 		if (strncmp(sec_name, sec_def->sec, len) != 0)
9735 			return false;
9736 		/* exact match or has '/' separator */
9737 		if (sec_name[len] == '\0' || sec_name[len] == '/')
9738 			return true;
9739 		return false;
9740 	}
9741 
9742 	return strcmp(sec_name, sec_def->sec) == 0;
9743 }
9744 
9745 static const struct bpf_sec_def *find_sec_def(const char *sec_name)
9746 {
9747 	const struct bpf_sec_def *sec_def;
9748 	int i, n;
9749 
9750 	n = custom_sec_def_cnt;
9751 	for (i = 0; i < n; i++) {
9752 		sec_def = &custom_sec_defs[i];
9753 		if (sec_def_matches(sec_def, sec_name))
9754 			return sec_def;
9755 	}
9756 
9757 	n = ARRAY_SIZE(section_defs);
9758 	for (i = 0; i < n; i++) {
9759 		sec_def = &section_defs[i];
9760 		if (sec_def_matches(sec_def, sec_name))
9761 			return sec_def;
9762 	}
9763 
9764 	if (has_custom_fallback_def)
9765 		return &custom_fallback_def;
9766 
9767 	return NULL;
9768 }
9769 
9770 #define MAX_TYPE_NAME_SIZE 32
9771 
9772 static char *libbpf_get_type_names(bool attach_type)
9773 {
9774 	int i, len = ARRAY_SIZE(section_defs) * MAX_TYPE_NAME_SIZE;
9775 	char *buf;
9776 
9777 	buf = malloc(len);
9778 	if (!buf)
9779 		return NULL;
9780 
9781 	buf[0] = '\0';
9782 	/* Forge string buf with all available names */
9783 	for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
9784 		const struct bpf_sec_def *sec_def = &section_defs[i];
9785 
9786 		if (attach_type) {
9787 			if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
9788 				continue;
9789 
9790 			if (!(sec_def->cookie & SEC_ATTACHABLE))
9791 				continue;
9792 		}
9793 
9794 		if (strlen(buf) + strlen(section_defs[i].sec) + 2 > len) {
9795 			free(buf);
9796 			return NULL;
9797 		}
9798 		strcat(buf, " ");
9799 		strcat(buf, section_defs[i].sec);
9800 	}
9801 
9802 	return buf;
9803 }
9804 
9805 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
9806 			     enum bpf_attach_type *expected_attach_type)
9807 {
9808 	const struct bpf_sec_def *sec_def;
9809 	char *type_names;
9810 
9811 	if (!name)
9812 		return libbpf_err(-EINVAL);
9813 
9814 	sec_def = find_sec_def(name);
9815 	if (sec_def) {
9816 		*prog_type = sec_def->prog_type;
9817 		*expected_attach_type = sec_def->expected_attach_type;
9818 		return 0;
9819 	}
9820 
9821 	pr_debug("failed to guess program type from ELF section '%s'\n", name);
9822 	type_names = libbpf_get_type_names(false);
9823 	if (type_names != NULL) {
9824 		pr_debug("supported section(type) names are:%s\n", type_names);
9825 		free(type_names);
9826 	}
9827 
9828 	return libbpf_err(-ESRCH);
9829 }
9830 
9831 const char *libbpf_bpf_attach_type_str(enum bpf_attach_type t)
9832 {
9833 	if (t < 0 || t >= ARRAY_SIZE(attach_type_name))
9834 		return NULL;
9835 
9836 	return attach_type_name[t];
9837 }
9838 
9839 const char *libbpf_bpf_link_type_str(enum bpf_link_type t)
9840 {
9841 	if (t < 0 || t >= ARRAY_SIZE(link_type_name))
9842 		return NULL;
9843 
9844 	return link_type_name[t];
9845 }
9846 
9847 const char *libbpf_bpf_map_type_str(enum bpf_map_type t)
9848 {
9849 	if (t < 0 || t >= ARRAY_SIZE(map_type_name))
9850 		return NULL;
9851 
9852 	return map_type_name[t];
9853 }
9854 
9855 const char *libbpf_bpf_prog_type_str(enum bpf_prog_type t)
9856 {
9857 	if (t < 0 || t >= ARRAY_SIZE(prog_type_name))
9858 		return NULL;
9859 
9860 	return prog_type_name[t];
9861 }
9862 
9863 static struct bpf_map *find_struct_ops_map_by_offset(struct bpf_object *obj,
9864 						     int sec_idx,
9865 						     size_t offset)
9866 {
9867 	struct bpf_map *map;
9868 	size_t i;
9869 
9870 	for (i = 0; i < obj->nr_maps; i++) {
9871 		map = &obj->maps[i];
9872 		if (!bpf_map__is_struct_ops(map))
9873 			continue;
9874 		if (map->sec_idx == sec_idx &&
9875 		    map->sec_offset <= offset &&
9876 		    offset - map->sec_offset < map->def.value_size)
9877 			return map;
9878 	}
9879 
9880 	return NULL;
9881 }
9882 
9883 /* Collect the reloc from ELF, populate the st_ops->progs[], and update
9884  * st_ops->data for shadow type.
9885  */
9886 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
9887 					    Elf64_Shdr *shdr, Elf_Data *data)
9888 {
9889 	const struct btf_type *type;
9890 	const struct btf_member *member;
9891 	struct bpf_struct_ops *st_ops;
9892 	struct bpf_program *prog;
9893 	unsigned int shdr_idx;
9894 	const struct btf *btf;
9895 	struct bpf_map *map;
9896 	unsigned int moff, insn_idx;
9897 	const char *name;
9898 	__u32 member_idx;
9899 	Elf64_Sym *sym;
9900 	Elf64_Rel *rel;
9901 	int i, nrels;
9902 
9903 	btf = obj->btf;
9904 	nrels = shdr->sh_size / shdr->sh_entsize;
9905 	for (i = 0; i < nrels; i++) {
9906 		rel = elf_rel_by_idx(data, i);
9907 		if (!rel) {
9908 			pr_warn("struct_ops reloc: failed to get %d reloc\n", i);
9909 			return -LIBBPF_ERRNO__FORMAT;
9910 		}
9911 
9912 		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
9913 		if (!sym) {
9914 			pr_warn("struct_ops reloc: symbol %zx not found\n",
9915 				(size_t)ELF64_R_SYM(rel->r_info));
9916 			return -LIBBPF_ERRNO__FORMAT;
9917 		}
9918 
9919 		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
9920 		map = find_struct_ops_map_by_offset(obj, shdr->sh_info, rel->r_offset);
9921 		if (!map) {
9922 			pr_warn("struct_ops reloc: cannot find map at rel->r_offset %zu\n",
9923 				(size_t)rel->r_offset);
9924 			return -EINVAL;
9925 		}
9926 
9927 		moff = rel->r_offset - map->sec_offset;
9928 		shdr_idx = sym->st_shndx;
9929 		st_ops = map->st_ops;
9930 		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",
9931 			 map->name,
9932 			 (long long)(rel->r_info >> 32),
9933 			 (long long)sym->st_value,
9934 			 shdr_idx, (size_t)rel->r_offset,
9935 			 map->sec_offset, sym->st_name, name);
9936 
9937 		if (shdr_idx >= SHN_LORESERVE) {
9938 			pr_warn("struct_ops reloc %s: rel->r_offset %zu shdr_idx %u unsupported non-static function\n",
9939 				map->name, (size_t)rel->r_offset, shdr_idx);
9940 			return -LIBBPF_ERRNO__RELOC;
9941 		}
9942 		if (sym->st_value % BPF_INSN_SZ) {
9943 			pr_warn("struct_ops reloc %s: invalid target program offset %llu\n",
9944 				map->name, (unsigned long long)sym->st_value);
9945 			return -LIBBPF_ERRNO__FORMAT;
9946 		}
9947 		insn_idx = sym->st_value / BPF_INSN_SZ;
9948 
9949 		type = btf__type_by_id(btf, st_ops->type_id);
9950 		member = find_member_by_offset(type, moff * 8);
9951 		if (!member) {
9952 			pr_warn("struct_ops reloc %s: cannot find member at moff %u\n",
9953 				map->name, moff);
9954 			return -EINVAL;
9955 		}
9956 		member_idx = member - btf_members(type);
9957 		name = btf__name_by_offset(btf, member->name_off);
9958 
9959 		if (!resolve_func_ptr(btf, member->type, NULL)) {
9960 			pr_warn("struct_ops reloc %s: cannot relocate non func ptr %s\n",
9961 				map->name, name);
9962 			return -EINVAL;
9963 		}
9964 
9965 		prog = find_prog_by_sec_insn(obj, shdr_idx, insn_idx);
9966 		if (!prog) {
9967 			pr_warn("struct_ops reloc %s: cannot find prog at shdr_idx %u to relocate func ptr %s\n",
9968 				map->name, shdr_idx, name);
9969 			return -EINVAL;
9970 		}
9971 
9972 		/* prevent the use of BPF prog with invalid type */
9973 		if (prog->type != BPF_PROG_TYPE_STRUCT_OPS) {
9974 			pr_warn("struct_ops reloc %s: prog %s is not struct_ops BPF program\n",
9975 				map->name, prog->name);
9976 			return -EINVAL;
9977 		}
9978 
9979 		st_ops->progs[member_idx] = prog;
9980 
9981 		/* st_ops->data will be exposed to users, being returned by
9982 		 * bpf_map__initial_value() as a pointer to the shadow
9983 		 * type. All function pointers in the original struct type
9984 		 * should be converted to a pointer to struct bpf_program
9985 		 * in the shadow type.
9986 		 */
9987 		*((struct bpf_program **)(st_ops->data + moff)) = prog;
9988 	}
9989 
9990 	return 0;
9991 }
9992 
9993 #define BTF_TRACE_PREFIX "btf_trace_"
9994 #define BTF_LSM_PREFIX "bpf_lsm_"
9995 #define BTF_ITER_PREFIX "bpf_iter_"
9996 #define BTF_MAX_NAME_SIZE 128
9997 
9998 void btf_get_kernel_prefix_kind(enum bpf_attach_type attach_type,
9999 				const char **prefix, int *kind)
10000 {
10001 	switch (attach_type) {
10002 	case BPF_TRACE_RAW_TP:
10003 		*prefix = BTF_TRACE_PREFIX;
10004 		*kind = BTF_KIND_TYPEDEF;
10005 		break;
10006 	case BPF_LSM_MAC:
10007 	case BPF_LSM_CGROUP:
10008 		*prefix = BTF_LSM_PREFIX;
10009 		*kind = BTF_KIND_FUNC;
10010 		break;
10011 	case BPF_TRACE_ITER:
10012 		*prefix = BTF_ITER_PREFIX;
10013 		*kind = BTF_KIND_FUNC;
10014 		break;
10015 	default:
10016 		*prefix = "";
10017 		*kind = BTF_KIND_FUNC;
10018 	}
10019 }
10020 
10021 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
10022 				   const char *name, __u32 kind)
10023 {
10024 	char btf_type_name[BTF_MAX_NAME_SIZE];
10025 	int ret;
10026 
10027 	ret = snprintf(btf_type_name, sizeof(btf_type_name),
10028 		       "%s%s", prefix, name);
10029 	/* snprintf returns the number of characters written excluding the
10030 	 * terminating null. So, if >= BTF_MAX_NAME_SIZE are written, it
10031 	 * indicates truncation.
10032 	 */
10033 	if (ret < 0 || ret >= sizeof(btf_type_name))
10034 		return -ENAMETOOLONG;
10035 	return btf__find_by_name_kind(btf, btf_type_name, kind);
10036 }
10037 
10038 static inline int find_attach_btf_id(struct btf *btf, const char *name,
10039 				     enum bpf_attach_type attach_type)
10040 {
10041 	const char *prefix;
10042 	int kind;
10043 
10044 	btf_get_kernel_prefix_kind(attach_type, &prefix, &kind);
10045 	return find_btf_by_prefix_kind(btf, prefix, name, kind);
10046 }
10047 
10048 int libbpf_find_vmlinux_btf_id(const char *name,
10049 			       enum bpf_attach_type attach_type)
10050 {
10051 	struct btf *btf;
10052 	int err;
10053 
10054 	btf = btf__load_vmlinux_btf();
10055 	err = libbpf_get_error(btf);
10056 	if (err) {
10057 		pr_warn("vmlinux BTF is not found\n");
10058 		return libbpf_err(err);
10059 	}
10060 
10061 	err = find_attach_btf_id(btf, name, attach_type);
10062 	if (err <= 0)
10063 		pr_warn("%s is not found in vmlinux BTF\n", name);
10064 
10065 	btf__free(btf);
10066 	return libbpf_err(err);
10067 }
10068 
10069 static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd, int token_fd)
10070 {
10071 	struct bpf_prog_info info;
10072 	__u32 info_len = sizeof(info);
10073 	struct btf *btf;
10074 	int err;
10075 
10076 	memset(&info, 0, info_len);
10077 	err = bpf_prog_get_info_by_fd(attach_prog_fd, &info, &info_len);
10078 	if (err) {
10079 		pr_warn("failed bpf_prog_get_info_by_fd for FD %d: %s\n",
10080 			attach_prog_fd, errstr(err));
10081 		return err;
10082 	}
10083 
10084 	err = -EINVAL;
10085 	if (!info.btf_id) {
10086 		pr_warn("The target program doesn't have BTF\n");
10087 		goto out;
10088 	}
10089 	btf = btf_load_from_kernel(info.btf_id, NULL, token_fd);
10090 	err = libbpf_get_error(btf);
10091 	if (err) {
10092 		pr_warn("Failed to get BTF %d of the program: %s\n", info.btf_id, errstr(err));
10093 		goto out;
10094 	}
10095 	err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
10096 	btf__free(btf);
10097 	if (err <= 0) {
10098 		pr_warn("%s is not found in prog's BTF\n", name);
10099 		goto out;
10100 	}
10101 out:
10102 	return err;
10103 }
10104 
10105 static int find_kernel_btf_id(struct bpf_object *obj, const char *attach_name,
10106 			      enum bpf_attach_type attach_type,
10107 			      int *btf_obj_fd, int *btf_type_id)
10108 {
10109 	int ret, i, mod_len = 0;
10110 	const char *fn_name, *mod_name = NULL;
10111 
10112 	fn_name = strchr(attach_name, ':');
10113 	if (fn_name) {
10114 		mod_name = attach_name;
10115 		mod_len = fn_name - mod_name;
10116 		fn_name++;
10117 	}
10118 
10119 	if (!mod_name || strncmp(mod_name, "vmlinux", mod_len) == 0) {
10120 		ret = find_attach_btf_id(obj->btf_vmlinux,
10121 					 mod_name ? fn_name : attach_name,
10122 					 attach_type);
10123 		if (ret > 0) {
10124 			*btf_obj_fd = 0; /* vmlinux BTF */
10125 			*btf_type_id = ret;
10126 			return 0;
10127 		}
10128 		if (ret != -ENOENT)
10129 			return ret;
10130 	}
10131 
10132 	ret = load_module_btfs(obj);
10133 	if (ret)
10134 		return ret;
10135 
10136 	for (i = 0; i < obj->btf_module_cnt; i++) {
10137 		const struct module_btf *mod = &obj->btf_modules[i];
10138 
10139 		if (mod_name && strncmp(mod->name, mod_name, mod_len) != 0)
10140 			continue;
10141 
10142 		ret = find_attach_btf_id(mod->btf,
10143 					 mod_name ? fn_name : attach_name,
10144 					 attach_type);
10145 		if (ret > 0) {
10146 			*btf_obj_fd = mod->fd;
10147 			*btf_type_id = ret;
10148 			return 0;
10149 		}
10150 		if (ret == -ENOENT)
10151 			continue;
10152 
10153 		return ret;
10154 	}
10155 
10156 	return -ESRCH;
10157 }
10158 
10159 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
10160 				     int *btf_obj_fd, int *btf_type_id)
10161 {
10162 	enum bpf_attach_type attach_type = prog->expected_attach_type;
10163 	__u32 attach_prog_fd = prog->attach_prog_fd;
10164 	int err = 0;
10165 
10166 	/* BPF program's BTF ID */
10167 	if (prog->type == BPF_PROG_TYPE_EXT || attach_prog_fd) {
10168 		if (!attach_prog_fd) {
10169 			pr_warn("prog '%s': attach program FD is not set\n", prog->name);
10170 			return -EINVAL;
10171 		}
10172 		err = libbpf_find_prog_btf_id(attach_name, attach_prog_fd, prog->obj->token_fd);
10173 		if (err < 0) {
10174 			pr_warn("prog '%s': failed to find BPF program (FD %d) BTF ID for '%s': %s\n",
10175 				prog->name, attach_prog_fd, attach_name, errstr(err));
10176 			return err;
10177 		}
10178 		*btf_obj_fd = 0;
10179 		*btf_type_id = err;
10180 		return 0;
10181 	}
10182 
10183 	/* kernel/module BTF ID */
10184 	if (prog->obj->gen_loader) {
10185 		bpf_gen__record_attach_target(prog->obj->gen_loader, attach_name, attach_type);
10186 		*btf_obj_fd = 0;
10187 		*btf_type_id = 1;
10188 	} else {
10189 		err = find_kernel_btf_id(prog->obj, attach_name,
10190 					 attach_type, btf_obj_fd,
10191 					 btf_type_id);
10192 	}
10193 	if (err) {
10194 		pr_warn("prog '%s': failed to find kernel BTF type ID of '%s': %s\n",
10195 			prog->name, attach_name, errstr(err));
10196 		return err;
10197 	}
10198 	return 0;
10199 }
10200 
10201 int libbpf_attach_type_by_name(const char *name,
10202 			       enum bpf_attach_type *attach_type)
10203 {
10204 	char *type_names;
10205 	const struct bpf_sec_def *sec_def;
10206 
10207 	if (!name)
10208 		return libbpf_err(-EINVAL);
10209 
10210 	sec_def = find_sec_def(name);
10211 	if (!sec_def) {
10212 		pr_debug("failed to guess attach type based on ELF section name '%s'\n", name);
10213 		type_names = libbpf_get_type_names(true);
10214 		if (type_names != NULL) {
10215 			pr_debug("attachable section(type) names are:%s\n", type_names);
10216 			free(type_names);
10217 		}
10218 
10219 		return libbpf_err(-EINVAL);
10220 	}
10221 
10222 	if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
10223 		return libbpf_err(-EINVAL);
10224 	if (!(sec_def->cookie & SEC_ATTACHABLE))
10225 		return libbpf_err(-EINVAL);
10226 
10227 	*attach_type = sec_def->expected_attach_type;
10228 	return 0;
10229 }
10230 
10231 int bpf_map__fd(const struct bpf_map *map)
10232 {
10233 	if (!map)
10234 		return libbpf_err(-EINVAL);
10235 	if (!map_is_created(map))
10236 		return -1;
10237 	return map->fd;
10238 }
10239 
10240 static bool map_uses_real_name(const struct bpf_map *map)
10241 {
10242 	/* Since libbpf started to support custom .data.* and .rodata.* maps,
10243 	 * their user-visible name differs from kernel-visible name. Users see
10244 	 * such map's corresponding ELF section name as a map name.
10245 	 * This check distinguishes .data/.rodata from .data.* and .rodata.*
10246 	 * maps to know which name has to be returned to the user.
10247 	 */
10248 	if (map->libbpf_type == LIBBPF_MAP_DATA && strcmp(map->real_name, DATA_SEC) != 0)
10249 		return true;
10250 	if (map->libbpf_type == LIBBPF_MAP_RODATA && strcmp(map->real_name, RODATA_SEC) != 0)
10251 		return true;
10252 	return false;
10253 }
10254 
10255 const char *bpf_map__name(const struct bpf_map *map)
10256 {
10257 	if (!map)
10258 		return NULL;
10259 
10260 	if (map_uses_real_name(map))
10261 		return map->real_name;
10262 
10263 	return map->name;
10264 }
10265 
10266 enum bpf_map_type bpf_map__type(const struct bpf_map *map)
10267 {
10268 	return map->def.type;
10269 }
10270 
10271 int bpf_map__set_type(struct bpf_map *map, enum bpf_map_type type)
10272 {
10273 	if (map_is_created(map))
10274 		return libbpf_err(-EBUSY);
10275 	map->def.type = type;
10276 	return 0;
10277 }
10278 
10279 __u32 bpf_map__map_flags(const struct bpf_map *map)
10280 {
10281 	return map->def.map_flags;
10282 }
10283 
10284 int bpf_map__set_map_flags(struct bpf_map *map, __u32 flags)
10285 {
10286 	if (map_is_created(map))
10287 		return libbpf_err(-EBUSY);
10288 	map->def.map_flags = flags;
10289 	return 0;
10290 }
10291 
10292 __u64 bpf_map__map_extra(const struct bpf_map *map)
10293 {
10294 	return map->map_extra;
10295 }
10296 
10297 int bpf_map__set_map_extra(struct bpf_map *map, __u64 map_extra)
10298 {
10299 	if (map_is_created(map))
10300 		return libbpf_err(-EBUSY);
10301 	map->map_extra = map_extra;
10302 	return 0;
10303 }
10304 
10305 __u32 bpf_map__numa_node(const struct bpf_map *map)
10306 {
10307 	return map->numa_node;
10308 }
10309 
10310 int bpf_map__set_numa_node(struct bpf_map *map, __u32 numa_node)
10311 {
10312 	if (map_is_created(map))
10313 		return libbpf_err(-EBUSY);
10314 	map->numa_node = numa_node;
10315 	return 0;
10316 }
10317 
10318 __u32 bpf_map__key_size(const struct bpf_map *map)
10319 {
10320 	return map->def.key_size;
10321 }
10322 
10323 int bpf_map__set_key_size(struct bpf_map *map, __u32 size)
10324 {
10325 	if (map_is_created(map))
10326 		return libbpf_err(-EBUSY);
10327 	map->def.key_size = size;
10328 	return 0;
10329 }
10330 
10331 __u32 bpf_map__value_size(const struct bpf_map *map)
10332 {
10333 	return map->def.value_size;
10334 }
10335 
10336 static int map_btf_datasec_resize(struct bpf_map *map, __u32 size)
10337 {
10338 	struct btf *btf;
10339 	struct btf_type *datasec_type, *var_type;
10340 	struct btf_var_secinfo *var;
10341 	const struct btf_type *array_type;
10342 	const struct btf_array *array;
10343 	int vlen, element_sz, new_array_id;
10344 	__u32 nr_elements;
10345 
10346 	/* check btf existence */
10347 	btf = bpf_object__btf(map->obj);
10348 	if (!btf)
10349 		return -ENOENT;
10350 
10351 	/* verify map is datasec */
10352 	datasec_type = btf_type_by_id(btf, bpf_map__btf_value_type_id(map));
10353 	if (!btf_is_datasec(datasec_type)) {
10354 		pr_warn("map '%s': cannot be resized, map value type is not a datasec\n",
10355 			bpf_map__name(map));
10356 		return -EINVAL;
10357 	}
10358 
10359 	/* verify datasec has at least one var */
10360 	vlen = btf_vlen(datasec_type);
10361 	if (vlen == 0) {
10362 		pr_warn("map '%s': cannot be resized, map value datasec is empty\n",
10363 			bpf_map__name(map));
10364 		return -EINVAL;
10365 	}
10366 
10367 	/* verify last var in the datasec is an array */
10368 	var = &btf_var_secinfos(datasec_type)[vlen - 1];
10369 	var_type = btf_type_by_id(btf, var->type);
10370 	array_type = skip_mods_and_typedefs(btf, var_type->type, NULL);
10371 	if (!btf_is_array(array_type)) {
10372 		pr_warn("map '%s': cannot be resized, last var must be an array\n",
10373 			bpf_map__name(map));
10374 		return -EINVAL;
10375 	}
10376 
10377 	/* verify request size aligns with array */
10378 	array = btf_array(array_type);
10379 	element_sz = btf__resolve_size(btf, array->type);
10380 	if (element_sz <= 0 || (size - var->offset) % element_sz != 0) {
10381 		pr_warn("map '%s': cannot be resized, element size (%d) doesn't align with new total size (%u)\n",
10382 			bpf_map__name(map), element_sz, size);
10383 		return -EINVAL;
10384 	}
10385 
10386 	/* create a new array based on the existing array, but with new length */
10387 	nr_elements = (size - var->offset) / element_sz;
10388 	new_array_id = btf__add_array(btf, array->index_type, array->type, nr_elements);
10389 	if (new_array_id < 0)
10390 		return new_array_id;
10391 
10392 	/* adding a new btf type invalidates existing pointers to btf objects,
10393 	 * so refresh pointers before proceeding
10394 	 */
10395 	datasec_type = btf_type_by_id(btf, map->btf_value_type_id);
10396 	var = &btf_var_secinfos(datasec_type)[vlen - 1];
10397 	var_type = btf_type_by_id(btf, var->type);
10398 
10399 	/* finally update btf info */
10400 	datasec_type->size = size;
10401 	var->size = size - var->offset;
10402 	var_type->type = new_array_id;
10403 
10404 	return 0;
10405 }
10406 
10407 int bpf_map__set_value_size(struct bpf_map *map, __u32 size)
10408 {
10409 	if (map_is_created(map))
10410 		return libbpf_err(-EBUSY);
10411 
10412 	if (map->mmaped) {
10413 		size_t mmap_old_sz, mmap_new_sz;
10414 		int err;
10415 
10416 		if (map->def.type != BPF_MAP_TYPE_ARRAY)
10417 			return libbpf_err(-EOPNOTSUPP);
10418 
10419 		mmap_old_sz = bpf_map_mmap_sz(map);
10420 		mmap_new_sz = array_map_mmap_sz(size, map->def.max_entries);
10421 		err = bpf_map_mmap_resize(map, mmap_old_sz, mmap_new_sz);
10422 		if (err) {
10423 			pr_warn("map '%s': failed to resize memory-mapped region: %s\n",
10424 				bpf_map__name(map), errstr(err));
10425 			return libbpf_err(err);
10426 		}
10427 		err = map_btf_datasec_resize(map, size);
10428 		if (err && err != -ENOENT) {
10429 			pr_warn("map '%s': failed to adjust resized BTF, clearing BTF key/value info: %s\n",
10430 				bpf_map__name(map), errstr(err));
10431 			map->btf_value_type_id = 0;
10432 			map->btf_key_type_id = 0;
10433 		}
10434 	}
10435 
10436 	map->def.value_size = size;
10437 	return 0;
10438 }
10439 
10440 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
10441 {
10442 	return map ? map->btf_key_type_id : 0;
10443 }
10444 
10445 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
10446 {
10447 	return map ? map->btf_value_type_id : 0;
10448 }
10449 
10450 int bpf_map__set_initial_value(struct bpf_map *map,
10451 			       const void *data, size_t size)
10452 {
10453 	size_t actual_sz;
10454 
10455 	if (map_is_created(map))
10456 		return libbpf_err(-EBUSY);
10457 
10458 	if (!map->mmaped || map->libbpf_type == LIBBPF_MAP_KCONFIG)
10459 		return libbpf_err(-EINVAL);
10460 
10461 	if (map->def.type == BPF_MAP_TYPE_ARENA)
10462 		actual_sz = map->obj->arena_data_sz;
10463 	else
10464 		actual_sz = map->def.value_size;
10465 	if (size != actual_sz)
10466 		return libbpf_err(-EINVAL);
10467 
10468 	memcpy(map->mmaped, data, size);
10469 	return 0;
10470 }
10471 
10472 void *bpf_map__initial_value(const struct bpf_map *map, size_t *psize)
10473 {
10474 	if (bpf_map__is_struct_ops(map)) {
10475 		if (psize)
10476 			*psize = map->def.value_size;
10477 		return map->st_ops->data;
10478 	}
10479 
10480 	if (!map->mmaped)
10481 		return NULL;
10482 
10483 	if (map->def.type == BPF_MAP_TYPE_ARENA)
10484 		*psize = map->obj->arena_data_sz;
10485 	else
10486 		*psize = map->def.value_size;
10487 
10488 	return map->mmaped;
10489 }
10490 
10491 bool bpf_map__is_internal(const struct bpf_map *map)
10492 {
10493 	return map->libbpf_type != LIBBPF_MAP_UNSPEC;
10494 }
10495 
10496 __u32 bpf_map__ifindex(const struct bpf_map *map)
10497 {
10498 	return map->map_ifindex;
10499 }
10500 
10501 int bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
10502 {
10503 	if (map_is_created(map))
10504 		return libbpf_err(-EBUSY);
10505 	map->map_ifindex = ifindex;
10506 	return 0;
10507 }
10508 
10509 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
10510 {
10511 	if (!bpf_map_type__is_map_in_map(map->def.type)) {
10512 		pr_warn("error: unsupported map type\n");
10513 		return libbpf_err(-EINVAL);
10514 	}
10515 	if (map->inner_map_fd != -1) {
10516 		pr_warn("error: inner_map_fd already specified\n");
10517 		return libbpf_err(-EINVAL);
10518 	}
10519 	if (map->inner_map) {
10520 		bpf_map__destroy(map->inner_map);
10521 		zfree(&map->inner_map);
10522 	}
10523 	map->inner_map_fd = fd;
10524 	return 0;
10525 }
10526 
10527 static struct bpf_map *
10528 __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
10529 {
10530 	ssize_t idx;
10531 	struct bpf_map *s, *e;
10532 
10533 	if (!obj || !obj->maps)
10534 		return errno = EINVAL, NULL;
10535 
10536 	s = obj->maps;
10537 	e = obj->maps + obj->nr_maps;
10538 
10539 	if ((m < s) || (m >= e)) {
10540 		pr_warn("error in %s: map handler doesn't belong to object\n",
10541 			 __func__);
10542 		return errno = EINVAL, NULL;
10543 	}
10544 
10545 	idx = (m - obj->maps) + i;
10546 	if (idx >= obj->nr_maps || idx < 0)
10547 		return NULL;
10548 	return &obj->maps[idx];
10549 }
10550 
10551 struct bpf_map *
10552 bpf_object__next_map(const struct bpf_object *obj, const struct bpf_map *prev)
10553 {
10554 	if (prev == NULL && obj != NULL)
10555 		return obj->maps;
10556 
10557 	return __bpf_map__iter(prev, obj, 1);
10558 }
10559 
10560 struct bpf_map *
10561 bpf_object__prev_map(const struct bpf_object *obj, const struct bpf_map *next)
10562 {
10563 	if (next == NULL && obj != NULL) {
10564 		if (!obj->nr_maps)
10565 			return NULL;
10566 		return obj->maps + obj->nr_maps - 1;
10567 	}
10568 
10569 	return __bpf_map__iter(next, obj, -1);
10570 }
10571 
10572 struct bpf_map *
10573 bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
10574 {
10575 	struct bpf_map *pos;
10576 
10577 	bpf_object__for_each_map(pos, obj) {
10578 		/* if it's a special internal map name (which always starts
10579 		 * with dot) then check if that special name matches the
10580 		 * real map name (ELF section name)
10581 		 */
10582 		if (name[0] == '.') {
10583 			if (pos->real_name && strcmp(pos->real_name, name) == 0)
10584 				return pos;
10585 			continue;
10586 		}
10587 		/* otherwise map name has to be an exact match */
10588 		if (map_uses_real_name(pos)) {
10589 			if (strcmp(pos->real_name, name) == 0)
10590 				return pos;
10591 			continue;
10592 		}
10593 		if (strcmp(pos->name, name) == 0)
10594 			return pos;
10595 	}
10596 	return errno = ENOENT, NULL;
10597 }
10598 
10599 int
10600 bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
10601 {
10602 	return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
10603 }
10604 
10605 static int validate_map_op(const struct bpf_map *map, size_t key_sz,
10606 			   size_t value_sz, bool check_value_sz)
10607 {
10608 	if (!map_is_created(map)) /* map is not yet created */
10609 		return -ENOENT;
10610 
10611 	if (map->def.key_size != key_sz) {
10612 		pr_warn("map '%s': unexpected key size %zu provided, expected %u\n",
10613 			map->name, key_sz, map->def.key_size);
10614 		return -EINVAL;
10615 	}
10616 
10617 	if (map->fd < 0) {
10618 		pr_warn("map '%s': can't use BPF map without FD (was it created?)\n", map->name);
10619 		return -EINVAL;
10620 	}
10621 
10622 	if (!check_value_sz)
10623 		return 0;
10624 
10625 	switch (map->def.type) {
10626 	case BPF_MAP_TYPE_PERCPU_ARRAY:
10627 	case BPF_MAP_TYPE_PERCPU_HASH:
10628 	case BPF_MAP_TYPE_LRU_PERCPU_HASH:
10629 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: {
10630 		int num_cpu = libbpf_num_possible_cpus();
10631 		size_t elem_sz = roundup(map->def.value_size, 8);
10632 
10633 		if (value_sz != num_cpu * elem_sz) {
10634 			pr_warn("map '%s': unexpected value size %zu provided for per-CPU map, expected %d * %zu = %zd\n",
10635 				map->name, value_sz, num_cpu, elem_sz, num_cpu * elem_sz);
10636 			return -EINVAL;
10637 		}
10638 		break;
10639 	}
10640 	default:
10641 		if (map->def.value_size != value_sz) {
10642 			pr_warn("map '%s': unexpected value size %zu provided, expected %u\n",
10643 				map->name, value_sz, map->def.value_size);
10644 			return -EINVAL;
10645 		}
10646 		break;
10647 	}
10648 	return 0;
10649 }
10650 
10651 int bpf_map__lookup_elem(const struct bpf_map *map,
10652 			 const void *key, size_t key_sz,
10653 			 void *value, size_t value_sz, __u64 flags)
10654 {
10655 	int err;
10656 
10657 	err = validate_map_op(map, key_sz, value_sz, true);
10658 	if (err)
10659 		return libbpf_err(err);
10660 
10661 	return bpf_map_lookup_elem_flags(map->fd, key, value, flags);
10662 }
10663 
10664 int bpf_map__update_elem(const struct bpf_map *map,
10665 			 const void *key, size_t key_sz,
10666 			 const void *value, size_t value_sz, __u64 flags)
10667 {
10668 	int err;
10669 
10670 	err = validate_map_op(map, key_sz, value_sz, true);
10671 	if (err)
10672 		return libbpf_err(err);
10673 
10674 	return bpf_map_update_elem(map->fd, key, value, flags);
10675 }
10676 
10677 int bpf_map__delete_elem(const struct bpf_map *map,
10678 			 const void *key, size_t key_sz, __u64 flags)
10679 {
10680 	int err;
10681 
10682 	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */);
10683 	if (err)
10684 		return libbpf_err(err);
10685 
10686 	return bpf_map_delete_elem_flags(map->fd, key, flags);
10687 }
10688 
10689 int bpf_map__lookup_and_delete_elem(const struct bpf_map *map,
10690 				    const void *key, size_t key_sz,
10691 				    void *value, size_t value_sz, __u64 flags)
10692 {
10693 	int err;
10694 
10695 	err = validate_map_op(map, key_sz, value_sz, true);
10696 	if (err)
10697 		return libbpf_err(err);
10698 
10699 	return bpf_map_lookup_and_delete_elem_flags(map->fd, key, value, flags);
10700 }
10701 
10702 int bpf_map__get_next_key(const struct bpf_map *map,
10703 			  const void *cur_key, void *next_key, size_t key_sz)
10704 {
10705 	int err;
10706 
10707 	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */);
10708 	if (err)
10709 		return libbpf_err(err);
10710 
10711 	return bpf_map_get_next_key(map->fd, cur_key, next_key);
10712 }
10713 
10714 long libbpf_get_error(const void *ptr)
10715 {
10716 	if (!IS_ERR_OR_NULL(ptr))
10717 		return 0;
10718 
10719 	if (IS_ERR(ptr))
10720 		errno = -PTR_ERR(ptr);
10721 
10722 	/* If ptr == NULL, then errno should be already set by the failing
10723 	 * API, because libbpf never returns NULL on success and it now always
10724 	 * sets errno on error. So no extra errno handling for ptr == NULL
10725 	 * case.
10726 	 */
10727 	return -errno;
10728 }
10729 
10730 /* Replace link's underlying BPF program with the new one */
10731 int bpf_link__update_program(struct bpf_link *link, struct bpf_program *prog)
10732 {
10733 	int ret;
10734 	int prog_fd = bpf_program__fd(prog);
10735 
10736 	if (prog_fd < 0) {
10737 		pr_warn("prog '%s': can't use BPF program without FD (was it loaded?)\n",
10738 			prog->name);
10739 		return libbpf_err(-EINVAL);
10740 	}
10741 
10742 	ret = bpf_link_update(bpf_link__fd(link), prog_fd, NULL);
10743 	return libbpf_err_errno(ret);
10744 }
10745 
10746 /* Release "ownership" of underlying BPF resource (typically, BPF program
10747  * attached to some BPF hook, e.g., tracepoint, kprobe, etc). Disconnected
10748  * link, when destructed through bpf_link__destroy() call won't attempt to
10749  * detach/unregisted that BPF resource. This is useful in situations where,
10750  * say, attached BPF program has to outlive userspace program that attached it
10751  * in the system. Depending on type of BPF program, though, there might be
10752  * additional steps (like pinning BPF program in BPF FS) necessary to ensure
10753  * exit of userspace program doesn't trigger automatic detachment and clean up
10754  * inside the kernel.
10755  */
10756 void bpf_link__disconnect(struct bpf_link *link)
10757 {
10758 	link->disconnected = true;
10759 }
10760 
10761 int bpf_link__destroy(struct bpf_link *link)
10762 {
10763 	int err = 0;
10764 
10765 	if (IS_ERR_OR_NULL(link))
10766 		return 0;
10767 
10768 	if (!link->disconnected && link->detach)
10769 		err = link->detach(link);
10770 	if (link->pin_path)
10771 		free(link->pin_path);
10772 	if (link->dealloc)
10773 		link->dealloc(link);
10774 	else
10775 		free(link);
10776 
10777 	return libbpf_err(err);
10778 }
10779 
10780 int bpf_link__fd(const struct bpf_link *link)
10781 {
10782 	return link->fd;
10783 }
10784 
10785 const char *bpf_link__pin_path(const struct bpf_link *link)
10786 {
10787 	return link->pin_path;
10788 }
10789 
10790 static int bpf_link__detach_fd(struct bpf_link *link)
10791 {
10792 	return libbpf_err_errno(close(link->fd));
10793 }
10794 
10795 struct bpf_link *bpf_link__open(const char *path)
10796 {
10797 	struct bpf_link *link;
10798 	int fd;
10799 
10800 	fd = bpf_obj_get(path);
10801 	if (fd < 0) {
10802 		fd = -errno;
10803 		pr_warn("failed to open link at %s: %d\n", path, fd);
10804 		return libbpf_err_ptr(fd);
10805 	}
10806 
10807 	link = calloc(1, sizeof(*link));
10808 	if (!link) {
10809 		close(fd);
10810 		return libbpf_err_ptr(-ENOMEM);
10811 	}
10812 	link->detach = &bpf_link__detach_fd;
10813 	link->fd = fd;
10814 
10815 	link->pin_path = strdup(path);
10816 	if (!link->pin_path) {
10817 		bpf_link__destroy(link);
10818 		return libbpf_err_ptr(-ENOMEM);
10819 	}
10820 
10821 	return link;
10822 }
10823 
10824 int bpf_link__detach(struct bpf_link *link)
10825 {
10826 	return bpf_link_detach(link->fd) ? -errno : 0;
10827 }
10828 
10829 int bpf_link__pin(struct bpf_link *link, const char *path)
10830 {
10831 	int err;
10832 
10833 	if (link->pin_path)
10834 		return libbpf_err(-EBUSY);
10835 	err = make_parent_dir(path);
10836 	if (err)
10837 		return libbpf_err(err);
10838 	err = check_path(path);
10839 	if (err)
10840 		return libbpf_err(err);
10841 
10842 	link->pin_path = strdup(path);
10843 	if (!link->pin_path)
10844 		return libbpf_err(-ENOMEM);
10845 
10846 	if (bpf_obj_pin(link->fd, link->pin_path)) {
10847 		err = -errno;
10848 		zfree(&link->pin_path);
10849 		return libbpf_err(err);
10850 	}
10851 
10852 	pr_debug("link fd=%d: pinned at %s\n", link->fd, link->pin_path);
10853 	return 0;
10854 }
10855 
10856 int bpf_link__unpin(struct bpf_link *link)
10857 {
10858 	int err;
10859 
10860 	if (!link->pin_path)
10861 		return libbpf_err(-EINVAL);
10862 
10863 	err = unlink(link->pin_path);
10864 	if (err != 0)
10865 		return -errno;
10866 
10867 	pr_debug("link fd=%d: unpinned from %s\n", link->fd, link->pin_path);
10868 	zfree(&link->pin_path);
10869 	return 0;
10870 }
10871 
10872 struct bpf_link_perf {
10873 	struct bpf_link link;
10874 	int perf_event_fd;
10875 	/* legacy kprobe support: keep track of probe identifier and type */
10876 	char *legacy_probe_name;
10877 	bool legacy_is_kprobe;
10878 	bool legacy_is_retprobe;
10879 };
10880 
10881 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe);
10882 static int remove_uprobe_event_legacy(const char *probe_name, bool retprobe);
10883 
10884 static int bpf_link_perf_detach(struct bpf_link *link)
10885 {
10886 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10887 	int err = 0;
10888 
10889 	if (ioctl(perf_link->perf_event_fd, PERF_EVENT_IOC_DISABLE, 0) < 0)
10890 		err = -errno;
10891 
10892 	if (perf_link->perf_event_fd != link->fd)
10893 		close(perf_link->perf_event_fd);
10894 	close(link->fd);
10895 
10896 	/* legacy uprobe/kprobe needs to be removed after perf event fd closure */
10897 	if (perf_link->legacy_probe_name) {
10898 		if (perf_link->legacy_is_kprobe) {
10899 			err = remove_kprobe_event_legacy(perf_link->legacy_probe_name,
10900 							 perf_link->legacy_is_retprobe);
10901 		} else {
10902 			err = remove_uprobe_event_legacy(perf_link->legacy_probe_name,
10903 							 perf_link->legacy_is_retprobe);
10904 		}
10905 	}
10906 
10907 	return err;
10908 }
10909 
10910 static void bpf_link_perf_dealloc(struct bpf_link *link)
10911 {
10912 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10913 
10914 	free(perf_link->legacy_probe_name);
10915 	free(perf_link);
10916 }
10917 
10918 struct bpf_link *bpf_program__attach_perf_event_opts(const struct bpf_program *prog, int pfd,
10919 						     const struct bpf_perf_event_opts *opts)
10920 {
10921 	struct bpf_link_perf *link;
10922 	int prog_fd, link_fd = -1, err;
10923 	bool force_ioctl_attach;
10924 
10925 	if (!OPTS_VALID(opts, bpf_perf_event_opts))
10926 		return libbpf_err_ptr(-EINVAL);
10927 
10928 	if (pfd < 0) {
10929 		pr_warn("prog '%s': invalid perf event FD %d\n",
10930 			prog->name, pfd);
10931 		return libbpf_err_ptr(-EINVAL);
10932 	}
10933 	prog_fd = bpf_program__fd(prog);
10934 	if (prog_fd < 0) {
10935 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
10936 			prog->name);
10937 		return libbpf_err_ptr(-EINVAL);
10938 	}
10939 
10940 	link = calloc(1, sizeof(*link));
10941 	if (!link)
10942 		return libbpf_err_ptr(-ENOMEM);
10943 	link->link.detach = &bpf_link_perf_detach;
10944 	link->link.dealloc = &bpf_link_perf_dealloc;
10945 	link->perf_event_fd = pfd;
10946 
10947 	force_ioctl_attach = OPTS_GET(opts, force_ioctl_attach, false);
10948 	if (kernel_supports(prog->obj, FEAT_PERF_LINK) && !force_ioctl_attach) {
10949 		DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_opts,
10950 			.perf_event.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0));
10951 
10952 		link_fd = bpf_link_create(prog_fd, pfd, BPF_PERF_EVENT, &link_opts);
10953 		if (link_fd < 0) {
10954 			err = -errno;
10955 			pr_warn("prog '%s': failed to create BPF link for perf_event FD %d: %s\n",
10956 				prog->name, pfd, errstr(err));
10957 			goto err_out;
10958 		}
10959 		link->link.fd = link_fd;
10960 	} else {
10961 		if (OPTS_GET(opts, bpf_cookie, 0)) {
10962 			pr_warn("prog '%s': user context value is not supported\n", prog->name);
10963 			err = -EOPNOTSUPP;
10964 			goto err_out;
10965 		}
10966 
10967 		if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
10968 			err = -errno;
10969 			pr_warn("prog '%s': failed to attach to perf_event FD %d: %s\n",
10970 				prog->name, pfd, errstr(err));
10971 			if (err == -EPROTO)
10972 				pr_warn("prog '%s': try add PERF_SAMPLE_CALLCHAIN to or remove exclude_callchain_[kernel|user] from pfd %d\n",
10973 					prog->name, pfd);
10974 			goto err_out;
10975 		}
10976 		link->link.fd = pfd;
10977 	}
10978 
10979 	if (!OPTS_GET(opts, dont_enable, false)) {
10980 		if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
10981 			err = -errno;
10982 			pr_warn("prog '%s': failed to enable perf_event FD %d: %s\n",
10983 				prog->name, pfd, errstr(err));
10984 			goto err_out;
10985 		}
10986 	}
10987 
10988 	return &link->link;
10989 err_out:
10990 	if (link_fd >= 0)
10991 		close(link_fd);
10992 	free(link);
10993 	return libbpf_err_ptr(err);
10994 }
10995 
10996 struct bpf_link *bpf_program__attach_perf_event(const struct bpf_program *prog, int pfd)
10997 {
10998 	return bpf_program__attach_perf_event_opts(prog, pfd, NULL);
10999 }
11000 
11001 /*
11002  * this function is expected to parse integer in the range of [0, 2^31-1] from
11003  * given file using scanf format string fmt. If actual parsed value is
11004  * negative, the result might be indistinguishable from error
11005  */
11006 static int parse_uint_from_file(const char *file, const char *fmt)
11007 {
11008 	int err, ret;
11009 	FILE *f;
11010 
11011 	f = fopen(file, "re");
11012 	if (!f) {
11013 		err = -errno;
11014 		pr_debug("failed to open '%s': %s\n", file, errstr(err));
11015 		return err;
11016 	}
11017 	err = fscanf(f, fmt, &ret);
11018 	if (err != 1) {
11019 		err = err == EOF ? -EIO : -errno;
11020 		pr_debug("failed to parse '%s': %s\n", file, errstr(err));
11021 		fclose(f);
11022 		return err;
11023 	}
11024 	fclose(f);
11025 	return ret;
11026 }
11027 
11028 static int determine_kprobe_perf_type(void)
11029 {
11030 	const char *file = "/sys/bus/event_source/devices/kprobe/type";
11031 
11032 	return parse_uint_from_file(file, "%d\n");
11033 }
11034 
11035 static int determine_uprobe_perf_type(void)
11036 {
11037 	const char *file = "/sys/bus/event_source/devices/uprobe/type";
11038 
11039 	return parse_uint_from_file(file, "%d\n");
11040 }
11041 
11042 static int determine_kprobe_retprobe_bit(void)
11043 {
11044 	const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
11045 
11046 	return parse_uint_from_file(file, "config:%d\n");
11047 }
11048 
11049 static int determine_uprobe_retprobe_bit(void)
11050 {
11051 	const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
11052 
11053 	return parse_uint_from_file(file, "config:%d\n");
11054 }
11055 
11056 #define PERF_UPROBE_REF_CTR_OFFSET_BITS 32
11057 #define PERF_UPROBE_REF_CTR_OFFSET_SHIFT 32
11058 
11059 static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
11060 				 uint64_t offset, int pid, size_t ref_ctr_off)
11061 {
11062 	const size_t attr_sz = sizeof(struct perf_event_attr);
11063 	struct perf_event_attr attr;
11064 	int type, pfd;
11065 
11066 	if ((__u64)ref_ctr_off >= (1ULL << PERF_UPROBE_REF_CTR_OFFSET_BITS))
11067 		return -EINVAL;
11068 
11069 	memset(&attr, 0, attr_sz);
11070 
11071 	type = uprobe ? determine_uprobe_perf_type()
11072 		      : determine_kprobe_perf_type();
11073 	if (type < 0) {
11074 		pr_warn("failed to determine %s perf type: %s\n",
11075 			uprobe ? "uprobe" : "kprobe",
11076 			errstr(type));
11077 		return type;
11078 	}
11079 	if (retprobe) {
11080 		int bit = uprobe ? determine_uprobe_retprobe_bit()
11081 				 : determine_kprobe_retprobe_bit();
11082 
11083 		if (bit < 0) {
11084 			pr_warn("failed to determine %s retprobe bit: %s\n",
11085 				uprobe ? "uprobe" : "kprobe",
11086 				errstr(bit));
11087 			return bit;
11088 		}
11089 		attr.config |= 1 << bit;
11090 	}
11091 	attr.size = attr_sz;
11092 	attr.type = type;
11093 	attr.config |= (__u64)ref_ctr_off << PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
11094 	attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
11095 	attr.config2 = offset;		 /* kprobe_addr or probe_offset */
11096 
11097 	/* pid filter is meaningful only for uprobes */
11098 	pfd = syscall(__NR_perf_event_open, &attr,
11099 		      pid < 0 ? -1 : pid /* pid */,
11100 		      pid == -1 ? 0 : -1 /* cpu */,
11101 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
11102 	return pfd >= 0 ? pfd : -errno;
11103 }
11104 
11105 static int append_to_file(const char *file, const char *fmt, ...)
11106 {
11107 	int fd, n, err = 0;
11108 	va_list ap;
11109 	char buf[1024];
11110 
11111 	va_start(ap, fmt);
11112 	n = vsnprintf(buf, sizeof(buf), fmt, ap);
11113 	va_end(ap);
11114 
11115 	if (n < 0 || n >= sizeof(buf))
11116 		return -EINVAL;
11117 
11118 	fd = open(file, O_WRONLY | O_APPEND | O_CLOEXEC, 0);
11119 	if (fd < 0)
11120 		return -errno;
11121 
11122 	if (write(fd, buf, n) < 0)
11123 		err = -errno;
11124 
11125 	close(fd);
11126 	return err;
11127 }
11128 
11129 #define DEBUGFS "/sys/kernel/debug/tracing"
11130 #define TRACEFS "/sys/kernel/tracing"
11131 
11132 static bool use_debugfs(void)
11133 {
11134 	static int has_debugfs = -1;
11135 
11136 	if (has_debugfs < 0)
11137 		has_debugfs = faccessat(AT_FDCWD, DEBUGFS, F_OK, AT_EACCESS) == 0;
11138 
11139 	return has_debugfs == 1;
11140 }
11141 
11142 static const char *tracefs_path(void)
11143 {
11144 	return use_debugfs() ? DEBUGFS : TRACEFS;
11145 }
11146 
11147 static const char *tracefs_kprobe_events(void)
11148 {
11149 	return use_debugfs() ? DEBUGFS"/kprobe_events" : TRACEFS"/kprobe_events";
11150 }
11151 
11152 static const char *tracefs_uprobe_events(void)
11153 {
11154 	return use_debugfs() ? DEBUGFS"/uprobe_events" : TRACEFS"/uprobe_events";
11155 }
11156 
11157 static const char *tracefs_available_filter_functions(void)
11158 {
11159 	return use_debugfs() ? DEBUGFS"/available_filter_functions"
11160 			     : TRACEFS"/available_filter_functions";
11161 }
11162 
11163 static const char *tracefs_available_filter_functions_addrs(void)
11164 {
11165 	return use_debugfs() ? DEBUGFS"/available_filter_functions_addrs"
11166 			     : TRACEFS"/available_filter_functions_addrs";
11167 }
11168 
11169 static void gen_probe_legacy_event_name(char *buf, size_t buf_sz,
11170 					const char *name, size_t offset)
11171 {
11172 	static int index = 0;
11173 	int i;
11174 
11175 	snprintf(buf, buf_sz, "libbpf_%u_%d_%s_0x%zx", getpid(),
11176 		 __sync_fetch_and_add(&index, 1), name, offset);
11177 
11178 	/* sanitize name in the probe name */
11179 	for (i = 0; buf[i]; i++) {
11180 		if (!isalnum(buf[i]))
11181 			buf[i] = '_';
11182 	}
11183 }
11184 
11185 static int add_kprobe_event_legacy(const char *probe_name, bool retprobe,
11186 				   const char *kfunc_name, size_t offset)
11187 {
11188 	return append_to_file(tracefs_kprobe_events(), "%c:%s/%s %s+0x%zx",
11189 			      retprobe ? 'r' : 'p',
11190 			      retprobe ? "kretprobes" : "kprobes",
11191 			      probe_name, kfunc_name, offset);
11192 }
11193 
11194 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe)
11195 {
11196 	return append_to_file(tracefs_kprobe_events(), "-:%s/%s",
11197 			      retprobe ? "kretprobes" : "kprobes", probe_name);
11198 }
11199 
11200 static int determine_kprobe_perf_type_legacy(const char *probe_name, bool retprobe)
11201 {
11202 	char file[256];
11203 
11204 	snprintf(file, sizeof(file), "%s/events/%s/%s/id",
11205 		 tracefs_path(), retprobe ? "kretprobes" : "kprobes", probe_name);
11206 
11207 	return parse_uint_from_file(file, "%d\n");
11208 }
11209 
11210 static int perf_event_kprobe_open_legacy(const char *probe_name, bool retprobe,
11211 					 const char *kfunc_name, size_t offset, int pid)
11212 {
11213 	const size_t attr_sz = sizeof(struct perf_event_attr);
11214 	struct perf_event_attr attr;
11215 	int type, pfd, err;
11216 
11217 	err = add_kprobe_event_legacy(probe_name, retprobe, kfunc_name, offset);
11218 	if (err < 0) {
11219 		pr_warn("failed to add legacy kprobe event for '%s+0x%zx': %s\n",
11220 			kfunc_name, offset,
11221 			errstr(err));
11222 		return err;
11223 	}
11224 	type = determine_kprobe_perf_type_legacy(probe_name, retprobe);
11225 	if (type < 0) {
11226 		err = type;
11227 		pr_warn("failed to determine legacy kprobe event id for '%s+0x%zx': %s\n",
11228 			kfunc_name, offset,
11229 			errstr(err));
11230 		goto err_clean_legacy;
11231 	}
11232 
11233 	memset(&attr, 0, attr_sz);
11234 	attr.size = attr_sz;
11235 	attr.config = type;
11236 	attr.type = PERF_TYPE_TRACEPOINT;
11237 
11238 	pfd = syscall(__NR_perf_event_open, &attr,
11239 		      pid < 0 ? -1 : pid, /* pid */
11240 		      pid == -1 ? 0 : -1, /* cpu */
11241 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
11242 	if (pfd < 0) {
11243 		err = -errno;
11244 		pr_warn("legacy kprobe perf_event_open() failed: %s\n",
11245 			errstr(err));
11246 		goto err_clean_legacy;
11247 	}
11248 	return pfd;
11249 
11250 err_clean_legacy:
11251 	/* Clear the newly added legacy kprobe_event */
11252 	remove_kprobe_event_legacy(probe_name, retprobe);
11253 	return err;
11254 }
11255 
11256 static const char *arch_specific_syscall_pfx(void)
11257 {
11258 #if defined(__x86_64__)
11259 	return "x64";
11260 #elif defined(__i386__)
11261 	return "ia32";
11262 #elif defined(__s390x__)
11263 	return "s390x";
11264 #elif defined(__s390__)
11265 	return "s390";
11266 #elif defined(__arm__)
11267 	return "arm";
11268 #elif defined(__aarch64__)
11269 	return "arm64";
11270 #elif defined(__mips__)
11271 	return "mips";
11272 #elif defined(__riscv)
11273 	return "riscv";
11274 #elif defined(__powerpc__)
11275 	return "powerpc";
11276 #elif defined(__powerpc64__)
11277 	return "powerpc64";
11278 #else
11279 	return NULL;
11280 #endif
11281 }
11282 
11283 int probe_kern_syscall_wrapper(int token_fd)
11284 {
11285 	char syscall_name[64];
11286 	const char *ksys_pfx;
11287 
11288 	ksys_pfx = arch_specific_syscall_pfx();
11289 	if (!ksys_pfx)
11290 		return 0;
11291 
11292 	snprintf(syscall_name, sizeof(syscall_name), "__%s_sys_bpf", ksys_pfx);
11293 
11294 	if (determine_kprobe_perf_type() >= 0) {
11295 		int pfd;
11296 
11297 		pfd = perf_event_open_probe(false, false, syscall_name, 0, getpid(), 0);
11298 		if (pfd >= 0)
11299 			close(pfd);
11300 
11301 		return pfd >= 0 ? 1 : 0;
11302 	} else { /* legacy mode */
11303 		char probe_name[MAX_EVENT_NAME_LEN];
11304 
11305 		gen_probe_legacy_event_name(probe_name, sizeof(probe_name), syscall_name, 0);
11306 		if (add_kprobe_event_legacy(probe_name, false, syscall_name, 0) < 0)
11307 			return 0;
11308 
11309 		(void)remove_kprobe_event_legacy(probe_name, false);
11310 		return 1;
11311 	}
11312 }
11313 
11314 struct bpf_link *
11315 bpf_program__attach_kprobe_opts(const struct bpf_program *prog,
11316 				const char *func_name,
11317 				const struct bpf_kprobe_opts *opts)
11318 {
11319 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
11320 	enum probe_attach_mode attach_mode;
11321 	char *legacy_probe = NULL;
11322 	struct bpf_link *link;
11323 	size_t offset;
11324 	bool retprobe, legacy;
11325 	int pfd, err;
11326 
11327 	if (!OPTS_VALID(opts, bpf_kprobe_opts))
11328 		return libbpf_err_ptr(-EINVAL);
11329 
11330 	attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
11331 	retprobe = OPTS_GET(opts, retprobe, false);
11332 	offset = OPTS_GET(opts, offset, 0);
11333 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11334 
11335 	legacy = determine_kprobe_perf_type() < 0;
11336 	switch (attach_mode) {
11337 	case PROBE_ATTACH_MODE_LEGACY:
11338 		legacy = true;
11339 		pe_opts.force_ioctl_attach = true;
11340 		break;
11341 	case PROBE_ATTACH_MODE_PERF:
11342 		if (legacy)
11343 			return libbpf_err_ptr(-ENOTSUP);
11344 		pe_opts.force_ioctl_attach = true;
11345 		break;
11346 	case PROBE_ATTACH_MODE_LINK:
11347 		if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
11348 			return libbpf_err_ptr(-ENOTSUP);
11349 		break;
11350 	case PROBE_ATTACH_MODE_DEFAULT:
11351 		break;
11352 	default:
11353 		return libbpf_err_ptr(-EINVAL);
11354 	}
11355 
11356 	if (!legacy) {
11357 		pfd = perf_event_open_probe(false /* uprobe */, retprobe,
11358 					    func_name, offset,
11359 					    -1 /* pid */, 0 /* ref_ctr_off */);
11360 	} else {
11361 		char probe_name[MAX_EVENT_NAME_LEN];
11362 
11363 		gen_probe_legacy_event_name(probe_name, sizeof(probe_name),
11364 					    func_name, offset);
11365 
11366 		legacy_probe = strdup(probe_name);
11367 		if (!legacy_probe)
11368 			return libbpf_err_ptr(-ENOMEM);
11369 
11370 		pfd = perf_event_kprobe_open_legacy(legacy_probe, retprobe, func_name,
11371 						    offset, -1 /* pid */);
11372 	}
11373 	if (pfd < 0) {
11374 		err = -errno;
11375 		pr_warn("prog '%s': failed to create %s '%s+0x%zx' perf event: %s\n",
11376 			prog->name, retprobe ? "kretprobe" : "kprobe",
11377 			func_name, offset,
11378 			errstr(err));
11379 		goto err_out;
11380 	}
11381 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
11382 	err = libbpf_get_error(link);
11383 	if (err) {
11384 		close(pfd);
11385 		pr_warn("prog '%s': failed to attach to %s '%s+0x%zx': %s\n",
11386 			prog->name, retprobe ? "kretprobe" : "kprobe",
11387 			func_name, offset,
11388 			errstr(err));
11389 		goto err_clean_legacy;
11390 	}
11391 	if (legacy) {
11392 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
11393 
11394 		perf_link->legacy_probe_name = legacy_probe;
11395 		perf_link->legacy_is_kprobe = true;
11396 		perf_link->legacy_is_retprobe = retprobe;
11397 	}
11398 
11399 	return link;
11400 
11401 err_clean_legacy:
11402 	if (legacy)
11403 		remove_kprobe_event_legacy(legacy_probe, retprobe);
11404 err_out:
11405 	free(legacy_probe);
11406 	return libbpf_err_ptr(err);
11407 }
11408 
11409 struct bpf_link *bpf_program__attach_kprobe(const struct bpf_program *prog,
11410 					    bool retprobe,
11411 					    const char *func_name)
11412 {
11413 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts,
11414 		.retprobe = retprobe,
11415 	);
11416 
11417 	return bpf_program__attach_kprobe_opts(prog, func_name, &opts);
11418 }
11419 
11420 struct bpf_link *bpf_program__attach_ksyscall(const struct bpf_program *prog,
11421 					      const char *syscall_name,
11422 					      const struct bpf_ksyscall_opts *opts)
11423 {
11424 	LIBBPF_OPTS(bpf_kprobe_opts, kprobe_opts);
11425 	char func_name[128];
11426 
11427 	if (!OPTS_VALID(opts, bpf_ksyscall_opts))
11428 		return libbpf_err_ptr(-EINVAL);
11429 
11430 	if (kernel_supports(prog->obj, FEAT_SYSCALL_WRAPPER)) {
11431 		/* arch_specific_syscall_pfx() should never return NULL here
11432 		 * because it is guarded by kernel_supports(). However, since
11433 		 * compiler does not know that we have an explicit conditional
11434 		 * as well.
11435 		 */
11436 		snprintf(func_name, sizeof(func_name), "__%s_sys_%s",
11437 			 arch_specific_syscall_pfx() ? : "", syscall_name);
11438 	} else {
11439 		snprintf(func_name, sizeof(func_name), "__se_sys_%s", syscall_name);
11440 	}
11441 
11442 	kprobe_opts.retprobe = OPTS_GET(opts, retprobe, false);
11443 	kprobe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11444 
11445 	return bpf_program__attach_kprobe_opts(prog, func_name, &kprobe_opts);
11446 }
11447 
11448 /* Adapted from perf/util/string.c */
11449 bool glob_match(const char *str, const char *pat)
11450 {
11451 	while (*str && *pat && *pat != '*') {
11452 		if (*pat == '?') {      /* Matches any single character */
11453 			str++;
11454 			pat++;
11455 			continue;
11456 		}
11457 		if (*str != *pat)
11458 			return false;
11459 		str++;
11460 		pat++;
11461 	}
11462 	/* Check wild card */
11463 	if (*pat == '*') {
11464 		while (*pat == '*')
11465 			pat++;
11466 		if (!*pat) /* Tail wild card matches all */
11467 			return true;
11468 		while (*str)
11469 			if (glob_match(str++, pat))
11470 				return true;
11471 	}
11472 	return !*str && !*pat;
11473 }
11474 
11475 struct kprobe_multi_resolve {
11476 	const char *pattern;
11477 	unsigned long *addrs;
11478 	size_t cap;
11479 	size_t cnt;
11480 };
11481 
11482 struct avail_kallsyms_data {
11483 	char **syms;
11484 	size_t cnt;
11485 	struct kprobe_multi_resolve *res;
11486 };
11487 
11488 static int avail_func_cmp(const void *a, const void *b)
11489 {
11490 	return strcmp(*(const char **)a, *(const char **)b);
11491 }
11492 
11493 static int avail_kallsyms_cb(unsigned long long sym_addr, char sym_type,
11494 			     const char *sym_name, void *ctx)
11495 {
11496 	struct avail_kallsyms_data *data = ctx;
11497 	struct kprobe_multi_resolve *res = data->res;
11498 	int err;
11499 
11500 	if (!glob_match(sym_name, res->pattern))
11501 		return 0;
11502 
11503 	if (!bsearch(&sym_name, data->syms, data->cnt, sizeof(*data->syms), avail_func_cmp)) {
11504 		/* Some versions of kernel strip out .llvm.<hash> suffix from
11505 		 * function names reported in available_filter_functions, but
11506 		 * don't do so for kallsyms. While this is clearly a kernel
11507 		 * bug (fixed by [0]) we try to accommodate that in libbpf to
11508 		 * make multi-kprobe usability a bit better: if no match is
11509 		 * found, we will strip .llvm. suffix and try one more time.
11510 		 *
11511 		 *   [0] fb6a421fb615 ("kallsyms: Match symbols exactly with CONFIG_LTO_CLANG")
11512 		 */
11513 		char sym_trim[256], *psym_trim = sym_trim, *sym_sfx;
11514 
11515 		if (!(sym_sfx = strstr(sym_name, ".llvm.")))
11516 			return 0;
11517 
11518 		/* psym_trim vs sym_trim dance is done to avoid pointer vs array
11519 		 * coercion differences and get proper `const char **` pointer
11520 		 * which avail_func_cmp() expects
11521 		 */
11522 		snprintf(sym_trim, sizeof(sym_trim), "%.*s", (int)(sym_sfx - sym_name), sym_name);
11523 		if (!bsearch(&psym_trim, data->syms, data->cnt, sizeof(*data->syms), avail_func_cmp))
11524 			return 0;
11525 	}
11526 
11527 	err = libbpf_ensure_mem((void **)&res->addrs, &res->cap, sizeof(*res->addrs), res->cnt + 1);
11528 	if (err)
11529 		return err;
11530 
11531 	res->addrs[res->cnt++] = (unsigned long)sym_addr;
11532 	return 0;
11533 }
11534 
11535 static int libbpf_available_kallsyms_parse(struct kprobe_multi_resolve *res)
11536 {
11537 	const char *available_functions_file = tracefs_available_filter_functions();
11538 	struct avail_kallsyms_data data;
11539 	char sym_name[500];
11540 	FILE *f;
11541 	int err = 0, ret, i;
11542 	char **syms = NULL;
11543 	size_t cap = 0, cnt = 0;
11544 
11545 	f = fopen(available_functions_file, "re");
11546 	if (!f) {
11547 		err = -errno;
11548 		pr_warn("failed to open %s: %s\n", available_functions_file, errstr(err));
11549 		return err;
11550 	}
11551 
11552 	while (true) {
11553 		char *name;
11554 
11555 		ret = fscanf(f, "%499s%*[^\n]\n", sym_name);
11556 		if (ret == EOF && feof(f))
11557 			break;
11558 
11559 		if (ret != 1) {
11560 			pr_warn("failed to parse available_filter_functions entry: %d\n", ret);
11561 			err = -EINVAL;
11562 			goto cleanup;
11563 		}
11564 
11565 		if (!glob_match(sym_name, res->pattern))
11566 			continue;
11567 
11568 		err = libbpf_ensure_mem((void **)&syms, &cap, sizeof(*syms), cnt + 1);
11569 		if (err)
11570 			goto cleanup;
11571 
11572 		name = strdup(sym_name);
11573 		if (!name) {
11574 			err = -errno;
11575 			goto cleanup;
11576 		}
11577 
11578 		syms[cnt++] = name;
11579 	}
11580 
11581 	/* no entries found, bail out */
11582 	if (cnt == 0) {
11583 		err = -ENOENT;
11584 		goto cleanup;
11585 	}
11586 
11587 	/* sort available functions */
11588 	qsort(syms, cnt, sizeof(*syms), avail_func_cmp);
11589 
11590 	data.syms = syms;
11591 	data.res = res;
11592 	data.cnt = cnt;
11593 	libbpf_kallsyms_parse(avail_kallsyms_cb, &data);
11594 
11595 	if (res->cnt == 0)
11596 		err = -ENOENT;
11597 
11598 cleanup:
11599 	for (i = 0; i < cnt; i++)
11600 		free((char *)syms[i]);
11601 	free(syms);
11602 
11603 	fclose(f);
11604 	return err;
11605 }
11606 
11607 static bool has_available_filter_functions_addrs(void)
11608 {
11609 	return access(tracefs_available_filter_functions_addrs(), R_OK) != -1;
11610 }
11611 
11612 static int libbpf_available_kprobes_parse(struct kprobe_multi_resolve *res)
11613 {
11614 	const char *available_path = tracefs_available_filter_functions_addrs();
11615 	char sym_name[500];
11616 	FILE *f;
11617 	int ret, err = 0;
11618 	unsigned long long sym_addr;
11619 
11620 	f = fopen(available_path, "re");
11621 	if (!f) {
11622 		err = -errno;
11623 		pr_warn("failed to open %s: %s\n", available_path, errstr(err));
11624 		return err;
11625 	}
11626 
11627 	while (true) {
11628 		ret = fscanf(f, "%llx %499s%*[^\n]\n", &sym_addr, sym_name);
11629 		if (ret == EOF && feof(f))
11630 			break;
11631 
11632 		if (ret != 2) {
11633 			pr_warn("failed to parse available_filter_functions_addrs entry: %d\n",
11634 				ret);
11635 			err = -EINVAL;
11636 			goto cleanup;
11637 		}
11638 
11639 		if (!glob_match(sym_name, res->pattern))
11640 			continue;
11641 
11642 		err = libbpf_ensure_mem((void **)&res->addrs, &res->cap,
11643 					sizeof(*res->addrs), res->cnt + 1);
11644 		if (err)
11645 			goto cleanup;
11646 
11647 		res->addrs[res->cnt++] = (unsigned long)sym_addr;
11648 	}
11649 
11650 	if (res->cnt == 0)
11651 		err = -ENOENT;
11652 
11653 cleanup:
11654 	fclose(f);
11655 	return err;
11656 }
11657 
11658 struct bpf_link *
11659 bpf_program__attach_kprobe_multi_opts(const struct bpf_program *prog,
11660 				      const char *pattern,
11661 				      const struct bpf_kprobe_multi_opts *opts)
11662 {
11663 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
11664 	struct kprobe_multi_resolve res = {
11665 		.pattern = pattern,
11666 	};
11667 	enum bpf_attach_type attach_type;
11668 	struct bpf_link *link = NULL;
11669 	const unsigned long *addrs;
11670 	int err, link_fd, prog_fd;
11671 	bool retprobe, session, unique_match;
11672 	const __u64 *cookies;
11673 	const char **syms;
11674 	size_t cnt;
11675 
11676 	if (!OPTS_VALID(opts, bpf_kprobe_multi_opts))
11677 		return libbpf_err_ptr(-EINVAL);
11678 
11679 	prog_fd = bpf_program__fd(prog);
11680 	if (prog_fd < 0) {
11681 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
11682 			prog->name);
11683 		return libbpf_err_ptr(-EINVAL);
11684 	}
11685 
11686 	syms    = OPTS_GET(opts, syms, false);
11687 	addrs   = OPTS_GET(opts, addrs, false);
11688 	cnt     = OPTS_GET(opts, cnt, false);
11689 	cookies = OPTS_GET(opts, cookies, false);
11690 	unique_match = OPTS_GET(opts, unique_match, false);
11691 
11692 	if (!pattern && !addrs && !syms)
11693 		return libbpf_err_ptr(-EINVAL);
11694 	if (pattern && (addrs || syms || cookies || cnt))
11695 		return libbpf_err_ptr(-EINVAL);
11696 	if (!pattern && !cnt)
11697 		return libbpf_err_ptr(-EINVAL);
11698 	if (!pattern && unique_match)
11699 		return libbpf_err_ptr(-EINVAL);
11700 	if (addrs && syms)
11701 		return libbpf_err_ptr(-EINVAL);
11702 
11703 	if (pattern) {
11704 		if (has_available_filter_functions_addrs())
11705 			err = libbpf_available_kprobes_parse(&res);
11706 		else
11707 			err = libbpf_available_kallsyms_parse(&res);
11708 		if (err)
11709 			goto error;
11710 
11711 		if (unique_match && res.cnt != 1) {
11712 			pr_warn("prog '%s': failed to find a unique match for '%s' (%zu matches)\n",
11713 				prog->name, pattern, res.cnt);
11714 			err = -EINVAL;
11715 			goto error;
11716 		}
11717 
11718 		addrs = res.addrs;
11719 		cnt = res.cnt;
11720 	}
11721 
11722 	retprobe = OPTS_GET(opts, retprobe, false);
11723 	session  = OPTS_GET(opts, session, false);
11724 
11725 	if (retprobe && session)
11726 		return libbpf_err_ptr(-EINVAL);
11727 
11728 	attach_type = session ? BPF_TRACE_KPROBE_SESSION : BPF_TRACE_KPROBE_MULTI;
11729 
11730 	lopts.kprobe_multi.syms = syms;
11731 	lopts.kprobe_multi.addrs = addrs;
11732 	lopts.kprobe_multi.cookies = cookies;
11733 	lopts.kprobe_multi.cnt = cnt;
11734 	lopts.kprobe_multi.flags = retprobe ? BPF_F_KPROBE_MULTI_RETURN : 0;
11735 
11736 	link = calloc(1, sizeof(*link));
11737 	if (!link) {
11738 		err = -ENOMEM;
11739 		goto error;
11740 	}
11741 	link->detach = &bpf_link__detach_fd;
11742 
11743 	link_fd = bpf_link_create(prog_fd, 0, attach_type, &lopts);
11744 	if (link_fd < 0) {
11745 		err = -errno;
11746 		pr_warn("prog '%s': failed to attach: %s\n",
11747 			prog->name, errstr(err));
11748 		goto error;
11749 	}
11750 	link->fd = link_fd;
11751 	free(res.addrs);
11752 	return link;
11753 
11754 error:
11755 	free(link);
11756 	free(res.addrs);
11757 	return libbpf_err_ptr(err);
11758 }
11759 
11760 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11761 {
11762 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts);
11763 	unsigned long offset = 0;
11764 	const char *func_name;
11765 	char *func;
11766 	int n;
11767 
11768 	*link = NULL;
11769 
11770 	/* no auto-attach for SEC("kprobe") and SEC("kretprobe") */
11771 	if (strcmp(prog->sec_name, "kprobe") == 0 || strcmp(prog->sec_name, "kretprobe") == 0)
11772 		return 0;
11773 
11774 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe/");
11775 	if (opts.retprobe)
11776 		func_name = prog->sec_name + sizeof("kretprobe/") - 1;
11777 	else
11778 		func_name = prog->sec_name + sizeof("kprobe/") - 1;
11779 
11780 	n = sscanf(func_name, "%m[a-zA-Z0-9_.]+%li", &func, &offset);
11781 	if (n < 1) {
11782 		pr_warn("kprobe name is invalid: %s\n", func_name);
11783 		return -EINVAL;
11784 	}
11785 	if (opts.retprobe && offset != 0) {
11786 		free(func);
11787 		pr_warn("kretprobes do not support offset specification\n");
11788 		return -EINVAL;
11789 	}
11790 
11791 	opts.offset = offset;
11792 	*link = bpf_program__attach_kprobe_opts(prog, func, &opts);
11793 	free(func);
11794 	return libbpf_get_error(*link);
11795 }
11796 
11797 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11798 {
11799 	LIBBPF_OPTS(bpf_ksyscall_opts, opts);
11800 	const char *syscall_name;
11801 
11802 	*link = NULL;
11803 
11804 	/* no auto-attach for SEC("ksyscall") and SEC("kretsyscall") */
11805 	if (strcmp(prog->sec_name, "ksyscall") == 0 || strcmp(prog->sec_name, "kretsyscall") == 0)
11806 		return 0;
11807 
11808 	opts.retprobe = str_has_pfx(prog->sec_name, "kretsyscall/");
11809 	if (opts.retprobe)
11810 		syscall_name = prog->sec_name + sizeof("kretsyscall/") - 1;
11811 	else
11812 		syscall_name = prog->sec_name + sizeof("ksyscall/") - 1;
11813 
11814 	*link = bpf_program__attach_ksyscall(prog, syscall_name, &opts);
11815 	return *link ? 0 : -errno;
11816 }
11817 
11818 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11819 {
11820 	LIBBPF_OPTS(bpf_kprobe_multi_opts, opts);
11821 	const char *spec;
11822 	char *pattern;
11823 	int n;
11824 
11825 	*link = NULL;
11826 
11827 	/* no auto-attach for SEC("kprobe.multi") and SEC("kretprobe.multi") */
11828 	if (strcmp(prog->sec_name, "kprobe.multi") == 0 ||
11829 	    strcmp(prog->sec_name, "kretprobe.multi") == 0)
11830 		return 0;
11831 
11832 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe.multi/");
11833 	if (opts.retprobe)
11834 		spec = prog->sec_name + sizeof("kretprobe.multi/") - 1;
11835 	else
11836 		spec = prog->sec_name + sizeof("kprobe.multi/") - 1;
11837 
11838 	n = sscanf(spec, "%m[a-zA-Z0-9_.*?]", &pattern);
11839 	if (n < 1) {
11840 		pr_warn("kprobe multi pattern is invalid: %s\n", spec);
11841 		return -EINVAL;
11842 	}
11843 
11844 	*link = bpf_program__attach_kprobe_multi_opts(prog, pattern, &opts);
11845 	free(pattern);
11846 	return libbpf_get_error(*link);
11847 }
11848 
11849 static int attach_kprobe_session(const struct bpf_program *prog, long cookie,
11850 				 struct bpf_link **link)
11851 {
11852 	LIBBPF_OPTS(bpf_kprobe_multi_opts, opts, .session = true);
11853 	const char *spec;
11854 	char *pattern;
11855 	int n;
11856 
11857 	*link = NULL;
11858 
11859 	/* no auto-attach for SEC("kprobe.session") */
11860 	if (strcmp(prog->sec_name, "kprobe.session") == 0)
11861 		return 0;
11862 
11863 	spec = prog->sec_name + sizeof("kprobe.session/") - 1;
11864 	n = sscanf(spec, "%m[a-zA-Z0-9_.*?]", &pattern);
11865 	if (n < 1) {
11866 		pr_warn("kprobe session pattern is invalid: %s\n", spec);
11867 		return -EINVAL;
11868 	}
11869 
11870 	*link = bpf_program__attach_kprobe_multi_opts(prog, pattern, &opts);
11871 	free(pattern);
11872 	return *link ? 0 : -errno;
11873 }
11874 
11875 static int attach_uprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11876 {
11877 	char *probe_type = NULL, *binary_path = NULL, *func_name = NULL;
11878 	LIBBPF_OPTS(bpf_uprobe_multi_opts, opts);
11879 	int n, ret = -EINVAL;
11880 
11881 	*link = NULL;
11882 
11883 	n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[^\n]",
11884 		   &probe_type, &binary_path, &func_name);
11885 	switch (n) {
11886 	case 1:
11887 		/* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
11888 		ret = 0;
11889 		break;
11890 	case 3:
11891 		opts.session = str_has_pfx(probe_type, "uprobe.session");
11892 		opts.retprobe = str_has_pfx(probe_type, "uretprobe.multi");
11893 
11894 		*link = bpf_program__attach_uprobe_multi(prog, -1, binary_path, func_name, &opts);
11895 		ret = libbpf_get_error(*link);
11896 		break;
11897 	default:
11898 		pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
11899 			prog->sec_name);
11900 		break;
11901 	}
11902 	free(probe_type);
11903 	free(binary_path);
11904 	free(func_name);
11905 	return ret;
11906 }
11907 
11908 static inline int add_uprobe_event_legacy(const char *probe_name, bool retprobe,
11909 					  const char *binary_path, size_t offset)
11910 {
11911 	return append_to_file(tracefs_uprobe_events(), "%c:%s/%s %s:0x%zx",
11912 			      retprobe ? 'r' : 'p',
11913 			      retprobe ? "uretprobes" : "uprobes",
11914 			      probe_name, binary_path, offset);
11915 }
11916 
11917 static inline int remove_uprobe_event_legacy(const char *probe_name, bool retprobe)
11918 {
11919 	return append_to_file(tracefs_uprobe_events(), "-:%s/%s",
11920 			      retprobe ? "uretprobes" : "uprobes", probe_name);
11921 }
11922 
11923 static int determine_uprobe_perf_type_legacy(const char *probe_name, bool retprobe)
11924 {
11925 	char file[512];
11926 
11927 	snprintf(file, sizeof(file), "%s/events/%s/%s/id",
11928 		 tracefs_path(), retprobe ? "uretprobes" : "uprobes", probe_name);
11929 
11930 	return parse_uint_from_file(file, "%d\n");
11931 }
11932 
11933 static int perf_event_uprobe_open_legacy(const char *probe_name, bool retprobe,
11934 					 const char *binary_path, size_t offset, int pid)
11935 {
11936 	const size_t attr_sz = sizeof(struct perf_event_attr);
11937 	struct perf_event_attr attr;
11938 	int type, pfd, err;
11939 
11940 	err = add_uprobe_event_legacy(probe_name, retprobe, binary_path, offset);
11941 	if (err < 0) {
11942 		pr_warn("failed to add legacy uprobe event for %s:0x%zx: %s\n",
11943 			binary_path, (size_t)offset, errstr(err));
11944 		return err;
11945 	}
11946 	type = determine_uprobe_perf_type_legacy(probe_name, retprobe);
11947 	if (type < 0) {
11948 		err = type;
11949 		pr_warn("failed to determine legacy uprobe event id for %s:0x%zx: %s\n",
11950 			binary_path, offset, errstr(err));
11951 		goto err_clean_legacy;
11952 	}
11953 
11954 	memset(&attr, 0, attr_sz);
11955 	attr.size = attr_sz;
11956 	attr.config = type;
11957 	attr.type = PERF_TYPE_TRACEPOINT;
11958 
11959 	pfd = syscall(__NR_perf_event_open, &attr,
11960 		      pid < 0 ? -1 : pid, /* pid */
11961 		      pid == -1 ? 0 : -1, /* cpu */
11962 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
11963 	if (pfd < 0) {
11964 		err = -errno;
11965 		pr_warn("legacy uprobe perf_event_open() failed: %s\n", errstr(err));
11966 		goto err_clean_legacy;
11967 	}
11968 	return pfd;
11969 
11970 err_clean_legacy:
11971 	/* Clear the newly added legacy uprobe_event */
11972 	remove_uprobe_event_legacy(probe_name, retprobe);
11973 	return err;
11974 }
11975 
11976 /* Find offset of function name in archive specified by path. Currently
11977  * supported are .zip files that do not compress their contents, as used on
11978  * Android in the form of APKs, for example. "file_name" is the name of the ELF
11979  * file inside the archive. "func_name" matches symbol name or name@@LIB for
11980  * library functions.
11981  *
11982  * An overview of the APK format specifically provided here:
11983  * https://en.wikipedia.org/w/index.php?title=Apk_(file_format)&oldid=1139099120#Package_contents
11984  */
11985 static long elf_find_func_offset_from_archive(const char *archive_path, const char *file_name,
11986 					      const char *func_name)
11987 {
11988 	struct zip_archive *archive;
11989 	struct zip_entry entry;
11990 	long ret;
11991 	Elf *elf;
11992 
11993 	archive = zip_archive_open(archive_path);
11994 	if (IS_ERR(archive)) {
11995 		ret = PTR_ERR(archive);
11996 		pr_warn("zip: failed to open %s: %ld\n", archive_path, ret);
11997 		return ret;
11998 	}
11999 
12000 	ret = zip_archive_find_entry(archive, file_name, &entry);
12001 	if (ret) {
12002 		pr_warn("zip: could not find archive member %s in %s: %ld\n", file_name,
12003 			archive_path, ret);
12004 		goto out;
12005 	}
12006 	pr_debug("zip: found entry for %s in %s at 0x%lx\n", file_name, archive_path,
12007 		 (unsigned long)entry.data_offset);
12008 
12009 	if (entry.compression) {
12010 		pr_warn("zip: entry %s of %s is compressed and cannot be handled\n", file_name,
12011 			archive_path);
12012 		ret = -LIBBPF_ERRNO__FORMAT;
12013 		goto out;
12014 	}
12015 
12016 	elf = elf_memory((void *)entry.data, entry.data_length);
12017 	if (!elf) {
12018 		pr_warn("elf: could not read elf file %s from %s: %s\n", file_name, archive_path,
12019 			elf_errmsg(-1));
12020 		ret = -LIBBPF_ERRNO__LIBELF;
12021 		goto out;
12022 	}
12023 
12024 	ret = elf_find_func_offset(elf, file_name, func_name);
12025 	if (ret > 0) {
12026 		pr_debug("elf: symbol address match for %s of %s in %s: 0x%x + 0x%lx = 0x%lx\n",
12027 			 func_name, file_name, archive_path, entry.data_offset, ret,
12028 			 ret + entry.data_offset);
12029 		ret += entry.data_offset;
12030 	}
12031 	elf_end(elf);
12032 
12033 out:
12034 	zip_archive_close(archive);
12035 	return ret;
12036 }
12037 
12038 static const char *arch_specific_lib_paths(void)
12039 {
12040 	/*
12041 	 * Based on https://packages.debian.org/sid/libc6.
12042 	 *
12043 	 * Assume that the traced program is built for the same architecture
12044 	 * as libbpf, which should cover the vast majority of cases.
12045 	 */
12046 #if defined(__x86_64__)
12047 	return "/lib/x86_64-linux-gnu";
12048 #elif defined(__i386__)
12049 	return "/lib/i386-linux-gnu";
12050 #elif defined(__s390x__)
12051 	return "/lib/s390x-linux-gnu";
12052 #elif defined(__s390__)
12053 	return "/lib/s390-linux-gnu";
12054 #elif defined(__arm__) && defined(__SOFTFP__)
12055 	return "/lib/arm-linux-gnueabi";
12056 #elif defined(__arm__) && !defined(__SOFTFP__)
12057 	return "/lib/arm-linux-gnueabihf";
12058 #elif defined(__aarch64__)
12059 	return "/lib/aarch64-linux-gnu";
12060 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 64
12061 	return "/lib/mips64el-linux-gnuabi64";
12062 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 32
12063 	return "/lib/mipsel-linux-gnu";
12064 #elif defined(__powerpc64__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
12065 	return "/lib/powerpc64le-linux-gnu";
12066 #elif defined(__sparc__) && defined(__arch64__)
12067 	return "/lib/sparc64-linux-gnu";
12068 #elif defined(__riscv) && __riscv_xlen == 64
12069 	return "/lib/riscv64-linux-gnu";
12070 #else
12071 	return NULL;
12072 #endif
12073 }
12074 
12075 /* Get full path to program/shared library. */
12076 static int resolve_full_path(const char *file, char *result, size_t result_sz)
12077 {
12078 	const char *search_paths[3] = {};
12079 	int i, perm;
12080 
12081 	if (str_has_sfx(file, ".so") || strstr(file, ".so.")) {
12082 		search_paths[0] = getenv("LD_LIBRARY_PATH");
12083 		search_paths[1] = "/usr/lib64:/usr/lib";
12084 		search_paths[2] = arch_specific_lib_paths();
12085 		perm = R_OK;
12086 	} else {
12087 		search_paths[0] = getenv("PATH");
12088 		search_paths[1] = "/usr/bin:/usr/sbin";
12089 		perm = R_OK | X_OK;
12090 	}
12091 
12092 	for (i = 0; i < ARRAY_SIZE(search_paths); i++) {
12093 		const char *s;
12094 
12095 		if (!search_paths[i])
12096 			continue;
12097 		for (s = search_paths[i]; s != NULL; s = strchr(s, ':')) {
12098 			char *next_path;
12099 			int seg_len;
12100 
12101 			if (s[0] == ':')
12102 				s++;
12103 			next_path = strchr(s, ':');
12104 			seg_len = next_path ? next_path - s : strlen(s);
12105 			if (!seg_len)
12106 				continue;
12107 			snprintf(result, result_sz, "%.*s/%s", seg_len, s, file);
12108 			/* ensure it has required permissions */
12109 			if (faccessat(AT_FDCWD, result, perm, AT_EACCESS) < 0)
12110 				continue;
12111 			pr_debug("resolved '%s' to '%s'\n", file, result);
12112 			return 0;
12113 		}
12114 	}
12115 	return -ENOENT;
12116 }
12117 
12118 struct bpf_link *
12119 bpf_program__attach_uprobe_multi(const struct bpf_program *prog,
12120 				 pid_t pid,
12121 				 const char *path,
12122 				 const char *func_pattern,
12123 				 const struct bpf_uprobe_multi_opts *opts)
12124 {
12125 	const unsigned long *ref_ctr_offsets = NULL, *offsets = NULL;
12126 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
12127 	unsigned long *resolved_offsets = NULL;
12128 	enum bpf_attach_type attach_type;
12129 	int err = 0, link_fd, prog_fd;
12130 	struct bpf_link *link = NULL;
12131 	char full_path[PATH_MAX];
12132 	bool retprobe, session;
12133 	const __u64 *cookies;
12134 	const char **syms;
12135 	size_t cnt;
12136 
12137 	if (!OPTS_VALID(opts, bpf_uprobe_multi_opts))
12138 		return libbpf_err_ptr(-EINVAL);
12139 
12140 	prog_fd = bpf_program__fd(prog);
12141 	if (prog_fd < 0) {
12142 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
12143 			prog->name);
12144 		return libbpf_err_ptr(-EINVAL);
12145 	}
12146 
12147 	syms = OPTS_GET(opts, syms, NULL);
12148 	offsets = OPTS_GET(opts, offsets, NULL);
12149 	ref_ctr_offsets = OPTS_GET(opts, ref_ctr_offsets, NULL);
12150 	cookies = OPTS_GET(opts, cookies, NULL);
12151 	cnt = OPTS_GET(opts, cnt, 0);
12152 	retprobe = OPTS_GET(opts, retprobe, false);
12153 	session  = OPTS_GET(opts, session, false);
12154 
12155 	/*
12156 	 * User can specify 2 mutually exclusive set of inputs:
12157 	 *
12158 	 * 1) use only path/func_pattern/pid arguments
12159 	 *
12160 	 * 2) use path/pid with allowed combinations of:
12161 	 *    syms/offsets/ref_ctr_offsets/cookies/cnt
12162 	 *
12163 	 *    - syms and offsets are mutually exclusive
12164 	 *    - ref_ctr_offsets and cookies are optional
12165 	 *
12166 	 * Any other usage results in error.
12167 	 */
12168 
12169 	if (!path)
12170 		return libbpf_err_ptr(-EINVAL);
12171 	if (!func_pattern && cnt == 0)
12172 		return libbpf_err_ptr(-EINVAL);
12173 
12174 	if (func_pattern) {
12175 		if (syms || offsets || ref_ctr_offsets || cookies || cnt)
12176 			return libbpf_err_ptr(-EINVAL);
12177 	} else {
12178 		if (!!syms == !!offsets)
12179 			return libbpf_err_ptr(-EINVAL);
12180 	}
12181 
12182 	if (retprobe && session)
12183 		return libbpf_err_ptr(-EINVAL);
12184 
12185 	if (func_pattern) {
12186 		if (!strchr(path, '/')) {
12187 			err = resolve_full_path(path, full_path, sizeof(full_path));
12188 			if (err) {
12189 				pr_warn("prog '%s': failed to resolve full path for '%s': %s\n",
12190 					prog->name, path, errstr(err));
12191 				return libbpf_err_ptr(err);
12192 			}
12193 			path = full_path;
12194 		}
12195 
12196 		err = elf_resolve_pattern_offsets(path, func_pattern,
12197 						  &resolved_offsets, &cnt);
12198 		if (err < 0)
12199 			return libbpf_err_ptr(err);
12200 		offsets = resolved_offsets;
12201 	} else if (syms) {
12202 		err = elf_resolve_syms_offsets(path, cnt, syms, &resolved_offsets, STT_FUNC);
12203 		if (err < 0)
12204 			return libbpf_err_ptr(err);
12205 		offsets = resolved_offsets;
12206 	}
12207 
12208 	attach_type = session ? BPF_TRACE_UPROBE_SESSION : BPF_TRACE_UPROBE_MULTI;
12209 
12210 	lopts.uprobe_multi.path = path;
12211 	lopts.uprobe_multi.offsets = offsets;
12212 	lopts.uprobe_multi.ref_ctr_offsets = ref_ctr_offsets;
12213 	lopts.uprobe_multi.cookies = cookies;
12214 	lopts.uprobe_multi.cnt = cnt;
12215 	lopts.uprobe_multi.flags = retprobe ? BPF_F_UPROBE_MULTI_RETURN : 0;
12216 
12217 	if (pid == 0)
12218 		pid = getpid();
12219 	if (pid > 0)
12220 		lopts.uprobe_multi.pid = pid;
12221 
12222 	link = calloc(1, sizeof(*link));
12223 	if (!link) {
12224 		err = -ENOMEM;
12225 		goto error;
12226 	}
12227 	link->detach = &bpf_link__detach_fd;
12228 
12229 	link_fd = bpf_link_create(prog_fd, 0, attach_type, &lopts);
12230 	if (link_fd < 0) {
12231 		err = -errno;
12232 		pr_warn("prog '%s': failed to attach multi-uprobe: %s\n",
12233 			prog->name, errstr(err));
12234 		goto error;
12235 	}
12236 	link->fd = link_fd;
12237 	free(resolved_offsets);
12238 	return link;
12239 
12240 error:
12241 	free(resolved_offsets);
12242 	free(link);
12243 	return libbpf_err_ptr(err);
12244 }
12245 
12246 LIBBPF_API struct bpf_link *
12247 bpf_program__attach_uprobe_opts(const struct bpf_program *prog, pid_t pid,
12248 				const char *binary_path, size_t func_offset,
12249 				const struct bpf_uprobe_opts *opts)
12250 {
12251 	const char *archive_path = NULL, *archive_sep = NULL;
12252 	char *legacy_probe = NULL;
12253 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
12254 	enum probe_attach_mode attach_mode;
12255 	char full_path[PATH_MAX];
12256 	struct bpf_link *link;
12257 	size_t ref_ctr_off;
12258 	int pfd, err;
12259 	bool retprobe, legacy;
12260 	const char *func_name;
12261 
12262 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
12263 		return libbpf_err_ptr(-EINVAL);
12264 
12265 	attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
12266 	retprobe = OPTS_GET(opts, retprobe, false);
12267 	ref_ctr_off = OPTS_GET(opts, ref_ctr_offset, 0);
12268 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
12269 
12270 	if (!binary_path)
12271 		return libbpf_err_ptr(-EINVAL);
12272 
12273 	/* Check if "binary_path" refers to an archive. */
12274 	archive_sep = strstr(binary_path, "!/");
12275 	if (archive_sep) {
12276 		full_path[0] = '\0';
12277 		libbpf_strlcpy(full_path, binary_path,
12278 			       min(sizeof(full_path), (size_t)(archive_sep - binary_path + 1)));
12279 		archive_path = full_path;
12280 		binary_path = archive_sep + 2;
12281 	} else if (!strchr(binary_path, '/')) {
12282 		err = resolve_full_path(binary_path, full_path, sizeof(full_path));
12283 		if (err) {
12284 			pr_warn("prog '%s': failed to resolve full path for '%s': %s\n",
12285 				prog->name, binary_path, errstr(err));
12286 			return libbpf_err_ptr(err);
12287 		}
12288 		binary_path = full_path;
12289 	}
12290 	func_name = OPTS_GET(opts, func_name, NULL);
12291 	if (func_name) {
12292 		long sym_off;
12293 
12294 		if (archive_path) {
12295 			sym_off = elf_find_func_offset_from_archive(archive_path, binary_path,
12296 								    func_name);
12297 			binary_path = archive_path;
12298 		} else {
12299 			sym_off = elf_find_func_offset_from_file(binary_path, func_name);
12300 		}
12301 		if (sym_off < 0)
12302 			return libbpf_err_ptr(sym_off);
12303 		func_offset += sym_off;
12304 	}
12305 
12306 	legacy = determine_uprobe_perf_type() < 0;
12307 	switch (attach_mode) {
12308 	case PROBE_ATTACH_MODE_LEGACY:
12309 		legacy = true;
12310 		pe_opts.force_ioctl_attach = true;
12311 		break;
12312 	case PROBE_ATTACH_MODE_PERF:
12313 		if (legacy)
12314 			return libbpf_err_ptr(-ENOTSUP);
12315 		pe_opts.force_ioctl_attach = true;
12316 		break;
12317 	case PROBE_ATTACH_MODE_LINK:
12318 		if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
12319 			return libbpf_err_ptr(-ENOTSUP);
12320 		break;
12321 	case PROBE_ATTACH_MODE_DEFAULT:
12322 		break;
12323 	default:
12324 		return libbpf_err_ptr(-EINVAL);
12325 	}
12326 
12327 	if (!legacy) {
12328 		pfd = perf_event_open_probe(true /* uprobe */, retprobe, binary_path,
12329 					    func_offset, pid, ref_ctr_off);
12330 	} else {
12331 		char probe_name[MAX_EVENT_NAME_LEN];
12332 
12333 		if (ref_ctr_off)
12334 			return libbpf_err_ptr(-EINVAL);
12335 
12336 		gen_probe_legacy_event_name(probe_name, sizeof(probe_name),
12337 					    strrchr(binary_path, '/') ? : binary_path,
12338 					    func_offset);
12339 
12340 		legacy_probe = strdup(probe_name);
12341 		if (!legacy_probe)
12342 			return libbpf_err_ptr(-ENOMEM);
12343 
12344 		pfd = perf_event_uprobe_open_legacy(legacy_probe, retprobe,
12345 						    binary_path, func_offset, pid);
12346 	}
12347 	if (pfd < 0) {
12348 		err = -errno;
12349 		pr_warn("prog '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
12350 			prog->name, retprobe ? "uretprobe" : "uprobe",
12351 			binary_path, func_offset,
12352 			errstr(err));
12353 		goto err_out;
12354 	}
12355 
12356 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
12357 	err = libbpf_get_error(link);
12358 	if (err) {
12359 		close(pfd);
12360 		pr_warn("prog '%s': failed to attach to %s '%s:0x%zx': %s\n",
12361 			prog->name, retprobe ? "uretprobe" : "uprobe",
12362 			binary_path, func_offset,
12363 			errstr(err));
12364 		goto err_clean_legacy;
12365 	}
12366 	if (legacy) {
12367 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
12368 
12369 		perf_link->legacy_probe_name = legacy_probe;
12370 		perf_link->legacy_is_kprobe = false;
12371 		perf_link->legacy_is_retprobe = retprobe;
12372 	}
12373 	return link;
12374 
12375 err_clean_legacy:
12376 	if (legacy)
12377 		remove_uprobe_event_legacy(legacy_probe, retprobe);
12378 err_out:
12379 	free(legacy_probe);
12380 	return libbpf_err_ptr(err);
12381 }
12382 
12383 /* Format of u[ret]probe section definition supporting auto-attach:
12384  * u[ret]probe/binary:function[+offset]
12385  *
12386  * binary can be an absolute/relative path or a filename; the latter is resolved to a
12387  * full binary path via bpf_program__attach_uprobe_opts.
12388  *
12389  * Specifying uprobe+ ensures we carry out strict matching; either "uprobe" must be
12390  * specified (and auto-attach is not possible) or the above format is specified for
12391  * auto-attach.
12392  */
12393 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12394 {
12395 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts);
12396 	char *probe_type = NULL, *binary_path = NULL, *func_name = NULL, *func_off;
12397 	int n, c, ret = -EINVAL;
12398 	long offset = 0;
12399 
12400 	*link = NULL;
12401 
12402 	n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[^\n]",
12403 		   &probe_type, &binary_path, &func_name);
12404 	switch (n) {
12405 	case 1:
12406 		/* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
12407 		ret = 0;
12408 		break;
12409 	case 2:
12410 		pr_warn("prog '%s': section '%s' missing ':function[+offset]' specification\n",
12411 			prog->name, prog->sec_name);
12412 		break;
12413 	case 3:
12414 		/* check if user specifies `+offset`, if yes, this should be
12415 		 * the last part of the string, make sure sscanf read to EOL
12416 		 */
12417 		func_off = strrchr(func_name, '+');
12418 		if (func_off) {
12419 			n = sscanf(func_off, "+%li%n", &offset, &c);
12420 			if (n == 1 && *(func_off + c) == '\0')
12421 				func_off[0] = '\0';
12422 			else
12423 				offset = 0;
12424 		}
12425 		opts.retprobe = strcmp(probe_type, "uretprobe") == 0 ||
12426 				strcmp(probe_type, "uretprobe.s") == 0;
12427 		if (opts.retprobe && offset != 0) {
12428 			pr_warn("prog '%s': uretprobes do not support offset specification\n",
12429 				prog->name);
12430 			break;
12431 		}
12432 		opts.func_name = func_name;
12433 		*link = bpf_program__attach_uprobe_opts(prog, -1, binary_path, offset, &opts);
12434 		ret = libbpf_get_error(*link);
12435 		break;
12436 	default:
12437 		pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
12438 			prog->sec_name);
12439 		break;
12440 	}
12441 	free(probe_type);
12442 	free(binary_path);
12443 	free(func_name);
12444 
12445 	return ret;
12446 }
12447 
12448 struct bpf_link *bpf_program__attach_uprobe(const struct bpf_program *prog,
12449 					    bool retprobe, pid_t pid,
12450 					    const char *binary_path,
12451 					    size_t func_offset)
12452 {
12453 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts, .retprobe = retprobe);
12454 
12455 	return bpf_program__attach_uprobe_opts(prog, pid, binary_path, func_offset, &opts);
12456 }
12457 
12458 struct bpf_link *bpf_program__attach_usdt(const struct bpf_program *prog,
12459 					  pid_t pid, const char *binary_path,
12460 					  const char *usdt_provider, const char *usdt_name,
12461 					  const struct bpf_usdt_opts *opts)
12462 {
12463 	char resolved_path[512];
12464 	struct bpf_object *obj = prog->obj;
12465 	struct bpf_link *link;
12466 	__u64 usdt_cookie;
12467 	int err;
12468 
12469 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
12470 		return libbpf_err_ptr(-EINVAL);
12471 
12472 	if (bpf_program__fd(prog) < 0) {
12473 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
12474 			prog->name);
12475 		return libbpf_err_ptr(-EINVAL);
12476 	}
12477 
12478 	if (!binary_path)
12479 		return libbpf_err_ptr(-EINVAL);
12480 
12481 	if (!strchr(binary_path, '/')) {
12482 		err = resolve_full_path(binary_path, resolved_path, sizeof(resolved_path));
12483 		if (err) {
12484 			pr_warn("prog '%s': failed to resolve full path for '%s': %s\n",
12485 				prog->name, binary_path, errstr(err));
12486 			return libbpf_err_ptr(err);
12487 		}
12488 		binary_path = resolved_path;
12489 	}
12490 
12491 	/* USDT manager is instantiated lazily on first USDT attach. It will
12492 	 * be destroyed together with BPF object in bpf_object__close().
12493 	 */
12494 	if (IS_ERR(obj->usdt_man))
12495 		return libbpf_ptr(obj->usdt_man);
12496 	if (!obj->usdt_man) {
12497 		obj->usdt_man = usdt_manager_new(obj);
12498 		if (IS_ERR(obj->usdt_man))
12499 			return libbpf_ptr(obj->usdt_man);
12500 	}
12501 
12502 	usdt_cookie = OPTS_GET(opts, usdt_cookie, 0);
12503 	link = usdt_manager_attach_usdt(obj->usdt_man, prog, pid, binary_path,
12504 					usdt_provider, usdt_name, usdt_cookie);
12505 	err = libbpf_get_error(link);
12506 	if (err)
12507 		return libbpf_err_ptr(err);
12508 	return link;
12509 }
12510 
12511 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12512 {
12513 	char *path = NULL, *provider = NULL, *name = NULL;
12514 	const char *sec_name;
12515 	int n, err;
12516 
12517 	sec_name = bpf_program__section_name(prog);
12518 	if (strcmp(sec_name, "usdt") == 0) {
12519 		/* no auto-attach for just SEC("usdt") */
12520 		*link = NULL;
12521 		return 0;
12522 	}
12523 
12524 	n = sscanf(sec_name, "usdt/%m[^:]:%m[^:]:%m[^:]", &path, &provider, &name);
12525 	if (n != 3) {
12526 		pr_warn("invalid section '%s', expected SEC(\"usdt/<path>:<provider>:<name>\")\n",
12527 			sec_name);
12528 		err = -EINVAL;
12529 	} else {
12530 		*link = bpf_program__attach_usdt(prog, -1 /* any process */, path,
12531 						 provider, name, NULL);
12532 		err = libbpf_get_error(*link);
12533 	}
12534 	free(path);
12535 	free(provider);
12536 	free(name);
12537 	return err;
12538 }
12539 
12540 static int determine_tracepoint_id(const char *tp_category,
12541 				   const char *tp_name)
12542 {
12543 	char file[PATH_MAX];
12544 	int ret;
12545 
12546 	ret = snprintf(file, sizeof(file), "%s/events/%s/%s/id",
12547 		       tracefs_path(), tp_category, tp_name);
12548 	if (ret < 0)
12549 		return -errno;
12550 	if (ret >= sizeof(file)) {
12551 		pr_debug("tracepoint %s/%s path is too long\n",
12552 			 tp_category, tp_name);
12553 		return -E2BIG;
12554 	}
12555 	return parse_uint_from_file(file, "%d\n");
12556 }
12557 
12558 static int perf_event_open_tracepoint(const char *tp_category,
12559 				      const char *tp_name)
12560 {
12561 	const size_t attr_sz = sizeof(struct perf_event_attr);
12562 	struct perf_event_attr attr;
12563 	int tp_id, pfd, err;
12564 
12565 	tp_id = determine_tracepoint_id(tp_category, tp_name);
12566 	if (tp_id < 0) {
12567 		pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
12568 			tp_category, tp_name,
12569 			errstr(tp_id));
12570 		return tp_id;
12571 	}
12572 
12573 	memset(&attr, 0, attr_sz);
12574 	attr.type = PERF_TYPE_TRACEPOINT;
12575 	attr.size = attr_sz;
12576 	attr.config = tp_id;
12577 
12578 	pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
12579 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
12580 	if (pfd < 0) {
12581 		err = -errno;
12582 		pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
12583 			tp_category, tp_name,
12584 			errstr(err));
12585 		return err;
12586 	}
12587 	return pfd;
12588 }
12589 
12590 struct bpf_link *bpf_program__attach_tracepoint_opts(const struct bpf_program *prog,
12591 						     const char *tp_category,
12592 						     const char *tp_name,
12593 						     const struct bpf_tracepoint_opts *opts)
12594 {
12595 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
12596 	struct bpf_link *link;
12597 	int pfd, err;
12598 
12599 	if (!OPTS_VALID(opts, bpf_tracepoint_opts))
12600 		return libbpf_err_ptr(-EINVAL);
12601 
12602 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
12603 
12604 	pfd = perf_event_open_tracepoint(tp_category, tp_name);
12605 	if (pfd < 0) {
12606 		pr_warn("prog '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
12607 			prog->name, tp_category, tp_name,
12608 			errstr(pfd));
12609 		return libbpf_err_ptr(pfd);
12610 	}
12611 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
12612 	err = libbpf_get_error(link);
12613 	if (err) {
12614 		close(pfd);
12615 		pr_warn("prog '%s': failed to attach to tracepoint '%s/%s': %s\n",
12616 			prog->name, tp_category, tp_name,
12617 			errstr(err));
12618 		return libbpf_err_ptr(err);
12619 	}
12620 	return link;
12621 }
12622 
12623 struct bpf_link *bpf_program__attach_tracepoint(const struct bpf_program *prog,
12624 						const char *tp_category,
12625 						const char *tp_name)
12626 {
12627 	return bpf_program__attach_tracepoint_opts(prog, tp_category, tp_name, NULL);
12628 }
12629 
12630 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12631 {
12632 	char *sec_name, *tp_cat, *tp_name;
12633 
12634 	*link = NULL;
12635 
12636 	/* no auto-attach for SEC("tp") or SEC("tracepoint") */
12637 	if (strcmp(prog->sec_name, "tp") == 0 || strcmp(prog->sec_name, "tracepoint") == 0)
12638 		return 0;
12639 
12640 	sec_name = strdup(prog->sec_name);
12641 	if (!sec_name)
12642 		return -ENOMEM;
12643 
12644 	/* extract "tp/<category>/<name>" or "tracepoint/<category>/<name>" */
12645 	if (str_has_pfx(prog->sec_name, "tp/"))
12646 		tp_cat = sec_name + sizeof("tp/") - 1;
12647 	else
12648 		tp_cat = sec_name + sizeof("tracepoint/") - 1;
12649 	tp_name = strchr(tp_cat, '/');
12650 	if (!tp_name) {
12651 		free(sec_name);
12652 		return -EINVAL;
12653 	}
12654 	*tp_name = '\0';
12655 	tp_name++;
12656 
12657 	*link = bpf_program__attach_tracepoint(prog, tp_cat, tp_name);
12658 	free(sec_name);
12659 	return libbpf_get_error(*link);
12660 }
12661 
12662 struct bpf_link *
12663 bpf_program__attach_raw_tracepoint_opts(const struct bpf_program *prog,
12664 					const char *tp_name,
12665 					struct bpf_raw_tracepoint_opts *opts)
12666 {
12667 	LIBBPF_OPTS(bpf_raw_tp_opts, raw_opts);
12668 	struct bpf_link *link;
12669 	int prog_fd, pfd;
12670 
12671 	if (!OPTS_VALID(opts, bpf_raw_tracepoint_opts))
12672 		return libbpf_err_ptr(-EINVAL);
12673 
12674 	prog_fd = bpf_program__fd(prog);
12675 	if (prog_fd < 0) {
12676 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12677 		return libbpf_err_ptr(-EINVAL);
12678 	}
12679 
12680 	link = calloc(1, sizeof(*link));
12681 	if (!link)
12682 		return libbpf_err_ptr(-ENOMEM);
12683 	link->detach = &bpf_link__detach_fd;
12684 
12685 	raw_opts.tp_name = tp_name;
12686 	raw_opts.cookie = OPTS_GET(opts, cookie, 0);
12687 	pfd = bpf_raw_tracepoint_open_opts(prog_fd, &raw_opts);
12688 	if (pfd < 0) {
12689 		pfd = -errno;
12690 		free(link);
12691 		pr_warn("prog '%s': failed to attach to raw tracepoint '%s': %s\n",
12692 			prog->name, tp_name, errstr(pfd));
12693 		return libbpf_err_ptr(pfd);
12694 	}
12695 	link->fd = pfd;
12696 	return link;
12697 }
12698 
12699 struct bpf_link *bpf_program__attach_raw_tracepoint(const struct bpf_program *prog,
12700 						    const char *tp_name)
12701 {
12702 	return bpf_program__attach_raw_tracepoint_opts(prog, tp_name, NULL);
12703 }
12704 
12705 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12706 {
12707 	static const char *const prefixes[] = {
12708 		"raw_tp",
12709 		"raw_tracepoint",
12710 		"raw_tp.w",
12711 		"raw_tracepoint.w",
12712 	};
12713 	size_t i;
12714 	const char *tp_name = NULL;
12715 
12716 	*link = NULL;
12717 
12718 	for (i = 0; i < ARRAY_SIZE(prefixes); i++) {
12719 		size_t pfx_len;
12720 
12721 		if (!str_has_pfx(prog->sec_name, prefixes[i]))
12722 			continue;
12723 
12724 		pfx_len = strlen(prefixes[i]);
12725 		/* no auto-attach case of, e.g., SEC("raw_tp") */
12726 		if (prog->sec_name[pfx_len] == '\0')
12727 			return 0;
12728 
12729 		if (prog->sec_name[pfx_len] != '/')
12730 			continue;
12731 
12732 		tp_name = prog->sec_name + pfx_len + 1;
12733 		break;
12734 	}
12735 
12736 	if (!tp_name) {
12737 		pr_warn("prog '%s': invalid section name '%s'\n",
12738 			prog->name, prog->sec_name);
12739 		return -EINVAL;
12740 	}
12741 
12742 	*link = bpf_program__attach_raw_tracepoint(prog, tp_name);
12743 	return libbpf_get_error(*link);
12744 }
12745 
12746 /* Common logic for all BPF program types that attach to a btf_id */
12747 static struct bpf_link *bpf_program__attach_btf_id(const struct bpf_program *prog,
12748 						   const struct bpf_trace_opts *opts)
12749 {
12750 	LIBBPF_OPTS(bpf_link_create_opts, link_opts);
12751 	struct bpf_link *link;
12752 	int prog_fd, pfd;
12753 
12754 	if (!OPTS_VALID(opts, bpf_trace_opts))
12755 		return libbpf_err_ptr(-EINVAL);
12756 
12757 	prog_fd = bpf_program__fd(prog);
12758 	if (prog_fd < 0) {
12759 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12760 		return libbpf_err_ptr(-EINVAL);
12761 	}
12762 
12763 	link = calloc(1, sizeof(*link));
12764 	if (!link)
12765 		return libbpf_err_ptr(-ENOMEM);
12766 	link->detach = &bpf_link__detach_fd;
12767 
12768 	/* libbpf is smart enough to redirect to BPF_RAW_TRACEPOINT_OPEN on old kernels */
12769 	link_opts.tracing.cookie = OPTS_GET(opts, cookie, 0);
12770 	pfd = bpf_link_create(prog_fd, 0, bpf_program__expected_attach_type(prog), &link_opts);
12771 	if (pfd < 0) {
12772 		pfd = -errno;
12773 		free(link);
12774 		pr_warn("prog '%s': failed to attach: %s\n",
12775 			prog->name, errstr(pfd));
12776 		return libbpf_err_ptr(pfd);
12777 	}
12778 	link->fd = pfd;
12779 	return link;
12780 }
12781 
12782 struct bpf_link *bpf_program__attach_trace(const struct bpf_program *prog)
12783 {
12784 	return bpf_program__attach_btf_id(prog, NULL);
12785 }
12786 
12787 struct bpf_link *bpf_program__attach_trace_opts(const struct bpf_program *prog,
12788 						const struct bpf_trace_opts *opts)
12789 {
12790 	return bpf_program__attach_btf_id(prog, opts);
12791 }
12792 
12793 struct bpf_link *bpf_program__attach_lsm(const struct bpf_program *prog)
12794 {
12795 	return bpf_program__attach_btf_id(prog, NULL);
12796 }
12797 
12798 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12799 {
12800 	*link = bpf_program__attach_trace(prog);
12801 	return libbpf_get_error(*link);
12802 }
12803 
12804 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12805 {
12806 	*link = bpf_program__attach_lsm(prog);
12807 	return libbpf_get_error(*link);
12808 }
12809 
12810 static struct bpf_link *
12811 bpf_program_attach_fd(const struct bpf_program *prog,
12812 		      int target_fd, const char *target_name,
12813 		      const struct bpf_link_create_opts *opts)
12814 {
12815 	enum bpf_attach_type attach_type;
12816 	struct bpf_link *link;
12817 	int prog_fd, link_fd;
12818 
12819 	prog_fd = bpf_program__fd(prog);
12820 	if (prog_fd < 0) {
12821 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12822 		return libbpf_err_ptr(-EINVAL);
12823 	}
12824 
12825 	link = calloc(1, sizeof(*link));
12826 	if (!link)
12827 		return libbpf_err_ptr(-ENOMEM);
12828 	link->detach = &bpf_link__detach_fd;
12829 
12830 	attach_type = bpf_program__expected_attach_type(prog);
12831 	link_fd = bpf_link_create(prog_fd, target_fd, attach_type, opts);
12832 	if (link_fd < 0) {
12833 		link_fd = -errno;
12834 		free(link);
12835 		pr_warn("prog '%s': failed to attach to %s: %s\n",
12836 			prog->name, target_name,
12837 			errstr(link_fd));
12838 		return libbpf_err_ptr(link_fd);
12839 	}
12840 	link->fd = link_fd;
12841 	return link;
12842 }
12843 
12844 struct bpf_link *
12845 bpf_program__attach_cgroup(const struct bpf_program *prog, int cgroup_fd)
12846 {
12847 	return bpf_program_attach_fd(prog, cgroup_fd, "cgroup", NULL);
12848 }
12849 
12850 struct bpf_link *
12851 bpf_program__attach_netns(const struct bpf_program *prog, int netns_fd)
12852 {
12853 	return bpf_program_attach_fd(prog, netns_fd, "netns", NULL);
12854 }
12855 
12856 struct bpf_link *
12857 bpf_program__attach_sockmap(const struct bpf_program *prog, int map_fd)
12858 {
12859 	return bpf_program_attach_fd(prog, map_fd, "sockmap", NULL);
12860 }
12861 
12862 struct bpf_link *bpf_program__attach_xdp(const struct bpf_program *prog, int ifindex)
12863 {
12864 	/* target_fd/target_ifindex use the same field in LINK_CREATE */
12865 	return bpf_program_attach_fd(prog, ifindex, "xdp", NULL);
12866 }
12867 
12868 struct bpf_link *
12869 bpf_program__attach_cgroup_opts(const struct bpf_program *prog, int cgroup_fd,
12870 				const struct bpf_cgroup_opts *opts)
12871 {
12872 	LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
12873 	__u32 relative_id;
12874 	int relative_fd;
12875 
12876 	if (!OPTS_VALID(opts, bpf_cgroup_opts))
12877 		return libbpf_err_ptr(-EINVAL);
12878 
12879 	relative_id = OPTS_GET(opts, relative_id, 0);
12880 	relative_fd = OPTS_GET(opts, relative_fd, 0);
12881 
12882 	if (relative_fd && relative_id) {
12883 		pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
12884 			prog->name);
12885 		return libbpf_err_ptr(-EINVAL);
12886 	}
12887 
12888 	link_create_opts.cgroup.expected_revision = OPTS_GET(opts, expected_revision, 0);
12889 	link_create_opts.cgroup.relative_fd = relative_fd;
12890 	link_create_opts.cgroup.relative_id = relative_id;
12891 	link_create_opts.flags = OPTS_GET(opts, flags, 0);
12892 
12893 	return bpf_program_attach_fd(prog, cgroup_fd, "cgroup", &link_create_opts);
12894 }
12895 
12896 struct bpf_link *
12897 bpf_program__attach_tcx(const struct bpf_program *prog, int ifindex,
12898 			const struct bpf_tcx_opts *opts)
12899 {
12900 	LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
12901 	__u32 relative_id;
12902 	int relative_fd;
12903 
12904 	if (!OPTS_VALID(opts, bpf_tcx_opts))
12905 		return libbpf_err_ptr(-EINVAL);
12906 
12907 	relative_id = OPTS_GET(opts, relative_id, 0);
12908 	relative_fd = OPTS_GET(opts, relative_fd, 0);
12909 
12910 	/* validate we don't have unexpected combinations of non-zero fields */
12911 	if (!ifindex) {
12912 		pr_warn("prog '%s': target netdevice ifindex cannot be zero\n",
12913 			prog->name);
12914 		return libbpf_err_ptr(-EINVAL);
12915 	}
12916 	if (relative_fd && relative_id) {
12917 		pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
12918 			prog->name);
12919 		return libbpf_err_ptr(-EINVAL);
12920 	}
12921 
12922 	link_create_opts.tcx.expected_revision = OPTS_GET(opts, expected_revision, 0);
12923 	link_create_opts.tcx.relative_fd = relative_fd;
12924 	link_create_opts.tcx.relative_id = relative_id;
12925 	link_create_opts.flags = OPTS_GET(opts, flags, 0);
12926 
12927 	/* target_fd/target_ifindex use the same field in LINK_CREATE */
12928 	return bpf_program_attach_fd(prog, ifindex, "tcx", &link_create_opts);
12929 }
12930 
12931 struct bpf_link *
12932 bpf_program__attach_netkit(const struct bpf_program *prog, int ifindex,
12933 			   const struct bpf_netkit_opts *opts)
12934 {
12935 	LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
12936 	__u32 relative_id;
12937 	int relative_fd;
12938 
12939 	if (!OPTS_VALID(opts, bpf_netkit_opts))
12940 		return libbpf_err_ptr(-EINVAL);
12941 
12942 	relative_id = OPTS_GET(opts, relative_id, 0);
12943 	relative_fd = OPTS_GET(opts, relative_fd, 0);
12944 
12945 	/* validate we don't have unexpected combinations of non-zero fields */
12946 	if (!ifindex) {
12947 		pr_warn("prog '%s': target netdevice ifindex cannot be zero\n",
12948 			prog->name);
12949 		return libbpf_err_ptr(-EINVAL);
12950 	}
12951 	if (relative_fd && relative_id) {
12952 		pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
12953 			prog->name);
12954 		return libbpf_err_ptr(-EINVAL);
12955 	}
12956 
12957 	link_create_opts.netkit.expected_revision = OPTS_GET(opts, expected_revision, 0);
12958 	link_create_opts.netkit.relative_fd = relative_fd;
12959 	link_create_opts.netkit.relative_id = relative_id;
12960 	link_create_opts.flags = OPTS_GET(opts, flags, 0);
12961 
12962 	return bpf_program_attach_fd(prog, ifindex, "netkit", &link_create_opts);
12963 }
12964 
12965 struct bpf_link *bpf_program__attach_freplace(const struct bpf_program *prog,
12966 					      int target_fd,
12967 					      const char *attach_func_name)
12968 {
12969 	int btf_id;
12970 
12971 	if (!!target_fd != !!attach_func_name) {
12972 		pr_warn("prog '%s': supply none or both of target_fd and attach_func_name\n",
12973 			prog->name);
12974 		return libbpf_err_ptr(-EINVAL);
12975 	}
12976 
12977 	if (prog->type != BPF_PROG_TYPE_EXT) {
12978 		pr_warn("prog '%s': only BPF_PROG_TYPE_EXT can attach as freplace\n",
12979 			prog->name);
12980 		return libbpf_err_ptr(-EINVAL);
12981 	}
12982 
12983 	if (target_fd) {
12984 		LIBBPF_OPTS(bpf_link_create_opts, target_opts);
12985 
12986 		btf_id = libbpf_find_prog_btf_id(attach_func_name, target_fd, prog->obj->token_fd);
12987 		if (btf_id < 0)
12988 			return libbpf_err_ptr(btf_id);
12989 
12990 		target_opts.target_btf_id = btf_id;
12991 
12992 		return bpf_program_attach_fd(prog, target_fd, "freplace",
12993 					     &target_opts);
12994 	} else {
12995 		/* no target, so use raw_tracepoint_open for compatibility
12996 		 * with old kernels
12997 		 */
12998 		return bpf_program__attach_trace(prog);
12999 	}
13000 }
13001 
13002 struct bpf_link *
13003 bpf_program__attach_iter(const struct bpf_program *prog,
13004 			 const struct bpf_iter_attach_opts *opts)
13005 {
13006 	DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
13007 	struct bpf_link *link;
13008 	int prog_fd, link_fd;
13009 	__u32 target_fd = 0;
13010 
13011 	if (!OPTS_VALID(opts, bpf_iter_attach_opts))
13012 		return libbpf_err_ptr(-EINVAL);
13013 
13014 	link_create_opts.iter_info = OPTS_GET(opts, link_info, (void *)0);
13015 	link_create_opts.iter_info_len = OPTS_GET(opts, link_info_len, 0);
13016 
13017 	prog_fd = bpf_program__fd(prog);
13018 	if (prog_fd < 0) {
13019 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
13020 		return libbpf_err_ptr(-EINVAL);
13021 	}
13022 
13023 	link = calloc(1, sizeof(*link));
13024 	if (!link)
13025 		return libbpf_err_ptr(-ENOMEM);
13026 	link->detach = &bpf_link__detach_fd;
13027 
13028 	link_fd = bpf_link_create(prog_fd, target_fd, BPF_TRACE_ITER,
13029 				  &link_create_opts);
13030 	if (link_fd < 0) {
13031 		link_fd = -errno;
13032 		free(link);
13033 		pr_warn("prog '%s': failed to attach to iterator: %s\n",
13034 			prog->name, errstr(link_fd));
13035 		return libbpf_err_ptr(link_fd);
13036 	}
13037 	link->fd = link_fd;
13038 	return link;
13039 }
13040 
13041 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link)
13042 {
13043 	*link = bpf_program__attach_iter(prog, NULL);
13044 	return libbpf_get_error(*link);
13045 }
13046 
13047 struct bpf_link *bpf_program__attach_netfilter(const struct bpf_program *prog,
13048 					       const struct bpf_netfilter_opts *opts)
13049 {
13050 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
13051 	struct bpf_link *link;
13052 	int prog_fd, link_fd;
13053 
13054 	if (!OPTS_VALID(opts, bpf_netfilter_opts))
13055 		return libbpf_err_ptr(-EINVAL);
13056 
13057 	prog_fd = bpf_program__fd(prog);
13058 	if (prog_fd < 0) {
13059 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
13060 		return libbpf_err_ptr(-EINVAL);
13061 	}
13062 
13063 	link = calloc(1, sizeof(*link));
13064 	if (!link)
13065 		return libbpf_err_ptr(-ENOMEM);
13066 
13067 	link->detach = &bpf_link__detach_fd;
13068 
13069 	lopts.netfilter.pf = OPTS_GET(opts, pf, 0);
13070 	lopts.netfilter.hooknum = OPTS_GET(opts, hooknum, 0);
13071 	lopts.netfilter.priority = OPTS_GET(opts, priority, 0);
13072 	lopts.netfilter.flags = OPTS_GET(opts, flags, 0);
13073 
13074 	link_fd = bpf_link_create(prog_fd, 0, BPF_NETFILTER, &lopts);
13075 	if (link_fd < 0) {
13076 		link_fd = -errno;
13077 		free(link);
13078 		pr_warn("prog '%s': failed to attach to netfilter: %s\n",
13079 			prog->name, errstr(link_fd));
13080 		return libbpf_err_ptr(link_fd);
13081 	}
13082 	link->fd = link_fd;
13083 
13084 	return link;
13085 }
13086 
13087 struct bpf_link *bpf_program__attach(const struct bpf_program *prog)
13088 {
13089 	struct bpf_link *link = NULL;
13090 	int err;
13091 
13092 	if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
13093 		return libbpf_err_ptr(-EOPNOTSUPP);
13094 
13095 	if (bpf_program__fd(prog) < 0) {
13096 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
13097 			prog->name);
13098 		return libbpf_err_ptr(-EINVAL);
13099 	}
13100 
13101 	err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, &link);
13102 	if (err)
13103 		return libbpf_err_ptr(err);
13104 
13105 	/* When calling bpf_program__attach() explicitly, auto-attach support
13106 	 * is expected to work, so NULL returned link is considered an error.
13107 	 * This is different for skeleton's attach, see comment in
13108 	 * bpf_object__attach_skeleton().
13109 	 */
13110 	if (!link)
13111 		return libbpf_err_ptr(-EOPNOTSUPP);
13112 
13113 	return link;
13114 }
13115 
13116 struct bpf_link_struct_ops {
13117 	struct bpf_link link;
13118 	int map_fd;
13119 };
13120 
13121 static int bpf_link__detach_struct_ops(struct bpf_link *link)
13122 {
13123 	struct bpf_link_struct_ops *st_link;
13124 	__u32 zero = 0;
13125 
13126 	st_link = container_of(link, struct bpf_link_struct_ops, link);
13127 
13128 	if (st_link->map_fd < 0)
13129 		/* w/o a real link */
13130 		return bpf_map_delete_elem(link->fd, &zero);
13131 
13132 	return close(link->fd);
13133 }
13134 
13135 struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map)
13136 {
13137 	struct bpf_link_struct_ops *link;
13138 	__u32 zero = 0;
13139 	int err, fd;
13140 
13141 	if (!bpf_map__is_struct_ops(map)) {
13142 		pr_warn("map '%s': can't attach non-struct_ops map\n", map->name);
13143 		return libbpf_err_ptr(-EINVAL);
13144 	}
13145 
13146 	if (map->fd < 0) {
13147 		pr_warn("map '%s': can't attach BPF map without FD (was it created?)\n", map->name);
13148 		return libbpf_err_ptr(-EINVAL);
13149 	}
13150 
13151 	link = calloc(1, sizeof(*link));
13152 	if (!link)
13153 		return libbpf_err_ptr(-EINVAL);
13154 
13155 	/* kern_vdata should be prepared during the loading phase. */
13156 	err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
13157 	/* It can be EBUSY if the map has been used to create or
13158 	 * update a link before.  We don't allow updating the value of
13159 	 * a struct_ops once it is set.  That ensures that the value
13160 	 * never changed.  So, it is safe to skip EBUSY.
13161 	 */
13162 	if (err && (!(map->def.map_flags & BPF_F_LINK) || err != -EBUSY)) {
13163 		free(link);
13164 		return libbpf_err_ptr(err);
13165 	}
13166 
13167 	link->link.detach = bpf_link__detach_struct_ops;
13168 
13169 	if (!(map->def.map_flags & BPF_F_LINK)) {
13170 		/* w/o a real link */
13171 		link->link.fd = map->fd;
13172 		link->map_fd = -1;
13173 		return &link->link;
13174 	}
13175 
13176 	fd = bpf_link_create(map->fd, 0, BPF_STRUCT_OPS, NULL);
13177 	if (fd < 0) {
13178 		free(link);
13179 		return libbpf_err_ptr(fd);
13180 	}
13181 
13182 	link->link.fd = fd;
13183 	link->map_fd = map->fd;
13184 
13185 	return &link->link;
13186 }
13187 
13188 /*
13189  * Swap the back struct_ops of a link with a new struct_ops map.
13190  */
13191 int bpf_link__update_map(struct bpf_link *link, const struct bpf_map *map)
13192 {
13193 	struct bpf_link_struct_ops *st_ops_link;
13194 	__u32 zero = 0;
13195 	int err;
13196 
13197 	if (!bpf_map__is_struct_ops(map))
13198 		return libbpf_err(-EINVAL);
13199 
13200 	if (map->fd < 0) {
13201 		pr_warn("map '%s': can't use BPF map without FD (was it created?)\n", map->name);
13202 		return libbpf_err(-EINVAL);
13203 	}
13204 
13205 	st_ops_link = container_of(link, struct bpf_link_struct_ops, link);
13206 	/* Ensure the type of a link is correct */
13207 	if (st_ops_link->map_fd < 0)
13208 		return libbpf_err(-EINVAL);
13209 
13210 	err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
13211 	/* It can be EBUSY if the map has been used to create or
13212 	 * update a link before.  We don't allow updating the value of
13213 	 * a struct_ops once it is set.  That ensures that the value
13214 	 * never changed.  So, it is safe to skip EBUSY.
13215 	 */
13216 	if (err && err != -EBUSY)
13217 		return err;
13218 
13219 	err = bpf_link_update(link->fd, map->fd, NULL);
13220 	if (err < 0)
13221 		return err;
13222 
13223 	st_ops_link->map_fd = map->fd;
13224 
13225 	return 0;
13226 }
13227 
13228 typedef enum bpf_perf_event_ret (*bpf_perf_event_print_t)(struct perf_event_header *hdr,
13229 							  void *private_data);
13230 
13231 static enum bpf_perf_event_ret
13232 perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
13233 		       void **copy_mem, size_t *copy_size,
13234 		       bpf_perf_event_print_t fn, void *private_data)
13235 {
13236 	struct perf_event_mmap_page *header = mmap_mem;
13237 	__u64 data_head = ring_buffer_read_head(header);
13238 	__u64 data_tail = header->data_tail;
13239 	void *base = ((__u8 *)header) + page_size;
13240 	int ret = LIBBPF_PERF_EVENT_CONT;
13241 	struct perf_event_header *ehdr;
13242 	size_t ehdr_size;
13243 
13244 	while (data_head != data_tail) {
13245 		ehdr = base + (data_tail & (mmap_size - 1));
13246 		ehdr_size = ehdr->size;
13247 
13248 		if (((void *)ehdr) + ehdr_size > base + mmap_size) {
13249 			void *copy_start = ehdr;
13250 			size_t len_first = base + mmap_size - copy_start;
13251 			size_t len_secnd = ehdr_size - len_first;
13252 
13253 			if (*copy_size < ehdr_size) {
13254 				free(*copy_mem);
13255 				*copy_mem = malloc(ehdr_size);
13256 				if (!*copy_mem) {
13257 					*copy_size = 0;
13258 					ret = LIBBPF_PERF_EVENT_ERROR;
13259 					break;
13260 				}
13261 				*copy_size = ehdr_size;
13262 			}
13263 
13264 			memcpy(*copy_mem, copy_start, len_first);
13265 			memcpy(*copy_mem + len_first, base, len_secnd);
13266 			ehdr = *copy_mem;
13267 		}
13268 
13269 		ret = fn(ehdr, private_data);
13270 		data_tail += ehdr_size;
13271 		if (ret != LIBBPF_PERF_EVENT_CONT)
13272 			break;
13273 	}
13274 
13275 	ring_buffer_write_tail(header, data_tail);
13276 	return libbpf_err(ret);
13277 }
13278 
13279 struct perf_buffer;
13280 
13281 struct perf_buffer_params {
13282 	struct perf_event_attr *attr;
13283 	/* if event_cb is specified, it takes precendence */
13284 	perf_buffer_event_fn event_cb;
13285 	/* sample_cb and lost_cb are higher-level common-case callbacks */
13286 	perf_buffer_sample_fn sample_cb;
13287 	perf_buffer_lost_fn lost_cb;
13288 	void *ctx;
13289 	int cpu_cnt;
13290 	int *cpus;
13291 	int *map_keys;
13292 };
13293 
13294 struct perf_cpu_buf {
13295 	struct perf_buffer *pb;
13296 	void *base; /* mmap()'ed memory */
13297 	void *buf; /* for reconstructing segmented data */
13298 	size_t buf_size;
13299 	int fd;
13300 	int cpu;
13301 	int map_key;
13302 };
13303 
13304 struct perf_buffer {
13305 	perf_buffer_event_fn event_cb;
13306 	perf_buffer_sample_fn sample_cb;
13307 	perf_buffer_lost_fn lost_cb;
13308 	void *ctx; /* passed into callbacks */
13309 
13310 	size_t page_size;
13311 	size_t mmap_size;
13312 	struct perf_cpu_buf **cpu_bufs;
13313 	struct epoll_event *events;
13314 	int cpu_cnt; /* number of allocated CPU buffers */
13315 	int epoll_fd; /* perf event FD */
13316 	int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
13317 };
13318 
13319 static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
13320 				      struct perf_cpu_buf *cpu_buf)
13321 {
13322 	if (!cpu_buf)
13323 		return;
13324 	if (cpu_buf->base &&
13325 	    munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
13326 		pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
13327 	if (cpu_buf->fd >= 0) {
13328 		ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
13329 		close(cpu_buf->fd);
13330 	}
13331 	free(cpu_buf->buf);
13332 	free(cpu_buf);
13333 }
13334 
13335 void perf_buffer__free(struct perf_buffer *pb)
13336 {
13337 	int i;
13338 
13339 	if (IS_ERR_OR_NULL(pb))
13340 		return;
13341 	if (pb->cpu_bufs) {
13342 		for (i = 0; i < pb->cpu_cnt; i++) {
13343 			struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
13344 
13345 			if (!cpu_buf)
13346 				continue;
13347 
13348 			bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
13349 			perf_buffer__free_cpu_buf(pb, cpu_buf);
13350 		}
13351 		free(pb->cpu_bufs);
13352 	}
13353 	if (pb->epoll_fd >= 0)
13354 		close(pb->epoll_fd);
13355 	free(pb->events);
13356 	free(pb);
13357 }
13358 
13359 static struct perf_cpu_buf *
13360 perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
13361 			  int cpu, int map_key)
13362 {
13363 	struct perf_cpu_buf *cpu_buf;
13364 	int err;
13365 
13366 	cpu_buf = calloc(1, sizeof(*cpu_buf));
13367 	if (!cpu_buf)
13368 		return ERR_PTR(-ENOMEM);
13369 
13370 	cpu_buf->pb = pb;
13371 	cpu_buf->cpu = cpu;
13372 	cpu_buf->map_key = map_key;
13373 
13374 	cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
13375 			      -1, PERF_FLAG_FD_CLOEXEC);
13376 	if (cpu_buf->fd < 0) {
13377 		err = -errno;
13378 		pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
13379 			cpu, errstr(err));
13380 		goto error;
13381 	}
13382 
13383 	cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
13384 			     PROT_READ | PROT_WRITE, MAP_SHARED,
13385 			     cpu_buf->fd, 0);
13386 	if (cpu_buf->base == MAP_FAILED) {
13387 		cpu_buf->base = NULL;
13388 		err = -errno;
13389 		pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
13390 			cpu, errstr(err));
13391 		goto error;
13392 	}
13393 
13394 	if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
13395 		err = -errno;
13396 		pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
13397 			cpu, errstr(err));
13398 		goto error;
13399 	}
13400 
13401 	return cpu_buf;
13402 
13403 error:
13404 	perf_buffer__free_cpu_buf(pb, cpu_buf);
13405 	return (struct perf_cpu_buf *)ERR_PTR(err);
13406 }
13407 
13408 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
13409 					      struct perf_buffer_params *p);
13410 
13411 struct perf_buffer *perf_buffer__new(int map_fd, size_t page_cnt,
13412 				     perf_buffer_sample_fn sample_cb,
13413 				     perf_buffer_lost_fn lost_cb,
13414 				     void *ctx,
13415 				     const struct perf_buffer_opts *opts)
13416 {
13417 	const size_t attr_sz = sizeof(struct perf_event_attr);
13418 	struct perf_buffer_params p = {};
13419 	struct perf_event_attr attr;
13420 	__u32 sample_period;
13421 
13422 	if (!OPTS_VALID(opts, perf_buffer_opts))
13423 		return libbpf_err_ptr(-EINVAL);
13424 
13425 	sample_period = OPTS_GET(opts, sample_period, 1);
13426 	if (!sample_period)
13427 		sample_period = 1;
13428 
13429 	memset(&attr, 0, attr_sz);
13430 	attr.size = attr_sz;
13431 	attr.config = PERF_COUNT_SW_BPF_OUTPUT;
13432 	attr.type = PERF_TYPE_SOFTWARE;
13433 	attr.sample_type = PERF_SAMPLE_RAW;
13434 	attr.wakeup_events = sample_period;
13435 
13436 	p.attr = &attr;
13437 	p.sample_cb = sample_cb;
13438 	p.lost_cb = lost_cb;
13439 	p.ctx = ctx;
13440 
13441 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
13442 }
13443 
13444 struct perf_buffer *perf_buffer__new_raw(int map_fd, size_t page_cnt,
13445 					 struct perf_event_attr *attr,
13446 					 perf_buffer_event_fn event_cb, void *ctx,
13447 					 const struct perf_buffer_raw_opts *opts)
13448 {
13449 	struct perf_buffer_params p = {};
13450 
13451 	if (!attr)
13452 		return libbpf_err_ptr(-EINVAL);
13453 
13454 	if (!OPTS_VALID(opts, perf_buffer_raw_opts))
13455 		return libbpf_err_ptr(-EINVAL);
13456 
13457 	p.attr = attr;
13458 	p.event_cb = event_cb;
13459 	p.ctx = ctx;
13460 	p.cpu_cnt = OPTS_GET(opts, cpu_cnt, 0);
13461 	p.cpus = OPTS_GET(opts, cpus, NULL);
13462 	p.map_keys = OPTS_GET(opts, map_keys, NULL);
13463 
13464 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
13465 }
13466 
13467 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
13468 					      struct perf_buffer_params *p)
13469 {
13470 	const char *online_cpus_file = "/sys/devices/system/cpu/online";
13471 	struct bpf_map_info map;
13472 	struct perf_buffer *pb;
13473 	bool *online = NULL;
13474 	__u32 map_info_len;
13475 	int err, i, j, n;
13476 
13477 	if (page_cnt == 0 || (page_cnt & (page_cnt - 1))) {
13478 		pr_warn("page count should be power of two, but is %zu\n",
13479 			page_cnt);
13480 		return ERR_PTR(-EINVAL);
13481 	}
13482 
13483 	/* best-effort sanity checks */
13484 	memset(&map, 0, sizeof(map));
13485 	map_info_len = sizeof(map);
13486 	err = bpf_map_get_info_by_fd(map_fd, &map, &map_info_len);
13487 	if (err) {
13488 		err = -errno;
13489 		/* if BPF_OBJ_GET_INFO_BY_FD is supported, will return
13490 		 * -EBADFD, -EFAULT, or -E2BIG on real error
13491 		 */
13492 		if (err != -EINVAL) {
13493 			pr_warn("failed to get map info for map FD %d: %s\n",
13494 				map_fd, errstr(err));
13495 			return ERR_PTR(err);
13496 		}
13497 		pr_debug("failed to get map info for FD %d; API not supported? Ignoring...\n",
13498 			 map_fd);
13499 	} else {
13500 		if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
13501 			pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
13502 				map.name);
13503 			return ERR_PTR(-EINVAL);
13504 		}
13505 	}
13506 
13507 	pb = calloc(1, sizeof(*pb));
13508 	if (!pb)
13509 		return ERR_PTR(-ENOMEM);
13510 
13511 	pb->event_cb = p->event_cb;
13512 	pb->sample_cb = p->sample_cb;
13513 	pb->lost_cb = p->lost_cb;
13514 	pb->ctx = p->ctx;
13515 
13516 	pb->page_size = getpagesize();
13517 	pb->mmap_size = pb->page_size * page_cnt;
13518 	pb->map_fd = map_fd;
13519 
13520 	pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
13521 	if (pb->epoll_fd < 0) {
13522 		err = -errno;
13523 		pr_warn("failed to create epoll instance: %s\n",
13524 			errstr(err));
13525 		goto error;
13526 	}
13527 
13528 	if (p->cpu_cnt > 0) {
13529 		pb->cpu_cnt = p->cpu_cnt;
13530 	} else {
13531 		pb->cpu_cnt = libbpf_num_possible_cpus();
13532 		if (pb->cpu_cnt < 0) {
13533 			err = pb->cpu_cnt;
13534 			goto error;
13535 		}
13536 		if (map.max_entries && map.max_entries < pb->cpu_cnt)
13537 			pb->cpu_cnt = map.max_entries;
13538 	}
13539 
13540 	pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
13541 	if (!pb->events) {
13542 		err = -ENOMEM;
13543 		pr_warn("failed to allocate events: out of memory\n");
13544 		goto error;
13545 	}
13546 	pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
13547 	if (!pb->cpu_bufs) {
13548 		err = -ENOMEM;
13549 		pr_warn("failed to allocate buffers: out of memory\n");
13550 		goto error;
13551 	}
13552 
13553 	err = parse_cpu_mask_file(online_cpus_file, &online, &n);
13554 	if (err) {
13555 		pr_warn("failed to get online CPU mask: %s\n", errstr(err));
13556 		goto error;
13557 	}
13558 
13559 	for (i = 0, j = 0; i < pb->cpu_cnt; i++) {
13560 		struct perf_cpu_buf *cpu_buf;
13561 		int cpu, map_key;
13562 
13563 		cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
13564 		map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
13565 
13566 		/* in case user didn't explicitly requested particular CPUs to
13567 		 * be attached to, skip offline/not present CPUs
13568 		 */
13569 		if (p->cpu_cnt <= 0 && (cpu >= n || !online[cpu]))
13570 			continue;
13571 
13572 		cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
13573 		if (IS_ERR(cpu_buf)) {
13574 			err = PTR_ERR(cpu_buf);
13575 			goto error;
13576 		}
13577 
13578 		pb->cpu_bufs[j] = cpu_buf;
13579 
13580 		err = bpf_map_update_elem(pb->map_fd, &map_key,
13581 					  &cpu_buf->fd, 0);
13582 		if (err) {
13583 			err = -errno;
13584 			pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
13585 				cpu, map_key, cpu_buf->fd,
13586 				errstr(err));
13587 			goto error;
13588 		}
13589 
13590 		pb->events[j].events = EPOLLIN;
13591 		pb->events[j].data.ptr = cpu_buf;
13592 		if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
13593 			      &pb->events[j]) < 0) {
13594 			err = -errno;
13595 			pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
13596 				cpu, cpu_buf->fd,
13597 				errstr(err));
13598 			goto error;
13599 		}
13600 		j++;
13601 	}
13602 	pb->cpu_cnt = j;
13603 	free(online);
13604 
13605 	return pb;
13606 
13607 error:
13608 	free(online);
13609 	if (pb)
13610 		perf_buffer__free(pb);
13611 	return ERR_PTR(err);
13612 }
13613 
13614 struct perf_sample_raw {
13615 	struct perf_event_header header;
13616 	uint32_t size;
13617 	char data[];
13618 };
13619 
13620 struct perf_sample_lost {
13621 	struct perf_event_header header;
13622 	uint64_t id;
13623 	uint64_t lost;
13624 	uint64_t sample_id;
13625 };
13626 
13627 static enum bpf_perf_event_ret
13628 perf_buffer__process_record(struct perf_event_header *e, void *ctx)
13629 {
13630 	struct perf_cpu_buf *cpu_buf = ctx;
13631 	struct perf_buffer *pb = cpu_buf->pb;
13632 	void *data = e;
13633 
13634 	/* user wants full control over parsing perf event */
13635 	if (pb->event_cb)
13636 		return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
13637 
13638 	switch (e->type) {
13639 	case PERF_RECORD_SAMPLE: {
13640 		struct perf_sample_raw *s = data;
13641 
13642 		if (pb->sample_cb)
13643 			pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
13644 		break;
13645 	}
13646 	case PERF_RECORD_LOST: {
13647 		struct perf_sample_lost *s = data;
13648 
13649 		if (pb->lost_cb)
13650 			pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
13651 		break;
13652 	}
13653 	default:
13654 		pr_warn("unknown perf sample type %d\n", e->type);
13655 		return LIBBPF_PERF_EVENT_ERROR;
13656 	}
13657 	return LIBBPF_PERF_EVENT_CONT;
13658 }
13659 
13660 static int perf_buffer__process_records(struct perf_buffer *pb,
13661 					struct perf_cpu_buf *cpu_buf)
13662 {
13663 	enum bpf_perf_event_ret ret;
13664 
13665 	ret = perf_event_read_simple(cpu_buf->base, pb->mmap_size,
13666 				     pb->page_size, &cpu_buf->buf,
13667 				     &cpu_buf->buf_size,
13668 				     perf_buffer__process_record, cpu_buf);
13669 	if (ret != LIBBPF_PERF_EVENT_CONT)
13670 		return ret;
13671 	return 0;
13672 }
13673 
13674 int perf_buffer__epoll_fd(const struct perf_buffer *pb)
13675 {
13676 	return pb->epoll_fd;
13677 }
13678 
13679 int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
13680 {
13681 	int i, cnt, err;
13682 
13683 	cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
13684 	if (cnt < 0)
13685 		return -errno;
13686 
13687 	for (i = 0; i < cnt; i++) {
13688 		struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
13689 
13690 		err = perf_buffer__process_records(pb, cpu_buf);
13691 		if (err) {
13692 			pr_warn("error while processing records: %s\n", errstr(err));
13693 			return libbpf_err(err);
13694 		}
13695 	}
13696 	return cnt;
13697 }
13698 
13699 /* Return number of PERF_EVENT_ARRAY map slots set up by this perf_buffer
13700  * manager.
13701  */
13702 size_t perf_buffer__buffer_cnt(const struct perf_buffer *pb)
13703 {
13704 	return pb->cpu_cnt;
13705 }
13706 
13707 /*
13708  * Return perf_event FD of a ring buffer in *buf_idx* slot of
13709  * PERF_EVENT_ARRAY BPF map. This FD can be polled for new data using
13710  * select()/poll()/epoll() Linux syscalls.
13711  */
13712 int perf_buffer__buffer_fd(const struct perf_buffer *pb, size_t buf_idx)
13713 {
13714 	struct perf_cpu_buf *cpu_buf;
13715 
13716 	if (buf_idx >= pb->cpu_cnt)
13717 		return libbpf_err(-EINVAL);
13718 
13719 	cpu_buf = pb->cpu_bufs[buf_idx];
13720 	if (!cpu_buf)
13721 		return libbpf_err(-ENOENT);
13722 
13723 	return cpu_buf->fd;
13724 }
13725 
13726 int perf_buffer__buffer(struct perf_buffer *pb, int buf_idx, void **buf, size_t *buf_size)
13727 {
13728 	struct perf_cpu_buf *cpu_buf;
13729 
13730 	if (buf_idx >= pb->cpu_cnt)
13731 		return libbpf_err(-EINVAL);
13732 
13733 	cpu_buf = pb->cpu_bufs[buf_idx];
13734 	if (!cpu_buf)
13735 		return libbpf_err(-ENOENT);
13736 
13737 	*buf = cpu_buf->base;
13738 	*buf_size = pb->mmap_size;
13739 	return 0;
13740 }
13741 
13742 /*
13743  * Consume data from perf ring buffer corresponding to slot *buf_idx* in
13744  * PERF_EVENT_ARRAY BPF map without waiting/polling. If there is no data to
13745  * consume, do nothing and return success.
13746  * Returns:
13747  *   - 0 on success;
13748  *   - <0 on failure.
13749  */
13750 int perf_buffer__consume_buffer(struct perf_buffer *pb, size_t buf_idx)
13751 {
13752 	struct perf_cpu_buf *cpu_buf;
13753 
13754 	if (buf_idx >= pb->cpu_cnt)
13755 		return libbpf_err(-EINVAL);
13756 
13757 	cpu_buf = pb->cpu_bufs[buf_idx];
13758 	if (!cpu_buf)
13759 		return libbpf_err(-ENOENT);
13760 
13761 	return perf_buffer__process_records(pb, cpu_buf);
13762 }
13763 
13764 int perf_buffer__consume(struct perf_buffer *pb)
13765 {
13766 	int i, err;
13767 
13768 	for (i = 0; i < pb->cpu_cnt; i++) {
13769 		struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
13770 
13771 		if (!cpu_buf)
13772 			continue;
13773 
13774 		err = perf_buffer__process_records(pb, cpu_buf);
13775 		if (err) {
13776 			pr_warn("perf_buffer: failed to process records in buffer #%d: %s\n",
13777 				i, errstr(err));
13778 			return libbpf_err(err);
13779 		}
13780 	}
13781 	return 0;
13782 }
13783 
13784 int bpf_program__set_attach_target(struct bpf_program *prog,
13785 				   int attach_prog_fd,
13786 				   const char *attach_func_name)
13787 {
13788 	int btf_obj_fd = 0, btf_id = 0, err;
13789 
13790 	if (!prog || attach_prog_fd < 0)
13791 		return libbpf_err(-EINVAL);
13792 
13793 	if (prog->obj->state >= OBJ_LOADED)
13794 		return libbpf_err(-EINVAL);
13795 
13796 	if (attach_prog_fd && !attach_func_name) {
13797 		/* remember attach_prog_fd and let bpf_program__load() find
13798 		 * BTF ID during the program load
13799 		 */
13800 		prog->attach_prog_fd = attach_prog_fd;
13801 		return 0;
13802 	}
13803 
13804 	if (attach_prog_fd) {
13805 		btf_id = libbpf_find_prog_btf_id(attach_func_name,
13806 						 attach_prog_fd, prog->obj->token_fd);
13807 		if (btf_id < 0)
13808 			return libbpf_err(btf_id);
13809 	} else {
13810 		if (!attach_func_name)
13811 			return libbpf_err(-EINVAL);
13812 
13813 		/* load btf_vmlinux, if not yet */
13814 		err = bpf_object__load_vmlinux_btf(prog->obj, true);
13815 		if (err)
13816 			return libbpf_err(err);
13817 		err = find_kernel_btf_id(prog->obj, attach_func_name,
13818 					 prog->expected_attach_type,
13819 					 &btf_obj_fd, &btf_id);
13820 		if (err)
13821 			return libbpf_err(err);
13822 	}
13823 
13824 	prog->attach_btf_id = btf_id;
13825 	prog->attach_btf_obj_fd = btf_obj_fd;
13826 	prog->attach_prog_fd = attach_prog_fd;
13827 	return 0;
13828 }
13829 
13830 int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz)
13831 {
13832 	int err = 0, n, len, start, end = -1;
13833 	bool *tmp;
13834 
13835 	*mask = NULL;
13836 	*mask_sz = 0;
13837 
13838 	/* Each sub string separated by ',' has format \d+-\d+ or \d+ */
13839 	while (*s) {
13840 		if (*s == ',' || *s == '\n') {
13841 			s++;
13842 			continue;
13843 		}
13844 		n = sscanf(s, "%d%n-%d%n", &start, &len, &end, &len);
13845 		if (n <= 0 || n > 2) {
13846 			pr_warn("Failed to get CPU range %s: %d\n", s, n);
13847 			err = -EINVAL;
13848 			goto cleanup;
13849 		} else if (n == 1) {
13850 			end = start;
13851 		}
13852 		if (start < 0 || start > end) {
13853 			pr_warn("Invalid CPU range [%d,%d] in %s\n",
13854 				start, end, s);
13855 			err = -EINVAL;
13856 			goto cleanup;
13857 		}
13858 		tmp = realloc(*mask, end + 1);
13859 		if (!tmp) {
13860 			err = -ENOMEM;
13861 			goto cleanup;
13862 		}
13863 		*mask = tmp;
13864 		memset(tmp + *mask_sz, 0, start - *mask_sz);
13865 		memset(tmp + start, 1, end - start + 1);
13866 		*mask_sz = end + 1;
13867 		s += len;
13868 	}
13869 	if (!*mask_sz) {
13870 		pr_warn("Empty CPU range\n");
13871 		return -EINVAL;
13872 	}
13873 	return 0;
13874 cleanup:
13875 	free(*mask);
13876 	*mask = NULL;
13877 	return err;
13878 }
13879 
13880 int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz)
13881 {
13882 	int fd, err = 0, len;
13883 	char buf[128];
13884 
13885 	fd = open(fcpu, O_RDONLY | O_CLOEXEC);
13886 	if (fd < 0) {
13887 		err = -errno;
13888 		pr_warn("Failed to open cpu mask file %s: %s\n", fcpu, errstr(err));
13889 		return err;
13890 	}
13891 	len = read(fd, buf, sizeof(buf));
13892 	close(fd);
13893 	if (len <= 0) {
13894 		err = len ? -errno : -EINVAL;
13895 		pr_warn("Failed to read cpu mask from %s: %s\n", fcpu, errstr(err));
13896 		return err;
13897 	}
13898 	if (len >= sizeof(buf)) {
13899 		pr_warn("CPU mask is too big in file %s\n", fcpu);
13900 		return -E2BIG;
13901 	}
13902 	buf[len] = '\0';
13903 
13904 	return parse_cpu_mask_str(buf, mask, mask_sz);
13905 }
13906 
13907 int libbpf_num_possible_cpus(void)
13908 {
13909 	static const char *fcpu = "/sys/devices/system/cpu/possible";
13910 	static int cpus;
13911 	int err, n, i, tmp_cpus;
13912 	bool *mask;
13913 
13914 	tmp_cpus = READ_ONCE(cpus);
13915 	if (tmp_cpus > 0)
13916 		return tmp_cpus;
13917 
13918 	err = parse_cpu_mask_file(fcpu, &mask, &n);
13919 	if (err)
13920 		return libbpf_err(err);
13921 
13922 	tmp_cpus = 0;
13923 	for (i = 0; i < n; i++) {
13924 		if (mask[i])
13925 			tmp_cpus++;
13926 	}
13927 	free(mask);
13928 
13929 	WRITE_ONCE(cpus, tmp_cpus);
13930 	return tmp_cpus;
13931 }
13932 
13933 static int populate_skeleton_maps(const struct bpf_object *obj,
13934 				  struct bpf_map_skeleton *maps,
13935 				  size_t map_cnt, size_t map_skel_sz)
13936 {
13937 	int i;
13938 
13939 	for (i = 0; i < map_cnt; i++) {
13940 		struct bpf_map_skeleton *map_skel = (void *)maps + i * map_skel_sz;
13941 		struct bpf_map **map = map_skel->map;
13942 		const char *name = map_skel->name;
13943 		void **mmaped = map_skel->mmaped;
13944 
13945 		*map = bpf_object__find_map_by_name(obj, name);
13946 		if (!*map) {
13947 			pr_warn("failed to find skeleton map '%s'\n", name);
13948 			return -ESRCH;
13949 		}
13950 
13951 		/* externs shouldn't be pre-setup from user code */
13952 		if (mmaped && (*map)->libbpf_type != LIBBPF_MAP_KCONFIG)
13953 			*mmaped = (*map)->mmaped;
13954 	}
13955 	return 0;
13956 }
13957 
13958 static int populate_skeleton_progs(const struct bpf_object *obj,
13959 				   struct bpf_prog_skeleton *progs,
13960 				   size_t prog_cnt, size_t prog_skel_sz)
13961 {
13962 	int i;
13963 
13964 	for (i = 0; i < prog_cnt; i++) {
13965 		struct bpf_prog_skeleton *prog_skel = (void *)progs + i * prog_skel_sz;
13966 		struct bpf_program **prog = prog_skel->prog;
13967 		const char *name = prog_skel->name;
13968 
13969 		*prog = bpf_object__find_program_by_name(obj, name);
13970 		if (!*prog) {
13971 			pr_warn("failed to find skeleton program '%s'\n", name);
13972 			return -ESRCH;
13973 		}
13974 	}
13975 	return 0;
13976 }
13977 
13978 int bpf_object__open_skeleton(struct bpf_object_skeleton *s,
13979 			      const struct bpf_object_open_opts *opts)
13980 {
13981 	struct bpf_object *obj;
13982 	int err;
13983 
13984 	obj = bpf_object_open(NULL, s->data, s->data_sz, s->name, opts);
13985 	if (IS_ERR(obj)) {
13986 		err = PTR_ERR(obj);
13987 		pr_warn("failed to initialize skeleton BPF object '%s': %s\n",
13988 			s->name, errstr(err));
13989 		return libbpf_err(err);
13990 	}
13991 
13992 	*s->obj = obj;
13993 	err = populate_skeleton_maps(obj, s->maps, s->map_cnt, s->map_skel_sz);
13994 	if (err) {
13995 		pr_warn("failed to populate skeleton maps for '%s': %s\n", s->name, errstr(err));
13996 		return libbpf_err(err);
13997 	}
13998 
13999 	err = populate_skeleton_progs(obj, s->progs, s->prog_cnt, s->prog_skel_sz);
14000 	if (err) {
14001 		pr_warn("failed to populate skeleton progs for '%s': %s\n", s->name, errstr(err));
14002 		return libbpf_err(err);
14003 	}
14004 
14005 	return 0;
14006 }
14007 
14008 int bpf_object__open_subskeleton(struct bpf_object_subskeleton *s)
14009 {
14010 	int err, len, var_idx, i;
14011 	const char *var_name;
14012 	const struct bpf_map *map;
14013 	struct btf *btf;
14014 	__u32 map_type_id;
14015 	const struct btf_type *map_type, *var_type;
14016 	const struct bpf_var_skeleton *var_skel;
14017 	struct btf_var_secinfo *var;
14018 
14019 	if (!s->obj)
14020 		return libbpf_err(-EINVAL);
14021 
14022 	btf = bpf_object__btf(s->obj);
14023 	if (!btf) {
14024 		pr_warn("subskeletons require BTF at runtime (object %s)\n",
14025 			bpf_object__name(s->obj));
14026 		return libbpf_err(-errno);
14027 	}
14028 
14029 	err = populate_skeleton_maps(s->obj, s->maps, s->map_cnt, s->map_skel_sz);
14030 	if (err) {
14031 		pr_warn("failed to populate subskeleton maps: %s\n", errstr(err));
14032 		return libbpf_err(err);
14033 	}
14034 
14035 	err = populate_skeleton_progs(s->obj, s->progs, s->prog_cnt, s->prog_skel_sz);
14036 	if (err) {
14037 		pr_warn("failed to populate subskeleton maps: %s\n", errstr(err));
14038 		return libbpf_err(err);
14039 	}
14040 
14041 	for (var_idx = 0; var_idx < s->var_cnt; var_idx++) {
14042 		var_skel = (void *)s->vars + var_idx * s->var_skel_sz;
14043 		map = *var_skel->map;
14044 		map_type_id = bpf_map__btf_value_type_id(map);
14045 		map_type = btf__type_by_id(btf, map_type_id);
14046 
14047 		if (!btf_is_datasec(map_type)) {
14048 			pr_warn("type for map '%1$s' is not a datasec: %2$s\n",
14049 				bpf_map__name(map),
14050 				__btf_kind_str(btf_kind(map_type)));
14051 			return libbpf_err(-EINVAL);
14052 		}
14053 
14054 		len = btf_vlen(map_type);
14055 		var = btf_var_secinfos(map_type);
14056 		for (i = 0; i < len; i++, var++) {
14057 			var_type = btf__type_by_id(btf, var->type);
14058 			var_name = btf__name_by_offset(btf, var_type->name_off);
14059 			if (strcmp(var_name, var_skel->name) == 0) {
14060 				*var_skel->addr = map->mmaped + var->offset;
14061 				break;
14062 			}
14063 		}
14064 	}
14065 	return 0;
14066 }
14067 
14068 void bpf_object__destroy_subskeleton(struct bpf_object_subskeleton *s)
14069 {
14070 	if (!s)
14071 		return;
14072 	free(s->maps);
14073 	free(s->progs);
14074 	free(s->vars);
14075 	free(s);
14076 }
14077 
14078 int bpf_object__load_skeleton(struct bpf_object_skeleton *s)
14079 {
14080 	int i, err;
14081 
14082 	err = bpf_object__load(*s->obj);
14083 	if (err) {
14084 		pr_warn("failed to load BPF skeleton '%s': %s\n", s->name, errstr(err));
14085 		return libbpf_err(err);
14086 	}
14087 
14088 	for (i = 0; i < s->map_cnt; i++) {
14089 		struct bpf_map_skeleton *map_skel = (void *)s->maps + i * s->map_skel_sz;
14090 		struct bpf_map *map = *map_skel->map;
14091 
14092 		if (!map_skel->mmaped)
14093 			continue;
14094 
14095 		*map_skel->mmaped = map->mmaped;
14096 	}
14097 
14098 	return 0;
14099 }
14100 
14101 int bpf_object__attach_skeleton(struct bpf_object_skeleton *s)
14102 {
14103 	int i, err;
14104 
14105 	for (i = 0; i < s->prog_cnt; i++) {
14106 		struct bpf_prog_skeleton *prog_skel = (void *)s->progs + i * s->prog_skel_sz;
14107 		struct bpf_program *prog = *prog_skel->prog;
14108 		struct bpf_link **link = prog_skel->link;
14109 
14110 		if (!prog->autoload || !prog->autoattach)
14111 			continue;
14112 
14113 		/* auto-attaching not supported for this program */
14114 		if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
14115 			continue;
14116 
14117 		/* if user already set the link manually, don't attempt auto-attach */
14118 		if (*link)
14119 			continue;
14120 
14121 		err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, link);
14122 		if (err) {
14123 			pr_warn("prog '%s': failed to auto-attach: %s\n",
14124 				bpf_program__name(prog), errstr(err));
14125 			return libbpf_err(err);
14126 		}
14127 
14128 		/* It's possible that for some SEC() definitions auto-attach
14129 		 * is supported in some cases (e.g., if definition completely
14130 		 * specifies target information), but is not in other cases.
14131 		 * SEC("uprobe") is one such case. If user specified target
14132 		 * binary and function name, such BPF program can be
14133 		 * auto-attached. But if not, it shouldn't trigger skeleton's
14134 		 * attach to fail. It should just be skipped.
14135 		 * attach_fn signals such case with returning 0 (no error) and
14136 		 * setting link to NULL.
14137 		 */
14138 	}
14139 
14140 
14141 	for (i = 0; i < s->map_cnt; i++) {
14142 		struct bpf_map_skeleton *map_skel = (void *)s->maps + i * s->map_skel_sz;
14143 		struct bpf_map *map = *map_skel->map;
14144 		struct bpf_link **link;
14145 
14146 		if (!map->autocreate || !map->autoattach)
14147 			continue;
14148 
14149 		/* only struct_ops maps can be attached */
14150 		if (!bpf_map__is_struct_ops(map))
14151 			continue;
14152 
14153 		/* skeleton is created with earlier version of bpftool, notify user */
14154 		if (s->map_skel_sz < offsetofend(struct bpf_map_skeleton, link)) {
14155 			pr_warn("map '%s': BPF skeleton version is old, skipping map auto-attachment...\n",
14156 				bpf_map__name(map));
14157 			continue;
14158 		}
14159 
14160 		link = map_skel->link;
14161 		if (!link) {
14162 			pr_warn("map '%s': BPF map skeleton link is uninitialized\n",
14163 				bpf_map__name(map));
14164 			continue;
14165 		}
14166 
14167 		if (*link)
14168 			continue;
14169 
14170 		*link = bpf_map__attach_struct_ops(map);
14171 		if (!*link) {
14172 			err = -errno;
14173 			pr_warn("map '%s': failed to auto-attach: %s\n",
14174 				bpf_map__name(map), errstr(err));
14175 			return libbpf_err(err);
14176 		}
14177 	}
14178 
14179 	return 0;
14180 }
14181 
14182 void bpf_object__detach_skeleton(struct bpf_object_skeleton *s)
14183 {
14184 	int i;
14185 
14186 	for (i = 0; i < s->prog_cnt; i++) {
14187 		struct bpf_prog_skeleton *prog_skel = (void *)s->progs + i * s->prog_skel_sz;
14188 		struct bpf_link **link = prog_skel->link;
14189 
14190 		bpf_link__destroy(*link);
14191 		*link = NULL;
14192 	}
14193 
14194 	if (s->map_skel_sz < sizeof(struct bpf_map_skeleton))
14195 		return;
14196 
14197 	for (i = 0; i < s->map_cnt; i++) {
14198 		struct bpf_map_skeleton *map_skel = (void *)s->maps + i * s->map_skel_sz;
14199 		struct bpf_link **link = map_skel->link;
14200 
14201 		if (link) {
14202 			bpf_link__destroy(*link);
14203 			*link = NULL;
14204 		}
14205 	}
14206 }
14207 
14208 void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s)
14209 {
14210 	if (!s)
14211 		return;
14212 
14213 	bpf_object__detach_skeleton(s);
14214 	if (s->obj)
14215 		bpf_object__close(*s->obj);
14216 	free(s->maps);
14217 	free(s->progs);
14218 	free(s);
14219 }
14220