xref: /openbmc/linux/tools/lib/bpf/libbpf.c (revision 8097e460cabd9973e424e0f93bc1ad44cebf6466)
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 	[BPF_TRACE_UPROBE_MULTI]	= "trace_uprobe_multi",
124 };
125 
126 static const char * const link_type_name[] = {
127 	[BPF_LINK_TYPE_UNSPEC]			= "unspec",
128 	[BPF_LINK_TYPE_RAW_TRACEPOINT]		= "raw_tracepoint",
129 	[BPF_LINK_TYPE_TRACING]			= "tracing",
130 	[BPF_LINK_TYPE_CGROUP]			= "cgroup",
131 	[BPF_LINK_TYPE_ITER]			= "iter",
132 	[BPF_LINK_TYPE_NETNS]			= "netns",
133 	[BPF_LINK_TYPE_XDP]			= "xdp",
134 	[BPF_LINK_TYPE_PERF_EVENT]		= "perf_event",
135 	[BPF_LINK_TYPE_KPROBE_MULTI]		= "kprobe_multi",
136 	[BPF_LINK_TYPE_STRUCT_OPS]		= "struct_ops",
137 	[BPF_LINK_TYPE_NETFILTER]		= "netfilter",
138 	[BPF_LINK_TYPE_TCX]			= "tcx",
139 	[BPF_LINK_TYPE_UPROBE_MULTI]		= "uprobe_multi",
140 };
141 
142 static const char * const map_type_name[] = {
143 	[BPF_MAP_TYPE_UNSPEC]			= "unspec",
144 	[BPF_MAP_TYPE_HASH]			= "hash",
145 	[BPF_MAP_TYPE_ARRAY]			= "array",
146 	[BPF_MAP_TYPE_PROG_ARRAY]		= "prog_array",
147 	[BPF_MAP_TYPE_PERF_EVENT_ARRAY]		= "perf_event_array",
148 	[BPF_MAP_TYPE_PERCPU_HASH]		= "percpu_hash",
149 	[BPF_MAP_TYPE_PERCPU_ARRAY]		= "percpu_array",
150 	[BPF_MAP_TYPE_STACK_TRACE]		= "stack_trace",
151 	[BPF_MAP_TYPE_CGROUP_ARRAY]		= "cgroup_array",
152 	[BPF_MAP_TYPE_LRU_HASH]			= "lru_hash",
153 	[BPF_MAP_TYPE_LRU_PERCPU_HASH]		= "lru_percpu_hash",
154 	[BPF_MAP_TYPE_LPM_TRIE]			= "lpm_trie",
155 	[BPF_MAP_TYPE_ARRAY_OF_MAPS]		= "array_of_maps",
156 	[BPF_MAP_TYPE_HASH_OF_MAPS]		= "hash_of_maps",
157 	[BPF_MAP_TYPE_DEVMAP]			= "devmap",
158 	[BPF_MAP_TYPE_DEVMAP_HASH]		= "devmap_hash",
159 	[BPF_MAP_TYPE_SOCKMAP]			= "sockmap",
160 	[BPF_MAP_TYPE_CPUMAP]			= "cpumap",
161 	[BPF_MAP_TYPE_XSKMAP]			= "xskmap",
162 	[BPF_MAP_TYPE_SOCKHASH]			= "sockhash",
163 	[BPF_MAP_TYPE_CGROUP_STORAGE]		= "cgroup_storage",
164 	[BPF_MAP_TYPE_REUSEPORT_SOCKARRAY]	= "reuseport_sockarray",
165 	[BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE]	= "percpu_cgroup_storage",
166 	[BPF_MAP_TYPE_QUEUE]			= "queue",
167 	[BPF_MAP_TYPE_STACK]			= "stack",
168 	[BPF_MAP_TYPE_SK_STORAGE]		= "sk_storage",
169 	[BPF_MAP_TYPE_STRUCT_OPS]		= "struct_ops",
170 	[BPF_MAP_TYPE_RINGBUF]			= "ringbuf",
171 	[BPF_MAP_TYPE_INODE_STORAGE]		= "inode_storage",
172 	[BPF_MAP_TYPE_TASK_STORAGE]		= "task_storage",
173 	[BPF_MAP_TYPE_BLOOM_FILTER]		= "bloom_filter",
174 	[BPF_MAP_TYPE_USER_RINGBUF]             = "user_ringbuf",
175 	[BPF_MAP_TYPE_CGRP_STORAGE]		= "cgrp_storage",
176 };
177 
178 static const char * const prog_type_name[] = {
179 	[BPF_PROG_TYPE_UNSPEC]			= "unspec",
180 	[BPF_PROG_TYPE_SOCKET_FILTER]		= "socket_filter",
181 	[BPF_PROG_TYPE_KPROBE]			= "kprobe",
182 	[BPF_PROG_TYPE_SCHED_CLS]		= "sched_cls",
183 	[BPF_PROG_TYPE_SCHED_ACT]		= "sched_act",
184 	[BPF_PROG_TYPE_TRACEPOINT]		= "tracepoint",
185 	[BPF_PROG_TYPE_XDP]			= "xdp",
186 	[BPF_PROG_TYPE_PERF_EVENT]		= "perf_event",
187 	[BPF_PROG_TYPE_CGROUP_SKB]		= "cgroup_skb",
188 	[BPF_PROG_TYPE_CGROUP_SOCK]		= "cgroup_sock",
189 	[BPF_PROG_TYPE_LWT_IN]			= "lwt_in",
190 	[BPF_PROG_TYPE_LWT_OUT]			= "lwt_out",
191 	[BPF_PROG_TYPE_LWT_XMIT]		= "lwt_xmit",
192 	[BPF_PROG_TYPE_SOCK_OPS]		= "sock_ops",
193 	[BPF_PROG_TYPE_SK_SKB]			= "sk_skb",
194 	[BPF_PROG_TYPE_CGROUP_DEVICE]		= "cgroup_device",
195 	[BPF_PROG_TYPE_SK_MSG]			= "sk_msg",
196 	[BPF_PROG_TYPE_RAW_TRACEPOINT]		= "raw_tracepoint",
197 	[BPF_PROG_TYPE_CGROUP_SOCK_ADDR]	= "cgroup_sock_addr",
198 	[BPF_PROG_TYPE_LWT_SEG6LOCAL]		= "lwt_seg6local",
199 	[BPF_PROG_TYPE_LIRC_MODE2]		= "lirc_mode2",
200 	[BPF_PROG_TYPE_SK_REUSEPORT]		= "sk_reuseport",
201 	[BPF_PROG_TYPE_FLOW_DISSECTOR]		= "flow_dissector",
202 	[BPF_PROG_TYPE_CGROUP_SYSCTL]		= "cgroup_sysctl",
203 	[BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE]	= "raw_tracepoint_writable",
204 	[BPF_PROG_TYPE_CGROUP_SOCKOPT]		= "cgroup_sockopt",
205 	[BPF_PROG_TYPE_TRACING]			= "tracing",
206 	[BPF_PROG_TYPE_STRUCT_OPS]		= "struct_ops",
207 	[BPF_PROG_TYPE_EXT]			= "ext",
208 	[BPF_PROG_TYPE_LSM]			= "lsm",
209 	[BPF_PROG_TYPE_SK_LOOKUP]		= "sk_lookup",
210 	[BPF_PROG_TYPE_SYSCALL]			= "syscall",
211 	[BPF_PROG_TYPE_NETFILTER]		= "netfilter",
212 };
213 
214 static int __base_pr(enum libbpf_print_level level, const char *format,
215 		     va_list args)
216 {
217 	if (level == LIBBPF_DEBUG)
218 		return 0;
219 
220 	return vfprintf(stderr, format, args);
221 }
222 
223 static libbpf_print_fn_t __libbpf_pr = __base_pr;
224 
225 libbpf_print_fn_t libbpf_set_print(libbpf_print_fn_t fn)
226 {
227 	libbpf_print_fn_t old_print_fn;
228 
229 	old_print_fn = __atomic_exchange_n(&__libbpf_pr, fn, __ATOMIC_RELAXED);
230 
231 	return old_print_fn;
232 }
233 
234 __printf(2, 3)
235 void libbpf_print(enum libbpf_print_level level, const char *format, ...)
236 {
237 	va_list args;
238 	int old_errno;
239 	libbpf_print_fn_t print_fn;
240 
241 	print_fn = __atomic_load_n(&__libbpf_pr, __ATOMIC_RELAXED);
242 	if (!print_fn)
243 		return;
244 
245 	old_errno = errno;
246 
247 	va_start(args, format);
248 	__libbpf_pr(level, format, args);
249 	va_end(args);
250 
251 	errno = old_errno;
252 }
253 
254 static void pr_perm_msg(int err)
255 {
256 	struct rlimit limit;
257 	char buf[100];
258 
259 	if (err != -EPERM || geteuid() != 0)
260 		return;
261 
262 	err = getrlimit(RLIMIT_MEMLOCK, &limit);
263 	if (err)
264 		return;
265 
266 	if (limit.rlim_cur == RLIM_INFINITY)
267 		return;
268 
269 	if (limit.rlim_cur < 1024)
270 		snprintf(buf, sizeof(buf), "%zu bytes", (size_t)limit.rlim_cur);
271 	else if (limit.rlim_cur < 1024*1024)
272 		snprintf(buf, sizeof(buf), "%.1f KiB", (double)limit.rlim_cur / 1024);
273 	else
274 		snprintf(buf, sizeof(buf), "%.1f MiB", (double)limit.rlim_cur / (1024*1024));
275 
276 	pr_warn("permission error while running as root; try raising 'ulimit -l'? current value: %s\n",
277 		buf);
278 }
279 
280 #define STRERR_BUFSIZE  128
281 
282 /* Copied from tools/perf/util/util.h */
283 #ifndef zfree
284 # define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
285 #endif
286 
287 #ifndef zclose
288 # define zclose(fd) ({			\
289 	int ___err = 0;			\
290 	if ((fd) >= 0)			\
291 		___err = close((fd));	\
292 	fd = -1;			\
293 	___err; })
294 #endif
295 
296 static inline __u64 ptr_to_u64(const void *ptr)
297 {
298 	return (__u64) (unsigned long) ptr;
299 }
300 
301 int libbpf_set_strict_mode(enum libbpf_strict_mode mode)
302 {
303 	/* as of v1.0 libbpf_set_strict_mode() is a no-op */
304 	return 0;
305 }
306 
307 __u32 libbpf_major_version(void)
308 {
309 	return LIBBPF_MAJOR_VERSION;
310 }
311 
312 __u32 libbpf_minor_version(void)
313 {
314 	return LIBBPF_MINOR_VERSION;
315 }
316 
317 const char *libbpf_version_string(void)
318 {
319 #define __S(X) #X
320 #define _S(X) __S(X)
321 	return  "v" _S(LIBBPF_MAJOR_VERSION) "." _S(LIBBPF_MINOR_VERSION);
322 #undef _S
323 #undef __S
324 }
325 
326 enum reloc_type {
327 	RELO_LD64,
328 	RELO_CALL,
329 	RELO_DATA,
330 	RELO_EXTERN_LD64,
331 	RELO_EXTERN_CALL,
332 	RELO_SUBPROG_ADDR,
333 	RELO_CORE,
334 };
335 
336 struct reloc_desc {
337 	enum reloc_type type;
338 	int insn_idx;
339 	union {
340 		const struct bpf_core_relo *core_relo; /* used when type == RELO_CORE */
341 		struct {
342 			int map_idx;
343 			int sym_off;
344 			int ext_idx;
345 		};
346 	};
347 };
348 
349 /* stored as sec_def->cookie for all libbpf-supported SEC()s */
350 enum sec_def_flags {
351 	SEC_NONE = 0,
352 	/* expected_attach_type is optional, if kernel doesn't support that */
353 	SEC_EXP_ATTACH_OPT = 1,
354 	/* legacy, only used by libbpf_get_type_names() and
355 	 * libbpf_attach_type_by_name(), not used by libbpf itself at all.
356 	 * This used to be associated with cgroup (and few other) BPF programs
357 	 * that were attachable through BPF_PROG_ATTACH command. Pretty
358 	 * meaningless nowadays, though.
359 	 */
360 	SEC_ATTACHABLE = 2,
361 	SEC_ATTACHABLE_OPT = SEC_ATTACHABLE | SEC_EXP_ATTACH_OPT,
362 	/* attachment target is specified through BTF ID in either kernel or
363 	 * other BPF program's BTF object
364 	 */
365 	SEC_ATTACH_BTF = 4,
366 	/* BPF program type allows sleeping/blocking in kernel */
367 	SEC_SLEEPABLE = 8,
368 	/* BPF program support non-linear XDP buffer */
369 	SEC_XDP_FRAGS = 16,
370 };
371 
372 struct bpf_sec_def {
373 	char *sec;
374 	enum bpf_prog_type prog_type;
375 	enum bpf_attach_type expected_attach_type;
376 	long cookie;
377 	int handler_id;
378 
379 	libbpf_prog_setup_fn_t prog_setup_fn;
380 	libbpf_prog_prepare_load_fn_t prog_prepare_load_fn;
381 	libbpf_prog_attach_fn_t prog_attach_fn;
382 };
383 
384 /*
385  * bpf_prog should be a better name but it has been used in
386  * linux/filter.h.
387  */
388 struct bpf_program {
389 	char *name;
390 	char *sec_name;
391 	size_t sec_idx;
392 	const struct bpf_sec_def *sec_def;
393 	/* this program's instruction offset (in number of instructions)
394 	 * within its containing ELF section
395 	 */
396 	size_t sec_insn_off;
397 	/* number of original instructions in ELF section belonging to this
398 	 * program, not taking into account subprogram instructions possible
399 	 * appended later during relocation
400 	 */
401 	size_t sec_insn_cnt;
402 	/* Offset (in number of instructions) of the start of instruction
403 	 * belonging to this BPF program  within its containing main BPF
404 	 * program. For the entry-point (main) BPF program, this is always
405 	 * zero. For a sub-program, this gets reset before each of main BPF
406 	 * programs are processed and relocated and is used to determined
407 	 * whether sub-program was already appended to the main program, and
408 	 * if yes, at which instruction offset.
409 	 */
410 	size_t sub_insn_off;
411 
412 	/* instructions that belong to BPF program; insns[0] is located at
413 	 * sec_insn_off instruction within its ELF section in ELF file, so
414 	 * when mapping ELF file instruction index to the local instruction,
415 	 * one needs to subtract sec_insn_off; and vice versa.
416 	 */
417 	struct bpf_insn *insns;
418 	/* actual number of instruction in this BPF program's image; for
419 	 * entry-point BPF programs this includes the size of main program
420 	 * itself plus all the used sub-programs, appended at the end
421 	 */
422 	size_t insns_cnt;
423 
424 	struct reloc_desc *reloc_desc;
425 	int nr_reloc;
426 
427 	/* BPF verifier log settings */
428 	char *log_buf;
429 	size_t log_size;
430 	__u32 log_level;
431 
432 	struct bpf_object *obj;
433 
434 	int fd;
435 	bool autoload;
436 	bool autoattach;
437 	bool mark_btf_static;
438 	enum bpf_prog_type type;
439 	enum bpf_attach_type expected_attach_type;
440 
441 	int prog_ifindex;
442 	__u32 attach_btf_obj_fd;
443 	__u32 attach_btf_id;
444 	__u32 attach_prog_fd;
445 
446 	void *func_info;
447 	__u32 func_info_rec_size;
448 	__u32 func_info_cnt;
449 
450 	void *line_info;
451 	__u32 line_info_rec_size;
452 	__u32 line_info_cnt;
453 	__u32 prog_flags;
454 };
455 
456 struct bpf_struct_ops {
457 	const char *tname;
458 	const struct btf_type *type;
459 	struct bpf_program **progs;
460 	__u32 *kern_func_off;
461 	/* e.g. struct tcp_congestion_ops in bpf_prog's btf format */
462 	void *data;
463 	/* e.g. struct bpf_struct_ops_tcp_congestion_ops in
464 	 *      btf_vmlinux's format.
465 	 * struct bpf_struct_ops_tcp_congestion_ops {
466 	 *	[... some other kernel fields ...]
467 	 *	struct tcp_congestion_ops data;
468 	 * }
469 	 * kern_vdata-size == sizeof(struct bpf_struct_ops_tcp_congestion_ops)
470 	 * bpf_map__init_kern_struct_ops() will populate the "kern_vdata"
471 	 * from "data".
472 	 */
473 	void *kern_vdata;
474 	__u32 type_id;
475 };
476 
477 #define DATA_SEC ".data"
478 #define BSS_SEC ".bss"
479 #define RODATA_SEC ".rodata"
480 #define KCONFIG_SEC ".kconfig"
481 #define KSYMS_SEC ".ksyms"
482 #define STRUCT_OPS_SEC ".struct_ops"
483 #define STRUCT_OPS_LINK_SEC ".struct_ops.link"
484 
485 enum libbpf_map_type {
486 	LIBBPF_MAP_UNSPEC,
487 	LIBBPF_MAP_DATA,
488 	LIBBPF_MAP_BSS,
489 	LIBBPF_MAP_RODATA,
490 	LIBBPF_MAP_KCONFIG,
491 };
492 
493 struct bpf_map_def {
494 	unsigned int type;
495 	unsigned int key_size;
496 	unsigned int value_size;
497 	unsigned int max_entries;
498 	unsigned int map_flags;
499 };
500 
501 struct bpf_map {
502 	struct bpf_object *obj;
503 	char *name;
504 	/* real_name is defined for special internal maps (.rodata*,
505 	 * .data*, .bss, .kconfig) and preserves their original ELF section
506 	 * name. This is important to be able to find corresponding BTF
507 	 * DATASEC information.
508 	 */
509 	char *real_name;
510 	int fd;
511 	int sec_idx;
512 	size_t sec_offset;
513 	int map_ifindex;
514 	int inner_map_fd;
515 	struct bpf_map_def def;
516 	__u32 numa_node;
517 	__u32 btf_var_idx;
518 	__u32 btf_key_type_id;
519 	__u32 btf_value_type_id;
520 	__u32 btf_vmlinux_value_type_id;
521 	enum libbpf_map_type libbpf_type;
522 	void *mmaped;
523 	struct bpf_struct_ops *st_ops;
524 	struct bpf_map *inner_map;
525 	void **init_slots;
526 	int init_slots_sz;
527 	char *pin_path;
528 	bool pinned;
529 	bool reused;
530 	bool autocreate;
531 	__u64 map_extra;
532 };
533 
534 enum extern_type {
535 	EXT_UNKNOWN,
536 	EXT_KCFG,
537 	EXT_KSYM,
538 };
539 
540 enum kcfg_type {
541 	KCFG_UNKNOWN,
542 	KCFG_CHAR,
543 	KCFG_BOOL,
544 	KCFG_INT,
545 	KCFG_TRISTATE,
546 	KCFG_CHAR_ARR,
547 };
548 
549 struct extern_desc {
550 	enum extern_type type;
551 	int sym_idx;
552 	int btf_id;
553 	int sec_btf_id;
554 	const char *name;
555 	char *essent_name;
556 	bool is_set;
557 	bool is_weak;
558 	union {
559 		struct {
560 			enum kcfg_type type;
561 			int sz;
562 			int align;
563 			int data_off;
564 			bool is_signed;
565 		} kcfg;
566 		struct {
567 			unsigned long long addr;
568 
569 			/* target btf_id of the corresponding kernel var. */
570 			int kernel_btf_obj_fd;
571 			int kernel_btf_id;
572 
573 			/* local btf_id of the ksym extern's type. */
574 			__u32 type_id;
575 			/* BTF fd index to be patched in for insn->off, this is
576 			 * 0 for vmlinux BTF, index in obj->fd_array for module
577 			 * BTF
578 			 */
579 			__s16 btf_fd_idx;
580 		} ksym;
581 	};
582 };
583 
584 struct module_btf {
585 	struct btf *btf;
586 	char *name;
587 	__u32 id;
588 	int fd;
589 	int fd_array_idx;
590 };
591 
592 enum sec_type {
593 	SEC_UNUSED = 0,
594 	SEC_RELO,
595 	SEC_BSS,
596 	SEC_DATA,
597 	SEC_RODATA,
598 };
599 
600 struct elf_sec_desc {
601 	enum sec_type sec_type;
602 	Elf64_Shdr *shdr;
603 	Elf_Data *data;
604 };
605 
606 struct elf_state {
607 	int fd;
608 	const void *obj_buf;
609 	size_t obj_buf_sz;
610 	Elf *elf;
611 	Elf64_Ehdr *ehdr;
612 	Elf_Data *symbols;
613 	Elf_Data *st_ops_data;
614 	Elf_Data *st_ops_link_data;
615 	size_t shstrndx; /* section index for section name strings */
616 	size_t strtabidx;
617 	struct elf_sec_desc *secs;
618 	size_t sec_cnt;
619 	int btf_maps_shndx;
620 	__u32 btf_maps_sec_btf_id;
621 	int text_shndx;
622 	int symbols_shndx;
623 	int st_ops_shndx;
624 	int st_ops_link_shndx;
625 };
626 
627 struct usdt_manager;
628 
629 struct bpf_object {
630 	char name[BPF_OBJ_NAME_LEN];
631 	char license[64];
632 	__u32 kern_version;
633 
634 	struct bpf_program *programs;
635 	size_t nr_programs;
636 	struct bpf_map *maps;
637 	size_t nr_maps;
638 	size_t maps_cap;
639 
640 	char *kconfig;
641 	struct extern_desc *externs;
642 	int nr_extern;
643 	int kconfig_map_idx;
644 
645 	bool loaded;
646 	bool has_subcalls;
647 	bool has_rodata;
648 
649 	struct bpf_gen *gen_loader;
650 
651 	/* Information when doing ELF related work. Only valid if efile.elf is not NULL */
652 	struct elf_state efile;
653 
654 	struct btf *btf;
655 	struct btf_ext *btf_ext;
656 
657 	/* Parse and load BTF vmlinux if any of the programs in the object need
658 	 * it at load time.
659 	 */
660 	struct btf *btf_vmlinux;
661 	/* Path to the custom BTF to be used for BPF CO-RE relocations as an
662 	 * override for vmlinux BTF.
663 	 */
664 	char *btf_custom_path;
665 	/* vmlinux BTF override for CO-RE relocations */
666 	struct btf *btf_vmlinux_override;
667 	/* Lazily initialized kernel module BTFs */
668 	struct module_btf *btf_modules;
669 	bool btf_modules_loaded;
670 	size_t btf_module_cnt;
671 	size_t btf_module_cap;
672 
673 	/* optional log settings passed to BPF_BTF_LOAD and BPF_PROG_LOAD commands */
674 	char *log_buf;
675 	size_t log_size;
676 	__u32 log_level;
677 
678 	int *fd_array;
679 	size_t fd_array_cap;
680 	size_t fd_array_cnt;
681 
682 	struct usdt_manager *usdt_man;
683 
684 	char path[];
685 };
686 
687 static const char *elf_sym_str(const struct bpf_object *obj, size_t off);
688 static const char *elf_sec_str(const struct bpf_object *obj, size_t off);
689 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx);
690 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name);
691 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn);
692 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn);
693 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn);
694 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx);
695 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx);
696 
697 void bpf_program__unload(struct bpf_program *prog)
698 {
699 	if (!prog)
700 		return;
701 
702 	zclose(prog->fd);
703 
704 	zfree(&prog->func_info);
705 	zfree(&prog->line_info);
706 }
707 
708 static void bpf_program__exit(struct bpf_program *prog)
709 {
710 	if (!prog)
711 		return;
712 
713 	bpf_program__unload(prog);
714 	zfree(&prog->name);
715 	zfree(&prog->sec_name);
716 	zfree(&prog->insns);
717 	zfree(&prog->reloc_desc);
718 
719 	prog->nr_reloc = 0;
720 	prog->insns_cnt = 0;
721 	prog->sec_idx = -1;
722 }
723 
724 static bool insn_is_subprog_call(const struct bpf_insn *insn)
725 {
726 	return BPF_CLASS(insn->code) == BPF_JMP &&
727 	       BPF_OP(insn->code) == BPF_CALL &&
728 	       BPF_SRC(insn->code) == BPF_K &&
729 	       insn->src_reg == BPF_PSEUDO_CALL &&
730 	       insn->dst_reg == 0 &&
731 	       insn->off == 0;
732 }
733 
734 static bool is_call_insn(const struct bpf_insn *insn)
735 {
736 	return insn->code == (BPF_JMP | BPF_CALL);
737 }
738 
739 static bool insn_is_pseudo_func(struct bpf_insn *insn)
740 {
741 	return is_ldimm64_insn(insn) && insn->src_reg == BPF_PSEUDO_FUNC;
742 }
743 
744 static int
745 bpf_object__init_prog(struct bpf_object *obj, struct bpf_program *prog,
746 		      const char *name, size_t sec_idx, const char *sec_name,
747 		      size_t sec_off, void *insn_data, size_t insn_data_sz)
748 {
749 	if (insn_data_sz == 0 || insn_data_sz % BPF_INSN_SZ || sec_off % BPF_INSN_SZ) {
750 		pr_warn("sec '%s': corrupted program '%s', offset %zu, size %zu\n",
751 			sec_name, name, sec_off, insn_data_sz);
752 		return -EINVAL;
753 	}
754 
755 	memset(prog, 0, sizeof(*prog));
756 	prog->obj = obj;
757 
758 	prog->sec_idx = sec_idx;
759 	prog->sec_insn_off = sec_off / BPF_INSN_SZ;
760 	prog->sec_insn_cnt = insn_data_sz / BPF_INSN_SZ;
761 	/* insns_cnt can later be increased by appending used subprograms */
762 	prog->insns_cnt = prog->sec_insn_cnt;
763 
764 	prog->type = BPF_PROG_TYPE_UNSPEC;
765 	prog->fd = -1;
766 
767 	/* libbpf's convention for SEC("?abc...") is that it's just like
768 	 * SEC("abc...") but the corresponding bpf_program starts out with
769 	 * autoload set to false.
770 	 */
771 	if (sec_name[0] == '?') {
772 		prog->autoload = false;
773 		/* from now on forget there was ? in section name */
774 		sec_name++;
775 	} else {
776 		prog->autoload = true;
777 	}
778 
779 	prog->autoattach = true;
780 
781 	/* inherit object's log_level */
782 	prog->log_level = obj->log_level;
783 
784 	prog->sec_name = strdup(sec_name);
785 	if (!prog->sec_name)
786 		goto errout;
787 
788 	prog->name = strdup(name);
789 	if (!prog->name)
790 		goto errout;
791 
792 	prog->insns = malloc(insn_data_sz);
793 	if (!prog->insns)
794 		goto errout;
795 	memcpy(prog->insns, insn_data, insn_data_sz);
796 
797 	return 0;
798 errout:
799 	pr_warn("sec '%s': failed to allocate memory for prog '%s'\n", sec_name, name);
800 	bpf_program__exit(prog);
801 	return -ENOMEM;
802 }
803 
804 static int
805 bpf_object__add_programs(struct bpf_object *obj, Elf_Data *sec_data,
806 			 const char *sec_name, int sec_idx)
807 {
808 	Elf_Data *symbols = obj->efile.symbols;
809 	struct bpf_program *prog, *progs;
810 	void *data = sec_data->d_buf;
811 	size_t sec_sz = sec_data->d_size, sec_off, prog_sz, nr_syms;
812 	int nr_progs, err, i;
813 	const char *name;
814 	Elf64_Sym *sym;
815 
816 	progs = obj->programs;
817 	nr_progs = obj->nr_programs;
818 	nr_syms = symbols->d_size / sizeof(Elf64_Sym);
819 
820 	for (i = 0; i < nr_syms; i++) {
821 		sym = elf_sym_by_idx(obj, i);
822 
823 		if (sym->st_shndx != sec_idx)
824 			continue;
825 		if (ELF64_ST_TYPE(sym->st_info) != STT_FUNC)
826 			continue;
827 
828 		prog_sz = sym->st_size;
829 		sec_off = sym->st_value;
830 
831 		name = elf_sym_str(obj, sym->st_name);
832 		if (!name) {
833 			pr_warn("sec '%s': failed to get symbol name for offset %zu\n",
834 				sec_name, sec_off);
835 			return -LIBBPF_ERRNO__FORMAT;
836 		}
837 
838 		if (sec_off + prog_sz > sec_sz) {
839 			pr_warn("sec '%s': program at offset %zu crosses section boundary\n",
840 				sec_name, sec_off);
841 			return -LIBBPF_ERRNO__FORMAT;
842 		}
843 
844 		if (sec_idx != obj->efile.text_shndx && ELF64_ST_BIND(sym->st_info) == STB_LOCAL) {
845 			pr_warn("sec '%s': program '%s' is static and not supported\n", sec_name, name);
846 			return -ENOTSUP;
847 		}
848 
849 		pr_debug("sec '%s': found program '%s' at insn offset %zu (%zu bytes), code size %zu insns (%zu bytes)\n",
850 			 sec_name, name, sec_off / BPF_INSN_SZ, sec_off, prog_sz / BPF_INSN_SZ, prog_sz);
851 
852 		progs = libbpf_reallocarray(progs, nr_progs + 1, sizeof(*progs));
853 		if (!progs) {
854 			/*
855 			 * In this case the original obj->programs
856 			 * is still valid, so don't need special treat for
857 			 * bpf_close_object().
858 			 */
859 			pr_warn("sec '%s': failed to alloc memory for new program '%s'\n",
860 				sec_name, name);
861 			return -ENOMEM;
862 		}
863 		obj->programs = progs;
864 
865 		prog = &progs[nr_progs];
866 
867 		err = bpf_object__init_prog(obj, prog, name, sec_idx, sec_name,
868 					    sec_off, data + sec_off, prog_sz);
869 		if (err)
870 			return err;
871 
872 		/* if function is a global/weak symbol, but has restricted
873 		 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF FUNC
874 		 * as static to enable more permissive BPF verification mode
875 		 * with more outside context available to BPF verifier
876 		 */
877 		if (ELF64_ST_BIND(sym->st_info) != STB_LOCAL
878 		    && (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
879 			|| ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL))
880 			prog->mark_btf_static = true;
881 
882 		nr_progs++;
883 		obj->nr_programs = nr_progs;
884 	}
885 
886 	return 0;
887 }
888 
889 static const struct btf_member *
890 find_member_by_offset(const struct btf_type *t, __u32 bit_offset)
891 {
892 	struct btf_member *m;
893 	int i;
894 
895 	for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
896 		if (btf_member_bit_offset(t, i) == bit_offset)
897 			return m;
898 	}
899 
900 	return NULL;
901 }
902 
903 static const struct btf_member *
904 find_member_by_name(const struct btf *btf, const struct btf_type *t,
905 		    const char *name)
906 {
907 	struct btf_member *m;
908 	int i;
909 
910 	for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
911 		if (!strcmp(btf__name_by_offset(btf, m->name_off), name))
912 			return m;
913 	}
914 
915 	return NULL;
916 }
917 
918 #define STRUCT_OPS_VALUE_PREFIX "bpf_struct_ops_"
919 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
920 				   const char *name, __u32 kind);
921 
922 static int
923 find_struct_ops_kern_types(const struct btf *btf, const char *tname,
924 			   const struct btf_type **type, __u32 *type_id,
925 			   const struct btf_type **vtype, __u32 *vtype_id,
926 			   const struct btf_member **data_member)
927 {
928 	const struct btf_type *kern_type, *kern_vtype;
929 	const struct btf_member *kern_data_member;
930 	__s32 kern_vtype_id, kern_type_id;
931 	__u32 i;
932 
933 	kern_type_id = btf__find_by_name_kind(btf, tname, BTF_KIND_STRUCT);
934 	if (kern_type_id < 0) {
935 		pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n",
936 			tname);
937 		return kern_type_id;
938 	}
939 	kern_type = btf__type_by_id(btf, kern_type_id);
940 
941 	/* Find the corresponding "map_value" type that will be used
942 	 * in map_update(BPF_MAP_TYPE_STRUCT_OPS).  For example,
943 	 * find "struct bpf_struct_ops_tcp_congestion_ops" from the
944 	 * btf_vmlinux.
945 	 */
946 	kern_vtype_id = find_btf_by_prefix_kind(btf, STRUCT_OPS_VALUE_PREFIX,
947 						tname, BTF_KIND_STRUCT);
948 	if (kern_vtype_id < 0) {
949 		pr_warn("struct_ops init_kern: struct %s%s is not found in kernel BTF\n",
950 			STRUCT_OPS_VALUE_PREFIX, tname);
951 		return kern_vtype_id;
952 	}
953 	kern_vtype = btf__type_by_id(btf, kern_vtype_id);
954 
955 	/* Find "struct tcp_congestion_ops" from
956 	 * struct bpf_struct_ops_tcp_congestion_ops {
957 	 *	[ ... ]
958 	 *	struct tcp_congestion_ops data;
959 	 * }
960 	 */
961 	kern_data_member = btf_members(kern_vtype);
962 	for (i = 0; i < btf_vlen(kern_vtype); i++, kern_data_member++) {
963 		if (kern_data_member->type == kern_type_id)
964 			break;
965 	}
966 	if (i == btf_vlen(kern_vtype)) {
967 		pr_warn("struct_ops init_kern: struct %s data is not found in struct %s%s\n",
968 			tname, STRUCT_OPS_VALUE_PREFIX, tname);
969 		return -EINVAL;
970 	}
971 
972 	*type = kern_type;
973 	*type_id = kern_type_id;
974 	*vtype = kern_vtype;
975 	*vtype_id = kern_vtype_id;
976 	*data_member = kern_data_member;
977 
978 	return 0;
979 }
980 
981 static bool bpf_map__is_struct_ops(const struct bpf_map *map)
982 {
983 	return map->def.type == BPF_MAP_TYPE_STRUCT_OPS;
984 }
985 
986 /* Init the map's fields that depend on kern_btf */
987 static int bpf_map__init_kern_struct_ops(struct bpf_map *map,
988 					 const struct btf *btf,
989 					 const struct btf *kern_btf)
990 {
991 	const struct btf_member *member, *kern_member, *kern_data_member;
992 	const struct btf_type *type, *kern_type, *kern_vtype;
993 	__u32 i, kern_type_id, kern_vtype_id, kern_data_off;
994 	struct bpf_struct_ops *st_ops;
995 	void *data, *kern_data;
996 	const char *tname;
997 	int err;
998 
999 	st_ops = map->st_ops;
1000 	type = st_ops->type;
1001 	tname = st_ops->tname;
1002 	err = find_struct_ops_kern_types(kern_btf, tname,
1003 					 &kern_type, &kern_type_id,
1004 					 &kern_vtype, &kern_vtype_id,
1005 					 &kern_data_member);
1006 	if (err)
1007 		return err;
1008 
1009 	pr_debug("struct_ops init_kern %s: type_id:%u kern_type_id:%u kern_vtype_id:%u\n",
1010 		 map->name, st_ops->type_id, kern_type_id, kern_vtype_id);
1011 
1012 	map->def.value_size = kern_vtype->size;
1013 	map->btf_vmlinux_value_type_id = kern_vtype_id;
1014 
1015 	st_ops->kern_vdata = calloc(1, kern_vtype->size);
1016 	if (!st_ops->kern_vdata)
1017 		return -ENOMEM;
1018 
1019 	data = st_ops->data;
1020 	kern_data_off = kern_data_member->offset / 8;
1021 	kern_data = st_ops->kern_vdata + kern_data_off;
1022 
1023 	member = btf_members(type);
1024 	for (i = 0; i < btf_vlen(type); i++, member++) {
1025 		const struct btf_type *mtype, *kern_mtype;
1026 		__u32 mtype_id, kern_mtype_id;
1027 		void *mdata, *kern_mdata;
1028 		__s64 msize, kern_msize;
1029 		__u32 moff, kern_moff;
1030 		__u32 kern_member_idx;
1031 		const char *mname;
1032 
1033 		mname = btf__name_by_offset(btf, member->name_off);
1034 		kern_member = find_member_by_name(kern_btf, kern_type, mname);
1035 		if (!kern_member) {
1036 			pr_warn("struct_ops init_kern %s: Cannot find member %s in kernel BTF\n",
1037 				map->name, mname);
1038 			return -ENOTSUP;
1039 		}
1040 
1041 		kern_member_idx = kern_member - btf_members(kern_type);
1042 		if (btf_member_bitfield_size(type, i) ||
1043 		    btf_member_bitfield_size(kern_type, kern_member_idx)) {
1044 			pr_warn("struct_ops init_kern %s: bitfield %s is not supported\n",
1045 				map->name, mname);
1046 			return -ENOTSUP;
1047 		}
1048 
1049 		moff = member->offset / 8;
1050 		kern_moff = kern_member->offset / 8;
1051 
1052 		mdata = data + moff;
1053 		kern_mdata = kern_data + kern_moff;
1054 
1055 		mtype = skip_mods_and_typedefs(btf, member->type, &mtype_id);
1056 		kern_mtype = skip_mods_and_typedefs(kern_btf, kern_member->type,
1057 						    &kern_mtype_id);
1058 		if (BTF_INFO_KIND(mtype->info) !=
1059 		    BTF_INFO_KIND(kern_mtype->info)) {
1060 			pr_warn("struct_ops init_kern %s: Unmatched member type %s %u != %u(kernel)\n",
1061 				map->name, mname, BTF_INFO_KIND(mtype->info),
1062 				BTF_INFO_KIND(kern_mtype->info));
1063 			return -ENOTSUP;
1064 		}
1065 
1066 		if (btf_is_ptr(mtype)) {
1067 			struct bpf_program *prog;
1068 
1069 			prog = st_ops->progs[i];
1070 			if (!prog)
1071 				continue;
1072 
1073 			kern_mtype = skip_mods_and_typedefs(kern_btf,
1074 							    kern_mtype->type,
1075 							    &kern_mtype_id);
1076 
1077 			/* mtype->type must be a func_proto which was
1078 			 * guaranteed in bpf_object__collect_st_ops_relos(),
1079 			 * so only check kern_mtype for func_proto here.
1080 			 */
1081 			if (!btf_is_func_proto(kern_mtype)) {
1082 				pr_warn("struct_ops init_kern %s: kernel member %s is not a func ptr\n",
1083 					map->name, mname);
1084 				return -ENOTSUP;
1085 			}
1086 
1087 			prog->attach_btf_id = kern_type_id;
1088 			prog->expected_attach_type = kern_member_idx;
1089 
1090 			st_ops->kern_func_off[i] = kern_data_off + kern_moff;
1091 
1092 			pr_debug("struct_ops init_kern %s: func ptr %s is set to prog %s from data(+%u) to kern_data(+%u)\n",
1093 				 map->name, mname, prog->name, moff,
1094 				 kern_moff);
1095 
1096 			continue;
1097 		}
1098 
1099 		msize = btf__resolve_size(btf, mtype_id);
1100 		kern_msize = btf__resolve_size(kern_btf, kern_mtype_id);
1101 		if (msize < 0 || kern_msize < 0 || msize != kern_msize) {
1102 			pr_warn("struct_ops init_kern %s: Error in size of member %s: %zd != %zd(kernel)\n",
1103 				map->name, mname, (ssize_t)msize,
1104 				(ssize_t)kern_msize);
1105 			return -ENOTSUP;
1106 		}
1107 
1108 		pr_debug("struct_ops init_kern %s: copy %s %u bytes from data(+%u) to kern_data(+%u)\n",
1109 			 map->name, mname, (unsigned int)msize,
1110 			 moff, kern_moff);
1111 		memcpy(kern_mdata, mdata, msize);
1112 	}
1113 
1114 	return 0;
1115 }
1116 
1117 static int bpf_object__init_kern_struct_ops_maps(struct bpf_object *obj)
1118 {
1119 	struct bpf_map *map;
1120 	size_t i;
1121 	int err;
1122 
1123 	for (i = 0; i < obj->nr_maps; i++) {
1124 		map = &obj->maps[i];
1125 
1126 		if (!bpf_map__is_struct_ops(map))
1127 			continue;
1128 
1129 		err = bpf_map__init_kern_struct_ops(map, obj->btf,
1130 						    obj->btf_vmlinux);
1131 		if (err)
1132 			return err;
1133 	}
1134 
1135 	return 0;
1136 }
1137 
1138 static int init_struct_ops_maps(struct bpf_object *obj, const char *sec_name,
1139 				int shndx, Elf_Data *data, __u32 map_flags)
1140 {
1141 	const struct btf_type *type, *datasec;
1142 	const struct btf_var_secinfo *vsi;
1143 	struct bpf_struct_ops *st_ops;
1144 	const char *tname, *var_name;
1145 	__s32 type_id, datasec_id;
1146 	const struct btf *btf;
1147 	struct bpf_map *map;
1148 	__u32 i;
1149 
1150 	if (shndx == -1)
1151 		return 0;
1152 
1153 	btf = obj->btf;
1154 	datasec_id = btf__find_by_name_kind(btf, sec_name,
1155 					    BTF_KIND_DATASEC);
1156 	if (datasec_id < 0) {
1157 		pr_warn("struct_ops init: DATASEC %s not found\n",
1158 			sec_name);
1159 		return -EINVAL;
1160 	}
1161 
1162 	datasec = btf__type_by_id(btf, datasec_id);
1163 	vsi = btf_var_secinfos(datasec);
1164 	for (i = 0; i < btf_vlen(datasec); i++, vsi++) {
1165 		type = btf__type_by_id(obj->btf, vsi->type);
1166 		var_name = btf__name_by_offset(obj->btf, type->name_off);
1167 
1168 		type_id = btf__resolve_type(obj->btf, vsi->type);
1169 		if (type_id < 0) {
1170 			pr_warn("struct_ops init: Cannot resolve var type_id %u in DATASEC %s\n",
1171 				vsi->type, sec_name);
1172 			return -EINVAL;
1173 		}
1174 
1175 		type = btf__type_by_id(obj->btf, type_id);
1176 		tname = btf__name_by_offset(obj->btf, type->name_off);
1177 		if (!tname[0]) {
1178 			pr_warn("struct_ops init: anonymous type is not supported\n");
1179 			return -ENOTSUP;
1180 		}
1181 		if (!btf_is_struct(type)) {
1182 			pr_warn("struct_ops init: %s is not a struct\n", tname);
1183 			return -EINVAL;
1184 		}
1185 
1186 		map = bpf_object__add_map(obj);
1187 		if (IS_ERR(map))
1188 			return PTR_ERR(map);
1189 
1190 		map->sec_idx = shndx;
1191 		map->sec_offset = vsi->offset;
1192 		map->name = strdup(var_name);
1193 		if (!map->name)
1194 			return -ENOMEM;
1195 
1196 		map->def.type = BPF_MAP_TYPE_STRUCT_OPS;
1197 		map->def.key_size = sizeof(int);
1198 		map->def.value_size = type->size;
1199 		map->def.max_entries = 1;
1200 		map->def.map_flags = map_flags;
1201 
1202 		map->st_ops = calloc(1, sizeof(*map->st_ops));
1203 		if (!map->st_ops)
1204 			return -ENOMEM;
1205 		st_ops = map->st_ops;
1206 		st_ops->data = malloc(type->size);
1207 		st_ops->progs = calloc(btf_vlen(type), sizeof(*st_ops->progs));
1208 		st_ops->kern_func_off = malloc(btf_vlen(type) *
1209 					       sizeof(*st_ops->kern_func_off));
1210 		if (!st_ops->data || !st_ops->progs || !st_ops->kern_func_off)
1211 			return -ENOMEM;
1212 
1213 		if (vsi->offset + type->size > data->d_size) {
1214 			pr_warn("struct_ops init: var %s is beyond the end of DATASEC %s\n",
1215 				var_name, sec_name);
1216 			return -EINVAL;
1217 		}
1218 
1219 		memcpy(st_ops->data,
1220 		       data->d_buf + vsi->offset,
1221 		       type->size);
1222 		st_ops->tname = tname;
1223 		st_ops->type = type;
1224 		st_ops->type_id = type_id;
1225 
1226 		pr_debug("struct_ops init: struct %s(type_id=%u) %s found at offset %u\n",
1227 			 tname, type_id, var_name, vsi->offset);
1228 	}
1229 
1230 	return 0;
1231 }
1232 
1233 static int bpf_object_init_struct_ops(struct bpf_object *obj)
1234 {
1235 	int err;
1236 
1237 	err = init_struct_ops_maps(obj, STRUCT_OPS_SEC, obj->efile.st_ops_shndx,
1238 				   obj->efile.st_ops_data, 0);
1239 	err = err ?: init_struct_ops_maps(obj, STRUCT_OPS_LINK_SEC,
1240 					  obj->efile.st_ops_link_shndx,
1241 					  obj->efile.st_ops_link_data,
1242 					  BPF_F_LINK);
1243 	return err;
1244 }
1245 
1246 static struct bpf_object *bpf_object__new(const char *path,
1247 					  const void *obj_buf,
1248 					  size_t obj_buf_sz,
1249 					  const char *obj_name)
1250 {
1251 	struct bpf_object *obj;
1252 	char *end;
1253 
1254 	obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
1255 	if (!obj) {
1256 		pr_warn("alloc memory failed for %s\n", path);
1257 		return ERR_PTR(-ENOMEM);
1258 	}
1259 
1260 	strcpy(obj->path, path);
1261 	if (obj_name) {
1262 		libbpf_strlcpy(obj->name, obj_name, sizeof(obj->name));
1263 	} else {
1264 		/* Using basename() GNU version which doesn't modify arg. */
1265 		libbpf_strlcpy(obj->name, basename((void *)path), sizeof(obj->name));
1266 		end = strchr(obj->name, '.');
1267 		if (end)
1268 			*end = 0;
1269 	}
1270 
1271 	obj->efile.fd = -1;
1272 	/*
1273 	 * Caller of this function should also call
1274 	 * bpf_object__elf_finish() after data collection to return
1275 	 * obj_buf to user. If not, we should duplicate the buffer to
1276 	 * avoid user freeing them before elf finish.
1277 	 */
1278 	obj->efile.obj_buf = obj_buf;
1279 	obj->efile.obj_buf_sz = obj_buf_sz;
1280 	obj->efile.btf_maps_shndx = -1;
1281 	obj->efile.st_ops_shndx = -1;
1282 	obj->efile.st_ops_link_shndx = -1;
1283 	obj->kconfig_map_idx = -1;
1284 
1285 	obj->kern_version = get_kernel_version();
1286 	obj->loaded = false;
1287 
1288 	return obj;
1289 }
1290 
1291 static void bpf_object__elf_finish(struct bpf_object *obj)
1292 {
1293 	if (!obj->efile.elf)
1294 		return;
1295 
1296 	elf_end(obj->efile.elf);
1297 	obj->efile.elf = NULL;
1298 	obj->efile.symbols = NULL;
1299 	obj->efile.st_ops_data = NULL;
1300 	obj->efile.st_ops_link_data = NULL;
1301 
1302 	zfree(&obj->efile.secs);
1303 	obj->efile.sec_cnt = 0;
1304 	zclose(obj->efile.fd);
1305 	obj->efile.obj_buf = NULL;
1306 	obj->efile.obj_buf_sz = 0;
1307 }
1308 
1309 static int bpf_object__elf_init(struct bpf_object *obj)
1310 {
1311 	Elf64_Ehdr *ehdr;
1312 	int err = 0;
1313 	Elf *elf;
1314 
1315 	if (obj->efile.elf) {
1316 		pr_warn("elf: init internal error\n");
1317 		return -LIBBPF_ERRNO__LIBELF;
1318 	}
1319 
1320 	if (obj->efile.obj_buf_sz > 0) {
1321 		/* obj_buf should have been validated by bpf_object__open_mem(). */
1322 		elf = elf_memory((char *)obj->efile.obj_buf, obj->efile.obj_buf_sz);
1323 	} else {
1324 		obj->efile.fd = open(obj->path, O_RDONLY | O_CLOEXEC);
1325 		if (obj->efile.fd < 0) {
1326 			char errmsg[STRERR_BUFSIZE], *cp;
1327 
1328 			err = -errno;
1329 			cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
1330 			pr_warn("elf: failed to open %s: %s\n", obj->path, cp);
1331 			return err;
1332 		}
1333 
1334 		elf = elf_begin(obj->efile.fd, ELF_C_READ_MMAP, NULL);
1335 	}
1336 
1337 	if (!elf) {
1338 		pr_warn("elf: failed to open %s as ELF file: %s\n", obj->path, elf_errmsg(-1));
1339 		err = -LIBBPF_ERRNO__LIBELF;
1340 		goto errout;
1341 	}
1342 
1343 	obj->efile.elf = elf;
1344 
1345 	if (elf_kind(elf) != ELF_K_ELF) {
1346 		err = -LIBBPF_ERRNO__FORMAT;
1347 		pr_warn("elf: '%s' is not a proper ELF object\n", obj->path);
1348 		goto errout;
1349 	}
1350 
1351 	if (gelf_getclass(elf) != ELFCLASS64) {
1352 		err = -LIBBPF_ERRNO__FORMAT;
1353 		pr_warn("elf: '%s' is not a 64-bit ELF object\n", obj->path);
1354 		goto errout;
1355 	}
1356 
1357 	obj->efile.ehdr = ehdr = elf64_getehdr(elf);
1358 	if (!obj->efile.ehdr) {
1359 		pr_warn("elf: failed to get ELF header from %s: %s\n", obj->path, elf_errmsg(-1));
1360 		err = -LIBBPF_ERRNO__FORMAT;
1361 		goto errout;
1362 	}
1363 
1364 	if (elf_getshdrstrndx(elf, &obj->efile.shstrndx)) {
1365 		pr_warn("elf: failed to get section names section index for %s: %s\n",
1366 			obj->path, elf_errmsg(-1));
1367 		err = -LIBBPF_ERRNO__FORMAT;
1368 		goto errout;
1369 	}
1370 
1371 	/* ELF is corrupted/truncated, avoid calling elf_strptr. */
1372 	if (!elf_rawdata(elf_getscn(elf, obj->efile.shstrndx), NULL)) {
1373 		pr_warn("elf: failed to get section names strings from %s: %s\n",
1374 			obj->path, elf_errmsg(-1));
1375 		err = -LIBBPF_ERRNO__FORMAT;
1376 		goto errout;
1377 	}
1378 
1379 	/* Old LLVM set e_machine to EM_NONE */
1380 	if (ehdr->e_type != ET_REL || (ehdr->e_machine && ehdr->e_machine != EM_BPF)) {
1381 		pr_warn("elf: %s is not a valid eBPF object file\n", obj->path);
1382 		err = -LIBBPF_ERRNO__FORMAT;
1383 		goto errout;
1384 	}
1385 
1386 	return 0;
1387 errout:
1388 	bpf_object__elf_finish(obj);
1389 	return err;
1390 }
1391 
1392 static int bpf_object__check_endianness(struct bpf_object *obj)
1393 {
1394 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1395 	if (obj->efile.ehdr->e_ident[EI_DATA] == ELFDATA2LSB)
1396 		return 0;
1397 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
1398 	if (obj->efile.ehdr->e_ident[EI_DATA] == ELFDATA2MSB)
1399 		return 0;
1400 #else
1401 # error "Unrecognized __BYTE_ORDER__"
1402 #endif
1403 	pr_warn("elf: endianness mismatch in %s.\n", obj->path);
1404 	return -LIBBPF_ERRNO__ENDIAN;
1405 }
1406 
1407 static int
1408 bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
1409 {
1410 	if (!data) {
1411 		pr_warn("invalid license section in %s\n", obj->path);
1412 		return -LIBBPF_ERRNO__FORMAT;
1413 	}
1414 	/* libbpf_strlcpy() only copies first N - 1 bytes, so size + 1 won't
1415 	 * go over allowed ELF data section buffer
1416 	 */
1417 	libbpf_strlcpy(obj->license, data, min(size + 1, sizeof(obj->license)));
1418 	pr_debug("license of %s is %s\n", obj->path, obj->license);
1419 	return 0;
1420 }
1421 
1422 static int
1423 bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
1424 {
1425 	__u32 kver;
1426 
1427 	if (!data || size != sizeof(kver)) {
1428 		pr_warn("invalid kver section in %s\n", obj->path);
1429 		return -LIBBPF_ERRNO__FORMAT;
1430 	}
1431 	memcpy(&kver, data, sizeof(kver));
1432 	obj->kern_version = kver;
1433 	pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
1434 	return 0;
1435 }
1436 
1437 static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
1438 {
1439 	if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
1440 	    type == BPF_MAP_TYPE_HASH_OF_MAPS)
1441 		return true;
1442 	return false;
1443 }
1444 
1445 static int find_elf_sec_sz(const struct bpf_object *obj, const char *name, __u32 *size)
1446 {
1447 	Elf_Data *data;
1448 	Elf_Scn *scn;
1449 
1450 	if (!name)
1451 		return -EINVAL;
1452 
1453 	scn = elf_sec_by_name(obj, name);
1454 	data = elf_sec_data(obj, scn);
1455 	if (data) {
1456 		*size = data->d_size;
1457 		return 0; /* found it */
1458 	}
1459 
1460 	return -ENOENT;
1461 }
1462 
1463 static Elf64_Sym *find_elf_var_sym(const struct bpf_object *obj, const char *name)
1464 {
1465 	Elf_Data *symbols = obj->efile.symbols;
1466 	const char *sname;
1467 	size_t si;
1468 
1469 	for (si = 0; si < symbols->d_size / sizeof(Elf64_Sym); si++) {
1470 		Elf64_Sym *sym = elf_sym_by_idx(obj, si);
1471 
1472 		if (ELF64_ST_TYPE(sym->st_info) != STT_OBJECT)
1473 			continue;
1474 
1475 		if (ELF64_ST_BIND(sym->st_info) != STB_GLOBAL &&
1476 		    ELF64_ST_BIND(sym->st_info) != STB_WEAK)
1477 			continue;
1478 
1479 		sname = elf_sym_str(obj, sym->st_name);
1480 		if (!sname) {
1481 			pr_warn("failed to get sym name string for var %s\n", name);
1482 			return ERR_PTR(-EIO);
1483 		}
1484 		if (strcmp(name, sname) == 0)
1485 			return sym;
1486 	}
1487 
1488 	return ERR_PTR(-ENOENT);
1489 }
1490 
1491 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
1492 {
1493 	struct bpf_map *map;
1494 	int err;
1495 
1496 	err = libbpf_ensure_mem((void **)&obj->maps, &obj->maps_cap,
1497 				sizeof(*obj->maps), obj->nr_maps + 1);
1498 	if (err)
1499 		return ERR_PTR(err);
1500 
1501 	map = &obj->maps[obj->nr_maps++];
1502 	map->obj = obj;
1503 	map->fd = -1;
1504 	map->inner_map_fd = -1;
1505 	map->autocreate = true;
1506 
1507 	return map;
1508 }
1509 
1510 static size_t bpf_map_mmap_sz(unsigned int value_sz, unsigned int max_entries)
1511 {
1512 	const long page_sz = sysconf(_SC_PAGE_SIZE);
1513 	size_t map_sz;
1514 
1515 	map_sz = (size_t)roundup(value_sz, 8) * max_entries;
1516 	map_sz = roundup(map_sz, page_sz);
1517 	return map_sz;
1518 }
1519 
1520 static int bpf_map_mmap_resize(struct bpf_map *map, size_t old_sz, size_t new_sz)
1521 {
1522 	void *mmaped;
1523 
1524 	if (!map->mmaped)
1525 		return -EINVAL;
1526 
1527 	if (old_sz == new_sz)
1528 		return 0;
1529 
1530 	mmaped = mmap(NULL, new_sz, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1531 	if (mmaped == MAP_FAILED)
1532 		return -errno;
1533 
1534 	memcpy(mmaped, map->mmaped, min(old_sz, new_sz));
1535 	munmap(map->mmaped, old_sz);
1536 	map->mmaped = mmaped;
1537 	return 0;
1538 }
1539 
1540 static char *internal_map_name(struct bpf_object *obj, const char *real_name)
1541 {
1542 	char map_name[BPF_OBJ_NAME_LEN], *p;
1543 	int pfx_len, sfx_len = max((size_t)7, strlen(real_name));
1544 
1545 	/* This is one of the more confusing parts of libbpf for various
1546 	 * reasons, some of which are historical. The original idea for naming
1547 	 * internal names was to include as much of BPF object name prefix as
1548 	 * possible, so that it can be distinguished from similar internal
1549 	 * maps of a different BPF object.
1550 	 * As an example, let's say we have bpf_object named 'my_object_name'
1551 	 * and internal map corresponding to '.rodata' ELF section. The final
1552 	 * map name advertised to user and to the kernel will be
1553 	 * 'my_objec.rodata', taking first 8 characters of object name and
1554 	 * entire 7 characters of '.rodata'.
1555 	 * Somewhat confusingly, if internal map ELF section name is shorter
1556 	 * than 7 characters, e.g., '.bss', we still reserve 7 characters
1557 	 * for the suffix, even though we only have 4 actual characters, and
1558 	 * resulting map will be called 'my_objec.bss', not even using all 15
1559 	 * characters allowed by the kernel. Oh well, at least the truncated
1560 	 * object name is somewhat consistent in this case. But if the map
1561 	 * name is '.kconfig', we'll still have entirety of '.kconfig' added
1562 	 * (8 chars) and thus will be left with only first 7 characters of the
1563 	 * object name ('my_obje'). Happy guessing, user, that the final map
1564 	 * name will be "my_obje.kconfig".
1565 	 * Now, with libbpf starting to support arbitrarily named .rodata.*
1566 	 * and .data.* data sections, it's possible that ELF section name is
1567 	 * longer than allowed 15 chars, so we now need to be careful to take
1568 	 * only up to 15 first characters of ELF name, taking no BPF object
1569 	 * name characters at all. So '.rodata.abracadabra' will result in
1570 	 * '.rodata.abracad' kernel and user-visible name.
1571 	 * We need to keep this convoluted logic intact for .data, .bss and
1572 	 * .rodata maps, but for new custom .data.custom and .rodata.custom
1573 	 * maps we use their ELF names as is, not prepending bpf_object name
1574 	 * in front. We still need to truncate them to 15 characters for the
1575 	 * kernel. Full name can be recovered for such maps by using DATASEC
1576 	 * BTF type associated with such map's value type, though.
1577 	 */
1578 	if (sfx_len >= BPF_OBJ_NAME_LEN)
1579 		sfx_len = BPF_OBJ_NAME_LEN - 1;
1580 
1581 	/* if there are two or more dots in map name, it's a custom dot map */
1582 	if (strchr(real_name + 1, '.') != NULL)
1583 		pfx_len = 0;
1584 	else
1585 		pfx_len = min((size_t)BPF_OBJ_NAME_LEN - sfx_len - 1, strlen(obj->name));
1586 
1587 	snprintf(map_name, sizeof(map_name), "%.*s%.*s", pfx_len, obj->name,
1588 		 sfx_len, real_name);
1589 
1590 	/* sanitise map name to characters allowed by kernel */
1591 	for (p = map_name; *p && p < map_name + sizeof(map_name); p++)
1592 		if (!isalnum(*p) && *p != '_' && *p != '.')
1593 			*p = '_';
1594 
1595 	return strdup(map_name);
1596 }
1597 
1598 static int
1599 map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map);
1600 
1601 /* Internal BPF map is mmap()'able only if at least one of corresponding
1602  * DATASEC's VARs are to be exposed through BPF skeleton. I.e., it's a GLOBAL
1603  * variable and it's not marked as __hidden (which turns it into, effectively,
1604  * a STATIC variable).
1605  */
1606 static bool map_is_mmapable(struct bpf_object *obj, struct bpf_map *map)
1607 {
1608 	const struct btf_type *t, *vt;
1609 	struct btf_var_secinfo *vsi;
1610 	int i, n;
1611 
1612 	if (!map->btf_value_type_id)
1613 		return false;
1614 
1615 	t = btf__type_by_id(obj->btf, map->btf_value_type_id);
1616 	if (!btf_is_datasec(t))
1617 		return false;
1618 
1619 	vsi = btf_var_secinfos(t);
1620 	for (i = 0, n = btf_vlen(t); i < n; i++, vsi++) {
1621 		vt = btf__type_by_id(obj->btf, vsi->type);
1622 		if (!btf_is_var(vt))
1623 			continue;
1624 
1625 		if (btf_var(vt)->linkage != BTF_VAR_STATIC)
1626 			return true;
1627 	}
1628 
1629 	return false;
1630 }
1631 
1632 static int
1633 bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
1634 			      const char *real_name, int sec_idx, void *data, size_t data_sz)
1635 {
1636 	struct bpf_map_def *def;
1637 	struct bpf_map *map;
1638 	size_t mmap_sz;
1639 	int err;
1640 
1641 	map = bpf_object__add_map(obj);
1642 	if (IS_ERR(map))
1643 		return PTR_ERR(map);
1644 
1645 	map->libbpf_type = type;
1646 	map->sec_idx = sec_idx;
1647 	map->sec_offset = 0;
1648 	map->real_name = strdup(real_name);
1649 	map->name = internal_map_name(obj, real_name);
1650 	if (!map->real_name || !map->name) {
1651 		zfree(&map->real_name);
1652 		zfree(&map->name);
1653 		return -ENOMEM;
1654 	}
1655 
1656 	def = &map->def;
1657 	def->type = BPF_MAP_TYPE_ARRAY;
1658 	def->key_size = sizeof(int);
1659 	def->value_size = data_sz;
1660 	def->max_entries = 1;
1661 	def->map_flags = type == LIBBPF_MAP_RODATA || type == LIBBPF_MAP_KCONFIG
1662 			 ? BPF_F_RDONLY_PROG : 0;
1663 
1664 	/* failures are fine because of maps like .rodata.str1.1 */
1665 	(void) map_fill_btf_type_info(obj, map);
1666 
1667 	if (map_is_mmapable(obj, map))
1668 		def->map_flags |= BPF_F_MMAPABLE;
1669 
1670 	pr_debug("map '%s' (global data): at sec_idx %d, offset %zu, flags %x.\n",
1671 		 map->name, map->sec_idx, map->sec_offset, def->map_flags);
1672 
1673 	mmap_sz = bpf_map_mmap_sz(map->def.value_size, map->def.max_entries);
1674 	map->mmaped = mmap(NULL, mmap_sz, PROT_READ | PROT_WRITE,
1675 			   MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1676 	if (map->mmaped == MAP_FAILED) {
1677 		err = -errno;
1678 		map->mmaped = NULL;
1679 		pr_warn("failed to alloc map '%s' content buffer: %d\n",
1680 			map->name, err);
1681 		zfree(&map->real_name);
1682 		zfree(&map->name);
1683 		return err;
1684 	}
1685 
1686 	if (data)
1687 		memcpy(map->mmaped, data, data_sz);
1688 
1689 	pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
1690 	return 0;
1691 }
1692 
1693 static int bpf_object__init_global_data_maps(struct bpf_object *obj)
1694 {
1695 	struct elf_sec_desc *sec_desc;
1696 	const char *sec_name;
1697 	int err = 0, sec_idx;
1698 
1699 	/*
1700 	 * Populate obj->maps with libbpf internal maps.
1701 	 */
1702 	for (sec_idx = 1; sec_idx < obj->efile.sec_cnt; sec_idx++) {
1703 		sec_desc = &obj->efile.secs[sec_idx];
1704 
1705 		/* Skip recognized sections with size 0. */
1706 		if (!sec_desc->data || sec_desc->data->d_size == 0)
1707 			continue;
1708 
1709 		switch (sec_desc->sec_type) {
1710 		case SEC_DATA:
1711 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1712 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
1713 							    sec_name, sec_idx,
1714 							    sec_desc->data->d_buf,
1715 							    sec_desc->data->d_size);
1716 			break;
1717 		case SEC_RODATA:
1718 			obj->has_rodata = true;
1719 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1720 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
1721 							    sec_name, sec_idx,
1722 							    sec_desc->data->d_buf,
1723 							    sec_desc->data->d_size);
1724 			break;
1725 		case SEC_BSS:
1726 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1727 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
1728 							    sec_name, sec_idx,
1729 							    NULL,
1730 							    sec_desc->data->d_size);
1731 			break;
1732 		default:
1733 			/* skip */
1734 			break;
1735 		}
1736 		if (err)
1737 			return err;
1738 	}
1739 	return 0;
1740 }
1741 
1742 
1743 static struct extern_desc *find_extern_by_name(const struct bpf_object *obj,
1744 					       const void *name)
1745 {
1746 	int i;
1747 
1748 	for (i = 0; i < obj->nr_extern; i++) {
1749 		if (strcmp(obj->externs[i].name, name) == 0)
1750 			return &obj->externs[i];
1751 	}
1752 	return NULL;
1753 }
1754 
1755 static int set_kcfg_value_tri(struct extern_desc *ext, void *ext_val,
1756 			      char value)
1757 {
1758 	switch (ext->kcfg.type) {
1759 	case KCFG_BOOL:
1760 		if (value == 'm') {
1761 			pr_warn("extern (kcfg) '%s': value '%c' implies tristate or char type\n",
1762 				ext->name, value);
1763 			return -EINVAL;
1764 		}
1765 		*(bool *)ext_val = value == 'y' ? true : false;
1766 		break;
1767 	case KCFG_TRISTATE:
1768 		if (value == 'y')
1769 			*(enum libbpf_tristate *)ext_val = TRI_YES;
1770 		else if (value == 'm')
1771 			*(enum libbpf_tristate *)ext_val = TRI_MODULE;
1772 		else /* value == 'n' */
1773 			*(enum libbpf_tristate *)ext_val = TRI_NO;
1774 		break;
1775 	case KCFG_CHAR:
1776 		*(char *)ext_val = value;
1777 		break;
1778 	case KCFG_UNKNOWN:
1779 	case KCFG_INT:
1780 	case KCFG_CHAR_ARR:
1781 	default:
1782 		pr_warn("extern (kcfg) '%s': value '%c' implies bool, tristate, or char type\n",
1783 			ext->name, value);
1784 		return -EINVAL;
1785 	}
1786 	ext->is_set = true;
1787 	return 0;
1788 }
1789 
1790 static int set_kcfg_value_str(struct extern_desc *ext, char *ext_val,
1791 			      const char *value)
1792 {
1793 	size_t len;
1794 
1795 	if (ext->kcfg.type != KCFG_CHAR_ARR) {
1796 		pr_warn("extern (kcfg) '%s': value '%s' implies char array type\n",
1797 			ext->name, value);
1798 		return -EINVAL;
1799 	}
1800 
1801 	len = strlen(value);
1802 	if (value[len - 1] != '"') {
1803 		pr_warn("extern (kcfg) '%s': invalid string config '%s'\n",
1804 			ext->name, value);
1805 		return -EINVAL;
1806 	}
1807 
1808 	/* strip quotes */
1809 	len -= 2;
1810 	if (len >= ext->kcfg.sz) {
1811 		pr_warn("extern (kcfg) '%s': long string '%s' of (%zu bytes) truncated to %d bytes\n",
1812 			ext->name, value, len, ext->kcfg.sz - 1);
1813 		len = ext->kcfg.sz - 1;
1814 	}
1815 	memcpy(ext_val, value + 1, len);
1816 	ext_val[len] = '\0';
1817 	ext->is_set = true;
1818 	return 0;
1819 }
1820 
1821 static int parse_u64(const char *value, __u64 *res)
1822 {
1823 	char *value_end;
1824 	int err;
1825 
1826 	errno = 0;
1827 	*res = strtoull(value, &value_end, 0);
1828 	if (errno) {
1829 		err = -errno;
1830 		pr_warn("failed to parse '%s' as integer: %d\n", value, err);
1831 		return err;
1832 	}
1833 	if (*value_end) {
1834 		pr_warn("failed to parse '%s' as integer completely\n", value);
1835 		return -EINVAL;
1836 	}
1837 	return 0;
1838 }
1839 
1840 static bool is_kcfg_value_in_range(const struct extern_desc *ext, __u64 v)
1841 {
1842 	int bit_sz = ext->kcfg.sz * 8;
1843 
1844 	if (ext->kcfg.sz == 8)
1845 		return true;
1846 
1847 	/* Validate that value stored in u64 fits in integer of `ext->sz`
1848 	 * bytes size without any loss of information. If the target integer
1849 	 * is signed, we rely on the following limits of integer type of
1850 	 * Y bits and subsequent transformation:
1851 	 *
1852 	 *     -2^(Y-1) <= X           <= 2^(Y-1) - 1
1853 	 *            0 <= X + 2^(Y-1) <= 2^Y - 1
1854 	 *            0 <= X + 2^(Y-1) <  2^Y
1855 	 *
1856 	 *  For unsigned target integer, check that all the (64 - Y) bits are
1857 	 *  zero.
1858 	 */
1859 	if (ext->kcfg.is_signed)
1860 		return v + (1ULL << (bit_sz - 1)) < (1ULL << bit_sz);
1861 	else
1862 		return (v >> bit_sz) == 0;
1863 }
1864 
1865 static int set_kcfg_value_num(struct extern_desc *ext, void *ext_val,
1866 			      __u64 value)
1867 {
1868 	if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR &&
1869 	    ext->kcfg.type != KCFG_BOOL) {
1870 		pr_warn("extern (kcfg) '%s': value '%llu' implies integer, char, or boolean type\n",
1871 			ext->name, (unsigned long long)value);
1872 		return -EINVAL;
1873 	}
1874 	if (ext->kcfg.type == KCFG_BOOL && value > 1) {
1875 		pr_warn("extern (kcfg) '%s': value '%llu' isn't boolean compatible\n",
1876 			ext->name, (unsigned long long)value);
1877 		return -EINVAL;
1878 
1879 	}
1880 	if (!is_kcfg_value_in_range(ext, value)) {
1881 		pr_warn("extern (kcfg) '%s': value '%llu' doesn't fit in %d bytes\n",
1882 			ext->name, (unsigned long long)value, ext->kcfg.sz);
1883 		return -ERANGE;
1884 	}
1885 	switch (ext->kcfg.sz) {
1886 	case 1:
1887 		*(__u8 *)ext_val = value;
1888 		break;
1889 	case 2:
1890 		*(__u16 *)ext_val = value;
1891 		break;
1892 	case 4:
1893 		*(__u32 *)ext_val = value;
1894 		break;
1895 	case 8:
1896 		*(__u64 *)ext_val = value;
1897 		break;
1898 	default:
1899 		return -EINVAL;
1900 	}
1901 	ext->is_set = true;
1902 	return 0;
1903 }
1904 
1905 static int bpf_object__process_kconfig_line(struct bpf_object *obj,
1906 					    char *buf, void *data)
1907 {
1908 	struct extern_desc *ext;
1909 	char *sep, *value;
1910 	int len, err = 0;
1911 	void *ext_val;
1912 	__u64 num;
1913 
1914 	if (!str_has_pfx(buf, "CONFIG_"))
1915 		return 0;
1916 
1917 	sep = strchr(buf, '=');
1918 	if (!sep) {
1919 		pr_warn("failed to parse '%s': no separator\n", buf);
1920 		return -EINVAL;
1921 	}
1922 
1923 	/* Trim ending '\n' */
1924 	len = strlen(buf);
1925 	if (buf[len - 1] == '\n')
1926 		buf[len - 1] = '\0';
1927 	/* Split on '=' and ensure that a value is present. */
1928 	*sep = '\0';
1929 	if (!sep[1]) {
1930 		*sep = '=';
1931 		pr_warn("failed to parse '%s': no value\n", buf);
1932 		return -EINVAL;
1933 	}
1934 
1935 	ext = find_extern_by_name(obj, buf);
1936 	if (!ext || ext->is_set)
1937 		return 0;
1938 
1939 	ext_val = data + ext->kcfg.data_off;
1940 	value = sep + 1;
1941 
1942 	switch (*value) {
1943 	case 'y': case 'n': case 'm':
1944 		err = set_kcfg_value_tri(ext, ext_val, *value);
1945 		break;
1946 	case '"':
1947 		err = set_kcfg_value_str(ext, ext_val, value);
1948 		break;
1949 	default:
1950 		/* assume integer */
1951 		err = parse_u64(value, &num);
1952 		if (err) {
1953 			pr_warn("extern (kcfg) '%s': value '%s' isn't a valid integer\n", ext->name, value);
1954 			return err;
1955 		}
1956 		if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR) {
1957 			pr_warn("extern (kcfg) '%s': value '%s' implies integer type\n", ext->name, value);
1958 			return -EINVAL;
1959 		}
1960 		err = set_kcfg_value_num(ext, ext_val, num);
1961 		break;
1962 	}
1963 	if (err)
1964 		return err;
1965 	pr_debug("extern (kcfg) '%s': set to %s\n", ext->name, value);
1966 	return 0;
1967 }
1968 
1969 static int bpf_object__read_kconfig_file(struct bpf_object *obj, void *data)
1970 {
1971 	char buf[PATH_MAX];
1972 	struct utsname uts;
1973 	int len, err = 0;
1974 	gzFile file;
1975 
1976 	uname(&uts);
1977 	len = snprintf(buf, PATH_MAX, "/boot/config-%s", uts.release);
1978 	if (len < 0)
1979 		return -EINVAL;
1980 	else if (len >= PATH_MAX)
1981 		return -ENAMETOOLONG;
1982 
1983 	/* gzopen also accepts uncompressed files. */
1984 	file = gzopen(buf, "re");
1985 	if (!file)
1986 		file = gzopen("/proc/config.gz", "re");
1987 
1988 	if (!file) {
1989 		pr_warn("failed to open system Kconfig\n");
1990 		return -ENOENT;
1991 	}
1992 
1993 	while (gzgets(file, buf, sizeof(buf))) {
1994 		err = bpf_object__process_kconfig_line(obj, buf, data);
1995 		if (err) {
1996 			pr_warn("error parsing system Kconfig line '%s': %d\n",
1997 				buf, err);
1998 			goto out;
1999 		}
2000 	}
2001 
2002 out:
2003 	gzclose(file);
2004 	return err;
2005 }
2006 
2007 static int bpf_object__read_kconfig_mem(struct bpf_object *obj,
2008 					const char *config, void *data)
2009 {
2010 	char buf[PATH_MAX];
2011 	int err = 0;
2012 	FILE *file;
2013 
2014 	file = fmemopen((void *)config, strlen(config), "r");
2015 	if (!file) {
2016 		err = -errno;
2017 		pr_warn("failed to open in-memory Kconfig: %d\n", err);
2018 		return err;
2019 	}
2020 
2021 	while (fgets(buf, sizeof(buf), file)) {
2022 		err = bpf_object__process_kconfig_line(obj, buf, data);
2023 		if (err) {
2024 			pr_warn("error parsing in-memory Kconfig line '%s': %d\n",
2025 				buf, err);
2026 			break;
2027 		}
2028 	}
2029 
2030 	fclose(file);
2031 	return err;
2032 }
2033 
2034 static int bpf_object__init_kconfig_map(struct bpf_object *obj)
2035 {
2036 	struct extern_desc *last_ext = NULL, *ext;
2037 	size_t map_sz;
2038 	int i, err;
2039 
2040 	for (i = 0; i < obj->nr_extern; i++) {
2041 		ext = &obj->externs[i];
2042 		if (ext->type == EXT_KCFG)
2043 			last_ext = ext;
2044 	}
2045 
2046 	if (!last_ext)
2047 		return 0;
2048 
2049 	map_sz = last_ext->kcfg.data_off + last_ext->kcfg.sz;
2050 	err = bpf_object__init_internal_map(obj, LIBBPF_MAP_KCONFIG,
2051 					    ".kconfig", obj->efile.symbols_shndx,
2052 					    NULL, map_sz);
2053 	if (err)
2054 		return err;
2055 
2056 	obj->kconfig_map_idx = obj->nr_maps - 1;
2057 
2058 	return 0;
2059 }
2060 
2061 const struct btf_type *
2062 skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id)
2063 {
2064 	const struct btf_type *t = btf__type_by_id(btf, id);
2065 
2066 	if (res_id)
2067 		*res_id = id;
2068 
2069 	while (btf_is_mod(t) || btf_is_typedef(t)) {
2070 		if (res_id)
2071 			*res_id = t->type;
2072 		t = btf__type_by_id(btf, t->type);
2073 	}
2074 
2075 	return t;
2076 }
2077 
2078 static const struct btf_type *
2079 resolve_func_ptr(const struct btf *btf, __u32 id, __u32 *res_id)
2080 {
2081 	const struct btf_type *t;
2082 
2083 	t = skip_mods_and_typedefs(btf, id, NULL);
2084 	if (!btf_is_ptr(t))
2085 		return NULL;
2086 
2087 	t = skip_mods_and_typedefs(btf, t->type, res_id);
2088 
2089 	return btf_is_func_proto(t) ? t : NULL;
2090 }
2091 
2092 static const char *__btf_kind_str(__u16 kind)
2093 {
2094 	switch (kind) {
2095 	case BTF_KIND_UNKN: return "void";
2096 	case BTF_KIND_INT: return "int";
2097 	case BTF_KIND_PTR: return "ptr";
2098 	case BTF_KIND_ARRAY: return "array";
2099 	case BTF_KIND_STRUCT: return "struct";
2100 	case BTF_KIND_UNION: return "union";
2101 	case BTF_KIND_ENUM: return "enum";
2102 	case BTF_KIND_FWD: return "fwd";
2103 	case BTF_KIND_TYPEDEF: return "typedef";
2104 	case BTF_KIND_VOLATILE: return "volatile";
2105 	case BTF_KIND_CONST: return "const";
2106 	case BTF_KIND_RESTRICT: return "restrict";
2107 	case BTF_KIND_FUNC: return "func";
2108 	case BTF_KIND_FUNC_PROTO: return "func_proto";
2109 	case BTF_KIND_VAR: return "var";
2110 	case BTF_KIND_DATASEC: return "datasec";
2111 	case BTF_KIND_FLOAT: return "float";
2112 	case BTF_KIND_DECL_TAG: return "decl_tag";
2113 	case BTF_KIND_TYPE_TAG: return "type_tag";
2114 	case BTF_KIND_ENUM64: return "enum64";
2115 	default: return "unknown";
2116 	}
2117 }
2118 
2119 const char *btf_kind_str(const struct btf_type *t)
2120 {
2121 	return __btf_kind_str(btf_kind(t));
2122 }
2123 
2124 /*
2125  * Fetch integer attribute of BTF map definition. Such attributes are
2126  * represented using a pointer to an array, in which dimensionality of array
2127  * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
2128  * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
2129  * type definition, while using only sizeof(void *) space in ELF data section.
2130  */
2131 static bool get_map_field_int(const char *map_name, const struct btf *btf,
2132 			      const struct btf_member *m, __u32 *res)
2133 {
2134 	const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
2135 	const char *name = btf__name_by_offset(btf, m->name_off);
2136 	const struct btf_array *arr_info;
2137 	const struct btf_type *arr_t;
2138 
2139 	if (!btf_is_ptr(t)) {
2140 		pr_warn("map '%s': attr '%s': expected PTR, got %s.\n",
2141 			map_name, name, btf_kind_str(t));
2142 		return false;
2143 	}
2144 
2145 	arr_t = btf__type_by_id(btf, t->type);
2146 	if (!arr_t) {
2147 		pr_warn("map '%s': attr '%s': type [%u] not found.\n",
2148 			map_name, name, t->type);
2149 		return false;
2150 	}
2151 	if (!btf_is_array(arr_t)) {
2152 		pr_warn("map '%s': attr '%s': expected ARRAY, got %s.\n",
2153 			map_name, name, btf_kind_str(arr_t));
2154 		return false;
2155 	}
2156 	arr_info = btf_array(arr_t);
2157 	*res = arr_info->nelems;
2158 	return true;
2159 }
2160 
2161 static int pathname_concat(char *buf, size_t buf_sz, const char *path, const char *name)
2162 {
2163 	int len;
2164 
2165 	len = snprintf(buf, buf_sz, "%s/%s", path, name);
2166 	if (len < 0)
2167 		return -EINVAL;
2168 	if (len >= buf_sz)
2169 		return -ENAMETOOLONG;
2170 
2171 	return 0;
2172 }
2173 
2174 static int build_map_pin_path(struct bpf_map *map, const char *path)
2175 {
2176 	char buf[PATH_MAX];
2177 	int err;
2178 
2179 	if (!path)
2180 		path = "/sys/fs/bpf";
2181 
2182 	err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
2183 	if (err)
2184 		return err;
2185 
2186 	return bpf_map__set_pin_path(map, buf);
2187 }
2188 
2189 /* should match definition in bpf_helpers.h */
2190 enum libbpf_pin_type {
2191 	LIBBPF_PIN_NONE,
2192 	/* PIN_BY_NAME: pin maps by name (in /sys/fs/bpf by default) */
2193 	LIBBPF_PIN_BY_NAME,
2194 };
2195 
2196 int parse_btf_map_def(const char *map_name, struct btf *btf,
2197 		      const struct btf_type *def_t, bool strict,
2198 		      struct btf_map_def *map_def, struct btf_map_def *inner_def)
2199 {
2200 	const struct btf_type *t;
2201 	const struct btf_member *m;
2202 	bool is_inner = inner_def == NULL;
2203 	int vlen, i;
2204 
2205 	vlen = btf_vlen(def_t);
2206 	m = btf_members(def_t);
2207 	for (i = 0; i < vlen; i++, m++) {
2208 		const char *name = btf__name_by_offset(btf, m->name_off);
2209 
2210 		if (!name) {
2211 			pr_warn("map '%s': invalid field #%d.\n", map_name, i);
2212 			return -EINVAL;
2213 		}
2214 		if (strcmp(name, "type") == 0) {
2215 			if (!get_map_field_int(map_name, btf, m, &map_def->map_type))
2216 				return -EINVAL;
2217 			map_def->parts |= MAP_DEF_MAP_TYPE;
2218 		} else if (strcmp(name, "max_entries") == 0) {
2219 			if (!get_map_field_int(map_name, btf, m, &map_def->max_entries))
2220 				return -EINVAL;
2221 			map_def->parts |= MAP_DEF_MAX_ENTRIES;
2222 		} else if (strcmp(name, "map_flags") == 0) {
2223 			if (!get_map_field_int(map_name, btf, m, &map_def->map_flags))
2224 				return -EINVAL;
2225 			map_def->parts |= MAP_DEF_MAP_FLAGS;
2226 		} else if (strcmp(name, "numa_node") == 0) {
2227 			if (!get_map_field_int(map_name, btf, m, &map_def->numa_node))
2228 				return -EINVAL;
2229 			map_def->parts |= MAP_DEF_NUMA_NODE;
2230 		} else if (strcmp(name, "key_size") == 0) {
2231 			__u32 sz;
2232 
2233 			if (!get_map_field_int(map_name, btf, m, &sz))
2234 				return -EINVAL;
2235 			if (map_def->key_size && map_def->key_size != sz) {
2236 				pr_warn("map '%s': conflicting key size %u != %u.\n",
2237 					map_name, map_def->key_size, sz);
2238 				return -EINVAL;
2239 			}
2240 			map_def->key_size = sz;
2241 			map_def->parts |= MAP_DEF_KEY_SIZE;
2242 		} else if (strcmp(name, "key") == 0) {
2243 			__s64 sz;
2244 
2245 			t = btf__type_by_id(btf, m->type);
2246 			if (!t) {
2247 				pr_warn("map '%s': key type [%d] not found.\n",
2248 					map_name, m->type);
2249 				return -EINVAL;
2250 			}
2251 			if (!btf_is_ptr(t)) {
2252 				pr_warn("map '%s': key spec is not PTR: %s.\n",
2253 					map_name, btf_kind_str(t));
2254 				return -EINVAL;
2255 			}
2256 			sz = btf__resolve_size(btf, t->type);
2257 			if (sz < 0) {
2258 				pr_warn("map '%s': can't determine key size for type [%u]: %zd.\n",
2259 					map_name, t->type, (ssize_t)sz);
2260 				return sz;
2261 			}
2262 			if (map_def->key_size && map_def->key_size != sz) {
2263 				pr_warn("map '%s': conflicting key size %u != %zd.\n",
2264 					map_name, map_def->key_size, (ssize_t)sz);
2265 				return -EINVAL;
2266 			}
2267 			map_def->key_size = sz;
2268 			map_def->key_type_id = t->type;
2269 			map_def->parts |= MAP_DEF_KEY_SIZE | MAP_DEF_KEY_TYPE;
2270 		} else if (strcmp(name, "value_size") == 0) {
2271 			__u32 sz;
2272 
2273 			if (!get_map_field_int(map_name, btf, m, &sz))
2274 				return -EINVAL;
2275 			if (map_def->value_size && map_def->value_size != sz) {
2276 				pr_warn("map '%s': conflicting value size %u != %u.\n",
2277 					map_name, map_def->value_size, sz);
2278 				return -EINVAL;
2279 			}
2280 			map_def->value_size = sz;
2281 			map_def->parts |= MAP_DEF_VALUE_SIZE;
2282 		} else if (strcmp(name, "value") == 0) {
2283 			__s64 sz;
2284 
2285 			t = btf__type_by_id(btf, m->type);
2286 			if (!t) {
2287 				pr_warn("map '%s': value type [%d] not found.\n",
2288 					map_name, m->type);
2289 				return -EINVAL;
2290 			}
2291 			if (!btf_is_ptr(t)) {
2292 				pr_warn("map '%s': value spec is not PTR: %s.\n",
2293 					map_name, btf_kind_str(t));
2294 				return -EINVAL;
2295 			}
2296 			sz = btf__resolve_size(btf, t->type);
2297 			if (sz < 0) {
2298 				pr_warn("map '%s': can't determine value size for type [%u]: %zd.\n",
2299 					map_name, t->type, (ssize_t)sz);
2300 				return sz;
2301 			}
2302 			if (map_def->value_size && map_def->value_size != sz) {
2303 				pr_warn("map '%s': conflicting value size %u != %zd.\n",
2304 					map_name, map_def->value_size, (ssize_t)sz);
2305 				return -EINVAL;
2306 			}
2307 			map_def->value_size = sz;
2308 			map_def->value_type_id = t->type;
2309 			map_def->parts |= MAP_DEF_VALUE_SIZE | MAP_DEF_VALUE_TYPE;
2310 		}
2311 		else if (strcmp(name, "values") == 0) {
2312 			bool is_map_in_map = bpf_map_type__is_map_in_map(map_def->map_type);
2313 			bool is_prog_array = map_def->map_type == BPF_MAP_TYPE_PROG_ARRAY;
2314 			const char *desc = is_map_in_map ? "map-in-map inner" : "prog-array value";
2315 			char inner_map_name[128];
2316 			int err;
2317 
2318 			if (is_inner) {
2319 				pr_warn("map '%s': multi-level inner maps not supported.\n",
2320 					map_name);
2321 				return -ENOTSUP;
2322 			}
2323 			if (i != vlen - 1) {
2324 				pr_warn("map '%s': '%s' member should be last.\n",
2325 					map_name, name);
2326 				return -EINVAL;
2327 			}
2328 			if (!is_map_in_map && !is_prog_array) {
2329 				pr_warn("map '%s': should be map-in-map or prog-array.\n",
2330 					map_name);
2331 				return -ENOTSUP;
2332 			}
2333 			if (map_def->value_size && map_def->value_size != 4) {
2334 				pr_warn("map '%s': conflicting value size %u != 4.\n",
2335 					map_name, map_def->value_size);
2336 				return -EINVAL;
2337 			}
2338 			map_def->value_size = 4;
2339 			t = btf__type_by_id(btf, m->type);
2340 			if (!t) {
2341 				pr_warn("map '%s': %s type [%d] not found.\n",
2342 					map_name, desc, m->type);
2343 				return -EINVAL;
2344 			}
2345 			if (!btf_is_array(t) || btf_array(t)->nelems) {
2346 				pr_warn("map '%s': %s spec is not a zero-sized array.\n",
2347 					map_name, desc);
2348 				return -EINVAL;
2349 			}
2350 			t = skip_mods_and_typedefs(btf, btf_array(t)->type, NULL);
2351 			if (!btf_is_ptr(t)) {
2352 				pr_warn("map '%s': %s def is of unexpected kind %s.\n",
2353 					map_name, desc, btf_kind_str(t));
2354 				return -EINVAL;
2355 			}
2356 			t = skip_mods_and_typedefs(btf, t->type, NULL);
2357 			if (is_prog_array) {
2358 				if (!btf_is_func_proto(t)) {
2359 					pr_warn("map '%s': prog-array value def is of unexpected kind %s.\n",
2360 						map_name, btf_kind_str(t));
2361 					return -EINVAL;
2362 				}
2363 				continue;
2364 			}
2365 			if (!btf_is_struct(t)) {
2366 				pr_warn("map '%s': map-in-map inner def is of unexpected kind %s.\n",
2367 					map_name, btf_kind_str(t));
2368 				return -EINVAL;
2369 			}
2370 
2371 			snprintf(inner_map_name, sizeof(inner_map_name), "%s.inner", map_name);
2372 			err = parse_btf_map_def(inner_map_name, btf, t, strict, inner_def, NULL);
2373 			if (err)
2374 				return err;
2375 
2376 			map_def->parts |= MAP_DEF_INNER_MAP;
2377 		} else if (strcmp(name, "pinning") == 0) {
2378 			__u32 val;
2379 
2380 			if (is_inner) {
2381 				pr_warn("map '%s': inner def can't be pinned.\n", map_name);
2382 				return -EINVAL;
2383 			}
2384 			if (!get_map_field_int(map_name, btf, m, &val))
2385 				return -EINVAL;
2386 			if (val != LIBBPF_PIN_NONE && val != LIBBPF_PIN_BY_NAME) {
2387 				pr_warn("map '%s': invalid pinning value %u.\n",
2388 					map_name, val);
2389 				return -EINVAL;
2390 			}
2391 			map_def->pinning = val;
2392 			map_def->parts |= MAP_DEF_PINNING;
2393 		} else if (strcmp(name, "map_extra") == 0) {
2394 			__u32 map_extra;
2395 
2396 			if (!get_map_field_int(map_name, btf, m, &map_extra))
2397 				return -EINVAL;
2398 			map_def->map_extra = map_extra;
2399 			map_def->parts |= MAP_DEF_MAP_EXTRA;
2400 		} else {
2401 			if (strict) {
2402 				pr_warn("map '%s': unknown field '%s'.\n", map_name, name);
2403 				return -ENOTSUP;
2404 			}
2405 			pr_debug("map '%s': ignoring unknown field '%s'.\n", map_name, name);
2406 		}
2407 	}
2408 
2409 	if (map_def->map_type == BPF_MAP_TYPE_UNSPEC) {
2410 		pr_warn("map '%s': map type isn't specified.\n", map_name);
2411 		return -EINVAL;
2412 	}
2413 
2414 	return 0;
2415 }
2416 
2417 static size_t adjust_ringbuf_sz(size_t sz)
2418 {
2419 	__u32 page_sz = sysconf(_SC_PAGE_SIZE);
2420 	__u32 mul;
2421 
2422 	/* if user forgot to set any size, make sure they see error */
2423 	if (sz == 0)
2424 		return 0;
2425 	/* Kernel expects BPF_MAP_TYPE_RINGBUF's max_entries to be
2426 	 * a power-of-2 multiple of kernel's page size. If user diligently
2427 	 * satisified these conditions, pass the size through.
2428 	 */
2429 	if ((sz % page_sz) == 0 && is_pow_of_2(sz / page_sz))
2430 		return sz;
2431 
2432 	/* Otherwise find closest (page_sz * power_of_2) product bigger than
2433 	 * user-set size to satisfy both user size request and kernel
2434 	 * requirements and substitute correct max_entries for map creation.
2435 	 */
2436 	for (mul = 1; mul <= UINT_MAX / page_sz; mul <<= 1) {
2437 		if (mul * page_sz > sz)
2438 			return mul * page_sz;
2439 	}
2440 
2441 	/* if it's impossible to satisfy the conditions (i.e., user size is
2442 	 * very close to UINT_MAX but is not a power-of-2 multiple of
2443 	 * page_size) then just return original size and let kernel reject it
2444 	 */
2445 	return sz;
2446 }
2447 
2448 static bool map_is_ringbuf(const struct bpf_map *map)
2449 {
2450 	return map->def.type == BPF_MAP_TYPE_RINGBUF ||
2451 	       map->def.type == BPF_MAP_TYPE_USER_RINGBUF;
2452 }
2453 
2454 static void fill_map_from_def(struct bpf_map *map, const struct btf_map_def *def)
2455 {
2456 	map->def.type = def->map_type;
2457 	map->def.key_size = def->key_size;
2458 	map->def.value_size = def->value_size;
2459 	map->def.max_entries = def->max_entries;
2460 	map->def.map_flags = def->map_flags;
2461 	map->map_extra = def->map_extra;
2462 
2463 	map->numa_node = def->numa_node;
2464 	map->btf_key_type_id = def->key_type_id;
2465 	map->btf_value_type_id = def->value_type_id;
2466 
2467 	/* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
2468 	if (map_is_ringbuf(map))
2469 		map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
2470 
2471 	if (def->parts & MAP_DEF_MAP_TYPE)
2472 		pr_debug("map '%s': found type = %u.\n", map->name, def->map_type);
2473 
2474 	if (def->parts & MAP_DEF_KEY_TYPE)
2475 		pr_debug("map '%s': found key [%u], sz = %u.\n",
2476 			 map->name, def->key_type_id, def->key_size);
2477 	else if (def->parts & MAP_DEF_KEY_SIZE)
2478 		pr_debug("map '%s': found key_size = %u.\n", map->name, def->key_size);
2479 
2480 	if (def->parts & MAP_DEF_VALUE_TYPE)
2481 		pr_debug("map '%s': found value [%u], sz = %u.\n",
2482 			 map->name, def->value_type_id, def->value_size);
2483 	else if (def->parts & MAP_DEF_VALUE_SIZE)
2484 		pr_debug("map '%s': found value_size = %u.\n", map->name, def->value_size);
2485 
2486 	if (def->parts & MAP_DEF_MAX_ENTRIES)
2487 		pr_debug("map '%s': found max_entries = %u.\n", map->name, def->max_entries);
2488 	if (def->parts & MAP_DEF_MAP_FLAGS)
2489 		pr_debug("map '%s': found map_flags = 0x%x.\n", map->name, def->map_flags);
2490 	if (def->parts & MAP_DEF_MAP_EXTRA)
2491 		pr_debug("map '%s': found map_extra = 0x%llx.\n", map->name,
2492 			 (unsigned long long)def->map_extra);
2493 	if (def->parts & MAP_DEF_PINNING)
2494 		pr_debug("map '%s': found pinning = %u.\n", map->name, def->pinning);
2495 	if (def->parts & MAP_DEF_NUMA_NODE)
2496 		pr_debug("map '%s': found numa_node = %u.\n", map->name, def->numa_node);
2497 
2498 	if (def->parts & MAP_DEF_INNER_MAP)
2499 		pr_debug("map '%s': found inner map definition.\n", map->name);
2500 }
2501 
2502 static const char *btf_var_linkage_str(__u32 linkage)
2503 {
2504 	switch (linkage) {
2505 	case BTF_VAR_STATIC: return "static";
2506 	case BTF_VAR_GLOBAL_ALLOCATED: return "global";
2507 	case BTF_VAR_GLOBAL_EXTERN: return "extern";
2508 	default: return "unknown";
2509 	}
2510 }
2511 
2512 static int bpf_object__init_user_btf_map(struct bpf_object *obj,
2513 					 const struct btf_type *sec,
2514 					 int var_idx, int sec_idx,
2515 					 const Elf_Data *data, bool strict,
2516 					 const char *pin_root_path)
2517 {
2518 	struct btf_map_def map_def = {}, inner_def = {};
2519 	const struct btf_type *var, *def;
2520 	const struct btf_var_secinfo *vi;
2521 	const struct btf_var *var_extra;
2522 	const char *map_name;
2523 	struct bpf_map *map;
2524 	int err;
2525 
2526 	vi = btf_var_secinfos(sec) + var_idx;
2527 	var = btf__type_by_id(obj->btf, vi->type);
2528 	var_extra = btf_var(var);
2529 	map_name = btf__name_by_offset(obj->btf, var->name_off);
2530 
2531 	if (map_name == NULL || map_name[0] == '\0') {
2532 		pr_warn("map #%d: empty name.\n", var_idx);
2533 		return -EINVAL;
2534 	}
2535 	if ((__u64)vi->offset + vi->size > data->d_size) {
2536 		pr_warn("map '%s' BTF data is corrupted.\n", map_name);
2537 		return -EINVAL;
2538 	}
2539 	if (!btf_is_var(var)) {
2540 		pr_warn("map '%s': unexpected var kind %s.\n",
2541 			map_name, btf_kind_str(var));
2542 		return -EINVAL;
2543 	}
2544 	if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED) {
2545 		pr_warn("map '%s': unsupported map linkage %s.\n",
2546 			map_name, btf_var_linkage_str(var_extra->linkage));
2547 		return -EOPNOTSUPP;
2548 	}
2549 
2550 	def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
2551 	if (!btf_is_struct(def)) {
2552 		pr_warn("map '%s': unexpected def kind %s.\n",
2553 			map_name, btf_kind_str(var));
2554 		return -EINVAL;
2555 	}
2556 	if (def->size > vi->size) {
2557 		pr_warn("map '%s': invalid def size.\n", map_name);
2558 		return -EINVAL;
2559 	}
2560 
2561 	map = bpf_object__add_map(obj);
2562 	if (IS_ERR(map))
2563 		return PTR_ERR(map);
2564 	map->name = strdup(map_name);
2565 	if (!map->name) {
2566 		pr_warn("map '%s': failed to alloc map name.\n", map_name);
2567 		return -ENOMEM;
2568 	}
2569 	map->libbpf_type = LIBBPF_MAP_UNSPEC;
2570 	map->def.type = BPF_MAP_TYPE_UNSPEC;
2571 	map->sec_idx = sec_idx;
2572 	map->sec_offset = vi->offset;
2573 	map->btf_var_idx = var_idx;
2574 	pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
2575 		 map_name, map->sec_idx, map->sec_offset);
2576 
2577 	err = parse_btf_map_def(map->name, obj->btf, def, strict, &map_def, &inner_def);
2578 	if (err)
2579 		return err;
2580 
2581 	fill_map_from_def(map, &map_def);
2582 
2583 	if (map_def.pinning == LIBBPF_PIN_BY_NAME) {
2584 		err = build_map_pin_path(map, pin_root_path);
2585 		if (err) {
2586 			pr_warn("map '%s': couldn't build pin path.\n", map->name);
2587 			return err;
2588 		}
2589 	}
2590 
2591 	if (map_def.parts & MAP_DEF_INNER_MAP) {
2592 		map->inner_map = calloc(1, sizeof(*map->inner_map));
2593 		if (!map->inner_map)
2594 			return -ENOMEM;
2595 		map->inner_map->fd = -1;
2596 		map->inner_map->sec_idx = sec_idx;
2597 		map->inner_map->name = malloc(strlen(map_name) + sizeof(".inner") + 1);
2598 		if (!map->inner_map->name)
2599 			return -ENOMEM;
2600 		sprintf(map->inner_map->name, "%s.inner", map_name);
2601 
2602 		fill_map_from_def(map->inner_map, &inner_def);
2603 	}
2604 
2605 	err = map_fill_btf_type_info(obj, map);
2606 	if (err)
2607 		return err;
2608 
2609 	return 0;
2610 }
2611 
2612 static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict,
2613 					  const char *pin_root_path)
2614 {
2615 	const struct btf_type *sec = NULL;
2616 	int nr_types, i, vlen, err;
2617 	const struct btf_type *t;
2618 	const char *name;
2619 	Elf_Data *data;
2620 	Elf_Scn *scn;
2621 
2622 	if (obj->efile.btf_maps_shndx < 0)
2623 		return 0;
2624 
2625 	scn = elf_sec_by_idx(obj, obj->efile.btf_maps_shndx);
2626 	data = elf_sec_data(obj, scn);
2627 	if (!scn || !data) {
2628 		pr_warn("elf: failed to get %s map definitions for %s\n",
2629 			MAPS_ELF_SEC, obj->path);
2630 		return -EINVAL;
2631 	}
2632 
2633 	nr_types = btf__type_cnt(obj->btf);
2634 	for (i = 1; i < nr_types; i++) {
2635 		t = btf__type_by_id(obj->btf, i);
2636 		if (!btf_is_datasec(t))
2637 			continue;
2638 		name = btf__name_by_offset(obj->btf, t->name_off);
2639 		if (strcmp(name, MAPS_ELF_SEC) == 0) {
2640 			sec = t;
2641 			obj->efile.btf_maps_sec_btf_id = i;
2642 			break;
2643 		}
2644 	}
2645 
2646 	if (!sec) {
2647 		pr_warn("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
2648 		return -ENOENT;
2649 	}
2650 
2651 	vlen = btf_vlen(sec);
2652 	for (i = 0; i < vlen; i++) {
2653 		err = bpf_object__init_user_btf_map(obj, sec, i,
2654 						    obj->efile.btf_maps_shndx,
2655 						    data, strict,
2656 						    pin_root_path);
2657 		if (err)
2658 			return err;
2659 	}
2660 
2661 	return 0;
2662 }
2663 
2664 static int bpf_object__init_maps(struct bpf_object *obj,
2665 				 const struct bpf_object_open_opts *opts)
2666 {
2667 	const char *pin_root_path;
2668 	bool strict;
2669 	int err = 0;
2670 
2671 	strict = !OPTS_GET(opts, relaxed_maps, false);
2672 	pin_root_path = OPTS_GET(opts, pin_root_path, NULL);
2673 
2674 	err = bpf_object__init_user_btf_maps(obj, strict, pin_root_path);
2675 	err = err ?: bpf_object__init_global_data_maps(obj);
2676 	err = err ?: bpf_object__init_kconfig_map(obj);
2677 	err = err ?: bpf_object_init_struct_ops(obj);
2678 
2679 	return err;
2680 }
2681 
2682 static bool section_have_execinstr(struct bpf_object *obj, int idx)
2683 {
2684 	Elf64_Shdr *sh;
2685 
2686 	sh = elf_sec_hdr(obj, elf_sec_by_idx(obj, idx));
2687 	if (!sh)
2688 		return false;
2689 
2690 	return sh->sh_flags & SHF_EXECINSTR;
2691 }
2692 
2693 static bool btf_needs_sanitization(struct bpf_object *obj)
2694 {
2695 	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
2696 	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
2697 	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
2698 	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
2699 	bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
2700 	bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
2701 	bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
2702 
2703 	return !has_func || !has_datasec || !has_func_global || !has_float ||
2704 	       !has_decl_tag || !has_type_tag || !has_enum64;
2705 }
2706 
2707 static int bpf_object__sanitize_btf(struct bpf_object *obj, struct btf *btf)
2708 {
2709 	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
2710 	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
2711 	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
2712 	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
2713 	bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
2714 	bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
2715 	bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
2716 	int enum64_placeholder_id = 0;
2717 	struct btf_type *t;
2718 	int i, j, vlen;
2719 
2720 	for (i = 1; i < btf__type_cnt(btf); i++) {
2721 		t = (struct btf_type *)btf__type_by_id(btf, i);
2722 
2723 		if ((!has_datasec && btf_is_var(t)) || (!has_decl_tag && btf_is_decl_tag(t))) {
2724 			/* replace VAR/DECL_TAG with INT */
2725 			t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
2726 			/*
2727 			 * using size = 1 is the safest choice, 4 will be too
2728 			 * big and cause kernel BTF validation failure if
2729 			 * original variable took less than 4 bytes
2730 			 */
2731 			t->size = 1;
2732 			*(int *)(t + 1) = BTF_INT_ENC(0, 0, 8);
2733 		} else if (!has_datasec && btf_is_datasec(t)) {
2734 			/* replace DATASEC with STRUCT */
2735 			const struct btf_var_secinfo *v = btf_var_secinfos(t);
2736 			struct btf_member *m = btf_members(t);
2737 			struct btf_type *vt;
2738 			char *name;
2739 
2740 			name = (char *)btf__name_by_offset(btf, t->name_off);
2741 			while (*name) {
2742 				if (*name == '.')
2743 					*name = '_';
2744 				name++;
2745 			}
2746 
2747 			vlen = btf_vlen(t);
2748 			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
2749 			for (j = 0; j < vlen; j++, v++, m++) {
2750 				/* order of field assignments is important */
2751 				m->offset = v->offset * 8;
2752 				m->type = v->type;
2753 				/* preserve variable name as member name */
2754 				vt = (void *)btf__type_by_id(btf, v->type);
2755 				m->name_off = vt->name_off;
2756 			}
2757 		} else if (!has_func && btf_is_func_proto(t)) {
2758 			/* replace FUNC_PROTO with ENUM */
2759 			vlen = btf_vlen(t);
2760 			t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
2761 			t->size = sizeof(__u32); /* kernel enforced */
2762 		} else if (!has_func && btf_is_func(t)) {
2763 			/* replace FUNC with TYPEDEF */
2764 			t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
2765 		} else if (!has_func_global && btf_is_func(t)) {
2766 			/* replace BTF_FUNC_GLOBAL with BTF_FUNC_STATIC */
2767 			t->info = BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0);
2768 		} else if (!has_float && btf_is_float(t)) {
2769 			/* replace FLOAT with an equally-sized empty STRUCT;
2770 			 * since C compilers do not accept e.g. "float" as a
2771 			 * valid struct name, make it anonymous
2772 			 */
2773 			t->name_off = 0;
2774 			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, 0);
2775 		} else if (!has_type_tag && btf_is_type_tag(t)) {
2776 			/* replace TYPE_TAG with a CONST */
2777 			t->name_off = 0;
2778 			t->info = BTF_INFO_ENC(BTF_KIND_CONST, 0, 0);
2779 		} else if (!has_enum64 && btf_is_enum(t)) {
2780 			/* clear the kflag */
2781 			t->info = btf_type_info(btf_kind(t), btf_vlen(t), false);
2782 		} else if (!has_enum64 && btf_is_enum64(t)) {
2783 			/* replace ENUM64 with a union */
2784 			struct btf_member *m;
2785 
2786 			if (enum64_placeholder_id == 0) {
2787 				enum64_placeholder_id = btf__add_int(btf, "enum64_placeholder", 1, 0);
2788 				if (enum64_placeholder_id < 0)
2789 					return enum64_placeholder_id;
2790 
2791 				t = (struct btf_type *)btf__type_by_id(btf, i);
2792 			}
2793 
2794 			m = btf_members(t);
2795 			vlen = btf_vlen(t);
2796 			t->info = BTF_INFO_ENC(BTF_KIND_UNION, 0, vlen);
2797 			for (j = 0; j < vlen; j++, m++) {
2798 				m->type = enum64_placeholder_id;
2799 				m->offset = 0;
2800 			}
2801 		}
2802 	}
2803 
2804 	return 0;
2805 }
2806 
2807 static bool libbpf_needs_btf(const struct bpf_object *obj)
2808 {
2809 	return obj->efile.btf_maps_shndx >= 0 ||
2810 	       obj->efile.st_ops_shndx >= 0 ||
2811 	       obj->efile.st_ops_link_shndx >= 0 ||
2812 	       obj->nr_extern > 0;
2813 }
2814 
2815 static bool kernel_needs_btf(const struct bpf_object *obj)
2816 {
2817 	return obj->efile.st_ops_shndx >= 0 || obj->efile.st_ops_link_shndx >= 0;
2818 }
2819 
2820 static int bpf_object__init_btf(struct bpf_object *obj,
2821 				Elf_Data *btf_data,
2822 				Elf_Data *btf_ext_data)
2823 {
2824 	int err = -ENOENT;
2825 
2826 	if (btf_data) {
2827 		obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
2828 		err = libbpf_get_error(obj->btf);
2829 		if (err) {
2830 			obj->btf = NULL;
2831 			pr_warn("Error loading ELF section %s: %d.\n", BTF_ELF_SEC, err);
2832 			goto out;
2833 		}
2834 		/* enforce 8-byte pointers for BPF-targeted BTFs */
2835 		btf__set_pointer_size(obj->btf, 8);
2836 	}
2837 	if (btf_ext_data) {
2838 		struct btf_ext_info *ext_segs[3];
2839 		int seg_num, sec_num;
2840 
2841 		if (!obj->btf) {
2842 			pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
2843 				 BTF_EXT_ELF_SEC, BTF_ELF_SEC);
2844 			goto out;
2845 		}
2846 		obj->btf_ext = btf_ext__new(btf_ext_data->d_buf, btf_ext_data->d_size);
2847 		err = libbpf_get_error(obj->btf_ext);
2848 		if (err) {
2849 			pr_warn("Error loading ELF section %s: %d. Ignored and continue.\n",
2850 				BTF_EXT_ELF_SEC, err);
2851 			obj->btf_ext = NULL;
2852 			goto out;
2853 		}
2854 
2855 		/* setup .BTF.ext to ELF section mapping */
2856 		ext_segs[0] = &obj->btf_ext->func_info;
2857 		ext_segs[1] = &obj->btf_ext->line_info;
2858 		ext_segs[2] = &obj->btf_ext->core_relo_info;
2859 		for (seg_num = 0; seg_num < ARRAY_SIZE(ext_segs); seg_num++) {
2860 			struct btf_ext_info *seg = ext_segs[seg_num];
2861 			const struct btf_ext_info_sec *sec;
2862 			const char *sec_name;
2863 			Elf_Scn *scn;
2864 
2865 			if (seg->sec_cnt == 0)
2866 				continue;
2867 
2868 			seg->sec_idxs = calloc(seg->sec_cnt, sizeof(*seg->sec_idxs));
2869 			if (!seg->sec_idxs) {
2870 				err = -ENOMEM;
2871 				goto out;
2872 			}
2873 
2874 			sec_num = 0;
2875 			for_each_btf_ext_sec(seg, sec) {
2876 				/* preventively increment index to avoid doing
2877 				 * this before every continue below
2878 				 */
2879 				sec_num++;
2880 
2881 				sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
2882 				if (str_is_empty(sec_name))
2883 					continue;
2884 				scn = elf_sec_by_name(obj, sec_name);
2885 				if (!scn)
2886 					continue;
2887 
2888 				seg->sec_idxs[sec_num - 1] = elf_ndxscn(scn);
2889 			}
2890 		}
2891 	}
2892 out:
2893 	if (err && libbpf_needs_btf(obj)) {
2894 		pr_warn("BTF is required, but is missing or corrupted.\n");
2895 		return err;
2896 	}
2897 	return 0;
2898 }
2899 
2900 static int compare_vsi_off(const void *_a, const void *_b)
2901 {
2902 	const struct btf_var_secinfo *a = _a;
2903 	const struct btf_var_secinfo *b = _b;
2904 
2905 	return a->offset - b->offset;
2906 }
2907 
2908 static int btf_fixup_datasec(struct bpf_object *obj, struct btf *btf,
2909 			     struct btf_type *t)
2910 {
2911 	__u32 size = 0, i, vars = btf_vlen(t);
2912 	const char *sec_name = btf__name_by_offset(btf, t->name_off);
2913 	struct btf_var_secinfo *vsi;
2914 	bool fixup_offsets = false;
2915 	int err;
2916 
2917 	if (!sec_name) {
2918 		pr_debug("No name found in string section for DATASEC kind.\n");
2919 		return -ENOENT;
2920 	}
2921 
2922 	/* Extern-backing datasecs (.ksyms, .kconfig) have their size and
2923 	 * variable offsets set at the previous step. Further, not every
2924 	 * extern BTF VAR has corresponding ELF symbol preserved, so we skip
2925 	 * all fixups altogether for such sections and go straight to sorting
2926 	 * VARs within their DATASEC.
2927 	 */
2928 	if (strcmp(sec_name, KCONFIG_SEC) == 0 || strcmp(sec_name, KSYMS_SEC) == 0)
2929 		goto sort_vars;
2930 
2931 	/* Clang leaves DATASEC size and VAR offsets as zeroes, so we need to
2932 	 * fix this up. But BPF static linker already fixes this up and fills
2933 	 * all the sizes and offsets during static linking. So this step has
2934 	 * to be optional. But the STV_HIDDEN handling is non-optional for any
2935 	 * non-extern DATASEC, so the variable fixup loop below handles both
2936 	 * functions at the same time, paying the cost of BTF VAR <-> ELF
2937 	 * symbol matching just once.
2938 	 */
2939 	if (t->size == 0) {
2940 		err = find_elf_sec_sz(obj, sec_name, &size);
2941 		if (err || !size) {
2942 			pr_debug("sec '%s': failed to determine size from ELF: size %u, err %d\n",
2943 				 sec_name, size, err);
2944 			return -ENOENT;
2945 		}
2946 
2947 		t->size = size;
2948 		fixup_offsets = true;
2949 	}
2950 
2951 	for (i = 0, vsi = btf_var_secinfos(t); i < vars; i++, vsi++) {
2952 		const struct btf_type *t_var;
2953 		struct btf_var *var;
2954 		const char *var_name;
2955 		Elf64_Sym *sym;
2956 
2957 		t_var = btf__type_by_id(btf, vsi->type);
2958 		if (!t_var || !btf_is_var(t_var)) {
2959 			pr_debug("sec '%s': unexpected non-VAR type found\n", sec_name);
2960 			return -EINVAL;
2961 		}
2962 
2963 		var = btf_var(t_var);
2964 		if (var->linkage == BTF_VAR_STATIC || var->linkage == BTF_VAR_GLOBAL_EXTERN)
2965 			continue;
2966 
2967 		var_name = btf__name_by_offset(btf, t_var->name_off);
2968 		if (!var_name) {
2969 			pr_debug("sec '%s': failed to find name of DATASEC's member #%d\n",
2970 				 sec_name, i);
2971 			return -ENOENT;
2972 		}
2973 
2974 		sym = find_elf_var_sym(obj, var_name);
2975 		if (IS_ERR(sym)) {
2976 			pr_debug("sec '%s': failed to find ELF symbol for VAR '%s'\n",
2977 				 sec_name, var_name);
2978 			return -ENOENT;
2979 		}
2980 
2981 		if (fixup_offsets)
2982 			vsi->offset = sym->st_value;
2983 
2984 		/* if variable is a global/weak symbol, but has restricted
2985 		 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF VAR
2986 		 * as static. This follows similar logic for functions (BPF
2987 		 * subprogs) and influences libbpf's further decisions about
2988 		 * whether to make global data BPF array maps as
2989 		 * BPF_F_MMAPABLE.
2990 		 */
2991 		if (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
2992 		    || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL)
2993 			var->linkage = BTF_VAR_STATIC;
2994 	}
2995 
2996 sort_vars:
2997 	qsort(btf_var_secinfos(t), vars, sizeof(*vsi), compare_vsi_off);
2998 	return 0;
2999 }
3000 
3001 static int bpf_object_fixup_btf(struct bpf_object *obj)
3002 {
3003 	int i, n, err = 0;
3004 
3005 	if (!obj->btf)
3006 		return 0;
3007 
3008 	n = btf__type_cnt(obj->btf);
3009 	for (i = 1; i < n; i++) {
3010 		struct btf_type *t = btf_type_by_id(obj->btf, i);
3011 
3012 		/* Loader needs to fix up some of the things compiler
3013 		 * couldn't get its hands on while emitting BTF. This
3014 		 * is section size and global variable offset. We use
3015 		 * the info from the ELF itself for this purpose.
3016 		 */
3017 		if (btf_is_datasec(t)) {
3018 			err = btf_fixup_datasec(obj, obj->btf, t);
3019 			if (err)
3020 				return err;
3021 		}
3022 	}
3023 
3024 	return 0;
3025 }
3026 
3027 static bool prog_needs_vmlinux_btf(struct bpf_program *prog)
3028 {
3029 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
3030 	    prog->type == BPF_PROG_TYPE_LSM)
3031 		return true;
3032 
3033 	/* BPF_PROG_TYPE_TRACING programs which do not attach to other programs
3034 	 * also need vmlinux BTF
3035 	 */
3036 	if (prog->type == BPF_PROG_TYPE_TRACING && !prog->attach_prog_fd)
3037 		return true;
3038 
3039 	return false;
3040 }
3041 
3042 static bool obj_needs_vmlinux_btf(const struct bpf_object *obj)
3043 {
3044 	struct bpf_program *prog;
3045 	int i;
3046 
3047 	/* CO-RE relocations need kernel BTF, only when btf_custom_path
3048 	 * is not specified
3049 	 */
3050 	if (obj->btf_ext && obj->btf_ext->core_relo_info.len && !obj->btf_custom_path)
3051 		return true;
3052 
3053 	/* Support for typed ksyms needs kernel BTF */
3054 	for (i = 0; i < obj->nr_extern; i++) {
3055 		const struct extern_desc *ext;
3056 
3057 		ext = &obj->externs[i];
3058 		if (ext->type == EXT_KSYM && ext->ksym.type_id)
3059 			return true;
3060 	}
3061 
3062 	bpf_object__for_each_program(prog, obj) {
3063 		if (!prog->autoload)
3064 			continue;
3065 		if (prog_needs_vmlinux_btf(prog))
3066 			return true;
3067 	}
3068 
3069 	return false;
3070 }
3071 
3072 static int bpf_object__load_vmlinux_btf(struct bpf_object *obj, bool force)
3073 {
3074 	int err;
3075 
3076 	/* btf_vmlinux could be loaded earlier */
3077 	if (obj->btf_vmlinux || obj->gen_loader)
3078 		return 0;
3079 
3080 	if (!force && !obj_needs_vmlinux_btf(obj))
3081 		return 0;
3082 
3083 	obj->btf_vmlinux = btf__load_vmlinux_btf();
3084 	err = libbpf_get_error(obj->btf_vmlinux);
3085 	if (err) {
3086 		pr_warn("Error loading vmlinux BTF: %d\n", err);
3087 		obj->btf_vmlinux = NULL;
3088 		return err;
3089 	}
3090 	return 0;
3091 }
3092 
3093 static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
3094 {
3095 	struct btf *kern_btf = obj->btf;
3096 	bool btf_mandatory, sanitize;
3097 	int i, err = 0;
3098 
3099 	if (!obj->btf)
3100 		return 0;
3101 
3102 	if (!kernel_supports(obj, FEAT_BTF)) {
3103 		if (kernel_needs_btf(obj)) {
3104 			err = -EOPNOTSUPP;
3105 			goto report;
3106 		}
3107 		pr_debug("Kernel doesn't support BTF, skipping uploading it.\n");
3108 		return 0;
3109 	}
3110 
3111 	/* Even though some subprogs are global/weak, user might prefer more
3112 	 * permissive BPF verification process that BPF verifier performs for
3113 	 * static functions, taking into account more context from the caller
3114 	 * functions. In such case, they need to mark such subprogs with
3115 	 * __attribute__((visibility("hidden"))) and libbpf will adjust
3116 	 * corresponding FUNC BTF type to be marked as static and trigger more
3117 	 * involved BPF verification process.
3118 	 */
3119 	for (i = 0; i < obj->nr_programs; i++) {
3120 		struct bpf_program *prog = &obj->programs[i];
3121 		struct btf_type *t;
3122 		const char *name;
3123 		int j, n;
3124 
3125 		if (!prog->mark_btf_static || !prog_is_subprog(obj, prog))
3126 			continue;
3127 
3128 		n = btf__type_cnt(obj->btf);
3129 		for (j = 1; j < n; j++) {
3130 			t = btf_type_by_id(obj->btf, j);
3131 			if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL)
3132 				continue;
3133 
3134 			name = btf__str_by_offset(obj->btf, t->name_off);
3135 			if (strcmp(name, prog->name) != 0)
3136 				continue;
3137 
3138 			t->info = btf_type_info(BTF_KIND_FUNC, BTF_FUNC_STATIC, 0);
3139 			break;
3140 		}
3141 	}
3142 
3143 	sanitize = btf_needs_sanitization(obj);
3144 	if (sanitize) {
3145 		const void *raw_data;
3146 		__u32 sz;
3147 
3148 		/* clone BTF to sanitize a copy and leave the original intact */
3149 		raw_data = btf__raw_data(obj->btf, &sz);
3150 		kern_btf = btf__new(raw_data, sz);
3151 		err = libbpf_get_error(kern_btf);
3152 		if (err)
3153 			return err;
3154 
3155 		/* enforce 8-byte pointers for BPF-targeted BTFs */
3156 		btf__set_pointer_size(obj->btf, 8);
3157 		err = bpf_object__sanitize_btf(obj, kern_btf);
3158 		if (err)
3159 			return err;
3160 	}
3161 
3162 	if (obj->gen_loader) {
3163 		__u32 raw_size = 0;
3164 		const void *raw_data = btf__raw_data(kern_btf, &raw_size);
3165 
3166 		if (!raw_data)
3167 			return -ENOMEM;
3168 		bpf_gen__load_btf(obj->gen_loader, raw_data, raw_size);
3169 		/* Pretend to have valid FD to pass various fd >= 0 checks.
3170 		 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
3171 		 */
3172 		btf__set_fd(kern_btf, 0);
3173 	} else {
3174 		/* currently BPF_BTF_LOAD only supports log_level 1 */
3175 		err = btf_load_into_kernel(kern_btf, obj->log_buf, obj->log_size,
3176 					   obj->log_level ? 1 : 0);
3177 	}
3178 	if (sanitize) {
3179 		if (!err) {
3180 			/* move fd to libbpf's BTF */
3181 			btf__set_fd(obj->btf, btf__fd(kern_btf));
3182 			btf__set_fd(kern_btf, -1);
3183 		}
3184 		btf__free(kern_btf);
3185 	}
3186 report:
3187 	if (err) {
3188 		btf_mandatory = kernel_needs_btf(obj);
3189 		pr_warn("Error loading .BTF into kernel: %d. %s\n", err,
3190 			btf_mandatory ? "BTF is mandatory, can't proceed."
3191 				      : "BTF is optional, ignoring.");
3192 		if (!btf_mandatory)
3193 			err = 0;
3194 	}
3195 	return err;
3196 }
3197 
3198 static const char *elf_sym_str(const struct bpf_object *obj, size_t off)
3199 {
3200 	const char *name;
3201 
3202 	name = elf_strptr(obj->efile.elf, obj->efile.strtabidx, off);
3203 	if (!name) {
3204 		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3205 			off, obj->path, elf_errmsg(-1));
3206 		return NULL;
3207 	}
3208 
3209 	return name;
3210 }
3211 
3212 static const char *elf_sec_str(const struct bpf_object *obj, size_t off)
3213 {
3214 	const char *name;
3215 
3216 	name = elf_strptr(obj->efile.elf, obj->efile.shstrndx, off);
3217 	if (!name) {
3218 		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3219 			off, obj->path, elf_errmsg(-1));
3220 		return NULL;
3221 	}
3222 
3223 	return name;
3224 }
3225 
3226 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx)
3227 {
3228 	Elf_Scn *scn;
3229 
3230 	scn = elf_getscn(obj->efile.elf, idx);
3231 	if (!scn) {
3232 		pr_warn("elf: failed to get section(%zu) from %s: %s\n",
3233 			idx, obj->path, elf_errmsg(-1));
3234 		return NULL;
3235 	}
3236 	return scn;
3237 }
3238 
3239 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name)
3240 {
3241 	Elf_Scn *scn = NULL;
3242 	Elf *elf = obj->efile.elf;
3243 	const char *sec_name;
3244 
3245 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3246 		sec_name = elf_sec_name(obj, scn);
3247 		if (!sec_name)
3248 			return NULL;
3249 
3250 		if (strcmp(sec_name, name) != 0)
3251 			continue;
3252 
3253 		return scn;
3254 	}
3255 	return NULL;
3256 }
3257 
3258 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn)
3259 {
3260 	Elf64_Shdr *shdr;
3261 
3262 	if (!scn)
3263 		return NULL;
3264 
3265 	shdr = elf64_getshdr(scn);
3266 	if (!shdr) {
3267 		pr_warn("elf: failed to get section(%zu) header from %s: %s\n",
3268 			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3269 		return NULL;
3270 	}
3271 
3272 	return shdr;
3273 }
3274 
3275 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn)
3276 {
3277 	const char *name;
3278 	Elf64_Shdr *sh;
3279 
3280 	if (!scn)
3281 		return NULL;
3282 
3283 	sh = elf_sec_hdr(obj, scn);
3284 	if (!sh)
3285 		return NULL;
3286 
3287 	name = elf_sec_str(obj, sh->sh_name);
3288 	if (!name) {
3289 		pr_warn("elf: failed to get section(%zu) name from %s: %s\n",
3290 			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3291 		return NULL;
3292 	}
3293 
3294 	return name;
3295 }
3296 
3297 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn)
3298 {
3299 	Elf_Data *data;
3300 
3301 	if (!scn)
3302 		return NULL;
3303 
3304 	data = elf_getdata(scn, 0);
3305 	if (!data) {
3306 		pr_warn("elf: failed to get section(%zu) %s data from %s: %s\n",
3307 			elf_ndxscn(scn), elf_sec_name(obj, scn) ?: "<?>",
3308 			obj->path, elf_errmsg(-1));
3309 		return NULL;
3310 	}
3311 
3312 	return data;
3313 }
3314 
3315 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx)
3316 {
3317 	if (idx >= obj->efile.symbols->d_size / sizeof(Elf64_Sym))
3318 		return NULL;
3319 
3320 	return (Elf64_Sym *)obj->efile.symbols->d_buf + idx;
3321 }
3322 
3323 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx)
3324 {
3325 	if (idx >= data->d_size / sizeof(Elf64_Rel))
3326 		return NULL;
3327 
3328 	return (Elf64_Rel *)data->d_buf + idx;
3329 }
3330 
3331 static bool is_sec_name_dwarf(const char *name)
3332 {
3333 	/* approximation, but the actual list is too long */
3334 	return str_has_pfx(name, ".debug_");
3335 }
3336 
3337 static bool ignore_elf_section(Elf64_Shdr *hdr, const char *name)
3338 {
3339 	/* no special handling of .strtab */
3340 	if (hdr->sh_type == SHT_STRTAB)
3341 		return true;
3342 
3343 	/* ignore .llvm_addrsig section as well */
3344 	if (hdr->sh_type == SHT_LLVM_ADDRSIG)
3345 		return true;
3346 
3347 	/* no subprograms will lead to an empty .text section, ignore it */
3348 	if (hdr->sh_type == SHT_PROGBITS && hdr->sh_size == 0 &&
3349 	    strcmp(name, ".text") == 0)
3350 		return true;
3351 
3352 	/* DWARF sections */
3353 	if (is_sec_name_dwarf(name))
3354 		return true;
3355 
3356 	if (str_has_pfx(name, ".rel")) {
3357 		name += sizeof(".rel") - 1;
3358 		/* DWARF section relocations */
3359 		if (is_sec_name_dwarf(name))
3360 			return true;
3361 
3362 		/* .BTF and .BTF.ext don't need relocations */
3363 		if (strcmp(name, BTF_ELF_SEC) == 0 ||
3364 		    strcmp(name, BTF_EXT_ELF_SEC) == 0)
3365 			return true;
3366 	}
3367 
3368 	return false;
3369 }
3370 
3371 static int cmp_progs(const void *_a, const void *_b)
3372 {
3373 	const struct bpf_program *a = _a;
3374 	const struct bpf_program *b = _b;
3375 
3376 	if (a->sec_idx != b->sec_idx)
3377 		return a->sec_idx < b->sec_idx ? -1 : 1;
3378 
3379 	/* sec_insn_off can't be the same within the section */
3380 	return a->sec_insn_off < b->sec_insn_off ? -1 : 1;
3381 }
3382 
3383 static int bpf_object__elf_collect(struct bpf_object *obj)
3384 {
3385 	struct elf_sec_desc *sec_desc;
3386 	Elf *elf = obj->efile.elf;
3387 	Elf_Data *btf_ext_data = NULL;
3388 	Elf_Data *btf_data = NULL;
3389 	int idx = 0, err = 0;
3390 	const char *name;
3391 	Elf_Data *data;
3392 	Elf_Scn *scn;
3393 	Elf64_Shdr *sh;
3394 
3395 	/* ELF section indices are 0-based, but sec #0 is special "invalid"
3396 	 * section. Since section count retrieved by elf_getshdrnum() does
3397 	 * include sec #0, it is already the necessary size of an array to keep
3398 	 * all the sections.
3399 	 */
3400 	if (elf_getshdrnum(obj->efile.elf, &obj->efile.sec_cnt)) {
3401 		pr_warn("elf: failed to get the number of sections for %s: %s\n",
3402 			obj->path, elf_errmsg(-1));
3403 		return -LIBBPF_ERRNO__FORMAT;
3404 	}
3405 	obj->efile.secs = calloc(obj->efile.sec_cnt, sizeof(*obj->efile.secs));
3406 	if (!obj->efile.secs)
3407 		return -ENOMEM;
3408 
3409 	/* a bunch of ELF parsing functionality depends on processing symbols,
3410 	 * so do the first pass and find the symbol table
3411 	 */
3412 	scn = NULL;
3413 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3414 		sh = elf_sec_hdr(obj, scn);
3415 		if (!sh)
3416 			return -LIBBPF_ERRNO__FORMAT;
3417 
3418 		if (sh->sh_type == SHT_SYMTAB) {
3419 			if (obj->efile.symbols) {
3420 				pr_warn("elf: multiple symbol tables in %s\n", obj->path);
3421 				return -LIBBPF_ERRNO__FORMAT;
3422 			}
3423 
3424 			data = elf_sec_data(obj, scn);
3425 			if (!data)
3426 				return -LIBBPF_ERRNO__FORMAT;
3427 
3428 			idx = elf_ndxscn(scn);
3429 
3430 			obj->efile.symbols = data;
3431 			obj->efile.symbols_shndx = idx;
3432 			obj->efile.strtabidx = sh->sh_link;
3433 		}
3434 	}
3435 
3436 	if (!obj->efile.symbols) {
3437 		pr_warn("elf: couldn't find symbol table in %s, stripped object file?\n",
3438 			obj->path);
3439 		return -ENOENT;
3440 	}
3441 
3442 	scn = NULL;
3443 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3444 		idx = elf_ndxscn(scn);
3445 		sec_desc = &obj->efile.secs[idx];
3446 
3447 		sh = elf_sec_hdr(obj, scn);
3448 		if (!sh)
3449 			return -LIBBPF_ERRNO__FORMAT;
3450 
3451 		name = elf_sec_str(obj, sh->sh_name);
3452 		if (!name)
3453 			return -LIBBPF_ERRNO__FORMAT;
3454 
3455 		if (ignore_elf_section(sh, name))
3456 			continue;
3457 
3458 		data = elf_sec_data(obj, scn);
3459 		if (!data)
3460 			return -LIBBPF_ERRNO__FORMAT;
3461 
3462 		pr_debug("elf: section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
3463 			 idx, name, (unsigned long)data->d_size,
3464 			 (int)sh->sh_link, (unsigned long)sh->sh_flags,
3465 			 (int)sh->sh_type);
3466 
3467 		if (strcmp(name, "license") == 0) {
3468 			err = bpf_object__init_license(obj, data->d_buf, data->d_size);
3469 			if (err)
3470 				return err;
3471 		} else if (strcmp(name, "version") == 0) {
3472 			err = bpf_object__init_kversion(obj, data->d_buf, data->d_size);
3473 			if (err)
3474 				return err;
3475 		} else if (strcmp(name, "maps") == 0) {
3476 			pr_warn("elf: legacy map definitions in 'maps' section are not supported by libbpf v1.0+\n");
3477 			return -ENOTSUP;
3478 		} else if (strcmp(name, MAPS_ELF_SEC) == 0) {
3479 			obj->efile.btf_maps_shndx = idx;
3480 		} else if (strcmp(name, BTF_ELF_SEC) == 0) {
3481 			if (sh->sh_type != SHT_PROGBITS)
3482 				return -LIBBPF_ERRNO__FORMAT;
3483 			btf_data = data;
3484 		} else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
3485 			if (sh->sh_type != SHT_PROGBITS)
3486 				return -LIBBPF_ERRNO__FORMAT;
3487 			btf_ext_data = data;
3488 		} else if (sh->sh_type == SHT_SYMTAB) {
3489 			/* already processed during the first pass above */
3490 		} else if (sh->sh_type == SHT_PROGBITS && data->d_size > 0) {
3491 			if (sh->sh_flags & SHF_EXECINSTR) {
3492 				if (strcmp(name, ".text") == 0)
3493 					obj->efile.text_shndx = idx;
3494 				err = bpf_object__add_programs(obj, data, name, idx);
3495 				if (err)
3496 					return err;
3497 			} else if (strcmp(name, DATA_SEC) == 0 ||
3498 				   str_has_pfx(name, DATA_SEC ".")) {
3499 				sec_desc->sec_type = SEC_DATA;
3500 				sec_desc->shdr = sh;
3501 				sec_desc->data = data;
3502 			} else if (strcmp(name, RODATA_SEC) == 0 ||
3503 				   str_has_pfx(name, RODATA_SEC ".")) {
3504 				sec_desc->sec_type = SEC_RODATA;
3505 				sec_desc->shdr = sh;
3506 				sec_desc->data = data;
3507 			} else if (strcmp(name, STRUCT_OPS_SEC) == 0) {
3508 				obj->efile.st_ops_data = data;
3509 				obj->efile.st_ops_shndx = idx;
3510 			} else if (strcmp(name, STRUCT_OPS_LINK_SEC) == 0) {
3511 				obj->efile.st_ops_link_data = data;
3512 				obj->efile.st_ops_link_shndx = idx;
3513 			} else {
3514 				pr_info("elf: skipping unrecognized data section(%d) %s\n",
3515 					idx, name);
3516 			}
3517 		} else if (sh->sh_type == SHT_REL) {
3518 			int targ_sec_idx = sh->sh_info; /* points to other section */
3519 
3520 			if (sh->sh_entsize != sizeof(Elf64_Rel) ||
3521 			    targ_sec_idx >= obj->efile.sec_cnt)
3522 				return -LIBBPF_ERRNO__FORMAT;
3523 
3524 			/* Only do relo for section with exec instructions */
3525 			if (!section_have_execinstr(obj, targ_sec_idx) &&
3526 			    strcmp(name, ".rel" STRUCT_OPS_SEC) &&
3527 			    strcmp(name, ".rel" STRUCT_OPS_LINK_SEC) &&
3528 			    strcmp(name, ".rel" MAPS_ELF_SEC)) {
3529 				pr_info("elf: skipping relo section(%d) %s for section(%d) %s\n",
3530 					idx, name, targ_sec_idx,
3531 					elf_sec_name(obj, elf_sec_by_idx(obj, targ_sec_idx)) ?: "<?>");
3532 				continue;
3533 			}
3534 
3535 			sec_desc->sec_type = SEC_RELO;
3536 			sec_desc->shdr = sh;
3537 			sec_desc->data = data;
3538 		} else if (sh->sh_type == SHT_NOBITS && (strcmp(name, BSS_SEC) == 0 ||
3539 							 str_has_pfx(name, BSS_SEC "."))) {
3540 			sec_desc->sec_type = SEC_BSS;
3541 			sec_desc->shdr = sh;
3542 			sec_desc->data = data;
3543 		} else {
3544 			pr_info("elf: skipping section(%d) %s (size %zu)\n", idx, name,
3545 				(size_t)sh->sh_size);
3546 		}
3547 	}
3548 
3549 	if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) {
3550 		pr_warn("elf: symbol strings section missing or invalid in %s\n", obj->path);
3551 		return -LIBBPF_ERRNO__FORMAT;
3552 	}
3553 
3554 	/* sort BPF programs by section name and in-section instruction offset
3555 	 * for faster search
3556 	 */
3557 	if (obj->nr_programs)
3558 		qsort(obj->programs, obj->nr_programs, sizeof(*obj->programs), cmp_progs);
3559 
3560 	return bpf_object__init_btf(obj, btf_data, btf_ext_data);
3561 }
3562 
3563 static bool sym_is_extern(const Elf64_Sym *sym)
3564 {
3565 	int bind = ELF64_ST_BIND(sym->st_info);
3566 	/* externs are symbols w/ type=NOTYPE, bind=GLOBAL|WEAK, section=UND */
3567 	return sym->st_shndx == SHN_UNDEF &&
3568 	       (bind == STB_GLOBAL || bind == STB_WEAK) &&
3569 	       ELF64_ST_TYPE(sym->st_info) == STT_NOTYPE;
3570 }
3571 
3572 static bool sym_is_subprog(const Elf64_Sym *sym, int text_shndx)
3573 {
3574 	int bind = ELF64_ST_BIND(sym->st_info);
3575 	int type = ELF64_ST_TYPE(sym->st_info);
3576 
3577 	/* in .text section */
3578 	if (sym->st_shndx != text_shndx)
3579 		return false;
3580 
3581 	/* local function */
3582 	if (bind == STB_LOCAL && type == STT_SECTION)
3583 		return true;
3584 
3585 	/* global function */
3586 	return bind == STB_GLOBAL && type == STT_FUNC;
3587 }
3588 
3589 static int find_extern_btf_id(const struct btf *btf, const char *ext_name)
3590 {
3591 	const struct btf_type *t;
3592 	const char *tname;
3593 	int i, n;
3594 
3595 	if (!btf)
3596 		return -ESRCH;
3597 
3598 	n = btf__type_cnt(btf);
3599 	for (i = 1; i < n; i++) {
3600 		t = btf__type_by_id(btf, i);
3601 
3602 		if (!btf_is_var(t) && !btf_is_func(t))
3603 			continue;
3604 
3605 		tname = btf__name_by_offset(btf, t->name_off);
3606 		if (strcmp(tname, ext_name))
3607 			continue;
3608 
3609 		if (btf_is_var(t) &&
3610 		    btf_var(t)->linkage != BTF_VAR_GLOBAL_EXTERN)
3611 			return -EINVAL;
3612 
3613 		if (btf_is_func(t) && btf_func_linkage(t) != BTF_FUNC_EXTERN)
3614 			return -EINVAL;
3615 
3616 		return i;
3617 	}
3618 
3619 	return -ENOENT;
3620 }
3621 
3622 static int find_extern_sec_btf_id(struct btf *btf, int ext_btf_id) {
3623 	const struct btf_var_secinfo *vs;
3624 	const struct btf_type *t;
3625 	int i, j, n;
3626 
3627 	if (!btf)
3628 		return -ESRCH;
3629 
3630 	n = btf__type_cnt(btf);
3631 	for (i = 1; i < n; i++) {
3632 		t = btf__type_by_id(btf, i);
3633 
3634 		if (!btf_is_datasec(t))
3635 			continue;
3636 
3637 		vs = btf_var_secinfos(t);
3638 		for (j = 0; j < btf_vlen(t); j++, vs++) {
3639 			if (vs->type == ext_btf_id)
3640 				return i;
3641 		}
3642 	}
3643 
3644 	return -ENOENT;
3645 }
3646 
3647 static enum kcfg_type find_kcfg_type(const struct btf *btf, int id,
3648 				     bool *is_signed)
3649 {
3650 	const struct btf_type *t;
3651 	const char *name;
3652 
3653 	t = skip_mods_and_typedefs(btf, id, NULL);
3654 	name = btf__name_by_offset(btf, t->name_off);
3655 
3656 	if (is_signed)
3657 		*is_signed = false;
3658 	switch (btf_kind(t)) {
3659 	case BTF_KIND_INT: {
3660 		int enc = btf_int_encoding(t);
3661 
3662 		if (enc & BTF_INT_BOOL)
3663 			return t->size == 1 ? KCFG_BOOL : KCFG_UNKNOWN;
3664 		if (is_signed)
3665 			*is_signed = enc & BTF_INT_SIGNED;
3666 		if (t->size == 1)
3667 			return KCFG_CHAR;
3668 		if (t->size < 1 || t->size > 8 || (t->size & (t->size - 1)))
3669 			return KCFG_UNKNOWN;
3670 		return KCFG_INT;
3671 	}
3672 	case BTF_KIND_ENUM:
3673 		if (t->size != 4)
3674 			return KCFG_UNKNOWN;
3675 		if (strcmp(name, "libbpf_tristate"))
3676 			return KCFG_UNKNOWN;
3677 		return KCFG_TRISTATE;
3678 	case BTF_KIND_ENUM64:
3679 		if (strcmp(name, "libbpf_tristate"))
3680 			return KCFG_UNKNOWN;
3681 		return KCFG_TRISTATE;
3682 	case BTF_KIND_ARRAY:
3683 		if (btf_array(t)->nelems == 0)
3684 			return KCFG_UNKNOWN;
3685 		if (find_kcfg_type(btf, btf_array(t)->type, NULL) != KCFG_CHAR)
3686 			return KCFG_UNKNOWN;
3687 		return KCFG_CHAR_ARR;
3688 	default:
3689 		return KCFG_UNKNOWN;
3690 	}
3691 }
3692 
3693 static int cmp_externs(const void *_a, const void *_b)
3694 {
3695 	const struct extern_desc *a = _a;
3696 	const struct extern_desc *b = _b;
3697 
3698 	if (a->type != b->type)
3699 		return a->type < b->type ? -1 : 1;
3700 
3701 	if (a->type == EXT_KCFG) {
3702 		/* descending order by alignment requirements */
3703 		if (a->kcfg.align != b->kcfg.align)
3704 			return a->kcfg.align > b->kcfg.align ? -1 : 1;
3705 		/* ascending order by size, within same alignment class */
3706 		if (a->kcfg.sz != b->kcfg.sz)
3707 			return a->kcfg.sz < b->kcfg.sz ? -1 : 1;
3708 	}
3709 
3710 	/* resolve ties by name */
3711 	return strcmp(a->name, b->name);
3712 }
3713 
3714 static int find_int_btf_id(const struct btf *btf)
3715 {
3716 	const struct btf_type *t;
3717 	int i, n;
3718 
3719 	n = btf__type_cnt(btf);
3720 	for (i = 1; i < n; i++) {
3721 		t = btf__type_by_id(btf, i);
3722 
3723 		if (btf_is_int(t) && btf_int_bits(t) == 32)
3724 			return i;
3725 	}
3726 
3727 	return 0;
3728 }
3729 
3730 static int add_dummy_ksym_var(struct btf *btf)
3731 {
3732 	int i, int_btf_id, sec_btf_id, dummy_var_btf_id;
3733 	const struct btf_var_secinfo *vs;
3734 	const struct btf_type *sec;
3735 
3736 	if (!btf)
3737 		return 0;
3738 
3739 	sec_btf_id = btf__find_by_name_kind(btf, KSYMS_SEC,
3740 					    BTF_KIND_DATASEC);
3741 	if (sec_btf_id < 0)
3742 		return 0;
3743 
3744 	sec = btf__type_by_id(btf, sec_btf_id);
3745 	vs = btf_var_secinfos(sec);
3746 	for (i = 0; i < btf_vlen(sec); i++, vs++) {
3747 		const struct btf_type *vt;
3748 
3749 		vt = btf__type_by_id(btf, vs->type);
3750 		if (btf_is_func(vt))
3751 			break;
3752 	}
3753 
3754 	/* No func in ksyms sec.  No need to add dummy var. */
3755 	if (i == btf_vlen(sec))
3756 		return 0;
3757 
3758 	int_btf_id = find_int_btf_id(btf);
3759 	dummy_var_btf_id = btf__add_var(btf,
3760 					"dummy_ksym",
3761 					BTF_VAR_GLOBAL_ALLOCATED,
3762 					int_btf_id);
3763 	if (dummy_var_btf_id < 0)
3764 		pr_warn("cannot create a dummy_ksym var\n");
3765 
3766 	return dummy_var_btf_id;
3767 }
3768 
3769 static int bpf_object__collect_externs(struct bpf_object *obj)
3770 {
3771 	struct btf_type *sec, *kcfg_sec = NULL, *ksym_sec = NULL;
3772 	const struct btf_type *t;
3773 	struct extern_desc *ext;
3774 	int i, n, off, dummy_var_btf_id;
3775 	const char *ext_name, *sec_name;
3776 	size_t ext_essent_len;
3777 	Elf_Scn *scn;
3778 	Elf64_Shdr *sh;
3779 
3780 	if (!obj->efile.symbols)
3781 		return 0;
3782 
3783 	scn = elf_sec_by_idx(obj, obj->efile.symbols_shndx);
3784 	sh = elf_sec_hdr(obj, scn);
3785 	if (!sh || sh->sh_entsize != sizeof(Elf64_Sym))
3786 		return -LIBBPF_ERRNO__FORMAT;
3787 
3788 	dummy_var_btf_id = add_dummy_ksym_var(obj->btf);
3789 	if (dummy_var_btf_id < 0)
3790 		return dummy_var_btf_id;
3791 
3792 	n = sh->sh_size / sh->sh_entsize;
3793 	pr_debug("looking for externs among %d symbols...\n", n);
3794 
3795 	for (i = 0; i < n; i++) {
3796 		Elf64_Sym *sym = elf_sym_by_idx(obj, i);
3797 
3798 		if (!sym)
3799 			return -LIBBPF_ERRNO__FORMAT;
3800 		if (!sym_is_extern(sym))
3801 			continue;
3802 		ext_name = elf_sym_str(obj, sym->st_name);
3803 		if (!ext_name || !ext_name[0])
3804 			continue;
3805 
3806 		ext = obj->externs;
3807 		ext = libbpf_reallocarray(ext, obj->nr_extern + 1, sizeof(*ext));
3808 		if (!ext)
3809 			return -ENOMEM;
3810 		obj->externs = ext;
3811 		ext = &ext[obj->nr_extern];
3812 		memset(ext, 0, sizeof(*ext));
3813 		obj->nr_extern++;
3814 
3815 		ext->btf_id = find_extern_btf_id(obj->btf, ext_name);
3816 		if (ext->btf_id <= 0) {
3817 			pr_warn("failed to find BTF for extern '%s': %d\n",
3818 				ext_name, ext->btf_id);
3819 			return ext->btf_id;
3820 		}
3821 		t = btf__type_by_id(obj->btf, ext->btf_id);
3822 		ext->name = btf__name_by_offset(obj->btf, t->name_off);
3823 		ext->sym_idx = i;
3824 		ext->is_weak = ELF64_ST_BIND(sym->st_info) == STB_WEAK;
3825 
3826 		ext_essent_len = bpf_core_essential_name_len(ext->name);
3827 		ext->essent_name = NULL;
3828 		if (ext_essent_len != strlen(ext->name)) {
3829 			ext->essent_name = strndup(ext->name, ext_essent_len);
3830 			if (!ext->essent_name)
3831 				return -ENOMEM;
3832 		}
3833 
3834 		ext->sec_btf_id = find_extern_sec_btf_id(obj->btf, ext->btf_id);
3835 		if (ext->sec_btf_id <= 0) {
3836 			pr_warn("failed to find BTF for extern '%s' [%d] section: %d\n",
3837 				ext_name, ext->btf_id, ext->sec_btf_id);
3838 			return ext->sec_btf_id;
3839 		}
3840 		sec = (void *)btf__type_by_id(obj->btf, ext->sec_btf_id);
3841 		sec_name = btf__name_by_offset(obj->btf, sec->name_off);
3842 
3843 		if (strcmp(sec_name, KCONFIG_SEC) == 0) {
3844 			if (btf_is_func(t)) {
3845 				pr_warn("extern function %s is unsupported under %s section\n",
3846 					ext->name, KCONFIG_SEC);
3847 				return -ENOTSUP;
3848 			}
3849 			kcfg_sec = sec;
3850 			ext->type = EXT_KCFG;
3851 			ext->kcfg.sz = btf__resolve_size(obj->btf, t->type);
3852 			if (ext->kcfg.sz <= 0) {
3853 				pr_warn("failed to resolve size of extern (kcfg) '%s': %d\n",
3854 					ext_name, ext->kcfg.sz);
3855 				return ext->kcfg.sz;
3856 			}
3857 			ext->kcfg.align = btf__align_of(obj->btf, t->type);
3858 			if (ext->kcfg.align <= 0) {
3859 				pr_warn("failed to determine alignment of extern (kcfg) '%s': %d\n",
3860 					ext_name, ext->kcfg.align);
3861 				return -EINVAL;
3862 			}
3863 			ext->kcfg.type = find_kcfg_type(obj->btf, t->type,
3864 							&ext->kcfg.is_signed);
3865 			if (ext->kcfg.type == KCFG_UNKNOWN) {
3866 				pr_warn("extern (kcfg) '%s': type is unsupported\n", ext_name);
3867 				return -ENOTSUP;
3868 			}
3869 		} else if (strcmp(sec_name, KSYMS_SEC) == 0) {
3870 			ksym_sec = sec;
3871 			ext->type = EXT_KSYM;
3872 			skip_mods_and_typedefs(obj->btf, t->type,
3873 					       &ext->ksym.type_id);
3874 		} else {
3875 			pr_warn("unrecognized extern section '%s'\n", sec_name);
3876 			return -ENOTSUP;
3877 		}
3878 	}
3879 	pr_debug("collected %d externs total\n", obj->nr_extern);
3880 
3881 	if (!obj->nr_extern)
3882 		return 0;
3883 
3884 	/* sort externs by type, for kcfg ones also by (align, size, name) */
3885 	qsort(obj->externs, obj->nr_extern, sizeof(*ext), cmp_externs);
3886 
3887 	/* for .ksyms section, we need to turn all externs into allocated
3888 	 * variables in BTF to pass kernel verification; we do this by
3889 	 * pretending that each extern is a 8-byte variable
3890 	 */
3891 	if (ksym_sec) {
3892 		/* find existing 4-byte integer type in BTF to use for fake
3893 		 * extern variables in DATASEC
3894 		 */
3895 		int int_btf_id = find_int_btf_id(obj->btf);
3896 		/* For extern function, a dummy_var added earlier
3897 		 * will be used to replace the vs->type and
3898 		 * its name string will be used to refill
3899 		 * the missing param's name.
3900 		 */
3901 		const struct btf_type *dummy_var;
3902 
3903 		dummy_var = btf__type_by_id(obj->btf, dummy_var_btf_id);
3904 		for (i = 0; i < obj->nr_extern; i++) {
3905 			ext = &obj->externs[i];
3906 			if (ext->type != EXT_KSYM)
3907 				continue;
3908 			pr_debug("extern (ksym) #%d: symbol %d, name %s\n",
3909 				 i, ext->sym_idx, ext->name);
3910 		}
3911 
3912 		sec = ksym_sec;
3913 		n = btf_vlen(sec);
3914 		for (i = 0, off = 0; i < n; i++, off += sizeof(int)) {
3915 			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
3916 			struct btf_type *vt;
3917 
3918 			vt = (void *)btf__type_by_id(obj->btf, vs->type);
3919 			ext_name = btf__name_by_offset(obj->btf, vt->name_off);
3920 			ext = find_extern_by_name(obj, ext_name);
3921 			if (!ext) {
3922 				pr_warn("failed to find extern definition for BTF %s '%s'\n",
3923 					btf_kind_str(vt), ext_name);
3924 				return -ESRCH;
3925 			}
3926 			if (btf_is_func(vt)) {
3927 				const struct btf_type *func_proto;
3928 				struct btf_param *param;
3929 				int j;
3930 
3931 				func_proto = btf__type_by_id(obj->btf,
3932 							     vt->type);
3933 				param = btf_params(func_proto);
3934 				/* Reuse the dummy_var string if the
3935 				 * func proto does not have param name.
3936 				 */
3937 				for (j = 0; j < btf_vlen(func_proto); j++)
3938 					if (param[j].type && !param[j].name_off)
3939 						param[j].name_off =
3940 							dummy_var->name_off;
3941 				vs->type = dummy_var_btf_id;
3942 				vt->info &= ~0xffff;
3943 				vt->info |= BTF_FUNC_GLOBAL;
3944 			} else {
3945 				btf_var(vt)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
3946 				vt->type = int_btf_id;
3947 			}
3948 			vs->offset = off;
3949 			vs->size = sizeof(int);
3950 		}
3951 		sec->size = off;
3952 	}
3953 
3954 	if (kcfg_sec) {
3955 		sec = kcfg_sec;
3956 		/* for kcfg externs calculate their offsets within a .kconfig map */
3957 		off = 0;
3958 		for (i = 0; i < obj->nr_extern; i++) {
3959 			ext = &obj->externs[i];
3960 			if (ext->type != EXT_KCFG)
3961 				continue;
3962 
3963 			ext->kcfg.data_off = roundup(off, ext->kcfg.align);
3964 			off = ext->kcfg.data_off + ext->kcfg.sz;
3965 			pr_debug("extern (kcfg) #%d: symbol %d, off %u, name %s\n",
3966 				 i, ext->sym_idx, ext->kcfg.data_off, ext->name);
3967 		}
3968 		sec->size = off;
3969 		n = btf_vlen(sec);
3970 		for (i = 0; i < n; i++) {
3971 			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
3972 
3973 			t = btf__type_by_id(obj->btf, vs->type);
3974 			ext_name = btf__name_by_offset(obj->btf, t->name_off);
3975 			ext = find_extern_by_name(obj, ext_name);
3976 			if (!ext) {
3977 				pr_warn("failed to find extern definition for BTF var '%s'\n",
3978 					ext_name);
3979 				return -ESRCH;
3980 			}
3981 			btf_var(t)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
3982 			vs->offset = ext->kcfg.data_off;
3983 		}
3984 	}
3985 	return 0;
3986 }
3987 
3988 static bool prog_is_subprog(const struct bpf_object *obj, const struct bpf_program *prog)
3989 {
3990 	return prog->sec_idx == obj->efile.text_shndx && obj->nr_programs > 1;
3991 }
3992 
3993 struct bpf_program *
3994 bpf_object__find_program_by_name(const struct bpf_object *obj,
3995 				 const char *name)
3996 {
3997 	struct bpf_program *prog;
3998 
3999 	bpf_object__for_each_program(prog, obj) {
4000 		if (prog_is_subprog(obj, prog))
4001 			continue;
4002 		if (!strcmp(prog->name, name))
4003 			return prog;
4004 	}
4005 	return errno = ENOENT, NULL;
4006 }
4007 
4008 static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
4009 				      int shndx)
4010 {
4011 	switch (obj->efile.secs[shndx].sec_type) {
4012 	case SEC_BSS:
4013 	case SEC_DATA:
4014 	case SEC_RODATA:
4015 		return true;
4016 	default:
4017 		return false;
4018 	}
4019 }
4020 
4021 static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
4022 				      int shndx)
4023 {
4024 	return shndx == obj->efile.btf_maps_shndx;
4025 }
4026 
4027 static enum libbpf_map_type
4028 bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
4029 {
4030 	if (shndx == obj->efile.symbols_shndx)
4031 		return LIBBPF_MAP_KCONFIG;
4032 
4033 	switch (obj->efile.secs[shndx].sec_type) {
4034 	case SEC_BSS:
4035 		return LIBBPF_MAP_BSS;
4036 	case SEC_DATA:
4037 		return LIBBPF_MAP_DATA;
4038 	case SEC_RODATA:
4039 		return LIBBPF_MAP_RODATA;
4040 	default:
4041 		return LIBBPF_MAP_UNSPEC;
4042 	}
4043 }
4044 
4045 static int bpf_program__record_reloc(struct bpf_program *prog,
4046 				     struct reloc_desc *reloc_desc,
4047 				     __u32 insn_idx, const char *sym_name,
4048 				     const Elf64_Sym *sym, const Elf64_Rel *rel)
4049 {
4050 	struct bpf_insn *insn = &prog->insns[insn_idx];
4051 	size_t map_idx, nr_maps = prog->obj->nr_maps;
4052 	struct bpf_object *obj = prog->obj;
4053 	__u32 shdr_idx = sym->st_shndx;
4054 	enum libbpf_map_type type;
4055 	const char *sym_sec_name;
4056 	struct bpf_map *map;
4057 
4058 	if (!is_call_insn(insn) && !is_ldimm64_insn(insn)) {
4059 		pr_warn("prog '%s': invalid relo against '%s' for insns[%d].code 0x%x\n",
4060 			prog->name, sym_name, insn_idx, insn->code);
4061 		return -LIBBPF_ERRNO__RELOC;
4062 	}
4063 
4064 	if (sym_is_extern(sym)) {
4065 		int sym_idx = ELF64_R_SYM(rel->r_info);
4066 		int i, n = obj->nr_extern;
4067 		struct extern_desc *ext;
4068 
4069 		for (i = 0; i < n; i++) {
4070 			ext = &obj->externs[i];
4071 			if (ext->sym_idx == sym_idx)
4072 				break;
4073 		}
4074 		if (i >= n) {
4075 			pr_warn("prog '%s': extern relo failed to find extern for '%s' (%d)\n",
4076 				prog->name, sym_name, sym_idx);
4077 			return -LIBBPF_ERRNO__RELOC;
4078 		}
4079 		pr_debug("prog '%s': found extern #%d '%s' (sym %d) for insn #%u\n",
4080 			 prog->name, i, ext->name, ext->sym_idx, insn_idx);
4081 		if (insn->code == (BPF_JMP | BPF_CALL))
4082 			reloc_desc->type = RELO_EXTERN_CALL;
4083 		else
4084 			reloc_desc->type = RELO_EXTERN_LD64;
4085 		reloc_desc->insn_idx = insn_idx;
4086 		reloc_desc->ext_idx = i;
4087 		return 0;
4088 	}
4089 
4090 	/* sub-program call relocation */
4091 	if (is_call_insn(insn)) {
4092 		if (insn->src_reg != BPF_PSEUDO_CALL) {
4093 			pr_warn("prog '%s': incorrect bpf_call opcode\n", prog->name);
4094 			return -LIBBPF_ERRNO__RELOC;
4095 		}
4096 		/* text_shndx can be 0, if no default "main" program exists */
4097 		if (!shdr_idx || shdr_idx != obj->efile.text_shndx) {
4098 			sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4099 			pr_warn("prog '%s': bad call relo against '%s' in section '%s'\n",
4100 				prog->name, sym_name, sym_sec_name);
4101 			return -LIBBPF_ERRNO__RELOC;
4102 		}
4103 		if (sym->st_value % BPF_INSN_SZ) {
4104 			pr_warn("prog '%s': bad call relo against '%s' at offset %zu\n",
4105 				prog->name, sym_name, (size_t)sym->st_value);
4106 			return -LIBBPF_ERRNO__RELOC;
4107 		}
4108 		reloc_desc->type = RELO_CALL;
4109 		reloc_desc->insn_idx = insn_idx;
4110 		reloc_desc->sym_off = sym->st_value;
4111 		return 0;
4112 	}
4113 
4114 	if (!shdr_idx || shdr_idx >= SHN_LORESERVE) {
4115 		pr_warn("prog '%s': invalid relo against '%s' in special section 0x%x; forgot to initialize global var?..\n",
4116 			prog->name, sym_name, shdr_idx);
4117 		return -LIBBPF_ERRNO__RELOC;
4118 	}
4119 
4120 	/* loading subprog addresses */
4121 	if (sym_is_subprog(sym, obj->efile.text_shndx)) {
4122 		/* global_func: sym->st_value = offset in the section, insn->imm = 0.
4123 		 * local_func: sym->st_value = 0, insn->imm = offset in the section.
4124 		 */
4125 		if ((sym->st_value % BPF_INSN_SZ) || (insn->imm % BPF_INSN_SZ)) {
4126 			pr_warn("prog '%s': bad subprog addr relo against '%s' at offset %zu+%d\n",
4127 				prog->name, sym_name, (size_t)sym->st_value, insn->imm);
4128 			return -LIBBPF_ERRNO__RELOC;
4129 		}
4130 
4131 		reloc_desc->type = RELO_SUBPROG_ADDR;
4132 		reloc_desc->insn_idx = insn_idx;
4133 		reloc_desc->sym_off = sym->st_value;
4134 		return 0;
4135 	}
4136 
4137 	type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
4138 	sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4139 
4140 	/* generic map reference relocation */
4141 	if (type == LIBBPF_MAP_UNSPEC) {
4142 		if (!bpf_object__shndx_is_maps(obj, shdr_idx)) {
4143 			pr_warn("prog '%s': bad map relo against '%s' in section '%s'\n",
4144 				prog->name, sym_name, sym_sec_name);
4145 			return -LIBBPF_ERRNO__RELOC;
4146 		}
4147 		for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4148 			map = &obj->maps[map_idx];
4149 			if (map->libbpf_type != type ||
4150 			    map->sec_idx != sym->st_shndx ||
4151 			    map->sec_offset != sym->st_value)
4152 				continue;
4153 			pr_debug("prog '%s': found map %zd (%s, sec %d, off %zu) for insn #%u\n",
4154 				 prog->name, map_idx, map->name, map->sec_idx,
4155 				 map->sec_offset, insn_idx);
4156 			break;
4157 		}
4158 		if (map_idx >= nr_maps) {
4159 			pr_warn("prog '%s': map relo failed to find map for section '%s', off %zu\n",
4160 				prog->name, sym_sec_name, (size_t)sym->st_value);
4161 			return -LIBBPF_ERRNO__RELOC;
4162 		}
4163 		reloc_desc->type = RELO_LD64;
4164 		reloc_desc->insn_idx = insn_idx;
4165 		reloc_desc->map_idx = map_idx;
4166 		reloc_desc->sym_off = 0; /* sym->st_value determines map_idx */
4167 		return 0;
4168 	}
4169 
4170 	/* global data map relocation */
4171 	if (!bpf_object__shndx_is_data(obj, shdr_idx)) {
4172 		pr_warn("prog '%s': bad data relo against section '%s'\n",
4173 			prog->name, sym_sec_name);
4174 		return -LIBBPF_ERRNO__RELOC;
4175 	}
4176 	for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4177 		map = &obj->maps[map_idx];
4178 		if (map->libbpf_type != type || map->sec_idx != sym->st_shndx)
4179 			continue;
4180 		pr_debug("prog '%s': found data map %zd (%s, sec %d, off %zu) for insn %u\n",
4181 			 prog->name, map_idx, map->name, map->sec_idx,
4182 			 map->sec_offset, insn_idx);
4183 		break;
4184 	}
4185 	if (map_idx >= nr_maps) {
4186 		pr_warn("prog '%s': data relo failed to find map for section '%s'\n",
4187 			prog->name, sym_sec_name);
4188 		return -LIBBPF_ERRNO__RELOC;
4189 	}
4190 
4191 	reloc_desc->type = RELO_DATA;
4192 	reloc_desc->insn_idx = insn_idx;
4193 	reloc_desc->map_idx = map_idx;
4194 	reloc_desc->sym_off = sym->st_value;
4195 	return 0;
4196 }
4197 
4198 static bool prog_contains_insn(const struct bpf_program *prog, size_t insn_idx)
4199 {
4200 	return insn_idx >= prog->sec_insn_off &&
4201 	       insn_idx < prog->sec_insn_off + prog->sec_insn_cnt;
4202 }
4203 
4204 static struct bpf_program *find_prog_by_sec_insn(const struct bpf_object *obj,
4205 						 size_t sec_idx, size_t insn_idx)
4206 {
4207 	int l = 0, r = obj->nr_programs - 1, m;
4208 	struct bpf_program *prog;
4209 
4210 	if (!obj->nr_programs)
4211 		return NULL;
4212 
4213 	while (l < r) {
4214 		m = l + (r - l + 1) / 2;
4215 		prog = &obj->programs[m];
4216 
4217 		if (prog->sec_idx < sec_idx ||
4218 		    (prog->sec_idx == sec_idx && prog->sec_insn_off <= insn_idx))
4219 			l = m;
4220 		else
4221 			r = m - 1;
4222 	}
4223 	/* matching program could be at index l, but it still might be the
4224 	 * wrong one, so we need to double check conditions for the last time
4225 	 */
4226 	prog = &obj->programs[l];
4227 	if (prog->sec_idx == sec_idx && prog_contains_insn(prog, insn_idx))
4228 		return prog;
4229 	return NULL;
4230 }
4231 
4232 static int
4233 bpf_object__collect_prog_relos(struct bpf_object *obj, Elf64_Shdr *shdr, Elf_Data *data)
4234 {
4235 	const char *relo_sec_name, *sec_name;
4236 	size_t sec_idx = shdr->sh_info, sym_idx;
4237 	struct bpf_program *prog;
4238 	struct reloc_desc *relos;
4239 	int err, i, nrels;
4240 	const char *sym_name;
4241 	__u32 insn_idx;
4242 	Elf_Scn *scn;
4243 	Elf_Data *scn_data;
4244 	Elf64_Sym *sym;
4245 	Elf64_Rel *rel;
4246 
4247 	if (sec_idx >= obj->efile.sec_cnt)
4248 		return -EINVAL;
4249 
4250 	scn = elf_sec_by_idx(obj, sec_idx);
4251 	scn_data = elf_sec_data(obj, scn);
4252 
4253 	relo_sec_name = elf_sec_str(obj, shdr->sh_name);
4254 	sec_name = elf_sec_name(obj, scn);
4255 	if (!relo_sec_name || !sec_name)
4256 		return -EINVAL;
4257 
4258 	pr_debug("sec '%s': collecting relocation for section(%zu) '%s'\n",
4259 		 relo_sec_name, sec_idx, sec_name);
4260 	nrels = shdr->sh_size / shdr->sh_entsize;
4261 
4262 	for (i = 0; i < nrels; i++) {
4263 		rel = elf_rel_by_idx(data, i);
4264 		if (!rel) {
4265 			pr_warn("sec '%s': failed to get relo #%d\n", relo_sec_name, i);
4266 			return -LIBBPF_ERRNO__FORMAT;
4267 		}
4268 
4269 		sym_idx = ELF64_R_SYM(rel->r_info);
4270 		sym = elf_sym_by_idx(obj, sym_idx);
4271 		if (!sym) {
4272 			pr_warn("sec '%s': symbol #%zu not found for relo #%d\n",
4273 				relo_sec_name, sym_idx, i);
4274 			return -LIBBPF_ERRNO__FORMAT;
4275 		}
4276 
4277 		if (sym->st_shndx >= obj->efile.sec_cnt) {
4278 			pr_warn("sec '%s': corrupted symbol #%zu pointing to invalid section #%zu for relo #%d\n",
4279 				relo_sec_name, sym_idx, (size_t)sym->st_shndx, i);
4280 			return -LIBBPF_ERRNO__FORMAT;
4281 		}
4282 
4283 		if (rel->r_offset % BPF_INSN_SZ || rel->r_offset >= scn_data->d_size) {
4284 			pr_warn("sec '%s': invalid offset 0x%zx for relo #%d\n",
4285 				relo_sec_name, (size_t)rel->r_offset, i);
4286 			return -LIBBPF_ERRNO__FORMAT;
4287 		}
4288 
4289 		insn_idx = rel->r_offset / BPF_INSN_SZ;
4290 		/* relocations against static functions are recorded as
4291 		 * relocations against the section that contains a function;
4292 		 * in such case, symbol will be STT_SECTION and sym.st_name
4293 		 * will point to empty string (0), so fetch section name
4294 		 * instead
4295 		 */
4296 		if (ELF64_ST_TYPE(sym->st_info) == STT_SECTION && sym->st_name == 0)
4297 			sym_name = elf_sec_name(obj, elf_sec_by_idx(obj, sym->st_shndx));
4298 		else
4299 			sym_name = elf_sym_str(obj, sym->st_name);
4300 		sym_name = sym_name ?: "<?";
4301 
4302 		pr_debug("sec '%s': relo #%d: insn #%u against '%s'\n",
4303 			 relo_sec_name, i, insn_idx, sym_name);
4304 
4305 		prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
4306 		if (!prog) {
4307 			pr_debug("sec '%s': relo #%d: couldn't find program in section '%s' for insn #%u, probably overridden weak function, skipping...\n",
4308 				relo_sec_name, i, sec_name, insn_idx);
4309 			continue;
4310 		}
4311 
4312 		relos = libbpf_reallocarray(prog->reloc_desc,
4313 					    prog->nr_reloc + 1, sizeof(*relos));
4314 		if (!relos)
4315 			return -ENOMEM;
4316 		prog->reloc_desc = relos;
4317 
4318 		/* adjust insn_idx to local BPF program frame of reference */
4319 		insn_idx -= prog->sec_insn_off;
4320 		err = bpf_program__record_reloc(prog, &relos[prog->nr_reloc],
4321 						insn_idx, sym_name, sym, rel);
4322 		if (err)
4323 			return err;
4324 
4325 		prog->nr_reloc++;
4326 	}
4327 	return 0;
4328 }
4329 
4330 static int map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map)
4331 {
4332 	int id;
4333 
4334 	if (!obj->btf)
4335 		return -ENOENT;
4336 
4337 	/* if it's BTF-defined map, we don't need to search for type IDs.
4338 	 * For struct_ops map, it does not need btf_key_type_id and
4339 	 * btf_value_type_id.
4340 	 */
4341 	if (map->sec_idx == obj->efile.btf_maps_shndx || bpf_map__is_struct_ops(map))
4342 		return 0;
4343 
4344 	/*
4345 	 * LLVM annotates global data differently in BTF, that is,
4346 	 * only as '.data', '.bss' or '.rodata'.
4347 	 */
4348 	if (!bpf_map__is_internal(map))
4349 		return -ENOENT;
4350 
4351 	id = btf__find_by_name(obj->btf, map->real_name);
4352 	if (id < 0)
4353 		return id;
4354 
4355 	map->btf_key_type_id = 0;
4356 	map->btf_value_type_id = id;
4357 	return 0;
4358 }
4359 
4360 static int bpf_get_map_info_from_fdinfo(int fd, struct bpf_map_info *info)
4361 {
4362 	char file[PATH_MAX], buff[4096];
4363 	FILE *fp;
4364 	__u32 val;
4365 	int err;
4366 
4367 	snprintf(file, sizeof(file), "/proc/%d/fdinfo/%d", getpid(), fd);
4368 	memset(info, 0, sizeof(*info));
4369 
4370 	fp = fopen(file, "re");
4371 	if (!fp) {
4372 		err = -errno;
4373 		pr_warn("failed to open %s: %d. No procfs support?\n", file,
4374 			err);
4375 		return err;
4376 	}
4377 
4378 	while (fgets(buff, sizeof(buff), fp)) {
4379 		if (sscanf(buff, "map_type:\t%u", &val) == 1)
4380 			info->type = val;
4381 		else if (sscanf(buff, "key_size:\t%u", &val) == 1)
4382 			info->key_size = val;
4383 		else if (sscanf(buff, "value_size:\t%u", &val) == 1)
4384 			info->value_size = val;
4385 		else if (sscanf(buff, "max_entries:\t%u", &val) == 1)
4386 			info->max_entries = val;
4387 		else if (sscanf(buff, "map_flags:\t%i", &val) == 1)
4388 			info->map_flags = val;
4389 	}
4390 
4391 	fclose(fp);
4392 
4393 	return 0;
4394 }
4395 
4396 bool bpf_map__autocreate(const struct bpf_map *map)
4397 {
4398 	return map->autocreate;
4399 }
4400 
4401 int bpf_map__set_autocreate(struct bpf_map *map, bool autocreate)
4402 {
4403 	if (map->obj->loaded)
4404 		return libbpf_err(-EBUSY);
4405 
4406 	map->autocreate = autocreate;
4407 	return 0;
4408 }
4409 
4410 int bpf_map__reuse_fd(struct bpf_map *map, int fd)
4411 {
4412 	struct bpf_map_info info;
4413 	__u32 len = sizeof(info), name_len;
4414 	int new_fd, err;
4415 	char *new_name;
4416 
4417 	memset(&info, 0, len);
4418 	err = bpf_map_get_info_by_fd(fd, &info, &len);
4419 	if (err && errno == EINVAL)
4420 		err = bpf_get_map_info_from_fdinfo(fd, &info);
4421 	if (err)
4422 		return libbpf_err(err);
4423 
4424 	name_len = strlen(info.name);
4425 	if (name_len == BPF_OBJ_NAME_LEN - 1 && strncmp(map->name, info.name, name_len) == 0)
4426 		new_name = strdup(map->name);
4427 	else
4428 		new_name = strdup(info.name);
4429 
4430 	if (!new_name)
4431 		return libbpf_err(-errno);
4432 
4433 	/*
4434 	 * Like dup(), but make sure new FD is >= 3 and has O_CLOEXEC set.
4435 	 * This is similar to what we do in ensure_good_fd(), but without
4436 	 * closing original FD.
4437 	 */
4438 	new_fd = fcntl(fd, F_DUPFD_CLOEXEC, 3);
4439 	if (new_fd < 0) {
4440 		err = -errno;
4441 		goto err_free_new_name;
4442 	}
4443 
4444 	err = zclose(map->fd);
4445 	if (err) {
4446 		err = -errno;
4447 		goto err_close_new_fd;
4448 	}
4449 	free(map->name);
4450 
4451 	map->fd = new_fd;
4452 	map->name = new_name;
4453 	map->def.type = info.type;
4454 	map->def.key_size = info.key_size;
4455 	map->def.value_size = info.value_size;
4456 	map->def.max_entries = info.max_entries;
4457 	map->def.map_flags = info.map_flags;
4458 	map->btf_key_type_id = info.btf_key_type_id;
4459 	map->btf_value_type_id = info.btf_value_type_id;
4460 	map->reused = true;
4461 	map->map_extra = info.map_extra;
4462 
4463 	return 0;
4464 
4465 err_close_new_fd:
4466 	close(new_fd);
4467 err_free_new_name:
4468 	free(new_name);
4469 	return libbpf_err(err);
4470 }
4471 
4472 __u32 bpf_map__max_entries(const struct bpf_map *map)
4473 {
4474 	return map->def.max_entries;
4475 }
4476 
4477 struct bpf_map *bpf_map__inner_map(struct bpf_map *map)
4478 {
4479 	if (!bpf_map_type__is_map_in_map(map->def.type))
4480 		return errno = EINVAL, NULL;
4481 
4482 	return map->inner_map;
4483 }
4484 
4485 int bpf_map__set_max_entries(struct bpf_map *map, __u32 max_entries)
4486 {
4487 	if (map->obj->loaded)
4488 		return libbpf_err(-EBUSY);
4489 
4490 	map->def.max_entries = max_entries;
4491 
4492 	/* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
4493 	if (map_is_ringbuf(map))
4494 		map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
4495 
4496 	return 0;
4497 }
4498 
4499 static int
4500 bpf_object__probe_loading(struct bpf_object *obj)
4501 {
4502 	char *cp, errmsg[STRERR_BUFSIZE];
4503 	struct bpf_insn insns[] = {
4504 		BPF_MOV64_IMM(BPF_REG_0, 0),
4505 		BPF_EXIT_INSN(),
4506 	};
4507 	int ret, insn_cnt = ARRAY_SIZE(insns);
4508 
4509 	if (obj->gen_loader)
4510 		return 0;
4511 
4512 	ret = bump_rlimit_memlock();
4513 	if (ret)
4514 		pr_warn("Failed to bump RLIMIT_MEMLOCK (err = %d), you might need to do it explicitly!\n", ret);
4515 
4516 	/* make sure basic loading works */
4517 	ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4518 	if (ret < 0)
4519 		ret = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, NULL);
4520 	if (ret < 0) {
4521 		ret = errno;
4522 		cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4523 		pr_warn("Error in %s():%s(%d). Couldn't load trivial BPF "
4524 			"program. Make sure your kernel supports BPF "
4525 			"(CONFIG_BPF_SYSCALL=y) and/or that RLIMIT_MEMLOCK is "
4526 			"set to big enough value.\n", __func__, cp, ret);
4527 		return -ret;
4528 	}
4529 	close(ret);
4530 
4531 	return 0;
4532 }
4533 
4534 static int probe_fd(int fd)
4535 {
4536 	if (fd >= 0)
4537 		close(fd);
4538 	return fd >= 0;
4539 }
4540 
4541 static int probe_kern_prog_name(void)
4542 {
4543 	const size_t attr_sz = offsetofend(union bpf_attr, prog_name);
4544 	struct bpf_insn insns[] = {
4545 		BPF_MOV64_IMM(BPF_REG_0, 0),
4546 		BPF_EXIT_INSN(),
4547 	};
4548 	union bpf_attr attr;
4549 	int ret;
4550 
4551 	memset(&attr, 0, attr_sz);
4552 	attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
4553 	attr.license = ptr_to_u64("GPL");
4554 	attr.insns = ptr_to_u64(insns);
4555 	attr.insn_cnt = (__u32)ARRAY_SIZE(insns);
4556 	libbpf_strlcpy(attr.prog_name, "libbpf_nametest", sizeof(attr.prog_name));
4557 
4558 	/* make sure loading with name works */
4559 	ret = sys_bpf_prog_load(&attr, attr_sz, PROG_LOAD_ATTEMPTS);
4560 	return probe_fd(ret);
4561 }
4562 
4563 static int probe_kern_global_data(void)
4564 {
4565 	char *cp, errmsg[STRERR_BUFSIZE];
4566 	struct bpf_insn insns[] = {
4567 		BPF_LD_MAP_VALUE(BPF_REG_1, 0, 16),
4568 		BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 42),
4569 		BPF_MOV64_IMM(BPF_REG_0, 0),
4570 		BPF_EXIT_INSN(),
4571 	};
4572 	int ret, map, insn_cnt = ARRAY_SIZE(insns);
4573 
4574 	map = bpf_map_create(BPF_MAP_TYPE_ARRAY, "libbpf_global", sizeof(int), 32, 1, NULL);
4575 	if (map < 0) {
4576 		ret = -errno;
4577 		cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4578 		pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
4579 			__func__, cp, -ret);
4580 		return ret;
4581 	}
4582 
4583 	insns[0].imm = map;
4584 
4585 	ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4586 	close(map);
4587 	return probe_fd(ret);
4588 }
4589 
4590 static int probe_kern_btf(void)
4591 {
4592 	static const char strs[] = "\0int";
4593 	__u32 types[] = {
4594 		/* int */
4595 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),
4596 	};
4597 
4598 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4599 					     strs, sizeof(strs)));
4600 }
4601 
4602 static int probe_kern_btf_func(void)
4603 {
4604 	static const char strs[] = "\0int\0x\0a";
4605 	/* void x(int a) {} */
4606 	__u32 types[] = {
4607 		/* int */
4608 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4609 		/* FUNC_PROTO */                                /* [2] */
4610 		BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
4611 		BTF_PARAM_ENC(7, 1),
4612 		/* FUNC x */                                    /* [3] */
4613 		BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0), 2),
4614 	};
4615 
4616 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4617 					     strs, sizeof(strs)));
4618 }
4619 
4620 static int probe_kern_btf_func_global(void)
4621 {
4622 	static const char strs[] = "\0int\0x\0a";
4623 	/* static void x(int a) {} */
4624 	__u32 types[] = {
4625 		/* int */
4626 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4627 		/* FUNC_PROTO */                                /* [2] */
4628 		BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
4629 		BTF_PARAM_ENC(7, 1),
4630 		/* FUNC x BTF_FUNC_GLOBAL */                    /* [3] */
4631 		BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, BTF_FUNC_GLOBAL), 2),
4632 	};
4633 
4634 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4635 					     strs, sizeof(strs)));
4636 }
4637 
4638 static int probe_kern_btf_datasec(void)
4639 {
4640 	static const char strs[] = "\0x\0.data";
4641 	/* static int a; */
4642 	__u32 types[] = {
4643 		/* int */
4644 		BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4645 		/* VAR x */                                     /* [2] */
4646 		BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
4647 		BTF_VAR_STATIC,
4648 		/* DATASEC val */                               /* [3] */
4649 		BTF_TYPE_ENC(3, BTF_INFO_ENC(BTF_KIND_DATASEC, 0, 1), 4),
4650 		BTF_VAR_SECINFO_ENC(2, 0, 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_float(void)
4658 {
4659 	static const char strs[] = "\0float";
4660 	__u32 types[] = {
4661 		/* float */
4662 		BTF_TYPE_FLOAT_ENC(1, 4),
4663 	};
4664 
4665 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4666 					     strs, sizeof(strs)));
4667 }
4668 
4669 static int probe_kern_btf_decl_tag(void)
4670 {
4671 	static const char strs[] = "\0tag";
4672 	__u32 types[] = {
4673 		/* int */
4674 		BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4675 		/* VAR x */                                     /* [2] */
4676 		BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
4677 		BTF_VAR_STATIC,
4678 		/* attr */
4679 		BTF_TYPE_DECL_TAG_ENC(1, 2, -1),
4680 	};
4681 
4682 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4683 					     strs, sizeof(strs)));
4684 }
4685 
4686 static int probe_kern_btf_type_tag(void)
4687 {
4688 	static const char strs[] = "\0tag";
4689 	__u32 types[] = {
4690 		/* int */
4691 		BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4),		/* [1] */
4692 		/* attr */
4693 		BTF_TYPE_TYPE_TAG_ENC(1, 1),				/* [2] */
4694 		/* ptr */
4695 		BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_PTR, 0, 0), 2),	/* [3] */
4696 	};
4697 
4698 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4699 					     strs, sizeof(strs)));
4700 }
4701 
4702 static int probe_kern_array_mmap(void)
4703 {
4704 	LIBBPF_OPTS(bpf_map_create_opts, opts, .map_flags = BPF_F_MMAPABLE);
4705 	int fd;
4706 
4707 	fd = bpf_map_create(BPF_MAP_TYPE_ARRAY, "libbpf_mmap", sizeof(int), sizeof(int), 1, &opts);
4708 	return probe_fd(fd);
4709 }
4710 
4711 static int probe_kern_exp_attach_type(void)
4712 {
4713 	LIBBPF_OPTS(bpf_prog_load_opts, opts, .expected_attach_type = BPF_CGROUP_INET_SOCK_CREATE);
4714 	struct bpf_insn insns[] = {
4715 		BPF_MOV64_IMM(BPF_REG_0, 0),
4716 		BPF_EXIT_INSN(),
4717 	};
4718 	int fd, insn_cnt = ARRAY_SIZE(insns);
4719 
4720 	/* use any valid combination of program type and (optional)
4721 	 * non-zero expected attach type (i.e., not a BPF_CGROUP_INET_INGRESS)
4722 	 * to see if kernel supports expected_attach_type field for
4723 	 * BPF_PROG_LOAD command
4724 	 */
4725 	fd = bpf_prog_load(BPF_PROG_TYPE_CGROUP_SOCK, NULL, "GPL", insns, insn_cnt, &opts);
4726 	return probe_fd(fd);
4727 }
4728 
4729 static int probe_kern_probe_read_kernel(void)
4730 {
4731 	struct bpf_insn insns[] = {
4732 		BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),	/* r1 = r10 (fp) */
4733 		BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -8),	/* r1 += -8 */
4734 		BPF_MOV64_IMM(BPF_REG_2, 8),		/* r2 = 8 */
4735 		BPF_MOV64_IMM(BPF_REG_3, 0),		/* r3 = 0 */
4736 		BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_probe_read_kernel),
4737 		BPF_EXIT_INSN(),
4738 	};
4739 	int fd, insn_cnt = ARRAY_SIZE(insns);
4740 
4741 	fd = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, NULL);
4742 	return probe_fd(fd);
4743 }
4744 
4745 static int probe_prog_bind_map(void)
4746 {
4747 	char *cp, errmsg[STRERR_BUFSIZE];
4748 	struct bpf_insn insns[] = {
4749 		BPF_MOV64_IMM(BPF_REG_0, 0),
4750 		BPF_EXIT_INSN(),
4751 	};
4752 	int ret, map, prog, insn_cnt = ARRAY_SIZE(insns);
4753 
4754 	map = bpf_map_create(BPF_MAP_TYPE_ARRAY, "libbpf_det_bind", sizeof(int), 32, 1, NULL);
4755 	if (map < 0) {
4756 		ret = -errno;
4757 		cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4758 		pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
4759 			__func__, cp, -ret);
4760 		return ret;
4761 	}
4762 
4763 	prog = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4764 	if (prog < 0) {
4765 		close(map);
4766 		return 0;
4767 	}
4768 
4769 	ret = bpf_prog_bind_map(prog, map, NULL);
4770 
4771 	close(map);
4772 	close(prog);
4773 
4774 	return ret >= 0;
4775 }
4776 
4777 static int probe_module_btf(void)
4778 {
4779 	static const char strs[] = "\0int";
4780 	__u32 types[] = {
4781 		/* int */
4782 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),
4783 	};
4784 	struct bpf_btf_info info;
4785 	__u32 len = sizeof(info);
4786 	char name[16];
4787 	int fd, err;
4788 
4789 	fd = libbpf__load_raw_btf((char *)types, sizeof(types), strs, sizeof(strs));
4790 	if (fd < 0)
4791 		return 0; /* BTF not supported at all */
4792 
4793 	memset(&info, 0, sizeof(info));
4794 	info.name = ptr_to_u64(name);
4795 	info.name_len = sizeof(name);
4796 
4797 	/* check that BPF_OBJ_GET_INFO_BY_FD supports specifying name pointer;
4798 	 * kernel's module BTF support coincides with support for
4799 	 * name/name_len fields in struct bpf_btf_info.
4800 	 */
4801 	err = bpf_btf_get_info_by_fd(fd, &info, &len);
4802 	close(fd);
4803 	return !err;
4804 }
4805 
4806 static int probe_perf_link(void)
4807 {
4808 	struct bpf_insn insns[] = {
4809 		BPF_MOV64_IMM(BPF_REG_0, 0),
4810 		BPF_EXIT_INSN(),
4811 	};
4812 	int prog_fd, link_fd, err;
4813 
4814 	prog_fd = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL",
4815 				insns, ARRAY_SIZE(insns), NULL);
4816 	if (prog_fd < 0)
4817 		return -errno;
4818 
4819 	/* use invalid perf_event FD to get EBADF, if link is supported;
4820 	 * otherwise EINVAL should be returned
4821 	 */
4822 	link_fd = bpf_link_create(prog_fd, -1, BPF_PERF_EVENT, NULL);
4823 	err = -errno; /* close() can clobber errno */
4824 
4825 	if (link_fd >= 0)
4826 		close(link_fd);
4827 	close(prog_fd);
4828 
4829 	return link_fd < 0 && err == -EBADF;
4830 }
4831 
4832 static int probe_kern_bpf_cookie(void)
4833 {
4834 	struct bpf_insn insns[] = {
4835 		BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_get_attach_cookie),
4836 		BPF_EXIT_INSN(),
4837 	};
4838 	int ret, insn_cnt = ARRAY_SIZE(insns);
4839 
4840 	ret = bpf_prog_load(BPF_PROG_TYPE_KPROBE, NULL, "GPL", insns, insn_cnt, NULL);
4841 	return probe_fd(ret);
4842 }
4843 
4844 static int probe_kern_btf_enum64(void)
4845 {
4846 	static const char strs[] = "\0enum64";
4847 	__u32 types[] = {
4848 		BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_ENUM64, 0, 0), 8),
4849 	};
4850 
4851 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4852 					     strs, sizeof(strs)));
4853 }
4854 
4855 static int probe_kern_syscall_wrapper(void);
4856 
4857 enum kern_feature_result {
4858 	FEAT_UNKNOWN = 0,
4859 	FEAT_SUPPORTED = 1,
4860 	FEAT_MISSING = 2,
4861 };
4862 
4863 typedef int (*feature_probe_fn)(void);
4864 
4865 static struct kern_feature_desc {
4866 	const char *desc;
4867 	feature_probe_fn probe;
4868 	enum kern_feature_result res;
4869 } feature_probes[__FEAT_CNT] = {
4870 	[FEAT_PROG_NAME] = {
4871 		"BPF program name", probe_kern_prog_name,
4872 	},
4873 	[FEAT_GLOBAL_DATA] = {
4874 		"global variables", probe_kern_global_data,
4875 	},
4876 	[FEAT_BTF] = {
4877 		"minimal BTF", probe_kern_btf,
4878 	},
4879 	[FEAT_BTF_FUNC] = {
4880 		"BTF functions", probe_kern_btf_func,
4881 	},
4882 	[FEAT_BTF_GLOBAL_FUNC] = {
4883 		"BTF global function", probe_kern_btf_func_global,
4884 	},
4885 	[FEAT_BTF_DATASEC] = {
4886 		"BTF data section and variable", probe_kern_btf_datasec,
4887 	},
4888 	[FEAT_ARRAY_MMAP] = {
4889 		"ARRAY map mmap()", probe_kern_array_mmap,
4890 	},
4891 	[FEAT_EXP_ATTACH_TYPE] = {
4892 		"BPF_PROG_LOAD expected_attach_type attribute",
4893 		probe_kern_exp_attach_type,
4894 	},
4895 	[FEAT_PROBE_READ_KERN] = {
4896 		"bpf_probe_read_kernel() helper", probe_kern_probe_read_kernel,
4897 	},
4898 	[FEAT_PROG_BIND_MAP] = {
4899 		"BPF_PROG_BIND_MAP support", probe_prog_bind_map,
4900 	},
4901 	[FEAT_MODULE_BTF] = {
4902 		"module BTF support", probe_module_btf,
4903 	},
4904 	[FEAT_BTF_FLOAT] = {
4905 		"BTF_KIND_FLOAT support", probe_kern_btf_float,
4906 	},
4907 	[FEAT_PERF_LINK] = {
4908 		"BPF perf link support", probe_perf_link,
4909 	},
4910 	[FEAT_BTF_DECL_TAG] = {
4911 		"BTF_KIND_DECL_TAG support", probe_kern_btf_decl_tag,
4912 	},
4913 	[FEAT_BTF_TYPE_TAG] = {
4914 		"BTF_KIND_TYPE_TAG support", probe_kern_btf_type_tag,
4915 	},
4916 	[FEAT_MEMCG_ACCOUNT] = {
4917 		"memcg-based memory accounting", probe_memcg_account,
4918 	},
4919 	[FEAT_BPF_COOKIE] = {
4920 		"BPF cookie support", probe_kern_bpf_cookie,
4921 	},
4922 	[FEAT_BTF_ENUM64] = {
4923 		"BTF_KIND_ENUM64 support", probe_kern_btf_enum64,
4924 	},
4925 	[FEAT_SYSCALL_WRAPPER] = {
4926 		"Kernel using syscall wrapper", probe_kern_syscall_wrapper,
4927 	},
4928 };
4929 
4930 bool kernel_supports(const struct bpf_object *obj, enum kern_feature_id feat_id)
4931 {
4932 	struct kern_feature_desc *feat = &feature_probes[feat_id];
4933 	int ret;
4934 
4935 	if (obj && obj->gen_loader)
4936 		/* To generate loader program assume the latest kernel
4937 		 * to avoid doing extra prog_load, map_create syscalls.
4938 		 */
4939 		return true;
4940 
4941 	if (READ_ONCE(feat->res) == FEAT_UNKNOWN) {
4942 		ret = feat->probe();
4943 		if (ret > 0) {
4944 			WRITE_ONCE(feat->res, FEAT_SUPPORTED);
4945 		} else if (ret == 0) {
4946 			WRITE_ONCE(feat->res, FEAT_MISSING);
4947 		} else {
4948 			pr_warn("Detection of kernel %s support failed: %d\n", feat->desc, ret);
4949 			WRITE_ONCE(feat->res, FEAT_MISSING);
4950 		}
4951 	}
4952 
4953 	return READ_ONCE(feat->res) == FEAT_SUPPORTED;
4954 }
4955 
4956 static bool map_is_reuse_compat(const struct bpf_map *map, int map_fd)
4957 {
4958 	struct bpf_map_info map_info;
4959 	char msg[STRERR_BUFSIZE];
4960 	__u32 map_info_len = sizeof(map_info);
4961 	int err;
4962 
4963 	memset(&map_info, 0, map_info_len);
4964 	err = bpf_map_get_info_by_fd(map_fd, &map_info, &map_info_len);
4965 	if (err && errno == EINVAL)
4966 		err = bpf_get_map_info_from_fdinfo(map_fd, &map_info);
4967 	if (err) {
4968 		pr_warn("failed to get map info for map FD %d: %s\n", map_fd,
4969 			libbpf_strerror_r(errno, msg, sizeof(msg)));
4970 		return false;
4971 	}
4972 
4973 	return (map_info.type == map->def.type &&
4974 		map_info.key_size == map->def.key_size &&
4975 		map_info.value_size == map->def.value_size &&
4976 		map_info.max_entries == map->def.max_entries &&
4977 		map_info.map_flags == map->def.map_flags &&
4978 		map_info.map_extra == map->map_extra);
4979 }
4980 
4981 static int
4982 bpf_object__reuse_map(struct bpf_map *map)
4983 {
4984 	char *cp, errmsg[STRERR_BUFSIZE];
4985 	int err, pin_fd;
4986 
4987 	pin_fd = bpf_obj_get(map->pin_path);
4988 	if (pin_fd < 0) {
4989 		err = -errno;
4990 		if (err == -ENOENT) {
4991 			pr_debug("found no pinned map to reuse at '%s'\n",
4992 				 map->pin_path);
4993 			return 0;
4994 		}
4995 
4996 		cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
4997 		pr_warn("couldn't retrieve pinned map '%s': %s\n",
4998 			map->pin_path, cp);
4999 		return err;
5000 	}
5001 
5002 	if (!map_is_reuse_compat(map, pin_fd)) {
5003 		pr_warn("couldn't reuse pinned map at '%s': parameter mismatch\n",
5004 			map->pin_path);
5005 		close(pin_fd);
5006 		return -EINVAL;
5007 	}
5008 
5009 	err = bpf_map__reuse_fd(map, pin_fd);
5010 	close(pin_fd);
5011 	if (err)
5012 		return err;
5013 
5014 	map->pinned = true;
5015 	pr_debug("reused pinned map at '%s'\n", map->pin_path);
5016 
5017 	return 0;
5018 }
5019 
5020 static int
5021 bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
5022 {
5023 	enum libbpf_map_type map_type = map->libbpf_type;
5024 	char *cp, errmsg[STRERR_BUFSIZE];
5025 	int err, zero = 0;
5026 
5027 	if (obj->gen_loader) {
5028 		bpf_gen__map_update_elem(obj->gen_loader, map - obj->maps,
5029 					 map->mmaped, map->def.value_size);
5030 		if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG)
5031 			bpf_gen__map_freeze(obj->gen_loader, map - obj->maps);
5032 		return 0;
5033 	}
5034 	err = bpf_map_update_elem(map->fd, &zero, map->mmaped, 0);
5035 	if (err) {
5036 		err = -errno;
5037 		cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5038 		pr_warn("Error setting initial map(%s) contents: %s\n",
5039 			map->name, cp);
5040 		return err;
5041 	}
5042 
5043 	/* Freeze .rodata and .kconfig map as read-only from syscall side. */
5044 	if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG) {
5045 		err = bpf_map_freeze(map->fd);
5046 		if (err) {
5047 			err = -errno;
5048 			cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5049 			pr_warn("Error freezing map(%s) as read-only: %s\n",
5050 				map->name, cp);
5051 			return err;
5052 		}
5053 	}
5054 	return 0;
5055 }
5056 
5057 static void bpf_map__destroy(struct bpf_map *map);
5058 
5059 static int bpf_object__create_map(struct bpf_object *obj, struct bpf_map *map, bool is_inner)
5060 {
5061 	LIBBPF_OPTS(bpf_map_create_opts, create_attr);
5062 	struct bpf_map_def *def = &map->def;
5063 	const char *map_name = NULL;
5064 	int err = 0;
5065 
5066 	if (kernel_supports(obj, FEAT_PROG_NAME))
5067 		map_name = map->name;
5068 	create_attr.map_ifindex = map->map_ifindex;
5069 	create_attr.map_flags = def->map_flags;
5070 	create_attr.numa_node = map->numa_node;
5071 	create_attr.map_extra = map->map_extra;
5072 
5073 	if (bpf_map__is_struct_ops(map))
5074 		create_attr.btf_vmlinux_value_type_id = map->btf_vmlinux_value_type_id;
5075 
5076 	if (obj->btf && btf__fd(obj->btf) >= 0) {
5077 		create_attr.btf_fd = btf__fd(obj->btf);
5078 		create_attr.btf_key_type_id = map->btf_key_type_id;
5079 		create_attr.btf_value_type_id = map->btf_value_type_id;
5080 	}
5081 
5082 	if (bpf_map_type__is_map_in_map(def->type)) {
5083 		if (map->inner_map) {
5084 			err = bpf_object__create_map(obj, map->inner_map, true);
5085 			if (err) {
5086 				pr_warn("map '%s': failed to create inner map: %d\n",
5087 					map->name, err);
5088 				return err;
5089 			}
5090 			map->inner_map_fd = bpf_map__fd(map->inner_map);
5091 		}
5092 		if (map->inner_map_fd >= 0)
5093 			create_attr.inner_map_fd = map->inner_map_fd;
5094 	}
5095 
5096 	switch (def->type) {
5097 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
5098 	case BPF_MAP_TYPE_CGROUP_ARRAY:
5099 	case BPF_MAP_TYPE_STACK_TRACE:
5100 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
5101 	case BPF_MAP_TYPE_HASH_OF_MAPS:
5102 	case BPF_MAP_TYPE_DEVMAP:
5103 	case BPF_MAP_TYPE_DEVMAP_HASH:
5104 	case BPF_MAP_TYPE_CPUMAP:
5105 	case BPF_MAP_TYPE_XSKMAP:
5106 	case BPF_MAP_TYPE_SOCKMAP:
5107 	case BPF_MAP_TYPE_SOCKHASH:
5108 	case BPF_MAP_TYPE_QUEUE:
5109 	case BPF_MAP_TYPE_STACK:
5110 		create_attr.btf_fd = 0;
5111 		create_attr.btf_key_type_id = 0;
5112 		create_attr.btf_value_type_id = 0;
5113 		map->btf_key_type_id = 0;
5114 		map->btf_value_type_id = 0;
5115 	default:
5116 		break;
5117 	}
5118 
5119 	if (obj->gen_loader) {
5120 		bpf_gen__map_create(obj->gen_loader, def->type, map_name,
5121 				    def->key_size, def->value_size, def->max_entries,
5122 				    &create_attr, is_inner ? -1 : map - obj->maps);
5123 		/* Pretend to have valid FD to pass various fd >= 0 checks.
5124 		 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
5125 		 */
5126 		map->fd = 0;
5127 	} else {
5128 		map->fd = bpf_map_create(def->type, map_name,
5129 					 def->key_size, def->value_size,
5130 					 def->max_entries, &create_attr);
5131 	}
5132 	if (map->fd < 0 && (create_attr.btf_key_type_id ||
5133 			    create_attr.btf_value_type_id)) {
5134 		char *cp, errmsg[STRERR_BUFSIZE];
5135 
5136 		err = -errno;
5137 		cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5138 		pr_warn("Error in bpf_create_map_xattr(%s):%s(%d). Retrying without BTF.\n",
5139 			map->name, cp, err);
5140 		create_attr.btf_fd = 0;
5141 		create_attr.btf_key_type_id = 0;
5142 		create_attr.btf_value_type_id = 0;
5143 		map->btf_key_type_id = 0;
5144 		map->btf_value_type_id = 0;
5145 		map->fd = bpf_map_create(def->type, map_name,
5146 					 def->key_size, def->value_size,
5147 					 def->max_entries, &create_attr);
5148 	}
5149 
5150 	err = map->fd < 0 ? -errno : 0;
5151 
5152 	if (bpf_map_type__is_map_in_map(def->type) && map->inner_map) {
5153 		if (obj->gen_loader)
5154 			map->inner_map->fd = -1;
5155 		bpf_map__destroy(map->inner_map);
5156 		zfree(&map->inner_map);
5157 	}
5158 
5159 	return err;
5160 }
5161 
5162 static int init_map_in_map_slots(struct bpf_object *obj, struct bpf_map *map)
5163 {
5164 	const struct bpf_map *targ_map;
5165 	unsigned int i;
5166 	int fd, err = 0;
5167 
5168 	for (i = 0; i < map->init_slots_sz; i++) {
5169 		if (!map->init_slots[i])
5170 			continue;
5171 
5172 		targ_map = map->init_slots[i];
5173 		fd = bpf_map__fd(targ_map);
5174 
5175 		if (obj->gen_loader) {
5176 			bpf_gen__populate_outer_map(obj->gen_loader,
5177 						    map - obj->maps, i,
5178 						    targ_map - obj->maps);
5179 		} else {
5180 			err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5181 		}
5182 		if (err) {
5183 			err = -errno;
5184 			pr_warn("map '%s': failed to initialize slot [%d] to map '%s' fd=%d: %d\n",
5185 				map->name, i, targ_map->name, fd, err);
5186 			return err;
5187 		}
5188 		pr_debug("map '%s': slot [%d] set to map '%s' fd=%d\n",
5189 			 map->name, i, targ_map->name, fd);
5190 	}
5191 
5192 	zfree(&map->init_slots);
5193 	map->init_slots_sz = 0;
5194 
5195 	return 0;
5196 }
5197 
5198 static int init_prog_array_slots(struct bpf_object *obj, struct bpf_map *map)
5199 {
5200 	const struct bpf_program *targ_prog;
5201 	unsigned int i;
5202 	int fd, err;
5203 
5204 	if (obj->gen_loader)
5205 		return -ENOTSUP;
5206 
5207 	for (i = 0; i < map->init_slots_sz; i++) {
5208 		if (!map->init_slots[i])
5209 			continue;
5210 
5211 		targ_prog = map->init_slots[i];
5212 		fd = bpf_program__fd(targ_prog);
5213 
5214 		err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5215 		if (err) {
5216 			err = -errno;
5217 			pr_warn("map '%s': failed to initialize slot [%d] to prog '%s' fd=%d: %d\n",
5218 				map->name, i, targ_prog->name, fd, err);
5219 			return err;
5220 		}
5221 		pr_debug("map '%s': slot [%d] set to prog '%s' fd=%d\n",
5222 			 map->name, i, targ_prog->name, fd);
5223 	}
5224 
5225 	zfree(&map->init_slots);
5226 	map->init_slots_sz = 0;
5227 
5228 	return 0;
5229 }
5230 
5231 static int bpf_object_init_prog_arrays(struct bpf_object *obj)
5232 {
5233 	struct bpf_map *map;
5234 	int i, err;
5235 
5236 	for (i = 0; i < obj->nr_maps; i++) {
5237 		map = &obj->maps[i];
5238 
5239 		if (!map->init_slots_sz || map->def.type != BPF_MAP_TYPE_PROG_ARRAY)
5240 			continue;
5241 
5242 		err = init_prog_array_slots(obj, map);
5243 		if (err < 0) {
5244 			zclose(map->fd);
5245 			return err;
5246 		}
5247 	}
5248 	return 0;
5249 }
5250 
5251 static int map_set_def_max_entries(struct bpf_map *map)
5252 {
5253 	if (map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY && !map->def.max_entries) {
5254 		int nr_cpus;
5255 
5256 		nr_cpus = libbpf_num_possible_cpus();
5257 		if (nr_cpus < 0) {
5258 			pr_warn("map '%s': failed to determine number of system CPUs: %d\n",
5259 				map->name, nr_cpus);
5260 			return nr_cpus;
5261 		}
5262 		pr_debug("map '%s': setting size to %d\n", map->name, nr_cpus);
5263 		map->def.max_entries = nr_cpus;
5264 	}
5265 
5266 	return 0;
5267 }
5268 
5269 static int
5270 bpf_object__create_maps(struct bpf_object *obj)
5271 {
5272 	struct bpf_map *map;
5273 	char *cp, errmsg[STRERR_BUFSIZE];
5274 	unsigned int i, j;
5275 	int err;
5276 	bool retried;
5277 
5278 	for (i = 0; i < obj->nr_maps; i++) {
5279 		map = &obj->maps[i];
5280 
5281 		/* To support old kernels, we skip creating global data maps
5282 		 * (.rodata, .data, .kconfig, etc); later on, during program
5283 		 * loading, if we detect that at least one of the to-be-loaded
5284 		 * programs is referencing any global data map, we'll error
5285 		 * out with program name and relocation index logged.
5286 		 * This approach allows to accommodate Clang emitting
5287 		 * unnecessary .rodata.str1.1 sections for string literals,
5288 		 * but also it allows to have CO-RE applications that use
5289 		 * global variables in some of BPF programs, but not others.
5290 		 * If those global variable-using programs are not loaded at
5291 		 * runtime due to bpf_program__set_autoload(prog, false),
5292 		 * bpf_object loading will succeed just fine even on old
5293 		 * kernels.
5294 		 */
5295 		if (bpf_map__is_internal(map) && !kernel_supports(obj, FEAT_GLOBAL_DATA))
5296 			map->autocreate = false;
5297 
5298 		if (!map->autocreate) {
5299 			pr_debug("map '%s': skipped auto-creating...\n", map->name);
5300 			continue;
5301 		}
5302 
5303 		err = map_set_def_max_entries(map);
5304 		if (err)
5305 			goto err_out;
5306 
5307 		retried = false;
5308 retry:
5309 		if (map->pin_path) {
5310 			err = bpf_object__reuse_map(map);
5311 			if (err) {
5312 				pr_warn("map '%s': error reusing pinned map\n",
5313 					map->name);
5314 				goto err_out;
5315 			}
5316 			if (retried && map->fd < 0) {
5317 				pr_warn("map '%s': cannot find pinned map\n",
5318 					map->name);
5319 				err = -ENOENT;
5320 				goto err_out;
5321 			}
5322 		}
5323 
5324 		if (map->fd >= 0) {
5325 			pr_debug("map '%s': skipping creation (preset fd=%d)\n",
5326 				 map->name, map->fd);
5327 		} else {
5328 			err = bpf_object__create_map(obj, map, false);
5329 			if (err)
5330 				goto err_out;
5331 
5332 			pr_debug("map '%s': created successfully, fd=%d\n",
5333 				 map->name, map->fd);
5334 
5335 			if (bpf_map__is_internal(map)) {
5336 				err = bpf_object__populate_internal_map(obj, map);
5337 				if (err < 0) {
5338 					zclose(map->fd);
5339 					goto err_out;
5340 				}
5341 			}
5342 
5343 			if (map->init_slots_sz && map->def.type != BPF_MAP_TYPE_PROG_ARRAY) {
5344 				err = init_map_in_map_slots(obj, map);
5345 				if (err < 0) {
5346 					zclose(map->fd);
5347 					goto err_out;
5348 				}
5349 			}
5350 		}
5351 
5352 		if (map->pin_path && !map->pinned) {
5353 			err = bpf_map__pin(map, NULL);
5354 			if (err) {
5355 				zclose(map->fd);
5356 				if (!retried && err == -EEXIST) {
5357 					retried = true;
5358 					goto retry;
5359 				}
5360 				pr_warn("map '%s': failed to auto-pin at '%s': %d\n",
5361 					map->name, map->pin_path, err);
5362 				goto err_out;
5363 			}
5364 		}
5365 	}
5366 
5367 	return 0;
5368 
5369 err_out:
5370 	cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5371 	pr_warn("map '%s': failed to create: %s(%d)\n", map->name, cp, err);
5372 	pr_perm_msg(err);
5373 	for (j = 0; j < i; j++)
5374 		zclose(obj->maps[j].fd);
5375 	return err;
5376 }
5377 
5378 static bool bpf_core_is_flavor_sep(const char *s)
5379 {
5380 	/* check X___Y name pattern, where X and Y are not underscores */
5381 	return s[0] != '_' &&				      /* X */
5382 	       s[1] == '_' && s[2] == '_' && s[3] == '_' &&   /* ___ */
5383 	       s[4] != '_';				      /* Y */
5384 }
5385 
5386 /* Given 'some_struct_name___with_flavor' return the length of a name prefix
5387  * before last triple underscore. Struct name part after last triple
5388  * underscore is ignored by BPF CO-RE relocation during relocation matching.
5389  */
5390 size_t bpf_core_essential_name_len(const char *name)
5391 {
5392 	size_t n = strlen(name);
5393 	int i;
5394 
5395 	for (i = n - 5; i >= 0; i--) {
5396 		if (bpf_core_is_flavor_sep(name + i))
5397 			return i + 1;
5398 	}
5399 	return n;
5400 }
5401 
5402 void bpf_core_free_cands(struct bpf_core_cand_list *cands)
5403 {
5404 	if (!cands)
5405 		return;
5406 
5407 	free(cands->cands);
5408 	free(cands);
5409 }
5410 
5411 int bpf_core_add_cands(struct bpf_core_cand *local_cand,
5412 		       size_t local_essent_len,
5413 		       const struct btf *targ_btf,
5414 		       const char *targ_btf_name,
5415 		       int targ_start_id,
5416 		       struct bpf_core_cand_list *cands)
5417 {
5418 	struct bpf_core_cand *new_cands, *cand;
5419 	const struct btf_type *t, *local_t;
5420 	const char *targ_name, *local_name;
5421 	size_t targ_essent_len;
5422 	int n, i;
5423 
5424 	local_t = btf__type_by_id(local_cand->btf, local_cand->id);
5425 	local_name = btf__str_by_offset(local_cand->btf, local_t->name_off);
5426 
5427 	n = btf__type_cnt(targ_btf);
5428 	for (i = targ_start_id; i < n; i++) {
5429 		t = btf__type_by_id(targ_btf, i);
5430 		if (!btf_kind_core_compat(t, local_t))
5431 			continue;
5432 
5433 		targ_name = btf__name_by_offset(targ_btf, t->name_off);
5434 		if (str_is_empty(targ_name))
5435 			continue;
5436 
5437 		targ_essent_len = bpf_core_essential_name_len(targ_name);
5438 		if (targ_essent_len != local_essent_len)
5439 			continue;
5440 
5441 		if (strncmp(local_name, targ_name, local_essent_len) != 0)
5442 			continue;
5443 
5444 		pr_debug("CO-RE relocating [%d] %s %s: found target candidate [%d] %s %s in [%s]\n",
5445 			 local_cand->id, btf_kind_str(local_t),
5446 			 local_name, i, btf_kind_str(t), targ_name,
5447 			 targ_btf_name);
5448 		new_cands = libbpf_reallocarray(cands->cands, cands->len + 1,
5449 					      sizeof(*cands->cands));
5450 		if (!new_cands)
5451 			return -ENOMEM;
5452 
5453 		cand = &new_cands[cands->len];
5454 		cand->btf = targ_btf;
5455 		cand->id = i;
5456 
5457 		cands->cands = new_cands;
5458 		cands->len++;
5459 	}
5460 	return 0;
5461 }
5462 
5463 static int load_module_btfs(struct bpf_object *obj)
5464 {
5465 	struct bpf_btf_info info;
5466 	struct module_btf *mod_btf;
5467 	struct btf *btf;
5468 	char name[64];
5469 	__u32 id = 0, len;
5470 	int err, fd;
5471 
5472 	if (obj->btf_modules_loaded)
5473 		return 0;
5474 
5475 	if (obj->gen_loader)
5476 		return 0;
5477 
5478 	/* don't do this again, even if we find no module BTFs */
5479 	obj->btf_modules_loaded = true;
5480 
5481 	/* kernel too old to support module BTFs */
5482 	if (!kernel_supports(obj, FEAT_MODULE_BTF))
5483 		return 0;
5484 
5485 	while (true) {
5486 		err = bpf_btf_get_next_id(id, &id);
5487 		if (err && errno == ENOENT)
5488 			return 0;
5489 		if (err && errno == EPERM) {
5490 			pr_debug("skipping module BTFs loading, missing privileges\n");
5491 			return 0;
5492 		}
5493 		if (err) {
5494 			err = -errno;
5495 			pr_warn("failed to iterate BTF objects: %d\n", err);
5496 			return err;
5497 		}
5498 
5499 		fd = bpf_btf_get_fd_by_id(id);
5500 		if (fd < 0) {
5501 			if (errno == ENOENT)
5502 				continue; /* expected race: BTF was unloaded */
5503 			err = -errno;
5504 			pr_warn("failed to get BTF object #%d FD: %d\n", id, err);
5505 			return err;
5506 		}
5507 
5508 		len = sizeof(info);
5509 		memset(&info, 0, sizeof(info));
5510 		info.name = ptr_to_u64(name);
5511 		info.name_len = sizeof(name);
5512 
5513 		err = bpf_btf_get_info_by_fd(fd, &info, &len);
5514 		if (err) {
5515 			err = -errno;
5516 			pr_warn("failed to get BTF object #%d info: %d\n", id, err);
5517 			goto err_out;
5518 		}
5519 
5520 		/* ignore non-module BTFs */
5521 		if (!info.kernel_btf || strcmp(name, "vmlinux") == 0) {
5522 			close(fd);
5523 			continue;
5524 		}
5525 
5526 		btf = btf_get_from_fd(fd, obj->btf_vmlinux);
5527 		err = libbpf_get_error(btf);
5528 		if (err) {
5529 			pr_warn("failed to load module [%s]'s BTF object #%d: %d\n",
5530 				name, id, err);
5531 			goto err_out;
5532 		}
5533 
5534 		err = libbpf_ensure_mem((void **)&obj->btf_modules, &obj->btf_module_cap,
5535 					sizeof(*obj->btf_modules), obj->btf_module_cnt + 1);
5536 		if (err)
5537 			goto err_out;
5538 
5539 		mod_btf = &obj->btf_modules[obj->btf_module_cnt++];
5540 
5541 		mod_btf->btf = btf;
5542 		mod_btf->id = id;
5543 		mod_btf->fd = fd;
5544 		mod_btf->name = strdup(name);
5545 		if (!mod_btf->name) {
5546 			err = -ENOMEM;
5547 			goto err_out;
5548 		}
5549 		continue;
5550 
5551 err_out:
5552 		close(fd);
5553 		return err;
5554 	}
5555 
5556 	return 0;
5557 }
5558 
5559 static struct bpf_core_cand_list *
5560 bpf_core_find_cands(struct bpf_object *obj, const struct btf *local_btf, __u32 local_type_id)
5561 {
5562 	struct bpf_core_cand local_cand = {};
5563 	struct bpf_core_cand_list *cands;
5564 	const struct btf *main_btf;
5565 	const struct btf_type *local_t;
5566 	const char *local_name;
5567 	size_t local_essent_len;
5568 	int err, i;
5569 
5570 	local_cand.btf = local_btf;
5571 	local_cand.id = local_type_id;
5572 	local_t = btf__type_by_id(local_btf, local_type_id);
5573 	if (!local_t)
5574 		return ERR_PTR(-EINVAL);
5575 
5576 	local_name = btf__name_by_offset(local_btf, local_t->name_off);
5577 	if (str_is_empty(local_name))
5578 		return ERR_PTR(-EINVAL);
5579 	local_essent_len = bpf_core_essential_name_len(local_name);
5580 
5581 	cands = calloc(1, sizeof(*cands));
5582 	if (!cands)
5583 		return ERR_PTR(-ENOMEM);
5584 
5585 	/* Attempt to find target candidates in vmlinux BTF first */
5586 	main_btf = obj->btf_vmlinux_override ?: obj->btf_vmlinux;
5587 	err = bpf_core_add_cands(&local_cand, local_essent_len, main_btf, "vmlinux", 1, cands);
5588 	if (err)
5589 		goto err_out;
5590 
5591 	/* if vmlinux BTF has any candidate, don't got for module BTFs */
5592 	if (cands->len)
5593 		return cands;
5594 
5595 	/* if vmlinux BTF was overridden, don't attempt to load module BTFs */
5596 	if (obj->btf_vmlinux_override)
5597 		return cands;
5598 
5599 	/* now look through module BTFs, trying to still find candidates */
5600 	err = load_module_btfs(obj);
5601 	if (err)
5602 		goto err_out;
5603 
5604 	for (i = 0; i < obj->btf_module_cnt; i++) {
5605 		err = bpf_core_add_cands(&local_cand, local_essent_len,
5606 					 obj->btf_modules[i].btf,
5607 					 obj->btf_modules[i].name,
5608 					 btf__type_cnt(obj->btf_vmlinux),
5609 					 cands);
5610 		if (err)
5611 			goto err_out;
5612 	}
5613 
5614 	return cands;
5615 err_out:
5616 	bpf_core_free_cands(cands);
5617 	return ERR_PTR(err);
5618 }
5619 
5620 /* Check local and target types for compatibility. This check is used for
5621  * type-based CO-RE relocations and follow slightly different rules than
5622  * field-based relocations. This function assumes that root types were already
5623  * checked for name match. Beyond that initial root-level name check, names
5624  * are completely ignored. Compatibility rules are as follows:
5625  *   - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs are considered compatible, but
5626  *     kind should match for local and target types (i.e., STRUCT is not
5627  *     compatible with UNION);
5628  *   - for ENUMs, the size is ignored;
5629  *   - for INT, size and signedness are ignored;
5630  *   - for ARRAY, dimensionality is ignored, element types are checked for
5631  *     compatibility recursively;
5632  *   - CONST/VOLATILE/RESTRICT modifiers are ignored;
5633  *   - TYPEDEFs/PTRs are compatible if types they pointing to are compatible;
5634  *   - FUNC_PROTOs are compatible if they have compatible signature: same
5635  *     number of input args and compatible return and argument types.
5636  * These rules are not set in stone and probably will be adjusted as we get
5637  * more experience with using BPF CO-RE relocations.
5638  */
5639 int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
5640 			      const struct btf *targ_btf, __u32 targ_id)
5641 {
5642 	return __bpf_core_types_are_compat(local_btf, local_id, targ_btf, targ_id, 32);
5643 }
5644 
5645 int bpf_core_types_match(const struct btf *local_btf, __u32 local_id,
5646 			 const struct btf *targ_btf, __u32 targ_id)
5647 {
5648 	return __bpf_core_types_match(local_btf, local_id, targ_btf, targ_id, false, 32);
5649 }
5650 
5651 static size_t bpf_core_hash_fn(const long key, void *ctx)
5652 {
5653 	return key;
5654 }
5655 
5656 static bool bpf_core_equal_fn(const long k1, const long k2, void *ctx)
5657 {
5658 	return k1 == k2;
5659 }
5660 
5661 static int record_relo_core(struct bpf_program *prog,
5662 			    const struct bpf_core_relo *core_relo, int insn_idx)
5663 {
5664 	struct reloc_desc *relos, *relo;
5665 
5666 	relos = libbpf_reallocarray(prog->reloc_desc,
5667 				    prog->nr_reloc + 1, sizeof(*relos));
5668 	if (!relos)
5669 		return -ENOMEM;
5670 	relo = &relos[prog->nr_reloc];
5671 	relo->type = RELO_CORE;
5672 	relo->insn_idx = insn_idx;
5673 	relo->core_relo = core_relo;
5674 	prog->reloc_desc = relos;
5675 	prog->nr_reloc++;
5676 	return 0;
5677 }
5678 
5679 static const struct bpf_core_relo *find_relo_core(struct bpf_program *prog, int insn_idx)
5680 {
5681 	struct reloc_desc *relo;
5682 	int i;
5683 
5684 	for (i = 0; i < prog->nr_reloc; i++) {
5685 		relo = &prog->reloc_desc[i];
5686 		if (relo->type != RELO_CORE || relo->insn_idx != insn_idx)
5687 			continue;
5688 
5689 		return relo->core_relo;
5690 	}
5691 
5692 	return NULL;
5693 }
5694 
5695 static int bpf_core_resolve_relo(struct bpf_program *prog,
5696 				 const struct bpf_core_relo *relo,
5697 				 int relo_idx,
5698 				 const struct btf *local_btf,
5699 				 struct hashmap *cand_cache,
5700 				 struct bpf_core_relo_res *targ_res)
5701 {
5702 	struct bpf_core_spec specs_scratch[3] = {};
5703 	struct bpf_core_cand_list *cands = NULL;
5704 	const char *prog_name = prog->name;
5705 	const struct btf_type *local_type;
5706 	const char *local_name;
5707 	__u32 local_id = relo->type_id;
5708 	int err;
5709 
5710 	local_type = btf__type_by_id(local_btf, local_id);
5711 	if (!local_type)
5712 		return -EINVAL;
5713 
5714 	local_name = btf__name_by_offset(local_btf, local_type->name_off);
5715 	if (!local_name)
5716 		return -EINVAL;
5717 
5718 	if (relo->kind != BPF_CORE_TYPE_ID_LOCAL &&
5719 	    !hashmap__find(cand_cache, local_id, &cands)) {
5720 		cands = bpf_core_find_cands(prog->obj, local_btf, local_id);
5721 		if (IS_ERR(cands)) {
5722 			pr_warn("prog '%s': relo #%d: target candidate search failed for [%d] %s %s: %ld\n",
5723 				prog_name, relo_idx, local_id, btf_kind_str(local_type),
5724 				local_name, PTR_ERR(cands));
5725 			return PTR_ERR(cands);
5726 		}
5727 		err = hashmap__set(cand_cache, local_id, cands, NULL, NULL);
5728 		if (err) {
5729 			bpf_core_free_cands(cands);
5730 			return err;
5731 		}
5732 	}
5733 
5734 	return bpf_core_calc_relo_insn(prog_name, relo, relo_idx, local_btf, cands, specs_scratch,
5735 				       targ_res);
5736 }
5737 
5738 static int
5739 bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
5740 {
5741 	const struct btf_ext_info_sec *sec;
5742 	struct bpf_core_relo_res targ_res;
5743 	const struct bpf_core_relo *rec;
5744 	const struct btf_ext_info *seg;
5745 	struct hashmap_entry *entry;
5746 	struct hashmap *cand_cache = NULL;
5747 	struct bpf_program *prog;
5748 	struct bpf_insn *insn;
5749 	const char *sec_name;
5750 	int i, err = 0, insn_idx, sec_idx, sec_num;
5751 
5752 	if (obj->btf_ext->core_relo_info.len == 0)
5753 		return 0;
5754 
5755 	if (targ_btf_path) {
5756 		obj->btf_vmlinux_override = btf__parse(targ_btf_path, NULL);
5757 		err = libbpf_get_error(obj->btf_vmlinux_override);
5758 		if (err) {
5759 			pr_warn("failed to parse target BTF: %d\n", err);
5760 			return err;
5761 		}
5762 	}
5763 
5764 	cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
5765 	if (IS_ERR(cand_cache)) {
5766 		err = PTR_ERR(cand_cache);
5767 		goto out;
5768 	}
5769 
5770 	seg = &obj->btf_ext->core_relo_info;
5771 	sec_num = 0;
5772 	for_each_btf_ext_sec(seg, sec) {
5773 		sec_idx = seg->sec_idxs[sec_num];
5774 		sec_num++;
5775 
5776 		sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
5777 		if (str_is_empty(sec_name)) {
5778 			err = -EINVAL;
5779 			goto out;
5780 		}
5781 
5782 		pr_debug("sec '%s': found %d CO-RE relocations\n", sec_name, sec->num_info);
5783 
5784 		for_each_btf_ext_rec(seg, sec, i, rec) {
5785 			if (rec->insn_off % BPF_INSN_SZ)
5786 				return -EINVAL;
5787 			insn_idx = rec->insn_off / BPF_INSN_SZ;
5788 			prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
5789 			if (!prog) {
5790 				/* When __weak subprog is "overridden" by another instance
5791 				 * of the subprog from a different object file, linker still
5792 				 * appends all the .BTF.ext info that used to belong to that
5793 				 * eliminated subprogram.
5794 				 * This is similar to what x86-64 linker does for relocations.
5795 				 * So just ignore such relocations just like we ignore
5796 				 * subprog instructions when discovering subprograms.
5797 				 */
5798 				pr_debug("sec '%s': skipping CO-RE relocation #%d for insn #%d belonging to eliminated weak subprogram\n",
5799 					 sec_name, i, insn_idx);
5800 				continue;
5801 			}
5802 			/* no need to apply CO-RE relocation if the program is
5803 			 * not going to be loaded
5804 			 */
5805 			if (!prog->autoload)
5806 				continue;
5807 
5808 			/* adjust insn_idx from section frame of reference to the local
5809 			 * program's frame of reference; (sub-)program code is not yet
5810 			 * relocated, so it's enough to just subtract in-section offset
5811 			 */
5812 			insn_idx = insn_idx - prog->sec_insn_off;
5813 			if (insn_idx >= prog->insns_cnt)
5814 				return -EINVAL;
5815 			insn = &prog->insns[insn_idx];
5816 
5817 			err = record_relo_core(prog, rec, insn_idx);
5818 			if (err) {
5819 				pr_warn("prog '%s': relo #%d: failed to record relocation: %d\n",
5820 					prog->name, i, err);
5821 				goto out;
5822 			}
5823 
5824 			if (prog->obj->gen_loader)
5825 				continue;
5826 
5827 			err = bpf_core_resolve_relo(prog, rec, i, obj->btf, cand_cache, &targ_res);
5828 			if (err) {
5829 				pr_warn("prog '%s': relo #%d: failed to relocate: %d\n",
5830 					prog->name, i, err);
5831 				goto out;
5832 			}
5833 
5834 			err = bpf_core_patch_insn(prog->name, insn, insn_idx, rec, i, &targ_res);
5835 			if (err) {
5836 				pr_warn("prog '%s': relo #%d: failed to patch insn #%u: %d\n",
5837 					prog->name, i, insn_idx, err);
5838 				goto out;
5839 			}
5840 		}
5841 	}
5842 
5843 out:
5844 	/* obj->btf_vmlinux and module BTFs are freed after object load */
5845 	btf__free(obj->btf_vmlinux_override);
5846 	obj->btf_vmlinux_override = NULL;
5847 
5848 	if (!IS_ERR_OR_NULL(cand_cache)) {
5849 		hashmap__for_each_entry(cand_cache, entry, i) {
5850 			bpf_core_free_cands(entry->pvalue);
5851 		}
5852 		hashmap__free(cand_cache);
5853 	}
5854 	return err;
5855 }
5856 
5857 /* base map load ldimm64 special constant, used also for log fixup logic */
5858 #define POISON_LDIMM64_MAP_BASE 2001000000
5859 #define POISON_LDIMM64_MAP_PFX "200100"
5860 
5861 static void poison_map_ldimm64(struct bpf_program *prog, int relo_idx,
5862 			       int insn_idx, struct bpf_insn *insn,
5863 			       int map_idx, const struct bpf_map *map)
5864 {
5865 	int i;
5866 
5867 	pr_debug("prog '%s': relo #%d: poisoning insn #%d that loads map #%d '%s'\n",
5868 		 prog->name, relo_idx, insn_idx, map_idx, map->name);
5869 
5870 	/* we turn single ldimm64 into two identical invalid calls */
5871 	for (i = 0; i < 2; i++) {
5872 		insn->code = BPF_JMP | BPF_CALL;
5873 		insn->dst_reg = 0;
5874 		insn->src_reg = 0;
5875 		insn->off = 0;
5876 		/* if this instruction is reachable (not a dead code),
5877 		 * verifier will complain with something like:
5878 		 * invalid func unknown#2001000123
5879 		 * where lower 123 is map index into obj->maps[] array
5880 		 */
5881 		insn->imm = POISON_LDIMM64_MAP_BASE + map_idx;
5882 
5883 		insn++;
5884 	}
5885 }
5886 
5887 /* unresolved kfunc call special constant, used also for log fixup logic */
5888 #define POISON_CALL_KFUNC_BASE 2002000000
5889 #define POISON_CALL_KFUNC_PFX "2002"
5890 
5891 static void poison_kfunc_call(struct bpf_program *prog, int relo_idx,
5892 			      int insn_idx, struct bpf_insn *insn,
5893 			      int ext_idx, const struct extern_desc *ext)
5894 {
5895 	pr_debug("prog '%s': relo #%d: poisoning insn #%d that calls kfunc '%s'\n",
5896 		 prog->name, relo_idx, insn_idx, ext->name);
5897 
5898 	/* we turn kfunc call into invalid helper call with identifiable constant */
5899 	insn->code = BPF_JMP | BPF_CALL;
5900 	insn->dst_reg = 0;
5901 	insn->src_reg = 0;
5902 	insn->off = 0;
5903 	/* if this instruction is reachable (not a dead code),
5904 	 * verifier will complain with something like:
5905 	 * invalid func unknown#2001000123
5906 	 * where lower 123 is extern index into obj->externs[] array
5907 	 */
5908 	insn->imm = POISON_CALL_KFUNC_BASE + ext_idx;
5909 }
5910 
5911 /* Relocate data references within program code:
5912  *  - map references;
5913  *  - global variable references;
5914  *  - extern references.
5915  */
5916 static int
5917 bpf_object__relocate_data(struct bpf_object *obj, struct bpf_program *prog)
5918 {
5919 	int i;
5920 
5921 	for (i = 0; i < prog->nr_reloc; i++) {
5922 		struct reloc_desc *relo = &prog->reloc_desc[i];
5923 		struct bpf_insn *insn = &prog->insns[relo->insn_idx];
5924 		const struct bpf_map *map;
5925 		struct extern_desc *ext;
5926 
5927 		switch (relo->type) {
5928 		case RELO_LD64:
5929 			map = &obj->maps[relo->map_idx];
5930 			if (obj->gen_loader) {
5931 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX;
5932 				insn[0].imm = relo->map_idx;
5933 			} else if (map->autocreate) {
5934 				insn[0].src_reg = BPF_PSEUDO_MAP_FD;
5935 				insn[0].imm = map->fd;
5936 			} else {
5937 				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
5938 						   relo->map_idx, map);
5939 			}
5940 			break;
5941 		case RELO_DATA:
5942 			map = &obj->maps[relo->map_idx];
5943 			insn[1].imm = insn[0].imm + relo->sym_off;
5944 			if (obj->gen_loader) {
5945 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
5946 				insn[0].imm = relo->map_idx;
5947 			} else if (map->autocreate) {
5948 				insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
5949 				insn[0].imm = map->fd;
5950 			} else {
5951 				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
5952 						   relo->map_idx, map);
5953 			}
5954 			break;
5955 		case RELO_EXTERN_LD64:
5956 			ext = &obj->externs[relo->ext_idx];
5957 			if (ext->type == EXT_KCFG) {
5958 				if (obj->gen_loader) {
5959 					insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
5960 					insn[0].imm = obj->kconfig_map_idx;
5961 				} else {
5962 					insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
5963 					insn[0].imm = obj->maps[obj->kconfig_map_idx].fd;
5964 				}
5965 				insn[1].imm = ext->kcfg.data_off;
5966 			} else /* EXT_KSYM */ {
5967 				if (ext->ksym.type_id && ext->is_set) { /* typed ksyms */
5968 					insn[0].src_reg = BPF_PSEUDO_BTF_ID;
5969 					insn[0].imm = ext->ksym.kernel_btf_id;
5970 					insn[1].imm = ext->ksym.kernel_btf_obj_fd;
5971 				} else { /* typeless ksyms or unresolved typed ksyms */
5972 					insn[0].imm = (__u32)ext->ksym.addr;
5973 					insn[1].imm = ext->ksym.addr >> 32;
5974 				}
5975 			}
5976 			break;
5977 		case RELO_EXTERN_CALL:
5978 			ext = &obj->externs[relo->ext_idx];
5979 			insn[0].src_reg = BPF_PSEUDO_KFUNC_CALL;
5980 			if (ext->is_set) {
5981 				insn[0].imm = ext->ksym.kernel_btf_id;
5982 				insn[0].off = ext->ksym.btf_fd_idx;
5983 			} else { /* unresolved weak kfunc call */
5984 				poison_kfunc_call(prog, i, relo->insn_idx, insn,
5985 						  relo->ext_idx, ext);
5986 			}
5987 			break;
5988 		case RELO_SUBPROG_ADDR:
5989 			if (insn[0].src_reg != BPF_PSEUDO_FUNC) {
5990 				pr_warn("prog '%s': relo #%d: bad insn\n",
5991 					prog->name, i);
5992 				return -EINVAL;
5993 			}
5994 			/* handled already */
5995 			break;
5996 		case RELO_CALL:
5997 			/* handled already */
5998 			break;
5999 		case RELO_CORE:
6000 			/* will be handled by bpf_program_record_relos() */
6001 			break;
6002 		default:
6003 			pr_warn("prog '%s': relo #%d: bad relo type %d\n",
6004 				prog->name, i, relo->type);
6005 			return -EINVAL;
6006 		}
6007 	}
6008 
6009 	return 0;
6010 }
6011 
6012 static int adjust_prog_btf_ext_info(const struct bpf_object *obj,
6013 				    const struct bpf_program *prog,
6014 				    const struct btf_ext_info *ext_info,
6015 				    void **prog_info, __u32 *prog_rec_cnt,
6016 				    __u32 *prog_rec_sz)
6017 {
6018 	void *copy_start = NULL, *copy_end = NULL;
6019 	void *rec, *rec_end, *new_prog_info;
6020 	const struct btf_ext_info_sec *sec;
6021 	size_t old_sz, new_sz;
6022 	int i, sec_num, sec_idx, off_adj;
6023 
6024 	sec_num = 0;
6025 	for_each_btf_ext_sec(ext_info, sec) {
6026 		sec_idx = ext_info->sec_idxs[sec_num];
6027 		sec_num++;
6028 		if (prog->sec_idx != sec_idx)
6029 			continue;
6030 
6031 		for_each_btf_ext_rec(ext_info, sec, i, rec) {
6032 			__u32 insn_off = *(__u32 *)rec / BPF_INSN_SZ;
6033 
6034 			if (insn_off < prog->sec_insn_off)
6035 				continue;
6036 			if (insn_off >= prog->sec_insn_off + prog->sec_insn_cnt)
6037 				break;
6038 
6039 			if (!copy_start)
6040 				copy_start = rec;
6041 			copy_end = rec + ext_info->rec_size;
6042 		}
6043 
6044 		if (!copy_start)
6045 			return -ENOENT;
6046 
6047 		/* append func/line info of a given (sub-)program to the main
6048 		 * program func/line info
6049 		 */
6050 		old_sz = (size_t)(*prog_rec_cnt) * ext_info->rec_size;
6051 		new_sz = old_sz + (copy_end - copy_start);
6052 		new_prog_info = realloc(*prog_info, new_sz);
6053 		if (!new_prog_info)
6054 			return -ENOMEM;
6055 		*prog_info = new_prog_info;
6056 		*prog_rec_cnt = new_sz / ext_info->rec_size;
6057 		memcpy(new_prog_info + old_sz, copy_start, copy_end - copy_start);
6058 
6059 		/* Kernel instruction offsets are in units of 8-byte
6060 		 * instructions, while .BTF.ext instruction offsets generated
6061 		 * by Clang are in units of bytes. So convert Clang offsets
6062 		 * into kernel offsets and adjust offset according to program
6063 		 * relocated position.
6064 		 */
6065 		off_adj = prog->sub_insn_off - prog->sec_insn_off;
6066 		rec = new_prog_info + old_sz;
6067 		rec_end = new_prog_info + new_sz;
6068 		for (; rec < rec_end; rec += ext_info->rec_size) {
6069 			__u32 *insn_off = rec;
6070 
6071 			*insn_off = *insn_off / BPF_INSN_SZ + off_adj;
6072 		}
6073 		*prog_rec_sz = ext_info->rec_size;
6074 		return 0;
6075 	}
6076 
6077 	return -ENOENT;
6078 }
6079 
6080 static int
6081 reloc_prog_func_and_line_info(const struct bpf_object *obj,
6082 			      struct bpf_program *main_prog,
6083 			      const struct bpf_program *prog)
6084 {
6085 	int err;
6086 
6087 	/* no .BTF.ext relocation if .BTF.ext is missing or kernel doesn't
6088 	 * supprot func/line info
6089 	 */
6090 	if (!obj->btf_ext || !kernel_supports(obj, FEAT_BTF_FUNC))
6091 		return 0;
6092 
6093 	/* only attempt func info relocation if main program's func_info
6094 	 * relocation was successful
6095 	 */
6096 	if (main_prog != prog && !main_prog->func_info)
6097 		goto line_info;
6098 
6099 	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->func_info,
6100 				       &main_prog->func_info,
6101 				       &main_prog->func_info_cnt,
6102 				       &main_prog->func_info_rec_size);
6103 	if (err) {
6104 		if (err != -ENOENT) {
6105 			pr_warn("prog '%s': error relocating .BTF.ext function info: %d\n",
6106 				prog->name, err);
6107 			return err;
6108 		}
6109 		if (main_prog->func_info) {
6110 			/*
6111 			 * Some info has already been found but has problem
6112 			 * in the last btf_ext reloc. Must have to error out.
6113 			 */
6114 			pr_warn("prog '%s': missing .BTF.ext function info.\n", prog->name);
6115 			return err;
6116 		}
6117 		/* Have problem loading the very first info. Ignore the rest. */
6118 		pr_warn("prog '%s': missing .BTF.ext function info for the main program, skipping all of .BTF.ext func info.\n",
6119 			prog->name);
6120 	}
6121 
6122 line_info:
6123 	/* don't relocate line info if main program's relocation failed */
6124 	if (main_prog != prog && !main_prog->line_info)
6125 		return 0;
6126 
6127 	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->line_info,
6128 				       &main_prog->line_info,
6129 				       &main_prog->line_info_cnt,
6130 				       &main_prog->line_info_rec_size);
6131 	if (err) {
6132 		if (err != -ENOENT) {
6133 			pr_warn("prog '%s': error relocating .BTF.ext line info: %d\n",
6134 				prog->name, err);
6135 			return err;
6136 		}
6137 		if (main_prog->line_info) {
6138 			/*
6139 			 * Some info has already been found but has problem
6140 			 * in the last btf_ext reloc. Must have to error out.
6141 			 */
6142 			pr_warn("prog '%s': missing .BTF.ext line info.\n", prog->name);
6143 			return err;
6144 		}
6145 		/* Have problem loading the very first info. Ignore the rest. */
6146 		pr_warn("prog '%s': missing .BTF.ext line info for the main program, skipping all of .BTF.ext line info.\n",
6147 			prog->name);
6148 	}
6149 	return 0;
6150 }
6151 
6152 static int cmp_relo_by_insn_idx(const void *key, const void *elem)
6153 {
6154 	size_t insn_idx = *(const size_t *)key;
6155 	const struct reloc_desc *relo = elem;
6156 
6157 	if (insn_idx == relo->insn_idx)
6158 		return 0;
6159 	return insn_idx < relo->insn_idx ? -1 : 1;
6160 }
6161 
6162 static struct reloc_desc *find_prog_insn_relo(const struct bpf_program *prog, size_t insn_idx)
6163 {
6164 	if (!prog->nr_reloc)
6165 		return NULL;
6166 	return bsearch(&insn_idx, prog->reloc_desc, prog->nr_reloc,
6167 		       sizeof(*prog->reloc_desc), cmp_relo_by_insn_idx);
6168 }
6169 
6170 static int append_subprog_relos(struct bpf_program *main_prog, struct bpf_program *subprog)
6171 {
6172 	int new_cnt = main_prog->nr_reloc + subprog->nr_reloc;
6173 	struct reloc_desc *relos;
6174 	int i;
6175 
6176 	if (main_prog == subprog)
6177 		return 0;
6178 	relos = libbpf_reallocarray(main_prog->reloc_desc, new_cnt, sizeof(*relos));
6179 	/* if new count is zero, reallocarray can return a valid NULL result;
6180 	 * in this case the previous pointer will be freed, so we *have to*
6181 	 * reassign old pointer to the new value (even if it's NULL)
6182 	 */
6183 	if (!relos && new_cnt)
6184 		return -ENOMEM;
6185 	if (subprog->nr_reloc)
6186 		memcpy(relos + main_prog->nr_reloc, subprog->reloc_desc,
6187 		       sizeof(*relos) * subprog->nr_reloc);
6188 
6189 	for (i = main_prog->nr_reloc; i < new_cnt; i++)
6190 		relos[i].insn_idx += subprog->sub_insn_off;
6191 	/* After insn_idx adjustment the 'relos' array is still sorted
6192 	 * by insn_idx and doesn't break bsearch.
6193 	 */
6194 	main_prog->reloc_desc = relos;
6195 	main_prog->nr_reloc = new_cnt;
6196 	return 0;
6197 }
6198 
6199 static int
6200 bpf_object__reloc_code(struct bpf_object *obj, struct bpf_program *main_prog,
6201 		       struct bpf_program *prog)
6202 {
6203 	size_t sub_insn_idx, insn_idx, new_cnt;
6204 	struct bpf_program *subprog;
6205 	struct bpf_insn *insns, *insn;
6206 	struct reloc_desc *relo;
6207 	int err;
6208 
6209 	err = reloc_prog_func_and_line_info(obj, main_prog, prog);
6210 	if (err)
6211 		return err;
6212 
6213 	for (insn_idx = 0; insn_idx < prog->sec_insn_cnt; insn_idx++) {
6214 		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6215 		if (!insn_is_subprog_call(insn) && !insn_is_pseudo_func(insn))
6216 			continue;
6217 
6218 		relo = find_prog_insn_relo(prog, insn_idx);
6219 		if (relo && relo->type == RELO_EXTERN_CALL)
6220 			/* kfunc relocations will be handled later
6221 			 * in bpf_object__relocate_data()
6222 			 */
6223 			continue;
6224 		if (relo && relo->type != RELO_CALL && relo->type != RELO_SUBPROG_ADDR) {
6225 			pr_warn("prog '%s': unexpected relo for insn #%zu, type %d\n",
6226 				prog->name, insn_idx, relo->type);
6227 			return -LIBBPF_ERRNO__RELOC;
6228 		}
6229 		if (relo) {
6230 			/* sub-program instruction index is a combination of
6231 			 * an offset of a symbol pointed to by relocation and
6232 			 * call instruction's imm field; for global functions,
6233 			 * call always has imm = -1, but for static functions
6234 			 * relocation is against STT_SECTION and insn->imm
6235 			 * points to a start of a static function
6236 			 *
6237 			 * for subprog addr relocation, the relo->sym_off + insn->imm is
6238 			 * the byte offset in the corresponding section.
6239 			 */
6240 			if (relo->type == RELO_CALL)
6241 				sub_insn_idx = relo->sym_off / BPF_INSN_SZ + insn->imm + 1;
6242 			else
6243 				sub_insn_idx = (relo->sym_off + insn->imm) / BPF_INSN_SZ;
6244 		} else if (insn_is_pseudo_func(insn)) {
6245 			/*
6246 			 * RELO_SUBPROG_ADDR relo is always emitted even if both
6247 			 * functions are in the same section, so it shouldn't reach here.
6248 			 */
6249 			pr_warn("prog '%s': missing subprog addr relo for insn #%zu\n",
6250 				prog->name, insn_idx);
6251 			return -LIBBPF_ERRNO__RELOC;
6252 		} else {
6253 			/* if subprogram call is to a static function within
6254 			 * the same ELF section, there won't be any relocation
6255 			 * emitted, but it also means there is no additional
6256 			 * offset necessary, insns->imm is relative to
6257 			 * instruction's original position within the section
6258 			 */
6259 			sub_insn_idx = prog->sec_insn_off + insn_idx + insn->imm + 1;
6260 		}
6261 
6262 		/* we enforce that sub-programs should be in .text section */
6263 		subprog = find_prog_by_sec_insn(obj, obj->efile.text_shndx, sub_insn_idx);
6264 		if (!subprog) {
6265 			pr_warn("prog '%s': no .text section found yet sub-program call exists\n",
6266 				prog->name);
6267 			return -LIBBPF_ERRNO__RELOC;
6268 		}
6269 
6270 		/* if it's the first call instruction calling into this
6271 		 * subprogram (meaning this subprog hasn't been processed
6272 		 * yet) within the context of current main program:
6273 		 *   - append it at the end of main program's instructions blog;
6274 		 *   - process is recursively, while current program is put on hold;
6275 		 *   - if that subprogram calls some other not yet processes
6276 		 *   subprogram, same thing will happen recursively until
6277 		 *   there are no more unprocesses subprograms left to append
6278 		 *   and relocate.
6279 		 */
6280 		if (subprog->sub_insn_off == 0) {
6281 			subprog->sub_insn_off = main_prog->insns_cnt;
6282 
6283 			new_cnt = main_prog->insns_cnt + subprog->insns_cnt;
6284 			insns = libbpf_reallocarray(main_prog->insns, new_cnt, sizeof(*insns));
6285 			if (!insns) {
6286 				pr_warn("prog '%s': failed to realloc prog code\n", main_prog->name);
6287 				return -ENOMEM;
6288 			}
6289 			main_prog->insns = insns;
6290 			main_prog->insns_cnt = new_cnt;
6291 
6292 			memcpy(main_prog->insns + subprog->sub_insn_off, subprog->insns,
6293 			       subprog->insns_cnt * sizeof(*insns));
6294 
6295 			pr_debug("prog '%s': added %zu insns from sub-prog '%s'\n",
6296 				 main_prog->name, subprog->insns_cnt, subprog->name);
6297 
6298 			/* The subprog insns are now appended. Append its relos too. */
6299 			err = append_subprog_relos(main_prog, subprog);
6300 			if (err)
6301 				return err;
6302 			err = bpf_object__reloc_code(obj, main_prog, subprog);
6303 			if (err)
6304 				return err;
6305 		}
6306 
6307 		/* main_prog->insns memory could have been re-allocated, so
6308 		 * calculate pointer again
6309 		 */
6310 		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6311 		/* calculate correct instruction position within current main
6312 		 * prog; each main prog can have a different set of
6313 		 * subprograms appended (potentially in different order as
6314 		 * well), so position of any subprog can be different for
6315 		 * different main programs
6316 		 */
6317 		insn->imm = subprog->sub_insn_off - (prog->sub_insn_off + insn_idx) - 1;
6318 
6319 		pr_debug("prog '%s': insn #%zu relocated, imm %d points to subprog '%s' (now at %zu offset)\n",
6320 			 prog->name, insn_idx, insn->imm, subprog->name, subprog->sub_insn_off);
6321 	}
6322 
6323 	return 0;
6324 }
6325 
6326 /*
6327  * Relocate sub-program calls.
6328  *
6329  * Algorithm operates as follows. Each entry-point BPF program (referred to as
6330  * main prog) is processed separately. For each subprog (non-entry functions,
6331  * that can be called from either entry progs or other subprogs) gets their
6332  * sub_insn_off reset to zero. This serves as indicator that this subprogram
6333  * hasn't been yet appended and relocated within current main prog. Once its
6334  * relocated, sub_insn_off will point at the position within current main prog
6335  * where given subprog was appended. This will further be used to relocate all
6336  * the call instructions jumping into this subprog.
6337  *
6338  * We start with main program and process all call instructions. If the call
6339  * is into a subprog that hasn't been processed (i.e., subprog->sub_insn_off
6340  * is zero), subprog instructions are appended at the end of main program's
6341  * instruction array. Then main program is "put on hold" while we recursively
6342  * process newly appended subprogram. If that subprogram calls into another
6343  * subprogram that hasn't been appended, new subprogram is appended again to
6344  * the *main* prog's instructions (subprog's instructions are always left
6345  * untouched, as they need to be in unmodified state for subsequent main progs
6346  * and subprog instructions are always sent only as part of a main prog) and
6347  * the process continues recursively. Once all the subprogs called from a main
6348  * prog or any of its subprogs are appended (and relocated), all their
6349  * positions within finalized instructions array are known, so it's easy to
6350  * rewrite call instructions with correct relative offsets, corresponding to
6351  * desired target subprog.
6352  *
6353  * Its important to realize that some subprogs might not be called from some
6354  * main prog and any of its called/used subprogs. Those will keep their
6355  * subprog->sub_insn_off as zero at all times and won't be appended to current
6356  * main prog and won't be relocated within the context of current main prog.
6357  * They might still be used from other main progs later.
6358  *
6359  * Visually this process can be shown as below. Suppose we have two main
6360  * programs mainA and mainB and BPF object contains three subprogs: subA,
6361  * subB, and subC. mainA calls only subA, mainB calls only subC, but subA and
6362  * subC both call subB:
6363  *
6364  *        +--------+ +-------+
6365  *        |        v v       |
6366  *     +--+---+ +--+-+-+ +---+--+
6367  *     | subA | | subB | | subC |
6368  *     +--+---+ +------+ +---+--+
6369  *        ^                  ^
6370  *        |                  |
6371  *    +---+-------+   +------+----+
6372  *    |   mainA   |   |   mainB   |
6373  *    +-----------+   +-----------+
6374  *
6375  * We'll start relocating mainA, will find subA, append it and start
6376  * processing sub A recursively:
6377  *
6378  *    +-----------+------+
6379  *    |   mainA   | subA |
6380  *    +-----------+------+
6381  *
6382  * At this point we notice that subB is used from subA, so we append it and
6383  * relocate (there are no further subcalls from subB):
6384  *
6385  *    +-----------+------+------+
6386  *    |   mainA   | subA | subB |
6387  *    +-----------+------+------+
6388  *
6389  * At this point, we relocate subA calls, then go one level up and finish with
6390  * relocatin mainA calls. mainA is done.
6391  *
6392  * For mainB process is similar but results in different order. We start with
6393  * mainB and skip subA and subB, as mainB never calls them (at least
6394  * directly), but we see subC is needed, so we append and start processing it:
6395  *
6396  *    +-----------+------+
6397  *    |   mainB   | subC |
6398  *    +-----------+------+
6399  * Now we see subC needs subB, so we go back to it, append and relocate it:
6400  *
6401  *    +-----------+------+------+
6402  *    |   mainB   | subC | subB |
6403  *    +-----------+------+------+
6404  *
6405  * At this point we unwind recursion, relocate calls in subC, then in mainB.
6406  */
6407 static int
6408 bpf_object__relocate_calls(struct bpf_object *obj, struct bpf_program *prog)
6409 {
6410 	struct bpf_program *subprog;
6411 	int i, err;
6412 
6413 	/* mark all subprogs as not relocated (yet) within the context of
6414 	 * current main program
6415 	 */
6416 	for (i = 0; i < obj->nr_programs; i++) {
6417 		subprog = &obj->programs[i];
6418 		if (!prog_is_subprog(obj, subprog))
6419 			continue;
6420 
6421 		subprog->sub_insn_off = 0;
6422 	}
6423 
6424 	err = bpf_object__reloc_code(obj, prog, prog);
6425 	if (err)
6426 		return err;
6427 
6428 	return 0;
6429 }
6430 
6431 static void
6432 bpf_object__free_relocs(struct bpf_object *obj)
6433 {
6434 	struct bpf_program *prog;
6435 	int i;
6436 
6437 	/* free up relocation descriptors */
6438 	for (i = 0; i < obj->nr_programs; i++) {
6439 		prog = &obj->programs[i];
6440 		zfree(&prog->reloc_desc);
6441 		prog->nr_reloc = 0;
6442 	}
6443 }
6444 
6445 static int cmp_relocs(const void *_a, const void *_b)
6446 {
6447 	const struct reloc_desc *a = _a;
6448 	const struct reloc_desc *b = _b;
6449 
6450 	if (a->insn_idx != b->insn_idx)
6451 		return a->insn_idx < b->insn_idx ? -1 : 1;
6452 
6453 	/* no two relocations should have the same insn_idx, but ... */
6454 	if (a->type != b->type)
6455 		return a->type < b->type ? -1 : 1;
6456 
6457 	return 0;
6458 }
6459 
6460 static void bpf_object__sort_relos(struct bpf_object *obj)
6461 {
6462 	int i;
6463 
6464 	for (i = 0; i < obj->nr_programs; i++) {
6465 		struct bpf_program *p = &obj->programs[i];
6466 
6467 		if (!p->nr_reloc)
6468 			continue;
6469 
6470 		qsort(p->reloc_desc, p->nr_reloc, sizeof(*p->reloc_desc), cmp_relocs);
6471 	}
6472 }
6473 
6474 static int
6475 bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
6476 {
6477 	struct bpf_program *prog;
6478 	size_t i, j;
6479 	int err;
6480 
6481 	if (obj->btf_ext) {
6482 		err = bpf_object__relocate_core(obj, targ_btf_path);
6483 		if (err) {
6484 			pr_warn("failed to perform CO-RE relocations: %d\n",
6485 				err);
6486 			return err;
6487 		}
6488 		bpf_object__sort_relos(obj);
6489 	}
6490 
6491 	/* Before relocating calls pre-process relocations and mark
6492 	 * few ld_imm64 instructions that points to subprogs.
6493 	 * Otherwise bpf_object__reloc_code() later would have to consider
6494 	 * all ld_imm64 insns as relocation candidates. That would
6495 	 * reduce relocation speed, since amount of find_prog_insn_relo()
6496 	 * would increase and most of them will fail to find a relo.
6497 	 */
6498 	for (i = 0; i < obj->nr_programs; i++) {
6499 		prog = &obj->programs[i];
6500 		for (j = 0; j < prog->nr_reloc; j++) {
6501 			struct reloc_desc *relo = &prog->reloc_desc[j];
6502 			struct bpf_insn *insn = &prog->insns[relo->insn_idx];
6503 
6504 			/* mark the insn, so it's recognized by insn_is_pseudo_func() */
6505 			if (relo->type == RELO_SUBPROG_ADDR)
6506 				insn[0].src_reg = BPF_PSEUDO_FUNC;
6507 		}
6508 	}
6509 
6510 	/* relocate subprogram calls and append used subprograms to main
6511 	 * programs; each copy of subprogram code needs to be relocated
6512 	 * differently for each main program, because its code location might
6513 	 * have changed.
6514 	 * Append subprog relos to main programs to allow data relos to be
6515 	 * processed after text is completely relocated.
6516 	 */
6517 	for (i = 0; i < obj->nr_programs; i++) {
6518 		prog = &obj->programs[i];
6519 		/* sub-program's sub-calls are relocated within the context of
6520 		 * its main program only
6521 		 */
6522 		if (prog_is_subprog(obj, prog))
6523 			continue;
6524 		if (!prog->autoload)
6525 			continue;
6526 
6527 		err = bpf_object__relocate_calls(obj, prog);
6528 		if (err) {
6529 			pr_warn("prog '%s': failed to relocate calls: %d\n",
6530 				prog->name, err);
6531 			return err;
6532 		}
6533 	}
6534 	/* Process data relos for main programs */
6535 	for (i = 0; i < obj->nr_programs; i++) {
6536 		prog = &obj->programs[i];
6537 		if (prog_is_subprog(obj, prog))
6538 			continue;
6539 		if (!prog->autoload)
6540 			continue;
6541 		err = bpf_object__relocate_data(obj, prog);
6542 		if (err) {
6543 			pr_warn("prog '%s': failed to relocate data references: %d\n",
6544 				prog->name, err);
6545 			return err;
6546 		}
6547 	}
6548 
6549 	return 0;
6550 }
6551 
6552 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
6553 					    Elf64_Shdr *shdr, Elf_Data *data);
6554 
6555 static int bpf_object__collect_map_relos(struct bpf_object *obj,
6556 					 Elf64_Shdr *shdr, Elf_Data *data)
6557 {
6558 	const int bpf_ptr_sz = 8, host_ptr_sz = sizeof(void *);
6559 	int i, j, nrels, new_sz;
6560 	const struct btf_var_secinfo *vi = NULL;
6561 	const struct btf_type *sec, *var, *def;
6562 	struct bpf_map *map = NULL, *targ_map = NULL;
6563 	struct bpf_program *targ_prog = NULL;
6564 	bool is_prog_array, is_map_in_map;
6565 	const struct btf_member *member;
6566 	const char *name, *mname, *type;
6567 	unsigned int moff;
6568 	Elf64_Sym *sym;
6569 	Elf64_Rel *rel;
6570 	void *tmp;
6571 
6572 	if (!obj->efile.btf_maps_sec_btf_id || !obj->btf)
6573 		return -EINVAL;
6574 	sec = btf__type_by_id(obj->btf, obj->efile.btf_maps_sec_btf_id);
6575 	if (!sec)
6576 		return -EINVAL;
6577 
6578 	nrels = shdr->sh_size / shdr->sh_entsize;
6579 	for (i = 0; i < nrels; i++) {
6580 		rel = elf_rel_by_idx(data, i);
6581 		if (!rel) {
6582 			pr_warn(".maps relo #%d: failed to get ELF relo\n", i);
6583 			return -LIBBPF_ERRNO__FORMAT;
6584 		}
6585 
6586 		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
6587 		if (!sym) {
6588 			pr_warn(".maps relo #%d: symbol %zx not found\n",
6589 				i, (size_t)ELF64_R_SYM(rel->r_info));
6590 			return -LIBBPF_ERRNO__FORMAT;
6591 		}
6592 		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
6593 
6594 		pr_debug(".maps relo #%d: for %zd value %zd rel->r_offset %zu name %d ('%s')\n",
6595 			 i, (ssize_t)(rel->r_info >> 32), (size_t)sym->st_value,
6596 			 (size_t)rel->r_offset, sym->st_name, name);
6597 
6598 		for (j = 0; j < obj->nr_maps; j++) {
6599 			map = &obj->maps[j];
6600 			if (map->sec_idx != obj->efile.btf_maps_shndx)
6601 				continue;
6602 
6603 			vi = btf_var_secinfos(sec) + map->btf_var_idx;
6604 			if (vi->offset <= rel->r_offset &&
6605 			    rel->r_offset + bpf_ptr_sz <= vi->offset + vi->size)
6606 				break;
6607 		}
6608 		if (j == obj->nr_maps) {
6609 			pr_warn(".maps relo #%d: cannot find map '%s' at rel->r_offset %zu\n",
6610 				i, name, (size_t)rel->r_offset);
6611 			return -EINVAL;
6612 		}
6613 
6614 		is_map_in_map = bpf_map_type__is_map_in_map(map->def.type);
6615 		is_prog_array = map->def.type == BPF_MAP_TYPE_PROG_ARRAY;
6616 		type = is_map_in_map ? "map" : "prog";
6617 		if (is_map_in_map) {
6618 			if (sym->st_shndx != obj->efile.btf_maps_shndx) {
6619 				pr_warn(".maps relo #%d: '%s' isn't a BTF-defined map\n",
6620 					i, name);
6621 				return -LIBBPF_ERRNO__RELOC;
6622 			}
6623 			if (map->def.type == BPF_MAP_TYPE_HASH_OF_MAPS &&
6624 			    map->def.key_size != sizeof(int)) {
6625 				pr_warn(".maps relo #%d: hash-of-maps '%s' should have key size %zu.\n",
6626 					i, map->name, sizeof(int));
6627 				return -EINVAL;
6628 			}
6629 			targ_map = bpf_object__find_map_by_name(obj, name);
6630 			if (!targ_map) {
6631 				pr_warn(".maps relo #%d: '%s' isn't a valid map reference\n",
6632 					i, name);
6633 				return -ESRCH;
6634 			}
6635 		} else if (is_prog_array) {
6636 			targ_prog = bpf_object__find_program_by_name(obj, name);
6637 			if (!targ_prog) {
6638 				pr_warn(".maps relo #%d: '%s' isn't a valid program reference\n",
6639 					i, name);
6640 				return -ESRCH;
6641 			}
6642 			if (targ_prog->sec_idx != sym->st_shndx ||
6643 			    targ_prog->sec_insn_off * 8 != sym->st_value ||
6644 			    prog_is_subprog(obj, targ_prog)) {
6645 				pr_warn(".maps relo #%d: '%s' isn't an entry-point program\n",
6646 					i, name);
6647 				return -LIBBPF_ERRNO__RELOC;
6648 			}
6649 		} else {
6650 			return -EINVAL;
6651 		}
6652 
6653 		var = btf__type_by_id(obj->btf, vi->type);
6654 		def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
6655 		if (btf_vlen(def) == 0)
6656 			return -EINVAL;
6657 		member = btf_members(def) + btf_vlen(def) - 1;
6658 		mname = btf__name_by_offset(obj->btf, member->name_off);
6659 		if (strcmp(mname, "values"))
6660 			return -EINVAL;
6661 
6662 		moff = btf_member_bit_offset(def, btf_vlen(def) - 1) / 8;
6663 		if (rel->r_offset - vi->offset < moff)
6664 			return -EINVAL;
6665 
6666 		moff = rel->r_offset - vi->offset - moff;
6667 		/* here we use BPF pointer size, which is always 64 bit, as we
6668 		 * are parsing ELF that was built for BPF target
6669 		 */
6670 		if (moff % bpf_ptr_sz)
6671 			return -EINVAL;
6672 		moff /= bpf_ptr_sz;
6673 		if (moff >= map->init_slots_sz) {
6674 			new_sz = moff + 1;
6675 			tmp = libbpf_reallocarray(map->init_slots, new_sz, host_ptr_sz);
6676 			if (!tmp)
6677 				return -ENOMEM;
6678 			map->init_slots = tmp;
6679 			memset(map->init_slots + map->init_slots_sz, 0,
6680 			       (new_sz - map->init_slots_sz) * host_ptr_sz);
6681 			map->init_slots_sz = new_sz;
6682 		}
6683 		map->init_slots[moff] = is_map_in_map ? (void *)targ_map : (void *)targ_prog;
6684 
6685 		pr_debug(".maps relo #%d: map '%s' slot [%d] points to %s '%s'\n",
6686 			 i, map->name, moff, type, name);
6687 	}
6688 
6689 	return 0;
6690 }
6691 
6692 static int bpf_object__collect_relos(struct bpf_object *obj)
6693 {
6694 	int i, err;
6695 
6696 	for (i = 0; i < obj->efile.sec_cnt; i++) {
6697 		struct elf_sec_desc *sec_desc = &obj->efile.secs[i];
6698 		Elf64_Shdr *shdr;
6699 		Elf_Data *data;
6700 		int idx;
6701 
6702 		if (sec_desc->sec_type != SEC_RELO)
6703 			continue;
6704 
6705 		shdr = sec_desc->shdr;
6706 		data = sec_desc->data;
6707 		idx = shdr->sh_info;
6708 
6709 		if (shdr->sh_type != SHT_REL) {
6710 			pr_warn("internal error at %d\n", __LINE__);
6711 			return -LIBBPF_ERRNO__INTERNAL;
6712 		}
6713 
6714 		if (idx == obj->efile.st_ops_shndx || idx == obj->efile.st_ops_link_shndx)
6715 			err = bpf_object__collect_st_ops_relos(obj, shdr, data);
6716 		else if (idx == obj->efile.btf_maps_shndx)
6717 			err = bpf_object__collect_map_relos(obj, shdr, data);
6718 		else
6719 			err = bpf_object__collect_prog_relos(obj, shdr, data);
6720 		if (err)
6721 			return err;
6722 	}
6723 
6724 	bpf_object__sort_relos(obj);
6725 	return 0;
6726 }
6727 
6728 static bool insn_is_helper_call(struct bpf_insn *insn, enum bpf_func_id *func_id)
6729 {
6730 	if (BPF_CLASS(insn->code) == BPF_JMP &&
6731 	    BPF_OP(insn->code) == BPF_CALL &&
6732 	    BPF_SRC(insn->code) == BPF_K &&
6733 	    insn->src_reg == 0 &&
6734 	    insn->dst_reg == 0) {
6735 		    *func_id = insn->imm;
6736 		    return true;
6737 	}
6738 	return false;
6739 }
6740 
6741 static int bpf_object__sanitize_prog(struct bpf_object *obj, struct bpf_program *prog)
6742 {
6743 	struct bpf_insn *insn = prog->insns;
6744 	enum bpf_func_id func_id;
6745 	int i;
6746 
6747 	if (obj->gen_loader)
6748 		return 0;
6749 
6750 	for (i = 0; i < prog->insns_cnt; i++, insn++) {
6751 		if (!insn_is_helper_call(insn, &func_id))
6752 			continue;
6753 
6754 		/* on kernels that don't yet support
6755 		 * bpf_probe_read_{kernel,user}[_str] helpers, fall back
6756 		 * to bpf_probe_read() which works well for old kernels
6757 		 */
6758 		switch (func_id) {
6759 		case BPF_FUNC_probe_read_kernel:
6760 		case BPF_FUNC_probe_read_user:
6761 			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
6762 				insn->imm = BPF_FUNC_probe_read;
6763 			break;
6764 		case BPF_FUNC_probe_read_kernel_str:
6765 		case BPF_FUNC_probe_read_user_str:
6766 			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
6767 				insn->imm = BPF_FUNC_probe_read_str;
6768 			break;
6769 		default:
6770 			break;
6771 		}
6772 	}
6773 	return 0;
6774 }
6775 
6776 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
6777 				     int *btf_obj_fd, int *btf_type_id);
6778 
6779 /* this is called as prog->sec_def->prog_prepare_load_fn for libbpf-supported sec_defs */
6780 static int libbpf_prepare_prog_load(struct bpf_program *prog,
6781 				    struct bpf_prog_load_opts *opts, long cookie)
6782 {
6783 	enum sec_def_flags def = cookie;
6784 
6785 	/* old kernels might not support specifying expected_attach_type */
6786 	if ((def & SEC_EXP_ATTACH_OPT) && !kernel_supports(prog->obj, FEAT_EXP_ATTACH_TYPE))
6787 		opts->expected_attach_type = 0;
6788 
6789 	if (def & SEC_SLEEPABLE)
6790 		opts->prog_flags |= BPF_F_SLEEPABLE;
6791 
6792 	if (prog->type == BPF_PROG_TYPE_XDP && (def & SEC_XDP_FRAGS))
6793 		opts->prog_flags |= BPF_F_XDP_HAS_FRAGS;
6794 
6795 	if ((def & SEC_ATTACH_BTF) && !prog->attach_btf_id) {
6796 		int btf_obj_fd = 0, btf_type_id = 0, err;
6797 		const char *attach_name;
6798 
6799 		attach_name = strchr(prog->sec_name, '/');
6800 		if (!attach_name) {
6801 			/* if BPF program is annotated with just SEC("fentry")
6802 			 * (or similar) without declaratively specifying
6803 			 * target, then it is expected that target will be
6804 			 * specified with bpf_program__set_attach_target() at
6805 			 * runtime before BPF object load step. If not, then
6806 			 * there is nothing to load into the kernel as BPF
6807 			 * verifier won't be able to validate BPF program
6808 			 * correctness anyways.
6809 			 */
6810 			pr_warn("prog '%s': no BTF-based attach target is specified, use bpf_program__set_attach_target()\n",
6811 				prog->name);
6812 			return -EINVAL;
6813 		}
6814 		attach_name++; /* skip over / */
6815 
6816 		err = libbpf_find_attach_btf_id(prog, attach_name, &btf_obj_fd, &btf_type_id);
6817 		if (err)
6818 			return err;
6819 
6820 		/* cache resolved BTF FD and BTF type ID in the prog */
6821 		prog->attach_btf_obj_fd = btf_obj_fd;
6822 		prog->attach_btf_id = btf_type_id;
6823 
6824 		/* but by now libbpf common logic is not utilizing
6825 		 * prog->atach_btf_obj_fd/prog->attach_btf_id anymore because
6826 		 * this callback is called after opts were populated by
6827 		 * libbpf, so this callback has to update opts explicitly here
6828 		 */
6829 		opts->attach_btf_obj_fd = btf_obj_fd;
6830 		opts->attach_btf_id = btf_type_id;
6831 	}
6832 	return 0;
6833 }
6834 
6835 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz);
6836 
6837 static int bpf_object_load_prog(struct bpf_object *obj, struct bpf_program *prog,
6838 				struct bpf_insn *insns, int insns_cnt,
6839 				const char *license, __u32 kern_version, int *prog_fd)
6840 {
6841 	LIBBPF_OPTS(bpf_prog_load_opts, load_attr);
6842 	const char *prog_name = NULL;
6843 	char *cp, errmsg[STRERR_BUFSIZE];
6844 	size_t log_buf_size = 0;
6845 	char *log_buf = NULL, *tmp;
6846 	int btf_fd, ret, err;
6847 	bool own_log_buf = true;
6848 	__u32 log_level = prog->log_level;
6849 
6850 	if (prog->type == BPF_PROG_TYPE_UNSPEC) {
6851 		/*
6852 		 * The program type must be set.  Most likely we couldn't find a proper
6853 		 * section definition at load time, and thus we didn't infer the type.
6854 		 */
6855 		pr_warn("prog '%s': missing BPF prog type, check ELF section name '%s'\n",
6856 			prog->name, prog->sec_name);
6857 		return -EINVAL;
6858 	}
6859 
6860 	if (!insns || !insns_cnt)
6861 		return -EINVAL;
6862 
6863 	load_attr.expected_attach_type = prog->expected_attach_type;
6864 	if (kernel_supports(obj, FEAT_PROG_NAME))
6865 		prog_name = prog->name;
6866 	load_attr.attach_prog_fd = prog->attach_prog_fd;
6867 	load_attr.attach_btf_obj_fd = prog->attach_btf_obj_fd;
6868 	load_attr.attach_btf_id = prog->attach_btf_id;
6869 	load_attr.kern_version = kern_version;
6870 	load_attr.prog_ifindex = prog->prog_ifindex;
6871 
6872 	/* specify func_info/line_info only if kernel supports them */
6873 	btf_fd = bpf_object__btf_fd(obj);
6874 	if (btf_fd >= 0 && kernel_supports(obj, FEAT_BTF_FUNC)) {
6875 		load_attr.prog_btf_fd = btf_fd;
6876 		load_attr.func_info = prog->func_info;
6877 		load_attr.func_info_rec_size = prog->func_info_rec_size;
6878 		load_attr.func_info_cnt = prog->func_info_cnt;
6879 		load_attr.line_info = prog->line_info;
6880 		load_attr.line_info_rec_size = prog->line_info_rec_size;
6881 		load_attr.line_info_cnt = prog->line_info_cnt;
6882 	}
6883 	load_attr.log_level = log_level;
6884 	load_attr.prog_flags = prog->prog_flags;
6885 	load_attr.fd_array = obj->fd_array;
6886 
6887 	/* adjust load_attr if sec_def provides custom preload callback */
6888 	if (prog->sec_def && prog->sec_def->prog_prepare_load_fn) {
6889 		err = prog->sec_def->prog_prepare_load_fn(prog, &load_attr, prog->sec_def->cookie);
6890 		if (err < 0) {
6891 			pr_warn("prog '%s': failed to prepare load attributes: %d\n",
6892 				prog->name, err);
6893 			return err;
6894 		}
6895 		insns = prog->insns;
6896 		insns_cnt = prog->insns_cnt;
6897 	}
6898 
6899 	if (obj->gen_loader) {
6900 		bpf_gen__prog_load(obj->gen_loader, prog->type, prog->name,
6901 				   license, insns, insns_cnt, &load_attr,
6902 				   prog - obj->programs);
6903 		*prog_fd = -1;
6904 		return 0;
6905 	}
6906 
6907 retry_load:
6908 	/* if log_level is zero, we don't request logs initially even if
6909 	 * custom log_buf is specified; if the program load fails, then we'll
6910 	 * bump log_level to 1 and use either custom log_buf or we'll allocate
6911 	 * our own and retry the load to get details on what failed
6912 	 */
6913 	if (log_level) {
6914 		if (prog->log_buf) {
6915 			log_buf = prog->log_buf;
6916 			log_buf_size = prog->log_size;
6917 			own_log_buf = false;
6918 		} else if (obj->log_buf) {
6919 			log_buf = obj->log_buf;
6920 			log_buf_size = obj->log_size;
6921 			own_log_buf = false;
6922 		} else {
6923 			log_buf_size = max((size_t)BPF_LOG_BUF_SIZE, log_buf_size * 2);
6924 			tmp = realloc(log_buf, log_buf_size);
6925 			if (!tmp) {
6926 				ret = -ENOMEM;
6927 				goto out;
6928 			}
6929 			log_buf = tmp;
6930 			log_buf[0] = '\0';
6931 			own_log_buf = true;
6932 		}
6933 	}
6934 
6935 	load_attr.log_buf = log_buf;
6936 	load_attr.log_size = log_buf_size;
6937 	load_attr.log_level = log_level;
6938 
6939 	ret = bpf_prog_load(prog->type, prog_name, license, insns, insns_cnt, &load_attr);
6940 	if (ret >= 0) {
6941 		if (log_level && own_log_buf) {
6942 			pr_debug("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
6943 				 prog->name, log_buf);
6944 		}
6945 
6946 		if (obj->has_rodata && kernel_supports(obj, FEAT_PROG_BIND_MAP)) {
6947 			struct bpf_map *map;
6948 			int i;
6949 
6950 			for (i = 0; i < obj->nr_maps; i++) {
6951 				map = &prog->obj->maps[i];
6952 				if (map->libbpf_type != LIBBPF_MAP_RODATA)
6953 					continue;
6954 
6955 				if (bpf_prog_bind_map(ret, bpf_map__fd(map), NULL)) {
6956 					cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
6957 					pr_warn("prog '%s': failed to bind map '%s': %s\n",
6958 						prog->name, map->real_name, cp);
6959 					/* Don't fail hard if can't bind rodata. */
6960 				}
6961 			}
6962 		}
6963 
6964 		*prog_fd = ret;
6965 		ret = 0;
6966 		goto out;
6967 	}
6968 
6969 	if (log_level == 0) {
6970 		log_level = 1;
6971 		goto retry_load;
6972 	}
6973 	/* On ENOSPC, increase log buffer size and retry, unless custom
6974 	 * log_buf is specified.
6975 	 * Be careful to not overflow u32, though. Kernel's log buf size limit
6976 	 * isn't part of UAPI so it can always be bumped to full 4GB. So don't
6977 	 * multiply by 2 unless we are sure we'll fit within 32 bits.
6978 	 * Currently, we'll get -EINVAL when we reach (UINT_MAX >> 2).
6979 	 */
6980 	if (own_log_buf && errno == ENOSPC && log_buf_size <= UINT_MAX / 2)
6981 		goto retry_load;
6982 
6983 	ret = -errno;
6984 
6985 	/* post-process verifier log to improve error descriptions */
6986 	fixup_verifier_log(prog, log_buf, log_buf_size);
6987 
6988 	cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
6989 	pr_warn("prog '%s': BPF program load failed: %s\n", prog->name, cp);
6990 	pr_perm_msg(ret);
6991 
6992 	if (own_log_buf && log_buf && log_buf[0] != '\0') {
6993 		pr_warn("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
6994 			prog->name, log_buf);
6995 	}
6996 
6997 out:
6998 	if (own_log_buf)
6999 		free(log_buf);
7000 	return ret;
7001 }
7002 
7003 static char *find_prev_line(char *buf, char *cur)
7004 {
7005 	char *p;
7006 
7007 	if (cur == buf) /* end of a log buf */
7008 		return NULL;
7009 
7010 	p = cur - 1;
7011 	while (p - 1 >= buf && *(p - 1) != '\n')
7012 		p--;
7013 
7014 	return p;
7015 }
7016 
7017 static void patch_log(char *buf, size_t buf_sz, size_t log_sz,
7018 		      char *orig, size_t orig_sz, const char *patch)
7019 {
7020 	/* size of the remaining log content to the right from the to-be-replaced part */
7021 	size_t rem_sz = (buf + log_sz) - (orig + orig_sz);
7022 	size_t patch_sz = strlen(patch);
7023 
7024 	if (patch_sz != orig_sz) {
7025 		/* If patch line(s) are longer than original piece of verifier log,
7026 		 * shift log contents by (patch_sz - orig_sz) bytes to the right
7027 		 * starting from after to-be-replaced part of the log.
7028 		 *
7029 		 * If patch line(s) are shorter than original piece of verifier log,
7030 		 * shift log contents by (orig_sz - patch_sz) bytes to the left
7031 		 * starting from after to-be-replaced part of the log
7032 		 *
7033 		 * We need to be careful about not overflowing available
7034 		 * buf_sz capacity. If that's the case, we'll truncate the end
7035 		 * of the original log, as necessary.
7036 		 */
7037 		if (patch_sz > orig_sz) {
7038 			if (orig + patch_sz >= buf + buf_sz) {
7039 				/* patch is big enough to cover remaining space completely */
7040 				patch_sz -= (orig + patch_sz) - (buf + buf_sz) + 1;
7041 				rem_sz = 0;
7042 			} else if (patch_sz - orig_sz > buf_sz - log_sz) {
7043 				/* patch causes part of remaining log to be truncated */
7044 				rem_sz -= (patch_sz - orig_sz) - (buf_sz - log_sz);
7045 			}
7046 		}
7047 		/* shift remaining log to the right by calculated amount */
7048 		memmove(orig + patch_sz, orig + orig_sz, rem_sz);
7049 	}
7050 
7051 	memcpy(orig, patch, patch_sz);
7052 }
7053 
7054 static void fixup_log_failed_core_relo(struct bpf_program *prog,
7055 				       char *buf, size_t buf_sz, size_t log_sz,
7056 				       char *line1, char *line2, char *line3)
7057 {
7058 	/* Expected log for failed and not properly guarded CO-RE relocation:
7059 	 * line1 -> 123: (85) call unknown#195896080
7060 	 * line2 -> invalid func unknown#195896080
7061 	 * line3 -> <anything else or end of buffer>
7062 	 *
7063 	 * "123" is the index of the instruction that was poisoned. We extract
7064 	 * instruction index to find corresponding CO-RE relocation and
7065 	 * replace this part of the log with more relevant information about
7066 	 * failed CO-RE relocation.
7067 	 */
7068 	const struct bpf_core_relo *relo;
7069 	struct bpf_core_spec spec;
7070 	char patch[512], spec_buf[256];
7071 	int insn_idx, err, spec_len;
7072 
7073 	if (sscanf(line1, "%d: (%*d) call unknown#195896080\n", &insn_idx) != 1)
7074 		return;
7075 
7076 	relo = find_relo_core(prog, insn_idx);
7077 	if (!relo)
7078 		return;
7079 
7080 	err = bpf_core_parse_spec(prog->name, prog->obj->btf, relo, &spec);
7081 	if (err)
7082 		return;
7083 
7084 	spec_len = bpf_core_format_spec(spec_buf, sizeof(spec_buf), &spec);
7085 	snprintf(patch, sizeof(patch),
7086 		 "%d: <invalid CO-RE relocation>\n"
7087 		 "failed to resolve CO-RE relocation %s%s\n",
7088 		 insn_idx, spec_buf, spec_len >= sizeof(spec_buf) ? "..." : "");
7089 
7090 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7091 }
7092 
7093 static void fixup_log_missing_map_load(struct bpf_program *prog,
7094 				       char *buf, size_t buf_sz, size_t log_sz,
7095 				       char *line1, char *line2, char *line3)
7096 {
7097 	/* Expected log for failed and not properly guarded map reference:
7098 	 * line1 -> 123: (85) call unknown#2001000345
7099 	 * line2 -> invalid func unknown#2001000345
7100 	 * line3 -> <anything else or end of buffer>
7101 	 *
7102 	 * "123" is the index of the instruction that was poisoned.
7103 	 * "345" in "2001000345" is a map index in obj->maps to fetch map name.
7104 	 */
7105 	struct bpf_object *obj = prog->obj;
7106 	const struct bpf_map *map;
7107 	int insn_idx, map_idx;
7108 	char patch[128];
7109 
7110 	if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &map_idx) != 2)
7111 		return;
7112 
7113 	map_idx -= POISON_LDIMM64_MAP_BASE;
7114 	if (map_idx < 0 || map_idx >= obj->nr_maps)
7115 		return;
7116 	map = &obj->maps[map_idx];
7117 
7118 	snprintf(patch, sizeof(patch),
7119 		 "%d: <invalid BPF map reference>\n"
7120 		 "BPF map '%s' is referenced but wasn't created\n",
7121 		 insn_idx, map->name);
7122 
7123 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7124 }
7125 
7126 static void fixup_log_missing_kfunc_call(struct bpf_program *prog,
7127 					 char *buf, size_t buf_sz, size_t log_sz,
7128 					 char *line1, char *line2, char *line3)
7129 {
7130 	/* Expected log for failed and not properly guarded kfunc call:
7131 	 * line1 -> 123: (85) call unknown#2002000345
7132 	 * line2 -> invalid func unknown#2002000345
7133 	 * line3 -> <anything else or end of buffer>
7134 	 *
7135 	 * "123" is the index of the instruction that was poisoned.
7136 	 * "345" in "2002000345" is an extern index in obj->externs to fetch kfunc name.
7137 	 */
7138 	struct bpf_object *obj = prog->obj;
7139 	const struct extern_desc *ext;
7140 	int insn_idx, ext_idx;
7141 	char patch[128];
7142 
7143 	if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &ext_idx) != 2)
7144 		return;
7145 
7146 	ext_idx -= POISON_CALL_KFUNC_BASE;
7147 	if (ext_idx < 0 || ext_idx >= obj->nr_extern)
7148 		return;
7149 	ext = &obj->externs[ext_idx];
7150 
7151 	snprintf(patch, sizeof(patch),
7152 		 "%d: <invalid kfunc call>\n"
7153 		 "kfunc '%s' is referenced but wasn't resolved\n",
7154 		 insn_idx, ext->name);
7155 
7156 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7157 }
7158 
7159 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz)
7160 {
7161 	/* look for familiar error patterns in last N lines of the log */
7162 	const size_t max_last_line_cnt = 10;
7163 	char *prev_line, *cur_line, *next_line;
7164 	size_t log_sz;
7165 	int i;
7166 
7167 	if (!buf)
7168 		return;
7169 
7170 	log_sz = strlen(buf) + 1;
7171 	next_line = buf + log_sz - 1;
7172 
7173 	for (i = 0; i < max_last_line_cnt; i++, next_line = cur_line) {
7174 		cur_line = find_prev_line(buf, next_line);
7175 		if (!cur_line)
7176 			return;
7177 
7178 		if (str_has_pfx(cur_line, "invalid func unknown#195896080\n")) {
7179 			prev_line = find_prev_line(buf, cur_line);
7180 			if (!prev_line)
7181 				continue;
7182 
7183 			/* failed CO-RE relocation case */
7184 			fixup_log_failed_core_relo(prog, buf, buf_sz, log_sz,
7185 						   prev_line, cur_line, next_line);
7186 			return;
7187 		} else if (str_has_pfx(cur_line, "invalid func unknown#"POISON_LDIMM64_MAP_PFX)) {
7188 			prev_line = find_prev_line(buf, cur_line);
7189 			if (!prev_line)
7190 				continue;
7191 
7192 			/* reference to uncreated BPF map */
7193 			fixup_log_missing_map_load(prog, buf, buf_sz, log_sz,
7194 						   prev_line, cur_line, next_line);
7195 			return;
7196 		} else if (str_has_pfx(cur_line, "invalid func unknown#"POISON_CALL_KFUNC_PFX)) {
7197 			prev_line = find_prev_line(buf, cur_line);
7198 			if (!prev_line)
7199 				continue;
7200 
7201 			/* reference to unresolved kfunc */
7202 			fixup_log_missing_kfunc_call(prog, buf, buf_sz, log_sz,
7203 						     prev_line, cur_line, next_line);
7204 			return;
7205 		}
7206 	}
7207 }
7208 
7209 static int bpf_program_record_relos(struct bpf_program *prog)
7210 {
7211 	struct bpf_object *obj = prog->obj;
7212 	int i;
7213 
7214 	for (i = 0; i < prog->nr_reloc; i++) {
7215 		struct reloc_desc *relo = &prog->reloc_desc[i];
7216 		struct extern_desc *ext = &obj->externs[relo->ext_idx];
7217 		int kind;
7218 
7219 		switch (relo->type) {
7220 		case RELO_EXTERN_LD64:
7221 			if (ext->type != EXT_KSYM)
7222 				continue;
7223 			kind = btf_is_var(btf__type_by_id(obj->btf, ext->btf_id)) ?
7224 				BTF_KIND_VAR : BTF_KIND_FUNC;
7225 			bpf_gen__record_extern(obj->gen_loader, ext->name,
7226 					       ext->is_weak, !ext->ksym.type_id,
7227 					       true, kind, relo->insn_idx);
7228 			break;
7229 		case RELO_EXTERN_CALL:
7230 			bpf_gen__record_extern(obj->gen_loader, ext->name,
7231 					       ext->is_weak, false, false, BTF_KIND_FUNC,
7232 					       relo->insn_idx);
7233 			break;
7234 		case RELO_CORE: {
7235 			struct bpf_core_relo cr = {
7236 				.insn_off = relo->insn_idx * 8,
7237 				.type_id = relo->core_relo->type_id,
7238 				.access_str_off = relo->core_relo->access_str_off,
7239 				.kind = relo->core_relo->kind,
7240 			};
7241 
7242 			bpf_gen__record_relo_core(obj->gen_loader, &cr);
7243 			break;
7244 		}
7245 		default:
7246 			continue;
7247 		}
7248 	}
7249 	return 0;
7250 }
7251 
7252 static int
7253 bpf_object__load_progs(struct bpf_object *obj, int log_level)
7254 {
7255 	struct bpf_program *prog;
7256 	size_t i;
7257 	int err;
7258 
7259 	for (i = 0; i < obj->nr_programs; i++) {
7260 		prog = &obj->programs[i];
7261 		err = bpf_object__sanitize_prog(obj, prog);
7262 		if (err)
7263 			return err;
7264 	}
7265 
7266 	for (i = 0; i < obj->nr_programs; i++) {
7267 		prog = &obj->programs[i];
7268 		if (prog_is_subprog(obj, prog))
7269 			continue;
7270 		if (!prog->autoload) {
7271 			pr_debug("prog '%s': skipped loading\n", prog->name);
7272 			continue;
7273 		}
7274 		prog->log_level |= log_level;
7275 
7276 		if (obj->gen_loader)
7277 			bpf_program_record_relos(prog);
7278 
7279 		err = bpf_object_load_prog(obj, prog, prog->insns, prog->insns_cnt,
7280 					   obj->license, obj->kern_version, &prog->fd);
7281 		if (err) {
7282 			pr_warn("prog '%s': failed to load: %d\n", prog->name, err);
7283 			return err;
7284 		}
7285 	}
7286 
7287 	bpf_object__free_relocs(obj);
7288 	return 0;
7289 }
7290 
7291 static const struct bpf_sec_def *find_sec_def(const char *sec_name);
7292 
7293 static int bpf_object_init_progs(struct bpf_object *obj, const struct bpf_object_open_opts *opts)
7294 {
7295 	struct bpf_program *prog;
7296 	int err;
7297 
7298 	bpf_object__for_each_program(prog, obj) {
7299 		prog->sec_def = find_sec_def(prog->sec_name);
7300 		if (!prog->sec_def) {
7301 			/* couldn't guess, but user might manually specify */
7302 			pr_debug("prog '%s': unrecognized ELF section name '%s'\n",
7303 				prog->name, prog->sec_name);
7304 			continue;
7305 		}
7306 
7307 		prog->type = prog->sec_def->prog_type;
7308 		prog->expected_attach_type = prog->sec_def->expected_attach_type;
7309 
7310 		/* sec_def can have custom callback which should be called
7311 		 * after bpf_program is initialized to adjust its properties
7312 		 */
7313 		if (prog->sec_def->prog_setup_fn) {
7314 			err = prog->sec_def->prog_setup_fn(prog, prog->sec_def->cookie);
7315 			if (err < 0) {
7316 				pr_warn("prog '%s': failed to initialize: %d\n",
7317 					prog->name, err);
7318 				return err;
7319 			}
7320 		}
7321 	}
7322 
7323 	return 0;
7324 }
7325 
7326 static struct bpf_object *bpf_object_open(const char *path, const void *obj_buf, size_t obj_buf_sz,
7327 					  const struct bpf_object_open_opts *opts)
7328 {
7329 	const char *obj_name, *kconfig, *btf_tmp_path;
7330 	struct bpf_object *obj;
7331 	char tmp_name[64];
7332 	int err;
7333 	char *log_buf;
7334 	size_t log_size;
7335 	__u32 log_level;
7336 
7337 	if (elf_version(EV_CURRENT) == EV_NONE) {
7338 		pr_warn("failed to init libelf for %s\n",
7339 			path ? : "(mem buf)");
7340 		return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
7341 	}
7342 
7343 	if (!OPTS_VALID(opts, bpf_object_open_opts))
7344 		return ERR_PTR(-EINVAL);
7345 
7346 	obj_name = OPTS_GET(opts, object_name, NULL);
7347 	if (obj_buf) {
7348 		if (!obj_name) {
7349 			snprintf(tmp_name, sizeof(tmp_name), "%lx-%lx",
7350 				 (unsigned long)obj_buf,
7351 				 (unsigned long)obj_buf_sz);
7352 			obj_name = tmp_name;
7353 		}
7354 		path = obj_name;
7355 		pr_debug("loading object '%s' from buffer\n", obj_name);
7356 	}
7357 
7358 	log_buf = OPTS_GET(opts, kernel_log_buf, NULL);
7359 	log_size = OPTS_GET(opts, kernel_log_size, 0);
7360 	log_level = OPTS_GET(opts, kernel_log_level, 0);
7361 	if (log_size > UINT_MAX)
7362 		return ERR_PTR(-EINVAL);
7363 	if (log_size && !log_buf)
7364 		return ERR_PTR(-EINVAL);
7365 
7366 	obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
7367 	if (IS_ERR(obj))
7368 		return obj;
7369 
7370 	obj->log_buf = log_buf;
7371 	obj->log_size = log_size;
7372 	obj->log_level = log_level;
7373 
7374 	btf_tmp_path = OPTS_GET(opts, btf_custom_path, NULL);
7375 	if (btf_tmp_path) {
7376 		if (strlen(btf_tmp_path) >= PATH_MAX) {
7377 			err = -ENAMETOOLONG;
7378 			goto out;
7379 		}
7380 		obj->btf_custom_path = strdup(btf_tmp_path);
7381 		if (!obj->btf_custom_path) {
7382 			err = -ENOMEM;
7383 			goto out;
7384 		}
7385 	}
7386 
7387 	kconfig = OPTS_GET(opts, kconfig, NULL);
7388 	if (kconfig) {
7389 		obj->kconfig = strdup(kconfig);
7390 		if (!obj->kconfig) {
7391 			err = -ENOMEM;
7392 			goto out;
7393 		}
7394 	}
7395 
7396 	err = bpf_object__elf_init(obj);
7397 	err = err ? : bpf_object__check_endianness(obj);
7398 	err = err ? : bpf_object__elf_collect(obj);
7399 	err = err ? : bpf_object__collect_externs(obj);
7400 	err = err ? : bpf_object_fixup_btf(obj);
7401 	err = err ? : bpf_object__init_maps(obj, opts);
7402 	err = err ? : bpf_object_init_progs(obj, opts);
7403 	err = err ? : bpf_object__collect_relos(obj);
7404 	if (err)
7405 		goto out;
7406 
7407 	bpf_object__elf_finish(obj);
7408 
7409 	return obj;
7410 out:
7411 	bpf_object__close(obj);
7412 	return ERR_PTR(err);
7413 }
7414 
7415 struct bpf_object *
7416 bpf_object__open_file(const char *path, const struct bpf_object_open_opts *opts)
7417 {
7418 	if (!path)
7419 		return libbpf_err_ptr(-EINVAL);
7420 
7421 	pr_debug("loading %s\n", path);
7422 
7423 	return libbpf_ptr(bpf_object_open(path, NULL, 0, opts));
7424 }
7425 
7426 struct bpf_object *bpf_object__open(const char *path)
7427 {
7428 	return bpf_object__open_file(path, NULL);
7429 }
7430 
7431 struct bpf_object *
7432 bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
7433 		     const struct bpf_object_open_opts *opts)
7434 {
7435 	if (!obj_buf || obj_buf_sz == 0)
7436 		return libbpf_err_ptr(-EINVAL);
7437 
7438 	return libbpf_ptr(bpf_object_open(NULL, obj_buf, obj_buf_sz, opts));
7439 }
7440 
7441 static int bpf_object_unload(struct bpf_object *obj)
7442 {
7443 	size_t i;
7444 
7445 	if (!obj)
7446 		return libbpf_err(-EINVAL);
7447 
7448 	for (i = 0; i < obj->nr_maps; i++) {
7449 		zclose(obj->maps[i].fd);
7450 		if (obj->maps[i].st_ops)
7451 			zfree(&obj->maps[i].st_ops->kern_vdata);
7452 	}
7453 
7454 	for (i = 0; i < obj->nr_programs; i++)
7455 		bpf_program__unload(&obj->programs[i]);
7456 
7457 	return 0;
7458 }
7459 
7460 static int bpf_object__sanitize_maps(struct bpf_object *obj)
7461 {
7462 	struct bpf_map *m;
7463 
7464 	bpf_object__for_each_map(m, obj) {
7465 		if (!bpf_map__is_internal(m))
7466 			continue;
7467 		if (!kernel_supports(obj, FEAT_ARRAY_MMAP))
7468 			m->def.map_flags &= ~BPF_F_MMAPABLE;
7469 	}
7470 
7471 	return 0;
7472 }
7473 
7474 int libbpf_kallsyms_parse(kallsyms_cb_t cb, void *ctx)
7475 {
7476 	char sym_type, sym_name[500];
7477 	unsigned long long sym_addr;
7478 	int ret, err = 0;
7479 	FILE *f;
7480 
7481 	f = fopen("/proc/kallsyms", "re");
7482 	if (!f) {
7483 		err = -errno;
7484 		pr_warn("failed to open /proc/kallsyms: %d\n", err);
7485 		return err;
7486 	}
7487 
7488 	while (true) {
7489 		ret = fscanf(f, "%llx %c %499s%*[^\n]\n",
7490 			     &sym_addr, &sym_type, sym_name);
7491 		if (ret == EOF && feof(f))
7492 			break;
7493 		if (ret != 3) {
7494 			pr_warn("failed to read kallsyms entry: %d\n", ret);
7495 			err = -EINVAL;
7496 			break;
7497 		}
7498 
7499 		err = cb(sym_addr, sym_type, sym_name, ctx);
7500 		if (err)
7501 			break;
7502 	}
7503 
7504 	fclose(f);
7505 	return err;
7506 }
7507 
7508 static int kallsyms_cb(unsigned long long sym_addr, char sym_type,
7509 		       const char *sym_name, void *ctx)
7510 {
7511 	struct bpf_object *obj = ctx;
7512 	const struct btf_type *t;
7513 	struct extern_desc *ext;
7514 
7515 	ext = find_extern_by_name(obj, sym_name);
7516 	if (!ext || ext->type != EXT_KSYM)
7517 		return 0;
7518 
7519 	t = btf__type_by_id(obj->btf, ext->btf_id);
7520 	if (!btf_is_var(t))
7521 		return 0;
7522 
7523 	if (ext->is_set && ext->ksym.addr != sym_addr) {
7524 		pr_warn("extern (ksym) '%s': resolution is ambiguous: 0x%llx or 0x%llx\n",
7525 			sym_name, ext->ksym.addr, sym_addr);
7526 		return -EINVAL;
7527 	}
7528 	if (!ext->is_set) {
7529 		ext->is_set = true;
7530 		ext->ksym.addr = sym_addr;
7531 		pr_debug("extern (ksym) '%s': set to 0x%llx\n", sym_name, sym_addr);
7532 	}
7533 	return 0;
7534 }
7535 
7536 static int bpf_object__read_kallsyms_file(struct bpf_object *obj)
7537 {
7538 	return libbpf_kallsyms_parse(kallsyms_cb, obj);
7539 }
7540 
7541 static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
7542 			    __u16 kind, struct btf **res_btf,
7543 			    struct module_btf **res_mod_btf)
7544 {
7545 	struct module_btf *mod_btf;
7546 	struct btf *btf;
7547 	int i, id, err;
7548 
7549 	btf = obj->btf_vmlinux;
7550 	mod_btf = NULL;
7551 	id = btf__find_by_name_kind(btf, ksym_name, kind);
7552 
7553 	if (id == -ENOENT) {
7554 		err = load_module_btfs(obj);
7555 		if (err)
7556 			return err;
7557 
7558 		for (i = 0; i < obj->btf_module_cnt; i++) {
7559 			/* we assume module_btf's BTF FD is always >0 */
7560 			mod_btf = &obj->btf_modules[i];
7561 			btf = mod_btf->btf;
7562 			id = btf__find_by_name_kind_own(btf, ksym_name, kind);
7563 			if (id != -ENOENT)
7564 				break;
7565 		}
7566 	}
7567 	if (id <= 0)
7568 		return -ESRCH;
7569 
7570 	*res_btf = btf;
7571 	*res_mod_btf = mod_btf;
7572 	return id;
7573 }
7574 
7575 static int bpf_object__resolve_ksym_var_btf_id(struct bpf_object *obj,
7576 					       struct extern_desc *ext)
7577 {
7578 	const struct btf_type *targ_var, *targ_type;
7579 	__u32 targ_type_id, local_type_id;
7580 	struct module_btf *mod_btf = NULL;
7581 	const char *targ_var_name;
7582 	struct btf *btf = NULL;
7583 	int id, err;
7584 
7585 	id = find_ksym_btf_id(obj, ext->name, BTF_KIND_VAR, &btf, &mod_btf);
7586 	if (id < 0) {
7587 		if (id == -ESRCH && ext->is_weak)
7588 			return 0;
7589 		pr_warn("extern (var ksym) '%s': not found in kernel BTF\n",
7590 			ext->name);
7591 		return id;
7592 	}
7593 
7594 	/* find local type_id */
7595 	local_type_id = ext->ksym.type_id;
7596 
7597 	/* find target type_id */
7598 	targ_var = btf__type_by_id(btf, id);
7599 	targ_var_name = btf__name_by_offset(btf, targ_var->name_off);
7600 	targ_type = skip_mods_and_typedefs(btf, targ_var->type, &targ_type_id);
7601 
7602 	err = bpf_core_types_are_compat(obj->btf, local_type_id,
7603 					btf, targ_type_id);
7604 	if (err <= 0) {
7605 		const struct btf_type *local_type;
7606 		const char *targ_name, *local_name;
7607 
7608 		local_type = btf__type_by_id(obj->btf, local_type_id);
7609 		local_name = btf__name_by_offset(obj->btf, local_type->name_off);
7610 		targ_name = btf__name_by_offset(btf, targ_type->name_off);
7611 
7612 		pr_warn("extern (var ksym) '%s': incompatible types, expected [%d] %s %s, but kernel has [%d] %s %s\n",
7613 			ext->name, local_type_id,
7614 			btf_kind_str(local_type), local_name, targ_type_id,
7615 			btf_kind_str(targ_type), targ_name);
7616 		return -EINVAL;
7617 	}
7618 
7619 	ext->is_set = true;
7620 	ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
7621 	ext->ksym.kernel_btf_id = id;
7622 	pr_debug("extern (var ksym) '%s': resolved to [%d] %s %s\n",
7623 		 ext->name, id, btf_kind_str(targ_var), targ_var_name);
7624 
7625 	return 0;
7626 }
7627 
7628 static int bpf_object__resolve_ksym_func_btf_id(struct bpf_object *obj,
7629 						struct extern_desc *ext)
7630 {
7631 	int local_func_proto_id, kfunc_proto_id, kfunc_id;
7632 	struct module_btf *mod_btf = NULL;
7633 	const struct btf_type *kern_func;
7634 	struct btf *kern_btf = NULL;
7635 	int ret;
7636 
7637 	local_func_proto_id = ext->ksym.type_id;
7638 
7639 	kfunc_id = find_ksym_btf_id(obj, ext->essent_name ?: ext->name, BTF_KIND_FUNC, &kern_btf,
7640 				    &mod_btf);
7641 	if (kfunc_id < 0) {
7642 		if (kfunc_id == -ESRCH && ext->is_weak)
7643 			return 0;
7644 		pr_warn("extern (func ksym) '%s': not found in kernel or module BTFs\n",
7645 			ext->name);
7646 		return kfunc_id;
7647 	}
7648 
7649 	kern_func = btf__type_by_id(kern_btf, kfunc_id);
7650 	kfunc_proto_id = kern_func->type;
7651 
7652 	ret = bpf_core_types_are_compat(obj->btf, local_func_proto_id,
7653 					kern_btf, kfunc_proto_id);
7654 	if (ret <= 0) {
7655 		if (ext->is_weak)
7656 			return 0;
7657 
7658 		pr_warn("extern (func ksym) '%s': func_proto [%d] incompatible with %s [%d]\n",
7659 			ext->name, local_func_proto_id,
7660 			mod_btf ? mod_btf->name : "vmlinux", kfunc_proto_id);
7661 		return -EINVAL;
7662 	}
7663 
7664 	/* set index for module BTF fd in fd_array, if unset */
7665 	if (mod_btf && !mod_btf->fd_array_idx) {
7666 		/* insn->off is s16 */
7667 		if (obj->fd_array_cnt == INT16_MAX) {
7668 			pr_warn("extern (func ksym) '%s': module BTF fd index %d too big to fit in bpf_insn offset\n",
7669 				ext->name, mod_btf->fd_array_idx);
7670 			return -E2BIG;
7671 		}
7672 		/* Cannot use index 0 for module BTF fd */
7673 		if (!obj->fd_array_cnt)
7674 			obj->fd_array_cnt = 1;
7675 
7676 		ret = libbpf_ensure_mem((void **)&obj->fd_array, &obj->fd_array_cap, sizeof(int),
7677 					obj->fd_array_cnt + 1);
7678 		if (ret)
7679 			return ret;
7680 		mod_btf->fd_array_idx = obj->fd_array_cnt;
7681 		/* we assume module BTF FD is always >0 */
7682 		obj->fd_array[obj->fd_array_cnt++] = mod_btf->fd;
7683 	}
7684 
7685 	ext->is_set = true;
7686 	ext->ksym.kernel_btf_id = kfunc_id;
7687 	ext->ksym.btf_fd_idx = mod_btf ? mod_btf->fd_array_idx : 0;
7688 	/* Also set kernel_btf_obj_fd to make sure that bpf_object__relocate_data()
7689 	 * populates FD into ld_imm64 insn when it's used to point to kfunc.
7690 	 * {kernel_btf_id, btf_fd_idx} -> fixup bpf_call.
7691 	 * {kernel_btf_id, kernel_btf_obj_fd} -> fixup ld_imm64.
7692 	 */
7693 	ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
7694 	pr_debug("extern (func ksym) '%s': resolved to %s [%d]\n",
7695 		 ext->name, mod_btf ? mod_btf->name : "vmlinux", kfunc_id);
7696 
7697 	return 0;
7698 }
7699 
7700 static int bpf_object__resolve_ksyms_btf_id(struct bpf_object *obj)
7701 {
7702 	const struct btf_type *t;
7703 	struct extern_desc *ext;
7704 	int i, err;
7705 
7706 	for (i = 0; i < obj->nr_extern; i++) {
7707 		ext = &obj->externs[i];
7708 		if (ext->type != EXT_KSYM || !ext->ksym.type_id)
7709 			continue;
7710 
7711 		if (obj->gen_loader) {
7712 			ext->is_set = true;
7713 			ext->ksym.kernel_btf_obj_fd = 0;
7714 			ext->ksym.kernel_btf_id = 0;
7715 			continue;
7716 		}
7717 		t = btf__type_by_id(obj->btf, ext->btf_id);
7718 		if (btf_is_var(t))
7719 			err = bpf_object__resolve_ksym_var_btf_id(obj, ext);
7720 		else
7721 			err = bpf_object__resolve_ksym_func_btf_id(obj, ext);
7722 		if (err)
7723 			return err;
7724 	}
7725 	return 0;
7726 }
7727 
7728 static int bpf_object__resolve_externs(struct bpf_object *obj,
7729 				       const char *extra_kconfig)
7730 {
7731 	bool need_config = false, need_kallsyms = false;
7732 	bool need_vmlinux_btf = false;
7733 	struct extern_desc *ext;
7734 	void *kcfg_data = NULL;
7735 	int err, i;
7736 
7737 	if (obj->nr_extern == 0)
7738 		return 0;
7739 
7740 	if (obj->kconfig_map_idx >= 0)
7741 		kcfg_data = obj->maps[obj->kconfig_map_idx].mmaped;
7742 
7743 	for (i = 0; i < obj->nr_extern; i++) {
7744 		ext = &obj->externs[i];
7745 
7746 		if (ext->type == EXT_KSYM) {
7747 			if (ext->ksym.type_id)
7748 				need_vmlinux_btf = true;
7749 			else
7750 				need_kallsyms = true;
7751 			continue;
7752 		} else if (ext->type == EXT_KCFG) {
7753 			void *ext_ptr = kcfg_data + ext->kcfg.data_off;
7754 			__u64 value = 0;
7755 
7756 			/* Kconfig externs need actual /proc/config.gz */
7757 			if (str_has_pfx(ext->name, "CONFIG_")) {
7758 				need_config = true;
7759 				continue;
7760 			}
7761 
7762 			/* Virtual kcfg externs are customly handled by libbpf */
7763 			if (strcmp(ext->name, "LINUX_KERNEL_VERSION") == 0) {
7764 				value = get_kernel_version();
7765 				if (!value) {
7766 					pr_warn("extern (kcfg) '%s': failed to get kernel version\n", ext->name);
7767 					return -EINVAL;
7768 				}
7769 			} else if (strcmp(ext->name, "LINUX_HAS_BPF_COOKIE") == 0) {
7770 				value = kernel_supports(obj, FEAT_BPF_COOKIE);
7771 			} else if (strcmp(ext->name, "LINUX_HAS_SYSCALL_WRAPPER") == 0) {
7772 				value = kernel_supports(obj, FEAT_SYSCALL_WRAPPER);
7773 			} else if (!str_has_pfx(ext->name, "LINUX_") || !ext->is_weak) {
7774 				/* Currently libbpf supports only CONFIG_ and LINUX_ prefixed
7775 				 * __kconfig externs, where LINUX_ ones are virtual and filled out
7776 				 * customly by libbpf (their values don't come from Kconfig).
7777 				 * If LINUX_xxx variable is not recognized by libbpf, but is marked
7778 				 * __weak, it defaults to zero value, just like for CONFIG_xxx
7779 				 * externs.
7780 				 */
7781 				pr_warn("extern (kcfg) '%s': unrecognized virtual extern\n", ext->name);
7782 				return -EINVAL;
7783 			}
7784 
7785 			err = set_kcfg_value_num(ext, ext_ptr, value);
7786 			if (err)
7787 				return err;
7788 			pr_debug("extern (kcfg) '%s': set to 0x%llx\n",
7789 				 ext->name, (long long)value);
7790 		} else {
7791 			pr_warn("extern '%s': unrecognized extern kind\n", ext->name);
7792 			return -EINVAL;
7793 		}
7794 	}
7795 	if (need_config && extra_kconfig) {
7796 		err = bpf_object__read_kconfig_mem(obj, extra_kconfig, kcfg_data);
7797 		if (err)
7798 			return -EINVAL;
7799 		need_config = false;
7800 		for (i = 0; i < obj->nr_extern; i++) {
7801 			ext = &obj->externs[i];
7802 			if (ext->type == EXT_KCFG && !ext->is_set) {
7803 				need_config = true;
7804 				break;
7805 			}
7806 		}
7807 	}
7808 	if (need_config) {
7809 		err = bpf_object__read_kconfig_file(obj, kcfg_data);
7810 		if (err)
7811 			return -EINVAL;
7812 	}
7813 	if (need_kallsyms) {
7814 		err = bpf_object__read_kallsyms_file(obj);
7815 		if (err)
7816 			return -EINVAL;
7817 	}
7818 	if (need_vmlinux_btf) {
7819 		err = bpf_object__resolve_ksyms_btf_id(obj);
7820 		if (err)
7821 			return -EINVAL;
7822 	}
7823 	for (i = 0; i < obj->nr_extern; i++) {
7824 		ext = &obj->externs[i];
7825 
7826 		if (!ext->is_set && !ext->is_weak) {
7827 			pr_warn("extern '%s' (strong): not resolved\n", ext->name);
7828 			return -ESRCH;
7829 		} else if (!ext->is_set) {
7830 			pr_debug("extern '%s' (weak): not resolved, defaulting to zero\n",
7831 				 ext->name);
7832 		}
7833 	}
7834 
7835 	return 0;
7836 }
7837 
7838 static void bpf_map_prepare_vdata(const struct bpf_map *map)
7839 {
7840 	struct bpf_struct_ops *st_ops;
7841 	__u32 i;
7842 
7843 	st_ops = map->st_ops;
7844 	for (i = 0; i < btf_vlen(st_ops->type); i++) {
7845 		struct bpf_program *prog = st_ops->progs[i];
7846 		void *kern_data;
7847 		int prog_fd;
7848 
7849 		if (!prog)
7850 			continue;
7851 
7852 		prog_fd = bpf_program__fd(prog);
7853 		kern_data = st_ops->kern_vdata + st_ops->kern_func_off[i];
7854 		*(unsigned long *)kern_data = prog_fd;
7855 	}
7856 }
7857 
7858 static int bpf_object_prepare_struct_ops(struct bpf_object *obj)
7859 {
7860 	int i;
7861 
7862 	for (i = 0; i < obj->nr_maps; i++)
7863 		if (bpf_map__is_struct_ops(&obj->maps[i]))
7864 			bpf_map_prepare_vdata(&obj->maps[i]);
7865 
7866 	return 0;
7867 }
7868 
7869 static int bpf_object_load(struct bpf_object *obj, int extra_log_level, const char *target_btf_path)
7870 {
7871 	int err, i;
7872 
7873 	if (!obj)
7874 		return libbpf_err(-EINVAL);
7875 
7876 	if (obj->loaded) {
7877 		pr_warn("object '%s': load can't be attempted twice\n", obj->name);
7878 		return libbpf_err(-EINVAL);
7879 	}
7880 
7881 	if (obj->gen_loader)
7882 		bpf_gen__init(obj->gen_loader, extra_log_level, obj->nr_programs, obj->nr_maps);
7883 
7884 	err = bpf_object__probe_loading(obj);
7885 	err = err ? : bpf_object__load_vmlinux_btf(obj, false);
7886 	err = err ? : bpf_object__resolve_externs(obj, obj->kconfig);
7887 	err = err ? : bpf_object__sanitize_and_load_btf(obj);
7888 	err = err ? : bpf_object__sanitize_maps(obj);
7889 	err = err ? : bpf_object__init_kern_struct_ops_maps(obj);
7890 	err = err ? : bpf_object__create_maps(obj);
7891 	err = err ? : bpf_object__relocate(obj, obj->btf_custom_path ? : target_btf_path);
7892 	err = err ? : bpf_object__load_progs(obj, extra_log_level);
7893 	err = err ? : bpf_object_init_prog_arrays(obj);
7894 	err = err ? : bpf_object_prepare_struct_ops(obj);
7895 
7896 	if (obj->gen_loader) {
7897 		/* reset FDs */
7898 		if (obj->btf)
7899 			btf__set_fd(obj->btf, -1);
7900 		for (i = 0; i < obj->nr_maps; i++)
7901 			obj->maps[i].fd = -1;
7902 		if (!err)
7903 			err = bpf_gen__finish(obj->gen_loader, obj->nr_programs, obj->nr_maps);
7904 	}
7905 
7906 	/* clean up fd_array */
7907 	zfree(&obj->fd_array);
7908 
7909 	/* clean up module BTFs */
7910 	for (i = 0; i < obj->btf_module_cnt; i++) {
7911 		close(obj->btf_modules[i].fd);
7912 		btf__free(obj->btf_modules[i].btf);
7913 		free(obj->btf_modules[i].name);
7914 	}
7915 	free(obj->btf_modules);
7916 
7917 	/* clean up vmlinux BTF */
7918 	btf__free(obj->btf_vmlinux);
7919 	obj->btf_vmlinux = NULL;
7920 
7921 	obj->loaded = true; /* doesn't matter if successfully or not */
7922 
7923 	if (err)
7924 		goto out;
7925 
7926 	return 0;
7927 out:
7928 	/* unpin any maps that were auto-pinned during load */
7929 	for (i = 0; i < obj->nr_maps; i++)
7930 		if (obj->maps[i].pinned && !obj->maps[i].reused)
7931 			bpf_map__unpin(&obj->maps[i], NULL);
7932 
7933 	bpf_object_unload(obj);
7934 	pr_warn("failed to load object '%s'\n", obj->path);
7935 	return libbpf_err(err);
7936 }
7937 
7938 int bpf_object__load(struct bpf_object *obj)
7939 {
7940 	return bpf_object_load(obj, 0, NULL);
7941 }
7942 
7943 static int make_parent_dir(const char *path)
7944 {
7945 	char *cp, errmsg[STRERR_BUFSIZE];
7946 	char *dname, *dir;
7947 	int err = 0;
7948 
7949 	dname = strdup(path);
7950 	if (dname == NULL)
7951 		return -ENOMEM;
7952 
7953 	dir = dirname(dname);
7954 	if (mkdir(dir, 0700) && errno != EEXIST)
7955 		err = -errno;
7956 
7957 	free(dname);
7958 	if (err) {
7959 		cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
7960 		pr_warn("failed to mkdir %s: %s\n", path, cp);
7961 	}
7962 	return err;
7963 }
7964 
7965 static int check_path(const char *path)
7966 {
7967 	char *cp, errmsg[STRERR_BUFSIZE];
7968 	struct statfs st_fs;
7969 	char *dname, *dir;
7970 	int err = 0;
7971 
7972 	if (path == NULL)
7973 		return -EINVAL;
7974 
7975 	dname = strdup(path);
7976 	if (dname == NULL)
7977 		return -ENOMEM;
7978 
7979 	dir = dirname(dname);
7980 	if (statfs(dir, &st_fs)) {
7981 		cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
7982 		pr_warn("failed to statfs %s: %s\n", dir, cp);
7983 		err = -errno;
7984 	}
7985 	free(dname);
7986 
7987 	if (!err && st_fs.f_type != BPF_FS_MAGIC) {
7988 		pr_warn("specified path %s is not on BPF FS\n", path);
7989 		err = -EINVAL;
7990 	}
7991 
7992 	return err;
7993 }
7994 
7995 int bpf_program__pin(struct bpf_program *prog, const char *path)
7996 {
7997 	char *cp, errmsg[STRERR_BUFSIZE];
7998 	int err;
7999 
8000 	if (prog->fd < 0) {
8001 		pr_warn("prog '%s': can't pin program that wasn't loaded\n", prog->name);
8002 		return libbpf_err(-EINVAL);
8003 	}
8004 
8005 	err = make_parent_dir(path);
8006 	if (err)
8007 		return libbpf_err(err);
8008 
8009 	err = check_path(path);
8010 	if (err)
8011 		return libbpf_err(err);
8012 
8013 	if (bpf_obj_pin(prog->fd, path)) {
8014 		err = -errno;
8015 		cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
8016 		pr_warn("prog '%s': failed to pin at '%s': %s\n", prog->name, path, cp);
8017 		return libbpf_err(err);
8018 	}
8019 
8020 	pr_debug("prog '%s': pinned at '%s'\n", prog->name, path);
8021 	return 0;
8022 }
8023 
8024 int bpf_program__unpin(struct bpf_program *prog, const char *path)
8025 {
8026 	int err;
8027 
8028 	if (prog->fd < 0) {
8029 		pr_warn("prog '%s': can't unpin program that wasn't loaded\n", prog->name);
8030 		return libbpf_err(-EINVAL);
8031 	}
8032 
8033 	err = check_path(path);
8034 	if (err)
8035 		return libbpf_err(err);
8036 
8037 	err = unlink(path);
8038 	if (err)
8039 		return libbpf_err(-errno);
8040 
8041 	pr_debug("prog '%s': unpinned from '%s'\n", prog->name, path);
8042 	return 0;
8043 }
8044 
8045 int bpf_map__pin(struct bpf_map *map, const char *path)
8046 {
8047 	char *cp, errmsg[STRERR_BUFSIZE];
8048 	int err;
8049 
8050 	if (map == NULL) {
8051 		pr_warn("invalid map pointer\n");
8052 		return libbpf_err(-EINVAL);
8053 	}
8054 
8055 	if (map->pin_path) {
8056 		if (path && strcmp(path, map->pin_path)) {
8057 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
8058 				bpf_map__name(map), map->pin_path, path);
8059 			return libbpf_err(-EINVAL);
8060 		} else if (map->pinned) {
8061 			pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
8062 				 bpf_map__name(map), map->pin_path);
8063 			return 0;
8064 		}
8065 	} else {
8066 		if (!path) {
8067 			pr_warn("missing a path to pin map '%s' at\n",
8068 				bpf_map__name(map));
8069 			return libbpf_err(-EINVAL);
8070 		} else if (map->pinned) {
8071 			pr_warn("map '%s' already pinned\n", bpf_map__name(map));
8072 			return libbpf_err(-EEXIST);
8073 		}
8074 
8075 		map->pin_path = strdup(path);
8076 		if (!map->pin_path) {
8077 			err = -errno;
8078 			goto out_err;
8079 		}
8080 	}
8081 
8082 	err = make_parent_dir(map->pin_path);
8083 	if (err)
8084 		return libbpf_err(err);
8085 
8086 	err = check_path(map->pin_path);
8087 	if (err)
8088 		return libbpf_err(err);
8089 
8090 	if (bpf_obj_pin(map->fd, map->pin_path)) {
8091 		err = -errno;
8092 		goto out_err;
8093 	}
8094 
8095 	map->pinned = true;
8096 	pr_debug("pinned map '%s'\n", map->pin_path);
8097 
8098 	return 0;
8099 
8100 out_err:
8101 	cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
8102 	pr_warn("failed to pin map: %s\n", cp);
8103 	return libbpf_err(err);
8104 }
8105 
8106 int bpf_map__unpin(struct bpf_map *map, const char *path)
8107 {
8108 	int err;
8109 
8110 	if (map == NULL) {
8111 		pr_warn("invalid map pointer\n");
8112 		return libbpf_err(-EINVAL);
8113 	}
8114 
8115 	if (map->pin_path) {
8116 		if (path && strcmp(path, map->pin_path)) {
8117 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
8118 				bpf_map__name(map), map->pin_path, path);
8119 			return libbpf_err(-EINVAL);
8120 		}
8121 		path = map->pin_path;
8122 	} else if (!path) {
8123 		pr_warn("no path to unpin map '%s' from\n",
8124 			bpf_map__name(map));
8125 		return libbpf_err(-EINVAL);
8126 	}
8127 
8128 	err = check_path(path);
8129 	if (err)
8130 		return libbpf_err(err);
8131 
8132 	err = unlink(path);
8133 	if (err != 0)
8134 		return libbpf_err(-errno);
8135 
8136 	map->pinned = false;
8137 	pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path);
8138 
8139 	return 0;
8140 }
8141 
8142 int bpf_map__set_pin_path(struct bpf_map *map, const char *path)
8143 {
8144 	char *new = NULL;
8145 
8146 	if (path) {
8147 		new = strdup(path);
8148 		if (!new)
8149 			return libbpf_err(-errno);
8150 	}
8151 
8152 	free(map->pin_path);
8153 	map->pin_path = new;
8154 	return 0;
8155 }
8156 
8157 __alias(bpf_map__pin_path)
8158 const char *bpf_map__get_pin_path(const struct bpf_map *map);
8159 
8160 const char *bpf_map__pin_path(const struct bpf_map *map)
8161 {
8162 	return map->pin_path;
8163 }
8164 
8165 bool bpf_map__is_pinned(const struct bpf_map *map)
8166 {
8167 	return map->pinned;
8168 }
8169 
8170 static void sanitize_pin_path(char *s)
8171 {
8172 	/* bpffs disallows periods in path names */
8173 	while (*s) {
8174 		if (*s == '.')
8175 			*s = '_';
8176 		s++;
8177 	}
8178 }
8179 
8180 int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
8181 {
8182 	struct bpf_map *map;
8183 	int err;
8184 
8185 	if (!obj)
8186 		return libbpf_err(-ENOENT);
8187 
8188 	if (!obj->loaded) {
8189 		pr_warn("object not yet loaded; load it first\n");
8190 		return libbpf_err(-ENOENT);
8191 	}
8192 
8193 	bpf_object__for_each_map(map, obj) {
8194 		char *pin_path = NULL;
8195 		char buf[PATH_MAX];
8196 
8197 		if (!map->autocreate)
8198 			continue;
8199 
8200 		if (path) {
8201 			err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
8202 			if (err)
8203 				goto err_unpin_maps;
8204 			sanitize_pin_path(buf);
8205 			pin_path = buf;
8206 		} else if (!map->pin_path) {
8207 			continue;
8208 		}
8209 
8210 		err = bpf_map__pin(map, pin_path);
8211 		if (err)
8212 			goto err_unpin_maps;
8213 	}
8214 
8215 	return 0;
8216 
8217 err_unpin_maps:
8218 	while ((map = bpf_object__prev_map(obj, map))) {
8219 		if (!map->pin_path)
8220 			continue;
8221 
8222 		bpf_map__unpin(map, NULL);
8223 	}
8224 
8225 	return libbpf_err(err);
8226 }
8227 
8228 int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
8229 {
8230 	struct bpf_map *map;
8231 	int err;
8232 
8233 	if (!obj)
8234 		return libbpf_err(-ENOENT);
8235 
8236 	bpf_object__for_each_map(map, obj) {
8237 		char *pin_path = NULL;
8238 		char buf[PATH_MAX];
8239 
8240 		if (path) {
8241 			err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
8242 			if (err)
8243 				return libbpf_err(err);
8244 			sanitize_pin_path(buf);
8245 			pin_path = buf;
8246 		} else if (!map->pin_path) {
8247 			continue;
8248 		}
8249 
8250 		err = bpf_map__unpin(map, pin_path);
8251 		if (err)
8252 			return libbpf_err(err);
8253 	}
8254 
8255 	return 0;
8256 }
8257 
8258 int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
8259 {
8260 	struct bpf_program *prog;
8261 	char buf[PATH_MAX];
8262 	int err;
8263 
8264 	if (!obj)
8265 		return libbpf_err(-ENOENT);
8266 
8267 	if (!obj->loaded) {
8268 		pr_warn("object not yet loaded; load it first\n");
8269 		return libbpf_err(-ENOENT);
8270 	}
8271 
8272 	bpf_object__for_each_program(prog, obj) {
8273 		err = pathname_concat(buf, sizeof(buf), path, prog->name);
8274 		if (err)
8275 			goto err_unpin_programs;
8276 
8277 		err = bpf_program__pin(prog, buf);
8278 		if (err)
8279 			goto err_unpin_programs;
8280 	}
8281 
8282 	return 0;
8283 
8284 err_unpin_programs:
8285 	while ((prog = bpf_object__prev_program(obj, prog))) {
8286 		if (pathname_concat(buf, sizeof(buf), path, prog->name))
8287 			continue;
8288 
8289 		bpf_program__unpin(prog, buf);
8290 	}
8291 
8292 	return libbpf_err(err);
8293 }
8294 
8295 int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
8296 {
8297 	struct bpf_program *prog;
8298 	int err;
8299 
8300 	if (!obj)
8301 		return libbpf_err(-ENOENT);
8302 
8303 	bpf_object__for_each_program(prog, obj) {
8304 		char buf[PATH_MAX];
8305 
8306 		err = pathname_concat(buf, sizeof(buf), path, prog->name);
8307 		if (err)
8308 			return libbpf_err(err);
8309 
8310 		err = bpf_program__unpin(prog, buf);
8311 		if (err)
8312 			return libbpf_err(err);
8313 	}
8314 
8315 	return 0;
8316 }
8317 
8318 int bpf_object__pin(struct bpf_object *obj, const char *path)
8319 {
8320 	int err;
8321 
8322 	err = bpf_object__pin_maps(obj, path);
8323 	if (err)
8324 		return libbpf_err(err);
8325 
8326 	err = bpf_object__pin_programs(obj, path);
8327 	if (err) {
8328 		bpf_object__unpin_maps(obj, path);
8329 		return libbpf_err(err);
8330 	}
8331 
8332 	return 0;
8333 }
8334 
8335 static void bpf_map__destroy(struct bpf_map *map)
8336 {
8337 	if (map->inner_map) {
8338 		bpf_map__destroy(map->inner_map);
8339 		zfree(&map->inner_map);
8340 	}
8341 
8342 	zfree(&map->init_slots);
8343 	map->init_slots_sz = 0;
8344 
8345 	if (map->mmaped) {
8346 		size_t mmap_sz;
8347 
8348 		mmap_sz = bpf_map_mmap_sz(map->def.value_size, map->def.max_entries);
8349 		munmap(map->mmaped, mmap_sz);
8350 		map->mmaped = NULL;
8351 	}
8352 
8353 	if (map->st_ops) {
8354 		zfree(&map->st_ops->data);
8355 		zfree(&map->st_ops->progs);
8356 		zfree(&map->st_ops->kern_func_off);
8357 		zfree(&map->st_ops);
8358 	}
8359 
8360 	zfree(&map->name);
8361 	zfree(&map->real_name);
8362 	zfree(&map->pin_path);
8363 
8364 	if (map->fd >= 0)
8365 		zclose(map->fd);
8366 }
8367 
8368 void bpf_object__close(struct bpf_object *obj)
8369 {
8370 	size_t i;
8371 
8372 	if (IS_ERR_OR_NULL(obj))
8373 		return;
8374 
8375 	usdt_manager_free(obj->usdt_man);
8376 	obj->usdt_man = NULL;
8377 
8378 	bpf_gen__free(obj->gen_loader);
8379 	bpf_object__elf_finish(obj);
8380 	bpf_object_unload(obj);
8381 	btf__free(obj->btf);
8382 	btf_ext__free(obj->btf_ext);
8383 
8384 	for (i = 0; i < obj->nr_maps; i++)
8385 		bpf_map__destroy(&obj->maps[i]);
8386 
8387 	zfree(&obj->btf_custom_path);
8388 	zfree(&obj->kconfig);
8389 
8390 	for (i = 0; i < obj->nr_extern; i++)
8391 		zfree(&obj->externs[i].essent_name);
8392 
8393 	zfree(&obj->externs);
8394 	obj->nr_extern = 0;
8395 
8396 	zfree(&obj->maps);
8397 	obj->nr_maps = 0;
8398 
8399 	if (obj->programs && obj->nr_programs) {
8400 		for (i = 0; i < obj->nr_programs; i++)
8401 			bpf_program__exit(&obj->programs[i]);
8402 	}
8403 	zfree(&obj->programs);
8404 
8405 	free(obj);
8406 }
8407 
8408 const char *bpf_object__name(const struct bpf_object *obj)
8409 {
8410 	return obj ? obj->name : libbpf_err_ptr(-EINVAL);
8411 }
8412 
8413 unsigned int bpf_object__kversion(const struct bpf_object *obj)
8414 {
8415 	return obj ? obj->kern_version : 0;
8416 }
8417 
8418 struct btf *bpf_object__btf(const struct bpf_object *obj)
8419 {
8420 	return obj ? obj->btf : NULL;
8421 }
8422 
8423 int bpf_object__btf_fd(const struct bpf_object *obj)
8424 {
8425 	return obj->btf ? btf__fd(obj->btf) : -1;
8426 }
8427 
8428 int bpf_object__set_kversion(struct bpf_object *obj, __u32 kern_version)
8429 {
8430 	if (obj->loaded)
8431 		return libbpf_err(-EINVAL);
8432 
8433 	obj->kern_version = kern_version;
8434 
8435 	return 0;
8436 }
8437 
8438 int bpf_object__gen_loader(struct bpf_object *obj, struct gen_loader_opts *opts)
8439 {
8440 	struct bpf_gen *gen;
8441 
8442 	if (!opts)
8443 		return -EFAULT;
8444 	if (!OPTS_VALID(opts, gen_loader_opts))
8445 		return -EINVAL;
8446 	gen = calloc(sizeof(*gen), 1);
8447 	if (!gen)
8448 		return -ENOMEM;
8449 	gen->opts = opts;
8450 	obj->gen_loader = gen;
8451 	return 0;
8452 }
8453 
8454 static struct bpf_program *
8455 __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
8456 		    bool forward)
8457 {
8458 	size_t nr_programs = obj->nr_programs;
8459 	ssize_t idx;
8460 
8461 	if (!nr_programs)
8462 		return NULL;
8463 
8464 	if (!p)
8465 		/* Iter from the beginning */
8466 		return forward ? &obj->programs[0] :
8467 			&obj->programs[nr_programs - 1];
8468 
8469 	if (p->obj != obj) {
8470 		pr_warn("error: program handler doesn't match object\n");
8471 		return errno = EINVAL, NULL;
8472 	}
8473 
8474 	idx = (p - obj->programs) + (forward ? 1 : -1);
8475 	if (idx >= obj->nr_programs || idx < 0)
8476 		return NULL;
8477 	return &obj->programs[idx];
8478 }
8479 
8480 struct bpf_program *
8481 bpf_object__next_program(const struct bpf_object *obj, struct bpf_program *prev)
8482 {
8483 	struct bpf_program *prog = prev;
8484 
8485 	do {
8486 		prog = __bpf_program__iter(prog, obj, true);
8487 	} while (prog && prog_is_subprog(obj, prog));
8488 
8489 	return prog;
8490 }
8491 
8492 struct bpf_program *
8493 bpf_object__prev_program(const struct bpf_object *obj, struct bpf_program *next)
8494 {
8495 	struct bpf_program *prog = next;
8496 
8497 	do {
8498 		prog = __bpf_program__iter(prog, obj, false);
8499 	} while (prog && prog_is_subprog(obj, prog));
8500 
8501 	return prog;
8502 }
8503 
8504 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
8505 {
8506 	prog->prog_ifindex = ifindex;
8507 }
8508 
8509 const char *bpf_program__name(const struct bpf_program *prog)
8510 {
8511 	return prog->name;
8512 }
8513 
8514 const char *bpf_program__section_name(const struct bpf_program *prog)
8515 {
8516 	return prog->sec_name;
8517 }
8518 
8519 bool bpf_program__autoload(const struct bpf_program *prog)
8520 {
8521 	return prog->autoload;
8522 }
8523 
8524 int bpf_program__set_autoload(struct bpf_program *prog, bool autoload)
8525 {
8526 	if (prog->obj->loaded)
8527 		return libbpf_err(-EINVAL);
8528 
8529 	prog->autoload = autoload;
8530 	return 0;
8531 }
8532 
8533 bool bpf_program__autoattach(const struct bpf_program *prog)
8534 {
8535 	return prog->autoattach;
8536 }
8537 
8538 void bpf_program__set_autoattach(struct bpf_program *prog, bool autoattach)
8539 {
8540 	prog->autoattach = autoattach;
8541 }
8542 
8543 const struct bpf_insn *bpf_program__insns(const struct bpf_program *prog)
8544 {
8545 	return prog->insns;
8546 }
8547 
8548 size_t bpf_program__insn_cnt(const struct bpf_program *prog)
8549 {
8550 	return prog->insns_cnt;
8551 }
8552 
8553 int bpf_program__set_insns(struct bpf_program *prog,
8554 			   struct bpf_insn *new_insns, size_t new_insn_cnt)
8555 {
8556 	struct bpf_insn *insns;
8557 
8558 	if (prog->obj->loaded)
8559 		return -EBUSY;
8560 
8561 	insns = libbpf_reallocarray(prog->insns, new_insn_cnt, sizeof(*insns));
8562 	/* NULL is a valid return from reallocarray if the new count is zero */
8563 	if (!insns && new_insn_cnt) {
8564 		pr_warn("prog '%s': failed to realloc prog code\n", prog->name);
8565 		return -ENOMEM;
8566 	}
8567 	memcpy(insns, new_insns, new_insn_cnt * sizeof(*insns));
8568 
8569 	prog->insns = insns;
8570 	prog->insns_cnt = new_insn_cnt;
8571 	return 0;
8572 }
8573 
8574 int bpf_program__fd(const struct bpf_program *prog)
8575 {
8576 	if (!prog)
8577 		return libbpf_err(-EINVAL);
8578 
8579 	if (prog->fd < 0)
8580 		return libbpf_err(-ENOENT);
8581 
8582 	return prog->fd;
8583 }
8584 
8585 __alias(bpf_program__type)
8586 enum bpf_prog_type bpf_program__get_type(const struct bpf_program *prog);
8587 
8588 enum bpf_prog_type bpf_program__type(const struct bpf_program *prog)
8589 {
8590 	return prog->type;
8591 }
8592 
8593 static size_t custom_sec_def_cnt;
8594 static struct bpf_sec_def *custom_sec_defs;
8595 static struct bpf_sec_def custom_fallback_def;
8596 static bool has_custom_fallback_def;
8597 static int last_custom_sec_def_handler_id;
8598 
8599 int bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
8600 {
8601 	if (prog->obj->loaded)
8602 		return libbpf_err(-EBUSY);
8603 
8604 	/* if type is not changed, do nothing */
8605 	if (prog->type == type)
8606 		return 0;
8607 
8608 	prog->type = type;
8609 
8610 	/* If a program type was changed, we need to reset associated SEC()
8611 	 * handler, as it will be invalid now. The only exception is a generic
8612 	 * fallback handler, which by definition is program type-agnostic and
8613 	 * is a catch-all custom handler, optionally set by the application,
8614 	 * so should be able to handle any type of BPF program.
8615 	 */
8616 	if (prog->sec_def != &custom_fallback_def)
8617 		prog->sec_def = NULL;
8618 	return 0;
8619 }
8620 
8621 __alias(bpf_program__expected_attach_type)
8622 enum bpf_attach_type bpf_program__get_expected_attach_type(const struct bpf_program *prog);
8623 
8624 enum bpf_attach_type bpf_program__expected_attach_type(const struct bpf_program *prog)
8625 {
8626 	return prog->expected_attach_type;
8627 }
8628 
8629 int bpf_program__set_expected_attach_type(struct bpf_program *prog,
8630 					   enum bpf_attach_type type)
8631 {
8632 	if (prog->obj->loaded)
8633 		return libbpf_err(-EBUSY);
8634 
8635 	prog->expected_attach_type = type;
8636 	return 0;
8637 }
8638 
8639 __u32 bpf_program__flags(const struct bpf_program *prog)
8640 {
8641 	return prog->prog_flags;
8642 }
8643 
8644 int bpf_program__set_flags(struct bpf_program *prog, __u32 flags)
8645 {
8646 	if (prog->obj->loaded)
8647 		return libbpf_err(-EBUSY);
8648 
8649 	prog->prog_flags = flags;
8650 	return 0;
8651 }
8652 
8653 __u32 bpf_program__log_level(const struct bpf_program *prog)
8654 {
8655 	return prog->log_level;
8656 }
8657 
8658 int bpf_program__set_log_level(struct bpf_program *prog, __u32 log_level)
8659 {
8660 	if (prog->obj->loaded)
8661 		return libbpf_err(-EBUSY);
8662 
8663 	prog->log_level = log_level;
8664 	return 0;
8665 }
8666 
8667 const char *bpf_program__log_buf(const struct bpf_program *prog, size_t *log_size)
8668 {
8669 	*log_size = prog->log_size;
8670 	return prog->log_buf;
8671 }
8672 
8673 int bpf_program__set_log_buf(struct bpf_program *prog, char *log_buf, size_t log_size)
8674 {
8675 	if (log_size && !log_buf)
8676 		return -EINVAL;
8677 	if (prog->log_size > UINT_MAX)
8678 		return -EINVAL;
8679 	if (prog->obj->loaded)
8680 		return -EBUSY;
8681 
8682 	prog->log_buf = log_buf;
8683 	prog->log_size = log_size;
8684 	return 0;
8685 }
8686 
8687 #define SEC_DEF(sec_pfx, ptype, atype, flags, ...) {			    \
8688 	.sec = (char *)sec_pfx,						    \
8689 	.prog_type = BPF_PROG_TYPE_##ptype,				    \
8690 	.expected_attach_type = atype,					    \
8691 	.cookie = (long)(flags),					    \
8692 	.prog_prepare_load_fn = libbpf_prepare_prog_load,		    \
8693 	__VA_ARGS__							    \
8694 }
8695 
8696 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8697 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8698 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8699 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8700 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8701 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8702 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8703 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8704 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8705 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8706 
8707 static const struct bpf_sec_def section_defs[] = {
8708 	SEC_DEF("socket",		SOCKET_FILTER, 0, SEC_NONE),
8709 	SEC_DEF("sk_reuseport/migrate",	SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT_OR_MIGRATE, SEC_ATTACHABLE),
8710 	SEC_DEF("sk_reuseport",		SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT, SEC_ATTACHABLE),
8711 	SEC_DEF("kprobe+",		KPROBE,	0, SEC_NONE, attach_kprobe),
8712 	SEC_DEF("uprobe+",		KPROBE,	0, SEC_NONE, attach_uprobe),
8713 	SEC_DEF("uprobe.s+",		KPROBE,	0, SEC_SLEEPABLE, attach_uprobe),
8714 	SEC_DEF("kretprobe+",		KPROBE, 0, SEC_NONE, attach_kprobe),
8715 	SEC_DEF("uretprobe+",		KPROBE, 0, SEC_NONE, attach_uprobe),
8716 	SEC_DEF("uretprobe.s+",		KPROBE, 0, SEC_SLEEPABLE, attach_uprobe),
8717 	SEC_DEF("kprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
8718 	SEC_DEF("kretprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
8719 	SEC_DEF("ksyscall+",		KPROBE,	0, SEC_NONE, attach_ksyscall),
8720 	SEC_DEF("kretsyscall+",		KPROBE, 0, SEC_NONE, attach_ksyscall),
8721 	SEC_DEF("usdt+",		KPROBE,	0, SEC_NONE, attach_usdt),
8722 	SEC_DEF("tc/ingress",		SCHED_CLS, BPF_TCX_INGRESS, SEC_NONE), /* alias for tcx */
8723 	SEC_DEF("tc/egress",		SCHED_CLS, BPF_TCX_EGRESS, SEC_NONE),  /* alias for tcx */
8724 	SEC_DEF("tcx/ingress",		SCHED_CLS, BPF_TCX_INGRESS, SEC_NONE),
8725 	SEC_DEF("tcx/egress",		SCHED_CLS, BPF_TCX_EGRESS, SEC_NONE),
8726 	SEC_DEF("tc",			SCHED_CLS, 0, SEC_NONE), /* deprecated / legacy, use tcx */
8727 	SEC_DEF("classifier",		SCHED_CLS, 0, SEC_NONE), /* deprecated / legacy, use tcx */
8728 	SEC_DEF("action",		SCHED_ACT, 0, SEC_NONE), /* deprecated / legacy, use tcx */
8729 	SEC_DEF("tracepoint+",		TRACEPOINT, 0, SEC_NONE, attach_tp),
8730 	SEC_DEF("tp+",			TRACEPOINT, 0, SEC_NONE, attach_tp),
8731 	SEC_DEF("raw_tracepoint+",	RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
8732 	SEC_DEF("raw_tp+",		RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
8733 	SEC_DEF("raw_tracepoint.w+",	RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
8734 	SEC_DEF("raw_tp.w+",		RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
8735 	SEC_DEF("tp_btf+",		TRACING, BPF_TRACE_RAW_TP, SEC_ATTACH_BTF, attach_trace),
8736 	SEC_DEF("fentry+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF, attach_trace),
8737 	SEC_DEF("fmod_ret+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF, attach_trace),
8738 	SEC_DEF("fexit+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF, attach_trace),
8739 	SEC_DEF("fentry.s+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8740 	SEC_DEF("fmod_ret.s+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8741 	SEC_DEF("fexit.s+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8742 	SEC_DEF("freplace+",		EXT, 0, SEC_ATTACH_BTF, attach_trace),
8743 	SEC_DEF("lsm+",			LSM, BPF_LSM_MAC, SEC_ATTACH_BTF, attach_lsm),
8744 	SEC_DEF("lsm.s+",		LSM, BPF_LSM_MAC, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_lsm),
8745 	SEC_DEF("lsm_cgroup+",		LSM, BPF_LSM_CGROUP, SEC_ATTACH_BTF),
8746 	SEC_DEF("iter+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF, attach_iter),
8747 	SEC_DEF("iter.s+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_iter),
8748 	SEC_DEF("syscall",		SYSCALL, 0, SEC_SLEEPABLE),
8749 	SEC_DEF("xdp.frags/devmap",	XDP, BPF_XDP_DEVMAP, SEC_XDP_FRAGS),
8750 	SEC_DEF("xdp/devmap",		XDP, BPF_XDP_DEVMAP, SEC_ATTACHABLE),
8751 	SEC_DEF("xdp.frags/cpumap",	XDP, BPF_XDP_CPUMAP, SEC_XDP_FRAGS),
8752 	SEC_DEF("xdp/cpumap",		XDP, BPF_XDP_CPUMAP, SEC_ATTACHABLE),
8753 	SEC_DEF("xdp.frags",		XDP, BPF_XDP, SEC_XDP_FRAGS),
8754 	SEC_DEF("xdp",			XDP, BPF_XDP, SEC_ATTACHABLE_OPT),
8755 	SEC_DEF("perf_event",		PERF_EVENT, 0, SEC_NONE),
8756 	SEC_DEF("lwt_in",		LWT_IN, 0, SEC_NONE),
8757 	SEC_DEF("lwt_out",		LWT_OUT, 0, SEC_NONE),
8758 	SEC_DEF("lwt_xmit",		LWT_XMIT, 0, SEC_NONE),
8759 	SEC_DEF("lwt_seg6local",	LWT_SEG6LOCAL, 0, SEC_NONE),
8760 	SEC_DEF("sockops",		SOCK_OPS, BPF_CGROUP_SOCK_OPS, SEC_ATTACHABLE_OPT),
8761 	SEC_DEF("sk_skb/stream_parser",	SK_SKB, BPF_SK_SKB_STREAM_PARSER, SEC_ATTACHABLE_OPT),
8762 	SEC_DEF("sk_skb/stream_verdict",SK_SKB, BPF_SK_SKB_STREAM_VERDICT, SEC_ATTACHABLE_OPT),
8763 	SEC_DEF("sk_skb",		SK_SKB, 0, SEC_NONE),
8764 	SEC_DEF("sk_msg",		SK_MSG, BPF_SK_MSG_VERDICT, SEC_ATTACHABLE_OPT),
8765 	SEC_DEF("lirc_mode2",		LIRC_MODE2, BPF_LIRC_MODE2, SEC_ATTACHABLE_OPT),
8766 	SEC_DEF("flow_dissector",	FLOW_DISSECTOR, BPF_FLOW_DISSECTOR, SEC_ATTACHABLE_OPT),
8767 	SEC_DEF("cgroup_skb/ingress",	CGROUP_SKB, BPF_CGROUP_INET_INGRESS, SEC_ATTACHABLE_OPT),
8768 	SEC_DEF("cgroup_skb/egress",	CGROUP_SKB, BPF_CGROUP_INET_EGRESS, SEC_ATTACHABLE_OPT),
8769 	SEC_DEF("cgroup/skb",		CGROUP_SKB, 0, SEC_NONE),
8770 	SEC_DEF("cgroup/sock_create",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE),
8771 	SEC_DEF("cgroup/sock_release",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_RELEASE, SEC_ATTACHABLE),
8772 	SEC_DEF("cgroup/sock",		CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE_OPT),
8773 	SEC_DEF("cgroup/post_bind4",	CGROUP_SOCK, BPF_CGROUP_INET4_POST_BIND, SEC_ATTACHABLE),
8774 	SEC_DEF("cgroup/post_bind6",	CGROUP_SOCK, BPF_CGROUP_INET6_POST_BIND, SEC_ATTACHABLE),
8775 	SEC_DEF("cgroup/bind4",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND, SEC_ATTACHABLE),
8776 	SEC_DEF("cgroup/bind6",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND, SEC_ATTACHABLE),
8777 	SEC_DEF("cgroup/connect4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT, SEC_ATTACHABLE),
8778 	SEC_DEF("cgroup/connect6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT, SEC_ATTACHABLE),
8779 	SEC_DEF("cgroup/sendmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG, SEC_ATTACHABLE),
8780 	SEC_DEF("cgroup/sendmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG, SEC_ATTACHABLE),
8781 	SEC_DEF("cgroup/recvmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_RECVMSG, SEC_ATTACHABLE),
8782 	SEC_DEF("cgroup/recvmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_RECVMSG, SEC_ATTACHABLE),
8783 	SEC_DEF("cgroup/getpeername4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETPEERNAME, SEC_ATTACHABLE),
8784 	SEC_DEF("cgroup/getpeername6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETPEERNAME, SEC_ATTACHABLE),
8785 	SEC_DEF("cgroup/getsockname4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETSOCKNAME, SEC_ATTACHABLE),
8786 	SEC_DEF("cgroup/getsockname6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETSOCKNAME, SEC_ATTACHABLE),
8787 	SEC_DEF("cgroup/sysctl",	CGROUP_SYSCTL, BPF_CGROUP_SYSCTL, SEC_ATTACHABLE),
8788 	SEC_DEF("cgroup/getsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_GETSOCKOPT, SEC_ATTACHABLE),
8789 	SEC_DEF("cgroup/setsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_SETSOCKOPT, SEC_ATTACHABLE),
8790 	SEC_DEF("cgroup/dev",		CGROUP_DEVICE, BPF_CGROUP_DEVICE, SEC_ATTACHABLE_OPT),
8791 	SEC_DEF("struct_ops+",		STRUCT_OPS, 0, SEC_NONE),
8792 	SEC_DEF("struct_ops.s+",	STRUCT_OPS, 0, SEC_SLEEPABLE),
8793 	SEC_DEF("sk_lookup",		SK_LOOKUP, BPF_SK_LOOKUP, SEC_ATTACHABLE),
8794 	SEC_DEF("netfilter",		NETFILTER, BPF_NETFILTER, SEC_NONE),
8795 };
8796 
8797 int libbpf_register_prog_handler(const char *sec,
8798 				 enum bpf_prog_type prog_type,
8799 				 enum bpf_attach_type exp_attach_type,
8800 				 const struct libbpf_prog_handler_opts *opts)
8801 {
8802 	struct bpf_sec_def *sec_def;
8803 
8804 	if (!OPTS_VALID(opts, libbpf_prog_handler_opts))
8805 		return libbpf_err(-EINVAL);
8806 
8807 	if (last_custom_sec_def_handler_id == INT_MAX) /* prevent overflow */
8808 		return libbpf_err(-E2BIG);
8809 
8810 	if (sec) {
8811 		sec_def = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt + 1,
8812 					      sizeof(*sec_def));
8813 		if (!sec_def)
8814 			return libbpf_err(-ENOMEM);
8815 
8816 		custom_sec_defs = sec_def;
8817 		sec_def = &custom_sec_defs[custom_sec_def_cnt];
8818 	} else {
8819 		if (has_custom_fallback_def)
8820 			return libbpf_err(-EBUSY);
8821 
8822 		sec_def = &custom_fallback_def;
8823 	}
8824 
8825 	sec_def->sec = sec ? strdup(sec) : NULL;
8826 	if (sec && !sec_def->sec)
8827 		return libbpf_err(-ENOMEM);
8828 
8829 	sec_def->prog_type = prog_type;
8830 	sec_def->expected_attach_type = exp_attach_type;
8831 	sec_def->cookie = OPTS_GET(opts, cookie, 0);
8832 
8833 	sec_def->prog_setup_fn = OPTS_GET(opts, prog_setup_fn, NULL);
8834 	sec_def->prog_prepare_load_fn = OPTS_GET(opts, prog_prepare_load_fn, NULL);
8835 	sec_def->prog_attach_fn = OPTS_GET(opts, prog_attach_fn, NULL);
8836 
8837 	sec_def->handler_id = ++last_custom_sec_def_handler_id;
8838 
8839 	if (sec)
8840 		custom_sec_def_cnt++;
8841 	else
8842 		has_custom_fallback_def = true;
8843 
8844 	return sec_def->handler_id;
8845 }
8846 
8847 int libbpf_unregister_prog_handler(int handler_id)
8848 {
8849 	struct bpf_sec_def *sec_defs;
8850 	int i;
8851 
8852 	if (handler_id <= 0)
8853 		return libbpf_err(-EINVAL);
8854 
8855 	if (has_custom_fallback_def && custom_fallback_def.handler_id == handler_id) {
8856 		memset(&custom_fallback_def, 0, sizeof(custom_fallback_def));
8857 		has_custom_fallback_def = false;
8858 		return 0;
8859 	}
8860 
8861 	for (i = 0; i < custom_sec_def_cnt; i++) {
8862 		if (custom_sec_defs[i].handler_id == handler_id)
8863 			break;
8864 	}
8865 
8866 	if (i == custom_sec_def_cnt)
8867 		return libbpf_err(-ENOENT);
8868 
8869 	free(custom_sec_defs[i].sec);
8870 	for (i = i + 1; i < custom_sec_def_cnt; i++)
8871 		custom_sec_defs[i - 1] = custom_sec_defs[i];
8872 	custom_sec_def_cnt--;
8873 
8874 	/* try to shrink the array, but it's ok if we couldn't */
8875 	sec_defs = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt, sizeof(*sec_defs));
8876 	/* if new count is zero, reallocarray can return a valid NULL result;
8877 	 * in this case the previous pointer will be freed, so we *have to*
8878 	 * reassign old pointer to the new value (even if it's NULL)
8879 	 */
8880 	if (sec_defs || custom_sec_def_cnt == 0)
8881 		custom_sec_defs = sec_defs;
8882 
8883 	return 0;
8884 }
8885 
8886 static bool sec_def_matches(const struct bpf_sec_def *sec_def, const char *sec_name)
8887 {
8888 	size_t len = strlen(sec_def->sec);
8889 
8890 	/* "type/" always has to have proper SEC("type/extras") form */
8891 	if (sec_def->sec[len - 1] == '/') {
8892 		if (str_has_pfx(sec_name, sec_def->sec))
8893 			return true;
8894 		return false;
8895 	}
8896 
8897 	/* "type+" means it can be either exact SEC("type") or
8898 	 * well-formed SEC("type/extras") with proper '/' separator
8899 	 */
8900 	if (sec_def->sec[len - 1] == '+') {
8901 		len--;
8902 		/* not even a prefix */
8903 		if (strncmp(sec_name, sec_def->sec, len) != 0)
8904 			return false;
8905 		/* exact match or has '/' separator */
8906 		if (sec_name[len] == '\0' || sec_name[len] == '/')
8907 			return true;
8908 		return false;
8909 	}
8910 
8911 	return strcmp(sec_name, sec_def->sec) == 0;
8912 }
8913 
8914 static const struct bpf_sec_def *find_sec_def(const char *sec_name)
8915 {
8916 	const struct bpf_sec_def *sec_def;
8917 	int i, n;
8918 
8919 	n = custom_sec_def_cnt;
8920 	for (i = 0; i < n; i++) {
8921 		sec_def = &custom_sec_defs[i];
8922 		if (sec_def_matches(sec_def, sec_name))
8923 			return sec_def;
8924 	}
8925 
8926 	n = ARRAY_SIZE(section_defs);
8927 	for (i = 0; i < n; i++) {
8928 		sec_def = &section_defs[i];
8929 		if (sec_def_matches(sec_def, sec_name))
8930 			return sec_def;
8931 	}
8932 
8933 	if (has_custom_fallback_def)
8934 		return &custom_fallback_def;
8935 
8936 	return NULL;
8937 }
8938 
8939 #define MAX_TYPE_NAME_SIZE 32
8940 
8941 static char *libbpf_get_type_names(bool attach_type)
8942 {
8943 	int i, len = ARRAY_SIZE(section_defs) * MAX_TYPE_NAME_SIZE;
8944 	char *buf;
8945 
8946 	buf = malloc(len);
8947 	if (!buf)
8948 		return NULL;
8949 
8950 	buf[0] = '\0';
8951 	/* Forge string buf with all available names */
8952 	for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
8953 		const struct bpf_sec_def *sec_def = &section_defs[i];
8954 
8955 		if (attach_type) {
8956 			if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
8957 				continue;
8958 
8959 			if (!(sec_def->cookie & SEC_ATTACHABLE))
8960 				continue;
8961 		}
8962 
8963 		if (strlen(buf) + strlen(section_defs[i].sec) + 2 > len) {
8964 			free(buf);
8965 			return NULL;
8966 		}
8967 		strcat(buf, " ");
8968 		strcat(buf, section_defs[i].sec);
8969 	}
8970 
8971 	return buf;
8972 }
8973 
8974 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
8975 			     enum bpf_attach_type *expected_attach_type)
8976 {
8977 	const struct bpf_sec_def *sec_def;
8978 	char *type_names;
8979 
8980 	if (!name)
8981 		return libbpf_err(-EINVAL);
8982 
8983 	sec_def = find_sec_def(name);
8984 	if (sec_def) {
8985 		*prog_type = sec_def->prog_type;
8986 		*expected_attach_type = sec_def->expected_attach_type;
8987 		return 0;
8988 	}
8989 
8990 	pr_debug("failed to guess program type from ELF section '%s'\n", name);
8991 	type_names = libbpf_get_type_names(false);
8992 	if (type_names != NULL) {
8993 		pr_debug("supported section(type) names are:%s\n", type_names);
8994 		free(type_names);
8995 	}
8996 
8997 	return libbpf_err(-ESRCH);
8998 }
8999 
9000 const char *libbpf_bpf_attach_type_str(enum bpf_attach_type t)
9001 {
9002 	if (t < 0 || t >= ARRAY_SIZE(attach_type_name))
9003 		return NULL;
9004 
9005 	return attach_type_name[t];
9006 }
9007 
9008 const char *libbpf_bpf_link_type_str(enum bpf_link_type t)
9009 {
9010 	if (t < 0 || t >= ARRAY_SIZE(link_type_name))
9011 		return NULL;
9012 
9013 	return link_type_name[t];
9014 }
9015 
9016 const char *libbpf_bpf_map_type_str(enum bpf_map_type t)
9017 {
9018 	if (t < 0 || t >= ARRAY_SIZE(map_type_name))
9019 		return NULL;
9020 
9021 	return map_type_name[t];
9022 }
9023 
9024 const char *libbpf_bpf_prog_type_str(enum bpf_prog_type t)
9025 {
9026 	if (t < 0 || t >= ARRAY_SIZE(prog_type_name))
9027 		return NULL;
9028 
9029 	return prog_type_name[t];
9030 }
9031 
9032 static struct bpf_map *find_struct_ops_map_by_offset(struct bpf_object *obj,
9033 						     int sec_idx,
9034 						     size_t offset)
9035 {
9036 	struct bpf_map *map;
9037 	size_t i;
9038 
9039 	for (i = 0; i < obj->nr_maps; i++) {
9040 		map = &obj->maps[i];
9041 		if (!bpf_map__is_struct_ops(map))
9042 			continue;
9043 		if (map->sec_idx == sec_idx &&
9044 		    map->sec_offset <= offset &&
9045 		    offset - map->sec_offset < map->def.value_size)
9046 			return map;
9047 	}
9048 
9049 	return NULL;
9050 }
9051 
9052 /* Collect the reloc from ELF and populate the st_ops->progs[] */
9053 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
9054 					    Elf64_Shdr *shdr, Elf_Data *data)
9055 {
9056 	const struct btf_member *member;
9057 	struct bpf_struct_ops *st_ops;
9058 	struct bpf_program *prog;
9059 	unsigned int shdr_idx;
9060 	const struct btf *btf;
9061 	struct bpf_map *map;
9062 	unsigned int moff, insn_idx;
9063 	const char *name;
9064 	__u32 member_idx;
9065 	Elf64_Sym *sym;
9066 	Elf64_Rel *rel;
9067 	int i, nrels;
9068 
9069 	btf = obj->btf;
9070 	nrels = shdr->sh_size / shdr->sh_entsize;
9071 	for (i = 0; i < nrels; i++) {
9072 		rel = elf_rel_by_idx(data, i);
9073 		if (!rel) {
9074 			pr_warn("struct_ops reloc: failed to get %d reloc\n", i);
9075 			return -LIBBPF_ERRNO__FORMAT;
9076 		}
9077 
9078 		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
9079 		if (!sym) {
9080 			pr_warn("struct_ops reloc: symbol %zx not found\n",
9081 				(size_t)ELF64_R_SYM(rel->r_info));
9082 			return -LIBBPF_ERRNO__FORMAT;
9083 		}
9084 
9085 		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
9086 		map = find_struct_ops_map_by_offset(obj, shdr->sh_info, rel->r_offset);
9087 		if (!map) {
9088 			pr_warn("struct_ops reloc: cannot find map at rel->r_offset %zu\n",
9089 				(size_t)rel->r_offset);
9090 			return -EINVAL;
9091 		}
9092 
9093 		moff = rel->r_offset - map->sec_offset;
9094 		shdr_idx = sym->st_shndx;
9095 		st_ops = map->st_ops;
9096 		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",
9097 			 map->name,
9098 			 (long long)(rel->r_info >> 32),
9099 			 (long long)sym->st_value,
9100 			 shdr_idx, (size_t)rel->r_offset,
9101 			 map->sec_offset, sym->st_name, name);
9102 
9103 		if (shdr_idx >= SHN_LORESERVE) {
9104 			pr_warn("struct_ops reloc %s: rel->r_offset %zu shdr_idx %u unsupported non-static function\n",
9105 				map->name, (size_t)rel->r_offset, shdr_idx);
9106 			return -LIBBPF_ERRNO__RELOC;
9107 		}
9108 		if (sym->st_value % BPF_INSN_SZ) {
9109 			pr_warn("struct_ops reloc %s: invalid target program offset %llu\n",
9110 				map->name, (unsigned long long)sym->st_value);
9111 			return -LIBBPF_ERRNO__FORMAT;
9112 		}
9113 		insn_idx = sym->st_value / BPF_INSN_SZ;
9114 
9115 		member = find_member_by_offset(st_ops->type, moff * 8);
9116 		if (!member) {
9117 			pr_warn("struct_ops reloc %s: cannot find member at moff %u\n",
9118 				map->name, moff);
9119 			return -EINVAL;
9120 		}
9121 		member_idx = member - btf_members(st_ops->type);
9122 		name = btf__name_by_offset(btf, member->name_off);
9123 
9124 		if (!resolve_func_ptr(btf, member->type, NULL)) {
9125 			pr_warn("struct_ops reloc %s: cannot relocate non func ptr %s\n",
9126 				map->name, name);
9127 			return -EINVAL;
9128 		}
9129 
9130 		prog = find_prog_by_sec_insn(obj, shdr_idx, insn_idx);
9131 		if (!prog) {
9132 			pr_warn("struct_ops reloc %s: cannot find prog at shdr_idx %u to relocate func ptr %s\n",
9133 				map->name, shdr_idx, name);
9134 			return -EINVAL;
9135 		}
9136 
9137 		/* prevent the use of BPF prog with invalid type */
9138 		if (prog->type != BPF_PROG_TYPE_STRUCT_OPS) {
9139 			pr_warn("struct_ops reloc %s: prog %s is not struct_ops BPF program\n",
9140 				map->name, prog->name);
9141 			return -EINVAL;
9142 		}
9143 
9144 		/* if we haven't yet processed this BPF program, record proper
9145 		 * attach_btf_id and member_idx
9146 		 */
9147 		if (!prog->attach_btf_id) {
9148 			prog->attach_btf_id = st_ops->type_id;
9149 			prog->expected_attach_type = member_idx;
9150 		}
9151 
9152 		/* struct_ops BPF prog can be re-used between multiple
9153 		 * .struct_ops & .struct_ops.link as long as it's the
9154 		 * same struct_ops struct definition and the same
9155 		 * function pointer field
9156 		 */
9157 		if (prog->attach_btf_id != st_ops->type_id ||
9158 		    prog->expected_attach_type != member_idx) {
9159 			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",
9160 				map->name, prog->name, prog->sec_name, prog->type,
9161 				prog->attach_btf_id, prog->expected_attach_type, name);
9162 			return -EINVAL;
9163 		}
9164 
9165 		st_ops->progs[member_idx] = prog;
9166 	}
9167 
9168 	return 0;
9169 }
9170 
9171 #define BTF_TRACE_PREFIX "btf_trace_"
9172 #define BTF_LSM_PREFIX "bpf_lsm_"
9173 #define BTF_ITER_PREFIX "bpf_iter_"
9174 #define BTF_MAX_NAME_SIZE 128
9175 
9176 void btf_get_kernel_prefix_kind(enum bpf_attach_type attach_type,
9177 				const char **prefix, int *kind)
9178 {
9179 	switch (attach_type) {
9180 	case BPF_TRACE_RAW_TP:
9181 		*prefix = BTF_TRACE_PREFIX;
9182 		*kind = BTF_KIND_TYPEDEF;
9183 		break;
9184 	case BPF_LSM_MAC:
9185 	case BPF_LSM_CGROUP:
9186 		*prefix = BTF_LSM_PREFIX;
9187 		*kind = BTF_KIND_FUNC;
9188 		break;
9189 	case BPF_TRACE_ITER:
9190 		*prefix = BTF_ITER_PREFIX;
9191 		*kind = BTF_KIND_FUNC;
9192 		break;
9193 	default:
9194 		*prefix = "";
9195 		*kind = BTF_KIND_FUNC;
9196 	}
9197 }
9198 
9199 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
9200 				   const char *name, __u32 kind)
9201 {
9202 	char btf_type_name[BTF_MAX_NAME_SIZE];
9203 	int ret;
9204 
9205 	ret = snprintf(btf_type_name, sizeof(btf_type_name),
9206 		       "%s%s", prefix, name);
9207 	/* snprintf returns the number of characters written excluding the
9208 	 * terminating null. So, if >= BTF_MAX_NAME_SIZE are written, it
9209 	 * indicates truncation.
9210 	 */
9211 	if (ret < 0 || ret >= sizeof(btf_type_name))
9212 		return -ENAMETOOLONG;
9213 	return btf__find_by_name_kind(btf, btf_type_name, kind);
9214 }
9215 
9216 static inline int find_attach_btf_id(struct btf *btf, const char *name,
9217 				     enum bpf_attach_type attach_type)
9218 {
9219 	const char *prefix;
9220 	int kind;
9221 
9222 	btf_get_kernel_prefix_kind(attach_type, &prefix, &kind);
9223 	return find_btf_by_prefix_kind(btf, prefix, name, kind);
9224 }
9225 
9226 int libbpf_find_vmlinux_btf_id(const char *name,
9227 			       enum bpf_attach_type attach_type)
9228 {
9229 	struct btf *btf;
9230 	int err;
9231 
9232 	btf = btf__load_vmlinux_btf();
9233 	err = libbpf_get_error(btf);
9234 	if (err) {
9235 		pr_warn("vmlinux BTF is not found\n");
9236 		return libbpf_err(err);
9237 	}
9238 
9239 	err = find_attach_btf_id(btf, name, attach_type);
9240 	if (err <= 0)
9241 		pr_warn("%s is not found in vmlinux BTF\n", name);
9242 
9243 	btf__free(btf);
9244 	return libbpf_err(err);
9245 }
9246 
9247 static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd)
9248 {
9249 	struct bpf_prog_info info;
9250 	__u32 info_len = sizeof(info);
9251 	struct btf *btf;
9252 	int err;
9253 
9254 	memset(&info, 0, info_len);
9255 	err = bpf_prog_get_info_by_fd(attach_prog_fd, &info, &info_len);
9256 	if (err) {
9257 		pr_warn("failed bpf_prog_get_info_by_fd for FD %d: %d\n",
9258 			attach_prog_fd, err);
9259 		return err;
9260 	}
9261 
9262 	err = -EINVAL;
9263 	if (!info.btf_id) {
9264 		pr_warn("The target program doesn't have BTF\n");
9265 		goto out;
9266 	}
9267 	btf = btf__load_from_kernel_by_id(info.btf_id);
9268 	err = libbpf_get_error(btf);
9269 	if (err) {
9270 		pr_warn("Failed to get BTF %d of the program: %d\n", info.btf_id, err);
9271 		goto out;
9272 	}
9273 	err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
9274 	btf__free(btf);
9275 	if (err <= 0) {
9276 		pr_warn("%s is not found in prog's BTF\n", name);
9277 		goto out;
9278 	}
9279 out:
9280 	return err;
9281 }
9282 
9283 static int find_kernel_btf_id(struct bpf_object *obj, const char *attach_name,
9284 			      enum bpf_attach_type attach_type,
9285 			      int *btf_obj_fd, int *btf_type_id)
9286 {
9287 	int ret, i;
9288 
9289 	ret = find_attach_btf_id(obj->btf_vmlinux, attach_name, attach_type);
9290 	if (ret > 0) {
9291 		*btf_obj_fd = 0; /* vmlinux BTF */
9292 		*btf_type_id = ret;
9293 		return 0;
9294 	}
9295 	if (ret != -ENOENT)
9296 		return ret;
9297 
9298 	ret = load_module_btfs(obj);
9299 	if (ret)
9300 		return ret;
9301 
9302 	for (i = 0; i < obj->btf_module_cnt; i++) {
9303 		const struct module_btf *mod = &obj->btf_modules[i];
9304 
9305 		ret = find_attach_btf_id(mod->btf, attach_name, attach_type);
9306 		if (ret > 0) {
9307 			*btf_obj_fd = mod->fd;
9308 			*btf_type_id = ret;
9309 			return 0;
9310 		}
9311 		if (ret == -ENOENT)
9312 			continue;
9313 
9314 		return ret;
9315 	}
9316 
9317 	return -ESRCH;
9318 }
9319 
9320 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
9321 				     int *btf_obj_fd, int *btf_type_id)
9322 {
9323 	enum bpf_attach_type attach_type = prog->expected_attach_type;
9324 	__u32 attach_prog_fd = prog->attach_prog_fd;
9325 	int err = 0;
9326 
9327 	/* BPF program's BTF ID */
9328 	if (prog->type == BPF_PROG_TYPE_EXT || attach_prog_fd) {
9329 		if (!attach_prog_fd) {
9330 			pr_warn("prog '%s': attach program FD is not set\n", prog->name);
9331 			return -EINVAL;
9332 		}
9333 		err = libbpf_find_prog_btf_id(attach_name, attach_prog_fd);
9334 		if (err < 0) {
9335 			pr_warn("prog '%s': failed to find BPF program (FD %d) BTF ID for '%s': %d\n",
9336 				 prog->name, attach_prog_fd, attach_name, err);
9337 			return err;
9338 		}
9339 		*btf_obj_fd = 0;
9340 		*btf_type_id = err;
9341 		return 0;
9342 	}
9343 
9344 	/* kernel/module BTF ID */
9345 	if (prog->obj->gen_loader) {
9346 		bpf_gen__record_attach_target(prog->obj->gen_loader, attach_name, attach_type);
9347 		*btf_obj_fd = 0;
9348 		*btf_type_id = 1;
9349 	} else {
9350 		err = find_kernel_btf_id(prog->obj, attach_name, attach_type, btf_obj_fd, btf_type_id);
9351 	}
9352 	if (err) {
9353 		pr_warn("prog '%s': failed to find kernel BTF type ID of '%s': %d\n",
9354 			prog->name, attach_name, err);
9355 		return err;
9356 	}
9357 	return 0;
9358 }
9359 
9360 int libbpf_attach_type_by_name(const char *name,
9361 			       enum bpf_attach_type *attach_type)
9362 {
9363 	char *type_names;
9364 	const struct bpf_sec_def *sec_def;
9365 
9366 	if (!name)
9367 		return libbpf_err(-EINVAL);
9368 
9369 	sec_def = find_sec_def(name);
9370 	if (!sec_def) {
9371 		pr_debug("failed to guess attach type based on ELF section name '%s'\n", name);
9372 		type_names = libbpf_get_type_names(true);
9373 		if (type_names != NULL) {
9374 			pr_debug("attachable section(type) names are:%s\n", type_names);
9375 			free(type_names);
9376 		}
9377 
9378 		return libbpf_err(-EINVAL);
9379 	}
9380 
9381 	if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
9382 		return libbpf_err(-EINVAL);
9383 	if (!(sec_def->cookie & SEC_ATTACHABLE))
9384 		return libbpf_err(-EINVAL);
9385 
9386 	*attach_type = sec_def->expected_attach_type;
9387 	return 0;
9388 }
9389 
9390 int bpf_map__fd(const struct bpf_map *map)
9391 {
9392 	return map ? map->fd : libbpf_err(-EINVAL);
9393 }
9394 
9395 static bool map_uses_real_name(const struct bpf_map *map)
9396 {
9397 	/* Since libbpf started to support custom .data.* and .rodata.* maps,
9398 	 * their user-visible name differs from kernel-visible name. Users see
9399 	 * such map's corresponding ELF section name as a map name.
9400 	 * This check distinguishes .data/.rodata from .data.* and .rodata.*
9401 	 * maps to know which name has to be returned to the user.
9402 	 */
9403 	if (map->libbpf_type == LIBBPF_MAP_DATA && strcmp(map->real_name, DATA_SEC) != 0)
9404 		return true;
9405 	if (map->libbpf_type == LIBBPF_MAP_RODATA && strcmp(map->real_name, RODATA_SEC) != 0)
9406 		return true;
9407 	return false;
9408 }
9409 
9410 const char *bpf_map__name(const struct bpf_map *map)
9411 {
9412 	if (!map)
9413 		return NULL;
9414 
9415 	if (map_uses_real_name(map))
9416 		return map->real_name;
9417 
9418 	return map->name;
9419 }
9420 
9421 enum bpf_map_type bpf_map__type(const struct bpf_map *map)
9422 {
9423 	return map->def.type;
9424 }
9425 
9426 int bpf_map__set_type(struct bpf_map *map, enum bpf_map_type type)
9427 {
9428 	if (map->fd >= 0)
9429 		return libbpf_err(-EBUSY);
9430 	map->def.type = type;
9431 	return 0;
9432 }
9433 
9434 __u32 bpf_map__map_flags(const struct bpf_map *map)
9435 {
9436 	return map->def.map_flags;
9437 }
9438 
9439 int bpf_map__set_map_flags(struct bpf_map *map, __u32 flags)
9440 {
9441 	if (map->fd >= 0)
9442 		return libbpf_err(-EBUSY);
9443 	map->def.map_flags = flags;
9444 	return 0;
9445 }
9446 
9447 __u64 bpf_map__map_extra(const struct bpf_map *map)
9448 {
9449 	return map->map_extra;
9450 }
9451 
9452 int bpf_map__set_map_extra(struct bpf_map *map, __u64 map_extra)
9453 {
9454 	if (map->fd >= 0)
9455 		return libbpf_err(-EBUSY);
9456 	map->map_extra = map_extra;
9457 	return 0;
9458 }
9459 
9460 __u32 bpf_map__numa_node(const struct bpf_map *map)
9461 {
9462 	return map->numa_node;
9463 }
9464 
9465 int bpf_map__set_numa_node(struct bpf_map *map, __u32 numa_node)
9466 {
9467 	if (map->fd >= 0)
9468 		return libbpf_err(-EBUSY);
9469 	map->numa_node = numa_node;
9470 	return 0;
9471 }
9472 
9473 __u32 bpf_map__key_size(const struct bpf_map *map)
9474 {
9475 	return map->def.key_size;
9476 }
9477 
9478 int bpf_map__set_key_size(struct bpf_map *map, __u32 size)
9479 {
9480 	if (map->fd >= 0)
9481 		return libbpf_err(-EBUSY);
9482 	map->def.key_size = size;
9483 	return 0;
9484 }
9485 
9486 __u32 bpf_map__value_size(const struct bpf_map *map)
9487 {
9488 	return map->def.value_size;
9489 }
9490 
9491 static int map_btf_datasec_resize(struct bpf_map *map, __u32 size)
9492 {
9493 	struct btf *btf;
9494 	struct btf_type *datasec_type, *var_type;
9495 	struct btf_var_secinfo *var;
9496 	const struct btf_type *array_type;
9497 	const struct btf_array *array;
9498 	int vlen, element_sz, new_array_id;
9499 	__u32 nr_elements;
9500 
9501 	/* check btf existence */
9502 	btf = bpf_object__btf(map->obj);
9503 	if (!btf)
9504 		return -ENOENT;
9505 
9506 	/* verify map is datasec */
9507 	datasec_type = btf_type_by_id(btf, bpf_map__btf_value_type_id(map));
9508 	if (!btf_is_datasec(datasec_type)) {
9509 		pr_warn("map '%s': cannot be resized, map value type is not a datasec\n",
9510 			bpf_map__name(map));
9511 		return -EINVAL;
9512 	}
9513 
9514 	/* verify datasec has at least one var */
9515 	vlen = btf_vlen(datasec_type);
9516 	if (vlen == 0) {
9517 		pr_warn("map '%s': cannot be resized, map value datasec is empty\n",
9518 			bpf_map__name(map));
9519 		return -EINVAL;
9520 	}
9521 
9522 	/* verify last var in the datasec is an array */
9523 	var = &btf_var_secinfos(datasec_type)[vlen - 1];
9524 	var_type = btf_type_by_id(btf, var->type);
9525 	array_type = skip_mods_and_typedefs(btf, var_type->type, NULL);
9526 	if (!btf_is_array(array_type)) {
9527 		pr_warn("map '%s': cannot be resized, last var must be an array\n",
9528 			bpf_map__name(map));
9529 		return -EINVAL;
9530 	}
9531 
9532 	/* verify request size aligns with array */
9533 	array = btf_array(array_type);
9534 	element_sz = btf__resolve_size(btf, array->type);
9535 	if (element_sz <= 0 || (size - var->offset) % element_sz != 0) {
9536 		pr_warn("map '%s': cannot be resized, element size (%d) doesn't align with new total size (%u)\n",
9537 			bpf_map__name(map), element_sz, size);
9538 		return -EINVAL;
9539 	}
9540 
9541 	/* create a new array based on the existing array, but with new length */
9542 	nr_elements = (size - var->offset) / element_sz;
9543 	new_array_id = btf__add_array(btf, array->index_type, array->type, nr_elements);
9544 	if (new_array_id < 0)
9545 		return new_array_id;
9546 
9547 	/* adding a new btf type invalidates existing pointers to btf objects,
9548 	 * so refresh pointers before proceeding
9549 	 */
9550 	datasec_type = btf_type_by_id(btf, map->btf_value_type_id);
9551 	var = &btf_var_secinfos(datasec_type)[vlen - 1];
9552 	var_type = btf_type_by_id(btf, var->type);
9553 
9554 	/* finally update btf info */
9555 	datasec_type->size = size;
9556 	var->size = size - var->offset;
9557 	var_type->type = new_array_id;
9558 
9559 	return 0;
9560 }
9561 
9562 int bpf_map__set_value_size(struct bpf_map *map, __u32 size)
9563 {
9564 	if (map->fd >= 0)
9565 		return libbpf_err(-EBUSY);
9566 
9567 	if (map->mmaped) {
9568 		int err;
9569 		size_t mmap_old_sz, mmap_new_sz;
9570 
9571 		mmap_old_sz = bpf_map_mmap_sz(map->def.value_size, map->def.max_entries);
9572 		mmap_new_sz = bpf_map_mmap_sz(size, map->def.max_entries);
9573 		err = bpf_map_mmap_resize(map, mmap_old_sz, mmap_new_sz);
9574 		if (err) {
9575 			pr_warn("map '%s': failed to resize memory-mapped region: %d\n",
9576 				bpf_map__name(map), err);
9577 			return err;
9578 		}
9579 		err = map_btf_datasec_resize(map, size);
9580 		if (err && err != -ENOENT) {
9581 			pr_warn("map '%s': failed to adjust resized BTF, clearing BTF key/value info: %d\n",
9582 				bpf_map__name(map), err);
9583 			map->btf_value_type_id = 0;
9584 			map->btf_key_type_id = 0;
9585 		}
9586 	}
9587 
9588 	map->def.value_size = size;
9589 	return 0;
9590 }
9591 
9592 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
9593 {
9594 	return map ? map->btf_key_type_id : 0;
9595 }
9596 
9597 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
9598 {
9599 	return map ? map->btf_value_type_id : 0;
9600 }
9601 
9602 int bpf_map__set_initial_value(struct bpf_map *map,
9603 			       const void *data, size_t size)
9604 {
9605 	if (!map->mmaped || map->libbpf_type == LIBBPF_MAP_KCONFIG ||
9606 	    size != map->def.value_size || map->fd >= 0)
9607 		return libbpf_err(-EINVAL);
9608 
9609 	memcpy(map->mmaped, data, size);
9610 	return 0;
9611 }
9612 
9613 void *bpf_map__initial_value(struct bpf_map *map, size_t *psize)
9614 {
9615 	if (!map->mmaped)
9616 		return NULL;
9617 	*psize = map->def.value_size;
9618 	return map->mmaped;
9619 }
9620 
9621 bool bpf_map__is_internal(const struct bpf_map *map)
9622 {
9623 	return map->libbpf_type != LIBBPF_MAP_UNSPEC;
9624 }
9625 
9626 __u32 bpf_map__ifindex(const struct bpf_map *map)
9627 {
9628 	return map->map_ifindex;
9629 }
9630 
9631 int bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
9632 {
9633 	if (map->fd >= 0)
9634 		return libbpf_err(-EBUSY);
9635 	map->map_ifindex = ifindex;
9636 	return 0;
9637 }
9638 
9639 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
9640 {
9641 	if (!bpf_map_type__is_map_in_map(map->def.type)) {
9642 		pr_warn("error: unsupported map type\n");
9643 		return libbpf_err(-EINVAL);
9644 	}
9645 	if (map->inner_map_fd != -1) {
9646 		pr_warn("error: inner_map_fd already specified\n");
9647 		return libbpf_err(-EINVAL);
9648 	}
9649 	if (map->inner_map) {
9650 		bpf_map__destroy(map->inner_map);
9651 		zfree(&map->inner_map);
9652 	}
9653 	map->inner_map_fd = fd;
9654 	return 0;
9655 }
9656 
9657 static struct bpf_map *
9658 __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
9659 {
9660 	ssize_t idx;
9661 	struct bpf_map *s, *e;
9662 
9663 	if (!obj || !obj->maps)
9664 		return errno = EINVAL, NULL;
9665 
9666 	s = obj->maps;
9667 	e = obj->maps + obj->nr_maps;
9668 
9669 	if ((m < s) || (m >= e)) {
9670 		pr_warn("error in %s: map handler doesn't belong to object\n",
9671 			 __func__);
9672 		return errno = EINVAL, NULL;
9673 	}
9674 
9675 	idx = (m - obj->maps) + i;
9676 	if (idx >= obj->nr_maps || idx < 0)
9677 		return NULL;
9678 	return &obj->maps[idx];
9679 }
9680 
9681 struct bpf_map *
9682 bpf_object__next_map(const struct bpf_object *obj, const struct bpf_map *prev)
9683 {
9684 	if (prev == NULL)
9685 		return obj->maps;
9686 
9687 	return __bpf_map__iter(prev, obj, 1);
9688 }
9689 
9690 struct bpf_map *
9691 bpf_object__prev_map(const struct bpf_object *obj, const struct bpf_map *next)
9692 {
9693 	if (next == NULL) {
9694 		if (!obj->nr_maps)
9695 			return NULL;
9696 		return obj->maps + obj->nr_maps - 1;
9697 	}
9698 
9699 	return __bpf_map__iter(next, obj, -1);
9700 }
9701 
9702 struct bpf_map *
9703 bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
9704 {
9705 	struct bpf_map *pos;
9706 
9707 	bpf_object__for_each_map(pos, obj) {
9708 		/* if it's a special internal map name (which always starts
9709 		 * with dot) then check if that special name matches the
9710 		 * real map name (ELF section name)
9711 		 */
9712 		if (name[0] == '.') {
9713 			if (pos->real_name && strcmp(pos->real_name, name) == 0)
9714 				return pos;
9715 			continue;
9716 		}
9717 		/* otherwise map name has to be an exact match */
9718 		if (map_uses_real_name(pos)) {
9719 			if (strcmp(pos->real_name, name) == 0)
9720 				return pos;
9721 			continue;
9722 		}
9723 		if (strcmp(pos->name, name) == 0)
9724 			return pos;
9725 	}
9726 	return errno = ENOENT, NULL;
9727 }
9728 
9729 int
9730 bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
9731 {
9732 	return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
9733 }
9734 
9735 static int validate_map_op(const struct bpf_map *map, size_t key_sz,
9736 			   size_t value_sz, bool check_value_sz)
9737 {
9738 	if (map->fd <= 0)
9739 		return -ENOENT;
9740 
9741 	if (map->def.key_size != key_sz) {
9742 		pr_warn("map '%s': unexpected key size %zu provided, expected %u\n",
9743 			map->name, key_sz, map->def.key_size);
9744 		return -EINVAL;
9745 	}
9746 
9747 	if (!check_value_sz)
9748 		return 0;
9749 
9750 	switch (map->def.type) {
9751 	case BPF_MAP_TYPE_PERCPU_ARRAY:
9752 	case BPF_MAP_TYPE_PERCPU_HASH:
9753 	case BPF_MAP_TYPE_LRU_PERCPU_HASH:
9754 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: {
9755 		int num_cpu = libbpf_num_possible_cpus();
9756 		size_t elem_sz = roundup(map->def.value_size, 8);
9757 
9758 		if (value_sz != num_cpu * elem_sz) {
9759 			pr_warn("map '%s': unexpected value size %zu provided for per-CPU map, expected %d * %zu = %zd\n",
9760 				map->name, value_sz, num_cpu, elem_sz, num_cpu * elem_sz);
9761 			return -EINVAL;
9762 		}
9763 		break;
9764 	}
9765 	default:
9766 		if (map->def.value_size != value_sz) {
9767 			pr_warn("map '%s': unexpected value size %zu provided, expected %u\n",
9768 				map->name, value_sz, map->def.value_size);
9769 			return -EINVAL;
9770 		}
9771 		break;
9772 	}
9773 	return 0;
9774 }
9775 
9776 int bpf_map__lookup_elem(const struct bpf_map *map,
9777 			 const void *key, size_t key_sz,
9778 			 void *value, size_t value_sz, __u64 flags)
9779 {
9780 	int err;
9781 
9782 	err = validate_map_op(map, key_sz, value_sz, true);
9783 	if (err)
9784 		return libbpf_err(err);
9785 
9786 	return bpf_map_lookup_elem_flags(map->fd, key, value, flags);
9787 }
9788 
9789 int bpf_map__update_elem(const struct bpf_map *map,
9790 			 const void *key, size_t key_sz,
9791 			 const void *value, size_t value_sz, __u64 flags)
9792 {
9793 	int err;
9794 
9795 	err = validate_map_op(map, key_sz, value_sz, true);
9796 	if (err)
9797 		return libbpf_err(err);
9798 
9799 	return bpf_map_update_elem(map->fd, key, value, flags);
9800 }
9801 
9802 int bpf_map__delete_elem(const struct bpf_map *map,
9803 			 const void *key, size_t key_sz, __u64 flags)
9804 {
9805 	int err;
9806 
9807 	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */);
9808 	if (err)
9809 		return libbpf_err(err);
9810 
9811 	return bpf_map_delete_elem_flags(map->fd, key, flags);
9812 }
9813 
9814 int bpf_map__lookup_and_delete_elem(const struct bpf_map *map,
9815 				    const void *key, size_t key_sz,
9816 				    void *value, size_t value_sz, __u64 flags)
9817 {
9818 	int err;
9819 
9820 	err = validate_map_op(map, key_sz, value_sz, true);
9821 	if (err)
9822 		return libbpf_err(err);
9823 
9824 	return bpf_map_lookup_and_delete_elem_flags(map->fd, key, value, flags);
9825 }
9826 
9827 int bpf_map__get_next_key(const struct bpf_map *map,
9828 			  const void *cur_key, void *next_key, size_t key_sz)
9829 {
9830 	int err;
9831 
9832 	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */);
9833 	if (err)
9834 		return libbpf_err(err);
9835 
9836 	return bpf_map_get_next_key(map->fd, cur_key, next_key);
9837 }
9838 
9839 long libbpf_get_error(const void *ptr)
9840 {
9841 	if (!IS_ERR_OR_NULL(ptr))
9842 		return 0;
9843 
9844 	if (IS_ERR(ptr))
9845 		errno = -PTR_ERR(ptr);
9846 
9847 	/* If ptr == NULL, then errno should be already set by the failing
9848 	 * API, because libbpf never returns NULL on success and it now always
9849 	 * sets errno on error. So no extra errno handling for ptr == NULL
9850 	 * case.
9851 	 */
9852 	return -errno;
9853 }
9854 
9855 /* Replace link's underlying BPF program with the new one */
9856 int bpf_link__update_program(struct bpf_link *link, struct bpf_program *prog)
9857 {
9858 	int ret;
9859 
9860 	ret = bpf_link_update(bpf_link__fd(link), bpf_program__fd(prog), NULL);
9861 	return libbpf_err_errno(ret);
9862 }
9863 
9864 /* Release "ownership" of underlying BPF resource (typically, BPF program
9865  * attached to some BPF hook, e.g., tracepoint, kprobe, etc). Disconnected
9866  * link, when destructed through bpf_link__destroy() call won't attempt to
9867  * detach/unregisted that BPF resource. This is useful in situations where,
9868  * say, attached BPF program has to outlive userspace program that attached it
9869  * in the system. Depending on type of BPF program, though, there might be
9870  * additional steps (like pinning BPF program in BPF FS) necessary to ensure
9871  * exit of userspace program doesn't trigger automatic detachment and clean up
9872  * inside the kernel.
9873  */
9874 void bpf_link__disconnect(struct bpf_link *link)
9875 {
9876 	link->disconnected = true;
9877 }
9878 
9879 int bpf_link__destroy(struct bpf_link *link)
9880 {
9881 	int err = 0;
9882 
9883 	if (IS_ERR_OR_NULL(link))
9884 		return 0;
9885 
9886 	if (!link->disconnected && link->detach)
9887 		err = link->detach(link);
9888 	if (link->pin_path)
9889 		free(link->pin_path);
9890 	if (link->dealloc)
9891 		link->dealloc(link);
9892 	else
9893 		free(link);
9894 
9895 	return libbpf_err(err);
9896 }
9897 
9898 int bpf_link__fd(const struct bpf_link *link)
9899 {
9900 	return link->fd;
9901 }
9902 
9903 const char *bpf_link__pin_path(const struct bpf_link *link)
9904 {
9905 	return link->pin_path;
9906 }
9907 
9908 static int bpf_link__detach_fd(struct bpf_link *link)
9909 {
9910 	return libbpf_err_errno(close(link->fd));
9911 }
9912 
9913 struct bpf_link *bpf_link__open(const char *path)
9914 {
9915 	struct bpf_link *link;
9916 	int fd;
9917 
9918 	fd = bpf_obj_get(path);
9919 	if (fd < 0) {
9920 		fd = -errno;
9921 		pr_warn("failed to open link at %s: %d\n", path, fd);
9922 		return libbpf_err_ptr(fd);
9923 	}
9924 
9925 	link = calloc(1, sizeof(*link));
9926 	if (!link) {
9927 		close(fd);
9928 		return libbpf_err_ptr(-ENOMEM);
9929 	}
9930 	link->detach = &bpf_link__detach_fd;
9931 	link->fd = fd;
9932 
9933 	link->pin_path = strdup(path);
9934 	if (!link->pin_path) {
9935 		bpf_link__destroy(link);
9936 		return libbpf_err_ptr(-ENOMEM);
9937 	}
9938 
9939 	return link;
9940 }
9941 
9942 int bpf_link__detach(struct bpf_link *link)
9943 {
9944 	return bpf_link_detach(link->fd) ? -errno : 0;
9945 }
9946 
9947 int bpf_link__pin(struct bpf_link *link, const char *path)
9948 {
9949 	int err;
9950 
9951 	if (link->pin_path)
9952 		return libbpf_err(-EBUSY);
9953 	err = make_parent_dir(path);
9954 	if (err)
9955 		return libbpf_err(err);
9956 	err = check_path(path);
9957 	if (err)
9958 		return libbpf_err(err);
9959 
9960 	link->pin_path = strdup(path);
9961 	if (!link->pin_path)
9962 		return libbpf_err(-ENOMEM);
9963 
9964 	if (bpf_obj_pin(link->fd, link->pin_path)) {
9965 		err = -errno;
9966 		zfree(&link->pin_path);
9967 		return libbpf_err(err);
9968 	}
9969 
9970 	pr_debug("link fd=%d: pinned at %s\n", link->fd, link->pin_path);
9971 	return 0;
9972 }
9973 
9974 int bpf_link__unpin(struct bpf_link *link)
9975 {
9976 	int err;
9977 
9978 	if (!link->pin_path)
9979 		return libbpf_err(-EINVAL);
9980 
9981 	err = unlink(link->pin_path);
9982 	if (err != 0)
9983 		return -errno;
9984 
9985 	pr_debug("link fd=%d: unpinned from %s\n", link->fd, link->pin_path);
9986 	zfree(&link->pin_path);
9987 	return 0;
9988 }
9989 
9990 struct bpf_link_perf {
9991 	struct bpf_link link;
9992 	int perf_event_fd;
9993 	/* legacy kprobe support: keep track of probe identifier and type */
9994 	char *legacy_probe_name;
9995 	bool legacy_is_kprobe;
9996 	bool legacy_is_retprobe;
9997 };
9998 
9999 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe);
10000 static int remove_uprobe_event_legacy(const char *probe_name, bool retprobe);
10001 
10002 static int bpf_link_perf_detach(struct bpf_link *link)
10003 {
10004 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10005 	int err = 0;
10006 
10007 	if (ioctl(perf_link->perf_event_fd, PERF_EVENT_IOC_DISABLE, 0) < 0)
10008 		err = -errno;
10009 
10010 	if (perf_link->perf_event_fd != link->fd)
10011 		close(perf_link->perf_event_fd);
10012 	close(link->fd);
10013 
10014 	/* legacy uprobe/kprobe needs to be removed after perf event fd closure */
10015 	if (perf_link->legacy_probe_name) {
10016 		if (perf_link->legacy_is_kprobe) {
10017 			err = remove_kprobe_event_legacy(perf_link->legacy_probe_name,
10018 							 perf_link->legacy_is_retprobe);
10019 		} else {
10020 			err = remove_uprobe_event_legacy(perf_link->legacy_probe_name,
10021 							 perf_link->legacy_is_retprobe);
10022 		}
10023 	}
10024 
10025 	return err;
10026 }
10027 
10028 static void bpf_link_perf_dealloc(struct bpf_link *link)
10029 {
10030 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10031 
10032 	free(perf_link->legacy_probe_name);
10033 	free(perf_link);
10034 }
10035 
10036 struct bpf_link *bpf_program__attach_perf_event_opts(const struct bpf_program *prog, int pfd,
10037 						     const struct bpf_perf_event_opts *opts)
10038 {
10039 	char errmsg[STRERR_BUFSIZE];
10040 	struct bpf_link_perf *link;
10041 	int prog_fd, link_fd = -1, err;
10042 	bool force_ioctl_attach;
10043 
10044 	if (!OPTS_VALID(opts, bpf_perf_event_opts))
10045 		return libbpf_err_ptr(-EINVAL);
10046 
10047 	if (pfd < 0) {
10048 		pr_warn("prog '%s': invalid perf event FD %d\n",
10049 			prog->name, pfd);
10050 		return libbpf_err_ptr(-EINVAL);
10051 	}
10052 	prog_fd = bpf_program__fd(prog);
10053 	if (prog_fd < 0) {
10054 		pr_warn("prog '%s': can't attach BPF program w/o FD (did you load it?)\n",
10055 			prog->name);
10056 		return libbpf_err_ptr(-EINVAL);
10057 	}
10058 
10059 	link = calloc(1, sizeof(*link));
10060 	if (!link)
10061 		return libbpf_err_ptr(-ENOMEM);
10062 	link->link.detach = &bpf_link_perf_detach;
10063 	link->link.dealloc = &bpf_link_perf_dealloc;
10064 	link->perf_event_fd = pfd;
10065 
10066 	force_ioctl_attach = OPTS_GET(opts, force_ioctl_attach, false);
10067 	if (kernel_supports(prog->obj, FEAT_PERF_LINK) && !force_ioctl_attach) {
10068 		DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_opts,
10069 			.perf_event.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0));
10070 
10071 		link_fd = bpf_link_create(prog_fd, pfd, BPF_PERF_EVENT, &link_opts);
10072 		if (link_fd < 0) {
10073 			err = -errno;
10074 			pr_warn("prog '%s': failed to create BPF link for perf_event FD %d: %d (%s)\n",
10075 				prog->name, pfd,
10076 				err, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10077 			goto err_out;
10078 		}
10079 		link->link.fd = link_fd;
10080 	} else {
10081 		if (OPTS_GET(opts, bpf_cookie, 0)) {
10082 			pr_warn("prog '%s': user context value is not supported\n", prog->name);
10083 			err = -EOPNOTSUPP;
10084 			goto err_out;
10085 		}
10086 
10087 		if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
10088 			err = -errno;
10089 			pr_warn("prog '%s': failed to attach to perf_event FD %d: %s\n",
10090 				prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10091 			if (err == -EPROTO)
10092 				pr_warn("prog '%s': try add PERF_SAMPLE_CALLCHAIN to or remove exclude_callchain_[kernel|user] from pfd %d\n",
10093 					prog->name, pfd);
10094 			goto err_out;
10095 		}
10096 		link->link.fd = pfd;
10097 	}
10098 	if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
10099 		err = -errno;
10100 		pr_warn("prog '%s': failed to enable perf_event FD %d: %s\n",
10101 			prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10102 		goto err_out;
10103 	}
10104 
10105 	return &link->link;
10106 err_out:
10107 	if (link_fd >= 0)
10108 		close(link_fd);
10109 	free(link);
10110 	return libbpf_err_ptr(err);
10111 }
10112 
10113 struct bpf_link *bpf_program__attach_perf_event(const struct bpf_program *prog, int pfd)
10114 {
10115 	return bpf_program__attach_perf_event_opts(prog, pfd, NULL);
10116 }
10117 
10118 /*
10119  * this function is expected to parse integer in the range of [0, 2^31-1] from
10120  * given file using scanf format string fmt. If actual parsed value is
10121  * negative, the result might be indistinguishable from error
10122  */
10123 static int parse_uint_from_file(const char *file, const char *fmt)
10124 {
10125 	char buf[STRERR_BUFSIZE];
10126 	int err, ret;
10127 	FILE *f;
10128 
10129 	f = fopen(file, "re");
10130 	if (!f) {
10131 		err = -errno;
10132 		pr_debug("failed to open '%s': %s\n", file,
10133 			 libbpf_strerror_r(err, buf, sizeof(buf)));
10134 		return err;
10135 	}
10136 	err = fscanf(f, fmt, &ret);
10137 	if (err != 1) {
10138 		err = err == EOF ? -EIO : -errno;
10139 		pr_debug("failed to parse '%s': %s\n", file,
10140 			libbpf_strerror_r(err, buf, sizeof(buf)));
10141 		fclose(f);
10142 		return err;
10143 	}
10144 	fclose(f);
10145 	return ret;
10146 }
10147 
10148 static int determine_kprobe_perf_type(void)
10149 {
10150 	const char *file = "/sys/bus/event_source/devices/kprobe/type";
10151 
10152 	return parse_uint_from_file(file, "%d\n");
10153 }
10154 
10155 static int determine_uprobe_perf_type(void)
10156 {
10157 	const char *file = "/sys/bus/event_source/devices/uprobe/type";
10158 
10159 	return parse_uint_from_file(file, "%d\n");
10160 }
10161 
10162 static int determine_kprobe_retprobe_bit(void)
10163 {
10164 	const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
10165 
10166 	return parse_uint_from_file(file, "config:%d\n");
10167 }
10168 
10169 static int determine_uprobe_retprobe_bit(void)
10170 {
10171 	const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
10172 
10173 	return parse_uint_from_file(file, "config:%d\n");
10174 }
10175 
10176 #define PERF_UPROBE_REF_CTR_OFFSET_BITS 32
10177 #define PERF_UPROBE_REF_CTR_OFFSET_SHIFT 32
10178 
10179 static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
10180 				 uint64_t offset, int pid, size_t ref_ctr_off)
10181 {
10182 	const size_t attr_sz = sizeof(struct perf_event_attr);
10183 	struct perf_event_attr attr;
10184 	char errmsg[STRERR_BUFSIZE];
10185 	int type, pfd;
10186 
10187 	if ((__u64)ref_ctr_off >= (1ULL << PERF_UPROBE_REF_CTR_OFFSET_BITS))
10188 		return -EINVAL;
10189 
10190 	memset(&attr, 0, attr_sz);
10191 
10192 	type = uprobe ? determine_uprobe_perf_type()
10193 		      : determine_kprobe_perf_type();
10194 	if (type < 0) {
10195 		pr_warn("failed to determine %s perf type: %s\n",
10196 			uprobe ? "uprobe" : "kprobe",
10197 			libbpf_strerror_r(type, errmsg, sizeof(errmsg)));
10198 		return type;
10199 	}
10200 	if (retprobe) {
10201 		int bit = uprobe ? determine_uprobe_retprobe_bit()
10202 				 : determine_kprobe_retprobe_bit();
10203 
10204 		if (bit < 0) {
10205 			pr_warn("failed to determine %s retprobe bit: %s\n",
10206 				uprobe ? "uprobe" : "kprobe",
10207 				libbpf_strerror_r(bit, errmsg, sizeof(errmsg)));
10208 			return bit;
10209 		}
10210 		attr.config |= 1 << bit;
10211 	}
10212 	attr.size = attr_sz;
10213 	attr.type = type;
10214 	attr.config |= (__u64)ref_ctr_off << PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
10215 	attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
10216 	attr.config2 = offset;		 /* kprobe_addr or probe_offset */
10217 
10218 	/* pid filter is meaningful only for uprobes */
10219 	pfd = syscall(__NR_perf_event_open, &attr,
10220 		      pid < 0 ? -1 : pid /* pid */,
10221 		      pid == -1 ? 0 : -1 /* cpu */,
10222 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
10223 	return pfd >= 0 ? pfd : -errno;
10224 }
10225 
10226 static int append_to_file(const char *file, const char *fmt, ...)
10227 {
10228 	int fd, n, err = 0;
10229 	va_list ap;
10230 	char buf[1024];
10231 
10232 	va_start(ap, fmt);
10233 	n = vsnprintf(buf, sizeof(buf), fmt, ap);
10234 	va_end(ap);
10235 
10236 	if (n < 0 || n >= sizeof(buf))
10237 		return -EINVAL;
10238 
10239 	fd = open(file, O_WRONLY | O_APPEND | O_CLOEXEC, 0);
10240 	if (fd < 0)
10241 		return -errno;
10242 
10243 	if (write(fd, buf, n) < 0)
10244 		err = -errno;
10245 
10246 	close(fd);
10247 	return err;
10248 }
10249 
10250 #define DEBUGFS "/sys/kernel/debug/tracing"
10251 #define TRACEFS "/sys/kernel/tracing"
10252 
10253 static bool use_debugfs(void)
10254 {
10255 	static int has_debugfs = -1;
10256 
10257 	if (has_debugfs < 0)
10258 		has_debugfs = faccessat(AT_FDCWD, DEBUGFS, F_OK, AT_EACCESS) == 0;
10259 
10260 	return has_debugfs == 1;
10261 }
10262 
10263 static const char *tracefs_path(void)
10264 {
10265 	return use_debugfs() ? DEBUGFS : TRACEFS;
10266 }
10267 
10268 static const char *tracefs_kprobe_events(void)
10269 {
10270 	return use_debugfs() ? DEBUGFS"/kprobe_events" : TRACEFS"/kprobe_events";
10271 }
10272 
10273 static const char *tracefs_uprobe_events(void)
10274 {
10275 	return use_debugfs() ? DEBUGFS"/uprobe_events" : TRACEFS"/uprobe_events";
10276 }
10277 
10278 static const char *tracefs_available_filter_functions(void)
10279 {
10280 	return use_debugfs() ? DEBUGFS"/available_filter_functions"
10281 			     : TRACEFS"/available_filter_functions";
10282 }
10283 
10284 static const char *tracefs_available_filter_functions_addrs(void)
10285 {
10286 	return use_debugfs() ? DEBUGFS"/available_filter_functions_addrs"
10287 			     : TRACEFS"/available_filter_functions_addrs";
10288 }
10289 
10290 static void gen_kprobe_legacy_event_name(char *buf, size_t buf_sz,
10291 					 const char *kfunc_name, size_t offset)
10292 {
10293 	static int index = 0;
10294 	int i;
10295 
10296 	snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx_%d", getpid(), kfunc_name, offset,
10297 		 __sync_fetch_and_add(&index, 1));
10298 
10299 	/* sanitize binary_path in the probe name */
10300 	for (i = 0; buf[i]; i++) {
10301 		if (!isalnum(buf[i]))
10302 			buf[i] = '_';
10303 	}
10304 }
10305 
10306 static int add_kprobe_event_legacy(const char *probe_name, bool retprobe,
10307 				   const char *kfunc_name, size_t offset)
10308 {
10309 	return append_to_file(tracefs_kprobe_events(), "%c:%s/%s %s+0x%zx",
10310 			      retprobe ? 'r' : 'p',
10311 			      retprobe ? "kretprobes" : "kprobes",
10312 			      probe_name, kfunc_name, offset);
10313 }
10314 
10315 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe)
10316 {
10317 	return append_to_file(tracefs_kprobe_events(), "-:%s/%s",
10318 			      retprobe ? "kretprobes" : "kprobes", probe_name);
10319 }
10320 
10321 static int determine_kprobe_perf_type_legacy(const char *probe_name, bool retprobe)
10322 {
10323 	char file[256];
10324 
10325 	snprintf(file, sizeof(file), "%s/events/%s/%s/id",
10326 		 tracefs_path(), retprobe ? "kretprobes" : "kprobes", probe_name);
10327 
10328 	return parse_uint_from_file(file, "%d\n");
10329 }
10330 
10331 static int perf_event_kprobe_open_legacy(const char *probe_name, bool retprobe,
10332 					 const char *kfunc_name, size_t offset, int pid)
10333 {
10334 	const size_t attr_sz = sizeof(struct perf_event_attr);
10335 	struct perf_event_attr attr;
10336 	char errmsg[STRERR_BUFSIZE];
10337 	int type, pfd, err;
10338 
10339 	err = add_kprobe_event_legacy(probe_name, retprobe, kfunc_name, offset);
10340 	if (err < 0) {
10341 		pr_warn("failed to add legacy kprobe event for '%s+0x%zx': %s\n",
10342 			kfunc_name, offset,
10343 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10344 		return err;
10345 	}
10346 	type = determine_kprobe_perf_type_legacy(probe_name, retprobe);
10347 	if (type < 0) {
10348 		err = type;
10349 		pr_warn("failed to determine legacy kprobe event id for '%s+0x%zx': %s\n",
10350 			kfunc_name, offset,
10351 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10352 		goto err_clean_legacy;
10353 	}
10354 
10355 	memset(&attr, 0, attr_sz);
10356 	attr.size = attr_sz;
10357 	attr.config = type;
10358 	attr.type = PERF_TYPE_TRACEPOINT;
10359 
10360 	pfd = syscall(__NR_perf_event_open, &attr,
10361 		      pid < 0 ? -1 : pid, /* pid */
10362 		      pid == -1 ? 0 : -1, /* cpu */
10363 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
10364 	if (pfd < 0) {
10365 		err = -errno;
10366 		pr_warn("legacy kprobe perf_event_open() failed: %s\n",
10367 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10368 		goto err_clean_legacy;
10369 	}
10370 	return pfd;
10371 
10372 err_clean_legacy:
10373 	/* Clear the newly added legacy kprobe_event */
10374 	remove_kprobe_event_legacy(probe_name, retprobe);
10375 	return err;
10376 }
10377 
10378 static const char *arch_specific_syscall_pfx(void)
10379 {
10380 #if defined(__x86_64__)
10381 	return "x64";
10382 #elif defined(__i386__)
10383 	return "ia32";
10384 #elif defined(__s390x__)
10385 	return "s390x";
10386 #elif defined(__s390__)
10387 	return "s390";
10388 #elif defined(__arm__)
10389 	return "arm";
10390 #elif defined(__aarch64__)
10391 	return "arm64";
10392 #elif defined(__mips__)
10393 	return "mips";
10394 #elif defined(__riscv)
10395 	return "riscv";
10396 #elif defined(__powerpc__)
10397 	return "powerpc";
10398 #elif defined(__powerpc64__)
10399 	return "powerpc64";
10400 #else
10401 	return NULL;
10402 #endif
10403 }
10404 
10405 static int probe_kern_syscall_wrapper(void)
10406 {
10407 	char syscall_name[64];
10408 	const char *ksys_pfx;
10409 
10410 	ksys_pfx = arch_specific_syscall_pfx();
10411 	if (!ksys_pfx)
10412 		return 0;
10413 
10414 	snprintf(syscall_name, sizeof(syscall_name), "__%s_sys_bpf", ksys_pfx);
10415 
10416 	if (determine_kprobe_perf_type() >= 0) {
10417 		int pfd;
10418 
10419 		pfd = perf_event_open_probe(false, false, syscall_name, 0, getpid(), 0);
10420 		if (pfd >= 0)
10421 			close(pfd);
10422 
10423 		return pfd >= 0 ? 1 : 0;
10424 	} else { /* legacy mode */
10425 		char probe_name[128];
10426 
10427 		gen_kprobe_legacy_event_name(probe_name, sizeof(probe_name), syscall_name, 0);
10428 		if (add_kprobe_event_legacy(probe_name, false, syscall_name, 0) < 0)
10429 			return 0;
10430 
10431 		(void)remove_kprobe_event_legacy(probe_name, false);
10432 		return 1;
10433 	}
10434 }
10435 
10436 struct bpf_link *
10437 bpf_program__attach_kprobe_opts(const struct bpf_program *prog,
10438 				const char *func_name,
10439 				const struct bpf_kprobe_opts *opts)
10440 {
10441 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
10442 	enum probe_attach_mode attach_mode;
10443 	char errmsg[STRERR_BUFSIZE];
10444 	char *legacy_probe = NULL;
10445 	struct bpf_link *link;
10446 	size_t offset;
10447 	bool retprobe, legacy;
10448 	int pfd, err;
10449 
10450 	if (!OPTS_VALID(opts, bpf_kprobe_opts))
10451 		return libbpf_err_ptr(-EINVAL);
10452 
10453 	attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
10454 	retprobe = OPTS_GET(opts, retprobe, false);
10455 	offset = OPTS_GET(opts, offset, 0);
10456 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
10457 
10458 	legacy = determine_kprobe_perf_type() < 0;
10459 	switch (attach_mode) {
10460 	case PROBE_ATTACH_MODE_LEGACY:
10461 		legacy = true;
10462 		pe_opts.force_ioctl_attach = true;
10463 		break;
10464 	case PROBE_ATTACH_MODE_PERF:
10465 		if (legacy)
10466 			return libbpf_err_ptr(-ENOTSUP);
10467 		pe_opts.force_ioctl_attach = true;
10468 		break;
10469 	case PROBE_ATTACH_MODE_LINK:
10470 		if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
10471 			return libbpf_err_ptr(-ENOTSUP);
10472 		break;
10473 	case PROBE_ATTACH_MODE_DEFAULT:
10474 		break;
10475 	default:
10476 		return libbpf_err_ptr(-EINVAL);
10477 	}
10478 
10479 	if (!legacy) {
10480 		pfd = perf_event_open_probe(false /* uprobe */, retprobe,
10481 					    func_name, offset,
10482 					    -1 /* pid */, 0 /* ref_ctr_off */);
10483 	} else {
10484 		char probe_name[256];
10485 
10486 		gen_kprobe_legacy_event_name(probe_name, sizeof(probe_name),
10487 					     func_name, offset);
10488 
10489 		legacy_probe = strdup(probe_name);
10490 		if (!legacy_probe)
10491 			return libbpf_err_ptr(-ENOMEM);
10492 
10493 		pfd = perf_event_kprobe_open_legacy(legacy_probe, retprobe, func_name,
10494 						    offset, -1 /* pid */);
10495 	}
10496 	if (pfd < 0) {
10497 		err = -errno;
10498 		pr_warn("prog '%s': failed to create %s '%s+0x%zx' perf event: %s\n",
10499 			prog->name, retprobe ? "kretprobe" : "kprobe",
10500 			func_name, offset,
10501 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10502 		goto err_out;
10503 	}
10504 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
10505 	err = libbpf_get_error(link);
10506 	if (err) {
10507 		close(pfd);
10508 		pr_warn("prog '%s': failed to attach to %s '%s+0x%zx': %s\n",
10509 			prog->name, retprobe ? "kretprobe" : "kprobe",
10510 			func_name, offset,
10511 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10512 		goto err_clean_legacy;
10513 	}
10514 	if (legacy) {
10515 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10516 
10517 		perf_link->legacy_probe_name = legacy_probe;
10518 		perf_link->legacy_is_kprobe = true;
10519 		perf_link->legacy_is_retprobe = retprobe;
10520 	}
10521 
10522 	return link;
10523 
10524 err_clean_legacy:
10525 	if (legacy)
10526 		remove_kprobe_event_legacy(legacy_probe, retprobe);
10527 err_out:
10528 	free(legacy_probe);
10529 	return libbpf_err_ptr(err);
10530 }
10531 
10532 struct bpf_link *bpf_program__attach_kprobe(const struct bpf_program *prog,
10533 					    bool retprobe,
10534 					    const char *func_name)
10535 {
10536 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts,
10537 		.retprobe = retprobe,
10538 	);
10539 
10540 	return bpf_program__attach_kprobe_opts(prog, func_name, &opts);
10541 }
10542 
10543 struct bpf_link *bpf_program__attach_ksyscall(const struct bpf_program *prog,
10544 					      const char *syscall_name,
10545 					      const struct bpf_ksyscall_opts *opts)
10546 {
10547 	LIBBPF_OPTS(bpf_kprobe_opts, kprobe_opts);
10548 	char func_name[128];
10549 
10550 	if (!OPTS_VALID(opts, bpf_ksyscall_opts))
10551 		return libbpf_err_ptr(-EINVAL);
10552 
10553 	if (kernel_supports(prog->obj, FEAT_SYSCALL_WRAPPER)) {
10554 		/* arch_specific_syscall_pfx() should never return NULL here
10555 		 * because it is guarded by kernel_supports(). However, since
10556 		 * compiler does not know that we have an explicit conditional
10557 		 * as well.
10558 		 */
10559 		snprintf(func_name, sizeof(func_name), "__%s_sys_%s",
10560 			 arch_specific_syscall_pfx() ? : "", syscall_name);
10561 	} else {
10562 		snprintf(func_name, sizeof(func_name), "__se_sys_%s", syscall_name);
10563 	}
10564 
10565 	kprobe_opts.retprobe = OPTS_GET(opts, retprobe, false);
10566 	kprobe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
10567 
10568 	return bpf_program__attach_kprobe_opts(prog, func_name, &kprobe_opts);
10569 }
10570 
10571 /* Adapted from perf/util/string.c */
10572 static bool glob_match(const char *str, const char *pat)
10573 {
10574 	while (*str && *pat && *pat != '*') {
10575 		if (*pat == '?') {      /* Matches any single character */
10576 			str++;
10577 			pat++;
10578 			continue;
10579 		}
10580 		if (*str != *pat)
10581 			return false;
10582 		str++;
10583 		pat++;
10584 	}
10585 	/* Check wild card */
10586 	if (*pat == '*') {
10587 		while (*pat == '*')
10588 			pat++;
10589 		if (!*pat) /* Tail wild card matches all */
10590 			return true;
10591 		while (*str)
10592 			if (glob_match(str++, pat))
10593 				return true;
10594 	}
10595 	return !*str && !*pat;
10596 }
10597 
10598 struct kprobe_multi_resolve {
10599 	const char *pattern;
10600 	unsigned long *addrs;
10601 	size_t cap;
10602 	size_t cnt;
10603 };
10604 
10605 struct avail_kallsyms_data {
10606 	char **syms;
10607 	size_t cnt;
10608 	struct kprobe_multi_resolve *res;
10609 };
10610 
10611 static int avail_func_cmp(const void *a, const void *b)
10612 {
10613 	return strcmp(*(const char **)a, *(const char **)b);
10614 }
10615 
10616 static int avail_kallsyms_cb(unsigned long long sym_addr, char sym_type,
10617 			     const char *sym_name, void *ctx)
10618 {
10619 	struct avail_kallsyms_data *data = ctx;
10620 	struct kprobe_multi_resolve *res = data->res;
10621 	int err;
10622 
10623 	if (!bsearch(&sym_name, data->syms, data->cnt, sizeof(*data->syms), avail_func_cmp))
10624 		return 0;
10625 
10626 	err = libbpf_ensure_mem((void **)&res->addrs, &res->cap, sizeof(*res->addrs), res->cnt + 1);
10627 	if (err)
10628 		return err;
10629 
10630 	res->addrs[res->cnt++] = (unsigned long)sym_addr;
10631 	return 0;
10632 }
10633 
10634 static int libbpf_available_kallsyms_parse(struct kprobe_multi_resolve *res)
10635 {
10636 	const char *available_functions_file = tracefs_available_filter_functions();
10637 	struct avail_kallsyms_data data;
10638 	char sym_name[500];
10639 	FILE *f;
10640 	int err = 0, ret, i;
10641 	char **syms = NULL;
10642 	size_t cap = 0, cnt = 0;
10643 
10644 	f = fopen(available_functions_file, "re");
10645 	if (!f) {
10646 		err = -errno;
10647 		pr_warn("failed to open %s: %d\n", available_functions_file, err);
10648 		return err;
10649 	}
10650 
10651 	while (true) {
10652 		char *name;
10653 
10654 		ret = fscanf(f, "%499s%*[^\n]\n", sym_name);
10655 		if (ret == EOF && feof(f))
10656 			break;
10657 
10658 		if (ret != 1) {
10659 			pr_warn("failed to parse available_filter_functions entry: %d\n", ret);
10660 			err = -EINVAL;
10661 			goto cleanup;
10662 		}
10663 
10664 		if (!glob_match(sym_name, res->pattern))
10665 			continue;
10666 
10667 		err = libbpf_ensure_mem((void **)&syms, &cap, sizeof(*syms), cnt + 1);
10668 		if (err)
10669 			goto cleanup;
10670 
10671 		name = strdup(sym_name);
10672 		if (!name) {
10673 			err = -errno;
10674 			goto cleanup;
10675 		}
10676 
10677 		syms[cnt++] = name;
10678 	}
10679 
10680 	/* no entries found, bail out */
10681 	if (cnt == 0) {
10682 		err = -ENOENT;
10683 		goto cleanup;
10684 	}
10685 
10686 	/* sort available functions */
10687 	qsort(syms, cnt, sizeof(*syms), avail_func_cmp);
10688 
10689 	data.syms = syms;
10690 	data.res = res;
10691 	data.cnt = cnt;
10692 	libbpf_kallsyms_parse(avail_kallsyms_cb, &data);
10693 
10694 	if (res->cnt == 0)
10695 		err = -ENOENT;
10696 
10697 cleanup:
10698 	for (i = 0; i < cnt; i++)
10699 		free((char *)syms[i]);
10700 	free(syms);
10701 
10702 	fclose(f);
10703 	return err;
10704 }
10705 
10706 static bool has_available_filter_functions_addrs(void)
10707 {
10708 	return access(tracefs_available_filter_functions_addrs(), R_OK) != -1;
10709 }
10710 
10711 static int libbpf_available_kprobes_parse(struct kprobe_multi_resolve *res)
10712 {
10713 	const char *available_path = tracefs_available_filter_functions_addrs();
10714 	char sym_name[500];
10715 	FILE *f;
10716 	int ret, err = 0;
10717 	unsigned long long sym_addr;
10718 
10719 	f = fopen(available_path, "re");
10720 	if (!f) {
10721 		err = -errno;
10722 		pr_warn("failed to open %s: %d\n", available_path, err);
10723 		return err;
10724 	}
10725 
10726 	while (true) {
10727 		ret = fscanf(f, "%llx %499s%*[^\n]\n", &sym_addr, sym_name);
10728 		if (ret == EOF && feof(f))
10729 			break;
10730 
10731 		if (ret != 2) {
10732 			pr_warn("failed to parse available_filter_functions_addrs entry: %d\n",
10733 				ret);
10734 			err = -EINVAL;
10735 			goto cleanup;
10736 		}
10737 
10738 		if (!glob_match(sym_name, res->pattern))
10739 			continue;
10740 
10741 		err = libbpf_ensure_mem((void **)&res->addrs, &res->cap,
10742 					sizeof(*res->addrs), res->cnt + 1);
10743 		if (err)
10744 			goto cleanup;
10745 
10746 		res->addrs[res->cnt++] = (unsigned long)sym_addr;
10747 	}
10748 
10749 	if (res->cnt == 0)
10750 		err = -ENOENT;
10751 
10752 cleanup:
10753 	fclose(f);
10754 	return err;
10755 }
10756 
10757 struct bpf_link *
10758 bpf_program__attach_kprobe_multi_opts(const struct bpf_program *prog,
10759 				      const char *pattern,
10760 				      const struct bpf_kprobe_multi_opts *opts)
10761 {
10762 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
10763 	struct kprobe_multi_resolve res = {
10764 		.pattern = pattern,
10765 	};
10766 	struct bpf_link *link = NULL;
10767 	char errmsg[STRERR_BUFSIZE];
10768 	const unsigned long *addrs;
10769 	int err, link_fd, prog_fd;
10770 	const __u64 *cookies;
10771 	const char **syms;
10772 	bool retprobe;
10773 	size_t cnt;
10774 
10775 	if (!OPTS_VALID(opts, bpf_kprobe_multi_opts))
10776 		return libbpf_err_ptr(-EINVAL);
10777 
10778 	syms    = OPTS_GET(opts, syms, false);
10779 	addrs   = OPTS_GET(opts, addrs, false);
10780 	cnt     = OPTS_GET(opts, cnt, false);
10781 	cookies = OPTS_GET(opts, cookies, false);
10782 
10783 	if (!pattern && !addrs && !syms)
10784 		return libbpf_err_ptr(-EINVAL);
10785 	if (pattern && (addrs || syms || cookies || cnt))
10786 		return libbpf_err_ptr(-EINVAL);
10787 	if (!pattern && !cnt)
10788 		return libbpf_err_ptr(-EINVAL);
10789 	if (addrs && syms)
10790 		return libbpf_err_ptr(-EINVAL);
10791 
10792 	if (pattern) {
10793 		if (has_available_filter_functions_addrs())
10794 			err = libbpf_available_kprobes_parse(&res);
10795 		else
10796 			err = libbpf_available_kallsyms_parse(&res);
10797 		if (err)
10798 			goto error;
10799 		addrs = res.addrs;
10800 		cnt = res.cnt;
10801 	}
10802 
10803 	retprobe = OPTS_GET(opts, retprobe, false);
10804 
10805 	lopts.kprobe_multi.syms = syms;
10806 	lopts.kprobe_multi.addrs = addrs;
10807 	lopts.kprobe_multi.cookies = cookies;
10808 	lopts.kprobe_multi.cnt = cnt;
10809 	lopts.kprobe_multi.flags = retprobe ? BPF_F_KPROBE_MULTI_RETURN : 0;
10810 
10811 	link = calloc(1, sizeof(*link));
10812 	if (!link) {
10813 		err = -ENOMEM;
10814 		goto error;
10815 	}
10816 	link->detach = &bpf_link__detach_fd;
10817 
10818 	prog_fd = bpf_program__fd(prog);
10819 	link_fd = bpf_link_create(prog_fd, 0, BPF_TRACE_KPROBE_MULTI, &lopts);
10820 	if (link_fd < 0) {
10821 		err = -errno;
10822 		pr_warn("prog '%s': failed to attach: %s\n",
10823 			prog->name, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10824 		goto error;
10825 	}
10826 	link->fd = link_fd;
10827 	free(res.addrs);
10828 	return link;
10829 
10830 error:
10831 	free(link);
10832 	free(res.addrs);
10833 	return libbpf_err_ptr(err);
10834 }
10835 
10836 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
10837 {
10838 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts);
10839 	unsigned long offset = 0;
10840 	const char *func_name;
10841 	char *func;
10842 	int n;
10843 
10844 	*link = NULL;
10845 
10846 	/* no auto-attach for SEC("kprobe") and SEC("kretprobe") */
10847 	if (strcmp(prog->sec_name, "kprobe") == 0 || strcmp(prog->sec_name, "kretprobe") == 0)
10848 		return 0;
10849 
10850 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe/");
10851 	if (opts.retprobe)
10852 		func_name = prog->sec_name + sizeof("kretprobe/") - 1;
10853 	else
10854 		func_name = prog->sec_name + sizeof("kprobe/") - 1;
10855 
10856 	n = sscanf(func_name, "%m[a-zA-Z0-9_.]+%li", &func, &offset);
10857 	if (n < 1) {
10858 		pr_warn("kprobe name is invalid: %s\n", func_name);
10859 		return -EINVAL;
10860 	}
10861 	if (opts.retprobe && offset != 0) {
10862 		free(func);
10863 		pr_warn("kretprobes do not support offset specification\n");
10864 		return -EINVAL;
10865 	}
10866 
10867 	opts.offset = offset;
10868 	*link = bpf_program__attach_kprobe_opts(prog, func, &opts);
10869 	free(func);
10870 	return libbpf_get_error(*link);
10871 }
10872 
10873 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link)
10874 {
10875 	LIBBPF_OPTS(bpf_ksyscall_opts, opts);
10876 	const char *syscall_name;
10877 
10878 	*link = NULL;
10879 
10880 	/* no auto-attach for SEC("ksyscall") and SEC("kretsyscall") */
10881 	if (strcmp(prog->sec_name, "ksyscall") == 0 || strcmp(prog->sec_name, "kretsyscall") == 0)
10882 		return 0;
10883 
10884 	opts.retprobe = str_has_pfx(prog->sec_name, "kretsyscall/");
10885 	if (opts.retprobe)
10886 		syscall_name = prog->sec_name + sizeof("kretsyscall/") - 1;
10887 	else
10888 		syscall_name = prog->sec_name + sizeof("ksyscall/") - 1;
10889 
10890 	*link = bpf_program__attach_ksyscall(prog, syscall_name, &opts);
10891 	return *link ? 0 : -errno;
10892 }
10893 
10894 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
10895 {
10896 	LIBBPF_OPTS(bpf_kprobe_multi_opts, opts);
10897 	const char *spec;
10898 	char *pattern;
10899 	int n;
10900 
10901 	*link = NULL;
10902 
10903 	/* no auto-attach for SEC("kprobe.multi") and SEC("kretprobe.multi") */
10904 	if (strcmp(prog->sec_name, "kprobe.multi") == 0 ||
10905 	    strcmp(prog->sec_name, "kretprobe.multi") == 0)
10906 		return 0;
10907 
10908 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe.multi/");
10909 	if (opts.retprobe)
10910 		spec = prog->sec_name + sizeof("kretprobe.multi/") - 1;
10911 	else
10912 		spec = prog->sec_name + sizeof("kprobe.multi/") - 1;
10913 
10914 	n = sscanf(spec, "%m[a-zA-Z0-9_.*?]", &pattern);
10915 	if (n < 1) {
10916 		pr_warn("kprobe multi pattern is invalid: %s\n", pattern);
10917 		return -EINVAL;
10918 	}
10919 
10920 	*link = bpf_program__attach_kprobe_multi_opts(prog, pattern, &opts);
10921 	free(pattern);
10922 	return libbpf_get_error(*link);
10923 }
10924 
10925 static void gen_uprobe_legacy_event_name(char *buf, size_t buf_sz,
10926 					 const char *binary_path, uint64_t offset)
10927 {
10928 	int i;
10929 
10930 	snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx", getpid(), binary_path, (size_t)offset);
10931 
10932 	/* sanitize binary_path in the probe name */
10933 	for (i = 0; buf[i]; i++) {
10934 		if (!isalnum(buf[i]))
10935 			buf[i] = '_';
10936 	}
10937 }
10938 
10939 static inline int add_uprobe_event_legacy(const char *probe_name, bool retprobe,
10940 					  const char *binary_path, size_t offset)
10941 {
10942 	return append_to_file(tracefs_uprobe_events(), "%c:%s/%s %s:0x%zx",
10943 			      retprobe ? 'r' : 'p',
10944 			      retprobe ? "uretprobes" : "uprobes",
10945 			      probe_name, binary_path, offset);
10946 }
10947 
10948 static inline int remove_uprobe_event_legacy(const char *probe_name, bool retprobe)
10949 {
10950 	return append_to_file(tracefs_uprobe_events(), "-:%s/%s",
10951 			      retprobe ? "uretprobes" : "uprobes", probe_name);
10952 }
10953 
10954 static int determine_uprobe_perf_type_legacy(const char *probe_name, bool retprobe)
10955 {
10956 	char file[512];
10957 
10958 	snprintf(file, sizeof(file), "%s/events/%s/%s/id",
10959 		 tracefs_path(), retprobe ? "uretprobes" : "uprobes", probe_name);
10960 
10961 	return parse_uint_from_file(file, "%d\n");
10962 }
10963 
10964 static int perf_event_uprobe_open_legacy(const char *probe_name, bool retprobe,
10965 					 const char *binary_path, size_t offset, int pid)
10966 {
10967 	const size_t attr_sz = sizeof(struct perf_event_attr);
10968 	struct perf_event_attr attr;
10969 	int type, pfd, err;
10970 
10971 	err = add_uprobe_event_legacy(probe_name, retprobe, binary_path, offset);
10972 	if (err < 0) {
10973 		pr_warn("failed to add legacy uprobe event for %s:0x%zx: %d\n",
10974 			binary_path, (size_t)offset, err);
10975 		return err;
10976 	}
10977 	type = determine_uprobe_perf_type_legacy(probe_name, retprobe);
10978 	if (type < 0) {
10979 		err = type;
10980 		pr_warn("failed to determine legacy uprobe event id for %s:0x%zx: %d\n",
10981 			binary_path, offset, err);
10982 		goto err_clean_legacy;
10983 	}
10984 
10985 	memset(&attr, 0, attr_sz);
10986 	attr.size = attr_sz;
10987 	attr.config = type;
10988 	attr.type = PERF_TYPE_TRACEPOINT;
10989 
10990 	pfd = syscall(__NR_perf_event_open, &attr,
10991 		      pid < 0 ? -1 : pid, /* pid */
10992 		      pid == -1 ? 0 : -1, /* cpu */
10993 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
10994 	if (pfd < 0) {
10995 		err = -errno;
10996 		pr_warn("legacy uprobe perf_event_open() failed: %d\n", err);
10997 		goto err_clean_legacy;
10998 	}
10999 	return pfd;
11000 
11001 err_clean_legacy:
11002 	/* Clear the newly added legacy uprobe_event */
11003 	remove_uprobe_event_legacy(probe_name, retprobe);
11004 	return err;
11005 }
11006 
11007 /* Return next ELF section of sh_type after scn, or first of that type if scn is NULL. */
11008 static Elf_Scn *elf_find_next_scn_by_type(Elf *elf, int sh_type, Elf_Scn *scn)
11009 {
11010 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
11011 		GElf_Shdr sh;
11012 
11013 		if (!gelf_getshdr(scn, &sh))
11014 			continue;
11015 		if (sh.sh_type == sh_type)
11016 			return scn;
11017 	}
11018 	return NULL;
11019 }
11020 
11021 /* Find offset of function name in the provided ELF object. "binary_path" is
11022  * the path to the ELF binary represented by "elf", and only used for error
11023  * reporting matters. "name" matches symbol name or name@@LIB for library
11024  * functions.
11025  */
11026 static long elf_find_func_offset(Elf *elf, const char *binary_path, const char *name)
11027 {
11028 	int i, sh_types[2] = { SHT_DYNSYM, SHT_SYMTAB };
11029 	bool is_shared_lib, is_name_qualified;
11030 	long ret = -ENOENT;
11031 	size_t name_len;
11032 	GElf_Ehdr ehdr;
11033 
11034 	if (!gelf_getehdr(elf, &ehdr)) {
11035 		pr_warn("elf: failed to get ehdr from %s: %s\n", binary_path, elf_errmsg(-1));
11036 		ret = -LIBBPF_ERRNO__FORMAT;
11037 		goto out;
11038 	}
11039 	/* for shared lib case, we do not need to calculate relative offset */
11040 	is_shared_lib = ehdr.e_type == ET_DYN;
11041 
11042 	name_len = strlen(name);
11043 	/* Does name specify "@@LIB"? */
11044 	is_name_qualified = strstr(name, "@@") != NULL;
11045 
11046 	/* Search SHT_DYNSYM, SHT_SYMTAB for symbol. This search order is used because if
11047 	 * a binary is stripped, it may only have SHT_DYNSYM, and a fully-statically
11048 	 * linked binary may not have SHT_DYMSYM, so absence of a section should not be
11049 	 * reported as a warning/error.
11050 	 */
11051 	for (i = 0; i < ARRAY_SIZE(sh_types); i++) {
11052 		size_t nr_syms, strtabidx, idx;
11053 		Elf_Data *symbols = NULL;
11054 		Elf_Scn *scn = NULL;
11055 		int last_bind = -1;
11056 		const char *sname;
11057 		GElf_Shdr sh;
11058 
11059 		scn = elf_find_next_scn_by_type(elf, sh_types[i], NULL);
11060 		if (!scn) {
11061 			pr_debug("elf: failed to find symbol table ELF sections in '%s'\n",
11062 				 binary_path);
11063 			continue;
11064 		}
11065 		if (!gelf_getshdr(scn, &sh))
11066 			continue;
11067 		strtabidx = sh.sh_link;
11068 		symbols = elf_getdata(scn, 0);
11069 		if (!symbols) {
11070 			pr_warn("elf: failed to get symbols for symtab section in '%s': %s\n",
11071 				binary_path, elf_errmsg(-1));
11072 			ret = -LIBBPF_ERRNO__FORMAT;
11073 			goto out;
11074 		}
11075 		nr_syms = symbols->d_size / sh.sh_entsize;
11076 
11077 		for (idx = 0; idx < nr_syms; idx++) {
11078 			int curr_bind;
11079 			GElf_Sym sym;
11080 			Elf_Scn *sym_scn;
11081 			GElf_Shdr sym_sh;
11082 
11083 			if (!gelf_getsym(symbols, idx, &sym))
11084 				continue;
11085 
11086 			if (GELF_ST_TYPE(sym.st_info) != STT_FUNC)
11087 				continue;
11088 
11089 			sname = elf_strptr(elf, strtabidx, sym.st_name);
11090 			if (!sname)
11091 				continue;
11092 
11093 			curr_bind = GELF_ST_BIND(sym.st_info);
11094 
11095 			/* User can specify func, func@@LIB or func@@LIB_VERSION. */
11096 			if (strncmp(sname, name, name_len) != 0)
11097 				continue;
11098 			/* ...but we don't want a search for "foo" to match 'foo2" also, so any
11099 			 * additional characters in sname should be of the form "@@LIB".
11100 			 */
11101 			if (!is_name_qualified && sname[name_len] != '\0' && sname[name_len] != '@')
11102 				continue;
11103 
11104 			if (ret >= 0) {
11105 				/* handle multiple matches */
11106 				if (last_bind != STB_WEAK && curr_bind != STB_WEAK) {
11107 					/* Only accept one non-weak bind. */
11108 					pr_warn("elf: ambiguous match for '%s', '%s' in '%s'\n",
11109 						sname, name, binary_path);
11110 					ret = -LIBBPF_ERRNO__FORMAT;
11111 					goto out;
11112 				} else if (curr_bind == STB_WEAK) {
11113 					/* already have a non-weak bind, and
11114 					 * this is a weak bind, so ignore.
11115 					 */
11116 					continue;
11117 				}
11118 			}
11119 
11120 			/* Transform symbol's virtual address (absolute for
11121 			 * binaries and relative for shared libs) into file
11122 			 * offset, which is what kernel is expecting for
11123 			 * uprobe/uretprobe attachment.
11124 			 * See Documentation/trace/uprobetracer.rst for more
11125 			 * details.
11126 			 * This is done by looking up symbol's containing
11127 			 * section's header and using it's virtual address
11128 			 * (sh_addr) and corresponding file offset (sh_offset)
11129 			 * to transform sym.st_value (virtual address) into
11130 			 * desired final file offset.
11131 			 */
11132 			sym_scn = elf_getscn(elf, sym.st_shndx);
11133 			if (!sym_scn)
11134 				continue;
11135 			if (!gelf_getshdr(sym_scn, &sym_sh))
11136 				continue;
11137 
11138 			ret = sym.st_value - sym_sh.sh_addr + sym_sh.sh_offset;
11139 			last_bind = curr_bind;
11140 		}
11141 		if (ret > 0)
11142 			break;
11143 	}
11144 
11145 	if (ret > 0) {
11146 		pr_debug("elf: symbol address match for '%s' in '%s': 0x%lx\n", name, binary_path,
11147 			 ret);
11148 	} else {
11149 		if (ret == 0) {
11150 			pr_warn("elf: '%s' is 0 in symtab for '%s': %s\n", name, binary_path,
11151 				is_shared_lib ? "should not be 0 in a shared library" :
11152 						"try using shared library path instead");
11153 			ret = -ENOENT;
11154 		} else {
11155 			pr_warn("elf: failed to find symbol '%s' in '%s'\n", name, binary_path);
11156 		}
11157 	}
11158 out:
11159 	return ret;
11160 }
11161 
11162 /* Find offset of function name in ELF object specified by path. "name" matches
11163  * symbol name or name@@LIB for library functions.
11164  */
11165 static long elf_find_func_offset_from_file(const char *binary_path, const char *name)
11166 {
11167 	char errmsg[STRERR_BUFSIZE];
11168 	long ret = -ENOENT;
11169 	Elf *elf;
11170 	int fd;
11171 
11172 	fd = open(binary_path, O_RDONLY | O_CLOEXEC);
11173 	if (fd < 0) {
11174 		ret = -errno;
11175 		pr_warn("failed to open %s: %s\n", binary_path,
11176 			libbpf_strerror_r(ret, errmsg, sizeof(errmsg)));
11177 		return ret;
11178 	}
11179 	elf = elf_begin(fd, ELF_C_READ_MMAP, NULL);
11180 	if (!elf) {
11181 		pr_warn("elf: could not read elf from %s: %s\n", binary_path, elf_errmsg(-1));
11182 		close(fd);
11183 		return -LIBBPF_ERRNO__FORMAT;
11184 	}
11185 
11186 	ret = elf_find_func_offset(elf, binary_path, name);
11187 	elf_end(elf);
11188 	close(fd);
11189 	return ret;
11190 }
11191 
11192 /* Find offset of function name in archive specified by path. Currently
11193  * supported are .zip files that do not compress their contents, as used on
11194  * Android in the form of APKs, for example. "file_name" is the name of the ELF
11195  * file inside the archive. "func_name" matches symbol name or name@@LIB for
11196  * library functions.
11197  *
11198  * An overview of the APK format specifically provided here:
11199  * https://en.wikipedia.org/w/index.php?title=Apk_(file_format)&oldid=1139099120#Package_contents
11200  */
11201 static long elf_find_func_offset_from_archive(const char *archive_path, const char *file_name,
11202 					      const char *func_name)
11203 {
11204 	struct zip_archive *archive;
11205 	struct zip_entry entry;
11206 	long ret;
11207 	Elf *elf;
11208 
11209 	archive = zip_archive_open(archive_path);
11210 	if (IS_ERR(archive)) {
11211 		ret = PTR_ERR(archive);
11212 		pr_warn("zip: failed to open %s: %ld\n", archive_path, ret);
11213 		return ret;
11214 	}
11215 
11216 	ret = zip_archive_find_entry(archive, file_name, &entry);
11217 	if (ret) {
11218 		pr_warn("zip: could not find archive member %s in %s: %ld\n", file_name,
11219 			archive_path, ret);
11220 		goto out;
11221 	}
11222 	pr_debug("zip: found entry for %s in %s at 0x%lx\n", file_name, archive_path,
11223 		 (unsigned long)entry.data_offset);
11224 
11225 	if (entry.compression) {
11226 		pr_warn("zip: entry %s of %s is compressed and cannot be handled\n", file_name,
11227 			archive_path);
11228 		ret = -LIBBPF_ERRNO__FORMAT;
11229 		goto out;
11230 	}
11231 
11232 	elf = elf_memory((void *)entry.data, entry.data_length);
11233 	if (!elf) {
11234 		pr_warn("elf: could not read elf file %s from %s: %s\n", file_name, archive_path,
11235 			elf_errmsg(-1));
11236 		ret = -LIBBPF_ERRNO__LIBELF;
11237 		goto out;
11238 	}
11239 
11240 	ret = elf_find_func_offset(elf, file_name, func_name);
11241 	if (ret > 0) {
11242 		pr_debug("elf: symbol address match for %s of %s in %s: 0x%x + 0x%lx = 0x%lx\n",
11243 			 func_name, file_name, archive_path, entry.data_offset, ret,
11244 			 ret + entry.data_offset);
11245 		ret += entry.data_offset;
11246 	}
11247 	elf_end(elf);
11248 
11249 out:
11250 	zip_archive_close(archive);
11251 	return ret;
11252 }
11253 
11254 static const char *arch_specific_lib_paths(void)
11255 {
11256 	/*
11257 	 * Based on https://packages.debian.org/sid/libc6.
11258 	 *
11259 	 * Assume that the traced program is built for the same architecture
11260 	 * as libbpf, which should cover the vast majority of cases.
11261 	 */
11262 #if defined(__x86_64__)
11263 	return "/lib/x86_64-linux-gnu";
11264 #elif defined(__i386__)
11265 	return "/lib/i386-linux-gnu";
11266 #elif defined(__s390x__)
11267 	return "/lib/s390x-linux-gnu";
11268 #elif defined(__s390__)
11269 	return "/lib/s390-linux-gnu";
11270 #elif defined(__arm__) && defined(__SOFTFP__)
11271 	return "/lib/arm-linux-gnueabi";
11272 #elif defined(__arm__) && !defined(__SOFTFP__)
11273 	return "/lib/arm-linux-gnueabihf";
11274 #elif defined(__aarch64__)
11275 	return "/lib/aarch64-linux-gnu";
11276 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 64
11277 	return "/lib/mips64el-linux-gnuabi64";
11278 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 32
11279 	return "/lib/mipsel-linux-gnu";
11280 #elif defined(__powerpc64__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
11281 	return "/lib/powerpc64le-linux-gnu";
11282 #elif defined(__sparc__) && defined(__arch64__)
11283 	return "/lib/sparc64-linux-gnu";
11284 #elif defined(__riscv) && __riscv_xlen == 64
11285 	return "/lib/riscv64-linux-gnu";
11286 #else
11287 	return NULL;
11288 #endif
11289 }
11290 
11291 /* Get full path to program/shared library. */
11292 static int resolve_full_path(const char *file, char *result, size_t result_sz)
11293 {
11294 	const char *search_paths[3] = {};
11295 	int i, perm;
11296 
11297 	if (str_has_sfx(file, ".so") || strstr(file, ".so.")) {
11298 		search_paths[0] = getenv("LD_LIBRARY_PATH");
11299 		search_paths[1] = "/usr/lib64:/usr/lib";
11300 		search_paths[2] = arch_specific_lib_paths();
11301 		perm = R_OK;
11302 	} else {
11303 		search_paths[0] = getenv("PATH");
11304 		search_paths[1] = "/usr/bin:/usr/sbin";
11305 		perm = R_OK | X_OK;
11306 	}
11307 
11308 	for (i = 0; i < ARRAY_SIZE(search_paths); i++) {
11309 		const char *s;
11310 
11311 		if (!search_paths[i])
11312 			continue;
11313 		for (s = search_paths[i]; s != NULL; s = strchr(s, ':')) {
11314 			char *next_path;
11315 			int seg_len;
11316 
11317 			if (s[0] == ':')
11318 				s++;
11319 			next_path = strchr(s, ':');
11320 			seg_len = next_path ? next_path - s : strlen(s);
11321 			if (!seg_len)
11322 				continue;
11323 			snprintf(result, result_sz, "%.*s/%s", seg_len, s, file);
11324 			/* ensure it has required permissions */
11325 			if (faccessat(AT_FDCWD, result, perm, AT_EACCESS) < 0)
11326 				continue;
11327 			pr_debug("resolved '%s' to '%s'\n", file, result);
11328 			return 0;
11329 		}
11330 	}
11331 	return -ENOENT;
11332 }
11333 
11334 LIBBPF_API struct bpf_link *
11335 bpf_program__attach_uprobe_opts(const struct bpf_program *prog, pid_t pid,
11336 				const char *binary_path, size_t func_offset,
11337 				const struct bpf_uprobe_opts *opts)
11338 {
11339 	const char *archive_path = NULL, *archive_sep = NULL;
11340 	char errmsg[STRERR_BUFSIZE], *legacy_probe = NULL;
11341 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
11342 	enum probe_attach_mode attach_mode;
11343 	char full_path[PATH_MAX];
11344 	struct bpf_link *link;
11345 	size_t ref_ctr_off;
11346 	int pfd, err;
11347 	bool retprobe, legacy;
11348 	const char *func_name;
11349 
11350 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
11351 		return libbpf_err_ptr(-EINVAL);
11352 
11353 	attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
11354 	retprobe = OPTS_GET(opts, retprobe, false);
11355 	ref_ctr_off = OPTS_GET(opts, ref_ctr_offset, 0);
11356 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11357 
11358 	if (!binary_path)
11359 		return libbpf_err_ptr(-EINVAL);
11360 
11361 	/* Check if "binary_path" refers to an archive. */
11362 	archive_sep = strstr(binary_path, "!/");
11363 	if (archive_sep) {
11364 		full_path[0] = '\0';
11365 		libbpf_strlcpy(full_path, binary_path,
11366 			       min(sizeof(full_path), (size_t)(archive_sep - binary_path + 1)));
11367 		archive_path = full_path;
11368 		binary_path = archive_sep + 2;
11369 	} else if (!strchr(binary_path, '/')) {
11370 		err = resolve_full_path(binary_path, full_path, sizeof(full_path));
11371 		if (err) {
11372 			pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
11373 				prog->name, binary_path, err);
11374 			return libbpf_err_ptr(err);
11375 		}
11376 		binary_path = full_path;
11377 	}
11378 	func_name = OPTS_GET(opts, func_name, NULL);
11379 	if (func_name) {
11380 		long sym_off;
11381 
11382 		if (archive_path) {
11383 			sym_off = elf_find_func_offset_from_archive(archive_path, binary_path,
11384 								    func_name);
11385 			binary_path = archive_path;
11386 		} else {
11387 			sym_off = elf_find_func_offset_from_file(binary_path, func_name);
11388 		}
11389 		if (sym_off < 0)
11390 			return libbpf_err_ptr(sym_off);
11391 		func_offset += sym_off;
11392 	}
11393 
11394 	legacy = determine_uprobe_perf_type() < 0;
11395 	switch (attach_mode) {
11396 	case PROBE_ATTACH_MODE_LEGACY:
11397 		legacy = true;
11398 		pe_opts.force_ioctl_attach = true;
11399 		break;
11400 	case PROBE_ATTACH_MODE_PERF:
11401 		if (legacy)
11402 			return libbpf_err_ptr(-ENOTSUP);
11403 		pe_opts.force_ioctl_attach = true;
11404 		break;
11405 	case PROBE_ATTACH_MODE_LINK:
11406 		if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
11407 			return libbpf_err_ptr(-ENOTSUP);
11408 		break;
11409 	case PROBE_ATTACH_MODE_DEFAULT:
11410 		break;
11411 	default:
11412 		return libbpf_err_ptr(-EINVAL);
11413 	}
11414 
11415 	if (!legacy) {
11416 		pfd = perf_event_open_probe(true /* uprobe */, retprobe, binary_path,
11417 					    func_offset, pid, ref_ctr_off);
11418 	} else {
11419 		char probe_name[PATH_MAX + 64];
11420 
11421 		if (ref_ctr_off)
11422 			return libbpf_err_ptr(-EINVAL);
11423 
11424 		gen_uprobe_legacy_event_name(probe_name, sizeof(probe_name),
11425 					     binary_path, func_offset);
11426 
11427 		legacy_probe = strdup(probe_name);
11428 		if (!legacy_probe)
11429 			return libbpf_err_ptr(-ENOMEM);
11430 
11431 		pfd = perf_event_uprobe_open_legacy(legacy_probe, retprobe,
11432 						    binary_path, func_offset, pid);
11433 	}
11434 	if (pfd < 0) {
11435 		err = -errno;
11436 		pr_warn("prog '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
11437 			prog->name, retprobe ? "uretprobe" : "uprobe",
11438 			binary_path, func_offset,
11439 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11440 		goto err_out;
11441 	}
11442 
11443 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
11444 	err = libbpf_get_error(link);
11445 	if (err) {
11446 		close(pfd);
11447 		pr_warn("prog '%s': failed to attach to %s '%s:0x%zx': %s\n",
11448 			prog->name, retprobe ? "uretprobe" : "uprobe",
11449 			binary_path, func_offset,
11450 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11451 		goto err_clean_legacy;
11452 	}
11453 	if (legacy) {
11454 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
11455 
11456 		perf_link->legacy_probe_name = legacy_probe;
11457 		perf_link->legacy_is_kprobe = false;
11458 		perf_link->legacy_is_retprobe = retprobe;
11459 	}
11460 	return link;
11461 
11462 err_clean_legacy:
11463 	if (legacy)
11464 		remove_uprobe_event_legacy(legacy_probe, retprobe);
11465 err_out:
11466 	free(legacy_probe);
11467 	return libbpf_err_ptr(err);
11468 }
11469 
11470 /* Format of u[ret]probe section definition supporting auto-attach:
11471  * u[ret]probe/binary:function[+offset]
11472  *
11473  * binary can be an absolute/relative path or a filename; the latter is resolved to a
11474  * full binary path via bpf_program__attach_uprobe_opts.
11475  *
11476  * Specifying uprobe+ ensures we carry out strict matching; either "uprobe" must be
11477  * specified (and auto-attach is not possible) or the above format is specified for
11478  * auto-attach.
11479  */
11480 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11481 {
11482 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts);
11483 	char *probe_type = NULL, *binary_path = NULL, *func_name = NULL;
11484 	int n, ret = -EINVAL;
11485 	long offset = 0;
11486 
11487 	*link = NULL;
11488 
11489 	n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[a-zA-Z0-9_.]+%li",
11490 		   &probe_type, &binary_path, &func_name, &offset);
11491 	switch (n) {
11492 	case 1:
11493 		/* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
11494 		ret = 0;
11495 		break;
11496 	case 2:
11497 		pr_warn("prog '%s': section '%s' missing ':function[+offset]' specification\n",
11498 			prog->name, prog->sec_name);
11499 		break;
11500 	case 3:
11501 	case 4:
11502 		opts.retprobe = strcmp(probe_type, "uretprobe") == 0 ||
11503 				strcmp(probe_type, "uretprobe.s") == 0;
11504 		if (opts.retprobe && offset != 0) {
11505 			pr_warn("prog '%s': uretprobes do not support offset specification\n",
11506 				prog->name);
11507 			break;
11508 		}
11509 		opts.func_name = func_name;
11510 		*link = bpf_program__attach_uprobe_opts(prog, -1, binary_path, offset, &opts);
11511 		ret = libbpf_get_error(*link);
11512 		break;
11513 	default:
11514 		pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
11515 			prog->sec_name);
11516 		break;
11517 	}
11518 	free(probe_type);
11519 	free(binary_path);
11520 	free(func_name);
11521 
11522 	return ret;
11523 }
11524 
11525 struct bpf_link *bpf_program__attach_uprobe(const struct bpf_program *prog,
11526 					    bool retprobe, pid_t pid,
11527 					    const char *binary_path,
11528 					    size_t func_offset)
11529 {
11530 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts, .retprobe = retprobe);
11531 
11532 	return bpf_program__attach_uprobe_opts(prog, pid, binary_path, func_offset, &opts);
11533 }
11534 
11535 struct bpf_link *bpf_program__attach_usdt(const struct bpf_program *prog,
11536 					  pid_t pid, const char *binary_path,
11537 					  const char *usdt_provider, const char *usdt_name,
11538 					  const struct bpf_usdt_opts *opts)
11539 {
11540 	char resolved_path[512];
11541 	struct bpf_object *obj = prog->obj;
11542 	struct bpf_link *link;
11543 	__u64 usdt_cookie;
11544 	int err;
11545 
11546 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
11547 		return libbpf_err_ptr(-EINVAL);
11548 
11549 	if (bpf_program__fd(prog) < 0) {
11550 		pr_warn("prog '%s': can't attach BPF program w/o FD (did you load it?)\n",
11551 			prog->name);
11552 		return libbpf_err_ptr(-EINVAL);
11553 	}
11554 
11555 	if (!binary_path)
11556 		return libbpf_err_ptr(-EINVAL);
11557 
11558 	if (!strchr(binary_path, '/')) {
11559 		err = resolve_full_path(binary_path, resolved_path, sizeof(resolved_path));
11560 		if (err) {
11561 			pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
11562 				prog->name, binary_path, err);
11563 			return libbpf_err_ptr(err);
11564 		}
11565 		binary_path = resolved_path;
11566 	}
11567 
11568 	/* USDT manager is instantiated lazily on first USDT attach. It will
11569 	 * be destroyed together with BPF object in bpf_object__close().
11570 	 */
11571 	if (IS_ERR(obj->usdt_man))
11572 		return libbpf_ptr(obj->usdt_man);
11573 	if (!obj->usdt_man) {
11574 		obj->usdt_man = usdt_manager_new(obj);
11575 		if (IS_ERR(obj->usdt_man))
11576 			return libbpf_ptr(obj->usdt_man);
11577 	}
11578 
11579 	usdt_cookie = OPTS_GET(opts, usdt_cookie, 0);
11580 	link = usdt_manager_attach_usdt(obj->usdt_man, prog, pid, binary_path,
11581 					usdt_provider, usdt_name, usdt_cookie);
11582 	err = libbpf_get_error(link);
11583 	if (err)
11584 		return libbpf_err_ptr(err);
11585 	return link;
11586 }
11587 
11588 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11589 {
11590 	char *path = NULL, *provider = NULL, *name = NULL;
11591 	const char *sec_name;
11592 	int n, err;
11593 
11594 	sec_name = bpf_program__section_name(prog);
11595 	if (strcmp(sec_name, "usdt") == 0) {
11596 		/* no auto-attach for just SEC("usdt") */
11597 		*link = NULL;
11598 		return 0;
11599 	}
11600 
11601 	n = sscanf(sec_name, "usdt/%m[^:]:%m[^:]:%m[^:]", &path, &provider, &name);
11602 	if (n != 3) {
11603 		pr_warn("invalid section '%s', expected SEC(\"usdt/<path>:<provider>:<name>\")\n",
11604 			sec_name);
11605 		err = -EINVAL;
11606 	} else {
11607 		*link = bpf_program__attach_usdt(prog, -1 /* any process */, path,
11608 						 provider, name, NULL);
11609 		err = libbpf_get_error(*link);
11610 	}
11611 	free(path);
11612 	free(provider);
11613 	free(name);
11614 	return err;
11615 }
11616 
11617 static int determine_tracepoint_id(const char *tp_category,
11618 				   const char *tp_name)
11619 {
11620 	char file[PATH_MAX];
11621 	int ret;
11622 
11623 	ret = snprintf(file, sizeof(file), "%s/events/%s/%s/id",
11624 		       tracefs_path(), tp_category, tp_name);
11625 	if (ret < 0)
11626 		return -errno;
11627 	if (ret >= sizeof(file)) {
11628 		pr_debug("tracepoint %s/%s path is too long\n",
11629 			 tp_category, tp_name);
11630 		return -E2BIG;
11631 	}
11632 	return parse_uint_from_file(file, "%d\n");
11633 }
11634 
11635 static int perf_event_open_tracepoint(const char *tp_category,
11636 				      const char *tp_name)
11637 {
11638 	const size_t attr_sz = sizeof(struct perf_event_attr);
11639 	struct perf_event_attr attr;
11640 	char errmsg[STRERR_BUFSIZE];
11641 	int tp_id, pfd, err;
11642 
11643 	tp_id = determine_tracepoint_id(tp_category, tp_name);
11644 	if (tp_id < 0) {
11645 		pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
11646 			tp_category, tp_name,
11647 			libbpf_strerror_r(tp_id, errmsg, sizeof(errmsg)));
11648 		return tp_id;
11649 	}
11650 
11651 	memset(&attr, 0, attr_sz);
11652 	attr.type = PERF_TYPE_TRACEPOINT;
11653 	attr.size = attr_sz;
11654 	attr.config = tp_id;
11655 
11656 	pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
11657 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
11658 	if (pfd < 0) {
11659 		err = -errno;
11660 		pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
11661 			tp_category, tp_name,
11662 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11663 		return err;
11664 	}
11665 	return pfd;
11666 }
11667 
11668 struct bpf_link *bpf_program__attach_tracepoint_opts(const struct bpf_program *prog,
11669 						     const char *tp_category,
11670 						     const char *tp_name,
11671 						     const struct bpf_tracepoint_opts *opts)
11672 {
11673 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
11674 	char errmsg[STRERR_BUFSIZE];
11675 	struct bpf_link *link;
11676 	int pfd, err;
11677 
11678 	if (!OPTS_VALID(opts, bpf_tracepoint_opts))
11679 		return libbpf_err_ptr(-EINVAL);
11680 
11681 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11682 
11683 	pfd = perf_event_open_tracepoint(tp_category, tp_name);
11684 	if (pfd < 0) {
11685 		pr_warn("prog '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
11686 			prog->name, tp_category, tp_name,
11687 			libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
11688 		return libbpf_err_ptr(pfd);
11689 	}
11690 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
11691 	err = libbpf_get_error(link);
11692 	if (err) {
11693 		close(pfd);
11694 		pr_warn("prog '%s': failed to attach to tracepoint '%s/%s': %s\n",
11695 			prog->name, tp_category, tp_name,
11696 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11697 		return libbpf_err_ptr(err);
11698 	}
11699 	return link;
11700 }
11701 
11702 struct bpf_link *bpf_program__attach_tracepoint(const struct bpf_program *prog,
11703 						const char *tp_category,
11704 						const char *tp_name)
11705 {
11706 	return bpf_program__attach_tracepoint_opts(prog, tp_category, tp_name, NULL);
11707 }
11708 
11709 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11710 {
11711 	char *sec_name, *tp_cat, *tp_name;
11712 
11713 	*link = NULL;
11714 
11715 	/* no auto-attach for SEC("tp") or SEC("tracepoint") */
11716 	if (strcmp(prog->sec_name, "tp") == 0 || strcmp(prog->sec_name, "tracepoint") == 0)
11717 		return 0;
11718 
11719 	sec_name = strdup(prog->sec_name);
11720 	if (!sec_name)
11721 		return -ENOMEM;
11722 
11723 	/* extract "tp/<category>/<name>" or "tracepoint/<category>/<name>" */
11724 	if (str_has_pfx(prog->sec_name, "tp/"))
11725 		tp_cat = sec_name + sizeof("tp/") - 1;
11726 	else
11727 		tp_cat = sec_name + sizeof("tracepoint/") - 1;
11728 	tp_name = strchr(tp_cat, '/');
11729 	if (!tp_name) {
11730 		free(sec_name);
11731 		return -EINVAL;
11732 	}
11733 	*tp_name = '\0';
11734 	tp_name++;
11735 
11736 	*link = bpf_program__attach_tracepoint(prog, tp_cat, tp_name);
11737 	free(sec_name);
11738 	return libbpf_get_error(*link);
11739 }
11740 
11741 struct bpf_link *bpf_program__attach_raw_tracepoint(const struct bpf_program *prog,
11742 						    const char *tp_name)
11743 {
11744 	char errmsg[STRERR_BUFSIZE];
11745 	struct bpf_link *link;
11746 	int prog_fd, pfd;
11747 
11748 	prog_fd = bpf_program__fd(prog);
11749 	if (prog_fd < 0) {
11750 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
11751 		return libbpf_err_ptr(-EINVAL);
11752 	}
11753 
11754 	link = calloc(1, sizeof(*link));
11755 	if (!link)
11756 		return libbpf_err_ptr(-ENOMEM);
11757 	link->detach = &bpf_link__detach_fd;
11758 
11759 	pfd = bpf_raw_tracepoint_open(tp_name, prog_fd);
11760 	if (pfd < 0) {
11761 		pfd = -errno;
11762 		free(link);
11763 		pr_warn("prog '%s': failed to attach to raw tracepoint '%s': %s\n",
11764 			prog->name, tp_name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
11765 		return libbpf_err_ptr(pfd);
11766 	}
11767 	link->fd = pfd;
11768 	return link;
11769 }
11770 
11771 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11772 {
11773 	static const char *const prefixes[] = {
11774 		"raw_tp",
11775 		"raw_tracepoint",
11776 		"raw_tp.w",
11777 		"raw_tracepoint.w",
11778 	};
11779 	size_t i;
11780 	const char *tp_name = NULL;
11781 
11782 	*link = NULL;
11783 
11784 	for (i = 0; i < ARRAY_SIZE(prefixes); i++) {
11785 		size_t pfx_len;
11786 
11787 		if (!str_has_pfx(prog->sec_name, prefixes[i]))
11788 			continue;
11789 
11790 		pfx_len = strlen(prefixes[i]);
11791 		/* no auto-attach case of, e.g., SEC("raw_tp") */
11792 		if (prog->sec_name[pfx_len] == '\0')
11793 			return 0;
11794 
11795 		if (prog->sec_name[pfx_len] != '/')
11796 			continue;
11797 
11798 		tp_name = prog->sec_name + pfx_len + 1;
11799 		break;
11800 	}
11801 
11802 	if (!tp_name) {
11803 		pr_warn("prog '%s': invalid section name '%s'\n",
11804 			prog->name, prog->sec_name);
11805 		return -EINVAL;
11806 	}
11807 
11808 	*link = bpf_program__attach_raw_tracepoint(prog, tp_name);
11809 	return libbpf_get_error(*link);
11810 }
11811 
11812 /* Common logic for all BPF program types that attach to a btf_id */
11813 static struct bpf_link *bpf_program__attach_btf_id(const struct bpf_program *prog,
11814 						   const struct bpf_trace_opts *opts)
11815 {
11816 	LIBBPF_OPTS(bpf_link_create_opts, link_opts);
11817 	char errmsg[STRERR_BUFSIZE];
11818 	struct bpf_link *link;
11819 	int prog_fd, pfd;
11820 
11821 	if (!OPTS_VALID(opts, bpf_trace_opts))
11822 		return libbpf_err_ptr(-EINVAL);
11823 
11824 	prog_fd = bpf_program__fd(prog);
11825 	if (prog_fd < 0) {
11826 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
11827 		return libbpf_err_ptr(-EINVAL);
11828 	}
11829 
11830 	link = calloc(1, sizeof(*link));
11831 	if (!link)
11832 		return libbpf_err_ptr(-ENOMEM);
11833 	link->detach = &bpf_link__detach_fd;
11834 
11835 	/* libbpf is smart enough to redirect to BPF_RAW_TRACEPOINT_OPEN on old kernels */
11836 	link_opts.tracing.cookie = OPTS_GET(opts, cookie, 0);
11837 	pfd = bpf_link_create(prog_fd, 0, bpf_program__expected_attach_type(prog), &link_opts);
11838 	if (pfd < 0) {
11839 		pfd = -errno;
11840 		free(link);
11841 		pr_warn("prog '%s': failed to attach: %s\n",
11842 			prog->name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
11843 		return libbpf_err_ptr(pfd);
11844 	}
11845 	link->fd = pfd;
11846 	return link;
11847 }
11848 
11849 struct bpf_link *bpf_program__attach_trace(const struct bpf_program *prog)
11850 {
11851 	return bpf_program__attach_btf_id(prog, NULL);
11852 }
11853 
11854 struct bpf_link *bpf_program__attach_trace_opts(const struct bpf_program *prog,
11855 						const struct bpf_trace_opts *opts)
11856 {
11857 	return bpf_program__attach_btf_id(prog, opts);
11858 }
11859 
11860 struct bpf_link *bpf_program__attach_lsm(const struct bpf_program *prog)
11861 {
11862 	return bpf_program__attach_btf_id(prog, NULL);
11863 }
11864 
11865 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11866 {
11867 	*link = bpf_program__attach_trace(prog);
11868 	return libbpf_get_error(*link);
11869 }
11870 
11871 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11872 {
11873 	*link = bpf_program__attach_lsm(prog);
11874 	return libbpf_get_error(*link);
11875 }
11876 
11877 static struct bpf_link *
11878 bpf_program_attach_fd(const struct bpf_program *prog,
11879 		      int target_fd, const char *target_name,
11880 		      const struct bpf_link_create_opts *opts)
11881 {
11882 	enum bpf_attach_type attach_type;
11883 	char errmsg[STRERR_BUFSIZE];
11884 	struct bpf_link *link;
11885 	int prog_fd, link_fd;
11886 
11887 	prog_fd = bpf_program__fd(prog);
11888 	if (prog_fd < 0) {
11889 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
11890 		return libbpf_err_ptr(-EINVAL);
11891 	}
11892 
11893 	link = calloc(1, sizeof(*link));
11894 	if (!link)
11895 		return libbpf_err_ptr(-ENOMEM);
11896 	link->detach = &bpf_link__detach_fd;
11897 
11898 	attach_type = bpf_program__expected_attach_type(prog);
11899 	link_fd = bpf_link_create(prog_fd, target_fd, attach_type, opts);
11900 	if (link_fd < 0) {
11901 		link_fd = -errno;
11902 		free(link);
11903 		pr_warn("prog '%s': failed to attach to %s: %s\n",
11904 			prog->name, target_name,
11905 			libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
11906 		return libbpf_err_ptr(link_fd);
11907 	}
11908 	link->fd = link_fd;
11909 	return link;
11910 }
11911 
11912 struct bpf_link *
11913 bpf_program__attach_cgroup(const struct bpf_program *prog, int cgroup_fd)
11914 {
11915 	return bpf_program_attach_fd(prog, cgroup_fd, "cgroup", NULL);
11916 }
11917 
11918 struct bpf_link *
11919 bpf_program__attach_netns(const struct bpf_program *prog, int netns_fd)
11920 {
11921 	return bpf_program_attach_fd(prog, netns_fd, "netns", NULL);
11922 }
11923 
11924 struct bpf_link *bpf_program__attach_xdp(const struct bpf_program *prog, int ifindex)
11925 {
11926 	/* target_fd/target_ifindex use the same field in LINK_CREATE */
11927 	return bpf_program_attach_fd(prog, ifindex, "xdp", NULL);
11928 }
11929 
11930 struct bpf_link *
11931 bpf_program__attach_tcx(const struct bpf_program *prog, int ifindex,
11932 			const struct bpf_tcx_opts *opts)
11933 {
11934 	LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
11935 	__u32 relative_id;
11936 	int relative_fd;
11937 
11938 	if (!OPTS_VALID(opts, bpf_tcx_opts))
11939 		return libbpf_err_ptr(-EINVAL);
11940 
11941 	relative_id = OPTS_GET(opts, relative_id, 0);
11942 	relative_fd = OPTS_GET(opts, relative_fd, 0);
11943 
11944 	/* validate we don't have unexpected combinations of non-zero fields */
11945 	if (!ifindex) {
11946 		pr_warn("prog '%s': target netdevice ifindex cannot be zero\n",
11947 			prog->name);
11948 		return libbpf_err_ptr(-EINVAL);
11949 	}
11950 	if (relative_fd && relative_id) {
11951 		pr_warn("prog '%s': relative_fd and relative_id cannot be set at the same time\n",
11952 			prog->name);
11953 		return libbpf_err_ptr(-EINVAL);
11954 	}
11955 
11956 	link_create_opts.tcx.expected_revision = OPTS_GET(opts, expected_revision, 0);
11957 	link_create_opts.tcx.relative_fd = relative_fd;
11958 	link_create_opts.tcx.relative_id = relative_id;
11959 	link_create_opts.flags = OPTS_GET(opts, flags, 0);
11960 
11961 	/* target_fd/target_ifindex use the same field in LINK_CREATE */
11962 	return bpf_program_attach_fd(prog, ifindex, "tcx", &link_create_opts);
11963 }
11964 
11965 struct bpf_link *bpf_program__attach_freplace(const struct bpf_program *prog,
11966 					      int target_fd,
11967 					      const char *attach_func_name)
11968 {
11969 	int btf_id;
11970 
11971 	if (!!target_fd != !!attach_func_name) {
11972 		pr_warn("prog '%s': supply none or both of target_fd and attach_func_name\n",
11973 			prog->name);
11974 		return libbpf_err_ptr(-EINVAL);
11975 	}
11976 
11977 	if (prog->type != BPF_PROG_TYPE_EXT) {
11978 		pr_warn("prog '%s': only BPF_PROG_TYPE_EXT can attach as freplace",
11979 			prog->name);
11980 		return libbpf_err_ptr(-EINVAL);
11981 	}
11982 
11983 	if (target_fd) {
11984 		LIBBPF_OPTS(bpf_link_create_opts, target_opts);
11985 
11986 		btf_id = libbpf_find_prog_btf_id(attach_func_name, target_fd);
11987 		if (btf_id < 0)
11988 			return libbpf_err_ptr(btf_id);
11989 
11990 		target_opts.target_btf_id = btf_id;
11991 
11992 		return bpf_program_attach_fd(prog, target_fd, "freplace",
11993 					     &target_opts);
11994 	} else {
11995 		/* no target, so use raw_tracepoint_open for compatibility
11996 		 * with old kernels
11997 		 */
11998 		return bpf_program__attach_trace(prog);
11999 	}
12000 }
12001 
12002 struct bpf_link *
12003 bpf_program__attach_iter(const struct bpf_program *prog,
12004 			 const struct bpf_iter_attach_opts *opts)
12005 {
12006 	DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
12007 	char errmsg[STRERR_BUFSIZE];
12008 	struct bpf_link *link;
12009 	int prog_fd, link_fd;
12010 	__u32 target_fd = 0;
12011 
12012 	if (!OPTS_VALID(opts, bpf_iter_attach_opts))
12013 		return libbpf_err_ptr(-EINVAL);
12014 
12015 	link_create_opts.iter_info = OPTS_GET(opts, link_info, (void *)0);
12016 	link_create_opts.iter_info_len = OPTS_GET(opts, link_info_len, 0);
12017 
12018 	prog_fd = bpf_program__fd(prog);
12019 	if (prog_fd < 0) {
12020 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12021 		return libbpf_err_ptr(-EINVAL);
12022 	}
12023 
12024 	link = calloc(1, sizeof(*link));
12025 	if (!link)
12026 		return libbpf_err_ptr(-ENOMEM);
12027 	link->detach = &bpf_link__detach_fd;
12028 
12029 	link_fd = bpf_link_create(prog_fd, target_fd, BPF_TRACE_ITER,
12030 				  &link_create_opts);
12031 	if (link_fd < 0) {
12032 		link_fd = -errno;
12033 		free(link);
12034 		pr_warn("prog '%s': failed to attach to iterator: %s\n",
12035 			prog->name, libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
12036 		return libbpf_err_ptr(link_fd);
12037 	}
12038 	link->fd = link_fd;
12039 	return link;
12040 }
12041 
12042 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link)
12043 {
12044 	*link = bpf_program__attach_iter(prog, NULL);
12045 	return libbpf_get_error(*link);
12046 }
12047 
12048 struct bpf_link *bpf_program__attach_netfilter(const struct bpf_program *prog,
12049 					       const struct bpf_netfilter_opts *opts)
12050 {
12051 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
12052 	struct bpf_link *link;
12053 	int prog_fd, link_fd;
12054 
12055 	if (!OPTS_VALID(opts, bpf_netfilter_opts))
12056 		return libbpf_err_ptr(-EINVAL);
12057 
12058 	prog_fd = bpf_program__fd(prog);
12059 	if (prog_fd < 0) {
12060 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
12061 		return libbpf_err_ptr(-EINVAL);
12062 	}
12063 
12064 	link = calloc(1, sizeof(*link));
12065 	if (!link)
12066 		return libbpf_err_ptr(-ENOMEM);
12067 
12068 	link->detach = &bpf_link__detach_fd;
12069 
12070 	lopts.netfilter.pf = OPTS_GET(opts, pf, 0);
12071 	lopts.netfilter.hooknum = OPTS_GET(opts, hooknum, 0);
12072 	lopts.netfilter.priority = OPTS_GET(opts, priority, 0);
12073 	lopts.netfilter.flags = OPTS_GET(opts, flags, 0);
12074 
12075 	link_fd = bpf_link_create(prog_fd, 0, BPF_NETFILTER, &lopts);
12076 	if (link_fd < 0) {
12077 		char errmsg[STRERR_BUFSIZE];
12078 
12079 		link_fd = -errno;
12080 		free(link);
12081 		pr_warn("prog '%s': failed to attach to netfilter: %s\n",
12082 			prog->name, libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
12083 		return libbpf_err_ptr(link_fd);
12084 	}
12085 	link->fd = link_fd;
12086 
12087 	return link;
12088 }
12089 
12090 struct bpf_link *bpf_program__attach(const struct bpf_program *prog)
12091 {
12092 	struct bpf_link *link = NULL;
12093 	int err;
12094 
12095 	if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
12096 		return libbpf_err_ptr(-EOPNOTSUPP);
12097 
12098 	err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, &link);
12099 	if (err)
12100 		return libbpf_err_ptr(err);
12101 
12102 	/* When calling bpf_program__attach() explicitly, auto-attach support
12103 	 * is expected to work, so NULL returned link is considered an error.
12104 	 * This is different for skeleton's attach, see comment in
12105 	 * bpf_object__attach_skeleton().
12106 	 */
12107 	if (!link)
12108 		return libbpf_err_ptr(-EOPNOTSUPP);
12109 
12110 	return link;
12111 }
12112 
12113 struct bpf_link_struct_ops {
12114 	struct bpf_link link;
12115 	int map_fd;
12116 };
12117 
12118 static int bpf_link__detach_struct_ops(struct bpf_link *link)
12119 {
12120 	struct bpf_link_struct_ops *st_link;
12121 	__u32 zero = 0;
12122 
12123 	st_link = container_of(link, struct bpf_link_struct_ops, link);
12124 
12125 	if (st_link->map_fd < 0)
12126 		/* w/o a real link */
12127 		return bpf_map_delete_elem(link->fd, &zero);
12128 
12129 	return close(link->fd);
12130 }
12131 
12132 struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map)
12133 {
12134 	struct bpf_link_struct_ops *link;
12135 	__u32 zero = 0;
12136 	int err, fd;
12137 
12138 	if (!bpf_map__is_struct_ops(map) || map->fd == -1)
12139 		return libbpf_err_ptr(-EINVAL);
12140 
12141 	link = calloc(1, sizeof(*link));
12142 	if (!link)
12143 		return libbpf_err_ptr(-EINVAL);
12144 
12145 	/* kern_vdata should be prepared during the loading phase. */
12146 	err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
12147 	/* It can be EBUSY if the map has been used to create or
12148 	 * update a link before.  We don't allow updating the value of
12149 	 * a struct_ops once it is set.  That ensures that the value
12150 	 * never changed.  So, it is safe to skip EBUSY.
12151 	 */
12152 	if (err && (!(map->def.map_flags & BPF_F_LINK) || err != -EBUSY)) {
12153 		free(link);
12154 		return libbpf_err_ptr(err);
12155 	}
12156 
12157 	link->link.detach = bpf_link__detach_struct_ops;
12158 
12159 	if (!(map->def.map_flags & BPF_F_LINK)) {
12160 		/* w/o a real link */
12161 		link->link.fd = map->fd;
12162 		link->map_fd = -1;
12163 		return &link->link;
12164 	}
12165 
12166 	fd = bpf_link_create(map->fd, 0, BPF_STRUCT_OPS, NULL);
12167 	if (fd < 0) {
12168 		free(link);
12169 		return libbpf_err_ptr(fd);
12170 	}
12171 
12172 	link->link.fd = fd;
12173 	link->map_fd = map->fd;
12174 
12175 	return &link->link;
12176 }
12177 
12178 /*
12179  * Swap the back struct_ops of a link with a new struct_ops map.
12180  */
12181 int bpf_link__update_map(struct bpf_link *link, const struct bpf_map *map)
12182 {
12183 	struct bpf_link_struct_ops *st_ops_link;
12184 	__u32 zero = 0;
12185 	int err;
12186 
12187 	if (!bpf_map__is_struct_ops(map) || map->fd < 0)
12188 		return -EINVAL;
12189 
12190 	st_ops_link = container_of(link, struct bpf_link_struct_ops, link);
12191 	/* Ensure the type of a link is correct */
12192 	if (st_ops_link->map_fd < 0)
12193 		return -EINVAL;
12194 
12195 	err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
12196 	/* It can be EBUSY if the map has been used to create or
12197 	 * update a link before.  We don't allow updating the value of
12198 	 * a struct_ops once it is set.  That ensures that the value
12199 	 * never changed.  So, it is safe to skip EBUSY.
12200 	 */
12201 	if (err && err != -EBUSY)
12202 		return err;
12203 
12204 	err = bpf_link_update(link->fd, map->fd, NULL);
12205 	if (err < 0)
12206 		return err;
12207 
12208 	st_ops_link->map_fd = map->fd;
12209 
12210 	return 0;
12211 }
12212 
12213 typedef enum bpf_perf_event_ret (*bpf_perf_event_print_t)(struct perf_event_header *hdr,
12214 							  void *private_data);
12215 
12216 static enum bpf_perf_event_ret
12217 perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
12218 		       void **copy_mem, size_t *copy_size,
12219 		       bpf_perf_event_print_t fn, void *private_data)
12220 {
12221 	struct perf_event_mmap_page *header = mmap_mem;
12222 	__u64 data_head = ring_buffer_read_head(header);
12223 	__u64 data_tail = header->data_tail;
12224 	void *base = ((__u8 *)header) + page_size;
12225 	int ret = LIBBPF_PERF_EVENT_CONT;
12226 	struct perf_event_header *ehdr;
12227 	size_t ehdr_size;
12228 
12229 	while (data_head != data_tail) {
12230 		ehdr = base + (data_tail & (mmap_size - 1));
12231 		ehdr_size = ehdr->size;
12232 
12233 		if (((void *)ehdr) + ehdr_size > base + mmap_size) {
12234 			void *copy_start = ehdr;
12235 			size_t len_first = base + mmap_size - copy_start;
12236 			size_t len_secnd = ehdr_size - len_first;
12237 
12238 			if (*copy_size < ehdr_size) {
12239 				free(*copy_mem);
12240 				*copy_mem = malloc(ehdr_size);
12241 				if (!*copy_mem) {
12242 					*copy_size = 0;
12243 					ret = LIBBPF_PERF_EVENT_ERROR;
12244 					break;
12245 				}
12246 				*copy_size = ehdr_size;
12247 			}
12248 
12249 			memcpy(*copy_mem, copy_start, len_first);
12250 			memcpy(*copy_mem + len_first, base, len_secnd);
12251 			ehdr = *copy_mem;
12252 		}
12253 
12254 		ret = fn(ehdr, private_data);
12255 		data_tail += ehdr_size;
12256 		if (ret != LIBBPF_PERF_EVENT_CONT)
12257 			break;
12258 	}
12259 
12260 	ring_buffer_write_tail(header, data_tail);
12261 	return libbpf_err(ret);
12262 }
12263 
12264 struct perf_buffer;
12265 
12266 struct perf_buffer_params {
12267 	struct perf_event_attr *attr;
12268 	/* if event_cb is specified, it takes precendence */
12269 	perf_buffer_event_fn event_cb;
12270 	/* sample_cb and lost_cb are higher-level common-case callbacks */
12271 	perf_buffer_sample_fn sample_cb;
12272 	perf_buffer_lost_fn lost_cb;
12273 	void *ctx;
12274 	int cpu_cnt;
12275 	int *cpus;
12276 	int *map_keys;
12277 };
12278 
12279 struct perf_cpu_buf {
12280 	struct perf_buffer *pb;
12281 	void *base; /* mmap()'ed memory */
12282 	void *buf; /* for reconstructing segmented data */
12283 	size_t buf_size;
12284 	int fd;
12285 	int cpu;
12286 	int map_key;
12287 };
12288 
12289 struct perf_buffer {
12290 	perf_buffer_event_fn event_cb;
12291 	perf_buffer_sample_fn sample_cb;
12292 	perf_buffer_lost_fn lost_cb;
12293 	void *ctx; /* passed into callbacks */
12294 
12295 	size_t page_size;
12296 	size_t mmap_size;
12297 	struct perf_cpu_buf **cpu_bufs;
12298 	struct epoll_event *events;
12299 	int cpu_cnt; /* number of allocated CPU buffers */
12300 	int epoll_fd; /* perf event FD */
12301 	int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
12302 };
12303 
12304 static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
12305 				      struct perf_cpu_buf *cpu_buf)
12306 {
12307 	if (!cpu_buf)
12308 		return;
12309 	if (cpu_buf->base &&
12310 	    munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
12311 		pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
12312 	if (cpu_buf->fd >= 0) {
12313 		ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
12314 		close(cpu_buf->fd);
12315 	}
12316 	free(cpu_buf->buf);
12317 	free(cpu_buf);
12318 }
12319 
12320 void perf_buffer__free(struct perf_buffer *pb)
12321 {
12322 	int i;
12323 
12324 	if (IS_ERR_OR_NULL(pb))
12325 		return;
12326 	if (pb->cpu_bufs) {
12327 		for (i = 0; i < pb->cpu_cnt; i++) {
12328 			struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
12329 
12330 			if (!cpu_buf)
12331 				continue;
12332 
12333 			bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
12334 			perf_buffer__free_cpu_buf(pb, cpu_buf);
12335 		}
12336 		free(pb->cpu_bufs);
12337 	}
12338 	if (pb->epoll_fd >= 0)
12339 		close(pb->epoll_fd);
12340 	free(pb->events);
12341 	free(pb);
12342 }
12343 
12344 static struct perf_cpu_buf *
12345 perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
12346 			  int cpu, int map_key)
12347 {
12348 	struct perf_cpu_buf *cpu_buf;
12349 	char msg[STRERR_BUFSIZE];
12350 	int err;
12351 
12352 	cpu_buf = calloc(1, sizeof(*cpu_buf));
12353 	if (!cpu_buf)
12354 		return ERR_PTR(-ENOMEM);
12355 
12356 	cpu_buf->pb = pb;
12357 	cpu_buf->cpu = cpu;
12358 	cpu_buf->map_key = map_key;
12359 
12360 	cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
12361 			      -1, PERF_FLAG_FD_CLOEXEC);
12362 	if (cpu_buf->fd < 0) {
12363 		err = -errno;
12364 		pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
12365 			cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
12366 		goto error;
12367 	}
12368 
12369 	cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
12370 			     PROT_READ | PROT_WRITE, MAP_SHARED,
12371 			     cpu_buf->fd, 0);
12372 	if (cpu_buf->base == MAP_FAILED) {
12373 		cpu_buf->base = NULL;
12374 		err = -errno;
12375 		pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
12376 			cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
12377 		goto error;
12378 	}
12379 
12380 	if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
12381 		err = -errno;
12382 		pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
12383 			cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
12384 		goto error;
12385 	}
12386 
12387 	return cpu_buf;
12388 
12389 error:
12390 	perf_buffer__free_cpu_buf(pb, cpu_buf);
12391 	return (struct perf_cpu_buf *)ERR_PTR(err);
12392 }
12393 
12394 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
12395 					      struct perf_buffer_params *p);
12396 
12397 struct perf_buffer *perf_buffer__new(int map_fd, size_t page_cnt,
12398 				     perf_buffer_sample_fn sample_cb,
12399 				     perf_buffer_lost_fn lost_cb,
12400 				     void *ctx,
12401 				     const struct perf_buffer_opts *opts)
12402 {
12403 	const size_t attr_sz = sizeof(struct perf_event_attr);
12404 	struct perf_buffer_params p = {};
12405 	struct perf_event_attr attr;
12406 	__u32 sample_period;
12407 
12408 	if (!OPTS_VALID(opts, perf_buffer_opts))
12409 		return libbpf_err_ptr(-EINVAL);
12410 
12411 	sample_period = OPTS_GET(opts, sample_period, 1);
12412 	if (!sample_period)
12413 		sample_period = 1;
12414 
12415 	memset(&attr, 0, attr_sz);
12416 	attr.size = attr_sz;
12417 	attr.config = PERF_COUNT_SW_BPF_OUTPUT;
12418 	attr.type = PERF_TYPE_SOFTWARE;
12419 	attr.sample_type = PERF_SAMPLE_RAW;
12420 	attr.sample_period = sample_period;
12421 	attr.wakeup_events = sample_period;
12422 
12423 	p.attr = &attr;
12424 	p.sample_cb = sample_cb;
12425 	p.lost_cb = lost_cb;
12426 	p.ctx = ctx;
12427 
12428 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
12429 }
12430 
12431 struct perf_buffer *perf_buffer__new_raw(int map_fd, size_t page_cnt,
12432 					 struct perf_event_attr *attr,
12433 					 perf_buffer_event_fn event_cb, void *ctx,
12434 					 const struct perf_buffer_raw_opts *opts)
12435 {
12436 	struct perf_buffer_params p = {};
12437 
12438 	if (!attr)
12439 		return libbpf_err_ptr(-EINVAL);
12440 
12441 	if (!OPTS_VALID(opts, perf_buffer_raw_opts))
12442 		return libbpf_err_ptr(-EINVAL);
12443 
12444 	p.attr = attr;
12445 	p.event_cb = event_cb;
12446 	p.ctx = ctx;
12447 	p.cpu_cnt = OPTS_GET(opts, cpu_cnt, 0);
12448 	p.cpus = OPTS_GET(opts, cpus, NULL);
12449 	p.map_keys = OPTS_GET(opts, map_keys, NULL);
12450 
12451 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
12452 }
12453 
12454 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
12455 					      struct perf_buffer_params *p)
12456 {
12457 	const char *online_cpus_file = "/sys/devices/system/cpu/online";
12458 	struct bpf_map_info map;
12459 	char msg[STRERR_BUFSIZE];
12460 	struct perf_buffer *pb;
12461 	bool *online = NULL;
12462 	__u32 map_info_len;
12463 	int err, i, j, n;
12464 
12465 	if (page_cnt == 0 || (page_cnt & (page_cnt - 1))) {
12466 		pr_warn("page count should be power of two, but is %zu\n",
12467 			page_cnt);
12468 		return ERR_PTR(-EINVAL);
12469 	}
12470 
12471 	/* best-effort sanity checks */
12472 	memset(&map, 0, sizeof(map));
12473 	map_info_len = sizeof(map);
12474 	err = bpf_map_get_info_by_fd(map_fd, &map, &map_info_len);
12475 	if (err) {
12476 		err = -errno;
12477 		/* if BPF_OBJ_GET_INFO_BY_FD is supported, will return
12478 		 * -EBADFD, -EFAULT, or -E2BIG on real error
12479 		 */
12480 		if (err != -EINVAL) {
12481 			pr_warn("failed to get map info for map FD %d: %s\n",
12482 				map_fd, libbpf_strerror_r(err, msg, sizeof(msg)));
12483 			return ERR_PTR(err);
12484 		}
12485 		pr_debug("failed to get map info for FD %d; API not supported? Ignoring...\n",
12486 			 map_fd);
12487 	} else {
12488 		if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
12489 			pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
12490 				map.name);
12491 			return ERR_PTR(-EINVAL);
12492 		}
12493 	}
12494 
12495 	pb = calloc(1, sizeof(*pb));
12496 	if (!pb)
12497 		return ERR_PTR(-ENOMEM);
12498 
12499 	pb->event_cb = p->event_cb;
12500 	pb->sample_cb = p->sample_cb;
12501 	pb->lost_cb = p->lost_cb;
12502 	pb->ctx = p->ctx;
12503 
12504 	pb->page_size = getpagesize();
12505 	pb->mmap_size = pb->page_size * page_cnt;
12506 	pb->map_fd = map_fd;
12507 
12508 	pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
12509 	if (pb->epoll_fd < 0) {
12510 		err = -errno;
12511 		pr_warn("failed to create epoll instance: %s\n",
12512 			libbpf_strerror_r(err, msg, sizeof(msg)));
12513 		goto error;
12514 	}
12515 
12516 	if (p->cpu_cnt > 0) {
12517 		pb->cpu_cnt = p->cpu_cnt;
12518 	} else {
12519 		pb->cpu_cnt = libbpf_num_possible_cpus();
12520 		if (pb->cpu_cnt < 0) {
12521 			err = pb->cpu_cnt;
12522 			goto error;
12523 		}
12524 		if (map.max_entries && map.max_entries < pb->cpu_cnt)
12525 			pb->cpu_cnt = map.max_entries;
12526 	}
12527 
12528 	pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
12529 	if (!pb->events) {
12530 		err = -ENOMEM;
12531 		pr_warn("failed to allocate events: out of memory\n");
12532 		goto error;
12533 	}
12534 	pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
12535 	if (!pb->cpu_bufs) {
12536 		err = -ENOMEM;
12537 		pr_warn("failed to allocate buffers: out of memory\n");
12538 		goto error;
12539 	}
12540 
12541 	err = parse_cpu_mask_file(online_cpus_file, &online, &n);
12542 	if (err) {
12543 		pr_warn("failed to get online CPU mask: %d\n", err);
12544 		goto error;
12545 	}
12546 
12547 	for (i = 0, j = 0; i < pb->cpu_cnt; i++) {
12548 		struct perf_cpu_buf *cpu_buf;
12549 		int cpu, map_key;
12550 
12551 		cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
12552 		map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
12553 
12554 		/* in case user didn't explicitly requested particular CPUs to
12555 		 * be attached to, skip offline/not present CPUs
12556 		 */
12557 		if (p->cpu_cnt <= 0 && (cpu >= n || !online[cpu]))
12558 			continue;
12559 
12560 		cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
12561 		if (IS_ERR(cpu_buf)) {
12562 			err = PTR_ERR(cpu_buf);
12563 			goto error;
12564 		}
12565 
12566 		pb->cpu_bufs[j] = cpu_buf;
12567 
12568 		err = bpf_map_update_elem(pb->map_fd, &map_key,
12569 					  &cpu_buf->fd, 0);
12570 		if (err) {
12571 			err = -errno;
12572 			pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
12573 				cpu, map_key, cpu_buf->fd,
12574 				libbpf_strerror_r(err, msg, sizeof(msg)));
12575 			goto error;
12576 		}
12577 
12578 		pb->events[j].events = EPOLLIN;
12579 		pb->events[j].data.ptr = cpu_buf;
12580 		if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
12581 			      &pb->events[j]) < 0) {
12582 			err = -errno;
12583 			pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
12584 				cpu, cpu_buf->fd,
12585 				libbpf_strerror_r(err, msg, sizeof(msg)));
12586 			goto error;
12587 		}
12588 		j++;
12589 	}
12590 	pb->cpu_cnt = j;
12591 	free(online);
12592 
12593 	return pb;
12594 
12595 error:
12596 	free(online);
12597 	if (pb)
12598 		perf_buffer__free(pb);
12599 	return ERR_PTR(err);
12600 }
12601 
12602 struct perf_sample_raw {
12603 	struct perf_event_header header;
12604 	uint32_t size;
12605 	char data[];
12606 };
12607 
12608 struct perf_sample_lost {
12609 	struct perf_event_header header;
12610 	uint64_t id;
12611 	uint64_t lost;
12612 	uint64_t sample_id;
12613 };
12614 
12615 static enum bpf_perf_event_ret
12616 perf_buffer__process_record(struct perf_event_header *e, void *ctx)
12617 {
12618 	struct perf_cpu_buf *cpu_buf = ctx;
12619 	struct perf_buffer *pb = cpu_buf->pb;
12620 	void *data = e;
12621 
12622 	/* user wants full control over parsing perf event */
12623 	if (pb->event_cb)
12624 		return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
12625 
12626 	switch (e->type) {
12627 	case PERF_RECORD_SAMPLE: {
12628 		struct perf_sample_raw *s = data;
12629 
12630 		if (pb->sample_cb)
12631 			pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
12632 		break;
12633 	}
12634 	case PERF_RECORD_LOST: {
12635 		struct perf_sample_lost *s = data;
12636 
12637 		if (pb->lost_cb)
12638 			pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
12639 		break;
12640 	}
12641 	default:
12642 		pr_warn("unknown perf sample type %d\n", e->type);
12643 		return LIBBPF_PERF_EVENT_ERROR;
12644 	}
12645 	return LIBBPF_PERF_EVENT_CONT;
12646 }
12647 
12648 static int perf_buffer__process_records(struct perf_buffer *pb,
12649 					struct perf_cpu_buf *cpu_buf)
12650 {
12651 	enum bpf_perf_event_ret ret;
12652 
12653 	ret = perf_event_read_simple(cpu_buf->base, pb->mmap_size,
12654 				     pb->page_size, &cpu_buf->buf,
12655 				     &cpu_buf->buf_size,
12656 				     perf_buffer__process_record, cpu_buf);
12657 	if (ret != LIBBPF_PERF_EVENT_CONT)
12658 		return ret;
12659 	return 0;
12660 }
12661 
12662 int perf_buffer__epoll_fd(const struct perf_buffer *pb)
12663 {
12664 	return pb->epoll_fd;
12665 }
12666 
12667 int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
12668 {
12669 	int i, cnt, err;
12670 
12671 	cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
12672 	if (cnt < 0)
12673 		return -errno;
12674 
12675 	for (i = 0; i < cnt; i++) {
12676 		struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
12677 
12678 		err = perf_buffer__process_records(pb, cpu_buf);
12679 		if (err) {
12680 			pr_warn("error while processing records: %d\n", err);
12681 			return libbpf_err(err);
12682 		}
12683 	}
12684 	return cnt;
12685 }
12686 
12687 /* Return number of PERF_EVENT_ARRAY map slots set up by this perf_buffer
12688  * manager.
12689  */
12690 size_t perf_buffer__buffer_cnt(const struct perf_buffer *pb)
12691 {
12692 	return pb->cpu_cnt;
12693 }
12694 
12695 /*
12696  * Return perf_event FD of a ring buffer in *buf_idx* slot of
12697  * PERF_EVENT_ARRAY BPF map. This FD can be polled for new data using
12698  * select()/poll()/epoll() Linux syscalls.
12699  */
12700 int perf_buffer__buffer_fd(const struct perf_buffer *pb, size_t buf_idx)
12701 {
12702 	struct perf_cpu_buf *cpu_buf;
12703 
12704 	if (buf_idx >= pb->cpu_cnt)
12705 		return libbpf_err(-EINVAL);
12706 
12707 	cpu_buf = pb->cpu_bufs[buf_idx];
12708 	if (!cpu_buf)
12709 		return libbpf_err(-ENOENT);
12710 
12711 	return cpu_buf->fd;
12712 }
12713 
12714 int perf_buffer__buffer(struct perf_buffer *pb, int buf_idx, void **buf, size_t *buf_size)
12715 {
12716 	struct perf_cpu_buf *cpu_buf;
12717 
12718 	if (buf_idx >= pb->cpu_cnt)
12719 		return libbpf_err(-EINVAL);
12720 
12721 	cpu_buf = pb->cpu_bufs[buf_idx];
12722 	if (!cpu_buf)
12723 		return libbpf_err(-ENOENT);
12724 
12725 	*buf = cpu_buf->base;
12726 	*buf_size = pb->mmap_size;
12727 	return 0;
12728 }
12729 
12730 /*
12731  * Consume data from perf ring buffer corresponding to slot *buf_idx* in
12732  * PERF_EVENT_ARRAY BPF map without waiting/polling. If there is no data to
12733  * consume, do nothing and return success.
12734  * Returns:
12735  *   - 0 on success;
12736  *   - <0 on failure.
12737  */
12738 int perf_buffer__consume_buffer(struct perf_buffer *pb, size_t buf_idx)
12739 {
12740 	struct perf_cpu_buf *cpu_buf;
12741 
12742 	if (buf_idx >= pb->cpu_cnt)
12743 		return libbpf_err(-EINVAL);
12744 
12745 	cpu_buf = pb->cpu_bufs[buf_idx];
12746 	if (!cpu_buf)
12747 		return libbpf_err(-ENOENT);
12748 
12749 	return perf_buffer__process_records(pb, cpu_buf);
12750 }
12751 
12752 int perf_buffer__consume(struct perf_buffer *pb)
12753 {
12754 	int i, err;
12755 
12756 	for (i = 0; i < pb->cpu_cnt; i++) {
12757 		struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
12758 
12759 		if (!cpu_buf)
12760 			continue;
12761 
12762 		err = perf_buffer__process_records(pb, cpu_buf);
12763 		if (err) {
12764 			pr_warn("perf_buffer: failed to process records in buffer #%d: %d\n", i, err);
12765 			return libbpf_err(err);
12766 		}
12767 	}
12768 	return 0;
12769 }
12770 
12771 int bpf_program__set_attach_target(struct bpf_program *prog,
12772 				   int attach_prog_fd,
12773 				   const char *attach_func_name)
12774 {
12775 	int btf_obj_fd = 0, btf_id = 0, err;
12776 
12777 	if (!prog || attach_prog_fd < 0)
12778 		return libbpf_err(-EINVAL);
12779 
12780 	if (prog->obj->loaded)
12781 		return libbpf_err(-EINVAL);
12782 
12783 	if (attach_prog_fd && !attach_func_name) {
12784 		/* remember attach_prog_fd and let bpf_program__load() find
12785 		 * BTF ID during the program load
12786 		 */
12787 		prog->attach_prog_fd = attach_prog_fd;
12788 		return 0;
12789 	}
12790 
12791 	if (attach_prog_fd) {
12792 		btf_id = libbpf_find_prog_btf_id(attach_func_name,
12793 						 attach_prog_fd);
12794 		if (btf_id < 0)
12795 			return libbpf_err(btf_id);
12796 	} else {
12797 		if (!attach_func_name)
12798 			return libbpf_err(-EINVAL);
12799 
12800 		/* load btf_vmlinux, if not yet */
12801 		err = bpf_object__load_vmlinux_btf(prog->obj, true);
12802 		if (err)
12803 			return libbpf_err(err);
12804 		err = find_kernel_btf_id(prog->obj, attach_func_name,
12805 					 prog->expected_attach_type,
12806 					 &btf_obj_fd, &btf_id);
12807 		if (err)
12808 			return libbpf_err(err);
12809 	}
12810 
12811 	prog->attach_btf_id = btf_id;
12812 	prog->attach_btf_obj_fd = btf_obj_fd;
12813 	prog->attach_prog_fd = attach_prog_fd;
12814 	return 0;
12815 }
12816 
12817 int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz)
12818 {
12819 	int err = 0, n, len, start, end = -1;
12820 	bool *tmp;
12821 
12822 	*mask = NULL;
12823 	*mask_sz = 0;
12824 
12825 	/* Each sub string separated by ',' has format \d+-\d+ or \d+ */
12826 	while (*s) {
12827 		if (*s == ',' || *s == '\n') {
12828 			s++;
12829 			continue;
12830 		}
12831 		n = sscanf(s, "%d%n-%d%n", &start, &len, &end, &len);
12832 		if (n <= 0 || n > 2) {
12833 			pr_warn("Failed to get CPU range %s: %d\n", s, n);
12834 			err = -EINVAL;
12835 			goto cleanup;
12836 		} else if (n == 1) {
12837 			end = start;
12838 		}
12839 		if (start < 0 || start > end) {
12840 			pr_warn("Invalid CPU range [%d,%d] in %s\n",
12841 				start, end, s);
12842 			err = -EINVAL;
12843 			goto cleanup;
12844 		}
12845 		tmp = realloc(*mask, end + 1);
12846 		if (!tmp) {
12847 			err = -ENOMEM;
12848 			goto cleanup;
12849 		}
12850 		*mask = tmp;
12851 		memset(tmp + *mask_sz, 0, start - *mask_sz);
12852 		memset(tmp + start, 1, end - start + 1);
12853 		*mask_sz = end + 1;
12854 		s += len;
12855 	}
12856 	if (!*mask_sz) {
12857 		pr_warn("Empty CPU range\n");
12858 		return -EINVAL;
12859 	}
12860 	return 0;
12861 cleanup:
12862 	free(*mask);
12863 	*mask = NULL;
12864 	return err;
12865 }
12866 
12867 int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz)
12868 {
12869 	int fd, err = 0, len;
12870 	char buf[128];
12871 
12872 	fd = open(fcpu, O_RDONLY | O_CLOEXEC);
12873 	if (fd < 0) {
12874 		err = -errno;
12875 		pr_warn("Failed to open cpu mask file %s: %d\n", fcpu, err);
12876 		return err;
12877 	}
12878 	len = read(fd, buf, sizeof(buf));
12879 	close(fd);
12880 	if (len <= 0) {
12881 		err = len ? -errno : -EINVAL;
12882 		pr_warn("Failed to read cpu mask from %s: %d\n", fcpu, err);
12883 		return err;
12884 	}
12885 	if (len >= sizeof(buf)) {
12886 		pr_warn("CPU mask is too big in file %s\n", fcpu);
12887 		return -E2BIG;
12888 	}
12889 	buf[len] = '\0';
12890 
12891 	return parse_cpu_mask_str(buf, mask, mask_sz);
12892 }
12893 
12894 int libbpf_num_possible_cpus(void)
12895 {
12896 	static const char *fcpu = "/sys/devices/system/cpu/possible";
12897 	static int cpus;
12898 	int err, n, i, tmp_cpus;
12899 	bool *mask;
12900 
12901 	tmp_cpus = READ_ONCE(cpus);
12902 	if (tmp_cpus > 0)
12903 		return tmp_cpus;
12904 
12905 	err = parse_cpu_mask_file(fcpu, &mask, &n);
12906 	if (err)
12907 		return libbpf_err(err);
12908 
12909 	tmp_cpus = 0;
12910 	for (i = 0; i < n; i++) {
12911 		if (mask[i])
12912 			tmp_cpus++;
12913 	}
12914 	free(mask);
12915 
12916 	WRITE_ONCE(cpus, tmp_cpus);
12917 	return tmp_cpus;
12918 }
12919 
12920 static int populate_skeleton_maps(const struct bpf_object *obj,
12921 				  struct bpf_map_skeleton *maps,
12922 				  size_t map_cnt)
12923 {
12924 	int i;
12925 
12926 	for (i = 0; i < map_cnt; i++) {
12927 		struct bpf_map **map = maps[i].map;
12928 		const char *name = maps[i].name;
12929 		void **mmaped = maps[i].mmaped;
12930 
12931 		*map = bpf_object__find_map_by_name(obj, name);
12932 		if (!*map) {
12933 			pr_warn("failed to find skeleton map '%s'\n", name);
12934 			return -ESRCH;
12935 		}
12936 
12937 		/* externs shouldn't be pre-setup from user code */
12938 		if (mmaped && (*map)->libbpf_type != LIBBPF_MAP_KCONFIG)
12939 			*mmaped = (*map)->mmaped;
12940 	}
12941 	return 0;
12942 }
12943 
12944 static int populate_skeleton_progs(const struct bpf_object *obj,
12945 				   struct bpf_prog_skeleton *progs,
12946 				   size_t prog_cnt)
12947 {
12948 	int i;
12949 
12950 	for (i = 0; i < prog_cnt; i++) {
12951 		struct bpf_program **prog = progs[i].prog;
12952 		const char *name = progs[i].name;
12953 
12954 		*prog = bpf_object__find_program_by_name(obj, name);
12955 		if (!*prog) {
12956 			pr_warn("failed to find skeleton program '%s'\n", name);
12957 			return -ESRCH;
12958 		}
12959 	}
12960 	return 0;
12961 }
12962 
12963 int bpf_object__open_skeleton(struct bpf_object_skeleton *s,
12964 			      const struct bpf_object_open_opts *opts)
12965 {
12966 	DECLARE_LIBBPF_OPTS(bpf_object_open_opts, skel_opts,
12967 		.object_name = s->name,
12968 	);
12969 	struct bpf_object *obj;
12970 	int err;
12971 
12972 	/* Attempt to preserve opts->object_name, unless overriden by user
12973 	 * explicitly. Overwriting object name for skeletons is discouraged,
12974 	 * as it breaks global data maps, because they contain object name
12975 	 * prefix as their own map name prefix. When skeleton is generated,
12976 	 * bpftool is making an assumption that this name will stay the same.
12977 	 */
12978 	if (opts) {
12979 		memcpy(&skel_opts, opts, sizeof(*opts));
12980 		if (!opts->object_name)
12981 			skel_opts.object_name = s->name;
12982 	}
12983 
12984 	obj = bpf_object__open_mem(s->data, s->data_sz, &skel_opts);
12985 	err = libbpf_get_error(obj);
12986 	if (err) {
12987 		pr_warn("failed to initialize skeleton BPF object '%s': %d\n",
12988 			s->name, err);
12989 		return libbpf_err(err);
12990 	}
12991 
12992 	*s->obj = obj;
12993 	err = populate_skeleton_maps(obj, s->maps, s->map_cnt);
12994 	if (err) {
12995 		pr_warn("failed to populate skeleton maps for '%s': %d\n", s->name, err);
12996 		return libbpf_err(err);
12997 	}
12998 
12999 	err = populate_skeleton_progs(obj, s->progs, s->prog_cnt);
13000 	if (err) {
13001 		pr_warn("failed to populate skeleton progs for '%s': %d\n", s->name, err);
13002 		return libbpf_err(err);
13003 	}
13004 
13005 	return 0;
13006 }
13007 
13008 int bpf_object__open_subskeleton(struct bpf_object_subskeleton *s)
13009 {
13010 	int err, len, var_idx, i;
13011 	const char *var_name;
13012 	const struct bpf_map *map;
13013 	struct btf *btf;
13014 	__u32 map_type_id;
13015 	const struct btf_type *map_type, *var_type;
13016 	const struct bpf_var_skeleton *var_skel;
13017 	struct btf_var_secinfo *var;
13018 
13019 	if (!s->obj)
13020 		return libbpf_err(-EINVAL);
13021 
13022 	btf = bpf_object__btf(s->obj);
13023 	if (!btf) {
13024 		pr_warn("subskeletons require BTF at runtime (object %s)\n",
13025 			bpf_object__name(s->obj));
13026 		return libbpf_err(-errno);
13027 	}
13028 
13029 	err = populate_skeleton_maps(s->obj, s->maps, s->map_cnt);
13030 	if (err) {
13031 		pr_warn("failed to populate subskeleton maps: %d\n", err);
13032 		return libbpf_err(err);
13033 	}
13034 
13035 	err = populate_skeleton_progs(s->obj, s->progs, s->prog_cnt);
13036 	if (err) {
13037 		pr_warn("failed to populate subskeleton maps: %d\n", err);
13038 		return libbpf_err(err);
13039 	}
13040 
13041 	for (var_idx = 0; var_idx < s->var_cnt; var_idx++) {
13042 		var_skel = &s->vars[var_idx];
13043 		map = *var_skel->map;
13044 		map_type_id = bpf_map__btf_value_type_id(map);
13045 		map_type = btf__type_by_id(btf, map_type_id);
13046 
13047 		if (!btf_is_datasec(map_type)) {
13048 			pr_warn("type for map '%1$s' is not a datasec: %2$s",
13049 				bpf_map__name(map),
13050 				__btf_kind_str(btf_kind(map_type)));
13051 			return libbpf_err(-EINVAL);
13052 		}
13053 
13054 		len = btf_vlen(map_type);
13055 		var = btf_var_secinfos(map_type);
13056 		for (i = 0; i < len; i++, var++) {
13057 			var_type = btf__type_by_id(btf, var->type);
13058 			var_name = btf__name_by_offset(btf, var_type->name_off);
13059 			if (strcmp(var_name, var_skel->name) == 0) {
13060 				*var_skel->addr = map->mmaped + var->offset;
13061 				break;
13062 			}
13063 		}
13064 	}
13065 	return 0;
13066 }
13067 
13068 void bpf_object__destroy_subskeleton(struct bpf_object_subskeleton *s)
13069 {
13070 	if (!s)
13071 		return;
13072 	free(s->maps);
13073 	free(s->progs);
13074 	free(s->vars);
13075 	free(s);
13076 }
13077 
13078 int bpf_object__load_skeleton(struct bpf_object_skeleton *s)
13079 {
13080 	int i, err;
13081 
13082 	err = bpf_object__load(*s->obj);
13083 	if (err) {
13084 		pr_warn("failed to load BPF skeleton '%s': %d\n", s->name, err);
13085 		return libbpf_err(err);
13086 	}
13087 
13088 	for (i = 0; i < s->map_cnt; i++) {
13089 		struct bpf_map *map = *s->maps[i].map;
13090 		size_t mmap_sz = bpf_map_mmap_sz(map->def.value_size, map->def.max_entries);
13091 		int prot, map_fd = bpf_map__fd(map);
13092 		void **mmaped = s->maps[i].mmaped;
13093 
13094 		if (!mmaped)
13095 			continue;
13096 
13097 		if (!(map->def.map_flags & BPF_F_MMAPABLE)) {
13098 			*mmaped = NULL;
13099 			continue;
13100 		}
13101 
13102 		if (map->def.map_flags & BPF_F_RDONLY_PROG)
13103 			prot = PROT_READ;
13104 		else
13105 			prot = PROT_READ | PROT_WRITE;
13106 
13107 		/* Remap anonymous mmap()-ed "map initialization image" as
13108 		 * a BPF map-backed mmap()-ed memory, but preserving the same
13109 		 * memory address. This will cause kernel to change process'
13110 		 * page table to point to a different piece of kernel memory,
13111 		 * but from userspace point of view memory address (and its
13112 		 * contents, being identical at this point) will stay the
13113 		 * same. This mapping will be released by bpf_object__close()
13114 		 * as per normal clean up procedure, so we don't need to worry
13115 		 * about it from skeleton's clean up perspective.
13116 		 */
13117 		*mmaped = mmap(map->mmaped, mmap_sz, prot, MAP_SHARED | MAP_FIXED, map_fd, 0);
13118 		if (*mmaped == MAP_FAILED) {
13119 			err = -errno;
13120 			*mmaped = NULL;
13121 			pr_warn("failed to re-mmap() map '%s': %d\n",
13122 				 bpf_map__name(map), err);
13123 			return libbpf_err(err);
13124 		}
13125 	}
13126 
13127 	return 0;
13128 }
13129 
13130 int bpf_object__attach_skeleton(struct bpf_object_skeleton *s)
13131 {
13132 	int i, err;
13133 
13134 	for (i = 0; i < s->prog_cnt; i++) {
13135 		struct bpf_program *prog = *s->progs[i].prog;
13136 		struct bpf_link **link = s->progs[i].link;
13137 
13138 		if (!prog->autoload || !prog->autoattach)
13139 			continue;
13140 
13141 		/* auto-attaching not supported for this program */
13142 		if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
13143 			continue;
13144 
13145 		/* if user already set the link manually, don't attempt auto-attach */
13146 		if (*link)
13147 			continue;
13148 
13149 		err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, link);
13150 		if (err) {
13151 			pr_warn("prog '%s': failed to auto-attach: %d\n",
13152 				bpf_program__name(prog), err);
13153 			return libbpf_err(err);
13154 		}
13155 
13156 		/* It's possible that for some SEC() definitions auto-attach
13157 		 * is supported in some cases (e.g., if definition completely
13158 		 * specifies target information), but is not in other cases.
13159 		 * SEC("uprobe") is one such case. If user specified target
13160 		 * binary and function name, such BPF program can be
13161 		 * auto-attached. But if not, it shouldn't trigger skeleton's
13162 		 * attach to fail. It should just be skipped.
13163 		 * attach_fn signals such case with returning 0 (no error) and
13164 		 * setting link to NULL.
13165 		 */
13166 	}
13167 
13168 	return 0;
13169 }
13170 
13171 void bpf_object__detach_skeleton(struct bpf_object_skeleton *s)
13172 {
13173 	int i;
13174 
13175 	for (i = 0; i < s->prog_cnt; i++) {
13176 		struct bpf_link **link = s->progs[i].link;
13177 
13178 		bpf_link__destroy(*link);
13179 		*link = NULL;
13180 	}
13181 }
13182 
13183 void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s)
13184 {
13185 	if (!s)
13186 		return;
13187 
13188 	if (s->progs)
13189 		bpf_object__detach_skeleton(s);
13190 	if (s->obj)
13191 		bpf_object__close(*s->obj);
13192 	free(s->maps);
13193 	free(s->progs);
13194 	free(s);
13195 }
13196