xref: /linux/tools/lib/bpf/libbpf.c (revision 40863f4d6ef2c34bb00dd1070dfaf9d5f27a497e)
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 <sys/socket.h>
47 #include <linux/if_alg.h>
48 #include <linux/socket.h>
49 #include <libelf.h>
50 #include <gelf.h>
51 #include <zlib.h>
52 
53 #include "libbpf.h"
54 #include "bpf.h"
55 #include "btf.h"
56 #include "str_error.h"
57 #include "libbpf_internal.h"
58 #include "hashmap.h"
59 #include "bpf_gen_internal.h"
60 #include "zip.h"
61 
62 #ifndef BPF_FS_MAGIC
63 #define BPF_FS_MAGIC		0xcafe4a11
64 #endif
65 
66 #define MAX_EVENT_NAME_LEN	64
67 
68 #define BPF_FS_DEFAULT_PATH "/sys/fs/bpf"
69 
70 #define BPF_INSN_SZ (sizeof(struct bpf_insn))
71 
72 /* vsprintf() in __base_pr() uses nonliteral format string. It may break
73  * compilation if user enables corresponding warning. Disable it explicitly.
74  */
75 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
76 
77 #define __printf(a, b)	__attribute__((format(printf, a, b)))
78 
79 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj);
80 static bool prog_is_subprog(const struct bpf_object *obj, const struct bpf_program *prog);
81 static int map_set_def_max_entries(struct bpf_map *map);
82 
83 static const char * const attach_type_name[] = {
84 	[BPF_CGROUP_INET_INGRESS]	= "cgroup_inet_ingress",
85 	[BPF_CGROUP_INET_EGRESS]	= "cgroup_inet_egress",
86 	[BPF_CGROUP_INET_SOCK_CREATE]	= "cgroup_inet_sock_create",
87 	[BPF_CGROUP_INET_SOCK_RELEASE]	= "cgroup_inet_sock_release",
88 	[BPF_CGROUP_SOCK_OPS]		= "cgroup_sock_ops",
89 	[BPF_CGROUP_DEVICE]		= "cgroup_device",
90 	[BPF_CGROUP_INET4_BIND]		= "cgroup_inet4_bind",
91 	[BPF_CGROUP_INET6_BIND]		= "cgroup_inet6_bind",
92 	[BPF_CGROUP_INET4_CONNECT]	= "cgroup_inet4_connect",
93 	[BPF_CGROUP_INET6_CONNECT]	= "cgroup_inet6_connect",
94 	[BPF_CGROUP_UNIX_CONNECT]       = "cgroup_unix_connect",
95 	[BPF_CGROUP_INET4_POST_BIND]	= "cgroup_inet4_post_bind",
96 	[BPF_CGROUP_INET6_POST_BIND]	= "cgroup_inet6_post_bind",
97 	[BPF_CGROUP_INET4_GETPEERNAME]	= "cgroup_inet4_getpeername",
98 	[BPF_CGROUP_INET6_GETPEERNAME]	= "cgroup_inet6_getpeername",
99 	[BPF_CGROUP_UNIX_GETPEERNAME]	= "cgroup_unix_getpeername",
100 	[BPF_CGROUP_INET4_GETSOCKNAME]	= "cgroup_inet4_getsockname",
101 	[BPF_CGROUP_INET6_GETSOCKNAME]	= "cgroup_inet6_getsockname",
102 	[BPF_CGROUP_UNIX_GETSOCKNAME]	= "cgroup_unix_getsockname",
103 	[BPF_CGROUP_UDP4_SENDMSG]	= "cgroup_udp4_sendmsg",
104 	[BPF_CGROUP_UDP6_SENDMSG]	= "cgroup_udp6_sendmsg",
105 	[BPF_CGROUP_UNIX_SENDMSG]	= "cgroup_unix_sendmsg",
106 	[BPF_CGROUP_SYSCTL]		= "cgroup_sysctl",
107 	[BPF_CGROUP_UDP4_RECVMSG]	= "cgroup_udp4_recvmsg",
108 	[BPF_CGROUP_UDP6_RECVMSG]	= "cgroup_udp6_recvmsg",
109 	[BPF_CGROUP_UNIX_RECVMSG]	= "cgroup_unix_recvmsg",
110 	[BPF_CGROUP_GETSOCKOPT]		= "cgroup_getsockopt",
111 	[BPF_CGROUP_SETSOCKOPT]		= "cgroup_setsockopt",
112 	[BPF_SK_SKB_STREAM_PARSER]	= "sk_skb_stream_parser",
113 	[BPF_SK_SKB_STREAM_VERDICT]	= "sk_skb_stream_verdict",
114 	[BPF_SK_SKB_VERDICT]		= "sk_skb_verdict",
115 	[BPF_SK_MSG_VERDICT]		= "sk_msg_verdict",
116 	[BPF_LIRC_MODE2]		= "lirc_mode2",
117 	[BPF_FLOW_DISSECTOR]		= "flow_dissector",
118 	[BPF_TRACE_RAW_TP]		= "trace_raw_tp",
119 	[BPF_TRACE_FENTRY]		= "trace_fentry",
120 	[BPF_TRACE_FEXIT]		= "trace_fexit",
121 	[BPF_MODIFY_RETURN]		= "modify_return",
122 	[BPF_LSM_MAC]			= "lsm_mac",
123 	[BPF_LSM_CGROUP]		= "lsm_cgroup",
124 	[BPF_SK_LOOKUP]			= "sk_lookup",
125 	[BPF_TRACE_ITER]		= "trace_iter",
126 	[BPF_XDP_DEVMAP]		= "xdp_devmap",
127 	[BPF_XDP_CPUMAP]		= "xdp_cpumap",
128 	[BPF_XDP]			= "xdp",
129 	[BPF_SK_REUSEPORT_SELECT]	= "sk_reuseport_select",
130 	[BPF_SK_REUSEPORT_SELECT_OR_MIGRATE]	= "sk_reuseport_select_or_migrate",
131 	[BPF_PERF_EVENT]		= "perf_event",
132 	[BPF_TRACE_KPROBE_MULTI]	= "trace_kprobe_multi",
133 	[BPF_STRUCT_OPS]		= "struct_ops",
134 	[BPF_NETFILTER]			= "netfilter",
135 	[BPF_TCX_INGRESS]		= "tcx_ingress",
136 	[BPF_TCX_EGRESS]		= "tcx_egress",
137 	[BPF_TRACE_UPROBE_MULTI]	= "trace_uprobe_multi",
138 	[BPF_NETKIT_PRIMARY]		= "netkit_primary",
139 	[BPF_NETKIT_PEER]		= "netkit_peer",
140 	[BPF_TRACE_KPROBE_SESSION]	= "trace_kprobe_session",
141 	[BPF_TRACE_UPROBE_SESSION]	= "trace_uprobe_session",
142 };
143 
144 static const char * const link_type_name[] = {
145 	[BPF_LINK_TYPE_UNSPEC]			= "unspec",
146 	[BPF_LINK_TYPE_RAW_TRACEPOINT]		= "raw_tracepoint",
147 	[BPF_LINK_TYPE_TRACING]			= "tracing",
148 	[BPF_LINK_TYPE_CGROUP]			= "cgroup",
149 	[BPF_LINK_TYPE_ITER]			= "iter",
150 	[BPF_LINK_TYPE_NETNS]			= "netns",
151 	[BPF_LINK_TYPE_XDP]			= "xdp",
152 	[BPF_LINK_TYPE_PERF_EVENT]		= "perf_event",
153 	[BPF_LINK_TYPE_KPROBE_MULTI]		= "kprobe_multi",
154 	[BPF_LINK_TYPE_STRUCT_OPS]		= "struct_ops",
155 	[BPF_LINK_TYPE_NETFILTER]		= "netfilter",
156 	[BPF_LINK_TYPE_TCX]			= "tcx",
157 	[BPF_LINK_TYPE_UPROBE_MULTI]		= "uprobe_multi",
158 	[BPF_LINK_TYPE_NETKIT]			= "netkit",
159 	[BPF_LINK_TYPE_SOCKMAP]			= "sockmap",
160 };
161 
162 static const char * const map_type_name[] = {
163 	[BPF_MAP_TYPE_UNSPEC]			= "unspec",
164 	[BPF_MAP_TYPE_HASH]			= "hash",
165 	[BPF_MAP_TYPE_ARRAY]			= "array",
166 	[BPF_MAP_TYPE_PROG_ARRAY]		= "prog_array",
167 	[BPF_MAP_TYPE_PERF_EVENT_ARRAY]		= "perf_event_array",
168 	[BPF_MAP_TYPE_PERCPU_HASH]		= "percpu_hash",
169 	[BPF_MAP_TYPE_PERCPU_ARRAY]		= "percpu_array",
170 	[BPF_MAP_TYPE_STACK_TRACE]		= "stack_trace",
171 	[BPF_MAP_TYPE_CGROUP_ARRAY]		= "cgroup_array",
172 	[BPF_MAP_TYPE_LRU_HASH]			= "lru_hash",
173 	[BPF_MAP_TYPE_LRU_PERCPU_HASH]		= "lru_percpu_hash",
174 	[BPF_MAP_TYPE_LPM_TRIE]			= "lpm_trie",
175 	[BPF_MAP_TYPE_ARRAY_OF_MAPS]		= "array_of_maps",
176 	[BPF_MAP_TYPE_HASH_OF_MAPS]		= "hash_of_maps",
177 	[BPF_MAP_TYPE_DEVMAP]			= "devmap",
178 	[BPF_MAP_TYPE_DEVMAP_HASH]		= "devmap_hash",
179 	[BPF_MAP_TYPE_SOCKMAP]			= "sockmap",
180 	[BPF_MAP_TYPE_CPUMAP]			= "cpumap",
181 	[BPF_MAP_TYPE_XSKMAP]			= "xskmap",
182 	[BPF_MAP_TYPE_SOCKHASH]			= "sockhash",
183 	[BPF_MAP_TYPE_CGROUP_STORAGE]		= "cgroup_storage",
184 	[BPF_MAP_TYPE_REUSEPORT_SOCKARRAY]	= "reuseport_sockarray",
185 	[BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE]	= "percpu_cgroup_storage",
186 	[BPF_MAP_TYPE_QUEUE]			= "queue",
187 	[BPF_MAP_TYPE_STACK]			= "stack",
188 	[BPF_MAP_TYPE_SK_STORAGE]		= "sk_storage",
189 	[BPF_MAP_TYPE_STRUCT_OPS]		= "struct_ops",
190 	[BPF_MAP_TYPE_RINGBUF]			= "ringbuf",
191 	[BPF_MAP_TYPE_INODE_STORAGE]		= "inode_storage",
192 	[BPF_MAP_TYPE_TASK_STORAGE]		= "task_storage",
193 	[BPF_MAP_TYPE_BLOOM_FILTER]		= "bloom_filter",
194 	[BPF_MAP_TYPE_USER_RINGBUF]             = "user_ringbuf",
195 	[BPF_MAP_TYPE_CGRP_STORAGE]		= "cgrp_storage",
196 	[BPF_MAP_TYPE_ARENA]			= "arena",
197 };
198 
199 static const char * const prog_type_name[] = {
200 	[BPF_PROG_TYPE_UNSPEC]			= "unspec",
201 	[BPF_PROG_TYPE_SOCKET_FILTER]		= "socket_filter",
202 	[BPF_PROG_TYPE_KPROBE]			= "kprobe",
203 	[BPF_PROG_TYPE_SCHED_CLS]		= "sched_cls",
204 	[BPF_PROG_TYPE_SCHED_ACT]		= "sched_act",
205 	[BPF_PROG_TYPE_TRACEPOINT]		= "tracepoint",
206 	[BPF_PROG_TYPE_XDP]			= "xdp",
207 	[BPF_PROG_TYPE_PERF_EVENT]		= "perf_event",
208 	[BPF_PROG_TYPE_CGROUP_SKB]		= "cgroup_skb",
209 	[BPF_PROG_TYPE_CGROUP_SOCK]		= "cgroup_sock",
210 	[BPF_PROG_TYPE_LWT_IN]			= "lwt_in",
211 	[BPF_PROG_TYPE_LWT_OUT]			= "lwt_out",
212 	[BPF_PROG_TYPE_LWT_XMIT]		= "lwt_xmit",
213 	[BPF_PROG_TYPE_SOCK_OPS]		= "sock_ops",
214 	[BPF_PROG_TYPE_SK_SKB]			= "sk_skb",
215 	[BPF_PROG_TYPE_CGROUP_DEVICE]		= "cgroup_device",
216 	[BPF_PROG_TYPE_SK_MSG]			= "sk_msg",
217 	[BPF_PROG_TYPE_RAW_TRACEPOINT]		= "raw_tracepoint",
218 	[BPF_PROG_TYPE_CGROUP_SOCK_ADDR]	= "cgroup_sock_addr",
219 	[BPF_PROG_TYPE_LWT_SEG6LOCAL]		= "lwt_seg6local",
220 	[BPF_PROG_TYPE_LIRC_MODE2]		= "lirc_mode2",
221 	[BPF_PROG_TYPE_SK_REUSEPORT]		= "sk_reuseport",
222 	[BPF_PROG_TYPE_FLOW_DISSECTOR]		= "flow_dissector",
223 	[BPF_PROG_TYPE_CGROUP_SYSCTL]		= "cgroup_sysctl",
224 	[BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE]	= "raw_tracepoint_writable",
225 	[BPF_PROG_TYPE_CGROUP_SOCKOPT]		= "cgroup_sockopt",
226 	[BPF_PROG_TYPE_TRACING]			= "tracing",
227 	[BPF_PROG_TYPE_STRUCT_OPS]		= "struct_ops",
228 	[BPF_PROG_TYPE_EXT]			= "ext",
229 	[BPF_PROG_TYPE_LSM]			= "lsm",
230 	[BPF_PROG_TYPE_SK_LOOKUP]		= "sk_lookup",
231 	[BPF_PROG_TYPE_SYSCALL]			= "syscall",
232 	[BPF_PROG_TYPE_NETFILTER]		= "netfilter",
233 };
234 
235 static int __base_pr(enum libbpf_print_level level, const char *format,
236 		     va_list args)
237 {
238 	const char *env_var = "LIBBPF_LOG_LEVEL";
239 	static enum libbpf_print_level min_level = LIBBPF_INFO;
240 	static bool initialized;
241 
242 	if (!initialized) {
243 		char *verbosity;
244 
245 		initialized = true;
246 		verbosity = getenv(env_var);
247 		if (verbosity) {
248 			if (strcasecmp(verbosity, "warn") == 0)
249 				min_level = LIBBPF_WARN;
250 			else if (strcasecmp(verbosity, "debug") == 0)
251 				min_level = LIBBPF_DEBUG;
252 			else if (strcasecmp(verbosity, "info") == 0)
253 				min_level = LIBBPF_INFO;
254 			else
255 				fprintf(stderr, "libbpf: unrecognized '%s' envvar value: '%s', should be one of 'warn', 'debug', or 'info'.\n",
256 					env_var, verbosity);
257 		}
258 	}
259 
260 	/* if too verbose, skip logging  */
261 	if (level > min_level)
262 		return 0;
263 
264 	return vfprintf(stderr, format, args);
265 }
266 
267 static libbpf_print_fn_t __libbpf_pr = __base_pr;
268 
269 libbpf_print_fn_t libbpf_set_print(libbpf_print_fn_t fn)
270 {
271 	libbpf_print_fn_t old_print_fn;
272 
273 	old_print_fn = __atomic_exchange_n(&__libbpf_pr, fn, __ATOMIC_RELAXED);
274 
275 	return old_print_fn;
276 }
277 
278 __printf(2, 3)
279 void libbpf_print(enum libbpf_print_level level, const char *format, ...)
280 {
281 	va_list args;
282 	int old_errno;
283 	libbpf_print_fn_t print_fn;
284 
285 	print_fn = __atomic_load_n(&__libbpf_pr, __ATOMIC_RELAXED);
286 	if (!print_fn)
287 		return;
288 
289 	old_errno = errno;
290 
291 	va_start(args, format);
292 	print_fn(level, format, args);
293 	va_end(args);
294 
295 	errno = old_errno;
296 }
297 
298 static void pr_perm_msg(int err)
299 {
300 	struct rlimit limit;
301 	char buf[100];
302 
303 	if (err != -EPERM || geteuid() != 0)
304 		return;
305 
306 	err = getrlimit(RLIMIT_MEMLOCK, &limit);
307 	if (err)
308 		return;
309 
310 	if (limit.rlim_cur == RLIM_INFINITY)
311 		return;
312 
313 	if (limit.rlim_cur < 1024)
314 		snprintf(buf, sizeof(buf), "%zu bytes", (size_t)limit.rlim_cur);
315 	else if (limit.rlim_cur < 1024*1024)
316 		snprintf(buf, sizeof(buf), "%.1f KiB", (double)limit.rlim_cur / 1024);
317 	else
318 		snprintf(buf, sizeof(buf), "%.1f MiB", (double)limit.rlim_cur / (1024*1024));
319 
320 	pr_warn("permission error while running as root; try raising 'ulimit -l'? current value: %s\n",
321 		buf);
322 }
323 
324 #define STRERR_BUFSIZE  128
325 
326 /* Copied from tools/perf/util/util.h */
327 #ifndef zfree
328 # define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
329 #endif
330 
331 #ifndef zclose
332 # define zclose(fd) ({			\
333 	int ___err = 0;			\
334 	if ((fd) >= 0)			\
335 		___err = close((fd));	\
336 	fd = -1;			\
337 	___err; })
338 #endif
339 
340 static inline __u64 ptr_to_u64(const void *ptr)
341 {
342 	return (__u64) (unsigned long) ptr;
343 }
344 
345 int libbpf_set_strict_mode(enum libbpf_strict_mode mode)
346 {
347 	/* as of v1.0 libbpf_set_strict_mode() is a no-op */
348 	return 0;
349 }
350 
351 __u32 libbpf_major_version(void)
352 {
353 	return LIBBPF_MAJOR_VERSION;
354 }
355 
356 __u32 libbpf_minor_version(void)
357 {
358 	return LIBBPF_MINOR_VERSION;
359 }
360 
361 const char *libbpf_version_string(void)
362 {
363 #define __S(X) #X
364 #define _S(X) __S(X)
365 	return  "v" _S(LIBBPF_MAJOR_VERSION) "." _S(LIBBPF_MINOR_VERSION);
366 #undef _S
367 #undef __S
368 }
369 
370 enum reloc_type {
371 	RELO_LD64,
372 	RELO_CALL,
373 	RELO_DATA,
374 	RELO_EXTERN_LD64,
375 	RELO_EXTERN_CALL,
376 	RELO_SUBPROG_ADDR,
377 	RELO_CORE,
378 };
379 
380 struct reloc_desc {
381 	enum reloc_type type;
382 	int insn_idx;
383 	union {
384 		const struct bpf_core_relo *core_relo; /* used when type == RELO_CORE */
385 		struct {
386 			int map_idx;
387 			int sym_off;
388 			int ext_idx;
389 		};
390 	};
391 };
392 
393 /* stored as sec_def->cookie for all libbpf-supported SEC()s */
394 enum sec_def_flags {
395 	SEC_NONE = 0,
396 	/* expected_attach_type is optional, if kernel doesn't support that */
397 	SEC_EXP_ATTACH_OPT = 1,
398 	/* legacy, only used by libbpf_get_type_names() and
399 	 * libbpf_attach_type_by_name(), not used by libbpf itself at all.
400 	 * This used to be associated with cgroup (and few other) BPF programs
401 	 * that were attachable through BPF_PROG_ATTACH command. Pretty
402 	 * meaningless nowadays, though.
403 	 */
404 	SEC_ATTACHABLE = 2,
405 	SEC_ATTACHABLE_OPT = SEC_ATTACHABLE | SEC_EXP_ATTACH_OPT,
406 	/* attachment target is specified through BTF ID in either kernel or
407 	 * other BPF program's BTF object
408 	 */
409 	SEC_ATTACH_BTF = 4,
410 	/* BPF program type allows sleeping/blocking in kernel */
411 	SEC_SLEEPABLE = 8,
412 	/* BPF program support non-linear XDP buffer */
413 	SEC_XDP_FRAGS = 16,
414 	/* Setup proper attach type for usdt probes. */
415 	SEC_USDT = 32,
416 };
417 
418 struct bpf_sec_def {
419 	char *sec;
420 	enum bpf_prog_type prog_type;
421 	enum bpf_attach_type expected_attach_type;
422 	long cookie;
423 	int handler_id;
424 
425 	libbpf_prog_setup_fn_t prog_setup_fn;
426 	libbpf_prog_prepare_load_fn_t prog_prepare_load_fn;
427 	libbpf_prog_attach_fn_t prog_attach_fn;
428 };
429 
430 /*
431  * bpf_prog should be a better name but it has been used in
432  * linux/filter.h.
433  */
434 struct bpf_program {
435 	char *name;
436 	char *sec_name;
437 	size_t sec_idx;
438 	const struct bpf_sec_def *sec_def;
439 	/* this program's instruction offset (in number of instructions)
440 	 * within its containing ELF section
441 	 */
442 	size_t sec_insn_off;
443 	/* number of original instructions in ELF section belonging to this
444 	 * program, not taking into account subprogram instructions possible
445 	 * appended later during relocation
446 	 */
447 	size_t sec_insn_cnt;
448 	/* Offset (in number of instructions) of the start of instruction
449 	 * belonging to this BPF program  within its containing main BPF
450 	 * program. For the entry-point (main) BPF program, this is always
451 	 * zero. For a sub-program, this gets reset before each of main BPF
452 	 * programs are processed and relocated and is used to determined
453 	 * whether sub-program was already appended to the main program, and
454 	 * if yes, at which instruction offset.
455 	 */
456 	size_t sub_insn_off;
457 
458 	/* instructions that belong to BPF program; insns[0] is located at
459 	 * sec_insn_off instruction within its ELF section in ELF file, so
460 	 * when mapping ELF file instruction index to the local instruction,
461 	 * one needs to subtract sec_insn_off; and vice versa.
462 	 */
463 	struct bpf_insn *insns;
464 	/* actual number of instruction in this BPF program's image; for
465 	 * entry-point BPF programs this includes the size of main program
466 	 * itself plus all the used sub-programs, appended at the end
467 	 */
468 	size_t insns_cnt;
469 
470 	struct reloc_desc *reloc_desc;
471 	int nr_reloc;
472 
473 	/* BPF verifier log settings */
474 	char *log_buf;
475 	size_t log_size;
476 	__u32 log_level;
477 
478 	struct bpf_object *obj;
479 
480 	int fd;
481 	bool autoload;
482 	bool autoattach;
483 	bool sym_global;
484 	bool mark_btf_static;
485 	enum bpf_prog_type type;
486 	enum bpf_attach_type expected_attach_type;
487 	int exception_cb_idx;
488 
489 	int prog_ifindex;
490 	__u32 attach_btf_obj_fd;
491 	__u32 attach_btf_id;
492 	__u32 attach_prog_fd;
493 
494 	void *func_info;
495 	__u32 func_info_rec_size;
496 	__u32 func_info_cnt;
497 
498 	void *line_info;
499 	__u32 line_info_rec_size;
500 	__u32 line_info_cnt;
501 	__u32 prog_flags;
502 	__u8  hash[SHA256_DIGEST_LENGTH];
503 };
504 
505 struct bpf_struct_ops {
506 	struct bpf_program **progs;
507 	__u32 *kern_func_off;
508 	/* e.g. struct tcp_congestion_ops in bpf_prog's btf format */
509 	void *data;
510 	/* e.g. struct bpf_struct_ops_tcp_congestion_ops in
511 	 *      btf_vmlinux's format.
512 	 * struct bpf_struct_ops_tcp_congestion_ops {
513 	 *	[... some other kernel fields ...]
514 	 *	struct tcp_congestion_ops data;
515 	 * }
516 	 * kern_vdata-size == sizeof(struct bpf_struct_ops_tcp_congestion_ops)
517 	 * bpf_map__init_kern_struct_ops() will populate the "kern_vdata"
518 	 * from "data".
519 	 */
520 	void *kern_vdata;
521 	__u32 type_id;
522 };
523 
524 #define DATA_SEC ".data"
525 #define BSS_SEC ".bss"
526 #define RODATA_SEC ".rodata"
527 #define KCONFIG_SEC ".kconfig"
528 #define KSYMS_SEC ".ksyms"
529 #define STRUCT_OPS_SEC ".struct_ops"
530 #define STRUCT_OPS_LINK_SEC ".struct_ops.link"
531 #define ARENA_SEC ".addr_space.1"
532 
533 enum libbpf_map_type {
534 	LIBBPF_MAP_UNSPEC,
535 	LIBBPF_MAP_DATA,
536 	LIBBPF_MAP_BSS,
537 	LIBBPF_MAP_RODATA,
538 	LIBBPF_MAP_KCONFIG,
539 };
540 
541 struct bpf_map_def {
542 	unsigned int type;
543 	unsigned int key_size;
544 	unsigned int value_size;
545 	unsigned int max_entries;
546 	unsigned int map_flags;
547 };
548 
549 struct bpf_map {
550 	struct bpf_object *obj;
551 	char *name;
552 	/* real_name is defined for special internal maps (.rodata*,
553 	 * .data*, .bss, .kconfig) and preserves their original ELF section
554 	 * name. This is important to be able to find corresponding BTF
555 	 * DATASEC information.
556 	 */
557 	char *real_name;
558 	int fd;
559 	int sec_idx;
560 	size_t sec_offset;
561 	int map_ifindex;
562 	int inner_map_fd;
563 	struct bpf_map_def def;
564 	__u32 numa_node;
565 	__u32 btf_var_idx;
566 	int mod_btf_fd;
567 	__u32 btf_key_type_id;
568 	__u32 btf_value_type_id;
569 	__u32 btf_vmlinux_value_type_id;
570 	enum libbpf_map_type libbpf_type;
571 	void *mmaped;
572 	struct bpf_struct_ops *st_ops;
573 	struct bpf_map *inner_map;
574 	void **init_slots;
575 	int init_slots_sz;
576 	char *pin_path;
577 	bool pinned;
578 	bool reused;
579 	bool autocreate;
580 	bool autoattach;
581 	__u64 map_extra;
582 	struct bpf_program *excl_prog;
583 };
584 
585 enum extern_type {
586 	EXT_UNKNOWN,
587 	EXT_KCFG,
588 	EXT_KSYM,
589 };
590 
591 enum kcfg_type {
592 	KCFG_UNKNOWN,
593 	KCFG_CHAR,
594 	KCFG_BOOL,
595 	KCFG_INT,
596 	KCFG_TRISTATE,
597 	KCFG_CHAR_ARR,
598 };
599 
600 struct extern_desc {
601 	enum extern_type type;
602 	int sym_idx;
603 	int btf_id;
604 	int sec_btf_id;
605 	char *name;
606 	char *essent_name;
607 	bool is_set;
608 	bool is_weak;
609 	union {
610 		struct {
611 			enum kcfg_type type;
612 			int sz;
613 			int align;
614 			int data_off;
615 			bool is_signed;
616 		} kcfg;
617 		struct {
618 			unsigned long long addr;
619 
620 			/* target btf_id of the corresponding kernel var. */
621 			int kernel_btf_obj_fd;
622 			int kernel_btf_id;
623 
624 			/* local btf_id of the ksym extern's type. */
625 			__u32 type_id;
626 			/* BTF fd index to be patched in for insn->off, this is
627 			 * 0 for vmlinux BTF, index in obj->fd_array for module
628 			 * BTF
629 			 */
630 			__s16 btf_fd_idx;
631 		} ksym;
632 	};
633 };
634 
635 struct module_btf {
636 	struct btf *btf;
637 	char *name;
638 	__u32 id;
639 	int fd;
640 	int fd_array_idx;
641 };
642 
643 enum sec_type {
644 	SEC_UNUSED = 0,
645 	SEC_RELO,
646 	SEC_BSS,
647 	SEC_DATA,
648 	SEC_RODATA,
649 	SEC_ST_OPS,
650 };
651 
652 struct elf_sec_desc {
653 	enum sec_type sec_type;
654 	Elf64_Shdr *shdr;
655 	Elf_Data *data;
656 };
657 
658 struct elf_state {
659 	int fd;
660 	const void *obj_buf;
661 	size_t obj_buf_sz;
662 	Elf *elf;
663 	Elf64_Ehdr *ehdr;
664 	Elf_Data *symbols;
665 	Elf_Data *arena_data;
666 	size_t shstrndx; /* section index for section name strings */
667 	size_t strtabidx;
668 	struct elf_sec_desc *secs;
669 	size_t sec_cnt;
670 	int btf_maps_shndx;
671 	__u32 btf_maps_sec_btf_id;
672 	int text_shndx;
673 	int symbols_shndx;
674 	bool has_st_ops;
675 	int arena_data_shndx;
676 };
677 
678 struct usdt_manager;
679 
680 enum bpf_object_state {
681 	OBJ_OPEN,
682 	OBJ_PREPARED,
683 	OBJ_LOADED,
684 };
685 
686 struct bpf_object {
687 	char name[BPF_OBJ_NAME_LEN];
688 	char license[64];
689 	__u32 kern_version;
690 
691 	enum bpf_object_state state;
692 	struct bpf_program *programs;
693 	size_t nr_programs;
694 	struct bpf_map *maps;
695 	size_t nr_maps;
696 	size_t maps_cap;
697 
698 	char *kconfig;
699 	struct extern_desc *externs;
700 	int nr_extern;
701 	int kconfig_map_idx;
702 
703 	bool has_subcalls;
704 	bool has_rodata;
705 
706 	struct bpf_gen *gen_loader;
707 
708 	/* Information when doing ELF related work. Only valid if efile.elf is not NULL */
709 	struct elf_state efile;
710 
711 	unsigned char byteorder;
712 
713 	struct btf *btf;
714 	struct btf_ext *btf_ext;
715 
716 	/* Parse and load BTF vmlinux if any of the programs in the object need
717 	 * it at load time.
718 	 */
719 	struct btf *btf_vmlinux;
720 	/* Path to the custom BTF to be used for BPF CO-RE relocations as an
721 	 * override for vmlinux BTF.
722 	 */
723 	char *btf_custom_path;
724 	/* vmlinux BTF override for CO-RE relocations */
725 	struct btf *btf_vmlinux_override;
726 	/* Lazily initialized kernel module BTFs */
727 	struct module_btf *btf_modules;
728 	bool btf_modules_loaded;
729 	size_t btf_module_cnt;
730 	size_t btf_module_cap;
731 
732 	/* optional log settings passed to BPF_BTF_LOAD and BPF_PROG_LOAD commands */
733 	char *log_buf;
734 	size_t log_size;
735 	__u32 log_level;
736 
737 	int *fd_array;
738 	size_t fd_array_cap;
739 	size_t fd_array_cnt;
740 
741 	struct usdt_manager *usdt_man;
742 
743 	int arena_map_idx;
744 	void *arena_data;
745 	size_t arena_data_sz;
746 
747 	struct kern_feature_cache *feat_cache;
748 	char *token_path;
749 	int token_fd;
750 
751 	char path[];
752 };
753 
754 static const char *elf_sym_str(const struct bpf_object *obj, size_t off);
755 static const char *elf_sec_str(const struct bpf_object *obj, size_t off);
756 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx);
757 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name);
758 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn);
759 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn);
760 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn);
761 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx);
762 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx);
763 
764 void bpf_program__unload(struct bpf_program *prog)
765 {
766 	if (!prog)
767 		return;
768 
769 	zclose(prog->fd);
770 
771 	zfree(&prog->func_info);
772 	zfree(&prog->line_info);
773 }
774 
775 static void bpf_program__exit(struct bpf_program *prog)
776 {
777 	if (!prog)
778 		return;
779 
780 	bpf_program__unload(prog);
781 	zfree(&prog->name);
782 	zfree(&prog->sec_name);
783 	zfree(&prog->insns);
784 	zfree(&prog->reloc_desc);
785 
786 	prog->nr_reloc = 0;
787 	prog->insns_cnt = 0;
788 	prog->sec_idx = -1;
789 }
790 
791 static bool insn_is_subprog_call(const struct bpf_insn *insn)
792 {
793 	return BPF_CLASS(insn->code) == BPF_JMP &&
794 	       BPF_OP(insn->code) == BPF_CALL &&
795 	       BPF_SRC(insn->code) == BPF_K &&
796 	       insn->src_reg == BPF_PSEUDO_CALL &&
797 	       insn->dst_reg == 0 &&
798 	       insn->off == 0;
799 }
800 
801 static bool is_call_insn(const struct bpf_insn *insn)
802 {
803 	return insn->code == (BPF_JMP | BPF_CALL);
804 }
805 
806 static bool insn_is_pseudo_func(struct bpf_insn *insn)
807 {
808 	return is_ldimm64_insn(insn) && insn->src_reg == BPF_PSEUDO_FUNC;
809 }
810 
811 static int
812 bpf_object__init_prog(struct bpf_object *obj, struct bpf_program *prog,
813 		      const char *name, size_t sec_idx, const char *sec_name,
814 		      size_t sec_off, void *insn_data, size_t insn_data_sz)
815 {
816 	if (insn_data_sz == 0 || insn_data_sz % BPF_INSN_SZ || sec_off % BPF_INSN_SZ) {
817 		pr_warn("sec '%s': corrupted program '%s', offset %zu, size %zu\n",
818 			sec_name, name, sec_off, insn_data_sz);
819 		return -EINVAL;
820 	}
821 
822 	memset(prog, 0, sizeof(*prog));
823 	prog->obj = obj;
824 
825 	prog->sec_idx = sec_idx;
826 	prog->sec_insn_off = sec_off / BPF_INSN_SZ;
827 	prog->sec_insn_cnt = insn_data_sz / BPF_INSN_SZ;
828 	/* insns_cnt can later be increased by appending used subprograms */
829 	prog->insns_cnt = prog->sec_insn_cnt;
830 
831 	prog->type = BPF_PROG_TYPE_UNSPEC;
832 	prog->fd = -1;
833 	prog->exception_cb_idx = -1;
834 
835 	/* libbpf's convention for SEC("?abc...") is that it's just like
836 	 * SEC("abc...") but the corresponding bpf_program starts out with
837 	 * autoload set to false.
838 	 */
839 	if (sec_name[0] == '?') {
840 		prog->autoload = false;
841 		/* from now on forget there was ? in section name */
842 		sec_name++;
843 	} else {
844 		prog->autoload = true;
845 	}
846 
847 	prog->autoattach = true;
848 
849 	/* inherit object's log_level */
850 	prog->log_level = obj->log_level;
851 
852 	prog->sec_name = strdup(sec_name);
853 	if (!prog->sec_name)
854 		goto errout;
855 
856 	prog->name = strdup(name);
857 	if (!prog->name)
858 		goto errout;
859 
860 	prog->insns = malloc(insn_data_sz);
861 	if (!prog->insns)
862 		goto errout;
863 	memcpy(prog->insns, insn_data, insn_data_sz);
864 
865 	return 0;
866 errout:
867 	pr_warn("sec '%s': failed to allocate memory for prog '%s'\n", sec_name, name);
868 	bpf_program__exit(prog);
869 	return -ENOMEM;
870 }
871 
872 static int
873 bpf_object__add_programs(struct bpf_object *obj, Elf_Data *sec_data,
874 			 const char *sec_name, int sec_idx)
875 {
876 	Elf_Data *symbols = obj->efile.symbols;
877 	struct bpf_program *prog, *progs;
878 	void *data = sec_data->d_buf;
879 	size_t sec_sz = sec_data->d_size, sec_off, prog_sz, nr_syms;
880 	int nr_progs, err, i;
881 	const char *name;
882 	Elf64_Sym *sym;
883 
884 	progs = obj->programs;
885 	nr_progs = obj->nr_programs;
886 	nr_syms = symbols->d_size / sizeof(Elf64_Sym);
887 
888 	for (i = 0; i < nr_syms; i++) {
889 		sym = elf_sym_by_idx(obj, i);
890 
891 		if (sym->st_shndx != sec_idx)
892 			continue;
893 		if (ELF64_ST_TYPE(sym->st_info) != STT_FUNC)
894 			continue;
895 
896 		prog_sz = sym->st_size;
897 		sec_off = sym->st_value;
898 
899 		name = elf_sym_str(obj, sym->st_name);
900 		if (!name) {
901 			pr_warn("sec '%s': failed to get symbol name for offset %zu\n",
902 				sec_name, sec_off);
903 			return -LIBBPF_ERRNO__FORMAT;
904 		}
905 
906 		if (sec_off + prog_sz > sec_sz || sec_off + prog_sz < sec_off) {
907 			pr_warn("sec '%s': program at offset %zu crosses section boundary\n",
908 				sec_name, sec_off);
909 			return -LIBBPF_ERRNO__FORMAT;
910 		}
911 
912 		if (sec_idx != obj->efile.text_shndx && ELF64_ST_BIND(sym->st_info) == STB_LOCAL) {
913 			pr_warn("sec '%s': program '%s' is static and not supported\n", sec_name, name);
914 			return -ENOTSUP;
915 		}
916 
917 		pr_debug("sec '%s': found program '%s' at insn offset %zu (%zu bytes), code size %zu insns (%zu bytes)\n",
918 			 sec_name, name, sec_off / BPF_INSN_SZ, sec_off, prog_sz / BPF_INSN_SZ, prog_sz);
919 
920 		progs = libbpf_reallocarray(progs, nr_progs + 1, sizeof(*progs));
921 		if (!progs) {
922 			/*
923 			 * In this case the original obj->programs
924 			 * is still valid, so don't need special treat for
925 			 * bpf_close_object().
926 			 */
927 			pr_warn("sec '%s': failed to alloc memory for new program '%s'\n",
928 				sec_name, name);
929 			return -ENOMEM;
930 		}
931 		obj->programs = progs;
932 
933 		prog = &progs[nr_progs];
934 
935 		err = bpf_object__init_prog(obj, prog, name, sec_idx, sec_name,
936 					    sec_off, data + sec_off, prog_sz);
937 		if (err)
938 			return err;
939 
940 		if (ELF64_ST_BIND(sym->st_info) != STB_LOCAL)
941 			prog->sym_global = true;
942 
943 		/* if function is a global/weak symbol, but has restricted
944 		 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF FUNC
945 		 * as static to enable more permissive BPF verification mode
946 		 * with more outside context available to BPF verifier
947 		 */
948 		if (prog->sym_global && (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
949 		    || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL))
950 			prog->mark_btf_static = true;
951 
952 		nr_progs++;
953 		obj->nr_programs = nr_progs;
954 	}
955 
956 	return 0;
957 }
958 
959 static void bpf_object_bswap_progs(struct bpf_object *obj)
960 {
961 	struct bpf_program *prog = obj->programs;
962 	struct bpf_insn *insn;
963 	int p, i;
964 
965 	for (p = 0; p < obj->nr_programs; p++, prog++) {
966 		insn = prog->insns;
967 		for (i = 0; i < prog->insns_cnt; i++, insn++)
968 			bpf_insn_bswap(insn);
969 	}
970 	pr_debug("converted %zu BPF programs to native byte order\n", obj->nr_programs);
971 }
972 
973 static const struct btf_member *
974 find_member_by_offset(const struct btf_type *t, __u32 bit_offset)
975 {
976 	struct btf_member *m;
977 	int i;
978 
979 	for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
980 		if (btf_member_bit_offset(t, i) == bit_offset)
981 			return m;
982 	}
983 
984 	return NULL;
985 }
986 
987 static const struct btf_member *
988 find_member_by_name(const struct btf *btf, const struct btf_type *t,
989 		    const char *name)
990 {
991 	struct btf_member *m;
992 	int i;
993 
994 	for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
995 		if (!strcmp(btf__name_by_offset(btf, m->name_off), name))
996 			return m;
997 	}
998 
999 	return NULL;
1000 }
1001 
1002 static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
1003 			    __u16 kind, struct btf **res_btf,
1004 			    struct module_btf **res_mod_btf);
1005 
1006 #define STRUCT_OPS_VALUE_PREFIX "bpf_struct_ops_"
1007 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
1008 				   const char *name, __u32 kind);
1009 
1010 static int
1011 find_struct_ops_kern_types(struct bpf_object *obj, const char *tname_raw,
1012 			   struct module_btf **mod_btf,
1013 			   const struct btf_type **type, __u32 *type_id,
1014 			   const struct btf_type **vtype, __u32 *vtype_id,
1015 			   const struct btf_member **data_member)
1016 {
1017 	const struct btf_type *kern_type, *kern_vtype;
1018 	const struct btf_member *kern_data_member;
1019 	struct btf *btf = NULL;
1020 	__s32 kern_vtype_id, kern_type_id;
1021 	char tname[256];
1022 	__u32 i;
1023 
1024 	snprintf(tname, sizeof(tname), "%.*s",
1025 		 (int)bpf_core_essential_name_len(tname_raw), tname_raw);
1026 
1027 	kern_type_id = find_ksym_btf_id(obj, tname, BTF_KIND_STRUCT,
1028 					&btf, mod_btf);
1029 	if (kern_type_id < 0) {
1030 		pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n",
1031 			tname);
1032 		return kern_type_id;
1033 	}
1034 	kern_type = btf__type_by_id(btf, kern_type_id);
1035 
1036 	/* Find the corresponding "map_value" type that will be used
1037 	 * in map_update(BPF_MAP_TYPE_STRUCT_OPS).  For example,
1038 	 * find "struct bpf_struct_ops_tcp_congestion_ops" from the
1039 	 * btf_vmlinux.
1040 	 */
1041 	kern_vtype_id = find_btf_by_prefix_kind(btf, STRUCT_OPS_VALUE_PREFIX,
1042 						tname, BTF_KIND_STRUCT);
1043 	if (kern_vtype_id < 0) {
1044 		pr_warn("struct_ops init_kern: struct %s%s is not found in kernel BTF\n",
1045 			STRUCT_OPS_VALUE_PREFIX, tname);
1046 		return kern_vtype_id;
1047 	}
1048 	kern_vtype = btf__type_by_id(btf, kern_vtype_id);
1049 
1050 	/* Find "struct tcp_congestion_ops" from
1051 	 * struct bpf_struct_ops_tcp_congestion_ops {
1052 	 *	[ ... ]
1053 	 *	struct tcp_congestion_ops data;
1054 	 * }
1055 	 */
1056 	kern_data_member = btf_members(kern_vtype);
1057 	for (i = 0; i < btf_vlen(kern_vtype); i++, kern_data_member++) {
1058 		if (kern_data_member->type == kern_type_id)
1059 			break;
1060 	}
1061 	if (i == btf_vlen(kern_vtype)) {
1062 		pr_warn("struct_ops init_kern: struct %s data is not found in struct %s%s\n",
1063 			tname, STRUCT_OPS_VALUE_PREFIX, tname);
1064 		return -EINVAL;
1065 	}
1066 
1067 	*type = kern_type;
1068 	*type_id = kern_type_id;
1069 	*vtype = kern_vtype;
1070 	*vtype_id = kern_vtype_id;
1071 	*data_member = kern_data_member;
1072 
1073 	return 0;
1074 }
1075 
1076 static bool bpf_map__is_struct_ops(const struct bpf_map *map)
1077 {
1078 	return map->def.type == BPF_MAP_TYPE_STRUCT_OPS;
1079 }
1080 
1081 static bool is_valid_st_ops_program(struct bpf_object *obj,
1082 				    const struct bpf_program *prog)
1083 {
1084 	int i;
1085 
1086 	for (i = 0; i < obj->nr_programs; i++) {
1087 		if (&obj->programs[i] == prog)
1088 			return prog->type == BPF_PROG_TYPE_STRUCT_OPS;
1089 	}
1090 
1091 	return false;
1092 }
1093 
1094 /* For each struct_ops program P, referenced from some struct_ops map M,
1095  * enable P.autoload if there are Ms for which M.autocreate is true,
1096  * disable P.autoload if for all Ms M.autocreate is false.
1097  * Don't change P.autoload for programs that are not referenced from any maps.
1098  */
1099 static int bpf_object_adjust_struct_ops_autoload(struct bpf_object *obj)
1100 {
1101 	struct bpf_program *prog, *slot_prog;
1102 	struct bpf_map *map;
1103 	int i, j, k, vlen;
1104 
1105 	for (i = 0; i < obj->nr_programs; ++i) {
1106 		int should_load = false;
1107 		int use_cnt = 0;
1108 
1109 		prog = &obj->programs[i];
1110 		if (prog->type != BPF_PROG_TYPE_STRUCT_OPS)
1111 			continue;
1112 
1113 		for (j = 0; j < obj->nr_maps; ++j) {
1114 			const struct btf_type *type;
1115 
1116 			map = &obj->maps[j];
1117 			if (!bpf_map__is_struct_ops(map))
1118 				continue;
1119 
1120 			type = btf__type_by_id(obj->btf, map->st_ops->type_id);
1121 			vlen = btf_vlen(type);
1122 			for (k = 0; k < vlen; ++k) {
1123 				slot_prog = map->st_ops->progs[k];
1124 				if (prog != slot_prog)
1125 					continue;
1126 
1127 				use_cnt++;
1128 				if (map->autocreate)
1129 					should_load = true;
1130 			}
1131 		}
1132 		if (use_cnt)
1133 			prog->autoload = should_load;
1134 	}
1135 
1136 	return 0;
1137 }
1138 
1139 /* Init the map's fields that depend on kern_btf */
1140 static int bpf_map__init_kern_struct_ops(struct bpf_map *map)
1141 {
1142 	const struct btf_member *member, *kern_member, *kern_data_member;
1143 	const struct btf_type *type, *kern_type, *kern_vtype;
1144 	__u32 i, kern_type_id, kern_vtype_id, kern_data_off;
1145 	struct bpf_object *obj = map->obj;
1146 	const struct btf *btf = obj->btf;
1147 	struct bpf_struct_ops *st_ops;
1148 	const struct btf *kern_btf;
1149 	struct module_btf *mod_btf = NULL;
1150 	void *data, *kern_data;
1151 	const char *tname;
1152 	int err;
1153 
1154 	st_ops = map->st_ops;
1155 	type = btf__type_by_id(btf, st_ops->type_id);
1156 	tname = btf__name_by_offset(btf, type->name_off);
1157 	err = find_struct_ops_kern_types(obj, tname, &mod_btf,
1158 					 &kern_type, &kern_type_id,
1159 					 &kern_vtype, &kern_vtype_id,
1160 					 &kern_data_member);
1161 	if (err)
1162 		return err;
1163 
1164 	kern_btf = mod_btf ? mod_btf->btf : obj->btf_vmlinux;
1165 
1166 	pr_debug("struct_ops init_kern %s: type_id:%u kern_type_id:%u kern_vtype_id:%u\n",
1167 		 map->name, st_ops->type_id, kern_type_id, kern_vtype_id);
1168 
1169 	map->mod_btf_fd = mod_btf ? mod_btf->fd : -1;
1170 	map->def.value_size = kern_vtype->size;
1171 	map->btf_vmlinux_value_type_id = kern_vtype_id;
1172 
1173 	st_ops->kern_vdata = calloc(1, kern_vtype->size);
1174 	if (!st_ops->kern_vdata)
1175 		return -ENOMEM;
1176 
1177 	data = st_ops->data;
1178 	kern_data_off = kern_data_member->offset / 8;
1179 	kern_data = st_ops->kern_vdata + kern_data_off;
1180 
1181 	member = btf_members(type);
1182 	for (i = 0; i < btf_vlen(type); i++, member++) {
1183 		const struct btf_type *mtype, *kern_mtype;
1184 		__u32 mtype_id, kern_mtype_id;
1185 		void *mdata, *kern_mdata;
1186 		struct bpf_program *prog;
1187 		__s64 msize, kern_msize;
1188 		__u32 moff, kern_moff;
1189 		__u32 kern_member_idx;
1190 		const char *mname;
1191 
1192 		mname = btf__name_by_offset(btf, member->name_off);
1193 		moff = member->offset / 8;
1194 		mdata = data + moff;
1195 		msize = btf__resolve_size(btf, member->type);
1196 		if (msize < 0) {
1197 			pr_warn("struct_ops init_kern %s: failed to resolve the size of member %s\n",
1198 				map->name, mname);
1199 			return msize;
1200 		}
1201 
1202 		kern_member = find_member_by_name(kern_btf, kern_type, mname);
1203 		if (!kern_member) {
1204 			if (!libbpf_is_mem_zeroed(mdata, msize)) {
1205 				pr_warn("struct_ops init_kern %s: Cannot find member %s in kernel BTF\n",
1206 					map->name, mname);
1207 				return -ENOTSUP;
1208 			}
1209 
1210 			if (st_ops->progs[i]) {
1211 				/* If we had declaratively set struct_ops callback, we need to
1212 				 * force its autoload to false, because it doesn't have
1213 				 * a chance of succeeding from POV of the current struct_ops map.
1214 				 * If this program is still referenced somewhere else, though,
1215 				 * then bpf_object_adjust_struct_ops_autoload() will update its
1216 				 * autoload accordingly.
1217 				 */
1218 				st_ops->progs[i]->autoload = false;
1219 				st_ops->progs[i] = NULL;
1220 			}
1221 
1222 			/* Skip all-zero/NULL fields if they are not present in the kernel BTF */
1223 			pr_info("struct_ops %s: member %s not found in kernel, skipping it as it's set to zero\n",
1224 				map->name, mname);
1225 			continue;
1226 		}
1227 
1228 		kern_member_idx = kern_member - btf_members(kern_type);
1229 		if (btf_member_bitfield_size(type, i) ||
1230 		    btf_member_bitfield_size(kern_type, kern_member_idx)) {
1231 			pr_warn("struct_ops init_kern %s: bitfield %s is not supported\n",
1232 				map->name, mname);
1233 			return -ENOTSUP;
1234 		}
1235 
1236 		kern_moff = kern_member->offset / 8;
1237 		kern_mdata = kern_data + kern_moff;
1238 
1239 		mtype = skip_mods_and_typedefs(btf, member->type, &mtype_id);
1240 		kern_mtype = skip_mods_and_typedefs(kern_btf, kern_member->type,
1241 						    &kern_mtype_id);
1242 		if (BTF_INFO_KIND(mtype->info) !=
1243 		    BTF_INFO_KIND(kern_mtype->info)) {
1244 			pr_warn("struct_ops init_kern %s: Unmatched member type %s %u != %u(kernel)\n",
1245 				map->name, mname, BTF_INFO_KIND(mtype->info),
1246 				BTF_INFO_KIND(kern_mtype->info));
1247 			return -ENOTSUP;
1248 		}
1249 
1250 		if (btf_is_ptr(mtype)) {
1251 			prog = *(void **)mdata;
1252 			/* just like for !kern_member case above, reset declaratively
1253 			 * set (at compile time) program's autload to false,
1254 			 * if user replaced it with another program or NULL
1255 			 */
1256 			if (st_ops->progs[i] && st_ops->progs[i] != prog)
1257 				st_ops->progs[i]->autoload = false;
1258 
1259 			/* Update the value from the shadow type */
1260 			st_ops->progs[i] = prog;
1261 			if (!prog)
1262 				continue;
1263 
1264 			if (!is_valid_st_ops_program(obj, prog)) {
1265 				pr_warn("struct_ops init_kern %s: member %s is not a struct_ops program\n",
1266 					map->name, mname);
1267 				return -ENOTSUP;
1268 			}
1269 
1270 			kern_mtype = skip_mods_and_typedefs(kern_btf,
1271 							    kern_mtype->type,
1272 							    &kern_mtype_id);
1273 
1274 			/* mtype->type must be a func_proto which was
1275 			 * guaranteed in bpf_object__collect_st_ops_relos(),
1276 			 * so only check kern_mtype for func_proto here.
1277 			 */
1278 			if (!btf_is_func_proto(kern_mtype)) {
1279 				pr_warn("struct_ops init_kern %s: kernel member %s is not a func ptr\n",
1280 					map->name, mname);
1281 				return -ENOTSUP;
1282 			}
1283 
1284 			if (mod_btf)
1285 				prog->attach_btf_obj_fd = mod_btf->fd;
1286 
1287 			/* if we haven't yet processed this BPF program, record proper
1288 			 * attach_btf_id and member_idx
1289 			 */
1290 			if (!prog->attach_btf_id) {
1291 				prog->attach_btf_id = kern_type_id;
1292 				prog->expected_attach_type = kern_member_idx;
1293 			}
1294 
1295 			/* struct_ops BPF prog can be re-used between multiple
1296 			 * .struct_ops & .struct_ops.link as long as it's the
1297 			 * same struct_ops struct definition and the same
1298 			 * function pointer field
1299 			 */
1300 			if (prog->attach_btf_id != kern_type_id) {
1301 				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",
1302 					map->name, mname, prog->name, prog->sec_name, prog->type,
1303 					prog->attach_btf_id, kern_type_id);
1304 				return -EINVAL;
1305 			}
1306 			if (prog->expected_attach_type != kern_member_idx) {
1307 				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",
1308 					map->name, mname, prog->name, prog->sec_name, prog->type,
1309 					prog->expected_attach_type, kern_member_idx);
1310 				return -EINVAL;
1311 			}
1312 
1313 			st_ops->kern_func_off[i] = kern_data_off + kern_moff;
1314 
1315 			pr_debug("struct_ops init_kern %s: func ptr %s is set to prog %s from data(+%u) to kern_data(+%u)\n",
1316 				 map->name, mname, prog->name, moff,
1317 				 kern_moff);
1318 
1319 			continue;
1320 		}
1321 
1322 		kern_msize = btf__resolve_size(kern_btf, kern_mtype_id);
1323 		if (kern_msize < 0 || msize != kern_msize) {
1324 			pr_warn("struct_ops init_kern %s: Error in size of member %s: %zd != %zd(kernel)\n",
1325 				map->name, mname, (ssize_t)msize,
1326 				(ssize_t)kern_msize);
1327 			return -ENOTSUP;
1328 		}
1329 
1330 		pr_debug("struct_ops init_kern %s: copy %s %u bytes from data(+%u) to kern_data(+%u)\n",
1331 			 map->name, mname, (unsigned int)msize,
1332 			 moff, kern_moff);
1333 		memcpy(kern_mdata, mdata, msize);
1334 	}
1335 
1336 	return 0;
1337 }
1338 
1339 static int bpf_object__init_kern_struct_ops_maps(struct bpf_object *obj)
1340 {
1341 	struct bpf_map *map;
1342 	size_t i;
1343 	int err;
1344 
1345 	for (i = 0; i < obj->nr_maps; i++) {
1346 		map = &obj->maps[i];
1347 
1348 		if (!bpf_map__is_struct_ops(map))
1349 			continue;
1350 
1351 		if (!map->autocreate)
1352 			continue;
1353 
1354 		err = bpf_map__init_kern_struct_ops(map);
1355 		if (err)
1356 			return err;
1357 	}
1358 
1359 	return 0;
1360 }
1361 
1362 static int init_struct_ops_maps(struct bpf_object *obj, const char *sec_name,
1363 				int shndx, Elf_Data *data)
1364 {
1365 	const struct btf_type *type, *datasec;
1366 	const struct btf_var_secinfo *vsi;
1367 	struct bpf_struct_ops *st_ops;
1368 	const char *tname, *var_name;
1369 	__s32 type_id, datasec_id;
1370 	const struct btf *btf;
1371 	struct bpf_map *map;
1372 	__u32 i;
1373 
1374 	if (shndx == -1)
1375 		return 0;
1376 
1377 	btf = obj->btf;
1378 	datasec_id = btf__find_by_name_kind(btf, sec_name,
1379 					    BTF_KIND_DATASEC);
1380 	if (datasec_id < 0) {
1381 		pr_warn("struct_ops init: DATASEC %s not found\n",
1382 			sec_name);
1383 		return -EINVAL;
1384 	}
1385 
1386 	datasec = btf__type_by_id(btf, datasec_id);
1387 	vsi = btf_var_secinfos(datasec);
1388 	for (i = 0; i < btf_vlen(datasec); i++, vsi++) {
1389 		type = btf__type_by_id(obj->btf, vsi->type);
1390 		var_name = btf__name_by_offset(obj->btf, type->name_off);
1391 
1392 		type_id = btf__resolve_type(obj->btf, vsi->type);
1393 		if (type_id < 0) {
1394 			pr_warn("struct_ops init: Cannot resolve var type_id %u in DATASEC %s\n",
1395 				vsi->type, sec_name);
1396 			return -EINVAL;
1397 		}
1398 
1399 		type = btf__type_by_id(obj->btf, type_id);
1400 		tname = btf__name_by_offset(obj->btf, type->name_off);
1401 		if (!tname[0]) {
1402 			pr_warn("struct_ops init: anonymous type is not supported\n");
1403 			return -ENOTSUP;
1404 		}
1405 		if (!btf_is_struct(type)) {
1406 			pr_warn("struct_ops init: %s is not a struct\n", tname);
1407 			return -EINVAL;
1408 		}
1409 
1410 		map = bpf_object__add_map(obj);
1411 		if (IS_ERR(map))
1412 			return PTR_ERR(map);
1413 
1414 		map->sec_idx = shndx;
1415 		map->sec_offset = vsi->offset;
1416 		map->name = strdup(var_name);
1417 		if (!map->name)
1418 			return -ENOMEM;
1419 		map->btf_value_type_id = type_id;
1420 
1421 		/* Follow same convention as for programs autoload:
1422 		 * SEC("?.struct_ops") means map is not created by default.
1423 		 */
1424 		if (sec_name[0] == '?') {
1425 			map->autocreate = false;
1426 			/* from now on forget there was ? in section name */
1427 			sec_name++;
1428 		}
1429 
1430 		map->def.type = BPF_MAP_TYPE_STRUCT_OPS;
1431 		map->def.key_size = sizeof(int);
1432 		map->def.value_size = type->size;
1433 		map->def.max_entries = 1;
1434 		map->def.map_flags = strcmp(sec_name, STRUCT_OPS_LINK_SEC) == 0 ? BPF_F_LINK : 0;
1435 		map->autoattach = true;
1436 
1437 		map->st_ops = calloc(1, sizeof(*map->st_ops));
1438 		if (!map->st_ops)
1439 			return -ENOMEM;
1440 		st_ops = map->st_ops;
1441 		st_ops->data = malloc(type->size);
1442 		st_ops->progs = calloc(btf_vlen(type), sizeof(*st_ops->progs));
1443 		st_ops->kern_func_off = malloc(btf_vlen(type) *
1444 					       sizeof(*st_ops->kern_func_off));
1445 		if (!st_ops->data || !st_ops->progs || !st_ops->kern_func_off)
1446 			return -ENOMEM;
1447 
1448 		if (vsi->offset + type->size > data->d_size) {
1449 			pr_warn("struct_ops init: var %s is beyond the end of DATASEC %s\n",
1450 				var_name, sec_name);
1451 			return -EINVAL;
1452 		}
1453 
1454 		memcpy(st_ops->data,
1455 		       data->d_buf + vsi->offset,
1456 		       type->size);
1457 		st_ops->type_id = type_id;
1458 
1459 		pr_debug("struct_ops init: struct %s(type_id=%u) %s found at offset %u\n",
1460 			 tname, type_id, var_name, vsi->offset);
1461 	}
1462 
1463 	return 0;
1464 }
1465 
1466 static int bpf_object_init_struct_ops(struct bpf_object *obj)
1467 {
1468 	const char *sec_name;
1469 	int sec_idx, err;
1470 
1471 	for (sec_idx = 0; sec_idx < obj->efile.sec_cnt; ++sec_idx) {
1472 		struct elf_sec_desc *desc = &obj->efile.secs[sec_idx];
1473 
1474 		if (desc->sec_type != SEC_ST_OPS)
1475 			continue;
1476 
1477 		sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1478 		if (!sec_name)
1479 			return -LIBBPF_ERRNO__FORMAT;
1480 
1481 		err = init_struct_ops_maps(obj, sec_name, sec_idx, desc->data);
1482 		if (err)
1483 			return err;
1484 	}
1485 
1486 	return 0;
1487 }
1488 
1489 static struct bpf_object *bpf_object__new(const char *path,
1490 					  const void *obj_buf,
1491 					  size_t obj_buf_sz,
1492 					  const char *obj_name)
1493 {
1494 	struct bpf_object *obj;
1495 	char *end;
1496 
1497 	obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
1498 	if (!obj) {
1499 		pr_warn("alloc memory failed for %s\n", path);
1500 		return ERR_PTR(-ENOMEM);
1501 	}
1502 
1503 	strcpy(obj->path, path);
1504 	if (obj_name) {
1505 		libbpf_strlcpy(obj->name, obj_name, sizeof(obj->name));
1506 	} else {
1507 		/* Using basename() GNU version which doesn't modify arg. */
1508 		libbpf_strlcpy(obj->name, basename((void *)path), sizeof(obj->name));
1509 		end = strchr(obj->name, '.');
1510 		if (end)
1511 			*end = 0;
1512 	}
1513 
1514 	obj->efile.fd = -1;
1515 	/*
1516 	 * Caller of this function should also call
1517 	 * bpf_object__elf_finish() after data collection to return
1518 	 * obj_buf to user. If not, we should duplicate the buffer to
1519 	 * avoid user freeing them before elf finish.
1520 	 */
1521 	obj->efile.obj_buf = obj_buf;
1522 	obj->efile.obj_buf_sz = obj_buf_sz;
1523 	obj->efile.btf_maps_shndx = -1;
1524 	obj->kconfig_map_idx = -1;
1525 	obj->arena_map_idx = -1;
1526 
1527 	obj->kern_version = get_kernel_version();
1528 	obj->state  = OBJ_OPEN;
1529 
1530 	return obj;
1531 }
1532 
1533 static void bpf_object__elf_finish(struct bpf_object *obj)
1534 {
1535 	if (!obj->efile.elf)
1536 		return;
1537 
1538 	elf_end(obj->efile.elf);
1539 	obj->efile.elf = NULL;
1540 	obj->efile.ehdr = NULL;
1541 	obj->efile.symbols = NULL;
1542 	obj->efile.arena_data = NULL;
1543 
1544 	zfree(&obj->efile.secs);
1545 	obj->efile.sec_cnt = 0;
1546 	zclose(obj->efile.fd);
1547 	obj->efile.obj_buf = NULL;
1548 	obj->efile.obj_buf_sz = 0;
1549 }
1550 
1551 static int bpf_object__elf_init(struct bpf_object *obj)
1552 {
1553 	Elf64_Ehdr *ehdr;
1554 	int err = 0;
1555 	Elf *elf;
1556 
1557 	if (obj->efile.elf) {
1558 		pr_warn("elf: init internal error\n");
1559 		return -LIBBPF_ERRNO__LIBELF;
1560 	}
1561 
1562 	if (obj->efile.obj_buf_sz > 0) {
1563 		/* obj_buf should have been validated by bpf_object__open_mem(). */
1564 		elf = elf_memory((char *)obj->efile.obj_buf, obj->efile.obj_buf_sz);
1565 	} else {
1566 		obj->efile.fd = open(obj->path, O_RDONLY | O_CLOEXEC);
1567 		if (obj->efile.fd < 0) {
1568 			err = -errno;
1569 			pr_warn("elf: failed to open %s: %s\n", obj->path, errstr(err));
1570 			return err;
1571 		}
1572 
1573 		elf = elf_begin(obj->efile.fd, ELF_C_READ_MMAP, NULL);
1574 	}
1575 
1576 	if (!elf) {
1577 		pr_warn("elf: failed to open %s as ELF file: %s\n", obj->path, elf_errmsg(-1));
1578 		err = -LIBBPF_ERRNO__LIBELF;
1579 		goto errout;
1580 	}
1581 
1582 	obj->efile.elf = elf;
1583 
1584 	if (elf_kind(elf) != ELF_K_ELF) {
1585 		err = -LIBBPF_ERRNO__FORMAT;
1586 		pr_warn("elf: '%s' is not a proper ELF object\n", obj->path);
1587 		goto errout;
1588 	}
1589 
1590 	if (gelf_getclass(elf) != ELFCLASS64) {
1591 		err = -LIBBPF_ERRNO__FORMAT;
1592 		pr_warn("elf: '%s' is not a 64-bit ELF object\n", obj->path);
1593 		goto errout;
1594 	}
1595 
1596 	obj->efile.ehdr = ehdr = elf64_getehdr(elf);
1597 	if (!obj->efile.ehdr) {
1598 		pr_warn("elf: failed to get ELF header from %s: %s\n", obj->path, elf_errmsg(-1));
1599 		err = -LIBBPF_ERRNO__FORMAT;
1600 		goto errout;
1601 	}
1602 
1603 	/* Validate ELF object endianness... */
1604 	if (ehdr->e_ident[EI_DATA] != ELFDATA2LSB &&
1605 	    ehdr->e_ident[EI_DATA] != ELFDATA2MSB) {
1606 		err = -LIBBPF_ERRNO__ENDIAN;
1607 		pr_warn("elf: '%s' has unknown byte order\n", obj->path);
1608 		goto errout;
1609 	}
1610 	/* and save after bpf_object_open() frees ELF data */
1611 	obj->byteorder = ehdr->e_ident[EI_DATA];
1612 
1613 	if (elf_getshdrstrndx(elf, &obj->efile.shstrndx)) {
1614 		pr_warn("elf: failed to get section names section index for %s: %s\n",
1615 			obj->path, elf_errmsg(-1));
1616 		err = -LIBBPF_ERRNO__FORMAT;
1617 		goto errout;
1618 	}
1619 
1620 	/* ELF is corrupted/truncated, avoid calling elf_strptr. */
1621 	if (!elf_rawdata(elf_getscn(elf, obj->efile.shstrndx), NULL)) {
1622 		pr_warn("elf: failed to get section names strings from %s: %s\n",
1623 			obj->path, elf_errmsg(-1));
1624 		err = -LIBBPF_ERRNO__FORMAT;
1625 		goto errout;
1626 	}
1627 
1628 	/* Old LLVM set e_machine to EM_NONE */
1629 	if (ehdr->e_type != ET_REL || (ehdr->e_machine && ehdr->e_machine != EM_BPF)) {
1630 		pr_warn("elf: %s is not a valid eBPF object file\n", obj->path);
1631 		err = -LIBBPF_ERRNO__FORMAT;
1632 		goto errout;
1633 	}
1634 
1635 	return 0;
1636 errout:
1637 	bpf_object__elf_finish(obj);
1638 	return err;
1639 }
1640 
1641 static bool is_native_endianness(struct bpf_object *obj)
1642 {
1643 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1644 	return obj->byteorder == ELFDATA2LSB;
1645 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
1646 	return obj->byteorder == ELFDATA2MSB;
1647 #else
1648 # error "Unrecognized __BYTE_ORDER__"
1649 #endif
1650 }
1651 
1652 static int
1653 bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
1654 {
1655 	if (!data) {
1656 		pr_warn("invalid license section in %s\n", obj->path);
1657 		return -LIBBPF_ERRNO__FORMAT;
1658 	}
1659 	/* libbpf_strlcpy() only copies first N - 1 bytes, so size + 1 won't
1660 	 * go over allowed ELF data section buffer
1661 	 */
1662 	libbpf_strlcpy(obj->license, data, min(size + 1, sizeof(obj->license)));
1663 	pr_debug("license of %s is %s\n", obj->path, obj->license);
1664 	return 0;
1665 }
1666 
1667 static int
1668 bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
1669 {
1670 	__u32 kver;
1671 
1672 	if (!data || size != sizeof(kver)) {
1673 		pr_warn("invalid kver section in %s\n", obj->path);
1674 		return -LIBBPF_ERRNO__FORMAT;
1675 	}
1676 	memcpy(&kver, data, sizeof(kver));
1677 	obj->kern_version = kver;
1678 	pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
1679 	return 0;
1680 }
1681 
1682 static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
1683 {
1684 	if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
1685 	    type == BPF_MAP_TYPE_HASH_OF_MAPS)
1686 		return true;
1687 	return false;
1688 }
1689 
1690 static int find_elf_sec_sz(const struct bpf_object *obj, const char *name, __u32 *size)
1691 {
1692 	Elf_Data *data;
1693 	Elf_Scn *scn;
1694 
1695 	if (!name)
1696 		return -EINVAL;
1697 
1698 	scn = elf_sec_by_name(obj, name);
1699 	data = elf_sec_data(obj, scn);
1700 	if (data) {
1701 		*size = data->d_size;
1702 		return 0; /* found it */
1703 	}
1704 
1705 	return -ENOENT;
1706 }
1707 
1708 static Elf64_Sym *find_elf_var_sym(const struct bpf_object *obj, const char *name)
1709 {
1710 	Elf_Data *symbols = obj->efile.symbols;
1711 	const char *sname;
1712 	size_t si;
1713 
1714 	for (si = 0; si < symbols->d_size / sizeof(Elf64_Sym); si++) {
1715 		Elf64_Sym *sym = elf_sym_by_idx(obj, si);
1716 
1717 		if (ELF64_ST_TYPE(sym->st_info) != STT_OBJECT)
1718 			continue;
1719 
1720 		if (ELF64_ST_BIND(sym->st_info) != STB_GLOBAL &&
1721 		    ELF64_ST_BIND(sym->st_info) != STB_WEAK)
1722 			continue;
1723 
1724 		sname = elf_sym_str(obj, sym->st_name);
1725 		if (!sname) {
1726 			pr_warn("failed to get sym name string for var %s\n", name);
1727 			return ERR_PTR(-EIO);
1728 		}
1729 		if (strcmp(name, sname) == 0)
1730 			return sym;
1731 	}
1732 
1733 	return ERR_PTR(-ENOENT);
1734 }
1735 
1736 #ifndef MFD_CLOEXEC
1737 #define MFD_CLOEXEC 0x0001U
1738 #endif
1739 #ifndef MFD_NOEXEC_SEAL
1740 #define MFD_NOEXEC_SEAL 0x0008U
1741 #endif
1742 
1743 static int create_placeholder_fd(void)
1744 {
1745 	unsigned int flags = MFD_CLOEXEC | MFD_NOEXEC_SEAL;
1746 	const char *name = "libbpf-placeholder-fd";
1747 	int fd;
1748 
1749 	fd = ensure_good_fd(sys_memfd_create(name, flags));
1750 	if (fd >= 0)
1751 		return fd;
1752 	else if (errno != EINVAL)
1753 		return -errno;
1754 
1755 	/* Possibly running on kernel without MFD_NOEXEC_SEAL */
1756 	fd = ensure_good_fd(sys_memfd_create(name, flags & ~MFD_NOEXEC_SEAL));
1757 	if (fd < 0)
1758 		return -errno;
1759 	return fd;
1760 }
1761 
1762 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
1763 {
1764 	struct bpf_map *map;
1765 	int err;
1766 
1767 	err = libbpf_ensure_mem((void **)&obj->maps, &obj->maps_cap,
1768 				sizeof(*obj->maps), obj->nr_maps + 1);
1769 	if (err)
1770 		return ERR_PTR(err);
1771 
1772 	map = &obj->maps[obj->nr_maps++];
1773 	map->obj = obj;
1774 	/* Preallocate map FD without actually creating BPF map just yet.
1775 	 * These map FD "placeholders" will be reused later without changing
1776 	 * FD value when map is actually created in the kernel.
1777 	 *
1778 	 * This is useful to be able to perform BPF program relocations
1779 	 * without having to create BPF maps before that step. This allows us
1780 	 * to finalize and load BTF very late in BPF object's loading phase,
1781 	 * right before BPF maps have to be created and BPF programs have to
1782 	 * be loaded. By having these map FD placeholders we can perform all
1783 	 * the sanitizations, relocations, and any other adjustments before we
1784 	 * start creating actual BPF kernel objects (BTF, maps, progs).
1785 	 */
1786 	map->fd = create_placeholder_fd();
1787 	if (map->fd < 0)
1788 		return ERR_PTR(map->fd);
1789 	map->inner_map_fd = -1;
1790 	map->autocreate = true;
1791 
1792 	return map;
1793 }
1794 
1795 static size_t array_map_mmap_sz(unsigned int value_sz, unsigned int max_entries)
1796 {
1797 	const long page_sz = sysconf(_SC_PAGE_SIZE);
1798 	size_t map_sz;
1799 
1800 	map_sz = (size_t)roundup(value_sz, 8) * max_entries;
1801 	map_sz = roundup(map_sz, page_sz);
1802 	return map_sz;
1803 }
1804 
1805 static size_t bpf_map_mmap_sz(const struct bpf_map *map)
1806 {
1807 	const long page_sz = sysconf(_SC_PAGE_SIZE);
1808 
1809 	switch (map->def.type) {
1810 	case BPF_MAP_TYPE_ARRAY:
1811 		return array_map_mmap_sz(map->def.value_size, map->def.max_entries);
1812 	case BPF_MAP_TYPE_ARENA:
1813 		return page_sz * map->def.max_entries;
1814 	default:
1815 		return 0; /* not supported */
1816 	}
1817 }
1818 
1819 static int bpf_map_mmap_resize(struct bpf_map *map, size_t old_sz, size_t new_sz)
1820 {
1821 	void *mmaped;
1822 
1823 	if (!map->mmaped)
1824 		return -EINVAL;
1825 
1826 	if (old_sz == new_sz)
1827 		return 0;
1828 
1829 	mmaped = mmap(NULL, new_sz, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1830 	if (mmaped == MAP_FAILED)
1831 		return -errno;
1832 
1833 	memcpy(mmaped, map->mmaped, min(old_sz, new_sz));
1834 	munmap(map->mmaped, old_sz);
1835 	map->mmaped = mmaped;
1836 	return 0;
1837 }
1838 
1839 static char *internal_map_name(struct bpf_object *obj, const char *real_name)
1840 {
1841 	char map_name[BPF_OBJ_NAME_LEN], *p;
1842 	int pfx_len, sfx_len = max((size_t)7, strlen(real_name));
1843 
1844 	/* This is one of the more confusing parts of libbpf for various
1845 	 * reasons, some of which are historical. The original idea for naming
1846 	 * internal names was to include as much of BPF object name prefix as
1847 	 * possible, so that it can be distinguished from similar internal
1848 	 * maps of a different BPF object.
1849 	 * As an example, let's say we have bpf_object named 'my_object_name'
1850 	 * and internal map corresponding to '.rodata' ELF section. The final
1851 	 * map name advertised to user and to the kernel will be
1852 	 * 'my_objec.rodata', taking first 8 characters of object name and
1853 	 * entire 7 characters of '.rodata'.
1854 	 * Somewhat confusingly, if internal map ELF section name is shorter
1855 	 * than 7 characters, e.g., '.bss', we still reserve 7 characters
1856 	 * for the suffix, even though we only have 4 actual characters, and
1857 	 * resulting map will be called 'my_objec.bss', not even using all 15
1858 	 * characters allowed by the kernel. Oh well, at least the truncated
1859 	 * object name is somewhat consistent in this case. But if the map
1860 	 * name is '.kconfig', we'll still have entirety of '.kconfig' added
1861 	 * (8 chars) and thus will be left with only first 7 characters of the
1862 	 * object name ('my_obje'). Happy guessing, user, that the final map
1863 	 * name will be "my_obje.kconfig".
1864 	 * Now, with libbpf starting to support arbitrarily named .rodata.*
1865 	 * and .data.* data sections, it's possible that ELF section name is
1866 	 * longer than allowed 15 chars, so we now need to be careful to take
1867 	 * only up to 15 first characters of ELF name, taking no BPF object
1868 	 * name characters at all. So '.rodata.abracadabra' will result in
1869 	 * '.rodata.abracad' kernel and user-visible name.
1870 	 * We need to keep this convoluted logic intact for .data, .bss and
1871 	 * .rodata maps, but for new custom .data.custom and .rodata.custom
1872 	 * maps we use their ELF names as is, not prepending bpf_object name
1873 	 * in front. We still need to truncate them to 15 characters for the
1874 	 * kernel. Full name can be recovered for such maps by using DATASEC
1875 	 * BTF type associated with such map's value type, though.
1876 	 */
1877 	if (sfx_len >= BPF_OBJ_NAME_LEN)
1878 		sfx_len = BPF_OBJ_NAME_LEN - 1;
1879 
1880 	/* if there are two or more dots in map name, it's a custom dot map */
1881 	if (strchr(real_name + 1, '.') != NULL)
1882 		pfx_len = 0;
1883 	else
1884 		pfx_len = min((size_t)BPF_OBJ_NAME_LEN - sfx_len - 1, strlen(obj->name));
1885 
1886 	snprintf(map_name, sizeof(map_name), "%.*s%.*s", pfx_len, obj->name,
1887 		 sfx_len, real_name);
1888 
1889 	/* sanities map name to characters allowed by kernel */
1890 	for (p = map_name; *p && p < map_name + sizeof(map_name); p++)
1891 		if (!isalnum(*p) && *p != '_' && *p != '.')
1892 			*p = '_';
1893 
1894 	return strdup(map_name);
1895 }
1896 
1897 static int
1898 map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map);
1899 
1900 /* Internal BPF map is mmap()'able only if at least one of corresponding
1901  * DATASEC's VARs are to be exposed through BPF skeleton. I.e., it's a GLOBAL
1902  * variable and it's not marked as __hidden (which turns it into, effectively,
1903  * a STATIC variable).
1904  */
1905 static bool map_is_mmapable(struct bpf_object *obj, struct bpf_map *map)
1906 {
1907 	const struct btf_type *t, *vt;
1908 	struct btf_var_secinfo *vsi;
1909 	int i, n;
1910 
1911 	if (!map->btf_value_type_id)
1912 		return false;
1913 
1914 	t = btf__type_by_id(obj->btf, map->btf_value_type_id);
1915 	if (!btf_is_datasec(t))
1916 		return false;
1917 
1918 	vsi = btf_var_secinfos(t);
1919 	for (i = 0, n = btf_vlen(t); i < n; i++, vsi++) {
1920 		vt = btf__type_by_id(obj->btf, vsi->type);
1921 		if (!btf_is_var(vt))
1922 			continue;
1923 
1924 		if (btf_var(vt)->linkage != BTF_VAR_STATIC)
1925 			return true;
1926 	}
1927 
1928 	return false;
1929 }
1930 
1931 static int
1932 bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
1933 			      const char *real_name, int sec_idx, void *data, size_t data_sz)
1934 {
1935 	struct bpf_map_def *def;
1936 	struct bpf_map *map;
1937 	size_t mmap_sz;
1938 	int err;
1939 
1940 	map = bpf_object__add_map(obj);
1941 	if (IS_ERR(map))
1942 		return PTR_ERR(map);
1943 
1944 	map->libbpf_type = type;
1945 	map->sec_idx = sec_idx;
1946 	map->sec_offset = 0;
1947 	map->real_name = strdup(real_name);
1948 	map->name = internal_map_name(obj, real_name);
1949 	if (!map->real_name || !map->name) {
1950 		zfree(&map->real_name);
1951 		zfree(&map->name);
1952 		return -ENOMEM;
1953 	}
1954 
1955 	def = &map->def;
1956 	def->type = BPF_MAP_TYPE_ARRAY;
1957 	def->key_size = sizeof(int);
1958 	def->value_size = data_sz;
1959 	def->max_entries = 1;
1960 	def->map_flags = type == LIBBPF_MAP_RODATA || type == LIBBPF_MAP_KCONFIG
1961 		? BPF_F_RDONLY_PROG : 0;
1962 
1963 	/* failures are fine because of maps like .rodata.str1.1 */
1964 	(void) map_fill_btf_type_info(obj, map);
1965 
1966 	if (map_is_mmapable(obj, map))
1967 		def->map_flags |= BPF_F_MMAPABLE;
1968 
1969 	pr_debug("map '%s' (global data): at sec_idx %d, offset %zu, flags %x.\n",
1970 		 map->name, map->sec_idx, map->sec_offset, def->map_flags);
1971 
1972 	mmap_sz = bpf_map_mmap_sz(map);
1973 	map->mmaped = mmap(NULL, mmap_sz, PROT_READ | PROT_WRITE,
1974 			   MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1975 	if (map->mmaped == MAP_FAILED) {
1976 		err = -errno;
1977 		map->mmaped = NULL;
1978 		pr_warn("failed to alloc map '%s' content buffer: %s\n", map->name, errstr(err));
1979 		zfree(&map->real_name);
1980 		zfree(&map->name);
1981 		return err;
1982 	}
1983 
1984 	if (data)
1985 		memcpy(map->mmaped, data, data_sz);
1986 
1987 	pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
1988 	return 0;
1989 }
1990 
1991 static int bpf_object__init_global_data_maps(struct bpf_object *obj)
1992 {
1993 	struct elf_sec_desc *sec_desc;
1994 	const char *sec_name;
1995 	int err = 0, sec_idx;
1996 
1997 	/*
1998 	 * Populate obj->maps with libbpf internal maps.
1999 	 */
2000 	for (sec_idx = 1; sec_idx < obj->efile.sec_cnt; sec_idx++) {
2001 		sec_desc = &obj->efile.secs[sec_idx];
2002 
2003 		/* Skip recognized sections with size 0. */
2004 		if (!sec_desc->data || sec_desc->data->d_size == 0)
2005 			continue;
2006 
2007 		switch (sec_desc->sec_type) {
2008 		case SEC_DATA:
2009 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
2010 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
2011 							    sec_name, sec_idx,
2012 							    sec_desc->data->d_buf,
2013 							    sec_desc->data->d_size);
2014 			break;
2015 		case SEC_RODATA:
2016 			obj->has_rodata = true;
2017 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
2018 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
2019 							    sec_name, sec_idx,
2020 							    sec_desc->data->d_buf,
2021 							    sec_desc->data->d_size);
2022 			break;
2023 		case SEC_BSS:
2024 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
2025 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
2026 							    sec_name, sec_idx,
2027 							    NULL,
2028 							    sec_desc->data->d_size);
2029 			break;
2030 		default:
2031 			/* skip */
2032 			break;
2033 		}
2034 		if (err)
2035 			return err;
2036 	}
2037 	return 0;
2038 }
2039 
2040 
2041 static struct extern_desc *find_extern_by_name(const struct bpf_object *obj,
2042 					       const void *name)
2043 {
2044 	int i;
2045 
2046 	for (i = 0; i < obj->nr_extern; i++) {
2047 		if (strcmp(obj->externs[i].name, name) == 0)
2048 			return &obj->externs[i];
2049 	}
2050 	return NULL;
2051 }
2052 
2053 static struct extern_desc *find_extern_by_name_with_len(const struct bpf_object *obj,
2054 							const void *name, int len)
2055 {
2056 	const char *ext_name;
2057 	int i;
2058 
2059 	for (i = 0; i < obj->nr_extern; i++) {
2060 		ext_name = obj->externs[i].name;
2061 		if (strlen(ext_name) == len && strncmp(ext_name, name, len) == 0)
2062 			return &obj->externs[i];
2063 	}
2064 	return NULL;
2065 }
2066 
2067 static int set_kcfg_value_tri(struct extern_desc *ext, void *ext_val,
2068 			      char value)
2069 {
2070 	switch (ext->kcfg.type) {
2071 	case KCFG_BOOL:
2072 		if (value == 'm') {
2073 			pr_warn("extern (kcfg) '%s': value '%c' implies tristate or char type\n",
2074 				ext->name, value);
2075 			return -EINVAL;
2076 		}
2077 		*(bool *)ext_val = value == 'y' ? true : false;
2078 		break;
2079 	case KCFG_TRISTATE:
2080 		if (value == 'y')
2081 			*(enum libbpf_tristate *)ext_val = TRI_YES;
2082 		else if (value == 'm')
2083 			*(enum libbpf_tristate *)ext_val = TRI_MODULE;
2084 		else /* value == 'n' */
2085 			*(enum libbpf_tristate *)ext_val = TRI_NO;
2086 		break;
2087 	case KCFG_CHAR:
2088 		*(char *)ext_val = value;
2089 		break;
2090 	case KCFG_UNKNOWN:
2091 	case KCFG_INT:
2092 	case KCFG_CHAR_ARR:
2093 	default:
2094 		pr_warn("extern (kcfg) '%s': value '%c' implies bool, tristate, or char type\n",
2095 			ext->name, value);
2096 		return -EINVAL;
2097 	}
2098 	ext->is_set = true;
2099 	return 0;
2100 }
2101 
2102 static int set_kcfg_value_str(struct extern_desc *ext, char *ext_val,
2103 			      const char *value)
2104 {
2105 	size_t len;
2106 
2107 	if (ext->kcfg.type != KCFG_CHAR_ARR) {
2108 		pr_warn("extern (kcfg) '%s': value '%s' implies char array type\n",
2109 			ext->name, value);
2110 		return -EINVAL;
2111 	}
2112 
2113 	len = strlen(value);
2114 	if (len < 2 || value[len - 1] != '"') {
2115 		pr_warn("extern (kcfg) '%s': invalid string config '%s'\n",
2116 			ext->name, value);
2117 		return -EINVAL;
2118 	}
2119 
2120 	/* strip quotes */
2121 	len -= 2;
2122 	if (len >= ext->kcfg.sz) {
2123 		pr_warn("extern (kcfg) '%s': long string '%s' of (%zu bytes) truncated to %d bytes\n",
2124 			ext->name, value, len, ext->kcfg.sz - 1);
2125 		len = ext->kcfg.sz - 1;
2126 	}
2127 	memcpy(ext_val, value + 1, len);
2128 	ext_val[len] = '\0';
2129 	ext->is_set = true;
2130 	return 0;
2131 }
2132 
2133 static int parse_u64(const char *value, __u64 *res)
2134 {
2135 	char *value_end;
2136 	int err;
2137 
2138 	errno = 0;
2139 	*res = strtoull(value, &value_end, 0);
2140 	if (errno) {
2141 		err = -errno;
2142 		pr_warn("failed to parse '%s': %s\n", value, errstr(err));
2143 		return err;
2144 	}
2145 	if (*value_end) {
2146 		pr_warn("failed to parse '%s' as integer completely\n", value);
2147 		return -EINVAL;
2148 	}
2149 	return 0;
2150 }
2151 
2152 static bool is_kcfg_value_in_range(const struct extern_desc *ext, __u64 v)
2153 {
2154 	int bit_sz = ext->kcfg.sz * 8;
2155 
2156 	if (ext->kcfg.sz == 8)
2157 		return true;
2158 
2159 	/* Validate that value stored in u64 fits in integer of `ext->sz`
2160 	 * bytes size without any loss of information. If the target integer
2161 	 * is signed, we rely on the following limits of integer type of
2162 	 * Y bits and subsequent transformation:
2163 	 *
2164 	 *     -2^(Y-1) <= X           <= 2^(Y-1) - 1
2165 	 *            0 <= X + 2^(Y-1) <= 2^Y - 1
2166 	 *            0 <= X + 2^(Y-1) <  2^Y
2167 	 *
2168 	 *  For unsigned target integer, check that all the (64 - Y) bits are
2169 	 *  zero.
2170 	 */
2171 	if (ext->kcfg.is_signed)
2172 		return v + (1ULL << (bit_sz - 1)) < (1ULL << bit_sz);
2173 	else
2174 		return (v >> bit_sz) == 0;
2175 }
2176 
2177 static int set_kcfg_value_num(struct extern_desc *ext, void *ext_val,
2178 			      __u64 value)
2179 {
2180 	if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR &&
2181 	    ext->kcfg.type != KCFG_BOOL) {
2182 		pr_warn("extern (kcfg) '%s': value '%llu' implies integer, char, or boolean type\n",
2183 			ext->name, (unsigned long long)value);
2184 		return -EINVAL;
2185 	}
2186 	if (ext->kcfg.type == KCFG_BOOL && value > 1) {
2187 		pr_warn("extern (kcfg) '%s': value '%llu' isn't boolean compatible\n",
2188 			ext->name, (unsigned long long)value);
2189 		return -EINVAL;
2190 
2191 	}
2192 	if (!is_kcfg_value_in_range(ext, value)) {
2193 		pr_warn("extern (kcfg) '%s': value '%llu' doesn't fit in %d bytes\n",
2194 			ext->name, (unsigned long long)value, ext->kcfg.sz);
2195 		return -ERANGE;
2196 	}
2197 	switch (ext->kcfg.sz) {
2198 	case 1:
2199 		*(__u8 *)ext_val = value;
2200 		break;
2201 	case 2:
2202 		*(__u16 *)ext_val = value;
2203 		break;
2204 	case 4:
2205 		*(__u32 *)ext_val = value;
2206 		break;
2207 	case 8:
2208 		*(__u64 *)ext_val = value;
2209 		break;
2210 	default:
2211 		return -EINVAL;
2212 	}
2213 	ext->is_set = true;
2214 	return 0;
2215 }
2216 
2217 static int bpf_object__process_kconfig_line(struct bpf_object *obj,
2218 					    char *buf, void *data)
2219 {
2220 	struct extern_desc *ext;
2221 	char *sep, *value;
2222 	int len, err = 0;
2223 	void *ext_val;
2224 	__u64 num;
2225 
2226 	if (!str_has_pfx(buf, "CONFIG_"))
2227 		return 0;
2228 
2229 	sep = strchr(buf, '=');
2230 	if (!sep) {
2231 		pr_warn("failed to parse '%s': no separator\n", buf);
2232 		return -EINVAL;
2233 	}
2234 
2235 	/* Trim ending '\n' */
2236 	len = strlen(buf);
2237 	if (buf[len - 1] == '\n')
2238 		buf[len - 1] = '\0';
2239 	/* Split on '=' and ensure that a value is present. */
2240 	*sep = '\0';
2241 	if (!sep[1]) {
2242 		*sep = '=';
2243 		pr_warn("failed to parse '%s': no value\n", buf);
2244 		return -EINVAL;
2245 	}
2246 
2247 	ext = find_extern_by_name(obj, buf);
2248 	if (!ext || ext->is_set)
2249 		return 0;
2250 
2251 	ext_val = data + ext->kcfg.data_off;
2252 	value = sep + 1;
2253 
2254 	switch (*value) {
2255 	case 'y': case 'n': case 'm':
2256 		err = set_kcfg_value_tri(ext, ext_val, *value);
2257 		break;
2258 	case '"':
2259 		err = set_kcfg_value_str(ext, ext_val, value);
2260 		break;
2261 	default:
2262 		/* assume integer */
2263 		err = parse_u64(value, &num);
2264 		if (err) {
2265 			pr_warn("extern (kcfg) '%s': value '%s' isn't a valid integer\n", ext->name, value);
2266 			return err;
2267 		}
2268 		if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR) {
2269 			pr_warn("extern (kcfg) '%s': value '%s' implies integer type\n", ext->name, value);
2270 			return -EINVAL;
2271 		}
2272 		err = set_kcfg_value_num(ext, ext_val, num);
2273 		break;
2274 	}
2275 	if (err)
2276 		return err;
2277 	pr_debug("extern (kcfg) '%s': set to %s\n", ext->name, value);
2278 	return 0;
2279 }
2280 
2281 static int bpf_object__read_kconfig_file(struct bpf_object *obj, void *data)
2282 {
2283 	char buf[PATH_MAX];
2284 	struct utsname uts;
2285 	int len, err = 0;
2286 	gzFile file;
2287 
2288 	uname(&uts);
2289 	len = snprintf(buf, PATH_MAX, "/boot/config-%s", uts.release);
2290 	if (len < 0)
2291 		return -EINVAL;
2292 	else if (len >= PATH_MAX)
2293 		return -ENAMETOOLONG;
2294 
2295 	/* gzopen also accepts uncompressed files. */
2296 	file = gzopen(buf, "re");
2297 	if (!file)
2298 		file = gzopen("/proc/config.gz", "re");
2299 
2300 	if (!file) {
2301 		pr_warn("failed to open system Kconfig\n");
2302 		return -ENOENT;
2303 	}
2304 
2305 	while (gzgets(file, buf, sizeof(buf))) {
2306 		err = bpf_object__process_kconfig_line(obj, buf, data);
2307 		if (err) {
2308 			pr_warn("error parsing system Kconfig line '%s': %s\n",
2309 				buf, errstr(err));
2310 			goto out;
2311 		}
2312 	}
2313 
2314 out:
2315 	gzclose(file);
2316 	return err;
2317 }
2318 
2319 static int bpf_object__read_kconfig_mem(struct bpf_object *obj,
2320 					const char *config, void *data)
2321 {
2322 	char buf[PATH_MAX];
2323 	int err = 0;
2324 	FILE *file;
2325 
2326 	file = fmemopen((void *)config, strlen(config), "r");
2327 	if (!file) {
2328 		err = -errno;
2329 		pr_warn("failed to open in-memory Kconfig: %s\n", errstr(err));
2330 		return err;
2331 	}
2332 
2333 	while (fgets(buf, sizeof(buf), file)) {
2334 		err = bpf_object__process_kconfig_line(obj, buf, data);
2335 		if (err) {
2336 			pr_warn("error parsing in-memory Kconfig line '%s': %s\n",
2337 				buf, errstr(err));
2338 			break;
2339 		}
2340 	}
2341 
2342 	fclose(file);
2343 	return err;
2344 }
2345 
2346 static int bpf_object__init_kconfig_map(struct bpf_object *obj)
2347 {
2348 	struct extern_desc *last_ext = NULL, *ext;
2349 	size_t map_sz;
2350 	int i, err;
2351 
2352 	for (i = 0; i < obj->nr_extern; i++) {
2353 		ext = &obj->externs[i];
2354 		if (ext->type == EXT_KCFG)
2355 			last_ext = ext;
2356 	}
2357 
2358 	if (!last_ext)
2359 		return 0;
2360 
2361 	map_sz = last_ext->kcfg.data_off + last_ext->kcfg.sz;
2362 	err = bpf_object__init_internal_map(obj, LIBBPF_MAP_KCONFIG,
2363 					    ".kconfig", obj->efile.symbols_shndx,
2364 					    NULL, map_sz);
2365 	if (err)
2366 		return err;
2367 
2368 	obj->kconfig_map_idx = obj->nr_maps - 1;
2369 
2370 	return 0;
2371 }
2372 
2373 const struct btf_type *
2374 skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id)
2375 {
2376 	const struct btf_type *t = btf__type_by_id(btf, id);
2377 
2378 	if (res_id)
2379 		*res_id = id;
2380 
2381 	while (btf_is_mod(t) || btf_is_typedef(t)) {
2382 		if (res_id)
2383 			*res_id = t->type;
2384 		t = btf__type_by_id(btf, t->type);
2385 	}
2386 
2387 	return t;
2388 }
2389 
2390 static const struct btf_type *
2391 resolve_func_ptr(const struct btf *btf, __u32 id, __u32 *res_id)
2392 {
2393 	const struct btf_type *t;
2394 
2395 	t = skip_mods_and_typedefs(btf, id, NULL);
2396 	if (!btf_is_ptr(t))
2397 		return NULL;
2398 
2399 	t = skip_mods_and_typedefs(btf, t->type, res_id);
2400 
2401 	return btf_is_func_proto(t) ? t : NULL;
2402 }
2403 
2404 static const char *__btf_kind_str(__u16 kind)
2405 {
2406 	switch (kind) {
2407 	case BTF_KIND_UNKN: return "void";
2408 	case BTF_KIND_INT: return "int";
2409 	case BTF_KIND_PTR: return "ptr";
2410 	case BTF_KIND_ARRAY: return "array";
2411 	case BTF_KIND_STRUCT: return "struct";
2412 	case BTF_KIND_UNION: return "union";
2413 	case BTF_KIND_ENUM: return "enum";
2414 	case BTF_KIND_FWD: return "fwd";
2415 	case BTF_KIND_TYPEDEF: return "typedef";
2416 	case BTF_KIND_VOLATILE: return "volatile";
2417 	case BTF_KIND_CONST: return "const";
2418 	case BTF_KIND_RESTRICT: return "restrict";
2419 	case BTF_KIND_FUNC: return "func";
2420 	case BTF_KIND_FUNC_PROTO: return "func_proto";
2421 	case BTF_KIND_VAR: return "var";
2422 	case BTF_KIND_DATASEC: return "datasec";
2423 	case BTF_KIND_FLOAT: return "float";
2424 	case BTF_KIND_DECL_TAG: return "decl_tag";
2425 	case BTF_KIND_TYPE_TAG: return "type_tag";
2426 	case BTF_KIND_ENUM64: return "enum64";
2427 	default: return "unknown";
2428 	}
2429 }
2430 
2431 const char *btf_kind_str(const struct btf_type *t)
2432 {
2433 	return __btf_kind_str(btf_kind(t));
2434 }
2435 
2436 /*
2437  * Fetch integer attribute of BTF map definition. Such attributes are
2438  * represented using a pointer to an array, in which dimensionality of array
2439  * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
2440  * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
2441  * type definition, while using only sizeof(void *) space in ELF data section.
2442  */
2443 static bool get_map_field_int(const char *map_name, const struct btf *btf,
2444 			      const struct btf_member *m, __u32 *res)
2445 {
2446 	const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
2447 	const char *name = btf__name_by_offset(btf, m->name_off);
2448 	const struct btf_array *arr_info;
2449 	const struct btf_type *arr_t;
2450 
2451 	if (!btf_is_ptr(t)) {
2452 		pr_warn("map '%s': attr '%s': expected PTR, got %s.\n",
2453 			map_name, name, btf_kind_str(t));
2454 		return false;
2455 	}
2456 
2457 	arr_t = btf__type_by_id(btf, t->type);
2458 	if (!arr_t) {
2459 		pr_warn("map '%s': attr '%s': type [%u] not found.\n",
2460 			map_name, name, t->type);
2461 		return false;
2462 	}
2463 	if (!btf_is_array(arr_t)) {
2464 		pr_warn("map '%s': attr '%s': expected ARRAY, got %s.\n",
2465 			map_name, name, btf_kind_str(arr_t));
2466 		return false;
2467 	}
2468 	arr_info = btf_array(arr_t);
2469 	*res = arr_info->nelems;
2470 	return true;
2471 }
2472 
2473 static bool get_map_field_long(const char *map_name, const struct btf *btf,
2474 			       const struct btf_member *m, __u64 *res)
2475 {
2476 	const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
2477 	const char *name = btf__name_by_offset(btf, m->name_off);
2478 
2479 	if (btf_is_ptr(t)) {
2480 		__u32 res32;
2481 		bool ret;
2482 
2483 		ret = get_map_field_int(map_name, btf, m, &res32);
2484 		if (ret)
2485 			*res = (__u64)res32;
2486 		return ret;
2487 	}
2488 
2489 	if (!btf_is_enum(t) && !btf_is_enum64(t)) {
2490 		pr_warn("map '%s': attr '%s': expected ENUM or ENUM64, got %s.\n",
2491 			map_name, name, btf_kind_str(t));
2492 		return false;
2493 	}
2494 
2495 	if (btf_vlen(t) != 1) {
2496 		pr_warn("map '%s': attr '%s': invalid __ulong\n",
2497 			map_name, name);
2498 		return false;
2499 	}
2500 
2501 	if (btf_is_enum(t)) {
2502 		const struct btf_enum *e = btf_enum(t);
2503 
2504 		*res = e->val;
2505 	} else {
2506 		const struct btf_enum64 *e = btf_enum64(t);
2507 
2508 		*res = btf_enum64_value(e);
2509 	}
2510 	return true;
2511 }
2512 
2513 static int pathname_concat(char *buf, size_t buf_sz, const char *path, const char *name)
2514 {
2515 	int len;
2516 
2517 	len = snprintf(buf, buf_sz, "%s/%s", path, name);
2518 	if (len < 0)
2519 		return -EINVAL;
2520 	if (len >= buf_sz)
2521 		return -ENAMETOOLONG;
2522 
2523 	return 0;
2524 }
2525 
2526 static int build_map_pin_path(struct bpf_map *map, const char *path)
2527 {
2528 	char buf[PATH_MAX];
2529 	int err;
2530 
2531 	if (!path)
2532 		path = BPF_FS_DEFAULT_PATH;
2533 
2534 	err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
2535 	if (err)
2536 		return err;
2537 
2538 	return bpf_map__set_pin_path(map, buf);
2539 }
2540 
2541 /* should match definition in bpf_helpers.h */
2542 enum libbpf_pin_type {
2543 	LIBBPF_PIN_NONE,
2544 	/* PIN_BY_NAME: pin maps by name (in /sys/fs/bpf by default) */
2545 	LIBBPF_PIN_BY_NAME,
2546 };
2547 
2548 int parse_btf_map_def(const char *map_name, struct btf *btf,
2549 		      const struct btf_type *def_t, bool strict,
2550 		      struct btf_map_def *map_def, struct btf_map_def *inner_def)
2551 {
2552 	const struct btf_type *t;
2553 	const struct btf_member *m;
2554 	bool is_inner = inner_def == NULL;
2555 	int vlen, i;
2556 
2557 	vlen = btf_vlen(def_t);
2558 	m = btf_members(def_t);
2559 	for (i = 0; i < vlen; i++, m++) {
2560 		const char *name = btf__name_by_offset(btf, m->name_off);
2561 
2562 		if (!name) {
2563 			pr_warn("map '%s': invalid field #%d.\n", map_name, i);
2564 			return -EINVAL;
2565 		}
2566 		if (strcmp(name, "type") == 0) {
2567 			if (!get_map_field_int(map_name, btf, m, &map_def->map_type))
2568 				return -EINVAL;
2569 			map_def->parts |= MAP_DEF_MAP_TYPE;
2570 		} else if (strcmp(name, "max_entries") == 0) {
2571 			if (!get_map_field_int(map_name, btf, m, &map_def->max_entries))
2572 				return -EINVAL;
2573 			map_def->parts |= MAP_DEF_MAX_ENTRIES;
2574 		} else if (strcmp(name, "map_flags") == 0) {
2575 			if (!get_map_field_int(map_name, btf, m, &map_def->map_flags))
2576 				return -EINVAL;
2577 			map_def->parts |= MAP_DEF_MAP_FLAGS;
2578 		} else if (strcmp(name, "numa_node") == 0) {
2579 			if (!get_map_field_int(map_name, btf, m, &map_def->numa_node))
2580 				return -EINVAL;
2581 			map_def->parts |= MAP_DEF_NUMA_NODE;
2582 		} else if (strcmp(name, "key_size") == 0) {
2583 			__u32 sz;
2584 
2585 			if (!get_map_field_int(map_name, btf, m, &sz))
2586 				return -EINVAL;
2587 			if (map_def->key_size && map_def->key_size != sz) {
2588 				pr_warn("map '%s': conflicting key size %u != %u.\n",
2589 					map_name, map_def->key_size, sz);
2590 				return -EINVAL;
2591 			}
2592 			map_def->key_size = sz;
2593 			map_def->parts |= MAP_DEF_KEY_SIZE;
2594 		} else if (strcmp(name, "key") == 0) {
2595 			__s64 sz;
2596 
2597 			t = btf__type_by_id(btf, m->type);
2598 			if (!t) {
2599 				pr_warn("map '%s': key type [%d] not found.\n",
2600 					map_name, m->type);
2601 				return -EINVAL;
2602 			}
2603 			if (!btf_is_ptr(t)) {
2604 				pr_warn("map '%s': key spec is not PTR: %s.\n",
2605 					map_name, btf_kind_str(t));
2606 				return -EINVAL;
2607 			}
2608 			sz = btf__resolve_size(btf, t->type);
2609 			if (sz < 0) {
2610 				pr_warn("map '%s': can't determine key size for type [%u]: %zd.\n",
2611 					map_name, t->type, (ssize_t)sz);
2612 				return sz;
2613 			}
2614 			if (map_def->key_size && map_def->key_size != sz) {
2615 				pr_warn("map '%s': conflicting key size %u != %zd.\n",
2616 					map_name, map_def->key_size, (ssize_t)sz);
2617 				return -EINVAL;
2618 			}
2619 			map_def->key_size = sz;
2620 			map_def->key_type_id = t->type;
2621 			map_def->parts |= MAP_DEF_KEY_SIZE | MAP_DEF_KEY_TYPE;
2622 		} else if (strcmp(name, "value_size") == 0) {
2623 			__u32 sz;
2624 
2625 			if (!get_map_field_int(map_name, btf, m, &sz))
2626 				return -EINVAL;
2627 			if (map_def->value_size && map_def->value_size != sz) {
2628 				pr_warn("map '%s': conflicting value size %u != %u.\n",
2629 					map_name, map_def->value_size, sz);
2630 				return -EINVAL;
2631 			}
2632 			map_def->value_size = sz;
2633 			map_def->parts |= MAP_DEF_VALUE_SIZE;
2634 		} else if (strcmp(name, "value") == 0) {
2635 			__s64 sz;
2636 
2637 			t = btf__type_by_id(btf, m->type);
2638 			if (!t) {
2639 				pr_warn("map '%s': value type [%d] not found.\n",
2640 					map_name, m->type);
2641 				return -EINVAL;
2642 			}
2643 			if (!btf_is_ptr(t)) {
2644 				pr_warn("map '%s': value spec is not PTR: %s.\n",
2645 					map_name, btf_kind_str(t));
2646 				return -EINVAL;
2647 			}
2648 			sz = btf__resolve_size(btf, t->type);
2649 			if (sz < 0) {
2650 				pr_warn("map '%s': can't determine value size for type [%u]: %zd.\n",
2651 					map_name, t->type, (ssize_t)sz);
2652 				return sz;
2653 			}
2654 			if (map_def->value_size && map_def->value_size != sz) {
2655 				pr_warn("map '%s': conflicting value size %u != %zd.\n",
2656 					map_name, map_def->value_size, (ssize_t)sz);
2657 				return -EINVAL;
2658 			}
2659 			map_def->value_size = sz;
2660 			map_def->value_type_id = t->type;
2661 			map_def->parts |= MAP_DEF_VALUE_SIZE | MAP_DEF_VALUE_TYPE;
2662 		}
2663 		else if (strcmp(name, "values") == 0) {
2664 			bool is_map_in_map = bpf_map_type__is_map_in_map(map_def->map_type);
2665 			bool is_prog_array = map_def->map_type == BPF_MAP_TYPE_PROG_ARRAY;
2666 			const char *desc = is_map_in_map ? "map-in-map inner" : "prog-array value";
2667 			char inner_map_name[128];
2668 			int err;
2669 
2670 			if (is_inner) {
2671 				pr_warn("map '%s': multi-level inner maps not supported.\n",
2672 					map_name);
2673 				return -ENOTSUP;
2674 			}
2675 			if (i != vlen - 1) {
2676 				pr_warn("map '%s': '%s' member should be last.\n",
2677 					map_name, name);
2678 				return -EINVAL;
2679 			}
2680 			if (!is_map_in_map && !is_prog_array) {
2681 				pr_warn("map '%s': should be map-in-map or prog-array.\n",
2682 					map_name);
2683 				return -ENOTSUP;
2684 			}
2685 			if (map_def->value_size && map_def->value_size != 4) {
2686 				pr_warn("map '%s': conflicting value size %u != 4.\n",
2687 					map_name, map_def->value_size);
2688 				return -EINVAL;
2689 			}
2690 			map_def->value_size = 4;
2691 			t = btf__type_by_id(btf, m->type);
2692 			if (!t) {
2693 				pr_warn("map '%s': %s type [%d] not found.\n",
2694 					map_name, desc, m->type);
2695 				return -EINVAL;
2696 			}
2697 			if (!btf_is_array(t) || btf_array(t)->nelems) {
2698 				pr_warn("map '%s': %s spec is not a zero-sized array.\n",
2699 					map_name, desc);
2700 				return -EINVAL;
2701 			}
2702 			t = skip_mods_and_typedefs(btf, btf_array(t)->type, NULL);
2703 			if (!btf_is_ptr(t)) {
2704 				pr_warn("map '%s': %s def is of unexpected kind %s.\n",
2705 					map_name, desc, btf_kind_str(t));
2706 				return -EINVAL;
2707 			}
2708 			t = skip_mods_and_typedefs(btf, t->type, NULL);
2709 			if (is_prog_array) {
2710 				if (!btf_is_func_proto(t)) {
2711 					pr_warn("map '%s': prog-array value def is of unexpected kind %s.\n",
2712 						map_name, btf_kind_str(t));
2713 					return -EINVAL;
2714 				}
2715 				continue;
2716 			}
2717 			if (!btf_is_struct(t)) {
2718 				pr_warn("map '%s': map-in-map inner def is of unexpected kind %s.\n",
2719 					map_name, btf_kind_str(t));
2720 				return -EINVAL;
2721 			}
2722 
2723 			snprintf(inner_map_name, sizeof(inner_map_name), "%s.inner", map_name);
2724 			err = parse_btf_map_def(inner_map_name, btf, t, strict, inner_def, NULL);
2725 			if (err)
2726 				return err;
2727 
2728 			map_def->parts |= MAP_DEF_INNER_MAP;
2729 		} else if (strcmp(name, "pinning") == 0) {
2730 			__u32 val;
2731 
2732 			if (is_inner) {
2733 				pr_warn("map '%s': inner def can't be pinned.\n", map_name);
2734 				return -EINVAL;
2735 			}
2736 			if (!get_map_field_int(map_name, btf, m, &val))
2737 				return -EINVAL;
2738 			if (val != LIBBPF_PIN_NONE && val != LIBBPF_PIN_BY_NAME) {
2739 				pr_warn("map '%s': invalid pinning value %u.\n",
2740 					map_name, val);
2741 				return -EINVAL;
2742 			}
2743 			map_def->pinning = val;
2744 			map_def->parts |= MAP_DEF_PINNING;
2745 		} else if (strcmp(name, "map_extra") == 0) {
2746 			__u64 map_extra;
2747 
2748 			if (!get_map_field_long(map_name, btf, m, &map_extra))
2749 				return -EINVAL;
2750 			map_def->map_extra = map_extra;
2751 			map_def->parts |= MAP_DEF_MAP_EXTRA;
2752 		} else {
2753 			if (strict) {
2754 				pr_warn("map '%s': unknown field '%s'.\n", map_name, name);
2755 				return -ENOTSUP;
2756 			}
2757 			pr_debug("map '%s': ignoring unknown field '%s'.\n", map_name, name);
2758 		}
2759 	}
2760 
2761 	if (map_def->map_type == BPF_MAP_TYPE_UNSPEC) {
2762 		pr_warn("map '%s': map type isn't specified.\n", map_name);
2763 		return -EINVAL;
2764 	}
2765 
2766 	return 0;
2767 }
2768 
2769 static size_t adjust_ringbuf_sz(size_t sz)
2770 {
2771 	__u32 page_sz = sysconf(_SC_PAGE_SIZE);
2772 	__u32 mul;
2773 
2774 	/* if user forgot to set any size, make sure they see error */
2775 	if (sz == 0)
2776 		return 0;
2777 	/* Kernel expects BPF_MAP_TYPE_RINGBUF's max_entries to be
2778 	 * a power-of-2 multiple of kernel's page size. If user diligently
2779 	 * satisified these conditions, pass the size through.
2780 	 */
2781 	if ((sz % page_sz) == 0 && is_pow_of_2(sz / page_sz))
2782 		return sz;
2783 
2784 	/* Otherwise find closest (page_sz * power_of_2) product bigger than
2785 	 * user-set size to satisfy both user size request and kernel
2786 	 * requirements and substitute correct max_entries for map creation.
2787 	 */
2788 	for (mul = 1; mul <= UINT_MAX / page_sz; mul <<= 1) {
2789 		if (mul * page_sz > sz)
2790 			return mul * page_sz;
2791 	}
2792 
2793 	/* if it's impossible to satisfy the conditions (i.e., user size is
2794 	 * very close to UINT_MAX but is not a power-of-2 multiple of
2795 	 * page_size) then just return original size and let kernel reject it
2796 	 */
2797 	return sz;
2798 }
2799 
2800 static bool map_is_ringbuf(const struct bpf_map *map)
2801 {
2802 	return map->def.type == BPF_MAP_TYPE_RINGBUF ||
2803 	       map->def.type == BPF_MAP_TYPE_USER_RINGBUF;
2804 }
2805 
2806 static void fill_map_from_def(struct bpf_map *map, const struct btf_map_def *def)
2807 {
2808 	map->def.type = def->map_type;
2809 	map->def.key_size = def->key_size;
2810 	map->def.value_size = def->value_size;
2811 	map->def.max_entries = def->max_entries;
2812 	map->def.map_flags = def->map_flags;
2813 	map->map_extra = def->map_extra;
2814 
2815 	map->numa_node = def->numa_node;
2816 	map->btf_key_type_id = def->key_type_id;
2817 	map->btf_value_type_id = def->value_type_id;
2818 
2819 	/* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
2820 	if (map_is_ringbuf(map))
2821 		map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
2822 
2823 	if (def->parts & MAP_DEF_MAP_TYPE)
2824 		pr_debug("map '%s': found type = %u.\n", map->name, def->map_type);
2825 
2826 	if (def->parts & MAP_DEF_KEY_TYPE)
2827 		pr_debug("map '%s': found key [%u], sz = %u.\n",
2828 			 map->name, def->key_type_id, def->key_size);
2829 	else if (def->parts & MAP_DEF_KEY_SIZE)
2830 		pr_debug("map '%s': found key_size = %u.\n", map->name, def->key_size);
2831 
2832 	if (def->parts & MAP_DEF_VALUE_TYPE)
2833 		pr_debug("map '%s': found value [%u], sz = %u.\n",
2834 			 map->name, def->value_type_id, def->value_size);
2835 	else if (def->parts & MAP_DEF_VALUE_SIZE)
2836 		pr_debug("map '%s': found value_size = %u.\n", map->name, def->value_size);
2837 
2838 	if (def->parts & MAP_DEF_MAX_ENTRIES)
2839 		pr_debug("map '%s': found max_entries = %u.\n", map->name, def->max_entries);
2840 	if (def->parts & MAP_DEF_MAP_FLAGS)
2841 		pr_debug("map '%s': found map_flags = 0x%x.\n", map->name, def->map_flags);
2842 	if (def->parts & MAP_DEF_MAP_EXTRA)
2843 		pr_debug("map '%s': found map_extra = 0x%llx.\n", map->name,
2844 			 (unsigned long long)def->map_extra);
2845 	if (def->parts & MAP_DEF_PINNING)
2846 		pr_debug("map '%s': found pinning = %u.\n", map->name, def->pinning);
2847 	if (def->parts & MAP_DEF_NUMA_NODE)
2848 		pr_debug("map '%s': found numa_node = %u.\n", map->name, def->numa_node);
2849 
2850 	if (def->parts & MAP_DEF_INNER_MAP)
2851 		pr_debug("map '%s': found inner map definition.\n", map->name);
2852 }
2853 
2854 static const char *btf_var_linkage_str(__u32 linkage)
2855 {
2856 	switch (linkage) {
2857 	case BTF_VAR_STATIC: return "static";
2858 	case BTF_VAR_GLOBAL_ALLOCATED: return "global";
2859 	case BTF_VAR_GLOBAL_EXTERN: return "extern";
2860 	default: return "unknown";
2861 	}
2862 }
2863 
2864 static int bpf_object__init_user_btf_map(struct bpf_object *obj,
2865 					 const struct btf_type *sec,
2866 					 int var_idx, int sec_idx,
2867 					 const Elf_Data *data, bool strict,
2868 					 const char *pin_root_path)
2869 {
2870 	struct btf_map_def map_def = {}, inner_def = {};
2871 	const struct btf_type *var, *def;
2872 	const struct btf_var_secinfo *vi;
2873 	const struct btf_var *var_extra;
2874 	const char *map_name;
2875 	struct bpf_map *map;
2876 	int err;
2877 
2878 	vi = btf_var_secinfos(sec) + var_idx;
2879 	var = btf__type_by_id(obj->btf, vi->type);
2880 	var_extra = btf_var(var);
2881 	map_name = btf__name_by_offset(obj->btf, var->name_off);
2882 
2883 	if (map_name == NULL || map_name[0] == '\0') {
2884 		pr_warn("map #%d: empty name.\n", var_idx);
2885 		return -EINVAL;
2886 	}
2887 	if ((__u64)vi->offset + vi->size > data->d_size) {
2888 		pr_warn("map '%s' BTF data is corrupted.\n", map_name);
2889 		return -EINVAL;
2890 	}
2891 	if (!btf_is_var(var)) {
2892 		pr_warn("map '%s': unexpected var kind %s.\n",
2893 			map_name, btf_kind_str(var));
2894 		return -EINVAL;
2895 	}
2896 	if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED) {
2897 		pr_warn("map '%s': unsupported map linkage %s.\n",
2898 			map_name, btf_var_linkage_str(var_extra->linkage));
2899 		return -EOPNOTSUPP;
2900 	}
2901 
2902 	def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
2903 	if (!btf_is_struct(def)) {
2904 		pr_warn("map '%s': unexpected def kind %s.\n",
2905 			map_name, btf_kind_str(var));
2906 		return -EINVAL;
2907 	}
2908 	if (def->size > vi->size) {
2909 		pr_warn("map '%s': invalid def size.\n", map_name);
2910 		return -EINVAL;
2911 	}
2912 
2913 	map = bpf_object__add_map(obj);
2914 	if (IS_ERR(map))
2915 		return PTR_ERR(map);
2916 	map->name = strdup(map_name);
2917 	if (!map->name) {
2918 		pr_warn("map '%s': failed to alloc map name.\n", map_name);
2919 		return -ENOMEM;
2920 	}
2921 	map->libbpf_type = LIBBPF_MAP_UNSPEC;
2922 	map->def.type = BPF_MAP_TYPE_UNSPEC;
2923 	map->sec_idx = sec_idx;
2924 	map->sec_offset = vi->offset;
2925 	map->btf_var_idx = var_idx;
2926 	pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
2927 		 map_name, map->sec_idx, map->sec_offset);
2928 
2929 	err = parse_btf_map_def(map->name, obj->btf, def, strict, &map_def, &inner_def);
2930 	if (err)
2931 		return err;
2932 
2933 	fill_map_from_def(map, &map_def);
2934 
2935 	if (map_def.pinning == LIBBPF_PIN_BY_NAME) {
2936 		err = build_map_pin_path(map, pin_root_path);
2937 		if (err) {
2938 			pr_warn("map '%s': couldn't build pin path.\n", map->name);
2939 			return err;
2940 		}
2941 	}
2942 
2943 	if (map_def.parts & MAP_DEF_INNER_MAP) {
2944 		map->inner_map = calloc(1, sizeof(*map->inner_map));
2945 		if (!map->inner_map)
2946 			return -ENOMEM;
2947 		map->inner_map->fd = create_placeholder_fd();
2948 		if (map->inner_map->fd < 0)
2949 			return map->inner_map->fd;
2950 		map->inner_map->sec_idx = sec_idx;
2951 		map->inner_map->name = malloc(strlen(map_name) + sizeof(".inner") + 1);
2952 		if (!map->inner_map->name)
2953 			return -ENOMEM;
2954 		sprintf(map->inner_map->name, "%s.inner", map_name);
2955 
2956 		fill_map_from_def(map->inner_map, &inner_def);
2957 	}
2958 
2959 	err = map_fill_btf_type_info(obj, map);
2960 	if (err)
2961 		return err;
2962 
2963 	return 0;
2964 }
2965 
2966 static int init_arena_map_data(struct bpf_object *obj, struct bpf_map *map,
2967 			       const char *sec_name, int sec_idx,
2968 			       void *data, size_t data_sz)
2969 {
2970 	const long page_sz = sysconf(_SC_PAGE_SIZE);
2971 	size_t mmap_sz;
2972 
2973 	mmap_sz = bpf_map_mmap_sz(map);
2974 	if (roundup(data_sz, page_sz) > mmap_sz) {
2975 		pr_warn("elf: sec '%s': declared ARENA map size (%zu) is too small to hold global __arena variables of size %zu\n",
2976 			sec_name, mmap_sz, data_sz);
2977 		return -E2BIG;
2978 	}
2979 
2980 	obj->arena_data = malloc(data_sz);
2981 	if (!obj->arena_data)
2982 		return -ENOMEM;
2983 	memcpy(obj->arena_data, data, data_sz);
2984 	obj->arena_data_sz = data_sz;
2985 
2986 	/* make bpf_map__init_value() work for ARENA maps */
2987 	map->mmaped = obj->arena_data;
2988 
2989 	return 0;
2990 }
2991 
2992 static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict,
2993 					  const char *pin_root_path)
2994 {
2995 	const struct btf_type *sec = NULL;
2996 	int nr_types, i, vlen, err;
2997 	const struct btf_type *t;
2998 	const char *name;
2999 	Elf_Data *data;
3000 	Elf_Scn *scn;
3001 
3002 	if (obj->efile.btf_maps_shndx < 0)
3003 		return 0;
3004 
3005 	scn = elf_sec_by_idx(obj, obj->efile.btf_maps_shndx);
3006 	data = elf_sec_data(obj, scn);
3007 	if (!scn || !data) {
3008 		pr_warn("elf: failed to get %s map definitions for %s\n",
3009 			MAPS_ELF_SEC, obj->path);
3010 		return -EINVAL;
3011 	}
3012 
3013 	nr_types = btf__type_cnt(obj->btf);
3014 	for (i = 1; i < nr_types; i++) {
3015 		t = btf__type_by_id(obj->btf, i);
3016 		if (!btf_is_datasec(t))
3017 			continue;
3018 		name = btf__name_by_offset(obj->btf, t->name_off);
3019 		if (strcmp(name, MAPS_ELF_SEC) == 0) {
3020 			sec = t;
3021 			obj->efile.btf_maps_sec_btf_id = i;
3022 			break;
3023 		}
3024 	}
3025 
3026 	if (!sec) {
3027 		pr_warn("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
3028 		return -ENOENT;
3029 	}
3030 
3031 	vlen = btf_vlen(sec);
3032 	for (i = 0; i < vlen; i++) {
3033 		err = bpf_object__init_user_btf_map(obj, sec, i,
3034 						    obj->efile.btf_maps_shndx,
3035 						    data, strict,
3036 						    pin_root_path);
3037 		if (err)
3038 			return err;
3039 	}
3040 
3041 	for (i = 0; i < obj->nr_maps; i++) {
3042 		struct bpf_map *map = &obj->maps[i];
3043 
3044 		if (map->def.type != BPF_MAP_TYPE_ARENA)
3045 			continue;
3046 
3047 		if (obj->arena_map_idx >= 0) {
3048 			pr_warn("map '%s': only single ARENA map is supported (map '%s' is also ARENA)\n",
3049 				map->name, obj->maps[obj->arena_map_idx].name);
3050 			return -EINVAL;
3051 		}
3052 		obj->arena_map_idx = i;
3053 
3054 		if (obj->efile.arena_data) {
3055 			err = init_arena_map_data(obj, map, ARENA_SEC, obj->efile.arena_data_shndx,
3056 						  obj->efile.arena_data->d_buf,
3057 						  obj->efile.arena_data->d_size);
3058 			if (err)
3059 				return err;
3060 		}
3061 	}
3062 	if (obj->efile.arena_data && obj->arena_map_idx < 0) {
3063 		pr_warn("elf: sec '%s': to use global __arena variables the ARENA map should be explicitly declared in SEC(\".maps\")\n",
3064 			ARENA_SEC);
3065 		return -ENOENT;
3066 	}
3067 
3068 	return 0;
3069 }
3070 
3071 static int bpf_object__init_maps(struct bpf_object *obj,
3072 				 const struct bpf_object_open_opts *opts)
3073 {
3074 	const char *pin_root_path;
3075 	bool strict;
3076 	int err = 0;
3077 
3078 	strict = !OPTS_GET(opts, relaxed_maps, false);
3079 	pin_root_path = OPTS_GET(opts, pin_root_path, NULL);
3080 
3081 	err = bpf_object__init_user_btf_maps(obj, strict, pin_root_path);
3082 	err = err ?: bpf_object__init_global_data_maps(obj);
3083 	err = err ?: bpf_object__init_kconfig_map(obj);
3084 	err = err ?: bpf_object_init_struct_ops(obj);
3085 
3086 	return err;
3087 }
3088 
3089 static bool section_have_execinstr(struct bpf_object *obj, int idx)
3090 {
3091 	Elf64_Shdr *sh;
3092 
3093 	sh = elf_sec_hdr(obj, elf_sec_by_idx(obj, idx));
3094 	if (!sh)
3095 		return false;
3096 
3097 	return sh->sh_flags & SHF_EXECINSTR;
3098 }
3099 
3100 static bool starts_with_qmark(const char *s)
3101 {
3102 	return s && s[0] == '?';
3103 }
3104 
3105 static bool btf_needs_sanitization(struct bpf_object *obj)
3106 {
3107 	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
3108 	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
3109 	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
3110 	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
3111 	bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
3112 	bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
3113 	bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
3114 	bool has_qmark_datasec = kernel_supports(obj, FEAT_BTF_QMARK_DATASEC);
3115 
3116 	return !has_func || !has_datasec || !has_func_global || !has_float ||
3117 	       !has_decl_tag || !has_type_tag || !has_enum64 || !has_qmark_datasec;
3118 }
3119 
3120 static int bpf_object__sanitize_btf(struct bpf_object *obj, struct btf *btf)
3121 {
3122 	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
3123 	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
3124 	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
3125 	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
3126 	bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
3127 	bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
3128 	bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
3129 	bool has_qmark_datasec = kernel_supports(obj, FEAT_BTF_QMARK_DATASEC);
3130 	int enum64_placeholder_id = 0;
3131 	struct btf_type *t;
3132 	int i, j, vlen;
3133 
3134 	for (i = 1; i < btf__type_cnt(btf); i++) {
3135 		t = (struct btf_type *)btf__type_by_id(btf, i);
3136 
3137 		if ((!has_datasec && btf_is_var(t)) || (!has_decl_tag && btf_is_decl_tag(t))) {
3138 			/* replace VAR/DECL_TAG with INT */
3139 			t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
3140 			/*
3141 			 * using size = 1 is the safest choice, 4 will be too
3142 			 * big and cause kernel BTF validation failure if
3143 			 * original variable took less than 4 bytes
3144 			 */
3145 			t->size = 1;
3146 			*(int *)(t + 1) = BTF_INT_ENC(0, 0, 8);
3147 		} else if (!has_datasec && btf_is_datasec(t)) {
3148 			/* replace DATASEC with STRUCT */
3149 			const struct btf_var_secinfo *v = btf_var_secinfos(t);
3150 			struct btf_member *m = btf_members(t);
3151 			struct btf_type *vt;
3152 			char *name;
3153 
3154 			name = (char *)btf__name_by_offset(btf, t->name_off);
3155 			while (*name) {
3156 				if (*name == '.' || *name == '?')
3157 					*name = '_';
3158 				name++;
3159 			}
3160 
3161 			vlen = btf_vlen(t);
3162 			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
3163 			for (j = 0; j < vlen; j++, v++, m++) {
3164 				/* order of field assignments is important */
3165 				m->offset = v->offset * 8;
3166 				m->type = v->type;
3167 				/* preserve variable name as member name */
3168 				vt = (void *)btf__type_by_id(btf, v->type);
3169 				m->name_off = vt->name_off;
3170 			}
3171 		} else if (!has_qmark_datasec && btf_is_datasec(t) &&
3172 			   starts_with_qmark(btf__name_by_offset(btf, t->name_off))) {
3173 			/* replace '?' prefix with '_' for DATASEC names */
3174 			char *name;
3175 
3176 			name = (char *)btf__name_by_offset(btf, t->name_off);
3177 			if (name[0] == '?')
3178 				name[0] = '_';
3179 		} else if (!has_func && btf_is_func_proto(t)) {
3180 			/* replace FUNC_PROTO with ENUM */
3181 			vlen = btf_vlen(t);
3182 			t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
3183 			t->size = sizeof(__u32); /* kernel enforced */
3184 		} else if (!has_func && btf_is_func(t)) {
3185 			/* replace FUNC with TYPEDEF */
3186 			t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
3187 		} else if (!has_func_global && btf_is_func(t)) {
3188 			/* replace BTF_FUNC_GLOBAL with BTF_FUNC_STATIC */
3189 			t->info = BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0);
3190 		} else if (!has_float && btf_is_float(t)) {
3191 			/* replace FLOAT with an equally-sized empty STRUCT;
3192 			 * since C compilers do not accept e.g. "float" as a
3193 			 * valid struct name, make it anonymous
3194 			 */
3195 			t->name_off = 0;
3196 			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, 0);
3197 		} else if (!has_type_tag && btf_is_type_tag(t)) {
3198 			/* replace TYPE_TAG with a CONST */
3199 			t->name_off = 0;
3200 			t->info = BTF_INFO_ENC(BTF_KIND_CONST, 0, 0);
3201 		} else if (!has_enum64 && btf_is_enum(t)) {
3202 			/* clear the kflag */
3203 			t->info = btf_type_info(btf_kind(t), btf_vlen(t), false);
3204 		} else if (!has_enum64 && btf_is_enum64(t)) {
3205 			/* replace ENUM64 with a union */
3206 			struct btf_member *m;
3207 
3208 			if (enum64_placeholder_id == 0) {
3209 				enum64_placeholder_id = btf__add_int(btf, "enum64_placeholder", 1, 0);
3210 				if (enum64_placeholder_id < 0)
3211 					return enum64_placeholder_id;
3212 
3213 				t = (struct btf_type *)btf__type_by_id(btf, i);
3214 			}
3215 
3216 			m = btf_members(t);
3217 			vlen = btf_vlen(t);
3218 			t->info = BTF_INFO_ENC(BTF_KIND_UNION, 0, vlen);
3219 			for (j = 0; j < vlen; j++, m++) {
3220 				m->type = enum64_placeholder_id;
3221 				m->offset = 0;
3222 			}
3223 		}
3224 	}
3225 
3226 	return 0;
3227 }
3228 
3229 static bool libbpf_needs_btf(const struct bpf_object *obj)
3230 {
3231 	return obj->efile.btf_maps_shndx >= 0 ||
3232 	       obj->efile.has_st_ops ||
3233 	       obj->nr_extern > 0;
3234 }
3235 
3236 static bool kernel_needs_btf(const struct bpf_object *obj)
3237 {
3238 	return obj->efile.has_st_ops;
3239 }
3240 
3241 static int bpf_object__init_btf(struct bpf_object *obj,
3242 				Elf_Data *btf_data,
3243 				Elf_Data *btf_ext_data)
3244 {
3245 	int err = -ENOENT;
3246 
3247 	if (btf_data) {
3248 		obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
3249 		err = libbpf_get_error(obj->btf);
3250 		if (err) {
3251 			obj->btf = NULL;
3252 			pr_warn("Error loading ELF section %s: %s.\n", BTF_ELF_SEC, errstr(err));
3253 			goto out;
3254 		}
3255 		/* enforce 8-byte pointers for BPF-targeted BTFs */
3256 		btf__set_pointer_size(obj->btf, 8);
3257 	}
3258 	if (btf_ext_data) {
3259 		struct btf_ext_info *ext_segs[3];
3260 		int seg_num, sec_num;
3261 
3262 		if (!obj->btf) {
3263 			pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
3264 				 BTF_EXT_ELF_SEC, BTF_ELF_SEC);
3265 			goto out;
3266 		}
3267 		obj->btf_ext = btf_ext__new(btf_ext_data->d_buf, btf_ext_data->d_size);
3268 		err = libbpf_get_error(obj->btf_ext);
3269 		if (err) {
3270 			pr_warn("Error loading ELF section %s: %s. Ignored and continue.\n",
3271 				BTF_EXT_ELF_SEC, errstr(err));
3272 			obj->btf_ext = NULL;
3273 			goto out;
3274 		}
3275 
3276 		/* setup .BTF.ext to ELF section mapping */
3277 		ext_segs[0] = &obj->btf_ext->func_info;
3278 		ext_segs[1] = &obj->btf_ext->line_info;
3279 		ext_segs[2] = &obj->btf_ext->core_relo_info;
3280 		for (seg_num = 0; seg_num < ARRAY_SIZE(ext_segs); seg_num++) {
3281 			struct btf_ext_info *seg = ext_segs[seg_num];
3282 			const struct btf_ext_info_sec *sec;
3283 			const char *sec_name;
3284 			Elf_Scn *scn;
3285 
3286 			if (seg->sec_cnt == 0)
3287 				continue;
3288 
3289 			seg->sec_idxs = calloc(seg->sec_cnt, sizeof(*seg->sec_idxs));
3290 			if (!seg->sec_idxs) {
3291 				err = -ENOMEM;
3292 				goto out;
3293 			}
3294 
3295 			sec_num = 0;
3296 			for_each_btf_ext_sec(seg, sec) {
3297 				/* preventively increment index to avoid doing
3298 				 * this before every continue below
3299 				 */
3300 				sec_num++;
3301 
3302 				sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
3303 				if (str_is_empty(sec_name))
3304 					continue;
3305 				scn = elf_sec_by_name(obj, sec_name);
3306 				if (!scn)
3307 					continue;
3308 
3309 				seg->sec_idxs[sec_num - 1] = elf_ndxscn(scn);
3310 			}
3311 		}
3312 	}
3313 out:
3314 	if (err && libbpf_needs_btf(obj)) {
3315 		pr_warn("BTF is required, but is missing or corrupted.\n");
3316 		return err;
3317 	}
3318 	return 0;
3319 }
3320 
3321 static int compare_vsi_off(const void *_a, const void *_b)
3322 {
3323 	const struct btf_var_secinfo *a = _a;
3324 	const struct btf_var_secinfo *b = _b;
3325 
3326 	return a->offset - b->offset;
3327 }
3328 
3329 static int btf_fixup_datasec(struct bpf_object *obj, struct btf *btf,
3330 			     struct btf_type *t)
3331 {
3332 	__u32 size = 0, i, vars = btf_vlen(t);
3333 	const char *sec_name = btf__name_by_offset(btf, t->name_off);
3334 	struct btf_var_secinfo *vsi;
3335 	bool fixup_offsets = false;
3336 	int err;
3337 
3338 	if (!sec_name) {
3339 		pr_debug("No name found in string section for DATASEC kind.\n");
3340 		return -ENOENT;
3341 	}
3342 
3343 	/* Extern-backing datasecs (.ksyms, .kconfig) have their size and
3344 	 * variable offsets set at the previous step. Further, not every
3345 	 * extern BTF VAR has corresponding ELF symbol preserved, so we skip
3346 	 * all fixups altogether for such sections and go straight to sorting
3347 	 * VARs within their DATASEC.
3348 	 */
3349 	if (strcmp(sec_name, KCONFIG_SEC) == 0 || strcmp(sec_name, KSYMS_SEC) == 0)
3350 		goto sort_vars;
3351 
3352 	/* Clang leaves DATASEC size and VAR offsets as zeroes, so we need to
3353 	 * fix this up. But BPF static linker already fixes this up and fills
3354 	 * all the sizes and offsets during static linking. So this step has
3355 	 * to be optional. But the STV_HIDDEN handling is non-optional for any
3356 	 * non-extern DATASEC, so the variable fixup loop below handles both
3357 	 * functions at the same time, paying the cost of BTF VAR <-> ELF
3358 	 * symbol matching just once.
3359 	 */
3360 	if (t->size == 0) {
3361 		err = find_elf_sec_sz(obj, sec_name, &size);
3362 		if (err || !size) {
3363 			pr_debug("sec '%s': failed to determine size from ELF: size %u, err %s\n",
3364 				 sec_name, size, errstr(err));
3365 			return -ENOENT;
3366 		}
3367 
3368 		t->size = size;
3369 		fixup_offsets = true;
3370 	}
3371 
3372 	for (i = 0, vsi = btf_var_secinfos(t); i < vars; i++, vsi++) {
3373 		const struct btf_type *t_var;
3374 		struct btf_var *var;
3375 		const char *var_name;
3376 		Elf64_Sym *sym;
3377 
3378 		t_var = btf__type_by_id(btf, vsi->type);
3379 		if (!t_var || !btf_is_var(t_var)) {
3380 			pr_debug("sec '%s': unexpected non-VAR type found\n", sec_name);
3381 			return -EINVAL;
3382 		}
3383 
3384 		var = btf_var(t_var);
3385 		if (var->linkage == BTF_VAR_STATIC || var->linkage == BTF_VAR_GLOBAL_EXTERN)
3386 			continue;
3387 
3388 		var_name = btf__name_by_offset(btf, t_var->name_off);
3389 		if (!var_name) {
3390 			pr_debug("sec '%s': failed to find name of DATASEC's member #%d\n",
3391 				 sec_name, i);
3392 			return -ENOENT;
3393 		}
3394 
3395 		sym = find_elf_var_sym(obj, var_name);
3396 		if (IS_ERR(sym)) {
3397 			pr_debug("sec '%s': failed to find ELF symbol for VAR '%s'\n",
3398 				 sec_name, var_name);
3399 			return -ENOENT;
3400 		}
3401 
3402 		if (fixup_offsets)
3403 			vsi->offset = sym->st_value;
3404 
3405 		/* if variable is a global/weak symbol, but has restricted
3406 		 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF VAR
3407 		 * as static. This follows similar logic for functions (BPF
3408 		 * subprogs) and influences libbpf's further decisions about
3409 		 * whether to make global data BPF array maps as
3410 		 * BPF_F_MMAPABLE.
3411 		 */
3412 		if (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
3413 		    || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL)
3414 			var->linkage = BTF_VAR_STATIC;
3415 	}
3416 
3417 sort_vars:
3418 	qsort(btf_var_secinfos(t), vars, sizeof(*vsi), compare_vsi_off);
3419 	return 0;
3420 }
3421 
3422 static int bpf_object_fixup_btf(struct bpf_object *obj)
3423 {
3424 	int i, n, err = 0;
3425 
3426 	if (!obj->btf)
3427 		return 0;
3428 
3429 	n = btf__type_cnt(obj->btf);
3430 	for (i = 1; i < n; i++) {
3431 		struct btf_type *t = btf_type_by_id(obj->btf, i);
3432 
3433 		/* Loader needs to fix up some of the things compiler
3434 		 * couldn't get its hands on while emitting BTF. This
3435 		 * is section size and global variable offset. We use
3436 		 * the info from the ELF itself for this purpose.
3437 		 */
3438 		if (btf_is_datasec(t)) {
3439 			err = btf_fixup_datasec(obj, obj->btf, t);
3440 			if (err)
3441 				return err;
3442 		}
3443 	}
3444 
3445 	return 0;
3446 }
3447 
3448 static bool prog_needs_vmlinux_btf(struct bpf_program *prog)
3449 {
3450 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
3451 	    prog->type == BPF_PROG_TYPE_LSM)
3452 		return true;
3453 
3454 	/* BPF_PROG_TYPE_TRACING programs which do not attach to other programs
3455 	 * also need vmlinux BTF
3456 	 */
3457 	if (prog->type == BPF_PROG_TYPE_TRACING && !prog->attach_prog_fd)
3458 		return true;
3459 
3460 	return false;
3461 }
3462 
3463 static bool map_needs_vmlinux_btf(struct bpf_map *map)
3464 {
3465 	return bpf_map__is_struct_ops(map);
3466 }
3467 
3468 static bool obj_needs_vmlinux_btf(const struct bpf_object *obj)
3469 {
3470 	struct bpf_program *prog;
3471 	struct bpf_map *map;
3472 	int i;
3473 
3474 	/* CO-RE relocations need kernel BTF, only when btf_custom_path
3475 	 * is not specified
3476 	 */
3477 	if (obj->btf_ext && obj->btf_ext->core_relo_info.len && !obj->btf_custom_path)
3478 		return true;
3479 
3480 	/* Support for typed ksyms needs kernel BTF */
3481 	for (i = 0; i < obj->nr_extern; i++) {
3482 		const struct extern_desc *ext;
3483 
3484 		ext = &obj->externs[i];
3485 		if (ext->type == EXT_KSYM && ext->ksym.type_id)
3486 			return true;
3487 	}
3488 
3489 	bpf_object__for_each_program(prog, obj) {
3490 		if (!prog->autoload)
3491 			continue;
3492 		if (prog_needs_vmlinux_btf(prog))
3493 			return true;
3494 	}
3495 
3496 	bpf_object__for_each_map(map, obj) {
3497 		if (map_needs_vmlinux_btf(map))
3498 			return true;
3499 	}
3500 
3501 	return false;
3502 }
3503 
3504 static int bpf_object__load_vmlinux_btf(struct bpf_object *obj, bool force)
3505 {
3506 	int err;
3507 
3508 	/* btf_vmlinux could be loaded earlier */
3509 	if (obj->btf_vmlinux || obj->gen_loader)
3510 		return 0;
3511 
3512 	if (!force && !obj_needs_vmlinux_btf(obj))
3513 		return 0;
3514 
3515 	obj->btf_vmlinux = btf__load_vmlinux_btf();
3516 	err = libbpf_get_error(obj->btf_vmlinux);
3517 	if (err) {
3518 		pr_warn("Error loading vmlinux BTF: %s\n", errstr(err));
3519 		obj->btf_vmlinux = NULL;
3520 		return err;
3521 	}
3522 	return 0;
3523 }
3524 
3525 static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
3526 {
3527 	struct btf *kern_btf = obj->btf;
3528 	bool btf_mandatory, sanitize;
3529 	int i, err = 0;
3530 
3531 	if (!obj->btf)
3532 		return 0;
3533 
3534 	if (!kernel_supports(obj, FEAT_BTF)) {
3535 		if (kernel_needs_btf(obj)) {
3536 			err = -EOPNOTSUPP;
3537 			goto report;
3538 		}
3539 		pr_debug("Kernel doesn't support BTF, skipping uploading it.\n");
3540 		return 0;
3541 	}
3542 
3543 	/* Even though some subprogs are global/weak, user might prefer more
3544 	 * permissive BPF verification process that BPF verifier performs for
3545 	 * static functions, taking into account more context from the caller
3546 	 * functions. In such case, they need to mark such subprogs with
3547 	 * __attribute__((visibility("hidden"))) and libbpf will adjust
3548 	 * corresponding FUNC BTF type to be marked as static and trigger more
3549 	 * involved BPF verification process.
3550 	 */
3551 	for (i = 0; i < obj->nr_programs; i++) {
3552 		struct bpf_program *prog = &obj->programs[i];
3553 		struct btf_type *t;
3554 		const char *name;
3555 		int j, n;
3556 
3557 		if (!prog->mark_btf_static || !prog_is_subprog(obj, prog))
3558 			continue;
3559 
3560 		n = btf__type_cnt(obj->btf);
3561 		for (j = 1; j < n; j++) {
3562 			t = btf_type_by_id(obj->btf, j);
3563 			if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL)
3564 				continue;
3565 
3566 			name = btf__str_by_offset(obj->btf, t->name_off);
3567 			if (strcmp(name, prog->name) != 0)
3568 				continue;
3569 
3570 			t->info = btf_type_info(BTF_KIND_FUNC, BTF_FUNC_STATIC, 0);
3571 			break;
3572 		}
3573 	}
3574 
3575 	sanitize = btf_needs_sanitization(obj);
3576 	if (sanitize) {
3577 		const void *raw_data;
3578 		__u32 sz;
3579 
3580 		/* clone BTF to sanitize a copy and leave the original intact */
3581 		raw_data = btf__raw_data(obj->btf, &sz);
3582 		kern_btf = btf__new(raw_data, sz);
3583 		err = libbpf_get_error(kern_btf);
3584 		if (err)
3585 			return err;
3586 
3587 		/* enforce 8-byte pointers for BPF-targeted BTFs */
3588 		btf__set_pointer_size(obj->btf, 8);
3589 		err = bpf_object__sanitize_btf(obj, kern_btf);
3590 		if (err)
3591 			return err;
3592 	}
3593 
3594 	if (obj->gen_loader) {
3595 		__u32 raw_size = 0;
3596 		const void *raw_data = btf__raw_data(kern_btf, &raw_size);
3597 
3598 		if (!raw_data)
3599 			return -ENOMEM;
3600 		bpf_gen__load_btf(obj->gen_loader, raw_data, raw_size);
3601 		/* Pretend to have valid FD to pass various fd >= 0 checks.
3602 		 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
3603 		 */
3604 		btf__set_fd(kern_btf, 0);
3605 	} else {
3606 		/* currently BPF_BTF_LOAD only supports log_level 1 */
3607 		err = btf_load_into_kernel(kern_btf, obj->log_buf, obj->log_size,
3608 					   obj->log_level ? 1 : 0, obj->token_fd);
3609 	}
3610 	if (sanitize) {
3611 		if (!err) {
3612 			/* move fd to libbpf's BTF */
3613 			btf__set_fd(obj->btf, btf__fd(kern_btf));
3614 			btf__set_fd(kern_btf, -1);
3615 		}
3616 		btf__free(kern_btf);
3617 	}
3618 report:
3619 	if (err) {
3620 		btf_mandatory = kernel_needs_btf(obj);
3621 		if (btf_mandatory) {
3622 			pr_warn("Error loading .BTF into kernel: %s. BTF is mandatory, can't proceed.\n",
3623 				errstr(err));
3624 		} else {
3625 			pr_info("Error loading .BTF into kernel: %s. BTF is optional, ignoring.\n",
3626 				errstr(err));
3627 			err = 0;
3628 		}
3629 	}
3630 	return err;
3631 }
3632 
3633 static const char *elf_sym_str(const struct bpf_object *obj, size_t off)
3634 {
3635 	const char *name;
3636 
3637 	name = elf_strptr(obj->efile.elf, obj->efile.strtabidx, off);
3638 	if (!name) {
3639 		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3640 			off, obj->path, elf_errmsg(-1));
3641 		return NULL;
3642 	}
3643 
3644 	return name;
3645 }
3646 
3647 static const char *elf_sec_str(const struct bpf_object *obj, size_t off)
3648 {
3649 	const char *name;
3650 
3651 	name = elf_strptr(obj->efile.elf, obj->efile.shstrndx, off);
3652 	if (!name) {
3653 		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3654 			off, obj->path, elf_errmsg(-1));
3655 		return NULL;
3656 	}
3657 
3658 	return name;
3659 }
3660 
3661 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx)
3662 {
3663 	Elf_Scn *scn;
3664 
3665 	scn = elf_getscn(obj->efile.elf, idx);
3666 	if (!scn) {
3667 		pr_warn("elf: failed to get section(%zu) from %s: %s\n",
3668 			idx, obj->path, elf_errmsg(-1));
3669 		return NULL;
3670 	}
3671 	return scn;
3672 }
3673 
3674 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name)
3675 {
3676 	Elf_Scn *scn = NULL;
3677 	Elf *elf = obj->efile.elf;
3678 	const char *sec_name;
3679 
3680 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3681 		sec_name = elf_sec_name(obj, scn);
3682 		if (!sec_name)
3683 			return NULL;
3684 
3685 		if (strcmp(sec_name, name) != 0)
3686 			continue;
3687 
3688 		return scn;
3689 	}
3690 	return NULL;
3691 }
3692 
3693 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn)
3694 {
3695 	Elf64_Shdr *shdr;
3696 
3697 	if (!scn)
3698 		return NULL;
3699 
3700 	shdr = elf64_getshdr(scn);
3701 	if (!shdr) {
3702 		pr_warn("elf: failed to get section(%zu) header from %s: %s\n",
3703 			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3704 		return NULL;
3705 	}
3706 
3707 	return shdr;
3708 }
3709 
3710 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn)
3711 {
3712 	const char *name;
3713 	Elf64_Shdr *sh;
3714 
3715 	if (!scn)
3716 		return NULL;
3717 
3718 	sh = elf_sec_hdr(obj, scn);
3719 	if (!sh)
3720 		return NULL;
3721 
3722 	name = elf_sec_str(obj, sh->sh_name);
3723 	if (!name) {
3724 		pr_warn("elf: failed to get section(%zu) name from %s: %s\n",
3725 			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3726 		return NULL;
3727 	}
3728 
3729 	return name;
3730 }
3731 
3732 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn)
3733 {
3734 	Elf_Data *data;
3735 
3736 	if (!scn)
3737 		return NULL;
3738 
3739 	data = elf_getdata(scn, 0);
3740 	if (!data) {
3741 		pr_warn("elf: failed to get section(%zu) %s data from %s: %s\n",
3742 			elf_ndxscn(scn), elf_sec_name(obj, scn) ?: "<?>",
3743 			obj->path, elf_errmsg(-1));
3744 		return NULL;
3745 	}
3746 
3747 	return data;
3748 }
3749 
3750 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx)
3751 {
3752 	if (idx >= obj->efile.symbols->d_size / sizeof(Elf64_Sym))
3753 		return NULL;
3754 
3755 	return (Elf64_Sym *)obj->efile.symbols->d_buf + idx;
3756 }
3757 
3758 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx)
3759 {
3760 	if (idx >= data->d_size / sizeof(Elf64_Rel))
3761 		return NULL;
3762 
3763 	return (Elf64_Rel *)data->d_buf + idx;
3764 }
3765 
3766 static bool is_sec_name_dwarf(const char *name)
3767 {
3768 	/* approximation, but the actual list is too long */
3769 	return str_has_pfx(name, ".debug_");
3770 }
3771 
3772 static bool ignore_elf_section(Elf64_Shdr *hdr, const char *name)
3773 {
3774 	/* no special handling of .strtab */
3775 	if (hdr->sh_type == SHT_STRTAB)
3776 		return true;
3777 
3778 	/* ignore .llvm_addrsig section as well */
3779 	if (hdr->sh_type == SHT_LLVM_ADDRSIG)
3780 		return true;
3781 
3782 	/* no subprograms will lead to an empty .text section, ignore it */
3783 	if (hdr->sh_type == SHT_PROGBITS && hdr->sh_size == 0 &&
3784 	    strcmp(name, ".text") == 0)
3785 		return true;
3786 
3787 	/* DWARF sections */
3788 	if (is_sec_name_dwarf(name))
3789 		return true;
3790 
3791 	if (str_has_pfx(name, ".rel")) {
3792 		name += sizeof(".rel") - 1;
3793 		/* DWARF section relocations */
3794 		if (is_sec_name_dwarf(name))
3795 			return true;
3796 
3797 		/* .BTF and .BTF.ext don't need relocations */
3798 		if (strcmp(name, BTF_ELF_SEC) == 0 ||
3799 		    strcmp(name, BTF_EXT_ELF_SEC) == 0)
3800 			return true;
3801 	}
3802 
3803 	return false;
3804 }
3805 
3806 static int cmp_progs(const void *_a, const void *_b)
3807 {
3808 	const struct bpf_program *a = _a;
3809 	const struct bpf_program *b = _b;
3810 
3811 	if (a->sec_idx != b->sec_idx)
3812 		return a->sec_idx < b->sec_idx ? -1 : 1;
3813 
3814 	/* sec_insn_off can't be the same within the section */
3815 	return a->sec_insn_off < b->sec_insn_off ? -1 : 1;
3816 }
3817 
3818 static int bpf_object__elf_collect(struct bpf_object *obj)
3819 {
3820 	struct elf_sec_desc *sec_desc;
3821 	Elf *elf = obj->efile.elf;
3822 	Elf_Data *btf_ext_data = NULL;
3823 	Elf_Data *btf_data = NULL;
3824 	int idx = 0, err = 0;
3825 	const char *name;
3826 	Elf_Data *data;
3827 	Elf_Scn *scn;
3828 	Elf64_Shdr *sh;
3829 
3830 	/* ELF section indices are 0-based, but sec #0 is special "invalid"
3831 	 * section. Since section count retrieved by elf_getshdrnum() does
3832 	 * include sec #0, it is already the necessary size of an array to keep
3833 	 * all the sections.
3834 	 */
3835 	if (elf_getshdrnum(obj->efile.elf, &obj->efile.sec_cnt)) {
3836 		pr_warn("elf: failed to get the number of sections for %s: %s\n",
3837 			obj->path, elf_errmsg(-1));
3838 		return -LIBBPF_ERRNO__FORMAT;
3839 	}
3840 	obj->efile.secs = calloc(obj->efile.sec_cnt, sizeof(*obj->efile.secs));
3841 	if (!obj->efile.secs)
3842 		return -ENOMEM;
3843 
3844 	/* a bunch of ELF parsing functionality depends on processing symbols,
3845 	 * so do the first pass and find the symbol table
3846 	 */
3847 	scn = NULL;
3848 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3849 		sh = elf_sec_hdr(obj, scn);
3850 		if (!sh)
3851 			return -LIBBPF_ERRNO__FORMAT;
3852 
3853 		if (sh->sh_type == SHT_SYMTAB) {
3854 			if (obj->efile.symbols) {
3855 				pr_warn("elf: multiple symbol tables in %s\n", obj->path);
3856 				return -LIBBPF_ERRNO__FORMAT;
3857 			}
3858 
3859 			data = elf_sec_data(obj, scn);
3860 			if (!data)
3861 				return -LIBBPF_ERRNO__FORMAT;
3862 
3863 			idx = elf_ndxscn(scn);
3864 
3865 			obj->efile.symbols = data;
3866 			obj->efile.symbols_shndx = idx;
3867 			obj->efile.strtabidx = sh->sh_link;
3868 		}
3869 	}
3870 
3871 	if (!obj->efile.symbols) {
3872 		pr_warn("elf: couldn't find symbol table in %s, stripped object file?\n",
3873 			obj->path);
3874 		return -ENOENT;
3875 	}
3876 
3877 	scn = NULL;
3878 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3879 		idx = elf_ndxscn(scn);
3880 		sec_desc = &obj->efile.secs[idx];
3881 
3882 		sh = elf_sec_hdr(obj, scn);
3883 		if (!sh)
3884 			return -LIBBPF_ERRNO__FORMAT;
3885 
3886 		name = elf_sec_str(obj, sh->sh_name);
3887 		if (!name)
3888 			return -LIBBPF_ERRNO__FORMAT;
3889 
3890 		if (ignore_elf_section(sh, name))
3891 			continue;
3892 
3893 		data = elf_sec_data(obj, scn);
3894 		if (!data)
3895 			return -LIBBPF_ERRNO__FORMAT;
3896 
3897 		pr_debug("elf: section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
3898 			 idx, name, (unsigned long)data->d_size,
3899 			 (int)sh->sh_link, (unsigned long)sh->sh_flags,
3900 			 (int)sh->sh_type);
3901 
3902 		if (strcmp(name, "license") == 0) {
3903 			err = bpf_object__init_license(obj, data->d_buf, data->d_size);
3904 			if (err)
3905 				return err;
3906 		} else if (strcmp(name, "version") == 0) {
3907 			err = bpf_object__init_kversion(obj, data->d_buf, data->d_size);
3908 			if (err)
3909 				return err;
3910 		} else if (strcmp(name, "maps") == 0) {
3911 			pr_warn("elf: legacy map definitions in 'maps' section are not supported by libbpf v1.0+\n");
3912 			return -ENOTSUP;
3913 		} else if (strcmp(name, MAPS_ELF_SEC) == 0) {
3914 			obj->efile.btf_maps_shndx = idx;
3915 		} else if (strcmp(name, BTF_ELF_SEC) == 0) {
3916 			if (sh->sh_type != SHT_PROGBITS)
3917 				return -LIBBPF_ERRNO__FORMAT;
3918 			btf_data = data;
3919 		} else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
3920 			if (sh->sh_type != SHT_PROGBITS)
3921 				return -LIBBPF_ERRNO__FORMAT;
3922 			btf_ext_data = data;
3923 		} else if (sh->sh_type == SHT_SYMTAB) {
3924 			/* already processed during the first pass above */
3925 		} else if (sh->sh_type == SHT_PROGBITS && data->d_size > 0) {
3926 			if (sh->sh_flags & SHF_EXECINSTR) {
3927 				if (strcmp(name, ".text") == 0)
3928 					obj->efile.text_shndx = idx;
3929 				err = bpf_object__add_programs(obj, data, name, idx);
3930 				if (err)
3931 					return err;
3932 			} else if (strcmp(name, DATA_SEC) == 0 ||
3933 				   str_has_pfx(name, DATA_SEC ".")) {
3934 				sec_desc->sec_type = SEC_DATA;
3935 				sec_desc->shdr = sh;
3936 				sec_desc->data = data;
3937 			} else if (strcmp(name, RODATA_SEC) == 0 ||
3938 				   str_has_pfx(name, RODATA_SEC ".")) {
3939 				sec_desc->sec_type = SEC_RODATA;
3940 				sec_desc->shdr = sh;
3941 				sec_desc->data = data;
3942 			} else if (strcmp(name, STRUCT_OPS_SEC) == 0 ||
3943 				   strcmp(name, STRUCT_OPS_LINK_SEC) == 0 ||
3944 				   strcmp(name, "?" STRUCT_OPS_SEC) == 0 ||
3945 				   strcmp(name, "?" STRUCT_OPS_LINK_SEC) == 0) {
3946 				sec_desc->sec_type = SEC_ST_OPS;
3947 				sec_desc->shdr = sh;
3948 				sec_desc->data = data;
3949 				obj->efile.has_st_ops = true;
3950 			} else if (strcmp(name, ARENA_SEC) == 0) {
3951 				obj->efile.arena_data = data;
3952 				obj->efile.arena_data_shndx = idx;
3953 			} else {
3954 				pr_info("elf: skipping unrecognized data section(%d) %s\n",
3955 					idx, name);
3956 			}
3957 		} else if (sh->sh_type == SHT_REL) {
3958 			int targ_sec_idx = sh->sh_info; /* points to other section */
3959 
3960 			if (sh->sh_entsize != sizeof(Elf64_Rel) ||
3961 			    targ_sec_idx >= obj->efile.sec_cnt)
3962 				return -LIBBPF_ERRNO__FORMAT;
3963 
3964 			/* Only do relo for section with exec instructions */
3965 			if (!section_have_execinstr(obj, targ_sec_idx) &&
3966 			    strcmp(name, ".rel" STRUCT_OPS_SEC) &&
3967 			    strcmp(name, ".rel" STRUCT_OPS_LINK_SEC) &&
3968 			    strcmp(name, ".rel?" STRUCT_OPS_SEC) &&
3969 			    strcmp(name, ".rel?" STRUCT_OPS_LINK_SEC) &&
3970 			    strcmp(name, ".rel" MAPS_ELF_SEC)) {
3971 				pr_info("elf: skipping relo section(%d) %s for section(%d) %s\n",
3972 					idx, name, targ_sec_idx,
3973 					elf_sec_name(obj, elf_sec_by_idx(obj, targ_sec_idx)) ?: "<?>");
3974 				continue;
3975 			}
3976 
3977 			sec_desc->sec_type = SEC_RELO;
3978 			sec_desc->shdr = sh;
3979 			sec_desc->data = data;
3980 		} else if (sh->sh_type == SHT_NOBITS && (strcmp(name, BSS_SEC) == 0 ||
3981 							 str_has_pfx(name, BSS_SEC "."))) {
3982 			sec_desc->sec_type = SEC_BSS;
3983 			sec_desc->shdr = sh;
3984 			sec_desc->data = data;
3985 		} else {
3986 			pr_info("elf: skipping section(%d) %s (size %zu)\n", idx, name,
3987 				(size_t)sh->sh_size);
3988 		}
3989 	}
3990 
3991 	if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) {
3992 		pr_warn("elf: symbol strings section missing or invalid in %s\n", obj->path);
3993 		return -LIBBPF_ERRNO__FORMAT;
3994 	}
3995 
3996 	/* change BPF program insns to native endianness for introspection */
3997 	if (!is_native_endianness(obj))
3998 		bpf_object_bswap_progs(obj);
3999 
4000 	/* sort BPF programs by section name and in-section instruction offset
4001 	 * for faster search
4002 	 */
4003 	if (obj->nr_programs)
4004 		qsort(obj->programs, obj->nr_programs, sizeof(*obj->programs), cmp_progs);
4005 
4006 	return bpf_object__init_btf(obj, btf_data, btf_ext_data);
4007 }
4008 
4009 static bool sym_is_extern(const Elf64_Sym *sym)
4010 {
4011 	int bind = ELF64_ST_BIND(sym->st_info);
4012 	/* externs are symbols w/ type=NOTYPE, bind=GLOBAL|WEAK, section=UND */
4013 	return sym->st_shndx == SHN_UNDEF &&
4014 	       (bind == STB_GLOBAL || bind == STB_WEAK) &&
4015 	       ELF64_ST_TYPE(sym->st_info) == STT_NOTYPE;
4016 }
4017 
4018 static bool sym_is_subprog(const Elf64_Sym *sym, int text_shndx)
4019 {
4020 	int bind = ELF64_ST_BIND(sym->st_info);
4021 	int type = ELF64_ST_TYPE(sym->st_info);
4022 
4023 	/* in .text section */
4024 	if (sym->st_shndx != text_shndx)
4025 		return false;
4026 
4027 	/* local function */
4028 	if (bind == STB_LOCAL && type == STT_SECTION)
4029 		return true;
4030 
4031 	/* global function */
4032 	return (bind == STB_GLOBAL || bind == STB_WEAK) && type == STT_FUNC;
4033 }
4034 
4035 static int find_extern_btf_id(const struct btf *btf, const char *ext_name)
4036 {
4037 	const struct btf_type *t;
4038 	const char *tname;
4039 	int i, n;
4040 
4041 	if (!btf)
4042 		return -ESRCH;
4043 
4044 	n = btf__type_cnt(btf);
4045 	for (i = 1; i < n; i++) {
4046 		t = btf__type_by_id(btf, i);
4047 
4048 		if (!btf_is_var(t) && !btf_is_func(t))
4049 			continue;
4050 
4051 		tname = btf__name_by_offset(btf, t->name_off);
4052 		if (strcmp(tname, ext_name))
4053 			continue;
4054 
4055 		if (btf_is_var(t) &&
4056 		    btf_var(t)->linkage != BTF_VAR_GLOBAL_EXTERN)
4057 			return -EINVAL;
4058 
4059 		if (btf_is_func(t) && btf_func_linkage(t) != BTF_FUNC_EXTERN)
4060 			return -EINVAL;
4061 
4062 		return i;
4063 	}
4064 
4065 	return -ENOENT;
4066 }
4067 
4068 static int find_extern_sec_btf_id(struct btf *btf, int ext_btf_id) {
4069 	const struct btf_var_secinfo *vs;
4070 	const struct btf_type *t;
4071 	int i, j, n;
4072 
4073 	if (!btf)
4074 		return -ESRCH;
4075 
4076 	n = btf__type_cnt(btf);
4077 	for (i = 1; i < n; i++) {
4078 		t = btf__type_by_id(btf, i);
4079 
4080 		if (!btf_is_datasec(t))
4081 			continue;
4082 
4083 		vs = btf_var_secinfos(t);
4084 		for (j = 0; j < btf_vlen(t); j++, vs++) {
4085 			if (vs->type == ext_btf_id)
4086 				return i;
4087 		}
4088 	}
4089 
4090 	return -ENOENT;
4091 }
4092 
4093 static enum kcfg_type find_kcfg_type(const struct btf *btf, int id,
4094 				     bool *is_signed)
4095 {
4096 	const struct btf_type *t;
4097 	const char *name;
4098 
4099 	t = skip_mods_and_typedefs(btf, id, NULL);
4100 	name = btf__name_by_offset(btf, t->name_off);
4101 
4102 	if (is_signed)
4103 		*is_signed = false;
4104 	switch (btf_kind(t)) {
4105 	case BTF_KIND_INT: {
4106 		int enc = btf_int_encoding(t);
4107 
4108 		if (enc & BTF_INT_BOOL)
4109 			return t->size == 1 ? KCFG_BOOL : KCFG_UNKNOWN;
4110 		if (is_signed)
4111 			*is_signed = enc & BTF_INT_SIGNED;
4112 		if (t->size == 1)
4113 			return KCFG_CHAR;
4114 		if (t->size < 1 || t->size > 8 || (t->size & (t->size - 1)))
4115 			return KCFG_UNKNOWN;
4116 		return KCFG_INT;
4117 	}
4118 	case BTF_KIND_ENUM:
4119 		if (t->size != 4)
4120 			return KCFG_UNKNOWN;
4121 		if (strcmp(name, "libbpf_tristate"))
4122 			return KCFG_UNKNOWN;
4123 		return KCFG_TRISTATE;
4124 	case BTF_KIND_ENUM64:
4125 		if (strcmp(name, "libbpf_tristate"))
4126 			return KCFG_UNKNOWN;
4127 		return KCFG_TRISTATE;
4128 	case BTF_KIND_ARRAY:
4129 		if (btf_array(t)->nelems == 0)
4130 			return KCFG_UNKNOWN;
4131 		if (find_kcfg_type(btf, btf_array(t)->type, NULL) != KCFG_CHAR)
4132 			return KCFG_UNKNOWN;
4133 		return KCFG_CHAR_ARR;
4134 	default:
4135 		return KCFG_UNKNOWN;
4136 	}
4137 }
4138 
4139 static int cmp_externs(const void *_a, const void *_b)
4140 {
4141 	const struct extern_desc *a = _a;
4142 	const struct extern_desc *b = _b;
4143 
4144 	if (a->type != b->type)
4145 		return a->type < b->type ? -1 : 1;
4146 
4147 	if (a->type == EXT_KCFG) {
4148 		/* descending order by alignment requirements */
4149 		if (a->kcfg.align != b->kcfg.align)
4150 			return a->kcfg.align > b->kcfg.align ? -1 : 1;
4151 		/* ascending order by size, within same alignment class */
4152 		if (a->kcfg.sz != b->kcfg.sz)
4153 			return a->kcfg.sz < b->kcfg.sz ? -1 : 1;
4154 	}
4155 
4156 	/* resolve ties by name */
4157 	return strcmp(a->name, b->name);
4158 }
4159 
4160 static int find_int_btf_id(const struct btf *btf)
4161 {
4162 	const struct btf_type *t;
4163 	int i, n;
4164 
4165 	n = btf__type_cnt(btf);
4166 	for (i = 1; i < n; i++) {
4167 		t = btf__type_by_id(btf, i);
4168 
4169 		if (btf_is_int(t) && btf_int_bits(t) == 32)
4170 			return i;
4171 	}
4172 
4173 	return 0;
4174 }
4175 
4176 static int add_dummy_ksym_var(struct btf *btf)
4177 {
4178 	int i, int_btf_id, sec_btf_id, dummy_var_btf_id;
4179 	const struct btf_var_secinfo *vs;
4180 	const struct btf_type *sec;
4181 
4182 	if (!btf)
4183 		return 0;
4184 
4185 	sec_btf_id = btf__find_by_name_kind(btf, KSYMS_SEC,
4186 					    BTF_KIND_DATASEC);
4187 	if (sec_btf_id < 0)
4188 		return 0;
4189 
4190 	sec = btf__type_by_id(btf, sec_btf_id);
4191 	vs = btf_var_secinfos(sec);
4192 	for (i = 0; i < btf_vlen(sec); i++, vs++) {
4193 		const struct btf_type *vt;
4194 
4195 		vt = btf__type_by_id(btf, vs->type);
4196 		if (btf_is_func(vt))
4197 			break;
4198 	}
4199 
4200 	/* No func in ksyms sec.  No need to add dummy var. */
4201 	if (i == btf_vlen(sec))
4202 		return 0;
4203 
4204 	int_btf_id = find_int_btf_id(btf);
4205 	dummy_var_btf_id = btf__add_var(btf,
4206 					"dummy_ksym",
4207 					BTF_VAR_GLOBAL_ALLOCATED,
4208 					int_btf_id);
4209 	if (dummy_var_btf_id < 0)
4210 		pr_warn("cannot create a dummy_ksym var\n");
4211 
4212 	return dummy_var_btf_id;
4213 }
4214 
4215 static int bpf_object__collect_externs(struct bpf_object *obj)
4216 {
4217 	struct btf_type *sec, *kcfg_sec = NULL, *ksym_sec = NULL;
4218 	const struct btf_type *t;
4219 	struct extern_desc *ext;
4220 	int i, n, off, dummy_var_btf_id;
4221 	const char *ext_name, *sec_name;
4222 	size_t ext_essent_len;
4223 	Elf_Scn *scn;
4224 	Elf64_Shdr *sh;
4225 
4226 	if (!obj->efile.symbols)
4227 		return 0;
4228 
4229 	scn = elf_sec_by_idx(obj, obj->efile.symbols_shndx);
4230 	sh = elf_sec_hdr(obj, scn);
4231 	if (!sh || sh->sh_entsize != sizeof(Elf64_Sym))
4232 		return -LIBBPF_ERRNO__FORMAT;
4233 
4234 	dummy_var_btf_id = add_dummy_ksym_var(obj->btf);
4235 	if (dummy_var_btf_id < 0)
4236 		return dummy_var_btf_id;
4237 
4238 	n = sh->sh_size / sh->sh_entsize;
4239 	pr_debug("looking for externs among %d symbols...\n", n);
4240 
4241 	for (i = 0; i < n; i++) {
4242 		Elf64_Sym *sym = elf_sym_by_idx(obj, i);
4243 
4244 		if (!sym)
4245 			return -LIBBPF_ERRNO__FORMAT;
4246 		if (!sym_is_extern(sym))
4247 			continue;
4248 		ext_name = elf_sym_str(obj, sym->st_name);
4249 		if (!ext_name || !ext_name[0])
4250 			continue;
4251 
4252 		ext = obj->externs;
4253 		ext = libbpf_reallocarray(ext, obj->nr_extern + 1, sizeof(*ext));
4254 		if (!ext)
4255 			return -ENOMEM;
4256 		obj->externs = ext;
4257 		ext = &ext[obj->nr_extern];
4258 		memset(ext, 0, sizeof(*ext));
4259 		obj->nr_extern++;
4260 
4261 		ext->btf_id = find_extern_btf_id(obj->btf, ext_name);
4262 		if (ext->btf_id <= 0) {
4263 			pr_warn("failed to find BTF for extern '%s': %d\n",
4264 				ext_name, ext->btf_id);
4265 			return ext->btf_id;
4266 		}
4267 		t = btf__type_by_id(obj->btf, ext->btf_id);
4268 		ext->name = strdup(btf__name_by_offset(obj->btf, t->name_off));
4269 		if (!ext->name)
4270 			return -ENOMEM;
4271 		ext->sym_idx = i;
4272 		ext->is_weak = ELF64_ST_BIND(sym->st_info) == STB_WEAK;
4273 
4274 		ext_essent_len = bpf_core_essential_name_len(ext->name);
4275 		ext->essent_name = NULL;
4276 		if (ext_essent_len != strlen(ext->name)) {
4277 			ext->essent_name = strndup(ext->name, ext_essent_len);
4278 			if (!ext->essent_name)
4279 				return -ENOMEM;
4280 		}
4281 
4282 		ext->sec_btf_id = find_extern_sec_btf_id(obj->btf, ext->btf_id);
4283 		if (ext->sec_btf_id <= 0) {
4284 			pr_warn("failed to find BTF for extern '%s' [%d] section: %d\n",
4285 				ext_name, ext->btf_id, ext->sec_btf_id);
4286 			return ext->sec_btf_id;
4287 		}
4288 		sec = (void *)btf__type_by_id(obj->btf, ext->sec_btf_id);
4289 		sec_name = btf__name_by_offset(obj->btf, sec->name_off);
4290 
4291 		if (strcmp(sec_name, KCONFIG_SEC) == 0) {
4292 			if (btf_is_func(t)) {
4293 				pr_warn("extern function %s is unsupported under %s section\n",
4294 					ext->name, KCONFIG_SEC);
4295 				return -ENOTSUP;
4296 			}
4297 			kcfg_sec = sec;
4298 			ext->type = EXT_KCFG;
4299 			ext->kcfg.sz = btf__resolve_size(obj->btf, t->type);
4300 			if (ext->kcfg.sz <= 0) {
4301 				pr_warn("failed to resolve size of extern (kcfg) '%s': %d\n",
4302 					ext_name, ext->kcfg.sz);
4303 				return ext->kcfg.sz;
4304 			}
4305 			ext->kcfg.align = btf__align_of(obj->btf, t->type);
4306 			if (ext->kcfg.align <= 0) {
4307 				pr_warn("failed to determine alignment of extern (kcfg) '%s': %d\n",
4308 					ext_name, ext->kcfg.align);
4309 				return -EINVAL;
4310 			}
4311 			ext->kcfg.type = find_kcfg_type(obj->btf, t->type,
4312 							&ext->kcfg.is_signed);
4313 			if (ext->kcfg.type == KCFG_UNKNOWN) {
4314 				pr_warn("extern (kcfg) '%s': type is unsupported\n", ext_name);
4315 				return -ENOTSUP;
4316 			}
4317 		} else if (strcmp(sec_name, KSYMS_SEC) == 0) {
4318 			ksym_sec = sec;
4319 			ext->type = EXT_KSYM;
4320 			skip_mods_and_typedefs(obj->btf, t->type,
4321 					       &ext->ksym.type_id);
4322 		} else {
4323 			pr_warn("unrecognized extern section '%s'\n", sec_name);
4324 			return -ENOTSUP;
4325 		}
4326 	}
4327 	pr_debug("collected %d externs total\n", obj->nr_extern);
4328 
4329 	if (!obj->nr_extern)
4330 		return 0;
4331 
4332 	/* sort externs by type, for kcfg ones also by (align, size, name) */
4333 	qsort(obj->externs, obj->nr_extern, sizeof(*ext), cmp_externs);
4334 
4335 	/* for .ksyms section, we need to turn all externs into allocated
4336 	 * variables in BTF to pass kernel verification; we do this by
4337 	 * pretending that each extern is a 8-byte variable
4338 	 */
4339 	if (ksym_sec) {
4340 		/* find existing 4-byte integer type in BTF to use for fake
4341 		 * extern variables in DATASEC
4342 		 */
4343 		int int_btf_id = find_int_btf_id(obj->btf);
4344 		/* For extern function, a dummy_var added earlier
4345 		 * will be used to replace the vs->type and
4346 		 * its name string will be used to refill
4347 		 * the missing param's name.
4348 		 */
4349 		const struct btf_type *dummy_var;
4350 
4351 		dummy_var = btf__type_by_id(obj->btf, dummy_var_btf_id);
4352 		for (i = 0; i < obj->nr_extern; i++) {
4353 			ext = &obj->externs[i];
4354 			if (ext->type != EXT_KSYM)
4355 				continue;
4356 			pr_debug("extern (ksym) #%d: symbol %d, name %s\n",
4357 				 i, ext->sym_idx, ext->name);
4358 		}
4359 
4360 		sec = ksym_sec;
4361 		n = btf_vlen(sec);
4362 		for (i = 0, off = 0; i < n; i++, off += sizeof(int)) {
4363 			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
4364 			struct btf_type *vt;
4365 
4366 			vt = (void *)btf__type_by_id(obj->btf, vs->type);
4367 			ext_name = btf__name_by_offset(obj->btf, vt->name_off);
4368 			ext = find_extern_by_name(obj, ext_name);
4369 			if (!ext) {
4370 				pr_warn("failed to find extern definition for BTF %s '%s'\n",
4371 					btf_kind_str(vt), ext_name);
4372 				return -ESRCH;
4373 			}
4374 			if (btf_is_func(vt)) {
4375 				const struct btf_type *func_proto;
4376 				struct btf_param *param;
4377 				int j;
4378 
4379 				func_proto = btf__type_by_id(obj->btf,
4380 							     vt->type);
4381 				param = btf_params(func_proto);
4382 				/* Reuse the dummy_var string if the
4383 				 * func proto does not have param name.
4384 				 */
4385 				for (j = 0; j < btf_vlen(func_proto); j++)
4386 					if (param[j].type && !param[j].name_off)
4387 						param[j].name_off =
4388 							dummy_var->name_off;
4389 				vs->type = dummy_var_btf_id;
4390 				vt->info &= ~0xffff;
4391 				vt->info |= BTF_FUNC_GLOBAL;
4392 			} else {
4393 				btf_var(vt)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
4394 				vt->type = int_btf_id;
4395 			}
4396 			vs->offset = off;
4397 			vs->size = sizeof(int);
4398 		}
4399 		sec->size = off;
4400 	}
4401 
4402 	if (kcfg_sec) {
4403 		sec = kcfg_sec;
4404 		/* for kcfg externs calculate their offsets within a .kconfig map */
4405 		off = 0;
4406 		for (i = 0; i < obj->nr_extern; i++) {
4407 			ext = &obj->externs[i];
4408 			if (ext->type != EXT_KCFG)
4409 				continue;
4410 
4411 			ext->kcfg.data_off = roundup(off, ext->kcfg.align);
4412 			off = ext->kcfg.data_off + ext->kcfg.sz;
4413 			pr_debug("extern (kcfg) #%d: symbol %d, off %u, name %s\n",
4414 				 i, ext->sym_idx, ext->kcfg.data_off, ext->name);
4415 		}
4416 		sec->size = off;
4417 		n = btf_vlen(sec);
4418 		for (i = 0; i < n; i++) {
4419 			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
4420 
4421 			t = btf__type_by_id(obj->btf, vs->type);
4422 			ext_name = btf__name_by_offset(obj->btf, t->name_off);
4423 			ext = find_extern_by_name(obj, ext_name);
4424 			if (!ext) {
4425 				pr_warn("failed to find extern definition for BTF var '%s'\n",
4426 					ext_name);
4427 				return -ESRCH;
4428 			}
4429 			btf_var(t)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
4430 			vs->offset = ext->kcfg.data_off;
4431 		}
4432 	}
4433 	return 0;
4434 }
4435 
4436 static bool prog_is_subprog(const struct bpf_object *obj, const struct bpf_program *prog)
4437 {
4438 	return prog->sec_idx == obj->efile.text_shndx;
4439 }
4440 
4441 struct bpf_program *
4442 bpf_object__find_program_by_name(const struct bpf_object *obj,
4443 				 const char *name)
4444 {
4445 	struct bpf_program *prog;
4446 
4447 	bpf_object__for_each_program(prog, obj) {
4448 		if (prog_is_subprog(obj, prog))
4449 			continue;
4450 		if (!strcmp(prog->name, name))
4451 			return prog;
4452 	}
4453 	return errno = ENOENT, NULL;
4454 }
4455 
4456 static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
4457 				      int shndx)
4458 {
4459 	switch (obj->efile.secs[shndx].sec_type) {
4460 	case SEC_BSS:
4461 	case SEC_DATA:
4462 	case SEC_RODATA:
4463 		return true;
4464 	default:
4465 		return false;
4466 	}
4467 }
4468 
4469 static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
4470 				      int shndx)
4471 {
4472 	return shndx == obj->efile.btf_maps_shndx;
4473 }
4474 
4475 static enum libbpf_map_type
4476 bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
4477 {
4478 	if (shndx == obj->efile.symbols_shndx)
4479 		return LIBBPF_MAP_KCONFIG;
4480 
4481 	switch (obj->efile.secs[shndx].sec_type) {
4482 	case SEC_BSS:
4483 		return LIBBPF_MAP_BSS;
4484 	case SEC_DATA:
4485 		return LIBBPF_MAP_DATA;
4486 	case SEC_RODATA:
4487 		return LIBBPF_MAP_RODATA;
4488 	default:
4489 		return LIBBPF_MAP_UNSPEC;
4490 	}
4491 }
4492 
4493 static int bpf_prog_compute_hash(struct bpf_program *prog)
4494 {
4495 	struct bpf_insn *purged;
4496 	int i, err;
4497 
4498 	purged = calloc(prog->insns_cnt, BPF_INSN_SZ);
4499 	if (!purged)
4500 		return -ENOMEM;
4501 
4502 	/* If relocations have been done, the map_fd needs to be
4503 	 * discarded for the digest calculation.
4504 	 */
4505 	for (i = 0; i < prog->insns_cnt; i++) {
4506 		purged[i] = prog->insns[i];
4507 		if (purged[i].code == (BPF_LD | BPF_IMM | BPF_DW) &&
4508 		    (purged[i].src_reg == BPF_PSEUDO_MAP_FD ||
4509 		     purged[i].src_reg == BPF_PSEUDO_MAP_VALUE)) {
4510 			purged[i].imm = 0;
4511 			i++;
4512 			if (i >= prog->insns_cnt ||
4513 			    prog->insns[i].code != 0 ||
4514 			    prog->insns[i].dst_reg != 0 ||
4515 			    prog->insns[i].src_reg != 0 ||
4516 			    prog->insns[i].off != 0) {
4517 				err = -EINVAL;
4518 				goto out;
4519 			}
4520 			purged[i] = prog->insns[i];
4521 			purged[i].imm = 0;
4522 		}
4523 	}
4524 	err = libbpf_sha256(purged, prog->insns_cnt * sizeof(struct bpf_insn),
4525 			    prog->hash, SHA256_DIGEST_LENGTH);
4526 out:
4527 	free(purged);
4528 	return err;
4529 }
4530 
4531 static int bpf_program__record_reloc(struct bpf_program *prog,
4532 				     struct reloc_desc *reloc_desc,
4533 				     __u32 insn_idx, const char *sym_name,
4534 				     const Elf64_Sym *sym, const Elf64_Rel *rel)
4535 {
4536 	struct bpf_insn *insn = &prog->insns[insn_idx];
4537 	size_t map_idx, nr_maps = prog->obj->nr_maps;
4538 	struct bpf_object *obj = prog->obj;
4539 	__u32 shdr_idx = sym->st_shndx;
4540 	enum libbpf_map_type type;
4541 	const char *sym_sec_name;
4542 	struct bpf_map *map;
4543 
4544 	if (!is_call_insn(insn) && !is_ldimm64_insn(insn)) {
4545 		pr_warn("prog '%s': invalid relo against '%s' for insns[%d].code 0x%x\n",
4546 			prog->name, sym_name, insn_idx, insn->code);
4547 		return -LIBBPF_ERRNO__RELOC;
4548 	}
4549 
4550 	if (sym_is_extern(sym)) {
4551 		int sym_idx = ELF64_R_SYM(rel->r_info);
4552 		int i, n = obj->nr_extern;
4553 		struct extern_desc *ext;
4554 
4555 		for (i = 0; i < n; i++) {
4556 			ext = &obj->externs[i];
4557 			if (ext->sym_idx == sym_idx)
4558 				break;
4559 		}
4560 		if (i >= n) {
4561 			pr_warn("prog '%s': extern relo failed to find extern for '%s' (%d)\n",
4562 				prog->name, sym_name, sym_idx);
4563 			return -LIBBPF_ERRNO__RELOC;
4564 		}
4565 		pr_debug("prog '%s': found extern #%d '%s' (sym %d) for insn #%u\n",
4566 			 prog->name, i, ext->name, ext->sym_idx, insn_idx);
4567 		if (insn->code == (BPF_JMP | BPF_CALL))
4568 			reloc_desc->type = RELO_EXTERN_CALL;
4569 		else
4570 			reloc_desc->type = RELO_EXTERN_LD64;
4571 		reloc_desc->insn_idx = insn_idx;
4572 		reloc_desc->ext_idx = i;
4573 		return 0;
4574 	}
4575 
4576 	/* sub-program call relocation */
4577 	if (is_call_insn(insn)) {
4578 		if (insn->src_reg != BPF_PSEUDO_CALL) {
4579 			pr_warn("prog '%s': incorrect bpf_call opcode\n", prog->name);
4580 			return -LIBBPF_ERRNO__RELOC;
4581 		}
4582 		/* text_shndx can be 0, if no default "main" program exists */
4583 		if (!shdr_idx || shdr_idx != obj->efile.text_shndx) {
4584 			sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4585 			pr_warn("prog '%s': bad call relo against '%s' in section '%s'\n",
4586 				prog->name, sym_name, sym_sec_name);
4587 			return -LIBBPF_ERRNO__RELOC;
4588 		}
4589 		if (sym->st_value % BPF_INSN_SZ) {
4590 			pr_warn("prog '%s': bad call relo against '%s' at offset %zu\n",
4591 				prog->name, sym_name, (size_t)sym->st_value);
4592 			return -LIBBPF_ERRNO__RELOC;
4593 		}
4594 		reloc_desc->type = RELO_CALL;
4595 		reloc_desc->insn_idx = insn_idx;
4596 		reloc_desc->sym_off = sym->st_value;
4597 		return 0;
4598 	}
4599 
4600 	if (!shdr_idx || shdr_idx >= SHN_LORESERVE) {
4601 		pr_warn("prog '%s': invalid relo against '%s' in special section 0x%x; forgot to initialize global var?..\n",
4602 			prog->name, sym_name, shdr_idx);
4603 		return -LIBBPF_ERRNO__RELOC;
4604 	}
4605 
4606 	/* loading subprog addresses */
4607 	if (sym_is_subprog(sym, obj->efile.text_shndx)) {
4608 		/* global_func: sym->st_value = offset in the section, insn->imm = 0.
4609 		 * local_func: sym->st_value = 0, insn->imm = offset in the section.
4610 		 */
4611 		if ((sym->st_value % BPF_INSN_SZ) || (insn->imm % BPF_INSN_SZ)) {
4612 			pr_warn("prog '%s': bad subprog addr relo against '%s' at offset %zu+%d\n",
4613 				prog->name, sym_name, (size_t)sym->st_value, insn->imm);
4614 			return -LIBBPF_ERRNO__RELOC;
4615 		}
4616 
4617 		reloc_desc->type = RELO_SUBPROG_ADDR;
4618 		reloc_desc->insn_idx = insn_idx;
4619 		reloc_desc->sym_off = sym->st_value;
4620 		return 0;
4621 	}
4622 
4623 	type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
4624 	sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4625 
4626 	/* arena data relocation */
4627 	if (shdr_idx == obj->efile.arena_data_shndx) {
4628 		if (obj->arena_map_idx < 0) {
4629 			pr_warn("prog '%s': bad arena data relocation at insn %u, no arena maps defined\n",
4630 				prog->name, insn_idx);
4631 			return -LIBBPF_ERRNO__RELOC;
4632 		}
4633 		reloc_desc->type = RELO_DATA;
4634 		reloc_desc->insn_idx = insn_idx;
4635 		reloc_desc->map_idx = obj->arena_map_idx;
4636 		reloc_desc->sym_off = sym->st_value;
4637 
4638 		map = &obj->maps[obj->arena_map_idx];
4639 		pr_debug("prog '%s': found arena map %d (%s, sec %d, off %zu) for insn %u\n",
4640 			 prog->name, obj->arena_map_idx, map->name, map->sec_idx,
4641 			 map->sec_offset, insn_idx);
4642 		return 0;
4643 	}
4644 
4645 	/* generic map reference relocation */
4646 	if (type == LIBBPF_MAP_UNSPEC) {
4647 		if (!bpf_object__shndx_is_maps(obj, shdr_idx)) {
4648 			pr_warn("prog '%s': bad map relo against '%s' in section '%s'\n",
4649 				prog->name, sym_name, sym_sec_name);
4650 			return -LIBBPF_ERRNO__RELOC;
4651 		}
4652 		for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4653 			map = &obj->maps[map_idx];
4654 			if (map->libbpf_type != type ||
4655 			    map->sec_idx != sym->st_shndx ||
4656 			    map->sec_offset != sym->st_value)
4657 				continue;
4658 			pr_debug("prog '%s': found map %zd (%s, sec %d, off %zu) for insn #%u\n",
4659 				 prog->name, map_idx, map->name, map->sec_idx,
4660 				 map->sec_offset, insn_idx);
4661 			break;
4662 		}
4663 		if (map_idx >= nr_maps) {
4664 			pr_warn("prog '%s': map relo failed to find map for section '%s', off %zu\n",
4665 				prog->name, sym_sec_name, (size_t)sym->st_value);
4666 			return -LIBBPF_ERRNO__RELOC;
4667 		}
4668 		reloc_desc->type = RELO_LD64;
4669 		reloc_desc->insn_idx = insn_idx;
4670 		reloc_desc->map_idx = map_idx;
4671 		reloc_desc->sym_off = 0; /* sym->st_value determines map_idx */
4672 		return 0;
4673 	}
4674 
4675 	/* global data map relocation */
4676 	if (!bpf_object__shndx_is_data(obj, shdr_idx)) {
4677 		pr_warn("prog '%s': bad data relo against section '%s'\n",
4678 			prog->name, sym_sec_name);
4679 		return -LIBBPF_ERRNO__RELOC;
4680 	}
4681 	for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4682 		map = &obj->maps[map_idx];
4683 		if (map->libbpf_type != type || map->sec_idx != sym->st_shndx)
4684 			continue;
4685 		pr_debug("prog '%s': found data map %zd (%s, sec %d, off %zu) for insn %u\n",
4686 			 prog->name, map_idx, map->name, map->sec_idx,
4687 			 map->sec_offset, insn_idx);
4688 		break;
4689 	}
4690 	if (map_idx >= nr_maps) {
4691 		pr_warn("prog '%s': data relo failed to find map for section '%s'\n",
4692 			prog->name, sym_sec_name);
4693 		return -LIBBPF_ERRNO__RELOC;
4694 	}
4695 
4696 	reloc_desc->type = RELO_DATA;
4697 	reloc_desc->insn_idx = insn_idx;
4698 	reloc_desc->map_idx = map_idx;
4699 	reloc_desc->sym_off = sym->st_value;
4700 	return 0;
4701 }
4702 
4703 static bool prog_contains_insn(const struct bpf_program *prog, size_t insn_idx)
4704 {
4705 	return insn_idx >= prog->sec_insn_off &&
4706 	       insn_idx < prog->sec_insn_off + prog->sec_insn_cnt;
4707 }
4708 
4709 static struct bpf_program *find_prog_by_sec_insn(const struct bpf_object *obj,
4710 						 size_t sec_idx, size_t insn_idx)
4711 {
4712 	int l = 0, r = obj->nr_programs - 1, m;
4713 	struct bpf_program *prog;
4714 
4715 	if (!obj->nr_programs)
4716 		return NULL;
4717 
4718 	while (l < r) {
4719 		m = l + (r - l + 1) / 2;
4720 		prog = &obj->programs[m];
4721 
4722 		if (prog->sec_idx < sec_idx ||
4723 		    (prog->sec_idx == sec_idx && prog->sec_insn_off <= insn_idx))
4724 			l = m;
4725 		else
4726 			r = m - 1;
4727 	}
4728 	/* matching program could be at index l, but it still might be the
4729 	 * wrong one, so we need to double check conditions for the last time
4730 	 */
4731 	prog = &obj->programs[l];
4732 	if (prog->sec_idx == sec_idx && prog_contains_insn(prog, insn_idx))
4733 		return prog;
4734 	return NULL;
4735 }
4736 
4737 static int
4738 bpf_object__collect_prog_relos(struct bpf_object *obj, Elf64_Shdr *shdr, Elf_Data *data)
4739 {
4740 	const char *relo_sec_name, *sec_name;
4741 	size_t sec_idx = shdr->sh_info, sym_idx;
4742 	struct bpf_program *prog;
4743 	struct reloc_desc *relos;
4744 	int err, i, nrels;
4745 	const char *sym_name;
4746 	__u32 insn_idx;
4747 	Elf_Scn *scn;
4748 	Elf_Data *scn_data;
4749 	Elf64_Sym *sym;
4750 	Elf64_Rel *rel;
4751 
4752 	if (sec_idx >= obj->efile.sec_cnt)
4753 		return -EINVAL;
4754 
4755 	scn = elf_sec_by_idx(obj, sec_idx);
4756 	scn_data = elf_sec_data(obj, scn);
4757 	if (!scn_data)
4758 		return -LIBBPF_ERRNO__FORMAT;
4759 
4760 	relo_sec_name = elf_sec_str(obj, shdr->sh_name);
4761 	sec_name = elf_sec_name(obj, scn);
4762 	if (!relo_sec_name || !sec_name)
4763 		return -EINVAL;
4764 
4765 	pr_debug("sec '%s': collecting relocation for section(%zu) '%s'\n",
4766 		 relo_sec_name, sec_idx, sec_name);
4767 	nrels = shdr->sh_size / shdr->sh_entsize;
4768 
4769 	for (i = 0; i < nrels; i++) {
4770 		rel = elf_rel_by_idx(data, i);
4771 		if (!rel) {
4772 			pr_warn("sec '%s': failed to get relo #%d\n", relo_sec_name, i);
4773 			return -LIBBPF_ERRNO__FORMAT;
4774 		}
4775 
4776 		sym_idx = ELF64_R_SYM(rel->r_info);
4777 		sym = elf_sym_by_idx(obj, sym_idx);
4778 		if (!sym) {
4779 			pr_warn("sec '%s': symbol #%zu not found for relo #%d\n",
4780 				relo_sec_name, sym_idx, i);
4781 			return -LIBBPF_ERRNO__FORMAT;
4782 		}
4783 
4784 		if (sym->st_shndx >= obj->efile.sec_cnt) {
4785 			pr_warn("sec '%s': corrupted symbol #%zu pointing to invalid section #%zu for relo #%d\n",
4786 				relo_sec_name, sym_idx, (size_t)sym->st_shndx, i);
4787 			return -LIBBPF_ERRNO__FORMAT;
4788 		}
4789 
4790 		if (rel->r_offset % BPF_INSN_SZ || rel->r_offset >= scn_data->d_size) {
4791 			pr_warn("sec '%s': invalid offset 0x%zx for relo #%d\n",
4792 				relo_sec_name, (size_t)rel->r_offset, i);
4793 			return -LIBBPF_ERRNO__FORMAT;
4794 		}
4795 
4796 		insn_idx = rel->r_offset / BPF_INSN_SZ;
4797 		/* relocations against static functions are recorded as
4798 		 * relocations against the section that contains a function;
4799 		 * in such case, symbol will be STT_SECTION and sym.st_name
4800 		 * will point to empty string (0), so fetch section name
4801 		 * instead
4802 		 */
4803 		if (ELF64_ST_TYPE(sym->st_info) == STT_SECTION && sym->st_name == 0)
4804 			sym_name = elf_sec_name(obj, elf_sec_by_idx(obj, sym->st_shndx));
4805 		else
4806 			sym_name = elf_sym_str(obj, sym->st_name);
4807 		sym_name = sym_name ?: "<?";
4808 
4809 		pr_debug("sec '%s': relo #%d: insn #%u against '%s'\n",
4810 			 relo_sec_name, i, insn_idx, sym_name);
4811 
4812 		prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
4813 		if (!prog) {
4814 			pr_debug("sec '%s': relo #%d: couldn't find program in section '%s' for insn #%u, probably overridden weak function, skipping...\n",
4815 				relo_sec_name, i, sec_name, insn_idx);
4816 			continue;
4817 		}
4818 
4819 		relos = libbpf_reallocarray(prog->reloc_desc,
4820 					    prog->nr_reloc + 1, sizeof(*relos));
4821 		if (!relos)
4822 			return -ENOMEM;
4823 		prog->reloc_desc = relos;
4824 
4825 		/* adjust insn_idx to local BPF program frame of reference */
4826 		insn_idx -= prog->sec_insn_off;
4827 		err = bpf_program__record_reloc(prog, &relos[prog->nr_reloc],
4828 						insn_idx, sym_name, sym, rel);
4829 		if (err)
4830 			return err;
4831 
4832 		prog->nr_reloc++;
4833 	}
4834 	return 0;
4835 }
4836 
4837 static int map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map)
4838 {
4839 	int id;
4840 
4841 	if (!obj->btf)
4842 		return -ENOENT;
4843 
4844 	/* if it's BTF-defined map, we don't need to search for type IDs.
4845 	 * For struct_ops map, it does not need btf_key_type_id and
4846 	 * btf_value_type_id.
4847 	 */
4848 	if (map->sec_idx == obj->efile.btf_maps_shndx || bpf_map__is_struct_ops(map))
4849 		return 0;
4850 
4851 	/*
4852 	 * LLVM annotates global data differently in BTF, that is,
4853 	 * only as '.data', '.bss' or '.rodata'.
4854 	 */
4855 	if (!bpf_map__is_internal(map))
4856 		return -ENOENT;
4857 
4858 	id = btf__find_by_name(obj->btf, map->real_name);
4859 	if (id < 0)
4860 		return id;
4861 
4862 	map->btf_key_type_id = 0;
4863 	map->btf_value_type_id = id;
4864 	return 0;
4865 }
4866 
4867 static int bpf_get_map_info_from_fdinfo(int fd, struct bpf_map_info *info)
4868 {
4869 	char file[PATH_MAX], buff[4096];
4870 	FILE *fp;
4871 	__u32 val;
4872 	int err;
4873 
4874 	snprintf(file, sizeof(file), "/proc/%d/fdinfo/%d", getpid(), fd);
4875 	memset(info, 0, sizeof(*info));
4876 
4877 	fp = fopen(file, "re");
4878 	if (!fp) {
4879 		err = -errno;
4880 		pr_warn("failed to open %s: %s. No procfs support?\n", file,
4881 			errstr(err));
4882 		return err;
4883 	}
4884 
4885 	while (fgets(buff, sizeof(buff), fp)) {
4886 		if (sscanf(buff, "map_type:\t%u", &val) == 1)
4887 			info->type = val;
4888 		else if (sscanf(buff, "key_size:\t%u", &val) == 1)
4889 			info->key_size = val;
4890 		else if (sscanf(buff, "value_size:\t%u", &val) == 1)
4891 			info->value_size = val;
4892 		else if (sscanf(buff, "max_entries:\t%u", &val) == 1)
4893 			info->max_entries = val;
4894 		else if (sscanf(buff, "map_flags:\t%i", &val) == 1)
4895 			info->map_flags = val;
4896 	}
4897 
4898 	fclose(fp);
4899 
4900 	return 0;
4901 }
4902 
4903 static bool map_is_created(const struct bpf_map *map)
4904 {
4905 	return map->obj->state >= OBJ_PREPARED || map->reused;
4906 }
4907 
4908 bool bpf_map__autocreate(const struct bpf_map *map)
4909 {
4910 	return map->autocreate;
4911 }
4912 
4913 int bpf_map__set_autocreate(struct bpf_map *map, bool autocreate)
4914 {
4915 	if (map_is_created(map))
4916 		return libbpf_err(-EBUSY);
4917 
4918 	map->autocreate = autocreate;
4919 	return 0;
4920 }
4921 
4922 int bpf_map__set_autoattach(struct bpf_map *map, bool autoattach)
4923 {
4924 	if (!bpf_map__is_struct_ops(map))
4925 		return libbpf_err(-EINVAL);
4926 
4927 	map->autoattach = autoattach;
4928 	return 0;
4929 }
4930 
4931 bool bpf_map__autoattach(const struct bpf_map *map)
4932 {
4933 	return map->autoattach;
4934 }
4935 
4936 int bpf_map__reuse_fd(struct bpf_map *map, int fd)
4937 {
4938 	struct bpf_map_info info;
4939 	__u32 len = sizeof(info), name_len;
4940 	int new_fd, err;
4941 	char *new_name;
4942 
4943 	memset(&info, 0, len);
4944 	err = bpf_map_get_info_by_fd(fd, &info, &len);
4945 	if (err && errno == EINVAL)
4946 		err = bpf_get_map_info_from_fdinfo(fd, &info);
4947 	if (err)
4948 		return libbpf_err(err);
4949 
4950 	name_len = strlen(info.name);
4951 	if (name_len == BPF_OBJ_NAME_LEN - 1 && strncmp(map->name, info.name, name_len) == 0)
4952 		new_name = strdup(map->name);
4953 	else
4954 		new_name = strdup(info.name);
4955 
4956 	if (!new_name)
4957 		return libbpf_err(-errno);
4958 
4959 	/*
4960 	 * Like dup(), but make sure new FD is >= 3 and has O_CLOEXEC set.
4961 	 * This is similar to what we do in ensure_good_fd(), but without
4962 	 * closing original FD.
4963 	 */
4964 	new_fd = fcntl(fd, F_DUPFD_CLOEXEC, 3);
4965 	if (new_fd < 0) {
4966 		err = -errno;
4967 		goto err_free_new_name;
4968 	}
4969 
4970 	err = reuse_fd(map->fd, new_fd);
4971 	if (err)
4972 		goto err_free_new_name;
4973 
4974 	free(map->name);
4975 
4976 	map->name = new_name;
4977 	map->def.type = info.type;
4978 	map->def.key_size = info.key_size;
4979 	map->def.value_size = info.value_size;
4980 	map->def.max_entries = info.max_entries;
4981 	map->def.map_flags = info.map_flags;
4982 	map->btf_key_type_id = info.btf_key_type_id;
4983 	map->btf_value_type_id = info.btf_value_type_id;
4984 	map->reused = true;
4985 	map->map_extra = info.map_extra;
4986 
4987 	return 0;
4988 
4989 err_free_new_name:
4990 	free(new_name);
4991 	return libbpf_err(err);
4992 }
4993 
4994 __u32 bpf_map__max_entries(const struct bpf_map *map)
4995 {
4996 	return map->def.max_entries;
4997 }
4998 
4999 struct bpf_map *bpf_map__inner_map(struct bpf_map *map)
5000 {
5001 	if (!bpf_map_type__is_map_in_map(map->def.type))
5002 		return errno = EINVAL, NULL;
5003 
5004 	return map->inner_map;
5005 }
5006 
5007 int bpf_map__set_max_entries(struct bpf_map *map, __u32 max_entries)
5008 {
5009 	if (map_is_created(map))
5010 		return libbpf_err(-EBUSY);
5011 
5012 	map->def.max_entries = max_entries;
5013 
5014 	/* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
5015 	if (map_is_ringbuf(map))
5016 		map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
5017 
5018 	return 0;
5019 }
5020 
5021 static int bpf_object_prepare_token(struct bpf_object *obj)
5022 {
5023 	const char *bpffs_path;
5024 	int bpffs_fd = -1, token_fd, err;
5025 	bool mandatory;
5026 	enum libbpf_print_level level;
5027 
5028 	/* token is explicitly prevented */
5029 	if (obj->token_path && obj->token_path[0] == '\0') {
5030 		pr_debug("object '%s': token is prevented, skipping...\n", obj->name);
5031 		return 0;
5032 	}
5033 
5034 	mandatory = obj->token_path != NULL;
5035 	level = mandatory ? LIBBPF_WARN : LIBBPF_DEBUG;
5036 
5037 	bpffs_path = obj->token_path ?: BPF_FS_DEFAULT_PATH;
5038 	bpffs_fd = open(bpffs_path, O_DIRECTORY, O_RDWR);
5039 	if (bpffs_fd < 0) {
5040 		err = -errno;
5041 		__pr(level, "object '%s': failed (%s) to open BPF FS mount at '%s'%s\n",
5042 		     obj->name, errstr(err), bpffs_path,
5043 		     mandatory ? "" : ", skipping optional step...");
5044 		return mandatory ? err : 0;
5045 	}
5046 
5047 	token_fd = bpf_token_create(bpffs_fd, 0);
5048 	close(bpffs_fd);
5049 	if (token_fd < 0) {
5050 		if (!mandatory && token_fd == -ENOENT) {
5051 			pr_debug("object '%s': BPF FS at '%s' doesn't have BPF token delegation set up, skipping...\n",
5052 				 obj->name, bpffs_path);
5053 			return 0;
5054 		}
5055 		__pr(level, "object '%s': failed (%d) to create BPF token from '%s'%s\n",
5056 		     obj->name, token_fd, bpffs_path,
5057 		     mandatory ? "" : ", skipping optional step...");
5058 		return mandatory ? token_fd : 0;
5059 	}
5060 
5061 	obj->feat_cache = calloc(1, sizeof(*obj->feat_cache));
5062 	if (!obj->feat_cache) {
5063 		close(token_fd);
5064 		return -ENOMEM;
5065 	}
5066 
5067 	obj->token_fd = token_fd;
5068 	obj->feat_cache->token_fd = token_fd;
5069 
5070 	return 0;
5071 }
5072 
5073 static int
5074 bpf_object__probe_loading(struct bpf_object *obj)
5075 {
5076 	struct bpf_insn insns[] = {
5077 		BPF_MOV64_IMM(BPF_REG_0, 0),
5078 		BPF_EXIT_INSN(),
5079 	};
5080 	int ret, insn_cnt = ARRAY_SIZE(insns);
5081 	LIBBPF_OPTS(bpf_prog_load_opts, opts,
5082 		.token_fd = obj->token_fd,
5083 		.prog_flags = obj->token_fd ? BPF_F_TOKEN_FD : 0,
5084 	);
5085 
5086 	if (obj->gen_loader)
5087 		return 0;
5088 
5089 	ret = bump_rlimit_memlock();
5090 	if (ret)
5091 		pr_warn("Failed to bump RLIMIT_MEMLOCK (err = %s), you might need to do it explicitly!\n",
5092 			errstr(ret));
5093 
5094 	/* make sure basic loading works */
5095 	ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, &opts);
5096 	if (ret < 0)
5097 		ret = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, &opts);
5098 	if (ret < 0) {
5099 		ret = errno;
5100 		pr_warn("Error in %s(): %s. Couldn't load trivial BPF program. Make sure your kernel supports BPF (CONFIG_BPF_SYSCALL=y) and/or that RLIMIT_MEMLOCK is set to big enough value.\n",
5101 			__func__, errstr(ret));
5102 		return -ret;
5103 	}
5104 	close(ret);
5105 
5106 	return 0;
5107 }
5108 
5109 bool kernel_supports(const struct bpf_object *obj, enum kern_feature_id feat_id)
5110 {
5111 	if (obj->gen_loader)
5112 		/* To generate loader program assume the latest kernel
5113 		 * to avoid doing extra prog_load, map_create syscalls.
5114 		 */
5115 		return true;
5116 
5117 	if (obj->token_fd)
5118 		return feat_supported(obj->feat_cache, feat_id);
5119 
5120 	return feat_supported(NULL, feat_id);
5121 }
5122 
5123 static bool map_is_reuse_compat(const struct bpf_map *map, int map_fd)
5124 {
5125 	struct bpf_map_info map_info;
5126 	__u32 map_info_len = sizeof(map_info);
5127 	int err;
5128 
5129 	memset(&map_info, 0, map_info_len);
5130 	err = bpf_map_get_info_by_fd(map_fd, &map_info, &map_info_len);
5131 	if (err && errno == EINVAL)
5132 		err = bpf_get_map_info_from_fdinfo(map_fd, &map_info);
5133 	if (err) {
5134 		pr_warn("failed to get map info for map FD %d: %s\n", map_fd,
5135 			errstr(err));
5136 		return false;
5137 	}
5138 
5139 	/*
5140 	 * bpf_get_map_info_by_fd() for DEVMAP will always return flags with
5141 	 * BPF_F_RDONLY_PROG set, but it generally is not set at map creation time.
5142 	 * Thus, ignore the BPF_F_RDONLY_PROG flag in the flags returned from
5143 	 * bpf_get_map_info_by_fd() when checking for compatibility with an
5144 	 * existing DEVMAP.
5145 	 */
5146 	if (map->def.type == BPF_MAP_TYPE_DEVMAP || map->def.type == BPF_MAP_TYPE_DEVMAP_HASH)
5147 		map_info.map_flags &= ~BPF_F_RDONLY_PROG;
5148 
5149 	return (map_info.type == map->def.type &&
5150 		map_info.key_size == map->def.key_size &&
5151 		map_info.value_size == map->def.value_size &&
5152 		map_info.max_entries == map->def.max_entries &&
5153 		map_info.map_flags == map->def.map_flags &&
5154 		map_info.map_extra == map->map_extra);
5155 }
5156 
5157 static int
5158 bpf_object__reuse_map(struct bpf_map *map)
5159 {
5160 	int err, pin_fd;
5161 
5162 	pin_fd = bpf_obj_get(map->pin_path);
5163 	if (pin_fd < 0) {
5164 		err = -errno;
5165 		if (err == -ENOENT) {
5166 			pr_debug("found no pinned map to reuse at '%s'\n",
5167 				 map->pin_path);
5168 			return 0;
5169 		}
5170 
5171 		pr_warn("couldn't retrieve pinned map '%s': %s\n",
5172 			map->pin_path, errstr(err));
5173 		return err;
5174 	}
5175 
5176 	if (!map_is_reuse_compat(map, pin_fd)) {
5177 		pr_warn("couldn't reuse pinned map at '%s': parameter mismatch\n",
5178 			map->pin_path);
5179 		close(pin_fd);
5180 		return -EINVAL;
5181 	}
5182 
5183 	err = bpf_map__reuse_fd(map, pin_fd);
5184 	close(pin_fd);
5185 	if (err)
5186 		return err;
5187 
5188 	map->pinned = true;
5189 	pr_debug("reused pinned map at '%s'\n", map->pin_path);
5190 
5191 	return 0;
5192 }
5193 
5194 static int
5195 bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
5196 {
5197 	enum libbpf_map_type map_type = map->libbpf_type;
5198 	int err, zero = 0;
5199 	size_t mmap_sz;
5200 
5201 	if (obj->gen_loader) {
5202 		bpf_gen__map_update_elem(obj->gen_loader, map - obj->maps,
5203 					 map->mmaped, map->def.value_size);
5204 		if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG)
5205 			bpf_gen__map_freeze(obj->gen_loader, map - obj->maps);
5206 		return 0;
5207 	}
5208 
5209 	err = bpf_map_update_elem(map->fd, &zero, map->mmaped, 0);
5210 	if (err) {
5211 		err = -errno;
5212 		pr_warn("map '%s': failed to set initial contents: %s\n",
5213 			bpf_map__name(map), errstr(err));
5214 		return err;
5215 	}
5216 
5217 	/* Freeze .rodata and .kconfig map as read-only from syscall side. */
5218 	if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG) {
5219 		err = bpf_map_freeze(map->fd);
5220 		if (err) {
5221 			err = -errno;
5222 			pr_warn("map '%s': failed to freeze as read-only: %s\n",
5223 				bpf_map__name(map), errstr(err));
5224 			return err;
5225 		}
5226 	}
5227 
5228 	/* Remap anonymous mmap()-ed "map initialization image" as
5229 	 * a BPF map-backed mmap()-ed memory, but preserving the same
5230 	 * memory address. This will cause kernel to change process'
5231 	 * page table to point to a different piece of kernel memory,
5232 	 * but from userspace point of view memory address (and its
5233 	 * contents, being identical at this point) will stay the
5234 	 * same. This mapping will be released by bpf_object__close()
5235 	 * as per normal clean up procedure.
5236 	 */
5237 	mmap_sz = bpf_map_mmap_sz(map);
5238 	if (map->def.map_flags & BPF_F_MMAPABLE) {
5239 		void *mmaped;
5240 		int prot;
5241 
5242 		if (map->def.map_flags & BPF_F_RDONLY_PROG)
5243 			prot = PROT_READ;
5244 		else
5245 			prot = PROT_READ | PROT_WRITE;
5246 		mmaped = mmap(map->mmaped, mmap_sz, prot, MAP_SHARED | MAP_FIXED, map->fd, 0);
5247 		if (mmaped == MAP_FAILED) {
5248 			err = -errno;
5249 			pr_warn("map '%s': failed to re-mmap() contents: %s\n",
5250 				bpf_map__name(map), errstr(err));
5251 			return err;
5252 		}
5253 		map->mmaped = mmaped;
5254 	} else if (map->mmaped) {
5255 		munmap(map->mmaped, mmap_sz);
5256 		map->mmaped = NULL;
5257 	}
5258 
5259 	return 0;
5260 }
5261 
5262 static void bpf_map__destroy(struct bpf_map *map);
5263 
5264 static int bpf_object__create_map(struct bpf_object *obj, struct bpf_map *map, bool is_inner)
5265 {
5266 	LIBBPF_OPTS(bpf_map_create_opts, create_attr);
5267 	struct bpf_map_def *def = &map->def;
5268 	const char *map_name = NULL;
5269 	int err = 0, map_fd;
5270 
5271 	if (kernel_supports(obj, FEAT_PROG_NAME))
5272 		map_name = map->name;
5273 	create_attr.map_ifindex = map->map_ifindex;
5274 	create_attr.map_flags = def->map_flags;
5275 	create_attr.numa_node = map->numa_node;
5276 	create_attr.map_extra = map->map_extra;
5277 	create_attr.token_fd = obj->token_fd;
5278 	if (obj->token_fd)
5279 		create_attr.map_flags |= BPF_F_TOKEN_FD;
5280 	if (map->excl_prog) {
5281 		err = bpf_prog_compute_hash(map->excl_prog);
5282 		if (err)
5283 			return err;
5284 
5285 		create_attr.excl_prog_hash = map->excl_prog->hash;
5286 		create_attr.excl_prog_hash_size = SHA256_DIGEST_LENGTH;
5287 	}
5288 
5289 	if (bpf_map__is_struct_ops(map)) {
5290 		create_attr.btf_vmlinux_value_type_id = map->btf_vmlinux_value_type_id;
5291 		if (map->mod_btf_fd >= 0) {
5292 			create_attr.value_type_btf_obj_fd = map->mod_btf_fd;
5293 			create_attr.map_flags |= BPF_F_VTYPE_BTF_OBJ_FD;
5294 		}
5295 	}
5296 
5297 	if (obj->btf && btf__fd(obj->btf) >= 0) {
5298 		create_attr.btf_fd = btf__fd(obj->btf);
5299 		create_attr.btf_key_type_id = map->btf_key_type_id;
5300 		create_attr.btf_value_type_id = map->btf_value_type_id;
5301 	}
5302 
5303 	if (bpf_map_type__is_map_in_map(def->type)) {
5304 		if (map->inner_map) {
5305 			err = map_set_def_max_entries(map->inner_map);
5306 			if (err)
5307 				return err;
5308 			err = bpf_object__create_map(obj, map->inner_map, true);
5309 			if (err) {
5310 				pr_warn("map '%s': failed to create inner map: %s\n",
5311 					map->name, errstr(err));
5312 				return err;
5313 			}
5314 			map->inner_map_fd = map->inner_map->fd;
5315 		}
5316 		if (map->inner_map_fd >= 0)
5317 			create_attr.inner_map_fd = map->inner_map_fd;
5318 	}
5319 
5320 	switch (def->type) {
5321 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
5322 	case BPF_MAP_TYPE_CGROUP_ARRAY:
5323 	case BPF_MAP_TYPE_STACK_TRACE:
5324 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
5325 	case BPF_MAP_TYPE_HASH_OF_MAPS:
5326 	case BPF_MAP_TYPE_DEVMAP:
5327 	case BPF_MAP_TYPE_DEVMAP_HASH:
5328 	case BPF_MAP_TYPE_CPUMAP:
5329 	case BPF_MAP_TYPE_XSKMAP:
5330 	case BPF_MAP_TYPE_SOCKMAP:
5331 	case BPF_MAP_TYPE_SOCKHASH:
5332 	case BPF_MAP_TYPE_QUEUE:
5333 	case BPF_MAP_TYPE_STACK:
5334 	case BPF_MAP_TYPE_ARENA:
5335 		create_attr.btf_fd = 0;
5336 		create_attr.btf_key_type_id = 0;
5337 		create_attr.btf_value_type_id = 0;
5338 		map->btf_key_type_id = 0;
5339 		map->btf_value_type_id = 0;
5340 		break;
5341 	case BPF_MAP_TYPE_STRUCT_OPS:
5342 		create_attr.btf_value_type_id = 0;
5343 		break;
5344 	default:
5345 		break;
5346 	}
5347 
5348 	if (obj->gen_loader) {
5349 		bpf_gen__map_create(obj->gen_loader, def->type, map_name,
5350 				    def->key_size, def->value_size, def->max_entries,
5351 				    &create_attr, is_inner ? -1 : map - obj->maps);
5352 		/* We keep pretenting we have valid FD to pass various fd >= 0
5353 		 * checks by just keeping original placeholder FDs in place.
5354 		 * See bpf_object__add_map() comment.
5355 		 * This placeholder fd will not be used with any syscall and
5356 		 * will be reset to -1 eventually.
5357 		 */
5358 		map_fd = map->fd;
5359 	} else {
5360 		map_fd = bpf_map_create(def->type, map_name,
5361 					def->key_size, def->value_size,
5362 					def->max_entries, &create_attr);
5363 	}
5364 	if (map_fd < 0 && (create_attr.btf_key_type_id || create_attr.btf_value_type_id)) {
5365 		err = -errno;
5366 		pr_warn("Error in bpf_create_map_xattr(%s): %s. Retrying without BTF.\n",
5367 			map->name, errstr(err));
5368 		create_attr.btf_fd = 0;
5369 		create_attr.btf_key_type_id = 0;
5370 		create_attr.btf_value_type_id = 0;
5371 		map->btf_key_type_id = 0;
5372 		map->btf_value_type_id = 0;
5373 		map_fd = bpf_map_create(def->type, map_name,
5374 					def->key_size, def->value_size,
5375 					def->max_entries, &create_attr);
5376 	}
5377 
5378 	if (bpf_map_type__is_map_in_map(def->type) && map->inner_map) {
5379 		if (obj->gen_loader)
5380 			map->inner_map->fd = -1;
5381 		bpf_map__destroy(map->inner_map);
5382 		zfree(&map->inner_map);
5383 	}
5384 
5385 	if (map_fd < 0)
5386 		return map_fd;
5387 
5388 	/* obj->gen_loader case, prevent reuse_fd() from closing map_fd */
5389 	if (map->fd == map_fd)
5390 		return 0;
5391 
5392 	/* Keep placeholder FD value but now point it to the BPF map object.
5393 	 * This way everything that relied on this map's FD (e.g., relocated
5394 	 * ldimm64 instructions) will stay valid and won't need adjustments.
5395 	 * map->fd stays valid but now point to what map_fd points to.
5396 	 */
5397 	return reuse_fd(map->fd, map_fd);
5398 }
5399 
5400 static int init_map_in_map_slots(struct bpf_object *obj, struct bpf_map *map)
5401 {
5402 	const struct bpf_map *targ_map;
5403 	unsigned int i;
5404 	int fd, err = 0;
5405 
5406 	for (i = 0; i < map->init_slots_sz; i++) {
5407 		if (!map->init_slots[i])
5408 			continue;
5409 
5410 		targ_map = map->init_slots[i];
5411 		fd = targ_map->fd;
5412 
5413 		if (obj->gen_loader) {
5414 			bpf_gen__populate_outer_map(obj->gen_loader,
5415 						    map - obj->maps, i,
5416 						    targ_map - obj->maps);
5417 		} else {
5418 			err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5419 		}
5420 		if (err) {
5421 			err = -errno;
5422 			pr_warn("map '%s': failed to initialize slot [%d] to map '%s' fd=%d: %s\n",
5423 				map->name, i, targ_map->name, fd, errstr(err));
5424 			return err;
5425 		}
5426 		pr_debug("map '%s': slot [%d] set to map '%s' fd=%d\n",
5427 			 map->name, i, targ_map->name, fd);
5428 	}
5429 
5430 	zfree(&map->init_slots);
5431 	map->init_slots_sz = 0;
5432 
5433 	return 0;
5434 }
5435 
5436 static int init_prog_array_slots(struct bpf_object *obj, struct bpf_map *map)
5437 {
5438 	const struct bpf_program *targ_prog;
5439 	unsigned int i;
5440 	int fd, err;
5441 
5442 	if (obj->gen_loader)
5443 		return -ENOTSUP;
5444 
5445 	for (i = 0; i < map->init_slots_sz; i++) {
5446 		if (!map->init_slots[i])
5447 			continue;
5448 
5449 		targ_prog = map->init_slots[i];
5450 		fd = bpf_program__fd(targ_prog);
5451 
5452 		err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5453 		if (err) {
5454 			err = -errno;
5455 			pr_warn("map '%s': failed to initialize slot [%d] to prog '%s' fd=%d: %s\n",
5456 				map->name, i, targ_prog->name, fd, errstr(err));
5457 			return err;
5458 		}
5459 		pr_debug("map '%s': slot [%d] set to prog '%s' fd=%d\n",
5460 			 map->name, i, targ_prog->name, fd);
5461 	}
5462 
5463 	zfree(&map->init_slots);
5464 	map->init_slots_sz = 0;
5465 
5466 	return 0;
5467 }
5468 
5469 static int bpf_object_init_prog_arrays(struct bpf_object *obj)
5470 {
5471 	struct bpf_map *map;
5472 	int i, err;
5473 
5474 	for (i = 0; i < obj->nr_maps; i++) {
5475 		map = &obj->maps[i];
5476 
5477 		if (!map->init_slots_sz || map->def.type != BPF_MAP_TYPE_PROG_ARRAY)
5478 			continue;
5479 
5480 		err = init_prog_array_slots(obj, map);
5481 		if (err < 0)
5482 			return err;
5483 	}
5484 	return 0;
5485 }
5486 
5487 static int map_set_def_max_entries(struct bpf_map *map)
5488 {
5489 	if (map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY && !map->def.max_entries) {
5490 		int nr_cpus;
5491 
5492 		nr_cpus = libbpf_num_possible_cpus();
5493 		if (nr_cpus < 0) {
5494 			pr_warn("map '%s': failed to determine number of system CPUs: %d\n",
5495 				map->name, nr_cpus);
5496 			return nr_cpus;
5497 		}
5498 		pr_debug("map '%s': setting size to %d\n", map->name, nr_cpus);
5499 		map->def.max_entries = nr_cpus;
5500 	}
5501 
5502 	return 0;
5503 }
5504 
5505 static int
5506 bpf_object__create_maps(struct bpf_object *obj)
5507 {
5508 	struct bpf_map *map;
5509 	unsigned int i, j;
5510 	int err;
5511 	bool retried;
5512 
5513 	for (i = 0; i < obj->nr_maps; i++) {
5514 		map = &obj->maps[i];
5515 
5516 		/* To support old kernels, we skip creating global data maps
5517 		 * (.rodata, .data, .kconfig, etc); later on, during program
5518 		 * loading, if we detect that at least one of the to-be-loaded
5519 		 * programs is referencing any global data map, we'll error
5520 		 * out with program name and relocation index logged.
5521 		 * This approach allows to accommodate Clang emitting
5522 		 * unnecessary .rodata.str1.1 sections for string literals,
5523 		 * but also it allows to have CO-RE applications that use
5524 		 * global variables in some of BPF programs, but not others.
5525 		 * If those global variable-using programs are not loaded at
5526 		 * runtime due to bpf_program__set_autoload(prog, false),
5527 		 * bpf_object loading will succeed just fine even on old
5528 		 * kernels.
5529 		 */
5530 		if (bpf_map__is_internal(map) && !kernel_supports(obj, FEAT_GLOBAL_DATA))
5531 			map->autocreate = false;
5532 
5533 		if (!map->autocreate) {
5534 			pr_debug("map '%s': skipped auto-creating...\n", map->name);
5535 			continue;
5536 		}
5537 
5538 		err = map_set_def_max_entries(map);
5539 		if (err)
5540 			goto err_out;
5541 
5542 		retried = false;
5543 retry:
5544 		if (map->pin_path) {
5545 			err = bpf_object__reuse_map(map);
5546 			if (err) {
5547 				pr_warn("map '%s': error reusing pinned map\n",
5548 					map->name);
5549 				goto err_out;
5550 			}
5551 			if (retried && map->fd < 0) {
5552 				pr_warn("map '%s': cannot find pinned map\n",
5553 					map->name);
5554 				err = -ENOENT;
5555 				goto err_out;
5556 			}
5557 		}
5558 
5559 		if (map->reused) {
5560 			pr_debug("map '%s': skipping creation (preset fd=%d)\n",
5561 				 map->name, map->fd);
5562 		} else {
5563 			err = bpf_object__create_map(obj, map, false);
5564 			if (err)
5565 				goto err_out;
5566 
5567 			pr_debug("map '%s': created successfully, fd=%d\n",
5568 				 map->name, map->fd);
5569 
5570 			if (bpf_map__is_internal(map)) {
5571 				err = bpf_object__populate_internal_map(obj, map);
5572 				if (err < 0)
5573 					goto err_out;
5574 			} else if (map->def.type == BPF_MAP_TYPE_ARENA) {
5575 				map->mmaped = mmap((void *)(long)map->map_extra,
5576 						   bpf_map_mmap_sz(map), PROT_READ | PROT_WRITE,
5577 						   map->map_extra ? MAP_SHARED | MAP_FIXED : MAP_SHARED,
5578 						   map->fd, 0);
5579 				if (map->mmaped == MAP_FAILED) {
5580 					err = -errno;
5581 					map->mmaped = NULL;
5582 					pr_warn("map '%s': failed to mmap arena: %s\n",
5583 						map->name, errstr(err));
5584 					return err;
5585 				}
5586 				if (obj->arena_data) {
5587 					memcpy(map->mmaped, obj->arena_data, obj->arena_data_sz);
5588 					zfree(&obj->arena_data);
5589 				}
5590 			}
5591 			if (map->init_slots_sz && map->def.type != BPF_MAP_TYPE_PROG_ARRAY) {
5592 				err = init_map_in_map_slots(obj, map);
5593 				if (err < 0)
5594 					goto err_out;
5595 			}
5596 		}
5597 
5598 		if (map->pin_path && !map->pinned) {
5599 			err = bpf_map__pin(map, NULL);
5600 			if (err) {
5601 				if (!retried && err == -EEXIST) {
5602 					retried = true;
5603 					goto retry;
5604 				}
5605 				pr_warn("map '%s': failed to auto-pin at '%s': %s\n",
5606 					map->name, map->pin_path, errstr(err));
5607 				goto err_out;
5608 			}
5609 		}
5610 	}
5611 
5612 	return 0;
5613 
5614 err_out:
5615 	pr_warn("map '%s': failed to create: %s\n", map->name, errstr(err));
5616 	pr_perm_msg(err);
5617 	for (j = 0; j < i; j++)
5618 		zclose(obj->maps[j].fd);
5619 	return err;
5620 }
5621 
5622 static bool bpf_core_is_flavor_sep(const char *s)
5623 {
5624 	/* check X___Y name pattern, where X and Y are not underscores */
5625 	return s[0] != '_' &&				      /* X */
5626 	       s[1] == '_' && s[2] == '_' && s[3] == '_' &&   /* ___ */
5627 	       s[4] != '_';				      /* Y */
5628 }
5629 
5630 /* Given 'some_struct_name___with_flavor' return the length of a name prefix
5631  * before last triple underscore. Struct name part after last triple
5632  * underscore is ignored by BPF CO-RE relocation during relocation matching.
5633  */
5634 size_t bpf_core_essential_name_len(const char *name)
5635 {
5636 	size_t n = strlen(name);
5637 	int i;
5638 
5639 	for (i = n - 5; i >= 0; i--) {
5640 		if (bpf_core_is_flavor_sep(name + i))
5641 			return i + 1;
5642 	}
5643 	return n;
5644 }
5645 
5646 void bpf_core_free_cands(struct bpf_core_cand_list *cands)
5647 {
5648 	if (!cands)
5649 		return;
5650 
5651 	free(cands->cands);
5652 	free(cands);
5653 }
5654 
5655 int bpf_core_add_cands(struct bpf_core_cand *local_cand,
5656 		       size_t local_essent_len,
5657 		       const struct btf *targ_btf,
5658 		       const char *targ_btf_name,
5659 		       int targ_start_id,
5660 		       struct bpf_core_cand_list *cands)
5661 {
5662 	struct bpf_core_cand *new_cands, *cand;
5663 	const struct btf_type *t, *local_t;
5664 	const char *targ_name, *local_name;
5665 	size_t targ_essent_len;
5666 	int n, i;
5667 
5668 	local_t = btf__type_by_id(local_cand->btf, local_cand->id);
5669 	local_name = btf__str_by_offset(local_cand->btf, local_t->name_off);
5670 
5671 	n = btf__type_cnt(targ_btf);
5672 	for (i = targ_start_id; i < n; i++) {
5673 		t = btf__type_by_id(targ_btf, i);
5674 		if (!btf_kind_core_compat(t, local_t))
5675 			continue;
5676 
5677 		targ_name = btf__name_by_offset(targ_btf, t->name_off);
5678 		if (str_is_empty(targ_name))
5679 			continue;
5680 
5681 		targ_essent_len = bpf_core_essential_name_len(targ_name);
5682 		if (targ_essent_len != local_essent_len)
5683 			continue;
5684 
5685 		if (strncmp(local_name, targ_name, local_essent_len) != 0)
5686 			continue;
5687 
5688 		pr_debug("CO-RE relocating [%d] %s %s: found target candidate [%d] %s %s in [%s]\n",
5689 			 local_cand->id, btf_kind_str(local_t),
5690 			 local_name, i, btf_kind_str(t), targ_name,
5691 			 targ_btf_name);
5692 		new_cands = libbpf_reallocarray(cands->cands, cands->len + 1,
5693 					      sizeof(*cands->cands));
5694 		if (!new_cands)
5695 			return -ENOMEM;
5696 
5697 		cand = &new_cands[cands->len];
5698 		cand->btf = targ_btf;
5699 		cand->id = i;
5700 
5701 		cands->cands = new_cands;
5702 		cands->len++;
5703 	}
5704 	return 0;
5705 }
5706 
5707 static int load_module_btfs(struct bpf_object *obj)
5708 {
5709 	struct bpf_btf_info info;
5710 	struct module_btf *mod_btf;
5711 	struct btf *btf;
5712 	char name[64];
5713 	__u32 id = 0, len;
5714 	int err, fd;
5715 
5716 	if (obj->btf_modules_loaded)
5717 		return 0;
5718 
5719 	if (obj->gen_loader)
5720 		return 0;
5721 
5722 	/* don't do this again, even if we find no module BTFs */
5723 	obj->btf_modules_loaded = true;
5724 
5725 	/* kernel too old to support module BTFs */
5726 	if (!kernel_supports(obj, FEAT_MODULE_BTF))
5727 		return 0;
5728 
5729 	while (true) {
5730 		err = bpf_btf_get_next_id(id, &id);
5731 		if (err && errno == ENOENT)
5732 			return 0;
5733 		if (err && errno == EPERM) {
5734 			pr_debug("skipping module BTFs loading, missing privileges\n");
5735 			return 0;
5736 		}
5737 		if (err) {
5738 			err = -errno;
5739 			pr_warn("failed to iterate BTF objects: %s\n", errstr(err));
5740 			return err;
5741 		}
5742 
5743 		fd = bpf_btf_get_fd_by_id(id);
5744 		if (fd < 0) {
5745 			if (errno == ENOENT)
5746 				continue; /* expected race: BTF was unloaded */
5747 			err = -errno;
5748 			pr_warn("failed to get BTF object #%d FD: %s\n", id, errstr(err));
5749 			return err;
5750 		}
5751 
5752 		len = sizeof(info);
5753 		memset(&info, 0, sizeof(info));
5754 		info.name = ptr_to_u64(name);
5755 		info.name_len = sizeof(name);
5756 
5757 		err = bpf_btf_get_info_by_fd(fd, &info, &len);
5758 		if (err) {
5759 			err = -errno;
5760 			pr_warn("failed to get BTF object #%d info: %s\n", id, errstr(err));
5761 			goto err_out;
5762 		}
5763 
5764 		/* ignore non-module BTFs */
5765 		if (!info.kernel_btf || strcmp(name, "vmlinux") == 0) {
5766 			close(fd);
5767 			continue;
5768 		}
5769 
5770 		btf = btf_get_from_fd(fd, obj->btf_vmlinux);
5771 		err = libbpf_get_error(btf);
5772 		if (err) {
5773 			pr_warn("failed to load module [%s]'s BTF object #%d: %s\n",
5774 				name, id, errstr(err));
5775 			goto err_out;
5776 		}
5777 
5778 		err = libbpf_ensure_mem((void **)&obj->btf_modules, &obj->btf_module_cap,
5779 					sizeof(*obj->btf_modules), obj->btf_module_cnt + 1);
5780 		if (err)
5781 			goto err_out;
5782 
5783 		mod_btf = &obj->btf_modules[obj->btf_module_cnt++];
5784 
5785 		mod_btf->btf = btf;
5786 		mod_btf->id = id;
5787 		mod_btf->fd = fd;
5788 		mod_btf->name = strdup(name);
5789 		if (!mod_btf->name) {
5790 			err = -ENOMEM;
5791 			goto err_out;
5792 		}
5793 		continue;
5794 
5795 err_out:
5796 		close(fd);
5797 		return err;
5798 	}
5799 
5800 	return 0;
5801 }
5802 
5803 static struct bpf_core_cand_list *
5804 bpf_core_find_cands(struct bpf_object *obj, const struct btf *local_btf, __u32 local_type_id)
5805 {
5806 	struct bpf_core_cand local_cand = {};
5807 	struct bpf_core_cand_list *cands;
5808 	const struct btf *main_btf;
5809 	const struct btf_type *local_t;
5810 	const char *local_name;
5811 	size_t local_essent_len;
5812 	int err, i;
5813 
5814 	local_cand.btf = local_btf;
5815 	local_cand.id = local_type_id;
5816 	local_t = btf__type_by_id(local_btf, local_type_id);
5817 	if (!local_t)
5818 		return ERR_PTR(-EINVAL);
5819 
5820 	local_name = btf__name_by_offset(local_btf, local_t->name_off);
5821 	if (str_is_empty(local_name))
5822 		return ERR_PTR(-EINVAL);
5823 	local_essent_len = bpf_core_essential_name_len(local_name);
5824 
5825 	cands = calloc(1, sizeof(*cands));
5826 	if (!cands)
5827 		return ERR_PTR(-ENOMEM);
5828 
5829 	/* Attempt to find target candidates in vmlinux BTF first */
5830 	main_btf = obj->btf_vmlinux_override ?: obj->btf_vmlinux;
5831 	err = bpf_core_add_cands(&local_cand, local_essent_len, main_btf, "vmlinux", 1, cands);
5832 	if (err)
5833 		goto err_out;
5834 
5835 	/* if vmlinux BTF has any candidate, don't got for module BTFs */
5836 	if (cands->len)
5837 		return cands;
5838 
5839 	/* if vmlinux BTF was overridden, don't attempt to load module BTFs */
5840 	if (obj->btf_vmlinux_override)
5841 		return cands;
5842 
5843 	/* now look through module BTFs, trying to still find candidates */
5844 	err = load_module_btfs(obj);
5845 	if (err)
5846 		goto err_out;
5847 
5848 	for (i = 0; i < obj->btf_module_cnt; i++) {
5849 		err = bpf_core_add_cands(&local_cand, local_essent_len,
5850 					 obj->btf_modules[i].btf,
5851 					 obj->btf_modules[i].name,
5852 					 btf__type_cnt(obj->btf_vmlinux),
5853 					 cands);
5854 		if (err)
5855 			goto err_out;
5856 	}
5857 
5858 	return cands;
5859 err_out:
5860 	bpf_core_free_cands(cands);
5861 	return ERR_PTR(err);
5862 }
5863 
5864 /* Check local and target types for compatibility. This check is used for
5865  * type-based CO-RE relocations and follow slightly different rules than
5866  * field-based relocations. This function assumes that root types were already
5867  * checked for name match. Beyond that initial root-level name check, names
5868  * are completely ignored. Compatibility rules are as follows:
5869  *   - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs are considered compatible, but
5870  *     kind should match for local and target types (i.e., STRUCT is not
5871  *     compatible with UNION);
5872  *   - for ENUMs, the size is ignored;
5873  *   - for INT, size and signedness are ignored;
5874  *   - for ARRAY, dimensionality is ignored, element types are checked for
5875  *     compatibility recursively;
5876  *   - CONST/VOLATILE/RESTRICT modifiers are ignored;
5877  *   - TYPEDEFs/PTRs are compatible if types they pointing to are compatible;
5878  *   - FUNC_PROTOs are compatible if they have compatible signature: same
5879  *     number of input args and compatible return and argument types.
5880  * These rules are not set in stone and probably will be adjusted as we get
5881  * more experience with using BPF CO-RE relocations.
5882  */
5883 int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
5884 			      const struct btf *targ_btf, __u32 targ_id)
5885 {
5886 	return __bpf_core_types_are_compat(local_btf, local_id, targ_btf, targ_id, 32);
5887 }
5888 
5889 int bpf_core_types_match(const struct btf *local_btf, __u32 local_id,
5890 			 const struct btf *targ_btf, __u32 targ_id)
5891 {
5892 	return __bpf_core_types_match(local_btf, local_id, targ_btf, targ_id, false, 32);
5893 }
5894 
5895 static size_t bpf_core_hash_fn(const long key, void *ctx)
5896 {
5897 	return key;
5898 }
5899 
5900 static bool bpf_core_equal_fn(const long k1, const long k2, void *ctx)
5901 {
5902 	return k1 == k2;
5903 }
5904 
5905 static int record_relo_core(struct bpf_program *prog,
5906 			    const struct bpf_core_relo *core_relo, int insn_idx)
5907 {
5908 	struct reloc_desc *relos, *relo;
5909 
5910 	relos = libbpf_reallocarray(prog->reloc_desc,
5911 				    prog->nr_reloc + 1, sizeof(*relos));
5912 	if (!relos)
5913 		return -ENOMEM;
5914 	relo = &relos[prog->nr_reloc];
5915 	relo->type = RELO_CORE;
5916 	relo->insn_idx = insn_idx;
5917 	relo->core_relo = core_relo;
5918 	prog->reloc_desc = relos;
5919 	prog->nr_reloc++;
5920 	return 0;
5921 }
5922 
5923 static const struct bpf_core_relo *find_relo_core(struct bpf_program *prog, int insn_idx)
5924 {
5925 	struct reloc_desc *relo;
5926 	int i;
5927 
5928 	for (i = 0; i < prog->nr_reloc; i++) {
5929 		relo = &prog->reloc_desc[i];
5930 		if (relo->type != RELO_CORE || relo->insn_idx != insn_idx)
5931 			continue;
5932 
5933 		return relo->core_relo;
5934 	}
5935 
5936 	return NULL;
5937 }
5938 
5939 static int bpf_core_resolve_relo(struct bpf_program *prog,
5940 				 const struct bpf_core_relo *relo,
5941 				 int relo_idx,
5942 				 const struct btf *local_btf,
5943 				 struct hashmap *cand_cache,
5944 				 struct bpf_core_relo_res *targ_res)
5945 {
5946 	struct bpf_core_spec specs_scratch[3] = {};
5947 	struct bpf_core_cand_list *cands = NULL;
5948 	const char *prog_name = prog->name;
5949 	const struct btf_type *local_type;
5950 	const char *local_name;
5951 	__u32 local_id = relo->type_id;
5952 	int err;
5953 
5954 	local_type = btf__type_by_id(local_btf, local_id);
5955 	if (!local_type)
5956 		return -EINVAL;
5957 
5958 	local_name = btf__name_by_offset(local_btf, local_type->name_off);
5959 	if (!local_name)
5960 		return -EINVAL;
5961 
5962 	if (relo->kind != BPF_CORE_TYPE_ID_LOCAL &&
5963 	    !hashmap__find(cand_cache, local_id, &cands)) {
5964 		cands = bpf_core_find_cands(prog->obj, local_btf, local_id);
5965 		if (IS_ERR(cands)) {
5966 			pr_warn("prog '%s': relo #%d: target candidate search failed for [%d] %s %s: %ld\n",
5967 				prog_name, relo_idx, local_id, btf_kind_str(local_type),
5968 				local_name, PTR_ERR(cands));
5969 			return PTR_ERR(cands);
5970 		}
5971 		err = hashmap__set(cand_cache, local_id, cands, NULL, NULL);
5972 		if (err) {
5973 			bpf_core_free_cands(cands);
5974 			return err;
5975 		}
5976 	}
5977 
5978 	return bpf_core_calc_relo_insn(prog_name, relo, relo_idx, local_btf, cands, specs_scratch,
5979 				       targ_res);
5980 }
5981 
5982 static int
5983 bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
5984 {
5985 	const struct btf_ext_info_sec *sec;
5986 	struct bpf_core_relo_res targ_res;
5987 	const struct bpf_core_relo *rec;
5988 	const struct btf_ext_info *seg;
5989 	struct hashmap_entry *entry;
5990 	struct hashmap *cand_cache = NULL;
5991 	struct bpf_program *prog;
5992 	struct bpf_insn *insn;
5993 	const char *sec_name;
5994 	int i, err = 0, insn_idx, sec_idx, sec_num;
5995 
5996 	if (obj->btf_ext->core_relo_info.len == 0)
5997 		return 0;
5998 
5999 	if (targ_btf_path) {
6000 		obj->btf_vmlinux_override = btf__parse(targ_btf_path, NULL);
6001 		err = libbpf_get_error(obj->btf_vmlinux_override);
6002 		if (err) {
6003 			pr_warn("failed to parse target BTF: %s\n", errstr(err));
6004 			return err;
6005 		}
6006 	}
6007 
6008 	cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
6009 	if (IS_ERR(cand_cache)) {
6010 		err = PTR_ERR(cand_cache);
6011 		goto out;
6012 	}
6013 
6014 	seg = &obj->btf_ext->core_relo_info;
6015 	sec_num = 0;
6016 	for_each_btf_ext_sec(seg, sec) {
6017 		sec_idx = seg->sec_idxs[sec_num];
6018 		sec_num++;
6019 
6020 		sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
6021 		if (str_is_empty(sec_name)) {
6022 			err = -EINVAL;
6023 			goto out;
6024 		}
6025 
6026 		pr_debug("sec '%s': found %d CO-RE relocations\n", sec_name, sec->num_info);
6027 
6028 		for_each_btf_ext_rec(seg, sec, i, rec) {
6029 			if (rec->insn_off % BPF_INSN_SZ)
6030 				return -EINVAL;
6031 			insn_idx = rec->insn_off / BPF_INSN_SZ;
6032 			prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
6033 			if (!prog) {
6034 				/* When __weak subprog is "overridden" by another instance
6035 				 * of the subprog from a different object file, linker still
6036 				 * appends all the .BTF.ext info that used to belong to that
6037 				 * eliminated subprogram.
6038 				 * This is similar to what x86-64 linker does for relocations.
6039 				 * So just ignore such relocations just like we ignore
6040 				 * subprog instructions when discovering subprograms.
6041 				 */
6042 				pr_debug("sec '%s': skipping CO-RE relocation #%d for insn #%d belonging to eliminated weak subprogram\n",
6043 					 sec_name, i, insn_idx);
6044 				continue;
6045 			}
6046 			/* no need to apply CO-RE relocation if the program is
6047 			 * not going to be loaded
6048 			 */
6049 			if (!prog->autoload)
6050 				continue;
6051 
6052 			/* adjust insn_idx from section frame of reference to the local
6053 			 * program's frame of reference; (sub-)program code is not yet
6054 			 * relocated, so it's enough to just subtract in-section offset
6055 			 */
6056 			insn_idx = insn_idx - prog->sec_insn_off;
6057 			if (insn_idx >= prog->insns_cnt)
6058 				return -EINVAL;
6059 			insn = &prog->insns[insn_idx];
6060 
6061 			err = record_relo_core(prog, rec, insn_idx);
6062 			if (err) {
6063 				pr_warn("prog '%s': relo #%d: failed to record relocation: %s\n",
6064 					prog->name, i, errstr(err));
6065 				goto out;
6066 			}
6067 
6068 			if (prog->obj->gen_loader)
6069 				continue;
6070 
6071 			err = bpf_core_resolve_relo(prog, rec, i, obj->btf, cand_cache, &targ_res);
6072 			if (err) {
6073 				pr_warn("prog '%s': relo #%d: failed to relocate: %s\n",
6074 					prog->name, i, errstr(err));
6075 				goto out;
6076 			}
6077 
6078 			err = bpf_core_patch_insn(prog->name, insn, insn_idx, rec, i, &targ_res);
6079 			if (err) {
6080 				pr_warn("prog '%s': relo #%d: failed to patch insn #%u: %s\n",
6081 					prog->name, i, insn_idx, errstr(err));
6082 				goto out;
6083 			}
6084 		}
6085 	}
6086 
6087 out:
6088 	/* obj->btf_vmlinux and module BTFs are freed after object load */
6089 	btf__free(obj->btf_vmlinux_override);
6090 	obj->btf_vmlinux_override = NULL;
6091 
6092 	if (!IS_ERR_OR_NULL(cand_cache)) {
6093 		hashmap__for_each_entry(cand_cache, entry, i) {
6094 			bpf_core_free_cands(entry->pvalue);
6095 		}
6096 		hashmap__free(cand_cache);
6097 	}
6098 	return err;
6099 }
6100 
6101 /* base map load ldimm64 special constant, used also for log fixup logic */
6102 #define POISON_LDIMM64_MAP_BASE 2001000000
6103 #define POISON_LDIMM64_MAP_PFX "200100"
6104 
6105 static void poison_map_ldimm64(struct bpf_program *prog, int relo_idx,
6106 			       int insn_idx, struct bpf_insn *insn,
6107 			       int map_idx, const struct bpf_map *map)
6108 {
6109 	int i;
6110 
6111 	pr_debug("prog '%s': relo #%d: poisoning insn #%d that loads map #%d '%s'\n",
6112 		 prog->name, relo_idx, insn_idx, map_idx, map->name);
6113 
6114 	/* we turn single ldimm64 into two identical invalid calls */
6115 	for (i = 0; i < 2; i++) {
6116 		insn->code = BPF_JMP | BPF_CALL;
6117 		insn->dst_reg = 0;
6118 		insn->src_reg = 0;
6119 		insn->off = 0;
6120 		/* if this instruction is reachable (not a dead code),
6121 		 * verifier will complain with something like:
6122 		 * invalid func unknown#2001000123
6123 		 * where lower 123 is map index into obj->maps[] array
6124 		 */
6125 		insn->imm = POISON_LDIMM64_MAP_BASE + map_idx;
6126 
6127 		insn++;
6128 	}
6129 }
6130 
6131 /* unresolved kfunc call special constant, used also for log fixup logic */
6132 #define POISON_CALL_KFUNC_BASE 2002000000
6133 #define POISON_CALL_KFUNC_PFX "2002"
6134 
6135 static void poison_kfunc_call(struct bpf_program *prog, int relo_idx,
6136 			      int insn_idx, struct bpf_insn *insn,
6137 			      int ext_idx, const struct extern_desc *ext)
6138 {
6139 	pr_debug("prog '%s': relo #%d: poisoning insn #%d that calls kfunc '%s'\n",
6140 		 prog->name, relo_idx, insn_idx, ext->name);
6141 
6142 	/* we turn kfunc call into invalid helper call with identifiable constant */
6143 	insn->code = BPF_JMP | BPF_CALL;
6144 	insn->dst_reg = 0;
6145 	insn->src_reg = 0;
6146 	insn->off = 0;
6147 	/* if this instruction is reachable (not a dead code),
6148 	 * verifier will complain with something like:
6149 	 * invalid func unknown#2001000123
6150 	 * where lower 123 is extern index into obj->externs[] array
6151 	 */
6152 	insn->imm = POISON_CALL_KFUNC_BASE + ext_idx;
6153 }
6154 
6155 /* Relocate data references within program code:
6156  *  - map references;
6157  *  - global variable references;
6158  *  - extern references.
6159  */
6160 static int
6161 bpf_object__relocate_data(struct bpf_object *obj, struct bpf_program *prog)
6162 {
6163 	int i;
6164 
6165 	for (i = 0; i < prog->nr_reloc; i++) {
6166 		struct reloc_desc *relo = &prog->reloc_desc[i];
6167 		struct bpf_insn *insn = &prog->insns[relo->insn_idx];
6168 		const struct bpf_map *map;
6169 		struct extern_desc *ext;
6170 
6171 		switch (relo->type) {
6172 		case RELO_LD64:
6173 			map = &obj->maps[relo->map_idx];
6174 			if (obj->gen_loader) {
6175 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX;
6176 				insn[0].imm = relo->map_idx;
6177 			} else if (map->autocreate) {
6178 				insn[0].src_reg = BPF_PSEUDO_MAP_FD;
6179 				insn[0].imm = map->fd;
6180 			} else {
6181 				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
6182 						   relo->map_idx, map);
6183 			}
6184 			break;
6185 		case RELO_DATA:
6186 			map = &obj->maps[relo->map_idx];
6187 			insn[1].imm = insn[0].imm + relo->sym_off;
6188 			if (obj->gen_loader) {
6189 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
6190 				insn[0].imm = relo->map_idx;
6191 			} else if (map->autocreate) {
6192 				insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6193 				insn[0].imm = map->fd;
6194 			} else {
6195 				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
6196 						   relo->map_idx, map);
6197 			}
6198 			break;
6199 		case RELO_EXTERN_LD64:
6200 			ext = &obj->externs[relo->ext_idx];
6201 			if (ext->type == EXT_KCFG) {
6202 				if (obj->gen_loader) {
6203 					insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
6204 					insn[0].imm = obj->kconfig_map_idx;
6205 				} else {
6206 					insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
6207 					insn[0].imm = obj->maps[obj->kconfig_map_idx].fd;
6208 				}
6209 				insn[1].imm = ext->kcfg.data_off;
6210 			} else /* EXT_KSYM */ {
6211 				if (ext->ksym.type_id && ext->is_set) { /* typed ksyms */
6212 					insn[0].src_reg = BPF_PSEUDO_BTF_ID;
6213 					insn[0].imm = ext->ksym.kernel_btf_id;
6214 					insn[1].imm = ext->ksym.kernel_btf_obj_fd;
6215 				} else { /* typeless ksyms or unresolved typed ksyms */
6216 					insn[0].imm = (__u32)ext->ksym.addr;
6217 					insn[1].imm = ext->ksym.addr >> 32;
6218 				}
6219 			}
6220 			break;
6221 		case RELO_EXTERN_CALL:
6222 			ext = &obj->externs[relo->ext_idx];
6223 			insn[0].src_reg = BPF_PSEUDO_KFUNC_CALL;
6224 			if (ext->is_set) {
6225 				insn[0].imm = ext->ksym.kernel_btf_id;
6226 				insn[0].off = ext->ksym.btf_fd_idx;
6227 			} else { /* unresolved weak kfunc call */
6228 				poison_kfunc_call(prog, i, relo->insn_idx, insn,
6229 						  relo->ext_idx, ext);
6230 			}
6231 			break;
6232 		case RELO_SUBPROG_ADDR:
6233 			if (insn[0].src_reg != BPF_PSEUDO_FUNC) {
6234 				pr_warn("prog '%s': relo #%d: bad insn\n",
6235 					prog->name, i);
6236 				return -EINVAL;
6237 			}
6238 			/* handled already */
6239 			break;
6240 		case RELO_CALL:
6241 			/* handled already */
6242 			break;
6243 		case RELO_CORE:
6244 			/* will be handled by bpf_program_record_relos() */
6245 			break;
6246 		default:
6247 			pr_warn("prog '%s': relo #%d: bad relo type %d\n",
6248 				prog->name, i, relo->type);
6249 			return -EINVAL;
6250 		}
6251 	}
6252 
6253 	return 0;
6254 }
6255 
6256 static int adjust_prog_btf_ext_info(const struct bpf_object *obj,
6257 				    const struct bpf_program *prog,
6258 				    const struct btf_ext_info *ext_info,
6259 				    void **prog_info, __u32 *prog_rec_cnt,
6260 				    __u32 *prog_rec_sz)
6261 {
6262 	void *copy_start = NULL, *copy_end = NULL;
6263 	void *rec, *rec_end, *new_prog_info;
6264 	const struct btf_ext_info_sec *sec;
6265 	size_t old_sz, new_sz;
6266 	int i, sec_num, sec_idx, off_adj;
6267 
6268 	sec_num = 0;
6269 	for_each_btf_ext_sec(ext_info, sec) {
6270 		sec_idx = ext_info->sec_idxs[sec_num];
6271 		sec_num++;
6272 		if (prog->sec_idx != sec_idx)
6273 			continue;
6274 
6275 		for_each_btf_ext_rec(ext_info, sec, i, rec) {
6276 			__u32 insn_off = *(__u32 *)rec / BPF_INSN_SZ;
6277 
6278 			if (insn_off < prog->sec_insn_off)
6279 				continue;
6280 			if (insn_off >= prog->sec_insn_off + prog->sec_insn_cnt)
6281 				break;
6282 
6283 			if (!copy_start)
6284 				copy_start = rec;
6285 			copy_end = rec + ext_info->rec_size;
6286 		}
6287 
6288 		if (!copy_start)
6289 			return -ENOENT;
6290 
6291 		/* append func/line info of a given (sub-)program to the main
6292 		 * program func/line info
6293 		 */
6294 		old_sz = (size_t)(*prog_rec_cnt) * ext_info->rec_size;
6295 		new_sz = old_sz + (copy_end - copy_start);
6296 		new_prog_info = realloc(*prog_info, new_sz);
6297 		if (!new_prog_info)
6298 			return -ENOMEM;
6299 		*prog_info = new_prog_info;
6300 		*prog_rec_cnt = new_sz / ext_info->rec_size;
6301 		memcpy(new_prog_info + old_sz, copy_start, copy_end - copy_start);
6302 
6303 		/* Kernel instruction offsets are in units of 8-byte
6304 		 * instructions, while .BTF.ext instruction offsets generated
6305 		 * by Clang are in units of bytes. So convert Clang offsets
6306 		 * into kernel offsets and adjust offset according to program
6307 		 * relocated position.
6308 		 */
6309 		off_adj = prog->sub_insn_off - prog->sec_insn_off;
6310 		rec = new_prog_info + old_sz;
6311 		rec_end = new_prog_info + new_sz;
6312 		for (; rec < rec_end; rec += ext_info->rec_size) {
6313 			__u32 *insn_off = rec;
6314 
6315 			*insn_off = *insn_off / BPF_INSN_SZ + off_adj;
6316 		}
6317 		*prog_rec_sz = ext_info->rec_size;
6318 		return 0;
6319 	}
6320 
6321 	return -ENOENT;
6322 }
6323 
6324 static int
6325 reloc_prog_func_and_line_info(const struct bpf_object *obj,
6326 			      struct bpf_program *main_prog,
6327 			      const struct bpf_program *prog)
6328 {
6329 	int err;
6330 
6331 	/* no .BTF.ext relocation if .BTF.ext is missing or kernel doesn't
6332 	 * support func/line info
6333 	 */
6334 	if (!obj->btf_ext || !kernel_supports(obj, FEAT_BTF_FUNC))
6335 		return 0;
6336 
6337 	/* only attempt func info relocation if main program's func_info
6338 	 * relocation was successful
6339 	 */
6340 	if (main_prog != prog && !main_prog->func_info)
6341 		goto line_info;
6342 
6343 	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->func_info,
6344 				       &main_prog->func_info,
6345 				       &main_prog->func_info_cnt,
6346 				       &main_prog->func_info_rec_size);
6347 	if (err) {
6348 		if (err != -ENOENT) {
6349 			pr_warn("prog '%s': error relocating .BTF.ext function info: %s\n",
6350 				prog->name, errstr(err));
6351 			return err;
6352 		}
6353 		if (main_prog->func_info) {
6354 			/*
6355 			 * Some info has already been found but has problem
6356 			 * in the last btf_ext reloc. Must have to error out.
6357 			 */
6358 			pr_warn("prog '%s': missing .BTF.ext function info.\n", prog->name);
6359 			return err;
6360 		}
6361 		/* Have problem loading the very first info. Ignore the rest. */
6362 		pr_warn("prog '%s': missing .BTF.ext function info for the main program, skipping all of .BTF.ext func info.\n",
6363 			prog->name);
6364 	}
6365 
6366 line_info:
6367 	/* don't relocate line info if main program's relocation failed */
6368 	if (main_prog != prog && !main_prog->line_info)
6369 		return 0;
6370 
6371 	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->line_info,
6372 				       &main_prog->line_info,
6373 				       &main_prog->line_info_cnt,
6374 				       &main_prog->line_info_rec_size);
6375 	if (err) {
6376 		if (err != -ENOENT) {
6377 			pr_warn("prog '%s': error relocating .BTF.ext line info: %s\n",
6378 				prog->name, errstr(err));
6379 			return err;
6380 		}
6381 		if (main_prog->line_info) {
6382 			/*
6383 			 * Some info has already been found but has problem
6384 			 * in the last btf_ext reloc. Must have to error out.
6385 			 */
6386 			pr_warn("prog '%s': missing .BTF.ext line info.\n", prog->name);
6387 			return err;
6388 		}
6389 		/* Have problem loading the very first info. Ignore the rest. */
6390 		pr_warn("prog '%s': missing .BTF.ext line info for the main program, skipping all of .BTF.ext line info.\n",
6391 			prog->name);
6392 	}
6393 	return 0;
6394 }
6395 
6396 static int cmp_relo_by_insn_idx(const void *key, const void *elem)
6397 {
6398 	size_t insn_idx = *(const size_t *)key;
6399 	const struct reloc_desc *relo = elem;
6400 
6401 	if (insn_idx == relo->insn_idx)
6402 		return 0;
6403 	return insn_idx < relo->insn_idx ? -1 : 1;
6404 }
6405 
6406 static struct reloc_desc *find_prog_insn_relo(const struct bpf_program *prog, size_t insn_idx)
6407 {
6408 	if (!prog->nr_reloc)
6409 		return NULL;
6410 	return bsearch(&insn_idx, prog->reloc_desc, prog->nr_reloc,
6411 		       sizeof(*prog->reloc_desc), cmp_relo_by_insn_idx);
6412 }
6413 
6414 static int append_subprog_relos(struct bpf_program *main_prog, struct bpf_program *subprog)
6415 {
6416 	int new_cnt = main_prog->nr_reloc + subprog->nr_reloc;
6417 	struct reloc_desc *relos;
6418 	int i;
6419 
6420 	if (main_prog == subprog)
6421 		return 0;
6422 	relos = libbpf_reallocarray(main_prog->reloc_desc, new_cnt, sizeof(*relos));
6423 	/* if new count is zero, reallocarray can return a valid NULL result;
6424 	 * in this case the previous pointer will be freed, so we *have to*
6425 	 * reassign old pointer to the new value (even if it's NULL)
6426 	 */
6427 	if (!relos && new_cnt)
6428 		return -ENOMEM;
6429 	if (subprog->nr_reloc)
6430 		memcpy(relos + main_prog->nr_reloc, subprog->reloc_desc,
6431 		       sizeof(*relos) * subprog->nr_reloc);
6432 
6433 	for (i = main_prog->nr_reloc; i < new_cnt; i++)
6434 		relos[i].insn_idx += subprog->sub_insn_off;
6435 	/* After insn_idx adjustment the 'relos' array is still sorted
6436 	 * by insn_idx and doesn't break bsearch.
6437 	 */
6438 	main_prog->reloc_desc = relos;
6439 	main_prog->nr_reloc = new_cnt;
6440 	return 0;
6441 }
6442 
6443 static int
6444 bpf_object__append_subprog_code(struct bpf_object *obj, struct bpf_program *main_prog,
6445 				struct bpf_program *subprog)
6446 {
6447        struct bpf_insn *insns;
6448        size_t new_cnt;
6449        int err;
6450 
6451        subprog->sub_insn_off = main_prog->insns_cnt;
6452 
6453        new_cnt = main_prog->insns_cnt + subprog->insns_cnt;
6454        insns = libbpf_reallocarray(main_prog->insns, new_cnt, sizeof(*insns));
6455        if (!insns) {
6456                pr_warn("prog '%s': failed to realloc prog code\n", main_prog->name);
6457                return -ENOMEM;
6458        }
6459        main_prog->insns = insns;
6460        main_prog->insns_cnt = new_cnt;
6461 
6462        memcpy(main_prog->insns + subprog->sub_insn_off, subprog->insns,
6463               subprog->insns_cnt * sizeof(*insns));
6464 
6465        pr_debug("prog '%s': added %zu insns from sub-prog '%s'\n",
6466                 main_prog->name, subprog->insns_cnt, subprog->name);
6467 
6468        /* The subprog insns are now appended. Append its relos too. */
6469        err = append_subprog_relos(main_prog, subprog);
6470        if (err)
6471                return err;
6472        return 0;
6473 }
6474 
6475 static int
6476 bpf_object__reloc_code(struct bpf_object *obj, struct bpf_program *main_prog,
6477 		       struct bpf_program *prog)
6478 {
6479 	size_t sub_insn_idx, insn_idx;
6480 	struct bpf_program *subprog;
6481 	struct reloc_desc *relo;
6482 	struct bpf_insn *insn;
6483 	int err;
6484 
6485 	err = reloc_prog_func_and_line_info(obj, main_prog, prog);
6486 	if (err)
6487 		return err;
6488 
6489 	for (insn_idx = 0; insn_idx < prog->sec_insn_cnt; insn_idx++) {
6490 		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6491 		if (!insn_is_subprog_call(insn) && !insn_is_pseudo_func(insn))
6492 			continue;
6493 
6494 		relo = find_prog_insn_relo(prog, insn_idx);
6495 		if (relo && relo->type == RELO_EXTERN_CALL)
6496 			/* kfunc relocations will be handled later
6497 			 * in bpf_object__relocate_data()
6498 			 */
6499 			continue;
6500 		if (relo && relo->type != RELO_CALL && relo->type != RELO_SUBPROG_ADDR) {
6501 			pr_warn("prog '%s': unexpected relo for insn #%zu, type %d\n",
6502 				prog->name, insn_idx, relo->type);
6503 			return -LIBBPF_ERRNO__RELOC;
6504 		}
6505 		if (relo) {
6506 			/* sub-program instruction index is a combination of
6507 			 * an offset of a symbol pointed to by relocation and
6508 			 * call instruction's imm field; for global functions,
6509 			 * call always has imm = -1, but for static functions
6510 			 * relocation is against STT_SECTION and insn->imm
6511 			 * points to a start of a static function
6512 			 *
6513 			 * for subprog addr relocation, the relo->sym_off + insn->imm is
6514 			 * the byte offset in the corresponding section.
6515 			 */
6516 			if (relo->type == RELO_CALL)
6517 				sub_insn_idx = relo->sym_off / BPF_INSN_SZ + insn->imm + 1;
6518 			else
6519 				sub_insn_idx = (relo->sym_off + insn->imm) / BPF_INSN_SZ;
6520 		} else if (insn_is_pseudo_func(insn)) {
6521 			/*
6522 			 * RELO_SUBPROG_ADDR relo is always emitted even if both
6523 			 * functions are in the same section, so it shouldn't reach here.
6524 			 */
6525 			pr_warn("prog '%s': missing subprog addr relo for insn #%zu\n",
6526 				prog->name, insn_idx);
6527 			return -LIBBPF_ERRNO__RELOC;
6528 		} else {
6529 			/* if subprogram call is to a static function within
6530 			 * the same ELF section, there won't be any relocation
6531 			 * emitted, but it also means there is no additional
6532 			 * offset necessary, insns->imm is relative to
6533 			 * instruction's original position within the section
6534 			 */
6535 			sub_insn_idx = prog->sec_insn_off + insn_idx + insn->imm + 1;
6536 		}
6537 
6538 		/* we enforce that sub-programs should be in .text section */
6539 		subprog = find_prog_by_sec_insn(obj, obj->efile.text_shndx, sub_insn_idx);
6540 		if (!subprog) {
6541 			pr_warn("prog '%s': no .text section found yet sub-program call exists\n",
6542 				prog->name);
6543 			return -LIBBPF_ERRNO__RELOC;
6544 		}
6545 
6546 		/* if it's the first call instruction calling into this
6547 		 * subprogram (meaning this subprog hasn't been processed
6548 		 * yet) within the context of current main program:
6549 		 *   - append it at the end of main program's instructions blog;
6550 		 *   - process is recursively, while current program is put on hold;
6551 		 *   - if that subprogram calls some other not yet processes
6552 		 *   subprogram, same thing will happen recursively until
6553 		 *   there are no more unprocesses subprograms left to append
6554 		 *   and relocate.
6555 		 */
6556 		if (subprog->sub_insn_off == 0) {
6557 			err = bpf_object__append_subprog_code(obj, main_prog, subprog);
6558 			if (err)
6559 				return err;
6560 			err = bpf_object__reloc_code(obj, main_prog, subprog);
6561 			if (err)
6562 				return err;
6563 		}
6564 
6565 		/* main_prog->insns memory could have been re-allocated, so
6566 		 * calculate pointer again
6567 		 */
6568 		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6569 		/* calculate correct instruction position within current main
6570 		 * prog; each main prog can have a different set of
6571 		 * subprograms appended (potentially in different order as
6572 		 * well), so position of any subprog can be different for
6573 		 * different main programs
6574 		 */
6575 		insn->imm = subprog->sub_insn_off - (prog->sub_insn_off + insn_idx) - 1;
6576 
6577 		pr_debug("prog '%s': insn #%zu relocated, imm %d points to subprog '%s' (now at %zu offset)\n",
6578 			 prog->name, insn_idx, insn->imm, subprog->name, subprog->sub_insn_off);
6579 	}
6580 
6581 	return 0;
6582 }
6583 
6584 /*
6585  * Relocate sub-program calls.
6586  *
6587  * Algorithm operates as follows. Each entry-point BPF program (referred to as
6588  * main prog) is processed separately. For each subprog (non-entry functions,
6589  * that can be called from either entry progs or other subprogs) gets their
6590  * sub_insn_off reset to zero. This serves as indicator that this subprogram
6591  * hasn't been yet appended and relocated within current main prog. Once its
6592  * relocated, sub_insn_off will point at the position within current main prog
6593  * where given subprog was appended. This will further be used to relocate all
6594  * the call instructions jumping into this subprog.
6595  *
6596  * We start with main program and process all call instructions. If the call
6597  * is into a subprog that hasn't been processed (i.e., subprog->sub_insn_off
6598  * is zero), subprog instructions are appended at the end of main program's
6599  * instruction array. Then main program is "put on hold" while we recursively
6600  * process newly appended subprogram. If that subprogram calls into another
6601  * subprogram that hasn't been appended, new subprogram is appended again to
6602  * the *main* prog's instructions (subprog's instructions are always left
6603  * untouched, as they need to be in unmodified state for subsequent main progs
6604  * and subprog instructions are always sent only as part of a main prog) and
6605  * the process continues recursively. Once all the subprogs called from a main
6606  * prog or any of its subprogs are appended (and relocated), all their
6607  * positions within finalized instructions array are known, so it's easy to
6608  * rewrite call instructions with correct relative offsets, corresponding to
6609  * desired target subprog.
6610  *
6611  * Its important to realize that some subprogs might not be called from some
6612  * main prog and any of its called/used subprogs. Those will keep their
6613  * subprog->sub_insn_off as zero at all times and won't be appended to current
6614  * main prog and won't be relocated within the context of current main prog.
6615  * They might still be used from other main progs later.
6616  *
6617  * Visually this process can be shown as below. Suppose we have two main
6618  * programs mainA and mainB and BPF object contains three subprogs: subA,
6619  * subB, and subC. mainA calls only subA, mainB calls only subC, but subA and
6620  * subC both call subB:
6621  *
6622  *        +--------+ +-------+
6623  *        |        v v       |
6624  *     +--+---+ +--+-+-+ +---+--+
6625  *     | subA | | subB | | subC |
6626  *     +--+---+ +------+ +---+--+
6627  *        ^                  ^
6628  *        |                  |
6629  *    +---+-------+   +------+----+
6630  *    |   mainA   |   |   mainB   |
6631  *    +-----------+   +-----------+
6632  *
6633  * We'll start relocating mainA, will find subA, append it and start
6634  * processing sub A recursively:
6635  *
6636  *    +-----------+------+
6637  *    |   mainA   | subA |
6638  *    +-----------+------+
6639  *
6640  * At this point we notice that subB is used from subA, so we append it and
6641  * relocate (there are no further subcalls from subB):
6642  *
6643  *    +-----------+------+------+
6644  *    |   mainA   | subA | subB |
6645  *    +-----------+------+------+
6646  *
6647  * At this point, we relocate subA calls, then go one level up and finish with
6648  * relocatin mainA calls. mainA is done.
6649  *
6650  * For mainB process is similar but results in different order. We start with
6651  * mainB and skip subA and subB, as mainB never calls them (at least
6652  * directly), but we see subC is needed, so we append and start processing it:
6653  *
6654  *    +-----------+------+
6655  *    |   mainB   | subC |
6656  *    +-----------+------+
6657  * Now we see subC needs subB, so we go back to it, append and relocate it:
6658  *
6659  *    +-----------+------+------+
6660  *    |   mainB   | subC | subB |
6661  *    +-----------+------+------+
6662  *
6663  * At this point we unwind recursion, relocate calls in subC, then in mainB.
6664  */
6665 static int
6666 bpf_object__relocate_calls(struct bpf_object *obj, struct bpf_program *prog)
6667 {
6668 	struct bpf_program *subprog;
6669 	int i, err;
6670 
6671 	/* mark all subprogs as not relocated (yet) within the context of
6672 	 * current main program
6673 	 */
6674 	for (i = 0; i < obj->nr_programs; i++) {
6675 		subprog = &obj->programs[i];
6676 		if (!prog_is_subprog(obj, subprog))
6677 			continue;
6678 
6679 		subprog->sub_insn_off = 0;
6680 	}
6681 
6682 	err = bpf_object__reloc_code(obj, prog, prog);
6683 	if (err)
6684 		return err;
6685 
6686 	return 0;
6687 }
6688 
6689 static void
6690 bpf_object__free_relocs(struct bpf_object *obj)
6691 {
6692 	struct bpf_program *prog;
6693 	int i;
6694 
6695 	/* free up relocation descriptors */
6696 	for (i = 0; i < obj->nr_programs; i++) {
6697 		prog = &obj->programs[i];
6698 		zfree(&prog->reloc_desc);
6699 		prog->nr_reloc = 0;
6700 	}
6701 }
6702 
6703 static int cmp_relocs(const void *_a, const void *_b)
6704 {
6705 	const struct reloc_desc *a = _a;
6706 	const struct reloc_desc *b = _b;
6707 
6708 	if (a->insn_idx != b->insn_idx)
6709 		return a->insn_idx < b->insn_idx ? -1 : 1;
6710 
6711 	/* no two relocations should have the same insn_idx, but ... */
6712 	if (a->type != b->type)
6713 		return a->type < b->type ? -1 : 1;
6714 
6715 	return 0;
6716 }
6717 
6718 static void bpf_object__sort_relos(struct bpf_object *obj)
6719 {
6720 	int i;
6721 
6722 	for (i = 0; i < obj->nr_programs; i++) {
6723 		struct bpf_program *p = &obj->programs[i];
6724 
6725 		if (!p->nr_reloc)
6726 			continue;
6727 
6728 		qsort(p->reloc_desc, p->nr_reloc, sizeof(*p->reloc_desc), cmp_relocs);
6729 	}
6730 }
6731 
6732 static int bpf_prog_assign_exc_cb(struct bpf_object *obj, struct bpf_program *prog)
6733 {
6734 	const char *str = "exception_callback:";
6735 	size_t pfx_len = strlen(str);
6736 	int i, j, n;
6737 
6738 	if (!obj->btf || !kernel_supports(obj, FEAT_BTF_DECL_TAG))
6739 		return 0;
6740 
6741 	n = btf__type_cnt(obj->btf);
6742 	for (i = 1; i < n; i++) {
6743 		const char *name;
6744 		struct btf_type *t;
6745 
6746 		t = btf_type_by_id(obj->btf, i);
6747 		if (!btf_is_decl_tag(t) || btf_decl_tag(t)->component_idx != -1)
6748 			continue;
6749 
6750 		name = btf__str_by_offset(obj->btf, t->name_off);
6751 		if (strncmp(name, str, pfx_len) != 0)
6752 			continue;
6753 
6754 		t = btf_type_by_id(obj->btf, t->type);
6755 		if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL) {
6756 			pr_warn("prog '%s': exception_callback:<value> decl tag not applied to the main program\n",
6757 				prog->name);
6758 			return -EINVAL;
6759 		}
6760 		if (strcmp(prog->name, btf__str_by_offset(obj->btf, t->name_off)) != 0)
6761 			continue;
6762 		/* Multiple callbacks are specified for the same prog,
6763 		 * the verifier will eventually return an error for this
6764 		 * case, hence simply skip appending a subprog.
6765 		 */
6766 		if (prog->exception_cb_idx >= 0) {
6767 			prog->exception_cb_idx = -1;
6768 			break;
6769 		}
6770 
6771 		name += pfx_len;
6772 		if (str_is_empty(name)) {
6773 			pr_warn("prog '%s': exception_callback:<value> decl tag contains empty value\n",
6774 				prog->name);
6775 			return -EINVAL;
6776 		}
6777 
6778 		for (j = 0; j < obj->nr_programs; j++) {
6779 			struct bpf_program *subprog = &obj->programs[j];
6780 
6781 			if (!prog_is_subprog(obj, subprog))
6782 				continue;
6783 			if (strcmp(name, subprog->name) != 0)
6784 				continue;
6785 			/* Enforce non-hidden, as from verifier point of
6786 			 * view it expects global functions, whereas the
6787 			 * mark_btf_static fixes up linkage as static.
6788 			 */
6789 			if (!subprog->sym_global || subprog->mark_btf_static) {
6790 				pr_warn("prog '%s': exception callback %s must be a global non-hidden function\n",
6791 					prog->name, subprog->name);
6792 				return -EINVAL;
6793 			}
6794 			/* Let's see if we already saw a static exception callback with the same name */
6795 			if (prog->exception_cb_idx >= 0) {
6796 				pr_warn("prog '%s': multiple subprogs with same name as exception callback '%s'\n",
6797 					prog->name, subprog->name);
6798 				return -EINVAL;
6799 			}
6800 			prog->exception_cb_idx = j;
6801 			break;
6802 		}
6803 
6804 		if (prog->exception_cb_idx >= 0)
6805 			continue;
6806 
6807 		pr_warn("prog '%s': cannot find exception callback '%s'\n", prog->name, name);
6808 		return -ENOENT;
6809 	}
6810 
6811 	return 0;
6812 }
6813 
6814 static struct {
6815 	enum bpf_prog_type prog_type;
6816 	const char *ctx_name;
6817 } global_ctx_map[] = {
6818 	{ BPF_PROG_TYPE_CGROUP_DEVICE,           "bpf_cgroup_dev_ctx" },
6819 	{ BPF_PROG_TYPE_CGROUP_SKB,              "__sk_buff" },
6820 	{ BPF_PROG_TYPE_CGROUP_SOCK,             "bpf_sock" },
6821 	{ BPF_PROG_TYPE_CGROUP_SOCK_ADDR,        "bpf_sock_addr" },
6822 	{ BPF_PROG_TYPE_CGROUP_SOCKOPT,          "bpf_sockopt" },
6823 	{ BPF_PROG_TYPE_CGROUP_SYSCTL,           "bpf_sysctl" },
6824 	{ BPF_PROG_TYPE_FLOW_DISSECTOR,          "__sk_buff" },
6825 	{ BPF_PROG_TYPE_KPROBE,                  "bpf_user_pt_regs_t" },
6826 	{ BPF_PROG_TYPE_LWT_IN,                  "__sk_buff" },
6827 	{ BPF_PROG_TYPE_LWT_OUT,                 "__sk_buff" },
6828 	{ BPF_PROG_TYPE_LWT_SEG6LOCAL,           "__sk_buff" },
6829 	{ BPF_PROG_TYPE_LWT_XMIT,                "__sk_buff" },
6830 	{ BPF_PROG_TYPE_NETFILTER,               "bpf_nf_ctx" },
6831 	{ BPF_PROG_TYPE_PERF_EVENT,              "bpf_perf_event_data" },
6832 	{ BPF_PROG_TYPE_RAW_TRACEPOINT,          "bpf_raw_tracepoint_args" },
6833 	{ BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE, "bpf_raw_tracepoint_args" },
6834 	{ BPF_PROG_TYPE_SCHED_ACT,               "__sk_buff" },
6835 	{ BPF_PROG_TYPE_SCHED_CLS,               "__sk_buff" },
6836 	{ BPF_PROG_TYPE_SK_LOOKUP,               "bpf_sk_lookup" },
6837 	{ BPF_PROG_TYPE_SK_MSG,                  "sk_msg_md" },
6838 	{ BPF_PROG_TYPE_SK_REUSEPORT,            "sk_reuseport_md" },
6839 	{ BPF_PROG_TYPE_SK_SKB,                  "__sk_buff" },
6840 	{ BPF_PROG_TYPE_SOCK_OPS,                "bpf_sock_ops" },
6841 	{ BPF_PROG_TYPE_SOCKET_FILTER,           "__sk_buff" },
6842 	{ BPF_PROG_TYPE_XDP,                     "xdp_md" },
6843 	/* all other program types don't have "named" context structs */
6844 };
6845 
6846 /* forward declarations for arch-specific underlying types of bpf_user_pt_regs_t typedef,
6847  * for below __builtin_types_compatible_p() checks;
6848  * with this approach we don't need any extra arch-specific #ifdef guards
6849  */
6850 struct pt_regs;
6851 struct user_pt_regs;
6852 struct user_regs_struct;
6853 
6854 static bool need_func_arg_type_fixup(const struct btf *btf, const struct bpf_program *prog,
6855 				     const char *subprog_name, int arg_idx,
6856 				     int arg_type_id, const char *ctx_name)
6857 {
6858 	const struct btf_type *t;
6859 	const char *tname;
6860 
6861 	/* check if existing parameter already matches verifier expectations */
6862 	t = skip_mods_and_typedefs(btf, arg_type_id, NULL);
6863 	if (!btf_is_ptr(t))
6864 		goto out_warn;
6865 
6866 	/* typedef bpf_user_pt_regs_t is a special PITA case, valid for kprobe
6867 	 * and perf_event programs, so check this case early on and forget
6868 	 * about it for subsequent checks
6869 	 */
6870 	while (btf_is_mod(t))
6871 		t = btf__type_by_id(btf, t->type);
6872 	if (btf_is_typedef(t) &&
6873 	    (prog->type == BPF_PROG_TYPE_KPROBE || prog->type == BPF_PROG_TYPE_PERF_EVENT)) {
6874 		tname = btf__str_by_offset(btf, t->name_off) ?: "<anon>";
6875 		if (strcmp(tname, "bpf_user_pt_regs_t") == 0)
6876 			return false; /* canonical type for kprobe/perf_event */
6877 	}
6878 
6879 	/* now we can ignore typedefs moving forward */
6880 	t = skip_mods_and_typedefs(btf, t->type, NULL);
6881 
6882 	/* if it's `void *`, definitely fix up BTF info */
6883 	if (btf_is_void(t))
6884 		return true;
6885 
6886 	/* if it's already proper canonical type, no need to fix up */
6887 	tname = btf__str_by_offset(btf, t->name_off) ?: "<anon>";
6888 	if (btf_is_struct(t) && strcmp(tname, ctx_name) == 0)
6889 		return false;
6890 
6891 	/* special cases */
6892 	switch (prog->type) {
6893 	case BPF_PROG_TYPE_KPROBE:
6894 		/* `struct pt_regs *` is expected, but we need to fix up */
6895 		if (btf_is_struct(t) && strcmp(tname, "pt_regs") == 0)
6896 			return true;
6897 		break;
6898 	case BPF_PROG_TYPE_PERF_EVENT:
6899 		if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct pt_regs) &&
6900 		    btf_is_struct(t) && strcmp(tname, "pt_regs") == 0)
6901 			return true;
6902 		if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct user_pt_regs) &&
6903 		    btf_is_struct(t) && strcmp(tname, "user_pt_regs") == 0)
6904 			return true;
6905 		if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct user_regs_struct) &&
6906 		    btf_is_struct(t) && strcmp(tname, "user_regs_struct") == 0)
6907 			return true;
6908 		break;
6909 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
6910 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
6911 		/* allow u64* as ctx */
6912 		if (btf_is_int(t) && t->size == 8)
6913 			return true;
6914 		break;
6915 	default:
6916 		break;
6917 	}
6918 
6919 out_warn:
6920 	pr_warn("prog '%s': subprog '%s' arg#%d is expected to be of `struct %s *` type\n",
6921 		prog->name, subprog_name, arg_idx, ctx_name);
6922 	return false;
6923 }
6924 
6925 static int clone_func_btf_info(struct btf *btf, int orig_fn_id, struct bpf_program *prog)
6926 {
6927 	int fn_id, fn_proto_id, ret_type_id, orig_proto_id;
6928 	int i, err, arg_cnt, fn_name_off, linkage;
6929 	struct btf_type *fn_t, *fn_proto_t, *t;
6930 	struct btf_param *p;
6931 
6932 	/* caller already validated FUNC -> FUNC_PROTO validity */
6933 	fn_t = btf_type_by_id(btf, orig_fn_id);
6934 	fn_proto_t = btf_type_by_id(btf, fn_t->type);
6935 
6936 	/* Note that each btf__add_xxx() operation invalidates
6937 	 * all btf_type and string pointers, so we need to be
6938 	 * very careful when cloning BTF types. BTF type
6939 	 * pointers have to be always refetched. And to avoid
6940 	 * problems with invalidated string pointers, we
6941 	 * add empty strings initially, then just fix up
6942 	 * name_off offsets in place. Offsets are stable for
6943 	 * existing strings, so that works out.
6944 	 */
6945 	fn_name_off = fn_t->name_off; /* we are about to invalidate fn_t */
6946 	linkage = btf_func_linkage(fn_t);
6947 	orig_proto_id = fn_t->type; /* original FUNC_PROTO ID */
6948 	ret_type_id = fn_proto_t->type; /* fn_proto_t will be invalidated */
6949 	arg_cnt = btf_vlen(fn_proto_t);
6950 
6951 	/* clone FUNC_PROTO and its params */
6952 	fn_proto_id = btf__add_func_proto(btf, ret_type_id);
6953 	if (fn_proto_id < 0)
6954 		return -EINVAL;
6955 
6956 	for (i = 0; i < arg_cnt; i++) {
6957 		int name_off;
6958 
6959 		/* copy original parameter data */
6960 		t = btf_type_by_id(btf, orig_proto_id);
6961 		p = &btf_params(t)[i];
6962 		name_off = p->name_off;
6963 
6964 		err = btf__add_func_param(btf, "", p->type);
6965 		if (err)
6966 			return err;
6967 
6968 		fn_proto_t = btf_type_by_id(btf, fn_proto_id);
6969 		p = &btf_params(fn_proto_t)[i];
6970 		p->name_off = name_off; /* use remembered str offset */
6971 	}
6972 
6973 	/* clone FUNC now, btf__add_func() enforces non-empty name, so use
6974 	 * entry program's name as a placeholder, which we replace immediately
6975 	 * with original name_off
6976 	 */
6977 	fn_id = btf__add_func(btf, prog->name, linkage, fn_proto_id);
6978 	if (fn_id < 0)
6979 		return -EINVAL;
6980 
6981 	fn_t = btf_type_by_id(btf, fn_id);
6982 	fn_t->name_off = fn_name_off; /* reuse original string */
6983 
6984 	return fn_id;
6985 }
6986 
6987 /* Check if main program or global subprog's function prototype has `arg:ctx`
6988  * argument tags, and, if necessary, substitute correct type to match what BPF
6989  * verifier would expect, taking into account specific program type. This
6990  * allows to support __arg_ctx tag transparently on old kernels that don't yet
6991  * have a native support for it in the verifier, making user's life much
6992  * easier.
6993  */
6994 static int bpf_program_fixup_func_info(struct bpf_object *obj, struct bpf_program *prog)
6995 {
6996 	const char *ctx_name = NULL, *ctx_tag = "arg:ctx", *fn_name;
6997 	struct bpf_func_info_min *func_rec;
6998 	struct btf_type *fn_t, *fn_proto_t;
6999 	struct btf *btf = obj->btf;
7000 	const struct btf_type *t;
7001 	struct btf_param *p;
7002 	int ptr_id = 0, struct_id, tag_id, orig_fn_id;
7003 	int i, n, arg_idx, arg_cnt, err, rec_idx;
7004 	int *orig_ids;
7005 
7006 	/* no .BTF.ext, no problem */
7007 	if (!obj->btf_ext || !prog->func_info)
7008 		return 0;
7009 
7010 	/* don't do any fix ups if kernel natively supports __arg_ctx */
7011 	if (kernel_supports(obj, FEAT_ARG_CTX_TAG))
7012 		return 0;
7013 
7014 	/* some BPF program types just don't have named context structs, so
7015 	 * this fallback mechanism doesn't work for them
7016 	 */
7017 	for (i = 0; i < ARRAY_SIZE(global_ctx_map); i++) {
7018 		if (global_ctx_map[i].prog_type != prog->type)
7019 			continue;
7020 		ctx_name = global_ctx_map[i].ctx_name;
7021 		break;
7022 	}
7023 	if (!ctx_name)
7024 		return 0;
7025 
7026 	/* remember original func BTF IDs to detect if we already cloned them */
7027 	orig_ids = calloc(prog->func_info_cnt, sizeof(*orig_ids));
7028 	if (!orig_ids)
7029 		return -ENOMEM;
7030 	for (i = 0; i < prog->func_info_cnt; i++) {
7031 		func_rec = prog->func_info + prog->func_info_rec_size * i;
7032 		orig_ids[i] = func_rec->type_id;
7033 	}
7034 
7035 	/* go through each DECL_TAG with "arg:ctx" and see if it points to one
7036 	 * of our subprogs; if yes and subprog is global and needs adjustment,
7037 	 * clone and adjust FUNC -> FUNC_PROTO combo
7038 	 */
7039 	for (i = 1, n = btf__type_cnt(btf); i < n; i++) {
7040 		/* only DECL_TAG with "arg:ctx" value are interesting */
7041 		t = btf__type_by_id(btf, i);
7042 		if (!btf_is_decl_tag(t))
7043 			continue;
7044 		if (strcmp(btf__str_by_offset(btf, t->name_off), ctx_tag) != 0)
7045 			continue;
7046 
7047 		/* only global funcs need adjustment, if at all */
7048 		orig_fn_id = t->type;
7049 		fn_t = btf_type_by_id(btf, orig_fn_id);
7050 		if (!btf_is_func(fn_t) || btf_func_linkage(fn_t) != BTF_FUNC_GLOBAL)
7051 			continue;
7052 
7053 		/* sanity check FUNC -> FUNC_PROTO chain, just in case */
7054 		fn_proto_t = btf_type_by_id(btf, fn_t->type);
7055 		if (!fn_proto_t || !btf_is_func_proto(fn_proto_t))
7056 			continue;
7057 
7058 		/* find corresponding func_info record */
7059 		func_rec = NULL;
7060 		for (rec_idx = 0; rec_idx < prog->func_info_cnt; rec_idx++) {
7061 			if (orig_ids[rec_idx] == t->type) {
7062 				func_rec = prog->func_info + prog->func_info_rec_size * rec_idx;
7063 				break;
7064 			}
7065 		}
7066 		/* current main program doesn't call into this subprog */
7067 		if (!func_rec)
7068 			continue;
7069 
7070 		/* some more sanity checking of DECL_TAG */
7071 		arg_cnt = btf_vlen(fn_proto_t);
7072 		arg_idx = btf_decl_tag(t)->component_idx;
7073 		if (arg_idx < 0 || arg_idx >= arg_cnt)
7074 			continue;
7075 
7076 		/* check if we should fix up argument type */
7077 		p = &btf_params(fn_proto_t)[arg_idx];
7078 		fn_name = btf__str_by_offset(btf, fn_t->name_off) ?: "<anon>";
7079 		if (!need_func_arg_type_fixup(btf, prog, fn_name, arg_idx, p->type, ctx_name))
7080 			continue;
7081 
7082 		/* clone fn/fn_proto, unless we already did it for another arg */
7083 		if (func_rec->type_id == orig_fn_id) {
7084 			int fn_id;
7085 
7086 			fn_id = clone_func_btf_info(btf, orig_fn_id, prog);
7087 			if (fn_id < 0) {
7088 				err = fn_id;
7089 				goto err_out;
7090 			}
7091 
7092 			/* point func_info record to a cloned FUNC type */
7093 			func_rec->type_id = fn_id;
7094 		}
7095 
7096 		/* create PTR -> STRUCT type chain to mark PTR_TO_CTX argument;
7097 		 * we do it just once per main BPF program, as all global
7098 		 * funcs share the same program type, so need only PTR ->
7099 		 * STRUCT type chain
7100 		 */
7101 		if (ptr_id == 0) {
7102 			struct_id = btf__add_struct(btf, ctx_name, 0);
7103 			ptr_id = btf__add_ptr(btf, struct_id);
7104 			if (ptr_id < 0 || struct_id < 0) {
7105 				err = -EINVAL;
7106 				goto err_out;
7107 			}
7108 		}
7109 
7110 		/* for completeness, clone DECL_TAG and point it to cloned param */
7111 		tag_id = btf__add_decl_tag(btf, ctx_tag, func_rec->type_id, arg_idx);
7112 		if (tag_id < 0) {
7113 			err = -EINVAL;
7114 			goto err_out;
7115 		}
7116 
7117 		/* all the BTF manipulations invalidated pointers, refetch them */
7118 		fn_t = btf_type_by_id(btf, func_rec->type_id);
7119 		fn_proto_t = btf_type_by_id(btf, fn_t->type);
7120 
7121 		/* fix up type ID pointed to by param */
7122 		p = &btf_params(fn_proto_t)[arg_idx];
7123 		p->type = ptr_id;
7124 	}
7125 
7126 	free(orig_ids);
7127 	return 0;
7128 err_out:
7129 	free(orig_ids);
7130 	return err;
7131 }
7132 
7133 static int bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
7134 {
7135 	struct bpf_program *prog;
7136 	size_t i, j;
7137 	int err;
7138 
7139 	if (obj->btf_ext) {
7140 		err = bpf_object__relocate_core(obj, targ_btf_path);
7141 		if (err) {
7142 			pr_warn("failed to perform CO-RE relocations: %s\n",
7143 				errstr(err));
7144 			return err;
7145 		}
7146 		bpf_object__sort_relos(obj);
7147 	}
7148 
7149 	/* Before relocating calls pre-process relocations and mark
7150 	 * few ld_imm64 instructions that points to subprogs.
7151 	 * Otherwise bpf_object__reloc_code() later would have to consider
7152 	 * all ld_imm64 insns as relocation candidates. That would
7153 	 * reduce relocation speed, since amount of find_prog_insn_relo()
7154 	 * would increase and most of them will fail to find a relo.
7155 	 */
7156 	for (i = 0; i < obj->nr_programs; i++) {
7157 		prog = &obj->programs[i];
7158 		for (j = 0; j < prog->nr_reloc; j++) {
7159 			struct reloc_desc *relo = &prog->reloc_desc[j];
7160 			struct bpf_insn *insn = &prog->insns[relo->insn_idx];
7161 
7162 			/* mark the insn, so it's recognized by insn_is_pseudo_func() */
7163 			if (relo->type == RELO_SUBPROG_ADDR)
7164 				insn[0].src_reg = BPF_PSEUDO_FUNC;
7165 		}
7166 	}
7167 
7168 	/* relocate subprogram calls and append used subprograms to main
7169 	 * programs; each copy of subprogram code needs to be relocated
7170 	 * differently for each main program, because its code location might
7171 	 * have changed.
7172 	 * Append subprog relos to main programs to allow data relos to be
7173 	 * processed after text is completely relocated.
7174 	 */
7175 	for (i = 0; i < obj->nr_programs; i++) {
7176 		prog = &obj->programs[i];
7177 		/* sub-program's sub-calls are relocated within the context of
7178 		 * its main program only
7179 		 */
7180 		if (prog_is_subprog(obj, prog))
7181 			continue;
7182 		if (!prog->autoload)
7183 			continue;
7184 
7185 		err = bpf_object__relocate_calls(obj, prog);
7186 		if (err) {
7187 			pr_warn("prog '%s': failed to relocate calls: %s\n",
7188 				prog->name, errstr(err));
7189 			return err;
7190 		}
7191 
7192 		err = bpf_prog_assign_exc_cb(obj, prog);
7193 		if (err)
7194 			return err;
7195 		/* Now, also append exception callback if it has not been done already. */
7196 		if (prog->exception_cb_idx >= 0) {
7197 			struct bpf_program *subprog = &obj->programs[prog->exception_cb_idx];
7198 
7199 			/* Calling exception callback directly is disallowed, which the
7200 			 * verifier will reject later. In case it was processed already,
7201 			 * we can skip this step, otherwise for all other valid cases we
7202 			 * have to append exception callback now.
7203 			 */
7204 			if (subprog->sub_insn_off == 0) {
7205 				err = bpf_object__append_subprog_code(obj, prog, subprog);
7206 				if (err)
7207 					return err;
7208 				err = bpf_object__reloc_code(obj, prog, subprog);
7209 				if (err)
7210 					return err;
7211 			}
7212 		}
7213 	}
7214 	for (i = 0; i < obj->nr_programs; i++) {
7215 		prog = &obj->programs[i];
7216 		if (prog_is_subprog(obj, prog))
7217 			continue;
7218 		if (!prog->autoload)
7219 			continue;
7220 
7221 		/* Process data relos for main programs */
7222 		err = bpf_object__relocate_data(obj, prog);
7223 		if (err) {
7224 			pr_warn("prog '%s': failed to relocate data references: %s\n",
7225 				prog->name, errstr(err));
7226 			return err;
7227 		}
7228 
7229 		/* Fix up .BTF.ext information, if necessary */
7230 		err = bpf_program_fixup_func_info(obj, prog);
7231 		if (err) {
7232 			pr_warn("prog '%s': failed to perform .BTF.ext fix ups: %s\n",
7233 				prog->name, errstr(err));
7234 			return err;
7235 		}
7236 	}
7237 
7238 	return 0;
7239 }
7240 
7241 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
7242 					    Elf64_Shdr *shdr, Elf_Data *data);
7243 
7244 static int bpf_object__collect_map_relos(struct bpf_object *obj,
7245 					 Elf64_Shdr *shdr, Elf_Data *data)
7246 {
7247 	const int bpf_ptr_sz = 8, host_ptr_sz = sizeof(void *);
7248 	int i, j, nrels, new_sz;
7249 	const struct btf_var_secinfo *vi = NULL;
7250 	const struct btf_type *sec, *var, *def;
7251 	struct bpf_map *map = NULL, *targ_map = NULL;
7252 	struct bpf_program *targ_prog = NULL;
7253 	bool is_prog_array, is_map_in_map;
7254 	const struct btf_member *member;
7255 	const char *name, *mname, *type;
7256 	unsigned int moff;
7257 	Elf64_Sym *sym;
7258 	Elf64_Rel *rel;
7259 	void *tmp;
7260 
7261 	if (!obj->efile.btf_maps_sec_btf_id || !obj->btf)
7262 		return -EINVAL;
7263 	sec = btf__type_by_id(obj->btf, obj->efile.btf_maps_sec_btf_id);
7264 	if (!sec)
7265 		return -EINVAL;
7266 
7267 	nrels = shdr->sh_size / shdr->sh_entsize;
7268 	for (i = 0; i < nrels; i++) {
7269 		rel = elf_rel_by_idx(data, i);
7270 		if (!rel) {
7271 			pr_warn(".maps relo #%d: failed to get ELF relo\n", i);
7272 			return -LIBBPF_ERRNO__FORMAT;
7273 		}
7274 
7275 		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
7276 		if (!sym) {
7277 			pr_warn(".maps relo #%d: symbol %zx not found\n",
7278 				i, (size_t)ELF64_R_SYM(rel->r_info));
7279 			return -LIBBPF_ERRNO__FORMAT;
7280 		}
7281 		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
7282 
7283 		pr_debug(".maps relo #%d: for %zd value %zd rel->r_offset %zu name %d ('%s')\n",
7284 			 i, (ssize_t)(rel->r_info >> 32), (size_t)sym->st_value,
7285 			 (size_t)rel->r_offset, sym->st_name, name);
7286 
7287 		for (j = 0; j < obj->nr_maps; j++) {
7288 			map = &obj->maps[j];
7289 			if (map->sec_idx != obj->efile.btf_maps_shndx)
7290 				continue;
7291 
7292 			vi = btf_var_secinfos(sec) + map->btf_var_idx;
7293 			if (vi->offset <= rel->r_offset &&
7294 			    rel->r_offset + bpf_ptr_sz <= vi->offset + vi->size)
7295 				break;
7296 		}
7297 		if (j == obj->nr_maps) {
7298 			pr_warn(".maps relo #%d: cannot find map '%s' at rel->r_offset %zu\n",
7299 				i, name, (size_t)rel->r_offset);
7300 			return -EINVAL;
7301 		}
7302 
7303 		is_map_in_map = bpf_map_type__is_map_in_map(map->def.type);
7304 		is_prog_array = map->def.type == BPF_MAP_TYPE_PROG_ARRAY;
7305 		type = is_map_in_map ? "map" : "prog";
7306 		if (is_map_in_map) {
7307 			if (sym->st_shndx != obj->efile.btf_maps_shndx) {
7308 				pr_warn(".maps relo #%d: '%s' isn't a BTF-defined map\n",
7309 					i, name);
7310 				return -LIBBPF_ERRNO__RELOC;
7311 			}
7312 			if (map->def.type == BPF_MAP_TYPE_HASH_OF_MAPS &&
7313 			    map->def.key_size != sizeof(int)) {
7314 				pr_warn(".maps relo #%d: hash-of-maps '%s' should have key size %zu.\n",
7315 					i, map->name, sizeof(int));
7316 				return -EINVAL;
7317 			}
7318 			targ_map = bpf_object__find_map_by_name(obj, name);
7319 			if (!targ_map) {
7320 				pr_warn(".maps relo #%d: '%s' isn't a valid map reference\n",
7321 					i, name);
7322 				return -ESRCH;
7323 			}
7324 		} else if (is_prog_array) {
7325 			targ_prog = bpf_object__find_program_by_name(obj, name);
7326 			if (!targ_prog) {
7327 				pr_warn(".maps relo #%d: '%s' isn't a valid program reference\n",
7328 					i, name);
7329 				return -ESRCH;
7330 			}
7331 			if (targ_prog->sec_idx != sym->st_shndx ||
7332 			    targ_prog->sec_insn_off * 8 != sym->st_value ||
7333 			    prog_is_subprog(obj, targ_prog)) {
7334 				pr_warn(".maps relo #%d: '%s' isn't an entry-point program\n",
7335 					i, name);
7336 				return -LIBBPF_ERRNO__RELOC;
7337 			}
7338 		} else {
7339 			return -EINVAL;
7340 		}
7341 
7342 		var = btf__type_by_id(obj->btf, vi->type);
7343 		def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
7344 		if (btf_vlen(def) == 0)
7345 			return -EINVAL;
7346 		member = btf_members(def) + btf_vlen(def) - 1;
7347 		mname = btf__name_by_offset(obj->btf, member->name_off);
7348 		if (strcmp(mname, "values"))
7349 			return -EINVAL;
7350 
7351 		moff = btf_member_bit_offset(def, btf_vlen(def) - 1) / 8;
7352 		if (rel->r_offset - vi->offset < moff)
7353 			return -EINVAL;
7354 
7355 		moff = rel->r_offset - vi->offset - moff;
7356 		/* here we use BPF pointer size, which is always 64 bit, as we
7357 		 * are parsing ELF that was built for BPF target
7358 		 */
7359 		if (moff % bpf_ptr_sz)
7360 			return -EINVAL;
7361 		moff /= bpf_ptr_sz;
7362 		if (moff >= map->init_slots_sz) {
7363 			new_sz = moff + 1;
7364 			tmp = libbpf_reallocarray(map->init_slots, new_sz, host_ptr_sz);
7365 			if (!tmp)
7366 				return -ENOMEM;
7367 			map->init_slots = tmp;
7368 			memset(map->init_slots + map->init_slots_sz, 0,
7369 			       (new_sz - map->init_slots_sz) * host_ptr_sz);
7370 			map->init_slots_sz = new_sz;
7371 		}
7372 		map->init_slots[moff] = is_map_in_map ? (void *)targ_map : (void *)targ_prog;
7373 
7374 		pr_debug(".maps relo #%d: map '%s' slot [%d] points to %s '%s'\n",
7375 			 i, map->name, moff, type, name);
7376 	}
7377 
7378 	return 0;
7379 }
7380 
7381 static int bpf_object__collect_relos(struct bpf_object *obj)
7382 {
7383 	int i, err;
7384 
7385 	for (i = 0; i < obj->efile.sec_cnt; i++) {
7386 		struct elf_sec_desc *sec_desc = &obj->efile.secs[i];
7387 		Elf64_Shdr *shdr;
7388 		Elf_Data *data;
7389 		int idx;
7390 
7391 		if (sec_desc->sec_type != SEC_RELO)
7392 			continue;
7393 
7394 		shdr = sec_desc->shdr;
7395 		data = sec_desc->data;
7396 		idx = shdr->sh_info;
7397 
7398 		if (shdr->sh_type != SHT_REL || idx < 0 || idx >= obj->efile.sec_cnt) {
7399 			pr_warn("internal error at %d\n", __LINE__);
7400 			return -LIBBPF_ERRNO__INTERNAL;
7401 		}
7402 
7403 		if (obj->efile.secs[idx].sec_type == SEC_ST_OPS)
7404 			err = bpf_object__collect_st_ops_relos(obj, shdr, data);
7405 		else if (idx == obj->efile.btf_maps_shndx)
7406 			err = bpf_object__collect_map_relos(obj, shdr, data);
7407 		else
7408 			err = bpf_object__collect_prog_relos(obj, shdr, data);
7409 		if (err)
7410 			return err;
7411 	}
7412 
7413 	bpf_object__sort_relos(obj);
7414 	return 0;
7415 }
7416 
7417 static bool insn_is_helper_call(struct bpf_insn *insn, enum bpf_func_id *func_id)
7418 {
7419 	if (BPF_CLASS(insn->code) == BPF_JMP &&
7420 	    BPF_OP(insn->code) == BPF_CALL &&
7421 	    BPF_SRC(insn->code) == BPF_K &&
7422 	    insn->src_reg == 0 &&
7423 	    insn->dst_reg == 0) {
7424 		    *func_id = insn->imm;
7425 		    return true;
7426 	}
7427 	return false;
7428 }
7429 
7430 static int bpf_object__sanitize_prog(struct bpf_object *obj, struct bpf_program *prog)
7431 {
7432 	struct bpf_insn *insn = prog->insns;
7433 	enum bpf_func_id func_id;
7434 	int i;
7435 
7436 	if (obj->gen_loader)
7437 		return 0;
7438 
7439 	for (i = 0; i < prog->insns_cnt; i++, insn++) {
7440 		if (!insn_is_helper_call(insn, &func_id))
7441 			continue;
7442 
7443 		/* on kernels that don't yet support
7444 		 * bpf_probe_read_{kernel,user}[_str] helpers, fall back
7445 		 * to bpf_probe_read() which works well for old kernels
7446 		 */
7447 		switch (func_id) {
7448 		case BPF_FUNC_probe_read_kernel:
7449 		case BPF_FUNC_probe_read_user:
7450 			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
7451 				insn->imm = BPF_FUNC_probe_read;
7452 			break;
7453 		case BPF_FUNC_probe_read_kernel_str:
7454 		case BPF_FUNC_probe_read_user_str:
7455 			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
7456 				insn->imm = BPF_FUNC_probe_read_str;
7457 			break;
7458 		default:
7459 			break;
7460 		}
7461 	}
7462 	return 0;
7463 }
7464 
7465 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
7466 				     int *btf_obj_fd, int *btf_type_id);
7467 
7468 /* this is called as prog->sec_def->prog_prepare_load_fn for libbpf-supported sec_defs */
7469 static int libbpf_prepare_prog_load(struct bpf_program *prog,
7470 				    struct bpf_prog_load_opts *opts, long cookie)
7471 {
7472 	enum sec_def_flags def = cookie;
7473 
7474 	/* old kernels might not support specifying expected_attach_type */
7475 	if ((def & SEC_EXP_ATTACH_OPT) && !kernel_supports(prog->obj, FEAT_EXP_ATTACH_TYPE))
7476 		opts->expected_attach_type = 0;
7477 
7478 	if (def & SEC_SLEEPABLE)
7479 		opts->prog_flags |= BPF_F_SLEEPABLE;
7480 
7481 	if (prog->type == BPF_PROG_TYPE_XDP && (def & SEC_XDP_FRAGS))
7482 		opts->prog_flags |= BPF_F_XDP_HAS_FRAGS;
7483 
7484 	/* special check for usdt to use uprobe_multi link */
7485 	if ((def & SEC_USDT) && kernel_supports(prog->obj, FEAT_UPROBE_MULTI_LINK)) {
7486 		/* for BPF_TRACE_UPROBE_MULTI, user might want to query expected_attach_type
7487 		 * in prog, and expected_attach_type we set in kernel is from opts, so we
7488 		 * update both.
7489 		 */
7490 		prog->expected_attach_type = BPF_TRACE_UPROBE_MULTI;
7491 		opts->expected_attach_type = BPF_TRACE_UPROBE_MULTI;
7492 	}
7493 
7494 	if ((def & SEC_ATTACH_BTF) && !prog->attach_btf_id) {
7495 		int btf_obj_fd = 0, btf_type_id = 0, err;
7496 		const char *attach_name;
7497 
7498 		attach_name = strchr(prog->sec_name, '/');
7499 		if (!attach_name) {
7500 			/* if BPF program is annotated with just SEC("fentry")
7501 			 * (or similar) without declaratively specifying
7502 			 * target, then it is expected that target will be
7503 			 * specified with bpf_program__set_attach_target() at
7504 			 * runtime before BPF object load step. If not, then
7505 			 * there is nothing to load into the kernel as BPF
7506 			 * verifier won't be able to validate BPF program
7507 			 * correctness anyways.
7508 			 */
7509 			pr_warn("prog '%s': no BTF-based attach target is specified, use bpf_program__set_attach_target()\n",
7510 				prog->name);
7511 			return -EINVAL;
7512 		}
7513 		attach_name++; /* skip over / */
7514 
7515 		err = libbpf_find_attach_btf_id(prog, attach_name, &btf_obj_fd, &btf_type_id);
7516 		if (err)
7517 			return err;
7518 
7519 		/* cache resolved BTF FD and BTF type ID in the prog */
7520 		prog->attach_btf_obj_fd = btf_obj_fd;
7521 		prog->attach_btf_id = btf_type_id;
7522 
7523 		/* but by now libbpf common logic is not utilizing
7524 		 * prog->atach_btf_obj_fd/prog->attach_btf_id anymore because
7525 		 * this callback is called after opts were populated by
7526 		 * libbpf, so this callback has to update opts explicitly here
7527 		 */
7528 		opts->attach_btf_obj_fd = btf_obj_fd;
7529 		opts->attach_btf_id = btf_type_id;
7530 	}
7531 	return 0;
7532 }
7533 
7534 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz);
7535 
7536 static int bpf_object_load_prog(struct bpf_object *obj, struct bpf_program *prog,
7537 				struct bpf_insn *insns, int insns_cnt,
7538 				const char *license, __u32 kern_version, int *prog_fd)
7539 {
7540 	LIBBPF_OPTS(bpf_prog_load_opts, load_attr);
7541 	const char *prog_name = NULL;
7542 	size_t log_buf_size = 0;
7543 	char *log_buf = NULL, *tmp;
7544 	bool own_log_buf = true;
7545 	__u32 log_level = prog->log_level;
7546 	int ret, err;
7547 
7548 	/* Be more helpful by rejecting programs that can't be validated early
7549 	 * with more meaningful and actionable error message.
7550 	 */
7551 	switch (prog->type) {
7552 	case BPF_PROG_TYPE_UNSPEC:
7553 		/*
7554 		 * The program type must be set.  Most likely we couldn't find a proper
7555 		 * section definition at load time, and thus we didn't infer the type.
7556 		 */
7557 		pr_warn("prog '%s': missing BPF prog type, check ELF section name '%s'\n",
7558 			prog->name, prog->sec_name);
7559 		return -EINVAL;
7560 	case BPF_PROG_TYPE_STRUCT_OPS:
7561 		if (prog->attach_btf_id == 0) {
7562 			pr_warn("prog '%s': SEC(\"struct_ops\") program isn't referenced anywhere, did you forget to use it?\n",
7563 				prog->name);
7564 			return -EINVAL;
7565 		}
7566 		break;
7567 	default:
7568 		break;
7569 	}
7570 
7571 	if (!insns || !insns_cnt)
7572 		return -EINVAL;
7573 
7574 	if (kernel_supports(obj, FEAT_PROG_NAME))
7575 		prog_name = prog->name;
7576 	load_attr.attach_prog_fd = prog->attach_prog_fd;
7577 	load_attr.attach_btf_obj_fd = prog->attach_btf_obj_fd;
7578 	load_attr.attach_btf_id = prog->attach_btf_id;
7579 	load_attr.kern_version = kern_version;
7580 	load_attr.prog_ifindex = prog->prog_ifindex;
7581 	load_attr.expected_attach_type = prog->expected_attach_type;
7582 
7583 	/* specify func_info/line_info only if kernel supports them */
7584 	if (obj->btf && btf__fd(obj->btf) >= 0 && kernel_supports(obj, FEAT_BTF_FUNC)) {
7585 		load_attr.prog_btf_fd = btf__fd(obj->btf);
7586 		load_attr.func_info = prog->func_info;
7587 		load_attr.func_info_rec_size = prog->func_info_rec_size;
7588 		load_attr.func_info_cnt = prog->func_info_cnt;
7589 		load_attr.line_info = prog->line_info;
7590 		load_attr.line_info_rec_size = prog->line_info_rec_size;
7591 		load_attr.line_info_cnt = prog->line_info_cnt;
7592 	}
7593 	load_attr.log_level = log_level;
7594 	load_attr.prog_flags = prog->prog_flags;
7595 	load_attr.fd_array = obj->fd_array;
7596 
7597 	load_attr.token_fd = obj->token_fd;
7598 	if (obj->token_fd)
7599 		load_attr.prog_flags |= BPF_F_TOKEN_FD;
7600 
7601 	/* adjust load_attr if sec_def provides custom preload callback */
7602 	if (prog->sec_def && prog->sec_def->prog_prepare_load_fn) {
7603 		err = prog->sec_def->prog_prepare_load_fn(prog, &load_attr, prog->sec_def->cookie);
7604 		if (err < 0) {
7605 			pr_warn("prog '%s': failed to prepare load attributes: %s\n",
7606 				prog->name, errstr(err));
7607 			return err;
7608 		}
7609 		insns = prog->insns;
7610 		insns_cnt = prog->insns_cnt;
7611 	}
7612 
7613 	if (obj->gen_loader) {
7614 		bpf_gen__prog_load(obj->gen_loader, prog->type, prog->name,
7615 				   license, insns, insns_cnt, &load_attr,
7616 				   prog - obj->programs);
7617 		*prog_fd = -1;
7618 		return 0;
7619 	}
7620 
7621 retry_load:
7622 	/* if log_level is zero, we don't request logs initially even if
7623 	 * custom log_buf is specified; if the program load fails, then we'll
7624 	 * bump log_level to 1 and use either custom log_buf or we'll allocate
7625 	 * our own and retry the load to get details on what failed
7626 	 */
7627 	if (log_level) {
7628 		if (prog->log_buf) {
7629 			log_buf = prog->log_buf;
7630 			log_buf_size = prog->log_size;
7631 			own_log_buf = false;
7632 		} else if (obj->log_buf) {
7633 			log_buf = obj->log_buf;
7634 			log_buf_size = obj->log_size;
7635 			own_log_buf = false;
7636 		} else {
7637 			log_buf_size = max((size_t)BPF_LOG_BUF_SIZE, log_buf_size * 2);
7638 			tmp = realloc(log_buf, log_buf_size);
7639 			if (!tmp) {
7640 				ret = -ENOMEM;
7641 				goto out;
7642 			}
7643 			log_buf = tmp;
7644 			log_buf[0] = '\0';
7645 			own_log_buf = true;
7646 		}
7647 	}
7648 
7649 	load_attr.log_buf = log_buf;
7650 	load_attr.log_size = log_buf_size;
7651 	load_attr.log_level = log_level;
7652 
7653 	ret = bpf_prog_load(prog->type, prog_name, license, insns, insns_cnt, &load_attr);
7654 	if (ret >= 0) {
7655 		if (log_level && own_log_buf) {
7656 			pr_debug("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
7657 				 prog->name, log_buf);
7658 		}
7659 
7660 		if (obj->has_rodata && kernel_supports(obj, FEAT_PROG_BIND_MAP)) {
7661 			struct bpf_map *map;
7662 			int i;
7663 
7664 			for (i = 0; i < obj->nr_maps; i++) {
7665 				map = &prog->obj->maps[i];
7666 				if (map->libbpf_type != LIBBPF_MAP_RODATA)
7667 					continue;
7668 
7669 				if (bpf_prog_bind_map(ret, map->fd, NULL)) {
7670 					pr_warn("prog '%s': failed to bind map '%s': %s\n",
7671 						prog->name, map->real_name, errstr(errno));
7672 					/* Don't fail hard if can't bind rodata. */
7673 				}
7674 			}
7675 		}
7676 
7677 		*prog_fd = ret;
7678 		ret = 0;
7679 		goto out;
7680 	}
7681 
7682 	if (log_level == 0) {
7683 		log_level = 1;
7684 		goto retry_load;
7685 	}
7686 	/* On ENOSPC, increase log buffer size and retry, unless custom
7687 	 * log_buf is specified.
7688 	 * Be careful to not overflow u32, though. Kernel's log buf size limit
7689 	 * isn't part of UAPI so it can always be bumped to full 4GB. So don't
7690 	 * multiply by 2 unless we are sure we'll fit within 32 bits.
7691 	 * Currently, we'll get -EINVAL when we reach (UINT_MAX >> 2).
7692 	 */
7693 	if (own_log_buf && errno == ENOSPC && log_buf_size <= UINT_MAX / 2)
7694 		goto retry_load;
7695 
7696 	ret = -errno;
7697 
7698 	/* post-process verifier log to improve error descriptions */
7699 	fixup_verifier_log(prog, log_buf, log_buf_size);
7700 
7701 	pr_warn("prog '%s': BPF program load failed: %s\n", prog->name, errstr(errno));
7702 	pr_perm_msg(ret);
7703 
7704 	if (own_log_buf && log_buf && log_buf[0] != '\0') {
7705 		pr_warn("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
7706 			prog->name, log_buf);
7707 	}
7708 
7709 out:
7710 	if (own_log_buf)
7711 		free(log_buf);
7712 	return ret;
7713 }
7714 
7715 static char *find_prev_line(char *buf, char *cur)
7716 {
7717 	char *p;
7718 
7719 	if (cur == buf) /* end of a log buf */
7720 		return NULL;
7721 
7722 	p = cur - 1;
7723 	while (p - 1 >= buf && *(p - 1) != '\n')
7724 		p--;
7725 
7726 	return p;
7727 }
7728 
7729 static void patch_log(char *buf, size_t buf_sz, size_t log_sz,
7730 		      char *orig, size_t orig_sz, const char *patch)
7731 {
7732 	/* size of the remaining log content to the right from the to-be-replaced part */
7733 	size_t rem_sz = (buf + log_sz) - (orig + orig_sz);
7734 	size_t patch_sz = strlen(patch);
7735 
7736 	if (patch_sz != orig_sz) {
7737 		/* If patch line(s) are longer than original piece of verifier log,
7738 		 * shift log contents by (patch_sz - orig_sz) bytes to the right
7739 		 * starting from after to-be-replaced part of the log.
7740 		 *
7741 		 * If patch line(s) are shorter than original piece of verifier log,
7742 		 * shift log contents by (orig_sz - patch_sz) bytes to the left
7743 		 * starting from after to-be-replaced part of the log
7744 		 *
7745 		 * We need to be careful about not overflowing available
7746 		 * buf_sz capacity. If that's the case, we'll truncate the end
7747 		 * of the original log, as necessary.
7748 		 */
7749 		if (patch_sz > orig_sz) {
7750 			if (orig + patch_sz >= buf + buf_sz) {
7751 				/* patch is big enough to cover remaining space completely */
7752 				patch_sz -= (orig + patch_sz) - (buf + buf_sz) + 1;
7753 				rem_sz = 0;
7754 			} else if (patch_sz - orig_sz > buf_sz - log_sz) {
7755 				/* patch causes part of remaining log to be truncated */
7756 				rem_sz -= (patch_sz - orig_sz) - (buf_sz - log_sz);
7757 			}
7758 		}
7759 		/* shift remaining log to the right by calculated amount */
7760 		memmove(orig + patch_sz, orig + orig_sz, rem_sz);
7761 	}
7762 
7763 	memcpy(orig, patch, patch_sz);
7764 }
7765 
7766 static void fixup_log_failed_core_relo(struct bpf_program *prog,
7767 				       char *buf, size_t buf_sz, size_t log_sz,
7768 				       char *line1, char *line2, char *line3)
7769 {
7770 	/* Expected log for failed and not properly guarded CO-RE relocation:
7771 	 * line1 -> 123: (85) call unknown#195896080
7772 	 * line2 -> invalid func unknown#195896080
7773 	 * line3 -> <anything else or end of buffer>
7774 	 *
7775 	 * "123" is the index of the instruction that was poisoned. We extract
7776 	 * instruction index to find corresponding CO-RE relocation and
7777 	 * replace this part of the log with more relevant information about
7778 	 * failed CO-RE relocation.
7779 	 */
7780 	const struct bpf_core_relo *relo;
7781 	struct bpf_core_spec spec;
7782 	char patch[512], spec_buf[256];
7783 	int insn_idx, err, spec_len;
7784 
7785 	if (sscanf(line1, "%d: (%*d) call unknown#195896080\n", &insn_idx) != 1)
7786 		return;
7787 
7788 	relo = find_relo_core(prog, insn_idx);
7789 	if (!relo)
7790 		return;
7791 
7792 	err = bpf_core_parse_spec(prog->name, prog->obj->btf, relo, &spec);
7793 	if (err)
7794 		return;
7795 
7796 	spec_len = bpf_core_format_spec(spec_buf, sizeof(spec_buf), &spec);
7797 	snprintf(patch, sizeof(patch),
7798 		 "%d: <invalid CO-RE relocation>\n"
7799 		 "failed to resolve CO-RE relocation %s%s\n",
7800 		 insn_idx, spec_buf, spec_len >= sizeof(spec_buf) ? "..." : "");
7801 
7802 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7803 }
7804 
7805 static void fixup_log_missing_map_load(struct bpf_program *prog,
7806 				       char *buf, size_t buf_sz, size_t log_sz,
7807 				       char *line1, char *line2, char *line3)
7808 {
7809 	/* Expected log for failed and not properly guarded map reference:
7810 	 * line1 -> 123: (85) call unknown#2001000345
7811 	 * line2 -> invalid func unknown#2001000345
7812 	 * line3 -> <anything else or end of buffer>
7813 	 *
7814 	 * "123" is the index of the instruction that was poisoned.
7815 	 * "345" in "2001000345" is a map index in obj->maps to fetch map name.
7816 	 */
7817 	struct bpf_object *obj = prog->obj;
7818 	const struct bpf_map *map;
7819 	int insn_idx, map_idx;
7820 	char patch[128];
7821 
7822 	if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &map_idx) != 2)
7823 		return;
7824 
7825 	map_idx -= POISON_LDIMM64_MAP_BASE;
7826 	if (map_idx < 0 || map_idx >= obj->nr_maps)
7827 		return;
7828 	map = &obj->maps[map_idx];
7829 
7830 	snprintf(patch, sizeof(patch),
7831 		 "%d: <invalid BPF map reference>\n"
7832 		 "BPF map '%s' is referenced but wasn't created\n",
7833 		 insn_idx, map->name);
7834 
7835 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7836 }
7837 
7838 static void fixup_log_missing_kfunc_call(struct bpf_program *prog,
7839 					 char *buf, size_t buf_sz, size_t log_sz,
7840 					 char *line1, char *line2, char *line3)
7841 {
7842 	/* Expected log for failed and not properly guarded kfunc call:
7843 	 * line1 -> 123: (85) call unknown#2002000345
7844 	 * line2 -> invalid func unknown#2002000345
7845 	 * line3 -> <anything else or end of buffer>
7846 	 *
7847 	 * "123" is the index of the instruction that was poisoned.
7848 	 * "345" in "2002000345" is an extern index in obj->externs to fetch kfunc name.
7849 	 */
7850 	struct bpf_object *obj = prog->obj;
7851 	const struct extern_desc *ext;
7852 	int insn_idx, ext_idx;
7853 	char patch[128];
7854 
7855 	if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &ext_idx) != 2)
7856 		return;
7857 
7858 	ext_idx -= POISON_CALL_KFUNC_BASE;
7859 	if (ext_idx < 0 || ext_idx >= obj->nr_extern)
7860 		return;
7861 	ext = &obj->externs[ext_idx];
7862 
7863 	snprintf(patch, sizeof(patch),
7864 		 "%d: <invalid kfunc call>\n"
7865 		 "kfunc '%s' is referenced but wasn't resolved\n",
7866 		 insn_idx, ext->name);
7867 
7868 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7869 }
7870 
7871 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz)
7872 {
7873 	/* look for familiar error patterns in last N lines of the log */
7874 	const size_t max_last_line_cnt = 10;
7875 	char *prev_line, *cur_line, *next_line;
7876 	size_t log_sz;
7877 	int i;
7878 
7879 	if (!buf)
7880 		return;
7881 
7882 	log_sz = strlen(buf) + 1;
7883 	next_line = buf + log_sz - 1;
7884 
7885 	for (i = 0; i < max_last_line_cnt; i++, next_line = cur_line) {
7886 		cur_line = find_prev_line(buf, next_line);
7887 		if (!cur_line)
7888 			return;
7889 
7890 		if (str_has_pfx(cur_line, "invalid func unknown#195896080\n")) {
7891 			prev_line = find_prev_line(buf, cur_line);
7892 			if (!prev_line)
7893 				continue;
7894 
7895 			/* failed CO-RE relocation case */
7896 			fixup_log_failed_core_relo(prog, buf, buf_sz, log_sz,
7897 						   prev_line, cur_line, next_line);
7898 			return;
7899 		} else if (str_has_pfx(cur_line, "invalid func unknown#"POISON_LDIMM64_MAP_PFX)) {
7900 			prev_line = find_prev_line(buf, cur_line);
7901 			if (!prev_line)
7902 				continue;
7903 
7904 			/* reference to uncreated BPF map */
7905 			fixup_log_missing_map_load(prog, buf, buf_sz, log_sz,
7906 						   prev_line, cur_line, next_line);
7907 			return;
7908 		} else if (str_has_pfx(cur_line, "invalid func unknown#"POISON_CALL_KFUNC_PFX)) {
7909 			prev_line = find_prev_line(buf, cur_line);
7910 			if (!prev_line)
7911 				continue;
7912 
7913 			/* reference to unresolved kfunc */
7914 			fixup_log_missing_kfunc_call(prog, buf, buf_sz, log_sz,
7915 						     prev_line, cur_line, next_line);
7916 			return;
7917 		}
7918 	}
7919 }
7920 
7921 static int bpf_program_record_relos(struct bpf_program *prog)
7922 {
7923 	struct bpf_object *obj = prog->obj;
7924 	int i;
7925 
7926 	for (i = 0; i < prog->nr_reloc; i++) {
7927 		struct reloc_desc *relo = &prog->reloc_desc[i];
7928 		struct extern_desc *ext = &obj->externs[relo->ext_idx];
7929 		int kind;
7930 
7931 		switch (relo->type) {
7932 		case RELO_EXTERN_LD64:
7933 			if (ext->type != EXT_KSYM)
7934 				continue;
7935 			kind = btf_is_var(btf__type_by_id(obj->btf, ext->btf_id)) ?
7936 				BTF_KIND_VAR : BTF_KIND_FUNC;
7937 			bpf_gen__record_extern(obj->gen_loader, ext->name,
7938 					       ext->is_weak, !ext->ksym.type_id,
7939 					       true, kind, relo->insn_idx);
7940 			break;
7941 		case RELO_EXTERN_CALL:
7942 			bpf_gen__record_extern(obj->gen_loader, ext->name,
7943 					       ext->is_weak, false, false, BTF_KIND_FUNC,
7944 					       relo->insn_idx);
7945 			break;
7946 		case RELO_CORE: {
7947 			struct bpf_core_relo cr = {
7948 				.insn_off = relo->insn_idx * 8,
7949 				.type_id = relo->core_relo->type_id,
7950 				.access_str_off = relo->core_relo->access_str_off,
7951 				.kind = relo->core_relo->kind,
7952 			};
7953 
7954 			bpf_gen__record_relo_core(obj->gen_loader, &cr);
7955 			break;
7956 		}
7957 		default:
7958 			continue;
7959 		}
7960 	}
7961 	return 0;
7962 }
7963 
7964 static int
7965 bpf_object__load_progs(struct bpf_object *obj, int log_level)
7966 {
7967 	struct bpf_program *prog;
7968 	size_t i;
7969 	int err;
7970 
7971 	for (i = 0; i < obj->nr_programs; i++) {
7972 		prog = &obj->programs[i];
7973 		if (prog_is_subprog(obj, prog))
7974 			continue;
7975 		if (!prog->autoload) {
7976 			pr_debug("prog '%s': skipped loading\n", prog->name);
7977 			continue;
7978 		}
7979 		prog->log_level |= log_level;
7980 
7981 		if (obj->gen_loader)
7982 			bpf_program_record_relos(prog);
7983 
7984 		err = bpf_object_load_prog(obj, prog, prog->insns, prog->insns_cnt,
7985 					   obj->license, obj->kern_version, &prog->fd);
7986 		if (err) {
7987 			pr_warn("prog '%s': failed to load: %s\n", prog->name, errstr(err));
7988 			return err;
7989 		}
7990 	}
7991 
7992 	bpf_object__free_relocs(obj);
7993 	return 0;
7994 }
7995 
7996 static int bpf_object_prepare_progs(struct bpf_object *obj)
7997 {
7998 	struct bpf_program *prog;
7999 	size_t i;
8000 	int err;
8001 
8002 	for (i = 0; i < obj->nr_programs; i++) {
8003 		prog = &obj->programs[i];
8004 		err = bpf_object__sanitize_prog(obj, prog);
8005 		if (err)
8006 			return err;
8007 	}
8008 	return 0;
8009 }
8010 
8011 static const struct bpf_sec_def *find_sec_def(const char *sec_name);
8012 
8013 static int bpf_object_init_progs(struct bpf_object *obj, const struct bpf_object_open_opts *opts)
8014 {
8015 	struct bpf_program *prog;
8016 	int err;
8017 
8018 	bpf_object__for_each_program(prog, obj) {
8019 		prog->sec_def = find_sec_def(prog->sec_name);
8020 		if (!prog->sec_def) {
8021 			/* couldn't guess, but user might manually specify */
8022 			pr_debug("prog '%s': unrecognized ELF section name '%s'\n",
8023 				prog->name, prog->sec_name);
8024 			continue;
8025 		}
8026 
8027 		prog->type = prog->sec_def->prog_type;
8028 		prog->expected_attach_type = prog->sec_def->expected_attach_type;
8029 
8030 		/* sec_def can have custom callback which should be called
8031 		 * after bpf_program is initialized to adjust its properties
8032 		 */
8033 		if (prog->sec_def->prog_setup_fn) {
8034 			err = prog->sec_def->prog_setup_fn(prog, prog->sec_def->cookie);
8035 			if (err < 0) {
8036 				pr_warn("prog '%s': failed to initialize: %s\n",
8037 					prog->name, errstr(err));
8038 				return err;
8039 			}
8040 		}
8041 	}
8042 
8043 	return 0;
8044 }
8045 
8046 static struct bpf_object *bpf_object_open(const char *path, const void *obj_buf, size_t obj_buf_sz,
8047 					  const char *obj_name,
8048 					  const struct bpf_object_open_opts *opts)
8049 {
8050 	const char *kconfig, *btf_tmp_path, *token_path;
8051 	struct bpf_object *obj;
8052 	int err;
8053 	char *log_buf;
8054 	size_t log_size;
8055 	__u32 log_level;
8056 
8057 	if (obj_buf && !obj_name)
8058 		return ERR_PTR(-EINVAL);
8059 
8060 	if (elf_version(EV_CURRENT) == EV_NONE) {
8061 		pr_warn("failed to init libelf for %s\n",
8062 			path ? : "(mem buf)");
8063 		return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
8064 	}
8065 
8066 	if (!OPTS_VALID(opts, bpf_object_open_opts))
8067 		return ERR_PTR(-EINVAL);
8068 
8069 	obj_name = OPTS_GET(opts, object_name, NULL) ?: obj_name;
8070 	if (obj_buf) {
8071 		path = obj_name;
8072 		pr_debug("loading object '%s' from buffer\n", obj_name);
8073 	} else {
8074 		pr_debug("loading object from %s\n", path);
8075 	}
8076 
8077 	log_buf = OPTS_GET(opts, kernel_log_buf, NULL);
8078 	log_size = OPTS_GET(opts, kernel_log_size, 0);
8079 	log_level = OPTS_GET(opts, kernel_log_level, 0);
8080 	if (log_size > UINT_MAX)
8081 		return ERR_PTR(-EINVAL);
8082 	if (log_size && !log_buf)
8083 		return ERR_PTR(-EINVAL);
8084 
8085 	token_path = OPTS_GET(opts, bpf_token_path, NULL);
8086 	/* if user didn't specify bpf_token_path explicitly, check if
8087 	 * LIBBPF_BPF_TOKEN_PATH envvar was set and treat it as bpf_token_path
8088 	 * option
8089 	 */
8090 	if (!token_path)
8091 		token_path = getenv("LIBBPF_BPF_TOKEN_PATH");
8092 	if (token_path && strlen(token_path) >= PATH_MAX)
8093 		return ERR_PTR(-ENAMETOOLONG);
8094 
8095 	obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
8096 	if (IS_ERR(obj))
8097 		return obj;
8098 
8099 	obj->log_buf = log_buf;
8100 	obj->log_size = log_size;
8101 	obj->log_level = log_level;
8102 
8103 	if (token_path) {
8104 		obj->token_path = strdup(token_path);
8105 		if (!obj->token_path) {
8106 			err = -ENOMEM;
8107 			goto out;
8108 		}
8109 	}
8110 
8111 	btf_tmp_path = OPTS_GET(opts, btf_custom_path, NULL);
8112 	if (btf_tmp_path) {
8113 		if (strlen(btf_tmp_path) >= PATH_MAX) {
8114 			err = -ENAMETOOLONG;
8115 			goto out;
8116 		}
8117 		obj->btf_custom_path = strdup(btf_tmp_path);
8118 		if (!obj->btf_custom_path) {
8119 			err = -ENOMEM;
8120 			goto out;
8121 		}
8122 	}
8123 
8124 	kconfig = OPTS_GET(opts, kconfig, NULL);
8125 	if (kconfig) {
8126 		obj->kconfig = strdup(kconfig);
8127 		if (!obj->kconfig) {
8128 			err = -ENOMEM;
8129 			goto out;
8130 		}
8131 	}
8132 
8133 	err = bpf_object__elf_init(obj);
8134 	err = err ? : bpf_object__elf_collect(obj);
8135 	err = err ? : bpf_object__collect_externs(obj);
8136 	err = err ? : bpf_object_fixup_btf(obj);
8137 	err = err ? : bpf_object__init_maps(obj, opts);
8138 	err = err ? : bpf_object_init_progs(obj, opts);
8139 	err = err ? : bpf_object__collect_relos(obj);
8140 	if (err)
8141 		goto out;
8142 
8143 	bpf_object__elf_finish(obj);
8144 
8145 	return obj;
8146 out:
8147 	bpf_object__close(obj);
8148 	return ERR_PTR(err);
8149 }
8150 
8151 struct bpf_object *
8152 bpf_object__open_file(const char *path, const struct bpf_object_open_opts *opts)
8153 {
8154 	if (!path)
8155 		return libbpf_err_ptr(-EINVAL);
8156 
8157 	return libbpf_ptr(bpf_object_open(path, NULL, 0, NULL, opts));
8158 }
8159 
8160 struct bpf_object *bpf_object__open(const char *path)
8161 {
8162 	return bpf_object__open_file(path, NULL);
8163 }
8164 
8165 struct bpf_object *
8166 bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
8167 		     const struct bpf_object_open_opts *opts)
8168 {
8169 	char tmp_name[64];
8170 
8171 	if (!obj_buf || obj_buf_sz == 0)
8172 		return libbpf_err_ptr(-EINVAL);
8173 
8174 	/* create a (quite useless) default "name" for this memory buffer object */
8175 	snprintf(tmp_name, sizeof(tmp_name), "%lx-%zx", (unsigned long)obj_buf, obj_buf_sz);
8176 
8177 	return libbpf_ptr(bpf_object_open(NULL, obj_buf, obj_buf_sz, tmp_name, opts));
8178 }
8179 
8180 static int bpf_object_unload(struct bpf_object *obj)
8181 {
8182 	size_t i;
8183 
8184 	if (!obj)
8185 		return libbpf_err(-EINVAL);
8186 
8187 	for (i = 0; i < obj->nr_maps; i++) {
8188 		zclose(obj->maps[i].fd);
8189 		if (obj->maps[i].st_ops)
8190 			zfree(&obj->maps[i].st_ops->kern_vdata);
8191 	}
8192 
8193 	for (i = 0; i < obj->nr_programs; i++)
8194 		bpf_program__unload(&obj->programs[i]);
8195 
8196 	return 0;
8197 }
8198 
8199 static int bpf_object__sanitize_maps(struct bpf_object *obj)
8200 {
8201 	struct bpf_map *m;
8202 
8203 	bpf_object__for_each_map(m, obj) {
8204 		if (!bpf_map__is_internal(m))
8205 			continue;
8206 		if (!kernel_supports(obj, FEAT_ARRAY_MMAP))
8207 			m->def.map_flags &= ~BPF_F_MMAPABLE;
8208 	}
8209 
8210 	return 0;
8211 }
8212 
8213 typedef int (*kallsyms_cb_t)(unsigned long long sym_addr, char sym_type,
8214 			     const char *sym_name, void *ctx);
8215 
8216 static int libbpf_kallsyms_parse(kallsyms_cb_t cb, void *ctx)
8217 {
8218 	char sym_type, sym_name[500];
8219 	unsigned long long sym_addr;
8220 	int ret, err = 0;
8221 	FILE *f;
8222 
8223 	f = fopen("/proc/kallsyms", "re");
8224 	if (!f) {
8225 		err = -errno;
8226 		pr_warn("failed to open /proc/kallsyms: %s\n", errstr(err));
8227 		return err;
8228 	}
8229 
8230 	while (true) {
8231 		ret = fscanf(f, "%llx %c %499s%*[^\n]\n",
8232 			     &sym_addr, &sym_type, sym_name);
8233 		if (ret == EOF && feof(f))
8234 			break;
8235 		if (ret != 3) {
8236 			pr_warn("failed to read kallsyms entry: %d\n", ret);
8237 			err = -EINVAL;
8238 			break;
8239 		}
8240 
8241 		err = cb(sym_addr, sym_type, sym_name, ctx);
8242 		if (err)
8243 			break;
8244 	}
8245 
8246 	fclose(f);
8247 	return err;
8248 }
8249 
8250 static int kallsyms_cb(unsigned long long sym_addr, char sym_type,
8251 		       const char *sym_name, void *ctx)
8252 {
8253 	struct bpf_object *obj = ctx;
8254 	const struct btf_type *t;
8255 	struct extern_desc *ext;
8256 	char *res;
8257 
8258 	res = strstr(sym_name, ".llvm.");
8259 	if (sym_type == 'd' && res)
8260 		ext = find_extern_by_name_with_len(obj, sym_name, res - sym_name);
8261 	else
8262 		ext = find_extern_by_name(obj, sym_name);
8263 	if (!ext || ext->type != EXT_KSYM)
8264 		return 0;
8265 
8266 	t = btf__type_by_id(obj->btf, ext->btf_id);
8267 	if (!btf_is_var(t))
8268 		return 0;
8269 
8270 	if (ext->is_set && ext->ksym.addr != sym_addr) {
8271 		pr_warn("extern (ksym) '%s': resolution is ambiguous: 0x%llx or 0x%llx\n",
8272 			sym_name, ext->ksym.addr, sym_addr);
8273 		return -EINVAL;
8274 	}
8275 	if (!ext->is_set) {
8276 		ext->is_set = true;
8277 		ext->ksym.addr = sym_addr;
8278 		pr_debug("extern (ksym) '%s': set to 0x%llx\n", sym_name, sym_addr);
8279 	}
8280 	return 0;
8281 }
8282 
8283 static int bpf_object__read_kallsyms_file(struct bpf_object *obj)
8284 {
8285 	return libbpf_kallsyms_parse(kallsyms_cb, obj);
8286 }
8287 
8288 static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
8289 			    __u16 kind, struct btf **res_btf,
8290 			    struct module_btf **res_mod_btf)
8291 {
8292 	struct module_btf *mod_btf;
8293 	struct btf *btf;
8294 	int i, id, err;
8295 
8296 	btf = obj->btf_vmlinux;
8297 	mod_btf = NULL;
8298 	id = btf__find_by_name_kind(btf, ksym_name, kind);
8299 
8300 	if (id == -ENOENT) {
8301 		err = load_module_btfs(obj);
8302 		if (err)
8303 			return err;
8304 
8305 		for (i = 0; i < obj->btf_module_cnt; i++) {
8306 			/* we assume module_btf's BTF FD is always >0 */
8307 			mod_btf = &obj->btf_modules[i];
8308 			btf = mod_btf->btf;
8309 			id = btf__find_by_name_kind_own(btf, ksym_name, kind);
8310 			if (id != -ENOENT)
8311 				break;
8312 		}
8313 	}
8314 	if (id <= 0)
8315 		return -ESRCH;
8316 
8317 	*res_btf = btf;
8318 	*res_mod_btf = mod_btf;
8319 	return id;
8320 }
8321 
8322 static int bpf_object__resolve_ksym_var_btf_id(struct bpf_object *obj,
8323 					       struct extern_desc *ext)
8324 {
8325 	const struct btf_type *targ_var, *targ_type;
8326 	__u32 targ_type_id, local_type_id;
8327 	struct module_btf *mod_btf = NULL;
8328 	const char *targ_var_name;
8329 	struct btf *btf = NULL;
8330 	int id, err;
8331 
8332 	id = find_ksym_btf_id(obj, ext->name, BTF_KIND_VAR, &btf, &mod_btf);
8333 	if (id < 0) {
8334 		if (id == -ESRCH && ext->is_weak)
8335 			return 0;
8336 		pr_warn("extern (var ksym) '%s': not found in kernel BTF\n",
8337 			ext->name);
8338 		return id;
8339 	}
8340 
8341 	/* find local type_id */
8342 	local_type_id = ext->ksym.type_id;
8343 
8344 	/* find target type_id */
8345 	targ_var = btf__type_by_id(btf, id);
8346 	targ_var_name = btf__name_by_offset(btf, targ_var->name_off);
8347 	targ_type = skip_mods_and_typedefs(btf, targ_var->type, &targ_type_id);
8348 
8349 	err = bpf_core_types_are_compat(obj->btf, local_type_id,
8350 					btf, targ_type_id);
8351 	if (err <= 0) {
8352 		const struct btf_type *local_type;
8353 		const char *targ_name, *local_name;
8354 
8355 		local_type = btf__type_by_id(obj->btf, local_type_id);
8356 		local_name = btf__name_by_offset(obj->btf, local_type->name_off);
8357 		targ_name = btf__name_by_offset(btf, targ_type->name_off);
8358 
8359 		pr_warn("extern (var ksym) '%s': incompatible types, expected [%d] %s %s, but kernel has [%d] %s %s\n",
8360 			ext->name, local_type_id,
8361 			btf_kind_str(local_type), local_name, targ_type_id,
8362 			btf_kind_str(targ_type), targ_name);
8363 		return -EINVAL;
8364 	}
8365 
8366 	ext->is_set = true;
8367 	ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
8368 	ext->ksym.kernel_btf_id = id;
8369 	pr_debug("extern (var ksym) '%s': resolved to [%d] %s %s\n",
8370 		 ext->name, id, btf_kind_str(targ_var), targ_var_name);
8371 
8372 	return 0;
8373 }
8374 
8375 static int bpf_object__resolve_ksym_func_btf_id(struct bpf_object *obj,
8376 						struct extern_desc *ext)
8377 {
8378 	int local_func_proto_id, kfunc_proto_id, kfunc_id;
8379 	struct module_btf *mod_btf = NULL;
8380 	const struct btf_type *kern_func;
8381 	struct btf *kern_btf = NULL;
8382 	int ret;
8383 
8384 	local_func_proto_id = ext->ksym.type_id;
8385 
8386 	kfunc_id = find_ksym_btf_id(obj, ext->essent_name ?: ext->name, BTF_KIND_FUNC, &kern_btf,
8387 				    &mod_btf);
8388 	if (kfunc_id < 0) {
8389 		if (kfunc_id == -ESRCH && ext->is_weak)
8390 			return 0;
8391 		pr_warn("extern (func ksym) '%s': not found in kernel or module BTFs\n",
8392 			ext->name);
8393 		return kfunc_id;
8394 	}
8395 
8396 	kern_func = btf__type_by_id(kern_btf, kfunc_id);
8397 	kfunc_proto_id = kern_func->type;
8398 
8399 	ret = bpf_core_types_are_compat(obj->btf, local_func_proto_id,
8400 					kern_btf, kfunc_proto_id);
8401 	if (ret <= 0) {
8402 		if (ext->is_weak)
8403 			return 0;
8404 
8405 		pr_warn("extern (func ksym) '%s': func_proto [%d] incompatible with %s [%d]\n",
8406 			ext->name, local_func_proto_id,
8407 			mod_btf ? mod_btf->name : "vmlinux", kfunc_proto_id);
8408 		return -EINVAL;
8409 	}
8410 
8411 	/* set index for module BTF fd in fd_array, if unset */
8412 	if (mod_btf && !mod_btf->fd_array_idx) {
8413 		/* insn->off is s16 */
8414 		if (obj->fd_array_cnt == INT16_MAX) {
8415 			pr_warn("extern (func ksym) '%s': module BTF fd index %d too big to fit in bpf_insn offset\n",
8416 				ext->name, mod_btf->fd_array_idx);
8417 			return -E2BIG;
8418 		}
8419 		/* Cannot use index 0 for module BTF fd */
8420 		if (!obj->fd_array_cnt)
8421 			obj->fd_array_cnt = 1;
8422 
8423 		ret = libbpf_ensure_mem((void **)&obj->fd_array, &obj->fd_array_cap, sizeof(int),
8424 					obj->fd_array_cnt + 1);
8425 		if (ret)
8426 			return ret;
8427 		mod_btf->fd_array_idx = obj->fd_array_cnt;
8428 		/* we assume module BTF FD is always >0 */
8429 		obj->fd_array[obj->fd_array_cnt++] = mod_btf->fd;
8430 	}
8431 
8432 	ext->is_set = true;
8433 	ext->ksym.kernel_btf_id = kfunc_id;
8434 	ext->ksym.btf_fd_idx = mod_btf ? mod_btf->fd_array_idx : 0;
8435 	/* Also set kernel_btf_obj_fd to make sure that bpf_object__relocate_data()
8436 	 * populates FD into ld_imm64 insn when it's used to point to kfunc.
8437 	 * {kernel_btf_id, btf_fd_idx} -> fixup bpf_call.
8438 	 * {kernel_btf_id, kernel_btf_obj_fd} -> fixup ld_imm64.
8439 	 */
8440 	ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
8441 	pr_debug("extern (func ksym) '%s': resolved to %s [%d]\n",
8442 		 ext->name, mod_btf ? mod_btf->name : "vmlinux", kfunc_id);
8443 
8444 	return 0;
8445 }
8446 
8447 static int bpf_object__resolve_ksyms_btf_id(struct bpf_object *obj)
8448 {
8449 	const struct btf_type *t;
8450 	struct extern_desc *ext;
8451 	int i, err;
8452 
8453 	for (i = 0; i < obj->nr_extern; i++) {
8454 		ext = &obj->externs[i];
8455 		if (ext->type != EXT_KSYM || !ext->ksym.type_id)
8456 			continue;
8457 
8458 		if (obj->gen_loader) {
8459 			ext->is_set = true;
8460 			ext->ksym.kernel_btf_obj_fd = 0;
8461 			ext->ksym.kernel_btf_id = 0;
8462 			continue;
8463 		}
8464 		t = btf__type_by_id(obj->btf, ext->btf_id);
8465 		if (btf_is_var(t))
8466 			err = bpf_object__resolve_ksym_var_btf_id(obj, ext);
8467 		else
8468 			err = bpf_object__resolve_ksym_func_btf_id(obj, ext);
8469 		if (err)
8470 			return err;
8471 	}
8472 	return 0;
8473 }
8474 
8475 static int bpf_object__resolve_externs(struct bpf_object *obj,
8476 				       const char *extra_kconfig)
8477 {
8478 	bool need_config = false, need_kallsyms = false;
8479 	bool need_vmlinux_btf = false;
8480 	struct extern_desc *ext;
8481 	void *kcfg_data = NULL;
8482 	int err, i;
8483 
8484 	if (obj->nr_extern == 0)
8485 		return 0;
8486 
8487 	if (obj->kconfig_map_idx >= 0)
8488 		kcfg_data = obj->maps[obj->kconfig_map_idx].mmaped;
8489 
8490 	for (i = 0; i < obj->nr_extern; i++) {
8491 		ext = &obj->externs[i];
8492 
8493 		if (ext->type == EXT_KSYM) {
8494 			if (ext->ksym.type_id)
8495 				need_vmlinux_btf = true;
8496 			else
8497 				need_kallsyms = true;
8498 			continue;
8499 		} else if (ext->type == EXT_KCFG) {
8500 			void *ext_ptr = kcfg_data + ext->kcfg.data_off;
8501 			__u64 value = 0;
8502 
8503 			/* Kconfig externs need actual /proc/config.gz */
8504 			if (str_has_pfx(ext->name, "CONFIG_")) {
8505 				need_config = true;
8506 				continue;
8507 			}
8508 
8509 			/* Virtual kcfg externs are customly handled by libbpf */
8510 			if (strcmp(ext->name, "LINUX_KERNEL_VERSION") == 0) {
8511 				value = get_kernel_version();
8512 				if (!value) {
8513 					pr_warn("extern (kcfg) '%s': failed to get kernel version\n", ext->name);
8514 					return -EINVAL;
8515 				}
8516 			} else if (strcmp(ext->name, "LINUX_HAS_BPF_COOKIE") == 0) {
8517 				value = kernel_supports(obj, FEAT_BPF_COOKIE);
8518 			} else if (strcmp(ext->name, "LINUX_HAS_SYSCALL_WRAPPER") == 0) {
8519 				value = kernel_supports(obj, FEAT_SYSCALL_WRAPPER);
8520 			} else if (!str_has_pfx(ext->name, "LINUX_") || !ext->is_weak) {
8521 				/* Currently libbpf supports only CONFIG_ and LINUX_ prefixed
8522 				 * __kconfig externs, where LINUX_ ones are virtual and filled out
8523 				 * customly by libbpf (their values don't come from Kconfig).
8524 				 * If LINUX_xxx variable is not recognized by libbpf, but is marked
8525 				 * __weak, it defaults to zero value, just like for CONFIG_xxx
8526 				 * externs.
8527 				 */
8528 				pr_warn("extern (kcfg) '%s': unrecognized virtual extern\n", ext->name);
8529 				return -EINVAL;
8530 			}
8531 
8532 			err = set_kcfg_value_num(ext, ext_ptr, value);
8533 			if (err)
8534 				return err;
8535 			pr_debug("extern (kcfg) '%s': set to 0x%llx\n",
8536 				 ext->name, (long long)value);
8537 		} else {
8538 			pr_warn("extern '%s': unrecognized extern kind\n", ext->name);
8539 			return -EINVAL;
8540 		}
8541 	}
8542 	if (need_config && extra_kconfig) {
8543 		err = bpf_object__read_kconfig_mem(obj, extra_kconfig, kcfg_data);
8544 		if (err)
8545 			return -EINVAL;
8546 		need_config = false;
8547 		for (i = 0; i < obj->nr_extern; i++) {
8548 			ext = &obj->externs[i];
8549 			if (ext->type == EXT_KCFG && !ext->is_set) {
8550 				need_config = true;
8551 				break;
8552 			}
8553 		}
8554 	}
8555 	if (need_config) {
8556 		err = bpf_object__read_kconfig_file(obj, kcfg_data);
8557 		if (err)
8558 			return -EINVAL;
8559 	}
8560 	if (need_kallsyms) {
8561 		err = bpf_object__read_kallsyms_file(obj);
8562 		if (err)
8563 			return -EINVAL;
8564 	}
8565 	if (need_vmlinux_btf) {
8566 		err = bpf_object__resolve_ksyms_btf_id(obj);
8567 		if (err)
8568 			return -EINVAL;
8569 	}
8570 	for (i = 0; i < obj->nr_extern; i++) {
8571 		ext = &obj->externs[i];
8572 
8573 		if (!ext->is_set && !ext->is_weak) {
8574 			pr_warn("extern '%s' (strong): not resolved\n", ext->name);
8575 			return -ESRCH;
8576 		} else if (!ext->is_set) {
8577 			pr_debug("extern '%s' (weak): not resolved, defaulting to zero\n",
8578 				 ext->name);
8579 		}
8580 	}
8581 
8582 	return 0;
8583 }
8584 
8585 static void bpf_map_prepare_vdata(const struct bpf_map *map)
8586 {
8587 	const struct btf_type *type;
8588 	struct bpf_struct_ops *st_ops;
8589 	__u32 i;
8590 
8591 	st_ops = map->st_ops;
8592 	type = btf__type_by_id(map->obj->btf, st_ops->type_id);
8593 	for (i = 0; i < btf_vlen(type); i++) {
8594 		struct bpf_program *prog = st_ops->progs[i];
8595 		void *kern_data;
8596 		int prog_fd;
8597 
8598 		if (!prog)
8599 			continue;
8600 
8601 		prog_fd = bpf_program__fd(prog);
8602 		kern_data = st_ops->kern_vdata + st_ops->kern_func_off[i];
8603 		*(unsigned long *)kern_data = prog_fd;
8604 	}
8605 }
8606 
8607 static int bpf_object_prepare_struct_ops(struct bpf_object *obj)
8608 {
8609 	struct bpf_map *map;
8610 	int i;
8611 
8612 	for (i = 0; i < obj->nr_maps; i++) {
8613 		map = &obj->maps[i];
8614 
8615 		if (!bpf_map__is_struct_ops(map))
8616 			continue;
8617 
8618 		if (!map->autocreate)
8619 			continue;
8620 
8621 		bpf_map_prepare_vdata(map);
8622 	}
8623 
8624 	return 0;
8625 }
8626 
8627 static void bpf_object_unpin(struct bpf_object *obj)
8628 {
8629 	int i;
8630 
8631 	/* unpin any maps that were auto-pinned during load */
8632 	for (i = 0; i < obj->nr_maps; i++)
8633 		if (obj->maps[i].pinned && !obj->maps[i].reused)
8634 			bpf_map__unpin(&obj->maps[i], NULL);
8635 }
8636 
8637 static void bpf_object_post_load_cleanup(struct bpf_object *obj)
8638 {
8639 	int i;
8640 
8641 	/* clean up fd_array */
8642 	zfree(&obj->fd_array);
8643 
8644 	/* clean up module BTFs */
8645 	for (i = 0; i < obj->btf_module_cnt; i++) {
8646 		close(obj->btf_modules[i].fd);
8647 		btf__free(obj->btf_modules[i].btf);
8648 		free(obj->btf_modules[i].name);
8649 	}
8650 	obj->btf_module_cnt = 0;
8651 	zfree(&obj->btf_modules);
8652 
8653 	/* clean up vmlinux BTF */
8654 	btf__free(obj->btf_vmlinux);
8655 	obj->btf_vmlinux = NULL;
8656 }
8657 
8658 static int bpf_object_prepare(struct bpf_object *obj, const char *target_btf_path)
8659 {
8660 	int err;
8661 
8662 	if (obj->state >= OBJ_PREPARED) {
8663 		pr_warn("object '%s': prepare loading can't be attempted twice\n", obj->name);
8664 		return -EINVAL;
8665 	}
8666 
8667 	err = bpf_object_prepare_token(obj);
8668 	err = err ? : bpf_object__probe_loading(obj);
8669 	err = err ? : bpf_object__load_vmlinux_btf(obj, false);
8670 	err = err ? : bpf_object__resolve_externs(obj, obj->kconfig);
8671 	err = err ? : bpf_object__sanitize_maps(obj);
8672 	err = err ? : bpf_object__init_kern_struct_ops_maps(obj);
8673 	err = err ? : bpf_object_adjust_struct_ops_autoload(obj);
8674 	err = err ? : bpf_object__relocate(obj, obj->btf_custom_path ? : target_btf_path);
8675 	err = err ? : bpf_object__sanitize_and_load_btf(obj);
8676 	err = err ? : bpf_object__create_maps(obj);
8677 	err = err ? : bpf_object_prepare_progs(obj);
8678 
8679 	if (err) {
8680 		bpf_object_unpin(obj);
8681 		bpf_object_unload(obj);
8682 		obj->state = OBJ_LOADED;
8683 		return err;
8684 	}
8685 
8686 	obj->state = OBJ_PREPARED;
8687 	return 0;
8688 }
8689 
8690 static int bpf_object_load(struct bpf_object *obj, int extra_log_level, const char *target_btf_path)
8691 {
8692 	int err;
8693 
8694 	if (!obj)
8695 		return libbpf_err(-EINVAL);
8696 
8697 	if (obj->state >= OBJ_LOADED) {
8698 		pr_warn("object '%s': load can't be attempted twice\n", obj->name);
8699 		return libbpf_err(-EINVAL);
8700 	}
8701 
8702 	/* Disallow kernel loading programs of non-native endianness but
8703 	 * permit cross-endian creation of "light skeleton".
8704 	 */
8705 	if (obj->gen_loader) {
8706 		bpf_gen__init(obj->gen_loader, extra_log_level, obj->nr_programs, obj->nr_maps);
8707 	} else if (!is_native_endianness(obj)) {
8708 		pr_warn("object '%s': loading non-native endianness is unsupported\n", obj->name);
8709 		return libbpf_err(-LIBBPF_ERRNO__ENDIAN);
8710 	}
8711 
8712 	if (obj->state < OBJ_PREPARED) {
8713 		err = bpf_object_prepare(obj, target_btf_path);
8714 		if (err)
8715 			return libbpf_err(err);
8716 	}
8717 	err = bpf_object__load_progs(obj, extra_log_level);
8718 	err = err ? : bpf_object_init_prog_arrays(obj);
8719 	err = err ? : bpf_object_prepare_struct_ops(obj);
8720 
8721 	if (obj->gen_loader) {
8722 		/* reset FDs */
8723 		if (obj->btf)
8724 			btf__set_fd(obj->btf, -1);
8725 		if (!err)
8726 			err = bpf_gen__finish(obj->gen_loader, obj->nr_programs, obj->nr_maps);
8727 	}
8728 
8729 	bpf_object_post_load_cleanup(obj);
8730 	obj->state = OBJ_LOADED; /* doesn't matter if successfully or not */
8731 
8732 	if (err) {
8733 		bpf_object_unpin(obj);
8734 		bpf_object_unload(obj);
8735 		pr_warn("failed to load object '%s'\n", obj->path);
8736 		return libbpf_err(err);
8737 	}
8738 
8739 	return 0;
8740 }
8741 
8742 int bpf_object__prepare(struct bpf_object *obj)
8743 {
8744 	return libbpf_err(bpf_object_prepare(obj, NULL));
8745 }
8746 
8747 int bpf_object__load(struct bpf_object *obj)
8748 {
8749 	return bpf_object_load(obj, 0, NULL);
8750 }
8751 
8752 static int make_parent_dir(const char *path)
8753 {
8754 	char *dname, *dir;
8755 	int err = 0;
8756 
8757 	dname = strdup(path);
8758 	if (dname == NULL)
8759 		return -ENOMEM;
8760 
8761 	dir = dirname(dname);
8762 	if (mkdir(dir, 0700) && errno != EEXIST)
8763 		err = -errno;
8764 
8765 	free(dname);
8766 	if (err) {
8767 		pr_warn("failed to mkdir %s: %s\n", path, errstr(err));
8768 	}
8769 	return err;
8770 }
8771 
8772 static int check_path(const char *path)
8773 {
8774 	struct statfs st_fs;
8775 	char *dname, *dir;
8776 	int err = 0;
8777 
8778 	if (path == NULL)
8779 		return -EINVAL;
8780 
8781 	dname = strdup(path);
8782 	if (dname == NULL)
8783 		return -ENOMEM;
8784 
8785 	dir = dirname(dname);
8786 	if (statfs(dir, &st_fs)) {
8787 		pr_warn("failed to statfs %s: %s\n", dir, errstr(errno));
8788 		err = -errno;
8789 	}
8790 	free(dname);
8791 
8792 	if (!err && st_fs.f_type != BPF_FS_MAGIC) {
8793 		pr_warn("specified path %s is not on BPF FS\n", path);
8794 		err = -EINVAL;
8795 	}
8796 
8797 	return err;
8798 }
8799 
8800 int bpf_program__pin(struct bpf_program *prog, const char *path)
8801 {
8802 	int err;
8803 
8804 	if (prog->fd < 0) {
8805 		pr_warn("prog '%s': can't pin program that wasn't loaded\n", prog->name);
8806 		return libbpf_err(-EINVAL);
8807 	}
8808 
8809 	err = make_parent_dir(path);
8810 	if (err)
8811 		return libbpf_err(err);
8812 
8813 	err = check_path(path);
8814 	if (err)
8815 		return libbpf_err(err);
8816 
8817 	if (bpf_obj_pin(prog->fd, path)) {
8818 		err = -errno;
8819 		pr_warn("prog '%s': failed to pin at '%s': %s\n", prog->name, path, errstr(err));
8820 		return libbpf_err(err);
8821 	}
8822 
8823 	pr_debug("prog '%s': pinned at '%s'\n", prog->name, path);
8824 	return 0;
8825 }
8826 
8827 int bpf_program__unpin(struct bpf_program *prog, const char *path)
8828 {
8829 	int err;
8830 
8831 	if (prog->fd < 0) {
8832 		pr_warn("prog '%s': can't unpin program that wasn't loaded\n", prog->name);
8833 		return libbpf_err(-EINVAL);
8834 	}
8835 
8836 	err = check_path(path);
8837 	if (err)
8838 		return libbpf_err(err);
8839 
8840 	err = unlink(path);
8841 	if (err)
8842 		return libbpf_err(-errno);
8843 
8844 	pr_debug("prog '%s': unpinned from '%s'\n", prog->name, path);
8845 	return 0;
8846 }
8847 
8848 int bpf_map__pin(struct bpf_map *map, const char *path)
8849 {
8850 	int err;
8851 
8852 	if (map == NULL) {
8853 		pr_warn("invalid map pointer\n");
8854 		return libbpf_err(-EINVAL);
8855 	}
8856 
8857 	if (map->fd < 0) {
8858 		pr_warn("map '%s': can't pin BPF map without FD (was it created?)\n", map->name);
8859 		return libbpf_err(-EINVAL);
8860 	}
8861 
8862 	if (map->pin_path) {
8863 		if (path && strcmp(path, map->pin_path)) {
8864 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
8865 				bpf_map__name(map), map->pin_path, path);
8866 			return libbpf_err(-EINVAL);
8867 		} else if (map->pinned) {
8868 			pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
8869 				 bpf_map__name(map), map->pin_path);
8870 			return 0;
8871 		}
8872 	} else {
8873 		if (!path) {
8874 			pr_warn("missing a path to pin map '%s' at\n",
8875 				bpf_map__name(map));
8876 			return libbpf_err(-EINVAL);
8877 		} else if (map->pinned) {
8878 			pr_warn("map '%s' already pinned\n", bpf_map__name(map));
8879 			return libbpf_err(-EEXIST);
8880 		}
8881 
8882 		map->pin_path = strdup(path);
8883 		if (!map->pin_path) {
8884 			err = -errno;
8885 			goto out_err;
8886 		}
8887 	}
8888 
8889 	err = make_parent_dir(map->pin_path);
8890 	if (err)
8891 		return libbpf_err(err);
8892 
8893 	err = check_path(map->pin_path);
8894 	if (err)
8895 		return libbpf_err(err);
8896 
8897 	if (bpf_obj_pin(map->fd, map->pin_path)) {
8898 		err = -errno;
8899 		goto out_err;
8900 	}
8901 
8902 	map->pinned = true;
8903 	pr_debug("pinned map '%s'\n", map->pin_path);
8904 
8905 	return 0;
8906 
8907 out_err:
8908 	pr_warn("failed to pin map: %s\n", errstr(err));
8909 	return libbpf_err(err);
8910 }
8911 
8912 int bpf_map__unpin(struct bpf_map *map, const char *path)
8913 {
8914 	int err;
8915 
8916 	if (map == NULL) {
8917 		pr_warn("invalid map pointer\n");
8918 		return libbpf_err(-EINVAL);
8919 	}
8920 
8921 	if (map->pin_path) {
8922 		if (path && strcmp(path, map->pin_path)) {
8923 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
8924 				bpf_map__name(map), map->pin_path, path);
8925 			return libbpf_err(-EINVAL);
8926 		}
8927 		path = map->pin_path;
8928 	} else if (!path) {
8929 		pr_warn("no path to unpin map '%s' from\n",
8930 			bpf_map__name(map));
8931 		return libbpf_err(-EINVAL);
8932 	}
8933 
8934 	err = check_path(path);
8935 	if (err)
8936 		return libbpf_err(err);
8937 
8938 	err = unlink(path);
8939 	if (err != 0)
8940 		return libbpf_err(-errno);
8941 
8942 	map->pinned = false;
8943 	pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path);
8944 
8945 	return 0;
8946 }
8947 
8948 int bpf_map__set_pin_path(struct bpf_map *map, const char *path)
8949 {
8950 	char *new = NULL;
8951 
8952 	if (path) {
8953 		new = strdup(path);
8954 		if (!new)
8955 			return libbpf_err(-errno);
8956 	}
8957 
8958 	free(map->pin_path);
8959 	map->pin_path = new;
8960 	return 0;
8961 }
8962 
8963 __alias(bpf_map__pin_path)
8964 const char *bpf_map__get_pin_path(const struct bpf_map *map);
8965 
8966 const char *bpf_map__pin_path(const struct bpf_map *map)
8967 {
8968 	return map->pin_path;
8969 }
8970 
8971 bool bpf_map__is_pinned(const struct bpf_map *map)
8972 {
8973 	return map->pinned;
8974 }
8975 
8976 static void sanitize_pin_path(char *s)
8977 {
8978 	/* bpffs disallows periods in path names */
8979 	while (*s) {
8980 		if (*s == '.')
8981 			*s = '_';
8982 		s++;
8983 	}
8984 }
8985 
8986 int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
8987 {
8988 	struct bpf_map *map;
8989 	int err;
8990 
8991 	if (!obj)
8992 		return libbpf_err(-ENOENT);
8993 
8994 	if (obj->state < OBJ_PREPARED) {
8995 		pr_warn("object not yet loaded; load it first\n");
8996 		return libbpf_err(-ENOENT);
8997 	}
8998 
8999 	bpf_object__for_each_map(map, obj) {
9000 		char *pin_path = NULL;
9001 		char buf[PATH_MAX];
9002 
9003 		if (!map->autocreate)
9004 			continue;
9005 
9006 		if (path) {
9007 			err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
9008 			if (err)
9009 				goto err_unpin_maps;
9010 			sanitize_pin_path(buf);
9011 			pin_path = buf;
9012 		} else if (!map->pin_path) {
9013 			continue;
9014 		}
9015 
9016 		err = bpf_map__pin(map, pin_path);
9017 		if (err)
9018 			goto err_unpin_maps;
9019 	}
9020 
9021 	return 0;
9022 
9023 err_unpin_maps:
9024 	while ((map = bpf_object__prev_map(obj, map))) {
9025 		if (!map->pin_path)
9026 			continue;
9027 
9028 		bpf_map__unpin(map, NULL);
9029 	}
9030 
9031 	return libbpf_err(err);
9032 }
9033 
9034 int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
9035 {
9036 	struct bpf_map *map;
9037 	int err;
9038 
9039 	if (!obj)
9040 		return libbpf_err(-ENOENT);
9041 
9042 	bpf_object__for_each_map(map, obj) {
9043 		char *pin_path = NULL;
9044 		char buf[PATH_MAX];
9045 
9046 		if (path) {
9047 			err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
9048 			if (err)
9049 				return libbpf_err(err);
9050 			sanitize_pin_path(buf);
9051 			pin_path = buf;
9052 		} else if (!map->pin_path) {
9053 			continue;
9054 		}
9055 
9056 		err = bpf_map__unpin(map, pin_path);
9057 		if (err)
9058 			return libbpf_err(err);
9059 	}
9060 
9061 	return 0;
9062 }
9063 
9064 int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
9065 {
9066 	struct bpf_program *prog;
9067 	char buf[PATH_MAX];
9068 	int err;
9069 
9070 	if (!obj)
9071 		return libbpf_err(-ENOENT);
9072 
9073 	if (obj->state < OBJ_LOADED) {
9074 		pr_warn("object not yet loaded; load it first\n");
9075 		return libbpf_err(-ENOENT);
9076 	}
9077 
9078 	bpf_object__for_each_program(prog, obj) {
9079 		err = pathname_concat(buf, sizeof(buf), path, prog->name);
9080 		if (err)
9081 			goto err_unpin_programs;
9082 
9083 		err = bpf_program__pin(prog, buf);
9084 		if (err)
9085 			goto err_unpin_programs;
9086 	}
9087 
9088 	return 0;
9089 
9090 err_unpin_programs:
9091 	while ((prog = bpf_object__prev_program(obj, prog))) {
9092 		if (pathname_concat(buf, sizeof(buf), path, prog->name))
9093 			continue;
9094 
9095 		bpf_program__unpin(prog, buf);
9096 	}
9097 
9098 	return libbpf_err(err);
9099 }
9100 
9101 int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
9102 {
9103 	struct bpf_program *prog;
9104 	int err;
9105 
9106 	if (!obj)
9107 		return libbpf_err(-ENOENT);
9108 
9109 	bpf_object__for_each_program(prog, obj) {
9110 		char buf[PATH_MAX];
9111 
9112 		err = pathname_concat(buf, sizeof(buf), path, prog->name);
9113 		if (err)
9114 			return libbpf_err(err);
9115 
9116 		err = bpf_program__unpin(prog, buf);
9117 		if (err)
9118 			return libbpf_err(err);
9119 	}
9120 
9121 	return 0;
9122 }
9123 
9124 int bpf_object__pin(struct bpf_object *obj, const char *path)
9125 {
9126 	int err;
9127 
9128 	err = bpf_object__pin_maps(obj, path);
9129 	if (err)
9130 		return libbpf_err(err);
9131 
9132 	err = bpf_object__pin_programs(obj, path);
9133 	if (err) {
9134 		bpf_object__unpin_maps(obj, path);
9135 		return libbpf_err(err);
9136 	}
9137 
9138 	return 0;
9139 }
9140 
9141 int bpf_object__unpin(struct bpf_object *obj, const char *path)
9142 {
9143 	int err;
9144 
9145 	err = bpf_object__unpin_programs(obj, path);
9146 	if (err)
9147 		return libbpf_err(err);
9148 
9149 	err = bpf_object__unpin_maps(obj, path);
9150 	if (err)
9151 		return libbpf_err(err);
9152 
9153 	return 0;
9154 }
9155 
9156 static void bpf_map__destroy(struct bpf_map *map)
9157 {
9158 	if (map->inner_map) {
9159 		bpf_map__destroy(map->inner_map);
9160 		zfree(&map->inner_map);
9161 	}
9162 
9163 	zfree(&map->init_slots);
9164 	map->init_slots_sz = 0;
9165 
9166 	if (map->mmaped && map->mmaped != map->obj->arena_data)
9167 		munmap(map->mmaped, bpf_map_mmap_sz(map));
9168 	map->mmaped = NULL;
9169 
9170 	if (map->st_ops) {
9171 		zfree(&map->st_ops->data);
9172 		zfree(&map->st_ops->progs);
9173 		zfree(&map->st_ops->kern_func_off);
9174 		zfree(&map->st_ops);
9175 	}
9176 
9177 	zfree(&map->name);
9178 	zfree(&map->real_name);
9179 	zfree(&map->pin_path);
9180 
9181 	if (map->fd >= 0)
9182 		zclose(map->fd);
9183 }
9184 
9185 void bpf_object__close(struct bpf_object *obj)
9186 {
9187 	size_t i;
9188 
9189 	if (IS_ERR_OR_NULL(obj))
9190 		return;
9191 
9192 	/*
9193 	 * if user called bpf_object__prepare() without ever getting to
9194 	 * bpf_object__load(), we need to clean up stuff that is normally
9195 	 * cleaned up at the end of loading step
9196 	 */
9197 	bpf_object_post_load_cleanup(obj);
9198 
9199 	usdt_manager_free(obj->usdt_man);
9200 	obj->usdt_man = NULL;
9201 
9202 	bpf_gen__free(obj->gen_loader);
9203 	bpf_object__elf_finish(obj);
9204 	bpf_object_unload(obj);
9205 	btf__free(obj->btf);
9206 	btf__free(obj->btf_vmlinux);
9207 	btf_ext__free(obj->btf_ext);
9208 
9209 	for (i = 0; i < obj->nr_maps; i++)
9210 		bpf_map__destroy(&obj->maps[i]);
9211 
9212 	zfree(&obj->btf_custom_path);
9213 	zfree(&obj->kconfig);
9214 
9215 	for (i = 0; i < obj->nr_extern; i++) {
9216 		zfree(&obj->externs[i].name);
9217 		zfree(&obj->externs[i].essent_name);
9218 	}
9219 
9220 	zfree(&obj->externs);
9221 	obj->nr_extern = 0;
9222 
9223 	zfree(&obj->maps);
9224 	obj->nr_maps = 0;
9225 
9226 	if (obj->programs && obj->nr_programs) {
9227 		for (i = 0; i < obj->nr_programs; i++)
9228 			bpf_program__exit(&obj->programs[i]);
9229 	}
9230 	zfree(&obj->programs);
9231 
9232 	zfree(&obj->feat_cache);
9233 	zfree(&obj->token_path);
9234 	if (obj->token_fd > 0)
9235 		close(obj->token_fd);
9236 
9237 	zfree(&obj->arena_data);
9238 
9239 	free(obj);
9240 }
9241 
9242 const char *bpf_object__name(const struct bpf_object *obj)
9243 {
9244 	return obj ? obj->name : libbpf_err_ptr(-EINVAL);
9245 }
9246 
9247 unsigned int bpf_object__kversion(const struct bpf_object *obj)
9248 {
9249 	return obj ? obj->kern_version : 0;
9250 }
9251 
9252 int bpf_object__token_fd(const struct bpf_object *obj)
9253 {
9254 	return obj->token_fd ?: -1;
9255 }
9256 
9257 struct btf *bpf_object__btf(const struct bpf_object *obj)
9258 {
9259 	return obj ? obj->btf : NULL;
9260 }
9261 
9262 int bpf_object__btf_fd(const struct bpf_object *obj)
9263 {
9264 	return obj->btf ? btf__fd(obj->btf) : -1;
9265 }
9266 
9267 int bpf_object__set_kversion(struct bpf_object *obj, __u32 kern_version)
9268 {
9269 	if (obj->state >= OBJ_LOADED)
9270 		return libbpf_err(-EINVAL);
9271 
9272 	obj->kern_version = kern_version;
9273 
9274 	return 0;
9275 }
9276 
9277 int bpf_object__gen_loader(struct bpf_object *obj, struct gen_loader_opts *opts)
9278 {
9279 	struct bpf_gen *gen;
9280 
9281 	if (!opts)
9282 		return libbpf_err(-EFAULT);
9283 	if (!OPTS_VALID(opts, gen_loader_opts))
9284 		return libbpf_err(-EINVAL);
9285 	gen = calloc(1, sizeof(*gen));
9286 	if (!gen)
9287 		return libbpf_err(-ENOMEM);
9288 	gen->opts = opts;
9289 	gen->swapped_endian = !is_native_endianness(obj);
9290 	obj->gen_loader = gen;
9291 	return 0;
9292 }
9293 
9294 static struct bpf_program *
9295 __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
9296 		    bool forward)
9297 {
9298 	size_t nr_programs = obj->nr_programs;
9299 	ssize_t idx;
9300 
9301 	if (!nr_programs)
9302 		return NULL;
9303 
9304 	if (!p)
9305 		/* Iter from the beginning */
9306 		return forward ? &obj->programs[0] :
9307 			&obj->programs[nr_programs - 1];
9308 
9309 	if (p->obj != obj) {
9310 		pr_warn("error: program handler doesn't match object\n");
9311 		return errno = EINVAL, NULL;
9312 	}
9313 
9314 	idx = (p - obj->programs) + (forward ? 1 : -1);
9315 	if (idx >= obj->nr_programs || idx < 0)
9316 		return NULL;
9317 	return &obj->programs[idx];
9318 }
9319 
9320 struct bpf_program *
9321 bpf_object__next_program(const struct bpf_object *obj, struct bpf_program *prev)
9322 {
9323 	struct bpf_program *prog = prev;
9324 
9325 	do {
9326 		prog = __bpf_program__iter(prog, obj, true);
9327 	} while (prog && prog_is_subprog(obj, prog));
9328 
9329 	return prog;
9330 }
9331 
9332 struct bpf_program *
9333 bpf_object__prev_program(const struct bpf_object *obj, struct bpf_program *next)
9334 {
9335 	struct bpf_program *prog = next;
9336 
9337 	do {
9338 		prog = __bpf_program__iter(prog, obj, false);
9339 	} while (prog && prog_is_subprog(obj, prog));
9340 
9341 	return prog;
9342 }
9343 
9344 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
9345 {
9346 	prog->prog_ifindex = ifindex;
9347 }
9348 
9349 const char *bpf_program__name(const struct bpf_program *prog)
9350 {
9351 	return prog->name;
9352 }
9353 
9354 const char *bpf_program__section_name(const struct bpf_program *prog)
9355 {
9356 	return prog->sec_name;
9357 }
9358 
9359 bool bpf_program__autoload(const struct bpf_program *prog)
9360 {
9361 	return prog->autoload;
9362 }
9363 
9364 int bpf_program__set_autoload(struct bpf_program *prog, bool autoload)
9365 {
9366 	if (prog->obj->state >= OBJ_LOADED)
9367 		return libbpf_err(-EINVAL);
9368 
9369 	prog->autoload = autoload;
9370 	return 0;
9371 }
9372 
9373 bool bpf_program__autoattach(const struct bpf_program *prog)
9374 {
9375 	return prog->autoattach;
9376 }
9377 
9378 void bpf_program__set_autoattach(struct bpf_program *prog, bool autoattach)
9379 {
9380 	prog->autoattach = autoattach;
9381 }
9382 
9383 const struct bpf_insn *bpf_program__insns(const struct bpf_program *prog)
9384 {
9385 	return prog->insns;
9386 }
9387 
9388 size_t bpf_program__insn_cnt(const struct bpf_program *prog)
9389 {
9390 	return prog->insns_cnt;
9391 }
9392 
9393 int bpf_program__set_insns(struct bpf_program *prog,
9394 			   struct bpf_insn *new_insns, size_t new_insn_cnt)
9395 {
9396 	struct bpf_insn *insns;
9397 
9398 	if (prog->obj->state >= OBJ_LOADED)
9399 		return libbpf_err(-EBUSY);
9400 
9401 	insns = libbpf_reallocarray(prog->insns, new_insn_cnt, sizeof(*insns));
9402 	/* NULL is a valid return from reallocarray if the new count is zero */
9403 	if (!insns && new_insn_cnt) {
9404 		pr_warn("prog '%s': failed to realloc prog code\n", prog->name);
9405 		return libbpf_err(-ENOMEM);
9406 	}
9407 	memcpy(insns, new_insns, new_insn_cnt * sizeof(*insns));
9408 
9409 	prog->insns = insns;
9410 	prog->insns_cnt = new_insn_cnt;
9411 	return 0;
9412 }
9413 
9414 int bpf_program__fd(const struct bpf_program *prog)
9415 {
9416 	if (!prog)
9417 		return libbpf_err(-EINVAL);
9418 
9419 	if (prog->fd < 0)
9420 		return libbpf_err(-ENOENT);
9421 
9422 	return prog->fd;
9423 }
9424 
9425 __alias(bpf_program__type)
9426 enum bpf_prog_type bpf_program__get_type(const struct bpf_program *prog);
9427 
9428 enum bpf_prog_type bpf_program__type(const struct bpf_program *prog)
9429 {
9430 	return prog->type;
9431 }
9432 
9433 static size_t custom_sec_def_cnt;
9434 static struct bpf_sec_def *custom_sec_defs;
9435 static struct bpf_sec_def custom_fallback_def;
9436 static bool has_custom_fallback_def;
9437 static int last_custom_sec_def_handler_id;
9438 
9439 int bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
9440 {
9441 	if (prog->obj->state >= OBJ_LOADED)
9442 		return libbpf_err(-EBUSY);
9443 
9444 	/* if type is not changed, do nothing */
9445 	if (prog->type == type)
9446 		return 0;
9447 
9448 	prog->type = type;
9449 
9450 	/* If a program type was changed, we need to reset associated SEC()
9451 	 * handler, as it will be invalid now. The only exception is a generic
9452 	 * fallback handler, which by definition is program type-agnostic and
9453 	 * is a catch-all custom handler, optionally set by the application,
9454 	 * so should be able to handle any type of BPF program.
9455 	 */
9456 	if (prog->sec_def != &custom_fallback_def)
9457 		prog->sec_def = NULL;
9458 	return 0;
9459 }
9460 
9461 __alias(bpf_program__expected_attach_type)
9462 enum bpf_attach_type bpf_program__get_expected_attach_type(const struct bpf_program *prog);
9463 
9464 enum bpf_attach_type bpf_program__expected_attach_type(const struct bpf_program *prog)
9465 {
9466 	return prog->expected_attach_type;
9467 }
9468 
9469 int bpf_program__set_expected_attach_type(struct bpf_program *prog,
9470 					   enum bpf_attach_type type)
9471 {
9472 	if (prog->obj->state >= OBJ_LOADED)
9473 		return libbpf_err(-EBUSY);
9474 
9475 	prog->expected_attach_type = type;
9476 	return 0;
9477 }
9478 
9479 __u32 bpf_program__flags(const struct bpf_program *prog)
9480 {
9481 	return prog->prog_flags;
9482 }
9483 
9484 int bpf_program__set_flags(struct bpf_program *prog, __u32 flags)
9485 {
9486 	if (prog->obj->state >= OBJ_LOADED)
9487 		return libbpf_err(-EBUSY);
9488 
9489 	prog->prog_flags = flags;
9490 	return 0;
9491 }
9492 
9493 __u32 bpf_program__log_level(const struct bpf_program *prog)
9494 {
9495 	return prog->log_level;
9496 }
9497 
9498 int bpf_program__set_log_level(struct bpf_program *prog, __u32 log_level)
9499 {
9500 	if (prog->obj->state >= OBJ_LOADED)
9501 		return libbpf_err(-EBUSY);
9502 
9503 	prog->log_level = log_level;
9504 	return 0;
9505 }
9506 
9507 const char *bpf_program__log_buf(const struct bpf_program *prog, size_t *log_size)
9508 {
9509 	*log_size = prog->log_size;
9510 	return prog->log_buf;
9511 }
9512 
9513 int bpf_program__set_log_buf(struct bpf_program *prog, char *log_buf, size_t log_size)
9514 {
9515 	if (log_size && !log_buf)
9516 		return libbpf_err(-EINVAL);
9517 	if (prog->log_size > UINT_MAX)
9518 		return libbpf_err(-EINVAL);
9519 	if (prog->obj->state >= OBJ_LOADED)
9520 		return libbpf_err(-EBUSY);
9521 
9522 	prog->log_buf = log_buf;
9523 	prog->log_size = log_size;
9524 	return 0;
9525 }
9526 
9527 struct bpf_func_info *bpf_program__func_info(const struct bpf_program *prog)
9528 {
9529 	if (prog->func_info_rec_size != sizeof(struct bpf_func_info))
9530 		return libbpf_err_ptr(-EOPNOTSUPP);
9531 	return prog->func_info;
9532 }
9533 
9534 __u32 bpf_program__func_info_cnt(const struct bpf_program *prog)
9535 {
9536 	return prog->func_info_cnt;
9537 }
9538 
9539 struct bpf_line_info *bpf_program__line_info(const struct bpf_program *prog)
9540 {
9541 	if (prog->line_info_rec_size != sizeof(struct bpf_line_info))
9542 		return libbpf_err_ptr(-EOPNOTSUPP);
9543 	return prog->line_info;
9544 }
9545 
9546 __u32 bpf_program__line_info_cnt(const struct bpf_program *prog)
9547 {
9548 	return prog->line_info_cnt;
9549 }
9550 
9551 #define SEC_DEF(sec_pfx, ptype, atype, flags, ...) {			    \
9552 	.sec = (char *)sec_pfx,						    \
9553 	.prog_type = BPF_PROG_TYPE_##ptype,				    \
9554 	.expected_attach_type = atype,					    \
9555 	.cookie = (long)(flags),					    \
9556 	.prog_prepare_load_fn = libbpf_prepare_prog_load,		    \
9557 	__VA_ARGS__							    \
9558 }
9559 
9560 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9561 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9562 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9563 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9564 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9565 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9566 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9567 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9568 static int attach_kprobe_session(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9569 static int attach_uprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9570 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9571 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link);
9572 
9573 static const struct bpf_sec_def section_defs[] = {
9574 	SEC_DEF("socket",		SOCKET_FILTER, 0, SEC_NONE),
9575 	SEC_DEF("sk_reuseport/migrate",	SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT_OR_MIGRATE, SEC_ATTACHABLE),
9576 	SEC_DEF("sk_reuseport",		SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT, SEC_ATTACHABLE),
9577 	SEC_DEF("kprobe+",		KPROBE,	0, SEC_NONE, attach_kprobe),
9578 	SEC_DEF("uprobe+",		KPROBE,	0, SEC_NONE, attach_uprobe),
9579 	SEC_DEF("uprobe.s+",		KPROBE,	0, SEC_SLEEPABLE, attach_uprobe),
9580 	SEC_DEF("kretprobe+",		KPROBE, 0, SEC_NONE, attach_kprobe),
9581 	SEC_DEF("uretprobe+",		KPROBE, 0, SEC_NONE, attach_uprobe),
9582 	SEC_DEF("uretprobe.s+",		KPROBE, 0, SEC_SLEEPABLE, attach_uprobe),
9583 	SEC_DEF("kprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
9584 	SEC_DEF("kretprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
9585 	SEC_DEF("kprobe.session+",	KPROBE,	BPF_TRACE_KPROBE_SESSION, SEC_NONE, attach_kprobe_session),
9586 	SEC_DEF("uprobe.multi+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_NONE, attach_uprobe_multi),
9587 	SEC_DEF("uretprobe.multi+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_NONE, attach_uprobe_multi),
9588 	SEC_DEF("uprobe.session+",	KPROBE,	BPF_TRACE_UPROBE_SESSION, SEC_NONE, attach_uprobe_multi),
9589 	SEC_DEF("uprobe.multi.s+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_SLEEPABLE, attach_uprobe_multi),
9590 	SEC_DEF("uretprobe.multi.s+",	KPROBE,	BPF_TRACE_UPROBE_MULTI, SEC_SLEEPABLE, attach_uprobe_multi),
9591 	SEC_DEF("uprobe.session.s+",	KPROBE,	BPF_TRACE_UPROBE_SESSION, SEC_SLEEPABLE, attach_uprobe_multi),
9592 	SEC_DEF("ksyscall+",		KPROBE,	0, SEC_NONE, attach_ksyscall),
9593 	SEC_DEF("kretsyscall+",		KPROBE, 0, SEC_NONE, attach_ksyscall),
9594 	SEC_DEF("usdt+",		KPROBE,	0, SEC_USDT, attach_usdt),
9595 	SEC_DEF("usdt.s+",		KPROBE,	0, SEC_USDT | SEC_SLEEPABLE, attach_usdt),
9596 	SEC_DEF("tc/ingress",		SCHED_CLS, BPF_TCX_INGRESS, SEC_NONE), /* alias for tcx */
9597 	SEC_DEF("tc/egress",		SCHED_CLS, BPF_TCX_EGRESS, SEC_NONE),  /* alias for tcx */
9598 	SEC_DEF("tcx/ingress",		SCHED_CLS, BPF_TCX_INGRESS, SEC_NONE),
9599 	SEC_DEF("tcx/egress",		SCHED_CLS, BPF_TCX_EGRESS, SEC_NONE),
9600 	SEC_DEF("tc",			SCHED_CLS, 0, SEC_NONE), /* deprecated / legacy, use tcx */
9601 	SEC_DEF("classifier",		SCHED_CLS, 0, SEC_NONE), /* deprecated / legacy, use tcx */
9602 	SEC_DEF("action",		SCHED_ACT, 0, SEC_NONE), /* deprecated / legacy, use tcx */
9603 	SEC_DEF("netkit/primary",	SCHED_CLS, BPF_NETKIT_PRIMARY, SEC_NONE),
9604 	SEC_DEF("netkit/peer",		SCHED_CLS, BPF_NETKIT_PEER, SEC_NONE),
9605 	SEC_DEF("tracepoint+",		TRACEPOINT, 0, SEC_NONE, attach_tp),
9606 	SEC_DEF("tp+",			TRACEPOINT, 0, SEC_NONE, attach_tp),
9607 	SEC_DEF("raw_tracepoint+",	RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
9608 	SEC_DEF("raw_tp+",		RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
9609 	SEC_DEF("raw_tracepoint.w+",	RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
9610 	SEC_DEF("raw_tp.w+",		RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
9611 	SEC_DEF("tp_btf+",		TRACING, BPF_TRACE_RAW_TP, SEC_ATTACH_BTF, attach_trace),
9612 	SEC_DEF("fentry+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF, attach_trace),
9613 	SEC_DEF("fmod_ret+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF, attach_trace),
9614 	SEC_DEF("fexit+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF, attach_trace),
9615 	SEC_DEF("fentry.s+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
9616 	SEC_DEF("fmod_ret.s+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
9617 	SEC_DEF("fexit.s+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
9618 	SEC_DEF("freplace+",		EXT, 0, SEC_ATTACH_BTF, attach_trace),
9619 	SEC_DEF("lsm+",			LSM, BPF_LSM_MAC, SEC_ATTACH_BTF, attach_lsm),
9620 	SEC_DEF("lsm.s+",		LSM, BPF_LSM_MAC, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_lsm),
9621 	SEC_DEF("lsm_cgroup+",		LSM, BPF_LSM_CGROUP, SEC_ATTACH_BTF),
9622 	SEC_DEF("iter+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF, attach_iter),
9623 	SEC_DEF("iter.s+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_iter),
9624 	SEC_DEF("syscall",		SYSCALL, 0, SEC_SLEEPABLE),
9625 	SEC_DEF("xdp.frags/devmap",	XDP, BPF_XDP_DEVMAP, SEC_XDP_FRAGS),
9626 	SEC_DEF("xdp/devmap",		XDP, BPF_XDP_DEVMAP, SEC_ATTACHABLE),
9627 	SEC_DEF("xdp.frags/cpumap",	XDP, BPF_XDP_CPUMAP, SEC_XDP_FRAGS),
9628 	SEC_DEF("xdp/cpumap",		XDP, BPF_XDP_CPUMAP, SEC_ATTACHABLE),
9629 	SEC_DEF("xdp.frags",		XDP, BPF_XDP, SEC_XDP_FRAGS),
9630 	SEC_DEF("xdp",			XDP, BPF_XDP, SEC_ATTACHABLE_OPT),
9631 	SEC_DEF("perf_event",		PERF_EVENT, 0, SEC_NONE),
9632 	SEC_DEF("lwt_in",		LWT_IN, 0, SEC_NONE),
9633 	SEC_DEF("lwt_out",		LWT_OUT, 0, SEC_NONE),
9634 	SEC_DEF("lwt_xmit",		LWT_XMIT, 0, SEC_NONE),
9635 	SEC_DEF("lwt_seg6local",	LWT_SEG6LOCAL, 0, SEC_NONE),
9636 	SEC_DEF("sockops",		SOCK_OPS, BPF_CGROUP_SOCK_OPS, SEC_ATTACHABLE_OPT),
9637 	SEC_DEF("sk_skb/stream_parser",	SK_SKB, BPF_SK_SKB_STREAM_PARSER, SEC_ATTACHABLE_OPT),
9638 	SEC_DEF("sk_skb/stream_verdict",SK_SKB, BPF_SK_SKB_STREAM_VERDICT, SEC_ATTACHABLE_OPT),
9639 	SEC_DEF("sk_skb/verdict",	SK_SKB, BPF_SK_SKB_VERDICT, SEC_ATTACHABLE_OPT),
9640 	SEC_DEF("sk_skb",		SK_SKB, 0, SEC_NONE),
9641 	SEC_DEF("sk_msg",		SK_MSG, BPF_SK_MSG_VERDICT, SEC_ATTACHABLE_OPT),
9642 	SEC_DEF("lirc_mode2",		LIRC_MODE2, BPF_LIRC_MODE2, SEC_ATTACHABLE_OPT),
9643 	SEC_DEF("flow_dissector",	FLOW_DISSECTOR, BPF_FLOW_DISSECTOR, SEC_ATTACHABLE_OPT),
9644 	SEC_DEF("cgroup_skb/ingress",	CGROUP_SKB, BPF_CGROUP_INET_INGRESS, SEC_ATTACHABLE_OPT),
9645 	SEC_DEF("cgroup_skb/egress",	CGROUP_SKB, BPF_CGROUP_INET_EGRESS, SEC_ATTACHABLE_OPT),
9646 	SEC_DEF("cgroup/skb",		CGROUP_SKB, 0, SEC_NONE),
9647 	SEC_DEF("cgroup/sock_create",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE),
9648 	SEC_DEF("cgroup/sock_release",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_RELEASE, SEC_ATTACHABLE),
9649 	SEC_DEF("cgroup/sock",		CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE_OPT),
9650 	SEC_DEF("cgroup/post_bind4",	CGROUP_SOCK, BPF_CGROUP_INET4_POST_BIND, SEC_ATTACHABLE),
9651 	SEC_DEF("cgroup/post_bind6",	CGROUP_SOCK, BPF_CGROUP_INET6_POST_BIND, SEC_ATTACHABLE),
9652 	SEC_DEF("cgroup/bind4",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND, SEC_ATTACHABLE),
9653 	SEC_DEF("cgroup/bind6",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND, SEC_ATTACHABLE),
9654 	SEC_DEF("cgroup/connect4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT, SEC_ATTACHABLE),
9655 	SEC_DEF("cgroup/connect6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT, SEC_ATTACHABLE),
9656 	SEC_DEF("cgroup/connect_unix",	CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_CONNECT, SEC_ATTACHABLE),
9657 	SEC_DEF("cgroup/sendmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG, SEC_ATTACHABLE),
9658 	SEC_DEF("cgroup/sendmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG, SEC_ATTACHABLE),
9659 	SEC_DEF("cgroup/sendmsg_unix",	CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_SENDMSG, SEC_ATTACHABLE),
9660 	SEC_DEF("cgroup/recvmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_RECVMSG, SEC_ATTACHABLE),
9661 	SEC_DEF("cgroup/recvmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_RECVMSG, SEC_ATTACHABLE),
9662 	SEC_DEF("cgroup/recvmsg_unix",	CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_RECVMSG, SEC_ATTACHABLE),
9663 	SEC_DEF("cgroup/getpeername4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETPEERNAME, SEC_ATTACHABLE),
9664 	SEC_DEF("cgroup/getpeername6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETPEERNAME, SEC_ATTACHABLE),
9665 	SEC_DEF("cgroup/getpeername_unix", CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_GETPEERNAME, SEC_ATTACHABLE),
9666 	SEC_DEF("cgroup/getsockname4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETSOCKNAME, SEC_ATTACHABLE),
9667 	SEC_DEF("cgroup/getsockname6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETSOCKNAME, SEC_ATTACHABLE),
9668 	SEC_DEF("cgroup/getsockname_unix", CGROUP_SOCK_ADDR, BPF_CGROUP_UNIX_GETSOCKNAME, SEC_ATTACHABLE),
9669 	SEC_DEF("cgroup/sysctl",	CGROUP_SYSCTL, BPF_CGROUP_SYSCTL, SEC_ATTACHABLE),
9670 	SEC_DEF("cgroup/getsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_GETSOCKOPT, SEC_ATTACHABLE),
9671 	SEC_DEF("cgroup/setsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_SETSOCKOPT, SEC_ATTACHABLE),
9672 	SEC_DEF("cgroup/dev",		CGROUP_DEVICE, BPF_CGROUP_DEVICE, SEC_ATTACHABLE_OPT),
9673 	SEC_DEF("struct_ops+",		STRUCT_OPS, 0, SEC_NONE),
9674 	SEC_DEF("struct_ops.s+",	STRUCT_OPS, 0, SEC_SLEEPABLE),
9675 	SEC_DEF("sk_lookup",		SK_LOOKUP, BPF_SK_LOOKUP, SEC_ATTACHABLE),
9676 	SEC_DEF("netfilter",		NETFILTER, BPF_NETFILTER, SEC_NONE),
9677 };
9678 
9679 int libbpf_register_prog_handler(const char *sec,
9680 				 enum bpf_prog_type prog_type,
9681 				 enum bpf_attach_type exp_attach_type,
9682 				 const struct libbpf_prog_handler_opts *opts)
9683 {
9684 	struct bpf_sec_def *sec_def;
9685 
9686 	if (!OPTS_VALID(opts, libbpf_prog_handler_opts))
9687 		return libbpf_err(-EINVAL);
9688 
9689 	if (last_custom_sec_def_handler_id == INT_MAX) /* prevent overflow */
9690 		return libbpf_err(-E2BIG);
9691 
9692 	if (sec) {
9693 		sec_def = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt + 1,
9694 					      sizeof(*sec_def));
9695 		if (!sec_def)
9696 			return libbpf_err(-ENOMEM);
9697 
9698 		custom_sec_defs = sec_def;
9699 		sec_def = &custom_sec_defs[custom_sec_def_cnt];
9700 	} else {
9701 		if (has_custom_fallback_def)
9702 			return libbpf_err(-EBUSY);
9703 
9704 		sec_def = &custom_fallback_def;
9705 	}
9706 
9707 	sec_def->sec = sec ? strdup(sec) : NULL;
9708 	if (sec && !sec_def->sec)
9709 		return libbpf_err(-ENOMEM);
9710 
9711 	sec_def->prog_type = prog_type;
9712 	sec_def->expected_attach_type = exp_attach_type;
9713 	sec_def->cookie = OPTS_GET(opts, cookie, 0);
9714 
9715 	sec_def->prog_setup_fn = OPTS_GET(opts, prog_setup_fn, NULL);
9716 	sec_def->prog_prepare_load_fn = OPTS_GET(opts, prog_prepare_load_fn, NULL);
9717 	sec_def->prog_attach_fn = OPTS_GET(opts, prog_attach_fn, NULL);
9718 
9719 	sec_def->handler_id = ++last_custom_sec_def_handler_id;
9720 
9721 	if (sec)
9722 		custom_sec_def_cnt++;
9723 	else
9724 		has_custom_fallback_def = true;
9725 
9726 	return sec_def->handler_id;
9727 }
9728 
9729 int libbpf_unregister_prog_handler(int handler_id)
9730 {
9731 	struct bpf_sec_def *sec_defs;
9732 	int i;
9733 
9734 	if (handler_id <= 0)
9735 		return libbpf_err(-EINVAL);
9736 
9737 	if (has_custom_fallback_def && custom_fallback_def.handler_id == handler_id) {
9738 		memset(&custom_fallback_def, 0, sizeof(custom_fallback_def));
9739 		has_custom_fallback_def = false;
9740 		return 0;
9741 	}
9742 
9743 	for (i = 0; i < custom_sec_def_cnt; i++) {
9744 		if (custom_sec_defs[i].handler_id == handler_id)
9745 			break;
9746 	}
9747 
9748 	if (i == custom_sec_def_cnt)
9749 		return libbpf_err(-ENOENT);
9750 
9751 	free(custom_sec_defs[i].sec);
9752 	for (i = i + 1; i < custom_sec_def_cnt; i++)
9753 		custom_sec_defs[i - 1] = custom_sec_defs[i];
9754 	custom_sec_def_cnt--;
9755 
9756 	/* try to shrink the array, but it's ok if we couldn't */
9757 	sec_defs = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt, sizeof(*sec_defs));
9758 	/* if new count is zero, reallocarray can return a valid NULL result;
9759 	 * in this case the previous pointer will be freed, so we *have to*
9760 	 * reassign old pointer to the new value (even if it's NULL)
9761 	 */
9762 	if (sec_defs || custom_sec_def_cnt == 0)
9763 		custom_sec_defs = sec_defs;
9764 
9765 	return 0;
9766 }
9767 
9768 static bool sec_def_matches(const struct bpf_sec_def *sec_def, const char *sec_name)
9769 {
9770 	size_t len = strlen(sec_def->sec);
9771 
9772 	/* "type/" always has to have proper SEC("type/extras") form */
9773 	if (sec_def->sec[len - 1] == '/') {
9774 		if (str_has_pfx(sec_name, sec_def->sec))
9775 			return true;
9776 		return false;
9777 	}
9778 
9779 	/* "type+" means it can be either exact SEC("type") or
9780 	 * well-formed SEC("type/extras") with proper '/' separator
9781 	 */
9782 	if (sec_def->sec[len - 1] == '+') {
9783 		len--;
9784 		/* not even a prefix */
9785 		if (strncmp(sec_name, sec_def->sec, len) != 0)
9786 			return false;
9787 		/* exact match or has '/' separator */
9788 		if (sec_name[len] == '\0' || sec_name[len] == '/')
9789 			return true;
9790 		return false;
9791 	}
9792 
9793 	return strcmp(sec_name, sec_def->sec) == 0;
9794 }
9795 
9796 static const struct bpf_sec_def *find_sec_def(const char *sec_name)
9797 {
9798 	const struct bpf_sec_def *sec_def;
9799 	int i, n;
9800 
9801 	n = custom_sec_def_cnt;
9802 	for (i = 0; i < n; i++) {
9803 		sec_def = &custom_sec_defs[i];
9804 		if (sec_def_matches(sec_def, sec_name))
9805 			return sec_def;
9806 	}
9807 
9808 	n = ARRAY_SIZE(section_defs);
9809 	for (i = 0; i < n; i++) {
9810 		sec_def = &section_defs[i];
9811 		if (sec_def_matches(sec_def, sec_name))
9812 			return sec_def;
9813 	}
9814 
9815 	if (has_custom_fallback_def)
9816 		return &custom_fallback_def;
9817 
9818 	return NULL;
9819 }
9820 
9821 #define MAX_TYPE_NAME_SIZE 32
9822 
9823 static char *libbpf_get_type_names(bool attach_type)
9824 {
9825 	int i, len = ARRAY_SIZE(section_defs) * MAX_TYPE_NAME_SIZE;
9826 	char *buf;
9827 
9828 	buf = malloc(len);
9829 	if (!buf)
9830 		return NULL;
9831 
9832 	buf[0] = '\0';
9833 	/* Forge string buf with all available names */
9834 	for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
9835 		const struct bpf_sec_def *sec_def = &section_defs[i];
9836 
9837 		if (attach_type) {
9838 			if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
9839 				continue;
9840 
9841 			if (!(sec_def->cookie & SEC_ATTACHABLE))
9842 				continue;
9843 		}
9844 
9845 		if (strlen(buf) + strlen(section_defs[i].sec) + 2 > len) {
9846 			free(buf);
9847 			return NULL;
9848 		}
9849 		strcat(buf, " ");
9850 		strcat(buf, section_defs[i].sec);
9851 	}
9852 
9853 	return buf;
9854 }
9855 
9856 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
9857 			     enum bpf_attach_type *expected_attach_type)
9858 {
9859 	const struct bpf_sec_def *sec_def;
9860 	char *type_names;
9861 
9862 	if (!name)
9863 		return libbpf_err(-EINVAL);
9864 
9865 	sec_def = find_sec_def(name);
9866 	if (sec_def) {
9867 		*prog_type = sec_def->prog_type;
9868 		*expected_attach_type = sec_def->expected_attach_type;
9869 		return 0;
9870 	}
9871 
9872 	pr_debug("failed to guess program type from ELF section '%s'\n", name);
9873 	type_names = libbpf_get_type_names(false);
9874 	if (type_names != NULL) {
9875 		pr_debug("supported section(type) names are:%s\n", type_names);
9876 		free(type_names);
9877 	}
9878 
9879 	return libbpf_err(-ESRCH);
9880 }
9881 
9882 const char *libbpf_bpf_attach_type_str(enum bpf_attach_type t)
9883 {
9884 	if (t < 0 || t >= ARRAY_SIZE(attach_type_name))
9885 		return NULL;
9886 
9887 	return attach_type_name[t];
9888 }
9889 
9890 const char *libbpf_bpf_link_type_str(enum bpf_link_type t)
9891 {
9892 	if (t < 0 || t >= ARRAY_SIZE(link_type_name))
9893 		return NULL;
9894 
9895 	return link_type_name[t];
9896 }
9897 
9898 const char *libbpf_bpf_map_type_str(enum bpf_map_type t)
9899 {
9900 	if (t < 0 || t >= ARRAY_SIZE(map_type_name))
9901 		return NULL;
9902 
9903 	return map_type_name[t];
9904 }
9905 
9906 const char *libbpf_bpf_prog_type_str(enum bpf_prog_type t)
9907 {
9908 	if (t < 0 || t >= ARRAY_SIZE(prog_type_name))
9909 		return NULL;
9910 
9911 	return prog_type_name[t];
9912 }
9913 
9914 static struct bpf_map *find_struct_ops_map_by_offset(struct bpf_object *obj,
9915 						     int sec_idx,
9916 						     size_t offset)
9917 {
9918 	struct bpf_map *map;
9919 	size_t i;
9920 
9921 	for (i = 0; i < obj->nr_maps; i++) {
9922 		map = &obj->maps[i];
9923 		if (!bpf_map__is_struct_ops(map))
9924 			continue;
9925 		if (map->sec_idx == sec_idx &&
9926 		    map->sec_offset <= offset &&
9927 		    offset - map->sec_offset < map->def.value_size)
9928 			return map;
9929 	}
9930 
9931 	return NULL;
9932 }
9933 
9934 /* Collect the reloc from ELF, populate the st_ops->progs[], and update
9935  * st_ops->data for shadow type.
9936  */
9937 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
9938 					    Elf64_Shdr *shdr, Elf_Data *data)
9939 {
9940 	const struct btf_type *type;
9941 	const struct btf_member *member;
9942 	struct bpf_struct_ops *st_ops;
9943 	struct bpf_program *prog;
9944 	unsigned int shdr_idx;
9945 	const struct btf *btf;
9946 	struct bpf_map *map;
9947 	unsigned int moff, insn_idx;
9948 	const char *name;
9949 	__u32 member_idx;
9950 	Elf64_Sym *sym;
9951 	Elf64_Rel *rel;
9952 	int i, nrels;
9953 
9954 	btf = obj->btf;
9955 	nrels = shdr->sh_size / shdr->sh_entsize;
9956 	for (i = 0; i < nrels; i++) {
9957 		rel = elf_rel_by_idx(data, i);
9958 		if (!rel) {
9959 			pr_warn("struct_ops reloc: failed to get %d reloc\n", i);
9960 			return -LIBBPF_ERRNO__FORMAT;
9961 		}
9962 
9963 		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
9964 		if (!sym) {
9965 			pr_warn("struct_ops reloc: symbol %zx not found\n",
9966 				(size_t)ELF64_R_SYM(rel->r_info));
9967 			return -LIBBPF_ERRNO__FORMAT;
9968 		}
9969 
9970 		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
9971 		map = find_struct_ops_map_by_offset(obj, shdr->sh_info, rel->r_offset);
9972 		if (!map) {
9973 			pr_warn("struct_ops reloc: cannot find map at rel->r_offset %zu\n",
9974 				(size_t)rel->r_offset);
9975 			return -EINVAL;
9976 		}
9977 
9978 		moff = rel->r_offset - map->sec_offset;
9979 		shdr_idx = sym->st_shndx;
9980 		st_ops = map->st_ops;
9981 		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",
9982 			 map->name,
9983 			 (long long)(rel->r_info >> 32),
9984 			 (long long)sym->st_value,
9985 			 shdr_idx, (size_t)rel->r_offset,
9986 			 map->sec_offset, sym->st_name, name);
9987 
9988 		if (shdr_idx >= SHN_LORESERVE) {
9989 			pr_warn("struct_ops reloc %s: rel->r_offset %zu shdr_idx %u unsupported non-static function\n",
9990 				map->name, (size_t)rel->r_offset, shdr_idx);
9991 			return -LIBBPF_ERRNO__RELOC;
9992 		}
9993 		if (sym->st_value % BPF_INSN_SZ) {
9994 			pr_warn("struct_ops reloc %s: invalid target program offset %llu\n",
9995 				map->name, (unsigned long long)sym->st_value);
9996 			return -LIBBPF_ERRNO__FORMAT;
9997 		}
9998 		insn_idx = sym->st_value / BPF_INSN_SZ;
9999 
10000 		type = btf__type_by_id(btf, st_ops->type_id);
10001 		member = find_member_by_offset(type, moff * 8);
10002 		if (!member) {
10003 			pr_warn("struct_ops reloc %s: cannot find member at moff %u\n",
10004 				map->name, moff);
10005 			return -EINVAL;
10006 		}
10007 		member_idx = member - btf_members(type);
10008 		name = btf__name_by_offset(btf, member->name_off);
10009 
10010 		if (!resolve_func_ptr(btf, member->type, NULL)) {
10011 			pr_warn("struct_ops reloc %s: cannot relocate non func ptr %s\n",
10012 				map->name, name);
10013 			return -EINVAL;
10014 		}
10015 
10016 		prog = find_prog_by_sec_insn(obj, shdr_idx, insn_idx);
10017 		if (!prog) {
10018 			pr_warn("struct_ops reloc %s: cannot find prog at shdr_idx %u to relocate func ptr %s\n",
10019 				map->name, shdr_idx, name);
10020 			return -EINVAL;
10021 		}
10022 
10023 		/* prevent the use of BPF prog with invalid type */
10024 		if (prog->type != BPF_PROG_TYPE_STRUCT_OPS) {
10025 			pr_warn("struct_ops reloc %s: prog %s is not struct_ops BPF program\n",
10026 				map->name, prog->name);
10027 			return -EINVAL;
10028 		}
10029 
10030 		st_ops->progs[member_idx] = prog;
10031 
10032 		/* st_ops->data will be exposed to users, being returned by
10033 		 * bpf_map__initial_value() as a pointer to the shadow
10034 		 * type. All function pointers in the original struct type
10035 		 * should be converted to a pointer to struct bpf_program
10036 		 * in the shadow type.
10037 		 */
10038 		*((struct bpf_program **)(st_ops->data + moff)) = prog;
10039 	}
10040 
10041 	return 0;
10042 }
10043 
10044 #define BTF_TRACE_PREFIX "btf_trace_"
10045 #define BTF_LSM_PREFIX "bpf_lsm_"
10046 #define BTF_ITER_PREFIX "bpf_iter_"
10047 #define BTF_MAX_NAME_SIZE 128
10048 
10049 void btf_get_kernel_prefix_kind(enum bpf_attach_type attach_type,
10050 				const char **prefix, int *kind)
10051 {
10052 	switch (attach_type) {
10053 	case BPF_TRACE_RAW_TP:
10054 		*prefix = BTF_TRACE_PREFIX;
10055 		*kind = BTF_KIND_TYPEDEF;
10056 		break;
10057 	case BPF_LSM_MAC:
10058 	case BPF_LSM_CGROUP:
10059 		*prefix = BTF_LSM_PREFIX;
10060 		*kind = BTF_KIND_FUNC;
10061 		break;
10062 	case BPF_TRACE_ITER:
10063 		*prefix = BTF_ITER_PREFIX;
10064 		*kind = BTF_KIND_FUNC;
10065 		break;
10066 	default:
10067 		*prefix = "";
10068 		*kind = BTF_KIND_FUNC;
10069 	}
10070 }
10071 
10072 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
10073 				   const char *name, __u32 kind)
10074 {
10075 	char btf_type_name[BTF_MAX_NAME_SIZE];
10076 	int ret;
10077 
10078 	ret = snprintf(btf_type_name, sizeof(btf_type_name),
10079 		       "%s%s", prefix, name);
10080 	/* snprintf returns the number of characters written excluding the
10081 	 * terminating null. So, if >= BTF_MAX_NAME_SIZE are written, it
10082 	 * indicates truncation.
10083 	 */
10084 	if (ret < 0 || ret >= sizeof(btf_type_name))
10085 		return -ENAMETOOLONG;
10086 	return btf__find_by_name_kind(btf, btf_type_name, kind);
10087 }
10088 
10089 static inline int find_attach_btf_id(struct btf *btf, const char *name,
10090 				     enum bpf_attach_type attach_type)
10091 {
10092 	const char *prefix;
10093 	int kind;
10094 
10095 	btf_get_kernel_prefix_kind(attach_type, &prefix, &kind);
10096 	return find_btf_by_prefix_kind(btf, prefix, name, kind);
10097 }
10098 
10099 int libbpf_find_vmlinux_btf_id(const char *name,
10100 			       enum bpf_attach_type attach_type)
10101 {
10102 	struct btf *btf;
10103 	int err;
10104 
10105 	btf = btf__load_vmlinux_btf();
10106 	err = libbpf_get_error(btf);
10107 	if (err) {
10108 		pr_warn("vmlinux BTF is not found\n");
10109 		return libbpf_err(err);
10110 	}
10111 
10112 	err = find_attach_btf_id(btf, name, attach_type);
10113 	if (err <= 0)
10114 		pr_warn("%s is not found in vmlinux BTF\n", name);
10115 
10116 	btf__free(btf);
10117 	return libbpf_err(err);
10118 }
10119 
10120 static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd, int token_fd)
10121 {
10122 	struct bpf_prog_info info;
10123 	__u32 info_len = sizeof(info);
10124 	struct btf *btf;
10125 	int err;
10126 
10127 	memset(&info, 0, info_len);
10128 	err = bpf_prog_get_info_by_fd(attach_prog_fd, &info, &info_len);
10129 	if (err) {
10130 		pr_warn("failed bpf_prog_get_info_by_fd for FD %d: %s\n",
10131 			attach_prog_fd, errstr(err));
10132 		return err;
10133 	}
10134 
10135 	err = -EINVAL;
10136 	if (!info.btf_id) {
10137 		pr_warn("The target program doesn't have BTF\n");
10138 		goto out;
10139 	}
10140 	btf = btf_load_from_kernel(info.btf_id, NULL, token_fd);
10141 	err = libbpf_get_error(btf);
10142 	if (err) {
10143 		pr_warn("Failed to get BTF %d of the program: %s\n", info.btf_id, errstr(err));
10144 		goto out;
10145 	}
10146 	err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
10147 	btf__free(btf);
10148 	if (err <= 0) {
10149 		pr_warn("%s is not found in prog's BTF\n", name);
10150 		goto out;
10151 	}
10152 out:
10153 	return err;
10154 }
10155 
10156 static int find_kernel_btf_id(struct bpf_object *obj, const char *attach_name,
10157 			      enum bpf_attach_type attach_type,
10158 			      int *btf_obj_fd, int *btf_type_id)
10159 {
10160 	int ret, i, mod_len = 0;
10161 	const char *fn_name, *mod_name = NULL;
10162 
10163 	fn_name = strchr(attach_name, ':');
10164 	if (fn_name) {
10165 		mod_name = attach_name;
10166 		mod_len = fn_name - mod_name;
10167 		fn_name++;
10168 	}
10169 
10170 	if (!mod_name || strncmp(mod_name, "vmlinux", mod_len) == 0) {
10171 		ret = find_attach_btf_id(obj->btf_vmlinux,
10172 					 mod_name ? fn_name : attach_name,
10173 					 attach_type);
10174 		if (ret > 0) {
10175 			*btf_obj_fd = 0; /* vmlinux BTF */
10176 			*btf_type_id = ret;
10177 			return 0;
10178 		}
10179 		if (ret != -ENOENT)
10180 			return ret;
10181 	}
10182 
10183 	ret = load_module_btfs(obj);
10184 	if (ret)
10185 		return ret;
10186 
10187 	for (i = 0; i < obj->btf_module_cnt; i++) {
10188 		const struct module_btf *mod = &obj->btf_modules[i];
10189 
10190 		if (mod_name && strncmp(mod->name, mod_name, mod_len) != 0)
10191 			continue;
10192 
10193 		ret = find_attach_btf_id(mod->btf,
10194 					 mod_name ? fn_name : attach_name,
10195 					 attach_type);
10196 		if (ret > 0) {
10197 			*btf_obj_fd = mod->fd;
10198 			*btf_type_id = ret;
10199 			return 0;
10200 		}
10201 		if (ret == -ENOENT)
10202 			continue;
10203 
10204 		return ret;
10205 	}
10206 
10207 	return -ESRCH;
10208 }
10209 
10210 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
10211 				     int *btf_obj_fd, int *btf_type_id)
10212 {
10213 	enum bpf_attach_type attach_type = prog->expected_attach_type;
10214 	__u32 attach_prog_fd = prog->attach_prog_fd;
10215 	int err = 0;
10216 
10217 	/* BPF program's BTF ID */
10218 	if (prog->type == BPF_PROG_TYPE_EXT || attach_prog_fd) {
10219 		if (!attach_prog_fd) {
10220 			pr_warn("prog '%s': attach program FD is not set\n", prog->name);
10221 			return -EINVAL;
10222 		}
10223 		err = libbpf_find_prog_btf_id(attach_name, attach_prog_fd, prog->obj->token_fd);
10224 		if (err < 0) {
10225 			pr_warn("prog '%s': failed to find BPF program (FD %d) BTF ID for '%s': %s\n",
10226 				prog->name, attach_prog_fd, attach_name, errstr(err));
10227 			return err;
10228 		}
10229 		*btf_obj_fd = 0;
10230 		*btf_type_id = err;
10231 		return 0;
10232 	}
10233 
10234 	/* kernel/module BTF ID */
10235 	if (prog->obj->gen_loader) {
10236 		bpf_gen__record_attach_target(prog->obj->gen_loader, attach_name, attach_type);
10237 		*btf_obj_fd = 0;
10238 		*btf_type_id = 1;
10239 	} else {
10240 		err = find_kernel_btf_id(prog->obj, attach_name,
10241 					 attach_type, btf_obj_fd,
10242 					 btf_type_id);
10243 	}
10244 	if (err) {
10245 		pr_warn("prog '%s': failed to find kernel BTF type ID of '%s': %s\n",
10246 			prog->name, attach_name, errstr(err));
10247 		return err;
10248 	}
10249 	return 0;
10250 }
10251 
10252 int libbpf_attach_type_by_name(const char *name,
10253 			       enum bpf_attach_type *attach_type)
10254 {
10255 	char *type_names;
10256 	const struct bpf_sec_def *sec_def;
10257 
10258 	if (!name)
10259 		return libbpf_err(-EINVAL);
10260 
10261 	sec_def = find_sec_def(name);
10262 	if (!sec_def) {
10263 		pr_debug("failed to guess attach type based on ELF section name '%s'\n", name);
10264 		type_names = libbpf_get_type_names(true);
10265 		if (type_names != NULL) {
10266 			pr_debug("attachable section(type) names are:%s\n", type_names);
10267 			free(type_names);
10268 		}
10269 
10270 		return libbpf_err(-EINVAL);
10271 	}
10272 
10273 	if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
10274 		return libbpf_err(-EINVAL);
10275 	if (!(sec_def->cookie & SEC_ATTACHABLE))
10276 		return libbpf_err(-EINVAL);
10277 
10278 	*attach_type = sec_def->expected_attach_type;
10279 	return 0;
10280 }
10281 
10282 int bpf_map__fd(const struct bpf_map *map)
10283 {
10284 	if (!map)
10285 		return libbpf_err(-EINVAL);
10286 	if (!map_is_created(map))
10287 		return -1;
10288 	return map->fd;
10289 }
10290 
10291 static bool map_uses_real_name(const struct bpf_map *map)
10292 {
10293 	/* Since libbpf started to support custom .data.* and .rodata.* maps,
10294 	 * their user-visible name differs from kernel-visible name. Users see
10295 	 * such map's corresponding ELF section name as a map name.
10296 	 * This check distinguishes .data/.rodata from .data.* and .rodata.*
10297 	 * maps to know which name has to be returned to the user.
10298 	 */
10299 	if (map->libbpf_type == LIBBPF_MAP_DATA && strcmp(map->real_name, DATA_SEC) != 0)
10300 		return true;
10301 	if (map->libbpf_type == LIBBPF_MAP_RODATA && strcmp(map->real_name, RODATA_SEC) != 0)
10302 		return true;
10303 	return false;
10304 }
10305 
10306 const char *bpf_map__name(const struct bpf_map *map)
10307 {
10308 	if (!map)
10309 		return NULL;
10310 
10311 	if (map_uses_real_name(map))
10312 		return map->real_name;
10313 
10314 	return map->name;
10315 }
10316 
10317 enum bpf_map_type bpf_map__type(const struct bpf_map *map)
10318 {
10319 	return map->def.type;
10320 }
10321 
10322 int bpf_map__set_type(struct bpf_map *map, enum bpf_map_type type)
10323 {
10324 	if (map_is_created(map))
10325 		return libbpf_err(-EBUSY);
10326 	map->def.type = type;
10327 	return 0;
10328 }
10329 
10330 __u32 bpf_map__map_flags(const struct bpf_map *map)
10331 {
10332 	return map->def.map_flags;
10333 }
10334 
10335 int bpf_map__set_map_flags(struct bpf_map *map, __u32 flags)
10336 {
10337 	if (map_is_created(map))
10338 		return libbpf_err(-EBUSY);
10339 	map->def.map_flags = flags;
10340 	return 0;
10341 }
10342 
10343 __u64 bpf_map__map_extra(const struct bpf_map *map)
10344 {
10345 	return map->map_extra;
10346 }
10347 
10348 int bpf_map__set_map_extra(struct bpf_map *map, __u64 map_extra)
10349 {
10350 	if (map_is_created(map))
10351 		return libbpf_err(-EBUSY);
10352 	map->map_extra = map_extra;
10353 	return 0;
10354 }
10355 
10356 __u32 bpf_map__numa_node(const struct bpf_map *map)
10357 {
10358 	return map->numa_node;
10359 }
10360 
10361 int bpf_map__set_numa_node(struct bpf_map *map, __u32 numa_node)
10362 {
10363 	if (map_is_created(map))
10364 		return libbpf_err(-EBUSY);
10365 	map->numa_node = numa_node;
10366 	return 0;
10367 }
10368 
10369 __u32 bpf_map__key_size(const struct bpf_map *map)
10370 {
10371 	return map->def.key_size;
10372 }
10373 
10374 int bpf_map__set_key_size(struct bpf_map *map, __u32 size)
10375 {
10376 	if (map_is_created(map))
10377 		return libbpf_err(-EBUSY);
10378 	map->def.key_size = size;
10379 	return 0;
10380 }
10381 
10382 __u32 bpf_map__value_size(const struct bpf_map *map)
10383 {
10384 	return map->def.value_size;
10385 }
10386 
10387 static int map_btf_datasec_resize(struct bpf_map *map, __u32 size)
10388 {
10389 	struct btf *btf;
10390 	struct btf_type *datasec_type, *var_type;
10391 	struct btf_var_secinfo *var;
10392 	const struct btf_type *array_type;
10393 	const struct btf_array *array;
10394 	int vlen, element_sz, new_array_id;
10395 	__u32 nr_elements;
10396 
10397 	/* check btf existence */
10398 	btf = bpf_object__btf(map->obj);
10399 	if (!btf)
10400 		return -ENOENT;
10401 
10402 	/* verify map is datasec */
10403 	datasec_type = btf_type_by_id(btf, bpf_map__btf_value_type_id(map));
10404 	if (!btf_is_datasec(datasec_type)) {
10405 		pr_warn("map '%s': cannot be resized, map value type is not a datasec\n",
10406 			bpf_map__name(map));
10407 		return -EINVAL;
10408 	}
10409 
10410 	/* verify datasec has at least one var */
10411 	vlen = btf_vlen(datasec_type);
10412 	if (vlen == 0) {
10413 		pr_warn("map '%s': cannot be resized, map value datasec is empty\n",
10414 			bpf_map__name(map));
10415 		return -EINVAL;
10416 	}
10417 
10418 	/* verify last var in the datasec is an array */
10419 	var = &btf_var_secinfos(datasec_type)[vlen - 1];
10420 	var_type = btf_type_by_id(btf, var->type);
10421 	array_type = skip_mods_and_typedefs(btf, var_type->type, NULL);
10422 	if (!btf_is_array(array_type)) {
10423 		pr_warn("map '%s': cannot be resized, last var must be an array\n",
10424 			bpf_map__name(map));
10425 		return -EINVAL;
10426 	}
10427 
10428 	/* verify request size aligns with array */
10429 	array = btf_array(array_type);
10430 	element_sz = btf__resolve_size(btf, array->type);
10431 	if (element_sz <= 0 || (size - var->offset) % element_sz != 0) {
10432 		pr_warn("map '%s': cannot be resized, element size (%d) doesn't align with new total size (%u)\n",
10433 			bpf_map__name(map), element_sz, size);
10434 		return -EINVAL;
10435 	}
10436 
10437 	/* create a new array based on the existing array, but with new length */
10438 	nr_elements = (size - var->offset) / element_sz;
10439 	new_array_id = btf__add_array(btf, array->index_type, array->type, nr_elements);
10440 	if (new_array_id < 0)
10441 		return new_array_id;
10442 
10443 	/* adding a new btf type invalidates existing pointers to btf objects,
10444 	 * so refresh pointers before proceeding
10445 	 */
10446 	datasec_type = btf_type_by_id(btf, map->btf_value_type_id);
10447 	var = &btf_var_secinfos(datasec_type)[vlen - 1];
10448 	var_type = btf_type_by_id(btf, var->type);
10449 
10450 	/* finally update btf info */
10451 	datasec_type->size = size;
10452 	var->size = size - var->offset;
10453 	var_type->type = new_array_id;
10454 
10455 	return 0;
10456 }
10457 
10458 int bpf_map__set_value_size(struct bpf_map *map, __u32 size)
10459 {
10460 	if (map_is_created(map))
10461 		return libbpf_err(-EBUSY);
10462 
10463 	if (map->mmaped) {
10464 		size_t mmap_old_sz, mmap_new_sz;
10465 		int err;
10466 
10467 		if (map->def.type != BPF_MAP_TYPE_ARRAY)
10468 			return libbpf_err(-EOPNOTSUPP);
10469 
10470 		mmap_old_sz = bpf_map_mmap_sz(map);
10471 		mmap_new_sz = array_map_mmap_sz(size, map->def.max_entries);
10472 		err = bpf_map_mmap_resize(map, mmap_old_sz, mmap_new_sz);
10473 		if (err) {
10474 			pr_warn("map '%s': failed to resize memory-mapped region: %s\n",
10475 				bpf_map__name(map), errstr(err));
10476 			return libbpf_err(err);
10477 		}
10478 		err = map_btf_datasec_resize(map, size);
10479 		if (err && err != -ENOENT) {
10480 			pr_warn("map '%s': failed to adjust resized BTF, clearing BTF key/value info: %s\n",
10481 				bpf_map__name(map), errstr(err));
10482 			map->btf_value_type_id = 0;
10483 			map->btf_key_type_id = 0;
10484 		}
10485 	}
10486 
10487 	map->def.value_size = size;
10488 	return 0;
10489 }
10490 
10491 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
10492 {
10493 	return map ? map->btf_key_type_id : 0;
10494 }
10495 
10496 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
10497 {
10498 	return map ? map->btf_value_type_id : 0;
10499 }
10500 
10501 int bpf_map__set_initial_value(struct bpf_map *map,
10502 			       const void *data, size_t size)
10503 {
10504 	size_t actual_sz;
10505 
10506 	if (map_is_created(map))
10507 		return libbpf_err(-EBUSY);
10508 
10509 	if (!map->mmaped || map->libbpf_type == LIBBPF_MAP_KCONFIG)
10510 		return libbpf_err(-EINVAL);
10511 
10512 	if (map->def.type == BPF_MAP_TYPE_ARENA)
10513 		actual_sz = map->obj->arena_data_sz;
10514 	else
10515 		actual_sz = map->def.value_size;
10516 	if (size != actual_sz)
10517 		return libbpf_err(-EINVAL);
10518 
10519 	memcpy(map->mmaped, data, size);
10520 	return 0;
10521 }
10522 
10523 void *bpf_map__initial_value(const struct bpf_map *map, size_t *psize)
10524 {
10525 	if (bpf_map__is_struct_ops(map)) {
10526 		if (psize)
10527 			*psize = map->def.value_size;
10528 		return map->st_ops->data;
10529 	}
10530 
10531 	if (!map->mmaped)
10532 		return NULL;
10533 
10534 	if (map->def.type == BPF_MAP_TYPE_ARENA)
10535 		*psize = map->obj->arena_data_sz;
10536 	else
10537 		*psize = map->def.value_size;
10538 
10539 	return map->mmaped;
10540 }
10541 
10542 bool bpf_map__is_internal(const struct bpf_map *map)
10543 {
10544 	return map->libbpf_type != LIBBPF_MAP_UNSPEC;
10545 }
10546 
10547 __u32 bpf_map__ifindex(const struct bpf_map *map)
10548 {
10549 	return map->map_ifindex;
10550 }
10551 
10552 int bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
10553 {
10554 	if (map_is_created(map))
10555 		return libbpf_err(-EBUSY);
10556 	map->map_ifindex = ifindex;
10557 	return 0;
10558 }
10559 
10560 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
10561 {
10562 	if (!bpf_map_type__is_map_in_map(map->def.type)) {
10563 		pr_warn("error: unsupported map type\n");
10564 		return libbpf_err(-EINVAL);
10565 	}
10566 	if (map->inner_map_fd != -1) {
10567 		pr_warn("error: inner_map_fd already specified\n");
10568 		return libbpf_err(-EINVAL);
10569 	}
10570 	if (map->inner_map) {
10571 		bpf_map__destroy(map->inner_map);
10572 		zfree(&map->inner_map);
10573 	}
10574 	map->inner_map_fd = fd;
10575 	return 0;
10576 }
10577 
10578 int bpf_map__set_exclusive_program(struct bpf_map *map, struct bpf_program *prog)
10579 {
10580 	if (map_is_created(map)) {
10581 		pr_warn("exclusive programs must be set before map creation\n");
10582 		return libbpf_err(-EINVAL);
10583 	}
10584 
10585 	if (map->obj != prog->obj) {
10586 		pr_warn("excl_prog and map must be from the same bpf object\n");
10587 		return libbpf_err(-EINVAL);
10588 	}
10589 
10590 	map->excl_prog = prog;
10591 	return 0;
10592 }
10593 
10594 struct bpf_program *bpf_map__exclusive_program(struct bpf_map *map)
10595 {
10596 	return map->excl_prog;
10597 }
10598 
10599 static struct bpf_map *
10600 __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
10601 {
10602 	ssize_t idx;
10603 	struct bpf_map *s, *e;
10604 
10605 	if (!obj || !obj->maps)
10606 		return errno = EINVAL, NULL;
10607 
10608 	s = obj->maps;
10609 	e = obj->maps + obj->nr_maps;
10610 
10611 	if ((m < s) || (m >= e)) {
10612 		pr_warn("error in %s: map handler doesn't belong to object\n",
10613 			 __func__);
10614 		return errno = EINVAL, NULL;
10615 	}
10616 
10617 	idx = (m - obj->maps) + i;
10618 	if (idx >= obj->nr_maps || idx < 0)
10619 		return NULL;
10620 	return &obj->maps[idx];
10621 }
10622 
10623 struct bpf_map *
10624 bpf_object__next_map(const struct bpf_object *obj, const struct bpf_map *prev)
10625 {
10626 	if (prev == NULL && obj != NULL)
10627 		return obj->maps;
10628 
10629 	return __bpf_map__iter(prev, obj, 1);
10630 }
10631 
10632 struct bpf_map *
10633 bpf_object__prev_map(const struct bpf_object *obj, const struct bpf_map *next)
10634 {
10635 	if (next == NULL && obj != NULL) {
10636 		if (!obj->nr_maps)
10637 			return NULL;
10638 		return obj->maps + obj->nr_maps - 1;
10639 	}
10640 
10641 	return __bpf_map__iter(next, obj, -1);
10642 }
10643 
10644 struct bpf_map *
10645 bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
10646 {
10647 	struct bpf_map *pos;
10648 
10649 	bpf_object__for_each_map(pos, obj) {
10650 		/* if it's a special internal map name (which always starts
10651 		 * with dot) then check if that special name matches the
10652 		 * real map name (ELF section name)
10653 		 */
10654 		if (name[0] == '.') {
10655 			if (pos->real_name && strcmp(pos->real_name, name) == 0)
10656 				return pos;
10657 			continue;
10658 		}
10659 		/* otherwise map name has to be an exact match */
10660 		if (map_uses_real_name(pos)) {
10661 			if (strcmp(pos->real_name, name) == 0)
10662 				return pos;
10663 			continue;
10664 		}
10665 		if (strcmp(pos->name, name) == 0)
10666 			return pos;
10667 	}
10668 	return errno = ENOENT, NULL;
10669 }
10670 
10671 int
10672 bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
10673 {
10674 	return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
10675 }
10676 
10677 static int validate_map_op(const struct bpf_map *map, size_t key_sz,
10678 			   size_t value_sz, bool check_value_sz)
10679 {
10680 	if (!map_is_created(map)) /* map is not yet created */
10681 		return -ENOENT;
10682 
10683 	if (map->def.key_size != key_sz) {
10684 		pr_warn("map '%s': unexpected key size %zu provided, expected %u\n",
10685 			map->name, key_sz, map->def.key_size);
10686 		return -EINVAL;
10687 	}
10688 
10689 	if (map->fd < 0) {
10690 		pr_warn("map '%s': can't use BPF map without FD (was it created?)\n", map->name);
10691 		return -EINVAL;
10692 	}
10693 
10694 	if (!check_value_sz)
10695 		return 0;
10696 
10697 	switch (map->def.type) {
10698 	case BPF_MAP_TYPE_PERCPU_ARRAY:
10699 	case BPF_MAP_TYPE_PERCPU_HASH:
10700 	case BPF_MAP_TYPE_LRU_PERCPU_HASH:
10701 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: {
10702 		int num_cpu = libbpf_num_possible_cpus();
10703 		size_t elem_sz = roundup(map->def.value_size, 8);
10704 
10705 		if (value_sz != num_cpu * elem_sz) {
10706 			pr_warn("map '%s': unexpected value size %zu provided for per-CPU map, expected %d * %zu = %zd\n",
10707 				map->name, value_sz, num_cpu, elem_sz, num_cpu * elem_sz);
10708 			return -EINVAL;
10709 		}
10710 		break;
10711 	}
10712 	default:
10713 		if (map->def.value_size != value_sz) {
10714 			pr_warn("map '%s': unexpected value size %zu provided, expected %u\n",
10715 				map->name, value_sz, map->def.value_size);
10716 			return -EINVAL;
10717 		}
10718 		break;
10719 	}
10720 	return 0;
10721 }
10722 
10723 int bpf_map__lookup_elem(const struct bpf_map *map,
10724 			 const void *key, size_t key_sz,
10725 			 void *value, size_t value_sz, __u64 flags)
10726 {
10727 	int err;
10728 
10729 	err = validate_map_op(map, key_sz, value_sz, true);
10730 	if (err)
10731 		return libbpf_err(err);
10732 
10733 	return bpf_map_lookup_elem_flags(map->fd, key, value, flags);
10734 }
10735 
10736 int bpf_map__update_elem(const struct bpf_map *map,
10737 			 const void *key, size_t key_sz,
10738 			 const void *value, size_t value_sz, __u64 flags)
10739 {
10740 	int err;
10741 
10742 	err = validate_map_op(map, key_sz, value_sz, true);
10743 	if (err)
10744 		return libbpf_err(err);
10745 
10746 	return bpf_map_update_elem(map->fd, key, value, flags);
10747 }
10748 
10749 int bpf_map__delete_elem(const struct bpf_map *map,
10750 			 const void *key, size_t key_sz, __u64 flags)
10751 {
10752 	int err;
10753 
10754 	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */);
10755 	if (err)
10756 		return libbpf_err(err);
10757 
10758 	return bpf_map_delete_elem_flags(map->fd, key, flags);
10759 }
10760 
10761 int bpf_map__lookup_and_delete_elem(const struct bpf_map *map,
10762 				    const void *key, size_t key_sz,
10763 				    void *value, size_t value_sz, __u64 flags)
10764 {
10765 	int err;
10766 
10767 	err = validate_map_op(map, key_sz, value_sz, true);
10768 	if (err)
10769 		return libbpf_err(err);
10770 
10771 	return bpf_map_lookup_and_delete_elem_flags(map->fd, key, value, flags);
10772 }
10773 
10774 int bpf_map__get_next_key(const struct bpf_map *map,
10775 			  const void *cur_key, void *next_key, size_t key_sz)
10776 {
10777 	int err;
10778 
10779 	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */);
10780 	if (err)
10781 		return libbpf_err(err);
10782 
10783 	return bpf_map_get_next_key(map->fd, cur_key, next_key);
10784 }
10785 
10786 long libbpf_get_error(const void *ptr)
10787 {
10788 	if (!IS_ERR_OR_NULL(ptr))
10789 		return 0;
10790 
10791 	if (IS_ERR(ptr))
10792 		errno = -PTR_ERR(ptr);
10793 
10794 	/* If ptr == NULL, then errno should be already set by the failing
10795 	 * API, because libbpf never returns NULL on success and it now always
10796 	 * sets errno on error. So no extra errno handling for ptr == NULL
10797 	 * case.
10798 	 */
10799 	return -errno;
10800 }
10801 
10802 /* Replace link's underlying BPF program with the new one */
10803 int bpf_link__update_program(struct bpf_link *link, struct bpf_program *prog)
10804 {
10805 	int ret;
10806 	int prog_fd = bpf_program__fd(prog);
10807 
10808 	if (prog_fd < 0) {
10809 		pr_warn("prog '%s': can't use BPF program without FD (was it loaded?)\n",
10810 			prog->name);
10811 		return libbpf_err(-EINVAL);
10812 	}
10813 
10814 	ret = bpf_link_update(bpf_link__fd(link), prog_fd, NULL);
10815 	return libbpf_err_errno(ret);
10816 }
10817 
10818 /* Release "ownership" of underlying BPF resource (typically, BPF program
10819  * attached to some BPF hook, e.g., tracepoint, kprobe, etc). Disconnected
10820  * link, when destructed through bpf_link__destroy() call won't attempt to
10821  * detach/unregisted that BPF resource. This is useful in situations where,
10822  * say, attached BPF program has to outlive userspace program that attached it
10823  * in the system. Depending on type of BPF program, though, there might be
10824  * additional steps (like pinning BPF program in BPF FS) necessary to ensure
10825  * exit of userspace program doesn't trigger automatic detachment and clean up
10826  * inside the kernel.
10827  */
10828 void bpf_link__disconnect(struct bpf_link *link)
10829 {
10830 	link->disconnected = true;
10831 }
10832 
10833 int bpf_link__destroy(struct bpf_link *link)
10834 {
10835 	int err = 0;
10836 
10837 	if (IS_ERR_OR_NULL(link))
10838 		return 0;
10839 
10840 	if (!link->disconnected && link->detach)
10841 		err = link->detach(link);
10842 	if (link->pin_path)
10843 		free(link->pin_path);
10844 	if (link->dealloc)
10845 		link->dealloc(link);
10846 	else
10847 		free(link);
10848 
10849 	return libbpf_err(err);
10850 }
10851 
10852 int bpf_link__fd(const struct bpf_link *link)
10853 {
10854 	return link->fd;
10855 }
10856 
10857 const char *bpf_link__pin_path(const struct bpf_link *link)
10858 {
10859 	return link->pin_path;
10860 }
10861 
10862 static int bpf_link__detach_fd(struct bpf_link *link)
10863 {
10864 	return libbpf_err_errno(close(link->fd));
10865 }
10866 
10867 struct bpf_link *bpf_link__open(const char *path)
10868 {
10869 	struct bpf_link *link;
10870 	int fd;
10871 
10872 	fd = bpf_obj_get(path);
10873 	if (fd < 0) {
10874 		fd = -errno;
10875 		pr_warn("failed to open link at %s: %d\n", path, fd);
10876 		return libbpf_err_ptr(fd);
10877 	}
10878 
10879 	link = calloc(1, sizeof(*link));
10880 	if (!link) {
10881 		close(fd);
10882 		return libbpf_err_ptr(-ENOMEM);
10883 	}
10884 	link->detach = &bpf_link__detach_fd;
10885 	link->fd = fd;
10886 
10887 	link->pin_path = strdup(path);
10888 	if (!link->pin_path) {
10889 		bpf_link__destroy(link);
10890 		return libbpf_err_ptr(-ENOMEM);
10891 	}
10892 
10893 	return link;
10894 }
10895 
10896 int bpf_link__detach(struct bpf_link *link)
10897 {
10898 	return bpf_link_detach(link->fd) ? -errno : 0;
10899 }
10900 
10901 int bpf_link__pin(struct bpf_link *link, const char *path)
10902 {
10903 	int err;
10904 
10905 	if (link->pin_path)
10906 		return libbpf_err(-EBUSY);
10907 	err = make_parent_dir(path);
10908 	if (err)
10909 		return libbpf_err(err);
10910 	err = check_path(path);
10911 	if (err)
10912 		return libbpf_err(err);
10913 
10914 	link->pin_path = strdup(path);
10915 	if (!link->pin_path)
10916 		return libbpf_err(-ENOMEM);
10917 
10918 	if (bpf_obj_pin(link->fd, link->pin_path)) {
10919 		err = -errno;
10920 		zfree(&link->pin_path);
10921 		return libbpf_err(err);
10922 	}
10923 
10924 	pr_debug("link fd=%d: pinned at %s\n", link->fd, link->pin_path);
10925 	return 0;
10926 }
10927 
10928 int bpf_link__unpin(struct bpf_link *link)
10929 {
10930 	int err;
10931 
10932 	if (!link->pin_path)
10933 		return libbpf_err(-EINVAL);
10934 
10935 	err = unlink(link->pin_path);
10936 	if (err != 0)
10937 		return -errno;
10938 
10939 	pr_debug("link fd=%d: unpinned from %s\n", link->fd, link->pin_path);
10940 	zfree(&link->pin_path);
10941 	return 0;
10942 }
10943 
10944 struct bpf_link_perf {
10945 	struct bpf_link link;
10946 	int perf_event_fd;
10947 	/* legacy kprobe support: keep track of probe identifier and type */
10948 	char *legacy_probe_name;
10949 	bool legacy_is_kprobe;
10950 	bool legacy_is_retprobe;
10951 };
10952 
10953 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe);
10954 static int remove_uprobe_event_legacy(const char *probe_name, bool retprobe);
10955 
10956 static int bpf_link_perf_detach(struct bpf_link *link)
10957 {
10958 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10959 	int err = 0;
10960 
10961 	if (ioctl(perf_link->perf_event_fd, PERF_EVENT_IOC_DISABLE, 0) < 0)
10962 		err = -errno;
10963 
10964 	if (perf_link->perf_event_fd != link->fd)
10965 		close(perf_link->perf_event_fd);
10966 	close(link->fd);
10967 
10968 	/* legacy uprobe/kprobe needs to be removed after perf event fd closure */
10969 	if (perf_link->legacy_probe_name) {
10970 		if (perf_link->legacy_is_kprobe) {
10971 			err = remove_kprobe_event_legacy(perf_link->legacy_probe_name,
10972 							 perf_link->legacy_is_retprobe);
10973 		} else {
10974 			err = remove_uprobe_event_legacy(perf_link->legacy_probe_name,
10975 							 perf_link->legacy_is_retprobe);
10976 		}
10977 	}
10978 
10979 	return err;
10980 }
10981 
10982 static void bpf_link_perf_dealloc(struct bpf_link *link)
10983 {
10984 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10985 
10986 	free(perf_link->legacy_probe_name);
10987 	free(perf_link);
10988 }
10989 
10990 struct bpf_link *bpf_program__attach_perf_event_opts(const struct bpf_program *prog, int pfd,
10991 						     const struct bpf_perf_event_opts *opts)
10992 {
10993 	struct bpf_link_perf *link;
10994 	int prog_fd, link_fd = -1, err;
10995 	bool force_ioctl_attach;
10996 
10997 	if (!OPTS_VALID(opts, bpf_perf_event_opts))
10998 		return libbpf_err_ptr(-EINVAL);
10999 
11000 	if (pfd < 0) {
11001 		pr_warn("prog '%s': invalid perf event FD %d\n",
11002 			prog->name, pfd);
11003 		return libbpf_err_ptr(-EINVAL);
11004 	}
11005 	prog_fd = bpf_program__fd(prog);
11006 	if (prog_fd < 0) {
11007 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
11008 			prog->name);
11009 		return libbpf_err_ptr(-EINVAL);
11010 	}
11011 
11012 	link = calloc(1, sizeof(*link));
11013 	if (!link)
11014 		return libbpf_err_ptr(-ENOMEM);
11015 	link->link.detach = &bpf_link_perf_detach;
11016 	link->link.dealloc = &bpf_link_perf_dealloc;
11017 	link->perf_event_fd = pfd;
11018 
11019 	force_ioctl_attach = OPTS_GET(opts, force_ioctl_attach, false);
11020 	if (kernel_supports(prog->obj, FEAT_PERF_LINK) && !force_ioctl_attach) {
11021 		DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_opts,
11022 			.perf_event.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0));
11023 
11024 		link_fd = bpf_link_create(prog_fd, pfd, BPF_PERF_EVENT, &link_opts);
11025 		if (link_fd < 0) {
11026 			err = -errno;
11027 			pr_warn("prog '%s': failed to create BPF link for perf_event FD %d: %s\n",
11028 				prog->name, pfd, errstr(err));
11029 			goto err_out;
11030 		}
11031 		link->link.fd = link_fd;
11032 	} else {
11033 		if (OPTS_GET(opts, bpf_cookie, 0)) {
11034 			pr_warn("prog '%s': user context value is not supported\n", prog->name);
11035 			err = -EOPNOTSUPP;
11036 			goto err_out;
11037 		}
11038 
11039 		if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
11040 			err = -errno;
11041 			pr_warn("prog '%s': failed to attach to perf_event FD %d: %s\n",
11042 				prog->name, pfd, errstr(err));
11043 			if (err == -EPROTO)
11044 				pr_warn("prog '%s': try add PERF_SAMPLE_CALLCHAIN to or remove exclude_callchain_[kernel|user] from pfd %d\n",
11045 					prog->name, pfd);
11046 			goto err_out;
11047 		}
11048 		link->link.fd = pfd;
11049 	}
11050 
11051 	if (!OPTS_GET(opts, dont_enable, false)) {
11052 		if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
11053 			err = -errno;
11054 			pr_warn("prog '%s': failed to enable perf_event FD %d: %s\n",
11055 				prog->name, pfd, errstr(err));
11056 			goto err_out;
11057 		}
11058 	}
11059 
11060 	return &link->link;
11061 err_out:
11062 	if (link_fd >= 0)
11063 		close(link_fd);
11064 	free(link);
11065 	return libbpf_err_ptr(err);
11066 }
11067 
11068 struct bpf_link *bpf_program__attach_perf_event(const struct bpf_program *prog, int pfd)
11069 {
11070 	return bpf_program__attach_perf_event_opts(prog, pfd, NULL);
11071 }
11072 
11073 /*
11074  * this function is expected to parse integer in the range of [0, 2^31-1] from
11075  * given file using scanf format string fmt. If actual parsed value is
11076  * negative, the result might be indistinguishable from error
11077  */
11078 static int parse_uint_from_file(const char *file, const char *fmt)
11079 {
11080 	int err, ret;
11081 	FILE *f;
11082 
11083 	f = fopen(file, "re");
11084 	if (!f) {
11085 		err = -errno;
11086 		pr_debug("failed to open '%s': %s\n", file, errstr(err));
11087 		return err;
11088 	}
11089 	err = fscanf(f, fmt, &ret);
11090 	if (err != 1) {
11091 		err = err == EOF ? -EIO : -errno;
11092 		pr_debug("failed to parse '%s': %s\n", file, errstr(err));
11093 		fclose(f);
11094 		return err;
11095 	}
11096 	fclose(f);
11097 	return ret;
11098 }
11099 
11100 static int determine_kprobe_perf_type(void)
11101 {
11102 	const char *file = "/sys/bus/event_source/devices/kprobe/type";
11103 
11104 	return parse_uint_from_file(file, "%d\n");
11105 }
11106 
11107 static int determine_uprobe_perf_type(void)
11108 {
11109 	const char *file = "/sys/bus/event_source/devices/uprobe/type";
11110 
11111 	return parse_uint_from_file(file, "%d\n");
11112 }
11113 
11114 static int determine_kprobe_retprobe_bit(void)
11115 {
11116 	const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
11117 
11118 	return parse_uint_from_file(file, "config:%d\n");
11119 }
11120 
11121 static int determine_uprobe_retprobe_bit(void)
11122 {
11123 	const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
11124 
11125 	return parse_uint_from_file(file, "config:%d\n");
11126 }
11127 
11128 #define PERF_UPROBE_REF_CTR_OFFSET_BITS 32
11129 #define PERF_UPROBE_REF_CTR_OFFSET_SHIFT 32
11130 
11131 static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
11132 				 uint64_t offset, int pid, size_t ref_ctr_off)
11133 {
11134 	const size_t attr_sz = sizeof(struct perf_event_attr);
11135 	struct perf_event_attr attr;
11136 	int type, pfd;
11137 
11138 	if ((__u64)ref_ctr_off >= (1ULL << PERF_UPROBE_REF_CTR_OFFSET_BITS))
11139 		return -EINVAL;
11140 
11141 	memset(&attr, 0, attr_sz);
11142 
11143 	type = uprobe ? determine_uprobe_perf_type()
11144 		      : determine_kprobe_perf_type();
11145 	if (type < 0) {
11146 		pr_warn("failed to determine %s perf type: %s\n",
11147 			uprobe ? "uprobe" : "kprobe",
11148 			errstr(type));
11149 		return type;
11150 	}
11151 	if (retprobe) {
11152 		int bit = uprobe ? determine_uprobe_retprobe_bit()
11153 				 : determine_kprobe_retprobe_bit();
11154 
11155 		if (bit < 0) {
11156 			pr_warn("failed to determine %s retprobe bit: %s\n",
11157 				uprobe ? "uprobe" : "kprobe",
11158 				errstr(bit));
11159 			return bit;
11160 		}
11161 		attr.config |= 1 << bit;
11162 	}
11163 	attr.size = attr_sz;
11164 	attr.type = type;
11165 	attr.config |= (__u64)ref_ctr_off << PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
11166 	attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
11167 	attr.config2 = offset;		 /* kprobe_addr or probe_offset */
11168 
11169 	/* pid filter is meaningful only for uprobes */
11170 	pfd = syscall(__NR_perf_event_open, &attr,
11171 		      pid < 0 ? -1 : pid /* pid */,
11172 		      pid == -1 ? 0 : -1 /* cpu */,
11173 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
11174 	return pfd >= 0 ? pfd : -errno;
11175 }
11176 
11177 static int append_to_file(const char *file, const char *fmt, ...)
11178 {
11179 	int fd, n, err = 0;
11180 	va_list ap;
11181 	char buf[1024];
11182 
11183 	va_start(ap, fmt);
11184 	n = vsnprintf(buf, sizeof(buf), fmt, ap);
11185 	va_end(ap);
11186 
11187 	if (n < 0 || n >= sizeof(buf))
11188 		return -EINVAL;
11189 
11190 	fd = open(file, O_WRONLY | O_APPEND | O_CLOEXEC, 0);
11191 	if (fd < 0)
11192 		return -errno;
11193 
11194 	if (write(fd, buf, n) < 0)
11195 		err = -errno;
11196 
11197 	close(fd);
11198 	return err;
11199 }
11200 
11201 #define DEBUGFS "/sys/kernel/debug/tracing"
11202 #define TRACEFS "/sys/kernel/tracing"
11203 
11204 static bool use_debugfs(void)
11205 {
11206 	static int has_debugfs = -1;
11207 
11208 	if (has_debugfs < 0)
11209 		has_debugfs = faccessat(AT_FDCWD, DEBUGFS, F_OK, AT_EACCESS) == 0;
11210 
11211 	return has_debugfs == 1;
11212 }
11213 
11214 static const char *tracefs_path(void)
11215 {
11216 	return use_debugfs() ? DEBUGFS : TRACEFS;
11217 }
11218 
11219 static const char *tracefs_kprobe_events(void)
11220 {
11221 	return use_debugfs() ? DEBUGFS"/kprobe_events" : TRACEFS"/kprobe_events";
11222 }
11223 
11224 static const char *tracefs_uprobe_events(void)
11225 {
11226 	return use_debugfs() ? DEBUGFS"/uprobe_events" : TRACEFS"/uprobe_events";
11227 }
11228 
11229 static const char *tracefs_available_filter_functions(void)
11230 {
11231 	return use_debugfs() ? DEBUGFS"/available_filter_functions"
11232 			     : TRACEFS"/available_filter_functions";
11233 }
11234 
11235 static const char *tracefs_available_filter_functions_addrs(void)
11236 {
11237 	return use_debugfs() ? DEBUGFS"/available_filter_functions_addrs"
11238 			     : TRACEFS"/available_filter_functions_addrs";
11239 }
11240 
11241 static void gen_probe_legacy_event_name(char *buf, size_t buf_sz,
11242 					const char *name, size_t offset)
11243 {
11244 	static int index = 0;
11245 	int i;
11246 
11247 	snprintf(buf, buf_sz, "libbpf_%u_%d_%s_0x%zx", getpid(),
11248 		 __sync_fetch_and_add(&index, 1), name, offset);
11249 
11250 	/* sanitize name in the probe name */
11251 	for (i = 0; buf[i]; i++) {
11252 		if (!isalnum(buf[i]))
11253 			buf[i] = '_';
11254 	}
11255 }
11256 
11257 static int add_kprobe_event_legacy(const char *probe_name, bool retprobe,
11258 				   const char *kfunc_name, size_t offset)
11259 {
11260 	return append_to_file(tracefs_kprobe_events(), "%c:%s/%s %s+0x%zx",
11261 			      retprobe ? 'r' : 'p',
11262 			      retprobe ? "kretprobes" : "kprobes",
11263 			      probe_name, kfunc_name, offset);
11264 }
11265 
11266 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe)
11267 {
11268 	return append_to_file(tracefs_kprobe_events(), "-:%s/%s",
11269 			      retprobe ? "kretprobes" : "kprobes", probe_name);
11270 }
11271 
11272 static int determine_kprobe_perf_type_legacy(const char *probe_name, bool retprobe)
11273 {
11274 	char file[256];
11275 
11276 	snprintf(file, sizeof(file), "%s/events/%s/%s/id",
11277 		 tracefs_path(), retprobe ? "kretprobes" : "kprobes", probe_name);
11278 
11279 	return parse_uint_from_file(file, "%d\n");
11280 }
11281 
11282 static int perf_event_kprobe_open_legacy(const char *probe_name, bool retprobe,
11283 					 const char *kfunc_name, size_t offset, int pid)
11284 {
11285 	const size_t attr_sz = sizeof(struct perf_event_attr);
11286 	struct perf_event_attr attr;
11287 	int type, pfd, err;
11288 
11289 	err = add_kprobe_event_legacy(probe_name, retprobe, kfunc_name, offset);
11290 	if (err < 0) {
11291 		pr_warn("failed to add legacy kprobe event for '%s+0x%zx': %s\n",
11292 			kfunc_name, offset,
11293 			errstr(err));
11294 		return err;
11295 	}
11296 	type = determine_kprobe_perf_type_legacy(probe_name, retprobe);
11297 	if (type < 0) {
11298 		err = type;
11299 		pr_warn("failed to determine legacy kprobe event id for '%s+0x%zx': %s\n",
11300 			kfunc_name, offset,
11301 			errstr(err));
11302 		goto err_clean_legacy;
11303 	}
11304 
11305 	memset(&attr, 0, attr_sz);
11306 	attr.size = attr_sz;
11307 	attr.config = type;
11308 	attr.type = PERF_TYPE_TRACEPOINT;
11309 
11310 	pfd = syscall(__NR_perf_event_open, &attr,
11311 		      pid < 0 ? -1 : pid, /* pid */
11312 		      pid == -1 ? 0 : -1, /* cpu */
11313 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
11314 	if (pfd < 0) {
11315 		err = -errno;
11316 		pr_warn("legacy kprobe perf_event_open() failed: %s\n",
11317 			errstr(err));
11318 		goto err_clean_legacy;
11319 	}
11320 	return pfd;
11321 
11322 err_clean_legacy:
11323 	/* Clear the newly added legacy kprobe_event */
11324 	remove_kprobe_event_legacy(probe_name, retprobe);
11325 	return err;
11326 }
11327 
11328 static const char *arch_specific_syscall_pfx(void)
11329 {
11330 #if defined(__x86_64__)
11331 	return "x64";
11332 #elif defined(__i386__)
11333 	return "ia32";
11334 #elif defined(__s390x__)
11335 	return "s390x";
11336 #elif defined(__s390__)
11337 	return "s390";
11338 #elif defined(__arm__)
11339 	return "arm";
11340 #elif defined(__aarch64__)
11341 	return "arm64";
11342 #elif defined(__mips__)
11343 	return "mips";
11344 #elif defined(__riscv)
11345 	return "riscv";
11346 #elif defined(__powerpc__)
11347 	return "powerpc";
11348 #elif defined(__powerpc64__)
11349 	return "powerpc64";
11350 #else
11351 	return NULL;
11352 #endif
11353 }
11354 
11355 int probe_kern_syscall_wrapper(int token_fd)
11356 {
11357 	char syscall_name[64];
11358 	const char *ksys_pfx;
11359 
11360 	ksys_pfx = arch_specific_syscall_pfx();
11361 	if (!ksys_pfx)
11362 		return 0;
11363 
11364 	snprintf(syscall_name, sizeof(syscall_name), "__%s_sys_bpf", ksys_pfx);
11365 
11366 	if (determine_kprobe_perf_type() >= 0) {
11367 		int pfd;
11368 
11369 		pfd = perf_event_open_probe(false, false, syscall_name, 0, getpid(), 0);
11370 		if (pfd >= 0)
11371 			close(pfd);
11372 
11373 		return pfd >= 0 ? 1 : 0;
11374 	} else { /* legacy mode */
11375 		char probe_name[MAX_EVENT_NAME_LEN];
11376 
11377 		gen_probe_legacy_event_name(probe_name, sizeof(probe_name), syscall_name, 0);
11378 		if (add_kprobe_event_legacy(probe_name, false, syscall_name, 0) < 0)
11379 			return 0;
11380 
11381 		(void)remove_kprobe_event_legacy(probe_name, false);
11382 		return 1;
11383 	}
11384 }
11385 
11386 struct bpf_link *
11387 bpf_program__attach_kprobe_opts(const struct bpf_program *prog,
11388 				const char *func_name,
11389 				const struct bpf_kprobe_opts *opts)
11390 {
11391 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
11392 	enum probe_attach_mode attach_mode;
11393 	char *legacy_probe = NULL;
11394 	struct bpf_link *link;
11395 	size_t offset;
11396 	bool retprobe, legacy;
11397 	int pfd, err;
11398 
11399 	if (!OPTS_VALID(opts, bpf_kprobe_opts))
11400 		return libbpf_err_ptr(-EINVAL);
11401 
11402 	attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
11403 	retprobe = OPTS_GET(opts, retprobe, false);
11404 	offset = OPTS_GET(opts, offset, 0);
11405 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11406 
11407 	legacy = determine_kprobe_perf_type() < 0;
11408 	switch (attach_mode) {
11409 	case PROBE_ATTACH_MODE_LEGACY:
11410 		legacy = true;
11411 		pe_opts.force_ioctl_attach = true;
11412 		break;
11413 	case PROBE_ATTACH_MODE_PERF:
11414 		if (legacy)
11415 			return libbpf_err_ptr(-ENOTSUP);
11416 		pe_opts.force_ioctl_attach = true;
11417 		break;
11418 	case PROBE_ATTACH_MODE_LINK:
11419 		if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
11420 			return libbpf_err_ptr(-ENOTSUP);
11421 		break;
11422 	case PROBE_ATTACH_MODE_DEFAULT:
11423 		break;
11424 	default:
11425 		return libbpf_err_ptr(-EINVAL);
11426 	}
11427 
11428 	if (!legacy) {
11429 		pfd = perf_event_open_probe(false /* uprobe */, retprobe,
11430 					    func_name, offset,
11431 					    -1 /* pid */, 0 /* ref_ctr_off */);
11432 	} else {
11433 		char probe_name[MAX_EVENT_NAME_LEN];
11434 
11435 		gen_probe_legacy_event_name(probe_name, sizeof(probe_name),
11436 					    func_name, offset);
11437 
11438 		legacy_probe = strdup(probe_name);
11439 		if (!legacy_probe)
11440 			return libbpf_err_ptr(-ENOMEM);
11441 
11442 		pfd = perf_event_kprobe_open_legacy(legacy_probe, retprobe, func_name,
11443 						    offset, -1 /* pid */);
11444 	}
11445 	if (pfd < 0) {
11446 		err = -errno;
11447 		pr_warn("prog '%s': failed to create %s '%s+0x%zx' perf event: %s\n",
11448 			prog->name, retprobe ? "kretprobe" : "kprobe",
11449 			func_name, offset,
11450 			errstr(err));
11451 		goto err_out;
11452 	}
11453 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
11454 	err = libbpf_get_error(link);
11455 	if (err) {
11456 		close(pfd);
11457 		pr_warn("prog '%s': failed to attach to %s '%s+0x%zx': %s\n",
11458 			prog->name, retprobe ? "kretprobe" : "kprobe",
11459 			func_name, offset,
11460 			errstr(err));
11461 		goto err_clean_legacy;
11462 	}
11463 	if (legacy) {
11464 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
11465 
11466 		perf_link->legacy_probe_name = legacy_probe;
11467 		perf_link->legacy_is_kprobe = true;
11468 		perf_link->legacy_is_retprobe = retprobe;
11469 	}
11470 
11471 	return link;
11472 
11473 err_clean_legacy:
11474 	if (legacy)
11475 		remove_kprobe_event_legacy(legacy_probe, retprobe);
11476 err_out:
11477 	free(legacy_probe);
11478 	return libbpf_err_ptr(err);
11479 }
11480 
11481 struct bpf_link *bpf_program__attach_kprobe(const struct bpf_program *prog,
11482 					    bool retprobe,
11483 					    const char *func_name)
11484 {
11485 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts,
11486 		.retprobe = retprobe,
11487 	);
11488 
11489 	return bpf_program__attach_kprobe_opts(prog, func_name, &opts);
11490 }
11491 
11492 struct bpf_link *bpf_program__attach_ksyscall(const struct bpf_program *prog,
11493 					      const char *syscall_name,
11494 					      const struct bpf_ksyscall_opts *opts)
11495 {
11496 	LIBBPF_OPTS(bpf_kprobe_opts, kprobe_opts);
11497 	char func_name[128];
11498 
11499 	if (!OPTS_VALID(opts, bpf_ksyscall_opts))
11500 		return libbpf_err_ptr(-EINVAL);
11501 
11502 	if (kernel_supports(prog->obj, FEAT_SYSCALL_WRAPPER)) {
11503 		/* arch_specific_syscall_pfx() should never return NULL here
11504 		 * because it is guarded by kernel_supports(). However, since
11505 		 * compiler does not know that we have an explicit conditional
11506 		 * as well.
11507 		 */
11508 		snprintf(func_name, sizeof(func_name), "__%s_sys_%s",
11509 			 arch_specific_syscall_pfx() ? : "", syscall_name);
11510 	} else {
11511 		snprintf(func_name, sizeof(func_name), "__se_sys_%s", syscall_name);
11512 	}
11513 
11514 	kprobe_opts.retprobe = OPTS_GET(opts, retprobe, false);
11515 	kprobe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11516 
11517 	return bpf_program__attach_kprobe_opts(prog, func_name, &kprobe_opts);
11518 }
11519 
11520 /* Adapted from perf/util/string.c */
11521 bool glob_match(const char *str, const char *pat)
11522 {
11523 	while (*str && *pat && *pat != '*') {
11524 		if (*pat == '?') {      /* Matches any single character */
11525 			str++;
11526 			pat++;
11527 			continue;
11528 		}
11529 		if (*str != *pat)
11530 			return false;
11531 		str++;
11532 		pat++;
11533 	}
11534 	/* Check wild card */
11535 	if (*pat == '*') {
11536 		while (*pat == '*')
11537 			pat++;
11538 		if (!*pat) /* Tail wild card matches all */
11539 			return true;
11540 		while (*str)
11541 			if (glob_match(str++, pat))
11542 				return true;
11543 	}
11544 	return !*str && !*pat;
11545 }
11546 
11547 struct kprobe_multi_resolve {
11548 	const char *pattern;
11549 	unsigned long *addrs;
11550 	size_t cap;
11551 	size_t cnt;
11552 };
11553 
11554 struct avail_kallsyms_data {
11555 	char **syms;
11556 	size_t cnt;
11557 	struct kprobe_multi_resolve *res;
11558 };
11559 
11560 static int avail_func_cmp(const void *a, const void *b)
11561 {
11562 	return strcmp(*(const char **)a, *(const char **)b);
11563 }
11564 
11565 static int avail_kallsyms_cb(unsigned long long sym_addr, char sym_type,
11566 			     const char *sym_name, void *ctx)
11567 {
11568 	struct avail_kallsyms_data *data = ctx;
11569 	struct kprobe_multi_resolve *res = data->res;
11570 	int err;
11571 
11572 	if (!glob_match(sym_name, res->pattern))
11573 		return 0;
11574 
11575 	if (!bsearch(&sym_name, data->syms, data->cnt, sizeof(*data->syms), avail_func_cmp)) {
11576 		/* Some versions of kernel strip out .llvm.<hash> suffix from
11577 		 * function names reported in available_filter_functions, but
11578 		 * don't do so for kallsyms. While this is clearly a kernel
11579 		 * bug (fixed by [0]) we try to accommodate that in libbpf to
11580 		 * make multi-kprobe usability a bit better: if no match is
11581 		 * found, we will strip .llvm. suffix and try one more time.
11582 		 *
11583 		 *   [0] fb6a421fb615 ("kallsyms: Match symbols exactly with CONFIG_LTO_CLANG")
11584 		 */
11585 		char sym_trim[256], *psym_trim = sym_trim, *sym_sfx;
11586 
11587 		if (!(sym_sfx = strstr(sym_name, ".llvm.")))
11588 			return 0;
11589 
11590 		/* psym_trim vs sym_trim dance is done to avoid pointer vs array
11591 		 * coercion differences and get proper `const char **` pointer
11592 		 * which avail_func_cmp() expects
11593 		 */
11594 		snprintf(sym_trim, sizeof(sym_trim), "%.*s", (int)(sym_sfx - sym_name), sym_name);
11595 		if (!bsearch(&psym_trim, data->syms, data->cnt, sizeof(*data->syms), avail_func_cmp))
11596 			return 0;
11597 	}
11598 
11599 	err = libbpf_ensure_mem((void **)&res->addrs, &res->cap, sizeof(*res->addrs), res->cnt + 1);
11600 	if (err)
11601 		return err;
11602 
11603 	res->addrs[res->cnt++] = (unsigned long)sym_addr;
11604 	return 0;
11605 }
11606 
11607 static int libbpf_available_kallsyms_parse(struct kprobe_multi_resolve *res)
11608 {
11609 	const char *available_functions_file = tracefs_available_filter_functions();
11610 	struct avail_kallsyms_data data;
11611 	char sym_name[500];
11612 	FILE *f;
11613 	int err = 0, ret, i;
11614 	char **syms = NULL;
11615 	size_t cap = 0, cnt = 0;
11616 
11617 	f = fopen(available_functions_file, "re");
11618 	if (!f) {
11619 		err = -errno;
11620 		pr_warn("failed to open %s: %s\n", available_functions_file, errstr(err));
11621 		return err;
11622 	}
11623 
11624 	while (true) {
11625 		char *name;
11626 
11627 		ret = fscanf(f, "%499s%*[^\n]\n", sym_name);
11628 		if (ret == EOF && feof(f))
11629 			break;
11630 
11631 		if (ret != 1) {
11632 			pr_warn("failed to parse available_filter_functions entry: %d\n", ret);
11633 			err = -EINVAL;
11634 			goto cleanup;
11635 		}
11636 
11637 		if (!glob_match(sym_name, res->pattern))
11638 			continue;
11639 
11640 		err = libbpf_ensure_mem((void **)&syms, &cap, sizeof(*syms), cnt + 1);
11641 		if (err)
11642 			goto cleanup;
11643 
11644 		name = strdup(sym_name);
11645 		if (!name) {
11646 			err = -errno;
11647 			goto cleanup;
11648 		}
11649 
11650 		syms[cnt++] = name;
11651 	}
11652 
11653 	/* no entries found, bail out */
11654 	if (cnt == 0) {
11655 		err = -ENOENT;
11656 		goto cleanup;
11657 	}
11658 
11659 	/* sort available functions */
11660 	qsort(syms, cnt, sizeof(*syms), avail_func_cmp);
11661 
11662 	data.syms = syms;
11663 	data.res = res;
11664 	data.cnt = cnt;
11665 	libbpf_kallsyms_parse(avail_kallsyms_cb, &data);
11666 
11667 	if (res->cnt == 0)
11668 		err = -ENOENT;
11669 
11670 cleanup:
11671 	for (i = 0; i < cnt; i++)
11672 		free((char *)syms[i]);
11673 	free(syms);
11674 
11675 	fclose(f);
11676 	return err;
11677 }
11678 
11679 static bool has_available_filter_functions_addrs(void)
11680 {
11681 	return access(tracefs_available_filter_functions_addrs(), R_OK) != -1;
11682 }
11683 
11684 static int libbpf_available_kprobes_parse(struct kprobe_multi_resolve *res)
11685 {
11686 	const char *available_path = tracefs_available_filter_functions_addrs();
11687 	char sym_name[500];
11688 	FILE *f;
11689 	int ret, err = 0;
11690 	unsigned long long sym_addr;
11691 
11692 	f = fopen(available_path, "re");
11693 	if (!f) {
11694 		err = -errno;
11695 		pr_warn("failed to open %s: %s\n", available_path, errstr(err));
11696 		return err;
11697 	}
11698 
11699 	while (true) {
11700 		ret = fscanf(f, "%llx %499s%*[^\n]\n", &sym_addr, sym_name);
11701 		if (ret == EOF && feof(f))
11702 			break;
11703 
11704 		if (ret != 2) {
11705 			pr_warn("failed to parse available_filter_functions_addrs entry: %d\n",
11706 				ret);
11707 			err = -EINVAL;
11708 			goto cleanup;
11709 		}
11710 
11711 		if (!glob_match(sym_name, res->pattern))
11712 			continue;
11713 
11714 		err = libbpf_ensure_mem((void **)&res->addrs, &res->cap,
11715 					sizeof(*res->addrs), res->cnt + 1);
11716 		if (err)
11717 			goto cleanup;
11718 
11719 		res->addrs[res->cnt++] = (unsigned long)sym_addr;
11720 	}
11721 
11722 	if (res->cnt == 0)
11723 		err = -ENOENT;
11724 
11725 cleanup:
11726 	fclose(f);
11727 	return err;
11728 }
11729 
11730 struct bpf_link *
11731 bpf_program__attach_kprobe_multi_opts(const struct bpf_program *prog,
11732 				      const char *pattern,
11733 				      const struct bpf_kprobe_multi_opts *opts)
11734 {
11735 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
11736 	struct kprobe_multi_resolve res = {
11737 		.pattern = pattern,
11738 	};
11739 	enum bpf_attach_type attach_type;
11740 	struct bpf_link *link = NULL;
11741 	const unsigned long *addrs;
11742 	int err, link_fd, prog_fd;
11743 	bool retprobe, session, unique_match;
11744 	const __u64 *cookies;
11745 	const char **syms;
11746 	size_t cnt;
11747 
11748 	if (!OPTS_VALID(opts, bpf_kprobe_multi_opts))
11749 		return libbpf_err_ptr(-EINVAL);
11750 
11751 	prog_fd = bpf_program__fd(prog);
11752 	if (prog_fd < 0) {
11753 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
11754 			prog->name);
11755 		return libbpf_err_ptr(-EINVAL);
11756 	}
11757 
11758 	syms    = OPTS_GET(opts, syms, false);
11759 	addrs   = OPTS_GET(opts, addrs, false);
11760 	cnt     = OPTS_GET(opts, cnt, false);
11761 	cookies = OPTS_GET(opts, cookies, false);
11762 	unique_match = OPTS_GET(opts, unique_match, false);
11763 
11764 	if (!pattern && !addrs && !syms)
11765 		return libbpf_err_ptr(-EINVAL);
11766 	if (pattern && (addrs || syms || cookies || cnt))
11767 		return libbpf_err_ptr(-EINVAL);
11768 	if (!pattern && !cnt)
11769 		return libbpf_err_ptr(-EINVAL);
11770 	if (!pattern && unique_match)
11771 		return libbpf_err_ptr(-EINVAL);
11772 	if (addrs && syms)
11773 		return libbpf_err_ptr(-EINVAL);
11774 
11775 	if (pattern) {
11776 		if (has_available_filter_functions_addrs())
11777 			err = libbpf_available_kprobes_parse(&res);
11778 		else
11779 			err = libbpf_available_kallsyms_parse(&res);
11780 		if (err)
11781 			goto error;
11782 
11783 		if (unique_match && res.cnt != 1) {
11784 			pr_warn("prog '%s': failed to find a unique match for '%s' (%zu matches)\n",
11785 				prog->name, pattern, res.cnt);
11786 			err = -EINVAL;
11787 			goto error;
11788 		}
11789 
11790 		addrs = res.addrs;
11791 		cnt = res.cnt;
11792 	}
11793 
11794 	retprobe = OPTS_GET(opts, retprobe, false);
11795 	session  = OPTS_GET(opts, session, false);
11796 
11797 	if (retprobe && session)
11798 		return libbpf_err_ptr(-EINVAL);
11799 
11800 	attach_type = session ? BPF_TRACE_KPROBE_SESSION : BPF_TRACE_KPROBE_MULTI;
11801 
11802 	lopts.kprobe_multi.syms = syms;
11803 	lopts.kprobe_multi.addrs = addrs;
11804 	lopts.kprobe_multi.cookies = cookies;
11805 	lopts.kprobe_multi.cnt = cnt;
11806 	lopts.kprobe_multi.flags = retprobe ? BPF_F_KPROBE_MULTI_RETURN : 0;
11807 
11808 	link = calloc(1, sizeof(*link));
11809 	if (!link) {
11810 		err = -ENOMEM;
11811 		goto error;
11812 	}
11813 	link->detach = &bpf_link__detach_fd;
11814 
11815 	link_fd = bpf_link_create(prog_fd, 0, attach_type, &lopts);
11816 	if (link_fd < 0) {
11817 		err = -errno;
11818 		pr_warn("prog '%s': failed to attach: %s\n",
11819 			prog->name, errstr(err));
11820 		goto error;
11821 	}
11822 	link->fd = link_fd;
11823 	free(res.addrs);
11824 	return link;
11825 
11826 error:
11827 	free(link);
11828 	free(res.addrs);
11829 	return libbpf_err_ptr(err);
11830 }
11831 
11832 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11833 {
11834 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts);
11835 	unsigned long offset = 0;
11836 	const char *func_name;
11837 	char *func;
11838 	int n;
11839 
11840 	*link = NULL;
11841 
11842 	/* no auto-attach for SEC("kprobe") and SEC("kretprobe") */
11843 	if (strcmp(prog->sec_name, "kprobe") == 0 || strcmp(prog->sec_name, "kretprobe") == 0)
11844 		return 0;
11845 
11846 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe/");
11847 	if (opts.retprobe)
11848 		func_name = prog->sec_name + sizeof("kretprobe/") - 1;
11849 	else
11850 		func_name = prog->sec_name + sizeof("kprobe/") - 1;
11851 
11852 	n = sscanf(func_name, "%m[a-zA-Z0-9_.]+%li", &func, &offset);
11853 	if (n < 1) {
11854 		pr_warn("kprobe name is invalid: %s\n", func_name);
11855 		return -EINVAL;
11856 	}
11857 	if (opts.retprobe && offset != 0) {
11858 		free(func);
11859 		pr_warn("kretprobes do not support offset specification\n");
11860 		return -EINVAL;
11861 	}
11862 
11863 	opts.offset = offset;
11864 	*link = bpf_program__attach_kprobe_opts(prog, func, &opts);
11865 	free(func);
11866 	return libbpf_get_error(*link);
11867 }
11868 
11869 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11870 {
11871 	LIBBPF_OPTS(bpf_ksyscall_opts, opts);
11872 	const char *syscall_name;
11873 
11874 	*link = NULL;
11875 
11876 	/* no auto-attach for SEC("ksyscall") and SEC("kretsyscall") */
11877 	if (strcmp(prog->sec_name, "ksyscall") == 0 || strcmp(prog->sec_name, "kretsyscall") == 0)
11878 		return 0;
11879 
11880 	opts.retprobe = str_has_pfx(prog->sec_name, "kretsyscall/");
11881 	if (opts.retprobe)
11882 		syscall_name = prog->sec_name + sizeof("kretsyscall/") - 1;
11883 	else
11884 		syscall_name = prog->sec_name + sizeof("ksyscall/") - 1;
11885 
11886 	*link = bpf_program__attach_ksyscall(prog, syscall_name, &opts);
11887 	return *link ? 0 : -errno;
11888 }
11889 
11890 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11891 {
11892 	LIBBPF_OPTS(bpf_kprobe_multi_opts, opts);
11893 	const char *spec;
11894 	char *pattern;
11895 	int n;
11896 
11897 	*link = NULL;
11898 
11899 	/* no auto-attach for SEC("kprobe.multi") and SEC("kretprobe.multi") */
11900 	if (strcmp(prog->sec_name, "kprobe.multi") == 0 ||
11901 	    strcmp(prog->sec_name, "kretprobe.multi") == 0)
11902 		return 0;
11903 
11904 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe.multi/");
11905 	if (opts.retprobe)
11906 		spec = prog->sec_name + sizeof("kretprobe.multi/") - 1;
11907 	else
11908 		spec = prog->sec_name + sizeof("kprobe.multi/") - 1;
11909 
11910 	n = sscanf(spec, "%m[a-zA-Z0-9_.*?]", &pattern);
11911 	if (n < 1) {
11912 		pr_warn("kprobe multi pattern is invalid: %s\n", spec);
11913 		return -EINVAL;
11914 	}
11915 
11916 	*link = bpf_program__attach_kprobe_multi_opts(prog, pattern, &opts);
11917 	free(pattern);
11918 	return libbpf_get_error(*link);
11919 }
11920 
11921 static int attach_kprobe_session(const struct bpf_program *prog, long cookie,
11922 				 struct bpf_link **link)
11923 {
11924 	LIBBPF_OPTS(bpf_kprobe_multi_opts, opts, .session = true);
11925 	const char *spec;
11926 	char *pattern;
11927 	int n;
11928 
11929 	*link = NULL;
11930 
11931 	/* no auto-attach for SEC("kprobe.session") */
11932 	if (strcmp(prog->sec_name, "kprobe.session") == 0)
11933 		return 0;
11934 
11935 	spec = prog->sec_name + sizeof("kprobe.session/") - 1;
11936 	n = sscanf(spec, "%m[a-zA-Z0-9_.*?]", &pattern);
11937 	if (n < 1) {
11938 		pr_warn("kprobe session pattern is invalid: %s\n", spec);
11939 		return -EINVAL;
11940 	}
11941 
11942 	*link = bpf_program__attach_kprobe_multi_opts(prog, pattern, &opts);
11943 	free(pattern);
11944 	return *link ? 0 : -errno;
11945 }
11946 
11947 static int attach_uprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11948 {
11949 	char *probe_type = NULL, *binary_path = NULL, *func_name = NULL;
11950 	LIBBPF_OPTS(bpf_uprobe_multi_opts, opts);
11951 	int n, ret = -EINVAL;
11952 
11953 	*link = NULL;
11954 
11955 	n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[^\n]",
11956 		   &probe_type, &binary_path, &func_name);
11957 	switch (n) {
11958 	case 1:
11959 		/* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
11960 		ret = 0;
11961 		break;
11962 	case 3:
11963 		opts.session = str_has_pfx(probe_type, "uprobe.session");
11964 		opts.retprobe = str_has_pfx(probe_type, "uretprobe.multi");
11965 
11966 		*link = bpf_program__attach_uprobe_multi(prog, -1, binary_path, func_name, &opts);
11967 		ret = libbpf_get_error(*link);
11968 		break;
11969 	default:
11970 		pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
11971 			prog->sec_name);
11972 		break;
11973 	}
11974 	free(probe_type);
11975 	free(binary_path);
11976 	free(func_name);
11977 	return ret;
11978 }
11979 
11980 static inline int add_uprobe_event_legacy(const char *probe_name, bool retprobe,
11981 					  const char *binary_path, size_t offset)
11982 {
11983 	return append_to_file(tracefs_uprobe_events(), "%c:%s/%s %s:0x%zx",
11984 			      retprobe ? 'r' : 'p',
11985 			      retprobe ? "uretprobes" : "uprobes",
11986 			      probe_name, binary_path, offset);
11987 }
11988 
11989 static inline int remove_uprobe_event_legacy(const char *probe_name, bool retprobe)
11990 {
11991 	return append_to_file(tracefs_uprobe_events(), "-:%s/%s",
11992 			      retprobe ? "uretprobes" : "uprobes", probe_name);
11993 }
11994 
11995 static int determine_uprobe_perf_type_legacy(const char *probe_name, bool retprobe)
11996 {
11997 	char file[512];
11998 
11999 	snprintf(file, sizeof(file), "%s/events/%s/%s/id",
12000 		 tracefs_path(), retprobe ? "uretprobes" : "uprobes", probe_name);
12001 
12002 	return parse_uint_from_file(file, "%d\n");
12003 }
12004 
12005 static int perf_event_uprobe_open_legacy(const char *probe_name, bool retprobe,
12006 					 const char *binary_path, size_t offset, int pid)
12007 {
12008 	const size_t attr_sz = sizeof(struct perf_event_attr);
12009 	struct perf_event_attr attr;
12010 	int type, pfd, err;
12011 
12012 	err = add_uprobe_event_legacy(probe_name, retprobe, binary_path, offset);
12013 	if (err < 0) {
12014 		pr_warn("failed to add legacy uprobe event for %s:0x%zx: %s\n",
12015 			binary_path, (size_t)offset, errstr(err));
12016 		return err;
12017 	}
12018 	type = determine_uprobe_perf_type_legacy(probe_name, retprobe);
12019 	if (type < 0) {
12020 		err = type;
12021 		pr_warn("failed to determine legacy uprobe event id for %s:0x%zx: %s\n",
12022 			binary_path, offset, errstr(err));
12023 		goto err_clean_legacy;
12024 	}
12025 
12026 	memset(&attr, 0, attr_sz);
12027 	attr.size = attr_sz;
12028 	attr.config = type;
12029 	attr.type = PERF_TYPE_TRACEPOINT;
12030 
12031 	pfd = syscall(__NR_perf_event_open, &attr,
12032 		      pid < 0 ? -1 : pid, /* pid */
12033 		      pid == -1 ? 0 : -1, /* cpu */
12034 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
12035 	if (pfd < 0) {
12036 		err = -errno;
12037 		pr_warn("legacy uprobe perf_event_open() failed: %s\n", errstr(err));
12038 		goto err_clean_legacy;
12039 	}
12040 	return pfd;
12041 
12042 err_clean_legacy:
12043 	/* Clear the newly added legacy uprobe_event */
12044 	remove_uprobe_event_legacy(probe_name, retprobe);
12045 	return err;
12046 }
12047 
12048 /* Find offset of function name in archive specified by path. Currently
12049  * supported are .zip files that do not compress their contents, as used on
12050  * Android in the form of APKs, for example. "file_name" is the name of the ELF
12051  * file inside the archive. "func_name" matches symbol name or name@@LIB for
12052  * library functions.
12053  *
12054  * An overview of the APK format specifically provided here:
12055  * https://en.wikipedia.org/w/index.php?title=Apk_(file_format)&oldid=1139099120#Package_contents
12056  */
12057 static long elf_find_func_offset_from_archive(const char *archive_path, const char *file_name,
12058 					      const char *func_name)
12059 {
12060 	struct zip_archive *archive;
12061 	struct zip_entry entry;
12062 	long ret;
12063 	Elf *elf;
12064 
12065 	archive = zip_archive_open(archive_path);
12066 	if (IS_ERR(archive)) {
12067 		ret = PTR_ERR(archive);
12068 		pr_warn("zip: failed to open %s: %ld\n", archive_path, ret);
12069 		return ret;
12070 	}
12071 
12072 	ret = zip_archive_find_entry(archive, file_name, &entry);
12073 	if (ret) {
12074 		pr_warn("zip: could not find archive member %s in %s: %ld\n", file_name,
12075 			archive_path, ret);
12076 		goto out;
12077 	}
12078 	pr_debug("zip: found entry for %s in %s at 0x%lx\n", file_name, archive_path,
12079 		 (unsigned long)entry.data_offset);
12080 
12081 	if (entry.compression) {
12082 		pr_warn("zip: entry %s of %s is compressed and cannot be handled\n", file_name,
12083 			archive_path);
12084 		ret = -LIBBPF_ERRNO__FORMAT;
12085 		goto out;
12086 	}
12087 
12088 	elf = elf_memory((void *)entry.data, entry.data_length);
12089 	if (!elf) {
12090 		pr_warn("elf: could not read elf file %s from %s: %s\n", file_name, archive_path,
12091 			elf_errmsg(-1));
12092 		ret = -LIBBPF_ERRNO__LIBELF;
12093 		goto out;
12094 	}
12095 
12096 	ret = elf_find_func_offset(elf, file_name, func_name);
12097 	if (ret > 0) {
12098 		pr_debug("elf: symbol address match for %s of %s in %s: 0x%x + 0x%lx = 0x%lx\n",
12099 			 func_name, file_name, archive_path, entry.data_offset, ret,
12100 			 ret + entry.data_offset);
12101 		ret += entry.data_offset;
12102 	}
12103 	elf_end(elf);
12104 
12105 out:
12106 	zip_archive_close(archive);
12107 	return ret;
12108 }
12109 
12110 static const char *arch_specific_lib_paths(void)
12111 {
12112 	/*
12113 	 * Based on https://packages.debian.org/sid/libc6.
12114 	 *
12115 	 * Assume that the traced program is built for the same architecture
12116 	 * as libbpf, which should cover the vast majority of cases.
12117 	 */
12118 #if defined(__x86_64__)
12119 	return "/lib/x86_64-linux-gnu";
12120 #elif defined(__i386__)
12121 	return "/lib/i386-linux-gnu";
12122 #elif defined(__s390x__)
12123 	return "/lib/s390x-linux-gnu";
12124 #elif defined(__s390__)
12125 	return "/lib/s390-linux-gnu";
12126 #elif defined(__arm__) && defined(__SOFTFP__)
12127 	return "/lib/arm-linux-gnueabi";
12128 #elif defined(__arm__) && !defined(__SOFTFP__)
12129 	return "/lib/arm-linux-gnueabihf";
12130 #elif defined(__aarch64__)
12131 	return "/lib/aarch64-linux-gnu";
12132 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 64
12133 	return "/lib/mips64el-linux-gnuabi64";
12134 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 32
12135 	return "/lib/mipsel-linux-gnu";
12136 #elif defined(__powerpc64__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
12137 	return "/lib/powerpc64le-linux-gnu";
12138 #elif defined(__sparc__) && defined(__arch64__)
12139 	return "/lib/sparc64-linux-gnu";
12140 #elif defined(__riscv) && __riscv_xlen == 64
12141 	return "/lib/riscv64-linux-gnu";
12142 #else
12143 	return NULL;
12144 #endif
12145 }
12146 
12147 /* Get full path to program/shared library. */
12148 static int resolve_full_path(const char *file, char *result, size_t result_sz)
12149 {
12150 	const char *search_paths[3] = {};
12151 	int i, perm;
12152 
12153 	if (str_has_sfx(file, ".so") || strstr(file, ".so.")) {
12154 		search_paths[0] = getenv("LD_LIBRARY_PATH");
12155 		search_paths[1] = "/usr/lib64:/usr/lib";
12156 		search_paths[2] = arch_specific_lib_paths();
12157 		perm = R_OK;
12158 	} else {
12159 		search_paths[0] = getenv("PATH");
12160 		search_paths[1] = "/usr/bin:/usr/sbin";
12161 		perm = R_OK | X_OK;
12162 	}
12163 
12164 	for (i = 0; i < ARRAY_SIZE(search_paths); i++) {
12165 		const char *s;
12166 
12167 		if (!search_paths[i])
12168 			continue;
12169 		for (s = search_paths[i]; s != NULL; s = strchr(s, ':')) {
12170 			char *next_path;
12171 			int seg_len;
12172 
12173 			if (s[0] == ':')
12174 				s++;
12175 			next_path = strchr(s, ':');
12176 			seg_len = next_path ? next_path - s : strlen(s);
12177 			if (!seg_len)
12178 				continue;
12179 			snprintf(result, result_sz, "%.*s/%s", seg_len, s, file);
12180 			/* ensure it has required permissions */
12181 			if (faccessat(AT_FDCWD, result, perm, AT_EACCESS) < 0)
12182 				continue;
12183 			pr_debug("resolved '%s' to '%s'\n", file, result);
12184 			return 0;
12185 		}
12186 	}
12187 	return -ENOENT;
12188 }
12189 
12190 struct bpf_link *
12191 bpf_program__attach_uprobe_multi(const struct bpf_program *prog,
12192 				 pid_t pid,
12193 				 const char *path,
12194 				 const char *func_pattern,
12195 				 const struct bpf_uprobe_multi_opts *opts)
12196 {
12197 	const unsigned long *ref_ctr_offsets = NULL, *offsets = NULL;
12198 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
12199 	unsigned long *resolved_offsets = NULL;
12200 	enum bpf_attach_type attach_type;
12201 	int err = 0, link_fd, prog_fd;
12202 	struct bpf_link *link = NULL;
12203 	char full_path[PATH_MAX];
12204 	bool retprobe, session;
12205 	const __u64 *cookies;
12206 	const char **syms;
12207 	size_t cnt;
12208 
12209 	if (!OPTS_VALID(opts, bpf_uprobe_multi_opts))
12210 		return libbpf_err_ptr(-EINVAL);
12211 
12212 	prog_fd = bpf_program__fd(prog);
12213 	if (prog_fd < 0) {
12214 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
12215 			prog->name);
12216 		return libbpf_err_ptr(-EINVAL);
12217 	}
12218 
12219 	syms = OPTS_GET(opts, syms, NULL);
12220 	offsets = OPTS_GET(opts, offsets, NULL);
12221 	ref_ctr_offsets = OPTS_GET(opts, ref_ctr_offsets, NULL);
12222 	cookies = OPTS_GET(opts, cookies, NULL);
12223 	cnt = OPTS_GET(opts, cnt, 0);
12224 	retprobe = OPTS_GET(opts, retprobe, false);
12225 	session  = OPTS_GET(opts, session, false);
12226 
12227 	/*
12228 	 * User can specify 2 mutually exclusive set of inputs:
12229 	 *
12230 	 * 1) use only path/func_pattern/pid arguments
12231 	 *
12232 	 * 2) use path/pid with allowed combinations of:
12233 	 *    syms/offsets/ref_ctr_offsets/cookies/cnt
12234 	 *
12235 	 *    - syms and offsets are mutually exclusive
12236 	 *    - ref_ctr_offsets and cookies are optional
12237 	 *
12238 	 * Any other usage results in error.
12239 	 */
12240 
12241 	if (!path)
12242 		return libbpf_err_ptr(-EINVAL);
12243 	if (!func_pattern && cnt == 0)
12244 		return libbpf_err_ptr(-EINVAL);
12245 
12246 	if (func_pattern) {
12247 		if (syms || offsets || ref_ctr_offsets || cookies || cnt)
12248 			return libbpf_err_ptr(-EINVAL);
12249 	} else {
12250 		if (!!syms == !!offsets)
12251 			return libbpf_err_ptr(-EINVAL);
12252 	}
12253 
12254 	if (retprobe && session)
12255 		return libbpf_err_ptr(-EINVAL);
12256 
12257 	if (func_pattern) {
12258 		if (!strchr(path, '/')) {
12259 			err = resolve_full_path(path, full_path, sizeof(full_path));
12260 			if (err) {
12261 				pr_warn("prog '%s': failed to resolve full path for '%s': %s\n",
12262 					prog->name, path, errstr(err));
12263 				return libbpf_err_ptr(err);
12264 			}
12265 			path = full_path;
12266 		}
12267 
12268 		err = elf_resolve_pattern_offsets(path, func_pattern,
12269 						  &resolved_offsets, &cnt);
12270 		if (err < 0)
12271 			return libbpf_err_ptr(err);
12272 		offsets = resolved_offsets;
12273 	} else if (syms) {
12274 		err = elf_resolve_syms_offsets(path, cnt, syms, &resolved_offsets, STT_FUNC);
12275 		if (err < 0)
12276 			return libbpf_err_ptr(err);
12277 		offsets = resolved_offsets;
12278 	}
12279 
12280 	attach_type = session ? BPF_TRACE_UPROBE_SESSION : BPF_TRACE_UPROBE_MULTI;
12281 
12282 	lopts.uprobe_multi.path = path;
12283 	lopts.uprobe_multi.offsets = offsets;
12284 	lopts.uprobe_multi.ref_ctr_offsets = ref_ctr_offsets;
12285 	lopts.uprobe_multi.cookies = cookies;
12286 	lopts.uprobe_multi.cnt = cnt;
12287 	lopts.uprobe_multi.flags = retprobe ? BPF_F_UPROBE_MULTI_RETURN : 0;
12288 
12289 	if (pid == 0)
12290 		pid = getpid();
12291 	if (pid > 0)
12292 		lopts.uprobe_multi.pid = pid;
12293 
12294 	link = calloc(1, sizeof(*link));
12295 	if (!link) {
12296 		err = -ENOMEM;
12297 		goto error;
12298 	}
12299 	link->detach = &bpf_link__detach_fd;
12300 
12301 	link_fd = bpf_link_create(prog_fd, 0, attach_type, &lopts);
12302 	if (link_fd < 0) {
12303 		err = -errno;
12304 		pr_warn("prog '%s': failed to attach multi-uprobe: %s\n",
12305 			prog->name, errstr(err));
12306 		goto error;
12307 	}
12308 	link->fd = link_fd;
12309 	free(resolved_offsets);
12310 	return link;
12311 
12312 error:
12313 	free(resolved_offsets);
12314 	free(link);
12315 	return libbpf_err_ptr(err);
12316 }
12317 
12318 LIBBPF_API struct bpf_link *
12319 bpf_program__attach_uprobe_opts(const struct bpf_program *prog, pid_t pid,
12320 				const char *binary_path, size_t func_offset,
12321 				const struct bpf_uprobe_opts *opts)
12322 {
12323 	const char *archive_path = NULL, *archive_sep = NULL;
12324 	char *legacy_probe = NULL;
12325 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
12326 	enum probe_attach_mode attach_mode;
12327 	char full_path[PATH_MAX];
12328 	struct bpf_link *link;
12329 	size_t ref_ctr_off;
12330 	int pfd, err;
12331 	bool retprobe, legacy;
12332 	const char *func_name;
12333 
12334 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
12335 		return libbpf_err_ptr(-EINVAL);
12336 
12337 	attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
12338 	retprobe = OPTS_GET(opts, retprobe, false);
12339 	ref_ctr_off = OPTS_GET(opts, ref_ctr_offset, 0);
12340 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
12341 
12342 	if (!binary_path)
12343 		return libbpf_err_ptr(-EINVAL);
12344 
12345 	/* Check if "binary_path" refers to an archive. */
12346 	archive_sep = strstr(binary_path, "!/");
12347 	if (archive_sep) {
12348 		full_path[0] = '\0';
12349 		libbpf_strlcpy(full_path, binary_path,
12350 			       min(sizeof(full_path), (size_t)(archive_sep - binary_path + 1)));
12351 		archive_path = full_path;
12352 		binary_path = archive_sep + 2;
12353 	} else if (!strchr(binary_path, '/')) {
12354 		err = resolve_full_path(binary_path, full_path, sizeof(full_path));
12355 		if (err) {
12356 			pr_warn("prog '%s': failed to resolve full path for '%s': %s\n",
12357 				prog->name, binary_path, errstr(err));
12358 			return libbpf_err_ptr(err);
12359 		}
12360 		binary_path = full_path;
12361 	}
12362 	func_name = OPTS_GET(opts, func_name, NULL);
12363 	if (func_name) {
12364 		long sym_off;
12365 
12366 		if (archive_path) {
12367 			sym_off = elf_find_func_offset_from_archive(archive_path, binary_path,
12368 								    func_name);
12369 			binary_path = archive_path;
12370 		} else {
12371 			sym_off = elf_find_func_offset_from_file(binary_path, func_name);
12372 		}
12373 		if (sym_off < 0)
12374 			return libbpf_err_ptr(sym_off);
12375 		func_offset += sym_off;
12376 	}
12377 
12378 	legacy = determine_uprobe_perf_type() < 0;
12379 	switch (attach_mode) {
12380 	case PROBE_ATTACH_MODE_LEGACY:
12381 		legacy = true;
12382 		pe_opts.force_ioctl_attach = true;
12383 		break;
12384 	case PROBE_ATTACH_MODE_PERF:
12385 		if (legacy)
12386 			return libbpf_err_ptr(-ENOTSUP);
12387 		pe_opts.force_ioctl_attach = true;
12388 		break;
12389 	case PROBE_ATTACH_MODE_LINK:
12390 		if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
12391 			return libbpf_err_ptr(-ENOTSUP);
12392 		break;
12393 	case PROBE_ATTACH_MODE_DEFAULT:
12394 		break;
12395 	default:
12396 		return libbpf_err_ptr(-EINVAL);
12397 	}
12398 
12399 	if (!legacy) {
12400 		pfd = perf_event_open_probe(true /* uprobe */, retprobe, binary_path,
12401 					    func_offset, pid, ref_ctr_off);
12402 	} else {
12403 		char probe_name[MAX_EVENT_NAME_LEN];
12404 
12405 		if (ref_ctr_off)
12406 			return libbpf_err_ptr(-EINVAL);
12407 
12408 		gen_probe_legacy_event_name(probe_name, sizeof(probe_name),
12409 					    strrchr(binary_path, '/') ? : binary_path,
12410 					    func_offset);
12411 
12412 		legacy_probe = strdup(probe_name);
12413 		if (!legacy_probe)
12414 			return libbpf_err_ptr(-ENOMEM);
12415 
12416 		pfd = perf_event_uprobe_open_legacy(legacy_probe, retprobe,
12417 						    binary_path, func_offset, pid);
12418 	}
12419 	if (pfd < 0) {
12420 		err = -errno;
12421 		pr_warn("prog '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
12422 			prog->name, retprobe ? "uretprobe" : "uprobe",
12423 			binary_path, func_offset,
12424 			errstr(err));
12425 		goto err_out;
12426 	}
12427 
12428 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
12429 	err = libbpf_get_error(link);
12430 	if (err) {
12431 		close(pfd);
12432 		pr_warn("prog '%s': failed to attach to %s '%s:0x%zx': %s\n",
12433 			prog->name, retprobe ? "uretprobe" : "uprobe",
12434 			binary_path, func_offset,
12435 			errstr(err));
12436 		goto err_clean_legacy;
12437 	}
12438 	if (legacy) {
12439 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
12440 
12441 		perf_link->legacy_probe_name = legacy_probe;
12442 		perf_link->legacy_is_kprobe = false;
12443 		perf_link->legacy_is_retprobe = retprobe;
12444 	}
12445 	return link;
12446 
12447 err_clean_legacy:
12448 	if (legacy)
12449 		remove_uprobe_event_legacy(legacy_probe, retprobe);
12450 err_out:
12451 	free(legacy_probe);
12452 	return libbpf_err_ptr(err);
12453 }
12454 
12455 /* Format of u[ret]probe section definition supporting auto-attach:
12456  * u[ret]probe/binary:function[+offset]
12457  *
12458  * binary can be an absolute/relative path or a filename; the latter is resolved to a
12459  * full binary path via bpf_program__attach_uprobe_opts.
12460  *
12461  * Specifying uprobe+ ensures we carry out strict matching; either "uprobe" must be
12462  * specified (and auto-attach is not possible) or the above format is specified for
12463  * auto-attach.
12464  */
12465 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12466 {
12467 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts);
12468 	char *probe_type = NULL, *binary_path = NULL, *func_name = NULL, *func_off;
12469 	int n, c, ret = -EINVAL;
12470 	long offset = 0;
12471 
12472 	*link = NULL;
12473 
12474 	n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[^\n]",
12475 		   &probe_type, &binary_path, &func_name);
12476 	switch (n) {
12477 	case 1:
12478 		/* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
12479 		ret = 0;
12480 		break;
12481 	case 2:
12482 		pr_warn("prog '%s': section '%s' missing ':function[+offset]' specification\n",
12483 			prog->name, prog->sec_name);
12484 		break;
12485 	case 3:
12486 		/* check if user specifies `+offset`, if yes, this should be
12487 		 * the last part of the string, make sure sscanf read to EOL
12488 		 */
12489 		func_off = strrchr(func_name, '+');
12490 		if (func_off) {
12491 			n = sscanf(func_off, "+%li%n", &offset, &c);
12492 			if (n == 1 && *(func_off + c) == '\0')
12493 				func_off[0] = '\0';
12494 			else
12495 				offset = 0;
12496 		}
12497 		opts.retprobe = strcmp(probe_type, "uretprobe") == 0 ||
12498 				strcmp(probe_type, "uretprobe.s") == 0;
12499 		if (opts.retprobe && offset != 0) {
12500 			pr_warn("prog '%s': uretprobes do not support offset specification\n",
12501 				prog->name);
12502 			break;
12503 		}
12504 		opts.func_name = func_name;
12505 		*link = bpf_program__attach_uprobe_opts(prog, -1, binary_path, offset, &opts);
12506 		ret = libbpf_get_error(*link);
12507 		break;
12508 	default:
12509 		pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
12510 			prog->sec_name);
12511 		break;
12512 	}
12513 	free(probe_type);
12514 	free(binary_path);
12515 	free(func_name);
12516 
12517 	return ret;
12518 }
12519 
12520 struct bpf_link *bpf_program__attach_uprobe(const struct bpf_program *prog,
12521 					    bool retprobe, pid_t pid,
12522 					    const char *binary_path,
12523 					    size_t func_offset)
12524 {
12525 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts, .retprobe = retprobe);
12526 
12527 	return bpf_program__attach_uprobe_opts(prog, pid, binary_path, func_offset, &opts);
12528 }
12529 
12530 struct bpf_link *bpf_program__attach_usdt(const struct bpf_program *prog,
12531 					  pid_t pid, const char *binary_path,
12532 					  const char *usdt_provider, const char *usdt_name,
12533 					  const struct bpf_usdt_opts *opts)
12534 {
12535 	char resolved_path[512];
12536 	struct bpf_object *obj = prog->obj;
12537 	struct bpf_link *link;
12538 	__u64 usdt_cookie;
12539 	int err;
12540 
12541 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
12542 		return libbpf_err_ptr(-EINVAL);
12543 
12544 	if (bpf_program__fd(prog) < 0) {
12545 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
12546 			prog->name);
12547 		return libbpf_err_ptr(-EINVAL);
12548 	}
12549 
12550 	if (!binary_path)
12551 		return libbpf_err_ptr(-EINVAL);
12552 
12553 	if (!strchr(binary_path, '/')) {
12554 		err = resolve_full_path(binary_path, resolved_path, sizeof(resolved_path));
12555 		if (err) {
12556 			pr_warn("prog '%s': failed to resolve full path for '%s': %s\n",
12557 				prog->name, binary_path, errstr(err));
12558 			return libbpf_err_ptr(err);
12559 		}
12560 		binary_path = resolved_path;
12561 	}
12562 
12563 	/* USDT manager is instantiated lazily on first USDT attach. It will
12564 	 * be destroyed together with BPF object in bpf_object__close().
12565 	 */
12566 	if (IS_ERR(obj->usdt_man))
12567 		return libbpf_ptr(obj->usdt_man);
12568 	if (!obj->usdt_man) {
12569 		obj->usdt_man = usdt_manager_new(obj);
12570 		if (IS_ERR(obj->usdt_man))
12571 			return libbpf_ptr(obj->usdt_man);
12572 	}
12573 
12574 	usdt_cookie = OPTS_GET(opts, usdt_cookie, 0);
12575 	link = usdt_manager_attach_usdt(obj->usdt_man, prog, pid, binary_path,
12576 					usdt_provider, usdt_name, usdt_cookie);
12577 	err = libbpf_get_error(link);
12578 	if (err)
12579 		return libbpf_err_ptr(err);
12580 	return link;
12581 }
12582 
12583 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12584 {
12585 	char *path = NULL, *provider = NULL, *name = NULL;
12586 	const char *sec_name;
12587 	int n, err;
12588 
12589 	sec_name = bpf_program__section_name(prog);
12590 	if (strcmp(sec_name, "usdt") == 0) {
12591 		/* no auto-attach for just SEC("usdt") */
12592 		*link = NULL;
12593 		return 0;
12594 	}
12595 
12596 	n = sscanf(sec_name, "usdt/%m[^:]:%m[^:]:%m[^:]", &path, &provider, &name);
12597 	if (n != 3) {
12598 		pr_warn("invalid section '%s', expected SEC(\"usdt/<path>:<provider>:<name>\")\n",
12599 			sec_name);
12600 		err = -EINVAL;
12601 	} else {
12602 		*link = bpf_program__attach_usdt(prog, -1 /* any process */, path,
12603 						 provider, name, NULL);
12604 		err = libbpf_get_error(*link);
12605 	}
12606 	free(path);
12607 	free(provider);
12608 	free(name);
12609 	return err;
12610 }
12611 
12612 static int determine_tracepoint_id(const char *tp_category,
12613 				   const char *tp_name)
12614 {
12615 	char file[PATH_MAX];
12616 	int ret;
12617 
12618 	ret = snprintf(file, sizeof(file), "%s/events/%s/%s/id",
12619 		       tracefs_path(), tp_category, tp_name);
12620 	if (ret < 0)
12621 		return -errno;
12622 	if (ret >= sizeof(file)) {
12623 		pr_debug("tracepoint %s/%s path is too long\n",
12624 			 tp_category, tp_name);
12625 		return -E2BIG;
12626 	}
12627 	return parse_uint_from_file(file, "%d\n");
12628 }
12629 
12630 static int perf_event_open_tracepoint(const char *tp_category,
12631 				      const char *tp_name)
12632 {
12633 	const size_t attr_sz = sizeof(struct perf_event_attr);
12634 	struct perf_event_attr attr;
12635 	int tp_id, pfd, err;
12636 
12637 	tp_id = determine_tracepoint_id(tp_category, tp_name);
12638 	if (tp_id < 0) {
12639 		pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
12640 			tp_category, tp_name,
12641 			errstr(tp_id));
12642 		return tp_id;
12643 	}
12644 
12645 	memset(&attr, 0, attr_sz);
12646 	attr.type = PERF_TYPE_TRACEPOINT;
12647 	attr.size = attr_sz;
12648 	attr.config = tp_id;
12649 
12650 	pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
12651 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
12652 	if (pfd < 0) {
12653 		err = -errno;
12654 		pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
12655 			tp_category, tp_name,
12656 			errstr(err));
12657 		return err;
12658 	}
12659 	return pfd;
12660 }
12661 
12662 struct bpf_link *bpf_program__attach_tracepoint_opts(const struct bpf_program *prog,
12663 						     const char *tp_category,
12664 						     const char *tp_name,
12665 						     const struct bpf_tracepoint_opts *opts)
12666 {
12667 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
12668 	struct bpf_link *link;
12669 	int pfd, err;
12670 
12671 	if (!OPTS_VALID(opts, bpf_tracepoint_opts))
12672 		return libbpf_err_ptr(-EINVAL);
12673 
12674 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
12675 
12676 	pfd = perf_event_open_tracepoint(tp_category, tp_name);
12677 	if (pfd < 0) {
12678 		pr_warn("prog '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
12679 			prog->name, tp_category, tp_name,
12680 			errstr(pfd));
12681 		return libbpf_err_ptr(pfd);
12682 	}
12683 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
12684 	err = libbpf_get_error(link);
12685 	if (err) {
12686 		close(pfd);
12687 		pr_warn("prog '%s': failed to attach to tracepoint '%s/%s': %s\n",
12688 			prog->name, tp_category, tp_name,
12689 			errstr(err));
12690 		return libbpf_err_ptr(err);
12691 	}
12692 	return link;
12693 }
12694 
12695 struct bpf_link *bpf_program__attach_tracepoint(const struct bpf_program *prog,
12696 						const char *tp_category,
12697 						const char *tp_name)
12698 {
12699 	return bpf_program__attach_tracepoint_opts(prog, tp_category, tp_name, NULL);
12700 }
12701 
12702 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12703 {
12704 	char *sec_name, *tp_cat, *tp_name;
12705 
12706 	*link = NULL;
12707 
12708 	/* no auto-attach for SEC("tp") or SEC("tracepoint") */
12709 	if (strcmp(prog->sec_name, "tp") == 0 || strcmp(prog->sec_name, "tracepoint") == 0)
12710 		return 0;
12711 
12712 	sec_name = strdup(prog->sec_name);
12713 	if (!sec_name)
12714 		return -ENOMEM;
12715 
12716 	/* extract "tp/<category>/<name>" or "tracepoint/<category>/<name>" */
12717 	if (str_has_pfx(prog->sec_name, "tp/"))
12718 		tp_cat = sec_name + sizeof("tp/") - 1;
12719 	else
12720 		tp_cat = sec_name + sizeof("tracepoint/") - 1;
12721 	tp_name = strchr(tp_cat, '/');
12722 	if (!tp_name) {
12723 		free(sec_name);
12724 		return -EINVAL;
12725 	}
12726 	*tp_name = '\0';
12727 	tp_name++;
12728 
12729 	*link = bpf_program__attach_tracepoint(prog, tp_cat, tp_name);
12730 	free(sec_name);
12731 	return libbpf_get_error(*link);
12732 }
12733 
12734 struct bpf_link *
12735 bpf_program__attach_raw_tracepoint_opts(const struct bpf_program *prog,
12736 					const char *tp_name,
12737 					struct bpf_raw_tracepoint_opts *opts)
12738 {
12739 	LIBBPF_OPTS(bpf_raw_tp_opts, raw_opts);
12740 	struct bpf_link *link;
12741 	int prog_fd, pfd;
12742 
12743 	if (!OPTS_VALID(opts, bpf_raw_tracepoint_opts))
12744 		return libbpf_err_ptr(-EINVAL);
12745 
12746 	prog_fd = bpf_program__fd(prog);
12747 	if (prog_fd < 0) {
12748 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12749 		return libbpf_err_ptr(-EINVAL);
12750 	}
12751 
12752 	link = calloc(1, sizeof(*link));
12753 	if (!link)
12754 		return libbpf_err_ptr(-ENOMEM);
12755 	link->detach = &bpf_link__detach_fd;
12756 
12757 	raw_opts.tp_name = tp_name;
12758 	raw_opts.cookie = OPTS_GET(opts, cookie, 0);
12759 	pfd = bpf_raw_tracepoint_open_opts(prog_fd, &raw_opts);
12760 	if (pfd < 0) {
12761 		pfd = -errno;
12762 		free(link);
12763 		pr_warn("prog '%s': failed to attach to raw tracepoint '%s': %s\n",
12764 			prog->name, tp_name, errstr(pfd));
12765 		return libbpf_err_ptr(pfd);
12766 	}
12767 	link->fd = pfd;
12768 	return link;
12769 }
12770 
12771 struct bpf_link *bpf_program__attach_raw_tracepoint(const struct bpf_program *prog,
12772 						    const char *tp_name)
12773 {
12774 	return bpf_program__attach_raw_tracepoint_opts(prog, tp_name, NULL);
12775 }
12776 
12777 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12778 {
12779 	static const char *const prefixes[] = {
12780 		"raw_tp",
12781 		"raw_tracepoint",
12782 		"raw_tp.w",
12783 		"raw_tracepoint.w",
12784 	};
12785 	size_t i;
12786 	const char *tp_name = NULL;
12787 
12788 	*link = NULL;
12789 
12790 	for (i = 0; i < ARRAY_SIZE(prefixes); i++) {
12791 		size_t pfx_len;
12792 
12793 		if (!str_has_pfx(prog->sec_name, prefixes[i]))
12794 			continue;
12795 
12796 		pfx_len = strlen(prefixes[i]);
12797 		/* no auto-attach case of, e.g., SEC("raw_tp") */
12798 		if (prog->sec_name[pfx_len] == '\0')
12799 			return 0;
12800 
12801 		if (prog->sec_name[pfx_len] != '/')
12802 			continue;
12803 
12804 		tp_name = prog->sec_name + pfx_len + 1;
12805 		break;
12806 	}
12807 
12808 	if (!tp_name) {
12809 		pr_warn("prog '%s': invalid section name '%s'\n",
12810 			prog->name, prog->sec_name);
12811 		return -EINVAL;
12812 	}
12813 
12814 	*link = bpf_program__attach_raw_tracepoint(prog, tp_name);
12815 	return libbpf_get_error(*link);
12816 }
12817 
12818 /* Common logic for all BPF program types that attach to a btf_id */
12819 static struct bpf_link *bpf_program__attach_btf_id(const struct bpf_program *prog,
12820 						   const struct bpf_trace_opts *opts)
12821 {
12822 	LIBBPF_OPTS(bpf_link_create_opts, link_opts);
12823 	struct bpf_link *link;
12824 	int prog_fd, pfd;
12825 
12826 	if (!OPTS_VALID(opts, bpf_trace_opts))
12827 		return libbpf_err_ptr(-EINVAL);
12828 
12829 	prog_fd = bpf_program__fd(prog);
12830 	if (prog_fd < 0) {
12831 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12832 		return libbpf_err_ptr(-EINVAL);
12833 	}
12834 
12835 	link = calloc(1, sizeof(*link));
12836 	if (!link)
12837 		return libbpf_err_ptr(-ENOMEM);
12838 	link->detach = &bpf_link__detach_fd;
12839 
12840 	/* libbpf is smart enough to redirect to BPF_RAW_TRACEPOINT_OPEN on old kernels */
12841 	link_opts.tracing.cookie = OPTS_GET(opts, cookie, 0);
12842 	pfd = bpf_link_create(prog_fd, 0, bpf_program__expected_attach_type(prog), &link_opts);
12843 	if (pfd < 0) {
12844 		pfd = -errno;
12845 		free(link);
12846 		pr_warn("prog '%s': failed to attach: %s\n",
12847 			prog->name, errstr(pfd));
12848 		return libbpf_err_ptr(pfd);
12849 	}
12850 	link->fd = pfd;
12851 	return link;
12852 }
12853 
12854 struct bpf_link *bpf_program__attach_trace(const struct bpf_program *prog)
12855 {
12856 	return bpf_program__attach_btf_id(prog, NULL);
12857 }
12858 
12859 struct bpf_link *bpf_program__attach_trace_opts(const struct bpf_program *prog,
12860 						const struct bpf_trace_opts *opts)
12861 {
12862 	return bpf_program__attach_btf_id(prog, opts);
12863 }
12864 
12865 struct bpf_link *bpf_program__attach_lsm(const struct bpf_program *prog)
12866 {
12867 	return bpf_program__attach_btf_id(prog, NULL);
12868 }
12869 
12870 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12871 {
12872 	*link = bpf_program__attach_trace(prog);
12873 	return libbpf_get_error(*link);
12874 }
12875 
12876 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12877 {
12878 	*link = bpf_program__attach_lsm(prog);
12879 	return libbpf_get_error(*link);
12880 }
12881 
12882 static struct bpf_link *
12883 bpf_program_attach_fd(const struct bpf_program *prog,
12884 		      int target_fd, const char *target_name,
12885 		      const struct bpf_link_create_opts *opts)
12886 {
12887 	enum bpf_attach_type attach_type;
12888 	struct bpf_link *link;
12889 	int prog_fd, link_fd;
12890 
12891 	prog_fd = bpf_program__fd(prog);
12892 	if (prog_fd < 0) {
12893 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12894 		return libbpf_err_ptr(-EINVAL);
12895 	}
12896 
12897 	link = calloc(1, sizeof(*link));
12898 	if (!link)
12899 		return libbpf_err_ptr(-ENOMEM);
12900 	link->detach = &bpf_link__detach_fd;
12901 
12902 	attach_type = bpf_program__expected_attach_type(prog);
12903 	link_fd = bpf_link_create(prog_fd, target_fd, attach_type, opts);
12904 	if (link_fd < 0) {
12905 		link_fd = -errno;
12906 		free(link);
12907 		pr_warn("prog '%s': failed to attach to %s: %s\n",
12908 			prog->name, target_name,
12909 			errstr(link_fd));
12910 		return libbpf_err_ptr(link_fd);
12911 	}
12912 	link->fd = link_fd;
12913 	return link;
12914 }
12915 
12916 struct bpf_link *
12917 bpf_program__attach_cgroup(const struct bpf_program *prog, int cgroup_fd)
12918 {
12919 	return bpf_program_attach_fd(prog, cgroup_fd, "cgroup", NULL);
12920 }
12921 
12922 struct bpf_link *
12923 bpf_program__attach_netns(const struct bpf_program *prog, int netns_fd)
12924 {
12925 	return bpf_program_attach_fd(prog, netns_fd, "netns", NULL);
12926 }
12927 
12928 struct bpf_link *
12929 bpf_program__attach_sockmap(const struct bpf_program *prog, int map_fd)
12930 {
12931 	return bpf_program_attach_fd(prog, map_fd, "sockmap", NULL);
12932 }
12933 
12934 struct bpf_link *bpf_program__attach_xdp(const struct bpf_program *prog, int ifindex)
12935 {
12936 	/* target_fd/target_ifindex use the same field in LINK_CREATE */
12937 	return bpf_program_attach_fd(prog, ifindex, "xdp", NULL);
12938 }
12939 
12940 struct bpf_link *
12941 bpf_program__attach_cgroup_opts(const struct bpf_program *prog, int cgroup_fd,
12942 				const struct bpf_cgroup_opts *opts)
12943 {
12944 	LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
12945 	__u32 relative_id;
12946 	int relative_fd;
12947 
12948 	if (!OPTS_VALID(opts, bpf_cgroup_opts))
12949 		return libbpf_err_ptr(-EINVAL);
12950 
12951 	relative_id = OPTS_GET(opts, relative_id, 0);
12952 	relative_fd = OPTS_GET(opts, relative_fd, 0);
12953 
12954 	if (relative_fd && relative_id) {
12955 		pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
12956 			prog->name);
12957 		return libbpf_err_ptr(-EINVAL);
12958 	}
12959 
12960 	link_create_opts.cgroup.expected_revision = OPTS_GET(opts, expected_revision, 0);
12961 	link_create_opts.cgroup.relative_fd = relative_fd;
12962 	link_create_opts.cgroup.relative_id = relative_id;
12963 	link_create_opts.flags = OPTS_GET(opts, flags, 0);
12964 
12965 	return bpf_program_attach_fd(prog, cgroup_fd, "cgroup", &link_create_opts);
12966 }
12967 
12968 struct bpf_link *
12969 bpf_program__attach_tcx(const struct bpf_program *prog, int ifindex,
12970 			const struct bpf_tcx_opts *opts)
12971 {
12972 	LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
12973 	__u32 relative_id;
12974 	int relative_fd;
12975 
12976 	if (!OPTS_VALID(opts, bpf_tcx_opts))
12977 		return libbpf_err_ptr(-EINVAL);
12978 
12979 	relative_id = OPTS_GET(opts, relative_id, 0);
12980 	relative_fd = OPTS_GET(opts, relative_fd, 0);
12981 
12982 	/* validate we don't have unexpected combinations of non-zero fields */
12983 	if (!ifindex) {
12984 		pr_warn("prog '%s': target netdevice ifindex cannot be zero\n",
12985 			prog->name);
12986 		return libbpf_err_ptr(-EINVAL);
12987 	}
12988 	if (relative_fd && relative_id) {
12989 		pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
12990 			prog->name);
12991 		return libbpf_err_ptr(-EINVAL);
12992 	}
12993 
12994 	link_create_opts.tcx.expected_revision = OPTS_GET(opts, expected_revision, 0);
12995 	link_create_opts.tcx.relative_fd = relative_fd;
12996 	link_create_opts.tcx.relative_id = relative_id;
12997 	link_create_opts.flags = OPTS_GET(opts, flags, 0);
12998 
12999 	/* target_fd/target_ifindex use the same field in LINK_CREATE */
13000 	return bpf_program_attach_fd(prog, ifindex, "tcx", &link_create_opts);
13001 }
13002 
13003 struct bpf_link *
13004 bpf_program__attach_netkit(const struct bpf_program *prog, int ifindex,
13005 			   const struct bpf_netkit_opts *opts)
13006 {
13007 	LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
13008 	__u32 relative_id;
13009 	int relative_fd;
13010 
13011 	if (!OPTS_VALID(opts, bpf_netkit_opts))
13012 		return libbpf_err_ptr(-EINVAL);
13013 
13014 	relative_id = OPTS_GET(opts, relative_id, 0);
13015 	relative_fd = OPTS_GET(opts, relative_fd, 0);
13016 
13017 	/* validate we don't have unexpected combinations of non-zero fields */
13018 	if (!ifindex) {
13019 		pr_warn("prog '%s': target netdevice ifindex cannot be zero\n",
13020 			prog->name);
13021 		return libbpf_err_ptr(-EINVAL);
13022 	}
13023 	if (relative_fd && relative_id) {
13024 		pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
13025 			prog->name);
13026 		return libbpf_err_ptr(-EINVAL);
13027 	}
13028 
13029 	link_create_opts.netkit.expected_revision = OPTS_GET(opts, expected_revision, 0);
13030 	link_create_opts.netkit.relative_fd = relative_fd;
13031 	link_create_opts.netkit.relative_id = relative_id;
13032 	link_create_opts.flags = OPTS_GET(opts, flags, 0);
13033 
13034 	return bpf_program_attach_fd(prog, ifindex, "netkit", &link_create_opts);
13035 }
13036 
13037 struct bpf_link *bpf_program__attach_freplace(const struct bpf_program *prog,
13038 					      int target_fd,
13039 					      const char *attach_func_name)
13040 {
13041 	int btf_id;
13042 
13043 	if (!!target_fd != !!attach_func_name) {
13044 		pr_warn("prog '%s': supply none or both of target_fd and attach_func_name\n",
13045 			prog->name);
13046 		return libbpf_err_ptr(-EINVAL);
13047 	}
13048 
13049 	if (prog->type != BPF_PROG_TYPE_EXT) {
13050 		pr_warn("prog '%s': only BPF_PROG_TYPE_EXT can attach as freplace\n",
13051 			prog->name);
13052 		return libbpf_err_ptr(-EINVAL);
13053 	}
13054 
13055 	if (target_fd) {
13056 		LIBBPF_OPTS(bpf_link_create_opts, target_opts);
13057 
13058 		btf_id = libbpf_find_prog_btf_id(attach_func_name, target_fd, prog->obj->token_fd);
13059 		if (btf_id < 0)
13060 			return libbpf_err_ptr(btf_id);
13061 
13062 		target_opts.target_btf_id = btf_id;
13063 
13064 		return bpf_program_attach_fd(prog, target_fd, "freplace",
13065 					     &target_opts);
13066 	} else {
13067 		/* no target, so use raw_tracepoint_open for compatibility
13068 		 * with old kernels
13069 		 */
13070 		return bpf_program__attach_trace(prog);
13071 	}
13072 }
13073 
13074 struct bpf_link *
13075 bpf_program__attach_iter(const struct bpf_program *prog,
13076 			 const struct bpf_iter_attach_opts *opts)
13077 {
13078 	DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
13079 	struct bpf_link *link;
13080 	int prog_fd, link_fd;
13081 	__u32 target_fd = 0;
13082 
13083 	if (!OPTS_VALID(opts, bpf_iter_attach_opts))
13084 		return libbpf_err_ptr(-EINVAL);
13085 
13086 	link_create_opts.iter_info = OPTS_GET(opts, link_info, (void *)0);
13087 	link_create_opts.iter_info_len = OPTS_GET(opts, link_info_len, 0);
13088 
13089 	prog_fd = bpf_program__fd(prog);
13090 	if (prog_fd < 0) {
13091 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
13092 		return libbpf_err_ptr(-EINVAL);
13093 	}
13094 
13095 	link = calloc(1, sizeof(*link));
13096 	if (!link)
13097 		return libbpf_err_ptr(-ENOMEM);
13098 	link->detach = &bpf_link__detach_fd;
13099 
13100 	link_fd = bpf_link_create(prog_fd, target_fd, BPF_TRACE_ITER,
13101 				  &link_create_opts);
13102 	if (link_fd < 0) {
13103 		link_fd = -errno;
13104 		free(link);
13105 		pr_warn("prog '%s': failed to attach to iterator: %s\n",
13106 			prog->name, errstr(link_fd));
13107 		return libbpf_err_ptr(link_fd);
13108 	}
13109 	link->fd = link_fd;
13110 	return link;
13111 }
13112 
13113 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link)
13114 {
13115 	*link = bpf_program__attach_iter(prog, NULL);
13116 	return libbpf_get_error(*link);
13117 }
13118 
13119 struct bpf_link *bpf_program__attach_netfilter(const struct bpf_program *prog,
13120 					       const struct bpf_netfilter_opts *opts)
13121 {
13122 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
13123 	struct bpf_link *link;
13124 	int prog_fd, link_fd;
13125 
13126 	if (!OPTS_VALID(opts, bpf_netfilter_opts))
13127 		return libbpf_err_ptr(-EINVAL);
13128 
13129 	prog_fd = bpf_program__fd(prog);
13130 	if (prog_fd < 0) {
13131 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
13132 		return libbpf_err_ptr(-EINVAL);
13133 	}
13134 
13135 	link = calloc(1, sizeof(*link));
13136 	if (!link)
13137 		return libbpf_err_ptr(-ENOMEM);
13138 
13139 	link->detach = &bpf_link__detach_fd;
13140 
13141 	lopts.netfilter.pf = OPTS_GET(opts, pf, 0);
13142 	lopts.netfilter.hooknum = OPTS_GET(opts, hooknum, 0);
13143 	lopts.netfilter.priority = OPTS_GET(opts, priority, 0);
13144 	lopts.netfilter.flags = OPTS_GET(opts, flags, 0);
13145 
13146 	link_fd = bpf_link_create(prog_fd, 0, BPF_NETFILTER, &lopts);
13147 	if (link_fd < 0) {
13148 		link_fd = -errno;
13149 		free(link);
13150 		pr_warn("prog '%s': failed to attach to netfilter: %s\n",
13151 			prog->name, errstr(link_fd));
13152 		return libbpf_err_ptr(link_fd);
13153 	}
13154 	link->fd = link_fd;
13155 
13156 	return link;
13157 }
13158 
13159 struct bpf_link *bpf_program__attach(const struct bpf_program *prog)
13160 {
13161 	struct bpf_link *link = NULL;
13162 	int err;
13163 
13164 	if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
13165 		return libbpf_err_ptr(-EOPNOTSUPP);
13166 
13167 	if (bpf_program__fd(prog) < 0) {
13168 		pr_warn("prog '%s': can't attach BPF program without FD (was it loaded?)\n",
13169 			prog->name);
13170 		return libbpf_err_ptr(-EINVAL);
13171 	}
13172 
13173 	err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, &link);
13174 	if (err)
13175 		return libbpf_err_ptr(err);
13176 
13177 	/* When calling bpf_program__attach() explicitly, auto-attach support
13178 	 * is expected to work, so NULL returned link is considered an error.
13179 	 * This is different for skeleton's attach, see comment in
13180 	 * bpf_object__attach_skeleton().
13181 	 */
13182 	if (!link)
13183 		return libbpf_err_ptr(-EOPNOTSUPP);
13184 
13185 	return link;
13186 }
13187 
13188 struct bpf_link_struct_ops {
13189 	struct bpf_link link;
13190 	int map_fd;
13191 };
13192 
13193 static int bpf_link__detach_struct_ops(struct bpf_link *link)
13194 {
13195 	struct bpf_link_struct_ops *st_link;
13196 	__u32 zero = 0;
13197 
13198 	st_link = container_of(link, struct bpf_link_struct_ops, link);
13199 
13200 	if (st_link->map_fd < 0)
13201 		/* w/o a real link */
13202 		return bpf_map_delete_elem(link->fd, &zero);
13203 
13204 	return close(link->fd);
13205 }
13206 
13207 struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map)
13208 {
13209 	struct bpf_link_struct_ops *link;
13210 	__u32 zero = 0;
13211 	int err, fd;
13212 
13213 	if (!bpf_map__is_struct_ops(map)) {
13214 		pr_warn("map '%s': can't attach non-struct_ops map\n", map->name);
13215 		return libbpf_err_ptr(-EINVAL);
13216 	}
13217 
13218 	if (map->fd < 0) {
13219 		pr_warn("map '%s': can't attach BPF map without FD (was it created?)\n", map->name);
13220 		return libbpf_err_ptr(-EINVAL);
13221 	}
13222 
13223 	link = calloc(1, sizeof(*link));
13224 	if (!link)
13225 		return libbpf_err_ptr(-EINVAL);
13226 
13227 	/* kern_vdata should be prepared during the loading phase. */
13228 	err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
13229 	/* It can be EBUSY if the map has been used to create or
13230 	 * update a link before.  We don't allow updating the value of
13231 	 * a struct_ops once it is set.  That ensures that the value
13232 	 * never changed.  So, it is safe to skip EBUSY.
13233 	 */
13234 	if (err && (!(map->def.map_flags & BPF_F_LINK) || err != -EBUSY)) {
13235 		free(link);
13236 		return libbpf_err_ptr(err);
13237 	}
13238 
13239 	link->link.detach = bpf_link__detach_struct_ops;
13240 
13241 	if (!(map->def.map_flags & BPF_F_LINK)) {
13242 		/* w/o a real link */
13243 		link->link.fd = map->fd;
13244 		link->map_fd = -1;
13245 		return &link->link;
13246 	}
13247 
13248 	fd = bpf_link_create(map->fd, 0, BPF_STRUCT_OPS, NULL);
13249 	if (fd < 0) {
13250 		free(link);
13251 		return libbpf_err_ptr(fd);
13252 	}
13253 
13254 	link->link.fd = fd;
13255 	link->map_fd = map->fd;
13256 
13257 	return &link->link;
13258 }
13259 
13260 /*
13261  * Swap the back struct_ops of a link with a new struct_ops map.
13262  */
13263 int bpf_link__update_map(struct bpf_link *link, const struct bpf_map *map)
13264 {
13265 	struct bpf_link_struct_ops *st_ops_link;
13266 	__u32 zero = 0;
13267 	int err;
13268 
13269 	if (!bpf_map__is_struct_ops(map))
13270 		return libbpf_err(-EINVAL);
13271 
13272 	if (map->fd < 0) {
13273 		pr_warn("map '%s': can't use BPF map without FD (was it created?)\n", map->name);
13274 		return libbpf_err(-EINVAL);
13275 	}
13276 
13277 	st_ops_link = container_of(link, struct bpf_link_struct_ops, link);
13278 	/* Ensure the type of a link is correct */
13279 	if (st_ops_link->map_fd < 0)
13280 		return libbpf_err(-EINVAL);
13281 
13282 	err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
13283 	/* It can be EBUSY if the map has been used to create or
13284 	 * update a link before.  We don't allow updating the value of
13285 	 * a struct_ops once it is set.  That ensures that the value
13286 	 * never changed.  So, it is safe to skip EBUSY.
13287 	 */
13288 	if (err && err != -EBUSY)
13289 		return err;
13290 
13291 	err = bpf_link_update(link->fd, map->fd, NULL);
13292 	if (err < 0)
13293 		return err;
13294 
13295 	st_ops_link->map_fd = map->fd;
13296 
13297 	return 0;
13298 }
13299 
13300 typedef enum bpf_perf_event_ret (*bpf_perf_event_print_t)(struct perf_event_header *hdr,
13301 							  void *private_data);
13302 
13303 static enum bpf_perf_event_ret
13304 perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
13305 		       void **copy_mem, size_t *copy_size,
13306 		       bpf_perf_event_print_t fn, void *private_data)
13307 {
13308 	struct perf_event_mmap_page *header = mmap_mem;
13309 	__u64 data_head = ring_buffer_read_head(header);
13310 	__u64 data_tail = header->data_tail;
13311 	void *base = ((__u8 *)header) + page_size;
13312 	int ret = LIBBPF_PERF_EVENT_CONT;
13313 	struct perf_event_header *ehdr;
13314 	size_t ehdr_size;
13315 
13316 	while (data_head != data_tail) {
13317 		ehdr = base + (data_tail & (mmap_size - 1));
13318 		ehdr_size = ehdr->size;
13319 
13320 		if (((void *)ehdr) + ehdr_size > base + mmap_size) {
13321 			void *copy_start = ehdr;
13322 			size_t len_first = base + mmap_size - copy_start;
13323 			size_t len_secnd = ehdr_size - len_first;
13324 
13325 			if (*copy_size < ehdr_size) {
13326 				free(*copy_mem);
13327 				*copy_mem = malloc(ehdr_size);
13328 				if (!*copy_mem) {
13329 					*copy_size = 0;
13330 					ret = LIBBPF_PERF_EVENT_ERROR;
13331 					break;
13332 				}
13333 				*copy_size = ehdr_size;
13334 			}
13335 
13336 			memcpy(*copy_mem, copy_start, len_first);
13337 			memcpy(*copy_mem + len_first, base, len_secnd);
13338 			ehdr = *copy_mem;
13339 		}
13340 
13341 		ret = fn(ehdr, private_data);
13342 		data_tail += ehdr_size;
13343 		if (ret != LIBBPF_PERF_EVENT_CONT)
13344 			break;
13345 	}
13346 
13347 	ring_buffer_write_tail(header, data_tail);
13348 	return libbpf_err(ret);
13349 }
13350 
13351 struct perf_buffer;
13352 
13353 struct perf_buffer_params {
13354 	struct perf_event_attr *attr;
13355 	/* if event_cb is specified, it takes precendence */
13356 	perf_buffer_event_fn event_cb;
13357 	/* sample_cb and lost_cb are higher-level common-case callbacks */
13358 	perf_buffer_sample_fn sample_cb;
13359 	perf_buffer_lost_fn lost_cb;
13360 	void *ctx;
13361 	int cpu_cnt;
13362 	int *cpus;
13363 	int *map_keys;
13364 };
13365 
13366 struct perf_cpu_buf {
13367 	struct perf_buffer *pb;
13368 	void *base; /* mmap()'ed memory */
13369 	void *buf; /* for reconstructing segmented data */
13370 	size_t buf_size;
13371 	int fd;
13372 	int cpu;
13373 	int map_key;
13374 };
13375 
13376 struct perf_buffer {
13377 	perf_buffer_event_fn event_cb;
13378 	perf_buffer_sample_fn sample_cb;
13379 	perf_buffer_lost_fn lost_cb;
13380 	void *ctx; /* passed into callbacks */
13381 
13382 	size_t page_size;
13383 	size_t mmap_size;
13384 	struct perf_cpu_buf **cpu_bufs;
13385 	struct epoll_event *events;
13386 	int cpu_cnt; /* number of allocated CPU buffers */
13387 	int epoll_fd; /* perf event FD */
13388 	int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
13389 };
13390 
13391 static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
13392 				      struct perf_cpu_buf *cpu_buf)
13393 {
13394 	if (!cpu_buf)
13395 		return;
13396 	if (cpu_buf->base &&
13397 	    munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
13398 		pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
13399 	if (cpu_buf->fd >= 0) {
13400 		ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
13401 		close(cpu_buf->fd);
13402 	}
13403 	free(cpu_buf->buf);
13404 	free(cpu_buf);
13405 }
13406 
13407 void perf_buffer__free(struct perf_buffer *pb)
13408 {
13409 	int i;
13410 
13411 	if (IS_ERR_OR_NULL(pb))
13412 		return;
13413 	if (pb->cpu_bufs) {
13414 		for (i = 0; i < pb->cpu_cnt; i++) {
13415 			struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
13416 
13417 			if (!cpu_buf)
13418 				continue;
13419 
13420 			bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
13421 			perf_buffer__free_cpu_buf(pb, cpu_buf);
13422 		}
13423 		free(pb->cpu_bufs);
13424 	}
13425 	if (pb->epoll_fd >= 0)
13426 		close(pb->epoll_fd);
13427 	free(pb->events);
13428 	free(pb);
13429 }
13430 
13431 static struct perf_cpu_buf *
13432 perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
13433 			  int cpu, int map_key)
13434 {
13435 	struct perf_cpu_buf *cpu_buf;
13436 	int err;
13437 
13438 	cpu_buf = calloc(1, sizeof(*cpu_buf));
13439 	if (!cpu_buf)
13440 		return ERR_PTR(-ENOMEM);
13441 
13442 	cpu_buf->pb = pb;
13443 	cpu_buf->cpu = cpu;
13444 	cpu_buf->map_key = map_key;
13445 
13446 	cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
13447 			      -1, PERF_FLAG_FD_CLOEXEC);
13448 	if (cpu_buf->fd < 0) {
13449 		err = -errno;
13450 		pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
13451 			cpu, errstr(err));
13452 		goto error;
13453 	}
13454 
13455 	cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
13456 			     PROT_READ | PROT_WRITE, MAP_SHARED,
13457 			     cpu_buf->fd, 0);
13458 	if (cpu_buf->base == MAP_FAILED) {
13459 		cpu_buf->base = NULL;
13460 		err = -errno;
13461 		pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
13462 			cpu, errstr(err));
13463 		goto error;
13464 	}
13465 
13466 	if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
13467 		err = -errno;
13468 		pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
13469 			cpu, errstr(err));
13470 		goto error;
13471 	}
13472 
13473 	return cpu_buf;
13474 
13475 error:
13476 	perf_buffer__free_cpu_buf(pb, cpu_buf);
13477 	return (struct perf_cpu_buf *)ERR_PTR(err);
13478 }
13479 
13480 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
13481 					      struct perf_buffer_params *p);
13482 
13483 struct perf_buffer *perf_buffer__new(int map_fd, size_t page_cnt,
13484 				     perf_buffer_sample_fn sample_cb,
13485 				     perf_buffer_lost_fn lost_cb,
13486 				     void *ctx,
13487 				     const struct perf_buffer_opts *opts)
13488 {
13489 	const size_t attr_sz = sizeof(struct perf_event_attr);
13490 	struct perf_buffer_params p = {};
13491 	struct perf_event_attr attr;
13492 	__u32 sample_period;
13493 
13494 	if (!OPTS_VALID(opts, perf_buffer_opts))
13495 		return libbpf_err_ptr(-EINVAL);
13496 
13497 	sample_period = OPTS_GET(opts, sample_period, 1);
13498 	if (!sample_period)
13499 		sample_period = 1;
13500 
13501 	memset(&attr, 0, attr_sz);
13502 	attr.size = attr_sz;
13503 	attr.config = PERF_COUNT_SW_BPF_OUTPUT;
13504 	attr.type = PERF_TYPE_SOFTWARE;
13505 	attr.sample_type = PERF_SAMPLE_RAW;
13506 	attr.wakeup_events = sample_period;
13507 
13508 	p.attr = &attr;
13509 	p.sample_cb = sample_cb;
13510 	p.lost_cb = lost_cb;
13511 	p.ctx = ctx;
13512 
13513 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
13514 }
13515 
13516 struct perf_buffer *perf_buffer__new_raw(int map_fd, size_t page_cnt,
13517 					 struct perf_event_attr *attr,
13518 					 perf_buffer_event_fn event_cb, void *ctx,
13519 					 const struct perf_buffer_raw_opts *opts)
13520 {
13521 	struct perf_buffer_params p = {};
13522 
13523 	if (!attr)
13524 		return libbpf_err_ptr(-EINVAL);
13525 
13526 	if (!OPTS_VALID(opts, perf_buffer_raw_opts))
13527 		return libbpf_err_ptr(-EINVAL);
13528 
13529 	p.attr = attr;
13530 	p.event_cb = event_cb;
13531 	p.ctx = ctx;
13532 	p.cpu_cnt = OPTS_GET(opts, cpu_cnt, 0);
13533 	p.cpus = OPTS_GET(opts, cpus, NULL);
13534 	p.map_keys = OPTS_GET(opts, map_keys, NULL);
13535 
13536 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
13537 }
13538 
13539 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
13540 					      struct perf_buffer_params *p)
13541 {
13542 	const char *online_cpus_file = "/sys/devices/system/cpu/online";
13543 	struct bpf_map_info map;
13544 	struct perf_buffer *pb;
13545 	bool *online = NULL;
13546 	__u32 map_info_len;
13547 	int err, i, j, n;
13548 
13549 	if (page_cnt == 0 || (page_cnt & (page_cnt - 1))) {
13550 		pr_warn("page count should be power of two, but is %zu\n",
13551 			page_cnt);
13552 		return ERR_PTR(-EINVAL);
13553 	}
13554 
13555 	/* best-effort sanity checks */
13556 	memset(&map, 0, sizeof(map));
13557 	map_info_len = sizeof(map);
13558 	err = bpf_map_get_info_by_fd(map_fd, &map, &map_info_len);
13559 	if (err) {
13560 		err = -errno;
13561 		/* if BPF_OBJ_GET_INFO_BY_FD is supported, will return
13562 		 * -EBADFD, -EFAULT, or -E2BIG on real error
13563 		 */
13564 		if (err != -EINVAL) {
13565 			pr_warn("failed to get map info for map FD %d: %s\n",
13566 				map_fd, errstr(err));
13567 			return ERR_PTR(err);
13568 		}
13569 		pr_debug("failed to get map info for FD %d; API not supported? Ignoring...\n",
13570 			 map_fd);
13571 	} else {
13572 		if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
13573 			pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
13574 				map.name);
13575 			return ERR_PTR(-EINVAL);
13576 		}
13577 	}
13578 
13579 	pb = calloc(1, sizeof(*pb));
13580 	if (!pb)
13581 		return ERR_PTR(-ENOMEM);
13582 
13583 	pb->event_cb = p->event_cb;
13584 	pb->sample_cb = p->sample_cb;
13585 	pb->lost_cb = p->lost_cb;
13586 	pb->ctx = p->ctx;
13587 
13588 	pb->page_size = getpagesize();
13589 	pb->mmap_size = pb->page_size * page_cnt;
13590 	pb->map_fd = map_fd;
13591 
13592 	pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
13593 	if (pb->epoll_fd < 0) {
13594 		err = -errno;
13595 		pr_warn("failed to create epoll instance: %s\n",
13596 			errstr(err));
13597 		goto error;
13598 	}
13599 
13600 	if (p->cpu_cnt > 0) {
13601 		pb->cpu_cnt = p->cpu_cnt;
13602 	} else {
13603 		pb->cpu_cnt = libbpf_num_possible_cpus();
13604 		if (pb->cpu_cnt < 0) {
13605 			err = pb->cpu_cnt;
13606 			goto error;
13607 		}
13608 		if (map.max_entries && map.max_entries < pb->cpu_cnt)
13609 			pb->cpu_cnt = map.max_entries;
13610 	}
13611 
13612 	pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
13613 	if (!pb->events) {
13614 		err = -ENOMEM;
13615 		pr_warn("failed to allocate events: out of memory\n");
13616 		goto error;
13617 	}
13618 	pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
13619 	if (!pb->cpu_bufs) {
13620 		err = -ENOMEM;
13621 		pr_warn("failed to allocate buffers: out of memory\n");
13622 		goto error;
13623 	}
13624 
13625 	err = parse_cpu_mask_file(online_cpus_file, &online, &n);
13626 	if (err) {
13627 		pr_warn("failed to get online CPU mask: %s\n", errstr(err));
13628 		goto error;
13629 	}
13630 
13631 	for (i = 0, j = 0; i < pb->cpu_cnt; i++) {
13632 		struct perf_cpu_buf *cpu_buf;
13633 		int cpu, map_key;
13634 
13635 		cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
13636 		map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
13637 
13638 		/* in case user didn't explicitly requested particular CPUs to
13639 		 * be attached to, skip offline/not present CPUs
13640 		 */
13641 		if (p->cpu_cnt <= 0 && (cpu >= n || !online[cpu]))
13642 			continue;
13643 
13644 		cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
13645 		if (IS_ERR(cpu_buf)) {
13646 			err = PTR_ERR(cpu_buf);
13647 			goto error;
13648 		}
13649 
13650 		pb->cpu_bufs[j] = cpu_buf;
13651 
13652 		err = bpf_map_update_elem(pb->map_fd, &map_key,
13653 					  &cpu_buf->fd, 0);
13654 		if (err) {
13655 			err = -errno;
13656 			pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
13657 				cpu, map_key, cpu_buf->fd,
13658 				errstr(err));
13659 			goto error;
13660 		}
13661 
13662 		pb->events[j].events = EPOLLIN;
13663 		pb->events[j].data.ptr = cpu_buf;
13664 		if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
13665 			      &pb->events[j]) < 0) {
13666 			err = -errno;
13667 			pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
13668 				cpu, cpu_buf->fd,
13669 				errstr(err));
13670 			goto error;
13671 		}
13672 		j++;
13673 	}
13674 	pb->cpu_cnt = j;
13675 	free(online);
13676 
13677 	return pb;
13678 
13679 error:
13680 	free(online);
13681 	if (pb)
13682 		perf_buffer__free(pb);
13683 	return ERR_PTR(err);
13684 }
13685 
13686 struct perf_sample_raw {
13687 	struct perf_event_header header;
13688 	uint32_t size;
13689 	char data[];
13690 };
13691 
13692 struct perf_sample_lost {
13693 	struct perf_event_header header;
13694 	uint64_t id;
13695 	uint64_t lost;
13696 	uint64_t sample_id;
13697 };
13698 
13699 static enum bpf_perf_event_ret
13700 perf_buffer__process_record(struct perf_event_header *e, void *ctx)
13701 {
13702 	struct perf_cpu_buf *cpu_buf = ctx;
13703 	struct perf_buffer *pb = cpu_buf->pb;
13704 	void *data = e;
13705 
13706 	/* user wants full control over parsing perf event */
13707 	if (pb->event_cb)
13708 		return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
13709 
13710 	switch (e->type) {
13711 	case PERF_RECORD_SAMPLE: {
13712 		struct perf_sample_raw *s = data;
13713 
13714 		if (pb->sample_cb)
13715 			pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
13716 		break;
13717 	}
13718 	case PERF_RECORD_LOST: {
13719 		struct perf_sample_lost *s = data;
13720 
13721 		if (pb->lost_cb)
13722 			pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
13723 		break;
13724 	}
13725 	default:
13726 		pr_warn("unknown perf sample type %d\n", e->type);
13727 		return LIBBPF_PERF_EVENT_ERROR;
13728 	}
13729 	return LIBBPF_PERF_EVENT_CONT;
13730 }
13731 
13732 static int perf_buffer__process_records(struct perf_buffer *pb,
13733 					struct perf_cpu_buf *cpu_buf)
13734 {
13735 	enum bpf_perf_event_ret ret;
13736 
13737 	ret = perf_event_read_simple(cpu_buf->base, pb->mmap_size,
13738 				     pb->page_size, &cpu_buf->buf,
13739 				     &cpu_buf->buf_size,
13740 				     perf_buffer__process_record, cpu_buf);
13741 	if (ret != LIBBPF_PERF_EVENT_CONT)
13742 		return ret;
13743 	return 0;
13744 }
13745 
13746 int perf_buffer__epoll_fd(const struct perf_buffer *pb)
13747 {
13748 	return pb->epoll_fd;
13749 }
13750 
13751 int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
13752 {
13753 	int i, cnt, err;
13754 
13755 	cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
13756 	if (cnt < 0)
13757 		return -errno;
13758 
13759 	for (i = 0; i < cnt; i++) {
13760 		struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
13761 
13762 		err = perf_buffer__process_records(pb, cpu_buf);
13763 		if (err) {
13764 			pr_warn("error while processing records: %s\n", errstr(err));
13765 			return libbpf_err(err);
13766 		}
13767 	}
13768 	return cnt;
13769 }
13770 
13771 /* Return number of PERF_EVENT_ARRAY map slots set up by this perf_buffer
13772  * manager.
13773  */
13774 size_t perf_buffer__buffer_cnt(const struct perf_buffer *pb)
13775 {
13776 	return pb->cpu_cnt;
13777 }
13778 
13779 /*
13780  * Return perf_event FD of a ring buffer in *buf_idx* slot of
13781  * PERF_EVENT_ARRAY BPF map. This FD can be polled for new data using
13782  * select()/poll()/epoll() Linux syscalls.
13783  */
13784 int perf_buffer__buffer_fd(const struct perf_buffer *pb, size_t buf_idx)
13785 {
13786 	struct perf_cpu_buf *cpu_buf;
13787 
13788 	if (buf_idx >= pb->cpu_cnt)
13789 		return libbpf_err(-EINVAL);
13790 
13791 	cpu_buf = pb->cpu_bufs[buf_idx];
13792 	if (!cpu_buf)
13793 		return libbpf_err(-ENOENT);
13794 
13795 	return cpu_buf->fd;
13796 }
13797 
13798 int perf_buffer__buffer(struct perf_buffer *pb, int buf_idx, void **buf, size_t *buf_size)
13799 {
13800 	struct perf_cpu_buf *cpu_buf;
13801 
13802 	if (buf_idx >= pb->cpu_cnt)
13803 		return libbpf_err(-EINVAL);
13804 
13805 	cpu_buf = pb->cpu_bufs[buf_idx];
13806 	if (!cpu_buf)
13807 		return libbpf_err(-ENOENT);
13808 
13809 	*buf = cpu_buf->base;
13810 	*buf_size = pb->mmap_size;
13811 	return 0;
13812 }
13813 
13814 /*
13815  * Consume data from perf ring buffer corresponding to slot *buf_idx* in
13816  * PERF_EVENT_ARRAY BPF map without waiting/polling. If there is no data to
13817  * consume, do nothing and return success.
13818  * Returns:
13819  *   - 0 on success;
13820  *   - <0 on failure.
13821  */
13822 int perf_buffer__consume_buffer(struct perf_buffer *pb, size_t buf_idx)
13823 {
13824 	struct perf_cpu_buf *cpu_buf;
13825 
13826 	if (buf_idx >= pb->cpu_cnt)
13827 		return libbpf_err(-EINVAL);
13828 
13829 	cpu_buf = pb->cpu_bufs[buf_idx];
13830 	if (!cpu_buf)
13831 		return libbpf_err(-ENOENT);
13832 
13833 	return perf_buffer__process_records(pb, cpu_buf);
13834 }
13835 
13836 int perf_buffer__consume(struct perf_buffer *pb)
13837 {
13838 	int i, err;
13839 
13840 	for (i = 0; i < pb->cpu_cnt; i++) {
13841 		struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
13842 
13843 		if (!cpu_buf)
13844 			continue;
13845 
13846 		err = perf_buffer__process_records(pb, cpu_buf);
13847 		if (err) {
13848 			pr_warn("perf_buffer: failed to process records in buffer #%d: %s\n",
13849 				i, errstr(err));
13850 			return libbpf_err(err);
13851 		}
13852 	}
13853 	return 0;
13854 }
13855 
13856 int bpf_program__set_attach_target(struct bpf_program *prog,
13857 				   int attach_prog_fd,
13858 				   const char *attach_func_name)
13859 {
13860 	int btf_obj_fd = 0, btf_id = 0, err;
13861 
13862 	if (!prog || attach_prog_fd < 0)
13863 		return libbpf_err(-EINVAL);
13864 
13865 	if (prog->obj->state >= OBJ_LOADED)
13866 		return libbpf_err(-EINVAL);
13867 
13868 	if (attach_prog_fd && !attach_func_name) {
13869 		/* remember attach_prog_fd and let bpf_program__load() find
13870 		 * BTF ID during the program load
13871 		 */
13872 		prog->attach_prog_fd = attach_prog_fd;
13873 		return 0;
13874 	}
13875 
13876 	if (attach_prog_fd) {
13877 		btf_id = libbpf_find_prog_btf_id(attach_func_name,
13878 						 attach_prog_fd, prog->obj->token_fd);
13879 		if (btf_id < 0)
13880 			return libbpf_err(btf_id);
13881 	} else {
13882 		if (!attach_func_name)
13883 			return libbpf_err(-EINVAL);
13884 
13885 		/* load btf_vmlinux, if not yet */
13886 		err = bpf_object__load_vmlinux_btf(prog->obj, true);
13887 		if (err)
13888 			return libbpf_err(err);
13889 		err = find_kernel_btf_id(prog->obj, attach_func_name,
13890 					 prog->expected_attach_type,
13891 					 &btf_obj_fd, &btf_id);
13892 		if (err)
13893 			return libbpf_err(err);
13894 	}
13895 
13896 	prog->attach_btf_id = btf_id;
13897 	prog->attach_btf_obj_fd = btf_obj_fd;
13898 	prog->attach_prog_fd = attach_prog_fd;
13899 	return 0;
13900 }
13901 
13902 int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz)
13903 {
13904 	int err = 0, n, len, start, end = -1;
13905 	bool *tmp;
13906 
13907 	*mask = NULL;
13908 	*mask_sz = 0;
13909 
13910 	/* Each sub string separated by ',' has format \d+-\d+ or \d+ */
13911 	while (*s) {
13912 		if (*s == ',' || *s == '\n') {
13913 			s++;
13914 			continue;
13915 		}
13916 		n = sscanf(s, "%d%n-%d%n", &start, &len, &end, &len);
13917 		if (n <= 0 || n > 2) {
13918 			pr_warn("Failed to get CPU range %s: %d\n", s, n);
13919 			err = -EINVAL;
13920 			goto cleanup;
13921 		} else if (n == 1) {
13922 			end = start;
13923 		}
13924 		if (start < 0 || start > end) {
13925 			pr_warn("Invalid CPU range [%d,%d] in %s\n",
13926 				start, end, s);
13927 			err = -EINVAL;
13928 			goto cleanup;
13929 		}
13930 		tmp = realloc(*mask, end + 1);
13931 		if (!tmp) {
13932 			err = -ENOMEM;
13933 			goto cleanup;
13934 		}
13935 		*mask = tmp;
13936 		memset(tmp + *mask_sz, 0, start - *mask_sz);
13937 		memset(tmp + start, 1, end - start + 1);
13938 		*mask_sz = end + 1;
13939 		s += len;
13940 	}
13941 	if (!*mask_sz) {
13942 		pr_warn("Empty CPU range\n");
13943 		return -EINVAL;
13944 	}
13945 	return 0;
13946 cleanup:
13947 	free(*mask);
13948 	*mask = NULL;
13949 	return err;
13950 }
13951 
13952 int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz)
13953 {
13954 	int fd, err = 0, len;
13955 	char buf[128];
13956 
13957 	fd = open(fcpu, O_RDONLY | O_CLOEXEC);
13958 	if (fd < 0) {
13959 		err = -errno;
13960 		pr_warn("Failed to open cpu mask file %s: %s\n", fcpu, errstr(err));
13961 		return err;
13962 	}
13963 	len = read(fd, buf, sizeof(buf));
13964 	close(fd);
13965 	if (len <= 0) {
13966 		err = len ? -errno : -EINVAL;
13967 		pr_warn("Failed to read cpu mask from %s: %s\n", fcpu, errstr(err));
13968 		return err;
13969 	}
13970 	if (len >= sizeof(buf)) {
13971 		pr_warn("CPU mask is too big in file %s\n", fcpu);
13972 		return -E2BIG;
13973 	}
13974 	buf[len] = '\0';
13975 
13976 	return parse_cpu_mask_str(buf, mask, mask_sz);
13977 }
13978 
13979 int libbpf_num_possible_cpus(void)
13980 {
13981 	static const char *fcpu = "/sys/devices/system/cpu/possible";
13982 	static int cpus;
13983 	int err, n, i, tmp_cpus;
13984 	bool *mask;
13985 
13986 	tmp_cpus = READ_ONCE(cpus);
13987 	if (tmp_cpus > 0)
13988 		return tmp_cpus;
13989 
13990 	err = parse_cpu_mask_file(fcpu, &mask, &n);
13991 	if (err)
13992 		return libbpf_err(err);
13993 
13994 	tmp_cpus = 0;
13995 	for (i = 0; i < n; i++) {
13996 		if (mask[i])
13997 			tmp_cpus++;
13998 	}
13999 	free(mask);
14000 
14001 	WRITE_ONCE(cpus, tmp_cpus);
14002 	return tmp_cpus;
14003 }
14004 
14005 static int populate_skeleton_maps(const struct bpf_object *obj,
14006 				  struct bpf_map_skeleton *maps,
14007 				  size_t map_cnt, size_t map_skel_sz)
14008 {
14009 	int i;
14010 
14011 	for (i = 0; i < map_cnt; i++) {
14012 		struct bpf_map_skeleton *map_skel = (void *)maps + i * map_skel_sz;
14013 		struct bpf_map **map = map_skel->map;
14014 		const char *name = map_skel->name;
14015 		void **mmaped = map_skel->mmaped;
14016 
14017 		*map = bpf_object__find_map_by_name(obj, name);
14018 		if (!*map) {
14019 			pr_warn("failed to find skeleton map '%s'\n", name);
14020 			return -ESRCH;
14021 		}
14022 
14023 		/* externs shouldn't be pre-setup from user code */
14024 		if (mmaped && (*map)->libbpf_type != LIBBPF_MAP_KCONFIG)
14025 			*mmaped = (*map)->mmaped;
14026 	}
14027 	return 0;
14028 }
14029 
14030 static int populate_skeleton_progs(const struct bpf_object *obj,
14031 				   struct bpf_prog_skeleton *progs,
14032 				   size_t prog_cnt, size_t prog_skel_sz)
14033 {
14034 	int i;
14035 
14036 	for (i = 0; i < prog_cnt; i++) {
14037 		struct bpf_prog_skeleton *prog_skel = (void *)progs + i * prog_skel_sz;
14038 		struct bpf_program **prog = prog_skel->prog;
14039 		const char *name = prog_skel->name;
14040 
14041 		*prog = bpf_object__find_program_by_name(obj, name);
14042 		if (!*prog) {
14043 			pr_warn("failed to find skeleton program '%s'\n", name);
14044 			return -ESRCH;
14045 		}
14046 	}
14047 	return 0;
14048 }
14049 
14050 int bpf_object__open_skeleton(struct bpf_object_skeleton *s,
14051 			      const struct bpf_object_open_opts *opts)
14052 {
14053 	struct bpf_object *obj;
14054 	int err;
14055 
14056 	obj = bpf_object_open(NULL, s->data, s->data_sz, s->name, opts);
14057 	if (IS_ERR(obj)) {
14058 		err = PTR_ERR(obj);
14059 		pr_warn("failed to initialize skeleton BPF object '%s': %s\n",
14060 			s->name, errstr(err));
14061 		return libbpf_err(err);
14062 	}
14063 
14064 	*s->obj = obj;
14065 	err = populate_skeleton_maps(obj, s->maps, s->map_cnt, s->map_skel_sz);
14066 	if (err) {
14067 		pr_warn("failed to populate skeleton maps for '%s': %s\n", s->name, errstr(err));
14068 		return libbpf_err(err);
14069 	}
14070 
14071 	err = populate_skeleton_progs(obj, s->progs, s->prog_cnt, s->prog_skel_sz);
14072 	if (err) {
14073 		pr_warn("failed to populate skeleton progs for '%s': %s\n", s->name, errstr(err));
14074 		return libbpf_err(err);
14075 	}
14076 
14077 	return 0;
14078 }
14079 
14080 int bpf_object__open_subskeleton(struct bpf_object_subskeleton *s)
14081 {
14082 	int err, len, var_idx, i;
14083 	const char *var_name;
14084 	const struct bpf_map *map;
14085 	struct btf *btf;
14086 	__u32 map_type_id;
14087 	const struct btf_type *map_type, *var_type;
14088 	const struct bpf_var_skeleton *var_skel;
14089 	struct btf_var_secinfo *var;
14090 
14091 	if (!s->obj)
14092 		return libbpf_err(-EINVAL);
14093 
14094 	btf = bpf_object__btf(s->obj);
14095 	if (!btf) {
14096 		pr_warn("subskeletons require BTF at runtime (object %s)\n",
14097 			bpf_object__name(s->obj));
14098 		return libbpf_err(-errno);
14099 	}
14100 
14101 	err = populate_skeleton_maps(s->obj, s->maps, s->map_cnt, s->map_skel_sz);
14102 	if (err) {
14103 		pr_warn("failed to populate subskeleton maps: %s\n", errstr(err));
14104 		return libbpf_err(err);
14105 	}
14106 
14107 	err = populate_skeleton_progs(s->obj, s->progs, s->prog_cnt, s->prog_skel_sz);
14108 	if (err) {
14109 		pr_warn("failed to populate subskeleton maps: %s\n", errstr(err));
14110 		return libbpf_err(err);
14111 	}
14112 
14113 	for (var_idx = 0; var_idx < s->var_cnt; var_idx++) {
14114 		var_skel = (void *)s->vars + var_idx * s->var_skel_sz;
14115 		map = *var_skel->map;
14116 		map_type_id = bpf_map__btf_value_type_id(map);
14117 		map_type = btf__type_by_id(btf, map_type_id);
14118 
14119 		if (!btf_is_datasec(map_type)) {
14120 			pr_warn("type for map '%1$s' is not a datasec: %2$s\n",
14121 				bpf_map__name(map),
14122 				__btf_kind_str(btf_kind(map_type)));
14123 			return libbpf_err(-EINVAL);
14124 		}
14125 
14126 		len = btf_vlen(map_type);
14127 		var = btf_var_secinfos(map_type);
14128 		for (i = 0; i < len; i++, var++) {
14129 			var_type = btf__type_by_id(btf, var->type);
14130 			var_name = btf__name_by_offset(btf, var_type->name_off);
14131 			if (strcmp(var_name, var_skel->name) == 0) {
14132 				*var_skel->addr = map->mmaped + var->offset;
14133 				break;
14134 			}
14135 		}
14136 	}
14137 	return 0;
14138 }
14139 
14140 void bpf_object__destroy_subskeleton(struct bpf_object_subskeleton *s)
14141 {
14142 	if (!s)
14143 		return;
14144 	free(s->maps);
14145 	free(s->progs);
14146 	free(s->vars);
14147 	free(s);
14148 }
14149 
14150 int bpf_object__load_skeleton(struct bpf_object_skeleton *s)
14151 {
14152 	int i, err;
14153 
14154 	err = bpf_object__load(*s->obj);
14155 	if (err) {
14156 		pr_warn("failed to load BPF skeleton '%s': %s\n", s->name, errstr(err));
14157 		return libbpf_err(err);
14158 	}
14159 
14160 	for (i = 0; i < s->map_cnt; i++) {
14161 		struct bpf_map_skeleton *map_skel = (void *)s->maps + i * s->map_skel_sz;
14162 		struct bpf_map *map = *map_skel->map;
14163 
14164 		if (!map_skel->mmaped)
14165 			continue;
14166 
14167 		*map_skel->mmaped = map->mmaped;
14168 	}
14169 
14170 	return 0;
14171 }
14172 
14173 int bpf_object__attach_skeleton(struct bpf_object_skeleton *s)
14174 {
14175 	int i, err;
14176 
14177 	for (i = 0; i < s->prog_cnt; i++) {
14178 		struct bpf_prog_skeleton *prog_skel = (void *)s->progs + i * s->prog_skel_sz;
14179 		struct bpf_program *prog = *prog_skel->prog;
14180 		struct bpf_link **link = prog_skel->link;
14181 
14182 		if (!prog->autoload || !prog->autoattach)
14183 			continue;
14184 
14185 		/* auto-attaching not supported for this program */
14186 		if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
14187 			continue;
14188 
14189 		/* if user already set the link manually, don't attempt auto-attach */
14190 		if (*link)
14191 			continue;
14192 
14193 		err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, link);
14194 		if (err) {
14195 			pr_warn("prog '%s': failed to auto-attach: %s\n",
14196 				bpf_program__name(prog), errstr(err));
14197 			return libbpf_err(err);
14198 		}
14199 
14200 		/* It's possible that for some SEC() definitions auto-attach
14201 		 * is supported in some cases (e.g., if definition completely
14202 		 * specifies target information), but is not in other cases.
14203 		 * SEC("uprobe") is one such case. If user specified target
14204 		 * binary and function name, such BPF program can be
14205 		 * auto-attached. But if not, it shouldn't trigger skeleton's
14206 		 * attach to fail. It should just be skipped.
14207 		 * attach_fn signals such case with returning 0 (no error) and
14208 		 * setting link to NULL.
14209 		 */
14210 	}
14211 
14212 
14213 	for (i = 0; i < s->map_cnt; i++) {
14214 		struct bpf_map_skeleton *map_skel = (void *)s->maps + i * s->map_skel_sz;
14215 		struct bpf_map *map = *map_skel->map;
14216 		struct bpf_link **link;
14217 
14218 		if (!map->autocreate || !map->autoattach)
14219 			continue;
14220 
14221 		/* only struct_ops maps can be attached */
14222 		if (!bpf_map__is_struct_ops(map))
14223 			continue;
14224 
14225 		/* skeleton is created with earlier version of bpftool, notify user */
14226 		if (s->map_skel_sz < offsetofend(struct bpf_map_skeleton, link)) {
14227 			pr_warn("map '%s': BPF skeleton version is old, skipping map auto-attachment...\n",
14228 				bpf_map__name(map));
14229 			continue;
14230 		}
14231 
14232 		link = map_skel->link;
14233 		if (!link) {
14234 			pr_warn("map '%s': BPF map skeleton link is uninitialized\n",
14235 				bpf_map__name(map));
14236 			continue;
14237 		}
14238 
14239 		if (*link)
14240 			continue;
14241 
14242 		*link = bpf_map__attach_struct_ops(map);
14243 		if (!*link) {
14244 			err = -errno;
14245 			pr_warn("map '%s': failed to auto-attach: %s\n",
14246 				bpf_map__name(map), errstr(err));
14247 			return libbpf_err(err);
14248 		}
14249 	}
14250 
14251 	return 0;
14252 }
14253 
14254 void bpf_object__detach_skeleton(struct bpf_object_skeleton *s)
14255 {
14256 	int i;
14257 
14258 	for (i = 0; i < s->prog_cnt; i++) {
14259 		struct bpf_prog_skeleton *prog_skel = (void *)s->progs + i * s->prog_skel_sz;
14260 		struct bpf_link **link = prog_skel->link;
14261 
14262 		bpf_link__destroy(*link);
14263 		*link = NULL;
14264 	}
14265 
14266 	if (s->map_skel_sz < sizeof(struct bpf_map_skeleton))
14267 		return;
14268 
14269 	for (i = 0; i < s->map_cnt; i++) {
14270 		struct bpf_map_skeleton *map_skel = (void *)s->maps + i * s->map_skel_sz;
14271 		struct bpf_link **link = map_skel->link;
14272 
14273 		if (link) {
14274 			bpf_link__destroy(*link);
14275 			*link = NULL;
14276 		}
14277 	}
14278 }
14279 
14280 void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s)
14281 {
14282 	if (!s)
14283 		return;
14284 
14285 	bpf_object__detach_skeleton(s);
14286 	if (s->obj)
14287 		bpf_object__close(*s->obj);
14288 	free(s->maps);
14289 	free(s->progs);
14290 	free(s);
14291 }
14292 
14293 int libbpf_sha256(const void *data, size_t data_sz, void *sha_out, size_t sha_out_sz)
14294 {
14295 	struct sockaddr_alg sa = {
14296 		.salg_family = AF_ALG,
14297 		.salg_type   = "hash",
14298 		.salg_name   = "sha256"
14299 	};
14300 	int sock_fd = -1;
14301 	int op_fd = -1;
14302 	int err = 0;
14303 
14304 	if (sha_out_sz != SHA256_DIGEST_LENGTH) {
14305 		pr_warn("sha_out_sz should be exactly 32 bytes for a SHA256 digest");
14306 		return -EINVAL;
14307 	}
14308 
14309 	sock_fd = socket(AF_ALG, SOCK_SEQPACKET, 0);
14310 	if (sock_fd < 0) {
14311 		err = -errno;
14312 		pr_warn("failed to create AF_ALG socket for SHA256: %s\n", errstr(err));
14313 		return err;
14314 	}
14315 
14316 	if (bind(sock_fd, (struct sockaddr *)&sa, sizeof(sa)) < 0) {
14317 		err = -errno;
14318 		pr_warn("failed to bind to AF_ALG socket for SHA256: %s\n", errstr(err));
14319 		goto out;
14320 	}
14321 
14322 	op_fd = accept(sock_fd, NULL, 0);
14323 	if (op_fd < 0) {
14324 		err = -errno;
14325 		pr_warn("failed to accept from AF_ALG socket for SHA256: %s\n", errstr(err));
14326 		goto out;
14327 	}
14328 
14329 	if (write(op_fd, data, data_sz) != data_sz) {
14330 		err = -errno;
14331 		pr_warn("failed to write data to AF_ALG socket for SHA256: %s\n", errstr(err));
14332 		goto out;
14333 	}
14334 
14335 	if (read(op_fd, sha_out, SHA256_DIGEST_LENGTH) != SHA256_DIGEST_LENGTH) {
14336 		err = -errno;
14337 		pr_warn("failed to read SHA256 from AF_ALG socket: %s\n", errstr(err));
14338 		goto out;
14339 	}
14340 
14341 out:
14342 	if (op_fd >= 0)
14343 		close(op_fd);
14344 	if (sock_fd >= 0)
14345 		close(sock_fd);
14346 	return err;
14347 }
14348