xref: /openbmc/linux/tools/lib/bpf/libbpf.c (revision 9b68f30b)
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 };
121 
122 static const char * const link_type_name[] = {
123 	[BPF_LINK_TYPE_UNSPEC]			= "unspec",
124 	[BPF_LINK_TYPE_RAW_TRACEPOINT]		= "raw_tracepoint",
125 	[BPF_LINK_TYPE_TRACING]			= "tracing",
126 	[BPF_LINK_TYPE_CGROUP]			= "cgroup",
127 	[BPF_LINK_TYPE_ITER]			= "iter",
128 	[BPF_LINK_TYPE_NETNS]			= "netns",
129 	[BPF_LINK_TYPE_XDP]			= "xdp",
130 	[BPF_LINK_TYPE_PERF_EVENT]		= "perf_event",
131 	[BPF_LINK_TYPE_KPROBE_MULTI]		= "kprobe_multi",
132 	[BPF_LINK_TYPE_STRUCT_OPS]		= "struct_ops",
133 	[BPF_LINK_TYPE_NETFILTER]		= "netfilter",
134 };
135 
136 static const char * const map_type_name[] = {
137 	[BPF_MAP_TYPE_UNSPEC]			= "unspec",
138 	[BPF_MAP_TYPE_HASH]			= "hash",
139 	[BPF_MAP_TYPE_ARRAY]			= "array",
140 	[BPF_MAP_TYPE_PROG_ARRAY]		= "prog_array",
141 	[BPF_MAP_TYPE_PERF_EVENT_ARRAY]		= "perf_event_array",
142 	[BPF_MAP_TYPE_PERCPU_HASH]		= "percpu_hash",
143 	[BPF_MAP_TYPE_PERCPU_ARRAY]		= "percpu_array",
144 	[BPF_MAP_TYPE_STACK_TRACE]		= "stack_trace",
145 	[BPF_MAP_TYPE_CGROUP_ARRAY]		= "cgroup_array",
146 	[BPF_MAP_TYPE_LRU_HASH]			= "lru_hash",
147 	[BPF_MAP_TYPE_LRU_PERCPU_HASH]		= "lru_percpu_hash",
148 	[BPF_MAP_TYPE_LPM_TRIE]			= "lpm_trie",
149 	[BPF_MAP_TYPE_ARRAY_OF_MAPS]		= "array_of_maps",
150 	[BPF_MAP_TYPE_HASH_OF_MAPS]		= "hash_of_maps",
151 	[BPF_MAP_TYPE_DEVMAP]			= "devmap",
152 	[BPF_MAP_TYPE_DEVMAP_HASH]		= "devmap_hash",
153 	[BPF_MAP_TYPE_SOCKMAP]			= "sockmap",
154 	[BPF_MAP_TYPE_CPUMAP]			= "cpumap",
155 	[BPF_MAP_TYPE_XSKMAP]			= "xskmap",
156 	[BPF_MAP_TYPE_SOCKHASH]			= "sockhash",
157 	[BPF_MAP_TYPE_CGROUP_STORAGE]		= "cgroup_storage",
158 	[BPF_MAP_TYPE_REUSEPORT_SOCKARRAY]	= "reuseport_sockarray",
159 	[BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE]	= "percpu_cgroup_storage",
160 	[BPF_MAP_TYPE_QUEUE]			= "queue",
161 	[BPF_MAP_TYPE_STACK]			= "stack",
162 	[BPF_MAP_TYPE_SK_STORAGE]		= "sk_storage",
163 	[BPF_MAP_TYPE_STRUCT_OPS]		= "struct_ops",
164 	[BPF_MAP_TYPE_RINGBUF]			= "ringbuf",
165 	[BPF_MAP_TYPE_INODE_STORAGE]		= "inode_storage",
166 	[BPF_MAP_TYPE_TASK_STORAGE]		= "task_storage",
167 	[BPF_MAP_TYPE_BLOOM_FILTER]		= "bloom_filter",
168 	[BPF_MAP_TYPE_USER_RINGBUF]             = "user_ringbuf",
169 	[BPF_MAP_TYPE_CGRP_STORAGE]		= "cgrp_storage",
170 };
171 
172 static const char * const prog_type_name[] = {
173 	[BPF_PROG_TYPE_UNSPEC]			= "unspec",
174 	[BPF_PROG_TYPE_SOCKET_FILTER]		= "socket_filter",
175 	[BPF_PROG_TYPE_KPROBE]			= "kprobe",
176 	[BPF_PROG_TYPE_SCHED_CLS]		= "sched_cls",
177 	[BPF_PROG_TYPE_SCHED_ACT]		= "sched_act",
178 	[BPF_PROG_TYPE_TRACEPOINT]		= "tracepoint",
179 	[BPF_PROG_TYPE_XDP]			= "xdp",
180 	[BPF_PROG_TYPE_PERF_EVENT]		= "perf_event",
181 	[BPF_PROG_TYPE_CGROUP_SKB]		= "cgroup_skb",
182 	[BPF_PROG_TYPE_CGROUP_SOCK]		= "cgroup_sock",
183 	[BPF_PROG_TYPE_LWT_IN]			= "lwt_in",
184 	[BPF_PROG_TYPE_LWT_OUT]			= "lwt_out",
185 	[BPF_PROG_TYPE_LWT_XMIT]		= "lwt_xmit",
186 	[BPF_PROG_TYPE_SOCK_OPS]		= "sock_ops",
187 	[BPF_PROG_TYPE_SK_SKB]			= "sk_skb",
188 	[BPF_PROG_TYPE_CGROUP_DEVICE]		= "cgroup_device",
189 	[BPF_PROG_TYPE_SK_MSG]			= "sk_msg",
190 	[BPF_PROG_TYPE_RAW_TRACEPOINT]		= "raw_tracepoint",
191 	[BPF_PROG_TYPE_CGROUP_SOCK_ADDR]	= "cgroup_sock_addr",
192 	[BPF_PROG_TYPE_LWT_SEG6LOCAL]		= "lwt_seg6local",
193 	[BPF_PROG_TYPE_LIRC_MODE2]		= "lirc_mode2",
194 	[BPF_PROG_TYPE_SK_REUSEPORT]		= "sk_reuseport",
195 	[BPF_PROG_TYPE_FLOW_DISSECTOR]		= "flow_dissector",
196 	[BPF_PROG_TYPE_CGROUP_SYSCTL]		= "cgroup_sysctl",
197 	[BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE]	= "raw_tracepoint_writable",
198 	[BPF_PROG_TYPE_CGROUP_SOCKOPT]		= "cgroup_sockopt",
199 	[BPF_PROG_TYPE_TRACING]			= "tracing",
200 	[BPF_PROG_TYPE_STRUCT_OPS]		= "struct_ops",
201 	[BPF_PROG_TYPE_EXT]			= "ext",
202 	[BPF_PROG_TYPE_LSM]			= "lsm",
203 	[BPF_PROG_TYPE_SK_LOOKUP]		= "sk_lookup",
204 	[BPF_PROG_TYPE_SYSCALL]			= "syscall",
205 	[BPF_PROG_TYPE_NETFILTER]		= "netfilter",
206 };
207 
208 static int __base_pr(enum libbpf_print_level level, const char *format,
209 		     va_list args)
210 {
211 	if (level == LIBBPF_DEBUG)
212 		return 0;
213 
214 	return vfprintf(stderr, format, args);
215 }
216 
217 static libbpf_print_fn_t __libbpf_pr = __base_pr;
218 
219 libbpf_print_fn_t libbpf_set_print(libbpf_print_fn_t fn)
220 {
221 	libbpf_print_fn_t old_print_fn;
222 
223 	old_print_fn = __atomic_exchange_n(&__libbpf_pr, fn, __ATOMIC_RELAXED);
224 
225 	return old_print_fn;
226 }
227 
228 __printf(2, 3)
229 void libbpf_print(enum libbpf_print_level level, const char *format, ...)
230 {
231 	va_list args;
232 	int old_errno;
233 	libbpf_print_fn_t print_fn;
234 
235 	print_fn = __atomic_load_n(&__libbpf_pr, __ATOMIC_RELAXED);
236 	if (!print_fn)
237 		return;
238 
239 	old_errno = errno;
240 
241 	va_start(args, format);
242 	__libbpf_pr(level, format, args);
243 	va_end(args);
244 
245 	errno = old_errno;
246 }
247 
248 static void pr_perm_msg(int err)
249 {
250 	struct rlimit limit;
251 	char buf[100];
252 
253 	if (err != -EPERM || geteuid() != 0)
254 		return;
255 
256 	err = getrlimit(RLIMIT_MEMLOCK, &limit);
257 	if (err)
258 		return;
259 
260 	if (limit.rlim_cur == RLIM_INFINITY)
261 		return;
262 
263 	if (limit.rlim_cur < 1024)
264 		snprintf(buf, sizeof(buf), "%zu bytes", (size_t)limit.rlim_cur);
265 	else if (limit.rlim_cur < 1024*1024)
266 		snprintf(buf, sizeof(buf), "%.1f KiB", (double)limit.rlim_cur / 1024);
267 	else
268 		snprintf(buf, sizeof(buf), "%.1f MiB", (double)limit.rlim_cur / (1024*1024));
269 
270 	pr_warn("permission error while running as root; try raising 'ulimit -l'? current value: %s\n",
271 		buf);
272 }
273 
274 #define STRERR_BUFSIZE  128
275 
276 /* Copied from tools/perf/util/util.h */
277 #ifndef zfree
278 # define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
279 #endif
280 
281 #ifndef zclose
282 # define zclose(fd) ({			\
283 	int ___err = 0;			\
284 	if ((fd) >= 0)			\
285 		___err = close((fd));	\
286 	fd = -1;			\
287 	___err; })
288 #endif
289 
290 static inline __u64 ptr_to_u64(const void *ptr)
291 {
292 	return (__u64) (unsigned long) ptr;
293 }
294 
295 int libbpf_set_strict_mode(enum libbpf_strict_mode mode)
296 {
297 	/* as of v1.0 libbpf_set_strict_mode() is a no-op */
298 	return 0;
299 }
300 
301 __u32 libbpf_major_version(void)
302 {
303 	return LIBBPF_MAJOR_VERSION;
304 }
305 
306 __u32 libbpf_minor_version(void)
307 {
308 	return LIBBPF_MINOR_VERSION;
309 }
310 
311 const char *libbpf_version_string(void)
312 {
313 #define __S(X) #X
314 #define _S(X) __S(X)
315 	return  "v" _S(LIBBPF_MAJOR_VERSION) "." _S(LIBBPF_MINOR_VERSION);
316 #undef _S
317 #undef __S
318 }
319 
320 enum reloc_type {
321 	RELO_LD64,
322 	RELO_CALL,
323 	RELO_DATA,
324 	RELO_EXTERN_LD64,
325 	RELO_EXTERN_CALL,
326 	RELO_SUBPROG_ADDR,
327 	RELO_CORE,
328 };
329 
330 struct reloc_desc {
331 	enum reloc_type type;
332 	int insn_idx;
333 	union {
334 		const struct bpf_core_relo *core_relo; /* used when type == RELO_CORE */
335 		struct {
336 			int map_idx;
337 			int sym_off;
338 			int ext_idx;
339 		};
340 	};
341 };
342 
343 /* stored as sec_def->cookie for all libbpf-supported SEC()s */
344 enum sec_def_flags {
345 	SEC_NONE = 0,
346 	/* expected_attach_type is optional, if kernel doesn't support that */
347 	SEC_EXP_ATTACH_OPT = 1,
348 	/* legacy, only used by libbpf_get_type_names() and
349 	 * libbpf_attach_type_by_name(), not used by libbpf itself at all.
350 	 * This used to be associated with cgroup (and few other) BPF programs
351 	 * that were attachable through BPF_PROG_ATTACH command. Pretty
352 	 * meaningless nowadays, though.
353 	 */
354 	SEC_ATTACHABLE = 2,
355 	SEC_ATTACHABLE_OPT = SEC_ATTACHABLE | SEC_EXP_ATTACH_OPT,
356 	/* attachment target is specified through BTF ID in either kernel or
357 	 * other BPF program's BTF object
358 	 */
359 	SEC_ATTACH_BTF = 4,
360 	/* BPF program type allows sleeping/blocking in kernel */
361 	SEC_SLEEPABLE = 8,
362 	/* BPF program support non-linear XDP buffer */
363 	SEC_XDP_FRAGS = 16,
364 };
365 
366 struct bpf_sec_def {
367 	char *sec;
368 	enum bpf_prog_type prog_type;
369 	enum bpf_attach_type expected_attach_type;
370 	long cookie;
371 	int handler_id;
372 
373 	libbpf_prog_setup_fn_t prog_setup_fn;
374 	libbpf_prog_prepare_load_fn_t prog_prepare_load_fn;
375 	libbpf_prog_attach_fn_t prog_attach_fn;
376 };
377 
378 /*
379  * bpf_prog should be a better name but it has been used in
380  * linux/filter.h.
381  */
382 struct bpf_program {
383 	char *name;
384 	char *sec_name;
385 	size_t sec_idx;
386 	const struct bpf_sec_def *sec_def;
387 	/* this program's instruction offset (in number of instructions)
388 	 * within its containing ELF section
389 	 */
390 	size_t sec_insn_off;
391 	/* number of original instructions in ELF section belonging to this
392 	 * program, not taking into account subprogram instructions possible
393 	 * appended later during relocation
394 	 */
395 	size_t sec_insn_cnt;
396 	/* Offset (in number of instructions) of the start of instruction
397 	 * belonging to this BPF program  within its containing main BPF
398 	 * program. For the entry-point (main) BPF program, this is always
399 	 * zero. For a sub-program, this gets reset before each of main BPF
400 	 * programs are processed and relocated and is used to determined
401 	 * whether sub-program was already appended to the main program, and
402 	 * if yes, at which instruction offset.
403 	 */
404 	size_t sub_insn_off;
405 
406 	/* instructions that belong to BPF program; insns[0] is located at
407 	 * sec_insn_off instruction within its ELF section in ELF file, so
408 	 * when mapping ELF file instruction index to the local instruction,
409 	 * one needs to subtract sec_insn_off; and vice versa.
410 	 */
411 	struct bpf_insn *insns;
412 	/* actual number of instruction in this BPF program's image; for
413 	 * entry-point BPF programs this includes the size of main program
414 	 * itself plus all the used sub-programs, appended at the end
415 	 */
416 	size_t insns_cnt;
417 
418 	struct reloc_desc *reloc_desc;
419 	int nr_reloc;
420 
421 	/* BPF verifier log settings */
422 	char *log_buf;
423 	size_t log_size;
424 	__u32 log_level;
425 
426 	struct bpf_object *obj;
427 
428 	int fd;
429 	bool autoload;
430 	bool autoattach;
431 	bool mark_btf_static;
432 	enum bpf_prog_type type;
433 	enum bpf_attach_type expected_attach_type;
434 
435 	int prog_ifindex;
436 	__u32 attach_btf_obj_fd;
437 	__u32 attach_btf_id;
438 	__u32 attach_prog_fd;
439 
440 	void *func_info;
441 	__u32 func_info_rec_size;
442 	__u32 func_info_cnt;
443 
444 	void *line_info;
445 	__u32 line_info_rec_size;
446 	__u32 line_info_cnt;
447 	__u32 prog_flags;
448 };
449 
450 struct bpf_struct_ops {
451 	const char *tname;
452 	const struct btf_type *type;
453 	struct bpf_program **progs;
454 	__u32 *kern_func_off;
455 	/* e.g. struct tcp_congestion_ops in bpf_prog's btf format */
456 	void *data;
457 	/* e.g. struct bpf_struct_ops_tcp_congestion_ops in
458 	 *      btf_vmlinux's format.
459 	 * struct bpf_struct_ops_tcp_congestion_ops {
460 	 *	[... some other kernel fields ...]
461 	 *	struct tcp_congestion_ops data;
462 	 * }
463 	 * kern_vdata-size == sizeof(struct bpf_struct_ops_tcp_congestion_ops)
464 	 * bpf_map__init_kern_struct_ops() will populate the "kern_vdata"
465 	 * from "data".
466 	 */
467 	void *kern_vdata;
468 	__u32 type_id;
469 };
470 
471 #define DATA_SEC ".data"
472 #define BSS_SEC ".bss"
473 #define RODATA_SEC ".rodata"
474 #define KCONFIG_SEC ".kconfig"
475 #define KSYMS_SEC ".ksyms"
476 #define STRUCT_OPS_SEC ".struct_ops"
477 #define STRUCT_OPS_LINK_SEC ".struct_ops.link"
478 
479 enum libbpf_map_type {
480 	LIBBPF_MAP_UNSPEC,
481 	LIBBPF_MAP_DATA,
482 	LIBBPF_MAP_BSS,
483 	LIBBPF_MAP_RODATA,
484 	LIBBPF_MAP_KCONFIG,
485 };
486 
487 struct bpf_map_def {
488 	unsigned int type;
489 	unsigned int key_size;
490 	unsigned int value_size;
491 	unsigned int max_entries;
492 	unsigned int map_flags;
493 };
494 
495 struct bpf_map {
496 	struct bpf_object *obj;
497 	char *name;
498 	/* real_name is defined for special internal maps (.rodata*,
499 	 * .data*, .bss, .kconfig) and preserves their original ELF section
500 	 * name. This is important to be able to find corresponding BTF
501 	 * DATASEC information.
502 	 */
503 	char *real_name;
504 	int fd;
505 	int sec_idx;
506 	size_t sec_offset;
507 	int map_ifindex;
508 	int inner_map_fd;
509 	struct bpf_map_def def;
510 	__u32 numa_node;
511 	__u32 btf_var_idx;
512 	__u32 btf_key_type_id;
513 	__u32 btf_value_type_id;
514 	__u32 btf_vmlinux_value_type_id;
515 	enum libbpf_map_type libbpf_type;
516 	void *mmaped;
517 	struct bpf_struct_ops *st_ops;
518 	struct bpf_map *inner_map;
519 	void **init_slots;
520 	int init_slots_sz;
521 	char *pin_path;
522 	bool pinned;
523 	bool reused;
524 	bool autocreate;
525 	__u64 map_extra;
526 };
527 
528 enum extern_type {
529 	EXT_UNKNOWN,
530 	EXT_KCFG,
531 	EXT_KSYM,
532 };
533 
534 enum kcfg_type {
535 	KCFG_UNKNOWN,
536 	KCFG_CHAR,
537 	KCFG_BOOL,
538 	KCFG_INT,
539 	KCFG_TRISTATE,
540 	KCFG_CHAR_ARR,
541 };
542 
543 struct extern_desc {
544 	enum extern_type type;
545 	int sym_idx;
546 	int btf_id;
547 	int sec_btf_id;
548 	const char *name;
549 	bool is_set;
550 	bool is_weak;
551 	union {
552 		struct {
553 			enum kcfg_type type;
554 			int sz;
555 			int align;
556 			int data_off;
557 			bool is_signed;
558 		} kcfg;
559 		struct {
560 			unsigned long long addr;
561 
562 			/* target btf_id of the corresponding kernel var. */
563 			int kernel_btf_obj_fd;
564 			int kernel_btf_id;
565 
566 			/* local btf_id of the ksym extern's type. */
567 			__u32 type_id;
568 			/* BTF fd index to be patched in for insn->off, this is
569 			 * 0 for vmlinux BTF, index in obj->fd_array for module
570 			 * BTF
571 			 */
572 			__s16 btf_fd_idx;
573 		} ksym;
574 	};
575 };
576 
577 struct module_btf {
578 	struct btf *btf;
579 	char *name;
580 	__u32 id;
581 	int fd;
582 	int fd_array_idx;
583 };
584 
585 enum sec_type {
586 	SEC_UNUSED = 0,
587 	SEC_RELO,
588 	SEC_BSS,
589 	SEC_DATA,
590 	SEC_RODATA,
591 };
592 
593 struct elf_sec_desc {
594 	enum sec_type sec_type;
595 	Elf64_Shdr *shdr;
596 	Elf_Data *data;
597 };
598 
599 struct elf_state {
600 	int fd;
601 	const void *obj_buf;
602 	size_t obj_buf_sz;
603 	Elf *elf;
604 	Elf64_Ehdr *ehdr;
605 	Elf_Data *symbols;
606 	Elf_Data *st_ops_data;
607 	Elf_Data *st_ops_link_data;
608 	size_t shstrndx; /* section index for section name strings */
609 	size_t strtabidx;
610 	struct elf_sec_desc *secs;
611 	size_t sec_cnt;
612 	int btf_maps_shndx;
613 	__u32 btf_maps_sec_btf_id;
614 	int text_shndx;
615 	int symbols_shndx;
616 	int st_ops_shndx;
617 	int st_ops_link_shndx;
618 };
619 
620 struct usdt_manager;
621 
622 struct bpf_object {
623 	char name[BPF_OBJ_NAME_LEN];
624 	char license[64];
625 	__u32 kern_version;
626 
627 	struct bpf_program *programs;
628 	size_t nr_programs;
629 	struct bpf_map *maps;
630 	size_t nr_maps;
631 	size_t maps_cap;
632 
633 	char *kconfig;
634 	struct extern_desc *externs;
635 	int nr_extern;
636 	int kconfig_map_idx;
637 
638 	bool loaded;
639 	bool has_subcalls;
640 	bool has_rodata;
641 
642 	struct bpf_gen *gen_loader;
643 
644 	/* Information when doing ELF related work. Only valid if efile.elf is not NULL */
645 	struct elf_state efile;
646 
647 	struct btf *btf;
648 	struct btf_ext *btf_ext;
649 
650 	/* Parse and load BTF vmlinux if any of the programs in the object need
651 	 * it at load time.
652 	 */
653 	struct btf *btf_vmlinux;
654 	/* Path to the custom BTF to be used for BPF CO-RE relocations as an
655 	 * override for vmlinux BTF.
656 	 */
657 	char *btf_custom_path;
658 	/* vmlinux BTF override for CO-RE relocations */
659 	struct btf *btf_vmlinux_override;
660 	/* Lazily initialized kernel module BTFs */
661 	struct module_btf *btf_modules;
662 	bool btf_modules_loaded;
663 	size_t btf_module_cnt;
664 	size_t btf_module_cap;
665 
666 	/* optional log settings passed to BPF_BTF_LOAD and BPF_PROG_LOAD commands */
667 	char *log_buf;
668 	size_t log_size;
669 	__u32 log_level;
670 
671 	int *fd_array;
672 	size_t fd_array_cap;
673 	size_t fd_array_cnt;
674 
675 	struct usdt_manager *usdt_man;
676 
677 	char path[];
678 };
679 
680 static const char *elf_sym_str(const struct bpf_object *obj, size_t off);
681 static const char *elf_sec_str(const struct bpf_object *obj, size_t off);
682 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx);
683 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name);
684 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn);
685 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn);
686 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn);
687 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx);
688 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx);
689 
690 void bpf_program__unload(struct bpf_program *prog)
691 {
692 	if (!prog)
693 		return;
694 
695 	zclose(prog->fd);
696 
697 	zfree(&prog->func_info);
698 	zfree(&prog->line_info);
699 }
700 
701 static void bpf_program__exit(struct bpf_program *prog)
702 {
703 	if (!prog)
704 		return;
705 
706 	bpf_program__unload(prog);
707 	zfree(&prog->name);
708 	zfree(&prog->sec_name);
709 	zfree(&prog->insns);
710 	zfree(&prog->reloc_desc);
711 
712 	prog->nr_reloc = 0;
713 	prog->insns_cnt = 0;
714 	prog->sec_idx = -1;
715 }
716 
717 static bool insn_is_subprog_call(const struct bpf_insn *insn)
718 {
719 	return BPF_CLASS(insn->code) == BPF_JMP &&
720 	       BPF_OP(insn->code) == BPF_CALL &&
721 	       BPF_SRC(insn->code) == BPF_K &&
722 	       insn->src_reg == BPF_PSEUDO_CALL &&
723 	       insn->dst_reg == 0 &&
724 	       insn->off == 0;
725 }
726 
727 static bool is_call_insn(const struct bpf_insn *insn)
728 {
729 	return insn->code == (BPF_JMP | BPF_CALL);
730 }
731 
732 static bool insn_is_pseudo_func(struct bpf_insn *insn)
733 {
734 	return is_ldimm64_insn(insn) && insn->src_reg == BPF_PSEUDO_FUNC;
735 }
736 
737 static int
738 bpf_object__init_prog(struct bpf_object *obj, struct bpf_program *prog,
739 		      const char *name, size_t sec_idx, const char *sec_name,
740 		      size_t sec_off, void *insn_data, size_t insn_data_sz)
741 {
742 	if (insn_data_sz == 0 || insn_data_sz % BPF_INSN_SZ || sec_off % BPF_INSN_SZ) {
743 		pr_warn("sec '%s': corrupted program '%s', offset %zu, size %zu\n",
744 			sec_name, name, sec_off, insn_data_sz);
745 		return -EINVAL;
746 	}
747 
748 	memset(prog, 0, sizeof(*prog));
749 	prog->obj = obj;
750 
751 	prog->sec_idx = sec_idx;
752 	prog->sec_insn_off = sec_off / BPF_INSN_SZ;
753 	prog->sec_insn_cnt = insn_data_sz / BPF_INSN_SZ;
754 	/* insns_cnt can later be increased by appending used subprograms */
755 	prog->insns_cnt = prog->sec_insn_cnt;
756 
757 	prog->type = BPF_PROG_TYPE_UNSPEC;
758 	prog->fd = -1;
759 
760 	/* libbpf's convention for SEC("?abc...") is that it's just like
761 	 * SEC("abc...") but the corresponding bpf_program starts out with
762 	 * autoload set to false.
763 	 */
764 	if (sec_name[0] == '?') {
765 		prog->autoload = false;
766 		/* from now on forget there was ? in section name */
767 		sec_name++;
768 	} else {
769 		prog->autoload = true;
770 	}
771 
772 	prog->autoattach = true;
773 
774 	/* inherit object's log_level */
775 	prog->log_level = obj->log_level;
776 
777 	prog->sec_name = strdup(sec_name);
778 	if (!prog->sec_name)
779 		goto errout;
780 
781 	prog->name = strdup(name);
782 	if (!prog->name)
783 		goto errout;
784 
785 	prog->insns = malloc(insn_data_sz);
786 	if (!prog->insns)
787 		goto errout;
788 	memcpy(prog->insns, insn_data, insn_data_sz);
789 
790 	return 0;
791 errout:
792 	pr_warn("sec '%s': failed to allocate memory for prog '%s'\n", sec_name, name);
793 	bpf_program__exit(prog);
794 	return -ENOMEM;
795 }
796 
797 static int
798 bpf_object__add_programs(struct bpf_object *obj, Elf_Data *sec_data,
799 			 const char *sec_name, int sec_idx)
800 {
801 	Elf_Data *symbols = obj->efile.symbols;
802 	struct bpf_program *prog, *progs;
803 	void *data = sec_data->d_buf;
804 	size_t sec_sz = sec_data->d_size, sec_off, prog_sz, nr_syms;
805 	int nr_progs, err, i;
806 	const char *name;
807 	Elf64_Sym *sym;
808 
809 	progs = obj->programs;
810 	nr_progs = obj->nr_programs;
811 	nr_syms = symbols->d_size / sizeof(Elf64_Sym);
812 
813 	for (i = 0; i < nr_syms; i++) {
814 		sym = elf_sym_by_idx(obj, i);
815 
816 		if (sym->st_shndx != sec_idx)
817 			continue;
818 		if (ELF64_ST_TYPE(sym->st_info) != STT_FUNC)
819 			continue;
820 
821 		prog_sz = sym->st_size;
822 		sec_off = sym->st_value;
823 
824 		name = elf_sym_str(obj, sym->st_name);
825 		if (!name) {
826 			pr_warn("sec '%s': failed to get symbol name for offset %zu\n",
827 				sec_name, sec_off);
828 			return -LIBBPF_ERRNO__FORMAT;
829 		}
830 
831 		if (sec_off + prog_sz > sec_sz) {
832 			pr_warn("sec '%s': program at offset %zu crosses section boundary\n",
833 				sec_name, sec_off);
834 			return -LIBBPF_ERRNO__FORMAT;
835 		}
836 
837 		if (sec_idx != obj->efile.text_shndx && ELF64_ST_BIND(sym->st_info) == STB_LOCAL) {
838 			pr_warn("sec '%s': program '%s' is static and not supported\n", sec_name, name);
839 			return -ENOTSUP;
840 		}
841 
842 		pr_debug("sec '%s': found program '%s' at insn offset %zu (%zu bytes), code size %zu insns (%zu bytes)\n",
843 			 sec_name, name, sec_off / BPF_INSN_SZ, sec_off, prog_sz / BPF_INSN_SZ, prog_sz);
844 
845 		progs = libbpf_reallocarray(progs, nr_progs + 1, sizeof(*progs));
846 		if (!progs) {
847 			/*
848 			 * In this case the original obj->programs
849 			 * is still valid, so don't need special treat for
850 			 * bpf_close_object().
851 			 */
852 			pr_warn("sec '%s': failed to alloc memory for new program '%s'\n",
853 				sec_name, name);
854 			return -ENOMEM;
855 		}
856 		obj->programs = progs;
857 
858 		prog = &progs[nr_progs];
859 
860 		err = bpf_object__init_prog(obj, prog, name, sec_idx, sec_name,
861 					    sec_off, data + sec_off, prog_sz);
862 		if (err)
863 			return err;
864 
865 		/* if function is a global/weak symbol, but has restricted
866 		 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF FUNC
867 		 * as static to enable more permissive BPF verification mode
868 		 * with more outside context available to BPF verifier
869 		 */
870 		if (ELF64_ST_BIND(sym->st_info) != STB_LOCAL
871 		    && (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
872 			|| ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL))
873 			prog->mark_btf_static = true;
874 
875 		nr_progs++;
876 		obj->nr_programs = nr_progs;
877 	}
878 
879 	return 0;
880 }
881 
882 static const struct btf_member *
883 find_member_by_offset(const struct btf_type *t, __u32 bit_offset)
884 {
885 	struct btf_member *m;
886 	int i;
887 
888 	for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
889 		if (btf_member_bit_offset(t, i) == bit_offset)
890 			return m;
891 	}
892 
893 	return NULL;
894 }
895 
896 static const struct btf_member *
897 find_member_by_name(const struct btf *btf, const struct btf_type *t,
898 		    const char *name)
899 {
900 	struct btf_member *m;
901 	int i;
902 
903 	for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
904 		if (!strcmp(btf__name_by_offset(btf, m->name_off), name))
905 			return m;
906 	}
907 
908 	return NULL;
909 }
910 
911 #define STRUCT_OPS_VALUE_PREFIX "bpf_struct_ops_"
912 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
913 				   const char *name, __u32 kind);
914 
915 static int
916 find_struct_ops_kern_types(const struct btf *btf, const char *tname,
917 			   const struct btf_type **type, __u32 *type_id,
918 			   const struct btf_type **vtype, __u32 *vtype_id,
919 			   const struct btf_member **data_member)
920 {
921 	const struct btf_type *kern_type, *kern_vtype;
922 	const struct btf_member *kern_data_member;
923 	__s32 kern_vtype_id, kern_type_id;
924 	__u32 i;
925 
926 	kern_type_id = btf__find_by_name_kind(btf, tname, BTF_KIND_STRUCT);
927 	if (kern_type_id < 0) {
928 		pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n",
929 			tname);
930 		return kern_type_id;
931 	}
932 	kern_type = btf__type_by_id(btf, kern_type_id);
933 
934 	/* Find the corresponding "map_value" type that will be used
935 	 * in map_update(BPF_MAP_TYPE_STRUCT_OPS).  For example,
936 	 * find "struct bpf_struct_ops_tcp_congestion_ops" from the
937 	 * btf_vmlinux.
938 	 */
939 	kern_vtype_id = find_btf_by_prefix_kind(btf, STRUCT_OPS_VALUE_PREFIX,
940 						tname, BTF_KIND_STRUCT);
941 	if (kern_vtype_id < 0) {
942 		pr_warn("struct_ops init_kern: struct %s%s is not found in kernel BTF\n",
943 			STRUCT_OPS_VALUE_PREFIX, tname);
944 		return kern_vtype_id;
945 	}
946 	kern_vtype = btf__type_by_id(btf, kern_vtype_id);
947 
948 	/* Find "struct tcp_congestion_ops" from
949 	 * struct bpf_struct_ops_tcp_congestion_ops {
950 	 *	[ ... ]
951 	 *	struct tcp_congestion_ops data;
952 	 * }
953 	 */
954 	kern_data_member = btf_members(kern_vtype);
955 	for (i = 0; i < btf_vlen(kern_vtype); i++, kern_data_member++) {
956 		if (kern_data_member->type == kern_type_id)
957 			break;
958 	}
959 	if (i == btf_vlen(kern_vtype)) {
960 		pr_warn("struct_ops init_kern: struct %s data is not found in struct %s%s\n",
961 			tname, STRUCT_OPS_VALUE_PREFIX, tname);
962 		return -EINVAL;
963 	}
964 
965 	*type = kern_type;
966 	*type_id = kern_type_id;
967 	*vtype = kern_vtype;
968 	*vtype_id = kern_vtype_id;
969 	*data_member = kern_data_member;
970 
971 	return 0;
972 }
973 
974 static bool bpf_map__is_struct_ops(const struct bpf_map *map)
975 {
976 	return map->def.type == BPF_MAP_TYPE_STRUCT_OPS;
977 }
978 
979 /* Init the map's fields that depend on kern_btf */
980 static int bpf_map__init_kern_struct_ops(struct bpf_map *map,
981 					 const struct btf *btf,
982 					 const struct btf *kern_btf)
983 {
984 	const struct btf_member *member, *kern_member, *kern_data_member;
985 	const struct btf_type *type, *kern_type, *kern_vtype;
986 	__u32 i, kern_type_id, kern_vtype_id, kern_data_off;
987 	struct bpf_struct_ops *st_ops;
988 	void *data, *kern_data;
989 	const char *tname;
990 	int err;
991 
992 	st_ops = map->st_ops;
993 	type = st_ops->type;
994 	tname = st_ops->tname;
995 	err = find_struct_ops_kern_types(kern_btf, tname,
996 					 &kern_type, &kern_type_id,
997 					 &kern_vtype, &kern_vtype_id,
998 					 &kern_data_member);
999 	if (err)
1000 		return err;
1001 
1002 	pr_debug("struct_ops init_kern %s: type_id:%u kern_type_id:%u kern_vtype_id:%u\n",
1003 		 map->name, st_ops->type_id, kern_type_id, kern_vtype_id);
1004 
1005 	map->def.value_size = kern_vtype->size;
1006 	map->btf_vmlinux_value_type_id = kern_vtype_id;
1007 
1008 	st_ops->kern_vdata = calloc(1, kern_vtype->size);
1009 	if (!st_ops->kern_vdata)
1010 		return -ENOMEM;
1011 
1012 	data = st_ops->data;
1013 	kern_data_off = kern_data_member->offset / 8;
1014 	kern_data = st_ops->kern_vdata + kern_data_off;
1015 
1016 	member = btf_members(type);
1017 	for (i = 0; i < btf_vlen(type); i++, member++) {
1018 		const struct btf_type *mtype, *kern_mtype;
1019 		__u32 mtype_id, kern_mtype_id;
1020 		void *mdata, *kern_mdata;
1021 		__s64 msize, kern_msize;
1022 		__u32 moff, kern_moff;
1023 		__u32 kern_member_idx;
1024 		const char *mname;
1025 
1026 		mname = btf__name_by_offset(btf, member->name_off);
1027 		kern_member = find_member_by_name(kern_btf, kern_type, mname);
1028 		if (!kern_member) {
1029 			pr_warn("struct_ops init_kern %s: Cannot find member %s in kernel BTF\n",
1030 				map->name, mname);
1031 			return -ENOTSUP;
1032 		}
1033 
1034 		kern_member_idx = kern_member - btf_members(kern_type);
1035 		if (btf_member_bitfield_size(type, i) ||
1036 		    btf_member_bitfield_size(kern_type, kern_member_idx)) {
1037 			pr_warn("struct_ops init_kern %s: bitfield %s is not supported\n",
1038 				map->name, mname);
1039 			return -ENOTSUP;
1040 		}
1041 
1042 		moff = member->offset / 8;
1043 		kern_moff = kern_member->offset / 8;
1044 
1045 		mdata = data + moff;
1046 		kern_mdata = kern_data + kern_moff;
1047 
1048 		mtype = skip_mods_and_typedefs(btf, member->type, &mtype_id);
1049 		kern_mtype = skip_mods_and_typedefs(kern_btf, kern_member->type,
1050 						    &kern_mtype_id);
1051 		if (BTF_INFO_KIND(mtype->info) !=
1052 		    BTF_INFO_KIND(kern_mtype->info)) {
1053 			pr_warn("struct_ops init_kern %s: Unmatched member type %s %u != %u(kernel)\n",
1054 				map->name, mname, BTF_INFO_KIND(mtype->info),
1055 				BTF_INFO_KIND(kern_mtype->info));
1056 			return -ENOTSUP;
1057 		}
1058 
1059 		if (btf_is_ptr(mtype)) {
1060 			struct bpf_program *prog;
1061 
1062 			prog = st_ops->progs[i];
1063 			if (!prog)
1064 				continue;
1065 
1066 			kern_mtype = skip_mods_and_typedefs(kern_btf,
1067 							    kern_mtype->type,
1068 							    &kern_mtype_id);
1069 
1070 			/* mtype->type must be a func_proto which was
1071 			 * guaranteed in bpf_object__collect_st_ops_relos(),
1072 			 * so only check kern_mtype for func_proto here.
1073 			 */
1074 			if (!btf_is_func_proto(kern_mtype)) {
1075 				pr_warn("struct_ops init_kern %s: kernel member %s is not a func ptr\n",
1076 					map->name, mname);
1077 				return -ENOTSUP;
1078 			}
1079 
1080 			prog->attach_btf_id = kern_type_id;
1081 			prog->expected_attach_type = kern_member_idx;
1082 
1083 			st_ops->kern_func_off[i] = kern_data_off + kern_moff;
1084 
1085 			pr_debug("struct_ops init_kern %s: func ptr %s is set to prog %s from data(+%u) to kern_data(+%u)\n",
1086 				 map->name, mname, prog->name, moff,
1087 				 kern_moff);
1088 
1089 			continue;
1090 		}
1091 
1092 		msize = btf__resolve_size(btf, mtype_id);
1093 		kern_msize = btf__resolve_size(kern_btf, kern_mtype_id);
1094 		if (msize < 0 || kern_msize < 0 || msize != kern_msize) {
1095 			pr_warn("struct_ops init_kern %s: Error in size of member %s: %zd != %zd(kernel)\n",
1096 				map->name, mname, (ssize_t)msize,
1097 				(ssize_t)kern_msize);
1098 			return -ENOTSUP;
1099 		}
1100 
1101 		pr_debug("struct_ops init_kern %s: copy %s %u bytes from data(+%u) to kern_data(+%u)\n",
1102 			 map->name, mname, (unsigned int)msize,
1103 			 moff, kern_moff);
1104 		memcpy(kern_mdata, mdata, msize);
1105 	}
1106 
1107 	return 0;
1108 }
1109 
1110 static int bpf_object__init_kern_struct_ops_maps(struct bpf_object *obj)
1111 {
1112 	struct bpf_map *map;
1113 	size_t i;
1114 	int err;
1115 
1116 	for (i = 0; i < obj->nr_maps; i++) {
1117 		map = &obj->maps[i];
1118 
1119 		if (!bpf_map__is_struct_ops(map))
1120 			continue;
1121 
1122 		err = bpf_map__init_kern_struct_ops(map, obj->btf,
1123 						    obj->btf_vmlinux);
1124 		if (err)
1125 			return err;
1126 	}
1127 
1128 	return 0;
1129 }
1130 
1131 static int init_struct_ops_maps(struct bpf_object *obj, const char *sec_name,
1132 				int shndx, Elf_Data *data, __u32 map_flags)
1133 {
1134 	const struct btf_type *type, *datasec;
1135 	const struct btf_var_secinfo *vsi;
1136 	struct bpf_struct_ops *st_ops;
1137 	const char *tname, *var_name;
1138 	__s32 type_id, datasec_id;
1139 	const struct btf *btf;
1140 	struct bpf_map *map;
1141 	__u32 i;
1142 
1143 	if (shndx == -1)
1144 		return 0;
1145 
1146 	btf = obj->btf;
1147 	datasec_id = btf__find_by_name_kind(btf, sec_name,
1148 					    BTF_KIND_DATASEC);
1149 	if (datasec_id < 0) {
1150 		pr_warn("struct_ops init: DATASEC %s not found\n",
1151 			sec_name);
1152 		return -EINVAL;
1153 	}
1154 
1155 	datasec = btf__type_by_id(btf, datasec_id);
1156 	vsi = btf_var_secinfos(datasec);
1157 	for (i = 0; i < btf_vlen(datasec); i++, vsi++) {
1158 		type = btf__type_by_id(obj->btf, vsi->type);
1159 		var_name = btf__name_by_offset(obj->btf, type->name_off);
1160 
1161 		type_id = btf__resolve_type(obj->btf, vsi->type);
1162 		if (type_id < 0) {
1163 			pr_warn("struct_ops init: Cannot resolve var type_id %u in DATASEC %s\n",
1164 				vsi->type, sec_name);
1165 			return -EINVAL;
1166 		}
1167 
1168 		type = btf__type_by_id(obj->btf, type_id);
1169 		tname = btf__name_by_offset(obj->btf, type->name_off);
1170 		if (!tname[0]) {
1171 			pr_warn("struct_ops init: anonymous type is not supported\n");
1172 			return -ENOTSUP;
1173 		}
1174 		if (!btf_is_struct(type)) {
1175 			pr_warn("struct_ops init: %s is not a struct\n", tname);
1176 			return -EINVAL;
1177 		}
1178 
1179 		map = bpf_object__add_map(obj);
1180 		if (IS_ERR(map))
1181 			return PTR_ERR(map);
1182 
1183 		map->sec_idx = shndx;
1184 		map->sec_offset = vsi->offset;
1185 		map->name = strdup(var_name);
1186 		if (!map->name)
1187 			return -ENOMEM;
1188 
1189 		map->def.type = BPF_MAP_TYPE_STRUCT_OPS;
1190 		map->def.key_size = sizeof(int);
1191 		map->def.value_size = type->size;
1192 		map->def.max_entries = 1;
1193 		map->def.map_flags = map_flags;
1194 
1195 		map->st_ops = calloc(1, sizeof(*map->st_ops));
1196 		if (!map->st_ops)
1197 			return -ENOMEM;
1198 		st_ops = map->st_ops;
1199 		st_ops->data = malloc(type->size);
1200 		st_ops->progs = calloc(btf_vlen(type), sizeof(*st_ops->progs));
1201 		st_ops->kern_func_off = malloc(btf_vlen(type) *
1202 					       sizeof(*st_ops->kern_func_off));
1203 		if (!st_ops->data || !st_ops->progs || !st_ops->kern_func_off)
1204 			return -ENOMEM;
1205 
1206 		if (vsi->offset + type->size > data->d_size) {
1207 			pr_warn("struct_ops init: var %s is beyond the end of DATASEC %s\n",
1208 				var_name, sec_name);
1209 			return -EINVAL;
1210 		}
1211 
1212 		memcpy(st_ops->data,
1213 		       data->d_buf + vsi->offset,
1214 		       type->size);
1215 		st_ops->tname = tname;
1216 		st_ops->type = type;
1217 		st_ops->type_id = type_id;
1218 
1219 		pr_debug("struct_ops init: struct %s(type_id=%u) %s found at offset %u\n",
1220 			 tname, type_id, var_name, vsi->offset);
1221 	}
1222 
1223 	return 0;
1224 }
1225 
1226 static int bpf_object_init_struct_ops(struct bpf_object *obj)
1227 {
1228 	int err;
1229 
1230 	err = init_struct_ops_maps(obj, STRUCT_OPS_SEC, obj->efile.st_ops_shndx,
1231 				   obj->efile.st_ops_data, 0);
1232 	err = err ?: init_struct_ops_maps(obj, STRUCT_OPS_LINK_SEC,
1233 					  obj->efile.st_ops_link_shndx,
1234 					  obj->efile.st_ops_link_data,
1235 					  BPF_F_LINK);
1236 	return err;
1237 }
1238 
1239 static struct bpf_object *bpf_object__new(const char *path,
1240 					  const void *obj_buf,
1241 					  size_t obj_buf_sz,
1242 					  const char *obj_name)
1243 {
1244 	struct bpf_object *obj;
1245 	char *end;
1246 
1247 	obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
1248 	if (!obj) {
1249 		pr_warn("alloc memory failed for %s\n", path);
1250 		return ERR_PTR(-ENOMEM);
1251 	}
1252 
1253 	strcpy(obj->path, path);
1254 	if (obj_name) {
1255 		libbpf_strlcpy(obj->name, obj_name, sizeof(obj->name));
1256 	} else {
1257 		/* Using basename() GNU version which doesn't modify arg. */
1258 		libbpf_strlcpy(obj->name, basename((void *)path), sizeof(obj->name));
1259 		end = strchr(obj->name, '.');
1260 		if (end)
1261 			*end = 0;
1262 	}
1263 
1264 	obj->efile.fd = -1;
1265 	/*
1266 	 * Caller of this function should also call
1267 	 * bpf_object__elf_finish() after data collection to return
1268 	 * obj_buf to user. If not, we should duplicate the buffer to
1269 	 * avoid user freeing them before elf finish.
1270 	 */
1271 	obj->efile.obj_buf = obj_buf;
1272 	obj->efile.obj_buf_sz = obj_buf_sz;
1273 	obj->efile.btf_maps_shndx = -1;
1274 	obj->efile.st_ops_shndx = -1;
1275 	obj->efile.st_ops_link_shndx = -1;
1276 	obj->kconfig_map_idx = -1;
1277 
1278 	obj->kern_version = get_kernel_version();
1279 	obj->loaded = false;
1280 
1281 	return obj;
1282 }
1283 
1284 static void bpf_object__elf_finish(struct bpf_object *obj)
1285 {
1286 	if (!obj->efile.elf)
1287 		return;
1288 
1289 	elf_end(obj->efile.elf);
1290 	obj->efile.elf = NULL;
1291 	obj->efile.symbols = NULL;
1292 	obj->efile.st_ops_data = NULL;
1293 	obj->efile.st_ops_link_data = NULL;
1294 
1295 	zfree(&obj->efile.secs);
1296 	obj->efile.sec_cnt = 0;
1297 	zclose(obj->efile.fd);
1298 	obj->efile.obj_buf = NULL;
1299 	obj->efile.obj_buf_sz = 0;
1300 }
1301 
1302 static int bpf_object__elf_init(struct bpf_object *obj)
1303 {
1304 	Elf64_Ehdr *ehdr;
1305 	int err = 0;
1306 	Elf *elf;
1307 
1308 	if (obj->efile.elf) {
1309 		pr_warn("elf: init internal error\n");
1310 		return -LIBBPF_ERRNO__LIBELF;
1311 	}
1312 
1313 	if (obj->efile.obj_buf_sz > 0) {
1314 		/* obj_buf should have been validated by bpf_object__open_mem(). */
1315 		elf = elf_memory((char *)obj->efile.obj_buf, obj->efile.obj_buf_sz);
1316 	} else {
1317 		obj->efile.fd = open(obj->path, O_RDONLY | O_CLOEXEC);
1318 		if (obj->efile.fd < 0) {
1319 			char errmsg[STRERR_BUFSIZE], *cp;
1320 
1321 			err = -errno;
1322 			cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
1323 			pr_warn("elf: failed to open %s: %s\n", obj->path, cp);
1324 			return err;
1325 		}
1326 
1327 		elf = elf_begin(obj->efile.fd, ELF_C_READ_MMAP, NULL);
1328 	}
1329 
1330 	if (!elf) {
1331 		pr_warn("elf: failed to open %s as ELF file: %s\n", obj->path, elf_errmsg(-1));
1332 		err = -LIBBPF_ERRNO__LIBELF;
1333 		goto errout;
1334 	}
1335 
1336 	obj->efile.elf = elf;
1337 
1338 	if (elf_kind(elf) != ELF_K_ELF) {
1339 		err = -LIBBPF_ERRNO__FORMAT;
1340 		pr_warn("elf: '%s' is not a proper ELF object\n", obj->path);
1341 		goto errout;
1342 	}
1343 
1344 	if (gelf_getclass(elf) != ELFCLASS64) {
1345 		err = -LIBBPF_ERRNO__FORMAT;
1346 		pr_warn("elf: '%s' is not a 64-bit ELF object\n", obj->path);
1347 		goto errout;
1348 	}
1349 
1350 	obj->efile.ehdr = ehdr = elf64_getehdr(elf);
1351 	if (!obj->efile.ehdr) {
1352 		pr_warn("elf: failed to get ELF header from %s: %s\n", obj->path, elf_errmsg(-1));
1353 		err = -LIBBPF_ERRNO__FORMAT;
1354 		goto errout;
1355 	}
1356 
1357 	if (elf_getshdrstrndx(elf, &obj->efile.shstrndx)) {
1358 		pr_warn("elf: failed to get section names section index for %s: %s\n",
1359 			obj->path, elf_errmsg(-1));
1360 		err = -LIBBPF_ERRNO__FORMAT;
1361 		goto errout;
1362 	}
1363 
1364 	/* ELF is corrupted/truncated, avoid calling elf_strptr. */
1365 	if (!elf_rawdata(elf_getscn(elf, obj->efile.shstrndx), NULL)) {
1366 		pr_warn("elf: failed to get section names strings from %s: %s\n",
1367 			obj->path, elf_errmsg(-1));
1368 		err = -LIBBPF_ERRNO__FORMAT;
1369 		goto errout;
1370 	}
1371 
1372 	/* Old LLVM set e_machine to EM_NONE */
1373 	if (ehdr->e_type != ET_REL || (ehdr->e_machine && ehdr->e_machine != EM_BPF)) {
1374 		pr_warn("elf: %s is not a valid eBPF object file\n", obj->path);
1375 		err = -LIBBPF_ERRNO__FORMAT;
1376 		goto errout;
1377 	}
1378 
1379 	return 0;
1380 errout:
1381 	bpf_object__elf_finish(obj);
1382 	return err;
1383 }
1384 
1385 static int bpf_object__check_endianness(struct bpf_object *obj)
1386 {
1387 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1388 	if (obj->efile.ehdr->e_ident[EI_DATA] == ELFDATA2LSB)
1389 		return 0;
1390 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
1391 	if (obj->efile.ehdr->e_ident[EI_DATA] == ELFDATA2MSB)
1392 		return 0;
1393 #else
1394 # error "Unrecognized __BYTE_ORDER__"
1395 #endif
1396 	pr_warn("elf: endianness mismatch in %s.\n", obj->path);
1397 	return -LIBBPF_ERRNO__ENDIAN;
1398 }
1399 
1400 static int
1401 bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
1402 {
1403 	if (!data) {
1404 		pr_warn("invalid license section in %s\n", obj->path);
1405 		return -LIBBPF_ERRNO__FORMAT;
1406 	}
1407 	/* libbpf_strlcpy() only copies first N - 1 bytes, so size + 1 won't
1408 	 * go over allowed ELF data section buffer
1409 	 */
1410 	libbpf_strlcpy(obj->license, data, min(size + 1, sizeof(obj->license)));
1411 	pr_debug("license of %s is %s\n", obj->path, obj->license);
1412 	return 0;
1413 }
1414 
1415 static int
1416 bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
1417 {
1418 	__u32 kver;
1419 
1420 	if (!data || size != sizeof(kver)) {
1421 		pr_warn("invalid kver section in %s\n", obj->path);
1422 		return -LIBBPF_ERRNO__FORMAT;
1423 	}
1424 	memcpy(&kver, data, sizeof(kver));
1425 	obj->kern_version = kver;
1426 	pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
1427 	return 0;
1428 }
1429 
1430 static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
1431 {
1432 	if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
1433 	    type == BPF_MAP_TYPE_HASH_OF_MAPS)
1434 		return true;
1435 	return false;
1436 }
1437 
1438 static int find_elf_sec_sz(const struct bpf_object *obj, const char *name, __u32 *size)
1439 {
1440 	Elf_Data *data;
1441 	Elf_Scn *scn;
1442 
1443 	if (!name)
1444 		return -EINVAL;
1445 
1446 	scn = elf_sec_by_name(obj, name);
1447 	data = elf_sec_data(obj, scn);
1448 	if (data) {
1449 		*size = data->d_size;
1450 		return 0; /* found it */
1451 	}
1452 
1453 	return -ENOENT;
1454 }
1455 
1456 static Elf64_Sym *find_elf_var_sym(const struct bpf_object *obj, const char *name)
1457 {
1458 	Elf_Data *symbols = obj->efile.symbols;
1459 	const char *sname;
1460 	size_t si;
1461 
1462 	for (si = 0; si < symbols->d_size / sizeof(Elf64_Sym); si++) {
1463 		Elf64_Sym *sym = elf_sym_by_idx(obj, si);
1464 
1465 		if (ELF64_ST_TYPE(sym->st_info) != STT_OBJECT)
1466 			continue;
1467 
1468 		if (ELF64_ST_BIND(sym->st_info) != STB_GLOBAL &&
1469 		    ELF64_ST_BIND(sym->st_info) != STB_WEAK)
1470 			continue;
1471 
1472 		sname = elf_sym_str(obj, sym->st_name);
1473 		if (!sname) {
1474 			pr_warn("failed to get sym name string for var %s\n", name);
1475 			return ERR_PTR(-EIO);
1476 		}
1477 		if (strcmp(name, sname) == 0)
1478 			return sym;
1479 	}
1480 
1481 	return ERR_PTR(-ENOENT);
1482 }
1483 
1484 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
1485 {
1486 	struct bpf_map *map;
1487 	int err;
1488 
1489 	err = libbpf_ensure_mem((void **)&obj->maps, &obj->maps_cap,
1490 				sizeof(*obj->maps), obj->nr_maps + 1);
1491 	if (err)
1492 		return ERR_PTR(err);
1493 
1494 	map = &obj->maps[obj->nr_maps++];
1495 	map->obj = obj;
1496 	map->fd = -1;
1497 	map->inner_map_fd = -1;
1498 	map->autocreate = true;
1499 
1500 	return map;
1501 }
1502 
1503 static size_t bpf_map_mmap_sz(unsigned int value_sz, unsigned int max_entries)
1504 {
1505 	const long page_sz = sysconf(_SC_PAGE_SIZE);
1506 	size_t map_sz;
1507 
1508 	map_sz = (size_t)roundup(value_sz, 8) * max_entries;
1509 	map_sz = roundup(map_sz, page_sz);
1510 	return map_sz;
1511 }
1512 
1513 static int bpf_map_mmap_resize(struct bpf_map *map, size_t old_sz, size_t new_sz)
1514 {
1515 	void *mmaped;
1516 
1517 	if (!map->mmaped)
1518 		return -EINVAL;
1519 
1520 	if (old_sz == new_sz)
1521 		return 0;
1522 
1523 	mmaped = mmap(NULL, new_sz, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1524 	if (mmaped == MAP_FAILED)
1525 		return -errno;
1526 
1527 	memcpy(mmaped, map->mmaped, min(old_sz, new_sz));
1528 	munmap(map->mmaped, old_sz);
1529 	map->mmaped = mmaped;
1530 	return 0;
1531 }
1532 
1533 static char *internal_map_name(struct bpf_object *obj, const char *real_name)
1534 {
1535 	char map_name[BPF_OBJ_NAME_LEN], *p;
1536 	int pfx_len, sfx_len = max((size_t)7, strlen(real_name));
1537 
1538 	/* This is one of the more confusing parts of libbpf for various
1539 	 * reasons, some of which are historical. The original idea for naming
1540 	 * internal names was to include as much of BPF object name prefix as
1541 	 * possible, so that it can be distinguished from similar internal
1542 	 * maps of a different BPF object.
1543 	 * As an example, let's say we have bpf_object named 'my_object_name'
1544 	 * and internal map corresponding to '.rodata' ELF section. The final
1545 	 * map name advertised to user and to the kernel will be
1546 	 * 'my_objec.rodata', taking first 8 characters of object name and
1547 	 * entire 7 characters of '.rodata'.
1548 	 * Somewhat confusingly, if internal map ELF section name is shorter
1549 	 * than 7 characters, e.g., '.bss', we still reserve 7 characters
1550 	 * for the suffix, even though we only have 4 actual characters, and
1551 	 * resulting map will be called 'my_objec.bss', not even using all 15
1552 	 * characters allowed by the kernel. Oh well, at least the truncated
1553 	 * object name is somewhat consistent in this case. But if the map
1554 	 * name is '.kconfig', we'll still have entirety of '.kconfig' added
1555 	 * (8 chars) and thus will be left with only first 7 characters of the
1556 	 * object name ('my_obje'). Happy guessing, user, that the final map
1557 	 * name will be "my_obje.kconfig".
1558 	 * Now, with libbpf starting to support arbitrarily named .rodata.*
1559 	 * and .data.* data sections, it's possible that ELF section name is
1560 	 * longer than allowed 15 chars, so we now need to be careful to take
1561 	 * only up to 15 first characters of ELF name, taking no BPF object
1562 	 * name characters at all. So '.rodata.abracadabra' will result in
1563 	 * '.rodata.abracad' kernel and user-visible name.
1564 	 * We need to keep this convoluted logic intact for .data, .bss and
1565 	 * .rodata maps, but for new custom .data.custom and .rodata.custom
1566 	 * maps we use their ELF names as is, not prepending bpf_object name
1567 	 * in front. We still need to truncate them to 15 characters for the
1568 	 * kernel. Full name can be recovered for such maps by using DATASEC
1569 	 * BTF type associated with such map's value type, though.
1570 	 */
1571 	if (sfx_len >= BPF_OBJ_NAME_LEN)
1572 		sfx_len = BPF_OBJ_NAME_LEN - 1;
1573 
1574 	/* if there are two or more dots in map name, it's a custom dot map */
1575 	if (strchr(real_name + 1, '.') != NULL)
1576 		pfx_len = 0;
1577 	else
1578 		pfx_len = min((size_t)BPF_OBJ_NAME_LEN - sfx_len - 1, strlen(obj->name));
1579 
1580 	snprintf(map_name, sizeof(map_name), "%.*s%.*s", pfx_len, obj->name,
1581 		 sfx_len, real_name);
1582 
1583 	/* sanitise map name to characters allowed by kernel */
1584 	for (p = map_name; *p && p < map_name + sizeof(map_name); p++)
1585 		if (!isalnum(*p) && *p != '_' && *p != '.')
1586 			*p = '_';
1587 
1588 	return strdup(map_name);
1589 }
1590 
1591 static int
1592 map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map);
1593 
1594 /* Internal BPF map is mmap()'able only if at least one of corresponding
1595  * DATASEC's VARs are to be exposed through BPF skeleton. I.e., it's a GLOBAL
1596  * variable and it's not marked as __hidden (which turns it into, effectively,
1597  * a STATIC variable).
1598  */
1599 static bool map_is_mmapable(struct bpf_object *obj, struct bpf_map *map)
1600 {
1601 	const struct btf_type *t, *vt;
1602 	struct btf_var_secinfo *vsi;
1603 	int i, n;
1604 
1605 	if (!map->btf_value_type_id)
1606 		return false;
1607 
1608 	t = btf__type_by_id(obj->btf, map->btf_value_type_id);
1609 	if (!btf_is_datasec(t))
1610 		return false;
1611 
1612 	vsi = btf_var_secinfos(t);
1613 	for (i = 0, n = btf_vlen(t); i < n; i++, vsi++) {
1614 		vt = btf__type_by_id(obj->btf, vsi->type);
1615 		if (!btf_is_var(vt))
1616 			continue;
1617 
1618 		if (btf_var(vt)->linkage != BTF_VAR_STATIC)
1619 			return true;
1620 	}
1621 
1622 	return false;
1623 }
1624 
1625 static int
1626 bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
1627 			      const char *real_name, int sec_idx, void *data, size_t data_sz)
1628 {
1629 	struct bpf_map_def *def;
1630 	struct bpf_map *map;
1631 	size_t mmap_sz;
1632 	int err;
1633 
1634 	map = bpf_object__add_map(obj);
1635 	if (IS_ERR(map))
1636 		return PTR_ERR(map);
1637 
1638 	map->libbpf_type = type;
1639 	map->sec_idx = sec_idx;
1640 	map->sec_offset = 0;
1641 	map->real_name = strdup(real_name);
1642 	map->name = internal_map_name(obj, real_name);
1643 	if (!map->real_name || !map->name) {
1644 		zfree(&map->real_name);
1645 		zfree(&map->name);
1646 		return -ENOMEM;
1647 	}
1648 
1649 	def = &map->def;
1650 	def->type = BPF_MAP_TYPE_ARRAY;
1651 	def->key_size = sizeof(int);
1652 	def->value_size = data_sz;
1653 	def->max_entries = 1;
1654 	def->map_flags = type == LIBBPF_MAP_RODATA || type == LIBBPF_MAP_KCONFIG
1655 			 ? BPF_F_RDONLY_PROG : 0;
1656 
1657 	/* failures are fine because of maps like .rodata.str1.1 */
1658 	(void) map_fill_btf_type_info(obj, map);
1659 
1660 	if (map_is_mmapable(obj, map))
1661 		def->map_flags |= BPF_F_MMAPABLE;
1662 
1663 	pr_debug("map '%s' (global data): at sec_idx %d, offset %zu, flags %x.\n",
1664 		 map->name, map->sec_idx, map->sec_offset, def->map_flags);
1665 
1666 	mmap_sz = bpf_map_mmap_sz(map->def.value_size, map->def.max_entries);
1667 	map->mmaped = mmap(NULL, mmap_sz, PROT_READ | PROT_WRITE,
1668 			   MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1669 	if (map->mmaped == MAP_FAILED) {
1670 		err = -errno;
1671 		map->mmaped = NULL;
1672 		pr_warn("failed to alloc map '%s' content buffer: %d\n",
1673 			map->name, err);
1674 		zfree(&map->real_name);
1675 		zfree(&map->name);
1676 		return err;
1677 	}
1678 
1679 	if (data)
1680 		memcpy(map->mmaped, data, data_sz);
1681 
1682 	pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
1683 	return 0;
1684 }
1685 
1686 static int bpf_object__init_global_data_maps(struct bpf_object *obj)
1687 {
1688 	struct elf_sec_desc *sec_desc;
1689 	const char *sec_name;
1690 	int err = 0, sec_idx;
1691 
1692 	/*
1693 	 * Populate obj->maps with libbpf internal maps.
1694 	 */
1695 	for (sec_idx = 1; sec_idx < obj->efile.sec_cnt; sec_idx++) {
1696 		sec_desc = &obj->efile.secs[sec_idx];
1697 
1698 		/* Skip recognized sections with size 0. */
1699 		if (!sec_desc->data || sec_desc->data->d_size == 0)
1700 			continue;
1701 
1702 		switch (sec_desc->sec_type) {
1703 		case SEC_DATA:
1704 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1705 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
1706 							    sec_name, sec_idx,
1707 							    sec_desc->data->d_buf,
1708 							    sec_desc->data->d_size);
1709 			break;
1710 		case SEC_RODATA:
1711 			obj->has_rodata = true;
1712 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1713 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
1714 							    sec_name, sec_idx,
1715 							    sec_desc->data->d_buf,
1716 							    sec_desc->data->d_size);
1717 			break;
1718 		case SEC_BSS:
1719 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1720 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
1721 							    sec_name, sec_idx,
1722 							    NULL,
1723 							    sec_desc->data->d_size);
1724 			break;
1725 		default:
1726 			/* skip */
1727 			break;
1728 		}
1729 		if (err)
1730 			return err;
1731 	}
1732 	return 0;
1733 }
1734 
1735 
1736 static struct extern_desc *find_extern_by_name(const struct bpf_object *obj,
1737 					       const void *name)
1738 {
1739 	int i;
1740 
1741 	for (i = 0; i < obj->nr_extern; i++) {
1742 		if (strcmp(obj->externs[i].name, name) == 0)
1743 			return &obj->externs[i];
1744 	}
1745 	return NULL;
1746 }
1747 
1748 static int set_kcfg_value_tri(struct extern_desc *ext, void *ext_val,
1749 			      char value)
1750 {
1751 	switch (ext->kcfg.type) {
1752 	case KCFG_BOOL:
1753 		if (value == 'm') {
1754 			pr_warn("extern (kcfg) '%s': value '%c' implies tristate or char type\n",
1755 				ext->name, value);
1756 			return -EINVAL;
1757 		}
1758 		*(bool *)ext_val = value == 'y' ? true : false;
1759 		break;
1760 	case KCFG_TRISTATE:
1761 		if (value == 'y')
1762 			*(enum libbpf_tristate *)ext_val = TRI_YES;
1763 		else if (value == 'm')
1764 			*(enum libbpf_tristate *)ext_val = TRI_MODULE;
1765 		else /* value == 'n' */
1766 			*(enum libbpf_tristate *)ext_val = TRI_NO;
1767 		break;
1768 	case KCFG_CHAR:
1769 		*(char *)ext_val = value;
1770 		break;
1771 	case KCFG_UNKNOWN:
1772 	case KCFG_INT:
1773 	case KCFG_CHAR_ARR:
1774 	default:
1775 		pr_warn("extern (kcfg) '%s': value '%c' implies bool, tristate, or char type\n",
1776 			ext->name, value);
1777 		return -EINVAL;
1778 	}
1779 	ext->is_set = true;
1780 	return 0;
1781 }
1782 
1783 static int set_kcfg_value_str(struct extern_desc *ext, char *ext_val,
1784 			      const char *value)
1785 {
1786 	size_t len;
1787 
1788 	if (ext->kcfg.type != KCFG_CHAR_ARR) {
1789 		pr_warn("extern (kcfg) '%s': value '%s' implies char array type\n",
1790 			ext->name, value);
1791 		return -EINVAL;
1792 	}
1793 
1794 	len = strlen(value);
1795 	if (value[len - 1] != '"') {
1796 		pr_warn("extern (kcfg) '%s': invalid string config '%s'\n",
1797 			ext->name, value);
1798 		return -EINVAL;
1799 	}
1800 
1801 	/* strip quotes */
1802 	len -= 2;
1803 	if (len >= ext->kcfg.sz) {
1804 		pr_warn("extern (kcfg) '%s': long string '%s' of (%zu bytes) truncated to %d bytes\n",
1805 			ext->name, value, len, ext->kcfg.sz - 1);
1806 		len = ext->kcfg.sz - 1;
1807 	}
1808 	memcpy(ext_val, value + 1, len);
1809 	ext_val[len] = '\0';
1810 	ext->is_set = true;
1811 	return 0;
1812 }
1813 
1814 static int parse_u64(const char *value, __u64 *res)
1815 {
1816 	char *value_end;
1817 	int err;
1818 
1819 	errno = 0;
1820 	*res = strtoull(value, &value_end, 0);
1821 	if (errno) {
1822 		err = -errno;
1823 		pr_warn("failed to parse '%s' as integer: %d\n", value, err);
1824 		return err;
1825 	}
1826 	if (*value_end) {
1827 		pr_warn("failed to parse '%s' as integer completely\n", value);
1828 		return -EINVAL;
1829 	}
1830 	return 0;
1831 }
1832 
1833 static bool is_kcfg_value_in_range(const struct extern_desc *ext, __u64 v)
1834 {
1835 	int bit_sz = ext->kcfg.sz * 8;
1836 
1837 	if (ext->kcfg.sz == 8)
1838 		return true;
1839 
1840 	/* Validate that value stored in u64 fits in integer of `ext->sz`
1841 	 * bytes size without any loss of information. If the target integer
1842 	 * is signed, we rely on the following limits of integer type of
1843 	 * Y bits and subsequent transformation:
1844 	 *
1845 	 *     -2^(Y-1) <= X           <= 2^(Y-1) - 1
1846 	 *            0 <= X + 2^(Y-1) <= 2^Y - 1
1847 	 *            0 <= X + 2^(Y-1) <  2^Y
1848 	 *
1849 	 *  For unsigned target integer, check that all the (64 - Y) bits are
1850 	 *  zero.
1851 	 */
1852 	if (ext->kcfg.is_signed)
1853 		return v + (1ULL << (bit_sz - 1)) < (1ULL << bit_sz);
1854 	else
1855 		return (v >> bit_sz) == 0;
1856 }
1857 
1858 static int set_kcfg_value_num(struct extern_desc *ext, void *ext_val,
1859 			      __u64 value)
1860 {
1861 	if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR &&
1862 	    ext->kcfg.type != KCFG_BOOL) {
1863 		pr_warn("extern (kcfg) '%s': value '%llu' implies integer, char, or boolean type\n",
1864 			ext->name, (unsigned long long)value);
1865 		return -EINVAL;
1866 	}
1867 	if (ext->kcfg.type == KCFG_BOOL && value > 1) {
1868 		pr_warn("extern (kcfg) '%s': value '%llu' isn't boolean compatible\n",
1869 			ext->name, (unsigned long long)value);
1870 		return -EINVAL;
1871 
1872 	}
1873 	if (!is_kcfg_value_in_range(ext, value)) {
1874 		pr_warn("extern (kcfg) '%s': value '%llu' doesn't fit in %d bytes\n",
1875 			ext->name, (unsigned long long)value, ext->kcfg.sz);
1876 		return -ERANGE;
1877 	}
1878 	switch (ext->kcfg.sz) {
1879 	case 1:
1880 		*(__u8 *)ext_val = value;
1881 		break;
1882 	case 2:
1883 		*(__u16 *)ext_val = value;
1884 		break;
1885 	case 4:
1886 		*(__u32 *)ext_val = value;
1887 		break;
1888 	case 8:
1889 		*(__u64 *)ext_val = value;
1890 		break;
1891 	default:
1892 		return -EINVAL;
1893 	}
1894 	ext->is_set = true;
1895 	return 0;
1896 }
1897 
1898 static int bpf_object__process_kconfig_line(struct bpf_object *obj,
1899 					    char *buf, void *data)
1900 {
1901 	struct extern_desc *ext;
1902 	char *sep, *value;
1903 	int len, err = 0;
1904 	void *ext_val;
1905 	__u64 num;
1906 
1907 	if (!str_has_pfx(buf, "CONFIG_"))
1908 		return 0;
1909 
1910 	sep = strchr(buf, '=');
1911 	if (!sep) {
1912 		pr_warn("failed to parse '%s': no separator\n", buf);
1913 		return -EINVAL;
1914 	}
1915 
1916 	/* Trim ending '\n' */
1917 	len = strlen(buf);
1918 	if (buf[len - 1] == '\n')
1919 		buf[len - 1] = '\0';
1920 	/* Split on '=' and ensure that a value is present. */
1921 	*sep = '\0';
1922 	if (!sep[1]) {
1923 		*sep = '=';
1924 		pr_warn("failed to parse '%s': no value\n", buf);
1925 		return -EINVAL;
1926 	}
1927 
1928 	ext = find_extern_by_name(obj, buf);
1929 	if (!ext || ext->is_set)
1930 		return 0;
1931 
1932 	ext_val = data + ext->kcfg.data_off;
1933 	value = sep + 1;
1934 
1935 	switch (*value) {
1936 	case 'y': case 'n': case 'm':
1937 		err = set_kcfg_value_tri(ext, ext_val, *value);
1938 		break;
1939 	case '"':
1940 		err = set_kcfg_value_str(ext, ext_val, value);
1941 		break;
1942 	default:
1943 		/* assume integer */
1944 		err = parse_u64(value, &num);
1945 		if (err) {
1946 			pr_warn("extern (kcfg) '%s': value '%s' isn't a valid integer\n", ext->name, value);
1947 			return err;
1948 		}
1949 		if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR) {
1950 			pr_warn("extern (kcfg) '%s': value '%s' implies integer type\n", ext->name, value);
1951 			return -EINVAL;
1952 		}
1953 		err = set_kcfg_value_num(ext, ext_val, num);
1954 		break;
1955 	}
1956 	if (err)
1957 		return err;
1958 	pr_debug("extern (kcfg) '%s': set to %s\n", ext->name, value);
1959 	return 0;
1960 }
1961 
1962 static int bpf_object__read_kconfig_file(struct bpf_object *obj, void *data)
1963 {
1964 	char buf[PATH_MAX];
1965 	struct utsname uts;
1966 	int len, err = 0;
1967 	gzFile file;
1968 
1969 	uname(&uts);
1970 	len = snprintf(buf, PATH_MAX, "/boot/config-%s", uts.release);
1971 	if (len < 0)
1972 		return -EINVAL;
1973 	else if (len >= PATH_MAX)
1974 		return -ENAMETOOLONG;
1975 
1976 	/* gzopen also accepts uncompressed files. */
1977 	file = gzopen(buf, "r");
1978 	if (!file)
1979 		file = gzopen("/proc/config.gz", "r");
1980 
1981 	if (!file) {
1982 		pr_warn("failed to open system Kconfig\n");
1983 		return -ENOENT;
1984 	}
1985 
1986 	while (gzgets(file, buf, sizeof(buf))) {
1987 		err = bpf_object__process_kconfig_line(obj, buf, data);
1988 		if (err) {
1989 			pr_warn("error parsing system Kconfig line '%s': %d\n",
1990 				buf, err);
1991 			goto out;
1992 		}
1993 	}
1994 
1995 out:
1996 	gzclose(file);
1997 	return err;
1998 }
1999 
2000 static int bpf_object__read_kconfig_mem(struct bpf_object *obj,
2001 					const char *config, void *data)
2002 {
2003 	char buf[PATH_MAX];
2004 	int err = 0;
2005 	FILE *file;
2006 
2007 	file = fmemopen((void *)config, strlen(config), "r");
2008 	if (!file) {
2009 		err = -errno;
2010 		pr_warn("failed to open in-memory Kconfig: %d\n", err);
2011 		return err;
2012 	}
2013 
2014 	while (fgets(buf, sizeof(buf), file)) {
2015 		err = bpf_object__process_kconfig_line(obj, buf, data);
2016 		if (err) {
2017 			pr_warn("error parsing in-memory Kconfig line '%s': %d\n",
2018 				buf, err);
2019 			break;
2020 		}
2021 	}
2022 
2023 	fclose(file);
2024 	return err;
2025 }
2026 
2027 static int bpf_object__init_kconfig_map(struct bpf_object *obj)
2028 {
2029 	struct extern_desc *last_ext = NULL, *ext;
2030 	size_t map_sz;
2031 	int i, err;
2032 
2033 	for (i = 0; i < obj->nr_extern; i++) {
2034 		ext = &obj->externs[i];
2035 		if (ext->type == EXT_KCFG)
2036 			last_ext = ext;
2037 	}
2038 
2039 	if (!last_ext)
2040 		return 0;
2041 
2042 	map_sz = last_ext->kcfg.data_off + last_ext->kcfg.sz;
2043 	err = bpf_object__init_internal_map(obj, LIBBPF_MAP_KCONFIG,
2044 					    ".kconfig", obj->efile.symbols_shndx,
2045 					    NULL, map_sz);
2046 	if (err)
2047 		return err;
2048 
2049 	obj->kconfig_map_idx = obj->nr_maps - 1;
2050 
2051 	return 0;
2052 }
2053 
2054 const struct btf_type *
2055 skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id)
2056 {
2057 	const struct btf_type *t = btf__type_by_id(btf, id);
2058 
2059 	if (res_id)
2060 		*res_id = id;
2061 
2062 	while (btf_is_mod(t) || btf_is_typedef(t)) {
2063 		if (res_id)
2064 			*res_id = t->type;
2065 		t = btf__type_by_id(btf, t->type);
2066 	}
2067 
2068 	return t;
2069 }
2070 
2071 static const struct btf_type *
2072 resolve_func_ptr(const struct btf *btf, __u32 id, __u32 *res_id)
2073 {
2074 	const struct btf_type *t;
2075 
2076 	t = skip_mods_and_typedefs(btf, id, NULL);
2077 	if (!btf_is_ptr(t))
2078 		return NULL;
2079 
2080 	t = skip_mods_and_typedefs(btf, t->type, res_id);
2081 
2082 	return btf_is_func_proto(t) ? t : NULL;
2083 }
2084 
2085 static const char *__btf_kind_str(__u16 kind)
2086 {
2087 	switch (kind) {
2088 	case BTF_KIND_UNKN: return "void";
2089 	case BTF_KIND_INT: return "int";
2090 	case BTF_KIND_PTR: return "ptr";
2091 	case BTF_KIND_ARRAY: return "array";
2092 	case BTF_KIND_STRUCT: return "struct";
2093 	case BTF_KIND_UNION: return "union";
2094 	case BTF_KIND_ENUM: return "enum";
2095 	case BTF_KIND_FWD: return "fwd";
2096 	case BTF_KIND_TYPEDEF: return "typedef";
2097 	case BTF_KIND_VOLATILE: return "volatile";
2098 	case BTF_KIND_CONST: return "const";
2099 	case BTF_KIND_RESTRICT: return "restrict";
2100 	case BTF_KIND_FUNC: return "func";
2101 	case BTF_KIND_FUNC_PROTO: return "func_proto";
2102 	case BTF_KIND_VAR: return "var";
2103 	case BTF_KIND_DATASEC: return "datasec";
2104 	case BTF_KIND_FLOAT: return "float";
2105 	case BTF_KIND_DECL_TAG: return "decl_tag";
2106 	case BTF_KIND_TYPE_TAG: return "type_tag";
2107 	case BTF_KIND_ENUM64: return "enum64";
2108 	default: return "unknown";
2109 	}
2110 }
2111 
2112 const char *btf_kind_str(const struct btf_type *t)
2113 {
2114 	return __btf_kind_str(btf_kind(t));
2115 }
2116 
2117 /*
2118  * Fetch integer attribute of BTF map definition. Such attributes are
2119  * represented using a pointer to an array, in which dimensionality of array
2120  * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
2121  * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
2122  * type definition, while using only sizeof(void *) space in ELF data section.
2123  */
2124 static bool get_map_field_int(const char *map_name, const struct btf *btf,
2125 			      const struct btf_member *m, __u32 *res)
2126 {
2127 	const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
2128 	const char *name = btf__name_by_offset(btf, m->name_off);
2129 	const struct btf_array *arr_info;
2130 	const struct btf_type *arr_t;
2131 
2132 	if (!btf_is_ptr(t)) {
2133 		pr_warn("map '%s': attr '%s': expected PTR, got %s.\n",
2134 			map_name, name, btf_kind_str(t));
2135 		return false;
2136 	}
2137 
2138 	arr_t = btf__type_by_id(btf, t->type);
2139 	if (!arr_t) {
2140 		pr_warn("map '%s': attr '%s': type [%u] not found.\n",
2141 			map_name, name, t->type);
2142 		return false;
2143 	}
2144 	if (!btf_is_array(arr_t)) {
2145 		pr_warn("map '%s': attr '%s': expected ARRAY, got %s.\n",
2146 			map_name, name, btf_kind_str(arr_t));
2147 		return false;
2148 	}
2149 	arr_info = btf_array(arr_t);
2150 	*res = arr_info->nelems;
2151 	return true;
2152 }
2153 
2154 static int pathname_concat(char *buf, size_t buf_sz, const char *path, const char *name)
2155 {
2156 	int len;
2157 
2158 	len = snprintf(buf, buf_sz, "%s/%s", path, name);
2159 	if (len < 0)
2160 		return -EINVAL;
2161 	if (len >= buf_sz)
2162 		return -ENAMETOOLONG;
2163 
2164 	return 0;
2165 }
2166 
2167 static int build_map_pin_path(struct bpf_map *map, const char *path)
2168 {
2169 	char buf[PATH_MAX];
2170 	int err;
2171 
2172 	if (!path)
2173 		path = "/sys/fs/bpf";
2174 
2175 	err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
2176 	if (err)
2177 		return err;
2178 
2179 	return bpf_map__set_pin_path(map, buf);
2180 }
2181 
2182 /* should match definition in bpf_helpers.h */
2183 enum libbpf_pin_type {
2184 	LIBBPF_PIN_NONE,
2185 	/* PIN_BY_NAME: pin maps by name (in /sys/fs/bpf by default) */
2186 	LIBBPF_PIN_BY_NAME,
2187 };
2188 
2189 int parse_btf_map_def(const char *map_name, struct btf *btf,
2190 		      const struct btf_type *def_t, bool strict,
2191 		      struct btf_map_def *map_def, struct btf_map_def *inner_def)
2192 {
2193 	const struct btf_type *t;
2194 	const struct btf_member *m;
2195 	bool is_inner = inner_def == NULL;
2196 	int vlen, i;
2197 
2198 	vlen = btf_vlen(def_t);
2199 	m = btf_members(def_t);
2200 	for (i = 0; i < vlen; i++, m++) {
2201 		const char *name = btf__name_by_offset(btf, m->name_off);
2202 
2203 		if (!name) {
2204 			pr_warn("map '%s': invalid field #%d.\n", map_name, i);
2205 			return -EINVAL;
2206 		}
2207 		if (strcmp(name, "type") == 0) {
2208 			if (!get_map_field_int(map_name, btf, m, &map_def->map_type))
2209 				return -EINVAL;
2210 			map_def->parts |= MAP_DEF_MAP_TYPE;
2211 		} else if (strcmp(name, "max_entries") == 0) {
2212 			if (!get_map_field_int(map_name, btf, m, &map_def->max_entries))
2213 				return -EINVAL;
2214 			map_def->parts |= MAP_DEF_MAX_ENTRIES;
2215 		} else if (strcmp(name, "map_flags") == 0) {
2216 			if (!get_map_field_int(map_name, btf, m, &map_def->map_flags))
2217 				return -EINVAL;
2218 			map_def->parts |= MAP_DEF_MAP_FLAGS;
2219 		} else if (strcmp(name, "numa_node") == 0) {
2220 			if (!get_map_field_int(map_name, btf, m, &map_def->numa_node))
2221 				return -EINVAL;
2222 			map_def->parts |= MAP_DEF_NUMA_NODE;
2223 		} else if (strcmp(name, "key_size") == 0) {
2224 			__u32 sz;
2225 
2226 			if (!get_map_field_int(map_name, btf, m, &sz))
2227 				return -EINVAL;
2228 			if (map_def->key_size && map_def->key_size != sz) {
2229 				pr_warn("map '%s': conflicting key size %u != %u.\n",
2230 					map_name, map_def->key_size, sz);
2231 				return -EINVAL;
2232 			}
2233 			map_def->key_size = sz;
2234 			map_def->parts |= MAP_DEF_KEY_SIZE;
2235 		} else if (strcmp(name, "key") == 0) {
2236 			__s64 sz;
2237 
2238 			t = btf__type_by_id(btf, m->type);
2239 			if (!t) {
2240 				pr_warn("map '%s': key type [%d] not found.\n",
2241 					map_name, m->type);
2242 				return -EINVAL;
2243 			}
2244 			if (!btf_is_ptr(t)) {
2245 				pr_warn("map '%s': key spec is not PTR: %s.\n",
2246 					map_name, btf_kind_str(t));
2247 				return -EINVAL;
2248 			}
2249 			sz = btf__resolve_size(btf, t->type);
2250 			if (sz < 0) {
2251 				pr_warn("map '%s': can't determine key size for type [%u]: %zd.\n",
2252 					map_name, t->type, (ssize_t)sz);
2253 				return sz;
2254 			}
2255 			if (map_def->key_size && map_def->key_size != sz) {
2256 				pr_warn("map '%s': conflicting key size %u != %zd.\n",
2257 					map_name, map_def->key_size, (ssize_t)sz);
2258 				return -EINVAL;
2259 			}
2260 			map_def->key_size = sz;
2261 			map_def->key_type_id = t->type;
2262 			map_def->parts |= MAP_DEF_KEY_SIZE | MAP_DEF_KEY_TYPE;
2263 		} else if (strcmp(name, "value_size") == 0) {
2264 			__u32 sz;
2265 
2266 			if (!get_map_field_int(map_name, btf, m, &sz))
2267 				return -EINVAL;
2268 			if (map_def->value_size && map_def->value_size != sz) {
2269 				pr_warn("map '%s': conflicting value size %u != %u.\n",
2270 					map_name, map_def->value_size, sz);
2271 				return -EINVAL;
2272 			}
2273 			map_def->value_size = sz;
2274 			map_def->parts |= MAP_DEF_VALUE_SIZE;
2275 		} else if (strcmp(name, "value") == 0) {
2276 			__s64 sz;
2277 
2278 			t = btf__type_by_id(btf, m->type);
2279 			if (!t) {
2280 				pr_warn("map '%s': value type [%d] not found.\n",
2281 					map_name, m->type);
2282 				return -EINVAL;
2283 			}
2284 			if (!btf_is_ptr(t)) {
2285 				pr_warn("map '%s': value spec is not PTR: %s.\n",
2286 					map_name, btf_kind_str(t));
2287 				return -EINVAL;
2288 			}
2289 			sz = btf__resolve_size(btf, t->type);
2290 			if (sz < 0) {
2291 				pr_warn("map '%s': can't determine value size for type [%u]: %zd.\n",
2292 					map_name, t->type, (ssize_t)sz);
2293 				return sz;
2294 			}
2295 			if (map_def->value_size && map_def->value_size != sz) {
2296 				pr_warn("map '%s': conflicting value size %u != %zd.\n",
2297 					map_name, map_def->value_size, (ssize_t)sz);
2298 				return -EINVAL;
2299 			}
2300 			map_def->value_size = sz;
2301 			map_def->value_type_id = t->type;
2302 			map_def->parts |= MAP_DEF_VALUE_SIZE | MAP_DEF_VALUE_TYPE;
2303 		}
2304 		else if (strcmp(name, "values") == 0) {
2305 			bool is_map_in_map = bpf_map_type__is_map_in_map(map_def->map_type);
2306 			bool is_prog_array = map_def->map_type == BPF_MAP_TYPE_PROG_ARRAY;
2307 			const char *desc = is_map_in_map ? "map-in-map inner" : "prog-array value";
2308 			char inner_map_name[128];
2309 			int err;
2310 
2311 			if (is_inner) {
2312 				pr_warn("map '%s': multi-level inner maps not supported.\n",
2313 					map_name);
2314 				return -ENOTSUP;
2315 			}
2316 			if (i != vlen - 1) {
2317 				pr_warn("map '%s': '%s' member should be last.\n",
2318 					map_name, name);
2319 				return -EINVAL;
2320 			}
2321 			if (!is_map_in_map && !is_prog_array) {
2322 				pr_warn("map '%s': should be map-in-map or prog-array.\n",
2323 					map_name);
2324 				return -ENOTSUP;
2325 			}
2326 			if (map_def->value_size && map_def->value_size != 4) {
2327 				pr_warn("map '%s': conflicting value size %u != 4.\n",
2328 					map_name, map_def->value_size);
2329 				return -EINVAL;
2330 			}
2331 			map_def->value_size = 4;
2332 			t = btf__type_by_id(btf, m->type);
2333 			if (!t) {
2334 				pr_warn("map '%s': %s type [%d] not found.\n",
2335 					map_name, desc, m->type);
2336 				return -EINVAL;
2337 			}
2338 			if (!btf_is_array(t) || btf_array(t)->nelems) {
2339 				pr_warn("map '%s': %s spec is not a zero-sized array.\n",
2340 					map_name, desc);
2341 				return -EINVAL;
2342 			}
2343 			t = skip_mods_and_typedefs(btf, btf_array(t)->type, NULL);
2344 			if (!btf_is_ptr(t)) {
2345 				pr_warn("map '%s': %s def is of unexpected kind %s.\n",
2346 					map_name, desc, btf_kind_str(t));
2347 				return -EINVAL;
2348 			}
2349 			t = skip_mods_and_typedefs(btf, t->type, NULL);
2350 			if (is_prog_array) {
2351 				if (!btf_is_func_proto(t)) {
2352 					pr_warn("map '%s': prog-array value def is of unexpected kind %s.\n",
2353 						map_name, btf_kind_str(t));
2354 					return -EINVAL;
2355 				}
2356 				continue;
2357 			}
2358 			if (!btf_is_struct(t)) {
2359 				pr_warn("map '%s': map-in-map inner def is of unexpected kind %s.\n",
2360 					map_name, btf_kind_str(t));
2361 				return -EINVAL;
2362 			}
2363 
2364 			snprintf(inner_map_name, sizeof(inner_map_name), "%s.inner", map_name);
2365 			err = parse_btf_map_def(inner_map_name, btf, t, strict, inner_def, NULL);
2366 			if (err)
2367 				return err;
2368 
2369 			map_def->parts |= MAP_DEF_INNER_MAP;
2370 		} else if (strcmp(name, "pinning") == 0) {
2371 			__u32 val;
2372 
2373 			if (is_inner) {
2374 				pr_warn("map '%s': inner def can't be pinned.\n", map_name);
2375 				return -EINVAL;
2376 			}
2377 			if (!get_map_field_int(map_name, btf, m, &val))
2378 				return -EINVAL;
2379 			if (val != LIBBPF_PIN_NONE && val != LIBBPF_PIN_BY_NAME) {
2380 				pr_warn("map '%s': invalid pinning value %u.\n",
2381 					map_name, val);
2382 				return -EINVAL;
2383 			}
2384 			map_def->pinning = val;
2385 			map_def->parts |= MAP_DEF_PINNING;
2386 		} else if (strcmp(name, "map_extra") == 0) {
2387 			__u32 map_extra;
2388 
2389 			if (!get_map_field_int(map_name, btf, m, &map_extra))
2390 				return -EINVAL;
2391 			map_def->map_extra = map_extra;
2392 			map_def->parts |= MAP_DEF_MAP_EXTRA;
2393 		} else {
2394 			if (strict) {
2395 				pr_warn("map '%s': unknown field '%s'.\n", map_name, name);
2396 				return -ENOTSUP;
2397 			}
2398 			pr_debug("map '%s': ignoring unknown field '%s'.\n", map_name, name);
2399 		}
2400 	}
2401 
2402 	if (map_def->map_type == BPF_MAP_TYPE_UNSPEC) {
2403 		pr_warn("map '%s': map type isn't specified.\n", map_name);
2404 		return -EINVAL;
2405 	}
2406 
2407 	return 0;
2408 }
2409 
2410 static size_t adjust_ringbuf_sz(size_t sz)
2411 {
2412 	__u32 page_sz = sysconf(_SC_PAGE_SIZE);
2413 	__u32 mul;
2414 
2415 	/* if user forgot to set any size, make sure they see error */
2416 	if (sz == 0)
2417 		return 0;
2418 	/* Kernel expects BPF_MAP_TYPE_RINGBUF's max_entries to be
2419 	 * a power-of-2 multiple of kernel's page size. If user diligently
2420 	 * satisified these conditions, pass the size through.
2421 	 */
2422 	if ((sz % page_sz) == 0 && is_pow_of_2(sz / page_sz))
2423 		return sz;
2424 
2425 	/* Otherwise find closest (page_sz * power_of_2) product bigger than
2426 	 * user-set size to satisfy both user size request and kernel
2427 	 * requirements and substitute correct max_entries for map creation.
2428 	 */
2429 	for (mul = 1; mul <= UINT_MAX / page_sz; mul <<= 1) {
2430 		if (mul * page_sz > sz)
2431 			return mul * page_sz;
2432 	}
2433 
2434 	/* if it's impossible to satisfy the conditions (i.e., user size is
2435 	 * very close to UINT_MAX but is not a power-of-2 multiple of
2436 	 * page_size) then just return original size and let kernel reject it
2437 	 */
2438 	return sz;
2439 }
2440 
2441 static bool map_is_ringbuf(const struct bpf_map *map)
2442 {
2443 	return map->def.type == BPF_MAP_TYPE_RINGBUF ||
2444 	       map->def.type == BPF_MAP_TYPE_USER_RINGBUF;
2445 }
2446 
2447 static void fill_map_from_def(struct bpf_map *map, const struct btf_map_def *def)
2448 {
2449 	map->def.type = def->map_type;
2450 	map->def.key_size = def->key_size;
2451 	map->def.value_size = def->value_size;
2452 	map->def.max_entries = def->max_entries;
2453 	map->def.map_flags = def->map_flags;
2454 	map->map_extra = def->map_extra;
2455 
2456 	map->numa_node = def->numa_node;
2457 	map->btf_key_type_id = def->key_type_id;
2458 	map->btf_value_type_id = def->value_type_id;
2459 
2460 	/* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
2461 	if (map_is_ringbuf(map))
2462 		map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
2463 
2464 	if (def->parts & MAP_DEF_MAP_TYPE)
2465 		pr_debug("map '%s': found type = %u.\n", map->name, def->map_type);
2466 
2467 	if (def->parts & MAP_DEF_KEY_TYPE)
2468 		pr_debug("map '%s': found key [%u], sz = %u.\n",
2469 			 map->name, def->key_type_id, def->key_size);
2470 	else if (def->parts & MAP_DEF_KEY_SIZE)
2471 		pr_debug("map '%s': found key_size = %u.\n", map->name, def->key_size);
2472 
2473 	if (def->parts & MAP_DEF_VALUE_TYPE)
2474 		pr_debug("map '%s': found value [%u], sz = %u.\n",
2475 			 map->name, def->value_type_id, def->value_size);
2476 	else if (def->parts & MAP_DEF_VALUE_SIZE)
2477 		pr_debug("map '%s': found value_size = %u.\n", map->name, def->value_size);
2478 
2479 	if (def->parts & MAP_DEF_MAX_ENTRIES)
2480 		pr_debug("map '%s': found max_entries = %u.\n", map->name, def->max_entries);
2481 	if (def->parts & MAP_DEF_MAP_FLAGS)
2482 		pr_debug("map '%s': found map_flags = 0x%x.\n", map->name, def->map_flags);
2483 	if (def->parts & MAP_DEF_MAP_EXTRA)
2484 		pr_debug("map '%s': found map_extra = 0x%llx.\n", map->name,
2485 			 (unsigned long long)def->map_extra);
2486 	if (def->parts & MAP_DEF_PINNING)
2487 		pr_debug("map '%s': found pinning = %u.\n", map->name, def->pinning);
2488 	if (def->parts & MAP_DEF_NUMA_NODE)
2489 		pr_debug("map '%s': found numa_node = %u.\n", map->name, def->numa_node);
2490 
2491 	if (def->parts & MAP_DEF_INNER_MAP)
2492 		pr_debug("map '%s': found inner map definition.\n", map->name);
2493 }
2494 
2495 static const char *btf_var_linkage_str(__u32 linkage)
2496 {
2497 	switch (linkage) {
2498 	case BTF_VAR_STATIC: return "static";
2499 	case BTF_VAR_GLOBAL_ALLOCATED: return "global";
2500 	case BTF_VAR_GLOBAL_EXTERN: return "extern";
2501 	default: return "unknown";
2502 	}
2503 }
2504 
2505 static int bpf_object__init_user_btf_map(struct bpf_object *obj,
2506 					 const struct btf_type *sec,
2507 					 int var_idx, int sec_idx,
2508 					 const Elf_Data *data, bool strict,
2509 					 const char *pin_root_path)
2510 {
2511 	struct btf_map_def map_def = {}, inner_def = {};
2512 	const struct btf_type *var, *def;
2513 	const struct btf_var_secinfo *vi;
2514 	const struct btf_var *var_extra;
2515 	const char *map_name;
2516 	struct bpf_map *map;
2517 	int err;
2518 
2519 	vi = btf_var_secinfos(sec) + var_idx;
2520 	var = btf__type_by_id(obj->btf, vi->type);
2521 	var_extra = btf_var(var);
2522 	map_name = btf__name_by_offset(obj->btf, var->name_off);
2523 
2524 	if (map_name == NULL || map_name[0] == '\0') {
2525 		pr_warn("map #%d: empty name.\n", var_idx);
2526 		return -EINVAL;
2527 	}
2528 	if ((__u64)vi->offset + vi->size > data->d_size) {
2529 		pr_warn("map '%s' BTF data is corrupted.\n", map_name);
2530 		return -EINVAL;
2531 	}
2532 	if (!btf_is_var(var)) {
2533 		pr_warn("map '%s': unexpected var kind %s.\n",
2534 			map_name, btf_kind_str(var));
2535 		return -EINVAL;
2536 	}
2537 	if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED) {
2538 		pr_warn("map '%s': unsupported map linkage %s.\n",
2539 			map_name, btf_var_linkage_str(var_extra->linkage));
2540 		return -EOPNOTSUPP;
2541 	}
2542 
2543 	def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
2544 	if (!btf_is_struct(def)) {
2545 		pr_warn("map '%s': unexpected def kind %s.\n",
2546 			map_name, btf_kind_str(var));
2547 		return -EINVAL;
2548 	}
2549 	if (def->size > vi->size) {
2550 		pr_warn("map '%s': invalid def size.\n", map_name);
2551 		return -EINVAL;
2552 	}
2553 
2554 	map = bpf_object__add_map(obj);
2555 	if (IS_ERR(map))
2556 		return PTR_ERR(map);
2557 	map->name = strdup(map_name);
2558 	if (!map->name) {
2559 		pr_warn("map '%s': failed to alloc map name.\n", map_name);
2560 		return -ENOMEM;
2561 	}
2562 	map->libbpf_type = LIBBPF_MAP_UNSPEC;
2563 	map->def.type = BPF_MAP_TYPE_UNSPEC;
2564 	map->sec_idx = sec_idx;
2565 	map->sec_offset = vi->offset;
2566 	map->btf_var_idx = var_idx;
2567 	pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
2568 		 map_name, map->sec_idx, map->sec_offset);
2569 
2570 	err = parse_btf_map_def(map->name, obj->btf, def, strict, &map_def, &inner_def);
2571 	if (err)
2572 		return err;
2573 
2574 	fill_map_from_def(map, &map_def);
2575 
2576 	if (map_def.pinning == LIBBPF_PIN_BY_NAME) {
2577 		err = build_map_pin_path(map, pin_root_path);
2578 		if (err) {
2579 			pr_warn("map '%s': couldn't build pin path.\n", map->name);
2580 			return err;
2581 		}
2582 	}
2583 
2584 	if (map_def.parts & MAP_DEF_INNER_MAP) {
2585 		map->inner_map = calloc(1, sizeof(*map->inner_map));
2586 		if (!map->inner_map)
2587 			return -ENOMEM;
2588 		map->inner_map->fd = -1;
2589 		map->inner_map->sec_idx = sec_idx;
2590 		map->inner_map->name = malloc(strlen(map_name) + sizeof(".inner") + 1);
2591 		if (!map->inner_map->name)
2592 			return -ENOMEM;
2593 		sprintf(map->inner_map->name, "%s.inner", map_name);
2594 
2595 		fill_map_from_def(map->inner_map, &inner_def);
2596 	}
2597 
2598 	err = map_fill_btf_type_info(obj, map);
2599 	if (err)
2600 		return err;
2601 
2602 	return 0;
2603 }
2604 
2605 static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict,
2606 					  const char *pin_root_path)
2607 {
2608 	const struct btf_type *sec = NULL;
2609 	int nr_types, i, vlen, err;
2610 	const struct btf_type *t;
2611 	const char *name;
2612 	Elf_Data *data;
2613 	Elf_Scn *scn;
2614 
2615 	if (obj->efile.btf_maps_shndx < 0)
2616 		return 0;
2617 
2618 	scn = elf_sec_by_idx(obj, obj->efile.btf_maps_shndx);
2619 	data = elf_sec_data(obj, scn);
2620 	if (!scn || !data) {
2621 		pr_warn("elf: failed to get %s map definitions for %s\n",
2622 			MAPS_ELF_SEC, obj->path);
2623 		return -EINVAL;
2624 	}
2625 
2626 	nr_types = btf__type_cnt(obj->btf);
2627 	for (i = 1; i < nr_types; i++) {
2628 		t = btf__type_by_id(obj->btf, i);
2629 		if (!btf_is_datasec(t))
2630 			continue;
2631 		name = btf__name_by_offset(obj->btf, t->name_off);
2632 		if (strcmp(name, MAPS_ELF_SEC) == 0) {
2633 			sec = t;
2634 			obj->efile.btf_maps_sec_btf_id = i;
2635 			break;
2636 		}
2637 	}
2638 
2639 	if (!sec) {
2640 		pr_warn("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
2641 		return -ENOENT;
2642 	}
2643 
2644 	vlen = btf_vlen(sec);
2645 	for (i = 0; i < vlen; i++) {
2646 		err = bpf_object__init_user_btf_map(obj, sec, i,
2647 						    obj->efile.btf_maps_shndx,
2648 						    data, strict,
2649 						    pin_root_path);
2650 		if (err)
2651 			return err;
2652 	}
2653 
2654 	return 0;
2655 }
2656 
2657 static int bpf_object__init_maps(struct bpf_object *obj,
2658 				 const struct bpf_object_open_opts *opts)
2659 {
2660 	const char *pin_root_path;
2661 	bool strict;
2662 	int err = 0;
2663 
2664 	strict = !OPTS_GET(opts, relaxed_maps, false);
2665 	pin_root_path = OPTS_GET(opts, pin_root_path, NULL);
2666 
2667 	err = bpf_object__init_user_btf_maps(obj, strict, pin_root_path);
2668 	err = err ?: bpf_object__init_global_data_maps(obj);
2669 	err = err ?: bpf_object__init_kconfig_map(obj);
2670 	err = err ?: bpf_object_init_struct_ops(obj);
2671 
2672 	return err;
2673 }
2674 
2675 static bool section_have_execinstr(struct bpf_object *obj, int idx)
2676 {
2677 	Elf64_Shdr *sh;
2678 
2679 	sh = elf_sec_hdr(obj, elf_sec_by_idx(obj, idx));
2680 	if (!sh)
2681 		return false;
2682 
2683 	return sh->sh_flags & SHF_EXECINSTR;
2684 }
2685 
2686 static bool btf_needs_sanitization(struct bpf_object *obj)
2687 {
2688 	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
2689 	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
2690 	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
2691 	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
2692 	bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
2693 	bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
2694 	bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
2695 
2696 	return !has_func || !has_datasec || !has_func_global || !has_float ||
2697 	       !has_decl_tag || !has_type_tag || !has_enum64;
2698 }
2699 
2700 static int bpf_object__sanitize_btf(struct bpf_object *obj, struct btf *btf)
2701 {
2702 	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
2703 	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
2704 	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
2705 	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
2706 	bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
2707 	bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
2708 	bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
2709 	int enum64_placeholder_id = 0;
2710 	struct btf_type *t;
2711 	int i, j, vlen;
2712 
2713 	for (i = 1; i < btf__type_cnt(btf); i++) {
2714 		t = (struct btf_type *)btf__type_by_id(btf, i);
2715 
2716 		if ((!has_datasec && btf_is_var(t)) || (!has_decl_tag && btf_is_decl_tag(t))) {
2717 			/* replace VAR/DECL_TAG with INT */
2718 			t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
2719 			/*
2720 			 * using size = 1 is the safest choice, 4 will be too
2721 			 * big and cause kernel BTF validation failure if
2722 			 * original variable took less than 4 bytes
2723 			 */
2724 			t->size = 1;
2725 			*(int *)(t + 1) = BTF_INT_ENC(0, 0, 8);
2726 		} else if (!has_datasec && btf_is_datasec(t)) {
2727 			/* replace DATASEC with STRUCT */
2728 			const struct btf_var_secinfo *v = btf_var_secinfos(t);
2729 			struct btf_member *m = btf_members(t);
2730 			struct btf_type *vt;
2731 			char *name;
2732 
2733 			name = (char *)btf__name_by_offset(btf, t->name_off);
2734 			while (*name) {
2735 				if (*name == '.')
2736 					*name = '_';
2737 				name++;
2738 			}
2739 
2740 			vlen = btf_vlen(t);
2741 			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
2742 			for (j = 0; j < vlen; j++, v++, m++) {
2743 				/* order of field assignments is important */
2744 				m->offset = v->offset * 8;
2745 				m->type = v->type;
2746 				/* preserve variable name as member name */
2747 				vt = (void *)btf__type_by_id(btf, v->type);
2748 				m->name_off = vt->name_off;
2749 			}
2750 		} else if (!has_func && btf_is_func_proto(t)) {
2751 			/* replace FUNC_PROTO with ENUM */
2752 			vlen = btf_vlen(t);
2753 			t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
2754 			t->size = sizeof(__u32); /* kernel enforced */
2755 		} else if (!has_func && btf_is_func(t)) {
2756 			/* replace FUNC with TYPEDEF */
2757 			t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
2758 		} else if (!has_func_global && btf_is_func(t)) {
2759 			/* replace BTF_FUNC_GLOBAL with BTF_FUNC_STATIC */
2760 			t->info = BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0);
2761 		} else if (!has_float && btf_is_float(t)) {
2762 			/* replace FLOAT with an equally-sized empty STRUCT;
2763 			 * since C compilers do not accept e.g. "float" as a
2764 			 * valid struct name, make it anonymous
2765 			 */
2766 			t->name_off = 0;
2767 			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, 0);
2768 		} else if (!has_type_tag && btf_is_type_tag(t)) {
2769 			/* replace TYPE_TAG with a CONST */
2770 			t->name_off = 0;
2771 			t->info = BTF_INFO_ENC(BTF_KIND_CONST, 0, 0);
2772 		} else if (!has_enum64 && btf_is_enum(t)) {
2773 			/* clear the kflag */
2774 			t->info = btf_type_info(btf_kind(t), btf_vlen(t), false);
2775 		} else if (!has_enum64 && btf_is_enum64(t)) {
2776 			/* replace ENUM64 with a union */
2777 			struct btf_member *m;
2778 
2779 			if (enum64_placeholder_id == 0) {
2780 				enum64_placeholder_id = btf__add_int(btf, "enum64_placeholder", 1, 0);
2781 				if (enum64_placeholder_id < 0)
2782 					return enum64_placeholder_id;
2783 
2784 				t = (struct btf_type *)btf__type_by_id(btf, i);
2785 			}
2786 
2787 			m = btf_members(t);
2788 			vlen = btf_vlen(t);
2789 			t->info = BTF_INFO_ENC(BTF_KIND_UNION, 0, vlen);
2790 			for (j = 0; j < vlen; j++, m++) {
2791 				m->type = enum64_placeholder_id;
2792 				m->offset = 0;
2793 			}
2794 		}
2795 	}
2796 
2797 	return 0;
2798 }
2799 
2800 static bool libbpf_needs_btf(const struct bpf_object *obj)
2801 {
2802 	return obj->efile.btf_maps_shndx >= 0 ||
2803 	       obj->efile.st_ops_shndx >= 0 ||
2804 	       obj->efile.st_ops_link_shndx >= 0 ||
2805 	       obj->nr_extern > 0;
2806 }
2807 
2808 static bool kernel_needs_btf(const struct bpf_object *obj)
2809 {
2810 	return obj->efile.st_ops_shndx >= 0 || obj->efile.st_ops_link_shndx >= 0;
2811 }
2812 
2813 static int bpf_object__init_btf(struct bpf_object *obj,
2814 				Elf_Data *btf_data,
2815 				Elf_Data *btf_ext_data)
2816 {
2817 	int err = -ENOENT;
2818 
2819 	if (btf_data) {
2820 		obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
2821 		err = libbpf_get_error(obj->btf);
2822 		if (err) {
2823 			obj->btf = NULL;
2824 			pr_warn("Error loading ELF section %s: %d.\n", BTF_ELF_SEC, err);
2825 			goto out;
2826 		}
2827 		/* enforce 8-byte pointers for BPF-targeted BTFs */
2828 		btf__set_pointer_size(obj->btf, 8);
2829 	}
2830 	if (btf_ext_data) {
2831 		struct btf_ext_info *ext_segs[3];
2832 		int seg_num, sec_num;
2833 
2834 		if (!obj->btf) {
2835 			pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
2836 				 BTF_EXT_ELF_SEC, BTF_ELF_SEC);
2837 			goto out;
2838 		}
2839 		obj->btf_ext = btf_ext__new(btf_ext_data->d_buf, btf_ext_data->d_size);
2840 		err = libbpf_get_error(obj->btf_ext);
2841 		if (err) {
2842 			pr_warn("Error loading ELF section %s: %d. Ignored and continue.\n",
2843 				BTF_EXT_ELF_SEC, err);
2844 			obj->btf_ext = NULL;
2845 			goto out;
2846 		}
2847 
2848 		/* setup .BTF.ext to ELF section mapping */
2849 		ext_segs[0] = &obj->btf_ext->func_info;
2850 		ext_segs[1] = &obj->btf_ext->line_info;
2851 		ext_segs[2] = &obj->btf_ext->core_relo_info;
2852 		for (seg_num = 0; seg_num < ARRAY_SIZE(ext_segs); seg_num++) {
2853 			struct btf_ext_info *seg = ext_segs[seg_num];
2854 			const struct btf_ext_info_sec *sec;
2855 			const char *sec_name;
2856 			Elf_Scn *scn;
2857 
2858 			if (seg->sec_cnt == 0)
2859 				continue;
2860 
2861 			seg->sec_idxs = calloc(seg->sec_cnt, sizeof(*seg->sec_idxs));
2862 			if (!seg->sec_idxs) {
2863 				err = -ENOMEM;
2864 				goto out;
2865 			}
2866 
2867 			sec_num = 0;
2868 			for_each_btf_ext_sec(seg, sec) {
2869 				/* preventively increment index to avoid doing
2870 				 * this before every continue below
2871 				 */
2872 				sec_num++;
2873 
2874 				sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
2875 				if (str_is_empty(sec_name))
2876 					continue;
2877 				scn = elf_sec_by_name(obj, sec_name);
2878 				if (!scn)
2879 					continue;
2880 
2881 				seg->sec_idxs[sec_num - 1] = elf_ndxscn(scn);
2882 			}
2883 		}
2884 	}
2885 out:
2886 	if (err && libbpf_needs_btf(obj)) {
2887 		pr_warn("BTF is required, but is missing or corrupted.\n");
2888 		return err;
2889 	}
2890 	return 0;
2891 }
2892 
2893 static int compare_vsi_off(const void *_a, const void *_b)
2894 {
2895 	const struct btf_var_secinfo *a = _a;
2896 	const struct btf_var_secinfo *b = _b;
2897 
2898 	return a->offset - b->offset;
2899 }
2900 
2901 static int btf_fixup_datasec(struct bpf_object *obj, struct btf *btf,
2902 			     struct btf_type *t)
2903 {
2904 	__u32 size = 0, i, vars = btf_vlen(t);
2905 	const char *sec_name = btf__name_by_offset(btf, t->name_off);
2906 	struct btf_var_secinfo *vsi;
2907 	bool fixup_offsets = false;
2908 	int err;
2909 
2910 	if (!sec_name) {
2911 		pr_debug("No name found in string section for DATASEC kind.\n");
2912 		return -ENOENT;
2913 	}
2914 
2915 	/* Extern-backing datasecs (.ksyms, .kconfig) have their size and
2916 	 * variable offsets set at the previous step. Further, not every
2917 	 * extern BTF VAR has corresponding ELF symbol preserved, so we skip
2918 	 * all fixups altogether for such sections and go straight to sorting
2919 	 * VARs within their DATASEC.
2920 	 */
2921 	if (strcmp(sec_name, KCONFIG_SEC) == 0 || strcmp(sec_name, KSYMS_SEC) == 0)
2922 		goto sort_vars;
2923 
2924 	/* Clang leaves DATASEC size and VAR offsets as zeroes, so we need to
2925 	 * fix this up. But BPF static linker already fixes this up and fills
2926 	 * all the sizes and offsets during static linking. So this step has
2927 	 * to be optional. But the STV_HIDDEN handling is non-optional for any
2928 	 * non-extern DATASEC, so the variable fixup loop below handles both
2929 	 * functions at the same time, paying the cost of BTF VAR <-> ELF
2930 	 * symbol matching just once.
2931 	 */
2932 	if (t->size == 0) {
2933 		err = find_elf_sec_sz(obj, sec_name, &size);
2934 		if (err || !size) {
2935 			pr_debug("sec '%s': failed to determine size from ELF: size %u, err %d\n",
2936 				 sec_name, size, err);
2937 			return -ENOENT;
2938 		}
2939 
2940 		t->size = size;
2941 		fixup_offsets = true;
2942 	}
2943 
2944 	for (i = 0, vsi = btf_var_secinfos(t); i < vars; i++, vsi++) {
2945 		const struct btf_type *t_var;
2946 		struct btf_var *var;
2947 		const char *var_name;
2948 		Elf64_Sym *sym;
2949 
2950 		t_var = btf__type_by_id(btf, vsi->type);
2951 		if (!t_var || !btf_is_var(t_var)) {
2952 			pr_debug("sec '%s': unexpected non-VAR type found\n", sec_name);
2953 			return -EINVAL;
2954 		}
2955 
2956 		var = btf_var(t_var);
2957 		if (var->linkage == BTF_VAR_STATIC || var->linkage == BTF_VAR_GLOBAL_EXTERN)
2958 			continue;
2959 
2960 		var_name = btf__name_by_offset(btf, t_var->name_off);
2961 		if (!var_name) {
2962 			pr_debug("sec '%s': failed to find name of DATASEC's member #%d\n",
2963 				 sec_name, i);
2964 			return -ENOENT;
2965 		}
2966 
2967 		sym = find_elf_var_sym(obj, var_name);
2968 		if (IS_ERR(sym)) {
2969 			pr_debug("sec '%s': failed to find ELF symbol for VAR '%s'\n",
2970 				 sec_name, var_name);
2971 			return -ENOENT;
2972 		}
2973 
2974 		if (fixup_offsets)
2975 			vsi->offset = sym->st_value;
2976 
2977 		/* if variable is a global/weak symbol, but has restricted
2978 		 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF VAR
2979 		 * as static. This follows similar logic for functions (BPF
2980 		 * subprogs) and influences libbpf's further decisions about
2981 		 * whether to make global data BPF array maps as
2982 		 * BPF_F_MMAPABLE.
2983 		 */
2984 		if (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
2985 		    || ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL)
2986 			var->linkage = BTF_VAR_STATIC;
2987 	}
2988 
2989 sort_vars:
2990 	qsort(btf_var_secinfos(t), vars, sizeof(*vsi), compare_vsi_off);
2991 	return 0;
2992 }
2993 
2994 static int bpf_object_fixup_btf(struct bpf_object *obj)
2995 {
2996 	int i, n, err = 0;
2997 
2998 	if (!obj->btf)
2999 		return 0;
3000 
3001 	n = btf__type_cnt(obj->btf);
3002 	for (i = 1; i < n; i++) {
3003 		struct btf_type *t = btf_type_by_id(obj->btf, i);
3004 
3005 		/* Loader needs to fix up some of the things compiler
3006 		 * couldn't get its hands on while emitting BTF. This
3007 		 * is section size and global variable offset. We use
3008 		 * the info from the ELF itself for this purpose.
3009 		 */
3010 		if (btf_is_datasec(t)) {
3011 			err = btf_fixup_datasec(obj, obj->btf, t);
3012 			if (err)
3013 				return err;
3014 		}
3015 	}
3016 
3017 	return 0;
3018 }
3019 
3020 static bool prog_needs_vmlinux_btf(struct bpf_program *prog)
3021 {
3022 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
3023 	    prog->type == BPF_PROG_TYPE_LSM)
3024 		return true;
3025 
3026 	/* BPF_PROG_TYPE_TRACING programs which do not attach to other programs
3027 	 * also need vmlinux BTF
3028 	 */
3029 	if (prog->type == BPF_PROG_TYPE_TRACING && !prog->attach_prog_fd)
3030 		return true;
3031 
3032 	return false;
3033 }
3034 
3035 static bool obj_needs_vmlinux_btf(const struct bpf_object *obj)
3036 {
3037 	struct bpf_program *prog;
3038 	int i;
3039 
3040 	/* CO-RE relocations need kernel BTF, only when btf_custom_path
3041 	 * is not specified
3042 	 */
3043 	if (obj->btf_ext && obj->btf_ext->core_relo_info.len && !obj->btf_custom_path)
3044 		return true;
3045 
3046 	/* Support for typed ksyms needs kernel BTF */
3047 	for (i = 0; i < obj->nr_extern; i++) {
3048 		const struct extern_desc *ext;
3049 
3050 		ext = &obj->externs[i];
3051 		if (ext->type == EXT_KSYM && ext->ksym.type_id)
3052 			return true;
3053 	}
3054 
3055 	bpf_object__for_each_program(prog, obj) {
3056 		if (!prog->autoload)
3057 			continue;
3058 		if (prog_needs_vmlinux_btf(prog))
3059 			return true;
3060 	}
3061 
3062 	return false;
3063 }
3064 
3065 static int bpf_object__load_vmlinux_btf(struct bpf_object *obj, bool force)
3066 {
3067 	int err;
3068 
3069 	/* btf_vmlinux could be loaded earlier */
3070 	if (obj->btf_vmlinux || obj->gen_loader)
3071 		return 0;
3072 
3073 	if (!force && !obj_needs_vmlinux_btf(obj))
3074 		return 0;
3075 
3076 	obj->btf_vmlinux = btf__load_vmlinux_btf();
3077 	err = libbpf_get_error(obj->btf_vmlinux);
3078 	if (err) {
3079 		pr_warn("Error loading vmlinux BTF: %d\n", err);
3080 		obj->btf_vmlinux = NULL;
3081 		return err;
3082 	}
3083 	return 0;
3084 }
3085 
3086 static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
3087 {
3088 	struct btf *kern_btf = obj->btf;
3089 	bool btf_mandatory, sanitize;
3090 	int i, err = 0;
3091 
3092 	if (!obj->btf)
3093 		return 0;
3094 
3095 	if (!kernel_supports(obj, FEAT_BTF)) {
3096 		if (kernel_needs_btf(obj)) {
3097 			err = -EOPNOTSUPP;
3098 			goto report;
3099 		}
3100 		pr_debug("Kernel doesn't support BTF, skipping uploading it.\n");
3101 		return 0;
3102 	}
3103 
3104 	/* Even though some subprogs are global/weak, user might prefer more
3105 	 * permissive BPF verification process that BPF verifier performs for
3106 	 * static functions, taking into account more context from the caller
3107 	 * functions. In such case, they need to mark such subprogs with
3108 	 * __attribute__((visibility("hidden"))) and libbpf will adjust
3109 	 * corresponding FUNC BTF type to be marked as static and trigger more
3110 	 * involved BPF verification process.
3111 	 */
3112 	for (i = 0; i < obj->nr_programs; i++) {
3113 		struct bpf_program *prog = &obj->programs[i];
3114 		struct btf_type *t;
3115 		const char *name;
3116 		int j, n;
3117 
3118 		if (!prog->mark_btf_static || !prog_is_subprog(obj, prog))
3119 			continue;
3120 
3121 		n = btf__type_cnt(obj->btf);
3122 		for (j = 1; j < n; j++) {
3123 			t = btf_type_by_id(obj->btf, j);
3124 			if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL)
3125 				continue;
3126 
3127 			name = btf__str_by_offset(obj->btf, t->name_off);
3128 			if (strcmp(name, prog->name) != 0)
3129 				continue;
3130 
3131 			t->info = btf_type_info(BTF_KIND_FUNC, BTF_FUNC_STATIC, 0);
3132 			break;
3133 		}
3134 	}
3135 
3136 	sanitize = btf_needs_sanitization(obj);
3137 	if (sanitize) {
3138 		const void *raw_data;
3139 		__u32 sz;
3140 
3141 		/* clone BTF to sanitize a copy and leave the original intact */
3142 		raw_data = btf__raw_data(obj->btf, &sz);
3143 		kern_btf = btf__new(raw_data, sz);
3144 		err = libbpf_get_error(kern_btf);
3145 		if (err)
3146 			return err;
3147 
3148 		/* enforce 8-byte pointers for BPF-targeted BTFs */
3149 		btf__set_pointer_size(obj->btf, 8);
3150 		err = bpf_object__sanitize_btf(obj, kern_btf);
3151 		if (err)
3152 			return err;
3153 	}
3154 
3155 	if (obj->gen_loader) {
3156 		__u32 raw_size = 0;
3157 		const void *raw_data = btf__raw_data(kern_btf, &raw_size);
3158 
3159 		if (!raw_data)
3160 			return -ENOMEM;
3161 		bpf_gen__load_btf(obj->gen_loader, raw_data, raw_size);
3162 		/* Pretend to have valid FD to pass various fd >= 0 checks.
3163 		 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
3164 		 */
3165 		btf__set_fd(kern_btf, 0);
3166 	} else {
3167 		/* currently BPF_BTF_LOAD only supports log_level 1 */
3168 		err = btf_load_into_kernel(kern_btf, obj->log_buf, obj->log_size,
3169 					   obj->log_level ? 1 : 0);
3170 	}
3171 	if (sanitize) {
3172 		if (!err) {
3173 			/* move fd to libbpf's BTF */
3174 			btf__set_fd(obj->btf, btf__fd(kern_btf));
3175 			btf__set_fd(kern_btf, -1);
3176 		}
3177 		btf__free(kern_btf);
3178 	}
3179 report:
3180 	if (err) {
3181 		btf_mandatory = kernel_needs_btf(obj);
3182 		pr_warn("Error loading .BTF into kernel: %d. %s\n", err,
3183 			btf_mandatory ? "BTF is mandatory, can't proceed."
3184 				      : "BTF is optional, ignoring.");
3185 		if (!btf_mandatory)
3186 			err = 0;
3187 	}
3188 	return err;
3189 }
3190 
3191 static const char *elf_sym_str(const struct bpf_object *obj, size_t off)
3192 {
3193 	const char *name;
3194 
3195 	name = elf_strptr(obj->efile.elf, obj->efile.strtabidx, off);
3196 	if (!name) {
3197 		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3198 			off, obj->path, elf_errmsg(-1));
3199 		return NULL;
3200 	}
3201 
3202 	return name;
3203 }
3204 
3205 static const char *elf_sec_str(const struct bpf_object *obj, size_t off)
3206 {
3207 	const char *name;
3208 
3209 	name = elf_strptr(obj->efile.elf, obj->efile.shstrndx, off);
3210 	if (!name) {
3211 		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3212 			off, obj->path, elf_errmsg(-1));
3213 		return NULL;
3214 	}
3215 
3216 	return name;
3217 }
3218 
3219 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx)
3220 {
3221 	Elf_Scn *scn;
3222 
3223 	scn = elf_getscn(obj->efile.elf, idx);
3224 	if (!scn) {
3225 		pr_warn("elf: failed to get section(%zu) from %s: %s\n",
3226 			idx, obj->path, elf_errmsg(-1));
3227 		return NULL;
3228 	}
3229 	return scn;
3230 }
3231 
3232 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name)
3233 {
3234 	Elf_Scn *scn = NULL;
3235 	Elf *elf = obj->efile.elf;
3236 	const char *sec_name;
3237 
3238 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3239 		sec_name = elf_sec_name(obj, scn);
3240 		if (!sec_name)
3241 			return NULL;
3242 
3243 		if (strcmp(sec_name, name) != 0)
3244 			continue;
3245 
3246 		return scn;
3247 	}
3248 	return NULL;
3249 }
3250 
3251 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn)
3252 {
3253 	Elf64_Shdr *shdr;
3254 
3255 	if (!scn)
3256 		return NULL;
3257 
3258 	shdr = elf64_getshdr(scn);
3259 	if (!shdr) {
3260 		pr_warn("elf: failed to get section(%zu) header from %s: %s\n",
3261 			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3262 		return NULL;
3263 	}
3264 
3265 	return shdr;
3266 }
3267 
3268 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn)
3269 {
3270 	const char *name;
3271 	Elf64_Shdr *sh;
3272 
3273 	if (!scn)
3274 		return NULL;
3275 
3276 	sh = elf_sec_hdr(obj, scn);
3277 	if (!sh)
3278 		return NULL;
3279 
3280 	name = elf_sec_str(obj, sh->sh_name);
3281 	if (!name) {
3282 		pr_warn("elf: failed to get section(%zu) name from %s: %s\n",
3283 			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3284 		return NULL;
3285 	}
3286 
3287 	return name;
3288 }
3289 
3290 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn)
3291 {
3292 	Elf_Data *data;
3293 
3294 	if (!scn)
3295 		return NULL;
3296 
3297 	data = elf_getdata(scn, 0);
3298 	if (!data) {
3299 		pr_warn("elf: failed to get section(%zu) %s data from %s: %s\n",
3300 			elf_ndxscn(scn), elf_sec_name(obj, scn) ?: "<?>",
3301 			obj->path, elf_errmsg(-1));
3302 		return NULL;
3303 	}
3304 
3305 	return data;
3306 }
3307 
3308 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx)
3309 {
3310 	if (idx >= obj->efile.symbols->d_size / sizeof(Elf64_Sym))
3311 		return NULL;
3312 
3313 	return (Elf64_Sym *)obj->efile.symbols->d_buf + idx;
3314 }
3315 
3316 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx)
3317 {
3318 	if (idx >= data->d_size / sizeof(Elf64_Rel))
3319 		return NULL;
3320 
3321 	return (Elf64_Rel *)data->d_buf + idx;
3322 }
3323 
3324 static bool is_sec_name_dwarf(const char *name)
3325 {
3326 	/* approximation, but the actual list is too long */
3327 	return str_has_pfx(name, ".debug_");
3328 }
3329 
3330 static bool ignore_elf_section(Elf64_Shdr *hdr, const char *name)
3331 {
3332 	/* no special handling of .strtab */
3333 	if (hdr->sh_type == SHT_STRTAB)
3334 		return true;
3335 
3336 	/* ignore .llvm_addrsig section as well */
3337 	if (hdr->sh_type == SHT_LLVM_ADDRSIG)
3338 		return true;
3339 
3340 	/* no subprograms will lead to an empty .text section, ignore it */
3341 	if (hdr->sh_type == SHT_PROGBITS && hdr->sh_size == 0 &&
3342 	    strcmp(name, ".text") == 0)
3343 		return true;
3344 
3345 	/* DWARF sections */
3346 	if (is_sec_name_dwarf(name))
3347 		return true;
3348 
3349 	if (str_has_pfx(name, ".rel")) {
3350 		name += sizeof(".rel") - 1;
3351 		/* DWARF section relocations */
3352 		if (is_sec_name_dwarf(name))
3353 			return true;
3354 
3355 		/* .BTF and .BTF.ext don't need relocations */
3356 		if (strcmp(name, BTF_ELF_SEC) == 0 ||
3357 		    strcmp(name, BTF_EXT_ELF_SEC) == 0)
3358 			return true;
3359 	}
3360 
3361 	return false;
3362 }
3363 
3364 static int cmp_progs(const void *_a, const void *_b)
3365 {
3366 	const struct bpf_program *a = _a;
3367 	const struct bpf_program *b = _b;
3368 
3369 	if (a->sec_idx != b->sec_idx)
3370 		return a->sec_idx < b->sec_idx ? -1 : 1;
3371 
3372 	/* sec_insn_off can't be the same within the section */
3373 	return a->sec_insn_off < b->sec_insn_off ? -1 : 1;
3374 }
3375 
3376 static int bpf_object__elf_collect(struct bpf_object *obj)
3377 {
3378 	struct elf_sec_desc *sec_desc;
3379 	Elf *elf = obj->efile.elf;
3380 	Elf_Data *btf_ext_data = NULL;
3381 	Elf_Data *btf_data = NULL;
3382 	int idx = 0, err = 0;
3383 	const char *name;
3384 	Elf_Data *data;
3385 	Elf_Scn *scn;
3386 	Elf64_Shdr *sh;
3387 
3388 	/* ELF section indices are 0-based, but sec #0 is special "invalid"
3389 	 * section. Since section count retrieved by elf_getshdrnum() does
3390 	 * include sec #0, it is already the necessary size of an array to keep
3391 	 * all the sections.
3392 	 */
3393 	if (elf_getshdrnum(obj->efile.elf, &obj->efile.sec_cnt)) {
3394 		pr_warn("elf: failed to get the number of sections for %s: %s\n",
3395 			obj->path, elf_errmsg(-1));
3396 		return -LIBBPF_ERRNO__FORMAT;
3397 	}
3398 	obj->efile.secs = calloc(obj->efile.sec_cnt, sizeof(*obj->efile.secs));
3399 	if (!obj->efile.secs)
3400 		return -ENOMEM;
3401 
3402 	/* a bunch of ELF parsing functionality depends on processing symbols,
3403 	 * so do the first pass and find the symbol table
3404 	 */
3405 	scn = NULL;
3406 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3407 		sh = elf_sec_hdr(obj, scn);
3408 		if (!sh)
3409 			return -LIBBPF_ERRNO__FORMAT;
3410 
3411 		if (sh->sh_type == SHT_SYMTAB) {
3412 			if (obj->efile.symbols) {
3413 				pr_warn("elf: multiple symbol tables in %s\n", obj->path);
3414 				return -LIBBPF_ERRNO__FORMAT;
3415 			}
3416 
3417 			data = elf_sec_data(obj, scn);
3418 			if (!data)
3419 				return -LIBBPF_ERRNO__FORMAT;
3420 
3421 			idx = elf_ndxscn(scn);
3422 
3423 			obj->efile.symbols = data;
3424 			obj->efile.symbols_shndx = idx;
3425 			obj->efile.strtabidx = sh->sh_link;
3426 		}
3427 	}
3428 
3429 	if (!obj->efile.symbols) {
3430 		pr_warn("elf: couldn't find symbol table in %s, stripped object file?\n",
3431 			obj->path);
3432 		return -ENOENT;
3433 	}
3434 
3435 	scn = NULL;
3436 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3437 		idx = elf_ndxscn(scn);
3438 		sec_desc = &obj->efile.secs[idx];
3439 
3440 		sh = elf_sec_hdr(obj, scn);
3441 		if (!sh)
3442 			return -LIBBPF_ERRNO__FORMAT;
3443 
3444 		name = elf_sec_str(obj, sh->sh_name);
3445 		if (!name)
3446 			return -LIBBPF_ERRNO__FORMAT;
3447 
3448 		if (ignore_elf_section(sh, name))
3449 			continue;
3450 
3451 		data = elf_sec_data(obj, scn);
3452 		if (!data)
3453 			return -LIBBPF_ERRNO__FORMAT;
3454 
3455 		pr_debug("elf: section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
3456 			 idx, name, (unsigned long)data->d_size,
3457 			 (int)sh->sh_link, (unsigned long)sh->sh_flags,
3458 			 (int)sh->sh_type);
3459 
3460 		if (strcmp(name, "license") == 0) {
3461 			err = bpf_object__init_license(obj, data->d_buf, data->d_size);
3462 			if (err)
3463 				return err;
3464 		} else if (strcmp(name, "version") == 0) {
3465 			err = bpf_object__init_kversion(obj, data->d_buf, data->d_size);
3466 			if (err)
3467 				return err;
3468 		} else if (strcmp(name, "maps") == 0) {
3469 			pr_warn("elf: legacy map definitions in 'maps' section are not supported by libbpf v1.0+\n");
3470 			return -ENOTSUP;
3471 		} else if (strcmp(name, MAPS_ELF_SEC) == 0) {
3472 			obj->efile.btf_maps_shndx = idx;
3473 		} else if (strcmp(name, BTF_ELF_SEC) == 0) {
3474 			if (sh->sh_type != SHT_PROGBITS)
3475 				return -LIBBPF_ERRNO__FORMAT;
3476 			btf_data = data;
3477 		} else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
3478 			if (sh->sh_type != SHT_PROGBITS)
3479 				return -LIBBPF_ERRNO__FORMAT;
3480 			btf_ext_data = data;
3481 		} else if (sh->sh_type == SHT_SYMTAB) {
3482 			/* already processed during the first pass above */
3483 		} else if (sh->sh_type == SHT_PROGBITS && data->d_size > 0) {
3484 			if (sh->sh_flags & SHF_EXECINSTR) {
3485 				if (strcmp(name, ".text") == 0)
3486 					obj->efile.text_shndx = idx;
3487 				err = bpf_object__add_programs(obj, data, name, idx);
3488 				if (err)
3489 					return err;
3490 			} else if (strcmp(name, DATA_SEC) == 0 ||
3491 				   str_has_pfx(name, DATA_SEC ".")) {
3492 				sec_desc->sec_type = SEC_DATA;
3493 				sec_desc->shdr = sh;
3494 				sec_desc->data = data;
3495 			} else if (strcmp(name, RODATA_SEC) == 0 ||
3496 				   str_has_pfx(name, RODATA_SEC ".")) {
3497 				sec_desc->sec_type = SEC_RODATA;
3498 				sec_desc->shdr = sh;
3499 				sec_desc->data = data;
3500 			} else if (strcmp(name, STRUCT_OPS_SEC) == 0) {
3501 				obj->efile.st_ops_data = data;
3502 				obj->efile.st_ops_shndx = idx;
3503 			} else if (strcmp(name, STRUCT_OPS_LINK_SEC) == 0) {
3504 				obj->efile.st_ops_link_data = data;
3505 				obj->efile.st_ops_link_shndx = idx;
3506 			} else {
3507 				pr_info("elf: skipping unrecognized data section(%d) %s\n",
3508 					idx, name);
3509 			}
3510 		} else if (sh->sh_type == SHT_REL) {
3511 			int targ_sec_idx = sh->sh_info; /* points to other section */
3512 
3513 			if (sh->sh_entsize != sizeof(Elf64_Rel) ||
3514 			    targ_sec_idx >= obj->efile.sec_cnt)
3515 				return -LIBBPF_ERRNO__FORMAT;
3516 
3517 			/* Only do relo for section with exec instructions */
3518 			if (!section_have_execinstr(obj, targ_sec_idx) &&
3519 			    strcmp(name, ".rel" STRUCT_OPS_SEC) &&
3520 			    strcmp(name, ".rel" STRUCT_OPS_LINK_SEC) &&
3521 			    strcmp(name, ".rel" MAPS_ELF_SEC)) {
3522 				pr_info("elf: skipping relo section(%d) %s for section(%d) %s\n",
3523 					idx, name, targ_sec_idx,
3524 					elf_sec_name(obj, elf_sec_by_idx(obj, targ_sec_idx)) ?: "<?>");
3525 				continue;
3526 			}
3527 
3528 			sec_desc->sec_type = SEC_RELO;
3529 			sec_desc->shdr = sh;
3530 			sec_desc->data = data;
3531 		} else if (sh->sh_type == SHT_NOBITS && (strcmp(name, BSS_SEC) == 0 ||
3532 							 str_has_pfx(name, BSS_SEC "."))) {
3533 			sec_desc->sec_type = SEC_BSS;
3534 			sec_desc->shdr = sh;
3535 			sec_desc->data = data;
3536 		} else {
3537 			pr_info("elf: skipping section(%d) %s (size %zu)\n", idx, name,
3538 				(size_t)sh->sh_size);
3539 		}
3540 	}
3541 
3542 	if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) {
3543 		pr_warn("elf: symbol strings section missing or invalid in %s\n", obj->path);
3544 		return -LIBBPF_ERRNO__FORMAT;
3545 	}
3546 
3547 	/* sort BPF programs by section name and in-section instruction offset
3548 	 * for faster search
3549 	 */
3550 	if (obj->nr_programs)
3551 		qsort(obj->programs, obj->nr_programs, sizeof(*obj->programs), cmp_progs);
3552 
3553 	return bpf_object__init_btf(obj, btf_data, btf_ext_data);
3554 }
3555 
3556 static bool sym_is_extern(const Elf64_Sym *sym)
3557 {
3558 	int bind = ELF64_ST_BIND(sym->st_info);
3559 	/* externs are symbols w/ type=NOTYPE, bind=GLOBAL|WEAK, section=UND */
3560 	return sym->st_shndx == SHN_UNDEF &&
3561 	       (bind == STB_GLOBAL || bind == STB_WEAK) &&
3562 	       ELF64_ST_TYPE(sym->st_info) == STT_NOTYPE;
3563 }
3564 
3565 static bool sym_is_subprog(const Elf64_Sym *sym, int text_shndx)
3566 {
3567 	int bind = ELF64_ST_BIND(sym->st_info);
3568 	int type = ELF64_ST_TYPE(sym->st_info);
3569 
3570 	/* in .text section */
3571 	if (sym->st_shndx != text_shndx)
3572 		return false;
3573 
3574 	/* local function */
3575 	if (bind == STB_LOCAL && type == STT_SECTION)
3576 		return true;
3577 
3578 	/* global function */
3579 	return bind == STB_GLOBAL && type == STT_FUNC;
3580 }
3581 
3582 static int find_extern_btf_id(const struct btf *btf, const char *ext_name)
3583 {
3584 	const struct btf_type *t;
3585 	const char *tname;
3586 	int i, n;
3587 
3588 	if (!btf)
3589 		return -ESRCH;
3590 
3591 	n = btf__type_cnt(btf);
3592 	for (i = 1; i < n; i++) {
3593 		t = btf__type_by_id(btf, i);
3594 
3595 		if (!btf_is_var(t) && !btf_is_func(t))
3596 			continue;
3597 
3598 		tname = btf__name_by_offset(btf, t->name_off);
3599 		if (strcmp(tname, ext_name))
3600 			continue;
3601 
3602 		if (btf_is_var(t) &&
3603 		    btf_var(t)->linkage != BTF_VAR_GLOBAL_EXTERN)
3604 			return -EINVAL;
3605 
3606 		if (btf_is_func(t) && btf_func_linkage(t) != BTF_FUNC_EXTERN)
3607 			return -EINVAL;
3608 
3609 		return i;
3610 	}
3611 
3612 	return -ENOENT;
3613 }
3614 
3615 static int find_extern_sec_btf_id(struct btf *btf, int ext_btf_id) {
3616 	const struct btf_var_secinfo *vs;
3617 	const struct btf_type *t;
3618 	int i, j, n;
3619 
3620 	if (!btf)
3621 		return -ESRCH;
3622 
3623 	n = btf__type_cnt(btf);
3624 	for (i = 1; i < n; i++) {
3625 		t = btf__type_by_id(btf, i);
3626 
3627 		if (!btf_is_datasec(t))
3628 			continue;
3629 
3630 		vs = btf_var_secinfos(t);
3631 		for (j = 0; j < btf_vlen(t); j++, vs++) {
3632 			if (vs->type == ext_btf_id)
3633 				return i;
3634 		}
3635 	}
3636 
3637 	return -ENOENT;
3638 }
3639 
3640 static enum kcfg_type find_kcfg_type(const struct btf *btf, int id,
3641 				     bool *is_signed)
3642 {
3643 	const struct btf_type *t;
3644 	const char *name;
3645 
3646 	t = skip_mods_and_typedefs(btf, id, NULL);
3647 	name = btf__name_by_offset(btf, t->name_off);
3648 
3649 	if (is_signed)
3650 		*is_signed = false;
3651 	switch (btf_kind(t)) {
3652 	case BTF_KIND_INT: {
3653 		int enc = btf_int_encoding(t);
3654 
3655 		if (enc & BTF_INT_BOOL)
3656 			return t->size == 1 ? KCFG_BOOL : KCFG_UNKNOWN;
3657 		if (is_signed)
3658 			*is_signed = enc & BTF_INT_SIGNED;
3659 		if (t->size == 1)
3660 			return KCFG_CHAR;
3661 		if (t->size < 1 || t->size > 8 || (t->size & (t->size - 1)))
3662 			return KCFG_UNKNOWN;
3663 		return KCFG_INT;
3664 	}
3665 	case BTF_KIND_ENUM:
3666 		if (t->size != 4)
3667 			return KCFG_UNKNOWN;
3668 		if (strcmp(name, "libbpf_tristate"))
3669 			return KCFG_UNKNOWN;
3670 		return KCFG_TRISTATE;
3671 	case BTF_KIND_ENUM64:
3672 		if (strcmp(name, "libbpf_tristate"))
3673 			return KCFG_UNKNOWN;
3674 		return KCFG_TRISTATE;
3675 	case BTF_KIND_ARRAY:
3676 		if (btf_array(t)->nelems == 0)
3677 			return KCFG_UNKNOWN;
3678 		if (find_kcfg_type(btf, btf_array(t)->type, NULL) != KCFG_CHAR)
3679 			return KCFG_UNKNOWN;
3680 		return KCFG_CHAR_ARR;
3681 	default:
3682 		return KCFG_UNKNOWN;
3683 	}
3684 }
3685 
3686 static int cmp_externs(const void *_a, const void *_b)
3687 {
3688 	const struct extern_desc *a = _a;
3689 	const struct extern_desc *b = _b;
3690 
3691 	if (a->type != b->type)
3692 		return a->type < b->type ? -1 : 1;
3693 
3694 	if (a->type == EXT_KCFG) {
3695 		/* descending order by alignment requirements */
3696 		if (a->kcfg.align != b->kcfg.align)
3697 			return a->kcfg.align > b->kcfg.align ? -1 : 1;
3698 		/* ascending order by size, within same alignment class */
3699 		if (a->kcfg.sz != b->kcfg.sz)
3700 			return a->kcfg.sz < b->kcfg.sz ? -1 : 1;
3701 	}
3702 
3703 	/* resolve ties by name */
3704 	return strcmp(a->name, b->name);
3705 }
3706 
3707 static int find_int_btf_id(const struct btf *btf)
3708 {
3709 	const struct btf_type *t;
3710 	int i, n;
3711 
3712 	n = btf__type_cnt(btf);
3713 	for (i = 1; i < n; i++) {
3714 		t = btf__type_by_id(btf, i);
3715 
3716 		if (btf_is_int(t) && btf_int_bits(t) == 32)
3717 			return i;
3718 	}
3719 
3720 	return 0;
3721 }
3722 
3723 static int add_dummy_ksym_var(struct btf *btf)
3724 {
3725 	int i, int_btf_id, sec_btf_id, dummy_var_btf_id;
3726 	const struct btf_var_secinfo *vs;
3727 	const struct btf_type *sec;
3728 
3729 	if (!btf)
3730 		return 0;
3731 
3732 	sec_btf_id = btf__find_by_name_kind(btf, KSYMS_SEC,
3733 					    BTF_KIND_DATASEC);
3734 	if (sec_btf_id < 0)
3735 		return 0;
3736 
3737 	sec = btf__type_by_id(btf, sec_btf_id);
3738 	vs = btf_var_secinfos(sec);
3739 	for (i = 0; i < btf_vlen(sec); i++, vs++) {
3740 		const struct btf_type *vt;
3741 
3742 		vt = btf__type_by_id(btf, vs->type);
3743 		if (btf_is_func(vt))
3744 			break;
3745 	}
3746 
3747 	/* No func in ksyms sec.  No need to add dummy var. */
3748 	if (i == btf_vlen(sec))
3749 		return 0;
3750 
3751 	int_btf_id = find_int_btf_id(btf);
3752 	dummy_var_btf_id = btf__add_var(btf,
3753 					"dummy_ksym",
3754 					BTF_VAR_GLOBAL_ALLOCATED,
3755 					int_btf_id);
3756 	if (dummy_var_btf_id < 0)
3757 		pr_warn("cannot create a dummy_ksym var\n");
3758 
3759 	return dummy_var_btf_id;
3760 }
3761 
3762 static int bpf_object__collect_externs(struct bpf_object *obj)
3763 {
3764 	struct btf_type *sec, *kcfg_sec = NULL, *ksym_sec = NULL;
3765 	const struct btf_type *t;
3766 	struct extern_desc *ext;
3767 	int i, n, off, dummy_var_btf_id;
3768 	const char *ext_name, *sec_name;
3769 	Elf_Scn *scn;
3770 	Elf64_Shdr *sh;
3771 
3772 	if (!obj->efile.symbols)
3773 		return 0;
3774 
3775 	scn = elf_sec_by_idx(obj, obj->efile.symbols_shndx);
3776 	sh = elf_sec_hdr(obj, scn);
3777 	if (!sh || sh->sh_entsize != sizeof(Elf64_Sym))
3778 		return -LIBBPF_ERRNO__FORMAT;
3779 
3780 	dummy_var_btf_id = add_dummy_ksym_var(obj->btf);
3781 	if (dummy_var_btf_id < 0)
3782 		return dummy_var_btf_id;
3783 
3784 	n = sh->sh_size / sh->sh_entsize;
3785 	pr_debug("looking for externs among %d symbols...\n", n);
3786 
3787 	for (i = 0; i < n; i++) {
3788 		Elf64_Sym *sym = elf_sym_by_idx(obj, i);
3789 
3790 		if (!sym)
3791 			return -LIBBPF_ERRNO__FORMAT;
3792 		if (!sym_is_extern(sym))
3793 			continue;
3794 		ext_name = elf_sym_str(obj, sym->st_name);
3795 		if (!ext_name || !ext_name[0])
3796 			continue;
3797 
3798 		ext = obj->externs;
3799 		ext = libbpf_reallocarray(ext, obj->nr_extern + 1, sizeof(*ext));
3800 		if (!ext)
3801 			return -ENOMEM;
3802 		obj->externs = ext;
3803 		ext = &ext[obj->nr_extern];
3804 		memset(ext, 0, sizeof(*ext));
3805 		obj->nr_extern++;
3806 
3807 		ext->btf_id = find_extern_btf_id(obj->btf, ext_name);
3808 		if (ext->btf_id <= 0) {
3809 			pr_warn("failed to find BTF for extern '%s': %d\n",
3810 				ext_name, ext->btf_id);
3811 			return ext->btf_id;
3812 		}
3813 		t = btf__type_by_id(obj->btf, ext->btf_id);
3814 		ext->name = btf__name_by_offset(obj->btf, t->name_off);
3815 		ext->sym_idx = i;
3816 		ext->is_weak = ELF64_ST_BIND(sym->st_info) == STB_WEAK;
3817 
3818 		ext->sec_btf_id = find_extern_sec_btf_id(obj->btf, ext->btf_id);
3819 		if (ext->sec_btf_id <= 0) {
3820 			pr_warn("failed to find BTF for extern '%s' [%d] section: %d\n",
3821 				ext_name, ext->btf_id, ext->sec_btf_id);
3822 			return ext->sec_btf_id;
3823 		}
3824 		sec = (void *)btf__type_by_id(obj->btf, ext->sec_btf_id);
3825 		sec_name = btf__name_by_offset(obj->btf, sec->name_off);
3826 
3827 		if (strcmp(sec_name, KCONFIG_SEC) == 0) {
3828 			if (btf_is_func(t)) {
3829 				pr_warn("extern function %s is unsupported under %s section\n",
3830 					ext->name, KCONFIG_SEC);
3831 				return -ENOTSUP;
3832 			}
3833 			kcfg_sec = sec;
3834 			ext->type = EXT_KCFG;
3835 			ext->kcfg.sz = btf__resolve_size(obj->btf, t->type);
3836 			if (ext->kcfg.sz <= 0) {
3837 				pr_warn("failed to resolve size of extern (kcfg) '%s': %d\n",
3838 					ext_name, ext->kcfg.sz);
3839 				return ext->kcfg.sz;
3840 			}
3841 			ext->kcfg.align = btf__align_of(obj->btf, t->type);
3842 			if (ext->kcfg.align <= 0) {
3843 				pr_warn("failed to determine alignment of extern (kcfg) '%s': %d\n",
3844 					ext_name, ext->kcfg.align);
3845 				return -EINVAL;
3846 			}
3847 			ext->kcfg.type = find_kcfg_type(obj->btf, t->type,
3848 							&ext->kcfg.is_signed);
3849 			if (ext->kcfg.type == KCFG_UNKNOWN) {
3850 				pr_warn("extern (kcfg) '%s': type is unsupported\n", ext_name);
3851 				return -ENOTSUP;
3852 			}
3853 		} else if (strcmp(sec_name, KSYMS_SEC) == 0) {
3854 			ksym_sec = sec;
3855 			ext->type = EXT_KSYM;
3856 			skip_mods_and_typedefs(obj->btf, t->type,
3857 					       &ext->ksym.type_id);
3858 		} else {
3859 			pr_warn("unrecognized extern section '%s'\n", sec_name);
3860 			return -ENOTSUP;
3861 		}
3862 	}
3863 	pr_debug("collected %d externs total\n", obj->nr_extern);
3864 
3865 	if (!obj->nr_extern)
3866 		return 0;
3867 
3868 	/* sort externs by type, for kcfg ones also by (align, size, name) */
3869 	qsort(obj->externs, obj->nr_extern, sizeof(*ext), cmp_externs);
3870 
3871 	/* for .ksyms section, we need to turn all externs into allocated
3872 	 * variables in BTF to pass kernel verification; we do this by
3873 	 * pretending that each extern is a 8-byte variable
3874 	 */
3875 	if (ksym_sec) {
3876 		/* find existing 4-byte integer type in BTF to use for fake
3877 		 * extern variables in DATASEC
3878 		 */
3879 		int int_btf_id = find_int_btf_id(obj->btf);
3880 		/* For extern function, a dummy_var added earlier
3881 		 * will be used to replace the vs->type and
3882 		 * its name string will be used to refill
3883 		 * the missing param's name.
3884 		 */
3885 		const struct btf_type *dummy_var;
3886 
3887 		dummy_var = btf__type_by_id(obj->btf, dummy_var_btf_id);
3888 		for (i = 0; i < obj->nr_extern; i++) {
3889 			ext = &obj->externs[i];
3890 			if (ext->type != EXT_KSYM)
3891 				continue;
3892 			pr_debug("extern (ksym) #%d: symbol %d, name %s\n",
3893 				 i, ext->sym_idx, ext->name);
3894 		}
3895 
3896 		sec = ksym_sec;
3897 		n = btf_vlen(sec);
3898 		for (i = 0, off = 0; i < n; i++, off += sizeof(int)) {
3899 			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
3900 			struct btf_type *vt;
3901 
3902 			vt = (void *)btf__type_by_id(obj->btf, vs->type);
3903 			ext_name = btf__name_by_offset(obj->btf, vt->name_off);
3904 			ext = find_extern_by_name(obj, ext_name);
3905 			if (!ext) {
3906 				pr_warn("failed to find extern definition for BTF %s '%s'\n",
3907 					btf_kind_str(vt), ext_name);
3908 				return -ESRCH;
3909 			}
3910 			if (btf_is_func(vt)) {
3911 				const struct btf_type *func_proto;
3912 				struct btf_param *param;
3913 				int j;
3914 
3915 				func_proto = btf__type_by_id(obj->btf,
3916 							     vt->type);
3917 				param = btf_params(func_proto);
3918 				/* Reuse the dummy_var string if the
3919 				 * func proto does not have param name.
3920 				 */
3921 				for (j = 0; j < btf_vlen(func_proto); j++)
3922 					if (param[j].type && !param[j].name_off)
3923 						param[j].name_off =
3924 							dummy_var->name_off;
3925 				vs->type = dummy_var_btf_id;
3926 				vt->info &= ~0xffff;
3927 				vt->info |= BTF_FUNC_GLOBAL;
3928 			} else {
3929 				btf_var(vt)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
3930 				vt->type = int_btf_id;
3931 			}
3932 			vs->offset = off;
3933 			vs->size = sizeof(int);
3934 		}
3935 		sec->size = off;
3936 	}
3937 
3938 	if (kcfg_sec) {
3939 		sec = kcfg_sec;
3940 		/* for kcfg externs calculate their offsets within a .kconfig map */
3941 		off = 0;
3942 		for (i = 0; i < obj->nr_extern; i++) {
3943 			ext = &obj->externs[i];
3944 			if (ext->type != EXT_KCFG)
3945 				continue;
3946 
3947 			ext->kcfg.data_off = roundup(off, ext->kcfg.align);
3948 			off = ext->kcfg.data_off + ext->kcfg.sz;
3949 			pr_debug("extern (kcfg) #%d: symbol %d, off %u, name %s\n",
3950 				 i, ext->sym_idx, ext->kcfg.data_off, ext->name);
3951 		}
3952 		sec->size = off;
3953 		n = btf_vlen(sec);
3954 		for (i = 0; i < n; i++) {
3955 			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
3956 
3957 			t = btf__type_by_id(obj->btf, vs->type);
3958 			ext_name = btf__name_by_offset(obj->btf, t->name_off);
3959 			ext = find_extern_by_name(obj, ext_name);
3960 			if (!ext) {
3961 				pr_warn("failed to find extern definition for BTF var '%s'\n",
3962 					ext_name);
3963 				return -ESRCH;
3964 			}
3965 			btf_var(t)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
3966 			vs->offset = ext->kcfg.data_off;
3967 		}
3968 	}
3969 	return 0;
3970 }
3971 
3972 static bool prog_is_subprog(const struct bpf_object *obj, const struct bpf_program *prog)
3973 {
3974 	return prog->sec_idx == obj->efile.text_shndx && obj->nr_programs > 1;
3975 }
3976 
3977 struct bpf_program *
3978 bpf_object__find_program_by_name(const struct bpf_object *obj,
3979 				 const char *name)
3980 {
3981 	struct bpf_program *prog;
3982 
3983 	bpf_object__for_each_program(prog, obj) {
3984 		if (prog_is_subprog(obj, prog))
3985 			continue;
3986 		if (!strcmp(prog->name, name))
3987 			return prog;
3988 	}
3989 	return errno = ENOENT, NULL;
3990 }
3991 
3992 static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
3993 				      int shndx)
3994 {
3995 	switch (obj->efile.secs[shndx].sec_type) {
3996 	case SEC_BSS:
3997 	case SEC_DATA:
3998 	case SEC_RODATA:
3999 		return true;
4000 	default:
4001 		return false;
4002 	}
4003 }
4004 
4005 static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
4006 				      int shndx)
4007 {
4008 	return shndx == obj->efile.btf_maps_shndx;
4009 }
4010 
4011 static enum libbpf_map_type
4012 bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
4013 {
4014 	if (shndx == obj->efile.symbols_shndx)
4015 		return LIBBPF_MAP_KCONFIG;
4016 
4017 	switch (obj->efile.secs[shndx].sec_type) {
4018 	case SEC_BSS:
4019 		return LIBBPF_MAP_BSS;
4020 	case SEC_DATA:
4021 		return LIBBPF_MAP_DATA;
4022 	case SEC_RODATA:
4023 		return LIBBPF_MAP_RODATA;
4024 	default:
4025 		return LIBBPF_MAP_UNSPEC;
4026 	}
4027 }
4028 
4029 static int bpf_program__record_reloc(struct bpf_program *prog,
4030 				     struct reloc_desc *reloc_desc,
4031 				     __u32 insn_idx, const char *sym_name,
4032 				     const Elf64_Sym *sym, const Elf64_Rel *rel)
4033 {
4034 	struct bpf_insn *insn = &prog->insns[insn_idx];
4035 	size_t map_idx, nr_maps = prog->obj->nr_maps;
4036 	struct bpf_object *obj = prog->obj;
4037 	__u32 shdr_idx = sym->st_shndx;
4038 	enum libbpf_map_type type;
4039 	const char *sym_sec_name;
4040 	struct bpf_map *map;
4041 
4042 	if (!is_call_insn(insn) && !is_ldimm64_insn(insn)) {
4043 		pr_warn("prog '%s': invalid relo against '%s' for insns[%d].code 0x%x\n",
4044 			prog->name, sym_name, insn_idx, insn->code);
4045 		return -LIBBPF_ERRNO__RELOC;
4046 	}
4047 
4048 	if (sym_is_extern(sym)) {
4049 		int sym_idx = ELF64_R_SYM(rel->r_info);
4050 		int i, n = obj->nr_extern;
4051 		struct extern_desc *ext;
4052 
4053 		for (i = 0; i < n; i++) {
4054 			ext = &obj->externs[i];
4055 			if (ext->sym_idx == sym_idx)
4056 				break;
4057 		}
4058 		if (i >= n) {
4059 			pr_warn("prog '%s': extern relo failed to find extern for '%s' (%d)\n",
4060 				prog->name, sym_name, sym_idx);
4061 			return -LIBBPF_ERRNO__RELOC;
4062 		}
4063 		pr_debug("prog '%s': found extern #%d '%s' (sym %d) for insn #%u\n",
4064 			 prog->name, i, ext->name, ext->sym_idx, insn_idx);
4065 		if (insn->code == (BPF_JMP | BPF_CALL))
4066 			reloc_desc->type = RELO_EXTERN_CALL;
4067 		else
4068 			reloc_desc->type = RELO_EXTERN_LD64;
4069 		reloc_desc->insn_idx = insn_idx;
4070 		reloc_desc->ext_idx = i;
4071 		return 0;
4072 	}
4073 
4074 	/* sub-program call relocation */
4075 	if (is_call_insn(insn)) {
4076 		if (insn->src_reg != BPF_PSEUDO_CALL) {
4077 			pr_warn("prog '%s': incorrect bpf_call opcode\n", prog->name);
4078 			return -LIBBPF_ERRNO__RELOC;
4079 		}
4080 		/* text_shndx can be 0, if no default "main" program exists */
4081 		if (!shdr_idx || shdr_idx != obj->efile.text_shndx) {
4082 			sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4083 			pr_warn("prog '%s': bad call relo against '%s' in section '%s'\n",
4084 				prog->name, sym_name, sym_sec_name);
4085 			return -LIBBPF_ERRNO__RELOC;
4086 		}
4087 		if (sym->st_value % BPF_INSN_SZ) {
4088 			pr_warn("prog '%s': bad call relo against '%s' at offset %zu\n",
4089 				prog->name, sym_name, (size_t)sym->st_value);
4090 			return -LIBBPF_ERRNO__RELOC;
4091 		}
4092 		reloc_desc->type = RELO_CALL;
4093 		reloc_desc->insn_idx = insn_idx;
4094 		reloc_desc->sym_off = sym->st_value;
4095 		return 0;
4096 	}
4097 
4098 	if (!shdr_idx || shdr_idx >= SHN_LORESERVE) {
4099 		pr_warn("prog '%s': invalid relo against '%s' in special section 0x%x; forgot to initialize global var?..\n",
4100 			prog->name, sym_name, shdr_idx);
4101 		return -LIBBPF_ERRNO__RELOC;
4102 	}
4103 
4104 	/* loading subprog addresses */
4105 	if (sym_is_subprog(sym, obj->efile.text_shndx)) {
4106 		/* global_func: sym->st_value = offset in the section, insn->imm = 0.
4107 		 * local_func: sym->st_value = 0, insn->imm = offset in the section.
4108 		 */
4109 		if ((sym->st_value % BPF_INSN_SZ) || (insn->imm % BPF_INSN_SZ)) {
4110 			pr_warn("prog '%s': bad subprog addr relo against '%s' at offset %zu+%d\n",
4111 				prog->name, sym_name, (size_t)sym->st_value, insn->imm);
4112 			return -LIBBPF_ERRNO__RELOC;
4113 		}
4114 
4115 		reloc_desc->type = RELO_SUBPROG_ADDR;
4116 		reloc_desc->insn_idx = insn_idx;
4117 		reloc_desc->sym_off = sym->st_value;
4118 		return 0;
4119 	}
4120 
4121 	type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
4122 	sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4123 
4124 	/* generic map reference relocation */
4125 	if (type == LIBBPF_MAP_UNSPEC) {
4126 		if (!bpf_object__shndx_is_maps(obj, shdr_idx)) {
4127 			pr_warn("prog '%s': bad map relo against '%s' in section '%s'\n",
4128 				prog->name, sym_name, sym_sec_name);
4129 			return -LIBBPF_ERRNO__RELOC;
4130 		}
4131 		for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4132 			map = &obj->maps[map_idx];
4133 			if (map->libbpf_type != type ||
4134 			    map->sec_idx != sym->st_shndx ||
4135 			    map->sec_offset != sym->st_value)
4136 				continue;
4137 			pr_debug("prog '%s': found map %zd (%s, sec %d, off %zu) for insn #%u\n",
4138 				 prog->name, map_idx, map->name, map->sec_idx,
4139 				 map->sec_offset, insn_idx);
4140 			break;
4141 		}
4142 		if (map_idx >= nr_maps) {
4143 			pr_warn("prog '%s': map relo failed to find map for section '%s', off %zu\n",
4144 				prog->name, sym_sec_name, (size_t)sym->st_value);
4145 			return -LIBBPF_ERRNO__RELOC;
4146 		}
4147 		reloc_desc->type = RELO_LD64;
4148 		reloc_desc->insn_idx = insn_idx;
4149 		reloc_desc->map_idx = map_idx;
4150 		reloc_desc->sym_off = 0; /* sym->st_value determines map_idx */
4151 		return 0;
4152 	}
4153 
4154 	/* global data map relocation */
4155 	if (!bpf_object__shndx_is_data(obj, shdr_idx)) {
4156 		pr_warn("prog '%s': bad data relo against section '%s'\n",
4157 			prog->name, sym_sec_name);
4158 		return -LIBBPF_ERRNO__RELOC;
4159 	}
4160 	for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4161 		map = &obj->maps[map_idx];
4162 		if (map->libbpf_type != type || map->sec_idx != sym->st_shndx)
4163 			continue;
4164 		pr_debug("prog '%s': found data map %zd (%s, sec %d, off %zu) for insn %u\n",
4165 			 prog->name, map_idx, map->name, map->sec_idx,
4166 			 map->sec_offset, insn_idx);
4167 		break;
4168 	}
4169 	if (map_idx >= nr_maps) {
4170 		pr_warn("prog '%s': data relo failed to find map for section '%s'\n",
4171 			prog->name, sym_sec_name);
4172 		return -LIBBPF_ERRNO__RELOC;
4173 	}
4174 
4175 	reloc_desc->type = RELO_DATA;
4176 	reloc_desc->insn_idx = insn_idx;
4177 	reloc_desc->map_idx = map_idx;
4178 	reloc_desc->sym_off = sym->st_value;
4179 	return 0;
4180 }
4181 
4182 static bool prog_contains_insn(const struct bpf_program *prog, size_t insn_idx)
4183 {
4184 	return insn_idx >= prog->sec_insn_off &&
4185 	       insn_idx < prog->sec_insn_off + prog->sec_insn_cnt;
4186 }
4187 
4188 static struct bpf_program *find_prog_by_sec_insn(const struct bpf_object *obj,
4189 						 size_t sec_idx, size_t insn_idx)
4190 {
4191 	int l = 0, r = obj->nr_programs - 1, m;
4192 	struct bpf_program *prog;
4193 
4194 	if (!obj->nr_programs)
4195 		return NULL;
4196 
4197 	while (l < r) {
4198 		m = l + (r - l + 1) / 2;
4199 		prog = &obj->programs[m];
4200 
4201 		if (prog->sec_idx < sec_idx ||
4202 		    (prog->sec_idx == sec_idx && prog->sec_insn_off <= insn_idx))
4203 			l = m;
4204 		else
4205 			r = m - 1;
4206 	}
4207 	/* matching program could be at index l, but it still might be the
4208 	 * wrong one, so we need to double check conditions for the last time
4209 	 */
4210 	prog = &obj->programs[l];
4211 	if (prog->sec_idx == sec_idx && prog_contains_insn(prog, insn_idx))
4212 		return prog;
4213 	return NULL;
4214 }
4215 
4216 static int
4217 bpf_object__collect_prog_relos(struct bpf_object *obj, Elf64_Shdr *shdr, Elf_Data *data)
4218 {
4219 	const char *relo_sec_name, *sec_name;
4220 	size_t sec_idx = shdr->sh_info, sym_idx;
4221 	struct bpf_program *prog;
4222 	struct reloc_desc *relos;
4223 	int err, i, nrels;
4224 	const char *sym_name;
4225 	__u32 insn_idx;
4226 	Elf_Scn *scn;
4227 	Elf_Data *scn_data;
4228 	Elf64_Sym *sym;
4229 	Elf64_Rel *rel;
4230 
4231 	if (sec_idx >= obj->efile.sec_cnt)
4232 		return -EINVAL;
4233 
4234 	scn = elf_sec_by_idx(obj, sec_idx);
4235 	scn_data = elf_sec_data(obj, scn);
4236 
4237 	relo_sec_name = elf_sec_str(obj, shdr->sh_name);
4238 	sec_name = elf_sec_name(obj, scn);
4239 	if (!relo_sec_name || !sec_name)
4240 		return -EINVAL;
4241 
4242 	pr_debug("sec '%s': collecting relocation for section(%zu) '%s'\n",
4243 		 relo_sec_name, sec_idx, sec_name);
4244 	nrels = shdr->sh_size / shdr->sh_entsize;
4245 
4246 	for (i = 0; i < nrels; i++) {
4247 		rel = elf_rel_by_idx(data, i);
4248 		if (!rel) {
4249 			pr_warn("sec '%s': failed to get relo #%d\n", relo_sec_name, i);
4250 			return -LIBBPF_ERRNO__FORMAT;
4251 		}
4252 
4253 		sym_idx = ELF64_R_SYM(rel->r_info);
4254 		sym = elf_sym_by_idx(obj, sym_idx);
4255 		if (!sym) {
4256 			pr_warn("sec '%s': symbol #%zu not found for relo #%d\n",
4257 				relo_sec_name, sym_idx, i);
4258 			return -LIBBPF_ERRNO__FORMAT;
4259 		}
4260 
4261 		if (sym->st_shndx >= obj->efile.sec_cnt) {
4262 			pr_warn("sec '%s': corrupted symbol #%zu pointing to invalid section #%zu for relo #%d\n",
4263 				relo_sec_name, sym_idx, (size_t)sym->st_shndx, i);
4264 			return -LIBBPF_ERRNO__FORMAT;
4265 		}
4266 
4267 		if (rel->r_offset % BPF_INSN_SZ || rel->r_offset >= scn_data->d_size) {
4268 			pr_warn("sec '%s': invalid offset 0x%zx for relo #%d\n",
4269 				relo_sec_name, (size_t)rel->r_offset, i);
4270 			return -LIBBPF_ERRNO__FORMAT;
4271 		}
4272 
4273 		insn_idx = rel->r_offset / BPF_INSN_SZ;
4274 		/* relocations against static functions are recorded as
4275 		 * relocations against the section that contains a function;
4276 		 * in such case, symbol will be STT_SECTION and sym.st_name
4277 		 * will point to empty string (0), so fetch section name
4278 		 * instead
4279 		 */
4280 		if (ELF64_ST_TYPE(sym->st_info) == STT_SECTION && sym->st_name == 0)
4281 			sym_name = elf_sec_name(obj, elf_sec_by_idx(obj, sym->st_shndx));
4282 		else
4283 			sym_name = elf_sym_str(obj, sym->st_name);
4284 		sym_name = sym_name ?: "<?";
4285 
4286 		pr_debug("sec '%s': relo #%d: insn #%u against '%s'\n",
4287 			 relo_sec_name, i, insn_idx, sym_name);
4288 
4289 		prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
4290 		if (!prog) {
4291 			pr_debug("sec '%s': relo #%d: couldn't find program in section '%s' for insn #%u, probably overridden weak function, skipping...\n",
4292 				relo_sec_name, i, sec_name, insn_idx);
4293 			continue;
4294 		}
4295 
4296 		relos = libbpf_reallocarray(prog->reloc_desc,
4297 					    prog->nr_reloc + 1, sizeof(*relos));
4298 		if (!relos)
4299 			return -ENOMEM;
4300 		prog->reloc_desc = relos;
4301 
4302 		/* adjust insn_idx to local BPF program frame of reference */
4303 		insn_idx -= prog->sec_insn_off;
4304 		err = bpf_program__record_reloc(prog, &relos[prog->nr_reloc],
4305 						insn_idx, sym_name, sym, rel);
4306 		if (err)
4307 			return err;
4308 
4309 		prog->nr_reloc++;
4310 	}
4311 	return 0;
4312 }
4313 
4314 static int map_fill_btf_type_info(struct bpf_object *obj, struct bpf_map *map)
4315 {
4316 	int id;
4317 
4318 	if (!obj->btf)
4319 		return -ENOENT;
4320 
4321 	/* if it's BTF-defined map, we don't need to search for type IDs.
4322 	 * For struct_ops map, it does not need btf_key_type_id and
4323 	 * btf_value_type_id.
4324 	 */
4325 	if (map->sec_idx == obj->efile.btf_maps_shndx || bpf_map__is_struct_ops(map))
4326 		return 0;
4327 
4328 	/*
4329 	 * LLVM annotates global data differently in BTF, that is,
4330 	 * only as '.data', '.bss' or '.rodata'.
4331 	 */
4332 	if (!bpf_map__is_internal(map))
4333 		return -ENOENT;
4334 
4335 	id = btf__find_by_name(obj->btf, map->real_name);
4336 	if (id < 0)
4337 		return id;
4338 
4339 	map->btf_key_type_id = 0;
4340 	map->btf_value_type_id = id;
4341 	return 0;
4342 }
4343 
4344 static int bpf_get_map_info_from_fdinfo(int fd, struct bpf_map_info *info)
4345 {
4346 	char file[PATH_MAX], buff[4096];
4347 	FILE *fp;
4348 	__u32 val;
4349 	int err;
4350 
4351 	snprintf(file, sizeof(file), "/proc/%d/fdinfo/%d", getpid(), fd);
4352 	memset(info, 0, sizeof(*info));
4353 
4354 	fp = fopen(file, "re");
4355 	if (!fp) {
4356 		err = -errno;
4357 		pr_warn("failed to open %s: %d. No procfs support?\n", file,
4358 			err);
4359 		return err;
4360 	}
4361 
4362 	while (fgets(buff, sizeof(buff), fp)) {
4363 		if (sscanf(buff, "map_type:\t%u", &val) == 1)
4364 			info->type = val;
4365 		else if (sscanf(buff, "key_size:\t%u", &val) == 1)
4366 			info->key_size = val;
4367 		else if (sscanf(buff, "value_size:\t%u", &val) == 1)
4368 			info->value_size = val;
4369 		else if (sscanf(buff, "max_entries:\t%u", &val) == 1)
4370 			info->max_entries = val;
4371 		else if (sscanf(buff, "map_flags:\t%i", &val) == 1)
4372 			info->map_flags = val;
4373 	}
4374 
4375 	fclose(fp);
4376 
4377 	return 0;
4378 }
4379 
4380 bool bpf_map__autocreate(const struct bpf_map *map)
4381 {
4382 	return map->autocreate;
4383 }
4384 
4385 int bpf_map__set_autocreate(struct bpf_map *map, bool autocreate)
4386 {
4387 	if (map->obj->loaded)
4388 		return libbpf_err(-EBUSY);
4389 
4390 	map->autocreate = autocreate;
4391 	return 0;
4392 }
4393 
4394 int bpf_map__reuse_fd(struct bpf_map *map, int fd)
4395 {
4396 	struct bpf_map_info info;
4397 	__u32 len = sizeof(info), name_len;
4398 	int new_fd, err;
4399 	char *new_name;
4400 
4401 	memset(&info, 0, len);
4402 	err = bpf_map_get_info_by_fd(fd, &info, &len);
4403 	if (err && errno == EINVAL)
4404 		err = bpf_get_map_info_from_fdinfo(fd, &info);
4405 	if (err)
4406 		return libbpf_err(err);
4407 
4408 	name_len = strlen(info.name);
4409 	if (name_len == BPF_OBJ_NAME_LEN - 1 && strncmp(map->name, info.name, name_len) == 0)
4410 		new_name = strdup(map->name);
4411 	else
4412 		new_name = strdup(info.name);
4413 
4414 	if (!new_name)
4415 		return libbpf_err(-errno);
4416 
4417 	/*
4418 	 * Like dup(), but make sure new FD is >= 3 and has O_CLOEXEC set.
4419 	 * This is similar to what we do in ensure_good_fd(), but without
4420 	 * closing original FD.
4421 	 */
4422 	new_fd = fcntl(fd, F_DUPFD_CLOEXEC, 3);
4423 	if (new_fd < 0) {
4424 		err = -errno;
4425 		goto err_free_new_name;
4426 	}
4427 
4428 	err = zclose(map->fd);
4429 	if (err) {
4430 		err = -errno;
4431 		goto err_close_new_fd;
4432 	}
4433 	free(map->name);
4434 
4435 	map->fd = new_fd;
4436 	map->name = new_name;
4437 	map->def.type = info.type;
4438 	map->def.key_size = info.key_size;
4439 	map->def.value_size = info.value_size;
4440 	map->def.max_entries = info.max_entries;
4441 	map->def.map_flags = info.map_flags;
4442 	map->btf_key_type_id = info.btf_key_type_id;
4443 	map->btf_value_type_id = info.btf_value_type_id;
4444 	map->reused = true;
4445 	map->map_extra = info.map_extra;
4446 
4447 	return 0;
4448 
4449 err_close_new_fd:
4450 	close(new_fd);
4451 err_free_new_name:
4452 	free(new_name);
4453 	return libbpf_err(err);
4454 }
4455 
4456 __u32 bpf_map__max_entries(const struct bpf_map *map)
4457 {
4458 	return map->def.max_entries;
4459 }
4460 
4461 struct bpf_map *bpf_map__inner_map(struct bpf_map *map)
4462 {
4463 	if (!bpf_map_type__is_map_in_map(map->def.type))
4464 		return errno = EINVAL, NULL;
4465 
4466 	return map->inner_map;
4467 }
4468 
4469 int bpf_map__set_max_entries(struct bpf_map *map, __u32 max_entries)
4470 {
4471 	if (map->obj->loaded)
4472 		return libbpf_err(-EBUSY);
4473 
4474 	map->def.max_entries = max_entries;
4475 
4476 	/* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
4477 	if (map_is_ringbuf(map))
4478 		map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
4479 
4480 	return 0;
4481 }
4482 
4483 static int
4484 bpf_object__probe_loading(struct bpf_object *obj)
4485 {
4486 	char *cp, errmsg[STRERR_BUFSIZE];
4487 	struct bpf_insn insns[] = {
4488 		BPF_MOV64_IMM(BPF_REG_0, 0),
4489 		BPF_EXIT_INSN(),
4490 	};
4491 	int ret, insn_cnt = ARRAY_SIZE(insns);
4492 
4493 	if (obj->gen_loader)
4494 		return 0;
4495 
4496 	ret = bump_rlimit_memlock();
4497 	if (ret)
4498 		pr_warn("Failed to bump RLIMIT_MEMLOCK (err = %d), you might need to do it explicitly!\n", ret);
4499 
4500 	/* make sure basic loading works */
4501 	ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4502 	if (ret < 0)
4503 		ret = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, NULL);
4504 	if (ret < 0) {
4505 		ret = errno;
4506 		cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4507 		pr_warn("Error in %s():%s(%d). Couldn't load trivial BPF "
4508 			"program. Make sure your kernel supports BPF "
4509 			"(CONFIG_BPF_SYSCALL=y) and/or that RLIMIT_MEMLOCK is "
4510 			"set to big enough value.\n", __func__, cp, ret);
4511 		return -ret;
4512 	}
4513 	close(ret);
4514 
4515 	return 0;
4516 }
4517 
4518 static int probe_fd(int fd)
4519 {
4520 	if (fd >= 0)
4521 		close(fd);
4522 	return fd >= 0;
4523 }
4524 
4525 static int probe_kern_prog_name(void)
4526 {
4527 	const size_t attr_sz = offsetofend(union bpf_attr, prog_name);
4528 	struct bpf_insn insns[] = {
4529 		BPF_MOV64_IMM(BPF_REG_0, 0),
4530 		BPF_EXIT_INSN(),
4531 	};
4532 	union bpf_attr attr;
4533 	int ret;
4534 
4535 	memset(&attr, 0, attr_sz);
4536 	attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
4537 	attr.license = ptr_to_u64("GPL");
4538 	attr.insns = ptr_to_u64(insns);
4539 	attr.insn_cnt = (__u32)ARRAY_SIZE(insns);
4540 	libbpf_strlcpy(attr.prog_name, "libbpf_nametest", sizeof(attr.prog_name));
4541 
4542 	/* make sure loading with name works */
4543 	ret = sys_bpf_prog_load(&attr, attr_sz, PROG_LOAD_ATTEMPTS);
4544 	return probe_fd(ret);
4545 }
4546 
4547 static int probe_kern_global_data(void)
4548 {
4549 	char *cp, errmsg[STRERR_BUFSIZE];
4550 	struct bpf_insn insns[] = {
4551 		BPF_LD_MAP_VALUE(BPF_REG_1, 0, 16),
4552 		BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 42),
4553 		BPF_MOV64_IMM(BPF_REG_0, 0),
4554 		BPF_EXIT_INSN(),
4555 	};
4556 	int ret, map, insn_cnt = ARRAY_SIZE(insns);
4557 
4558 	map = bpf_map_create(BPF_MAP_TYPE_ARRAY, "libbpf_global", sizeof(int), 32, 1, NULL);
4559 	if (map < 0) {
4560 		ret = -errno;
4561 		cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4562 		pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
4563 			__func__, cp, -ret);
4564 		return ret;
4565 	}
4566 
4567 	insns[0].imm = map;
4568 
4569 	ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4570 	close(map);
4571 	return probe_fd(ret);
4572 }
4573 
4574 static int probe_kern_btf(void)
4575 {
4576 	static const char strs[] = "\0int";
4577 	__u32 types[] = {
4578 		/* int */
4579 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),
4580 	};
4581 
4582 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4583 					     strs, sizeof(strs)));
4584 }
4585 
4586 static int probe_kern_btf_func(void)
4587 {
4588 	static const char strs[] = "\0int\0x\0a";
4589 	/* void x(int a) {} */
4590 	__u32 types[] = {
4591 		/* int */
4592 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4593 		/* FUNC_PROTO */                                /* [2] */
4594 		BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
4595 		BTF_PARAM_ENC(7, 1),
4596 		/* FUNC x */                                    /* [3] */
4597 		BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0), 2),
4598 	};
4599 
4600 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4601 					     strs, sizeof(strs)));
4602 }
4603 
4604 static int probe_kern_btf_func_global(void)
4605 {
4606 	static const char strs[] = "\0int\0x\0a";
4607 	/* static void x(int a) {} */
4608 	__u32 types[] = {
4609 		/* int */
4610 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4611 		/* FUNC_PROTO */                                /* [2] */
4612 		BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
4613 		BTF_PARAM_ENC(7, 1),
4614 		/* FUNC x BTF_FUNC_GLOBAL */                    /* [3] */
4615 		BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, BTF_FUNC_GLOBAL), 2),
4616 	};
4617 
4618 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4619 					     strs, sizeof(strs)));
4620 }
4621 
4622 static int probe_kern_btf_datasec(void)
4623 {
4624 	static const char strs[] = "\0x\0.data";
4625 	/* static int a; */
4626 	__u32 types[] = {
4627 		/* int */
4628 		BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4629 		/* VAR x */                                     /* [2] */
4630 		BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
4631 		BTF_VAR_STATIC,
4632 		/* DATASEC val */                               /* [3] */
4633 		BTF_TYPE_ENC(3, BTF_INFO_ENC(BTF_KIND_DATASEC, 0, 1), 4),
4634 		BTF_VAR_SECINFO_ENC(2, 0, 4),
4635 	};
4636 
4637 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4638 					     strs, sizeof(strs)));
4639 }
4640 
4641 static int probe_kern_btf_float(void)
4642 {
4643 	static const char strs[] = "\0float";
4644 	__u32 types[] = {
4645 		/* float */
4646 		BTF_TYPE_FLOAT_ENC(1, 4),
4647 	};
4648 
4649 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4650 					     strs, sizeof(strs)));
4651 }
4652 
4653 static int probe_kern_btf_decl_tag(void)
4654 {
4655 	static const char strs[] = "\0tag";
4656 	__u32 types[] = {
4657 		/* int */
4658 		BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4659 		/* VAR x */                                     /* [2] */
4660 		BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
4661 		BTF_VAR_STATIC,
4662 		/* attr */
4663 		BTF_TYPE_DECL_TAG_ENC(1, 2, -1),
4664 	};
4665 
4666 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4667 					     strs, sizeof(strs)));
4668 }
4669 
4670 static int probe_kern_btf_type_tag(void)
4671 {
4672 	static const char strs[] = "\0tag";
4673 	__u32 types[] = {
4674 		/* int */
4675 		BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4),		/* [1] */
4676 		/* attr */
4677 		BTF_TYPE_TYPE_TAG_ENC(1, 1),				/* [2] */
4678 		/* ptr */
4679 		BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_PTR, 0, 0), 2),	/* [3] */
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_array_mmap(void)
4687 {
4688 	LIBBPF_OPTS(bpf_map_create_opts, opts, .map_flags = BPF_F_MMAPABLE);
4689 	int fd;
4690 
4691 	fd = bpf_map_create(BPF_MAP_TYPE_ARRAY, "libbpf_mmap", sizeof(int), sizeof(int), 1, &opts);
4692 	return probe_fd(fd);
4693 }
4694 
4695 static int probe_kern_exp_attach_type(void)
4696 {
4697 	LIBBPF_OPTS(bpf_prog_load_opts, opts, .expected_attach_type = BPF_CGROUP_INET_SOCK_CREATE);
4698 	struct bpf_insn insns[] = {
4699 		BPF_MOV64_IMM(BPF_REG_0, 0),
4700 		BPF_EXIT_INSN(),
4701 	};
4702 	int fd, insn_cnt = ARRAY_SIZE(insns);
4703 
4704 	/* use any valid combination of program type and (optional)
4705 	 * non-zero expected attach type (i.e., not a BPF_CGROUP_INET_INGRESS)
4706 	 * to see if kernel supports expected_attach_type field for
4707 	 * BPF_PROG_LOAD command
4708 	 */
4709 	fd = bpf_prog_load(BPF_PROG_TYPE_CGROUP_SOCK, NULL, "GPL", insns, insn_cnt, &opts);
4710 	return probe_fd(fd);
4711 }
4712 
4713 static int probe_kern_probe_read_kernel(void)
4714 {
4715 	struct bpf_insn insns[] = {
4716 		BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),	/* r1 = r10 (fp) */
4717 		BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -8),	/* r1 += -8 */
4718 		BPF_MOV64_IMM(BPF_REG_2, 8),		/* r2 = 8 */
4719 		BPF_MOV64_IMM(BPF_REG_3, 0),		/* r3 = 0 */
4720 		BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_probe_read_kernel),
4721 		BPF_EXIT_INSN(),
4722 	};
4723 	int fd, insn_cnt = ARRAY_SIZE(insns);
4724 
4725 	fd = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, NULL);
4726 	return probe_fd(fd);
4727 }
4728 
4729 static int probe_prog_bind_map(void)
4730 {
4731 	char *cp, errmsg[STRERR_BUFSIZE];
4732 	struct bpf_insn insns[] = {
4733 		BPF_MOV64_IMM(BPF_REG_0, 0),
4734 		BPF_EXIT_INSN(),
4735 	};
4736 	int ret, map, prog, insn_cnt = ARRAY_SIZE(insns);
4737 
4738 	map = bpf_map_create(BPF_MAP_TYPE_ARRAY, "libbpf_det_bind", sizeof(int), 32, 1, NULL);
4739 	if (map < 0) {
4740 		ret = -errno;
4741 		cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4742 		pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
4743 			__func__, cp, -ret);
4744 		return ret;
4745 	}
4746 
4747 	prog = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4748 	if (prog < 0) {
4749 		close(map);
4750 		return 0;
4751 	}
4752 
4753 	ret = bpf_prog_bind_map(prog, map, NULL);
4754 
4755 	close(map);
4756 	close(prog);
4757 
4758 	return ret >= 0;
4759 }
4760 
4761 static int probe_module_btf(void)
4762 {
4763 	static const char strs[] = "\0int";
4764 	__u32 types[] = {
4765 		/* int */
4766 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),
4767 	};
4768 	struct bpf_btf_info info;
4769 	__u32 len = sizeof(info);
4770 	char name[16];
4771 	int fd, err;
4772 
4773 	fd = libbpf__load_raw_btf((char *)types, sizeof(types), strs, sizeof(strs));
4774 	if (fd < 0)
4775 		return 0; /* BTF not supported at all */
4776 
4777 	memset(&info, 0, sizeof(info));
4778 	info.name = ptr_to_u64(name);
4779 	info.name_len = sizeof(name);
4780 
4781 	/* check that BPF_OBJ_GET_INFO_BY_FD supports specifying name pointer;
4782 	 * kernel's module BTF support coincides with support for
4783 	 * name/name_len fields in struct bpf_btf_info.
4784 	 */
4785 	err = bpf_btf_get_info_by_fd(fd, &info, &len);
4786 	close(fd);
4787 	return !err;
4788 }
4789 
4790 static int probe_perf_link(void)
4791 {
4792 	struct bpf_insn insns[] = {
4793 		BPF_MOV64_IMM(BPF_REG_0, 0),
4794 		BPF_EXIT_INSN(),
4795 	};
4796 	int prog_fd, link_fd, err;
4797 
4798 	prog_fd = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL",
4799 				insns, ARRAY_SIZE(insns), NULL);
4800 	if (prog_fd < 0)
4801 		return -errno;
4802 
4803 	/* use invalid perf_event FD to get EBADF, if link is supported;
4804 	 * otherwise EINVAL should be returned
4805 	 */
4806 	link_fd = bpf_link_create(prog_fd, -1, BPF_PERF_EVENT, NULL);
4807 	err = -errno; /* close() can clobber errno */
4808 
4809 	if (link_fd >= 0)
4810 		close(link_fd);
4811 	close(prog_fd);
4812 
4813 	return link_fd < 0 && err == -EBADF;
4814 }
4815 
4816 static int probe_kern_bpf_cookie(void)
4817 {
4818 	struct bpf_insn insns[] = {
4819 		BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_get_attach_cookie),
4820 		BPF_EXIT_INSN(),
4821 	};
4822 	int ret, insn_cnt = ARRAY_SIZE(insns);
4823 
4824 	ret = bpf_prog_load(BPF_PROG_TYPE_KPROBE, NULL, "GPL", insns, insn_cnt, NULL);
4825 	return probe_fd(ret);
4826 }
4827 
4828 static int probe_kern_btf_enum64(void)
4829 {
4830 	static const char strs[] = "\0enum64";
4831 	__u32 types[] = {
4832 		BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_ENUM64, 0, 0), 8),
4833 	};
4834 
4835 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4836 					     strs, sizeof(strs)));
4837 }
4838 
4839 static int probe_kern_syscall_wrapper(void);
4840 
4841 enum kern_feature_result {
4842 	FEAT_UNKNOWN = 0,
4843 	FEAT_SUPPORTED = 1,
4844 	FEAT_MISSING = 2,
4845 };
4846 
4847 typedef int (*feature_probe_fn)(void);
4848 
4849 static struct kern_feature_desc {
4850 	const char *desc;
4851 	feature_probe_fn probe;
4852 	enum kern_feature_result res;
4853 } feature_probes[__FEAT_CNT] = {
4854 	[FEAT_PROG_NAME] = {
4855 		"BPF program name", probe_kern_prog_name,
4856 	},
4857 	[FEAT_GLOBAL_DATA] = {
4858 		"global variables", probe_kern_global_data,
4859 	},
4860 	[FEAT_BTF] = {
4861 		"minimal BTF", probe_kern_btf,
4862 	},
4863 	[FEAT_BTF_FUNC] = {
4864 		"BTF functions", probe_kern_btf_func,
4865 	},
4866 	[FEAT_BTF_GLOBAL_FUNC] = {
4867 		"BTF global function", probe_kern_btf_func_global,
4868 	},
4869 	[FEAT_BTF_DATASEC] = {
4870 		"BTF data section and variable", probe_kern_btf_datasec,
4871 	},
4872 	[FEAT_ARRAY_MMAP] = {
4873 		"ARRAY map mmap()", probe_kern_array_mmap,
4874 	},
4875 	[FEAT_EXP_ATTACH_TYPE] = {
4876 		"BPF_PROG_LOAD expected_attach_type attribute",
4877 		probe_kern_exp_attach_type,
4878 	},
4879 	[FEAT_PROBE_READ_KERN] = {
4880 		"bpf_probe_read_kernel() helper", probe_kern_probe_read_kernel,
4881 	},
4882 	[FEAT_PROG_BIND_MAP] = {
4883 		"BPF_PROG_BIND_MAP support", probe_prog_bind_map,
4884 	},
4885 	[FEAT_MODULE_BTF] = {
4886 		"module BTF support", probe_module_btf,
4887 	},
4888 	[FEAT_BTF_FLOAT] = {
4889 		"BTF_KIND_FLOAT support", probe_kern_btf_float,
4890 	},
4891 	[FEAT_PERF_LINK] = {
4892 		"BPF perf link support", probe_perf_link,
4893 	},
4894 	[FEAT_BTF_DECL_TAG] = {
4895 		"BTF_KIND_DECL_TAG support", probe_kern_btf_decl_tag,
4896 	},
4897 	[FEAT_BTF_TYPE_TAG] = {
4898 		"BTF_KIND_TYPE_TAG support", probe_kern_btf_type_tag,
4899 	},
4900 	[FEAT_MEMCG_ACCOUNT] = {
4901 		"memcg-based memory accounting", probe_memcg_account,
4902 	},
4903 	[FEAT_BPF_COOKIE] = {
4904 		"BPF cookie support", probe_kern_bpf_cookie,
4905 	},
4906 	[FEAT_BTF_ENUM64] = {
4907 		"BTF_KIND_ENUM64 support", probe_kern_btf_enum64,
4908 	},
4909 	[FEAT_SYSCALL_WRAPPER] = {
4910 		"Kernel using syscall wrapper", probe_kern_syscall_wrapper,
4911 	},
4912 };
4913 
4914 bool kernel_supports(const struct bpf_object *obj, enum kern_feature_id feat_id)
4915 {
4916 	struct kern_feature_desc *feat = &feature_probes[feat_id];
4917 	int ret;
4918 
4919 	if (obj && obj->gen_loader)
4920 		/* To generate loader program assume the latest kernel
4921 		 * to avoid doing extra prog_load, map_create syscalls.
4922 		 */
4923 		return true;
4924 
4925 	if (READ_ONCE(feat->res) == FEAT_UNKNOWN) {
4926 		ret = feat->probe();
4927 		if (ret > 0) {
4928 			WRITE_ONCE(feat->res, FEAT_SUPPORTED);
4929 		} else if (ret == 0) {
4930 			WRITE_ONCE(feat->res, FEAT_MISSING);
4931 		} else {
4932 			pr_warn("Detection of kernel %s support failed: %d\n", feat->desc, ret);
4933 			WRITE_ONCE(feat->res, FEAT_MISSING);
4934 		}
4935 	}
4936 
4937 	return READ_ONCE(feat->res) == FEAT_SUPPORTED;
4938 }
4939 
4940 static bool map_is_reuse_compat(const struct bpf_map *map, int map_fd)
4941 {
4942 	struct bpf_map_info map_info;
4943 	char msg[STRERR_BUFSIZE];
4944 	__u32 map_info_len = sizeof(map_info);
4945 	int err;
4946 
4947 	memset(&map_info, 0, map_info_len);
4948 	err = bpf_map_get_info_by_fd(map_fd, &map_info, &map_info_len);
4949 	if (err && errno == EINVAL)
4950 		err = bpf_get_map_info_from_fdinfo(map_fd, &map_info);
4951 	if (err) {
4952 		pr_warn("failed to get map info for map FD %d: %s\n", map_fd,
4953 			libbpf_strerror_r(errno, msg, sizeof(msg)));
4954 		return false;
4955 	}
4956 
4957 	return (map_info.type == map->def.type &&
4958 		map_info.key_size == map->def.key_size &&
4959 		map_info.value_size == map->def.value_size &&
4960 		map_info.max_entries == map->def.max_entries &&
4961 		map_info.map_flags == map->def.map_flags &&
4962 		map_info.map_extra == map->map_extra);
4963 }
4964 
4965 static int
4966 bpf_object__reuse_map(struct bpf_map *map)
4967 {
4968 	char *cp, errmsg[STRERR_BUFSIZE];
4969 	int err, pin_fd;
4970 
4971 	pin_fd = bpf_obj_get(map->pin_path);
4972 	if (pin_fd < 0) {
4973 		err = -errno;
4974 		if (err == -ENOENT) {
4975 			pr_debug("found no pinned map to reuse at '%s'\n",
4976 				 map->pin_path);
4977 			return 0;
4978 		}
4979 
4980 		cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
4981 		pr_warn("couldn't retrieve pinned map '%s': %s\n",
4982 			map->pin_path, cp);
4983 		return err;
4984 	}
4985 
4986 	if (!map_is_reuse_compat(map, pin_fd)) {
4987 		pr_warn("couldn't reuse pinned map at '%s': parameter mismatch\n",
4988 			map->pin_path);
4989 		close(pin_fd);
4990 		return -EINVAL;
4991 	}
4992 
4993 	err = bpf_map__reuse_fd(map, pin_fd);
4994 	close(pin_fd);
4995 	if (err)
4996 		return err;
4997 
4998 	map->pinned = true;
4999 	pr_debug("reused pinned map at '%s'\n", map->pin_path);
5000 
5001 	return 0;
5002 }
5003 
5004 static int
5005 bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
5006 {
5007 	enum libbpf_map_type map_type = map->libbpf_type;
5008 	char *cp, errmsg[STRERR_BUFSIZE];
5009 	int err, zero = 0;
5010 
5011 	if (obj->gen_loader) {
5012 		bpf_gen__map_update_elem(obj->gen_loader, map - obj->maps,
5013 					 map->mmaped, map->def.value_size);
5014 		if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG)
5015 			bpf_gen__map_freeze(obj->gen_loader, map - obj->maps);
5016 		return 0;
5017 	}
5018 	err = bpf_map_update_elem(map->fd, &zero, map->mmaped, 0);
5019 	if (err) {
5020 		err = -errno;
5021 		cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5022 		pr_warn("Error setting initial map(%s) contents: %s\n",
5023 			map->name, cp);
5024 		return err;
5025 	}
5026 
5027 	/* Freeze .rodata and .kconfig map as read-only from syscall side. */
5028 	if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG) {
5029 		err = bpf_map_freeze(map->fd);
5030 		if (err) {
5031 			err = -errno;
5032 			cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5033 			pr_warn("Error freezing map(%s) as read-only: %s\n",
5034 				map->name, cp);
5035 			return err;
5036 		}
5037 	}
5038 	return 0;
5039 }
5040 
5041 static void bpf_map__destroy(struct bpf_map *map);
5042 
5043 static int bpf_object__create_map(struct bpf_object *obj, struct bpf_map *map, bool is_inner)
5044 {
5045 	LIBBPF_OPTS(bpf_map_create_opts, create_attr);
5046 	struct bpf_map_def *def = &map->def;
5047 	const char *map_name = NULL;
5048 	int err = 0;
5049 
5050 	if (kernel_supports(obj, FEAT_PROG_NAME))
5051 		map_name = map->name;
5052 	create_attr.map_ifindex = map->map_ifindex;
5053 	create_attr.map_flags = def->map_flags;
5054 	create_attr.numa_node = map->numa_node;
5055 	create_attr.map_extra = map->map_extra;
5056 
5057 	if (bpf_map__is_struct_ops(map))
5058 		create_attr.btf_vmlinux_value_type_id = map->btf_vmlinux_value_type_id;
5059 
5060 	if (obj->btf && btf__fd(obj->btf) >= 0) {
5061 		create_attr.btf_fd = btf__fd(obj->btf);
5062 		create_attr.btf_key_type_id = map->btf_key_type_id;
5063 		create_attr.btf_value_type_id = map->btf_value_type_id;
5064 	}
5065 
5066 	if (bpf_map_type__is_map_in_map(def->type)) {
5067 		if (map->inner_map) {
5068 			err = bpf_object__create_map(obj, map->inner_map, true);
5069 			if (err) {
5070 				pr_warn("map '%s': failed to create inner map: %d\n",
5071 					map->name, err);
5072 				return err;
5073 			}
5074 			map->inner_map_fd = bpf_map__fd(map->inner_map);
5075 		}
5076 		if (map->inner_map_fd >= 0)
5077 			create_attr.inner_map_fd = map->inner_map_fd;
5078 	}
5079 
5080 	switch (def->type) {
5081 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
5082 	case BPF_MAP_TYPE_CGROUP_ARRAY:
5083 	case BPF_MAP_TYPE_STACK_TRACE:
5084 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
5085 	case BPF_MAP_TYPE_HASH_OF_MAPS:
5086 	case BPF_MAP_TYPE_DEVMAP:
5087 	case BPF_MAP_TYPE_DEVMAP_HASH:
5088 	case BPF_MAP_TYPE_CPUMAP:
5089 	case BPF_MAP_TYPE_XSKMAP:
5090 	case BPF_MAP_TYPE_SOCKMAP:
5091 	case BPF_MAP_TYPE_SOCKHASH:
5092 	case BPF_MAP_TYPE_QUEUE:
5093 	case BPF_MAP_TYPE_STACK:
5094 		create_attr.btf_fd = 0;
5095 		create_attr.btf_key_type_id = 0;
5096 		create_attr.btf_value_type_id = 0;
5097 		map->btf_key_type_id = 0;
5098 		map->btf_value_type_id = 0;
5099 	default:
5100 		break;
5101 	}
5102 
5103 	if (obj->gen_loader) {
5104 		bpf_gen__map_create(obj->gen_loader, def->type, map_name,
5105 				    def->key_size, def->value_size, def->max_entries,
5106 				    &create_attr, is_inner ? -1 : map - obj->maps);
5107 		/* Pretend to have valid FD to pass various fd >= 0 checks.
5108 		 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
5109 		 */
5110 		map->fd = 0;
5111 	} else {
5112 		map->fd = bpf_map_create(def->type, map_name,
5113 					 def->key_size, def->value_size,
5114 					 def->max_entries, &create_attr);
5115 	}
5116 	if (map->fd < 0 && (create_attr.btf_key_type_id ||
5117 			    create_attr.btf_value_type_id)) {
5118 		char *cp, errmsg[STRERR_BUFSIZE];
5119 
5120 		err = -errno;
5121 		cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5122 		pr_warn("Error in bpf_create_map_xattr(%s):%s(%d). Retrying without BTF.\n",
5123 			map->name, cp, err);
5124 		create_attr.btf_fd = 0;
5125 		create_attr.btf_key_type_id = 0;
5126 		create_attr.btf_value_type_id = 0;
5127 		map->btf_key_type_id = 0;
5128 		map->btf_value_type_id = 0;
5129 		map->fd = bpf_map_create(def->type, map_name,
5130 					 def->key_size, def->value_size,
5131 					 def->max_entries, &create_attr);
5132 	}
5133 
5134 	err = map->fd < 0 ? -errno : 0;
5135 
5136 	if (bpf_map_type__is_map_in_map(def->type) && map->inner_map) {
5137 		if (obj->gen_loader)
5138 			map->inner_map->fd = -1;
5139 		bpf_map__destroy(map->inner_map);
5140 		zfree(&map->inner_map);
5141 	}
5142 
5143 	return err;
5144 }
5145 
5146 static int init_map_in_map_slots(struct bpf_object *obj, struct bpf_map *map)
5147 {
5148 	const struct bpf_map *targ_map;
5149 	unsigned int i;
5150 	int fd, err = 0;
5151 
5152 	for (i = 0; i < map->init_slots_sz; i++) {
5153 		if (!map->init_slots[i])
5154 			continue;
5155 
5156 		targ_map = map->init_slots[i];
5157 		fd = bpf_map__fd(targ_map);
5158 
5159 		if (obj->gen_loader) {
5160 			bpf_gen__populate_outer_map(obj->gen_loader,
5161 						    map - obj->maps, i,
5162 						    targ_map - obj->maps);
5163 		} else {
5164 			err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5165 		}
5166 		if (err) {
5167 			err = -errno;
5168 			pr_warn("map '%s': failed to initialize slot [%d] to map '%s' fd=%d: %d\n",
5169 				map->name, i, targ_map->name, fd, err);
5170 			return err;
5171 		}
5172 		pr_debug("map '%s': slot [%d] set to map '%s' fd=%d\n",
5173 			 map->name, i, targ_map->name, fd);
5174 	}
5175 
5176 	zfree(&map->init_slots);
5177 	map->init_slots_sz = 0;
5178 
5179 	return 0;
5180 }
5181 
5182 static int init_prog_array_slots(struct bpf_object *obj, struct bpf_map *map)
5183 {
5184 	const struct bpf_program *targ_prog;
5185 	unsigned int i;
5186 	int fd, err;
5187 
5188 	if (obj->gen_loader)
5189 		return -ENOTSUP;
5190 
5191 	for (i = 0; i < map->init_slots_sz; i++) {
5192 		if (!map->init_slots[i])
5193 			continue;
5194 
5195 		targ_prog = map->init_slots[i];
5196 		fd = bpf_program__fd(targ_prog);
5197 
5198 		err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5199 		if (err) {
5200 			err = -errno;
5201 			pr_warn("map '%s': failed to initialize slot [%d] to prog '%s' fd=%d: %d\n",
5202 				map->name, i, targ_prog->name, fd, err);
5203 			return err;
5204 		}
5205 		pr_debug("map '%s': slot [%d] set to prog '%s' fd=%d\n",
5206 			 map->name, i, targ_prog->name, fd);
5207 	}
5208 
5209 	zfree(&map->init_slots);
5210 	map->init_slots_sz = 0;
5211 
5212 	return 0;
5213 }
5214 
5215 static int bpf_object_init_prog_arrays(struct bpf_object *obj)
5216 {
5217 	struct bpf_map *map;
5218 	int i, err;
5219 
5220 	for (i = 0; i < obj->nr_maps; i++) {
5221 		map = &obj->maps[i];
5222 
5223 		if (!map->init_slots_sz || map->def.type != BPF_MAP_TYPE_PROG_ARRAY)
5224 			continue;
5225 
5226 		err = init_prog_array_slots(obj, map);
5227 		if (err < 0) {
5228 			zclose(map->fd);
5229 			return err;
5230 		}
5231 	}
5232 	return 0;
5233 }
5234 
5235 static int map_set_def_max_entries(struct bpf_map *map)
5236 {
5237 	if (map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY && !map->def.max_entries) {
5238 		int nr_cpus;
5239 
5240 		nr_cpus = libbpf_num_possible_cpus();
5241 		if (nr_cpus < 0) {
5242 			pr_warn("map '%s': failed to determine number of system CPUs: %d\n",
5243 				map->name, nr_cpus);
5244 			return nr_cpus;
5245 		}
5246 		pr_debug("map '%s': setting size to %d\n", map->name, nr_cpus);
5247 		map->def.max_entries = nr_cpus;
5248 	}
5249 
5250 	return 0;
5251 }
5252 
5253 static int
5254 bpf_object__create_maps(struct bpf_object *obj)
5255 {
5256 	struct bpf_map *map;
5257 	char *cp, errmsg[STRERR_BUFSIZE];
5258 	unsigned int i, j;
5259 	int err;
5260 	bool retried;
5261 
5262 	for (i = 0; i < obj->nr_maps; i++) {
5263 		map = &obj->maps[i];
5264 
5265 		/* To support old kernels, we skip creating global data maps
5266 		 * (.rodata, .data, .kconfig, etc); later on, during program
5267 		 * loading, if we detect that at least one of the to-be-loaded
5268 		 * programs is referencing any global data map, we'll error
5269 		 * out with program name and relocation index logged.
5270 		 * This approach allows to accommodate Clang emitting
5271 		 * unnecessary .rodata.str1.1 sections for string literals,
5272 		 * but also it allows to have CO-RE applications that use
5273 		 * global variables in some of BPF programs, but not others.
5274 		 * If those global variable-using programs are not loaded at
5275 		 * runtime due to bpf_program__set_autoload(prog, false),
5276 		 * bpf_object loading will succeed just fine even on old
5277 		 * kernels.
5278 		 */
5279 		if (bpf_map__is_internal(map) && !kernel_supports(obj, FEAT_GLOBAL_DATA))
5280 			map->autocreate = false;
5281 
5282 		if (!map->autocreate) {
5283 			pr_debug("map '%s': skipped auto-creating...\n", map->name);
5284 			continue;
5285 		}
5286 
5287 		err = map_set_def_max_entries(map);
5288 		if (err)
5289 			goto err_out;
5290 
5291 		retried = false;
5292 retry:
5293 		if (map->pin_path) {
5294 			err = bpf_object__reuse_map(map);
5295 			if (err) {
5296 				pr_warn("map '%s': error reusing pinned map\n",
5297 					map->name);
5298 				goto err_out;
5299 			}
5300 			if (retried && map->fd < 0) {
5301 				pr_warn("map '%s': cannot find pinned map\n",
5302 					map->name);
5303 				err = -ENOENT;
5304 				goto err_out;
5305 			}
5306 		}
5307 
5308 		if (map->fd >= 0) {
5309 			pr_debug("map '%s': skipping creation (preset fd=%d)\n",
5310 				 map->name, map->fd);
5311 		} else {
5312 			err = bpf_object__create_map(obj, map, false);
5313 			if (err)
5314 				goto err_out;
5315 
5316 			pr_debug("map '%s': created successfully, fd=%d\n",
5317 				 map->name, map->fd);
5318 
5319 			if (bpf_map__is_internal(map)) {
5320 				err = bpf_object__populate_internal_map(obj, map);
5321 				if (err < 0) {
5322 					zclose(map->fd);
5323 					goto err_out;
5324 				}
5325 			}
5326 
5327 			if (map->init_slots_sz && map->def.type != BPF_MAP_TYPE_PROG_ARRAY) {
5328 				err = init_map_in_map_slots(obj, map);
5329 				if (err < 0) {
5330 					zclose(map->fd);
5331 					goto err_out;
5332 				}
5333 			}
5334 		}
5335 
5336 		if (map->pin_path && !map->pinned) {
5337 			err = bpf_map__pin(map, NULL);
5338 			if (err) {
5339 				zclose(map->fd);
5340 				if (!retried && err == -EEXIST) {
5341 					retried = true;
5342 					goto retry;
5343 				}
5344 				pr_warn("map '%s': failed to auto-pin at '%s': %d\n",
5345 					map->name, map->pin_path, err);
5346 				goto err_out;
5347 			}
5348 		}
5349 	}
5350 
5351 	return 0;
5352 
5353 err_out:
5354 	cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5355 	pr_warn("map '%s': failed to create: %s(%d)\n", map->name, cp, err);
5356 	pr_perm_msg(err);
5357 	for (j = 0; j < i; j++)
5358 		zclose(obj->maps[j].fd);
5359 	return err;
5360 }
5361 
5362 static bool bpf_core_is_flavor_sep(const char *s)
5363 {
5364 	/* check X___Y name pattern, where X and Y are not underscores */
5365 	return s[0] != '_' &&				      /* X */
5366 	       s[1] == '_' && s[2] == '_' && s[3] == '_' &&   /* ___ */
5367 	       s[4] != '_';				      /* Y */
5368 }
5369 
5370 /* Given 'some_struct_name___with_flavor' return the length of a name prefix
5371  * before last triple underscore. Struct name part after last triple
5372  * underscore is ignored by BPF CO-RE relocation during relocation matching.
5373  */
5374 size_t bpf_core_essential_name_len(const char *name)
5375 {
5376 	size_t n = strlen(name);
5377 	int i;
5378 
5379 	for (i = n - 5; i >= 0; i--) {
5380 		if (bpf_core_is_flavor_sep(name + i))
5381 			return i + 1;
5382 	}
5383 	return n;
5384 }
5385 
5386 void bpf_core_free_cands(struct bpf_core_cand_list *cands)
5387 {
5388 	if (!cands)
5389 		return;
5390 
5391 	free(cands->cands);
5392 	free(cands);
5393 }
5394 
5395 int bpf_core_add_cands(struct bpf_core_cand *local_cand,
5396 		       size_t local_essent_len,
5397 		       const struct btf *targ_btf,
5398 		       const char *targ_btf_name,
5399 		       int targ_start_id,
5400 		       struct bpf_core_cand_list *cands)
5401 {
5402 	struct bpf_core_cand *new_cands, *cand;
5403 	const struct btf_type *t, *local_t;
5404 	const char *targ_name, *local_name;
5405 	size_t targ_essent_len;
5406 	int n, i;
5407 
5408 	local_t = btf__type_by_id(local_cand->btf, local_cand->id);
5409 	local_name = btf__str_by_offset(local_cand->btf, local_t->name_off);
5410 
5411 	n = btf__type_cnt(targ_btf);
5412 	for (i = targ_start_id; i < n; i++) {
5413 		t = btf__type_by_id(targ_btf, i);
5414 		if (!btf_kind_core_compat(t, local_t))
5415 			continue;
5416 
5417 		targ_name = btf__name_by_offset(targ_btf, t->name_off);
5418 		if (str_is_empty(targ_name))
5419 			continue;
5420 
5421 		targ_essent_len = bpf_core_essential_name_len(targ_name);
5422 		if (targ_essent_len != local_essent_len)
5423 			continue;
5424 
5425 		if (strncmp(local_name, targ_name, local_essent_len) != 0)
5426 			continue;
5427 
5428 		pr_debug("CO-RE relocating [%d] %s %s: found target candidate [%d] %s %s in [%s]\n",
5429 			 local_cand->id, btf_kind_str(local_t),
5430 			 local_name, i, btf_kind_str(t), targ_name,
5431 			 targ_btf_name);
5432 		new_cands = libbpf_reallocarray(cands->cands, cands->len + 1,
5433 					      sizeof(*cands->cands));
5434 		if (!new_cands)
5435 			return -ENOMEM;
5436 
5437 		cand = &new_cands[cands->len];
5438 		cand->btf = targ_btf;
5439 		cand->id = i;
5440 
5441 		cands->cands = new_cands;
5442 		cands->len++;
5443 	}
5444 	return 0;
5445 }
5446 
5447 static int load_module_btfs(struct bpf_object *obj)
5448 {
5449 	struct bpf_btf_info info;
5450 	struct module_btf *mod_btf;
5451 	struct btf *btf;
5452 	char name[64];
5453 	__u32 id = 0, len;
5454 	int err, fd;
5455 
5456 	if (obj->btf_modules_loaded)
5457 		return 0;
5458 
5459 	if (obj->gen_loader)
5460 		return 0;
5461 
5462 	/* don't do this again, even if we find no module BTFs */
5463 	obj->btf_modules_loaded = true;
5464 
5465 	/* kernel too old to support module BTFs */
5466 	if (!kernel_supports(obj, FEAT_MODULE_BTF))
5467 		return 0;
5468 
5469 	while (true) {
5470 		err = bpf_btf_get_next_id(id, &id);
5471 		if (err && errno == ENOENT)
5472 			return 0;
5473 		if (err) {
5474 			err = -errno;
5475 			pr_warn("failed to iterate BTF objects: %d\n", err);
5476 			return err;
5477 		}
5478 
5479 		fd = bpf_btf_get_fd_by_id(id);
5480 		if (fd < 0) {
5481 			if (errno == ENOENT)
5482 				continue; /* expected race: BTF was unloaded */
5483 			err = -errno;
5484 			pr_warn("failed to get BTF object #%d FD: %d\n", id, err);
5485 			return err;
5486 		}
5487 
5488 		len = sizeof(info);
5489 		memset(&info, 0, sizeof(info));
5490 		info.name = ptr_to_u64(name);
5491 		info.name_len = sizeof(name);
5492 
5493 		err = bpf_btf_get_info_by_fd(fd, &info, &len);
5494 		if (err) {
5495 			err = -errno;
5496 			pr_warn("failed to get BTF object #%d info: %d\n", id, err);
5497 			goto err_out;
5498 		}
5499 
5500 		/* ignore non-module BTFs */
5501 		if (!info.kernel_btf || strcmp(name, "vmlinux") == 0) {
5502 			close(fd);
5503 			continue;
5504 		}
5505 
5506 		btf = btf_get_from_fd(fd, obj->btf_vmlinux);
5507 		err = libbpf_get_error(btf);
5508 		if (err) {
5509 			pr_warn("failed to load module [%s]'s BTF object #%d: %d\n",
5510 				name, id, err);
5511 			goto err_out;
5512 		}
5513 
5514 		err = libbpf_ensure_mem((void **)&obj->btf_modules, &obj->btf_module_cap,
5515 					sizeof(*obj->btf_modules), obj->btf_module_cnt + 1);
5516 		if (err)
5517 			goto err_out;
5518 
5519 		mod_btf = &obj->btf_modules[obj->btf_module_cnt++];
5520 
5521 		mod_btf->btf = btf;
5522 		mod_btf->id = id;
5523 		mod_btf->fd = fd;
5524 		mod_btf->name = strdup(name);
5525 		if (!mod_btf->name) {
5526 			err = -ENOMEM;
5527 			goto err_out;
5528 		}
5529 		continue;
5530 
5531 err_out:
5532 		close(fd);
5533 		return err;
5534 	}
5535 
5536 	return 0;
5537 }
5538 
5539 static struct bpf_core_cand_list *
5540 bpf_core_find_cands(struct bpf_object *obj, const struct btf *local_btf, __u32 local_type_id)
5541 {
5542 	struct bpf_core_cand local_cand = {};
5543 	struct bpf_core_cand_list *cands;
5544 	const struct btf *main_btf;
5545 	const struct btf_type *local_t;
5546 	const char *local_name;
5547 	size_t local_essent_len;
5548 	int err, i;
5549 
5550 	local_cand.btf = local_btf;
5551 	local_cand.id = local_type_id;
5552 	local_t = btf__type_by_id(local_btf, local_type_id);
5553 	if (!local_t)
5554 		return ERR_PTR(-EINVAL);
5555 
5556 	local_name = btf__name_by_offset(local_btf, local_t->name_off);
5557 	if (str_is_empty(local_name))
5558 		return ERR_PTR(-EINVAL);
5559 	local_essent_len = bpf_core_essential_name_len(local_name);
5560 
5561 	cands = calloc(1, sizeof(*cands));
5562 	if (!cands)
5563 		return ERR_PTR(-ENOMEM);
5564 
5565 	/* Attempt to find target candidates in vmlinux BTF first */
5566 	main_btf = obj->btf_vmlinux_override ?: obj->btf_vmlinux;
5567 	err = bpf_core_add_cands(&local_cand, local_essent_len, main_btf, "vmlinux", 1, cands);
5568 	if (err)
5569 		goto err_out;
5570 
5571 	/* if vmlinux BTF has any candidate, don't got for module BTFs */
5572 	if (cands->len)
5573 		return cands;
5574 
5575 	/* if vmlinux BTF was overridden, don't attempt to load module BTFs */
5576 	if (obj->btf_vmlinux_override)
5577 		return cands;
5578 
5579 	/* now look through module BTFs, trying to still find candidates */
5580 	err = load_module_btfs(obj);
5581 	if (err)
5582 		goto err_out;
5583 
5584 	for (i = 0; i < obj->btf_module_cnt; i++) {
5585 		err = bpf_core_add_cands(&local_cand, local_essent_len,
5586 					 obj->btf_modules[i].btf,
5587 					 obj->btf_modules[i].name,
5588 					 btf__type_cnt(obj->btf_vmlinux),
5589 					 cands);
5590 		if (err)
5591 			goto err_out;
5592 	}
5593 
5594 	return cands;
5595 err_out:
5596 	bpf_core_free_cands(cands);
5597 	return ERR_PTR(err);
5598 }
5599 
5600 /* Check local and target types for compatibility. This check is used for
5601  * type-based CO-RE relocations and follow slightly different rules than
5602  * field-based relocations. This function assumes that root types were already
5603  * checked for name match. Beyond that initial root-level name check, names
5604  * are completely ignored. Compatibility rules are as follows:
5605  *   - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs are considered compatible, but
5606  *     kind should match for local and target types (i.e., STRUCT is not
5607  *     compatible with UNION);
5608  *   - for ENUMs, the size is ignored;
5609  *   - for INT, size and signedness are ignored;
5610  *   - for ARRAY, dimensionality is ignored, element types are checked for
5611  *     compatibility recursively;
5612  *   - CONST/VOLATILE/RESTRICT modifiers are ignored;
5613  *   - TYPEDEFs/PTRs are compatible if types they pointing to are compatible;
5614  *   - FUNC_PROTOs are compatible if they have compatible signature: same
5615  *     number of input args and compatible return and argument types.
5616  * These rules are not set in stone and probably will be adjusted as we get
5617  * more experience with using BPF CO-RE relocations.
5618  */
5619 int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
5620 			      const struct btf *targ_btf, __u32 targ_id)
5621 {
5622 	return __bpf_core_types_are_compat(local_btf, local_id, targ_btf, targ_id, 32);
5623 }
5624 
5625 int bpf_core_types_match(const struct btf *local_btf, __u32 local_id,
5626 			 const struct btf *targ_btf, __u32 targ_id)
5627 {
5628 	return __bpf_core_types_match(local_btf, local_id, targ_btf, targ_id, false, 32);
5629 }
5630 
5631 static size_t bpf_core_hash_fn(const long key, void *ctx)
5632 {
5633 	return key;
5634 }
5635 
5636 static bool bpf_core_equal_fn(const long k1, const long k2, void *ctx)
5637 {
5638 	return k1 == k2;
5639 }
5640 
5641 static int record_relo_core(struct bpf_program *prog,
5642 			    const struct bpf_core_relo *core_relo, int insn_idx)
5643 {
5644 	struct reloc_desc *relos, *relo;
5645 
5646 	relos = libbpf_reallocarray(prog->reloc_desc,
5647 				    prog->nr_reloc + 1, sizeof(*relos));
5648 	if (!relos)
5649 		return -ENOMEM;
5650 	relo = &relos[prog->nr_reloc];
5651 	relo->type = RELO_CORE;
5652 	relo->insn_idx = insn_idx;
5653 	relo->core_relo = core_relo;
5654 	prog->reloc_desc = relos;
5655 	prog->nr_reloc++;
5656 	return 0;
5657 }
5658 
5659 static const struct bpf_core_relo *find_relo_core(struct bpf_program *prog, int insn_idx)
5660 {
5661 	struct reloc_desc *relo;
5662 	int i;
5663 
5664 	for (i = 0; i < prog->nr_reloc; i++) {
5665 		relo = &prog->reloc_desc[i];
5666 		if (relo->type != RELO_CORE || relo->insn_idx != insn_idx)
5667 			continue;
5668 
5669 		return relo->core_relo;
5670 	}
5671 
5672 	return NULL;
5673 }
5674 
5675 static int bpf_core_resolve_relo(struct bpf_program *prog,
5676 				 const struct bpf_core_relo *relo,
5677 				 int relo_idx,
5678 				 const struct btf *local_btf,
5679 				 struct hashmap *cand_cache,
5680 				 struct bpf_core_relo_res *targ_res)
5681 {
5682 	struct bpf_core_spec specs_scratch[3] = {};
5683 	struct bpf_core_cand_list *cands = NULL;
5684 	const char *prog_name = prog->name;
5685 	const struct btf_type *local_type;
5686 	const char *local_name;
5687 	__u32 local_id = relo->type_id;
5688 	int err;
5689 
5690 	local_type = btf__type_by_id(local_btf, local_id);
5691 	if (!local_type)
5692 		return -EINVAL;
5693 
5694 	local_name = btf__name_by_offset(local_btf, local_type->name_off);
5695 	if (!local_name)
5696 		return -EINVAL;
5697 
5698 	if (relo->kind != BPF_CORE_TYPE_ID_LOCAL &&
5699 	    !hashmap__find(cand_cache, local_id, &cands)) {
5700 		cands = bpf_core_find_cands(prog->obj, local_btf, local_id);
5701 		if (IS_ERR(cands)) {
5702 			pr_warn("prog '%s': relo #%d: target candidate search failed for [%d] %s %s: %ld\n",
5703 				prog_name, relo_idx, local_id, btf_kind_str(local_type),
5704 				local_name, PTR_ERR(cands));
5705 			return PTR_ERR(cands);
5706 		}
5707 		err = hashmap__set(cand_cache, local_id, cands, NULL, NULL);
5708 		if (err) {
5709 			bpf_core_free_cands(cands);
5710 			return err;
5711 		}
5712 	}
5713 
5714 	return bpf_core_calc_relo_insn(prog_name, relo, relo_idx, local_btf, cands, specs_scratch,
5715 				       targ_res);
5716 }
5717 
5718 static int
5719 bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
5720 {
5721 	const struct btf_ext_info_sec *sec;
5722 	struct bpf_core_relo_res targ_res;
5723 	const struct bpf_core_relo *rec;
5724 	const struct btf_ext_info *seg;
5725 	struct hashmap_entry *entry;
5726 	struct hashmap *cand_cache = NULL;
5727 	struct bpf_program *prog;
5728 	struct bpf_insn *insn;
5729 	const char *sec_name;
5730 	int i, err = 0, insn_idx, sec_idx, sec_num;
5731 
5732 	if (obj->btf_ext->core_relo_info.len == 0)
5733 		return 0;
5734 
5735 	if (targ_btf_path) {
5736 		obj->btf_vmlinux_override = btf__parse(targ_btf_path, NULL);
5737 		err = libbpf_get_error(obj->btf_vmlinux_override);
5738 		if (err) {
5739 			pr_warn("failed to parse target BTF: %d\n", err);
5740 			return err;
5741 		}
5742 	}
5743 
5744 	cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
5745 	if (IS_ERR(cand_cache)) {
5746 		err = PTR_ERR(cand_cache);
5747 		goto out;
5748 	}
5749 
5750 	seg = &obj->btf_ext->core_relo_info;
5751 	sec_num = 0;
5752 	for_each_btf_ext_sec(seg, sec) {
5753 		sec_idx = seg->sec_idxs[sec_num];
5754 		sec_num++;
5755 
5756 		sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
5757 		if (str_is_empty(sec_name)) {
5758 			err = -EINVAL;
5759 			goto out;
5760 		}
5761 
5762 		pr_debug("sec '%s': found %d CO-RE relocations\n", sec_name, sec->num_info);
5763 
5764 		for_each_btf_ext_rec(seg, sec, i, rec) {
5765 			if (rec->insn_off % BPF_INSN_SZ)
5766 				return -EINVAL;
5767 			insn_idx = rec->insn_off / BPF_INSN_SZ;
5768 			prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
5769 			if (!prog) {
5770 				/* When __weak subprog is "overridden" by another instance
5771 				 * of the subprog from a different object file, linker still
5772 				 * appends all the .BTF.ext info that used to belong to that
5773 				 * eliminated subprogram.
5774 				 * This is similar to what x86-64 linker does for relocations.
5775 				 * So just ignore such relocations just like we ignore
5776 				 * subprog instructions when discovering subprograms.
5777 				 */
5778 				pr_debug("sec '%s': skipping CO-RE relocation #%d for insn #%d belonging to eliminated weak subprogram\n",
5779 					 sec_name, i, insn_idx);
5780 				continue;
5781 			}
5782 			/* no need to apply CO-RE relocation if the program is
5783 			 * not going to be loaded
5784 			 */
5785 			if (!prog->autoload)
5786 				continue;
5787 
5788 			/* adjust insn_idx from section frame of reference to the local
5789 			 * program's frame of reference; (sub-)program code is not yet
5790 			 * relocated, so it's enough to just subtract in-section offset
5791 			 */
5792 			insn_idx = insn_idx - prog->sec_insn_off;
5793 			if (insn_idx >= prog->insns_cnt)
5794 				return -EINVAL;
5795 			insn = &prog->insns[insn_idx];
5796 
5797 			err = record_relo_core(prog, rec, insn_idx);
5798 			if (err) {
5799 				pr_warn("prog '%s': relo #%d: failed to record relocation: %d\n",
5800 					prog->name, i, err);
5801 				goto out;
5802 			}
5803 
5804 			if (prog->obj->gen_loader)
5805 				continue;
5806 
5807 			err = bpf_core_resolve_relo(prog, rec, i, obj->btf, cand_cache, &targ_res);
5808 			if (err) {
5809 				pr_warn("prog '%s': relo #%d: failed to relocate: %d\n",
5810 					prog->name, i, err);
5811 				goto out;
5812 			}
5813 
5814 			err = bpf_core_patch_insn(prog->name, insn, insn_idx, rec, i, &targ_res);
5815 			if (err) {
5816 				pr_warn("prog '%s': relo #%d: failed to patch insn #%u: %d\n",
5817 					prog->name, i, insn_idx, err);
5818 				goto out;
5819 			}
5820 		}
5821 	}
5822 
5823 out:
5824 	/* obj->btf_vmlinux and module BTFs are freed after object load */
5825 	btf__free(obj->btf_vmlinux_override);
5826 	obj->btf_vmlinux_override = NULL;
5827 
5828 	if (!IS_ERR_OR_NULL(cand_cache)) {
5829 		hashmap__for_each_entry(cand_cache, entry, i) {
5830 			bpf_core_free_cands(entry->pvalue);
5831 		}
5832 		hashmap__free(cand_cache);
5833 	}
5834 	return err;
5835 }
5836 
5837 /* base map load ldimm64 special constant, used also for log fixup logic */
5838 #define POISON_LDIMM64_MAP_BASE 2001000000
5839 #define POISON_LDIMM64_MAP_PFX "200100"
5840 
5841 static void poison_map_ldimm64(struct bpf_program *prog, int relo_idx,
5842 			       int insn_idx, struct bpf_insn *insn,
5843 			       int map_idx, const struct bpf_map *map)
5844 {
5845 	int i;
5846 
5847 	pr_debug("prog '%s': relo #%d: poisoning insn #%d that loads map #%d '%s'\n",
5848 		 prog->name, relo_idx, insn_idx, map_idx, map->name);
5849 
5850 	/* we turn single ldimm64 into two identical invalid calls */
5851 	for (i = 0; i < 2; i++) {
5852 		insn->code = BPF_JMP | BPF_CALL;
5853 		insn->dst_reg = 0;
5854 		insn->src_reg = 0;
5855 		insn->off = 0;
5856 		/* if this instruction is reachable (not a dead code),
5857 		 * verifier will complain with something like:
5858 		 * invalid func unknown#2001000123
5859 		 * where lower 123 is map index into obj->maps[] array
5860 		 */
5861 		insn->imm = POISON_LDIMM64_MAP_BASE + map_idx;
5862 
5863 		insn++;
5864 	}
5865 }
5866 
5867 /* unresolved kfunc call special constant, used also for log fixup logic */
5868 #define POISON_CALL_KFUNC_BASE 2002000000
5869 #define POISON_CALL_KFUNC_PFX "2002"
5870 
5871 static void poison_kfunc_call(struct bpf_program *prog, int relo_idx,
5872 			      int insn_idx, struct bpf_insn *insn,
5873 			      int ext_idx, const struct extern_desc *ext)
5874 {
5875 	pr_debug("prog '%s': relo #%d: poisoning insn #%d that calls kfunc '%s'\n",
5876 		 prog->name, relo_idx, insn_idx, ext->name);
5877 
5878 	/* we turn kfunc call into invalid helper call with identifiable constant */
5879 	insn->code = BPF_JMP | BPF_CALL;
5880 	insn->dst_reg = 0;
5881 	insn->src_reg = 0;
5882 	insn->off = 0;
5883 	/* if this instruction is reachable (not a dead code),
5884 	 * verifier will complain with something like:
5885 	 * invalid func unknown#2001000123
5886 	 * where lower 123 is extern index into obj->externs[] array
5887 	 */
5888 	insn->imm = POISON_CALL_KFUNC_BASE + ext_idx;
5889 }
5890 
5891 /* Relocate data references within program code:
5892  *  - map references;
5893  *  - global variable references;
5894  *  - extern references.
5895  */
5896 static int
5897 bpf_object__relocate_data(struct bpf_object *obj, struct bpf_program *prog)
5898 {
5899 	int i;
5900 
5901 	for (i = 0; i < prog->nr_reloc; i++) {
5902 		struct reloc_desc *relo = &prog->reloc_desc[i];
5903 		struct bpf_insn *insn = &prog->insns[relo->insn_idx];
5904 		const struct bpf_map *map;
5905 		struct extern_desc *ext;
5906 
5907 		switch (relo->type) {
5908 		case RELO_LD64:
5909 			map = &obj->maps[relo->map_idx];
5910 			if (obj->gen_loader) {
5911 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX;
5912 				insn[0].imm = relo->map_idx;
5913 			} else if (map->autocreate) {
5914 				insn[0].src_reg = BPF_PSEUDO_MAP_FD;
5915 				insn[0].imm = map->fd;
5916 			} else {
5917 				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
5918 						   relo->map_idx, map);
5919 			}
5920 			break;
5921 		case RELO_DATA:
5922 			map = &obj->maps[relo->map_idx];
5923 			insn[1].imm = insn[0].imm + relo->sym_off;
5924 			if (obj->gen_loader) {
5925 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
5926 				insn[0].imm = relo->map_idx;
5927 			} else if (map->autocreate) {
5928 				insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
5929 				insn[0].imm = map->fd;
5930 			} else {
5931 				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
5932 						   relo->map_idx, map);
5933 			}
5934 			break;
5935 		case RELO_EXTERN_LD64:
5936 			ext = &obj->externs[relo->ext_idx];
5937 			if (ext->type == EXT_KCFG) {
5938 				if (obj->gen_loader) {
5939 					insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
5940 					insn[0].imm = obj->kconfig_map_idx;
5941 				} else {
5942 					insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
5943 					insn[0].imm = obj->maps[obj->kconfig_map_idx].fd;
5944 				}
5945 				insn[1].imm = ext->kcfg.data_off;
5946 			} else /* EXT_KSYM */ {
5947 				if (ext->ksym.type_id && ext->is_set) { /* typed ksyms */
5948 					insn[0].src_reg = BPF_PSEUDO_BTF_ID;
5949 					insn[0].imm = ext->ksym.kernel_btf_id;
5950 					insn[1].imm = ext->ksym.kernel_btf_obj_fd;
5951 				} else { /* typeless ksyms or unresolved typed ksyms */
5952 					insn[0].imm = (__u32)ext->ksym.addr;
5953 					insn[1].imm = ext->ksym.addr >> 32;
5954 				}
5955 			}
5956 			break;
5957 		case RELO_EXTERN_CALL:
5958 			ext = &obj->externs[relo->ext_idx];
5959 			insn[0].src_reg = BPF_PSEUDO_KFUNC_CALL;
5960 			if (ext->is_set) {
5961 				insn[0].imm = ext->ksym.kernel_btf_id;
5962 				insn[0].off = ext->ksym.btf_fd_idx;
5963 			} else { /* unresolved weak kfunc call */
5964 				poison_kfunc_call(prog, i, relo->insn_idx, insn,
5965 						  relo->ext_idx, ext);
5966 			}
5967 			break;
5968 		case RELO_SUBPROG_ADDR:
5969 			if (insn[0].src_reg != BPF_PSEUDO_FUNC) {
5970 				pr_warn("prog '%s': relo #%d: bad insn\n",
5971 					prog->name, i);
5972 				return -EINVAL;
5973 			}
5974 			/* handled already */
5975 			break;
5976 		case RELO_CALL:
5977 			/* handled already */
5978 			break;
5979 		case RELO_CORE:
5980 			/* will be handled by bpf_program_record_relos() */
5981 			break;
5982 		default:
5983 			pr_warn("prog '%s': relo #%d: bad relo type %d\n",
5984 				prog->name, i, relo->type);
5985 			return -EINVAL;
5986 		}
5987 	}
5988 
5989 	return 0;
5990 }
5991 
5992 static int adjust_prog_btf_ext_info(const struct bpf_object *obj,
5993 				    const struct bpf_program *prog,
5994 				    const struct btf_ext_info *ext_info,
5995 				    void **prog_info, __u32 *prog_rec_cnt,
5996 				    __u32 *prog_rec_sz)
5997 {
5998 	void *copy_start = NULL, *copy_end = NULL;
5999 	void *rec, *rec_end, *new_prog_info;
6000 	const struct btf_ext_info_sec *sec;
6001 	size_t old_sz, new_sz;
6002 	int i, sec_num, sec_idx, off_adj;
6003 
6004 	sec_num = 0;
6005 	for_each_btf_ext_sec(ext_info, sec) {
6006 		sec_idx = ext_info->sec_idxs[sec_num];
6007 		sec_num++;
6008 		if (prog->sec_idx != sec_idx)
6009 			continue;
6010 
6011 		for_each_btf_ext_rec(ext_info, sec, i, rec) {
6012 			__u32 insn_off = *(__u32 *)rec / BPF_INSN_SZ;
6013 
6014 			if (insn_off < prog->sec_insn_off)
6015 				continue;
6016 			if (insn_off >= prog->sec_insn_off + prog->sec_insn_cnt)
6017 				break;
6018 
6019 			if (!copy_start)
6020 				copy_start = rec;
6021 			copy_end = rec + ext_info->rec_size;
6022 		}
6023 
6024 		if (!copy_start)
6025 			return -ENOENT;
6026 
6027 		/* append func/line info of a given (sub-)program to the main
6028 		 * program func/line info
6029 		 */
6030 		old_sz = (size_t)(*prog_rec_cnt) * ext_info->rec_size;
6031 		new_sz = old_sz + (copy_end - copy_start);
6032 		new_prog_info = realloc(*prog_info, new_sz);
6033 		if (!new_prog_info)
6034 			return -ENOMEM;
6035 		*prog_info = new_prog_info;
6036 		*prog_rec_cnt = new_sz / ext_info->rec_size;
6037 		memcpy(new_prog_info + old_sz, copy_start, copy_end - copy_start);
6038 
6039 		/* Kernel instruction offsets are in units of 8-byte
6040 		 * instructions, while .BTF.ext instruction offsets generated
6041 		 * by Clang are in units of bytes. So convert Clang offsets
6042 		 * into kernel offsets and adjust offset according to program
6043 		 * relocated position.
6044 		 */
6045 		off_adj = prog->sub_insn_off - prog->sec_insn_off;
6046 		rec = new_prog_info + old_sz;
6047 		rec_end = new_prog_info + new_sz;
6048 		for (; rec < rec_end; rec += ext_info->rec_size) {
6049 			__u32 *insn_off = rec;
6050 
6051 			*insn_off = *insn_off / BPF_INSN_SZ + off_adj;
6052 		}
6053 		*prog_rec_sz = ext_info->rec_size;
6054 		return 0;
6055 	}
6056 
6057 	return -ENOENT;
6058 }
6059 
6060 static int
6061 reloc_prog_func_and_line_info(const struct bpf_object *obj,
6062 			      struct bpf_program *main_prog,
6063 			      const struct bpf_program *prog)
6064 {
6065 	int err;
6066 
6067 	/* no .BTF.ext relocation if .BTF.ext is missing or kernel doesn't
6068 	 * supprot func/line info
6069 	 */
6070 	if (!obj->btf_ext || !kernel_supports(obj, FEAT_BTF_FUNC))
6071 		return 0;
6072 
6073 	/* only attempt func info relocation if main program's func_info
6074 	 * relocation was successful
6075 	 */
6076 	if (main_prog != prog && !main_prog->func_info)
6077 		goto line_info;
6078 
6079 	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->func_info,
6080 				       &main_prog->func_info,
6081 				       &main_prog->func_info_cnt,
6082 				       &main_prog->func_info_rec_size);
6083 	if (err) {
6084 		if (err != -ENOENT) {
6085 			pr_warn("prog '%s': error relocating .BTF.ext function info: %d\n",
6086 				prog->name, err);
6087 			return err;
6088 		}
6089 		if (main_prog->func_info) {
6090 			/*
6091 			 * Some info has already been found but has problem
6092 			 * in the last btf_ext reloc. Must have to error out.
6093 			 */
6094 			pr_warn("prog '%s': missing .BTF.ext function info.\n", prog->name);
6095 			return err;
6096 		}
6097 		/* Have problem loading the very first info. Ignore the rest. */
6098 		pr_warn("prog '%s': missing .BTF.ext function info for the main program, skipping all of .BTF.ext func info.\n",
6099 			prog->name);
6100 	}
6101 
6102 line_info:
6103 	/* don't relocate line info if main program's relocation failed */
6104 	if (main_prog != prog && !main_prog->line_info)
6105 		return 0;
6106 
6107 	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->line_info,
6108 				       &main_prog->line_info,
6109 				       &main_prog->line_info_cnt,
6110 				       &main_prog->line_info_rec_size);
6111 	if (err) {
6112 		if (err != -ENOENT) {
6113 			pr_warn("prog '%s': error relocating .BTF.ext line info: %d\n",
6114 				prog->name, err);
6115 			return err;
6116 		}
6117 		if (main_prog->line_info) {
6118 			/*
6119 			 * Some info has already been found but has problem
6120 			 * in the last btf_ext reloc. Must have to error out.
6121 			 */
6122 			pr_warn("prog '%s': missing .BTF.ext line info.\n", prog->name);
6123 			return err;
6124 		}
6125 		/* Have problem loading the very first info. Ignore the rest. */
6126 		pr_warn("prog '%s': missing .BTF.ext line info for the main program, skipping all of .BTF.ext line info.\n",
6127 			prog->name);
6128 	}
6129 	return 0;
6130 }
6131 
6132 static int cmp_relo_by_insn_idx(const void *key, const void *elem)
6133 {
6134 	size_t insn_idx = *(const size_t *)key;
6135 	const struct reloc_desc *relo = elem;
6136 
6137 	if (insn_idx == relo->insn_idx)
6138 		return 0;
6139 	return insn_idx < relo->insn_idx ? -1 : 1;
6140 }
6141 
6142 static struct reloc_desc *find_prog_insn_relo(const struct bpf_program *prog, size_t insn_idx)
6143 {
6144 	if (!prog->nr_reloc)
6145 		return NULL;
6146 	return bsearch(&insn_idx, prog->reloc_desc, prog->nr_reloc,
6147 		       sizeof(*prog->reloc_desc), cmp_relo_by_insn_idx);
6148 }
6149 
6150 static int append_subprog_relos(struct bpf_program *main_prog, struct bpf_program *subprog)
6151 {
6152 	int new_cnt = main_prog->nr_reloc + subprog->nr_reloc;
6153 	struct reloc_desc *relos;
6154 	int i;
6155 
6156 	if (main_prog == subprog)
6157 		return 0;
6158 	relos = libbpf_reallocarray(main_prog->reloc_desc, new_cnt, sizeof(*relos));
6159 	if (!relos)
6160 		return -ENOMEM;
6161 	if (subprog->nr_reloc)
6162 		memcpy(relos + main_prog->nr_reloc, subprog->reloc_desc,
6163 		       sizeof(*relos) * subprog->nr_reloc);
6164 
6165 	for (i = main_prog->nr_reloc; i < new_cnt; i++)
6166 		relos[i].insn_idx += subprog->sub_insn_off;
6167 	/* After insn_idx adjustment the 'relos' array is still sorted
6168 	 * by insn_idx and doesn't break bsearch.
6169 	 */
6170 	main_prog->reloc_desc = relos;
6171 	main_prog->nr_reloc = new_cnt;
6172 	return 0;
6173 }
6174 
6175 static int
6176 bpf_object__reloc_code(struct bpf_object *obj, struct bpf_program *main_prog,
6177 		       struct bpf_program *prog)
6178 {
6179 	size_t sub_insn_idx, insn_idx, new_cnt;
6180 	struct bpf_program *subprog;
6181 	struct bpf_insn *insns, *insn;
6182 	struct reloc_desc *relo;
6183 	int err;
6184 
6185 	err = reloc_prog_func_and_line_info(obj, main_prog, prog);
6186 	if (err)
6187 		return err;
6188 
6189 	for (insn_idx = 0; insn_idx < prog->sec_insn_cnt; insn_idx++) {
6190 		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6191 		if (!insn_is_subprog_call(insn) && !insn_is_pseudo_func(insn))
6192 			continue;
6193 
6194 		relo = find_prog_insn_relo(prog, insn_idx);
6195 		if (relo && relo->type == RELO_EXTERN_CALL)
6196 			/* kfunc relocations will be handled later
6197 			 * in bpf_object__relocate_data()
6198 			 */
6199 			continue;
6200 		if (relo && relo->type != RELO_CALL && relo->type != RELO_SUBPROG_ADDR) {
6201 			pr_warn("prog '%s': unexpected relo for insn #%zu, type %d\n",
6202 				prog->name, insn_idx, relo->type);
6203 			return -LIBBPF_ERRNO__RELOC;
6204 		}
6205 		if (relo) {
6206 			/* sub-program instruction index is a combination of
6207 			 * an offset of a symbol pointed to by relocation and
6208 			 * call instruction's imm field; for global functions,
6209 			 * call always has imm = -1, but for static functions
6210 			 * relocation is against STT_SECTION and insn->imm
6211 			 * points to a start of a static function
6212 			 *
6213 			 * for subprog addr relocation, the relo->sym_off + insn->imm is
6214 			 * the byte offset in the corresponding section.
6215 			 */
6216 			if (relo->type == RELO_CALL)
6217 				sub_insn_idx = relo->sym_off / BPF_INSN_SZ + insn->imm + 1;
6218 			else
6219 				sub_insn_idx = (relo->sym_off + insn->imm) / BPF_INSN_SZ;
6220 		} else if (insn_is_pseudo_func(insn)) {
6221 			/*
6222 			 * RELO_SUBPROG_ADDR relo is always emitted even if both
6223 			 * functions are in the same section, so it shouldn't reach here.
6224 			 */
6225 			pr_warn("prog '%s': missing subprog addr relo for insn #%zu\n",
6226 				prog->name, insn_idx);
6227 			return -LIBBPF_ERRNO__RELOC;
6228 		} else {
6229 			/* if subprogram call is to a static function within
6230 			 * the same ELF section, there won't be any relocation
6231 			 * emitted, but it also means there is no additional
6232 			 * offset necessary, insns->imm is relative to
6233 			 * instruction's original position within the section
6234 			 */
6235 			sub_insn_idx = prog->sec_insn_off + insn_idx + insn->imm + 1;
6236 		}
6237 
6238 		/* we enforce that sub-programs should be in .text section */
6239 		subprog = find_prog_by_sec_insn(obj, obj->efile.text_shndx, sub_insn_idx);
6240 		if (!subprog) {
6241 			pr_warn("prog '%s': no .text section found yet sub-program call exists\n",
6242 				prog->name);
6243 			return -LIBBPF_ERRNO__RELOC;
6244 		}
6245 
6246 		/* if it's the first call instruction calling into this
6247 		 * subprogram (meaning this subprog hasn't been processed
6248 		 * yet) within the context of current main program:
6249 		 *   - append it at the end of main program's instructions blog;
6250 		 *   - process is recursively, while current program is put on hold;
6251 		 *   - if that subprogram calls some other not yet processes
6252 		 *   subprogram, same thing will happen recursively until
6253 		 *   there are no more unprocesses subprograms left to append
6254 		 *   and relocate.
6255 		 */
6256 		if (subprog->sub_insn_off == 0) {
6257 			subprog->sub_insn_off = main_prog->insns_cnt;
6258 
6259 			new_cnt = main_prog->insns_cnt + subprog->insns_cnt;
6260 			insns = libbpf_reallocarray(main_prog->insns, new_cnt, sizeof(*insns));
6261 			if (!insns) {
6262 				pr_warn("prog '%s': failed to realloc prog code\n", main_prog->name);
6263 				return -ENOMEM;
6264 			}
6265 			main_prog->insns = insns;
6266 			main_prog->insns_cnt = new_cnt;
6267 
6268 			memcpy(main_prog->insns + subprog->sub_insn_off, subprog->insns,
6269 			       subprog->insns_cnt * sizeof(*insns));
6270 
6271 			pr_debug("prog '%s': added %zu insns from sub-prog '%s'\n",
6272 				 main_prog->name, subprog->insns_cnt, subprog->name);
6273 
6274 			/* The subprog insns are now appended. Append its relos too. */
6275 			err = append_subprog_relos(main_prog, subprog);
6276 			if (err)
6277 				return err;
6278 			err = bpf_object__reloc_code(obj, main_prog, subprog);
6279 			if (err)
6280 				return err;
6281 		}
6282 
6283 		/* main_prog->insns memory could have been re-allocated, so
6284 		 * calculate pointer again
6285 		 */
6286 		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6287 		/* calculate correct instruction position within current main
6288 		 * prog; each main prog can have a different set of
6289 		 * subprograms appended (potentially in different order as
6290 		 * well), so position of any subprog can be different for
6291 		 * different main programs
6292 		 */
6293 		insn->imm = subprog->sub_insn_off - (prog->sub_insn_off + insn_idx) - 1;
6294 
6295 		pr_debug("prog '%s': insn #%zu relocated, imm %d points to subprog '%s' (now at %zu offset)\n",
6296 			 prog->name, insn_idx, insn->imm, subprog->name, subprog->sub_insn_off);
6297 	}
6298 
6299 	return 0;
6300 }
6301 
6302 /*
6303  * Relocate sub-program calls.
6304  *
6305  * Algorithm operates as follows. Each entry-point BPF program (referred to as
6306  * main prog) is processed separately. For each subprog (non-entry functions,
6307  * that can be called from either entry progs or other subprogs) gets their
6308  * sub_insn_off reset to zero. This serves as indicator that this subprogram
6309  * hasn't been yet appended and relocated within current main prog. Once its
6310  * relocated, sub_insn_off will point at the position within current main prog
6311  * where given subprog was appended. This will further be used to relocate all
6312  * the call instructions jumping into this subprog.
6313  *
6314  * We start with main program and process all call instructions. If the call
6315  * is into a subprog that hasn't been processed (i.e., subprog->sub_insn_off
6316  * is zero), subprog instructions are appended at the end of main program's
6317  * instruction array. Then main program is "put on hold" while we recursively
6318  * process newly appended subprogram. If that subprogram calls into another
6319  * subprogram that hasn't been appended, new subprogram is appended again to
6320  * the *main* prog's instructions (subprog's instructions are always left
6321  * untouched, as they need to be in unmodified state for subsequent main progs
6322  * and subprog instructions are always sent only as part of a main prog) and
6323  * the process continues recursively. Once all the subprogs called from a main
6324  * prog or any of its subprogs are appended (and relocated), all their
6325  * positions within finalized instructions array are known, so it's easy to
6326  * rewrite call instructions with correct relative offsets, corresponding to
6327  * desired target subprog.
6328  *
6329  * Its important to realize that some subprogs might not be called from some
6330  * main prog and any of its called/used subprogs. Those will keep their
6331  * subprog->sub_insn_off as zero at all times and won't be appended to current
6332  * main prog and won't be relocated within the context of current main prog.
6333  * They might still be used from other main progs later.
6334  *
6335  * Visually this process can be shown as below. Suppose we have two main
6336  * programs mainA and mainB and BPF object contains three subprogs: subA,
6337  * subB, and subC. mainA calls only subA, mainB calls only subC, but subA and
6338  * subC both call subB:
6339  *
6340  *        +--------+ +-------+
6341  *        |        v v       |
6342  *     +--+---+ +--+-+-+ +---+--+
6343  *     | subA | | subB | | subC |
6344  *     +--+---+ +------+ +---+--+
6345  *        ^                  ^
6346  *        |                  |
6347  *    +---+-------+   +------+----+
6348  *    |   mainA   |   |   mainB   |
6349  *    +-----------+   +-----------+
6350  *
6351  * We'll start relocating mainA, will find subA, append it and start
6352  * processing sub A recursively:
6353  *
6354  *    +-----------+------+
6355  *    |   mainA   | subA |
6356  *    +-----------+------+
6357  *
6358  * At this point we notice that subB is used from subA, so we append it and
6359  * relocate (there are no further subcalls from subB):
6360  *
6361  *    +-----------+------+------+
6362  *    |   mainA   | subA | subB |
6363  *    +-----------+------+------+
6364  *
6365  * At this point, we relocate subA calls, then go one level up and finish with
6366  * relocatin mainA calls. mainA is done.
6367  *
6368  * For mainB process is similar but results in different order. We start with
6369  * mainB and skip subA and subB, as mainB never calls them (at least
6370  * directly), but we see subC is needed, so we append and start processing it:
6371  *
6372  *    +-----------+------+
6373  *    |   mainB   | subC |
6374  *    +-----------+------+
6375  * Now we see subC needs subB, so we go back to it, append and relocate it:
6376  *
6377  *    +-----------+------+------+
6378  *    |   mainB   | subC | subB |
6379  *    +-----------+------+------+
6380  *
6381  * At this point we unwind recursion, relocate calls in subC, then in mainB.
6382  */
6383 static int
6384 bpf_object__relocate_calls(struct bpf_object *obj, struct bpf_program *prog)
6385 {
6386 	struct bpf_program *subprog;
6387 	int i, err;
6388 
6389 	/* mark all subprogs as not relocated (yet) within the context of
6390 	 * current main program
6391 	 */
6392 	for (i = 0; i < obj->nr_programs; i++) {
6393 		subprog = &obj->programs[i];
6394 		if (!prog_is_subprog(obj, subprog))
6395 			continue;
6396 
6397 		subprog->sub_insn_off = 0;
6398 	}
6399 
6400 	err = bpf_object__reloc_code(obj, prog, prog);
6401 	if (err)
6402 		return err;
6403 
6404 	return 0;
6405 }
6406 
6407 static void
6408 bpf_object__free_relocs(struct bpf_object *obj)
6409 {
6410 	struct bpf_program *prog;
6411 	int i;
6412 
6413 	/* free up relocation descriptors */
6414 	for (i = 0; i < obj->nr_programs; i++) {
6415 		prog = &obj->programs[i];
6416 		zfree(&prog->reloc_desc);
6417 		prog->nr_reloc = 0;
6418 	}
6419 }
6420 
6421 static int cmp_relocs(const void *_a, const void *_b)
6422 {
6423 	const struct reloc_desc *a = _a;
6424 	const struct reloc_desc *b = _b;
6425 
6426 	if (a->insn_idx != b->insn_idx)
6427 		return a->insn_idx < b->insn_idx ? -1 : 1;
6428 
6429 	/* no two relocations should have the same insn_idx, but ... */
6430 	if (a->type != b->type)
6431 		return a->type < b->type ? -1 : 1;
6432 
6433 	return 0;
6434 }
6435 
6436 static void bpf_object__sort_relos(struct bpf_object *obj)
6437 {
6438 	int i;
6439 
6440 	for (i = 0; i < obj->nr_programs; i++) {
6441 		struct bpf_program *p = &obj->programs[i];
6442 
6443 		if (!p->nr_reloc)
6444 			continue;
6445 
6446 		qsort(p->reloc_desc, p->nr_reloc, sizeof(*p->reloc_desc), cmp_relocs);
6447 	}
6448 }
6449 
6450 static int
6451 bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
6452 {
6453 	struct bpf_program *prog;
6454 	size_t i, j;
6455 	int err;
6456 
6457 	if (obj->btf_ext) {
6458 		err = bpf_object__relocate_core(obj, targ_btf_path);
6459 		if (err) {
6460 			pr_warn("failed to perform CO-RE relocations: %d\n",
6461 				err);
6462 			return err;
6463 		}
6464 		bpf_object__sort_relos(obj);
6465 	}
6466 
6467 	/* Before relocating calls pre-process relocations and mark
6468 	 * few ld_imm64 instructions that points to subprogs.
6469 	 * Otherwise bpf_object__reloc_code() later would have to consider
6470 	 * all ld_imm64 insns as relocation candidates. That would
6471 	 * reduce relocation speed, since amount of find_prog_insn_relo()
6472 	 * would increase and most of them will fail to find a relo.
6473 	 */
6474 	for (i = 0; i < obj->nr_programs; i++) {
6475 		prog = &obj->programs[i];
6476 		for (j = 0; j < prog->nr_reloc; j++) {
6477 			struct reloc_desc *relo = &prog->reloc_desc[j];
6478 			struct bpf_insn *insn = &prog->insns[relo->insn_idx];
6479 
6480 			/* mark the insn, so it's recognized by insn_is_pseudo_func() */
6481 			if (relo->type == RELO_SUBPROG_ADDR)
6482 				insn[0].src_reg = BPF_PSEUDO_FUNC;
6483 		}
6484 	}
6485 
6486 	/* relocate subprogram calls and append used subprograms to main
6487 	 * programs; each copy of subprogram code needs to be relocated
6488 	 * differently for each main program, because its code location might
6489 	 * have changed.
6490 	 * Append subprog relos to main programs to allow data relos to be
6491 	 * processed after text is completely relocated.
6492 	 */
6493 	for (i = 0; i < obj->nr_programs; i++) {
6494 		prog = &obj->programs[i];
6495 		/* sub-program's sub-calls are relocated within the context of
6496 		 * its main program only
6497 		 */
6498 		if (prog_is_subprog(obj, prog))
6499 			continue;
6500 		if (!prog->autoload)
6501 			continue;
6502 
6503 		err = bpf_object__relocate_calls(obj, prog);
6504 		if (err) {
6505 			pr_warn("prog '%s': failed to relocate calls: %d\n",
6506 				prog->name, err);
6507 			return err;
6508 		}
6509 	}
6510 	/* Process data relos for main programs */
6511 	for (i = 0; i < obj->nr_programs; i++) {
6512 		prog = &obj->programs[i];
6513 		if (prog_is_subprog(obj, prog))
6514 			continue;
6515 		if (!prog->autoload)
6516 			continue;
6517 		err = bpf_object__relocate_data(obj, prog);
6518 		if (err) {
6519 			pr_warn("prog '%s': failed to relocate data references: %d\n",
6520 				prog->name, err);
6521 			return err;
6522 		}
6523 	}
6524 
6525 	return 0;
6526 }
6527 
6528 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
6529 					    Elf64_Shdr *shdr, Elf_Data *data);
6530 
6531 static int bpf_object__collect_map_relos(struct bpf_object *obj,
6532 					 Elf64_Shdr *shdr, Elf_Data *data)
6533 {
6534 	const int bpf_ptr_sz = 8, host_ptr_sz = sizeof(void *);
6535 	int i, j, nrels, new_sz;
6536 	const struct btf_var_secinfo *vi = NULL;
6537 	const struct btf_type *sec, *var, *def;
6538 	struct bpf_map *map = NULL, *targ_map = NULL;
6539 	struct bpf_program *targ_prog = NULL;
6540 	bool is_prog_array, is_map_in_map;
6541 	const struct btf_member *member;
6542 	const char *name, *mname, *type;
6543 	unsigned int moff;
6544 	Elf64_Sym *sym;
6545 	Elf64_Rel *rel;
6546 	void *tmp;
6547 
6548 	if (!obj->efile.btf_maps_sec_btf_id || !obj->btf)
6549 		return -EINVAL;
6550 	sec = btf__type_by_id(obj->btf, obj->efile.btf_maps_sec_btf_id);
6551 	if (!sec)
6552 		return -EINVAL;
6553 
6554 	nrels = shdr->sh_size / shdr->sh_entsize;
6555 	for (i = 0; i < nrels; i++) {
6556 		rel = elf_rel_by_idx(data, i);
6557 		if (!rel) {
6558 			pr_warn(".maps relo #%d: failed to get ELF relo\n", i);
6559 			return -LIBBPF_ERRNO__FORMAT;
6560 		}
6561 
6562 		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
6563 		if (!sym) {
6564 			pr_warn(".maps relo #%d: symbol %zx not found\n",
6565 				i, (size_t)ELF64_R_SYM(rel->r_info));
6566 			return -LIBBPF_ERRNO__FORMAT;
6567 		}
6568 		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
6569 
6570 		pr_debug(".maps relo #%d: for %zd value %zd rel->r_offset %zu name %d ('%s')\n",
6571 			 i, (ssize_t)(rel->r_info >> 32), (size_t)sym->st_value,
6572 			 (size_t)rel->r_offset, sym->st_name, name);
6573 
6574 		for (j = 0; j < obj->nr_maps; j++) {
6575 			map = &obj->maps[j];
6576 			if (map->sec_idx != obj->efile.btf_maps_shndx)
6577 				continue;
6578 
6579 			vi = btf_var_secinfos(sec) + map->btf_var_idx;
6580 			if (vi->offset <= rel->r_offset &&
6581 			    rel->r_offset + bpf_ptr_sz <= vi->offset + vi->size)
6582 				break;
6583 		}
6584 		if (j == obj->nr_maps) {
6585 			pr_warn(".maps relo #%d: cannot find map '%s' at rel->r_offset %zu\n",
6586 				i, name, (size_t)rel->r_offset);
6587 			return -EINVAL;
6588 		}
6589 
6590 		is_map_in_map = bpf_map_type__is_map_in_map(map->def.type);
6591 		is_prog_array = map->def.type == BPF_MAP_TYPE_PROG_ARRAY;
6592 		type = is_map_in_map ? "map" : "prog";
6593 		if (is_map_in_map) {
6594 			if (sym->st_shndx != obj->efile.btf_maps_shndx) {
6595 				pr_warn(".maps relo #%d: '%s' isn't a BTF-defined map\n",
6596 					i, name);
6597 				return -LIBBPF_ERRNO__RELOC;
6598 			}
6599 			if (map->def.type == BPF_MAP_TYPE_HASH_OF_MAPS &&
6600 			    map->def.key_size != sizeof(int)) {
6601 				pr_warn(".maps relo #%d: hash-of-maps '%s' should have key size %zu.\n",
6602 					i, map->name, sizeof(int));
6603 				return -EINVAL;
6604 			}
6605 			targ_map = bpf_object__find_map_by_name(obj, name);
6606 			if (!targ_map) {
6607 				pr_warn(".maps relo #%d: '%s' isn't a valid map reference\n",
6608 					i, name);
6609 				return -ESRCH;
6610 			}
6611 		} else if (is_prog_array) {
6612 			targ_prog = bpf_object__find_program_by_name(obj, name);
6613 			if (!targ_prog) {
6614 				pr_warn(".maps relo #%d: '%s' isn't a valid program reference\n",
6615 					i, name);
6616 				return -ESRCH;
6617 			}
6618 			if (targ_prog->sec_idx != sym->st_shndx ||
6619 			    targ_prog->sec_insn_off * 8 != sym->st_value ||
6620 			    prog_is_subprog(obj, targ_prog)) {
6621 				pr_warn(".maps relo #%d: '%s' isn't an entry-point program\n",
6622 					i, name);
6623 				return -LIBBPF_ERRNO__RELOC;
6624 			}
6625 		} else {
6626 			return -EINVAL;
6627 		}
6628 
6629 		var = btf__type_by_id(obj->btf, vi->type);
6630 		def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
6631 		if (btf_vlen(def) == 0)
6632 			return -EINVAL;
6633 		member = btf_members(def) + btf_vlen(def) - 1;
6634 		mname = btf__name_by_offset(obj->btf, member->name_off);
6635 		if (strcmp(mname, "values"))
6636 			return -EINVAL;
6637 
6638 		moff = btf_member_bit_offset(def, btf_vlen(def) - 1) / 8;
6639 		if (rel->r_offset - vi->offset < moff)
6640 			return -EINVAL;
6641 
6642 		moff = rel->r_offset - vi->offset - moff;
6643 		/* here we use BPF pointer size, which is always 64 bit, as we
6644 		 * are parsing ELF that was built for BPF target
6645 		 */
6646 		if (moff % bpf_ptr_sz)
6647 			return -EINVAL;
6648 		moff /= bpf_ptr_sz;
6649 		if (moff >= map->init_slots_sz) {
6650 			new_sz = moff + 1;
6651 			tmp = libbpf_reallocarray(map->init_slots, new_sz, host_ptr_sz);
6652 			if (!tmp)
6653 				return -ENOMEM;
6654 			map->init_slots = tmp;
6655 			memset(map->init_slots + map->init_slots_sz, 0,
6656 			       (new_sz - map->init_slots_sz) * host_ptr_sz);
6657 			map->init_slots_sz = new_sz;
6658 		}
6659 		map->init_slots[moff] = is_map_in_map ? (void *)targ_map : (void *)targ_prog;
6660 
6661 		pr_debug(".maps relo #%d: map '%s' slot [%d] points to %s '%s'\n",
6662 			 i, map->name, moff, type, name);
6663 	}
6664 
6665 	return 0;
6666 }
6667 
6668 static int bpf_object__collect_relos(struct bpf_object *obj)
6669 {
6670 	int i, err;
6671 
6672 	for (i = 0; i < obj->efile.sec_cnt; i++) {
6673 		struct elf_sec_desc *sec_desc = &obj->efile.secs[i];
6674 		Elf64_Shdr *shdr;
6675 		Elf_Data *data;
6676 		int idx;
6677 
6678 		if (sec_desc->sec_type != SEC_RELO)
6679 			continue;
6680 
6681 		shdr = sec_desc->shdr;
6682 		data = sec_desc->data;
6683 		idx = shdr->sh_info;
6684 
6685 		if (shdr->sh_type != SHT_REL) {
6686 			pr_warn("internal error at %d\n", __LINE__);
6687 			return -LIBBPF_ERRNO__INTERNAL;
6688 		}
6689 
6690 		if (idx == obj->efile.st_ops_shndx || idx == obj->efile.st_ops_link_shndx)
6691 			err = bpf_object__collect_st_ops_relos(obj, shdr, data);
6692 		else if (idx == obj->efile.btf_maps_shndx)
6693 			err = bpf_object__collect_map_relos(obj, shdr, data);
6694 		else
6695 			err = bpf_object__collect_prog_relos(obj, shdr, data);
6696 		if (err)
6697 			return err;
6698 	}
6699 
6700 	bpf_object__sort_relos(obj);
6701 	return 0;
6702 }
6703 
6704 static bool insn_is_helper_call(struct bpf_insn *insn, enum bpf_func_id *func_id)
6705 {
6706 	if (BPF_CLASS(insn->code) == BPF_JMP &&
6707 	    BPF_OP(insn->code) == BPF_CALL &&
6708 	    BPF_SRC(insn->code) == BPF_K &&
6709 	    insn->src_reg == 0 &&
6710 	    insn->dst_reg == 0) {
6711 		    *func_id = insn->imm;
6712 		    return true;
6713 	}
6714 	return false;
6715 }
6716 
6717 static int bpf_object__sanitize_prog(struct bpf_object *obj, struct bpf_program *prog)
6718 {
6719 	struct bpf_insn *insn = prog->insns;
6720 	enum bpf_func_id func_id;
6721 	int i;
6722 
6723 	if (obj->gen_loader)
6724 		return 0;
6725 
6726 	for (i = 0; i < prog->insns_cnt; i++, insn++) {
6727 		if (!insn_is_helper_call(insn, &func_id))
6728 			continue;
6729 
6730 		/* on kernels that don't yet support
6731 		 * bpf_probe_read_{kernel,user}[_str] helpers, fall back
6732 		 * to bpf_probe_read() which works well for old kernels
6733 		 */
6734 		switch (func_id) {
6735 		case BPF_FUNC_probe_read_kernel:
6736 		case BPF_FUNC_probe_read_user:
6737 			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
6738 				insn->imm = BPF_FUNC_probe_read;
6739 			break;
6740 		case BPF_FUNC_probe_read_kernel_str:
6741 		case BPF_FUNC_probe_read_user_str:
6742 			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
6743 				insn->imm = BPF_FUNC_probe_read_str;
6744 			break;
6745 		default:
6746 			break;
6747 		}
6748 	}
6749 	return 0;
6750 }
6751 
6752 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
6753 				     int *btf_obj_fd, int *btf_type_id);
6754 
6755 /* this is called as prog->sec_def->prog_prepare_load_fn for libbpf-supported sec_defs */
6756 static int libbpf_prepare_prog_load(struct bpf_program *prog,
6757 				    struct bpf_prog_load_opts *opts, long cookie)
6758 {
6759 	enum sec_def_flags def = cookie;
6760 
6761 	/* old kernels might not support specifying expected_attach_type */
6762 	if ((def & SEC_EXP_ATTACH_OPT) && !kernel_supports(prog->obj, FEAT_EXP_ATTACH_TYPE))
6763 		opts->expected_attach_type = 0;
6764 
6765 	if (def & SEC_SLEEPABLE)
6766 		opts->prog_flags |= BPF_F_SLEEPABLE;
6767 
6768 	if (prog->type == BPF_PROG_TYPE_XDP && (def & SEC_XDP_FRAGS))
6769 		opts->prog_flags |= BPF_F_XDP_HAS_FRAGS;
6770 
6771 	if ((def & SEC_ATTACH_BTF) && !prog->attach_btf_id) {
6772 		int btf_obj_fd = 0, btf_type_id = 0, err;
6773 		const char *attach_name;
6774 
6775 		attach_name = strchr(prog->sec_name, '/');
6776 		if (!attach_name) {
6777 			/* if BPF program is annotated with just SEC("fentry")
6778 			 * (or similar) without declaratively specifying
6779 			 * target, then it is expected that target will be
6780 			 * specified with bpf_program__set_attach_target() at
6781 			 * runtime before BPF object load step. If not, then
6782 			 * there is nothing to load into the kernel as BPF
6783 			 * verifier won't be able to validate BPF program
6784 			 * correctness anyways.
6785 			 */
6786 			pr_warn("prog '%s': no BTF-based attach target is specified, use bpf_program__set_attach_target()\n",
6787 				prog->name);
6788 			return -EINVAL;
6789 		}
6790 		attach_name++; /* skip over / */
6791 
6792 		err = libbpf_find_attach_btf_id(prog, attach_name, &btf_obj_fd, &btf_type_id);
6793 		if (err)
6794 			return err;
6795 
6796 		/* cache resolved BTF FD and BTF type ID in the prog */
6797 		prog->attach_btf_obj_fd = btf_obj_fd;
6798 		prog->attach_btf_id = btf_type_id;
6799 
6800 		/* but by now libbpf common logic is not utilizing
6801 		 * prog->atach_btf_obj_fd/prog->attach_btf_id anymore because
6802 		 * this callback is called after opts were populated by
6803 		 * libbpf, so this callback has to update opts explicitly here
6804 		 */
6805 		opts->attach_btf_obj_fd = btf_obj_fd;
6806 		opts->attach_btf_id = btf_type_id;
6807 	}
6808 	return 0;
6809 }
6810 
6811 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz);
6812 
6813 static int bpf_object_load_prog(struct bpf_object *obj, struct bpf_program *prog,
6814 				struct bpf_insn *insns, int insns_cnt,
6815 				const char *license, __u32 kern_version, int *prog_fd)
6816 {
6817 	LIBBPF_OPTS(bpf_prog_load_opts, load_attr);
6818 	const char *prog_name = NULL;
6819 	char *cp, errmsg[STRERR_BUFSIZE];
6820 	size_t log_buf_size = 0;
6821 	char *log_buf = NULL, *tmp;
6822 	int btf_fd, ret, err;
6823 	bool own_log_buf = true;
6824 	__u32 log_level = prog->log_level;
6825 
6826 	if (prog->type == BPF_PROG_TYPE_UNSPEC) {
6827 		/*
6828 		 * The program type must be set.  Most likely we couldn't find a proper
6829 		 * section definition at load time, and thus we didn't infer the type.
6830 		 */
6831 		pr_warn("prog '%s': missing BPF prog type, check ELF section name '%s'\n",
6832 			prog->name, prog->sec_name);
6833 		return -EINVAL;
6834 	}
6835 
6836 	if (!insns || !insns_cnt)
6837 		return -EINVAL;
6838 
6839 	load_attr.expected_attach_type = prog->expected_attach_type;
6840 	if (kernel_supports(obj, FEAT_PROG_NAME))
6841 		prog_name = prog->name;
6842 	load_attr.attach_prog_fd = prog->attach_prog_fd;
6843 	load_attr.attach_btf_obj_fd = prog->attach_btf_obj_fd;
6844 	load_attr.attach_btf_id = prog->attach_btf_id;
6845 	load_attr.kern_version = kern_version;
6846 	load_attr.prog_ifindex = prog->prog_ifindex;
6847 
6848 	/* specify func_info/line_info only if kernel supports them */
6849 	btf_fd = bpf_object__btf_fd(obj);
6850 	if (btf_fd >= 0 && kernel_supports(obj, FEAT_BTF_FUNC)) {
6851 		load_attr.prog_btf_fd = btf_fd;
6852 		load_attr.func_info = prog->func_info;
6853 		load_attr.func_info_rec_size = prog->func_info_rec_size;
6854 		load_attr.func_info_cnt = prog->func_info_cnt;
6855 		load_attr.line_info = prog->line_info;
6856 		load_attr.line_info_rec_size = prog->line_info_rec_size;
6857 		load_attr.line_info_cnt = prog->line_info_cnt;
6858 	}
6859 	load_attr.log_level = log_level;
6860 	load_attr.prog_flags = prog->prog_flags;
6861 	load_attr.fd_array = obj->fd_array;
6862 
6863 	/* adjust load_attr if sec_def provides custom preload callback */
6864 	if (prog->sec_def && prog->sec_def->prog_prepare_load_fn) {
6865 		err = prog->sec_def->prog_prepare_load_fn(prog, &load_attr, prog->sec_def->cookie);
6866 		if (err < 0) {
6867 			pr_warn("prog '%s': failed to prepare load attributes: %d\n",
6868 				prog->name, err);
6869 			return err;
6870 		}
6871 		insns = prog->insns;
6872 		insns_cnt = prog->insns_cnt;
6873 	}
6874 
6875 	if (obj->gen_loader) {
6876 		bpf_gen__prog_load(obj->gen_loader, prog->type, prog->name,
6877 				   license, insns, insns_cnt, &load_attr,
6878 				   prog - obj->programs);
6879 		*prog_fd = -1;
6880 		return 0;
6881 	}
6882 
6883 retry_load:
6884 	/* if log_level is zero, we don't request logs initially even if
6885 	 * custom log_buf is specified; if the program load fails, then we'll
6886 	 * bump log_level to 1 and use either custom log_buf or we'll allocate
6887 	 * our own and retry the load to get details on what failed
6888 	 */
6889 	if (log_level) {
6890 		if (prog->log_buf) {
6891 			log_buf = prog->log_buf;
6892 			log_buf_size = prog->log_size;
6893 			own_log_buf = false;
6894 		} else if (obj->log_buf) {
6895 			log_buf = obj->log_buf;
6896 			log_buf_size = obj->log_size;
6897 			own_log_buf = false;
6898 		} else {
6899 			log_buf_size = max((size_t)BPF_LOG_BUF_SIZE, log_buf_size * 2);
6900 			tmp = realloc(log_buf, log_buf_size);
6901 			if (!tmp) {
6902 				ret = -ENOMEM;
6903 				goto out;
6904 			}
6905 			log_buf = tmp;
6906 			log_buf[0] = '\0';
6907 			own_log_buf = true;
6908 		}
6909 	}
6910 
6911 	load_attr.log_buf = log_buf;
6912 	load_attr.log_size = log_buf_size;
6913 	load_attr.log_level = log_level;
6914 
6915 	ret = bpf_prog_load(prog->type, prog_name, license, insns, insns_cnt, &load_attr);
6916 	if (ret >= 0) {
6917 		if (log_level && own_log_buf) {
6918 			pr_debug("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
6919 				 prog->name, log_buf);
6920 		}
6921 
6922 		if (obj->has_rodata && kernel_supports(obj, FEAT_PROG_BIND_MAP)) {
6923 			struct bpf_map *map;
6924 			int i;
6925 
6926 			for (i = 0; i < obj->nr_maps; i++) {
6927 				map = &prog->obj->maps[i];
6928 				if (map->libbpf_type != LIBBPF_MAP_RODATA)
6929 					continue;
6930 
6931 				if (bpf_prog_bind_map(ret, bpf_map__fd(map), NULL)) {
6932 					cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
6933 					pr_warn("prog '%s': failed to bind map '%s': %s\n",
6934 						prog->name, map->real_name, cp);
6935 					/* Don't fail hard if can't bind rodata. */
6936 				}
6937 			}
6938 		}
6939 
6940 		*prog_fd = ret;
6941 		ret = 0;
6942 		goto out;
6943 	}
6944 
6945 	if (log_level == 0) {
6946 		log_level = 1;
6947 		goto retry_load;
6948 	}
6949 	/* On ENOSPC, increase log buffer size and retry, unless custom
6950 	 * log_buf is specified.
6951 	 * Be careful to not overflow u32, though. Kernel's log buf size limit
6952 	 * isn't part of UAPI so it can always be bumped to full 4GB. So don't
6953 	 * multiply by 2 unless we are sure we'll fit within 32 bits.
6954 	 * Currently, we'll get -EINVAL when we reach (UINT_MAX >> 2).
6955 	 */
6956 	if (own_log_buf && errno == ENOSPC && log_buf_size <= UINT_MAX / 2)
6957 		goto retry_load;
6958 
6959 	ret = -errno;
6960 
6961 	/* post-process verifier log to improve error descriptions */
6962 	fixup_verifier_log(prog, log_buf, log_buf_size);
6963 
6964 	cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
6965 	pr_warn("prog '%s': BPF program load failed: %s\n", prog->name, cp);
6966 	pr_perm_msg(ret);
6967 
6968 	if (own_log_buf && log_buf && log_buf[0] != '\0') {
6969 		pr_warn("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
6970 			prog->name, log_buf);
6971 	}
6972 
6973 out:
6974 	if (own_log_buf)
6975 		free(log_buf);
6976 	return ret;
6977 }
6978 
6979 static char *find_prev_line(char *buf, char *cur)
6980 {
6981 	char *p;
6982 
6983 	if (cur == buf) /* end of a log buf */
6984 		return NULL;
6985 
6986 	p = cur - 1;
6987 	while (p - 1 >= buf && *(p - 1) != '\n')
6988 		p--;
6989 
6990 	return p;
6991 }
6992 
6993 static void patch_log(char *buf, size_t buf_sz, size_t log_sz,
6994 		      char *orig, size_t orig_sz, const char *patch)
6995 {
6996 	/* size of the remaining log content to the right from the to-be-replaced part */
6997 	size_t rem_sz = (buf + log_sz) - (orig + orig_sz);
6998 	size_t patch_sz = strlen(patch);
6999 
7000 	if (patch_sz != orig_sz) {
7001 		/* If patch line(s) are longer than original piece of verifier log,
7002 		 * shift log contents by (patch_sz - orig_sz) bytes to the right
7003 		 * starting from after to-be-replaced part of the log.
7004 		 *
7005 		 * If patch line(s) are shorter than original piece of verifier log,
7006 		 * shift log contents by (orig_sz - patch_sz) bytes to the left
7007 		 * starting from after to-be-replaced part of the log
7008 		 *
7009 		 * We need to be careful about not overflowing available
7010 		 * buf_sz capacity. If that's the case, we'll truncate the end
7011 		 * of the original log, as necessary.
7012 		 */
7013 		if (patch_sz > orig_sz) {
7014 			if (orig + patch_sz >= buf + buf_sz) {
7015 				/* patch is big enough to cover remaining space completely */
7016 				patch_sz -= (orig + patch_sz) - (buf + buf_sz) + 1;
7017 				rem_sz = 0;
7018 			} else if (patch_sz - orig_sz > buf_sz - log_sz) {
7019 				/* patch causes part of remaining log to be truncated */
7020 				rem_sz -= (patch_sz - orig_sz) - (buf_sz - log_sz);
7021 			}
7022 		}
7023 		/* shift remaining log to the right by calculated amount */
7024 		memmove(orig + patch_sz, orig + orig_sz, rem_sz);
7025 	}
7026 
7027 	memcpy(orig, patch, patch_sz);
7028 }
7029 
7030 static void fixup_log_failed_core_relo(struct bpf_program *prog,
7031 				       char *buf, size_t buf_sz, size_t log_sz,
7032 				       char *line1, char *line2, char *line3)
7033 {
7034 	/* Expected log for failed and not properly guarded CO-RE relocation:
7035 	 * line1 -> 123: (85) call unknown#195896080
7036 	 * line2 -> invalid func unknown#195896080
7037 	 * line3 -> <anything else or end of buffer>
7038 	 *
7039 	 * "123" is the index of the instruction that was poisoned. We extract
7040 	 * instruction index to find corresponding CO-RE relocation and
7041 	 * replace this part of the log with more relevant information about
7042 	 * failed CO-RE relocation.
7043 	 */
7044 	const struct bpf_core_relo *relo;
7045 	struct bpf_core_spec spec;
7046 	char patch[512], spec_buf[256];
7047 	int insn_idx, err, spec_len;
7048 
7049 	if (sscanf(line1, "%d: (%*d) call unknown#195896080\n", &insn_idx) != 1)
7050 		return;
7051 
7052 	relo = find_relo_core(prog, insn_idx);
7053 	if (!relo)
7054 		return;
7055 
7056 	err = bpf_core_parse_spec(prog->name, prog->obj->btf, relo, &spec);
7057 	if (err)
7058 		return;
7059 
7060 	spec_len = bpf_core_format_spec(spec_buf, sizeof(spec_buf), &spec);
7061 	snprintf(patch, sizeof(patch),
7062 		 "%d: <invalid CO-RE relocation>\n"
7063 		 "failed to resolve CO-RE relocation %s%s\n",
7064 		 insn_idx, spec_buf, spec_len >= sizeof(spec_buf) ? "..." : "");
7065 
7066 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7067 }
7068 
7069 static void fixup_log_missing_map_load(struct bpf_program *prog,
7070 				       char *buf, size_t buf_sz, size_t log_sz,
7071 				       char *line1, char *line2, char *line3)
7072 {
7073 	/* Expected log for failed and not properly guarded map reference:
7074 	 * line1 -> 123: (85) call unknown#2001000345
7075 	 * line2 -> invalid func unknown#2001000345
7076 	 * line3 -> <anything else or end of buffer>
7077 	 *
7078 	 * "123" is the index of the instruction that was poisoned.
7079 	 * "345" in "2001000345" is a map index in obj->maps to fetch map name.
7080 	 */
7081 	struct bpf_object *obj = prog->obj;
7082 	const struct bpf_map *map;
7083 	int insn_idx, map_idx;
7084 	char patch[128];
7085 
7086 	if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &map_idx) != 2)
7087 		return;
7088 
7089 	map_idx -= POISON_LDIMM64_MAP_BASE;
7090 	if (map_idx < 0 || map_idx >= obj->nr_maps)
7091 		return;
7092 	map = &obj->maps[map_idx];
7093 
7094 	snprintf(patch, sizeof(patch),
7095 		 "%d: <invalid BPF map reference>\n"
7096 		 "BPF map '%s' is referenced but wasn't created\n",
7097 		 insn_idx, map->name);
7098 
7099 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7100 }
7101 
7102 static void fixup_log_missing_kfunc_call(struct bpf_program *prog,
7103 					 char *buf, size_t buf_sz, size_t log_sz,
7104 					 char *line1, char *line2, char *line3)
7105 {
7106 	/* Expected log for failed and not properly guarded kfunc call:
7107 	 * line1 -> 123: (85) call unknown#2002000345
7108 	 * line2 -> invalid func unknown#2002000345
7109 	 * line3 -> <anything else or end of buffer>
7110 	 *
7111 	 * "123" is the index of the instruction that was poisoned.
7112 	 * "345" in "2002000345" is an extern index in obj->externs to fetch kfunc name.
7113 	 */
7114 	struct bpf_object *obj = prog->obj;
7115 	const struct extern_desc *ext;
7116 	int insn_idx, ext_idx;
7117 	char patch[128];
7118 
7119 	if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &ext_idx) != 2)
7120 		return;
7121 
7122 	ext_idx -= POISON_CALL_KFUNC_BASE;
7123 	if (ext_idx < 0 || ext_idx >= obj->nr_extern)
7124 		return;
7125 	ext = &obj->externs[ext_idx];
7126 
7127 	snprintf(patch, sizeof(patch),
7128 		 "%d: <invalid kfunc call>\n"
7129 		 "kfunc '%s' is referenced but wasn't resolved\n",
7130 		 insn_idx, ext->name);
7131 
7132 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
7133 }
7134 
7135 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz)
7136 {
7137 	/* look for familiar error patterns in last N lines of the log */
7138 	const size_t max_last_line_cnt = 10;
7139 	char *prev_line, *cur_line, *next_line;
7140 	size_t log_sz;
7141 	int i;
7142 
7143 	if (!buf)
7144 		return;
7145 
7146 	log_sz = strlen(buf) + 1;
7147 	next_line = buf + log_sz - 1;
7148 
7149 	for (i = 0; i < max_last_line_cnt; i++, next_line = cur_line) {
7150 		cur_line = find_prev_line(buf, next_line);
7151 		if (!cur_line)
7152 			return;
7153 
7154 		if (str_has_pfx(cur_line, "invalid func unknown#195896080\n")) {
7155 			prev_line = find_prev_line(buf, cur_line);
7156 			if (!prev_line)
7157 				continue;
7158 
7159 			/* failed CO-RE relocation case */
7160 			fixup_log_failed_core_relo(prog, buf, buf_sz, log_sz,
7161 						   prev_line, cur_line, next_line);
7162 			return;
7163 		} else if (str_has_pfx(cur_line, "invalid func unknown#"POISON_LDIMM64_MAP_PFX)) {
7164 			prev_line = find_prev_line(buf, cur_line);
7165 			if (!prev_line)
7166 				continue;
7167 
7168 			/* reference to uncreated BPF map */
7169 			fixup_log_missing_map_load(prog, buf, buf_sz, log_sz,
7170 						   prev_line, cur_line, next_line);
7171 			return;
7172 		} else if (str_has_pfx(cur_line, "invalid func unknown#"POISON_CALL_KFUNC_PFX)) {
7173 			prev_line = find_prev_line(buf, cur_line);
7174 			if (!prev_line)
7175 				continue;
7176 
7177 			/* reference to unresolved kfunc */
7178 			fixup_log_missing_kfunc_call(prog, buf, buf_sz, log_sz,
7179 						     prev_line, cur_line, next_line);
7180 			return;
7181 		}
7182 	}
7183 }
7184 
7185 static int bpf_program_record_relos(struct bpf_program *prog)
7186 {
7187 	struct bpf_object *obj = prog->obj;
7188 	int i;
7189 
7190 	for (i = 0; i < prog->nr_reloc; i++) {
7191 		struct reloc_desc *relo = &prog->reloc_desc[i];
7192 		struct extern_desc *ext = &obj->externs[relo->ext_idx];
7193 		int kind;
7194 
7195 		switch (relo->type) {
7196 		case RELO_EXTERN_LD64:
7197 			if (ext->type != EXT_KSYM)
7198 				continue;
7199 			kind = btf_is_var(btf__type_by_id(obj->btf, ext->btf_id)) ?
7200 				BTF_KIND_VAR : BTF_KIND_FUNC;
7201 			bpf_gen__record_extern(obj->gen_loader, ext->name,
7202 					       ext->is_weak, !ext->ksym.type_id,
7203 					       true, kind, relo->insn_idx);
7204 			break;
7205 		case RELO_EXTERN_CALL:
7206 			bpf_gen__record_extern(obj->gen_loader, ext->name,
7207 					       ext->is_weak, false, false, BTF_KIND_FUNC,
7208 					       relo->insn_idx);
7209 			break;
7210 		case RELO_CORE: {
7211 			struct bpf_core_relo cr = {
7212 				.insn_off = relo->insn_idx * 8,
7213 				.type_id = relo->core_relo->type_id,
7214 				.access_str_off = relo->core_relo->access_str_off,
7215 				.kind = relo->core_relo->kind,
7216 			};
7217 
7218 			bpf_gen__record_relo_core(obj->gen_loader, &cr);
7219 			break;
7220 		}
7221 		default:
7222 			continue;
7223 		}
7224 	}
7225 	return 0;
7226 }
7227 
7228 static int
7229 bpf_object__load_progs(struct bpf_object *obj, int log_level)
7230 {
7231 	struct bpf_program *prog;
7232 	size_t i;
7233 	int err;
7234 
7235 	for (i = 0; i < obj->nr_programs; i++) {
7236 		prog = &obj->programs[i];
7237 		err = bpf_object__sanitize_prog(obj, prog);
7238 		if (err)
7239 			return err;
7240 	}
7241 
7242 	for (i = 0; i < obj->nr_programs; i++) {
7243 		prog = &obj->programs[i];
7244 		if (prog_is_subprog(obj, prog))
7245 			continue;
7246 		if (!prog->autoload) {
7247 			pr_debug("prog '%s': skipped loading\n", prog->name);
7248 			continue;
7249 		}
7250 		prog->log_level |= log_level;
7251 
7252 		if (obj->gen_loader)
7253 			bpf_program_record_relos(prog);
7254 
7255 		err = bpf_object_load_prog(obj, prog, prog->insns, prog->insns_cnt,
7256 					   obj->license, obj->kern_version, &prog->fd);
7257 		if (err) {
7258 			pr_warn("prog '%s': failed to load: %d\n", prog->name, err);
7259 			return err;
7260 		}
7261 	}
7262 
7263 	bpf_object__free_relocs(obj);
7264 	return 0;
7265 }
7266 
7267 static const struct bpf_sec_def *find_sec_def(const char *sec_name);
7268 
7269 static int bpf_object_init_progs(struct bpf_object *obj, const struct bpf_object_open_opts *opts)
7270 {
7271 	struct bpf_program *prog;
7272 	int err;
7273 
7274 	bpf_object__for_each_program(prog, obj) {
7275 		prog->sec_def = find_sec_def(prog->sec_name);
7276 		if (!prog->sec_def) {
7277 			/* couldn't guess, but user might manually specify */
7278 			pr_debug("prog '%s': unrecognized ELF section name '%s'\n",
7279 				prog->name, prog->sec_name);
7280 			continue;
7281 		}
7282 
7283 		prog->type = prog->sec_def->prog_type;
7284 		prog->expected_attach_type = prog->sec_def->expected_attach_type;
7285 
7286 		/* sec_def can have custom callback which should be called
7287 		 * after bpf_program is initialized to adjust its properties
7288 		 */
7289 		if (prog->sec_def->prog_setup_fn) {
7290 			err = prog->sec_def->prog_setup_fn(prog, prog->sec_def->cookie);
7291 			if (err < 0) {
7292 				pr_warn("prog '%s': failed to initialize: %d\n",
7293 					prog->name, err);
7294 				return err;
7295 			}
7296 		}
7297 	}
7298 
7299 	return 0;
7300 }
7301 
7302 static struct bpf_object *bpf_object_open(const char *path, const void *obj_buf, size_t obj_buf_sz,
7303 					  const struct bpf_object_open_opts *opts)
7304 {
7305 	const char *obj_name, *kconfig, *btf_tmp_path;
7306 	struct bpf_object *obj;
7307 	char tmp_name[64];
7308 	int err;
7309 	char *log_buf;
7310 	size_t log_size;
7311 	__u32 log_level;
7312 
7313 	if (elf_version(EV_CURRENT) == EV_NONE) {
7314 		pr_warn("failed to init libelf for %s\n",
7315 			path ? : "(mem buf)");
7316 		return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
7317 	}
7318 
7319 	if (!OPTS_VALID(opts, bpf_object_open_opts))
7320 		return ERR_PTR(-EINVAL);
7321 
7322 	obj_name = OPTS_GET(opts, object_name, NULL);
7323 	if (obj_buf) {
7324 		if (!obj_name) {
7325 			snprintf(tmp_name, sizeof(tmp_name), "%lx-%lx",
7326 				 (unsigned long)obj_buf,
7327 				 (unsigned long)obj_buf_sz);
7328 			obj_name = tmp_name;
7329 		}
7330 		path = obj_name;
7331 		pr_debug("loading object '%s' from buffer\n", obj_name);
7332 	}
7333 
7334 	log_buf = OPTS_GET(opts, kernel_log_buf, NULL);
7335 	log_size = OPTS_GET(opts, kernel_log_size, 0);
7336 	log_level = OPTS_GET(opts, kernel_log_level, 0);
7337 	if (log_size > UINT_MAX)
7338 		return ERR_PTR(-EINVAL);
7339 	if (log_size && !log_buf)
7340 		return ERR_PTR(-EINVAL);
7341 
7342 	obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
7343 	if (IS_ERR(obj))
7344 		return obj;
7345 
7346 	obj->log_buf = log_buf;
7347 	obj->log_size = log_size;
7348 	obj->log_level = log_level;
7349 
7350 	btf_tmp_path = OPTS_GET(opts, btf_custom_path, NULL);
7351 	if (btf_tmp_path) {
7352 		if (strlen(btf_tmp_path) >= PATH_MAX) {
7353 			err = -ENAMETOOLONG;
7354 			goto out;
7355 		}
7356 		obj->btf_custom_path = strdup(btf_tmp_path);
7357 		if (!obj->btf_custom_path) {
7358 			err = -ENOMEM;
7359 			goto out;
7360 		}
7361 	}
7362 
7363 	kconfig = OPTS_GET(opts, kconfig, NULL);
7364 	if (kconfig) {
7365 		obj->kconfig = strdup(kconfig);
7366 		if (!obj->kconfig) {
7367 			err = -ENOMEM;
7368 			goto out;
7369 		}
7370 	}
7371 
7372 	err = bpf_object__elf_init(obj);
7373 	err = err ? : bpf_object__check_endianness(obj);
7374 	err = err ? : bpf_object__elf_collect(obj);
7375 	err = err ? : bpf_object__collect_externs(obj);
7376 	err = err ? : bpf_object_fixup_btf(obj);
7377 	err = err ? : bpf_object__init_maps(obj, opts);
7378 	err = err ? : bpf_object_init_progs(obj, opts);
7379 	err = err ? : bpf_object__collect_relos(obj);
7380 	if (err)
7381 		goto out;
7382 
7383 	bpf_object__elf_finish(obj);
7384 
7385 	return obj;
7386 out:
7387 	bpf_object__close(obj);
7388 	return ERR_PTR(err);
7389 }
7390 
7391 struct bpf_object *
7392 bpf_object__open_file(const char *path, const struct bpf_object_open_opts *opts)
7393 {
7394 	if (!path)
7395 		return libbpf_err_ptr(-EINVAL);
7396 
7397 	pr_debug("loading %s\n", path);
7398 
7399 	return libbpf_ptr(bpf_object_open(path, NULL, 0, opts));
7400 }
7401 
7402 struct bpf_object *bpf_object__open(const char *path)
7403 {
7404 	return bpf_object__open_file(path, NULL);
7405 }
7406 
7407 struct bpf_object *
7408 bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
7409 		     const struct bpf_object_open_opts *opts)
7410 {
7411 	if (!obj_buf || obj_buf_sz == 0)
7412 		return libbpf_err_ptr(-EINVAL);
7413 
7414 	return libbpf_ptr(bpf_object_open(NULL, obj_buf, obj_buf_sz, opts));
7415 }
7416 
7417 static int bpf_object_unload(struct bpf_object *obj)
7418 {
7419 	size_t i;
7420 
7421 	if (!obj)
7422 		return libbpf_err(-EINVAL);
7423 
7424 	for (i = 0; i < obj->nr_maps; i++) {
7425 		zclose(obj->maps[i].fd);
7426 		if (obj->maps[i].st_ops)
7427 			zfree(&obj->maps[i].st_ops->kern_vdata);
7428 	}
7429 
7430 	for (i = 0; i < obj->nr_programs; i++)
7431 		bpf_program__unload(&obj->programs[i]);
7432 
7433 	return 0;
7434 }
7435 
7436 static int bpf_object__sanitize_maps(struct bpf_object *obj)
7437 {
7438 	struct bpf_map *m;
7439 
7440 	bpf_object__for_each_map(m, obj) {
7441 		if (!bpf_map__is_internal(m))
7442 			continue;
7443 		if (!kernel_supports(obj, FEAT_ARRAY_MMAP))
7444 			m->def.map_flags &= ~BPF_F_MMAPABLE;
7445 	}
7446 
7447 	return 0;
7448 }
7449 
7450 int libbpf_kallsyms_parse(kallsyms_cb_t cb, void *ctx)
7451 {
7452 	char sym_type, sym_name[500];
7453 	unsigned long long sym_addr;
7454 	int ret, err = 0;
7455 	FILE *f;
7456 
7457 	f = fopen("/proc/kallsyms", "re");
7458 	if (!f) {
7459 		err = -errno;
7460 		pr_warn("failed to open /proc/kallsyms: %d\n", err);
7461 		return err;
7462 	}
7463 
7464 	while (true) {
7465 		ret = fscanf(f, "%llx %c %499s%*[^\n]\n",
7466 			     &sym_addr, &sym_type, sym_name);
7467 		if (ret == EOF && feof(f))
7468 			break;
7469 		if (ret != 3) {
7470 			pr_warn("failed to read kallsyms entry: %d\n", ret);
7471 			err = -EINVAL;
7472 			break;
7473 		}
7474 
7475 		err = cb(sym_addr, sym_type, sym_name, ctx);
7476 		if (err)
7477 			break;
7478 	}
7479 
7480 	fclose(f);
7481 	return err;
7482 }
7483 
7484 static int kallsyms_cb(unsigned long long sym_addr, char sym_type,
7485 		       const char *sym_name, void *ctx)
7486 {
7487 	struct bpf_object *obj = ctx;
7488 	const struct btf_type *t;
7489 	struct extern_desc *ext;
7490 
7491 	ext = find_extern_by_name(obj, sym_name);
7492 	if (!ext || ext->type != EXT_KSYM)
7493 		return 0;
7494 
7495 	t = btf__type_by_id(obj->btf, ext->btf_id);
7496 	if (!btf_is_var(t))
7497 		return 0;
7498 
7499 	if (ext->is_set && ext->ksym.addr != sym_addr) {
7500 		pr_warn("extern (ksym) '%s': resolution is ambiguous: 0x%llx or 0x%llx\n",
7501 			sym_name, ext->ksym.addr, sym_addr);
7502 		return -EINVAL;
7503 	}
7504 	if (!ext->is_set) {
7505 		ext->is_set = true;
7506 		ext->ksym.addr = sym_addr;
7507 		pr_debug("extern (ksym) '%s': set to 0x%llx\n", sym_name, sym_addr);
7508 	}
7509 	return 0;
7510 }
7511 
7512 static int bpf_object__read_kallsyms_file(struct bpf_object *obj)
7513 {
7514 	return libbpf_kallsyms_parse(kallsyms_cb, obj);
7515 }
7516 
7517 static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
7518 			    __u16 kind, struct btf **res_btf,
7519 			    struct module_btf **res_mod_btf)
7520 {
7521 	struct module_btf *mod_btf;
7522 	struct btf *btf;
7523 	int i, id, err;
7524 
7525 	btf = obj->btf_vmlinux;
7526 	mod_btf = NULL;
7527 	id = btf__find_by_name_kind(btf, ksym_name, kind);
7528 
7529 	if (id == -ENOENT) {
7530 		err = load_module_btfs(obj);
7531 		if (err)
7532 			return err;
7533 
7534 		for (i = 0; i < obj->btf_module_cnt; i++) {
7535 			/* we assume module_btf's BTF FD is always >0 */
7536 			mod_btf = &obj->btf_modules[i];
7537 			btf = mod_btf->btf;
7538 			id = btf__find_by_name_kind_own(btf, ksym_name, kind);
7539 			if (id != -ENOENT)
7540 				break;
7541 		}
7542 	}
7543 	if (id <= 0)
7544 		return -ESRCH;
7545 
7546 	*res_btf = btf;
7547 	*res_mod_btf = mod_btf;
7548 	return id;
7549 }
7550 
7551 static int bpf_object__resolve_ksym_var_btf_id(struct bpf_object *obj,
7552 					       struct extern_desc *ext)
7553 {
7554 	const struct btf_type *targ_var, *targ_type;
7555 	__u32 targ_type_id, local_type_id;
7556 	struct module_btf *mod_btf = NULL;
7557 	const char *targ_var_name;
7558 	struct btf *btf = NULL;
7559 	int id, err;
7560 
7561 	id = find_ksym_btf_id(obj, ext->name, BTF_KIND_VAR, &btf, &mod_btf);
7562 	if (id < 0) {
7563 		if (id == -ESRCH && ext->is_weak)
7564 			return 0;
7565 		pr_warn("extern (var ksym) '%s': not found in kernel BTF\n",
7566 			ext->name);
7567 		return id;
7568 	}
7569 
7570 	/* find local type_id */
7571 	local_type_id = ext->ksym.type_id;
7572 
7573 	/* find target type_id */
7574 	targ_var = btf__type_by_id(btf, id);
7575 	targ_var_name = btf__name_by_offset(btf, targ_var->name_off);
7576 	targ_type = skip_mods_and_typedefs(btf, targ_var->type, &targ_type_id);
7577 
7578 	err = bpf_core_types_are_compat(obj->btf, local_type_id,
7579 					btf, targ_type_id);
7580 	if (err <= 0) {
7581 		const struct btf_type *local_type;
7582 		const char *targ_name, *local_name;
7583 
7584 		local_type = btf__type_by_id(obj->btf, local_type_id);
7585 		local_name = btf__name_by_offset(obj->btf, local_type->name_off);
7586 		targ_name = btf__name_by_offset(btf, targ_type->name_off);
7587 
7588 		pr_warn("extern (var ksym) '%s': incompatible types, expected [%d] %s %s, but kernel has [%d] %s %s\n",
7589 			ext->name, local_type_id,
7590 			btf_kind_str(local_type), local_name, targ_type_id,
7591 			btf_kind_str(targ_type), targ_name);
7592 		return -EINVAL;
7593 	}
7594 
7595 	ext->is_set = true;
7596 	ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
7597 	ext->ksym.kernel_btf_id = id;
7598 	pr_debug("extern (var ksym) '%s': resolved to [%d] %s %s\n",
7599 		 ext->name, id, btf_kind_str(targ_var), targ_var_name);
7600 
7601 	return 0;
7602 }
7603 
7604 static int bpf_object__resolve_ksym_func_btf_id(struct bpf_object *obj,
7605 						struct extern_desc *ext)
7606 {
7607 	int local_func_proto_id, kfunc_proto_id, kfunc_id;
7608 	struct module_btf *mod_btf = NULL;
7609 	const struct btf_type *kern_func;
7610 	struct btf *kern_btf = NULL;
7611 	int ret;
7612 
7613 	local_func_proto_id = ext->ksym.type_id;
7614 
7615 	kfunc_id = find_ksym_btf_id(obj, ext->name, BTF_KIND_FUNC, &kern_btf, &mod_btf);
7616 	if (kfunc_id < 0) {
7617 		if (kfunc_id == -ESRCH && ext->is_weak)
7618 			return 0;
7619 		pr_warn("extern (func ksym) '%s': not found in kernel or module BTFs\n",
7620 			ext->name);
7621 		return kfunc_id;
7622 	}
7623 
7624 	kern_func = btf__type_by_id(kern_btf, kfunc_id);
7625 	kfunc_proto_id = kern_func->type;
7626 
7627 	ret = bpf_core_types_are_compat(obj->btf, local_func_proto_id,
7628 					kern_btf, kfunc_proto_id);
7629 	if (ret <= 0) {
7630 		pr_warn("extern (func ksym) '%s': func_proto [%d] incompatible with %s [%d]\n",
7631 			ext->name, local_func_proto_id,
7632 			mod_btf ? mod_btf->name : "vmlinux", kfunc_proto_id);
7633 		return -EINVAL;
7634 	}
7635 
7636 	/* set index for module BTF fd in fd_array, if unset */
7637 	if (mod_btf && !mod_btf->fd_array_idx) {
7638 		/* insn->off is s16 */
7639 		if (obj->fd_array_cnt == INT16_MAX) {
7640 			pr_warn("extern (func ksym) '%s': module BTF fd index %d too big to fit in bpf_insn offset\n",
7641 				ext->name, mod_btf->fd_array_idx);
7642 			return -E2BIG;
7643 		}
7644 		/* Cannot use index 0 for module BTF fd */
7645 		if (!obj->fd_array_cnt)
7646 			obj->fd_array_cnt = 1;
7647 
7648 		ret = libbpf_ensure_mem((void **)&obj->fd_array, &obj->fd_array_cap, sizeof(int),
7649 					obj->fd_array_cnt + 1);
7650 		if (ret)
7651 			return ret;
7652 		mod_btf->fd_array_idx = obj->fd_array_cnt;
7653 		/* we assume module BTF FD is always >0 */
7654 		obj->fd_array[obj->fd_array_cnt++] = mod_btf->fd;
7655 	}
7656 
7657 	ext->is_set = true;
7658 	ext->ksym.kernel_btf_id = kfunc_id;
7659 	ext->ksym.btf_fd_idx = mod_btf ? mod_btf->fd_array_idx : 0;
7660 	/* Also set kernel_btf_obj_fd to make sure that bpf_object__relocate_data()
7661 	 * populates FD into ld_imm64 insn when it's used to point to kfunc.
7662 	 * {kernel_btf_id, btf_fd_idx} -> fixup bpf_call.
7663 	 * {kernel_btf_id, kernel_btf_obj_fd} -> fixup ld_imm64.
7664 	 */
7665 	ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
7666 	pr_debug("extern (func ksym) '%s': resolved to %s [%d]\n",
7667 		 ext->name, mod_btf ? mod_btf->name : "vmlinux", kfunc_id);
7668 
7669 	return 0;
7670 }
7671 
7672 static int bpf_object__resolve_ksyms_btf_id(struct bpf_object *obj)
7673 {
7674 	const struct btf_type *t;
7675 	struct extern_desc *ext;
7676 	int i, err;
7677 
7678 	for (i = 0; i < obj->nr_extern; i++) {
7679 		ext = &obj->externs[i];
7680 		if (ext->type != EXT_KSYM || !ext->ksym.type_id)
7681 			continue;
7682 
7683 		if (obj->gen_loader) {
7684 			ext->is_set = true;
7685 			ext->ksym.kernel_btf_obj_fd = 0;
7686 			ext->ksym.kernel_btf_id = 0;
7687 			continue;
7688 		}
7689 		t = btf__type_by_id(obj->btf, ext->btf_id);
7690 		if (btf_is_var(t))
7691 			err = bpf_object__resolve_ksym_var_btf_id(obj, ext);
7692 		else
7693 			err = bpf_object__resolve_ksym_func_btf_id(obj, ext);
7694 		if (err)
7695 			return err;
7696 	}
7697 	return 0;
7698 }
7699 
7700 static int bpf_object__resolve_externs(struct bpf_object *obj,
7701 				       const char *extra_kconfig)
7702 {
7703 	bool need_config = false, need_kallsyms = false;
7704 	bool need_vmlinux_btf = false;
7705 	struct extern_desc *ext;
7706 	void *kcfg_data = NULL;
7707 	int err, i;
7708 
7709 	if (obj->nr_extern == 0)
7710 		return 0;
7711 
7712 	if (obj->kconfig_map_idx >= 0)
7713 		kcfg_data = obj->maps[obj->kconfig_map_idx].mmaped;
7714 
7715 	for (i = 0; i < obj->nr_extern; i++) {
7716 		ext = &obj->externs[i];
7717 
7718 		if (ext->type == EXT_KSYM) {
7719 			if (ext->ksym.type_id)
7720 				need_vmlinux_btf = true;
7721 			else
7722 				need_kallsyms = true;
7723 			continue;
7724 		} else if (ext->type == EXT_KCFG) {
7725 			void *ext_ptr = kcfg_data + ext->kcfg.data_off;
7726 			__u64 value = 0;
7727 
7728 			/* Kconfig externs need actual /proc/config.gz */
7729 			if (str_has_pfx(ext->name, "CONFIG_")) {
7730 				need_config = true;
7731 				continue;
7732 			}
7733 
7734 			/* Virtual kcfg externs are customly handled by libbpf */
7735 			if (strcmp(ext->name, "LINUX_KERNEL_VERSION") == 0) {
7736 				value = get_kernel_version();
7737 				if (!value) {
7738 					pr_warn("extern (kcfg) '%s': failed to get kernel version\n", ext->name);
7739 					return -EINVAL;
7740 				}
7741 			} else if (strcmp(ext->name, "LINUX_HAS_BPF_COOKIE") == 0) {
7742 				value = kernel_supports(obj, FEAT_BPF_COOKIE);
7743 			} else if (strcmp(ext->name, "LINUX_HAS_SYSCALL_WRAPPER") == 0) {
7744 				value = kernel_supports(obj, FEAT_SYSCALL_WRAPPER);
7745 			} else if (!str_has_pfx(ext->name, "LINUX_") || !ext->is_weak) {
7746 				/* Currently libbpf supports only CONFIG_ and LINUX_ prefixed
7747 				 * __kconfig externs, where LINUX_ ones are virtual and filled out
7748 				 * customly by libbpf (their values don't come from Kconfig).
7749 				 * If LINUX_xxx variable is not recognized by libbpf, but is marked
7750 				 * __weak, it defaults to zero value, just like for CONFIG_xxx
7751 				 * externs.
7752 				 */
7753 				pr_warn("extern (kcfg) '%s': unrecognized virtual extern\n", ext->name);
7754 				return -EINVAL;
7755 			}
7756 
7757 			err = set_kcfg_value_num(ext, ext_ptr, value);
7758 			if (err)
7759 				return err;
7760 			pr_debug("extern (kcfg) '%s': set to 0x%llx\n",
7761 				 ext->name, (long long)value);
7762 		} else {
7763 			pr_warn("extern '%s': unrecognized extern kind\n", ext->name);
7764 			return -EINVAL;
7765 		}
7766 	}
7767 	if (need_config && extra_kconfig) {
7768 		err = bpf_object__read_kconfig_mem(obj, extra_kconfig, kcfg_data);
7769 		if (err)
7770 			return -EINVAL;
7771 		need_config = false;
7772 		for (i = 0; i < obj->nr_extern; i++) {
7773 			ext = &obj->externs[i];
7774 			if (ext->type == EXT_KCFG && !ext->is_set) {
7775 				need_config = true;
7776 				break;
7777 			}
7778 		}
7779 	}
7780 	if (need_config) {
7781 		err = bpf_object__read_kconfig_file(obj, kcfg_data);
7782 		if (err)
7783 			return -EINVAL;
7784 	}
7785 	if (need_kallsyms) {
7786 		err = bpf_object__read_kallsyms_file(obj);
7787 		if (err)
7788 			return -EINVAL;
7789 	}
7790 	if (need_vmlinux_btf) {
7791 		err = bpf_object__resolve_ksyms_btf_id(obj);
7792 		if (err)
7793 			return -EINVAL;
7794 	}
7795 	for (i = 0; i < obj->nr_extern; i++) {
7796 		ext = &obj->externs[i];
7797 
7798 		if (!ext->is_set && !ext->is_weak) {
7799 			pr_warn("extern '%s' (strong): not resolved\n", ext->name);
7800 			return -ESRCH;
7801 		} else if (!ext->is_set) {
7802 			pr_debug("extern '%s' (weak): not resolved, defaulting to zero\n",
7803 				 ext->name);
7804 		}
7805 	}
7806 
7807 	return 0;
7808 }
7809 
7810 static void bpf_map_prepare_vdata(const struct bpf_map *map)
7811 {
7812 	struct bpf_struct_ops *st_ops;
7813 	__u32 i;
7814 
7815 	st_ops = map->st_ops;
7816 	for (i = 0; i < btf_vlen(st_ops->type); i++) {
7817 		struct bpf_program *prog = st_ops->progs[i];
7818 		void *kern_data;
7819 		int prog_fd;
7820 
7821 		if (!prog)
7822 			continue;
7823 
7824 		prog_fd = bpf_program__fd(prog);
7825 		kern_data = st_ops->kern_vdata + st_ops->kern_func_off[i];
7826 		*(unsigned long *)kern_data = prog_fd;
7827 	}
7828 }
7829 
7830 static int bpf_object_prepare_struct_ops(struct bpf_object *obj)
7831 {
7832 	int i;
7833 
7834 	for (i = 0; i < obj->nr_maps; i++)
7835 		if (bpf_map__is_struct_ops(&obj->maps[i]))
7836 			bpf_map_prepare_vdata(&obj->maps[i]);
7837 
7838 	return 0;
7839 }
7840 
7841 static int bpf_object_load(struct bpf_object *obj, int extra_log_level, const char *target_btf_path)
7842 {
7843 	int err, i;
7844 
7845 	if (!obj)
7846 		return libbpf_err(-EINVAL);
7847 
7848 	if (obj->loaded) {
7849 		pr_warn("object '%s': load can't be attempted twice\n", obj->name);
7850 		return libbpf_err(-EINVAL);
7851 	}
7852 
7853 	if (obj->gen_loader)
7854 		bpf_gen__init(obj->gen_loader, extra_log_level, obj->nr_programs, obj->nr_maps);
7855 
7856 	err = bpf_object__probe_loading(obj);
7857 	err = err ? : bpf_object__load_vmlinux_btf(obj, false);
7858 	err = err ? : bpf_object__resolve_externs(obj, obj->kconfig);
7859 	err = err ? : bpf_object__sanitize_and_load_btf(obj);
7860 	err = err ? : bpf_object__sanitize_maps(obj);
7861 	err = err ? : bpf_object__init_kern_struct_ops_maps(obj);
7862 	err = err ? : bpf_object__create_maps(obj);
7863 	err = err ? : bpf_object__relocate(obj, obj->btf_custom_path ? : target_btf_path);
7864 	err = err ? : bpf_object__load_progs(obj, extra_log_level);
7865 	err = err ? : bpf_object_init_prog_arrays(obj);
7866 	err = err ? : bpf_object_prepare_struct_ops(obj);
7867 
7868 	if (obj->gen_loader) {
7869 		/* reset FDs */
7870 		if (obj->btf)
7871 			btf__set_fd(obj->btf, -1);
7872 		for (i = 0; i < obj->nr_maps; i++)
7873 			obj->maps[i].fd = -1;
7874 		if (!err)
7875 			err = bpf_gen__finish(obj->gen_loader, obj->nr_programs, obj->nr_maps);
7876 	}
7877 
7878 	/* clean up fd_array */
7879 	zfree(&obj->fd_array);
7880 
7881 	/* clean up module BTFs */
7882 	for (i = 0; i < obj->btf_module_cnt; i++) {
7883 		close(obj->btf_modules[i].fd);
7884 		btf__free(obj->btf_modules[i].btf);
7885 		free(obj->btf_modules[i].name);
7886 	}
7887 	free(obj->btf_modules);
7888 
7889 	/* clean up vmlinux BTF */
7890 	btf__free(obj->btf_vmlinux);
7891 	obj->btf_vmlinux = NULL;
7892 
7893 	obj->loaded = true; /* doesn't matter if successfully or not */
7894 
7895 	if (err)
7896 		goto out;
7897 
7898 	return 0;
7899 out:
7900 	/* unpin any maps that were auto-pinned during load */
7901 	for (i = 0; i < obj->nr_maps; i++)
7902 		if (obj->maps[i].pinned && !obj->maps[i].reused)
7903 			bpf_map__unpin(&obj->maps[i], NULL);
7904 
7905 	bpf_object_unload(obj);
7906 	pr_warn("failed to load object '%s'\n", obj->path);
7907 	return libbpf_err(err);
7908 }
7909 
7910 int bpf_object__load(struct bpf_object *obj)
7911 {
7912 	return bpf_object_load(obj, 0, NULL);
7913 }
7914 
7915 static int make_parent_dir(const char *path)
7916 {
7917 	char *cp, errmsg[STRERR_BUFSIZE];
7918 	char *dname, *dir;
7919 	int err = 0;
7920 
7921 	dname = strdup(path);
7922 	if (dname == NULL)
7923 		return -ENOMEM;
7924 
7925 	dir = dirname(dname);
7926 	if (mkdir(dir, 0700) && errno != EEXIST)
7927 		err = -errno;
7928 
7929 	free(dname);
7930 	if (err) {
7931 		cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
7932 		pr_warn("failed to mkdir %s: %s\n", path, cp);
7933 	}
7934 	return err;
7935 }
7936 
7937 static int check_path(const char *path)
7938 {
7939 	char *cp, errmsg[STRERR_BUFSIZE];
7940 	struct statfs st_fs;
7941 	char *dname, *dir;
7942 	int err = 0;
7943 
7944 	if (path == NULL)
7945 		return -EINVAL;
7946 
7947 	dname = strdup(path);
7948 	if (dname == NULL)
7949 		return -ENOMEM;
7950 
7951 	dir = dirname(dname);
7952 	if (statfs(dir, &st_fs)) {
7953 		cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
7954 		pr_warn("failed to statfs %s: %s\n", dir, cp);
7955 		err = -errno;
7956 	}
7957 	free(dname);
7958 
7959 	if (!err && st_fs.f_type != BPF_FS_MAGIC) {
7960 		pr_warn("specified path %s is not on BPF FS\n", path);
7961 		err = -EINVAL;
7962 	}
7963 
7964 	return err;
7965 }
7966 
7967 int bpf_program__pin(struct bpf_program *prog, const char *path)
7968 {
7969 	char *cp, errmsg[STRERR_BUFSIZE];
7970 	int err;
7971 
7972 	if (prog->fd < 0) {
7973 		pr_warn("prog '%s': can't pin program that wasn't loaded\n", prog->name);
7974 		return libbpf_err(-EINVAL);
7975 	}
7976 
7977 	err = make_parent_dir(path);
7978 	if (err)
7979 		return libbpf_err(err);
7980 
7981 	err = check_path(path);
7982 	if (err)
7983 		return libbpf_err(err);
7984 
7985 	if (bpf_obj_pin(prog->fd, path)) {
7986 		err = -errno;
7987 		cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
7988 		pr_warn("prog '%s': failed to pin at '%s': %s\n", prog->name, path, cp);
7989 		return libbpf_err(err);
7990 	}
7991 
7992 	pr_debug("prog '%s': pinned at '%s'\n", prog->name, path);
7993 	return 0;
7994 }
7995 
7996 int bpf_program__unpin(struct bpf_program *prog, const char *path)
7997 {
7998 	int err;
7999 
8000 	if (prog->fd < 0) {
8001 		pr_warn("prog '%s': can't unpin program that wasn't loaded\n", prog->name);
8002 		return libbpf_err(-EINVAL);
8003 	}
8004 
8005 	err = check_path(path);
8006 	if (err)
8007 		return libbpf_err(err);
8008 
8009 	err = unlink(path);
8010 	if (err)
8011 		return libbpf_err(-errno);
8012 
8013 	pr_debug("prog '%s': unpinned from '%s'\n", prog->name, path);
8014 	return 0;
8015 }
8016 
8017 int bpf_map__pin(struct bpf_map *map, const char *path)
8018 {
8019 	char *cp, errmsg[STRERR_BUFSIZE];
8020 	int err;
8021 
8022 	if (map == NULL) {
8023 		pr_warn("invalid map pointer\n");
8024 		return libbpf_err(-EINVAL);
8025 	}
8026 
8027 	if (map->pin_path) {
8028 		if (path && strcmp(path, map->pin_path)) {
8029 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
8030 				bpf_map__name(map), map->pin_path, path);
8031 			return libbpf_err(-EINVAL);
8032 		} else if (map->pinned) {
8033 			pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
8034 				 bpf_map__name(map), map->pin_path);
8035 			return 0;
8036 		}
8037 	} else {
8038 		if (!path) {
8039 			pr_warn("missing a path to pin map '%s' at\n",
8040 				bpf_map__name(map));
8041 			return libbpf_err(-EINVAL);
8042 		} else if (map->pinned) {
8043 			pr_warn("map '%s' already pinned\n", bpf_map__name(map));
8044 			return libbpf_err(-EEXIST);
8045 		}
8046 
8047 		map->pin_path = strdup(path);
8048 		if (!map->pin_path) {
8049 			err = -errno;
8050 			goto out_err;
8051 		}
8052 	}
8053 
8054 	err = make_parent_dir(map->pin_path);
8055 	if (err)
8056 		return libbpf_err(err);
8057 
8058 	err = check_path(map->pin_path);
8059 	if (err)
8060 		return libbpf_err(err);
8061 
8062 	if (bpf_obj_pin(map->fd, map->pin_path)) {
8063 		err = -errno;
8064 		goto out_err;
8065 	}
8066 
8067 	map->pinned = true;
8068 	pr_debug("pinned map '%s'\n", map->pin_path);
8069 
8070 	return 0;
8071 
8072 out_err:
8073 	cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
8074 	pr_warn("failed to pin map: %s\n", cp);
8075 	return libbpf_err(err);
8076 }
8077 
8078 int bpf_map__unpin(struct bpf_map *map, const char *path)
8079 {
8080 	int err;
8081 
8082 	if (map == NULL) {
8083 		pr_warn("invalid map pointer\n");
8084 		return libbpf_err(-EINVAL);
8085 	}
8086 
8087 	if (map->pin_path) {
8088 		if (path && strcmp(path, map->pin_path)) {
8089 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
8090 				bpf_map__name(map), map->pin_path, path);
8091 			return libbpf_err(-EINVAL);
8092 		}
8093 		path = map->pin_path;
8094 	} else if (!path) {
8095 		pr_warn("no path to unpin map '%s' from\n",
8096 			bpf_map__name(map));
8097 		return libbpf_err(-EINVAL);
8098 	}
8099 
8100 	err = check_path(path);
8101 	if (err)
8102 		return libbpf_err(err);
8103 
8104 	err = unlink(path);
8105 	if (err != 0)
8106 		return libbpf_err(-errno);
8107 
8108 	map->pinned = false;
8109 	pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path);
8110 
8111 	return 0;
8112 }
8113 
8114 int bpf_map__set_pin_path(struct bpf_map *map, const char *path)
8115 {
8116 	char *new = NULL;
8117 
8118 	if (path) {
8119 		new = strdup(path);
8120 		if (!new)
8121 			return libbpf_err(-errno);
8122 	}
8123 
8124 	free(map->pin_path);
8125 	map->pin_path = new;
8126 	return 0;
8127 }
8128 
8129 __alias(bpf_map__pin_path)
8130 const char *bpf_map__get_pin_path(const struct bpf_map *map);
8131 
8132 const char *bpf_map__pin_path(const struct bpf_map *map)
8133 {
8134 	return map->pin_path;
8135 }
8136 
8137 bool bpf_map__is_pinned(const struct bpf_map *map)
8138 {
8139 	return map->pinned;
8140 }
8141 
8142 static void sanitize_pin_path(char *s)
8143 {
8144 	/* bpffs disallows periods in path names */
8145 	while (*s) {
8146 		if (*s == '.')
8147 			*s = '_';
8148 		s++;
8149 	}
8150 }
8151 
8152 int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
8153 {
8154 	struct bpf_map *map;
8155 	int err;
8156 
8157 	if (!obj)
8158 		return libbpf_err(-ENOENT);
8159 
8160 	if (!obj->loaded) {
8161 		pr_warn("object not yet loaded; load it first\n");
8162 		return libbpf_err(-ENOENT);
8163 	}
8164 
8165 	bpf_object__for_each_map(map, obj) {
8166 		char *pin_path = NULL;
8167 		char buf[PATH_MAX];
8168 
8169 		if (!map->autocreate)
8170 			continue;
8171 
8172 		if (path) {
8173 			err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
8174 			if (err)
8175 				goto err_unpin_maps;
8176 			sanitize_pin_path(buf);
8177 			pin_path = buf;
8178 		} else if (!map->pin_path) {
8179 			continue;
8180 		}
8181 
8182 		err = bpf_map__pin(map, pin_path);
8183 		if (err)
8184 			goto err_unpin_maps;
8185 	}
8186 
8187 	return 0;
8188 
8189 err_unpin_maps:
8190 	while ((map = bpf_object__prev_map(obj, map))) {
8191 		if (!map->pin_path)
8192 			continue;
8193 
8194 		bpf_map__unpin(map, NULL);
8195 	}
8196 
8197 	return libbpf_err(err);
8198 }
8199 
8200 int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
8201 {
8202 	struct bpf_map *map;
8203 	int err;
8204 
8205 	if (!obj)
8206 		return libbpf_err(-ENOENT);
8207 
8208 	bpf_object__for_each_map(map, obj) {
8209 		char *pin_path = NULL;
8210 		char buf[PATH_MAX];
8211 
8212 		if (path) {
8213 			err = pathname_concat(buf, sizeof(buf), path, bpf_map__name(map));
8214 			if (err)
8215 				return libbpf_err(err);
8216 			sanitize_pin_path(buf);
8217 			pin_path = buf;
8218 		} else if (!map->pin_path) {
8219 			continue;
8220 		}
8221 
8222 		err = bpf_map__unpin(map, pin_path);
8223 		if (err)
8224 			return libbpf_err(err);
8225 	}
8226 
8227 	return 0;
8228 }
8229 
8230 int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
8231 {
8232 	struct bpf_program *prog;
8233 	char buf[PATH_MAX];
8234 	int err;
8235 
8236 	if (!obj)
8237 		return libbpf_err(-ENOENT);
8238 
8239 	if (!obj->loaded) {
8240 		pr_warn("object not yet loaded; load it first\n");
8241 		return libbpf_err(-ENOENT);
8242 	}
8243 
8244 	bpf_object__for_each_program(prog, obj) {
8245 		err = pathname_concat(buf, sizeof(buf), path, prog->name);
8246 		if (err)
8247 			goto err_unpin_programs;
8248 
8249 		err = bpf_program__pin(prog, buf);
8250 		if (err)
8251 			goto err_unpin_programs;
8252 	}
8253 
8254 	return 0;
8255 
8256 err_unpin_programs:
8257 	while ((prog = bpf_object__prev_program(obj, prog))) {
8258 		if (pathname_concat(buf, sizeof(buf), path, prog->name))
8259 			continue;
8260 
8261 		bpf_program__unpin(prog, buf);
8262 	}
8263 
8264 	return libbpf_err(err);
8265 }
8266 
8267 int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
8268 {
8269 	struct bpf_program *prog;
8270 	int err;
8271 
8272 	if (!obj)
8273 		return libbpf_err(-ENOENT);
8274 
8275 	bpf_object__for_each_program(prog, obj) {
8276 		char buf[PATH_MAX];
8277 
8278 		err = pathname_concat(buf, sizeof(buf), path, prog->name);
8279 		if (err)
8280 			return libbpf_err(err);
8281 
8282 		err = bpf_program__unpin(prog, buf);
8283 		if (err)
8284 			return libbpf_err(err);
8285 	}
8286 
8287 	return 0;
8288 }
8289 
8290 int bpf_object__pin(struct bpf_object *obj, const char *path)
8291 {
8292 	int err;
8293 
8294 	err = bpf_object__pin_maps(obj, path);
8295 	if (err)
8296 		return libbpf_err(err);
8297 
8298 	err = bpf_object__pin_programs(obj, path);
8299 	if (err) {
8300 		bpf_object__unpin_maps(obj, path);
8301 		return libbpf_err(err);
8302 	}
8303 
8304 	return 0;
8305 }
8306 
8307 static void bpf_map__destroy(struct bpf_map *map)
8308 {
8309 	if (map->inner_map) {
8310 		bpf_map__destroy(map->inner_map);
8311 		zfree(&map->inner_map);
8312 	}
8313 
8314 	zfree(&map->init_slots);
8315 	map->init_slots_sz = 0;
8316 
8317 	if (map->mmaped) {
8318 		size_t mmap_sz;
8319 
8320 		mmap_sz = bpf_map_mmap_sz(map->def.value_size, map->def.max_entries);
8321 		munmap(map->mmaped, mmap_sz);
8322 		map->mmaped = NULL;
8323 	}
8324 
8325 	if (map->st_ops) {
8326 		zfree(&map->st_ops->data);
8327 		zfree(&map->st_ops->progs);
8328 		zfree(&map->st_ops->kern_func_off);
8329 		zfree(&map->st_ops);
8330 	}
8331 
8332 	zfree(&map->name);
8333 	zfree(&map->real_name);
8334 	zfree(&map->pin_path);
8335 
8336 	if (map->fd >= 0)
8337 		zclose(map->fd);
8338 }
8339 
8340 void bpf_object__close(struct bpf_object *obj)
8341 {
8342 	size_t i;
8343 
8344 	if (IS_ERR_OR_NULL(obj))
8345 		return;
8346 
8347 	usdt_manager_free(obj->usdt_man);
8348 	obj->usdt_man = NULL;
8349 
8350 	bpf_gen__free(obj->gen_loader);
8351 	bpf_object__elf_finish(obj);
8352 	bpf_object_unload(obj);
8353 	btf__free(obj->btf);
8354 	btf_ext__free(obj->btf_ext);
8355 
8356 	for (i = 0; i < obj->nr_maps; i++)
8357 		bpf_map__destroy(&obj->maps[i]);
8358 
8359 	zfree(&obj->btf_custom_path);
8360 	zfree(&obj->kconfig);
8361 	zfree(&obj->externs);
8362 	obj->nr_extern = 0;
8363 
8364 	zfree(&obj->maps);
8365 	obj->nr_maps = 0;
8366 
8367 	if (obj->programs && obj->nr_programs) {
8368 		for (i = 0; i < obj->nr_programs; i++)
8369 			bpf_program__exit(&obj->programs[i]);
8370 	}
8371 	zfree(&obj->programs);
8372 
8373 	free(obj);
8374 }
8375 
8376 const char *bpf_object__name(const struct bpf_object *obj)
8377 {
8378 	return obj ? obj->name : libbpf_err_ptr(-EINVAL);
8379 }
8380 
8381 unsigned int bpf_object__kversion(const struct bpf_object *obj)
8382 {
8383 	return obj ? obj->kern_version : 0;
8384 }
8385 
8386 struct btf *bpf_object__btf(const struct bpf_object *obj)
8387 {
8388 	return obj ? obj->btf : NULL;
8389 }
8390 
8391 int bpf_object__btf_fd(const struct bpf_object *obj)
8392 {
8393 	return obj->btf ? btf__fd(obj->btf) : -1;
8394 }
8395 
8396 int bpf_object__set_kversion(struct bpf_object *obj, __u32 kern_version)
8397 {
8398 	if (obj->loaded)
8399 		return libbpf_err(-EINVAL);
8400 
8401 	obj->kern_version = kern_version;
8402 
8403 	return 0;
8404 }
8405 
8406 int bpf_object__gen_loader(struct bpf_object *obj, struct gen_loader_opts *opts)
8407 {
8408 	struct bpf_gen *gen;
8409 
8410 	if (!opts)
8411 		return -EFAULT;
8412 	if (!OPTS_VALID(opts, gen_loader_opts))
8413 		return -EINVAL;
8414 	gen = calloc(sizeof(*gen), 1);
8415 	if (!gen)
8416 		return -ENOMEM;
8417 	gen->opts = opts;
8418 	obj->gen_loader = gen;
8419 	return 0;
8420 }
8421 
8422 static struct bpf_program *
8423 __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
8424 		    bool forward)
8425 {
8426 	size_t nr_programs = obj->nr_programs;
8427 	ssize_t idx;
8428 
8429 	if (!nr_programs)
8430 		return NULL;
8431 
8432 	if (!p)
8433 		/* Iter from the beginning */
8434 		return forward ? &obj->programs[0] :
8435 			&obj->programs[nr_programs - 1];
8436 
8437 	if (p->obj != obj) {
8438 		pr_warn("error: program handler doesn't match object\n");
8439 		return errno = EINVAL, NULL;
8440 	}
8441 
8442 	idx = (p - obj->programs) + (forward ? 1 : -1);
8443 	if (idx >= obj->nr_programs || idx < 0)
8444 		return NULL;
8445 	return &obj->programs[idx];
8446 }
8447 
8448 struct bpf_program *
8449 bpf_object__next_program(const struct bpf_object *obj, struct bpf_program *prev)
8450 {
8451 	struct bpf_program *prog = prev;
8452 
8453 	do {
8454 		prog = __bpf_program__iter(prog, obj, true);
8455 	} while (prog && prog_is_subprog(obj, prog));
8456 
8457 	return prog;
8458 }
8459 
8460 struct bpf_program *
8461 bpf_object__prev_program(const struct bpf_object *obj, struct bpf_program *next)
8462 {
8463 	struct bpf_program *prog = next;
8464 
8465 	do {
8466 		prog = __bpf_program__iter(prog, obj, false);
8467 	} while (prog && prog_is_subprog(obj, prog));
8468 
8469 	return prog;
8470 }
8471 
8472 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
8473 {
8474 	prog->prog_ifindex = ifindex;
8475 }
8476 
8477 const char *bpf_program__name(const struct bpf_program *prog)
8478 {
8479 	return prog->name;
8480 }
8481 
8482 const char *bpf_program__section_name(const struct bpf_program *prog)
8483 {
8484 	return prog->sec_name;
8485 }
8486 
8487 bool bpf_program__autoload(const struct bpf_program *prog)
8488 {
8489 	return prog->autoload;
8490 }
8491 
8492 int bpf_program__set_autoload(struct bpf_program *prog, bool autoload)
8493 {
8494 	if (prog->obj->loaded)
8495 		return libbpf_err(-EINVAL);
8496 
8497 	prog->autoload = autoload;
8498 	return 0;
8499 }
8500 
8501 bool bpf_program__autoattach(const struct bpf_program *prog)
8502 {
8503 	return prog->autoattach;
8504 }
8505 
8506 void bpf_program__set_autoattach(struct bpf_program *prog, bool autoattach)
8507 {
8508 	prog->autoattach = autoattach;
8509 }
8510 
8511 const struct bpf_insn *bpf_program__insns(const struct bpf_program *prog)
8512 {
8513 	return prog->insns;
8514 }
8515 
8516 size_t bpf_program__insn_cnt(const struct bpf_program *prog)
8517 {
8518 	return prog->insns_cnt;
8519 }
8520 
8521 int bpf_program__set_insns(struct bpf_program *prog,
8522 			   struct bpf_insn *new_insns, size_t new_insn_cnt)
8523 {
8524 	struct bpf_insn *insns;
8525 
8526 	if (prog->obj->loaded)
8527 		return -EBUSY;
8528 
8529 	insns = libbpf_reallocarray(prog->insns, new_insn_cnt, sizeof(*insns));
8530 	if (!insns) {
8531 		pr_warn("prog '%s': failed to realloc prog code\n", prog->name);
8532 		return -ENOMEM;
8533 	}
8534 	memcpy(insns, new_insns, new_insn_cnt * sizeof(*insns));
8535 
8536 	prog->insns = insns;
8537 	prog->insns_cnt = new_insn_cnt;
8538 	return 0;
8539 }
8540 
8541 int bpf_program__fd(const struct bpf_program *prog)
8542 {
8543 	if (!prog)
8544 		return libbpf_err(-EINVAL);
8545 
8546 	if (prog->fd < 0)
8547 		return libbpf_err(-ENOENT);
8548 
8549 	return prog->fd;
8550 }
8551 
8552 __alias(bpf_program__type)
8553 enum bpf_prog_type bpf_program__get_type(const struct bpf_program *prog);
8554 
8555 enum bpf_prog_type bpf_program__type(const struct bpf_program *prog)
8556 {
8557 	return prog->type;
8558 }
8559 
8560 int bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
8561 {
8562 	if (prog->obj->loaded)
8563 		return libbpf_err(-EBUSY);
8564 
8565 	prog->type = type;
8566 	prog->sec_def = NULL;
8567 	return 0;
8568 }
8569 
8570 __alias(bpf_program__expected_attach_type)
8571 enum bpf_attach_type bpf_program__get_expected_attach_type(const struct bpf_program *prog);
8572 
8573 enum bpf_attach_type bpf_program__expected_attach_type(const struct bpf_program *prog)
8574 {
8575 	return prog->expected_attach_type;
8576 }
8577 
8578 int bpf_program__set_expected_attach_type(struct bpf_program *prog,
8579 					   enum bpf_attach_type type)
8580 {
8581 	if (prog->obj->loaded)
8582 		return libbpf_err(-EBUSY);
8583 
8584 	prog->expected_attach_type = type;
8585 	return 0;
8586 }
8587 
8588 __u32 bpf_program__flags(const struct bpf_program *prog)
8589 {
8590 	return prog->prog_flags;
8591 }
8592 
8593 int bpf_program__set_flags(struct bpf_program *prog, __u32 flags)
8594 {
8595 	if (prog->obj->loaded)
8596 		return libbpf_err(-EBUSY);
8597 
8598 	prog->prog_flags = flags;
8599 	return 0;
8600 }
8601 
8602 __u32 bpf_program__log_level(const struct bpf_program *prog)
8603 {
8604 	return prog->log_level;
8605 }
8606 
8607 int bpf_program__set_log_level(struct bpf_program *prog, __u32 log_level)
8608 {
8609 	if (prog->obj->loaded)
8610 		return libbpf_err(-EBUSY);
8611 
8612 	prog->log_level = log_level;
8613 	return 0;
8614 }
8615 
8616 const char *bpf_program__log_buf(const struct bpf_program *prog, size_t *log_size)
8617 {
8618 	*log_size = prog->log_size;
8619 	return prog->log_buf;
8620 }
8621 
8622 int bpf_program__set_log_buf(struct bpf_program *prog, char *log_buf, size_t log_size)
8623 {
8624 	if (log_size && !log_buf)
8625 		return -EINVAL;
8626 	if (prog->log_size > UINT_MAX)
8627 		return -EINVAL;
8628 	if (prog->obj->loaded)
8629 		return -EBUSY;
8630 
8631 	prog->log_buf = log_buf;
8632 	prog->log_size = log_size;
8633 	return 0;
8634 }
8635 
8636 #define SEC_DEF(sec_pfx, ptype, atype, flags, ...) {			    \
8637 	.sec = (char *)sec_pfx,						    \
8638 	.prog_type = BPF_PROG_TYPE_##ptype,				    \
8639 	.expected_attach_type = atype,					    \
8640 	.cookie = (long)(flags),					    \
8641 	.prog_prepare_load_fn = libbpf_prepare_prog_load,		    \
8642 	__VA_ARGS__							    \
8643 }
8644 
8645 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8646 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8647 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8648 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8649 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8650 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8651 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8652 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8653 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8654 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8655 
8656 static const struct bpf_sec_def section_defs[] = {
8657 	SEC_DEF("socket",		SOCKET_FILTER, 0, SEC_NONE),
8658 	SEC_DEF("sk_reuseport/migrate",	SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT_OR_MIGRATE, SEC_ATTACHABLE),
8659 	SEC_DEF("sk_reuseport",		SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT, SEC_ATTACHABLE),
8660 	SEC_DEF("kprobe+",		KPROBE,	0, SEC_NONE, attach_kprobe),
8661 	SEC_DEF("uprobe+",		KPROBE,	0, SEC_NONE, attach_uprobe),
8662 	SEC_DEF("uprobe.s+",		KPROBE,	0, SEC_SLEEPABLE, attach_uprobe),
8663 	SEC_DEF("kretprobe+",		KPROBE, 0, SEC_NONE, attach_kprobe),
8664 	SEC_DEF("uretprobe+",		KPROBE, 0, SEC_NONE, attach_uprobe),
8665 	SEC_DEF("uretprobe.s+",		KPROBE, 0, SEC_SLEEPABLE, attach_uprobe),
8666 	SEC_DEF("kprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
8667 	SEC_DEF("kretprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
8668 	SEC_DEF("ksyscall+",		KPROBE,	0, SEC_NONE, attach_ksyscall),
8669 	SEC_DEF("kretsyscall+",		KPROBE, 0, SEC_NONE, attach_ksyscall),
8670 	SEC_DEF("usdt+",		KPROBE,	0, SEC_NONE, attach_usdt),
8671 	SEC_DEF("tc",			SCHED_CLS, 0, SEC_NONE),
8672 	SEC_DEF("classifier",		SCHED_CLS, 0, SEC_NONE),
8673 	SEC_DEF("action",		SCHED_ACT, 0, SEC_NONE),
8674 	SEC_DEF("tracepoint+",		TRACEPOINT, 0, SEC_NONE, attach_tp),
8675 	SEC_DEF("tp+",			TRACEPOINT, 0, SEC_NONE, attach_tp),
8676 	SEC_DEF("raw_tracepoint+",	RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
8677 	SEC_DEF("raw_tp+",		RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
8678 	SEC_DEF("raw_tracepoint.w+",	RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
8679 	SEC_DEF("raw_tp.w+",		RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
8680 	SEC_DEF("tp_btf+",		TRACING, BPF_TRACE_RAW_TP, SEC_ATTACH_BTF, attach_trace),
8681 	SEC_DEF("fentry+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF, attach_trace),
8682 	SEC_DEF("fmod_ret+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF, attach_trace),
8683 	SEC_DEF("fexit+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF, attach_trace),
8684 	SEC_DEF("fentry.s+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8685 	SEC_DEF("fmod_ret.s+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8686 	SEC_DEF("fexit.s+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8687 	SEC_DEF("freplace+",		EXT, 0, SEC_ATTACH_BTF, attach_trace),
8688 	SEC_DEF("lsm+",			LSM, BPF_LSM_MAC, SEC_ATTACH_BTF, attach_lsm),
8689 	SEC_DEF("lsm.s+",		LSM, BPF_LSM_MAC, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_lsm),
8690 	SEC_DEF("lsm_cgroup+",		LSM, BPF_LSM_CGROUP, SEC_ATTACH_BTF),
8691 	SEC_DEF("iter+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF, attach_iter),
8692 	SEC_DEF("iter.s+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_iter),
8693 	SEC_DEF("syscall",		SYSCALL, 0, SEC_SLEEPABLE),
8694 	SEC_DEF("xdp.frags/devmap",	XDP, BPF_XDP_DEVMAP, SEC_XDP_FRAGS),
8695 	SEC_DEF("xdp/devmap",		XDP, BPF_XDP_DEVMAP, SEC_ATTACHABLE),
8696 	SEC_DEF("xdp.frags/cpumap",	XDP, BPF_XDP_CPUMAP, SEC_XDP_FRAGS),
8697 	SEC_DEF("xdp/cpumap",		XDP, BPF_XDP_CPUMAP, SEC_ATTACHABLE),
8698 	SEC_DEF("xdp.frags",		XDP, BPF_XDP, SEC_XDP_FRAGS),
8699 	SEC_DEF("xdp",			XDP, BPF_XDP, SEC_ATTACHABLE_OPT),
8700 	SEC_DEF("perf_event",		PERF_EVENT, 0, SEC_NONE),
8701 	SEC_DEF("lwt_in",		LWT_IN, 0, SEC_NONE),
8702 	SEC_DEF("lwt_out",		LWT_OUT, 0, SEC_NONE),
8703 	SEC_DEF("lwt_xmit",		LWT_XMIT, 0, SEC_NONE),
8704 	SEC_DEF("lwt_seg6local",	LWT_SEG6LOCAL, 0, SEC_NONE),
8705 	SEC_DEF("sockops",		SOCK_OPS, BPF_CGROUP_SOCK_OPS, SEC_ATTACHABLE_OPT),
8706 	SEC_DEF("sk_skb/stream_parser",	SK_SKB, BPF_SK_SKB_STREAM_PARSER, SEC_ATTACHABLE_OPT),
8707 	SEC_DEF("sk_skb/stream_verdict",SK_SKB, BPF_SK_SKB_STREAM_VERDICT, SEC_ATTACHABLE_OPT),
8708 	SEC_DEF("sk_skb",		SK_SKB, 0, SEC_NONE),
8709 	SEC_DEF("sk_msg",		SK_MSG, BPF_SK_MSG_VERDICT, SEC_ATTACHABLE_OPT),
8710 	SEC_DEF("lirc_mode2",		LIRC_MODE2, BPF_LIRC_MODE2, SEC_ATTACHABLE_OPT),
8711 	SEC_DEF("flow_dissector",	FLOW_DISSECTOR, BPF_FLOW_DISSECTOR, SEC_ATTACHABLE_OPT),
8712 	SEC_DEF("cgroup_skb/ingress",	CGROUP_SKB, BPF_CGROUP_INET_INGRESS, SEC_ATTACHABLE_OPT),
8713 	SEC_DEF("cgroup_skb/egress",	CGROUP_SKB, BPF_CGROUP_INET_EGRESS, SEC_ATTACHABLE_OPT),
8714 	SEC_DEF("cgroup/skb",		CGROUP_SKB, 0, SEC_NONE),
8715 	SEC_DEF("cgroup/sock_create",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE),
8716 	SEC_DEF("cgroup/sock_release",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_RELEASE, SEC_ATTACHABLE),
8717 	SEC_DEF("cgroup/sock",		CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE_OPT),
8718 	SEC_DEF("cgroup/post_bind4",	CGROUP_SOCK, BPF_CGROUP_INET4_POST_BIND, SEC_ATTACHABLE),
8719 	SEC_DEF("cgroup/post_bind6",	CGROUP_SOCK, BPF_CGROUP_INET6_POST_BIND, SEC_ATTACHABLE),
8720 	SEC_DEF("cgroup/bind4",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND, SEC_ATTACHABLE),
8721 	SEC_DEF("cgroup/bind6",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND, SEC_ATTACHABLE),
8722 	SEC_DEF("cgroup/connect4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT, SEC_ATTACHABLE),
8723 	SEC_DEF("cgroup/connect6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT, SEC_ATTACHABLE),
8724 	SEC_DEF("cgroup/sendmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG, SEC_ATTACHABLE),
8725 	SEC_DEF("cgroup/sendmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG, SEC_ATTACHABLE),
8726 	SEC_DEF("cgroup/recvmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_RECVMSG, SEC_ATTACHABLE),
8727 	SEC_DEF("cgroup/recvmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_RECVMSG, SEC_ATTACHABLE),
8728 	SEC_DEF("cgroup/getpeername4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETPEERNAME, SEC_ATTACHABLE),
8729 	SEC_DEF("cgroup/getpeername6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETPEERNAME, SEC_ATTACHABLE),
8730 	SEC_DEF("cgroup/getsockname4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETSOCKNAME, SEC_ATTACHABLE),
8731 	SEC_DEF("cgroup/getsockname6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETSOCKNAME, SEC_ATTACHABLE),
8732 	SEC_DEF("cgroup/sysctl",	CGROUP_SYSCTL, BPF_CGROUP_SYSCTL, SEC_ATTACHABLE),
8733 	SEC_DEF("cgroup/getsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_GETSOCKOPT, SEC_ATTACHABLE),
8734 	SEC_DEF("cgroup/setsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_SETSOCKOPT, SEC_ATTACHABLE),
8735 	SEC_DEF("cgroup/dev",		CGROUP_DEVICE, BPF_CGROUP_DEVICE, SEC_ATTACHABLE_OPT),
8736 	SEC_DEF("struct_ops+",		STRUCT_OPS, 0, SEC_NONE),
8737 	SEC_DEF("struct_ops.s+",	STRUCT_OPS, 0, SEC_SLEEPABLE),
8738 	SEC_DEF("sk_lookup",		SK_LOOKUP, BPF_SK_LOOKUP, SEC_ATTACHABLE),
8739 	SEC_DEF("netfilter",		NETFILTER, 0, SEC_NONE),
8740 };
8741 
8742 static size_t custom_sec_def_cnt;
8743 static struct bpf_sec_def *custom_sec_defs;
8744 static struct bpf_sec_def custom_fallback_def;
8745 static bool has_custom_fallback_def;
8746 
8747 static int last_custom_sec_def_handler_id;
8748 
8749 int libbpf_register_prog_handler(const char *sec,
8750 				 enum bpf_prog_type prog_type,
8751 				 enum bpf_attach_type exp_attach_type,
8752 				 const struct libbpf_prog_handler_opts *opts)
8753 {
8754 	struct bpf_sec_def *sec_def;
8755 
8756 	if (!OPTS_VALID(opts, libbpf_prog_handler_opts))
8757 		return libbpf_err(-EINVAL);
8758 
8759 	if (last_custom_sec_def_handler_id == INT_MAX) /* prevent overflow */
8760 		return libbpf_err(-E2BIG);
8761 
8762 	if (sec) {
8763 		sec_def = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt + 1,
8764 					      sizeof(*sec_def));
8765 		if (!sec_def)
8766 			return libbpf_err(-ENOMEM);
8767 
8768 		custom_sec_defs = sec_def;
8769 		sec_def = &custom_sec_defs[custom_sec_def_cnt];
8770 	} else {
8771 		if (has_custom_fallback_def)
8772 			return libbpf_err(-EBUSY);
8773 
8774 		sec_def = &custom_fallback_def;
8775 	}
8776 
8777 	sec_def->sec = sec ? strdup(sec) : NULL;
8778 	if (sec && !sec_def->sec)
8779 		return libbpf_err(-ENOMEM);
8780 
8781 	sec_def->prog_type = prog_type;
8782 	sec_def->expected_attach_type = exp_attach_type;
8783 	sec_def->cookie = OPTS_GET(opts, cookie, 0);
8784 
8785 	sec_def->prog_setup_fn = OPTS_GET(opts, prog_setup_fn, NULL);
8786 	sec_def->prog_prepare_load_fn = OPTS_GET(opts, prog_prepare_load_fn, NULL);
8787 	sec_def->prog_attach_fn = OPTS_GET(opts, prog_attach_fn, NULL);
8788 
8789 	sec_def->handler_id = ++last_custom_sec_def_handler_id;
8790 
8791 	if (sec)
8792 		custom_sec_def_cnt++;
8793 	else
8794 		has_custom_fallback_def = true;
8795 
8796 	return sec_def->handler_id;
8797 }
8798 
8799 int libbpf_unregister_prog_handler(int handler_id)
8800 {
8801 	struct bpf_sec_def *sec_defs;
8802 	int i;
8803 
8804 	if (handler_id <= 0)
8805 		return libbpf_err(-EINVAL);
8806 
8807 	if (has_custom_fallback_def && custom_fallback_def.handler_id == handler_id) {
8808 		memset(&custom_fallback_def, 0, sizeof(custom_fallback_def));
8809 		has_custom_fallback_def = false;
8810 		return 0;
8811 	}
8812 
8813 	for (i = 0; i < custom_sec_def_cnt; i++) {
8814 		if (custom_sec_defs[i].handler_id == handler_id)
8815 			break;
8816 	}
8817 
8818 	if (i == custom_sec_def_cnt)
8819 		return libbpf_err(-ENOENT);
8820 
8821 	free(custom_sec_defs[i].sec);
8822 	for (i = i + 1; i < custom_sec_def_cnt; i++)
8823 		custom_sec_defs[i - 1] = custom_sec_defs[i];
8824 	custom_sec_def_cnt--;
8825 
8826 	/* try to shrink the array, but it's ok if we couldn't */
8827 	sec_defs = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt, sizeof(*sec_defs));
8828 	if (sec_defs)
8829 		custom_sec_defs = sec_defs;
8830 
8831 	return 0;
8832 }
8833 
8834 static bool sec_def_matches(const struct bpf_sec_def *sec_def, const char *sec_name)
8835 {
8836 	size_t len = strlen(sec_def->sec);
8837 
8838 	/* "type/" always has to have proper SEC("type/extras") form */
8839 	if (sec_def->sec[len - 1] == '/') {
8840 		if (str_has_pfx(sec_name, sec_def->sec))
8841 			return true;
8842 		return false;
8843 	}
8844 
8845 	/* "type+" means it can be either exact SEC("type") or
8846 	 * well-formed SEC("type/extras") with proper '/' separator
8847 	 */
8848 	if (sec_def->sec[len - 1] == '+') {
8849 		len--;
8850 		/* not even a prefix */
8851 		if (strncmp(sec_name, sec_def->sec, len) != 0)
8852 			return false;
8853 		/* exact match or has '/' separator */
8854 		if (sec_name[len] == '\0' || sec_name[len] == '/')
8855 			return true;
8856 		return false;
8857 	}
8858 
8859 	return strcmp(sec_name, sec_def->sec) == 0;
8860 }
8861 
8862 static const struct bpf_sec_def *find_sec_def(const char *sec_name)
8863 {
8864 	const struct bpf_sec_def *sec_def;
8865 	int i, n;
8866 
8867 	n = custom_sec_def_cnt;
8868 	for (i = 0; i < n; i++) {
8869 		sec_def = &custom_sec_defs[i];
8870 		if (sec_def_matches(sec_def, sec_name))
8871 			return sec_def;
8872 	}
8873 
8874 	n = ARRAY_SIZE(section_defs);
8875 	for (i = 0; i < n; i++) {
8876 		sec_def = &section_defs[i];
8877 		if (sec_def_matches(sec_def, sec_name))
8878 			return sec_def;
8879 	}
8880 
8881 	if (has_custom_fallback_def)
8882 		return &custom_fallback_def;
8883 
8884 	return NULL;
8885 }
8886 
8887 #define MAX_TYPE_NAME_SIZE 32
8888 
8889 static char *libbpf_get_type_names(bool attach_type)
8890 {
8891 	int i, len = ARRAY_SIZE(section_defs) * MAX_TYPE_NAME_SIZE;
8892 	char *buf;
8893 
8894 	buf = malloc(len);
8895 	if (!buf)
8896 		return NULL;
8897 
8898 	buf[0] = '\0';
8899 	/* Forge string buf with all available names */
8900 	for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
8901 		const struct bpf_sec_def *sec_def = &section_defs[i];
8902 
8903 		if (attach_type) {
8904 			if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
8905 				continue;
8906 
8907 			if (!(sec_def->cookie & SEC_ATTACHABLE))
8908 				continue;
8909 		}
8910 
8911 		if (strlen(buf) + strlen(section_defs[i].sec) + 2 > len) {
8912 			free(buf);
8913 			return NULL;
8914 		}
8915 		strcat(buf, " ");
8916 		strcat(buf, section_defs[i].sec);
8917 	}
8918 
8919 	return buf;
8920 }
8921 
8922 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
8923 			     enum bpf_attach_type *expected_attach_type)
8924 {
8925 	const struct bpf_sec_def *sec_def;
8926 	char *type_names;
8927 
8928 	if (!name)
8929 		return libbpf_err(-EINVAL);
8930 
8931 	sec_def = find_sec_def(name);
8932 	if (sec_def) {
8933 		*prog_type = sec_def->prog_type;
8934 		*expected_attach_type = sec_def->expected_attach_type;
8935 		return 0;
8936 	}
8937 
8938 	pr_debug("failed to guess program type from ELF section '%s'\n", name);
8939 	type_names = libbpf_get_type_names(false);
8940 	if (type_names != NULL) {
8941 		pr_debug("supported section(type) names are:%s\n", type_names);
8942 		free(type_names);
8943 	}
8944 
8945 	return libbpf_err(-ESRCH);
8946 }
8947 
8948 const char *libbpf_bpf_attach_type_str(enum bpf_attach_type t)
8949 {
8950 	if (t < 0 || t >= ARRAY_SIZE(attach_type_name))
8951 		return NULL;
8952 
8953 	return attach_type_name[t];
8954 }
8955 
8956 const char *libbpf_bpf_link_type_str(enum bpf_link_type t)
8957 {
8958 	if (t < 0 || t >= ARRAY_SIZE(link_type_name))
8959 		return NULL;
8960 
8961 	return link_type_name[t];
8962 }
8963 
8964 const char *libbpf_bpf_map_type_str(enum bpf_map_type t)
8965 {
8966 	if (t < 0 || t >= ARRAY_SIZE(map_type_name))
8967 		return NULL;
8968 
8969 	return map_type_name[t];
8970 }
8971 
8972 const char *libbpf_bpf_prog_type_str(enum bpf_prog_type t)
8973 {
8974 	if (t < 0 || t >= ARRAY_SIZE(prog_type_name))
8975 		return NULL;
8976 
8977 	return prog_type_name[t];
8978 }
8979 
8980 static struct bpf_map *find_struct_ops_map_by_offset(struct bpf_object *obj,
8981 						     int sec_idx,
8982 						     size_t offset)
8983 {
8984 	struct bpf_map *map;
8985 	size_t i;
8986 
8987 	for (i = 0; i < obj->nr_maps; i++) {
8988 		map = &obj->maps[i];
8989 		if (!bpf_map__is_struct_ops(map))
8990 			continue;
8991 		if (map->sec_idx == sec_idx &&
8992 		    map->sec_offset <= offset &&
8993 		    offset - map->sec_offset < map->def.value_size)
8994 			return map;
8995 	}
8996 
8997 	return NULL;
8998 }
8999 
9000 /* Collect the reloc from ELF and populate the st_ops->progs[] */
9001 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
9002 					    Elf64_Shdr *shdr, Elf_Data *data)
9003 {
9004 	const struct btf_member *member;
9005 	struct bpf_struct_ops *st_ops;
9006 	struct bpf_program *prog;
9007 	unsigned int shdr_idx;
9008 	const struct btf *btf;
9009 	struct bpf_map *map;
9010 	unsigned int moff, insn_idx;
9011 	const char *name;
9012 	__u32 member_idx;
9013 	Elf64_Sym *sym;
9014 	Elf64_Rel *rel;
9015 	int i, nrels;
9016 
9017 	btf = obj->btf;
9018 	nrels = shdr->sh_size / shdr->sh_entsize;
9019 	for (i = 0; i < nrels; i++) {
9020 		rel = elf_rel_by_idx(data, i);
9021 		if (!rel) {
9022 			pr_warn("struct_ops reloc: failed to get %d reloc\n", i);
9023 			return -LIBBPF_ERRNO__FORMAT;
9024 		}
9025 
9026 		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
9027 		if (!sym) {
9028 			pr_warn("struct_ops reloc: symbol %zx not found\n",
9029 				(size_t)ELF64_R_SYM(rel->r_info));
9030 			return -LIBBPF_ERRNO__FORMAT;
9031 		}
9032 
9033 		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
9034 		map = find_struct_ops_map_by_offset(obj, shdr->sh_info, rel->r_offset);
9035 		if (!map) {
9036 			pr_warn("struct_ops reloc: cannot find map at rel->r_offset %zu\n",
9037 				(size_t)rel->r_offset);
9038 			return -EINVAL;
9039 		}
9040 
9041 		moff = rel->r_offset - map->sec_offset;
9042 		shdr_idx = sym->st_shndx;
9043 		st_ops = map->st_ops;
9044 		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",
9045 			 map->name,
9046 			 (long long)(rel->r_info >> 32),
9047 			 (long long)sym->st_value,
9048 			 shdr_idx, (size_t)rel->r_offset,
9049 			 map->sec_offset, sym->st_name, name);
9050 
9051 		if (shdr_idx >= SHN_LORESERVE) {
9052 			pr_warn("struct_ops reloc %s: rel->r_offset %zu shdr_idx %u unsupported non-static function\n",
9053 				map->name, (size_t)rel->r_offset, shdr_idx);
9054 			return -LIBBPF_ERRNO__RELOC;
9055 		}
9056 		if (sym->st_value % BPF_INSN_SZ) {
9057 			pr_warn("struct_ops reloc %s: invalid target program offset %llu\n",
9058 				map->name, (unsigned long long)sym->st_value);
9059 			return -LIBBPF_ERRNO__FORMAT;
9060 		}
9061 		insn_idx = sym->st_value / BPF_INSN_SZ;
9062 
9063 		member = find_member_by_offset(st_ops->type, moff * 8);
9064 		if (!member) {
9065 			pr_warn("struct_ops reloc %s: cannot find member at moff %u\n",
9066 				map->name, moff);
9067 			return -EINVAL;
9068 		}
9069 		member_idx = member - btf_members(st_ops->type);
9070 		name = btf__name_by_offset(btf, member->name_off);
9071 
9072 		if (!resolve_func_ptr(btf, member->type, NULL)) {
9073 			pr_warn("struct_ops reloc %s: cannot relocate non func ptr %s\n",
9074 				map->name, name);
9075 			return -EINVAL;
9076 		}
9077 
9078 		prog = find_prog_by_sec_insn(obj, shdr_idx, insn_idx);
9079 		if (!prog) {
9080 			pr_warn("struct_ops reloc %s: cannot find prog at shdr_idx %u to relocate func ptr %s\n",
9081 				map->name, shdr_idx, name);
9082 			return -EINVAL;
9083 		}
9084 
9085 		/* prevent the use of BPF prog with invalid type */
9086 		if (prog->type != BPF_PROG_TYPE_STRUCT_OPS) {
9087 			pr_warn("struct_ops reloc %s: prog %s is not struct_ops BPF program\n",
9088 				map->name, prog->name);
9089 			return -EINVAL;
9090 		}
9091 
9092 		/* if we haven't yet processed this BPF program, record proper
9093 		 * attach_btf_id and member_idx
9094 		 */
9095 		if (!prog->attach_btf_id) {
9096 			prog->attach_btf_id = st_ops->type_id;
9097 			prog->expected_attach_type = member_idx;
9098 		}
9099 
9100 		/* struct_ops BPF prog can be re-used between multiple
9101 		 * .struct_ops & .struct_ops.link as long as it's the
9102 		 * same struct_ops struct definition and the same
9103 		 * function pointer field
9104 		 */
9105 		if (prog->attach_btf_id != st_ops->type_id ||
9106 		    prog->expected_attach_type != member_idx) {
9107 			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",
9108 				map->name, prog->name, prog->sec_name, prog->type,
9109 				prog->attach_btf_id, prog->expected_attach_type, name);
9110 			return -EINVAL;
9111 		}
9112 
9113 		st_ops->progs[member_idx] = prog;
9114 	}
9115 
9116 	return 0;
9117 }
9118 
9119 #define BTF_TRACE_PREFIX "btf_trace_"
9120 #define BTF_LSM_PREFIX "bpf_lsm_"
9121 #define BTF_ITER_PREFIX "bpf_iter_"
9122 #define BTF_MAX_NAME_SIZE 128
9123 
9124 void btf_get_kernel_prefix_kind(enum bpf_attach_type attach_type,
9125 				const char **prefix, int *kind)
9126 {
9127 	switch (attach_type) {
9128 	case BPF_TRACE_RAW_TP:
9129 		*prefix = BTF_TRACE_PREFIX;
9130 		*kind = BTF_KIND_TYPEDEF;
9131 		break;
9132 	case BPF_LSM_MAC:
9133 	case BPF_LSM_CGROUP:
9134 		*prefix = BTF_LSM_PREFIX;
9135 		*kind = BTF_KIND_FUNC;
9136 		break;
9137 	case BPF_TRACE_ITER:
9138 		*prefix = BTF_ITER_PREFIX;
9139 		*kind = BTF_KIND_FUNC;
9140 		break;
9141 	default:
9142 		*prefix = "";
9143 		*kind = BTF_KIND_FUNC;
9144 	}
9145 }
9146 
9147 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
9148 				   const char *name, __u32 kind)
9149 {
9150 	char btf_type_name[BTF_MAX_NAME_SIZE];
9151 	int ret;
9152 
9153 	ret = snprintf(btf_type_name, sizeof(btf_type_name),
9154 		       "%s%s", prefix, name);
9155 	/* snprintf returns the number of characters written excluding the
9156 	 * terminating null. So, if >= BTF_MAX_NAME_SIZE are written, it
9157 	 * indicates truncation.
9158 	 */
9159 	if (ret < 0 || ret >= sizeof(btf_type_name))
9160 		return -ENAMETOOLONG;
9161 	return btf__find_by_name_kind(btf, btf_type_name, kind);
9162 }
9163 
9164 static inline int find_attach_btf_id(struct btf *btf, const char *name,
9165 				     enum bpf_attach_type attach_type)
9166 {
9167 	const char *prefix;
9168 	int kind;
9169 
9170 	btf_get_kernel_prefix_kind(attach_type, &prefix, &kind);
9171 	return find_btf_by_prefix_kind(btf, prefix, name, kind);
9172 }
9173 
9174 int libbpf_find_vmlinux_btf_id(const char *name,
9175 			       enum bpf_attach_type attach_type)
9176 {
9177 	struct btf *btf;
9178 	int err;
9179 
9180 	btf = btf__load_vmlinux_btf();
9181 	err = libbpf_get_error(btf);
9182 	if (err) {
9183 		pr_warn("vmlinux BTF is not found\n");
9184 		return libbpf_err(err);
9185 	}
9186 
9187 	err = find_attach_btf_id(btf, name, attach_type);
9188 	if (err <= 0)
9189 		pr_warn("%s is not found in vmlinux BTF\n", name);
9190 
9191 	btf__free(btf);
9192 	return libbpf_err(err);
9193 }
9194 
9195 static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd)
9196 {
9197 	struct bpf_prog_info info;
9198 	__u32 info_len = sizeof(info);
9199 	struct btf *btf;
9200 	int err;
9201 
9202 	memset(&info, 0, info_len);
9203 	err = bpf_prog_get_info_by_fd(attach_prog_fd, &info, &info_len);
9204 	if (err) {
9205 		pr_warn("failed bpf_prog_get_info_by_fd for FD %d: %d\n",
9206 			attach_prog_fd, err);
9207 		return err;
9208 	}
9209 
9210 	err = -EINVAL;
9211 	if (!info.btf_id) {
9212 		pr_warn("The target program doesn't have BTF\n");
9213 		goto out;
9214 	}
9215 	btf = btf__load_from_kernel_by_id(info.btf_id);
9216 	err = libbpf_get_error(btf);
9217 	if (err) {
9218 		pr_warn("Failed to get BTF %d of the program: %d\n", info.btf_id, err);
9219 		goto out;
9220 	}
9221 	err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
9222 	btf__free(btf);
9223 	if (err <= 0) {
9224 		pr_warn("%s is not found in prog's BTF\n", name);
9225 		goto out;
9226 	}
9227 out:
9228 	return err;
9229 }
9230 
9231 static int find_kernel_btf_id(struct bpf_object *obj, const char *attach_name,
9232 			      enum bpf_attach_type attach_type,
9233 			      int *btf_obj_fd, int *btf_type_id)
9234 {
9235 	int ret, i;
9236 
9237 	ret = find_attach_btf_id(obj->btf_vmlinux, attach_name, attach_type);
9238 	if (ret > 0) {
9239 		*btf_obj_fd = 0; /* vmlinux BTF */
9240 		*btf_type_id = ret;
9241 		return 0;
9242 	}
9243 	if (ret != -ENOENT)
9244 		return ret;
9245 
9246 	ret = load_module_btfs(obj);
9247 	if (ret)
9248 		return ret;
9249 
9250 	for (i = 0; i < obj->btf_module_cnt; i++) {
9251 		const struct module_btf *mod = &obj->btf_modules[i];
9252 
9253 		ret = find_attach_btf_id(mod->btf, attach_name, attach_type);
9254 		if (ret > 0) {
9255 			*btf_obj_fd = mod->fd;
9256 			*btf_type_id = ret;
9257 			return 0;
9258 		}
9259 		if (ret == -ENOENT)
9260 			continue;
9261 
9262 		return ret;
9263 	}
9264 
9265 	return -ESRCH;
9266 }
9267 
9268 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
9269 				     int *btf_obj_fd, int *btf_type_id)
9270 {
9271 	enum bpf_attach_type attach_type = prog->expected_attach_type;
9272 	__u32 attach_prog_fd = prog->attach_prog_fd;
9273 	int err = 0;
9274 
9275 	/* BPF program's BTF ID */
9276 	if (prog->type == BPF_PROG_TYPE_EXT || attach_prog_fd) {
9277 		if (!attach_prog_fd) {
9278 			pr_warn("prog '%s': attach program FD is not set\n", prog->name);
9279 			return -EINVAL;
9280 		}
9281 		err = libbpf_find_prog_btf_id(attach_name, attach_prog_fd);
9282 		if (err < 0) {
9283 			pr_warn("prog '%s': failed to find BPF program (FD %d) BTF ID for '%s': %d\n",
9284 				 prog->name, attach_prog_fd, attach_name, err);
9285 			return err;
9286 		}
9287 		*btf_obj_fd = 0;
9288 		*btf_type_id = err;
9289 		return 0;
9290 	}
9291 
9292 	/* kernel/module BTF ID */
9293 	if (prog->obj->gen_loader) {
9294 		bpf_gen__record_attach_target(prog->obj->gen_loader, attach_name, attach_type);
9295 		*btf_obj_fd = 0;
9296 		*btf_type_id = 1;
9297 	} else {
9298 		err = find_kernel_btf_id(prog->obj, attach_name, attach_type, btf_obj_fd, btf_type_id);
9299 	}
9300 	if (err) {
9301 		pr_warn("prog '%s': failed to find kernel BTF type ID of '%s': %d\n",
9302 			prog->name, attach_name, err);
9303 		return err;
9304 	}
9305 	return 0;
9306 }
9307 
9308 int libbpf_attach_type_by_name(const char *name,
9309 			       enum bpf_attach_type *attach_type)
9310 {
9311 	char *type_names;
9312 	const struct bpf_sec_def *sec_def;
9313 
9314 	if (!name)
9315 		return libbpf_err(-EINVAL);
9316 
9317 	sec_def = find_sec_def(name);
9318 	if (!sec_def) {
9319 		pr_debug("failed to guess attach type based on ELF section name '%s'\n", name);
9320 		type_names = libbpf_get_type_names(true);
9321 		if (type_names != NULL) {
9322 			pr_debug("attachable section(type) names are:%s\n", type_names);
9323 			free(type_names);
9324 		}
9325 
9326 		return libbpf_err(-EINVAL);
9327 	}
9328 
9329 	if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
9330 		return libbpf_err(-EINVAL);
9331 	if (!(sec_def->cookie & SEC_ATTACHABLE))
9332 		return libbpf_err(-EINVAL);
9333 
9334 	*attach_type = sec_def->expected_attach_type;
9335 	return 0;
9336 }
9337 
9338 int bpf_map__fd(const struct bpf_map *map)
9339 {
9340 	return map ? map->fd : libbpf_err(-EINVAL);
9341 }
9342 
9343 static bool map_uses_real_name(const struct bpf_map *map)
9344 {
9345 	/* Since libbpf started to support custom .data.* and .rodata.* maps,
9346 	 * their user-visible name differs from kernel-visible name. Users see
9347 	 * such map's corresponding ELF section name as a map name.
9348 	 * This check distinguishes .data/.rodata from .data.* and .rodata.*
9349 	 * maps to know which name has to be returned to the user.
9350 	 */
9351 	if (map->libbpf_type == LIBBPF_MAP_DATA && strcmp(map->real_name, DATA_SEC) != 0)
9352 		return true;
9353 	if (map->libbpf_type == LIBBPF_MAP_RODATA && strcmp(map->real_name, RODATA_SEC) != 0)
9354 		return true;
9355 	return false;
9356 }
9357 
9358 const char *bpf_map__name(const struct bpf_map *map)
9359 {
9360 	if (!map)
9361 		return NULL;
9362 
9363 	if (map_uses_real_name(map))
9364 		return map->real_name;
9365 
9366 	return map->name;
9367 }
9368 
9369 enum bpf_map_type bpf_map__type(const struct bpf_map *map)
9370 {
9371 	return map->def.type;
9372 }
9373 
9374 int bpf_map__set_type(struct bpf_map *map, enum bpf_map_type type)
9375 {
9376 	if (map->fd >= 0)
9377 		return libbpf_err(-EBUSY);
9378 	map->def.type = type;
9379 	return 0;
9380 }
9381 
9382 __u32 bpf_map__map_flags(const struct bpf_map *map)
9383 {
9384 	return map->def.map_flags;
9385 }
9386 
9387 int bpf_map__set_map_flags(struct bpf_map *map, __u32 flags)
9388 {
9389 	if (map->fd >= 0)
9390 		return libbpf_err(-EBUSY);
9391 	map->def.map_flags = flags;
9392 	return 0;
9393 }
9394 
9395 __u64 bpf_map__map_extra(const struct bpf_map *map)
9396 {
9397 	return map->map_extra;
9398 }
9399 
9400 int bpf_map__set_map_extra(struct bpf_map *map, __u64 map_extra)
9401 {
9402 	if (map->fd >= 0)
9403 		return libbpf_err(-EBUSY);
9404 	map->map_extra = map_extra;
9405 	return 0;
9406 }
9407 
9408 __u32 bpf_map__numa_node(const struct bpf_map *map)
9409 {
9410 	return map->numa_node;
9411 }
9412 
9413 int bpf_map__set_numa_node(struct bpf_map *map, __u32 numa_node)
9414 {
9415 	if (map->fd >= 0)
9416 		return libbpf_err(-EBUSY);
9417 	map->numa_node = numa_node;
9418 	return 0;
9419 }
9420 
9421 __u32 bpf_map__key_size(const struct bpf_map *map)
9422 {
9423 	return map->def.key_size;
9424 }
9425 
9426 int bpf_map__set_key_size(struct bpf_map *map, __u32 size)
9427 {
9428 	if (map->fd >= 0)
9429 		return libbpf_err(-EBUSY);
9430 	map->def.key_size = size;
9431 	return 0;
9432 }
9433 
9434 __u32 bpf_map__value_size(const struct bpf_map *map)
9435 {
9436 	return map->def.value_size;
9437 }
9438 
9439 static int map_btf_datasec_resize(struct bpf_map *map, __u32 size)
9440 {
9441 	struct btf *btf;
9442 	struct btf_type *datasec_type, *var_type;
9443 	struct btf_var_secinfo *var;
9444 	const struct btf_type *array_type;
9445 	const struct btf_array *array;
9446 	int vlen, element_sz, new_array_id;
9447 	__u32 nr_elements;
9448 
9449 	/* check btf existence */
9450 	btf = bpf_object__btf(map->obj);
9451 	if (!btf)
9452 		return -ENOENT;
9453 
9454 	/* verify map is datasec */
9455 	datasec_type = btf_type_by_id(btf, bpf_map__btf_value_type_id(map));
9456 	if (!btf_is_datasec(datasec_type)) {
9457 		pr_warn("map '%s': cannot be resized, map value type is not a datasec\n",
9458 			bpf_map__name(map));
9459 		return -EINVAL;
9460 	}
9461 
9462 	/* verify datasec has at least one var */
9463 	vlen = btf_vlen(datasec_type);
9464 	if (vlen == 0) {
9465 		pr_warn("map '%s': cannot be resized, map value datasec is empty\n",
9466 			bpf_map__name(map));
9467 		return -EINVAL;
9468 	}
9469 
9470 	/* verify last var in the datasec is an array */
9471 	var = &btf_var_secinfos(datasec_type)[vlen - 1];
9472 	var_type = btf_type_by_id(btf, var->type);
9473 	array_type = skip_mods_and_typedefs(btf, var_type->type, NULL);
9474 	if (!btf_is_array(array_type)) {
9475 		pr_warn("map '%s': cannot be resized, last var must be an array\n",
9476 			bpf_map__name(map));
9477 		return -EINVAL;
9478 	}
9479 
9480 	/* verify request size aligns with array */
9481 	array = btf_array(array_type);
9482 	element_sz = btf__resolve_size(btf, array->type);
9483 	if (element_sz <= 0 || (size - var->offset) % element_sz != 0) {
9484 		pr_warn("map '%s': cannot be resized, element size (%d) doesn't align with new total size (%u)\n",
9485 			bpf_map__name(map), element_sz, size);
9486 		return -EINVAL;
9487 	}
9488 
9489 	/* create a new array based on the existing array, but with new length */
9490 	nr_elements = (size - var->offset) / element_sz;
9491 	new_array_id = btf__add_array(btf, array->index_type, array->type, nr_elements);
9492 	if (new_array_id < 0)
9493 		return new_array_id;
9494 
9495 	/* adding a new btf type invalidates existing pointers to btf objects,
9496 	 * so refresh pointers before proceeding
9497 	 */
9498 	datasec_type = btf_type_by_id(btf, map->btf_value_type_id);
9499 	var = &btf_var_secinfos(datasec_type)[vlen - 1];
9500 	var_type = btf_type_by_id(btf, var->type);
9501 
9502 	/* finally update btf info */
9503 	datasec_type->size = size;
9504 	var->size = size - var->offset;
9505 	var_type->type = new_array_id;
9506 
9507 	return 0;
9508 }
9509 
9510 int bpf_map__set_value_size(struct bpf_map *map, __u32 size)
9511 {
9512 	if (map->fd >= 0)
9513 		return libbpf_err(-EBUSY);
9514 
9515 	if (map->mmaped) {
9516 		int err;
9517 		size_t mmap_old_sz, mmap_new_sz;
9518 
9519 		mmap_old_sz = bpf_map_mmap_sz(map->def.value_size, map->def.max_entries);
9520 		mmap_new_sz = bpf_map_mmap_sz(size, map->def.max_entries);
9521 		err = bpf_map_mmap_resize(map, mmap_old_sz, mmap_new_sz);
9522 		if (err) {
9523 			pr_warn("map '%s': failed to resize memory-mapped region: %d\n",
9524 				bpf_map__name(map), err);
9525 			return err;
9526 		}
9527 		err = map_btf_datasec_resize(map, size);
9528 		if (err && err != -ENOENT) {
9529 			pr_warn("map '%s': failed to adjust resized BTF, clearing BTF key/value info: %d\n",
9530 				bpf_map__name(map), err);
9531 			map->btf_value_type_id = 0;
9532 			map->btf_key_type_id = 0;
9533 		}
9534 	}
9535 
9536 	map->def.value_size = size;
9537 	return 0;
9538 }
9539 
9540 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
9541 {
9542 	return map ? map->btf_key_type_id : 0;
9543 }
9544 
9545 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
9546 {
9547 	return map ? map->btf_value_type_id : 0;
9548 }
9549 
9550 int bpf_map__set_initial_value(struct bpf_map *map,
9551 			       const void *data, size_t size)
9552 {
9553 	if (!map->mmaped || map->libbpf_type == LIBBPF_MAP_KCONFIG ||
9554 	    size != map->def.value_size || map->fd >= 0)
9555 		return libbpf_err(-EINVAL);
9556 
9557 	memcpy(map->mmaped, data, size);
9558 	return 0;
9559 }
9560 
9561 void *bpf_map__initial_value(struct bpf_map *map, size_t *psize)
9562 {
9563 	if (!map->mmaped)
9564 		return NULL;
9565 	*psize = map->def.value_size;
9566 	return map->mmaped;
9567 }
9568 
9569 bool bpf_map__is_internal(const struct bpf_map *map)
9570 {
9571 	return map->libbpf_type != LIBBPF_MAP_UNSPEC;
9572 }
9573 
9574 __u32 bpf_map__ifindex(const struct bpf_map *map)
9575 {
9576 	return map->map_ifindex;
9577 }
9578 
9579 int bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
9580 {
9581 	if (map->fd >= 0)
9582 		return libbpf_err(-EBUSY);
9583 	map->map_ifindex = ifindex;
9584 	return 0;
9585 }
9586 
9587 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
9588 {
9589 	if (!bpf_map_type__is_map_in_map(map->def.type)) {
9590 		pr_warn("error: unsupported map type\n");
9591 		return libbpf_err(-EINVAL);
9592 	}
9593 	if (map->inner_map_fd != -1) {
9594 		pr_warn("error: inner_map_fd already specified\n");
9595 		return libbpf_err(-EINVAL);
9596 	}
9597 	if (map->inner_map) {
9598 		bpf_map__destroy(map->inner_map);
9599 		zfree(&map->inner_map);
9600 	}
9601 	map->inner_map_fd = fd;
9602 	return 0;
9603 }
9604 
9605 static struct bpf_map *
9606 __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
9607 {
9608 	ssize_t idx;
9609 	struct bpf_map *s, *e;
9610 
9611 	if (!obj || !obj->maps)
9612 		return errno = EINVAL, NULL;
9613 
9614 	s = obj->maps;
9615 	e = obj->maps + obj->nr_maps;
9616 
9617 	if ((m < s) || (m >= e)) {
9618 		pr_warn("error in %s: map handler doesn't belong to object\n",
9619 			 __func__);
9620 		return errno = EINVAL, NULL;
9621 	}
9622 
9623 	idx = (m - obj->maps) + i;
9624 	if (idx >= obj->nr_maps || idx < 0)
9625 		return NULL;
9626 	return &obj->maps[idx];
9627 }
9628 
9629 struct bpf_map *
9630 bpf_object__next_map(const struct bpf_object *obj, const struct bpf_map *prev)
9631 {
9632 	if (prev == NULL)
9633 		return obj->maps;
9634 
9635 	return __bpf_map__iter(prev, obj, 1);
9636 }
9637 
9638 struct bpf_map *
9639 bpf_object__prev_map(const struct bpf_object *obj, const struct bpf_map *next)
9640 {
9641 	if (next == NULL) {
9642 		if (!obj->nr_maps)
9643 			return NULL;
9644 		return obj->maps + obj->nr_maps - 1;
9645 	}
9646 
9647 	return __bpf_map__iter(next, obj, -1);
9648 }
9649 
9650 struct bpf_map *
9651 bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
9652 {
9653 	struct bpf_map *pos;
9654 
9655 	bpf_object__for_each_map(pos, obj) {
9656 		/* if it's a special internal map name (which always starts
9657 		 * with dot) then check if that special name matches the
9658 		 * real map name (ELF section name)
9659 		 */
9660 		if (name[0] == '.') {
9661 			if (pos->real_name && strcmp(pos->real_name, name) == 0)
9662 				return pos;
9663 			continue;
9664 		}
9665 		/* otherwise map name has to be an exact match */
9666 		if (map_uses_real_name(pos)) {
9667 			if (strcmp(pos->real_name, name) == 0)
9668 				return pos;
9669 			continue;
9670 		}
9671 		if (strcmp(pos->name, name) == 0)
9672 			return pos;
9673 	}
9674 	return errno = ENOENT, NULL;
9675 }
9676 
9677 int
9678 bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
9679 {
9680 	return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
9681 }
9682 
9683 static int validate_map_op(const struct bpf_map *map, size_t key_sz,
9684 			   size_t value_sz, bool check_value_sz)
9685 {
9686 	if (map->fd <= 0)
9687 		return -ENOENT;
9688 
9689 	if (map->def.key_size != key_sz) {
9690 		pr_warn("map '%s': unexpected key size %zu provided, expected %u\n",
9691 			map->name, key_sz, map->def.key_size);
9692 		return -EINVAL;
9693 	}
9694 
9695 	if (!check_value_sz)
9696 		return 0;
9697 
9698 	switch (map->def.type) {
9699 	case BPF_MAP_TYPE_PERCPU_ARRAY:
9700 	case BPF_MAP_TYPE_PERCPU_HASH:
9701 	case BPF_MAP_TYPE_LRU_PERCPU_HASH:
9702 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: {
9703 		int num_cpu = libbpf_num_possible_cpus();
9704 		size_t elem_sz = roundup(map->def.value_size, 8);
9705 
9706 		if (value_sz != num_cpu * elem_sz) {
9707 			pr_warn("map '%s': unexpected value size %zu provided for per-CPU map, expected %d * %zu = %zd\n",
9708 				map->name, value_sz, num_cpu, elem_sz, num_cpu * elem_sz);
9709 			return -EINVAL;
9710 		}
9711 		break;
9712 	}
9713 	default:
9714 		if (map->def.value_size != value_sz) {
9715 			pr_warn("map '%s': unexpected value size %zu provided, expected %u\n",
9716 				map->name, value_sz, map->def.value_size);
9717 			return -EINVAL;
9718 		}
9719 		break;
9720 	}
9721 	return 0;
9722 }
9723 
9724 int bpf_map__lookup_elem(const struct bpf_map *map,
9725 			 const void *key, size_t key_sz,
9726 			 void *value, size_t value_sz, __u64 flags)
9727 {
9728 	int err;
9729 
9730 	err = validate_map_op(map, key_sz, value_sz, true);
9731 	if (err)
9732 		return libbpf_err(err);
9733 
9734 	return bpf_map_lookup_elem_flags(map->fd, key, value, flags);
9735 }
9736 
9737 int bpf_map__update_elem(const struct bpf_map *map,
9738 			 const void *key, size_t key_sz,
9739 			 const void *value, size_t value_sz, __u64 flags)
9740 {
9741 	int err;
9742 
9743 	err = validate_map_op(map, key_sz, value_sz, true);
9744 	if (err)
9745 		return libbpf_err(err);
9746 
9747 	return bpf_map_update_elem(map->fd, key, value, flags);
9748 }
9749 
9750 int bpf_map__delete_elem(const struct bpf_map *map,
9751 			 const void *key, size_t key_sz, __u64 flags)
9752 {
9753 	int err;
9754 
9755 	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */);
9756 	if (err)
9757 		return libbpf_err(err);
9758 
9759 	return bpf_map_delete_elem_flags(map->fd, key, flags);
9760 }
9761 
9762 int bpf_map__lookup_and_delete_elem(const struct bpf_map *map,
9763 				    const void *key, size_t key_sz,
9764 				    void *value, size_t value_sz, __u64 flags)
9765 {
9766 	int err;
9767 
9768 	err = validate_map_op(map, key_sz, value_sz, true);
9769 	if (err)
9770 		return libbpf_err(err);
9771 
9772 	return bpf_map_lookup_and_delete_elem_flags(map->fd, key, value, flags);
9773 }
9774 
9775 int bpf_map__get_next_key(const struct bpf_map *map,
9776 			  const void *cur_key, void *next_key, size_t key_sz)
9777 {
9778 	int err;
9779 
9780 	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */);
9781 	if (err)
9782 		return libbpf_err(err);
9783 
9784 	return bpf_map_get_next_key(map->fd, cur_key, next_key);
9785 }
9786 
9787 long libbpf_get_error(const void *ptr)
9788 {
9789 	if (!IS_ERR_OR_NULL(ptr))
9790 		return 0;
9791 
9792 	if (IS_ERR(ptr))
9793 		errno = -PTR_ERR(ptr);
9794 
9795 	/* If ptr == NULL, then errno should be already set by the failing
9796 	 * API, because libbpf never returns NULL on success and it now always
9797 	 * sets errno on error. So no extra errno handling for ptr == NULL
9798 	 * case.
9799 	 */
9800 	return -errno;
9801 }
9802 
9803 /* Replace link's underlying BPF program with the new one */
9804 int bpf_link__update_program(struct bpf_link *link, struct bpf_program *prog)
9805 {
9806 	int ret;
9807 
9808 	ret = bpf_link_update(bpf_link__fd(link), bpf_program__fd(prog), NULL);
9809 	return libbpf_err_errno(ret);
9810 }
9811 
9812 /* Release "ownership" of underlying BPF resource (typically, BPF program
9813  * attached to some BPF hook, e.g., tracepoint, kprobe, etc). Disconnected
9814  * link, when destructed through bpf_link__destroy() call won't attempt to
9815  * detach/unregisted that BPF resource. This is useful in situations where,
9816  * say, attached BPF program has to outlive userspace program that attached it
9817  * in the system. Depending on type of BPF program, though, there might be
9818  * additional steps (like pinning BPF program in BPF FS) necessary to ensure
9819  * exit of userspace program doesn't trigger automatic detachment and clean up
9820  * inside the kernel.
9821  */
9822 void bpf_link__disconnect(struct bpf_link *link)
9823 {
9824 	link->disconnected = true;
9825 }
9826 
9827 int bpf_link__destroy(struct bpf_link *link)
9828 {
9829 	int err = 0;
9830 
9831 	if (IS_ERR_OR_NULL(link))
9832 		return 0;
9833 
9834 	if (!link->disconnected && link->detach)
9835 		err = link->detach(link);
9836 	if (link->pin_path)
9837 		free(link->pin_path);
9838 	if (link->dealloc)
9839 		link->dealloc(link);
9840 	else
9841 		free(link);
9842 
9843 	return libbpf_err(err);
9844 }
9845 
9846 int bpf_link__fd(const struct bpf_link *link)
9847 {
9848 	return link->fd;
9849 }
9850 
9851 const char *bpf_link__pin_path(const struct bpf_link *link)
9852 {
9853 	return link->pin_path;
9854 }
9855 
9856 static int bpf_link__detach_fd(struct bpf_link *link)
9857 {
9858 	return libbpf_err_errno(close(link->fd));
9859 }
9860 
9861 struct bpf_link *bpf_link__open(const char *path)
9862 {
9863 	struct bpf_link *link;
9864 	int fd;
9865 
9866 	fd = bpf_obj_get(path);
9867 	if (fd < 0) {
9868 		fd = -errno;
9869 		pr_warn("failed to open link at %s: %d\n", path, fd);
9870 		return libbpf_err_ptr(fd);
9871 	}
9872 
9873 	link = calloc(1, sizeof(*link));
9874 	if (!link) {
9875 		close(fd);
9876 		return libbpf_err_ptr(-ENOMEM);
9877 	}
9878 	link->detach = &bpf_link__detach_fd;
9879 	link->fd = fd;
9880 
9881 	link->pin_path = strdup(path);
9882 	if (!link->pin_path) {
9883 		bpf_link__destroy(link);
9884 		return libbpf_err_ptr(-ENOMEM);
9885 	}
9886 
9887 	return link;
9888 }
9889 
9890 int bpf_link__detach(struct bpf_link *link)
9891 {
9892 	return bpf_link_detach(link->fd) ? -errno : 0;
9893 }
9894 
9895 int bpf_link__pin(struct bpf_link *link, const char *path)
9896 {
9897 	int err;
9898 
9899 	if (link->pin_path)
9900 		return libbpf_err(-EBUSY);
9901 	err = make_parent_dir(path);
9902 	if (err)
9903 		return libbpf_err(err);
9904 	err = check_path(path);
9905 	if (err)
9906 		return libbpf_err(err);
9907 
9908 	link->pin_path = strdup(path);
9909 	if (!link->pin_path)
9910 		return libbpf_err(-ENOMEM);
9911 
9912 	if (bpf_obj_pin(link->fd, link->pin_path)) {
9913 		err = -errno;
9914 		zfree(&link->pin_path);
9915 		return libbpf_err(err);
9916 	}
9917 
9918 	pr_debug("link fd=%d: pinned at %s\n", link->fd, link->pin_path);
9919 	return 0;
9920 }
9921 
9922 int bpf_link__unpin(struct bpf_link *link)
9923 {
9924 	int err;
9925 
9926 	if (!link->pin_path)
9927 		return libbpf_err(-EINVAL);
9928 
9929 	err = unlink(link->pin_path);
9930 	if (err != 0)
9931 		return -errno;
9932 
9933 	pr_debug("link fd=%d: unpinned from %s\n", link->fd, link->pin_path);
9934 	zfree(&link->pin_path);
9935 	return 0;
9936 }
9937 
9938 struct bpf_link_perf {
9939 	struct bpf_link link;
9940 	int perf_event_fd;
9941 	/* legacy kprobe support: keep track of probe identifier and type */
9942 	char *legacy_probe_name;
9943 	bool legacy_is_kprobe;
9944 	bool legacy_is_retprobe;
9945 };
9946 
9947 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe);
9948 static int remove_uprobe_event_legacy(const char *probe_name, bool retprobe);
9949 
9950 static int bpf_link_perf_detach(struct bpf_link *link)
9951 {
9952 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
9953 	int err = 0;
9954 
9955 	if (ioctl(perf_link->perf_event_fd, PERF_EVENT_IOC_DISABLE, 0) < 0)
9956 		err = -errno;
9957 
9958 	if (perf_link->perf_event_fd != link->fd)
9959 		close(perf_link->perf_event_fd);
9960 	close(link->fd);
9961 
9962 	/* legacy uprobe/kprobe needs to be removed after perf event fd closure */
9963 	if (perf_link->legacy_probe_name) {
9964 		if (perf_link->legacy_is_kprobe) {
9965 			err = remove_kprobe_event_legacy(perf_link->legacy_probe_name,
9966 							 perf_link->legacy_is_retprobe);
9967 		} else {
9968 			err = remove_uprobe_event_legacy(perf_link->legacy_probe_name,
9969 							 perf_link->legacy_is_retprobe);
9970 		}
9971 	}
9972 
9973 	return err;
9974 }
9975 
9976 static void bpf_link_perf_dealloc(struct bpf_link *link)
9977 {
9978 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
9979 
9980 	free(perf_link->legacy_probe_name);
9981 	free(perf_link);
9982 }
9983 
9984 struct bpf_link *bpf_program__attach_perf_event_opts(const struct bpf_program *prog, int pfd,
9985 						     const struct bpf_perf_event_opts *opts)
9986 {
9987 	char errmsg[STRERR_BUFSIZE];
9988 	struct bpf_link_perf *link;
9989 	int prog_fd, link_fd = -1, err;
9990 	bool force_ioctl_attach;
9991 
9992 	if (!OPTS_VALID(opts, bpf_perf_event_opts))
9993 		return libbpf_err_ptr(-EINVAL);
9994 
9995 	if (pfd < 0) {
9996 		pr_warn("prog '%s': invalid perf event FD %d\n",
9997 			prog->name, pfd);
9998 		return libbpf_err_ptr(-EINVAL);
9999 	}
10000 	prog_fd = bpf_program__fd(prog);
10001 	if (prog_fd < 0) {
10002 		pr_warn("prog '%s': can't attach BPF program w/o FD (did you load it?)\n",
10003 			prog->name);
10004 		return libbpf_err_ptr(-EINVAL);
10005 	}
10006 
10007 	link = calloc(1, sizeof(*link));
10008 	if (!link)
10009 		return libbpf_err_ptr(-ENOMEM);
10010 	link->link.detach = &bpf_link_perf_detach;
10011 	link->link.dealloc = &bpf_link_perf_dealloc;
10012 	link->perf_event_fd = pfd;
10013 
10014 	force_ioctl_attach = OPTS_GET(opts, force_ioctl_attach, false);
10015 	if (kernel_supports(prog->obj, FEAT_PERF_LINK) && !force_ioctl_attach) {
10016 		DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_opts,
10017 			.perf_event.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0));
10018 
10019 		link_fd = bpf_link_create(prog_fd, pfd, BPF_PERF_EVENT, &link_opts);
10020 		if (link_fd < 0) {
10021 			err = -errno;
10022 			pr_warn("prog '%s': failed to create BPF link for perf_event FD %d: %d (%s)\n",
10023 				prog->name, pfd,
10024 				err, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10025 			goto err_out;
10026 		}
10027 		link->link.fd = link_fd;
10028 	} else {
10029 		if (OPTS_GET(opts, bpf_cookie, 0)) {
10030 			pr_warn("prog '%s': user context value is not supported\n", prog->name);
10031 			err = -EOPNOTSUPP;
10032 			goto err_out;
10033 		}
10034 
10035 		if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
10036 			err = -errno;
10037 			pr_warn("prog '%s': failed to attach to perf_event FD %d: %s\n",
10038 				prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10039 			if (err == -EPROTO)
10040 				pr_warn("prog '%s': try add PERF_SAMPLE_CALLCHAIN to or remove exclude_callchain_[kernel|user] from pfd %d\n",
10041 					prog->name, pfd);
10042 			goto err_out;
10043 		}
10044 		link->link.fd = pfd;
10045 	}
10046 	if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
10047 		err = -errno;
10048 		pr_warn("prog '%s': failed to enable perf_event FD %d: %s\n",
10049 			prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10050 		goto err_out;
10051 	}
10052 
10053 	return &link->link;
10054 err_out:
10055 	if (link_fd >= 0)
10056 		close(link_fd);
10057 	free(link);
10058 	return libbpf_err_ptr(err);
10059 }
10060 
10061 struct bpf_link *bpf_program__attach_perf_event(const struct bpf_program *prog, int pfd)
10062 {
10063 	return bpf_program__attach_perf_event_opts(prog, pfd, NULL);
10064 }
10065 
10066 /*
10067  * this function is expected to parse integer in the range of [0, 2^31-1] from
10068  * given file using scanf format string fmt. If actual parsed value is
10069  * negative, the result might be indistinguishable from error
10070  */
10071 static int parse_uint_from_file(const char *file, const char *fmt)
10072 {
10073 	char buf[STRERR_BUFSIZE];
10074 	int err, ret;
10075 	FILE *f;
10076 
10077 	f = fopen(file, "re");
10078 	if (!f) {
10079 		err = -errno;
10080 		pr_debug("failed to open '%s': %s\n", file,
10081 			 libbpf_strerror_r(err, buf, sizeof(buf)));
10082 		return err;
10083 	}
10084 	err = fscanf(f, fmt, &ret);
10085 	if (err != 1) {
10086 		err = err == EOF ? -EIO : -errno;
10087 		pr_debug("failed to parse '%s': %s\n", file,
10088 			libbpf_strerror_r(err, buf, sizeof(buf)));
10089 		fclose(f);
10090 		return err;
10091 	}
10092 	fclose(f);
10093 	return ret;
10094 }
10095 
10096 static int determine_kprobe_perf_type(void)
10097 {
10098 	const char *file = "/sys/bus/event_source/devices/kprobe/type";
10099 
10100 	return parse_uint_from_file(file, "%d\n");
10101 }
10102 
10103 static int determine_uprobe_perf_type(void)
10104 {
10105 	const char *file = "/sys/bus/event_source/devices/uprobe/type";
10106 
10107 	return parse_uint_from_file(file, "%d\n");
10108 }
10109 
10110 static int determine_kprobe_retprobe_bit(void)
10111 {
10112 	const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
10113 
10114 	return parse_uint_from_file(file, "config:%d\n");
10115 }
10116 
10117 static int determine_uprobe_retprobe_bit(void)
10118 {
10119 	const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
10120 
10121 	return parse_uint_from_file(file, "config:%d\n");
10122 }
10123 
10124 #define PERF_UPROBE_REF_CTR_OFFSET_BITS 32
10125 #define PERF_UPROBE_REF_CTR_OFFSET_SHIFT 32
10126 
10127 static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
10128 				 uint64_t offset, int pid, size_t ref_ctr_off)
10129 {
10130 	const size_t attr_sz = sizeof(struct perf_event_attr);
10131 	struct perf_event_attr attr;
10132 	char errmsg[STRERR_BUFSIZE];
10133 	int type, pfd;
10134 
10135 	if ((__u64)ref_ctr_off >= (1ULL << PERF_UPROBE_REF_CTR_OFFSET_BITS))
10136 		return -EINVAL;
10137 
10138 	memset(&attr, 0, attr_sz);
10139 
10140 	type = uprobe ? determine_uprobe_perf_type()
10141 		      : determine_kprobe_perf_type();
10142 	if (type < 0) {
10143 		pr_warn("failed to determine %s perf type: %s\n",
10144 			uprobe ? "uprobe" : "kprobe",
10145 			libbpf_strerror_r(type, errmsg, sizeof(errmsg)));
10146 		return type;
10147 	}
10148 	if (retprobe) {
10149 		int bit = uprobe ? determine_uprobe_retprobe_bit()
10150 				 : determine_kprobe_retprobe_bit();
10151 
10152 		if (bit < 0) {
10153 			pr_warn("failed to determine %s retprobe bit: %s\n",
10154 				uprobe ? "uprobe" : "kprobe",
10155 				libbpf_strerror_r(bit, errmsg, sizeof(errmsg)));
10156 			return bit;
10157 		}
10158 		attr.config |= 1 << bit;
10159 	}
10160 	attr.size = attr_sz;
10161 	attr.type = type;
10162 	attr.config |= (__u64)ref_ctr_off << PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
10163 	attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
10164 	attr.config2 = offset;		 /* kprobe_addr or probe_offset */
10165 
10166 	/* pid filter is meaningful only for uprobes */
10167 	pfd = syscall(__NR_perf_event_open, &attr,
10168 		      pid < 0 ? -1 : pid /* pid */,
10169 		      pid == -1 ? 0 : -1 /* cpu */,
10170 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
10171 	return pfd >= 0 ? pfd : -errno;
10172 }
10173 
10174 static int append_to_file(const char *file, const char *fmt, ...)
10175 {
10176 	int fd, n, err = 0;
10177 	va_list ap;
10178 	char buf[1024];
10179 
10180 	va_start(ap, fmt);
10181 	n = vsnprintf(buf, sizeof(buf), fmt, ap);
10182 	va_end(ap);
10183 
10184 	if (n < 0 || n >= sizeof(buf))
10185 		return -EINVAL;
10186 
10187 	fd = open(file, O_WRONLY | O_APPEND | O_CLOEXEC, 0);
10188 	if (fd < 0)
10189 		return -errno;
10190 
10191 	if (write(fd, buf, n) < 0)
10192 		err = -errno;
10193 
10194 	close(fd);
10195 	return err;
10196 }
10197 
10198 #define DEBUGFS "/sys/kernel/debug/tracing"
10199 #define TRACEFS "/sys/kernel/tracing"
10200 
10201 static bool use_debugfs(void)
10202 {
10203 	static int has_debugfs = -1;
10204 
10205 	if (has_debugfs < 0)
10206 		has_debugfs = faccessat(AT_FDCWD, DEBUGFS, F_OK, AT_EACCESS) == 0;
10207 
10208 	return has_debugfs == 1;
10209 }
10210 
10211 static const char *tracefs_path(void)
10212 {
10213 	return use_debugfs() ? DEBUGFS : TRACEFS;
10214 }
10215 
10216 static const char *tracefs_kprobe_events(void)
10217 {
10218 	return use_debugfs() ? DEBUGFS"/kprobe_events" : TRACEFS"/kprobe_events";
10219 }
10220 
10221 static const char *tracefs_uprobe_events(void)
10222 {
10223 	return use_debugfs() ? DEBUGFS"/uprobe_events" : TRACEFS"/uprobe_events";
10224 }
10225 
10226 static void gen_kprobe_legacy_event_name(char *buf, size_t buf_sz,
10227 					 const char *kfunc_name, size_t offset)
10228 {
10229 	static int index = 0;
10230 	int i;
10231 
10232 	snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx_%d", getpid(), kfunc_name, offset,
10233 		 __sync_fetch_and_add(&index, 1));
10234 
10235 	/* sanitize binary_path in the probe name */
10236 	for (i = 0; buf[i]; i++) {
10237 		if (!isalnum(buf[i]))
10238 			buf[i] = '_';
10239 	}
10240 }
10241 
10242 static int add_kprobe_event_legacy(const char *probe_name, bool retprobe,
10243 				   const char *kfunc_name, size_t offset)
10244 {
10245 	return append_to_file(tracefs_kprobe_events(), "%c:%s/%s %s+0x%zx",
10246 			      retprobe ? 'r' : 'p',
10247 			      retprobe ? "kretprobes" : "kprobes",
10248 			      probe_name, kfunc_name, offset);
10249 }
10250 
10251 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe)
10252 {
10253 	return append_to_file(tracefs_kprobe_events(), "-:%s/%s",
10254 			      retprobe ? "kretprobes" : "kprobes", probe_name);
10255 }
10256 
10257 static int determine_kprobe_perf_type_legacy(const char *probe_name, bool retprobe)
10258 {
10259 	char file[256];
10260 
10261 	snprintf(file, sizeof(file), "%s/events/%s/%s/id",
10262 		 tracefs_path(), retprobe ? "kretprobes" : "kprobes", probe_name);
10263 
10264 	return parse_uint_from_file(file, "%d\n");
10265 }
10266 
10267 static int perf_event_kprobe_open_legacy(const char *probe_name, bool retprobe,
10268 					 const char *kfunc_name, size_t offset, int pid)
10269 {
10270 	const size_t attr_sz = sizeof(struct perf_event_attr);
10271 	struct perf_event_attr attr;
10272 	char errmsg[STRERR_BUFSIZE];
10273 	int type, pfd, err;
10274 
10275 	err = add_kprobe_event_legacy(probe_name, retprobe, kfunc_name, offset);
10276 	if (err < 0) {
10277 		pr_warn("failed to add legacy kprobe event for '%s+0x%zx': %s\n",
10278 			kfunc_name, offset,
10279 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10280 		return err;
10281 	}
10282 	type = determine_kprobe_perf_type_legacy(probe_name, retprobe);
10283 	if (type < 0) {
10284 		err = type;
10285 		pr_warn("failed to determine legacy kprobe event id for '%s+0x%zx': %s\n",
10286 			kfunc_name, offset,
10287 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10288 		goto err_clean_legacy;
10289 	}
10290 
10291 	memset(&attr, 0, attr_sz);
10292 	attr.size = attr_sz;
10293 	attr.config = type;
10294 	attr.type = PERF_TYPE_TRACEPOINT;
10295 
10296 	pfd = syscall(__NR_perf_event_open, &attr,
10297 		      pid < 0 ? -1 : pid, /* pid */
10298 		      pid == -1 ? 0 : -1, /* cpu */
10299 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
10300 	if (pfd < 0) {
10301 		err = -errno;
10302 		pr_warn("legacy kprobe perf_event_open() failed: %s\n",
10303 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10304 		goto err_clean_legacy;
10305 	}
10306 	return pfd;
10307 
10308 err_clean_legacy:
10309 	/* Clear the newly added legacy kprobe_event */
10310 	remove_kprobe_event_legacy(probe_name, retprobe);
10311 	return err;
10312 }
10313 
10314 static const char *arch_specific_syscall_pfx(void)
10315 {
10316 #if defined(__x86_64__)
10317 	return "x64";
10318 #elif defined(__i386__)
10319 	return "ia32";
10320 #elif defined(__s390x__)
10321 	return "s390x";
10322 #elif defined(__s390__)
10323 	return "s390";
10324 #elif defined(__arm__)
10325 	return "arm";
10326 #elif defined(__aarch64__)
10327 	return "arm64";
10328 #elif defined(__mips__)
10329 	return "mips";
10330 #elif defined(__riscv)
10331 	return "riscv";
10332 #elif defined(__powerpc__)
10333 	return "powerpc";
10334 #elif defined(__powerpc64__)
10335 	return "powerpc64";
10336 #else
10337 	return NULL;
10338 #endif
10339 }
10340 
10341 static int probe_kern_syscall_wrapper(void)
10342 {
10343 	char syscall_name[64];
10344 	const char *ksys_pfx;
10345 
10346 	ksys_pfx = arch_specific_syscall_pfx();
10347 	if (!ksys_pfx)
10348 		return 0;
10349 
10350 	snprintf(syscall_name, sizeof(syscall_name), "__%s_sys_bpf", ksys_pfx);
10351 
10352 	if (determine_kprobe_perf_type() >= 0) {
10353 		int pfd;
10354 
10355 		pfd = perf_event_open_probe(false, false, syscall_name, 0, getpid(), 0);
10356 		if (pfd >= 0)
10357 			close(pfd);
10358 
10359 		return pfd >= 0 ? 1 : 0;
10360 	} else { /* legacy mode */
10361 		char probe_name[128];
10362 
10363 		gen_kprobe_legacy_event_name(probe_name, sizeof(probe_name), syscall_name, 0);
10364 		if (add_kprobe_event_legacy(probe_name, false, syscall_name, 0) < 0)
10365 			return 0;
10366 
10367 		(void)remove_kprobe_event_legacy(probe_name, false);
10368 		return 1;
10369 	}
10370 }
10371 
10372 struct bpf_link *
10373 bpf_program__attach_kprobe_opts(const struct bpf_program *prog,
10374 				const char *func_name,
10375 				const struct bpf_kprobe_opts *opts)
10376 {
10377 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
10378 	enum probe_attach_mode attach_mode;
10379 	char errmsg[STRERR_BUFSIZE];
10380 	char *legacy_probe = NULL;
10381 	struct bpf_link *link;
10382 	size_t offset;
10383 	bool retprobe, legacy;
10384 	int pfd, err;
10385 
10386 	if (!OPTS_VALID(opts, bpf_kprobe_opts))
10387 		return libbpf_err_ptr(-EINVAL);
10388 
10389 	attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
10390 	retprobe = OPTS_GET(opts, retprobe, false);
10391 	offset = OPTS_GET(opts, offset, 0);
10392 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
10393 
10394 	legacy = determine_kprobe_perf_type() < 0;
10395 	switch (attach_mode) {
10396 	case PROBE_ATTACH_MODE_LEGACY:
10397 		legacy = true;
10398 		pe_opts.force_ioctl_attach = true;
10399 		break;
10400 	case PROBE_ATTACH_MODE_PERF:
10401 		if (legacy)
10402 			return libbpf_err_ptr(-ENOTSUP);
10403 		pe_opts.force_ioctl_attach = true;
10404 		break;
10405 	case PROBE_ATTACH_MODE_LINK:
10406 		if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
10407 			return libbpf_err_ptr(-ENOTSUP);
10408 		break;
10409 	case PROBE_ATTACH_MODE_DEFAULT:
10410 		break;
10411 	default:
10412 		return libbpf_err_ptr(-EINVAL);
10413 	}
10414 
10415 	if (!legacy) {
10416 		pfd = perf_event_open_probe(false /* uprobe */, retprobe,
10417 					    func_name, offset,
10418 					    -1 /* pid */, 0 /* ref_ctr_off */);
10419 	} else {
10420 		char probe_name[256];
10421 
10422 		gen_kprobe_legacy_event_name(probe_name, sizeof(probe_name),
10423 					     func_name, offset);
10424 
10425 		legacy_probe = strdup(probe_name);
10426 		if (!legacy_probe)
10427 			return libbpf_err_ptr(-ENOMEM);
10428 
10429 		pfd = perf_event_kprobe_open_legacy(legacy_probe, retprobe, func_name,
10430 						    offset, -1 /* pid */);
10431 	}
10432 	if (pfd < 0) {
10433 		err = -errno;
10434 		pr_warn("prog '%s': failed to create %s '%s+0x%zx' perf event: %s\n",
10435 			prog->name, retprobe ? "kretprobe" : "kprobe",
10436 			func_name, offset,
10437 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10438 		goto err_out;
10439 	}
10440 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
10441 	err = libbpf_get_error(link);
10442 	if (err) {
10443 		close(pfd);
10444 		pr_warn("prog '%s': failed to attach to %s '%s+0x%zx': %s\n",
10445 			prog->name, retprobe ? "kretprobe" : "kprobe",
10446 			func_name, offset,
10447 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10448 		goto err_clean_legacy;
10449 	}
10450 	if (legacy) {
10451 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10452 
10453 		perf_link->legacy_probe_name = legacy_probe;
10454 		perf_link->legacy_is_kprobe = true;
10455 		perf_link->legacy_is_retprobe = retprobe;
10456 	}
10457 
10458 	return link;
10459 
10460 err_clean_legacy:
10461 	if (legacy)
10462 		remove_kprobe_event_legacy(legacy_probe, retprobe);
10463 err_out:
10464 	free(legacy_probe);
10465 	return libbpf_err_ptr(err);
10466 }
10467 
10468 struct bpf_link *bpf_program__attach_kprobe(const struct bpf_program *prog,
10469 					    bool retprobe,
10470 					    const char *func_name)
10471 {
10472 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts,
10473 		.retprobe = retprobe,
10474 	);
10475 
10476 	return bpf_program__attach_kprobe_opts(prog, func_name, &opts);
10477 }
10478 
10479 struct bpf_link *bpf_program__attach_ksyscall(const struct bpf_program *prog,
10480 					      const char *syscall_name,
10481 					      const struct bpf_ksyscall_opts *opts)
10482 {
10483 	LIBBPF_OPTS(bpf_kprobe_opts, kprobe_opts);
10484 	char func_name[128];
10485 
10486 	if (!OPTS_VALID(opts, bpf_ksyscall_opts))
10487 		return libbpf_err_ptr(-EINVAL);
10488 
10489 	if (kernel_supports(prog->obj, FEAT_SYSCALL_WRAPPER)) {
10490 		/* arch_specific_syscall_pfx() should never return NULL here
10491 		 * because it is guarded by kernel_supports(). However, since
10492 		 * compiler does not know that we have an explicit conditional
10493 		 * as well.
10494 		 */
10495 		snprintf(func_name, sizeof(func_name), "__%s_sys_%s",
10496 			 arch_specific_syscall_pfx() ? : "", syscall_name);
10497 	} else {
10498 		snprintf(func_name, sizeof(func_name), "__se_sys_%s", syscall_name);
10499 	}
10500 
10501 	kprobe_opts.retprobe = OPTS_GET(opts, retprobe, false);
10502 	kprobe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
10503 
10504 	return bpf_program__attach_kprobe_opts(prog, func_name, &kprobe_opts);
10505 }
10506 
10507 /* Adapted from perf/util/string.c */
10508 static bool glob_match(const char *str, const char *pat)
10509 {
10510 	while (*str && *pat && *pat != '*') {
10511 		if (*pat == '?') {      /* Matches any single character */
10512 			str++;
10513 			pat++;
10514 			continue;
10515 		}
10516 		if (*str != *pat)
10517 			return false;
10518 		str++;
10519 		pat++;
10520 	}
10521 	/* Check wild card */
10522 	if (*pat == '*') {
10523 		while (*pat == '*')
10524 			pat++;
10525 		if (!*pat) /* Tail wild card matches all */
10526 			return true;
10527 		while (*str)
10528 			if (glob_match(str++, pat))
10529 				return true;
10530 	}
10531 	return !*str && !*pat;
10532 }
10533 
10534 struct kprobe_multi_resolve {
10535 	const char *pattern;
10536 	unsigned long *addrs;
10537 	size_t cap;
10538 	size_t cnt;
10539 };
10540 
10541 static int
10542 resolve_kprobe_multi_cb(unsigned long long sym_addr, char sym_type,
10543 			const char *sym_name, void *ctx)
10544 {
10545 	struct kprobe_multi_resolve *res = ctx;
10546 	int err;
10547 
10548 	if (!glob_match(sym_name, res->pattern))
10549 		return 0;
10550 
10551 	err = libbpf_ensure_mem((void **) &res->addrs, &res->cap, sizeof(unsigned long),
10552 				res->cnt + 1);
10553 	if (err)
10554 		return err;
10555 
10556 	res->addrs[res->cnt++] = (unsigned long) sym_addr;
10557 	return 0;
10558 }
10559 
10560 struct bpf_link *
10561 bpf_program__attach_kprobe_multi_opts(const struct bpf_program *prog,
10562 				      const char *pattern,
10563 				      const struct bpf_kprobe_multi_opts *opts)
10564 {
10565 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
10566 	struct kprobe_multi_resolve res = {
10567 		.pattern = pattern,
10568 	};
10569 	struct bpf_link *link = NULL;
10570 	char errmsg[STRERR_BUFSIZE];
10571 	const unsigned long *addrs;
10572 	int err, link_fd, prog_fd;
10573 	const __u64 *cookies;
10574 	const char **syms;
10575 	bool retprobe;
10576 	size_t cnt;
10577 
10578 	if (!OPTS_VALID(opts, bpf_kprobe_multi_opts))
10579 		return libbpf_err_ptr(-EINVAL);
10580 
10581 	syms    = OPTS_GET(opts, syms, false);
10582 	addrs   = OPTS_GET(opts, addrs, false);
10583 	cnt     = OPTS_GET(opts, cnt, false);
10584 	cookies = OPTS_GET(opts, cookies, false);
10585 
10586 	if (!pattern && !addrs && !syms)
10587 		return libbpf_err_ptr(-EINVAL);
10588 	if (pattern && (addrs || syms || cookies || cnt))
10589 		return libbpf_err_ptr(-EINVAL);
10590 	if (!pattern && !cnt)
10591 		return libbpf_err_ptr(-EINVAL);
10592 	if (addrs && syms)
10593 		return libbpf_err_ptr(-EINVAL);
10594 
10595 	if (pattern) {
10596 		err = libbpf_kallsyms_parse(resolve_kprobe_multi_cb, &res);
10597 		if (err)
10598 			goto error;
10599 		if (!res.cnt) {
10600 			err = -ENOENT;
10601 			goto error;
10602 		}
10603 		addrs = res.addrs;
10604 		cnt = res.cnt;
10605 	}
10606 
10607 	retprobe = OPTS_GET(opts, retprobe, false);
10608 
10609 	lopts.kprobe_multi.syms = syms;
10610 	lopts.kprobe_multi.addrs = addrs;
10611 	lopts.kprobe_multi.cookies = cookies;
10612 	lopts.kprobe_multi.cnt = cnt;
10613 	lopts.kprobe_multi.flags = retprobe ? BPF_F_KPROBE_MULTI_RETURN : 0;
10614 
10615 	link = calloc(1, sizeof(*link));
10616 	if (!link) {
10617 		err = -ENOMEM;
10618 		goto error;
10619 	}
10620 	link->detach = &bpf_link__detach_fd;
10621 
10622 	prog_fd = bpf_program__fd(prog);
10623 	link_fd = bpf_link_create(prog_fd, 0, BPF_TRACE_KPROBE_MULTI, &lopts);
10624 	if (link_fd < 0) {
10625 		err = -errno;
10626 		pr_warn("prog '%s': failed to attach: %s\n",
10627 			prog->name, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10628 		goto error;
10629 	}
10630 	link->fd = link_fd;
10631 	free(res.addrs);
10632 	return link;
10633 
10634 error:
10635 	free(link);
10636 	free(res.addrs);
10637 	return libbpf_err_ptr(err);
10638 }
10639 
10640 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
10641 {
10642 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts);
10643 	unsigned long offset = 0;
10644 	const char *func_name;
10645 	char *func;
10646 	int n;
10647 
10648 	*link = NULL;
10649 
10650 	/* no auto-attach for SEC("kprobe") and SEC("kretprobe") */
10651 	if (strcmp(prog->sec_name, "kprobe") == 0 || strcmp(prog->sec_name, "kretprobe") == 0)
10652 		return 0;
10653 
10654 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe/");
10655 	if (opts.retprobe)
10656 		func_name = prog->sec_name + sizeof("kretprobe/") - 1;
10657 	else
10658 		func_name = prog->sec_name + sizeof("kprobe/") - 1;
10659 
10660 	n = sscanf(func_name, "%m[a-zA-Z0-9_.]+%li", &func, &offset);
10661 	if (n < 1) {
10662 		pr_warn("kprobe name is invalid: %s\n", func_name);
10663 		return -EINVAL;
10664 	}
10665 	if (opts.retprobe && offset != 0) {
10666 		free(func);
10667 		pr_warn("kretprobes do not support offset specification\n");
10668 		return -EINVAL;
10669 	}
10670 
10671 	opts.offset = offset;
10672 	*link = bpf_program__attach_kprobe_opts(prog, func, &opts);
10673 	free(func);
10674 	return libbpf_get_error(*link);
10675 }
10676 
10677 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link)
10678 {
10679 	LIBBPF_OPTS(bpf_ksyscall_opts, opts);
10680 	const char *syscall_name;
10681 
10682 	*link = NULL;
10683 
10684 	/* no auto-attach for SEC("ksyscall") and SEC("kretsyscall") */
10685 	if (strcmp(prog->sec_name, "ksyscall") == 0 || strcmp(prog->sec_name, "kretsyscall") == 0)
10686 		return 0;
10687 
10688 	opts.retprobe = str_has_pfx(prog->sec_name, "kretsyscall/");
10689 	if (opts.retprobe)
10690 		syscall_name = prog->sec_name + sizeof("kretsyscall/") - 1;
10691 	else
10692 		syscall_name = prog->sec_name + sizeof("ksyscall/") - 1;
10693 
10694 	*link = bpf_program__attach_ksyscall(prog, syscall_name, &opts);
10695 	return *link ? 0 : -errno;
10696 }
10697 
10698 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
10699 {
10700 	LIBBPF_OPTS(bpf_kprobe_multi_opts, opts);
10701 	const char *spec;
10702 	char *pattern;
10703 	int n;
10704 
10705 	*link = NULL;
10706 
10707 	/* no auto-attach for SEC("kprobe.multi") and SEC("kretprobe.multi") */
10708 	if (strcmp(prog->sec_name, "kprobe.multi") == 0 ||
10709 	    strcmp(prog->sec_name, "kretprobe.multi") == 0)
10710 		return 0;
10711 
10712 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe.multi/");
10713 	if (opts.retprobe)
10714 		spec = prog->sec_name + sizeof("kretprobe.multi/") - 1;
10715 	else
10716 		spec = prog->sec_name + sizeof("kprobe.multi/") - 1;
10717 
10718 	n = sscanf(spec, "%m[a-zA-Z0-9_.*?]", &pattern);
10719 	if (n < 1) {
10720 		pr_warn("kprobe multi pattern is invalid: %s\n", pattern);
10721 		return -EINVAL;
10722 	}
10723 
10724 	*link = bpf_program__attach_kprobe_multi_opts(prog, pattern, &opts);
10725 	free(pattern);
10726 	return libbpf_get_error(*link);
10727 }
10728 
10729 static void gen_uprobe_legacy_event_name(char *buf, size_t buf_sz,
10730 					 const char *binary_path, uint64_t offset)
10731 {
10732 	int i;
10733 
10734 	snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx", getpid(), binary_path, (size_t)offset);
10735 
10736 	/* sanitize binary_path in the probe name */
10737 	for (i = 0; buf[i]; i++) {
10738 		if (!isalnum(buf[i]))
10739 			buf[i] = '_';
10740 	}
10741 }
10742 
10743 static inline int add_uprobe_event_legacy(const char *probe_name, bool retprobe,
10744 					  const char *binary_path, size_t offset)
10745 {
10746 	return append_to_file(tracefs_uprobe_events(), "%c:%s/%s %s:0x%zx",
10747 			      retprobe ? 'r' : 'p',
10748 			      retprobe ? "uretprobes" : "uprobes",
10749 			      probe_name, binary_path, offset);
10750 }
10751 
10752 static inline int remove_uprobe_event_legacy(const char *probe_name, bool retprobe)
10753 {
10754 	return append_to_file(tracefs_uprobe_events(), "-:%s/%s",
10755 			      retprobe ? "uretprobes" : "uprobes", probe_name);
10756 }
10757 
10758 static int determine_uprobe_perf_type_legacy(const char *probe_name, bool retprobe)
10759 {
10760 	char file[512];
10761 
10762 	snprintf(file, sizeof(file), "%s/events/%s/%s/id",
10763 		 tracefs_path(), retprobe ? "uretprobes" : "uprobes", probe_name);
10764 
10765 	return parse_uint_from_file(file, "%d\n");
10766 }
10767 
10768 static int perf_event_uprobe_open_legacy(const char *probe_name, bool retprobe,
10769 					 const char *binary_path, size_t offset, int pid)
10770 {
10771 	const size_t attr_sz = sizeof(struct perf_event_attr);
10772 	struct perf_event_attr attr;
10773 	int type, pfd, err;
10774 
10775 	err = add_uprobe_event_legacy(probe_name, retprobe, binary_path, offset);
10776 	if (err < 0) {
10777 		pr_warn("failed to add legacy uprobe event for %s:0x%zx: %d\n",
10778 			binary_path, (size_t)offset, err);
10779 		return err;
10780 	}
10781 	type = determine_uprobe_perf_type_legacy(probe_name, retprobe);
10782 	if (type < 0) {
10783 		err = type;
10784 		pr_warn("failed to determine legacy uprobe event id for %s:0x%zx: %d\n",
10785 			binary_path, offset, err);
10786 		goto err_clean_legacy;
10787 	}
10788 
10789 	memset(&attr, 0, attr_sz);
10790 	attr.size = attr_sz;
10791 	attr.config = type;
10792 	attr.type = PERF_TYPE_TRACEPOINT;
10793 
10794 	pfd = syscall(__NR_perf_event_open, &attr,
10795 		      pid < 0 ? -1 : pid, /* pid */
10796 		      pid == -1 ? 0 : -1, /* cpu */
10797 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
10798 	if (pfd < 0) {
10799 		err = -errno;
10800 		pr_warn("legacy uprobe perf_event_open() failed: %d\n", err);
10801 		goto err_clean_legacy;
10802 	}
10803 	return pfd;
10804 
10805 err_clean_legacy:
10806 	/* Clear the newly added legacy uprobe_event */
10807 	remove_uprobe_event_legacy(probe_name, retprobe);
10808 	return err;
10809 }
10810 
10811 /* Return next ELF section of sh_type after scn, or first of that type if scn is NULL. */
10812 static Elf_Scn *elf_find_next_scn_by_type(Elf *elf, int sh_type, Elf_Scn *scn)
10813 {
10814 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
10815 		GElf_Shdr sh;
10816 
10817 		if (!gelf_getshdr(scn, &sh))
10818 			continue;
10819 		if (sh.sh_type == sh_type)
10820 			return scn;
10821 	}
10822 	return NULL;
10823 }
10824 
10825 /* Find offset of function name in the provided ELF object. "binary_path" is
10826  * the path to the ELF binary represented by "elf", and only used for error
10827  * reporting matters. "name" matches symbol name or name@@LIB for library
10828  * functions.
10829  */
10830 static long elf_find_func_offset(Elf *elf, const char *binary_path, const char *name)
10831 {
10832 	int i, sh_types[2] = { SHT_DYNSYM, SHT_SYMTAB };
10833 	bool is_shared_lib, is_name_qualified;
10834 	long ret = -ENOENT;
10835 	size_t name_len;
10836 	GElf_Ehdr ehdr;
10837 
10838 	if (!gelf_getehdr(elf, &ehdr)) {
10839 		pr_warn("elf: failed to get ehdr from %s: %s\n", binary_path, elf_errmsg(-1));
10840 		ret = -LIBBPF_ERRNO__FORMAT;
10841 		goto out;
10842 	}
10843 	/* for shared lib case, we do not need to calculate relative offset */
10844 	is_shared_lib = ehdr.e_type == ET_DYN;
10845 
10846 	name_len = strlen(name);
10847 	/* Does name specify "@@LIB"? */
10848 	is_name_qualified = strstr(name, "@@") != NULL;
10849 
10850 	/* Search SHT_DYNSYM, SHT_SYMTAB for symbol. This search order is used because if
10851 	 * a binary is stripped, it may only have SHT_DYNSYM, and a fully-statically
10852 	 * linked binary may not have SHT_DYMSYM, so absence of a section should not be
10853 	 * reported as a warning/error.
10854 	 */
10855 	for (i = 0; i < ARRAY_SIZE(sh_types); i++) {
10856 		size_t nr_syms, strtabidx, idx;
10857 		Elf_Data *symbols = NULL;
10858 		Elf_Scn *scn = NULL;
10859 		int last_bind = -1;
10860 		const char *sname;
10861 		GElf_Shdr sh;
10862 
10863 		scn = elf_find_next_scn_by_type(elf, sh_types[i], NULL);
10864 		if (!scn) {
10865 			pr_debug("elf: failed to find symbol table ELF sections in '%s'\n",
10866 				 binary_path);
10867 			continue;
10868 		}
10869 		if (!gelf_getshdr(scn, &sh))
10870 			continue;
10871 		strtabidx = sh.sh_link;
10872 		symbols = elf_getdata(scn, 0);
10873 		if (!symbols) {
10874 			pr_warn("elf: failed to get symbols for symtab section in '%s': %s\n",
10875 				binary_path, elf_errmsg(-1));
10876 			ret = -LIBBPF_ERRNO__FORMAT;
10877 			goto out;
10878 		}
10879 		nr_syms = symbols->d_size / sh.sh_entsize;
10880 
10881 		for (idx = 0; idx < nr_syms; idx++) {
10882 			int curr_bind;
10883 			GElf_Sym sym;
10884 			Elf_Scn *sym_scn;
10885 			GElf_Shdr sym_sh;
10886 
10887 			if (!gelf_getsym(symbols, idx, &sym))
10888 				continue;
10889 
10890 			if (GELF_ST_TYPE(sym.st_info) != STT_FUNC)
10891 				continue;
10892 
10893 			sname = elf_strptr(elf, strtabidx, sym.st_name);
10894 			if (!sname)
10895 				continue;
10896 
10897 			curr_bind = GELF_ST_BIND(sym.st_info);
10898 
10899 			/* User can specify func, func@@LIB or func@@LIB_VERSION. */
10900 			if (strncmp(sname, name, name_len) != 0)
10901 				continue;
10902 			/* ...but we don't want a search for "foo" to match 'foo2" also, so any
10903 			 * additional characters in sname should be of the form "@@LIB".
10904 			 */
10905 			if (!is_name_qualified && sname[name_len] != '\0' && sname[name_len] != '@')
10906 				continue;
10907 
10908 			if (ret >= 0) {
10909 				/* handle multiple matches */
10910 				if (last_bind != STB_WEAK && curr_bind != STB_WEAK) {
10911 					/* Only accept one non-weak bind. */
10912 					pr_warn("elf: ambiguous match for '%s', '%s' in '%s'\n",
10913 						sname, name, binary_path);
10914 					ret = -LIBBPF_ERRNO__FORMAT;
10915 					goto out;
10916 				} else if (curr_bind == STB_WEAK) {
10917 					/* already have a non-weak bind, and
10918 					 * this is a weak bind, so ignore.
10919 					 */
10920 					continue;
10921 				}
10922 			}
10923 
10924 			/* Transform symbol's virtual address (absolute for
10925 			 * binaries and relative for shared libs) into file
10926 			 * offset, which is what kernel is expecting for
10927 			 * uprobe/uretprobe attachment.
10928 			 * See Documentation/trace/uprobetracer.rst for more
10929 			 * details.
10930 			 * This is done by looking up symbol's containing
10931 			 * section's header and using it's virtual address
10932 			 * (sh_addr) and corresponding file offset (sh_offset)
10933 			 * to transform sym.st_value (virtual address) into
10934 			 * desired final file offset.
10935 			 */
10936 			sym_scn = elf_getscn(elf, sym.st_shndx);
10937 			if (!sym_scn)
10938 				continue;
10939 			if (!gelf_getshdr(sym_scn, &sym_sh))
10940 				continue;
10941 
10942 			ret = sym.st_value - sym_sh.sh_addr + sym_sh.sh_offset;
10943 			last_bind = curr_bind;
10944 		}
10945 		if (ret > 0)
10946 			break;
10947 	}
10948 
10949 	if (ret > 0) {
10950 		pr_debug("elf: symbol address match for '%s' in '%s': 0x%lx\n", name, binary_path,
10951 			 ret);
10952 	} else {
10953 		if (ret == 0) {
10954 			pr_warn("elf: '%s' is 0 in symtab for '%s': %s\n", name, binary_path,
10955 				is_shared_lib ? "should not be 0 in a shared library" :
10956 						"try using shared library path instead");
10957 			ret = -ENOENT;
10958 		} else {
10959 			pr_warn("elf: failed to find symbol '%s' in '%s'\n", name, binary_path);
10960 		}
10961 	}
10962 out:
10963 	return ret;
10964 }
10965 
10966 /* Find offset of function name in ELF object specified by path. "name" matches
10967  * symbol name or name@@LIB for library functions.
10968  */
10969 static long elf_find_func_offset_from_file(const char *binary_path, const char *name)
10970 {
10971 	char errmsg[STRERR_BUFSIZE];
10972 	long ret = -ENOENT;
10973 	Elf *elf;
10974 	int fd;
10975 
10976 	fd = open(binary_path, O_RDONLY | O_CLOEXEC);
10977 	if (fd < 0) {
10978 		ret = -errno;
10979 		pr_warn("failed to open %s: %s\n", binary_path,
10980 			libbpf_strerror_r(ret, errmsg, sizeof(errmsg)));
10981 		return ret;
10982 	}
10983 	elf = elf_begin(fd, ELF_C_READ_MMAP, NULL);
10984 	if (!elf) {
10985 		pr_warn("elf: could not read elf from %s: %s\n", binary_path, elf_errmsg(-1));
10986 		close(fd);
10987 		return -LIBBPF_ERRNO__FORMAT;
10988 	}
10989 
10990 	ret = elf_find_func_offset(elf, binary_path, name);
10991 	elf_end(elf);
10992 	close(fd);
10993 	return ret;
10994 }
10995 
10996 /* Find offset of function name in archive specified by path. Currently
10997  * supported are .zip files that do not compress their contents, as used on
10998  * Android in the form of APKs, for example. "file_name" is the name of the ELF
10999  * file inside the archive. "func_name" matches symbol name or name@@LIB for
11000  * library functions.
11001  *
11002  * An overview of the APK format specifically provided here:
11003  * https://en.wikipedia.org/w/index.php?title=Apk_(file_format)&oldid=1139099120#Package_contents
11004  */
11005 static long elf_find_func_offset_from_archive(const char *archive_path, const char *file_name,
11006 					      const char *func_name)
11007 {
11008 	struct zip_archive *archive;
11009 	struct zip_entry entry;
11010 	long ret;
11011 	Elf *elf;
11012 
11013 	archive = zip_archive_open(archive_path);
11014 	if (IS_ERR(archive)) {
11015 		ret = PTR_ERR(archive);
11016 		pr_warn("zip: failed to open %s: %ld\n", archive_path, ret);
11017 		return ret;
11018 	}
11019 
11020 	ret = zip_archive_find_entry(archive, file_name, &entry);
11021 	if (ret) {
11022 		pr_warn("zip: could not find archive member %s in %s: %ld\n", file_name,
11023 			archive_path, ret);
11024 		goto out;
11025 	}
11026 	pr_debug("zip: found entry for %s in %s at 0x%lx\n", file_name, archive_path,
11027 		 (unsigned long)entry.data_offset);
11028 
11029 	if (entry.compression) {
11030 		pr_warn("zip: entry %s of %s is compressed and cannot be handled\n", file_name,
11031 			archive_path);
11032 		ret = -LIBBPF_ERRNO__FORMAT;
11033 		goto out;
11034 	}
11035 
11036 	elf = elf_memory((void *)entry.data, entry.data_length);
11037 	if (!elf) {
11038 		pr_warn("elf: could not read elf file %s from %s: %s\n", file_name, archive_path,
11039 			elf_errmsg(-1));
11040 		ret = -LIBBPF_ERRNO__LIBELF;
11041 		goto out;
11042 	}
11043 
11044 	ret = elf_find_func_offset(elf, file_name, func_name);
11045 	if (ret > 0) {
11046 		pr_debug("elf: symbol address match for %s of %s in %s: 0x%x + 0x%lx = 0x%lx\n",
11047 			 func_name, file_name, archive_path, entry.data_offset, ret,
11048 			 ret + entry.data_offset);
11049 		ret += entry.data_offset;
11050 	}
11051 	elf_end(elf);
11052 
11053 out:
11054 	zip_archive_close(archive);
11055 	return ret;
11056 }
11057 
11058 static const char *arch_specific_lib_paths(void)
11059 {
11060 	/*
11061 	 * Based on https://packages.debian.org/sid/libc6.
11062 	 *
11063 	 * Assume that the traced program is built for the same architecture
11064 	 * as libbpf, which should cover the vast majority of cases.
11065 	 */
11066 #if defined(__x86_64__)
11067 	return "/lib/x86_64-linux-gnu";
11068 #elif defined(__i386__)
11069 	return "/lib/i386-linux-gnu";
11070 #elif defined(__s390x__)
11071 	return "/lib/s390x-linux-gnu";
11072 #elif defined(__s390__)
11073 	return "/lib/s390-linux-gnu";
11074 #elif defined(__arm__) && defined(__SOFTFP__)
11075 	return "/lib/arm-linux-gnueabi";
11076 #elif defined(__arm__) && !defined(__SOFTFP__)
11077 	return "/lib/arm-linux-gnueabihf";
11078 #elif defined(__aarch64__)
11079 	return "/lib/aarch64-linux-gnu";
11080 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 64
11081 	return "/lib/mips64el-linux-gnuabi64";
11082 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 32
11083 	return "/lib/mipsel-linux-gnu";
11084 #elif defined(__powerpc64__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
11085 	return "/lib/powerpc64le-linux-gnu";
11086 #elif defined(__sparc__) && defined(__arch64__)
11087 	return "/lib/sparc64-linux-gnu";
11088 #elif defined(__riscv) && __riscv_xlen == 64
11089 	return "/lib/riscv64-linux-gnu";
11090 #else
11091 	return NULL;
11092 #endif
11093 }
11094 
11095 /* Get full path to program/shared library. */
11096 static int resolve_full_path(const char *file, char *result, size_t result_sz)
11097 {
11098 	const char *search_paths[3] = {};
11099 	int i, perm;
11100 
11101 	if (str_has_sfx(file, ".so") || strstr(file, ".so.")) {
11102 		search_paths[0] = getenv("LD_LIBRARY_PATH");
11103 		search_paths[1] = "/usr/lib64:/usr/lib";
11104 		search_paths[2] = arch_specific_lib_paths();
11105 		perm = R_OK;
11106 	} else {
11107 		search_paths[0] = getenv("PATH");
11108 		search_paths[1] = "/usr/bin:/usr/sbin";
11109 		perm = R_OK | X_OK;
11110 	}
11111 
11112 	for (i = 0; i < ARRAY_SIZE(search_paths); i++) {
11113 		const char *s;
11114 
11115 		if (!search_paths[i])
11116 			continue;
11117 		for (s = search_paths[i]; s != NULL; s = strchr(s, ':')) {
11118 			char *next_path;
11119 			int seg_len;
11120 
11121 			if (s[0] == ':')
11122 				s++;
11123 			next_path = strchr(s, ':');
11124 			seg_len = next_path ? next_path - s : strlen(s);
11125 			if (!seg_len)
11126 				continue;
11127 			snprintf(result, result_sz, "%.*s/%s", seg_len, s, file);
11128 			/* ensure it has required permissions */
11129 			if (faccessat(AT_FDCWD, result, perm, AT_EACCESS) < 0)
11130 				continue;
11131 			pr_debug("resolved '%s' to '%s'\n", file, result);
11132 			return 0;
11133 		}
11134 	}
11135 	return -ENOENT;
11136 }
11137 
11138 LIBBPF_API struct bpf_link *
11139 bpf_program__attach_uprobe_opts(const struct bpf_program *prog, pid_t pid,
11140 				const char *binary_path, size_t func_offset,
11141 				const struct bpf_uprobe_opts *opts)
11142 {
11143 	const char *archive_path = NULL, *archive_sep = NULL;
11144 	char errmsg[STRERR_BUFSIZE], *legacy_probe = NULL;
11145 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
11146 	enum probe_attach_mode attach_mode;
11147 	char full_path[PATH_MAX];
11148 	struct bpf_link *link;
11149 	size_t ref_ctr_off;
11150 	int pfd, err;
11151 	bool retprobe, legacy;
11152 	const char *func_name;
11153 
11154 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
11155 		return libbpf_err_ptr(-EINVAL);
11156 
11157 	attach_mode = OPTS_GET(opts, attach_mode, PROBE_ATTACH_MODE_DEFAULT);
11158 	retprobe = OPTS_GET(opts, retprobe, false);
11159 	ref_ctr_off = OPTS_GET(opts, ref_ctr_offset, 0);
11160 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11161 
11162 	if (!binary_path)
11163 		return libbpf_err_ptr(-EINVAL);
11164 
11165 	/* Check if "binary_path" refers to an archive. */
11166 	archive_sep = strstr(binary_path, "!/");
11167 	if (archive_sep) {
11168 		full_path[0] = '\0';
11169 		libbpf_strlcpy(full_path, binary_path,
11170 			       min(sizeof(full_path), (size_t)(archive_sep - binary_path + 1)));
11171 		archive_path = full_path;
11172 		binary_path = archive_sep + 2;
11173 	} else if (!strchr(binary_path, '/')) {
11174 		err = resolve_full_path(binary_path, full_path, sizeof(full_path));
11175 		if (err) {
11176 			pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
11177 				prog->name, binary_path, err);
11178 			return libbpf_err_ptr(err);
11179 		}
11180 		binary_path = full_path;
11181 	}
11182 	func_name = OPTS_GET(opts, func_name, NULL);
11183 	if (func_name) {
11184 		long sym_off;
11185 
11186 		if (archive_path) {
11187 			sym_off = elf_find_func_offset_from_archive(archive_path, binary_path,
11188 								    func_name);
11189 			binary_path = archive_path;
11190 		} else {
11191 			sym_off = elf_find_func_offset_from_file(binary_path, func_name);
11192 		}
11193 		if (sym_off < 0)
11194 			return libbpf_err_ptr(sym_off);
11195 		func_offset += sym_off;
11196 	}
11197 
11198 	legacy = determine_uprobe_perf_type() < 0;
11199 	switch (attach_mode) {
11200 	case PROBE_ATTACH_MODE_LEGACY:
11201 		legacy = true;
11202 		pe_opts.force_ioctl_attach = true;
11203 		break;
11204 	case PROBE_ATTACH_MODE_PERF:
11205 		if (legacy)
11206 			return libbpf_err_ptr(-ENOTSUP);
11207 		pe_opts.force_ioctl_attach = true;
11208 		break;
11209 	case PROBE_ATTACH_MODE_LINK:
11210 		if (legacy || !kernel_supports(prog->obj, FEAT_PERF_LINK))
11211 			return libbpf_err_ptr(-ENOTSUP);
11212 		break;
11213 	case PROBE_ATTACH_MODE_DEFAULT:
11214 		break;
11215 	default:
11216 		return libbpf_err_ptr(-EINVAL);
11217 	}
11218 
11219 	if (!legacy) {
11220 		pfd = perf_event_open_probe(true /* uprobe */, retprobe, binary_path,
11221 					    func_offset, pid, ref_ctr_off);
11222 	} else {
11223 		char probe_name[PATH_MAX + 64];
11224 
11225 		if (ref_ctr_off)
11226 			return libbpf_err_ptr(-EINVAL);
11227 
11228 		gen_uprobe_legacy_event_name(probe_name, sizeof(probe_name),
11229 					     binary_path, func_offset);
11230 
11231 		legacy_probe = strdup(probe_name);
11232 		if (!legacy_probe)
11233 			return libbpf_err_ptr(-ENOMEM);
11234 
11235 		pfd = perf_event_uprobe_open_legacy(legacy_probe, retprobe,
11236 						    binary_path, func_offset, pid);
11237 	}
11238 	if (pfd < 0) {
11239 		err = -errno;
11240 		pr_warn("prog '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
11241 			prog->name, retprobe ? "uretprobe" : "uprobe",
11242 			binary_path, func_offset,
11243 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11244 		goto err_out;
11245 	}
11246 
11247 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
11248 	err = libbpf_get_error(link);
11249 	if (err) {
11250 		close(pfd);
11251 		pr_warn("prog '%s': failed to attach to %s '%s:0x%zx': %s\n",
11252 			prog->name, retprobe ? "uretprobe" : "uprobe",
11253 			binary_path, func_offset,
11254 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11255 		goto err_clean_legacy;
11256 	}
11257 	if (legacy) {
11258 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
11259 
11260 		perf_link->legacy_probe_name = legacy_probe;
11261 		perf_link->legacy_is_kprobe = false;
11262 		perf_link->legacy_is_retprobe = retprobe;
11263 	}
11264 	return link;
11265 
11266 err_clean_legacy:
11267 	if (legacy)
11268 		remove_uprobe_event_legacy(legacy_probe, retprobe);
11269 err_out:
11270 	free(legacy_probe);
11271 	return libbpf_err_ptr(err);
11272 }
11273 
11274 /* Format of u[ret]probe section definition supporting auto-attach:
11275  * u[ret]probe/binary:function[+offset]
11276  *
11277  * binary can be an absolute/relative path or a filename; the latter is resolved to a
11278  * full binary path via bpf_program__attach_uprobe_opts.
11279  *
11280  * Specifying uprobe+ ensures we carry out strict matching; either "uprobe" must be
11281  * specified (and auto-attach is not possible) or the above format is specified for
11282  * auto-attach.
11283  */
11284 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11285 {
11286 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts);
11287 	char *probe_type = NULL, *binary_path = NULL, *func_name = NULL;
11288 	int n, ret = -EINVAL;
11289 	long offset = 0;
11290 
11291 	*link = NULL;
11292 
11293 	n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[a-zA-Z0-9_.]+%li",
11294 		   &probe_type, &binary_path, &func_name, &offset);
11295 	switch (n) {
11296 	case 1:
11297 		/* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
11298 		ret = 0;
11299 		break;
11300 	case 2:
11301 		pr_warn("prog '%s': section '%s' missing ':function[+offset]' specification\n",
11302 			prog->name, prog->sec_name);
11303 		break;
11304 	case 3:
11305 	case 4:
11306 		opts.retprobe = strcmp(probe_type, "uretprobe") == 0 ||
11307 				strcmp(probe_type, "uretprobe.s") == 0;
11308 		if (opts.retprobe && offset != 0) {
11309 			pr_warn("prog '%s': uretprobes do not support offset specification\n",
11310 				prog->name);
11311 			break;
11312 		}
11313 		opts.func_name = func_name;
11314 		*link = bpf_program__attach_uprobe_opts(prog, -1, binary_path, offset, &opts);
11315 		ret = libbpf_get_error(*link);
11316 		break;
11317 	default:
11318 		pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
11319 			prog->sec_name);
11320 		break;
11321 	}
11322 	free(probe_type);
11323 	free(binary_path);
11324 	free(func_name);
11325 
11326 	return ret;
11327 }
11328 
11329 struct bpf_link *bpf_program__attach_uprobe(const struct bpf_program *prog,
11330 					    bool retprobe, pid_t pid,
11331 					    const char *binary_path,
11332 					    size_t func_offset)
11333 {
11334 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts, .retprobe = retprobe);
11335 
11336 	return bpf_program__attach_uprobe_opts(prog, pid, binary_path, func_offset, &opts);
11337 }
11338 
11339 struct bpf_link *bpf_program__attach_usdt(const struct bpf_program *prog,
11340 					  pid_t pid, const char *binary_path,
11341 					  const char *usdt_provider, const char *usdt_name,
11342 					  const struct bpf_usdt_opts *opts)
11343 {
11344 	char resolved_path[512];
11345 	struct bpf_object *obj = prog->obj;
11346 	struct bpf_link *link;
11347 	__u64 usdt_cookie;
11348 	int err;
11349 
11350 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
11351 		return libbpf_err_ptr(-EINVAL);
11352 
11353 	if (bpf_program__fd(prog) < 0) {
11354 		pr_warn("prog '%s': can't attach BPF program w/o FD (did you load it?)\n",
11355 			prog->name);
11356 		return libbpf_err_ptr(-EINVAL);
11357 	}
11358 
11359 	if (!binary_path)
11360 		return libbpf_err_ptr(-EINVAL);
11361 
11362 	if (!strchr(binary_path, '/')) {
11363 		err = resolve_full_path(binary_path, resolved_path, sizeof(resolved_path));
11364 		if (err) {
11365 			pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
11366 				prog->name, binary_path, err);
11367 			return libbpf_err_ptr(err);
11368 		}
11369 		binary_path = resolved_path;
11370 	}
11371 
11372 	/* USDT manager is instantiated lazily on first USDT attach. It will
11373 	 * be destroyed together with BPF object in bpf_object__close().
11374 	 */
11375 	if (IS_ERR(obj->usdt_man))
11376 		return libbpf_ptr(obj->usdt_man);
11377 	if (!obj->usdt_man) {
11378 		obj->usdt_man = usdt_manager_new(obj);
11379 		if (IS_ERR(obj->usdt_man))
11380 			return libbpf_ptr(obj->usdt_man);
11381 	}
11382 
11383 	usdt_cookie = OPTS_GET(opts, usdt_cookie, 0);
11384 	link = usdt_manager_attach_usdt(obj->usdt_man, prog, pid, binary_path,
11385 					usdt_provider, usdt_name, usdt_cookie);
11386 	err = libbpf_get_error(link);
11387 	if (err)
11388 		return libbpf_err_ptr(err);
11389 	return link;
11390 }
11391 
11392 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11393 {
11394 	char *path = NULL, *provider = NULL, *name = NULL;
11395 	const char *sec_name;
11396 	int n, err;
11397 
11398 	sec_name = bpf_program__section_name(prog);
11399 	if (strcmp(sec_name, "usdt") == 0) {
11400 		/* no auto-attach for just SEC("usdt") */
11401 		*link = NULL;
11402 		return 0;
11403 	}
11404 
11405 	n = sscanf(sec_name, "usdt/%m[^:]:%m[^:]:%m[^:]", &path, &provider, &name);
11406 	if (n != 3) {
11407 		pr_warn("invalid section '%s', expected SEC(\"usdt/<path>:<provider>:<name>\")\n",
11408 			sec_name);
11409 		err = -EINVAL;
11410 	} else {
11411 		*link = bpf_program__attach_usdt(prog, -1 /* any process */, path,
11412 						 provider, name, NULL);
11413 		err = libbpf_get_error(*link);
11414 	}
11415 	free(path);
11416 	free(provider);
11417 	free(name);
11418 	return err;
11419 }
11420 
11421 static int determine_tracepoint_id(const char *tp_category,
11422 				   const char *tp_name)
11423 {
11424 	char file[PATH_MAX];
11425 	int ret;
11426 
11427 	ret = snprintf(file, sizeof(file), "%s/events/%s/%s/id",
11428 		       tracefs_path(), tp_category, tp_name);
11429 	if (ret < 0)
11430 		return -errno;
11431 	if (ret >= sizeof(file)) {
11432 		pr_debug("tracepoint %s/%s path is too long\n",
11433 			 tp_category, tp_name);
11434 		return -E2BIG;
11435 	}
11436 	return parse_uint_from_file(file, "%d\n");
11437 }
11438 
11439 static int perf_event_open_tracepoint(const char *tp_category,
11440 				      const char *tp_name)
11441 {
11442 	const size_t attr_sz = sizeof(struct perf_event_attr);
11443 	struct perf_event_attr attr;
11444 	char errmsg[STRERR_BUFSIZE];
11445 	int tp_id, pfd, err;
11446 
11447 	tp_id = determine_tracepoint_id(tp_category, tp_name);
11448 	if (tp_id < 0) {
11449 		pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
11450 			tp_category, tp_name,
11451 			libbpf_strerror_r(tp_id, errmsg, sizeof(errmsg)));
11452 		return tp_id;
11453 	}
11454 
11455 	memset(&attr, 0, attr_sz);
11456 	attr.type = PERF_TYPE_TRACEPOINT;
11457 	attr.size = attr_sz;
11458 	attr.config = tp_id;
11459 
11460 	pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
11461 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
11462 	if (pfd < 0) {
11463 		err = -errno;
11464 		pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
11465 			tp_category, tp_name,
11466 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11467 		return err;
11468 	}
11469 	return pfd;
11470 }
11471 
11472 struct bpf_link *bpf_program__attach_tracepoint_opts(const struct bpf_program *prog,
11473 						     const char *tp_category,
11474 						     const char *tp_name,
11475 						     const struct bpf_tracepoint_opts *opts)
11476 {
11477 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
11478 	char errmsg[STRERR_BUFSIZE];
11479 	struct bpf_link *link;
11480 	int pfd, err;
11481 
11482 	if (!OPTS_VALID(opts, bpf_tracepoint_opts))
11483 		return libbpf_err_ptr(-EINVAL);
11484 
11485 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11486 
11487 	pfd = perf_event_open_tracepoint(tp_category, tp_name);
11488 	if (pfd < 0) {
11489 		pr_warn("prog '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
11490 			prog->name, tp_category, tp_name,
11491 			libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
11492 		return libbpf_err_ptr(pfd);
11493 	}
11494 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
11495 	err = libbpf_get_error(link);
11496 	if (err) {
11497 		close(pfd);
11498 		pr_warn("prog '%s': failed to attach to tracepoint '%s/%s': %s\n",
11499 			prog->name, tp_category, tp_name,
11500 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11501 		return libbpf_err_ptr(err);
11502 	}
11503 	return link;
11504 }
11505 
11506 struct bpf_link *bpf_program__attach_tracepoint(const struct bpf_program *prog,
11507 						const char *tp_category,
11508 						const char *tp_name)
11509 {
11510 	return bpf_program__attach_tracepoint_opts(prog, tp_category, tp_name, NULL);
11511 }
11512 
11513 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11514 {
11515 	char *sec_name, *tp_cat, *tp_name;
11516 
11517 	*link = NULL;
11518 
11519 	/* no auto-attach for SEC("tp") or SEC("tracepoint") */
11520 	if (strcmp(prog->sec_name, "tp") == 0 || strcmp(prog->sec_name, "tracepoint") == 0)
11521 		return 0;
11522 
11523 	sec_name = strdup(prog->sec_name);
11524 	if (!sec_name)
11525 		return -ENOMEM;
11526 
11527 	/* extract "tp/<category>/<name>" or "tracepoint/<category>/<name>" */
11528 	if (str_has_pfx(prog->sec_name, "tp/"))
11529 		tp_cat = sec_name + sizeof("tp/") - 1;
11530 	else
11531 		tp_cat = sec_name + sizeof("tracepoint/") - 1;
11532 	tp_name = strchr(tp_cat, '/');
11533 	if (!tp_name) {
11534 		free(sec_name);
11535 		return -EINVAL;
11536 	}
11537 	*tp_name = '\0';
11538 	tp_name++;
11539 
11540 	*link = bpf_program__attach_tracepoint(prog, tp_cat, tp_name);
11541 	free(sec_name);
11542 	return libbpf_get_error(*link);
11543 }
11544 
11545 struct bpf_link *bpf_program__attach_raw_tracepoint(const struct bpf_program *prog,
11546 						    const char *tp_name)
11547 {
11548 	char errmsg[STRERR_BUFSIZE];
11549 	struct bpf_link *link;
11550 	int prog_fd, pfd;
11551 
11552 	prog_fd = bpf_program__fd(prog);
11553 	if (prog_fd < 0) {
11554 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
11555 		return libbpf_err_ptr(-EINVAL);
11556 	}
11557 
11558 	link = calloc(1, sizeof(*link));
11559 	if (!link)
11560 		return libbpf_err_ptr(-ENOMEM);
11561 	link->detach = &bpf_link__detach_fd;
11562 
11563 	pfd = bpf_raw_tracepoint_open(tp_name, prog_fd);
11564 	if (pfd < 0) {
11565 		pfd = -errno;
11566 		free(link);
11567 		pr_warn("prog '%s': failed to attach to raw tracepoint '%s': %s\n",
11568 			prog->name, tp_name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
11569 		return libbpf_err_ptr(pfd);
11570 	}
11571 	link->fd = pfd;
11572 	return link;
11573 }
11574 
11575 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11576 {
11577 	static const char *const prefixes[] = {
11578 		"raw_tp",
11579 		"raw_tracepoint",
11580 		"raw_tp.w",
11581 		"raw_tracepoint.w",
11582 	};
11583 	size_t i;
11584 	const char *tp_name = NULL;
11585 
11586 	*link = NULL;
11587 
11588 	for (i = 0; i < ARRAY_SIZE(prefixes); i++) {
11589 		size_t pfx_len;
11590 
11591 		if (!str_has_pfx(prog->sec_name, prefixes[i]))
11592 			continue;
11593 
11594 		pfx_len = strlen(prefixes[i]);
11595 		/* no auto-attach case of, e.g., SEC("raw_tp") */
11596 		if (prog->sec_name[pfx_len] == '\0')
11597 			return 0;
11598 
11599 		if (prog->sec_name[pfx_len] != '/')
11600 			continue;
11601 
11602 		tp_name = prog->sec_name + pfx_len + 1;
11603 		break;
11604 	}
11605 
11606 	if (!tp_name) {
11607 		pr_warn("prog '%s': invalid section name '%s'\n",
11608 			prog->name, prog->sec_name);
11609 		return -EINVAL;
11610 	}
11611 
11612 	*link = bpf_program__attach_raw_tracepoint(prog, tp_name);
11613 	return libbpf_get_error(*link);
11614 }
11615 
11616 /* Common logic for all BPF program types that attach to a btf_id */
11617 static struct bpf_link *bpf_program__attach_btf_id(const struct bpf_program *prog,
11618 						   const struct bpf_trace_opts *opts)
11619 {
11620 	LIBBPF_OPTS(bpf_link_create_opts, link_opts);
11621 	char errmsg[STRERR_BUFSIZE];
11622 	struct bpf_link *link;
11623 	int prog_fd, pfd;
11624 
11625 	if (!OPTS_VALID(opts, bpf_trace_opts))
11626 		return libbpf_err_ptr(-EINVAL);
11627 
11628 	prog_fd = bpf_program__fd(prog);
11629 	if (prog_fd < 0) {
11630 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
11631 		return libbpf_err_ptr(-EINVAL);
11632 	}
11633 
11634 	link = calloc(1, sizeof(*link));
11635 	if (!link)
11636 		return libbpf_err_ptr(-ENOMEM);
11637 	link->detach = &bpf_link__detach_fd;
11638 
11639 	/* libbpf is smart enough to redirect to BPF_RAW_TRACEPOINT_OPEN on old kernels */
11640 	link_opts.tracing.cookie = OPTS_GET(opts, cookie, 0);
11641 	pfd = bpf_link_create(prog_fd, 0, bpf_program__expected_attach_type(prog), &link_opts);
11642 	if (pfd < 0) {
11643 		pfd = -errno;
11644 		free(link);
11645 		pr_warn("prog '%s': failed to attach: %s\n",
11646 			prog->name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
11647 		return libbpf_err_ptr(pfd);
11648 	}
11649 	link->fd = pfd;
11650 	return link;
11651 }
11652 
11653 struct bpf_link *bpf_program__attach_trace(const struct bpf_program *prog)
11654 {
11655 	return bpf_program__attach_btf_id(prog, NULL);
11656 }
11657 
11658 struct bpf_link *bpf_program__attach_trace_opts(const struct bpf_program *prog,
11659 						const struct bpf_trace_opts *opts)
11660 {
11661 	return bpf_program__attach_btf_id(prog, opts);
11662 }
11663 
11664 struct bpf_link *bpf_program__attach_lsm(const struct bpf_program *prog)
11665 {
11666 	return bpf_program__attach_btf_id(prog, NULL);
11667 }
11668 
11669 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11670 {
11671 	*link = bpf_program__attach_trace(prog);
11672 	return libbpf_get_error(*link);
11673 }
11674 
11675 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11676 {
11677 	*link = bpf_program__attach_lsm(prog);
11678 	return libbpf_get_error(*link);
11679 }
11680 
11681 static struct bpf_link *
11682 bpf_program__attach_fd(const struct bpf_program *prog, int target_fd, int btf_id,
11683 		       const char *target_name)
11684 {
11685 	DECLARE_LIBBPF_OPTS(bpf_link_create_opts, opts,
11686 			    .target_btf_id = btf_id);
11687 	enum bpf_attach_type attach_type;
11688 	char errmsg[STRERR_BUFSIZE];
11689 	struct bpf_link *link;
11690 	int prog_fd, link_fd;
11691 
11692 	prog_fd = bpf_program__fd(prog);
11693 	if (prog_fd < 0) {
11694 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
11695 		return libbpf_err_ptr(-EINVAL);
11696 	}
11697 
11698 	link = calloc(1, sizeof(*link));
11699 	if (!link)
11700 		return libbpf_err_ptr(-ENOMEM);
11701 	link->detach = &bpf_link__detach_fd;
11702 
11703 	attach_type = bpf_program__expected_attach_type(prog);
11704 	link_fd = bpf_link_create(prog_fd, target_fd, attach_type, &opts);
11705 	if (link_fd < 0) {
11706 		link_fd = -errno;
11707 		free(link);
11708 		pr_warn("prog '%s': failed to attach to %s: %s\n",
11709 			prog->name, target_name,
11710 			libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
11711 		return libbpf_err_ptr(link_fd);
11712 	}
11713 	link->fd = link_fd;
11714 	return link;
11715 }
11716 
11717 struct bpf_link *
11718 bpf_program__attach_cgroup(const struct bpf_program *prog, int cgroup_fd)
11719 {
11720 	return bpf_program__attach_fd(prog, cgroup_fd, 0, "cgroup");
11721 }
11722 
11723 struct bpf_link *
11724 bpf_program__attach_netns(const struct bpf_program *prog, int netns_fd)
11725 {
11726 	return bpf_program__attach_fd(prog, netns_fd, 0, "netns");
11727 }
11728 
11729 struct bpf_link *bpf_program__attach_xdp(const struct bpf_program *prog, int ifindex)
11730 {
11731 	/* target_fd/target_ifindex use the same field in LINK_CREATE */
11732 	return bpf_program__attach_fd(prog, ifindex, 0, "xdp");
11733 }
11734 
11735 struct bpf_link *bpf_program__attach_freplace(const struct bpf_program *prog,
11736 					      int target_fd,
11737 					      const char *attach_func_name)
11738 {
11739 	int btf_id;
11740 
11741 	if (!!target_fd != !!attach_func_name) {
11742 		pr_warn("prog '%s': supply none or both of target_fd and attach_func_name\n",
11743 			prog->name);
11744 		return libbpf_err_ptr(-EINVAL);
11745 	}
11746 
11747 	if (prog->type != BPF_PROG_TYPE_EXT) {
11748 		pr_warn("prog '%s': only BPF_PROG_TYPE_EXT can attach as freplace",
11749 			prog->name);
11750 		return libbpf_err_ptr(-EINVAL);
11751 	}
11752 
11753 	if (target_fd) {
11754 		btf_id = libbpf_find_prog_btf_id(attach_func_name, target_fd);
11755 		if (btf_id < 0)
11756 			return libbpf_err_ptr(btf_id);
11757 
11758 		return bpf_program__attach_fd(prog, target_fd, btf_id, "freplace");
11759 	} else {
11760 		/* no target, so use raw_tracepoint_open for compatibility
11761 		 * with old kernels
11762 		 */
11763 		return bpf_program__attach_trace(prog);
11764 	}
11765 }
11766 
11767 struct bpf_link *
11768 bpf_program__attach_iter(const struct bpf_program *prog,
11769 			 const struct bpf_iter_attach_opts *opts)
11770 {
11771 	DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
11772 	char errmsg[STRERR_BUFSIZE];
11773 	struct bpf_link *link;
11774 	int prog_fd, link_fd;
11775 	__u32 target_fd = 0;
11776 
11777 	if (!OPTS_VALID(opts, bpf_iter_attach_opts))
11778 		return libbpf_err_ptr(-EINVAL);
11779 
11780 	link_create_opts.iter_info = OPTS_GET(opts, link_info, (void *)0);
11781 	link_create_opts.iter_info_len = OPTS_GET(opts, link_info_len, 0);
11782 
11783 	prog_fd = bpf_program__fd(prog);
11784 	if (prog_fd < 0) {
11785 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
11786 		return libbpf_err_ptr(-EINVAL);
11787 	}
11788 
11789 	link = calloc(1, sizeof(*link));
11790 	if (!link)
11791 		return libbpf_err_ptr(-ENOMEM);
11792 	link->detach = &bpf_link__detach_fd;
11793 
11794 	link_fd = bpf_link_create(prog_fd, target_fd, BPF_TRACE_ITER,
11795 				  &link_create_opts);
11796 	if (link_fd < 0) {
11797 		link_fd = -errno;
11798 		free(link);
11799 		pr_warn("prog '%s': failed to attach to iterator: %s\n",
11800 			prog->name, libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
11801 		return libbpf_err_ptr(link_fd);
11802 	}
11803 	link->fd = link_fd;
11804 	return link;
11805 }
11806 
11807 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11808 {
11809 	*link = bpf_program__attach_iter(prog, NULL);
11810 	return libbpf_get_error(*link);
11811 }
11812 
11813 struct bpf_link *bpf_program__attach(const struct bpf_program *prog)
11814 {
11815 	struct bpf_link *link = NULL;
11816 	int err;
11817 
11818 	if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
11819 		return libbpf_err_ptr(-EOPNOTSUPP);
11820 
11821 	err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, &link);
11822 	if (err)
11823 		return libbpf_err_ptr(err);
11824 
11825 	/* When calling bpf_program__attach() explicitly, auto-attach support
11826 	 * is expected to work, so NULL returned link is considered an error.
11827 	 * This is different for skeleton's attach, see comment in
11828 	 * bpf_object__attach_skeleton().
11829 	 */
11830 	if (!link)
11831 		return libbpf_err_ptr(-EOPNOTSUPP);
11832 
11833 	return link;
11834 }
11835 
11836 struct bpf_link_struct_ops {
11837 	struct bpf_link link;
11838 	int map_fd;
11839 };
11840 
11841 static int bpf_link__detach_struct_ops(struct bpf_link *link)
11842 {
11843 	struct bpf_link_struct_ops *st_link;
11844 	__u32 zero = 0;
11845 
11846 	st_link = container_of(link, struct bpf_link_struct_ops, link);
11847 
11848 	if (st_link->map_fd < 0)
11849 		/* w/o a real link */
11850 		return bpf_map_delete_elem(link->fd, &zero);
11851 
11852 	return close(link->fd);
11853 }
11854 
11855 struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map)
11856 {
11857 	struct bpf_link_struct_ops *link;
11858 	__u32 zero = 0;
11859 	int err, fd;
11860 
11861 	if (!bpf_map__is_struct_ops(map) || map->fd == -1)
11862 		return libbpf_err_ptr(-EINVAL);
11863 
11864 	link = calloc(1, sizeof(*link));
11865 	if (!link)
11866 		return libbpf_err_ptr(-EINVAL);
11867 
11868 	/* kern_vdata should be prepared during the loading phase. */
11869 	err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
11870 	/* It can be EBUSY if the map has been used to create or
11871 	 * update a link before.  We don't allow updating the value of
11872 	 * a struct_ops once it is set.  That ensures that the value
11873 	 * never changed.  So, it is safe to skip EBUSY.
11874 	 */
11875 	if (err && (!(map->def.map_flags & BPF_F_LINK) || err != -EBUSY)) {
11876 		free(link);
11877 		return libbpf_err_ptr(err);
11878 	}
11879 
11880 	link->link.detach = bpf_link__detach_struct_ops;
11881 
11882 	if (!(map->def.map_flags & BPF_F_LINK)) {
11883 		/* w/o a real link */
11884 		link->link.fd = map->fd;
11885 		link->map_fd = -1;
11886 		return &link->link;
11887 	}
11888 
11889 	fd = bpf_link_create(map->fd, 0, BPF_STRUCT_OPS, NULL);
11890 	if (fd < 0) {
11891 		free(link);
11892 		return libbpf_err_ptr(fd);
11893 	}
11894 
11895 	link->link.fd = fd;
11896 	link->map_fd = map->fd;
11897 
11898 	return &link->link;
11899 }
11900 
11901 /*
11902  * Swap the back struct_ops of a link with a new struct_ops map.
11903  */
11904 int bpf_link__update_map(struct bpf_link *link, const struct bpf_map *map)
11905 {
11906 	struct bpf_link_struct_ops *st_ops_link;
11907 	__u32 zero = 0;
11908 	int err;
11909 
11910 	if (!bpf_map__is_struct_ops(map) || map->fd < 0)
11911 		return -EINVAL;
11912 
11913 	st_ops_link = container_of(link, struct bpf_link_struct_ops, link);
11914 	/* Ensure the type of a link is correct */
11915 	if (st_ops_link->map_fd < 0)
11916 		return -EINVAL;
11917 
11918 	err = bpf_map_update_elem(map->fd, &zero, map->st_ops->kern_vdata, 0);
11919 	/* It can be EBUSY if the map has been used to create or
11920 	 * update a link before.  We don't allow updating the value of
11921 	 * a struct_ops once it is set.  That ensures that the value
11922 	 * never changed.  So, it is safe to skip EBUSY.
11923 	 */
11924 	if (err && err != -EBUSY)
11925 		return err;
11926 
11927 	err = bpf_link_update(link->fd, map->fd, NULL);
11928 	if (err < 0)
11929 		return err;
11930 
11931 	st_ops_link->map_fd = map->fd;
11932 
11933 	return 0;
11934 }
11935 
11936 typedef enum bpf_perf_event_ret (*bpf_perf_event_print_t)(struct perf_event_header *hdr,
11937 							  void *private_data);
11938 
11939 static enum bpf_perf_event_ret
11940 perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
11941 		       void **copy_mem, size_t *copy_size,
11942 		       bpf_perf_event_print_t fn, void *private_data)
11943 {
11944 	struct perf_event_mmap_page *header = mmap_mem;
11945 	__u64 data_head = ring_buffer_read_head(header);
11946 	__u64 data_tail = header->data_tail;
11947 	void *base = ((__u8 *)header) + page_size;
11948 	int ret = LIBBPF_PERF_EVENT_CONT;
11949 	struct perf_event_header *ehdr;
11950 	size_t ehdr_size;
11951 
11952 	while (data_head != data_tail) {
11953 		ehdr = base + (data_tail & (mmap_size - 1));
11954 		ehdr_size = ehdr->size;
11955 
11956 		if (((void *)ehdr) + ehdr_size > base + mmap_size) {
11957 			void *copy_start = ehdr;
11958 			size_t len_first = base + mmap_size - copy_start;
11959 			size_t len_secnd = ehdr_size - len_first;
11960 
11961 			if (*copy_size < ehdr_size) {
11962 				free(*copy_mem);
11963 				*copy_mem = malloc(ehdr_size);
11964 				if (!*copy_mem) {
11965 					*copy_size = 0;
11966 					ret = LIBBPF_PERF_EVENT_ERROR;
11967 					break;
11968 				}
11969 				*copy_size = ehdr_size;
11970 			}
11971 
11972 			memcpy(*copy_mem, copy_start, len_first);
11973 			memcpy(*copy_mem + len_first, base, len_secnd);
11974 			ehdr = *copy_mem;
11975 		}
11976 
11977 		ret = fn(ehdr, private_data);
11978 		data_tail += ehdr_size;
11979 		if (ret != LIBBPF_PERF_EVENT_CONT)
11980 			break;
11981 	}
11982 
11983 	ring_buffer_write_tail(header, data_tail);
11984 	return libbpf_err(ret);
11985 }
11986 
11987 struct perf_buffer;
11988 
11989 struct perf_buffer_params {
11990 	struct perf_event_attr *attr;
11991 	/* if event_cb is specified, it takes precendence */
11992 	perf_buffer_event_fn event_cb;
11993 	/* sample_cb and lost_cb are higher-level common-case callbacks */
11994 	perf_buffer_sample_fn sample_cb;
11995 	perf_buffer_lost_fn lost_cb;
11996 	void *ctx;
11997 	int cpu_cnt;
11998 	int *cpus;
11999 	int *map_keys;
12000 };
12001 
12002 struct perf_cpu_buf {
12003 	struct perf_buffer *pb;
12004 	void *base; /* mmap()'ed memory */
12005 	void *buf; /* for reconstructing segmented data */
12006 	size_t buf_size;
12007 	int fd;
12008 	int cpu;
12009 	int map_key;
12010 };
12011 
12012 struct perf_buffer {
12013 	perf_buffer_event_fn event_cb;
12014 	perf_buffer_sample_fn sample_cb;
12015 	perf_buffer_lost_fn lost_cb;
12016 	void *ctx; /* passed into callbacks */
12017 
12018 	size_t page_size;
12019 	size_t mmap_size;
12020 	struct perf_cpu_buf **cpu_bufs;
12021 	struct epoll_event *events;
12022 	int cpu_cnt; /* number of allocated CPU buffers */
12023 	int epoll_fd; /* perf event FD */
12024 	int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
12025 };
12026 
12027 static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
12028 				      struct perf_cpu_buf *cpu_buf)
12029 {
12030 	if (!cpu_buf)
12031 		return;
12032 	if (cpu_buf->base &&
12033 	    munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
12034 		pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
12035 	if (cpu_buf->fd >= 0) {
12036 		ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
12037 		close(cpu_buf->fd);
12038 	}
12039 	free(cpu_buf->buf);
12040 	free(cpu_buf);
12041 }
12042 
12043 void perf_buffer__free(struct perf_buffer *pb)
12044 {
12045 	int i;
12046 
12047 	if (IS_ERR_OR_NULL(pb))
12048 		return;
12049 	if (pb->cpu_bufs) {
12050 		for (i = 0; i < pb->cpu_cnt; i++) {
12051 			struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
12052 
12053 			if (!cpu_buf)
12054 				continue;
12055 
12056 			bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
12057 			perf_buffer__free_cpu_buf(pb, cpu_buf);
12058 		}
12059 		free(pb->cpu_bufs);
12060 	}
12061 	if (pb->epoll_fd >= 0)
12062 		close(pb->epoll_fd);
12063 	free(pb->events);
12064 	free(pb);
12065 }
12066 
12067 static struct perf_cpu_buf *
12068 perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
12069 			  int cpu, int map_key)
12070 {
12071 	struct perf_cpu_buf *cpu_buf;
12072 	char msg[STRERR_BUFSIZE];
12073 	int err;
12074 
12075 	cpu_buf = calloc(1, sizeof(*cpu_buf));
12076 	if (!cpu_buf)
12077 		return ERR_PTR(-ENOMEM);
12078 
12079 	cpu_buf->pb = pb;
12080 	cpu_buf->cpu = cpu;
12081 	cpu_buf->map_key = map_key;
12082 
12083 	cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
12084 			      -1, PERF_FLAG_FD_CLOEXEC);
12085 	if (cpu_buf->fd < 0) {
12086 		err = -errno;
12087 		pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
12088 			cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
12089 		goto error;
12090 	}
12091 
12092 	cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
12093 			     PROT_READ | PROT_WRITE, MAP_SHARED,
12094 			     cpu_buf->fd, 0);
12095 	if (cpu_buf->base == MAP_FAILED) {
12096 		cpu_buf->base = NULL;
12097 		err = -errno;
12098 		pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
12099 			cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
12100 		goto error;
12101 	}
12102 
12103 	if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
12104 		err = -errno;
12105 		pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
12106 			cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
12107 		goto error;
12108 	}
12109 
12110 	return cpu_buf;
12111 
12112 error:
12113 	perf_buffer__free_cpu_buf(pb, cpu_buf);
12114 	return (struct perf_cpu_buf *)ERR_PTR(err);
12115 }
12116 
12117 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
12118 					      struct perf_buffer_params *p);
12119 
12120 struct perf_buffer *perf_buffer__new(int map_fd, size_t page_cnt,
12121 				     perf_buffer_sample_fn sample_cb,
12122 				     perf_buffer_lost_fn lost_cb,
12123 				     void *ctx,
12124 				     const struct perf_buffer_opts *opts)
12125 {
12126 	const size_t attr_sz = sizeof(struct perf_event_attr);
12127 	struct perf_buffer_params p = {};
12128 	struct perf_event_attr attr;
12129 	__u32 sample_period;
12130 
12131 	if (!OPTS_VALID(opts, perf_buffer_opts))
12132 		return libbpf_err_ptr(-EINVAL);
12133 
12134 	sample_period = OPTS_GET(opts, sample_period, 1);
12135 	if (!sample_period)
12136 		sample_period = 1;
12137 
12138 	memset(&attr, 0, attr_sz);
12139 	attr.size = attr_sz;
12140 	attr.config = PERF_COUNT_SW_BPF_OUTPUT;
12141 	attr.type = PERF_TYPE_SOFTWARE;
12142 	attr.sample_type = PERF_SAMPLE_RAW;
12143 	attr.sample_period = sample_period;
12144 	attr.wakeup_events = sample_period;
12145 
12146 	p.attr = &attr;
12147 	p.sample_cb = sample_cb;
12148 	p.lost_cb = lost_cb;
12149 	p.ctx = ctx;
12150 
12151 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
12152 }
12153 
12154 struct perf_buffer *perf_buffer__new_raw(int map_fd, size_t page_cnt,
12155 					 struct perf_event_attr *attr,
12156 					 perf_buffer_event_fn event_cb, void *ctx,
12157 					 const struct perf_buffer_raw_opts *opts)
12158 {
12159 	struct perf_buffer_params p = {};
12160 
12161 	if (!attr)
12162 		return libbpf_err_ptr(-EINVAL);
12163 
12164 	if (!OPTS_VALID(opts, perf_buffer_raw_opts))
12165 		return libbpf_err_ptr(-EINVAL);
12166 
12167 	p.attr = attr;
12168 	p.event_cb = event_cb;
12169 	p.ctx = ctx;
12170 	p.cpu_cnt = OPTS_GET(opts, cpu_cnt, 0);
12171 	p.cpus = OPTS_GET(opts, cpus, NULL);
12172 	p.map_keys = OPTS_GET(opts, map_keys, NULL);
12173 
12174 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
12175 }
12176 
12177 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
12178 					      struct perf_buffer_params *p)
12179 {
12180 	const char *online_cpus_file = "/sys/devices/system/cpu/online";
12181 	struct bpf_map_info map;
12182 	char msg[STRERR_BUFSIZE];
12183 	struct perf_buffer *pb;
12184 	bool *online = NULL;
12185 	__u32 map_info_len;
12186 	int err, i, j, n;
12187 
12188 	if (page_cnt == 0 || (page_cnt & (page_cnt - 1))) {
12189 		pr_warn("page count should be power of two, but is %zu\n",
12190 			page_cnt);
12191 		return ERR_PTR(-EINVAL);
12192 	}
12193 
12194 	/* best-effort sanity checks */
12195 	memset(&map, 0, sizeof(map));
12196 	map_info_len = sizeof(map);
12197 	err = bpf_map_get_info_by_fd(map_fd, &map, &map_info_len);
12198 	if (err) {
12199 		err = -errno;
12200 		/* if BPF_OBJ_GET_INFO_BY_FD is supported, will return
12201 		 * -EBADFD, -EFAULT, or -E2BIG on real error
12202 		 */
12203 		if (err != -EINVAL) {
12204 			pr_warn("failed to get map info for map FD %d: %s\n",
12205 				map_fd, libbpf_strerror_r(err, msg, sizeof(msg)));
12206 			return ERR_PTR(err);
12207 		}
12208 		pr_debug("failed to get map info for FD %d; API not supported? Ignoring...\n",
12209 			 map_fd);
12210 	} else {
12211 		if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
12212 			pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
12213 				map.name);
12214 			return ERR_PTR(-EINVAL);
12215 		}
12216 	}
12217 
12218 	pb = calloc(1, sizeof(*pb));
12219 	if (!pb)
12220 		return ERR_PTR(-ENOMEM);
12221 
12222 	pb->event_cb = p->event_cb;
12223 	pb->sample_cb = p->sample_cb;
12224 	pb->lost_cb = p->lost_cb;
12225 	pb->ctx = p->ctx;
12226 
12227 	pb->page_size = getpagesize();
12228 	pb->mmap_size = pb->page_size * page_cnt;
12229 	pb->map_fd = map_fd;
12230 
12231 	pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
12232 	if (pb->epoll_fd < 0) {
12233 		err = -errno;
12234 		pr_warn("failed to create epoll instance: %s\n",
12235 			libbpf_strerror_r(err, msg, sizeof(msg)));
12236 		goto error;
12237 	}
12238 
12239 	if (p->cpu_cnt > 0) {
12240 		pb->cpu_cnt = p->cpu_cnt;
12241 	} else {
12242 		pb->cpu_cnt = libbpf_num_possible_cpus();
12243 		if (pb->cpu_cnt < 0) {
12244 			err = pb->cpu_cnt;
12245 			goto error;
12246 		}
12247 		if (map.max_entries && map.max_entries < pb->cpu_cnt)
12248 			pb->cpu_cnt = map.max_entries;
12249 	}
12250 
12251 	pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
12252 	if (!pb->events) {
12253 		err = -ENOMEM;
12254 		pr_warn("failed to allocate events: out of memory\n");
12255 		goto error;
12256 	}
12257 	pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
12258 	if (!pb->cpu_bufs) {
12259 		err = -ENOMEM;
12260 		pr_warn("failed to allocate buffers: out of memory\n");
12261 		goto error;
12262 	}
12263 
12264 	err = parse_cpu_mask_file(online_cpus_file, &online, &n);
12265 	if (err) {
12266 		pr_warn("failed to get online CPU mask: %d\n", err);
12267 		goto error;
12268 	}
12269 
12270 	for (i = 0, j = 0; i < pb->cpu_cnt; i++) {
12271 		struct perf_cpu_buf *cpu_buf;
12272 		int cpu, map_key;
12273 
12274 		cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
12275 		map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
12276 
12277 		/* in case user didn't explicitly requested particular CPUs to
12278 		 * be attached to, skip offline/not present CPUs
12279 		 */
12280 		if (p->cpu_cnt <= 0 && (cpu >= n || !online[cpu]))
12281 			continue;
12282 
12283 		cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
12284 		if (IS_ERR(cpu_buf)) {
12285 			err = PTR_ERR(cpu_buf);
12286 			goto error;
12287 		}
12288 
12289 		pb->cpu_bufs[j] = cpu_buf;
12290 
12291 		err = bpf_map_update_elem(pb->map_fd, &map_key,
12292 					  &cpu_buf->fd, 0);
12293 		if (err) {
12294 			err = -errno;
12295 			pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
12296 				cpu, map_key, cpu_buf->fd,
12297 				libbpf_strerror_r(err, msg, sizeof(msg)));
12298 			goto error;
12299 		}
12300 
12301 		pb->events[j].events = EPOLLIN;
12302 		pb->events[j].data.ptr = cpu_buf;
12303 		if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
12304 			      &pb->events[j]) < 0) {
12305 			err = -errno;
12306 			pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
12307 				cpu, cpu_buf->fd,
12308 				libbpf_strerror_r(err, msg, sizeof(msg)));
12309 			goto error;
12310 		}
12311 		j++;
12312 	}
12313 	pb->cpu_cnt = j;
12314 	free(online);
12315 
12316 	return pb;
12317 
12318 error:
12319 	free(online);
12320 	if (pb)
12321 		perf_buffer__free(pb);
12322 	return ERR_PTR(err);
12323 }
12324 
12325 struct perf_sample_raw {
12326 	struct perf_event_header header;
12327 	uint32_t size;
12328 	char data[];
12329 };
12330 
12331 struct perf_sample_lost {
12332 	struct perf_event_header header;
12333 	uint64_t id;
12334 	uint64_t lost;
12335 	uint64_t sample_id;
12336 };
12337 
12338 static enum bpf_perf_event_ret
12339 perf_buffer__process_record(struct perf_event_header *e, void *ctx)
12340 {
12341 	struct perf_cpu_buf *cpu_buf = ctx;
12342 	struct perf_buffer *pb = cpu_buf->pb;
12343 	void *data = e;
12344 
12345 	/* user wants full control over parsing perf event */
12346 	if (pb->event_cb)
12347 		return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
12348 
12349 	switch (e->type) {
12350 	case PERF_RECORD_SAMPLE: {
12351 		struct perf_sample_raw *s = data;
12352 
12353 		if (pb->sample_cb)
12354 			pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
12355 		break;
12356 	}
12357 	case PERF_RECORD_LOST: {
12358 		struct perf_sample_lost *s = data;
12359 
12360 		if (pb->lost_cb)
12361 			pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
12362 		break;
12363 	}
12364 	default:
12365 		pr_warn("unknown perf sample type %d\n", e->type);
12366 		return LIBBPF_PERF_EVENT_ERROR;
12367 	}
12368 	return LIBBPF_PERF_EVENT_CONT;
12369 }
12370 
12371 static int perf_buffer__process_records(struct perf_buffer *pb,
12372 					struct perf_cpu_buf *cpu_buf)
12373 {
12374 	enum bpf_perf_event_ret ret;
12375 
12376 	ret = perf_event_read_simple(cpu_buf->base, pb->mmap_size,
12377 				     pb->page_size, &cpu_buf->buf,
12378 				     &cpu_buf->buf_size,
12379 				     perf_buffer__process_record, cpu_buf);
12380 	if (ret != LIBBPF_PERF_EVENT_CONT)
12381 		return ret;
12382 	return 0;
12383 }
12384 
12385 int perf_buffer__epoll_fd(const struct perf_buffer *pb)
12386 {
12387 	return pb->epoll_fd;
12388 }
12389 
12390 int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
12391 {
12392 	int i, cnt, err;
12393 
12394 	cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
12395 	if (cnt < 0)
12396 		return -errno;
12397 
12398 	for (i = 0; i < cnt; i++) {
12399 		struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
12400 
12401 		err = perf_buffer__process_records(pb, cpu_buf);
12402 		if (err) {
12403 			pr_warn("error while processing records: %d\n", err);
12404 			return libbpf_err(err);
12405 		}
12406 	}
12407 	return cnt;
12408 }
12409 
12410 /* Return number of PERF_EVENT_ARRAY map slots set up by this perf_buffer
12411  * manager.
12412  */
12413 size_t perf_buffer__buffer_cnt(const struct perf_buffer *pb)
12414 {
12415 	return pb->cpu_cnt;
12416 }
12417 
12418 /*
12419  * Return perf_event FD of a ring buffer in *buf_idx* slot of
12420  * PERF_EVENT_ARRAY BPF map. This FD can be polled for new data using
12421  * select()/poll()/epoll() Linux syscalls.
12422  */
12423 int perf_buffer__buffer_fd(const struct perf_buffer *pb, size_t buf_idx)
12424 {
12425 	struct perf_cpu_buf *cpu_buf;
12426 
12427 	if (buf_idx >= pb->cpu_cnt)
12428 		return libbpf_err(-EINVAL);
12429 
12430 	cpu_buf = pb->cpu_bufs[buf_idx];
12431 	if (!cpu_buf)
12432 		return libbpf_err(-ENOENT);
12433 
12434 	return cpu_buf->fd;
12435 }
12436 
12437 int perf_buffer__buffer(struct perf_buffer *pb, int buf_idx, void **buf, size_t *buf_size)
12438 {
12439 	struct perf_cpu_buf *cpu_buf;
12440 
12441 	if (buf_idx >= pb->cpu_cnt)
12442 		return libbpf_err(-EINVAL);
12443 
12444 	cpu_buf = pb->cpu_bufs[buf_idx];
12445 	if (!cpu_buf)
12446 		return libbpf_err(-ENOENT);
12447 
12448 	*buf = cpu_buf->base;
12449 	*buf_size = pb->mmap_size;
12450 	return 0;
12451 }
12452 
12453 /*
12454  * Consume data from perf ring buffer corresponding to slot *buf_idx* in
12455  * PERF_EVENT_ARRAY BPF map without waiting/polling. If there is no data to
12456  * consume, do nothing and return success.
12457  * Returns:
12458  *   - 0 on success;
12459  *   - <0 on failure.
12460  */
12461 int perf_buffer__consume_buffer(struct perf_buffer *pb, size_t buf_idx)
12462 {
12463 	struct perf_cpu_buf *cpu_buf;
12464 
12465 	if (buf_idx >= pb->cpu_cnt)
12466 		return libbpf_err(-EINVAL);
12467 
12468 	cpu_buf = pb->cpu_bufs[buf_idx];
12469 	if (!cpu_buf)
12470 		return libbpf_err(-ENOENT);
12471 
12472 	return perf_buffer__process_records(pb, cpu_buf);
12473 }
12474 
12475 int perf_buffer__consume(struct perf_buffer *pb)
12476 {
12477 	int i, err;
12478 
12479 	for (i = 0; i < pb->cpu_cnt; i++) {
12480 		struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
12481 
12482 		if (!cpu_buf)
12483 			continue;
12484 
12485 		err = perf_buffer__process_records(pb, cpu_buf);
12486 		if (err) {
12487 			pr_warn("perf_buffer: failed to process records in buffer #%d: %d\n", i, err);
12488 			return libbpf_err(err);
12489 		}
12490 	}
12491 	return 0;
12492 }
12493 
12494 int bpf_program__set_attach_target(struct bpf_program *prog,
12495 				   int attach_prog_fd,
12496 				   const char *attach_func_name)
12497 {
12498 	int btf_obj_fd = 0, btf_id = 0, err;
12499 
12500 	if (!prog || attach_prog_fd < 0)
12501 		return libbpf_err(-EINVAL);
12502 
12503 	if (prog->obj->loaded)
12504 		return libbpf_err(-EINVAL);
12505 
12506 	if (attach_prog_fd && !attach_func_name) {
12507 		/* remember attach_prog_fd and let bpf_program__load() find
12508 		 * BTF ID during the program load
12509 		 */
12510 		prog->attach_prog_fd = attach_prog_fd;
12511 		return 0;
12512 	}
12513 
12514 	if (attach_prog_fd) {
12515 		btf_id = libbpf_find_prog_btf_id(attach_func_name,
12516 						 attach_prog_fd);
12517 		if (btf_id < 0)
12518 			return libbpf_err(btf_id);
12519 	} else {
12520 		if (!attach_func_name)
12521 			return libbpf_err(-EINVAL);
12522 
12523 		/* load btf_vmlinux, if not yet */
12524 		err = bpf_object__load_vmlinux_btf(prog->obj, true);
12525 		if (err)
12526 			return libbpf_err(err);
12527 		err = find_kernel_btf_id(prog->obj, attach_func_name,
12528 					 prog->expected_attach_type,
12529 					 &btf_obj_fd, &btf_id);
12530 		if (err)
12531 			return libbpf_err(err);
12532 	}
12533 
12534 	prog->attach_btf_id = btf_id;
12535 	prog->attach_btf_obj_fd = btf_obj_fd;
12536 	prog->attach_prog_fd = attach_prog_fd;
12537 	return 0;
12538 }
12539 
12540 int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz)
12541 {
12542 	int err = 0, n, len, start, end = -1;
12543 	bool *tmp;
12544 
12545 	*mask = NULL;
12546 	*mask_sz = 0;
12547 
12548 	/* Each sub string separated by ',' has format \d+-\d+ or \d+ */
12549 	while (*s) {
12550 		if (*s == ',' || *s == '\n') {
12551 			s++;
12552 			continue;
12553 		}
12554 		n = sscanf(s, "%d%n-%d%n", &start, &len, &end, &len);
12555 		if (n <= 0 || n > 2) {
12556 			pr_warn("Failed to get CPU range %s: %d\n", s, n);
12557 			err = -EINVAL;
12558 			goto cleanup;
12559 		} else if (n == 1) {
12560 			end = start;
12561 		}
12562 		if (start < 0 || start > end) {
12563 			pr_warn("Invalid CPU range [%d,%d] in %s\n",
12564 				start, end, s);
12565 			err = -EINVAL;
12566 			goto cleanup;
12567 		}
12568 		tmp = realloc(*mask, end + 1);
12569 		if (!tmp) {
12570 			err = -ENOMEM;
12571 			goto cleanup;
12572 		}
12573 		*mask = tmp;
12574 		memset(tmp + *mask_sz, 0, start - *mask_sz);
12575 		memset(tmp + start, 1, end - start + 1);
12576 		*mask_sz = end + 1;
12577 		s += len;
12578 	}
12579 	if (!*mask_sz) {
12580 		pr_warn("Empty CPU range\n");
12581 		return -EINVAL;
12582 	}
12583 	return 0;
12584 cleanup:
12585 	free(*mask);
12586 	*mask = NULL;
12587 	return err;
12588 }
12589 
12590 int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz)
12591 {
12592 	int fd, err = 0, len;
12593 	char buf[128];
12594 
12595 	fd = open(fcpu, O_RDONLY | O_CLOEXEC);
12596 	if (fd < 0) {
12597 		err = -errno;
12598 		pr_warn("Failed to open cpu mask file %s: %d\n", fcpu, err);
12599 		return err;
12600 	}
12601 	len = read(fd, buf, sizeof(buf));
12602 	close(fd);
12603 	if (len <= 0) {
12604 		err = len ? -errno : -EINVAL;
12605 		pr_warn("Failed to read cpu mask from %s: %d\n", fcpu, err);
12606 		return err;
12607 	}
12608 	if (len >= sizeof(buf)) {
12609 		pr_warn("CPU mask is too big in file %s\n", fcpu);
12610 		return -E2BIG;
12611 	}
12612 	buf[len] = '\0';
12613 
12614 	return parse_cpu_mask_str(buf, mask, mask_sz);
12615 }
12616 
12617 int libbpf_num_possible_cpus(void)
12618 {
12619 	static const char *fcpu = "/sys/devices/system/cpu/possible";
12620 	static int cpus;
12621 	int err, n, i, tmp_cpus;
12622 	bool *mask;
12623 
12624 	tmp_cpus = READ_ONCE(cpus);
12625 	if (tmp_cpus > 0)
12626 		return tmp_cpus;
12627 
12628 	err = parse_cpu_mask_file(fcpu, &mask, &n);
12629 	if (err)
12630 		return libbpf_err(err);
12631 
12632 	tmp_cpus = 0;
12633 	for (i = 0; i < n; i++) {
12634 		if (mask[i])
12635 			tmp_cpus++;
12636 	}
12637 	free(mask);
12638 
12639 	WRITE_ONCE(cpus, tmp_cpus);
12640 	return tmp_cpus;
12641 }
12642 
12643 static int populate_skeleton_maps(const struct bpf_object *obj,
12644 				  struct bpf_map_skeleton *maps,
12645 				  size_t map_cnt)
12646 {
12647 	int i;
12648 
12649 	for (i = 0; i < map_cnt; i++) {
12650 		struct bpf_map **map = maps[i].map;
12651 		const char *name = maps[i].name;
12652 		void **mmaped = maps[i].mmaped;
12653 
12654 		*map = bpf_object__find_map_by_name(obj, name);
12655 		if (!*map) {
12656 			pr_warn("failed to find skeleton map '%s'\n", name);
12657 			return -ESRCH;
12658 		}
12659 
12660 		/* externs shouldn't be pre-setup from user code */
12661 		if (mmaped && (*map)->libbpf_type != LIBBPF_MAP_KCONFIG)
12662 			*mmaped = (*map)->mmaped;
12663 	}
12664 	return 0;
12665 }
12666 
12667 static int populate_skeleton_progs(const struct bpf_object *obj,
12668 				   struct bpf_prog_skeleton *progs,
12669 				   size_t prog_cnt)
12670 {
12671 	int i;
12672 
12673 	for (i = 0; i < prog_cnt; i++) {
12674 		struct bpf_program **prog = progs[i].prog;
12675 		const char *name = progs[i].name;
12676 
12677 		*prog = bpf_object__find_program_by_name(obj, name);
12678 		if (!*prog) {
12679 			pr_warn("failed to find skeleton program '%s'\n", name);
12680 			return -ESRCH;
12681 		}
12682 	}
12683 	return 0;
12684 }
12685 
12686 int bpf_object__open_skeleton(struct bpf_object_skeleton *s,
12687 			      const struct bpf_object_open_opts *opts)
12688 {
12689 	DECLARE_LIBBPF_OPTS(bpf_object_open_opts, skel_opts,
12690 		.object_name = s->name,
12691 	);
12692 	struct bpf_object *obj;
12693 	int err;
12694 
12695 	/* Attempt to preserve opts->object_name, unless overriden by user
12696 	 * explicitly. Overwriting object name for skeletons is discouraged,
12697 	 * as it breaks global data maps, because they contain object name
12698 	 * prefix as their own map name prefix. When skeleton is generated,
12699 	 * bpftool is making an assumption that this name will stay the same.
12700 	 */
12701 	if (opts) {
12702 		memcpy(&skel_opts, opts, sizeof(*opts));
12703 		if (!opts->object_name)
12704 			skel_opts.object_name = s->name;
12705 	}
12706 
12707 	obj = bpf_object__open_mem(s->data, s->data_sz, &skel_opts);
12708 	err = libbpf_get_error(obj);
12709 	if (err) {
12710 		pr_warn("failed to initialize skeleton BPF object '%s': %d\n",
12711 			s->name, err);
12712 		return libbpf_err(err);
12713 	}
12714 
12715 	*s->obj = obj;
12716 	err = populate_skeleton_maps(obj, s->maps, s->map_cnt);
12717 	if (err) {
12718 		pr_warn("failed to populate skeleton maps for '%s': %d\n", s->name, err);
12719 		return libbpf_err(err);
12720 	}
12721 
12722 	err = populate_skeleton_progs(obj, s->progs, s->prog_cnt);
12723 	if (err) {
12724 		pr_warn("failed to populate skeleton progs for '%s': %d\n", s->name, err);
12725 		return libbpf_err(err);
12726 	}
12727 
12728 	return 0;
12729 }
12730 
12731 int bpf_object__open_subskeleton(struct bpf_object_subskeleton *s)
12732 {
12733 	int err, len, var_idx, i;
12734 	const char *var_name;
12735 	const struct bpf_map *map;
12736 	struct btf *btf;
12737 	__u32 map_type_id;
12738 	const struct btf_type *map_type, *var_type;
12739 	const struct bpf_var_skeleton *var_skel;
12740 	struct btf_var_secinfo *var;
12741 
12742 	if (!s->obj)
12743 		return libbpf_err(-EINVAL);
12744 
12745 	btf = bpf_object__btf(s->obj);
12746 	if (!btf) {
12747 		pr_warn("subskeletons require BTF at runtime (object %s)\n",
12748 			bpf_object__name(s->obj));
12749 		return libbpf_err(-errno);
12750 	}
12751 
12752 	err = populate_skeleton_maps(s->obj, s->maps, s->map_cnt);
12753 	if (err) {
12754 		pr_warn("failed to populate subskeleton maps: %d\n", err);
12755 		return libbpf_err(err);
12756 	}
12757 
12758 	err = populate_skeleton_progs(s->obj, s->progs, s->prog_cnt);
12759 	if (err) {
12760 		pr_warn("failed to populate subskeleton maps: %d\n", err);
12761 		return libbpf_err(err);
12762 	}
12763 
12764 	for (var_idx = 0; var_idx < s->var_cnt; var_idx++) {
12765 		var_skel = &s->vars[var_idx];
12766 		map = *var_skel->map;
12767 		map_type_id = bpf_map__btf_value_type_id(map);
12768 		map_type = btf__type_by_id(btf, map_type_id);
12769 
12770 		if (!btf_is_datasec(map_type)) {
12771 			pr_warn("type for map '%1$s' is not a datasec: %2$s",
12772 				bpf_map__name(map),
12773 				__btf_kind_str(btf_kind(map_type)));
12774 			return libbpf_err(-EINVAL);
12775 		}
12776 
12777 		len = btf_vlen(map_type);
12778 		var = btf_var_secinfos(map_type);
12779 		for (i = 0; i < len; i++, var++) {
12780 			var_type = btf__type_by_id(btf, var->type);
12781 			var_name = btf__name_by_offset(btf, var_type->name_off);
12782 			if (strcmp(var_name, var_skel->name) == 0) {
12783 				*var_skel->addr = map->mmaped + var->offset;
12784 				break;
12785 			}
12786 		}
12787 	}
12788 	return 0;
12789 }
12790 
12791 void bpf_object__destroy_subskeleton(struct bpf_object_subskeleton *s)
12792 {
12793 	if (!s)
12794 		return;
12795 	free(s->maps);
12796 	free(s->progs);
12797 	free(s->vars);
12798 	free(s);
12799 }
12800 
12801 int bpf_object__load_skeleton(struct bpf_object_skeleton *s)
12802 {
12803 	int i, err;
12804 
12805 	err = bpf_object__load(*s->obj);
12806 	if (err) {
12807 		pr_warn("failed to load BPF skeleton '%s': %d\n", s->name, err);
12808 		return libbpf_err(err);
12809 	}
12810 
12811 	for (i = 0; i < s->map_cnt; i++) {
12812 		struct bpf_map *map = *s->maps[i].map;
12813 		size_t mmap_sz = bpf_map_mmap_sz(map->def.value_size, map->def.max_entries);
12814 		int prot, map_fd = bpf_map__fd(map);
12815 		void **mmaped = s->maps[i].mmaped;
12816 
12817 		if (!mmaped)
12818 			continue;
12819 
12820 		if (!(map->def.map_flags & BPF_F_MMAPABLE)) {
12821 			*mmaped = NULL;
12822 			continue;
12823 		}
12824 
12825 		if (map->def.map_flags & BPF_F_RDONLY_PROG)
12826 			prot = PROT_READ;
12827 		else
12828 			prot = PROT_READ | PROT_WRITE;
12829 
12830 		/* Remap anonymous mmap()-ed "map initialization image" as
12831 		 * a BPF map-backed mmap()-ed memory, but preserving the same
12832 		 * memory address. This will cause kernel to change process'
12833 		 * page table to point to a different piece of kernel memory,
12834 		 * but from userspace point of view memory address (and its
12835 		 * contents, being identical at this point) will stay the
12836 		 * same. This mapping will be released by bpf_object__close()
12837 		 * as per normal clean up procedure, so we don't need to worry
12838 		 * about it from skeleton's clean up perspective.
12839 		 */
12840 		*mmaped = mmap(map->mmaped, mmap_sz, prot, MAP_SHARED | MAP_FIXED, map_fd, 0);
12841 		if (*mmaped == MAP_FAILED) {
12842 			err = -errno;
12843 			*mmaped = NULL;
12844 			pr_warn("failed to re-mmap() map '%s': %d\n",
12845 				 bpf_map__name(map), err);
12846 			return libbpf_err(err);
12847 		}
12848 	}
12849 
12850 	return 0;
12851 }
12852 
12853 int bpf_object__attach_skeleton(struct bpf_object_skeleton *s)
12854 {
12855 	int i, err;
12856 
12857 	for (i = 0; i < s->prog_cnt; i++) {
12858 		struct bpf_program *prog = *s->progs[i].prog;
12859 		struct bpf_link **link = s->progs[i].link;
12860 
12861 		if (!prog->autoload || !prog->autoattach)
12862 			continue;
12863 
12864 		/* auto-attaching not supported for this program */
12865 		if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
12866 			continue;
12867 
12868 		/* if user already set the link manually, don't attempt auto-attach */
12869 		if (*link)
12870 			continue;
12871 
12872 		err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, link);
12873 		if (err) {
12874 			pr_warn("prog '%s': failed to auto-attach: %d\n",
12875 				bpf_program__name(prog), err);
12876 			return libbpf_err(err);
12877 		}
12878 
12879 		/* It's possible that for some SEC() definitions auto-attach
12880 		 * is supported in some cases (e.g., if definition completely
12881 		 * specifies target information), but is not in other cases.
12882 		 * SEC("uprobe") is one such case. If user specified target
12883 		 * binary and function name, such BPF program can be
12884 		 * auto-attached. But if not, it shouldn't trigger skeleton's
12885 		 * attach to fail. It should just be skipped.
12886 		 * attach_fn signals such case with returning 0 (no error) and
12887 		 * setting link to NULL.
12888 		 */
12889 	}
12890 
12891 	return 0;
12892 }
12893 
12894 void bpf_object__detach_skeleton(struct bpf_object_skeleton *s)
12895 {
12896 	int i;
12897 
12898 	for (i = 0; i < s->prog_cnt; i++) {
12899 		struct bpf_link **link = s->progs[i].link;
12900 
12901 		bpf_link__destroy(*link);
12902 		*link = NULL;
12903 	}
12904 }
12905 
12906 void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s)
12907 {
12908 	if (!s)
12909 		return;
12910 
12911 	if (s->progs)
12912 		bpf_object__detach_skeleton(s);
12913 	if (s->obj)
12914 		bpf_object__close(*s->obj);
12915 	free(s->maps);
12916 	free(s->progs);
12917 	free(s);
12918 }
12919