xref: /openbmc/linux/tools/lib/bpf/libbpf.c (revision 801b27e8)
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/ring_buffer.h>
37 #include <sys/epoll.h>
38 #include <sys/ioctl.h>
39 #include <sys/mman.h>
40 #include <sys/stat.h>
41 #include <sys/types.h>
42 #include <sys/vfs.h>
43 #include <sys/utsname.h>
44 #include <sys/resource.h>
45 #include <libelf.h>
46 #include <gelf.h>
47 #include <zlib.h>
48 
49 #include "libbpf.h"
50 #include "bpf.h"
51 #include "btf.h"
52 #include "str_error.h"
53 #include "libbpf_internal.h"
54 #include "hashmap.h"
55 #include "bpf_gen_internal.h"
56 #include "zip.h"
57 
58 #ifndef BPF_FS_MAGIC
59 #define BPF_FS_MAGIC		0xcafe4a11
60 #endif
61 
62 #define BPF_INSN_SZ (sizeof(struct bpf_insn))
63 
64 /* vsprintf() in __base_pr() uses nonliteral format string. It may break
65  * compilation if user enables corresponding warning. Disable it explicitly.
66  */
67 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
68 
69 #define __printf(a, b)	__attribute__((format(printf, a, b)))
70 
71 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj);
72 static bool prog_is_subprog(const struct bpf_object *obj, const struct bpf_program *prog);
73 
74 static const char * const attach_type_name[] = {
75 	[BPF_CGROUP_INET_INGRESS]	= "cgroup_inet_ingress",
76 	[BPF_CGROUP_INET_EGRESS]	= "cgroup_inet_egress",
77 	[BPF_CGROUP_INET_SOCK_CREATE]	= "cgroup_inet_sock_create",
78 	[BPF_CGROUP_INET_SOCK_RELEASE]	= "cgroup_inet_sock_release",
79 	[BPF_CGROUP_SOCK_OPS]		= "cgroup_sock_ops",
80 	[BPF_CGROUP_DEVICE]		= "cgroup_device",
81 	[BPF_CGROUP_INET4_BIND]		= "cgroup_inet4_bind",
82 	[BPF_CGROUP_INET6_BIND]		= "cgroup_inet6_bind",
83 	[BPF_CGROUP_INET4_CONNECT]	= "cgroup_inet4_connect",
84 	[BPF_CGROUP_INET6_CONNECT]	= "cgroup_inet6_connect",
85 	[BPF_CGROUP_INET4_POST_BIND]	= "cgroup_inet4_post_bind",
86 	[BPF_CGROUP_INET6_POST_BIND]	= "cgroup_inet6_post_bind",
87 	[BPF_CGROUP_INET4_GETPEERNAME]	= "cgroup_inet4_getpeername",
88 	[BPF_CGROUP_INET6_GETPEERNAME]	= "cgroup_inet6_getpeername",
89 	[BPF_CGROUP_INET4_GETSOCKNAME]	= "cgroup_inet4_getsockname",
90 	[BPF_CGROUP_INET6_GETSOCKNAME]	= "cgroup_inet6_getsockname",
91 	[BPF_CGROUP_UDP4_SENDMSG]	= "cgroup_udp4_sendmsg",
92 	[BPF_CGROUP_UDP6_SENDMSG]	= "cgroup_udp6_sendmsg",
93 	[BPF_CGROUP_SYSCTL]		= "cgroup_sysctl",
94 	[BPF_CGROUP_UDP4_RECVMSG]	= "cgroup_udp4_recvmsg",
95 	[BPF_CGROUP_UDP6_RECVMSG]	= "cgroup_udp6_recvmsg",
96 	[BPF_CGROUP_GETSOCKOPT]		= "cgroup_getsockopt",
97 	[BPF_CGROUP_SETSOCKOPT]		= "cgroup_setsockopt",
98 	[BPF_SK_SKB_STREAM_PARSER]	= "sk_skb_stream_parser",
99 	[BPF_SK_SKB_STREAM_VERDICT]	= "sk_skb_stream_verdict",
100 	[BPF_SK_SKB_VERDICT]		= "sk_skb_verdict",
101 	[BPF_SK_MSG_VERDICT]		= "sk_msg_verdict",
102 	[BPF_LIRC_MODE2]		= "lirc_mode2",
103 	[BPF_FLOW_DISSECTOR]		= "flow_dissector",
104 	[BPF_TRACE_RAW_TP]		= "trace_raw_tp",
105 	[BPF_TRACE_FENTRY]		= "trace_fentry",
106 	[BPF_TRACE_FEXIT]		= "trace_fexit",
107 	[BPF_MODIFY_RETURN]		= "modify_return",
108 	[BPF_LSM_MAC]			= "lsm_mac",
109 	[BPF_LSM_CGROUP]		= "lsm_cgroup",
110 	[BPF_SK_LOOKUP]			= "sk_lookup",
111 	[BPF_TRACE_ITER]		= "trace_iter",
112 	[BPF_XDP_DEVMAP]		= "xdp_devmap",
113 	[BPF_XDP_CPUMAP]		= "xdp_cpumap",
114 	[BPF_XDP]			= "xdp",
115 	[BPF_SK_REUSEPORT_SELECT]	= "sk_reuseport_select",
116 	[BPF_SK_REUSEPORT_SELECT_OR_MIGRATE]	= "sk_reuseport_select_or_migrate",
117 	[BPF_PERF_EVENT]		= "perf_event",
118 	[BPF_TRACE_KPROBE_MULTI]	= "trace_kprobe_multi",
119 	[BPF_STRUCT_OPS]		= "struct_ops",
120 	[BPF_NETFILTER]			= "netfilter",
121 	[BPF_TCX_INGRESS]		= "tcx_ingress",
122 	[BPF_TCX_EGRESS]		= "tcx_egress",
123 };
124 
125 static const char * const link_type_name[] = {
126 	[BPF_LINK_TYPE_UNSPEC]			= "unspec",
127 	[BPF_LINK_TYPE_RAW_TRACEPOINT]		= "raw_tracepoint",
128 	[BPF_LINK_TYPE_TRACING]			= "tracing",
129 	[BPF_LINK_TYPE_CGROUP]			= "cgroup",
130 	[BPF_LINK_TYPE_ITER]			= "iter",
131 	[BPF_LINK_TYPE_NETNS]			= "netns",
132 	[BPF_LINK_TYPE_XDP]			= "xdp",
133 	[BPF_LINK_TYPE_PERF_EVENT]		= "perf_event",
134 	[BPF_LINK_TYPE_KPROBE_MULTI]		= "kprobe_multi",
135 	[BPF_LINK_TYPE_STRUCT_OPS]		= "struct_ops",
136 	[BPF_LINK_TYPE_NETFILTER]		= "netfilter",
137 	[BPF_LINK_TYPE_TCX]			= "tcx",
138 };
139 
140 static const char * const map_type_name[] = {
141 	[BPF_MAP_TYPE_UNSPEC]			= "unspec",
142 	[BPF_MAP_TYPE_HASH]			= "hash",
143 	[BPF_MAP_TYPE_ARRAY]			= "array",
144 	[BPF_MAP_TYPE_PROG_ARRAY]		= "prog_array",
145 	[BPF_MAP_TYPE_PERF_EVENT_ARRAY]		= "perf_event_array",
146 	[BPF_MAP_TYPE_PERCPU_HASH]		= "percpu_hash",
147 	[BPF_MAP_TYPE_PERCPU_ARRAY]		= "percpu_array",
148 	[BPF_MAP_TYPE_STACK_TRACE]		= "stack_trace",
149 	[BPF_MAP_TYPE_CGROUP_ARRAY]		= "cgroup_array",
150 	[BPF_MAP_TYPE_LRU_HASH]			= "lru_hash",
151 	[BPF_MAP_TYPE_LRU_PERCPU_HASH]		= "lru_percpu_hash",
152 	[BPF_MAP_TYPE_LPM_TRIE]			= "lpm_trie",
153 	[BPF_MAP_TYPE_ARRAY_OF_MAPS]		= "array_of_maps",
154 	[BPF_MAP_TYPE_HASH_OF_MAPS]		= "hash_of_maps",
155 	[BPF_MAP_TYPE_DEVMAP]			= "devmap",
156 	[BPF_MAP_TYPE_DEVMAP_HASH]		= "devmap_hash",
157 	[BPF_MAP_TYPE_SOCKMAP]			= "sockmap",
158 	[BPF_MAP_TYPE_CPUMAP]			= "cpumap",
159 	[BPF_MAP_TYPE_XSKMAP]			= "xskmap",
160 	[BPF_MAP_TYPE_SOCKHASH]			= "sockhash",
161 	[BPF_MAP_TYPE_CGROUP_STORAGE]		= "cgroup_storage",
162 	[BPF_MAP_TYPE_REUSEPORT_SOCKARRAY]	= "reuseport_sockarray",
163 	[BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE]	= "percpu_cgroup_storage",
164 	[BPF_MAP_TYPE_QUEUE]			= "queue",
165 	[BPF_MAP_TYPE_STACK]			= "stack",
166 	[BPF_MAP_TYPE_SK_STORAGE]		= "sk_storage",
167 	[BPF_MAP_TYPE_STRUCT_OPS]		= "struct_ops",
168 	[BPF_MAP_TYPE_RINGBUF]			= "ringbuf",
169 	[BPF_MAP_TYPE_INODE_STORAGE]		= "inode_storage",
170 	[BPF_MAP_TYPE_TASK_STORAGE]		= "task_storage",
171 	[BPF_MAP_TYPE_BLOOM_FILTER]		= "bloom_filter",
172 	[BPF_MAP_TYPE_USER_RINGBUF]             = "user_ringbuf",
173 	[BPF_MAP_TYPE_CGRP_STORAGE]		= "cgrp_storage",
174 };
175 
176 static const char * const prog_type_name[] = {
177 	[BPF_PROG_TYPE_UNSPEC]			= "unspec",
178 	[BPF_PROG_TYPE_SOCKET_FILTER]		= "socket_filter",
179 	[BPF_PROG_TYPE_KPROBE]			= "kprobe",
180 	[BPF_PROG_TYPE_SCHED_CLS]		= "sched_cls",
181 	[BPF_PROG_TYPE_SCHED_ACT]		= "sched_act",
182 	[BPF_PROG_TYPE_TRACEPOINT]		= "tracepoint",
183 	[BPF_PROG_TYPE_XDP]			= "xdp",
184 	[BPF_PROG_TYPE_PERF_EVENT]		= "perf_event",
185 	[BPF_PROG_TYPE_CGROUP_SKB]		= "cgroup_skb",
186 	[BPF_PROG_TYPE_CGROUP_SOCK]		= "cgroup_sock",
187 	[BPF_PROG_TYPE_LWT_IN]			= "lwt_in",
188 	[BPF_PROG_TYPE_LWT_OUT]			= "lwt_out",
189 	[BPF_PROG_TYPE_LWT_XMIT]		= "lwt_xmit",
190 	[BPF_PROG_TYPE_SOCK_OPS]		= "sock_ops",
191 	[BPF_PROG_TYPE_SK_SKB]			= "sk_skb",
192 	[BPF_PROG_TYPE_CGROUP_DEVICE]		= "cgroup_device",
193 	[BPF_PROG_TYPE_SK_MSG]			= "sk_msg",
194 	[BPF_PROG_TYPE_RAW_TRACEPOINT]		= "raw_tracepoint",
195 	[BPF_PROG_TYPE_CGROUP_SOCK_ADDR]	= "cgroup_sock_addr",
196 	[BPF_PROG_TYPE_LWT_SEG6LOCAL]		= "lwt_seg6local",
197 	[BPF_PROG_TYPE_LIRC_MODE2]		= "lirc_mode2",
198 	[BPF_PROG_TYPE_SK_REUSEPORT]		= "sk_reuseport",
199 	[BPF_PROG_TYPE_FLOW_DISSECTOR]		= "flow_dissector",
200 	[BPF_PROG_TYPE_CGROUP_SYSCTL]		= "cgroup_sysctl",
201 	[BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE]	= "raw_tracepoint_writable",
202 	[BPF_PROG_TYPE_CGROUP_SOCKOPT]		= "cgroup_sockopt",
203 	[BPF_PROG_TYPE_TRACING]			= "tracing",
204 	[BPF_PROG_TYPE_STRUCT_OPS]		= "struct_ops",
205 	[BPF_PROG_TYPE_EXT]			= "ext",
206 	[BPF_PROG_TYPE_LSM]			= "lsm",
207 	[BPF_PROG_TYPE_SK_LOOKUP]		= "sk_lookup",
208 	[BPF_PROG_TYPE_SYSCALL]			= "syscall",
209 	[BPF_PROG_TYPE_NETFILTER]		= "netfilter",
210 };
211 
212 static int __base_pr(enum libbpf_print_level level, const char *format,
213 		     va_list args)
214 {
215 	if (level == LIBBPF_DEBUG)
216 		return 0;
217 
218 	return vfprintf(stderr, format, args);
219 }
220 
221 static libbpf_print_fn_t __libbpf_pr = __base_pr;
222 
223 libbpf_print_fn_t libbpf_set_print(libbpf_print_fn_t fn)
224 {
225 	libbpf_print_fn_t old_print_fn;
226 
227 	old_print_fn = __atomic_exchange_n(&__libbpf_pr, fn, __ATOMIC_RELAXED);
228 
229 	return old_print_fn;
230 }
231 
232 __printf(2, 3)
233 void libbpf_print(enum libbpf_print_level level, const char *format, ...)
234 {
235 	va_list args;
236 	int old_errno;
237 	libbpf_print_fn_t print_fn;
238 
239 	print_fn = __atomic_load_n(&__libbpf_pr, __ATOMIC_RELAXED);
240 	if (!print_fn)
241 		return;
242 
243 	old_errno = errno;
244 
245 	va_start(args, format);
246 	__libbpf_pr(level, format, args);
247 	va_end(args);
248 
249 	errno = old_errno;
250 }
251 
252 static void pr_perm_msg(int err)
253 {
254 	struct rlimit limit;
255 	char buf[100];
256 
257 	if (err != -EPERM || geteuid() != 0)
258 		return;
259 
260 	err = getrlimit(RLIMIT_MEMLOCK, &limit);
261 	if (err)
262 		return;
263 
264 	if (limit.rlim_cur == RLIM_INFINITY)
265 		return;
266 
267 	if (limit.rlim_cur < 1024)
268 		snprintf(buf, sizeof(buf), "%zu bytes", (size_t)limit.rlim_cur);
269 	else if (limit.rlim_cur < 1024*1024)
270 		snprintf(buf, sizeof(buf), "%.1f KiB", (double)limit.rlim_cur / 1024);
271 	else
272 		snprintf(buf, sizeof(buf), "%.1f MiB", (double)limit.rlim_cur / (1024*1024));
273 
274 	pr_warn("permission error while running as root; try raising 'ulimit -l'? current value: %s\n",
275 		buf);
276 }
277 
278 #define STRERR_BUFSIZE  128
279 
280 /* Copied from tools/perf/util/util.h */
281 #ifndef zfree
282 # define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
283 #endif
284 
285 #ifndef zclose
286 # define zclose(fd) ({			\
287 	int ___err = 0;			\
288 	if ((fd) >= 0)			\
289 		___err = close((fd));	\
290 	fd = -1;			\
291 	___err; })
292 #endif
293 
294 static inline __u64 ptr_to_u64(const void *ptr)
295 {
296 	return (__u64) (unsigned long) ptr;
297 }
298 
299 int libbpf_set_strict_mode(enum libbpf_strict_mode mode)
300 {
301 	/* as of v1.0 libbpf_set_strict_mode() is a no-op */
302 	return 0;
303 }
304 
305 __u32 libbpf_major_version(void)
306 {
307 	return LIBBPF_MAJOR_VERSION;
308 }
309 
310 __u32 libbpf_minor_version(void)
311 {
312 	return LIBBPF_MINOR_VERSION;
313 }
314 
315 const char *libbpf_version_string(void)
316 {
317 #define __S(X) #X
318 #define _S(X) __S(X)
319 	return  "v" _S(LIBBPF_MAJOR_VERSION) "." _S(LIBBPF_MINOR_VERSION);
320 #undef _S
321 #undef __S
322 }
323 
324 enum reloc_type {
325 	RELO_LD64,
326 	RELO_CALL,
327 	RELO_DATA,
328 	RELO_EXTERN_LD64,
329 	RELO_EXTERN_CALL,
330 	RELO_SUBPROG_ADDR,
331 	RELO_CORE,
332 };
333 
334 struct reloc_desc {
335 	enum reloc_type type;
336 	int insn_idx;
337 	union {
338 		const struct bpf_core_relo *core_relo; /* used when type == RELO_CORE */
339 		struct {
340 			int map_idx;
341 			int sym_off;
342 			int ext_idx;
343 		};
344 	};
345 };
346 
347 /* stored as sec_def->cookie for all libbpf-supported SEC()s */
348 enum sec_def_flags {
349 	SEC_NONE = 0,
350 	/* expected_attach_type is optional, if kernel doesn't support that */
351 	SEC_EXP_ATTACH_OPT = 1,
352 	/* legacy, only used by libbpf_get_type_names() and
353 	 * libbpf_attach_type_by_name(), not used by libbpf itself at all.
354 	 * This used to be associated with cgroup (and few other) BPF programs
355 	 * that were attachable through BPF_PROG_ATTACH command. Pretty
356 	 * meaningless nowadays, though.
357 	 */
358 	SEC_ATTACHABLE = 2,
359 	SEC_ATTACHABLE_OPT = SEC_ATTACHABLE | SEC_EXP_ATTACH_OPT,
360 	/* attachment target is specified through BTF ID in either kernel or
361 	 * other BPF program's BTF object
362 	 */
363 	SEC_ATTACH_BTF = 4,
364 	/* BPF program type allows sleeping/blocking in kernel */
365 	SEC_SLEEPABLE = 8,
366 	/* BPF program support non-linear XDP buffer */
367 	SEC_XDP_FRAGS = 16,
368 };
369 
370 struct bpf_sec_def {
371 	char *sec;
372 	enum bpf_prog_type prog_type;
373 	enum bpf_attach_type expected_attach_type;
374 	long cookie;
375 	int handler_id;
376 
377 	libbpf_prog_setup_fn_t prog_setup_fn;
378 	libbpf_prog_prepare_load_fn_t prog_prepare_load_fn;
379 	libbpf_prog_attach_fn_t prog_attach_fn;
380 };
381 
382 /*
383  * bpf_prog should be a better name but it has been used in
384  * linux/filter.h.
385  */
386 struct bpf_program {
387 	char *name;
388 	char *sec_name;
389 	size_t sec_idx;
390 	const struct bpf_sec_def *sec_def;
391 	/* this program's instruction offset (in number of instructions)
392 	 * within its containing ELF section
393 	 */
394 	size_t sec_insn_off;
395 	/* number of original instructions in ELF section belonging to this
396 	 * program, not taking into account subprogram instructions possible
397 	 * appended later during relocation
398 	 */
399 	size_t sec_insn_cnt;
400 	/* Offset (in number of instructions) of the start of instruction
401 	 * belonging to this BPF program  within its containing main BPF
402 	 * program. For the entry-point (main) BPF program, this is always
403 	 * zero. For a sub-program, this gets reset before each of main BPF
404 	 * programs are processed and relocated and is used to determined
405 	 * whether sub-program was already appended to the main program, and
406 	 * if yes, at which instruction offset.
407 	 */
408 	size_t sub_insn_off;
409 
410 	/* instructions that belong to BPF program; insns[0] is located at
411 	 * sec_insn_off instruction within its ELF section in ELF file, so
412 	 * when mapping ELF file instruction index to the local instruction,
413 	 * one needs to subtract sec_insn_off; and vice versa.
414 	 */
415 	struct bpf_insn *insns;
416 	/* actual number of instruction in this BPF program's image; for
417 	 * entry-point BPF programs this includes the size of main program
418 	 * itself plus all the used sub-programs, appended at the end
419 	 */
420 	size_t insns_cnt;
421 
422 	struct reloc_desc *reloc_desc;
423 	int nr_reloc;
424 
425 	/* BPF verifier log settings */
426 	char *log_buf;
427 	size_t log_size;
428 	__u32 log_level;
429 
430 	struct bpf_object *obj;
431 
432 	int fd;
433 	bool autoload;
434 	bool autoattach;
435 	bool mark_btf_static;
436 	enum bpf_prog_type type;
437 	enum bpf_attach_type expected_attach_type;
438 
439 	int prog_ifindex;
440 	__u32 attach_btf_obj_fd;
441 	__u32 attach_btf_id;
442 	__u32 attach_prog_fd;
443 
444 	void *func_info;
445 	__u32 func_info_rec_size;
446 	__u32 func_info_cnt;
447 
448 	void *line_info;
449 	__u32 line_info_rec_size;
450 	__u32 line_info_cnt;
451 	__u32 prog_flags;
452 };
453 
454 struct bpf_struct_ops {
455 	const char *tname;
456 	const struct btf_type *type;
457 	struct bpf_program **progs;
458 	__u32 *kern_func_off;
459 	/* e.g. struct tcp_congestion_ops in bpf_prog's btf format */
460 	void *data;
461 	/* e.g. struct bpf_struct_ops_tcp_congestion_ops in
462 	 *      btf_vmlinux's format.
463 	 * struct bpf_struct_ops_tcp_congestion_ops {
464 	 *	[... some other kernel fields ...]
465 	 *	struct tcp_congestion_ops data;
466 	 * }
467 	 * kern_vdata-size == sizeof(struct bpf_struct_ops_tcp_congestion_ops)
468 	 * bpf_map__init_kern_struct_ops() will populate the "kern_vdata"
469 	 * from "data".
470 	 */
471 	void *kern_vdata;
472 	__u32 type_id;
473 };
474 
475 #define DATA_SEC ".data"
476 #define BSS_SEC ".bss"
477 #define RODATA_SEC ".rodata"
478 #define KCONFIG_SEC ".kconfig"
479 #define KSYMS_SEC ".ksyms"
480 #define STRUCT_OPS_SEC ".struct_ops"
481 #define STRUCT_OPS_LINK_SEC ".struct_ops.link"
482 
483 enum libbpf_map_type {
484 	LIBBPF_MAP_UNSPEC,
485 	LIBBPF_MAP_DATA,
486 	LIBBPF_MAP_BSS,
487 	LIBBPF_MAP_RODATA,
488 	LIBBPF_MAP_KCONFIG,
489 };
490 
491 struct bpf_map_def {
492 	unsigned int type;
493 	unsigned int key_size;
494 	unsigned int value_size;
495 	unsigned int max_entries;
496 	unsigned int map_flags;
497 };
498 
499 struct bpf_map {
500 	struct bpf_object *obj;
501 	char *name;
502 	/* real_name is defined for special internal maps (.rodata*,
503 	 * .data*, .bss, .kconfig) and preserves their original ELF section
504 	 * name. This is important to be able to find corresponding BTF
505 	 * DATASEC information.
506 	 */
507 	char *real_name;
508 	int fd;
509 	int sec_idx;
510 	size_t sec_offset;
511 	int map_ifindex;
512 	int inner_map_fd;
513 	struct bpf_map_def def;
514 	__u32 numa_node;
515 	__u32 btf_var_idx;
516 	__u32 btf_key_type_id;
517 	__u32 btf_value_type_id;
518 	__u32 btf_vmlinux_value_type_id;
519 	enum libbpf_map_type libbpf_type;
520 	void *mmaped;
521 	struct bpf_struct_ops *st_ops;
522 	struct bpf_map *inner_map;
523 	void **init_slots;
524 	int init_slots_sz;
525 	char *pin_path;
526 	bool pinned;
527 	bool reused;
528 	bool autocreate;
529 	__u64 map_extra;
530 };
531 
532 enum extern_type {
533 	EXT_UNKNOWN,
534 	EXT_KCFG,
535 	EXT_KSYM,
536 };
537 
538 enum kcfg_type {
539 	KCFG_UNKNOWN,
540 	KCFG_CHAR,
541 	KCFG_BOOL,
542 	KCFG_INT,
543 	KCFG_TRISTATE,
544 	KCFG_CHAR_ARR,
545 };
546 
547 struct extern_desc {
548 	enum extern_type type;
549 	int sym_idx;
550 	int btf_id;
551 	int sec_btf_id;
552 	const char *name;
553 	bool is_set;
554 	bool is_weak;
555 	union {
556 		struct {
557 			enum kcfg_type type;
558 			int sz;
559 			int align;
560 			int data_off;
561 			bool is_signed;
562 		} kcfg;
563 		struct {
564 			unsigned long long addr;
565 
566 			/* target btf_id of the corresponding kernel var. */
567 			int kernel_btf_obj_fd;
568 			int kernel_btf_id;
569 
570 			/* local btf_id of the ksym extern's type. */
571 			__u32 type_id;
572 			/* BTF fd index to be patched in for insn->off, this is
573 			 * 0 for vmlinux BTF, index in obj->fd_array for module
574 			 * BTF
575 			 */
576 			__s16 btf_fd_idx;
577 		} ksym;
578 	};
579 };
580 
581 struct module_btf {
582 	struct btf *btf;
583 	char *name;
584 	__u32 id;
585 	int fd;
586 	int fd_array_idx;
587 };
588 
589 enum sec_type {
590 	SEC_UNUSED = 0,
591 	SEC_RELO,
592 	SEC_BSS,
593 	SEC_DATA,
594 	SEC_RODATA,
595 };
596 
597 struct elf_sec_desc {
598 	enum sec_type sec_type;
599 	Elf64_Shdr *shdr;
600 	Elf_Data *data;
601 };
602 
603 struct elf_state {
604 	int fd;
605 	const void *obj_buf;
606 	size_t obj_buf_sz;
607 	Elf *elf;
608 	Elf64_Ehdr *ehdr;
609 	Elf_Data *symbols;
610 	Elf_Data *st_ops_data;
611 	Elf_Data *st_ops_link_data;
612 	size_t shstrndx; /* section index for section name strings */
613 	size_t strtabidx;
614 	struct elf_sec_desc *secs;
615 	size_t sec_cnt;
616 	int btf_maps_shndx;
617 	__u32 btf_maps_sec_btf_id;
618 	int text_shndx;
619 	int symbols_shndx;
620 	int st_ops_shndx;
621 	int st_ops_link_shndx;
622 };
623 
624 struct usdt_manager;
625 
626 struct bpf_object {
627 	char name[BPF_OBJ_NAME_LEN];
628 	char license[64];
629 	__u32 kern_version;
630 
631 	struct bpf_program *programs;
632 	size_t nr_programs;
633 	struct bpf_map *maps;
634 	size_t nr_maps;
635 	size_t maps_cap;
636 
637 	char *kconfig;
638 	struct extern_desc *externs;
639 	int nr_extern;
640 	int kconfig_map_idx;
641 
642 	bool loaded;
643 	bool has_subcalls;
644 	bool has_rodata;
645 
646 	struct bpf_gen *gen_loader;
647 
648 	/* Information when doing ELF related work. Only valid if efile.elf is not NULL */
649 	struct elf_state efile;
650 
651 	struct btf *btf;
652 	struct btf_ext *btf_ext;
653 
654 	/* Parse and load BTF vmlinux if any of the programs in the object need
655 	 * it at load time.
656 	 */
657 	struct btf *btf_vmlinux;
658 	/* Path to the custom BTF to be used for BPF CO-RE relocations as an
659 	 * override for vmlinux BTF.
660 	 */
661 	char *btf_custom_path;
662 	/* vmlinux BTF override for CO-RE relocations */
663 	struct btf *btf_vmlinux_override;
664 	/* Lazily initialized kernel module BTFs */
665 	struct module_btf *btf_modules;
666 	bool btf_modules_loaded;
667 	size_t btf_module_cnt;
668 	size_t btf_module_cap;
669 
670 	/* optional log settings passed to BPF_BTF_LOAD and BPF_PROG_LOAD commands */
671 	char *log_buf;
672 	size_t log_size;
673 	__u32 log_level;
674 
675 	int *fd_array;
676 	size_t fd_array_cap;
677 	size_t fd_array_cnt;
678 
679 	struct usdt_manager *usdt_man;
680 
681 	char path[];
682 };
683 
684 static const char *elf_sym_str(const struct bpf_object *obj, size_t off);
685 static const char *elf_sec_str(const struct bpf_object *obj, size_t off);
686 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx);
687 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name);
688 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn);
689 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn);
690 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn);
691 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx);
692 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx);
693 
694 void bpf_program__unload(struct bpf_program *prog)
695 {
696 	if (!prog)
697 		return;
698 
699 	zclose(prog->fd);
700 
701 	zfree(&prog->func_info);
702 	zfree(&prog->line_info);
703 }
704 
705 static void bpf_program__exit(struct bpf_program *prog)
706 {
707 	if (!prog)
708 		return;
709 
710 	bpf_program__unload(prog);
711 	zfree(&prog->name);
712 	zfree(&prog->sec_name);
713 	zfree(&prog->insns);
714 	zfree(&prog->reloc_desc);
715 
716 	prog->nr_reloc = 0;
717 	prog->insns_cnt = 0;
718 	prog->sec_idx = -1;
719 }
720 
721 static bool insn_is_subprog_call(const struct bpf_insn *insn)
722 {
723 	return BPF_CLASS(insn->code) == BPF_JMP &&
724 	       BPF_OP(insn->code) == BPF_CALL &&
725 	       BPF_SRC(insn->code) == BPF_K &&
726 	       insn->src_reg == BPF_PSEUDO_CALL &&
727 	       insn->dst_reg == 0 &&
728 	       insn->off == 0;
729 }
730 
731 static bool is_call_insn(const struct bpf_insn *insn)
732 {
733 	return insn->code == (BPF_JMP | BPF_CALL);
734 }
735 
736 static bool insn_is_pseudo_func(struct bpf_insn *insn)
737 {
738 	return is_ldimm64_insn(insn) && insn->src_reg == BPF_PSEUDO_FUNC;
739 }
740 
741 static int
742 bpf_object__init_prog(struct bpf_object *obj, struct bpf_program *prog,
743 		      const char *name, size_t sec_idx, const char *sec_name,
744 		      size_t sec_off, void *insn_data, size_t insn_data_sz)
745 {
746 	if (insn_data_sz == 0 || insn_data_sz % BPF_INSN_SZ || sec_off % BPF_INSN_SZ) {
747 		pr_warn("sec '%s': corrupted program '%s', offset %zu, size %zu\n",
748 			sec_name, name, sec_off, insn_data_sz);
749 		return -EINVAL;
750 	}
751 
752 	memset(prog, 0, sizeof(*prog));
753 	prog->obj = obj;
754 
755 	prog->sec_idx = sec_idx;
756 	prog->sec_insn_off = sec_off / BPF_INSN_SZ;
757 	prog->sec_insn_cnt = insn_data_sz / BPF_INSN_SZ;
758 	/* insns_cnt can later be increased by appending used subprograms */
759 	prog->insns_cnt = prog->sec_insn_cnt;
760 
761 	prog->type = BPF_PROG_TYPE_UNSPEC;
762 	prog->fd = -1;
763 
764 	/* libbpf's convention for SEC("?abc...") is that it's just like
765 	 * SEC("abc...") but the corresponding bpf_program starts out with
766 	 * autoload set to false.
767 	 */
768 	if (sec_name[0] == '?') {
769 		prog->autoload = false;
770 		/* from now on forget there was ? in section name */
771 		sec_name++;
772 	} else {
773 		prog->autoload = true;
774 	}
775 
776 	prog->autoattach = true;
777 
778 	/* inherit object's log_level */
779 	prog->log_level = obj->log_level;
780 
781 	prog->sec_name = strdup(sec_name);
782 	if (!prog->sec_name)
783 		goto errout;
784 
785 	prog->name = strdup(name);
786 	if (!prog->name)
787 		goto errout;
788 
789 	prog->insns = malloc(insn_data_sz);
790 	if (!prog->insns)
791 		goto errout;
792 	memcpy(prog->insns, insn_data, insn_data_sz);
793 
794 	return 0;
795 errout:
796 	pr_warn("sec '%s': failed to allocate memory for prog '%s'\n", sec_name, name);
797 	bpf_program__exit(prog);
798 	return -ENOMEM;
799 }
800 
801 static int
802 bpf_object__add_programs(struct bpf_object *obj, Elf_Data *sec_data,
803 			 const char *sec_name, int sec_idx)
804 {
805 	Elf_Data *symbols = obj->efile.symbols;
806 	struct bpf_program *prog, *progs;
807 	void *data = sec_data->d_buf;
808 	size_t sec_sz = sec_data->d_size, sec_off, prog_sz, nr_syms;
809 	int nr_progs, err, i;
810 	const char *name;
811 	Elf64_Sym *sym;
812 
813 	progs = obj->programs;
814 	nr_progs = obj->nr_programs;
815 	nr_syms = symbols->d_size / sizeof(Elf64_Sym);
816 
817 	for (i = 0; i < nr_syms; i++) {
818 		sym = elf_sym_by_idx(obj, i);
819 
820 		if (sym->st_shndx != sec_idx)
821 			continue;
822 		if (ELF64_ST_TYPE(sym->st_info) != STT_FUNC)
823 			continue;
824 
825 		prog_sz = sym->st_size;
826 		sec_off = sym->st_value;
827 
828 		name = elf_sym_str(obj, sym->st_name);
829 		if (!name) {
830 			pr_warn("sec '%s': failed to get symbol name for offset %zu\n",
831 				sec_name, sec_off);
832 			return -LIBBPF_ERRNO__FORMAT;
833 		}
834 
835 		if (sec_off + prog_sz > sec_sz) {
836 			pr_warn("sec '%s': program at offset %zu crosses section boundary\n",
837 				sec_name, sec_off);
838 			return -LIBBPF_ERRNO__FORMAT;
839 		}
840 
841 		if (sec_idx != obj->efile.text_shndx && ELF64_ST_BIND(sym->st_info) == STB_LOCAL) {
842 			pr_warn("sec '%s': program '%s' is static and not supported\n", sec_name, name);
843 			return -ENOTSUP;
844 		}
845 
846 		pr_debug("sec '%s': found program '%s' at insn offset %zu (%zu bytes), code size %zu insns (%zu bytes)\n",
847 			 sec_name, name, sec_off / BPF_INSN_SZ, sec_off, prog_sz / BPF_INSN_SZ, prog_sz);
848 
849 		progs = libbpf_reallocarray(progs, nr_progs + 1, sizeof(*progs));
850 		if (!progs) {
851 			/*
852 			 * In this case the original obj->programs
853 			 * is still valid, so don't need special treat for
854 			 * bpf_close_object().
855 			 */
856 			pr_warn("sec '%s': failed to alloc memory for new program '%s'\n",
857 				sec_name, name);
858 			return -ENOMEM;
859 		}
860 		obj->programs = progs;
861 
862 		prog = &progs[nr_progs];
863 
864 		err = bpf_object__init_prog(obj, prog, name, sec_idx, sec_name,
865 					    sec_off, data + sec_off, prog_sz);
866 		if (err)
867 			return err;
868 
869 		/* if function is a global/weak symbol, but has restricted
870 		 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF FUNC
871 		 * as static to enable more permissive BPF verification mode
872 		 * with more outside context available to BPF verifier
873 		 */
874 		if (ELF64_ST_BIND(sym->st_info) != STB_LOCAL
875 		    && (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
876 			|| ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL))
877 			prog->mark_btf_static = true;
878 
879 		nr_progs++;
880 		obj->nr_programs = nr_progs;
881 	}
882 
883 	return 0;
884 }
885 
886 static const struct btf_member *
887 find_member_by_offset(const struct btf_type *t, __u32 bit_offset)
888 {
889 	struct btf_member *m;
890 	int i;
891 
892 	for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
893 		if (btf_member_bit_offset(t, i) == bit_offset)
894 			return m;
895 	}
896 
897 	return NULL;
898 }
899 
900 static const struct btf_member *
901 find_member_by_name(const struct btf *btf, const struct btf_type *t,
902 		    const char *name)
903 {
904 	struct btf_member *m;
905 	int i;
906 
907 	for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
908 		if (!strcmp(btf__name_by_offset(btf, m->name_off), name))
909 			return m;
910 	}
911 
912 	return NULL;
913 }
914 
915 #define STRUCT_OPS_VALUE_PREFIX "bpf_struct_ops_"
916 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
917 				   const char *name, __u32 kind);
918 
919 static int
920 find_struct_ops_kern_types(const struct btf *btf, const char *tname,
921 			   const struct btf_type **type, __u32 *type_id,
922 			   const struct btf_type **vtype, __u32 *vtype_id,
923 			   const struct btf_member **data_member)
924 {
925 	const struct btf_type *kern_type, *kern_vtype;
926 	const struct btf_member *kern_data_member;
927 	__s32 kern_vtype_id, kern_type_id;
928 	__u32 i;
929 
930 	kern_type_id = btf__find_by_name_kind(btf, tname, BTF_KIND_STRUCT);
931 	if (kern_type_id < 0) {
932 		pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n",
933 			tname);
934 		return kern_type_id;
935 	}
936 	kern_type = btf__type_by_id(btf, kern_type_id);
937 
938 	/* Find the corresponding "map_value" type that will be used
939 	 * in map_update(BPF_MAP_TYPE_STRUCT_OPS).  For example,
940 	 * find "struct bpf_struct_ops_tcp_congestion_ops" from the
941 	 * btf_vmlinux.
942 	 */
943 	kern_vtype_id = find_btf_by_prefix_kind(btf, STRUCT_OPS_VALUE_PREFIX,
944 						tname, BTF_KIND_STRUCT);
945 	if (kern_vtype_id < 0) {
946 		pr_warn("struct_ops init_kern: struct %s%s is not found in kernel BTF\n",
947 			STRUCT_OPS_VALUE_PREFIX, tname);
948 		return kern_vtype_id;
949 	}
950 	kern_vtype = btf__type_by_id(btf, kern_vtype_id);
951 
952 	/* Find "struct tcp_congestion_ops" from
953 	 * struct bpf_struct_ops_tcp_congestion_ops {
954 	 *	[ ... ]
955 	 *	struct tcp_congestion_ops data;
956 	 * }
957 	 */
958 	kern_data_member = btf_members(kern_vtype);
959 	for (i = 0; i < btf_vlen(kern_vtype); i++, kern_data_member++) {
960 		if (kern_data_member->type == kern_type_id)
961 			break;
962 	}
963 	if (i == btf_vlen(kern_vtype)) {
964 		pr_warn("struct_ops init_kern: struct %s data is not found in struct %s%s\n",
965 			tname, STRUCT_OPS_VALUE_PREFIX, tname);
966 		return -EINVAL;
967 	}
968 
969 	*type = kern_type;
970 	*type_id = kern_type_id;
971 	*vtype = kern_vtype;
972 	*vtype_id = kern_vtype_id;
973 	*data_member = kern_data_member;
974 
975 	return 0;
976 }
977 
978 static bool bpf_map__is_struct_ops(const struct bpf_map *map)
979 {
980 	return map->def.type == BPF_MAP_TYPE_STRUCT_OPS;
981 }
982 
983 /* Init the map's fields that depend on kern_btf */
984 static int bpf_map__init_kern_struct_ops(struct bpf_map *map,
985 					 const struct btf *btf,
986 					 const struct btf *kern_btf)
987 {
988 	const struct btf_member *member, *kern_member, *kern_data_member;
989 	const struct btf_type *type, *kern_type, *kern_vtype;
990 	__u32 i, kern_type_id, kern_vtype_id, kern_data_off;
991 	struct bpf_struct_ops *st_ops;
992 	void *data, *kern_data;
993 	const char *tname;
994 	int err;
995 
996 	st_ops = map->st_ops;
997 	type = st_ops->type;
998 	tname = st_ops->tname;
999 	err = find_struct_ops_kern_types(kern_btf, tname,
1000 					 &kern_type, &kern_type_id,
1001 					 &kern_vtype, &kern_vtype_id,
1002 					 &kern_data_member);
1003 	if (err)
1004 		return err;
1005 
1006 	pr_debug("struct_ops init_kern %s: type_id:%u kern_type_id:%u kern_vtype_id:%u\n",
1007 		 map->name, st_ops->type_id, kern_type_id, kern_vtype_id);
1008 
1009 	map->def.value_size = kern_vtype->size;
1010 	map->btf_vmlinux_value_type_id = kern_vtype_id;
1011 
1012 	st_ops->kern_vdata = calloc(1, kern_vtype->size);
1013 	if (!st_ops->kern_vdata)
1014 		return -ENOMEM;
1015 
1016 	data = st_ops->data;
1017 	kern_data_off = kern_data_member->offset / 8;
1018 	kern_data = st_ops->kern_vdata + kern_data_off;
1019 
1020 	member = btf_members(type);
1021 	for (i = 0; i < btf_vlen(type); i++, member++) {
1022 		const struct btf_type *mtype, *kern_mtype;
1023 		__u32 mtype_id, kern_mtype_id;
1024 		void *mdata, *kern_mdata;
1025 		__s64 msize, kern_msize;
1026 		__u32 moff, kern_moff;
1027 		__u32 kern_member_idx;
1028 		const char *mname;
1029 
1030 		mname = btf__name_by_offset(btf, member->name_off);
1031 		kern_member = find_member_by_name(kern_btf, kern_type, mname);
1032 		if (!kern_member) {
1033 			pr_warn("struct_ops init_kern %s: Cannot find member %s in kernel BTF\n",
1034 				map->name, mname);
1035 			return -ENOTSUP;
1036 		}
1037 
1038 		kern_member_idx = kern_member - btf_members(kern_type);
1039 		if (btf_member_bitfield_size(type, i) ||
1040 		    btf_member_bitfield_size(kern_type, kern_member_idx)) {
1041 			pr_warn("struct_ops init_kern %s: bitfield %s is not supported\n",
1042 				map->name, mname);
1043 			return -ENOTSUP;
1044 		}
1045 
1046 		moff = member->offset / 8;
1047 		kern_moff = kern_member->offset / 8;
1048 
1049 		mdata = data + moff;
1050 		kern_mdata = kern_data + kern_moff;
1051 
1052 		mtype = skip_mods_and_typedefs(btf, member->type, &mtype_id);
1053 		kern_mtype = skip_mods_and_typedefs(kern_btf, kern_member->type,
1054 						    &kern_mtype_id);
1055 		if (BTF_INFO_KIND(mtype->info) !=
1056 		    BTF_INFO_KIND(kern_mtype->info)) {
1057 			pr_warn("struct_ops init_kern %s: Unmatched member type %s %u != %u(kernel)\n",
1058 				map->name, mname, BTF_INFO_KIND(mtype->info),
1059 				BTF_INFO_KIND(kern_mtype->info));
1060 			return -ENOTSUP;
1061 		}
1062 
1063 		if (btf_is_ptr(mtype)) {
1064 			struct bpf_program *prog;
1065 
1066 			prog = st_ops->progs[i];
1067 			if (!prog)
1068 				continue;
1069 
1070 			kern_mtype = skip_mods_and_typedefs(kern_btf,
1071 							    kern_mtype->type,
1072 							    &kern_mtype_id);
1073 
1074 			/* mtype->type must be a func_proto which was
1075 			 * guaranteed in bpf_object__collect_st_ops_relos(),
1076 			 * so only check kern_mtype for func_proto here.
1077 			 */
1078 			if (!btf_is_func_proto(kern_mtype)) {
1079 				pr_warn("struct_ops init_kern %s: kernel member %s is not a func ptr\n",
1080 					map->name, mname);
1081 				return -ENOTSUP;
1082 			}
1083 
1084 			prog->attach_btf_id = kern_type_id;
1085 			prog->expected_attach_type = kern_member_idx;
1086 
1087 			st_ops->kern_func_off[i] = kern_data_off + kern_moff;
1088 
1089 			pr_debug("struct_ops init_kern %s: func ptr %s is set to prog %s from data(+%u) to kern_data(+%u)\n",
1090 				 map->name, mname, prog->name, moff,
1091 				 kern_moff);
1092 
1093 			continue;
1094 		}
1095 
1096 		msize = btf__resolve_size(btf, mtype_id);
1097 		kern_msize = btf__resolve_size(kern_btf, kern_mtype_id);
1098 		if (msize < 0 || kern_msize < 0 || msize != kern_msize) {
1099 			pr_warn("struct_ops init_kern %s: Error in size of member %s: %zd != %zd(kernel)\n",
1100 				map->name, mname, (ssize_t)msize,
1101 				(ssize_t)kern_msize);
1102 			return -ENOTSUP;
1103 		}
1104 
1105 		pr_debug("struct_ops init_kern %s: copy %s %u bytes from data(+%u) to kern_data(+%u)\n",
1106 			 map->name, mname, (unsigned int)msize,
1107 			 moff, kern_moff);
1108 		memcpy(kern_mdata, mdata, msize);
1109 	}
1110 
1111 	return 0;
1112 }
1113 
1114 static int bpf_object__init_kern_struct_ops_maps(struct bpf_object *obj)
1115 {
1116 	struct bpf_map *map;
1117 	size_t i;
1118 	int err;
1119 
1120 	for (i = 0; i < obj->nr_maps; i++) {
1121 		map = &obj->maps[i];
1122 
1123 		if (!bpf_map__is_struct_ops(map))
1124 			continue;
1125 
1126 		err = bpf_map__init_kern_struct_ops(map, obj->btf,
1127 						    obj->btf_vmlinux);
1128 		if (err)
1129 			return err;
1130 	}
1131 
1132 	return 0;
1133 }
1134 
1135 static int init_struct_ops_maps(struct bpf_object *obj, const char *sec_name,
1136 				int shndx, Elf_Data *data, __u32 map_flags)
1137 {
1138 	const struct btf_type *type, *datasec;
1139 	const struct btf_var_secinfo *vsi;
1140 	struct bpf_struct_ops *st_ops;
1141 	const char *tname, *var_name;
1142 	__s32 type_id, datasec_id;
1143 	const struct btf *btf;
1144 	struct bpf_map *map;
1145 	__u32 i;
1146 
1147 	if (shndx == -1)
1148 		return 0;
1149 
1150 	btf = obj->btf;
1151 	datasec_id = btf__find_by_name_kind(btf, sec_name,
1152 					    BTF_KIND_DATASEC);
1153 	if (datasec_id < 0) {
1154 		pr_warn("struct_ops init: DATASEC %s not found\n",
1155 			sec_name);
1156 		return -EINVAL;
1157 	}
1158 
1159 	datasec = btf__type_by_id(btf, datasec_id);
1160 	vsi = btf_var_secinfos(datasec);
1161 	for (i = 0; i < btf_vlen(datasec); i++, vsi++) {
1162 		type = btf__type_by_id(obj->btf, vsi->type);
1163 		var_name = btf__name_by_offset(obj->btf, type->name_off);
1164 
1165 		type_id = btf__resolve_type(obj->btf, vsi->type);
1166 		if (type_id < 0) {
1167 			pr_warn("struct_ops init: Cannot resolve var type_id %u in DATASEC %s\n",
1168 				vsi->type, sec_name);
1169 			return -EINVAL;
1170 		}
1171 
1172 		type = btf__type_by_id(obj->btf, type_id);
1173 		tname = btf__name_by_offset(obj->btf, type->name_off);
1174 		if (!tname[0]) {
1175 			pr_warn("struct_ops init: anonymous type is not supported\n");
1176 			return -ENOTSUP;
1177 		}
1178 		if (!btf_is_struct(type)) {
1179 			pr_warn("struct_ops init: %s is not a struct\n", tname);
1180 			return -EINVAL;
1181 		}
1182 
1183 		map = bpf_object__add_map(obj);
1184 		if (IS_ERR(map))
1185 			return PTR_ERR(map);
1186 
1187 		map->sec_idx = shndx;
1188 		map->sec_offset = vsi->offset;
1189 		map->name = strdup(var_name);
1190 		if (!map->name)
1191 			return -ENOMEM;
1192 
1193 		map->def.type = BPF_MAP_TYPE_STRUCT_OPS;
1194 		map->def.key_size = sizeof(int);
1195 		map->def.value_size = type->size;
1196 		map->def.max_entries = 1;
1197 		map->def.map_flags = map_flags;
1198 
1199 		map->st_ops = calloc(1, sizeof(*map->st_ops));
1200 		if (!map->st_ops)
1201 			return -ENOMEM;
1202 		st_ops = map->st_ops;
1203 		st_ops->data = malloc(type->size);
1204 		st_ops->progs = calloc(btf_vlen(type), sizeof(*st_ops->progs));
1205 		st_ops->kern_func_off = malloc(btf_vlen(type) *
1206 					       sizeof(*st_ops->kern_func_off));
1207 		if (!st_ops->data || !st_ops->progs || !st_ops->kern_func_off)
1208 			return -ENOMEM;
1209 
1210 		if (vsi->offset + type->size > data->d_size) {
1211 			pr_warn("struct_ops init: var %s is beyond the end of DATASEC %s\n",
1212 				var_name, sec_name);
1213 			return -EINVAL;
1214 		}
1215 
1216 		memcpy(st_ops->data,
1217 		       data->d_buf + vsi->offset,
1218 		       type->size);
1219 		st_ops->tname = tname;
1220 		st_ops->type = type;
1221 		st_ops->type_id = type_id;
1222 
1223 		pr_debug("struct_ops init: struct %s(type_id=%u) %s found at offset %u\n",
1224 			 tname, type_id, var_name, vsi->offset);
1225 	}
1226 
1227 	return 0;
1228 }
1229 
1230 static int bpf_object_init_struct_ops(struct bpf_object *obj)
1231 {
1232 	int err;
1233 
1234 	err = init_struct_ops_maps(obj, STRUCT_OPS_SEC, obj->efile.st_ops_shndx,
1235 				   obj->efile.st_ops_data, 0);
1236 	err = err ?: init_struct_ops_maps(obj, STRUCT_OPS_LINK_SEC,
1237 					  obj->efile.st_ops_link_shndx,
1238 					  obj->efile.st_ops_link_data,
1239 					  BPF_F_LINK);
1240 	return err;
1241 }
1242 
1243 static struct bpf_object *bpf_object__new(const char *path,
1244 					  const void *obj_buf,
1245 					  size_t obj_buf_sz,
1246 					  const char *obj_name)
1247 {
1248 	struct bpf_object *obj;
1249 	char *end;
1250 
1251 	obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
1252 	if (!obj) {
1253 		pr_warn("alloc memory failed for %s\n", path);
1254 		return ERR_PTR(-ENOMEM);
1255 	}
1256 
1257 	strcpy(obj->path, path);
1258 	if (obj_name) {
1259 		libbpf_strlcpy(obj->name, obj_name, sizeof(obj->name));
1260 	} else {
1261 		/* Using basename() GNU version which doesn't modify arg. */
1262 		libbpf_strlcpy(obj->name, basename((void *)path), sizeof(obj->name));
1263 		end = strchr(obj->name, '.');
1264 		if (end)
1265 			*end = 0;
1266 	}
1267 
1268 	obj->efile.fd = -1;
1269 	/*
1270 	 * Caller of this function should also call
1271 	 * bpf_object__elf_finish() after data collection to return
1272 	 * obj_buf to user. If not, we should duplicate the buffer to
1273 	 * avoid user freeing them before elf finish.
1274 	 */
1275 	obj->efile.obj_buf = obj_buf;
1276 	obj->efile.obj_buf_sz = obj_buf_sz;
1277 	obj->efile.btf_maps_shndx = -1;
1278 	obj->efile.st_ops_shndx = -1;
1279 	obj->efile.st_ops_link_shndx = -1;
1280 	obj->kconfig_map_idx = -1;
1281 
1282 	obj->kern_version = get_kernel_version();
1283 	obj->loaded = false;
1284 
1285 	return obj;
1286 }
1287 
1288 static void bpf_object__elf_finish(struct bpf_object *obj)
1289 {
1290 	if (!obj->efile.elf)
1291 		return;
1292 
1293 	elf_end(obj->efile.elf);
1294 	obj->efile.elf = NULL;
1295 	obj->efile.symbols = NULL;
1296 	obj->efile.st_ops_data = NULL;
1297 	obj->efile.st_ops_link_data = NULL;
1298 
1299 	zfree(&obj->efile.secs);
1300 	obj->efile.sec_cnt = 0;
1301 	zclose(obj->efile.fd);
1302 	obj->efile.obj_buf = NULL;
1303 	obj->efile.obj_buf_sz = 0;
1304 }
1305 
1306 static int bpf_object__elf_init(struct bpf_object *obj)
1307 {
1308 	Elf64_Ehdr *ehdr;
1309 	int err = 0;
1310 	Elf *elf;
1311 
1312 	if (obj->efile.elf) {
1313 		pr_warn("elf: init internal error\n");
1314 		return -LIBBPF_ERRNO__LIBELF;
1315 	}
1316 
1317 	if (obj->efile.obj_buf_sz > 0) {
1318 		/* obj_buf should have been validated by bpf_object__open_mem(). */
1319 		elf = elf_memory((char *)obj->efile.obj_buf, obj->efile.obj_buf_sz);
1320 	} else {
1321 		obj->efile.fd = open(obj->path, O_RDONLY | O_CLOEXEC);
1322 		if (obj->efile.fd < 0) {
1323 			char errmsg[STRERR_BUFSIZE], *cp;
1324 
1325 			err = -errno;
1326 			cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
1327 			pr_warn("elf: failed to open %s: %s\n", obj->path, cp);
1328 			return err;
1329 		}
1330 
1331 		elf = elf_begin(obj->efile.fd, ELF_C_READ_MMAP, NULL);
1332 	}
1333 
1334 	if (!elf) {
1335 		pr_warn("elf: failed to open %s as ELF file: %s\n", obj->path, elf_errmsg(-1));
1336 		err = -LIBBPF_ERRNO__LIBELF;
1337 		goto errout;
1338 	}
1339 
1340 	obj->efile.elf = elf;
1341 
1342 	if (elf_kind(elf) != ELF_K_ELF) {
1343 		err = -LIBBPF_ERRNO__FORMAT;
1344 		pr_warn("elf: '%s' is not a proper ELF object\n", obj->path);
1345 		goto errout;
1346 	}
1347 
1348 	if (gelf_getclass(elf) != ELFCLASS64) {
1349 		err = -LIBBPF_ERRNO__FORMAT;
1350 		pr_warn("elf: '%s' is not a 64-bit ELF object\n", obj->path);
1351 		goto errout;
1352 	}
1353 
1354 	obj->efile.ehdr = ehdr = elf64_getehdr(elf);
1355 	if (!obj->efile.ehdr) {
1356 		pr_warn("elf: failed to get ELF header from %s: %s\n", obj->path, elf_errmsg(-1));
1357 		err = -LIBBPF_ERRNO__FORMAT;
1358 		goto errout;
1359 	}
1360 
1361 	if (elf_getshdrstrndx(elf, &obj->efile.shstrndx)) {
1362 		pr_warn("elf: failed to get section names section index for %s: %s\n",
1363 			obj->path, elf_errmsg(-1));
1364 		err = -LIBBPF_ERRNO__FORMAT;
1365 		goto errout;
1366 	}
1367 
1368 	/* ELF is corrupted/truncated, avoid calling elf_strptr. */
1369 	if (!elf_rawdata(elf_getscn(elf, obj->efile.shstrndx), NULL)) {
1370 		pr_warn("elf: failed to get section names strings from %s: %s\n",
1371 			obj->path, elf_errmsg(-1));
1372 		err = -LIBBPF_ERRNO__FORMAT;
1373 		goto errout;
1374 	}
1375 
1376 	/* Old LLVM set e_machine to EM_NONE */
1377 	if (ehdr->e_type != ET_REL || (ehdr->e_machine && ehdr->e_machine != EM_BPF)) {
1378 		pr_warn("elf: %s is not a valid eBPF object file\n", obj->path);
1379 		err = -LIBBPF_ERRNO__FORMAT;
1380 		goto errout;
1381 	}
1382 
1383 	return 0;
1384 errout:
1385 	bpf_object__elf_finish(obj);
1386 	return err;
1387 }
1388 
1389 static int bpf_object__check_endianness(struct bpf_object *obj)
1390 {
1391 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1392 	if (obj->efile.ehdr->e_ident[EI_DATA] == ELFDATA2LSB)
1393 		return 0;
1394 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
1395 	if (obj->efile.ehdr->e_ident[EI_DATA] == ELFDATA2MSB)
1396 		return 0;
1397 #else
1398 # error "Unrecognized __BYTE_ORDER__"
1399 #endif
1400 	pr_warn("elf: endianness mismatch in %s.\n", obj->path);
1401 	return -LIBBPF_ERRNO__ENDIAN;
1402 }
1403 
1404 static int
1405 bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
1406 {
1407 	if (!data) {
1408 		pr_warn("invalid license section in %s\n", obj->path);
1409 		return -LIBBPF_ERRNO__FORMAT;
1410 	}
1411 	/* libbpf_strlcpy() only copies first N - 1 bytes, so size + 1 won't
1412 	 * go over allowed ELF data section buffer
1413 	 */
1414 	libbpf_strlcpy(obj->license, data, min(size + 1, sizeof(obj->license)));
1415 	pr_debug("license of %s is %s\n", obj->path, obj->license);
1416 	return 0;
1417 }
1418 
1419 static int
1420 bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
1421 {
1422 	__u32 kver;
1423 
1424 	if (!data || size != sizeof(kver)) {
1425 		pr_warn("invalid kver section in %s\n", obj->path);
1426 		return -LIBBPF_ERRNO__FORMAT;
1427 	}
1428 	memcpy(&kver, data, sizeof(kver));
1429 	obj->kern_version = kver;
1430 	pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
1431 	return 0;
1432 }
1433 
1434 static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
1435 {
1436 	if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
1437 	    type == BPF_MAP_TYPE_HASH_OF_MAPS)
1438 		return true;
1439 	return false;
1440 }
1441 
1442 static int find_elf_sec_sz(const struct bpf_object *obj, const char *name, __u32 *size)
1443 {
1444 	Elf_Data *data;
1445 	Elf_Scn *scn;
1446 
1447 	if (!name)
1448 		return -EINVAL;
1449 
1450 	scn = elf_sec_by_name(obj, name);
1451 	data = elf_sec_data(obj, scn);
1452 	if (data) {
1453 		*size = data->d_size;
1454 		return 0; /* found it */
1455 	}
1456 
1457 	return -ENOENT;
1458 }
1459 
1460 static Elf64_Sym *find_elf_var_sym(const struct bpf_object *obj, const char *name)
1461 {
1462 	Elf_Data *symbols = obj->efile.symbols;
1463 	const char *sname;
1464 	size_t si;
1465 
1466 	for (si = 0; si < symbols->d_size / sizeof(Elf64_Sym); si++) {
1467 		Elf64_Sym *sym = elf_sym_by_idx(obj, si);
1468 
1469 		if (ELF64_ST_TYPE(sym->st_info) != STT_OBJECT)
1470 			continue;
1471 
1472 		if (ELF64_ST_BIND(sym->st_info) != STB_GLOBAL &&
1473 		    ELF64_ST_BIND(sym->st_info) != STB_WEAK)
1474 			continue;
1475 
1476 		sname = elf_sym_str(obj, sym->st_name);
1477 		if (!sname) {
1478 			pr_warn("failed to get sym name string for var %s\n", name);
1479 			return ERR_PTR(-EIO);
1480 		}
1481 		if (strcmp(name, sname) == 0)
1482 			return sym;
1483 	}
1484 
1485 	return ERR_PTR(-ENOENT);
1486 }
1487 
1488 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
1489 {
1490 	struct bpf_map *map;
1491 	int err;
1492 
1493 	err = libbpf_ensure_mem((void **)&obj->maps, &obj->maps_cap,
1494 				sizeof(*obj->maps), obj->nr_maps + 1);
1495 	if (err)
1496 		return ERR_PTR(err);
1497 
1498 	map = &obj->maps[obj->nr_maps++];
1499 	map->obj = obj;
1500 	map->fd = -1;
1501 	map->inner_map_fd = -1;
1502 	map->autocreate = true;
1503 
1504 	return map;
1505 }
1506 
1507 static size_t bpf_map_mmap_sz(unsigned int value_sz, unsigned int max_entries)
1508 {
1509 	const long page_sz = sysconf(_SC_PAGE_SIZE);
1510 	size_t map_sz;
1511 
1512 	map_sz = (size_t)roundup(value_sz, 8) * max_entries;
1513 	map_sz = roundup(map_sz, page_sz);
1514 	return map_sz;
1515 }
1516 
1517 static int bpf_map_mmap_resize(struct bpf_map *map, size_t old_sz, size_t new_sz)
1518 {
1519 	void *mmaped;
1520 
1521 	if (!map->mmaped)
1522 		return -EINVAL;
1523 
1524 	if (old_sz == new_sz)
1525 		return 0;
1526 
1527 	mmaped = mmap(NULL, new_sz, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1528 	if (mmaped == MAP_FAILED)
1529 		return -errno;
1530 
1531 	memcpy(mmaped, map->mmaped, min(old_sz, new_sz));
1532 	munmap(map->mmaped, old_sz);
1533 	map->mmaped = mmaped;
1534 	return 0;
1535 }
1536 
1537 static char *internal_map_name(struct bpf_object *obj, const char *real_name)
1538 {
1539 	char map_name[BPF_OBJ_NAME_LEN], *p;
1540 	int pfx_len, sfx_len = max((size_t)7, strlen(real_name));
1541 
1542 	/* This is one of the more confusing parts of libbpf for various
1543 	 * reasons, some of which are historical. The original idea for naming
1544 	 * internal names was to include as much of BPF object name prefix as
1545 	 * possible, so that it can be distinguished from similar internal
1546 	 * maps of a different BPF object.
1547 	 * As an example, let's say we have bpf_object named 'my_object_name'
1548 	 * and internal map corresponding to '.rodata' ELF section. The final
1549 	 * map name advertised to user and to the kernel will be
1550 	 * 'my_objec.rodata', taking first 8 characters of object name and
1551 	 * entire 7 characters of '.rodata'.
1552 	 * Somewhat confusingly, if internal map ELF section name is shorter
1553 	 * than 7 characters, e.g., '.bss', we still reserve 7 characters
1554 	 * for the suffix, even though we only have 4 actual characters, and
1555 	 * resulting map will be called 'my_objec.bss', not even using all 15
1556 	 * characters allowed by the kernel. Oh well, at least the truncated
1557 	 * object name is somewhat consistent in this case. But if the map
1558 	 * name is '.kconfig', we'll still have entirety of '.kconfig' added
1559 	 * (8 chars) and thus will be left with only first 7 characters of the
1560 	 * object name ('my_obje'). Happy guessing, user, that the final map
1561 	 * name will be "my_obje.kconfig".
1562 	 * Now, with libbpf starting to support arbitrarily named .rodata.*
1563 	 * and .data.* data sections, it's possible that ELF section name is
1564 	 * longer than allowed 15 chars, so we now need to be careful to take
1565 	 * only up to 15 first characters of ELF name, taking no BPF object
1566 	 * name characters at all. So '.rodata.abracadabra' will result in
1567 	 * '.rodata.abracad' kernel and user-visible name.
1568 	 * We need to keep this convoluted logic intact for .data, .bss and
1569 	 * .rodata maps, but for new custom .data.custom and .rodata.custom
1570 	 * maps we use their ELF names as is, not prepending bpf_object name
1571 	 * in front. We still need to truncate them to 15 characters for the
1572 	 * kernel. Full name can be recovered for such maps by using DATASEC
1573 	 * BTF type associated with such map's value type, though.
1574 	 */
1575 	if (sfx_len >= BPF_OBJ_NAME_LEN)
1576 		sfx_len = BPF_OBJ_NAME_LEN - 1;
1577 
1578 	/* if there are two or more dots in map name, it's a custom dot map */
1579 	if (strchr(real_name + 1, '.') != NULL)
1580 		pfx_len = 0;
1581 	else
1582 		pfx_len = min((size_t)BPF_OBJ_NAME_LEN - sfx_len - 1, strlen(obj->name));
1583 
1584 	snprintf(map_name, sizeof(map_name), "%.*s%.*s", pfx_len, obj->name,
1585 		 sfx_len, real_name);
1586 
1587 	/* sanitise map name to characters allowed by kernel */
1588 	for (p = map_name; *p && p < map_name + sizeof(map_name); p++)
1589 		if (!isalnum(*p) && *p != '_' && *p != '.')
1590 			*p = '_';
1591 
1592 	return strdup(map_name);
1593 }
1594 
1595 static int
1596 map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map);
1597 
1598 /* Internal BPF map is mmap()'able only if at least one of corresponding
1599  * DATASEC's VARs are to be exposed through BPF skeleton. I.e., it's a GLOBAL
1600  * variable and it's not marked as __hidden (which turns it into, effectively,
1601  * a STATIC variable).
1602  */
1603 static bool map_is_mmapable(struct bpf_object *obj, struct bpf_map *map)
1604 {
1605 	const struct btf_type *t, *vt;
1606 	struct btf_var_secinfo *vsi;
1607 	int i, n;
1608 
1609 	if (!map->btf_value_type_id)
1610 		return false;
1611 
1612 	t = btf__type_by_id(obj->btf, map->btf_value_type_id);
1613 	if (!btf_is_datasec(t))
1614 		return false;
1615 
1616 	vsi = btf_var_secinfos(t);
1617 	for (i = 0, n = btf_vlen(t); i < n; i++, vsi++) {
1618 		vt = btf__type_by_id(obj->btf, vsi->type);
1619 		if (!btf_is_var(vt))
1620 			continue;
1621 
1622 		if (btf_var(vt)->linkage != BTF_VAR_STATIC)
1623 			return true;
1624 	}
1625 
1626 	return false;
1627 }
1628 
1629 static int
1630 bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
1631 			      const char *real_name, int sec_idx, void *data, size_t data_sz)
1632 {
1633 	struct bpf_map_def *def;
1634 	struct bpf_map *map;
1635 	size_t mmap_sz;
1636 	int err;
1637 
1638 	map = bpf_object__add_map(obj);
1639 	if (IS_ERR(map))
1640 		return PTR_ERR(map);
1641 
1642 	map->libbpf_type = type;
1643 	map->sec_idx = sec_idx;
1644 	map->sec_offset = 0;
1645 	map->real_name = strdup(real_name);
1646 	map->name = internal_map_name(obj, real_name);
1647 	if (!map->real_name || !map->name) {
1648 		zfree(&map->real_name);
1649 		zfree(&map->name);
1650 		return -ENOMEM;
1651 	}
1652 
1653 	def = &map->def;
1654 	def->type = BPF_MAP_TYPE_ARRAY;
1655 	def->key_size = sizeof(int);
1656 	def->value_size = data_sz;
1657 	def->max_entries = 1;
1658 	def->map_flags = type == LIBBPF_MAP_RODATA || type == LIBBPF_MAP_KCONFIG
1659 			 ? BPF_F_RDONLY_PROG : 0;
1660 
1661 	/* failures are fine because of maps like .rodata.str1.1 */
1662 	(void) map_fill_btf_type_info(obj, map);
1663 
1664 	if (map_is_mmapable(obj, map))
1665 		def->map_flags |= BPF_F_MMAPABLE;
1666 
1667 	pr_debug("map '%s' (global data): at sec_idx %d, offset %zu, flags %x.\n",
1668 		 map->name, map->sec_idx, map->sec_offset, def->map_flags);
1669 
1670 	mmap_sz = bpf_map_mmap_sz(map->def.value_size, map->def.max_entries);
1671 	map->mmaped = mmap(NULL, mmap_sz, PROT_READ | PROT_WRITE,
1672 			   MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1673 	if (map->mmaped == MAP_FAILED) {
1674 		err = -errno;
1675 		map->mmaped = NULL;
1676 		pr_warn("failed to alloc map '%s' content buffer: %d\n",
1677 			map->name, err);
1678 		zfree(&map->real_name);
1679 		zfree(&map->name);
1680 		return err;
1681 	}
1682 
1683 	if (data)
1684 		memcpy(map->mmaped, data, data_sz);
1685 
1686 	pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
1687 	return 0;
1688 }
1689 
1690 static int bpf_object__init_global_data_maps(struct bpf_object *obj)
1691 {
1692 	struct elf_sec_desc *sec_desc;
1693 	const char *sec_name;
1694 	int err = 0, sec_idx;
1695 
1696 	/*
1697 	 * Populate obj->maps with libbpf internal maps.
1698 	 */
1699 	for (sec_idx = 1; sec_idx < obj->efile.sec_cnt; sec_idx++) {
1700 		sec_desc = &obj->efile.secs[sec_idx];
1701 
1702 		/* Skip recognized sections with size 0. */
1703 		if (!sec_desc->data || sec_desc->data->d_size == 0)
1704 			continue;
1705 
1706 		switch (sec_desc->sec_type) {
1707 		case SEC_DATA:
1708 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1709 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
1710 							    sec_name, sec_idx,
1711 							    sec_desc->data->d_buf,
1712 							    sec_desc->data->d_size);
1713 			break;
1714 		case SEC_RODATA:
1715 			obj->has_rodata = true;
1716 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1717 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
1718 							    sec_name, sec_idx,
1719 							    sec_desc->data->d_buf,
1720 							    sec_desc->data->d_size);
1721 			break;
1722 		case SEC_BSS:
1723 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1724 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
1725 							    sec_name, sec_idx,
1726 							    NULL,
1727 							    sec_desc->data->d_size);
1728 			break;
1729 		default:
1730 			/* skip */
1731 			break;
1732 		}
1733 		if (err)
1734 			return err;
1735 	}
1736 	return 0;
1737 }
1738 
1739 
1740 static struct extern_desc *find_extern_by_name(const struct bpf_object *obj,
1741 					       const void *name)
1742 {
1743 	int i;
1744 
1745 	for (i = 0; i < obj->nr_extern; i++) {
1746 		if (strcmp(obj->externs[i].name, name) == 0)
1747 			return &obj->externs[i];
1748 	}
1749 	return NULL;
1750 }
1751 
1752 static int set_kcfg_value_tri(struct extern_desc *ext, void *ext_val,
1753 			      char value)
1754 {
1755 	switch (ext->kcfg.type) {
1756 	case KCFG_BOOL:
1757 		if (value == 'm') {
1758 			pr_warn("extern (kcfg) '%s': value '%c' implies tristate or char type\n",
1759 				ext->name, value);
1760 			return -EINVAL;
1761 		}
1762 		*(bool *)ext_val = value == 'y' ? true : false;
1763 		break;
1764 	case KCFG_TRISTATE:
1765 		if (value == 'y')
1766 			*(enum libbpf_tristate *)ext_val = TRI_YES;
1767 		else if (value == 'm')
1768 			*(enum libbpf_tristate *)ext_val = TRI_MODULE;
1769 		else /* value == 'n' */
1770 			*(enum libbpf_tristate *)ext_val = TRI_NO;
1771 		break;
1772 	case KCFG_CHAR:
1773 		*(char *)ext_val = value;
1774 		break;
1775 	case KCFG_UNKNOWN:
1776 	case KCFG_INT:
1777 	case KCFG_CHAR_ARR:
1778 	default:
1779 		pr_warn("extern (kcfg) '%s': value '%c' implies bool, tristate, or char type\n",
1780 			ext->name, value);
1781 		return -EINVAL;
1782 	}
1783 	ext->is_set = true;
1784 	return 0;
1785 }
1786 
1787 static int set_kcfg_value_str(struct extern_desc *ext, char *ext_val,
1788 			      const char *value)
1789 {
1790 	size_t len;
1791 
1792 	if (ext->kcfg.type != KCFG_CHAR_ARR) {
1793 		pr_warn("extern (kcfg) '%s': value '%s' implies char array type\n",
1794 			ext->name, value);
1795 		return -EINVAL;
1796 	}
1797 
1798 	len = strlen(value);
1799 	if (value[len - 1] != '"') {
1800 		pr_warn("extern (kcfg) '%s': invalid string config '%s'\n",
1801 			ext->name, value);
1802 		return -EINVAL;
1803 	}
1804 
1805 	/* strip quotes */
1806 	len -= 2;
1807 	if (len >= ext->kcfg.sz) {
1808 		pr_warn("extern (kcfg) '%s': long string '%s' of (%zu bytes) truncated to %d bytes\n",
1809 			ext->name, value, len, ext->kcfg.sz - 1);
1810 		len = ext->kcfg.sz - 1;
1811 	}
1812 	memcpy(ext_val, value + 1, len);
1813 	ext_val[len] = '\0';
1814 	ext->is_set = true;
1815 	return 0;
1816 }
1817 
1818 static int parse_u64(const char *value, __u64 *res)
1819 {
1820 	char *value_end;
1821 	int err;
1822 
1823 	errno = 0;
1824 	*res = strtoull(value, &value_end, 0);
1825 	if (errno) {
1826 		err = -errno;
1827 		pr_warn("failed to parse '%s' as integer: %d\n", value, err);
1828 		return err;
1829 	}
1830 	if (*value_end) {
1831 		pr_warn("failed to parse '%s' as integer completely\n", value);
1832 		return -EINVAL;
1833 	}
1834 	return 0;
1835 }
1836 
1837 static bool is_kcfg_value_in_range(const struct extern_desc *ext, __u64 v)
1838 {
1839 	int bit_sz = ext->kcfg.sz * 8;
1840 
1841 	if (ext->kcfg.sz == 8)
1842 		return true;
1843 
1844 	/* Validate that value stored in u64 fits in integer of `ext->sz`
1845 	 * bytes size without any loss of information. If the target integer
1846 	 * is signed, we rely on the following limits of integer type of
1847 	 * Y bits and subsequent transformation:
1848 	 *
1849 	 *     -2^(Y-1) <= X           <= 2^(Y-1) - 1
1850 	 *            0 <= X + 2^(Y-1) <= 2^Y - 1
1851 	 *            0 <= X + 2^(Y-1) <  2^Y
1852 	 *
1853 	 *  For unsigned target integer, check that all the (64 - Y) bits are
1854 	 *  zero.
1855 	 */
1856 	if (ext->kcfg.is_signed)
1857 		return v + (1ULL << (bit_sz - 1)) < (1ULL << bit_sz);
1858 	else
1859 		return (v >> bit_sz) == 0;
1860 }
1861 
1862 static int set_kcfg_value_num(struct extern_desc *ext, void *ext_val,
1863 			      __u64 value)
1864 {
1865 	if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR &&
1866 	    ext->kcfg.type != KCFG_BOOL) {
1867 		pr_warn("extern (kcfg) '%s': value '%llu' implies integer, char, or boolean type\n",
1868 			ext->name, (unsigned long long)value);
1869 		return -EINVAL;
1870 	}
1871 	if (ext->kcfg.type == KCFG_BOOL && value > 1) {
1872 		pr_warn("extern (kcfg) '%s': value '%llu' isn't boolean compatible\n",
1873 			ext->name, (unsigned long long)value);
1874 		return -EINVAL;
1875 
1876 	}
1877 	if (!is_kcfg_value_in_range(ext, value)) {
1878 		pr_warn("extern (kcfg) '%s': value '%llu' doesn't fit in %d bytes\n",
1879 			ext->name, (unsigned long long)value, ext->kcfg.sz);
1880 		return -ERANGE;
1881 	}
1882 	switch (ext->kcfg.sz) {
1883 	case 1:
1884 		*(__u8 *)ext_val = value;
1885 		break;
1886 	case 2:
1887 		*(__u16 *)ext_val = value;
1888 		break;
1889 	case 4:
1890 		*(__u32 *)ext_val = value;
1891 		break;
1892 	case 8:
1893 		*(__u64 *)ext_val = value;
1894 		break;
1895 	default:
1896 		return -EINVAL;
1897 	}
1898 	ext->is_set = true;
1899 	return 0;
1900 }
1901 
1902 static int bpf_object__process_kconfig_line(struct bpf_object *obj,
1903 					    char *buf, void *data)
1904 {
1905 	struct extern_desc *ext;
1906 	char *sep, *value;
1907 	int len, err = 0;
1908 	void *ext_val;
1909 	__u64 num;
1910 
1911 	if (!str_has_pfx(buf, "CONFIG_"))
1912 		return 0;
1913 
1914 	sep = strchr(buf, '=');
1915 	if (!sep) {
1916 		pr_warn("failed to parse '%s': no separator\n", buf);
1917 		return -EINVAL;
1918 	}
1919 
1920 	/* Trim ending '\n' */
1921 	len = strlen(buf);
1922 	if (buf[len - 1] == '\n')
1923 		buf[len - 1] = '\0';
1924 	/* Split on '=' and ensure that a value is present. */
1925 	*sep = '\0';
1926 	if (!sep[1]) {
1927 		*sep = '=';
1928 		pr_warn("failed to parse '%s': no value\n", buf);
1929 		return -EINVAL;
1930 	}
1931 
1932 	ext = find_extern_by_name(obj, buf);
1933 	if (!ext || ext->is_set)
1934 		return 0;
1935 
1936 	ext_val = data + ext->kcfg.data_off;
1937 	value = sep + 1;
1938 
1939 	switch (*value) {
1940 	case 'y': case 'n': case 'm':
1941 		err = set_kcfg_value_tri(ext, ext_val, *value);
1942 		break;
1943 	case '"':
1944 		err = set_kcfg_value_str(ext, ext_val, value);
1945 		break;
1946 	default:
1947 		/* assume integer */
1948 		err = parse_u64(value, &num);
1949 		if (err) {
1950 			pr_warn("extern (kcfg) '%s': value '%s' isn't a valid integer\n", ext->name, value);
1951 			return err;
1952 		}
1953 		if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR) {
1954 			pr_warn("extern (kcfg) '%s': value '%s' implies integer type\n", ext->name, value);
1955 			return -EINVAL;
1956 		}
1957 		err = set_kcfg_value_num(ext, ext_val, num);
1958 		break;
1959 	}
1960 	if (err)
1961 		return err;
1962 	pr_debug("extern (kcfg) '%s': set to %s\n", ext->name, value);
1963 	return 0;
1964 }
1965 
1966 static int bpf_object__read_kconfig_file(struct bpf_object *obj, void *data)
1967 {
1968 	char buf[PATH_MAX];
1969 	struct utsname uts;
1970 	int len, err = 0;
1971 	gzFile file;
1972 
1973 	uname(&uts);
1974 	len = snprintf(buf, PATH_MAX, "/boot/config-%s", uts.release);
1975 	if (len < 0)
1976 		return -EINVAL;
1977 	else if (len >= PATH_MAX)
1978 		return -ENAMETOOLONG;
1979 
1980 	/* gzopen also accepts uncompressed files. */
1981 	file = gzopen(buf, "r");
1982 	if (!file)
1983 		file = gzopen("/proc/config.gz", "r");
1984 
1985 	if (!file) {
1986 		pr_warn("failed to open system Kconfig\n");
1987 		return -ENOENT;
1988 	}
1989 
1990 	while (gzgets(file, buf, sizeof(buf))) {
1991 		err = bpf_object__process_kconfig_line(obj, buf, data);
1992 		if (err) {
1993 			pr_warn("error parsing system Kconfig line '%s': %d\n",
1994 				buf, err);
1995 			goto out;
1996 		}
1997 	}
1998 
1999 out:
2000 	gzclose(file);
2001 	return err;
2002 }
2003 
2004 static int bpf_object__read_kconfig_mem(struct bpf_object *obj,
2005 					const char *config, void *data)
2006 {
2007 	char buf[PATH_MAX];
2008 	int err = 0;
2009 	FILE *file;
2010 
2011 	file = fmemopen((void *)config, strlen(config), "r");
2012 	if (!file) {
2013 		err = -errno;
2014 		pr_warn("failed to open in-memory Kconfig: %d\n", err);
2015 		return err;
2016 	}
2017 
2018 	while (fgets(buf, sizeof(buf), file)) {
2019 		err = bpf_object__process_kconfig_line(obj, buf, data);
2020 		if (err) {
2021 			pr_warn("error parsing in-memory Kconfig line '%s': %d\n",
2022 				buf, err);
2023 			break;
2024 		}
2025 	}
2026 
2027 	fclose(file);
2028 	return err;
2029 }
2030 
2031 static int bpf_object__init_kconfig_map(struct bpf_object *obj)
2032 {
2033 	struct extern_desc *last_ext = NULL, *ext;
2034 	size_t map_sz;
2035 	int i, err;
2036 
2037 	for (i = 0; i < obj->nr_extern; i++) {
2038 		ext = &obj->externs[i];
2039 		if (ext->type == EXT_KCFG)
2040 			last_ext = ext;
2041 	}
2042 
2043 	if (!last_ext)
2044 		return 0;
2045 
2046 	map_sz = last_ext->kcfg.data_off + last_ext->kcfg.sz;
2047 	err = bpf_object__init_internal_map(obj, LIBBPF_MAP_KCONFIG,
2048 					    ".kconfig", obj->efile.symbols_shndx,
2049 					    NULL, map_sz);
2050 	if (err)
2051 		return err;
2052 
2053 	obj->kconfig_map_idx = obj->nr_maps - 1;
2054 
2055 	return 0;
2056 }
2057 
2058 const struct btf_type *
2059 skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id)
2060 {
2061 	const struct btf_type *t = btf__type_by_id(btf, id);
2062 
2063 	if (res_id)
2064 		*res_id = id;
2065 
2066 	while (btf_is_mod(t) || btf_is_typedef(t)) {
2067 		if (res_id)
2068 			*res_id = t->type;
2069 		t = btf__type_by_id(btf, t->type);
2070 	}
2071 
2072 	return t;
2073 }
2074 
2075 static const struct btf_type *
2076 resolve_func_ptr(const struct btf *btf, __u32 id, __u32 *res_id)
2077 {
2078 	const struct btf_type *t;
2079 
2080 	t = skip_mods_and_typedefs(btf, id, NULL);
2081 	if (!btf_is_ptr(t))
2082 		return NULL;
2083 
2084 	t = skip_mods_and_typedefs(btf, t->type, res_id);
2085 
2086 	return btf_is_func_proto(t) ? t : NULL;
2087 }
2088 
2089 static const char *__btf_kind_str(__u16 kind)
2090 {
2091 	switch (kind) {
2092 	case BTF_KIND_UNKN: return "void";
2093 	case BTF_KIND_INT: return "int";
2094 	case BTF_KIND_PTR: return "ptr";
2095 	case BTF_KIND_ARRAY: return "array";
2096 	case BTF_KIND_STRUCT: return "struct";
2097 	case BTF_KIND_UNION: return "union";
2098 	case BTF_KIND_ENUM: return "enum";
2099 	case BTF_KIND_FWD: return "fwd";
2100 	case BTF_KIND_TYPEDEF: return "typedef";
2101 	case BTF_KIND_VOLATILE: return "volatile";
2102 	case BTF_KIND_CONST: return "const";
2103 	case BTF_KIND_RESTRICT: return "restrict";
2104 	case BTF_KIND_FUNC: return "func";
2105 	case BTF_KIND_FUNC_PROTO: return "func_proto";
2106 	case BTF_KIND_VAR: return "var";
2107 	case BTF_KIND_DATASEC: return "datasec";
2108 	case BTF_KIND_FLOAT: return "float";
2109 	case BTF_KIND_DECL_TAG: return "decl_tag";
2110 	case BTF_KIND_TYPE_TAG: return "type_tag";
2111 	case BTF_KIND_ENUM64: return "enum64";
2112 	default: return "unknown";
2113 	}
2114 }
2115 
2116 const char *btf_kind_str(const struct btf_type *t)
2117 {
2118 	return __btf_kind_str(btf_kind(t));
2119 }
2120 
2121 /*
2122  * Fetch integer attribute of BTF map definition. Such attributes are
2123  * represented using a pointer to an array, in which dimensionality of array
2124  * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
2125  * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
2126  * type definition, while using only sizeof(void *) space in ELF data section.
2127  */
2128 static bool get_map_field_int(const char *map_name, const struct btf *btf,
2129 			      const struct btf_member *m, __u32 *res)
2130 {
2131 	const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
2132 	const char *name = btf__name_by_offset(btf, m->name_off);
2133 	const struct btf_array *arr_info;
2134 	const struct btf_type *arr_t;
2135 
2136 	if (!btf_is_ptr(t)) {
2137 		pr_warn("map '%s': attr '%s': expected PTR, got %s.\n",
2138 			map_name, name, btf_kind_str(t));
2139 		return false;
2140 	}
2141 
2142 	arr_t = btf__type_by_id(btf, t->type);
2143 	if (!arr_t) {
2144 		pr_warn("map '%s': attr '%s': type [%u] not found.\n",
2145 			map_name, name, t->type);
2146 		return false;
2147 	}
2148 	if (!btf_is_array(arr_t)) {
2149 		pr_warn("map '%s': attr '%s': expected ARRAY, got %s.\n",
2150 			map_name, name, btf_kind_str(arr_t));
2151 		return false;
2152 	}
2153 	arr_info = btf_array(arr_t);
2154 	*res = arr_info->nelems;
2155 	return true;
2156 }
2157 
2158 static int pathname_concat(char *buf, size_t buf_sz, const char *path, const char *name)
2159 {
2160 	int len;
2161 
2162 	len = snprintf(buf, buf_sz, "%s/%s", path, name);
2163 	if (len < 0)
2164 		return -EINVAL;
2165 	if (len >= buf_sz)
2166 		return -ENAMETOOLONG;
2167 
2168 	return 0;
2169 }
2170 
2171 static int build_map_pin_path(struct bpf_map *map, const char *path)
2172 {
2173 	char buf[PATH_MAX];
2174 	int err;
2175 
2176 	if (!path)
2177 		path = "/sys/fs/bpf";
2178 
2179 	err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
2180 	if (err)
2181 		return err;
2182 
2183 	return bpf_map__set_pin_path(map, buf);
2184 }
2185 
2186 /* should match definition in bpf_helpers.h */
2187 enum libbpf_pin_type {
2188 	LIBBPF_PIN_NONE,
2189 	/* PIN_BY_NAME: pin maps by name (in /sys/fs/bpf by default) */
2190 	LIBBPF_PIN_BY_NAME,
2191 };
2192 
2193 int parse_btf_map_def(const char *map_name, struct btf *btf,
2194 		      const struct btf_type *def_t, bool strict,
2195 		      struct btf_map_def *map_def, struct btf_map_def *inner_def)
2196 {
2197 	const struct btf_type *t;
2198 	const struct btf_member *m;
2199 	bool is_inner = inner_def == NULL;
2200 	int vlen, i;
2201 
2202 	vlen = btf_vlen(def_t);
2203 	m = btf_members(def_t);
2204 	for (i = 0; i < vlen; i++, m++) {
2205 		const char *name = btf__name_by_offset(btf, m->name_off);
2206 
2207 		if (!name) {
2208 			pr_warn("map '%s': invalid field #%d.\n", map_name, i);
2209 			return -EINVAL;
2210 		}
2211 		if (strcmp(name, "type") == 0) {
2212 			if (!get_map_field_int(map_name, btf, m, &map_def->map_type))
2213 				return -EINVAL;
2214 			map_def->parts |= MAP_DEF_MAP_TYPE;
2215 		} else if (strcmp(name, "max_entries") == 0) {
2216 			if (!get_map_field_int(map_name, btf, m, &map_def->max_entries))
2217 				return -EINVAL;
2218 			map_def->parts |= MAP_DEF_MAX_ENTRIES;
2219 		} else if (strcmp(name, "map_flags") == 0) {
2220 			if (!get_map_field_int(map_name, btf, m, &map_def->map_flags))
2221 				return -EINVAL;
2222 			map_def->parts |= MAP_DEF_MAP_FLAGS;
2223 		} else if (strcmp(name, "numa_node") == 0) {
2224 			if (!get_map_field_int(map_name, btf, m, &map_def->numa_node))
2225 				return -EINVAL;
2226 			map_def->parts |= MAP_DEF_NUMA_NODE;
2227 		} else if (strcmp(name, "key_size") == 0) {
2228 			__u32 sz;
2229 
2230 			if (!get_map_field_int(map_name, btf, m, &sz))
2231 				return -EINVAL;
2232 			if (map_def->key_size && map_def->key_size != sz) {
2233 				pr_warn("map '%s': conflicting key size %u != %u.\n",
2234 					map_name, map_def->key_size, sz);
2235 				return -EINVAL;
2236 			}
2237 			map_def->key_size = sz;
2238 			map_def->parts |= MAP_DEF_KEY_SIZE;
2239 		} else if (strcmp(name, "key") == 0) {
2240 			__s64 sz;
2241 
2242 			t = btf__type_by_id(btf, m->type);
2243 			if (!t) {
2244 				pr_warn("map '%s': key type [%d] not found.\n",
2245 					map_name, m->type);
2246 				return -EINVAL;
2247 			}
2248 			if (!btf_is_ptr(t)) {
2249 				pr_warn("map '%s': key spec is not PTR: %s.\n",
2250 					map_name, btf_kind_str(t));
2251 				return -EINVAL;
2252 			}
2253 			sz = btf__resolve_size(btf, t->type);
2254 			if (sz < 0) {
2255 				pr_warn("map '%s': can't determine key size for type [%u]: %zd.\n",
2256 					map_name, t->type, (ssize_t)sz);
2257 				return sz;
2258 			}
2259 			if (map_def->key_size && map_def->key_size != sz) {
2260 				pr_warn("map '%s': conflicting key size %u != %zd.\n",
2261 					map_name, map_def->key_size, (ssize_t)sz);
2262 				return -EINVAL;
2263 			}
2264 			map_def->key_size = sz;
2265 			map_def->key_type_id = t->type;
2266 			map_def->parts |= MAP_DEF_KEY_SIZE | MAP_DEF_KEY_TYPE;
2267 		} else if (strcmp(name, "value_size") == 0) {
2268 			__u32 sz;
2269 
2270 			if (!get_map_field_int(map_name, btf, m, &sz))
2271 				return -EINVAL;
2272 			if (map_def->value_size && map_def->value_size != sz) {
2273 				pr_warn("map '%s': conflicting value size %u != %u.\n",
2274 					map_name, map_def->value_size, sz);
2275 				return -EINVAL;
2276 			}
2277 			map_def->value_size = sz;
2278 			map_def->parts |= MAP_DEF_VALUE_SIZE;
2279 		} else if (strcmp(name, "value") == 0) {
2280 			__s64 sz;
2281 
2282 			t = btf__type_by_id(btf, m->type);
2283 			if (!t) {
2284 				pr_warn("map '%s': value type [%d] not found.\n",
2285 					map_name, m->type);
2286 				return -EINVAL;
2287 			}
2288 			if (!btf_is_ptr(t)) {
2289 				pr_warn("map '%s': value spec is not PTR: %s.\n",
2290 					map_name, btf_kind_str(t));
2291 				return -EINVAL;
2292 			}
2293 			sz = btf__resolve_size(btf, t->type);
2294 			if (sz < 0) {
2295 				pr_warn("map '%s': can't determine value size for type [%u]: %zd.\n",
2296 					map_name, t->type, (ssize_t)sz);
2297 				return sz;
2298 			}
2299 			if (map_def->value_size && map_def->value_size != sz) {
2300 				pr_warn("map '%s': conflicting value size %u != %zd.\n",
2301 					map_name, map_def->value_size, (ssize_t)sz);
2302 				return -EINVAL;
2303 			}
2304 			map_def->value_size = sz;
2305 			map_def->value_type_id = t->type;
2306 			map_def->parts |= MAP_DEF_VALUE_SIZE | MAP_DEF_VALUE_TYPE;
2307 		}
2308 		else if (strcmp(name, "values") == 0) {
2309 			bool is_map_in_map = bpf_map_type__is_map_in_map(map_def->map_type);
2310 			bool is_prog_array = map_def->map_type == BPF_MAP_TYPE_PROG_ARRAY;
2311 			const char *desc = is_map_in_map ? "map-in-map inner" : "prog-array value";
2312 			char inner_map_name[128];
2313 			int err;
2314 
2315 			if (is_inner) {
2316 				pr_warn("map '%s': multi-level inner maps not supported.\n",
2317 					map_name);
2318 				return -ENOTSUP;
2319 			}
2320 			if (i != vlen - 1) {
2321 				pr_warn("map '%s': '%s' member should be last.\n",
2322 					map_name, name);
2323 				return -EINVAL;
2324 			}
2325 			if (!is_map_in_map && !is_prog_array) {
2326 				pr_warn("map '%s': should be map-in-map or prog-array.\n",
2327 					map_name);
2328 				return -ENOTSUP;
2329 			}
2330 			if (map_def->value_size && map_def->value_size != 4) {
2331 				pr_warn("map '%s': conflicting value size %u != 4.\n",
2332 					map_name, map_def->value_size);
2333 				return -EINVAL;
2334 			}
2335 			map_def->value_size = 4;
2336 			t = btf__type_by_id(btf, m->type);
2337 			if (!t) {
2338 				pr_warn("map '%s': %s type [%d] not found.\n",
2339 					map_name, desc, m->type);
2340 				return -EINVAL;
2341 			}
2342 			if (!btf_is_array(t) || btf_array(t)->nelems) {
2343 				pr_warn("map '%s': %s spec is not a zero-sized array.\n",
2344 					map_name, desc);
2345 				return -EINVAL;
2346 			}
2347 			t = skip_mods_and_typedefs(btf, btf_array(t)->type, NULL);
2348 			if (!btf_is_ptr(t)) {
2349 				pr_warn("map '%s': %s def is of unexpected kind %s.\n",
2350 					map_name, desc, btf_kind_str(t));
2351 				return -EINVAL;
2352 			}
2353 			t = skip_mods_and_typedefs(btf, t->type, NULL);
2354 			if (is_prog_array) {
2355 				if (!btf_is_func_proto(t)) {
2356 					pr_warn("map '%s': prog-array value def is of unexpected kind %s.\n",
2357 						map_name, btf_kind_str(t));
2358 					return -EINVAL;
2359 				}
2360 				continue;
2361 			}
2362 			if (!btf_is_struct(t)) {
2363 				pr_warn("map '%s': map-in-map inner def is of unexpected kind %s.\n",
2364 					map_name, btf_kind_str(t));
2365 				return -EINVAL;
2366 			}
2367 
2368 			snprintf(inner_map_name, sizeof(inner_map_name), "%s.inner", map_name);
2369 			err = parse_btf_map_def(inner_map_name, btf, t, strict, inner_def, NULL);
2370 			if (err)
2371 				return err;
2372 
2373 			map_def->parts |= MAP_DEF_INNER_MAP;
2374 		} else if (strcmp(name, "pinning") == 0) {
2375 			__u32 val;
2376 
2377 			if (is_inner) {
2378 				pr_warn("map '%s': inner def can't be pinned.\n", map_name);
2379 				return -EINVAL;
2380 			}
2381 			if (!get_map_field_int(map_name, btf, m, &val))
2382 				return -EINVAL;
2383 			if (val != LIBBPF_PIN_NONE && val != LIBBPF_PIN_BY_NAME) {
2384 				pr_warn("map '%s': invalid pinning value %u.\n",
2385 					map_name, val);
2386 				return -EINVAL;
2387 			}
2388 			map_def->pinning = val;
2389 			map_def->parts |= MAP_DEF_PINNING;
2390 		} else if (strcmp(name, "map_extra") == 0) {
2391 			__u32 map_extra;
2392 
2393 			if (!get_map_field_int(map_name, btf, m, &map_extra))
2394 				return -EINVAL;
2395 			map_def->map_extra = map_extra;
2396 			map_def->parts |= MAP_DEF_MAP_EXTRA;
2397 		} else {
2398 			if (strict) {
2399 				pr_warn("map '%s': unknown field '%s'.\n", map_name, name);
2400 				return -ENOTSUP;
2401 			}
2402 			pr_debug("map '%s': ignoring unknown field '%s'.\n", map_name, name);
2403 		}
2404 	}
2405 
2406 	if (map_def->map_type == BPF_MAP_TYPE_UNSPEC) {
2407 		pr_warn("map '%s': map type isn't specified.\n", map_name);
2408 		return -EINVAL;
2409 	}
2410 
2411 	return 0;
2412 }
2413 
2414 static size_t adjust_ringbuf_sz(size_t sz)
2415 {
2416 	__u32 page_sz = sysconf(_SC_PAGE_SIZE);
2417 	__u32 mul;
2418 
2419 	/* if user forgot to set any size, make sure they see error */
2420 	if (sz == 0)
2421 		return 0;
2422 	/* Kernel expects BPF_MAP_TYPE_RINGBUF's max_entries to be
2423 	 * a power-of-2 multiple of kernel's page size. If user diligently
2424 	 * satisified these conditions, pass the size through.
2425 	 */
2426 	if ((sz % page_sz) == 0 && is_pow_of_2(sz / page_sz))
2427 		return sz;
2428 
2429 	/* Otherwise find closest (page_sz * power_of_2) product bigger than
2430 	 * user-set size to satisfy both user size request and kernel
2431 	 * requirements and substitute correct max_entries for map creation.
2432 	 */
2433 	for (mul = 1; mul <= UINT_MAX / page_sz; mul <<= 1) {
2434 		if (mul * page_sz > sz)
2435 			return mul * page_sz;
2436 	}
2437 
2438 	/* if it's impossible to satisfy the conditions (i.e., user size is
2439 	 * very close to UINT_MAX but is not a power-of-2 multiple of
2440 	 * page_size) then just return original size and let kernel reject it
2441 	 */
2442 	return sz;
2443 }
2444 
2445 static bool map_is_ringbuf(const struct bpf_map *map)
2446 {
2447 	return map->def.type == BPF_MAP_TYPE_RINGBUF ||
2448 	       map->def.type == BPF_MAP_TYPE_USER_RINGBUF;
2449 }
2450 
2451 static void fill_map_from_def(struct bpf_map *map, const struct btf_map_def *def)
2452 {
2453 	map->def.type = def->map_type;
2454 	map->def.key_size = def->key_size;
2455 	map->def.value_size = def->value_size;
2456 	map->def.max_entries = def->max_entries;
2457 	map->def.map_flags = def->map_flags;
2458 	map->map_extra = def->map_extra;
2459 
2460 	map->numa_node = def->numa_node;
2461 	map->btf_key_type_id = def->key_type_id;
2462 	map->btf_value_type_id = def->value_type_id;
2463 
2464 	/* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
2465 	if (map_is_ringbuf(map))
2466 		map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
2467 
2468 	if (def->parts & MAP_DEF_MAP_TYPE)
2469 		pr_debug("map '%s': found type = %u.\n", map->name, def->map_type);
2470 
2471 	if (def->parts & MAP_DEF_KEY_TYPE)
2472 		pr_debug("map '%s': found key [%u], sz = %u.\n",
2473 			 map->name, def->key_type_id, def->key_size);
2474 	else if (def->parts & MAP_DEF_KEY_SIZE)
2475 		pr_debug("map '%s': found key_size = %u.\n", map->name, def->key_size);
2476 
2477 	if (def->parts & MAP_DEF_VALUE_TYPE)
2478 		pr_debug("map '%s': found value [%u], sz = %u.\n",
2479 			 map->name, def->value_type_id, def->value_size);
2480 	else if (def->parts & MAP_DEF_VALUE_SIZE)
2481 		pr_debug("map '%s': found value_size = %u.\n", map->name, def->value_size);
2482 
2483 	if (def->parts & MAP_DEF_MAX_ENTRIES)
2484 		pr_debug("map '%s': found max_entries = %u.\n", map->name, def->max_entries);
2485 	if (def->parts & MAP_DEF_MAP_FLAGS)
2486 		pr_debug("map '%s': found map_flags = 0x%x.\n", map->name, def->map_flags);
2487 	if (def->parts & MAP_DEF_MAP_EXTRA)
2488 		pr_debug("map '%s': found map_extra = 0x%llx.\n", map->name,
2489 			 (unsigned long long)def->map_extra);
2490 	if (def->parts & MAP_DEF_PINNING)
2491 		pr_debug("map '%s': found pinning = %u.\n", map->name, def->pinning);
2492 	if (def->parts & MAP_DEF_NUMA_NODE)
2493 		pr_debug("map '%s': found numa_node = %u.\n", map->name, def->numa_node);
2494 
2495 	if (def->parts & MAP_DEF_INNER_MAP)
2496 		pr_debug("map '%s': found inner map definition.\n", map->name);
2497 }
2498 
2499 static const char *btf_var_linkage_str(__u32 linkage)
2500 {
2501 	switch (linkage) {
2502 	case BTF_VAR_STATIC: return "static";
2503 	case BTF_VAR_GLOBAL_ALLOCATED: return "global";
2504 	case BTF_VAR_GLOBAL_EXTERN: return "extern";
2505 	default: return "unknown";
2506 	}
2507 }
2508 
2509 static int bpf_object__init_user_btf_map(struct bpf_object *obj,
2510 					 const struct btf_type *sec,
2511 					 int var_idx, int sec_idx,
2512 					 const Elf_Data *data, bool strict,
2513 					 const char *pin_root_path)
2514 {
2515 	struct btf_map_def map_def = {}, inner_def = {};
2516 	const struct btf_type *var, *def;
2517 	const struct btf_var_secinfo *vi;
2518 	const struct btf_var *var_extra;
2519 	const char *map_name;
2520 	struct bpf_map *map;
2521 	int err;
2522 
2523 	vi = btf_var_secinfos(sec) + var_idx;
2524 	var = btf__type_by_id(obj->btf, vi->type);
2525 	var_extra = btf_var(var);
2526 	map_name = btf__name_by_offset(obj->btf, var->name_off);
2527 
2528 	if (map_name == NULL || map_name[0] == '\0') {
2529 		pr_warn("map #%d: empty name.\n", var_idx);
2530 		return -EINVAL;
2531 	}
2532 	if ((__u64)vi->offset + vi->size > data->d_size) {
2533 		pr_warn("map '%s' BTF data is corrupted.\n", map_name);
2534 		return -EINVAL;
2535 	}
2536 	if (!btf_is_var(var)) {
2537 		pr_warn("map '%s': unexpected var kind %s.\n",
2538 			map_name, btf_kind_str(var));
2539 		return -EINVAL;
2540 	}
2541 	if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED) {
2542 		pr_warn("map '%s': unsupported map linkage %s.\n",
2543 			map_name, btf_var_linkage_str(var_extra->linkage));
2544 		return -EOPNOTSUPP;
2545 	}
2546 
2547 	def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
2548 	if (!btf_is_struct(def)) {
2549 		pr_warn("map '%s': unexpected def kind %s.\n",
2550 			map_name, btf_kind_str(var));
2551 		return -EINVAL;
2552 	}
2553 	if (def->size > vi->size) {
2554 		pr_warn("map '%s': invalid def size.\n", map_name);
2555 		return -EINVAL;
2556 	}
2557 
2558 	map = bpf_object__add_map(obj);
2559 	if (IS_ERR(map))
2560 		return PTR_ERR(map);
2561 	map->name = strdup(map_name);
2562 	if (!map->name) {
2563 		pr_warn("map '%s': failed to alloc map name.\n", map_name);
2564 		return -ENOMEM;
2565 	}
2566 	map->libbpf_type = LIBBPF_MAP_UNSPEC;
2567 	map->def.type = BPF_MAP_TYPE_UNSPEC;
2568 	map->sec_idx = sec_idx;
2569 	map->sec_offset = vi->offset;
2570 	map->btf_var_idx = var_idx;
2571 	pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
2572 		 map_name, map->sec_idx, map->sec_offset);
2573 
2574 	err = parse_btf_map_def(map->name, obj->btf, def, strict, &map_def, &inner_def);
2575 	if (err)
2576 		return err;
2577 
2578 	fill_map_from_def(map, &map_def);
2579 
2580 	if (map_def.pinning == LIBBPF_PIN_BY_NAME) {
2581 		err = build_map_pin_path(map, pin_root_path);
2582 		if (err) {
2583 			pr_warn("map '%s': couldn't build pin path.\n", map->name);
2584 			return err;
2585 		}
2586 	}
2587 
2588 	if (map_def.parts & MAP_DEF_INNER_MAP) {
2589 		map->inner_map = calloc(1, sizeof(*map->inner_map));
2590 		if (!map->inner_map)
2591 			return -ENOMEM;
2592 		map->inner_map->fd = -1;
2593 		map->inner_map->sec_idx = sec_idx;
2594 		map->inner_map->name = malloc(strlen(map_name) + sizeof(".inner") + 1);
2595 		if (!map->inner_map->name)
2596 			return -ENOMEM;
2597 		sprintf(map->inner_map->name, "%s.inner", map_name);
2598 
2599 		fill_map_from_def(map->inner_map, &inner_def);
2600 	}
2601 
2602 	err = map_fill_btf_type_info(obj, map);
2603 	if (err)
2604 		return err;
2605 
2606 	return 0;
2607 }
2608 
2609 static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict,
2610 					  const char *pin_root_path)
2611 {
2612 	const struct btf_type *sec = NULL;
2613 	int nr_types, i, vlen, err;
2614 	const struct btf_type *t;
2615 	const char *name;
2616 	Elf_Data *data;
2617 	Elf_Scn *scn;
2618 
2619 	if (obj->efile.btf_maps_shndx < 0)
2620 		return 0;
2621 
2622 	scn = elf_sec_by_idx(obj, obj->efile.btf_maps_shndx);
2623 	data = elf_sec_data(obj, scn);
2624 	if (!scn || !data) {
2625 		pr_warn("elf: failed to get %s map definitions for %s\n",
2626 			MAPS_ELF_SEC, obj->path);
2627 		return -EINVAL;
2628 	}
2629 
2630 	nr_types = btf__type_cnt(obj->btf);
2631 	for (i = 1; i < nr_types; i++) {
2632 		t = btf__type_by_id(obj->btf, i);
2633 		if (!btf_is_datasec(t))
2634 			continue;
2635 		name = btf__name_by_offset(obj->btf, t->name_off);
2636 		if (strcmp(name, MAPS_ELF_SEC) == 0) {
2637 			sec = t;
2638 			obj->efile.btf_maps_sec_btf_id = i;
2639 			break;
2640 		}
2641 	}
2642 
2643 	if (!sec) {
2644 		pr_warn("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
2645 		return -ENOENT;
2646 	}
2647 
2648 	vlen = btf_vlen(sec);
2649 	for (i = 0; i < vlen; i++) {
2650 		err = bpf_object__init_user_btf_map(obj, sec, i,
2651 						    obj->efile.btf_maps_shndx,
2652 						    data, strict,
2653 						    pin_root_path);
2654 		if (err)
2655 			return err;
2656 	}
2657 
2658 	return 0;
2659 }
2660 
2661 static int bpf_object__init_maps(struct bpf_object *obj,
2662 				 const struct bpf_object_open_opts *opts)
2663 {
2664 	const char *pin_root_path;
2665 	bool strict;
2666 	int err = 0;
2667 
2668 	strict = !OPTS_GET(opts, relaxed_maps, false);
2669 	pin_root_path = OPTS_GET(opts, pin_root_path, NULL);
2670 
2671 	err = bpf_object__init_user_btf_maps(obj, strict, pin_root_path);
2672 	err = err ?: bpf_object__init_global_data_maps(obj);
2673 	err = err ?: bpf_object__init_kconfig_map(obj);
2674 	err = err ?: bpf_object_init_struct_ops(obj);
2675 
2676 	return err;
2677 }
2678 
2679 static bool section_have_execinstr(struct bpf_object *obj, int idx)
2680 {
2681 	Elf64_Shdr *sh;
2682 
2683 	sh = elf_sec_hdr(obj, elf_sec_by_idx(obj, idx));
2684 	if (!sh)
2685 		return false;
2686 
2687 	return sh->sh_flags & SHF_EXECINSTR;
2688 }
2689 
2690 static bool btf_needs_sanitization(struct bpf_object *obj)
2691 {
2692 	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
2693 	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
2694 	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
2695 	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
2696 	bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
2697 	bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
2698 	bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
2699 
2700 	return !has_func || !has_datasec || !has_func_global || !has_float ||
2701 	       !has_decl_tag || !has_type_tag || !has_enum64;
2702 }
2703 
2704 static int bpf_object__sanitize_btf(struct bpf_object *obj, struct btf *btf)
2705 {
2706 	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
2707 	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
2708 	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
2709 	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
2710 	bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
2711 	bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
2712 	bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
2713 	int enum64_placeholder_id = 0;
2714 	struct btf_type *t;
2715 	int i, j, vlen;
2716 
2717 	for (i = 1; i < btf__type_cnt(btf); i++) {
2718 		t = (struct btf_type *)btf__type_by_id(btf, i);
2719 
2720 		if ((!has_datasec && btf_is_var(t)) || (!has_decl_tag && btf_is_decl_tag(t))) {
2721 			/* replace VAR/DECL_TAG with INT */
2722 			t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
2723 			/*
2724 			 * using size = 1 is the safest choice, 4 will be too
2725 			 * big and cause kernel BTF validation failure if
2726 			 * original variable took less than 4 bytes
2727 			 */
2728 			t->size = 1;
2729 			*(int *)(t + 1) = BTF_INT_ENC(0, 0, 8);
2730 		} else if (!has_datasec && btf_is_datasec(t)) {
2731 			/* replace DATASEC with STRUCT */
2732 			const struct btf_var_secinfo *v = btf_var_secinfos(t);
2733 			struct btf_member *m = btf_members(t);
2734 			struct btf_type *vt;
2735 			char *name;
2736 
2737 			name = (char *)btf__name_by_offset(btf, t->name_off);
2738 			while (*name) {
2739 				if (*name == '.')
2740 					*name = '_';
2741 				name++;
2742 			}
2743 
2744 			vlen = btf_vlen(t);
2745 			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
2746 			for (j = 0; j < vlen; j++, v++, m++) {
2747 				/* order of field assignments is important */
2748 				m->offset = v->offset * 8;
2749 				m->type = v->type;
2750 				/* preserve variable name as member name */
2751 				vt = (void *)btf__type_by_id(btf, v->type);
2752 				m->name_off = vt->name_off;
2753 			}
2754 		} else if (!has_func && btf_is_func_proto(t)) {
2755 			/* replace FUNC_PROTO with ENUM */
2756 			vlen = btf_vlen(t);
2757 			t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
2758 			t->size = sizeof(__u32); /* kernel enforced */
2759 		} else if (!has_func && btf_is_func(t)) {
2760 			/* replace FUNC with TYPEDEF */
2761 			t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
2762 		} else if (!has_func_global && btf_is_func(t)) {
2763 			/* replace BTF_FUNC_GLOBAL with BTF_FUNC_STATIC */
2764 			t->info = BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0);
2765 		} else if (!has_float && btf_is_float(t)) {
2766 			/* replace FLOAT with an equally-sized empty STRUCT;
2767 			 * since C compilers do not accept e.g. "float" as a
2768 			 * valid struct name, make it anonymous
2769 			 */
2770 			t->name_off = 0;
2771 			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, 0);
2772 		} else if (!has_type_tag && btf_is_type_tag(t)) {
2773 			/* replace TYPE_TAG with a CONST */
2774 			t->name_off = 0;
2775 			t->info = BTF_INFO_ENC(BTF_KIND_CONST, 0, 0);
2776 		} else if (!has_enum64 && btf_is_enum(t)) {
2777 			/* clear the kflag */
2778 			t->info = btf_type_info(btf_kind(t), btf_vlen(t), false);
2779 		} else if (!has_enum64 && btf_is_enum64(t)) {
2780 			/* replace ENUM64 with a union */
2781 			struct btf_member *m;
2782 
2783 			if (enum64_placeholder_id == 0) {
2784 				enum64_placeholder_id = btf__add_int(btf, "enum64_placeholder", 1, 0);
2785 				if (enum64_placeholder_id < 0)
2786 					return enum64_placeholder_id;
2787 
2788 				t = (struct btf_type *)btf__type_by_id(btf, i);
2789 			}
2790 
2791 			m = btf_members(t);
2792 			vlen = btf_vlen(t);
2793 			t->info = BTF_INFO_ENC(BTF_KIND_UNION, 0, vlen);
2794 			for (j = 0; j < vlen; j++, m++) {
2795 				m->type = enum64_placeholder_id;
2796 				m->offset = 0;
2797 			}
2798 		}
2799 	}
2800 
2801 	return 0;
2802 }
2803 
2804 static bool libbpf_needs_btf(const struct bpf_object *obj)
2805 {
2806 	return obj->efile.btf_maps_shndx >= 0 ||
2807 	       obj->efile.st_ops_shndx >= 0 ||
2808 	       obj->efile.st_ops_link_shndx >= 0 ||
2809 	       obj->nr_extern > 0;
2810 }
2811 
2812 static bool kernel_needs_btf(const struct bpf_object *obj)
2813 {
2814 	return obj->efile.st_ops_shndx >= 0 || obj->efile.st_ops_link_shndx >= 0;
2815 }
2816 
2817 static int bpf_object__init_btf(struct bpf_object *obj,
2818 				Elf_Data *btf_data,
2819 				Elf_Data *btf_ext_data)
2820 {
2821 	int err = -ENOENT;
2822 
2823 	if (btf_data) {
2824 		obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
2825 		err = libbpf_get_error(obj->btf);
2826 		if (err) {
2827 			obj->btf = NULL;
2828 			pr_warn("Error loading ELF section %s: %d.\n", BTF_ELF_SEC, err);
2829 			goto out;
2830 		}
2831 		/* enforce 8-byte pointers for BPF-targeted BTFs */
2832 		btf__set_pointer_size(obj->btf, 8);
2833 	}
2834 	if (btf_ext_data) {
2835 		struct btf_ext_info *ext_segs[3];
2836 		int seg_num, sec_num;
2837 
2838 		if (!obj->btf) {
2839 			pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
2840 				 BTF_EXT_ELF_SEC, BTF_ELF_SEC);
2841 			goto out;
2842 		}
2843 		obj->btf_ext = btf_ext__new(btf_ext_data->d_buf, btf_ext_data->d_size);
2844 		err = libbpf_get_error(obj->btf_ext);
2845 		if (err) {
2846 			pr_warn("Error loading ELF section %s: %d. Ignored and continue.\n",
2847 				BTF_EXT_ELF_SEC, err);
2848 			obj->btf_ext = NULL;
2849 			goto out;
2850 		}
2851 
2852 		/* setup .BTF.ext to ELF section mapping */
2853 		ext_segs[0] = &obj->btf_ext->func_info;
2854 		ext_segs[1] = &obj->btf_ext->line_info;
2855 		ext_segs[2] = &obj->btf_ext->core_relo_info;
2856 		for (seg_num = 0; seg_num < ARRAY_SIZE(ext_segs); seg_num++) {
2857 			struct btf_ext_info *seg = ext_segs[seg_num];
2858 			const struct btf_ext_info_sec *sec;
2859 			const char *sec_name;
2860 			Elf_Scn *scn;
2861 
2862 			if (seg->sec_cnt == 0)
2863 				continue;
2864 
2865 			seg->sec_idxs = calloc(seg->sec_cnt, sizeof(*seg->sec_idxs));
2866 			if (!seg->sec_idxs) {
2867 				err = -ENOMEM;
2868 				goto out;
2869 			}
2870 
2871 			sec_num = 0;
2872 			for_each_btf_ext_sec(seg, sec) {
2873 				/* preventively increment index to avoid doing
2874 				 * this before every continue below
2875 				 */
2876 				sec_num++;
2877 
2878 				sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
2879 				if (str_is_empty(sec_name))
2880 					continue;
2881 				scn = elf_sec_by_name(obj, sec_name);
2882 				if (!scn)
2883 					continue;
2884 
2885 				seg->sec_idxs[sec_num - 1] = elf_ndxscn(scn);
2886 			}
2887 		}
2888 	}
2889 out:
2890 	if (err && libbpf_needs_btf(obj)) {
2891 		pr_warn("BTF is required, but is missing or corrupted.\n");
2892 		return err;
2893 	}
2894 	return 0;
2895 }
2896 
2897 static int compare_vsi_off(const void *_a, const void *_b)
2898 {
2899 	const struct btf_var_secinfo *a = _a;
2900 	const struct btf_var_secinfo *b = _b;
2901 
2902 	return a->offset - b->offset;
2903 }
2904 
2905 static int btf_fixup_datasec(struct bpf_object *obj, struct btf *btf,
2906 			     struct btf_type *t)
2907 {
2908 	__u32 size = 0, i, vars = btf_vlen(t);
2909 	const char *sec_name = btf__name_by_offset(btf, t->name_off);
2910 	struct btf_var_secinfo *vsi;
2911 	bool fixup_offsets = false;
2912 	int err;
2913 
2914 	if (!sec_name) {
2915 		pr_debug("No name found in string section for DATASEC kind.\n");
2916 		return -ENOENT;
2917 	}
2918 
2919 	/* Extern-backing datasecs (.ksyms, .kconfig) have their size and
2920 	 * variable offsets set at the previous step. Further, not every
2921 	 * extern BTF VAR has corresponding ELF symbol preserved, so we skip
2922 	 * all fixups altogether for such sections and go straight to sorting
2923 	 * VARs within their DATASEC.
2924 	 */
2925 	if (strcmp(sec_name, KCONFIG_SEC) == 0 || strcmp(sec_name, KSYMS_SEC) == 0)
2926 		goto sort_vars;
2927 
2928 	/* Clang leaves DATASEC size and VAR offsets as zeroes, so we need to
2929 	 * fix this up. But BPF static linker already fixes this up and fills
2930 	 * all the sizes and offsets during static linking. So this step has
2931 	 * to be optional. But the STV_HIDDEN handling is non-optional for any
2932 	 * non-extern DATASEC, so the variable fixup loop below handles both
2933 	 * functions at the same time, paying the cost of BTF VAR <-> ELF
2934 	 * symbol matching just once.
2935 	 */
2936 	if (t->size == 0) {
2937 		err = find_elf_sec_sz(obj, sec_name, &size);
2938 		if (err || !size) {
2939 			pr_debug("sec '%s': failed to determine size from ELF: size %u, err %d\n",
2940 				 sec_name, size, err);
2941 			return -ENOENT;
2942 		}
2943 
2944 		t->size = size;
2945 		fixup_offsets = true;
2946 	}
2947 
2948 	for (i = 0, vsi = btf_var_secinfos(t); i < vars; i++, vsi++) {
2949 		const struct btf_type *t_var;
2950 		struct btf_var *var;
2951 		const char *var_name;
2952 		Elf64_Sym *sym;
2953 
2954 		t_var = btf__type_by_id(btf, vsi->type);
2955 		if (!t_var || !btf_is_var(t_var)) {
2956 			pr_debug("sec '%s': unexpected non-VAR type found\n", sec_name);
2957 			return -EINVAL;
2958 		}
2959 
2960 		var = btf_var(t_var);
2961 		if (var->linkage == BTF_VAR_STATIC || var->linkage == BTF_VAR_GLOBAL_EXTERN)
2962 			continue;
2963 
2964 		var_name = btf__name_by_offset(btf, t_var->name_off);
2965 		if (!var_name) {
2966 			pr_debug("sec '%s': failed to find name of DATASEC's member #%d\n",
2967 				 sec_name, i);
2968 			return -ENOENT;
2969 		}
2970 
2971 		sym = find_elf_var_sym(obj, var_name);
2972 		if (IS_ERR(sym)) {
2973 			pr_debug("sec '%s': failed to find ELF symbol for VAR '%s'\n",
2974 				 sec_name, var_name);
2975 			return -ENOENT;
2976 		}
2977 
2978 		if (fixup_offsets)
2979 			vsi->offset = sym->st_value;
2980 
2981 		/* if variable is a global/weak symbol, but has restricted
2982 		 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF VAR
2983 		 * as static. This follows similar logic for functions (BPF
2984 		 * subprogs) and influences libbpf's further decisions about
2985 		 * whether to make global data BPF array maps as
2986 		 * BPF_F_MMAPABLE.
2987 		 */
2988 		if (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
2989 		    || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL)
2990 			var->linkage = BTF_VAR_STATIC;
2991 	}
2992 
2993 sort_vars:
2994 	qsort(btf_var_secinfos(t), vars, sizeof(*vsi), compare_vsi_off);
2995 	return 0;
2996 }
2997 
2998 static int bpf_object_fixup_btf(struct bpf_object *obj)
2999 {
3000 	int i, n, err = 0;
3001 
3002 	if (!obj->btf)
3003 		return 0;
3004 
3005 	n = btf__type_cnt(obj->btf);
3006 	for (i = 1; i < n; i++) {
3007 		struct btf_type *t = btf_type_by_id(obj->btf, i);
3008 
3009 		/* Loader needs to fix up some of the things compiler
3010 		 * couldn't get its hands on while emitting BTF. This
3011 		 * is section size and global variable offset. We use
3012 		 * the info from the ELF itself for this purpose.
3013 		 */
3014 		if (btf_is_datasec(t)) {
3015 			err = btf_fixup_datasec(obj, obj->btf, t);
3016 			if (err)
3017 				return err;
3018 		}
3019 	}
3020 
3021 	return 0;
3022 }
3023 
3024 static bool prog_needs_vmlinux_btf(struct bpf_program *prog)
3025 {
3026 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
3027 	    prog->type == BPF_PROG_TYPE_LSM)
3028 		return true;
3029 
3030 	/* BPF_PROG_TYPE_TRACING programs which do not attach to other programs
3031 	 * also need vmlinux BTF
3032 	 */
3033 	if (prog->type == BPF_PROG_TYPE_TRACING && !prog->attach_prog_fd)
3034 		return true;
3035 
3036 	return false;
3037 }
3038 
3039 static bool obj_needs_vmlinux_btf(const struct bpf_object *obj)
3040 {
3041 	struct bpf_program *prog;
3042 	int i;
3043 
3044 	/* CO-RE relocations need kernel BTF, only when btf_custom_path
3045 	 * is not specified
3046 	 */
3047 	if (obj->btf_ext && obj->btf_ext->core_relo_info.len && !obj->btf_custom_path)
3048 		return true;
3049 
3050 	/* Support for typed ksyms needs kernel BTF */
3051 	for (i = 0; i < obj->nr_extern; i++) {
3052 		const struct extern_desc *ext;
3053 
3054 		ext = &obj->externs[i];
3055 		if (ext->type == EXT_KSYM && ext->ksym.type_id)
3056 			return true;
3057 	}
3058 
3059 	bpf_object__for_each_program(prog, obj) {
3060 		if (!prog->autoload)
3061 			continue;
3062 		if (prog_needs_vmlinux_btf(prog))
3063 			return true;
3064 	}
3065 
3066 	return false;
3067 }
3068 
3069 static int bpf_object__load_vmlinux_btf(struct bpf_object *obj, bool force)
3070 {
3071 	int err;
3072 
3073 	/* btf_vmlinux could be loaded earlier */
3074 	if (obj->btf_vmlinux || obj->gen_loader)
3075 		return 0;
3076 
3077 	if (!force && !obj_needs_vmlinux_btf(obj))
3078 		return 0;
3079 
3080 	obj->btf_vmlinux = btf__load_vmlinux_btf();
3081 	err = libbpf_get_error(obj->btf_vmlinux);
3082 	if (err) {
3083 		pr_warn("Error loading vmlinux BTF: %d\n", err);
3084 		obj->btf_vmlinux = NULL;
3085 		return err;
3086 	}
3087 	return 0;
3088 }
3089 
3090 static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
3091 {
3092 	struct btf *kern_btf = obj->btf;
3093 	bool btf_mandatory, sanitize;
3094 	int i, err = 0;
3095 
3096 	if (!obj->btf)
3097 		return 0;
3098 
3099 	if (!kernel_supports(obj, FEAT_BTF)) {
3100 		if (kernel_needs_btf(obj)) {
3101 			err = -EOPNOTSUPP;
3102 			goto report;
3103 		}
3104 		pr_debug("Kernel doesn't support BTF, skipping uploading it.\n");
3105 		return 0;
3106 	}
3107 
3108 	/* Even though some subprogs are global/weak, user might prefer more
3109 	 * permissive BPF verification process that BPF verifier performs for
3110 	 * static functions, taking into account more context from the caller
3111 	 * functions. In such case, they need to mark such subprogs with
3112 	 * __attribute__((visibility("hidden"))) and libbpf will adjust
3113 	 * corresponding FUNC BTF type to be marked as static and trigger more
3114 	 * involved BPF verification process.
3115 	 */
3116 	for (i = 0; i < obj->nr_programs; i++) {
3117 		struct bpf_program *prog = &obj->programs[i];
3118 		struct btf_type *t;
3119 		const char *name;
3120 		int j, n;
3121 
3122 		if (!prog->mark_btf_static || !prog_is_subprog(obj, prog))
3123 			continue;
3124 
3125 		n = btf__type_cnt(obj->btf);
3126 		for (j = 1; j < n; j++) {
3127 			t = btf_type_by_id(obj->btf, j);
3128 			if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL)
3129 				continue;
3130 
3131 			name = btf__str_by_offset(obj->btf, t->name_off);
3132 			if (strcmp(name, prog->name) != 0)
3133 				continue;
3134 
3135 			t->info = btf_type_info(BTF_KIND_FUNC, BTF_FUNC_STATIC, 0);
3136 			break;
3137 		}
3138 	}
3139 
3140 	sanitize = btf_needs_sanitization(obj);
3141 	if (sanitize) {
3142 		const void *raw_data;
3143 		__u32 sz;
3144 
3145 		/* clone BTF to sanitize a copy and leave the original intact */
3146 		raw_data = btf__raw_data(obj->btf, &sz);
3147 		kern_btf = btf__new(raw_data, sz);
3148 		err = libbpf_get_error(kern_btf);
3149 		if (err)
3150 			return err;
3151 
3152 		/* enforce 8-byte pointers for BPF-targeted BTFs */
3153 		btf__set_pointer_size(obj->btf, 8);
3154 		err = bpf_object__sanitize_btf(obj, kern_btf);
3155 		if (err)
3156 			return err;
3157 	}
3158 
3159 	if (obj->gen_loader) {
3160 		__u32 raw_size = 0;
3161 		const void *raw_data = btf__raw_data(kern_btf, &raw_size);
3162 
3163 		if (!raw_data)
3164 			return -ENOMEM;
3165 		bpf_gen__load_btf(obj->gen_loader, raw_data, raw_size);
3166 		/* Pretend to have valid FD to pass various fd >= 0 checks.
3167 		 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
3168 		 */
3169 		btf__set_fd(kern_btf, 0);
3170 	} else {
3171 		/* currently BPF_BTF_LOAD only supports log_level 1 */
3172 		err = btf_load_into_kernel(kern_btf, obj->log_buf, obj->log_size,
3173 					   obj->log_level ? 1 : 0);
3174 	}
3175 	if (sanitize) {
3176 		if (!err) {
3177 			/* move fd to libbpf's BTF */
3178 			btf__set_fd(obj->btf, btf__fd(kern_btf));
3179 			btf__set_fd(kern_btf, -1);
3180 		}
3181 		btf__free(kern_btf);
3182 	}
3183 report:
3184 	if (err) {
3185 		btf_mandatory = kernel_needs_btf(obj);
3186 		pr_warn("Error loading .BTF into kernel: %d. %s\n", err,
3187 			btf_mandatory ? "BTF is mandatory, can't proceed."
3188 				      : "BTF is optional, ignoring.");
3189 		if (!btf_mandatory)
3190 			err = 0;
3191 	}
3192 	return err;
3193 }
3194 
3195 static const char *elf_sym_str(const struct bpf_object *obj, size_t off)
3196 {
3197 	const char *name;
3198 
3199 	name = elf_strptr(obj->efile.elf, obj->efile.strtabidx, off);
3200 	if (!name) {
3201 		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3202 			off, obj->path, elf_errmsg(-1));
3203 		return NULL;
3204 	}
3205 
3206 	return name;
3207 }
3208 
3209 static const char *elf_sec_str(const struct bpf_object *obj, size_t off)
3210 {
3211 	const char *name;
3212 
3213 	name = elf_strptr(obj->efile.elf, obj->efile.shstrndx, off);
3214 	if (!name) {
3215 		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3216 			off, obj->path, elf_errmsg(-1));
3217 		return NULL;
3218 	}
3219 
3220 	return name;
3221 }
3222 
3223 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx)
3224 {
3225 	Elf_Scn *scn;
3226 
3227 	scn = elf_getscn(obj->efile.elf, idx);
3228 	if (!scn) {
3229 		pr_warn("elf: failed to get section(%zu) from %s: %s\n",
3230 			idx, obj->path, elf_errmsg(-1));
3231 		return NULL;
3232 	}
3233 	return scn;
3234 }
3235 
3236 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name)
3237 {
3238 	Elf_Scn *scn = NULL;
3239 	Elf *elf = obj->efile.elf;
3240 	const char *sec_name;
3241 
3242 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3243 		sec_name = elf_sec_name(obj, scn);
3244 		if (!sec_name)
3245 			return NULL;
3246 
3247 		if (strcmp(sec_name, name) != 0)
3248 			continue;
3249 
3250 		return scn;
3251 	}
3252 	return NULL;
3253 }
3254 
3255 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn)
3256 {
3257 	Elf64_Shdr *shdr;
3258 
3259 	if (!scn)
3260 		return NULL;
3261 
3262 	shdr = elf64_getshdr(scn);
3263 	if (!shdr) {
3264 		pr_warn("elf: failed to get section(%zu) header from %s: %s\n",
3265 			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3266 		return NULL;
3267 	}
3268 
3269 	return shdr;
3270 }
3271 
3272 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn)
3273 {
3274 	const char *name;
3275 	Elf64_Shdr *sh;
3276 
3277 	if (!scn)
3278 		return NULL;
3279 
3280 	sh = elf_sec_hdr(obj, scn);
3281 	if (!sh)
3282 		return NULL;
3283 
3284 	name = elf_sec_str(obj, sh->sh_name);
3285 	if (!name) {
3286 		pr_warn("elf: failed to get section(%zu) name from %s: %s\n",
3287 			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3288 		return NULL;
3289 	}
3290 
3291 	return name;
3292 }
3293 
3294 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn)
3295 {
3296 	Elf_Data *data;
3297 
3298 	if (!scn)
3299 		return NULL;
3300 
3301 	data = elf_getdata(scn, 0);
3302 	if (!data) {
3303 		pr_warn("elf: failed to get section(%zu) %s data from %s: %s\n",
3304 			elf_ndxscn(scn), elf_sec_name(obj, scn) ?: "<?>",
3305 			obj->path, elf_errmsg(-1));
3306 		return NULL;
3307 	}
3308 
3309 	return data;
3310 }
3311 
3312 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx)
3313 {
3314 	if (idx >= obj->efile.symbols->d_size / sizeof(Elf64_Sym))
3315 		return NULL;
3316 
3317 	return (Elf64_Sym *)obj->efile.symbols->d_buf + idx;
3318 }
3319 
3320 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx)
3321 {
3322 	if (idx >= data->d_size / sizeof(Elf64_Rel))
3323 		return NULL;
3324 
3325 	return (Elf64_Rel *)data->d_buf + idx;
3326 }
3327 
3328 static bool is_sec_name_dwarf(const char *name)
3329 {
3330 	/* approximation, but the actual list is too long */
3331 	return str_has_pfx(name, ".debug_");
3332 }
3333 
3334 static bool ignore_elf_section(Elf64_Shdr *hdr, const char *name)
3335 {
3336 	/* no special handling of .strtab */
3337 	if (hdr->sh_type == SHT_STRTAB)
3338 		return true;
3339 
3340 	/* ignore .llvm_addrsig section as well */
3341 	if (hdr->sh_type == SHT_LLVM_ADDRSIG)
3342 		return true;
3343 
3344 	/* no subprograms will lead to an empty .text section, ignore it */
3345 	if (hdr->sh_type == SHT_PROGBITS && hdr->sh_size == 0 &&
3346 	    strcmp(name, ".text") == 0)
3347 		return true;
3348 
3349 	/* DWARF sections */
3350 	if (is_sec_name_dwarf(name))
3351 		return true;
3352 
3353 	if (str_has_pfx(name, ".rel")) {
3354 		name += sizeof(".rel") - 1;
3355 		/* DWARF section relocations */
3356 		if (is_sec_name_dwarf(name))
3357 			return true;
3358 
3359 		/* .BTF and .BTF.ext don't need relocations */
3360 		if (strcmp(name, BTF_ELF_SEC) == 0 ||
3361 		    strcmp(name, BTF_EXT_ELF_SEC) == 0)
3362 			return true;
3363 	}
3364 
3365 	return false;
3366 }
3367 
3368 static int cmp_progs(const void *_a, const void *_b)
3369 {
3370 	const struct bpf_program *a = _a;
3371 	const struct bpf_program *b = _b;
3372 
3373 	if (a->sec_idx != b->sec_idx)
3374 		return a->sec_idx < b->sec_idx ? -1 : 1;
3375 
3376 	/* sec_insn_off can't be the same within the section */
3377 	return a->sec_insn_off < b->sec_insn_off ? -1 : 1;
3378 }
3379 
3380 static int bpf_object__elf_collect(struct bpf_object *obj)
3381 {
3382 	struct elf_sec_desc *sec_desc;
3383 	Elf *elf = obj->efile.elf;
3384 	Elf_Data *btf_ext_data = NULL;
3385 	Elf_Data *btf_data = NULL;
3386 	int idx = 0, err = 0;
3387 	const char *name;
3388 	Elf_Data *data;
3389 	Elf_Scn *scn;
3390 	Elf64_Shdr *sh;
3391 
3392 	/* ELF section indices are 0-based, but sec #0 is special "invalid"
3393 	 * section. Since section count retrieved by elf_getshdrnum() does
3394 	 * include sec #0, it is already the necessary size of an array to keep
3395 	 * all the sections.
3396 	 */
3397 	if (elf_getshdrnum(obj->efile.elf, &obj->efile.sec_cnt)) {
3398 		pr_warn("elf: failed to get the number of sections for %s: %s\n",
3399 			obj->path, elf_errmsg(-1));
3400 		return -LIBBPF_ERRNO__FORMAT;
3401 	}
3402 	obj->efile.secs = calloc(obj->efile.sec_cnt, sizeof(*obj->efile.secs));
3403 	if (!obj->efile.secs)
3404 		return -ENOMEM;
3405 
3406 	/* a bunch of ELF parsing functionality depends on processing symbols,
3407 	 * so do the first pass and find the symbol table
3408 	 */
3409 	scn = NULL;
3410 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3411 		sh = elf_sec_hdr(obj, scn);
3412 		if (!sh)
3413 			return -LIBBPF_ERRNO__FORMAT;
3414 
3415 		if (sh->sh_type == SHT_SYMTAB) {
3416 			if (obj->efile.symbols) {
3417 				pr_warn("elf: multiple symbol tables in %s\n", obj->path);
3418 				return -LIBBPF_ERRNO__FORMAT;
3419 			}
3420 
3421 			data = elf_sec_data(obj, scn);
3422 			if (!data)
3423 				return -LIBBPF_ERRNO__FORMAT;
3424 
3425 			idx = elf_ndxscn(scn);
3426 
3427 			obj->efile.symbols = data;
3428 			obj->efile.symbols_shndx = idx;
3429 			obj->efile.strtabidx = sh->sh_link;
3430 		}
3431 	}
3432 
3433 	if (!obj->efile.symbols) {
3434 		pr_warn("elf: couldn't find symbol table in %s, stripped object file?\n",
3435 			obj->path);
3436 		return -ENOENT;
3437 	}
3438 
3439 	scn = NULL;
3440 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3441 		idx = elf_ndxscn(scn);
3442 		sec_desc = &obj->efile.secs[idx];
3443 
3444 		sh = elf_sec_hdr(obj, scn);
3445 		if (!sh)
3446 			return -LIBBPF_ERRNO__FORMAT;
3447 
3448 		name = elf_sec_str(obj, sh->sh_name);
3449 		if (!name)
3450 			return -LIBBPF_ERRNO__FORMAT;
3451 
3452 		if (ignore_elf_section(sh, name))
3453 			continue;
3454 
3455 		data = elf_sec_data(obj, scn);
3456 		if (!data)
3457 			return -LIBBPF_ERRNO__FORMAT;
3458 
3459 		pr_debug("elf: section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
3460 			 idx, name, (unsigned long)data->d_size,
3461 			 (int)sh->sh_link, (unsigned long)sh->sh_flags,
3462 			 (int)sh->sh_type);
3463 
3464 		if (strcmp(name, "license") == 0) {
3465 			err = bpf_object__init_license(obj, data->d_buf, data->d_size);
3466 			if (err)
3467 				return err;
3468 		} else if (strcmp(name, "version") == 0) {
3469 			err = bpf_object__init_kversion(obj, data->d_buf, data->d_size);
3470 			if (err)
3471 				return err;
3472 		} else if (strcmp(name, "maps") == 0) {
3473 			pr_warn("elf: legacy map definitions in 'maps' section are not supported by libbpf v1.0+\n");
3474 			return -ENOTSUP;
3475 		} else if (strcmp(name, MAPS_ELF_SEC) == 0) {
3476 			obj->efile.btf_maps_shndx = idx;
3477 		} else if (strcmp(name, BTF_ELF_SEC) == 0) {
3478 			if (sh->sh_type != SHT_PROGBITS)
3479 				return -LIBBPF_ERRNO__FORMAT;
3480 			btf_data = data;
3481 		} else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
3482 			if (sh->sh_type != SHT_PROGBITS)
3483 				return -LIBBPF_ERRNO__FORMAT;
3484 			btf_ext_data = data;
3485 		} else if (sh->sh_type == SHT_SYMTAB) {
3486 			/* already processed during the first pass above */
3487 		} else if (sh->sh_type == SHT_PROGBITS && data->d_size > 0) {
3488 			if (sh->sh_flags & SHF_EXECINSTR) {
3489 				if (strcmp(name, ".text") == 0)
3490 					obj->efile.text_shndx = idx;
3491 				err = bpf_object__add_programs(obj, data, name, idx);
3492 				if (err)
3493 					return err;
3494 			} else if (strcmp(name, DATA_SEC) == 0 ||
3495 				   str_has_pfx(name, DATA_SEC ".")) {
3496 				sec_desc->sec_type = SEC_DATA;
3497 				sec_desc->shdr = sh;
3498 				sec_desc->data = data;
3499 			} else if (strcmp(name, RODATA_SEC) == 0 ||
3500 				   str_has_pfx(name, RODATA_SEC ".")) {
3501 				sec_desc->sec_type = SEC_RODATA;
3502 				sec_desc->shdr = sh;
3503 				sec_desc->data = data;
3504 			} else if (strcmp(name, STRUCT_OPS_SEC) == 0) {
3505 				obj->efile.st_ops_data = data;
3506 				obj->efile.st_ops_shndx = idx;
3507 			} else if (strcmp(name, STRUCT_OPS_LINK_SEC) == 0) {
3508 				obj->efile.st_ops_link_data = data;
3509 				obj->efile.st_ops_link_shndx = idx;
3510 			} else {
3511 				pr_info("elf: skipping unrecognized data section(%d) %s\n",
3512 					idx, name);
3513 			}
3514 		} else if (sh->sh_type == SHT_REL) {
3515 			int targ_sec_idx = sh->sh_info; /* points to other section */
3516 
3517 			if (sh->sh_entsize != sizeof(Elf64_Rel) ||
3518 			    targ_sec_idx >= obj->efile.sec_cnt)
3519 				return -LIBBPF_ERRNO__FORMAT;
3520 
3521 			/* Only do relo for section with exec instructions */
3522 			if (!section_have_execinstr(obj, targ_sec_idx) &&
3523 			    strcmp(name, ".rel" STRUCT_OPS_SEC) &&
3524 			    strcmp(name, ".rel" STRUCT_OPS_LINK_SEC) &&
3525 			    strcmp(name, ".rel" MAPS_ELF_SEC)) {
3526 				pr_info("elf: skipping relo section(%d) %s for section(%d) %s\n",
3527 					idx, name, targ_sec_idx,
3528 					elf_sec_name(obj, elf_sec_by_idx(obj, targ_sec_idx)) ?: "<?>");
3529 				continue;
3530 			}
3531 
3532 			sec_desc->sec_type = SEC_RELO;
3533 			sec_desc->shdr = sh;
3534 			sec_desc->data = data;
3535 		} else if (sh->sh_type == SHT_NOBITS && (strcmp(name, BSS_SEC) == 0 ||
3536 							 str_has_pfx(name, BSS_SEC "."))) {
3537 			sec_desc->sec_type = SEC_BSS;
3538 			sec_desc->shdr = sh;
3539 			sec_desc->data = data;
3540 		} else {
3541 			pr_info("elf: skipping section(%d) %s (size %zu)\n", idx, name,
3542 				(size_t)sh->sh_size);
3543 		}
3544 	}
3545 
3546 	if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) {
3547 		pr_warn("elf: symbol strings section missing or invalid in %s\n", obj->path);
3548 		return -LIBBPF_ERRNO__FORMAT;
3549 	}
3550 
3551 	/* sort BPF programs by section name and in-section instruction offset
3552 	 * for faster search
3553 	 */
3554 	if (obj->nr_programs)
3555 		qsort(obj->programs, obj->nr_programs, sizeof(*obj->programs), cmp_progs);
3556 
3557 	return bpf_object__init_btf(obj, btf_data, btf_ext_data);
3558 }
3559 
3560 static bool sym_is_extern(const Elf64_Sym *sym)
3561 {
3562 	int bind = ELF64_ST_BIND(sym->st_info);
3563 	/* externs are symbols w/ type=NOTYPE, bind=GLOBAL|WEAK, section=UND */
3564 	return sym->st_shndx == SHN_UNDEF &&
3565 	       (bind == STB_GLOBAL || bind == STB_WEAK) &&
3566 	       ELF64_ST_TYPE(sym->st_info) == STT_NOTYPE;
3567 }
3568 
3569 static bool sym_is_subprog(const Elf64_Sym *sym, int text_shndx)
3570 {
3571 	int bind = ELF64_ST_BIND(sym->st_info);
3572 	int type = ELF64_ST_TYPE(sym->st_info);
3573 
3574 	/* in .text section */
3575 	if (sym->st_shndx != text_shndx)
3576 		return false;
3577 
3578 	/* local function */
3579 	if (bind == STB_LOCAL && type == STT_SECTION)
3580 		return true;
3581 
3582 	/* global function */
3583 	return bind == STB_GLOBAL && type == STT_FUNC;
3584 }
3585 
3586 static int find_extern_btf_id(const struct btf *btf, const char *ext_name)
3587 {
3588 	const struct btf_type *t;
3589 	const char *tname;
3590 	int i, n;
3591 
3592 	if (!btf)
3593 		return -ESRCH;
3594 
3595 	n = btf__type_cnt(btf);
3596 	for (i = 1; i < n; i++) {
3597 		t = btf__type_by_id(btf, i);
3598 
3599 		if (!btf_is_var(t) && !btf_is_func(t))
3600 			continue;
3601 
3602 		tname = btf__name_by_offset(btf, t->name_off);
3603 		if (strcmp(tname, ext_name))
3604 			continue;
3605 
3606 		if (btf_is_var(t) &&
3607 		    btf_var(t)->linkage != BTF_VAR_GLOBAL_EXTERN)
3608 			return -EINVAL;
3609 
3610 		if (btf_is_func(t) && btf_func_linkage(t) != BTF_FUNC_EXTERN)
3611 			return -EINVAL;
3612 
3613 		return i;
3614 	}
3615 
3616 	return -ENOENT;
3617 }
3618 
3619 static int find_extern_sec_btf_id(struct btf *btf, int ext_btf_id) {
3620 	const struct btf_var_secinfo *vs;
3621 	const struct btf_type *t;
3622 	int i, j, n;
3623 
3624 	if (!btf)
3625 		return -ESRCH;
3626 
3627 	n = btf__type_cnt(btf);
3628 	for (i = 1; i < n; i++) {
3629 		t = btf__type_by_id(btf, i);
3630 
3631 		if (!btf_is_datasec(t))
3632 			continue;
3633 
3634 		vs = btf_var_secinfos(t);
3635 		for (j = 0; j < btf_vlen(t); j++, vs++) {
3636 			if (vs->type == ext_btf_id)
3637 				return i;
3638 		}
3639 	}
3640 
3641 	return -ENOENT;
3642 }
3643 
3644 static enum kcfg_type find_kcfg_type(const struct btf *btf, int id,
3645 				     bool *is_signed)
3646 {
3647 	const struct btf_type *t;
3648 	const char *name;
3649 
3650 	t = skip_mods_and_typedefs(btf, id, NULL);
3651 	name = btf__name_by_offset(btf, t->name_off);
3652 
3653 	if (is_signed)
3654 		*is_signed = false;
3655 	switch (btf_kind(t)) {
3656 	case BTF_KIND_INT: {
3657 		int enc = btf_int_encoding(t);
3658 
3659 		if (enc & BTF_INT_BOOL)
3660 			return t->size == 1 ? KCFG_BOOL : KCFG_UNKNOWN;
3661 		if (is_signed)
3662 			*is_signed = enc & BTF_INT_SIGNED;
3663 		if (t->size == 1)
3664 			return KCFG_CHAR;
3665 		if (t->size < 1 || t->size > 8 || (t->size & (t->size - 1)))
3666 			return KCFG_UNKNOWN;
3667 		return KCFG_INT;
3668 	}
3669 	case BTF_KIND_ENUM:
3670 		if (t->size != 4)
3671 			return KCFG_UNKNOWN;
3672 		if (strcmp(name, "libbpf_tristate"))
3673 			return KCFG_UNKNOWN;
3674 		return KCFG_TRISTATE;
3675 	case BTF_KIND_ENUM64:
3676 		if (strcmp(name, "libbpf_tristate"))
3677 			return KCFG_UNKNOWN;
3678 		return KCFG_TRISTATE;
3679 	case BTF_KIND_ARRAY:
3680 		if (btf_array(t)->nelems == 0)
3681 			return KCFG_UNKNOWN;
3682 		if (find_kcfg_type(btf, btf_array(t)->type, NULL) != KCFG_CHAR)
3683 			return KCFG_UNKNOWN;
3684 		return KCFG_CHAR_ARR;
3685 	default:
3686 		return KCFG_UNKNOWN;
3687 	}
3688 }
3689 
3690 static int cmp_externs(const void *_a, const void *_b)
3691 {
3692 	const struct extern_desc *a = _a;
3693 	const struct extern_desc *b = _b;
3694 
3695 	if (a->type != b->type)
3696 		return a->type < b->type ? -1 : 1;
3697 
3698 	if (a->type == EXT_KCFG) {
3699 		/* descending order by alignment requirements */
3700 		if (a->kcfg.align != b->kcfg.align)
3701 			return a->kcfg.align > b->kcfg.align ? -1 : 1;
3702 		/* ascending order by size, within same alignment class */
3703 		if (a->kcfg.sz != b->kcfg.sz)
3704 			return a->kcfg.sz < b->kcfg.sz ? -1 : 1;
3705 	}
3706 
3707 	/* resolve ties by name */
3708 	return strcmp(a->name, b->name);
3709 }
3710 
3711 static int find_int_btf_id(const struct btf *btf)
3712 {
3713 	const struct btf_type *t;
3714 	int i, n;
3715 
3716 	n = btf__type_cnt(btf);
3717 	for (i = 1; i < n; i++) {
3718 		t = btf__type_by_id(btf, i);
3719 
3720 		if (btf_is_int(t) && btf_int_bits(t) == 32)
3721 			return i;
3722 	}
3723 
3724 	return 0;
3725 }
3726 
3727 static int add_dummy_ksym_var(struct btf *btf)
3728 {
3729 	int i, int_btf_id, sec_btf_id, dummy_var_btf_id;
3730 	const struct btf_var_secinfo *vs;
3731 	const struct btf_type *sec;
3732 
3733 	if (!btf)
3734 		return 0;
3735 
3736 	sec_btf_id = btf__find_by_name_kind(btf, KSYMS_SEC,
3737 					    BTF_KIND_DATASEC);
3738 	if (sec_btf_id < 0)
3739 		return 0;
3740 
3741 	sec = btf__type_by_id(btf, sec_btf_id);
3742 	vs = btf_var_secinfos(sec);
3743 	for (i = 0; i < btf_vlen(sec); i++, vs++) {
3744 		const struct btf_type *vt;
3745 
3746 		vt = btf__type_by_id(btf, vs->type);
3747 		if (btf_is_func(vt))
3748 			break;
3749 	}
3750 
3751 	/* No func in ksyms sec.  No need to add dummy var. */
3752 	if (i == btf_vlen(sec))
3753 		return 0;
3754 
3755 	int_btf_id = find_int_btf_id(btf);
3756 	dummy_var_btf_id = btf__add_var(btf,
3757 					"dummy_ksym",
3758 					BTF_VAR_GLOBAL_ALLOCATED,
3759 					int_btf_id);
3760 	if (dummy_var_btf_id < 0)
3761 		pr_warn("cannot create a dummy_ksym var\n");
3762 
3763 	return dummy_var_btf_id;
3764 }
3765 
3766 static int bpf_object__collect_externs(struct bpf_object *obj)
3767 {
3768 	struct btf_type *sec, *kcfg_sec = NULL, *ksym_sec = NULL;
3769 	const struct btf_type *t;
3770 	struct extern_desc *ext;
3771 	int i, n, off, dummy_var_btf_id;
3772 	const char *ext_name, *sec_name;
3773 	Elf_Scn *scn;
3774 	Elf64_Shdr *sh;
3775 
3776 	if (!obj->efile.symbols)
3777 		return 0;
3778 
3779 	scn = elf_sec_by_idx(obj, obj->efile.symbols_shndx);
3780 	sh = elf_sec_hdr(obj, scn);
3781 	if (!sh || sh->sh_entsize != sizeof(Elf64_Sym))
3782 		return -LIBBPF_ERRNO__FORMAT;
3783 
3784 	dummy_var_btf_id = add_dummy_ksym_var(obj->btf);
3785 	if (dummy_var_btf_id < 0)
3786 		return dummy_var_btf_id;
3787 
3788 	n = sh->sh_size / sh->sh_entsize;
3789 	pr_debug("looking for externs among %d symbols...\n", n);
3790 
3791 	for (i = 0; i < n; i++) {
3792 		Elf64_Sym *sym = elf_sym_by_idx(obj, i);
3793 
3794 		if (!sym)
3795 			return -LIBBPF_ERRNO__FORMAT;
3796 		if (!sym_is_extern(sym))
3797 			continue;
3798 		ext_name = elf_sym_str(obj, sym->st_name);
3799 		if (!ext_name || !ext_name[0])
3800 			continue;
3801 
3802 		ext = obj->externs;
3803 		ext = libbpf_reallocarray(ext, obj->nr_extern + 1, sizeof(*ext));
3804 		if (!ext)
3805 			return -ENOMEM;
3806 		obj->externs = ext;
3807 		ext = &ext[obj->nr_extern];
3808 		memset(ext, 0, sizeof(*ext));
3809 		obj->nr_extern++;
3810 
3811 		ext->btf_id = find_extern_btf_id(obj->btf, ext_name);
3812 		if (ext->btf_id <= 0) {
3813 			pr_warn("failed to find BTF for extern '%s': %d\n",
3814 				ext_name, ext->btf_id);
3815 			return ext->btf_id;
3816 		}
3817 		t = btf__type_by_id(obj->btf, ext->btf_id);
3818 		ext->name = btf__name_by_offset(obj->btf, t->name_off);
3819 		ext->sym_idx = i;
3820 		ext->is_weak = ELF64_ST_BIND(sym->st_info) == STB_WEAK;
3821 
3822 		ext->sec_btf_id = find_extern_sec_btf_id(obj->btf, ext->btf_id);
3823 		if (ext->sec_btf_id <= 0) {
3824 			pr_warn("failed to find BTF for extern '%s' [%d] section: %d\n",
3825 				ext_name, ext->btf_id, ext->sec_btf_id);
3826 			return ext->sec_btf_id;
3827 		}
3828 		sec = (void *)btf__type_by_id(obj->btf, ext->sec_btf_id);
3829 		sec_name = btf__name_by_offset(obj->btf, sec->name_off);
3830 
3831 		if (strcmp(sec_name, KCONFIG_SEC) == 0) {
3832 			if (btf_is_func(t)) {
3833 				pr_warn("extern function %s is unsupported under %s section\n",
3834 					ext->name, KCONFIG_SEC);
3835 				return -ENOTSUP;
3836 			}
3837 			kcfg_sec = sec;
3838 			ext->type = EXT_KCFG;
3839 			ext->kcfg.sz = btf__resolve_size(obj->btf, t->type);
3840 			if (ext->kcfg.sz <= 0) {
3841 				pr_warn("failed to resolve size of extern (kcfg) '%s': %d\n",
3842 					ext_name, ext->kcfg.sz);
3843 				return ext->kcfg.sz;
3844 			}
3845 			ext->kcfg.align = btf__align_of(obj->btf, t->type);
3846 			if (ext->kcfg.align <= 0) {
3847 				pr_warn("failed to determine alignment of extern (kcfg) '%s': %d\n",
3848 					ext_name, ext->kcfg.align);
3849 				return -EINVAL;
3850 			}
3851 			ext->kcfg.type = find_kcfg_type(obj->btf, t->type,
3852 							&ext->kcfg.is_signed);
3853 			if (ext->kcfg.type == KCFG_UNKNOWN) {
3854 				pr_warn("extern (kcfg) '%s': type is unsupported\n", ext_name);
3855 				return -ENOTSUP;
3856 			}
3857 		} else if (strcmp(sec_name, KSYMS_SEC) == 0) {
3858 			ksym_sec = sec;
3859 			ext->type = EXT_KSYM;
3860 			skip_mods_and_typedefs(obj->btf, t->type,
3861 					       &ext->ksym.type_id);
3862 		} else {
3863 			pr_warn("unrecognized extern section '%s'\n", sec_name);
3864 			return -ENOTSUP;
3865 		}
3866 	}
3867 	pr_debug("collected %d externs total\n", obj->nr_extern);
3868 
3869 	if (!obj->nr_extern)
3870 		return 0;
3871 
3872 	/* sort externs by type, for kcfg ones also by (align, size, name) */
3873 	qsort(obj->externs, obj->nr_extern, sizeof(*ext), cmp_externs);
3874 
3875 	/* for .ksyms section, we need to turn all externs into allocated
3876 	 * variables in BTF to pass kernel verification; we do this by
3877 	 * pretending that each extern is a 8-byte variable
3878 	 */
3879 	if (ksym_sec) {
3880 		/* find existing 4-byte integer type in BTF to use for fake
3881 		 * extern variables in DATASEC
3882 		 */
3883 		int int_btf_id = find_int_btf_id(obj->btf);
3884 		/* For extern function, a dummy_var added earlier
3885 		 * will be used to replace the vs->type and
3886 		 * its name string will be used to refill
3887 		 * the missing param's name.
3888 		 */
3889 		const struct btf_type *dummy_var;
3890 
3891 		dummy_var = btf__type_by_id(obj->btf, dummy_var_btf_id);
3892 		for (i = 0; i < obj->nr_extern; i++) {
3893 			ext = &obj->externs[i];
3894 			if (ext->type != EXT_KSYM)
3895 				continue;
3896 			pr_debug("extern (ksym) #%d: symbol %d, name %s\n",
3897 				 i, ext->sym_idx, ext->name);
3898 		}
3899 
3900 		sec = ksym_sec;
3901 		n = btf_vlen(sec);
3902 		for (i = 0, off = 0; i < n; i++, off += sizeof(int)) {
3903 			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
3904 			struct btf_type *vt;
3905 
3906 			vt = (void *)btf__type_by_id(obj->btf, vs->type);
3907 			ext_name = btf__name_by_offset(obj->btf, vt->name_off);
3908 			ext = find_extern_by_name(obj, ext_name);
3909 			if (!ext) {
3910 				pr_warn("failed to find extern definition for BTF %s '%s'\n",
3911 					btf_kind_str(vt), ext_name);
3912 				return -ESRCH;
3913 			}
3914 			if (btf_is_func(vt)) {
3915 				const struct btf_type *func_proto;
3916 				struct btf_param *param;
3917 				int j;
3918 
3919 				func_proto = btf__type_by_id(obj->btf,
3920 							     vt->type);
3921 				param = btf_params(func_proto);
3922 				/* Reuse the dummy_var string if the
3923 				 * func proto does not have param name.
3924 				 */
3925 				for (j = 0; j < btf_vlen(func_proto); j++)
3926 					if (param[j].type && !param[j].name_off)
3927 						param[j].name_off =
3928 							dummy_var->name_off;
3929 				vs->type = dummy_var_btf_id;
3930 				vt->info &= ~0xffff;
3931 				vt->info |= BTF_FUNC_GLOBAL;
3932 			} else {
3933 				btf_var(vt)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
3934 				vt->type = int_btf_id;
3935 			}
3936 			vs->offset = off;
3937 			vs->size = sizeof(int);
3938 		}
3939 		sec->size = off;
3940 	}
3941 
3942 	if (kcfg_sec) {
3943 		sec = kcfg_sec;
3944 		/* for kcfg externs calculate their offsets within a .kconfig map */
3945 		off = 0;
3946 		for (i = 0; i < obj->nr_extern; i++) {
3947 			ext = &obj->externs[i];
3948 			if (ext->type != EXT_KCFG)
3949 				continue;
3950 
3951 			ext->kcfg.data_off = roundup(off, ext->kcfg.align);
3952 			off = ext->kcfg.data_off + ext->kcfg.sz;
3953 			pr_debug("extern (kcfg) #%d: symbol %d, off %u, name %s\n",
3954 				 i, ext->sym_idx, ext->kcfg.data_off, ext->name);
3955 		}
3956 		sec->size = off;
3957 		n = btf_vlen(sec);
3958 		for (i = 0; i < n; i++) {
3959 			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
3960 
3961 			t = btf__type_by_id(obj->btf, vs->type);
3962 			ext_name = btf__name_by_offset(obj->btf, t->name_off);
3963 			ext = find_extern_by_name(obj, ext_name);
3964 			if (!ext) {
3965 				pr_warn("failed to find extern definition for BTF var '%s'\n",
3966 					ext_name);
3967 				return -ESRCH;
3968 			}
3969 			btf_var(t)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
3970 			vs->offset = ext->kcfg.data_off;
3971 		}
3972 	}
3973 	return 0;
3974 }
3975 
3976 static bool prog_is_subprog(const struct bpf_object *obj, const struct bpf_program *prog)
3977 {
3978 	return prog->sec_idx == obj->efile.text_shndx && obj->nr_programs > 1;
3979 }
3980 
3981 struct bpf_program *
3982 bpf_object__find_program_by_name(const struct bpf_object *obj,
3983 				 const char *name)
3984 {
3985 	struct bpf_program *prog;
3986 
3987 	bpf_object__for_each_program(prog, obj) {
3988 		if (prog_is_subprog(obj, prog))
3989 			continue;
3990 		if (!strcmp(prog->name, name))
3991 			return prog;
3992 	}
3993 	return errno = ENOENT, NULL;
3994 }
3995 
3996 static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
3997 				      int shndx)
3998 {
3999 	switch (obj->efile.secs[shndx].sec_type) {
4000 	case SEC_BSS:
4001 	case SEC_DATA:
4002 	case SEC_RODATA:
4003 		return true;
4004 	default:
4005 		return false;
4006 	}
4007 }
4008 
4009 static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
4010 				      int shndx)
4011 {
4012 	return shndx == obj->efile.btf_maps_shndx;
4013 }
4014 
4015 static enum libbpf_map_type
4016 bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
4017 {
4018 	if (shndx == obj->efile.symbols_shndx)
4019 		return LIBBPF_MAP_KCONFIG;
4020 
4021 	switch (obj->efile.secs[shndx].sec_type) {
4022 	case SEC_BSS:
4023 		return LIBBPF_MAP_BSS;
4024 	case SEC_DATA:
4025 		return LIBBPF_MAP_DATA;
4026 	case SEC_RODATA:
4027 		return LIBBPF_MAP_RODATA;
4028 	default:
4029 		return LIBBPF_MAP_UNSPEC;
4030 	}
4031 }
4032 
4033 static int bpf_program__record_reloc(struct bpf_program *prog,
4034 				     struct reloc_desc *reloc_desc,
4035 				     __u32 insn_idx, const char *sym_name,
4036 				     const Elf64_Sym *sym, const Elf64_Rel *rel)
4037 {
4038 	struct bpf_insn *insn = &prog->insns[insn_idx];
4039 	size_t map_idx, nr_maps = prog->obj->nr_maps;
4040 	struct bpf_object *obj = prog->obj;
4041 	__u32 shdr_idx = sym->st_shndx;
4042 	enum libbpf_map_type type;
4043 	const char *sym_sec_name;
4044 	struct bpf_map *map;
4045 
4046 	if (!is_call_insn(insn) && !is_ldimm64_insn(insn)) {
4047 		pr_warn("prog '%s': invalid relo against '%s' for insns[%d].code 0x%x\n",
4048 			prog->name, sym_name, insn_idx, insn->code);
4049 		return -LIBBPF_ERRNO__RELOC;
4050 	}
4051 
4052 	if (sym_is_extern(sym)) {
4053 		int sym_idx = ELF64_R_SYM(rel->r_info);
4054 		int i, n = obj->nr_extern;
4055 		struct extern_desc *ext;
4056 
4057 		for (i = 0; i < n; i++) {
4058 			ext = &obj->externs[i];
4059 			if (ext->sym_idx == sym_idx)
4060 				break;
4061 		}
4062 		if (i >= n) {
4063 			pr_warn("prog '%s': extern relo failed to find extern for '%s' (%d)\n",
4064 				prog->name, sym_name, sym_idx);
4065 			return -LIBBPF_ERRNO__RELOC;
4066 		}
4067 		pr_debug("prog '%s': found extern #%d '%s' (sym %d) for insn #%u\n",
4068 			 prog->name, i, ext->name, ext->sym_idx, insn_idx);
4069 		if (insn->code == (BPF_JMP | BPF_CALL))
4070 			reloc_desc->type = RELO_EXTERN_CALL;
4071 		else
4072 			reloc_desc->type = RELO_EXTERN_LD64;
4073 		reloc_desc->insn_idx = insn_idx;
4074 		reloc_desc->ext_idx = i;
4075 		return 0;
4076 	}
4077 
4078 	/* sub-program call relocation */
4079 	if (is_call_insn(insn)) {
4080 		if (insn->src_reg != BPF_PSEUDO_CALL) {
4081 			pr_warn("prog '%s': incorrect bpf_call opcode\n", prog->name);
4082 			return -LIBBPF_ERRNO__RELOC;
4083 		}
4084 		/* text_shndx can be 0, if no default "main" program exists */
4085 		if (!shdr_idx || shdr_idx != obj->efile.text_shndx) {
4086 			sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4087 			pr_warn("prog '%s': bad call relo against '%s' in section '%s'\n",
4088 				prog->name, sym_name, sym_sec_name);
4089 			return -LIBBPF_ERRNO__RELOC;
4090 		}
4091 		if (sym->st_value % BPF_INSN_SZ) {
4092 			pr_warn("prog '%s': bad call relo against '%s' at offset %zu\n",
4093 				prog->name, sym_name, (size_t)sym->st_value);
4094 			return -LIBBPF_ERRNO__RELOC;
4095 		}
4096 		reloc_desc->type = RELO_CALL;
4097 		reloc_desc->insn_idx = insn_idx;
4098 		reloc_desc->sym_off = sym->st_value;
4099 		return 0;
4100 	}
4101 
4102 	if (!shdr_idx || shdr_idx >= SHN_LORESERVE) {
4103 		pr_warn("prog '%s': invalid relo against '%s' in special section 0x%x; forgot to initialize global var?..\n",
4104 			prog->name, sym_name, shdr_idx);
4105 		return -LIBBPF_ERRNO__RELOC;
4106 	}
4107 
4108 	/* loading subprog addresses */
4109 	if (sym_is_subprog(sym, obj->efile.text_shndx)) {
4110 		/* global_func: sym->st_value = offset in the section, insn->imm = 0.
4111 		 * local_func: sym->st_value = 0, insn->imm = offset in the section.
4112 		 */
4113 		if ((sym->st_value % BPF_INSN_SZ) || (insn->imm % BPF_INSN_SZ)) {
4114 			pr_warn("prog '%s': bad subprog addr relo against '%s' at offset %zu+%d\n",
4115 				prog->name, sym_name, (size_t)sym->st_value, insn->imm);
4116 			return -LIBBPF_ERRNO__RELOC;
4117 		}
4118 
4119 		reloc_desc->type = RELO_SUBPROG_ADDR;
4120 		reloc_desc->insn_idx = insn_idx;
4121 		reloc_desc->sym_off = sym->st_value;
4122 		return 0;
4123 	}
4124 
4125 	type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
4126 	sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4127 
4128 	/* generic map reference relocation */
4129 	if (type == LIBBPF_MAP_UNSPEC) {
4130 		if (!bpf_object__shndx_is_maps(obj, shdr_idx)) {
4131 			pr_warn("prog '%s': bad map relo against '%s' in section '%s'\n",
4132 				prog->name, sym_name, sym_sec_name);
4133 			return -LIBBPF_ERRNO__RELOC;
4134 		}
4135 		for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4136 			map = &obj->maps[map_idx];
4137 			if (map->libbpf_type != type ||
4138 			    map->sec_idx != sym->st_shndx ||
4139 			    map->sec_offset != sym->st_value)
4140 				continue;
4141 			pr_debug("prog '%s': found map %zd (%s, sec %d, off %zu) for insn #%u\n",
4142 				 prog->name, map_idx, map->name, map->sec_idx,
4143 				 map->sec_offset, insn_idx);
4144 			break;
4145 		}
4146 		if (map_idx >= nr_maps) {
4147 			pr_warn("prog '%s': map relo failed to find map for section '%s', off %zu\n",
4148 				prog->name, sym_sec_name, (size_t)sym->st_value);
4149 			return -LIBBPF_ERRNO__RELOC;
4150 		}
4151 		reloc_desc->type = RELO_LD64;
4152 		reloc_desc->insn_idx = insn_idx;
4153 		reloc_desc->map_idx = map_idx;
4154 		reloc_desc->sym_off = 0; /* sym->st_value determines map_idx */
4155 		return 0;
4156 	}
4157 
4158 	/* global data map relocation */
4159 	if (!bpf_object__shndx_is_data(obj, shdr_idx)) {
4160 		pr_warn("prog '%s': bad data relo against section '%s'\n",
4161 			prog->name, sym_sec_name);
4162 		return -LIBBPF_ERRNO__RELOC;
4163 	}
4164 	for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4165 		map = &obj->maps[map_idx];
4166 		if (map->libbpf_type != type || map->sec_idx != sym->st_shndx)
4167 			continue;
4168 		pr_debug("prog '%s': found data map %zd (%s, sec %d, off %zu) for insn %u\n",
4169 			 prog->name, map_idx, map->name, map->sec_idx,
4170 			 map->sec_offset, insn_idx);
4171 		break;
4172 	}
4173 	if (map_idx >= nr_maps) {
4174 		pr_warn("prog '%s': data relo failed to find map for section '%s'\n",
4175 			prog->name, sym_sec_name);
4176 		return -LIBBPF_ERRNO__RELOC;
4177 	}
4178 
4179 	reloc_desc->type = RELO_DATA;
4180 	reloc_desc->insn_idx = insn_idx;
4181 	reloc_desc->map_idx = map_idx;
4182 	reloc_desc->sym_off = sym->st_value;
4183 	return 0;
4184 }
4185 
4186 static bool prog_contains_insn(const struct bpf_program *prog, size_t insn_idx)
4187 {
4188 	return insn_idx >= prog->sec_insn_off &&
4189 	       insn_idx < prog->sec_insn_off + prog->sec_insn_cnt;
4190 }
4191 
4192 static struct bpf_program *find_prog_by_sec_insn(const struct bpf_object *obj,
4193 						 size_t sec_idx, size_t insn_idx)
4194 {
4195 	int l = 0, r = obj->nr_programs - 1, m;
4196 	struct bpf_program *prog;
4197 
4198 	if (!obj->nr_programs)
4199 		return NULL;
4200 
4201 	while (l < r) {
4202 		m = l + (r - l + 1) / 2;
4203 		prog = &obj->programs[m];
4204 
4205 		if (prog->sec_idx < sec_idx ||
4206 		    (prog->sec_idx == sec_idx && prog->sec_insn_off <= insn_idx))
4207 			l = m;
4208 		else
4209 			r = m - 1;
4210 	}
4211 	/* matching program could be at index l, but it still might be the
4212 	 * wrong one, so we need to double check conditions for the last time
4213 	 */
4214 	prog = &obj->programs[l];
4215 	if (prog->sec_idx == sec_idx && prog_contains_insn(prog, insn_idx))
4216 		return prog;
4217 	return NULL;
4218 }
4219 
4220 static int
4221 bpf_object__collect_prog_relos(struct bpf_object *obj, Elf64_Shdr *shdr, Elf_Data *data)
4222 {
4223 	const char *relo_sec_name, *sec_name;
4224 	size_t sec_idx = shdr->sh_info, sym_idx;
4225 	struct bpf_program *prog;
4226 	struct reloc_desc *relos;
4227 	int err, i, nrels;
4228 	const char *sym_name;
4229 	__u32 insn_idx;
4230 	Elf_Scn *scn;
4231 	Elf_Data *scn_data;
4232 	Elf64_Sym *sym;
4233 	Elf64_Rel *rel;
4234 
4235 	if (sec_idx >= obj->efile.sec_cnt)
4236 		return -EINVAL;
4237 
4238 	scn = elf_sec_by_idx(obj, sec_idx);
4239 	scn_data = elf_sec_data(obj, scn);
4240 
4241 	relo_sec_name = elf_sec_str(obj, shdr->sh_name);
4242 	sec_name = elf_sec_name(obj, scn);
4243 	if (!relo_sec_name || !sec_name)
4244 		return -EINVAL;
4245 
4246 	pr_debug("sec '%s': collecting relocation for section(%zu) '%s'\n",
4247 		 relo_sec_name, sec_idx, sec_name);
4248 	nrels = shdr->sh_size / shdr->sh_entsize;
4249 
4250 	for (i = 0; i < nrels; i++) {
4251 		rel = elf_rel_by_idx(data, i);
4252 		if (!rel) {
4253 			pr_warn("sec '%s': failed to get relo #%d\n", relo_sec_name, i);
4254 			return -LIBBPF_ERRNO__FORMAT;
4255 		}
4256 
4257 		sym_idx = ELF64_R_SYM(rel->r_info);
4258 		sym = elf_sym_by_idx(obj, sym_idx);
4259 		if (!sym) {
4260 			pr_warn("sec '%s': symbol #%zu not found for relo #%d\n",
4261 				relo_sec_name, sym_idx, i);
4262 			return -LIBBPF_ERRNO__FORMAT;
4263 		}
4264 
4265 		if (sym->st_shndx >= obj->efile.sec_cnt) {
4266 			pr_warn("sec '%s': corrupted symbol #%zu pointing to invalid section #%zu for relo #%d\n",
4267 				relo_sec_name, sym_idx, (size_t)sym->st_shndx, i);
4268 			return -LIBBPF_ERRNO__FORMAT;
4269 		}
4270 
4271 		if (rel->r_offset % BPF_INSN_SZ || rel->r_offset >= scn_data->d_size) {
4272 			pr_warn("sec '%s': invalid offset 0x%zx for relo #%d\n",
4273 				relo_sec_name, (size_t)rel->r_offset, i);
4274 			return -LIBBPF_ERRNO__FORMAT;
4275 		}
4276 
4277 		insn_idx = rel->r_offset / BPF_INSN_SZ;
4278 		/* relocations against static functions are recorded as
4279 		 * relocations against the section that contains a function;
4280 		 * in such case, symbol will be STT_SECTION and sym.st_name
4281 		 * will point to empty string (0), so fetch section name
4282 		 * instead
4283 		 */
4284 		if (ELF64_ST_TYPE(sym->st_info) == STT_SECTION && sym->st_name == 0)
4285 			sym_name = elf_sec_name(obj, elf_sec_by_idx(obj, sym->st_shndx));
4286 		else
4287 			sym_name = elf_sym_str(obj, sym->st_name);
4288 		sym_name = sym_name ?: "<?";
4289 
4290 		pr_debug("sec '%s': relo #%d: insn #%u against '%s'\n",
4291 			 relo_sec_name, i, insn_idx, sym_name);
4292 
4293 		prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
4294 		if (!prog) {
4295 			pr_debug("sec '%s': relo #%d: couldn't find program in section '%s' for insn #%u, probably overridden weak function, skipping...\n",
4296 				relo_sec_name, i, sec_name, insn_idx);
4297 			continue;
4298 		}
4299 
4300 		relos = libbpf_reallocarray(prog->reloc_desc,
4301 					    prog->nr_reloc + 1, sizeof(*relos));
4302 		if (!relos)
4303 			return -ENOMEM;
4304 		prog->reloc_desc = relos;
4305 
4306 		/* adjust insn_idx to local BPF program frame of reference */
4307 		insn_idx -= prog->sec_insn_off;
4308 		err = bpf_program__record_reloc(prog, &relos[prog->nr_reloc],
4309 						insn_idx, sym_name, sym, rel);
4310 		if (err)
4311 			return err;
4312 
4313 		prog->nr_reloc++;
4314 	}
4315 	return 0;
4316 }
4317 
4318 static int map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map)
4319 {
4320 	int id;
4321 
4322 	if (!obj->btf)
4323 		return -ENOENT;
4324 
4325 	/* if it's BTF-defined map, we don't need to search for type IDs.
4326 	 * For struct_ops map, it does not need btf_key_type_id and
4327 	 * btf_value_type_id.
4328 	 */
4329 	if (map->sec_idx == obj->efile.btf_maps_shndx || bpf_map__is_struct_ops(map))
4330 		return 0;
4331 
4332 	/*
4333 	 * LLVM annotates global data differently in BTF, that is,
4334 	 * only as '.data', '.bss' or '.rodata'.
4335 	 */
4336 	if (!bpf_map__is_internal(map))
4337 		return -ENOENT;
4338 
4339 	id = btf__find_by_name(obj->btf, map->real_name);
4340 	if (id < 0)
4341 		return id;
4342 
4343 	map->btf_key_type_id = 0;
4344 	map->btf_value_type_id = id;
4345 	return 0;
4346 }
4347 
4348 static int bpf_get_map_info_from_fdinfo(int fd, struct bpf_map_info *info)
4349 {
4350 	char file[PATH_MAX], buff[4096];
4351 	FILE *fp;
4352 	__u32 val;
4353 	int err;
4354 
4355 	snprintf(file, sizeof(file), "/proc/%d/fdinfo/%d", getpid(), fd);
4356 	memset(info, 0, sizeof(*info));
4357 
4358 	fp = fopen(file, "re");
4359 	if (!fp) {
4360 		err = -errno;
4361 		pr_warn("failed to open %s: %d. No procfs support?\n", file,
4362 			err);
4363 		return err;
4364 	}
4365 
4366 	while (fgets(buff, sizeof(buff), fp)) {
4367 		if (sscanf(buff, "map_type:\t%u", &val) == 1)
4368 			info->type = val;
4369 		else if (sscanf(buff, "key_size:\t%u", &val) == 1)
4370 			info->key_size = val;
4371 		else if (sscanf(buff, "value_size:\t%u", &val) == 1)
4372 			info->value_size = val;
4373 		else if (sscanf(buff, "max_entries:\t%u", &val) == 1)
4374 			info->max_entries = val;
4375 		else if (sscanf(buff, "map_flags:\t%i", &val) == 1)
4376 			info->map_flags = val;
4377 	}
4378 
4379 	fclose(fp);
4380 
4381 	return 0;
4382 }
4383 
4384 bool bpf_map__autocreate(const struct bpf_map *map)
4385 {
4386 	return map->autocreate;
4387 }
4388 
4389 int bpf_map__set_autocreate(struct bpf_map *map, bool autocreate)
4390 {
4391 	if (map->obj->loaded)
4392 		return libbpf_err(-EBUSY);
4393 
4394 	map->autocreate = autocreate;
4395 	return 0;
4396 }
4397 
4398 int bpf_map__reuse_fd(struct bpf_map *map, int fd)
4399 {
4400 	struct bpf_map_info info;
4401 	__u32 len = sizeof(info), name_len;
4402 	int new_fd, err;
4403 	char *new_name;
4404 
4405 	memset(&info, 0, len);
4406 	err = bpf_map_get_info_by_fd(fd, &info, &len);
4407 	if (err && errno == EINVAL)
4408 		err = bpf_get_map_info_from_fdinfo(fd, &info);
4409 	if (err)
4410 		return libbpf_err(err);
4411 
4412 	name_len = strlen(info.name);
4413 	if (name_len == BPF_OBJ_NAME_LEN - 1 && strncmp(map->name, info.name, name_len) == 0)
4414 		new_name = strdup(map->name);
4415 	else
4416 		new_name = strdup(info.name);
4417 
4418 	if (!new_name)
4419 		return libbpf_err(-errno);
4420 
4421 	/*
4422 	 * Like dup(), but make sure new FD is >= 3 and has O_CLOEXEC set.
4423 	 * This is similar to what we do in ensure_good_fd(), but without
4424 	 * closing original FD.
4425 	 */
4426 	new_fd = fcntl(fd, F_DUPFD_CLOEXEC, 3);
4427 	if (new_fd < 0) {
4428 		err = -errno;
4429 		goto err_free_new_name;
4430 	}
4431 
4432 	err = zclose(map->fd);
4433 	if (err) {
4434 		err = -errno;
4435 		goto err_close_new_fd;
4436 	}
4437 	free(map->name);
4438 
4439 	map->fd = new_fd;
4440 	map->name = new_name;
4441 	map->def.type = info.type;
4442 	map->def.key_size = info.key_size;
4443 	map->def.value_size = info.value_size;
4444 	map->def.max_entries = info.max_entries;
4445 	map->def.map_flags = info.map_flags;
4446 	map->btf_key_type_id = info.btf_key_type_id;
4447 	map->btf_value_type_id = info.btf_value_type_id;
4448 	map->reused = true;
4449 	map->map_extra = info.map_extra;
4450 
4451 	return 0;
4452 
4453 err_close_new_fd:
4454 	close(new_fd);
4455 err_free_new_name:
4456 	free(new_name);
4457 	return libbpf_err(err);
4458 }
4459 
4460 __u32 bpf_map__max_entries(const struct bpf_map *map)
4461 {
4462 	return map->def.max_entries;
4463 }
4464 
4465 struct bpf_map *bpf_map__inner_map(struct bpf_map *map)
4466 {
4467 	if (!bpf_map_type__is_map_in_map(map->def.type))
4468 		return errno = EINVAL, NULL;
4469 
4470 	return map->inner_map;
4471 }
4472 
4473 int bpf_map__set_max_entries(struct bpf_map *map, __u32 max_entries)
4474 {
4475 	if (map->obj->loaded)
4476 		return libbpf_err(-EBUSY);
4477 
4478 	map->def.max_entries = max_entries;
4479 
4480 	/* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
4481 	if (map_is_ringbuf(map))
4482 		map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
4483 
4484 	return 0;
4485 }
4486 
4487 static int
4488 bpf_object__probe_loading(struct bpf_object *obj)
4489 {
4490 	char *cp, errmsg[STRERR_BUFSIZE];
4491 	struct bpf_insn insns[] = {
4492 		BPF_MOV64_IMM(BPF_REG_0, 0),
4493 		BPF_EXIT_INSN(),
4494 	};
4495 	int ret, insn_cnt = ARRAY_SIZE(insns);
4496 
4497 	if (obj->gen_loader)
4498 		return 0;
4499 
4500 	ret = bump_rlimit_memlock();
4501 	if (ret)
4502 		pr_warn("Failed to bump RLIMIT_MEMLOCK (err = %d), you might need to do it explicitly!\n", ret);
4503 
4504 	/* make sure basic loading works */
4505 	ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4506 	if (ret < 0)
4507 		ret = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, NULL);
4508 	if (ret < 0) {
4509 		ret = errno;
4510 		cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4511 		pr_warn("Error in %s():%s(%d). Couldn't load trivial BPF "
4512 			"program. Make sure your kernel supports BPF "
4513 			"(CONFIG_BPF_SYSCALL=y) and/or that RLIMIT_MEMLOCK is "
4514 			"set to big enough value.\n", __func__, cp, ret);
4515 		return -ret;
4516 	}
4517 	close(ret);
4518 
4519 	return 0;
4520 }
4521 
4522 static int probe_fd(int fd)
4523 {
4524 	if (fd >= 0)
4525 		close(fd);
4526 	return fd >= 0;
4527 }
4528 
4529 static int probe_kern_prog_name(void)
4530 {
4531 	const size_t attr_sz = offsetofend(union bpf_attr, prog_name);
4532 	struct bpf_insn insns[] = {
4533 		BPF_MOV64_IMM(BPF_REG_0, 0),
4534 		BPF_EXIT_INSN(),
4535 	};
4536 	union bpf_attr attr;
4537 	int ret;
4538 
4539 	memset(&attr, 0, attr_sz);
4540 	attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
4541 	attr.license = ptr_to_u64("GPL");
4542 	attr.insns = ptr_to_u64(insns);
4543 	attr.insn_cnt = (__u32)ARRAY_SIZE(insns);
4544 	libbpf_strlcpy(attr.prog_name, "libbpf_nametest", sizeof(attr.prog_name));
4545 
4546 	/* make sure loading with name works */
4547 	ret = sys_bpf_prog_load(&attr, attr_sz, PROG_LOAD_ATTEMPTS);
4548 	return probe_fd(ret);
4549 }
4550 
4551 static int probe_kern_global_data(void)
4552 {
4553 	char *cp, errmsg[STRERR_BUFSIZE];
4554 	struct bpf_insn insns[] = {
4555 		BPF_LD_MAP_VALUE(BPF_REG_1, 0, 16),
4556 		BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 42),
4557 		BPF_MOV64_IMM(BPF_REG_0, 0),
4558 		BPF_EXIT_INSN(),
4559 	};
4560 	int ret, map, insn_cnt = ARRAY_SIZE(insns);
4561 
4562 	map = bpf_map_create(BPF_MAP_TYPE_ARRAY, "libbpf_global", sizeof(int), 32, 1, NULL);
4563 	if (map < 0) {
4564 		ret = -errno;
4565 		cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4566 		pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
4567 			__func__, cp, -ret);
4568 		return ret;
4569 	}
4570 
4571 	insns[0].imm = map;
4572 
4573 	ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4574 	close(map);
4575 	return probe_fd(ret);
4576 }
4577 
4578 static int probe_kern_btf(void)
4579 {
4580 	static const char strs[] = "\0int";
4581 	__u32 types[] = {
4582 		/* int */
4583 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),
4584 	};
4585 
4586 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4587 					     strs, sizeof(strs)));
4588 }
4589 
4590 static int probe_kern_btf_func(void)
4591 {
4592 	static const char strs[] = "\0int\0x\0a";
4593 	/* void x(int a) {} */
4594 	__u32 types[] = {
4595 		/* int */
4596 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4597 		/* FUNC_PROTO */                                /* [2] */
4598 		BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
4599 		BTF_PARAM_ENC(7, 1),
4600 		/* FUNC x */                                    /* [3] */
4601 		BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0), 2),
4602 	};
4603 
4604 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4605 					     strs, sizeof(strs)));
4606 }
4607 
4608 static int probe_kern_btf_func_global(void)
4609 {
4610 	static const char strs[] = "\0int\0x\0a";
4611 	/* static void x(int a) {} */
4612 	__u32 types[] = {
4613 		/* int */
4614 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4615 		/* FUNC_PROTO */                                /* [2] */
4616 		BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
4617 		BTF_PARAM_ENC(7, 1),
4618 		/* FUNC x BTF_FUNC_GLOBAL */                    /* [3] */
4619 		BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, BTF_FUNC_GLOBAL), 2),
4620 	};
4621 
4622 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4623 					     strs, sizeof(strs)));
4624 }
4625 
4626 static int probe_kern_btf_datasec(void)
4627 {
4628 	static const char strs[] = "\0x\0.data";
4629 	/* static int a; */
4630 	__u32 types[] = {
4631 		/* int */
4632 		BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4633 		/* VAR x */                                     /* [2] */
4634 		BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
4635 		BTF_VAR_STATIC,
4636 		/* DATASEC val */                               /* [3] */
4637 		BTF_TYPE_ENC(3, BTF_INFO_ENC(BTF_KIND_DATASEC, 0, 1), 4),
4638 		BTF_VAR_SECINFO_ENC(2, 0, 4),
4639 	};
4640 
4641 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4642 					     strs, sizeof(strs)));
4643 }
4644 
4645 static int probe_kern_btf_float(void)
4646 {
4647 	static const char strs[] = "\0float";
4648 	__u32 types[] = {
4649 		/* float */
4650 		BTF_TYPE_FLOAT_ENC(1, 4),
4651 	};
4652 
4653 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4654 					     strs, sizeof(strs)));
4655 }
4656 
4657 static int probe_kern_btf_decl_tag(void)
4658 {
4659 	static const char strs[] = "\0tag";
4660 	__u32 types[] = {
4661 		/* int */
4662 		BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4663 		/* VAR x */                                     /* [2] */
4664 		BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
4665 		BTF_VAR_STATIC,
4666 		/* attr */
4667 		BTF_TYPE_DECL_TAG_ENC(1, 2, -1),
4668 	};
4669 
4670 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4671 					     strs, sizeof(strs)));
4672 }
4673 
4674 static int probe_kern_btf_type_tag(void)
4675 {
4676 	static const char strs[] = "\0tag";
4677 	__u32 types[] = {
4678 		/* int */
4679 		BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4),		/* [1] */
4680 		/* attr */
4681 		BTF_TYPE_TYPE_TAG_ENC(1, 1),				/* [2] */
4682 		/* ptr */
4683 		BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_PTR, 0, 0), 2),	/* [3] */
4684 	};
4685 
4686 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4687 					     strs, sizeof(strs)));
4688 }
4689 
4690 static int probe_kern_array_mmap(void)
4691 {
4692 	LIBBPF_OPTS(bpf_map_create_opts, opts, .map_flags = BPF_F_MMAPABLE);
4693 	int fd;
4694 
4695 	fd = bpf_map_create(BPF_MAP_TYPE_ARRAY, "libbpf_mmap", sizeof(int), sizeof(int), 1, &opts);
4696 	return probe_fd(fd);
4697 }
4698 
4699 static int probe_kern_exp_attach_type(void)
4700 {
4701 	LIBBPF_OPTS(bpf_prog_load_opts, opts, .expected_attach_type = BPF_CGROUP_INET_SOCK_CREATE);
4702 	struct bpf_insn insns[] = {
4703 		BPF_MOV64_IMM(BPF_REG_0, 0),
4704 		BPF_EXIT_INSN(),
4705 	};
4706 	int fd, insn_cnt = ARRAY_SIZE(insns);
4707 
4708 	/* use any valid combination of program type and (optional)
4709 	 * non-zero expected attach type (i.e., not a BPF_CGROUP_INET_INGRESS)
4710 	 * to see if kernel supports expected_attach_type field for
4711 	 * BPF_PROG_LOAD command
4712 	 */
4713 	fd = bpf_prog_load(BPF_PROG_TYPE_CGROUP_SOCK, NULL, "GPL", insns, insn_cnt, &opts);
4714 	return probe_fd(fd);
4715 }
4716 
4717 static int probe_kern_probe_read_kernel(void)
4718 {
4719 	struct bpf_insn insns[] = {
4720 		BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),	/* r1 = r10 (fp) */
4721 		BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -8),	/* r1 += -8 */
4722 		BPF_MOV64_IMM(BPF_REG_2, 8),		/* r2 = 8 */
4723 		BPF_MOV64_IMM(BPF_REG_3, 0),		/* r3 = 0 */
4724 		BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_probe_read_kernel),
4725 		BPF_EXIT_INSN(),
4726 	};
4727 	int fd, insn_cnt = ARRAY_SIZE(insns);
4728 
4729 	fd = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, NULL);
4730 	return probe_fd(fd);
4731 }
4732 
4733 static int probe_prog_bind_map(void)
4734 {
4735 	char *cp, errmsg[STRERR_BUFSIZE];
4736 	struct bpf_insn insns[] = {
4737 		BPF_MOV64_IMM(BPF_REG_0, 0),
4738 		BPF_EXIT_INSN(),
4739 	};
4740 	int ret, map, prog, insn_cnt = ARRAY_SIZE(insns);
4741 
4742 	map = bpf_map_create(BPF_MAP_TYPE_ARRAY, "libbpf_det_bind", sizeof(int), 32, 1, NULL);
4743 	if (map < 0) {
4744 		ret = -errno;
4745 		cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4746 		pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
4747 			__func__, cp, -ret);
4748 		return ret;
4749 	}
4750 
4751 	prog = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4752 	if (prog < 0) {
4753 		close(map);
4754 		return 0;
4755 	}
4756 
4757 	ret = bpf_prog_bind_map(prog, map, NULL);
4758 
4759 	close(map);
4760 	close(prog);
4761 
4762 	return ret >= 0;
4763 }
4764 
4765 static int probe_module_btf(void)
4766 {
4767 	static const char strs[] = "\0int";
4768 	__u32 types[] = {
4769 		/* int */
4770 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),
4771 	};
4772 	struct bpf_btf_info info;
4773 	__u32 len = sizeof(info);
4774 	char name[16];
4775 	int fd, err;
4776 
4777 	fd = libbpf__load_raw_btf((char *)types, sizeof(types), strs, sizeof(strs));
4778 	if (fd < 0)
4779 		return 0; /* BTF not supported at all */
4780 
4781 	memset(&info, 0, sizeof(info));
4782 	info.name = ptr_to_u64(name);
4783 	info.name_len = sizeof(name);
4784 
4785 	/* check that BPF_OBJ_GET_INFO_BY_FD supports specifying name pointer;
4786 	 * kernel's module BTF support coincides with support for
4787 	 * name/name_len fields in struct bpf_btf_info.
4788 	 */
4789 	err = bpf_btf_get_info_by_fd(fd, &info, &len);
4790 	close(fd);
4791 	return !err;
4792 }
4793 
4794 static int probe_perf_link(void)
4795 {
4796 	struct bpf_insn insns[] = {
4797 		BPF_MOV64_IMM(BPF_REG_0, 0),
4798 		BPF_EXIT_INSN(),
4799 	};
4800 	int prog_fd, link_fd, err;
4801 
4802 	prog_fd = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL",
4803 				insns, ARRAY_SIZE(insns), NULL);
4804 	if (prog_fd < 0)
4805 		return -errno;
4806 
4807 	/* use invalid perf_event FD to get EBADF, if link is supported;
4808 	 * otherwise EINVAL should be returned
4809 	 */
4810 	link_fd = bpf_link_create(prog_fd, -1, BPF_PERF_EVENT, NULL);
4811 	err = -errno; /* close() can clobber errno */
4812 
4813 	if (link_fd >= 0)
4814 		close(link_fd);
4815 	close(prog_fd);
4816 
4817 	return link_fd < 0 && err == -EBADF;
4818 }
4819 
4820 static int probe_kern_bpf_cookie(void)
4821 {
4822 	struct bpf_insn insns[] = {
4823 		BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_get_attach_cookie),
4824 		BPF_EXIT_INSN(),
4825 	};
4826 	int ret, insn_cnt = ARRAY_SIZE(insns);
4827 
4828 	ret = bpf_prog_load(BPF_PROG_TYPE_KPROBE, NULL, "GPL", insns, insn_cnt, NULL);
4829 	return probe_fd(ret);
4830 }
4831 
4832 static int probe_kern_btf_enum64(void)
4833 {
4834 	static const char strs[] = "\0enum64";
4835 	__u32 types[] = {
4836 		BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_ENUM64, 0, 0), 8),
4837 	};
4838 
4839 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4840 					     strs, sizeof(strs)));
4841 }
4842 
4843 static int probe_kern_syscall_wrapper(void);
4844 
4845 enum kern_feature_result {
4846 	FEAT_UNKNOWN = 0,
4847 	FEAT_SUPPORTED = 1,
4848 	FEAT_MISSING = 2,
4849 };
4850 
4851 typedef int (*feature_probe_fn)(void);
4852 
4853 static struct kern_feature_desc {
4854 	const char *desc;
4855 	feature_probe_fn probe;
4856 	enum kern_feature_result res;
4857 } feature_probes[__FEAT_CNT] = {
4858 	[FEAT_PROG_NAME] = {
4859 		"BPF program name", probe_kern_prog_name,
4860 	},
4861 	[FEAT_GLOBAL_DATA] = {
4862 		"global variables", probe_kern_global_data,
4863 	},
4864 	[FEAT_BTF] = {
4865 		"minimal BTF", probe_kern_btf,
4866 	},
4867 	[FEAT_BTF_FUNC] = {
4868 		"BTF functions", probe_kern_btf_func,
4869 	},
4870 	[FEAT_BTF_GLOBAL_FUNC] = {
4871 		"BTF global function", probe_kern_btf_func_global,
4872 	},
4873 	[FEAT_BTF_DATASEC] = {
4874 		"BTF data section and variable", probe_kern_btf_datasec,
4875 	},
4876 	[FEAT_ARRAY_MMAP] = {
4877 		"ARRAY map mmap()", probe_kern_array_mmap,
4878 	},
4879 	[FEAT_EXP_ATTACH_TYPE] = {
4880 		"BPF_PROG_LOAD expected_attach_type attribute",
4881 		probe_kern_exp_attach_type,
4882 	},
4883 	[FEAT_PROBE_READ_KERN] = {
4884 		"bpf_probe_read_kernel() helper", probe_kern_probe_read_kernel,
4885 	},
4886 	[FEAT_PROG_BIND_MAP] = {
4887 		"BPF_PROG_BIND_MAP support", probe_prog_bind_map,
4888 	},
4889 	[FEAT_MODULE_BTF] = {
4890 		"module BTF support", probe_module_btf,
4891 	},
4892 	[FEAT_BTF_FLOAT] = {
4893 		"BTF_KIND_FLOAT support", probe_kern_btf_float,
4894 	},
4895 	[FEAT_PERF_LINK] = {
4896 		"BPF perf link support", probe_perf_link,
4897 	},
4898 	[FEAT_BTF_DECL_TAG] = {
4899 		"BTF_KIND_DECL_TAG support", probe_kern_btf_decl_tag,
4900 	},
4901 	[FEAT_BTF_TYPE_TAG] = {
4902 		"BTF_KIND_TYPE_TAG support", probe_kern_btf_type_tag,
4903 	},
4904 	[FEAT_MEMCG_ACCOUNT] = {
4905 		"memcg-based memory accounting", probe_memcg_account,
4906 	},
4907 	[FEAT_BPF_COOKIE] = {
4908 		"BPF cookie support", probe_kern_bpf_cookie,
4909 	},
4910 	[FEAT_BTF_ENUM64] = {
4911 		"BTF_KIND_ENUM64 support", probe_kern_btf_enum64,
4912 	},
4913 	[FEAT_SYSCALL_WRAPPER] = {
4914 		"Kernel using syscall wrapper", probe_kern_syscall_wrapper,
4915 	},
4916 };
4917 
4918 bool kernel_supports(const struct bpf_object *obj, enum kern_feature_id feat_id)
4919 {
4920 	struct kern_feature_desc *feat = &feature_probes[feat_id];
4921 	int ret;
4922 
4923 	if (obj && obj->gen_loader)
4924 		/* To generate loader program assume the latest kernel
4925 		 * to avoid doing extra prog_load, map_create syscalls.
4926 		 */
4927 		return true;
4928 
4929 	if (READ_ONCE(feat->res) == FEAT_UNKNOWN) {
4930 		ret = feat->probe();
4931 		if (ret > 0) {
4932 			WRITE_ONCE(feat->res, FEAT_SUPPORTED);
4933 		} else if (ret == 0) {
4934 			WRITE_ONCE(feat->res, FEAT_MISSING);
4935 		} else {
4936 			pr_warn("Detection of kernel %s support failed: %d\n", feat->desc, ret);
4937 			WRITE_ONCE(feat->res, FEAT_MISSING);
4938 		}
4939 	}
4940 
4941 	return READ_ONCE(feat->res) == FEAT_SUPPORTED;
4942 }
4943 
4944 static bool map_is_reuse_compat(const struct bpf_map *map, int map_fd)
4945 {
4946 	struct bpf_map_info map_info;
4947 	char msg[STRERR_BUFSIZE];
4948 	__u32 map_info_len = sizeof(map_info);
4949 	int err;
4950 
4951 	memset(&map_info, 0, map_info_len);
4952 	err = bpf_map_get_info_by_fd(map_fd, &map_info, &map_info_len);
4953 	if (err && errno == EINVAL)
4954 		err = bpf_get_map_info_from_fdinfo(map_fd, &map_info);
4955 	if (err) {
4956 		pr_warn("failed to get map info for map FD %d: %s\n", map_fd,
4957 			libbpf_strerror_r(errno, msg, sizeof(msg)));
4958 		return false;
4959 	}
4960 
4961 	return (map_info.type == map->def.type &&
4962 		map_info.key_size == map->def.key_size &&
4963 		map_info.value_size == map->def.value_size &&
4964 		map_info.max_entries == map->def.max_entries &&
4965 		map_info.map_flags == map->def.map_flags &&
4966 		map_info.map_extra == map->map_extra);
4967 }
4968 
4969 static int
4970 bpf_object__reuse_map(struct bpf_map *map)
4971 {
4972 	char *cp, errmsg[STRERR_BUFSIZE];
4973 	int err, pin_fd;
4974 
4975 	pin_fd = bpf_obj_get(map->pin_path);
4976 	if (pin_fd < 0) {
4977 		err = -errno;
4978 		if (err == -ENOENT) {
4979 			pr_debug("found no pinned map to reuse at '%s'\n",
4980 				 map->pin_path);
4981 			return 0;
4982 		}
4983 
4984 		cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
4985 		pr_warn("couldn't retrieve pinned map '%s': %s\n",
4986 			map->pin_path, cp);
4987 		return err;
4988 	}
4989 
4990 	if (!map_is_reuse_compat(map, pin_fd)) {
4991 		pr_warn("couldn't reuse pinned map at '%s': parameter mismatch\n",
4992 			map->pin_path);
4993 		close(pin_fd);
4994 		return -EINVAL;
4995 	}
4996 
4997 	err = bpf_map__reuse_fd(map, pin_fd);
4998 	close(pin_fd);
4999 	if (err)
5000 		return err;
5001 
5002 	map->pinned = true;
5003 	pr_debug("reused pinned map at '%s'\n", map->pin_path);
5004 
5005 	return 0;
5006 }
5007 
5008 static int
5009 bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
5010 {
5011 	enum libbpf_map_type map_type = map->libbpf_type;
5012 	char *cp, errmsg[STRERR_BUFSIZE];
5013 	int err, zero = 0;
5014 
5015 	if (obj->gen_loader) {
5016 		bpf_gen__map_update_elem(obj->gen_loader, map - obj->maps,
5017 					 map->mmaped, map->def.value_size);
5018 		if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG)
5019 			bpf_gen__map_freeze(obj->gen_loader, map - obj->maps);
5020 		return 0;
5021 	}
5022 	err = bpf_map_update_elem(map->fd, &zero, map->mmaped, 0);
5023 	if (err) {
5024 		err = -errno;
5025 		cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5026 		pr_warn("Error setting initial map(%s) contents: %s\n",
5027 			map->name, cp);
5028 		return err;
5029 	}
5030 
5031 	/* Freeze .rodata and .kconfig map as read-only from syscall side. */
5032 	if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG) {
5033 		err = bpf_map_freeze(map->fd);
5034 		if (err) {
5035 			err = -errno;
5036 			cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5037 			pr_warn("Error freezing map(%s) as read-only: %s\n",
5038 				map->name, cp);
5039 			return err;
5040 		}
5041 	}
5042 	return 0;
5043 }
5044 
5045 static void bpf_map__destroy(struct bpf_map *map);
5046 
5047 static int bpf_object__create_map(struct bpf_object *obj, struct bpf_map *map, bool is_inner)
5048 {
5049 	LIBBPF_OPTS(bpf_map_create_opts, create_attr);
5050 	struct bpf_map_def *def = &map->def;
5051 	const char *map_name = NULL;
5052 	int err = 0;
5053 
5054 	if (kernel_supports(obj, FEAT_PROG_NAME))
5055 		map_name = map->name;
5056 	create_attr.map_ifindex = map->map_ifindex;
5057 	create_attr.map_flags = def->map_flags;
5058 	create_attr.numa_node = map->numa_node;
5059 	create_attr.map_extra = map->map_extra;
5060 
5061 	if (bpf_map__is_struct_ops(map))
5062 		create_attr.btf_vmlinux_value_type_id = map->btf_vmlinux_value_type_id;
5063 
5064 	if (obj->btf && btf__fd(obj->btf) >= 0) {
5065 		create_attr.btf_fd = btf__fd(obj->btf);
5066 		create_attr.btf_key_type_id = map->btf_key_type_id;
5067 		create_attr.btf_value_type_id = map->btf_value_type_id;
5068 	}
5069 
5070 	if (bpf_map_type__is_map_in_map(def->type)) {
5071 		if (map->inner_map) {
5072 			err = bpf_object__create_map(obj, map->inner_map, true);
5073 			if (err) {
5074 				pr_warn("map '%s': failed to create inner map: %d\n",
5075 					map->name, err);
5076 				return err;
5077 			}
5078 			map->inner_map_fd = bpf_map__fd(map->inner_map);
5079 		}
5080 		if (map->inner_map_fd >= 0)
5081 			create_attr.inner_map_fd = map->inner_map_fd;
5082 	}
5083 
5084 	switch (def->type) {
5085 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
5086 	case BPF_MAP_TYPE_CGROUP_ARRAY:
5087 	case BPF_MAP_TYPE_STACK_TRACE:
5088 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
5089 	case BPF_MAP_TYPE_HASH_OF_MAPS:
5090 	case BPF_MAP_TYPE_DEVMAP:
5091 	case BPF_MAP_TYPE_DEVMAP_HASH:
5092 	case BPF_MAP_TYPE_CPUMAP:
5093 	case BPF_MAP_TYPE_XSKMAP:
5094 	case BPF_MAP_TYPE_SOCKMAP:
5095 	case BPF_MAP_TYPE_SOCKHASH:
5096 	case BPF_MAP_TYPE_QUEUE:
5097 	case BPF_MAP_TYPE_STACK:
5098 		create_attr.btf_fd = 0;
5099 		create_attr.btf_key_type_id = 0;
5100 		create_attr.btf_value_type_id = 0;
5101 		map->btf_key_type_id = 0;
5102 		map->btf_value_type_id = 0;
5103 	default:
5104 		break;
5105 	}
5106 
5107 	if (obj->gen_loader) {
5108 		bpf_gen__map_create(obj->gen_loader, def->type, map_name,
5109 				    def->key_size, def->value_size, def->max_entries,
5110 				    &create_attr, is_inner ? -1 : map - obj->maps);
5111 		/* Pretend to have valid FD to pass various fd >= 0 checks.
5112 		 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
5113 		 */
5114 		map->fd = 0;
5115 	} else {
5116 		map->fd = bpf_map_create(def->type, map_name,
5117 					 def->key_size, def->value_size,
5118 					 def->max_entries, &create_attr);
5119 	}
5120 	if (map->fd < 0 && (create_attr.btf_key_type_id ||
5121 			    create_attr.btf_value_type_id)) {
5122 		char *cp, errmsg[STRERR_BUFSIZE];
5123 
5124 		err = -errno;
5125 		cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5126 		pr_warn("Error in bpf_create_map_xattr(%s):%s(%d). Retrying without BTF.\n",
5127 			map->name, cp, err);
5128 		create_attr.btf_fd = 0;
5129 		create_attr.btf_key_type_id = 0;
5130 		create_attr.btf_value_type_id = 0;
5131 		map->btf_key_type_id = 0;
5132 		map->btf_value_type_id = 0;
5133 		map->fd = bpf_map_create(def->type, map_name,
5134 					 def->key_size, def->value_size,
5135 					 def->max_entries, &create_attr);
5136 	}
5137 
5138 	err = map->fd < 0 ? -errno : 0;
5139 
5140 	if (bpf_map_type__is_map_in_map(def->type) && map->inner_map) {
5141 		if (obj->gen_loader)
5142 			map->inner_map->fd = -1;
5143 		bpf_map__destroy(map->inner_map);
5144 		zfree(&map->inner_map);
5145 	}
5146 
5147 	return err;
5148 }
5149 
5150 static int init_map_in_map_slots(struct bpf_object *obj, struct bpf_map *map)
5151 {
5152 	const struct bpf_map *targ_map;
5153 	unsigned int i;
5154 	int fd, err = 0;
5155 
5156 	for (i = 0; i < map->init_slots_sz; i++) {
5157 		if (!map->init_slots[i])
5158 			continue;
5159 
5160 		targ_map = map->init_slots[i];
5161 		fd = bpf_map__fd(targ_map);
5162 
5163 		if (obj->gen_loader) {
5164 			bpf_gen__populate_outer_map(obj->gen_loader,
5165 						    map - obj->maps, i,
5166 						    targ_map - obj->maps);
5167 		} else {
5168 			err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5169 		}
5170 		if (err) {
5171 			err = -errno;
5172 			pr_warn("map '%s': failed to initialize slot [%d] to map '%s' fd=%d: %d\n",
5173 				map->name, i, targ_map->name, fd, err);
5174 			return err;
5175 		}
5176 		pr_debug("map '%s': slot [%d] set to map '%s' fd=%d\n",
5177 			 map->name, i, targ_map->name, fd);
5178 	}
5179 
5180 	zfree(&map->init_slots);
5181 	map->init_slots_sz = 0;
5182 
5183 	return 0;
5184 }
5185 
5186 static int init_prog_array_slots(struct bpf_object *obj, struct bpf_map *map)
5187 {
5188 	const struct bpf_program *targ_prog;
5189 	unsigned int i;
5190 	int fd, err;
5191 
5192 	if (obj->gen_loader)
5193 		return -ENOTSUP;
5194 
5195 	for (i = 0; i < map->init_slots_sz; i++) {
5196 		if (!map->init_slots[i])
5197 			continue;
5198 
5199 		targ_prog = map->init_slots[i];
5200 		fd = bpf_program__fd(targ_prog);
5201 
5202 		err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5203 		if (err) {
5204 			err = -errno;
5205 			pr_warn("map '%s': failed to initialize slot [%d] to prog '%s' fd=%d: %d\n",
5206 				map->name, i, targ_prog->name, fd, err);
5207 			return err;
5208 		}
5209 		pr_debug("map '%s': slot [%d] set to prog '%s' fd=%d\n",
5210 			 map->name, i, targ_prog->name, fd);
5211 	}
5212 
5213 	zfree(&map->init_slots);
5214 	map->init_slots_sz = 0;
5215 
5216 	return 0;
5217 }
5218 
5219 static int bpf_object_init_prog_arrays(struct bpf_object *obj)
5220 {
5221 	struct bpf_map *map;
5222 	int i, err;
5223 
5224 	for (i = 0; i < obj->nr_maps; i++) {
5225 		map = &obj->maps[i];
5226 
5227 		if (!map->init_slots_sz || map->def.type != BPF_MAP_TYPE_PROG_ARRAY)
5228 			continue;
5229 
5230 		err = init_prog_array_slots(obj, map);
5231 		if (err < 0) {
5232 			zclose(map->fd);
5233 			return err;
5234 		}
5235 	}
5236 	return 0;
5237 }
5238 
5239 static int map_set_def_max_entries(struct bpf_map *map)
5240 {
5241 	if (map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY && !map->def.max_entries) {
5242 		int nr_cpus;
5243 
5244 		nr_cpus = libbpf_num_possible_cpus();
5245 		if (nr_cpus < 0) {
5246 			pr_warn("map '%s': failed to determine number of system CPUs: %d\n",
5247 				map->name, nr_cpus);
5248 			return nr_cpus;
5249 		}
5250 		pr_debug("map '%s': setting size to %d\n", map->name, nr_cpus);
5251 		map->def.max_entries = nr_cpus;
5252 	}
5253 
5254 	return 0;
5255 }
5256 
5257 static int
5258 bpf_object__create_maps(struct bpf_object *obj)
5259 {
5260 	struct bpf_map *map;
5261 	char *cp, errmsg[STRERR_BUFSIZE];
5262 	unsigned int i, j;
5263 	int err;
5264 	bool retried;
5265 
5266 	for (i = 0; i < obj->nr_maps; i++) {
5267 		map = &obj->maps[i];
5268 
5269 		/* To support old kernels, we skip creating global data maps
5270 		 * (.rodata, .data, .kconfig, etc); later on, during program
5271 		 * loading, if we detect that at least one of the to-be-loaded
5272 		 * programs is referencing any global data map, we'll error
5273 		 * out with program name and relocation index logged.
5274 		 * This approach allows to accommodate Clang emitting
5275 		 * unnecessary .rodata.str1.1 sections for string literals,
5276 		 * but also it allows to have CO-RE applications that use
5277 		 * global variables in some of BPF programs, but not others.
5278 		 * If those global variable-using programs are not loaded at
5279 		 * runtime due to bpf_program__set_autoload(prog, false),
5280 		 * bpf_object loading will succeed just fine even on old
5281 		 * kernels.
5282 		 */
5283 		if (bpf_map__is_internal(map) && !kernel_supports(obj, FEAT_GLOBAL_DATA))
5284 			map->autocreate = false;
5285 
5286 		if (!map->autocreate) {
5287 			pr_debug("map '%s': skipped auto-creating...\n", map->name);
5288 			continue;
5289 		}
5290 
5291 		err = map_set_def_max_entries(map);
5292 		if (err)
5293 			goto err_out;
5294 
5295 		retried = false;
5296 retry:
5297 		if (map->pin_path) {
5298 			err = bpf_object__reuse_map(map);
5299 			if (err) {
5300 				pr_warn("map '%s': error reusing pinned map\n",
5301 					map->name);
5302 				goto err_out;
5303 			}
5304 			if (retried && map->fd < 0) {
5305 				pr_warn("map '%s': cannot find pinned map\n",
5306 					map->name);
5307 				err = -ENOENT;
5308 				goto err_out;
5309 			}
5310 		}
5311 
5312 		if (map->fd >= 0) {
5313 			pr_debug("map '%s': skipping creation (preset fd=%d)\n",
5314 				 map->name, map->fd);
5315 		} else {
5316 			err = bpf_object__create_map(obj, map, false);
5317 			if (err)
5318 				goto err_out;
5319 
5320 			pr_debug("map '%s': created successfully, fd=%d\n",
5321 				 map->name, map->fd);
5322 
5323 			if (bpf_map__is_internal(map)) {
5324 				err = bpf_object__populate_internal_map(obj, map);
5325 				if (err < 0) {
5326 					zclose(map->fd);
5327 					goto err_out;
5328 				}
5329 			}
5330 
5331 			if (map->init_slots_sz && map->def.type != BPF_MAP_TYPE_PROG_ARRAY) {
5332 				err = init_map_in_map_slots(obj, map);
5333 				if (err < 0) {
5334 					zclose(map->fd);
5335 					goto err_out;
5336 				}
5337 			}
5338 		}
5339 
5340 		if (map->pin_path && !map->pinned) {
5341 			err = bpf_map__pin(map, NULL);
5342 			if (err) {
5343 				zclose(map->fd);
5344 				if (!retried && err == -EEXIST) {
5345 					retried = true;
5346 					goto retry;
5347 				}
5348 				pr_warn("map '%s': failed to auto-pin at '%s': %d\n",
5349 					map->name, map->pin_path, err);
5350 				goto err_out;
5351 			}
5352 		}
5353 	}
5354 
5355 	return 0;
5356 
5357 err_out:
5358 	cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5359 	pr_warn("map '%s': failed to create: %s(%d)\n", map->name, cp, err);
5360 	pr_perm_msg(err);
5361 	for (j = 0; j < i; j++)
5362 		zclose(obj->maps[j].fd);
5363 	return err;
5364 }
5365 
5366 static bool bpf_core_is_flavor_sep(const char *s)
5367 {
5368 	/* check X___Y name pattern, where X and Y are not underscores */
5369 	return s[0] != '_' &&				      /* X */
5370 	       s[1] == '_' && s[2] == '_' && s[3] == '_' &&   /* ___ */
5371 	       s[4] != '_';				      /* Y */
5372 }
5373 
5374 /* Given 'some_struct_name___with_flavor' return the length of a name prefix
5375  * before last triple underscore. Struct name part after last triple
5376  * underscore is ignored by BPF CO-RE relocation during relocation matching.
5377  */
5378 size_t bpf_core_essential_name_len(const char *name)
5379 {
5380 	size_t n = strlen(name);
5381 	int i;
5382 
5383 	for (i = n - 5; i >= 0; i--) {
5384 		if (bpf_core_is_flavor_sep(name + i))
5385 			return i + 1;
5386 	}
5387 	return n;
5388 }
5389 
5390 void bpf_core_free_cands(struct bpf_core_cand_list *cands)
5391 {
5392 	if (!cands)
5393 		return;
5394 
5395 	free(cands->cands);
5396 	free(cands);
5397 }
5398 
5399 int bpf_core_add_cands(struct bpf_core_cand *local_cand,
5400 		       size_t local_essent_len,
5401 		       const struct btf *targ_btf,
5402 		       const char *targ_btf_name,
5403 		       int targ_start_id,
5404 		       struct bpf_core_cand_list *cands)
5405 {
5406 	struct bpf_core_cand *new_cands, *cand;
5407 	const struct btf_type *t, *local_t;
5408 	const char *targ_name, *local_name;
5409 	size_t targ_essent_len;
5410 	int n, i;
5411 
5412 	local_t = btf__type_by_id(local_cand->btf, local_cand->id);
5413 	local_name = btf__str_by_offset(local_cand->btf, local_t->name_off);
5414 
5415 	n = btf__type_cnt(targ_btf);
5416 	for (i = targ_start_id; i < n; i++) {
5417 		t = btf__type_by_id(targ_btf, i);
5418 		if (!btf_kind_core_compat(t, local_t))
5419 			continue;
5420 
5421 		targ_name = btf__name_by_offset(targ_btf, t->name_off);
5422 		if (str_is_empty(targ_name))
5423 			continue;
5424 
5425 		targ_essent_len = bpf_core_essential_name_len(targ_name);
5426 		if (targ_essent_len != local_essent_len)
5427 			continue;
5428 
5429 		if (strncmp(local_name, targ_name, local_essent_len) != 0)
5430 			continue;
5431 
5432 		pr_debug("CO-RE relocating [%d] %s %s: found target candidate [%d] %s %s in [%s]\n",
5433 			 local_cand->id, btf_kind_str(local_t),
5434 			 local_name, i, btf_kind_str(t), targ_name,
5435 			 targ_btf_name);
5436 		new_cands = libbpf_reallocarray(cands->cands, cands->len + 1,
5437 					      sizeof(*cands->cands));
5438 		if (!new_cands)
5439 			return -ENOMEM;
5440 
5441 		cand = &new_cands[cands->len];
5442 		cand->btf = targ_btf;
5443 		cand->id = i;
5444 
5445 		cands->cands = new_cands;
5446 		cands->len++;
5447 	}
5448 	return 0;
5449 }
5450 
5451 static int load_module_btfs(struct bpf_object *obj)
5452 {
5453 	struct bpf_btf_info info;
5454 	struct module_btf *mod_btf;
5455 	struct btf *btf;
5456 	char name[64];
5457 	__u32 id = 0, len;
5458 	int err, fd;
5459 
5460 	if (obj->btf_modules_loaded)
5461 		return 0;
5462 
5463 	if (obj->gen_loader)
5464 		return 0;
5465 
5466 	/* don't do this again, even if we find no module BTFs */
5467 	obj->btf_modules_loaded = true;
5468 
5469 	/* kernel too old to support module BTFs */
5470 	if (!kernel_supports(obj, FEAT_MODULE_BTF))
5471 		return 0;
5472 
5473 	while (true) {
5474 		err = bpf_btf_get_next_id(id, &id);
5475 		if (err && errno == ENOENT)
5476 			return 0;
5477 		if (err && errno == EPERM) {
5478 			pr_debug("skipping module BTFs loading, missing privileges\n");
5479 			return 0;
5480 		}
5481 		if (err) {
5482 			err = -errno;
5483 			pr_warn("failed to iterate BTF objects: %d\n", err);
5484 			return err;
5485 		}
5486 
5487 		fd = bpf_btf_get_fd_by_id(id);
5488 		if (fd < 0) {
5489 			if (errno == ENOENT)
5490 				continue; /* expected race: BTF was unloaded */
5491 			err = -errno;
5492 			pr_warn("failed to get BTF object #%d FD: %d\n", id, err);
5493 			return err;
5494 		}
5495 
5496 		len = sizeof(info);
5497 		memset(&info, 0, sizeof(info));
5498 		info.name = ptr_to_u64(name);
5499 		info.name_len = sizeof(name);
5500 
5501 		err = bpf_btf_get_info_by_fd(fd, &info, &len);
5502 		if (err) {
5503 			err = -errno;
5504 			pr_warn("failed to get BTF object #%d info: %d\n", id, err);
5505 			goto err_out;
5506 		}
5507 
5508 		/* ignore non-module BTFs */
5509 		if (!info.kernel_btf || strcmp(name, "vmlinux") == 0) {
5510 			close(fd);
5511 			continue;
5512 		}
5513 
5514 		btf = btf_get_from_fd(fd, obj->btf_vmlinux);
5515 		err = libbpf_get_error(btf);
5516 		if (err) {
5517 			pr_warn("failed to load module [%s]'s BTF object #%d: %d\n",
5518 				name, id, err);
5519 			goto err_out;
5520 		}
5521 
5522 		err = libbpf_ensure_mem((void **)&obj->btf_modules, &obj->btf_module_cap,
5523 					sizeof(*obj->btf_modules), obj->btf_module_cnt + 1);
5524 		if (err)
5525 			goto err_out;
5526 
5527 		mod_btf = &obj->btf_modules[obj->btf_module_cnt++];
5528 
5529 		mod_btf->btf = btf;
5530 		mod_btf->id = id;
5531 		mod_btf->fd = fd;
5532 		mod_btf->name = strdup(name);
5533 		if (!mod_btf->name) {
5534 			err = -ENOMEM;
5535 			goto err_out;
5536 		}
5537 		continue;
5538 
5539 err_out:
5540 		close(fd);
5541 		return err;
5542 	}
5543 
5544 	return 0;
5545 }
5546 
5547 static struct bpf_core_cand_list *
5548 bpf_core_find_cands(struct bpf_object *obj, const struct btf *local_btf, __u32 local_type_id)
5549 {
5550 	struct bpf_core_cand local_cand = {};
5551 	struct bpf_core_cand_list *cands;
5552 	const struct btf *main_btf;
5553 	const struct btf_type *local_t;
5554 	const char *local_name;
5555 	size_t local_essent_len;
5556 	int err, i;
5557 
5558 	local_cand.btf = local_btf;
5559 	local_cand.id = local_type_id;
5560 	local_t = btf__type_by_id(local_btf, local_type_id);
5561 	if (!local_t)
5562 		return ERR_PTR(-EINVAL);
5563 
5564 	local_name = btf__name_by_offset(local_btf, local_t->name_off);
5565 	if (str_is_empty(local_name))
5566 		return ERR_PTR(-EINVAL);
5567 	local_essent_len = bpf_core_essential_name_len(local_name);
5568 
5569 	cands = calloc(1, sizeof(*cands));
5570 	if (!cands)
5571 		return ERR_PTR(-ENOMEM);
5572 
5573 	/* Attempt to find target candidates in vmlinux BTF first */
5574 	main_btf = obj->btf_vmlinux_override ?: obj->btf_vmlinux;
5575 	err = bpf_core_add_cands(&local_cand, local_essent_len, main_btf, "vmlinux", 1, cands);
5576 	if (err)
5577 		goto err_out;
5578 
5579 	/* if vmlinux BTF has any candidate, don't got for module BTFs */
5580 	if (cands->len)
5581 		return cands;
5582 
5583 	/* if vmlinux BTF was overridden, don't attempt to load module BTFs */
5584 	if (obj->btf_vmlinux_override)
5585 		return cands;
5586 
5587 	/* now look through module BTFs, trying to still find candidates */
5588 	err = load_module_btfs(obj);
5589 	if (err)
5590 		goto err_out;
5591 
5592 	for (i = 0; i < obj->btf_module_cnt; i++) {
5593 		err = bpf_core_add_cands(&local_cand, local_essent_len,
5594 					 obj->btf_modules[i].btf,
5595 					 obj->btf_modules[i].name,
5596 					 btf__type_cnt(obj->btf_vmlinux),
5597 					 cands);
5598 		if (err)
5599 			goto err_out;
5600 	}
5601 
5602 	return cands;
5603 err_out:
5604 	bpf_core_free_cands(cands);
5605 	return ERR_PTR(err);
5606 }
5607 
5608 /* Check local and target types for compatibility. This check is used for
5609  * type-based CO-RE relocations and follow slightly different rules than
5610  * field-based relocations. This function assumes that root types were already
5611  * checked for name match. Beyond that initial root-level name check, names
5612  * are completely ignored. Compatibility rules are as follows:
5613  *   - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs are considered compatible, but
5614  *     kind should match for local and target types (i.e., STRUCT is not
5615  *     compatible with UNION);
5616  *   - for ENUMs, the size is ignored;
5617  *   - for INT, size and signedness are ignored;
5618  *   - for ARRAY, dimensionality is ignored, element types are checked for
5619  *     compatibility recursively;
5620  *   - CONST/VOLATILE/RESTRICT modifiers are ignored;
5621  *   - TYPEDEFs/PTRs are compatible if types they pointing to are compatible;
5622  *   - FUNC_PROTOs are compatible if they have compatible signature: same
5623  *     number of input args and compatible return and argument types.
5624  * These rules are not set in stone and probably will be adjusted as we get
5625  * more experience with using BPF CO-RE relocations.
5626  */
5627 int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
5628 			      const struct btf *targ_btf, __u32 targ_id)
5629 {
5630 	return __bpf_core_types_are_compat(local_btf, local_id, targ_btf, targ_id, 32);
5631 }
5632 
5633 int bpf_core_types_match(const struct btf *local_btf, __u32 local_id,
5634 			 const struct btf *targ_btf, __u32 targ_id)
5635 {
5636 	return __bpf_core_types_match(local_btf, local_id, targ_btf, targ_id, false, 32);
5637 }
5638 
5639 static size_t bpf_core_hash_fn(const long key, void *ctx)
5640 {
5641 	return key;
5642 }
5643 
5644 static bool bpf_core_equal_fn(const long k1, const long k2, void *ctx)
5645 {
5646 	return k1 == k2;
5647 }
5648 
5649 static int record_relo_core(struct bpf_program *prog,
5650 			    const struct bpf_core_relo *core_relo, int insn_idx)
5651 {
5652 	struct reloc_desc *relos, *relo;
5653 
5654 	relos = libbpf_reallocarray(prog->reloc_desc,
5655 				    prog->nr_reloc + 1, sizeof(*relos));
5656 	if (!relos)
5657 		return -ENOMEM;
5658 	relo = &relos[prog->nr_reloc];
5659 	relo->type = RELO_CORE;
5660 	relo->insn_idx = insn_idx;
5661 	relo->core_relo = core_relo;
5662 	prog->reloc_desc = relos;
5663 	prog->nr_reloc++;
5664 	return 0;
5665 }
5666 
5667 static const struct bpf_core_relo *find_relo_core(struct bpf_program *prog, int insn_idx)
5668 {
5669 	struct reloc_desc *relo;
5670 	int i;
5671 
5672 	for (i = 0; i < prog->nr_reloc; i++) {
5673 		relo = &prog->reloc_desc[i];
5674 		if (relo->type != RELO_CORE || relo->insn_idx != insn_idx)
5675 			continue;
5676 
5677 		return relo->core_relo;
5678 	}
5679 
5680 	return NULL;
5681 }
5682 
5683 static int bpf_core_resolve_relo(struct bpf_program *prog,
5684 				 const struct bpf_core_relo *relo,
5685 				 int relo_idx,
5686 				 const struct btf *local_btf,
5687 				 struct hashmap *cand_cache,
5688 				 struct bpf_core_relo_res *targ_res)
5689 {
5690 	struct bpf_core_spec specs_scratch[3] = {};
5691 	struct bpf_core_cand_list *cands = NULL;
5692 	const char *prog_name = prog->name;
5693 	const struct btf_type *local_type;
5694 	const char *local_name;
5695 	__u32 local_id = relo->type_id;
5696 	int err;
5697 
5698 	local_type = btf__type_by_id(local_btf, local_id);
5699 	if (!local_type)
5700 		return -EINVAL;
5701 
5702 	local_name = btf__name_by_offset(local_btf, local_type->name_off);
5703 	if (!local_name)
5704 		return -EINVAL;
5705 
5706 	if (relo->kind != BPF_CORE_TYPE_ID_LOCAL &&
5707 	    !hashmap__find(cand_cache, local_id, &cands)) {
5708 		cands = bpf_core_find_cands(prog->obj, local_btf, local_id);
5709 		if (IS_ERR(cands)) {
5710 			pr_warn("prog '%s': relo #%d: target candidate search failed for [%d] %s %s: %ld\n",
5711 				prog_name, relo_idx, local_id, btf_kind_str(local_type),
5712 				local_name, PTR_ERR(cands));
5713 			return PTR_ERR(cands);
5714 		}
5715 		err = hashmap__set(cand_cache, local_id, cands, NULL, NULL);
5716 		if (err) {
5717 			bpf_core_free_cands(cands);
5718 			return err;
5719 		}
5720 	}
5721 
5722 	return bpf_core_calc_relo_insn(prog_name, relo, relo_idx, local_btf, cands, specs_scratch,
5723 				       targ_res);
5724 }
5725 
5726 static int
5727 bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
5728 {
5729 	const struct btf_ext_info_sec *sec;
5730 	struct bpf_core_relo_res targ_res;
5731 	const struct bpf_core_relo *rec;
5732 	const struct btf_ext_info *seg;
5733 	struct hashmap_entry *entry;
5734 	struct hashmap *cand_cache = NULL;
5735 	struct bpf_program *prog;
5736 	struct bpf_insn *insn;
5737 	const char *sec_name;
5738 	int i, err = 0, insn_idx, sec_idx, sec_num;
5739 
5740 	if (obj->btf_ext->core_relo_info.len == 0)
5741 		return 0;
5742 
5743 	if (targ_btf_path) {
5744 		obj->btf_vmlinux_override = btf__parse(targ_btf_path, NULL);
5745 		err = libbpf_get_error(obj->btf_vmlinux_override);
5746 		if (err) {
5747 			pr_warn("failed to parse target BTF: %d\n", err);
5748 			return err;
5749 		}
5750 	}
5751 
5752 	cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
5753 	if (IS_ERR(cand_cache)) {
5754 		err = PTR_ERR(cand_cache);
5755 		goto out;
5756 	}
5757 
5758 	seg = &obj->btf_ext->core_relo_info;
5759 	sec_num = 0;
5760 	for_each_btf_ext_sec(seg, sec) {
5761 		sec_idx = seg->sec_idxs[sec_num];
5762 		sec_num++;
5763 
5764 		sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
5765 		if (str_is_empty(sec_name)) {
5766 			err = -EINVAL;
5767 			goto out;
5768 		}
5769 
5770 		pr_debug("sec '%s': found %d CO-RE relocations\n", sec_name, sec->num_info);
5771 
5772 		for_each_btf_ext_rec(seg, sec, i, rec) {
5773 			if (rec->insn_off % BPF_INSN_SZ)
5774 				return -EINVAL;
5775 			insn_idx = rec->insn_off / BPF_INSN_SZ;
5776 			prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
5777 			if (!prog) {
5778 				/* When __weak subprog is "overridden" by another instance
5779 				 * of the subprog from a different object file, linker still
5780 				 * appends all the .BTF.ext info that used to belong to that
5781 				 * eliminated subprogram.
5782 				 * This is similar to what x86-64 linker does for relocations.
5783 				 * So just ignore such relocations just like we ignore
5784 				 * subprog instructions when discovering subprograms.
5785 				 */
5786 				pr_debug("sec '%s': skipping CO-RE relocation #%d for insn #%d belonging to eliminated weak subprogram\n",
5787 					 sec_name, i, insn_idx);
5788 				continue;
5789 			}
5790 			/* no need to apply CO-RE relocation if the program is
5791 			 * not going to be loaded
5792 			 */
5793 			if (!prog->autoload)
5794 				continue;
5795 
5796 			/* adjust insn_idx from section frame of reference to the local
5797 			 * program's frame of reference; (sub-)program code is not yet
5798 			 * relocated, so it's enough to just subtract in-section offset
5799 			 */
5800 			insn_idx = insn_idx - prog->sec_insn_off;
5801 			if (insn_idx >= prog->insns_cnt)
5802 				return -EINVAL;
5803 			insn = &prog->insns[insn_idx];
5804 
5805 			err = record_relo_core(prog, rec, insn_idx);
5806 			if (err) {
5807 				pr_warn("prog '%s': relo #%d: failed to record relocation: %d\n",
5808 					prog->name, i, err);
5809 				goto out;
5810 			}
5811 
5812 			if (prog->obj->gen_loader)
5813 				continue;
5814 
5815 			err = bpf_core_resolve_relo(prog, rec, i, obj->btf, cand_cache, &targ_res);
5816 			if (err) {
5817 				pr_warn("prog '%s': relo #%d: failed to relocate: %d\n",
5818 					prog->name, i, err);
5819 				goto out;
5820 			}
5821 
5822 			err = bpf_core_patch_insn(prog->name, insn, insn_idx, rec, i, &targ_res);
5823 			if (err) {
5824 				pr_warn("prog '%s': relo #%d: failed to patch insn #%u: %d\n",
5825 					prog->name, i, insn_idx, err);
5826 				goto out;
5827 			}
5828 		}
5829 	}
5830 
5831 out:
5832 	/* obj->btf_vmlinux and module BTFs are freed after object load */
5833 	btf__free(obj->btf_vmlinux_override);
5834 	obj->btf_vmlinux_override = NULL;
5835 
5836 	if (!IS_ERR_OR_NULL(cand_cache)) {
5837 		hashmap__for_each_entry(cand_cache, entry, i) {
5838 			bpf_core_free_cands(entry->pvalue);
5839 		}
5840 		hashmap__free(cand_cache);
5841 	}
5842 	return err;
5843 }
5844 
5845 /* base map load ldimm64 special constant, used also for log fixup logic */
5846 #define POISON_LDIMM64_MAP_BASE 2001000000
5847 #define POISON_LDIMM64_MAP_PFX "200100"
5848 
5849 static void poison_map_ldimm64(struct bpf_program *prog, int relo_idx,
5850 			       int insn_idx, struct bpf_insn *insn,
5851 			       int map_idx, const struct bpf_map *map)
5852 {
5853 	int i;
5854 
5855 	pr_debug("prog '%s': relo #%d: poisoning insn #%d that loads map #%d '%s'\n",
5856 		 prog->name, relo_idx, insn_idx, map_idx, map->name);
5857 
5858 	/* we turn single ldimm64 into two identical invalid calls */
5859 	for (i = 0; i < 2; i++) {
5860 		insn->code = BPF_JMP | BPF_CALL;
5861 		insn->dst_reg = 0;
5862 		insn->src_reg = 0;
5863 		insn->off = 0;
5864 		/* if this instruction is reachable (not a dead code),
5865 		 * verifier will complain with something like:
5866 		 * invalid func unknown#2001000123
5867 		 * where lower 123 is map index into obj->maps[] array
5868 		 */
5869 		insn->imm = POISON_LDIMM64_MAP_BASE + map_idx;
5870 
5871 		insn++;
5872 	}
5873 }
5874 
5875 /* unresolved kfunc call special constant, used also for log fixup logic */
5876 #define POISON_CALL_KFUNC_BASE 2002000000
5877 #define POISON_CALL_KFUNC_PFX "2002"
5878 
5879 static void poison_kfunc_call(struct bpf_program *prog, int relo_idx,
5880 			      int insn_idx, struct bpf_insn *insn,
5881 			      int ext_idx, const struct extern_desc *ext)
5882 {
5883 	pr_debug("prog '%s': relo #%d: poisoning insn #%d that calls kfunc '%s'\n",
5884 		 prog->name, relo_idx, insn_idx, ext->name);
5885 
5886 	/* we turn kfunc call into invalid helper call with identifiable constant */
5887 	insn->code = BPF_JMP | BPF_CALL;
5888 	insn->dst_reg = 0;
5889 	insn->src_reg = 0;
5890 	insn->off = 0;
5891 	/* if this instruction is reachable (not a dead code),
5892 	 * verifier will complain with something like:
5893 	 * invalid func unknown#2001000123
5894 	 * where lower 123 is extern index into obj->externs[] array
5895 	 */
5896 	insn->imm = POISON_CALL_KFUNC_BASE + ext_idx;
5897 }
5898 
5899 /* Relocate data references within program code:
5900  *  - map references;
5901  *  - global variable references;
5902  *  - extern references.
5903  */
5904 static int
5905 bpf_object__relocate_data(struct bpf_object *obj, struct bpf_program *prog)
5906 {
5907 	int i;
5908 
5909 	for (i = 0; i < prog->nr_reloc; i++) {
5910 		struct reloc_desc *relo = &prog->reloc_desc[i];
5911 		struct bpf_insn *insn = &prog->insns[relo->insn_idx];
5912 		const struct bpf_map *map;
5913 		struct extern_desc *ext;
5914 
5915 		switch (relo->type) {
5916 		case RELO_LD64:
5917 			map = &obj->maps[relo->map_idx];
5918 			if (obj->gen_loader) {
5919 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX;
5920 				insn[0].imm = relo->map_idx;
5921 			} else if (map->autocreate) {
5922 				insn[0].src_reg = BPF_PSEUDO_MAP_FD;
5923 				insn[0].imm = map->fd;
5924 			} else {
5925 				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
5926 						   relo->map_idx, map);
5927 			}
5928 			break;
5929 		case RELO_DATA:
5930 			map = &obj->maps[relo->map_idx];
5931 			insn[1].imm = insn[0].imm + relo->sym_off;
5932 			if (obj->gen_loader) {
5933 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
5934 				insn[0].imm = relo->map_idx;
5935 			} else if (map->autocreate) {
5936 				insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
5937 				insn[0].imm = map->fd;
5938 			} else {
5939 				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
5940 						   relo->map_idx, map);
5941 			}
5942 			break;
5943 		case RELO_EXTERN_LD64:
5944 			ext = &obj->externs[relo->ext_idx];
5945 			if (ext->type == EXT_KCFG) {
5946 				if (obj->gen_loader) {
5947 					insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
5948 					insn[0].imm = obj->kconfig_map_idx;
5949 				} else {
5950 					insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
5951 					insn[0].imm = obj->maps[obj->kconfig_map_idx].fd;
5952 				}
5953 				insn[1].imm = ext->kcfg.data_off;
5954 			} else /* EXT_KSYM */ {
5955 				if (ext->ksym.type_id && ext->is_set) { /* typed ksyms */
5956 					insn[0].src_reg = BPF_PSEUDO_BTF_ID;
5957 					insn[0].imm = ext->ksym.kernel_btf_id;
5958 					insn[1].imm = ext->ksym.kernel_btf_obj_fd;
5959 				} else { /* typeless ksyms or unresolved typed ksyms */
5960 					insn[0].imm = (__u32)ext->ksym.addr;
5961 					insn[1].imm = ext->ksym.addr >> 32;
5962 				}
5963 			}
5964 			break;
5965 		case RELO_EXTERN_CALL:
5966 			ext = &obj->externs[relo->ext_idx];
5967 			insn[0].src_reg = BPF_PSEUDO_KFUNC_CALL;
5968 			if (ext->is_set) {
5969 				insn[0].imm = ext->ksym.kernel_btf_id;
5970 				insn[0].off = ext->ksym.btf_fd_idx;
5971 			} else { /* unresolved weak kfunc call */
5972 				poison_kfunc_call(prog, i, relo->insn_idx, insn,
5973 						  relo->ext_idx, ext);
5974 			}
5975 			break;
5976 		case RELO_SUBPROG_ADDR:
5977 			if (insn[0].src_reg != BPF_PSEUDO_FUNC) {
5978 				pr_warn("prog '%s': relo #%d: bad insn\n",
5979 					prog->name, i);
5980 				return -EINVAL;
5981 			}
5982 			/* handled already */
5983 			break;
5984 		case RELO_CALL:
5985 			/* handled already */
5986 			break;
5987 		case RELO_CORE:
5988 			/* will be handled by bpf_program_record_relos() */
5989 			break;
5990 		default:
5991 			pr_warn("prog '%s': relo #%d: bad relo type %d\n",
5992 				prog->name, i, relo->type);
5993 			return -EINVAL;
5994 		}
5995 	}
5996 
5997 	return 0;
5998 }
5999 
6000 static int adjust_prog_btf_ext_info(const struct bpf_object *obj,
6001 				    const struct bpf_program *prog,
6002 				    const struct btf_ext_info *ext_info,
6003 				    void **prog_info, __u32 *prog_rec_cnt,
6004 				    __u32 *prog_rec_sz)
6005 {
6006 	void *copy_start = NULL, *copy_end = NULL;
6007 	void *rec, *rec_end, *new_prog_info;
6008 	const struct btf_ext_info_sec *sec;
6009 	size_t old_sz, new_sz;
6010 	int i, sec_num, sec_idx, off_adj;
6011 
6012 	sec_num = 0;
6013 	for_each_btf_ext_sec(ext_info, sec) {
6014 		sec_idx = ext_info->sec_idxs[sec_num];
6015 		sec_num++;
6016 		if (prog->sec_idx != sec_idx)
6017 			continue;
6018 
6019 		for_each_btf_ext_rec(ext_info, sec, i, rec) {
6020 			__u32 insn_off = *(__u32 *)rec / BPF_INSN_SZ;
6021 
6022 			if (insn_off < prog->sec_insn_off)
6023 				continue;
6024 			if (insn_off >= prog->sec_insn_off + prog->sec_insn_cnt)
6025 				break;
6026 
6027 			if (!copy_start)
6028 				copy_start = rec;
6029 			copy_end = rec + ext_info->rec_size;
6030 		}
6031 
6032 		if (!copy_start)
6033 			return -ENOENT;
6034 
6035 		/* append func/line info of a given (sub-)program to the main
6036 		 * program func/line info
6037 		 */
6038 		old_sz = (size_t)(*prog_rec_cnt) * ext_info->rec_size;
6039 		new_sz = old_sz + (copy_end - copy_start);
6040 		new_prog_info = realloc(*prog_info, new_sz);
6041 		if (!new_prog_info)
6042 			return -ENOMEM;
6043 		*prog_info = new_prog_info;
6044 		*prog_rec_cnt = new_sz / ext_info->rec_size;
6045 		memcpy(new_prog_info + old_sz, copy_start, copy_end - copy_start);
6046 
6047 		/* Kernel instruction offsets are in units of 8-byte
6048 		 * instructions, while .BTF.ext instruction offsets generated
6049 		 * by Clang are in units of bytes. So convert Clang offsets
6050 		 * into kernel offsets and adjust offset according to program
6051 		 * relocated position.
6052 		 */
6053 		off_adj = prog->sub_insn_off - prog->sec_insn_off;
6054 		rec = new_prog_info + old_sz;
6055 		rec_end = new_prog_info + new_sz;
6056 		for (; rec < rec_end; rec += ext_info->rec_size) {
6057 			__u32 *insn_off = rec;
6058 
6059 			*insn_off = *insn_off / BPF_INSN_SZ + off_adj;
6060 		}
6061 		*prog_rec_sz = ext_info->rec_size;
6062 		return 0;
6063 	}
6064 
6065 	return -ENOENT;
6066 }
6067 
6068 static int
6069 reloc_prog_func_and_line_info(const struct bpf_object *obj,
6070 			      struct bpf_program *main_prog,
6071 			      const struct bpf_program *prog)
6072 {
6073 	int err;
6074 
6075 	/* no .BTF.ext relocation if .BTF.ext is missing or kernel doesn't
6076 	 * supprot func/line info
6077 	 */
6078 	if (!obj->btf_ext || !kernel_supports(obj, FEAT_BTF_FUNC))
6079 		return 0;
6080 
6081 	/* only attempt func info relocation if main program's func_info
6082 	 * relocation was successful
6083 	 */
6084 	if (main_prog != prog && !main_prog->func_info)
6085 		goto line_info;
6086 
6087 	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->func_info,
6088 				       &main_prog->func_info,
6089 				       &main_prog->func_info_cnt,
6090 				       &main_prog->func_info_rec_size);
6091 	if (err) {
6092 		if (err != -ENOENT) {
6093 			pr_warn("prog '%s': error relocating .BTF.ext function info: %d\n",
6094 				prog->name, err);
6095 			return err;
6096 		}
6097 		if (main_prog->func_info) {
6098 			/*
6099 			 * Some info has already been found but has problem
6100 			 * in the last btf_ext reloc. Must have to error out.
6101 			 */
6102 			pr_warn("prog '%s': missing .BTF.ext function info.\n", prog->name);
6103 			return err;
6104 		}
6105 		/* Have problem loading the very first info. Ignore the rest. */
6106 		pr_warn("prog '%s': missing .BTF.ext function info for the main program, skipping all of .BTF.ext func info.\n",
6107 			prog->name);
6108 	}
6109 
6110 line_info:
6111 	/* don't relocate line info if main program's relocation failed */
6112 	if (main_prog != prog && !main_prog->line_info)
6113 		return 0;
6114 
6115 	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->line_info,
6116 				       &main_prog->line_info,
6117 				       &main_prog->line_info_cnt,
6118 				       &main_prog->line_info_rec_size);
6119 	if (err) {
6120 		if (err != -ENOENT) {
6121 			pr_warn("prog '%s': error relocating .BTF.ext line info: %d\n",
6122 				prog->name, err);
6123 			return err;
6124 		}
6125 		if (main_prog->line_info) {
6126 			/*
6127 			 * Some info has already been found but has problem
6128 			 * in the last btf_ext reloc. Must have to error out.
6129 			 */
6130 			pr_warn("prog '%s': missing .BTF.ext line info.\n", prog->name);
6131 			return err;
6132 		}
6133 		/* Have problem loading the very first info. Ignore the rest. */
6134 		pr_warn("prog '%s': missing .BTF.ext line info for the main program, skipping all of .BTF.ext line info.\n",
6135 			prog->name);
6136 	}
6137 	return 0;
6138 }
6139 
6140 static int cmp_relo_by_insn_idx(const void *key, const void *elem)
6141 {
6142 	size_t insn_idx = *(const size_t *)key;
6143 	const struct reloc_desc *relo = elem;
6144 
6145 	if (insn_idx == relo->insn_idx)
6146 		return 0;
6147 	return insn_idx < relo->insn_idx ? -1 : 1;
6148 }
6149 
6150 static struct reloc_desc *find_prog_insn_relo(const struct bpf_program *prog, size_t insn_idx)
6151 {
6152 	if (!prog->nr_reloc)
6153 		return NULL;
6154 	return bsearch(&insn_idx, prog->reloc_desc, prog->nr_reloc,
6155 		       sizeof(*prog->reloc_desc), cmp_relo_by_insn_idx);
6156 }
6157 
6158 static int append_subprog_relos(struct bpf_program *main_prog, struct bpf_program *subprog)
6159 {
6160 	int new_cnt = main_prog->nr_reloc + subprog->nr_reloc;
6161 	struct reloc_desc *relos;
6162 	int i;
6163 
6164 	if (main_prog == subprog)
6165 		return 0;
6166 	relos = libbpf_reallocarray(main_prog->reloc_desc, new_cnt, sizeof(*relos));
6167 	/* if new count is zero, reallocarray can return a valid NULL result;
6168 	 * in this case the previous pointer will be freed, so we *have to*
6169 	 * reassign old pointer to the new value (even if it's NULL)
6170 	 */
6171 	if (!relos && new_cnt)
6172 		return -ENOMEM;
6173 	if (subprog->nr_reloc)
6174 		memcpy(relos + main_prog->nr_reloc, subprog->reloc_desc,
6175 		       sizeof(*relos) * subprog->nr_reloc);
6176 
6177 	for (i = main_prog->nr_reloc; i < new_cnt; i++)
6178 		relos[i].insn_idx += subprog->sub_insn_off;
6179 	/* After insn_idx adjustment the 'relos' array is still sorted
6180 	 * by insn_idx and doesn't break bsearch.
6181 	 */
6182 	main_prog->reloc_desc = relos;
6183 	main_prog->nr_reloc = new_cnt;
6184 	return 0;
6185 }
6186 
6187 static int
6188 bpf_object__reloc_code(struct bpf_object *obj, struct bpf_program *main_prog,
6189 		       struct bpf_program *prog)
6190 {
6191 	size_t sub_insn_idx, insn_idx, new_cnt;
6192 	struct bpf_program *subprog;
6193 	struct bpf_insn *insns, *insn;
6194 	struct reloc_desc *relo;
6195 	int err;
6196 
6197 	err = reloc_prog_func_and_line_info(obj, main_prog, prog);
6198 	if (err)
6199 		return err;
6200 
6201 	for (insn_idx = 0; insn_idx < prog->sec_insn_cnt; insn_idx++) {
6202 		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6203 		if (!insn_is_subprog_call(insn) && !insn_is_pseudo_func(insn))
6204 			continue;
6205 
6206 		relo = find_prog_insn_relo(prog, insn_idx);
6207 		if (relo && relo->type == RELO_EXTERN_CALL)
6208 			/* kfunc relocations will be handled later
6209 			 * in bpf_object__relocate_data()
6210 			 */
6211 			continue;
6212 		if (relo && relo->type != RELO_CALL && relo->type != RELO_SUBPROG_ADDR) {
6213 			pr_warn("prog '%s': unexpected relo for insn #%zu, type %d\n",
6214 				prog->name, insn_idx, relo->type);
6215 			return -LIBBPF_ERRNO__RELOC;
6216 		}
6217 		if (relo) {
6218 			/* sub-program instruction index is a combination of
6219 			 * an offset of a symbol pointed to by relocation and
6220 			 * call instruction's imm field; for global functions,
6221 			 * call always has imm = -1, but for static functions
6222 			 * relocation is against STT_SECTION and insn->imm
6223 			 * points to a start of a static function
6224 			 *
6225 			 * for subprog addr relocation, the relo->sym_off + insn->imm is
6226 			 * the byte offset in the corresponding section.
6227 			 */
6228 			if (relo->type == RELO_CALL)
6229 				sub_insn_idx = relo->sym_off / BPF_INSN_SZ + insn->imm + 1;
6230 			else
6231 				sub_insn_idx = (relo->sym_off + insn->imm) / BPF_INSN_SZ;
6232 		} else if (insn_is_pseudo_func(insn)) {
6233 			/*
6234 			 * RELO_SUBPROG_ADDR relo is always emitted even if both
6235 			 * functions are in the same section, so it shouldn't reach here.
6236 			 */
6237 			pr_warn("prog '%s': missing subprog addr relo for insn #%zu\n",
6238 				prog->name, insn_idx);
6239 			return -LIBBPF_ERRNO__RELOC;
6240 		} else {
6241 			/* if subprogram call is to a static function within
6242 			 * the same ELF section, there won't be any relocation
6243 			 * emitted, but it also means there is no additional
6244 			 * offset necessary, insns->imm is relative to
6245 			 * instruction's original position within the section
6246 			 */
6247 			sub_insn_idx = prog->sec_insn_off + insn_idx + insn->imm + 1;
6248 		}
6249 
6250 		/* we enforce that sub-programs should be in .text section */
6251 		subprog = find_prog_by_sec_insn(obj, obj->efile.text_shndx, sub_insn_idx);
6252 		if (!subprog) {
6253 			pr_warn("prog '%s': no .text section found yet sub-program call exists\n",
6254 				prog->name);
6255 			return -LIBBPF_ERRNO__RELOC;
6256 		}
6257 
6258 		/* if it's the first call instruction calling into this
6259 		 * subprogram (meaning this subprog hasn't been processed
6260 		 * yet) within the context of current main program:
6261 		 *   - append it at the end of main program's instructions blog;
6262 		 *   - process is recursively, while current program is put on hold;
6263 		 *   - if that subprogram calls some other not yet processes
6264 		 *   subprogram, same thing will happen recursively until
6265 		 *   there are no more unprocesses subprograms left to append
6266 		 *   and relocate.
6267 		 */
6268 		if (subprog->sub_insn_off == 0) {
6269 			subprog->sub_insn_off = main_prog->insns_cnt;
6270 
6271 			new_cnt = main_prog->insns_cnt + subprog->insns_cnt;
6272 			insns = libbpf_reallocarray(main_prog->insns, new_cnt, sizeof(*insns));
6273 			if (!insns) {
6274 				pr_warn("prog '%s': failed to realloc prog code\n", main_prog->name);
6275 				return -ENOMEM;
6276 			}
6277 			main_prog->insns = insns;
6278 			main_prog->insns_cnt = new_cnt;
6279 
6280 			memcpy(main_prog->insns + subprog->sub_insn_off, subprog->insns,
6281 			       subprog->insns_cnt * sizeof(*insns));
6282 
6283 			pr_debug("prog '%s': added %zu insns from sub-prog '%s'\n",
6284 				 main_prog->name, subprog->insns_cnt, subprog->name);
6285 
6286 			/* The subprog insns are now appended. Append its relos too. */
6287 			err = append_subprog_relos(main_prog, subprog);
6288 			if (err)
6289 				return err;
6290 			err = bpf_object__reloc_code(obj, main_prog, subprog);
6291 			if (err)
6292 				return err;
6293 		}
6294 
6295 		/* main_prog->insns memory could have been re-allocated, so
6296 		 * calculate pointer again
6297 		 */
6298 		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6299 		/* calculate correct instruction position within current main
6300 		 * prog; each main prog can have a different set of
6301 		 * subprograms appended (potentially in different order as
6302 		 * well), so position of any subprog can be different for
6303 		 * different main programs
6304 		 */
6305 		insn->imm = subprog->sub_insn_off - (prog->sub_insn_off + insn_idx) - 1;
6306 
6307 		pr_debug("prog '%s': insn #%zu relocated, imm %d points to subprog '%s' (now at %zu offset)\n",
6308 			 prog->name, insn_idx, insn->imm, subprog->name, subprog->sub_insn_off);
6309 	}
6310 
6311 	return 0;
6312 }
6313 
6314 /*
6315  * Relocate sub-program calls.
6316  *
6317  * Algorithm operates as follows. Each entry-point BPF program (referred to as
6318  * main prog) is processed separately. For each subprog (non-entry functions,
6319  * that can be called from either entry progs or other subprogs) gets their
6320  * sub_insn_off reset to zero. This serves as indicator that this subprogram
6321  * hasn't been yet appended and relocated within current main prog. Once its
6322  * relocated, sub_insn_off will point at the position within current main prog
6323  * where given subprog was appended. This will further be used to relocate all
6324  * the call instructions jumping into this subprog.
6325  *
6326  * We start with main program and process all call instructions. If the call
6327  * is into a subprog that hasn't been processed (i.e., subprog->sub_insn_off
6328  * is zero), subprog instructions are appended at the end of main program's
6329  * instruction array. Then main program is "put on hold" while we recursively
6330  * process newly appended subprogram. If that subprogram calls into another
6331  * subprogram that hasn't been appended, new subprogram is appended again to
6332  * the *main* prog's instructions (subprog's instructions are always left
6333  * untouched, as they need to be in unmodified state for subsequent main progs
6334  * and subprog instructions are always sent only as part of a main prog) and
6335  * the process continues recursively. Once all the subprogs called from a main
6336  * prog or any of its subprogs are appended (and relocated), all their
6337  * positions within finalized instructions array are known, so it's easy to
6338  * rewrite call instructions with correct relative offsets, corresponding to
6339  * desired target subprog.
6340  *
6341  * Its important to realize that some subprogs might not be called from some
6342  * main prog and any of its called/used subprogs. Those will keep their
6343  * subprog->sub_insn_off as zero at all times and won't be appended to current
6344  * main prog and won't be relocated within the context of current main prog.
6345  * They might still be used from other main progs later.
6346  *
6347  * Visually this process can be shown as below. Suppose we have two main
6348  * programs mainA and mainB and BPF object contains three subprogs: subA,
6349  * subB, and subC. mainA calls only subA, mainB calls only subC, but subA and
6350  * subC both call subB:
6351  *
6352  *        +--------+ +-------+
6353  *        |        v v       |
6354  *     +--+---+ +--+-+-+ +---+--+
6355  *     | subA | | subB | | subC |
6356  *     +--+---+ +------+ +---+--+
6357  *        ^                  ^
6358  *        |                  |
6359  *    +---+-------+   +------+----+
6360  *    |   mainA   |   |   mainB   |
6361  *    +-----------+   +-----------+
6362  *
6363  * We'll start relocating mainA, will find subA, append it and start
6364  * processing sub A recursively:
6365  *
6366  *    +-----------+------+
6367  *    |   mainA   | subA |
6368  *    +-----------+------+
6369  *
6370  * At this point we notice that subB is used from subA, so we append it and
6371  * relocate (there are no further subcalls from subB):
6372  *
6373  *    +-----------+------+------+
6374  *    |   mainA   | subA | subB |
6375  *    +-----------+------+------+
6376  *
6377  * At this point, we relocate subA calls, then go one level up and finish with
6378  * relocatin mainA calls. mainA is done.
6379  *
6380  * For mainB process is similar but results in different order. We start with
6381  * mainB and skip subA and subB, as mainB never calls them (at least
6382  * directly), but we see subC is needed, so we append and start processing it:
6383  *
6384  *    +-----------+------+
6385  *    |   mainB   | subC |
6386  *    +-----------+------+
6387  * Now we see subC needs subB, so we go back to it, append and relocate it:
6388  *
6389  *    +-----------+------+------+
6390  *    |   mainB   | subC | subB |
6391  *    +-----------+------+------+
6392  *
6393  * At this point we unwind recursion, relocate calls in subC, then in mainB.
6394  */
6395 static int
6396 bpf_object__relocate_calls(struct bpf_object *obj, struct bpf_program *prog)
6397 {
6398 	struct bpf_program *subprog;
6399 	int i, err;
6400 
6401 	/* mark all subprogs as not relocated (yet) within the context of
6402 	 * current main program
6403 	 */
6404 	for (i = 0; i < obj->nr_programs; i++) {
6405 		subprog = &obj->programs[i];
6406 		if (!prog_is_subprog(obj, subprog))
6407 			continue;
6408 
6409 		subprog->sub_insn_off = 0;
6410 	}
6411 
6412 	err = bpf_object__reloc_code(obj, prog, prog);
6413 	if (err)
6414 		return err;
6415 
6416 	return 0;
6417 }
6418 
6419 static void
6420 bpf_object__free_relocs(struct bpf_object *obj)
6421 {
6422 	struct bpf_program *prog;
6423 	int i;
6424 
6425 	/* free up relocation descriptors */
6426 	for (i = 0; i < obj->nr_programs; i++) {
6427 		prog = &obj->programs[i];
6428 		zfree(&prog->reloc_desc);
6429 		prog->nr_reloc = 0;
6430 	}
6431 }
6432 
6433 static int cmp_relocs(const void *_a, const void *_b)
6434 {
6435 	const struct reloc_desc *a = _a;
6436 	const struct reloc_desc *b = _b;
6437 
6438 	if (a->insn_idx != b->insn_idx)
6439 		return a->insn_idx < b->insn_idx ? -1 : 1;
6440 
6441 	/* no two relocations should have the same insn_idx, but ... */
6442 	if (a->type != b->type)
6443 		return a->type < b->type ? -1 : 1;
6444 
6445 	return 0;
6446 }
6447 
6448 static void bpf_object__sort_relos(struct bpf_object *obj)
6449 {
6450 	int i;
6451 
6452 	for (i = 0; i < obj->nr_programs; i++) {
6453 		struct bpf_program *p = &obj->programs[i];
6454 
6455 		if (!p->nr_reloc)
6456 			continue;
6457 
6458 		qsort(p->reloc_desc, p->nr_reloc, sizeof(*p->reloc_desc), cmp_relocs);
6459 	}
6460 }
6461 
6462 static int
6463 bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
6464 {
6465 	struct bpf_program *prog;
6466 	size_t i, j;
6467 	int err;
6468 
6469 	if (obj->btf_ext) {
6470 		err = bpf_object__relocate_core(obj, targ_btf_path);
6471 		if (err) {
6472 			pr_warn("failed to perform CO-RE relocations: %d\n",
6473 				err);
6474 			return err;
6475 		}
6476 		bpf_object__sort_relos(obj);
6477 	}
6478 
6479 	/* Before relocating calls pre-process relocations and mark
6480 	 * few ld_imm64 instructions that points to subprogs.
6481 	 * Otherwise bpf_object__reloc_code() later would have to consider
6482 	 * all ld_imm64 insns as relocation candidates. That would
6483 	 * reduce relocation speed, since amount of find_prog_insn_relo()
6484 	 * would increase and most of them will fail to find a relo.
6485 	 */
6486 	for (i = 0; i < obj->nr_programs; i++) {
6487 		prog = &obj->programs[i];
6488 		for (j = 0; j < prog->nr_reloc; j++) {
6489 			struct reloc_desc *relo = &prog->reloc_desc[j];
6490 			struct bpf_insn *insn = &prog->insns[relo->insn_idx];
6491 
6492 			/* mark the insn, so it's recognized by insn_is_pseudo_func() */
6493 			if (relo->type == RELO_SUBPROG_ADDR)
6494 				insn[0].src_reg = BPF_PSEUDO_FUNC;
6495 		}
6496 	}
6497 
6498 	/* relocate subprogram calls and append used subprograms to main
6499 	 * programs; each copy of subprogram code needs to be relocated
6500 	 * differently for each main program, because its code location might
6501 	 * have changed.
6502 	 * Append subprog relos to main programs to allow data relos to be
6503 	 * processed after text is completely relocated.
6504 	 */
6505 	for (i = 0; i < obj->nr_programs; i++) {
6506 		prog = &obj->programs[i];
6507 		/* sub-program's sub-calls are relocated within the context of
6508 		 * its main program only
6509 		 */
6510 		if (prog_is_subprog(obj, prog))
6511 			continue;
6512 		if (!prog->autoload)
6513 			continue;
6514 
6515 		err = bpf_object__relocate_calls(obj, prog);
6516 		if (err) {
6517 			pr_warn("prog '%s': failed to relocate calls: %d\n",
6518 				prog->name, err);
6519 			return err;
6520 		}
6521 	}
6522 	/* Process data relos for main programs */
6523 	for (i = 0; i < obj->nr_programs; i++) {
6524 		prog = &obj->programs[i];
6525 		if (prog_is_subprog(obj, prog))
6526 			continue;
6527 		if (!prog->autoload)
6528 			continue;
6529 		err = bpf_object__relocate_data(obj, prog);
6530 		if (err) {
6531 			pr_warn("prog '%s': failed to relocate data references: %d\n",
6532 				prog->name, err);
6533 			return err;
6534 		}
6535 	}
6536 
6537 	return 0;
6538 }
6539 
6540 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
6541 					    Elf64_Shdr *shdr, Elf_Data *data);
6542 
6543 static int bpf_object__collect_map_relos(struct bpf_object *obj,
6544 					 Elf64_Shdr *shdr, Elf_Data *data)
6545 {
6546 	const int bpf_ptr_sz = 8, host_ptr_sz = sizeof(void *);
6547 	int i, j, nrels, new_sz;
6548 	const struct btf_var_secinfo *vi = NULL;
6549 	const struct btf_type *sec, *var, *def;
6550 	struct bpf_map *map = NULL, *targ_map = NULL;
6551 	struct bpf_program *targ_prog = NULL;
6552 	bool is_prog_array, is_map_in_map;
6553 	const struct btf_member *member;
6554 	const char *name, *mname, *type;
6555 	unsigned int moff;
6556 	Elf64_Sym *sym;
6557 	Elf64_Rel *rel;
6558 	void *tmp;
6559 
6560 	if (!obj->efile.btf_maps_sec_btf_id || !obj->btf)
6561 		return -EINVAL;
6562 	sec = btf__type_by_id(obj->btf, obj->efile.btf_maps_sec_btf_id);
6563 	if (!sec)
6564 		return -EINVAL;
6565 
6566 	nrels = shdr->sh_size / shdr->sh_entsize;
6567 	for (i = 0; i < nrels; i++) {
6568 		rel = elf_rel_by_idx(data, i);
6569 		if (!rel) {
6570 			pr_warn(".maps relo #%d: failed to get ELF relo\n", i);
6571 			return -LIBBPF_ERRNO__FORMAT;
6572 		}
6573 
6574 		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
6575 		if (!sym) {
6576 			pr_warn(".maps relo #%d: symbol %zx not found\n",
6577 				i, (size_t)ELF64_R_SYM(rel->r_info));
6578 			return -LIBBPF_ERRNO__FORMAT;
6579 		}
6580 		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
6581 
6582 		pr_debug(".maps relo #%d: for %zd value %zd rel->r_offset %zu name %d ('%s')\n",
6583 			 i, (ssize_t)(rel->r_info >> 32), (size_t)sym->st_value,
6584 			 (size_t)rel->r_offset, sym->st_name, name);
6585 
6586 		for (j = 0; j < obj->nr_maps; j++) {
6587 			map = &obj->maps[j];
6588 			if (map->sec_idx != obj->efile.btf_maps_shndx)
6589 				continue;
6590 
6591 			vi = btf_var_secinfos(sec) + map->btf_var_idx;
6592 			if (vi->offset <= rel->r_offset &&
6593 			    rel->r_offset + bpf_ptr_sz <= vi->offset + vi->size)
6594 				break;
6595 		}
6596 		if (j == obj->nr_maps) {
6597 			pr_warn(".maps relo #%d: cannot find map '%s' at rel->r_offset %zu\n",
6598 				i, name, (size_t)rel->r_offset);
6599 			return -EINVAL;
6600 		}
6601 
6602 		is_map_in_map = bpf_map_type__is_map_in_map(map->def.type);
6603 		is_prog_array = map->def.type == BPF_MAP_TYPE_PROG_ARRAY;
6604 		type = is_map_in_map ? "map" : "prog";
6605 		if (is_map_in_map) {
6606 			if (sym->st_shndx != obj->efile.btf_maps_shndx) {
6607 				pr_warn(".maps relo #%d: '%s' isn't a BTF-defined map\n",
6608 					i, name);
6609 				return -LIBBPF_ERRNO__RELOC;
6610 			}
6611 			if (map->def.type == BPF_MAP_TYPE_HASH_OF_MAPS &&
6612 			    map->def.key_size != sizeof(int)) {
6613 				pr_warn(".maps relo #%d: hash-of-maps '%s' should have key size %zu.\n",
6614 					i, map->name, sizeof(int));
6615 				return -EINVAL;
6616 			}
6617 			targ_map = bpf_object__find_map_by_name(obj, name);
6618 			if (!targ_map) {
6619 				pr_warn(".maps relo #%d: '%s' isn't a valid map reference\n",
6620 					i, name);
6621 				return -ESRCH;
6622 			}
6623 		} else if (is_prog_array) {
6624 			targ_prog = bpf_object__find_program_by_name(obj, name);
6625 			if (!targ_prog) {
6626 				pr_warn(".maps relo #%d: '%s' isn't a valid program reference\n",
6627 					i, name);
6628 				return -ESRCH;
6629 			}
6630 			if (targ_prog->sec_idx != sym->st_shndx ||
6631 			    targ_prog->sec_insn_off * 8 != sym->st_value ||
6632 			    prog_is_subprog(obj, targ_prog)) {
6633 				pr_warn(".maps relo #%d: '%s' isn't an entry-point program\n",
6634 					i, name);
6635 				return -LIBBPF_ERRNO__RELOC;
6636 			}
6637 		} else {
6638 			return -EINVAL;
6639 		}
6640 
6641 		var = btf__type_by_id(obj->btf, vi->type);
6642 		def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
6643 		if (btf_vlen(def) == 0)
6644 			return -EINVAL;
6645 		member = btf_members(def) + btf_vlen(def) - 1;
6646 		mname = btf__name_by_offset(obj->btf, member->name_off);
6647 		if (strcmp(mname, "values"))
6648 			return -EINVAL;
6649 
6650 		moff = btf_member_bit_offset(def, btf_vlen(def) - 1) / 8;
6651 		if (rel->r_offset - vi->offset < moff)
6652 			return -EINVAL;
6653 
6654 		moff = rel->r_offset - vi->offset - moff;
6655 		/* here we use BPF pointer size, which is always 64 bit, as we
6656 		 * are parsing ELF that was built for BPF target
6657 		 */
6658 		if (moff % bpf_ptr_sz)
6659 			return -EINVAL;
6660 		moff /= bpf_ptr_sz;
6661 		if (moff >= map->init_slots_sz) {
6662 			new_sz = moff + 1;
6663 			tmp = libbpf_reallocarray(map->init_slots, new_sz, host_ptr_sz);
6664 			if (!tmp)
6665 				return -ENOMEM;
6666 			map->init_slots = tmp;
6667 			memset(map->init_slots + map->init_slots_sz, 0,
6668 			       (new_sz - map->init_slots_sz) * host_ptr_sz);
6669 			map->init_slots_sz = new_sz;
6670 		}
6671 		map->init_slots[moff] = is_map_in_map ? (void *)targ_map : (void *)targ_prog;
6672 
6673 		pr_debug(".maps relo #%d: map '%s' slot [%d] points to %s '%s'\n",
6674 			 i, map->name, moff, type, name);
6675 	}
6676 
6677 	return 0;
6678 }
6679 
6680 static int bpf_object__collect_relos(struct bpf_object *obj)
6681 {
6682 	int i, err;
6683 
6684 	for (i = 0; i < obj->efile.sec_cnt; i++) {
6685 		struct elf_sec_desc *sec_desc = &obj->efile.secs[i];
6686 		Elf64_Shdr *shdr;
6687 		Elf_Data *data;
6688 		int idx;
6689 
6690 		if (sec_desc->sec_type != SEC_RELO)
6691 			continue;
6692 
6693 		shdr = sec_desc->shdr;
6694 		data = sec_desc->data;
6695 		idx = shdr->sh_info;
6696 
6697 		if (shdr->sh_type != SHT_REL) {
6698 			pr_warn("internal error at %d\n", __LINE__);
6699 			return -LIBBPF_ERRNO__INTERNAL;
6700 		}
6701 
6702 		if (idx == obj->efile.st_ops_shndx || idx == obj->efile.st_ops_link_shndx)
6703 			err = bpf_object__collect_st_ops_relos(obj, shdr, data);
6704 		else if (idx == obj->efile.btf_maps_shndx)
6705 			err = bpf_object__collect_map_relos(obj, shdr, data);
6706 		else
6707 			err = bpf_object__collect_prog_relos(obj, shdr, data);
6708 		if (err)
6709 			return err;
6710 	}
6711 
6712 	bpf_object__sort_relos(obj);
6713 	return 0;
6714 }
6715 
6716 static bool insn_is_helper_call(struct bpf_insn *insn, enum bpf_func_id *func_id)
6717 {
6718 	if (BPF_CLASS(insn->code) == BPF_JMP &&
6719 	    BPF_OP(insn->code) == BPF_CALL &&
6720 	    BPF_SRC(insn->code) == BPF_K &&
6721 	    insn->src_reg == 0 &&
6722 	    insn->dst_reg == 0) {
6723 		    *func_id = insn->imm;
6724 		    return true;
6725 	}
6726 	return false;
6727 }
6728 
6729 static int bpf_object__sanitize_prog(struct bpf_object *obj, struct bpf_program *prog)
6730 {
6731 	struct bpf_insn *insn = prog->insns;
6732 	enum bpf_func_id func_id;
6733 	int i;
6734 
6735 	if (obj->gen_loader)
6736 		return 0;
6737 
6738 	for (i = 0; i < prog->insns_cnt; i++, insn++) {
6739 		if (!insn_is_helper_call(insn, &func_id))
6740 			continue;
6741 
6742 		/* on kernels that don't yet support
6743 		 * bpf_probe_read_{kernel,user}[_str] helpers, fall back
6744 		 * to bpf_probe_read() which works well for old kernels
6745 		 */
6746 		switch (func_id) {
6747 		case BPF_FUNC_probe_read_kernel:
6748 		case BPF_FUNC_probe_read_user:
6749 			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
6750 				insn->imm = BPF_FUNC_probe_read;
6751 			break;
6752 		case BPF_FUNC_probe_read_kernel_str:
6753 		case BPF_FUNC_probe_read_user_str:
6754 			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
6755 				insn->imm = BPF_FUNC_probe_read_str;
6756 			break;
6757 		default:
6758 			break;
6759 		}
6760 	}
6761 	return 0;
6762 }
6763 
6764 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
6765 				     int *btf_obj_fd, int *btf_type_id);
6766 
6767 /* this is called as prog->sec_def->prog_prepare_load_fn for libbpf-supported sec_defs */
6768 static int libbpf_prepare_prog_load(struct bpf_program *prog,
6769 				    struct bpf_prog_load_opts *opts, long cookie)
6770 {
6771 	enum sec_def_flags def = cookie;
6772 
6773 	/* old kernels might not support specifying expected_attach_type */
6774 	if ((def & SEC_EXP_ATTACH_OPT) && !kernel_supports(prog->obj, FEAT_EXP_ATTACH_TYPE))
6775 		opts->expected_attach_type = 0;
6776 
6777 	if (def & SEC_SLEEPABLE)
6778 		opts->prog_flags |= BPF_F_SLEEPABLE;
6779 
6780 	if (prog->type == BPF_PROG_TYPE_XDP && (def & SEC_XDP_FRAGS))
6781 		opts->prog_flags |= BPF_F_XDP_HAS_FRAGS;
6782 
6783 	if ((def & SEC_ATTACH_BTF) && !prog->attach_btf_id) {
6784 		int btf_obj_fd = 0, btf_type_id = 0, err;
6785 		const char *attach_name;
6786 
6787 		attach_name = strchr(prog->sec_name, '/');
6788 		if (!attach_name) {
6789 			/* if BPF program is annotated with just SEC("fentry")
6790 			 * (or similar) without declaratively specifying
6791 			 * target, then it is expected that target will be
6792 			 * specified with bpf_program__set_attach_target() at
6793 			 * runtime before BPF object load step. If not, then
6794 			 * there is nothing to load into the kernel as BPF
6795 			 * verifier won't be able to validate BPF program
6796 			 * correctness anyways.
6797 			 */
6798 			pr_warn("prog '%s': no BTF-based attach target is specified, use bpf_program__set_attach_target()\n",
6799 				prog->name);
6800 			return -EINVAL;
6801 		}
6802 		attach_name++; /* skip over / */
6803 
6804 		err = libbpf_find_attach_btf_id(prog, attach_name, &btf_obj_fd, &btf_type_id);
6805 		if (err)
6806 			return err;
6807 
6808 		/* cache resolved BTF FD and BTF type ID in the prog */
6809 		prog->attach_btf_obj_fd = btf_obj_fd;
6810 		prog->attach_btf_id = btf_type_id;
6811 
6812 		/* but by now libbpf common logic is not utilizing
6813 		 * prog->atach_btf_obj_fd/prog->attach_btf_id anymore because
6814 		 * this callback is called after opts were populated by
6815 		 * libbpf, so this callback has to update opts explicitly here
6816 		 */
6817 		opts->attach_btf_obj_fd = btf_obj_fd;
6818 		opts->attach_btf_id = btf_type_id;
6819 	}
6820 	return 0;
6821 }
6822 
6823 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz);
6824 
6825 static int bpf_object_load_prog(struct bpf_object *obj, struct bpf_program *prog,
6826 				struct bpf_insn *insns, int insns_cnt,
6827 				const char *license, __u32 kern_version, int *prog_fd)
6828 {
6829 	LIBBPF_OPTS(bpf_prog_load_opts, load_attr);
6830 	const char *prog_name = NULL;
6831 	char *cp, errmsg[STRERR_BUFSIZE];
6832 	size_t log_buf_size = 0;
6833 	char *log_buf = NULL, *tmp;
6834 	int btf_fd, ret, err;
6835 	bool own_log_buf = true;
6836 	__u32 log_level = prog->log_level;
6837 
6838 	if (prog->type == BPF_PROG_TYPE_UNSPEC) {
6839 		/*
6840 		 * The program type must be set.  Most likely we couldn't find a proper
6841 		 * section definition at load time, and thus we didn't infer the type.
6842 		 */
6843 		pr_warn("prog '%s': missing BPF prog type, check ELF section name '%s'\n",
6844 			prog->name, prog->sec_name);
6845 		return -EINVAL;
6846 	}
6847 
6848 	if (!insns || !insns_cnt)
6849 		return -EINVAL;
6850 
6851 	load_attr.expected_attach_type = prog->expected_attach_type;
6852 	if (kernel_supports(obj, FEAT_PROG_NAME))
6853 		prog_name = prog->name;
6854 	load_attr.attach_prog_fd = prog->attach_prog_fd;
6855 	load_attr.attach_btf_obj_fd = prog->attach_btf_obj_fd;
6856 	load_attr.attach_btf_id = prog->attach_btf_id;
6857 	load_attr.kern_version = kern_version;
6858 	load_attr.prog_ifindex = prog->prog_ifindex;
6859 
6860 	/* specify func_info/line_info only if kernel supports them */
6861 	btf_fd = bpf_object__btf_fd(obj);
6862 	if (btf_fd >= 0 && kernel_supports(obj, FEAT_BTF_FUNC)) {
6863 		load_attr.prog_btf_fd = btf_fd;
6864 		load_attr.func_info = prog->func_info;
6865 		load_attr.func_info_rec_size = prog->func_info_rec_size;
6866 		load_attr.func_info_cnt = prog->func_info_cnt;
6867 		load_attr.line_info = prog->line_info;
6868 		load_attr.line_info_rec_size = prog->line_info_rec_size;
6869 		load_attr.line_info_cnt = prog->line_info_cnt;
6870 	}
6871 	load_attr.log_level = log_level;
6872 	load_attr.prog_flags = prog->prog_flags;
6873 	load_attr.fd_array = obj->fd_array;
6874 
6875 	/* adjust load_attr if sec_def provides custom preload callback */
6876 	if (prog->sec_def && prog->sec_def->prog_prepare_load_fn) {
6877 		err = prog->sec_def->prog_prepare_load_fn(prog, &load_attr, prog->sec_def->cookie);
6878 		if (err < 0) {
6879 			pr_warn("prog '%s': failed to prepare load attributes: %d\n",
6880 				prog->name, err);
6881 			return err;
6882 		}
6883 		insns = prog->insns;
6884 		insns_cnt = prog->insns_cnt;
6885 	}
6886 
6887 	if (obj->gen_loader) {
6888 		bpf_gen__prog_load(obj->gen_loader, prog->type, prog->name,
6889 				   license, insns, insns_cnt, &load_attr,
6890 				   prog - obj->programs);
6891 		*prog_fd = -1;
6892 		return 0;
6893 	}
6894 
6895 retry_load:
6896 	/* if log_level is zero, we don't request logs initially even if
6897 	 * custom log_buf is specified; if the program load fails, then we'll
6898 	 * bump log_level to 1 and use either custom log_buf or we'll allocate
6899 	 * our own and retry the load to get details on what failed
6900 	 */
6901 	if (log_level) {
6902 		if (prog->log_buf) {
6903 			log_buf = prog->log_buf;
6904 			log_buf_size = prog->log_size;
6905 			own_log_buf = false;
6906 		} else if (obj->log_buf) {
6907 			log_buf = obj->log_buf;
6908 			log_buf_size = obj->log_size;
6909 			own_log_buf = false;
6910 		} else {
6911 			log_buf_size = max((size_t)BPF_LOG_BUF_SIZE, log_buf_size * 2);
6912 			tmp = realloc(log_buf, log_buf_size);
6913 			if (!tmp) {
6914 				ret = -ENOMEM;
6915 				goto out;
6916 			}
6917 			log_buf = tmp;
6918 			log_buf[0] = '\0';
6919 			own_log_buf = true;
6920 		}
6921 	}
6922 
6923 	load_attr.log_buf = log_buf;
6924 	load_attr.log_size = log_buf_size;
6925 	load_attr.log_level = log_level;
6926 
6927 	ret = bpf_prog_load(prog->type, prog_name, license, insns, insns_cnt, &load_attr);
6928 	if (ret >= 0) {
6929 		if (log_level && own_log_buf) {
6930 			pr_debug("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
6931 				 prog->name, log_buf);
6932 		}
6933 
6934 		if (obj->has_rodata && kernel_supports(obj, FEAT_PROG_BIND_MAP)) {
6935 			struct bpf_map *map;
6936 			int i;
6937 
6938 			for (i = 0; i < obj->nr_maps; i++) {
6939 				map = &prog->obj->maps[i];
6940 				if (map->libbpf_type != LIBBPF_MAP_RODATA)
6941 					continue;
6942 
6943 				if (bpf_prog_bind_map(ret, bpf_map__fd(map), NULL)) {
6944 					cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
6945 					pr_warn("prog '%s': failed to bind map '%s': %s\n",
6946 						prog->name, map->real_name, cp);
6947 					/* Don't fail hard if can't bind rodata. */
6948 				}
6949 			}
6950 		}
6951 
6952 		*prog_fd = ret;
6953 		ret = 0;
6954 		goto out;
6955 	}
6956 
6957 	if (log_level == 0) {
6958 		log_level = 1;
6959 		goto retry_load;
6960 	}
6961 	/* On ENOSPC, increase log buffer size and retry, unless custom
6962 	 * log_buf is specified.
6963 	 * Be careful to not overflow u32, though. Kernel's log buf size limit
6964 	 * isn't part of UAPI so it can always be bumped to full 4GB. So don't
6965 	 * multiply by 2 unless we are sure we'll fit within 32 bits.
6966 	 * Currently, we'll get -EINVAL when we reach (UINT_MAX >> 2).
6967 	 */
6968 	if (own_log_buf && errno == ENOSPC && log_buf_size <= UINT_MAX / 2)
6969 		goto retry_load;
6970 
6971 	ret = -errno;
6972 
6973 	/* post-process verifier log to improve error descriptions */
6974 	fixup_verifier_log(prog, log_buf, log_buf_size);
6975 
6976 	cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
6977 	pr_warn("prog '%s': BPF program load failed: %s\n", prog->name, cp);
6978 	pr_perm_msg(ret);
6979 
6980 	if (own_log_buf && log_buf && log_buf[0] != '\0') {
6981 		pr_warn("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
6982 			prog->name, log_buf);
6983 	}
6984 
6985 out:
6986 	if (own_log_buf)
6987 		free(log_buf);
6988 	return ret;
6989 }
6990 
6991 static char *find_prev_line(char *buf, char *cur)
6992 {
6993 	char *p;
6994 
6995 	if (cur == buf) /* end of a log buf */
6996 		return NULL;
6997 
6998 	p = cur - 1;
6999 	while (p - 1 >= buf && *(p - 1) != '\n')
7000 		p--;
7001 
7002 	return p;
7003 }
7004 
7005 static void patch_log(char *buf, size_t buf_sz, size_t log_sz,
7006 		      char *orig, size_t orig_sz, const char *patch)
7007 {
7008 	/* size of the remaining log content to the right from the to-be-replaced part */
7009 	size_t rem_sz = (buf + log_sz) - (orig + orig_sz);
7010 	size_t patch_sz = strlen(patch);
7011 
7012 	if (patch_sz != orig_sz) {
7013 		/* If patch line(s) are longer than original piece of verifier log,
7014 		 * shift log contents by (patch_sz - orig_sz) bytes to the right
7015 		 * starting from after to-be-replaced part of the log.
7016 		 *
7017 		 * If patch line(s) are shorter than original piece of verifier log,
7018 		 * shift log contents by (orig_sz - patch_sz) bytes to the left
7019 		 * starting from after to-be-replaced part of the log
7020 		 *
7021 		 * We need to be careful about not overflowing available
7022 		 * buf_sz capacity. If that's the case, we'll truncate the end
7023 		 * of the original log, as necessary.
7024 		 */
7025 		if (patch_sz > orig_sz) {
7026 			if (orig + patch_sz >= buf + buf_sz) {
7027 				/* patch is big enough to cover remaining space completely */
7028 				patch_sz -= (orig + patch_sz) - (buf + buf_sz) + 1;
7029 				rem_sz = 0;
7030 			} else if (patch_sz - orig_sz > buf_sz - log_sz) {
7031 				/* patch causes part of remaining log to be truncated */
7032 				rem_sz -= (patch_sz - orig_sz) - (buf_sz - log_sz);
7033 			}
7034 		}
7035 		/* shift remaining log to the right by calculated amount */
7036 		memmove(orig + patch_sz, orig + orig_sz, rem_sz);
7037 	}
7038 
7039 	memcpy(orig, patch, patch_sz);
7040 }
7041 
7042 static void fixup_log_failed_core_relo(struct bpf_program *prog,
7043 				       char *buf, size_t buf_sz, size_t log_sz,
7044 				       char *line1, char *line2, char *line3)
7045 {
7046 	/* Expected log for failed and not properly guarded CO-RE relocation:
7047 	 * line1 -> 123: (85) call unknown#195896080
7048 	 * line2 -> invalid func unknown#195896080
7049 	 * line3 -> <anything else or end of buffer>
7050 	 *
7051 	 * "123" is the index of the instruction that was poisoned. We extract
7052 	 * instruction index to find corresponding CO-RE relocation and
7053 	 * replace this part of the log with more relevant information about
7054 	 * failed CO-RE relocation.
7055 	 */
7056 	const struct bpf_core_relo *relo;
7057 	struct bpf_core_spec spec;
7058 	char patch[512], spec_buf[256];
7059 	int insn_idx, err, spec_len;
7060 
7061 	if (sscanf(line1, "%d: (%*d) call unknown#195896080\n", &insn_idx) != 1)
7062 		return;
7063 
7064 	relo = find_relo_core(prog, insn_idx);
7065 	if (!relo)
7066 		return;
7067 
7068 	err = bpf_core_parse_spec(prog->name, prog->obj->btf, relo, &spec);
7069 	if (err)
7070 		return;
7071 
7072 	spec_len = bpf_core_format_spec(spec_buf, sizeof(spec_buf), &spec);
7073 	snprintf(patch, sizeof(patch),
7074 		 "%d: <invalid CO-RE relocation>\n"
7075 		 "failed to resolve CO-RE relocation %s%s\n",
7076 		 insn_idx, spec_buf, spec_len >= sizeof(spec_buf) ? "..." : "");
7077 
7078 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7079 }
7080 
7081 static void fixup_log_missing_map_load(struct bpf_program *prog,
7082 				       char *buf, size_t buf_sz, size_t log_sz,
7083 				       char *line1, char *line2, char *line3)
7084 {
7085 	/* Expected log for failed and not properly guarded map reference:
7086 	 * line1 -> 123: (85) call unknown#2001000345
7087 	 * line2 -> invalid func unknown#2001000345
7088 	 * line3 -> <anything else or end of buffer>
7089 	 *
7090 	 * "123" is the index of the instruction that was poisoned.
7091 	 * "345" in "2001000345" is a map index in obj->maps to fetch map name.
7092 	 */
7093 	struct bpf_object *obj = prog->obj;
7094 	const struct bpf_map *map;
7095 	int insn_idx, map_idx;
7096 	char patch[128];
7097 
7098 	if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &map_idx) != 2)
7099 		return;
7100 
7101 	map_idx -= POISON_LDIMM64_MAP_BASE;
7102 	if (map_idx < 0 || map_idx >= obj->nr_maps)
7103 		return;
7104 	map = &obj->maps[map_idx];
7105 
7106 	snprintf(patch, sizeof(patch),
7107 		 "%d: <invalid BPF map reference>\n"
7108 		 "BPF map '%s' is referenced but wasn't created\n",
7109 		 insn_idx, map->name);
7110 
7111 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7112 }
7113 
7114 static void fixup_log_missing_kfunc_call(struct bpf_program *prog,
7115 					 char *buf, size_t buf_sz, size_t log_sz,
7116 					 char *line1, char *line2, char *line3)
7117 {
7118 	/* Expected log for failed and not properly guarded kfunc call:
7119 	 * line1 -> 123: (85) call unknown#2002000345
7120 	 * line2 -> invalid func unknown#2002000345
7121 	 * line3 -> <anything else or end of buffer>
7122 	 *
7123 	 * "123" is the index of the instruction that was poisoned.
7124 	 * "345" in "2002000345" is an extern index in obj->externs to fetch kfunc name.
7125 	 */
7126 	struct bpf_object *obj = prog->obj;
7127 	const struct extern_desc *ext;
7128 	int insn_idx, ext_idx;
7129 	char patch[128];
7130 
7131 	if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &ext_idx) != 2)
7132 		return;
7133 
7134 	ext_idx -= POISON_CALL_KFUNC_BASE;
7135 	if (ext_idx < 0 || ext_idx >= obj->nr_extern)
7136 		return;
7137 	ext = &obj->externs[ext_idx];
7138 
7139 	snprintf(patch, sizeof(patch),
7140 		 "%d: <invalid kfunc call>\n"
7141 		 "kfunc '%s' is referenced but wasn't resolved\n",
7142 		 insn_idx, ext->name);
7143 
7144 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7145 }
7146 
7147 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz)
7148 {
7149 	/* look for familiar error patterns in last N lines of the log */
7150 	const size_t max_last_line_cnt = 10;
7151 	char *prev_line, *cur_line, *next_line;
7152 	size_t log_sz;
7153 	int i;
7154 
7155 	if (!buf)
7156 		return;
7157 
7158 	log_sz = strlen(buf) + 1;
7159 	next_line = buf + log_sz - 1;
7160 
7161 	for (i = 0; i < max_last_line_cnt; i++, next_line = cur_line) {
7162 		cur_line = find_prev_line(buf, next_line);
7163 		if (!cur_line)
7164 			return;
7165 
7166 		if (str_has_pfx(cur_line, "invalid func unknown#195896080\n")) {
7167 			prev_line = find_prev_line(buf, cur_line);
7168 			if (!prev_line)
7169 				continue;
7170 
7171 			/* failed CO-RE relocation case */
7172 			fixup_log_failed_core_relo(prog, buf, buf_sz, log_sz,
7173 						   prev_line, cur_line, next_line);
7174 			return;
7175 		} else if (str_has_pfx(cur_line, "invalid func unknown#"POISON_LDIMM64_MAP_PFX)) {
7176 			prev_line = find_prev_line(buf, cur_line);
7177 			if (!prev_line)
7178 				continue;
7179 
7180 			/* reference to uncreated BPF map */
7181 			fixup_log_missing_map_load(prog, buf, buf_sz, log_sz,
7182 						   prev_line, cur_line, next_line);
7183 			return;
7184 		} else if (str_has_pfx(cur_line, "invalid func unknown#"POISON_CALL_KFUNC_PFX)) {
7185 			prev_line = find_prev_line(buf, cur_line);
7186 			if (!prev_line)
7187 				continue;
7188 
7189 			/* reference to unresolved kfunc */
7190 			fixup_log_missing_kfunc_call(prog, buf, buf_sz, log_sz,
7191 						     prev_line, cur_line, next_line);
7192 			return;
7193 		}
7194 	}
7195 }
7196 
7197 static int bpf_program_record_relos(struct bpf_program *prog)
7198 {
7199 	struct bpf_object *obj = prog->obj;
7200 	int i;
7201 
7202 	for (i = 0; i < prog->nr_reloc; i++) {
7203 		struct reloc_desc *relo = &prog->reloc_desc[i];
7204 		struct extern_desc *ext = &obj->externs[relo->ext_idx];
7205 		int kind;
7206 
7207 		switch (relo->type) {
7208 		case RELO_EXTERN_LD64:
7209 			if (ext->type != EXT_KSYM)
7210 				continue;
7211 			kind = btf_is_var(btf__type_by_id(obj->btf, ext->btf_id)) ?
7212 				BTF_KIND_VAR : BTF_KIND_FUNC;
7213 			bpf_gen__record_extern(obj->gen_loader, ext->name,
7214 					       ext->is_weak, !ext->ksym.type_id,
7215 					       true, kind, relo->insn_idx);
7216 			break;
7217 		case RELO_EXTERN_CALL:
7218 			bpf_gen__record_extern(obj->gen_loader, ext->name,
7219 					       ext->is_weak, false, false, BTF_KIND_FUNC,
7220 					       relo->insn_idx);
7221 			break;
7222 		case RELO_CORE: {
7223 			struct bpf_core_relo cr = {
7224 				.insn_off = relo->insn_idx * 8,
7225 				.type_id = relo->core_relo->type_id,
7226 				.access_str_off = relo->core_relo->access_str_off,
7227 				.kind = relo->core_relo->kind,
7228 			};
7229 
7230 			bpf_gen__record_relo_core(obj->gen_loader, &cr);
7231 			break;
7232 		}
7233 		default:
7234 			continue;
7235 		}
7236 	}
7237 	return 0;
7238 }
7239 
7240 static int
7241 bpf_object__load_progs(struct bpf_object *obj, int log_level)
7242 {
7243 	struct bpf_program *prog;
7244 	size_t i;
7245 	int err;
7246 
7247 	for (i = 0; i < obj->nr_programs; i++) {
7248 		prog = &obj->programs[i];
7249 		err = bpf_object__sanitize_prog(obj, prog);
7250 		if (err)
7251 			return err;
7252 	}
7253 
7254 	for (i = 0; i < obj->nr_programs; i++) {
7255 		prog = &obj->programs[i];
7256 		if (prog_is_subprog(obj, prog))
7257 			continue;
7258 		if (!prog->autoload) {
7259 			pr_debug("prog '%s': skipped loading\n", prog->name);
7260 			continue;
7261 		}
7262 		prog->log_level |= log_level;
7263 
7264 		if (obj->gen_loader)
7265 			bpf_program_record_relos(prog);
7266 
7267 		err = bpf_object_load_prog(obj, prog, prog->insns, prog->insns_cnt,
7268 					   obj->license, obj->kern_version, &prog->fd);
7269 		if (err) {
7270 			pr_warn("prog '%s': failed to load: %d\n", prog->name, err);
7271 			return err;
7272 		}
7273 	}
7274 
7275 	bpf_object__free_relocs(obj);
7276 	return 0;
7277 }
7278 
7279 static const struct bpf_sec_def *find_sec_def(const char *sec_name);
7280 
7281 static int bpf_object_init_progs(struct bpf_object *obj, const struct bpf_object_open_opts *opts)
7282 {
7283 	struct bpf_program *prog;
7284 	int err;
7285 
7286 	bpf_object__for_each_program(prog, obj) {
7287 		prog->sec_def = find_sec_def(prog->sec_name);
7288 		if (!prog->sec_def) {
7289 			/* couldn't guess, but user might manually specify */
7290 			pr_debug("prog '%s': unrecognized ELF section name '%s'\n",
7291 				prog->name, prog->sec_name);
7292 			continue;
7293 		}
7294 
7295 		prog->type = prog->sec_def->prog_type;
7296 		prog->expected_attach_type = prog->sec_def->expected_attach_type;
7297 
7298 		/* sec_def can have custom callback which should be called
7299 		 * after bpf_program is initialized to adjust its properties
7300 		 */
7301 		if (prog->sec_def->prog_setup_fn) {
7302 			err = prog->sec_def->prog_setup_fn(prog, prog->sec_def->cookie);
7303 			if (err < 0) {
7304 				pr_warn("prog '%s': failed to initialize: %d\n",
7305 					prog->name, err);
7306 				return err;
7307 			}
7308 		}
7309 	}
7310 
7311 	return 0;
7312 }
7313 
7314 static struct bpf_object *bpf_object_open(const char *path, const void *obj_buf, size_t obj_buf_sz,
7315 					  const struct bpf_object_open_opts *opts)
7316 {
7317 	const char *obj_name, *kconfig, *btf_tmp_path;
7318 	struct bpf_object *obj;
7319 	char tmp_name[64];
7320 	int err;
7321 	char *log_buf;
7322 	size_t log_size;
7323 	__u32 log_level;
7324 
7325 	if (elf_version(EV_CURRENT) == EV_NONE) {
7326 		pr_warn("failed to init libelf for %s\n",
7327 			path ? : "(mem buf)");
7328 		return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
7329 	}
7330 
7331 	if (!OPTS_VALID(opts, bpf_object_open_opts))
7332 		return ERR_PTR(-EINVAL);
7333 
7334 	obj_name = OPTS_GET(opts, object_name, NULL);
7335 	if (obj_buf) {
7336 		if (!obj_name) {
7337 			snprintf(tmp_name, sizeof(tmp_name), "%lx-%lx",
7338 				 (unsigned long)obj_buf,
7339 				 (unsigned long)obj_buf_sz);
7340 			obj_name = tmp_name;
7341 		}
7342 		path = obj_name;
7343 		pr_debug("loading object '%s' from buffer\n", obj_name);
7344 	}
7345 
7346 	log_buf = OPTS_GET(opts, kernel_log_buf, NULL);
7347 	log_size = OPTS_GET(opts, kernel_log_size, 0);
7348 	log_level = OPTS_GET(opts, kernel_log_level, 0);
7349 	if (log_size > UINT_MAX)
7350 		return ERR_PTR(-EINVAL);
7351 	if (log_size && !log_buf)
7352 		return ERR_PTR(-EINVAL);
7353 
7354 	obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
7355 	if (IS_ERR(obj))
7356 		return obj;
7357 
7358 	obj->log_buf = log_buf;
7359 	obj->log_size = log_size;
7360 	obj->log_level = log_level;
7361 
7362 	btf_tmp_path = OPTS_GET(opts, btf_custom_path, NULL);
7363 	if (btf_tmp_path) {
7364 		if (strlen(btf_tmp_path) >= PATH_MAX) {
7365 			err = -ENAMETOOLONG;
7366 			goto out;
7367 		}
7368 		obj->btf_custom_path = strdup(btf_tmp_path);
7369 		if (!obj->btf_custom_path) {
7370 			err = -ENOMEM;
7371 			goto out;
7372 		}
7373 	}
7374 
7375 	kconfig = OPTS_GET(opts, kconfig, NULL);
7376 	if (kconfig) {
7377 		obj->kconfig = strdup(kconfig);
7378 		if (!obj->kconfig) {
7379 			err = -ENOMEM;
7380 			goto out;
7381 		}
7382 	}
7383 
7384 	err = bpf_object__elf_init(obj);
7385 	err = err ? : bpf_object__check_endianness(obj);
7386 	err = err ? : bpf_object__elf_collect(obj);
7387 	err = err ? : bpf_object__collect_externs(obj);
7388 	err = err ? : bpf_object_fixup_btf(obj);
7389 	err = err ? : bpf_object__init_maps(obj, opts);
7390 	err = err ? : bpf_object_init_progs(obj, opts);
7391 	err = err ? : bpf_object__collect_relos(obj);
7392 	if (err)
7393 		goto out;
7394 
7395 	bpf_object__elf_finish(obj);
7396 
7397 	return obj;
7398 out:
7399 	bpf_object__close(obj);
7400 	return ERR_PTR(err);
7401 }
7402 
7403 struct bpf_object *
7404 bpf_object__open_file(const char *path, const struct bpf_object_open_opts *opts)
7405 {
7406 	if (!path)
7407 		return libbpf_err_ptr(-EINVAL);
7408 
7409 	pr_debug("loading %s\n", path);
7410 
7411 	return libbpf_ptr(bpf_object_open(path, NULL, 0, opts));
7412 }
7413 
7414 struct bpf_object *bpf_object__open(const char *path)
7415 {
7416 	return bpf_object__open_file(path, NULL);
7417 }
7418 
7419 struct bpf_object *
7420 bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
7421 		     const struct bpf_object_open_opts *opts)
7422 {
7423 	if (!obj_buf || obj_buf_sz == 0)
7424 		return libbpf_err_ptr(-EINVAL);
7425 
7426 	return libbpf_ptr(bpf_object_open(NULL, obj_buf, obj_buf_sz, opts));
7427 }
7428 
7429 static int bpf_object_unload(struct bpf_object *obj)
7430 {
7431 	size_t i;
7432 
7433 	if (!obj)
7434 		return libbpf_err(-EINVAL);
7435 
7436 	for (i = 0; i < obj->nr_maps; i++) {
7437 		zclose(obj->maps[i].fd);
7438 		if (obj->maps[i].st_ops)
7439 			zfree(&obj->maps[i].st_ops->kern_vdata);
7440 	}
7441 
7442 	for (i = 0; i < obj->nr_programs; i++)
7443 		bpf_program__unload(&obj->programs[i]);
7444 
7445 	return 0;
7446 }
7447 
7448 static int bpf_object__sanitize_maps(struct bpf_object *obj)
7449 {
7450 	struct bpf_map *m;
7451 
7452 	bpf_object__for_each_map(m, obj) {
7453 		if (!bpf_map__is_internal(m))
7454 			continue;
7455 		if (!kernel_supports(obj, FEAT_ARRAY_MMAP))
7456 			m->def.map_flags &= ~BPF_F_MMAPABLE;
7457 	}
7458 
7459 	return 0;
7460 }
7461 
7462 int libbpf_kallsyms_parse(kallsyms_cb_t cb, void *ctx)
7463 {
7464 	char sym_type, sym_name[500];
7465 	unsigned long long sym_addr;
7466 	int ret, err = 0;
7467 	FILE *f;
7468 
7469 	f = fopen("/proc/kallsyms", "re");
7470 	if (!f) {
7471 		err = -errno;
7472 		pr_warn("failed to open /proc/kallsyms: %d\n", err);
7473 		return err;
7474 	}
7475 
7476 	while (true) {
7477 		ret = fscanf(f, "%llx %c %499s%*[^\n]\n",
7478 			     &sym_addr, &sym_type, sym_name);
7479 		if (ret == EOF && feof(f))
7480 			break;
7481 		if (ret != 3) {
7482 			pr_warn("failed to read kallsyms entry: %d\n", ret);
7483 			err = -EINVAL;
7484 			break;
7485 		}
7486 
7487 		err = cb(sym_addr, sym_type, sym_name, ctx);
7488 		if (err)
7489 			break;
7490 	}
7491 
7492 	fclose(f);
7493 	return err;
7494 }
7495 
7496 static int kallsyms_cb(unsigned long long sym_addr, char sym_type,
7497 		       const char *sym_name, void *ctx)
7498 {
7499 	struct bpf_object *obj = ctx;
7500 	const struct btf_type *t;
7501 	struct extern_desc *ext;
7502 
7503 	ext = find_extern_by_name(obj, sym_name);
7504 	if (!ext || ext->type != EXT_KSYM)
7505 		return 0;
7506 
7507 	t = btf__type_by_id(obj->btf, ext->btf_id);
7508 	if (!btf_is_var(t))
7509 		return 0;
7510 
7511 	if (ext->is_set && ext->ksym.addr != sym_addr) {
7512 		pr_warn("extern (ksym) '%s': resolution is ambiguous: 0x%llx or 0x%llx\n",
7513 			sym_name, ext->ksym.addr, sym_addr);
7514 		return -EINVAL;
7515 	}
7516 	if (!ext->is_set) {
7517 		ext->is_set = true;
7518 		ext->ksym.addr = sym_addr;
7519 		pr_debug("extern (ksym) '%s': set to 0x%llx\n", sym_name, sym_addr);
7520 	}
7521 	return 0;
7522 }
7523 
7524 static int bpf_object__read_kallsyms_file(struct bpf_object *obj)
7525 {
7526 	return libbpf_kallsyms_parse(kallsyms_cb, obj);
7527 }
7528 
7529 static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
7530 			    __u16 kind, struct btf **res_btf,
7531 			    struct module_btf **res_mod_btf)
7532 {
7533 	struct module_btf *mod_btf;
7534 	struct btf *btf;
7535 	int i, id, err;
7536 
7537 	btf = obj->btf_vmlinux;
7538 	mod_btf = NULL;
7539 	id = btf__find_by_name_kind(btf, ksym_name, kind);
7540 
7541 	if (id == -ENOENT) {
7542 		err = load_module_btfs(obj);
7543 		if (err)
7544 			return err;
7545 
7546 		for (i = 0; i < obj->btf_module_cnt; i++) {
7547 			/* we assume module_btf's BTF FD is always >0 */
7548 			mod_btf = &obj->btf_modules[i];
7549 			btf = mod_btf->btf;
7550 			id = btf__find_by_name_kind_own(btf, ksym_name, kind);
7551 			if (id != -ENOENT)
7552 				break;
7553 		}
7554 	}
7555 	if (id <= 0)
7556 		return -ESRCH;
7557 
7558 	*res_btf = btf;
7559 	*res_mod_btf = mod_btf;
7560 	return id;
7561 }
7562 
7563 static int bpf_object__resolve_ksym_var_btf_id(struct bpf_object *obj,
7564 					       struct extern_desc *ext)
7565 {
7566 	const struct btf_type *targ_var, *targ_type;
7567 	__u32 targ_type_id, local_type_id;
7568 	struct module_btf *mod_btf = NULL;
7569 	const char *targ_var_name;
7570 	struct btf *btf = NULL;
7571 	int id, err;
7572 
7573 	id = find_ksym_btf_id(obj, ext->name, BTF_KIND_VAR, &btf, &mod_btf);
7574 	if (id < 0) {
7575 		if (id == -ESRCH && ext->is_weak)
7576 			return 0;
7577 		pr_warn("extern (var ksym) '%s': not found in kernel BTF\n",
7578 			ext->name);
7579 		return id;
7580 	}
7581 
7582 	/* find local type_id */
7583 	local_type_id = ext->ksym.type_id;
7584 
7585 	/* find target type_id */
7586 	targ_var = btf__type_by_id(btf, id);
7587 	targ_var_name = btf__name_by_offset(btf, targ_var->name_off);
7588 	targ_type = skip_mods_and_typedefs(btf, targ_var->type, &targ_type_id);
7589 
7590 	err = bpf_core_types_are_compat(obj->btf, local_type_id,
7591 					btf, targ_type_id);
7592 	if (err <= 0) {
7593 		const struct btf_type *local_type;
7594 		const char *targ_name, *local_name;
7595 
7596 		local_type = btf__type_by_id(obj->btf, local_type_id);
7597 		local_name = btf__name_by_offset(obj->btf, local_type->name_off);
7598 		targ_name = btf__name_by_offset(btf, targ_type->name_off);
7599 
7600 		pr_warn("extern (var ksym) '%s': incompatible types, expected [%d] %s %s, but kernel has [%d] %s %s\n",
7601 			ext->name, local_type_id,
7602 			btf_kind_str(local_type), local_name, targ_type_id,
7603 			btf_kind_str(targ_type), targ_name);
7604 		return -EINVAL;
7605 	}
7606 
7607 	ext->is_set = true;
7608 	ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
7609 	ext->ksym.kernel_btf_id = id;
7610 	pr_debug("extern (var ksym) '%s': resolved to [%d] %s %s\n",
7611 		 ext->name, id, btf_kind_str(targ_var), targ_var_name);
7612 
7613 	return 0;
7614 }
7615 
7616 static int bpf_object__resolve_ksym_func_btf_id(struct bpf_object *obj,
7617 						struct extern_desc *ext)
7618 {
7619 	int local_func_proto_id, kfunc_proto_id, kfunc_id;
7620 	struct module_btf *mod_btf = NULL;
7621 	const struct btf_type *kern_func;
7622 	struct btf *kern_btf = NULL;
7623 	int ret;
7624 
7625 	local_func_proto_id = ext->ksym.type_id;
7626 
7627 	kfunc_id = find_ksym_btf_id(obj, ext->name, BTF_KIND_FUNC, &kern_btf, &mod_btf);
7628 	if (kfunc_id < 0) {
7629 		if (kfunc_id == -ESRCH && ext->is_weak)
7630 			return 0;
7631 		pr_warn("extern (func ksym) '%s': not found in kernel or module BTFs\n",
7632 			ext->name);
7633 		return kfunc_id;
7634 	}
7635 
7636 	kern_func = btf__type_by_id(kern_btf, kfunc_id);
7637 	kfunc_proto_id = kern_func->type;
7638 
7639 	ret = bpf_core_types_are_compat(obj->btf, local_func_proto_id,
7640 					kern_btf, kfunc_proto_id);
7641 	if (ret <= 0) {
7642 		pr_warn("extern (func ksym) '%s': func_proto [%d] incompatible with %s [%d]\n",
7643 			ext->name, local_func_proto_id,
7644 			mod_btf ? mod_btf->name : "vmlinux", kfunc_proto_id);
7645 		return -EINVAL;
7646 	}
7647 
7648 	/* set index for module BTF fd in fd_array, if unset */
7649 	if (mod_btf && !mod_btf->fd_array_idx) {
7650 		/* insn->off is s16 */
7651 		if (obj->fd_array_cnt == INT16_MAX) {
7652 			pr_warn("extern (func ksym) '%s': module BTF fd index %d too big to fit in bpf_insn offset\n",
7653 				ext->name, mod_btf->fd_array_idx);
7654 			return -E2BIG;
7655 		}
7656 		/* Cannot use index 0 for module BTF fd */
7657 		if (!obj->fd_array_cnt)
7658 			obj->fd_array_cnt = 1;
7659 
7660 		ret = libbpf_ensure_mem((void **)&obj->fd_array, &obj->fd_array_cap, sizeof(int),
7661 					obj->fd_array_cnt + 1);
7662 		if (ret)
7663 			return ret;
7664 		mod_btf->fd_array_idx = obj->fd_array_cnt;
7665 		/* we assume module BTF FD is always >0 */
7666 		obj->fd_array[obj->fd_array_cnt++] = mod_btf->fd;
7667 	}
7668 
7669 	ext->is_set = true;
7670 	ext->ksym.kernel_btf_id = kfunc_id;
7671 	ext->ksym.btf_fd_idx = mod_btf ? mod_btf->fd_array_idx : 0;
7672 	/* Also set kernel_btf_obj_fd to make sure that bpf_object__relocate_data()
7673 	 * populates FD into ld_imm64 insn when it's used to point to kfunc.
7674 	 * {kernel_btf_id, btf_fd_idx} -> fixup bpf_call.
7675 	 * {kernel_btf_id, kernel_btf_obj_fd} -> fixup ld_imm64.
7676 	 */
7677 	ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
7678 	pr_debug("extern (func ksym) '%s': resolved to %s [%d]\n",
7679 		 ext->name, mod_btf ? mod_btf->name : "vmlinux", kfunc_id);
7680 
7681 	return 0;
7682 }
7683 
7684 static int bpf_object__resolve_ksyms_btf_id(struct bpf_object *obj)
7685 {
7686 	const struct btf_type *t;
7687 	struct extern_desc *ext;
7688 	int i, err;
7689 
7690 	for (i = 0; i < obj->nr_extern; i++) {
7691 		ext = &obj->externs[i];
7692 		if (ext->type != EXT_KSYM || !ext->ksym.type_id)
7693 			continue;
7694 
7695 		if (obj->gen_loader) {
7696 			ext->is_set = true;
7697 			ext->ksym.kernel_btf_obj_fd = 0;
7698 			ext->ksym.kernel_btf_id = 0;
7699 			continue;
7700 		}
7701 		t = btf__type_by_id(obj->btf, ext->btf_id);
7702 		if (btf_is_var(t))
7703 			err = bpf_object__resolve_ksym_var_btf_id(obj, ext);
7704 		else
7705 			err = bpf_object__resolve_ksym_func_btf_id(obj, ext);
7706 		if (err)
7707 			return err;
7708 	}
7709 	return 0;
7710 }
7711 
7712 static int bpf_object__resolve_externs(struct bpf_object *obj,
7713 				       const char *extra_kconfig)
7714 {
7715 	bool need_config = false, need_kallsyms = false;
7716 	bool need_vmlinux_btf = false;
7717 	struct extern_desc *ext;
7718 	void *kcfg_data = NULL;
7719 	int err, i;
7720 
7721 	if (obj->nr_extern == 0)
7722 		return 0;
7723 
7724 	if (obj->kconfig_map_idx >= 0)
7725 		kcfg_data = obj->maps[obj->kconfig_map_idx].mmaped;
7726 
7727 	for (i = 0; i < obj->nr_extern; i++) {
7728 		ext = &obj->externs[i];
7729 
7730 		if (ext->type == EXT_KSYM) {
7731 			if (ext->ksym.type_id)
7732 				need_vmlinux_btf = true;
7733 			else
7734 				need_kallsyms = true;
7735 			continue;
7736 		} else if (ext->type == EXT_KCFG) {
7737 			void *ext_ptr = kcfg_data + ext->kcfg.data_off;
7738 			__u64 value = 0;
7739 
7740 			/* Kconfig externs need actual /proc/config.gz */
7741 			if (str_has_pfx(ext->name, "CONFIG_")) {
7742 				need_config = true;
7743 				continue;
7744 			}
7745 
7746 			/* Virtual kcfg externs are customly handled by libbpf */
7747 			if (strcmp(ext->name, "LINUX_KERNEL_VERSION") == 0) {
7748 				value = get_kernel_version();
7749 				if (!value) {
7750 					pr_warn("extern (kcfg) '%s': failed to get kernel version\n", ext->name);
7751 					return -EINVAL;
7752 				}
7753 			} else if (strcmp(ext->name, "LINUX_HAS_BPF_COOKIE") == 0) {
7754 				value = kernel_supports(obj, FEAT_BPF_COOKIE);
7755 			} else if (strcmp(ext->name, "LINUX_HAS_SYSCALL_WRAPPER") == 0) {
7756 				value = kernel_supports(obj, FEAT_SYSCALL_WRAPPER);
7757 			} else if (!str_has_pfx(ext->name, "LINUX_") || !ext->is_weak) {
7758 				/* Currently libbpf supports only CONFIG_ and LINUX_ prefixed
7759 				 * __kconfig externs, where LINUX_ ones are virtual and filled out
7760 				 * customly by libbpf (their values don't come from Kconfig).
7761 				 * If LINUX_xxx variable is not recognized by libbpf, but is marked
7762 				 * __weak, it defaults to zero value, just like for CONFIG_xxx
7763 				 * externs.
7764 				 */
7765 				pr_warn("extern (kcfg) '%s': unrecognized virtual extern\n", ext->name);
7766 				return -EINVAL;
7767 			}
7768 
7769 			err = set_kcfg_value_num(ext, ext_ptr, value);
7770 			if (err)
7771 				return err;
7772 			pr_debug("extern (kcfg) '%s': set to 0x%llx\n",
7773 				 ext->name, (long long)value);
7774 		} else {
7775 			pr_warn("extern '%s': unrecognized extern kind\n", ext->name);
7776 			return -EINVAL;
7777 		}
7778 	}
7779 	if (need_config && extra_kconfig) {
7780 		err = bpf_object__read_kconfig_mem(obj, extra_kconfig, kcfg_data);
7781 		if (err)
7782 			return -EINVAL;
7783 		need_config = false;
7784 		for (i = 0; i < obj->nr_extern; i++) {
7785 			ext = &obj->externs[i];
7786 			if (ext->type == EXT_KCFG && !ext->is_set) {
7787 				need_config = true;
7788 				break;
7789 			}
7790 		}
7791 	}
7792 	if (need_config) {
7793 		err = bpf_object__read_kconfig_file(obj, kcfg_data);
7794 		if (err)
7795 			return -EINVAL;
7796 	}
7797 	if (need_kallsyms) {
7798 		err = bpf_object__read_kallsyms_file(obj);
7799 		if (err)
7800 			return -EINVAL;
7801 	}
7802 	if (need_vmlinux_btf) {
7803 		err = bpf_object__resolve_ksyms_btf_id(obj);
7804 		if (err)
7805 			return -EINVAL;
7806 	}
7807 	for (i = 0; i < obj->nr_extern; i++) {
7808 		ext = &obj->externs[i];
7809 
7810 		if (!ext->is_set && !ext->is_weak) {
7811 			pr_warn("extern '%s' (strong): not resolved\n", ext->name);
7812 			return -ESRCH;
7813 		} else if (!ext->is_set) {
7814 			pr_debug("extern '%s' (weak): not resolved, defaulting to zero\n",
7815 				 ext->name);
7816 		}
7817 	}
7818 
7819 	return 0;
7820 }
7821 
7822 static void bpf_map_prepare_vdata(const struct bpf_map *map)
7823 {
7824 	struct bpf_struct_ops *st_ops;
7825 	__u32 i;
7826 
7827 	st_ops = map->st_ops;
7828 	for (i = 0; i < btf_vlen(st_ops->type); i++) {
7829 		struct bpf_program *prog = st_ops->progs[i];
7830 		void *kern_data;
7831 		int prog_fd;
7832 
7833 		if (!prog)
7834 			continue;
7835 
7836 		prog_fd = bpf_program__fd(prog);
7837 		kern_data = st_ops->kern_vdata + st_ops->kern_func_off[i];
7838 		*(unsigned long *)kern_data = prog_fd;
7839 	}
7840 }
7841 
7842 static int bpf_object_prepare_struct_ops(struct bpf_object *obj)
7843 {
7844 	int i;
7845 
7846 	for (i = 0; i < obj->nr_maps; i++)
7847 		if (bpf_map__is_struct_ops(&obj->maps[i]))
7848 			bpf_map_prepare_vdata(&obj->maps[i]);
7849 
7850 	return 0;
7851 }
7852 
7853 static int bpf_object_load(struct bpf_object *obj, int extra_log_level, const char *target_btf_path)
7854 {
7855 	int err, i;
7856 
7857 	if (!obj)
7858 		return libbpf_err(-EINVAL);
7859 
7860 	if (obj->loaded) {
7861 		pr_warn("object '%s': load can't be attempted twice\n", obj->name);
7862 		return libbpf_err(-EINVAL);
7863 	}
7864 
7865 	if (obj->gen_loader)
7866 		bpf_gen__init(obj->gen_loader, extra_log_level, obj->nr_programs, obj->nr_maps);
7867 
7868 	err = bpf_object__probe_loading(obj);
7869 	err = err ? : bpf_object__load_vmlinux_btf(obj, false);
7870 	err = err ? : bpf_object__resolve_externs(obj, obj->kconfig);
7871 	err = err ? : bpf_object__sanitize_and_load_btf(obj);
7872 	err = err ? : bpf_object__sanitize_maps(obj);
7873 	err = err ? : bpf_object__init_kern_struct_ops_maps(obj);
7874 	err = err ? : bpf_object__create_maps(obj);
7875 	err = err ? : bpf_object__relocate(obj, obj->btf_custom_path ? : target_btf_path);
7876 	err = err ? : bpf_object__load_progs(obj, extra_log_level);
7877 	err = err ? : bpf_object_init_prog_arrays(obj);
7878 	err = err ? : bpf_object_prepare_struct_ops(obj);
7879 
7880 	if (obj->gen_loader) {
7881 		/* reset FDs */
7882 		if (obj->btf)
7883 			btf__set_fd(obj->btf, -1);
7884 		for (i = 0; i < obj->nr_maps; i++)
7885 			obj->maps[i].fd = -1;
7886 		if (!err)
7887 			err = bpf_gen__finish(obj->gen_loader, obj->nr_programs, obj->nr_maps);
7888 	}
7889 
7890 	/* clean up fd_array */
7891 	zfree(&obj->fd_array);
7892 
7893 	/* clean up module BTFs */
7894 	for (i = 0; i < obj->btf_module_cnt; i++) {
7895 		close(obj->btf_modules[i].fd);
7896 		btf__free(obj->btf_modules[i].btf);
7897 		free(obj->btf_modules[i].name);
7898 	}
7899 	free(obj->btf_modules);
7900 
7901 	/* clean up vmlinux BTF */
7902 	btf__free(obj->btf_vmlinux);
7903 	obj->btf_vmlinux = NULL;
7904 
7905 	obj->loaded = true; /* doesn't matter if successfully or not */
7906 
7907 	if (err)
7908 		goto out;
7909 
7910 	return 0;
7911 out:
7912 	/* unpin any maps that were auto-pinned during load */
7913 	for (i = 0; i < obj->nr_maps; i++)
7914 		if (obj->maps[i].pinned && !obj->maps[i].reused)
7915 			bpf_map__unpin(&obj->maps[i], NULL);
7916 
7917 	bpf_object_unload(obj);
7918 	pr_warn("failed to load object '%s'\n", obj->path);
7919 	return libbpf_err(err);
7920 }
7921 
7922 int bpf_object__load(struct bpf_object *obj)
7923 {
7924 	return bpf_object_load(obj, 0, NULL);
7925 }
7926 
7927 static int make_parent_dir(const char *path)
7928 {
7929 	char *cp, errmsg[STRERR_BUFSIZE];
7930 	char *dname, *dir;
7931 	int err = 0;
7932 
7933 	dname = strdup(path);
7934 	if (dname == NULL)
7935 		return -ENOMEM;
7936 
7937 	dir = dirname(dname);
7938 	if (mkdir(dir, 0700) && errno != EEXIST)
7939 		err = -errno;
7940 
7941 	free(dname);
7942 	if (err) {
7943 		cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
7944 		pr_warn("failed to mkdir %s: %s\n", path, cp);
7945 	}
7946 	return err;
7947 }
7948 
7949 static int check_path(const char *path)
7950 {
7951 	char *cp, errmsg[STRERR_BUFSIZE];
7952 	struct statfs st_fs;
7953 	char *dname, *dir;
7954 	int err = 0;
7955 
7956 	if (path == NULL)
7957 		return -EINVAL;
7958 
7959 	dname = strdup(path);
7960 	if (dname == NULL)
7961 		return -ENOMEM;
7962 
7963 	dir = dirname(dname);
7964 	if (statfs(dir, &st_fs)) {
7965 		cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
7966 		pr_warn("failed to statfs %s: %s\n", dir, cp);
7967 		err = -errno;
7968 	}
7969 	free(dname);
7970 
7971 	if (!err && st_fs.f_type != BPF_FS_MAGIC) {
7972 		pr_warn("specified path %s is not on BPF FS\n", path);
7973 		err = -EINVAL;
7974 	}
7975 
7976 	return err;
7977 }
7978 
7979 int bpf_program__pin(struct bpf_program *prog, const char *path)
7980 {
7981 	char *cp, errmsg[STRERR_BUFSIZE];
7982 	int err;
7983 
7984 	if (prog->fd < 0) {
7985 		pr_warn("prog '%s': can't pin program that wasn't loaded\n", prog->name);
7986 		return libbpf_err(-EINVAL);
7987 	}
7988 
7989 	err = make_parent_dir(path);
7990 	if (err)
7991 		return libbpf_err(err);
7992 
7993 	err = check_path(path);
7994 	if (err)
7995 		return libbpf_err(err);
7996 
7997 	if (bpf_obj_pin(prog->fd, path)) {
7998 		err = -errno;
7999 		cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
8000 		pr_warn("prog '%s': failed to pin at '%s': %s\n", prog->name, path, cp);
8001 		return libbpf_err(err);
8002 	}
8003 
8004 	pr_debug("prog '%s': pinned at '%s'\n", prog->name, path);
8005 	return 0;
8006 }
8007 
8008 int bpf_program__unpin(struct bpf_program *prog, const char *path)
8009 {
8010 	int err;
8011 
8012 	if (prog->fd < 0) {
8013 		pr_warn("prog '%s': can't unpin program that wasn't loaded\n", prog->name);
8014 		return libbpf_err(-EINVAL);
8015 	}
8016 
8017 	err = check_path(path);
8018 	if (err)
8019 		return libbpf_err(err);
8020 
8021 	err = unlink(path);
8022 	if (err)
8023 		return libbpf_err(-errno);
8024 
8025 	pr_debug("prog '%s': unpinned from '%s'\n", prog->name, path);
8026 	return 0;
8027 }
8028 
8029 int bpf_map__pin(struct bpf_map *map, const char *path)
8030 {
8031 	char *cp, errmsg[STRERR_BUFSIZE];
8032 	int err;
8033 
8034 	if (map == NULL) {
8035 		pr_warn("invalid map pointer\n");
8036 		return libbpf_err(-EINVAL);
8037 	}
8038 
8039 	if (map->pin_path) {
8040 		if (path && strcmp(path, map->pin_path)) {
8041 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
8042 				bpf_map__name(map), map->pin_path, path);
8043 			return libbpf_err(-EINVAL);
8044 		} else if (map->pinned) {
8045 			pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
8046 				 bpf_map__name(map), map->pin_path);
8047 			return 0;
8048 		}
8049 	} else {
8050 		if (!path) {
8051 			pr_warn("missing a path to pin map '%s' at\n",
8052 				bpf_map__name(map));
8053 			return libbpf_err(-EINVAL);
8054 		} else if (map->pinned) {
8055 			pr_warn("map '%s' already pinned\n", bpf_map__name(map));
8056 			return libbpf_err(-EEXIST);
8057 		}
8058 
8059 		map->pin_path = strdup(path);
8060 		if (!map->pin_path) {
8061 			err = -errno;
8062 			goto out_err;
8063 		}
8064 	}
8065 
8066 	err = make_parent_dir(map->pin_path);
8067 	if (err)
8068 		return libbpf_err(err);
8069 
8070 	err = check_path(map->pin_path);
8071 	if (err)
8072 		return libbpf_err(err);
8073 
8074 	if (bpf_obj_pin(map->fd, map->pin_path)) {
8075 		err = -errno;
8076 		goto out_err;
8077 	}
8078 
8079 	map->pinned = true;
8080 	pr_debug("pinned map '%s'\n", map->pin_path);
8081 
8082 	return 0;
8083 
8084 out_err:
8085 	cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
8086 	pr_warn("failed to pin map: %s\n", cp);
8087 	return libbpf_err(err);
8088 }
8089 
8090 int bpf_map__unpin(struct bpf_map *map, const char *path)
8091 {
8092 	int err;
8093 
8094 	if (map == NULL) {
8095 		pr_warn("invalid map pointer\n");
8096 		return libbpf_err(-EINVAL);
8097 	}
8098 
8099 	if (map->pin_path) {
8100 		if (path && strcmp(path, map->pin_path)) {
8101 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
8102 				bpf_map__name(map), map->pin_path, path);
8103 			return libbpf_err(-EINVAL);
8104 		}
8105 		path = map->pin_path;
8106 	} else if (!path) {
8107 		pr_warn("no path to unpin map '%s' from\n",
8108 			bpf_map__name(map));
8109 		return libbpf_err(-EINVAL);
8110 	}
8111 
8112 	err = check_path(path);
8113 	if (err)
8114 		return libbpf_err(err);
8115 
8116 	err = unlink(path);
8117 	if (err != 0)
8118 		return libbpf_err(-errno);
8119 
8120 	map->pinned = false;
8121 	pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path);
8122 
8123 	return 0;
8124 }
8125 
8126 int bpf_map__set_pin_path(struct bpf_map *map, const char *path)
8127 {
8128 	char *new = NULL;
8129 
8130 	if (path) {
8131 		new = strdup(path);
8132 		if (!new)
8133 			return libbpf_err(-errno);
8134 	}
8135 
8136 	free(map->pin_path);
8137 	map->pin_path = new;
8138 	return 0;
8139 }
8140 
8141 __alias(bpf_map__pin_path)
8142 const char *bpf_map__get_pin_path(const struct bpf_map *map);
8143 
8144 const char *bpf_map__pin_path(const struct bpf_map *map)
8145 {
8146 	return map->pin_path;
8147 }
8148 
8149 bool bpf_map__is_pinned(const struct bpf_map *map)
8150 {
8151 	return map->pinned;
8152 }
8153 
8154 static void sanitize_pin_path(char *s)
8155 {
8156 	/* bpffs disallows periods in path names */
8157 	while (*s) {
8158 		if (*s == '.')
8159 			*s = '_';
8160 		s++;
8161 	}
8162 }
8163 
8164 int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
8165 {
8166 	struct bpf_map *map;
8167 	int err;
8168 
8169 	if (!obj)
8170 		return libbpf_err(-ENOENT);
8171 
8172 	if (!obj->loaded) {
8173 		pr_warn("object not yet loaded; load it first\n");
8174 		return libbpf_err(-ENOENT);
8175 	}
8176 
8177 	bpf_object__for_each_map(map, obj) {
8178 		char *pin_path = NULL;
8179 		char buf[PATH_MAX];
8180 
8181 		if (!map->autocreate)
8182 			continue;
8183 
8184 		if (path) {
8185 			err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
8186 			if (err)
8187 				goto err_unpin_maps;
8188 			sanitize_pin_path(buf);
8189 			pin_path = buf;
8190 		} else if (!map->pin_path) {
8191 			continue;
8192 		}
8193 
8194 		err = bpf_map__pin(map, pin_path);
8195 		if (err)
8196 			goto err_unpin_maps;
8197 	}
8198 
8199 	return 0;
8200 
8201 err_unpin_maps:
8202 	while ((map = bpf_object__prev_map(obj, map))) {
8203 		if (!map->pin_path)
8204 			continue;
8205 
8206 		bpf_map__unpin(map, NULL);
8207 	}
8208 
8209 	return libbpf_err(err);
8210 }
8211 
8212 int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
8213 {
8214 	struct bpf_map *map;
8215 	int err;
8216 
8217 	if (!obj)
8218 		return libbpf_err(-ENOENT);
8219 
8220 	bpf_object__for_each_map(map, obj) {
8221 		char *pin_path = NULL;
8222 		char buf[PATH_MAX];
8223 
8224 		if (path) {
8225 			err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
8226 			if (err)
8227 				return libbpf_err(err);
8228 			sanitize_pin_path(buf);
8229 			pin_path = buf;
8230 		} else if (!map->pin_path) {
8231 			continue;
8232 		}
8233 
8234 		err = bpf_map__unpin(map, pin_path);
8235 		if (err)
8236 			return libbpf_err(err);
8237 	}
8238 
8239 	return 0;
8240 }
8241 
8242 int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
8243 {
8244 	struct bpf_program *prog;
8245 	char buf[PATH_MAX];
8246 	int err;
8247 
8248 	if (!obj)
8249 		return libbpf_err(-ENOENT);
8250 
8251 	if (!obj->loaded) {
8252 		pr_warn("object not yet loaded; load it first\n");
8253 		return libbpf_err(-ENOENT);
8254 	}
8255 
8256 	bpf_object__for_each_program(prog, obj) {
8257 		err = pathname_concat(buf, sizeof(buf), path, prog->name);
8258 		if (err)
8259 			goto err_unpin_programs;
8260 
8261 		err = bpf_program__pin(prog, buf);
8262 		if (err)
8263 			goto err_unpin_programs;
8264 	}
8265 
8266 	return 0;
8267 
8268 err_unpin_programs:
8269 	while ((prog = bpf_object__prev_program(obj, prog))) {
8270 		if (pathname_concat(buf, sizeof(buf), path, prog->name))
8271 			continue;
8272 
8273 		bpf_program__unpin(prog, buf);
8274 	}
8275 
8276 	return libbpf_err(err);
8277 }
8278 
8279 int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
8280 {
8281 	struct bpf_program *prog;
8282 	int err;
8283 
8284 	if (!obj)
8285 		return libbpf_err(-ENOENT);
8286 
8287 	bpf_object__for_each_program(prog, obj) {
8288 		char buf[PATH_MAX];
8289 
8290 		err = pathname_concat(buf, sizeof(buf), path, prog->name);
8291 		if (err)
8292 			return libbpf_err(err);
8293 
8294 		err = bpf_program__unpin(prog, buf);
8295 		if (err)
8296 			return libbpf_err(err);
8297 	}
8298 
8299 	return 0;
8300 }
8301 
8302 int bpf_object__pin(struct bpf_object *obj, const char *path)
8303 {
8304 	int err;
8305 
8306 	err = bpf_object__pin_maps(obj, path);
8307 	if (err)
8308 		return libbpf_err(err);
8309 
8310 	err = bpf_object__pin_programs(obj, path);
8311 	if (err) {
8312 		bpf_object__unpin_maps(obj, path);
8313 		return libbpf_err(err);
8314 	}
8315 
8316 	return 0;
8317 }
8318 
8319 static void bpf_map__destroy(struct bpf_map *map)
8320 {
8321 	if (map->inner_map) {
8322 		bpf_map__destroy(map->inner_map);
8323 		zfree(&map->inner_map);
8324 	}
8325 
8326 	zfree(&map->init_slots);
8327 	map->init_slots_sz = 0;
8328 
8329 	if (map->mmaped) {
8330 		size_t mmap_sz;
8331 
8332 		mmap_sz = bpf_map_mmap_sz(map->def.value_size, map->def.max_entries);
8333 		munmap(map->mmaped, mmap_sz);
8334 		map->mmaped = NULL;
8335 	}
8336 
8337 	if (map->st_ops) {
8338 		zfree(&map->st_ops->data);
8339 		zfree(&map->st_ops->progs);
8340 		zfree(&map->st_ops->kern_func_off);
8341 		zfree(&map->st_ops);
8342 	}
8343 
8344 	zfree(&map->name);
8345 	zfree(&map->real_name);
8346 	zfree(&map->pin_path);
8347 
8348 	if (map->fd >= 0)
8349 		zclose(map->fd);
8350 }
8351 
8352 void bpf_object__close(struct bpf_object *obj)
8353 {
8354 	size_t i;
8355 
8356 	if (IS_ERR_OR_NULL(obj))
8357 		return;
8358 
8359 	usdt_manager_free(obj->usdt_man);
8360 	obj->usdt_man = NULL;
8361 
8362 	bpf_gen__free(obj->gen_loader);
8363 	bpf_object__elf_finish(obj);
8364 	bpf_object_unload(obj);
8365 	btf__free(obj->btf);
8366 	btf_ext__free(obj->btf_ext);
8367 
8368 	for (i = 0; i < obj->nr_maps; i++)
8369 		bpf_map__destroy(&obj->maps[i]);
8370 
8371 	zfree(&obj->btf_custom_path);
8372 	zfree(&obj->kconfig);
8373 	zfree(&obj->externs);
8374 	obj->nr_extern = 0;
8375 
8376 	zfree(&obj->maps);
8377 	obj->nr_maps = 0;
8378 
8379 	if (obj->programs && obj->nr_programs) {
8380 		for (i = 0; i < obj->nr_programs; i++)
8381 			bpf_program__exit(&obj->programs[i]);
8382 	}
8383 	zfree(&obj->programs);
8384 
8385 	free(obj);
8386 }
8387 
8388 const char *bpf_object__name(const struct bpf_object *obj)
8389 {
8390 	return obj ? obj->name : libbpf_err_ptr(-EINVAL);
8391 }
8392 
8393 unsigned int bpf_object__kversion(const struct bpf_object *obj)
8394 {
8395 	return obj ? obj->kern_version : 0;
8396 }
8397 
8398 struct btf *bpf_object__btf(const struct bpf_object *obj)
8399 {
8400 	return obj ? obj->btf : NULL;
8401 }
8402 
8403 int bpf_object__btf_fd(const struct bpf_object *obj)
8404 {
8405 	return obj->btf ? btf__fd(obj->btf) : -1;
8406 }
8407 
8408 int bpf_object__set_kversion(struct bpf_object *obj, __u32 kern_version)
8409 {
8410 	if (obj->loaded)
8411 		return libbpf_err(-EINVAL);
8412 
8413 	obj->kern_version = kern_version;
8414 
8415 	return 0;
8416 }
8417 
8418 int bpf_object__gen_loader(struct bpf_object *obj, struct gen_loader_opts *opts)
8419 {
8420 	struct bpf_gen *gen;
8421 
8422 	if (!opts)
8423 		return -EFAULT;
8424 	if (!OPTS_VALID(opts, gen_loader_opts))
8425 		return -EINVAL;
8426 	gen = calloc(sizeof(*gen), 1);
8427 	if (!gen)
8428 		return -ENOMEM;
8429 	gen->opts = opts;
8430 	obj->gen_loader = gen;
8431 	return 0;
8432 }
8433 
8434 static struct bpf_program *
8435 __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
8436 		    bool forward)
8437 {
8438 	size_t nr_programs = obj->nr_programs;
8439 	ssize_t idx;
8440 
8441 	if (!nr_programs)
8442 		return NULL;
8443 
8444 	if (!p)
8445 		/* Iter from the beginning */
8446 		return forward ? &obj->programs[0] :
8447 			&obj->programs[nr_programs - 1];
8448 
8449 	if (p->obj != obj) {
8450 		pr_warn("error: program handler doesn't match object\n");
8451 		return errno = EINVAL, NULL;
8452 	}
8453 
8454 	idx = (p - obj->programs) + (forward ? 1 : -1);
8455 	if (idx >= obj->nr_programs || idx < 0)
8456 		return NULL;
8457 	return &obj->programs[idx];
8458 }
8459 
8460 struct bpf_program *
8461 bpf_object__next_program(const struct bpf_object *obj, struct bpf_program *prev)
8462 {
8463 	struct bpf_program *prog = prev;
8464 
8465 	do {
8466 		prog = __bpf_program__iter(prog, obj, true);
8467 	} while (prog && prog_is_subprog(obj, prog));
8468 
8469 	return prog;
8470 }
8471 
8472 struct bpf_program *
8473 bpf_object__prev_program(const struct bpf_object *obj, struct bpf_program *next)
8474 {
8475 	struct bpf_program *prog = next;
8476 
8477 	do {
8478 		prog = __bpf_program__iter(prog, obj, false);
8479 	} while (prog && prog_is_subprog(obj, prog));
8480 
8481 	return prog;
8482 }
8483 
8484 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
8485 {
8486 	prog->prog_ifindex = ifindex;
8487 }
8488 
8489 const char *bpf_program__name(const struct bpf_program *prog)
8490 {
8491 	return prog->name;
8492 }
8493 
8494 const char *bpf_program__section_name(const struct bpf_program *prog)
8495 {
8496 	return prog->sec_name;
8497 }
8498 
8499 bool bpf_program__autoload(const struct bpf_program *prog)
8500 {
8501 	return prog->autoload;
8502 }
8503 
8504 int bpf_program__set_autoload(struct bpf_program *prog, bool autoload)
8505 {
8506 	if (prog->obj->loaded)
8507 		return libbpf_err(-EINVAL);
8508 
8509 	prog->autoload = autoload;
8510 	return 0;
8511 }
8512 
8513 bool bpf_program__autoattach(const struct bpf_program *prog)
8514 {
8515 	return prog->autoattach;
8516 }
8517 
8518 void bpf_program__set_autoattach(struct bpf_program *prog, bool autoattach)
8519 {
8520 	prog->autoattach = autoattach;
8521 }
8522 
8523 const struct bpf_insn *bpf_program__insns(const struct bpf_program *prog)
8524 {
8525 	return prog->insns;
8526 }
8527 
8528 size_t bpf_program__insn_cnt(const struct bpf_program *prog)
8529 {
8530 	return prog->insns_cnt;
8531 }
8532 
8533 int bpf_program__set_insns(struct bpf_program *prog,
8534 			   struct bpf_insn *new_insns, size_t new_insn_cnt)
8535 {
8536 	struct bpf_insn *insns;
8537 
8538 	if (prog->obj->loaded)
8539 		return -EBUSY;
8540 
8541 	insns = libbpf_reallocarray(prog->insns, new_insn_cnt, sizeof(*insns));
8542 	/* NULL is a valid return from reallocarray if the new count is zero */
8543 	if (!insns && new_insn_cnt) {
8544 		pr_warn("prog '%s': failed to realloc prog code\n", prog->name);
8545 		return -ENOMEM;
8546 	}
8547 	memcpy(insns, new_insns, new_insn_cnt * sizeof(*insns));
8548 
8549 	prog->insns = insns;
8550 	prog->insns_cnt = new_insn_cnt;
8551 	return 0;
8552 }
8553 
8554 int bpf_program__fd(const struct bpf_program *prog)
8555 {
8556 	if (!prog)
8557 		return libbpf_err(-EINVAL);
8558 
8559 	if (prog->fd < 0)
8560 		return libbpf_err(-ENOENT);
8561 
8562 	return prog->fd;
8563 }
8564 
8565 __alias(bpf_program__type)
8566 enum bpf_prog_type bpf_program__get_type(const struct bpf_program *prog);
8567 
8568 enum bpf_prog_type bpf_program__type(const struct bpf_program *prog)
8569 {
8570 	return prog->type;
8571 }
8572 
8573 static size_t custom_sec_def_cnt;
8574 static struct bpf_sec_def *custom_sec_defs;
8575 static struct bpf_sec_def custom_fallback_def;
8576 static bool has_custom_fallback_def;
8577 static int last_custom_sec_def_handler_id;
8578 
8579 int bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
8580 {
8581 	if (prog->obj->loaded)
8582 		return libbpf_err(-EBUSY);
8583 
8584 	/* if type is not changed, do nothing */
8585 	if (prog->type == type)
8586 		return 0;
8587 
8588 	prog->type = type;
8589 
8590 	/* If a program type was changed, we need to reset associated SEC()
8591 	 * handler, as it will be invalid now. The only exception is a generic
8592 	 * fallback handler, which by definition is program type-agnostic and
8593 	 * is a catch-all custom handler, optionally set by the application,
8594 	 * so should be able to handle any type of BPF program.
8595 	 */
8596 	if (prog->sec_def != &custom_fallback_def)
8597 		prog->sec_def = NULL;
8598 	return 0;
8599 }
8600 
8601 __alias(bpf_program__expected_attach_type)
8602 enum bpf_attach_type bpf_program__get_expected_attach_type(const struct bpf_program *prog);
8603 
8604 enum bpf_attach_type bpf_program__expected_attach_type(const struct bpf_program *prog)
8605 {
8606 	return prog->expected_attach_type;
8607 }
8608 
8609 int bpf_program__set_expected_attach_type(struct bpf_program *prog,
8610 					   enum bpf_attach_type type)
8611 {
8612 	if (prog->obj->loaded)
8613 		return libbpf_err(-EBUSY);
8614 
8615 	prog->expected_attach_type = type;
8616 	return 0;
8617 }
8618 
8619 __u32 bpf_program__flags(const struct bpf_program *prog)
8620 {
8621 	return prog->prog_flags;
8622 }
8623 
8624 int bpf_program__set_flags(struct bpf_program *prog, __u32 flags)
8625 {
8626 	if (prog->obj->loaded)
8627 		return libbpf_err(-EBUSY);
8628 
8629 	prog->prog_flags = flags;
8630 	return 0;
8631 }
8632 
8633 __u32 bpf_program__log_level(const struct bpf_program *prog)
8634 {
8635 	return prog->log_level;
8636 }
8637 
8638 int bpf_program__set_log_level(struct bpf_program *prog, __u32 log_level)
8639 {
8640 	if (prog->obj->loaded)
8641 		return libbpf_err(-EBUSY);
8642 
8643 	prog->log_level = log_level;
8644 	return 0;
8645 }
8646 
8647 const char *bpf_program__log_buf(const struct bpf_program *prog, size_t *log_size)
8648 {
8649 	*log_size = prog->log_size;
8650 	return prog->log_buf;
8651 }
8652 
8653 int bpf_program__set_log_buf(struct bpf_program *prog, char *log_buf, size_t log_size)
8654 {
8655 	if (log_size && !log_buf)
8656 		return -EINVAL;
8657 	if (prog->log_size > UINT_MAX)
8658 		return -EINVAL;
8659 	if (prog->obj->loaded)
8660 		return -EBUSY;
8661 
8662 	prog->log_buf = log_buf;
8663 	prog->log_size = log_size;
8664 	return 0;
8665 }
8666 
8667 #define SEC_DEF(sec_pfx, ptype, atype, flags, ...) {			    \
8668 	.sec = (char *)sec_pfx,						    \
8669 	.prog_type = BPF_PROG_TYPE_##ptype,				    \
8670 	.expected_attach_type = atype,					    \
8671 	.cookie = (long)(flags),					    \
8672 	.prog_prepare_load_fn = libbpf_prepare_prog_load,		    \
8673 	__VA_ARGS__							    \
8674 }
8675 
8676 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8677 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8678 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8679 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8680 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8681 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8682 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8683 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8684 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8685 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8686 
8687 static const struct bpf_sec_def section_defs[] = {
8688 	SEC_DEF("socket",		SOCKET_FILTER, 0, SEC_NONE),
8689 	SEC_DEF("sk_reuseport/migrate",	SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT_OR_MIGRATE, SEC_ATTACHABLE),
8690 	SEC_DEF("sk_reuseport",		SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT, SEC_ATTACHABLE),
8691 	SEC_DEF("kprobe+",		KPROBE,	0, SEC_NONE, attach_kprobe),
8692 	SEC_DEF("uprobe+",		KPROBE,	0, SEC_NONE, attach_uprobe),
8693 	SEC_DEF("uprobe.s+",		KPROBE,	0, SEC_SLEEPABLE, attach_uprobe),
8694 	SEC_DEF("kretprobe+",		KPROBE, 0, SEC_NONE, attach_kprobe),
8695 	SEC_DEF("uretprobe+",		KPROBE, 0, SEC_NONE, attach_uprobe),
8696 	SEC_DEF("uretprobe.s+",		KPROBE, 0, SEC_SLEEPABLE, attach_uprobe),
8697 	SEC_DEF("kprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
8698 	SEC_DEF("kretprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
8699 	SEC_DEF("ksyscall+",		KPROBE,	0, SEC_NONE, attach_ksyscall),
8700 	SEC_DEF("kretsyscall+",		KPROBE, 0, SEC_NONE, attach_ksyscall),
8701 	SEC_DEF("usdt+",		KPROBE,	0, SEC_NONE, attach_usdt),
8702 	SEC_DEF("tc/ingress",		SCHED_CLS, BPF_TCX_INGRESS, SEC_NONE), /* alias for tcx */
8703 	SEC_DEF("tc/egress",		SCHED_CLS, BPF_TCX_EGRESS, SEC_NONE),  /* alias for tcx */
8704 	SEC_DEF("tcx/ingress",		SCHED_CLS, BPF_TCX_INGRESS, SEC_NONE),
8705 	SEC_DEF("tcx/egress",		SCHED_CLS, BPF_TCX_EGRESS, SEC_NONE),
8706 	SEC_DEF("tc",			SCHED_CLS, 0, SEC_NONE), /* deprecated / legacy, use tcx */
8707 	SEC_DEF("classifier",		SCHED_CLS, 0, SEC_NONE), /* deprecated / legacy, use tcx */
8708 	SEC_DEF("action",		SCHED_ACT, 0, SEC_NONE), /* deprecated / legacy, use tcx */
8709 	SEC_DEF("tracepoint+",		TRACEPOINT, 0, SEC_NONE, attach_tp),
8710 	SEC_DEF("tp+",			TRACEPOINT, 0, SEC_NONE, attach_tp),
8711 	SEC_DEF("raw_tracepoint+",	RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
8712 	SEC_DEF("raw_tp+",		RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
8713 	SEC_DEF("raw_tracepoint.w+",	RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
8714 	SEC_DEF("raw_tp.w+",		RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
8715 	SEC_DEF("tp_btf+",		TRACING, BPF_TRACE_RAW_TP, SEC_ATTACH_BTF, attach_trace),
8716 	SEC_DEF("fentry+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF, attach_trace),
8717 	SEC_DEF("fmod_ret+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF, attach_trace),
8718 	SEC_DEF("fexit+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF, attach_trace),
8719 	SEC_DEF("fentry.s+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8720 	SEC_DEF("fmod_ret.s+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8721 	SEC_DEF("fexit.s+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8722 	SEC_DEF("freplace+",		EXT, 0, SEC_ATTACH_BTF, attach_trace),
8723 	SEC_DEF("lsm+",			LSM, BPF_LSM_MAC, SEC_ATTACH_BTF, attach_lsm),
8724 	SEC_DEF("lsm.s+",		LSM, BPF_LSM_MAC, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_lsm),
8725 	SEC_DEF("lsm_cgroup+",		LSM, BPF_LSM_CGROUP, SEC_ATTACH_BTF),
8726 	SEC_DEF("iter+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF, attach_iter),
8727 	SEC_DEF("iter.s+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_iter),
8728 	SEC_DEF("syscall",		SYSCALL, 0, SEC_SLEEPABLE),
8729 	SEC_DEF("xdp.frags/devmap",	XDP, BPF_XDP_DEVMAP, SEC_XDP_FRAGS),
8730 	SEC_DEF("xdp/devmap",		XDP, BPF_XDP_DEVMAP, SEC_ATTACHABLE),
8731 	SEC_DEF("xdp.frags/cpumap",	XDP, BPF_XDP_CPUMAP, SEC_XDP_FRAGS),
8732 	SEC_DEF("xdp/cpumap",		XDP, BPF_XDP_CPUMAP, SEC_ATTACHABLE),
8733 	SEC_DEF("xdp.frags",		XDP, BPF_XDP, SEC_XDP_FRAGS),
8734 	SEC_DEF("xdp",			XDP, BPF_XDP, SEC_ATTACHABLE_OPT),
8735 	SEC_DEF("perf_event",		PERF_EVENT, 0, SEC_NONE),
8736 	SEC_DEF("lwt_in",		LWT_IN, 0, SEC_NONE),
8737 	SEC_DEF("lwt_out",		LWT_OUT, 0, SEC_NONE),
8738 	SEC_DEF("lwt_xmit",		LWT_XMIT, 0, SEC_NONE),
8739 	SEC_DEF("lwt_seg6local",	LWT_SEG6LOCAL, 0, SEC_NONE),
8740 	SEC_DEF("sockops",		SOCK_OPS, BPF_CGROUP_SOCK_OPS, SEC_ATTACHABLE_OPT),
8741 	SEC_DEF("sk_skb/stream_parser",	SK_SKB, BPF_SK_SKB_STREAM_PARSER, SEC_ATTACHABLE_OPT),
8742 	SEC_DEF("sk_skb/stream_verdict",SK_SKB, BPF_SK_SKB_STREAM_VERDICT, SEC_ATTACHABLE_OPT),
8743 	SEC_DEF("sk_skb",		SK_SKB, 0, SEC_NONE),
8744 	SEC_DEF("sk_msg",		SK_MSG, BPF_SK_MSG_VERDICT, SEC_ATTACHABLE_OPT),
8745 	SEC_DEF("lirc_mode2",		LIRC_MODE2, BPF_LIRC_MODE2, SEC_ATTACHABLE_OPT),
8746 	SEC_DEF("flow_dissector",	FLOW_DISSECTOR, BPF_FLOW_DISSECTOR, SEC_ATTACHABLE_OPT),
8747 	SEC_DEF("cgroup_skb/ingress",	CGROUP_SKB, BPF_CGROUP_INET_INGRESS, SEC_ATTACHABLE_OPT),
8748 	SEC_DEF("cgroup_skb/egress",	CGROUP_SKB, BPF_CGROUP_INET_EGRESS, SEC_ATTACHABLE_OPT),
8749 	SEC_DEF("cgroup/skb",		CGROUP_SKB, 0, SEC_NONE),
8750 	SEC_DEF("cgroup/sock_create",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE),
8751 	SEC_DEF("cgroup/sock_release",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_RELEASE, SEC_ATTACHABLE),
8752 	SEC_DEF("cgroup/sock",		CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE_OPT),
8753 	SEC_DEF("cgroup/post_bind4",	CGROUP_SOCK, BPF_CGROUP_INET4_POST_BIND, SEC_ATTACHABLE),
8754 	SEC_DEF("cgroup/post_bind6",	CGROUP_SOCK, BPF_CGROUP_INET6_POST_BIND, SEC_ATTACHABLE),
8755 	SEC_DEF("cgroup/bind4",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND, SEC_ATTACHABLE),
8756 	SEC_DEF("cgroup/bind6",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND, SEC_ATTACHABLE),
8757 	SEC_DEF("cgroup/connect4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT, SEC_ATTACHABLE),
8758 	SEC_DEF("cgroup/connect6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT, SEC_ATTACHABLE),
8759 	SEC_DEF("cgroup/sendmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG, SEC_ATTACHABLE),
8760 	SEC_DEF("cgroup/sendmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG, SEC_ATTACHABLE),
8761 	SEC_DEF("cgroup/recvmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_RECVMSG, SEC_ATTACHABLE),
8762 	SEC_DEF("cgroup/recvmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_RECVMSG, SEC_ATTACHABLE),
8763 	SEC_DEF("cgroup/getpeername4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETPEERNAME, SEC_ATTACHABLE),
8764 	SEC_DEF("cgroup/getpeername6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETPEERNAME, SEC_ATTACHABLE),
8765 	SEC_DEF("cgroup/getsockname4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETSOCKNAME, SEC_ATTACHABLE),
8766 	SEC_DEF("cgroup/getsockname6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETSOCKNAME, SEC_ATTACHABLE),
8767 	SEC_DEF("cgroup/sysctl",	CGROUP_SYSCTL, BPF_CGROUP_SYSCTL, SEC_ATTACHABLE),
8768 	SEC_DEF("cgroup/getsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_GETSOCKOPT, SEC_ATTACHABLE),
8769 	SEC_DEF("cgroup/setsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_SETSOCKOPT, SEC_ATTACHABLE),
8770 	SEC_DEF("cgroup/dev",		CGROUP_DEVICE, BPF_CGROUP_DEVICE, SEC_ATTACHABLE_OPT),
8771 	SEC_DEF("struct_ops+",		STRUCT_OPS, 0, SEC_NONE),
8772 	SEC_DEF("struct_ops.s+",	STRUCT_OPS, 0, SEC_SLEEPABLE),
8773 	SEC_DEF("sk_lookup",		SK_LOOKUP, BPF_SK_LOOKUP, SEC_ATTACHABLE),
8774 	SEC_DEF("netfilter",		NETFILTER, BPF_NETFILTER, SEC_NONE),
8775 };
8776 
8777 int libbpf_register_prog_handler(const char *sec,
8778 				 enum bpf_prog_type prog_type,
8779 				 enum bpf_attach_type exp_attach_type,
8780 				 const struct libbpf_prog_handler_opts *opts)
8781 {
8782 	struct bpf_sec_def *sec_def;
8783 
8784 	if (!OPTS_VALID(opts, libbpf_prog_handler_opts))
8785 		return libbpf_err(-EINVAL);
8786 
8787 	if (last_custom_sec_def_handler_id == INT_MAX) /* prevent overflow */
8788 		return libbpf_err(-E2BIG);
8789 
8790 	if (sec) {
8791 		sec_def = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt + 1,
8792 					      sizeof(*sec_def));
8793 		if (!sec_def)
8794 			return libbpf_err(-ENOMEM);
8795 
8796 		custom_sec_defs = sec_def;
8797 		sec_def = &custom_sec_defs[custom_sec_def_cnt];
8798 	} else {
8799 		if (has_custom_fallback_def)
8800 			return libbpf_err(-EBUSY);
8801 
8802 		sec_def = &custom_fallback_def;
8803 	}
8804 
8805 	sec_def->sec = sec ? strdup(sec) : NULL;
8806 	if (sec && !sec_def->sec)
8807 		return libbpf_err(-ENOMEM);
8808 
8809 	sec_def->prog_type = prog_type;
8810 	sec_def->expected_attach_type = exp_attach_type;
8811 	sec_def->cookie = OPTS_GET(opts, cookie, 0);
8812 
8813 	sec_def->prog_setup_fn = OPTS_GET(opts, prog_setup_fn, NULL);
8814 	sec_def->prog_prepare_load_fn = OPTS_GET(opts, prog_prepare_load_fn, NULL);
8815 	sec_def->prog_attach_fn = OPTS_GET(opts, prog_attach_fn, NULL);
8816 
8817 	sec_def->handler_id = ++last_custom_sec_def_handler_id;
8818 
8819 	if (sec)
8820 		custom_sec_def_cnt++;
8821 	else
8822 		has_custom_fallback_def = true;
8823 
8824 	return sec_def->handler_id;
8825 }
8826 
8827 int libbpf_unregister_prog_handler(int handler_id)
8828 {
8829 	struct bpf_sec_def *sec_defs;
8830 	int i;
8831 
8832 	if (handler_id <= 0)
8833 		return libbpf_err(-EINVAL);
8834 
8835 	if (has_custom_fallback_def && custom_fallback_def.handler_id == handler_id) {
8836 		memset(&custom_fallback_def, 0, sizeof(custom_fallback_def));
8837 		has_custom_fallback_def = false;
8838 		return 0;
8839 	}
8840 
8841 	for (i = 0; i < custom_sec_def_cnt; i++) {
8842 		if (custom_sec_defs[i].handler_id == handler_id)
8843 			break;
8844 	}
8845 
8846 	if (i == custom_sec_def_cnt)
8847 		return libbpf_err(-ENOENT);
8848 
8849 	free(custom_sec_defs[i].sec);
8850 	for (i = i + 1; i < custom_sec_def_cnt; i++)
8851 		custom_sec_defs[i - 1] = custom_sec_defs[i];
8852 	custom_sec_def_cnt--;
8853 
8854 	/* try to shrink the array, but it's ok if we couldn't */
8855 	sec_defs = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt, sizeof(*sec_defs));
8856 	/* if new count is zero, reallocarray can return a valid NULL result;
8857 	 * in this case the previous pointer will be freed, so we *have to*
8858 	 * reassign old pointer to the new value (even if it's NULL)
8859 	 */
8860 	if (sec_defs || custom_sec_def_cnt == 0)
8861 		custom_sec_defs = sec_defs;
8862 
8863 	return 0;
8864 }
8865 
8866 static bool sec_def_matches(const struct bpf_sec_def *sec_def, const char *sec_name)
8867 {
8868 	size_t len = strlen(sec_def->sec);
8869 
8870 	/* "type/" always has to have proper SEC("type/extras") form */
8871 	if (sec_def->sec[len - 1] == '/') {
8872 		if (str_has_pfx(sec_name, sec_def->sec))
8873 			return true;
8874 		return false;
8875 	}
8876 
8877 	/* "type+" means it can be either exact SEC("type") or
8878 	 * well-formed SEC("type/extras") with proper '/' separator
8879 	 */
8880 	if (sec_def->sec[len - 1] == '+') {
8881 		len--;
8882 		/* not even a prefix */
8883 		if (strncmp(sec_name, sec_def->sec, len) != 0)
8884 			return false;
8885 		/* exact match or has '/' separator */
8886 		if (sec_name[len] == '\0' || sec_name[len] == '/')
8887 			return true;
8888 		return false;
8889 	}
8890 
8891 	return strcmp(sec_name, sec_def->sec) == 0;
8892 }
8893 
8894 static const struct bpf_sec_def *find_sec_def(const char *sec_name)
8895 {
8896 	const struct bpf_sec_def *sec_def;
8897 	int i, n;
8898 
8899 	n = custom_sec_def_cnt;
8900 	for (i = 0; i < n; i++) {
8901 		sec_def = &custom_sec_defs[i];
8902 		if (sec_def_matches(sec_def, sec_name))
8903 			return sec_def;
8904 	}
8905 
8906 	n = ARRAY_SIZE(section_defs);
8907 	for (i = 0; i < n; i++) {
8908 		sec_def = &section_defs[i];
8909 		if (sec_def_matches(sec_def, sec_name))
8910 			return sec_def;
8911 	}
8912 
8913 	if (has_custom_fallback_def)
8914 		return &custom_fallback_def;
8915 
8916 	return NULL;
8917 }
8918 
8919 #define MAX_TYPE_NAME_SIZE 32
8920 
8921 static char *libbpf_get_type_names(bool attach_type)
8922 {
8923 	int i, len = ARRAY_SIZE(section_defs) * MAX_TYPE_NAME_SIZE;
8924 	char *buf;
8925 
8926 	buf = malloc(len);
8927 	if (!buf)
8928 		return NULL;
8929 
8930 	buf[0] = '\0';
8931 	/* Forge string buf with all available names */
8932 	for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
8933 		const struct bpf_sec_def *sec_def = &section_defs[i];
8934 
8935 		if (attach_type) {
8936 			if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
8937 				continue;
8938 
8939 			if (!(sec_def->cookie & SEC_ATTACHABLE))
8940 				continue;
8941 		}
8942 
8943 		if (strlen(buf) + strlen(section_defs[i].sec) + 2 > len) {
8944 			free(buf);
8945 			return NULL;
8946 		}
8947 		strcat(buf, " ");
8948 		strcat(buf, section_defs[i].sec);
8949 	}
8950 
8951 	return buf;
8952 }
8953 
8954 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
8955 			     enum bpf_attach_type *expected_attach_type)
8956 {
8957 	const struct bpf_sec_def *sec_def;
8958 	char *type_names;
8959 
8960 	if (!name)
8961 		return libbpf_err(-EINVAL);
8962 
8963 	sec_def = find_sec_def(name);
8964 	if (sec_def) {
8965 		*prog_type = sec_def->prog_type;
8966 		*expected_attach_type = sec_def->expected_attach_type;
8967 		return 0;
8968 	}
8969 
8970 	pr_debug("failed to guess program type from ELF section '%s'\n", name);
8971 	type_names = libbpf_get_type_names(false);
8972 	if (type_names != NULL) {
8973 		pr_debug("supported section(type) names are:%s\n", type_names);
8974 		free(type_names);
8975 	}
8976 
8977 	return libbpf_err(-ESRCH);
8978 }
8979 
8980 const char *libbpf_bpf_attach_type_str(enum bpf_attach_type t)
8981 {
8982 	if (t < 0 || t >= ARRAY_SIZE(attach_type_name))
8983 		return NULL;
8984 
8985 	return attach_type_name[t];
8986 }
8987 
8988 const char *libbpf_bpf_link_type_str(enum bpf_link_type t)
8989 {
8990 	if (t < 0 || t >= ARRAY_SIZE(link_type_name))
8991 		return NULL;
8992 
8993 	return link_type_name[t];
8994 }
8995 
8996 const char *libbpf_bpf_map_type_str(enum bpf_map_type t)
8997 {
8998 	if (t < 0 || t >= ARRAY_SIZE(map_type_name))
8999 		return NULL;
9000 
9001 	return map_type_name[t];
9002 }
9003 
9004 const char *libbpf_bpf_prog_type_str(enum bpf_prog_type t)
9005 {
9006 	if (t < 0 || t >= ARRAY_SIZE(prog_type_name))
9007 		return NULL;
9008 
9009 	return prog_type_name[t];
9010 }
9011 
9012 static struct bpf_map *find_struct_ops_map_by_offset(struct bpf_object *obj,
9013 						     int sec_idx,
9014 						     size_t offset)
9015 {
9016 	struct bpf_map *map;
9017 	size_t i;
9018 
9019 	for (i = 0; i < obj->nr_maps; i++) {
9020 		map = &obj->maps[i];
9021 		if (!bpf_map__is_struct_ops(map))
9022 			continue;
9023 		if (map->sec_idx == sec_idx &&
9024 		    map->sec_offset <= offset &&
9025 		    offset - map->sec_offset < map->def.value_size)
9026 			return map;
9027 	}
9028 
9029 	return NULL;
9030 }
9031 
9032 /* Collect the reloc from ELF and populate the st_ops->progs[] */
9033 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
9034 					    Elf64_Shdr *shdr, Elf_Data *data)
9035 {
9036 	const struct btf_member *member;
9037 	struct bpf_struct_ops *st_ops;
9038 	struct bpf_program *prog;
9039 	unsigned int shdr_idx;
9040 	const struct btf *btf;
9041 	struct bpf_map *map;
9042 	unsigned int moff, insn_idx;
9043 	const char *name;
9044 	__u32 member_idx;
9045 	Elf64_Sym *sym;
9046 	Elf64_Rel *rel;
9047 	int i, nrels;
9048 
9049 	btf = obj->btf;
9050 	nrels = shdr->sh_size / shdr->sh_entsize;
9051 	for (i = 0; i < nrels; i++) {
9052 		rel = elf_rel_by_idx(data, i);
9053 		if (!rel) {
9054 			pr_warn("struct_ops reloc: failed to get %d reloc\n", i);
9055 			return -LIBBPF_ERRNO__FORMAT;
9056 		}
9057 
9058 		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
9059 		if (!sym) {
9060 			pr_warn("struct_ops reloc: symbol %zx not found\n",
9061 				(size_t)ELF64_R_SYM(rel->r_info));
9062 			return -LIBBPF_ERRNO__FORMAT;
9063 		}
9064 
9065 		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
9066 		map = find_struct_ops_map_by_offset(obj, shdr->sh_info, rel->r_offset);
9067 		if (!map) {
9068 			pr_warn("struct_ops reloc: cannot find map at rel->r_offset %zu\n",
9069 				(size_t)rel->r_offset);
9070 			return -EINVAL;
9071 		}
9072 
9073 		moff = rel->r_offset - map->sec_offset;
9074 		shdr_idx = sym->st_shndx;
9075 		st_ops = map->st_ops;
9076 		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",
9077 			 map->name,
9078 			 (long long)(rel->r_info >> 32),
9079 			 (long long)sym->st_value,
9080 			 shdr_idx, (size_t)rel->r_offset,
9081 			 map->sec_offset, sym->st_name, name);
9082 
9083 		if (shdr_idx >= SHN_LORESERVE) {
9084 			pr_warn("struct_ops reloc %s: rel->r_offset %zu shdr_idx %u unsupported non-static function\n",
9085 				map->name, (size_t)rel->r_offset, shdr_idx);
9086 			return -LIBBPF_ERRNO__RELOC;
9087 		}
9088 		if (sym->st_value % BPF_INSN_SZ) {
9089 			pr_warn("struct_ops reloc %s: invalid target program offset %llu\n",
9090 				map->name, (unsigned long long)sym->st_value);
9091 			return -LIBBPF_ERRNO__FORMAT;
9092 		}
9093 		insn_idx = sym->st_value / BPF_INSN_SZ;
9094 
9095 		member = find_member_by_offset(st_ops->type, moff * 8);
9096 		if (!member) {
9097 			pr_warn("struct_ops reloc %s: cannot find member at moff %u\n",
9098 				map->name, moff);
9099 			return -EINVAL;
9100 		}
9101 		member_idx = member - btf_members(st_ops->type);
9102 		name = btf__name_by_offset(btf, member->name_off);
9103 
9104 		if (!resolve_func_ptr(btf, member->type, NULL)) {
9105 			pr_warn("struct_ops reloc %s: cannot relocate non func ptr %s\n",
9106 				map->name, name);
9107 			return -EINVAL;
9108 		}
9109 
9110 		prog = find_prog_by_sec_insn(obj, shdr_idx, insn_idx);
9111 		if (!prog) {
9112 			pr_warn("struct_ops reloc %s: cannot find prog at shdr_idx %u to relocate func ptr %s\n",
9113 				map->name, shdr_idx, name);
9114 			return -EINVAL;
9115 		}
9116 
9117 		/* prevent the use of BPF prog with invalid type */
9118 		if (prog->type != BPF_PROG_TYPE_STRUCT_OPS) {
9119 			pr_warn("struct_ops reloc %s: prog %s is not struct_ops BPF program\n",
9120 				map->name, prog->name);
9121 			return -EINVAL;
9122 		}
9123 
9124 		/* if we haven't yet processed this BPF program, record proper
9125 		 * attach_btf_id and member_idx
9126 		 */
9127 		if (!prog->attach_btf_id) {
9128 			prog->attach_btf_id = st_ops->type_id;
9129 			prog->expected_attach_type = member_idx;
9130 		}
9131 
9132 		/* struct_ops BPF prog can be re-used between multiple
9133 		 * .struct_ops & .struct_ops.link as long as it's the
9134 		 * same struct_ops struct definition and the same
9135 		 * function pointer field
9136 		 */
9137 		if (prog->attach_btf_id != st_ops->type_id ||
9138 		    prog->expected_attach_type != member_idx) {
9139 			pr_warn("struct_ops reloc %s: cannot use prog %s in sec %s with type %u attach_btf_id %u expected_attach_type %u for func ptr %s\n",
9140 				map->name, prog->name, prog->sec_name, prog->type,
9141 				prog->attach_btf_id, prog->expected_attach_type, name);
9142 			return -EINVAL;
9143 		}
9144 
9145 		st_ops->progs[member_idx] = prog;
9146 	}
9147 
9148 	return 0;
9149 }
9150 
9151 #define BTF_TRACE_PREFIX "btf_trace_"
9152 #define BTF_LSM_PREFIX "bpf_lsm_"
9153 #define BTF_ITER_PREFIX "bpf_iter_"
9154 #define BTF_MAX_NAME_SIZE 128
9155 
9156 void btf_get_kernel_prefix_kind(enum bpf_attach_type attach_type,
9157 				const char **prefix, int *kind)
9158 {
9159 	switch (attach_type) {
9160 	case BPF_TRACE_RAW_TP:
9161 		*prefix = BTF_TRACE_PREFIX;
9162 		*kind = BTF_KIND_TYPEDEF;
9163 		break;
9164 	case BPF_LSM_MAC:
9165 	case BPF_LSM_CGROUP:
9166 		*prefix = BTF_LSM_PREFIX;
9167 		*kind = BTF_KIND_FUNC;
9168 		break;
9169 	case BPF_TRACE_ITER:
9170 		*prefix = BTF_ITER_PREFIX;
9171 		*kind = BTF_KIND_FUNC;
9172 		break;
9173 	default:
9174 		*prefix = "";
9175 		*kind = BTF_KIND_FUNC;
9176 	}
9177 }
9178 
9179 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
9180 				   const char *name, __u32 kind)
9181 {
9182 	char btf_type_name[BTF_MAX_NAME_SIZE];
9183 	int ret;
9184 
9185 	ret = snprintf(btf_type_name, sizeof(btf_type_name),
9186 		       "%s%s", prefix, name);
9187 	/* snprintf returns the number of characters written excluding the
9188 	 * terminating null. So, if >= BTF_MAX_NAME_SIZE are written, it
9189 	 * indicates truncation.
9190 	 */
9191 	if (ret < 0 || ret >= sizeof(btf_type_name))
9192 		return -ENAMETOOLONG;
9193 	return btf__find_by_name_kind(btf, btf_type_name, kind);
9194 }
9195 
9196 static inline int find_attach_btf_id(struct btf *btf, const char *name,
9197 				     enum bpf_attach_type attach_type)
9198 {
9199 	const char *prefix;
9200 	int kind;
9201 
9202 	btf_get_kernel_prefix_kind(attach_type, &prefix, &kind);
9203 	return find_btf_by_prefix_kind(btf, prefix, name, kind);
9204 }
9205 
9206 int libbpf_find_vmlinux_btf_id(const char *name,
9207 			       enum bpf_attach_type attach_type)
9208 {
9209 	struct btf *btf;
9210 	int err;
9211 
9212 	btf = btf__load_vmlinux_btf();
9213 	err = libbpf_get_error(btf);
9214 	if (err) {
9215 		pr_warn("vmlinux BTF is not found\n");
9216 		return libbpf_err(err);
9217 	}
9218 
9219 	err = find_attach_btf_id(btf, name, attach_type);
9220 	if (err <= 0)
9221 		pr_warn("%s is not found in vmlinux BTF\n", name);
9222 
9223 	btf__free(btf);
9224 	return libbpf_err(err);
9225 }
9226 
9227 static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd)
9228 {
9229 	struct bpf_prog_info info;
9230 	__u32 info_len = sizeof(info);
9231 	struct btf *btf;
9232 	int err;
9233 
9234 	memset(&info, 0, info_len);
9235 	err = bpf_prog_get_info_by_fd(attach_prog_fd, &info, &info_len);
9236 	if (err) {
9237 		pr_warn("failed bpf_prog_get_info_by_fd for FD %d: %d\n",
9238 			attach_prog_fd, err);
9239 		return err;
9240 	}
9241 
9242 	err = -EINVAL;
9243 	if (!info.btf_id) {
9244 		pr_warn("The target program doesn't have BTF\n");
9245 		goto out;
9246 	}
9247 	btf = btf__load_from_kernel_by_id(info.btf_id);
9248 	err = libbpf_get_error(btf);
9249 	if (err) {
9250 		pr_warn("Failed to get BTF %d of the program: %d\n", info.btf_id, err);
9251 		goto out;
9252 	}
9253 	err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
9254 	btf__free(btf);
9255 	if (err <= 0) {
9256 		pr_warn("%s is not found in prog's BTF\n", name);
9257 		goto out;
9258 	}
9259 out:
9260 	return err;
9261 }
9262 
9263 static int find_kernel_btf_id(struct bpf_object *obj, const char *attach_name,
9264 			      enum bpf_attach_type attach_type,
9265 			      int *btf_obj_fd, int *btf_type_id)
9266 {
9267 	int ret, i;
9268 
9269 	ret = find_attach_btf_id(obj->btf_vmlinux, attach_name, attach_type);
9270 	if (ret > 0) {
9271 		*btf_obj_fd = 0; /* vmlinux BTF */
9272 		*btf_type_id = ret;
9273 		return 0;
9274 	}
9275 	if (ret != -ENOENT)
9276 		return ret;
9277 
9278 	ret = load_module_btfs(obj);
9279 	if (ret)
9280 		return ret;
9281 
9282 	for (i = 0; i < obj->btf_module_cnt; i++) {
9283 		const struct module_btf *mod = &obj->btf_modules[i];
9284 
9285 		ret = find_attach_btf_id(mod->btf, attach_name, attach_type);
9286 		if (ret > 0) {
9287 			*btf_obj_fd = mod->fd;
9288 			*btf_type_id = ret;
9289 			return 0;
9290 		}
9291 		if (ret == -ENOENT)
9292 			continue;
9293 
9294 		return ret;
9295 	}
9296 
9297 	return -ESRCH;
9298 }
9299 
9300 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
9301 				     int *btf_obj_fd, int *btf_type_id)
9302 {
9303 	enum bpf_attach_type attach_type = prog->expected_attach_type;
9304 	__u32 attach_prog_fd = prog->attach_prog_fd;
9305 	int err = 0;
9306 
9307 	/* BPF program's BTF ID */
9308 	if (prog->type == BPF_PROG_TYPE_EXT || attach_prog_fd) {
9309 		if (!attach_prog_fd) {
9310 			pr_warn("prog '%s': attach program FD is not set\n", prog->name);
9311 			return -EINVAL;
9312 		}
9313 		err = libbpf_find_prog_btf_id(attach_name, attach_prog_fd);
9314 		if (err < 0) {
9315 			pr_warn("prog '%s': failed to find BPF program (FD %d) BTF ID for '%s': %d\n",
9316 				 prog->name, attach_prog_fd, attach_name, err);
9317 			return err;
9318 		}
9319 		*btf_obj_fd = 0;
9320 		*btf_type_id = err;
9321 		return 0;
9322 	}
9323 
9324 	/* kernel/module BTF ID */
9325 	if (prog->obj->gen_loader) {
9326 		bpf_gen__record_attach_target(prog->obj->gen_loader, attach_name, attach_type);
9327 		*btf_obj_fd = 0;
9328 		*btf_type_id = 1;
9329 	} else {
9330 		err = find_kernel_btf_id(prog->obj, attach_name, attach_type, btf_obj_fd, btf_type_id);
9331 	}
9332 	if (err) {
9333 		pr_warn("prog '%s': failed to find kernel BTF type ID of '%s': %d\n",
9334 			prog->name, attach_name, err);
9335 		return err;
9336 	}
9337 	return 0;
9338 }
9339 
9340 int libbpf_attach_type_by_name(const char *name,
9341 			       enum bpf_attach_type *attach_type)
9342 {
9343 	char *type_names;
9344 	const struct bpf_sec_def *sec_def;
9345 
9346 	if (!name)
9347 		return libbpf_err(-EINVAL);
9348 
9349 	sec_def = find_sec_def(name);
9350 	if (!sec_def) {
9351 		pr_debug("failed to guess attach type based on ELF section name '%s'\n", name);
9352 		type_names = libbpf_get_type_names(true);
9353 		if (type_names != NULL) {
9354 			pr_debug("attachable section(type) names are:%s\n", type_names);
9355 			free(type_names);
9356 		}
9357 
9358 		return libbpf_err(-EINVAL);
9359 	}
9360 
9361 	if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
9362 		return libbpf_err(-EINVAL);
9363 	if (!(sec_def->cookie & SEC_ATTACHABLE))
9364 		return libbpf_err(-EINVAL);
9365 
9366 	*attach_type = sec_def->expected_attach_type;
9367 	return 0;
9368 }
9369 
9370 int bpf_map__fd(const struct bpf_map *map)
9371 {
9372 	return map ? map->fd : libbpf_err(-EINVAL);
9373 }
9374 
9375 static bool map_uses_real_name(const struct bpf_map *map)
9376 {
9377 	/* Since libbpf started to support custom .data.* and .rodata.* maps,
9378 	 * their user-visible name differs from kernel-visible name. Users see
9379 	 * such map's corresponding ELF section name as a map name.
9380 	 * This check distinguishes .data/.rodata from .data.* and .rodata.*
9381 	 * maps to know which name has to be returned to the user.
9382 	 */
9383 	if (map->libbpf_type == LIBBPF_MAP_DATA && strcmp(map->real_name, DATA_SEC) != 0)
9384 		return true;
9385 	if (map->libbpf_type == LIBBPF_MAP_RODATA && strcmp(map->real_name, RODATA_SEC) != 0)
9386 		return true;
9387 	return false;
9388 }
9389 
9390 const char *bpf_map__name(const struct bpf_map *map)
9391 {
9392 	if (!map)
9393 		return NULL;
9394 
9395 	if (map_uses_real_name(map))
9396 		return map->real_name;
9397 
9398 	return map->name;
9399 }
9400 
9401 enum bpf_map_type bpf_map__type(const struct bpf_map *map)
9402 {
9403 	return map->def.type;
9404 }
9405 
9406 int bpf_map__set_type(struct bpf_map *map, enum bpf_map_type type)
9407 {
9408 	if (map->fd >= 0)
9409 		return libbpf_err(-EBUSY);
9410 	map->def.type = type;
9411 	return 0;
9412 }
9413 
9414 __u32 bpf_map__map_flags(const struct bpf_map *map)
9415 {
9416 	return map->def.map_flags;
9417 }
9418 
9419 int bpf_map__set_map_flags(struct bpf_map *map, __u32 flags)
9420 {
9421 	if (map->fd >= 0)
9422 		return libbpf_err(-EBUSY);
9423 	map->def.map_flags = flags;
9424 	return 0;
9425 }
9426 
9427 __u64 bpf_map__map_extra(const struct bpf_map *map)
9428 {
9429 	return map->map_extra;
9430 }
9431 
9432 int bpf_map__set_map_extra(struct bpf_map *map, __u64 map_extra)
9433 {
9434 	if (map->fd >= 0)
9435 		return libbpf_err(-EBUSY);
9436 	map->map_extra = map_extra;
9437 	return 0;
9438 }
9439 
9440 __u32 bpf_map__numa_node(const struct bpf_map *map)
9441 {
9442 	return map->numa_node;
9443 }
9444 
9445 int bpf_map__set_numa_node(struct bpf_map *map, __u32 numa_node)
9446 {
9447 	if (map->fd >= 0)
9448 		return libbpf_err(-EBUSY);
9449 	map->numa_node = numa_node;
9450 	return 0;
9451 }
9452 
9453 __u32 bpf_map__key_size(const struct bpf_map *map)
9454 {
9455 	return map->def.key_size;
9456 }
9457 
9458 int bpf_map__set_key_size(struct bpf_map *map, __u32 size)
9459 {
9460 	if (map->fd >= 0)
9461 		return libbpf_err(-EBUSY);
9462 	map->def.key_size = size;
9463 	return 0;
9464 }
9465 
9466 __u32 bpf_map__value_size(const struct bpf_map *map)
9467 {
9468 	return map->def.value_size;
9469 }
9470 
9471 static int map_btf_datasec_resize(struct bpf_map *map, __u32 size)
9472 {
9473 	struct btf *btf;
9474 	struct btf_type *datasec_type, *var_type;
9475 	struct btf_var_secinfo *var;
9476 	const struct btf_type *array_type;
9477 	const struct btf_array *array;
9478 	int vlen, element_sz, new_array_id;
9479 	__u32 nr_elements;
9480 
9481 	/* check btf existence */
9482 	btf = bpf_object__btf(map->obj);
9483 	if (!btf)
9484 		return -ENOENT;
9485 
9486 	/* verify map is datasec */
9487 	datasec_type = btf_type_by_id(btf, bpf_map__btf_value_type_id(map));
9488 	if (!btf_is_datasec(datasec_type)) {
9489 		pr_warn("map '%s': cannot be resized, map value type is not a datasec\n",
9490 			bpf_map__name(map));
9491 		return -EINVAL;
9492 	}
9493 
9494 	/* verify datasec has at least one var */
9495 	vlen = btf_vlen(datasec_type);
9496 	if (vlen == 0) {
9497 		pr_warn("map '%s': cannot be resized, map value datasec is empty\n",
9498 			bpf_map__name(map));
9499 		return -EINVAL;
9500 	}
9501 
9502 	/* verify last var in the datasec is an array */
9503 	var = &btf_var_secinfos(datasec_type)[vlen - 1];
9504 	var_type = btf_type_by_id(btf, var->type);
9505 	array_type = skip_mods_and_typedefs(btf, var_type->type, NULL);
9506 	if (!btf_is_array(array_type)) {
9507 		pr_warn("map '%s': cannot be resized, last var must be an array\n",
9508 			bpf_map__name(map));
9509 		return -EINVAL;
9510 	}
9511 
9512 	/* verify request size aligns with array */
9513 	array = btf_array(array_type);
9514 	element_sz = btf__resolve_size(btf, array->type);
9515 	if (element_sz <= 0 || (size - var->offset) % element_sz != 0) {
9516 		pr_warn("map '%s': cannot be resized, element size (%d) doesn't align with new total size (%u)\n",
9517 			bpf_map__name(map), element_sz, size);
9518 		return -EINVAL;
9519 	}
9520 
9521 	/* create a new array based on the existing array, but with new length */
9522 	nr_elements = (size - var->offset) / element_sz;
9523 	new_array_id = btf__add_array(btf, array->index_type, array->type, nr_elements);
9524 	if (new_array_id < 0)
9525 		return new_array_id;
9526 
9527 	/* adding a new btf type invalidates existing pointers to btf objects,
9528 	 * so refresh pointers before proceeding
9529 	 */
9530 	datasec_type = btf_type_by_id(btf, map->btf_value_type_id);
9531 	var = &btf_var_secinfos(datasec_type)[vlen - 1];
9532 	var_type = btf_type_by_id(btf, var->type);
9533 
9534 	/* finally update btf info */
9535 	datasec_type->size = size;
9536 	var->size = size - var->offset;
9537 	var_type->type = new_array_id;
9538 
9539 	return 0;
9540 }
9541 
9542 int bpf_map__set_value_size(struct bpf_map *map, __u32 size)
9543 {
9544 	if (map->fd >= 0)
9545 		return libbpf_err(-EBUSY);
9546 
9547 	if (map->mmaped) {
9548 		int err;
9549 		size_t mmap_old_sz, mmap_new_sz;
9550 
9551 		mmap_old_sz = bpf_map_mmap_sz(map->def.value_size, map->def.max_entries);
9552 		mmap_new_sz = bpf_map_mmap_sz(size, map->def.max_entries);
9553 		err = bpf_map_mmap_resize(map, mmap_old_sz, mmap_new_sz);
9554 		if (err) {
9555 			pr_warn("map '%s': failed to resize memory-mapped region: %d\n",
9556 				bpf_map__name(map), err);
9557 			return err;
9558 		}
9559 		err = map_btf_datasec_resize(map, size);
9560 		if (err && err != -ENOENT) {
9561 			pr_warn("map '%s': failed to adjust resized BTF, clearing BTF key/value info: %d\n",
9562 				bpf_map__name(map), err);
9563 			map->btf_value_type_id = 0;
9564 			map->btf_key_type_id = 0;
9565 		}
9566 	}
9567 
9568 	map->def.value_size = size;
9569 	return 0;
9570 }
9571 
9572 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
9573 {
9574 	return map ? map->btf_key_type_id : 0;
9575 }
9576 
9577 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
9578 {
9579 	return map ? map->btf_value_type_id : 0;
9580 }
9581 
9582 int bpf_map__set_initial_value(struct bpf_map *map,
9583 			       const void *data, size_t size)
9584 {
9585 	if (!map->mmaped || map->libbpf_type == LIBBPF_MAP_KCONFIG ||
9586 	    size != map->def.value_size || map->fd >= 0)
9587 		return libbpf_err(-EINVAL);
9588 
9589 	memcpy(map->mmaped, data, size);
9590 	return 0;
9591 }
9592 
9593 void *bpf_map__initial_value(struct bpf_map *map, size_t *psize)
9594 {
9595 	if (!map->mmaped)
9596 		return NULL;
9597 	*psize = map->def.value_size;
9598 	return map->mmaped;
9599 }
9600 
9601 bool bpf_map__is_internal(const struct bpf_map *map)
9602 {
9603 	return map->libbpf_type != LIBBPF_MAP_UNSPEC;
9604 }
9605 
9606 __u32 bpf_map__ifindex(const struct bpf_map *map)
9607 {
9608 	return map->map_ifindex;
9609 }
9610 
9611 int bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
9612 {
9613 	if (map->fd >= 0)
9614 		return libbpf_err(-EBUSY);
9615 	map->map_ifindex = ifindex;
9616 	return 0;
9617 }
9618 
9619 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
9620 {
9621 	if (!bpf_map_type__is_map_in_map(map->def.type)) {
9622 		pr_warn("error: unsupported map type\n");
9623 		return libbpf_err(-EINVAL);
9624 	}
9625 	if (map->inner_map_fd != -1) {
9626 		pr_warn("error: inner_map_fd already specified\n");
9627 		return libbpf_err(-EINVAL);
9628 	}
9629 	if (map->inner_map) {
9630 		bpf_map__destroy(map->inner_map);
9631 		zfree(&map->inner_map);
9632 	}
9633 	map->inner_map_fd = fd;
9634 	return 0;
9635 }
9636 
9637 static struct bpf_map *
9638 __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
9639 {
9640 	ssize_t idx;
9641 	struct bpf_map *s, *e;
9642 
9643 	if (!obj || !obj->maps)
9644 		return errno = EINVAL, NULL;
9645 
9646 	s = obj->maps;
9647 	e = obj->maps + obj->nr_maps;
9648 
9649 	if ((m < s) || (m >= e)) {
9650 		pr_warn("error in %s: map handler doesn't belong to object\n",
9651 			 __func__);
9652 		return errno = EINVAL, NULL;
9653 	}
9654 
9655 	idx = (m - obj->maps) + i;
9656 	if (idx >= obj->nr_maps || idx < 0)
9657 		return NULL;
9658 	return &obj->maps[idx];
9659 }
9660 
9661 struct bpf_map *
9662 bpf_object__next_map(const struct bpf_object *obj, const struct bpf_map *prev)
9663 {
9664 	if (prev == NULL)
9665 		return obj->maps;
9666 
9667 	return __bpf_map__iter(prev, obj, 1);
9668 }
9669 
9670 struct bpf_map *
9671 bpf_object__prev_map(const struct bpf_object *obj, const struct bpf_map *next)
9672 {
9673 	if (next == NULL) {
9674 		if (!obj->nr_maps)
9675 			return NULL;
9676 		return obj->maps + obj->nr_maps - 1;
9677 	}
9678 
9679 	return __bpf_map__iter(next, obj, -1);
9680 }
9681 
9682 struct bpf_map *
9683 bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
9684 {
9685 	struct bpf_map *pos;
9686 
9687 	bpf_object__for_each_map(pos, obj) {
9688 		/* if it's a special internal map name (which always starts
9689 		 * with dot) then check if that special name matches the
9690 		 * real map name (ELF section name)
9691 		 */
9692 		if (name[0] == '.') {
9693 			if (pos->real_name && strcmp(pos->real_name, name) == 0)
9694 				return pos;
9695 			continue;
9696 		}
9697 		/* otherwise map name has to be an exact match */
9698 		if (map_uses_real_name(pos)) {
9699 			if (strcmp(pos->real_name, name) == 0)
9700 				return pos;
9701 			continue;
9702 		}
9703 		if (strcmp(pos->name, name) == 0)
9704 			return pos;
9705 	}
9706 	return errno = ENOENT, NULL;
9707 }
9708 
9709 int
9710 bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
9711 {
9712 	return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
9713 }
9714 
9715 static int validate_map_op(const struct bpf_map *map, size_t key_sz,
9716 			   size_t value_sz, bool check_value_sz)
9717 {
9718 	if (map->fd <= 0)
9719 		return -ENOENT;
9720 
9721 	if (map->def.key_size != key_sz) {
9722 		pr_warn("map '%s': unexpected key size %zu provided, expected %u\n",
9723 			map->name, key_sz, map->def.key_size);
9724 		return -EINVAL;
9725 	}
9726 
9727 	if (!check_value_sz)
9728 		return 0;
9729 
9730 	switch (map->def.type) {
9731 	case BPF_MAP_TYPE_PERCPU_ARRAY:
9732 	case BPF_MAP_TYPE_PERCPU_HASH:
9733 	case BPF_MAP_TYPE_LRU_PERCPU_HASH:
9734 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: {
9735 		int num_cpu = libbpf_num_possible_cpus();
9736 		size_t elem_sz = roundup(map->def.value_size, 8);
9737 
9738 		if (value_sz != num_cpu * elem_sz) {
9739 			pr_warn("map '%s': unexpected value size %zu provided for per-CPU map, expected %d * %zu = %zd\n",
9740 				map->name, value_sz, num_cpu, elem_sz, num_cpu * elem_sz);
9741 			return -EINVAL;
9742 		}
9743 		break;
9744 	}
9745 	default:
9746 		if (map->def.value_size != value_sz) {
9747 			pr_warn("map '%s': unexpected value size %zu provided, expected %u\n",
9748 				map->name, value_sz, map->def.value_size);
9749 			return -EINVAL;
9750 		}
9751 		break;
9752 	}
9753 	return 0;
9754 }
9755 
9756 int bpf_map__lookup_elem(const struct bpf_map *map,
9757 			 const void *key, size_t key_sz,
9758 			 void *value, size_t value_sz, __u64 flags)
9759 {
9760 	int err;
9761 
9762 	err = validate_map_op(map, key_sz, value_sz, true);
9763 	if (err)
9764 		return libbpf_err(err);
9765 
9766 	return bpf_map_lookup_elem_flags(map->fd, key, value, flags);
9767 }
9768 
9769 int bpf_map__update_elem(const struct bpf_map *map,
9770 			 const void *key, size_t key_sz,
9771 			 const void *value, size_t value_sz, __u64 flags)
9772 {
9773 	int err;
9774 
9775 	err = validate_map_op(map, key_sz, value_sz, true);
9776 	if (err)
9777 		return libbpf_err(err);
9778 
9779 	return bpf_map_update_elem(map->fd, key, value, flags);
9780 }
9781 
9782 int bpf_map__delete_elem(const struct bpf_map *map,
9783 			 const void *key, size_t key_sz, __u64 flags)
9784 {
9785 	int err;
9786 
9787 	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */);
9788 	if (err)
9789 		return libbpf_err(err);
9790 
9791 	return bpf_map_delete_elem_flags(map->fd, key, flags);
9792 }
9793 
9794 int bpf_map__lookup_and_delete_elem(const struct bpf_map *map,
9795 				    const void *key, size_t key_sz,
9796 				    void *value, size_t value_sz, __u64 flags)
9797 {
9798 	int err;
9799 
9800 	err = validate_map_op(map, key_sz, value_sz, true);
9801 	if (err)
9802 		return libbpf_err(err);
9803 
9804 	return bpf_map_lookup_and_delete_elem_flags(map->fd, key, value, flags);
9805 }
9806 
9807 int bpf_map__get_next_key(const struct bpf_map *map,
9808 			  const void *cur_key, void *next_key, size_t key_sz)
9809 {
9810 	int err;
9811 
9812 	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */);
9813 	if (err)
9814 		return libbpf_err(err);
9815 
9816 	return bpf_map_get_next_key(map->fd, cur_key, next_key);
9817 }
9818 
9819 long libbpf_get_error(const void *ptr)
9820 {
9821 	if (!IS_ERR_OR_NULL(ptr))
9822 		return 0;
9823 
9824 	if (IS_ERR(ptr))
9825 		errno = -PTR_ERR(ptr);
9826 
9827 	/* If ptr == NULL, then errno should be already set by the failing
9828 	 * API, because libbpf never returns NULL on success and it now always
9829 	 * sets errno on error. So no extra errno handling for ptr == NULL
9830 	 * case.
9831 	 */
9832 	return -errno;
9833 }
9834 
9835 /* Replace link's underlying BPF program with the new one */
9836 int bpf_link__update_program(struct bpf_link *link, struct bpf_program *prog)
9837 {
9838 	int ret;
9839 
9840 	ret = bpf_link_update(bpf_link__fd(link), bpf_program__fd(prog), NULL);
9841 	return libbpf_err_errno(ret);
9842 }
9843 
9844 /* Release "ownership" of underlying BPF resource (typically, BPF program
9845  * attached to some BPF hook, e.g., tracepoint, kprobe, etc). Disconnected
9846  * link, when destructed through bpf_link__destroy() call won't attempt to
9847  * detach/unregisted that BPF resource. This is useful in situations where,
9848  * say, attached BPF program has to outlive userspace program that attached it
9849  * in the system. Depending on type of BPF program, though, there might be
9850  * additional steps (like pinning BPF program in BPF FS) necessary to ensure
9851  * exit of userspace program doesn't trigger automatic detachment and clean up
9852  * inside the kernel.
9853  */
9854 void bpf_link__disconnect(struct bpf_link *link)
9855 {
9856 	link->disconnected = true;
9857 }
9858 
9859 int bpf_link__destroy(struct bpf_link *link)
9860 {
9861 	int err = 0;
9862 
9863 	if (IS_ERR_OR_NULL(link))
9864 		return 0;
9865 
9866 	if (!link->disconnected && link->detach)
9867 		err = link->detach(link);
9868 	if (link->pin_path)
9869 		free(link->pin_path);
9870 	if (link->dealloc)
9871 		link->dealloc(link);
9872 	else
9873 		free(link);
9874 
9875 	return libbpf_err(err);
9876 }
9877 
9878 int bpf_link__fd(const struct bpf_link *link)
9879 {
9880 	return link->fd;
9881 }
9882 
9883 const char *bpf_link__pin_path(const struct bpf_link *link)
9884 {
9885 	return link->pin_path;
9886 }
9887 
9888 static int bpf_link__detach_fd(struct bpf_link *link)
9889 {
9890 	return libbpf_err_errno(close(link->fd));
9891 }
9892 
9893 struct bpf_link *bpf_link__open(const char *path)
9894 {
9895 	struct bpf_link *link;
9896 	int fd;
9897 
9898 	fd = bpf_obj_get(path);
9899 	if (fd < 0) {
9900 		fd = -errno;
9901 		pr_warn("failed to open link at %s: %d\n", path, fd);
9902 		return libbpf_err_ptr(fd);
9903 	}
9904 
9905 	link = calloc(1, sizeof(*link));
9906 	if (!link) {
9907 		close(fd);
9908 		return libbpf_err_ptr(-ENOMEM);
9909 	}
9910 	link->detach = &bpf_link__detach_fd;
9911 	link->fd = fd;
9912 
9913 	link->pin_path = strdup(path);
9914 	if (!link->pin_path) {
9915 		bpf_link__destroy(link);
9916 		return libbpf_err_ptr(-ENOMEM);
9917 	}
9918 
9919 	return link;
9920 }
9921 
9922 int bpf_link__detach(struct bpf_link *link)
9923 {
9924 	return bpf_link_detach(link->fd) ? -errno : 0;
9925 }
9926 
9927 int bpf_link__pin(struct bpf_link *link, const char *path)
9928 {
9929 	int err;
9930 
9931 	if (link->pin_path)
9932 		return libbpf_err(-EBUSY);
9933 	err = make_parent_dir(path);
9934 	if (err)
9935 		return libbpf_err(err);
9936 	err = check_path(path);
9937 	if (err)
9938 		return libbpf_err(err);
9939 
9940 	link->pin_path = strdup(path);
9941 	if (!link->pin_path)
9942 		return libbpf_err(-ENOMEM);
9943 
9944 	if (bpf_obj_pin(link->fd, link->pin_path)) {
9945 		err = -errno;
9946 		zfree(&link->pin_path);
9947 		return libbpf_err(err);
9948 	}
9949 
9950 	pr_debug("link fd=%d: pinned at %s\n", link->fd, link->pin_path);
9951 	return 0;
9952 }
9953 
9954 int bpf_link__unpin(struct bpf_link *link)
9955 {
9956 	int err;
9957 
9958 	if (!link->pin_path)
9959 		return libbpf_err(-EINVAL);
9960 
9961 	err = unlink(link->pin_path);
9962 	if (err != 0)
9963 		return -errno;
9964 
9965 	pr_debug("link fd=%d: unpinned from %s\n", link->fd, link->pin_path);
9966 	zfree(&link->pin_path);
9967 	return 0;
9968 }
9969 
9970 struct bpf_link_perf {
9971 	struct bpf_link link;
9972 	int perf_event_fd;
9973 	/* legacy kprobe support: keep track of probe identifier and type */
9974 	char *legacy_probe_name;
9975 	bool legacy_is_kprobe;
9976 	bool legacy_is_retprobe;
9977 };
9978 
9979 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe);
9980 static int remove_uprobe_event_legacy(const char *probe_name, bool retprobe);
9981 
9982 static int bpf_link_perf_detach(struct bpf_link *link)
9983 {
9984 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
9985 	int err = 0;
9986 
9987 	if (ioctl(perf_link->perf_event_fd, PERF_EVENT_IOC_DISABLE, 0) < 0)
9988 		err = -errno;
9989 
9990 	if (perf_link->perf_event_fd != link->fd)
9991 		close(perf_link->perf_event_fd);
9992 	close(link->fd);
9993 
9994 	/* legacy uprobe/kprobe needs to be removed after perf event fd closure */
9995 	if (perf_link->legacy_probe_name) {
9996 		if (perf_link->legacy_is_kprobe) {
9997 			err = remove_kprobe_event_legacy(perf_link->legacy_probe_name,
9998 							 perf_link->legacy_is_retprobe);
9999 		} else {
10000 			err = remove_uprobe_event_legacy(perf_link->legacy_probe_name,
10001 							 perf_link->legacy_is_retprobe);
10002 		}
10003 	}
10004 
10005 	return err;
10006 }
10007 
10008 static void bpf_link_perf_dealloc(struct bpf_link *link)
10009 {
10010 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10011 
10012 	free(perf_link->legacy_probe_name);
10013 	free(perf_link);
10014 }
10015 
10016 struct bpf_link *bpf_program__attach_perf_event_opts(const struct bpf_program *prog, int pfd,
10017 						     const struct bpf_perf_event_opts *opts)
10018 {
10019 	char errmsg[STRERR_BUFSIZE];
10020 	struct bpf_link_perf *link;
10021 	int prog_fd, link_fd = -1, err;
10022 	bool force_ioctl_attach;
10023 
10024 	if (!OPTS_VALID(opts, bpf_perf_event_opts))
10025 		return libbpf_err_ptr(-EINVAL);
10026 
10027 	if (pfd < 0) {
10028 		pr_warn("prog '%s': invalid perf event FD %d\n",
10029 			prog->name, pfd);
10030 		return libbpf_err_ptr(-EINVAL);
10031 	}
10032 	prog_fd = bpf_program__fd(prog);
10033 	if (prog_fd < 0) {
10034 		pr_warn("prog '%s': can't attach BPF program w/o FD (did you load it?)\n",
10035 			prog->name);
10036 		return libbpf_err_ptr(-EINVAL);
10037 	}
10038 
10039 	link = calloc(1, sizeof(*link));
10040 	if (!link)
10041 		return libbpf_err_ptr(-ENOMEM);
10042 	link->link.detach = &bpf_link_perf_detach;
10043 	link->link.dealloc = &bpf_link_perf_dealloc;
10044 	link->perf_event_fd = pfd;
10045 
10046 	force_ioctl_attach = OPTS_GET(opts, force_ioctl_attach, false);
10047 	if (kernel_supports(prog->obj, FEAT_PERF_LINK) && !force_ioctl_attach) {
10048 		DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_opts,
10049 			.perf_event.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0));
10050 
10051 		link_fd = bpf_link_create(prog_fd, pfd, BPF_PERF_EVENT, &link_opts);
10052 		if (link_fd < 0) {
10053 			err = -errno;
10054 			pr_warn("prog '%s': failed to create BPF link for perf_event FD %d: %d (%s)\n",
10055 				prog->name, pfd,
10056 				err, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10057 			goto err_out;
10058 		}
10059 		link->link.fd = link_fd;
10060 	} else {
10061 		if (OPTS_GET(opts, bpf_cookie, 0)) {
10062 			pr_warn("prog '%s': user context value is not supported\n", prog->name);
10063 			err = -EOPNOTSUPP;
10064 			goto err_out;
10065 		}
10066 
10067 		if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
10068 			err = -errno;
10069 			pr_warn("prog '%s': failed to attach to perf_event FD %d: %s\n",
10070 				prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10071 			if (err == -EPROTO)
10072 				pr_warn("prog '%s': try add PERF_SAMPLE_CALLCHAIN to or remove exclude_callchain_[kernel|user] from pfd %d\n",
10073 					prog->name, pfd);
10074 			goto err_out;
10075 		}
10076 		link->link.fd = pfd;
10077 	}
10078 	if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
10079 		err = -errno;
10080 		pr_warn("prog '%s': failed to enable perf_event FD %d: %s\n",
10081 			prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10082 		goto err_out;
10083 	}
10084 
10085 	return &link->link;
10086 err_out:
10087 	if (link_fd >= 0)
10088 		close(link_fd);
10089 	free(link);
10090 	return libbpf_err_ptr(err);
10091 }
10092 
10093 struct bpf_link *bpf_program__attach_perf_event(const struct bpf_program *prog, int pfd)
10094 {
10095 	return bpf_program__attach_perf_event_opts(prog, pfd, NULL);
10096 }
10097 
10098 /*
10099  * this function is expected to parse integer in the range of [0, 2^31-1] from
10100  * given file using scanf format string fmt. If actual parsed value is
10101  * negative, the result might be indistinguishable from error
10102  */
10103 static int parse_uint_from_file(const char *file, const char *fmt)
10104 {
10105 	char buf[STRERR_BUFSIZE];
10106 	int err, ret;
10107 	FILE *f;
10108 
10109 	f = fopen(file, "re");
10110 	if (!f) {
10111 		err = -errno;
10112 		pr_debug("failed to open '%s': %s\n", file,
10113 			 libbpf_strerror_r(err, buf, sizeof(buf)));
10114 		return err;
10115 	}
10116 	err = fscanf(f, fmt, &ret);
10117 	if (err != 1) {
10118 		err = err == EOF ? -EIO : -errno;
10119 		pr_debug("failed to parse '%s': %s\n", file,
10120 			libbpf_strerror_r(err, buf, sizeof(buf)));
10121 		fclose(f);
10122 		return err;
10123 	}
10124 	fclose(f);
10125 	return ret;
10126 }
10127 
10128 static int determine_kprobe_perf_type(void)
10129 {
10130 	const char *file = "/sys/bus/event_source/devices/kprobe/type";
10131 
10132 	return parse_uint_from_file(file, "%d\n");
10133 }
10134 
10135 static int determine_uprobe_perf_type(void)
10136 {
10137 	const char *file = "/sys/bus/event_source/devices/uprobe/type";
10138 
10139 	return parse_uint_from_file(file, "%d\n");
10140 }
10141 
10142 static int determine_kprobe_retprobe_bit(void)
10143 {
10144 	const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
10145 
10146 	return parse_uint_from_file(file, "config:%d\n");
10147 }
10148 
10149 static int determine_uprobe_retprobe_bit(void)
10150 {
10151 	const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
10152 
10153 	return parse_uint_from_file(file, "config:%d\n");
10154 }
10155 
10156 #define PERF_UPROBE_REF_CTR_OFFSET_BITS 32
10157 #define PERF_UPROBE_REF_CTR_OFFSET_SHIFT 32
10158 
10159 static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
10160 				 uint64_t offset, int pid, size_t ref_ctr_off)
10161 {
10162 	const size_t attr_sz = sizeof(struct perf_event_attr);
10163 	struct perf_event_attr attr;
10164 	char errmsg[STRERR_BUFSIZE];
10165 	int type, pfd;
10166 
10167 	if ((__u64)ref_ctr_off >= (1ULL << PERF_UPROBE_REF_CTR_OFFSET_BITS))
10168 		return -EINVAL;
10169 
10170 	memset(&attr, 0, attr_sz);
10171 
10172 	type = uprobe ? determine_uprobe_perf_type()
10173 		      : determine_kprobe_perf_type();
10174 	if (type < 0) {
10175 		pr_warn("failed to determine %s perf type: %s\n",
10176 			uprobe ? "uprobe" : "kprobe",
10177 			libbpf_strerror_r(type, errmsg, sizeof(errmsg)));
10178 		return type;
10179 	}
10180 	if (retprobe) {
10181 		int bit = uprobe ? determine_uprobe_retprobe_bit()
10182 				 : determine_kprobe_retprobe_bit();
10183 
10184 		if (bit < 0) {
10185 			pr_warn("failed to determine %s retprobe bit: %s\n",
10186 				uprobe ? "uprobe" : "kprobe",
10187 				libbpf_strerror_r(bit, errmsg, sizeof(errmsg)));
10188 			return bit;
10189 		}
10190 		attr.config |= 1 << bit;
10191 	}
10192 	attr.size = attr_sz;
10193 	attr.type = type;
10194 	attr.config |= (__u64)ref_ctr_off << PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
10195 	attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
10196 	attr.config2 = offset;		 /* kprobe_addr or probe_offset */
10197 
10198 	/* pid filter is meaningful only for uprobes */
10199 	pfd = syscall(__NR_perf_event_open, &attr,
10200 		      pid < 0 ? -1 : pid /* pid */,
10201 		      pid == -1 ? 0 : -1 /* cpu */,
10202 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
10203 	return pfd >= 0 ? pfd : -errno;
10204 }
10205 
10206 static int append_to_file(const char *file, const char *fmt, ...)
10207 {
10208 	int fd, n, err = 0;
10209 	va_list ap;
10210 	char buf[1024];
10211 
10212 	va_start(ap, fmt);
10213 	n = vsnprintf(buf, sizeof(buf), fmt, ap);
10214 	va_end(ap);
10215 
10216 	if (n < 0 || n >= sizeof(buf))
10217 		return -EINVAL;
10218 
10219 	fd = open(file, O_WRONLY | O_APPEND | O_CLOEXEC, 0);
10220 	if (fd < 0)
10221 		return -errno;
10222 
10223 	if (write(fd, buf, n) < 0)
10224 		err = -errno;
10225 
10226 	close(fd);
10227 	return err;
10228 }
10229 
10230 #define DEBUGFS "/sys/kernel/debug/tracing"
10231 #define TRACEFS "/sys/kernel/tracing"
10232 
10233 static bool use_debugfs(void)
10234 {
10235 	static int has_debugfs = -1;
10236 
10237 	if (has_debugfs < 0)
10238 		has_debugfs = faccessat(AT_FDCWD, DEBUGFS, F_OK, AT_EACCESS) == 0;
10239 
10240 	return has_debugfs == 1;
10241 }
10242 
10243 static const char *tracefs_path(void)
10244 {
10245 	return use_debugfs() ? DEBUGFS : TRACEFS;
10246 }
10247 
10248 static const char *tracefs_kprobe_events(void)
10249 {
10250 	return use_debugfs() ? DEBUGFS"/kprobe_events" : TRACEFS"/kprobe_events";
10251 }
10252 
10253 static const char *tracefs_uprobe_events(void)
10254 {
10255 	return use_debugfs() ? DEBUGFS"/uprobe_events" : TRACEFS"/uprobe_events";
10256 }
10257 
10258 static const char *tracefs_available_filter_functions(void)
10259 {
10260 	return use_debugfs() ? DEBUGFS"/available_filter_functions"
10261 			     : TRACEFS"/available_filter_functions";
10262 }
10263 
10264 static const char *tracefs_available_filter_functions_addrs(void)
10265 {
10266 	return use_debugfs() ? DEBUGFS"/available_filter_functions_addrs"
10267 			     : TRACEFS"/available_filter_functions_addrs";
10268 }
10269 
10270 static void gen_kprobe_legacy_event_name(char *buf, size_t buf_sz,
10271 					 const char *kfunc_name, size_t offset)
10272 {
10273 	static int index = 0;
10274 	int i;
10275 
10276 	snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx_%d", getpid(), kfunc_name, offset,
10277 		 __sync_fetch_and_add(&index, 1));
10278 
10279 	/* sanitize binary_path in the probe name */
10280 	for (i = 0; buf[i]; i++) {
10281 		if (!isalnum(buf[i]))
10282 			buf[i] = '_';
10283 	}
10284 }
10285 
10286 static int add_kprobe_event_legacy(const char *probe_name, bool retprobe,
10287 				   const char *kfunc_name, size_t offset)
10288 {
10289 	return append_to_file(tracefs_kprobe_events(), "%c:%s/%s %s+0x%zx",
10290 			      retprobe ? 'r' : 'p',
10291 			      retprobe ? "kretprobes" : "kprobes",
10292 			      probe_name, kfunc_name, offset);
10293 }
10294 
10295 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe)
10296 {
10297 	return append_to_file(tracefs_kprobe_events(), "-:%s/%s",
10298 			      retprobe ? "kretprobes" : "kprobes", probe_name);
10299 }
10300 
10301 static int determine_kprobe_perf_type_legacy(const char *probe_name, bool retprobe)
10302 {
10303 	char file[256];
10304 
10305 	snprintf(file, sizeof(file), "%s/events/%s/%s/id",
10306 		 tracefs_path(), retprobe ? "kretprobes" : "kprobes", probe_name);
10307 
10308 	return parse_uint_from_file(file, "%d\n");
10309 }
10310 
10311 static int perf_event_kprobe_open_legacy(const char *probe_name, bool retprobe,
10312 					 const char *kfunc_name, size_t offset, int pid)
10313 {
10314 	const size_t attr_sz = sizeof(struct perf_event_attr);
10315 	struct perf_event_attr attr;
10316 	char errmsg[STRERR_BUFSIZE];
10317 	int type, pfd, err;
10318 
10319 	err = add_kprobe_event_legacy(probe_name, retprobe, kfunc_name, offset);
10320 	if (err < 0) {
10321 		pr_warn("failed to add legacy kprobe event for '%s+0x%zx': %s\n",
10322 			kfunc_name, offset,
10323 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10324 		return err;
10325 	}
10326 	type = determine_kprobe_perf_type_legacy(probe_name, retprobe);
10327 	if (type < 0) {
10328 		err = type;
10329 		pr_warn("failed to determine legacy kprobe event id for '%s+0x%zx': %s\n",
10330 			kfunc_name, offset,
10331 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10332 		goto err_clean_legacy;
10333 	}
10334 
10335 	memset(&attr, 0, attr_sz);
10336 	attr.size = attr_sz;
10337 	attr.config = type;
10338 	attr.type = PERF_TYPE_TRACEPOINT;
10339 
10340 	pfd = syscall(__NR_perf_event_open, &attr,
10341 		      pid < 0 ? -1 : pid, /* pid */
10342 		      pid == -1 ? 0 : -1, /* cpu */
10343 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
10344 	if (pfd < 0) {
10345 		err = -errno;
10346 		pr_warn("legacy kprobe perf_event_open() failed: %s\n",
10347 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10348 		goto err_clean_legacy;
10349 	}
10350 	return pfd;
10351 
10352 err_clean_legacy:
10353 	/* Clear the newly added legacy kprobe_event */
10354 	remove_kprobe_event_legacy(probe_name, retprobe);
10355 	return err;
10356 }
10357 
10358 static const char *arch_specific_syscall_pfx(void)
10359 {
10360 #if defined(__x86_64__)
10361 	return "x64";
10362 #elif defined(__i386__)
10363 	return "ia32";
10364 #elif defined(__s390x__)
10365 	return "s390x";
10366 #elif defined(__s390__)
10367 	return "s390";
10368 #elif defined(__arm__)
10369 	return "arm";
10370 #elif defined(__aarch64__)
10371 	return "arm64";
10372 #elif defined(__mips__)
10373 	return "mips";
10374 #elif defined(__riscv)
10375 	return "riscv";
10376 #elif defined(__powerpc__)
10377 	return "powerpc";
10378 #elif defined(__powerpc64__)
10379 	return "powerpc64";
10380 #else
10381 	return NULL;
10382 #endif
10383 }
10384 
10385 static int probe_kern_syscall_wrapper(void)
10386 {
10387 	char syscall_name[64];
10388 	const char *ksys_pfx;
10389 
10390 	ksys_pfx = arch_specific_syscall_pfx();
10391 	if (!ksys_pfx)
10392 		return 0;
10393 
10394 	snprintf(syscall_name, sizeof(syscall_name), "__%s_sys_bpf", ksys_pfx);
10395 
10396 	if (determine_kprobe_perf_type() >= 0) {
10397 		int pfd;
10398 
10399 		pfd = perf_event_open_probe(false, false, syscall_name, 0, getpid(), 0);
10400 		if (pfd >= 0)
10401 			close(pfd);
10402 
10403 		return pfd >= 0 ? 1 : 0;
10404 	} else { /* legacy mode */
10405 		char probe_name[128];
10406 
10407 		gen_kprobe_legacy_event_name(probe_name, sizeof(probe_name), syscall_name, 0);
10408 		if (add_kprobe_event_legacy(probe_name, false, syscall_name, 0) < 0)
10409 			return 0;
10410 
10411 		(void)remove_kprobe_event_legacy(probe_name, false);
10412 		return 1;
10413 	}
10414 }
10415 
10416 struct bpf_link *
10417 bpf_program__attach_kprobe_opts(const struct bpf_program *prog,
10418 				const char *func_name,
10419 				const struct bpf_kprobe_opts *opts)
10420 {
10421 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
10422 	enum probe_attach_mode attach_mode;
10423 	char errmsg[STRERR_BUFSIZE];
10424 	char *legacy_probe = NULL;
10425 	struct bpf_link *link;
10426 	size_t offset;
10427 	bool retprobe, legacy;
10428 	int pfd, err;
10429 
10430 	if (!OPTS_VALID(opts, bpf_kprobe_opts))
10431 		return libbpf_err_ptr(-EINVAL);
10432 
10433 	attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
10434 	retprobe = OPTS_GET(opts, retprobe, false);
10435 	offset = OPTS_GET(opts, offset, 0);
10436 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
10437 
10438 	legacy = determine_kprobe_perf_type() < 0;
10439 	switch (attach_mode) {
10440 	case PROBE_ATTACH_MODE_LEGACY:
10441 		legacy = true;
10442 		pe_opts.force_ioctl_attach = true;
10443 		break;
10444 	case PROBE_ATTACH_MODE_PERF:
10445 		if (legacy)
10446 			return libbpf_err_ptr(-ENOTSUP);
10447 		pe_opts.force_ioctl_attach = true;
10448 		break;
10449 	case PROBE_ATTACH_MODE_LINK:
10450 		if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
10451 			return libbpf_err_ptr(-ENOTSUP);
10452 		break;
10453 	case PROBE_ATTACH_MODE_DEFAULT:
10454 		break;
10455 	default:
10456 		return libbpf_err_ptr(-EINVAL);
10457 	}
10458 
10459 	if (!legacy) {
10460 		pfd = perf_event_open_probe(false /* uprobe */, retprobe,
10461 					    func_name, offset,
10462 					    -1 /* pid */, 0 /* ref_ctr_off */);
10463 	} else {
10464 		char probe_name[256];
10465 
10466 		gen_kprobe_legacy_event_name(probe_name, sizeof(probe_name),
10467 					     func_name, offset);
10468 
10469 		legacy_probe = strdup(probe_name);
10470 		if (!legacy_probe)
10471 			return libbpf_err_ptr(-ENOMEM);
10472 
10473 		pfd = perf_event_kprobe_open_legacy(legacy_probe, retprobe, func_name,
10474 						    offset, -1 /* pid */);
10475 	}
10476 	if (pfd < 0) {
10477 		err = -errno;
10478 		pr_warn("prog '%s': failed to create %s '%s+0x%zx' perf event: %s\n",
10479 			prog->name, retprobe ? "kretprobe" : "kprobe",
10480 			func_name, offset,
10481 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10482 		goto err_out;
10483 	}
10484 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
10485 	err = libbpf_get_error(link);
10486 	if (err) {
10487 		close(pfd);
10488 		pr_warn("prog '%s': failed to attach to %s '%s+0x%zx': %s\n",
10489 			prog->name, retprobe ? "kretprobe" : "kprobe",
10490 			func_name, offset,
10491 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10492 		goto err_clean_legacy;
10493 	}
10494 	if (legacy) {
10495 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10496 
10497 		perf_link->legacy_probe_name = legacy_probe;
10498 		perf_link->legacy_is_kprobe = true;
10499 		perf_link->legacy_is_retprobe = retprobe;
10500 	}
10501 
10502 	return link;
10503 
10504 err_clean_legacy:
10505 	if (legacy)
10506 		remove_kprobe_event_legacy(legacy_probe, retprobe);
10507 err_out:
10508 	free(legacy_probe);
10509 	return libbpf_err_ptr(err);
10510 }
10511 
10512 struct bpf_link *bpf_program__attach_kprobe(const struct bpf_program *prog,
10513 					    bool retprobe,
10514 					    const char *func_name)
10515 {
10516 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts,
10517 		.retprobe = retprobe,
10518 	);
10519 
10520 	return bpf_program__attach_kprobe_opts(prog, func_name, &opts);
10521 }
10522 
10523 struct bpf_link *bpf_program__attach_ksyscall(const struct bpf_program *prog,
10524 					      const char *syscall_name,
10525 					      const struct bpf_ksyscall_opts *opts)
10526 {
10527 	LIBBPF_OPTS(bpf_kprobe_opts, kprobe_opts);
10528 	char func_name[128];
10529 
10530 	if (!OPTS_VALID(opts, bpf_ksyscall_opts))
10531 		return libbpf_err_ptr(-EINVAL);
10532 
10533 	if (kernel_supports(prog->obj, FEAT_SYSCALL_WRAPPER)) {
10534 		/* arch_specific_syscall_pfx() should never return NULL here
10535 		 * because it is guarded by kernel_supports(). However, since
10536 		 * compiler does not know that we have an explicit conditional
10537 		 * as well.
10538 		 */
10539 		snprintf(func_name, sizeof(func_name), "__%s_sys_%s",
10540 			 arch_specific_syscall_pfx() ? : "", syscall_name);
10541 	} else {
10542 		snprintf(func_name, sizeof(func_name), "__se_sys_%s", syscall_name);
10543 	}
10544 
10545 	kprobe_opts.retprobe = OPTS_GET(opts, retprobe, false);
10546 	kprobe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
10547 
10548 	return bpf_program__attach_kprobe_opts(prog, func_name, &kprobe_opts);
10549 }
10550 
10551 /* Adapted from perf/util/string.c */
10552 static bool glob_match(const char *str, const char *pat)
10553 {
10554 	while (*str && *pat && *pat != '*') {
10555 		if (*pat == '?') {      /* Matches any single character */
10556 			str++;
10557 			pat++;
10558 			continue;
10559 		}
10560 		if (*str != *pat)
10561 			return false;
10562 		str++;
10563 		pat++;
10564 	}
10565 	/* Check wild card */
10566 	if (*pat == '*') {
10567 		while (*pat == '*')
10568 			pat++;
10569 		if (!*pat) /* Tail wild card matches all */
10570 			return true;
10571 		while (*str)
10572 			if (glob_match(str++, pat))
10573 				return true;
10574 	}
10575 	return !*str && !*pat;
10576 }
10577 
10578 struct kprobe_multi_resolve {
10579 	const char *pattern;
10580 	unsigned long *addrs;
10581 	size_t cap;
10582 	size_t cnt;
10583 };
10584 
10585 struct avail_kallsyms_data {
10586 	char **syms;
10587 	size_t cnt;
10588 	struct kprobe_multi_resolve *res;
10589 };
10590 
10591 static int avail_func_cmp(const void *a, const void *b)
10592 {
10593 	return strcmp(*(const char **)a, *(const char **)b);
10594 }
10595 
10596 static int avail_kallsyms_cb(unsigned long long sym_addr, char sym_type,
10597 			     const char *sym_name, void *ctx)
10598 {
10599 	struct avail_kallsyms_data *data = ctx;
10600 	struct kprobe_multi_resolve *res = data->res;
10601 	int err;
10602 
10603 	if (!bsearch(&sym_name, data->syms, data->cnt, sizeof(*data->syms), avail_func_cmp))
10604 		return 0;
10605 
10606 	err = libbpf_ensure_mem((void **)&res->addrs, &res->cap, sizeof(*res->addrs), res->cnt + 1);
10607 	if (err)
10608 		return err;
10609 
10610 	res->addrs[res->cnt++] = (unsigned long)sym_addr;
10611 	return 0;
10612 }
10613 
10614 static int libbpf_available_kallsyms_parse(struct kprobe_multi_resolve *res)
10615 {
10616 	const char *available_functions_file = tracefs_available_filter_functions();
10617 	struct avail_kallsyms_data data;
10618 	char sym_name[500];
10619 	FILE *f;
10620 	int err = 0, ret, i;
10621 	char **syms = NULL;
10622 	size_t cap = 0, cnt = 0;
10623 
10624 	f = fopen(available_functions_file, "re");
10625 	if (!f) {
10626 		err = -errno;
10627 		pr_warn("failed to open %s: %d\n", available_functions_file, err);
10628 		return err;
10629 	}
10630 
10631 	while (true) {
10632 		char *name;
10633 
10634 		ret = fscanf(f, "%499s%*[^\n]\n", sym_name);
10635 		if (ret == EOF && feof(f))
10636 			break;
10637 
10638 		if (ret != 1) {
10639 			pr_warn("failed to parse available_filter_functions entry: %d\n", ret);
10640 			err = -EINVAL;
10641 			goto cleanup;
10642 		}
10643 
10644 		if (!glob_match(sym_name, res->pattern))
10645 			continue;
10646 
10647 		err = libbpf_ensure_mem((void **)&syms, &cap, sizeof(*syms), cnt + 1);
10648 		if (err)
10649 			goto cleanup;
10650 
10651 		name = strdup(sym_name);
10652 		if (!name) {
10653 			err = -errno;
10654 			goto cleanup;
10655 		}
10656 
10657 		syms[cnt++] = name;
10658 	}
10659 
10660 	/* no entries found, bail out */
10661 	if (cnt == 0) {
10662 		err = -ENOENT;
10663 		goto cleanup;
10664 	}
10665 
10666 	/* sort available functions */
10667 	qsort(syms, cnt, sizeof(*syms), avail_func_cmp);
10668 
10669 	data.syms = syms;
10670 	data.res = res;
10671 	data.cnt = cnt;
10672 	libbpf_kallsyms_parse(avail_kallsyms_cb, &data);
10673 
10674 	if (res->cnt == 0)
10675 		err = -ENOENT;
10676 
10677 cleanup:
10678 	for (i = 0; i < cnt; i++)
10679 		free((char *)syms[i]);
10680 	free(syms);
10681 
10682 	fclose(f);
10683 	return err;
10684 }
10685 
10686 static bool has_available_filter_functions_addrs(void)
10687 {
10688 	return access(tracefs_available_filter_functions_addrs(), R_OK) != -1;
10689 }
10690 
10691 static int libbpf_available_kprobes_parse(struct kprobe_multi_resolve *res)
10692 {
10693 	const char *available_path = tracefs_available_filter_functions_addrs();
10694 	char sym_name[500];
10695 	FILE *f;
10696 	int ret, err = 0;
10697 	unsigned long long sym_addr;
10698 
10699 	f = fopen(available_path, "re");
10700 	if (!f) {
10701 		err = -errno;
10702 		pr_warn("failed to open %s: %d\n", available_path, err);
10703 		return err;
10704 	}
10705 
10706 	while (true) {
10707 		ret = fscanf(f, "%llx %499s%*[^\n]\n", &sym_addr, sym_name);
10708 		if (ret == EOF && feof(f))
10709 			break;
10710 
10711 		if (ret != 2) {
10712 			pr_warn("failed to parse available_filter_functions_addrs entry: %d\n",
10713 				ret);
10714 			err = -EINVAL;
10715 			goto cleanup;
10716 		}
10717 
10718 		if (!glob_match(sym_name, res->pattern))
10719 			continue;
10720 
10721 		err = libbpf_ensure_mem((void **)&res->addrs, &res->cap,
10722 					sizeof(*res->addrs), res->cnt + 1);
10723 		if (err)
10724 			goto cleanup;
10725 
10726 		res->addrs[res->cnt++] = (unsigned long)sym_addr;
10727 	}
10728 
10729 	if (res->cnt == 0)
10730 		err = -ENOENT;
10731 
10732 cleanup:
10733 	fclose(f);
10734 	return err;
10735 }
10736 
10737 struct bpf_link *
10738 bpf_program__attach_kprobe_multi_opts(const struct bpf_program *prog,
10739 				      const char *pattern,
10740 				      const struct bpf_kprobe_multi_opts *opts)
10741 {
10742 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
10743 	struct kprobe_multi_resolve res = {
10744 		.pattern = pattern,
10745 	};
10746 	struct bpf_link *link = NULL;
10747 	char errmsg[STRERR_BUFSIZE];
10748 	const unsigned long *addrs;
10749 	int err, link_fd, prog_fd;
10750 	const __u64 *cookies;
10751 	const char **syms;
10752 	bool retprobe;
10753 	size_t cnt;
10754 
10755 	if (!OPTS_VALID(opts, bpf_kprobe_multi_opts))
10756 		return libbpf_err_ptr(-EINVAL);
10757 
10758 	syms    = OPTS_GET(opts, syms, false);
10759 	addrs   = OPTS_GET(opts, addrs, false);
10760 	cnt     = OPTS_GET(opts, cnt, false);
10761 	cookies = OPTS_GET(opts, cookies, false);
10762 
10763 	if (!pattern && !addrs && !syms)
10764 		return libbpf_err_ptr(-EINVAL);
10765 	if (pattern && (addrs || syms || cookies || cnt))
10766 		return libbpf_err_ptr(-EINVAL);
10767 	if (!pattern && !cnt)
10768 		return libbpf_err_ptr(-EINVAL);
10769 	if (addrs && syms)
10770 		return libbpf_err_ptr(-EINVAL);
10771 
10772 	if (pattern) {
10773 		if (has_available_filter_functions_addrs())
10774 			err = libbpf_available_kprobes_parse(&res);
10775 		else
10776 			err = libbpf_available_kallsyms_parse(&res);
10777 		if (err)
10778 			goto error;
10779 		addrs = res.addrs;
10780 		cnt = res.cnt;
10781 	}
10782 
10783 	retprobe = OPTS_GET(opts, retprobe, false);
10784 
10785 	lopts.kprobe_multi.syms = syms;
10786 	lopts.kprobe_multi.addrs = addrs;
10787 	lopts.kprobe_multi.cookies = cookies;
10788 	lopts.kprobe_multi.cnt = cnt;
10789 	lopts.kprobe_multi.flags = retprobe ? BPF_F_KPROBE_MULTI_RETURN : 0;
10790 
10791 	link = calloc(1, sizeof(*link));
10792 	if (!link) {
10793 		err = -ENOMEM;
10794 		goto error;
10795 	}
10796 	link->detach = &bpf_link__detach_fd;
10797 
10798 	prog_fd = bpf_program__fd(prog);
10799 	link_fd = bpf_link_create(prog_fd, 0, BPF_TRACE_KPROBE_MULTI, &lopts);
10800 	if (link_fd < 0) {
10801 		err = -errno;
10802 		pr_warn("prog '%s': failed to attach: %s\n",
10803 			prog->name, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10804 		goto error;
10805 	}
10806 	link->fd = link_fd;
10807 	free(res.addrs);
10808 	return link;
10809 
10810 error:
10811 	free(link);
10812 	free(res.addrs);
10813 	return libbpf_err_ptr(err);
10814 }
10815 
10816 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
10817 {
10818 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts);
10819 	unsigned long offset = 0;
10820 	const char *func_name;
10821 	char *func;
10822 	int n;
10823 
10824 	*link = NULL;
10825 
10826 	/* no auto-attach for SEC("kprobe") and SEC("kretprobe") */
10827 	if (strcmp(prog->sec_name, "kprobe") == 0 || strcmp(prog->sec_name, "kretprobe") == 0)
10828 		return 0;
10829 
10830 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe/");
10831 	if (opts.retprobe)
10832 		func_name = prog->sec_name + sizeof("kretprobe/") - 1;
10833 	else
10834 		func_name = prog->sec_name + sizeof("kprobe/") - 1;
10835 
10836 	n = sscanf(func_name, "%m[a-zA-Z0-9_.]+%li", &func, &offset);
10837 	if (n < 1) {
10838 		pr_warn("kprobe name is invalid: %s\n", func_name);
10839 		return -EINVAL;
10840 	}
10841 	if (opts.retprobe && offset != 0) {
10842 		free(func);
10843 		pr_warn("kretprobes do not support offset specification\n");
10844 		return -EINVAL;
10845 	}
10846 
10847 	opts.offset = offset;
10848 	*link = bpf_program__attach_kprobe_opts(prog, func, &opts);
10849 	free(func);
10850 	return libbpf_get_error(*link);
10851 }
10852 
10853 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link)
10854 {
10855 	LIBBPF_OPTS(bpf_ksyscall_opts, opts);
10856 	const char *syscall_name;
10857 
10858 	*link = NULL;
10859 
10860 	/* no auto-attach for SEC("ksyscall") and SEC("kretsyscall") */
10861 	if (strcmp(prog->sec_name, "ksyscall") == 0 || strcmp(prog->sec_name, "kretsyscall") == 0)
10862 		return 0;
10863 
10864 	opts.retprobe = str_has_pfx(prog->sec_name, "kretsyscall/");
10865 	if (opts.retprobe)
10866 		syscall_name = prog->sec_name + sizeof("kretsyscall/") - 1;
10867 	else
10868 		syscall_name = prog->sec_name + sizeof("ksyscall/") - 1;
10869 
10870 	*link = bpf_program__attach_ksyscall(prog, syscall_name, &opts);
10871 	return *link ? 0 : -errno;
10872 }
10873 
10874 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
10875 {
10876 	LIBBPF_OPTS(bpf_kprobe_multi_opts, opts);
10877 	const char *spec;
10878 	char *pattern;
10879 	int n;
10880 
10881 	*link = NULL;
10882 
10883 	/* no auto-attach for SEC("kprobe.multi") and SEC("kretprobe.multi") */
10884 	if (strcmp(prog->sec_name, "kprobe.multi") == 0 ||
10885 	    strcmp(prog->sec_name, "kretprobe.multi") == 0)
10886 		return 0;
10887 
10888 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe.multi/");
10889 	if (opts.retprobe)
10890 		spec = prog->sec_name + sizeof("kretprobe.multi/") - 1;
10891 	else
10892 		spec = prog->sec_name + sizeof("kprobe.multi/") - 1;
10893 
10894 	n = sscanf(spec, "%m[a-zA-Z0-9_.*?]", &pattern);
10895 	if (n < 1) {
10896 		pr_warn("kprobe multi pattern is invalid: %s\n", pattern);
10897 		return -EINVAL;
10898 	}
10899 
10900 	*link = bpf_program__attach_kprobe_multi_opts(prog, pattern, &opts);
10901 	free(pattern);
10902 	return libbpf_get_error(*link);
10903 }
10904 
10905 static void gen_uprobe_legacy_event_name(char *buf, size_t buf_sz,
10906 					 const char *binary_path, uint64_t offset)
10907 {
10908 	int i;
10909 
10910 	snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx", getpid(), binary_path, (size_t)offset);
10911 
10912 	/* sanitize binary_path in the probe name */
10913 	for (i = 0; buf[i]; i++) {
10914 		if (!isalnum(buf[i]))
10915 			buf[i] = '_';
10916 	}
10917 }
10918 
10919 static inline int add_uprobe_event_legacy(const char *probe_name, bool retprobe,
10920 					  const char *binary_path, size_t offset)
10921 {
10922 	return append_to_file(tracefs_uprobe_events(), "%c:%s/%s %s:0x%zx",
10923 			      retprobe ? 'r' : 'p',
10924 			      retprobe ? "uretprobes" : "uprobes",
10925 			      probe_name, binary_path, offset);
10926 }
10927 
10928 static inline int remove_uprobe_event_legacy(const char *probe_name, bool retprobe)
10929 {
10930 	return append_to_file(tracefs_uprobe_events(), "-:%s/%s",
10931 			      retprobe ? "uretprobes" : "uprobes", probe_name);
10932 }
10933 
10934 static int determine_uprobe_perf_type_legacy(const char *probe_name, bool retprobe)
10935 {
10936 	char file[512];
10937 
10938 	snprintf(file, sizeof(file), "%s/events/%s/%s/id",
10939 		 tracefs_path(), retprobe ? "uretprobes" : "uprobes", probe_name);
10940 
10941 	return parse_uint_from_file(file, "%d\n");
10942 }
10943 
10944 static int perf_event_uprobe_open_legacy(const char *probe_name, bool retprobe,
10945 					 const char *binary_path, size_t offset, int pid)
10946 {
10947 	const size_t attr_sz = sizeof(struct perf_event_attr);
10948 	struct perf_event_attr attr;
10949 	int type, pfd, err;
10950 
10951 	err = add_uprobe_event_legacy(probe_name, retprobe, binary_path, offset);
10952 	if (err < 0) {
10953 		pr_warn("failed to add legacy uprobe event for %s:0x%zx: %d\n",
10954 			binary_path, (size_t)offset, err);
10955 		return err;
10956 	}
10957 	type = determine_uprobe_perf_type_legacy(probe_name, retprobe);
10958 	if (type < 0) {
10959 		err = type;
10960 		pr_warn("failed to determine legacy uprobe event id for %s:0x%zx: %d\n",
10961 			binary_path, offset, err);
10962 		goto err_clean_legacy;
10963 	}
10964 
10965 	memset(&attr, 0, attr_sz);
10966 	attr.size = attr_sz;
10967 	attr.config = type;
10968 	attr.type = PERF_TYPE_TRACEPOINT;
10969 
10970 	pfd = syscall(__NR_perf_event_open, &attr,
10971 		      pid < 0 ? -1 : pid, /* pid */
10972 		      pid == -1 ? 0 : -1, /* cpu */
10973 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
10974 	if (pfd < 0) {
10975 		err = -errno;
10976 		pr_warn("legacy uprobe perf_event_open() failed: %d\n", err);
10977 		goto err_clean_legacy;
10978 	}
10979 	return pfd;
10980 
10981 err_clean_legacy:
10982 	/* Clear the newly added legacy uprobe_event */
10983 	remove_uprobe_event_legacy(probe_name, retprobe);
10984 	return err;
10985 }
10986 
10987 /* Return next ELF section of sh_type after scn, or first of that type if scn is NULL. */
10988 static Elf_Scn *elf_find_next_scn_by_type(Elf *elf, int sh_type, Elf_Scn *scn)
10989 {
10990 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
10991 		GElf_Shdr sh;
10992 
10993 		if (!gelf_getshdr(scn, &sh))
10994 			continue;
10995 		if (sh.sh_type == sh_type)
10996 			return scn;
10997 	}
10998 	return NULL;
10999 }
11000 
11001 /* Find offset of function name in the provided ELF object. "binary_path" is
11002  * the path to the ELF binary represented by "elf", and only used for error
11003  * reporting matters. "name" matches symbol name or name@@LIB for library
11004  * functions.
11005  */
11006 static long elf_find_func_offset(Elf *elf, const char *binary_path, const char *name)
11007 {
11008 	int i, sh_types[2] = { SHT_DYNSYM, SHT_SYMTAB };
11009 	bool is_shared_lib, is_name_qualified;
11010 	long ret = -ENOENT;
11011 	size_t name_len;
11012 	GElf_Ehdr ehdr;
11013 
11014 	if (!gelf_getehdr(elf, &ehdr)) {
11015 		pr_warn("elf: failed to get ehdr from %s: %s\n", binary_path, elf_errmsg(-1));
11016 		ret = -LIBBPF_ERRNO__FORMAT;
11017 		goto out;
11018 	}
11019 	/* for shared lib case, we do not need to calculate relative offset */
11020 	is_shared_lib = ehdr.e_type == ET_DYN;
11021 
11022 	name_len = strlen(name);
11023 	/* Does name specify "@@LIB"? */
11024 	is_name_qualified = strstr(name, "@@") != NULL;
11025 
11026 	/* Search SHT_DYNSYM, SHT_SYMTAB for symbol. This search order is used because if
11027 	 * a binary is stripped, it may only have SHT_DYNSYM, and a fully-statically
11028 	 * linked binary may not have SHT_DYMSYM, so absence of a section should not be
11029 	 * reported as a warning/error.
11030 	 */
11031 	for (i = 0; i < ARRAY_SIZE(sh_types); i++) {
11032 		size_t nr_syms, strtabidx, idx;
11033 		Elf_Data *symbols = NULL;
11034 		Elf_Scn *scn = NULL;
11035 		int last_bind = -1;
11036 		const char *sname;
11037 		GElf_Shdr sh;
11038 
11039 		scn = elf_find_next_scn_by_type(elf, sh_types[i], NULL);
11040 		if (!scn) {
11041 			pr_debug("elf: failed to find symbol table ELF sections in '%s'\n",
11042 				 binary_path);
11043 			continue;
11044 		}
11045 		if (!gelf_getshdr(scn, &sh))
11046 			continue;
11047 		strtabidx = sh.sh_link;
11048 		symbols = elf_getdata(scn, 0);
11049 		if (!symbols) {
11050 			pr_warn("elf: failed to get symbols for symtab section in '%s': %s\n",
11051 				binary_path, elf_errmsg(-1));
11052 			ret = -LIBBPF_ERRNO__FORMAT;
11053 			goto out;
11054 		}
11055 		nr_syms = symbols->d_size / sh.sh_entsize;
11056 
11057 		for (idx = 0; idx < nr_syms; idx++) {
11058 			int curr_bind;
11059 			GElf_Sym sym;
11060 			Elf_Scn *sym_scn;
11061 			GElf_Shdr sym_sh;
11062 
11063 			if (!gelf_getsym(symbols, idx, &sym))
11064 				continue;
11065 
11066 			if (GELF_ST_TYPE(sym.st_info) != STT_FUNC)
11067 				continue;
11068 
11069 			sname = elf_strptr(elf, strtabidx, sym.st_name);
11070 			if (!sname)
11071 				continue;
11072 
11073 			curr_bind = GELF_ST_BIND(sym.st_info);
11074 
11075 			/* User can specify func, func@@LIB or func@@LIB_VERSION. */
11076 			if (strncmp(sname, name, name_len) != 0)
11077 				continue;
11078 			/* ...but we don't want a search for "foo" to match 'foo2" also, so any
11079 			 * additional characters in sname should be of the form "@@LIB".
11080 			 */
11081 			if (!is_name_qualified && sname[name_len] != '\0' && sname[name_len] != '@')
11082 				continue;
11083 
11084 			if (ret >= 0) {
11085 				/* handle multiple matches */
11086 				if (last_bind != STB_WEAK && curr_bind != STB_WEAK) {
11087 					/* Only accept one non-weak bind. */
11088 					pr_warn("elf: ambiguous match for '%s', '%s' in '%s'\n",
11089 						sname, name, binary_path);
11090 					ret = -LIBBPF_ERRNO__FORMAT;
11091 					goto out;
11092 				} else if (curr_bind == STB_WEAK) {
11093 					/* already have a non-weak bind, and
11094 					 * this is a weak bind, so ignore.
11095 					 */
11096 					continue;
11097 				}
11098 			}
11099 
11100 			/* Transform symbol's virtual address (absolute for
11101 			 * binaries and relative for shared libs) into file
11102 			 * offset, which is what kernel is expecting for
11103 			 * uprobe/uretprobe attachment.
11104 			 * See Documentation/trace/uprobetracer.rst for more
11105 			 * details.
11106 			 * This is done by looking up symbol's containing
11107 			 * section's header and using it's virtual address
11108 			 * (sh_addr) and corresponding file offset (sh_offset)
11109 			 * to transform sym.st_value (virtual address) into
11110 			 * desired final file offset.
11111 			 */
11112 			sym_scn = elf_getscn(elf, sym.st_shndx);
11113 			if (!sym_scn)
11114 				continue;
11115 			if (!gelf_getshdr(sym_scn, &sym_sh))
11116 				continue;
11117 
11118 			ret = sym.st_value - sym_sh.sh_addr + sym_sh.sh_offset;
11119 			last_bind = curr_bind;
11120 		}
11121 		if (ret > 0)
11122 			break;
11123 	}
11124 
11125 	if (ret > 0) {
11126 		pr_debug("elf: symbol address match for '%s' in '%s': 0x%lx\n", name, binary_path,
11127 			 ret);
11128 	} else {
11129 		if (ret == 0) {
11130 			pr_warn("elf: '%s' is 0 in symtab for '%s': %s\n", name, binary_path,
11131 				is_shared_lib ? "should not be 0 in a shared library" :
11132 						"try using shared library path instead");
11133 			ret = -ENOENT;
11134 		} else {
11135 			pr_warn("elf: failed to find symbol '%s' in '%s'\n", name, binary_path);
11136 		}
11137 	}
11138 out:
11139 	return ret;
11140 }
11141 
11142 /* Find offset of function name in ELF object specified by path. "name" matches
11143  * symbol name or name@@LIB for library functions.
11144  */
11145 static long elf_find_func_offset_from_file(const char *binary_path, const char *name)
11146 {
11147 	char errmsg[STRERR_BUFSIZE];
11148 	long ret = -ENOENT;
11149 	Elf *elf;
11150 	int fd;
11151 
11152 	fd = open(binary_path, O_RDONLY | O_CLOEXEC);
11153 	if (fd < 0) {
11154 		ret = -errno;
11155 		pr_warn("failed to open %s: %s\n", binary_path,
11156 			libbpf_strerror_r(ret, errmsg, sizeof(errmsg)));
11157 		return ret;
11158 	}
11159 	elf = elf_begin(fd, ELF_C_READ_MMAP, NULL);
11160 	if (!elf) {
11161 		pr_warn("elf: could not read elf from %s: %s\n", binary_path, elf_errmsg(-1));
11162 		close(fd);
11163 		return -LIBBPF_ERRNO__FORMAT;
11164 	}
11165 
11166 	ret = elf_find_func_offset(elf, binary_path, name);
11167 	elf_end(elf);
11168 	close(fd);
11169 	return ret;
11170 }
11171 
11172 /* Find offset of function name in archive specified by path. Currently
11173  * supported are .zip files that do not compress their contents, as used on
11174  * Android in the form of APKs, for example. "file_name" is the name of the ELF
11175  * file inside the archive. "func_name" matches symbol name or name@@LIB for
11176  * library functions.
11177  *
11178  * An overview of the APK format specifically provided here:
11179  * https://en.wikipedia.org/w/index.php?title=Apk_(file_format)&oldid=1139099120#Package_contents
11180  */
11181 static long elf_find_func_offset_from_archive(const char *archive_path, const char *file_name,
11182 					      const char *func_name)
11183 {
11184 	struct zip_archive *archive;
11185 	struct zip_entry entry;
11186 	long ret;
11187 	Elf *elf;
11188 
11189 	archive = zip_archive_open(archive_path);
11190 	if (IS_ERR(archive)) {
11191 		ret = PTR_ERR(archive);
11192 		pr_warn("zip: failed to open %s: %ld\n", archive_path, ret);
11193 		return ret;
11194 	}
11195 
11196 	ret = zip_archive_find_entry(archive, file_name, &entry);
11197 	if (ret) {
11198 		pr_warn("zip: could not find archive member %s in %s: %ld\n", file_name,
11199 			archive_path, ret);
11200 		goto out;
11201 	}
11202 	pr_debug("zip: found entry for %s in %s at 0x%lx\n", file_name, archive_path,
11203 		 (unsigned long)entry.data_offset);
11204 
11205 	if (entry.compression) {
11206 		pr_warn("zip: entry %s of %s is compressed and cannot be handled\n", file_name,
11207 			archive_path);
11208 		ret = -LIBBPF_ERRNO__FORMAT;
11209 		goto out;
11210 	}
11211 
11212 	elf = elf_memory((void *)entry.data, entry.data_length);
11213 	if (!elf) {
11214 		pr_warn("elf: could not read elf file %s from %s: %s\n", file_name, archive_path,
11215 			elf_errmsg(-1));
11216 		ret = -LIBBPF_ERRNO__LIBELF;
11217 		goto out;
11218 	}
11219 
11220 	ret = elf_find_func_offset(elf, file_name, func_name);
11221 	if (ret > 0) {
11222 		pr_debug("elf: symbol address match for %s of %s in %s: 0x%x + 0x%lx = 0x%lx\n",
11223 			 func_name, file_name, archive_path, entry.data_offset, ret,
11224 			 ret + entry.data_offset);
11225 		ret += entry.data_offset;
11226 	}
11227 	elf_end(elf);
11228 
11229 out:
11230 	zip_archive_close(archive);
11231 	return ret;
11232 }
11233 
11234 static const char *arch_specific_lib_paths(void)
11235 {
11236 	/*
11237 	 * Based on https://packages.debian.org/sid/libc6.
11238 	 *
11239 	 * Assume that the traced program is built for the same architecture
11240 	 * as libbpf, which should cover the vast majority of cases.
11241 	 */
11242 #if defined(__x86_64__)
11243 	return "/lib/x86_64-linux-gnu";
11244 #elif defined(__i386__)
11245 	return "/lib/i386-linux-gnu";
11246 #elif defined(__s390x__)
11247 	return "/lib/s390x-linux-gnu";
11248 #elif defined(__s390__)
11249 	return "/lib/s390-linux-gnu";
11250 #elif defined(__arm__) && defined(__SOFTFP__)
11251 	return "/lib/arm-linux-gnueabi";
11252 #elif defined(__arm__) && !defined(__SOFTFP__)
11253 	return "/lib/arm-linux-gnueabihf";
11254 #elif defined(__aarch64__)
11255 	return "/lib/aarch64-linux-gnu";
11256 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 64
11257 	return "/lib/mips64el-linux-gnuabi64";
11258 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 32
11259 	return "/lib/mipsel-linux-gnu";
11260 #elif defined(__powerpc64__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
11261 	return "/lib/powerpc64le-linux-gnu";
11262 #elif defined(__sparc__) && defined(__arch64__)
11263 	return "/lib/sparc64-linux-gnu";
11264 #elif defined(__riscv) && __riscv_xlen == 64
11265 	return "/lib/riscv64-linux-gnu";
11266 #else
11267 	return NULL;
11268 #endif
11269 }
11270 
11271 /* Get full path to program/shared library. */
11272 static int resolve_full_path(const char *file, char *result, size_t result_sz)
11273 {
11274 	const char *search_paths[3] = {};
11275 	int i, perm;
11276 
11277 	if (str_has_sfx(file, ".so") || strstr(file, ".so.")) {
11278 		search_paths[0] = getenv("LD_LIBRARY_PATH");
11279 		search_paths[1] = "/usr/lib64:/usr/lib";
11280 		search_paths[2] = arch_specific_lib_paths();
11281 		perm = R_OK;
11282 	} else {
11283 		search_paths[0] = getenv("PATH");
11284 		search_paths[1] = "/usr/bin:/usr/sbin";
11285 		perm = R_OK | X_OK;
11286 	}
11287 
11288 	for (i = 0; i < ARRAY_SIZE(search_paths); i++) {
11289 		const char *s;
11290 
11291 		if (!search_paths[i])
11292 			continue;
11293 		for (s = search_paths[i]; s != NULL; s = strchr(s, ':')) {
11294 			char *next_path;
11295 			int seg_len;
11296 
11297 			if (s[0] == ':')
11298 				s++;
11299 			next_path = strchr(s, ':');
11300 			seg_len = next_path ? next_path - s : strlen(s);
11301 			if (!seg_len)
11302 				continue;
11303 			snprintf(result, result_sz, "%.*s/%s", seg_len, s, file);
11304 			/* ensure it has required permissions */
11305 			if (faccessat(AT_FDCWD, result, perm, AT_EACCESS) < 0)
11306 				continue;
11307 			pr_debug("resolved '%s' to '%s'\n", file, result);
11308 			return 0;
11309 		}
11310 	}
11311 	return -ENOENT;
11312 }
11313 
11314 LIBBPF_API struct bpf_link *
11315 bpf_program__attach_uprobe_opts(const struct bpf_program *prog, pid_t pid,
11316 				const char *binary_path, size_t func_offset,
11317 				const struct bpf_uprobe_opts *opts)
11318 {
11319 	const char *archive_path = NULL, *archive_sep = NULL;
11320 	char errmsg[STRERR_BUFSIZE], *legacy_probe = NULL;
11321 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
11322 	enum probe_attach_mode attach_mode;
11323 	char full_path[PATH_MAX];
11324 	struct bpf_link *link;
11325 	size_t ref_ctr_off;
11326 	int pfd, err;
11327 	bool retprobe, legacy;
11328 	const char *func_name;
11329 
11330 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
11331 		return libbpf_err_ptr(-EINVAL);
11332 
11333 	attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
11334 	retprobe = OPTS_GET(opts, retprobe, false);
11335 	ref_ctr_off = OPTS_GET(opts, ref_ctr_offset, 0);
11336 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11337 
11338 	if (!binary_path)
11339 		return libbpf_err_ptr(-EINVAL);
11340 
11341 	/* Check if "binary_path" refers to an archive. */
11342 	archive_sep = strstr(binary_path, "!/");
11343 	if (archive_sep) {
11344 		full_path[0] = '\0';
11345 		libbpf_strlcpy(full_path, binary_path,
11346 			       min(sizeof(full_path), (size_t)(archive_sep - binary_path + 1)));
11347 		archive_path = full_path;
11348 		binary_path = archive_sep + 2;
11349 	} else if (!strchr(binary_path, '/')) {
11350 		err = resolve_full_path(binary_path, full_path, sizeof(full_path));
11351 		if (err) {
11352 			pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
11353 				prog->name, binary_path, err);
11354 			return libbpf_err_ptr(err);
11355 		}
11356 		binary_path = full_path;
11357 	}
11358 	func_name = OPTS_GET(opts, func_name, NULL);
11359 	if (func_name) {
11360 		long sym_off;
11361 
11362 		if (archive_path) {
11363 			sym_off = elf_find_func_offset_from_archive(archive_path, binary_path,
11364 								    func_name);
11365 			binary_path = archive_path;
11366 		} else {
11367 			sym_off = elf_find_func_offset_from_file(binary_path, func_name);
11368 		}
11369 		if (sym_off < 0)
11370 			return libbpf_err_ptr(sym_off);
11371 		func_offset += sym_off;
11372 	}
11373 
11374 	legacy = determine_uprobe_perf_type() < 0;
11375 	switch (attach_mode) {
11376 	case PROBE_ATTACH_MODE_LEGACY:
11377 		legacy = true;
11378 		pe_opts.force_ioctl_attach = true;
11379 		break;
11380 	case PROBE_ATTACH_MODE_PERF:
11381 		if (legacy)
11382 			return libbpf_err_ptr(-ENOTSUP);
11383 		pe_opts.force_ioctl_attach = true;
11384 		break;
11385 	case PROBE_ATTACH_MODE_LINK:
11386 		if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
11387 			return libbpf_err_ptr(-ENOTSUP);
11388 		break;
11389 	case PROBE_ATTACH_MODE_DEFAULT:
11390 		break;
11391 	default:
11392 		return libbpf_err_ptr(-EINVAL);
11393 	}
11394 
11395 	if (!legacy) {
11396 		pfd = perf_event_open_probe(true /* uprobe */, retprobe, binary_path,
11397 					    func_offset, pid, ref_ctr_off);
11398 	} else {
11399 		char probe_name[PATH_MAX + 64];
11400 
11401 		if (ref_ctr_off)
11402 			return libbpf_err_ptr(-EINVAL);
11403 
11404 		gen_uprobe_legacy_event_name(probe_name, sizeof(probe_name),
11405 					     binary_path, func_offset);
11406 
11407 		legacy_probe = strdup(probe_name);
11408 		if (!legacy_probe)
11409 			return libbpf_err_ptr(-ENOMEM);
11410 
11411 		pfd = perf_event_uprobe_open_legacy(legacy_probe, retprobe,
11412 						    binary_path, func_offset, pid);
11413 	}
11414 	if (pfd < 0) {
11415 		err = -errno;
11416 		pr_warn("prog '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
11417 			prog->name, retprobe ? "uretprobe" : "uprobe",
11418 			binary_path, func_offset,
11419 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11420 		goto err_out;
11421 	}
11422 
11423 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
11424 	err = libbpf_get_error(link);
11425 	if (err) {
11426 		close(pfd);
11427 		pr_warn("prog '%s': failed to attach to %s '%s:0x%zx': %s\n",
11428 			prog->name, retprobe ? "uretprobe" : "uprobe",
11429 			binary_path, func_offset,
11430 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11431 		goto err_clean_legacy;
11432 	}
11433 	if (legacy) {
11434 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
11435 
11436 		perf_link->legacy_probe_name = legacy_probe;
11437 		perf_link->legacy_is_kprobe = false;
11438 		perf_link->legacy_is_retprobe = retprobe;
11439 	}
11440 	return link;
11441 
11442 err_clean_legacy:
11443 	if (legacy)
11444 		remove_uprobe_event_legacy(legacy_probe, retprobe);
11445 err_out:
11446 	free(legacy_probe);
11447 	return libbpf_err_ptr(err);
11448 }
11449 
11450 /* Format of u[ret]probe section definition supporting auto-attach:
11451  * u[ret]probe/binary:function[+offset]
11452  *
11453  * binary can be an absolute/relative path or a filename; the latter is resolved to a
11454  * full binary path via bpf_program__attach_uprobe_opts.
11455  *
11456  * Specifying uprobe+ ensures we carry out strict matching; either "uprobe" must be
11457  * specified (and auto-attach is not possible) or the above format is specified for
11458  * auto-attach.
11459  */
11460 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11461 {
11462 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts);
11463 	char *probe_type = NULL, *binary_path = NULL, *func_name = NULL;
11464 	int n, ret = -EINVAL;
11465 	long offset = 0;
11466 
11467 	*link = NULL;
11468 
11469 	n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[a-zA-Z0-9_.]+%li",
11470 		   &probe_type, &binary_path, &func_name, &offset);
11471 	switch (n) {
11472 	case 1:
11473 		/* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
11474 		ret = 0;
11475 		break;
11476 	case 2:
11477 		pr_warn("prog '%s': section '%s' missing ':function[+offset]' specification\n",
11478 			prog->name, prog->sec_name);
11479 		break;
11480 	case 3:
11481 	case 4:
11482 		opts.retprobe = strcmp(probe_type, "uretprobe") == 0 ||
11483 				strcmp(probe_type, "uretprobe.s") == 0;
11484 		if (opts.retprobe && offset != 0) {
11485 			pr_warn("prog '%s': uretprobes do not support offset specification\n",
11486 				prog->name);
11487 			break;
11488 		}
11489 		opts.func_name = func_name;
11490 		*link = bpf_program__attach_uprobe_opts(prog, -1, binary_path, offset, &opts);
11491 		ret = libbpf_get_error(*link);
11492 		break;
11493 	default:
11494 		pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
11495 			prog->sec_name);
11496 		break;
11497 	}
11498 	free(probe_type);
11499 	free(binary_path);
11500 	free(func_name);
11501 
11502 	return ret;
11503 }
11504 
11505 struct bpf_link *bpf_program__attach_uprobe(const struct bpf_program *prog,
11506 					    bool retprobe, pid_t pid,
11507 					    const char *binary_path,
11508 					    size_t func_offset)
11509 {
11510 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts, .retprobe = retprobe);
11511 
11512 	return bpf_program__attach_uprobe_opts(prog, pid, binary_path, func_offset, &opts);
11513 }
11514 
11515 struct bpf_link *bpf_program__attach_usdt(const struct bpf_program *prog,
11516 					  pid_t pid, const char *binary_path,
11517 					  const char *usdt_provider, const char *usdt_name,
11518 					  const struct bpf_usdt_opts *opts)
11519 {
11520 	char resolved_path[512];
11521 	struct bpf_object *obj = prog->obj;
11522 	struct bpf_link *link;
11523 	__u64 usdt_cookie;
11524 	int err;
11525 
11526 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
11527 		return libbpf_err_ptr(-EINVAL);
11528 
11529 	if (bpf_program__fd(prog) < 0) {
11530 		pr_warn("prog '%s': can't attach BPF program w/o FD (did you load it?)\n",
11531 			prog->name);
11532 		return libbpf_err_ptr(-EINVAL);
11533 	}
11534 
11535 	if (!binary_path)
11536 		return libbpf_err_ptr(-EINVAL);
11537 
11538 	if (!strchr(binary_path, '/')) {
11539 		err = resolve_full_path(binary_path, resolved_path, sizeof(resolved_path));
11540 		if (err) {
11541 			pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
11542 				prog->name, binary_path, err);
11543 			return libbpf_err_ptr(err);
11544 		}
11545 		binary_path = resolved_path;
11546 	}
11547 
11548 	/* USDT manager is instantiated lazily on first USDT attach. It will
11549 	 * be destroyed together with BPF object in bpf_object__close().
11550 	 */
11551 	if (IS_ERR(obj->usdt_man))
11552 		return libbpf_ptr(obj->usdt_man);
11553 	if (!obj->usdt_man) {
11554 		obj->usdt_man = usdt_manager_new(obj);
11555 		if (IS_ERR(obj->usdt_man))
11556 			return libbpf_ptr(obj->usdt_man);
11557 	}
11558 
11559 	usdt_cookie = OPTS_GET(opts, usdt_cookie, 0);
11560 	link = usdt_manager_attach_usdt(obj->usdt_man, prog, pid, binary_path,
11561 					usdt_provider, usdt_name, usdt_cookie);
11562 	err = libbpf_get_error(link);
11563 	if (err)
11564 		return libbpf_err_ptr(err);
11565 	return link;
11566 }
11567 
11568 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11569 {
11570 	char *path = NULL, *provider = NULL, *name = NULL;
11571 	const char *sec_name;
11572 	int n, err;
11573 
11574 	sec_name = bpf_program__section_name(prog);
11575 	if (strcmp(sec_name, "usdt") == 0) {
11576 		/* no auto-attach for just SEC("usdt") */
11577 		*link = NULL;
11578 		return 0;
11579 	}
11580 
11581 	n = sscanf(sec_name, "usdt/%m[^:]:%m[^:]:%m[^:]", &path, &provider, &name);
11582 	if (n != 3) {
11583 		pr_warn("invalid section '%s', expected SEC(\"usdt/<path>:<provider>:<name>\")\n",
11584 			sec_name);
11585 		err = -EINVAL;
11586 	} else {
11587 		*link = bpf_program__attach_usdt(prog, -1 /* any process */, path,
11588 						 provider, name, NULL);
11589 		err = libbpf_get_error(*link);
11590 	}
11591 	free(path);
11592 	free(provider);
11593 	free(name);
11594 	return err;
11595 }
11596 
11597 static int determine_tracepoint_id(const char *tp_category,
11598 				   const char *tp_name)
11599 {
11600 	char file[PATH_MAX];
11601 	int ret;
11602 
11603 	ret = snprintf(file, sizeof(file), "%s/events/%s/%s/id",
11604 		       tracefs_path(), tp_category, tp_name);
11605 	if (ret < 0)
11606 		return -errno;
11607 	if (ret >= sizeof(file)) {
11608 		pr_debug("tracepoint %s/%s path is too long\n",
11609 			 tp_category, tp_name);
11610 		return -E2BIG;
11611 	}
11612 	return parse_uint_from_file(file, "%d\n");
11613 }
11614 
11615 static int perf_event_open_tracepoint(const char *tp_category,
11616 				      const char *tp_name)
11617 {
11618 	const size_t attr_sz = sizeof(struct perf_event_attr);
11619 	struct perf_event_attr attr;
11620 	char errmsg[STRERR_BUFSIZE];
11621 	int tp_id, pfd, err;
11622 
11623 	tp_id = determine_tracepoint_id(tp_category, tp_name);
11624 	if (tp_id < 0) {
11625 		pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
11626 			tp_category, tp_name,
11627 			libbpf_strerror_r(tp_id, errmsg, sizeof(errmsg)));
11628 		return tp_id;
11629 	}
11630 
11631 	memset(&attr, 0, attr_sz);
11632 	attr.type = PERF_TYPE_TRACEPOINT;
11633 	attr.size = attr_sz;
11634 	attr.config = tp_id;
11635 
11636 	pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
11637 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
11638 	if (pfd < 0) {
11639 		err = -errno;
11640 		pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
11641 			tp_category, tp_name,
11642 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11643 		return err;
11644 	}
11645 	return pfd;
11646 }
11647 
11648 struct bpf_link *bpf_program__attach_tracepoint_opts(const struct bpf_program *prog,
11649 						     const char *tp_category,
11650 						     const char *tp_name,
11651 						     const struct bpf_tracepoint_opts *opts)
11652 {
11653 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
11654 	char errmsg[STRERR_BUFSIZE];
11655 	struct bpf_link *link;
11656 	int pfd, err;
11657 
11658 	if (!OPTS_VALID(opts, bpf_tracepoint_opts))
11659 		return libbpf_err_ptr(-EINVAL);
11660 
11661 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11662 
11663 	pfd = perf_event_open_tracepoint(tp_category, tp_name);
11664 	if (pfd < 0) {
11665 		pr_warn("prog '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
11666 			prog->name, tp_category, tp_name,
11667 			libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
11668 		return libbpf_err_ptr(pfd);
11669 	}
11670 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
11671 	err = libbpf_get_error(link);
11672 	if (err) {
11673 		close(pfd);
11674 		pr_warn("prog '%s': failed to attach to tracepoint '%s/%s': %s\n",
11675 			prog->name, tp_category, tp_name,
11676 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11677 		return libbpf_err_ptr(err);
11678 	}
11679 	return link;
11680 }
11681 
11682 struct bpf_link *bpf_program__attach_tracepoint(const struct bpf_program *prog,
11683 						const char *tp_category,
11684 						const char *tp_name)
11685 {
11686 	return bpf_program__attach_tracepoint_opts(prog, tp_category, tp_name, NULL);
11687 }
11688 
11689 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11690 {
11691 	char *sec_name, *tp_cat, *tp_name;
11692 
11693 	*link = NULL;
11694 
11695 	/* no auto-attach for SEC("tp") or SEC("tracepoint") */
11696 	if (strcmp(prog->sec_name, "tp") == 0 || strcmp(prog->sec_name, "tracepoint") == 0)
11697 		return 0;
11698 
11699 	sec_name = strdup(prog->sec_name);
11700 	if (!sec_name)
11701 		return -ENOMEM;
11702 
11703 	/* extract "tp/<category>/<name>" or "tracepoint/<category>/<name>" */
11704 	if (str_has_pfx(prog->sec_name, "tp/"))
11705 		tp_cat = sec_name + sizeof("tp/") - 1;
11706 	else
11707 		tp_cat = sec_name + sizeof("tracepoint/") - 1;
11708 	tp_name = strchr(tp_cat, '/');
11709 	if (!tp_name) {
11710 		free(sec_name);
11711 		return -EINVAL;
11712 	}
11713 	*tp_name = '\0';
11714 	tp_name++;
11715 
11716 	*link = bpf_program__attach_tracepoint(prog, tp_cat, tp_name);
11717 	free(sec_name);
11718 	return libbpf_get_error(*link);
11719 }
11720 
11721 struct bpf_link *bpf_program__attach_raw_tracepoint(const struct bpf_program *prog,
11722 						    const char *tp_name)
11723 {
11724 	char errmsg[STRERR_BUFSIZE];
11725 	struct bpf_link *link;
11726 	int prog_fd, pfd;
11727 
11728 	prog_fd = bpf_program__fd(prog);
11729 	if (prog_fd < 0) {
11730 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
11731 		return libbpf_err_ptr(-EINVAL);
11732 	}
11733 
11734 	link = calloc(1, sizeof(*link));
11735 	if (!link)
11736 		return libbpf_err_ptr(-ENOMEM);
11737 	link->detach = &bpf_link__detach_fd;
11738 
11739 	pfd = bpf_raw_tracepoint_open(tp_name, prog_fd);
11740 	if (pfd < 0) {
11741 		pfd = -errno;
11742 		free(link);
11743 		pr_warn("prog '%s': failed to attach to raw tracepoint '%s': %s\n",
11744 			prog->name, tp_name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
11745 		return libbpf_err_ptr(pfd);
11746 	}
11747 	link->fd = pfd;
11748 	return link;
11749 }
11750 
11751 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11752 {
11753 	static const char *const prefixes[] = {
11754 		"raw_tp",
11755 		"raw_tracepoint",
11756 		"raw_tp.w",
11757 		"raw_tracepoint.w",
11758 	};
11759 	size_t i;
11760 	const char *tp_name = NULL;
11761 
11762 	*link = NULL;
11763 
11764 	for (i = 0; i < ARRAY_SIZE(prefixes); i++) {
11765 		size_t pfx_len;
11766 
11767 		if (!str_has_pfx(prog->sec_name, prefixes[i]))
11768 			continue;
11769 
11770 		pfx_len = strlen(prefixes[i]);
11771 		/* no auto-attach case of, e.g., SEC("raw_tp") */
11772 		if (prog->sec_name[pfx_len] == '\0')
11773 			return 0;
11774 
11775 		if (prog->sec_name[pfx_len] != '/')
11776 			continue;
11777 
11778 		tp_name = prog->sec_name + pfx_len + 1;
11779 		break;
11780 	}
11781 
11782 	if (!tp_name) {
11783 		pr_warn("prog '%s': invalid section name '%s'\n",
11784 			prog->name, prog->sec_name);
11785 		return -EINVAL;
11786 	}
11787 
11788 	*link = bpf_program__attach_raw_tracepoint(prog, tp_name);
11789 	return libbpf_get_error(*link);
11790 }
11791 
11792 /* Common logic for all BPF program types that attach to a btf_id */
11793 static struct bpf_link *bpf_program__attach_btf_id(const struct bpf_program *prog,
11794 						   const struct bpf_trace_opts *opts)
11795 {
11796 	LIBBPF_OPTS(bpf_link_create_opts, link_opts);
11797 	char errmsg[STRERR_BUFSIZE];
11798 	struct bpf_link *link;
11799 	int prog_fd, pfd;
11800 
11801 	if (!OPTS_VALID(opts, bpf_trace_opts))
11802 		return libbpf_err_ptr(-EINVAL);
11803 
11804 	prog_fd = bpf_program__fd(prog);
11805 	if (prog_fd < 0) {
11806 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
11807 		return libbpf_err_ptr(-EINVAL);
11808 	}
11809 
11810 	link = calloc(1, sizeof(*link));
11811 	if (!link)
11812 		return libbpf_err_ptr(-ENOMEM);
11813 	link->detach = &bpf_link__detach_fd;
11814 
11815 	/* libbpf is smart enough to redirect to BPF_RAW_TRACEPOINT_OPEN on old kernels */
11816 	link_opts.tracing.cookie = OPTS_GET(opts, cookie, 0);
11817 	pfd = bpf_link_create(prog_fd, 0, bpf_program__expected_attach_type(prog), &link_opts);
11818 	if (pfd < 0) {
11819 		pfd = -errno;
11820 		free(link);
11821 		pr_warn("prog '%s': failed to attach: %s\n",
11822 			prog->name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
11823 		return libbpf_err_ptr(pfd);
11824 	}
11825 	link->fd = pfd;
11826 	return link;
11827 }
11828 
11829 struct bpf_link *bpf_program__attach_trace(const struct bpf_program *prog)
11830 {
11831 	return bpf_program__attach_btf_id(prog, NULL);
11832 }
11833 
11834 struct bpf_link *bpf_program__attach_trace_opts(const struct bpf_program *prog,
11835 						const struct bpf_trace_opts *opts)
11836 {
11837 	return bpf_program__attach_btf_id(prog, opts);
11838 }
11839 
11840 struct bpf_link *bpf_program__attach_lsm(const struct bpf_program *prog)
11841 {
11842 	return bpf_program__attach_btf_id(prog, NULL);
11843 }
11844 
11845 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11846 {
11847 	*link = bpf_program__attach_trace(prog);
11848 	return libbpf_get_error(*link);
11849 }
11850 
11851 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11852 {
11853 	*link = bpf_program__attach_lsm(prog);
11854 	return libbpf_get_error(*link);
11855 }
11856 
11857 static struct bpf_link *
11858 bpf_program_attach_fd(const struct bpf_program *prog,
11859 		      int target_fd, const char *target_name,
11860 		      const struct bpf_link_create_opts *opts)
11861 {
11862 	enum bpf_attach_type attach_type;
11863 	char errmsg[STRERR_BUFSIZE];
11864 	struct bpf_link *link;
11865 	int prog_fd, link_fd;
11866 
11867 	prog_fd = bpf_program__fd(prog);
11868 	if (prog_fd < 0) {
11869 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
11870 		return libbpf_err_ptr(-EINVAL);
11871 	}
11872 
11873 	link = calloc(1, sizeof(*link));
11874 	if (!link)
11875 		return libbpf_err_ptr(-ENOMEM);
11876 	link->detach = &bpf_link__detach_fd;
11877 
11878 	attach_type = bpf_program__expected_attach_type(prog);
11879 	link_fd = bpf_link_create(prog_fd, target_fd, attach_type, opts);
11880 	if (link_fd < 0) {
11881 		link_fd = -errno;
11882 		free(link);
11883 		pr_warn("prog '%s': failed to attach to %s: %s\n",
11884 			prog->name, target_name,
11885 			libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
11886 		return libbpf_err_ptr(link_fd);
11887 	}
11888 	link->fd = link_fd;
11889 	return link;
11890 }
11891 
11892 struct bpf_link *
11893 bpf_program__attach_cgroup(const struct bpf_program *prog, int cgroup_fd)
11894 {
11895 	return bpf_program_attach_fd(prog, cgroup_fd, "cgroup", NULL);
11896 }
11897 
11898 struct bpf_link *
11899 bpf_program__attach_netns(const struct bpf_program *prog, int netns_fd)
11900 {
11901 	return bpf_program_attach_fd(prog, netns_fd, "netns", NULL);
11902 }
11903 
11904 struct bpf_link *bpf_program__attach_xdp(const struct bpf_program *prog, int ifindex)
11905 {
11906 	/* target_fd/target_ifindex use the same field in LINK_CREATE */
11907 	return bpf_program_attach_fd(prog, ifindex, "xdp", NULL);
11908 }
11909 
11910 struct bpf_link *
11911 bpf_program__attach_tcx(const struct bpf_program *prog, int ifindex,
11912 			const struct bpf_tcx_opts *opts)
11913 {
11914 	LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
11915 	__u32 relative_id;
11916 	int relative_fd;
11917 
11918 	if (!OPTS_VALID(opts, bpf_tcx_opts))
11919 		return libbpf_err_ptr(-EINVAL);
11920 
11921 	relative_id = OPTS_GET(opts, relative_id, 0);
11922 	relative_fd = OPTS_GET(opts, relative_fd, 0);
11923 
11924 	/* validate we don't have unexpected combinations of non-zero fields */
11925 	if (!ifindex) {
11926 		pr_warn("prog '%s': target netdevice ifindex cannot be zero\n",
11927 			prog->name);
11928 		return libbpf_err_ptr(-EINVAL);
11929 	}
11930 	if (relative_fd && relative_id) {
11931 		pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
11932 			prog->name);
11933 		return libbpf_err_ptr(-EINVAL);
11934 	}
11935 
11936 	link_create_opts.tcx.expected_revision = OPTS_GET(opts, expected_revision, 0);
11937 	link_create_opts.tcx.relative_fd = relative_fd;
11938 	link_create_opts.tcx.relative_id = relative_id;
11939 	link_create_opts.flags = OPTS_GET(opts, flags, 0);
11940 
11941 	/* target_fd/target_ifindex use the same field in LINK_CREATE */
11942 	return bpf_program_attach_fd(prog, ifindex, "tcx", &link_create_opts);
11943 }
11944 
11945 struct bpf_link *bpf_program__attach_freplace(const struct bpf_program *prog,
11946 					      int target_fd,
11947 					      const char *attach_func_name)
11948 {
11949 	int btf_id;
11950 
11951 	if (!!target_fd != !!attach_func_name) {
11952 		pr_warn("prog '%s': supply none or both of target_fd and attach_func_name\n",
11953 			prog->name);
11954 		return libbpf_err_ptr(-EINVAL);
11955 	}
11956 
11957 	if (prog->type != BPF_PROG_TYPE_EXT) {
11958 		pr_warn("prog '%s': only BPF_PROG_TYPE_EXT can attach as freplace",
11959 			prog->name);
11960 		return libbpf_err_ptr(-EINVAL);
11961 	}
11962 
11963 	if (target_fd) {
11964 		LIBBPF_OPTS(bpf_link_create_opts, target_opts);
11965 
11966 		btf_id = libbpf_find_prog_btf_id(attach_func_name, target_fd);
11967 		if (btf_id < 0)
11968 			return libbpf_err_ptr(btf_id);
11969 
11970 		target_opts.target_btf_id = btf_id;
11971 
11972 		return bpf_program_attach_fd(prog, target_fd, "freplace",
11973 					     &target_opts);
11974 	} else {
11975 		/* no target, so use raw_tracepoint_open for compatibility
11976 		 * with old kernels
11977 		 */
11978 		return bpf_program__attach_trace(prog);
11979 	}
11980 }
11981 
11982 struct bpf_link *
11983 bpf_program__attach_iter(const struct bpf_program *prog,
11984 			 const struct bpf_iter_attach_opts *opts)
11985 {
11986 	DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
11987 	char errmsg[STRERR_BUFSIZE];
11988 	struct bpf_link *link;
11989 	int prog_fd, link_fd;
11990 	__u32 target_fd = 0;
11991 
11992 	if (!OPTS_VALID(opts, bpf_iter_attach_opts))
11993 		return libbpf_err_ptr(-EINVAL);
11994 
11995 	link_create_opts.iter_info = OPTS_GET(opts, link_info, (void *)0);
11996 	link_create_opts.iter_info_len = OPTS_GET(opts, link_info_len, 0);
11997 
11998 	prog_fd = bpf_program__fd(prog);
11999 	if (prog_fd < 0) {
12000 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12001 		return libbpf_err_ptr(-EINVAL);
12002 	}
12003 
12004 	link = calloc(1, sizeof(*link));
12005 	if (!link)
12006 		return libbpf_err_ptr(-ENOMEM);
12007 	link->detach = &bpf_link__detach_fd;
12008 
12009 	link_fd = bpf_link_create(prog_fd, target_fd, BPF_TRACE_ITER,
12010 				  &link_create_opts);
12011 	if (link_fd < 0) {
12012 		link_fd = -errno;
12013 		free(link);
12014 		pr_warn("prog '%s': failed to attach to iterator: %s\n",
12015 			prog->name, libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
12016 		return libbpf_err_ptr(link_fd);
12017 	}
12018 	link->fd = link_fd;
12019 	return link;
12020 }
12021 
12022 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12023 {
12024 	*link = bpf_program__attach_iter(prog, NULL);
12025 	return libbpf_get_error(*link);
12026 }
12027 
12028 struct bpf_link *bpf_program__attach_netfilter(const struct bpf_program *prog,
12029 					       const struct bpf_netfilter_opts *opts)
12030 {
12031 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
12032 	struct bpf_link *link;
12033 	int prog_fd, link_fd;
12034 
12035 	if (!OPTS_VALID(opts, bpf_netfilter_opts))
12036 		return libbpf_err_ptr(-EINVAL);
12037 
12038 	prog_fd = bpf_program__fd(prog);
12039 	if (prog_fd < 0) {
12040 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12041 		return libbpf_err_ptr(-EINVAL);
12042 	}
12043 
12044 	link = calloc(1, sizeof(*link));
12045 	if (!link)
12046 		return libbpf_err_ptr(-ENOMEM);
12047 
12048 	link->detach = &bpf_link__detach_fd;
12049 
12050 	lopts.netfilter.pf = OPTS_GET(opts, pf, 0);
12051 	lopts.netfilter.hooknum = OPTS_GET(opts, hooknum, 0);
12052 	lopts.netfilter.priority = OPTS_GET(opts, priority, 0);
12053 	lopts.netfilter.flags = OPTS_GET(opts, flags, 0);
12054 
12055 	link_fd = bpf_link_create(prog_fd, 0, BPF_NETFILTER, &lopts);
12056 	if (link_fd < 0) {
12057 		char errmsg[STRERR_BUFSIZE];
12058 
12059 		link_fd = -errno;
12060 		free(link);
12061 		pr_warn("prog '%s': failed to attach to netfilter: %s\n",
12062 			prog->name, libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
12063 		return libbpf_err_ptr(link_fd);
12064 	}
12065 	link->fd = link_fd;
12066 
12067 	return link;
12068 }
12069 
12070 struct bpf_link *bpf_program__attach(const struct bpf_program *prog)
12071 {
12072 	struct bpf_link *link = NULL;
12073 	int err;
12074 
12075 	if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
12076 		return libbpf_err_ptr(-EOPNOTSUPP);
12077 
12078 	err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, &link);
12079 	if (err)
12080 		return libbpf_err_ptr(err);
12081 
12082 	/* When calling bpf_program__attach() explicitly, auto-attach support
12083 	 * is expected to work, so NULL returned link is considered an error.
12084 	 * This is different for skeleton's attach, see comment in
12085 	 * bpf_object__attach_skeleton().
12086 	 */
12087 	if (!link)
12088 		return libbpf_err_ptr(-EOPNOTSUPP);
12089 
12090 	return link;
12091 }
12092 
12093 struct bpf_link_struct_ops {
12094 	struct bpf_link link;
12095 	int map_fd;
12096 };
12097 
12098 static int bpf_link__detach_struct_ops(struct bpf_link *link)
12099 {
12100 	struct bpf_link_struct_ops *st_link;
12101 	__u32 zero = 0;
12102 
12103 	st_link = container_of(link, struct bpf_link_struct_ops, link);
12104 
12105 	if (st_link->map_fd < 0)
12106 		/* w/o a real link */
12107 		return bpf_map_delete_elem(link->fd, &zero);
12108 
12109 	return close(link->fd);
12110 }
12111 
12112 struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map)
12113 {
12114 	struct bpf_link_struct_ops *link;
12115 	__u32 zero = 0;
12116 	int err, fd;
12117 
12118 	if (!bpf_map__is_struct_ops(map) || map->fd == -1)
12119 		return libbpf_err_ptr(-EINVAL);
12120 
12121 	link = calloc(1, sizeof(*link));
12122 	if (!link)
12123 		return libbpf_err_ptr(-EINVAL);
12124 
12125 	/* kern_vdata should be prepared during the loading phase. */
12126 	err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
12127 	/* It can be EBUSY if the map has been used to create or
12128 	 * update a link before.  We don't allow updating the value of
12129 	 * a struct_ops once it is set.  That ensures that the value
12130 	 * never changed.  So, it is safe to skip EBUSY.
12131 	 */
12132 	if (err && (!(map->def.map_flags & BPF_F_LINK) || err != -EBUSY)) {
12133 		free(link);
12134 		return libbpf_err_ptr(err);
12135 	}
12136 
12137 	link->link.detach = bpf_link__detach_struct_ops;
12138 
12139 	if (!(map->def.map_flags & BPF_F_LINK)) {
12140 		/* w/o a real link */
12141 		link->link.fd = map->fd;
12142 		link->map_fd = -1;
12143 		return &link->link;
12144 	}
12145 
12146 	fd = bpf_link_create(map->fd, 0, BPF_STRUCT_OPS, NULL);
12147 	if (fd < 0) {
12148 		free(link);
12149 		return libbpf_err_ptr(fd);
12150 	}
12151 
12152 	link->link.fd = fd;
12153 	link->map_fd = map->fd;
12154 
12155 	return &link->link;
12156 }
12157 
12158 /*
12159  * Swap the back struct_ops of a link with a new struct_ops map.
12160  */
12161 int bpf_link__update_map(struct bpf_link *link, const struct bpf_map *map)
12162 {
12163 	struct bpf_link_struct_ops *st_ops_link;
12164 	__u32 zero = 0;
12165 	int err;
12166 
12167 	if (!bpf_map__is_struct_ops(map) || map->fd < 0)
12168 		return -EINVAL;
12169 
12170 	st_ops_link = container_of(link, struct bpf_link_struct_ops, link);
12171 	/* Ensure the type of a link is correct */
12172 	if (st_ops_link->map_fd < 0)
12173 		return -EINVAL;
12174 
12175 	err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
12176 	/* It can be EBUSY if the map has been used to create or
12177 	 * update a link before.  We don't allow updating the value of
12178 	 * a struct_ops once it is set.  That ensures that the value
12179 	 * never changed.  So, it is safe to skip EBUSY.
12180 	 */
12181 	if (err && err != -EBUSY)
12182 		return err;
12183 
12184 	err = bpf_link_update(link->fd, map->fd, NULL);
12185 	if (err < 0)
12186 		return err;
12187 
12188 	st_ops_link->map_fd = map->fd;
12189 
12190 	return 0;
12191 }
12192 
12193 typedef enum bpf_perf_event_ret (*bpf_perf_event_print_t)(struct perf_event_header *hdr,
12194 							  void *private_data);
12195 
12196 static enum bpf_perf_event_ret
12197 perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
12198 		       void **copy_mem, size_t *copy_size,
12199 		       bpf_perf_event_print_t fn, void *private_data)
12200 {
12201 	struct perf_event_mmap_page *header = mmap_mem;
12202 	__u64 data_head = ring_buffer_read_head(header);
12203 	__u64 data_tail = header->data_tail;
12204 	void *base = ((__u8 *)header) + page_size;
12205 	int ret = LIBBPF_PERF_EVENT_CONT;
12206 	struct perf_event_header *ehdr;
12207 	size_t ehdr_size;
12208 
12209 	while (data_head != data_tail) {
12210 		ehdr = base + (data_tail & (mmap_size - 1));
12211 		ehdr_size = ehdr->size;
12212 
12213 		if (((void *)ehdr) + ehdr_size > base + mmap_size) {
12214 			void *copy_start = ehdr;
12215 			size_t len_first = base + mmap_size - copy_start;
12216 			size_t len_secnd = ehdr_size - len_first;
12217 
12218 			if (*copy_size < ehdr_size) {
12219 				free(*copy_mem);
12220 				*copy_mem = malloc(ehdr_size);
12221 				if (!*copy_mem) {
12222 					*copy_size = 0;
12223 					ret = LIBBPF_PERF_EVENT_ERROR;
12224 					break;
12225 				}
12226 				*copy_size = ehdr_size;
12227 			}
12228 
12229 			memcpy(*copy_mem, copy_start, len_first);
12230 			memcpy(*copy_mem + len_first, base, len_secnd);
12231 			ehdr = *copy_mem;
12232 		}
12233 
12234 		ret = fn(ehdr, private_data);
12235 		data_tail += ehdr_size;
12236 		if (ret != LIBBPF_PERF_EVENT_CONT)
12237 			break;
12238 	}
12239 
12240 	ring_buffer_write_tail(header, data_tail);
12241 	return libbpf_err(ret);
12242 }
12243 
12244 struct perf_buffer;
12245 
12246 struct perf_buffer_params {
12247 	struct perf_event_attr *attr;
12248 	/* if event_cb is specified, it takes precendence */
12249 	perf_buffer_event_fn event_cb;
12250 	/* sample_cb and lost_cb are higher-level common-case callbacks */
12251 	perf_buffer_sample_fn sample_cb;
12252 	perf_buffer_lost_fn lost_cb;
12253 	void *ctx;
12254 	int cpu_cnt;
12255 	int *cpus;
12256 	int *map_keys;
12257 };
12258 
12259 struct perf_cpu_buf {
12260 	struct perf_buffer *pb;
12261 	void *base; /* mmap()'ed memory */
12262 	void *buf; /* for reconstructing segmented data */
12263 	size_t buf_size;
12264 	int fd;
12265 	int cpu;
12266 	int map_key;
12267 };
12268 
12269 struct perf_buffer {
12270 	perf_buffer_event_fn event_cb;
12271 	perf_buffer_sample_fn sample_cb;
12272 	perf_buffer_lost_fn lost_cb;
12273 	void *ctx; /* passed into callbacks */
12274 
12275 	size_t page_size;
12276 	size_t mmap_size;
12277 	struct perf_cpu_buf **cpu_bufs;
12278 	struct epoll_event *events;
12279 	int cpu_cnt; /* number of allocated CPU buffers */
12280 	int epoll_fd; /* perf event FD */
12281 	int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
12282 };
12283 
12284 static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
12285 				      struct perf_cpu_buf *cpu_buf)
12286 {
12287 	if (!cpu_buf)
12288 		return;
12289 	if (cpu_buf->base &&
12290 	    munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
12291 		pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
12292 	if (cpu_buf->fd >= 0) {
12293 		ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
12294 		close(cpu_buf->fd);
12295 	}
12296 	free(cpu_buf->buf);
12297 	free(cpu_buf);
12298 }
12299 
12300 void perf_buffer__free(struct perf_buffer *pb)
12301 {
12302 	int i;
12303 
12304 	if (IS_ERR_OR_NULL(pb))
12305 		return;
12306 	if (pb->cpu_bufs) {
12307 		for (i = 0; i < pb->cpu_cnt; i++) {
12308 			struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
12309 
12310 			if (!cpu_buf)
12311 				continue;
12312 
12313 			bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
12314 			perf_buffer__free_cpu_buf(pb, cpu_buf);
12315 		}
12316 		free(pb->cpu_bufs);
12317 	}
12318 	if (pb->epoll_fd >= 0)
12319 		close(pb->epoll_fd);
12320 	free(pb->events);
12321 	free(pb);
12322 }
12323 
12324 static struct perf_cpu_buf *
12325 perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
12326 			  int cpu, int map_key)
12327 {
12328 	struct perf_cpu_buf *cpu_buf;
12329 	char msg[STRERR_BUFSIZE];
12330 	int err;
12331 
12332 	cpu_buf = calloc(1, sizeof(*cpu_buf));
12333 	if (!cpu_buf)
12334 		return ERR_PTR(-ENOMEM);
12335 
12336 	cpu_buf->pb = pb;
12337 	cpu_buf->cpu = cpu;
12338 	cpu_buf->map_key = map_key;
12339 
12340 	cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
12341 			      -1, PERF_FLAG_FD_CLOEXEC);
12342 	if (cpu_buf->fd < 0) {
12343 		err = -errno;
12344 		pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
12345 			cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
12346 		goto error;
12347 	}
12348 
12349 	cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
12350 			     PROT_READ | PROT_WRITE, MAP_SHARED,
12351 			     cpu_buf->fd, 0);
12352 	if (cpu_buf->base == MAP_FAILED) {
12353 		cpu_buf->base = NULL;
12354 		err = -errno;
12355 		pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
12356 			cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
12357 		goto error;
12358 	}
12359 
12360 	if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
12361 		err = -errno;
12362 		pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
12363 			cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
12364 		goto error;
12365 	}
12366 
12367 	return cpu_buf;
12368 
12369 error:
12370 	perf_buffer__free_cpu_buf(pb, cpu_buf);
12371 	return (struct perf_cpu_buf *)ERR_PTR(err);
12372 }
12373 
12374 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
12375 					      struct perf_buffer_params *p);
12376 
12377 struct perf_buffer *perf_buffer__new(int map_fd, size_t page_cnt,
12378 				     perf_buffer_sample_fn sample_cb,
12379 				     perf_buffer_lost_fn lost_cb,
12380 				     void *ctx,
12381 				     const struct perf_buffer_opts *opts)
12382 {
12383 	const size_t attr_sz = sizeof(struct perf_event_attr);
12384 	struct perf_buffer_params p = {};
12385 	struct perf_event_attr attr;
12386 	__u32 sample_period;
12387 
12388 	if (!OPTS_VALID(opts, perf_buffer_opts))
12389 		return libbpf_err_ptr(-EINVAL);
12390 
12391 	sample_period = OPTS_GET(opts, sample_period, 1);
12392 	if (!sample_period)
12393 		sample_period = 1;
12394 
12395 	memset(&attr, 0, attr_sz);
12396 	attr.size = attr_sz;
12397 	attr.config = PERF_COUNT_SW_BPF_OUTPUT;
12398 	attr.type = PERF_TYPE_SOFTWARE;
12399 	attr.sample_type = PERF_SAMPLE_RAW;
12400 	attr.sample_period = sample_period;
12401 	attr.wakeup_events = sample_period;
12402 
12403 	p.attr = &attr;
12404 	p.sample_cb = sample_cb;
12405 	p.lost_cb = lost_cb;
12406 	p.ctx = ctx;
12407 
12408 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
12409 }
12410 
12411 struct perf_buffer *perf_buffer__new_raw(int map_fd, size_t page_cnt,
12412 					 struct perf_event_attr *attr,
12413 					 perf_buffer_event_fn event_cb, void *ctx,
12414 					 const struct perf_buffer_raw_opts *opts)
12415 {
12416 	struct perf_buffer_params p = {};
12417 
12418 	if (!attr)
12419 		return libbpf_err_ptr(-EINVAL);
12420 
12421 	if (!OPTS_VALID(opts, perf_buffer_raw_opts))
12422 		return libbpf_err_ptr(-EINVAL);
12423 
12424 	p.attr = attr;
12425 	p.event_cb = event_cb;
12426 	p.ctx = ctx;
12427 	p.cpu_cnt = OPTS_GET(opts, cpu_cnt, 0);
12428 	p.cpus = OPTS_GET(opts, cpus, NULL);
12429 	p.map_keys = OPTS_GET(opts, map_keys, NULL);
12430 
12431 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
12432 }
12433 
12434 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
12435 					      struct perf_buffer_params *p)
12436 {
12437 	const char *online_cpus_file = "/sys/devices/system/cpu/online";
12438 	struct bpf_map_info map;
12439 	char msg[STRERR_BUFSIZE];
12440 	struct perf_buffer *pb;
12441 	bool *online = NULL;
12442 	__u32 map_info_len;
12443 	int err, i, j, n;
12444 
12445 	if (page_cnt == 0 || (page_cnt & (page_cnt - 1))) {
12446 		pr_warn("page count should be power of two, but is %zu\n",
12447 			page_cnt);
12448 		return ERR_PTR(-EINVAL);
12449 	}
12450 
12451 	/* best-effort sanity checks */
12452 	memset(&map, 0, sizeof(map));
12453 	map_info_len = sizeof(map);
12454 	err = bpf_map_get_info_by_fd(map_fd, &map, &map_info_len);
12455 	if (err) {
12456 		err = -errno;
12457 		/* if BPF_OBJ_GET_INFO_BY_FD is supported, will return
12458 		 * -EBADFD, -EFAULT, or -E2BIG on real error
12459 		 */
12460 		if (err != -EINVAL) {
12461 			pr_warn("failed to get map info for map FD %d: %s\n",
12462 				map_fd, libbpf_strerror_r(err, msg, sizeof(msg)));
12463 			return ERR_PTR(err);
12464 		}
12465 		pr_debug("failed to get map info for FD %d; API not supported? Ignoring...\n",
12466 			 map_fd);
12467 	} else {
12468 		if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
12469 			pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
12470 				map.name);
12471 			return ERR_PTR(-EINVAL);
12472 		}
12473 	}
12474 
12475 	pb = calloc(1, sizeof(*pb));
12476 	if (!pb)
12477 		return ERR_PTR(-ENOMEM);
12478 
12479 	pb->event_cb = p->event_cb;
12480 	pb->sample_cb = p->sample_cb;
12481 	pb->lost_cb = p->lost_cb;
12482 	pb->ctx = p->ctx;
12483 
12484 	pb->page_size = getpagesize();
12485 	pb->mmap_size = pb->page_size * page_cnt;
12486 	pb->map_fd = map_fd;
12487 
12488 	pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
12489 	if (pb->epoll_fd < 0) {
12490 		err = -errno;
12491 		pr_warn("failed to create epoll instance: %s\n",
12492 			libbpf_strerror_r(err, msg, sizeof(msg)));
12493 		goto error;
12494 	}
12495 
12496 	if (p->cpu_cnt > 0) {
12497 		pb->cpu_cnt = p->cpu_cnt;
12498 	} else {
12499 		pb->cpu_cnt = libbpf_num_possible_cpus();
12500 		if (pb->cpu_cnt < 0) {
12501 			err = pb->cpu_cnt;
12502 			goto error;
12503 		}
12504 		if (map.max_entries && map.max_entries < pb->cpu_cnt)
12505 			pb->cpu_cnt = map.max_entries;
12506 	}
12507 
12508 	pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
12509 	if (!pb->events) {
12510 		err = -ENOMEM;
12511 		pr_warn("failed to allocate events: out of memory\n");
12512 		goto error;
12513 	}
12514 	pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
12515 	if (!pb->cpu_bufs) {
12516 		err = -ENOMEM;
12517 		pr_warn("failed to allocate buffers: out of memory\n");
12518 		goto error;
12519 	}
12520 
12521 	err = parse_cpu_mask_file(online_cpus_file, &online, &n);
12522 	if (err) {
12523 		pr_warn("failed to get online CPU mask: %d\n", err);
12524 		goto error;
12525 	}
12526 
12527 	for (i = 0, j = 0; i < pb->cpu_cnt; i++) {
12528 		struct perf_cpu_buf *cpu_buf;
12529 		int cpu, map_key;
12530 
12531 		cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
12532 		map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
12533 
12534 		/* in case user didn't explicitly requested particular CPUs to
12535 		 * be attached to, skip offline/not present CPUs
12536 		 */
12537 		if (p->cpu_cnt <= 0 && (cpu >= n || !online[cpu]))
12538 			continue;
12539 
12540 		cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
12541 		if (IS_ERR(cpu_buf)) {
12542 			err = PTR_ERR(cpu_buf);
12543 			goto error;
12544 		}
12545 
12546 		pb->cpu_bufs[j] = cpu_buf;
12547 
12548 		err = bpf_map_update_elem(pb->map_fd, &map_key,
12549 					  &cpu_buf->fd, 0);
12550 		if (err) {
12551 			err = -errno;
12552 			pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
12553 				cpu, map_key, cpu_buf->fd,
12554 				libbpf_strerror_r(err, msg, sizeof(msg)));
12555 			goto error;
12556 		}
12557 
12558 		pb->events[j].events = EPOLLIN;
12559 		pb->events[j].data.ptr = cpu_buf;
12560 		if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
12561 			      &pb->events[j]) < 0) {
12562 			err = -errno;
12563 			pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
12564 				cpu, cpu_buf->fd,
12565 				libbpf_strerror_r(err, msg, sizeof(msg)));
12566 			goto error;
12567 		}
12568 		j++;
12569 	}
12570 	pb->cpu_cnt = j;
12571 	free(online);
12572 
12573 	return pb;
12574 
12575 error:
12576 	free(online);
12577 	if (pb)
12578 		perf_buffer__free(pb);
12579 	return ERR_PTR(err);
12580 }
12581 
12582 struct perf_sample_raw {
12583 	struct perf_event_header header;
12584 	uint32_t size;
12585 	char data[];
12586 };
12587 
12588 struct perf_sample_lost {
12589 	struct perf_event_header header;
12590 	uint64_t id;
12591 	uint64_t lost;
12592 	uint64_t sample_id;
12593 };
12594 
12595 static enum bpf_perf_event_ret
12596 perf_buffer__process_record(struct perf_event_header *e, void *ctx)
12597 {
12598 	struct perf_cpu_buf *cpu_buf = ctx;
12599 	struct perf_buffer *pb = cpu_buf->pb;
12600 	void *data = e;
12601 
12602 	/* user wants full control over parsing perf event */
12603 	if (pb->event_cb)
12604 		return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
12605 
12606 	switch (e->type) {
12607 	case PERF_RECORD_SAMPLE: {
12608 		struct perf_sample_raw *s = data;
12609 
12610 		if (pb->sample_cb)
12611 			pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
12612 		break;
12613 	}
12614 	case PERF_RECORD_LOST: {
12615 		struct perf_sample_lost *s = data;
12616 
12617 		if (pb->lost_cb)
12618 			pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
12619 		break;
12620 	}
12621 	default:
12622 		pr_warn("unknown perf sample type %d\n", e->type);
12623 		return LIBBPF_PERF_EVENT_ERROR;
12624 	}
12625 	return LIBBPF_PERF_EVENT_CONT;
12626 }
12627 
12628 static int perf_buffer__process_records(struct perf_buffer *pb,
12629 					struct perf_cpu_buf *cpu_buf)
12630 {
12631 	enum bpf_perf_event_ret ret;
12632 
12633 	ret = perf_event_read_simple(cpu_buf->base, pb->mmap_size,
12634 				     pb->page_size, &cpu_buf->buf,
12635 				     &cpu_buf->buf_size,
12636 				     perf_buffer__process_record, cpu_buf);
12637 	if (ret != LIBBPF_PERF_EVENT_CONT)
12638 		return ret;
12639 	return 0;
12640 }
12641 
12642 int perf_buffer__epoll_fd(const struct perf_buffer *pb)
12643 {
12644 	return pb->epoll_fd;
12645 }
12646 
12647 int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
12648 {
12649 	int i, cnt, err;
12650 
12651 	cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
12652 	if (cnt < 0)
12653 		return -errno;
12654 
12655 	for (i = 0; i < cnt; i++) {
12656 		struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
12657 
12658 		err = perf_buffer__process_records(pb, cpu_buf);
12659 		if (err) {
12660 			pr_warn("error while processing records: %d\n", err);
12661 			return libbpf_err(err);
12662 		}
12663 	}
12664 	return cnt;
12665 }
12666 
12667 /* Return number of PERF_EVENT_ARRAY map slots set up by this perf_buffer
12668  * manager.
12669  */
12670 size_t perf_buffer__buffer_cnt(const struct perf_buffer *pb)
12671 {
12672 	return pb->cpu_cnt;
12673 }
12674 
12675 /*
12676  * Return perf_event FD of a ring buffer in *buf_idx* slot of
12677  * PERF_EVENT_ARRAY BPF map. This FD can be polled for new data using
12678  * select()/poll()/epoll() Linux syscalls.
12679  */
12680 int perf_buffer__buffer_fd(const struct perf_buffer *pb, size_t buf_idx)
12681 {
12682 	struct perf_cpu_buf *cpu_buf;
12683 
12684 	if (buf_idx >= pb->cpu_cnt)
12685 		return libbpf_err(-EINVAL);
12686 
12687 	cpu_buf = pb->cpu_bufs[buf_idx];
12688 	if (!cpu_buf)
12689 		return libbpf_err(-ENOENT);
12690 
12691 	return cpu_buf->fd;
12692 }
12693 
12694 int perf_buffer__buffer(struct perf_buffer *pb, int buf_idx, void **buf, size_t *buf_size)
12695 {
12696 	struct perf_cpu_buf *cpu_buf;
12697 
12698 	if (buf_idx >= pb->cpu_cnt)
12699 		return libbpf_err(-EINVAL);
12700 
12701 	cpu_buf = pb->cpu_bufs[buf_idx];
12702 	if (!cpu_buf)
12703 		return libbpf_err(-ENOENT);
12704 
12705 	*buf = cpu_buf->base;
12706 	*buf_size = pb->mmap_size;
12707 	return 0;
12708 }
12709 
12710 /*
12711  * Consume data from perf ring buffer corresponding to slot *buf_idx* in
12712  * PERF_EVENT_ARRAY BPF map without waiting/polling. If there is no data to
12713  * consume, do nothing and return success.
12714  * Returns:
12715  *   - 0 on success;
12716  *   - <0 on failure.
12717  */
12718 int perf_buffer__consume_buffer(struct perf_buffer *pb, size_t buf_idx)
12719 {
12720 	struct perf_cpu_buf *cpu_buf;
12721 
12722 	if (buf_idx >= pb->cpu_cnt)
12723 		return libbpf_err(-EINVAL);
12724 
12725 	cpu_buf = pb->cpu_bufs[buf_idx];
12726 	if (!cpu_buf)
12727 		return libbpf_err(-ENOENT);
12728 
12729 	return perf_buffer__process_records(pb, cpu_buf);
12730 }
12731 
12732 int perf_buffer__consume(struct perf_buffer *pb)
12733 {
12734 	int i, err;
12735 
12736 	for (i = 0; i < pb->cpu_cnt; i++) {
12737 		struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
12738 
12739 		if (!cpu_buf)
12740 			continue;
12741 
12742 		err = perf_buffer__process_records(pb, cpu_buf);
12743 		if (err) {
12744 			pr_warn("perf_buffer: failed to process records in buffer #%d: %d\n", i, err);
12745 			return libbpf_err(err);
12746 		}
12747 	}
12748 	return 0;
12749 }
12750 
12751 int bpf_program__set_attach_target(struct bpf_program *prog,
12752 				   int attach_prog_fd,
12753 				   const char *attach_func_name)
12754 {
12755 	int btf_obj_fd = 0, btf_id = 0, err;
12756 
12757 	if (!prog || attach_prog_fd < 0)
12758 		return libbpf_err(-EINVAL);
12759 
12760 	if (prog->obj->loaded)
12761 		return libbpf_err(-EINVAL);
12762 
12763 	if (attach_prog_fd && !attach_func_name) {
12764 		/* remember attach_prog_fd and let bpf_program__load() find
12765 		 * BTF ID during the program load
12766 		 */
12767 		prog->attach_prog_fd = attach_prog_fd;
12768 		return 0;
12769 	}
12770 
12771 	if (attach_prog_fd) {
12772 		btf_id = libbpf_find_prog_btf_id(attach_func_name,
12773 						 attach_prog_fd);
12774 		if (btf_id < 0)
12775 			return libbpf_err(btf_id);
12776 	} else {
12777 		if (!attach_func_name)
12778 			return libbpf_err(-EINVAL);
12779 
12780 		/* load btf_vmlinux, if not yet */
12781 		err = bpf_object__load_vmlinux_btf(prog->obj, true);
12782 		if (err)
12783 			return libbpf_err(err);
12784 		err = find_kernel_btf_id(prog->obj, attach_func_name,
12785 					 prog->expected_attach_type,
12786 					 &btf_obj_fd, &btf_id);
12787 		if (err)
12788 			return libbpf_err(err);
12789 	}
12790 
12791 	prog->attach_btf_id = btf_id;
12792 	prog->attach_btf_obj_fd = btf_obj_fd;
12793 	prog->attach_prog_fd = attach_prog_fd;
12794 	return 0;
12795 }
12796 
12797 int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz)
12798 {
12799 	int err = 0, n, len, start, end = -1;
12800 	bool *tmp;
12801 
12802 	*mask = NULL;
12803 	*mask_sz = 0;
12804 
12805 	/* Each sub string separated by ',' has format \d+-\d+ or \d+ */
12806 	while (*s) {
12807 		if (*s == ',' || *s == '\n') {
12808 			s++;
12809 			continue;
12810 		}
12811 		n = sscanf(s, "%d%n-%d%n", &start, &len, &end, &len);
12812 		if (n <= 0 || n > 2) {
12813 			pr_warn("Failed to get CPU range %s: %d\n", s, n);
12814 			err = -EINVAL;
12815 			goto cleanup;
12816 		} else if (n == 1) {
12817 			end = start;
12818 		}
12819 		if (start < 0 || start > end) {
12820 			pr_warn("Invalid CPU range [%d,%d] in %s\n",
12821 				start, end, s);
12822 			err = -EINVAL;
12823 			goto cleanup;
12824 		}
12825 		tmp = realloc(*mask, end + 1);
12826 		if (!tmp) {
12827 			err = -ENOMEM;
12828 			goto cleanup;
12829 		}
12830 		*mask = tmp;
12831 		memset(tmp + *mask_sz, 0, start - *mask_sz);
12832 		memset(tmp + start, 1, end - start + 1);
12833 		*mask_sz = end + 1;
12834 		s += len;
12835 	}
12836 	if (!*mask_sz) {
12837 		pr_warn("Empty CPU range\n");
12838 		return -EINVAL;
12839 	}
12840 	return 0;
12841 cleanup:
12842 	free(*mask);
12843 	*mask = NULL;
12844 	return err;
12845 }
12846 
12847 int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz)
12848 {
12849 	int fd, err = 0, len;
12850 	char buf[128];
12851 
12852 	fd = open(fcpu, O_RDONLY | O_CLOEXEC);
12853 	if (fd < 0) {
12854 		err = -errno;
12855 		pr_warn("Failed to open cpu mask file %s: %d\n", fcpu, err);
12856 		return err;
12857 	}
12858 	len = read(fd, buf, sizeof(buf));
12859 	close(fd);
12860 	if (len <= 0) {
12861 		err = len ? -errno : -EINVAL;
12862 		pr_warn("Failed to read cpu mask from %s: %d\n", fcpu, err);
12863 		return err;
12864 	}
12865 	if (len >= sizeof(buf)) {
12866 		pr_warn("CPU mask is too big in file %s\n", fcpu);
12867 		return -E2BIG;
12868 	}
12869 	buf[len] = '\0';
12870 
12871 	return parse_cpu_mask_str(buf, mask, mask_sz);
12872 }
12873 
12874 int libbpf_num_possible_cpus(void)
12875 {
12876 	static const char *fcpu = "/sys/devices/system/cpu/possible";
12877 	static int cpus;
12878 	int err, n, i, tmp_cpus;
12879 	bool *mask;
12880 
12881 	tmp_cpus = READ_ONCE(cpus);
12882 	if (tmp_cpus > 0)
12883 		return tmp_cpus;
12884 
12885 	err = parse_cpu_mask_file(fcpu, &mask, &n);
12886 	if (err)
12887 		return libbpf_err(err);
12888 
12889 	tmp_cpus = 0;
12890 	for (i = 0; i < n; i++) {
12891 		if (mask[i])
12892 			tmp_cpus++;
12893 	}
12894 	free(mask);
12895 
12896 	WRITE_ONCE(cpus, tmp_cpus);
12897 	return tmp_cpus;
12898 }
12899 
12900 static int populate_skeleton_maps(const struct bpf_object *obj,
12901 				  struct bpf_map_skeleton *maps,
12902 				  size_t map_cnt)
12903 {
12904 	int i;
12905 
12906 	for (i = 0; i < map_cnt; i++) {
12907 		struct bpf_map **map = maps[i].map;
12908 		const char *name = maps[i].name;
12909 		void **mmaped = maps[i].mmaped;
12910 
12911 		*map = bpf_object__find_map_by_name(obj, name);
12912 		if (!*map) {
12913 			pr_warn("failed to find skeleton map '%s'\n", name);
12914 			return -ESRCH;
12915 		}
12916 
12917 		/* externs shouldn't be pre-setup from user code */
12918 		if (mmaped && (*map)->libbpf_type != LIBBPF_MAP_KCONFIG)
12919 			*mmaped = (*map)->mmaped;
12920 	}
12921 	return 0;
12922 }
12923 
12924 static int populate_skeleton_progs(const struct bpf_object *obj,
12925 				   struct bpf_prog_skeleton *progs,
12926 				   size_t prog_cnt)
12927 {
12928 	int i;
12929 
12930 	for (i = 0; i < prog_cnt; i++) {
12931 		struct bpf_program **prog = progs[i].prog;
12932 		const char *name = progs[i].name;
12933 
12934 		*prog = bpf_object__find_program_by_name(obj, name);
12935 		if (!*prog) {
12936 			pr_warn("failed to find skeleton program '%s'\n", name);
12937 			return -ESRCH;
12938 		}
12939 	}
12940 	return 0;
12941 }
12942 
12943 int bpf_object__open_skeleton(struct bpf_object_skeleton *s,
12944 			      const struct bpf_object_open_opts *opts)
12945 {
12946 	DECLARE_LIBBPF_OPTS(bpf_object_open_opts, skel_opts,
12947 		.object_name = s->name,
12948 	);
12949 	struct bpf_object *obj;
12950 	int err;
12951 
12952 	/* Attempt to preserve opts->object_name, unless overriden by user
12953 	 * explicitly. Overwriting object name for skeletons is discouraged,
12954 	 * as it breaks global data maps, because they contain object name
12955 	 * prefix as their own map name prefix. When skeleton is generated,
12956 	 * bpftool is making an assumption that this name will stay the same.
12957 	 */
12958 	if (opts) {
12959 		memcpy(&skel_opts, opts, sizeof(*opts));
12960 		if (!opts->object_name)
12961 			skel_opts.object_name = s->name;
12962 	}
12963 
12964 	obj = bpf_object__open_mem(s->data, s->data_sz, &skel_opts);
12965 	err = libbpf_get_error(obj);
12966 	if (err) {
12967 		pr_warn("failed to initialize skeleton BPF object '%s': %d\n",
12968 			s->name, err);
12969 		return libbpf_err(err);
12970 	}
12971 
12972 	*s->obj = obj;
12973 	err = populate_skeleton_maps(obj, s->maps, s->map_cnt);
12974 	if (err) {
12975 		pr_warn("failed to populate skeleton maps for '%s': %d\n", s->name, err);
12976 		return libbpf_err(err);
12977 	}
12978 
12979 	err = populate_skeleton_progs(obj, s->progs, s->prog_cnt);
12980 	if (err) {
12981 		pr_warn("failed to populate skeleton progs for '%s': %d\n", s->name, err);
12982 		return libbpf_err(err);
12983 	}
12984 
12985 	return 0;
12986 }
12987 
12988 int bpf_object__open_subskeleton(struct bpf_object_subskeleton *s)
12989 {
12990 	int err, len, var_idx, i;
12991 	const char *var_name;
12992 	const struct bpf_map *map;
12993 	struct btf *btf;
12994 	__u32 map_type_id;
12995 	const struct btf_type *map_type, *var_type;
12996 	const struct bpf_var_skeleton *var_skel;
12997 	struct btf_var_secinfo *var;
12998 
12999 	if (!s->obj)
13000 		return libbpf_err(-EINVAL);
13001 
13002 	btf = bpf_object__btf(s->obj);
13003 	if (!btf) {
13004 		pr_warn("subskeletons require BTF at runtime (object %s)\n",
13005 			bpf_object__name(s->obj));
13006 		return libbpf_err(-errno);
13007 	}
13008 
13009 	err = populate_skeleton_maps(s->obj, s->maps, s->map_cnt);
13010 	if (err) {
13011 		pr_warn("failed to populate subskeleton maps: %d\n", err);
13012 		return libbpf_err(err);
13013 	}
13014 
13015 	err = populate_skeleton_progs(s->obj, s->progs, s->prog_cnt);
13016 	if (err) {
13017 		pr_warn("failed to populate subskeleton maps: %d\n", err);
13018 		return libbpf_err(err);
13019 	}
13020 
13021 	for (var_idx = 0; var_idx < s->var_cnt; var_idx++) {
13022 		var_skel = &s->vars[var_idx];
13023 		map = *var_skel->map;
13024 		map_type_id = bpf_map__btf_value_type_id(map);
13025 		map_type = btf__type_by_id(btf, map_type_id);
13026 
13027 		if (!btf_is_datasec(map_type)) {
13028 			pr_warn("type for map '%1$s' is not a datasec: %2$s",
13029 				bpf_map__name(map),
13030 				__btf_kind_str(btf_kind(map_type)));
13031 			return libbpf_err(-EINVAL);
13032 		}
13033 
13034 		len = btf_vlen(map_type);
13035 		var = btf_var_secinfos(map_type);
13036 		for (i = 0; i < len; i++, var++) {
13037 			var_type = btf__type_by_id(btf, var->type);
13038 			var_name = btf__name_by_offset(btf, var_type->name_off);
13039 			if (strcmp(var_name, var_skel->name) == 0) {
13040 				*var_skel->addr = map->mmaped + var->offset;
13041 				break;
13042 			}
13043 		}
13044 	}
13045 	return 0;
13046 }
13047 
13048 void bpf_object__destroy_subskeleton(struct bpf_object_subskeleton *s)
13049 {
13050 	if (!s)
13051 		return;
13052 	free(s->maps);
13053 	free(s->progs);
13054 	free(s->vars);
13055 	free(s);
13056 }
13057 
13058 int bpf_object__load_skeleton(struct bpf_object_skeleton *s)
13059 {
13060 	int i, err;
13061 
13062 	err = bpf_object__load(*s->obj);
13063 	if (err) {
13064 		pr_warn("failed to load BPF skeleton '%s': %d\n", s->name, err);
13065 		return libbpf_err(err);
13066 	}
13067 
13068 	for (i = 0; i < s->map_cnt; i++) {
13069 		struct bpf_map *map = *s->maps[i].map;
13070 		size_t mmap_sz = bpf_map_mmap_sz(map->def.value_size, map->def.max_entries);
13071 		int prot, map_fd = bpf_map__fd(map);
13072 		void **mmaped = s->maps[i].mmaped;
13073 
13074 		if (!mmaped)
13075 			continue;
13076 
13077 		if (!(map->def.map_flags & BPF_F_MMAPABLE)) {
13078 			*mmaped = NULL;
13079 			continue;
13080 		}
13081 
13082 		if (map->def.map_flags & BPF_F_RDONLY_PROG)
13083 			prot = PROT_READ;
13084 		else
13085 			prot = PROT_READ | PROT_WRITE;
13086 
13087 		/* Remap anonymous mmap()-ed "map initialization image" as
13088 		 * a BPF map-backed mmap()-ed memory, but preserving the same
13089 		 * memory address. This will cause kernel to change process'
13090 		 * page table to point to a different piece of kernel memory,
13091 		 * but from userspace point of view memory address (and its
13092 		 * contents, being identical at this point) will stay the
13093 		 * same. This mapping will be released by bpf_object__close()
13094 		 * as per normal clean up procedure, so we don't need to worry
13095 		 * about it from skeleton's clean up perspective.
13096 		 */
13097 		*mmaped = mmap(map->mmaped, mmap_sz, prot, MAP_SHARED | MAP_FIXED, map_fd, 0);
13098 		if (*mmaped == MAP_FAILED) {
13099 			err = -errno;
13100 			*mmaped = NULL;
13101 			pr_warn("failed to re-mmap() map '%s': %d\n",
13102 				 bpf_map__name(map), err);
13103 			return libbpf_err(err);
13104 		}
13105 	}
13106 
13107 	return 0;
13108 }
13109 
13110 int bpf_object__attach_skeleton(struct bpf_object_skeleton *s)
13111 {
13112 	int i, err;
13113 
13114 	for (i = 0; i < s->prog_cnt; i++) {
13115 		struct bpf_program *prog = *s->progs[i].prog;
13116 		struct bpf_link **link = s->progs[i].link;
13117 
13118 		if (!prog->autoload || !prog->autoattach)
13119 			continue;
13120 
13121 		/* auto-attaching not supported for this program */
13122 		if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
13123 			continue;
13124 
13125 		/* if user already set the link manually, don't attempt auto-attach */
13126 		if (*link)
13127 			continue;
13128 
13129 		err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, link);
13130 		if (err) {
13131 			pr_warn("prog '%s': failed to auto-attach: %d\n",
13132 				bpf_program__name(prog), err);
13133 			return libbpf_err(err);
13134 		}
13135 
13136 		/* It's possible that for some SEC() definitions auto-attach
13137 		 * is supported in some cases (e.g., if definition completely
13138 		 * specifies target information), but is not in other cases.
13139 		 * SEC("uprobe") is one such case. If user specified target
13140 		 * binary and function name, such BPF program can be
13141 		 * auto-attached. But if not, it shouldn't trigger skeleton's
13142 		 * attach to fail. It should just be skipped.
13143 		 * attach_fn signals such case with returning 0 (no error) and
13144 		 * setting link to NULL.
13145 		 */
13146 	}
13147 
13148 	return 0;
13149 }
13150 
13151 void bpf_object__detach_skeleton(struct bpf_object_skeleton *s)
13152 {
13153 	int i;
13154 
13155 	for (i = 0; i < s->prog_cnt; i++) {
13156 		struct bpf_link **link = s->progs[i].link;
13157 
13158 		bpf_link__destroy(*link);
13159 		*link = NULL;
13160 	}
13161 }
13162 
13163 void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s)
13164 {
13165 	if (!s)
13166 		return;
13167 
13168 	if (s->progs)
13169 		bpf_object__detach_skeleton(s);
13170 	if (s->obj)
13171 		bpf_object__close(*s->obj);
13172 	free(s->maps);
13173 	free(s->progs);
13174 	free(s);
13175 }
13176