xref: /linux/tools/lib/bpf/libbpf.c (revision 7a4ffec9fd54ea27395e24dff726dbf58e2fe06b)
1 // SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
2 
3 /*
4  * Common eBPF ELF object loading operations.
5  *
6  * Copyright (C) 2013-2015 Alexei Starovoitov <ast@kernel.org>
7  * Copyright (C) 2015 Wang Nan <wangnan0@huawei.com>
8  * Copyright (C) 2015 Huawei Inc.
9  * Copyright (C) 2017 Nicira, Inc.
10  * Copyright (C) 2019 Isovalent, Inc.
11  */
12 
13 #ifndef _GNU_SOURCE
14 #define _GNU_SOURCE
15 #endif
16 #include <stdlib.h>
17 #include <stdio.h>
18 #include <stdarg.h>
19 #include <libgen.h>
20 #include <inttypes.h>
21 #include <limits.h>
22 #include <string.h>
23 #include <unistd.h>
24 #include <endian.h>
25 #include <fcntl.h>
26 #include <errno.h>
27 #include <ctype.h>
28 #include <asm/unistd.h>
29 #include <linux/err.h>
30 #include <linux/kernel.h>
31 #include <linux/bpf.h>
32 #include <linux/btf.h>
33 #include <linux/filter.h>
34 #include <linux/limits.h>
35 #include <linux/perf_event.h>
36 #include <linux/bpf_perf_event.h>
37 #include <linux/ring_buffer.h>
38 #include <sys/epoll.h>
39 #include <sys/ioctl.h>
40 #include <sys/mman.h>
41 #include <sys/stat.h>
42 #include <sys/types.h>
43 #include <sys/vfs.h>
44 #include <sys/utsname.h>
45 #include <sys/resource.h>
46 #include <libelf.h>
47 #include <gelf.h>
48 #include <zlib.h>
49 
50 #include "libbpf.h"
51 #include "bpf.h"
52 #include "btf.h"
53 #include "str_error.h"
54 #include "libbpf_internal.h"
55 #include "hashmap.h"
56 #include "bpf_gen_internal.h"
57 #include "zip.h"
58 
59 #ifndef BPF_FS_MAGIC
60 #define BPF_FS_MAGIC		0xcafe4a11
61 #endif
62 
63 #define BPF_FS_DEFAULT_PATH "/sys/fs/bpf"
64 
65 #define BPF_INSN_SZ (sizeof(struct bpf_insn))
66 
67 /* vsprintf() in __base_pr() uses nonliteral format string. It may break
68  * compilation if user enables corresponding warning. Disable it explicitly.
69  */
70 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
71 
72 #define __printf(a, b)	__attribute__((format(printf, a, b)))
73 
74 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj);
75 static bool prog_is_subprog(const struct bpf_object *obj, const struct bpf_program *prog);
76 static int map_set_def_max_entries(struct bpf_map *map);
77 
78 static const char * const attach_type_name[] = {
79 	[BPF_CGROUP_INET_INGRESS]	= "cgroup_inet_ingress",
80 	[BPF_CGROUP_INET_EGRESS]	= "cgroup_inet_egress",
81 	[BPF_CGROUP_INET_SOCK_CREATE]	= "cgroup_inet_sock_create",
82 	[BPF_CGROUP_INET_SOCK_RELEASE]	= "cgroup_inet_sock_release",
83 	[BPF_CGROUP_SOCK_OPS]		= "cgroup_sock_ops",
84 	[BPF_CGROUP_DEVICE]		= "cgroup_device",
85 	[BPF_CGROUP_INET4_BIND]		= "cgroup_inet4_bind",
86 	[BPF_CGROUP_INET6_BIND]		= "cgroup_inet6_bind",
87 	[BPF_CGROUP_INET4_CONNECT]	= "cgroup_inet4_connect",
88 	[BPF_CGROUP_INET6_CONNECT]	= "cgroup_inet6_connect",
89 	[BPF_CGROUP_UNIX_CONNECT]       = "cgroup_unix_connect",
90 	[BPF_CGROUP_INET4_POST_BIND]	= "cgroup_inet4_post_bind",
91 	[BPF_CGROUP_INET6_POST_BIND]	= "cgroup_inet6_post_bind",
92 	[BPF_CGROUP_INET4_GETPEERNAME]	= "cgroup_inet4_getpeername",
93 	[BPF_CGROUP_INET6_GETPEERNAME]	= "cgroup_inet6_getpeername",
94 	[BPF_CGROUP_UNIX_GETPEERNAME]	= "cgroup_unix_getpeername",
95 	[BPF_CGROUP_INET4_GETSOCKNAME]	= "cgroup_inet4_getsockname",
96 	[BPF_CGROUP_INET6_GETSOCKNAME]	= "cgroup_inet6_getsockname",
97 	[BPF_CGROUP_UNIX_GETSOCKNAME]	= "cgroup_unix_getsockname",
98 	[BPF_CGROUP_UDP4_SENDMSG]	= "cgroup_udp4_sendmsg",
99 	[BPF_CGROUP_UDP6_SENDMSG]	= "cgroup_udp6_sendmsg",
100 	[BPF_CGROUP_UNIX_SENDMSG]	= "cgroup_unix_sendmsg",
101 	[BPF_CGROUP_SYSCTL]		= "cgroup_sysctl",
102 	[BPF_CGROUP_UDP4_RECVMSG]	= "cgroup_udp4_recvmsg",
103 	[BPF_CGROUP_UDP6_RECVMSG]	= "cgroup_udp6_recvmsg",
104 	[BPF_CGROUP_UNIX_RECVMSG]	= "cgroup_unix_recvmsg",
105 	[BPF_CGROUP_GETSOCKOPT]		= "cgroup_getsockopt",
106 	[BPF_CGROUP_SETSOCKOPT]		= "cgroup_setsockopt",
107 	[BPF_SK_SKB_STREAM_PARSER]	= "sk_skb_stream_parser",
108 	[BPF_SK_SKB_STREAM_VERDICT]	= "sk_skb_stream_verdict",
109 	[BPF_SK_SKB_VERDICT]		= "sk_skb_verdict",
110 	[BPF_SK_MSG_VERDICT]		= "sk_msg_verdict",
111 	[BPF_LIRC_MODE2]		= "lirc_mode2",
112 	[BPF_FLOW_DISSECTOR]		= "flow_dissector",
113 	[BPF_TRACE_RAW_TP]		= "trace_raw_tp",
114 	[BPF_TRACE_FENTRY]		= "trace_fentry",
115 	[BPF_TRACE_FEXIT]		= "trace_fexit",
116 	[BPF_MODIFY_RETURN]		= "modify_return",
117 	[BPF_LSM_MAC]			= "lsm_mac",
118 	[BPF_LSM_CGROUP]		= "lsm_cgroup",
119 	[BPF_SK_LOOKUP]			= "sk_lookup",
120 	[BPF_TRACE_ITER]		= "trace_iter",
121 	[BPF_XDP_DEVMAP]		= "xdp_devmap",
122 	[BPF_XDP_CPUMAP]		= "xdp_cpumap",
123 	[BPF_XDP]			= "xdp",
124 	[BPF_SK_REUSEPORT_SELECT]	= "sk_reuseport_select",
125 	[BPF_SK_REUSEPORT_SELECT_OR_MIGRATE]	= "sk_reuseport_select_or_migrate",
126 	[BPF_PERF_EVENT]		= "perf_event",
127 	[BPF_TRACE_KPROBE_MULTI]	= "trace_kprobe_multi",
128 	[BPF_STRUCT_OPS]		= "struct_ops",
129 	[BPF_NETFILTER]			= "netfilter",
130 	[BPF_TCX_INGRESS]		= "tcx_ingress",
131 	[BPF_TCX_EGRESS]		= "tcx_egress",
132 	[BPF_TRACE_UPROBE_MULTI]	= "trace_uprobe_multi",
133 	[BPF_NETKIT_PRIMARY]		= "netkit_primary",
134 	[BPF_NETKIT_PEER]		= "netkit_peer",
135 	[BPF_TRACE_KPROBE_SESSION]	= "trace_kprobe_session",
136 };
137 
138 static const char * const link_type_name[] = {
139 	[BPF_LINK_TYPE_UNSPEC]			= "unspec",
140 	[BPF_LINK_TYPE_RAW_TRACEPOINT]		= "raw_tracepoint",
141 	[BPF_LINK_TYPE_TRACING]			= "tracing",
142 	[BPF_LINK_TYPE_CGROUP]			= "cgroup",
143 	[BPF_LINK_TYPE_ITER]			= "iter",
144 	[BPF_LINK_TYPE_NETNS]			= "netns",
145 	[BPF_LINK_TYPE_XDP]			= "xdp",
146 	[BPF_LINK_TYPE_PERF_EVENT]		= "perf_event",
147 	[BPF_LINK_TYPE_KPROBE_MULTI]		= "kprobe_multi",
148 	[BPF_LINK_TYPE_STRUCT_OPS]		= "struct_ops",
149 	[BPF_LINK_TYPE_NETFILTER]		= "netfilter",
150 	[BPF_LINK_TYPE_TCX]			= "tcx",
151 	[BPF_LINK_TYPE_UPROBE_MULTI]		= "uprobe_multi",
152 	[BPF_LINK_TYPE_NETKIT]			= "netkit",
153 	[BPF_LINK_TYPE_SOCKMAP]			= "sockmap",
154 };
155 
156 static const char * const map_type_name[] = {
157 	[BPF_MAP_TYPE_UNSPEC]			= "unspec",
158 	[BPF_MAP_TYPE_HASH]			= "hash",
159 	[BPF_MAP_TYPE_ARRAY]			= "array",
160 	[BPF_MAP_TYPE_PROG_ARRAY]		= "prog_array",
161 	[BPF_MAP_TYPE_PERF_EVENT_ARRAY]		= "perf_event_array",
162 	[BPF_MAP_TYPE_PERCPU_HASH]		= "percpu_hash",
163 	[BPF_MAP_TYPE_PERCPU_ARRAY]		= "percpu_array",
164 	[BPF_MAP_TYPE_STACK_TRACE]		= "stack_trace",
165 	[BPF_MAP_TYPE_CGROUP_ARRAY]		= "cgroup_array",
166 	[BPF_MAP_TYPE_LRU_HASH]			= "lru_hash",
167 	[BPF_MAP_TYPE_LRU_PERCPU_HASH]		= "lru_percpu_hash",
168 	[BPF_MAP_TYPE_LPM_TRIE]			= "lpm_trie",
169 	[BPF_MAP_TYPE_ARRAY_OF_MAPS]		= "array_of_maps",
170 	[BPF_MAP_TYPE_HASH_OF_MAPS]		= "hash_of_maps",
171 	[BPF_MAP_TYPE_DEVMAP]			= "devmap",
172 	[BPF_MAP_TYPE_DEVMAP_HASH]		= "devmap_hash",
173 	[BPF_MAP_TYPE_SOCKMAP]			= "sockmap",
174 	[BPF_MAP_TYPE_CPUMAP]			= "cpumap",
175 	[BPF_MAP_TYPE_XSKMAP]			= "xskmap",
176 	[BPF_MAP_TYPE_SOCKHASH]			= "sockhash",
177 	[BPF_MAP_TYPE_CGROUP_STORAGE]		= "cgroup_storage",
178 	[BPF_MAP_TYPE_REUSEPORT_SOCKARRAY]	= "reuseport_sockarray",
179 	[BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE]	= "percpu_cgroup_storage",
180 	[BPF_MAP_TYPE_QUEUE]			= "queue",
181 	[BPF_MAP_TYPE_STACK]			= "stack",
182 	[BPF_MAP_TYPE_SK_STORAGE]		= "sk_storage",
183 	[BPF_MAP_TYPE_STRUCT_OPS]		= "struct_ops",
184 	[BPF_MAP_TYPE_RINGBUF]			= "ringbuf",
185 	[BPF_MAP_TYPE_INODE_STORAGE]		= "inode_storage",
186 	[BPF_MAP_TYPE_TASK_STORAGE]		= "task_storage",
187 	[BPF_MAP_TYPE_BLOOM_FILTER]		= "bloom_filter",
188 	[BPF_MAP_TYPE_USER_RINGBUF]             = "user_ringbuf",
189 	[BPF_MAP_TYPE_CGRP_STORAGE]		= "cgrp_storage",
190 	[BPF_MAP_TYPE_ARENA]			= "arena",
191 };
192 
193 static const char * const prog_type_name[] = {
194 	[BPF_PROG_TYPE_UNSPEC]			= "unspec",
195 	[BPF_PROG_TYPE_SOCKET_FILTER]		= "socket_filter",
196 	[BPF_PROG_TYPE_KPROBE]			= "kprobe",
197 	[BPF_PROG_TYPE_SCHED_CLS]		= "sched_cls",
198 	[BPF_PROG_TYPE_SCHED_ACT]		= "sched_act",
199 	[BPF_PROG_TYPE_TRACEPOINT]		= "tracepoint",
200 	[BPF_PROG_TYPE_XDP]			= "xdp",
201 	[BPF_PROG_TYPE_PERF_EVENT]		= "perf_event",
202 	[BPF_PROG_TYPE_CGROUP_SKB]		= "cgroup_skb",
203 	[BPF_PROG_TYPE_CGROUP_SOCK]		= "cgroup_sock",
204 	[BPF_PROG_TYPE_LWT_IN]			= "lwt_in",
205 	[BPF_PROG_TYPE_LWT_OUT]			= "lwt_out",
206 	[BPF_PROG_TYPE_LWT_XMIT]		= "lwt_xmit",
207 	[BPF_PROG_TYPE_SOCK_OPS]		= "sock_ops",
208 	[BPF_PROG_TYPE_SK_SKB]			= "sk_skb",
209 	[BPF_PROG_TYPE_CGROUP_DEVICE]		= "cgroup_device",
210 	[BPF_PROG_TYPE_SK_MSG]			= "sk_msg",
211 	[BPF_PROG_TYPE_RAW_TRACEPOINT]		= "raw_tracepoint",
212 	[BPF_PROG_TYPE_CGROUP_SOCK_ADDR]	= "cgroup_sock_addr",
213 	[BPF_PROG_TYPE_LWT_SEG6LOCAL]		= "lwt_seg6local",
214 	[BPF_PROG_TYPE_LIRC_MODE2]		= "lirc_mode2",
215 	[BPF_PROG_TYPE_SK_REUSEPORT]		= "sk_reuseport",
216 	[BPF_PROG_TYPE_FLOW_DISSECTOR]		= "flow_dissector",
217 	[BPF_PROG_TYPE_CGROUP_SYSCTL]		= "cgroup_sysctl",
218 	[BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE]	= "raw_tracepoint_writable",
219 	[BPF_PROG_TYPE_CGROUP_SOCKOPT]		= "cgroup_sockopt",
220 	[BPF_PROG_TYPE_TRACING]			= "tracing",
221 	[BPF_PROG_TYPE_STRUCT_OPS]		= "struct_ops",
222 	[BPF_PROG_TYPE_EXT]			= "ext",
223 	[BPF_PROG_TYPE_LSM]			= "lsm",
224 	[BPF_PROG_TYPE_SK_LOOKUP]		= "sk_lookup",
225 	[BPF_PROG_TYPE_SYSCALL]			= "syscall",
226 	[BPF_PROG_TYPE_NETFILTER]		= "netfilter",
227 };
228 
229 static int __base_pr(enum libbpf_print_level level, const char *format,
230 		     va_list args)
231 {
232 	const char *env_var = "LIBBPF_LOG_LEVEL";
233 	static enum libbpf_print_level min_level = LIBBPF_INFO;
234 	static bool initialized;
235 
236 	if (!initialized) {
237 		char *verbosity;
238 
239 		initialized = true;
240 		verbosity = getenv(env_var);
241 		if (verbosity) {
242 			if (strcasecmp(verbosity, "warn") == 0)
243 				min_level = LIBBPF_WARN;
244 			else if (strcasecmp(verbosity, "debug") == 0)
245 				min_level = LIBBPF_DEBUG;
246 			else if (strcasecmp(verbosity, "info") == 0)
247 				min_level = LIBBPF_INFO;
248 			else
249 				fprintf(stderr, "libbpf: unrecognized '%s' envvar value: '%s', should be one of 'warn', 'debug', or 'info'.\n",
250 					env_var, verbosity);
251 		}
252 	}
253 
254 	/* if too verbose, skip logging  */
255 	if (level > min_level)
256 		return 0;
257 
258 	return vfprintf(stderr, format, args);
259 }
260 
261 static libbpf_print_fn_t __libbpf_pr = __base_pr;
262 
263 libbpf_print_fn_t libbpf_set_print(libbpf_print_fn_t fn)
264 {
265 	libbpf_print_fn_t old_print_fn;
266 
267 	old_print_fn = __atomic_exchange_n(&__libbpf_pr, fn, __ATOMIC_RELAXED);
268 
269 	return old_print_fn;
270 }
271 
272 __printf(2, 3)
273 void libbpf_print(enum libbpf_print_level level, const char *format, ...)
274 {
275 	va_list args;
276 	int old_errno;
277 	libbpf_print_fn_t print_fn;
278 
279 	print_fn = __atomic_load_n(&__libbpf_pr, __ATOMIC_RELAXED);
280 	if (!print_fn)
281 		return;
282 
283 	old_errno = errno;
284 
285 	va_start(args, format);
286 	__libbpf_pr(level, format, args);
287 	va_end(args);
288 
289 	errno = old_errno;
290 }
291 
292 static void pr_perm_msg(int err)
293 {
294 	struct rlimit limit;
295 	char buf[100];
296 
297 	if (err != -EPERM || geteuid() != 0)
298 		return;
299 
300 	err = getrlimit(RLIMIT_MEMLOCK, &limit);
301 	if (err)
302 		return;
303 
304 	if (limit.rlim_cur == RLIM_INFINITY)
305 		return;
306 
307 	if (limit.rlim_cur < 1024)
308 		snprintf(buf, sizeof(buf), "%zu bytes", (size_t)limit.rlim_cur);
309 	else if (limit.rlim_cur < 1024*1024)
310 		snprintf(buf, sizeof(buf), "%.1f KiB", (double)limit.rlim_cur / 1024);
311 	else
312 		snprintf(buf, sizeof(buf), "%.1f MiB", (double)limit.rlim_cur / (1024*1024));
313 
314 	pr_warn("permission error while running as root; try raising 'ulimit -l'? current value: %s\n",
315 		buf);
316 }
317 
318 #define STRERR_BUFSIZE  128
319 
320 /* Copied from tools/perf/util/util.h */
321 #ifndef zfree
322 # define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
323 #endif
324 
325 #ifndef zclose
326 # define zclose(fd) ({			\
327 	int ___err = 0;			\
328 	if ((fd) >= 0)			\
329 		___err = close((fd));	\
330 	fd = -1;			\
331 	___err; })
332 #endif
333 
334 static inline __u64 ptr_to_u64(const void *ptr)
335 {
336 	return (__u64) (unsigned long) ptr;
337 }
338 
339 int libbpf_set_strict_mode(enum libbpf_strict_mode mode)
340 {
341 	/* as of v1.0 libbpf_set_strict_mode() is a no-op */
342 	return 0;
343 }
344 
345 __u32 libbpf_major_version(void)
346 {
347 	return LIBBPF_MAJOR_VERSION;
348 }
349 
350 __u32 libbpf_minor_version(void)
351 {
352 	return LIBBPF_MINOR_VERSION;
353 }
354 
355 const char *libbpf_version_string(void)
356 {
357 #define __S(X) #X
358 #define _S(X) __S(X)
359 	return  "v" _S(LIBBPF_MAJOR_VERSION) "." _S(LIBBPF_MINOR_VERSION);
360 #undef _S
361 #undef __S
362 }
363 
364 enum reloc_type {
365 	RELO_LD64,
366 	RELO_CALL,
367 	RELO_DATA,
368 	RELO_EXTERN_LD64,
369 	RELO_EXTERN_CALL,
370 	RELO_SUBPROG_ADDR,
371 	RELO_CORE,
372 };
373 
374 struct reloc_desc {
375 	enum reloc_type type;
376 	int insn_idx;
377 	union {
378 		const struct bpf_core_relo *core_relo; /* used when type == RELO_CORE */
379 		struct {
380 			int map_idx;
381 			int sym_off;
382 			int ext_idx;
383 		};
384 	};
385 };
386 
387 /* stored as sec_def->cookie for all libbpf-supported SEC()s */
388 enum sec_def_flags {
389 	SEC_NONE = 0,
390 	/* expected_attach_type is optional, if kernel doesn't support that */
391 	SEC_EXP_ATTACH_OPT = 1,
392 	/* legacy, only used by libbpf_get_type_names() and
393 	 * libbpf_attach_type_by_name(), not used by libbpf itself at all.
394 	 * This used to be associated with cgroup (and few other) BPF programs
395 	 * that were attachable through BPF_PROG_ATTACH command. Pretty
396 	 * meaningless nowadays, though.
397 	 */
398 	SEC_ATTACHABLE = 2,
399 	SEC_ATTACHABLE_OPT = SEC_ATTACHABLE | SEC_EXP_ATTACH_OPT,
400 	/* attachment target is specified through BTF ID in either kernel or
401 	 * other BPF program's BTF object
402 	 */
403 	SEC_ATTACH_BTF = 4,
404 	/* BPF program type allows sleeping/blocking in kernel */
405 	SEC_SLEEPABLE = 8,
406 	/* BPF program support non-linear XDP buffer */
407 	SEC_XDP_FRAGS = 16,
408 	/* Setup proper attach type for usdt probes. */
409 	SEC_USDT = 32,
410 };
411 
412 struct bpf_sec_def {
413 	char *sec;
414 	enum bpf_prog_type prog_type;
415 	enum bpf_attach_type expected_attach_type;
416 	long cookie;
417 	int handler_id;
418 
419 	libbpf_prog_setup_fn_t prog_setup_fn;
420 	libbpf_prog_prepare_load_fn_t prog_prepare_load_fn;
421 	libbpf_prog_attach_fn_t prog_attach_fn;
422 };
423 
424 /*
425  * bpf_prog should be a better name but it has been used in
426  * linux/filter.h.
427  */
428 struct bpf_program {
429 	char *name;
430 	char *sec_name;
431 	size_t sec_idx;
432 	const struct bpf_sec_def *sec_def;
433 	/* this program's instruction offset (in number of instructions)
434 	 * within its containing ELF section
435 	 */
436 	size_t sec_insn_off;
437 	/* number of original instructions in ELF section belonging to this
438 	 * program, not taking into account subprogram instructions possible
439 	 * appended later during relocation
440 	 */
441 	size_t sec_insn_cnt;
442 	/* Offset (in number of instructions) of the start of instruction
443 	 * belonging to this BPF program  within its containing main BPF
444 	 * program. For the entry-point (main) BPF program, this is always
445 	 * zero. For a sub-program, this gets reset before each of main BPF
446 	 * programs are processed and relocated and is used to determined
447 	 * whether sub-program was already appended to the main program, and
448 	 * if yes, at which instruction offset.
449 	 */
450 	size_t sub_insn_off;
451 
452 	/* instructions that belong to BPF program; insns[0] is located at
453 	 * sec_insn_off instruction within its ELF section in ELF file, so
454 	 * when mapping ELF file instruction index to the local instruction,
455 	 * one needs to subtract sec_insn_off; and vice versa.
456 	 */
457 	struct bpf_insn *insns;
458 	/* actual number of instruction in this BPF program's image; for
459 	 * entry-point BPF programs this includes the size of main program
460 	 * itself plus all the used sub-programs, appended at the end
461 	 */
462 	size_t insns_cnt;
463 
464 	struct reloc_desc *reloc_desc;
465 	int nr_reloc;
466 
467 	/* BPF verifier log settings */
468 	char *log_buf;
469 	size_t log_size;
470 	__u32 log_level;
471 
472 	struct bpf_object *obj;
473 
474 	int fd;
475 	bool autoload;
476 	bool autoattach;
477 	bool sym_global;
478 	bool mark_btf_static;
479 	enum bpf_prog_type type;
480 	enum bpf_attach_type expected_attach_type;
481 	int exception_cb_idx;
482 
483 	int prog_ifindex;
484 	__u32 attach_btf_obj_fd;
485 	__u32 attach_btf_id;
486 	__u32 attach_prog_fd;
487 
488 	void *func_info;
489 	__u32 func_info_rec_size;
490 	__u32 func_info_cnt;
491 
492 	void *line_info;
493 	__u32 line_info_rec_size;
494 	__u32 line_info_cnt;
495 	__u32 prog_flags;
496 };
497 
498 struct bpf_struct_ops {
499 	struct bpf_program **progs;
500 	__u32 *kern_func_off;
501 	/* e.g. struct tcp_congestion_ops in bpf_prog's btf format */
502 	void *data;
503 	/* e.g. struct bpf_struct_ops_tcp_congestion_ops in
504 	 *      btf_vmlinux's format.
505 	 * struct bpf_struct_ops_tcp_congestion_ops {
506 	 *	[... some other kernel fields ...]
507 	 *	struct tcp_congestion_ops data;
508 	 * }
509 	 * kern_vdata-size == sizeof(struct bpf_struct_ops_tcp_congestion_ops)
510 	 * bpf_map__init_kern_struct_ops() will populate the "kern_vdata"
511 	 * from "data".
512 	 */
513 	void *kern_vdata;
514 	__u32 type_id;
515 };
516 
517 #define DATA_SEC ".data"
518 #define BSS_SEC ".bss"
519 #define RODATA_SEC ".rodata"
520 #define KCONFIG_SEC ".kconfig"
521 #define KSYMS_SEC ".ksyms"
522 #define STRUCT_OPS_SEC ".struct_ops"
523 #define STRUCT_OPS_LINK_SEC ".struct_ops.link"
524 #define ARENA_SEC ".addr_space.1"
525 
526 enum libbpf_map_type {
527 	LIBBPF_MAP_UNSPEC,
528 	LIBBPF_MAP_DATA,
529 	LIBBPF_MAP_BSS,
530 	LIBBPF_MAP_RODATA,
531 	LIBBPF_MAP_KCONFIG,
532 };
533 
534 struct bpf_map_def {
535 	unsigned int type;
536 	unsigned int key_size;
537 	unsigned int value_size;
538 	unsigned int max_entries;
539 	unsigned int map_flags;
540 };
541 
542 struct bpf_map {
543 	struct bpf_object *obj;
544 	char *name;
545 	/* real_name is defined for special internal maps (.rodata*,
546 	 * .data*, .bss, .kconfig) and preserves their original ELF section
547 	 * name. This is important to be able to find corresponding BTF
548 	 * DATASEC information.
549 	 */
550 	char *real_name;
551 	int fd;
552 	int sec_idx;
553 	size_t sec_offset;
554 	int map_ifindex;
555 	int inner_map_fd;
556 	struct bpf_map_def def;
557 	__u32 numa_node;
558 	__u32 btf_var_idx;
559 	int mod_btf_fd;
560 	__u32 btf_key_type_id;
561 	__u32 btf_value_type_id;
562 	__u32 btf_vmlinux_value_type_id;
563 	enum libbpf_map_type libbpf_type;
564 	void *mmaped;
565 	struct bpf_struct_ops *st_ops;
566 	struct bpf_map *inner_map;
567 	void **init_slots;
568 	int init_slots_sz;
569 	char *pin_path;
570 	bool pinned;
571 	bool reused;
572 	bool autocreate;
573 	bool autoattach;
574 	__u64 map_extra;
575 };
576 
577 enum extern_type {
578 	EXT_UNKNOWN,
579 	EXT_KCFG,
580 	EXT_KSYM,
581 };
582 
583 enum kcfg_type {
584 	KCFG_UNKNOWN,
585 	KCFG_CHAR,
586 	KCFG_BOOL,
587 	KCFG_INT,
588 	KCFG_TRISTATE,
589 	KCFG_CHAR_ARR,
590 };
591 
592 struct extern_desc {
593 	enum extern_type type;
594 	int sym_idx;
595 	int btf_id;
596 	int sec_btf_id;
597 	const char *name;
598 	char *essent_name;
599 	bool is_set;
600 	bool is_weak;
601 	union {
602 		struct {
603 			enum kcfg_type type;
604 			int sz;
605 			int align;
606 			int data_off;
607 			bool is_signed;
608 		} kcfg;
609 		struct {
610 			unsigned long long addr;
611 
612 			/* target btf_id of the corresponding kernel var. */
613 			int kernel_btf_obj_fd;
614 			int kernel_btf_id;
615 
616 			/* local btf_id of the ksym extern's type. */
617 			__u32 type_id;
618 			/* BTF fd index to be patched in for insn->off, this is
619 			 * 0 for vmlinux BTF, index in obj->fd_array for module
620 			 * BTF
621 			 */
622 			__s16 btf_fd_idx;
623 		} ksym;
624 	};
625 };
626 
627 struct module_btf {
628 	struct btf *btf;
629 	char *name;
630 	__u32 id;
631 	int fd;
632 	int fd_array_idx;
633 };
634 
635 enum sec_type {
636 	SEC_UNUSED = 0,
637 	SEC_RELO,
638 	SEC_BSS,
639 	SEC_DATA,
640 	SEC_RODATA,
641 	SEC_ST_OPS,
642 };
643 
644 struct elf_sec_desc {
645 	enum sec_type sec_type;
646 	Elf64_Shdr *shdr;
647 	Elf_Data *data;
648 };
649 
650 struct elf_state {
651 	int fd;
652 	const void *obj_buf;
653 	size_t obj_buf_sz;
654 	Elf *elf;
655 	Elf64_Ehdr *ehdr;
656 	Elf_Data *symbols;
657 	Elf_Data *arena_data;
658 	size_t shstrndx; /* section index for section name strings */
659 	size_t strtabidx;
660 	struct elf_sec_desc *secs;
661 	size_t sec_cnt;
662 	int btf_maps_shndx;
663 	__u32 btf_maps_sec_btf_id;
664 	int text_shndx;
665 	int symbols_shndx;
666 	bool has_st_ops;
667 	int arena_data_shndx;
668 };
669 
670 struct usdt_manager;
671 
672 struct bpf_object {
673 	char name[BPF_OBJ_NAME_LEN];
674 	char license[64];
675 	__u32 kern_version;
676 
677 	struct bpf_program *programs;
678 	size_t nr_programs;
679 	struct bpf_map *maps;
680 	size_t nr_maps;
681 	size_t maps_cap;
682 
683 	char *kconfig;
684 	struct extern_desc *externs;
685 	int nr_extern;
686 	int kconfig_map_idx;
687 
688 	bool loaded;
689 	bool has_subcalls;
690 	bool has_rodata;
691 
692 	struct bpf_gen *gen_loader;
693 
694 	/* Information when doing ELF related work. Only valid if efile.elf is not NULL */
695 	struct elf_state efile;
696 
697 	unsigned char byteorder;
698 
699 	struct btf *btf;
700 	struct btf_ext *btf_ext;
701 
702 	/* Parse and load BTF vmlinux if any of the programs in the object need
703 	 * it at load time.
704 	 */
705 	struct btf *btf_vmlinux;
706 	/* Path to the custom BTF to be used for BPF CO-RE relocations as an
707 	 * override for vmlinux BTF.
708 	 */
709 	char *btf_custom_path;
710 	/* vmlinux BTF override for CO-RE relocations */
711 	struct btf *btf_vmlinux_override;
712 	/* Lazily initialized kernel module BTFs */
713 	struct module_btf *btf_modules;
714 	bool btf_modules_loaded;
715 	size_t btf_module_cnt;
716 	size_t btf_module_cap;
717 
718 	/* optional log settings passed to BPF_BTF_LOAD and BPF_PROG_LOAD commands */
719 	char *log_buf;
720 	size_t log_size;
721 	__u32 log_level;
722 
723 	int *fd_array;
724 	size_t fd_array_cap;
725 	size_t fd_array_cnt;
726 
727 	struct usdt_manager *usdt_man;
728 
729 	struct bpf_map *arena_map;
730 	void *arena_data;
731 	size_t arena_data_sz;
732 
733 	struct kern_feature_cache *feat_cache;
734 	char *token_path;
735 	int token_fd;
736 
737 	char path[];
738 };
739 
740 static const char *elf_sym_str(const struct bpf_object *obj, size_t off);
741 static const char *elf_sec_str(const struct bpf_object *obj, size_t off);
742 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx);
743 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name);
744 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn);
745 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn);
746 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn);
747 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx);
748 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx);
749 
750 void bpf_program__unload(struct bpf_program *prog)
751 {
752 	if (!prog)
753 		return;
754 
755 	zclose(prog->fd);
756 
757 	zfree(&prog->func_info);
758 	zfree(&prog->line_info);
759 }
760 
761 static void bpf_program__exit(struct bpf_program *prog)
762 {
763 	if (!prog)
764 		return;
765 
766 	bpf_program__unload(prog);
767 	zfree(&prog->name);
768 	zfree(&prog->sec_name);
769 	zfree(&prog->insns);
770 	zfree(&prog->reloc_desc);
771 
772 	prog->nr_reloc = 0;
773 	prog->insns_cnt = 0;
774 	prog->sec_idx = -1;
775 }
776 
777 static bool insn_is_subprog_call(const struct bpf_insn *insn)
778 {
779 	return BPF_CLASS(insn->code) == BPF_JMP &&
780 	       BPF_OP(insn->code) == BPF_CALL &&
781 	       BPF_SRC(insn->code) == BPF_K &&
782 	       insn->src_reg == BPF_PSEUDO_CALL &&
783 	       insn->dst_reg == 0 &&
784 	       insn->off == 0;
785 }
786 
787 static bool is_call_insn(const struct bpf_insn *insn)
788 {
789 	return insn->code == (BPF_JMP | BPF_CALL);
790 }
791 
792 static bool insn_is_pseudo_func(struct bpf_insn *insn)
793 {
794 	return is_ldimm64_insn(insn) && insn->src_reg == BPF_PSEUDO_FUNC;
795 }
796 
797 static int
798 bpf_object__init_prog(struct bpf_object *obj, struct bpf_program *prog,
799 		      const char *name, size_t sec_idx, const char *sec_name,
800 		      size_t sec_off, void *insn_data, size_t insn_data_sz)
801 {
802 	if (insn_data_sz == 0 || insn_data_sz % BPF_INSN_SZ || sec_off % BPF_INSN_SZ) {
803 		pr_warn("sec '%s': corrupted program '%s', offset %zu, size %zu\n",
804 			sec_name, name, sec_off, insn_data_sz);
805 		return -EINVAL;
806 	}
807 
808 	memset(prog, 0, sizeof(*prog));
809 	prog->obj = obj;
810 
811 	prog->sec_idx = sec_idx;
812 	prog->sec_insn_off = sec_off / BPF_INSN_SZ;
813 	prog->sec_insn_cnt = insn_data_sz / BPF_INSN_SZ;
814 	/* insns_cnt can later be increased by appending used subprograms */
815 	prog->insns_cnt = prog->sec_insn_cnt;
816 
817 	prog->type = BPF_PROG_TYPE_UNSPEC;
818 	prog->fd = -1;
819 	prog->exception_cb_idx = -1;
820 
821 	/* libbpf's convention for SEC("?abc...") is that it's just like
822 	 * SEC("abc...") but the corresponding bpf_program starts out with
823 	 * autoload set to false.
824 	 */
825 	if (sec_name[0] == '?') {
826 		prog->autoload = false;
827 		/* from now on forget there was ? in section name */
828 		sec_name++;
829 	} else {
830 		prog->autoload = true;
831 	}
832 
833 	prog->autoattach = true;
834 
835 	/* inherit object's log_level */
836 	prog->log_level = obj->log_level;
837 
838 	prog->sec_name = strdup(sec_name);
839 	if (!prog->sec_name)
840 		goto errout;
841 
842 	prog->name = strdup(name);
843 	if (!prog->name)
844 		goto errout;
845 
846 	prog->insns = malloc(insn_data_sz);
847 	if (!prog->insns)
848 		goto errout;
849 	memcpy(prog->insns, insn_data, insn_data_sz);
850 
851 	return 0;
852 errout:
853 	pr_warn("sec '%s': failed to allocate memory for prog '%s'\n", sec_name, name);
854 	bpf_program__exit(prog);
855 	return -ENOMEM;
856 }
857 
858 static int
859 bpf_object__add_programs(struct bpf_object *obj, Elf_Data *sec_data,
860 			 const char *sec_name, int sec_idx)
861 {
862 	Elf_Data *symbols = obj->efile.symbols;
863 	struct bpf_program *prog, *progs;
864 	void *data = sec_data->d_buf;
865 	size_t sec_sz = sec_data->d_size, sec_off, prog_sz, nr_syms;
866 	int nr_progs, err, i;
867 	const char *name;
868 	Elf64_Sym *sym;
869 
870 	progs = obj->programs;
871 	nr_progs = obj->nr_programs;
872 	nr_syms = symbols->d_size / sizeof(Elf64_Sym);
873 
874 	for (i = 0; i < nr_syms; i++) {
875 		sym = elf_sym_by_idx(obj, i);
876 
877 		if (sym->st_shndx != sec_idx)
878 			continue;
879 		if (ELF64_ST_TYPE(sym->st_info) != STT_FUNC)
880 			continue;
881 
882 		prog_sz = sym->st_size;
883 		sec_off = sym->st_value;
884 
885 		name = elf_sym_str(obj, sym->st_name);
886 		if (!name) {
887 			pr_warn("sec '%s': failed to get symbol name for offset %zu\n",
888 				sec_name, sec_off);
889 			return -LIBBPF_ERRNO__FORMAT;
890 		}
891 
892 		if (sec_off + prog_sz > sec_sz) {
893 			pr_warn("sec '%s': program at offset %zu crosses section boundary\n",
894 				sec_name, sec_off);
895 			return -LIBBPF_ERRNO__FORMAT;
896 		}
897 
898 		if (sec_idx != obj->efile.text_shndx && ELF64_ST_BIND(sym->st_info) == STB_LOCAL) {
899 			pr_warn("sec '%s': program '%s' is static and not supported\n", sec_name, name);
900 			return -ENOTSUP;
901 		}
902 
903 		pr_debug("sec '%s': found program '%s' at insn offset %zu (%zu bytes), code size %zu insns (%zu bytes)\n",
904 			 sec_name, name, sec_off / BPF_INSN_SZ, sec_off, prog_sz / BPF_INSN_SZ, prog_sz);
905 
906 		progs = libbpf_reallocarray(progs, nr_progs + 1, sizeof(*progs));
907 		if (!progs) {
908 			/*
909 			 * In this case the original obj->programs
910 			 * is still valid, so don't need special treat for
911 			 * bpf_close_object().
912 			 */
913 			pr_warn("sec '%s': failed to alloc memory for new program '%s'\n",
914 				sec_name, name);
915 			return -ENOMEM;
916 		}
917 		obj->programs = progs;
918 
919 		prog = &progs[nr_progs];
920 
921 		err = bpf_object__init_prog(obj, prog, name, sec_idx, sec_name,
922 					    sec_off, data + sec_off, prog_sz);
923 		if (err)
924 			return err;
925 
926 		if (ELF64_ST_BIND(sym->st_info) != STB_LOCAL)
927 			prog->sym_global = true;
928 
929 		/* if function is a global/weak symbol, but has restricted
930 		 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF FUNC
931 		 * as static to enable more permissive BPF verification mode
932 		 * with more outside context available to BPF verifier
933 		 */
934 		if (prog->sym_global && (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
935 		    || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL))
936 			prog->mark_btf_static = true;
937 
938 		nr_progs++;
939 		obj->nr_programs = nr_progs;
940 	}
941 
942 	return 0;
943 }
944 
945 static void bpf_object_bswap_progs(struct bpf_object *obj)
946 {
947 	struct bpf_program *prog = obj->programs;
948 	struct bpf_insn *insn;
949 	int p, i;
950 
951 	for (p = 0; p < obj->nr_programs; p++, prog++) {
952 		insn = prog->insns;
953 		for (i = 0; i < prog->insns_cnt; i++, insn++)
954 			bpf_insn_bswap(insn);
955 	}
956 	pr_debug("converted %zu BPF programs to native byte order\n", obj->nr_programs);
957 }
958 
959 static const struct btf_member *
960 find_member_by_offset(const struct btf_type *t, __u32 bit_offset)
961 {
962 	struct btf_member *m;
963 	int i;
964 
965 	for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
966 		if (btf_member_bit_offset(t, i) == bit_offset)
967 			return m;
968 	}
969 
970 	return NULL;
971 }
972 
973 static const struct btf_member *
974 find_member_by_name(const struct btf *btf, const struct btf_type *t,
975 		    const char *name)
976 {
977 	struct btf_member *m;
978 	int i;
979 
980 	for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
981 		if (!strcmp(btf__name_by_offset(btf, m->name_off), name))
982 			return m;
983 	}
984 
985 	return NULL;
986 }
987 
988 static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
989 			    __u16 kind, struct btf **res_btf,
990 			    struct module_btf **res_mod_btf);
991 
992 #define STRUCT_OPS_VALUE_PREFIX "bpf_struct_ops_"
993 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
994 				   const char *name, __u32 kind);
995 
996 static int
997 find_struct_ops_kern_types(struct bpf_object *obj, const char *tname_raw,
998 			   struct module_btf **mod_btf,
999 			   const struct btf_type **type, __u32 *type_id,
1000 			   const struct btf_type **vtype, __u32 *vtype_id,
1001 			   const struct btf_member **data_member)
1002 {
1003 	const struct btf_type *kern_type, *kern_vtype;
1004 	const struct btf_member *kern_data_member;
1005 	struct btf *btf = NULL;
1006 	__s32 kern_vtype_id, kern_type_id;
1007 	char tname[256];
1008 	__u32 i;
1009 
1010 	snprintf(tname, sizeof(tname), "%.*s",
1011 		 (int)bpf_core_essential_name_len(tname_raw), tname_raw);
1012 
1013 	kern_type_id = find_ksym_btf_id(obj, tname, BTF_KIND_STRUCT,
1014 					&btf, mod_btf);
1015 	if (kern_type_id < 0) {
1016 		pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n",
1017 			tname);
1018 		return kern_type_id;
1019 	}
1020 	kern_type = btf__type_by_id(btf, kern_type_id);
1021 
1022 	/* Find the corresponding "map_value" type that will be used
1023 	 * in map_update(BPF_MAP_TYPE_STRUCT_OPS).  For example,
1024 	 * find "struct bpf_struct_ops_tcp_congestion_ops" from the
1025 	 * btf_vmlinux.
1026 	 */
1027 	kern_vtype_id = find_btf_by_prefix_kind(btf, STRUCT_OPS_VALUE_PREFIX,
1028 						tname, BTF_KIND_STRUCT);
1029 	if (kern_vtype_id < 0) {
1030 		pr_warn("struct_ops init_kern: struct %s%s is not found in kernel BTF\n",
1031 			STRUCT_OPS_VALUE_PREFIX, tname);
1032 		return kern_vtype_id;
1033 	}
1034 	kern_vtype = btf__type_by_id(btf, kern_vtype_id);
1035 
1036 	/* Find "struct tcp_congestion_ops" from
1037 	 * struct bpf_struct_ops_tcp_congestion_ops {
1038 	 *	[ ... ]
1039 	 *	struct tcp_congestion_ops data;
1040 	 * }
1041 	 */
1042 	kern_data_member = btf_members(kern_vtype);
1043 	for (i = 0; i < btf_vlen(kern_vtype); i++, kern_data_member++) {
1044 		if (kern_data_member->type == kern_type_id)
1045 			break;
1046 	}
1047 	if (i == btf_vlen(kern_vtype)) {
1048 		pr_warn("struct_ops init_kern: struct %s data is not found in struct %s%s\n",
1049 			tname, STRUCT_OPS_VALUE_PREFIX, tname);
1050 		return -EINVAL;
1051 	}
1052 
1053 	*type = kern_type;
1054 	*type_id = kern_type_id;
1055 	*vtype = kern_vtype;
1056 	*vtype_id = kern_vtype_id;
1057 	*data_member = kern_data_member;
1058 
1059 	return 0;
1060 }
1061 
1062 static bool bpf_map__is_struct_ops(const struct bpf_map *map)
1063 {
1064 	return map->def.type == BPF_MAP_TYPE_STRUCT_OPS;
1065 }
1066 
1067 static bool is_valid_st_ops_program(struct bpf_object *obj,
1068 				    const struct bpf_program *prog)
1069 {
1070 	int i;
1071 
1072 	for (i = 0; i < obj->nr_programs; i++) {
1073 		if (&obj->programs[i] == prog)
1074 			return prog->type == BPF_PROG_TYPE_STRUCT_OPS;
1075 	}
1076 
1077 	return false;
1078 }
1079 
1080 /* For each struct_ops program P, referenced from some struct_ops map M,
1081  * enable P.autoload if there are Ms for which M.autocreate is true,
1082  * disable P.autoload if for all Ms M.autocreate is false.
1083  * Don't change P.autoload for programs that are not referenced from any maps.
1084  */
1085 static int bpf_object_adjust_struct_ops_autoload(struct bpf_object *obj)
1086 {
1087 	struct bpf_program *prog, *slot_prog;
1088 	struct bpf_map *map;
1089 	int i, j, k, vlen;
1090 
1091 	for (i = 0; i < obj->nr_programs; ++i) {
1092 		int should_load = false;
1093 		int use_cnt = 0;
1094 
1095 		prog = &obj->programs[i];
1096 		if (prog->type != BPF_PROG_TYPE_STRUCT_OPS)
1097 			continue;
1098 
1099 		for (j = 0; j < obj->nr_maps; ++j) {
1100 			const struct btf_type *type;
1101 
1102 			map = &obj->maps[j];
1103 			if (!bpf_map__is_struct_ops(map))
1104 				continue;
1105 
1106 			type = btf__type_by_id(obj->btf, map->st_ops->type_id);
1107 			vlen = btf_vlen(type);
1108 			for (k = 0; k < vlen; ++k) {
1109 				slot_prog = map->st_ops->progs[k];
1110 				if (prog != slot_prog)
1111 					continue;
1112 
1113 				use_cnt++;
1114 				if (map->autocreate)
1115 					should_load = true;
1116 			}
1117 		}
1118 		if (use_cnt)
1119 			prog->autoload = should_load;
1120 	}
1121 
1122 	return 0;
1123 }
1124 
1125 /* Init the map's fields that depend on kern_btf */
1126 static int bpf_map__init_kern_struct_ops(struct bpf_map *map)
1127 {
1128 	const struct btf_member *member, *kern_member, *kern_data_member;
1129 	const struct btf_type *type, *kern_type, *kern_vtype;
1130 	__u32 i, kern_type_id, kern_vtype_id, kern_data_off;
1131 	struct bpf_object *obj = map->obj;
1132 	const struct btf *btf = obj->btf;
1133 	struct bpf_struct_ops *st_ops;
1134 	const struct btf *kern_btf;
1135 	struct module_btf *mod_btf = NULL;
1136 	void *data, *kern_data;
1137 	const char *tname;
1138 	int err;
1139 
1140 	st_ops = map->st_ops;
1141 	type = btf__type_by_id(btf, st_ops->type_id);
1142 	tname = btf__name_by_offset(btf, type->name_off);
1143 	err = find_struct_ops_kern_types(obj, tname, &mod_btf,
1144 					 &kern_type, &kern_type_id,
1145 					 &kern_vtype, &kern_vtype_id,
1146 					 &kern_data_member);
1147 	if (err)
1148 		return err;
1149 
1150 	kern_btf = mod_btf ? mod_btf->btf : obj->btf_vmlinux;
1151 
1152 	pr_debug("struct_ops init_kern %s: type_id:%u kern_type_id:%u kern_vtype_id:%u\n",
1153 		 map->name, st_ops->type_id, kern_type_id, kern_vtype_id);
1154 
1155 	map->mod_btf_fd = mod_btf ? mod_btf->fd : -1;
1156 	map->def.value_size = kern_vtype->size;
1157 	map->btf_vmlinux_value_type_id = kern_vtype_id;
1158 
1159 	st_ops->kern_vdata = calloc(1, kern_vtype->size);
1160 	if (!st_ops->kern_vdata)
1161 		return -ENOMEM;
1162 
1163 	data = st_ops->data;
1164 	kern_data_off = kern_data_member->offset / 8;
1165 	kern_data = st_ops->kern_vdata + kern_data_off;
1166 
1167 	member = btf_members(type);
1168 	for (i = 0; i < btf_vlen(type); i++, member++) {
1169 		const struct btf_type *mtype, *kern_mtype;
1170 		__u32 mtype_id, kern_mtype_id;
1171 		void *mdata, *kern_mdata;
1172 		struct bpf_program *prog;
1173 		__s64 msize, kern_msize;
1174 		__u32 moff, kern_moff;
1175 		__u32 kern_member_idx;
1176 		const char *mname;
1177 
1178 		mname = btf__name_by_offset(btf, member->name_off);
1179 		moff = member->offset / 8;
1180 		mdata = data + moff;
1181 		msize = btf__resolve_size(btf, member->type);
1182 		if (msize < 0) {
1183 			pr_warn("struct_ops init_kern %s: failed to resolve the size of member %s\n",
1184 				map->name, mname);
1185 			return msize;
1186 		}
1187 
1188 		kern_member = find_member_by_name(kern_btf, kern_type, mname);
1189 		if (!kern_member) {
1190 			if (!libbpf_is_mem_zeroed(mdata, msize)) {
1191 				pr_warn("struct_ops init_kern %s: Cannot find member %s in kernel BTF\n",
1192 					map->name, mname);
1193 				return -ENOTSUP;
1194 			}
1195 
1196 			if (st_ops->progs[i]) {
1197 				/* If we had declaratively set struct_ops callback, we need to
1198 				 * force its autoload to false, because it doesn't have
1199 				 * a chance of succeeding from POV of the current struct_ops map.
1200 				 * If this program is still referenced somewhere else, though,
1201 				 * then bpf_object_adjust_struct_ops_autoload() will update its
1202 				 * autoload accordingly.
1203 				 */
1204 				st_ops->progs[i]->autoload = false;
1205 				st_ops->progs[i] = NULL;
1206 			}
1207 
1208 			/* Skip all-zero/NULL fields if they are not present in the kernel BTF */
1209 			pr_info("struct_ops %s: member %s not found in kernel, skipping it as it's set to zero\n",
1210 				map->name, mname);
1211 			continue;
1212 		}
1213 
1214 		kern_member_idx = kern_member - btf_members(kern_type);
1215 		if (btf_member_bitfield_size(type, i) ||
1216 		    btf_member_bitfield_size(kern_type, kern_member_idx)) {
1217 			pr_warn("struct_ops init_kern %s: bitfield %s is not supported\n",
1218 				map->name, mname);
1219 			return -ENOTSUP;
1220 		}
1221 
1222 		kern_moff = kern_member->offset / 8;
1223 		kern_mdata = kern_data + kern_moff;
1224 
1225 		mtype = skip_mods_and_typedefs(btf, member->type, &mtype_id);
1226 		kern_mtype = skip_mods_and_typedefs(kern_btf, kern_member->type,
1227 						    &kern_mtype_id);
1228 		if (BTF_INFO_KIND(mtype->info) !=
1229 		    BTF_INFO_KIND(kern_mtype->info)) {
1230 			pr_warn("struct_ops init_kern %s: Unmatched member type %s %u != %u(kernel)\n",
1231 				map->name, mname, BTF_INFO_KIND(mtype->info),
1232 				BTF_INFO_KIND(kern_mtype->info));
1233 			return -ENOTSUP;
1234 		}
1235 
1236 		if (btf_is_ptr(mtype)) {
1237 			prog = *(void **)mdata;
1238 			/* just like for !kern_member case above, reset declaratively
1239 			 * set (at compile time) program's autload to false,
1240 			 * if user replaced it with another program or NULL
1241 			 */
1242 			if (st_ops->progs[i] && st_ops->progs[i] != prog)
1243 				st_ops->progs[i]->autoload = false;
1244 
1245 			/* Update the value from the shadow type */
1246 			st_ops->progs[i] = prog;
1247 			if (!prog)
1248 				continue;
1249 
1250 			if (!is_valid_st_ops_program(obj, prog)) {
1251 				pr_warn("struct_ops init_kern %s: member %s is not a struct_ops program\n",
1252 					map->name, mname);
1253 				return -ENOTSUP;
1254 			}
1255 
1256 			kern_mtype = skip_mods_and_typedefs(kern_btf,
1257 							    kern_mtype->type,
1258 							    &kern_mtype_id);
1259 
1260 			/* mtype->type must be a func_proto which was
1261 			 * guaranteed in bpf_object__collect_st_ops_relos(),
1262 			 * so only check kern_mtype for func_proto here.
1263 			 */
1264 			if (!btf_is_func_proto(kern_mtype)) {
1265 				pr_warn("struct_ops init_kern %s: kernel member %s is not a func ptr\n",
1266 					map->name, mname);
1267 				return -ENOTSUP;
1268 			}
1269 
1270 			if (mod_btf)
1271 				prog->attach_btf_obj_fd = mod_btf->fd;
1272 
1273 			/* if we haven't yet processed this BPF program, record proper
1274 			 * attach_btf_id and member_idx
1275 			 */
1276 			if (!prog->attach_btf_id) {
1277 				prog->attach_btf_id = kern_type_id;
1278 				prog->expected_attach_type = kern_member_idx;
1279 			}
1280 
1281 			/* struct_ops BPF prog can be re-used between multiple
1282 			 * .struct_ops & .struct_ops.link as long as it's the
1283 			 * same struct_ops struct definition and the same
1284 			 * function pointer field
1285 			 */
1286 			if (prog->attach_btf_id != kern_type_id) {
1287 				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",
1288 					map->name, mname, prog->name, prog->sec_name, prog->type,
1289 					prog->attach_btf_id, kern_type_id);
1290 				return -EINVAL;
1291 			}
1292 			if (prog->expected_attach_type != kern_member_idx) {
1293 				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",
1294 					map->name, mname, prog->name, prog->sec_name, prog->type,
1295 					prog->expected_attach_type, kern_member_idx);
1296 				return -EINVAL;
1297 			}
1298 
1299 			st_ops->kern_func_off[i] = kern_data_off + kern_moff;
1300 
1301 			pr_debug("struct_ops init_kern %s: func ptr %s is set to prog %s from data(+%u) to kern_data(+%u)\n",
1302 				 map->name, mname, prog->name, moff,
1303 				 kern_moff);
1304 
1305 			continue;
1306 		}
1307 
1308 		kern_msize = btf__resolve_size(kern_btf, kern_mtype_id);
1309 		if (kern_msize < 0 || msize != kern_msize) {
1310 			pr_warn("struct_ops init_kern %s: Error in size of member %s: %zd != %zd(kernel)\n",
1311 				map->name, mname, (ssize_t)msize,
1312 				(ssize_t)kern_msize);
1313 			return -ENOTSUP;
1314 		}
1315 
1316 		pr_debug("struct_ops init_kern %s: copy %s %u bytes from data(+%u) to kern_data(+%u)\n",
1317 			 map->name, mname, (unsigned int)msize,
1318 			 moff, kern_moff);
1319 		memcpy(kern_mdata, mdata, msize);
1320 	}
1321 
1322 	return 0;
1323 }
1324 
1325 static int bpf_object__init_kern_struct_ops_maps(struct bpf_object *obj)
1326 {
1327 	struct bpf_map *map;
1328 	size_t i;
1329 	int err;
1330 
1331 	for (i = 0; i < obj->nr_maps; i++) {
1332 		map = &obj->maps[i];
1333 
1334 		if (!bpf_map__is_struct_ops(map))
1335 			continue;
1336 
1337 		if (!map->autocreate)
1338 			continue;
1339 
1340 		err = bpf_map__init_kern_struct_ops(map);
1341 		if (err)
1342 			return err;
1343 	}
1344 
1345 	return 0;
1346 }
1347 
1348 static int init_struct_ops_maps(struct bpf_object *obj, const char *sec_name,
1349 				int shndx, Elf_Data *data)
1350 {
1351 	const struct btf_type *type, *datasec;
1352 	const struct btf_var_secinfo *vsi;
1353 	struct bpf_struct_ops *st_ops;
1354 	const char *tname, *var_name;
1355 	__s32 type_id, datasec_id;
1356 	const struct btf *btf;
1357 	struct bpf_map *map;
1358 	__u32 i;
1359 
1360 	if (shndx == -1)
1361 		return 0;
1362 
1363 	btf = obj->btf;
1364 	datasec_id = btf__find_by_name_kind(btf, sec_name,
1365 					    BTF_KIND_DATASEC);
1366 	if (datasec_id < 0) {
1367 		pr_warn("struct_ops init: DATASEC %s not found\n",
1368 			sec_name);
1369 		return -EINVAL;
1370 	}
1371 
1372 	datasec = btf__type_by_id(btf, datasec_id);
1373 	vsi = btf_var_secinfos(datasec);
1374 	for (i = 0; i < btf_vlen(datasec); i++, vsi++) {
1375 		type = btf__type_by_id(obj->btf, vsi->type);
1376 		var_name = btf__name_by_offset(obj->btf, type->name_off);
1377 
1378 		type_id = btf__resolve_type(obj->btf, vsi->type);
1379 		if (type_id < 0) {
1380 			pr_warn("struct_ops init: Cannot resolve var type_id %u in DATASEC %s\n",
1381 				vsi->type, sec_name);
1382 			return -EINVAL;
1383 		}
1384 
1385 		type = btf__type_by_id(obj->btf, type_id);
1386 		tname = btf__name_by_offset(obj->btf, type->name_off);
1387 		if (!tname[0]) {
1388 			pr_warn("struct_ops init: anonymous type is not supported\n");
1389 			return -ENOTSUP;
1390 		}
1391 		if (!btf_is_struct(type)) {
1392 			pr_warn("struct_ops init: %s is not a struct\n", tname);
1393 			return -EINVAL;
1394 		}
1395 
1396 		map = bpf_object__add_map(obj);
1397 		if (IS_ERR(map))
1398 			return PTR_ERR(map);
1399 
1400 		map->sec_idx = shndx;
1401 		map->sec_offset = vsi->offset;
1402 		map->name = strdup(var_name);
1403 		if (!map->name)
1404 			return -ENOMEM;
1405 		map->btf_value_type_id = type_id;
1406 
1407 		/* Follow same convention as for programs autoload:
1408 		 * SEC("?.struct_ops") means map is not created by default.
1409 		 */
1410 		if (sec_name[0] == '?') {
1411 			map->autocreate = false;
1412 			/* from now on forget there was ? in section name */
1413 			sec_name++;
1414 		}
1415 
1416 		map->def.type = BPF_MAP_TYPE_STRUCT_OPS;
1417 		map->def.key_size = sizeof(int);
1418 		map->def.value_size = type->size;
1419 		map->def.max_entries = 1;
1420 		map->def.map_flags = strcmp(sec_name, STRUCT_OPS_LINK_SEC) == 0 ? BPF_F_LINK : 0;
1421 		map->autoattach = true;
1422 
1423 		map->st_ops = calloc(1, sizeof(*map->st_ops));
1424 		if (!map->st_ops)
1425 			return -ENOMEM;
1426 		st_ops = map->st_ops;
1427 		st_ops->data = malloc(type->size);
1428 		st_ops->progs = calloc(btf_vlen(type), sizeof(*st_ops->progs));
1429 		st_ops->kern_func_off = malloc(btf_vlen(type) *
1430 					       sizeof(*st_ops->kern_func_off));
1431 		if (!st_ops->data || !st_ops->progs || !st_ops->kern_func_off)
1432 			return -ENOMEM;
1433 
1434 		if (vsi->offset + type->size > data->d_size) {
1435 			pr_warn("struct_ops init: var %s is beyond the end of DATASEC %s\n",
1436 				var_name, sec_name);
1437 			return -EINVAL;
1438 		}
1439 
1440 		memcpy(st_ops->data,
1441 		       data->d_buf + vsi->offset,
1442 		       type->size);
1443 		st_ops->type_id = type_id;
1444 
1445 		pr_debug("struct_ops init: struct %s(type_id=%u) %s found at offset %u\n",
1446 			 tname, type_id, var_name, vsi->offset);
1447 	}
1448 
1449 	return 0;
1450 }
1451 
1452 static int bpf_object_init_struct_ops(struct bpf_object *obj)
1453 {
1454 	const char *sec_name;
1455 	int sec_idx, err;
1456 
1457 	for (sec_idx = 0; sec_idx < obj->efile.sec_cnt; ++sec_idx) {
1458 		struct elf_sec_desc *desc = &obj->efile.secs[sec_idx];
1459 
1460 		if (desc->sec_type != SEC_ST_OPS)
1461 			continue;
1462 
1463 		sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1464 		if (!sec_name)
1465 			return -LIBBPF_ERRNO__FORMAT;
1466 
1467 		err = init_struct_ops_maps(obj, sec_name, sec_idx, desc->data);
1468 		if (err)
1469 			return err;
1470 	}
1471 
1472 	return 0;
1473 }
1474 
1475 static struct bpf_object *bpf_object__new(const char *path,
1476 					  const void *obj_buf,
1477 					  size_t obj_buf_sz,
1478 					  const char *obj_name)
1479 {
1480 	struct bpf_object *obj;
1481 	char *end;
1482 
1483 	obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
1484 	if (!obj) {
1485 		pr_warn("alloc memory failed for %s\n", path);
1486 		return ERR_PTR(-ENOMEM);
1487 	}
1488 
1489 	strcpy(obj->path, path);
1490 	if (obj_name) {
1491 		libbpf_strlcpy(obj->name, obj_name, sizeof(obj->name));
1492 	} else {
1493 		/* Using basename() GNU version which doesn't modify arg. */
1494 		libbpf_strlcpy(obj->name, basename((void *)path), sizeof(obj->name));
1495 		end = strchr(obj->name, '.');
1496 		if (end)
1497 			*end = 0;
1498 	}
1499 
1500 	obj->efile.fd = -1;
1501 	/*
1502 	 * Caller of this function should also call
1503 	 * bpf_object__elf_finish() after data collection to return
1504 	 * obj_buf to user. If not, we should duplicate the buffer to
1505 	 * avoid user freeing them before elf finish.
1506 	 */
1507 	obj->efile.obj_buf = obj_buf;
1508 	obj->efile.obj_buf_sz = obj_buf_sz;
1509 	obj->efile.btf_maps_shndx = -1;
1510 	obj->kconfig_map_idx = -1;
1511 
1512 	obj->kern_version = get_kernel_version();
1513 	obj->loaded = false;
1514 
1515 	return obj;
1516 }
1517 
1518 static void bpf_object__elf_finish(struct bpf_object *obj)
1519 {
1520 	if (!obj->efile.elf)
1521 		return;
1522 
1523 	elf_end(obj->efile.elf);
1524 	obj->efile.elf = NULL;
1525 	obj->efile.ehdr = NULL;
1526 	obj->efile.symbols = NULL;
1527 	obj->efile.arena_data = NULL;
1528 
1529 	zfree(&obj->efile.secs);
1530 	obj->efile.sec_cnt = 0;
1531 	zclose(obj->efile.fd);
1532 	obj->efile.obj_buf = NULL;
1533 	obj->efile.obj_buf_sz = 0;
1534 }
1535 
1536 static int bpf_object__elf_init(struct bpf_object *obj)
1537 {
1538 	Elf64_Ehdr *ehdr;
1539 	int err = 0;
1540 	Elf *elf;
1541 
1542 	if (obj->efile.elf) {
1543 		pr_warn("elf: init internal error\n");
1544 		return -LIBBPF_ERRNO__LIBELF;
1545 	}
1546 
1547 	if (obj->efile.obj_buf_sz > 0) {
1548 		/* obj_buf should have been validated by bpf_object__open_mem(). */
1549 		elf = elf_memory((char *)obj->efile.obj_buf, obj->efile.obj_buf_sz);
1550 	} else {
1551 		obj->efile.fd = open(obj->path, O_RDONLY | O_CLOEXEC);
1552 		if (obj->efile.fd < 0) {
1553 			char errmsg[STRERR_BUFSIZE], *cp;
1554 
1555 			err = -errno;
1556 			cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
1557 			pr_warn("elf: failed to open %s: %s\n", obj->path, cp);
1558 			return err;
1559 		}
1560 
1561 		elf = elf_begin(obj->efile.fd, ELF_C_READ_MMAP, NULL);
1562 	}
1563 
1564 	if (!elf) {
1565 		pr_warn("elf: failed to open %s as ELF file: %s\n", obj->path, elf_errmsg(-1));
1566 		err = -LIBBPF_ERRNO__LIBELF;
1567 		goto errout;
1568 	}
1569 
1570 	obj->efile.elf = elf;
1571 
1572 	if (elf_kind(elf) != ELF_K_ELF) {
1573 		err = -LIBBPF_ERRNO__FORMAT;
1574 		pr_warn("elf: '%s' is not a proper ELF object\n", obj->path);
1575 		goto errout;
1576 	}
1577 
1578 	if (gelf_getclass(elf) != ELFCLASS64) {
1579 		err = -LIBBPF_ERRNO__FORMAT;
1580 		pr_warn("elf: '%s' is not a 64-bit ELF object\n", obj->path);
1581 		goto errout;
1582 	}
1583 
1584 	obj->efile.ehdr = ehdr = elf64_getehdr(elf);
1585 	if (!obj->efile.ehdr) {
1586 		pr_warn("elf: failed to get ELF header from %s: %s\n", obj->path, elf_errmsg(-1));
1587 		err = -LIBBPF_ERRNO__FORMAT;
1588 		goto errout;
1589 	}
1590 
1591 	/* Validate ELF object endianness... */
1592 	if (ehdr->e_ident[EI_DATA] != ELFDATA2LSB &&
1593 	    ehdr->e_ident[EI_DATA] != ELFDATA2MSB) {
1594 		err = -LIBBPF_ERRNO__ENDIAN;
1595 		pr_warn("elf: '%s' has unknown byte order\n", obj->path);
1596 		goto errout;
1597 	}
1598 	/* and save after bpf_object_open() frees ELF data */
1599 	obj->byteorder = ehdr->e_ident[EI_DATA];
1600 
1601 	if (elf_getshdrstrndx(elf, &obj->efile.shstrndx)) {
1602 		pr_warn("elf: failed to get section names section index for %s: %s\n",
1603 			obj->path, elf_errmsg(-1));
1604 		err = -LIBBPF_ERRNO__FORMAT;
1605 		goto errout;
1606 	}
1607 
1608 	/* ELF is corrupted/truncated, avoid calling elf_strptr. */
1609 	if (!elf_rawdata(elf_getscn(elf, obj->efile.shstrndx), NULL)) {
1610 		pr_warn("elf: failed to get section names strings from %s: %s\n",
1611 			obj->path, elf_errmsg(-1));
1612 		err = -LIBBPF_ERRNO__FORMAT;
1613 		goto errout;
1614 	}
1615 
1616 	/* Old LLVM set e_machine to EM_NONE */
1617 	if (ehdr->e_type != ET_REL || (ehdr->e_machine && ehdr->e_machine != EM_BPF)) {
1618 		pr_warn("elf: %s is not a valid eBPF object file\n", obj->path);
1619 		err = -LIBBPF_ERRNO__FORMAT;
1620 		goto errout;
1621 	}
1622 
1623 	return 0;
1624 errout:
1625 	bpf_object__elf_finish(obj);
1626 	return err;
1627 }
1628 
1629 static bool is_native_endianness(struct bpf_object *obj)
1630 {
1631 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1632 	return obj->byteorder == ELFDATA2LSB;
1633 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
1634 	return obj->byteorder == ELFDATA2MSB;
1635 #else
1636 # error "Unrecognized __BYTE_ORDER__"
1637 #endif
1638 }
1639 
1640 static int
1641 bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
1642 {
1643 	if (!data) {
1644 		pr_warn("invalid license section in %s\n", obj->path);
1645 		return -LIBBPF_ERRNO__FORMAT;
1646 	}
1647 	/* libbpf_strlcpy() only copies first N - 1 bytes, so size + 1 won't
1648 	 * go over allowed ELF data section buffer
1649 	 */
1650 	libbpf_strlcpy(obj->license, data, min(size + 1, sizeof(obj->license)));
1651 	pr_debug("license of %s is %s\n", obj->path, obj->license);
1652 	return 0;
1653 }
1654 
1655 static int
1656 bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
1657 {
1658 	__u32 kver;
1659 
1660 	if (!data || size != sizeof(kver)) {
1661 		pr_warn("invalid kver section in %s\n", obj->path);
1662 		return -LIBBPF_ERRNO__FORMAT;
1663 	}
1664 	memcpy(&kver, data, sizeof(kver));
1665 	obj->kern_version = kver;
1666 	pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
1667 	return 0;
1668 }
1669 
1670 static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
1671 {
1672 	if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
1673 	    type == BPF_MAP_TYPE_HASH_OF_MAPS)
1674 		return true;
1675 	return false;
1676 }
1677 
1678 static int find_elf_sec_sz(const struct bpf_object *obj, const char *name, __u32 *size)
1679 {
1680 	Elf_Data *data;
1681 	Elf_Scn *scn;
1682 
1683 	if (!name)
1684 		return -EINVAL;
1685 
1686 	scn = elf_sec_by_name(obj, name);
1687 	data = elf_sec_data(obj, scn);
1688 	if (data) {
1689 		*size = data->d_size;
1690 		return 0; /* found it */
1691 	}
1692 
1693 	return -ENOENT;
1694 }
1695 
1696 static Elf64_Sym *find_elf_var_sym(const struct bpf_object *obj, const char *name)
1697 {
1698 	Elf_Data *symbols = obj->efile.symbols;
1699 	const char *sname;
1700 	size_t si;
1701 
1702 	for (si = 0; si < symbols->d_size / sizeof(Elf64_Sym); si++) {
1703 		Elf64_Sym *sym = elf_sym_by_idx(obj, si);
1704 
1705 		if (ELF64_ST_TYPE(sym->st_info) != STT_OBJECT)
1706 			continue;
1707 
1708 		if (ELF64_ST_BIND(sym->st_info) != STB_GLOBAL &&
1709 		    ELF64_ST_BIND(sym->st_info) != STB_WEAK)
1710 			continue;
1711 
1712 		sname = elf_sym_str(obj, sym->st_name);
1713 		if (!sname) {
1714 			pr_warn("failed to get sym name string for var %s\n", name);
1715 			return ERR_PTR(-EIO);
1716 		}
1717 		if (strcmp(name, sname) == 0)
1718 			return sym;
1719 	}
1720 
1721 	return ERR_PTR(-ENOENT);
1722 }
1723 
1724 /* Some versions of Android don't provide memfd_create() in their libc
1725  * implementation, so avoid complications and just go straight to Linux
1726  * syscall.
1727  */
1728 static int sys_memfd_create(const char *name, unsigned flags)
1729 {
1730 	return syscall(__NR_memfd_create, name, flags);
1731 }
1732 
1733 #ifndef MFD_CLOEXEC
1734 #define MFD_CLOEXEC 0x0001U
1735 #endif
1736 
1737 static int create_placeholder_fd(void)
1738 {
1739 	int fd;
1740 
1741 	fd = ensure_good_fd(sys_memfd_create("libbpf-placeholder-fd", MFD_CLOEXEC));
1742 	if (fd < 0)
1743 		return -errno;
1744 	return fd;
1745 }
1746 
1747 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
1748 {
1749 	struct bpf_map *map;
1750 	int err;
1751 
1752 	err = libbpf_ensure_mem((void **)&obj->maps, &obj->maps_cap,
1753 				sizeof(*obj->maps), obj->nr_maps + 1);
1754 	if (err)
1755 		return ERR_PTR(err);
1756 
1757 	map = &obj->maps[obj->nr_maps++];
1758 	map->obj = obj;
1759 	/* Preallocate map FD without actually creating BPF map just yet.
1760 	 * These map FD "placeholders" will be reused later without changing
1761 	 * FD value when map is actually created in the kernel.
1762 	 *
1763 	 * This is useful to be able to perform BPF program relocations
1764 	 * without having to create BPF maps before that step. This allows us
1765 	 * to finalize and load BTF very late in BPF object's loading phase,
1766 	 * right before BPF maps have to be created and BPF programs have to
1767 	 * be loaded. By having these map FD placeholders we can perform all
1768 	 * the sanitizations, relocations, and any other adjustments before we
1769 	 * start creating actual BPF kernel objects (BTF, maps, progs).
1770 	 */
1771 	map->fd = create_placeholder_fd();
1772 	if (map->fd < 0)
1773 		return ERR_PTR(map->fd);
1774 	map->inner_map_fd = -1;
1775 	map->autocreate = true;
1776 
1777 	return map;
1778 }
1779 
1780 static size_t array_map_mmap_sz(unsigned int value_sz, unsigned int max_entries)
1781 {
1782 	const long page_sz = sysconf(_SC_PAGE_SIZE);
1783 	size_t map_sz;
1784 
1785 	map_sz = (size_t)roundup(value_sz, 8) * max_entries;
1786 	map_sz = roundup(map_sz, page_sz);
1787 	return map_sz;
1788 }
1789 
1790 static size_t bpf_map_mmap_sz(const struct bpf_map *map)
1791 {
1792 	const long page_sz = sysconf(_SC_PAGE_SIZE);
1793 
1794 	switch (map->def.type) {
1795 	case BPF_MAP_TYPE_ARRAY:
1796 		return array_map_mmap_sz(map->def.value_size, map->def.max_entries);
1797 	case BPF_MAP_TYPE_ARENA:
1798 		return page_sz * map->def.max_entries;
1799 	default:
1800 		return 0; /* not supported */
1801 	}
1802 }
1803 
1804 static int bpf_map_mmap_resize(struct bpf_map *map, size_t old_sz, size_t new_sz)
1805 {
1806 	void *mmaped;
1807 
1808 	if (!map->mmaped)
1809 		return -EINVAL;
1810 
1811 	if (old_sz == new_sz)
1812 		return 0;
1813 
1814 	mmaped = mmap(NULL, new_sz, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1815 	if (mmaped == MAP_FAILED)
1816 		return -errno;
1817 
1818 	memcpy(mmaped, map->mmaped, min(old_sz, new_sz));
1819 	munmap(map->mmaped, old_sz);
1820 	map->mmaped = mmaped;
1821 	return 0;
1822 }
1823 
1824 static char *internal_map_name(struct bpf_object *obj, const char *real_name)
1825 {
1826 	char map_name[BPF_OBJ_NAME_LEN], *p;
1827 	int pfx_len, sfx_len = max((size_t)7, strlen(real_name));
1828 
1829 	/* This is one of the more confusing parts of libbpf for various
1830 	 * reasons, some of which are historical. The original idea for naming
1831 	 * internal names was to include as much of BPF object name prefix as
1832 	 * possible, so that it can be distinguished from similar internal
1833 	 * maps of a different BPF object.
1834 	 * As an example, let's say we have bpf_object named 'my_object_name'
1835 	 * and internal map corresponding to '.rodata' ELF section. The final
1836 	 * map name advertised to user and to the kernel will be
1837 	 * 'my_objec.rodata', taking first 8 characters of object name and
1838 	 * entire 7 characters of '.rodata'.
1839 	 * Somewhat confusingly, if internal map ELF section name is shorter
1840 	 * than 7 characters, e.g., '.bss', we still reserve 7 characters
1841 	 * for the suffix, even though we only have 4 actual characters, and
1842 	 * resulting map will be called 'my_objec.bss', not even using all 15
1843 	 * characters allowed by the kernel. Oh well, at least the truncated
1844 	 * object name is somewhat consistent in this case. But if the map
1845 	 * name is '.kconfig', we'll still have entirety of '.kconfig' added
1846 	 * (8 chars) and thus will be left with only first 7 characters of the
1847 	 * object name ('my_obje'). Happy guessing, user, that the final map
1848 	 * name will be "my_obje.kconfig".
1849 	 * Now, with libbpf starting to support arbitrarily named .rodata.*
1850 	 * and .data.* data sections, it's possible that ELF section name is
1851 	 * longer than allowed 15 chars, so we now need to be careful to take
1852 	 * only up to 15 first characters of ELF name, taking no BPF object
1853 	 * name characters at all. So '.rodata.abracadabra' will result in
1854 	 * '.rodata.abracad' kernel and user-visible name.
1855 	 * We need to keep this convoluted logic intact for .data, .bss and
1856 	 * .rodata maps, but for new custom .data.custom and .rodata.custom
1857 	 * maps we use their ELF names as is, not prepending bpf_object name
1858 	 * in front. We still need to truncate them to 15 characters for the
1859 	 * kernel. Full name can be recovered for such maps by using DATASEC
1860 	 * BTF type associated with such map's value type, though.
1861 	 */
1862 	if (sfx_len >= BPF_OBJ_NAME_LEN)
1863 		sfx_len = BPF_OBJ_NAME_LEN - 1;
1864 
1865 	/* if there are two or more dots in map name, it's a custom dot map */
1866 	if (strchr(real_name + 1, '.') != NULL)
1867 		pfx_len = 0;
1868 	else
1869 		pfx_len = min((size_t)BPF_OBJ_NAME_LEN - sfx_len - 1, strlen(obj->name));
1870 
1871 	snprintf(map_name, sizeof(map_name), "%.*s%.*s", pfx_len, obj->name,
1872 		 sfx_len, real_name);
1873 
1874 	/* sanities map name to characters allowed by kernel */
1875 	for (p = map_name; *p && p < map_name + sizeof(map_name); p++)
1876 		if (!isalnum(*p) && *p != '_' && *p != '.')
1877 			*p = '_';
1878 
1879 	return strdup(map_name);
1880 }
1881 
1882 static int
1883 map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map);
1884 
1885 /* Internal BPF map is mmap()'able only if at least one of corresponding
1886  * DATASEC's VARs are to be exposed through BPF skeleton. I.e., it's a GLOBAL
1887  * variable and it's not marked as __hidden (which turns it into, effectively,
1888  * a STATIC variable).
1889  */
1890 static bool map_is_mmapable(struct bpf_object *obj, struct bpf_map *map)
1891 {
1892 	const struct btf_type *t, *vt;
1893 	struct btf_var_secinfo *vsi;
1894 	int i, n;
1895 
1896 	if (!map->btf_value_type_id)
1897 		return false;
1898 
1899 	t = btf__type_by_id(obj->btf, map->btf_value_type_id);
1900 	if (!btf_is_datasec(t))
1901 		return false;
1902 
1903 	vsi = btf_var_secinfos(t);
1904 	for (i = 0, n = btf_vlen(t); i < n; i++, vsi++) {
1905 		vt = btf__type_by_id(obj->btf, vsi->type);
1906 		if (!btf_is_var(vt))
1907 			continue;
1908 
1909 		if (btf_var(vt)->linkage != BTF_VAR_STATIC)
1910 			return true;
1911 	}
1912 
1913 	return false;
1914 }
1915 
1916 static int
1917 bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
1918 			      const char *real_name, int sec_idx, void *data, size_t data_sz)
1919 {
1920 	struct bpf_map_def *def;
1921 	struct bpf_map *map;
1922 	size_t mmap_sz;
1923 	int err;
1924 
1925 	map = bpf_object__add_map(obj);
1926 	if (IS_ERR(map))
1927 		return PTR_ERR(map);
1928 
1929 	map->libbpf_type = type;
1930 	map->sec_idx = sec_idx;
1931 	map->sec_offset = 0;
1932 	map->real_name = strdup(real_name);
1933 	map->name = internal_map_name(obj, real_name);
1934 	if (!map->real_name || !map->name) {
1935 		zfree(&map->real_name);
1936 		zfree(&map->name);
1937 		return -ENOMEM;
1938 	}
1939 
1940 	def = &map->def;
1941 	def->type = BPF_MAP_TYPE_ARRAY;
1942 	def->key_size = sizeof(int);
1943 	def->value_size = data_sz;
1944 	def->max_entries = 1;
1945 	def->map_flags = type == LIBBPF_MAP_RODATA || type == LIBBPF_MAP_KCONFIG
1946 		? BPF_F_RDONLY_PROG : 0;
1947 
1948 	/* failures are fine because of maps like .rodata.str1.1 */
1949 	(void) map_fill_btf_type_info(obj, map);
1950 
1951 	if (map_is_mmapable(obj, map))
1952 		def->map_flags |= BPF_F_MMAPABLE;
1953 
1954 	pr_debug("map '%s' (global data): at sec_idx %d, offset %zu, flags %x.\n",
1955 		 map->name, map->sec_idx, map->sec_offset, def->map_flags);
1956 
1957 	mmap_sz = bpf_map_mmap_sz(map);
1958 	map->mmaped = mmap(NULL, mmap_sz, PROT_READ | PROT_WRITE,
1959 			   MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1960 	if (map->mmaped == MAP_FAILED) {
1961 		err = -errno;
1962 		map->mmaped = NULL;
1963 		pr_warn("failed to alloc map '%s' content buffer: %d\n",
1964 			map->name, err);
1965 		zfree(&map->real_name);
1966 		zfree(&map->name);
1967 		return err;
1968 	}
1969 
1970 	if (data)
1971 		memcpy(map->mmaped, data, data_sz);
1972 
1973 	pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
1974 	return 0;
1975 }
1976 
1977 static int bpf_object__init_global_data_maps(struct bpf_object *obj)
1978 {
1979 	struct elf_sec_desc *sec_desc;
1980 	const char *sec_name;
1981 	int err = 0, sec_idx;
1982 
1983 	/*
1984 	 * Populate obj->maps with libbpf internal maps.
1985 	 */
1986 	for (sec_idx = 1; sec_idx < obj->efile.sec_cnt; sec_idx++) {
1987 		sec_desc = &obj->efile.secs[sec_idx];
1988 
1989 		/* Skip recognized sections with size 0. */
1990 		if (!sec_desc->data || sec_desc->data->d_size == 0)
1991 			continue;
1992 
1993 		switch (sec_desc->sec_type) {
1994 		case SEC_DATA:
1995 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1996 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
1997 							    sec_name, sec_idx,
1998 							    sec_desc->data->d_buf,
1999 							    sec_desc->data->d_size);
2000 			break;
2001 		case SEC_RODATA:
2002 			obj->has_rodata = true;
2003 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
2004 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
2005 							    sec_name, sec_idx,
2006 							    sec_desc->data->d_buf,
2007 							    sec_desc->data->d_size);
2008 			break;
2009 		case SEC_BSS:
2010 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
2011 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
2012 							    sec_name, sec_idx,
2013 							    NULL,
2014 							    sec_desc->data->d_size);
2015 			break;
2016 		default:
2017 			/* skip */
2018 			break;
2019 		}
2020 		if (err)
2021 			return err;
2022 	}
2023 	return 0;
2024 }
2025 
2026 
2027 static struct extern_desc *find_extern_by_name(const struct bpf_object *obj,
2028 					       const void *name)
2029 {
2030 	int i;
2031 
2032 	for (i = 0; i < obj->nr_extern; i++) {
2033 		if (strcmp(obj->externs[i].name, name) == 0)
2034 			return &obj->externs[i];
2035 	}
2036 	return NULL;
2037 }
2038 
2039 static struct extern_desc *find_extern_by_name_with_len(const struct bpf_object *obj,
2040 							const void *name, int len)
2041 {
2042 	const char *ext_name;
2043 	int i;
2044 
2045 	for (i = 0; i < obj->nr_extern; i++) {
2046 		ext_name = obj->externs[i].name;
2047 		if (strlen(ext_name) == len && strncmp(ext_name, name, len) == 0)
2048 			return &obj->externs[i];
2049 	}
2050 	return NULL;
2051 }
2052 
2053 static int set_kcfg_value_tri(struct extern_desc *ext, void *ext_val,
2054 			      char value)
2055 {
2056 	switch (ext->kcfg.type) {
2057 	case KCFG_BOOL:
2058 		if (value == 'm') {
2059 			pr_warn("extern (kcfg) '%s': value '%c' implies tristate or char type\n",
2060 				ext->name, value);
2061 			return -EINVAL;
2062 		}
2063 		*(bool *)ext_val = value == 'y' ? true : false;
2064 		break;
2065 	case KCFG_TRISTATE:
2066 		if (value == 'y')
2067 			*(enum libbpf_tristate *)ext_val = TRI_YES;
2068 		else if (value == 'm')
2069 			*(enum libbpf_tristate *)ext_val = TRI_MODULE;
2070 		else /* value == 'n' */
2071 			*(enum libbpf_tristate *)ext_val = TRI_NO;
2072 		break;
2073 	case KCFG_CHAR:
2074 		*(char *)ext_val = value;
2075 		break;
2076 	case KCFG_UNKNOWN:
2077 	case KCFG_INT:
2078 	case KCFG_CHAR_ARR:
2079 	default:
2080 		pr_warn("extern (kcfg) '%s': value '%c' implies bool, tristate, or char type\n",
2081 			ext->name, value);
2082 		return -EINVAL;
2083 	}
2084 	ext->is_set = true;
2085 	return 0;
2086 }
2087 
2088 static int set_kcfg_value_str(struct extern_desc *ext, char *ext_val,
2089 			      const char *value)
2090 {
2091 	size_t len;
2092 
2093 	if (ext->kcfg.type != KCFG_CHAR_ARR) {
2094 		pr_warn("extern (kcfg) '%s': value '%s' implies char array type\n",
2095 			ext->name, value);
2096 		return -EINVAL;
2097 	}
2098 
2099 	len = strlen(value);
2100 	if (value[len - 1] != '"') {
2101 		pr_warn("extern (kcfg) '%s': invalid string config '%s'\n",
2102 			ext->name, value);
2103 		return -EINVAL;
2104 	}
2105 
2106 	/* strip quotes */
2107 	len -= 2;
2108 	if (len >= ext->kcfg.sz) {
2109 		pr_warn("extern (kcfg) '%s': long string '%s' of (%zu bytes) truncated to %d bytes\n",
2110 			ext->name, value, len, ext->kcfg.sz - 1);
2111 		len = ext->kcfg.sz - 1;
2112 	}
2113 	memcpy(ext_val, value + 1, len);
2114 	ext_val[len] = '\0';
2115 	ext->is_set = true;
2116 	return 0;
2117 }
2118 
2119 static int parse_u64(const char *value, __u64 *res)
2120 {
2121 	char *value_end;
2122 	int err;
2123 
2124 	errno = 0;
2125 	*res = strtoull(value, &value_end, 0);
2126 	if (errno) {
2127 		err = -errno;
2128 		pr_warn("failed to parse '%s' as integer: %d\n", value, err);
2129 		return err;
2130 	}
2131 	if (*value_end) {
2132 		pr_warn("failed to parse '%s' as integer completely\n", value);
2133 		return -EINVAL;
2134 	}
2135 	return 0;
2136 }
2137 
2138 static bool is_kcfg_value_in_range(const struct extern_desc *ext, __u64 v)
2139 {
2140 	int bit_sz = ext->kcfg.sz * 8;
2141 
2142 	if (ext->kcfg.sz == 8)
2143 		return true;
2144 
2145 	/* Validate that value stored in u64 fits in integer of `ext->sz`
2146 	 * bytes size without any loss of information. If the target integer
2147 	 * is signed, we rely on the following limits of integer type of
2148 	 * Y bits and subsequent transformation:
2149 	 *
2150 	 *     -2^(Y-1) <= X           <= 2^(Y-1) - 1
2151 	 *            0 <= X + 2^(Y-1) <= 2^Y - 1
2152 	 *            0 <= X + 2^(Y-1) <  2^Y
2153 	 *
2154 	 *  For unsigned target integer, check that all the (64 - Y) bits are
2155 	 *  zero.
2156 	 */
2157 	if (ext->kcfg.is_signed)
2158 		return v + (1ULL << (bit_sz - 1)) < (1ULL << bit_sz);
2159 	else
2160 		return (v >> bit_sz) == 0;
2161 }
2162 
2163 static int set_kcfg_value_num(struct extern_desc *ext, void *ext_val,
2164 			      __u64 value)
2165 {
2166 	if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR &&
2167 	    ext->kcfg.type != KCFG_BOOL) {
2168 		pr_warn("extern (kcfg) '%s': value '%llu' implies integer, char, or boolean type\n",
2169 			ext->name, (unsigned long long)value);
2170 		return -EINVAL;
2171 	}
2172 	if (ext->kcfg.type == KCFG_BOOL && value > 1) {
2173 		pr_warn("extern (kcfg) '%s': value '%llu' isn't boolean compatible\n",
2174 			ext->name, (unsigned long long)value);
2175 		return -EINVAL;
2176 
2177 	}
2178 	if (!is_kcfg_value_in_range(ext, value)) {
2179 		pr_warn("extern (kcfg) '%s': value '%llu' doesn't fit in %d bytes\n",
2180 			ext->name, (unsigned long long)value, ext->kcfg.sz);
2181 		return -ERANGE;
2182 	}
2183 	switch (ext->kcfg.sz) {
2184 	case 1:
2185 		*(__u8 *)ext_val = value;
2186 		break;
2187 	case 2:
2188 		*(__u16 *)ext_val = value;
2189 		break;
2190 	case 4:
2191 		*(__u32 *)ext_val = value;
2192 		break;
2193 	case 8:
2194 		*(__u64 *)ext_val = value;
2195 		break;
2196 	default:
2197 		return -EINVAL;
2198 	}
2199 	ext->is_set = true;
2200 	return 0;
2201 }
2202 
2203 static int bpf_object__process_kconfig_line(struct bpf_object *obj,
2204 					    char *buf, void *data)
2205 {
2206 	struct extern_desc *ext;
2207 	char *sep, *value;
2208 	int len, err = 0;
2209 	void *ext_val;
2210 	__u64 num;
2211 
2212 	if (!str_has_pfx(buf, "CONFIG_"))
2213 		return 0;
2214 
2215 	sep = strchr(buf, '=');
2216 	if (!sep) {
2217 		pr_warn("failed to parse '%s': no separator\n", buf);
2218 		return -EINVAL;
2219 	}
2220 
2221 	/* Trim ending '\n' */
2222 	len = strlen(buf);
2223 	if (buf[len - 1] == '\n')
2224 		buf[len - 1] = '\0';
2225 	/* Split on '=' and ensure that a value is present. */
2226 	*sep = '\0';
2227 	if (!sep[1]) {
2228 		*sep = '=';
2229 		pr_warn("failed to parse '%s': no value\n", buf);
2230 		return -EINVAL;
2231 	}
2232 
2233 	ext = find_extern_by_name(obj, buf);
2234 	if (!ext || ext->is_set)
2235 		return 0;
2236 
2237 	ext_val = data + ext->kcfg.data_off;
2238 	value = sep + 1;
2239 
2240 	switch (*value) {
2241 	case 'y': case 'n': case 'm':
2242 		err = set_kcfg_value_tri(ext, ext_val, *value);
2243 		break;
2244 	case '"':
2245 		err = set_kcfg_value_str(ext, ext_val, value);
2246 		break;
2247 	default:
2248 		/* assume integer */
2249 		err = parse_u64(value, &num);
2250 		if (err) {
2251 			pr_warn("extern (kcfg) '%s': value '%s' isn't a valid integer\n", ext->name, value);
2252 			return err;
2253 		}
2254 		if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR) {
2255 			pr_warn("extern (kcfg) '%s': value '%s' implies integer type\n", ext->name, value);
2256 			return -EINVAL;
2257 		}
2258 		err = set_kcfg_value_num(ext, ext_val, num);
2259 		break;
2260 	}
2261 	if (err)
2262 		return err;
2263 	pr_debug("extern (kcfg) '%s': set to %s\n", ext->name, value);
2264 	return 0;
2265 }
2266 
2267 static int bpf_object__read_kconfig_file(struct bpf_object *obj, void *data)
2268 {
2269 	char buf[PATH_MAX];
2270 	struct utsname uts;
2271 	int len, err = 0;
2272 	gzFile file;
2273 
2274 	uname(&uts);
2275 	len = snprintf(buf, PATH_MAX, "/boot/config-%s", uts.release);
2276 	if (len < 0)
2277 		return -EINVAL;
2278 	else if (len >= PATH_MAX)
2279 		return -ENAMETOOLONG;
2280 
2281 	/* gzopen also accepts uncompressed files. */
2282 	file = gzopen(buf, "re");
2283 	if (!file)
2284 		file = gzopen("/proc/config.gz", "re");
2285 
2286 	if (!file) {
2287 		pr_warn("failed to open system Kconfig\n");
2288 		return -ENOENT;
2289 	}
2290 
2291 	while (gzgets(file, buf, sizeof(buf))) {
2292 		err = bpf_object__process_kconfig_line(obj, buf, data);
2293 		if (err) {
2294 			pr_warn("error parsing system Kconfig line '%s': %d\n",
2295 				buf, err);
2296 			goto out;
2297 		}
2298 	}
2299 
2300 out:
2301 	gzclose(file);
2302 	return err;
2303 }
2304 
2305 static int bpf_object__read_kconfig_mem(struct bpf_object *obj,
2306 					const char *config, void *data)
2307 {
2308 	char buf[PATH_MAX];
2309 	int err = 0;
2310 	FILE *file;
2311 
2312 	file = fmemopen((void *)config, strlen(config), "r");
2313 	if (!file) {
2314 		err = -errno;
2315 		pr_warn("failed to open in-memory Kconfig: %d\n", err);
2316 		return err;
2317 	}
2318 
2319 	while (fgets(buf, sizeof(buf), file)) {
2320 		err = bpf_object__process_kconfig_line(obj, buf, data);
2321 		if (err) {
2322 			pr_warn("error parsing in-memory Kconfig line '%s': %d\n",
2323 				buf, err);
2324 			break;
2325 		}
2326 	}
2327 
2328 	fclose(file);
2329 	return err;
2330 }
2331 
2332 static int bpf_object__init_kconfig_map(struct bpf_object *obj)
2333 {
2334 	struct extern_desc *last_ext = NULL, *ext;
2335 	size_t map_sz;
2336 	int i, err;
2337 
2338 	for (i = 0; i < obj->nr_extern; i++) {
2339 		ext = &obj->externs[i];
2340 		if (ext->type == EXT_KCFG)
2341 			last_ext = ext;
2342 	}
2343 
2344 	if (!last_ext)
2345 		return 0;
2346 
2347 	map_sz = last_ext->kcfg.data_off + last_ext->kcfg.sz;
2348 	err = bpf_object__init_internal_map(obj, LIBBPF_MAP_KCONFIG,
2349 					    ".kconfig", obj->efile.symbols_shndx,
2350 					    NULL, map_sz);
2351 	if (err)
2352 		return err;
2353 
2354 	obj->kconfig_map_idx = obj->nr_maps - 1;
2355 
2356 	return 0;
2357 }
2358 
2359 const struct btf_type *
2360 skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id)
2361 {
2362 	const struct btf_type *t = btf__type_by_id(btf, id);
2363 
2364 	if (res_id)
2365 		*res_id = id;
2366 
2367 	while (btf_is_mod(t) || btf_is_typedef(t)) {
2368 		if (res_id)
2369 			*res_id = t->type;
2370 		t = btf__type_by_id(btf, t->type);
2371 	}
2372 
2373 	return t;
2374 }
2375 
2376 static const struct btf_type *
2377 resolve_func_ptr(const struct btf *btf, __u32 id, __u32 *res_id)
2378 {
2379 	const struct btf_type *t;
2380 
2381 	t = skip_mods_and_typedefs(btf, id, NULL);
2382 	if (!btf_is_ptr(t))
2383 		return NULL;
2384 
2385 	t = skip_mods_and_typedefs(btf, t->type, res_id);
2386 
2387 	return btf_is_func_proto(t) ? t : NULL;
2388 }
2389 
2390 static const char *__btf_kind_str(__u16 kind)
2391 {
2392 	switch (kind) {
2393 	case BTF_KIND_UNKN: return "void";
2394 	case BTF_KIND_INT: return "int";
2395 	case BTF_KIND_PTR: return "ptr";
2396 	case BTF_KIND_ARRAY: return "array";
2397 	case BTF_KIND_STRUCT: return "struct";
2398 	case BTF_KIND_UNION: return "union";
2399 	case BTF_KIND_ENUM: return "enum";
2400 	case BTF_KIND_FWD: return "fwd";
2401 	case BTF_KIND_TYPEDEF: return "typedef";
2402 	case BTF_KIND_VOLATILE: return "volatile";
2403 	case BTF_KIND_CONST: return "const";
2404 	case BTF_KIND_RESTRICT: return "restrict";
2405 	case BTF_KIND_FUNC: return "func";
2406 	case BTF_KIND_FUNC_PROTO: return "func_proto";
2407 	case BTF_KIND_VAR: return "var";
2408 	case BTF_KIND_DATASEC: return "datasec";
2409 	case BTF_KIND_FLOAT: return "float";
2410 	case BTF_KIND_DECL_TAG: return "decl_tag";
2411 	case BTF_KIND_TYPE_TAG: return "type_tag";
2412 	case BTF_KIND_ENUM64: return "enum64";
2413 	default: return "unknown";
2414 	}
2415 }
2416 
2417 const char *btf_kind_str(const struct btf_type *t)
2418 {
2419 	return __btf_kind_str(btf_kind(t));
2420 }
2421 
2422 /*
2423  * Fetch integer attribute of BTF map definition. Such attributes are
2424  * represented using a pointer to an array, in which dimensionality of array
2425  * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
2426  * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
2427  * type definition, while using only sizeof(void *) space in ELF data section.
2428  */
2429 static bool get_map_field_int(const char *map_name, const struct btf *btf,
2430 			      const struct btf_member *m, __u32 *res)
2431 {
2432 	const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
2433 	const char *name = btf__name_by_offset(btf, m->name_off);
2434 	const struct btf_array *arr_info;
2435 	const struct btf_type *arr_t;
2436 
2437 	if (!btf_is_ptr(t)) {
2438 		pr_warn("map '%s': attr '%s': expected PTR, got %s.\n",
2439 			map_name, name, btf_kind_str(t));
2440 		return false;
2441 	}
2442 
2443 	arr_t = btf__type_by_id(btf, t->type);
2444 	if (!arr_t) {
2445 		pr_warn("map '%s': attr '%s': type [%u] not found.\n",
2446 			map_name, name, t->type);
2447 		return false;
2448 	}
2449 	if (!btf_is_array(arr_t)) {
2450 		pr_warn("map '%s': attr '%s': expected ARRAY, got %s.\n",
2451 			map_name, name, btf_kind_str(arr_t));
2452 		return false;
2453 	}
2454 	arr_info = btf_array(arr_t);
2455 	*res = arr_info->nelems;
2456 	return true;
2457 }
2458 
2459 static bool get_map_field_long(const char *map_name, const struct btf *btf,
2460 			       const struct btf_member *m, __u64 *res)
2461 {
2462 	const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
2463 	const char *name = btf__name_by_offset(btf, m->name_off);
2464 
2465 	if (btf_is_ptr(t)) {
2466 		__u32 res32;
2467 		bool ret;
2468 
2469 		ret = get_map_field_int(map_name, btf, m, &res32);
2470 		if (ret)
2471 			*res = (__u64)res32;
2472 		return ret;
2473 	}
2474 
2475 	if (!btf_is_enum(t) && !btf_is_enum64(t)) {
2476 		pr_warn("map '%s': attr '%s': expected ENUM or ENUM64, got %s.\n",
2477 			map_name, name, btf_kind_str(t));
2478 		return false;
2479 	}
2480 
2481 	if (btf_vlen(t) != 1) {
2482 		pr_warn("map '%s': attr '%s': invalid __ulong\n",
2483 			map_name, name);
2484 		return false;
2485 	}
2486 
2487 	if (btf_is_enum(t)) {
2488 		const struct btf_enum *e = btf_enum(t);
2489 
2490 		*res = e->val;
2491 	} else {
2492 		const struct btf_enum64 *e = btf_enum64(t);
2493 
2494 		*res = btf_enum64_value(e);
2495 	}
2496 	return true;
2497 }
2498 
2499 static int pathname_concat(char *buf, size_t buf_sz, const char *path, const char *name)
2500 {
2501 	int len;
2502 
2503 	len = snprintf(buf, buf_sz, "%s/%s", path, name);
2504 	if (len < 0)
2505 		return -EINVAL;
2506 	if (len >= buf_sz)
2507 		return -ENAMETOOLONG;
2508 
2509 	return 0;
2510 }
2511 
2512 static int build_map_pin_path(struct bpf_map *map, const char *path)
2513 {
2514 	char buf[PATH_MAX];
2515 	int err;
2516 
2517 	if (!path)
2518 		path = BPF_FS_DEFAULT_PATH;
2519 
2520 	err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
2521 	if (err)
2522 		return err;
2523 
2524 	return bpf_map__set_pin_path(map, buf);
2525 }
2526 
2527 /* should match definition in bpf_helpers.h */
2528 enum libbpf_pin_type {
2529 	LIBBPF_PIN_NONE,
2530 	/* PIN_BY_NAME: pin maps by name (in /sys/fs/bpf by default) */
2531 	LIBBPF_PIN_BY_NAME,
2532 };
2533 
2534 int parse_btf_map_def(const char *map_name, struct btf *btf,
2535 		      const struct btf_type *def_t, bool strict,
2536 		      struct btf_map_def *map_def, struct btf_map_def *inner_def)
2537 {
2538 	const struct btf_type *t;
2539 	const struct btf_member *m;
2540 	bool is_inner = inner_def == NULL;
2541 	int vlen, i;
2542 
2543 	vlen = btf_vlen(def_t);
2544 	m = btf_members(def_t);
2545 	for (i = 0; i < vlen; i++, m++) {
2546 		const char *name = btf__name_by_offset(btf, m->name_off);
2547 
2548 		if (!name) {
2549 			pr_warn("map '%s': invalid field #%d.\n", map_name, i);
2550 			return -EINVAL;
2551 		}
2552 		if (strcmp(name, "type") == 0) {
2553 			if (!get_map_field_int(map_name, btf, m, &map_def->map_type))
2554 				return -EINVAL;
2555 			map_def->parts |= MAP_DEF_MAP_TYPE;
2556 		} else if (strcmp(name, "max_entries") == 0) {
2557 			if (!get_map_field_int(map_name, btf, m, &map_def->max_entries))
2558 				return -EINVAL;
2559 			map_def->parts |= MAP_DEF_MAX_ENTRIES;
2560 		} else if (strcmp(name, "map_flags") == 0) {
2561 			if (!get_map_field_int(map_name, btf, m, &map_def->map_flags))
2562 				return -EINVAL;
2563 			map_def->parts |= MAP_DEF_MAP_FLAGS;
2564 		} else if (strcmp(name, "numa_node") == 0) {
2565 			if (!get_map_field_int(map_name, btf, m, &map_def->numa_node))
2566 				return -EINVAL;
2567 			map_def->parts |= MAP_DEF_NUMA_NODE;
2568 		} else if (strcmp(name, "key_size") == 0) {
2569 			__u32 sz;
2570 
2571 			if (!get_map_field_int(map_name, btf, m, &sz))
2572 				return -EINVAL;
2573 			if (map_def->key_size && map_def->key_size != sz) {
2574 				pr_warn("map '%s': conflicting key size %u != %u.\n",
2575 					map_name, map_def->key_size, sz);
2576 				return -EINVAL;
2577 			}
2578 			map_def->key_size = sz;
2579 			map_def->parts |= MAP_DEF_KEY_SIZE;
2580 		} else if (strcmp(name, "key") == 0) {
2581 			__s64 sz;
2582 
2583 			t = btf__type_by_id(btf, m->type);
2584 			if (!t) {
2585 				pr_warn("map '%s': key type [%d] not found.\n",
2586 					map_name, m->type);
2587 				return -EINVAL;
2588 			}
2589 			if (!btf_is_ptr(t)) {
2590 				pr_warn("map '%s': key spec is not PTR: %s.\n",
2591 					map_name, btf_kind_str(t));
2592 				return -EINVAL;
2593 			}
2594 			sz = btf__resolve_size(btf, t->type);
2595 			if (sz < 0) {
2596 				pr_warn("map '%s': can't determine key size for type [%u]: %zd.\n",
2597 					map_name, t->type, (ssize_t)sz);
2598 				return sz;
2599 			}
2600 			if (map_def->key_size && map_def->key_size != sz) {
2601 				pr_warn("map '%s': conflicting key size %u != %zd.\n",
2602 					map_name, map_def->key_size, (ssize_t)sz);
2603 				return -EINVAL;
2604 			}
2605 			map_def->key_size = sz;
2606 			map_def->key_type_id = t->type;
2607 			map_def->parts |= MAP_DEF_KEY_SIZE | MAP_DEF_KEY_TYPE;
2608 		} else if (strcmp(name, "value_size") == 0) {
2609 			__u32 sz;
2610 
2611 			if (!get_map_field_int(map_name, btf, m, &sz))
2612 				return -EINVAL;
2613 			if (map_def->value_size && map_def->value_size != sz) {
2614 				pr_warn("map '%s': conflicting value size %u != %u.\n",
2615 					map_name, map_def->value_size, sz);
2616 				return -EINVAL;
2617 			}
2618 			map_def->value_size = sz;
2619 			map_def->parts |= MAP_DEF_VALUE_SIZE;
2620 		} else if (strcmp(name, "value") == 0) {
2621 			__s64 sz;
2622 
2623 			t = btf__type_by_id(btf, m->type);
2624 			if (!t) {
2625 				pr_warn("map '%s': value type [%d] not found.\n",
2626 					map_name, m->type);
2627 				return -EINVAL;
2628 			}
2629 			if (!btf_is_ptr(t)) {
2630 				pr_warn("map '%s': value spec is not PTR: %s.\n",
2631 					map_name, btf_kind_str(t));
2632 				return -EINVAL;
2633 			}
2634 			sz = btf__resolve_size(btf, t->type);
2635 			if (sz < 0) {
2636 				pr_warn("map '%s': can't determine value size for type [%u]: %zd.\n",
2637 					map_name, t->type, (ssize_t)sz);
2638 				return sz;
2639 			}
2640 			if (map_def->value_size && map_def->value_size != sz) {
2641 				pr_warn("map '%s': conflicting value size %u != %zd.\n",
2642 					map_name, map_def->value_size, (ssize_t)sz);
2643 				return -EINVAL;
2644 			}
2645 			map_def->value_size = sz;
2646 			map_def->value_type_id = t->type;
2647 			map_def->parts |= MAP_DEF_VALUE_SIZE | MAP_DEF_VALUE_TYPE;
2648 		}
2649 		else if (strcmp(name, "values") == 0) {
2650 			bool is_map_in_map = bpf_map_type__is_map_in_map(map_def->map_type);
2651 			bool is_prog_array = map_def->map_type == BPF_MAP_TYPE_PROG_ARRAY;
2652 			const char *desc = is_map_in_map ? "map-in-map inner" : "prog-array value";
2653 			char inner_map_name[128];
2654 			int err;
2655 
2656 			if (is_inner) {
2657 				pr_warn("map '%s': multi-level inner maps not supported.\n",
2658 					map_name);
2659 				return -ENOTSUP;
2660 			}
2661 			if (i != vlen - 1) {
2662 				pr_warn("map '%s': '%s' member should be last.\n",
2663 					map_name, name);
2664 				return -EINVAL;
2665 			}
2666 			if (!is_map_in_map && !is_prog_array) {
2667 				pr_warn("map '%s': should be map-in-map or prog-array.\n",
2668 					map_name);
2669 				return -ENOTSUP;
2670 			}
2671 			if (map_def->value_size && map_def->value_size != 4) {
2672 				pr_warn("map '%s': conflicting value size %u != 4.\n",
2673 					map_name, map_def->value_size);
2674 				return -EINVAL;
2675 			}
2676 			map_def->value_size = 4;
2677 			t = btf__type_by_id(btf, m->type);
2678 			if (!t) {
2679 				pr_warn("map '%s': %s type [%d] not found.\n",
2680 					map_name, desc, m->type);
2681 				return -EINVAL;
2682 			}
2683 			if (!btf_is_array(t) || btf_array(t)->nelems) {
2684 				pr_warn("map '%s': %s spec is not a zero-sized array.\n",
2685 					map_name, desc);
2686 				return -EINVAL;
2687 			}
2688 			t = skip_mods_and_typedefs(btf, btf_array(t)->type, NULL);
2689 			if (!btf_is_ptr(t)) {
2690 				pr_warn("map '%s': %s def is of unexpected kind %s.\n",
2691 					map_name, desc, btf_kind_str(t));
2692 				return -EINVAL;
2693 			}
2694 			t = skip_mods_and_typedefs(btf, t->type, NULL);
2695 			if (is_prog_array) {
2696 				if (!btf_is_func_proto(t)) {
2697 					pr_warn("map '%s': prog-array value def is of unexpected kind %s.\n",
2698 						map_name, btf_kind_str(t));
2699 					return -EINVAL;
2700 				}
2701 				continue;
2702 			}
2703 			if (!btf_is_struct(t)) {
2704 				pr_warn("map '%s': map-in-map inner def is of unexpected kind %s.\n",
2705 					map_name, btf_kind_str(t));
2706 				return -EINVAL;
2707 			}
2708 
2709 			snprintf(inner_map_name, sizeof(inner_map_name), "%s.inner", map_name);
2710 			err = parse_btf_map_def(inner_map_name, btf, t, strict, inner_def, NULL);
2711 			if (err)
2712 				return err;
2713 
2714 			map_def->parts |= MAP_DEF_INNER_MAP;
2715 		} else if (strcmp(name, "pinning") == 0) {
2716 			__u32 val;
2717 
2718 			if (is_inner) {
2719 				pr_warn("map '%s': inner def can't be pinned.\n", map_name);
2720 				return -EINVAL;
2721 			}
2722 			if (!get_map_field_int(map_name, btf, m, &val))
2723 				return -EINVAL;
2724 			if (val != LIBBPF_PIN_NONE && val != LIBBPF_PIN_BY_NAME) {
2725 				pr_warn("map '%s': invalid pinning value %u.\n",
2726 					map_name, val);
2727 				return -EINVAL;
2728 			}
2729 			map_def->pinning = val;
2730 			map_def->parts |= MAP_DEF_PINNING;
2731 		} else if (strcmp(name, "map_extra") == 0) {
2732 			__u64 map_extra;
2733 
2734 			if (!get_map_field_long(map_name, btf, m, &map_extra))
2735 				return -EINVAL;
2736 			map_def->map_extra = map_extra;
2737 			map_def->parts |= MAP_DEF_MAP_EXTRA;
2738 		} else {
2739 			if (strict) {
2740 				pr_warn("map '%s': unknown field '%s'.\n", map_name, name);
2741 				return -ENOTSUP;
2742 			}
2743 			pr_debug("map '%s': ignoring unknown field '%s'.\n", map_name, name);
2744 		}
2745 	}
2746 
2747 	if (map_def->map_type == BPF_MAP_TYPE_UNSPEC) {
2748 		pr_warn("map '%s': map type isn't specified.\n", map_name);
2749 		return -EINVAL;
2750 	}
2751 
2752 	return 0;
2753 }
2754 
2755 static size_t adjust_ringbuf_sz(size_t sz)
2756 {
2757 	__u32 page_sz = sysconf(_SC_PAGE_SIZE);
2758 	__u32 mul;
2759 
2760 	/* if user forgot to set any size, make sure they see error */
2761 	if (sz == 0)
2762 		return 0;
2763 	/* Kernel expects BPF_MAP_TYPE_RINGBUF's max_entries to be
2764 	 * a power-of-2 multiple of kernel's page size. If user diligently
2765 	 * satisified these conditions, pass the size through.
2766 	 */
2767 	if ((sz % page_sz) == 0 && is_pow_of_2(sz / page_sz))
2768 		return sz;
2769 
2770 	/* Otherwise find closest (page_sz * power_of_2) product bigger than
2771 	 * user-set size to satisfy both user size request and kernel
2772 	 * requirements and substitute correct max_entries for map creation.
2773 	 */
2774 	for (mul = 1; mul <= UINT_MAX / page_sz; mul <<= 1) {
2775 		if (mul * page_sz > sz)
2776 			return mul * page_sz;
2777 	}
2778 
2779 	/* if it's impossible to satisfy the conditions (i.e., user size is
2780 	 * very close to UINT_MAX but is not a power-of-2 multiple of
2781 	 * page_size) then just return original size and let kernel reject it
2782 	 */
2783 	return sz;
2784 }
2785 
2786 static bool map_is_ringbuf(const struct bpf_map *map)
2787 {
2788 	return map->def.type == BPF_MAP_TYPE_RINGBUF ||
2789 	       map->def.type == BPF_MAP_TYPE_USER_RINGBUF;
2790 }
2791 
2792 static void fill_map_from_def(struct bpf_map *map, const struct btf_map_def *def)
2793 {
2794 	map->def.type = def->map_type;
2795 	map->def.key_size = def->key_size;
2796 	map->def.value_size = def->value_size;
2797 	map->def.max_entries = def->max_entries;
2798 	map->def.map_flags = def->map_flags;
2799 	map->map_extra = def->map_extra;
2800 
2801 	map->numa_node = def->numa_node;
2802 	map->btf_key_type_id = def->key_type_id;
2803 	map->btf_value_type_id = def->value_type_id;
2804 
2805 	/* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
2806 	if (map_is_ringbuf(map))
2807 		map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
2808 
2809 	if (def->parts & MAP_DEF_MAP_TYPE)
2810 		pr_debug("map '%s': found type = %u.\n", map->name, def->map_type);
2811 
2812 	if (def->parts & MAP_DEF_KEY_TYPE)
2813 		pr_debug("map '%s': found key [%u], sz = %u.\n",
2814 			 map->name, def->key_type_id, def->key_size);
2815 	else if (def->parts & MAP_DEF_KEY_SIZE)
2816 		pr_debug("map '%s': found key_size = %u.\n", map->name, def->key_size);
2817 
2818 	if (def->parts & MAP_DEF_VALUE_TYPE)
2819 		pr_debug("map '%s': found value [%u], sz = %u.\n",
2820 			 map->name, def->value_type_id, def->value_size);
2821 	else if (def->parts & MAP_DEF_VALUE_SIZE)
2822 		pr_debug("map '%s': found value_size = %u.\n", map->name, def->value_size);
2823 
2824 	if (def->parts & MAP_DEF_MAX_ENTRIES)
2825 		pr_debug("map '%s': found max_entries = %u.\n", map->name, def->max_entries);
2826 	if (def->parts & MAP_DEF_MAP_FLAGS)
2827 		pr_debug("map '%s': found map_flags = 0x%x.\n", map->name, def->map_flags);
2828 	if (def->parts & MAP_DEF_MAP_EXTRA)
2829 		pr_debug("map '%s': found map_extra = 0x%llx.\n", map->name,
2830 			 (unsigned long long)def->map_extra);
2831 	if (def->parts & MAP_DEF_PINNING)
2832 		pr_debug("map '%s': found pinning = %u.\n", map->name, def->pinning);
2833 	if (def->parts & MAP_DEF_NUMA_NODE)
2834 		pr_debug("map '%s': found numa_node = %u.\n", map->name, def->numa_node);
2835 
2836 	if (def->parts & MAP_DEF_INNER_MAP)
2837 		pr_debug("map '%s': found inner map definition.\n", map->name);
2838 }
2839 
2840 static const char *btf_var_linkage_str(__u32 linkage)
2841 {
2842 	switch (linkage) {
2843 	case BTF_VAR_STATIC: return "static";
2844 	case BTF_VAR_GLOBAL_ALLOCATED: return "global";
2845 	case BTF_VAR_GLOBAL_EXTERN: return "extern";
2846 	default: return "unknown";
2847 	}
2848 }
2849 
2850 static int bpf_object__init_user_btf_map(struct bpf_object *obj,
2851 					 const struct btf_type *sec,
2852 					 int var_idx, int sec_idx,
2853 					 const Elf_Data *data, bool strict,
2854 					 const char *pin_root_path)
2855 {
2856 	struct btf_map_def map_def = {}, inner_def = {};
2857 	const struct btf_type *var, *def;
2858 	const struct btf_var_secinfo *vi;
2859 	const struct btf_var *var_extra;
2860 	const char *map_name;
2861 	struct bpf_map *map;
2862 	int err;
2863 
2864 	vi = btf_var_secinfos(sec) + var_idx;
2865 	var = btf__type_by_id(obj->btf, vi->type);
2866 	var_extra = btf_var(var);
2867 	map_name = btf__name_by_offset(obj->btf, var->name_off);
2868 
2869 	if (map_name == NULL || map_name[0] == '\0') {
2870 		pr_warn("map #%d: empty name.\n", var_idx);
2871 		return -EINVAL;
2872 	}
2873 	if ((__u64)vi->offset + vi->size > data->d_size) {
2874 		pr_warn("map '%s' BTF data is corrupted.\n", map_name);
2875 		return -EINVAL;
2876 	}
2877 	if (!btf_is_var(var)) {
2878 		pr_warn("map '%s': unexpected var kind %s.\n",
2879 			map_name, btf_kind_str(var));
2880 		return -EINVAL;
2881 	}
2882 	if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED) {
2883 		pr_warn("map '%s': unsupported map linkage %s.\n",
2884 			map_name, btf_var_linkage_str(var_extra->linkage));
2885 		return -EOPNOTSUPP;
2886 	}
2887 
2888 	def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
2889 	if (!btf_is_struct(def)) {
2890 		pr_warn("map '%s': unexpected def kind %s.\n",
2891 			map_name, btf_kind_str(var));
2892 		return -EINVAL;
2893 	}
2894 	if (def->size > vi->size) {
2895 		pr_warn("map '%s': invalid def size.\n", map_name);
2896 		return -EINVAL;
2897 	}
2898 
2899 	map = bpf_object__add_map(obj);
2900 	if (IS_ERR(map))
2901 		return PTR_ERR(map);
2902 	map->name = strdup(map_name);
2903 	if (!map->name) {
2904 		pr_warn("map '%s': failed to alloc map name.\n", map_name);
2905 		return -ENOMEM;
2906 	}
2907 	map->libbpf_type = LIBBPF_MAP_UNSPEC;
2908 	map->def.type = BPF_MAP_TYPE_UNSPEC;
2909 	map->sec_idx = sec_idx;
2910 	map->sec_offset = vi->offset;
2911 	map->btf_var_idx = var_idx;
2912 	pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
2913 		 map_name, map->sec_idx, map->sec_offset);
2914 
2915 	err = parse_btf_map_def(map->name, obj->btf, def, strict, &map_def, &inner_def);
2916 	if (err)
2917 		return err;
2918 
2919 	fill_map_from_def(map, &map_def);
2920 
2921 	if (map_def.pinning == LIBBPF_PIN_BY_NAME) {
2922 		err = build_map_pin_path(map, pin_root_path);
2923 		if (err) {
2924 			pr_warn("map '%s': couldn't build pin path.\n", map->name);
2925 			return err;
2926 		}
2927 	}
2928 
2929 	if (map_def.parts & MAP_DEF_INNER_MAP) {
2930 		map->inner_map = calloc(1, sizeof(*map->inner_map));
2931 		if (!map->inner_map)
2932 			return -ENOMEM;
2933 		map->inner_map->fd = create_placeholder_fd();
2934 		if (map->inner_map->fd < 0)
2935 			return map->inner_map->fd;
2936 		map->inner_map->sec_idx = sec_idx;
2937 		map->inner_map->name = malloc(strlen(map_name) + sizeof(".inner") + 1);
2938 		if (!map->inner_map->name)
2939 			return -ENOMEM;
2940 		sprintf(map->inner_map->name, "%s.inner", map_name);
2941 
2942 		fill_map_from_def(map->inner_map, &inner_def);
2943 	}
2944 
2945 	err = map_fill_btf_type_info(obj, map);
2946 	if (err)
2947 		return err;
2948 
2949 	return 0;
2950 }
2951 
2952 static int init_arena_map_data(struct bpf_object *obj, struct bpf_map *map,
2953 			       const char *sec_name, int sec_idx,
2954 			       void *data, size_t data_sz)
2955 {
2956 	const long page_sz = sysconf(_SC_PAGE_SIZE);
2957 	size_t mmap_sz;
2958 
2959 	mmap_sz = bpf_map_mmap_sz(obj->arena_map);
2960 	if (roundup(data_sz, page_sz) > mmap_sz) {
2961 		pr_warn("elf: sec '%s': declared ARENA map size (%zu) is too small to hold global __arena variables of size %zu\n",
2962 			sec_name, mmap_sz, data_sz);
2963 		return -E2BIG;
2964 	}
2965 
2966 	obj->arena_data = malloc(data_sz);
2967 	if (!obj->arena_data)
2968 		return -ENOMEM;
2969 	memcpy(obj->arena_data, data, data_sz);
2970 	obj->arena_data_sz = data_sz;
2971 
2972 	/* make bpf_map__init_value() work for ARENA maps */
2973 	map->mmaped = obj->arena_data;
2974 
2975 	return 0;
2976 }
2977 
2978 static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict,
2979 					  const char *pin_root_path)
2980 {
2981 	const struct btf_type *sec = NULL;
2982 	int nr_types, i, vlen, err;
2983 	const struct btf_type *t;
2984 	const char *name;
2985 	Elf_Data *data;
2986 	Elf_Scn *scn;
2987 
2988 	if (obj->efile.btf_maps_shndx < 0)
2989 		return 0;
2990 
2991 	scn = elf_sec_by_idx(obj, obj->efile.btf_maps_shndx);
2992 	data = elf_sec_data(obj, scn);
2993 	if (!scn || !data) {
2994 		pr_warn("elf: failed to get %s map definitions for %s\n",
2995 			MAPS_ELF_SEC, obj->path);
2996 		return -EINVAL;
2997 	}
2998 
2999 	nr_types = btf__type_cnt(obj->btf);
3000 	for (i = 1; i < nr_types; i++) {
3001 		t = btf__type_by_id(obj->btf, i);
3002 		if (!btf_is_datasec(t))
3003 			continue;
3004 		name = btf__name_by_offset(obj->btf, t->name_off);
3005 		if (strcmp(name, MAPS_ELF_SEC) == 0) {
3006 			sec = t;
3007 			obj->efile.btf_maps_sec_btf_id = i;
3008 			break;
3009 		}
3010 	}
3011 
3012 	if (!sec) {
3013 		pr_warn("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
3014 		return -ENOENT;
3015 	}
3016 
3017 	vlen = btf_vlen(sec);
3018 	for (i = 0; i < vlen; i++) {
3019 		err = bpf_object__init_user_btf_map(obj, sec, i,
3020 						    obj->efile.btf_maps_shndx,
3021 						    data, strict,
3022 						    pin_root_path);
3023 		if (err)
3024 			return err;
3025 	}
3026 
3027 	for (i = 0; i < obj->nr_maps; i++) {
3028 		struct bpf_map *map = &obj->maps[i];
3029 
3030 		if (map->def.type != BPF_MAP_TYPE_ARENA)
3031 			continue;
3032 
3033 		if (obj->arena_map) {
3034 			pr_warn("map '%s': only single ARENA map is supported (map '%s' is also ARENA)\n",
3035 				map->name, obj->arena_map->name);
3036 			return -EINVAL;
3037 		}
3038 		obj->arena_map = map;
3039 
3040 		if (obj->efile.arena_data) {
3041 			err = init_arena_map_data(obj, map, ARENA_SEC, obj->efile.arena_data_shndx,
3042 						  obj->efile.arena_data->d_buf,
3043 						  obj->efile.arena_data->d_size);
3044 			if (err)
3045 				return err;
3046 		}
3047 	}
3048 	if (obj->efile.arena_data && !obj->arena_map) {
3049 		pr_warn("elf: sec '%s': to use global __arena variables the ARENA map should be explicitly declared in SEC(\".maps\")\n",
3050 			ARENA_SEC);
3051 		return -ENOENT;
3052 	}
3053 
3054 	return 0;
3055 }
3056 
3057 static int bpf_object__init_maps(struct bpf_object *obj,
3058 				 const struct bpf_object_open_opts *opts)
3059 {
3060 	const char *pin_root_path;
3061 	bool strict;
3062 	int err = 0;
3063 
3064 	strict = !OPTS_GET(opts, relaxed_maps, false);
3065 	pin_root_path = OPTS_GET(opts, pin_root_path, NULL);
3066 
3067 	err = bpf_object__init_user_btf_maps(obj, strict, pin_root_path);
3068 	err = err ?: bpf_object__init_global_data_maps(obj);
3069 	err = err ?: bpf_object__init_kconfig_map(obj);
3070 	err = err ?: bpf_object_init_struct_ops(obj);
3071 
3072 	return err;
3073 }
3074 
3075 static bool section_have_execinstr(struct bpf_object *obj, int idx)
3076 {
3077 	Elf64_Shdr *sh;
3078 
3079 	sh = elf_sec_hdr(obj, elf_sec_by_idx(obj, idx));
3080 	if (!sh)
3081 		return false;
3082 
3083 	return sh->sh_flags & SHF_EXECINSTR;
3084 }
3085 
3086 static bool starts_with_qmark(const char *s)
3087 {
3088 	return s && s[0] == '?';
3089 }
3090 
3091 static bool btf_needs_sanitization(struct bpf_object *obj)
3092 {
3093 	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
3094 	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
3095 	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
3096 	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
3097 	bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
3098 	bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
3099 	bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
3100 	bool has_qmark_datasec = kernel_supports(obj, FEAT_BTF_QMARK_DATASEC);
3101 
3102 	return !has_func || !has_datasec || !has_func_global || !has_float ||
3103 	       !has_decl_tag || !has_type_tag || !has_enum64 || !has_qmark_datasec;
3104 }
3105 
3106 static int bpf_object__sanitize_btf(struct bpf_object *obj, struct btf *btf)
3107 {
3108 	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
3109 	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
3110 	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
3111 	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
3112 	bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
3113 	bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
3114 	bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
3115 	bool has_qmark_datasec = kernel_supports(obj, FEAT_BTF_QMARK_DATASEC);
3116 	int enum64_placeholder_id = 0;
3117 	struct btf_type *t;
3118 	int i, j, vlen;
3119 
3120 	for (i = 1; i < btf__type_cnt(btf); i++) {
3121 		t = (struct btf_type *)btf__type_by_id(btf, i);
3122 
3123 		if ((!has_datasec && btf_is_var(t)) || (!has_decl_tag && btf_is_decl_tag(t))) {
3124 			/* replace VAR/DECL_TAG with INT */
3125 			t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
3126 			/*
3127 			 * using size = 1 is the safest choice, 4 will be too
3128 			 * big and cause kernel BTF validation failure if
3129 			 * original variable took less than 4 bytes
3130 			 */
3131 			t->size = 1;
3132 			*(int *)(t + 1) = BTF_INT_ENC(0, 0, 8);
3133 		} else if (!has_datasec && btf_is_datasec(t)) {
3134 			/* replace DATASEC with STRUCT */
3135 			const struct btf_var_secinfo *v = btf_var_secinfos(t);
3136 			struct btf_member *m = btf_members(t);
3137 			struct btf_type *vt;
3138 			char *name;
3139 
3140 			name = (char *)btf__name_by_offset(btf, t->name_off);
3141 			while (*name) {
3142 				if (*name == '.' || *name == '?')
3143 					*name = '_';
3144 				name++;
3145 			}
3146 
3147 			vlen = btf_vlen(t);
3148 			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
3149 			for (j = 0; j < vlen; j++, v++, m++) {
3150 				/* order of field assignments is important */
3151 				m->offset = v->offset * 8;
3152 				m->type = v->type;
3153 				/* preserve variable name as member name */
3154 				vt = (void *)btf__type_by_id(btf, v->type);
3155 				m->name_off = vt->name_off;
3156 			}
3157 		} else if (!has_qmark_datasec && btf_is_datasec(t) &&
3158 			   starts_with_qmark(btf__name_by_offset(btf, t->name_off))) {
3159 			/* replace '?' prefix with '_' for DATASEC names */
3160 			char *name;
3161 
3162 			name = (char *)btf__name_by_offset(btf, t->name_off);
3163 			if (name[0] == '?')
3164 				name[0] = '_';
3165 		} else if (!has_func && btf_is_func_proto(t)) {
3166 			/* replace FUNC_PROTO with ENUM */
3167 			vlen = btf_vlen(t);
3168 			t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
3169 			t->size = sizeof(__u32); /* kernel enforced */
3170 		} else if (!has_func && btf_is_func(t)) {
3171 			/* replace FUNC with TYPEDEF */
3172 			t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
3173 		} else if (!has_func_global && btf_is_func(t)) {
3174 			/* replace BTF_FUNC_GLOBAL with BTF_FUNC_STATIC */
3175 			t->info = BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0);
3176 		} else if (!has_float && btf_is_float(t)) {
3177 			/* replace FLOAT with an equally-sized empty STRUCT;
3178 			 * since C compilers do not accept e.g. "float" as a
3179 			 * valid struct name, make it anonymous
3180 			 */
3181 			t->name_off = 0;
3182 			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, 0);
3183 		} else if (!has_type_tag && btf_is_type_tag(t)) {
3184 			/* replace TYPE_TAG with a CONST */
3185 			t->name_off = 0;
3186 			t->info = BTF_INFO_ENC(BTF_KIND_CONST, 0, 0);
3187 		} else if (!has_enum64 && btf_is_enum(t)) {
3188 			/* clear the kflag */
3189 			t->info = btf_type_info(btf_kind(t), btf_vlen(t), false);
3190 		} else if (!has_enum64 && btf_is_enum64(t)) {
3191 			/* replace ENUM64 with a union */
3192 			struct btf_member *m;
3193 
3194 			if (enum64_placeholder_id == 0) {
3195 				enum64_placeholder_id = btf__add_int(btf, "enum64_placeholder", 1, 0);
3196 				if (enum64_placeholder_id < 0)
3197 					return enum64_placeholder_id;
3198 
3199 				t = (struct btf_type *)btf__type_by_id(btf, i);
3200 			}
3201 
3202 			m = btf_members(t);
3203 			vlen = btf_vlen(t);
3204 			t->info = BTF_INFO_ENC(BTF_KIND_UNION, 0, vlen);
3205 			for (j = 0; j < vlen; j++, m++) {
3206 				m->type = enum64_placeholder_id;
3207 				m->offset = 0;
3208 			}
3209 		}
3210 	}
3211 
3212 	return 0;
3213 }
3214 
3215 static bool libbpf_needs_btf(const struct bpf_object *obj)
3216 {
3217 	return obj->efile.btf_maps_shndx >= 0 ||
3218 	       obj->efile.has_st_ops ||
3219 	       obj->nr_extern > 0;
3220 }
3221 
3222 static bool kernel_needs_btf(const struct bpf_object *obj)
3223 {
3224 	return obj->efile.has_st_ops;
3225 }
3226 
3227 static int bpf_object__init_btf(struct bpf_object *obj,
3228 				Elf_Data *btf_data,
3229 				Elf_Data *btf_ext_data)
3230 {
3231 	int err = -ENOENT;
3232 
3233 	if (btf_data) {
3234 		obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
3235 		err = libbpf_get_error(obj->btf);
3236 		if (err) {
3237 			obj->btf = NULL;
3238 			pr_warn("Error loading ELF section %s: %d.\n", BTF_ELF_SEC, err);
3239 			goto out;
3240 		}
3241 		/* enforce 8-byte pointers for BPF-targeted BTFs */
3242 		btf__set_pointer_size(obj->btf, 8);
3243 	}
3244 	if (btf_ext_data) {
3245 		struct btf_ext_info *ext_segs[3];
3246 		int seg_num, sec_num;
3247 
3248 		if (!obj->btf) {
3249 			pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
3250 				 BTF_EXT_ELF_SEC, BTF_ELF_SEC);
3251 			goto out;
3252 		}
3253 		obj->btf_ext = btf_ext__new(btf_ext_data->d_buf, btf_ext_data->d_size);
3254 		err = libbpf_get_error(obj->btf_ext);
3255 		if (err) {
3256 			pr_warn("Error loading ELF section %s: %d. Ignored and continue.\n",
3257 				BTF_EXT_ELF_SEC, err);
3258 			obj->btf_ext = NULL;
3259 			goto out;
3260 		}
3261 
3262 		/* setup .BTF.ext to ELF section mapping */
3263 		ext_segs[0] = &obj->btf_ext->func_info;
3264 		ext_segs[1] = &obj->btf_ext->line_info;
3265 		ext_segs[2] = &obj->btf_ext->core_relo_info;
3266 		for (seg_num = 0; seg_num < ARRAY_SIZE(ext_segs); seg_num++) {
3267 			struct btf_ext_info *seg = ext_segs[seg_num];
3268 			const struct btf_ext_info_sec *sec;
3269 			const char *sec_name;
3270 			Elf_Scn *scn;
3271 
3272 			if (seg->sec_cnt == 0)
3273 				continue;
3274 
3275 			seg->sec_idxs = calloc(seg->sec_cnt, sizeof(*seg->sec_idxs));
3276 			if (!seg->sec_idxs) {
3277 				err = -ENOMEM;
3278 				goto out;
3279 			}
3280 
3281 			sec_num = 0;
3282 			for_each_btf_ext_sec(seg, sec) {
3283 				/* preventively increment index to avoid doing
3284 				 * this before every continue below
3285 				 */
3286 				sec_num++;
3287 
3288 				sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
3289 				if (str_is_empty(sec_name))
3290 					continue;
3291 				scn = elf_sec_by_name(obj, sec_name);
3292 				if (!scn)
3293 					continue;
3294 
3295 				seg->sec_idxs[sec_num - 1] = elf_ndxscn(scn);
3296 			}
3297 		}
3298 	}
3299 out:
3300 	if (err && libbpf_needs_btf(obj)) {
3301 		pr_warn("BTF is required, but is missing or corrupted.\n");
3302 		return err;
3303 	}
3304 	return 0;
3305 }
3306 
3307 static int compare_vsi_off(const void *_a, const void *_b)
3308 {
3309 	const struct btf_var_secinfo *a = _a;
3310 	const struct btf_var_secinfo *b = _b;
3311 
3312 	return a->offset - b->offset;
3313 }
3314 
3315 static int btf_fixup_datasec(struct bpf_object *obj, struct btf *btf,
3316 			     struct btf_type *t)
3317 {
3318 	__u32 size = 0, i, vars = btf_vlen(t);
3319 	const char *sec_name = btf__name_by_offset(btf, t->name_off);
3320 	struct btf_var_secinfo *vsi;
3321 	bool fixup_offsets = false;
3322 	int err;
3323 
3324 	if (!sec_name) {
3325 		pr_debug("No name found in string section for DATASEC kind.\n");
3326 		return -ENOENT;
3327 	}
3328 
3329 	/* Extern-backing datasecs (.ksyms, .kconfig) have their size and
3330 	 * variable offsets set at the previous step. Further, not every
3331 	 * extern BTF VAR has corresponding ELF symbol preserved, so we skip
3332 	 * all fixups altogether for such sections and go straight to sorting
3333 	 * VARs within their DATASEC.
3334 	 */
3335 	if (strcmp(sec_name, KCONFIG_SEC) == 0 || strcmp(sec_name, KSYMS_SEC) == 0)
3336 		goto sort_vars;
3337 
3338 	/* Clang leaves DATASEC size and VAR offsets as zeroes, so we need to
3339 	 * fix this up. But BPF static linker already fixes this up and fills
3340 	 * all the sizes and offsets during static linking. So this step has
3341 	 * to be optional. But the STV_HIDDEN handling is non-optional for any
3342 	 * non-extern DATASEC, so the variable fixup loop below handles both
3343 	 * functions at the same time, paying the cost of BTF VAR <-> ELF
3344 	 * symbol matching just once.
3345 	 */
3346 	if (t->size == 0) {
3347 		err = find_elf_sec_sz(obj, sec_name, &size);
3348 		if (err || !size) {
3349 			pr_debug("sec '%s': failed to determine size from ELF: size %u, err %d\n",
3350 				 sec_name, size, err);
3351 			return -ENOENT;
3352 		}
3353 
3354 		t->size = size;
3355 		fixup_offsets = true;
3356 	}
3357 
3358 	for (i = 0, vsi = btf_var_secinfos(t); i < vars; i++, vsi++) {
3359 		const struct btf_type *t_var;
3360 		struct btf_var *var;
3361 		const char *var_name;
3362 		Elf64_Sym *sym;
3363 
3364 		t_var = btf__type_by_id(btf, vsi->type);
3365 		if (!t_var || !btf_is_var(t_var)) {
3366 			pr_debug("sec '%s': unexpected non-VAR type found\n", sec_name);
3367 			return -EINVAL;
3368 		}
3369 
3370 		var = btf_var(t_var);
3371 		if (var->linkage == BTF_VAR_STATIC || var->linkage == BTF_VAR_GLOBAL_EXTERN)
3372 			continue;
3373 
3374 		var_name = btf__name_by_offset(btf, t_var->name_off);
3375 		if (!var_name) {
3376 			pr_debug("sec '%s': failed to find name of DATASEC's member #%d\n",
3377 				 sec_name, i);
3378 			return -ENOENT;
3379 		}
3380 
3381 		sym = find_elf_var_sym(obj, var_name);
3382 		if (IS_ERR(sym)) {
3383 			pr_debug("sec '%s': failed to find ELF symbol for VAR '%s'\n",
3384 				 sec_name, var_name);
3385 			return -ENOENT;
3386 		}
3387 
3388 		if (fixup_offsets)
3389 			vsi->offset = sym->st_value;
3390 
3391 		/* if variable is a global/weak symbol, but has restricted
3392 		 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF VAR
3393 		 * as static. This follows similar logic for functions (BPF
3394 		 * subprogs) and influences libbpf's further decisions about
3395 		 * whether to make global data BPF array maps as
3396 		 * BPF_F_MMAPABLE.
3397 		 */
3398 		if (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
3399 		    || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL)
3400 			var->linkage = BTF_VAR_STATIC;
3401 	}
3402 
3403 sort_vars:
3404 	qsort(btf_var_secinfos(t), vars, sizeof(*vsi), compare_vsi_off);
3405 	return 0;
3406 }
3407 
3408 static int bpf_object_fixup_btf(struct bpf_object *obj)
3409 {
3410 	int i, n, err = 0;
3411 
3412 	if (!obj->btf)
3413 		return 0;
3414 
3415 	n = btf__type_cnt(obj->btf);
3416 	for (i = 1; i < n; i++) {
3417 		struct btf_type *t = btf_type_by_id(obj->btf, i);
3418 
3419 		/* Loader needs to fix up some of the things compiler
3420 		 * couldn't get its hands on while emitting BTF. This
3421 		 * is section size and global variable offset. We use
3422 		 * the info from the ELF itself for this purpose.
3423 		 */
3424 		if (btf_is_datasec(t)) {
3425 			err = btf_fixup_datasec(obj, obj->btf, t);
3426 			if (err)
3427 				return err;
3428 		}
3429 	}
3430 
3431 	return 0;
3432 }
3433 
3434 static bool prog_needs_vmlinux_btf(struct bpf_program *prog)
3435 {
3436 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
3437 	    prog->type == BPF_PROG_TYPE_LSM)
3438 		return true;
3439 
3440 	/* BPF_PROG_TYPE_TRACING programs which do not attach to other programs
3441 	 * also need vmlinux BTF
3442 	 */
3443 	if (prog->type == BPF_PROG_TYPE_TRACING && !prog->attach_prog_fd)
3444 		return true;
3445 
3446 	return false;
3447 }
3448 
3449 static bool map_needs_vmlinux_btf(struct bpf_map *map)
3450 {
3451 	return bpf_map__is_struct_ops(map);
3452 }
3453 
3454 static bool obj_needs_vmlinux_btf(const struct bpf_object *obj)
3455 {
3456 	struct bpf_program *prog;
3457 	struct bpf_map *map;
3458 	int i;
3459 
3460 	/* CO-RE relocations need kernel BTF, only when btf_custom_path
3461 	 * is not specified
3462 	 */
3463 	if (obj->btf_ext && obj->btf_ext->core_relo_info.len && !obj->btf_custom_path)
3464 		return true;
3465 
3466 	/* Support for typed ksyms needs kernel BTF */
3467 	for (i = 0; i < obj->nr_extern; i++) {
3468 		const struct extern_desc *ext;
3469 
3470 		ext = &obj->externs[i];
3471 		if (ext->type == EXT_KSYM && ext->ksym.type_id)
3472 			return true;
3473 	}
3474 
3475 	bpf_object__for_each_program(prog, obj) {
3476 		if (!prog->autoload)
3477 			continue;
3478 		if (prog_needs_vmlinux_btf(prog))
3479 			return true;
3480 	}
3481 
3482 	bpf_object__for_each_map(map, obj) {
3483 		if (map_needs_vmlinux_btf(map))
3484 			return true;
3485 	}
3486 
3487 	return false;
3488 }
3489 
3490 static int bpf_object__load_vmlinux_btf(struct bpf_object *obj, bool force)
3491 {
3492 	int err;
3493 
3494 	/* btf_vmlinux could be loaded earlier */
3495 	if (obj->btf_vmlinux || obj->gen_loader)
3496 		return 0;
3497 
3498 	if (!force && !obj_needs_vmlinux_btf(obj))
3499 		return 0;
3500 
3501 	obj->btf_vmlinux = btf__load_vmlinux_btf();
3502 	err = libbpf_get_error(obj->btf_vmlinux);
3503 	if (err) {
3504 		pr_warn("Error loading vmlinux BTF: %d\n", err);
3505 		obj->btf_vmlinux = NULL;
3506 		return err;
3507 	}
3508 	return 0;
3509 }
3510 
3511 static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
3512 {
3513 	struct btf *kern_btf = obj->btf;
3514 	bool btf_mandatory, sanitize;
3515 	int i, err = 0;
3516 
3517 	if (!obj->btf)
3518 		return 0;
3519 
3520 	if (!kernel_supports(obj, FEAT_BTF)) {
3521 		if (kernel_needs_btf(obj)) {
3522 			err = -EOPNOTSUPP;
3523 			goto report;
3524 		}
3525 		pr_debug("Kernel doesn't support BTF, skipping uploading it.\n");
3526 		return 0;
3527 	}
3528 
3529 	/* Even though some subprogs are global/weak, user might prefer more
3530 	 * permissive BPF verification process that BPF verifier performs for
3531 	 * static functions, taking into account more context from the caller
3532 	 * functions. In such case, they need to mark such subprogs with
3533 	 * __attribute__((visibility("hidden"))) and libbpf will adjust
3534 	 * corresponding FUNC BTF type to be marked as static and trigger more
3535 	 * involved BPF verification process.
3536 	 */
3537 	for (i = 0; i < obj->nr_programs; i++) {
3538 		struct bpf_program *prog = &obj->programs[i];
3539 		struct btf_type *t;
3540 		const char *name;
3541 		int j, n;
3542 
3543 		if (!prog->mark_btf_static || !prog_is_subprog(obj, prog))
3544 			continue;
3545 
3546 		n = btf__type_cnt(obj->btf);
3547 		for (j = 1; j < n; j++) {
3548 			t = btf_type_by_id(obj->btf, j);
3549 			if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL)
3550 				continue;
3551 
3552 			name = btf__str_by_offset(obj->btf, t->name_off);
3553 			if (strcmp(name, prog->name) != 0)
3554 				continue;
3555 
3556 			t->info = btf_type_info(BTF_KIND_FUNC, BTF_FUNC_STATIC, 0);
3557 			break;
3558 		}
3559 	}
3560 
3561 	sanitize = btf_needs_sanitization(obj);
3562 	if (sanitize) {
3563 		const void *raw_data;
3564 		__u32 sz;
3565 
3566 		/* clone BTF to sanitize a copy and leave the original intact */
3567 		raw_data = btf__raw_data(obj->btf, &sz);
3568 		kern_btf = btf__new(raw_data, sz);
3569 		err = libbpf_get_error(kern_btf);
3570 		if (err)
3571 			return err;
3572 
3573 		/* enforce 8-byte pointers for BPF-targeted BTFs */
3574 		btf__set_pointer_size(obj->btf, 8);
3575 		err = bpf_object__sanitize_btf(obj, kern_btf);
3576 		if (err)
3577 			return err;
3578 	}
3579 
3580 	if (obj->gen_loader) {
3581 		__u32 raw_size = 0;
3582 		const void *raw_data = btf__raw_data(kern_btf, &raw_size);
3583 
3584 		if (!raw_data)
3585 			return -ENOMEM;
3586 		bpf_gen__load_btf(obj->gen_loader, raw_data, raw_size);
3587 		/* Pretend to have valid FD to pass various fd >= 0 checks.
3588 		 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
3589 		 */
3590 		btf__set_fd(kern_btf, 0);
3591 	} else {
3592 		/* currently BPF_BTF_LOAD only supports log_level 1 */
3593 		err = btf_load_into_kernel(kern_btf, obj->log_buf, obj->log_size,
3594 					   obj->log_level ? 1 : 0, obj->token_fd);
3595 	}
3596 	if (sanitize) {
3597 		if (!err) {
3598 			/* move fd to libbpf's BTF */
3599 			btf__set_fd(obj->btf, btf__fd(kern_btf));
3600 			btf__set_fd(kern_btf, -1);
3601 		}
3602 		btf__free(kern_btf);
3603 	}
3604 report:
3605 	if (err) {
3606 		btf_mandatory = kernel_needs_btf(obj);
3607 		if (btf_mandatory) {
3608 			pr_warn("Error loading .BTF into kernel: %d. BTF is mandatory, can't proceed.\n", err);
3609 		} else {
3610 			pr_info("Error loading .BTF into kernel: %d. BTF is optional, ignoring.\n", err);
3611 			err = 0;
3612 		}
3613 	}
3614 	return err;
3615 }
3616 
3617 static const char *elf_sym_str(const struct bpf_object *obj, size_t off)
3618 {
3619 	const char *name;
3620 
3621 	name = elf_strptr(obj->efile.elf, obj->efile.strtabidx, off);
3622 	if (!name) {
3623 		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3624 			off, obj->path, elf_errmsg(-1));
3625 		return NULL;
3626 	}
3627 
3628 	return name;
3629 }
3630 
3631 static const char *elf_sec_str(const struct bpf_object *obj, size_t off)
3632 {
3633 	const char *name;
3634 
3635 	name = elf_strptr(obj->efile.elf, obj->efile.shstrndx, off);
3636 	if (!name) {
3637 		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3638 			off, obj->path, elf_errmsg(-1));
3639 		return NULL;
3640 	}
3641 
3642 	return name;
3643 }
3644 
3645 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx)
3646 {
3647 	Elf_Scn *scn;
3648 
3649 	scn = elf_getscn(obj->efile.elf, idx);
3650 	if (!scn) {
3651 		pr_warn("elf: failed to get section(%zu) from %s: %s\n",
3652 			idx, obj->path, elf_errmsg(-1));
3653 		return NULL;
3654 	}
3655 	return scn;
3656 }
3657 
3658 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name)
3659 {
3660 	Elf_Scn *scn = NULL;
3661 	Elf *elf = obj->efile.elf;
3662 	const char *sec_name;
3663 
3664 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3665 		sec_name = elf_sec_name(obj, scn);
3666 		if (!sec_name)
3667 			return NULL;
3668 
3669 		if (strcmp(sec_name, name) != 0)
3670 			continue;
3671 
3672 		return scn;
3673 	}
3674 	return NULL;
3675 }
3676 
3677 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn)
3678 {
3679 	Elf64_Shdr *shdr;
3680 
3681 	if (!scn)
3682 		return NULL;
3683 
3684 	shdr = elf64_getshdr(scn);
3685 	if (!shdr) {
3686 		pr_warn("elf: failed to get section(%zu) header from %s: %s\n",
3687 			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3688 		return NULL;
3689 	}
3690 
3691 	return shdr;
3692 }
3693 
3694 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn)
3695 {
3696 	const char *name;
3697 	Elf64_Shdr *sh;
3698 
3699 	if (!scn)
3700 		return NULL;
3701 
3702 	sh = elf_sec_hdr(obj, scn);
3703 	if (!sh)
3704 		return NULL;
3705 
3706 	name = elf_sec_str(obj, sh->sh_name);
3707 	if (!name) {
3708 		pr_warn("elf: failed to get section(%zu) name from %s: %s\n",
3709 			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3710 		return NULL;
3711 	}
3712 
3713 	return name;
3714 }
3715 
3716 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn)
3717 {
3718 	Elf_Data *data;
3719 
3720 	if (!scn)
3721 		return NULL;
3722 
3723 	data = elf_getdata(scn, 0);
3724 	if (!data) {
3725 		pr_warn("elf: failed to get section(%zu) %s data from %s: %s\n",
3726 			elf_ndxscn(scn), elf_sec_name(obj, scn) ?: "<?>",
3727 			obj->path, elf_errmsg(-1));
3728 		return NULL;
3729 	}
3730 
3731 	return data;
3732 }
3733 
3734 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx)
3735 {
3736 	if (idx >= obj->efile.symbols->d_size / sizeof(Elf64_Sym))
3737 		return NULL;
3738 
3739 	return (Elf64_Sym *)obj->efile.symbols->d_buf + idx;
3740 }
3741 
3742 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx)
3743 {
3744 	if (idx >= data->d_size / sizeof(Elf64_Rel))
3745 		return NULL;
3746 
3747 	return (Elf64_Rel *)data->d_buf + idx;
3748 }
3749 
3750 static bool is_sec_name_dwarf(const char *name)
3751 {
3752 	/* approximation, but the actual list is too long */
3753 	return str_has_pfx(name, ".debug_");
3754 }
3755 
3756 static bool ignore_elf_section(Elf64_Shdr *hdr, const char *name)
3757 {
3758 	/* no special handling of .strtab */
3759 	if (hdr->sh_type == SHT_STRTAB)
3760 		return true;
3761 
3762 	/* ignore .llvm_addrsig section as well */
3763 	if (hdr->sh_type == SHT_LLVM_ADDRSIG)
3764 		return true;
3765 
3766 	/* no subprograms will lead to an empty .text section, ignore it */
3767 	if (hdr->sh_type == SHT_PROGBITS && hdr->sh_size == 0 &&
3768 	    strcmp(name, ".text") == 0)
3769 		return true;
3770 
3771 	/* DWARF sections */
3772 	if (is_sec_name_dwarf(name))
3773 		return true;
3774 
3775 	if (str_has_pfx(name, ".rel")) {
3776 		name += sizeof(".rel") - 1;
3777 		/* DWARF section relocations */
3778 		if (is_sec_name_dwarf(name))
3779 			return true;
3780 
3781 		/* .BTF and .BTF.ext don't need relocations */
3782 		if (strcmp(name, BTF_ELF_SEC) == 0 ||
3783 		    strcmp(name, BTF_EXT_ELF_SEC) == 0)
3784 			return true;
3785 	}
3786 
3787 	return false;
3788 }
3789 
3790 static int cmp_progs(const void *_a, const void *_b)
3791 {
3792 	const struct bpf_program *a = _a;
3793 	const struct bpf_program *b = _b;
3794 
3795 	if (a->sec_idx != b->sec_idx)
3796 		return a->sec_idx < b->sec_idx ? -1 : 1;
3797 
3798 	/* sec_insn_off can't be the same within the section */
3799 	return a->sec_insn_off < b->sec_insn_off ? -1 : 1;
3800 }
3801 
3802 static int bpf_object__elf_collect(struct bpf_object *obj)
3803 {
3804 	struct elf_sec_desc *sec_desc;
3805 	Elf *elf = obj->efile.elf;
3806 	Elf_Data *btf_ext_data = NULL;
3807 	Elf_Data *btf_data = NULL;
3808 	int idx = 0, err = 0;
3809 	const char *name;
3810 	Elf_Data *data;
3811 	Elf_Scn *scn;
3812 	Elf64_Shdr *sh;
3813 
3814 	/* ELF section indices are 0-based, but sec #0 is special "invalid"
3815 	 * section. Since section count retrieved by elf_getshdrnum() does
3816 	 * include sec #0, it is already the necessary size of an array to keep
3817 	 * all the sections.
3818 	 */
3819 	if (elf_getshdrnum(obj->efile.elf, &obj->efile.sec_cnt)) {
3820 		pr_warn("elf: failed to get the number of sections for %s: %s\n",
3821 			obj->path, elf_errmsg(-1));
3822 		return -LIBBPF_ERRNO__FORMAT;
3823 	}
3824 	obj->efile.secs = calloc(obj->efile.sec_cnt, sizeof(*obj->efile.secs));
3825 	if (!obj->efile.secs)
3826 		return -ENOMEM;
3827 
3828 	/* a bunch of ELF parsing functionality depends on processing symbols,
3829 	 * so do the first pass and find the symbol table
3830 	 */
3831 	scn = NULL;
3832 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3833 		sh = elf_sec_hdr(obj, scn);
3834 		if (!sh)
3835 			return -LIBBPF_ERRNO__FORMAT;
3836 
3837 		if (sh->sh_type == SHT_SYMTAB) {
3838 			if (obj->efile.symbols) {
3839 				pr_warn("elf: multiple symbol tables in %s\n", obj->path);
3840 				return -LIBBPF_ERRNO__FORMAT;
3841 			}
3842 
3843 			data = elf_sec_data(obj, scn);
3844 			if (!data)
3845 				return -LIBBPF_ERRNO__FORMAT;
3846 
3847 			idx = elf_ndxscn(scn);
3848 
3849 			obj->efile.symbols = data;
3850 			obj->efile.symbols_shndx = idx;
3851 			obj->efile.strtabidx = sh->sh_link;
3852 		}
3853 	}
3854 
3855 	if (!obj->efile.symbols) {
3856 		pr_warn("elf: couldn't find symbol table in %s, stripped object file?\n",
3857 			obj->path);
3858 		return -ENOENT;
3859 	}
3860 
3861 	scn = NULL;
3862 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3863 		idx = elf_ndxscn(scn);
3864 		sec_desc = &obj->efile.secs[idx];
3865 
3866 		sh = elf_sec_hdr(obj, scn);
3867 		if (!sh)
3868 			return -LIBBPF_ERRNO__FORMAT;
3869 
3870 		name = elf_sec_str(obj, sh->sh_name);
3871 		if (!name)
3872 			return -LIBBPF_ERRNO__FORMAT;
3873 
3874 		if (ignore_elf_section(sh, name))
3875 			continue;
3876 
3877 		data = elf_sec_data(obj, scn);
3878 		if (!data)
3879 			return -LIBBPF_ERRNO__FORMAT;
3880 
3881 		pr_debug("elf: section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
3882 			 idx, name, (unsigned long)data->d_size,
3883 			 (int)sh->sh_link, (unsigned long)sh->sh_flags,
3884 			 (int)sh->sh_type);
3885 
3886 		if (strcmp(name, "license") == 0) {
3887 			err = bpf_object__init_license(obj, data->d_buf, data->d_size);
3888 			if (err)
3889 				return err;
3890 		} else if (strcmp(name, "version") == 0) {
3891 			err = bpf_object__init_kversion(obj, data->d_buf, data->d_size);
3892 			if (err)
3893 				return err;
3894 		} else if (strcmp(name, "maps") == 0) {
3895 			pr_warn("elf: legacy map definitions in 'maps' section are not supported by libbpf v1.0+\n");
3896 			return -ENOTSUP;
3897 		} else if (strcmp(name, MAPS_ELF_SEC) == 0) {
3898 			obj->efile.btf_maps_shndx = idx;
3899 		} else if (strcmp(name, BTF_ELF_SEC) == 0) {
3900 			if (sh->sh_type != SHT_PROGBITS)
3901 				return -LIBBPF_ERRNO__FORMAT;
3902 			btf_data = data;
3903 		} else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
3904 			if (sh->sh_type != SHT_PROGBITS)
3905 				return -LIBBPF_ERRNO__FORMAT;
3906 			btf_ext_data = data;
3907 		} else if (sh->sh_type == SHT_SYMTAB) {
3908 			/* already processed during the first pass above */
3909 		} else if (sh->sh_type == SHT_PROGBITS && data->d_size > 0) {
3910 			if (sh->sh_flags & SHF_EXECINSTR) {
3911 				if (strcmp(name, ".text") == 0)
3912 					obj->efile.text_shndx = idx;
3913 				err = bpf_object__add_programs(obj, data, name, idx);
3914 				if (err)
3915 					return err;
3916 			} else if (strcmp(name, DATA_SEC) == 0 ||
3917 				   str_has_pfx(name, DATA_SEC ".")) {
3918 				sec_desc->sec_type = SEC_DATA;
3919 				sec_desc->shdr = sh;
3920 				sec_desc->data = data;
3921 			} else if (strcmp(name, RODATA_SEC) == 0 ||
3922 				   str_has_pfx(name, RODATA_SEC ".")) {
3923 				sec_desc->sec_type = SEC_RODATA;
3924 				sec_desc->shdr = sh;
3925 				sec_desc->data = data;
3926 			} else if (strcmp(name, STRUCT_OPS_SEC) == 0 ||
3927 				   strcmp(name, STRUCT_OPS_LINK_SEC) == 0 ||
3928 				   strcmp(name, "?" STRUCT_OPS_SEC) == 0 ||
3929 				   strcmp(name, "?" STRUCT_OPS_LINK_SEC) == 0) {
3930 				sec_desc->sec_type = SEC_ST_OPS;
3931 				sec_desc->shdr = sh;
3932 				sec_desc->data = data;
3933 				obj->efile.has_st_ops = true;
3934 			} else if (strcmp(name, ARENA_SEC) == 0) {
3935 				obj->efile.arena_data = data;
3936 				obj->efile.arena_data_shndx = idx;
3937 			} else {
3938 				pr_info("elf: skipping unrecognized data section(%d) %s\n",
3939 					idx, name);
3940 			}
3941 		} else if (sh->sh_type == SHT_REL) {
3942 			int targ_sec_idx = sh->sh_info; /* points to other section */
3943 
3944 			if (sh->sh_entsize != sizeof(Elf64_Rel) ||
3945 			    targ_sec_idx >= obj->efile.sec_cnt)
3946 				return -LIBBPF_ERRNO__FORMAT;
3947 
3948 			/* Only do relo for section with exec instructions */
3949 			if (!section_have_execinstr(obj, targ_sec_idx) &&
3950 			    strcmp(name, ".rel" STRUCT_OPS_SEC) &&
3951 			    strcmp(name, ".rel" STRUCT_OPS_LINK_SEC) &&
3952 			    strcmp(name, ".rel?" STRUCT_OPS_SEC) &&
3953 			    strcmp(name, ".rel?" STRUCT_OPS_LINK_SEC) &&
3954 			    strcmp(name, ".rel" MAPS_ELF_SEC)) {
3955 				pr_info("elf: skipping relo section(%d) %s for section(%d) %s\n",
3956 					idx, name, targ_sec_idx,
3957 					elf_sec_name(obj, elf_sec_by_idx(obj, targ_sec_idx)) ?: "<?>");
3958 				continue;
3959 			}
3960 
3961 			sec_desc->sec_type = SEC_RELO;
3962 			sec_desc->shdr = sh;
3963 			sec_desc->data = data;
3964 		} else if (sh->sh_type == SHT_NOBITS && (strcmp(name, BSS_SEC) == 0 ||
3965 							 str_has_pfx(name, BSS_SEC "."))) {
3966 			sec_desc->sec_type = SEC_BSS;
3967 			sec_desc->shdr = sh;
3968 			sec_desc->data = data;
3969 		} else {
3970 			pr_info("elf: skipping section(%d) %s (size %zu)\n", idx, name,
3971 				(size_t)sh->sh_size);
3972 		}
3973 	}
3974 
3975 	if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) {
3976 		pr_warn("elf: symbol strings section missing or invalid in %s\n", obj->path);
3977 		return -LIBBPF_ERRNO__FORMAT;
3978 	}
3979 
3980 	/* change BPF program insns to native endianness for introspection */
3981 	if (!is_native_endianness(obj))
3982 		bpf_object_bswap_progs(obj);
3983 
3984 	/* sort BPF programs by section name and in-section instruction offset
3985 	 * for faster search
3986 	 */
3987 	if (obj->nr_programs)
3988 		qsort(obj->programs, obj->nr_programs, sizeof(*obj->programs), cmp_progs);
3989 
3990 	return bpf_object__init_btf(obj, btf_data, btf_ext_data);
3991 }
3992 
3993 static bool sym_is_extern(const Elf64_Sym *sym)
3994 {
3995 	int bind = ELF64_ST_BIND(sym->st_info);
3996 	/* externs are symbols w/ type=NOTYPE, bind=GLOBAL|WEAK, section=UND */
3997 	return sym->st_shndx == SHN_UNDEF &&
3998 	       (bind == STB_GLOBAL || bind == STB_WEAK) &&
3999 	       ELF64_ST_TYPE(sym->st_info) == STT_NOTYPE;
4000 }
4001 
4002 static bool sym_is_subprog(const Elf64_Sym *sym, int text_shndx)
4003 {
4004 	int bind = ELF64_ST_BIND(sym->st_info);
4005 	int type = ELF64_ST_TYPE(sym->st_info);
4006 
4007 	/* in .text section */
4008 	if (sym->st_shndx != text_shndx)
4009 		return false;
4010 
4011 	/* local function */
4012 	if (bind == STB_LOCAL && type == STT_SECTION)
4013 		return true;
4014 
4015 	/* global function */
4016 	return (bind == STB_GLOBAL || bind == STB_WEAK) && type == STT_FUNC;
4017 }
4018 
4019 static int find_extern_btf_id(const struct btf *btf, const char *ext_name)
4020 {
4021 	const struct btf_type *t;
4022 	const char *tname;
4023 	int i, n;
4024 
4025 	if (!btf)
4026 		return -ESRCH;
4027 
4028 	n = btf__type_cnt(btf);
4029 	for (i = 1; i < n; i++) {
4030 		t = btf__type_by_id(btf, i);
4031 
4032 		if (!btf_is_var(t) && !btf_is_func(t))
4033 			continue;
4034 
4035 		tname = btf__name_by_offset(btf, t->name_off);
4036 		if (strcmp(tname, ext_name))
4037 			continue;
4038 
4039 		if (btf_is_var(t) &&
4040 		    btf_var(t)->linkage != BTF_VAR_GLOBAL_EXTERN)
4041 			return -EINVAL;
4042 
4043 		if (btf_is_func(t) && btf_func_linkage(t) != BTF_FUNC_EXTERN)
4044 			return -EINVAL;
4045 
4046 		return i;
4047 	}
4048 
4049 	return -ENOENT;
4050 }
4051 
4052 static int find_extern_sec_btf_id(struct btf *btf, int ext_btf_id) {
4053 	const struct btf_var_secinfo *vs;
4054 	const struct btf_type *t;
4055 	int i, j, n;
4056 
4057 	if (!btf)
4058 		return -ESRCH;
4059 
4060 	n = btf__type_cnt(btf);
4061 	for (i = 1; i < n; i++) {
4062 		t = btf__type_by_id(btf, i);
4063 
4064 		if (!btf_is_datasec(t))
4065 			continue;
4066 
4067 		vs = btf_var_secinfos(t);
4068 		for (j = 0; j < btf_vlen(t); j++, vs++) {
4069 			if (vs->type == ext_btf_id)
4070 				return i;
4071 		}
4072 	}
4073 
4074 	return -ENOENT;
4075 }
4076 
4077 static enum kcfg_type find_kcfg_type(const struct btf *btf, int id,
4078 				     bool *is_signed)
4079 {
4080 	const struct btf_type *t;
4081 	const char *name;
4082 
4083 	t = skip_mods_and_typedefs(btf, id, NULL);
4084 	name = btf__name_by_offset(btf, t->name_off);
4085 
4086 	if (is_signed)
4087 		*is_signed = false;
4088 	switch (btf_kind(t)) {
4089 	case BTF_KIND_INT: {
4090 		int enc = btf_int_encoding(t);
4091 
4092 		if (enc & BTF_INT_BOOL)
4093 			return t->size == 1 ? KCFG_BOOL : KCFG_UNKNOWN;
4094 		if (is_signed)
4095 			*is_signed = enc & BTF_INT_SIGNED;
4096 		if (t->size == 1)
4097 			return KCFG_CHAR;
4098 		if (t->size < 1 || t->size > 8 || (t->size & (t->size - 1)))
4099 			return KCFG_UNKNOWN;
4100 		return KCFG_INT;
4101 	}
4102 	case BTF_KIND_ENUM:
4103 		if (t->size != 4)
4104 			return KCFG_UNKNOWN;
4105 		if (strcmp(name, "libbpf_tristate"))
4106 			return KCFG_UNKNOWN;
4107 		return KCFG_TRISTATE;
4108 	case BTF_KIND_ENUM64:
4109 		if (strcmp(name, "libbpf_tristate"))
4110 			return KCFG_UNKNOWN;
4111 		return KCFG_TRISTATE;
4112 	case BTF_KIND_ARRAY:
4113 		if (btf_array(t)->nelems == 0)
4114 			return KCFG_UNKNOWN;
4115 		if (find_kcfg_type(btf, btf_array(t)->type, NULL) != KCFG_CHAR)
4116 			return KCFG_UNKNOWN;
4117 		return KCFG_CHAR_ARR;
4118 	default:
4119 		return KCFG_UNKNOWN;
4120 	}
4121 }
4122 
4123 static int cmp_externs(const void *_a, const void *_b)
4124 {
4125 	const struct extern_desc *a = _a;
4126 	const struct extern_desc *b = _b;
4127 
4128 	if (a->type != b->type)
4129 		return a->type < b->type ? -1 : 1;
4130 
4131 	if (a->type == EXT_KCFG) {
4132 		/* descending order by alignment requirements */
4133 		if (a->kcfg.align != b->kcfg.align)
4134 			return a->kcfg.align > b->kcfg.align ? -1 : 1;
4135 		/* ascending order by size, within same alignment class */
4136 		if (a->kcfg.sz != b->kcfg.sz)
4137 			return a->kcfg.sz < b->kcfg.sz ? -1 : 1;
4138 	}
4139 
4140 	/* resolve ties by name */
4141 	return strcmp(a->name, b->name);
4142 }
4143 
4144 static int find_int_btf_id(const struct btf *btf)
4145 {
4146 	const struct btf_type *t;
4147 	int i, n;
4148 
4149 	n = btf__type_cnt(btf);
4150 	for (i = 1; i < n; i++) {
4151 		t = btf__type_by_id(btf, i);
4152 
4153 		if (btf_is_int(t) && btf_int_bits(t) == 32)
4154 			return i;
4155 	}
4156 
4157 	return 0;
4158 }
4159 
4160 static int add_dummy_ksym_var(struct btf *btf)
4161 {
4162 	int i, int_btf_id, sec_btf_id, dummy_var_btf_id;
4163 	const struct btf_var_secinfo *vs;
4164 	const struct btf_type *sec;
4165 
4166 	if (!btf)
4167 		return 0;
4168 
4169 	sec_btf_id = btf__find_by_name_kind(btf, KSYMS_SEC,
4170 					    BTF_KIND_DATASEC);
4171 	if (sec_btf_id < 0)
4172 		return 0;
4173 
4174 	sec = btf__type_by_id(btf, sec_btf_id);
4175 	vs = btf_var_secinfos(sec);
4176 	for (i = 0; i < btf_vlen(sec); i++, vs++) {
4177 		const struct btf_type *vt;
4178 
4179 		vt = btf__type_by_id(btf, vs->type);
4180 		if (btf_is_func(vt))
4181 			break;
4182 	}
4183 
4184 	/* No func in ksyms sec.  No need to add dummy var. */
4185 	if (i == btf_vlen(sec))
4186 		return 0;
4187 
4188 	int_btf_id = find_int_btf_id(btf);
4189 	dummy_var_btf_id = btf__add_var(btf,
4190 					"dummy_ksym",
4191 					BTF_VAR_GLOBAL_ALLOCATED,
4192 					int_btf_id);
4193 	if (dummy_var_btf_id < 0)
4194 		pr_warn("cannot create a dummy_ksym var\n");
4195 
4196 	return dummy_var_btf_id;
4197 }
4198 
4199 static int bpf_object__collect_externs(struct bpf_object *obj)
4200 {
4201 	struct btf_type *sec, *kcfg_sec = NULL, *ksym_sec = NULL;
4202 	const struct btf_type *t;
4203 	struct extern_desc *ext;
4204 	int i, n, off, dummy_var_btf_id;
4205 	const char *ext_name, *sec_name;
4206 	size_t ext_essent_len;
4207 	Elf_Scn *scn;
4208 	Elf64_Shdr *sh;
4209 
4210 	if (!obj->efile.symbols)
4211 		return 0;
4212 
4213 	scn = elf_sec_by_idx(obj, obj->efile.symbols_shndx);
4214 	sh = elf_sec_hdr(obj, scn);
4215 	if (!sh || sh->sh_entsize != sizeof(Elf64_Sym))
4216 		return -LIBBPF_ERRNO__FORMAT;
4217 
4218 	dummy_var_btf_id = add_dummy_ksym_var(obj->btf);
4219 	if (dummy_var_btf_id < 0)
4220 		return dummy_var_btf_id;
4221 
4222 	n = sh->sh_size / sh->sh_entsize;
4223 	pr_debug("looking for externs among %d symbols...\n", n);
4224 
4225 	for (i = 0; i < n; i++) {
4226 		Elf64_Sym *sym = elf_sym_by_idx(obj, i);
4227 
4228 		if (!sym)
4229 			return -LIBBPF_ERRNO__FORMAT;
4230 		if (!sym_is_extern(sym))
4231 			continue;
4232 		ext_name = elf_sym_str(obj, sym->st_name);
4233 		if (!ext_name || !ext_name[0])
4234 			continue;
4235 
4236 		ext = obj->externs;
4237 		ext = libbpf_reallocarray(ext, obj->nr_extern + 1, sizeof(*ext));
4238 		if (!ext)
4239 			return -ENOMEM;
4240 		obj->externs = ext;
4241 		ext = &ext[obj->nr_extern];
4242 		memset(ext, 0, sizeof(*ext));
4243 		obj->nr_extern++;
4244 
4245 		ext->btf_id = find_extern_btf_id(obj->btf, ext_name);
4246 		if (ext->btf_id <= 0) {
4247 			pr_warn("failed to find BTF for extern '%s': %d\n",
4248 				ext_name, ext->btf_id);
4249 			return ext->btf_id;
4250 		}
4251 		t = btf__type_by_id(obj->btf, ext->btf_id);
4252 		ext->name = btf__name_by_offset(obj->btf, t->name_off);
4253 		ext->sym_idx = i;
4254 		ext->is_weak = ELF64_ST_BIND(sym->st_info) == STB_WEAK;
4255 
4256 		ext_essent_len = bpf_core_essential_name_len(ext->name);
4257 		ext->essent_name = NULL;
4258 		if (ext_essent_len != strlen(ext->name)) {
4259 			ext->essent_name = strndup(ext->name, ext_essent_len);
4260 			if (!ext->essent_name)
4261 				return -ENOMEM;
4262 		}
4263 
4264 		ext->sec_btf_id = find_extern_sec_btf_id(obj->btf, ext->btf_id);
4265 		if (ext->sec_btf_id <= 0) {
4266 			pr_warn("failed to find BTF for extern '%s' [%d] section: %d\n",
4267 				ext_name, ext->btf_id, ext->sec_btf_id);
4268 			return ext->sec_btf_id;
4269 		}
4270 		sec = (void *)btf__type_by_id(obj->btf, ext->sec_btf_id);
4271 		sec_name = btf__name_by_offset(obj->btf, sec->name_off);
4272 
4273 		if (strcmp(sec_name, KCONFIG_SEC) == 0) {
4274 			if (btf_is_func(t)) {
4275 				pr_warn("extern function %s is unsupported under %s section\n",
4276 					ext->name, KCONFIG_SEC);
4277 				return -ENOTSUP;
4278 			}
4279 			kcfg_sec = sec;
4280 			ext->type = EXT_KCFG;
4281 			ext->kcfg.sz = btf__resolve_size(obj->btf, t->type);
4282 			if (ext->kcfg.sz <= 0) {
4283 				pr_warn("failed to resolve size of extern (kcfg) '%s': %d\n",
4284 					ext_name, ext->kcfg.sz);
4285 				return ext->kcfg.sz;
4286 			}
4287 			ext->kcfg.align = btf__align_of(obj->btf, t->type);
4288 			if (ext->kcfg.align <= 0) {
4289 				pr_warn("failed to determine alignment of extern (kcfg) '%s': %d\n",
4290 					ext_name, ext->kcfg.align);
4291 				return -EINVAL;
4292 			}
4293 			ext->kcfg.type = find_kcfg_type(obj->btf, t->type,
4294 							&ext->kcfg.is_signed);
4295 			if (ext->kcfg.type == KCFG_UNKNOWN) {
4296 				pr_warn("extern (kcfg) '%s': type is unsupported\n", ext_name);
4297 				return -ENOTSUP;
4298 			}
4299 		} else if (strcmp(sec_name, KSYMS_SEC) == 0) {
4300 			ksym_sec = sec;
4301 			ext->type = EXT_KSYM;
4302 			skip_mods_and_typedefs(obj->btf, t->type,
4303 					       &ext->ksym.type_id);
4304 		} else {
4305 			pr_warn("unrecognized extern section '%s'\n", sec_name);
4306 			return -ENOTSUP;
4307 		}
4308 	}
4309 	pr_debug("collected %d externs total\n", obj->nr_extern);
4310 
4311 	if (!obj->nr_extern)
4312 		return 0;
4313 
4314 	/* sort externs by type, for kcfg ones also by (align, size, name) */
4315 	qsort(obj->externs, obj->nr_extern, sizeof(*ext), cmp_externs);
4316 
4317 	/* for .ksyms section, we need to turn all externs into allocated
4318 	 * variables in BTF to pass kernel verification; we do this by
4319 	 * pretending that each extern is a 8-byte variable
4320 	 */
4321 	if (ksym_sec) {
4322 		/* find existing 4-byte integer type in BTF to use for fake
4323 		 * extern variables in DATASEC
4324 		 */
4325 		int int_btf_id = find_int_btf_id(obj->btf);
4326 		/* For extern function, a dummy_var added earlier
4327 		 * will be used to replace the vs->type and
4328 		 * its name string will be used to refill
4329 		 * the missing param's name.
4330 		 */
4331 		const struct btf_type *dummy_var;
4332 
4333 		dummy_var = btf__type_by_id(obj->btf, dummy_var_btf_id);
4334 		for (i = 0; i < obj->nr_extern; i++) {
4335 			ext = &obj->externs[i];
4336 			if (ext->type != EXT_KSYM)
4337 				continue;
4338 			pr_debug("extern (ksym) #%d: symbol %d, name %s\n",
4339 				 i, ext->sym_idx, ext->name);
4340 		}
4341 
4342 		sec = ksym_sec;
4343 		n = btf_vlen(sec);
4344 		for (i = 0, off = 0; i < n; i++, off += sizeof(int)) {
4345 			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
4346 			struct btf_type *vt;
4347 
4348 			vt = (void *)btf__type_by_id(obj->btf, vs->type);
4349 			ext_name = btf__name_by_offset(obj->btf, vt->name_off);
4350 			ext = find_extern_by_name(obj, ext_name);
4351 			if (!ext) {
4352 				pr_warn("failed to find extern definition for BTF %s '%s'\n",
4353 					btf_kind_str(vt), ext_name);
4354 				return -ESRCH;
4355 			}
4356 			if (btf_is_func(vt)) {
4357 				const struct btf_type *func_proto;
4358 				struct btf_param *param;
4359 				int j;
4360 
4361 				func_proto = btf__type_by_id(obj->btf,
4362 							     vt->type);
4363 				param = btf_params(func_proto);
4364 				/* Reuse the dummy_var string if the
4365 				 * func proto does not have param name.
4366 				 */
4367 				for (j = 0; j < btf_vlen(func_proto); j++)
4368 					if (param[j].type && !param[j].name_off)
4369 						param[j].name_off =
4370 							dummy_var->name_off;
4371 				vs->type = dummy_var_btf_id;
4372 				vt->info &= ~0xffff;
4373 				vt->info |= BTF_FUNC_GLOBAL;
4374 			} else {
4375 				btf_var(vt)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
4376 				vt->type = int_btf_id;
4377 			}
4378 			vs->offset = off;
4379 			vs->size = sizeof(int);
4380 		}
4381 		sec->size = off;
4382 	}
4383 
4384 	if (kcfg_sec) {
4385 		sec = kcfg_sec;
4386 		/* for kcfg externs calculate their offsets within a .kconfig map */
4387 		off = 0;
4388 		for (i = 0; i < obj->nr_extern; i++) {
4389 			ext = &obj->externs[i];
4390 			if (ext->type != EXT_KCFG)
4391 				continue;
4392 
4393 			ext->kcfg.data_off = roundup(off, ext->kcfg.align);
4394 			off = ext->kcfg.data_off + ext->kcfg.sz;
4395 			pr_debug("extern (kcfg) #%d: symbol %d, off %u, name %s\n",
4396 				 i, ext->sym_idx, ext->kcfg.data_off, ext->name);
4397 		}
4398 		sec->size = off;
4399 		n = btf_vlen(sec);
4400 		for (i = 0; i < n; i++) {
4401 			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
4402 
4403 			t = btf__type_by_id(obj->btf, vs->type);
4404 			ext_name = btf__name_by_offset(obj->btf, t->name_off);
4405 			ext = find_extern_by_name(obj, ext_name);
4406 			if (!ext) {
4407 				pr_warn("failed to find extern definition for BTF var '%s'\n",
4408 					ext_name);
4409 				return -ESRCH;
4410 			}
4411 			btf_var(t)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
4412 			vs->offset = ext->kcfg.data_off;
4413 		}
4414 	}
4415 	return 0;
4416 }
4417 
4418 static bool prog_is_subprog(const struct bpf_object *obj, const struct bpf_program *prog)
4419 {
4420 	return prog->sec_idx == obj->efile.text_shndx;
4421 }
4422 
4423 struct bpf_program *
4424 bpf_object__find_program_by_name(const struct bpf_object *obj,
4425 				 const char *name)
4426 {
4427 	struct bpf_program *prog;
4428 
4429 	bpf_object__for_each_program(prog, obj) {
4430 		if (prog_is_subprog(obj, prog))
4431 			continue;
4432 		if (!strcmp(prog->name, name))
4433 			return prog;
4434 	}
4435 	return errno = ENOENT, NULL;
4436 }
4437 
4438 static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
4439 				      int shndx)
4440 {
4441 	switch (obj->efile.secs[shndx].sec_type) {
4442 	case SEC_BSS:
4443 	case SEC_DATA:
4444 	case SEC_RODATA:
4445 		return true;
4446 	default:
4447 		return false;
4448 	}
4449 }
4450 
4451 static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
4452 				      int shndx)
4453 {
4454 	return shndx == obj->efile.btf_maps_shndx;
4455 }
4456 
4457 static enum libbpf_map_type
4458 bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
4459 {
4460 	if (shndx == obj->efile.symbols_shndx)
4461 		return LIBBPF_MAP_KCONFIG;
4462 
4463 	switch (obj->efile.secs[shndx].sec_type) {
4464 	case SEC_BSS:
4465 		return LIBBPF_MAP_BSS;
4466 	case SEC_DATA:
4467 		return LIBBPF_MAP_DATA;
4468 	case SEC_RODATA:
4469 		return LIBBPF_MAP_RODATA;
4470 	default:
4471 		return LIBBPF_MAP_UNSPEC;
4472 	}
4473 }
4474 
4475 static int bpf_program__record_reloc(struct bpf_program *prog,
4476 				     struct reloc_desc *reloc_desc,
4477 				     __u32 insn_idx, const char *sym_name,
4478 				     const Elf64_Sym *sym, const Elf64_Rel *rel)
4479 {
4480 	struct bpf_insn *insn = &prog->insns[insn_idx];
4481 	size_t map_idx, nr_maps = prog->obj->nr_maps;
4482 	struct bpf_object *obj = prog->obj;
4483 	__u32 shdr_idx = sym->st_shndx;
4484 	enum libbpf_map_type type;
4485 	const char *sym_sec_name;
4486 	struct bpf_map *map;
4487 
4488 	if (!is_call_insn(insn) && !is_ldimm64_insn(insn)) {
4489 		pr_warn("prog '%s': invalid relo against '%s' for insns[%d].code 0x%x\n",
4490 			prog->name, sym_name, insn_idx, insn->code);
4491 		return -LIBBPF_ERRNO__RELOC;
4492 	}
4493 
4494 	if (sym_is_extern(sym)) {
4495 		int sym_idx = ELF64_R_SYM(rel->r_info);
4496 		int i, n = obj->nr_extern;
4497 		struct extern_desc *ext;
4498 
4499 		for (i = 0; i < n; i++) {
4500 			ext = &obj->externs[i];
4501 			if (ext->sym_idx == sym_idx)
4502 				break;
4503 		}
4504 		if (i >= n) {
4505 			pr_warn("prog '%s': extern relo failed to find extern for '%s' (%d)\n",
4506 				prog->name, sym_name, sym_idx);
4507 			return -LIBBPF_ERRNO__RELOC;
4508 		}
4509 		pr_debug("prog '%s': found extern #%d '%s' (sym %d) for insn #%u\n",
4510 			 prog->name, i, ext->name, ext->sym_idx, insn_idx);
4511 		if (insn->code == (BPF_JMP | BPF_CALL))
4512 			reloc_desc->type = RELO_EXTERN_CALL;
4513 		else
4514 			reloc_desc->type = RELO_EXTERN_LD64;
4515 		reloc_desc->insn_idx = insn_idx;
4516 		reloc_desc->ext_idx = i;
4517 		return 0;
4518 	}
4519 
4520 	/* sub-program call relocation */
4521 	if (is_call_insn(insn)) {
4522 		if (insn->src_reg != BPF_PSEUDO_CALL) {
4523 			pr_warn("prog '%s': incorrect bpf_call opcode\n", prog->name);
4524 			return -LIBBPF_ERRNO__RELOC;
4525 		}
4526 		/* text_shndx can be 0, if no default "main" program exists */
4527 		if (!shdr_idx || shdr_idx != obj->efile.text_shndx) {
4528 			sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4529 			pr_warn("prog '%s': bad call relo against '%s' in section '%s'\n",
4530 				prog->name, sym_name, sym_sec_name);
4531 			return -LIBBPF_ERRNO__RELOC;
4532 		}
4533 		if (sym->st_value % BPF_INSN_SZ) {
4534 			pr_warn("prog '%s': bad call relo against '%s' at offset %zu\n",
4535 				prog->name, sym_name, (size_t)sym->st_value);
4536 			return -LIBBPF_ERRNO__RELOC;
4537 		}
4538 		reloc_desc->type = RELO_CALL;
4539 		reloc_desc->insn_idx = insn_idx;
4540 		reloc_desc->sym_off = sym->st_value;
4541 		return 0;
4542 	}
4543 
4544 	if (!shdr_idx || shdr_idx >= SHN_LORESERVE) {
4545 		pr_warn("prog '%s': invalid relo against '%s' in special section 0x%x; forgot to initialize global var?..\n",
4546 			prog->name, sym_name, shdr_idx);
4547 		return -LIBBPF_ERRNO__RELOC;
4548 	}
4549 
4550 	/* loading subprog addresses */
4551 	if (sym_is_subprog(sym, obj->efile.text_shndx)) {
4552 		/* global_func: sym->st_value = offset in the section, insn->imm = 0.
4553 		 * local_func: sym->st_value = 0, insn->imm = offset in the section.
4554 		 */
4555 		if ((sym->st_value % BPF_INSN_SZ) || (insn->imm % BPF_INSN_SZ)) {
4556 			pr_warn("prog '%s': bad subprog addr relo against '%s' at offset %zu+%d\n",
4557 				prog->name, sym_name, (size_t)sym->st_value, insn->imm);
4558 			return -LIBBPF_ERRNO__RELOC;
4559 		}
4560 
4561 		reloc_desc->type = RELO_SUBPROG_ADDR;
4562 		reloc_desc->insn_idx = insn_idx;
4563 		reloc_desc->sym_off = sym->st_value;
4564 		return 0;
4565 	}
4566 
4567 	type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
4568 	sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4569 
4570 	/* arena data relocation */
4571 	if (shdr_idx == obj->efile.arena_data_shndx) {
4572 		reloc_desc->type = RELO_DATA;
4573 		reloc_desc->insn_idx = insn_idx;
4574 		reloc_desc->map_idx = obj->arena_map - obj->maps;
4575 		reloc_desc->sym_off = sym->st_value;
4576 		return 0;
4577 	}
4578 
4579 	/* generic map reference relocation */
4580 	if (type == LIBBPF_MAP_UNSPEC) {
4581 		if (!bpf_object__shndx_is_maps(obj, shdr_idx)) {
4582 			pr_warn("prog '%s': bad map relo against '%s' in section '%s'\n",
4583 				prog->name, sym_name, sym_sec_name);
4584 			return -LIBBPF_ERRNO__RELOC;
4585 		}
4586 		for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4587 			map = &obj->maps[map_idx];
4588 			if (map->libbpf_type != type ||
4589 			    map->sec_idx != sym->st_shndx ||
4590 			    map->sec_offset != sym->st_value)
4591 				continue;
4592 			pr_debug("prog '%s': found map %zd (%s, sec %d, off %zu) for insn #%u\n",
4593 				 prog->name, map_idx, map->name, map->sec_idx,
4594 				 map->sec_offset, insn_idx);
4595 			break;
4596 		}
4597 		if (map_idx >= nr_maps) {
4598 			pr_warn("prog '%s': map relo failed to find map for section '%s', off %zu\n",
4599 				prog->name, sym_sec_name, (size_t)sym->st_value);
4600 			return -LIBBPF_ERRNO__RELOC;
4601 		}
4602 		reloc_desc->type = RELO_LD64;
4603 		reloc_desc->insn_idx = insn_idx;
4604 		reloc_desc->map_idx = map_idx;
4605 		reloc_desc->sym_off = 0; /* sym->st_value determines map_idx */
4606 		return 0;
4607 	}
4608 
4609 	/* global data map relocation */
4610 	if (!bpf_object__shndx_is_data(obj, shdr_idx)) {
4611 		pr_warn("prog '%s': bad data relo against section '%s'\n",
4612 			prog->name, sym_sec_name);
4613 		return -LIBBPF_ERRNO__RELOC;
4614 	}
4615 	for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4616 		map = &obj->maps[map_idx];
4617 		if (map->libbpf_type != type || map->sec_idx != sym->st_shndx)
4618 			continue;
4619 		pr_debug("prog '%s': found data map %zd (%s, sec %d, off %zu) for insn %u\n",
4620 			 prog->name, map_idx, map->name, map->sec_idx,
4621 			 map->sec_offset, insn_idx);
4622 		break;
4623 	}
4624 	if (map_idx >= nr_maps) {
4625 		pr_warn("prog '%s': data relo failed to find map for section '%s'\n",
4626 			prog->name, sym_sec_name);
4627 		return -LIBBPF_ERRNO__RELOC;
4628 	}
4629 
4630 	reloc_desc->type = RELO_DATA;
4631 	reloc_desc->insn_idx = insn_idx;
4632 	reloc_desc->map_idx = map_idx;
4633 	reloc_desc->sym_off = sym->st_value;
4634 	return 0;
4635 }
4636 
4637 static bool prog_contains_insn(const struct bpf_program *prog, size_t insn_idx)
4638 {
4639 	return insn_idx >= prog->sec_insn_off &&
4640 	       insn_idx < prog->sec_insn_off + prog->sec_insn_cnt;
4641 }
4642 
4643 static struct bpf_program *find_prog_by_sec_insn(const struct bpf_object *obj,
4644 						 size_t sec_idx, size_t insn_idx)
4645 {
4646 	int l = 0, r = obj->nr_programs - 1, m;
4647 	struct bpf_program *prog;
4648 
4649 	if (!obj->nr_programs)
4650 		return NULL;
4651 
4652 	while (l < r) {
4653 		m = l + (r - l + 1) / 2;
4654 		prog = &obj->programs[m];
4655 
4656 		if (prog->sec_idx < sec_idx ||
4657 		    (prog->sec_idx == sec_idx && prog->sec_insn_off <= insn_idx))
4658 			l = m;
4659 		else
4660 			r = m - 1;
4661 	}
4662 	/* matching program could be at index l, but it still might be the
4663 	 * wrong one, so we need to double check conditions for the last time
4664 	 */
4665 	prog = &obj->programs[l];
4666 	if (prog->sec_idx == sec_idx && prog_contains_insn(prog, insn_idx))
4667 		return prog;
4668 	return NULL;
4669 }
4670 
4671 static int
4672 bpf_object__collect_prog_relos(struct bpf_object *obj, Elf64_Shdr *shdr, Elf_Data *data)
4673 {
4674 	const char *relo_sec_name, *sec_name;
4675 	size_t sec_idx = shdr->sh_info, sym_idx;
4676 	struct bpf_program *prog;
4677 	struct reloc_desc *relos;
4678 	int err, i, nrels;
4679 	const char *sym_name;
4680 	__u32 insn_idx;
4681 	Elf_Scn *scn;
4682 	Elf_Data *scn_data;
4683 	Elf64_Sym *sym;
4684 	Elf64_Rel *rel;
4685 
4686 	if (sec_idx >= obj->efile.sec_cnt)
4687 		return -EINVAL;
4688 
4689 	scn = elf_sec_by_idx(obj, sec_idx);
4690 	scn_data = elf_sec_data(obj, scn);
4691 	if (!scn_data)
4692 		return -LIBBPF_ERRNO__FORMAT;
4693 
4694 	relo_sec_name = elf_sec_str(obj, shdr->sh_name);
4695 	sec_name = elf_sec_name(obj, scn);
4696 	if (!relo_sec_name || !sec_name)
4697 		return -EINVAL;
4698 
4699 	pr_debug("sec '%s': collecting relocation for section(%zu) '%s'\n",
4700 		 relo_sec_name, sec_idx, sec_name);
4701 	nrels = shdr->sh_size / shdr->sh_entsize;
4702 
4703 	for (i = 0; i < nrels; i++) {
4704 		rel = elf_rel_by_idx(data, i);
4705 		if (!rel) {
4706 			pr_warn("sec '%s': failed to get relo #%d\n", relo_sec_name, i);
4707 			return -LIBBPF_ERRNO__FORMAT;
4708 		}
4709 
4710 		sym_idx = ELF64_R_SYM(rel->r_info);
4711 		sym = elf_sym_by_idx(obj, sym_idx);
4712 		if (!sym) {
4713 			pr_warn("sec '%s': symbol #%zu not found for relo #%d\n",
4714 				relo_sec_name, sym_idx, i);
4715 			return -LIBBPF_ERRNO__FORMAT;
4716 		}
4717 
4718 		if (sym->st_shndx >= obj->efile.sec_cnt) {
4719 			pr_warn("sec '%s': corrupted symbol #%zu pointing to invalid section #%zu for relo #%d\n",
4720 				relo_sec_name, sym_idx, (size_t)sym->st_shndx, i);
4721 			return -LIBBPF_ERRNO__FORMAT;
4722 		}
4723 
4724 		if (rel->r_offset % BPF_INSN_SZ || rel->r_offset >= scn_data->d_size) {
4725 			pr_warn("sec '%s': invalid offset 0x%zx for relo #%d\n",
4726 				relo_sec_name, (size_t)rel->r_offset, i);
4727 			return -LIBBPF_ERRNO__FORMAT;
4728 		}
4729 
4730 		insn_idx = rel->r_offset / BPF_INSN_SZ;
4731 		/* relocations against static functions are recorded as
4732 		 * relocations against the section that contains a function;
4733 		 * in such case, symbol will be STT_SECTION and sym.st_name
4734 		 * will point to empty string (0), so fetch section name
4735 		 * instead
4736 		 */
4737 		if (ELF64_ST_TYPE(sym->st_info) == STT_SECTION && sym->st_name == 0)
4738 			sym_name = elf_sec_name(obj, elf_sec_by_idx(obj, sym->st_shndx));
4739 		else
4740 			sym_name = elf_sym_str(obj, sym->st_name);
4741 		sym_name = sym_name ?: "<?";
4742 
4743 		pr_debug("sec '%s': relo #%d: insn #%u against '%s'\n",
4744 			 relo_sec_name, i, insn_idx, sym_name);
4745 
4746 		prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
4747 		if (!prog) {
4748 			pr_debug("sec '%s': relo #%d: couldn't find program in section '%s' for insn #%u, probably overridden weak function, skipping...\n",
4749 				relo_sec_name, i, sec_name, insn_idx);
4750 			continue;
4751 		}
4752 
4753 		relos = libbpf_reallocarray(prog->reloc_desc,
4754 					    prog->nr_reloc + 1, sizeof(*relos));
4755 		if (!relos)
4756 			return -ENOMEM;
4757 		prog->reloc_desc = relos;
4758 
4759 		/* adjust insn_idx to local BPF program frame of reference */
4760 		insn_idx -= prog->sec_insn_off;
4761 		err = bpf_program__record_reloc(prog, &relos[prog->nr_reloc],
4762 						insn_idx, sym_name, sym, rel);
4763 		if (err)
4764 			return err;
4765 
4766 		prog->nr_reloc++;
4767 	}
4768 	return 0;
4769 }
4770 
4771 static int map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map)
4772 {
4773 	int id;
4774 
4775 	if (!obj->btf)
4776 		return -ENOENT;
4777 
4778 	/* if it's BTF-defined map, we don't need to search for type IDs.
4779 	 * For struct_ops map, it does not need btf_key_type_id and
4780 	 * btf_value_type_id.
4781 	 */
4782 	if (map->sec_idx == obj->efile.btf_maps_shndx || bpf_map__is_struct_ops(map))
4783 		return 0;
4784 
4785 	/*
4786 	 * LLVM annotates global data differently in BTF, that is,
4787 	 * only as '.data', '.bss' or '.rodata'.
4788 	 */
4789 	if (!bpf_map__is_internal(map))
4790 		return -ENOENT;
4791 
4792 	id = btf__find_by_name(obj->btf, map->real_name);
4793 	if (id < 0)
4794 		return id;
4795 
4796 	map->btf_key_type_id = 0;
4797 	map->btf_value_type_id = id;
4798 	return 0;
4799 }
4800 
4801 static int bpf_get_map_info_from_fdinfo(int fd, struct bpf_map_info *info)
4802 {
4803 	char file[PATH_MAX], buff[4096];
4804 	FILE *fp;
4805 	__u32 val;
4806 	int err;
4807 
4808 	snprintf(file, sizeof(file), "/proc/%d/fdinfo/%d", getpid(), fd);
4809 	memset(info, 0, sizeof(*info));
4810 
4811 	fp = fopen(file, "re");
4812 	if (!fp) {
4813 		err = -errno;
4814 		pr_warn("failed to open %s: %d. No procfs support?\n", file,
4815 			err);
4816 		return err;
4817 	}
4818 
4819 	while (fgets(buff, sizeof(buff), fp)) {
4820 		if (sscanf(buff, "map_type:\t%u", &val) == 1)
4821 			info->type = val;
4822 		else if (sscanf(buff, "key_size:\t%u", &val) == 1)
4823 			info->key_size = val;
4824 		else if (sscanf(buff, "value_size:\t%u", &val) == 1)
4825 			info->value_size = val;
4826 		else if (sscanf(buff, "max_entries:\t%u", &val) == 1)
4827 			info->max_entries = val;
4828 		else if (sscanf(buff, "map_flags:\t%i", &val) == 1)
4829 			info->map_flags = val;
4830 	}
4831 
4832 	fclose(fp);
4833 
4834 	return 0;
4835 }
4836 
4837 bool bpf_map__autocreate(const struct bpf_map *map)
4838 {
4839 	return map->autocreate;
4840 }
4841 
4842 int bpf_map__set_autocreate(struct bpf_map *map, bool autocreate)
4843 {
4844 	if (map->obj->loaded)
4845 		return libbpf_err(-EBUSY);
4846 
4847 	map->autocreate = autocreate;
4848 	return 0;
4849 }
4850 
4851 int bpf_map__set_autoattach(struct bpf_map *map, bool autoattach)
4852 {
4853 	if (!bpf_map__is_struct_ops(map))
4854 		return libbpf_err(-EINVAL);
4855 
4856 	map->autoattach = autoattach;
4857 	return 0;
4858 }
4859 
4860 bool bpf_map__autoattach(const struct bpf_map *map)
4861 {
4862 	return map->autoattach;
4863 }
4864 
4865 int bpf_map__reuse_fd(struct bpf_map *map, int fd)
4866 {
4867 	struct bpf_map_info info;
4868 	__u32 len = sizeof(info), name_len;
4869 	int new_fd, err;
4870 	char *new_name;
4871 
4872 	memset(&info, 0, len);
4873 	err = bpf_map_get_info_by_fd(fd, &info, &len);
4874 	if (err && errno == EINVAL)
4875 		err = bpf_get_map_info_from_fdinfo(fd, &info);
4876 	if (err)
4877 		return libbpf_err(err);
4878 
4879 	name_len = strlen(info.name);
4880 	if (name_len == BPF_OBJ_NAME_LEN - 1 && strncmp(map->name, info.name, name_len) == 0)
4881 		new_name = strdup(map->name);
4882 	else
4883 		new_name = strdup(info.name);
4884 
4885 	if (!new_name)
4886 		return libbpf_err(-errno);
4887 
4888 	/*
4889 	 * Like dup(), but make sure new FD is >= 3 and has O_CLOEXEC set.
4890 	 * This is similar to what we do in ensure_good_fd(), but without
4891 	 * closing original FD.
4892 	 */
4893 	new_fd = fcntl(fd, F_DUPFD_CLOEXEC, 3);
4894 	if (new_fd < 0) {
4895 		err = -errno;
4896 		goto err_free_new_name;
4897 	}
4898 
4899 	err = reuse_fd(map->fd, new_fd);
4900 	if (err)
4901 		goto err_free_new_name;
4902 
4903 	free(map->name);
4904 
4905 	map->name = new_name;
4906 	map->def.type = info.type;
4907 	map->def.key_size = info.key_size;
4908 	map->def.value_size = info.value_size;
4909 	map->def.max_entries = info.max_entries;
4910 	map->def.map_flags = info.map_flags;
4911 	map->btf_key_type_id = info.btf_key_type_id;
4912 	map->btf_value_type_id = info.btf_value_type_id;
4913 	map->reused = true;
4914 	map->map_extra = info.map_extra;
4915 
4916 	return 0;
4917 
4918 err_free_new_name:
4919 	free(new_name);
4920 	return libbpf_err(err);
4921 }
4922 
4923 __u32 bpf_map__max_entries(const struct bpf_map *map)
4924 {
4925 	return map->def.max_entries;
4926 }
4927 
4928 struct bpf_map *bpf_map__inner_map(struct bpf_map *map)
4929 {
4930 	if (!bpf_map_type__is_map_in_map(map->def.type))
4931 		return errno = EINVAL, NULL;
4932 
4933 	return map->inner_map;
4934 }
4935 
4936 int bpf_map__set_max_entries(struct bpf_map *map, __u32 max_entries)
4937 {
4938 	if (map->obj->loaded)
4939 		return libbpf_err(-EBUSY);
4940 
4941 	map->def.max_entries = max_entries;
4942 
4943 	/* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
4944 	if (map_is_ringbuf(map))
4945 		map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
4946 
4947 	return 0;
4948 }
4949 
4950 static int bpf_object_prepare_token(struct bpf_object *obj)
4951 {
4952 	const char *bpffs_path;
4953 	int bpffs_fd = -1, token_fd, err;
4954 	bool mandatory;
4955 	enum libbpf_print_level level;
4956 
4957 	/* token is explicitly prevented */
4958 	if (obj->token_path && obj->token_path[0] == '\0') {
4959 		pr_debug("object '%s': token is prevented, skipping...\n", obj->name);
4960 		return 0;
4961 	}
4962 
4963 	mandatory = obj->token_path != NULL;
4964 	level = mandatory ? LIBBPF_WARN : LIBBPF_DEBUG;
4965 
4966 	bpffs_path = obj->token_path ?: BPF_FS_DEFAULT_PATH;
4967 	bpffs_fd = open(bpffs_path, O_DIRECTORY, O_RDWR);
4968 	if (bpffs_fd < 0) {
4969 		err = -errno;
4970 		__pr(level, "object '%s': failed (%d) to open BPF FS mount at '%s'%s\n",
4971 		     obj->name, err, bpffs_path,
4972 		     mandatory ? "" : ", skipping optional step...");
4973 		return mandatory ? err : 0;
4974 	}
4975 
4976 	token_fd = bpf_token_create(bpffs_fd, 0);
4977 	close(bpffs_fd);
4978 	if (token_fd < 0) {
4979 		if (!mandatory && token_fd == -ENOENT) {
4980 			pr_debug("object '%s': BPF FS at '%s' doesn't have BPF token delegation set up, skipping...\n",
4981 				 obj->name, bpffs_path);
4982 			return 0;
4983 		}
4984 		__pr(level, "object '%s': failed (%d) to create BPF token from '%s'%s\n",
4985 		     obj->name, token_fd, bpffs_path,
4986 		     mandatory ? "" : ", skipping optional step...");
4987 		return mandatory ? token_fd : 0;
4988 	}
4989 
4990 	obj->feat_cache = calloc(1, sizeof(*obj->feat_cache));
4991 	if (!obj->feat_cache) {
4992 		close(token_fd);
4993 		return -ENOMEM;
4994 	}
4995 
4996 	obj->token_fd = token_fd;
4997 	obj->feat_cache->token_fd = token_fd;
4998 
4999 	return 0;
5000 }
5001 
5002 static int
5003 bpf_object__probe_loading(struct bpf_object *obj)
5004 {
5005 	char *cp, errmsg[STRERR_BUFSIZE];
5006 	struct bpf_insn insns[] = {
5007 		BPF_MOV64_IMM(BPF_REG_0, 0),
5008 		BPF_EXIT_INSN(),
5009 	};
5010 	int ret, insn_cnt = ARRAY_SIZE(insns);
5011 	LIBBPF_OPTS(bpf_prog_load_opts, opts,
5012 		.token_fd = obj->token_fd,
5013 		.prog_flags = obj->token_fd ? BPF_F_TOKEN_FD : 0,
5014 	);
5015 
5016 	if (obj->gen_loader)
5017 		return 0;
5018 
5019 	ret = bump_rlimit_memlock();
5020 	if (ret)
5021 		pr_warn("Failed to bump RLIMIT_MEMLOCK (err = %d), you might need to do it explicitly!\n", ret);
5022 
5023 	/* make sure basic loading works */
5024 	ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, &opts);
5025 	if (ret < 0)
5026 		ret = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, &opts);
5027 	if (ret < 0) {
5028 		ret = errno;
5029 		cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
5030 		pr_warn("Error in %s():%s(%d). Couldn't load trivial BPF "
5031 			"program. Make sure your kernel supports BPF "
5032 			"(CONFIG_BPF_SYSCALL=y) and/or that RLIMIT_MEMLOCK is "
5033 			"set to big enough value.\n", __func__, cp, ret);
5034 		return -ret;
5035 	}
5036 	close(ret);
5037 
5038 	return 0;
5039 }
5040 
5041 bool kernel_supports(const struct bpf_object *obj, enum kern_feature_id feat_id)
5042 {
5043 	if (obj->gen_loader)
5044 		/* To generate loader program assume the latest kernel
5045 		 * to avoid doing extra prog_load, map_create syscalls.
5046 		 */
5047 		return true;
5048 
5049 	if (obj->token_fd)
5050 		return feat_supported(obj->feat_cache, feat_id);
5051 
5052 	return feat_supported(NULL, feat_id);
5053 }
5054 
5055 static bool map_is_reuse_compat(const struct bpf_map *map, int map_fd)
5056 {
5057 	struct bpf_map_info map_info;
5058 	char msg[STRERR_BUFSIZE];
5059 	__u32 map_info_len = sizeof(map_info);
5060 	int err;
5061 
5062 	memset(&map_info, 0, map_info_len);
5063 	err = bpf_map_get_info_by_fd(map_fd, &map_info, &map_info_len);
5064 	if (err && errno == EINVAL)
5065 		err = bpf_get_map_info_from_fdinfo(map_fd, &map_info);
5066 	if (err) {
5067 		pr_warn("failed to get map info for map FD %d: %s\n", map_fd,
5068 			libbpf_strerror_r(errno, msg, sizeof(msg)));
5069 		return false;
5070 	}
5071 
5072 	return (map_info.type == map->def.type &&
5073 		map_info.key_size == map->def.key_size &&
5074 		map_info.value_size == map->def.value_size &&
5075 		map_info.max_entries == map->def.max_entries &&
5076 		map_info.map_flags == map->def.map_flags &&
5077 		map_info.map_extra == map->map_extra);
5078 }
5079 
5080 static int
5081 bpf_object__reuse_map(struct bpf_map *map)
5082 {
5083 	char *cp, errmsg[STRERR_BUFSIZE];
5084 	int err, pin_fd;
5085 
5086 	pin_fd = bpf_obj_get(map->pin_path);
5087 	if (pin_fd < 0) {
5088 		err = -errno;
5089 		if (err == -ENOENT) {
5090 			pr_debug("found no pinned map to reuse at '%s'\n",
5091 				 map->pin_path);
5092 			return 0;
5093 		}
5094 
5095 		cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
5096 		pr_warn("couldn't retrieve pinned map '%s': %s\n",
5097 			map->pin_path, cp);
5098 		return err;
5099 	}
5100 
5101 	if (!map_is_reuse_compat(map, pin_fd)) {
5102 		pr_warn("couldn't reuse pinned map at '%s': parameter mismatch\n",
5103 			map->pin_path);
5104 		close(pin_fd);
5105 		return -EINVAL;
5106 	}
5107 
5108 	err = bpf_map__reuse_fd(map, pin_fd);
5109 	close(pin_fd);
5110 	if (err)
5111 		return err;
5112 
5113 	map->pinned = true;
5114 	pr_debug("reused pinned map at '%s'\n", map->pin_path);
5115 
5116 	return 0;
5117 }
5118 
5119 static int
5120 bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
5121 {
5122 	enum libbpf_map_type map_type = map->libbpf_type;
5123 	char *cp, errmsg[STRERR_BUFSIZE];
5124 	int err, zero = 0;
5125 
5126 	if (obj->gen_loader) {
5127 		bpf_gen__map_update_elem(obj->gen_loader, map - obj->maps,
5128 					 map->mmaped, map->def.value_size);
5129 		if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG)
5130 			bpf_gen__map_freeze(obj->gen_loader, map - obj->maps);
5131 		return 0;
5132 	}
5133 
5134 	err = bpf_map_update_elem(map->fd, &zero, map->mmaped, 0);
5135 	if (err) {
5136 		err = -errno;
5137 		cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5138 		pr_warn("Error setting initial map(%s) contents: %s\n",
5139 			map->name, cp);
5140 		return err;
5141 	}
5142 
5143 	/* Freeze .rodata and .kconfig map as read-only from syscall side. */
5144 	if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG) {
5145 		err = bpf_map_freeze(map->fd);
5146 		if (err) {
5147 			err = -errno;
5148 			cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5149 			pr_warn("Error freezing map(%s) as read-only: %s\n",
5150 				map->name, cp);
5151 			return err;
5152 		}
5153 	}
5154 	return 0;
5155 }
5156 
5157 static void bpf_map__destroy(struct bpf_map *map);
5158 
5159 static bool map_is_created(const struct bpf_map *map)
5160 {
5161 	return map->obj->loaded || map->reused;
5162 }
5163 
5164 static int bpf_object__create_map(struct bpf_object *obj, struct bpf_map *map, bool is_inner)
5165 {
5166 	LIBBPF_OPTS(bpf_map_create_opts, create_attr);
5167 	struct bpf_map_def *def = &map->def;
5168 	const char *map_name = NULL;
5169 	int err = 0, map_fd;
5170 
5171 	if (kernel_supports(obj, FEAT_PROG_NAME))
5172 		map_name = map->name;
5173 	create_attr.map_ifindex = map->map_ifindex;
5174 	create_attr.map_flags = def->map_flags;
5175 	create_attr.numa_node = map->numa_node;
5176 	create_attr.map_extra = map->map_extra;
5177 	create_attr.token_fd = obj->token_fd;
5178 	if (obj->token_fd)
5179 		create_attr.map_flags |= BPF_F_TOKEN_FD;
5180 
5181 	if (bpf_map__is_struct_ops(map)) {
5182 		create_attr.btf_vmlinux_value_type_id = map->btf_vmlinux_value_type_id;
5183 		if (map->mod_btf_fd >= 0) {
5184 			create_attr.value_type_btf_obj_fd = map->mod_btf_fd;
5185 			create_attr.map_flags |= BPF_F_VTYPE_BTF_OBJ_FD;
5186 		}
5187 	}
5188 
5189 	if (obj->btf && btf__fd(obj->btf) >= 0) {
5190 		create_attr.btf_fd = btf__fd(obj->btf);
5191 		create_attr.btf_key_type_id = map->btf_key_type_id;
5192 		create_attr.btf_value_type_id = map->btf_value_type_id;
5193 	}
5194 
5195 	if (bpf_map_type__is_map_in_map(def->type)) {
5196 		if (map->inner_map) {
5197 			err = map_set_def_max_entries(map->inner_map);
5198 			if (err)
5199 				return err;
5200 			err = bpf_object__create_map(obj, map->inner_map, true);
5201 			if (err) {
5202 				pr_warn("map '%s': failed to create inner map: %d\n",
5203 					map->name, err);
5204 				return err;
5205 			}
5206 			map->inner_map_fd = map->inner_map->fd;
5207 		}
5208 		if (map->inner_map_fd >= 0)
5209 			create_attr.inner_map_fd = map->inner_map_fd;
5210 	}
5211 
5212 	switch (def->type) {
5213 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
5214 	case BPF_MAP_TYPE_CGROUP_ARRAY:
5215 	case BPF_MAP_TYPE_STACK_TRACE:
5216 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
5217 	case BPF_MAP_TYPE_HASH_OF_MAPS:
5218 	case BPF_MAP_TYPE_DEVMAP:
5219 	case BPF_MAP_TYPE_DEVMAP_HASH:
5220 	case BPF_MAP_TYPE_CPUMAP:
5221 	case BPF_MAP_TYPE_XSKMAP:
5222 	case BPF_MAP_TYPE_SOCKMAP:
5223 	case BPF_MAP_TYPE_SOCKHASH:
5224 	case BPF_MAP_TYPE_QUEUE:
5225 	case BPF_MAP_TYPE_STACK:
5226 	case BPF_MAP_TYPE_ARENA:
5227 		create_attr.btf_fd = 0;
5228 		create_attr.btf_key_type_id = 0;
5229 		create_attr.btf_value_type_id = 0;
5230 		map->btf_key_type_id = 0;
5231 		map->btf_value_type_id = 0;
5232 		break;
5233 	case BPF_MAP_TYPE_STRUCT_OPS:
5234 		create_attr.btf_value_type_id = 0;
5235 		break;
5236 	default:
5237 		break;
5238 	}
5239 
5240 	if (obj->gen_loader) {
5241 		bpf_gen__map_create(obj->gen_loader, def->type, map_name,
5242 				    def->key_size, def->value_size, def->max_entries,
5243 				    &create_attr, is_inner ? -1 : map - obj->maps);
5244 		/* We keep pretenting we have valid FD to pass various fd >= 0
5245 		 * checks by just keeping original placeholder FDs in place.
5246 		 * See bpf_object__add_map() comment.
5247 		 * This placeholder fd will not be used with any syscall and
5248 		 * will be reset to -1 eventually.
5249 		 */
5250 		map_fd = map->fd;
5251 	} else {
5252 		map_fd = bpf_map_create(def->type, map_name,
5253 					def->key_size, def->value_size,
5254 					def->max_entries, &create_attr);
5255 	}
5256 	if (map_fd < 0 && (create_attr.btf_key_type_id || create_attr.btf_value_type_id)) {
5257 		char *cp, errmsg[STRERR_BUFSIZE];
5258 
5259 		err = -errno;
5260 		cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5261 		pr_warn("Error in bpf_create_map_xattr(%s):%s(%d). Retrying without BTF.\n",
5262 			map->name, cp, err);
5263 		create_attr.btf_fd = 0;
5264 		create_attr.btf_key_type_id = 0;
5265 		create_attr.btf_value_type_id = 0;
5266 		map->btf_key_type_id = 0;
5267 		map->btf_value_type_id = 0;
5268 		map_fd = bpf_map_create(def->type, map_name,
5269 					def->key_size, def->value_size,
5270 					def->max_entries, &create_attr);
5271 	}
5272 
5273 	if (bpf_map_type__is_map_in_map(def->type) && map->inner_map) {
5274 		if (obj->gen_loader)
5275 			map->inner_map->fd = -1;
5276 		bpf_map__destroy(map->inner_map);
5277 		zfree(&map->inner_map);
5278 	}
5279 
5280 	if (map_fd < 0)
5281 		return map_fd;
5282 
5283 	/* obj->gen_loader case, prevent reuse_fd() from closing map_fd */
5284 	if (map->fd == map_fd)
5285 		return 0;
5286 
5287 	/* Keep placeholder FD value but now point it to the BPF map object.
5288 	 * This way everything that relied on this map's FD (e.g., relocated
5289 	 * ldimm64 instructions) will stay valid and won't need adjustments.
5290 	 * map->fd stays valid but now point to what map_fd points to.
5291 	 */
5292 	return reuse_fd(map->fd, map_fd);
5293 }
5294 
5295 static int init_map_in_map_slots(struct bpf_object *obj, struct bpf_map *map)
5296 {
5297 	const struct bpf_map *targ_map;
5298 	unsigned int i;
5299 	int fd, err = 0;
5300 
5301 	for (i = 0; i < map->init_slots_sz; i++) {
5302 		if (!map->init_slots[i])
5303 			continue;
5304 
5305 		targ_map = map->init_slots[i];
5306 		fd = targ_map->fd;
5307 
5308 		if (obj->gen_loader) {
5309 			bpf_gen__populate_outer_map(obj->gen_loader,
5310 						    map - obj->maps, i,
5311 						    targ_map - obj->maps);
5312 		} else {
5313 			err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5314 		}
5315 		if (err) {
5316 			err = -errno;
5317 			pr_warn("map '%s': failed to initialize slot [%d] to map '%s' fd=%d: %d\n",
5318 				map->name, i, targ_map->name, fd, err);
5319 			return err;
5320 		}
5321 		pr_debug("map '%s': slot [%d] set to map '%s' fd=%d\n",
5322 			 map->name, i, targ_map->name, fd);
5323 	}
5324 
5325 	zfree(&map->init_slots);
5326 	map->init_slots_sz = 0;
5327 
5328 	return 0;
5329 }
5330 
5331 static int init_prog_array_slots(struct bpf_object *obj, struct bpf_map *map)
5332 {
5333 	const struct bpf_program *targ_prog;
5334 	unsigned int i;
5335 	int fd, err;
5336 
5337 	if (obj->gen_loader)
5338 		return -ENOTSUP;
5339 
5340 	for (i = 0; i < map->init_slots_sz; i++) {
5341 		if (!map->init_slots[i])
5342 			continue;
5343 
5344 		targ_prog = map->init_slots[i];
5345 		fd = bpf_program__fd(targ_prog);
5346 
5347 		err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5348 		if (err) {
5349 			err = -errno;
5350 			pr_warn("map '%s': failed to initialize slot [%d] to prog '%s' fd=%d: %d\n",
5351 				map->name, i, targ_prog->name, fd, err);
5352 			return err;
5353 		}
5354 		pr_debug("map '%s': slot [%d] set to prog '%s' fd=%d\n",
5355 			 map->name, i, targ_prog->name, fd);
5356 	}
5357 
5358 	zfree(&map->init_slots);
5359 	map->init_slots_sz = 0;
5360 
5361 	return 0;
5362 }
5363 
5364 static int bpf_object_init_prog_arrays(struct bpf_object *obj)
5365 {
5366 	struct bpf_map *map;
5367 	int i, err;
5368 
5369 	for (i = 0; i < obj->nr_maps; i++) {
5370 		map = &obj->maps[i];
5371 
5372 		if (!map->init_slots_sz || map->def.type != BPF_MAP_TYPE_PROG_ARRAY)
5373 			continue;
5374 
5375 		err = init_prog_array_slots(obj, map);
5376 		if (err < 0)
5377 			return err;
5378 	}
5379 	return 0;
5380 }
5381 
5382 static int map_set_def_max_entries(struct bpf_map *map)
5383 {
5384 	if (map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY && !map->def.max_entries) {
5385 		int nr_cpus;
5386 
5387 		nr_cpus = libbpf_num_possible_cpus();
5388 		if (nr_cpus < 0) {
5389 			pr_warn("map '%s': failed to determine number of system CPUs: %d\n",
5390 				map->name, nr_cpus);
5391 			return nr_cpus;
5392 		}
5393 		pr_debug("map '%s': setting size to %d\n", map->name, nr_cpus);
5394 		map->def.max_entries = nr_cpus;
5395 	}
5396 
5397 	return 0;
5398 }
5399 
5400 static int
5401 bpf_object__create_maps(struct bpf_object *obj)
5402 {
5403 	struct bpf_map *map;
5404 	char *cp, errmsg[STRERR_BUFSIZE];
5405 	unsigned int i, j;
5406 	int err;
5407 	bool retried;
5408 
5409 	for (i = 0; i < obj->nr_maps; i++) {
5410 		map = &obj->maps[i];
5411 
5412 		/* To support old kernels, we skip creating global data maps
5413 		 * (.rodata, .data, .kconfig, etc); later on, during program
5414 		 * loading, if we detect that at least one of the to-be-loaded
5415 		 * programs is referencing any global data map, we'll error
5416 		 * out with program name and relocation index logged.
5417 		 * This approach allows to accommodate Clang emitting
5418 		 * unnecessary .rodata.str1.1 sections for string literals,
5419 		 * but also it allows to have CO-RE applications that use
5420 		 * global variables in some of BPF programs, but not others.
5421 		 * If those global variable-using programs are not loaded at
5422 		 * runtime due to bpf_program__set_autoload(prog, false),
5423 		 * bpf_object loading will succeed just fine even on old
5424 		 * kernels.
5425 		 */
5426 		if (bpf_map__is_internal(map) && !kernel_supports(obj, FEAT_GLOBAL_DATA))
5427 			map->autocreate = false;
5428 
5429 		if (!map->autocreate) {
5430 			pr_debug("map '%s': skipped auto-creating...\n", map->name);
5431 			continue;
5432 		}
5433 
5434 		err = map_set_def_max_entries(map);
5435 		if (err)
5436 			goto err_out;
5437 
5438 		retried = false;
5439 retry:
5440 		if (map->pin_path) {
5441 			err = bpf_object__reuse_map(map);
5442 			if (err) {
5443 				pr_warn("map '%s': error reusing pinned map\n",
5444 					map->name);
5445 				goto err_out;
5446 			}
5447 			if (retried && map->fd < 0) {
5448 				pr_warn("map '%s': cannot find pinned map\n",
5449 					map->name);
5450 				err = -ENOENT;
5451 				goto err_out;
5452 			}
5453 		}
5454 
5455 		if (map->reused) {
5456 			pr_debug("map '%s': skipping creation (preset fd=%d)\n",
5457 				 map->name, map->fd);
5458 		} else {
5459 			err = bpf_object__create_map(obj, map, false);
5460 			if (err)
5461 				goto err_out;
5462 
5463 			pr_debug("map '%s': created successfully, fd=%d\n",
5464 				 map->name, map->fd);
5465 
5466 			if (bpf_map__is_internal(map)) {
5467 				err = bpf_object__populate_internal_map(obj, map);
5468 				if (err < 0)
5469 					goto err_out;
5470 			}
5471 			if (map->def.type == BPF_MAP_TYPE_ARENA) {
5472 				map->mmaped = mmap((void *)(long)map->map_extra,
5473 						   bpf_map_mmap_sz(map), PROT_READ | PROT_WRITE,
5474 						   map->map_extra ? MAP_SHARED | MAP_FIXED : MAP_SHARED,
5475 						   map->fd, 0);
5476 				if (map->mmaped == MAP_FAILED) {
5477 					err = -errno;
5478 					map->mmaped = NULL;
5479 					pr_warn("map '%s': failed to mmap arena: %d\n",
5480 						map->name, err);
5481 					return err;
5482 				}
5483 				if (obj->arena_data) {
5484 					memcpy(map->mmaped, obj->arena_data, obj->arena_data_sz);
5485 					zfree(&obj->arena_data);
5486 				}
5487 			}
5488 			if (map->init_slots_sz && map->def.type != BPF_MAP_TYPE_PROG_ARRAY) {
5489 				err = init_map_in_map_slots(obj, map);
5490 				if (err < 0)
5491 					goto err_out;
5492 			}
5493 		}
5494 
5495 		if (map->pin_path && !map->pinned) {
5496 			err = bpf_map__pin(map, NULL);
5497 			if (err) {
5498 				if (!retried && err == -EEXIST) {
5499 					retried = true;
5500 					goto retry;
5501 				}
5502 				pr_warn("map '%s': failed to auto-pin at '%s': %d\n",
5503 					map->name, map->pin_path, err);
5504 				goto err_out;
5505 			}
5506 		}
5507 	}
5508 
5509 	return 0;
5510 
5511 err_out:
5512 	cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5513 	pr_warn("map '%s': failed to create: %s(%d)\n", map->name, cp, err);
5514 	pr_perm_msg(err);
5515 	for (j = 0; j < i; j++)
5516 		zclose(obj->maps[j].fd);
5517 	return err;
5518 }
5519 
5520 static bool bpf_core_is_flavor_sep(const char *s)
5521 {
5522 	/* check X___Y name pattern, where X and Y are not underscores */
5523 	return s[0] != '_' &&				      /* X */
5524 	       s[1] == '_' && s[2] == '_' && s[3] == '_' &&   /* ___ */
5525 	       s[4] != '_';				      /* Y */
5526 }
5527 
5528 /* Given 'some_struct_name___with_flavor' return the length of a name prefix
5529  * before last triple underscore. Struct name part after last triple
5530  * underscore is ignored by BPF CO-RE relocation during relocation matching.
5531  */
5532 size_t bpf_core_essential_name_len(const char *name)
5533 {
5534 	size_t n = strlen(name);
5535 	int i;
5536 
5537 	for (i = n - 5; i >= 0; i--) {
5538 		if (bpf_core_is_flavor_sep(name + i))
5539 			return i + 1;
5540 	}
5541 	return n;
5542 }
5543 
5544 void bpf_core_free_cands(struct bpf_core_cand_list *cands)
5545 {
5546 	if (!cands)
5547 		return;
5548 
5549 	free(cands->cands);
5550 	free(cands);
5551 }
5552 
5553 int bpf_core_add_cands(struct bpf_core_cand *local_cand,
5554 		       size_t local_essent_len,
5555 		       const struct btf *targ_btf,
5556 		       const char *targ_btf_name,
5557 		       int targ_start_id,
5558 		       struct bpf_core_cand_list *cands)
5559 {
5560 	struct bpf_core_cand *new_cands, *cand;
5561 	const struct btf_type *t, *local_t;
5562 	const char *targ_name, *local_name;
5563 	size_t targ_essent_len;
5564 	int n, i;
5565 
5566 	local_t = btf__type_by_id(local_cand->btf, local_cand->id);
5567 	local_name = btf__str_by_offset(local_cand->btf, local_t->name_off);
5568 
5569 	n = btf__type_cnt(targ_btf);
5570 	for (i = targ_start_id; i < n; i++) {
5571 		t = btf__type_by_id(targ_btf, i);
5572 		if (!btf_kind_core_compat(t, local_t))
5573 			continue;
5574 
5575 		targ_name = btf__name_by_offset(targ_btf, t->name_off);
5576 		if (str_is_empty(targ_name))
5577 			continue;
5578 
5579 		targ_essent_len = bpf_core_essential_name_len(targ_name);
5580 		if (targ_essent_len != local_essent_len)
5581 			continue;
5582 
5583 		if (strncmp(local_name, targ_name, local_essent_len) != 0)
5584 			continue;
5585 
5586 		pr_debug("CO-RE relocating [%d] %s %s: found target candidate [%d] %s %s in [%s]\n",
5587 			 local_cand->id, btf_kind_str(local_t),
5588 			 local_name, i, btf_kind_str(t), targ_name,
5589 			 targ_btf_name);
5590 		new_cands = libbpf_reallocarray(cands->cands, cands->len + 1,
5591 					      sizeof(*cands->cands));
5592 		if (!new_cands)
5593 			return -ENOMEM;
5594 
5595 		cand = &new_cands[cands->len];
5596 		cand->btf = targ_btf;
5597 		cand->id = i;
5598 
5599 		cands->cands = new_cands;
5600 		cands->len++;
5601 	}
5602 	return 0;
5603 }
5604 
5605 static int load_module_btfs(struct bpf_object *obj)
5606 {
5607 	struct bpf_btf_info info;
5608 	struct module_btf *mod_btf;
5609 	struct btf *btf;
5610 	char name[64];
5611 	__u32 id = 0, len;
5612 	int err, fd;
5613 
5614 	if (obj->btf_modules_loaded)
5615 		return 0;
5616 
5617 	if (obj->gen_loader)
5618 		return 0;
5619 
5620 	/* don't do this again, even if we find no module BTFs */
5621 	obj->btf_modules_loaded = true;
5622 
5623 	/* kernel too old to support module BTFs */
5624 	if (!kernel_supports(obj, FEAT_MODULE_BTF))
5625 		return 0;
5626 
5627 	while (true) {
5628 		err = bpf_btf_get_next_id(id, &id);
5629 		if (err && errno == ENOENT)
5630 			return 0;
5631 		if (err && errno == EPERM) {
5632 			pr_debug("skipping module BTFs loading, missing privileges\n");
5633 			return 0;
5634 		}
5635 		if (err) {
5636 			err = -errno;
5637 			pr_warn("failed to iterate BTF objects: %d\n", err);
5638 			return err;
5639 		}
5640 
5641 		fd = bpf_btf_get_fd_by_id(id);
5642 		if (fd < 0) {
5643 			if (errno == ENOENT)
5644 				continue; /* expected race: BTF was unloaded */
5645 			err = -errno;
5646 			pr_warn("failed to get BTF object #%d FD: %d\n", id, err);
5647 			return err;
5648 		}
5649 
5650 		len = sizeof(info);
5651 		memset(&info, 0, sizeof(info));
5652 		info.name = ptr_to_u64(name);
5653 		info.name_len = sizeof(name);
5654 
5655 		err = bpf_btf_get_info_by_fd(fd, &info, &len);
5656 		if (err) {
5657 			err = -errno;
5658 			pr_warn("failed to get BTF object #%d info: %d\n", id, err);
5659 			goto err_out;
5660 		}
5661 
5662 		/* ignore non-module BTFs */
5663 		if (!info.kernel_btf || strcmp(name, "vmlinux") == 0) {
5664 			close(fd);
5665 			continue;
5666 		}
5667 
5668 		btf = btf_get_from_fd(fd, obj->btf_vmlinux);
5669 		err = libbpf_get_error(btf);
5670 		if (err) {
5671 			pr_warn("failed to load module [%s]'s BTF object #%d: %d\n",
5672 				name, id, err);
5673 			goto err_out;
5674 		}
5675 
5676 		err = libbpf_ensure_mem((void **)&obj->btf_modules, &obj->btf_module_cap,
5677 					sizeof(*obj->btf_modules), obj->btf_module_cnt + 1);
5678 		if (err)
5679 			goto err_out;
5680 
5681 		mod_btf = &obj->btf_modules[obj->btf_module_cnt++];
5682 
5683 		mod_btf->btf = btf;
5684 		mod_btf->id = id;
5685 		mod_btf->fd = fd;
5686 		mod_btf->name = strdup(name);
5687 		if (!mod_btf->name) {
5688 			err = -ENOMEM;
5689 			goto err_out;
5690 		}
5691 		continue;
5692 
5693 err_out:
5694 		close(fd);
5695 		return err;
5696 	}
5697 
5698 	return 0;
5699 }
5700 
5701 static struct bpf_core_cand_list *
5702 bpf_core_find_cands(struct bpf_object *obj, const struct btf *local_btf, __u32 local_type_id)
5703 {
5704 	struct bpf_core_cand local_cand = {};
5705 	struct bpf_core_cand_list *cands;
5706 	const struct btf *main_btf;
5707 	const struct btf_type *local_t;
5708 	const char *local_name;
5709 	size_t local_essent_len;
5710 	int err, i;
5711 
5712 	local_cand.btf = local_btf;
5713 	local_cand.id = local_type_id;
5714 	local_t = btf__type_by_id(local_btf, local_type_id);
5715 	if (!local_t)
5716 		return ERR_PTR(-EINVAL);
5717 
5718 	local_name = btf__name_by_offset(local_btf, local_t->name_off);
5719 	if (str_is_empty(local_name))
5720 		return ERR_PTR(-EINVAL);
5721 	local_essent_len = bpf_core_essential_name_len(local_name);
5722 
5723 	cands = calloc(1, sizeof(*cands));
5724 	if (!cands)
5725 		return ERR_PTR(-ENOMEM);
5726 
5727 	/* Attempt to find target candidates in vmlinux BTF first */
5728 	main_btf = obj->btf_vmlinux_override ?: obj->btf_vmlinux;
5729 	err = bpf_core_add_cands(&local_cand, local_essent_len, main_btf, "vmlinux", 1, cands);
5730 	if (err)
5731 		goto err_out;
5732 
5733 	/* if vmlinux BTF has any candidate, don't got for module BTFs */
5734 	if (cands->len)
5735 		return cands;
5736 
5737 	/* if vmlinux BTF was overridden, don't attempt to load module BTFs */
5738 	if (obj->btf_vmlinux_override)
5739 		return cands;
5740 
5741 	/* now look through module BTFs, trying to still find candidates */
5742 	err = load_module_btfs(obj);
5743 	if (err)
5744 		goto err_out;
5745 
5746 	for (i = 0; i < obj->btf_module_cnt; i++) {
5747 		err = bpf_core_add_cands(&local_cand, local_essent_len,
5748 					 obj->btf_modules[i].btf,
5749 					 obj->btf_modules[i].name,
5750 					 btf__type_cnt(obj->btf_vmlinux),
5751 					 cands);
5752 		if (err)
5753 			goto err_out;
5754 	}
5755 
5756 	return cands;
5757 err_out:
5758 	bpf_core_free_cands(cands);
5759 	return ERR_PTR(err);
5760 }
5761 
5762 /* Check local and target types for compatibility. This check is used for
5763  * type-based CO-RE relocations and follow slightly different rules than
5764  * field-based relocations. This function assumes that root types were already
5765  * checked for name match. Beyond that initial root-level name check, names
5766  * are completely ignored. Compatibility rules are as follows:
5767  *   - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs are considered compatible, but
5768  *     kind should match for local and target types (i.e., STRUCT is not
5769  *     compatible with UNION);
5770  *   - for ENUMs, the size is ignored;
5771  *   - for INT, size and signedness are ignored;
5772  *   - for ARRAY, dimensionality is ignored, element types are checked for
5773  *     compatibility recursively;
5774  *   - CONST/VOLATILE/RESTRICT modifiers are ignored;
5775  *   - TYPEDEFs/PTRs are compatible if types they pointing to are compatible;
5776  *   - FUNC_PROTOs are compatible if they have compatible signature: same
5777  *     number of input args and compatible return and argument types.
5778  * These rules are not set in stone and probably will be adjusted as we get
5779  * more experience with using BPF CO-RE relocations.
5780  */
5781 int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
5782 			      const struct btf *targ_btf, __u32 targ_id)
5783 {
5784 	return __bpf_core_types_are_compat(local_btf, local_id, targ_btf, targ_id, 32);
5785 }
5786 
5787 int bpf_core_types_match(const struct btf *local_btf, __u32 local_id,
5788 			 const struct btf *targ_btf, __u32 targ_id)
5789 {
5790 	return __bpf_core_types_match(local_btf, local_id, targ_btf, targ_id, false, 32);
5791 }
5792 
5793 static size_t bpf_core_hash_fn(const long key, void *ctx)
5794 {
5795 	return key;
5796 }
5797 
5798 static bool bpf_core_equal_fn(const long k1, const long k2, void *ctx)
5799 {
5800 	return k1 == k2;
5801 }
5802 
5803 static int record_relo_core(struct bpf_program *prog,
5804 			    const struct bpf_core_relo *core_relo, int insn_idx)
5805 {
5806 	struct reloc_desc *relos, *relo;
5807 
5808 	relos = libbpf_reallocarray(prog->reloc_desc,
5809 				    prog->nr_reloc + 1, sizeof(*relos));
5810 	if (!relos)
5811 		return -ENOMEM;
5812 	relo = &relos[prog->nr_reloc];
5813 	relo->type = RELO_CORE;
5814 	relo->insn_idx = insn_idx;
5815 	relo->core_relo = core_relo;
5816 	prog->reloc_desc = relos;
5817 	prog->nr_reloc++;
5818 	return 0;
5819 }
5820 
5821 static const struct bpf_core_relo *find_relo_core(struct bpf_program *prog, int insn_idx)
5822 {
5823 	struct reloc_desc *relo;
5824 	int i;
5825 
5826 	for (i = 0; i < prog->nr_reloc; i++) {
5827 		relo = &prog->reloc_desc[i];
5828 		if (relo->type != RELO_CORE || relo->insn_idx != insn_idx)
5829 			continue;
5830 
5831 		return relo->core_relo;
5832 	}
5833 
5834 	return NULL;
5835 }
5836 
5837 static int bpf_core_resolve_relo(struct bpf_program *prog,
5838 				 const struct bpf_core_relo *relo,
5839 				 int relo_idx,
5840 				 const struct btf *local_btf,
5841 				 struct hashmap *cand_cache,
5842 				 struct bpf_core_relo_res *targ_res)
5843 {
5844 	struct bpf_core_spec specs_scratch[3] = {};
5845 	struct bpf_core_cand_list *cands = NULL;
5846 	const char *prog_name = prog->name;
5847 	const struct btf_type *local_type;
5848 	const char *local_name;
5849 	__u32 local_id = relo->type_id;
5850 	int err;
5851 
5852 	local_type = btf__type_by_id(local_btf, local_id);
5853 	if (!local_type)
5854 		return -EINVAL;
5855 
5856 	local_name = btf__name_by_offset(local_btf, local_type->name_off);
5857 	if (!local_name)
5858 		return -EINVAL;
5859 
5860 	if (relo->kind != BPF_CORE_TYPE_ID_LOCAL &&
5861 	    !hashmap__find(cand_cache, local_id, &cands)) {
5862 		cands = bpf_core_find_cands(prog->obj, local_btf, local_id);
5863 		if (IS_ERR(cands)) {
5864 			pr_warn("prog '%s': relo #%d: target candidate search failed for [%d] %s %s: %ld\n",
5865 				prog_name, relo_idx, local_id, btf_kind_str(local_type),
5866 				local_name, PTR_ERR(cands));
5867 			return PTR_ERR(cands);
5868 		}
5869 		err = hashmap__set(cand_cache, local_id, cands, NULL, NULL);
5870 		if (err) {
5871 			bpf_core_free_cands(cands);
5872 			return err;
5873 		}
5874 	}
5875 
5876 	return bpf_core_calc_relo_insn(prog_name, relo, relo_idx, local_btf, cands, specs_scratch,
5877 				       targ_res);
5878 }
5879 
5880 static int
5881 bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
5882 {
5883 	const struct btf_ext_info_sec *sec;
5884 	struct bpf_core_relo_res targ_res;
5885 	const struct bpf_core_relo *rec;
5886 	const struct btf_ext_info *seg;
5887 	struct hashmap_entry *entry;
5888 	struct hashmap *cand_cache = NULL;
5889 	struct bpf_program *prog;
5890 	struct bpf_insn *insn;
5891 	const char *sec_name;
5892 	int i, err = 0, insn_idx, sec_idx, sec_num;
5893 
5894 	if (obj->btf_ext->core_relo_info.len == 0)
5895 		return 0;
5896 
5897 	if (targ_btf_path) {
5898 		obj->btf_vmlinux_override = btf__parse(targ_btf_path, NULL);
5899 		err = libbpf_get_error(obj->btf_vmlinux_override);
5900 		if (err) {
5901 			pr_warn("failed to parse target BTF: %d\n", err);
5902 			return err;
5903 		}
5904 	}
5905 
5906 	cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
5907 	if (IS_ERR(cand_cache)) {
5908 		err = PTR_ERR(cand_cache);
5909 		goto out;
5910 	}
5911 
5912 	seg = &obj->btf_ext->core_relo_info;
5913 	sec_num = 0;
5914 	for_each_btf_ext_sec(seg, sec) {
5915 		sec_idx = seg->sec_idxs[sec_num];
5916 		sec_num++;
5917 
5918 		sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
5919 		if (str_is_empty(sec_name)) {
5920 			err = -EINVAL;
5921 			goto out;
5922 		}
5923 
5924 		pr_debug("sec '%s': found %d CO-RE relocations\n", sec_name, sec->num_info);
5925 
5926 		for_each_btf_ext_rec(seg, sec, i, rec) {
5927 			if (rec->insn_off % BPF_INSN_SZ)
5928 				return -EINVAL;
5929 			insn_idx = rec->insn_off / BPF_INSN_SZ;
5930 			prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
5931 			if (!prog) {
5932 				/* When __weak subprog is "overridden" by another instance
5933 				 * of the subprog from a different object file, linker still
5934 				 * appends all the .BTF.ext info that used to belong to that
5935 				 * eliminated subprogram.
5936 				 * This is similar to what x86-64 linker does for relocations.
5937 				 * So just ignore such relocations just like we ignore
5938 				 * subprog instructions when discovering subprograms.
5939 				 */
5940 				pr_debug("sec '%s': skipping CO-RE relocation #%d for insn #%d belonging to eliminated weak subprogram\n",
5941 					 sec_name, i, insn_idx);
5942 				continue;
5943 			}
5944 			/* no need to apply CO-RE relocation if the program is
5945 			 * not going to be loaded
5946 			 */
5947 			if (!prog->autoload)
5948 				continue;
5949 
5950 			/* adjust insn_idx from section frame of reference to the local
5951 			 * program's frame of reference; (sub-)program code is not yet
5952 			 * relocated, so it's enough to just subtract in-section offset
5953 			 */
5954 			insn_idx = insn_idx - prog->sec_insn_off;
5955 			if (insn_idx >= prog->insns_cnt)
5956 				return -EINVAL;
5957 			insn = &prog->insns[insn_idx];
5958 
5959 			err = record_relo_core(prog, rec, insn_idx);
5960 			if (err) {
5961 				pr_warn("prog '%s': relo #%d: failed to record relocation: %d\n",
5962 					prog->name, i, err);
5963 				goto out;
5964 			}
5965 
5966 			if (prog->obj->gen_loader)
5967 				continue;
5968 
5969 			err = bpf_core_resolve_relo(prog, rec, i, obj->btf, cand_cache, &targ_res);
5970 			if (err) {
5971 				pr_warn("prog '%s': relo #%d: failed to relocate: %d\n",
5972 					prog->name, i, err);
5973 				goto out;
5974 			}
5975 
5976 			err = bpf_core_patch_insn(prog->name, insn, insn_idx, rec, i, &targ_res);
5977 			if (err) {
5978 				pr_warn("prog '%s': relo #%d: failed to patch insn #%u: %d\n",
5979 					prog->name, i, insn_idx, err);
5980 				goto out;
5981 			}
5982 		}
5983 	}
5984 
5985 out:
5986 	/* obj->btf_vmlinux and module BTFs are freed after object load */
5987 	btf__free(obj->btf_vmlinux_override);
5988 	obj->btf_vmlinux_override = NULL;
5989 
5990 	if (!IS_ERR_OR_NULL(cand_cache)) {
5991 		hashmap__for_each_entry(cand_cache, entry, i) {
5992 			bpf_core_free_cands(entry->pvalue);
5993 		}
5994 		hashmap__free(cand_cache);
5995 	}
5996 	return err;
5997 }
5998 
5999 /* base map load ldimm64 special constant, used also for log fixup logic */
6000 #define POISON_LDIMM64_MAP_BASE 2001000000
6001 #define POISON_LDIMM64_MAP_PFX "200100"
6002 
6003 static void poison_map_ldimm64(struct bpf_program *prog, int relo_idx,
6004 			       int insn_idx, struct bpf_insn *insn,
6005 			       int map_idx, const struct bpf_map *map)
6006 {
6007 	int i;
6008 
6009 	pr_debug("prog '%s': relo #%d: poisoning insn #%d that loads map #%d '%s'\n",
6010 		 prog->name, relo_idx, insn_idx, map_idx, map->name);
6011 
6012 	/* we turn single ldimm64 into two identical invalid calls */
6013 	for (i = 0; i < 2; i++) {
6014 		insn->code = BPF_JMP | BPF_CALL;
6015 		insn->dst_reg = 0;
6016 		insn->src_reg = 0;
6017 		insn->off = 0;
6018 		/* if this instruction is reachable (not a dead code),
6019 		 * verifier will complain with something like:
6020 		 * invalid func unknown#2001000123
6021 		 * where lower 123 is map index into obj->maps[] array
6022 		 */
6023 		insn->imm = POISON_LDIMM64_MAP_BASE + map_idx;
6024 
6025 		insn++;
6026 	}
6027 }
6028 
6029 /* unresolved kfunc call special constant, used also for log fixup logic */
6030 #define POISON_CALL_KFUNC_BASE 2002000000
6031 #define POISON_CALL_KFUNC_PFX "2002"
6032 
6033 static void poison_kfunc_call(struct bpf_program *prog, int relo_idx,
6034 			      int insn_idx, struct bpf_insn *insn,
6035 			      int ext_idx, const struct extern_desc *ext)
6036 {
6037 	pr_debug("prog '%s': relo #%d: poisoning insn #%d that calls kfunc '%s'\n",
6038 		 prog->name, relo_idx, insn_idx, ext->name);
6039 
6040 	/* we turn kfunc call into invalid helper call with identifiable constant */
6041 	insn->code = BPF_JMP | BPF_CALL;
6042 	insn->dst_reg = 0;
6043 	insn->src_reg = 0;
6044 	insn->off = 0;
6045 	/* if this instruction is reachable (not a dead code),
6046 	 * verifier will complain with something like:
6047 	 * invalid func unknown#2001000123
6048 	 * where lower 123 is extern index into obj->externs[] array
6049 	 */
6050 	insn->imm = POISON_CALL_KFUNC_BASE + ext_idx;
6051 }
6052 
6053 /* Relocate data references within program code:
6054  *  - map references;
6055  *  - global variable references;
6056  *  - extern references.
6057  */
6058 static int
6059 bpf_object__relocate_data(struct bpf_object *obj, struct bpf_program *prog)
6060 {
6061 	int i;
6062 
6063 	for (i = 0; i < prog->nr_reloc; i++) {
6064 		struct reloc_desc *relo = &prog->reloc_desc[i];
6065 		struct bpf_insn *insn = &prog->insns[relo->insn_idx];
6066 		const struct bpf_map *map;
6067 		struct extern_desc *ext;
6068 
6069 		switch (relo->type) {
6070 		case RELO_LD64:
6071 			map = &obj->maps[relo->map_idx];
6072 			if (obj->gen_loader) {
6073 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX;
6074 				insn[0].imm = relo->map_idx;
6075 			} else if (map->autocreate) {
6076 				insn[0].src_reg = BPF_PSEUDO_MAP_FD;
6077 				insn[0].imm = map->fd;
6078 			} else {
6079 				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
6080 						   relo->map_idx, map);
6081 			}
6082 			break;
6083 		case RELO_DATA:
6084 			map = &obj->maps[relo->map_idx];
6085 			insn[1].imm = insn[0].imm + relo->sym_off;
6086 			if (obj->gen_loader) {
6087 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
6088 				insn[0].imm = relo->map_idx;
6089 			} else if (map->autocreate) {
6090 				insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6091 				insn[0].imm = map->fd;
6092 			} else {
6093 				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
6094 						   relo->map_idx, map);
6095 			}
6096 			break;
6097 		case RELO_EXTERN_LD64:
6098 			ext = &obj->externs[relo->ext_idx];
6099 			if (ext->type == EXT_KCFG) {
6100 				if (obj->gen_loader) {
6101 					insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
6102 					insn[0].imm = obj->kconfig_map_idx;
6103 				} else {
6104 					insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6105 					insn[0].imm = obj->maps[obj->kconfig_map_idx].fd;
6106 				}
6107 				insn[1].imm = ext->kcfg.data_off;
6108 			} else /* EXT_KSYM */ {
6109 				if (ext->ksym.type_id && ext->is_set) { /* typed ksyms */
6110 					insn[0].src_reg = BPF_PSEUDO_BTF_ID;
6111 					insn[0].imm = ext->ksym.kernel_btf_id;
6112 					insn[1].imm = ext->ksym.kernel_btf_obj_fd;
6113 				} else { /* typeless ksyms or unresolved typed ksyms */
6114 					insn[0].imm = (__u32)ext->ksym.addr;
6115 					insn[1].imm = ext->ksym.addr >> 32;
6116 				}
6117 			}
6118 			break;
6119 		case RELO_EXTERN_CALL:
6120 			ext = &obj->externs[relo->ext_idx];
6121 			insn[0].src_reg = BPF_PSEUDO_KFUNC_CALL;
6122 			if (ext->is_set) {
6123 				insn[0].imm = ext->ksym.kernel_btf_id;
6124 				insn[0].off = ext->ksym.btf_fd_idx;
6125 			} else { /* unresolved weak kfunc call */
6126 				poison_kfunc_call(prog, i, relo->insn_idx, insn,
6127 						  relo->ext_idx, ext);
6128 			}
6129 			break;
6130 		case RELO_SUBPROG_ADDR:
6131 			if (insn[0].src_reg != BPF_PSEUDO_FUNC) {
6132 				pr_warn("prog '%s': relo #%d: bad insn\n",
6133 					prog->name, i);
6134 				return -EINVAL;
6135 			}
6136 			/* handled already */
6137 			break;
6138 		case RELO_CALL:
6139 			/* handled already */
6140 			break;
6141 		case RELO_CORE:
6142 			/* will be handled by bpf_program_record_relos() */
6143 			break;
6144 		default:
6145 			pr_warn("prog '%s': relo #%d: bad relo type %d\n",
6146 				prog->name, i, relo->type);
6147 			return -EINVAL;
6148 		}
6149 	}
6150 
6151 	return 0;
6152 }
6153 
6154 static int adjust_prog_btf_ext_info(const struct bpf_object *obj,
6155 				    const struct bpf_program *prog,
6156 				    const struct btf_ext_info *ext_info,
6157 				    void **prog_info, __u32 *prog_rec_cnt,
6158 				    __u32 *prog_rec_sz)
6159 {
6160 	void *copy_start = NULL, *copy_end = NULL;
6161 	void *rec, *rec_end, *new_prog_info;
6162 	const struct btf_ext_info_sec *sec;
6163 	size_t old_sz, new_sz;
6164 	int i, sec_num, sec_idx, off_adj;
6165 
6166 	sec_num = 0;
6167 	for_each_btf_ext_sec(ext_info, sec) {
6168 		sec_idx = ext_info->sec_idxs[sec_num];
6169 		sec_num++;
6170 		if (prog->sec_idx != sec_idx)
6171 			continue;
6172 
6173 		for_each_btf_ext_rec(ext_info, sec, i, rec) {
6174 			__u32 insn_off = *(__u32 *)rec / BPF_INSN_SZ;
6175 
6176 			if (insn_off < prog->sec_insn_off)
6177 				continue;
6178 			if (insn_off >= prog->sec_insn_off + prog->sec_insn_cnt)
6179 				break;
6180 
6181 			if (!copy_start)
6182 				copy_start = rec;
6183 			copy_end = rec + ext_info->rec_size;
6184 		}
6185 
6186 		if (!copy_start)
6187 			return -ENOENT;
6188 
6189 		/* append func/line info of a given (sub-)program to the main
6190 		 * program func/line info
6191 		 */
6192 		old_sz = (size_t)(*prog_rec_cnt) * ext_info->rec_size;
6193 		new_sz = old_sz + (copy_end - copy_start);
6194 		new_prog_info = realloc(*prog_info, new_sz);
6195 		if (!new_prog_info)
6196 			return -ENOMEM;
6197 		*prog_info = new_prog_info;
6198 		*prog_rec_cnt = new_sz / ext_info->rec_size;
6199 		memcpy(new_prog_info + old_sz, copy_start, copy_end - copy_start);
6200 
6201 		/* Kernel instruction offsets are in units of 8-byte
6202 		 * instructions, while .BTF.ext instruction offsets generated
6203 		 * by Clang are in units of bytes. So convert Clang offsets
6204 		 * into kernel offsets and adjust offset according to program
6205 		 * relocated position.
6206 		 */
6207 		off_adj = prog->sub_insn_off - prog->sec_insn_off;
6208 		rec = new_prog_info + old_sz;
6209 		rec_end = new_prog_info + new_sz;
6210 		for (; rec < rec_end; rec += ext_info->rec_size) {
6211 			__u32 *insn_off = rec;
6212 
6213 			*insn_off = *insn_off / BPF_INSN_SZ + off_adj;
6214 		}
6215 		*prog_rec_sz = ext_info->rec_size;
6216 		return 0;
6217 	}
6218 
6219 	return -ENOENT;
6220 }
6221 
6222 static int
6223 reloc_prog_func_and_line_info(const struct bpf_object *obj,
6224 			      struct bpf_program *main_prog,
6225 			      const struct bpf_program *prog)
6226 {
6227 	int err;
6228 
6229 	/* no .BTF.ext relocation if .BTF.ext is missing or kernel doesn't
6230 	 * support func/line info
6231 	 */
6232 	if (!obj->btf_ext || !kernel_supports(obj, FEAT_BTF_FUNC))
6233 		return 0;
6234 
6235 	/* only attempt func info relocation if main program's func_info
6236 	 * relocation was successful
6237 	 */
6238 	if (main_prog != prog && !main_prog->func_info)
6239 		goto line_info;
6240 
6241 	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->func_info,
6242 				       &main_prog->func_info,
6243 				       &main_prog->func_info_cnt,
6244 				       &main_prog->func_info_rec_size);
6245 	if (err) {
6246 		if (err != -ENOENT) {
6247 			pr_warn("prog '%s': error relocating .BTF.ext function info: %d\n",
6248 				prog->name, err);
6249 			return err;
6250 		}
6251 		if (main_prog->func_info) {
6252 			/*
6253 			 * Some info has already been found but has problem
6254 			 * in the last btf_ext reloc. Must have to error out.
6255 			 */
6256 			pr_warn("prog '%s': missing .BTF.ext function info.\n", prog->name);
6257 			return err;
6258 		}
6259 		/* Have problem loading the very first info. Ignore the rest. */
6260 		pr_warn("prog '%s': missing .BTF.ext function info for the main program, skipping all of .BTF.ext func info.\n",
6261 			prog->name);
6262 	}
6263 
6264 line_info:
6265 	/* don't relocate line info if main program's relocation failed */
6266 	if (main_prog != prog && !main_prog->line_info)
6267 		return 0;
6268 
6269 	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->line_info,
6270 				       &main_prog->line_info,
6271 				       &main_prog->line_info_cnt,
6272 				       &main_prog->line_info_rec_size);
6273 	if (err) {
6274 		if (err != -ENOENT) {
6275 			pr_warn("prog '%s': error relocating .BTF.ext line info: %d\n",
6276 				prog->name, err);
6277 			return err;
6278 		}
6279 		if (main_prog->line_info) {
6280 			/*
6281 			 * Some info has already been found but has problem
6282 			 * in the last btf_ext reloc. Must have to error out.
6283 			 */
6284 			pr_warn("prog '%s': missing .BTF.ext line info.\n", prog->name);
6285 			return err;
6286 		}
6287 		/* Have problem loading the very first info. Ignore the rest. */
6288 		pr_warn("prog '%s': missing .BTF.ext line info for the main program, skipping all of .BTF.ext line info.\n",
6289 			prog->name);
6290 	}
6291 	return 0;
6292 }
6293 
6294 static int cmp_relo_by_insn_idx(const void *key, const void *elem)
6295 {
6296 	size_t insn_idx = *(const size_t *)key;
6297 	const struct reloc_desc *relo = elem;
6298 
6299 	if (insn_idx == relo->insn_idx)
6300 		return 0;
6301 	return insn_idx < relo->insn_idx ? -1 : 1;
6302 }
6303 
6304 static struct reloc_desc *find_prog_insn_relo(const struct bpf_program *prog, size_t insn_idx)
6305 {
6306 	if (!prog->nr_reloc)
6307 		return NULL;
6308 	return bsearch(&insn_idx, prog->reloc_desc, prog->nr_reloc,
6309 		       sizeof(*prog->reloc_desc), cmp_relo_by_insn_idx);
6310 }
6311 
6312 static int append_subprog_relos(struct bpf_program *main_prog, struct bpf_program *subprog)
6313 {
6314 	int new_cnt = main_prog->nr_reloc + subprog->nr_reloc;
6315 	struct reloc_desc *relos;
6316 	int i;
6317 
6318 	if (main_prog == subprog)
6319 		return 0;
6320 	relos = libbpf_reallocarray(main_prog->reloc_desc, new_cnt, sizeof(*relos));
6321 	/* if new count is zero, reallocarray can return a valid NULL result;
6322 	 * in this case the previous pointer will be freed, so we *have to*
6323 	 * reassign old pointer to the new value (even if it's NULL)
6324 	 */
6325 	if (!relos && new_cnt)
6326 		return -ENOMEM;
6327 	if (subprog->nr_reloc)
6328 		memcpy(relos + main_prog->nr_reloc, subprog->reloc_desc,
6329 		       sizeof(*relos) * subprog->nr_reloc);
6330 
6331 	for (i = main_prog->nr_reloc; i < new_cnt; i++)
6332 		relos[i].insn_idx += subprog->sub_insn_off;
6333 	/* After insn_idx adjustment the 'relos' array is still sorted
6334 	 * by insn_idx and doesn't break bsearch.
6335 	 */
6336 	main_prog->reloc_desc = relos;
6337 	main_prog->nr_reloc = new_cnt;
6338 	return 0;
6339 }
6340 
6341 static int
6342 bpf_object__append_subprog_code(struct bpf_object *obj, struct bpf_program *main_prog,
6343 				struct bpf_program *subprog)
6344 {
6345        struct bpf_insn *insns;
6346        size_t new_cnt;
6347        int err;
6348 
6349        subprog->sub_insn_off = main_prog->insns_cnt;
6350 
6351        new_cnt = main_prog->insns_cnt + subprog->insns_cnt;
6352        insns = libbpf_reallocarray(main_prog->insns, new_cnt, sizeof(*insns));
6353        if (!insns) {
6354                pr_warn("prog '%s': failed to realloc prog code\n", main_prog->name);
6355                return -ENOMEM;
6356        }
6357        main_prog->insns = insns;
6358        main_prog->insns_cnt = new_cnt;
6359 
6360        memcpy(main_prog->insns + subprog->sub_insn_off, subprog->insns,
6361               subprog->insns_cnt * sizeof(*insns));
6362 
6363        pr_debug("prog '%s': added %zu insns from sub-prog '%s'\n",
6364                 main_prog->name, subprog->insns_cnt, subprog->name);
6365 
6366        /* The subprog insns are now appended. Append its relos too. */
6367        err = append_subprog_relos(main_prog, subprog);
6368        if (err)
6369                return err;
6370        return 0;
6371 }
6372 
6373 static int
6374 bpf_object__reloc_code(struct bpf_object *obj, struct bpf_program *main_prog,
6375 		       struct bpf_program *prog)
6376 {
6377 	size_t sub_insn_idx, insn_idx;
6378 	struct bpf_program *subprog;
6379 	struct reloc_desc *relo;
6380 	struct bpf_insn *insn;
6381 	int err;
6382 
6383 	err = reloc_prog_func_and_line_info(obj, main_prog, prog);
6384 	if (err)
6385 		return err;
6386 
6387 	for (insn_idx = 0; insn_idx < prog->sec_insn_cnt; insn_idx++) {
6388 		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6389 		if (!insn_is_subprog_call(insn) && !insn_is_pseudo_func(insn))
6390 			continue;
6391 
6392 		relo = find_prog_insn_relo(prog, insn_idx);
6393 		if (relo && relo->type == RELO_EXTERN_CALL)
6394 			/* kfunc relocations will be handled later
6395 			 * in bpf_object__relocate_data()
6396 			 */
6397 			continue;
6398 		if (relo && relo->type != RELO_CALL && relo->type != RELO_SUBPROG_ADDR) {
6399 			pr_warn("prog '%s': unexpected relo for insn #%zu, type %d\n",
6400 				prog->name, insn_idx, relo->type);
6401 			return -LIBBPF_ERRNO__RELOC;
6402 		}
6403 		if (relo) {
6404 			/* sub-program instruction index is a combination of
6405 			 * an offset of a symbol pointed to by relocation and
6406 			 * call instruction's imm field; for global functions,
6407 			 * call always has imm = -1, but for static functions
6408 			 * relocation is against STT_SECTION and insn->imm
6409 			 * points to a start of a static function
6410 			 *
6411 			 * for subprog addr relocation, the relo->sym_off + insn->imm is
6412 			 * the byte offset in the corresponding section.
6413 			 */
6414 			if (relo->type == RELO_CALL)
6415 				sub_insn_idx = relo->sym_off / BPF_INSN_SZ + insn->imm + 1;
6416 			else
6417 				sub_insn_idx = (relo->sym_off + insn->imm) / BPF_INSN_SZ;
6418 		} else if (insn_is_pseudo_func(insn)) {
6419 			/*
6420 			 * RELO_SUBPROG_ADDR relo is always emitted even if both
6421 			 * functions are in the same section, so it shouldn't reach here.
6422 			 */
6423 			pr_warn("prog '%s': missing subprog addr relo for insn #%zu\n",
6424 				prog->name, insn_idx);
6425 			return -LIBBPF_ERRNO__RELOC;
6426 		} else {
6427 			/* if subprogram call is to a static function within
6428 			 * the same ELF section, there won't be any relocation
6429 			 * emitted, but it also means there is no additional
6430 			 * offset necessary, insns->imm is relative to
6431 			 * instruction's original position within the section
6432 			 */
6433 			sub_insn_idx = prog->sec_insn_off + insn_idx + insn->imm + 1;
6434 		}
6435 
6436 		/* we enforce that sub-programs should be in .text section */
6437 		subprog = find_prog_by_sec_insn(obj, obj->efile.text_shndx, sub_insn_idx);
6438 		if (!subprog) {
6439 			pr_warn("prog '%s': no .text section found yet sub-program call exists\n",
6440 				prog->name);
6441 			return -LIBBPF_ERRNO__RELOC;
6442 		}
6443 
6444 		/* if it's the first call instruction calling into this
6445 		 * subprogram (meaning this subprog hasn't been processed
6446 		 * yet) within the context of current main program:
6447 		 *   - append it at the end of main program's instructions blog;
6448 		 *   - process is recursively, while current program is put on hold;
6449 		 *   - if that subprogram calls some other not yet processes
6450 		 *   subprogram, same thing will happen recursively until
6451 		 *   there are no more unprocesses subprograms left to append
6452 		 *   and relocate.
6453 		 */
6454 		if (subprog->sub_insn_off == 0) {
6455 			err = bpf_object__append_subprog_code(obj, main_prog, subprog);
6456 			if (err)
6457 				return err;
6458 			err = bpf_object__reloc_code(obj, main_prog, subprog);
6459 			if (err)
6460 				return err;
6461 		}
6462 
6463 		/* main_prog->insns memory could have been re-allocated, so
6464 		 * calculate pointer again
6465 		 */
6466 		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6467 		/* calculate correct instruction position within current main
6468 		 * prog; each main prog can have a different set of
6469 		 * subprograms appended (potentially in different order as
6470 		 * well), so position of any subprog can be different for
6471 		 * different main programs
6472 		 */
6473 		insn->imm = subprog->sub_insn_off - (prog->sub_insn_off + insn_idx) - 1;
6474 
6475 		pr_debug("prog '%s': insn #%zu relocated, imm %d points to subprog '%s' (now at %zu offset)\n",
6476 			 prog->name, insn_idx, insn->imm, subprog->name, subprog->sub_insn_off);
6477 	}
6478 
6479 	return 0;
6480 }
6481 
6482 /*
6483  * Relocate sub-program calls.
6484  *
6485  * Algorithm operates as follows. Each entry-point BPF program (referred to as
6486  * main prog) is processed separately. For each subprog (non-entry functions,
6487  * that can be called from either entry progs or other subprogs) gets their
6488  * sub_insn_off reset to zero. This serves as indicator that this subprogram
6489  * hasn't been yet appended and relocated within current main prog. Once its
6490  * relocated, sub_insn_off will point at the position within current main prog
6491  * where given subprog was appended. This will further be used to relocate all
6492  * the call instructions jumping into this subprog.
6493  *
6494  * We start with main program and process all call instructions. If the call
6495  * is into a subprog that hasn't been processed (i.e., subprog->sub_insn_off
6496  * is zero), subprog instructions are appended at the end of main program's
6497  * instruction array. Then main program is "put on hold" while we recursively
6498  * process newly appended subprogram. If that subprogram calls into another
6499  * subprogram that hasn't been appended, new subprogram is appended again to
6500  * the *main* prog's instructions (subprog's instructions are always left
6501  * untouched, as they need to be in unmodified state for subsequent main progs
6502  * and subprog instructions are always sent only as part of a main prog) and
6503  * the process continues recursively. Once all the subprogs called from a main
6504  * prog or any of its subprogs are appended (and relocated), all their
6505  * positions within finalized instructions array are known, so it's easy to
6506  * rewrite call instructions with correct relative offsets, corresponding to
6507  * desired target subprog.
6508  *
6509  * Its important to realize that some subprogs might not be called from some
6510  * main prog and any of its called/used subprogs. Those will keep their
6511  * subprog->sub_insn_off as zero at all times and won't be appended to current
6512  * main prog and won't be relocated within the context of current main prog.
6513  * They might still be used from other main progs later.
6514  *
6515  * Visually this process can be shown as below. Suppose we have two main
6516  * programs mainA and mainB and BPF object contains three subprogs: subA,
6517  * subB, and subC. mainA calls only subA, mainB calls only subC, but subA and
6518  * subC both call subB:
6519  *
6520  *        +--------+ +-------+
6521  *        |        v v       |
6522  *     +--+---+ +--+-+-+ +---+--+
6523  *     | subA | | subB | | subC |
6524  *     +--+---+ +------+ +---+--+
6525  *        ^                  ^
6526  *        |                  |
6527  *    +---+-------+   +------+----+
6528  *    |   mainA   |   |   mainB   |
6529  *    +-----------+   +-----------+
6530  *
6531  * We'll start relocating mainA, will find subA, append it and start
6532  * processing sub A recursively:
6533  *
6534  *    +-----------+------+
6535  *    |   mainA   | subA |
6536  *    +-----------+------+
6537  *
6538  * At this point we notice that subB is used from subA, so we append it and
6539  * relocate (there are no further subcalls from subB):
6540  *
6541  *    +-----------+------+------+
6542  *    |   mainA   | subA | subB |
6543  *    +-----------+------+------+
6544  *
6545  * At this point, we relocate subA calls, then go one level up and finish with
6546  * relocatin mainA calls. mainA is done.
6547  *
6548  * For mainB process is similar but results in different order. We start with
6549  * mainB and skip subA and subB, as mainB never calls them (at least
6550  * directly), but we see subC is needed, so we append and start processing it:
6551  *
6552  *    +-----------+------+
6553  *    |   mainB   | subC |
6554  *    +-----------+------+
6555  * Now we see subC needs subB, so we go back to it, append and relocate it:
6556  *
6557  *    +-----------+------+------+
6558  *    |   mainB   | subC | subB |
6559  *    +-----------+------+------+
6560  *
6561  * At this point we unwind recursion, relocate calls in subC, then in mainB.
6562  */
6563 static int
6564 bpf_object__relocate_calls(struct bpf_object *obj, struct bpf_program *prog)
6565 {
6566 	struct bpf_program *subprog;
6567 	int i, err;
6568 
6569 	/* mark all subprogs as not relocated (yet) within the context of
6570 	 * current main program
6571 	 */
6572 	for (i = 0; i < obj->nr_programs; i++) {
6573 		subprog = &obj->programs[i];
6574 		if (!prog_is_subprog(obj, subprog))
6575 			continue;
6576 
6577 		subprog->sub_insn_off = 0;
6578 	}
6579 
6580 	err = bpf_object__reloc_code(obj, prog, prog);
6581 	if (err)
6582 		return err;
6583 
6584 	return 0;
6585 }
6586 
6587 static void
6588 bpf_object__free_relocs(struct bpf_object *obj)
6589 {
6590 	struct bpf_program *prog;
6591 	int i;
6592 
6593 	/* free up relocation descriptors */
6594 	for (i = 0; i < obj->nr_programs; i++) {
6595 		prog = &obj->programs[i];
6596 		zfree(&prog->reloc_desc);
6597 		prog->nr_reloc = 0;
6598 	}
6599 }
6600 
6601 static int cmp_relocs(const void *_a, const void *_b)
6602 {
6603 	const struct reloc_desc *a = _a;
6604 	const struct reloc_desc *b = _b;
6605 
6606 	if (a->insn_idx != b->insn_idx)
6607 		return a->insn_idx < b->insn_idx ? -1 : 1;
6608 
6609 	/* no two relocations should have the same insn_idx, but ... */
6610 	if (a->type != b->type)
6611 		return a->type < b->type ? -1 : 1;
6612 
6613 	return 0;
6614 }
6615 
6616 static void bpf_object__sort_relos(struct bpf_object *obj)
6617 {
6618 	int i;
6619 
6620 	for (i = 0; i < obj->nr_programs; i++) {
6621 		struct bpf_program *p = &obj->programs[i];
6622 
6623 		if (!p->nr_reloc)
6624 			continue;
6625 
6626 		qsort(p->reloc_desc, p->nr_reloc, sizeof(*p->reloc_desc), cmp_relocs);
6627 	}
6628 }
6629 
6630 static int bpf_prog_assign_exc_cb(struct bpf_object *obj, struct bpf_program *prog)
6631 {
6632 	const char *str = "exception_callback:";
6633 	size_t pfx_len = strlen(str);
6634 	int i, j, n;
6635 
6636 	if (!obj->btf || !kernel_supports(obj, FEAT_BTF_DECL_TAG))
6637 		return 0;
6638 
6639 	n = btf__type_cnt(obj->btf);
6640 	for (i = 1; i < n; i++) {
6641 		const char *name;
6642 		struct btf_type *t;
6643 
6644 		t = btf_type_by_id(obj->btf, i);
6645 		if (!btf_is_decl_tag(t) || btf_decl_tag(t)->component_idx != -1)
6646 			continue;
6647 
6648 		name = btf__str_by_offset(obj->btf, t->name_off);
6649 		if (strncmp(name, str, pfx_len) != 0)
6650 			continue;
6651 
6652 		t = btf_type_by_id(obj->btf, t->type);
6653 		if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL) {
6654 			pr_warn("prog '%s': exception_callback:<value> decl tag not applied to the main program\n",
6655 				prog->name);
6656 			return -EINVAL;
6657 		}
6658 		if (strcmp(prog->name, btf__str_by_offset(obj->btf, t->name_off)) != 0)
6659 			continue;
6660 		/* Multiple callbacks are specified for the same prog,
6661 		 * the verifier will eventually return an error for this
6662 		 * case, hence simply skip appending a subprog.
6663 		 */
6664 		if (prog->exception_cb_idx >= 0) {
6665 			prog->exception_cb_idx = -1;
6666 			break;
6667 		}
6668 
6669 		name += pfx_len;
6670 		if (str_is_empty(name)) {
6671 			pr_warn("prog '%s': exception_callback:<value> decl tag contains empty value\n",
6672 				prog->name);
6673 			return -EINVAL;
6674 		}
6675 
6676 		for (j = 0; j < obj->nr_programs; j++) {
6677 			struct bpf_program *subprog = &obj->programs[j];
6678 
6679 			if (!prog_is_subprog(obj, subprog))
6680 				continue;
6681 			if (strcmp(name, subprog->name) != 0)
6682 				continue;
6683 			/* Enforce non-hidden, as from verifier point of
6684 			 * view it expects global functions, whereas the
6685 			 * mark_btf_static fixes up linkage as static.
6686 			 */
6687 			if (!subprog->sym_global || subprog->mark_btf_static) {
6688 				pr_warn("prog '%s': exception callback %s must be a global non-hidden function\n",
6689 					prog->name, subprog->name);
6690 				return -EINVAL;
6691 			}
6692 			/* Let's see if we already saw a static exception callback with the same name */
6693 			if (prog->exception_cb_idx >= 0) {
6694 				pr_warn("prog '%s': multiple subprogs with same name as exception callback '%s'\n",
6695 					prog->name, subprog->name);
6696 				return -EINVAL;
6697 			}
6698 			prog->exception_cb_idx = j;
6699 			break;
6700 		}
6701 
6702 		if (prog->exception_cb_idx >= 0)
6703 			continue;
6704 
6705 		pr_warn("prog '%s': cannot find exception callback '%s'\n", prog->name, name);
6706 		return -ENOENT;
6707 	}
6708 
6709 	return 0;
6710 }
6711 
6712 static struct {
6713 	enum bpf_prog_type prog_type;
6714 	const char *ctx_name;
6715 } global_ctx_map[] = {
6716 	{ BPF_PROG_TYPE_CGROUP_DEVICE,           "bpf_cgroup_dev_ctx" },
6717 	{ BPF_PROG_TYPE_CGROUP_SKB,              "__sk_buff" },
6718 	{ BPF_PROG_TYPE_CGROUP_SOCK,             "bpf_sock" },
6719 	{ BPF_PROG_TYPE_CGROUP_SOCK_ADDR,        "bpf_sock_addr" },
6720 	{ BPF_PROG_TYPE_CGROUP_SOCKOPT,          "bpf_sockopt" },
6721 	{ BPF_PROG_TYPE_CGROUP_SYSCTL,           "bpf_sysctl" },
6722 	{ BPF_PROG_TYPE_FLOW_DISSECTOR,          "__sk_buff" },
6723 	{ BPF_PROG_TYPE_KPROBE,                  "bpf_user_pt_regs_t" },
6724 	{ BPF_PROG_TYPE_LWT_IN,                  "__sk_buff" },
6725 	{ BPF_PROG_TYPE_LWT_OUT,                 "__sk_buff" },
6726 	{ BPF_PROG_TYPE_LWT_SEG6LOCAL,           "__sk_buff" },
6727 	{ BPF_PROG_TYPE_LWT_XMIT,                "__sk_buff" },
6728 	{ BPF_PROG_TYPE_NETFILTER,               "bpf_nf_ctx" },
6729 	{ BPF_PROG_TYPE_PERF_EVENT,              "bpf_perf_event_data" },
6730 	{ BPF_PROG_TYPE_RAW_TRACEPOINT,          "bpf_raw_tracepoint_args" },
6731 	{ BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE, "bpf_raw_tracepoint_args" },
6732 	{ BPF_PROG_TYPE_SCHED_ACT,               "__sk_buff" },
6733 	{ BPF_PROG_TYPE_SCHED_CLS,               "__sk_buff" },
6734 	{ BPF_PROG_TYPE_SK_LOOKUP,               "bpf_sk_lookup" },
6735 	{ BPF_PROG_TYPE_SK_MSG,                  "sk_msg_md" },
6736 	{ BPF_PROG_TYPE_SK_REUSEPORT,            "sk_reuseport_md" },
6737 	{ BPF_PROG_TYPE_SK_SKB,                  "__sk_buff" },
6738 	{ BPF_PROG_TYPE_SOCK_OPS,                "bpf_sock_ops" },
6739 	{ BPF_PROG_TYPE_SOCKET_FILTER,           "__sk_buff" },
6740 	{ BPF_PROG_TYPE_XDP,                     "xdp_md" },
6741 	/* all other program types don't have "named" context structs */
6742 };
6743 
6744 /* forward declarations for arch-specific underlying types of bpf_user_pt_regs_t typedef,
6745  * for below __builtin_types_compatible_p() checks;
6746  * with this approach we don't need any extra arch-specific #ifdef guards
6747  */
6748 struct pt_regs;
6749 struct user_pt_regs;
6750 struct user_regs_struct;
6751 
6752 static bool need_func_arg_type_fixup(const struct btf *btf, const struct bpf_program *prog,
6753 				     const char *subprog_name, int arg_idx,
6754 				     int arg_type_id, const char *ctx_name)
6755 {
6756 	const struct btf_type *t;
6757 	const char *tname;
6758 
6759 	/* check if existing parameter already matches verifier expectations */
6760 	t = skip_mods_and_typedefs(btf, arg_type_id, NULL);
6761 	if (!btf_is_ptr(t))
6762 		goto out_warn;
6763 
6764 	/* typedef bpf_user_pt_regs_t is a special PITA case, valid for kprobe
6765 	 * and perf_event programs, so check this case early on and forget
6766 	 * about it for subsequent checks
6767 	 */
6768 	while (btf_is_mod(t))
6769 		t = btf__type_by_id(btf, t->type);
6770 	if (btf_is_typedef(t) &&
6771 	    (prog->type == BPF_PROG_TYPE_KPROBE || prog->type == BPF_PROG_TYPE_PERF_EVENT)) {
6772 		tname = btf__str_by_offset(btf, t->name_off) ?: "<anon>";
6773 		if (strcmp(tname, "bpf_user_pt_regs_t") == 0)
6774 			return false; /* canonical type for kprobe/perf_event */
6775 	}
6776 
6777 	/* now we can ignore typedefs moving forward */
6778 	t = skip_mods_and_typedefs(btf, t->type, NULL);
6779 
6780 	/* if it's `void *`, definitely fix up BTF info */
6781 	if (btf_is_void(t))
6782 		return true;
6783 
6784 	/* if it's already proper canonical type, no need to fix up */
6785 	tname = btf__str_by_offset(btf, t->name_off) ?: "<anon>";
6786 	if (btf_is_struct(t) && strcmp(tname, ctx_name) == 0)
6787 		return false;
6788 
6789 	/* special cases */
6790 	switch (prog->type) {
6791 	case BPF_PROG_TYPE_KPROBE:
6792 		/* `struct pt_regs *` is expected, but we need to fix up */
6793 		if (btf_is_struct(t) && strcmp(tname, "pt_regs") == 0)
6794 			return true;
6795 		break;
6796 	case BPF_PROG_TYPE_PERF_EVENT:
6797 		if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct pt_regs) &&
6798 		    btf_is_struct(t) && strcmp(tname, "pt_regs") == 0)
6799 			return true;
6800 		if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct user_pt_regs) &&
6801 		    btf_is_struct(t) && strcmp(tname, "user_pt_regs") == 0)
6802 			return true;
6803 		if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct user_regs_struct) &&
6804 		    btf_is_struct(t) && strcmp(tname, "user_regs_struct") == 0)
6805 			return true;
6806 		break;
6807 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
6808 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
6809 		/* allow u64* as ctx */
6810 		if (btf_is_int(t) && t->size == 8)
6811 			return true;
6812 		break;
6813 	default:
6814 		break;
6815 	}
6816 
6817 out_warn:
6818 	pr_warn("prog '%s': subprog '%s' arg#%d is expected to be of `struct %s *` type\n",
6819 		prog->name, subprog_name, arg_idx, ctx_name);
6820 	return false;
6821 }
6822 
6823 static int clone_func_btf_info(struct btf *btf, int orig_fn_id, struct bpf_program *prog)
6824 {
6825 	int fn_id, fn_proto_id, ret_type_id, orig_proto_id;
6826 	int i, err, arg_cnt, fn_name_off, linkage;
6827 	struct btf_type *fn_t, *fn_proto_t, *t;
6828 	struct btf_param *p;
6829 
6830 	/* caller already validated FUNC -> FUNC_PROTO validity */
6831 	fn_t = btf_type_by_id(btf, orig_fn_id);
6832 	fn_proto_t = btf_type_by_id(btf, fn_t->type);
6833 
6834 	/* Note that each btf__add_xxx() operation invalidates
6835 	 * all btf_type and string pointers, so we need to be
6836 	 * very careful when cloning BTF types. BTF type
6837 	 * pointers have to be always refetched. And to avoid
6838 	 * problems with invalidated string pointers, we
6839 	 * add empty strings initially, then just fix up
6840 	 * name_off offsets in place. Offsets are stable for
6841 	 * existing strings, so that works out.
6842 	 */
6843 	fn_name_off = fn_t->name_off; /* we are about to invalidate fn_t */
6844 	linkage = btf_func_linkage(fn_t);
6845 	orig_proto_id = fn_t->type; /* original FUNC_PROTO ID */
6846 	ret_type_id = fn_proto_t->type; /* fn_proto_t will be invalidated */
6847 	arg_cnt = btf_vlen(fn_proto_t);
6848 
6849 	/* clone FUNC_PROTO and its params */
6850 	fn_proto_id = btf__add_func_proto(btf, ret_type_id);
6851 	if (fn_proto_id < 0)
6852 		return -EINVAL;
6853 
6854 	for (i = 0; i < arg_cnt; i++) {
6855 		int name_off;
6856 
6857 		/* copy original parameter data */
6858 		t = btf_type_by_id(btf, orig_proto_id);
6859 		p = &btf_params(t)[i];
6860 		name_off = p->name_off;
6861 
6862 		err = btf__add_func_param(btf, "", p->type);
6863 		if (err)
6864 			return err;
6865 
6866 		fn_proto_t = btf_type_by_id(btf, fn_proto_id);
6867 		p = &btf_params(fn_proto_t)[i];
6868 		p->name_off = name_off; /* use remembered str offset */
6869 	}
6870 
6871 	/* clone FUNC now, btf__add_func() enforces non-empty name, so use
6872 	 * entry program's name as a placeholder, which we replace immediately
6873 	 * with original name_off
6874 	 */
6875 	fn_id = btf__add_func(btf, prog->name, linkage, fn_proto_id);
6876 	if (fn_id < 0)
6877 		return -EINVAL;
6878 
6879 	fn_t = btf_type_by_id(btf, fn_id);
6880 	fn_t->name_off = fn_name_off; /* reuse original string */
6881 
6882 	return fn_id;
6883 }
6884 
6885 /* Check if main program or global subprog's function prototype has `arg:ctx`
6886  * argument tags, and, if necessary, substitute correct type to match what BPF
6887  * verifier would expect, taking into account specific program type. This
6888  * allows to support __arg_ctx tag transparently on old kernels that don't yet
6889  * have a native support for it in the verifier, making user's life much
6890  * easier.
6891  */
6892 static int bpf_program_fixup_func_info(struct bpf_object *obj, struct bpf_program *prog)
6893 {
6894 	const char *ctx_name = NULL, *ctx_tag = "arg:ctx", *fn_name;
6895 	struct bpf_func_info_min *func_rec;
6896 	struct btf_type *fn_t, *fn_proto_t;
6897 	struct btf *btf = obj->btf;
6898 	const struct btf_type *t;
6899 	struct btf_param *p;
6900 	int ptr_id = 0, struct_id, tag_id, orig_fn_id;
6901 	int i, n, arg_idx, arg_cnt, err, rec_idx;
6902 	int *orig_ids;
6903 
6904 	/* no .BTF.ext, no problem */
6905 	if (!obj->btf_ext || !prog->func_info)
6906 		return 0;
6907 
6908 	/* don't do any fix ups if kernel natively supports __arg_ctx */
6909 	if (kernel_supports(obj, FEAT_ARG_CTX_TAG))
6910 		return 0;
6911 
6912 	/* some BPF program types just don't have named context structs, so
6913 	 * this fallback mechanism doesn't work for them
6914 	 */
6915 	for (i = 0; i < ARRAY_SIZE(global_ctx_map); i++) {
6916 		if (global_ctx_map[i].prog_type != prog->type)
6917 			continue;
6918 		ctx_name = global_ctx_map[i].ctx_name;
6919 		break;
6920 	}
6921 	if (!ctx_name)
6922 		return 0;
6923 
6924 	/* remember original func BTF IDs to detect if we already cloned them */
6925 	orig_ids = calloc(prog->func_info_cnt, sizeof(*orig_ids));
6926 	if (!orig_ids)
6927 		return -ENOMEM;
6928 	for (i = 0; i < prog->func_info_cnt; i++) {
6929 		func_rec = prog->func_info + prog->func_info_rec_size * i;
6930 		orig_ids[i] = func_rec->type_id;
6931 	}
6932 
6933 	/* go through each DECL_TAG with "arg:ctx" and see if it points to one
6934 	 * of our subprogs; if yes and subprog is global and needs adjustment,
6935 	 * clone and adjust FUNC -> FUNC_PROTO combo
6936 	 */
6937 	for (i = 1, n = btf__type_cnt(btf); i < n; i++) {
6938 		/* only DECL_TAG with "arg:ctx" value are interesting */
6939 		t = btf__type_by_id(btf, i);
6940 		if (!btf_is_decl_tag(t))
6941 			continue;
6942 		if (strcmp(btf__str_by_offset(btf, t->name_off), ctx_tag) != 0)
6943 			continue;
6944 
6945 		/* only global funcs need adjustment, if at all */
6946 		orig_fn_id = t->type;
6947 		fn_t = btf_type_by_id(btf, orig_fn_id);
6948 		if (!btf_is_func(fn_t) || btf_func_linkage(fn_t) != BTF_FUNC_GLOBAL)
6949 			continue;
6950 
6951 		/* sanity check FUNC -> FUNC_PROTO chain, just in case */
6952 		fn_proto_t = btf_type_by_id(btf, fn_t->type);
6953 		if (!fn_proto_t || !btf_is_func_proto(fn_proto_t))
6954 			continue;
6955 
6956 		/* find corresponding func_info record */
6957 		func_rec = NULL;
6958 		for (rec_idx = 0; rec_idx < prog->func_info_cnt; rec_idx++) {
6959 			if (orig_ids[rec_idx] == t->type) {
6960 				func_rec = prog->func_info + prog->func_info_rec_size * rec_idx;
6961 				break;
6962 			}
6963 		}
6964 		/* current main program doesn't call into this subprog */
6965 		if (!func_rec)
6966 			continue;
6967 
6968 		/* some more sanity checking of DECL_TAG */
6969 		arg_cnt = btf_vlen(fn_proto_t);
6970 		arg_idx = btf_decl_tag(t)->component_idx;
6971 		if (arg_idx < 0 || arg_idx >= arg_cnt)
6972 			continue;
6973 
6974 		/* check if we should fix up argument type */
6975 		p = &btf_params(fn_proto_t)[arg_idx];
6976 		fn_name = btf__str_by_offset(btf, fn_t->name_off) ?: "<anon>";
6977 		if (!need_func_arg_type_fixup(btf, prog, fn_name, arg_idx, p->type, ctx_name))
6978 			continue;
6979 
6980 		/* clone fn/fn_proto, unless we already did it for another arg */
6981 		if (func_rec->type_id == orig_fn_id) {
6982 			int fn_id;
6983 
6984 			fn_id = clone_func_btf_info(btf, orig_fn_id, prog);
6985 			if (fn_id < 0) {
6986 				err = fn_id;
6987 				goto err_out;
6988 			}
6989 
6990 			/* point func_info record to a cloned FUNC type */
6991 			func_rec->type_id = fn_id;
6992 		}
6993 
6994 		/* create PTR -> STRUCT type chain to mark PTR_TO_CTX argument;
6995 		 * we do it just once per main BPF program, as all global
6996 		 * funcs share the same program type, so need only PTR ->
6997 		 * STRUCT type chain
6998 		 */
6999 		if (ptr_id == 0) {
7000 			struct_id = btf__add_struct(btf, ctx_name, 0);
7001 			ptr_id = btf__add_ptr(btf, struct_id);
7002 			if (ptr_id < 0 || struct_id < 0) {
7003 				err = -EINVAL;
7004 				goto err_out;
7005 			}
7006 		}
7007 
7008 		/* for completeness, clone DECL_TAG and point it to cloned param */
7009 		tag_id = btf__add_decl_tag(btf, ctx_tag, func_rec->type_id, arg_idx);
7010 		if (tag_id < 0) {
7011 			err = -EINVAL;
7012 			goto err_out;
7013 		}
7014 
7015 		/* all the BTF manipulations invalidated pointers, refetch them */
7016 		fn_t = btf_type_by_id(btf, func_rec->type_id);
7017 		fn_proto_t = btf_type_by_id(btf, fn_t->type);
7018 
7019 		/* fix up type ID pointed to by param */
7020 		p = &btf_params(fn_proto_t)[arg_idx];
7021 		p->type = ptr_id;
7022 	}
7023 
7024 	free(orig_ids);
7025 	return 0;
7026 err_out:
7027 	free(orig_ids);
7028 	return err;
7029 }
7030 
7031 static int bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
7032 {
7033 	struct bpf_program *prog;
7034 	size_t i, j;
7035 	int err;
7036 
7037 	if (obj->btf_ext) {
7038 		err = bpf_object__relocate_core(obj, targ_btf_path);
7039 		if (err) {
7040 			pr_warn("failed to perform CO-RE relocations: %d\n",
7041 				err);
7042 			return err;
7043 		}
7044 		bpf_object__sort_relos(obj);
7045 	}
7046 
7047 	/* Before relocating calls pre-process relocations and mark
7048 	 * few ld_imm64 instructions that points to subprogs.
7049 	 * Otherwise bpf_object__reloc_code() later would have to consider
7050 	 * all ld_imm64 insns as relocation candidates. That would
7051 	 * reduce relocation speed, since amount of find_prog_insn_relo()
7052 	 * would increase and most of them will fail to find a relo.
7053 	 */
7054 	for (i = 0; i < obj->nr_programs; i++) {
7055 		prog = &obj->programs[i];
7056 		for (j = 0; j < prog->nr_reloc; j++) {
7057 			struct reloc_desc *relo = &prog->reloc_desc[j];
7058 			struct bpf_insn *insn = &prog->insns[relo->insn_idx];
7059 
7060 			/* mark the insn, so it's recognized by insn_is_pseudo_func() */
7061 			if (relo->type == RELO_SUBPROG_ADDR)
7062 				insn[0].src_reg = BPF_PSEUDO_FUNC;
7063 		}
7064 	}
7065 
7066 	/* relocate subprogram calls and append used subprograms to main
7067 	 * programs; each copy of subprogram code needs to be relocated
7068 	 * differently for each main program, because its code location might
7069 	 * have changed.
7070 	 * Append subprog relos to main programs to allow data relos to be
7071 	 * processed after text is completely relocated.
7072 	 */
7073 	for (i = 0; i < obj->nr_programs; i++) {
7074 		prog = &obj->programs[i];
7075 		/* sub-program's sub-calls are relocated within the context of
7076 		 * its main program only
7077 		 */
7078 		if (prog_is_subprog(obj, prog))
7079 			continue;
7080 		if (!prog->autoload)
7081 			continue;
7082 
7083 		err = bpf_object__relocate_calls(obj, prog);
7084 		if (err) {
7085 			pr_warn("prog '%s': failed to relocate calls: %d\n",
7086 				prog->name, err);
7087 			return err;
7088 		}
7089 
7090 		err = bpf_prog_assign_exc_cb(obj, prog);
7091 		if (err)
7092 			return err;
7093 		/* Now, also append exception callback if it has not been done already. */
7094 		if (prog->exception_cb_idx >= 0) {
7095 			struct bpf_program *subprog = &obj->programs[prog->exception_cb_idx];
7096 
7097 			/* Calling exception callback directly is disallowed, which the
7098 			 * verifier will reject later. In case it was processed already,
7099 			 * we can skip this step, otherwise for all other valid cases we
7100 			 * have to append exception callback now.
7101 			 */
7102 			if (subprog->sub_insn_off == 0) {
7103 				err = bpf_object__append_subprog_code(obj, prog, subprog);
7104 				if (err)
7105 					return err;
7106 				err = bpf_object__reloc_code(obj, prog, subprog);
7107 				if (err)
7108 					return err;
7109 			}
7110 		}
7111 	}
7112 	for (i = 0; i < obj->nr_programs; i++) {
7113 		prog = &obj->programs[i];
7114 		if (prog_is_subprog(obj, prog))
7115 			continue;
7116 		if (!prog->autoload)
7117 			continue;
7118 
7119 		/* Process data relos for main programs */
7120 		err = bpf_object__relocate_data(obj, prog);
7121 		if (err) {
7122 			pr_warn("prog '%s': failed to relocate data references: %d\n",
7123 				prog->name, err);
7124 			return err;
7125 		}
7126 
7127 		/* Fix up .BTF.ext information, if necessary */
7128 		err = bpf_program_fixup_func_info(obj, prog);
7129 		if (err) {
7130 			pr_warn("prog '%s': failed to perform .BTF.ext fix ups: %d\n",
7131 				prog->name, err);
7132 			return err;
7133 		}
7134 	}
7135 
7136 	return 0;
7137 }
7138 
7139 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
7140 					    Elf64_Shdr *shdr, Elf_Data *data);
7141 
7142 static int bpf_object__collect_map_relos(struct bpf_object *obj,
7143 					 Elf64_Shdr *shdr, Elf_Data *data)
7144 {
7145 	const int bpf_ptr_sz = 8, host_ptr_sz = sizeof(void *);
7146 	int i, j, nrels, new_sz;
7147 	const struct btf_var_secinfo *vi = NULL;
7148 	const struct btf_type *sec, *var, *def;
7149 	struct bpf_map *map = NULL, *targ_map = NULL;
7150 	struct bpf_program *targ_prog = NULL;
7151 	bool is_prog_array, is_map_in_map;
7152 	const struct btf_member *member;
7153 	const char *name, *mname, *type;
7154 	unsigned int moff;
7155 	Elf64_Sym *sym;
7156 	Elf64_Rel *rel;
7157 	void *tmp;
7158 
7159 	if (!obj->efile.btf_maps_sec_btf_id || !obj->btf)
7160 		return -EINVAL;
7161 	sec = btf__type_by_id(obj->btf, obj->efile.btf_maps_sec_btf_id);
7162 	if (!sec)
7163 		return -EINVAL;
7164 
7165 	nrels = shdr->sh_size / shdr->sh_entsize;
7166 	for (i = 0; i < nrels; i++) {
7167 		rel = elf_rel_by_idx(data, i);
7168 		if (!rel) {
7169 			pr_warn(".maps relo #%d: failed to get ELF relo\n", i);
7170 			return -LIBBPF_ERRNO__FORMAT;
7171 		}
7172 
7173 		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
7174 		if (!sym) {
7175 			pr_warn(".maps relo #%d: symbol %zx not found\n",
7176 				i, (size_t)ELF64_R_SYM(rel->r_info));
7177 			return -LIBBPF_ERRNO__FORMAT;
7178 		}
7179 		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
7180 
7181 		pr_debug(".maps relo #%d: for %zd value %zd rel->r_offset %zu name %d ('%s')\n",
7182 			 i, (ssize_t)(rel->r_info >> 32), (size_t)sym->st_value,
7183 			 (size_t)rel->r_offset, sym->st_name, name);
7184 
7185 		for (j = 0; j < obj->nr_maps; j++) {
7186 			map = &obj->maps[j];
7187 			if (map->sec_idx != obj->efile.btf_maps_shndx)
7188 				continue;
7189 
7190 			vi = btf_var_secinfos(sec) + map->btf_var_idx;
7191 			if (vi->offset <= rel->r_offset &&
7192 			    rel->r_offset + bpf_ptr_sz <= vi->offset + vi->size)
7193 				break;
7194 		}
7195 		if (j == obj->nr_maps) {
7196 			pr_warn(".maps relo #%d: cannot find map '%s' at rel->r_offset %zu\n",
7197 				i, name, (size_t)rel->r_offset);
7198 			return -EINVAL;
7199 		}
7200 
7201 		is_map_in_map = bpf_map_type__is_map_in_map(map->def.type);
7202 		is_prog_array = map->def.type == BPF_MAP_TYPE_PROG_ARRAY;
7203 		type = is_map_in_map ? "map" : "prog";
7204 		if (is_map_in_map) {
7205 			if (sym->st_shndx != obj->efile.btf_maps_shndx) {
7206 				pr_warn(".maps relo #%d: '%s' isn't a BTF-defined map\n",
7207 					i, name);
7208 				return -LIBBPF_ERRNO__RELOC;
7209 			}
7210 			if (map->def.type == BPF_MAP_TYPE_HASH_OF_MAPS &&
7211 			    map->def.key_size != sizeof(int)) {
7212 				pr_warn(".maps relo #%d: hash-of-maps '%s' should have key size %zu.\n",
7213 					i, map->name, sizeof(int));
7214 				return -EINVAL;
7215 			}
7216 			targ_map = bpf_object__find_map_by_name(obj, name);
7217 			if (!targ_map) {
7218 				pr_warn(".maps relo #%d: '%s' isn't a valid map reference\n",
7219 					i, name);
7220 				return -ESRCH;
7221 			}
7222 		} else if (is_prog_array) {
7223 			targ_prog = bpf_object__find_program_by_name(obj, name);
7224 			if (!targ_prog) {
7225 				pr_warn(".maps relo #%d: '%s' isn't a valid program reference\n",
7226 					i, name);
7227 				return -ESRCH;
7228 			}
7229 			if (targ_prog->sec_idx != sym->st_shndx ||
7230 			    targ_prog->sec_insn_off * 8 != sym->st_value ||
7231 			    prog_is_subprog(obj, targ_prog)) {
7232 				pr_warn(".maps relo #%d: '%s' isn't an entry-point program\n",
7233 					i, name);
7234 				return -LIBBPF_ERRNO__RELOC;
7235 			}
7236 		} else {
7237 			return -EINVAL;
7238 		}
7239 
7240 		var = btf__type_by_id(obj->btf, vi->type);
7241 		def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
7242 		if (btf_vlen(def) == 0)
7243 			return -EINVAL;
7244 		member = btf_members(def) + btf_vlen(def) - 1;
7245 		mname = btf__name_by_offset(obj->btf, member->name_off);
7246 		if (strcmp(mname, "values"))
7247 			return -EINVAL;
7248 
7249 		moff = btf_member_bit_offset(def, btf_vlen(def) - 1) / 8;
7250 		if (rel->r_offset - vi->offset < moff)
7251 			return -EINVAL;
7252 
7253 		moff = rel->r_offset - vi->offset - moff;
7254 		/* here we use BPF pointer size, which is always 64 bit, as we
7255 		 * are parsing ELF that was built for BPF target
7256 		 */
7257 		if (moff % bpf_ptr_sz)
7258 			return -EINVAL;
7259 		moff /= bpf_ptr_sz;
7260 		if (moff >= map->init_slots_sz) {
7261 			new_sz = moff + 1;
7262 			tmp = libbpf_reallocarray(map->init_slots, new_sz, host_ptr_sz);
7263 			if (!tmp)
7264 				return -ENOMEM;
7265 			map->init_slots = tmp;
7266 			memset(map->init_slots + map->init_slots_sz, 0,
7267 			       (new_sz - map->init_slots_sz) * host_ptr_sz);
7268 			map->init_slots_sz = new_sz;
7269 		}
7270 		map->init_slots[moff] = is_map_in_map ? (void *)targ_map : (void *)targ_prog;
7271 
7272 		pr_debug(".maps relo #%d: map '%s' slot [%d] points to %s '%s'\n",
7273 			 i, map->name, moff, type, name);
7274 	}
7275 
7276 	return 0;
7277 }
7278 
7279 static int bpf_object__collect_relos(struct bpf_object *obj)
7280 {
7281 	int i, err;
7282 
7283 	for (i = 0; i < obj->efile.sec_cnt; i++) {
7284 		struct elf_sec_desc *sec_desc = &obj->efile.secs[i];
7285 		Elf64_Shdr *shdr;
7286 		Elf_Data *data;
7287 		int idx;
7288 
7289 		if (sec_desc->sec_type != SEC_RELO)
7290 			continue;
7291 
7292 		shdr = sec_desc->shdr;
7293 		data = sec_desc->data;
7294 		idx = shdr->sh_info;
7295 
7296 		if (shdr->sh_type != SHT_REL || idx < 0 || idx >= obj->efile.sec_cnt) {
7297 			pr_warn("internal error at %d\n", __LINE__);
7298 			return -LIBBPF_ERRNO__INTERNAL;
7299 		}
7300 
7301 		if (obj->efile.secs[idx].sec_type == SEC_ST_OPS)
7302 			err = bpf_object__collect_st_ops_relos(obj, shdr, data);
7303 		else if (idx == obj->efile.btf_maps_shndx)
7304 			err = bpf_object__collect_map_relos(obj, shdr, data);
7305 		else
7306 			err = bpf_object__collect_prog_relos(obj, shdr, data);
7307 		if (err)
7308 			return err;
7309 	}
7310 
7311 	bpf_object__sort_relos(obj);
7312 	return 0;
7313 }
7314 
7315 static bool insn_is_helper_call(struct bpf_insn *insn, enum bpf_func_id *func_id)
7316 {
7317 	if (BPF_CLASS(insn->code) == BPF_JMP &&
7318 	    BPF_OP(insn->code) == BPF_CALL &&
7319 	    BPF_SRC(insn->code) == BPF_K &&
7320 	    insn->src_reg == 0 &&
7321 	    insn->dst_reg == 0) {
7322 		    *func_id = insn->imm;
7323 		    return true;
7324 	}
7325 	return false;
7326 }
7327 
7328 static int bpf_object__sanitize_prog(struct bpf_object *obj, struct bpf_program *prog)
7329 {
7330 	struct bpf_insn *insn = prog->insns;
7331 	enum bpf_func_id func_id;
7332 	int i;
7333 
7334 	if (obj->gen_loader)
7335 		return 0;
7336 
7337 	for (i = 0; i < prog->insns_cnt; i++, insn++) {
7338 		if (!insn_is_helper_call(insn, &func_id))
7339 			continue;
7340 
7341 		/* on kernels that don't yet support
7342 		 * bpf_probe_read_{kernel,user}[_str] helpers, fall back
7343 		 * to bpf_probe_read() which works well for old kernels
7344 		 */
7345 		switch (func_id) {
7346 		case BPF_FUNC_probe_read_kernel:
7347 		case BPF_FUNC_probe_read_user:
7348 			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
7349 				insn->imm = BPF_FUNC_probe_read;
7350 			break;
7351 		case BPF_FUNC_probe_read_kernel_str:
7352 		case BPF_FUNC_probe_read_user_str:
7353 			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
7354 				insn->imm = BPF_FUNC_probe_read_str;
7355 			break;
7356 		default:
7357 			break;
7358 		}
7359 	}
7360 	return 0;
7361 }
7362 
7363 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
7364 				     int *btf_obj_fd, int *btf_type_id);
7365 
7366 /* this is called as prog->sec_def->prog_prepare_load_fn for libbpf-supported sec_defs */
7367 static int libbpf_prepare_prog_load(struct bpf_program *prog,
7368 				    struct bpf_prog_load_opts *opts, long cookie)
7369 {
7370 	enum sec_def_flags def = cookie;
7371 
7372 	/* old kernels might not support specifying expected_attach_type */
7373 	if ((def & SEC_EXP_ATTACH_OPT) && !kernel_supports(prog->obj, FEAT_EXP_ATTACH_TYPE))
7374 		opts->expected_attach_type = 0;
7375 
7376 	if (def & SEC_SLEEPABLE)
7377 		opts->prog_flags |= BPF_F_SLEEPABLE;
7378 
7379 	if (prog->type == BPF_PROG_TYPE_XDP && (def & SEC_XDP_FRAGS))
7380 		opts->prog_flags |= BPF_F_XDP_HAS_FRAGS;
7381 
7382 	/* special check for usdt to use uprobe_multi link */
7383 	if ((def & SEC_USDT) && kernel_supports(prog->obj, FEAT_UPROBE_MULTI_LINK)) {
7384 		/* for BPF_TRACE_UPROBE_MULTI, user might want to query expected_attach_type
7385 		 * in prog, and expected_attach_type we set in kernel is from opts, so we
7386 		 * update both.
7387 		 */
7388 		prog->expected_attach_type = BPF_TRACE_UPROBE_MULTI;
7389 		opts->expected_attach_type = BPF_TRACE_UPROBE_MULTI;
7390 	}
7391 
7392 	if ((def & SEC_ATTACH_BTF) && !prog->attach_btf_id) {
7393 		int btf_obj_fd = 0, btf_type_id = 0, err;
7394 		const char *attach_name;
7395 
7396 		attach_name = strchr(prog->sec_name, '/');
7397 		if (!attach_name) {
7398 			/* if BPF program is annotated with just SEC("fentry")
7399 			 * (or similar) without declaratively specifying
7400 			 * target, then it is expected that target will be
7401 			 * specified with bpf_program__set_attach_target() at
7402 			 * runtime before BPF object load step. If not, then
7403 			 * there is nothing to load into the kernel as BPF
7404 			 * verifier won't be able to validate BPF program
7405 			 * correctness anyways.
7406 			 */
7407 			pr_warn("prog '%s': no BTF-based attach target is specified, use bpf_program__set_attach_target()\n",
7408 				prog->name);
7409 			return -EINVAL;
7410 		}
7411 		attach_name++; /* skip over / */
7412 
7413 		err = libbpf_find_attach_btf_id(prog, attach_name, &btf_obj_fd, &btf_type_id);
7414 		if (err)
7415 			return err;
7416 
7417 		/* cache resolved BTF FD and BTF type ID in the prog */
7418 		prog->attach_btf_obj_fd = btf_obj_fd;
7419 		prog->attach_btf_id = btf_type_id;
7420 
7421 		/* but by now libbpf common logic is not utilizing
7422 		 * prog->atach_btf_obj_fd/prog->attach_btf_id anymore because
7423 		 * this callback is called after opts were populated by
7424 		 * libbpf, so this callback has to update opts explicitly here
7425 		 */
7426 		opts->attach_btf_obj_fd = btf_obj_fd;
7427 		opts->attach_btf_id = btf_type_id;
7428 	}
7429 	return 0;
7430 }
7431 
7432 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz);
7433 
7434 static int bpf_object_load_prog(struct bpf_object *obj, struct bpf_program *prog,
7435 				struct bpf_insn *insns, int insns_cnt,
7436 				const char *license, __u32 kern_version, int *prog_fd)
7437 {
7438 	LIBBPF_OPTS(bpf_prog_load_opts, load_attr);
7439 	const char *prog_name = NULL;
7440 	char *cp, errmsg[STRERR_BUFSIZE];
7441 	size_t log_buf_size = 0;
7442 	char *log_buf = NULL, *tmp;
7443 	bool own_log_buf = true;
7444 	__u32 log_level = prog->log_level;
7445 	int ret, err;
7446 
7447 	/* Be more helpful by rejecting programs that can't be validated early
7448 	 * with more meaningful and actionable error message.
7449 	 */
7450 	switch (prog->type) {
7451 	case BPF_PROG_TYPE_UNSPEC:
7452 		/*
7453 		 * The program type must be set.  Most likely we couldn't find a proper
7454 		 * section definition at load time, and thus we didn't infer the type.
7455 		 */
7456 		pr_warn("prog '%s': missing BPF prog type, check ELF section name '%s'\n",
7457 			prog->name, prog->sec_name);
7458 		return -EINVAL;
7459 	case BPF_PROG_TYPE_STRUCT_OPS:
7460 		if (prog->attach_btf_id == 0) {
7461 			pr_warn("prog '%s': SEC(\"struct_ops\") program isn't referenced anywhere, did you forget to use it?\n",
7462 				prog->name);
7463 			return -EINVAL;
7464 		}
7465 		break;
7466 	default:
7467 		break;
7468 	}
7469 
7470 	if (!insns || !insns_cnt)
7471 		return -EINVAL;
7472 
7473 	if (kernel_supports(obj, FEAT_PROG_NAME))
7474 		prog_name = prog->name;
7475 	load_attr.attach_prog_fd = prog->attach_prog_fd;
7476 	load_attr.attach_btf_obj_fd = prog->attach_btf_obj_fd;
7477 	load_attr.attach_btf_id = prog->attach_btf_id;
7478 	load_attr.kern_version = kern_version;
7479 	load_attr.prog_ifindex = prog->prog_ifindex;
7480 	load_attr.expected_attach_type = prog->expected_attach_type;
7481 
7482 	/* specify func_info/line_info only if kernel supports them */
7483 	if (obj->btf && btf__fd(obj->btf) >= 0 && kernel_supports(obj, FEAT_BTF_FUNC)) {
7484 		load_attr.prog_btf_fd = btf__fd(obj->btf);
7485 		load_attr.func_info = prog->func_info;
7486 		load_attr.func_info_rec_size = prog->func_info_rec_size;
7487 		load_attr.func_info_cnt = prog->func_info_cnt;
7488 		load_attr.line_info = prog->line_info;
7489 		load_attr.line_info_rec_size = prog->line_info_rec_size;
7490 		load_attr.line_info_cnt = prog->line_info_cnt;
7491 	}
7492 	load_attr.log_level = log_level;
7493 	load_attr.prog_flags = prog->prog_flags;
7494 	load_attr.fd_array = obj->fd_array;
7495 
7496 	load_attr.token_fd = obj->token_fd;
7497 	if (obj->token_fd)
7498 		load_attr.prog_flags |= BPF_F_TOKEN_FD;
7499 
7500 	/* adjust load_attr if sec_def provides custom preload callback */
7501 	if (prog->sec_def && prog->sec_def->prog_prepare_load_fn) {
7502 		err = prog->sec_def->prog_prepare_load_fn(prog, &load_attr, prog->sec_def->cookie);
7503 		if (err < 0) {
7504 			pr_warn("prog '%s': failed to prepare load attributes: %d\n",
7505 				prog->name, err);
7506 			return err;
7507 		}
7508 		insns = prog->insns;
7509 		insns_cnt = prog->insns_cnt;
7510 	}
7511 
7512 	if (obj->gen_loader) {
7513 		bpf_gen__prog_load(obj->gen_loader, prog->type, prog->name,
7514 				   license, insns, insns_cnt, &load_attr,
7515 				   prog - obj->programs);
7516 		*prog_fd = -1;
7517 		return 0;
7518 	}
7519 
7520 retry_load:
7521 	/* if log_level is zero, we don't request logs initially even if
7522 	 * custom log_buf is specified; if the program load fails, then we'll
7523 	 * bump log_level to 1 and use either custom log_buf or we'll allocate
7524 	 * our own and retry the load to get details on what failed
7525 	 */
7526 	if (log_level) {
7527 		if (prog->log_buf) {
7528 			log_buf = prog->log_buf;
7529 			log_buf_size = prog->log_size;
7530 			own_log_buf = false;
7531 		} else if (obj->log_buf) {
7532 			log_buf = obj->log_buf;
7533 			log_buf_size = obj->log_size;
7534 			own_log_buf = false;
7535 		} else {
7536 			log_buf_size = max((size_t)BPF_LOG_BUF_SIZE, log_buf_size * 2);
7537 			tmp = realloc(log_buf, log_buf_size);
7538 			if (!tmp) {
7539 				ret = -ENOMEM;
7540 				goto out;
7541 			}
7542 			log_buf = tmp;
7543 			log_buf[0] = '\0';
7544 			own_log_buf = true;
7545 		}
7546 	}
7547 
7548 	load_attr.log_buf = log_buf;
7549 	load_attr.log_size = log_buf_size;
7550 	load_attr.log_level = log_level;
7551 
7552 	ret = bpf_prog_load(prog->type, prog_name, license, insns, insns_cnt, &load_attr);
7553 	if (ret >= 0) {
7554 		if (log_level && own_log_buf) {
7555 			pr_debug("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
7556 				 prog->name, log_buf);
7557 		}
7558 
7559 		if (obj->has_rodata && kernel_supports(obj, FEAT_PROG_BIND_MAP)) {
7560 			struct bpf_map *map;
7561 			int i;
7562 
7563 			for (i = 0; i < obj->nr_maps; i++) {
7564 				map = &prog->obj->maps[i];
7565 				if (map->libbpf_type != LIBBPF_MAP_RODATA)
7566 					continue;
7567 
7568 				if (bpf_prog_bind_map(ret, map->fd, NULL)) {
7569 					cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
7570 					pr_warn("prog '%s': failed to bind map '%s': %s\n",
7571 						prog->name, map->real_name, cp);
7572 					/* Don't fail hard if can't bind rodata. */
7573 				}
7574 			}
7575 		}
7576 
7577 		*prog_fd = ret;
7578 		ret = 0;
7579 		goto out;
7580 	}
7581 
7582 	if (log_level == 0) {
7583 		log_level = 1;
7584 		goto retry_load;
7585 	}
7586 	/* On ENOSPC, increase log buffer size and retry, unless custom
7587 	 * log_buf is specified.
7588 	 * Be careful to not overflow u32, though. Kernel's log buf size limit
7589 	 * isn't part of UAPI so it can always be bumped to full 4GB. So don't
7590 	 * multiply by 2 unless we are sure we'll fit within 32 bits.
7591 	 * Currently, we'll get -EINVAL when we reach (UINT_MAX >> 2).
7592 	 */
7593 	if (own_log_buf && errno == ENOSPC && log_buf_size <= UINT_MAX / 2)
7594 		goto retry_load;
7595 
7596 	ret = -errno;
7597 
7598 	/* post-process verifier log to improve error descriptions */
7599 	fixup_verifier_log(prog, log_buf, log_buf_size);
7600 
7601 	cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
7602 	pr_warn("prog '%s': BPF program load failed: %s\n", prog->name, cp);
7603 	pr_perm_msg(ret);
7604 
7605 	if (own_log_buf && log_buf && log_buf[0] != '\0') {
7606 		pr_warn("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
7607 			prog->name, log_buf);
7608 	}
7609 
7610 out:
7611 	if (own_log_buf)
7612 		free(log_buf);
7613 	return ret;
7614 }
7615 
7616 static char *find_prev_line(char *buf, char *cur)
7617 {
7618 	char *p;
7619 
7620 	if (cur == buf) /* end of a log buf */
7621 		return NULL;
7622 
7623 	p = cur - 1;
7624 	while (p - 1 >= buf && *(p - 1) != '\n')
7625 		p--;
7626 
7627 	return p;
7628 }
7629 
7630 static void patch_log(char *buf, size_t buf_sz, size_t log_sz,
7631 		      char *orig, size_t orig_sz, const char *patch)
7632 {
7633 	/* size of the remaining log content to the right from the to-be-replaced part */
7634 	size_t rem_sz = (buf + log_sz) - (orig + orig_sz);
7635 	size_t patch_sz = strlen(patch);
7636 
7637 	if (patch_sz != orig_sz) {
7638 		/* If patch line(s) are longer than original piece of verifier log,
7639 		 * shift log contents by (patch_sz - orig_sz) bytes to the right
7640 		 * starting from after to-be-replaced part of the log.
7641 		 *
7642 		 * If patch line(s) are shorter than original piece of verifier log,
7643 		 * shift log contents by (orig_sz - patch_sz) bytes to the left
7644 		 * starting from after to-be-replaced part of the log
7645 		 *
7646 		 * We need to be careful about not overflowing available
7647 		 * buf_sz capacity. If that's the case, we'll truncate the end
7648 		 * of the original log, as necessary.
7649 		 */
7650 		if (patch_sz > orig_sz) {
7651 			if (orig + patch_sz >= buf + buf_sz) {
7652 				/* patch is big enough to cover remaining space completely */
7653 				patch_sz -= (orig + patch_sz) - (buf + buf_sz) + 1;
7654 				rem_sz = 0;
7655 			} else if (patch_sz - orig_sz > buf_sz - log_sz) {
7656 				/* patch causes part of remaining log to be truncated */
7657 				rem_sz -= (patch_sz - orig_sz) - (buf_sz - log_sz);
7658 			}
7659 		}
7660 		/* shift remaining log to the right by calculated amount */
7661 		memmove(orig + patch_sz, orig + orig_sz, rem_sz);
7662 	}
7663 
7664 	memcpy(orig, patch, patch_sz);
7665 }
7666 
7667 static void fixup_log_failed_core_relo(struct bpf_program *prog,
7668 				       char *buf, size_t buf_sz, size_t log_sz,
7669 				       char *line1, char *line2, char *line3)
7670 {
7671 	/* Expected log for failed and not properly guarded CO-RE relocation:
7672 	 * line1 -> 123: (85) call unknown#195896080
7673 	 * line2 -> invalid func unknown#195896080
7674 	 * line3 -> <anything else or end of buffer>
7675 	 *
7676 	 * "123" is the index of the instruction that was poisoned. We extract
7677 	 * instruction index to find corresponding CO-RE relocation and
7678 	 * replace this part of the log with more relevant information about
7679 	 * failed CO-RE relocation.
7680 	 */
7681 	const struct bpf_core_relo *relo;
7682 	struct bpf_core_spec spec;
7683 	char patch[512], spec_buf[256];
7684 	int insn_idx, err, spec_len;
7685 
7686 	if (sscanf(line1, "%d: (%*d) call unknown#195896080\n", &insn_idx) != 1)
7687 		return;
7688 
7689 	relo = find_relo_core(prog, insn_idx);
7690 	if (!relo)
7691 		return;
7692 
7693 	err = bpf_core_parse_spec(prog->name, prog->obj->btf, relo, &spec);
7694 	if (err)
7695 		return;
7696 
7697 	spec_len = bpf_core_format_spec(spec_buf, sizeof(spec_buf), &spec);
7698 	snprintf(patch, sizeof(patch),
7699 		 "%d: <invalid CO-RE relocation>\n"
7700 		 "failed to resolve CO-RE relocation %s%s\n",
7701 		 insn_idx, spec_buf, spec_len >= sizeof(spec_buf) ? "..." : "");
7702 
7703 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7704 }
7705 
7706 static void fixup_log_missing_map_load(struct bpf_program *prog,
7707 				       char *buf, size_t buf_sz, size_t log_sz,
7708 				       char *line1, char *line2, char *line3)
7709 {
7710 	/* Expected log for failed and not properly guarded map reference:
7711 	 * line1 -> 123: (85) call unknown#2001000345
7712 	 * line2 -> invalid func unknown#2001000345
7713 	 * line3 -> <anything else or end of buffer>
7714 	 *
7715 	 * "123" is the index of the instruction that was poisoned.
7716 	 * "345" in "2001000345" is a map index in obj->maps to fetch map name.
7717 	 */
7718 	struct bpf_object *obj = prog->obj;
7719 	const struct bpf_map *map;
7720 	int insn_idx, map_idx;
7721 	char patch[128];
7722 
7723 	if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &map_idx) != 2)
7724 		return;
7725 
7726 	map_idx -= POISON_LDIMM64_MAP_BASE;
7727 	if (map_idx < 0 || map_idx >= obj->nr_maps)
7728 		return;
7729 	map = &obj->maps[map_idx];
7730 
7731 	snprintf(patch, sizeof(patch),
7732 		 "%d: <invalid BPF map reference>\n"
7733 		 "BPF map '%s' is referenced but wasn't created\n",
7734 		 insn_idx, map->name);
7735 
7736 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7737 }
7738 
7739 static void fixup_log_missing_kfunc_call(struct bpf_program *prog,
7740 					 char *buf, size_t buf_sz, size_t log_sz,
7741 					 char *line1, char *line2, char *line3)
7742 {
7743 	/* Expected log for failed and not properly guarded kfunc call:
7744 	 * line1 -> 123: (85) call unknown#2002000345
7745 	 * line2 -> invalid func unknown#2002000345
7746 	 * line3 -> <anything else or end of buffer>
7747 	 *
7748 	 * "123" is the index of the instruction that was poisoned.
7749 	 * "345" in "2002000345" is an extern index in obj->externs to fetch kfunc name.
7750 	 */
7751 	struct bpf_object *obj = prog->obj;
7752 	const struct extern_desc *ext;
7753 	int insn_idx, ext_idx;
7754 	char patch[128];
7755 
7756 	if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &ext_idx) != 2)
7757 		return;
7758 
7759 	ext_idx -= POISON_CALL_KFUNC_BASE;
7760 	if (ext_idx < 0 || ext_idx >= obj->nr_extern)
7761 		return;
7762 	ext = &obj->externs[ext_idx];
7763 
7764 	snprintf(patch, sizeof(patch),
7765 		 "%d: <invalid kfunc call>\n"
7766 		 "kfunc '%s' is referenced but wasn't resolved\n",
7767 		 insn_idx, ext->name);
7768 
7769 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7770 }
7771 
7772 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz)
7773 {
7774 	/* look for familiar error patterns in last N lines of the log */
7775 	const size_t max_last_line_cnt = 10;
7776 	char *prev_line, *cur_line, *next_line;
7777 	size_t log_sz;
7778 	int i;
7779 
7780 	if (!buf)
7781 		return;
7782 
7783 	log_sz = strlen(buf) + 1;
7784 	next_line = buf + log_sz - 1;
7785 
7786 	for (i = 0; i < max_last_line_cnt; i++, next_line = cur_line) {
7787 		cur_line = find_prev_line(buf, next_line);
7788 		if (!cur_line)
7789 			return;
7790 
7791 		if (str_has_pfx(cur_line, "invalid func unknown#195896080\n")) {
7792 			prev_line = find_prev_line(buf, cur_line);
7793 			if (!prev_line)
7794 				continue;
7795 
7796 			/* failed CO-RE relocation case */
7797 			fixup_log_failed_core_relo(prog, buf, buf_sz, log_sz,
7798 						   prev_line, cur_line, next_line);
7799 			return;
7800 		} else if (str_has_pfx(cur_line, "invalid func unknown#"POISON_LDIMM64_MAP_PFX)) {
7801 			prev_line = find_prev_line(buf, cur_line);
7802 			if (!prev_line)
7803 				continue;
7804 
7805 			/* reference to uncreated BPF map */
7806 			fixup_log_missing_map_load(prog, buf, buf_sz, log_sz,
7807 						   prev_line, cur_line, next_line);
7808 			return;
7809 		} else if (str_has_pfx(cur_line, "invalid func unknown#"POISON_CALL_KFUNC_PFX)) {
7810 			prev_line = find_prev_line(buf, cur_line);
7811 			if (!prev_line)
7812 				continue;
7813 
7814 			/* reference to unresolved kfunc */
7815 			fixup_log_missing_kfunc_call(prog, buf, buf_sz, log_sz,
7816 						     prev_line, cur_line, next_line);
7817 			return;
7818 		}
7819 	}
7820 }
7821 
7822 static int bpf_program_record_relos(struct bpf_program *prog)
7823 {
7824 	struct bpf_object *obj = prog->obj;
7825 	int i;
7826 
7827 	for (i = 0; i < prog->nr_reloc; i++) {
7828 		struct reloc_desc *relo = &prog->reloc_desc[i];
7829 		struct extern_desc *ext = &obj->externs[relo->ext_idx];
7830 		int kind;
7831 
7832 		switch (relo->type) {
7833 		case RELO_EXTERN_LD64:
7834 			if (ext->type != EXT_KSYM)
7835 				continue;
7836 			kind = btf_is_var(btf__type_by_id(obj->btf, ext->btf_id)) ?
7837 				BTF_KIND_VAR : BTF_KIND_FUNC;
7838 			bpf_gen__record_extern(obj->gen_loader, ext->name,
7839 					       ext->is_weak, !ext->ksym.type_id,
7840 					       true, kind, relo->insn_idx);
7841 			break;
7842 		case RELO_EXTERN_CALL:
7843 			bpf_gen__record_extern(obj->gen_loader, ext->name,
7844 					       ext->is_weak, false, false, BTF_KIND_FUNC,
7845 					       relo->insn_idx);
7846 			break;
7847 		case RELO_CORE: {
7848 			struct bpf_core_relo cr = {
7849 				.insn_off = relo->insn_idx * 8,
7850 				.type_id = relo->core_relo->type_id,
7851 				.access_str_off = relo->core_relo->access_str_off,
7852 				.kind = relo->core_relo->kind,
7853 			};
7854 
7855 			bpf_gen__record_relo_core(obj->gen_loader, &cr);
7856 			break;
7857 		}
7858 		default:
7859 			continue;
7860 		}
7861 	}
7862 	return 0;
7863 }
7864 
7865 static int
7866 bpf_object__load_progs(struct bpf_object *obj, int log_level)
7867 {
7868 	struct bpf_program *prog;
7869 	size_t i;
7870 	int err;
7871 
7872 	for (i = 0; i < obj->nr_programs; i++) {
7873 		prog = &obj->programs[i];
7874 		err = bpf_object__sanitize_prog(obj, prog);
7875 		if (err)
7876 			return err;
7877 	}
7878 
7879 	for (i = 0; i < obj->nr_programs; i++) {
7880 		prog = &obj->programs[i];
7881 		if (prog_is_subprog(obj, prog))
7882 			continue;
7883 		if (!prog->autoload) {
7884 			pr_debug("prog '%s': skipped loading\n", prog->name);
7885 			continue;
7886 		}
7887 		prog->log_level |= log_level;
7888 
7889 		if (obj->gen_loader)
7890 			bpf_program_record_relos(prog);
7891 
7892 		err = bpf_object_load_prog(obj, prog, prog->insns, prog->insns_cnt,
7893 					   obj->license, obj->kern_version, &prog->fd);
7894 		if (err) {
7895 			pr_warn("prog '%s': failed to load: %d\n", prog->name, err);
7896 			return err;
7897 		}
7898 	}
7899 
7900 	bpf_object__free_relocs(obj);
7901 	return 0;
7902 }
7903 
7904 static const struct bpf_sec_def *find_sec_def(const char *sec_name);
7905 
7906 static int bpf_object_init_progs(struct bpf_object *obj, const struct bpf_object_open_opts *opts)
7907 {
7908 	struct bpf_program *prog;
7909 	int err;
7910 
7911 	bpf_object__for_each_program(prog, obj) {
7912 		prog->sec_def = find_sec_def(prog->sec_name);
7913 		if (!prog->sec_def) {
7914 			/* couldn't guess, but user might manually specify */
7915 			pr_debug("prog '%s': unrecognized ELF section name '%s'\n",
7916 				prog->name, prog->sec_name);
7917 			continue;
7918 		}
7919 
7920 		prog->type = prog->sec_def->prog_type;
7921 		prog->expected_attach_type = prog->sec_def->expected_attach_type;
7922 
7923 		/* sec_def can have custom callback which should be called
7924 		 * after bpf_program is initialized to adjust its properties
7925 		 */
7926 		if (prog->sec_def->prog_setup_fn) {
7927 			err = prog->sec_def->prog_setup_fn(prog, prog->sec_def->cookie);
7928 			if (err < 0) {
7929 				pr_warn("prog '%s': failed to initialize: %d\n",
7930 					prog->name, err);
7931 				return err;
7932 			}
7933 		}
7934 	}
7935 
7936 	return 0;
7937 }
7938 
7939 static struct bpf_object *bpf_object_open(const char *path, const void *obj_buf, size_t obj_buf_sz,
7940 					  const char *obj_name,
7941 					  const struct bpf_object_open_opts *opts)
7942 {
7943 	const char *kconfig, *btf_tmp_path, *token_path;
7944 	struct bpf_object *obj;
7945 	int err;
7946 	char *log_buf;
7947 	size_t log_size;
7948 	__u32 log_level;
7949 
7950 	if (obj_buf && !obj_name)
7951 		return ERR_PTR(-EINVAL);
7952 
7953 	if (elf_version(EV_CURRENT) == EV_NONE) {
7954 		pr_warn("failed to init libelf for %s\n",
7955 			path ? : "(mem buf)");
7956 		return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
7957 	}
7958 
7959 	if (!OPTS_VALID(opts, bpf_object_open_opts))
7960 		return ERR_PTR(-EINVAL);
7961 
7962 	obj_name = OPTS_GET(opts, object_name, NULL) ?: obj_name;
7963 	if (obj_buf) {
7964 		path = obj_name;
7965 		pr_debug("loading object '%s' from buffer\n", obj_name);
7966 	} else {
7967 		pr_debug("loading object from %s\n", path);
7968 	}
7969 
7970 	log_buf = OPTS_GET(opts, kernel_log_buf, NULL);
7971 	log_size = OPTS_GET(opts, kernel_log_size, 0);
7972 	log_level = OPTS_GET(opts, kernel_log_level, 0);
7973 	if (log_size > UINT_MAX)
7974 		return ERR_PTR(-EINVAL);
7975 	if (log_size && !log_buf)
7976 		return ERR_PTR(-EINVAL);
7977 
7978 	token_path = OPTS_GET(opts, bpf_token_path, NULL);
7979 	/* if user didn't specify bpf_token_path explicitly, check if
7980 	 * LIBBPF_BPF_TOKEN_PATH envvar was set and treat it as bpf_token_path
7981 	 * option
7982 	 */
7983 	if (!token_path)
7984 		token_path = getenv("LIBBPF_BPF_TOKEN_PATH");
7985 	if (token_path && strlen(token_path) >= PATH_MAX)
7986 		return ERR_PTR(-ENAMETOOLONG);
7987 
7988 	obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
7989 	if (IS_ERR(obj))
7990 		return obj;
7991 
7992 	obj->log_buf = log_buf;
7993 	obj->log_size = log_size;
7994 	obj->log_level = log_level;
7995 
7996 	if (token_path) {
7997 		obj->token_path = strdup(token_path);
7998 		if (!obj->token_path) {
7999 			err = -ENOMEM;
8000 			goto out;
8001 		}
8002 	}
8003 
8004 	btf_tmp_path = OPTS_GET(opts, btf_custom_path, NULL);
8005 	if (btf_tmp_path) {
8006 		if (strlen(btf_tmp_path) >= PATH_MAX) {
8007 			err = -ENAMETOOLONG;
8008 			goto out;
8009 		}
8010 		obj->btf_custom_path = strdup(btf_tmp_path);
8011 		if (!obj->btf_custom_path) {
8012 			err = -ENOMEM;
8013 			goto out;
8014 		}
8015 	}
8016 
8017 	kconfig = OPTS_GET(opts, kconfig, NULL);
8018 	if (kconfig) {
8019 		obj->kconfig = strdup(kconfig);
8020 		if (!obj->kconfig) {
8021 			err = -ENOMEM;
8022 			goto out;
8023 		}
8024 	}
8025 
8026 	err = bpf_object__elf_init(obj);
8027 	err = err ? : bpf_object__elf_collect(obj);
8028 	err = err ? : bpf_object__collect_externs(obj);
8029 	err = err ? : bpf_object_fixup_btf(obj);
8030 	err = err ? : bpf_object__init_maps(obj, opts);
8031 	err = err ? : bpf_object_init_progs(obj, opts);
8032 	err = err ? : bpf_object__collect_relos(obj);
8033 	if (err)
8034 		goto out;
8035 
8036 	bpf_object__elf_finish(obj);
8037 
8038 	return obj;
8039 out:
8040 	bpf_object__close(obj);
8041 	return ERR_PTR(err);
8042 }
8043 
8044 struct bpf_object *
8045 bpf_object__open_file(const char *path, const struct bpf_object_open_opts *opts)
8046 {
8047 	if (!path)
8048 		return libbpf_err_ptr(-EINVAL);
8049 
8050 	return libbpf_ptr(bpf_object_open(path, NULL, 0, NULL, opts));
8051 }
8052 
8053 struct bpf_object *bpf_object__open(const char *path)
8054 {
8055 	return bpf_object__open_file(path, NULL);
8056 }
8057 
8058 struct bpf_object *
8059 bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
8060 		     const struct bpf_object_open_opts *opts)
8061 {
8062 	char tmp_name[64];
8063 
8064 	if (!obj_buf || obj_buf_sz == 0)
8065 		return libbpf_err_ptr(-EINVAL);
8066 
8067 	/* create a (quite useless) default "name" for this memory buffer object */
8068 	snprintf(tmp_name, sizeof(tmp_name), "%lx-%zx", (unsigned long)obj_buf, obj_buf_sz);
8069 
8070 	return libbpf_ptr(bpf_object_open(NULL, obj_buf, obj_buf_sz, tmp_name, opts));
8071 }
8072 
8073 static int bpf_object_unload(struct bpf_object *obj)
8074 {
8075 	size_t i;
8076 
8077 	if (!obj)
8078 		return libbpf_err(-EINVAL);
8079 
8080 	for (i = 0; i < obj->nr_maps; i++) {
8081 		zclose(obj->maps[i].fd);
8082 		if (obj->maps[i].st_ops)
8083 			zfree(&obj->maps[i].st_ops->kern_vdata);
8084 	}
8085 
8086 	for (i = 0; i < obj->nr_programs; i++)
8087 		bpf_program__unload(&obj->programs[i]);
8088 
8089 	return 0;
8090 }
8091 
8092 static int bpf_object__sanitize_maps(struct bpf_object *obj)
8093 {
8094 	struct bpf_map *m;
8095 
8096 	bpf_object__for_each_map(m, obj) {
8097 		if (!bpf_map__is_internal(m))
8098 			continue;
8099 		if (!kernel_supports(obj, FEAT_ARRAY_MMAP))
8100 			m->def.map_flags &= ~BPF_F_MMAPABLE;
8101 	}
8102 
8103 	return 0;
8104 }
8105 
8106 typedef int (*kallsyms_cb_t)(unsigned long long sym_addr, char sym_type,
8107 			     const char *sym_name, void *ctx);
8108 
8109 static int libbpf_kallsyms_parse(kallsyms_cb_t cb, void *ctx)
8110 {
8111 	char sym_type, sym_name[500];
8112 	unsigned long long sym_addr;
8113 	int ret, err = 0;
8114 	FILE *f;
8115 
8116 	f = fopen("/proc/kallsyms", "re");
8117 	if (!f) {
8118 		err = -errno;
8119 		pr_warn("failed to open /proc/kallsyms: %d\n", err);
8120 		return err;
8121 	}
8122 
8123 	while (true) {
8124 		ret = fscanf(f, "%llx %c %499s%*[^\n]\n",
8125 			     &sym_addr, &sym_type, sym_name);
8126 		if (ret == EOF && feof(f))
8127 			break;
8128 		if (ret != 3) {
8129 			pr_warn("failed to read kallsyms entry: %d\n", ret);
8130 			err = -EINVAL;
8131 			break;
8132 		}
8133 
8134 		err = cb(sym_addr, sym_type, sym_name, ctx);
8135 		if (err)
8136 			break;
8137 	}
8138 
8139 	fclose(f);
8140 	return err;
8141 }
8142 
8143 static int kallsyms_cb(unsigned long long sym_addr, char sym_type,
8144 		       const char *sym_name, void *ctx)
8145 {
8146 	struct bpf_object *obj = ctx;
8147 	const struct btf_type *t;
8148 	struct extern_desc *ext;
8149 	char *res;
8150 
8151 	res = strstr(sym_name, ".llvm.");
8152 	if (sym_type == 'd' && res)
8153 		ext = find_extern_by_name_with_len(obj, sym_name, res - sym_name);
8154 	else
8155 		ext = find_extern_by_name(obj, sym_name);
8156 	if (!ext || ext->type != EXT_KSYM)
8157 		return 0;
8158 
8159 	t = btf__type_by_id(obj->btf, ext->btf_id);
8160 	if (!btf_is_var(t))
8161 		return 0;
8162 
8163 	if (ext->is_set && ext->ksym.addr != sym_addr) {
8164 		pr_warn("extern (ksym) '%s': resolution is ambiguous: 0x%llx or 0x%llx\n",
8165 			sym_name, ext->ksym.addr, sym_addr);
8166 		return -EINVAL;
8167 	}
8168 	if (!ext->is_set) {
8169 		ext->is_set = true;
8170 		ext->ksym.addr = sym_addr;
8171 		pr_debug("extern (ksym) '%s': set to 0x%llx\n", sym_name, sym_addr);
8172 	}
8173 	return 0;
8174 }
8175 
8176 static int bpf_object__read_kallsyms_file(struct bpf_object *obj)
8177 {
8178 	return libbpf_kallsyms_parse(kallsyms_cb, obj);
8179 }
8180 
8181 static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
8182 			    __u16 kind, struct btf **res_btf,
8183 			    struct module_btf **res_mod_btf)
8184 {
8185 	struct module_btf *mod_btf;
8186 	struct btf *btf;
8187 	int i, id, err;
8188 
8189 	btf = obj->btf_vmlinux;
8190 	mod_btf = NULL;
8191 	id = btf__find_by_name_kind(btf, ksym_name, kind);
8192 
8193 	if (id == -ENOENT) {
8194 		err = load_module_btfs(obj);
8195 		if (err)
8196 			return err;
8197 
8198 		for (i = 0; i < obj->btf_module_cnt; i++) {
8199 			/* we assume module_btf's BTF FD is always >0 */
8200 			mod_btf = &obj->btf_modules[i];
8201 			btf = mod_btf->btf;
8202 			id = btf__find_by_name_kind_own(btf, ksym_name, kind);
8203 			if (id != -ENOENT)
8204 				break;
8205 		}
8206 	}
8207 	if (id <= 0)
8208 		return -ESRCH;
8209 
8210 	*res_btf = btf;
8211 	*res_mod_btf = mod_btf;
8212 	return id;
8213 }
8214 
8215 static int bpf_object__resolve_ksym_var_btf_id(struct bpf_object *obj,
8216 					       struct extern_desc *ext)
8217 {
8218 	const struct btf_type *targ_var, *targ_type;
8219 	__u32 targ_type_id, local_type_id;
8220 	struct module_btf *mod_btf = NULL;
8221 	const char *targ_var_name;
8222 	struct btf *btf = NULL;
8223 	int id, err;
8224 
8225 	id = find_ksym_btf_id(obj, ext->name, BTF_KIND_VAR, &btf, &mod_btf);
8226 	if (id < 0) {
8227 		if (id == -ESRCH && ext->is_weak)
8228 			return 0;
8229 		pr_warn("extern (var ksym) '%s': not found in kernel BTF\n",
8230 			ext->name);
8231 		return id;
8232 	}
8233 
8234 	/* find local type_id */
8235 	local_type_id = ext->ksym.type_id;
8236 
8237 	/* find target type_id */
8238 	targ_var = btf__type_by_id(btf, id);
8239 	targ_var_name = btf__name_by_offset(btf, targ_var->name_off);
8240 	targ_type = skip_mods_and_typedefs(btf, targ_var->type, &targ_type_id);
8241 
8242 	err = bpf_core_types_are_compat(obj->btf, local_type_id,
8243 					btf, targ_type_id);
8244 	if (err <= 0) {
8245 		const struct btf_type *local_type;
8246 		const char *targ_name, *local_name;
8247 
8248 		local_type = btf__type_by_id(obj->btf, local_type_id);
8249 		local_name = btf__name_by_offset(obj->btf, local_type->name_off);
8250 		targ_name = btf__name_by_offset(btf, targ_type->name_off);
8251 
8252 		pr_warn("extern (var ksym) '%s': incompatible types, expected [%d] %s %s, but kernel has [%d] %s %s\n",
8253 			ext->name, local_type_id,
8254 			btf_kind_str(local_type), local_name, targ_type_id,
8255 			btf_kind_str(targ_type), targ_name);
8256 		return -EINVAL;
8257 	}
8258 
8259 	ext->is_set = true;
8260 	ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
8261 	ext->ksym.kernel_btf_id = id;
8262 	pr_debug("extern (var ksym) '%s': resolved to [%d] %s %s\n",
8263 		 ext->name, id, btf_kind_str(targ_var), targ_var_name);
8264 
8265 	return 0;
8266 }
8267 
8268 static int bpf_object__resolve_ksym_func_btf_id(struct bpf_object *obj,
8269 						struct extern_desc *ext)
8270 {
8271 	int local_func_proto_id, kfunc_proto_id, kfunc_id;
8272 	struct module_btf *mod_btf = NULL;
8273 	const struct btf_type *kern_func;
8274 	struct btf *kern_btf = NULL;
8275 	int ret;
8276 
8277 	local_func_proto_id = ext->ksym.type_id;
8278 
8279 	kfunc_id = find_ksym_btf_id(obj, ext->essent_name ?: ext->name, BTF_KIND_FUNC, &kern_btf,
8280 				    &mod_btf);
8281 	if (kfunc_id < 0) {
8282 		if (kfunc_id == -ESRCH && ext->is_weak)
8283 			return 0;
8284 		pr_warn("extern (func ksym) '%s': not found in kernel or module BTFs\n",
8285 			ext->name);
8286 		return kfunc_id;
8287 	}
8288 
8289 	kern_func = btf__type_by_id(kern_btf, kfunc_id);
8290 	kfunc_proto_id = kern_func->type;
8291 
8292 	ret = bpf_core_types_are_compat(obj->btf, local_func_proto_id,
8293 					kern_btf, kfunc_proto_id);
8294 	if (ret <= 0) {
8295 		if (ext->is_weak)
8296 			return 0;
8297 
8298 		pr_warn("extern (func ksym) '%s': func_proto [%d] incompatible with %s [%d]\n",
8299 			ext->name, local_func_proto_id,
8300 			mod_btf ? mod_btf->name : "vmlinux", kfunc_proto_id);
8301 		return -EINVAL;
8302 	}
8303 
8304 	/* set index for module BTF fd in fd_array, if unset */
8305 	if (mod_btf && !mod_btf->fd_array_idx) {
8306 		/* insn->off is s16 */
8307 		if (obj->fd_array_cnt == INT16_MAX) {
8308 			pr_warn("extern (func ksym) '%s': module BTF fd index %d too big to fit in bpf_insn offset\n",
8309 				ext->name, mod_btf->fd_array_idx);
8310 			return -E2BIG;
8311 		}
8312 		/* Cannot use index 0 for module BTF fd */
8313 		if (!obj->fd_array_cnt)
8314 			obj->fd_array_cnt = 1;
8315 
8316 		ret = libbpf_ensure_mem((void **)&obj->fd_array, &obj->fd_array_cap, sizeof(int),
8317 					obj->fd_array_cnt + 1);
8318 		if (ret)
8319 			return ret;
8320 		mod_btf->fd_array_idx = obj->fd_array_cnt;
8321 		/* we assume module BTF FD is always >0 */
8322 		obj->fd_array[obj->fd_array_cnt++] = mod_btf->fd;
8323 	}
8324 
8325 	ext->is_set = true;
8326 	ext->ksym.kernel_btf_id = kfunc_id;
8327 	ext->ksym.btf_fd_idx = mod_btf ? mod_btf->fd_array_idx : 0;
8328 	/* Also set kernel_btf_obj_fd to make sure that bpf_object__relocate_data()
8329 	 * populates FD into ld_imm64 insn when it's used to point to kfunc.
8330 	 * {kernel_btf_id, btf_fd_idx} -> fixup bpf_call.
8331 	 * {kernel_btf_id, kernel_btf_obj_fd} -> fixup ld_imm64.
8332 	 */
8333 	ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
8334 	pr_debug("extern (func ksym) '%s': resolved to %s [%d]\n",
8335 		 ext->name, mod_btf ? mod_btf->name : "vmlinux", kfunc_id);
8336 
8337 	return 0;
8338 }
8339 
8340 static int bpf_object__resolve_ksyms_btf_id(struct bpf_object *obj)
8341 {
8342 	const struct btf_type *t;
8343 	struct extern_desc *ext;
8344 	int i, err;
8345 
8346 	for (i = 0; i < obj->nr_extern; i++) {
8347 		ext = &obj->externs[i];
8348 		if (ext->type != EXT_KSYM || !ext->ksym.type_id)
8349 			continue;
8350 
8351 		if (obj->gen_loader) {
8352 			ext->is_set = true;
8353 			ext->ksym.kernel_btf_obj_fd = 0;
8354 			ext->ksym.kernel_btf_id = 0;
8355 			continue;
8356 		}
8357 		t = btf__type_by_id(obj->btf, ext->btf_id);
8358 		if (btf_is_var(t))
8359 			err = bpf_object__resolve_ksym_var_btf_id(obj, ext);
8360 		else
8361 			err = bpf_object__resolve_ksym_func_btf_id(obj, ext);
8362 		if (err)
8363 			return err;
8364 	}
8365 	return 0;
8366 }
8367 
8368 static int bpf_object__resolve_externs(struct bpf_object *obj,
8369 				       const char *extra_kconfig)
8370 {
8371 	bool need_config = false, need_kallsyms = false;
8372 	bool need_vmlinux_btf = false;
8373 	struct extern_desc *ext;
8374 	void *kcfg_data = NULL;
8375 	int err, i;
8376 
8377 	if (obj->nr_extern == 0)
8378 		return 0;
8379 
8380 	if (obj->kconfig_map_idx >= 0)
8381 		kcfg_data = obj->maps[obj->kconfig_map_idx].mmaped;
8382 
8383 	for (i = 0; i < obj->nr_extern; i++) {
8384 		ext = &obj->externs[i];
8385 
8386 		if (ext->type == EXT_KSYM) {
8387 			if (ext->ksym.type_id)
8388 				need_vmlinux_btf = true;
8389 			else
8390 				need_kallsyms = true;
8391 			continue;
8392 		} else if (ext->type == EXT_KCFG) {
8393 			void *ext_ptr = kcfg_data + ext->kcfg.data_off;
8394 			__u64 value = 0;
8395 
8396 			/* Kconfig externs need actual /proc/config.gz */
8397 			if (str_has_pfx(ext->name, "CONFIG_")) {
8398 				need_config = true;
8399 				continue;
8400 			}
8401 
8402 			/* Virtual kcfg externs are customly handled by libbpf */
8403 			if (strcmp(ext->name, "LINUX_KERNEL_VERSION") == 0) {
8404 				value = get_kernel_version();
8405 				if (!value) {
8406 					pr_warn("extern (kcfg) '%s': failed to get kernel version\n", ext->name);
8407 					return -EINVAL;
8408 				}
8409 			} else if (strcmp(ext->name, "LINUX_HAS_BPF_COOKIE") == 0) {
8410 				value = kernel_supports(obj, FEAT_BPF_COOKIE);
8411 			} else if (strcmp(ext->name, "LINUX_HAS_SYSCALL_WRAPPER") == 0) {
8412 				value = kernel_supports(obj, FEAT_SYSCALL_WRAPPER);
8413 			} else if (!str_has_pfx(ext->name, "LINUX_") || !ext->is_weak) {
8414 				/* Currently libbpf supports only CONFIG_ and LINUX_ prefixed
8415 				 * __kconfig externs, where LINUX_ ones are virtual and filled out
8416 				 * customly by libbpf (their values don't come from Kconfig).
8417 				 * If LINUX_xxx variable is not recognized by libbpf, but is marked
8418 				 * __weak, it defaults to zero value, just like for CONFIG_xxx
8419 				 * externs.
8420 				 */
8421 				pr_warn("extern (kcfg) '%s': unrecognized virtual extern\n", ext->name);
8422 				return -EINVAL;
8423 			}
8424 
8425 			err = set_kcfg_value_num(ext, ext_ptr, value);
8426 			if (err)
8427 				return err;
8428 			pr_debug("extern (kcfg) '%s': set to 0x%llx\n",
8429 				 ext->name, (long long)value);
8430 		} else {
8431 			pr_warn("extern '%s': unrecognized extern kind\n", ext->name);
8432 			return -EINVAL;
8433 		}
8434 	}
8435 	if (need_config && extra_kconfig) {
8436 		err = bpf_object__read_kconfig_mem(obj, extra_kconfig, kcfg_data);
8437 		if (err)
8438 			return -EINVAL;
8439 		need_config = false;
8440 		for (i = 0; i < obj->nr_extern; i++) {
8441 			ext = &obj->externs[i];
8442 			if (ext->type == EXT_KCFG && !ext->is_set) {
8443 				need_config = true;
8444 				break;
8445 			}
8446 		}
8447 	}
8448 	if (need_config) {
8449 		err = bpf_object__read_kconfig_file(obj, kcfg_data);
8450 		if (err)
8451 			return -EINVAL;
8452 	}
8453 	if (need_kallsyms) {
8454 		err = bpf_object__read_kallsyms_file(obj);
8455 		if (err)
8456 			return -EINVAL;
8457 	}
8458 	if (need_vmlinux_btf) {
8459 		err = bpf_object__resolve_ksyms_btf_id(obj);
8460 		if (err)
8461 			return -EINVAL;
8462 	}
8463 	for (i = 0; i < obj->nr_extern; i++) {
8464 		ext = &obj->externs[i];
8465 
8466 		if (!ext->is_set && !ext->is_weak) {
8467 			pr_warn("extern '%s' (strong): not resolved\n", ext->name);
8468 			return -ESRCH;
8469 		} else if (!ext->is_set) {
8470 			pr_debug("extern '%s' (weak): not resolved, defaulting to zero\n",
8471 				 ext->name);
8472 		}
8473 	}
8474 
8475 	return 0;
8476 }
8477 
8478 static void bpf_map_prepare_vdata(const struct bpf_map *map)
8479 {
8480 	const struct btf_type *type;
8481 	struct bpf_struct_ops *st_ops;
8482 	__u32 i;
8483 
8484 	st_ops = map->st_ops;
8485 	type = btf__type_by_id(map->obj->btf, st_ops->type_id);
8486 	for (i = 0; i < btf_vlen(type); i++) {
8487 		struct bpf_program *prog = st_ops->progs[i];
8488 		void *kern_data;
8489 		int prog_fd;
8490 
8491 		if (!prog)
8492 			continue;
8493 
8494 		prog_fd = bpf_program__fd(prog);
8495 		kern_data = st_ops->kern_vdata + st_ops->kern_func_off[i];
8496 		*(unsigned long *)kern_data = prog_fd;
8497 	}
8498 }
8499 
8500 static int bpf_object_prepare_struct_ops(struct bpf_object *obj)
8501 {
8502 	struct bpf_map *map;
8503 	int i;
8504 
8505 	for (i = 0; i < obj->nr_maps; i++) {
8506 		map = &obj->maps[i];
8507 
8508 		if (!bpf_map__is_struct_ops(map))
8509 			continue;
8510 
8511 		if (!map->autocreate)
8512 			continue;
8513 
8514 		bpf_map_prepare_vdata(map);
8515 	}
8516 
8517 	return 0;
8518 }
8519 
8520 static int bpf_object_load(struct bpf_object *obj, int extra_log_level, const char *target_btf_path)
8521 {
8522 	int err, i;
8523 
8524 	if (!obj)
8525 		return libbpf_err(-EINVAL);
8526 
8527 	if (obj->loaded) {
8528 		pr_warn("object '%s': load can't be attempted twice\n", obj->name);
8529 		return libbpf_err(-EINVAL);
8530 	}
8531 
8532 	/* Disallow kernel loading programs of non-native endianness but
8533 	 * permit cross-endian creation of "light skeleton".
8534 	 */
8535 	if (obj->gen_loader) {
8536 		bpf_gen__init(obj->gen_loader, extra_log_level, obj->nr_programs, obj->nr_maps);
8537 	} else if (!is_native_endianness(obj)) {
8538 		pr_warn("object '%s': loading non-native endianness is unsupported\n", obj->name);
8539 		return libbpf_err(-LIBBPF_ERRNO__ENDIAN);
8540 	}
8541 
8542 	err = bpf_object_prepare_token(obj);
8543 	err = err ? : bpf_object__probe_loading(obj);
8544 	err = err ? : bpf_object__load_vmlinux_btf(obj, false);
8545 	err = err ? : bpf_object__resolve_externs(obj, obj->kconfig);
8546 	err = err ? : bpf_object__sanitize_maps(obj);
8547 	err = err ? : bpf_object__init_kern_struct_ops_maps(obj);
8548 	err = err ? : bpf_object_adjust_struct_ops_autoload(obj);
8549 	err = err ? : bpf_object__relocate(obj, obj->btf_custom_path ? : target_btf_path);
8550 	err = err ? : bpf_object__sanitize_and_load_btf(obj);
8551 	err = err ? : bpf_object__create_maps(obj);
8552 	err = err ? : bpf_object__load_progs(obj, extra_log_level);
8553 	err = err ? : bpf_object_init_prog_arrays(obj);
8554 	err = err ? : bpf_object_prepare_struct_ops(obj);
8555 
8556 	if (obj->gen_loader) {
8557 		/* reset FDs */
8558 		if (obj->btf)
8559 			btf__set_fd(obj->btf, -1);
8560 		if (!err)
8561 			err = bpf_gen__finish(obj->gen_loader, obj->nr_programs, obj->nr_maps);
8562 	}
8563 
8564 	/* clean up fd_array */
8565 	zfree(&obj->fd_array);
8566 
8567 	/* clean up module BTFs */
8568 	for (i = 0; i < obj->btf_module_cnt; i++) {
8569 		close(obj->btf_modules[i].fd);
8570 		btf__free(obj->btf_modules[i].btf);
8571 		free(obj->btf_modules[i].name);
8572 	}
8573 	free(obj->btf_modules);
8574 
8575 	/* clean up vmlinux BTF */
8576 	btf__free(obj->btf_vmlinux);
8577 	obj->btf_vmlinux = NULL;
8578 
8579 	obj->loaded = true; /* doesn't matter if successfully or not */
8580 
8581 	if (err)
8582 		goto out;
8583 
8584 	return 0;
8585 out:
8586 	/* unpin any maps that were auto-pinned during load */
8587 	for (i = 0; i < obj->nr_maps; i++)
8588 		if (obj->maps[i].pinned && !obj->maps[i].reused)
8589 			bpf_map__unpin(&obj->maps[i], NULL);
8590 
8591 	bpf_object_unload(obj);
8592 	pr_warn("failed to load object '%s'\n", obj->path);
8593 	return libbpf_err(err);
8594 }
8595 
8596 int bpf_object__load(struct bpf_object *obj)
8597 {
8598 	return bpf_object_load(obj, 0, NULL);
8599 }
8600 
8601 static int make_parent_dir(const char *path)
8602 {
8603 	char *cp, errmsg[STRERR_BUFSIZE];
8604 	char *dname, *dir;
8605 	int err = 0;
8606 
8607 	dname = strdup(path);
8608 	if (dname == NULL)
8609 		return -ENOMEM;
8610 
8611 	dir = dirname(dname);
8612 	if (mkdir(dir, 0700) && errno != EEXIST)
8613 		err = -errno;
8614 
8615 	free(dname);
8616 	if (err) {
8617 		cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
8618 		pr_warn("failed to mkdir %s: %s\n", path, cp);
8619 	}
8620 	return err;
8621 }
8622 
8623 static int check_path(const char *path)
8624 {
8625 	char *cp, errmsg[STRERR_BUFSIZE];
8626 	struct statfs st_fs;
8627 	char *dname, *dir;
8628 	int err = 0;
8629 
8630 	if (path == NULL)
8631 		return -EINVAL;
8632 
8633 	dname = strdup(path);
8634 	if (dname == NULL)
8635 		return -ENOMEM;
8636 
8637 	dir = dirname(dname);
8638 	if (statfs(dir, &st_fs)) {
8639 		cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
8640 		pr_warn("failed to statfs %s: %s\n", dir, cp);
8641 		err = -errno;
8642 	}
8643 	free(dname);
8644 
8645 	if (!err && st_fs.f_type != BPF_FS_MAGIC) {
8646 		pr_warn("specified path %s is not on BPF FS\n", path);
8647 		err = -EINVAL;
8648 	}
8649 
8650 	return err;
8651 }
8652 
8653 int bpf_program__pin(struct bpf_program *prog, const char *path)
8654 {
8655 	char *cp, errmsg[STRERR_BUFSIZE];
8656 	int err;
8657 
8658 	if (prog->fd < 0) {
8659 		pr_warn("prog '%s': can't pin program that wasn't loaded\n", prog->name);
8660 		return libbpf_err(-EINVAL);
8661 	}
8662 
8663 	err = make_parent_dir(path);
8664 	if (err)
8665 		return libbpf_err(err);
8666 
8667 	err = check_path(path);
8668 	if (err)
8669 		return libbpf_err(err);
8670 
8671 	if (bpf_obj_pin(prog->fd, path)) {
8672 		err = -errno;
8673 		cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
8674 		pr_warn("prog '%s': failed to pin at '%s': %s\n", prog->name, path, cp);
8675 		return libbpf_err(err);
8676 	}
8677 
8678 	pr_debug("prog '%s': pinned at '%s'\n", prog->name, path);
8679 	return 0;
8680 }
8681 
8682 int bpf_program__unpin(struct bpf_program *prog, const char *path)
8683 {
8684 	int err;
8685 
8686 	if (prog->fd < 0) {
8687 		pr_warn("prog '%s': can't unpin program that wasn't loaded\n", prog->name);
8688 		return libbpf_err(-EINVAL);
8689 	}
8690 
8691 	err = check_path(path);
8692 	if (err)
8693 		return libbpf_err(err);
8694 
8695 	err = unlink(path);
8696 	if (err)
8697 		return libbpf_err(-errno);
8698 
8699 	pr_debug("prog '%s': unpinned from '%s'\n", prog->name, path);
8700 	return 0;
8701 }
8702 
8703 int bpf_map__pin(struct bpf_map *map, const char *path)
8704 {
8705 	char *cp, errmsg[STRERR_BUFSIZE];
8706 	int err;
8707 
8708 	if (map == NULL) {
8709 		pr_warn("invalid map pointer\n");
8710 		return libbpf_err(-EINVAL);
8711 	}
8712 
8713 	if (map->fd < 0) {
8714 		pr_warn("map '%s': can't pin BPF map without FD (was it created?)\n", map->name);
8715 		return libbpf_err(-EINVAL);
8716 	}
8717 
8718 	if (map->pin_path) {
8719 		if (path && strcmp(path, map->pin_path)) {
8720 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
8721 				bpf_map__name(map), map->pin_path, path);
8722 			return libbpf_err(-EINVAL);
8723 		} else if (map->pinned) {
8724 			pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
8725 				 bpf_map__name(map), map->pin_path);
8726 			return 0;
8727 		}
8728 	} else {
8729 		if (!path) {
8730 			pr_warn("missing a path to pin map '%s' at\n",
8731 				bpf_map__name(map));
8732 			return libbpf_err(-EINVAL);
8733 		} else if (map->pinned) {
8734 			pr_warn("map '%s' already pinned\n", bpf_map__name(map));
8735 			return libbpf_err(-EEXIST);
8736 		}
8737 
8738 		map->pin_path = strdup(path);
8739 		if (!map->pin_path) {
8740 			err = -errno;
8741 			goto out_err;
8742 		}
8743 	}
8744 
8745 	err = make_parent_dir(map->pin_path);
8746 	if (err)
8747 		return libbpf_err(err);
8748 
8749 	err = check_path(map->pin_path);
8750 	if (err)
8751 		return libbpf_err(err);
8752 
8753 	if (bpf_obj_pin(map->fd, map->pin_path)) {
8754 		err = -errno;
8755 		goto out_err;
8756 	}
8757 
8758 	map->pinned = true;
8759 	pr_debug("pinned map '%s'\n", map->pin_path);
8760 
8761 	return 0;
8762 
8763 out_err:
8764 	cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
8765 	pr_warn("failed to pin map: %s\n", cp);
8766 	return libbpf_err(err);
8767 }
8768 
8769 int bpf_map__unpin(struct bpf_map *map, const char *path)
8770 {
8771 	int err;
8772 
8773 	if (map == NULL) {
8774 		pr_warn("invalid map pointer\n");
8775 		return libbpf_err(-EINVAL);
8776 	}
8777 
8778 	if (map->pin_path) {
8779 		if (path && strcmp(path, map->pin_path)) {
8780 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
8781 				bpf_map__name(map), map->pin_path, path);
8782 			return libbpf_err(-EINVAL);
8783 		}
8784 		path = map->pin_path;
8785 	} else if (!path) {
8786 		pr_warn("no path to unpin map '%s' from\n",
8787 			bpf_map__name(map));
8788 		return libbpf_err(-EINVAL);
8789 	}
8790 
8791 	err = check_path(path);
8792 	if (err)
8793 		return libbpf_err(err);
8794 
8795 	err = unlink(path);
8796 	if (err != 0)
8797 		return libbpf_err(-errno);
8798 
8799 	map->pinned = false;
8800 	pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path);
8801 
8802 	return 0;
8803 }
8804 
8805 int bpf_map__set_pin_path(struct bpf_map *map, const char *path)
8806 {
8807 	char *new = NULL;
8808 
8809 	if (path) {
8810 		new = strdup(path);
8811 		if (!new)
8812 			return libbpf_err(-errno);
8813 	}
8814 
8815 	free(map->pin_path);
8816 	map->pin_path = new;
8817 	return 0;
8818 }
8819 
8820 __alias(bpf_map__pin_path)
8821 const char *bpf_map__get_pin_path(const struct bpf_map *map);
8822 
8823 const char *bpf_map__pin_path(const struct bpf_map *map)
8824 {
8825 	return map->pin_path;
8826 }
8827 
8828 bool bpf_map__is_pinned(const struct bpf_map *map)
8829 {
8830 	return map->pinned;
8831 }
8832 
8833 static void sanitize_pin_path(char *s)
8834 {
8835 	/* bpffs disallows periods in path names */
8836 	while (*s) {
8837 		if (*s == '.')
8838 			*s = '_';
8839 		s++;
8840 	}
8841 }
8842 
8843 int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
8844 {
8845 	struct bpf_map *map;
8846 	int err;
8847 
8848 	if (!obj)
8849 		return libbpf_err(-ENOENT);
8850 
8851 	if (!obj->loaded) {
8852 		pr_warn("object not yet loaded; load it first\n");
8853 		return libbpf_err(-ENOENT);
8854 	}
8855 
8856 	bpf_object__for_each_map(map, obj) {
8857 		char *pin_path = NULL;
8858 		char buf[PATH_MAX];
8859 
8860 		if (!map->autocreate)
8861 			continue;
8862 
8863 		if (path) {
8864 			err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
8865 			if (err)
8866 				goto err_unpin_maps;
8867 			sanitize_pin_path(buf);
8868 			pin_path = buf;
8869 		} else if (!map->pin_path) {
8870 			continue;
8871 		}
8872 
8873 		err = bpf_map__pin(map, pin_path);
8874 		if (err)
8875 			goto err_unpin_maps;
8876 	}
8877 
8878 	return 0;
8879 
8880 err_unpin_maps:
8881 	while ((map = bpf_object__prev_map(obj, map))) {
8882 		if (!map->pin_path)
8883 			continue;
8884 
8885 		bpf_map__unpin(map, NULL);
8886 	}
8887 
8888 	return libbpf_err(err);
8889 }
8890 
8891 int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
8892 {
8893 	struct bpf_map *map;
8894 	int err;
8895 
8896 	if (!obj)
8897 		return libbpf_err(-ENOENT);
8898 
8899 	bpf_object__for_each_map(map, obj) {
8900 		char *pin_path = NULL;
8901 		char buf[PATH_MAX];
8902 
8903 		if (path) {
8904 			err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
8905 			if (err)
8906 				return libbpf_err(err);
8907 			sanitize_pin_path(buf);
8908 			pin_path = buf;
8909 		} else if (!map->pin_path) {
8910 			continue;
8911 		}
8912 
8913 		err = bpf_map__unpin(map, pin_path);
8914 		if (err)
8915 			return libbpf_err(err);
8916 	}
8917 
8918 	return 0;
8919 }
8920 
8921 int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
8922 {
8923 	struct bpf_program *prog;
8924 	char buf[PATH_MAX];
8925 	int err;
8926 
8927 	if (!obj)
8928 		return libbpf_err(-ENOENT);
8929 
8930 	if (!obj->loaded) {
8931 		pr_warn("object not yet loaded; load it first\n");
8932 		return libbpf_err(-ENOENT);
8933 	}
8934 
8935 	bpf_object__for_each_program(prog, obj) {
8936 		err = pathname_concat(buf, sizeof(buf), path, prog->name);
8937 		if (err)
8938 			goto err_unpin_programs;
8939 
8940 		err = bpf_program__pin(prog, buf);
8941 		if (err)
8942 			goto err_unpin_programs;
8943 	}
8944 
8945 	return 0;
8946 
8947 err_unpin_programs:
8948 	while ((prog = bpf_object__prev_program(obj, prog))) {
8949 		if (pathname_concat(buf, sizeof(buf), path, prog->name))
8950 			continue;
8951 
8952 		bpf_program__unpin(prog, buf);
8953 	}
8954 
8955 	return libbpf_err(err);
8956 }
8957 
8958 int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
8959 {
8960 	struct bpf_program *prog;
8961 	int err;
8962 
8963 	if (!obj)
8964 		return libbpf_err(-ENOENT);
8965 
8966 	bpf_object__for_each_program(prog, obj) {
8967 		char buf[PATH_MAX];
8968 
8969 		err = pathname_concat(buf, sizeof(buf), path, prog->name);
8970 		if (err)
8971 			return libbpf_err(err);
8972 
8973 		err = bpf_program__unpin(prog, buf);
8974 		if (err)
8975 			return libbpf_err(err);
8976 	}
8977 
8978 	return 0;
8979 }
8980 
8981 int bpf_object__pin(struct bpf_object *obj, const char *path)
8982 {
8983 	int err;
8984 
8985 	err = bpf_object__pin_maps(obj, path);
8986 	if (err)
8987 		return libbpf_err(err);
8988 
8989 	err = bpf_object__pin_programs(obj, path);
8990 	if (err) {
8991 		bpf_object__unpin_maps(obj, path);
8992 		return libbpf_err(err);
8993 	}
8994 
8995 	return 0;
8996 }
8997 
8998 int bpf_object__unpin(struct bpf_object *obj, const char *path)
8999 {
9000 	int err;
9001 
9002 	err = bpf_object__unpin_programs(obj, path);
9003 	if (err)
9004 		return libbpf_err(err);
9005 
9006 	err = bpf_object__unpin_maps(obj, path);
9007 	if (err)
9008 		return libbpf_err(err);
9009 
9010 	return 0;
9011 }
9012 
9013 static void bpf_map__destroy(struct bpf_map *map)
9014 {
9015 	if (map->inner_map) {
9016 		bpf_map__destroy(map->inner_map);
9017 		zfree(&map->inner_map);
9018 	}
9019 
9020 	zfree(&map->init_slots);
9021 	map->init_slots_sz = 0;
9022 
9023 	if (map->mmaped && map->mmaped != map->obj->arena_data)
9024 		munmap(map->mmaped, bpf_map_mmap_sz(map));
9025 	map->mmaped = NULL;
9026 
9027 	if (map->st_ops) {
9028 		zfree(&map->st_ops->data);
9029 		zfree(&map->st_ops->progs);
9030 		zfree(&map->st_ops->kern_func_off);
9031 		zfree(&map->st_ops);
9032 	}
9033 
9034 	zfree(&map->name);
9035 	zfree(&map->real_name);
9036 	zfree(&map->pin_path);
9037 
9038 	if (map->fd >= 0)
9039 		zclose(map->fd);
9040 }
9041 
9042 void bpf_object__close(struct bpf_object *obj)
9043 {
9044 	size_t i;
9045 
9046 	if (IS_ERR_OR_NULL(obj))
9047 		return;
9048 
9049 	usdt_manager_free(obj->usdt_man);
9050 	obj->usdt_man = NULL;
9051 
9052 	bpf_gen__free(obj->gen_loader);
9053 	bpf_object__elf_finish(obj);
9054 	bpf_object_unload(obj);
9055 	btf__free(obj->btf);
9056 	btf__free(obj->btf_vmlinux);
9057 	btf_ext__free(obj->btf_ext);
9058 
9059 	for (i = 0; i < obj->nr_maps; i++)
9060 		bpf_map__destroy(&obj->maps[i]);
9061 
9062 	zfree(&obj->btf_custom_path);
9063 	zfree(&obj->kconfig);
9064 
9065 	for (i = 0; i < obj->nr_extern; i++)
9066 		zfree(&obj->externs[i].essent_name);
9067 
9068 	zfree(&obj->externs);
9069 	obj->nr_extern = 0;
9070 
9071 	zfree(&obj->maps);
9072 	obj->nr_maps = 0;
9073 
9074 	if (obj->programs && obj->nr_programs) {
9075 		for (i = 0; i < obj->nr_programs; i++)
9076 			bpf_program__exit(&obj->programs[i]);
9077 	}
9078 	zfree(&obj->programs);
9079 
9080 	zfree(&obj->feat_cache);
9081 	zfree(&obj->token_path);
9082 	if (obj->token_fd > 0)
9083 		close(obj->token_fd);
9084 
9085 	zfree(&obj->arena_data);
9086 
9087 	free(obj);
9088 }
9089 
9090 const char *bpf_object__name(const struct bpf_object *obj)
9091 {
9092 	return obj ? obj->name : libbpf_err_ptr(-EINVAL);
9093 }
9094 
9095 unsigned int bpf_object__kversion(const struct bpf_object *obj)
9096 {
9097 	return obj ? obj->kern_version : 0;
9098 }
9099 
9100 int bpf_object__token_fd(const struct bpf_object *obj)
9101 {
9102 	return obj->token_fd ?: -1;
9103 }
9104 
9105 struct btf *bpf_object__btf(const struct bpf_object *obj)
9106 {
9107 	return obj ? obj->btf : NULL;
9108 }
9109 
9110 int bpf_object__btf_fd(const struct bpf_object *obj)
9111 {
9112 	return obj->btf ? btf__fd(obj->btf) : -1;
9113 }
9114 
9115 int bpf_object__set_kversion(struct bpf_object *obj, __u32 kern_version)
9116 {
9117 	if (obj->loaded)
9118 		return libbpf_err(-EINVAL);
9119 
9120 	obj->kern_version = kern_version;
9121 
9122 	return 0;
9123 }
9124 
9125 int bpf_object__gen_loader(struct bpf_object *obj, struct gen_loader_opts *opts)
9126 {
9127 	struct bpf_gen *gen;
9128 
9129 	if (!opts)
9130 		return -EFAULT;
9131 	if (!OPTS_VALID(opts, gen_loader_opts))
9132 		return -EINVAL;
9133 	gen = calloc(sizeof(*gen), 1);
9134 	if (!gen)
9135 		return -ENOMEM;
9136 	gen->opts = opts;
9137 	gen->swapped_endian = !is_native_endianness(obj);
9138 	obj->gen_loader = gen;
9139 	return 0;
9140 }
9141 
9142 static struct bpf_program *
9143 __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
9144 		    bool forward)
9145 {
9146 	size_t nr_programs = obj->nr_programs;
9147 	ssize_t idx;
9148 
9149 	if (!nr_programs)
9150 		return NULL;
9151 
9152 	if (!p)
9153 		/* Iter from the beginning */
9154 		return forward ? &obj->programs[0] :
9155 			&obj->programs[nr_programs - 1];
9156 
9157 	if (p->obj != obj) {
9158 		pr_warn("error: program handler doesn't match object\n");
9159 		return errno = EINVAL, NULL;
9160 	}
9161 
9162 	idx = (p - obj->programs) + (forward ? 1 : -1);
9163 	if (idx >= obj->nr_programs || idx < 0)
9164 		return NULL;
9165 	return &obj->programs[idx];
9166 }
9167 
9168 struct bpf_program *
9169 bpf_object__next_program(const struct bpf_object *obj, struct bpf_program *prev)
9170 {
9171 	struct bpf_program *prog = prev;
9172 
9173 	do {
9174 		prog = __bpf_program__iter(prog, obj, true);
9175 	} while (prog && prog_is_subprog(obj, prog));
9176 
9177 	return prog;
9178 }
9179 
9180 struct bpf_program *
9181 bpf_object__prev_program(const struct bpf_object *obj, struct bpf_program *next)
9182 {
9183 	struct bpf_program *prog = next;
9184 
9185 	do {
9186 		prog = __bpf_program__iter(prog, obj, false);
9187 	} while (prog && prog_is_subprog(obj, prog));
9188 
9189 	return prog;
9190 }
9191 
9192 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
9193 {
9194 	prog->prog_ifindex = ifindex;
9195 }
9196 
9197 const char *bpf_program__name(const struct bpf_program *prog)
9198 {
9199 	return prog->name;
9200 }
9201 
9202 const char *bpf_program__section_name(const struct bpf_program *prog)
9203 {
9204 	return prog->sec_name;
9205 }
9206 
9207 bool bpf_program__autoload(const struct bpf_program *prog)
9208 {
9209 	return prog->autoload;
9210 }
9211 
9212 int bpf_program__set_autoload(struct bpf_program *prog, bool autoload)
9213 {
9214 	if (prog->obj->loaded)
9215 		return libbpf_err(-EINVAL);
9216 
9217 	prog->autoload = autoload;
9218 	return 0;
9219 }
9220 
9221 bool bpf_program__autoattach(const struct bpf_program *prog)
9222 {
9223 	return prog->autoattach;
9224 }
9225 
9226 void bpf_program__set_autoattach(struct bpf_program *prog, bool autoattach)
9227 {
9228 	prog->autoattach = autoattach;
9229 }
9230 
9231 const struct bpf_insn *bpf_program__insns(const struct bpf_program *prog)
9232 {
9233 	return prog->insns;
9234 }
9235 
9236 size_t bpf_program__insn_cnt(const struct bpf_program *prog)
9237 {
9238 	return prog->insns_cnt;
9239 }
9240 
9241 int bpf_program__set_insns(struct bpf_program *prog,
9242 			   struct bpf_insn *new_insns, size_t new_insn_cnt)
9243 {
9244 	struct bpf_insn *insns;
9245 
9246 	if (prog->obj->loaded)
9247 		return -EBUSY;
9248 
9249 	insns = libbpf_reallocarray(prog->insns, new_insn_cnt, sizeof(*insns));
9250 	/* NULL is a valid return from reallocarray if the new count is zero */
9251 	if (!insns && new_insn_cnt) {
9252 		pr_warn("prog '%s': failed to realloc prog code\n", prog->name);
9253 		return -ENOMEM;
9254 	}
9255 	memcpy(insns, new_insns, new_insn_cnt * sizeof(*insns));
9256 
9257 	prog->insns = insns;
9258 	prog->insns_cnt = new_insn_cnt;
9259 	return 0;
9260 }
9261 
9262 int bpf_program__fd(const struct bpf_program *prog)
9263 {
9264 	if (!prog)
9265 		return libbpf_err(-EINVAL);
9266 
9267 	if (prog->fd < 0)
9268 		return libbpf_err(-ENOENT);
9269 
9270 	return prog->fd;
9271 }
9272 
9273 __alias(bpf_program__type)
9274 enum bpf_prog_type bpf_program__get_type(const struct bpf_program *prog);
9275 
9276 enum bpf_prog_type bpf_program__type(const struct bpf_program *prog)
9277 {
9278 	return prog->type;
9279 }
9280 
9281 static size_t custom_sec_def_cnt;
9282 static struct bpf_sec_def *custom_sec_defs;
9283 static struct bpf_sec_def custom_fallback_def;
9284 static bool has_custom_fallback_def;
9285 static int last_custom_sec_def_handler_id;
9286 
9287 int bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
9288 {
9289 	if (prog->obj->loaded)
9290 		return libbpf_err(-EBUSY);
9291 
9292 	/* if type is not changed, do nothing */
9293 	if (prog->type == type)
9294 		return 0;
9295 
9296 	prog->type = type;
9297 
9298 	/* If a program type was changed, we need to reset associated SEC()
9299 	 * handler, as it will be invalid now. The only exception is a generic
9300 	 * fallback handler, which by definition is program type-agnostic and
9301 	 * is a catch-all custom handler, optionally set by the application,
9302 	 * so should be able to handle any type of BPF program.
9303 	 */
9304 	if (prog->sec_def != &custom_fallback_def)
9305 		prog->sec_def = NULL;
9306 	return 0;
9307 }
9308 
9309 __alias(bpf_program__expected_attach_type)
9310 enum bpf_attach_type bpf_program__get_expected_attach_type(const struct bpf_program *prog);
9311 
9312 enum bpf_attach_type bpf_program__expected_attach_type(const struct bpf_program *prog)
9313 {
9314 	return prog->expected_attach_type;
9315 }
9316 
9317 int bpf_program__set_expected_attach_type(struct bpf_program *prog,
9318 					   enum bpf_attach_type type)
9319 {
9320 	if (prog->obj->loaded)
9321 		return libbpf_err(-EBUSY);
9322 
9323 	prog->expected_attach_type = type;
9324 	return 0;
9325 }
9326 
9327 __u32 bpf_program__flags(const struct bpf_program *prog)
9328 {
9329 	return prog->prog_flags;
9330 }
9331 
9332 int bpf_program__set_flags(struct bpf_program *prog, __u32 flags)
9333 {
9334 	if (prog->obj->loaded)
9335 		return libbpf_err(-EBUSY);
9336 
9337 	prog->prog_flags = flags;
9338 	return 0;
9339 }
9340 
9341 __u32 bpf_program__log_level(const struct bpf_program *prog)
9342 {
9343 	return prog->log_level;
9344 }
9345 
9346 int bpf_program__set_log_level(struct bpf_program *prog, __u32 log_level)
9347 {
9348 	if (prog->obj->loaded)
9349 		return libbpf_err(-EBUSY);
9350 
9351 	prog->log_level = log_level;
9352 	return 0;
9353 }
9354 
9355 const char *bpf_program__log_buf(const struct bpf_program *prog, size_t *log_size)
9356 {
9357 	*log_size = prog->log_size;
9358 	return prog->log_buf;
9359 }
9360 
9361 int bpf_program__set_log_buf(struct bpf_program *prog, char *log_buf, size_t log_size)
9362 {
9363 	if (log_size && !log_buf)
9364 		return -EINVAL;
9365 	if (prog->log_size > UINT_MAX)
9366 		return -EINVAL;
9367 	if (prog->obj->loaded)
9368 		return -EBUSY;
9369 
9370 	prog->log_buf = log_buf;
9371 	prog->log_size = log_size;
9372 	return 0;
9373 }
9374 
9375 #define SEC_DEF(sec_pfx, ptype, atype, flags, ...) {			    \
9376 	.sec = (char *)sec_pfx,						    \
9377 	.prog_type = BPF_PROG_TYPE_##ptype,				    \
9378 	.expected_attach_type = atype,					    \
9379 	.cookie = (long)(flags),					    \
9380 	.prog_prepare_load_fn = libbpf_prepare_prog_load,		    \
9381 	__VA_ARGS__							    \
9382 }
9383 
9384 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9385 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9386 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9387 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9388 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9389 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9390 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9391 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9392 static int attach_kprobe_session(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9393 static int attach_uprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9394 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9395 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9396 
9397 static const struct bpf_sec_def section_defs[] = {
9398 	SEC_DEF("socket",		SOCKET_FILTER, 0, SEC_NONE),
9399 	SEC_DEF("sk_reuseport/migrate",	SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT_OR_MIGRATE, SEC_ATTACHABLE),
9400 	SEC_DEF("sk_reuseport",		SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT, SEC_ATTACHABLE),
9401 	SEC_DEF("kprobe+",		KPROBE,	0, SEC_NONE, attach_kprobe),
9402 	SEC_DEF("uprobe+",		KPROBE,	0, SEC_NONE, attach_uprobe),
9403 	SEC_DEF("uprobe.s+",		KPROBE,	0, SEC_SLEEPABLE, attach_uprobe),
9404 	SEC_DEF("kretprobe+",		KPROBE, 0, SEC_NONE, attach_kprobe),
9405 	SEC_DEF("uretprobe+",		KPROBE, 0, SEC_NONE, attach_uprobe),
9406 	SEC_DEF("uretprobe.s+",		KPROBE, 0, SEC_SLEEPABLE, attach_uprobe),
9407 	SEC_DEF("kprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
9408 	SEC_DEF("kretprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
9409 	SEC_DEF("kprobe.session+",	KPROBE,	BPF_TRACE_KPROBE_SESSION, SEC_NONE, attach_kprobe_session),
9410 	SEC_DEF("uprobe.multi+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_NONE, attach_uprobe_multi),
9411 	SEC_DEF("uretprobe.multi+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_NONE, attach_uprobe_multi),
9412 	SEC_DEF("uprobe.multi.s+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_SLEEPABLE, attach_uprobe_multi),
9413 	SEC_DEF("uretprobe.multi.s+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_SLEEPABLE, attach_uprobe_multi),
9414 	SEC_DEF("ksyscall+",		KPROBE,	0, SEC_NONE, attach_ksyscall),
9415 	SEC_DEF("kretsyscall+",		KPROBE, 0, SEC_NONE, attach_ksyscall),
9416 	SEC_DEF("usdt+",		KPROBE,	0, SEC_USDT, attach_usdt),
9417 	SEC_DEF("usdt.s+",		KPROBE,	0, SEC_USDT | SEC_SLEEPABLE, attach_usdt),
9418 	SEC_DEF("tc/ingress",		SCHED_CLS, BPF_TCX_INGRESS, SEC_NONE), /* alias for tcx */
9419 	SEC_DEF("tc/egress",		SCHED_CLS, BPF_TCX_EGRESS, SEC_NONE),  /* alias for tcx */
9420 	SEC_DEF("tcx/ingress",		SCHED_CLS, BPF_TCX_INGRESS, SEC_NONE),
9421 	SEC_DEF("tcx/egress",		SCHED_CLS, BPF_TCX_EGRESS, SEC_NONE),
9422 	SEC_DEF("tc",			SCHED_CLS, 0, SEC_NONE), /* deprecated / legacy, use tcx */
9423 	SEC_DEF("classifier",		SCHED_CLS, 0, SEC_NONE), /* deprecated / legacy, use tcx */
9424 	SEC_DEF("action",		SCHED_ACT, 0, SEC_NONE), /* deprecated / legacy, use tcx */
9425 	SEC_DEF("netkit/primary",	SCHED_CLS, BPF_NETKIT_PRIMARY, SEC_NONE),
9426 	SEC_DEF("netkit/peer",		SCHED_CLS, BPF_NETKIT_PEER, SEC_NONE),
9427 	SEC_DEF("tracepoint+",		TRACEPOINT, 0, SEC_NONE, attach_tp),
9428 	SEC_DEF("tp+",			TRACEPOINT, 0, SEC_NONE, attach_tp),
9429 	SEC_DEF("raw_tracepoint+",	RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
9430 	SEC_DEF("raw_tp+",		RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
9431 	SEC_DEF("raw_tracepoint.w+",	RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
9432 	SEC_DEF("raw_tp.w+",		RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
9433 	SEC_DEF("tp_btf+",		TRACING, BPF_TRACE_RAW_TP, SEC_ATTACH_BTF, attach_trace),
9434 	SEC_DEF("fentry+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF, attach_trace),
9435 	SEC_DEF("fmod_ret+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF, attach_trace),
9436 	SEC_DEF("fexit+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF, attach_trace),
9437 	SEC_DEF("fentry.s+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
9438 	SEC_DEF("fmod_ret.s+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
9439 	SEC_DEF("fexit.s+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
9440 	SEC_DEF("freplace+",		EXT, 0, SEC_ATTACH_BTF, attach_trace),
9441 	SEC_DEF("lsm+",			LSM, BPF_LSM_MAC, SEC_ATTACH_BTF, attach_lsm),
9442 	SEC_DEF("lsm.s+",		LSM, BPF_LSM_MAC, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_lsm),
9443 	SEC_DEF("lsm_cgroup+",		LSM, BPF_LSM_CGROUP, SEC_ATTACH_BTF),
9444 	SEC_DEF("iter+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF, attach_iter),
9445 	SEC_DEF("iter.s+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_iter),
9446 	SEC_DEF("syscall",		SYSCALL, 0, SEC_SLEEPABLE),
9447 	SEC_DEF("xdp.frags/devmap",	XDP, BPF_XDP_DEVMAP, SEC_XDP_FRAGS),
9448 	SEC_DEF("xdp/devmap",		XDP, BPF_XDP_DEVMAP, SEC_ATTACHABLE),
9449 	SEC_DEF("xdp.frags/cpumap",	XDP, BPF_XDP_CPUMAP, SEC_XDP_FRAGS),
9450 	SEC_DEF("xdp/cpumap",		XDP, BPF_XDP_CPUMAP, SEC_ATTACHABLE),
9451 	SEC_DEF("xdp.frags",		XDP, BPF_XDP, SEC_XDP_FRAGS),
9452 	SEC_DEF("xdp",			XDP, BPF_XDP, SEC_ATTACHABLE_OPT),
9453 	SEC_DEF("perf_event",		PERF_EVENT, 0, SEC_NONE),
9454 	SEC_DEF("lwt_in",		LWT_IN, 0, SEC_NONE),
9455 	SEC_DEF("lwt_out",		LWT_OUT, 0, SEC_NONE),
9456 	SEC_DEF("lwt_xmit",		LWT_XMIT, 0, SEC_NONE),
9457 	SEC_DEF("lwt_seg6local",	LWT_SEG6LOCAL, 0, SEC_NONE),
9458 	SEC_DEF("sockops",		SOCK_OPS, BPF_CGROUP_SOCK_OPS, SEC_ATTACHABLE_OPT),
9459 	SEC_DEF("sk_skb/stream_parser",	SK_SKB, BPF_SK_SKB_STREAM_PARSER, SEC_ATTACHABLE_OPT),
9460 	SEC_DEF("sk_skb/stream_verdict",SK_SKB, BPF_SK_SKB_STREAM_VERDICT, SEC_ATTACHABLE_OPT),
9461 	SEC_DEF("sk_skb/verdict",	SK_SKB, BPF_SK_SKB_VERDICT, SEC_ATTACHABLE_OPT),
9462 	SEC_DEF("sk_skb",		SK_SKB, 0, SEC_NONE),
9463 	SEC_DEF("sk_msg",		SK_MSG, BPF_SK_MSG_VERDICT, SEC_ATTACHABLE_OPT),
9464 	SEC_DEF("lirc_mode2",		LIRC_MODE2, BPF_LIRC_MODE2, SEC_ATTACHABLE_OPT),
9465 	SEC_DEF("flow_dissector",	FLOW_DISSECTOR, BPF_FLOW_DISSECTOR, SEC_ATTACHABLE_OPT),
9466 	SEC_DEF("cgroup_skb/ingress",	CGROUP_SKB, BPF_CGROUP_INET_INGRESS, SEC_ATTACHABLE_OPT),
9467 	SEC_DEF("cgroup_skb/egress",	CGROUP_SKB, BPF_CGROUP_INET_EGRESS, SEC_ATTACHABLE_OPT),
9468 	SEC_DEF("cgroup/skb",		CGROUP_SKB, 0, SEC_NONE),
9469 	SEC_DEF("cgroup/sock_create",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE),
9470 	SEC_DEF("cgroup/sock_release",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_RELEASE, SEC_ATTACHABLE),
9471 	SEC_DEF("cgroup/sock",		CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE_OPT),
9472 	SEC_DEF("cgroup/post_bind4",	CGROUP_SOCK, BPF_CGROUP_INET4_POST_BIND, SEC_ATTACHABLE),
9473 	SEC_DEF("cgroup/post_bind6",	CGROUP_SOCK, BPF_CGROUP_INET6_POST_BIND, SEC_ATTACHABLE),
9474 	SEC_DEF("cgroup/bind4",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND, SEC_ATTACHABLE),
9475 	SEC_DEF("cgroup/bind6",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND, SEC_ATTACHABLE),
9476 	SEC_DEF("cgroup/connect4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT, SEC_ATTACHABLE),
9477 	SEC_DEF("cgroup/connect6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT, SEC_ATTACHABLE),
9478 	SEC_DEF("cgroup/connect_unix",	CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_CONNECT, SEC_ATTACHABLE),
9479 	SEC_DEF("cgroup/sendmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG, SEC_ATTACHABLE),
9480 	SEC_DEF("cgroup/sendmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG, SEC_ATTACHABLE),
9481 	SEC_DEF("cgroup/sendmsg_unix",	CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_SENDMSG, SEC_ATTACHABLE),
9482 	SEC_DEF("cgroup/recvmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_RECVMSG, SEC_ATTACHABLE),
9483 	SEC_DEF("cgroup/recvmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_RECVMSG, SEC_ATTACHABLE),
9484 	SEC_DEF("cgroup/recvmsg_unix",	CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_RECVMSG, SEC_ATTACHABLE),
9485 	SEC_DEF("cgroup/getpeername4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETPEERNAME, SEC_ATTACHABLE),
9486 	SEC_DEF("cgroup/getpeername6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETPEERNAME, SEC_ATTACHABLE),
9487 	SEC_DEF("cgroup/getpeername_unix", CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_GETPEERNAME, SEC_ATTACHABLE),
9488 	SEC_DEF("cgroup/getsockname4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETSOCKNAME, SEC_ATTACHABLE),
9489 	SEC_DEF("cgroup/getsockname6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETSOCKNAME, SEC_ATTACHABLE),
9490 	SEC_DEF("cgroup/getsockname_unix", CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_GETSOCKNAME, SEC_ATTACHABLE),
9491 	SEC_DEF("cgroup/sysctl",	CGROUP_SYSCTL, BPF_CGROUP_SYSCTL, SEC_ATTACHABLE),
9492 	SEC_DEF("cgroup/getsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_GETSOCKOPT, SEC_ATTACHABLE),
9493 	SEC_DEF("cgroup/setsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_SETSOCKOPT, SEC_ATTACHABLE),
9494 	SEC_DEF("cgroup/dev",		CGROUP_DEVICE, BPF_CGROUP_DEVICE, SEC_ATTACHABLE_OPT),
9495 	SEC_DEF("struct_ops+",		STRUCT_OPS, 0, SEC_NONE),
9496 	SEC_DEF("struct_ops.s+",	STRUCT_OPS, 0, SEC_SLEEPABLE),
9497 	SEC_DEF("sk_lookup",		SK_LOOKUP, BPF_SK_LOOKUP, SEC_ATTACHABLE),
9498 	SEC_DEF("netfilter",		NETFILTER, BPF_NETFILTER, SEC_NONE),
9499 };
9500 
9501 int libbpf_register_prog_handler(const char *sec,
9502 				 enum bpf_prog_type prog_type,
9503 				 enum bpf_attach_type exp_attach_type,
9504 				 const struct libbpf_prog_handler_opts *opts)
9505 {
9506 	struct bpf_sec_def *sec_def;
9507 
9508 	if (!OPTS_VALID(opts, libbpf_prog_handler_opts))
9509 		return libbpf_err(-EINVAL);
9510 
9511 	if (last_custom_sec_def_handler_id == INT_MAX) /* prevent overflow */
9512 		return libbpf_err(-E2BIG);
9513 
9514 	if (sec) {
9515 		sec_def = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt + 1,
9516 					      sizeof(*sec_def));
9517 		if (!sec_def)
9518 			return libbpf_err(-ENOMEM);
9519 
9520 		custom_sec_defs = sec_def;
9521 		sec_def = &custom_sec_defs[custom_sec_def_cnt];
9522 	} else {
9523 		if (has_custom_fallback_def)
9524 			return libbpf_err(-EBUSY);
9525 
9526 		sec_def = &custom_fallback_def;
9527 	}
9528 
9529 	sec_def->sec = sec ? strdup(sec) : NULL;
9530 	if (sec && !sec_def->sec)
9531 		return libbpf_err(-ENOMEM);
9532 
9533 	sec_def->prog_type = prog_type;
9534 	sec_def->expected_attach_type = exp_attach_type;
9535 	sec_def->cookie = OPTS_GET(opts, cookie, 0);
9536 
9537 	sec_def->prog_setup_fn = OPTS_GET(opts, prog_setup_fn, NULL);
9538 	sec_def->prog_prepare_load_fn = OPTS_GET(opts, prog_prepare_load_fn, NULL);
9539 	sec_def->prog_attach_fn = OPTS_GET(opts, prog_attach_fn, NULL);
9540 
9541 	sec_def->handler_id = ++last_custom_sec_def_handler_id;
9542 
9543 	if (sec)
9544 		custom_sec_def_cnt++;
9545 	else
9546 		has_custom_fallback_def = true;
9547 
9548 	return sec_def->handler_id;
9549 }
9550 
9551 int libbpf_unregister_prog_handler(int handler_id)
9552 {
9553 	struct bpf_sec_def *sec_defs;
9554 	int i;
9555 
9556 	if (handler_id <= 0)
9557 		return libbpf_err(-EINVAL);
9558 
9559 	if (has_custom_fallback_def && custom_fallback_def.handler_id == handler_id) {
9560 		memset(&custom_fallback_def, 0, sizeof(custom_fallback_def));
9561 		has_custom_fallback_def = false;
9562 		return 0;
9563 	}
9564 
9565 	for (i = 0; i < custom_sec_def_cnt; i++) {
9566 		if (custom_sec_defs[i].handler_id == handler_id)
9567 			break;
9568 	}
9569 
9570 	if (i == custom_sec_def_cnt)
9571 		return libbpf_err(-ENOENT);
9572 
9573 	free(custom_sec_defs[i].sec);
9574 	for (i = i + 1; i < custom_sec_def_cnt; i++)
9575 		custom_sec_defs[i - 1] = custom_sec_defs[i];
9576 	custom_sec_def_cnt--;
9577 
9578 	/* try to shrink the array, but it's ok if we couldn't */
9579 	sec_defs = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt, sizeof(*sec_defs));
9580 	/* if new count is zero, reallocarray can return a valid NULL result;
9581 	 * in this case the previous pointer will be freed, so we *have to*
9582 	 * reassign old pointer to the new value (even if it's NULL)
9583 	 */
9584 	if (sec_defs || custom_sec_def_cnt == 0)
9585 		custom_sec_defs = sec_defs;
9586 
9587 	return 0;
9588 }
9589 
9590 static bool sec_def_matches(const struct bpf_sec_def *sec_def, const char *sec_name)
9591 {
9592 	size_t len = strlen(sec_def->sec);
9593 
9594 	/* "type/" always has to have proper SEC("type/extras") form */
9595 	if (sec_def->sec[len - 1] == '/') {
9596 		if (str_has_pfx(sec_name, sec_def->sec))
9597 			return true;
9598 		return false;
9599 	}
9600 
9601 	/* "type+" means it can be either exact SEC("type") or
9602 	 * well-formed SEC("type/extras") with proper '/' separator
9603 	 */
9604 	if (sec_def->sec[len - 1] == '+') {
9605 		len--;
9606 		/* not even a prefix */
9607 		if (strncmp(sec_name, sec_def->sec, len) != 0)
9608 			return false;
9609 		/* exact match or has '/' separator */
9610 		if (sec_name[len] == '\0' || sec_name[len] == '/')
9611 			return true;
9612 		return false;
9613 	}
9614 
9615 	return strcmp(sec_name, sec_def->sec) == 0;
9616 }
9617 
9618 static const struct bpf_sec_def *find_sec_def(const char *sec_name)
9619 {
9620 	const struct bpf_sec_def *sec_def;
9621 	int i, n;
9622 
9623 	n = custom_sec_def_cnt;
9624 	for (i = 0; i < n; i++) {
9625 		sec_def = &custom_sec_defs[i];
9626 		if (sec_def_matches(sec_def, sec_name))
9627 			return sec_def;
9628 	}
9629 
9630 	n = ARRAY_SIZE(section_defs);
9631 	for (i = 0; i < n; i++) {
9632 		sec_def = &section_defs[i];
9633 		if (sec_def_matches(sec_def, sec_name))
9634 			return sec_def;
9635 	}
9636 
9637 	if (has_custom_fallback_def)
9638 		return &custom_fallback_def;
9639 
9640 	return NULL;
9641 }
9642 
9643 #define MAX_TYPE_NAME_SIZE 32
9644 
9645 static char *libbpf_get_type_names(bool attach_type)
9646 {
9647 	int i, len = ARRAY_SIZE(section_defs) * MAX_TYPE_NAME_SIZE;
9648 	char *buf;
9649 
9650 	buf = malloc(len);
9651 	if (!buf)
9652 		return NULL;
9653 
9654 	buf[0] = '\0';
9655 	/* Forge string buf with all available names */
9656 	for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
9657 		const struct bpf_sec_def *sec_def = &section_defs[i];
9658 
9659 		if (attach_type) {
9660 			if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
9661 				continue;
9662 
9663 			if (!(sec_def->cookie & SEC_ATTACHABLE))
9664 				continue;
9665 		}
9666 
9667 		if (strlen(buf) + strlen(section_defs[i].sec) + 2 > len) {
9668 			free(buf);
9669 			return NULL;
9670 		}
9671 		strcat(buf, " ");
9672 		strcat(buf, section_defs[i].sec);
9673 	}
9674 
9675 	return buf;
9676 }
9677 
9678 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
9679 			     enum bpf_attach_type *expected_attach_type)
9680 {
9681 	const struct bpf_sec_def *sec_def;
9682 	char *type_names;
9683 
9684 	if (!name)
9685 		return libbpf_err(-EINVAL);
9686 
9687 	sec_def = find_sec_def(name);
9688 	if (sec_def) {
9689 		*prog_type = sec_def->prog_type;
9690 		*expected_attach_type = sec_def->expected_attach_type;
9691 		return 0;
9692 	}
9693 
9694 	pr_debug("failed to guess program type from ELF section '%s'\n", name);
9695 	type_names = libbpf_get_type_names(false);
9696 	if (type_names != NULL) {
9697 		pr_debug("supported section(type) names are:%s\n", type_names);
9698 		free(type_names);
9699 	}
9700 
9701 	return libbpf_err(-ESRCH);
9702 }
9703 
9704 const char *libbpf_bpf_attach_type_str(enum bpf_attach_type t)
9705 {
9706 	if (t < 0 || t >= ARRAY_SIZE(attach_type_name))
9707 		return NULL;
9708 
9709 	return attach_type_name[t];
9710 }
9711 
9712 const char *libbpf_bpf_link_type_str(enum bpf_link_type t)
9713 {
9714 	if (t < 0 || t >= ARRAY_SIZE(link_type_name))
9715 		return NULL;
9716 
9717 	return link_type_name[t];
9718 }
9719 
9720 const char *libbpf_bpf_map_type_str(enum bpf_map_type t)
9721 {
9722 	if (t < 0 || t >= ARRAY_SIZE(map_type_name))
9723 		return NULL;
9724 
9725 	return map_type_name[t];
9726 }
9727 
9728 const char *libbpf_bpf_prog_type_str(enum bpf_prog_type t)
9729 {
9730 	if (t < 0 || t >= ARRAY_SIZE(prog_type_name))
9731 		return NULL;
9732 
9733 	return prog_type_name[t];
9734 }
9735 
9736 static struct bpf_map *find_struct_ops_map_by_offset(struct bpf_object *obj,
9737 						     int sec_idx,
9738 						     size_t offset)
9739 {
9740 	struct bpf_map *map;
9741 	size_t i;
9742 
9743 	for (i = 0; i < obj->nr_maps; i++) {
9744 		map = &obj->maps[i];
9745 		if (!bpf_map__is_struct_ops(map))
9746 			continue;
9747 		if (map->sec_idx == sec_idx &&
9748 		    map->sec_offset <= offset &&
9749 		    offset - map->sec_offset < map->def.value_size)
9750 			return map;
9751 	}
9752 
9753 	return NULL;
9754 }
9755 
9756 /* Collect the reloc from ELF, populate the st_ops->progs[], and update
9757  * st_ops->data for shadow type.
9758  */
9759 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
9760 					    Elf64_Shdr *shdr, Elf_Data *data)
9761 {
9762 	const struct btf_type *type;
9763 	const struct btf_member *member;
9764 	struct bpf_struct_ops *st_ops;
9765 	struct bpf_program *prog;
9766 	unsigned int shdr_idx;
9767 	const struct btf *btf;
9768 	struct bpf_map *map;
9769 	unsigned int moff, insn_idx;
9770 	const char *name;
9771 	__u32 member_idx;
9772 	Elf64_Sym *sym;
9773 	Elf64_Rel *rel;
9774 	int i, nrels;
9775 
9776 	btf = obj->btf;
9777 	nrels = shdr->sh_size / shdr->sh_entsize;
9778 	for (i = 0; i < nrels; i++) {
9779 		rel = elf_rel_by_idx(data, i);
9780 		if (!rel) {
9781 			pr_warn("struct_ops reloc: failed to get %d reloc\n", i);
9782 			return -LIBBPF_ERRNO__FORMAT;
9783 		}
9784 
9785 		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
9786 		if (!sym) {
9787 			pr_warn("struct_ops reloc: symbol %zx not found\n",
9788 				(size_t)ELF64_R_SYM(rel->r_info));
9789 			return -LIBBPF_ERRNO__FORMAT;
9790 		}
9791 
9792 		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
9793 		map = find_struct_ops_map_by_offset(obj, shdr->sh_info, rel->r_offset);
9794 		if (!map) {
9795 			pr_warn("struct_ops reloc: cannot find map at rel->r_offset %zu\n",
9796 				(size_t)rel->r_offset);
9797 			return -EINVAL;
9798 		}
9799 
9800 		moff = rel->r_offset - map->sec_offset;
9801 		shdr_idx = sym->st_shndx;
9802 		st_ops = map->st_ops;
9803 		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",
9804 			 map->name,
9805 			 (long long)(rel->r_info >> 32),
9806 			 (long long)sym->st_value,
9807 			 shdr_idx, (size_t)rel->r_offset,
9808 			 map->sec_offset, sym->st_name, name);
9809 
9810 		if (shdr_idx >= SHN_LORESERVE) {
9811 			pr_warn("struct_ops reloc %s: rel->r_offset %zu shdr_idx %u unsupported non-static function\n",
9812 				map->name, (size_t)rel->r_offset, shdr_idx);
9813 			return -LIBBPF_ERRNO__RELOC;
9814 		}
9815 		if (sym->st_value % BPF_INSN_SZ) {
9816 			pr_warn("struct_ops reloc %s: invalid target program offset %llu\n",
9817 				map->name, (unsigned long long)sym->st_value);
9818 			return -LIBBPF_ERRNO__FORMAT;
9819 		}
9820 		insn_idx = sym->st_value / BPF_INSN_SZ;
9821 
9822 		type = btf__type_by_id(btf, st_ops->type_id);
9823 		member = find_member_by_offset(type, moff * 8);
9824 		if (!member) {
9825 			pr_warn("struct_ops reloc %s: cannot find member at moff %u\n",
9826 				map->name, moff);
9827 			return -EINVAL;
9828 		}
9829 		member_idx = member - btf_members(type);
9830 		name = btf__name_by_offset(btf, member->name_off);
9831 
9832 		if (!resolve_func_ptr(btf, member->type, NULL)) {
9833 			pr_warn("struct_ops reloc %s: cannot relocate non func ptr %s\n",
9834 				map->name, name);
9835 			return -EINVAL;
9836 		}
9837 
9838 		prog = find_prog_by_sec_insn(obj, shdr_idx, insn_idx);
9839 		if (!prog) {
9840 			pr_warn("struct_ops reloc %s: cannot find prog at shdr_idx %u to relocate func ptr %s\n",
9841 				map->name, shdr_idx, name);
9842 			return -EINVAL;
9843 		}
9844 
9845 		/* prevent the use of BPF prog with invalid type */
9846 		if (prog->type != BPF_PROG_TYPE_STRUCT_OPS) {
9847 			pr_warn("struct_ops reloc %s: prog %s is not struct_ops BPF program\n",
9848 				map->name, prog->name);
9849 			return -EINVAL;
9850 		}
9851 
9852 		st_ops->progs[member_idx] = prog;
9853 
9854 		/* st_ops->data will be exposed to users, being returned by
9855 		 * bpf_map__initial_value() as a pointer to the shadow
9856 		 * type. All function pointers in the original struct type
9857 		 * should be converted to a pointer to struct bpf_program
9858 		 * in the shadow type.
9859 		 */
9860 		*((struct bpf_program **)(st_ops->data + moff)) = prog;
9861 	}
9862 
9863 	return 0;
9864 }
9865 
9866 #define BTF_TRACE_PREFIX "btf_trace_"
9867 #define BTF_LSM_PREFIX "bpf_lsm_"
9868 #define BTF_ITER_PREFIX "bpf_iter_"
9869 #define BTF_MAX_NAME_SIZE 128
9870 
9871 void btf_get_kernel_prefix_kind(enum bpf_attach_type attach_type,
9872 				const char **prefix, int *kind)
9873 {
9874 	switch (attach_type) {
9875 	case BPF_TRACE_RAW_TP:
9876 		*prefix = BTF_TRACE_PREFIX;
9877 		*kind = BTF_KIND_TYPEDEF;
9878 		break;
9879 	case BPF_LSM_MAC:
9880 	case BPF_LSM_CGROUP:
9881 		*prefix = BTF_LSM_PREFIX;
9882 		*kind = BTF_KIND_FUNC;
9883 		break;
9884 	case BPF_TRACE_ITER:
9885 		*prefix = BTF_ITER_PREFIX;
9886 		*kind = BTF_KIND_FUNC;
9887 		break;
9888 	default:
9889 		*prefix = "";
9890 		*kind = BTF_KIND_FUNC;
9891 	}
9892 }
9893 
9894 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
9895 				   const char *name, __u32 kind)
9896 {
9897 	char btf_type_name[BTF_MAX_NAME_SIZE];
9898 	int ret;
9899 
9900 	ret = snprintf(btf_type_name, sizeof(btf_type_name),
9901 		       "%s%s", prefix, name);
9902 	/* snprintf returns the number of characters written excluding the
9903 	 * terminating null. So, if >= BTF_MAX_NAME_SIZE are written, it
9904 	 * indicates truncation.
9905 	 */
9906 	if (ret < 0 || ret >= sizeof(btf_type_name))
9907 		return -ENAMETOOLONG;
9908 	return btf__find_by_name_kind(btf, btf_type_name, kind);
9909 }
9910 
9911 static inline int find_attach_btf_id(struct btf *btf, const char *name,
9912 				     enum bpf_attach_type attach_type)
9913 {
9914 	const char *prefix;
9915 	int kind;
9916 
9917 	btf_get_kernel_prefix_kind(attach_type, &prefix, &kind);
9918 	return find_btf_by_prefix_kind(btf, prefix, name, kind);
9919 }
9920 
9921 int libbpf_find_vmlinux_btf_id(const char *name,
9922 			       enum bpf_attach_type attach_type)
9923 {
9924 	struct btf *btf;
9925 	int err;
9926 
9927 	btf = btf__load_vmlinux_btf();
9928 	err = libbpf_get_error(btf);
9929 	if (err) {
9930 		pr_warn("vmlinux BTF is not found\n");
9931 		return libbpf_err(err);
9932 	}
9933 
9934 	err = find_attach_btf_id(btf, name, attach_type);
9935 	if (err <= 0)
9936 		pr_warn("%s is not found in vmlinux BTF\n", name);
9937 
9938 	btf__free(btf);
9939 	return libbpf_err(err);
9940 }
9941 
9942 static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd)
9943 {
9944 	struct bpf_prog_info info;
9945 	__u32 info_len = sizeof(info);
9946 	struct btf *btf;
9947 	int err;
9948 
9949 	memset(&info, 0, info_len);
9950 	err = bpf_prog_get_info_by_fd(attach_prog_fd, &info, &info_len);
9951 	if (err) {
9952 		pr_warn("failed bpf_prog_get_info_by_fd for FD %d: %d\n",
9953 			attach_prog_fd, err);
9954 		return err;
9955 	}
9956 
9957 	err = -EINVAL;
9958 	if (!info.btf_id) {
9959 		pr_warn("The target program doesn't have BTF\n");
9960 		goto out;
9961 	}
9962 	btf = btf__load_from_kernel_by_id(info.btf_id);
9963 	err = libbpf_get_error(btf);
9964 	if (err) {
9965 		pr_warn("Failed to get BTF %d of the program: %d\n", info.btf_id, err);
9966 		goto out;
9967 	}
9968 	err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
9969 	btf__free(btf);
9970 	if (err <= 0) {
9971 		pr_warn("%s is not found in prog's BTF\n", name);
9972 		goto out;
9973 	}
9974 out:
9975 	return err;
9976 }
9977 
9978 static int find_kernel_btf_id(struct bpf_object *obj, const char *attach_name,
9979 			      enum bpf_attach_type attach_type,
9980 			      int *btf_obj_fd, int *btf_type_id)
9981 {
9982 	int ret, i, mod_len;
9983 	const char *fn_name, *mod_name = NULL;
9984 
9985 	fn_name = strchr(attach_name, ':');
9986 	if (fn_name) {
9987 		mod_name = attach_name;
9988 		mod_len = fn_name - mod_name;
9989 		fn_name++;
9990 	}
9991 
9992 	if (!mod_name || strncmp(mod_name, "vmlinux", mod_len) == 0) {
9993 		ret = find_attach_btf_id(obj->btf_vmlinux,
9994 					 mod_name ? fn_name : attach_name,
9995 					 attach_type);
9996 		if (ret > 0) {
9997 			*btf_obj_fd = 0; /* vmlinux BTF */
9998 			*btf_type_id = ret;
9999 			return 0;
10000 		}
10001 		if (ret != -ENOENT)
10002 			return ret;
10003 	}
10004 
10005 	ret = load_module_btfs(obj);
10006 	if (ret)
10007 		return ret;
10008 
10009 	for (i = 0; i < obj->btf_module_cnt; i++) {
10010 		const struct module_btf *mod = &obj->btf_modules[i];
10011 
10012 		if (mod_name && strncmp(mod->name, mod_name, mod_len) != 0)
10013 			continue;
10014 
10015 		ret = find_attach_btf_id(mod->btf,
10016 					 mod_name ? fn_name : attach_name,
10017 					 attach_type);
10018 		if (ret > 0) {
10019 			*btf_obj_fd = mod->fd;
10020 			*btf_type_id = ret;
10021 			return 0;
10022 		}
10023 		if (ret == -ENOENT)
10024 			continue;
10025 
10026 		return ret;
10027 	}
10028 
10029 	return -ESRCH;
10030 }
10031 
10032 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
10033 				     int *btf_obj_fd, int *btf_type_id)
10034 {
10035 	enum bpf_attach_type attach_type = prog->expected_attach_type;
10036 	__u32 attach_prog_fd = prog->attach_prog_fd;
10037 	int err = 0;
10038 
10039 	/* BPF program's BTF ID */
10040 	if (prog->type == BPF_PROG_TYPE_EXT || attach_prog_fd) {
10041 		if (!attach_prog_fd) {
10042 			pr_warn("prog '%s': attach program FD is not set\n", prog->name);
10043 			return -EINVAL;
10044 		}
10045 		err = libbpf_find_prog_btf_id(attach_name, attach_prog_fd);
10046 		if (err < 0) {
10047 			pr_warn("prog '%s': failed to find BPF program (FD %d) BTF ID for '%s': %d\n",
10048 				 prog->name, attach_prog_fd, attach_name, err);
10049 			return err;
10050 		}
10051 		*btf_obj_fd = 0;
10052 		*btf_type_id = err;
10053 		return 0;
10054 	}
10055 
10056 	/* kernel/module BTF ID */
10057 	if (prog->obj->gen_loader) {
10058 		bpf_gen__record_attach_target(prog->obj->gen_loader, attach_name, attach_type);
10059 		*btf_obj_fd = 0;
10060 		*btf_type_id = 1;
10061 	} else {
10062 		err = find_kernel_btf_id(prog->obj, attach_name,
10063 					 attach_type, btf_obj_fd,
10064 					 btf_type_id);
10065 	}
10066 	if (err) {
10067 		pr_warn("prog '%s': failed to find kernel BTF type ID of '%s': %d\n",
10068 			prog->name, attach_name, err);
10069 		return err;
10070 	}
10071 	return 0;
10072 }
10073 
10074 int libbpf_attach_type_by_name(const char *name,
10075 			       enum bpf_attach_type *attach_type)
10076 {
10077 	char *type_names;
10078 	const struct bpf_sec_def *sec_def;
10079 
10080 	if (!name)
10081 		return libbpf_err(-EINVAL);
10082 
10083 	sec_def = find_sec_def(name);
10084 	if (!sec_def) {
10085 		pr_debug("failed to guess attach type based on ELF section name '%s'\n", name);
10086 		type_names = libbpf_get_type_names(true);
10087 		if (type_names != NULL) {
10088 			pr_debug("attachable section(type) names are:%s\n", type_names);
10089 			free(type_names);
10090 		}
10091 
10092 		return libbpf_err(-EINVAL);
10093 	}
10094 
10095 	if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
10096 		return libbpf_err(-EINVAL);
10097 	if (!(sec_def->cookie & SEC_ATTACHABLE))
10098 		return libbpf_err(-EINVAL);
10099 
10100 	*attach_type = sec_def->expected_attach_type;
10101 	return 0;
10102 }
10103 
10104 int bpf_map__fd(const struct bpf_map *map)
10105 {
10106 	if (!map)
10107 		return libbpf_err(-EINVAL);
10108 	if (!map_is_created(map))
10109 		return -1;
10110 	return map->fd;
10111 }
10112 
10113 static bool map_uses_real_name(const struct bpf_map *map)
10114 {
10115 	/* Since libbpf started to support custom .data.* and .rodata.* maps,
10116 	 * their user-visible name differs from kernel-visible name. Users see
10117 	 * such map's corresponding ELF section name as a map name.
10118 	 * This check distinguishes .data/.rodata from .data.* and .rodata.*
10119 	 * maps to know which name has to be returned to the user.
10120 	 */
10121 	if (map->libbpf_type == LIBBPF_MAP_DATA && strcmp(map->real_name, DATA_SEC) != 0)
10122 		return true;
10123 	if (map->libbpf_type == LIBBPF_MAP_RODATA && strcmp(map->real_name, RODATA_SEC) != 0)
10124 		return true;
10125 	return false;
10126 }
10127 
10128 const char *bpf_map__name(const struct bpf_map *map)
10129 {
10130 	if (!map)
10131 		return NULL;
10132 
10133 	if (map_uses_real_name(map))
10134 		return map->real_name;
10135 
10136 	return map->name;
10137 }
10138 
10139 enum bpf_map_type bpf_map__type(const struct bpf_map *map)
10140 {
10141 	return map->def.type;
10142 }
10143 
10144 int bpf_map__set_type(struct bpf_map *map, enum bpf_map_type type)
10145 {
10146 	if (map_is_created(map))
10147 		return libbpf_err(-EBUSY);
10148 	map->def.type = type;
10149 	return 0;
10150 }
10151 
10152 __u32 bpf_map__map_flags(const struct bpf_map *map)
10153 {
10154 	return map->def.map_flags;
10155 }
10156 
10157 int bpf_map__set_map_flags(struct bpf_map *map, __u32 flags)
10158 {
10159 	if (map_is_created(map))
10160 		return libbpf_err(-EBUSY);
10161 	map->def.map_flags = flags;
10162 	return 0;
10163 }
10164 
10165 __u64 bpf_map__map_extra(const struct bpf_map *map)
10166 {
10167 	return map->map_extra;
10168 }
10169 
10170 int bpf_map__set_map_extra(struct bpf_map *map, __u64 map_extra)
10171 {
10172 	if (map_is_created(map))
10173 		return libbpf_err(-EBUSY);
10174 	map->map_extra = map_extra;
10175 	return 0;
10176 }
10177 
10178 __u32 bpf_map__numa_node(const struct bpf_map *map)
10179 {
10180 	return map->numa_node;
10181 }
10182 
10183 int bpf_map__set_numa_node(struct bpf_map *map, __u32 numa_node)
10184 {
10185 	if (map_is_created(map))
10186 		return libbpf_err(-EBUSY);
10187 	map->numa_node = numa_node;
10188 	return 0;
10189 }
10190 
10191 __u32 bpf_map__key_size(const struct bpf_map *map)
10192 {
10193 	return map->def.key_size;
10194 }
10195 
10196 int bpf_map__set_key_size(struct bpf_map *map, __u32 size)
10197 {
10198 	if (map_is_created(map))
10199 		return libbpf_err(-EBUSY);
10200 	map->def.key_size = size;
10201 	return 0;
10202 }
10203 
10204 __u32 bpf_map__value_size(const struct bpf_map *map)
10205 {
10206 	return map->def.value_size;
10207 }
10208 
10209 static int map_btf_datasec_resize(struct bpf_map *map, __u32 size)
10210 {
10211 	struct btf *btf;
10212 	struct btf_type *datasec_type, *var_type;
10213 	struct btf_var_secinfo *var;
10214 	const struct btf_type *array_type;
10215 	const struct btf_array *array;
10216 	int vlen, element_sz, new_array_id;
10217 	__u32 nr_elements;
10218 
10219 	/* check btf existence */
10220 	btf = bpf_object__btf(map->obj);
10221 	if (!btf)
10222 		return -ENOENT;
10223 
10224 	/* verify map is datasec */
10225 	datasec_type = btf_type_by_id(btf, bpf_map__btf_value_type_id(map));
10226 	if (!btf_is_datasec(datasec_type)) {
10227 		pr_warn("map '%s': cannot be resized, map value type is not a datasec\n",
10228 			bpf_map__name(map));
10229 		return -EINVAL;
10230 	}
10231 
10232 	/* verify datasec has at least one var */
10233 	vlen = btf_vlen(datasec_type);
10234 	if (vlen == 0) {
10235 		pr_warn("map '%s': cannot be resized, map value datasec is empty\n",
10236 			bpf_map__name(map));
10237 		return -EINVAL;
10238 	}
10239 
10240 	/* verify last var in the datasec is an array */
10241 	var = &btf_var_secinfos(datasec_type)[vlen - 1];
10242 	var_type = btf_type_by_id(btf, var->type);
10243 	array_type = skip_mods_and_typedefs(btf, var_type->type, NULL);
10244 	if (!btf_is_array(array_type)) {
10245 		pr_warn("map '%s': cannot be resized, last var must be an array\n",
10246 			bpf_map__name(map));
10247 		return -EINVAL;
10248 	}
10249 
10250 	/* verify request size aligns with array */
10251 	array = btf_array(array_type);
10252 	element_sz = btf__resolve_size(btf, array->type);
10253 	if (element_sz <= 0 || (size - var->offset) % element_sz != 0) {
10254 		pr_warn("map '%s': cannot be resized, element size (%d) doesn't align with new total size (%u)\n",
10255 			bpf_map__name(map), element_sz, size);
10256 		return -EINVAL;
10257 	}
10258 
10259 	/* create a new array based on the existing array, but with new length */
10260 	nr_elements = (size - var->offset) / element_sz;
10261 	new_array_id = btf__add_array(btf, array->index_type, array->type, nr_elements);
10262 	if (new_array_id < 0)
10263 		return new_array_id;
10264 
10265 	/* adding a new btf type invalidates existing pointers to btf objects,
10266 	 * so refresh pointers before proceeding
10267 	 */
10268 	datasec_type = btf_type_by_id(btf, map->btf_value_type_id);
10269 	var = &btf_var_secinfos(datasec_type)[vlen - 1];
10270 	var_type = btf_type_by_id(btf, var->type);
10271 
10272 	/* finally update btf info */
10273 	datasec_type->size = size;
10274 	var->size = size - var->offset;
10275 	var_type->type = new_array_id;
10276 
10277 	return 0;
10278 }
10279 
10280 int bpf_map__set_value_size(struct bpf_map *map, __u32 size)
10281 {
10282 	if (map->obj->loaded || map->reused)
10283 		return libbpf_err(-EBUSY);
10284 
10285 	if (map->mmaped) {
10286 		size_t mmap_old_sz, mmap_new_sz;
10287 		int err;
10288 
10289 		if (map->def.type != BPF_MAP_TYPE_ARRAY)
10290 			return -EOPNOTSUPP;
10291 
10292 		mmap_old_sz = bpf_map_mmap_sz(map);
10293 		mmap_new_sz = array_map_mmap_sz(size, map->def.max_entries);
10294 		err = bpf_map_mmap_resize(map, mmap_old_sz, mmap_new_sz);
10295 		if (err) {
10296 			pr_warn("map '%s': failed to resize memory-mapped region: %d\n",
10297 				bpf_map__name(map), err);
10298 			return err;
10299 		}
10300 		err = map_btf_datasec_resize(map, size);
10301 		if (err && err != -ENOENT) {
10302 			pr_warn("map '%s': failed to adjust resized BTF, clearing BTF key/value info: %d\n",
10303 				bpf_map__name(map), err);
10304 			map->btf_value_type_id = 0;
10305 			map->btf_key_type_id = 0;
10306 		}
10307 	}
10308 
10309 	map->def.value_size = size;
10310 	return 0;
10311 }
10312 
10313 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
10314 {
10315 	return map ? map->btf_key_type_id : 0;
10316 }
10317 
10318 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
10319 {
10320 	return map ? map->btf_value_type_id : 0;
10321 }
10322 
10323 int bpf_map__set_initial_value(struct bpf_map *map,
10324 			       const void *data, size_t size)
10325 {
10326 	size_t actual_sz;
10327 
10328 	if (map->obj->loaded || map->reused)
10329 		return libbpf_err(-EBUSY);
10330 
10331 	if (!map->mmaped || map->libbpf_type == LIBBPF_MAP_KCONFIG)
10332 		return libbpf_err(-EINVAL);
10333 
10334 	if (map->def.type == BPF_MAP_TYPE_ARENA)
10335 		actual_sz = map->obj->arena_data_sz;
10336 	else
10337 		actual_sz = map->def.value_size;
10338 	if (size != actual_sz)
10339 		return libbpf_err(-EINVAL);
10340 
10341 	memcpy(map->mmaped, data, size);
10342 	return 0;
10343 }
10344 
10345 void *bpf_map__initial_value(const struct bpf_map *map, size_t *psize)
10346 {
10347 	if (bpf_map__is_struct_ops(map)) {
10348 		if (psize)
10349 			*psize = map->def.value_size;
10350 		return map->st_ops->data;
10351 	}
10352 
10353 	if (!map->mmaped)
10354 		return NULL;
10355 
10356 	if (map->def.type == BPF_MAP_TYPE_ARENA)
10357 		*psize = map->obj->arena_data_sz;
10358 	else
10359 		*psize = map->def.value_size;
10360 
10361 	return map->mmaped;
10362 }
10363 
10364 bool bpf_map__is_internal(const struct bpf_map *map)
10365 {
10366 	return map->libbpf_type != LIBBPF_MAP_UNSPEC;
10367 }
10368 
10369 __u32 bpf_map__ifindex(const struct bpf_map *map)
10370 {
10371 	return map->map_ifindex;
10372 }
10373 
10374 int bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
10375 {
10376 	if (map_is_created(map))
10377 		return libbpf_err(-EBUSY);
10378 	map->map_ifindex = ifindex;
10379 	return 0;
10380 }
10381 
10382 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
10383 {
10384 	if (!bpf_map_type__is_map_in_map(map->def.type)) {
10385 		pr_warn("error: unsupported map type\n");
10386 		return libbpf_err(-EINVAL);
10387 	}
10388 	if (map->inner_map_fd != -1) {
10389 		pr_warn("error: inner_map_fd already specified\n");
10390 		return libbpf_err(-EINVAL);
10391 	}
10392 	if (map->inner_map) {
10393 		bpf_map__destroy(map->inner_map);
10394 		zfree(&map->inner_map);
10395 	}
10396 	map->inner_map_fd = fd;
10397 	return 0;
10398 }
10399 
10400 static struct bpf_map *
10401 __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
10402 {
10403 	ssize_t idx;
10404 	struct bpf_map *s, *e;
10405 
10406 	if (!obj || !obj->maps)
10407 		return errno = EINVAL, NULL;
10408 
10409 	s = obj->maps;
10410 	e = obj->maps + obj->nr_maps;
10411 
10412 	if ((m < s) || (m >= e)) {
10413 		pr_warn("error in %s: map handler doesn't belong to object\n",
10414 			 __func__);
10415 		return errno = EINVAL, NULL;
10416 	}
10417 
10418 	idx = (m - obj->maps) + i;
10419 	if (idx >= obj->nr_maps || idx < 0)
10420 		return NULL;
10421 	return &obj->maps[idx];
10422 }
10423 
10424 struct bpf_map *
10425 bpf_object__next_map(const struct bpf_object *obj, const struct bpf_map *prev)
10426 {
10427 	if (prev == NULL && obj != NULL)
10428 		return obj->maps;
10429 
10430 	return __bpf_map__iter(prev, obj, 1);
10431 }
10432 
10433 struct bpf_map *
10434 bpf_object__prev_map(const struct bpf_object *obj, const struct bpf_map *next)
10435 {
10436 	if (next == NULL && obj != NULL) {
10437 		if (!obj->nr_maps)
10438 			return NULL;
10439 		return obj->maps + obj->nr_maps - 1;
10440 	}
10441 
10442 	return __bpf_map__iter(next, obj, -1);
10443 }
10444 
10445 struct bpf_map *
10446 bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
10447 {
10448 	struct bpf_map *pos;
10449 
10450 	bpf_object__for_each_map(pos, obj) {
10451 		/* if it's a special internal map name (which always starts
10452 		 * with dot) then check if that special name matches the
10453 		 * real map name (ELF section name)
10454 		 */
10455 		if (name[0] == '.') {
10456 			if (pos->real_name && strcmp(pos->real_name, name) == 0)
10457 				return pos;
10458 			continue;
10459 		}
10460 		/* otherwise map name has to be an exact match */
10461 		if (map_uses_real_name(pos)) {
10462 			if (strcmp(pos->real_name, name) == 0)
10463 				return pos;
10464 			continue;
10465 		}
10466 		if (strcmp(pos->name, name) == 0)
10467 			return pos;
10468 	}
10469 	return errno = ENOENT, NULL;
10470 }
10471 
10472 int
10473 bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
10474 {
10475 	return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
10476 }
10477 
10478 static int validate_map_op(const struct bpf_map *map, size_t key_sz,
10479 			   size_t value_sz, bool check_value_sz)
10480 {
10481 	if (!map_is_created(map)) /* map is not yet created */
10482 		return -ENOENT;
10483 
10484 	if (map->def.key_size != key_sz) {
10485 		pr_warn("map '%s': unexpected key size %zu provided, expected %u\n",
10486 			map->name, key_sz, map->def.key_size);
10487 		return -EINVAL;
10488 	}
10489 
10490 	if (map->fd < 0) {
10491 		pr_warn("map '%s': can't use BPF map without FD (was it created?)\n", map->name);
10492 		return -EINVAL;
10493 	}
10494 
10495 	if (!check_value_sz)
10496 		return 0;
10497 
10498 	switch (map->def.type) {
10499 	case BPF_MAP_TYPE_PERCPU_ARRAY:
10500 	case BPF_MAP_TYPE_PERCPU_HASH:
10501 	case BPF_MAP_TYPE_LRU_PERCPU_HASH:
10502 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: {
10503 		int num_cpu = libbpf_num_possible_cpus();
10504 		size_t elem_sz = roundup(map->def.value_size, 8);
10505 
10506 		if (value_sz != num_cpu * elem_sz) {
10507 			pr_warn("map '%s': unexpected value size %zu provided for per-CPU map, expected %d * %zu = %zd\n",
10508 				map->name, value_sz, num_cpu, elem_sz, num_cpu * elem_sz);
10509 			return -EINVAL;
10510 		}
10511 		break;
10512 	}
10513 	default:
10514 		if (map->def.value_size != value_sz) {
10515 			pr_warn("map '%s': unexpected value size %zu provided, expected %u\n",
10516 				map->name, value_sz, map->def.value_size);
10517 			return -EINVAL;
10518 		}
10519 		break;
10520 	}
10521 	return 0;
10522 }
10523 
10524 int bpf_map__lookup_elem(const struct bpf_map *map,
10525 			 const void *key, size_t key_sz,
10526 			 void *value, size_t value_sz, __u64 flags)
10527 {
10528 	int err;
10529 
10530 	err = validate_map_op(map, key_sz, value_sz, true);
10531 	if (err)
10532 		return libbpf_err(err);
10533 
10534 	return bpf_map_lookup_elem_flags(map->fd, key, value, flags);
10535 }
10536 
10537 int bpf_map__update_elem(const struct bpf_map *map,
10538 			 const void *key, size_t key_sz,
10539 			 const void *value, size_t value_sz, __u64 flags)
10540 {
10541 	int err;
10542 
10543 	err = validate_map_op(map, key_sz, value_sz, true);
10544 	if (err)
10545 		return libbpf_err(err);
10546 
10547 	return bpf_map_update_elem(map->fd, key, value, flags);
10548 }
10549 
10550 int bpf_map__delete_elem(const struct bpf_map *map,
10551 			 const void *key, size_t key_sz, __u64 flags)
10552 {
10553 	int err;
10554 
10555 	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */);
10556 	if (err)
10557 		return libbpf_err(err);
10558 
10559 	return bpf_map_delete_elem_flags(map->fd, key, flags);
10560 }
10561 
10562 int bpf_map__lookup_and_delete_elem(const struct bpf_map *map,
10563 				    const void *key, size_t key_sz,
10564 				    void *value, size_t value_sz, __u64 flags)
10565 {
10566 	int err;
10567 
10568 	err = validate_map_op(map, key_sz, value_sz, true);
10569 	if (err)
10570 		return libbpf_err(err);
10571 
10572 	return bpf_map_lookup_and_delete_elem_flags(map->fd, key, value, flags);
10573 }
10574 
10575 int bpf_map__get_next_key(const struct bpf_map *map,
10576 			  const void *cur_key, void *next_key, size_t key_sz)
10577 {
10578 	int err;
10579 
10580 	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */);
10581 	if (err)
10582 		return libbpf_err(err);
10583 
10584 	return bpf_map_get_next_key(map->fd, cur_key, next_key);
10585 }
10586 
10587 long libbpf_get_error(const void *ptr)
10588 {
10589 	if (!IS_ERR_OR_NULL(ptr))
10590 		return 0;
10591 
10592 	if (IS_ERR(ptr))
10593 		errno = -PTR_ERR(ptr);
10594 
10595 	/* If ptr == NULL, then errno should be already set by the failing
10596 	 * API, because libbpf never returns NULL on success and it now always
10597 	 * sets errno on error. So no extra errno handling for ptr == NULL
10598 	 * case.
10599 	 */
10600 	return -errno;
10601 }
10602 
10603 /* Replace link's underlying BPF program with the new one */
10604 int bpf_link__update_program(struct bpf_link *link, struct bpf_program *prog)
10605 {
10606 	int ret;
10607 	int prog_fd = bpf_program__fd(prog);
10608 
10609 	if (prog_fd < 0) {
10610 		pr_warn("prog '%s': can't use BPF program without FD (was it loaded?)\n",
10611 			prog->name);
10612 		return libbpf_err(-EINVAL);
10613 	}
10614 
10615 	ret = bpf_link_update(bpf_link__fd(link), prog_fd, NULL);
10616 	return libbpf_err_errno(ret);
10617 }
10618 
10619 /* Release "ownership" of underlying BPF resource (typically, BPF program
10620  * attached to some BPF hook, e.g., tracepoint, kprobe, etc). Disconnected
10621  * link, when destructed through bpf_link__destroy() call won't attempt to
10622  * detach/unregisted that BPF resource. This is useful in situations where,
10623  * say, attached BPF program has to outlive userspace program that attached it
10624  * in the system. Depending on type of BPF program, though, there might be
10625  * additional steps (like pinning BPF program in BPF FS) necessary to ensure
10626  * exit of userspace program doesn't trigger automatic detachment and clean up
10627  * inside the kernel.
10628  */
10629 void bpf_link__disconnect(struct bpf_link *link)
10630 {
10631 	link->disconnected = true;
10632 }
10633 
10634 int bpf_link__destroy(struct bpf_link *link)
10635 {
10636 	int err = 0;
10637 
10638 	if (IS_ERR_OR_NULL(link))
10639 		return 0;
10640 
10641 	if (!link->disconnected && link->detach)
10642 		err = link->detach(link);
10643 	if (link->pin_path)
10644 		free(link->pin_path);
10645 	if (link->dealloc)
10646 		link->dealloc(link);
10647 	else
10648 		free(link);
10649 
10650 	return libbpf_err(err);
10651 }
10652 
10653 int bpf_link__fd(const struct bpf_link *link)
10654 {
10655 	return link->fd;
10656 }
10657 
10658 const char *bpf_link__pin_path(const struct bpf_link *link)
10659 {
10660 	return link->pin_path;
10661 }
10662 
10663 static int bpf_link__detach_fd(struct bpf_link *link)
10664 {
10665 	return libbpf_err_errno(close(link->fd));
10666 }
10667 
10668 struct bpf_link *bpf_link__open(const char *path)
10669 {
10670 	struct bpf_link *link;
10671 	int fd;
10672 
10673 	fd = bpf_obj_get(path);
10674 	if (fd < 0) {
10675 		fd = -errno;
10676 		pr_warn("failed to open link at %s: %d\n", path, fd);
10677 		return libbpf_err_ptr(fd);
10678 	}
10679 
10680 	link = calloc(1, sizeof(*link));
10681 	if (!link) {
10682 		close(fd);
10683 		return libbpf_err_ptr(-ENOMEM);
10684 	}
10685 	link->detach = &bpf_link__detach_fd;
10686 	link->fd = fd;
10687 
10688 	link->pin_path = strdup(path);
10689 	if (!link->pin_path) {
10690 		bpf_link__destroy(link);
10691 		return libbpf_err_ptr(-ENOMEM);
10692 	}
10693 
10694 	return link;
10695 }
10696 
10697 int bpf_link__detach(struct bpf_link *link)
10698 {
10699 	return bpf_link_detach(link->fd) ? -errno : 0;
10700 }
10701 
10702 int bpf_link__pin(struct bpf_link *link, const char *path)
10703 {
10704 	int err;
10705 
10706 	if (link->pin_path)
10707 		return libbpf_err(-EBUSY);
10708 	err = make_parent_dir(path);
10709 	if (err)
10710 		return libbpf_err(err);
10711 	err = check_path(path);
10712 	if (err)
10713 		return libbpf_err(err);
10714 
10715 	link->pin_path = strdup(path);
10716 	if (!link->pin_path)
10717 		return libbpf_err(-ENOMEM);
10718 
10719 	if (bpf_obj_pin(link->fd, link->pin_path)) {
10720 		err = -errno;
10721 		zfree(&link->pin_path);
10722 		return libbpf_err(err);
10723 	}
10724 
10725 	pr_debug("link fd=%d: pinned at %s\n", link->fd, link->pin_path);
10726 	return 0;
10727 }
10728 
10729 int bpf_link__unpin(struct bpf_link *link)
10730 {
10731 	int err;
10732 
10733 	if (!link->pin_path)
10734 		return libbpf_err(-EINVAL);
10735 
10736 	err = unlink(link->pin_path);
10737 	if (err != 0)
10738 		return -errno;
10739 
10740 	pr_debug("link fd=%d: unpinned from %s\n", link->fd, link->pin_path);
10741 	zfree(&link->pin_path);
10742 	return 0;
10743 }
10744 
10745 struct bpf_link_perf {
10746 	struct bpf_link link;
10747 	int perf_event_fd;
10748 	/* legacy kprobe support: keep track of probe identifier and type */
10749 	char *legacy_probe_name;
10750 	bool legacy_is_kprobe;
10751 	bool legacy_is_retprobe;
10752 };
10753 
10754 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe);
10755 static int remove_uprobe_event_legacy(const char *probe_name, bool retprobe);
10756 
10757 static int bpf_link_perf_detach(struct bpf_link *link)
10758 {
10759 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10760 	int err = 0;
10761 
10762 	if (ioctl(perf_link->perf_event_fd, PERF_EVENT_IOC_DISABLE, 0) < 0)
10763 		err = -errno;
10764 
10765 	if (perf_link->perf_event_fd != link->fd)
10766 		close(perf_link->perf_event_fd);
10767 	close(link->fd);
10768 
10769 	/* legacy uprobe/kprobe needs to be removed after perf event fd closure */
10770 	if (perf_link->legacy_probe_name) {
10771 		if (perf_link->legacy_is_kprobe) {
10772 			err = remove_kprobe_event_legacy(perf_link->legacy_probe_name,
10773 							 perf_link->legacy_is_retprobe);
10774 		} else {
10775 			err = remove_uprobe_event_legacy(perf_link->legacy_probe_name,
10776 							 perf_link->legacy_is_retprobe);
10777 		}
10778 	}
10779 
10780 	return err;
10781 }
10782 
10783 static void bpf_link_perf_dealloc(struct bpf_link *link)
10784 {
10785 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10786 
10787 	free(perf_link->legacy_probe_name);
10788 	free(perf_link);
10789 }
10790 
10791 struct bpf_link *bpf_program__attach_perf_event_opts(const struct bpf_program *prog, int pfd,
10792 						     const struct bpf_perf_event_opts *opts)
10793 {
10794 	char errmsg[STRERR_BUFSIZE];
10795 	struct bpf_link_perf *link;
10796 	int prog_fd, link_fd = -1, err;
10797 	bool force_ioctl_attach;
10798 
10799 	if (!OPTS_VALID(opts, bpf_perf_event_opts))
10800 		return libbpf_err_ptr(-EINVAL);
10801 
10802 	if (pfd < 0) {
10803 		pr_warn("prog '%s': invalid perf event FD %d\n",
10804 			prog->name, pfd);
10805 		return libbpf_err_ptr(-EINVAL);
10806 	}
10807 	prog_fd = bpf_program__fd(prog);
10808 	if (prog_fd < 0) {
10809 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
10810 			prog->name);
10811 		return libbpf_err_ptr(-EINVAL);
10812 	}
10813 
10814 	link = calloc(1, sizeof(*link));
10815 	if (!link)
10816 		return libbpf_err_ptr(-ENOMEM);
10817 	link->link.detach = &bpf_link_perf_detach;
10818 	link->link.dealloc = &bpf_link_perf_dealloc;
10819 	link->perf_event_fd = pfd;
10820 
10821 	force_ioctl_attach = OPTS_GET(opts, force_ioctl_attach, false);
10822 	if (kernel_supports(prog->obj, FEAT_PERF_LINK) && !force_ioctl_attach) {
10823 		DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_opts,
10824 			.perf_event.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0));
10825 
10826 		link_fd = bpf_link_create(prog_fd, pfd, BPF_PERF_EVENT, &link_opts);
10827 		if (link_fd < 0) {
10828 			err = -errno;
10829 			pr_warn("prog '%s': failed to create BPF link for perf_event FD %d: %d (%s)\n",
10830 				prog->name, pfd,
10831 				err, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10832 			goto err_out;
10833 		}
10834 		link->link.fd = link_fd;
10835 	} else {
10836 		if (OPTS_GET(opts, bpf_cookie, 0)) {
10837 			pr_warn("prog '%s': user context value is not supported\n", prog->name);
10838 			err = -EOPNOTSUPP;
10839 			goto err_out;
10840 		}
10841 
10842 		if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
10843 			err = -errno;
10844 			pr_warn("prog '%s': failed to attach to perf_event FD %d: %s\n",
10845 				prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10846 			if (err == -EPROTO)
10847 				pr_warn("prog '%s': try add PERF_SAMPLE_CALLCHAIN to or remove exclude_callchain_[kernel|user] from pfd %d\n",
10848 					prog->name, pfd);
10849 			goto err_out;
10850 		}
10851 		link->link.fd = pfd;
10852 	}
10853 	if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
10854 		err = -errno;
10855 		pr_warn("prog '%s': failed to enable perf_event FD %d: %s\n",
10856 			prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10857 		goto err_out;
10858 	}
10859 
10860 	return &link->link;
10861 err_out:
10862 	if (link_fd >= 0)
10863 		close(link_fd);
10864 	free(link);
10865 	return libbpf_err_ptr(err);
10866 }
10867 
10868 struct bpf_link *bpf_program__attach_perf_event(const struct bpf_program *prog, int pfd)
10869 {
10870 	return bpf_program__attach_perf_event_opts(prog, pfd, NULL);
10871 }
10872 
10873 /*
10874  * this function is expected to parse integer in the range of [0, 2^31-1] from
10875  * given file using scanf format string fmt. If actual parsed value is
10876  * negative, the result might be indistinguishable from error
10877  */
10878 static int parse_uint_from_file(const char *file, const char *fmt)
10879 {
10880 	char buf[STRERR_BUFSIZE];
10881 	int err, ret;
10882 	FILE *f;
10883 
10884 	f = fopen(file, "re");
10885 	if (!f) {
10886 		err = -errno;
10887 		pr_debug("failed to open '%s': %s\n", file,
10888 			 libbpf_strerror_r(err, buf, sizeof(buf)));
10889 		return err;
10890 	}
10891 	err = fscanf(f, fmt, &ret);
10892 	if (err != 1) {
10893 		err = err == EOF ? -EIO : -errno;
10894 		pr_debug("failed to parse '%s': %s\n", file,
10895 			libbpf_strerror_r(err, buf, sizeof(buf)));
10896 		fclose(f);
10897 		return err;
10898 	}
10899 	fclose(f);
10900 	return ret;
10901 }
10902 
10903 static int determine_kprobe_perf_type(void)
10904 {
10905 	const char *file = "/sys/bus/event_source/devices/kprobe/type";
10906 
10907 	return parse_uint_from_file(file, "%d\n");
10908 }
10909 
10910 static int determine_uprobe_perf_type(void)
10911 {
10912 	const char *file = "/sys/bus/event_source/devices/uprobe/type";
10913 
10914 	return parse_uint_from_file(file, "%d\n");
10915 }
10916 
10917 static int determine_kprobe_retprobe_bit(void)
10918 {
10919 	const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
10920 
10921 	return parse_uint_from_file(file, "config:%d\n");
10922 }
10923 
10924 static int determine_uprobe_retprobe_bit(void)
10925 {
10926 	const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
10927 
10928 	return parse_uint_from_file(file, "config:%d\n");
10929 }
10930 
10931 #define PERF_UPROBE_REF_CTR_OFFSET_BITS 32
10932 #define PERF_UPROBE_REF_CTR_OFFSET_SHIFT 32
10933 
10934 static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
10935 				 uint64_t offset, int pid, size_t ref_ctr_off)
10936 {
10937 	const size_t attr_sz = sizeof(struct perf_event_attr);
10938 	struct perf_event_attr attr;
10939 	char errmsg[STRERR_BUFSIZE];
10940 	int type, pfd;
10941 
10942 	if ((__u64)ref_ctr_off >= (1ULL << PERF_UPROBE_REF_CTR_OFFSET_BITS))
10943 		return -EINVAL;
10944 
10945 	memset(&attr, 0, attr_sz);
10946 
10947 	type = uprobe ? determine_uprobe_perf_type()
10948 		      : determine_kprobe_perf_type();
10949 	if (type < 0) {
10950 		pr_warn("failed to determine %s perf type: %s\n",
10951 			uprobe ? "uprobe" : "kprobe",
10952 			libbpf_strerror_r(type, errmsg, sizeof(errmsg)));
10953 		return type;
10954 	}
10955 	if (retprobe) {
10956 		int bit = uprobe ? determine_uprobe_retprobe_bit()
10957 				 : determine_kprobe_retprobe_bit();
10958 
10959 		if (bit < 0) {
10960 			pr_warn("failed to determine %s retprobe bit: %s\n",
10961 				uprobe ? "uprobe" : "kprobe",
10962 				libbpf_strerror_r(bit, errmsg, sizeof(errmsg)));
10963 			return bit;
10964 		}
10965 		attr.config |= 1 << bit;
10966 	}
10967 	attr.size = attr_sz;
10968 	attr.type = type;
10969 	attr.config |= (__u64)ref_ctr_off << PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
10970 	attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
10971 	attr.config2 = offset;		 /* kprobe_addr or probe_offset */
10972 
10973 	/* pid filter is meaningful only for uprobes */
10974 	pfd = syscall(__NR_perf_event_open, &attr,
10975 		      pid < 0 ? -1 : pid /* pid */,
10976 		      pid == -1 ? 0 : -1 /* cpu */,
10977 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
10978 	return pfd >= 0 ? pfd : -errno;
10979 }
10980 
10981 static int append_to_file(const char *file, const char *fmt, ...)
10982 {
10983 	int fd, n, err = 0;
10984 	va_list ap;
10985 	char buf[1024];
10986 
10987 	va_start(ap, fmt);
10988 	n = vsnprintf(buf, sizeof(buf), fmt, ap);
10989 	va_end(ap);
10990 
10991 	if (n < 0 || n >= sizeof(buf))
10992 		return -EINVAL;
10993 
10994 	fd = open(file, O_WRONLY | O_APPEND | O_CLOEXEC, 0);
10995 	if (fd < 0)
10996 		return -errno;
10997 
10998 	if (write(fd, buf, n) < 0)
10999 		err = -errno;
11000 
11001 	close(fd);
11002 	return err;
11003 }
11004 
11005 #define DEBUGFS "/sys/kernel/debug/tracing"
11006 #define TRACEFS "/sys/kernel/tracing"
11007 
11008 static bool use_debugfs(void)
11009 {
11010 	static int has_debugfs = -1;
11011 
11012 	if (has_debugfs < 0)
11013 		has_debugfs = faccessat(AT_FDCWD, DEBUGFS, F_OK, AT_EACCESS) == 0;
11014 
11015 	return has_debugfs == 1;
11016 }
11017 
11018 static const char *tracefs_path(void)
11019 {
11020 	return use_debugfs() ? DEBUGFS : TRACEFS;
11021 }
11022 
11023 static const char *tracefs_kprobe_events(void)
11024 {
11025 	return use_debugfs() ? DEBUGFS"/kprobe_events" : TRACEFS"/kprobe_events";
11026 }
11027 
11028 static const char *tracefs_uprobe_events(void)
11029 {
11030 	return use_debugfs() ? DEBUGFS"/uprobe_events" : TRACEFS"/uprobe_events";
11031 }
11032 
11033 static const char *tracefs_available_filter_functions(void)
11034 {
11035 	return use_debugfs() ? DEBUGFS"/available_filter_functions"
11036 			     : TRACEFS"/available_filter_functions";
11037 }
11038 
11039 static const char *tracefs_available_filter_functions_addrs(void)
11040 {
11041 	return use_debugfs() ? DEBUGFS"/available_filter_functions_addrs"
11042 			     : TRACEFS"/available_filter_functions_addrs";
11043 }
11044 
11045 static void gen_kprobe_legacy_event_name(char *buf, size_t buf_sz,
11046 					 const char *kfunc_name, size_t offset)
11047 {
11048 	static int index = 0;
11049 	int i;
11050 
11051 	snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx_%d", getpid(), kfunc_name, offset,
11052 		 __sync_fetch_and_add(&index, 1));
11053 
11054 	/* sanitize binary_path in the probe name */
11055 	for (i = 0; buf[i]; i++) {
11056 		if (!isalnum(buf[i]))
11057 			buf[i] = '_';
11058 	}
11059 }
11060 
11061 static int add_kprobe_event_legacy(const char *probe_name, bool retprobe,
11062 				   const char *kfunc_name, size_t offset)
11063 {
11064 	return append_to_file(tracefs_kprobe_events(), "%c:%s/%s %s+0x%zx",
11065 			      retprobe ? 'r' : 'p',
11066 			      retprobe ? "kretprobes" : "kprobes",
11067 			      probe_name, kfunc_name, offset);
11068 }
11069 
11070 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe)
11071 {
11072 	return append_to_file(tracefs_kprobe_events(), "-:%s/%s",
11073 			      retprobe ? "kretprobes" : "kprobes", probe_name);
11074 }
11075 
11076 static int determine_kprobe_perf_type_legacy(const char *probe_name, bool retprobe)
11077 {
11078 	char file[256];
11079 
11080 	snprintf(file, sizeof(file), "%s/events/%s/%s/id",
11081 		 tracefs_path(), retprobe ? "kretprobes" : "kprobes", probe_name);
11082 
11083 	return parse_uint_from_file(file, "%d\n");
11084 }
11085 
11086 static int perf_event_kprobe_open_legacy(const char *probe_name, bool retprobe,
11087 					 const char *kfunc_name, size_t offset, int pid)
11088 {
11089 	const size_t attr_sz = sizeof(struct perf_event_attr);
11090 	struct perf_event_attr attr;
11091 	char errmsg[STRERR_BUFSIZE];
11092 	int type, pfd, err;
11093 
11094 	err = add_kprobe_event_legacy(probe_name, retprobe, kfunc_name, offset);
11095 	if (err < 0) {
11096 		pr_warn("failed to add legacy kprobe event for '%s+0x%zx': %s\n",
11097 			kfunc_name, offset,
11098 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11099 		return err;
11100 	}
11101 	type = determine_kprobe_perf_type_legacy(probe_name, retprobe);
11102 	if (type < 0) {
11103 		err = type;
11104 		pr_warn("failed to determine legacy kprobe event id for '%s+0x%zx': %s\n",
11105 			kfunc_name, offset,
11106 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11107 		goto err_clean_legacy;
11108 	}
11109 
11110 	memset(&attr, 0, attr_sz);
11111 	attr.size = attr_sz;
11112 	attr.config = type;
11113 	attr.type = PERF_TYPE_TRACEPOINT;
11114 
11115 	pfd = syscall(__NR_perf_event_open, &attr,
11116 		      pid < 0 ? -1 : pid, /* pid */
11117 		      pid == -1 ? 0 : -1, /* cpu */
11118 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
11119 	if (pfd < 0) {
11120 		err = -errno;
11121 		pr_warn("legacy kprobe perf_event_open() failed: %s\n",
11122 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11123 		goto err_clean_legacy;
11124 	}
11125 	return pfd;
11126 
11127 err_clean_legacy:
11128 	/* Clear the newly added legacy kprobe_event */
11129 	remove_kprobe_event_legacy(probe_name, retprobe);
11130 	return err;
11131 }
11132 
11133 static const char *arch_specific_syscall_pfx(void)
11134 {
11135 #if defined(__x86_64__)
11136 	return "x64";
11137 #elif defined(__i386__)
11138 	return "ia32";
11139 #elif defined(__s390x__)
11140 	return "s390x";
11141 #elif defined(__s390__)
11142 	return "s390";
11143 #elif defined(__arm__)
11144 	return "arm";
11145 #elif defined(__aarch64__)
11146 	return "arm64";
11147 #elif defined(__mips__)
11148 	return "mips";
11149 #elif defined(__riscv)
11150 	return "riscv";
11151 #elif defined(__powerpc__)
11152 	return "powerpc";
11153 #elif defined(__powerpc64__)
11154 	return "powerpc64";
11155 #else
11156 	return NULL;
11157 #endif
11158 }
11159 
11160 int probe_kern_syscall_wrapper(int token_fd)
11161 {
11162 	char syscall_name[64];
11163 	const char *ksys_pfx;
11164 
11165 	ksys_pfx = arch_specific_syscall_pfx();
11166 	if (!ksys_pfx)
11167 		return 0;
11168 
11169 	snprintf(syscall_name, sizeof(syscall_name), "__%s_sys_bpf", ksys_pfx);
11170 
11171 	if (determine_kprobe_perf_type() >= 0) {
11172 		int pfd;
11173 
11174 		pfd = perf_event_open_probe(false, false, syscall_name, 0, getpid(), 0);
11175 		if (pfd >= 0)
11176 			close(pfd);
11177 
11178 		return pfd >= 0 ? 1 : 0;
11179 	} else { /* legacy mode */
11180 		char probe_name[128];
11181 
11182 		gen_kprobe_legacy_event_name(probe_name, sizeof(probe_name), syscall_name, 0);
11183 		if (add_kprobe_event_legacy(probe_name, false, syscall_name, 0) < 0)
11184 			return 0;
11185 
11186 		(void)remove_kprobe_event_legacy(probe_name, false);
11187 		return 1;
11188 	}
11189 }
11190 
11191 struct bpf_link *
11192 bpf_program__attach_kprobe_opts(const struct bpf_program *prog,
11193 				const char *func_name,
11194 				const struct bpf_kprobe_opts *opts)
11195 {
11196 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
11197 	enum probe_attach_mode attach_mode;
11198 	char errmsg[STRERR_BUFSIZE];
11199 	char *legacy_probe = NULL;
11200 	struct bpf_link *link;
11201 	size_t offset;
11202 	bool retprobe, legacy;
11203 	int pfd, err;
11204 
11205 	if (!OPTS_VALID(opts, bpf_kprobe_opts))
11206 		return libbpf_err_ptr(-EINVAL);
11207 
11208 	attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
11209 	retprobe = OPTS_GET(opts, retprobe, false);
11210 	offset = OPTS_GET(opts, offset, 0);
11211 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11212 
11213 	legacy = determine_kprobe_perf_type() < 0;
11214 	switch (attach_mode) {
11215 	case PROBE_ATTACH_MODE_LEGACY:
11216 		legacy = true;
11217 		pe_opts.force_ioctl_attach = true;
11218 		break;
11219 	case PROBE_ATTACH_MODE_PERF:
11220 		if (legacy)
11221 			return libbpf_err_ptr(-ENOTSUP);
11222 		pe_opts.force_ioctl_attach = true;
11223 		break;
11224 	case PROBE_ATTACH_MODE_LINK:
11225 		if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
11226 			return libbpf_err_ptr(-ENOTSUP);
11227 		break;
11228 	case PROBE_ATTACH_MODE_DEFAULT:
11229 		break;
11230 	default:
11231 		return libbpf_err_ptr(-EINVAL);
11232 	}
11233 
11234 	if (!legacy) {
11235 		pfd = perf_event_open_probe(false /* uprobe */, retprobe,
11236 					    func_name, offset,
11237 					    -1 /* pid */, 0 /* ref_ctr_off */);
11238 	} else {
11239 		char probe_name[256];
11240 
11241 		gen_kprobe_legacy_event_name(probe_name, sizeof(probe_name),
11242 					     func_name, offset);
11243 
11244 		legacy_probe = strdup(probe_name);
11245 		if (!legacy_probe)
11246 			return libbpf_err_ptr(-ENOMEM);
11247 
11248 		pfd = perf_event_kprobe_open_legacy(legacy_probe, retprobe, func_name,
11249 						    offset, -1 /* pid */);
11250 	}
11251 	if (pfd < 0) {
11252 		err = -errno;
11253 		pr_warn("prog '%s': failed to create %s '%s+0x%zx' perf event: %s\n",
11254 			prog->name, retprobe ? "kretprobe" : "kprobe",
11255 			func_name, offset,
11256 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11257 		goto err_out;
11258 	}
11259 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
11260 	err = libbpf_get_error(link);
11261 	if (err) {
11262 		close(pfd);
11263 		pr_warn("prog '%s': failed to attach to %s '%s+0x%zx': %s\n",
11264 			prog->name, retprobe ? "kretprobe" : "kprobe",
11265 			func_name, offset,
11266 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11267 		goto err_clean_legacy;
11268 	}
11269 	if (legacy) {
11270 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
11271 
11272 		perf_link->legacy_probe_name = legacy_probe;
11273 		perf_link->legacy_is_kprobe = true;
11274 		perf_link->legacy_is_retprobe = retprobe;
11275 	}
11276 
11277 	return link;
11278 
11279 err_clean_legacy:
11280 	if (legacy)
11281 		remove_kprobe_event_legacy(legacy_probe, retprobe);
11282 err_out:
11283 	free(legacy_probe);
11284 	return libbpf_err_ptr(err);
11285 }
11286 
11287 struct bpf_link *bpf_program__attach_kprobe(const struct bpf_program *prog,
11288 					    bool retprobe,
11289 					    const char *func_name)
11290 {
11291 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts,
11292 		.retprobe = retprobe,
11293 	);
11294 
11295 	return bpf_program__attach_kprobe_opts(prog, func_name, &opts);
11296 }
11297 
11298 struct bpf_link *bpf_program__attach_ksyscall(const struct bpf_program *prog,
11299 					      const char *syscall_name,
11300 					      const struct bpf_ksyscall_opts *opts)
11301 {
11302 	LIBBPF_OPTS(bpf_kprobe_opts, kprobe_opts);
11303 	char func_name[128];
11304 
11305 	if (!OPTS_VALID(opts, bpf_ksyscall_opts))
11306 		return libbpf_err_ptr(-EINVAL);
11307 
11308 	if (kernel_supports(prog->obj, FEAT_SYSCALL_WRAPPER)) {
11309 		/* arch_specific_syscall_pfx() should never return NULL here
11310 		 * because it is guarded by kernel_supports(). However, since
11311 		 * compiler does not know that we have an explicit conditional
11312 		 * as well.
11313 		 */
11314 		snprintf(func_name, sizeof(func_name), "__%s_sys_%s",
11315 			 arch_specific_syscall_pfx() ? : "", syscall_name);
11316 	} else {
11317 		snprintf(func_name, sizeof(func_name), "__se_sys_%s", syscall_name);
11318 	}
11319 
11320 	kprobe_opts.retprobe = OPTS_GET(opts, retprobe, false);
11321 	kprobe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11322 
11323 	return bpf_program__attach_kprobe_opts(prog, func_name, &kprobe_opts);
11324 }
11325 
11326 /* Adapted from perf/util/string.c */
11327 bool glob_match(const char *str, const char *pat)
11328 {
11329 	while (*str && *pat && *pat != '*') {
11330 		if (*pat == '?') {      /* Matches any single character */
11331 			str++;
11332 			pat++;
11333 			continue;
11334 		}
11335 		if (*str != *pat)
11336 			return false;
11337 		str++;
11338 		pat++;
11339 	}
11340 	/* Check wild card */
11341 	if (*pat == '*') {
11342 		while (*pat == '*')
11343 			pat++;
11344 		if (!*pat) /* Tail wild card matches all */
11345 			return true;
11346 		while (*str)
11347 			if (glob_match(str++, pat))
11348 				return true;
11349 	}
11350 	return !*str && !*pat;
11351 }
11352 
11353 struct kprobe_multi_resolve {
11354 	const char *pattern;
11355 	unsigned long *addrs;
11356 	size_t cap;
11357 	size_t cnt;
11358 };
11359 
11360 struct avail_kallsyms_data {
11361 	char **syms;
11362 	size_t cnt;
11363 	struct kprobe_multi_resolve *res;
11364 };
11365 
11366 static int avail_func_cmp(const void *a, const void *b)
11367 {
11368 	return strcmp(*(const char **)a, *(const char **)b);
11369 }
11370 
11371 static int avail_kallsyms_cb(unsigned long long sym_addr, char sym_type,
11372 			     const char *sym_name, void *ctx)
11373 {
11374 	struct avail_kallsyms_data *data = ctx;
11375 	struct kprobe_multi_resolve *res = data->res;
11376 	int err;
11377 
11378 	if (!bsearch(&sym_name, data->syms, data->cnt, sizeof(*data->syms), avail_func_cmp))
11379 		return 0;
11380 
11381 	err = libbpf_ensure_mem((void **)&res->addrs, &res->cap, sizeof(*res->addrs), res->cnt + 1);
11382 	if (err)
11383 		return err;
11384 
11385 	res->addrs[res->cnt++] = (unsigned long)sym_addr;
11386 	return 0;
11387 }
11388 
11389 static int libbpf_available_kallsyms_parse(struct kprobe_multi_resolve *res)
11390 {
11391 	const char *available_functions_file = tracefs_available_filter_functions();
11392 	struct avail_kallsyms_data data;
11393 	char sym_name[500];
11394 	FILE *f;
11395 	int err = 0, ret, i;
11396 	char **syms = NULL;
11397 	size_t cap = 0, cnt = 0;
11398 
11399 	f = fopen(available_functions_file, "re");
11400 	if (!f) {
11401 		err = -errno;
11402 		pr_warn("failed to open %s: %d\n", available_functions_file, err);
11403 		return err;
11404 	}
11405 
11406 	while (true) {
11407 		char *name;
11408 
11409 		ret = fscanf(f, "%499s%*[^\n]\n", sym_name);
11410 		if (ret == EOF && feof(f))
11411 			break;
11412 
11413 		if (ret != 1) {
11414 			pr_warn("failed to parse available_filter_functions entry: %d\n", ret);
11415 			err = -EINVAL;
11416 			goto cleanup;
11417 		}
11418 
11419 		if (!glob_match(sym_name, res->pattern))
11420 			continue;
11421 
11422 		err = libbpf_ensure_mem((void **)&syms, &cap, sizeof(*syms), cnt + 1);
11423 		if (err)
11424 			goto cleanup;
11425 
11426 		name = strdup(sym_name);
11427 		if (!name) {
11428 			err = -errno;
11429 			goto cleanup;
11430 		}
11431 
11432 		syms[cnt++] = name;
11433 	}
11434 
11435 	/* no entries found, bail out */
11436 	if (cnt == 0) {
11437 		err = -ENOENT;
11438 		goto cleanup;
11439 	}
11440 
11441 	/* sort available functions */
11442 	qsort(syms, cnt, sizeof(*syms), avail_func_cmp);
11443 
11444 	data.syms = syms;
11445 	data.res = res;
11446 	data.cnt = cnt;
11447 	libbpf_kallsyms_parse(avail_kallsyms_cb, &data);
11448 
11449 	if (res->cnt == 0)
11450 		err = -ENOENT;
11451 
11452 cleanup:
11453 	for (i = 0; i < cnt; i++)
11454 		free((char *)syms[i]);
11455 	free(syms);
11456 
11457 	fclose(f);
11458 	return err;
11459 }
11460 
11461 static bool has_available_filter_functions_addrs(void)
11462 {
11463 	return access(tracefs_available_filter_functions_addrs(), R_OK) != -1;
11464 }
11465 
11466 static int libbpf_available_kprobes_parse(struct kprobe_multi_resolve *res)
11467 {
11468 	const char *available_path = tracefs_available_filter_functions_addrs();
11469 	char sym_name[500];
11470 	FILE *f;
11471 	int ret, err = 0;
11472 	unsigned long long sym_addr;
11473 
11474 	f = fopen(available_path, "re");
11475 	if (!f) {
11476 		err = -errno;
11477 		pr_warn("failed to open %s: %d\n", available_path, err);
11478 		return err;
11479 	}
11480 
11481 	while (true) {
11482 		ret = fscanf(f, "%llx %499s%*[^\n]\n", &sym_addr, sym_name);
11483 		if (ret == EOF && feof(f))
11484 			break;
11485 
11486 		if (ret != 2) {
11487 			pr_warn("failed to parse available_filter_functions_addrs entry: %d\n",
11488 				ret);
11489 			err = -EINVAL;
11490 			goto cleanup;
11491 		}
11492 
11493 		if (!glob_match(sym_name, res->pattern))
11494 			continue;
11495 
11496 		err = libbpf_ensure_mem((void **)&res->addrs, &res->cap,
11497 					sizeof(*res->addrs), res->cnt + 1);
11498 		if (err)
11499 			goto cleanup;
11500 
11501 		res->addrs[res->cnt++] = (unsigned long)sym_addr;
11502 	}
11503 
11504 	if (res->cnt == 0)
11505 		err = -ENOENT;
11506 
11507 cleanup:
11508 	fclose(f);
11509 	return err;
11510 }
11511 
11512 struct bpf_link *
11513 bpf_program__attach_kprobe_multi_opts(const struct bpf_program *prog,
11514 				      const char *pattern,
11515 				      const struct bpf_kprobe_multi_opts *opts)
11516 {
11517 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
11518 	struct kprobe_multi_resolve res = {
11519 		.pattern = pattern,
11520 	};
11521 	enum bpf_attach_type attach_type;
11522 	struct bpf_link *link = NULL;
11523 	char errmsg[STRERR_BUFSIZE];
11524 	const unsigned long *addrs;
11525 	int err, link_fd, prog_fd;
11526 	bool retprobe, session;
11527 	const __u64 *cookies;
11528 	const char **syms;
11529 	size_t cnt;
11530 
11531 	if (!OPTS_VALID(opts, bpf_kprobe_multi_opts))
11532 		return libbpf_err_ptr(-EINVAL);
11533 
11534 	prog_fd = bpf_program__fd(prog);
11535 	if (prog_fd < 0) {
11536 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
11537 			prog->name);
11538 		return libbpf_err_ptr(-EINVAL);
11539 	}
11540 
11541 	syms    = OPTS_GET(opts, syms, false);
11542 	addrs   = OPTS_GET(opts, addrs, false);
11543 	cnt     = OPTS_GET(opts, cnt, false);
11544 	cookies = OPTS_GET(opts, cookies, false);
11545 
11546 	if (!pattern && !addrs && !syms)
11547 		return libbpf_err_ptr(-EINVAL);
11548 	if (pattern && (addrs || syms || cookies || cnt))
11549 		return libbpf_err_ptr(-EINVAL);
11550 	if (!pattern && !cnt)
11551 		return libbpf_err_ptr(-EINVAL);
11552 	if (addrs && syms)
11553 		return libbpf_err_ptr(-EINVAL);
11554 
11555 	if (pattern) {
11556 		if (has_available_filter_functions_addrs())
11557 			err = libbpf_available_kprobes_parse(&res);
11558 		else
11559 			err = libbpf_available_kallsyms_parse(&res);
11560 		if (err)
11561 			goto error;
11562 		addrs = res.addrs;
11563 		cnt = res.cnt;
11564 	}
11565 
11566 	retprobe = OPTS_GET(opts, retprobe, false);
11567 	session  = OPTS_GET(opts, session, false);
11568 
11569 	if (retprobe && session)
11570 		return libbpf_err_ptr(-EINVAL);
11571 
11572 	attach_type = session ? BPF_TRACE_KPROBE_SESSION : BPF_TRACE_KPROBE_MULTI;
11573 
11574 	lopts.kprobe_multi.syms = syms;
11575 	lopts.kprobe_multi.addrs = addrs;
11576 	lopts.kprobe_multi.cookies = cookies;
11577 	lopts.kprobe_multi.cnt = cnt;
11578 	lopts.kprobe_multi.flags = retprobe ? BPF_F_KPROBE_MULTI_RETURN : 0;
11579 
11580 	link = calloc(1, sizeof(*link));
11581 	if (!link) {
11582 		err = -ENOMEM;
11583 		goto error;
11584 	}
11585 	link->detach = &bpf_link__detach_fd;
11586 
11587 	link_fd = bpf_link_create(prog_fd, 0, attach_type, &lopts);
11588 	if (link_fd < 0) {
11589 		err = -errno;
11590 		pr_warn("prog '%s': failed to attach: %s\n",
11591 			prog->name, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11592 		goto error;
11593 	}
11594 	link->fd = link_fd;
11595 	free(res.addrs);
11596 	return link;
11597 
11598 error:
11599 	free(link);
11600 	free(res.addrs);
11601 	return libbpf_err_ptr(err);
11602 }
11603 
11604 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11605 {
11606 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts);
11607 	unsigned long offset = 0;
11608 	const char *func_name;
11609 	char *func;
11610 	int n;
11611 
11612 	*link = NULL;
11613 
11614 	/* no auto-attach for SEC("kprobe") and SEC("kretprobe") */
11615 	if (strcmp(prog->sec_name, "kprobe") == 0 || strcmp(prog->sec_name, "kretprobe") == 0)
11616 		return 0;
11617 
11618 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe/");
11619 	if (opts.retprobe)
11620 		func_name = prog->sec_name + sizeof("kretprobe/") - 1;
11621 	else
11622 		func_name = prog->sec_name + sizeof("kprobe/") - 1;
11623 
11624 	n = sscanf(func_name, "%m[a-zA-Z0-9_.]+%li", &func, &offset);
11625 	if (n < 1) {
11626 		pr_warn("kprobe name is invalid: %s\n", func_name);
11627 		return -EINVAL;
11628 	}
11629 	if (opts.retprobe && offset != 0) {
11630 		free(func);
11631 		pr_warn("kretprobes do not support offset specification\n");
11632 		return -EINVAL;
11633 	}
11634 
11635 	opts.offset = offset;
11636 	*link = bpf_program__attach_kprobe_opts(prog, func, &opts);
11637 	free(func);
11638 	return libbpf_get_error(*link);
11639 }
11640 
11641 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11642 {
11643 	LIBBPF_OPTS(bpf_ksyscall_opts, opts);
11644 	const char *syscall_name;
11645 
11646 	*link = NULL;
11647 
11648 	/* no auto-attach for SEC("ksyscall") and SEC("kretsyscall") */
11649 	if (strcmp(prog->sec_name, "ksyscall") == 0 || strcmp(prog->sec_name, "kretsyscall") == 0)
11650 		return 0;
11651 
11652 	opts.retprobe = str_has_pfx(prog->sec_name, "kretsyscall/");
11653 	if (opts.retprobe)
11654 		syscall_name = prog->sec_name + sizeof("kretsyscall/") - 1;
11655 	else
11656 		syscall_name = prog->sec_name + sizeof("ksyscall/") - 1;
11657 
11658 	*link = bpf_program__attach_ksyscall(prog, syscall_name, &opts);
11659 	return *link ? 0 : -errno;
11660 }
11661 
11662 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11663 {
11664 	LIBBPF_OPTS(bpf_kprobe_multi_opts, opts);
11665 	const char *spec;
11666 	char *pattern;
11667 	int n;
11668 
11669 	*link = NULL;
11670 
11671 	/* no auto-attach for SEC("kprobe.multi") and SEC("kretprobe.multi") */
11672 	if (strcmp(prog->sec_name, "kprobe.multi") == 0 ||
11673 	    strcmp(prog->sec_name, "kretprobe.multi") == 0)
11674 		return 0;
11675 
11676 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe.multi/");
11677 	if (opts.retprobe)
11678 		spec = prog->sec_name + sizeof("kretprobe.multi/") - 1;
11679 	else
11680 		spec = prog->sec_name + sizeof("kprobe.multi/") - 1;
11681 
11682 	n = sscanf(spec, "%m[a-zA-Z0-9_.*?]", &pattern);
11683 	if (n < 1) {
11684 		pr_warn("kprobe multi pattern is invalid: %s\n", spec);
11685 		return -EINVAL;
11686 	}
11687 
11688 	*link = bpf_program__attach_kprobe_multi_opts(prog, pattern, &opts);
11689 	free(pattern);
11690 	return libbpf_get_error(*link);
11691 }
11692 
11693 static int attach_kprobe_session(const struct bpf_program *prog, long cookie,
11694 				 struct bpf_link **link)
11695 {
11696 	LIBBPF_OPTS(bpf_kprobe_multi_opts, opts, .session = true);
11697 	const char *spec;
11698 	char *pattern;
11699 	int n;
11700 
11701 	*link = NULL;
11702 
11703 	/* no auto-attach for SEC("kprobe.session") */
11704 	if (strcmp(prog->sec_name, "kprobe.session") == 0)
11705 		return 0;
11706 
11707 	spec = prog->sec_name + sizeof("kprobe.session/") - 1;
11708 	n = sscanf(spec, "%m[a-zA-Z0-9_.*?]", &pattern);
11709 	if (n < 1) {
11710 		pr_warn("kprobe session pattern is invalid: %s\n", spec);
11711 		return -EINVAL;
11712 	}
11713 
11714 	*link = bpf_program__attach_kprobe_multi_opts(prog, pattern, &opts);
11715 	free(pattern);
11716 	return *link ? 0 : -errno;
11717 }
11718 
11719 static int attach_uprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11720 {
11721 	char *probe_type = NULL, *binary_path = NULL, *func_name = NULL;
11722 	LIBBPF_OPTS(bpf_uprobe_multi_opts, opts);
11723 	int n, ret = -EINVAL;
11724 
11725 	*link = NULL;
11726 
11727 	n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[^\n]",
11728 		   &probe_type, &binary_path, &func_name);
11729 	switch (n) {
11730 	case 1:
11731 		/* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
11732 		ret = 0;
11733 		break;
11734 	case 3:
11735 		opts.retprobe = str_has_pfx(probe_type, "uretprobe.multi");
11736 		*link = bpf_program__attach_uprobe_multi(prog, -1, binary_path, func_name, &opts);
11737 		ret = libbpf_get_error(*link);
11738 		break;
11739 	default:
11740 		pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
11741 			prog->sec_name);
11742 		break;
11743 	}
11744 	free(probe_type);
11745 	free(binary_path);
11746 	free(func_name);
11747 	return ret;
11748 }
11749 
11750 static void gen_uprobe_legacy_event_name(char *buf, size_t buf_sz,
11751 					 const char *binary_path, uint64_t offset)
11752 {
11753 	int i;
11754 
11755 	snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx", getpid(), binary_path, (size_t)offset);
11756 
11757 	/* sanitize binary_path in the probe name */
11758 	for (i = 0; buf[i]; i++) {
11759 		if (!isalnum(buf[i]))
11760 			buf[i] = '_';
11761 	}
11762 }
11763 
11764 static inline int add_uprobe_event_legacy(const char *probe_name, bool retprobe,
11765 					  const char *binary_path, size_t offset)
11766 {
11767 	return append_to_file(tracefs_uprobe_events(), "%c:%s/%s %s:0x%zx",
11768 			      retprobe ? 'r' : 'p',
11769 			      retprobe ? "uretprobes" : "uprobes",
11770 			      probe_name, binary_path, offset);
11771 }
11772 
11773 static inline int remove_uprobe_event_legacy(const char *probe_name, bool retprobe)
11774 {
11775 	return append_to_file(tracefs_uprobe_events(), "-:%s/%s",
11776 			      retprobe ? "uretprobes" : "uprobes", probe_name);
11777 }
11778 
11779 static int determine_uprobe_perf_type_legacy(const char *probe_name, bool retprobe)
11780 {
11781 	char file[512];
11782 
11783 	snprintf(file, sizeof(file), "%s/events/%s/%s/id",
11784 		 tracefs_path(), retprobe ? "uretprobes" : "uprobes", probe_name);
11785 
11786 	return parse_uint_from_file(file, "%d\n");
11787 }
11788 
11789 static int perf_event_uprobe_open_legacy(const char *probe_name, bool retprobe,
11790 					 const char *binary_path, size_t offset, int pid)
11791 {
11792 	const size_t attr_sz = sizeof(struct perf_event_attr);
11793 	struct perf_event_attr attr;
11794 	int type, pfd, err;
11795 
11796 	err = add_uprobe_event_legacy(probe_name, retprobe, binary_path, offset);
11797 	if (err < 0) {
11798 		pr_warn("failed to add legacy uprobe event for %s:0x%zx: %d\n",
11799 			binary_path, (size_t)offset, err);
11800 		return err;
11801 	}
11802 	type = determine_uprobe_perf_type_legacy(probe_name, retprobe);
11803 	if (type < 0) {
11804 		err = type;
11805 		pr_warn("failed to determine legacy uprobe event id for %s:0x%zx: %d\n",
11806 			binary_path, offset, err);
11807 		goto err_clean_legacy;
11808 	}
11809 
11810 	memset(&attr, 0, attr_sz);
11811 	attr.size = attr_sz;
11812 	attr.config = type;
11813 	attr.type = PERF_TYPE_TRACEPOINT;
11814 
11815 	pfd = syscall(__NR_perf_event_open, &attr,
11816 		      pid < 0 ? -1 : pid, /* pid */
11817 		      pid == -1 ? 0 : -1, /* cpu */
11818 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
11819 	if (pfd < 0) {
11820 		err = -errno;
11821 		pr_warn("legacy uprobe perf_event_open() failed: %d\n", err);
11822 		goto err_clean_legacy;
11823 	}
11824 	return pfd;
11825 
11826 err_clean_legacy:
11827 	/* Clear the newly added legacy uprobe_event */
11828 	remove_uprobe_event_legacy(probe_name, retprobe);
11829 	return err;
11830 }
11831 
11832 /* Find offset of function name in archive specified by path. Currently
11833  * supported are .zip files that do not compress their contents, as used on
11834  * Android in the form of APKs, for example. "file_name" is the name of the ELF
11835  * file inside the archive. "func_name" matches symbol name or name@@LIB for
11836  * library functions.
11837  *
11838  * An overview of the APK format specifically provided here:
11839  * https://en.wikipedia.org/w/index.php?title=Apk_(file_format)&oldid=1139099120#Package_contents
11840  */
11841 static long elf_find_func_offset_from_archive(const char *archive_path, const char *file_name,
11842 					      const char *func_name)
11843 {
11844 	struct zip_archive *archive;
11845 	struct zip_entry entry;
11846 	long ret;
11847 	Elf *elf;
11848 
11849 	archive = zip_archive_open(archive_path);
11850 	if (IS_ERR(archive)) {
11851 		ret = PTR_ERR(archive);
11852 		pr_warn("zip: failed to open %s: %ld\n", archive_path, ret);
11853 		return ret;
11854 	}
11855 
11856 	ret = zip_archive_find_entry(archive, file_name, &entry);
11857 	if (ret) {
11858 		pr_warn("zip: could not find archive member %s in %s: %ld\n", file_name,
11859 			archive_path, ret);
11860 		goto out;
11861 	}
11862 	pr_debug("zip: found entry for %s in %s at 0x%lx\n", file_name, archive_path,
11863 		 (unsigned long)entry.data_offset);
11864 
11865 	if (entry.compression) {
11866 		pr_warn("zip: entry %s of %s is compressed and cannot be handled\n", file_name,
11867 			archive_path);
11868 		ret = -LIBBPF_ERRNO__FORMAT;
11869 		goto out;
11870 	}
11871 
11872 	elf = elf_memory((void *)entry.data, entry.data_length);
11873 	if (!elf) {
11874 		pr_warn("elf: could not read elf file %s from %s: %s\n", file_name, archive_path,
11875 			elf_errmsg(-1));
11876 		ret = -LIBBPF_ERRNO__LIBELF;
11877 		goto out;
11878 	}
11879 
11880 	ret = elf_find_func_offset(elf, file_name, func_name);
11881 	if (ret > 0) {
11882 		pr_debug("elf: symbol address match for %s of %s in %s: 0x%x + 0x%lx = 0x%lx\n",
11883 			 func_name, file_name, archive_path, entry.data_offset, ret,
11884 			 ret + entry.data_offset);
11885 		ret += entry.data_offset;
11886 	}
11887 	elf_end(elf);
11888 
11889 out:
11890 	zip_archive_close(archive);
11891 	return ret;
11892 }
11893 
11894 static const char *arch_specific_lib_paths(void)
11895 {
11896 	/*
11897 	 * Based on https://packages.debian.org/sid/libc6.
11898 	 *
11899 	 * Assume that the traced program is built for the same architecture
11900 	 * as libbpf, which should cover the vast majority of cases.
11901 	 */
11902 #if defined(__x86_64__)
11903 	return "/lib/x86_64-linux-gnu";
11904 #elif defined(__i386__)
11905 	return "/lib/i386-linux-gnu";
11906 #elif defined(__s390x__)
11907 	return "/lib/s390x-linux-gnu";
11908 #elif defined(__s390__)
11909 	return "/lib/s390-linux-gnu";
11910 #elif defined(__arm__) && defined(__SOFTFP__)
11911 	return "/lib/arm-linux-gnueabi";
11912 #elif defined(__arm__) && !defined(__SOFTFP__)
11913 	return "/lib/arm-linux-gnueabihf";
11914 #elif defined(__aarch64__)
11915 	return "/lib/aarch64-linux-gnu";
11916 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 64
11917 	return "/lib/mips64el-linux-gnuabi64";
11918 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 32
11919 	return "/lib/mipsel-linux-gnu";
11920 #elif defined(__powerpc64__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
11921 	return "/lib/powerpc64le-linux-gnu";
11922 #elif defined(__sparc__) && defined(__arch64__)
11923 	return "/lib/sparc64-linux-gnu";
11924 #elif defined(__riscv) && __riscv_xlen == 64
11925 	return "/lib/riscv64-linux-gnu";
11926 #else
11927 	return NULL;
11928 #endif
11929 }
11930 
11931 /* Get full path to program/shared library. */
11932 static int resolve_full_path(const char *file, char *result, size_t result_sz)
11933 {
11934 	const char *search_paths[3] = {};
11935 	int i, perm;
11936 
11937 	if (str_has_sfx(file, ".so") || strstr(file, ".so.")) {
11938 		search_paths[0] = getenv("LD_LIBRARY_PATH");
11939 		search_paths[1] = "/usr/lib64:/usr/lib";
11940 		search_paths[2] = arch_specific_lib_paths();
11941 		perm = R_OK;
11942 	} else {
11943 		search_paths[0] = getenv("PATH");
11944 		search_paths[1] = "/usr/bin:/usr/sbin";
11945 		perm = R_OK | X_OK;
11946 	}
11947 
11948 	for (i = 0; i < ARRAY_SIZE(search_paths); i++) {
11949 		const char *s;
11950 
11951 		if (!search_paths[i])
11952 			continue;
11953 		for (s = search_paths[i]; s != NULL; s = strchr(s, ':')) {
11954 			char *next_path;
11955 			int seg_len;
11956 
11957 			if (s[0] == ':')
11958 				s++;
11959 			next_path = strchr(s, ':');
11960 			seg_len = next_path ? next_path - s : strlen(s);
11961 			if (!seg_len)
11962 				continue;
11963 			snprintf(result, result_sz, "%.*s/%s", seg_len, s, file);
11964 			/* ensure it has required permissions */
11965 			if (faccessat(AT_FDCWD, result, perm, AT_EACCESS) < 0)
11966 				continue;
11967 			pr_debug("resolved '%s' to '%s'\n", file, result);
11968 			return 0;
11969 		}
11970 	}
11971 	return -ENOENT;
11972 }
11973 
11974 struct bpf_link *
11975 bpf_program__attach_uprobe_multi(const struct bpf_program *prog,
11976 				 pid_t pid,
11977 				 const char *path,
11978 				 const char *func_pattern,
11979 				 const struct bpf_uprobe_multi_opts *opts)
11980 {
11981 	const unsigned long *ref_ctr_offsets = NULL, *offsets = NULL;
11982 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
11983 	unsigned long *resolved_offsets = NULL;
11984 	int err = 0, link_fd, prog_fd;
11985 	struct bpf_link *link = NULL;
11986 	char errmsg[STRERR_BUFSIZE];
11987 	char full_path[PATH_MAX];
11988 	const __u64 *cookies;
11989 	const char **syms;
11990 	size_t cnt;
11991 
11992 	if (!OPTS_VALID(opts, bpf_uprobe_multi_opts))
11993 		return libbpf_err_ptr(-EINVAL);
11994 
11995 	prog_fd = bpf_program__fd(prog);
11996 	if (prog_fd < 0) {
11997 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
11998 			prog->name);
11999 		return libbpf_err_ptr(-EINVAL);
12000 	}
12001 
12002 	syms = OPTS_GET(opts, syms, NULL);
12003 	offsets = OPTS_GET(opts, offsets, NULL);
12004 	ref_ctr_offsets = OPTS_GET(opts, ref_ctr_offsets, NULL);
12005 	cookies = OPTS_GET(opts, cookies, NULL);
12006 	cnt = OPTS_GET(opts, cnt, 0);
12007 
12008 	/*
12009 	 * User can specify 2 mutually exclusive set of inputs:
12010 	 *
12011 	 * 1) use only path/func_pattern/pid arguments
12012 	 *
12013 	 * 2) use path/pid with allowed combinations of:
12014 	 *    syms/offsets/ref_ctr_offsets/cookies/cnt
12015 	 *
12016 	 *    - syms and offsets are mutually exclusive
12017 	 *    - ref_ctr_offsets and cookies are optional
12018 	 *
12019 	 * Any other usage results in error.
12020 	 */
12021 
12022 	if (!path)
12023 		return libbpf_err_ptr(-EINVAL);
12024 	if (!func_pattern && cnt == 0)
12025 		return libbpf_err_ptr(-EINVAL);
12026 
12027 	if (func_pattern) {
12028 		if (syms || offsets || ref_ctr_offsets || cookies || cnt)
12029 			return libbpf_err_ptr(-EINVAL);
12030 	} else {
12031 		if (!!syms == !!offsets)
12032 			return libbpf_err_ptr(-EINVAL);
12033 	}
12034 
12035 	if (func_pattern) {
12036 		if (!strchr(path, '/')) {
12037 			err = resolve_full_path(path, full_path, sizeof(full_path));
12038 			if (err) {
12039 				pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
12040 					prog->name, path, err);
12041 				return libbpf_err_ptr(err);
12042 			}
12043 			path = full_path;
12044 		}
12045 
12046 		err = elf_resolve_pattern_offsets(path, func_pattern,
12047 						  &resolved_offsets, &cnt);
12048 		if (err < 0)
12049 			return libbpf_err_ptr(err);
12050 		offsets = resolved_offsets;
12051 	} else if (syms) {
12052 		err = elf_resolve_syms_offsets(path, cnt, syms, &resolved_offsets, STT_FUNC);
12053 		if (err < 0)
12054 			return libbpf_err_ptr(err);
12055 		offsets = resolved_offsets;
12056 	}
12057 
12058 	lopts.uprobe_multi.path = path;
12059 	lopts.uprobe_multi.offsets = offsets;
12060 	lopts.uprobe_multi.ref_ctr_offsets = ref_ctr_offsets;
12061 	lopts.uprobe_multi.cookies = cookies;
12062 	lopts.uprobe_multi.cnt = cnt;
12063 	lopts.uprobe_multi.flags = OPTS_GET(opts, retprobe, false) ? BPF_F_UPROBE_MULTI_RETURN : 0;
12064 
12065 	if (pid == 0)
12066 		pid = getpid();
12067 	if (pid > 0)
12068 		lopts.uprobe_multi.pid = pid;
12069 
12070 	link = calloc(1, sizeof(*link));
12071 	if (!link) {
12072 		err = -ENOMEM;
12073 		goto error;
12074 	}
12075 	link->detach = &bpf_link__detach_fd;
12076 
12077 	link_fd = bpf_link_create(prog_fd, 0, BPF_TRACE_UPROBE_MULTI, &lopts);
12078 	if (link_fd < 0) {
12079 		err = -errno;
12080 		pr_warn("prog '%s': failed to attach multi-uprobe: %s\n",
12081 			prog->name, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
12082 		goto error;
12083 	}
12084 	link->fd = link_fd;
12085 	free(resolved_offsets);
12086 	return link;
12087 
12088 error:
12089 	free(resolved_offsets);
12090 	free(link);
12091 	return libbpf_err_ptr(err);
12092 }
12093 
12094 LIBBPF_API struct bpf_link *
12095 bpf_program__attach_uprobe_opts(const struct bpf_program *prog, pid_t pid,
12096 				const char *binary_path, size_t func_offset,
12097 				const struct bpf_uprobe_opts *opts)
12098 {
12099 	const char *archive_path = NULL, *archive_sep = NULL;
12100 	char errmsg[STRERR_BUFSIZE], *legacy_probe = NULL;
12101 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
12102 	enum probe_attach_mode attach_mode;
12103 	char full_path[PATH_MAX];
12104 	struct bpf_link *link;
12105 	size_t ref_ctr_off;
12106 	int pfd, err;
12107 	bool retprobe, legacy;
12108 	const char *func_name;
12109 
12110 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
12111 		return libbpf_err_ptr(-EINVAL);
12112 
12113 	attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
12114 	retprobe = OPTS_GET(opts, retprobe, false);
12115 	ref_ctr_off = OPTS_GET(opts, ref_ctr_offset, 0);
12116 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
12117 
12118 	if (!binary_path)
12119 		return libbpf_err_ptr(-EINVAL);
12120 
12121 	/* Check if "binary_path" refers to an archive. */
12122 	archive_sep = strstr(binary_path, "!/");
12123 	if (archive_sep) {
12124 		full_path[0] = '\0';
12125 		libbpf_strlcpy(full_path, binary_path,
12126 			       min(sizeof(full_path), (size_t)(archive_sep - binary_path + 1)));
12127 		archive_path = full_path;
12128 		binary_path = archive_sep + 2;
12129 	} else if (!strchr(binary_path, '/')) {
12130 		err = resolve_full_path(binary_path, full_path, sizeof(full_path));
12131 		if (err) {
12132 			pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
12133 				prog->name, binary_path, err);
12134 			return libbpf_err_ptr(err);
12135 		}
12136 		binary_path = full_path;
12137 	}
12138 	func_name = OPTS_GET(opts, func_name, NULL);
12139 	if (func_name) {
12140 		long sym_off;
12141 
12142 		if (archive_path) {
12143 			sym_off = elf_find_func_offset_from_archive(archive_path, binary_path,
12144 								    func_name);
12145 			binary_path = archive_path;
12146 		} else {
12147 			sym_off = elf_find_func_offset_from_file(binary_path, func_name);
12148 		}
12149 		if (sym_off < 0)
12150 			return libbpf_err_ptr(sym_off);
12151 		func_offset += sym_off;
12152 	}
12153 
12154 	legacy = determine_uprobe_perf_type() < 0;
12155 	switch (attach_mode) {
12156 	case PROBE_ATTACH_MODE_LEGACY:
12157 		legacy = true;
12158 		pe_opts.force_ioctl_attach = true;
12159 		break;
12160 	case PROBE_ATTACH_MODE_PERF:
12161 		if (legacy)
12162 			return libbpf_err_ptr(-ENOTSUP);
12163 		pe_opts.force_ioctl_attach = true;
12164 		break;
12165 	case PROBE_ATTACH_MODE_LINK:
12166 		if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
12167 			return libbpf_err_ptr(-ENOTSUP);
12168 		break;
12169 	case PROBE_ATTACH_MODE_DEFAULT:
12170 		break;
12171 	default:
12172 		return libbpf_err_ptr(-EINVAL);
12173 	}
12174 
12175 	if (!legacy) {
12176 		pfd = perf_event_open_probe(true /* uprobe */, retprobe, binary_path,
12177 					    func_offset, pid, ref_ctr_off);
12178 	} else {
12179 		char probe_name[PATH_MAX + 64];
12180 
12181 		if (ref_ctr_off)
12182 			return libbpf_err_ptr(-EINVAL);
12183 
12184 		gen_uprobe_legacy_event_name(probe_name, sizeof(probe_name),
12185 					     binary_path, func_offset);
12186 
12187 		legacy_probe = strdup(probe_name);
12188 		if (!legacy_probe)
12189 			return libbpf_err_ptr(-ENOMEM);
12190 
12191 		pfd = perf_event_uprobe_open_legacy(legacy_probe, retprobe,
12192 						    binary_path, func_offset, pid);
12193 	}
12194 	if (pfd < 0) {
12195 		err = -errno;
12196 		pr_warn("prog '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
12197 			prog->name, retprobe ? "uretprobe" : "uprobe",
12198 			binary_path, func_offset,
12199 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
12200 		goto err_out;
12201 	}
12202 
12203 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
12204 	err = libbpf_get_error(link);
12205 	if (err) {
12206 		close(pfd);
12207 		pr_warn("prog '%s': failed to attach to %s '%s:0x%zx': %s\n",
12208 			prog->name, retprobe ? "uretprobe" : "uprobe",
12209 			binary_path, func_offset,
12210 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
12211 		goto err_clean_legacy;
12212 	}
12213 	if (legacy) {
12214 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
12215 
12216 		perf_link->legacy_probe_name = legacy_probe;
12217 		perf_link->legacy_is_kprobe = false;
12218 		perf_link->legacy_is_retprobe = retprobe;
12219 	}
12220 	return link;
12221 
12222 err_clean_legacy:
12223 	if (legacy)
12224 		remove_uprobe_event_legacy(legacy_probe, retprobe);
12225 err_out:
12226 	free(legacy_probe);
12227 	return libbpf_err_ptr(err);
12228 }
12229 
12230 /* Format of u[ret]probe section definition supporting auto-attach:
12231  * u[ret]probe/binary:function[+offset]
12232  *
12233  * binary can be an absolute/relative path or a filename; the latter is resolved to a
12234  * full binary path via bpf_program__attach_uprobe_opts.
12235  *
12236  * Specifying uprobe+ ensures we carry out strict matching; either "uprobe" must be
12237  * specified (and auto-attach is not possible) or the above format is specified for
12238  * auto-attach.
12239  */
12240 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12241 {
12242 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts);
12243 	char *probe_type = NULL, *binary_path = NULL, *func_name = NULL, *func_off;
12244 	int n, c, ret = -EINVAL;
12245 	long offset = 0;
12246 
12247 	*link = NULL;
12248 
12249 	n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[^\n]",
12250 		   &probe_type, &binary_path, &func_name);
12251 	switch (n) {
12252 	case 1:
12253 		/* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
12254 		ret = 0;
12255 		break;
12256 	case 2:
12257 		pr_warn("prog '%s': section '%s' missing ':function[+offset]' specification\n",
12258 			prog->name, prog->sec_name);
12259 		break;
12260 	case 3:
12261 		/* check if user specifies `+offset`, if yes, this should be
12262 		 * the last part of the string, make sure sscanf read to EOL
12263 		 */
12264 		func_off = strrchr(func_name, '+');
12265 		if (func_off) {
12266 			n = sscanf(func_off, "+%li%n", &offset, &c);
12267 			if (n == 1 && *(func_off + c) == '\0')
12268 				func_off[0] = '\0';
12269 			else
12270 				offset = 0;
12271 		}
12272 		opts.retprobe = strcmp(probe_type, "uretprobe") == 0 ||
12273 				strcmp(probe_type, "uretprobe.s") == 0;
12274 		if (opts.retprobe && offset != 0) {
12275 			pr_warn("prog '%s': uretprobes do not support offset specification\n",
12276 				prog->name);
12277 			break;
12278 		}
12279 		opts.func_name = func_name;
12280 		*link = bpf_program__attach_uprobe_opts(prog, -1, binary_path, offset, &opts);
12281 		ret = libbpf_get_error(*link);
12282 		break;
12283 	default:
12284 		pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
12285 			prog->sec_name);
12286 		break;
12287 	}
12288 	free(probe_type);
12289 	free(binary_path);
12290 	free(func_name);
12291 
12292 	return ret;
12293 }
12294 
12295 struct bpf_link *bpf_program__attach_uprobe(const struct bpf_program *prog,
12296 					    bool retprobe, pid_t pid,
12297 					    const char *binary_path,
12298 					    size_t func_offset)
12299 {
12300 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts, .retprobe = retprobe);
12301 
12302 	return bpf_program__attach_uprobe_opts(prog, pid, binary_path, func_offset, &opts);
12303 }
12304 
12305 struct bpf_link *bpf_program__attach_usdt(const struct bpf_program *prog,
12306 					  pid_t pid, const char *binary_path,
12307 					  const char *usdt_provider, const char *usdt_name,
12308 					  const struct bpf_usdt_opts *opts)
12309 {
12310 	char resolved_path[512];
12311 	struct bpf_object *obj = prog->obj;
12312 	struct bpf_link *link;
12313 	__u64 usdt_cookie;
12314 	int err;
12315 
12316 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
12317 		return libbpf_err_ptr(-EINVAL);
12318 
12319 	if (bpf_program__fd(prog) < 0) {
12320 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
12321 			prog->name);
12322 		return libbpf_err_ptr(-EINVAL);
12323 	}
12324 
12325 	if (!binary_path)
12326 		return libbpf_err_ptr(-EINVAL);
12327 
12328 	if (!strchr(binary_path, '/')) {
12329 		err = resolve_full_path(binary_path, resolved_path, sizeof(resolved_path));
12330 		if (err) {
12331 			pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
12332 				prog->name, binary_path, err);
12333 			return libbpf_err_ptr(err);
12334 		}
12335 		binary_path = resolved_path;
12336 	}
12337 
12338 	/* USDT manager is instantiated lazily on first USDT attach. It will
12339 	 * be destroyed together with BPF object in bpf_object__close().
12340 	 */
12341 	if (IS_ERR(obj->usdt_man))
12342 		return libbpf_ptr(obj->usdt_man);
12343 	if (!obj->usdt_man) {
12344 		obj->usdt_man = usdt_manager_new(obj);
12345 		if (IS_ERR(obj->usdt_man))
12346 			return libbpf_ptr(obj->usdt_man);
12347 	}
12348 
12349 	usdt_cookie = OPTS_GET(opts, usdt_cookie, 0);
12350 	link = usdt_manager_attach_usdt(obj->usdt_man, prog, pid, binary_path,
12351 					usdt_provider, usdt_name, usdt_cookie);
12352 	err = libbpf_get_error(link);
12353 	if (err)
12354 		return libbpf_err_ptr(err);
12355 	return link;
12356 }
12357 
12358 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12359 {
12360 	char *path = NULL, *provider = NULL, *name = NULL;
12361 	const char *sec_name;
12362 	int n, err;
12363 
12364 	sec_name = bpf_program__section_name(prog);
12365 	if (strcmp(sec_name, "usdt") == 0) {
12366 		/* no auto-attach for just SEC("usdt") */
12367 		*link = NULL;
12368 		return 0;
12369 	}
12370 
12371 	n = sscanf(sec_name, "usdt/%m[^:]:%m[^:]:%m[^:]", &path, &provider, &name);
12372 	if (n != 3) {
12373 		pr_warn("invalid section '%s', expected SEC(\"usdt/<path>:<provider>:<name>\")\n",
12374 			sec_name);
12375 		err = -EINVAL;
12376 	} else {
12377 		*link = bpf_program__attach_usdt(prog, -1 /* any process */, path,
12378 						 provider, name, NULL);
12379 		err = libbpf_get_error(*link);
12380 	}
12381 	free(path);
12382 	free(provider);
12383 	free(name);
12384 	return err;
12385 }
12386 
12387 static int determine_tracepoint_id(const char *tp_category,
12388 				   const char *tp_name)
12389 {
12390 	char file[PATH_MAX];
12391 	int ret;
12392 
12393 	ret = snprintf(file, sizeof(file), "%s/events/%s/%s/id",
12394 		       tracefs_path(), tp_category, tp_name);
12395 	if (ret < 0)
12396 		return -errno;
12397 	if (ret >= sizeof(file)) {
12398 		pr_debug("tracepoint %s/%s path is too long\n",
12399 			 tp_category, tp_name);
12400 		return -E2BIG;
12401 	}
12402 	return parse_uint_from_file(file, "%d\n");
12403 }
12404 
12405 static int perf_event_open_tracepoint(const char *tp_category,
12406 				      const char *tp_name)
12407 {
12408 	const size_t attr_sz = sizeof(struct perf_event_attr);
12409 	struct perf_event_attr attr;
12410 	char errmsg[STRERR_BUFSIZE];
12411 	int tp_id, pfd, err;
12412 
12413 	tp_id = determine_tracepoint_id(tp_category, tp_name);
12414 	if (tp_id < 0) {
12415 		pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
12416 			tp_category, tp_name,
12417 			libbpf_strerror_r(tp_id, errmsg, sizeof(errmsg)));
12418 		return tp_id;
12419 	}
12420 
12421 	memset(&attr, 0, attr_sz);
12422 	attr.type = PERF_TYPE_TRACEPOINT;
12423 	attr.size = attr_sz;
12424 	attr.config = tp_id;
12425 
12426 	pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
12427 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
12428 	if (pfd < 0) {
12429 		err = -errno;
12430 		pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
12431 			tp_category, tp_name,
12432 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
12433 		return err;
12434 	}
12435 	return pfd;
12436 }
12437 
12438 struct bpf_link *bpf_program__attach_tracepoint_opts(const struct bpf_program *prog,
12439 						     const char *tp_category,
12440 						     const char *tp_name,
12441 						     const struct bpf_tracepoint_opts *opts)
12442 {
12443 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
12444 	char errmsg[STRERR_BUFSIZE];
12445 	struct bpf_link *link;
12446 	int pfd, err;
12447 
12448 	if (!OPTS_VALID(opts, bpf_tracepoint_opts))
12449 		return libbpf_err_ptr(-EINVAL);
12450 
12451 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
12452 
12453 	pfd = perf_event_open_tracepoint(tp_category, tp_name);
12454 	if (pfd < 0) {
12455 		pr_warn("prog '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
12456 			prog->name, tp_category, tp_name,
12457 			libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
12458 		return libbpf_err_ptr(pfd);
12459 	}
12460 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
12461 	err = libbpf_get_error(link);
12462 	if (err) {
12463 		close(pfd);
12464 		pr_warn("prog '%s': failed to attach to tracepoint '%s/%s': %s\n",
12465 			prog->name, tp_category, tp_name,
12466 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
12467 		return libbpf_err_ptr(err);
12468 	}
12469 	return link;
12470 }
12471 
12472 struct bpf_link *bpf_program__attach_tracepoint(const struct bpf_program *prog,
12473 						const char *tp_category,
12474 						const char *tp_name)
12475 {
12476 	return bpf_program__attach_tracepoint_opts(prog, tp_category, tp_name, NULL);
12477 }
12478 
12479 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12480 {
12481 	char *sec_name, *tp_cat, *tp_name;
12482 
12483 	*link = NULL;
12484 
12485 	/* no auto-attach for SEC("tp") or SEC("tracepoint") */
12486 	if (strcmp(prog->sec_name, "tp") == 0 || strcmp(prog->sec_name, "tracepoint") == 0)
12487 		return 0;
12488 
12489 	sec_name = strdup(prog->sec_name);
12490 	if (!sec_name)
12491 		return -ENOMEM;
12492 
12493 	/* extract "tp/<category>/<name>" or "tracepoint/<category>/<name>" */
12494 	if (str_has_pfx(prog->sec_name, "tp/"))
12495 		tp_cat = sec_name + sizeof("tp/") - 1;
12496 	else
12497 		tp_cat = sec_name + sizeof("tracepoint/") - 1;
12498 	tp_name = strchr(tp_cat, '/');
12499 	if (!tp_name) {
12500 		free(sec_name);
12501 		return -EINVAL;
12502 	}
12503 	*tp_name = '\0';
12504 	tp_name++;
12505 
12506 	*link = bpf_program__attach_tracepoint(prog, tp_cat, tp_name);
12507 	free(sec_name);
12508 	return libbpf_get_error(*link);
12509 }
12510 
12511 struct bpf_link *
12512 bpf_program__attach_raw_tracepoint_opts(const struct bpf_program *prog,
12513 					const char *tp_name,
12514 					struct bpf_raw_tracepoint_opts *opts)
12515 {
12516 	LIBBPF_OPTS(bpf_raw_tp_opts, raw_opts);
12517 	char errmsg[STRERR_BUFSIZE];
12518 	struct bpf_link *link;
12519 	int prog_fd, pfd;
12520 
12521 	if (!OPTS_VALID(opts, bpf_raw_tracepoint_opts))
12522 		return libbpf_err_ptr(-EINVAL);
12523 
12524 	prog_fd = bpf_program__fd(prog);
12525 	if (prog_fd < 0) {
12526 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12527 		return libbpf_err_ptr(-EINVAL);
12528 	}
12529 
12530 	link = calloc(1, sizeof(*link));
12531 	if (!link)
12532 		return libbpf_err_ptr(-ENOMEM);
12533 	link->detach = &bpf_link__detach_fd;
12534 
12535 	raw_opts.tp_name = tp_name;
12536 	raw_opts.cookie = OPTS_GET(opts, cookie, 0);
12537 	pfd = bpf_raw_tracepoint_open_opts(prog_fd, &raw_opts);
12538 	if (pfd < 0) {
12539 		pfd = -errno;
12540 		free(link);
12541 		pr_warn("prog '%s': failed to attach to raw tracepoint '%s': %s\n",
12542 			prog->name, tp_name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
12543 		return libbpf_err_ptr(pfd);
12544 	}
12545 	link->fd = pfd;
12546 	return link;
12547 }
12548 
12549 struct bpf_link *bpf_program__attach_raw_tracepoint(const struct bpf_program *prog,
12550 						    const char *tp_name)
12551 {
12552 	return bpf_program__attach_raw_tracepoint_opts(prog, tp_name, NULL);
12553 }
12554 
12555 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12556 {
12557 	static const char *const prefixes[] = {
12558 		"raw_tp",
12559 		"raw_tracepoint",
12560 		"raw_tp.w",
12561 		"raw_tracepoint.w",
12562 	};
12563 	size_t i;
12564 	const char *tp_name = NULL;
12565 
12566 	*link = NULL;
12567 
12568 	for (i = 0; i < ARRAY_SIZE(prefixes); i++) {
12569 		size_t pfx_len;
12570 
12571 		if (!str_has_pfx(prog->sec_name, prefixes[i]))
12572 			continue;
12573 
12574 		pfx_len = strlen(prefixes[i]);
12575 		/* no auto-attach case of, e.g., SEC("raw_tp") */
12576 		if (prog->sec_name[pfx_len] == '\0')
12577 			return 0;
12578 
12579 		if (prog->sec_name[pfx_len] != '/')
12580 			continue;
12581 
12582 		tp_name = prog->sec_name + pfx_len + 1;
12583 		break;
12584 	}
12585 
12586 	if (!tp_name) {
12587 		pr_warn("prog '%s': invalid section name '%s'\n",
12588 			prog->name, prog->sec_name);
12589 		return -EINVAL;
12590 	}
12591 
12592 	*link = bpf_program__attach_raw_tracepoint(prog, tp_name);
12593 	return libbpf_get_error(*link);
12594 }
12595 
12596 /* Common logic for all BPF program types that attach to a btf_id */
12597 static struct bpf_link *bpf_program__attach_btf_id(const struct bpf_program *prog,
12598 						   const struct bpf_trace_opts *opts)
12599 {
12600 	LIBBPF_OPTS(bpf_link_create_opts, link_opts);
12601 	char errmsg[STRERR_BUFSIZE];
12602 	struct bpf_link *link;
12603 	int prog_fd, pfd;
12604 
12605 	if (!OPTS_VALID(opts, bpf_trace_opts))
12606 		return libbpf_err_ptr(-EINVAL);
12607 
12608 	prog_fd = bpf_program__fd(prog);
12609 	if (prog_fd < 0) {
12610 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12611 		return libbpf_err_ptr(-EINVAL);
12612 	}
12613 
12614 	link = calloc(1, sizeof(*link));
12615 	if (!link)
12616 		return libbpf_err_ptr(-ENOMEM);
12617 	link->detach = &bpf_link__detach_fd;
12618 
12619 	/* libbpf is smart enough to redirect to BPF_RAW_TRACEPOINT_OPEN on old kernels */
12620 	link_opts.tracing.cookie = OPTS_GET(opts, cookie, 0);
12621 	pfd = bpf_link_create(prog_fd, 0, bpf_program__expected_attach_type(prog), &link_opts);
12622 	if (pfd < 0) {
12623 		pfd = -errno;
12624 		free(link);
12625 		pr_warn("prog '%s': failed to attach: %s\n",
12626 			prog->name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
12627 		return libbpf_err_ptr(pfd);
12628 	}
12629 	link->fd = pfd;
12630 	return link;
12631 }
12632 
12633 struct bpf_link *bpf_program__attach_trace(const struct bpf_program *prog)
12634 {
12635 	return bpf_program__attach_btf_id(prog, NULL);
12636 }
12637 
12638 struct bpf_link *bpf_program__attach_trace_opts(const struct bpf_program *prog,
12639 						const struct bpf_trace_opts *opts)
12640 {
12641 	return bpf_program__attach_btf_id(prog, opts);
12642 }
12643 
12644 struct bpf_link *bpf_program__attach_lsm(const struct bpf_program *prog)
12645 {
12646 	return bpf_program__attach_btf_id(prog, NULL);
12647 }
12648 
12649 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12650 {
12651 	*link = bpf_program__attach_trace(prog);
12652 	return libbpf_get_error(*link);
12653 }
12654 
12655 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12656 {
12657 	*link = bpf_program__attach_lsm(prog);
12658 	return libbpf_get_error(*link);
12659 }
12660 
12661 static struct bpf_link *
12662 bpf_program_attach_fd(const struct bpf_program *prog,
12663 		      int target_fd, const char *target_name,
12664 		      const struct bpf_link_create_opts *opts)
12665 {
12666 	enum bpf_attach_type attach_type;
12667 	char errmsg[STRERR_BUFSIZE];
12668 	struct bpf_link *link;
12669 	int prog_fd, link_fd;
12670 
12671 	prog_fd = bpf_program__fd(prog);
12672 	if (prog_fd < 0) {
12673 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12674 		return libbpf_err_ptr(-EINVAL);
12675 	}
12676 
12677 	link = calloc(1, sizeof(*link));
12678 	if (!link)
12679 		return libbpf_err_ptr(-ENOMEM);
12680 	link->detach = &bpf_link__detach_fd;
12681 
12682 	attach_type = bpf_program__expected_attach_type(prog);
12683 	link_fd = bpf_link_create(prog_fd, target_fd, attach_type, opts);
12684 	if (link_fd < 0) {
12685 		link_fd = -errno;
12686 		free(link);
12687 		pr_warn("prog '%s': failed to attach to %s: %s\n",
12688 			prog->name, target_name,
12689 			libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
12690 		return libbpf_err_ptr(link_fd);
12691 	}
12692 	link->fd = link_fd;
12693 	return link;
12694 }
12695 
12696 struct bpf_link *
12697 bpf_program__attach_cgroup(const struct bpf_program *prog, int cgroup_fd)
12698 {
12699 	return bpf_program_attach_fd(prog, cgroup_fd, "cgroup", NULL);
12700 }
12701 
12702 struct bpf_link *
12703 bpf_program__attach_netns(const struct bpf_program *prog, int netns_fd)
12704 {
12705 	return bpf_program_attach_fd(prog, netns_fd, "netns", NULL);
12706 }
12707 
12708 struct bpf_link *
12709 bpf_program__attach_sockmap(const struct bpf_program *prog, int map_fd)
12710 {
12711 	return bpf_program_attach_fd(prog, map_fd, "sockmap", NULL);
12712 }
12713 
12714 struct bpf_link *bpf_program__attach_xdp(const struct bpf_program *prog, int ifindex)
12715 {
12716 	/* target_fd/target_ifindex use the same field in LINK_CREATE */
12717 	return bpf_program_attach_fd(prog, ifindex, "xdp", NULL);
12718 }
12719 
12720 struct bpf_link *
12721 bpf_program__attach_tcx(const struct bpf_program *prog, int ifindex,
12722 			const struct bpf_tcx_opts *opts)
12723 {
12724 	LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
12725 	__u32 relative_id;
12726 	int relative_fd;
12727 
12728 	if (!OPTS_VALID(opts, bpf_tcx_opts))
12729 		return libbpf_err_ptr(-EINVAL);
12730 
12731 	relative_id = OPTS_GET(opts, relative_id, 0);
12732 	relative_fd = OPTS_GET(opts, relative_fd, 0);
12733 
12734 	/* validate we don't have unexpected combinations of non-zero fields */
12735 	if (!ifindex) {
12736 		pr_warn("prog '%s': target netdevice ifindex cannot be zero\n",
12737 			prog->name);
12738 		return libbpf_err_ptr(-EINVAL);
12739 	}
12740 	if (relative_fd && relative_id) {
12741 		pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
12742 			prog->name);
12743 		return libbpf_err_ptr(-EINVAL);
12744 	}
12745 
12746 	link_create_opts.tcx.expected_revision = OPTS_GET(opts, expected_revision, 0);
12747 	link_create_opts.tcx.relative_fd = relative_fd;
12748 	link_create_opts.tcx.relative_id = relative_id;
12749 	link_create_opts.flags = OPTS_GET(opts, flags, 0);
12750 
12751 	/* target_fd/target_ifindex use the same field in LINK_CREATE */
12752 	return bpf_program_attach_fd(prog, ifindex, "tcx", &link_create_opts);
12753 }
12754 
12755 struct bpf_link *
12756 bpf_program__attach_netkit(const struct bpf_program *prog, int ifindex,
12757 			   const struct bpf_netkit_opts *opts)
12758 {
12759 	LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
12760 	__u32 relative_id;
12761 	int relative_fd;
12762 
12763 	if (!OPTS_VALID(opts, bpf_netkit_opts))
12764 		return libbpf_err_ptr(-EINVAL);
12765 
12766 	relative_id = OPTS_GET(opts, relative_id, 0);
12767 	relative_fd = OPTS_GET(opts, relative_fd, 0);
12768 
12769 	/* validate we don't have unexpected combinations of non-zero fields */
12770 	if (!ifindex) {
12771 		pr_warn("prog '%s': target netdevice ifindex cannot be zero\n",
12772 			prog->name);
12773 		return libbpf_err_ptr(-EINVAL);
12774 	}
12775 	if (relative_fd && relative_id) {
12776 		pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
12777 			prog->name);
12778 		return libbpf_err_ptr(-EINVAL);
12779 	}
12780 
12781 	link_create_opts.netkit.expected_revision = OPTS_GET(opts, expected_revision, 0);
12782 	link_create_opts.netkit.relative_fd = relative_fd;
12783 	link_create_opts.netkit.relative_id = relative_id;
12784 	link_create_opts.flags = OPTS_GET(opts, flags, 0);
12785 
12786 	return bpf_program_attach_fd(prog, ifindex, "netkit", &link_create_opts);
12787 }
12788 
12789 struct bpf_link *bpf_program__attach_freplace(const struct bpf_program *prog,
12790 					      int target_fd,
12791 					      const char *attach_func_name)
12792 {
12793 	int btf_id;
12794 
12795 	if (!!target_fd != !!attach_func_name) {
12796 		pr_warn("prog '%s': supply none or both of target_fd and attach_func_name\n",
12797 			prog->name);
12798 		return libbpf_err_ptr(-EINVAL);
12799 	}
12800 
12801 	if (prog->type != BPF_PROG_TYPE_EXT) {
12802 		pr_warn("prog '%s': only BPF_PROG_TYPE_EXT can attach as freplace\n",
12803 			prog->name);
12804 		return libbpf_err_ptr(-EINVAL);
12805 	}
12806 
12807 	if (target_fd) {
12808 		LIBBPF_OPTS(bpf_link_create_opts, target_opts);
12809 
12810 		btf_id = libbpf_find_prog_btf_id(attach_func_name, target_fd);
12811 		if (btf_id < 0)
12812 			return libbpf_err_ptr(btf_id);
12813 
12814 		target_opts.target_btf_id = btf_id;
12815 
12816 		return bpf_program_attach_fd(prog, target_fd, "freplace",
12817 					     &target_opts);
12818 	} else {
12819 		/* no target, so use raw_tracepoint_open for compatibility
12820 		 * with old kernels
12821 		 */
12822 		return bpf_program__attach_trace(prog);
12823 	}
12824 }
12825 
12826 struct bpf_link *
12827 bpf_program__attach_iter(const struct bpf_program *prog,
12828 			 const struct bpf_iter_attach_opts *opts)
12829 {
12830 	DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
12831 	char errmsg[STRERR_BUFSIZE];
12832 	struct bpf_link *link;
12833 	int prog_fd, link_fd;
12834 	__u32 target_fd = 0;
12835 
12836 	if (!OPTS_VALID(opts, bpf_iter_attach_opts))
12837 		return libbpf_err_ptr(-EINVAL);
12838 
12839 	link_create_opts.iter_info = OPTS_GET(opts, link_info, (void *)0);
12840 	link_create_opts.iter_info_len = OPTS_GET(opts, link_info_len, 0);
12841 
12842 	prog_fd = bpf_program__fd(prog);
12843 	if (prog_fd < 0) {
12844 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12845 		return libbpf_err_ptr(-EINVAL);
12846 	}
12847 
12848 	link = calloc(1, sizeof(*link));
12849 	if (!link)
12850 		return libbpf_err_ptr(-ENOMEM);
12851 	link->detach = &bpf_link__detach_fd;
12852 
12853 	link_fd = bpf_link_create(prog_fd, target_fd, BPF_TRACE_ITER,
12854 				  &link_create_opts);
12855 	if (link_fd < 0) {
12856 		link_fd = -errno;
12857 		free(link);
12858 		pr_warn("prog '%s': failed to attach to iterator: %s\n",
12859 			prog->name, libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
12860 		return libbpf_err_ptr(link_fd);
12861 	}
12862 	link->fd = link_fd;
12863 	return link;
12864 }
12865 
12866 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12867 {
12868 	*link = bpf_program__attach_iter(prog, NULL);
12869 	return libbpf_get_error(*link);
12870 }
12871 
12872 struct bpf_link *bpf_program__attach_netfilter(const struct bpf_program *prog,
12873 					       const struct bpf_netfilter_opts *opts)
12874 {
12875 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
12876 	struct bpf_link *link;
12877 	int prog_fd, link_fd;
12878 
12879 	if (!OPTS_VALID(opts, bpf_netfilter_opts))
12880 		return libbpf_err_ptr(-EINVAL);
12881 
12882 	prog_fd = bpf_program__fd(prog);
12883 	if (prog_fd < 0) {
12884 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12885 		return libbpf_err_ptr(-EINVAL);
12886 	}
12887 
12888 	link = calloc(1, sizeof(*link));
12889 	if (!link)
12890 		return libbpf_err_ptr(-ENOMEM);
12891 
12892 	link->detach = &bpf_link__detach_fd;
12893 
12894 	lopts.netfilter.pf = OPTS_GET(opts, pf, 0);
12895 	lopts.netfilter.hooknum = OPTS_GET(opts, hooknum, 0);
12896 	lopts.netfilter.priority = OPTS_GET(opts, priority, 0);
12897 	lopts.netfilter.flags = OPTS_GET(opts, flags, 0);
12898 
12899 	link_fd = bpf_link_create(prog_fd, 0, BPF_NETFILTER, &lopts);
12900 	if (link_fd < 0) {
12901 		char errmsg[STRERR_BUFSIZE];
12902 
12903 		link_fd = -errno;
12904 		free(link);
12905 		pr_warn("prog '%s': failed to attach to netfilter: %s\n",
12906 			prog->name, libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
12907 		return libbpf_err_ptr(link_fd);
12908 	}
12909 	link->fd = link_fd;
12910 
12911 	return link;
12912 }
12913 
12914 struct bpf_link *bpf_program__attach(const struct bpf_program *prog)
12915 {
12916 	struct bpf_link *link = NULL;
12917 	int err;
12918 
12919 	if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
12920 		return libbpf_err_ptr(-EOPNOTSUPP);
12921 
12922 	if (bpf_program__fd(prog) < 0) {
12923 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
12924 			prog->name);
12925 		return libbpf_err_ptr(-EINVAL);
12926 	}
12927 
12928 	err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, &link);
12929 	if (err)
12930 		return libbpf_err_ptr(err);
12931 
12932 	/* When calling bpf_program__attach() explicitly, auto-attach support
12933 	 * is expected to work, so NULL returned link is considered an error.
12934 	 * This is different for skeleton's attach, see comment in
12935 	 * bpf_object__attach_skeleton().
12936 	 */
12937 	if (!link)
12938 		return libbpf_err_ptr(-EOPNOTSUPP);
12939 
12940 	return link;
12941 }
12942 
12943 struct bpf_link_struct_ops {
12944 	struct bpf_link link;
12945 	int map_fd;
12946 };
12947 
12948 static int bpf_link__detach_struct_ops(struct bpf_link *link)
12949 {
12950 	struct bpf_link_struct_ops *st_link;
12951 	__u32 zero = 0;
12952 
12953 	st_link = container_of(link, struct bpf_link_struct_ops, link);
12954 
12955 	if (st_link->map_fd < 0)
12956 		/* w/o a real link */
12957 		return bpf_map_delete_elem(link->fd, &zero);
12958 
12959 	return close(link->fd);
12960 }
12961 
12962 struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map)
12963 {
12964 	struct bpf_link_struct_ops *link;
12965 	__u32 zero = 0;
12966 	int err, fd;
12967 
12968 	if (!bpf_map__is_struct_ops(map)) {
12969 		pr_warn("map '%s': can't attach non-struct_ops map\n", map->name);
12970 		return libbpf_err_ptr(-EINVAL);
12971 	}
12972 
12973 	if (map->fd < 0) {
12974 		pr_warn("map '%s': can't attach BPF map without FD (was it created?)\n", map->name);
12975 		return libbpf_err_ptr(-EINVAL);
12976 	}
12977 
12978 	link = calloc(1, sizeof(*link));
12979 	if (!link)
12980 		return libbpf_err_ptr(-EINVAL);
12981 
12982 	/* kern_vdata should be prepared during the loading phase. */
12983 	err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
12984 	/* It can be EBUSY if the map has been used to create or
12985 	 * update a link before.  We don't allow updating the value of
12986 	 * a struct_ops once it is set.  That ensures that the value
12987 	 * never changed.  So, it is safe to skip EBUSY.
12988 	 */
12989 	if (err && (!(map->def.map_flags & BPF_F_LINK) || err != -EBUSY)) {
12990 		free(link);
12991 		return libbpf_err_ptr(err);
12992 	}
12993 
12994 	link->link.detach = bpf_link__detach_struct_ops;
12995 
12996 	if (!(map->def.map_flags & BPF_F_LINK)) {
12997 		/* w/o a real link */
12998 		link->link.fd = map->fd;
12999 		link->map_fd = -1;
13000 		return &link->link;
13001 	}
13002 
13003 	fd = bpf_link_create(map->fd, 0, BPF_STRUCT_OPS, NULL);
13004 	if (fd < 0) {
13005 		free(link);
13006 		return libbpf_err_ptr(fd);
13007 	}
13008 
13009 	link->link.fd = fd;
13010 	link->map_fd = map->fd;
13011 
13012 	return &link->link;
13013 }
13014 
13015 /*
13016  * Swap the back struct_ops of a link with a new struct_ops map.
13017  */
13018 int bpf_link__update_map(struct bpf_link *link, const struct bpf_map *map)
13019 {
13020 	struct bpf_link_struct_ops *st_ops_link;
13021 	__u32 zero = 0;
13022 	int err;
13023 
13024 	if (!bpf_map__is_struct_ops(map))
13025 		return -EINVAL;
13026 
13027 	if (map->fd < 0) {
13028 		pr_warn("map '%s': can't use BPF map without FD (was it created?)\n", map->name);
13029 		return -EINVAL;
13030 	}
13031 
13032 	st_ops_link = container_of(link, struct bpf_link_struct_ops, link);
13033 	/* Ensure the type of a link is correct */
13034 	if (st_ops_link->map_fd < 0)
13035 		return -EINVAL;
13036 
13037 	err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
13038 	/* It can be EBUSY if the map has been used to create or
13039 	 * update a link before.  We don't allow updating the value of
13040 	 * a struct_ops once it is set.  That ensures that the value
13041 	 * never changed.  So, it is safe to skip EBUSY.
13042 	 */
13043 	if (err && err != -EBUSY)
13044 		return err;
13045 
13046 	err = bpf_link_update(link->fd, map->fd, NULL);
13047 	if (err < 0)
13048 		return err;
13049 
13050 	st_ops_link->map_fd = map->fd;
13051 
13052 	return 0;
13053 }
13054 
13055 typedef enum bpf_perf_event_ret (*bpf_perf_event_print_t)(struct perf_event_header *hdr,
13056 							  void *private_data);
13057 
13058 static enum bpf_perf_event_ret
13059 perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
13060 		       void **copy_mem, size_t *copy_size,
13061 		       bpf_perf_event_print_t fn, void *private_data)
13062 {
13063 	struct perf_event_mmap_page *header = mmap_mem;
13064 	__u64 data_head = ring_buffer_read_head(header);
13065 	__u64 data_tail = header->data_tail;
13066 	void *base = ((__u8 *)header) + page_size;
13067 	int ret = LIBBPF_PERF_EVENT_CONT;
13068 	struct perf_event_header *ehdr;
13069 	size_t ehdr_size;
13070 
13071 	while (data_head != data_tail) {
13072 		ehdr = base + (data_tail & (mmap_size - 1));
13073 		ehdr_size = ehdr->size;
13074 
13075 		if (((void *)ehdr) + ehdr_size > base + mmap_size) {
13076 			void *copy_start = ehdr;
13077 			size_t len_first = base + mmap_size - copy_start;
13078 			size_t len_secnd = ehdr_size - len_first;
13079 
13080 			if (*copy_size < ehdr_size) {
13081 				free(*copy_mem);
13082 				*copy_mem = malloc(ehdr_size);
13083 				if (!*copy_mem) {
13084 					*copy_size = 0;
13085 					ret = LIBBPF_PERF_EVENT_ERROR;
13086 					break;
13087 				}
13088 				*copy_size = ehdr_size;
13089 			}
13090 
13091 			memcpy(*copy_mem, copy_start, len_first);
13092 			memcpy(*copy_mem + len_first, base, len_secnd);
13093 			ehdr = *copy_mem;
13094 		}
13095 
13096 		ret = fn(ehdr, private_data);
13097 		data_tail += ehdr_size;
13098 		if (ret != LIBBPF_PERF_EVENT_CONT)
13099 			break;
13100 	}
13101 
13102 	ring_buffer_write_tail(header, data_tail);
13103 	return libbpf_err(ret);
13104 }
13105 
13106 struct perf_buffer;
13107 
13108 struct perf_buffer_params {
13109 	struct perf_event_attr *attr;
13110 	/* if event_cb is specified, it takes precendence */
13111 	perf_buffer_event_fn event_cb;
13112 	/* sample_cb and lost_cb are higher-level common-case callbacks */
13113 	perf_buffer_sample_fn sample_cb;
13114 	perf_buffer_lost_fn lost_cb;
13115 	void *ctx;
13116 	int cpu_cnt;
13117 	int *cpus;
13118 	int *map_keys;
13119 };
13120 
13121 struct perf_cpu_buf {
13122 	struct perf_buffer *pb;
13123 	void *base; /* mmap()'ed memory */
13124 	void *buf; /* for reconstructing segmented data */
13125 	size_t buf_size;
13126 	int fd;
13127 	int cpu;
13128 	int map_key;
13129 };
13130 
13131 struct perf_buffer {
13132 	perf_buffer_event_fn event_cb;
13133 	perf_buffer_sample_fn sample_cb;
13134 	perf_buffer_lost_fn lost_cb;
13135 	void *ctx; /* passed into callbacks */
13136 
13137 	size_t page_size;
13138 	size_t mmap_size;
13139 	struct perf_cpu_buf **cpu_bufs;
13140 	struct epoll_event *events;
13141 	int cpu_cnt; /* number of allocated CPU buffers */
13142 	int epoll_fd; /* perf event FD */
13143 	int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
13144 };
13145 
13146 static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
13147 				      struct perf_cpu_buf *cpu_buf)
13148 {
13149 	if (!cpu_buf)
13150 		return;
13151 	if (cpu_buf->base &&
13152 	    munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
13153 		pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
13154 	if (cpu_buf->fd >= 0) {
13155 		ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
13156 		close(cpu_buf->fd);
13157 	}
13158 	free(cpu_buf->buf);
13159 	free(cpu_buf);
13160 }
13161 
13162 void perf_buffer__free(struct perf_buffer *pb)
13163 {
13164 	int i;
13165 
13166 	if (IS_ERR_OR_NULL(pb))
13167 		return;
13168 	if (pb->cpu_bufs) {
13169 		for (i = 0; i < pb->cpu_cnt; i++) {
13170 			struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
13171 
13172 			if (!cpu_buf)
13173 				continue;
13174 
13175 			bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
13176 			perf_buffer__free_cpu_buf(pb, cpu_buf);
13177 		}
13178 		free(pb->cpu_bufs);
13179 	}
13180 	if (pb->epoll_fd >= 0)
13181 		close(pb->epoll_fd);
13182 	free(pb->events);
13183 	free(pb);
13184 }
13185 
13186 static struct perf_cpu_buf *
13187 perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
13188 			  int cpu, int map_key)
13189 {
13190 	struct perf_cpu_buf *cpu_buf;
13191 	char msg[STRERR_BUFSIZE];
13192 	int err;
13193 
13194 	cpu_buf = calloc(1, sizeof(*cpu_buf));
13195 	if (!cpu_buf)
13196 		return ERR_PTR(-ENOMEM);
13197 
13198 	cpu_buf->pb = pb;
13199 	cpu_buf->cpu = cpu;
13200 	cpu_buf->map_key = map_key;
13201 
13202 	cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
13203 			      -1, PERF_FLAG_FD_CLOEXEC);
13204 	if (cpu_buf->fd < 0) {
13205 		err = -errno;
13206 		pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
13207 			cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
13208 		goto error;
13209 	}
13210 
13211 	cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
13212 			     PROT_READ | PROT_WRITE, MAP_SHARED,
13213 			     cpu_buf->fd, 0);
13214 	if (cpu_buf->base == MAP_FAILED) {
13215 		cpu_buf->base = NULL;
13216 		err = -errno;
13217 		pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
13218 			cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
13219 		goto error;
13220 	}
13221 
13222 	if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
13223 		err = -errno;
13224 		pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
13225 			cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
13226 		goto error;
13227 	}
13228 
13229 	return cpu_buf;
13230 
13231 error:
13232 	perf_buffer__free_cpu_buf(pb, cpu_buf);
13233 	return (struct perf_cpu_buf *)ERR_PTR(err);
13234 }
13235 
13236 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
13237 					      struct perf_buffer_params *p);
13238 
13239 struct perf_buffer *perf_buffer__new(int map_fd, size_t page_cnt,
13240 				     perf_buffer_sample_fn sample_cb,
13241 				     perf_buffer_lost_fn lost_cb,
13242 				     void *ctx,
13243 				     const struct perf_buffer_opts *opts)
13244 {
13245 	const size_t attr_sz = sizeof(struct perf_event_attr);
13246 	struct perf_buffer_params p = {};
13247 	struct perf_event_attr attr;
13248 	__u32 sample_period;
13249 
13250 	if (!OPTS_VALID(opts, perf_buffer_opts))
13251 		return libbpf_err_ptr(-EINVAL);
13252 
13253 	sample_period = OPTS_GET(opts, sample_period, 1);
13254 	if (!sample_period)
13255 		sample_period = 1;
13256 
13257 	memset(&attr, 0, attr_sz);
13258 	attr.size = attr_sz;
13259 	attr.config = PERF_COUNT_SW_BPF_OUTPUT;
13260 	attr.type = PERF_TYPE_SOFTWARE;
13261 	attr.sample_type = PERF_SAMPLE_RAW;
13262 	attr.sample_period = sample_period;
13263 	attr.wakeup_events = sample_period;
13264 
13265 	p.attr = &attr;
13266 	p.sample_cb = sample_cb;
13267 	p.lost_cb = lost_cb;
13268 	p.ctx = ctx;
13269 
13270 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
13271 }
13272 
13273 struct perf_buffer *perf_buffer__new_raw(int map_fd, size_t page_cnt,
13274 					 struct perf_event_attr *attr,
13275 					 perf_buffer_event_fn event_cb, void *ctx,
13276 					 const struct perf_buffer_raw_opts *opts)
13277 {
13278 	struct perf_buffer_params p = {};
13279 
13280 	if (!attr)
13281 		return libbpf_err_ptr(-EINVAL);
13282 
13283 	if (!OPTS_VALID(opts, perf_buffer_raw_opts))
13284 		return libbpf_err_ptr(-EINVAL);
13285 
13286 	p.attr = attr;
13287 	p.event_cb = event_cb;
13288 	p.ctx = ctx;
13289 	p.cpu_cnt = OPTS_GET(opts, cpu_cnt, 0);
13290 	p.cpus = OPTS_GET(opts, cpus, NULL);
13291 	p.map_keys = OPTS_GET(opts, map_keys, NULL);
13292 
13293 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
13294 }
13295 
13296 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
13297 					      struct perf_buffer_params *p)
13298 {
13299 	const char *online_cpus_file = "/sys/devices/system/cpu/online";
13300 	struct bpf_map_info map;
13301 	char msg[STRERR_BUFSIZE];
13302 	struct perf_buffer *pb;
13303 	bool *online = NULL;
13304 	__u32 map_info_len;
13305 	int err, i, j, n;
13306 
13307 	if (page_cnt == 0 || (page_cnt & (page_cnt - 1))) {
13308 		pr_warn("page count should be power of two, but is %zu\n",
13309 			page_cnt);
13310 		return ERR_PTR(-EINVAL);
13311 	}
13312 
13313 	/* best-effort sanity checks */
13314 	memset(&map, 0, sizeof(map));
13315 	map_info_len = sizeof(map);
13316 	err = bpf_map_get_info_by_fd(map_fd, &map, &map_info_len);
13317 	if (err) {
13318 		err = -errno;
13319 		/* if BPF_OBJ_GET_INFO_BY_FD is supported, will return
13320 		 * -EBADFD, -EFAULT, or -E2BIG on real error
13321 		 */
13322 		if (err != -EINVAL) {
13323 			pr_warn("failed to get map info for map FD %d: %s\n",
13324 				map_fd, libbpf_strerror_r(err, msg, sizeof(msg)));
13325 			return ERR_PTR(err);
13326 		}
13327 		pr_debug("failed to get map info for FD %d; API not supported? Ignoring...\n",
13328 			 map_fd);
13329 	} else {
13330 		if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
13331 			pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
13332 				map.name);
13333 			return ERR_PTR(-EINVAL);
13334 		}
13335 	}
13336 
13337 	pb = calloc(1, sizeof(*pb));
13338 	if (!pb)
13339 		return ERR_PTR(-ENOMEM);
13340 
13341 	pb->event_cb = p->event_cb;
13342 	pb->sample_cb = p->sample_cb;
13343 	pb->lost_cb = p->lost_cb;
13344 	pb->ctx = p->ctx;
13345 
13346 	pb->page_size = getpagesize();
13347 	pb->mmap_size = pb->page_size * page_cnt;
13348 	pb->map_fd = map_fd;
13349 
13350 	pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
13351 	if (pb->epoll_fd < 0) {
13352 		err = -errno;
13353 		pr_warn("failed to create epoll instance: %s\n",
13354 			libbpf_strerror_r(err, msg, sizeof(msg)));
13355 		goto error;
13356 	}
13357 
13358 	if (p->cpu_cnt > 0) {
13359 		pb->cpu_cnt = p->cpu_cnt;
13360 	} else {
13361 		pb->cpu_cnt = libbpf_num_possible_cpus();
13362 		if (pb->cpu_cnt < 0) {
13363 			err = pb->cpu_cnt;
13364 			goto error;
13365 		}
13366 		if (map.max_entries && map.max_entries < pb->cpu_cnt)
13367 			pb->cpu_cnt = map.max_entries;
13368 	}
13369 
13370 	pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
13371 	if (!pb->events) {
13372 		err = -ENOMEM;
13373 		pr_warn("failed to allocate events: out of memory\n");
13374 		goto error;
13375 	}
13376 	pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
13377 	if (!pb->cpu_bufs) {
13378 		err = -ENOMEM;
13379 		pr_warn("failed to allocate buffers: out of memory\n");
13380 		goto error;
13381 	}
13382 
13383 	err = parse_cpu_mask_file(online_cpus_file, &online, &n);
13384 	if (err) {
13385 		pr_warn("failed to get online CPU mask: %d\n", err);
13386 		goto error;
13387 	}
13388 
13389 	for (i = 0, j = 0; i < pb->cpu_cnt; i++) {
13390 		struct perf_cpu_buf *cpu_buf;
13391 		int cpu, map_key;
13392 
13393 		cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
13394 		map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
13395 
13396 		/* in case user didn't explicitly requested particular CPUs to
13397 		 * be attached to, skip offline/not present CPUs
13398 		 */
13399 		if (p->cpu_cnt <= 0 && (cpu >= n || !online[cpu]))
13400 			continue;
13401 
13402 		cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
13403 		if (IS_ERR(cpu_buf)) {
13404 			err = PTR_ERR(cpu_buf);
13405 			goto error;
13406 		}
13407 
13408 		pb->cpu_bufs[j] = cpu_buf;
13409 
13410 		err = bpf_map_update_elem(pb->map_fd, &map_key,
13411 					  &cpu_buf->fd, 0);
13412 		if (err) {
13413 			err = -errno;
13414 			pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
13415 				cpu, map_key, cpu_buf->fd,
13416 				libbpf_strerror_r(err, msg, sizeof(msg)));
13417 			goto error;
13418 		}
13419 
13420 		pb->events[j].events = EPOLLIN;
13421 		pb->events[j].data.ptr = cpu_buf;
13422 		if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
13423 			      &pb->events[j]) < 0) {
13424 			err = -errno;
13425 			pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
13426 				cpu, cpu_buf->fd,
13427 				libbpf_strerror_r(err, msg, sizeof(msg)));
13428 			goto error;
13429 		}
13430 		j++;
13431 	}
13432 	pb->cpu_cnt = j;
13433 	free(online);
13434 
13435 	return pb;
13436 
13437 error:
13438 	free(online);
13439 	if (pb)
13440 		perf_buffer__free(pb);
13441 	return ERR_PTR(err);
13442 }
13443 
13444 struct perf_sample_raw {
13445 	struct perf_event_header header;
13446 	uint32_t size;
13447 	char data[];
13448 };
13449 
13450 struct perf_sample_lost {
13451 	struct perf_event_header header;
13452 	uint64_t id;
13453 	uint64_t lost;
13454 	uint64_t sample_id;
13455 };
13456 
13457 static enum bpf_perf_event_ret
13458 perf_buffer__process_record(struct perf_event_header *e, void *ctx)
13459 {
13460 	struct perf_cpu_buf *cpu_buf = ctx;
13461 	struct perf_buffer *pb = cpu_buf->pb;
13462 	void *data = e;
13463 
13464 	/* user wants full control over parsing perf event */
13465 	if (pb->event_cb)
13466 		return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
13467 
13468 	switch (e->type) {
13469 	case PERF_RECORD_SAMPLE: {
13470 		struct perf_sample_raw *s = data;
13471 
13472 		if (pb->sample_cb)
13473 			pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
13474 		break;
13475 	}
13476 	case PERF_RECORD_LOST: {
13477 		struct perf_sample_lost *s = data;
13478 
13479 		if (pb->lost_cb)
13480 			pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
13481 		break;
13482 	}
13483 	default:
13484 		pr_warn("unknown perf sample type %d\n", e->type);
13485 		return LIBBPF_PERF_EVENT_ERROR;
13486 	}
13487 	return LIBBPF_PERF_EVENT_CONT;
13488 }
13489 
13490 static int perf_buffer__process_records(struct perf_buffer *pb,
13491 					struct perf_cpu_buf *cpu_buf)
13492 {
13493 	enum bpf_perf_event_ret ret;
13494 
13495 	ret = perf_event_read_simple(cpu_buf->base, pb->mmap_size,
13496 				     pb->page_size, &cpu_buf->buf,
13497 				     &cpu_buf->buf_size,
13498 				     perf_buffer__process_record, cpu_buf);
13499 	if (ret != LIBBPF_PERF_EVENT_CONT)
13500 		return ret;
13501 	return 0;
13502 }
13503 
13504 int perf_buffer__epoll_fd(const struct perf_buffer *pb)
13505 {
13506 	return pb->epoll_fd;
13507 }
13508 
13509 int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
13510 {
13511 	int i, cnt, err;
13512 
13513 	cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
13514 	if (cnt < 0)
13515 		return -errno;
13516 
13517 	for (i = 0; i < cnt; i++) {
13518 		struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
13519 
13520 		err = perf_buffer__process_records(pb, cpu_buf);
13521 		if (err) {
13522 			pr_warn("error while processing records: %d\n", err);
13523 			return libbpf_err(err);
13524 		}
13525 	}
13526 	return cnt;
13527 }
13528 
13529 /* Return number of PERF_EVENT_ARRAY map slots set up by this perf_buffer
13530  * manager.
13531  */
13532 size_t perf_buffer__buffer_cnt(const struct perf_buffer *pb)
13533 {
13534 	return pb->cpu_cnt;
13535 }
13536 
13537 /*
13538  * Return perf_event FD of a ring buffer in *buf_idx* slot of
13539  * PERF_EVENT_ARRAY BPF map. This FD can be polled for new data using
13540  * select()/poll()/epoll() Linux syscalls.
13541  */
13542 int perf_buffer__buffer_fd(const struct perf_buffer *pb, size_t buf_idx)
13543 {
13544 	struct perf_cpu_buf *cpu_buf;
13545 
13546 	if (buf_idx >= pb->cpu_cnt)
13547 		return libbpf_err(-EINVAL);
13548 
13549 	cpu_buf = pb->cpu_bufs[buf_idx];
13550 	if (!cpu_buf)
13551 		return libbpf_err(-ENOENT);
13552 
13553 	return cpu_buf->fd;
13554 }
13555 
13556 int perf_buffer__buffer(struct perf_buffer *pb, int buf_idx, void **buf, size_t *buf_size)
13557 {
13558 	struct perf_cpu_buf *cpu_buf;
13559 
13560 	if (buf_idx >= pb->cpu_cnt)
13561 		return libbpf_err(-EINVAL);
13562 
13563 	cpu_buf = pb->cpu_bufs[buf_idx];
13564 	if (!cpu_buf)
13565 		return libbpf_err(-ENOENT);
13566 
13567 	*buf = cpu_buf->base;
13568 	*buf_size = pb->mmap_size;
13569 	return 0;
13570 }
13571 
13572 /*
13573  * Consume data from perf ring buffer corresponding to slot *buf_idx* in
13574  * PERF_EVENT_ARRAY BPF map without waiting/polling. If there is no data to
13575  * consume, do nothing and return success.
13576  * Returns:
13577  *   - 0 on success;
13578  *   - <0 on failure.
13579  */
13580 int perf_buffer__consume_buffer(struct perf_buffer *pb, size_t buf_idx)
13581 {
13582 	struct perf_cpu_buf *cpu_buf;
13583 
13584 	if (buf_idx >= pb->cpu_cnt)
13585 		return libbpf_err(-EINVAL);
13586 
13587 	cpu_buf = pb->cpu_bufs[buf_idx];
13588 	if (!cpu_buf)
13589 		return libbpf_err(-ENOENT);
13590 
13591 	return perf_buffer__process_records(pb, cpu_buf);
13592 }
13593 
13594 int perf_buffer__consume(struct perf_buffer *pb)
13595 {
13596 	int i, err;
13597 
13598 	for (i = 0; i < pb->cpu_cnt; i++) {
13599 		struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
13600 
13601 		if (!cpu_buf)
13602 			continue;
13603 
13604 		err = perf_buffer__process_records(pb, cpu_buf);
13605 		if (err) {
13606 			pr_warn("perf_buffer: failed to process records in buffer #%d: %d\n", i, err);
13607 			return libbpf_err(err);
13608 		}
13609 	}
13610 	return 0;
13611 }
13612 
13613 int bpf_program__set_attach_target(struct bpf_program *prog,
13614 				   int attach_prog_fd,
13615 				   const char *attach_func_name)
13616 {
13617 	int btf_obj_fd = 0, btf_id = 0, err;
13618 
13619 	if (!prog || attach_prog_fd < 0)
13620 		return libbpf_err(-EINVAL);
13621 
13622 	if (prog->obj->loaded)
13623 		return libbpf_err(-EINVAL);
13624 
13625 	if (attach_prog_fd && !attach_func_name) {
13626 		/* remember attach_prog_fd and let bpf_program__load() find
13627 		 * BTF ID during the program load
13628 		 */
13629 		prog->attach_prog_fd = attach_prog_fd;
13630 		return 0;
13631 	}
13632 
13633 	if (attach_prog_fd) {
13634 		btf_id = libbpf_find_prog_btf_id(attach_func_name,
13635 						 attach_prog_fd);
13636 		if (btf_id < 0)
13637 			return libbpf_err(btf_id);
13638 	} else {
13639 		if (!attach_func_name)
13640 			return libbpf_err(-EINVAL);
13641 
13642 		/* load btf_vmlinux, if not yet */
13643 		err = bpf_object__load_vmlinux_btf(prog->obj, true);
13644 		if (err)
13645 			return libbpf_err(err);
13646 		err = find_kernel_btf_id(prog->obj, attach_func_name,
13647 					 prog->expected_attach_type,
13648 					 &btf_obj_fd, &btf_id);
13649 		if (err)
13650 			return libbpf_err(err);
13651 	}
13652 
13653 	prog->attach_btf_id = btf_id;
13654 	prog->attach_btf_obj_fd = btf_obj_fd;
13655 	prog->attach_prog_fd = attach_prog_fd;
13656 	return 0;
13657 }
13658 
13659 int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz)
13660 {
13661 	int err = 0, n, len, start, end = -1;
13662 	bool *tmp;
13663 
13664 	*mask = NULL;
13665 	*mask_sz = 0;
13666 
13667 	/* Each sub string separated by ',' has format \d+-\d+ or \d+ */
13668 	while (*s) {
13669 		if (*s == ',' || *s == '\n') {
13670 			s++;
13671 			continue;
13672 		}
13673 		n = sscanf(s, "%d%n-%d%n", &start, &len, &end, &len);
13674 		if (n <= 0 || n > 2) {
13675 			pr_warn("Failed to get CPU range %s: %d\n", s, n);
13676 			err = -EINVAL;
13677 			goto cleanup;
13678 		} else if (n == 1) {
13679 			end = start;
13680 		}
13681 		if (start < 0 || start > end) {
13682 			pr_warn("Invalid CPU range [%d,%d] in %s\n",
13683 				start, end, s);
13684 			err = -EINVAL;
13685 			goto cleanup;
13686 		}
13687 		tmp = realloc(*mask, end + 1);
13688 		if (!tmp) {
13689 			err = -ENOMEM;
13690 			goto cleanup;
13691 		}
13692 		*mask = tmp;
13693 		memset(tmp + *mask_sz, 0, start - *mask_sz);
13694 		memset(tmp + start, 1, end - start + 1);
13695 		*mask_sz = end + 1;
13696 		s += len;
13697 	}
13698 	if (!*mask_sz) {
13699 		pr_warn("Empty CPU range\n");
13700 		return -EINVAL;
13701 	}
13702 	return 0;
13703 cleanup:
13704 	free(*mask);
13705 	*mask = NULL;
13706 	return err;
13707 }
13708 
13709 int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz)
13710 {
13711 	int fd, err = 0, len;
13712 	char buf[128];
13713 
13714 	fd = open(fcpu, O_RDONLY | O_CLOEXEC);
13715 	if (fd < 0) {
13716 		err = -errno;
13717 		pr_warn("Failed to open cpu mask file %s: %d\n", fcpu, err);
13718 		return err;
13719 	}
13720 	len = read(fd, buf, sizeof(buf));
13721 	close(fd);
13722 	if (len <= 0) {
13723 		err = len ? -errno : -EINVAL;
13724 		pr_warn("Failed to read cpu mask from %s: %d\n", fcpu, err);
13725 		return err;
13726 	}
13727 	if (len >= sizeof(buf)) {
13728 		pr_warn("CPU mask is too big in file %s\n", fcpu);
13729 		return -E2BIG;
13730 	}
13731 	buf[len] = '\0';
13732 
13733 	return parse_cpu_mask_str(buf, mask, mask_sz);
13734 }
13735 
13736 int libbpf_num_possible_cpus(void)
13737 {
13738 	static const char *fcpu = "/sys/devices/system/cpu/possible";
13739 	static int cpus;
13740 	int err, n, i, tmp_cpus;
13741 	bool *mask;
13742 
13743 	tmp_cpus = READ_ONCE(cpus);
13744 	if (tmp_cpus > 0)
13745 		return tmp_cpus;
13746 
13747 	err = parse_cpu_mask_file(fcpu, &mask, &n);
13748 	if (err)
13749 		return libbpf_err(err);
13750 
13751 	tmp_cpus = 0;
13752 	for (i = 0; i < n; i++) {
13753 		if (mask[i])
13754 			tmp_cpus++;
13755 	}
13756 	free(mask);
13757 
13758 	WRITE_ONCE(cpus, tmp_cpus);
13759 	return tmp_cpus;
13760 }
13761 
13762 static int populate_skeleton_maps(const struct bpf_object *obj,
13763 				  struct bpf_map_skeleton *maps,
13764 				  size_t map_cnt, size_t map_skel_sz)
13765 {
13766 	int i;
13767 
13768 	for (i = 0; i < map_cnt; i++) {
13769 		struct bpf_map_skeleton *map_skel = (void *)maps + i * map_skel_sz;
13770 		struct bpf_map **map = map_skel->map;
13771 		const char *name = map_skel->name;
13772 		void **mmaped = map_skel->mmaped;
13773 
13774 		*map = bpf_object__find_map_by_name(obj, name);
13775 		if (!*map) {
13776 			pr_warn("failed to find skeleton map '%s'\n", name);
13777 			return -ESRCH;
13778 		}
13779 
13780 		/* externs shouldn't be pre-setup from user code */
13781 		if (mmaped && (*map)->libbpf_type != LIBBPF_MAP_KCONFIG)
13782 			*mmaped = (*map)->mmaped;
13783 	}
13784 	return 0;
13785 }
13786 
13787 static int populate_skeleton_progs(const struct bpf_object *obj,
13788 				   struct bpf_prog_skeleton *progs,
13789 				   size_t prog_cnt, size_t prog_skel_sz)
13790 {
13791 	int i;
13792 
13793 	for (i = 0; i < prog_cnt; i++) {
13794 		struct bpf_prog_skeleton *prog_skel = (void *)progs + i * prog_skel_sz;
13795 		struct bpf_program **prog = prog_skel->prog;
13796 		const char *name = prog_skel->name;
13797 
13798 		*prog = bpf_object__find_program_by_name(obj, name);
13799 		if (!*prog) {
13800 			pr_warn("failed to find skeleton program '%s'\n", name);
13801 			return -ESRCH;
13802 		}
13803 	}
13804 	return 0;
13805 }
13806 
13807 int bpf_object__open_skeleton(struct bpf_object_skeleton *s,
13808 			      const struct bpf_object_open_opts *opts)
13809 {
13810 	struct bpf_object *obj;
13811 	int err;
13812 
13813 	obj = bpf_object_open(NULL, s->data, s->data_sz, s->name, opts);
13814 	if (IS_ERR(obj)) {
13815 		err = PTR_ERR(obj);
13816 		pr_warn("failed to initialize skeleton BPF object '%s': %d\n", s->name, err);
13817 		return libbpf_err(err);
13818 	}
13819 
13820 	*s->obj = obj;
13821 	err = populate_skeleton_maps(obj, s->maps, s->map_cnt, s->map_skel_sz);
13822 	if (err) {
13823 		pr_warn("failed to populate skeleton maps for '%s': %d\n", s->name, err);
13824 		return libbpf_err(err);
13825 	}
13826 
13827 	err = populate_skeleton_progs(obj, s->progs, s->prog_cnt, s->prog_skel_sz);
13828 	if (err) {
13829 		pr_warn("failed to populate skeleton progs for '%s': %d\n", s->name, err);
13830 		return libbpf_err(err);
13831 	}
13832 
13833 	return 0;
13834 }
13835 
13836 int bpf_object__open_subskeleton(struct bpf_object_subskeleton *s)
13837 {
13838 	int err, len, var_idx, i;
13839 	const char *var_name;
13840 	const struct bpf_map *map;
13841 	struct btf *btf;
13842 	__u32 map_type_id;
13843 	const struct btf_type *map_type, *var_type;
13844 	const struct bpf_var_skeleton *var_skel;
13845 	struct btf_var_secinfo *var;
13846 
13847 	if (!s->obj)
13848 		return libbpf_err(-EINVAL);
13849 
13850 	btf = bpf_object__btf(s->obj);
13851 	if (!btf) {
13852 		pr_warn("subskeletons require BTF at runtime (object %s)\n",
13853 			bpf_object__name(s->obj));
13854 		return libbpf_err(-errno);
13855 	}
13856 
13857 	err = populate_skeleton_maps(s->obj, s->maps, s->map_cnt, s->map_skel_sz);
13858 	if (err) {
13859 		pr_warn("failed to populate subskeleton maps: %d\n", err);
13860 		return libbpf_err(err);
13861 	}
13862 
13863 	err = populate_skeleton_progs(s->obj, s->progs, s->prog_cnt, s->prog_skel_sz);
13864 	if (err) {
13865 		pr_warn("failed to populate subskeleton maps: %d\n", err);
13866 		return libbpf_err(err);
13867 	}
13868 
13869 	for (var_idx = 0; var_idx < s->var_cnt; var_idx++) {
13870 		var_skel = (void *)s->vars + var_idx * s->var_skel_sz;
13871 		map = *var_skel->map;
13872 		map_type_id = bpf_map__btf_value_type_id(map);
13873 		map_type = btf__type_by_id(btf, map_type_id);
13874 
13875 		if (!btf_is_datasec(map_type)) {
13876 			pr_warn("type for map '%1$s' is not a datasec: %2$s\n",
13877 				bpf_map__name(map),
13878 				__btf_kind_str(btf_kind(map_type)));
13879 			return libbpf_err(-EINVAL);
13880 		}
13881 
13882 		len = btf_vlen(map_type);
13883 		var = btf_var_secinfos(map_type);
13884 		for (i = 0; i < len; i++, var++) {
13885 			var_type = btf__type_by_id(btf, var->type);
13886 			var_name = btf__name_by_offset(btf, var_type->name_off);
13887 			if (strcmp(var_name, var_skel->name) == 0) {
13888 				*var_skel->addr = map->mmaped + var->offset;
13889 				break;
13890 			}
13891 		}
13892 	}
13893 	return 0;
13894 }
13895 
13896 void bpf_object__destroy_subskeleton(struct bpf_object_subskeleton *s)
13897 {
13898 	if (!s)
13899 		return;
13900 	free(s->maps);
13901 	free(s->progs);
13902 	free(s->vars);
13903 	free(s);
13904 }
13905 
13906 int bpf_object__load_skeleton(struct bpf_object_skeleton *s)
13907 {
13908 	int i, err;
13909 
13910 	err = bpf_object__load(*s->obj);
13911 	if (err) {
13912 		pr_warn("failed to load BPF skeleton '%s': %d\n", s->name, err);
13913 		return libbpf_err(err);
13914 	}
13915 
13916 	for (i = 0; i < s->map_cnt; i++) {
13917 		struct bpf_map_skeleton *map_skel = (void *)s->maps + i * s->map_skel_sz;
13918 		struct bpf_map *map = *map_skel->map;
13919 		size_t mmap_sz = bpf_map_mmap_sz(map);
13920 		int prot, map_fd = map->fd;
13921 		void **mmaped = map_skel->mmaped;
13922 
13923 		if (!mmaped)
13924 			continue;
13925 
13926 		if (!(map->def.map_flags & BPF_F_MMAPABLE)) {
13927 			*mmaped = NULL;
13928 			continue;
13929 		}
13930 
13931 		if (map->def.type == BPF_MAP_TYPE_ARENA) {
13932 			*mmaped = map->mmaped;
13933 			continue;
13934 		}
13935 
13936 		if (map->def.map_flags & BPF_F_RDONLY_PROG)
13937 			prot = PROT_READ;
13938 		else
13939 			prot = PROT_READ | PROT_WRITE;
13940 
13941 		/* Remap anonymous mmap()-ed "map initialization image" as
13942 		 * a BPF map-backed mmap()-ed memory, but preserving the same
13943 		 * memory address. This will cause kernel to change process'
13944 		 * page table to point to a different piece of kernel memory,
13945 		 * but from userspace point of view memory address (and its
13946 		 * contents, being identical at this point) will stay the
13947 		 * same. This mapping will be released by bpf_object__close()
13948 		 * as per normal clean up procedure, so we don't need to worry
13949 		 * about it from skeleton's clean up perspective.
13950 		 */
13951 		*mmaped = mmap(map->mmaped, mmap_sz, prot, MAP_SHARED | MAP_FIXED, map_fd, 0);
13952 		if (*mmaped == MAP_FAILED) {
13953 			err = -errno;
13954 			*mmaped = NULL;
13955 			pr_warn("failed to re-mmap() map '%s': %d\n",
13956 				 bpf_map__name(map), err);
13957 			return libbpf_err(err);
13958 		}
13959 	}
13960 
13961 	return 0;
13962 }
13963 
13964 int bpf_object__attach_skeleton(struct bpf_object_skeleton *s)
13965 {
13966 	int i, err;
13967 
13968 	for (i = 0; i < s->prog_cnt; i++) {
13969 		struct bpf_prog_skeleton *prog_skel = (void *)s->progs + i * s->prog_skel_sz;
13970 		struct bpf_program *prog = *prog_skel->prog;
13971 		struct bpf_link **link = prog_skel->link;
13972 
13973 		if (!prog->autoload || !prog->autoattach)
13974 			continue;
13975 
13976 		/* auto-attaching not supported for this program */
13977 		if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
13978 			continue;
13979 
13980 		/* if user already set the link manually, don't attempt auto-attach */
13981 		if (*link)
13982 			continue;
13983 
13984 		err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, link);
13985 		if (err) {
13986 			pr_warn("prog '%s': failed to auto-attach: %d\n",
13987 				bpf_program__name(prog), err);
13988 			return libbpf_err(err);
13989 		}
13990 
13991 		/* It's possible that for some SEC() definitions auto-attach
13992 		 * is supported in some cases (e.g., if definition completely
13993 		 * specifies target information), but is not in other cases.
13994 		 * SEC("uprobe") is one such case. If user specified target
13995 		 * binary and function name, such BPF program can be
13996 		 * auto-attached. But if not, it shouldn't trigger skeleton's
13997 		 * attach to fail. It should just be skipped.
13998 		 * attach_fn signals such case with returning 0 (no error) and
13999 		 * setting link to NULL.
14000 		 */
14001 	}
14002 
14003 
14004 	for (i = 0; i < s->map_cnt; i++) {
14005 		struct bpf_map_skeleton *map_skel = (void *)s->maps + i * s->map_skel_sz;
14006 		struct bpf_map *map = *map_skel->map;
14007 		struct bpf_link **link;
14008 
14009 		if (!map->autocreate || !map->autoattach)
14010 			continue;
14011 
14012 		/* only struct_ops maps can be attached */
14013 		if (!bpf_map__is_struct_ops(map))
14014 			continue;
14015 
14016 		/* skeleton is created with earlier version of bpftool, notify user */
14017 		if (s->map_skel_sz < offsetofend(struct bpf_map_skeleton, link)) {
14018 			pr_warn("map '%s': BPF skeleton version is old, skipping map auto-attachment...\n",
14019 				bpf_map__name(map));
14020 			continue;
14021 		}
14022 
14023 		link = map_skel->link;
14024 		if (*link)
14025 			continue;
14026 
14027 		*link = bpf_map__attach_struct_ops(map);
14028 		if (!*link) {
14029 			err = -errno;
14030 			pr_warn("map '%s': failed to auto-attach: %d\n", bpf_map__name(map), err);
14031 			return libbpf_err(err);
14032 		}
14033 	}
14034 
14035 	return 0;
14036 }
14037 
14038 void bpf_object__detach_skeleton(struct bpf_object_skeleton *s)
14039 {
14040 	int i;
14041 
14042 	for (i = 0; i < s->prog_cnt; i++) {
14043 		struct bpf_prog_skeleton *prog_skel = (void *)s->progs + i * s->prog_skel_sz;
14044 		struct bpf_link **link = prog_skel->link;
14045 
14046 		bpf_link__destroy(*link);
14047 		*link = NULL;
14048 	}
14049 
14050 	if (s->map_skel_sz < sizeof(struct bpf_map_skeleton))
14051 		return;
14052 
14053 	for (i = 0; i < s->map_cnt; i++) {
14054 		struct bpf_map_skeleton *map_skel = (void *)s->maps + i * s->map_skel_sz;
14055 		struct bpf_link **link = map_skel->link;
14056 
14057 		if (link) {
14058 			bpf_link__destroy(*link);
14059 			*link = NULL;
14060 		}
14061 	}
14062 }
14063 
14064 void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s)
14065 {
14066 	if (!s)
14067 		return;
14068 
14069 	bpf_object__detach_skeleton(s);
14070 	if (s->obj)
14071 		bpf_object__close(*s->obj);
14072 	free(s->maps);
14073 	free(s->progs);
14074 	free(s);
14075 }
14076