xref: /openbmc/linux/tools/lib/bpf/libbpf.c (revision 15b209cd)
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 <linux/version.h>
38 #include <sys/epoll.h>
39 #include <sys/ioctl.h>
40 #include <sys/mman.h>
41 #include <sys/stat.h>
42 #include <sys/types.h>
43 #include <sys/vfs.h>
44 #include <sys/utsname.h>
45 #include <sys/resource.h>
46 #include <libelf.h>
47 #include <gelf.h>
48 #include <zlib.h>
49 
50 #include "libbpf.h"
51 #include "bpf.h"
52 #include "btf.h"
53 #include "str_error.h"
54 #include "libbpf_internal.h"
55 #include "hashmap.h"
56 #include "bpf_gen_internal.h"
57 
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 };
120 
121 static const char * const link_type_name[] = {
122 	[BPF_LINK_TYPE_UNSPEC]			= "unspec",
123 	[BPF_LINK_TYPE_RAW_TRACEPOINT]		= "raw_tracepoint",
124 	[BPF_LINK_TYPE_TRACING]			= "tracing",
125 	[BPF_LINK_TYPE_CGROUP]			= "cgroup",
126 	[BPF_LINK_TYPE_ITER]			= "iter",
127 	[BPF_LINK_TYPE_NETNS]			= "netns",
128 	[BPF_LINK_TYPE_XDP]			= "xdp",
129 	[BPF_LINK_TYPE_PERF_EVENT]		= "perf_event",
130 	[BPF_LINK_TYPE_KPROBE_MULTI]		= "kprobe_multi",
131 	[BPF_LINK_TYPE_STRUCT_OPS]		= "struct_ops",
132 };
133 
134 static const char * const map_type_name[] = {
135 	[BPF_MAP_TYPE_UNSPEC]			= "unspec",
136 	[BPF_MAP_TYPE_HASH]			= "hash",
137 	[BPF_MAP_TYPE_ARRAY]			= "array",
138 	[BPF_MAP_TYPE_PROG_ARRAY]		= "prog_array",
139 	[BPF_MAP_TYPE_PERF_EVENT_ARRAY]		= "perf_event_array",
140 	[BPF_MAP_TYPE_PERCPU_HASH]		= "percpu_hash",
141 	[BPF_MAP_TYPE_PERCPU_ARRAY]		= "percpu_array",
142 	[BPF_MAP_TYPE_STACK_TRACE]		= "stack_trace",
143 	[BPF_MAP_TYPE_CGROUP_ARRAY]		= "cgroup_array",
144 	[BPF_MAP_TYPE_LRU_HASH]			= "lru_hash",
145 	[BPF_MAP_TYPE_LRU_PERCPU_HASH]		= "lru_percpu_hash",
146 	[BPF_MAP_TYPE_LPM_TRIE]			= "lpm_trie",
147 	[BPF_MAP_TYPE_ARRAY_OF_MAPS]		= "array_of_maps",
148 	[BPF_MAP_TYPE_HASH_OF_MAPS]		= "hash_of_maps",
149 	[BPF_MAP_TYPE_DEVMAP]			= "devmap",
150 	[BPF_MAP_TYPE_DEVMAP_HASH]		= "devmap_hash",
151 	[BPF_MAP_TYPE_SOCKMAP]			= "sockmap",
152 	[BPF_MAP_TYPE_CPUMAP]			= "cpumap",
153 	[BPF_MAP_TYPE_XSKMAP]			= "xskmap",
154 	[BPF_MAP_TYPE_SOCKHASH]			= "sockhash",
155 	[BPF_MAP_TYPE_CGROUP_STORAGE]		= "cgroup_storage",
156 	[BPF_MAP_TYPE_REUSEPORT_SOCKARRAY]	= "reuseport_sockarray",
157 	[BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE]	= "percpu_cgroup_storage",
158 	[BPF_MAP_TYPE_QUEUE]			= "queue",
159 	[BPF_MAP_TYPE_STACK]			= "stack",
160 	[BPF_MAP_TYPE_SK_STORAGE]		= "sk_storage",
161 	[BPF_MAP_TYPE_STRUCT_OPS]		= "struct_ops",
162 	[BPF_MAP_TYPE_RINGBUF]			= "ringbuf",
163 	[BPF_MAP_TYPE_INODE_STORAGE]		= "inode_storage",
164 	[BPF_MAP_TYPE_TASK_STORAGE]		= "task_storage",
165 	[BPF_MAP_TYPE_BLOOM_FILTER]		= "bloom_filter",
166 };
167 
168 static const char * const prog_type_name[] = {
169 	[BPF_PROG_TYPE_UNSPEC]			= "unspec",
170 	[BPF_PROG_TYPE_SOCKET_FILTER]		= "socket_filter",
171 	[BPF_PROG_TYPE_KPROBE]			= "kprobe",
172 	[BPF_PROG_TYPE_SCHED_CLS]		= "sched_cls",
173 	[BPF_PROG_TYPE_SCHED_ACT]		= "sched_act",
174 	[BPF_PROG_TYPE_TRACEPOINT]		= "tracepoint",
175 	[BPF_PROG_TYPE_XDP]			= "xdp",
176 	[BPF_PROG_TYPE_PERF_EVENT]		= "perf_event",
177 	[BPF_PROG_TYPE_CGROUP_SKB]		= "cgroup_skb",
178 	[BPF_PROG_TYPE_CGROUP_SOCK]		= "cgroup_sock",
179 	[BPF_PROG_TYPE_LWT_IN]			= "lwt_in",
180 	[BPF_PROG_TYPE_LWT_OUT]			= "lwt_out",
181 	[BPF_PROG_TYPE_LWT_XMIT]		= "lwt_xmit",
182 	[BPF_PROG_TYPE_SOCK_OPS]		= "sock_ops",
183 	[BPF_PROG_TYPE_SK_SKB]			= "sk_skb",
184 	[BPF_PROG_TYPE_CGROUP_DEVICE]		= "cgroup_device",
185 	[BPF_PROG_TYPE_SK_MSG]			= "sk_msg",
186 	[BPF_PROG_TYPE_RAW_TRACEPOINT]		= "raw_tracepoint",
187 	[BPF_PROG_TYPE_CGROUP_SOCK_ADDR]	= "cgroup_sock_addr",
188 	[BPF_PROG_TYPE_LWT_SEG6LOCAL]		= "lwt_seg6local",
189 	[BPF_PROG_TYPE_LIRC_MODE2]		= "lirc_mode2",
190 	[BPF_PROG_TYPE_SK_REUSEPORT]		= "sk_reuseport",
191 	[BPF_PROG_TYPE_FLOW_DISSECTOR]		= "flow_dissector",
192 	[BPF_PROG_TYPE_CGROUP_SYSCTL]		= "cgroup_sysctl",
193 	[BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE]	= "raw_tracepoint_writable",
194 	[BPF_PROG_TYPE_CGROUP_SOCKOPT]		= "cgroup_sockopt",
195 	[BPF_PROG_TYPE_TRACING]			= "tracing",
196 	[BPF_PROG_TYPE_STRUCT_OPS]		= "struct_ops",
197 	[BPF_PROG_TYPE_EXT]			= "ext",
198 	[BPF_PROG_TYPE_LSM]			= "lsm",
199 	[BPF_PROG_TYPE_SK_LOOKUP]		= "sk_lookup",
200 	[BPF_PROG_TYPE_SYSCALL]			= "syscall",
201 };
202 
203 static int __base_pr(enum libbpf_print_level level, const char *format,
204 		     va_list args)
205 {
206 	if (level == LIBBPF_DEBUG)
207 		return 0;
208 
209 	return vfprintf(stderr, format, args);
210 }
211 
212 static libbpf_print_fn_t __libbpf_pr = __base_pr;
213 
214 libbpf_print_fn_t libbpf_set_print(libbpf_print_fn_t fn)
215 {
216 	libbpf_print_fn_t old_print_fn = __libbpf_pr;
217 
218 	__libbpf_pr = fn;
219 	return old_print_fn;
220 }
221 
222 __printf(2, 3)
223 void libbpf_print(enum libbpf_print_level level, const char *format, ...)
224 {
225 	va_list args;
226 	int old_errno;
227 
228 	if (!__libbpf_pr)
229 		return;
230 
231 	old_errno = errno;
232 
233 	va_start(args, format);
234 	__libbpf_pr(level, format, args);
235 	va_end(args);
236 
237 	errno = old_errno;
238 }
239 
240 static void pr_perm_msg(int err)
241 {
242 	struct rlimit limit;
243 	char buf[100];
244 
245 	if (err != -EPERM || geteuid() != 0)
246 		return;
247 
248 	err = getrlimit(RLIMIT_MEMLOCK, &limit);
249 	if (err)
250 		return;
251 
252 	if (limit.rlim_cur == RLIM_INFINITY)
253 		return;
254 
255 	if (limit.rlim_cur < 1024)
256 		snprintf(buf, sizeof(buf), "%zu bytes", (size_t)limit.rlim_cur);
257 	else if (limit.rlim_cur < 1024*1024)
258 		snprintf(buf, sizeof(buf), "%.1f KiB", (double)limit.rlim_cur / 1024);
259 	else
260 		snprintf(buf, sizeof(buf), "%.1f MiB", (double)limit.rlim_cur / (1024*1024));
261 
262 	pr_warn("permission error while running as root; try raising 'ulimit -l'? current value: %s\n",
263 		buf);
264 }
265 
266 #define STRERR_BUFSIZE  128
267 
268 /* Copied from tools/perf/util/util.h */
269 #ifndef zfree
270 # define zfree(ptr) ({ free(*ptr); *ptr = NULL; })
271 #endif
272 
273 #ifndef zclose
274 # define zclose(fd) ({			\
275 	int ___err = 0;			\
276 	if ((fd) >= 0)			\
277 		___err = close((fd));	\
278 	fd = -1;			\
279 	___err; })
280 #endif
281 
282 static inline __u64 ptr_to_u64(const void *ptr)
283 {
284 	return (__u64) (unsigned long) ptr;
285 }
286 
287 int libbpf_set_strict_mode(enum libbpf_strict_mode mode)
288 {
289 	/* as of v1.0 libbpf_set_strict_mode() is a no-op */
290 	return 0;
291 }
292 
293 __u32 libbpf_major_version(void)
294 {
295 	return LIBBPF_MAJOR_VERSION;
296 }
297 
298 __u32 libbpf_minor_version(void)
299 {
300 	return LIBBPF_MINOR_VERSION;
301 }
302 
303 const char *libbpf_version_string(void)
304 {
305 #define __S(X) #X
306 #define _S(X) __S(X)
307 	return  "v" _S(LIBBPF_MAJOR_VERSION) "." _S(LIBBPF_MINOR_VERSION);
308 #undef _S
309 #undef __S
310 }
311 
312 enum reloc_type {
313 	RELO_LD64,
314 	RELO_CALL,
315 	RELO_DATA,
316 	RELO_EXTERN_VAR,
317 	RELO_EXTERN_FUNC,
318 	RELO_SUBPROG_ADDR,
319 	RELO_CORE,
320 };
321 
322 struct reloc_desc {
323 	enum reloc_type type;
324 	int insn_idx;
325 	union {
326 		const struct bpf_core_relo *core_relo; /* used when type == RELO_CORE */
327 		struct {
328 			int map_idx;
329 			int sym_off;
330 		};
331 	};
332 };
333 
334 /* stored as sec_def->cookie for all libbpf-supported SEC()s */
335 enum sec_def_flags {
336 	SEC_NONE = 0,
337 	/* expected_attach_type is optional, if kernel doesn't support that */
338 	SEC_EXP_ATTACH_OPT = 1,
339 	/* legacy, only used by libbpf_get_type_names() and
340 	 * libbpf_attach_type_by_name(), not used by libbpf itself at all.
341 	 * This used to be associated with cgroup (and few other) BPF programs
342 	 * that were attachable through BPF_PROG_ATTACH command. Pretty
343 	 * meaningless nowadays, though.
344 	 */
345 	SEC_ATTACHABLE = 2,
346 	SEC_ATTACHABLE_OPT = SEC_ATTACHABLE | SEC_EXP_ATTACH_OPT,
347 	/* attachment target is specified through BTF ID in either kernel or
348 	 * other BPF program's BTF object */
349 	SEC_ATTACH_BTF = 4,
350 	/* BPF program type allows sleeping/blocking in kernel */
351 	SEC_SLEEPABLE = 8,
352 	/* BPF program support non-linear XDP buffer */
353 	SEC_XDP_FRAGS = 16,
354 };
355 
356 struct bpf_sec_def {
357 	char *sec;
358 	enum bpf_prog_type prog_type;
359 	enum bpf_attach_type expected_attach_type;
360 	long cookie;
361 	int handler_id;
362 
363 	libbpf_prog_setup_fn_t prog_setup_fn;
364 	libbpf_prog_prepare_load_fn_t prog_prepare_load_fn;
365 	libbpf_prog_attach_fn_t prog_attach_fn;
366 };
367 
368 /*
369  * bpf_prog should be a better name but it has been used in
370  * linux/filter.h.
371  */
372 struct bpf_program {
373 	char *name;
374 	char *sec_name;
375 	size_t sec_idx;
376 	const struct bpf_sec_def *sec_def;
377 	/* this program's instruction offset (in number of instructions)
378 	 * within its containing ELF section
379 	 */
380 	size_t sec_insn_off;
381 	/* number of original instructions in ELF section belonging to this
382 	 * program, not taking into account subprogram instructions possible
383 	 * appended later during relocation
384 	 */
385 	size_t sec_insn_cnt;
386 	/* Offset (in number of instructions) of the start of instruction
387 	 * belonging to this BPF program  within its containing main BPF
388 	 * program. For the entry-point (main) BPF program, this is always
389 	 * zero. For a sub-program, this gets reset before each of main BPF
390 	 * programs are processed and relocated and is used to determined
391 	 * whether sub-program was already appended to the main program, and
392 	 * if yes, at which instruction offset.
393 	 */
394 	size_t sub_insn_off;
395 
396 	/* instructions that belong to BPF program; insns[0] is located at
397 	 * sec_insn_off instruction within its ELF section in ELF file, so
398 	 * when mapping ELF file instruction index to the local instruction,
399 	 * one needs to subtract sec_insn_off; and vice versa.
400 	 */
401 	struct bpf_insn *insns;
402 	/* actual number of instruction in this BPF program's image; for
403 	 * entry-point BPF programs this includes the size of main program
404 	 * itself plus all the used sub-programs, appended at the end
405 	 */
406 	size_t insns_cnt;
407 
408 	struct reloc_desc *reloc_desc;
409 	int nr_reloc;
410 
411 	/* BPF verifier log settings */
412 	char *log_buf;
413 	size_t log_size;
414 	__u32 log_level;
415 
416 	struct bpf_object *obj;
417 
418 	int fd;
419 	bool autoload;
420 	bool autoattach;
421 	bool mark_btf_static;
422 	enum bpf_prog_type type;
423 	enum bpf_attach_type expected_attach_type;
424 
425 	int prog_ifindex;
426 	__u32 attach_btf_obj_fd;
427 	__u32 attach_btf_id;
428 	__u32 attach_prog_fd;
429 
430 	void *func_info;
431 	__u32 func_info_rec_size;
432 	__u32 func_info_cnt;
433 
434 	void *line_info;
435 	__u32 line_info_rec_size;
436 	__u32 line_info_cnt;
437 	__u32 prog_flags;
438 };
439 
440 struct bpf_struct_ops {
441 	const char *tname;
442 	const struct btf_type *type;
443 	struct bpf_program **progs;
444 	__u32 *kern_func_off;
445 	/* e.g. struct tcp_congestion_ops in bpf_prog's btf format */
446 	void *data;
447 	/* e.g. struct bpf_struct_ops_tcp_congestion_ops in
448 	 *      btf_vmlinux's format.
449 	 * struct bpf_struct_ops_tcp_congestion_ops {
450 	 *	[... some other kernel fields ...]
451 	 *	struct tcp_congestion_ops data;
452 	 * }
453 	 * kern_vdata-size == sizeof(struct bpf_struct_ops_tcp_congestion_ops)
454 	 * bpf_map__init_kern_struct_ops() will populate the "kern_vdata"
455 	 * from "data".
456 	 */
457 	void *kern_vdata;
458 	__u32 type_id;
459 };
460 
461 #define DATA_SEC ".data"
462 #define BSS_SEC ".bss"
463 #define RODATA_SEC ".rodata"
464 #define KCONFIG_SEC ".kconfig"
465 #define KSYMS_SEC ".ksyms"
466 #define STRUCT_OPS_SEC ".struct_ops"
467 
468 enum libbpf_map_type {
469 	LIBBPF_MAP_UNSPEC,
470 	LIBBPF_MAP_DATA,
471 	LIBBPF_MAP_BSS,
472 	LIBBPF_MAP_RODATA,
473 	LIBBPF_MAP_KCONFIG,
474 };
475 
476 struct bpf_map_def {
477 	unsigned int type;
478 	unsigned int key_size;
479 	unsigned int value_size;
480 	unsigned int max_entries;
481 	unsigned int map_flags;
482 };
483 
484 struct bpf_map {
485 	struct bpf_object *obj;
486 	char *name;
487 	/* real_name is defined for special internal maps (.rodata*,
488 	 * .data*, .bss, .kconfig) and preserves their original ELF section
489 	 * name. This is important to be be able to find corresponding BTF
490 	 * DATASEC information.
491 	 */
492 	char *real_name;
493 	int fd;
494 	int sec_idx;
495 	size_t sec_offset;
496 	int map_ifindex;
497 	int inner_map_fd;
498 	struct bpf_map_def def;
499 	__u32 numa_node;
500 	__u32 btf_var_idx;
501 	__u32 btf_key_type_id;
502 	__u32 btf_value_type_id;
503 	__u32 btf_vmlinux_value_type_id;
504 	enum libbpf_map_type libbpf_type;
505 	void *mmaped;
506 	struct bpf_struct_ops *st_ops;
507 	struct bpf_map *inner_map;
508 	void **init_slots;
509 	int init_slots_sz;
510 	char *pin_path;
511 	bool pinned;
512 	bool reused;
513 	bool autocreate;
514 	__u64 map_extra;
515 };
516 
517 enum extern_type {
518 	EXT_UNKNOWN,
519 	EXT_KCFG,
520 	EXT_KSYM,
521 };
522 
523 enum kcfg_type {
524 	KCFG_UNKNOWN,
525 	KCFG_CHAR,
526 	KCFG_BOOL,
527 	KCFG_INT,
528 	KCFG_TRISTATE,
529 	KCFG_CHAR_ARR,
530 };
531 
532 struct extern_desc {
533 	enum extern_type type;
534 	int sym_idx;
535 	int btf_id;
536 	int sec_btf_id;
537 	const char *name;
538 	bool is_set;
539 	bool is_weak;
540 	union {
541 		struct {
542 			enum kcfg_type type;
543 			int sz;
544 			int align;
545 			int data_off;
546 			bool is_signed;
547 		} kcfg;
548 		struct {
549 			unsigned long long addr;
550 
551 			/* target btf_id of the corresponding kernel var. */
552 			int kernel_btf_obj_fd;
553 			int kernel_btf_id;
554 
555 			/* local btf_id of the ksym extern's type. */
556 			__u32 type_id;
557 			/* BTF fd index to be patched in for insn->off, this is
558 			 * 0 for vmlinux BTF, index in obj->fd_array for module
559 			 * BTF
560 			 */
561 			__s16 btf_fd_idx;
562 		} ksym;
563 	};
564 };
565 
566 struct module_btf {
567 	struct btf *btf;
568 	char *name;
569 	__u32 id;
570 	int fd;
571 	int fd_array_idx;
572 };
573 
574 enum sec_type {
575 	SEC_UNUSED = 0,
576 	SEC_RELO,
577 	SEC_BSS,
578 	SEC_DATA,
579 	SEC_RODATA,
580 };
581 
582 struct elf_sec_desc {
583 	enum sec_type sec_type;
584 	Elf64_Shdr *shdr;
585 	Elf_Data *data;
586 };
587 
588 struct elf_state {
589 	int fd;
590 	const void *obj_buf;
591 	size_t obj_buf_sz;
592 	Elf *elf;
593 	Elf64_Ehdr *ehdr;
594 	Elf_Data *symbols;
595 	Elf_Data *st_ops_data;
596 	size_t shstrndx; /* section index for section name strings */
597 	size_t strtabidx;
598 	struct elf_sec_desc *secs;
599 	int sec_cnt;
600 	int btf_maps_shndx;
601 	__u32 btf_maps_sec_btf_id;
602 	int text_shndx;
603 	int symbols_shndx;
604 	int st_ops_shndx;
605 };
606 
607 struct usdt_manager;
608 
609 struct bpf_object {
610 	char name[BPF_OBJ_NAME_LEN];
611 	char license[64];
612 	__u32 kern_version;
613 
614 	struct bpf_program *programs;
615 	size_t nr_programs;
616 	struct bpf_map *maps;
617 	size_t nr_maps;
618 	size_t maps_cap;
619 
620 	char *kconfig;
621 	struct extern_desc *externs;
622 	int nr_extern;
623 	int kconfig_map_idx;
624 
625 	bool loaded;
626 	bool has_subcalls;
627 	bool has_rodata;
628 
629 	struct bpf_gen *gen_loader;
630 
631 	/* Information when doing ELF related work. Only valid if efile.elf is not NULL */
632 	struct elf_state efile;
633 
634 	struct btf *btf;
635 	struct btf_ext *btf_ext;
636 
637 	/* Parse and load BTF vmlinux if any of the programs in the object need
638 	 * it at load time.
639 	 */
640 	struct btf *btf_vmlinux;
641 	/* Path to the custom BTF to be used for BPF CO-RE relocations as an
642 	 * override for vmlinux BTF.
643 	 */
644 	char *btf_custom_path;
645 	/* vmlinux BTF override for CO-RE relocations */
646 	struct btf *btf_vmlinux_override;
647 	/* Lazily initialized kernel module BTFs */
648 	struct module_btf *btf_modules;
649 	bool btf_modules_loaded;
650 	size_t btf_module_cnt;
651 	size_t btf_module_cap;
652 
653 	/* optional log settings passed to BPF_BTF_LOAD and BPF_PROG_LOAD commands */
654 	char *log_buf;
655 	size_t log_size;
656 	__u32 log_level;
657 
658 	int *fd_array;
659 	size_t fd_array_cap;
660 	size_t fd_array_cnt;
661 
662 	struct usdt_manager *usdt_man;
663 
664 	char path[];
665 };
666 
667 static const char *elf_sym_str(const struct bpf_object *obj, size_t off);
668 static const char *elf_sec_str(const struct bpf_object *obj, size_t off);
669 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx);
670 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name);
671 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn);
672 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn);
673 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn);
674 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx);
675 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx);
676 
677 void bpf_program__unload(struct bpf_program *prog)
678 {
679 	if (!prog)
680 		return;
681 
682 	zclose(prog->fd);
683 
684 	zfree(&prog->func_info);
685 	zfree(&prog->line_info);
686 }
687 
688 static void bpf_program__exit(struct bpf_program *prog)
689 {
690 	if (!prog)
691 		return;
692 
693 	bpf_program__unload(prog);
694 	zfree(&prog->name);
695 	zfree(&prog->sec_name);
696 	zfree(&prog->insns);
697 	zfree(&prog->reloc_desc);
698 
699 	prog->nr_reloc = 0;
700 	prog->insns_cnt = 0;
701 	prog->sec_idx = -1;
702 }
703 
704 static bool insn_is_subprog_call(const struct bpf_insn *insn)
705 {
706 	return BPF_CLASS(insn->code) == BPF_JMP &&
707 	       BPF_OP(insn->code) == BPF_CALL &&
708 	       BPF_SRC(insn->code) == BPF_K &&
709 	       insn->src_reg == BPF_PSEUDO_CALL &&
710 	       insn->dst_reg == 0 &&
711 	       insn->off == 0;
712 }
713 
714 static bool is_call_insn(const struct bpf_insn *insn)
715 {
716 	return insn->code == (BPF_JMP | BPF_CALL);
717 }
718 
719 static bool insn_is_pseudo_func(struct bpf_insn *insn)
720 {
721 	return is_ldimm64_insn(insn) && insn->src_reg == BPF_PSEUDO_FUNC;
722 }
723 
724 static int
725 bpf_object__init_prog(struct bpf_object *obj, struct bpf_program *prog,
726 		      const char *name, size_t sec_idx, const char *sec_name,
727 		      size_t sec_off, void *insn_data, size_t insn_data_sz)
728 {
729 	if (insn_data_sz == 0 || insn_data_sz % BPF_INSN_SZ || sec_off % BPF_INSN_SZ) {
730 		pr_warn("sec '%s': corrupted program '%s', offset %zu, size %zu\n",
731 			sec_name, name, sec_off, insn_data_sz);
732 		return -EINVAL;
733 	}
734 
735 	memset(prog, 0, sizeof(*prog));
736 	prog->obj = obj;
737 
738 	prog->sec_idx = sec_idx;
739 	prog->sec_insn_off = sec_off / BPF_INSN_SZ;
740 	prog->sec_insn_cnt = insn_data_sz / BPF_INSN_SZ;
741 	/* insns_cnt can later be increased by appending used subprograms */
742 	prog->insns_cnt = prog->sec_insn_cnt;
743 
744 	prog->type = BPF_PROG_TYPE_UNSPEC;
745 	prog->fd = -1;
746 
747 	/* libbpf's convention for SEC("?abc...") is that it's just like
748 	 * SEC("abc...") but the corresponding bpf_program starts out with
749 	 * autoload set to false.
750 	 */
751 	if (sec_name[0] == '?') {
752 		prog->autoload = false;
753 		/* from now on forget there was ? in section name */
754 		sec_name++;
755 	} else {
756 		prog->autoload = true;
757 	}
758 
759 	prog->autoattach = true;
760 
761 	/* inherit object's log_level */
762 	prog->log_level = obj->log_level;
763 
764 	prog->sec_name = strdup(sec_name);
765 	if (!prog->sec_name)
766 		goto errout;
767 
768 	prog->name = strdup(name);
769 	if (!prog->name)
770 		goto errout;
771 
772 	prog->insns = malloc(insn_data_sz);
773 	if (!prog->insns)
774 		goto errout;
775 	memcpy(prog->insns, insn_data, insn_data_sz);
776 
777 	return 0;
778 errout:
779 	pr_warn("sec '%s': failed to allocate memory for prog '%s'\n", sec_name, name);
780 	bpf_program__exit(prog);
781 	return -ENOMEM;
782 }
783 
784 static int
785 bpf_object__add_programs(struct bpf_object *obj, Elf_Data *sec_data,
786 			 const char *sec_name, int sec_idx)
787 {
788 	Elf_Data *symbols = obj->efile.symbols;
789 	struct bpf_program *prog, *progs;
790 	void *data = sec_data->d_buf;
791 	size_t sec_sz = sec_data->d_size, sec_off, prog_sz, nr_syms;
792 	int nr_progs, err, i;
793 	const char *name;
794 	Elf64_Sym *sym;
795 
796 	progs = obj->programs;
797 	nr_progs = obj->nr_programs;
798 	nr_syms = symbols->d_size / sizeof(Elf64_Sym);
799 	sec_off = 0;
800 
801 	for (i = 0; i < nr_syms; i++) {
802 		sym = elf_sym_by_idx(obj, i);
803 
804 		if (sym->st_shndx != sec_idx)
805 			continue;
806 		if (ELF64_ST_TYPE(sym->st_info) != STT_FUNC)
807 			continue;
808 
809 		prog_sz = sym->st_size;
810 		sec_off = sym->st_value;
811 
812 		name = elf_sym_str(obj, sym->st_name);
813 		if (!name) {
814 			pr_warn("sec '%s': failed to get symbol name for offset %zu\n",
815 				sec_name, sec_off);
816 			return -LIBBPF_ERRNO__FORMAT;
817 		}
818 
819 		if (sec_off + prog_sz > sec_sz) {
820 			pr_warn("sec '%s': program at offset %zu crosses section boundary\n",
821 				sec_name, sec_off);
822 			return -LIBBPF_ERRNO__FORMAT;
823 		}
824 
825 		if (sec_idx != obj->efile.text_shndx && ELF64_ST_BIND(sym->st_info) == STB_LOCAL) {
826 			pr_warn("sec '%s': program '%s' is static and not supported\n", sec_name, name);
827 			return -ENOTSUP;
828 		}
829 
830 		pr_debug("sec '%s': found program '%s' at insn offset %zu (%zu bytes), code size %zu insns (%zu bytes)\n",
831 			 sec_name, name, sec_off / BPF_INSN_SZ, sec_off, prog_sz / BPF_INSN_SZ, prog_sz);
832 
833 		progs = libbpf_reallocarray(progs, nr_progs + 1, sizeof(*progs));
834 		if (!progs) {
835 			/*
836 			 * In this case the original obj->programs
837 			 * is still valid, so don't need special treat for
838 			 * bpf_close_object().
839 			 */
840 			pr_warn("sec '%s': failed to alloc memory for new program '%s'\n",
841 				sec_name, name);
842 			return -ENOMEM;
843 		}
844 		obj->programs = progs;
845 
846 		prog = &progs[nr_progs];
847 
848 		err = bpf_object__init_prog(obj, prog, name, sec_idx, sec_name,
849 					    sec_off, data + sec_off, prog_sz);
850 		if (err)
851 			return err;
852 
853 		/* if function is a global/weak symbol, but has restricted
854 		 * (STV_HIDDEN or STV_INTERNAL) visibility, mark its BTF FUNC
855 		 * as static to enable more permissive BPF verification mode
856 		 * with more outside context available to BPF verifier
857 		 */
858 		if (ELF64_ST_BIND(sym->st_info) != STB_LOCAL
859 		    && (ELF64_ST_VISIBILITY(sym->st_other) == STV_HIDDEN
860 			|| ELF64_ST_VISIBILITY(sym->st_other) == STV_INTERNAL))
861 			prog->mark_btf_static = true;
862 
863 		nr_progs++;
864 		obj->nr_programs = nr_progs;
865 	}
866 
867 	return 0;
868 }
869 
870 __u32 get_kernel_version(void)
871 {
872 	/* On Ubuntu LINUX_VERSION_CODE doesn't correspond to info.release,
873 	 * but Ubuntu provides /proc/version_signature file, as described at
874 	 * https://ubuntu.com/kernel, with an example contents below, which we
875 	 * can use to get a proper LINUX_VERSION_CODE.
876 	 *
877 	 *   Ubuntu 5.4.0-12.15-generic 5.4.8
878 	 *
879 	 * In the above, 5.4.8 is what kernel is actually expecting, while
880 	 * uname() call will return 5.4.0 in info.release.
881 	 */
882 	const char *ubuntu_kver_file = "/proc/version_signature";
883 	__u32 major, minor, patch;
884 	struct utsname info;
885 
886 	if (access(ubuntu_kver_file, R_OK) == 0) {
887 		FILE *f;
888 
889 		f = fopen(ubuntu_kver_file, "r");
890 		if (f) {
891 			if (fscanf(f, "%*s %*s %d.%d.%d\n", &major, &minor, &patch) == 3) {
892 				fclose(f);
893 				return KERNEL_VERSION(major, minor, patch);
894 			}
895 			fclose(f);
896 		}
897 		/* something went wrong, fall back to uname() approach */
898 	}
899 
900 	uname(&info);
901 	if (sscanf(info.release, "%u.%u.%u", &major, &minor, &patch) != 3)
902 		return 0;
903 	return KERNEL_VERSION(major, minor, patch);
904 }
905 
906 static const struct btf_member *
907 find_member_by_offset(const struct btf_type *t, __u32 bit_offset)
908 {
909 	struct btf_member *m;
910 	int i;
911 
912 	for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
913 		if (btf_member_bit_offset(t, i) == bit_offset)
914 			return m;
915 	}
916 
917 	return NULL;
918 }
919 
920 static const struct btf_member *
921 find_member_by_name(const struct btf *btf, const struct btf_type *t,
922 		    const char *name)
923 {
924 	struct btf_member *m;
925 	int i;
926 
927 	for (i = 0, m = btf_members(t); i < btf_vlen(t); i++, m++) {
928 		if (!strcmp(btf__name_by_offset(btf, m->name_off), name))
929 			return m;
930 	}
931 
932 	return NULL;
933 }
934 
935 #define STRUCT_OPS_VALUE_PREFIX "bpf_struct_ops_"
936 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
937 				   const char *name, __u32 kind);
938 
939 static int
940 find_struct_ops_kern_types(const struct btf *btf, const char *tname,
941 			   const struct btf_type **type, __u32 *type_id,
942 			   const struct btf_type **vtype, __u32 *vtype_id,
943 			   const struct btf_member **data_member)
944 {
945 	const struct btf_type *kern_type, *kern_vtype;
946 	const struct btf_member *kern_data_member;
947 	__s32 kern_vtype_id, kern_type_id;
948 	__u32 i;
949 
950 	kern_type_id = btf__find_by_name_kind(btf, tname, BTF_KIND_STRUCT);
951 	if (kern_type_id < 0) {
952 		pr_warn("struct_ops init_kern: struct %s is not found in kernel BTF\n",
953 			tname);
954 		return kern_type_id;
955 	}
956 	kern_type = btf__type_by_id(btf, kern_type_id);
957 
958 	/* Find the corresponding "map_value" type that will be used
959 	 * in map_update(BPF_MAP_TYPE_STRUCT_OPS).  For example,
960 	 * find "struct bpf_struct_ops_tcp_congestion_ops" from the
961 	 * btf_vmlinux.
962 	 */
963 	kern_vtype_id = find_btf_by_prefix_kind(btf, STRUCT_OPS_VALUE_PREFIX,
964 						tname, BTF_KIND_STRUCT);
965 	if (kern_vtype_id < 0) {
966 		pr_warn("struct_ops init_kern: struct %s%s is not found in kernel BTF\n",
967 			STRUCT_OPS_VALUE_PREFIX, tname);
968 		return kern_vtype_id;
969 	}
970 	kern_vtype = btf__type_by_id(btf, kern_vtype_id);
971 
972 	/* Find "struct tcp_congestion_ops" from
973 	 * struct bpf_struct_ops_tcp_congestion_ops {
974 	 *	[ ... ]
975 	 *	struct tcp_congestion_ops data;
976 	 * }
977 	 */
978 	kern_data_member = btf_members(kern_vtype);
979 	for (i = 0; i < btf_vlen(kern_vtype); i++, kern_data_member++) {
980 		if (kern_data_member->type == kern_type_id)
981 			break;
982 	}
983 	if (i == btf_vlen(kern_vtype)) {
984 		pr_warn("struct_ops init_kern: struct %s data is not found in struct %s%s\n",
985 			tname, STRUCT_OPS_VALUE_PREFIX, tname);
986 		return -EINVAL;
987 	}
988 
989 	*type = kern_type;
990 	*type_id = kern_type_id;
991 	*vtype = kern_vtype;
992 	*vtype_id = kern_vtype_id;
993 	*data_member = kern_data_member;
994 
995 	return 0;
996 }
997 
998 static bool bpf_map__is_struct_ops(const struct bpf_map *map)
999 {
1000 	return map->def.type == BPF_MAP_TYPE_STRUCT_OPS;
1001 }
1002 
1003 /* Init the map's fields that depend on kern_btf */
1004 static int bpf_map__init_kern_struct_ops(struct bpf_map *map,
1005 					 const struct btf *btf,
1006 					 const struct btf *kern_btf)
1007 {
1008 	const struct btf_member *member, *kern_member, *kern_data_member;
1009 	const struct btf_type *type, *kern_type, *kern_vtype;
1010 	__u32 i, kern_type_id, kern_vtype_id, kern_data_off;
1011 	struct bpf_struct_ops *st_ops;
1012 	void *data, *kern_data;
1013 	const char *tname;
1014 	int err;
1015 
1016 	st_ops = map->st_ops;
1017 	type = st_ops->type;
1018 	tname = st_ops->tname;
1019 	err = find_struct_ops_kern_types(kern_btf, tname,
1020 					 &kern_type, &kern_type_id,
1021 					 &kern_vtype, &kern_vtype_id,
1022 					 &kern_data_member);
1023 	if (err)
1024 		return err;
1025 
1026 	pr_debug("struct_ops init_kern %s: type_id:%u kern_type_id:%u kern_vtype_id:%u\n",
1027 		 map->name, st_ops->type_id, kern_type_id, kern_vtype_id);
1028 
1029 	map->def.value_size = kern_vtype->size;
1030 	map->btf_vmlinux_value_type_id = kern_vtype_id;
1031 
1032 	st_ops->kern_vdata = calloc(1, kern_vtype->size);
1033 	if (!st_ops->kern_vdata)
1034 		return -ENOMEM;
1035 
1036 	data = st_ops->data;
1037 	kern_data_off = kern_data_member->offset / 8;
1038 	kern_data = st_ops->kern_vdata + kern_data_off;
1039 
1040 	member = btf_members(type);
1041 	for (i = 0; i < btf_vlen(type); i++, member++) {
1042 		const struct btf_type *mtype, *kern_mtype;
1043 		__u32 mtype_id, kern_mtype_id;
1044 		void *mdata, *kern_mdata;
1045 		__s64 msize, kern_msize;
1046 		__u32 moff, kern_moff;
1047 		__u32 kern_member_idx;
1048 		const char *mname;
1049 
1050 		mname = btf__name_by_offset(btf, member->name_off);
1051 		kern_member = find_member_by_name(kern_btf, kern_type, mname);
1052 		if (!kern_member) {
1053 			pr_warn("struct_ops init_kern %s: Cannot find member %s in kernel BTF\n",
1054 				map->name, mname);
1055 			return -ENOTSUP;
1056 		}
1057 
1058 		kern_member_idx = kern_member - btf_members(kern_type);
1059 		if (btf_member_bitfield_size(type, i) ||
1060 		    btf_member_bitfield_size(kern_type, kern_member_idx)) {
1061 			pr_warn("struct_ops init_kern %s: bitfield %s is not supported\n",
1062 				map->name, mname);
1063 			return -ENOTSUP;
1064 		}
1065 
1066 		moff = member->offset / 8;
1067 		kern_moff = kern_member->offset / 8;
1068 
1069 		mdata = data + moff;
1070 		kern_mdata = kern_data + kern_moff;
1071 
1072 		mtype = skip_mods_and_typedefs(btf, member->type, &mtype_id);
1073 		kern_mtype = skip_mods_and_typedefs(kern_btf, kern_member->type,
1074 						    &kern_mtype_id);
1075 		if (BTF_INFO_KIND(mtype->info) !=
1076 		    BTF_INFO_KIND(kern_mtype->info)) {
1077 			pr_warn("struct_ops init_kern %s: Unmatched member type %s %u != %u(kernel)\n",
1078 				map->name, mname, BTF_INFO_KIND(mtype->info),
1079 				BTF_INFO_KIND(kern_mtype->info));
1080 			return -ENOTSUP;
1081 		}
1082 
1083 		if (btf_is_ptr(mtype)) {
1084 			struct bpf_program *prog;
1085 
1086 			prog = st_ops->progs[i];
1087 			if (!prog)
1088 				continue;
1089 
1090 			kern_mtype = skip_mods_and_typedefs(kern_btf,
1091 							    kern_mtype->type,
1092 							    &kern_mtype_id);
1093 
1094 			/* mtype->type must be a func_proto which was
1095 			 * guaranteed in bpf_object__collect_st_ops_relos(),
1096 			 * so only check kern_mtype for func_proto here.
1097 			 */
1098 			if (!btf_is_func_proto(kern_mtype)) {
1099 				pr_warn("struct_ops init_kern %s: kernel member %s is not a func ptr\n",
1100 					map->name, mname);
1101 				return -ENOTSUP;
1102 			}
1103 
1104 			prog->attach_btf_id = kern_type_id;
1105 			prog->expected_attach_type = kern_member_idx;
1106 
1107 			st_ops->kern_func_off[i] = kern_data_off + kern_moff;
1108 
1109 			pr_debug("struct_ops init_kern %s: func ptr %s is set to prog %s from data(+%u) to kern_data(+%u)\n",
1110 				 map->name, mname, prog->name, moff,
1111 				 kern_moff);
1112 
1113 			continue;
1114 		}
1115 
1116 		msize = btf__resolve_size(btf, mtype_id);
1117 		kern_msize = btf__resolve_size(kern_btf, kern_mtype_id);
1118 		if (msize < 0 || kern_msize < 0 || msize != kern_msize) {
1119 			pr_warn("struct_ops init_kern %s: Error in size of member %s: %zd != %zd(kernel)\n",
1120 				map->name, mname, (ssize_t)msize,
1121 				(ssize_t)kern_msize);
1122 			return -ENOTSUP;
1123 		}
1124 
1125 		pr_debug("struct_ops init_kern %s: copy %s %u bytes from data(+%u) to kern_data(+%u)\n",
1126 			 map->name, mname, (unsigned int)msize,
1127 			 moff, kern_moff);
1128 		memcpy(kern_mdata, mdata, msize);
1129 	}
1130 
1131 	return 0;
1132 }
1133 
1134 static int bpf_object__init_kern_struct_ops_maps(struct bpf_object *obj)
1135 {
1136 	struct bpf_map *map;
1137 	size_t i;
1138 	int err;
1139 
1140 	for (i = 0; i < obj->nr_maps; i++) {
1141 		map = &obj->maps[i];
1142 
1143 		if (!bpf_map__is_struct_ops(map))
1144 			continue;
1145 
1146 		err = bpf_map__init_kern_struct_ops(map, obj->btf,
1147 						    obj->btf_vmlinux);
1148 		if (err)
1149 			return err;
1150 	}
1151 
1152 	return 0;
1153 }
1154 
1155 static int bpf_object__init_struct_ops_maps(struct bpf_object *obj)
1156 {
1157 	const struct btf_type *type, *datasec;
1158 	const struct btf_var_secinfo *vsi;
1159 	struct bpf_struct_ops *st_ops;
1160 	const char *tname, *var_name;
1161 	__s32 type_id, datasec_id;
1162 	const struct btf *btf;
1163 	struct bpf_map *map;
1164 	__u32 i;
1165 
1166 	if (obj->efile.st_ops_shndx == -1)
1167 		return 0;
1168 
1169 	btf = obj->btf;
1170 	datasec_id = btf__find_by_name_kind(btf, STRUCT_OPS_SEC,
1171 					    BTF_KIND_DATASEC);
1172 	if (datasec_id < 0) {
1173 		pr_warn("struct_ops init: DATASEC %s not found\n",
1174 			STRUCT_OPS_SEC);
1175 		return -EINVAL;
1176 	}
1177 
1178 	datasec = btf__type_by_id(btf, datasec_id);
1179 	vsi = btf_var_secinfos(datasec);
1180 	for (i = 0; i < btf_vlen(datasec); i++, vsi++) {
1181 		type = btf__type_by_id(obj->btf, vsi->type);
1182 		var_name = btf__name_by_offset(obj->btf, type->name_off);
1183 
1184 		type_id = btf__resolve_type(obj->btf, vsi->type);
1185 		if (type_id < 0) {
1186 			pr_warn("struct_ops init: Cannot resolve var type_id %u in DATASEC %s\n",
1187 				vsi->type, STRUCT_OPS_SEC);
1188 			return -EINVAL;
1189 		}
1190 
1191 		type = btf__type_by_id(obj->btf, type_id);
1192 		tname = btf__name_by_offset(obj->btf, type->name_off);
1193 		if (!tname[0]) {
1194 			pr_warn("struct_ops init: anonymous type is not supported\n");
1195 			return -ENOTSUP;
1196 		}
1197 		if (!btf_is_struct(type)) {
1198 			pr_warn("struct_ops init: %s is not a struct\n", tname);
1199 			return -EINVAL;
1200 		}
1201 
1202 		map = bpf_object__add_map(obj);
1203 		if (IS_ERR(map))
1204 			return PTR_ERR(map);
1205 
1206 		map->sec_idx = obj->efile.st_ops_shndx;
1207 		map->sec_offset = vsi->offset;
1208 		map->name = strdup(var_name);
1209 		if (!map->name)
1210 			return -ENOMEM;
1211 
1212 		map->def.type = BPF_MAP_TYPE_STRUCT_OPS;
1213 		map->def.key_size = sizeof(int);
1214 		map->def.value_size = type->size;
1215 		map->def.max_entries = 1;
1216 
1217 		map->st_ops = calloc(1, sizeof(*map->st_ops));
1218 		if (!map->st_ops)
1219 			return -ENOMEM;
1220 		st_ops = map->st_ops;
1221 		st_ops->data = malloc(type->size);
1222 		st_ops->progs = calloc(btf_vlen(type), sizeof(*st_ops->progs));
1223 		st_ops->kern_func_off = malloc(btf_vlen(type) *
1224 					       sizeof(*st_ops->kern_func_off));
1225 		if (!st_ops->data || !st_ops->progs || !st_ops->kern_func_off)
1226 			return -ENOMEM;
1227 
1228 		if (vsi->offset + type->size > obj->efile.st_ops_data->d_size) {
1229 			pr_warn("struct_ops init: var %s is beyond the end of DATASEC %s\n",
1230 				var_name, STRUCT_OPS_SEC);
1231 			return -EINVAL;
1232 		}
1233 
1234 		memcpy(st_ops->data,
1235 		       obj->efile.st_ops_data->d_buf + vsi->offset,
1236 		       type->size);
1237 		st_ops->tname = tname;
1238 		st_ops->type = type;
1239 		st_ops->type_id = type_id;
1240 
1241 		pr_debug("struct_ops init: struct %s(type_id=%u) %s found at offset %u\n",
1242 			 tname, type_id, var_name, vsi->offset);
1243 	}
1244 
1245 	return 0;
1246 }
1247 
1248 static struct bpf_object *bpf_object__new(const char *path,
1249 					  const void *obj_buf,
1250 					  size_t obj_buf_sz,
1251 					  const char *obj_name)
1252 {
1253 	struct bpf_object *obj;
1254 	char *end;
1255 
1256 	obj = calloc(1, sizeof(struct bpf_object) + strlen(path) + 1);
1257 	if (!obj) {
1258 		pr_warn("alloc memory failed for %s\n", path);
1259 		return ERR_PTR(-ENOMEM);
1260 	}
1261 
1262 	strcpy(obj->path, path);
1263 	if (obj_name) {
1264 		libbpf_strlcpy(obj->name, obj_name, sizeof(obj->name));
1265 	} else {
1266 		/* Using basename() GNU version which doesn't modify arg. */
1267 		libbpf_strlcpy(obj->name, basename((void *)path), sizeof(obj->name));
1268 		end = strchr(obj->name, '.');
1269 		if (end)
1270 			*end = 0;
1271 	}
1272 
1273 	obj->efile.fd = -1;
1274 	/*
1275 	 * Caller of this function should also call
1276 	 * bpf_object__elf_finish() after data collection to return
1277 	 * obj_buf to user. If not, we should duplicate the buffer to
1278 	 * avoid user freeing them before elf finish.
1279 	 */
1280 	obj->efile.obj_buf = obj_buf;
1281 	obj->efile.obj_buf_sz = obj_buf_sz;
1282 	obj->efile.btf_maps_shndx = -1;
1283 	obj->efile.st_ops_shndx = -1;
1284 	obj->kconfig_map_idx = -1;
1285 
1286 	obj->kern_version = get_kernel_version();
1287 	obj->loaded = false;
1288 
1289 	return obj;
1290 }
1291 
1292 static void bpf_object__elf_finish(struct bpf_object *obj)
1293 {
1294 	if (!obj->efile.elf)
1295 		return;
1296 
1297 	elf_end(obj->efile.elf);
1298 	obj->efile.elf = NULL;
1299 	obj->efile.symbols = NULL;
1300 	obj->efile.st_ops_data = NULL;
1301 
1302 	zfree(&obj->efile.secs);
1303 	obj->efile.sec_cnt = 0;
1304 	zclose(obj->efile.fd);
1305 	obj->efile.obj_buf = NULL;
1306 	obj->efile.obj_buf_sz = 0;
1307 }
1308 
1309 static int bpf_object__elf_init(struct bpf_object *obj)
1310 {
1311 	Elf64_Ehdr *ehdr;
1312 	int err = 0;
1313 	Elf *elf;
1314 
1315 	if (obj->efile.elf) {
1316 		pr_warn("elf: init internal error\n");
1317 		return -LIBBPF_ERRNO__LIBELF;
1318 	}
1319 
1320 	if (obj->efile.obj_buf_sz > 0) {
1321 		/* obj_buf should have been validated by bpf_object__open_mem(). */
1322 		elf = elf_memory((char *)obj->efile.obj_buf, obj->efile.obj_buf_sz);
1323 	} else {
1324 		obj->efile.fd = open(obj->path, O_RDONLY | O_CLOEXEC);
1325 		if (obj->efile.fd < 0) {
1326 			char errmsg[STRERR_BUFSIZE], *cp;
1327 
1328 			err = -errno;
1329 			cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
1330 			pr_warn("elf: failed to open %s: %s\n", obj->path, cp);
1331 			return err;
1332 		}
1333 
1334 		elf = elf_begin(obj->efile.fd, ELF_C_READ_MMAP, NULL);
1335 	}
1336 
1337 	if (!elf) {
1338 		pr_warn("elf: failed to open %s as ELF file: %s\n", obj->path, elf_errmsg(-1));
1339 		err = -LIBBPF_ERRNO__LIBELF;
1340 		goto errout;
1341 	}
1342 
1343 	obj->efile.elf = elf;
1344 
1345 	if (elf_kind(elf) != ELF_K_ELF) {
1346 		err = -LIBBPF_ERRNO__FORMAT;
1347 		pr_warn("elf: '%s' is not a proper ELF object\n", obj->path);
1348 		goto errout;
1349 	}
1350 
1351 	if (gelf_getclass(elf) != ELFCLASS64) {
1352 		err = -LIBBPF_ERRNO__FORMAT;
1353 		pr_warn("elf: '%s' is not a 64-bit ELF object\n", obj->path);
1354 		goto errout;
1355 	}
1356 
1357 	obj->efile.ehdr = ehdr = elf64_getehdr(elf);
1358 	if (!obj->efile.ehdr) {
1359 		pr_warn("elf: failed to get ELF header from %s: %s\n", obj->path, elf_errmsg(-1));
1360 		err = -LIBBPF_ERRNO__FORMAT;
1361 		goto errout;
1362 	}
1363 
1364 	if (elf_getshdrstrndx(elf, &obj->efile.shstrndx)) {
1365 		pr_warn("elf: failed to get section names section index for %s: %s\n",
1366 			obj->path, elf_errmsg(-1));
1367 		err = -LIBBPF_ERRNO__FORMAT;
1368 		goto errout;
1369 	}
1370 
1371 	/* Elf is corrupted/truncated, avoid calling elf_strptr. */
1372 	if (!elf_rawdata(elf_getscn(elf, obj->efile.shstrndx), NULL)) {
1373 		pr_warn("elf: failed to get section names strings from %s: %s\n",
1374 			obj->path, elf_errmsg(-1));
1375 		err = -LIBBPF_ERRNO__FORMAT;
1376 		goto errout;
1377 	}
1378 
1379 	/* Old LLVM set e_machine to EM_NONE */
1380 	if (ehdr->e_type != ET_REL || (ehdr->e_machine && ehdr->e_machine != EM_BPF)) {
1381 		pr_warn("elf: %s is not a valid eBPF object file\n", obj->path);
1382 		err = -LIBBPF_ERRNO__FORMAT;
1383 		goto errout;
1384 	}
1385 
1386 	return 0;
1387 errout:
1388 	bpf_object__elf_finish(obj);
1389 	return err;
1390 }
1391 
1392 static int bpf_object__check_endianness(struct bpf_object *obj)
1393 {
1394 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
1395 	if (obj->efile.ehdr->e_ident[EI_DATA] == ELFDATA2LSB)
1396 		return 0;
1397 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
1398 	if (obj->efile.ehdr->e_ident[EI_DATA] == ELFDATA2MSB)
1399 		return 0;
1400 #else
1401 # error "Unrecognized __BYTE_ORDER__"
1402 #endif
1403 	pr_warn("elf: endianness mismatch in %s.\n", obj->path);
1404 	return -LIBBPF_ERRNO__ENDIAN;
1405 }
1406 
1407 static int
1408 bpf_object__init_license(struct bpf_object *obj, void *data, size_t size)
1409 {
1410 	/* libbpf_strlcpy() only copies first N - 1 bytes, so size + 1 won't
1411 	 * go over allowed ELF data section buffer
1412 	 */
1413 	libbpf_strlcpy(obj->license, data, min(size + 1, sizeof(obj->license)));
1414 	pr_debug("license of %s is %s\n", obj->path, obj->license);
1415 	return 0;
1416 }
1417 
1418 static int
1419 bpf_object__init_kversion(struct bpf_object *obj, void *data, size_t size)
1420 {
1421 	__u32 kver;
1422 
1423 	if (size != sizeof(kver)) {
1424 		pr_warn("invalid kver section in %s\n", obj->path);
1425 		return -LIBBPF_ERRNO__FORMAT;
1426 	}
1427 	memcpy(&kver, data, sizeof(kver));
1428 	obj->kern_version = kver;
1429 	pr_debug("kernel version of %s is %x\n", obj->path, obj->kern_version);
1430 	return 0;
1431 }
1432 
1433 static bool bpf_map_type__is_map_in_map(enum bpf_map_type type)
1434 {
1435 	if (type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
1436 	    type == BPF_MAP_TYPE_HASH_OF_MAPS)
1437 		return true;
1438 	return false;
1439 }
1440 
1441 static int find_elf_sec_sz(const struct bpf_object *obj, const char *name, __u32 *size)
1442 {
1443 	Elf_Data *data;
1444 	Elf_Scn *scn;
1445 
1446 	if (!name)
1447 		return -EINVAL;
1448 
1449 	scn = elf_sec_by_name(obj, name);
1450 	data = elf_sec_data(obj, scn);
1451 	if (data) {
1452 		*size = data->d_size;
1453 		return 0; /* found it */
1454 	}
1455 
1456 	return -ENOENT;
1457 }
1458 
1459 static int find_elf_var_offset(const struct bpf_object *obj, const char *name, __u32 *off)
1460 {
1461 	Elf_Data *symbols = obj->efile.symbols;
1462 	const char *sname;
1463 	size_t si;
1464 
1465 	if (!name || !off)
1466 		return -EINVAL;
1467 
1468 	for (si = 0; si < symbols->d_size / sizeof(Elf64_Sym); si++) {
1469 		Elf64_Sym *sym = elf_sym_by_idx(obj, si);
1470 
1471 		if (ELF64_ST_TYPE(sym->st_info) != STT_OBJECT)
1472 			continue;
1473 
1474 		if (ELF64_ST_BIND(sym->st_info) != STB_GLOBAL &&
1475 		    ELF64_ST_BIND(sym->st_info) != STB_WEAK)
1476 			continue;
1477 
1478 		sname = elf_sym_str(obj, sym->st_name);
1479 		if (!sname) {
1480 			pr_warn("failed to get sym name string for var %s\n", name);
1481 			return -EIO;
1482 		}
1483 		if (strcmp(name, sname) == 0) {
1484 			*off = sym->st_value;
1485 			return 0;
1486 		}
1487 	}
1488 
1489 	return -ENOENT;
1490 }
1491 
1492 static struct bpf_map *bpf_object__add_map(struct bpf_object *obj)
1493 {
1494 	struct bpf_map *map;
1495 	int err;
1496 
1497 	err = libbpf_ensure_mem((void **)&obj->maps, &obj->maps_cap,
1498 				sizeof(*obj->maps), obj->nr_maps + 1);
1499 	if (err)
1500 		return ERR_PTR(err);
1501 
1502 	map = &obj->maps[obj->nr_maps++];
1503 	map->obj = obj;
1504 	map->fd = -1;
1505 	map->inner_map_fd = -1;
1506 	map->autocreate = true;
1507 
1508 	return map;
1509 }
1510 
1511 static size_t bpf_map_mmap_sz(const struct bpf_map *map)
1512 {
1513 	long page_sz = sysconf(_SC_PAGE_SIZE);
1514 	size_t map_sz;
1515 
1516 	map_sz = (size_t)roundup(map->def.value_size, 8) * map->def.max_entries;
1517 	map_sz = roundup(map_sz, page_sz);
1518 	return map_sz;
1519 }
1520 
1521 static char *internal_map_name(struct bpf_object *obj, const char *real_name)
1522 {
1523 	char map_name[BPF_OBJ_NAME_LEN], *p;
1524 	int pfx_len, sfx_len = max((size_t)7, strlen(real_name));
1525 
1526 	/* This is one of the more confusing parts of libbpf for various
1527 	 * reasons, some of which are historical. The original idea for naming
1528 	 * internal names was to include as much of BPF object name prefix as
1529 	 * possible, so that it can be distinguished from similar internal
1530 	 * maps of a different BPF object.
1531 	 * As an example, let's say we have bpf_object named 'my_object_name'
1532 	 * and internal map corresponding to '.rodata' ELF section. The final
1533 	 * map name advertised to user and to the kernel will be
1534 	 * 'my_objec.rodata', taking first 8 characters of object name and
1535 	 * entire 7 characters of '.rodata'.
1536 	 * Somewhat confusingly, if internal map ELF section name is shorter
1537 	 * than 7 characters, e.g., '.bss', we still reserve 7 characters
1538 	 * for the suffix, even though we only have 4 actual characters, and
1539 	 * resulting map will be called 'my_objec.bss', not even using all 15
1540 	 * characters allowed by the kernel. Oh well, at least the truncated
1541 	 * object name is somewhat consistent in this case. But if the map
1542 	 * name is '.kconfig', we'll still have entirety of '.kconfig' added
1543 	 * (8 chars) and thus will be left with only first 7 characters of the
1544 	 * object name ('my_obje'). Happy guessing, user, that the final map
1545 	 * name will be "my_obje.kconfig".
1546 	 * Now, with libbpf starting to support arbitrarily named .rodata.*
1547 	 * and .data.* data sections, it's possible that ELF section name is
1548 	 * longer than allowed 15 chars, so we now need to be careful to take
1549 	 * only up to 15 first characters of ELF name, taking no BPF object
1550 	 * name characters at all. So '.rodata.abracadabra' will result in
1551 	 * '.rodata.abracad' kernel and user-visible name.
1552 	 * We need to keep this convoluted logic intact for .data, .bss and
1553 	 * .rodata maps, but for new custom .data.custom and .rodata.custom
1554 	 * maps we use their ELF names as is, not prepending bpf_object name
1555 	 * in front. We still need to truncate them to 15 characters for the
1556 	 * kernel. Full name can be recovered for such maps by using DATASEC
1557 	 * BTF type associated with such map's value type, though.
1558 	 */
1559 	if (sfx_len >= BPF_OBJ_NAME_LEN)
1560 		sfx_len = BPF_OBJ_NAME_LEN - 1;
1561 
1562 	/* if there are two or more dots in map name, it's a custom dot map */
1563 	if (strchr(real_name + 1, '.') != NULL)
1564 		pfx_len = 0;
1565 	else
1566 		pfx_len = min((size_t)BPF_OBJ_NAME_LEN - sfx_len - 1, strlen(obj->name));
1567 
1568 	snprintf(map_name, sizeof(map_name), "%.*s%.*s", pfx_len, obj->name,
1569 		 sfx_len, real_name);
1570 
1571 	/* sanitise map name to characters allowed by kernel */
1572 	for (p = map_name; *p && p < map_name + sizeof(map_name); p++)
1573 		if (!isalnum(*p) && *p != '_' && *p != '.')
1574 			*p = '_';
1575 
1576 	return strdup(map_name);
1577 }
1578 
1579 static int
1580 bpf_map_find_btf_info(struct bpf_object *obj, struct bpf_map *map);
1581 
1582 static int
1583 bpf_object__init_internal_map(struct bpf_object *obj, enum libbpf_map_type type,
1584 			      const char *real_name, int sec_idx, void *data, size_t data_sz)
1585 {
1586 	struct bpf_map_def *def;
1587 	struct bpf_map *map;
1588 	int err;
1589 
1590 	map = bpf_object__add_map(obj);
1591 	if (IS_ERR(map))
1592 		return PTR_ERR(map);
1593 
1594 	map->libbpf_type = type;
1595 	map->sec_idx = sec_idx;
1596 	map->sec_offset = 0;
1597 	map->real_name = strdup(real_name);
1598 	map->name = internal_map_name(obj, real_name);
1599 	if (!map->real_name || !map->name) {
1600 		zfree(&map->real_name);
1601 		zfree(&map->name);
1602 		return -ENOMEM;
1603 	}
1604 
1605 	def = &map->def;
1606 	def->type = BPF_MAP_TYPE_ARRAY;
1607 	def->key_size = sizeof(int);
1608 	def->value_size = data_sz;
1609 	def->max_entries = 1;
1610 	def->map_flags = type == LIBBPF_MAP_RODATA || type == LIBBPF_MAP_KCONFIG
1611 			 ? BPF_F_RDONLY_PROG : 0;
1612 	def->map_flags |= BPF_F_MMAPABLE;
1613 
1614 	pr_debug("map '%s' (global data): at sec_idx %d, offset %zu, flags %x.\n",
1615 		 map->name, map->sec_idx, map->sec_offset, def->map_flags);
1616 
1617 	map->mmaped = mmap(NULL, bpf_map_mmap_sz(map), PROT_READ | PROT_WRITE,
1618 			   MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1619 	if (map->mmaped == MAP_FAILED) {
1620 		err = -errno;
1621 		map->mmaped = NULL;
1622 		pr_warn("failed to alloc map '%s' content buffer: %d\n",
1623 			map->name, err);
1624 		zfree(&map->real_name);
1625 		zfree(&map->name);
1626 		return err;
1627 	}
1628 
1629 	/* failures are fine because of maps like .rodata.str1.1 */
1630 	(void) bpf_map_find_btf_info(obj, map);
1631 
1632 	if (data)
1633 		memcpy(map->mmaped, data, data_sz);
1634 
1635 	pr_debug("map %td is \"%s\"\n", map - obj->maps, map->name);
1636 	return 0;
1637 }
1638 
1639 static int bpf_object__init_global_data_maps(struct bpf_object *obj)
1640 {
1641 	struct elf_sec_desc *sec_desc;
1642 	const char *sec_name;
1643 	int err = 0, sec_idx;
1644 
1645 	/*
1646 	 * Populate obj->maps with libbpf internal maps.
1647 	 */
1648 	for (sec_idx = 1; sec_idx < obj->efile.sec_cnt; sec_idx++) {
1649 		sec_desc = &obj->efile.secs[sec_idx];
1650 
1651 		/* Skip recognized sections with size 0. */
1652 		if (!sec_desc->data || sec_desc->data->d_size == 0)
1653 			continue;
1654 
1655 		switch (sec_desc->sec_type) {
1656 		case SEC_DATA:
1657 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1658 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_DATA,
1659 							    sec_name, sec_idx,
1660 							    sec_desc->data->d_buf,
1661 							    sec_desc->data->d_size);
1662 			break;
1663 		case SEC_RODATA:
1664 			obj->has_rodata = true;
1665 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1666 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_RODATA,
1667 							    sec_name, sec_idx,
1668 							    sec_desc->data->d_buf,
1669 							    sec_desc->data->d_size);
1670 			break;
1671 		case SEC_BSS:
1672 			sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, sec_idx));
1673 			err = bpf_object__init_internal_map(obj, LIBBPF_MAP_BSS,
1674 							    sec_name, sec_idx,
1675 							    NULL,
1676 							    sec_desc->data->d_size);
1677 			break;
1678 		default:
1679 			/* skip */
1680 			break;
1681 		}
1682 		if (err)
1683 			return err;
1684 	}
1685 	return 0;
1686 }
1687 
1688 
1689 static struct extern_desc *find_extern_by_name(const struct bpf_object *obj,
1690 					       const void *name)
1691 {
1692 	int i;
1693 
1694 	for (i = 0; i < obj->nr_extern; i++) {
1695 		if (strcmp(obj->externs[i].name, name) == 0)
1696 			return &obj->externs[i];
1697 	}
1698 	return NULL;
1699 }
1700 
1701 static int set_kcfg_value_tri(struct extern_desc *ext, void *ext_val,
1702 			      char value)
1703 {
1704 	switch (ext->kcfg.type) {
1705 	case KCFG_BOOL:
1706 		if (value == 'm') {
1707 			pr_warn("extern (kcfg) '%s': value '%c' implies tristate or char type\n",
1708 				ext->name, value);
1709 			return -EINVAL;
1710 		}
1711 		*(bool *)ext_val = value == 'y' ? true : false;
1712 		break;
1713 	case KCFG_TRISTATE:
1714 		if (value == 'y')
1715 			*(enum libbpf_tristate *)ext_val = TRI_YES;
1716 		else if (value == 'm')
1717 			*(enum libbpf_tristate *)ext_val = TRI_MODULE;
1718 		else /* value == 'n' */
1719 			*(enum libbpf_tristate *)ext_val = TRI_NO;
1720 		break;
1721 	case KCFG_CHAR:
1722 		*(char *)ext_val = value;
1723 		break;
1724 	case KCFG_UNKNOWN:
1725 	case KCFG_INT:
1726 	case KCFG_CHAR_ARR:
1727 	default:
1728 		pr_warn("extern (kcfg) '%s': value '%c' implies bool, tristate, or char type\n",
1729 			ext->name, value);
1730 		return -EINVAL;
1731 	}
1732 	ext->is_set = true;
1733 	return 0;
1734 }
1735 
1736 static int set_kcfg_value_str(struct extern_desc *ext, char *ext_val,
1737 			      const char *value)
1738 {
1739 	size_t len;
1740 
1741 	if (ext->kcfg.type != KCFG_CHAR_ARR) {
1742 		pr_warn("extern (kcfg) '%s': value '%s' implies char array type\n",
1743 			ext->name, value);
1744 		return -EINVAL;
1745 	}
1746 
1747 	len = strlen(value);
1748 	if (value[len - 1] != '"') {
1749 		pr_warn("extern (kcfg) '%s': invalid string config '%s'\n",
1750 			ext->name, value);
1751 		return -EINVAL;
1752 	}
1753 
1754 	/* strip quotes */
1755 	len -= 2;
1756 	if (len >= ext->kcfg.sz) {
1757 		pr_warn("extern (kcfg) '%s': long string '%s' of (%zu bytes) truncated to %d bytes\n",
1758 			ext->name, value, len, ext->kcfg.sz - 1);
1759 		len = ext->kcfg.sz - 1;
1760 	}
1761 	memcpy(ext_val, value + 1, len);
1762 	ext_val[len] = '\0';
1763 	ext->is_set = true;
1764 	return 0;
1765 }
1766 
1767 static int parse_u64(const char *value, __u64 *res)
1768 {
1769 	char *value_end;
1770 	int err;
1771 
1772 	errno = 0;
1773 	*res = strtoull(value, &value_end, 0);
1774 	if (errno) {
1775 		err = -errno;
1776 		pr_warn("failed to parse '%s' as integer: %d\n", value, err);
1777 		return err;
1778 	}
1779 	if (*value_end) {
1780 		pr_warn("failed to parse '%s' as integer completely\n", value);
1781 		return -EINVAL;
1782 	}
1783 	return 0;
1784 }
1785 
1786 static bool is_kcfg_value_in_range(const struct extern_desc *ext, __u64 v)
1787 {
1788 	int bit_sz = ext->kcfg.sz * 8;
1789 
1790 	if (ext->kcfg.sz == 8)
1791 		return true;
1792 
1793 	/* Validate that value stored in u64 fits in integer of `ext->sz`
1794 	 * bytes size without any loss of information. If the target integer
1795 	 * is signed, we rely on the following limits of integer type of
1796 	 * Y bits and subsequent transformation:
1797 	 *
1798 	 *     -2^(Y-1) <= X           <= 2^(Y-1) - 1
1799 	 *            0 <= X + 2^(Y-1) <= 2^Y - 1
1800 	 *            0 <= X + 2^(Y-1) <  2^Y
1801 	 *
1802 	 *  For unsigned target integer, check that all the (64 - Y) bits are
1803 	 *  zero.
1804 	 */
1805 	if (ext->kcfg.is_signed)
1806 		return v + (1ULL << (bit_sz - 1)) < (1ULL << bit_sz);
1807 	else
1808 		return (v >> bit_sz) == 0;
1809 }
1810 
1811 static int set_kcfg_value_num(struct extern_desc *ext, void *ext_val,
1812 			      __u64 value)
1813 {
1814 	if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR &&
1815 	    ext->kcfg.type != KCFG_BOOL) {
1816 		pr_warn("extern (kcfg) '%s': value '%llu' implies integer, char, or boolean type\n",
1817 			ext->name, (unsigned long long)value);
1818 		return -EINVAL;
1819 	}
1820 	if (ext->kcfg.type == KCFG_BOOL && value > 1) {
1821 		pr_warn("extern (kcfg) '%s': value '%llu' isn't boolean compatible\n",
1822 			ext->name, (unsigned long long)value);
1823 		return -EINVAL;
1824 
1825 	}
1826 	if (!is_kcfg_value_in_range(ext, value)) {
1827 		pr_warn("extern (kcfg) '%s': value '%llu' doesn't fit in %d bytes\n",
1828 			ext->name, (unsigned long long)value, ext->kcfg.sz);
1829 		return -ERANGE;
1830 	}
1831 	switch (ext->kcfg.sz) {
1832 		case 1: *(__u8 *)ext_val = value; break;
1833 		case 2: *(__u16 *)ext_val = value; break;
1834 		case 4: *(__u32 *)ext_val = value; break;
1835 		case 8: *(__u64 *)ext_val = value; break;
1836 		default:
1837 			return -EINVAL;
1838 	}
1839 	ext->is_set = true;
1840 	return 0;
1841 }
1842 
1843 static int bpf_object__process_kconfig_line(struct bpf_object *obj,
1844 					    char *buf, void *data)
1845 {
1846 	struct extern_desc *ext;
1847 	char *sep, *value;
1848 	int len, err = 0;
1849 	void *ext_val;
1850 	__u64 num;
1851 
1852 	if (!str_has_pfx(buf, "CONFIG_"))
1853 		return 0;
1854 
1855 	sep = strchr(buf, '=');
1856 	if (!sep) {
1857 		pr_warn("failed to parse '%s': no separator\n", buf);
1858 		return -EINVAL;
1859 	}
1860 
1861 	/* Trim ending '\n' */
1862 	len = strlen(buf);
1863 	if (buf[len - 1] == '\n')
1864 		buf[len - 1] = '\0';
1865 	/* Split on '=' and ensure that a value is present. */
1866 	*sep = '\0';
1867 	if (!sep[1]) {
1868 		*sep = '=';
1869 		pr_warn("failed to parse '%s': no value\n", buf);
1870 		return -EINVAL;
1871 	}
1872 
1873 	ext = find_extern_by_name(obj, buf);
1874 	if (!ext || ext->is_set)
1875 		return 0;
1876 
1877 	ext_val = data + ext->kcfg.data_off;
1878 	value = sep + 1;
1879 
1880 	switch (*value) {
1881 	case 'y': case 'n': case 'm':
1882 		err = set_kcfg_value_tri(ext, ext_val, *value);
1883 		break;
1884 	case '"':
1885 		err = set_kcfg_value_str(ext, ext_val, value);
1886 		break;
1887 	default:
1888 		/* assume integer */
1889 		err = parse_u64(value, &num);
1890 		if (err) {
1891 			pr_warn("extern (kcfg) '%s': value '%s' isn't a valid integer\n", ext->name, value);
1892 			return err;
1893 		}
1894 		if (ext->kcfg.type != KCFG_INT && ext->kcfg.type != KCFG_CHAR) {
1895 			pr_warn("extern (kcfg) '%s': value '%s' implies integer type\n", ext->name, value);
1896 			return -EINVAL;
1897 		}
1898 		err = set_kcfg_value_num(ext, ext_val, num);
1899 		break;
1900 	}
1901 	if (err)
1902 		return err;
1903 	pr_debug("extern (kcfg) '%s': set to %s\n", ext->name, value);
1904 	return 0;
1905 }
1906 
1907 static int bpf_object__read_kconfig_file(struct bpf_object *obj, void *data)
1908 {
1909 	char buf[PATH_MAX];
1910 	struct utsname uts;
1911 	int len, err = 0;
1912 	gzFile file;
1913 
1914 	uname(&uts);
1915 	len = snprintf(buf, PATH_MAX, "/boot/config-%s", uts.release);
1916 	if (len < 0)
1917 		return -EINVAL;
1918 	else if (len >= PATH_MAX)
1919 		return -ENAMETOOLONG;
1920 
1921 	/* gzopen also accepts uncompressed files. */
1922 	file = gzopen(buf, "r");
1923 	if (!file)
1924 		file = gzopen("/proc/config.gz", "r");
1925 
1926 	if (!file) {
1927 		pr_warn("failed to open system Kconfig\n");
1928 		return -ENOENT;
1929 	}
1930 
1931 	while (gzgets(file, buf, sizeof(buf))) {
1932 		err = bpf_object__process_kconfig_line(obj, buf, data);
1933 		if (err) {
1934 			pr_warn("error parsing system Kconfig line '%s': %d\n",
1935 				buf, err);
1936 			goto out;
1937 		}
1938 	}
1939 
1940 out:
1941 	gzclose(file);
1942 	return err;
1943 }
1944 
1945 static int bpf_object__read_kconfig_mem(struct bpf_object *obj,
1946 					const char *config, void *data)
1947 {
1948 	char buf[PATH_MAX];
1949 	int err = 0;
1950 	FILE *file;
1951 
1952 	file = fmemopen((void *)config, strlen(config), "r");
1953 	if (!file) {
1954 		err = -errno;
1955 		pr_warn("failed to open in-memory Kconfig: %d\n", err);
1956 		return err;
1957 	}
1958 
1959 	while (fgets(buf, sizeof(buf), file)) {
1960 		err = bpf_object__process_kconfig_line(obj, buf, data);
1961 		if (err) {
1962 			pr_warn("error parsing in-memory Kconfig line '%s': %d\n",
1963 				buf, err);
1964 			break;
1965 		}
1966 	}
1967 
1968 	fclose(file);
1969 	return err;
1970 }
1971 
1972 static int bpf_object__init_kconfig_map(struct bpf_object *obj)
1973 {
1974 	struct extern_desc *last_ext = NULL, *ext;
1975 	size_t map_sz;
1976 	int i, err;
1977 
1978 	for (i = 0; i < obj->nr_extern; i++) {
1979 		ext = &obj->externs[i];
1980 		if (ext->type == EXT_KCFG)
1981 			last_ext = ext;
1982 	}
1983 
1984 	if (!last_ext)
1985 		return 0;
1986 
1987 	map_sz = last_ext->kcfg.data_off + last_ext->kcfg.sz;
1988 	err = bpf_object__init_internal_map(obj, LIBBPF_MAP_KCONFIG,
1989 					    ".kconfig", obj->efile.symbols_shndx,
1990 					    NULL, map_sz);
1991 	if (err)
1992 		return err;
1993 
1994 	obj->kconfig_map_idx = obj->nr_maps - 1;
1995 
1996 	return 0;
1997 }
1998 
1999 const struct btf_type *
2000 skip_mods_and_typedefs(const struct btf *btf, __u32 id, __u32 *res_id)
2001 {
2002 	const struct btf_type *t = btf__type_by_id(btf, id);
2003 
2004 	if (res_id)
2005 		*res_id = id;
2006 
2007 	while (btf_is_mod(t) || btf_is_typedef(t)) {
2008 		if (res_id)
2009 			*res_id = t->type;
2010 		t = btf__type_by_id(btf, t->type);
2011 	}
2012 
2013 	return t;
2014 }
2015 
2016 static const struct btf_type *
2017 resolve_func_ptr(const struct btf *btf, __u32 id, __u32 *res_id)
2018 {
2019 	const struct btf_type *t;
2020 
2021 	t = skip_mods_and_typedefs(btf, id, NULL);
2022 	if (!btf_is_ptr(t))
2023 		return NULL;
2024 
2025 	t = skip_mods_and_typedefs(btf, t->type, res_id);
2026 
2027 	return btf_is_func_proto(t) ? t : NULL;
2028 }
2029 
2030 static const char *__btf_kind_str(__u16 kind)
2031 {
2032 	switch (kind) {
2033 	case BTF_KIND_UNKN: return "void";
2034 	case BTF_KIND_INT: return "int";
2035 	case BTF_KIND_PTR: return "ptr";
2036 	case BTF_KIND_ARRAY: return "array";
2037 	case BTF_KIND_STRUCT: return "struct";
2038 	case BTF_KIND_UNION: return "union";
2039 	case BTF_KIND_ENUM: return "enum";
2040 	case BTF_KIND_FWD: return "fwd";
2041 	case BTF_KIND_TYPEDEF: return "typedef";
2042 	case BTF_KIND_VOLATILE: return "volatile";
2043 	case BTF_KIND_CONST: return "const";
2044 	case BTF_KIND_RESTRICT: return "restrict";
2045 	case BTF_KIND_FUNC: return "func";
2046 	case BTF_KIND_FUNC_PROTO: return "func_proto";
2047 	case BTF_KIND_VAR: return "var";
2048 	case BTF_KIND_DATASEC: return "datasec";
2049 	case BTF_KIND_FLOAT: return "float";
2050 	case BTF_KIND_DECL_TAG: return "decl_tag";
2051 	case BTF_KIND_TYPE_TAG: return "type_tag";
2052 	case BTF_KIND_ENUM64: return "enum64";
2053 	default: return "unknown";
2054 	}
2055 }
2056 
2057 const char *btf_kind_str(const struct btf_type *t)
2058 {
2059 	return __btf_kind_str(btf_kind(t));
2060 }
2061 
2062 /*
2063  * Fetch integer attribute of BTF map definition. Such attributes are
2064  * represented using a pointer to an array, in which dimensionality of array
2065  * encodes specified integer value. E.g., int (*type)[BPF_MAP_TYPE_ARRAY];
2066  * encodes `type => BPF_MAP_TYPE_ARRAY` key/value pair completely using BTF
2067  * type definition, while using only sizeof(void *) space in ELF data section.
2068  */
2069 static bool get_map_field_int(const char *map_name, const struct btf *btf,
2070 			      const struct btf_member *m, __u32 *res)
2071 {
2072 	const struct btf_type *t = skip_mods_and_typedefs(btf, m->type, NULL);
2073 	const char *name = btf__name_by_offset(btf, m->name_off);
2074 	const struct btf_array *arr_info;
2075 	const struct btf_type *arr_t;
2076 
2077 	if (!btf_is_ptr(t)) {
2078 		pr_warn("map '%s': attr '%s': expected PTR, got %s.\n",
2079 			map_name, name, btf_kind_str(t));
2080 		return false;
2081 	}
2082 
2083 	arr_t = btf__type_by_id(btf, t->type);
2084 	if (!arr_t) {
2085 		pr_warn("map '%s': attr '%s': type [%u] not found.\n",
2086 			map_name, name, t->type);
2087 		return false;
2088 	}
2089 	if (!btf_is_array(arr_t)) {
2090 		pr_warn("map '%s': attr '%s': expected ARRAY, got %s.\n",
2091 			map_name, name, btf_kind_str(arr_t));
2092 		return false;
2093 	}
2094 	arr_info = btf_array(arr_t);
2095 	*res = arr_info->nelems;
2096 	return true;
2097 }
2098 
2099 static int build_map_pin_path(struct bpf_map *map, const char *path)
2100 {
2101 	char buf[PATH_MAX];
2102 	int len;
2103 
2104 	if (!path)
2105 		path = "/sys/fs/bpf";
2106 
2107 	len = snprintf(buf, PATH_MAX, "%s/%s", path, bpf_map__name(map));
2108 	if (len < 0)
2109 		return -EINVAL;
2110 	else if (len >= PATH_MAX)
2111 		return -ENAMETOOLONG;
2112 
2113 	return bpf_map__set_pin_path(map, buf);
2114 }
2115 
2116 /* should match definition in bpf_helpers.h */
2117 enum libbpf_pin_type {
2118 	LIBBPF_PIN_NONE,
2119 	/* PIN_BY_NAME: pin maps by name (in /sys/fs/bpf by default) */
2120 	LIBBPF_PIN_BY_NAME,
2121 };
2122 
2123 int parse_btf_map_def(const char *map_name, struct btf *btf,
2124 		      const struct btf_type *def_t, bool strict,
2125 		      struct btf_map_def *map_def, struct btf_map_def *inner_def)
2126 {
2127 	const struct btf_type *t;
2128 	const struct btf_member *m;
2129 	bool is_inner = inner_def == NULL;
2130 	int vlen, i;
2131 
2132 	vlen = btf_vlen(def_t);
2133 	m = btf_members(def_t);
2134 	for (i = 0; i < vlen; i++, m++) {
2135 		const char *name = btf__name_by_offset(btf, m->name_off);
2136 
2137 		if (!name) {
2138 			pr_warn("map '%s': invalid field #%d.\n", map_name, i);
2139 			return -EINVAL;
2140 		}
2141 		if (strcmp(name, "type") == 0) {
2142 			if (!get_map_field_int(map_name, btf, m, &map_def->map_type))
2143 				return -EINVAL;
2144 			map_def->parts |= MAP_DEF_MAP_TYPE;
2145 		} else if (strcmp(name, "max_entries") == 0) {
2146 			if (!get_map_field_int(map_name, btf, m, &map_def->max_entries))
2147 				return -EINVAL;
2148 			map_def->parts |= MAP_DEF_MAX_ENTRIES;
2149 		} else if (strcmp(name, "map_flags") == 0) {
2150 			if (!get_map_field_int(map_name, btf, m, &map_def->map_flags))
2151 				return -EINVAL;
2152 			map_def->parts |= MAP_DEF_MAP_FLAGS;
2153 		} else if (strcmp(name, "numa_node") == 0) {
2154 			if (!get_map_field_int(map_name, btf, m, &map_def->numa_node))
2155 				return -EINVAL;
2156 			map_def->parts |= MAP_DEF_NUMA_NODE;
2157 		} else if (strcmp(name, "key_size") == 0) {
2158 			__u32 sz;
2159 
2160 			if (!get_map_field_int(map_name, btf, m, &sz))
2161 				return -EINVAL;
2162 			if (map_def->key_size && map_def->key_size != sz) {
2163 				pr_warn("map '%s': conflicting key size %u != %u.\n",
2164 					map_name, map_def->key_size, sz);
2165 				return -EINVAL;
2166 			}
2167 			map_def->key_size = sz;
2168 			map_def->parts |= MAP_DEF_KEY_SIZE;
2169 		} else if (strcmp(name, "key") == 0) {
2170 			__s64 sz;
2171 
2172 			t = btf__type_by_id(btf, m->type);
2173 			if (!t) {
2174 				pr_warn("map '%s': key type [%d] not found.\n",
2175 					map_name, m->type);
2176 				return -EINVAL;
2177 			}
2178 			if (!btf_is_ptr(t)) {
2179 				pr_warn("map '%s': key spec is not PTR: %s.\n",
2180 					map_name, btf_kind_str(t));
2181 				return -EINVAL;
2182 			}
2183 			sz = btf__resolve_size(btf, t->type);
2184 			if (sz < 0) {
2185 				pr_warn("map '%s': can't determine key size for type [%u]: %zd.\n",
2186 					map_name, t->type, (ssize_t)sz);
2187 				return sz;
2188 			}
2189 			if (map_def->key_size && map_def->key_size != sz) {
2190 				pr_warn("map '%s': conflicting key size %u != %zd.\n",
2191 					map_name, map_def->key_size, (ssize_t)sz);
2192 				return -EINVAL;
2193 			}
2194 			map_def->key_size = sz;
2195 			map_def->key_type_id = t->type;
2196 			map_def->parts |= MAP_DEF_KEY_SIZE | MAP_DEF_KEY_TYPE;
2197 		} else if (strcmp(name, "value_size") == 0) {
2198 			__u32 sz;
2199 
2200 			if (!get_map_field_int(map_name, btf, m, &sz))
2201 				return -EINVAL;
2202 			if (map_def->value_size && map_def->value_size != sz) {
2203 				pr_warn("map '%s': conflicting value size %u != %u.\n",
2204 					map_name, map_def->value_size, sz);
2205 				return -EINVAL;
2206 			}
2207 			map_def->value_size = sz;
2208 			map_def->parts |= MAP_DEF_VALUE_SIZE;
2209 		} else if (strcmp(name, "value") == 0) {
2210 			__s64 sz;
2211 
2212 			t = btf__type_by_id(btf, m->type);
2213 			if (!t) {
2214 				pr_warn("map '%s': value type [%d] not found.\n",
2215 					map_name, m->type);
2216 				return -EINVAL;
2217 			}
2218 			if (!btf_is_ptr(t)) {
2219 				pr_warn("map '%s': value spec is not PTR: %s.\n",
2220 					map_name, btf_kind_str(t));
2221 				return -EINVAL;
2222 			}
2223 			sz = btf__resolve_size(btf, t->type);
2224 			if (sz < 0) {
2225 				pr_warn("map '%s': can't determine value size for type [%u]: %zd.\n",
2226 					map_name, t->type, (ssize_t)sz);
2227 				return sz;
2228 			}
2229 			if (map_def->value_size && map_def->value_size != sz) {
2230 				pr_warn("map '%s': conflicting value size %u != %zd.\n",
2231 					map_name, map_def->value_size, (ssize_t)sz);
2232 				return -EINVAL;
2233 			}
2234 			map_def->value_size = sz;
2235 			map_def->value_type_id = t->type;
2236 			map_def->parts |= MAP_DEF_VALUE_SIZE | MAP_DEF_VALUE_TYPE;
2237 		}
2238 		else if (strcmp(name, "values") == 0) {
2239 			bool is_map_in_map = bpf_map_type__is_map_in_map(map_def->map_type);
2240 			bool is_prog_array = map_def->map_type == BPF_MAP_TYPE_PROG_ARRAY;
2241 			const char *desc = is_map_in_map ? "map-in-map inner" : "prog-array value";
2242 			char inner_map_name[128];
2243 			int err;
2244 
2245 			if (is_inner) {
2246 				pr_warn("map '%s': multi-level inner maps not supported.\n",
2247 					map_name);
2248 				return -ENOTSUP;
2249 			}
2250 			if (i != vlen - 1) {
2251 				pr_warn("map '%s': '%s' member should be last.\n",
2252 					map_name, name);
2253 				return -EINVAL;
2254 			}
2255 			if (!is_map_in_map && !is_prog_array) {
2256 				pr_warn("map '%s': should be map-in-map or prog-array.\n",
2257 					map_name);
2258 				return -ENOTSUP;
2259 			}
2260 			if (map_def->value_size && map_def->value_size != 4) {
2261 				pr_warn("map '%s': conflicting value size %u != 4.\n",
2262 					map_name, map_def->value_size);
2263 				return -EINVAL;
2264 			}
2265 			map_def->value_size = 4;
2266 			t = btf__type_by_id(btf, m->type);
2267 			if (!t) {
2268 				pr_warn("map '%s': %s type [%d] not found.\n",
2269 					map_name, desc, m->type);
2270 				return -EINVAL;
2271 			}
2272 			if (!btf_is_array(t) || btf_array(t)->nelems) {
2273 				pr_warn("map '%s': %s spec is not a zero-sized array.\n",
2274 					map_name, desc);
2275 				return -EINVAL;
2276 			}
2277 			t = skip_mods_and_typedefs(btf, btf_array(t)->type, NULL);
2278 			if (!btf_is_ptr(t)) {
2279 				pr_warn("map '%s': %s def is of unexpected kind %s.\n",
2280 					map_name, desc, btf_kind_str(t));
2281 				return -EINVAL;
2282 			}
2283 			t = skip_mods_and_typedefs(btf, t->type, NULL);
2284 			if (is_prog_array) {
2285 				if (!btf_is_func_proto(t)) {
2286 					pr_warn("map '%s': prog-array value def is of unexpected kind %s.\n",
2287 						map_name, btf_kind_str(t));
2288 					return -EINVAL;
2289 				}
2290 				continue;
2291 			}
2292 			if (!btf_is_struct(t)) {
2293 				pr_warn("map '%s': map-in-map inner def is of unexpected kind %s.\n",
2294 					map_name, btf_kind_str(t));
2295 				return -EINVAL;
2296 			}
2297 
2298 			snprintf(inner_map_name, sizeof(inner_map_name), "%s.inner", map_name);
2299 			err = parse_btf_map_def(inner_map_name, btf, t, strict, inner_def, NULL);
2300 			if (err)
2301 				return err;
2302 
2303 			map_def->parts |= MAP_DEF_INNER_MAP;
2304 		} else if (strcmp(name, "pinning") == 0) {
2305 			__u32 val;
2306 
2307 			if (is_inner) {
2308 				pr_warn("map '%s': inner def can't be pinned.\n", map_name);
2309 				return -EINVAL;
2310 			}
2311 			if (!get_map_field_int(map_name, btf, m, &val))
2312 				return -EINVAL;
2313 			if (val != LIBBPF_PIN_NONE && val != LIBBPF_PIN_BY_NAME) {
2314 				pr_warn("map '%s': invalid pinning value %u.\n",
2315 					map_name, val);
2316 				return -EINVAL;
2317 			}
2318 			map_def->pinning = val;
2319 			map_def->parts |= MAP_DEF_PINNING;
2320 		} else if (strcmp(name, "map_extra") == 0) {
2321 			__u32 map_extra;
2322 
2323 			if (!get_map_field_int(map_name, btf, m, &map_extra))
2324 				return -EINVAL;
2325 			map_def->map_extra = map_extra;
2326 			map_def->parts |= MAP_DEF_MAP_EXTRA;
2327 		} else {
2328 			if (strict) {
2329 				pr_warn("map '%s': unknown field '%s'.\n", map_name, name);
2330 				return -ENOTSUP;
2331 			}
2332 			pr_debug("map '%s': ignoring unknown field '%s'.\n", map_name, name);
2333 		}
2334 	}
2335 
2336 	if (map_def->map_type == BPF_MAP_TYPE_UNSPEC) {
2337 		pr_warn("map '%s': map type isn't specified.\n", map_name);
2338 		return -EINVAL;
2339 	}
2340 
2341 	return 0;
2342 }
2343 
2344 static size_t adjust_ringbuf_sz(size_t sz)
2345 {
2346 	__u32 page_sz = sysconf(_SC_PAGE_SIZE);
2347 	__u32 mul;
2348 
2349 	/* if user forgot to set any size, make sure they see error */
2350 	if (sz == 0)
2351 		return 0;
2352 	/* Kernel expects BPF_MAP_TYPE_RINGBUF's max_entries to be
2353 	 * a power-of-2 multiple of kernel's page size. If user diligently
2354 	 * satisified these conditions, pass the size through.
2355 	 */
2356 	if ((sz % page_sz) == 0 && is_pow_of_2(sz / page_sz))
2357 		return sz;
2358 
2359 	/* Otherwise find closest (page_sz * power_of_2) product bigger than
2360 	 * user-set size to satisfy both user size request and kernel
2361 	 * requirements and substitute correct max_entries for map creation.
2362 	 */
2363 	for (mul = 1; mul <= UINT_MAX / page_sz; mul <<= 1) {
2364 		if (mul * page_sz > sz)
2365 			return mul * page_sz;
2366 	}
2367 
2368 	/* if it's impossible to satisfy the conditions (i.e., user size is
2369 	 * very close to UINT_MAX but is not a power-of-2 multiple of
2370 	 * page_size) then just return original size and let kernel reject it
2371 	 */
2372 	return sz;
2373 }
2374 
2375 static void fill_map_from_def(struct bpf_map *map, const struct btf_map_def *def)
2376 {
2377 	map->def.type = def->map_type;
2378 	map->def.key_size = def->key_size;
2379 	map->def.value_size = def->value_size;
2380 	map->def.max_entries = def->max_entries;
2381 	map->def.map_flags = def->map_flags;
2382 	map->map_extra = def->map_extra;
2383 
2384 	map->numa_node = def->numa_node;
2385 	map->btf_key_type_id = def->key_type_id;
2386 	map->btf_value_type_id = def->value_type_id;
2387 
2388 	/* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
2389 	if (map->def.type == BPF_MAP_TYPE_RINGBUF)
2390 		map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
2391 
2392 	if (def->parts & MAP_DEF_MAP_TYPE)
2393 		pr_debug("map '%s': found type = %u.\n", map->name, def->map_type);
2394 
2395 	if (def->parts & MAP_DEF_KEY_TYPE)
2396 		pr_debug("map '%s': found key [%u], sz = %u.\n",
2397 			 map->name, def->key_type_id, def->key_size);
2398 	else if (def->parts & MAP_DEF_KEY_SIZE)
2399 		pr_debug("map '%s': found key_size = %u.\n", map->name, def->key_size);
2400 
2401 	if (def->parts & MAP_DEF_VALUE_TYPE)
2402 		pr_debug("map '%s': found value [%u], sz = %u.\n",
2403 			 map->name, def->value_type_id, def->value_size);
2404 	else if (def->parts & MAP_DEF_VALUE_SIZE)
2405 		pr_debug("map '%s': found value_size = %u.\n", map->name, def->value_size);
2406 
2407 	if (def->parts & MAP_DEF_MAX_ENTRIES)
2408 		pr_debug("map '%s': found max_entries = %u.\n", map->name, def->max_entries);
2409 	if (def->parts & MAP_DEF_MAP_FLAGS)
2410 		pr_debug("map '%s': found map_flags = 0x%x.\n", map->name, def->map_flags);
2411 	if (def->parts & MAP_DEF_MAP_EXTRA)
2412 		pr_debug("map '%s': found map_extra = 0x%llx.\n", map->name,
2413 			 (unsigned long long)def->map_extra);
2414 	if (def->parts & MAP_DEF_PINNING)
2415 		pr_debug("map '%s': found pinning = %u.\n", map->name, def->pinning);
2416 	if (def->parts & MAP_DEF_NUMA_NODE)
2417 		pr_debug("map '%s': found numa_node = %u.\n", map->name, def->numa_node);
2418 
2419 	if (def->parts & MAP_DEF_INNER_MAP)
2420 		pr_debug("map '%s': found inner map definition.\n", map->name);
2421 }
2422 
2423 static const char *btf_var_linkage_str(__u32 linkage)
2424 {
2425 	switch (linkage) {
2426 	case BTF_VAR_STATIC: return "static";
2427 	case BTF_VAR_GLOBAL_ALLOCATED: return "global";
2428 	case BTF_VAR_GLOBAL_EXTERN: return "extern";
2429 	default: return "unknown";
2430 	}
2431 }
2432 
2433 static int bpf_object__init_user_btf_map(struct bpf_object *obj,
2434 					 const struct btf_type *sec,
2435 					 int var_idx, int sec_idx,
2436 					 const Elf_Data *data, bool strict,
2437 					 const char *pin_root_path)
2438 {
2439 	struct btf_map_def map_def = {}, inner_def = {};
2440 	const struct btf_type *var, *def;
2441 	const struct btf_var_secinfo *vi;
2442 	const struct btf_var *var_extra;
2443 	const char *map_name;
2444 	struct bpf_map *map;
2445 	int err;
2446 
2447 	vi = btf_var_secinfos(sec) + var_idx;
2448 	var = btf__type_by_id(obj->btf, vi->type);
2449 	var_extra = btf_var(var);
2450 	map_name = btf__name_by_offset(obj->btf, var->name_off);
2451 
2452 	if (map_name == NULL || map_name[0] == '\0') {
2453 		pr_warn("map #%d: empty name.\n", var_idx);
2454 		return -EINVAL;
2455 	}
2456 	if ((__u64)vi->offset + vi->size > data->d_size) {
2457 		pr_warn("map '%s' BTF data is corrupted.\n", map_name);
2458 		return -EINVAL;
2459 	}
2460 	if (!btf_is_var(var)) {
2461 		pr_warn("map '%s': unexpected var kind %s.\n",
2462 			map_name, btf_kind_str(var));
2463 		return -EINVAL;
2464 	}
2465 	if (var_extra->linkage != BTF_VAR_GLOBAL_ALLOCATED) {
2466 		pr_warn("map '%s': unsupported map linkage %s.\n",
2467 			map_name, btf_var_linkage_str(var_extra->linkage));
2468 		return -EOPNOTSUPP;
2469 	}
2470 
2471 	def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
2472 	if (!btf_is_struct(def)) {
2473 		pr_warn("map '%s': unexpected def kind %s.\n",
2474 			map_name, btf_kind_str(var));
2475 		return -EINVAL;
2476 	}
2477 	if (def->size > vi->size) {
2478 		pr_warn("map '%s': invalid def size.\n", map_name);
2479 		return -EINVAL;
2480 	}
2481 
2482 	map = bpf_object__add_map(obj);
2483 	if (IS_ERR(map))
2484 		return PTR_ERR(map);
2485 	map->name = strdup(map_name);
2486 	if (!map->name) {
2487 		pr_warn("map '%s': failed to alloc map name.\n", map_name);
2488 		return -ENOMEM;
2489 	}
2490 	map->libbpf_type = LIBBPF_MAP_UNSPEC;
2491 	map->def.type = BPF_MAP_TYPE_UNSPEC;
2492 	map->sec_idx = sec_idx;
2493 	map->sec_offset = vi->offset;
2494 	map->btf_var_idx = var_idx;
2495 	pr_debug("map '%s': at sec_idx %d, offset %zu.\n",
2496 		 map_name, map->sec_idx, map->sec_offset);
2497 
2498 	err = parse_btf_map_def(map->name, obj->btf, def, strict, &map_def, &inner_def);
2499 	if (err)
2500 		return err;
2501 
2502 	fill_map_from_def(map, &map_def);
2503 
2504 	if (map_def.pinning == LIBBPF_PIN_BY_NAME) {
2505 		err = build_map_pin_path(map, pin_root_path);
2506 		if (err) {
2507 			pr_warn("map '%s': couldn't build pin path.\n", map->name);
2508 			return err;
2509 		}
2510 	}
2511 
2512 	if (map_def.parts & MAP_DEF_INNER_MAP) {
2513 		map->inner_map = calloc(1, sizeof(*map->inner_map));
2514 		if (!map->inner_map)
2515 			return -ENOMEM;
2516 		map->inner_map->fd = -1;
2517 		map->inner_map->sec_idx = sec_idx;
2518 		map->inner_map->name = malloc(strlen(map_name) + sizeof(".inner") + 1);
2519 		if (!map->inner_map->name)
2520 			return -ENOMEM;
2521 		sprintf(map->inner_map->name, "%s.inner", map_name);
2522 
2523 		fill_map_from_def(map->inner_map, &inner_def);
2524 	}
2525 
2526 	err = bpf_map_find_btf_info(obj, map);
2527 	if (err)
2528 		return err;
2529 
2530 	return 0;
2531 }
2532 
2533 static int bpf_object__init_user_btf_maps(struct bpf_object *obj, bool strict,
2534 					  const char *pin_root_path)
2535 {
2536 	const struct btf_type *sec = NULL;
2537 	int nr_types, i, vlen, err;
2538 	const struct btf_type *t;
2539 	const char *name;
2540 	Elf_Data *data;
2541 	Elf_Scn *scn;
2542 
2543 	if (obj->efile.btf_maps_shndx < 0)
2544 		return 0;
2545 
2546 	scn = elf_sec_by_idx(obj, obj->efile.btf_maps_shndx);
2547 	data = elf_sec_data(obj, scn);
2548 	if (!scn || !data) {
2549 		pr_warn("elf: failed to get %s map definitions for %s\n",
2550 			MAPS_ELF_SEC, obj->path);
2551 		return -EINVAL;
2552 	}
2553 
2554 	nr_types = btf__type_cnt(obj->btf);
2555 	for (i = 1; i < nr_types; i++) {
2556 		t = btf__type_by_id(obj->btf, i);
2557 		if (!btf_is_datasec(t))
2558 			continue;
2559 		name = btf__name_by_offset(obj->btf, t->name_off);
2560 		if (strcmp(name, MAPS_ELF_SEC) == 0) {
2561 			sec = t;
2562 			obj->efile.btf_maps_sec_btf_id = i;
2563 			break;
2564 		}
2565 	}
2566 
2567 	if (!sec) {
2568 		pr_warn("DATASEC '%s' not found.\n", MAPS_ELF_SEC);
2569 		return -ENOENT;
2570 	}
2571 
2572 	vlen = btf_vlen(sec);
2573 	for (i = 0; i < vlen; i++) {
2574 		err = bpf_object__init_user_btf_map(obj, sec, i,
2575 						    obj->efile.btf_maps_shndx,
2576 						    data, strict,
2577 						    pin_root_path);
2578 		if (err)
2579 			return err;
2580 	}
2581 
2582 	return 0;
2583 }
2584 
2585 static int bpf_object__init_maps(struct bpf_object *obj,
2586 				 const struct bpf_object_open_opts *opts)
2587 {
2588 	const char *pin_root_path;
2589 	bool strict;
2590 	int err = 0;
2591 
2592 	strict = !OPTS_GET(opts, relaxed_maps, false);
2593 	pin_root_path = OPTS_GET(opts, pin_root_path, NULL);
2594 
2595 	err = err ?: bpf_object__init_user_btf_maps(obj, strict, pin_root_path);
2596 	err = err ?: bpf_object__init_global_data_maps(obj);
2597 	err = err ?: bpf_object__init_kconfig_map(obj);
2598 	err = err ?: bpf_object__init_struct_ops_maps(obj);
2599 
2600 	return err;
2601 }
2602 
2603 static bool section_have_execinstr(struct bpf_object *obj, int idx)
2604 {
2605 	Elf64_Shdr *sh;
2606 
2607 	sh = elf_sec_hdr(obj, elf_sec_by_idx(obj, idx));
2608 	if (!sh)
2609 		return false;
2610 
2611 	return sh->sh_flags & SHF_EXECINSTR;
2612 }
2613 
2614 static bool btf_needs_sanitization(struct bpf_object *obj)
2615 {
2616 	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
2617 	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
2618 	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
2619 	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
2620 	bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
2621 	bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
2622 	bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
2623 
2624 	return !has_func || !has_datasec || !has_func_global || !has_float ||
2625 	       !has_decl_tag || !has_type_tag || !has_enum64;
2626 }
2627 
2628 static int bpf_object__sanitize_btf(struct bpf_object *obj, struct btf *btf)
2629 {
2630 	bool has_func_global = kernel_supports(obj, FEAT_BTF_GLOBAL_FUNC);
2631 	bool has_datasec = kernel_supports(obj, FEAT_BTF_DATASEC);
2632 	bool has_float = kernel_supports(obj, FEAT_BTF_FLOAT);
2633 	bool has_func = kernel_supports(obj, FEAT_BTF_FUNC);
2634 	bool has_decl_tag = kernel_supports(obj, FEAT_BTF_DECL_TAG);
2635 	bool has_type_tag = kernel_supports(obj, FEAT_BTF_TYPE_TAG);
2636 	bool has_enum64 = kernel_supports(obj, FEAT_BTF_ENUM64);
2637 	int enum64_placeholder_id = 0;
2638 	struct btf_type *t;
2639 	int i, j, vlen;
2640 
2641 	for (i = 1; i < btf__type_cnt(btf); i++) {
2642 		t = (struct btf_type *)btf__type_by_id(btf, i);
2643 
2644 		if ((!has_datasec && btf_is_var(t)) || (!has_decl_tag && btf_is_decl_tag(t))) {
2645 			/* replace VAR/DECL_TAG with INT */
2646 			t->info = BTF_INFO_ENC(BTF_KIND_INT, 0, 0);
2647 			/*
2648 			 * using size = 1 is the safest choice, 4 will be too
2649 			 * big and cause kernel BTF validation failure if
2650 			 * original variable took less than 4 bytes
2651 			 */
2652 			t->size = 1;
2653 			*(int *)(t + 1) = BTF_INT_ENC(0, 0, 8);
2654 		} else if (!has_datasec && btf_is_datasec(t)) {
2655 			/* replace DATASEC with STRUCT */
2656 			const struct btf_var_secinfo *v = btf_var_secinfos(t);
2657 			struct btf_member *m = btf_members(t);
2658 			struct btf_type *vt;
2659 			char *name;
2660 
2661 			name = (char *)btf__name_by_offset(btf, t->name_off);
2662 			while (*name) {
2663 				if (*name == '.')
2664 					*name = '_';
2665 				name++;
2666 			}
2667 
2668 			vlen = btf_vlen(t);
2669 			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, vlen);
2670 			for (j = 0; j < vlen; j++, v++, m++) {
2671 				/* order of field assignments is important */
2672 				m->offset = v->offset * 8;
2673 				m->type = v->type;
2674 				/* preserve variable name as member name */
2675 				vt = (void *)btf__type_by_id(btf, v->type);
2676 				m->name_off = vt->name_off;
2677 			}
2678 		} else if (!has_func && btf_is_func_proto(t)) {
2679 			/* replace FUNC_PROTO with ENUM */
2680 			vlen = btf_vlen(t);
2681 			t->info = BTF_INFO_ENC(BTF_KIND_ENUM, 0, vlen);
2682 			t->size = sizeof(__u32); /* kernel enforced */
2683 		} else if (!has_func && btf_is_func(t)) {
2684 			/* replace FUNC with TYPEDEF */
2685 			t->info = BTF_INFO_ENC(BTF_KIND_TYPEDEF, 0, 0);
2686 		} else if (!has_func_global && btf_is_func(t)) {
2687 			/* replace BTF_FUNC_GLOBAL with BTF_FUNC_STATIC */
2688 			t->info = BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0);
2689 		} else if (!has_float && btf_is_float(t)) {
2690 			/* replace FLOAT with an equally-sized empty STRUCT;
2691 			 * since C compilers do not accept e.g. "float" as a
2692 			 * valid struct name, make it anonymous
2693 			 */
2694 			t->name_off = 0;
2695 			t->info = BTF_INFO_ENC(BTF_KIND_STRUCT, 0, 0);
2696 		} else if (!has_type_tag && btf_is_type_tag(t)) {
2697 			/* replace TYPE_TAG with a CONST */
2698 			t->name_off = 0;
2699 			t->info = BTF_INFO_ENC(BTF_KIND_CONST, 0, 0);
2700 		} else if (!has_enum64 && btf_is_enum(t)) {
2701 			/* clear the kflag */
2702 			t->info = btf_type_info(btf_kind(t), btf_vlen(t), false);
2703 		} else if (!has_enum64 && btf_is_enum64(t)) {
2704 			/* replace ENUM64 with a union */
2705 			struct btf_member *m;
2706 
2707 			if (enum64_placeholder_id == 0) {
2708 				enum64_placeholder_id = btf__add_int(btf, "enum64_placeholder", 1, 0);
2709 				if (enum64_placeholder_id < 0)
2710 					return enum64_placeholder_id;
2711 
2712 				t = (struct btf_type *)btf__type_by_id(btf, i);
2713 			}
2714 
2715 			m = btf_members(t);
2716 			vlen = btf_vlen(t);
2717 			t->info = BTF_INFO_ENC(BTF_KIND_UNION, 0, vlen);
2718 			for (j = 0; j < vlen; j++, m++) {
2719 				m->type = enum64_placeholder_id;
2720 				m->offset = 0;
2721 			}
2722                 }
2723 	}
2724 
2725 	return 0;
2726 }
2727 
2728 static bool libbpf_needs_btf(const struct bpf_object *obj)
2729 {
2730 	return obj->efile.btf_maps_shndx >= 0 ||
2731 	       obj->efile.st_ops_shndx >= 0 ||
2732 	       obj->nr_extern > 0;
2733 }
2734 
2735 static bool kernel_needs_btf(const struct bpf_object *obj)
2736 {
2737 	return obj->efile.st_ops_shndx >= 0;
2738 }
2739 
2740 static int bpf_object__init_btf(struct bpf_object *obj,
2741 				Elf_Data *btf_data,
2742 				Elf_Data *btf_ext_data)
2743 {
2744 	int err = -ENOENT;
2745 
2746 	if (btf_data) {
2747 		obj->btf = btf__new(btf_data->d_buf, btf_data->d_size);
2748 		err = libbpf_get_error(obj->btf);
2749 		if (err) {
2750 			obj->btf = NULL;
2751 			pr_warn("Error loading ELF section %s: %d.\n", BTF_ELF_SEC, err);
2752 			goto out;
2753 		}
2754 		/* enforce 8-byte pointers for BPF-targeted BTFs */
2755 		btf__set_pointer_size(obj->btf, 8);
2756 	}
2757 	if (btf_ext_data) {
2758 		struct btf_ext_info *ext_segs[3];
2759 		int seg_num, sec_num;
2760 
2761 		if (!obj->btf) {
2762 			pr_debug("Ignore ELF section %s because its depending ELF section %s is not found.\n",
2763 				 BTF_EXT_ELF_SEC, BTF_ELF_SEC);
2764 			goto out;
2765 		}
2766 		obj->btf_ext = btf_ext__new(btf_ext_data->d_buf, btf_ext_data->d_size);
2767 		err = libbpf_get_error(obj->btf_ext);
2768 		if (err) {
2769 			pr_warn("Error loading ELF section %s: %d. Ignored and continue.\n",
2770 				BTF_EXT_ELF_SEC, err);
2771 			obj->btf_ext = NULL;
2772 			goto out;
2773 		}
2774 
2775 		/* setup .BTF.ext to ELF section mapping */
2776 		ext_segs[0] = &obj->btf_ext->func_info;
2777 		ext_segs[1] = &obj->btf_ext->line_info;
2778 		ext_segs[2] = &obj->btf_ext->core_relo_info;
2779 		for (seg_num = 0; seg_num < ARRAY_SIZE(ext_segs); seg_num++) {
2780 			struct btf_ext_info *seg = ext_segs[seg_num];
2781 			const struct btf_ext_info_sec *sec;
2782 			const char *sec_name;
2783 			Elf_Scn *scn;
2784 
2785 			if (seg->sec_cnt == 0)
2786 				continue;
2787 
2788 			seg->sec_idxs = calloc(seg->sec_cnt, sizeof(*seg->sec_idxs));
2789 			if (!seg->sec_idxs) {
2790 				err = -ENOMEM;
2791 				goto out;
2792 			}
2793 
2794 			sec_num = 0;
2795 			for_each_btf_ext_sec(seg, sec) {
2796 				/* preventively increment index to avoid doing
2797 				 * this before every continue below
2798 				 */
2799 				sec_num++;
2800 
2801 				sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
2802 				if (str_is_empty(sec_name))
2803 					continue;
2804 				scn = elf_sec_by_name(obj, sec_name);
2805 				if (!scn)
2806 					continue;
2807 
2808 				seg->sec_idxs[sec_num - 1] = elf_ndxscn(scn);
2809 			}
2810 		}
2811 	}
2812 out:
2813 	if (err && libbpf_needs_btf(obj)) {
2814 		pr_warn("BTF is required, but is missing or corrupted.\n");
2815 		return err;
2816 	}
2817 	return 0;
2818 }
2819 
2820 static int compare_vsi_off(const void *_a, const void *_b)
2821 {
2822 	const struct btf_var_secinfo *a = _a;
2823 	const struct btf_var_secinfo *b = _b;
2824 
2825 	return a->offset - b->offset;
2826 }
2827 
2828 static int btf_fixup_datasec(struct bpf_object *obj, struct btf *btf,
2829 			     struct btf_type *t)
2830 {
2831 	__u32 size = 0, off = 0, i, vars = btf_vlen(t);
2832 	const char *name = btf__name_by_offset(btf, t->name_off);
2833 	const struct btf_type *t_var;
2834 	struct btf_var_secinfo *vsi;
2835 	const struct btf_var *var;
2836 	int ret;
2837 
2838 	if (!name) {
2839 		pr_debug("No name found in string section for DATASEC kind.\n");
2840 		return -ENOENT;
2841 	}
2842 
2843 	/* .extern datasec size and var offsets were set correctly during
2844 	 * extern collection step, so just skip straight to sorting variables
2845 	 */
2846 	if (t->size)
2847 		goto sort_vars;
2848 
2849 	ret = find_elf_sec_sz(obj, name, &size);
2850 	if (ret || !size) {
2851 		pr_debug("Invalid size for section %s: %u bytes\n", name, size);
2852 		return -ENOENT;
2853 	}
2854 
2855 	t->size = size;
2856 
2857 	for (i = 0, vsi = btf_var_secinfos(t); i < vars; i++, vsi++) {
2858 		t_var = btf__type_by_id(btf, vsi->type);
2859 		if (!t_var || !btf_is_var(t_var)) {
2860 			pr_debug("Non-VAR type seen in section %s\n", name);
2861 			return -EINVAL;
2862 		}
2863 
2864 		var = btf_var(t_var);
2865 		if (var->linkage == BTF_VAR_STATIC)
2866 			continue;
2867 
2868 		name = btf__name_by_offset(btf, t_var->name_off);
2869 		if (!name) {
2870 			pr_debug("No name found in string section for VAR kind\n");
2871 			return -ENOENT;
2872 		}
2873 
2874 		ret = find_elf_var_offset(obj, name, &off);
2875 		if (ret) {
2876 			pr_debug("No offset found in symbol table for VAR %s\n",
2877 				 name);
2878 			return -ENOENT;
2879 		}
2880 
2881 		vsi->offset = off;
2882 	}
2883 
2884 sort_vars:
2885 	qsort(btf_var_secinfos(t), vars, sizeof(*vsi), compare_vsi_off);
2886 	return 0;
2887 }
2888 
2889 static int btf_finalize_data(struct bpf_object *obj, struct btf *btf)
2890 {
2891 	int err = 0;
2892 	__u32 i, n = btf__type_cnt(btf);
2893 
2894 	for (i = 1; i < n; i++) {
2895 		struct btf_type *t = btf_type_by_id(btf, i);
2896 
2897 		/* Loader needs to fix up some of the things compiler
2898 		 * couldn't get its hands on while emitting BTF. This
2899 		 * is section size and global variable offset. We use
2900 		 * the info from the ELF itself for this purpose.
2901 		 */
2902 		if (btf_is_datasec(t)) {
2903 			err = btf_fixup_datasec(obj, btf, t);
2904 			if (err)
2905 				break;
2906 		}
2907 	}
2908 
2909 	return libbpf_err(err);
2910 }
2911 
2912 static int bpf_object__finalize_btf(struct bpf_object *obj)
2913 {
2914 	int err;
2915 
2916 	if (!obj->btf)
2917 		return 0;
2918 
2919 	err = btf_finalize_data(obj, obj->btf);
2920 	if (err) {
2921 		pr_warn("Error finalizing %s: %d.\n", BTF_ELF_SEC, err);
2922 		return err;
2923 	}
2924 
2925 	return 0;
2926 }
2927 
2928 static bool prog_needs_vmlinux_btf(struct bpf_program *prog)
2929 {
2930 	if (prog->type == BPF_PROG_TYPE_STRUCT_OPS ||
2931 	    prog->type == BPF_PROG_TYPE_LSM)
2932 		return true;
2933 
2934 	/* BPF_PROG_TYPE_TRACING programs which do not attach to other programs
2935 	 * also need vmlinux BTF
2936 	 */
2937 	if (prog->type == BPF_PROG_TYPE_TRACING && !prog->attach_prog_fd)
2938 		return true;
2939 
2940 	return false;
2941 }
2942 
2943 static bool obj_needs_vmlinux_btf(const struct bpf_object *obj)
2944 {
2945 	struct bpf_program *prog;
2946 	int i;
2947 
2948 	/* CO-RE relocations need kernel BTF, only when btf_custom_path
2949 	 * is not specified
2950 	 */
2951 	if (obj->btf_ext && obj->btf_ext->core_relo_info.len && !obj->btf_custom_path)
2952 		return true;
2953 
2954 	/* Support for typed ksyms needs kernel BTF */
2955 	for (i = 0; i < obj->nr_extern; i++) {
2956 		const struct extern_desc *ext;
2957 
2958 		ext = &obj->externs[i];
2959 		if (ext->type == EXT_KSYM && ext->ksym.type_id)
2960 			return true;
2961 	}
2962 
2963 	bpf_object__for_each_program(prog, obj) {
2964 		if (!prog->autoload)
2965 			continue;
2966 		if (prog_needs_vmlinux_btf(prog))
2967 			return true;
2968 	}
2969 
2970 	return false;
2971 }
2972 
2973 static int bpf_object__load_vmlinux_btf(struct bpf_object *obj, bool force)
2974 {
2975 	int err;
2976 
2977 	/* btf_vmlinux could be loaded earlier */
2978 	if (obj->btf_vmlinux || obj->gen_loader)
2979 		return 0;
2980 
2981 	if (!force && !obj_needs_vmlinux_btf(obj))
2982 		return 0;
2983 
2984 	obj->btf_vmlinux = btf__load_vmlinux_btf();
2985 	err = libbpf_get_error(obj->btf_vmlinux);
2986 	if (err) {
2987 		pr_warn("Error loading vmlinux BTF: %d\n", err);
2988 		obj->btf_vmlinux = NULL;
2989 		return err;
2990 	}
2991 	return 0;
2992 }
2993 
2994 static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
2995 {
2996 	struct btf *kern_btf = obj->btf;
2997 	bool btf_mandatory, sanitize;
2998 	int i, err = 0;
2999 
3000 	if (!obj->btf)
3001 		return 0;
3002 
3003 	if (!kernel_supports(obj, FEAT_BTF)) {
3004 		if (kernel_needs_btf(obj)) {
3005 			err = -EOPNOTSUPP;
3006 			goto report;
3007 		}
3008 		pr_debug("Kernel doesn't support BTF, skipping uploading it.\n");
3009 		return 0;
3010 	}
3011 
3012 	/* Even though some subprogs are global/weak, user might prefer more
3013 	 * permissive BPF verification process that BPF verifier performs for
3014 	 * static functions, taking into account more context from the caller
3015 	 * functions. In such case, they need to mark such subprogs with
3016 	 * __attribute__((visibility("hidden"))) and libbpf will adjust
3017 	 * corresponding FUNC BTF type to be marked as static and trigger more
3018 	 * involved BPF verification process.
3019 	 */
3020 	for (i = 0; i < obj->nr_programs; i++) {
3021 		struct bpf_program *prog = &obj->programs[i];
3022 		struct btf_type *t;
3023 		const char *name;
3024 		int j, n;
3025 
3026 		if (!prog->mark_btf_static || !prog_is_subprog(obj, prog))
3027 			continue;
3028 
3029 		n = btf__type_cnt(obj->btf);
3030 		for (j = 1; j < n; j++) {
3031 			t = btf_type_by_id(obj->btf, j);
3032 			if (!btf_is_func(t) || btf_func_linkage(t) != BTF_FUNC_GLOBAL)
3033 				continue;
3034 
3035 			name = btf__str_by_offset(obj->btf, t->name_off);
3036 			if (strcmp(name, prog->name) != 0)
3037 				continue;
3038 
3039 			t->info = btf_type_info(BTF_KIND_FUNC, BTF_FUNC_STATIC, 0);
3040 			break;
3041 		}
3042 	}
3043 
3044 	sanitize = btf_needs_sanitization(obj);
3045 	if (sanitize) {
3046 		const void *raw_data;
3047 		__u32 sz;
3048 
3049 		/* clone BTF to sanitize a copy and leave the original intact */
3050 		raw_data = btf__raw_data(obj->btf, &sz);
3051 		kern_btf = btf__new(raw_data, sz);
3052 		err = libbpf_get_error(kern_btf);
3053 		if (err)
3054 			return err;
3055 
3056 		/* enforce 8-byte pointers for BPF-targeted BTFs */
3057 		btf__set_pointer_size(obj->btf, 8);
3058 		err = bpf_object__sanitize_btf(obj, kern_btf);
3059 		if (err)
3060 			return err;
3061 	}
3062 
3063 	if (obj->gen_loader) {
3064 		__u32 raw_size = 0;
3065 		const void *raw_data = btf__raw_data(kern_btf, &raw_size);
3066 
3067 		if (!raw_data)
3068 			return -ENOMEM;
3069 		bpf_gen__load_btf(obj->gen_loader, raw_data, raw_size);
3070 		/* Pretend to have valid FD to pass various fd >= 0 checks.
3071 		 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
3072 		 */
3073 		btf__set_fd(kern_btf, 0);
3074 	} else {
3075 		/* currently BPF_BTF_LOAD only supports log_level 1 */
3076 		err = btf_load_into_kernel(kern_btf, obj->log_buf, obj->log_size,
3077 					   obj->log_level ? 1 : 0);
3078 	}
3079 	if (sanitize) {
3080 		if (!err) {
3081 			/* move fd to libbpf's BTF */
3082 			btf__set_fd(obj->btf, btf__fd(kern_btf));
3083 			btf__set_fd(kern_btf, -1);
3084 		}
3085 		btf__free(kern_btf);
3086 	}
3087 report:
3088 	if (err) {
3089 		btf_mandatory = kernel_needs_btf(obj);
3090 		pr_warn("Error loading .BTF into kernel: %d. %s\n", err,
3091 			btf_mandatory ? "BTF is mandatory, can't proceed."
3092 				      : "BTF is optional, ignoring.");
3093 		if (!btf_mandatory)
3094 			err = 0;
3095 	}
3096 	return err;
3097 }
3098 
3099 static const char *elf_sym_str(const struct bpf_object *obj, size_t off)
3100 {
3101 	const char *name;
3102 
3103 	name = elf_strptr(obj->efile.elf, obj->efile.strtabidx, off);
3104 	if (!name) {
3105 		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3106 			off, obj->path, elf_errmsg(-1));
3107 		return NULL;
3108 	}
3109 
3110 	return name;
3111 }
3112 
3113 static const char *elf_sec_str(const struct bpf_object *obj, size_t off)
3114 {
3115 	const char *name;
3116 
3117 	name = elf_strptr(obj->efile.elf, obj->efile.shstrndx, off);
3118 	if (!name) {
3119 		pr_warn("elf: failed to get section name string at offset %zu from %s: %s\n",
3120 			off, obj->path, elf_errmsg(-1));
3121 		return NULL;
3122 	}
3123 
3124 	return name;
3125 }
3126 
3127 static Elf_Scn *elf_sec_by_idx(const struct bpf_object *obj, size_t idx)
3128 {
3129 	Elf_Scn *scn;
3130 
3131 	scn = elf_getscn(obj->efile.elf, idx);
3132 	if (!scn) {
3133 		pr_warn("elf: failed to get section(%zu) from %s: %s\n",
3134 			idx, obj->path, elf_errmsg(-1));
3135 		return NULL;
3136 	}
3137 	return scn;
3138 }
3139 
3140 static Elf_Scn *elf_sec_by_name(const struct bpf_object *obj, const char *name)
3141 {
3142 	Elf_Scn *scn = NULL;
3143 	Elf *elf = obj->efile.elf;
3144 	const char *sec_name;
3145 
3146 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3147 		sec_name = elf_sec_name(obj, scn);
3148 		if (!sec_name)
3149 			return NULL;
3150 
3151 		if (strcmp(sec_name, name) != 0)
3152 			continue;
3153 
3154 		return scn;
3155 	}
3156 	return NULL;
3157 }
3158 
3159 static Elf64_Shdr *elf_sec_hdr(const struct bpf_object *obj, Elf_Scn *scn)
3160 {
3161 	Elf64_Shdr *shdr;
3162 
3163 	if (!scn)
3164 		return NULL;
3165 
3166 	shdr = elf64_getshdr(scn);
3167 	if (!shdr) {
3168 		pr_warn("elf: failed to get section(%zu) header from %s: %s\n",
3169 			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3170 		return NULL;
3171 	}
3172 
3173 	return shdr;
3174 }
3175 
3176 static const char *elf_sec_name(const struct bpf_object *obj, Elf_Scn *scn)
3177 {
3178 	const char *name;
3179 	Elf64_Shdr *sh;
3180 
3181 	if (!scn)
3182 		return NULL;
3183 
3184 	sh = elf_sec_hdr(obj, scn);
3185 	if (!sh)
3186 		return NULL;
3187 
3188 	name = elf_sec_str(obj, sh->sh_name);
3189 	if (!name) {
3190 		pr_warn("elf: failed to get section(%zu) name from %s: %s\n",
3191 			elf_ndxscn(scn), obj->path, elf_errmsg(-1));
3192 		return NULL;
3193 	}
3194 
3195 	return name;
3196 }
3197 
3198 static Elf_Data *elf_sec_data(const struct bpf_object *obj, Elf_Scn *scn)
3199 {
3200 	Elf_Data *data;
3201 
3202 	if (!scn)
3203 		return NULL;
3204 
3205 	data = elf_getdata(scn, 0);
3206 	if (!data) {
3207 		pr_warn("elf: failed to get section(%zu) %s data from %s: %s\n",
3208 			elf_ndxscn(scn), elf_sec_name(obj, scn) ?: "<?>",
3209 			obj->path, elf_errmsg(-1));
3210 		return NULL;
3211 	}
3212 
3213 	return data;
3214 }
3215 
3216 static Elf64_Sym *elf_sym_by_idx(const struct bpf_object *obj, size_t idx)
3217 {
3218 	if (idx >= obj->efile.symbols->d_size / sizeof(Elf64_Sym))
3219 		return NULL;
3220 
3221 	return (Elf64_Sym *)obj->efile.symbols->d_buf + idx;
3222 }
3223 
3224 static Elf64_Rel *elf_rel_by_idx(Elf_Data *data, size_t idx)
3225 {
3226 	if (idx >= data->d_size / sizeof(Elf64_Rel))
3227 		return NULL;
3228 
3229 	return (Elf64_Rel *)data->d_buf + idx;
3230 }
3231 
3232 static bool is_sec_name_dwarf(const char *name)
3233 {
3234 	/* approximation, but the actual list is too long */
3235 	return str_has_pfx(name, ".debug_");
3236 }
3237 
3238 static bool ignore_elf_section(Elf64_Shdr *hdr, const char *name)
3239 {
3240 	/* no special handling of .strtab */
3241 	if (hdr->sh_type == SHT_STRTAB)
3242 		return true;
3243 
3244 	/* ignore .llvm_addrsig section as well */
3245 	if (hdr->sh_type == SHT_LLVM_ADDRSIG)
3246 		return true;
3247 
3248 	/* no subprograms will lead to an empty .text section, ignore it */
3249 	if (hdr->sh_type == SHT_PROGBITS && hdr->sh_size == 0 &&
3250 	    strcmp(name, ".text") == 0)
3251 		return true;
3252 
3253 	/* DWARF sections */
3254 	if (is_sec_name_dwarf(name))
3255 		return true;
3256 
3257 	if (str_has_pfx(name, ".rel")) {
3258 		name += sizeof(".rel") - 1;
3259 		/* DWARF section relocations */
3260 		if (is_sec_name_dwarf(name))
3261 			return true;
3262 
3263 		/* .BTF and .BTF.ext don't need relocations */
3264 		if (strcmp(name, BTF_ELF_SEC) == 0 ||
3265 		    strcmp(name, BTF_EXT_ELF_SEC) == 0)
3266 			return true;
3267 	}
3268 
3269 	return false;
3270 }
3271 
3272 static int cmp_progs(const void *_a, const void *_b)
3273 {
3274 	const struct bpf_program *a = _a;
3275 	const struct bpf_program *b = _b;
3276 
3277 	if (a->sec_idx != b->sec_idx)
3278 		return a->sec_idx < b->sec_idx ? -1 : 1;
3279 
3280 	/* sec_insn_off can't be the same within the section */
3281 	return a->sec_insn_off < b->sec_insn_off ? -1 : 1;
3282 }
3283 
3284 static int bpf_object__elf_collect(struct bpf_object *obj)
3285 {
3286 	struct elf_sec_desc *sec_desc;
3287 	Elf *elf = obj->efile.elf;
3288 	Elf_Data *btf_ext_data = NULL;
3289 	Elf_Data *btf_data = NULL;
3290 	int idx = 0, err = 0;
3291 	const char *name;
3292 	Elf_Data *data;
3293 	Elf_Scn *scn;
3294 	Elf64_Shdr *sh;
3295 
3296 	/* ELF section indices are 0-based, but sec #0 is special "invalid"
3297 	 * section. e_shnum does include sec #0, so e_shnum is the necessary
3298 	 * size of an array to keep all the sections.
3299 	 */
3300 	obj->efile.sec_cnt = obj->efile.ehdr->e_shnum;
3301 	obj->efile.secs = calloc(obj->efile.sec_cnt, sizeof(*obj->efile.secs));
3302 	if (!obj->efile.secs)
3303 		return -ENOMEM;
3304 
3305 	/* a bunch of ELF parsing functionality depends on processing symbols,
3306 	 * so do the first pass and find the symbol table
3307 	 */
3308 	scn = NULL;
3309 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3310 		sh = elf_sec_hdr(obj, scn);
3311 		if (!sh)
3312 			return -LIBBPF_ERRNO__FORMAT;
3313 
3314 		if (sh->sh_type == SHT_SYMTAB) {
3315 			if (obj->efile.symbols) {
3316 				pr_warn("elf: multiple symbol tables in %s\n", obj->path);
3317 				return -LIBBPF_ERRNO__FORMAT;
3318 			}
3319 
3320 			data = elf_sec_data(obj, scn);
3321 			if (!data)
3322 				return -LIBBPF_ERRNO__FORMAT;
3323 
3324 			idx = elf_ndxscn(scn);
3325 
3326 			obj->efile.symbols = data;
3327 			obj->efile.symbols_shndx = idx;
3328 			obj->efile.strtabidx = sh->sh_link;
3329 		}
3330 	}
3331 
3332 	if (!obj->efile.symbols) {
3333 		pr_warn("elf: couldn't find symbol table in %s, stripped object file?\n",
3334 			obj->path);
3335 		return -ENOENT;
3336 	}
3337 
3338 	scn = NULL;
3339 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
3340 		idx = elf_ndxscn(scn);
3341 		sec_desc = &obj->efile.secs[idx];
3342 
3343 		sh = elf_sec_hdr(obj, scn);
3344 		if (!sh)
3345 			return -LIBBPF_ERRNO__FORMAT;
3346 
3347 		name = elf_sec_str(obj, sh->sh_name);
3348 		if (!name)
3349 			return -LIBBPF_ERRNO__FORMAT;
3350 
3351 		if (ignore_elf_section(sh, name))
3352 			continue;
3353 
3354 		data = elf_sec_data(obj, scn);
3355 		if (!data)
3356 			return -LIBBPF_ERRNO__FORMAT;
3357 
3358 		pr_debug("elf: section(%d) %s, size %ld, link %d, flags %lx, type=%d\n",
3359 			 idx, name, (unsigned long)data->d_size,
3360 			 (int)sh->sh_link, (unsigned long)sh->sh_flags,
3361 			 (int)sh->sh_type);
3362 
3363 		if (strcmp(name, "license") == 0) {
3364 			err = bpf_object__init_license(obj, data->d_buf, data->d_size);
3365 			if (err)
3366 				return err;
3367 		} else if (strcmp(name, "version") == 0) {
3368 			err = bpf_object__init_kversion(obj, data->d_buf, data->d_size);
3369 			if (err)
3370 				return err;
3371 		} else if (strcmp(name, "maps") == 0) {
3372 			pr_warn("elf: legacy map definitions in 'maps' section are not supported by libbpf v1.0+\n");
3373 			return -ENOTSUP;
3374 		} else if (strcmp(name, MAPS_ELF_SEC) == 0) {
3375 			obj->efile.btf_maps_shndx = idx;
3376 		} else if (strcmp(name, BTF_ELF_SEC) == 0) {
3377 			if (sh->sh_type != SHT_PROGBITS)
3378 				return -LIBBPF_ERRNO__FORMAT;
3379 			btf_data = data;
3380 		} else if (strcmp(name, BTF_EXT_ELF_SEC) == 0) {
3381 			if (sh->sh_type != SHT_PROGBITS)
3382 				return -LIBBPF_ERRNO__FORMAT;
3383 			btf_ext_data = data;
3384 		} else if (sh->sh_type == SHT_SYMTAB) {
3385 			/* already processed during the first pass above */
3386 		} else if (sh->sh_type == SHT_PROGBITS && data->d_size > 0) {
3387 			if (sh->sh_flags & SHF_EXECINSTR) {
3388 				if (strcmp(name, ".text") == 0)
3389 					obj->efile.text_shndx = idx;
3390 				err = bpf_object__add_programs(obj, data, name, idx);
3391 				if (err)
3392 					return err;
3393 			} else if (strcmp(name, DATA_SEC) == 0 ||
3394 				   str_has_pfx(name, DATA_SEC ".")) {
3395 				sec_desc->sec_type = SEC_DATA;
3396 				sec_desc->shdr = sh;
3397 				sec_desc->data = data;
3398 			} else if (strcmp(name, RODATA_SEC) == 0 ||
3399 				   str_has_pfx(name, RODATA_SEC ".")) {
3400 				sec_desc->sec_type = SEC_RODATA;
3401 				sec_desc->shdr = sh;
3402 				sec_desc->data = data;
3403 			} else if (strcmp(name, STRUCT_OPS_SEC) == 0) {
3404 				obj->efile.st_ops_data = data;
3405 				obj->efile.st_ops_shndx = idx;
3406 			} else {
3407 				pr_info("elf: skipping unrecognized data section(%d) %s\n",
3408 					idx, name);
3409 			}
3410 		} else if (sh->sh_type == SHT_REL) {
3411 			int targ_sec_idx = sh->sh_info; /* points to other section */
3412 
3413 			if (sh->sh_entsize != sizeof(Elf64_Rel) ||
3414 			    targ_sec_idx >= obj->efile.sec_cnt)
3415 				return -LIBBPF_ERRNO__FORMAT;
3416 
3417 			/* Only do relo for section with exec instructions */
3418 			if (!section_have_execinstr(obj, targ_sec_idx) &&
3419 			    strcmp(name, ".rel" STRUCT_OPS_SEC) &&
3420 			    strcmp(name, ".rel" MAPS_ELF_SEC)) {
3421 				pr_info("elf: skipping relo section(%d) %s for section(%d) %s\n",
3422 					idx, name, targ_sec_idx,
3423 					elf_sec_name(obj, elf_sec_by_idx(obj, targ_sec_idx)) ?: "<?>");
3424 				continue;
3425 			}
3426 
3427 			sec_desc->sec_type = SEC_RELO;
3428 			sec_desc->shdr = sh;
3429 			sec_desc->data = data;
3430 		} else if (sh->sh_type == SHT_NOBITS && strcmp(name, BSS_SEC) == 0) {
3431 			sec_desc->sec_type = SEC_BSS;
3432 			sec_desc->shdr = sh;
3433 			sec_desc->data = data;
3434 		} else {
3435 			pr_info("elf: skipping section(%d) %s (size %zu)\n", idx, name,
3436 				(size_t)sh->sh_size);
3437 		}
3438 	}
3439 
3440 	if (!obj->efile.strtabidx || obj->efile.strtabidx > idx) {
3441 		pr_warn("elf: symbol strings section missing or invalid in %s\n", obj->path);
3442 		return -LIBBPF_ERRNO__FORMAT;
3443 	}
3444 
3445 	/* sort BPF programs by section name and in-section instruction offset
3446 	 * for faster search */
3447 	if (obj->nr_programs)
3448 		qsort(obj->programs, obj->nr_programs, sizeof(*obj->programs), cmp_progs);
3449 
3450 	return bpf_object__init_btf(obj, btf_data, btf_ext_data);
3451 }
3452 
3453 static bool sym_is_extern(const Elf64_Sym *sym)
3454 {
3455 	int bind = ELF64_ST_BIND(sym->st_info);
3456 	/* externs are symbols w/ type=NOTYPE, bind=GLOBAL|WEAK, section=UND */
3457 	return sym->st_shndx == SHN_UNDEF &&
3458 	       (bind == STB_GLOBAL || bind == STB_WEAK) &&
3459 	       ELF64_ST_TYPE(sym->st_info) == STT_NOTYPE;
3460 }
3461 
3462 static bool sym_is_subprog(const Elf64_Sym *sym, int text_shndx)
3463 {
3464 	int bind = ELF64_ST_BIND(sym->st_info);
3465 	int type = ELF64_ST_TYPE(sym->st_info);
3466 
3467 	/* in .text section */
3468 	if (sym->st_shndx != text_shndx)
3469 		return false;
3470 
3471 	/* local function */
3472 	if (bind == STB_LOCAL && type == STT_SECTION)
3473 		return true;
3474 
3475 	/* global function */
3476 	return bind == STB_GLOBAL && type == STT_FUNC;
3477 }
3478 
3479 static int find_extern_btf_id(const struct btf *btf, const char *ext_name)
3480 {
3481 	const struct btf_type *t;
3482 	const char *tname;
3483 	int i, n;
3484 
3485 	if (!btf)
3486 		return -ESRCH;
3487 
3488 	n = btf__type_cnt(btf);
3489 	for (i = 1; i < n; i++) {
3490 		t = btf__type_by_id(btf, i);
3491 
3492 		if (!btf_is_var(t) && !btf_is_func(t))
3493 			continue;
3494 
3495 		tname = btf__name_by_offset(btf, t->name_off);
3496 		if (strcmp(tname, ext_name))
3497 			continue;
3498 
3499 		if (btf_is_var(t) &&
3500 		    btf_var(t)->linkage != BTF_VAR_GLOBAL_EXTERN)
3501 			return -EINVAL;
3502 
3503 		if (btf_is_func(t) && btf_func_linkage(t) != BTF_FUNC_EXTERN)
3504 			return -EINVAL;
3505 
3506 		return i;
3507 	}
3508 
3509 	return -ENOENT;
3510 }
3511 
3512 static int find_extern_sec_btf_id(struct btf *btf, int ext_btf_id) {
3513 	const struct btf_var_secinfo *vs;
3514 	const struct btf_type *t;
3515 	int i, j, n;
3516 
3517 	if (!btf)
3518 		return -ESRCH;
3519 
3520 	n = btf__type_cnt(btf);
3521 	for (i = 1; i < n; i++) {
3522 		t = btf__type_by_id(btf, i);
3523 
3524 		if (!btf_is_datasec(t))
3525 			continue;
3526 
3527 		vs = btf_var_secinfos(t);
3528 		for (j = 0; j < btf_vlen(t); j++, vs++) {
3529 			if (vs->type == ext_btf_id)
3530 				return i;
3531 		}
3532 	}
3533 
3534 	return -ENOENT;
3535 }
3536 
3537 static enum kcfg_type find_kcfg_type(const struct btf *btf, int id,
3538 				     bool *is_signed)
3539 {
3540 	const struct btf_type *t;
3541 	const char *name;
3542 
3543 	t = skip_mods_and_typedefs(btf, id, NULL);
3544 	name = btf__name_by_offset(btf, t->name_off);
3545 
3546 	if (is_signed)
3547 		*is_signed = false;
3548 	switch (btf_kind(t)) {
3549 	case BTF_KIND_INT: {
3550 		int enc = btf_int_encoding(t);
3551 
3552 		if (enc & BTF_INT_BOOL)
3553 			return t->size == 1 ? KCFG_BOOL : KCFG_UNKNOWN;
3554 		if (is_signed)
3555 			*is_signed = enc & BTF_INT_SIGNED;
3556 		if (t->size == 1)
3557 			return KCFG_CHAR;
3558 		if (t->size < 1 || t->size > 8 || (t->size & (t->size - 1)))
3559 			return KCFG_UNKNOWN;
3560 		return KCFG_INT;
3561 	}
3562 	case BTF_KIND_ENUM:
3563 		if (t->size != 4)
3564 			return KCFG_UNKNOWN;
3565 		if (strcmp(name, "libbpf_tristate"))
3566 			return KCFG_UNKNOWN;
3567 		return KCFG_TRISTATE;
3568 	case BTF_KIND_ENUM64:
3569 		if (strcmp(name, "libbpf_tristate"))
3570 			return KCFG_UNKNOWN;
3571 		return KCFG_TRISTATE;
3572 	case BTF_KIND_ARRAY:
3573 		if (btf_array(t)->nelems == 0)
3574 			return KCFG_UNKNOWN;
3575 		if (find_kcfg_type(btf, btf_array(t)->type, NULL) != KCFG_CHAR)
3576 			return KCFG_UNKNOWN;
3577 		return KCFG_CHAR_ARR;
3578 	default:
3579 		return KCFG_UNKNOWN;
3580 	}
3581 }
3582 
3583 static int cmp_externs(const void *_a, const void *_b)
3584 {
3585 	const struct extern_desc *a = _a;
3586 	const struct extern_desc *b = _b;
3587 
3588 	if (a->type != b->type)
3589 		return a->type < b->type ? -1 : 1;
3590 
3591 	if (a->type == EXT_KCFG) {
3592 		/* descending order by alignment requirements */
3593 		if (a->kcfg.align != b->kcfg.align)
3594 			return a->kcfg.align > b->kcfg.align ? -1 : 1;
3595 		/* ascending order by size, within same alignment class */
3596 		if (a->kcfg.sz != b->kcfg.sz)
3597 			return a->kcfg.sz < b->kcfg.sz ? -1 : 1;
3598 	}
3599 
3600 	/* resolve ties by name */
3601 	return strcmp(a->name, b->name);
3602 }
3603 
3604 static int find_int_btf_id(const struct btf *btf)
3605 {
3606 	const struct btf_type *t;
3607 	int i, n;
3608 
3609 	n = btf__type_cnt(btf);
3610 	for (i = 1; i < n; i++) {
3611 		t = btf__type_by_id(btf, i);
3612 
3613 		if (btf_is_int(t) && btf_int_bits(t) == 32)
3614 			return i;
3615 	}
3616 
3617 	return 0;
3618 }
3619 
3620 static int add_dummy_ksym_var(struct btf *btf)
3621 {
3622 	int i, int_btf_id, sec_btf_id, dummy_var_btf_id;
3623 	const struct btf_var_secinfo *vs;
3624 	const struct btf_type *sec;
3625 
3626 	if (!btf)
3627 		return 0;
3628 
3629 	sec_btf_id = btf__find_by_name_kind(btf, KSYMS_SEC,
3630 					    BTF_KIND_DATASEC);
3631 	if (sec_btf_id < 0)
3632 		return 0;
3633 
3634 	sec = btf__type_by_id(btf, sec_btf_id);
3635 	vs = btf_var_secinfos(sec);
3636 	for (i = 0; i < btf_vlen(sec); i++, vs++) {
3637 		const struct btf_type *vt;
3638 
3639 		vt = btf__type_by_id(btf, vs->type);
3640 		if (btf_is_func(vt))
3641 			break;
3642 	}
3643 
3644 	/* No func in ksyms sec.  No need to add dummy var. */
3645 	if (i == btf_vlen(sec))
3646 		return 0;
3647 
3648 	int_btf_id = find_int_btf_id(btf);
3649 	dummy_var_btf_id = btf__add_var(btf,
3650 					"dummy_ksym",
3651 					BTF_VAR_GLOBAL_ALLOCATED,
3652 					int_btf_id);
3653 	if (dummy_var_btf_id < 0)
3654 		pr_warn("cannot create a dummy_ksym var\n");
3655 
3656 	return dummy_var_btf_id;
3657 }
3658 
3659 static int bpf_object__collect_externs(struct bpf_object *obj)
3660 {
3661 	struct btf_type *sec, *kcfg_sec = NULL, *ksym_sec = NULL;
3662 	const struct btf_type *t;
3663 	struct extern_desc *ext;
3664 	int i, n, off, dummy_var_btf_id;
3665 	const char *ext_name, *sec_name;
3666 	Elf_Scn *scn;
3667 	Elf64_Shdr *sh;
3668 
3669 	if (!obj->efile.symbols)
3670 		return 0;
3671 
3672 	scn = elf_sec_by_idx(obj, obj->efile.symbols_shndx);
3673 	sh = elf_sec_hdr(obj, scn);
3674 	if (!sh || sh->sh_entsize != sizeof(Elf64_Sym))
3675 		return -LIBBPF_ERRNO__FORMAT;
3676 
3677 	dummy_var_btf_id = add_dummy_ksym_var(obj->btf);
3678 	if (dummy_var_btf_id < 0)
3679 		return dummy_var_btf_id;
3680 
3681 	n = sh->sh_size / sh->sh_entsize;
3682 	pr_debug("looking for externs among %d symbols...\n", n);
3683 
3684 	for (i = 0; i < n; i++) {
3685 		Elf64_Sym *sym = elf_sym_by_idx(obj, i);
3686 
3687 		if (!sym)
3688 			return -LIBBPF_ERRNO__FORMAT;
3689 		if (!sym_is_extern(sym))
3690 			continue;
3691 		ext_name = elf_sym_str(obj, sym->st_name);
3692 		if (!ext_name || !ext_name[0])
3693 			continue;
3694 
3695 		ext = obj->externs;
3696 		ext = libbpf_reallocarray(ext, obj->nr_extern + 1, sizeof(*ext));
3697 		if (!ext)
3698 			return -ENOMEM;
3699 		obj->externs = ext;
3700 		ext = &ext[obj->nr_extern];
3701 		memset(ext, 0, sizeof(*ext));
3702 		obj->nr_extern++;
3703 
3704 		ext->btf_id = find_extern_btf_id(obj->btf, ext_name);
3705 		if (ext->btf_id <= 0) {
3706 			pr_warn("failed to find BTF for extern '%s': %d\n",
3707 				ext_name, ext->btf_id);
3708 			return ext->btf_id;
3709 		}
3710 		t = btf__type_by_id(obj->btf, ext->btf_id);
3711 		ext->name = btf__name_by_offset(obj->btf, t->name_off);
3712 		ext->sym_idx = i;
3713 		ext->is_weak = ELF64_ST_BIND(sym->st_info) == STB_WEAK;
3714 
3715 		ext->sec_btf_id = find_extern_sec_btf_id(obj->btf, ext->btf_id);
3716 		if (ext->sec_btf_id <= 0) {
3717 			pr_warn("failed to find BTF for extern '%s' [%d] section: %d\n",
3718 				ext_name, ext->btf_id, ext->sec_btf_id);
3719 			return ext->sec_btf_id;
3720 		}
3721 		sec = (void *)btf__type_by_id(obj->btf, ext->sec_btf_id);
3722 		sec_name = btf__name_by_offset(obj->btf, sec->name_off);
3723 
3724 		if (strcmp(sec_name, KCONFIG_SEC) == 0) {
3725 			if (btf_is_func(t)) {
3726 				pr_warn("extern function %s is unsupported under %s section\n",
3727 					ext->name, KCONFIG_SEC);
3728 				return -ENOTSUP;
3729 			}
3730 			kcfg_sec = sec;
3731 			ext->type = EXT_KCFG;
3732 			ext->kcfg.sz = btf__resolve_size(obj->btf, t->type);
3733 			if (ext->kcfg.sz <= 0) {
3734 				pr_warn("failed to resolve size of extern (kcfg) '%s': %d\n",
3735 					ext_name, ext->kcfg.sz);
3736 				return ext->kcfg.sz;
3737 			}
3738 			ext->kcfg.align = btf__align_of(obj->btf, t->type);
3739 			if (ext->kcfg.align <= 0) {
3740 				pr_warn("failed to determine alignment of extern (kcfg) '%s': %d\n",
3741 					ext_name, ext->kcfg.align);
3742 				return -EINVAL;
3743 			}
3744 			ext->kcfg.type = find_kcfg_type(obj->btf, t->type,
3745 						        &ext->kcfg.is_signed);
3746 			if (ext->kcfg.type == KCFG_UNKNOWN) {
3747 				pr_warn("extern (kcfg) '%s': type is unsupported\n", ext_name);
3748 				return -ENOTSUP;
3749 			}
3750 		} else if (strcmp(sec_name, KSYMS_SEC) == 0) {
3751 			ksym_sec = sec;
3752 			ext->type = EXT_KSYM;
3753 			skip_mods_and_typedefs(obj->btf, t->type,
3754 					       &ext->ksym.type_id);
3755 		} else {
3756 			pr_warn("unrecognized extern section '%s'\n", sec_name);
3757 			return -ENOTSUP;
3758 		}
3759 	}
3760 	pr_debug("collected %d externs total\n", obj->nr_extern);
3761 
3762 	if (!obj->nr_extern)
3763 		return 0;
3764 
3765 	/* sort externs by type, for kcfg ones also by (align, size, name) */
3766 	qsort(obj->externs, obj->nr_extern, sizeof(*ext), cmp_externs);
3767 
3768 	/* for .ksyms section, we need to turn all externs into allocated
3769 	 * variables in BTF to pass kernel verification; we do this by
3770 	 * pretending that each extern is a 8-byte variable
3771 	 */
3772 	if (ksym_sec) {
3773 		/* find existing 4-byte integer type in BTF to use for fake
3774 		 * extern variables in DATASEC
3775 		 */
3776 		int int_btf_id = find_int_btf_id(obj->btf);
3777 		/* For extern function, a dummy_var added earlier
3778 		 * will be used to replace the vs->type and
3779 		 * its name string will be used to refill
3780 		 * the missing param's name.
3781 		 */
3782 		const struct btf_type *dummy_var;
3783 
3784 		dummy_var = btf__type_by_id(obj->btf, dummy_var_btf_id);
3785 		for (i = 0; i < obj->nr_extern; i++) {
3786 			ext = &obj->externs[i];
3787 			if (ext->type != EXT_KSYM)
3788 				continue;
3789 			pr_debug("extern (ksym) #%d: symbol %d, name %s\n",
3790 				 i, ext->sym_idx, ext->name);
3791 		}
3792 
3793 		sec = ksym_sec;
3794 		n = btf_vlen(sec);
3795 		for (i = 0, off = 0; i < n; i++, off += sizeof(int)) {
3796 			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
3797 			struct btf_type *vt;
3798 
3799 			vt = (void *)btf__type_by_id(obj->btf, vs->type);
3800 			ext_name = btf__name_by_offset(obj->btf, vt->name_off);
3801 			ext = find_extern_by_name(obj, ext_name);
3802 			if (!ext) {
3803 				pr_warn("failed to find extern definition for BTF %s '%s'\n",
3804 					btf_kind_str(vt), ext_name);
3805 				return -ESRCH;
3806 			}
3807 			if (btf_is_func(vt)) {
3808 				const struct btf_type *func_proto;
3809 				struct btf_param *param;
3810 				int j;
3811 
3812 				func_proto = btf__type_by_id(obj->btf,
3813 							     vt->type);
3814 				param = btf_params(func_proto);
3815 				/* Reuse the dummy_var string if the
3816 				 * func proto does not have param name.
3817 				 */
3818 				for (j = 0; j < btf_vlen(func_proto); j++)
3819 					if (param[j].type && !param[j].name_off)
3820 						param[j].name_off =
3821 							dummy_var->name_off;
3822 				vs->type = dummy_var_btf_id;
3823 				vt->info &= ~0xffff;
3824 				vt->info |= BTF_FUNC_GLOBAL;
3825 			} else {
3826 				btf_var(vt)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
3827 				vt->type = int_btf_id;
3828 			}
3829 			vs->offset = off;
3830 			vs->size = sizeof(int);
3831 		}
3832 		sec->size = off;
3833 	}
3834 
3835 	if (kcfg_sec) {
3836 		sec = kcfg_sec;
3837 		/* for kcfg externs calculate their offsets within a .kconfig map */
3838 		off = 0;
3839 		for (i = 0; i < obj->nr_extern; i++) {
3840 			ext = &obj->externs[i];
3841 			if (ext->type != EXT_KCFG)
3842 				continue;
3843 
3844 			ext->kcfg.data_off = roundup(off, ext->kcfg.align);
3845 			off = ext->kcfg.data_off + ext->kcfg.sz;
3846 			pr_debug("extern (kcfg) #%d: symbol %d, off %u, name %s\n",
3847 				 i, ext->sym_idx, ext->kcfg.data_off, ext->name);
3848 		}
3849 		sec->size = off;
3850 		n = btf_vlen(sec);
3851 		for (i = 0; i < n; i++) {
3852 			struct btf_var_secinfo *vs = btf_var_secinfos(sec) + i;
3853 
3854 			t = btf__type_by_id(obj->btf, vs->type);
3855 			ext_name = btf__name_by_offset(obj->btf, t->name_off);
3856 			ext = find_extern_by_name(obj, ext_name);
3857 			if (!ext) {
3858 				pr_warn("failed to find extern definition for BTF var '%s'\n",
3859 					ext_name);
3860 				return -ESRCH;
3861 			}
3862 			btf_var(t)->linkage = BTF_VAR_GLOBAL_ALLOCATED;
3863 			vs->offset = ext->kcfg.data_off;
3864 		}
3865 	}
3866 	return 0;
3867 }
3868 
3869 static bool prog_is_subprog(const struct bpf_object *obj, const struct bpf_program *prog)
3870 {
3871 	return prog->sec_idx == obj->efile.text_shndx && obj->nr_programs > 1;
3872 }
3873 
3874 struct bpf_program *
3875 bpf_object__find_program_by_name(const struct bpf_object *obj,
3876 				 const char *name)
3877 {
3878 	struct bpf_program *prog;
3879 
3880 	bpf_object__for_each_program(prog, obj) {
3881 		if (prog_is_subprog(obj, prog))
3882 			continue;
3883 		if (!strcmp(prog->name, name))
3884 			return prog;
3885 	}
3886 	return errno = ENOENT, NULL;
3887 }
3888 
3889 static bool bpf_object__shndx_is_data(const struct bpf_object *obj,
3890 				      int shndx)
3891 {
3892 	switch (obj->efile.secs[shndx].sec_type) {
3893 	case SEC_BSS:
3894 	case SEC_DATA:
3895 	case SEC_RODATA:
3896 		return true;
3897 	default:
3898 		return false;
3899 	}
3900 }
3901 
3902 static bool bpf_object__shndx_is_maps(const struct bpf_object *obj,
3903 				      int shndx)
3904 {
3905 	return shndx == obj->efile.btf_maps_shndx;
3906 }
3907 
3908 static enum libbpf_map_type
3909 bpf_object__section_to_libbpf_map_type(const struct bpf_object *obj, int shndx)
3910 {
3911 	if (shndx == obj->efile.symbols_shndx)
3912 		return LIBBPF_MAP_KCONFIG;
3913 
3914 	switch (obj->efile.secs[shndx].sec_type) {
3915 	case SEC_BSS:
3916 		return LIBBPF_MAP_BSS;
3917 	case SEC_DATA:
3918 		return LIBBPF_MAP_DATA;
3919 	case SEC_RODATA:
3920 		return LIBBPF_MAP_RODATA;
3921 	default:
3922 		return LIBBPF_MAP_UNSPEC;
3923 	}
3924 }
3925 
3926 static int bpf_program__record_reloc(struct bpf_program *prog,
3927 				     struct reloc_desc *reloc_desc,
3928 				     __u32 insn_idx, const char *sym_name,
3929 				     const Elf64_Sym *sym, const Elf64_Rel *rel)
3930 {
3931 	struct bpf_insn *insn = &prog->insns[insn_idx];
3932 	size_t map_idx, nr_maps = prog->obj->nr_maps;
3933 	struct bpf_object *obj = prog->obj;
3934 	__u32 shdr_idx = sym->st_shndx;
3935 	enum libbpf_map_type type;
3936 	const char *sym_sec_name;
3937 	struct bpf_map *map;
3938 
3939 	if (!is_call_insn(insn) && !is_ldimm64_insn(insn)) {
3940 		pr_warn("prog '%s': invalid relo against '%s' for insns[%d].code 0x%x\n",
3941 			prog->name, sym_name, insn_idx, insn->code);
3942 		return -LIBBPF_ERRNO__RELOC;
3943 	}
3944 
3945 	if (sym_is_extern(sym)) {
3946 		int sym_idx = ELF64_R_SYM(rel->r_info);
3947 		int i, n = obj->nr_extern;
3948 		struct extern_desc *ext;
3949 
3950 		for (i = 0; i < n; i++) {
3951 			ext = &obj->externs[i];
3952 			if (ext->sym_idx == sym_idx)
3953 				break;
3954 		}
3955 		if (i >= n) {
3956 			pr_warn("prog '%s': extern relo failed to find extern for '%s' (%d)\n",
3957 				prog->name, sym_name, sym_idx);
3958 			return -LIBBPF_ERRNO__RELOC;
3959 		}
3960 		pr_debug("prog '%s': found extern #%d '%s' (sym %d) for insn #%u\n",
3961 			 prog->name, i, ext->name, ext->sym_idx, insn_idx);
3962 		if (insn->code == (BPF_JMP | BPF_CALL))
3963 			reloc_desc->type = RELO_EXTERN_FUNC;
3964 		else
3965 			reloc_desc->type = RELO_EXTERN_VAR;
3966 		reloc_desc->insn_idx = insn_idx;
3967 		reloc_desc->sym_off = i; /* sym_off stores extern index */
3968 		return 0;
3969 	}
3970 
3971 	/* sub-program call relocation */
3972 	if (is_call_insn(insn)) {
3973 		if (insn->src_reg != BPF_PSEUDO_CALL) {
3974 			pr_warn("prog '%s': incorrect bpf_call opcode\n", prog->name);
3975 			return -LIBBPF_ERRNO__RELOC;
3976 		}
3977 		/* text_shndx can be 0, if no default "main" program exists */
3978 		if (!shdr_idx || shdr_idx != obj->efile.text_shndx) {
3979 			sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
3980 			pr_warn("prog '%s': bad call relo against '%s' in section '%s'\n",
3981 				prog->name, sym_name, sym_sec_name);
3982 			return -LIBBPF_ERRNO__RELOC;
3983 		}
3984 		if (sym->st_value % BPF_INSN_SZ) {
3985 			pr_warn("prog '%s': bad call relo against '%s' at offset %zu\n",
3986 				prog->name, sym_name, (size_t)sym->st_value);
3987 			return -LIBBPF_ERRNO__RELOC;
3988 		}
3989 		reloc_desc->type = RELO_CALL;
3990 		reloc_desc->insn_idx = insn_idx;
3991 		reloc_desc->sym_off = sym->st_value;
3992 		return 0;
3993 	}
3994 
3995 	if (!shdr_idx || shdr_idx >= SHN_LORESERVE) {
3996 		pr_warn("prog '%s': invalid relo against '%s' in special section 0x%x; forgot to initialize global var?..\n",
3997 			prog->name, sym_name, shdr_idx);
3998 		return -LIBBPF_ERRNO__RELOC;
3999 	}
4000 
4001 	/* loading subprog addresses */
4002 	if (sym_is_subprog(sym, obj->efile.text_shndx)) {
4003 		/* global_func: sym->st_value = offset in the section, insn->imm = 0.
4004 		 * local_func: sym->st_value = 0, insn->imm = offset in the section.
4005 		 */
4006 		if ((sym->st_value % BPF_INSN_SZ) || (insn->imm % BPF_INSN_SZ)) {
4007 			pr_warn("prog '%s': bad subprog addr relo against '%s' at offset %zu+%d\n",
4008 				prog->name, sym_name, (size_t)sym->st_value, insn->imm);
4009 			return -LIBBPF_ERRNO__RELOC;
4010 		}
4011 
4012 		reloc_desc->type = RELO_SUBPROG_ADDR;
4013 		reloc_desc->insn_idx = insn_idx;
4014 		reloc_desc->sym_off = sym->st_value;
4015 		return 0;
4016 	}
4017 
4018 	type = bpf_object__section_to_libbpf_map_type(obj, shdr_idx);
4019 	sym_sec_name = elf_sec_name(obj, elf_sec_by_idx(obj, shdr_idx));
4020 
4021 	/* generic map reference relocation */
4022 	if (type == LIBBPF_MAP_UNSPEC) {
4023 		if (!bpf_object__shndx_is_maps(obj, shdr_idx)) {
4024 			pr_warn("prog '%s': bad map relo against '%s' in section '%s'\n",
4025 				prog->name, sym_name, sym_sec_name);
4026 			return -LIBBPF_ERRNO__RELOC;
4027 		}
4028 		for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4029 			map = &obj->maps[map_idx];
4030 			if (map->libbpf_type != type ||
4031 			    map->sec_idx != sym->st_shndx ||
4032 			    map->sec_offset != sym->st_value)
4033 				continue;
4034 			pr_debug("prog '%s': found map %zd (%s, sec %d, off %zu) for insn #%u\n",
4035 				 prog->name, map_idx, map->name, map->sec_idx,
4036 				 map->sec_offset, insn_idx);
4037 			break;
4038 		}
4039 		if (map_idx >= nr_maps) {
4040 			pr_warn("prog '%s': map relo failed to find map for section '%s', off %zu\n",
4041 				prog->name, sym_sec_name, (size_t)sym->st_value);
4042 			return -LIBBPF_ERRNO__RELOC;
4043 		}
4044 		reloc_desc->type = RELO_LD64;
4045 		reloc_desc->insn_idx = insn_idx;
4046 		reloc_desc->map_idx = map_idx;
4047 		reloc_desc->sym_off = 0; /* sym->st_value determines map_idx */
4048 		return 0;
4049 	}
4050 
4051 	/* global data map relocation */
4052 	if (!bpf_object__shndx_is_data(obj, shdr_idx)) {
4053 		pr_warn("prog '%s': bad data relo against section '%s'\n",
4054 			prog->name, sym_sec_name);
4055 		return -LIBBPF_ERRNO__RELOC;
4056 	}
4057 	for (map_idx = 0; map_idx < nr_maps; map_idx++) {
4058 		map = &obj->maps[map_idx];
4059 		if (map->libbpf_type != type || map->sec_idx != sym->st_shndx)
4060 			continue;
4061 		pr_debug("prog '%s': found data map %zd (%s, sec %d, off %zu) for insn %u\n",
4062 			 prog->name, map_idx, map->name, map->sec_idx,
4063 			 map->sec_offset, insn_idx);
4064 		break;
4065 	}
4066 	if (map_idx >= nr_maps) {
4067 		pr_warn("prog '%s': data relo failed to find map for section '%s'\n",
4068 			prog->name, sym_sec_name);
4069 		return -LIBBPF_ERRNO__RELOC;
4070 	}
4071 
4072 	reloc_desc->type = RELO_DATA;
4073 	reloc_desc->insn_idx = insn_idx;
4074 	reloc_desc->map_idx = map_idx;
4075 	reloc_desc->sym_off = sym->st_value;
4076 	return 0;
4077 }
4078 
4079 static bool prog_contains_insn(const struct bpf_program *prog, size_t insn_idx)
4080 {
4081 	return insn_idx >= prog->sec_insn_off &&
4082 	       insn_idx < prog->sec_insn_off + prog->sec_insn_cnt;
4083 }
4084 
4085 static struct bpf_program *find_prog_by_sec_insn(const struct bpf_object *obj,
4086 						 size_t sec_idx, size_t insn_idx)
4087 {
4088 	int l = 0, r = obj->nr_programs - 1, m;
4089 	struct bpf_program *prog;
4090 
4091 	while (l < r) {
4092 		m = l + (r - l + 1) / 2;
4093 		prog = &obj->programs[m];
4094 
4095 		if (prog->sec_idx < sec_idx ||
4096 		    (prog->sec_idx == sec_idx && prog->sec_insn_off <= insn_idx))
4097 			l = m;
4098 		else
4099 			r = m - 1;
4100 	}
4101 	/* matching program could be at index l, but it still might be the
4102 	 * wrong one, so we need to double check conditions for the last time
4103 	 */
4104 	prog = &obj->programs[l];
4105 	if (prog->sec_idx == sec_idx && prog_contains_insn(prog, insn_idx))
4106 		return prog;
4107 	return NULL;
4108 }
4109 
4110 static int
4111 bpf_object__collect_prog_relos(struct bpf_object *obj, Elf64_Shdr *shdr, Elf_Data *data)
4112 {
4113 	const char *relo_sec_name, *sec_name;
4114 	size_t sec_idx = shdr->sh_info, sym_idx;
4115 	struct bpf_program *prog;
4116 	struct reloc_desc *relos;
4117 	int err, i, nrels;
4118 	const char *sym_name;
4119 	__u32 insn_idx;
4120 	Elf_Scn *scn;
4121 	Elf_Data *scn_data;
4122 	Elf64_Sym *sym;
4123 	Elf64_Rel *rel;
4124 
4125 	if (sec_idx >= obj->efile.sec_cnt)
4126 		return -EINVAL;
4127 
4128 	scn = elf_sec_by_idx(obj, sec_idx);
4129 	scn_data = elf_sec_data(obj, scn);
4130 
4131 	relo_sec_name = elf_sec_str(obj, shdr->sh_name);
4132 	sec_name = elf_sec_name(obj, scn);
4133 	if (!relo_sec_name || !sec_name)
4134 		return -EINVAL;
4135 
4136 	pr_debug("sec '%s': collecting relocation for section(%zu) '%s'\n",
4137 		 relo_sec_name, sec_idx, sec_name);
4138 	nrels = shdr->sh_size / shdr->sh_entsize;
4139 
4140 	for (i = 0; i < nrels; i++) {
4141 		rel = elf_rel_by_idx(data, i);
4142 		if (!rel) {
4143 			pr_warn("sec '%s': failed to get relo #%d\n", relo_sec_name, i);
4144 			return -LIBBPF_ERRNO__FORMAT;
4145 		}
4146 
4147 		sym_idx = ELF64_R_SYM(rel->r_info);
4148 		sym = elf_sym_by_idx(obj, sym_idx);
4149 		if (!sym) {
4150 			pr_warn("sec '%s': symbol #%zu not found for relo #%d\n",
4151 				relo_sec_name, sym_idx, i);
4152 			return -LIBBPF_ERRNO__FORMAT;
4153 		}
4154 
4155 		if (sym->st_shndx >= obj->efile.sec_cnt) {
4156 			pr_warn("sec '%s': corrupted symbol #%zu pointing to invalid section #%zu for relo #%d\n",
4157 				relo_sec_name, sym_idx, (size_t)sym->st_shndx, i);
4158 			return -LIBBPF_ERRNO__FORMAT;
4159 		}
4160 
4161 		if (rel->r_offset % BPF_INSN_SZ || rel->r_offset >= scn_data->d_size) {
4162 			pr_warn("sec '%s': invalid offset 0x%zx for relo #%d\n",
4163 				relo_sec_name, (size_t)rel->r_offset, i);
4164 			return -LIBBPF_ERRNO__FORMAT;
4165 		}
4166 
4167 		insn_idx = rel->r_offset / BPF_INSN_SZ;
4168 		/* relocations against static functions are recorded as
4169 		 * relocations against the section that contains a function;
4170 		 * in such case, symbol will be STT_SECTION and sym.st_name
4171 		 * will point to empty string (0), so fetch section name
4172 		 * instead
4173 		 */
4174 		if (ELF64_ST_TYPE(sym->st_info) == STT_SECTION && sym->st_name == 0)
4175 			sym_name = elf_sec_name(obj, elf_sec_by_idx(obj, sym->st_shndx));
4176 		else
4177 			sym_name = elf_sym_str(obj, sym->st_name);
4178 		sym_name = sym_name ?: "<?";
4179 
4180 		pr_debug("sec '%s': relo #%d: insn #%u against '%s'\n",
4181 			 relo_sec_name, i, insn_idx, sym_name);
4182 
4183 		prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
4184 		if (!prog) {
4185 			pr_debug("sec '%s': relo #%d: couldn't find program in section '%s' for insn #%u, probably overridden weak function, skipping...\n",
4186 				relo_sec_name, i, sec_name, insn_idx);
4187 			continue;
4188 		}
4189 
4190 		relos = libbpf_reallocarray(prog->reloc_desc,
4191 					    prog->nr_reloc + 1, sizeof(*relos));
4192 		if (!relos)
4193 			return -ENOMEM;
4194 		prog->reloc_desc = relos;
4195 
4196 		/* adjust insn_idx to local BPF program frame of reference */
4197 		insn_idx -= prog->sec_insn_off;
4198 		err = bpf_program__record_reloc(prog, &relos[prog->nr_reloc],
4199 						insn_idx, sym_name, sym, rel);
4200 		if (err)
4201 			return err;
4202 
4203 		prog->nr_reloc++;
4204 	}
4205 	return 0;
4206 }
4207 
4208 static int bpf_map_find_btf_info(struct bpf_object *obj, struct bpf_map *map)
4209 {
4210 	int id;
4211 
4212 	if (!obj->btf)
4213 		return -ENOENT;
4214 
4215 	/* if it's BTF-defined map, we don't need to search for type IDs.
4216 	 * For struct_ops map, it does not need btf_key_type_id and
4217 	 * btf_value_type_id.
4218 	 */
4219 	if (map->sec_idx == obj->efile.btf_maps_shndx || bpf_map__is_struct_ops(map))
4220 		return 0;
4221 
4222 	/*
4223 	 * LLVM annotates global data differently in BTF, that is,
4224 	 * only as '.data', '.bss' or '.rodata'.
4225 	 */
4226 	if (!bpf_map__is_internal(map))
4227 		return -ENOENT;
4228 
4229 	id = btf__find_by_name(obj->btf, map->real_name);
4230 	if (id < 0)
4231 		return id;
4232 
4233 	map->btf_key_type_id = 0;
4234 	map->btf_value_type_id = id;
4235 	return 0;
4236 }
4237 
4238 static int bpf_get_map_info_from_fdinfo(int fd, struct bpf_map_info *info)
4239 {
4240 	char file[PATH_MAX], buff[4096];
4241 	FILE *fp;
4242 	__u32 val;
4243 	int err;
4244 
4245 	snprintf(file, sizeof(file), "/proc/%d/fdinfo/%d", getpid(), fd);
4246 	memset(info, 0, sizeof(*info));
4247 
4248 	fp = fopen(file, "r");
4249 	if (!fp) {
4250 		err = -errno;
4251 		pr_warn("failed to open %s: %d. No procfs support?\n", file,
4252 			err);
4253 		return err;
4254 	}
4255 
4256 	while (fgets(buff, sizeof(buff), fp)) {
4257 		if (sscanf(buff, "map_type:\t%u", &val) == 1)
4258 			info->type = val;
4259 		else if (sscanf(buff, "key_size:\t%u", &val) == 1)
4260 			info->key_size = val;
4261 		else if (sscanf(buff, "value_size:\t%u", &val) == 1)
4262 			info->value_size = val;
4263 		else if (sscanf(buff, "max_entries:\t%u", &val) == 1)
4264 			info->max_entries = val;
4265 		else if (sscanf(buff, "map_flags:\t%i", &val) == 1)
4266 			info->map_flags = val;
4267 	}
4268 
4269 	fclose(fp);
4270 
4271 	return 0;
4272 }
4273 
4274 bool bpf_map__autocreate(const struct bpf_map *map)
4275 {
4276 	return map->autocreate;
4277 }
4278 
4279 int bpf_map__set_autocreate(struct bpf_map *map, bool autocreate)
4280 {
4281 	if (map->obj->loaded)
4282 		return libbpf_err(-EBUSY);
4283 
4284 	map->autocreate = autocreate;
4285 	return 0;
4286 }
4287 
4288 int bpf_map__reuse_fd(struct bpf_map *map, int fd)
4289 {
4290 	struct bpf_map_info info;
4291 	__u32 len = sizeof(info), name_len;
4292 	int new_fd, err;
4293 	char *new_name;
4294 
4295 	memset(&info, 0, len);
4296 	err = bpf_obj_get_info_by_fd(fd, &info, &len);
4297 	if (err && errno == EINVAL)
4298 		err = bpf_get_map_info_from_fdinfo(fd, &info);
4299 	if (err)
4300 		return libbpf_err(err);
4301 
4302 	name_len = strlen(info.name);
4303 	if (name_len == BPF_OBJ_NAME_LEN - 1 && strncmp(map->name, info.name, name_len) == 0)
4304 		new_name = strdup(map->name);
4305 	else
4306 		new_name = strdup(info.name);
4307 
4308 	if (!new_name)
4309 		return libbpf_err(-errno);
4310 
4311 	new_fd = open("/", O_RDONLY | O_CLOEXEC);
4312 	if (new_fd < 0) {
4313 		err = -errno;
4314 		goto err_free_new_name;
4315 	}
4316 
4317 	new_fd = dup3(fd, new_fd, O_CLOEXEC);
4318 	if (new_fd < 0) {
4319 		err = -errno;
4320 		goto err_close_new_fd;
4321 	}
4322 
4323 	err = zclose(map->fd);
4324 	if (err) {
4325 		err = -errno;
4326 		goto err_close_new_fd;
4327 	}
4328 	free(map->name);
4329 
4330 	map->fd = new_fd;
4331 	map->name = new_name;
4332 	map->def.type = info.type;
4333 	map->def.key_size = info.key_size;
4334 	map->def.value_size = info.value_size;
4335 	map->def.max_entries = info.max_entries;
4336 	map->def.map_flags = info.map_flags;
4337 	map->btf_key_type_id = info.btf_key_type_id;
4338 	map->btf_value_type_id = info.btf_value_type_id;
4339 	map->reused = true;
4340 	map->map_extra = info.map_extra;
4341 
4342 	return 0;
4343 
4344 err_close_new_fd:
4345 	close(new_fd);
4346 err_free_new_name:
4347 	free(new_name);
4348 	return libbpf_err(err);
4349 }
4350 
4351 __u32 bpf_map__max_entries(const struct bpf_map *map)
4352 {
4353 	return map->def.max_entries;
4354 }
4355 
4356 struct bpf_map *bpf_map__inner_map(struct bpf_map *map)
4357 {
4358 	if (!bpf_map_type__is_map_in_map(map->def.type))
4359 		return errno = EINVAL, NULL;
4360 
4361 	return map->inner_map;
4362 }
4363 
4364 int bpf_map__set_max_entries(struct bpf_map *map, __u32 max_entries)
4365 {
4366 	if (map->obj->loaded)
4367 		return libbpf_err(-EBUSY);
4368 
4369 	map->def.max_entries = max_entries;
4370 
4371 	/* auto-adjust BPF ringbuf map max_entries to be a multiple of page size */
4372 	if (map->def.type == BPF_MAP_TYPE_RINGBUF)
4373 		map->def.max_entries = adjust_ringbuf_sz(map->def.max_entries);
4374 
4375 	return 0;
4376 }
4377 
4378 static int
4379 bpf_object__probe_loading(struct bpf_object *obj)
4380 {
4381 	char *cp, errmsg[STRERR_BUFSIZE];
4382 	struct bpf_insn insns[] = {
4383 		BPF_MOV64_IMM(BPF_REG_0, 0),
4384 		BPF_EXIT_INSN(),
4385 	};
4386 	int ret, insn_cnt = ARRAY_SIZE(insns);
4387 
4388 	if (obj->gen_loader)
4389 		return 0;
4390 
4391 	ret = bump_rlimit_memlock();
4392 	if (ret)
4393 		pr_warn("Failed to bump RLIMIT_MEMLOCK (err = %d), you might need to do it explicitly!\n", ret);
4394 
4395 	/* make sure basic loading works */
4396 	ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4397 	if (ret < 0)
4398 		ret = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, NULL);
4399 	if (ret < 0) {
4400 		ret = errno;
4401 		cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4402 		pr_warn("Error in %s():%s(%d). Couldn't load trivial BPF "
4403 			"program. Make sure your kernel supports BPF "
4404 			"(CONFIG_BPF_SYSCALL=y) and/or that RLIMIT_MEMLOCK is "
4405 			"set to big enough value.\n", __func__, cp, ret);
4406 		return -ret;
4407 	}
4408 	close(ret);
4409 
4410 	return 0;
4411 }
4412 
4413 static int probe_fd(int fd)
4414 {
4415 	if (fd >= 0)
4416 		close(fd);
4417 	return fd >= 0;
4418 }
4419 
4420 static int probe_kern_prog_name(void)
4421 {
4422 	const size_t attr_sz = offsetofend(union bpf_attr, prog_name);
4423 	struct bpf_insn insns[] = {
4424 		BPF_MOV64_IMM(BPF_REG_0, 0),
4425 		BPF_EXIT_INSN(),
4426 	};
4427 	union bpf_attr attr;
4428 	int ret;
4429 
4430 	memset(&attr, 0, attr_sz);
4431 	attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
4432 	attr.license = ptr_to_u64("GPL");
4433 	attr.insns = ptr_to_u64(insns);
4434 	attr.insn_cnt = (__u32)ARRAY_SIZE(insns);
4435 	libbpf_strlcpy(attr.prog_name, "libbpf_nametest", sizeof(attr.prog_name));
4436 
4437 	/* make sure loading with name works */
4438 	ret = sys_bpf_prog_load(&attr, attr_sz, PROG_LOAD_ATTEMPTS);
4439 	return probe_fd(ret);
4440 }
4441 
4442 static int probe_kern_global_data(void)
4443 {
4444 	char *cp, errmsg[STRERR_BUFSIZE];
4445 	struct bpf_insn insns[] = {
4446 		BPF_LD_MAP_VALUE(BPF_REG_1, 0, 16),
4447 		BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 42),
4448 		BPF_MOV64_IMM(BPF_REG_0, 0),
4449 		BPF_EXIT_INSN(),
4450 	};
4451 	int ret, map, insn_cnt = ARRAY_SIZE(insns);
4452 
4453 	map = bpf_map_create(BPF_MAP_TYPE_ARRAY, "libbpf_global", sizeof(int), 32, 1, NULL);
4454 	if (map < 0) {
4455 		ret = -errno;
4456 		cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4457 		pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
4458 			__func__, cp, -ret);
4459 		return ret;
4460 	}
4461 
4462 	insns[0].imm = map;
4463 
4464 	ret = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4465 	close(map);
4466 	return probe_fd(ret);
4467 }
4468 
4469 static int probe_kern_btf(void)
4470 {
4471 	static const char strs[] = "\0int";
4472 	__u32 types[] = {
4473 		/* int */
4474 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),
4475 	};
4476 
4477 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4478 					     strs, sizeof(strs)));
4479 }
4480 
4481 static int probe_kern_btf_func(void)
4482 {
4483 	static const char strs[] = "\0int\0x\0a";
4484 	/* void x(int a) {} */
4485 	__u32 types[] = {
4486 		/* int */
4487 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4488 		/* FUNC_PROTO */                                /* [2] */
4489 		BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
4490 		BTF_PARAM_ENC(7, 1),
4491 		/* FUNC x */                                    /* [3] */
4492 		BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, 0), 2),
4493 	};
4494 
4495 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4496 					     strs, sizeof(strs)));
4497 }
4498 
4499 static int probe_kern_btf_func_global(void)
4500 {
4501 	static const char strs[] = "\0int\0x\0a";
4502 	/* static void x(int a) {} */
4503 	__u32 types[] = {
4504 		/* int */
4505 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4506 		/* FUNC_PROTO */                                /* [2] */
4507 		BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_FUNC_PROTO, 0, 1), 0),
4508 		BTF_PARAM_ENC(7, 1),
4509 		/* FUNC x BTF_FUNC_GLOBAL */                    /* [3] */
4510 		BTF_TYPE_ENC(5, BTF_INFO_ENC(BTF_KIND_FUNC, 0, BTF_FUNC_GLOBAL), 2),
4511 	};
4512 
4513 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4514 					     strs, sizeof(strs)));
4515 }
4516 
4517 static int probe_kern_btf_datasec(void)
4518 {
4519 	static const char strs[] = "\0x\0.data";
4520 	/* static int a; */
4521 	__u32 types[] = {
4522 		/* int */
4523 		BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4524 		/* VAR x */                                     /* [2] */
4525 		BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
4526 		BTF_VAR_STATIC,
4527 		/* DATASEC val */                               /* [3] */
4528 		BTF_TYPE_ENC(3, BTF_INFO_ENC(BTF_KIND_DATASEC, 0, 1), 4),
4529 		BTF_VAR_SECINFO_ENC(2, 0, 4),
4530 	};
4531 
4532 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4533 					     strs, sizeof(strs)));
4534 }
4535 
4536 static int probe_kern_btf_float(void)
4537 {
4538 	static const char strs[] = "\0float";
4539 	__u32 types[] = {
4540 		/* float */
4541 		BTF_TYPE_FLOAT_ENC(1, 4),
4542 	};
4543 
4544 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4545 					     strs, sizeof(strs)));
4546 }
4547 
4548 static int probe_kern_btf_decl_tag(void)
4549 {
4550 	static const char strs[] = "\0tag";
4551 	__u32 types[] = {
4552 		/* int */
4553 		BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4),  /* [1] */
4554 		/* VAR x */                                     /* [2] */
4555 		BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_VAR, 0, 0), 1),
4556 		BTF_VAR_STATIC,
4557 		/* attr */
4558 		BTF_TYPE_DECL_TAG_ENC(1, 2, -1),
4559 	};
4560 
4561 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4562 					     strs, sizeof(strs)));
4563 }
4564 
4565 static int probe_kern_btf_type_tag(void)
4566 {
4567 	static const char strs[] = "\0tag";
4568 	__u32 types[] = {
4569 		/* int */
4570 		BTF_TYPE_INT_ENC(0, BTF_INT_SIGNED, 0, 32, 4),		/* [1] */
4571 		/* attr */
4572 		BTF_TYPE_TYPE_TAG_ENC(1, 1),				/* [2] */
4573 		/* ptr */
4574 		BTF_TYPE_ENC(0, BTF_INFO_ENC(BTF_KIND_PTR, 0, 0), 2),	/* [3] */
4575 	};
4576 
4577 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4578 					     strs, sizeof(strs)));
4579 }
4580 
4581 static int probe_kern_array_mmap(void)
4582 {
4583 	LIBBPF_OPTS(bpf_map_create_opts, opts, .map_flags = BPF_F_MMAPABLE);
4584 	int fd;
4585 
4586 	fd = bpf_map_create(BPF_MAP_TYPE_ARRAY, "libbpf_mmap", sizeof(int), sizeof(int), 1, &opts);
4587 	return probe_fd(fd);
4588 }
4589 
4590 static int probe_kern_exp_attach_type(void)
4591 {
4592 	LIBBPF_OPTS(bpf_prog_load_opts, opts, .expected_attach_type = BPF_CGROUP_INET_SOCK_CREATE);
4593 	struct bpf_insn insns[] = {
4594 		BPF_MOV64_IMM(BPF_REG_0, 0),
4595 		BPF_EXIT_INSN(),
4596 	};
4597 	int fd, insn_cnt = ARRAY_SIZE(insns);
4598 
4599 	/* use any valid combination of program type and (optional)
4600 	 * non-zero expected attach type (i.e., not a BPF_CGROUP_INET_INGRESS)
4601 	 * to see if kernel supports expected_attach_type field for
4602 	 * BPF_PROG_LOAD command
4603 	 */
4604 	fd = bpf_prog_load(BPF_PROG_TYPE_CGROUP_SOCK, NULL, "GPL", insns, insn_cnt, &opts);
4605 	return probe_fd(fd);
4606 }
4607 
4608 static int probe_kern_probe_read_kernel(void)
4609 {
4610 	struct bpf_insn insns[] = {
4611 		BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),	/* r1 = r10 (fp) */
4612 		BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -8),	/* r1 += -8 */
4613 		BPF_MOV64_IMM(BPF_REG_2, 8),		/* r2 = 8 */
4614 		BPF_MOV64_IMM(BPF_REG_3, 0),		/* r3 = 0 */
4615 		BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_probe_read_kernel),
4616 		BPF_EXIT_INSN(),
4617 	};
4618 	int fd, insn_cnt = ARRAY_SIZE(insns);
4619 
4620 	fd = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL", insns, insn_cnt, NULL);
4621 	return probe_fd(fd);
4622 }
4623 
4624 static int probe_prog_bind_map(void)
4625 {
4626 	char *cp, errmsg[STRERR_BUFSIZE];
4627 	struct bpf_insn insns[] = {
4628 		BPF_MOV64_IMM(BPF_REG_0, 0),
4629 		BPF_EXIT_INSN(),
4630 	};
4631 	int ret, map, prog, insn_cnt = ARRAY_SIZE(insns);
4632 
4633 	map = bpf_map_create(BPF_MAP_TYPE_ARRAY, "libbpf_det_bind", sizeof(int), 32, 1, NULL);
4634 	if (map < 0) {
4635 		ret = -errno;
4636 		cp = libbpf_strerror_r(ret, errmsg, sizeof(errmsg));
4637 		pr_warn("Error in %s():%s(%d). Couldn't create simple array map.\n",
4638 			__func__, cp, -ret);
4639 		return ret;
4640 	}
4641 
4642 	prog = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns, insn_cnt, NULL);
4643 	if (prog < 0) {
4644 		close(map);
4645 		return 0;
4646 	}
4647 
4648 	ret = bpf_prog_bind_map(prog, map, NULL);
4649 
4650 	close(map);
4651 	close(prog);
4652 
4653 	return ret >= 0;
4654 }
4655 
4656 static int probe_module_btf(void)
4657 {
4658 	static const char strs[] = "\0int";
4659 	__u32 types[] = {
4660 		/* int */
4661 		BTF_TYPE_INT_ENC(1, BTF_INT_SIGNED, 0, 32, 4),
4662 	};
4663 	struct bpf_btf_info info;
4664 	__u32 len = sizeof(info);
4665 	char name[16];
4666 	int fd, err;
4667 
4668 	fd = libbpf__load_raw_btf((char *)types, sizeof(types), strs, sizeof(strs));
4669 	if (fd < 0)
4670 		return 0; /* BTF not supported at all */
4671 
4672 	memset(&info, 0, sizeof(info));
4673 	info.name = ptr_to_u64(name);
4674 	info.name_len = sizeof(name);
4675 
4676 	/* check that BPF_OBJ_GET_INFO_BY_FD supports specifying name pointer;
4677 	 * kernel's module BTF support coincides with support for
4678 	 * name/name_len fields in struct bpf_btf_info.
4679 	 */
4680 	err = bpf_obj_get_info_by_fd(fd, &info, &len);
4681 	close(fd);
4682 	return !err;
4683 }
4684 
4685 static int probe_perf_link(void)
4686 {
4687 	struct bpf_insn insns[] = {
4688 		BPF_MOV64_IMM(BPF_REG_0, 0),
4689 		BPF_EXIT_INSN(),
4690 	};
4691 	int prog_fd, link_fd, err;
4692 
4693 	prog_fd = bpf_prog_load(BPF_PROG_TYPE_TRACEPOINT, NULL, "GPL",
4694 				insns, ARRAY_SIZE(insns), NULL);
4695 	if (prog_fd < 0)
4696 		return -errno;
4697 
4698 	/* use invalid perf_event FD to get EBADF, if link is supported;
4699 	 * otherwise EINVAL should be returned
4700 	 */
4701 	link_fd = bpf_link_create(prog_fd, -1, BPF_PERF_EVENT, NULL);
4702 	err = -errno; /* close() can clobber errno */
4703 
4704 	if (link_fd >= 0)
4705 		close(link_fd);
4706 	close(prog_fd);
4707 
4708 	return link_fd < 0 && err == -EBADF;
4709 }
4710 
4711 static int probe_kern_bpf_cookie(void)
4712 {
4713 	struct bpf_insn insns[] = {
4714 		BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_get_attach_cookie),
4715 		BPF_EXIT_INSN(),
4716 	};
4717 	int ret, insn_cnt = ARRAY_SIZE(insns);
4718 
4719 	ret = bpf_prog_load(BPF_PROG_TYPE_KPROBE, NULL, "GPL", insns, insn_cnt, NULL);
4720 	return probe_fd(ret);
4721 }
4722 
4723 static int probe_kern_btf_enum64(void)
4724 {
4725 	static const char strs[] = "\0enum64";
4726 	__u32 types[] = {
4727 		BTF_TYPE_ENC(1, BTF_INFO_ENC(BTF_KIND_ENUM64, 0, 0), 8),
4728 	};
4729 
4730 	return probe_fd(libbpf__load_raw_btf((char *)types, sizeof(types),
4731 					     strs, sizeof(strs)));
4732 }
4733 
4734 static int probe_kern_syscall_wrapper(void);
4735 
4736 enum kern_feature_result {
4737 	FEAT_UNKNOWN = 0,
4738 	FEAT_SUPPORTED = 1,
4739 	FEAT_MISSING = 2,
4740 };
4741 
4742 typedef int (*feature_probe_fn)(void);
4743 
4744 static struct kern_feature_desc {
4745 	const char *desc;
4746 	feature_probe_fn probe;
4747 	enum kern_feature_result res;
4748 } feature_probes[__FEAT_CNT] = {
4749 	[FEAT_PROG_NAME] = {
4750 		"BPF program name", probe_kern_prog_name,
4751 	},
4752 	[FEAT_GLOBAL_DATA] = {
4753 		"global variables", probe_kern_global_data,
4754 	},
4755 	[FEAT_BTF] = {
4756 		"minimal BTF", probe_kern_btf,
4757 	},
4758 	[FEAT_BTF_FUNC] = {
4759 		"BTF functions", probe_kern_btf_func,
4760 	},
4761 	[FEAT_BTF_GLOBAL_FUNC] = {
4762 		"BTF global function", probe_kern_btf_func_global,
4763 	},
4764 	[FEAT_BTF_DATASEC] = {
4765 		"BTF data section and variable", probe_kern_btf_datasec,
4766 	},
4767 	[FEAT_ARRAY_MMAP] = {
4768 		"ARRAY map mmap()", probe_kern_array_mmap,
4769 	},
4770 	[FEAT_EXP_ATTACH_TYPE] = {
4771 		"BPF_PROG_LOAD expected_attach_type attribute",
4772 		probe_kern_exp_attach_type,
4773 	},
4774 	[FEAT_PROBE_READ_KERN] = {
4775 		"bpf_probe_read_kernel() helper", probe_kern_probe_read_kernel,
4776 	},
4777 	[FEAT_PROG_BIND_MAP] = {
4778 		"BPF_PROG_BIND_MAP support", probe_prog_bind_map,
4779 	},
4780 	[FEAT_MODULE_BTF] = {
4781 		"module BTF support", probe_module_btf,
4782 	},
4783 	[FEAT_BTF_FLOAT] = {
4784 		"BTF_KIND_FLOAT support", probe_kern_btf_float,
4785 	},
4786 	[FEAT_PERF_LINK] = {
4787 		"BPF perf link support", probe_perf_link,
4788 	},
4789 	[FEAT_BTF_DECL_TAG] = {
4790 		"BTF_KIND_DECL_TAG support", probe_kern_btf_decl_tag,
4791 	},
4792 	[FEAT_BTF_TYPE_TAG] = {
4793 		"BTF_KIND_TYPE_TAG support", probe_kern_btf_type_tag,
4794 	},
4795 	[FEAT_MEMCG_ACCOUNT] = {
4796 		"memcg-based memory accounting", probe_memcg_account,
4797 	},
4798 	[FEAT_BPF_COOKIE] = {
4799 		"BPF cookie support", probe_kern_bpf_cookie,
4800 	},
4801 	[FEAT_BTF_ENUM64] = {
4802 		"BTF_KIND_ENUM64 support", probe_kern_btf_enum64,
4803 	},
4804 	[FEAT_SYSCALL_WRAPPER] = {
4805 		"Kernel using syscall wrapper", probe_kern_syscall_wrapper,
4806 	},
4807 };
4808 
4809 bool kernel_supports(const struct bpf_object *obj, enum kern_feature_id feat_id)
4810 {
4811 	struct kern_feature_desc *feat = &feature_probes[feat_id];
4812 	int ret;
4813 
4814 	if (obj && obj->gen_loader)
4815 		/* To generate loader program assume the latest kernel
4816 		 * to avoid doing extra prog_load, map_create syscalls.
4817 		 */
4818 		return true;
4819 
4820 	if (READ_ONCE(feat->res) == FEAT_UNKNOWN) {
4821 		ret = feat->probe();
4822 		if (ret > 0) {
4823 			WRITE_ONCE(feat->res, FEAT_SUPPORTED);
4824 		} else if (ret == 0) {
4825 			WRITE_ONCE(feat->res, FEAT_MISSING);
4826 		} else {
4827 			pr_warn("Detection of kernel %s support failed: %d\n", feat->desc, ret);
4828 			WRITE_ONCE(feat->res, FEAT_MISSING);
4829 		}
4830 	}
4831 
4832 	return READ_ONCE(feat->res) == FEAT_SUPPORTED;
4833 }
4834 
4835 static bool map_is_reuse_compat(const struct bpf_map *map, int map_fd)
4836 {
4837 	struct bpf_map_info map_info;
4838 	char msg[STRERR_BUFSIZE];
4839 	__u32 map_info_len = sizeof(map_info);
4840 	int err;
4841 
4842 	memset(&map_info, 0, map_info_len);
4843 	err = bpf_obj_get_info_by_fd(map_fd, &map_info, &map_info_len);
4844 	if (err && errno == EINVAL)
4845 		err = bpf_get_map_info_from_fdinfo(map_fd, &map_info);
4846 	if (err) {
4847 		pr_warn("failed to get map info for map FD %d: %s\n", map_fd,
4848 			libbpf_strerror_r(errno, msg, sizeof(msg)));
4849 		return false;
4850 	}
4851 
4852 	return (map_info.type == map->def.type &&
4853 		map_info.key_size == map->def.key_size &&
4854 		map_info.value_size == map->def.value_size &&
4855 		map_info.max_entries == map->def.max_entries &&
4856 		map_info.map_flags == map->def.map_flags &&
4857 		map_info.map_extra == map->map_extra);
4858 }
4859 
4860 static int
4861 bpf_object__reuse_map(struct bpf_map *map)
4862 {
4863 	char *cp, errmsg[STRERR_BUFSIZE];
4864 	int err, pin_fd;
4865 
4866 	pin_fd = bpf_obj_get(map->pin_path);
4867 	if (pin_fd < 0) {
4868 		err = -errno;
4869 		if (err == -ENOENT) {
4870 			pr_debug("found no pinned map to reuse at '%s'\n",
4871 				 map->pin_path);
4872 			return 0;
4873 		}
4874 
4875 		cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
4876 		pr_warn("couldn't retrieve pinned map '%s': %s\n",
4877 			map->pin_path, cp);
4878 		return err;
4879 	}
4880 
4881 	if (!map_is_reuse_compat(map, pin_fd)) {
4882 		pr_warn("couldn't reuse pinned map at '%s': parameter mismatch\n",
4883 			map->pin_path);
4884 		close(pin_fd);
4885 		return -EINVAL;
4886 	}
4887 
4888 	err = bpf_map__reuse_fd(map, pin_fd);
4889 	close(pin_fd);
4890 	if (err) {
4891 		return err;
4892 	}
4893 	map->pinned = true;
4894 	pr_debug("reused pinned map at '%s'\n", map->pin_path);
4895 
4896 	return 0;
4897 }
4898 
4899 static int
4900 bpf_object__populate_internal_map(struct bpf_object *obj, struct bpf_map *map)
4901 {
4902 	enum libbpf_map_type map_type = map->libbpf_type;
4903 	char *cp, errmsg[STRERR_BUFSIZE];
4904 	int err, zero = 0;
4905 
4906 	if (obj->gen_loader) {
4907 		bpf_gen__map_update_elem(obj->gen_loader, map - obj->maps,
4908 					 map->mmaped, map->def.value_size);
4909 		if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG)
4910 			bpf_gen__map_freeze(obj->gen_loader, map - obj->maps);
4911 		return 0;
4912 	}
4913 	err = bpf_map_update_elem(map->fd, &zero, map->mmaped, 0);
4914 	if (err) {
4915 		err = -errno;
4916 		cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
4917 		pr_warn("Error setting initial map(%s) contents: %s\n",
4918 			map->name, cp);
4919 		return err;
4920 	}
4921 
4922 	/* Freeze .rodata and .kconfig map as read-only from syscall side. */
4923 	if (map_type == LIBBPF_MAP_RODATA || map_type == LIBBPF_MAP_KCONFIG) {
4924 		err = bpf_map_freeze(map->fd);
4925 		if (err) {
4926 			err = -errno;
4927 			cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
4928 			pr_warn("Error freezing map(%s) as read-only: %s\n",
4929 				map->name, cp);
4930 			return err;
4931 		}
4932 	}
4933 	return 0;
4934 }
4935 
4936 static void bpf_map__destroy(struct bpf_map *map);
4937 
4938 static int bpf_object__create_map(struct bpf_object *obj, struct bpf_map *map, bool is_inner)
4939 {
4940 	LIBBPF_OPTS(bpf_map_create_opts, create_attr);
4941 	struct bpf_map_def *def = &map->def;
4942 	const char *map_name = NULL;
4943 	int err = 0;
4944 
4945 	if (kernel_supports(obj, FEAT_PROG_NAME))
4946 		map_name = map->name;
4947 	create_attr.map_ifindex = map->map_ifindex;
4948 	create_attr.map_flags = def->map_flags;
4949 	create_attr.numa_node = map->numa_node;
4950 	create_attr.map_extra = map->map_extra;
4951 
4952 	if (bpf_map__is_struct_ops(map))
4953 		create_attr.btf_vmlinux_value_type_id = map->btf_vmlinux_value_type_id;
4954 
4955 	if (obj->btf && btf__fd(obj->btf) >= 0) {
4956 		create_attr.btf_fd = btf__fd(obj->btf);
4957 		create_attr.btf_key_type_id = map->btf_key_type_id;
4958 		create_attr.btf_value_type_id = map->btf_value_type_id;
4959 	}
4960 
4961 	if (bpf_map_type__is_map_in_map(def->type)) {
4962 		if (map->inner_map) {
4963 			err = bpf_object__create_map(obj, map->inner_map, true);
4964 			if (err) {
4965 				pr_warn("map '%s': failed to create inner map: %d\n",
4966 					map->name, err);
4967 				return err;
4968 			}
4969 			map->inner_map_fd = bpf_map__fd(map->inner_map);
4970 		}
4971 		if (map->inner_map_fd >= 0)
4972 			create_attr.inner_map_fd = map->inner_map_fd;
4973 	}
4974 
4975 	switch (def->type) {
4976 	case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
4977 	case BPF_MAP_TYPE_CGROUP_ARRAY:
4978 	case BPF_MAP_TYPE_STACK_TRACE:
4979 	case BPF_MAP_TYPE_ARRAY_OF_MAPS:
4980 	case BPF_MAP_TYPE_HASH_OF_MAPS:
4981 	case BPF_MAP_TYPE_DEVMAP:
4982 	case BPF_MAP_TYPE_DEVMAP_HASH:
4983 	case BPF_MAP_TYPE_CPUMAP:
4984 	case BPF_MAP_TYPE_XSKMAP:
4985 	case BPF_MAP_TYPE_SOCKMAP:
4986 	case BPF_MAP_TYPE_SOCKHASH:
4987 	case BPF_MAP_TYPE_QUEUE:
4988 	case BPF_MAP_TYPE_STACK:
4989 		create_attr.btf_fd = 0;
4990 		create_attr.btf_key_type_id = 0;
4991 		create_attr.btf_value_type_id = 0;
4992 		map->btf_key_type_id = 0;
4993 		map->btf_value_type_id = 0;
4994 	default:
4995 		break;
4996 	}
4997 
4998 	if (obj->gen_loader) {
4999 		bpf_gen__map_create(obj->gen_loader, def->type, map_name,
5000 				    def->key_size, def->value_size, def->max_entries,
5001 				    &create_attr, is_inner ? -1 : map - obj->maps);
5002 		/* Pretend to have valid FD to pass various fd >= 0 checks.
5003 		 * This fd == 0 will not be used with any syscall and will be reset to -1 eventually.
5004 		 */
5005 		map->fd = 0;
5006 	} else {
5007 		map->fd = bpf_map_create(def->type, map_name,
5008 					 def->key_size, def->value_size,
5009 					 def->max_entries, &create_attr);
5010 	}
5011 	if (map->fd < 0 && (create_attr.btf_key_type_id ||
5012 			    create_attr.btf_value_type_id)) {
5013 		char *cp, errmsg[STRERR_BUFSIZE];
5014 
5015 		err = -errno;
5016 		cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5017 		pr_warn("Error in bpf_create_map_xattr(%s):%s(%d). Retrying without BTF.\n",
5018 			map->name, cp, err);
5019 		create_attr.btf_fd = 0;
5020 		create_attr.btf_key_type_id = 0;
5021 		create_attr.btf_value_type_id = 0;
5022 		map->btf_key_type_id = 0;
5023 		map->btf_value_type_id = 0;
5024 		map->fd = bpf_map_create(def->type, map_name,
5025 					 def->key_size, def->value_size,
5026 					 def->max_entries, &create_attr);
5027 	}
5028 
5029 	err = map->fd < 0 ? -errno : 0;
5030 
5031 	if (bpf_map_type__is_map_in_map(def->type) && map->inner_map) {
5032 		if (obj->gen_loader)
5033 			map->inner_map->fd = -1;
5034 		bpf_map__destroy(map->inner_map);
5035 		zfree(&map->inner_map);
5036 	}
5037 
5038 	return err;
5039 }
5040 
5041 static int init_map_in_map_slots(struct bpf_object *obj, struct bpf_map *map)
5042 {
5043 	const struct bpf_map *targ_map;
5044 	unsigned int i;
5045 	int fd, err = 0;
5046 
5047 	for (i = 0; i < map->init_slots_sz; i++) {
5048 		if (!map->init_slots[i])
5049 			continue;
5050 
5051 		targ_map = map->init_slots[i];
5052 		fd = bpf_map__fd(targ_map);
5053 
5054 		if (obj->gen_loader) {
5055 			bpf_gen__populate_outer_map(obj->gen_loader,
5056 						    map - obj->maps, i,
5057 						    targ_map - obj->maps);
5058 		} else {
5059 			err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5060 		}
5061 		if (err) {
5062 			err = -errno;
5063 			pr_warn("map '%s': failed to initialize slot [%d] to map '%s' fd=%d: %d\n",
5064 				map->name, i, targ_map->name, fd, err);
5065 			return err;
5066 		}
5067 		pr_debug("map '%s': slot [%d] set to map '%s' fd=%d\n",
5068 			 map->name, i, targ_map->name, fd);
5069 	}
5070 
5071 	zfree(&map->init_slots);
5072 	map->init_slots_sz = 0;
5073 
5074 	return 0;
5075 }
5076 
5077 static int init_prog_array_slots(struct bpf_object *obj, struct bpf_map *map)
5078 {
5079 	const struct bpf_program *targ_prog;
5080 	unsigned int i;
5081 	int fd, err;
5082 
5083 	if (obj->gen_loader)
5084 		return -ENOTSUP;
5085 
5086 	for (i = 0; i < map->init_slots_sz; i++) {
5087 		if (!map->init_slots[i])
5088 			continue;
5089 
5090 		targ_prog = map->init_slots[i];
5091 		fd = bpf_program__fd(targ_prog);
5092 
5093 		err = bpf_map_update_elem(map->fd, &i, &fd, 0);
5094 		if (err) {
5095 			err = -errno;
5096 			pr_warn("map '%s': failed to initialize slot [%d] to prog '%s' fd=%d: %d\n",
5097 				map->name, i, targ_prog->name, fd, err);
5098 			return err;
5099 		}
5100 		pr_debug("map '%s': slot [%d] set to prog '%s' fd=%d\n",
5101 			 map->name, i, targ_prog->name, fd);
5102 	}
5103 
5104 	zfree(&map->init_slots);
5105 	map->init_slots_sz = 0;
5106 
5107 	return 0;
5108 }
5109 
5110 static int bpf_object_init_prog_arrays(struct bpf_object *obj)
5111 {
5112 	struct bpf_map *map;
5113 	int i, err;
5114 
5115 	for (i = 0; i < obj->nr_maps; i++) {
5116 		map = &obj->maps[i];
5117 
5118 		if (!map->init_slots_sz || map->def.type != BPF_MAP_TYPE_PROG_ARRAY)
5119 			continue;
5120 
5121 		err = init_prog_array_slots(obj, map);
5122 		if (err < 0) {
5123 			zclose(map->fd);
5124 			return err;
5125 		}
5126 	}
5127 	return 0;
5128 }
5129 
5130 static int map_set_def_max_entries(struct bpf_map *map)
5131 {
5132 	if (map->def.type == BPF_MAP_TYPE_PERF_EVENT_ARRAY && !map->def.max_entries) {
5133 		int nr_cpus;
5134 
5135 		nr_cpus = libbpf_num_possible_cpus();
5136 		if (nr_cpus < 0) {
5137 			pr_warn("map '%s': failed to determine number of system CPUs: %d\n",
5138 				map->name, nr_cpus);
5139 			return nr_cpus;
5140 		}
5141 		pr_debug("map '%s': setting size to %d\n", map->name, nr_cpus);
5142 		map->def.max_entries = nr_cpus;
5143 	}
5144 
5145 	return 0;
5146 }
5147 
5148 static int
5149 bpf_object__create_maps(struct bpf_object *obj)
5150 {
5151 	struct bpf_map *map;
5152 	char *cp, errmsg[STRERR_BUFSIZE];
5153 	unsigned int i, j;
5154 	int err;
5155 	bool retried;
5156 
5157 	for (i = 0; i < obj->nr_maps; i++) {
5158 		map = &obj->maps[i];
5159 
5160 		/* To support old kernels, we skip creating global data maps
5161 		 * (.rodata, .data, .kconfig, etc); later on, during program
5162 		 * loading, if we detect that at least one of the to-be-loaded
5163 		 * programs is referencing any global data map, we'll error
5164 		 * out with program name and relocation index logged.
5165 		 * This approach allows to accommodate Clang emitting
5166 		 * unnecessary .rodata.str1.1 sections for string literals,
5167 		 * but also it allows to have CO-RE applications that use
5168 		 * global variables in some of BPF programs, but not others.
5169 		 * If those global variable-using programs are not loaded at
5170 		 * runtime due to bpf_program__set_autoload(prog, false),
5171 		 * bpf_object loading will succeed just fine even on old
5172 		 * kernels.
5173 		 */
5174 		if (bpf_map__is_internal(map) && !kernel_supports(obj, FEAT_GLOBAL_DATA))
5175 			map->autocreate = false;
5176 
5177 		if (!map->autocreate) {
5178 			pr_debug("map '%s': skipped auto-creating...\n", map->name);
5179 			continue;
5180 		}
5181 
5182 		err = map_set_def_max_entries(map);
5183 		if (err)
5184 			goto err_out;
5185 
5186 		retried = false;
5187 retry:
5188 		if (map->pin_path) {
5189 			err = bpf_object__reuse_map(map);
5190 			if (err) {
5191 				pr_warn("map '%s': error reusing pinned map\n",
5192 					map->name);
5193 				goto err_out;
5194 			}
5195 			if (retried && map->fd < 0) {
5196 				pr_warn("map '%s': cannot find pinned map\n",
5197 					map->name);
5198 				err = -ENOENT;
5199 				goto err_out;
5200 			}
5201 		}
5202 
5203 		if (map->fd >= 0) {
5204 			pr_debug("map '%s': skipping creation (preset fd=%d)\n",
5205 				 map->name, map->fd);
5206 		} else {
5207 			err = bpf_object__create_map(obj, map, false);
5208 			if (err)
5209 				goto err_out;
5210 
5211 			pr_debug("map '%s': created successfully, fd=%d\n",
5212 				 map->name, map->fd);
5213 
5214 			if (bpf_map__is_internal(map)) {
5215 				err = bpf_object__populate_internal_map(obj, map);
5216 				if (err < 0) {
5217 					zclose(map->fd);
5218 					goto err_out;
5219 				}
5220 			}
5221 
5222 			if (map->init_slots_sz && map->def.type != BPF_MAP_TYPE_PROG_ARRAY) {
5223 				err = init_map_in_map_slots(obj, map);
5224 				if (err < 0) {
5225 					zclose(map->fd);
5226 					goto err_out;
5227 				}
5228 			}
5229 		}
5230 
5231 		if (map->pin_path && !map->pinned) {
5232 			err = bpf_map__pin(map, NULL);
5233 			if (err) {
5234 				zclose(map->fd);
5235 				if (!retried && err == -EEXIST) {
5236 					retried = true;
5237 					goto retry;
5238 				}
5239 				pr_warn("map '%s': failed to auto-pin at '%s': %d\n",
5240 					map->name, map->pin_path, err);
5241 				goto err_out;
5242 			}
5243 		}
5244 	}
5245 
5246 	return 0;
5247 
5248 err_out:
5249 	cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
5250 	pr_warn("map '%s': failed to create: %s(%d)\n", map->name, cp, err);
5251 	pr_perm_msg(err);
5252 	for (j = 0; j < i; j++)
5253 		zclose(obj->maps[j].fd);
5254 	return err;
5255 }
5256 
5257 static bool bpf_core_is_flavor_sep(const char *s)
5258 {
5259 	/* check X___Y name pattern, where X and Y are not underscores */
5260 	return s[0] != '_' &&				      /* X */
5261 	       s[1] == '_' && s[2] == '_' && s[3] == '_' &&   /* ___ */
5262 	       s[4] != '_';				      /* Y */
5263 }
5264 
5265 /* Given 'some_struct_name___with_flavor' return the length of a name prefix
5266  * before last triple underscore. Struct name part after last triple
5267  * underscore is ignored by BPF CO-RE relocation during relocation matching.
5268  */
5269 size_t bpf_core_essential_name_len(const char *name)
5270 {
5271 	size_t n = strlen(name);
5272 	int i;
5273 
5274 	for (i = n - 5; i >= 0; i--) {
5275 		if (bpf_core_is_flavor_sep(name + i))
5276 			return i + 1;
5277 	}
5278 	return n;
5279 }
5280 
5281 void bpf_core_free_cands(struct bpf_core_cand_list *cands)
5282 {
5283 	if (!cands)
5284 		return;
5285 
5286 	free(cands->cands);
5287 	free(cands);
5288 }
5289 
5290 int bpf_core_add_cands(struct bpf_core_cand *local_cand,
5291 		       size_t local_essent_len,
5292 		       const struct btf *targ_btf,
5293 		       const char *targ_btf_name,
5294 		       int targ_start_id,
5295 		       struct bpf_core_cand_list *cands)
5296 {
5297 	struct bpf_core_cand *new_cands, *cand;
5298 	const struct btf_type *t, *local_t;
5299 	const char *targ_name, *local_name;
5300 	size_t targ_essent_len;
5301 	int n, i;
5302 
5303 	local_t = btf__type_by_id(local_cand->btf, local_cand->id);
5304 	local_name = btf__str_by_offset(local_cand->btf, local_t->name_off);
5305 
5306 	n = btf__type_cnt(targ_btf);
5307 	for (i = targ_start_id; i < n; i++) {
5308 		t = btf__type_by_id(targ_btf, i);
5309 		if (!btf_kind_core_compat(t, local_t))
5310 			continue;
5311 
5312 		targ_name = btf__name_by_offset(targ_btf, t->name_off);
5313 		if (str_is_empty(targ_name))
5314 			continue;
5315 
5316 		targ_essent_len = bpf_core_essential_name_len(targ_name);
5317 		if (targ_essent_len != local_essent_len)
5318 			continue;
5319 
5320 		if (strncmp(local_name, targ_name, local_essent_len) != 0)
5321 			continue;
5322 
5323 		pr_debug("CO-RE relocating [%d] %s %s: found target candidate [%d] %s %s in [%s]\n",
5324 			 local_cand->id, btf_kind_str(local_t),
5325 			 local_name, i, btf_kind_str(t), targ_name,
5326 			 targ_btf_name);
5327 		new_cands = libbpf_reallocarray(cands->cands, cands->len + 1,
5328 					      sizeof(*cands->cands));
5329 		if (!new_cands)
5330 			return -ENOMEM;
5331 
5332 		cand = &new_cands[cands->len];
5333 		cand->btf = targ_btf;
5334 		cand->id = i;
5335 
5336 		cands->cands = new_cands;
5337 		cands->len++;
5338 	}
5339 	return 0;
5340 }
5341 
5342 static int load_module_btfs(struct bpf_object *obj)
5343 {
5344 	struct bpf_btf_info info;
5345 	struct module_btf *mod_btf;
5346 	struct btf *btf;
5347 	char name[64];
5348 	__u32 id = 0, len;
5349 	int err, fd;
5350 
5351 	if (obj->btf_modules_loaded)
5352 		return 0;
5353 
5354 	if (obj->gen_loader)
5355 		return 0;
5356 
5357 	/* don't do this again, even if we find no module BTFs */
5358 	obj->btf_modules_loaded = true;
5359 
5360 	/* kernel too old to support module BTFs */
5361 	if (!kernel_supports(obj, FEAT_MODULE_BTF))
5362 		return 0;
5363 
5364 	while (true) {
5365 		err = bpf_btf_get_next_id(id, &id);
5366 		if (err && errno == ENOENT)
5367 			return 0;
5368 		if (err) {
5369 			err = -errno;
5370 			pr_warn("failed to iterate BTF objects: %d\n", err);
5371 			return err;
5372 		}
5373 
5374 		fd = bpf_btf_get_fd_by_id(id);
5375 		if (fd < 0) {
5376 			if (errno == ENOENT)
5377 				continue; /* expected race: BTF was unloaded */
5378 			err = -errno;
5379 			pr_warn("failed to get BTF object #%d FD: %d\n", id, err);
5380 			return err;
5381 		}
5382 
5383 		len = sizeof(info);
5384 		memset(&info, 0, sizeof(info));
5385 		info.name = ptr_to_u64(name);
5386 		info.name_len = sizeof(name);
5387 
5388 		err = bpf_obj_get_info_by_fd(fd, &info, &len);
5389 		if (err) {
5390 			err = -errno;
5391 			pr_warn("failed to get BTF object #%d info: %d\n", id, err);
5392 			goto err_out;
5393 		}
5394 
5395 		/* ignore non-module BTFs */
5396 		if (!info.kernel_btf || strcmp(name, "vmlinux") == 0) {
5397 			close(fd);
5398 			continue;
5399 		}
5400 
5401 		btf = btf_get_from_fd(fd, obj->btf_vmlinux);
5402 		err = libbpf_get_error(btf);
5403 		if (err) {
5404 			pr_warn("failed to load module [%s]'s BTF object #%d: %d\n",
5405 				name, id, err);
5406 			goto err_out;
5407 		}
5408 
5409 		err = libbpf_ensure_mem((void **)&obj->btf_modules, &obj->btf_module_cap,
5410 				        sizeof(*obj->btf_modules), obj->btf_module_cnt + 1);
5411 		if (err)
5412 			goto err_out;
5413 
5414 		mod_btf = &obj->btf_modules[obj->btf_module_cnt++];
5415 
5416 		mod_btf->btf = btf;
5417 		mod_btf->id = id;
5418 		mod_btf->fd = fd;
5419 		mod_btf->name = strdup(name);
5420 		if (!mod_btf->name) {
5421 			err = -ENOMEM;
5422 			goto err_out;
5423 		}
5424 		continue;
5425 
5426 err_out:
5427 		close(fd);
5428 		return err;
5429 	}
5430 
5431 	return 0;
5432 }
5433 
5434 static struct bpf_core_cand_list *
5435 bpf_core_find_cands(struct bpf_object *obj, const struct btf *local_btf, __u32 local_type_id)
5436 {
5437 	struct bpf_core_cand local_cand = {};
5438 	struct bpf_core_cand_list *cands;
5439 	const struct btf *main_btf;
5440 	const struct btf_type *local_t;
5441 	const char *local_name;
5442 	size_t local_essent_len;
5443 	int err, i;
5444 
5445 	local_cand.btf = local_btf;
5446 	local_cand.id = local_type_id;
5447 	local_t = btf__type_by_id(local_btf, local_type_id);
5448 	if (!local_t)
5449 		return ERR_PTR(-EINVAL);
5450 
5451 	local_name = btf__name_by_offset(local_btf, local_t->name_off);
5452 	if (str_is_empty(local_name))
5453 		return ERR_PTR(-EINVAL);
5454 	local_essent_len = bpf_core_essential_name_len(local_name);
5455 
5456 	cands = calloc(1, sizeof(*cands));
5457 	if (!cands)
5458 		return ERR_PTR(-ENOMEM);
5459 
5460 	/* Attempt to find target candidates in vmlinux BTF first */
5461 	main_btf = obj->btf_vmlinux_override ?: obj->btf_vmlinux;
5462 	err = bpf_core_add_cands(&local_cand, local_essent_len, main_btf, "vmlinux", 1, cands);
5463 	if (err)
5464 		goto err_out;
5465 
5466 	/* if vmlinux BTF has any candidate, don't got for module BTFs */
5467 	if (cands->len)
5468 		return cands;
5469 
5470 	/* if vmlinux BTF was overridden, don't attempt to load module BTFs */
5471 	if (obj->btf_vmlinux_override)
5472 		return cands;
5473 
5474 	/* now look through module BTFs, trying to still find candidates */
5475 	err = load_module_btfs(obj);
5476 	if (err)
5477 		goto err_out;
5478 
5479 	for (i = 0; i < obj->btf_module_cnt; i++) {
5480 		err = bpf_core_add_cands(&local_cand, local_essent_len,
5481 					 obj->btf_modules[i].btf,
5482 					 obj->btf_modules[i].name,
5483 					 btf__type_cnt(obj->btf_vmlinux),
5484 					 cands);
5485 		if (err)
5486 			goto err_out;
5487 	}
5488 
5489 	return cands;
5490 err_out:
5491 	bpf_core_free_cands(cands);
5492 	return ERR_PTR(err);
5493 }
5494 
5495 /* Check local and target types for compatibility. This check is used for
5496  * type-based CO-RE relocations and follow slightly different rules than
5497  * field-based relocations. This function assumes that root types were already
5498  * checked for name match. Beyond that initial root-level name check, names
5499  * are completely ignored. Compatibility rules are as follows:
5500  *   - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs are considered compatible, but
5501  *     kind should match for local and target types (i.e., STRUCT is not
5502  *     compatible with UNION);
5503  *   - for ENUMs, the size is ignored;
5504  *   - for INT, size and signedness are ignored;
5505  *   - for ARRAY, dimensionality is ignored, element types are checked for
5506  *     compatibility recursively;
5507  *   - CONST/VOLATILE/RESTRICT modifiers are ignored;
5508  *   - TYPEDEFs/PTRs are compatible if types they pointing to are compatible;
5509  *   - FUNC_PROTOs are compatible if they have compatible signature: same
5510  *     number of input args and compatible return and argument types.
5511  * These rules are not set in stone and probably will be adjusted as we get
5512  * more experience with using BPF CO-RE relocations.
5513  */
5514 int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
5515 			      const struct btf *targ_btf, __u32 targ_id)
5516 {
5517 	return __bpf_core_types_are_compat(local_btf, local_id, targ_btf, targ_id, 32);
5518 }
5519 
5520 int bpf_core_types_match(const struct btf *local_btf, __u32 local_id,
5521 			 const struct btf *targ_btf, __u32 targ_id)
5522 {
5523 	return __bpf_core_types_match(local_btf, local_id, targ_btf, targ_id, false, 32);
5524 }
5525 
5526 static size_t bpf_core_hash_fn(const void *key, void *ctx)
5527 {
5528 	return (size_t)key;
5529 }
5530 
5531 static bool bpf_core_equal_fn(const void *k1, const void *k2, void *ctx)
5532 {
5533 	return k1 == k2;
5534 }
5535 
5536 static void *u32_as_hash_key(__u32 x)
5537 {
5538 	return (void *)(uintptr_t)x;
5539 }
5540 
5541 static int record_relo_core(struct bpf_program *prog,
5542 			    const struct bpf_core_relo *core_relo, int insn_idx)
5543 {
5544 	struct reloc_desc *relos, *relo;
5545 
5546 	relos = libbpf_reallocarray(prog->reloc_desc,
5547 				    prog->nr_reloc + 1, sizeof(*relos));
5548 	if (!relos)
5549 		return -ENOMEM;
5550 	relo = &relos[prog->nr_reloc];
5551 	relo->type = RELO_CORE;
5552 	relo->insn_idx = insn_idx;
5553 	relo->core_relo = core_relo;
5554 	prog->reloc_desc = relos;
5555 	prog->nr_reloc++;
5556 	return 0;
5557 }
5558 
5559 static const struct bpf_core_relo *find_relo_core(struct bpf_program *prog, int insn_idx)
5560 {
5561 	struct reloc_desc *relo;
5562 	int i;
5563 
5564 	for (i = 0; i < prog->nr_reloc; i++) {
5565 		relo = &prog->reloc_desc[i];
5566 		if (relo->type != RELO_CORE || relo->insn_idx != insn_idx)
5567 			continue;
5568 
5569 		return relo->core_relo;
5570 	}
5571 
5572 	return NULL;
5573 }
5574 
5575 static int bpf_core_resolve_relo(struct bpf_program *prog,
5576 				 const struct bpf_core_relo *relo,
5577 				 int relo_idx,
5578 				 const struct btf *local_btf,
5579 				 struct hashmap *cand_cache,
5580 				 struct bpf_core_relo_res *targ_res)
5581 {
5582 	struct bpf_core_spec specs_scratch[3] = {};
5583 	const void *type_key = u32_as_hash_key(relo->type_id);
5584 	struct bpf_core_cand_list *cands = NULL;
5585 	const char *prog_name = prog->name;
5586 	const struct btf_type *local_type;
5587 	const char *local_name;
5588 	__u32 local_id = relo->type_id;
5589 	int err;
5590 
5591 	local_type = btf__type_by_id(local_btf, local_id);
5592 	if (!local_type)
5593 		return -EINVAL;
5594 
5595 	local_name = btf__name_by_offset(local_btf, local_type->name_off);
5596 	if (!local_name)
5597 		return -EINVAL;
5598 
5599 	if (relo->kind != BPF_CORE_TYPE_ID_LOCAL &&
5600 	    !hashmap__find(cand_cache, type_key, (void **)&cands)) {
5601 		cands = bpf_core_find_cands(prog->obj, local_btf, local_id);
5602 		if (IS_ERR(cands)) {
5603 			pr_warn("prog '%s': relo #%d: target candidate search failed for [%d] %s %s: %ld\n",
5604 				prog_name, relo_idx, local_id, btf_kind_str(local_type),
5605 				local_name, PTR_ERR(cands));
5606 			return PTR_ERR(cands);
5607 		}
5608 		err = hashmap__set(cand_cache, type_key, cands, NULL, NULL);
5609 		if (err) {
5610 			bpf_core_free_cands(cands);
5611 			return err;
5612 		}
5613 	}
5614 
5615 	return bpf_core_calc_relo_insn(prog_name, relo, relo_idx, local_btf, cands, specs_scratch,
5616 				       targ_res);
5617 }
5618 
5619 static int
5620 bpf_object__relocate_core(struct bpf_object *obj, const char *targ_btf_path)
5621 {
5622 	const struct btf_ext_info_sec *sec;
5623 	struct bpf_core_relo_res targ_res;
5624 	const struct bpf_core_relo *rec;
5625 	const struct btf_ext_info *seg;
5626 	struct hashmap_entry *entry;
5627 	struct hashmap *cand_cache = NULL;
5628 	struct bpf_program *prog;
5629 	struct bpf_insn *insn;
5630 	const char *sec_name;
5631 	int i, err = 0, insn_idx, sec_idx, sec_num;
5632 
5633 	if (obj->btf_ext->core_relo_info.len == 0)
5634 		return 0;
5635 
5636 	if (targ_btf_path) {
5637 		obj->btf_vmlinux_override = btf__parse(targ_btf_path, NULL);
5638 		err = libbpf_get_error(obj->btf_vmlinux_override);
5639 		if (err) {
5640 			pr_warn("failed to parse target BTF: %d\n", err);
5641 			return err;
5642 		}
5643 	}
5644 
5645 	cand_cache = hashmap__new(bpf_core_hash_fn, bpf_core_equal_fn, NULL);
5646 	if (IS_ERR(cand_cache)) {
5647 		err = PTR_ERR(cand_cache);
5648 		goto out;
5649 	}
5650 
5651 	seg = &obj->btf_ext->core_relo_info;
5652 	sec_num = 0;
5653 	for_each_btf_ext_sec(seg, sec) {
5654 		sec_idx = seg->sec_idxs[sec_num];
5655 		sec_num++;
5656 
5657 		sec_name = btf__name_by_offset(obj->btf, sec->sec_name_off);
5658 		if (str_is_empty(sec_name)) {
5659 			err = -EINVAL;
5660 			goto out;
5661 		}
5662 
5663 		pr_debug("sec '%s': found %d CO-RE relocations\n", sec_name, sec->num_info);
5664 
5665 		for_each_btf_ext_rec(seg, sec, i, rec) {
5666 			if (rec->insn_off % BPF_INSN_SZ)
5667 				return -EINVAL;
5668 			insn_idx = rec->insn_off / BPF_INSN_SZ;
5669 			prog = find_prog_by_sec_insn(obj, sec_idx, insn_idx);
5670 			if (!prog) {
5671 				/* When __weak subprog is "overridden" by another instance
5672 				 * of the subprog from a different object file, linker still
5673 				 * appends all the .BTF.ext info that used to belong to that
5674 				 * eliminated subprogram.
5675 				 * This is similar to what x86-64 linker does for relocations.
5676 				 * So just ignore such relocations just like we ignore
5677 				 * subprog instructions when discovering subprograms.
5678 				 */
5679 				pr_debug("sec '%s': skipping CO-RE relocation #%d for insn #%d belonging to eliminated weak subprogram\n",
5680 					 sec_name, i, insn_idx);
5681 				continue;
5682 			}
5683 			/* no need to apply CO-RE relocation if the program is
5684 			 * not going to be loaded
5685 			 */
5686 			if (!prog->autoload)
5687 				continue;
5688 
5689 			/* adjust insn_idx from section frame of reference to the local
5690 			 * program's frame of reference; (sub-)program code is not yet
5691 			 * relocated, so it's enough to just subtract in-section offset
5692 			 */
5693 			insn_idx = insn_idx - prog->sec_insn_off;
5694 			if (insn_idx >= prog->insns_cnt)
5695 				return -EINVAL;
5696 			insn = &prog->insns[insn_idx];
5697 
5698 			err = record_relo_core(prog, rec, insn_idx);
5699 			if (err) {
5700 				pr_warn("prog '%s': relo #%d: failed to record relocation: %d\n",
5701 					prog->name, i, err);
5702 				goto out;
5703 			}
5704 
5705 			if (prog->obj->gen_loader)
5706 				continue;
5707 
5708 			err = bpf_core_resolve_relo(prog, rec, i, obj->btf, cand_cache, &targ_res);
5709 			if (err) {
5710 				pr_warn("prog '%s': relo #%d: failed to relocate: %d\n",
5711 					prog->name, i, err);
5712 				goto out;
5713 			}
5714 
5715 			err = bpf_core_patch_insn(prog->name, insn, insn_idx, rec, i, &targ_res);
5716 			if (err) {
5717 				pr_warn("prog '%s': relo #%d: failed to patch insn #%u: %d\n",
5718 					prog->name, i, insn_idx, err);
5719 				goto out;
5720 			}
5721 		}
5722 	}
5723 
5724 out:
5725 	/* obj->btf_vmlinux and module BTFs are freed after object load */
5726 	btf__free(obj->btf_vmlinux_override);
5727 	obj->btf_vmlinux_override = NULL;
5728 
5729 	if (!IS_ERR_OR_NULL(cand_cache)) {
5730 		hashmap__for_each_entry(cand_cache, entry, i) {
5731 			bpf_core_free_cands(entry->value);
5732 		}
5733 		hashmap__free(cand_cache);
5734 	}
5735 	return err;
5736 }
5737 
5738 /* base map load ldimm64 special constant, used also for log fixup logic */
5739 #define MAP_LDIMM64_POISON_BASE 2001000000
5740 #define MAP_LDIMM64_POISON_PFX "200100"
5741 
5742 static void poison_map_ldimm64(struct bpf_program *prog, int relo_idx,
5743 			       int insn_idx, struct bpf_insn *insn,
5744 			       int map_idx, const struct bpf_map *map)
5745 {
5746 	int i;
5747 
5748 	pr_debug("prog '%s': relo #%d: poisoning insn #%d that loads map #%d '%s'\n",
5749 		 prog->name, relo_idx, insn_idx, map_idx, map->name);
5750 
5751 	/* we turn single ldimm64 into two identical invalid calls */
5752 	for (i = 0; i < 2; i++) {
5753 		insn->code = BPF_JMP | BPF_CALL;
5754 		insn->dst_reg = 0;
5755 		insn->src_reg = 0;
5756 		insn->off = 0;
5757 		/* if this instruction is reachable (not a dead code),
5758 		 * verifier will complain with something like:
5759 		 * invalid func unknown#2001000123
5760 		 * where lower 123 is map index into obj->maps[] array
5761 		 */
5762 		insn->imm = MAP_LDIMM64_POISON_BASE + map_idx;
5763 
5764 		insn++;
5765 	}
5766 }
5767 
5768 /* Relocate data references within program code:
5769  *  - map references;
5770  *  - global variable references;
5771  *  - extern references.
5772  */
5773 static int
5774 bpf_object__relocate_data(struct bpf_object *obj, struct bpf_program *prog)
5775 {
5776 	int i;
5777 
5778 	for (i = 0; i < prog->nr_reloc; i++) {
5779 		struct reloc_desc *relo = &prog->reloc_desc[i];
5780 		struct bpf_insn *insn = &prog->insns[relo->insn_idx];
5781 		const struct bpf_map *map;
5782 		struct extern_desc *ext;
5783 
5784 		switch (relo->type) {
5785 		case RELO_LD64:
5786 			map = &obj->maps[relo->map_idx];
5787 			if (obj->gen_loader) {
5788 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX;
5789 				insn[0].imm = relo->map_idx;
5790 			} else if (map->autocreate) {
5791 				insn[0].src_reg = BPF_PSEUDO_MAP_FD;
5792 				insn[0].imm = map->fd;
5793 			} else {
5794 				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
5795 						   relo->map_idx, map);
5796 			}
5797 			break;
5798 		case RELO_DATA:
5799 			map = &obj->maps[relo->map_idx];
5800 			insn[1].imm = insn[0].imm + relo->sym_off;
5801 			if (obj->gen_loader) {
5802 				insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
5803 				insn[0].imm = relo->map_idx;
5804 			} else if (map->autocreate) {
5805 				insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
5806 				insn[0].imm = map->fd;
5807 			} else {
5808 				poison_map_ldimm64(prog, i, relo->insn_idx, insn,
5809 						   relo->map_idx, map);
5810 			}
5811 			break;
5812 		case RELO_EXTERN_VAR:
5813 			ext = &obj->externs[relo->sym_off];
5814 			if (ext->type == EXT_KCFG) {
5815 				if (obj->gen_loader) {
5816 					insn[0].src_reg = BPF_PSEUDO_MAP_IDX_VALUE;
5817 					insn[0].imm = obj->kconfig_map_idx;
5818 				} else {
5819 					insn[0].src_reg = BPF_PSEUDO_MAP_VALUE;
5820 					insn[0].imm = obj->maps[obj->kconfig_map_idx].fd;
5821 				}
5822 				insn[1].imm = ext->kcfg.data_off;
5823 			} else /* EXT_KSYM */ {
5824 				if (ext->ksym.type_id && ext->is_set) { /* typed ksyms */
5825 					insn[0].src_reg = BPF_PSEUDO_BTF_ID;
5826 					insn[0].imm = ext->ksym.kernel_btf_id;
5827 					insn[1].imm = ext->ksym.kernel_btf_obj_fd;
5828 				} else { /* typeless ksyms or unresolved typed ksyms */
5829 					insn[0].imm = (__u32)ext->ksym.addr;
5830 					insn[1].imm = ext->ksym.addr >> 32;
5831 				}
5832 			}
5833 			break;
5834 		case RELO_EXTERN_FUNC:
5835 			ext = &obj->externs[relo->sym_off];
5836 			insn[0].src_reg = BPF_PSEUDO_KFUNC_CALL;
5837 			if (ext->is_set) {
5838 				insn[0].imm = ext->ksym.kernel_btf_id;
5839 				insn[0].off = ext->ksym.btf_fd_idx;
5840 			} else { /* unresolved weak kfunc */
5841 				insn[0].imm = 0;
5842 				insn[0].off = 0;
5843 			}
5844 			break;
5845 		case RELO_SUBPROG_ADDR:
5846 			if (insn[0].src_reg != BPF_PSEUDO_FUNC) {
5847 				pr_warn("prog '%s': relo #%d: bad insn\n",
5848 					prog->name, i);
5849 				return -EINVAL;
5850 			}
5851 			/* handled already */
5852 			break;
5853 		case RELO_CALL:
5854 			/* handled already */
5855 			break;
5856 		case RELO_CORE:
5857 			/* will be handled by bpf_program_record_relos() */
5858 			break;
5859 		default:
5860 			pr_warn("prog '%s': relo #%d: bad relo type %d\n",
5861 				prog->name, i, relo->type);
5862 			return -EINVAL;
5863 		}
5864 	}
5865 
5866 	return 0;
5867 }
5868 
5869 static int adjust_prog_btf_ext_info(const struct bpf_object *obj,
5870 				    const struct bpf_program *prog,
5871 				    const struct btf_ext_info *ext_info,
5872 				    void **prog_info, __u32 *prog_rec_cnt,
5873 				    __u32 *prog_rec_sz)
5874 {
5875 	void *copy_start = NULL, *copy_end = NULL;
5876 	void *rec, *rec_end, *new_prog_info;
5877 	const struct btf_ext_info_sec *sec;
5878 	size_t old_sz, new_sz;
5879 	int i, sec_num, sec_idx, off_adj;
5880 
5881 	sec_num = 0;
5882 	for_each_btf_ext_sec(ext_info, sec) {
5883 		sec_idx = ext_info->sec_idxs[sec_num];
5884 		sec_num++;
5885 		if (prog->sec_idx != sec_idx)
5886 			continue;
5887 
5888 		for_each_btf_ext_rec(ext_info, sec, i, rec) {
5889 			__u32 insn_off = *(__u32 *)rec / BPF_INSN_SZ;
5890 
5891 			if (insn_off < prog->sec_insn_off)
5892 				continue;
5893 			if (insn_off >= prog->sec_insn_off + prog->sec_insn_cnt)
5894 				break;
5895 
5896 			if (!copy_start)
5897 				copy_start = rec;
5898 			copy_end = rec + ext_info->rec_size;
5899 		}
5900 
5901 		if (!copy_start)
5902 			return -ENOENT;
5903 
5904 		/* append func/line info of a given (sub-)program to the main
5905 		 * program func/line info
5906 		 */
5907 		old_sz = (size_t)(*prog_rec_cnt) * ext_info->rec_size;
5908 		new_sz = old_sz + (copy_end - copy_start);
5909 		new_prog_info = realloc(*prog_info, new_sz);
5910 		if (!new_prog_info)
5911 			return -ENOMEM;
5912 		*prog_info = new_prog_info;
5913 		*prog_rec_cnt = new_sz / ext_info->rec_size;
5914 		memcpy(new_prog_info + old_sz, copy_start, copy_end - copy_start);
5915 
5916 		/* Kernel instruction offsets are in units of 8-byte
5917 		 * instructions, while .BTF.ext instruction offsets generated
5918 		 * by Clang are in units of bytes. So convert Clang offsets
5919 		 * into kernel offsets and adjust offset according to program
5920 		 * relocated position.
5921 		 */
5922 		off_adj = prog->sub_insn_off - prog->sec_insn_off;
5923 		rec = new_prog_info + old_sz;
5924 		rec_end = new_prog_info + new_sz;
5925 		for (; rec < rec_end; rec += ext_info->rec_size) {
5926 			__u32 *insn_off = rec;
5927 
5928 			*insn_off = *insn_off / BPF_INSN_SZ + off_adj;
5929 		}
5930 		*prog_rec_sz = ext_info->rec_size;
5931 		return 0;
5932 	}
5933 
5934 	return -ENOENT;
5935 }
5936 
5937 static int
5938 reloc_prog_func_and_line_info(const struct bpf_object *obj,
5939 			      struct bpf_program *main_prog,
5940 			      const struct bpf_program *prog)
5941 {
5942 	int err;
5943 
5944 	/* no .BTF.ext relocation if .BTF.ext is missing or kernel doesn't
5945 	 * supprot func/line info
5946 	 */
5947 	if (!obj->btf_ext || !kernel_supports(obj, FEAT_BTF_FUNC))
5948 		return 0;
5949 
5950 	/* only attempt func info relocation if main program's func_info
5951 	 * relocation was successful
5952 	 */
5953 	if (main_prog != prog && !main_prog->func_info)
5954 		goto line_info;
5955 
5956 	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->func_info,
5957 				       &main_prog->func_info,
5958 				       &main_prog->func_info_cnt,
5959 				       &main_prog->func_info_rec_size);
5960 	if (err) {
5961 		if (err != -ENOENT) {
5962 			pr_warn("prog '%s': error relocating .BTF.ext function info: %d\n",
5963 				prog->name, err);
5964 			return err;
5965 		}
5966 		if (main_prog->func_info) {
5967 			/*
5968 			 * Some info has already been found but has problem
5969 			 * in the last btf_ext reloc. Must have to error out.
5970 			 */
5971 			pr_warn("prog '%s': missing .BTF.ext function info.\n", prog->name);
5972 			return err;
5973 		}
5974 		/* Have problem loading the very first info. Ignore the rest. */
5975 		pr_warn("prog '%s': missing .BTF.ext function info for the main program, skipping all of .BTF.ext func info.\n",
5976 			prog->name);
5977 	}
5978 
5979 line_info:
5980 	/* don't relocate line info if main program's relocation failed */
5981 	if (main_prog != prog && !main_prog->line_info)
5982 		return 0;
5983 
5984 	err = adjust_prog_btf_ext_info(obj, prog, &obj->btf_ext->line_info,
5985 				       &main_prog->line_info,
5986 				       &main_prog->line_info_cnt,
5987 				       &main_prog->line_info_rec_size);
5988 	if (err) {
5989 		if (err != -ENOENT) {
5990 			pr_warn("prog '%s': error relocating .BTF.ext line info: %d\n",
5991 				prog->name, err);
5992 			return err;
5993 		}
5994 		if (main_prog->line_info) {
5995 			/*
5996 			 * Some info has already been found but has problem
5997 			 * in the last btf_ext reloc. Must have to error out.
5998 			 */
5999 			pr_warn("prog '%s': missing .BTF.ext line info.\n", prog->name);
6000 			return err;
6001 		}
6002 		/* Have problem loading the very first info. Ignore the rest. */
6003 		pr_warn("prog '%s': missing .BTF.ext line info for the main program, skipping all of .BTF.ext line info.\n",
6004 			prog->name);
6005 	}
6006 	return 0;
6007 }
6008 
6009 static int cmp_relo_by_insn_idx(const void *key, const void *elem)
6010 {
6011 	size_t insn_idx = *(const size_t *)key;
6012 	const struct reloc_desc *relo = elem;
6013 
6014 	if (insn_idx == relo->insn_idx)
6015 		return 0;
6016 	return insn_idx < relo->insn_idx ? -1 : 1;
6017 }
6018 
6019 static struct reloc_desc *find_prog_insn_relo(const struct bpf_program *prog, size_t insn_idx)
6020 {
6021 	if (!prog->nr_reloc)
6022 		return NULL;
6023 	return bsearch(&insn_idx, prog->reloc_desc, prog->nr_reloc,
6024 		       sizeof(*prog->reloc_desc), cmp_relo_by_insn_idx);
6025 }
6026 
6027 static int append_subprog_relos(struct bpf_program *main_prog, struct bpf_program *subprog)
6028 {
6029 	int new_cnt = main_prog->nr_reloc + subprog->nr_reloc;
6030 	struct reloc_desc *relos;
6031 	int i;
6032 
6033 	if (main_prog == subprog)
6034 		return 0;
6035 	relos = libbpf_reallocarray(main_prog->reloc_desc, new_cnt, sizeof(*relos));
6036 	if (!relos)
6037 		return -ENOMEM;
6038 	if (subprog->nr_reloc)
6039 		memcpy(relos + main_prog->nr_reloc, subprog->reloc_desc,
6040 		       sizeof(*relos) * subprog->nr_reloc);
6041 
6042 	for (i = main_prog->nr_reloc; i < new_cnt; i++)
6043 		relos[i].insn_idx += subprog->sub_insn_off;
6044 	/* After insn_idx adjustment the 'relos' array is still sorted
6045 	 * by insn_idx and doesn't break bsearch.
6046 	 */
6047 	main_prog->reloc_desc = relos;
6048 	main_prog->nr_reloc = new_cnt;
6049 	return 0;
6050 }
6051 
6052 static int
6053 bpf_object__reloc_code(struct bpf_object *obj, struct bpf_program *main_prog,
6054 		       struct bpf_program *prog)
6055 {
6056 	size_t sub_insn_idx, insn_idx, new_cnt;
6057 	struct bpf_program *subprog;
6058 	struct bpf_insn *insns, *insn;
6059 	struct reloc_desc *relo;
6060 	int err;
6061 
6062 	err = reloc_prog_func_and_line_info(obj, main_prog, prog);
6063 	if (err)
6064 		return err;
6065 
6066 	for (insn_idx = 0; insn_idx < prog->sec_insn_cnt; insn_idx++) {
6067 		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6068 		if (!insn_is_subprog_call(insn) && !insn_is_pseudo_func(insn))
6069 			continue;
6070 
6071 		relo = find_prog_insn_relo(prog, insn_idx);
6072 		if (relo && relo->type == RELO_EXTERN_FUNC)
6073 			/* kfunc relocations will be handled later
6074 			 * in bpf_object__relocate_data()
6075 			 */
6076 			continue;
6077 		if (relo && relo->type != RELO_CALL && relo->type != RELO_SUBPROG_ADDR) {
6078 			pr_warn("prog '%s': unexpected relo for insn #%zu, type %d\n",
6079 				prog->name, insn_idx, relo->type);
6080 			return -LIBBPF_ERRNO__RELOC;
6081 		}
6082 		if (relo) {
6083 			/* sub-program instruction index is a combination of
6084 			 * an offset of a symbol pointed to by relocation and
6085 			 * call instruction's imm field; for global functions,
6086 			 * call always has imm = -1, but for static functions
6087 			 * relocation is against STT_SECTION and insn->imm
6088 			 * points to a start of a static function
6089 			 *
6090 			 * for subprog addr relocation, the relo->sym_off + insn->imm is
6091 			 * the byte offset in the corresponding section.
6092 			 */
6093 			if (relo->type == RELO_CALL)
6094 				sub_insn_idx = relo->sym_off / BPF_INSN_SZ + insn->imm + 1;
6095 			else
6096 				sub_insn_idx = (relo->sym_off + insn->imm) / BPF_INSN_SZ;
6097 		} else if (insn_is_pseudo_func(insn)) {
6098 			/*
6099 			 * RELO_SUBPROG_ADDR relo is always emitted even if both
6100 			 * functions are in the same section, so it shouldn't reach here.
6101 			 */
6102 			pr_warn("prog '%s': missing subprog addr relo for insn #%zu\n",
6103 				prog->name, insn_idx);
6104 			return -LIBBPF_ERRNO__RELOC;
6105 		} else {
6106 			/* if subprogram call is to a static function within
6107 			 * the same ELF section, there won't be any relocation
6108 			 * emitted, but it also means there is no additional
6109 			 * offset necessary, insns->imm is relative to
6110 			 * instruction's original position within the section
6111 			 */
6112 			sub_insn_idx = prog->sec_insn_off + insn_idx + insn->imm + 1;
6113 		}
6114 
6115 		/* we enforce that sub-programs should be in .text section */
6116 		subprog = find_prog_by_sec_insn(obj, obj->efile.text_shndx, sub_insn_idx);
6117 		if (!subprog) {
6118 			pr_warn("prog '%s': no .text section found yet sub-program call exists\n",
6119 				prog->name);
6120 			return -LIBBPF_ERRNO__RELOC;
6121 		}
6122 
6123 		/* if it's the first call instruction calling into this
6124 		 * subprogram (meaning this subprog hasn't been processed
6125 		 * yet) within the context of current main program:
6126 		 *   - append it at the end of main program's instructions blog;
6127 		 *   - process is recursively, while current program is put on hold;
6128 		 *   - if that subprogram calls some other not yet processes
6129 		 *   subprogram, same thing will happen recursively until
6130 		 *   there are no more unprocesses subprograms left to append
6131 		 *   and relocate.
6132 		 */
6133 		if (subprog->sub_insn_off == 0) {
6134 			subprog->sub_insn_off = main_prog->insns_cnt;
6135 
6136 			new_cnt = main_prog->insns_cnt + subprog->insns_cnt;
6137 			insns = libbpf_reallocarray(main_prog->insns, new_cnt, sizeof(*insns));
6138 			if (!insns) {
6139 				pr_warn("prog '%s': failed to realloc prog code\n", main_prog->name);
6140 				return -ENOMEM;
6141 			}
6142 			main_prog->insns = insns;
6143 			main_prog->insns_cnt = new_cnt;
6144 
6145 			memcpy(main_prog->insns + subprog->sub_insn_off, subprog->insns,
6146 			       subprog->insns_cnt * sizeof(*insns));
6147 
6148 			pr_debug("prog '%s': added %zu insns from sub-prog '%s'\n",
6149 				 main_prog->name, subprog->insns_cnt, subprog->name);
6150 
6151 			/* The subprog insns are now appended. Append its relos too. */
6152 			err = append_subprog_relos(main_prog, subprog);
6153 			if (err)
6154 				return err;
6155 			err = bpf_object__reloc_code(obj, main_prog, subprog);
6156 			if (err)
6157 				return err;
6158 		}
6159 
6160 		/* main_prog->insns memory could have been re-allocated, so
6161 		 * calculate pointer again
6162 		 */
6163 		insn = &main_prog->insns[prog->sub_insn_off + insn_idx];
6164 		/* calculate correct instruction position within current main
6165 		 * prog; each main prog can have a different set of
6166 		 * subprograms appended (potentially in different order as
6167 		 * well), so position of any subprog can be different for
6168 		 * different main programs */
6169 		insn->imm = subprog->sub_insn_off - (prog->sub_insn_off + insn_idx) - 1;
6170 
6171 		pr_debug("prog '%s': insn #%zu relocated, imm %d points to subprog '%s' (now at %zu offset)\n",
6172 			 prog->name, insn_idx, insn->imm, subprog->name, subprog->sub_insn_off);
6173 	}
6174 
6175 	return 0;
6176 }
6177 
6178 /*
6179  * Relocate sub-program calls.
6180  *
6181  * Algorithm operates as follows. Each entry-point BPF program (referred to as
6182  * main prog) is processed separately. For each subprog (non-entry functions,
6183  * that can be called from either entry progs or other subprogs) gets their
6184  * sub_insn_off reset to zero. This serves as indicator that this subprogram
6185  * hasn't been yet appended and relocated within current main prog. Once its
6186  * relocated, sub_insn_off will point at the position within current main prog
6187  * where given subprog was appended. This will further be used to relocate all
6188  * the call instructions jumping into this subprog.
6189  *
6190  * We start with main program and process all call instructions. If the call
6191  * is into a subprog that hasn't been processed (i.e., subprog->sub_insn_off
6192  * is zero), subprog instructions are appended at the end of main program's
6193  * instruction array. Then main program is "put on hold" while we recursively
6194  * process newly appended subprogram. If that subprogram calls into another
6195  * subprogram that hasn't been appended, new subprogram is appended again to
6196  * the *main* prog's instructions (subprog's instructions are always left
6197  * untouched, as they need to be in unmodified state for subsequent main progs
6198  * and subprog instructions are always sent only as part of a main prog) and
6199  * the process continues recursively. Once all the subprogs called from a main
6200  * prog or any of its subprogs are appended (and relocated), all their
6201  * positions within finalized instructions array are known, so it's easy to
6202  * rewrite call instructions with correct relative offsets, corresponding to
6203  * desired target subprog.
6204  *
6205  * Its important to realize that some subprogs might not be called from some
6206  * main prog and any of its called/used subprogs. Those will keep their
6207  * subprog->sub_insn_off as zero at all times and won't be appended to current
6208  * main prog and won't be relocated within the context of current main prog.
6209  * They might still be used from other main progs later.
6210  *
6211  * Visually this process can be shown as below. Suppose we have two main
6212  * programs mainA and mainB and BPF object contains three subprogs: subA,
6213  * subB, and subC. mainA calls only subA, mainB calls only subC, but subA and
6214  * subC both call subB:
6215  *
6216  *        +--------+ +-------+
6217  *        |        v v       |
6218  *     +--+---+ +--+-+-+ +---+--+
6219  *     | subA | | subB | | subC |
6220  *     +--+---+ +------+ +---+--+
6221  *        ^                  ^
6222  *        |                  |
6223  *    +---+-------+   +------+----+
6224  *    |   mainA   |   |   mainB   |
6225  *    +-----------+   +-----------+
6226  *
6227  * We'll start relocating mainA, will find subA, append it and start
6228  * processing sub A recursively:
6229  *
6230  *    +-----------+------+
6231  *    |   mainA   | subA |
6232  *    +-----------+------+
6233  *
6234  * At this point we notice that subB is used from subA, so we append it and
6235  * relocate (there are no further subcalls from subB):
6236  *
6237  *    +-----------+------+------+
6238  *    |   mainA   | subA | subB |
6239  *    +-----------+------+------+
6240  *
6241  * At this point, we relocate subA calls, then go one level up and finish with
6242  * relocatin mainA calls. mainA is done.
6243  *
6244  * For mainB process is similar but results in different order. We start with
6245  * mainB and skip subA and subB, as mainB never calls them (at least
6246  * directly), but we see subC is needed, so we append and start processing it:
6247  *
6248  *    +-----------+------+
6249  *    |   mainB   | subC |
6250  *    +-----------+------+
6251  * Now we see subC needs subB, so we go back to it, append and relocate it:
6252  *
6253  *    +-----------+------+------+
6254  *    |   mainB   | subC | subB |
6255  *    +-----------+------+------+
6256  *
6257  * At this point we unwind recursion, relocate calls in subC, then in mainB.
6258  */
6259 static int
6260 bpf_object__relocate_calls(struct bpf_object *obj, struct bpf_program *prog)
6261 {
6262 	struct bpf_program *subprog;
6263 	int i, err;
6264 
6265 	/* mark all subprogs as not relocated (yet) within the context of
6266 	 * current main program
6267 	 */
6268 	for (i = 0; i < obj->nr_programs; i++) {
6269 		subprog = &obj->programs[i];
6270 		if (!prog_is_subprog(obj, subprog))
6271 			continue;
6272 
6273 		subprog->sub_insn_off = 0;
6274 	}
6275 
6276 	err = bpf_object__reloc_code(obj, prog, prog);
6277 	if (err)
6278 		return err;
6279 
6280 	return 0;
6281 }
6282 
6283 static void
6284 bpf_object__free_relocs(struct bpf_object *obj)
6285 {
6286 	struct bpf_program *prog;
6287 	int i;
6288 
6289 	/* free up relocation descriptors */
6290 	for (i = 0; i < obj->nr_programs; i++) {
6291 		prog = &obj->programs[i];
6292 		zfree(&prog->reloc_desc);
6293 		prog->nr_reloc = 0;
6294 	}
6295 }
6296 
6297 static int cmp_relocs(const void *_a, const void *_b)
6298 {
6299 	const struct reloc_desc *a = _a;
6300 	const struct reloc_desc *b = _b;
6301 
6302 	if (a->insn_idx != b->insn_idx)
6303 		return a->insn_idx < b->insn_idx ? -1 : 1;
6304 
6305 	/* no two relocations should have the same insn_idx, but ... */
6306 	if (a->type != b->type)
6307 		return a->type < b->type ? -1 : 1;
6308 
6309 	return 0;
6310 }
6311 
6312 static void bpf_object__sort_relos(struct bpf_object *obj)
6313 {
6314 	int i;
6315 
6316 	for (i = 0; i < obj->nr_programs; i++) {
6317 		struct bpf_program *p = &obj->programs[i];
6318 
6319 		if (!p->nr_reloc)
6320 			continue;
6321 
6322 		qsort(p->reloc_desc, p->nr_reloc, sizeof(*p->reloc_desc), cmp_relocs);
6323 	}
6324 }
6325 
6326 static int
6327 bpf_object__relocate(struct bpf_object *obj, const char *targ_btf_path)
6328 {
6329 	struct bpf_program *prog;
6330 	size_t i, j;
6331 	int err;
6332 
6333 	if (obj->btf_ext) {
6334 		err = bpf_object__relocate_core(obj, targ_btf_path);
6335 		if (err) {
6336 			pr_warn("failed to perform CO-RE relocations: %d\n",
6337 				err);
6338 			return err;
6339 		}
6340 		bpf_object__sort_relos(obj);
6341 	}
6342 
6343 	/* Before relocating calls pre-process relocations and mark
6344 	 * few ld_imm64 instructions that points to subprogs.
6345 	 * Otherwise bpf_object__reloc_code() later would have to consider
6346 	 * all ld_imm64 insns as relocation candidates. That would
6347 	 * reduce relocation speed, since amount of find_prog_insn_relo()
6348 	 * would increase and most of them will fail to find a relo.
6349 	 */
6350 	for (i = 0; i < obj->nr_programs; i++) {
6351 		prog = &obj->programs[i];
6352 		for (j = 0; j < prog->nr_reloc; j++) {
6353 			struct reloc_desc *relo = &prog->reloc_desc[j];
6354 			struct bpf_insn *insn = &prog->insns[relo->insn_idx];
6355 
6356 			/* mark the insn, so it's recognized by insn_is_pseudo_func() */
6357 			if (relo->type == RELO_SUBPROG_ADDR)
6358 				insn[0].src_reg = BPF_PSEUDO_FUNC;
6359 		}
6360 	}
6361 
6362 	/* relocate subprogram calls and append used subprograms to main
6363 	 * programs; each copy of subprogram code needs to be relocated
6364 	 * differently for each main program, because its code location might
6365 	 * have changed.
6366 	 * Append subprog relos to main programs to allow data relos to be
6367 	 * processed after text is completely relocated.
6368 	 */
6369 	for (i = 0; i < obj->nr_programs; i++) {
6370 		prog = &obj->programs[i];
6371 		/* sub-program's sub-calls are relocated within the context of
6372 		 * its main program only
6373 		 */
6374 		if (prog_is_subprog(obj, prog))
6375 			continue;
6376 		if (!prog->autoload)
6377 			continue;
6378 
6379 		err = bpf_object__relocate_calls(obj, prog);
6380 		if (err) {
6381 			pr_warn("prog '%s': failed to relocate calls: %d\n",
6382 				prog->name, err);
6383 			return err;
6384 		}
6385 	}
6386 	/* Process data relos for main programs */
6387 	for (i = 0; i < obj->nr_programs; i++) {
6388 		prog = &obj->programs[i];
6389 		if (prog_is_subprog(obj, prog))
6390 			continue;
6391 		if (!prog->autoload)
6392 			continue;
6393 		err = bpf_object__relocate_data(obj, prog);
6394 		if (err) {
6395 			pr_warn("prog '%s': failed to relocate data references: %d\n",
6396 				prog->name, err);
6397 			return err;
6398 		}
6399 	}
6400 
6401 	return 0;
6402 }
6403 
6404 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
6405 					    Elf64_Shdr *shdr, Elf_Data *data);
6406 
6407 static int bpf_object__collect_map_relos(struct bpf_object *obj,
6408 					 Elf64_Shdr *shdr, Elf_Data *data)
6409 {
6410 	const int bpf_ptr_sz = 8, host_ptr_sz = sizeof(void *);
6411 	int i, j, nrels, new_sz;
6412 	const struct btf_var_secinfo *vi = NULL;
6413 	const struct btf_type *sec, *var, *def;
6414 	struct bpf_map *map = NULL, *targ_map = NULL;
6415 	struct bpf_program *targ_prog = NULL;
6416 	bool is_prog_array, is_map_in_map;
6417 	const struct btf_member *member;
6418 	const char *name, *mname, *type;
6419 	unsigned int moff;
6420 	Elf64_Sym *sym;
6421 	Elf64_Rel *rel;
6422 	void *tmp;
6423 
6424 	if (!obj->efile.btf_maps_sec_btf_id || !obj->btf)
6425 		return -EINVAL;
6426 	sec = btf__type_by_id(obj->btf, obj->efile.btf_maps_sec_btf_id);
6427 	if (!sec)
6428 		return -EINVAL;
6429 
6430 	nrels = shdr->sh_size / shdr->sh_entsize;
6431 	for (i = 0; i < nrels; i++) {
6432 		rel = elf_rel_by_idx(data, i);
6433 		if (!rel) {
6434 			pr_warn(".maps relo #%d: failed to get ELF relo\n", i);
6435 			return -LIBBPF_ERRNO__FORMAT;
6436 		}
6437 
6438 		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
6439 		if (!sym) {
6440 			pr_warn(".maps relo #%d: symbol %zx not found\n",
6441 				i, (size_t)ELF64_R_SYM(rel->r_info));
6442 			return -LIBBPF_ERRNO__FORMAT;
6443 		}
6444 		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
6445 
6446 		pr_debug(".maps relo #%d: for %zd value %zd rel->r_offset %zu name %d ('%s')\n",
6447 			 i, (ssize_t)(rel->r_info >> 32), (size_t)sym->st_value,
6448 			 (size_t)rel->r_offset, sym->st_name, name);
6449 
6450 		for (j = 0; j < obj->nr_maps; j++) {
6451 			map = &obj->maps[j];
6452 			if (map->sec_idx != obj->efile.btf_maps_shndx)
6453 				continue;
6454 
6455 			vi = btf_var_secinfos(sec) + map->btf_var_idx;
6456 			if (vi->offset <= rel->r_offset &&
6457 			    rel->r_offset + bpf_ptr_sz <= vi->offset + vi->size)
6458 				break;
6459 		}
6460 		if (j == obj->nr_maps) {
6461 			pr_warn(".maps relo #%d: cannot find map '%s' at rel->r_offset %zu\n",
6462 				i, name, (size_t)rel->r_offset);
6463 			return -EINVAL;
6464 		}
6465 
6466 		is_map_in_map = bpf_map_type__is_map_in_map(map->def.type);
6467 		is_prog_array = map->def.type == BPF_MAP_TYPE_PROG_ARRAY;
6468 		type = is_map_in_map ? "map" : "prog";
6469 		if (is_map_in_map) {
6470 			if (sym->st_shndx != obj->efile.btf_maps_shndx) {
6471 				pr_warn(".maps relo #%d: '%s' isn't a BTF-defined map\n",
6472 					i, name);
6473 				return -LIBBPF_ERRNO__RELOC;
6474 			}
6475 			if (map->def.type == BPF_MAP_TYPE_HASH_OF_MAPS &&
6476 			    map->def.key_size != sizeof(int)) {
6477 				pr_warn(".maps relo #%d: hash-of-maps '%s' should have key size %zu.\n",
6478 					i, map->name, sizeof(int));
6479 				return -EINVAL;
6480 			}
6481 			targ_map = bpf_object__find_map_by_name(obj, name);
6482 			if (!targ_map) {
6483 				pr_warn(".maps relo #%d: '%s' isn't a valid map reference\n",
6484 					i, name);
6485 				return -ESRCH;
6486 			}
6487 		} else if (is_prog_array) {
6488 			targ_prog = bpf_object__find_program_by_name(obj, name);
6489 			if (!targ_prog) {
6490 				pr_warn(".maps relo #%d: '%s' isn't a valid program reference\n",
6491 					i, name);
6492 				return -ESRCH;
6493 			}
6494 			if (targ_prog->sec_idx != sym->st_shndx ||
6495 			    targ_prog->sec_insn_off * 8 != sym->st_value ||
6496 			    prog_is_subprog(obj, targ_prog)) {
6497 				pr_warn(".maps relo #%d: '%s' isn't an entry-point program\n",
6498 					i, name);
6499 				return -LIBBPF_ERRNO__RELOC;
6500 			}
6501 		} else {
6502 			return -EINVAL;
6503 		}
6504 
6505 		var = btf__type_by_id(obj->btf, vi->type);
6506 		def = skip_mods_and_typedefs(obj->btf, var->type, NULL);
6507 		if (btf_vlen(def) == 0)
6508 			return -EINVAL;
6509 		member = btf_members(def) + btf_vlen(def) - 1;
6510 		mname = btf__name_by_offset(obj->btf, member->name_off);
6511 		if (strcmp(mname, "values"))
6512 			return -EINVAL;
6513 
6514 		moff = btf_member_bit_offset(def, btf_vlen(def) - 1) / 8;
6515 		if (rel->r_offset - vi->offset < moff)
6516 			return -EINVAL;
6517 
6518 		moff = rel->r_offset - vi->offset - moff;
6519 		/* here we use BPF pointer size, which is always 64 bit, as we
6520 		 * are parsing ELF that was built for BPF target
6521 		 */
6522 		if (moff % bpf_ptr_sz)
6523 			return -EINVAL;
6524 		moff /= bpf_ptr_sz;
6525 		if (moff >= map->init_slots_sz) {
6526 			new_sz = moff + 1;
6527 			tmp = libbpf_reallocarray(map->init_slots, new_sz, host_ptr_sz);
6528 			if (!tmp)
6529 				return -ENOMEM;
6530 			map->init_slots = tmp;
6531 			memset(map->init_slots + map->init_slots_sz, 0,
6532 			       (new_sz - map->init_slots_sz) * host_ptr_sz);
6533 			map->init_slots_sz = new_sz;
6534 		}
6535 		map->init_slots[moff] = is_map_in_map ? (void *)targ_map : (void *)targ_prog;
6536 
6537 		pr_debug(".maps relo #%d: map '%s' slot [%d] points to %s '%s'\n",
6538 			 i, map->name, moff, type, name);
6539 	}
6540 
6541 	return 0;
6542 }
6543 
6544 static int bpf_object__collect_relos(struct bpf_object *obj)
6545 {
6546 	int i, err;
6547 
6548 	for (i = 0; i < obj->efile.sec_cnt; i++) {
6549 		struct elf_sec_desc *sec_desc = &obj->efile.secs[i];
6550 		Elf64_Shdr *shdr;
6551 		Elf_Data *data;
6552 		int idx;
6553 
6554 		if (sec_desc->sec_type != SEC_RELO)
6555 			continue;
6556 
6557 		shdr = sec_desc->shdr;
6558 		data = sec_desc->data;
6559 		idx = shdr->sh_info;
6560 
6561 		if (shdr->sh_type != SHT_REL) {
6562 			pr_warn("internal error at %d\n", __LINE__);
6563 			return -LIBBPF_ERRNO__INTERNAL;
6564 		}
6565 
6566 		if (idx == obj->efile.st_ops_shndx)
6567 			err = bpf_object__collect_st_ops_relos(obj, shdr, data);
6568 		else if (idx == obj->efile.btf_maps_shndx)
6569 			err = bpf_object__collect_map_relos(obj, shdr, data);
6570 		else
6571 			err = bpf_object__collect_prog_relos(obj, shdr, data);
6572 		if (err)
6573 			return err;
6574 	}
6575 
6576 	bpf_object__sort_relos(obj);
6577 	return 0;
6578 }
6579 
6580 static bool insn_is_helper_call(struct bpf_insn *insn, enum bpf_func_id *func_id)
6581 {
6582 	if (BPF_CLASS(insn->code) == BPF_JMP &&
6583 	    BPF_OP(insn->code) == BPF_CALL &&
6584 	    BPF_SRC(insn->code) == BPF_K &&
6585 	    insn->src_reg == 0 &&
6586 	    insn->dst_reg == 0) {
6587 		    *func_id = insn->imm;
6588 		    return true;
6589 	}
6590 	return false;
6591 }
6592 
6593 static int bpf_object__sanitize_prog(struct bpf_object *obj, struct bpf_program *prog)
6594 {
6595 	struct bpf_insn *insn = prog->insns;
6596 	enum bpf_func_id func_id;
6597 	int i;
6598 
6599 	if (obj->gen_loader)
6600 		return 0;
6601 
6602 	for (i = 0; i < prog->insns_cnt; i++, insn++) {
6603 		if (!insn_is_helper_call(insn, &func_id))
6604 			continue;
6605 
6606 		/* on kernels that don't yet support
6607 		 * bpf_probe_read_{kernel,user}[_str] helpers, fall back
6608 		 * to bpf_probe_read() which works well for old kernels
6609 		 */
6610 		switch (func_id) {
6611 		case BPF_FUNC_probe_read_kernel:
6612 		case BPF_FUNC_probe_read_user:
6613 			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
6614 				insn->imm = BPF_FUNC_probe_read;
6615 			break;
6616 		case BPF_FUNC_probe_read_kernel_str:
6617 		case BPF_FUNC_probe_read_user_str:
6618 			if (!kernel_supports(obj, FEAT_PROBE_READ_KERN))
6619 				insn->imm = BPF_FUNC_probe_read_str;
6620 			break;
6621 		default:
6622 			break;
6623 		}
6624 	}
6625 	return 0;
6626 }
6627 
6628 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
6629 				     int *btf_obj_fd, int *btf_type_id);
6630 
6631 /* this is called as prog->sec_def->prog_prepare_load_fn for libbpf-supported sec_defs */
6632 static int libbpf_prepare_prog_load(struct bpf_program *prog,
6633 				    struct bpf_prog_load_opts *opts, long cookie)
6634 {
6635 	enum sec_def_flags def = cookie;
6636 
6637 	/* old kernels might not support specifying expected_attach_type */
6638 	if ((def & SEC_EXP_ATTACH_OPT) && !kernel_supports(prog->obj, FEAT_EXP_ATTACH_TYPE))
6639 		opts->expected_attach_type = 0;
6640 
6641 	if (def & SEC_SLEEPABLE)
6642 		opts->prog_flags |= BPF_F_SLEEPABLE;
6643 
6644 	if (prog->type == BPF_PROG_TYPE_XDP && (def & SEC_XDP_FRAGS))
6645 		opts->prog_flags |= BPF_F_XDP_HAS_FRAGS;
6646 
6647 	if ((def & SEC_ATTACH_BTF) && !prog->attach_btf_id) {
6648 		int btf_obj_fd = 0, btf_type_id = 0, err;
6649 		const char *attach_name;
6650 
6651 		attach_name = strchr(prog->sec_name, '/');
6652 		if (!attach_name) {
6653 			/* if BPF program is annotated with just SEC("fentry")
6654 			 * (or similar) without declaratively specifying
6655 			 * target, then it is expected that target will be
6656 			 * specified with bpf_program__set_attach_target() at
6657 			 * runtime before BPF object load step. If not, then
6658 			 * there is nothing to load into the kernel as BPF
6659 			 * verifier won't be able to validate BPF program
6660 			 * correctness anyways.
6661 			 */
6662 			pr_warn("prog '%s': no BTF-based attach target is specified, use bpf_program__set_attach_target()\n",
6663 				prog->name);
6664 			return -EINVAL;
6665 		}
6666 		attach_name++; /* skip over / */
6667 
6668 		err = libbpf_find_attach_btf_id(prog, attach_name, &btf_obj_fd, &btf_type_id);
6669 		if (err)
6670 			return err;
6671 
6672 		/* cache resolved BTF FD and BTF type ID in the prog */
6673 		prog->attach_btf_obj_fd = btf_obj_fd;
6674 		prog->attach_btf_id = btf_type_id;
6675 
6676 		/* but by now libbpf common logic is not utilizing
6677 		 * prog->atach_btf_obj_fd/prog->attach_btf_id anymore because
6678 		 * this callback is called after opts were populated by
6679 		 * libbpf, so this callback has to update opts explicitly here
6680 		 */
6681 		opts->attach_btf_obj_fd = btf_obj_fd;
6682 		opts->attach_btf_id = btf_type_id;
6683 	}
6684 	return 0;
6685 }
6686 
6687 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz);
6688 
6689 static int bpf_object_load_prog(struct bpf_object *obj, struct bpf_program *prog,
6690 				struct bpf_insn *insns, int insns_cnt,
6691 				const char *license, __u32 kern_version, int *prog_fd)
6692 {
6693 	LIBBPF_OPTS(bpf_prog_load_opts, load_attr);
6694 	const char *prog_name = NULL;
6695 	char *cp, errmsg[STRERR_BUFSIZE];
6696 	size_t log_buf_size = 0;
6697 	char *log_buf = NULL, *tmp;
6698 	int btf_fd, ret, err;
6699 	bool own_log_buf = true;
6700 	__u32 log_level = prog->log_level;
6701 
6702 	if (prog->type == BPF_PROG_TYPE_UNSPEC) {
6703 		/*
6704 		 * The program type must be set.  Most likely we couldn't find a proper
6705 		 * section definition at load time, and thus we didn't infer the type.
6706 		 */
6707 		pr_warn("prog '%s': missing BPF prog type, check ELF section name '%s'\n",
6708 			prog->name, prog->sec_name);
6709 		return -EINVAL;
6710 	}
6711 
6712 	if (!insns || !insns_cnt)
6713 		return -EINVAL;
6714 
6715 	load_attr.expected_attach_type = prog->expected_attach_type;
6716 	if (kernel_supports(obj, FEAT_PROG_NAME))
6717 		prog_name = prog->name;
6718 	load_attr.attach_prog_fd = prog->attach_prog_fd;
6719 	load_attr.attach_btf_obj_fd = prog->attach_btf_obj_fd;
6720 	load_attr.attach_btf_id = prog->attach_btf_id;
6721 	load_attr.kern_version = kern_version;
6722 	load_attr.prog_ifindex = prog->prog_ifindex;
6723 
6724 	/* specify func_info/line_info only if kernel supports them */
6725 	btf_fd = bpf_object__btf_fd(obj);
6726 	if (btf_fd >= 0 && kernel_supports(obj, FEAT_BTF_FUNC)) {
6727 		load_attr.prog_btf_fd = btf_fd;
6728 		load_attr.func_info = prog->func_info;
6729 		load_attr.func_info_rec_size = prog->func_info_rec_size;
6730 		load_attr.func_info_cnt = prog->func_info_cnt;
6731 		load_attr.line_info = prog->line_info;
6732 		load_attr.line_info_rec_size = prog->line_info_rec_size;
6733 		load_attr.line_info_cnt = prog->line_info_cnt;
6734 	}
6735 	load_attr.log_level = log_level;
6736 	load_attr.prog_flags = prog->prog_flags;
6737 	load_attr.fd_array = obj->fd_array;
6738 
6739 	/* adjust load_attr if sec_def provides custom preload callback */
6740 	if (prog->sec_def && prog->sec_def->prog_prepare_load_fn) {
6741 		err = prog->sec_def->prog_prepare_load_fn(prog, &load_attr, prog->sec_def->cookie);
6742 		if (err < 0) {
6743 			pr_warn("prog '%s': failed to prepare load attributes: %d\n",
6744 				prog->name, err);
6745 			return err;
6746 		}
6747 		insns = prog->insns;
6748 		insns_cnt = prog->insns_cnt;
6749 	}
6750 
6751 	if (obj->gen_loader) {
6752 		bpf_gen__prog_load(obj->gen_loader, prog->type, prog->name,
6753 				   license, insns, insns_cnt, &load_attr,
6754 				   prog - obj->programs);
6755 		*prog_fd = -1;
6756 		return 0;
6757 	}
6758 
6759 retry_load:
6760 	/* if log_level is zero, we don't request logs initially even if
6761 	 * custom log_buf is specified; if the program load fails, then we'll
6762 	 * bump log_level to 1 and use either custom log_buf or we'll allocate
6763 	 * our own and retry the load to get details on what failed
6764 	 */
6765 	if (log_level) {
6766 		if (prog->log_buf) {
6767 			log_buf = prog->log_buf;
6768 			log_buf_size = prog->log_size;
6769 			own_log_buf = false;
6770 		} else if (obj->log_buf) {
6771 			log_buf = obj->log_buf;
6772 			log_buf_size = obj->log_size;
6773 			own_log_buf = false;
6774 		} else {
6775 			log_buf_size = max((size_t)BPF_LOG_BUF_SIZE, log_buf_size * 2);
6776 			tmp = realloc(log_buf, log_buf_size);
6777 			if (!tmp) {
6778 				ret = -ENOMEM;
6779 				goto out;
6780 			}
6781 			log_buf = tmp;
6782 			log_buf[0] = '\0';
6783 			own_log_buf = true;
6784 		}
6785 	}
6786 
6787 	load_attr.log_buf = log_buf;
6788 	load_attr.log_size = log_buf_size;
6789 	load_attr.log_level = log_level;
6790 
6791 	ret = bpf_prog_load(prog->type, prog_name, license, insns, insns_cnt, &load_attr);
6792 	if (ret >= 0) {
6793 		if (log_level && own_log_buf) {
6794 			pr_debug("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
6795 				 prog->name, log_buf);
6796 		}
6797 
6798 		if (obj->has_rodata && kernel_supports(obj, FEAT_PROG_BIND_MAP)) {
6799 			struct bpf_map *map;
6800 			int i;
6801 
6802 			for (i = 0; i < obj->nr_maps; i++) {
6803 				map = &prog->obj->maps[i];
6804 				if (map->libbpf_type != LIBBPF_MAP_RODATA)
6805 					continue;
6806 
6807 				if (bpf_prog_bind_map(ret, bpf_map__fd(map), NULL)) {
6808 					cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
6809 					pr_warn("prog '%s': failed to bind map '%s': %s\n",
6810 						prog->name, map->real_name, cp);
6811 					/* Don't fail hard if can't bind rodata. */
6812 				}
6813 			}
6814 		}
6815 
6816 		*prog_fd = ret;
6817 		ret = 0;
6818 		goto out;
6819 	}
6820 
6821 	if (log_level == 0) {
6822 		log_level = 1;
6823 		goto retry_load;
6824 	}
6825 	/* On ENOSPC, increase log buffer size and retry, unless custom
6826 	 * log_buf is specified.
6827 	 * Be careful to not overflow u32, though. Kernel's log buf size limit
6828 	 * isn't part of UAPI so it can always be bumped to full 4GB. So don't
6829 	 * multiply by 2 unless we are sure we'll fit within 32 bits.
6830 	 * Currently, we'll get -EINVAL when we reach (UINT_MAX >> 2).
6831 	 */
6832 	if (own_log_buf && errno == ENOSPC && log_buf_size <= UINT_MAX / 2)
6833 		goto retry_load;
6834 
6835 	ret = -errno;
6836 
6837 	/* post-process verifier log to improve error descriptions */
6838 	fixup_verifier_log(prog, log_buf, log_buf_size);
6839 
6840 	cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
6841 	pr_warn("prog '%s': BPF program load failed: %s\n", prog->name, cp);
6842 	pr_perm_msg(ret);
6843 
6844 	if (own_log_buf && log_buf && log_buf[0] != '\0') {
6845 		pr_warn("prog '%s': -- BEGIN PROG LOAD LOG --\n%s-- END PROG LOAD LOG --\n",
6846 			prog->name, log_buf);
6847 	}
6848 
6849 out:
6850 	if (own_log_buf)
6851 		free(log_buf);
6852 	return ret;
6853 }
6854 
6855 static char *find_prev_line(char *buf, char *cur)
6856 {
6857 	char *p;
6858 
6859 	if (cur == buf) /* end of a log buf */
6860 		return NULL;
6861 
6862 	p = cur - 1;
6863 	while (p - 1 >= buf && *(p - 1) != '\n')
6864 		p--;
6865 
6866 	return p;
6867 }
6868 
6869 static void patch_log(char *buf, size_t buf_sz, size_t log_sz,
6870 		      char *orig, size_t orig_sz, const char *patch)
6871 {
6872 	/* size of the remaining log content to the right from the to-be-replaced part */
6873 	size_t rem_sz = (buf + log_sz) - (orig + orig_sz);
6874 	size_t patch_sz = strlen(patch);
6875 
6876 	if (patch_sz != orig_sz) {
6877 		/* If patch line(s) are longer than original piece of verifier log,
6878 		 * shift log contents by (patch_sz - orig_sz) bytes to the right
6879 		 * starting from after to-be-replaced part of the log.
6880 		 *
6881 		 * If patch line(s) are shorter than original piece of verifier log,
6882 		 * shift log contents by (orig_sz - patch_sz) bytes to the left
6883 		 * starting from after to-be-replaced part of the log
6884 		 *
6885 		 * We need to be careful about not overflowing available
6886 		 * buf_sz capacity. If that's the case, we'll truncate the end
6887 		 * of the original log, as necessary.
6888 		 */
6889 		if (patch_sz > orig_sz) {
6890 			if (orig + patch_sz >= buf + buf_sz) {
6891 				/* patch is big enough to cover remaining space completely */
6892 				patch_sz -= (orig + patch_sz) - (buf + buf_sz) + 1;
6893 				rem_sz = 0;
6894 			} else if (patch_sz - orig_sz > buf_sz - log_sz) {
6895 				/* patch causes part of remaining log to be truncated */
6896 				rem_sz -= (patch_sz - orig_sz) - (buf_sz - log_sz);
6897 			}
6898 		}
6899 		/* shift remaining log to the right by calculated amount */
6900 		memmove(orig + patch_sz, orig + orig_sz, rem_sz);
6901 	}
6902 
6903 	memcpy(orig, patch, patch_sz);
6904 }
6905 
6906 static void fixup_log_failed_core_relo(struct bpf_program *prog,
6907 				       char *buf, size_t buf_sz, size_t log_sz,
6908 				       char *line1, char *line2, char *line3)
6909 {
6910 	/* Expected log for failed and not properly guarded CO-RE relocation:
6911 	 * line1 -> 123: (85) call unknown#195896080
6912 	 * line2 -> invalid func unknown#195896080
6913 	 * line3 -> <anything else or end of buffer>
6914 	 *
6915 	 * "123" is the index of the instruction that was poisoned. We extract
6916 	 * instruction index to find corresponding CO-RE relocation and
6917 	 * replace this part of the log with more relevant information about
6918 	 * failed CO-RE relocation.
6919 	 */
6920 	const struct bpf_core_relo *relo;
6921 	struct bpf_core_spec spec;
6922 	char patch[512], spec_buf[256];
6923 	int insn_idx, err, spec_len;
6924 
6925 	if (sscanf(line1, "%d: (%*d) call unknown#195896080\n", &insn_idx) != 1)
6926 		return;
6927 
6928 	relo = find_relo_core(prog, insn_idx);
6929 	if (!relo)
6930 		return;
6931 
6932 	err = bpf_core_parse_spec(prog->name, prog->obj->btf, relo, &spec);
6933 	if (err)
6934 		return;
6935 
6936 	spec_len = bpf_core_format_spec(spec_buf, sizeof(spec_buf), &spec);
6937 	snprintf(patch, sizeof(patch),
6938 		 "%d: <invalid CO-RE relocation>\n"
6939 		 "failed to resolve CO-RE relocation %s%s\n",
6940 		 insn_idx, spec_buf, spec_len >= sizeof(spec_buf) ? "..." : "");
6941 
6942 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
6943 }
6944 
6945 static void fixup_log_missing_map_load(struct bpf_program *prog,
6946 				       char *buf, size_t buf_sz, size_t log_sz,
6947 				       char *line1, char *line2, char *line3)
6948 {
6949 	/* Expected log for failed and not properly guarded CO-RE relocation:
6950 	 * line1 -> 123: (85) call unknown#2001000345
6951 	 * line2 -> invalid func unknown#2001000345
6952 	 * line3 -> <anything else or end of buffer>
6953 	 *
6954 	 * "123" is the index of the instruction that was poisoned.
6955 	 * "345" in "2001000345" are map index in obj->maps to fetch map name.
6956 	 */
6957 	struct bpf_object *obj = prog->obj;
6958 	const struct bpf_map *map;
6959 	int insn_idx, map_idx;
6960 	char patch[128];
6961 
6962 	if (sscanf(line1, "%d: (%*d) call unknown#%d\n", &insn_idx, &map_idx) != 2)
6963 		return;
6964 
6965 	map_idx -= MAP_LDIMM64_POISON_BASE;
6966 	if (map_idx < 0 || map_idx >= obj->nr_maps)
6967 		return;
6968 	map = &obj->maps[map_idx];
6969 
6970 	snprintf(patch, sizeof(patch),
6971 		 "%d: <invalid BPF map reference>\n"
6972 		 "BPF map '%s' is referenced but wasn't created\n",
6973 		 insn_idx, map->name);
6974 
6975 	patch_log(buf, buf_sz, log_sz, line1, line3 - line1, patch);
6976 }
6977 
6978 static void fixup_verifier_log(struct bpf_program *prog, char *buf, size_t buf_sz)
6979 {
6980 	/* look for familiar error patterns in last N lines of the log */
6981 	const size_t max_last_line_cnt = 10;
6982 	char *prev_line, *cur_line, *next_line;
6983 	size_t log_sz;
6984 	int i;
6985 
6986 	if (!buf)
6987 		return;
6988 
6989 	log_sz = strlen(buf) + 1;
6990 	next_line = buf + log_sz - 1;
6991 
6992 	for (i = 0; i < max_last_line_cnt; i++, next_line = cur_line) {
6993 		cur_line = find_prev_line(buf, next_line);
6994 		if (!cur_line)
6995 			return;
6996 
6997 		/* failed CO-RE relocation case */
6998 		if (str_has_pfx(cur_line, "invalid func unknown#195896080\n")) {
6999 			prev_line = find_prev_line(buf, cur_line);
7000 			if (!prev_line)
7001 				continue;
7002 
7003 			fixup_log_failed_core_relo(prog, buf, buf_sz, log_sz,
7004 						   prev_line, cur_line, next_line);
7005 			return;
7006 		} else if (str_has_pfx(cur_line, "invalid func unknown#"MAP_LDIMM64_POISON_PFX)) {
7007 			prev_line = find_prev_line(buf, cur_line);
7008 			if (!prev_line)
7009 				continue;
7010 
7011 			fixup_log_missing_map_load(prog, buf, buf_sz, log_sz,
7012 						   prev_line, cur_line, next_line);
7013 			return;
7014 		}
7015 	}
7016 }
7017 
7018 static int bpf_program_record_relos(struct bpf_program *prog)
7019 {
7020 	struct bpf_object *obj = prog->obj;
7021 	int i;
7022 
7023 	for (i = 0; i < prog->nr_reloc; i++) {
7024 		struct reloc_desc *relo = &prog->reloc_desc[i];
7025 		struct extern_desc *ext = &obj->externs[relo->sym_off];
7026 
7027 		switch (relo->type) {
7028 		case RELO_EXTERN_VAR:
7029 			if (ext->type != EXT_KSYM)
7030 				continue;
7031 			bpf_gen__record_extern(obj->gen_loader, ext->name,
7032 					       ext->is_weak, !ext->ksym.type_id,
7033 					       BTF_KIND_VAR, relo->insn_idx);
7034 			break;
7035 		case RELO_EXTERN_FUNC:
7036 			bpf_gen__record_extern(obj->gen_loader, ext->name,
7037 					       ext->is_weak, false, BTF_KIND_FUNC,
7038 					       relo->insn_idx);
7039 			break;
7040 		case RELO_CORE: {
7041 			struct bpf_core_relo cr = {
7042 				.insn_off = relo->insn_idx * 8,
7043 				.type_id = relo->core_relo->type_id,
7044 				.access_str_off = relo->core_relo->access_str_off,
7045 				.kind = relo->core_relo->kind,
7046 			};
7047 
7048 			bpf_gen__record_relo_core(obj->gen_loader, &cr);
7049 			break;
7050 		}
7051 		default:
7052 			continue;
7053 		}
7054 	}
7055 	return 0;
7056 }
7057 
7058 static int
7059 bpf_object__load_progs(struct bpf_object *obj, int log_level)
7060 {
7061 	struct bpf_program *prog;
7062 	size_t i;
7063 	int err;
7064 
7065 	for (i = 0; i < obj->nr_programs; i++) {
7066 		prog = &obj->programs[i];
7067 		err = bpf_object__sanitize_prog(obj, prog);
7068 		if (err)
7069 			return err;
7070 	}
7071 
7072 	for (i = 0; i < obj->nr_programs; i++) {
7073 		prog = &obj->programs[i];
7074 		if (prog_is_subprog(obj, prog))
7075 			continue;
7076 		if (!prog->autoload) {
7077 			pr_debug("prog '%s': skipped loading\n", prog->name);
7078 			continue;
7079 		}
7080 		prog->log_level |= log_level;
7081 
7082 		if (obj->gen_loader)
7083 			bpf_program_record_relos(prog);
7084 
7085 		err = bpf_object_load_prog(obj, prog, prog->insns, prog->insns_cnt,
7086 					   obj->license, obj->kern_version, &prog->fd);
7087 		if (err) {
7088 			pr_warn("prog '%s': failed to load: %d\n", prog->name, err);
7089 			return err;
7090 		}
7091 	}
7092 
7093 	bpf_object__free_relocs(obj);
7094 	return 0;
7095 }
7096 
7097 static const struct bpf_sec_def *find_sec_def(const char *sec_name);
7098 
7099 static int bpf_object_init_progs(struct bpf_object *obj, const struct bpf_object_open_opts *opts)
7100 {
7101 	struct bpf_program *prog;
7102 	int err;
7103 
7104 	bpf_object__for_each_program(prog, obj) {
7105 		prog->sec_def = find_sec_def(prog->sec_name);
7106 		if (!prog->sec_def) {
7107 			/* couldn't guess, but user might manually specify */
7108 			pr_debug("prog '%s': unrecognized ELF section name '%s'\n",
7109 				prog->name, prog->sec_name);
7110 			continue;
7111 		}
7112 
7113 		prog->type = prog->sec_def->prog_type;
7114 		prog->expected_attach_type = prog->sec_def->expected_attach_type;
7115 
7116 		/* sec_def can have custom callback which should be called
7117 		 * after bpf_program is initialized to adjust its properties
7118 		 */
7119 		if (prog->sec_def->prog_setup_fn) {
7120 			err = prog->sec_def->prog_setup_fn(prog, prog->sec_def->cookie);
7121 			if (err < 0) {
7122 				pr_warn("prog '%s': failed to initialize: %d\n",
7123 					prog->name, err);
7124 				return err;
7125 			}
7126 		}
7127 	}
7128 
7129 	return 0;
7130 }
7131 
7132 static struct bpf_object *bpf_object_open(const char *path, const void *obj_buf, size_t obj_buf_sz,
7133 					  const struct bpf_object_open_opts *opts)
7134 {
7135 	const char *obj_name, *kconfig, *btf_tmp_path;
7136 	struct bpf_object *obj;
7137 	char tmp_name[64];
7138 	int err;
7139 	char *log_buf;
7140 	size_t log_size;
7141 	__u32 log_level;
7142 
7143 	if (elf_version(EV_CURRENT) == EV_NONE) {
7144 		pr_warn("failed to init libelf for %s\n",
7145 			path ? : "(mem buf)");
7146 		return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
7147 	}
7148 
7149 	if (!OPTS_VALID(opts, bpf_object_open_opts))
7150 		return ERR_PTR(-EINVAL);
7151 
7152 	obj_name = OPTS_GET(opts, object_name, NULL);
7153 	if (obj_buf) {
7154 		if (!obj_name) {
7155 			snprintf(tmp_name, sizeof(tmp_name), "%lx-%lx",
7156 				 (unsigned long)obj_buf,
7157 				 (unsigned long)obj_buf_sz);
7158 			obj_name = tmp_name;
7159 		}
7160 		path = obj_name;
7161 		pr_debug("loading object '%s' from buffer\n", obj_name);
7162 	}
7163 
7164 	log_buf = OPTS_GET(opts, kernel_log_buf, NULL);
7165 	log_size = OPTS_GET(opts, kernel_log_size, 0);
7166 	log_level = OPTS_GET(opts, kernel_log_level, 0);
7167 	if (log_size > UINT_MAX)
7168 		return ERR_PTR(-EINVAL);
7169 	if (log_size && !log_buf)
7170 		return ERR_PTR(-EINVAL);
7171 
7172 	obj = bpf_object__new(path, obj_buf, obj_buf_sz, obj_name);
7173 	if (IS_ERR(obj))
7174 		return obj;
7175 
7176 	obj->log_buf = log_buf;
7177 	obj->log_size = log_size;
7178 	obj->log_level = log_level;
7179 
7180 	btf_tmp_path = OPTS_GET(opts, btf_custom_path, NULL);
7181 	if (btf_tmp_path) {
7182 		if (strlen(btf_tmp_path) >= PATH_MAX) {
7183 			err = -ENAMETOOLONG;
7184 			goto out;
7185 		}
7186 		obj->btf_custom_path = strdup(btf_tmp_path);
7187 		if (!obj->btf_custom_path) {
7188 			err = -ENOMEM;
7189 			goto out;
7190 		}
7191 	}
7192 
7193 	kconfig = OPTS_GET(opts, kconfig, NULL);
7194 	if (kconfig) {
7195 		obj->kconfig = strdup(kconfig);
7196 		if (!obj->kconfig) {
7197 			err = -ENOMEM;
7198 			goto out;
7199 		}
7200 	}
7201 
7202 	err = bpf_object__elf_init(obj);
7203 	err = err ? : bpf_object__check_endianness(obj);
7204 	err = err ? : bpf_object__elf_collect(obj);
7205 	err = err ? : bpf_object__collect_externs(obj);
7206 	err = err ? : bpf_object__finalize_btf(obj);
7207 	err = err ? : bpf_object__init_maps(obj, opts);
7208 	err = err ? : bpf_object_init_progs(obj, opts);
7209 	err = err ? : bpf_object__collect_relos(obj);
7210 	if (err)
7211 		goto out;
7212 
7213 	bpf_object__elf_finish(obj);
7214 
7215 	return obj;
7216 out:
7217 	bpf_object__close(obj);
7218 	return ERR_PTR(err);
7219 }
7220 
7221 struct bpf_object *
7222 bpf_object__open_file(const char *path, const struct bpf_object_open_opts *opts)
7223 {
7224 	if (!path)
7225 		return libbpf_err_ptr(-EINVAL);
7226 
7227 	pr_debug("loading %s\n", path);
7228 
7229 	return libbpf_ptr(bpf_object_open(path, NULL, 0, opts));
7230 }
7231 
7232 struct bpf_object *bpf_object__open(const char *path)
7233 {
7234 	return bpf_object__open_file(path, NULL);
7235 }
7236 
7237 struct bpf_object *
7238 bpf_object__open_mem(const void *obj_buf, size_t obj_buf_sz,
7239 		     const struct bpf_object_open_opts *opts)
7240 {
7241 	if (!obj_buf || obj_buf_sz == 0)
7242 		return libbpf_err_ptr(-EINVAL);
7243 
7244 	return libbpf_ptr(bpf_object_open(NULL, obj_buf, obj_buf_sz, opts));
7245 }
7246 
7247 static int bpf_object_unload(struct bpf_object *obj)
7248 {
7249 	size_t i;
7250 
7251 	if (!obj)
7252 		return libbpf_err(-EINVAL);
7253 
7254 	for (i = 0; i < obj->nr_maps; i++) {
7255 		zclose(obj->maps[i].fd);
7256 		if (obj->maps[i].st_ops)
7257 			zfree(&obj->maps[i].st_ops->kern_vdata);
7258 	}
7259 
7260 	for (i = 0; i < obj->nr_programs; i++)
7261 		bpf_program__unload(&obj->programs[i]);
7262 
7263 	return 0;
7264 }
7265 
7266 static int bpf_object__sanitize_maps(struct bpf_object *obj)
7267 {
7268 	struct bpf_map *m;
7269 
7270 	bpf_object__for_each_map(m, obj) {
7271 		if (!bpf_map__is_internal(m))
7272 			continue;
7273 		if (!kernel_supports(obj, FEAT_ARRAY_MMAP))
7274 			m->def.map_flags ^= BPF_F_MMAPABLE;
7275 	}
7276 
7277 	return 0;
7278 }
7279 
7280 int libbpf_kallsyms_parse(kallsyms_cb_t cb, void *ctx)
7281 {
7282 	char sym_type, sym_name[500];
7283 	unsigned long long sym_addr;
7284 	int ret, err = 0;
7285 	FILE *f;
7286 
7287 	f = fopen("/proc/kallsyms", "r");
7288 	if (!f) {
7289 		err = -errno;
7290 		pr_warn("failed to open /proc/kallsyms: %d\n", err);
7291 		return err;
7292 	}
7293 
7294 	while (true) {
7295 		ret = fscanf(f, "%llx %c %499s%*[^\n]\n",
7296 			     &sym_addr, &sym_type, sym_name);
7297 		if (ret == EOF && feof(f))
7298 			break;
7299 		if (ret != 3) {
7300 			pr_warn("failed to read kallsyms entry: %d\n", ret);
7301 			err = -EINVAL;
7302 			break;
7303 		}
7304 
7305 		err = cb(sym_addr, sym_type, sym_name, ctx);
7306 		if (err)
7307 			break;
7308 	}
7309 
7310 	fclose(f);
7311 	return err;
7312 }
7313 
7314 static int kallsyms_cb(unsigned long long sym_addr, char sym_type,
7315 		       const char *sym_name, void *ctx)
7316 {
7317 	struct bpf_object *obj = ctx;
7318 	const struct btf_type *t;
7319 	struct extern_desc *ext;
7320 
7321 	ext = find_extern_by_name(obj, sym_name);
7322 	if (!ext || ext->type != EXT_KSYM)
7323 		return 0;
7324 
7325 	t = btf__type_by_id(obj->btf, ext->btf_id);
7326 	if (!btf_is_var(t))
7327 		return 0;
7328 
7329 	if (ext->is_set && ext->ksym.addr != sym_addr) {
7330 		pr_warn("extern (ksym) '%s': resolution is ambiguous: 0x%llx or 0x%llx\n",
7331 			sym_name, ext->ksym.addr, sym_addr);
7332 		return -EINVAL;
7333 	}
7334 	if (!ext->is_set) {
7335 		ext->is_set = true;
7336 		ext->ksym.addr = sym_addr;
7337 		pr_debug("extern (ksym) '%s': set to 0x%llx\n", sym_name, sym_addr);
7338 	}
7339 	return 0;
7340 }
7341 
7342 static int bpf_object__read_kallsyms_file(struct bpf_object *obj)
7343 {
7344 	return libbpf_kallsyms_parse(kallsyms_cb, obj);
7345 }
7346 
7347 static int find_ksym_btf_id(struct bpf_object *obj, const char *ksym_name,
7348 			    __u16 kind, struct btf **res_btf,
7349 			    struct module_btf **res_mod_btf)
7350 {
7351 	struct module_btf *mod_btf;
7352 	struct btf *btf;
7353 	int i, id, err;
7354 
7355 	btf = obj->btf_vmlinux;
7356 	mod_btf = NULL;
7357 	id = btf__find_by_name_kind(btf, ksym_name, kind);
7358 
7359 	if (id == -ENOENT) {
7360 		err = load_module_btfs(obj);
7361 		if (err)
7362 			return err;
7363 
7364 		for (i = 0; i < obj->btf_module_cnt; i++) {
7365 			/* we assume module_btf's BTF FD is always >0 */
7366 			mod_btf = &obj->btf_modules[i];
7367 			btf = mod_btf->btf;
7368 			id = btf__find_by_name_kind_own(btf, ksym_name, kind);
7369 			if (id != -ENOENT)
7370 				break;
7371 		}
7372 	}
7373 	if (id <= 0)
7374 		return -ESRCH;
7375 
7376 	*res_btf = btf;
7377 	*res_mod_btf = mod_btf;
7378 	return id;
7379 }
7380 
7381 static int bpf_object__resolve_ksym_var_btf_id(struct bpf_object *obj,
7382 					       struct extern_desc *ext)
7383 {
7384 	const struct btf_type *targ_var, *targ_type;
7385 	__u32 targ_type_id, local_type_id;
7386 	struct module_btf *mod_btf = NULL;
7387 	const char *targ_var_name;
7388 	struct btf *btf = NULL;
7389 	int id, err;
7390 
7391 	id = find_ksym_btf_id(obj, ext->name, BTF_KIND_VAR, &btf, &mod_btf);
7392 	if (id < 0) {
7393 		if (id == -ESRCH && ext->is_weak)
7394 			return 0;
7395 		pr_warn("extern (var ksym) '%s': not found in kernel BTF\n",
7396 			ext->name);
7397 		return id;
7398 	}
7399 
7400 	/* find local type_id */
7401 	local_type_id = ext->ksym.type_id;
7402 
7403 	/* find target type_id */
7404 	targ_var = btf__type_by_id(btf, id);
7405 	targ_var_name = btf__name_by_offset(btf, targ_var->name_off);
7406 	targ_type = skip_mods_and_typedefs(btf, targ_var->type, &targ_type_id);
7407 
7408 	err = bpf_core_types_are_compat(obj->btf, local_type_id,
7409 					btf, targ_type_id);
7410 	if (err <= 0) {
7411 		const struct btf_type *local_type;
7412 		const char *targ_name, *local_name;
7413 
7414 		local_type = btf__type_by_id(obj->btf, local_type_id);
7415 		local_name = btf__name_by_offset(obj->btf, local_type->name_off);
7416 		targ_name = btf__name_by_offset(btf, targ_type->name_off);
7417 
7418 		pr_warn("extern (var ksym) '%s': incompatible types, expected [%d] %s %s, but kernel has [%d] %s %s\n",
7419 			ext->name, local_type_id,
7420 			btf_kind_str(local_type), local_name, targ_type_id,
7421 			btf_kind_str(targ_type), targ_name);
7422 		return -EINVAL;
7423 	}
7424 
7425 	ext->is_set = true;
7426 	ext->ksym.kernel_btf_obj_fd = mod_btf ? mod_btf->fd : 0;
7427 	ext->ksym.kernel_btf_id = id;
7428 	pr_debug("extern (var ksym) '%s': resolved to [%d] %s %s\n",
7429 		 ext->name, id, btf_kind_str(targ_var), targ_var_name);
7430 
7431 	return 0;
7432 }
7433 
7434 static int bpf_object__resolve_ksym_func_btf_id(struct bpf_object *obj,
7435 						struct extern_desc *ext)
7436 {
7437 	int local_func_proto_id, kfunc_proto_id, kfunc_id;
7438 	struct module_btf *mod_btf = NULL;
7439 	const struct btf_type *kern_func;
7440 	struct btf *kern_btf = NULL;
7441 	int ret;
7442 
7443 	local_func_proto_id = ext->ksym.type_id;
7444 
7445 	kfunc_id = find_ksym_btf_id(obj, ext->name, BTF_KIND_FUNC, &kern_btf, &mod_btf);
7446 	if (kfunc_id < 0) {
7447 		if (kfunc_id == -ESRCH && ext->is_weak)
7448 			return 0;
7449 		pr_warn("extern (func ksym) '%s': not found in kernel or module BTFs\n",
7450 			ext->name);
7451 		return kfunc_id;
7452 	}
7453 
7454 	kern_func = btf__type_by_id(kern_btf, kfunc_id);
7455 	kfunc_proto_id = kern_func->type;
7456 
7457 	ret = bpf_core_types_are_compat(obj->btf, local_func_proto_id,
7458 					kern_btf, kfunc_proto_id);
7459 	if (ret <= 0) {
7460 		pr_warn("extern (func ksym) '%s': func_proto [%d] incompatible with kernel [%d]\n",
7461 			ext->name, local_func_proto_id, kfunc_proto_id);
7462 		return -EINVAL;
7463 	}
7464 
7465 	/* set index for module BTF fd in fd_array, if unset */
7466 	if (mod_btf && !mod_btf->fd_array_idx) {
7467 		/* insn->off is s16 */
7468 		if (obj->fd_array_cnt == INT16_MAX) {
7469 			pr_warn("extern (func ksym) '%s': module BTF fd index %d too big to fit in bpf_insn offset\n",
7470 				ext->name, mod_btf->fd_array_idx);
7471 			return -E2BIG;
7472 		}
7473 		/* Cannot use index 0 for module BTF fd */
7474 		if (!obj->fd_array_cnt)
7475 			obj->fd_array_cnt = 1;
7476 
7477 		ret = libbpf_ensure_mem((void **)&obj->fd_array, &obj->fd_array_cap, sizeof(int),
7478 					obj->fd_array_cnt + 1);
7479 		if (ret)
7480 			return ret;
7481 		mod_btf->fd_array_idx = obj->fd_array_cnt;
7482 		/* we assume module BTF FD is always >0 */
7483 		obj->fd_array[obj->fd_array_cnt++] = mod_btf->fd;
7484 	}
7485 
7486 	ext->is_set = true;
7487 	ext->ksym.kernel_btf_id = kfunc_id;
7488 	ext->ksym.btf_fd_idx = mod_btf ? mod_btf->fd_array_idx : 0;
7489 	pr_debug("extern (func ksym) '%s': resolved to kernel [%d]\n",
7490 		 ext->name, kfunc_id);
7491 
7492 	return 0;
7493 }
7494 
7495 static int bpf_object__resolve_ksyms_btf_id(struct bpf_object *obj)
7496 {
7497 	const struct btf_type *t;
7498 	struct extern_desc *ext;
7499 	int i, err;
7500 
7501 	for (i = 0; i < obj->nr_extern; i++) {
7502 		ext = &obj->externs[i];
7503 		if (ext->type != EXT_KSYM || !ext->ksym.type_id)
7504 			continue;
7505 
7506 		if (obj->gen_loader) {
7507 			ext->is_set = true;
7508 			ext->ksym.kernel_btf_obj_fd = 0;
7509 			ext->ksym.kernel_btf_id = 0;
7510 			continue;
7511 		}
7512 		t = btf__type_by_id(obj->btf, ext->btf_id);
7513 		if (btf_is_var(t))
7514 			err = bpf_object__resolve_ksym_var_btf_id(obj, ext);
7515 		else
7516 			err = bpf_object__resolve_ksym_func_btf_id(obj, ext);
7517 		if (err)
7518 			return err;
7519 	}
7520 	return 0;
7521 }
7522 
7523 static int bpf_object__resolve_externs(struct bpf_object *obj,
7524 				       const char *extra_kconfig)
7525 {
7526 	bool need_config = false, need_kallsyms = false;
7527 	bool need_vmlinux_btf = false;
7528 	struct extern_desc *ext;
7529 	void *kcfg_data = NULL;
7530 	int err, i;
7531 
7532 	if (obj->nr_extern == 0)
7533 		return 0;
7534 
7535 	if (obj->kconfig_map_idx >= 0)
7536 		kcfg_data = obj->maps[obj->kconfig_map_idx].mmaped;
7537 
7538 	for (i = 0; i < obj->nr_extern; i++) {
7539 		ext = &obj->externs[i];
7540 
7541 		if (ext->type == EXT_KSYM) {
7542 			if (ext->ksym.type_id)
7543 				need_vmlinux_btf = true;
7544 			else
7545 				need_kallsyms = true;
7546 			continue;
7547 		} else if (ext->type == EXT_KCFG) {
7548 			void *ext_ptr = kcfg_data + ext->kcfg.data_off;
7549 			__u64 value = 0;
7550 
7551 			/* Kconfig externs need actual /proc/config.gz */
7552 			if (str_has_pfx(ext->name, "CONFIG_")) {
7553 				need_config = true;
7554 				continue;
7555 			}
7556 
7557 			/* Virtual kcfg externs are customly handled by libbpf */
7558 			if (strcmp(ext->name, "LINUX_KERNEL_VERSION") == 0) {
7559 				value = get_kernel_version();
7560 				if (!value) {
7561 					pr_warn("extern (kcfg) '%s': failed to get kernel version\n", ext->name);
7562 					return -EINVAL;
7563 				}
7564 			} else if (strcmp(ext->name, "LINUX_HAS_BPF_COOKIE") == 0) {
7565 				value = kernel_supports(obj, FEAT_BPF_COOKIE);
7566 			} else if (strcmp(ext->name, "LINUX_HAS_SYSCALL_WRAPPER") == 0) {
7567 				value = kernel_supports(obj, FEAT_SYSCALL_WRAPPER);
7568 			} else if (!str_has_pfx(ext->name, "LINUX_") || !ext->is_weak) {
7569 				/* Currently libbpf supports only CONFIG_ and LINUX_ prefixed
7570 				 * __kconfig externs, where LINUX_ ones are virtual and filled out
7571 				 * customly by libbpf (their values don't come from Kconfig).
7572 				 * If LINUX_xxx variable is not recognized by libbpf, but is marked
7573 				 * __weak, it defaults to zero value, just like for CONFIG_xxx
7574 				 * externs.
7575 				 */
7576 				pr_warn("extern (kcfg) '%s': unrecognized virtual extern\n", ext->name);
7577 				return -EINVAL;
7578 			}
7579 
7580 			err = set_kcfg_value_num(ext, ext_ptr, value);
7581 			if (err)
7582 				return err;
7583 			pr_debug("extern (kcfg) '%s': set to 0x%llx\n",
7584 				 ext->name, (long long)value);
7585 		} else {
7586 			pr_warn("extern '%s': unrecognized extern kind\n", ext->name);
7587 			return -EINVAL;
7588 		}
7589 	}
7590 	if (need_config && extra_kconfig) {
7591 		err = bpf_object__read_kconfig_mem(obj, extra_kconfig, kcfg_data);
7592 		if (err)
7593 			return -EINVAL;
7594 		need_config = false;
7595 		for (i = 0; i < obj->nr_extern; i++) {
7596 			ext = &obj->externs[i];
7597 			if (ext->type == EXT_KCFG && !ext->is_set) {
7598 				need_config = true;
7599 				break;
7600 			}
7601 		}
7602 	}
7603 	if (need_config) {
7604 		err = bpf_object__read_kconfig_file(obj, kcfg_data);
7605 		if (err)
7606 			return -EINVAL;
7607 	}
7608 	if (need_kallsyms) {
7609 		err = bpf_object__read_kallsyms_file(obj);
7610 		if (err)
7611 			return -EINVAL;
7612 	}
7613 	if (need_vmlinux_btf) {
7614 		err = bpf_object__resolve_ksyms_btf_id(obj);
7615 		if (err)
7616 			return -EINVAL;
7617 	}
7618 	for (i = 0; i < obj->nr_extern; i++) {
7619 		ext = &obj->externs[i];
7620 
7621 		if (!ext->is_set && !ext->is_weak) {
7622 			pr_warn("extern '%s' (strong): not resolved\n", ext->name);
7623 			return -ESRCH;
7624 		} else if (!ext->is_set) {
7625 			pr_debug("extern '%s' (weak): not resolved, defaulting to zero\n",
7626 				 ext->name);
7627 		}
7628 	}
7629 
7630 	return 0;
7631 }
7632 
7633 static int bpf_object_load(struct bpf_object *obj, int extra_log_level, const char *target_btf_path)
7634 {
7635 	int err, i;
7636 
7637 	if (!obj)
7638 		return libbpf_err(-EINVAL);
7639 
7640 	if (obj->loaded) {
7641 		pr_warn("object '%s': load can't be attempted twice\n", obj->name);
7642 		return libbpf_err(-EINVAL);
7643 	}
7644 
7645 	if (obj->gen_loader)
7646 		bpf_gen__init(obj->gen_loader, extra_log_level, obj->nr_programs, obj->nr_maps);
7647 
7648 	err = bpf_object__probe_loading(obj);
7649 	err = err ? : bpf_object__load_vmlinux_btf(obj, false);
7650 	err = err ? : bpf_object__resolve_externs(obj, obj->kconfig);
7651 	err = err ? : bpf_object__sanitize_and_load_btf(obj);
7652 	err = err ? : bpf_object__sanitize_maps(obj);
7653 	err = err ? : bpf_object__init_kern_struct_ops_maps(obj);
7654 	err = err ? : bpf_object__create_maps(obj);
7655 	err = err ? : bpf_object__relocate(obj, obj->btf_custom_path ? : target_btf_path);
7656 	err = err ? : bpf_object__load_progs(obj, extra_log_level);
7657 	err = err ? : bpf_object_init_prog_arrays(obj);
7658 
7659 	if (obj->gen_loader) {
7660 		/* reset FDs */
7661 		if (obj->btf)
7662 			btf__set_fd(obj->btf, -1);
7663 		for (i = 0; i < obj->nr_maps; i++)
7664 			obj->maps[i].fd = -1;
7665 		if (!err)
7666 			err = bpf_gen__finish(obj->gen_loader, obj->nr_programs, obj->nr_maps);
7667 	}
7668 
7669 	/* clean up fd_array */
7670 	zfree(&obj->fd_array);
7671 
7672 	/* clean up module BTFs */
7673 	for (i = 0; i < obj->btf_module_cnt; i++) {
7674 		close(obj->btf_modules[i].fd);
7675 		btf__free(obj->btf_modules[i].btf);
7676 		free(obj->btf_modules[i].name);
7677 	}
7678 	free(obj->btf_modules);
7679 
7680 	/* clean up vmlinux BTF */
7681 	btf__free(obj->btf_vmlinux);
7682 	obj->btf_vmlinux = NULL;
7683 
7684 	obj->loaded = true; /* doesn't matter if successfully or not */
7685 
7686 	if (err)
7687 		goto out;
7688 
7689 	return 0;
7690 out:
7691 	/* unpin any maps that were auto-pinned during load */
7692 	for (i = 0; i < obj->nr_maps; i++)
7693 		if (obj->maps[i].pinned && !obj->maps[i].reused)
7694 			bpf_map__unpin(&obj->maps[i], NULL);
7695 
7696 	bpf_object_unload(obj);
7697 	pr_warn("failed to load object '%s'\n", obj->path);
7698 	return libbpf_err(err);
7699 }
7700 
7701 int bpf_object__load(struct bpf_object *obj)
7702 {
7703 	return bpf_object_load(obj, 0, NULL);
7704 }
7705 
7706 static int make_parent_dir(const char *path)
7707 {
7708 	char *cp, errmsg[STRERR_BUFSIZE];
7709 	char *dname, *dir;
7710 	int err = 0;
7711 
7712 	dname = strdup(path);
7713 	if (dname == NULL)
7714 		return -ENOMEM;
7715 
7716 	dir = dirname(dname);
7717 	if (mkdir(dir, 0700) && errno != EEXIST)
7718 		err = -errno;
7719 
7720 	free(dname);
7721 	if (err) {
7722 		cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
7723 		pr_warn("failed to mkdir %s: %s\n", path, cp);
7724 	}
7725 	return err;
7726 }
7727 
7728 static int check_path(const char *path)
7729 {
7730 	char *cp, errmsg[STRERR_BUFSIZE];
7731 	struct statfs st_fs;
7732 	char *dname, *dir;
7733 	int err = 0;
7734 
7735 	if (path == NULL)
7736 		return -EINVAL;
7737 
7738 	dname = strdup(path);
7739 	if (dname == NULL)
7740 		return -ENOMEM;
7741 
7742 	dir = dirname(dname);
7743 	if (statfs(dir, &st_fs)) {
7744 		cp = libbpf_strerror_r(errno, errmsg, sizeof(errmsg));
7745 		pr_warn("failed to statfs %s: %s\n", dir, cp);
7746 		err = -errno;
7747 	}
7748 	free(dname);
7749 
7750 	if (!err && st_fs.f_type != BPF_FS_MAGIC) {
7751 		pr_warn("specified path %s is not on BPF FS\n", path);
7752 		err = -EINVAL;
7753 	}
7754 
7755 	return err;
7756 }
7757 
7758 int bpf_program__pin(struct bpf_program *prog, const char *path)
7759 {
7760 	char *cp, errmsg[STRERR_BUFSIZE];
7761 	int err;
7762 
7763 	if (prog->fd < 0) {
7764 		pr_warn("prog '%s': can't pin program that wasn't loaded\n", prog->name);
7765 		return libbpf_err(-EINVAL);
7766 	}
7767 
7768 	err = make_parent_dir(path);
7769 	if (err)
7770 		return libbpf_err(err);
7771 
7772 	err = check_path(path);
7773 	if (err)
7774 		return libbpf_err(err);
7775 
7776 	if (bpf_obj_pin(prog->fd, path)) {
7777 		err = -errno;
7778 		cp = libbpf_strerror_r(err, errmsg, sizeof(errmsg));
7779 		pr_warn("prog '%s': failed to pin at '%s': %s\n", prog->name, path, cp);
7780 		return libbpf_err(err);
7781 	}
7782 
7783 	pr_debug("prog '%s': pinned at '%s'\n", prog->name, path);
7784 	return 0;
7785 }
7786 
7787 int bpf_program__unpin(struct bpf_program *prog, const char *path)
7788 {
7789 	int err;
7790 
7791 	if (prog->fd < 0) {
7792 		pr_warn("prog '%s': can't unpin program that wasn't loaded\n", prog->name);
7793 		return libbpf_err(-EINVAL);
7794 	}
7795 
7796 	err = check_path(path);
7797 	if (err)
7798 		return libbpf_err(err);
7799 
7800 	err = unlink(path);
7801 	if (err)
7802 		return libbpf_err(-errno);
7803 
7804 	pr_debug("prog '%s': unpinned from '%s'\n", prog->name, path);
7805 	return 0;
7806 }
7807 
7808 int bpf_map__pin(struct bpf_map *map, const char *path)
7809 {
7810 	char *cp, errmsg[STRERR_BUFSIZE];
7811 	int err;
7812 
7813 	if (map == NULL) {
7814 		pr_warn("invalid map pointer\n");
7815 		return libbpf_err(-EINVAL);
7816 	}
7817 
7818 	if (map->pin_path) {
7819 		if (path && strcmp(path, map->pin_path)) {
7820 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
7821 				bpf_map__name(map), map->pin_path, path);
7822 			return libbpf_err(-EINVAL);
7823 		} else if (map->pinned) {
7824 			pr_debug("map '%s' already pinned at '%s'; not re-pinning\n",
7825 				 bpf_map__name(map), map->pin_path);
7826 			return 0;
7827 		}
7828 	} else {
7829 		if (!path) {
7830 			pr_warn("missing a path to pin map '%s' at\n",
7831 				bpf_map__name(map));
7832 			return libbpf_err(-EINVAL);
7833 		} else if (map->pinned) {
7834 			pr_warn("map '%s' already pinned\n", bpf_map__name(map));
7835 			return libbpf_err(-EEXIST);
7836 		}
7837 
7838 		map->pin_path = strdup(path);
7839 		if (!map->pin_path) {
7840 			err = -errno;
7841 			goto out_err;
7842 		}
7843 	}
7844 
7845 	err = make_parent_dir(map->pin_path);
7846 	if (err)
7847 		return libbpf_err(err);
7848 
7849 	err = check_path(map->pin_path);
7850 	if (err)
7851 		return libbpf_err(err);
7852 
7853 	if (bpf_obj_pin(map->fd, map->pin_path)) {
7854 		err = -errno;
7855 		goto out_err;
7856 	}
7857 
7858 	map->pinned = true;
7859 	pr_debug("pinned map '%s'\n", map->pin_path);
7860 
7861 	return 0;
7862 
7863 out_err:
7864 	cp = libbpf_strerror_r(-err, errmsg, sizeof(errmsg));
7865 	pr_warn("failed to pin map: %s\n", cp);
7866 	return libbpf_err(err);
7867 }
7868 
7869 int bpf_map__unpin(struct bpf_map *map, const char *path)
7870 {
7871 	int err;
7872 
7873 	if (map == NULL) {
7874 		pr_warn("invalid map pointer\n");
7875 		return libbpf_err(-EINVAL);
7876 	}
7877 
7878 	if (map->pin_path) {
7879 		if (path && strcmp(path, map->pin_path)) {
7880 			pr_warn("map '%s' already has pin path '%s' different from '%s'\n",
7881 				bpf_map__name(map), map->pin_path, path);
7882 			return libbpf_err(-EINVAL);
7883 		}
7884 		path = map->pin_path;
7885 	} else if (!path) {
7886 		pr_warn("no path to unpin map '%s' from\n",
7887 			bpf_map__name(map));
7888 		return libbpf_err(-EINVAL);
7889 	}
7890 
7891 	err = check_path(path);
7892 	if (err)
7893 		return libbpf_err(err);
7894 
7895 	err = unlink(path);
7896 	if (err != 0)
7897 		return libbpf_err(-errno);
7898 
7899 	map->pinned = false;
7900 	pr_debug("unpinned map '%s' from '%s'\n", bpf_map__name(map), path);
7901 
7902 	return 0;
7903 }
7904 
7905 int bpf_map__set_pin_path(struct bpf_map *map, const char *path)
7906 {
7907 	char *new = NULL;
7908 
7909 	if (path) {
7910 		new = strdup(path);
7911 		if (!new)
7912 			return libbpf_err(-errno);
7913 	}
7914 
7915 	free(map->pin_path);
7916 	map->pin_path = new;
7917 	return 0;
7918 }
7919 
7920 __alias(bpf_map__pin_path)
7921 const char *bpf_map__get_pin_path(const struct bpf_map *map);
7922 
7923 const char *bpf_map__pin_path(const struct bpf_map *map)
7924 {
7925 	return map->pin_path;
7926 }
7927 
7928 bool bpf_map__is_pinned(const struct bpf_map *map)
7929 {
7930 	return map->pinned;
7931 }
7932 
7933 static void sanitize_pin_path(char *s)
7934 {
7935 	/* bpffs disallows periods in path names */
7936 	while (*s) {
7937 		if (*s == '.')
7938 			*s = '_';
7939 		s++;
7940 	}
7941 }
7942 
7943 int bpf_object__pin_maps(struct bpf_object *obj, const char *path)
7944 {
7945 	struct bpf_map *map;
7946 	int err;
7947 
7948 	if (!obj)
7949 		return libbpf_err(-ENOENT);
7950 
7951 	if (!obj->loaded) {
7952 		pr_warn("object not yet loaded; load it first\n");
7953 		return libbpf_err(-ENOENT);
7954 	}
7955 
7956 	bpf_object__for_each_map(map, obj) {
7957 		char *pin_path = NULL;
7958 		char buf[PATH_MAX];
7959 
7960 		if (!map->autocreate)
7961 			continue;
7962 
7963 		if (path) {
7964 			int len;
7965 
7966 			len = snprintf(buf, PATH_MAX, "%s/%s", path,
7967 				       bpf_map__name(map));
7968 			if (len < 0) {
7969 				err = -EINVAL;
7970 				goto err_unpin_maps;
7971 			} else if (len >= PATH_MAX) {
7972 				err = -ENAMETOOLONG;
7973 				goto err_unpin_maps;
7974 			}
7975 			sanitize_pin_path(buf);
7976 			pin_path = buf;
7977 		} else if (!map->pin_path) {
7978 			continue;
7979 		}
7980 
7981 		err = bpf_map__pin(map, pin_path);
7982 		if (err)
7983 			goto err_unpin_maps;
7984 	}
7985 
7986 	return 0;
7987 
7988 err_unpin_maps:
7989 	while ((map = bpf_object__prev_map(obj, map))) {
7990 		if (!map->pin_path)
7991 			continue;
7992 
7993 		bpf_map__unpin(map, NULL);
7994 	}
7995 
7996 	return libbpf_err(err);
7997 }
7998 
7999 int bpf_object__unpin_maps(struct bpf_object *obj, const char *path)
8000 {
8001 	struct bpf_map *map;
8002 	int err;
8003 
8004 	if (!obj)
8005 		return libbpf_err(-ENOENT);
8006 
8007 	bpf_object__for_each_map(map, obj) {
8008 		char *pin_path = NULL;
8009 		char buf[PATH_MAX];
8010 
8011 		if (path) {
8012 			int len;
8013 
8014 			len = snprintf(buf, PATH_MAX, "%s/%s", path,
8015 				       bpf_map__name(map));
8016 			if (len < 0)
8017 				return libbpf_err(-EINVAL);
8018 			else if (len >= PATH_MAX)
8019 				return libbpf_err(-ENAMETOOLONG);
8020 			sanitize_pin_path(buf);
8021 			pin_path = buf;
8022 		} else if (!map->pin_path) {
8023 			continue;
8024 		}
8025 
8026 		err = bpf_map__unpin(map, pin_path);
8027 		if (err)
8028 			return libbpf_err(err);
8029 	}
8030 
8031 	return 0;
8032 }
8033 
8034 int bpf_object__pin_programs(struct bpf_object *obj, const char *path)
8035 {
8036 	struct bpf_program *prog;
8037 	int err;
8038 
8039 	if (!obj)
8040 		return libbpf_err(-ENOENT);
8041 
8042 	if (!obj->loaded) {
8043 		pr_warn("object not yet loaded; load it first\n");
8044 		return libbpf_err(-ENOENT);
8045 	}
8046 
8047 	bpf_object__for_each_program(prog, obj) {
8048 		char buf[PATH_MAX];
8049 		int len;
8050 
8051 		len = snprintf(buf, PATH_MAX, "%s/%s", path, prog->name);
8052 		if (len < 0) {
8053 			err = -EINVAL;
8054 			goto err_unpin_programs;
8055 		} else if (len >= PATH_MAX) {
8056 			err = -ENAMETOOLONG;
8057 			goto err_unpin_programs;
8058 		}
8059 
8060 		err = bpf_program__pin(prog, buf);
8061 		if (err)
8062 			goto err_unpin_programs;
8063 	}
8064 
8065 	return 0;
8066 
8067 err_unpin_programs:
8068 	while ((prog = bpf_object__prev_program(obj, prog))) {
8069 		char buf[PATH_MAX];
8070 		int len;
8071 
8072 		len = snprintf(buf, PATH_MAX, "%s/%s", path, prog->name);
8073 		if (len < 0)
8074 			continue;
8075 		else if (len >= PATH_MAX)
8076 			continue;
8077 
8078 		bpf_program__unpin(prog, buf);
8079 	}
8080 
8081 	return libbpf_err(err);
8082 }
8083 
8084 int bpf_object__unpin_programs(struct bpf_object *obj, const char *path)
8085 {
8086 	struct bpf_program *prog;
8087 	int err;
8088 
8089 	if (!obj)
8090 		return libbpf_err(-ENOENT);
8091 
8092 	bpf_object__for_each_program(prog, obj) {
8093 		char buf[PATH_MAX];
8094 		int len;
8095 
8096 		len = snprintf(buf, PATH_MAX, "%s/%s", path, prog->name);
8097 		if (len < 0)
8098 			return libbpf_err(-EINVAL);
8099 		else if (len >= PATH_MAX)
8100 			return libbpf_err(-ENAMETOOLONG);
8101 
8102 		err = bpf_program__unpin(prog, buf);
8103 		if (err)
8104 			return libbpf_err(err);
8105 	}
8106 
8107 	return 0;
8108 }
8109 
8110 int bpf_object__pin(struct bpf_object *obj, const char *path)
8111 {
8112 	int err;
8113 
8114 	err = bpf_object__pin_maps(obj, path);
8115 	if (err)
8116 		return libbpf_err(err);
8117 
8118 	err = bpf_object__pin_programs(obj, path);
8119 	if (err) {
8120 		bpf_object__unpin_maps(obj, path);
8121 		return libbpf_err(err);
8122 	}
8123 
8124 	return 0;
8125 }
8126 
8127 static void bpf_map__destroy(struct bpf_map *map)
8128 {
8129 	if (map->inner_map) {
8130 		bpf_map__destroy(map->inner_map);
8131 		zfree(&map->inner_map);
8132 	}
8133 
8134 	zfree(&map->init_slots);
8135 	map->init_slots_sz = 0;
8136 
8137 	if (map->mmaped) {
8138 		munmap(map->mmaped, bpf_map_mmap_sz(map));
8139 		map->mmaped = NULL;
8140 	}
8141 
8142 	if (map->st_ops) {
8143 		zfree(&map->st_ops->data);
8144 		zfree(&map->st_ops->progs);
8145 		zfree(&map->st_ops->kern_func_off);
8146 		zfree(&map->st_ops);
8147 	}
8148 
8149 	zfree(&map->name);
8150 	zfree(&map->real_name);
8151 	zfree(&map->pin_path);
8152 
8153 	if (map->fd >= 0)
8154 		zclose(map->fd);
8155 }
8156 
8157 void bpf_object__close(struct bpf_object *obj)
8158 {
8159 	size_t i;
8160 
8161 	if (IS_ERR_OR_NULL(obj))
8162 		return;
8163 
8164 	usdt_manager_free(obj->usdt_man);
8165 	obj->usdt_man = NULL;
8166 
8167 	bpf_gen__free(obj->gen_loader);
8168 	bpf_object__elf_finish(obj);
8169 	bpf_object_unload(obj);
8170 	btf__free(obj->btf);
8171 	btf_ext__free(obj->btf_ext);
8172 
8173 	for (i = 0; i < obj->nr_maps; i++)
8174 		bpf_map__destroy(&obj->maps[i]);
8175 
8176 	zfree(&obj->btf_custom_path);
8177 	zfree(&obj->kconfig);
8178 	zfree(&obj->externs);
8179 	obj->nr_extern = 0;
8180 
8181 	zfree(&obj->maps);
8182 	obj->nr_maps = 0;
8183 
8184 	if (obj->programs && obj->nr_programs) {
8185 		for (i = 0; i < obj->nr_programs; i++)
8186 			bpf_program__exit(&obj->programs[i]);
8187 	}
8188 	zfree(&obj->programs);
8189 
8190 	free(obj);
8191 }
8192 
8193 const char *bpf_object__name(const struct bpf_object *obj)
8194 {
8195 	return obj ? obj->name : libbpf_err_ptr(-EINVAL);
8196 }
8197 
8198 unsigned int bpf_object__kversion(const struct bpf_object *obj)
8199 {
8200 	return obj ? obj->kern_version : 0;
8201 }
8202 
8203 struct btf *bpf_object__btf(const struct bpf_object *obj)
8204 {
8205 	return obj ? obj->btf : NULL;
8206 }
8207 
8208 int bpf_object__btf_fd(const struct bpf_object *obj)
8209 {
8210 	return obj->btf ? btf__fd(obj->btf) : -1;
8211 }
8212 
8213 int bpf_object__set_kversion(struct bpf_object *obj, __u32 kern_version)
8214 {
8215 	if (obj->loaded)
8216 		return libbpf_err(-EINVAL);
8217 
8218 	obj->kern_version = kern_version;
8219 
8220 	return 0;
8221 }
8222 
8223 int bpf_object__gen_loader(struct bpf_object *obj, struct gen_loader_opts *opts)
8224 {
8225 	struct bpf_gen *gen;
8226 
8227 	if (!opts)
8228 		return -EFAULT;
8229 	if (!OPTS_VALID(opts, gen_loader_opts))
8230 		return -EINVAL;
8231 	gen = calloc(sizeof(*gen), 1);
8232 	if (!gen)
8233 		return -ENOMEM;
8234 	gen->opts = opts;
8235 	obj->gen_loader = gen;
8236 	return 0;
8237 }
8238 
8239 static struct bpf_program *
8240 __bpf_program__iter(const struct bpf_program *p, const struct bpf_object *obj,
8241 		    bool forward)
8242 {
8243 	size_t nr_programs = obj->nr_programs;
8244 	ssize_t idx;
8245 
8246 	if (!nr_programs)
8247 		return NULL;
8248 
8249 	if (!p)
8250 		/* Iter from the beginning */
8251 		return forward ? &obj->programs[0] :
8252 			&obj->programs[nr_programs - 1];
8253 
8254 	if (p->obj != obj) {
8255 		pr_warn("error: program handler doesn't match object\n");
8256 		return errno = EINVAL, NULL;
8257 	}
8258 
8259 	idx = (p - obj->programs) + (forward ? 1 : -1);
8260 	if (idx >= obj->nr_programs || idx < 0)
8261 		return NULL;
8262 	return &obj->programs[idx];
8263 }
8264 
8265 struct bpf_program *
8266 bpf_object__next_program(const struct bpf_object *obj, struct bpf_program *prev)
8267 {
8268 	struct bpf_program *prog = prev;
8269 
8270 	do {
8271 		prog = __bpf_program__iter(prog, obj, true);
8272 	} while (prog && prog_is_subprog(obj, prog));
8273 
8274 	return prog;
8275 }
8276 
8277 struct bpf_program *
8278 bpf_object__prev_program(const struct bpf_object *obj, struct bpf_program *next)
8279 {
8280 	struct bpf_program *prog = next;
8281 
8282 	do {
8283 		prog = __bpf_program__iter(prog, obj, false);
8284 	} while (prog && prog_is_subprog(obj, prog));
8285 
8286 	return prog;
8287 }
8288 
8289 void bpf_program__set_ifindex(struct bpf_program *prog, __u32 ifindex)
8290 {
8291 	prog->prog_ifindex = ifindex;
8292 }
8293 
8294 const char *bpf_program__name(const struct bpf_program *prog)
8295 {
8296 	return prog->name;
8297 }
8298 
8299 const char *bpf_program__section_name(const struct bpf_program *prog)
8300 {
8301 	return prog->sec_name;
8302 }
8303 
8304 bool bpf_program__autoload(const struct bpf_program *prog)
8305 {
8306 	return prog->autoload;
8307 }
8308 
8309 int bpf_program__set_autoload(struct bpf_program *prog, bool autoload)
8310 {
8311 	if (prog->obj->loaded)
8312 		return libbpf_err(-EINVAL);
8313 
8314 	prog->autoload = autoload;
8315 	return 0;
8316 }
8317 
8318 bool bpf_program__autoattach(const struct bpf_program *prog)
8319 {
8320 	return prog->autoattach;
8321 }
8322 
8323 void bpf_program__set_autoattach(struct bpf_program *prog, bool autoattach)
8324 {
8325 	prog->autoattach = autoattach;
8326 }
8327 
8328 const struct bpf_insn *bpf_program__insns(const struct bpf_program *prog)
8329 {
8330 	return prog->insns;
8331 }
8332 
8333 size_t bpf_program__insn_cnt(const struct bpf_program *prog)
8334 {
8335 	return prog->insns_cnt;
8336 }
8337 
8338 int bpf_program__set_insns(struct bpf_program *prog,
8339 			   struct bpf_insn *new_insns, size_t new_insn_cnt)
8340 {
8341 	struct bpf_insn *insns;
8342 
8343 	if (prog->obj->loaded)
8344 		return -EBUSY;
8345 
8346 	insns = libbpf_reallocarray(prog->insns, new_insn_cnt, sizeof(*insns));
8347 	if (!insns) {
8348 		pr_warn("prog '%s': failed to realloc prog code\n", prog->name);
8349 		return -ENOMEM;
8350 	}
8351 	memcpy(insns, new_insns, new_insn_cnt * sizeof(*insns));
8352 
8353 	prog->insns = insns;
8354 	prog->insns_cnt = new_insn_cnt;
8355 	return 0;
8356 }
8357 
8358 int bpf_program__fd(const struct bpf_program *prog)
8359 {
8360 	if (!prog)
8361 		return libbpf_err(-EINVAL);
8362 
8363 	if (prog->fd < 0)
8364 		return libbpf_err(-ENOENT);
8365 
8366 	return prog->fd;
8367 }
8368 
8369 __alias(bpf_program__type)
8370 enum bpf_prog_type bpf_program__get_type(const struct bpf_program *prog);
8371 
8372 enum bpf_prog_type bpf_program__type(const struct bpf_program *prog)
8373 {
8374 	return prog->type;
8375 }
8376 
8377 int bpf_program__set_type(struct bpf_program *prog, enum bpf_prog_type type)
8378 {
8379 	if (prog->obj->loaded)
8380 		return libbpf_err(-EBUSY);
8381 
8382 	prog->type = type;
8383 	return 0;
8384 }
8385 
8386 __alias(bpf_program__expected_attach_type)
8387 enum bpf_attach_type bpf_program__get_expected_attach_type(const struct bpf_program *prog);
8388 
8389 enum bpf_attach_type bpf_program__expected_attach_type(const struct bpf_program *prog)
8390 {
8391 	return prog->expected_attach_type;
8392 }
8393 
8394 int bpf_program__set_expected_attach_type(struct bpf_program *prog,
8395 					   enum bpf_attach_type type)
8396 {
8397 	if (prog->obj->loaded)
8398 		return libbpf_err(-EBUSY);
8399 
8400 	prog->expected_attach_type = type;
8401 	return 0;
8402 }
8403 
8404 __u32 bpf_program__flags(const struct bpf_program *prog)
8405 {
8406 	return prog->prog_flags;
8407 }
8408 
8409 int bpf_program__set_flags(struct bpf_program *prog, __u32 flags)
8410 {
8411 	if (prog->obj->loaded)
8412 		return libbpf_err(-EBUSY);
8413 
8414 	prog->prog_flags = flags;
8415 	return 0;
8416 }
8417 
8418 __u32 bpf_program__log_level(const struct bpf_program *prog)
8419 {
8420 	return prog->log_level;
8421 }
8422 
8423 int bpf_program__set_log_level(struct bpf_program *prog, __u32 log_level)
8424 {
8425 	if (prog->obj->loaded)
8426 		return libbpf_err(-EBUSY);
8427 
8428 	prog->log_level = log_level;
8429 	return 0;
8430 }
8431 
8432 const char *bpf_program__log_buf(const struct bpf_program *prog, size_t *log_size)
8433 {
8434 	*log_size = prog->log_size;
8435 	return prog->log_buf;
8436 }
8437 
8438 int bpf_program__set_log_buf(struct bpf_program *prog, char *log_buf, size_t log_size)
8439 {
8440 	if (log_size && !log_buf)
8441 		return -EINVAL;
8442 	if (prog->log_size > UINT_MAX)
8443 		return -EINVAL;
8444 	if (prog->obj->loaded)
8445 		return -EBUSY;
8446 
8447 	prog->log_buf = log_buf;
8448 	prog->log_size = log_size;
8449 	return 0;
8450 }
8451 
8452 #define SEC_DEF(sec_pfx, ptype, atype, flags, ...) {			    \
8453 	.sec = (char *)sec_pfx,						    \
8454 	.prog_type = BPF_PROG_TYPE_##ptype,				    \
8455 	.expected_attach_type = atype,					    \
8456 	.cookie = (long)(flags),					    \
8457 	.prog_prepare_load_fn = libbpf_prepare_prog_load,		    \
8458 	__VA_ARGS__							    \
8459 }
8460 
8461 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8462 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8463 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8464 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8465 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8466 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8467 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8468 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8469 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8470 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link);
8471 
8472 static const struct bpf_sec_def section_defs[] = {
8473 	SEC_DEF("socket",		SOCKET_FILTER, 0, SEC_NONE),
8474 	SEC_DEF("sk_reuseport/migrate",	SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT_OR_MIGRATE, SEC_ATTACHABLE),
8475 	SEC_DEF("sk_reuseport",		SK_REUSEPORT, BPF_SK_REUSEPORT_SELECT, SEC_ATTACHABLE),
8476 	SEC_DEF("kprobe+",		KPROBE,	0, SEC_NONE, attach_kprobe),
8477 	SEC_DEF("uprobe+",		KPROBE,	0, SEC_NONE, attach_uprobe),
8478 	SEC_DEF("uprobe.s+",		KPROBE,	0, SEC_SLEEPABLE, attach_uprobe),
8479 	SEC_DEF("kretprobe+",		KPROBE, 0, SEC_NONE, attach_kprobe),
8480 	SEC_DEF("uretprobe+",		KPROBE, 0, SEC_NONE, attach_uprobe),
8481 	SEC_DEF("uretprobe.s+",		KPROBE, 0, SEC_SLEEPABLE, attach_uprobe),
8482 	SEC_DEF("kprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
8483 	SEC_DEF("kretprobe.multi+",	KPROBE,	BPF_TRACE_KPROBE_MULTI, SEC_NONE, attach_kprobe_multi),
8484 	SEC_DEF("ksyscall+",		KPROBE,	0, SEC_NONE, attach_ksyscall),
8485 	SEC_DEF("kretsyscall+",		KPROBE, 0, SEC_NONE, attach_ksyscall),
8486 	SEC_DEF("usdt+",		KPROBE,	0, SEC_NONE, attach_usdt),
8487 	SEC_DEF("tc",			SCHED_CLS, 0, SEC_NONE),
8488 	SEC_DEF("classifier",		SCHED_CLS, 0, SEC_NONE),
8489 	SEC_DEF("action",		SCHED_ACT, 0, SEC_NONE),
8490 	SEC_DEF("tracepoint+",		TRACEPOINT, 0, SEC_NONE, attach_tp),
8491 	SEC_DEF("tp+",			TRACEPOINT, 0, SEC_NONE, attach_tp),
8492 	SEC_DEF("raw_tracepoint+",	RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
8493 	SEC_DEF("raw_tp+",		RAW_TRACEPOINT, 0, SEC_NONE, attach_raw_tp),
8494 	SEC_DEF("raw_tracepoint.w+",	RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
8495 	SEC_DEF("raw_tp.w+",		RAW_TRACEPOINT_WRITABLE, 0, SEC_NONE, attach_raw_tp),
8496 	SEC_DEF("tp_btf+",		TRACING, BPF_TRACE_RAW_TP, SEC_ATTACH_BTF, attach_trace),
8497 	SEC_DEF("fentry+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF, attach_trace),
8498 	SEC_DEF("fmod_ret+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF, attach_trace),
8499 	SEC_DEF("fexit+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF, attach_trace),
8500 	SEC_DEF("fentry.s+",		TRACING, BPF_TRACE_FENTRY, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8501 	SEC_DEF("fmod_ret.s+",		TRACING, BPF_MODIFY_RETURN, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8502 	SEC_DEF("fexit.s+",		TRACING, BPF_TRACE_FEXIT, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_trace),
8503 	SEC_DEF("freplace+",		EXT, 0, SEC_ATTACH_BTF, attach_trace),
8504 	SEC_DEF("lsm+",			LSM, BPF_LSM_MAC, SEC_ATTACH_BTF, attach_lsm),
8505 	SEC_DEF("lsm.s+",		LSM, BPF_LSM_MAC, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_lsm),
8506 	SEC_DEF("lsm_cgroup+",		LSM, BPF_LSM_CGROUP, SEC_ATTACH_BTF),
8507 	SEC_DEF("iter+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF, attach_iter),
8508 	SEC_DEF("iter.s+",		TRACING, BPF_TRACE_ITER, SEC_ATTACH_BTF | SEC_SLEEPABLE, attach_iter),
8509 	SEC_DEF("syscall",		SYSCALL, 0, SEC_SLEEPABLE),
8510 	SEC_DEF("xdp.frags/devmap",	XDP, BPF_XDP_DEVMAP, SEC_XDP_FRAGS),
8511 	SEC_DEF("xdp/devmap",		XDP, BPF_XDP_DEVMAP, SEC_ATTACHABLE),
8512 	SEC_DEF("xdp.frags/cpumap",	XDP, BPF_XDP_CPUMAP, SEC_XDP_FRAGS),
8513 	SEC_DEF("xdp/cpumap",		XDP, BPF_XDP_CPUMAP, SEC_ATTACHABLE),
8514 	SEC_DEF("xdp.frags",		XDP, BPF_XDP, SEC_XDP_FRAGS),
8515 	SEC_DEF("xdp",			XDP, BPF_XDP, SEC_ATTACHABLE_OPT),
8516 	SEC_DEF("perf_event",		PERF_EVENT, 0, SEC_NONE),
8517 	SEC_DEF("lwt_in",		LWT_IN, 0, SEC_NONE),
8518 	SEC_DEF("lwt_out",		LWT_OUT, 0, SEC_NONE),
8519 	SEC_DEF("lwt_xmit",		LWT_XMIT, 0, SEC_NONE),
8520 	SEC_DEF("lwt_seg6local",	LWT_SEG6LOCAL, 0, SEC_NONE),
8521 	SEC_DEF("sockops",		SOCK_OPS, BPF_CGROUP_SOCK_OPS, SEC_ATTACHABLE_OPT),
8522 	SEC_DEF("sk_skb/stream_parser",	SK_SKB, BPF_SK_SKB_STREAM_PARSER, SEC_ATTACHABLE_OPT),
8523 	SEC_DEF("sk_skb/stream_verdict",SK_SKB, BPF_SK_SKB_STREAM_VERDICT, SEC_ATTACHABLE_OPT),
8524 	SEC_DEF("sk_skb",		SK_SKB, 0, SEC_NONE),
8525 	SEC_DEF("sk_msg",		SK_MSG, BPF_SK_MSG_VERDICT, SEC_ATTACHABLE_OPT),
8526 	SEC_DEF("lirc_mode2",		LIRC_MODE2, BPF_LIRC_MODE2, SEC_ATTACHABLE_OPT),
8527 	SEC_DEF("flow_dissector",	FLOW_DISSECTOR, BPF_FLOW_DISSECTOR, SEC_ATTACHABLE_OPT),
8528 	SEC_DEF("cgroup_skb/ingress",	CGROUP_SKB, BPF_CGROUP_INET_INGRESS, SEC_ATTACHABLE_OPT),
8529 	SEC_DEF("cgroup_skb/egress",	CGROUP_SKB, BPF_CGROUP_INET_EGRESS, SEC_ATTACHABLE_OPT),
8530 	SEC_DEF("cgroup/skb",		CGROUP_SKB, 0, SEC_NONE),
8531 	SEC_DEF("cgroup/sock_create",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE),
8532 	SEC_DEF("cgroup/sock_release",	CGROUP_SOCK, BPF_CGROUP_INET_SOCK_RELEASE, SEC_ATTACHABLE),
8533 	SEC_DEF("cgroup/sock",		CGROUP_SOCK, BPF_CGROUP_INET_SOCK_CREATE, SEC_ATTACHABLE_OPT),
8534 	SEC_DEF("cgroup/post_bind4",	CGROUP_SOCK, BPF_CGROUP_INET4_POST_BIND, SEC_ATTACHABLE),
8535 	SEC_DEF("cgroup/post_bind6",	CGROUP_SOCK, BPF_CGROUP_INET6_POST_BIND, SEC_ATTACHABLE),
8536 	SEC_DEF("cgroup/bind4",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_BIND, SEC_ATTACHABLE),
8537 	SEC_DEF("cgroup/bind6",		CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_BIND, SEC_ATTACHABLE),
8538 	SEC_DEF("cgroup/connect4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_CONNECT, SEC_ATTACHABLE),
8539 	SEC_DEF("cgroup/connect6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_CONNECT, SEC_ATTACHABLE),
8540 	SEC_DEF("cgroup/sendmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_SENDMSG, SEC_ATTACHABLE),
8541 	SEC_DEF("cgroup/sendmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_SENDMSG, SEC_ATTACHABLE),
8542 	SEC_DEF("cgroup/recvmsg4",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP4_RECVMSG, SEC_ATTACHABLE),
8543 	SEC_DEF("cgroup/recvmsg6",	CGROUP_SOCK_ADDR, BPF_CGROUP_UDP6_RECVMSG, SEC_ATTACHABLE),
8544 	SEC_DEF("cgroup/getpeername4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETPEERNAME, SEC_ATTACHABLE),
8545 	SEC_DEF("cgroup/getpeername6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETPEERNAME, SEC_ATTACHABLE),
8546 	SEC_DEF("cgroup/getsockname4",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET4_GETSOCKNAME, SEC_ATTACHABLE),
8547 	SEC_DEF("cgroup/getsockname6",	CGROUP_SOCK_ADDR, BPF_CGROUP_INET6_GETSOCKNAME, SEC_ATTACHABLE),
8548 	SEC_DEF("cgroup/sysctl",	CGROUP_SYSCTL, BPF_CGROUP_SYSCTL, SEC_ATTACHABLE),
8549 	SEC_DEF("cgroup/getsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_GETSOCKOPT, SEC_ATTACHABLE),
8550 	SEC_DEF("cgroup/setsockopt",	CGROUP_SOCKOPT, BPF_CGROUP_SETSOCKOPT, SEC_ATTACHABLE),
8551 	SEC_DEF("cgroup/dev",		CGROUP_DEVICE, BPF_CGROUP_DEVICE, SEC_ATTACHABLE_OPT),
8552 	SEC_DEF("struct_ops+",		STRUCT_OPS, 0, SEC_NONE),
8553 	SEC_DEF("sk_lookup",		SK_LOOKUP, BPF_SK_LOOKUP, SEC_ATTACHABLE),
8554 };
8555 
8556 static size_t custom_sec_def_cnt;
8557 static struct bpf_sec_def *custom_sec_defs;
8558 static struct bpf_sec_def custom_fallback_def;
8559 static bool has_custom_fallback_def;
8560 
8561 static int last_custom_sec_def_handler_id;
8562 
8563 int libbpf_register_prog_handler(const char *sec,
8564 				 enum bpf_prog_type prog_type,
8565 				 enum bpf_attach_type exp_attach_type,
8566 				 const struct libbpf_prog_handler_opts *opts)
8567 {
8568 	struct bpf_sec_def *sec_def;
8569 
8570 	if (!OPTS_VALID(opts, libbpf_prog_handler_opts))
8571 		return libbpf_err(-EINVAL);
8572 
8573 	if (last_custom_sec_def_handler_id == INT_MAX) /* prevent overflow */
8574 		return libbpf_err(-E2BIG);
8575 
8576 	if (sec) {
8577 		sec_def = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt + 1,
8578 					      sizeof(*sec_def));
8579 		if (!sec_def)
8580 			return libbpf_err(-ENOMEM);
8581 
8582 		custom_sec_defs = sec_def;
8583 		sec_def = &custom_sec_defs[custom_sec_def_cnt];
8584 	} else {
8585 		if (has_custom_fallback_def)
8586 			return libbpf_err(-EBUSY);
8587 
8588 		sec_def = &custom_fallback_def;
8589 	}
8590 
8591 	sec_def->sec = sec ? strdup(sec) : NULL;
8592 	if (sec && !sec_def->sec)
8593 		return libbpf_err(-ENOMEM);
8594 
8595 	sec_def->prog_type = prog_type;
8596 	sec_def->expected_attach_type = exp_attach_type;
8597 	sec_def->cookie = OPTS_GET(opts, cookie, 0);
8598 
8599 	sec_def->prog_setup_fn = OPTS_GET(opts, prog_setup_fn, NULL);
8600 	sec_def->prog_prepare_load_fn = OPTS_GET(opts, prog_prepare_load_fn, NULL);
8601 	sec_def->prog_attach_fn = OPTS_GET(opts, prog_attach_fn, NULL);
8602 
8603 	sec_def->handler_id = ++last_custom_sec_def_handler_id;
8604 
8605 	if (sec)
8606 		custom_sec_def_cnt++;
8607 	else
8608 		has_custom_fallback_def = true;
8609 
8610 	return sec_def->handler_id;
8611 }
8612 
8613 int libbpf_unregister_prog_handler(int handler_id)
8614 {
8615 	struct bpf_sec_def *sec_defs;
8616 	int i;
8617 
8618 	if (handler_id <= 0)
8619 		return libbpf_err(-EINVAL);
8620 
8621 	if (has_custom_fallback_def && custom_fallback_def.handler_id == handler_id) {
8622 		memset(&custom_fallback_def, 0, sizeof(custom_fallback_def));
8623 		has_custom_fallback_def = false;
8624 		return 0;
8625 	}
8626 
8627 	for (i = 0; i < custom_sec_def_cnt; i++) {
8628 		if (custom_sec_defs[i].handler_id == handler_id)
8629 			break;
8630 	}
8631 
8632 	if (i == custom_sec_def_cnt)
8633 		return libbpf_err(-ENOENT);
8634 
8635 	free(custom_sec_defs[i].sec);
8636 	for (i = i + 1; i < custom_sec_def_cnt; i++)
8637 		custom_sec_defs[i - 1] = custom_sec_defs[i];
8638 	custom_sec_def_cnt--;
8639 
8640 	/* try to shrink the array, but it's ok if we couldn't */
8641 	sec_defs = libbpf_reallocarray(custom_sec_defs, custom_sec_def_cnt, sizeof(*sec_defs));
8642 	if (sec_defs)
8643 		custom_sec_defs = sec_defs;
8644 
8645 	return 0;
8646 }
8647 
8648 static bool sec_def_matches(const struct bpf_sec_def *sec_def, const char *sec_name)
8649 {
8650 	size_t len = strlen(sec_def->sec);
8651 
8652 	/* "type/" always has to have proper SEC("type/extras") form */
8653 	if (sec_def->sec[len - 1] == '/') {
8654 		if (str_has_pfx(sec_name, sec_def->sec))
8655 			return true;
8656 		return false;
8657 	}
8658 
8659 	/* "type+" means it can be either exact SEC("type") or
8660 	 * well-formed SEC("type/extras") with proper '/' separator
8661 	 */
8662 	if (sec_def->sec[len - 1] == '+') {
8663 		len--;
8664 		/* not even a prefix */
8665 		if (strncmp(sec_name, sec_def->sec, len) != 0)
8666 			return false;
8667 		/* exact match or has '/' separator */
8668 		if (sec_name[len] == '\0' || sec_name[len] == '/')
8669 			return true;
8670 		return false;
8671 	}
8672 
8673 	return strcmp(sec_name, sec_def->sec) == 0;
8674 }
8675 
8676 static const struct bpf_sec_def *find_sec_def(const char *sec_name)
8677 {
8678 	const struct bpf_sec_def *sec_def;
8679 	int i, n;
8680 
8681 	n = custom_sec_def_cnt;
8682 	for (i = 0; i < n; i++) {
8683 		sec_def = &custom_sec_defs[i];
8684 		if (sec_def_matches(sec_def, sec_name))
8685 			return sec_def;
8686 	}
8687 
8688 	n = ARRAY_SIZE(section_defs);
8689 	for (i = 0; i < n; i++) {
8690 		sec_def = &section_defs[i];
8691 		if (sec_def_matches(sec_def, sec_name))
8692 			return sec_def;
8693 	}
8694 
8695 	if (has_custom_fallback_def)
8696 		return &custom_fallback_def;
8697 
8698 	return NULL;
8699 }
8700 
8701 #define MAX_TYPE_NAME_SIZE 32
8702 
8703 static char *libbpf_get_type_names(bool attach_type)
8704 {
8705 	int i, len = ARRAY_SIZE(section_defs) * MAX_TYPE_NAME_SIZE;
8706 	char *buf;
8707 
8708 	buf = malloc(len);
8709 	if (!buf)
8710 		return NULL;
8711 
8712 	buf[0] = '\0';
8713 	/* Forge string buf with all available names */
8714 	for (i = 0; i < ARRAY_SIZE(section_defs); i++) {
8715 		const struct bpf_sec_def *sec_def = &section_defs[i];
8716 
8717 		if (attach_type) {
8718 			if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
8719 				continue;
8720 
8721 			if (!(sec_def->cookie & SEC_ATTACHABLE))
8722 				continue;
8723 		}
8724 
8725 		if (strlen(buf) + strlen(section_defs[i].sec) + 2 > len) {
8726 			free(buf);
8727 			return NULL;
8728 		}
8729 		strcat(buf, " ");
8730 		strcat(buf, section_defs[i].sec);
8731 	}
8732 
8733 	return buf;
8734 }
8735 
8736 int libbpf_prog_type_by_name(const char *name, enum bpf_prog_type *prog_type,
8737 			     enum bpf_attach_type *expected_attach_type)
8738 {
8739 	const struct bpf_sec_def *sec_def;
8740 	char *type_names;
8741 
8742 	if (!name)
8743 		return libbpf_err(-EINVAL);
8744 
8745 	sec_def = find_sec_def(name);
8746 	if (sec_def) {
8747 		*prog_type = sec_def->prog_type;
8748 		*expected_attach_type = sec_def->expected_attach_type;
8749 		return 0;
8750 	}
8751 
8752 	pr_debug("failed to guess program type from ELF section '%s'\n", name);
8753 	type_names = libbpf_get_type_names(false);
8754 	if (type_names != NULL) {
8755 		pr_debug("supported section(type) names are:%s\n", type_names);
8756 		free(type_names);
8757 	}
8758 
8759 	return libbpf_err(-ESRCH);
8760 }
8761 
8762 const char *libbpf_bpf_attach_type_str(enum bpf_attach_type t)
8763 {
8764 	if (t < 0 || t >= ARRAY_SIZE(attach_type_name))
8765 		return NULL;
8766 
8767 	return attach_type_name[t];
8768 }
8769 
8770 const char *libbpf_bpf_link_type_str(enum bpf_link_type t)
8771 {
8772 	if (t < 0 || t >= ARRAY_SIZE(link_type_name))
8773 		return NULL;
8774 
8775 	return link_type_name[t];
8776 }
8777 
8778 const char *libbpf_bpf_map_type_str(enum bpf_map_type t)
8779 {
8780 	if (t < 0 || t >= ARRAY_SIZE(map_type_name))
8781 		return NULL;
8782 
8783 	return map_type_name[t];
8784 }
8785 
8786 const char *libbpf_bpf_prog_type_str(enum bpf_prog_type t)
8787 {
8788 	if (t < 0 || t >= ARRAY_SIZE(prog_type_name))
8789 		return NULL;
8790 
8791 	return prog_type_name[t];
8792 }
8793 
8794 static struct bpf_map *find_struct_ops_map_by_offset(struct bpf_object *obj,
8795 						     size_t offset)
8796 {
8797 	struct bpf_map *map;
8798 	size_t i;
8799 
8800 	for (i = 0; i < obj->nr_maps; i++) {
8801 		map = &obj->maps[i];
8802 		if (!bpf_map__is_struct_ops(map))
8803 			continue;
8804 		if (map->sec_offset <= offset &&
8805 		    offset - map->sec_offset < map->def.value_size)
8806 			return map;
8807 	}
8808 
8809 	return NULL;
8810 }
8811 
8812 /* Collect the reloc from ELF and populate the st_ops->progs[] */
8813 static int bpf_object__collect_st_ops_relos(struct bpf_object *obj,
8814 					    Elf64_Shdr *shdr, Elf_Data *data)
8815 {
8816 	const struct btf_member *member;
8817 	struct bpf_struct_ops *st_ops;
8818 	struct bpf_program *prog;
8819 	unsigned int shdr_idx;
8820 	const struct btf *btf;
8821 	struct bpf_map *map;
8822 	unsigned int moff, insn_idx;
8823 	const char *name;
8824 	__u32 member_idx;
8825 	Elf64_Sym *sym;
8826 	Elf64_Rel *rel;
8827 	int i, nrels;
8828 
8829 	btf = obj->btf;
8830 	nrels = shdr->sh_size / shdr->sh_entsize;
8831 	for (i = 0; i < nrels; i++) {
8832 		rel = elf_rel_by_idx(data, i);
8833 		if (!rel) {
8834 			pr_warn("struct_ops reloc: failed to get %d reloc\n", i);
8835 			return -LIBBPF_ERRNO__FORMAT;
8836 		}
8837 
8838 		sym = elf_sym_by_idx(obj, ELF64_R_SYM(rel->r_info));
8839 		if (!sym) {
8840 			pr_warn("struct_ops reloc: symbol %zx not found\n",
8841 				(size_t)ELF64_R_SYM(rel->r_info));
8842 			return -LIBBPF_ERRNO__FORMAT;
8843 		}
8844 
8845 		name = elf_sym_str(obj, sym->st_name) ?: "<?>";
8846 		map = find_struct_ops_map_by_offset(obj, rel->r_offset);
8847 		if (!map) {
8848 			pr_warn("struct_ops reloc: cannot find map at rel->r_offset %zu\n",
8849 				(size_t)rel->r_offset);
8850 			return -EINVAL;
8851 		}
8852 
8853 		moff = rel->r_offset - map->sec_offset;
8854 		shdr_idx = sym->st_shndx;
8855 		st_ops = map->st_ops;
8856 		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",
8857 			 map->name,
8858 			 (long long)(rel->r_info >> 32),
8859 			 (long long)sym->st_value,
8860 			 shdr_idx, (size_t)rel->r_offset,
8861 			 map->sec_offset, sym->st_name, name);
8862 
8863 		if (shdr_idx >= SHN_LORESERVE) {
8864 			pr_warn("struct_ops reloc %s: rel->r_offset %zu shdr_idx %u unsupported non-static function\n",
8865 				map->name, (size_t)rel->r_offset, shdr_idx);
8866 			return -LIBBPF_ERRNO__RELOC;
8867 		}
8868 		if (sym->st_value % BPF_INSN_SZ) {
8869 			pr_warn("struct_ops reloc %s: invalid target program offset %llu\n",
8870 				map->name, (unsigned long long)sym->st_value);
8871 			return -LIBBPF_ERRNO__FORMAT;
8872 		}
8873 		insn_idx = sym->st_value / BPF_INSN_SZ;
8874 
8875 		member = find_member_by_offset(st_ops->type, moff * 8);
8876 		if (!member) {
8877 			pr_warn("struct_ops reloc %s: cannot find member at moff %u\n",
8878 				map->name, moff);
8879 			return -EINVAL;
8880 		}
8881 		member_idx = member - btf_members(st_ops->type);
8882 		name = btf__name_by_offset(btf, member->name_off);
8883 
8884 		if (!resolve_func_ptr(btf, member->type, NULL)) {
8885 			pr_warn("struct_ops reloc %s: cannot relocate non func ptr %s\n",
8886 				map->name, name);
8887 			return -EINVAL;
8888 		}
8889 
8890 		prog = find_prog_by_sec_insn(obj, shdr_idx, insn_idx);
8891 		if (!prog) {
8892 			pr_warn("struct_ops reloc %s: cannot find prog at shdr_idx %u to relocate func ptr %s\n",
8893 				map->name, shdr_idx, name);
8894 			return -EINVAL;
8895 		}
8896 
8897 		/* prevent the use of BPF prog with invalid type */
8898 		if (prog->type != BPF_PROG_TYPE_STRUCT_OPS) {
8899 			pr_warn("struct_ops reloc %s: prog %s is not struct_ops BPF program\n",
8900 				map->name, prog->name);
8901 			return -EINVAL;
8902 		}
8903 
8904 		/* if we haven't yet processed this BPF program, record proper
8905 		 * attach_btf_id and member_idx
8906 		 */
8907 		if (!prog->attach_btf_id) {
8908 			prog->attach_btf_id = st_ops->type_id;
8909 			prog->expected_attach_type = member_idx;
8910 		}
8911 
8912 		/* struct_ops BPF prog can be re-used between multiple
8913 		 * .struct_ops as long as it's the same struct_ops struct
8914 		 * definition and the same function pointer field
8915 		 */
8916 		if (prog->attach_btf_id != st_ops->type_id ||
8917 		    prog->expected_attach_type != member_idx) {
8918 			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",
8919 				map->name, prog->name, prog->sec_name, prog->type,
8920 				prog->attach_btf_id, prog->expected_attach_type, name);
8921 			return -EINVAL;
8922 		}
8923 
8924 		st_ops->progs[member_idx] = prog;
8925 	}
8926 
8927 	return 0;
8928 }
8929 
8930 #define BTF_TRACE_PREFIX "btf_trace_"
8931 #define BTF_LSM_PREFIX "bpf_lsm_"
8932 #define BTF_ITER_PREFIX "bpf_iter_"
8933 #define BTF_MAX_NAME_SIZE 128
8934 
8935 void btf_get_kernel_prefix_kind(enum bpf_attach_type attach_type,
8936 				const char **prefix, int *kind)
8937 {
8938 	switch (attach_type) {
8939 	case BPF_TRACE_RAW_TP:
8940 		*prefix = BTF_TRACE_PREFIX;
8941 		*kind = BTF_KIND_TYPEDEF;
8942 		break;
8943 	case BPF_LSM_MAC:
8944 	case BPF_LSM_CGROUP:
8945 		*prefix = BTF_LSM_PREFIX;
8946 		*kind = BTF_KIND_FUNC;
8947 		break;
8948 	case BPF_TRACE_ITER:
8949 		*prefix = BTF_ITER_PREFIX;
8950 		*kind = BTF_KIND_FUNC;
8951 		break;
8952 	default:
8953 		*prefix = "";
8954 		*kind = BTF_KIND_FUNC;
8955 	}
8956 }
8957 
8958 static int find_btf_by_prefix_kind(const struct btf *btf, const char *prefix,
8959 				   const char *name, __u32 kind)
8960 {
8961 	char btf_type_name[BTF_MAX_NAME_SIZE];
8962 	int ret;
8963 
8964 	ret = snprintf(btf_type_name, sizeof(btf_type_name),
8965 		       "%s%s", prefix, name);
8966 	/* snprintf returns the number of characters written excluding the
8967 	 * terminating null. So, if >= BTF_MAX_NAME_SIZE are written, it
8968 	 * indicates truncation.
8969 	 */
8970 	if (ret < 0 || ret >= sizeof(btf_type_name))
8971 		return -ENAMETOOLONG;
8972 	return btf__find_by_name_kind(btf, btf_type_name, kind);
8973 }
8974 
8975 static inline int find_attach_btf_id(struct btf *btf, const char *name,
8976 				     enum bpf_attach_type attach_type)
8977 {
8978 	const char *prefix;
8979 	int kind;
8980 
8981 	btf_get_kernel_prefix_kind(attach_type, &prefix, &kind);
8982 	return find_btf_by_prefix_kind(btf, prefix, name, kind);
8983 }
8984 
8985 int libbpf_find_vmlinux_btf_id(const char *name,
8986 			       enum bpf_attach_type attach_type)
8987 {
8988 	struct btf *btf;
8989 	int err;
8990 
8991 	btf = btf__load_vmlinux_btf();
8992 	err = libbpf_get_error(btf);
8993 	if (err) {
8994 		pr_warn("vmlinux BTF is not found\n");
8995 		return libbpf_err(err);
8996 	}
8997 
8998 	err = find_attach_btf_id(btf, name, attach_type);
8999 	if (err <= 0)
9000 		pr_warn("%s is not found in vmlinux BTF\n", name);
9001 
9002 	btf__free(btf);
9003 	return libbpf_err(err);
9004 }
9005 
9006 static int libbpf_find_prog_btf_id(const char *name, __u32 attach_prog_fd)
9007 {
9008 	struct bpf_prog_info info;
9009 	__u32 info_len = sizeof(info);
9010 	struct btf *btf;
9011 	int err;
9012 
9013 	memset(&info, 0, info_len);
9014 	err = bpf_obj_get_info_by_fd(attach_prog_fd, &info, &info_len);
9015 	if (err) {
9016 		pr_warn("failed bpf_obj_get_info_by_fd for FD %d: %d\n",
9017 			attach_prog_fd, err);
9018 		return err;
9019 	}
9020 
9021 	err = -EINVAL;
9022 	if (!info.btf_id) {
9023 		pr_warn("The target program doesn't have BTF\n");
9024 		goto out;
9025 	}
9026 	btf = btf__load_from_kernel_by_id(info.btf_id);
9027 	err = libbpf_get_error(btf);
9028 	if (err) {
9029 		pr_warn("Failed to get BTF %d of the program: %d\n", info.btf_id, err);
9030 		goto out;
9031 	}
9032 	err = btf__find_by_name_kind(btf, name, BTF_KIND_FUNC);
9033 	btf__free(btf);
9034 	if (err <= 0) {
9035 		pr_warn("%s is not found in prog's BTF\n", name);
9036 		goto out;
9037 	}
9038 out:
9039 	return err;
9040 }
9041 
9042 static int find_kernel_btf_id(struct bpf_object *obj, const char *attach_name,
9043 			      enum bpf_attach_type attach_type,
9044 			      int *btf_obj_fd, int *btf_type_id)
9045 {
9046 	int ret, i;
9047 
9048 	ret = find_attach_btf_id(obj->btf_vmlinux, attach_name, attach_type);
9049 	if (ret > 0) {
9050 		*btf_obj_fd = 0; /* vmlinux BTF */
9051 		*btf_type_id = ret;
9052 		return 0;
9053 	}
9054 	if (ret != -ENOENT)
9055 		return ret;
9056 
9057 	ret = load_module_btfs(obj);
9058 	if (ret)
9059 		return ret;
9060 
9061 	for (i = 0; i < obj->btf_module_cnt; i++) {
9062 		const struct module_btf *mod = &obj->btf_modules[i];
9063 
9064 		ret = find_attach_btf_id(mod->btf, attach_name, attach_type);
9065 		if (ret > 0) {
9066 			*btf_obj_fd = mod->fd;
9067 			*btf_type_id = ret;
9068 			return 0;
9069 		}
9070 		if (ret == -ENOENT)
9071 			continue;
9072 
9073 		return ret;
9074 	}
9075 
9076 	return -ESRCH;
9077 }
9078 
9079 static int libbpf_find_attach_btf_id(struct bpf_program *prog, const char *attach_name,
9080 				     int *btf_obj_fd, int *btf_type_id)
9081 {
9082 	enum bpf_attach_type attach_type = prog->expected_attach_type;
9083 	__u32 attach_prog_fd = prog->attach_prog_fd;
9084 	int err = 0;
9085 
9086 	/* BPF program's BTF ID */
9087 	if (attach_prog_fd) {
9088 		err = libbpf_find_prog_btf_id(attach_name, attach_prog_fd);
9089 		if (err < 0) {
9090 			pr_warn("failed to find BPF program (FD %d) BTF ID for '%s': %d\n",
9091 				 attach_prog_fd, attach_name, err);
9092 			return err;
9093 		}
9094 		*btf_obj_fd = 0;
9095 		*btf_type_id = err;
9096 		return 0;
9097 	}
9098 
9099 	/* kernel/module BTF ID */
9100 	if (prog->obj->gen_loader) {
9101 		bpf_gen__record_attach_target(prog->obj->gen_loader, attach_name, attach_type);
9102 		*btf_obj_fd = 0;
9103 		*btf_type_id = 1;
9104 	} else {
9105 		err = find_kernel_btf_id(prog->obj, attach_name, attach_type, btf_obj_fd, btf_type_id);
9106 	}
9107 	if (err) {
9108 		pr_warn("failed to find kernel BTF type ID of '%s': %d\n", attach_name, err);
9109 		return err;
9110 	}
9111 	return 0;
9112 }
9113 
9114 int libbpf_attach_type_by_name(const char *name,
9115 			       enum bpf_attach_type *attach_type)
9116 {
9117 	char *type_names;
9118 	const struct bpf_sec_def *sec_def;
9119 
9120 	if (!name)
9121 		return libbpf_err(-EINVAL);
9122 
9123 	sec_def = find_sec_def(name);
9124 	if (!sec_def) {
9125 		pr_debug("failed to guess attach type based on ELF section name '%s'\n", name);
9126 		type_names = libbpf_get_type_names(true);
9127 		if (type_names != NULL) {
9128 			pr_debug("attachable section(type) names are:%s\n", type_names);
9129 			free(type_names);
9130 		}
9131 
9132 		return libbpf_err(-EINVAL);
9133 	}
9134 
9135 	if (sec_def->prog_prepare_load_fn != libbpf_prepare_prog_load)
9136 		return libbpf_err(-EINVAL);
9137 	if (!(sec_def->cookie & SEC_ATTACHABLE))
9138 		return libbpf_err(-EINVAL);
9139 
9140 	*attach_type = sec_def->expected_attach_type;
9141 	return 0;
9142 }
9143 
9144 int bpf_map__fd(const struct bpf_map *map)
9145 {
9146 	return map ? map->fd : libbpf_err(-EINVAL);
9147 }
9148 
9149 static bool map_uses_real_name(const struct bpf_map *map)
9150 {
9151 	/* Since libbpf started to support custom .data.* and .rodata.* maps,
9152 	 * their user-visible name differs from kernel-visible name. Users see
9153 	 * such map's corresponding ELF section name as a map name.
9154 	 * This check distinguishes .data/.rodata from .data.* and .rodata.*
9155 	 * maps to know which name has to be returned to the user.
9156 	 */
9157 	if (map->libbpf_type == LIBBPF_MAP_DATA && strcmp(map->real_name, DATA_SEC) != 0)
9158 		return true;
9159 	if (map->libbpf_type == LIBBPF_MAP_RODATA && strcmp(map->real_name, RODATA_SEC) != 0)
9160 		return true;
9161 	return false;
9162 }
9163 
9164 const char *bpf_map__name(const struct bpf_map *map)
9165 {
9166 	if (!map)
9167 		return NULL;
9168 
9169 	if (map_uses_real_name(map))
9170 		return map->real_name;
9171 
9172 	return map->name;
9173 }
9174 
9175 enum bpf_map_type bpf_map__type(const struct bpf_map *map)
9176 {
9177 	return map->def.type;
9178 }
9179 
9180 int bpf_map__set_type(struct bpf_map *map, enum bpf_map_type type)
9181 {
9182 	if (map->fd >= 0)
9183 		return libbpf_err(-EBUSY);
9184 	map->def.type = type;
9185 	return 0;
9186 }
9187 
9188 __u32 bpf_map__map_flags(const struct bpf_map *map)
9189 {
9190 	return map->def.map_flags;
9191 }
9192 
9193 int bpf_map__set_map_flags(struct bpf_map *map, __u32 flags)
9194 {
9195 	if (map->fd >= 0)
9196 		return libbpf_err(-EBUSY);
9197 	map->def.map_flags = flags;
9198 	return 0;
9199 }
9200 
9201 __u64 bpf_map__map_extra(const struct bpf_map *map)
9202 {
9203 	return map->map_extra;
9204 }
9205 
9206 int bpf_map__set_map_extra(struct bpf_map *map, __u64 map_extra)
9207 {
9208 	if (map->fd >= 0)
9209 		return libbpf_err(-EBUSY);
9210 	map->map_extra = map_extra;
9211 	return 0;
9212 }
9213 
9214 __u32 bpf_map__numa_node(const struct bpf_map *map)
9215 {
9216 	return map->numa_node;
9217 }
9218 
9219 int bpf_map__set_numa_node(struct bpf_map *map, __u32 numa_node)
9220 {
9221 	if (map->fd >= 0)
9222 		return libbpf_err(-EBUSY);
9223 	map->numa_node = numa_node;
9224 	return 0;
9225 }
9226 
9227 __u32 bpf_map__key_size(const struct bpf_map *map)
9228 {
9229 	return map->def.key_size;
9230 }
9231 
9232 int bpf_map__set_key_size(struct bpf_map *map, __u32 size)
9233 {
9234 	if (map->fd >= 0)
9235 		return libbpf_err(-EBUSY);
9236 	map->def.key_size = size;
9237 	return 0;
9238 }
9239 
9240 __u32 bpf_map__value_size(const struct bpf_map *map)
9241 {
9242 	return map->def.value_size;
9243 }
9244 
9245 int bpf_map__set_value_size(struct bpf_map *map, __u32 size)
9246 {
9247 	if (map->fd >= 0)
9248 		return libbpf_err(-EBUSY);
9249 	map->def.value_size = size;
9250 	return 0;
9251 }
9252 
9253 __u32 bpf_map__btf_key_type_id(const struct bpf_map *map)
9254 {
9255 	return map ? map->btf_key_type_id : 0;
9256 }
9257 
9258 __u32 bpf_map__btf_value_type_id(const struct bpf_map *map)
9259 {
9260 	return map ? map->btf_value_type_id : 0;
9261 }
9262 
9263 int bpf_map__set_initial_value(struct bpf_map *map,
9264 			       const void *data, size_t size)
9265 {
9266 	if (!map->mmaped || map->libbpf_type == LIBBPF_MAP_KCONFIG ||
9267 	    size != map->def.value_size || map->fd >= 0)
9268 		return libbpf_err(-EINVAL);
9269 
9270 	memcpy(map->mmaped, data, size);
9271 	return 0;
9272 }
9273 
9274 const void *bpf_map__initial_value(struct bpf_map *map, size_t *psize)
9275 {
9276 	if (!map->mmaped)
9277 		return NULL;
9278 	*psize = map->def.value_size;
9279 	return map->mmaped;
9280 }
9281 
9282 bool bpf_map__is_internal(const struct bpf_map *map)
9283 {
9284 	return map->libbpf_type != LIBBPF_MAP_UNSPEC;
9285 }
9286 
9287 __u32 bpf_map__ifindex(const struct bpf_map *map)
9288 {
9289 	return map->map_ifindex;
9290 }
9291 
9292 int bpf_map__set_ifindex(struct bpf_map *map, __u32 ifindex)
9293 {
9294 	if (map->fd >= 0)
9295 		return libbpf_err(-EBUSY);
9296 	map->map_ifindex = ifindex;
9297 	return 0;
9298 }
9299 
9300 int bpf_map__set_inner_map_fd(struct bpf_map *map, int fd)
9301 {
9302 	if (!bpf_map_type__is_map_in_map(map->def.type)) {
9303 		pr_warn("error: unsupported map type\n");
9304 		return libbpf_err(-EINVAL);
9305 	}
9306 	if (map->inner_map_fd != -1) {
9307 		pr_warn("error: inner_map_fd already specified\n");
9308 		return libbpf_err(-EINVAL);
9309 	}
9310 	if (map->inner_map) {
9311 		bpf_map__destroy(map->inner_map);
9312 		zfree(&map->inner_map);
9313 	}
9314 	map->inner_map_fd = fd;
9315 	return 0;
9316 }
9317 
9318 static struct bpf_map *
9319 __bpf_map__iter(const struct bpf_map *m, const struct bpf_object *obj, int i)
9320 {
9321 	ssize_t idx;
9322 	struct bpf_map *s, *e;
9323 
9324 	if (!obj || !obj->maps)
9325 		return errno = EINVAL, NULL;
9326 
9327 	s = obj->maps;
9328 	e = obj->maps + obj->nr_maps;
9329 
9330 	if ((m < s) || (m >= e)) {
9331 		pr_warn("error in %s: map handler doesn't belong to object\n",
9332 			 __func__);
9333 		return errno = EINVAL, NULL;
9334 	}
9335 
9336 	idx = (m - obj->maps) + i;
9337 	if (idx >= obj->nr_maps || idx < 0)
9338 		return NULL;
9339 	return &obj->maps[idx];
9340 }
9341 
9342 struct bpf_map *
9343 bpf_object__next_map(const struct bpf_object *obj, const struct bpf_map *prev)
9344 {
9345 	if (prev == NULL)
9346 		return obj->maps;
9347 
9348 	return __bpf_map__iter(prev, obj, 1);
9349 }
9350 
9351 struct bpf_map *
9352 bpf_object__prev_map(const struct bpf_object *obj, const struct bpf_map *next)
9353 {
9354 	if (next == NULL) {
9355 		if (!obj->nr_maps)
9356 			return NULL;
9357 		return obj->maps + obj->nr_maps - 1;
9358 	}
9359 
9360 	return __bpf_map__iter(next, obj, -1);
9361 }
9362 
9363 struct bpf_map *
9364 bpf_object__find_map_by_name(const struct bpf_object *obj, const char *name)
9365 {
9366 	struct bpf_map *pos;
9367 
9368 	bpf_object__for_each_map(pos, obj) {
9369 		/* if it's a special internal map name (which always starts
9370 		 * with dot) then check if that special name matches the
9371 		 * real map name (ELF section name)
9372 		 */
9373 		if (name[0] == '.') {
9374 			if (pos->real_name && strcmp(pos->real_name, name) == 0)
9375 				return pos;
9376 			continue;
9377 		}
9378 		/* otherwise map name has to be an exact match */
9379 		if (map_uses_real_name(pos)) {
9380 			if (strcmp(pos->real_name, name) == 0)
9381 				return pos;
9382 			continue;
9383 		}
9384 		if (strcmp(pos->name, name) == 0)
9385 			return pos;
9386 	}
9387 	return errno = ENOENT, NULL;
9388 }
9389 
9390 int
9391 bpf_object__find_map_fd_by_name(const struct bpf_object *obj, const char *name)
9392 {
9393 	return bpf_map__fd(bpf_object__find_map_by_name(obj, name));
9394 }
9395 
9396 static int validate_map_op(const struct bpf_map *map, size_t key_sz,
9397 			   size_t value_sz, bool check_value_sz)
9398 {
9399 	if (map->fd <= 0)
9400 		return -ENOENT;
9401 
9402 	if (map->def.key_size != key_sz) {
9403 		pr_warn("map '%s': unexpected key size %zu provided, expected %u\n",
9404 			map->name, key_sz, map->def.key_size);
9405 		return -EINVAL;
9406 	}
9407 
9408 	if (!check_value_sz)
9409 		return 0;
9410 
9411 	switch (map->def.type) {
9412 	case BPF_MAP_TYPE_PERCPU_ARRAY:
9413 	case BPF_MAP_TYPE_PERCPU_HASH:
9414 	case BPF_MAP_TYPE_LRU_PERCPU_HASH:
9415 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: {
9416 		int num_cpu = libbpf_num_possible_cpus();
9417 		size_t elem_sz = roundup(map->def.value_size, 8);
9418 
9419 		if (value_sz != num_cpu * elem_sz) {
9420 			pr_warn("map '%s': unexpected value size %zu provided for per-CPU map, expected %d * %zu = %zd\n",
9421 				map->name, value_sz, num_cpu, elem_sz, num_cpu * elem_sz);
9422 			return -EINVAL;
9423 		}
9424 		break;
9425 	}
9426 	default:
9427 		if (map->def.value_size != value_sz) {
9428 			pr_warn("map '%s': unexpected value size %zu provided, expected %u\n",
9429 				map->name, value_sz, map->def.value_size);
9430 			return -EINVAL;
9431 		}
9432 		break;
9433 	}
9434 	return 0;
9435 }
9436 
9437 int bpf_map__lookup_elem(const struct bpf_map *map,
9438 			 const void *key, size_t key_sz,
9439 			 void *value, size_t value_sz, __u64 flags)
9440 {
9441 	int err;
9442 
9443 	err = validate_map_op(map, key_sz, value_sz, true);
9444 	if (err)
9445 		return libbpf_err(err);
9446 
9447 	return bpf_map_lookup_elem_flags(map->fd, key, value, flags);
9448 }
9449 
9450 int bpf_map__update_elem(const struct bpf_map *map,
9451 			 const void *key, size_t key_sz,
9452 			 const void *value, size_t value_sz, __u64 flags)
9453 {
9454 	int err;
9455 
9456 	err = validate_map_op(map, key_sz, value_sz, true);
9457 	if (err)
9458 		return libbpf_err(err);
9459 
9460 	return bpf_map_update_elem(map->fd, key, value, flags);
9461 }
9462 
9463 int bpf_map__delete_elem(const struct bpf_map *map,
9464 			 const void *key, size_t key_sz, __u64 flags)
9465 {
9466 	int err;
9467 
9468 	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */);
9469 	if (err)
9470 		return libbpf_err(err);
9471 
9472 	return bpf_map_delete_elem_flags(map->fd, key, flags);
9473 }
9474 
9475 int bpf_map__lookup_and_delete_elem(const struct bpf_map *map,
9476 				    const void *key, size_t key_sz,
9477 				    void *value, size_t value_sz, __u64 flags)
9478 {
9479 	int err;
9480 
9481 	err = validate_map_op(map, key_sz, value_sz, true);
9482 	if (err)
9483 		return libbpf_err(err);
9484 
9485 	return bpf_map_lookup_and_delete_elem_flags(map->fd, key, value, flags);
9486 }
9487 
9488 int bpf_map__get_next_key(const struct bpf_map *map,
9489 			  const void *cur_key, void *next_key, size_t key_sz)
9490 {
9491 	int err;
9492 
9493 	err = validate_map_op(map, key_sz, 0, false /* check_value_sz */);
9494 	if (err)
9495 		return libbpf_err(err);
9496 
9497 	return bpf_map_get_next_key(map->fd, cur_key, next_key);
9498 }
9499 
9500 long libbpf_get_error(const void *ptr)
9501 {
9502 	if (!IS_ERR_OR_NULL(ptr))
9503 		return 0;
9504 
9505 	if (IS_ERR(ptr))
9506 		errno = -PTR_ERR(ptr);
9507 
9508 	/* If ptr == NULL, then errno should be already set by the failing
9509 	 * API, because libbpf never returns NULL on success and it now always
9510 	 * sets errno on error. So no extra errno handling for ptr == NULL
9511 	 * case.
9512 	 */
9513 	return -errno;
9514 }
9515 
9516 /* Replace link's underlying BPF program with the new one */
9517 int bpf_link__update_program(struct bpf_link *link, struct bpf_program *prog)
9518 {
9519 	int ret;
9520 
9521 	ret = bpf_link_update(bpf_link__fd(link), bpf_program__fd(prog), NULL);
9522 	return libbpf_err_errno(ret);
9523 }
9524 
9525 /* Release "ownership" of underlying BPF resource (typically, BPF program
9526  * attached to some BPF hook, e.g., tracepoint, kprobe, etc). Disconnected
9527  * link, when destructed through bpf_link__destroy() call won't attempt to
9528  * detach/unregisted that BPF resource. This is useful in situations where,
9529  * say, attached BPF program has to outlive userspace program that attached it
9530  * in the system. Depending on type of BPF program, though, there might be
9531  * additional steps (like pinning BPF program in BPF FS) necessary to ensure
9532  * exit of userspace program doesn't trigger automatic detachment and clean up
9533  * inside the kernel.
9534  */
9535 void bpf_link__disconnect(struct bpf_link *link)
9536 {
9537 	link->disconnected = true;
9538 }
9539 
9540 int bpf_link__destroy(struct bpf_link *link)
9541 {
9542 	int err = 0;
9543 
9544 	if (IS_ERR_OR_NULL(link))
9545 		return 0;
9546 
9547 	if (!link->disconnected && link->detach)
9548 		err = link->detach(link);
9549 	if (link->pin_path)
9550 		free(link->pin_path);
9551 	if (link->dealloc)
9552 		link->dealloc(link);
9553 	else
9554 		free(link);
9555 
9556 	return libbpf_err(err);
9557 }
9558 
9559 int bpf_link__fd(const struct bpf_link *link)
9560 {
9561 	return link->fd;
9562 }
9563 
9564 const char *bpf_link__pin_path(const struct bpf_link *link)
9565 {
9566 	return link->pin_path;
9567 }
9568 
9569 static int bpf_link__detach_fd(struct bpf_link *link)
9570 {
9571 	return libbpf_err_errno(close(link->fd));
9572 }
9573 
9574 struct bpf_link *bpf_link__open(const char *path)
9575 {
9576 	struct bpf_link *link;
9577 	int fd;
9578 
9579 	fd = bpf_obj_get(path);
9580 	if (fd < 0) {
9581 		fd = -errno;
9582 		pr_warn("failed to open link at %s: %d\n", path, fd);
9583 		return libbpf_err_ptr(fd);
9584 	}
9585 
9586 	link = calloc(1, sizeof(*link));
9587 	if (!link) {
9588 		close(fd);
9589 		return libbpf_err_ptr(-ENOMEM);
9590 	}
9591 	link->detach = &bpf_link__detach_fd;
9592 	link->fd = fd;
9593 
9594 	link->pin_path = strdup(path);
9595 	if (!link->pin_path) {
9596 		bpf_link__destroy(link);
9597 		return libbpf_err_ptr(-ENOMEM);
9598 	}
9599 
9600 	return link;
9601 }
9602 
9603 int bpf_link__detach(struct bpf_link *link)
9604 {
9605 	return bpf_link_detach(link->fd) ? -errno : 0;
9606 }
9607 
9608 int bpf_link__pin(struct bpf_link *link, const char *path)
9609 {
9610 	int err;
9611 
9612 	if (link->pin_path)
9613 		return libbpf_err(-EBUSY);
9614 	err = make_parent_dir(path);
9615 	if (err)
9616 		return libbpf_err(err);
9617 	err = check_path(path);
9618 	if (err)
9619 		return libbpf_err(err);
9620 
9621 	link->pin_path = strdup(path);
9622 	if (!link->pin_path)
9623 		return libbpf_err(-ENOMEM);
9624 
9625 	if (bpf_obj_pin(link->fd, link->pin_path)) {
9626 		err = -errno;
9627 		zfree(&link->pin_path);
9628 		return libbpf_err(err);
9629 	}
9630 
9631 	pr_debug("link fd=%d: pinned at %s\n", link->fd, link->pin_path);
9632 	return 0;
9633 }
9634 
9635 int bpf_link__unpin(struct bpf_link *link)
9636 {
9637 	int err;
9638 
9639 	if (!link->pin_path)
9640 		return libbpf_err(-EINVAL);
9641 
9642 	err = unlink(link->pin_path);
9643 	if (err != 0)
9644 		return -errno;
9645 
9646 	pr_debug("link fd=%d: unpinned from %s\n", link->fd, link->pin_path);
9647 	zfree(&link->pin_path);
9648 	return 0;
9649 }
9650 
9651 struct bpf_link_perf {
9652 	struct bpf_link link;
9653 	int perf_event_fd;
9654 	/* legacy kprobe support: keep track of probe identifier and type */
9655 	char *legacy_probe_name;
9656 	bool legacy_is_kprobe;
9657 	bool legacy_is_retprobe;
9658 };
9659 
9660 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe);
9661 static int remove_uprobe_event_legacy(const char *probe_name, bool retprobe);
9662 
9663 static int bpf_link_perf_detach(struct bpf_link *link)
9664 {
9665 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
9666 	int err = 0;
9667 
9668 	if (ioctl(perf_link->perf_event_fd, PERF_EVENT_IOC_DISABLE, 0) < 0)
9669 		err = -errno;
9670 
9671 	if (perf_link->perf_event_fd != link->fd)
9672 		close(perf_link->perf_event_fd);
9673 	close(link->fd);
9674 
9675 	/* legacy uprobe/kprobe needs to be removed after perf event fd closure */
9676 	if (perf_link->legacy_probe_name) {
9677 		if (perf_link->legacy_is_kprobe) {
9678 			err = remove_kprobe_event_legacy(perf_link->legacy_probe_name,
9679 							 perf_link->legacy_is_retprobe);
9680 		} else {
9681 			err = remove_uprobe_event_legacy(perf_link->legacy_probe_name,
9682 							 perf_link->legacy_is_retprobe);
9683 		}
9684 	}
9685 
9686 	return err;
9687 }
9688 
9689 static void bpf_link_perf_dealloc(struct bpf_link *link)
9690 {
9691 	struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
9692 
9693 	free(perf_link->legacy_probe_name);
9694 	free(perf_link);
9695 }
9696 
9697 struct bpf_link *bpf_program__attach_perf_event_opts(const struct bpf_program *prog, int pfd,
9698 						     const struct bpf_perf_event_opts *opts)
9699 {
9700 	char errmsg[STRERR_BUFSIZE];
9701 	struct bpf_link_perf *link;
9702 	int prog_fd, link_fd = -1, err;
9703 
9704 	if (!OPTS_VALID(opts, bpf_perf_event_opts))
9705 		return libbpf_err_ptr(-EINVAL);
9706 
9707 	if (pfd < 0) {
9708 		pr_warn("prog '%s': invalid perf event FD %d\n",
9709 			prog->name, pfd);
9710 		return libbpf_err_ptr(-EINVAL);
9711 	}
9712 	prog_fd = bpf_program__fd(prog);
9713 	if (prog_fd < 0) {
9714 		pr_warn("prog '%s': can't attach BPF program w/o FD (did you load it?)\n",
9715 			prog->name);
9716 		return libbpf_err_ptr(-EINVAL);
9717 	}
9718 
9719 	link = calloc(1, sizeof(*link));
9720 	if (!link)
9721 		return libbpf_err_ptr(-ENOMEM);
9722 	link->link.detach = &bpf_link_perf_detach;
9723 	link->link.dealloc = &bpf_link_perf_dealloc;
9724 	link->perf_event_fd = pfd;
9725 
9726 	if (kernel_supports(prog->obj, FEAT_PERF_LINK)) {
9727 		DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_opts,
9728 			.perf_event.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0));
9729 
9730 		link_fd = bpf_link_create(prog_fd, pfd, BPF_PERF_EVENT, &link_opts);
9731 		if (link_fd < 0) {
9732 			err = -errno;
9733 			pr_warn("prog '%s': failed to create BPF link for perf_event FD %d: %d (%s)\n",
9734 				prog->name, pfd,
9735 				err, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9736 			goto err_out;
9737 		}
9738 		link->link.fd = link_fd;
9739 	} else {
9740 		if (OPTS_GET(opts, bpf_cookie, 0)) {
9741 			pr_warn("prog '%s': user context value is not supported\n", prog->name);
9742 			err = -EOPNOTSUPP;
9743 			goto err_out;
9744 		}
9745 
9746 		if (ioctl(pfd, PERF_EVENT_IOC_SET_BPF, prog_fd) < 0) {
9747 			err = -errno;
9748 			pr_warn("prog '%s': failed to attach to perf_event FD %d: %s\n",
9749 				prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9750 			if (err == -EPROTO)
9751 				pr_warn("prog '%s': try add PERF_SAMPLE_CALLCHAIN to or remove exclude_callchain_[kernel|user] from pfd %d\n",
9752 					prog->name, pfd);
9753 			goto err_out;
9754 		}
9755 		link->link.fd = pfd;
9756 	}
9757 	if (ioctl(pfd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
9758 		err = -errno;
9759 		pr_warn("prog '%s': failed to enable perf_event FD %d: %s\n",
9760 			prog->name, pfd, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9761 		goto err_out;
9762 	}
9763 
9764 	return &link->link;
9765 err_out:
9766 	if (link_fd >= 0)
9767 		close(link_fd);
9768 	free(link);
9769 	return libbpf_err_ptr(err);
9770 }
9771 
9772 struct bpf_link *bpf_program__attach_perf_event(const struct bpf_program *prog, int pfd)
9773 {
9774 	return bpf_program__attach_perf_event_opts(prog, pfd, NULL);
9775 }
9776 
9777 /*
9778  * this function is expected to parse integer in the range of [0, 2^31-1] from
9779  * given file using scanf format string fmt. If actual parsed value is
9780  * negative, the result might be indistinguishable from error
9781  */
9782 static int parse_uint_from_file(const char *file, const char *fmt)
9783 {
9784 	char buf[STRERR_BUFSIZE];
9785 	int err, ret;
9786 	FILE *f;
9787 
9788 	f = fopen(file, "r");
9789 	if (!f) {
9790 		err = -errno;
9791 		pr_debug("failed to open '%s': %s\n", file,
9792 			 libbpf_strerror_r(err, buf, sizeof(buf)));
9793 		return err;
9794 	}
9795 	err = fscanf(f, fmt, &ret);
9796 	if (err != 1) {
9797 		err = err == EOF ? -EIO : -errno;
9798 		pr_debug("failed to parse '%s': %s\n", file,
9799 			libbpf_strerror_r(err, buf, sizeof(buf)));
9800 		fclose(f);
9801 		return err;
9802 	}
9803 	fclose(f);
9804 	return ret;
9805 }
9806 
9807 static int determine_kprobe_perf_type(void)
9808 {
9809 	const char *file = "/sys/bus/event_source/devices/kprobe/type";
9810 
9811 	return parse_uint_from_file(file, "%d\n");
9812 }
9813 
9814 static int determine_uprobe_perf_type(void)
9815 {
9816 	const char *file = "/sys/bus/event_source/devices/uprobe/type";
9817 
9818 	return parse_uint_from_file(file, "%d\n");
9819 }
9820 
9821 static int determine_kprobe_retprobe_bit(void)
9822 {
9823 	const char *file = "/sys/bus/event_source/devices/kprobe/format/retprobe";
9824 
9825 	return parse_uint_from_file(file, "config:%d\n");
9826 }
9827 
9828 static int determine_uprobe_retprobe_bit(void)
9829 {
9830 	const char *file = "/sys/bus/event_source/devices/uprobe/format/retprobe";
9831 
9832 	return parse_uint_from_file(file, "config:%d\n");
9833 }
9834 
9835 #define PERF_UPROBE_REF_CTR_OFFSET_BITS 32
9836 #define PERF_UPROBE_REF_CTR_OFFSET_SHIFT 32
9837 
9838 static int perf_event_open_probe(bool uprobe, bool retprobe, const char *name,
9839 				 uint64_t offset, int pid, size_t ref_ctr_off)
9840 {
9841 	const size_t attr_sz = sizeof(struct perf_event_attr);
9842 	struct perf_event_attr attr;
9843 	char errmsg[STRERR_BUFSIZE];
9844 	int type, pfd;
9845 
9846 	if (ref_ctr_off >= (1ULL << PERF_UPROBE_REF_CTR_OFFSET_BITS))
9847 		return -EINVAL;
9848 
9849 	memset(&attr, 0, attr_sz);
9850 
9851 	type = uprobe ? determine_uprobe_perf_type()
9852 		      : determine_kprobe_perf_type();
9853 	if (type < 0) {
9854 		pr_warn("failed to determine %s perf type: %s\n",
9855 			uprobe ? "uprobe" : "kprobe",
9856 			libbpf_strerror_r(type, errmsg, sizeof(errmsg)));
9857 		return type;
9858 	}
9859 	if (retprobe) {
9860 		int bit = uprobe ? determine_uprobe_retprobe_bit()
9861 				 : determine_kprobe_retprobe_bit();
9862 
9863 		if (bit < 0) {
9864 			pr_warn("failed to determine %s retprobe bit: %s\n",
9865 				uprobe ? "uprobe" : "kprobe",
9866 				libbpf_strerror_r(bit, errmsg, sizeof(errmsg)));
9867 			return bit;
9868 		}
9869 		attr.config |= 1 << bit;
9870 	}
9871 	attr.size = attr_sz;
9872 	attr.type = type;
9873 	attr.config |= (__u64)ref_ctr_off << PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
9874 	attr.config1 = ptr_to_u64(name); /* kprobe_func or uprobe_path */
9875 	attr.config2 = offset;		 /* kprobe_addr or probe_offset */
9876 
9877 	/* pid filter is meaningful only for uprobes */
9878 	pfd = syscall(__NR_perf_event_open, &attr,
9879 		      pid < 0 ? -1 : pid /* pid */,
9880 		      pid == -1 ? 0 : -1 /* cpu */,
9881 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
9882 	return pfd >= 0 ? pfd : -errno;
9883 }
9884 
9885 static int append_to_file(const char *file, const char *fmt, ...)
9886 {
9887 	int fd, n, err = 0;
9888 	va_list ap;
9889 
9890 	fd = open(file, O_WRONLY | O_APPEND | O_CLOEXEC, 0);
9891 	if (fd < 0)
9892 		return -errno;
9893 
9894 	va_start(ap, fmt);
9895 	n = vdprintf(fd, fmt, ap);
9896 	va_end(ap);
9897 
9898 	if (n < 0)
9899 		err = -errno;
9900 
9901 	close(fd);
9902 	return err;
9903 }
9904 
9905 #define DEBUGFS "/sys/kernel/debug/tracing"
9906 #define TRACEFS "/sys/kernel/tracing"
9907 
9908 static bool use_debugfs(void)
9909 {
9910 	static int has_debugfs = -1;
9911 
9912 	if (has_debugfs < 0)
9913 		has_debugfs = access(DEBUGFS, F_OK) == 0;
9914 
9915 	return has_debugfs == 1;
9916 }
9917 
9918 static const char *tracefs_path(void)
9919 {
9920 	return use_debugfs() ? DEBUGFS : TRACEFS;
9921 }
9922 
9923 static const char *tracefs_kprobe_events(void)
9924 {
9925 	return use_debugfs() ? DEBUGFS"/kprobe_events" : TRACEFS"/kprobe_events";
9926 }
9927 
9928 static const char *tracefs_uprobe_events(void)
9929 {
9930 	return use_debugfs() ? DEBUGFS"/uprobe_events" : TRACEFS"/uprobe_events";
9931 }
9932 
9933 static void gen_kprobe_legacy_event_name(char *buf, size_t buf_sz,
9934 					 const char *kfunc_name, size_t offset)
9935 {
9936 	static int index = 0;
9937 
9938 	snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx_%d", getpid(), kfunc_name, offset,
9939 		 __sync_fetch_and_add(&index, 1));
9940 }
9941 
9942 static int add_kprobe_event_legacy(const char *probe_name, bool retprobe,
9943 				   const char *kfunc_name, size_t offset)
9944 {
9945 	return append_to_file(tracefs_kprobe_events(), "%c:%s/%s %s+0x%zx",
9946 			      retprobe ? 'r' : 'p',
9947 			      retprobe ? "kretprobes" : "kprobes",
9948 			      probe_name, kfunc_name, offset);
9949 }
9950 
9951 static int remove_kprobe_event_legacy(const char *probe_name, bool retprobe)
9952 {
9953 	return append_to_file(tracefs_kprobe_events(), "-:%s/%s",
9954 			      retprobe ? "kretprobes" : "kprobes", probe_name);
9955 }
9956 
9957 static int determine_kprobe_perf_type_legacy(const char *probe_name, bool retprobe)
9958 {
9959 	char file[256];
9960 
9961 	snprintf(file, sizeof(file), "%s/events/%s/%s/id",
9962 		 tracefs_path(), retprobe ? "kretprobes" : "kprobes", probe_name);
9963 
9964 	return parse_uint_from_file(file, "%d\n");
9965 }
9966 
9967 static int perf_event_kprobe_open_legacy(const char *probe_name, bool retprobe,
9968 					 const char *kfunc_name, size_t offset, int pid)
9969 {
9970 	const size_t attr_sz = sizeof(struct perf_event_attr);
9971 	struct perf_event_attr attr;
9972 	char errmsg[STRERR_BUFSIZE];
9973 	int type, pfd, err;
9974 
9975 	err = add_kprobe_event_legacy(probe_name, retprobe, kfunc_name, offset);
9976 	if (err < 0) {
9977 		pr_warn("failed to add legacy kprobe event for '%s+0x%zx': %s\n",
9978 			kfunc_name, offset,
9979 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9980 		return err;
9981 	}
9982 	type = determine_kprobe_perf_type_legacy(probe_name, retprobe);
9983 	if (type < 0) {
9984 		err = type;
9985 		pr_warn("failed to determine legacy kprobe event id for '%s+0x%zx': %s\n",
9986 			kfunc_name, offset,
9987 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
9988 		goto err_clean_legacy;
9989 	}
9990 
9991 	memset(&attr, 0, attr_sz);
9992 	attr.size = attr_sz;
9993 	attr.config = type;
9994 	attr.type = PERF_TYPE_TRACEPOINT;
9995 
9996 	pfd = syscall(__NR_perf_event_open, &attr,
9997 		      pid < 0 ? -1 : pid, /* pid */
9998 		      pid == -1 ? 0 : -1, /* cpu */
9999 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
10000 	if (pfd < 0) {
10001 		err = -errno;
10002 		pr_warn("legacy kprobe perf_event_open() failed: %s\n",
10003 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10004 		goto err_clean_legacy;
10005 	}
10006 	return pfd;
10007 
10008 err_clean_legacy:
10009 	/* Clear the newly added legacy kprobe_event */
10010 	remove_kprobe_event_legacy(probe_name, retprobe);
10011 	return err;
10012 }
10013 
10014 static const char *arch_specific_syscall_pfx(void)
10015 {
10016 #if defined(__x86_64__)
10017 	return "x64";
10018 #elif defined(__i386__)
10019 	return "ia32";
10020 #elif defined(__s390x__)
10021 	return "s390x";
10022 #elif defined(__s390__)
10023 	return "s390";
10024 #elif defined(__arm__)
10025 	return "arm";
10026 #elif defined(__aarch64__)
10027 	return "arm64";
10028 #elif defined(__mips__)
10029 	return "mips";
10030 #elif defined(__riscv)
10031 	return "riscv";
10032 #elif defined(__powerpc__)
10033 	return "powerpc";
10034 #elif defined(__powerpc64__)
10035 	return "powerpc64";
10036 #else
10037 	return NULL;
10038 #endif
10039 }
10040 
10041 static int probe_kern_syscall_wrapper(void)
10042 {
10043 	char syscall_name[64];
10044 	const char *ksys_pfx;
10045 
10046 	ksys_pfx = arch_specific_syscall_pfx();
10047 	if (!ksys_pfx)
10048 		return 0;
10049 
10050 	snprintf(syscall_name, sizeof(syscall_name), "__%s_sys_bpf", ksys_pfx);
10051 
10052 	if (determine_kprobe_perf_type() >= 0) {
10053 		int pfd;
10054 
10055 		pfd = perf_event_open_probe(false, false, syscall_name, 0, getpid(), 0);
10056 		if (pfd >= 0)
10057 			close(pfd);
10058 
10059 		return pfd >= 0 ? 1 : 0;
10060 	} else { /* legacy mode */
10061 		char probe_name[128];
10062 
10063 		gen_kprobe_legacy_event_name(probe_name, sizeof(probe_name), syscall_name, 0);
10064 		if (add_kprobe_event_legacy(probe_name, false, syscall_name, 0) < 0)
10065 			return 0;
10066 
10067 		(void)remove_kprobe_event_legacy(probe_name, false);
10068 		return 1;
10069 	}
10070 }
10071 
10072 struct bpf_link *
10073 bpf_program__attach_kprobe_opts(const struct bpf_program *prog,
10074 				const char *func_name,
10075 				const struct bpf_kprobe_opts *opts)
10076 {
10077 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
10078 	char errmsg[STRERR_BUFSIZE];
10079 	char *legacy_probe = NULL;
10080 	struct bpf_link *link;
10081 	size_t offset;
10082 	bool retprobe, legacy;
10083 	int pfd, err;
10084 
10085 	if (!OPTS_VALID(opts, bpf_kprobe_opts))
10086 		return libbpf_err_ptr(-EINVAL);
10087 
10088 	retprobe = OPTS_GET(opts, retprobe, false);
10089 	offset = OPTS_GET(opts, offset, 0);
10090 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
10091 
10092 	legacy = determine_kprobe_perf_type() < 0;
10093 	if (!legacy) {
10094 		pfd = perf_event_open_probe(false /* uprobe */, retprobe,
10095 					    func_name, offset,
10096 					    -1 /* pid */, 0 /* ref_ctr_off */);
10097 	} else {
10098 		char probe_name[256];
10099 
10100 		gen_kprobe_legacy_event_name(probe_name, sizeof(probe_name),
10101 					     func_name, offset);
10102 
10103 		legacy_probe = strdup(probe_name);
10104 		if (!legacy_probe)
10105 			return libbpf_err_ptr(-ENOMEM);
10106 
10107 		pfd = perf_event_kprobe_open_legacy(legacy_probe, retprobe, func_name,
10108 						    offset, -1 /* pid */);
10109 	}
10110 	if (pfd < 0) {
10111 		err = -errno;
10112 		pr_warn("prog '%s': failed to create %s '%s+0x%zx' perf event: %s\n",
10113 			prog->name, retprobe ? "kretprobe" : "kprobe",
10114 			func_name, offset,
10115 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10116 		goto err_out;
10117 	}
10118 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
10119 	err = libbpf_get_error(link);
10120 	if (err) {
10121 		close(pfd);
10122 		pr_warn("prog '%s': failed to attach to %s '%s+0x%zx': %s\n",
10123 			prog->name, retprobe ? "kretprobe" : "kprobe",
10124 			func_name, offset,
10125 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10126 		goto err_clean_legacy;
10127 	}
10128 	if (legacy) {
10129 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10130 
10131 		perf_link->legacy_probe_name = legacy_probe;
10132 		perf_link->legacy_is_kprobe = true;
10133 		perf_link->legacy_is_retprobe = retprobe;
10134 	}
10135 
10136 	return link;
10137 
10138 err_clean_legacy:
10139 	if (legacy)
10140 		remove_kprobe_event_legacy(legacy_probe, retprobe);
10141 err_out:
10142 	free(legacy_probe);
10143 	return libbpf_err_ptr(err);
10144 }
10145 
10146 struct bpf_link *bpf_program__attach_kprobe(const struct bpf_program *prog,
10147 					    bool retprobe,
10148 					    const char *func_name)
10149 {
10150 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts,
10151 		.retprobe = retprobe,
10152 	);
10153 
10154 	return bpf_program__attach_kprobe_opts(prog, func_name, &opts);
10155 }
10156 
10157 struct bpf_link *bpf_program__attach_ksyscall(const struct bpf_program *prog,
10158 					      const char *syscall_name,
10159 					      const struct bpf_ksyscall_opts *opts)
10160 {
10161 	LIBBPF_OPTS(bpf_kprobe_opts, kprobe_opts);
10162 	char func_name[128];
10163 
10164 	if (!OPTS_VALID(opts, bpf_ksyscall_opts))
10165 		return libbpf_err_ptr(-EINVAL);
10166 
10167 	if (kernel_supports(prog->obj, FEAT_SYSCALL_WRAPPER)) {
10168 		/* arch_specific_syscall_pfx() should never return NULL here
10169 		 * because it is guarded by kernel_supports(). However, since
10170 		 * compiler does not know that we have an explicit conditional
10171 		 * as well.
10172 		 */
10173 		snprintf(func_name, sizeof(func_name), "__%s_sys_%s",
10174 			 arch_specific_syscall_pfx() ? : "", syscall_name);
10175 	} else {
10176 		snprintf(func_name, sizeof(func_name), "__se_sys_%s", syscall_name);
10177 	}
10178 
10179 	kprobe_opts.retprobe = OPTS_GET(opts, retprobe, false);
10180 	kprobe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
10181 
10182 	return bpf_program__attach_kprobe_opts(prog, func_name, &kprobe_opts);
10183 }
10184 
10185 /* Adapted from perf/util/string.c */
10186 static bool glob_match(const char *str, const char *pat)
10187 {
10188 	while (*str && *pat && *pat != '*') {
10189 		if (*pat == '?') {      /* Matches any single character */
10190 			str++;
10191 			pat++;
10192 			continue;
10193 		}
10194 		if (*str != *pat)
10195 			return false;
10196 		str++;
10197 		pat++;
10198 	}
10199 	/* Check wild card */
10200 	if (*pat == '*') {
10201 		while (*pat == '*')
10202 			pat++;
10203 		if (!*pat) /* Tail wild card matches all */
10204 			return true;
10205 		while (*str)
10206 			if (glob_match(str++, pat))
10207 				return true;
10208 	}
10209 	return !*str && !*pat;
10210 }
10211 
10212 struct kprobe_multi_resolve {
10213 	const char *pattern;
10214 	unsigned long *addrs;
10215 	size_t cap;
10216 	size_t cnt;
10217 };
10218 
10219 static int
10220 resolve_kprobe_multi_cb(unsigned long long sym_addr, char sym_type,
10221 			const char *sym_name, void *ctx)
10222 {
10223 	struct kprobe_multi_resolve *res = ctx;
10224 	int err;
10225 
10226 	if (!glob_match(sym_name, res->pattern))
10227 		return 0;
10228 
10229 	err = libbpf_ensure_mem((void **) &res->addrs, &res->cap, sizeof(unsigned long),
10230 				res->cnt + 1);
10231 	if (err)
10232 		return err;
10233 
10234 	res->addrs[res->cnt++] = (unsigned long) sym_addr;
10235 	return 0;
10236 }
10237 
10238 struct bpf_link *
10239 bpf_program__attach_kprobe_multi_opts(const struct bpf_program *prog,
10240 				      const char *pattern,
10241 				      const struct bpf_kprobe_multi_opts *opts)
10242 {
10243 	LIBBPF_OPTS(bpf_link_create_opts, lopts);
10244 	struct kprobe_multi_resolve res = {
10245 		.pattern = pattern,
10246 	};
10247 	struct bpf_link *link = NULL;
10248 	char errmsg[STRERR_BUFSIZE];
10249 	const unsigned long *addrs;
10250 	int err, link_fd, prog_fd;
10251 	const __u64 *cookies;
10252 	const char **syms;
10253 	bool retprobe;
10254 	size_t cnt;
10255 
10256 	if (!OPTS_VALID(opts, bpf_kprobe_multi_opts))
10257 		return libbpf_err_ptr(-EINVAL);
10258 
10259 	syms    = OPTS_GET(opts, syms, false);
10260 	addrs   = OPTS_GET(opts, addrs, false);
10261 	cnt     = OPTS_GET(opts, cnt, false);
10262 	cookies = OPTS_GET(opts, cookies, false);
10263 
10264 	if (!pattern && !addrs && !syms)
10265 		return libbpf_err_ptr(-EINVAL);
10266 	if (pattern && (addrs || syms || cookies || cnt))
10267 		return libbpf_err_ptr(-EINVAL);
10268 	if (!pattern && !cnt)
10269 		return libbpf_err_ptr(-EINVAL);
10270 	if (addrs && syms)
10271 		return libbpf_err_ptr(-EINVAL);
10272 
10273 	if (pattern) {
10274 		err = libbpf_kallsyms_parse(resolve_kprobe_multi_cb, &res);
10275 		if (err)
10276 			goto error;
10277 		if (!res.cnt) {
10278 			err = -ENOENT;
10279 			goto error;
10280 		}
10281 		addrs = res.addrs;
10282 		cnt = res.cnt;
10283 	}
10284 
10285 	retprobe = OPTS_GET(opts, retprobe, false);
10286 
10287 	lopts.kprobe_multi.syms = syms;
10288 	lopts.kprobe_multi.addrs = addrs;
10289 	lopts.kprobe_multi.cookies = cookies;
10290 	lopts.kprobe_multi.cnt = cnt;
10291 	lopts.kprobe_multi.flags = retprobe ? BPF_F_KPROBE_MULTI_RETURN : 0;
10292 
10293 	link = calloc(1, sizeof(*link));
10294 	if (!link) {
10295 		err = -ENOMEM;
10296 		goto error;
10297 	}
10298 	link->detach = &bpf_link__detach_fd;
10299 
10300 	prog_fd = bpf_program__fd(prog);
10301 	link_fd = bpf_link_create(prog_fd, 0, BPF_TRACE_KPROBE_MULTI, &lopts);
10302 	if (link_fd < 0) {
10303 		err = -errno;
10304 		pr_warn("prog '%s': failed to attach: %s\n",
10305 			prog->name, libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10306 		goto error;
10307 	}
10308 	link->fd = link_fd;
10309 	free(res.addrs);
10310 	return link;
10311 
10312 error:
10313 	free(link);
10314 	free(res.addrs);
10315 	return libbpf_err_ptr(err);
10316 }
10317 
10318 static int attach_kprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
10319 {
10320 	DECLARE_LIBBPF_OPTS(bpf_kprobe_opts, opts);
10321 	unsigned long offset = 0;
10322 	const char *func_name;
10323 	char *func;
10324 	int n;
10325 
10326 	*link = NULL;
10327 
10328 	/* no auto-attach for SEC("kprobe") and SEC("kretprobe") */
10329 	if (strcmp(prog->sec_name, "kprobe") == 0 || strcmp(prog->sec_name, "kretprobe") == 0)
10330 		return 0;
10331 
10332 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe/");
10333 	if (opts.retprobe)
10334 		func_name = prog->sec_name + sizeof("kretprobe/") - 1;
10335 	else
10336 		func_name = prog->sec_name + sizeof("kprobe/") - 1;
10337 
10338 	n = sscanf(func_name, "%m[a-zA-Z0-9_.]+%li", &func, &offset);
10339 	if (n < 1) {
10340 		pr_warn("kprobe name is invalid: %s\n", func_name);
10341 		return -EINVAL;
10342 	}
10343 	if (opts.retprobe && offset != 0) {
10344 		free(func);
10345 		pr_warn("kretprobes do not support offset specification\n");
10346 		return -EINVAL;
10347 	}
10348 
10349 	opts.offset = offset;
10350 	*link = bpf_program__attach_kprobe_opts(prog, func, &opts);
10351 	free(func);
10352 	return libbpf_get_error(*link);
10353 }
10354 
10355 static int attach_ksyscall(const struct bpf_program *prog, long cookie, struct bpf_link **link)
10356 {
10357 	LIBBPF_OPTS(bpf_ksyscall_opts, opts);
10358 	const char *syscall_name;
10359 
10360 	*link = NULL;
10361 
10362 	/* no auto-attach for SEC("ksyscall") and SEC("kretsyscall") */
10363 	if (strcmp(prog->sec_name, "ksyscall") == 0 || strcmp(prog->sec_name, "kretsyscall") == 0)
10364 		return 0;
10365 
10366 	opts.retprobe = str_has_pfx(prog->sec_name, "kretsyscall/");
10367 	if (opts.retprobe)
10368 		syscall_name = prog->sec_name + sizeof("kretsyscall/") - 1;
10369 	else
10370 		syscall_name = prog->sec_name + sizeof("ksyscall/") - 1;
10371 
10372 	*link = bpf_program__attach_ksyscall(prog, syscall_name, &opts);
10373 	return *link ? 0 : -errno;
10374 }
10375 
10376 static int attach_kprobe_multi(const struct bpf_program *prog, long cookie, struct bpf_link **link)
10377 {
10378 	LIBBPF_OPTS(bpf_kprobe_multi_opts, opts);
10379 	const char *spec;
10380 	char *pattern;
10381 	int n;
10382 
10383 	*link = NULL;
10384 
10385 	/* no auto-attach for SEC("kprobe.multi") and SEC("kretprobe.multi") */
10386 	if (strcmp(prog->sec_name, "kprobe.multi") == 0 ||
10387 	    strcmp(prog->sec_name, "kretprobe.multi") == 0)
10388 		return 0;
10389 
10390 	opts.retprobe = str_has_pfx(prog->sec_name, "kretprobe.multi/");
10391 	if (opts.retprobe)
10392 		spec = prog->sec_name + sizeof("kretprobe.multi/") - 1;
10393 	else
10394 		spec = prog->sec_name + sizeof("kprobe.multi/") - 1;
10395 
10396 	n = sscanf(spec, "%m[a-zA-Z0-9_.*?]", &pattern);
10397 	if (n < 1) {
10398 		pr_warn("kprobe multi pattern is invalid: %s\n", pattern);
10399 		return -EINVAL;
10400 	}
10401 
10402 	*link = bpf_program__attach_kprobe_multi_opts(prog, pattern, &opts);
10403 	free(pattern);
10404 	return libbpf_get_error(*link);
10405 }
10406 
10407 static void gen_uprobe_legacy_event_name(char *buf, size_t buf_sz,
10408 					 const char *binary_path, uint64_t offset)
10409 {
10410 	int i;
10411 
10412 	snprintf(buf, buf_sz, "libbpf_%u_%s_0x%zx", getpid(), binary_path, (size_t)offset);
10413 
10414 	/* sanitize binary_path in the probe name */
10415 	for (i = 0; buf[i]; i++) {
10416 		if (!isalnum(buf[i]))
10417 			buf[i] = '_';
10418 	}
10419 }
10420 
10421 static inline int add_uprobe_event_legacy(const char *probe_name, bool retprobe,
10422 					  const char *binary_path, size_t offset)
10423 {
10424 	return append_to_file(tracefs_uprobe_events(), "%c:%s/%s %s:0x%zx",
10425 			      retprobe ? 'r' : 'p',
10426 			      retprobe ? "uretprobes" : "uprobes",
10427 			      probe_name, binary_path, offset);
10428 }
10429 
10430 static inline int remove_uprobe_event_legacy(const char *probe_name, bool retprobe)
10431 {
10432 	return append_to_file(tracefs_uprobe_events(), "-:%s/%s",
10433 			      retprobe ? "uretprobes" : "uprobes", probe_name);
10434 }
10435 
10436 static int determine_uprobe_perf_type_legacy(const char *probe_name, bool retprobe)
10437 {
10438 	char file[512];
10439 
10440 	snprintf(file, sizeof(file), "%s/events/%s/%s/id",
10441 		 tracefs_path(), retprobe ? "uretprobes" : "uprobes", probe_name);
10442 
10443 	return parse_uint_from_file(file, "%d\n");
10444 }
10445 
10446 static int perf_event_uprobe_open_legacy(const char *probe_name, bool retprobe,
10447 					 const char *binary_path, size_t offset, int pid)
10448 {
10449 	const size_t attr_sz = sizeof(struct perf_event_attr);
10450 	struct perf_event_attr attr;
10451 	int type, pfd, err;
10452 
10453 	err = add_uprobe_event_legacy(probe_name, retprobe, binary_path, offset);
10454 	if (err < 0) {
10455 		pr_warn("failed to add legacy uprobe event for %s:0x%zx: %d\n",
10456 			binary_path, (size_t)offset, err);
10457 		return err;
10458 	}
10459 	type = determine_uprobe_perf_type_legacy(probe_name, retprobe);
10460 	if (type < 0) {
10461 		err = type;
10462 		pr_warn("failed to determine legacy uprobe event id for %s:0x%zx: %d\n",
10463 			binary_path, offset, err);
10464 		goto err_clean_legacy;
10465 	}
10466 
10467 	memset(&attr, 0, attr_sz);
10468 	attr.size = attr_sz;
10469 	attr.config = type;
10470 	attr.type = PERF_TYPE_TRACEPOINT;
10471 
10472 	pfd = syscall(__NR_perf_event_open, &attr,
10473 		      pid < 0 ? -1 : pid, /* pid */
10474 		      pid == -1 ? 0 : -1, /* cpu */
10475 		      -1 /* group_fd */,  PERF_FLAG_FD_CLOEXEC);
10476 	if (pfd < 0) {
10477 		err = -errno;
10478 		pr_warn("legacy uprobe perf_event_open() failed: %d\n", err);
10479 		goto err_clean_legacy;
10480 	}
10481 	return pfd;
10482 
10483 err_clean_legacy:
10484 	/* Clear the newly added legacy uprobe_event */
10485 	remove_uprobe_event_legacy(probe_name, retprobe);
10486 	return err;
10487 }
10488 
10489 /* Return next ELF section of sh_type after scn, or first of that type if scn is NULL. */
10490 static Elf_Scn *elf_find_next_scn_by_type(Elf *elf, int sh_type, Elf_Scn *scn)
10491 {
10492 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
10493 		GElf_Shdr sh;
10494 
10495 		if (!gelf_getshdr(scn, &sh))
10496 			continue;
10497 		if (sh.sh_type == sh_type)
10498 			return scn;
10499 	}
10500 	return NULL;
10501 }
10502 
10503 /* Find offset of function name in object specified by path.  "name" matches
10504  * symbol name or name@@LIB for library functions.
10505  */
10506 static long elf_find_func_offset(const char *binary_path, const char *name)
10507 {
10508 	int fd, i, sh_types[2] = { SHT_DYNSYM, SHT_SYMTAB };
10509 	bool is_shared_lib, is_name_qualified;
10510 	char errmsg[STRERR_BUFSIZE];
10511 	long ret = -ENOENT;
10512 	size_t name_len;
10513 	GElf_Ehdr ehdr;
10514 	Elf *elf;
10515 
10516 	fd = open(binary_path, O_RDONLY | O_CLOEXEC);
10517 	if (fd < 0) {
10518 		ret = -errno;
10519 		pr_warn("failed to open %s: %s\n", binary_path,
10520 			libbpf_strerror_r(ret, errmsg, sizeof(errmsg)));
10521 		return ret;
10522 	}
10523 	elf = elf_begin(fd, ELF_C_READ_MMAP, NULL);
10524 	if (!elf) {
10525 		pr_warn("elf: could not read elf from %s: %s\n", binary_path, elf_errmsg(-1));
10526 		close(fd);
10527 		return -LIBBPF_ERRNO__FORMAT;
10528 	}
10529 	if (!gelf_getehdr(elf, &ehdr)) {
10530 		pr_warn("elf: failed to get ehdr from %s: %s\n", binary_path, elf_errmsg(-1));
10531 		ret = -LIBBPF_ERRNO__FORMAT;
10532 		goto out;
10533 	}
10534 	/* for shared lib case, we do not need to calculate relative offset */
10535 	is_shared_lib = ehdr.e_type == ET_DYN;
10536 
10537 	name_len = strlen(name);
10538 	/* Does name specify "@@LIB"? */
10539 	is_name_qualified = strstr(name, "@@") != NULL;
10540 
10541 	/* Search SHT_DYNSYM, SHT_SYMTAB for symbol.  This search order is used because if
10542 	 * a binary is stripped, it may only have SHT_DYNSYM, and a fully-statically
10543 	 * linked binary may not have SHT_DYMSYM, so absence of a section should not be
10544 	 * reported as a warning/error.
10545 	 */
10546 	for (i = 0; i < ARRAY_SIZE(sh_types); i++) {
10547 		size_t nr_syms, strtabidx, idx;
10548 		Elf_Data *symbols = NULL;
10549 		Elf_Scn *scn = NULL;
10550 		int last_bind = -1;
10551 		const char *sname;
10552 		GElf_Shdr sh;
10553 
10554 		scn = elf_find_next_scn_by_type(elf, sh_types[i], NULL);
10555 		if (!scn) {
10556 			pr_debug("elf: failed to find symbol table ELF sections in '%s'\n",
10557 				 binary_path);
10558 			continue;
10559 		}
10560 		if (!gelf_getshdr(scn, &sh))
10561 			continue;
10562 		strtabidx = sh.sh_link;
10563 		symbols = elf_getdata(scn, 0);
10564 		if (!symbols) {
10565 			pr_warn("elf: failed to get symbols for symtab section in '%s': %s\n",
10566 				binary_path, elf_errmsg(-1));
10567 			ret = -LIBBPF_ERRNO__FORMAT;
10568 			goto out;
10569 		}
10570 		nr_syms = symbols->d_size / sh.sh_entsize;
10571 
10572 		for (idx = 0; idx < nr_syms; idx++) {
10573 			int curr_bind;
10574 			GElf_Sym sym;
10575 			Elf_Scn *sym_scn;
10576 			GElf_Shdr sym_sh;
10577 
10578 			if (!gelf_getsym(symbols, idx, &sym))
10579 				continue;
10580 
10581 			if (GELF_ST_TYPE(sym.st_info) != STT_FUNC)
10582 				continue;
10583 
10584 			sname = elf_strptr(elf, strtabidx, sym.st_name);
10585 			if (!sname)
10586 				continue;
10587 
10588 			curr_bind = GELF_ST_BIND(sym.st_info);
10589 
10590 			/* User can specify func, func@@LIB or func@@LIB_VERSION. */
10591 			if (strncmp(sname, name, name_len) != 0)
10592 				continue;
10593 			/* ...but we don't want a search for "foo" to match 'foo2" also, so any
10594 			 * additional characters in sname should be of the form "@@LIB".
10595 			 */
10596 			if (!is_name_qualified && sname[name_len] != '\0' && sname[name_len] != '@')
10597 				continue;
10598 
10599 			if (ret >= 0) {
10600 				/* handle multiple matches */
10601 				if (last_bind != STB_WEAK && curr_bind != STB_WEAK) {
10602 					/* Only accept one non-weak bind. */
10603 					pr_warn("elf: ambiguous match for '%s', '%s' in '%s'\n",
10604 						sname, name, binary_path);
10605 					ret = -LIBBPF_ERRNO__FORMAT;
10606 					goto out;
10607 				} else if (curr_bind == STB_WEAK) {
10608 					/* already have a non-weak bind, and
10609 					 * this is a weak bind, so ignore.
10610 					 */
10611 					continue;
10612 				}
10613 			}
10614 
10615 			/* Transform symbol's virtual address (absolute for
10616 			 * binaries and relative for shared libs) into file
10617 			 * offset, which is what kernel is expecting for
10618 			 * uprobe/uretprobe attachment.
10619 			 * See Documentation/trace/uprobetracer.rst for more
10620 			 * details.
10621 			 * This is done by looking up symbol's containing
10622 			 * section's header and using it's virtual address
10623 			 * (sh_addr) and corresponding file offset (sh_offset)
10624 			 * to transform sym.st_value (virtual address) into
10625 			 * desired final file offset.
10626 			 */
10627 			sym_scn = elf_getscn(elf, sym.st_shndx);
10628 			if (!sym_scn)
10629 				continue;
10630 			if (!gelf_getshdr(sym_scn, &sym_sh))
10631 				continue;
10632 
10633 			ret = sym.st_value - sym_sh.sh_addr + sym_sh.sh_offset;
10634 			last_bind = curr_bind;
10635 		}
10636 		if (ret > 0)
10637 			break;
10638 	}
10639 
10640 	if (ret > 0) {
10641 		pr_debug("elf: symbol address match for '%s' in '%s': 0x%lx\n", name, binary_path,
10642 			 ret);
10643 	} else {
10644 		if (ret == 0) {
10645 			pr_warn("elf: '%s' is 0 in symtab for '%s': %s\n", name, binary_path,
10646 				is_shared_lib ? "should not be 0 in a shared library" :
10647 						"try using shared library path instead");
10648 			ret = -ENOENT;
10649 		} else {
10650 			pr_warn("elf: failed to find symbol '%s' in '%s'\n", name, binary_path);
10651 		}
10652 	}
10653 out:
10654 	elf_end(elf);
10655 	close(fd);
10656 	return ret;
10657 }
10658 
10659 static const char *arch_specific_lib_paths(void)
10660 {
10661 	/*
10662 	 * Based on https://packages.debian.org/sid/libc6.
10663 	 *
10664 	 * Assume that the traced program is built for the same architecture
10665 	 * as libbpf, which should cover the vast majority of cases.
10666 	 */
10667 #if defined(__x86_64__)
10668 	return "/lib/x86_64-linux-gnu";
10669 #elif defined(__i386__)
10670 	return "/lib/i386-linux-gnu";
10671 #elif defined(__s390x__)
10672 	return "/lib/s390x-linux-gnu";
10673 #elif defined(__s390__)
10674 	return "/lib/s390-linux-gnu";
10675 #elif defined(__arm__) && defined(__SOFTFP__)
10676 	return "/lib/arm-linux-gnueabi";
10677 #elif defined(__arm__) && !defined(__SOFTFP__)
10678 	return "/lib/arm-linux-gnueabihf";
10679 #elif defined(__aarch64__)
10680 	return "/lib/aarch64-linux-gnu";
10681 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 64
10682 	return "/lib/mips64el-linux-gnuabi64";
10683 #elif defined(__mips__) && defined(__MIPSEL__) && _MIPS_SZLONG == 32
10684 	return "/lib/mipsel-linux-gnu";
10685 #elif defined(__powerpc64__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
10686 	return "/lib/powerpc64le-linux-gnu";
10687 #elif defined(__sparc__) && defined(__arch64__)
10688 	return "/lib/sparc64-linux-gnu";
10689 #elif defined(__riscv) && __riscv_xlen == 64
10690 	return "/lib/riscv64-linux-gnu";
10691 #else
10692 	return NULL;
10693 #endif
10694 }
10695 
10696 /* Get full path to program/shared library. */
10697 static int resolve_full_path(const char *file, char *result, size_t result_sz)
10698 {
10699 	const char *search_paths[3] = {};
10700 	int i, perm;
10701 
10702 	if (str_has_sfx(file, ".so") || strstr(file, ".so.")) {
10703 		search_paths[0] = getenv("LD_LIBRARY_PATH");
10704 		search_paths[1] = "/usr/lib64:/usr/lib";
10705 		search_paths[2] = arch_specific_lib_paths();
10706 		perm = R_OK;
10707 	} else {
10708 		search_paths[0] = getenv("PATH");
10709 		search_paths[1] = "/usr/bin:/usr/sbin";
10710 		perm = R_OK | X_OK;
10711 	}
10712 
10713 	for (i = 0; i < ARRAY_SIZE(search_paths); i++) {
10714 		const char *s;
10715 
10716 		if (!search_paths[i])
10717 			continue;
10718 		for (s = search_paths[i]; s != NULL; s = strchr(s, ':')) {
10719 			char *next_path;
10720 			int seg_len;
10721 
10722 			if (s[0] == ':')
10723 				s++;
10724 			next_path = strchr(s, ':');
10725 			seg_len = next_path ? next_path - s : strlen(s);
10726 			if (!seg_len)
10727 				continue;
10728 			snprintf(result, result_sz, "%.*s/%s", seg_len, s, file);
10729 			/* ensure it has required permissions */
10730 			if (access(result, perm) < 0)
10731 				continue;
10732 			pr_debug("resolved '%s' to '%s'\n", file, result);
10733 			return 0;
10734 		}
10735 	}
10736 	return -ENOENT;
10737 }
10738 
10739 LIBBPF_API struct bpf_link *
10740 bpf_program__attach_uprobe_opts(const struct bpf_program *prog, pid_t pid,
10741 				const char *binary_path, size_t func_offset,
10742 				const struct bpf_uprobe_opts *opts)
10743 {
10744 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
10745 	char errmsg[STRERR_BUFSIZE], *legacy_probe = NULL;
10746 	char full_binary_path[PATH_MAX];
10747 	struct bpf_link *link;
10748 	size_t ref_ctr_off;
10749 	int pfd, err;
10750 	bool retprobe, legacy;
10751 	const char *func_name;
10752 
10753 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
10754 		return libbpf_err_ptr(-EINVAL);
10755 
10756 	retprobe = OPTS_GET(opts, retprobe, false);
10757 	ref_ctr_off = OPTS_GET(opts, ref_ctr_offset, 0);
10758 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
10759 
10760 	if (!binary_path)
10761 		return libbpf_err_ptr(-EINVAL);
10762 
10763 	if (!strchr(binary_path, '/')) {
10764 		err = resolve_full_path(binary_path, full_binary_path,
10765 					sizeof(full_binary_path));
10766 		if (err) {
10767 			pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
10768 				prog->name, binary_path, err);
10769 			return libbpf_err_ptr(err);
10770 		}
10771 		binary_path = full_binary_path;
10772 	}
10773 	func_name = OPTS_GET(opts, func_name, NULL);
10774 	if (func_name) {
10775 		long sym_off;
10776 
10777 		sym_off = elf_find_func_offset(binary_path, func_name);
10778 		if (sym_off < 0)
10779 			return libbpf_err_ptr(sym_off);
10780 		func_offset += sym_off;
10781 	}
10782 
10783 	legacy = determine_uprobe_perf_type() < 0;
10784 	if (!legacy) {
10785 		pfd = perf_event_open_probe(true /* uprobe */, retprobe, binary_path,
10786 					    func_offset, pid, ref_ctr_off);
10787 	} else {
10788 		char probe_name[PATH_MAX + 64];
10789 
10790 		if (ref_ctr_off)
10791 			return libbpf_err_ptr(-EINVAL);
10792 
10793 		gen_uprobe_legacy_event_name(probe_name, sizeof(probe_name),
10794 					     binary_path, func_offset);
10795 
10796 		legacy_probe = strdup(probe_name);
10797 		if (!legacy_probe)
10798 			return libbpf_err_ptr(-ENOMEM);
10799 
10800 		pfd = perf_event_uprobe_open_legacy(legacy_probe, retprobe,
10801 						    binary_path, func_offset, pid);
10802 	}
10803 	if (pfd < 0) {
10804 		err = -errno;
10805 		pr_warn("prog '%s': failed to create %s '%s:0x%zx' perf event: %s\n",
10806 			prog->name, retprobe ? "uretprobe" : "uprobe",
10807 			binary_path, func_offset,
10808 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10809 		goto err_out;
10810 	}
10811 
10812 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
10813 	err = libbpf_get_error(link);
10814 	if (err) {
10815 		close(pfd);
10816 		pr_warn("prog '%s': failed to attach to %s '%s:0x%zx': %s\n",
10817 			prog->name, retprobe ? "uretprobe" : "uprobe",
10818 			binary_path, func_offset,
10819 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
10820 		goto err_clean_legacy;
10821 	}
10822 	if (legacy) {
10823 		struct bpf_link_perf *perf_link = container_of(link, struct bpf_link_perf, link);
10824 
10825 		perf_link->legacy_probe_name = legacy_probe;
10826 		perf_link->legacy_is_kprobe = false;
10827 		perf_link->legacy_is_retprobe = retprobe;
10828 	}
10829 	return link;
10830 
10831 err_clean_legacy:
10832 	if (legacy)
10833 		remove_uprobe_event_legacy(legacy_probe, retprobe);
10834 err_out:
10835 	free(legacy_probe);
10836 	return libbpf_err_ptr(err);
10837 }
10838 
10839 /* Format of u[ret]probe section definition supporting auto-attach:
10840  * u[ret]probe/binary:function[+offset]
10841  *
10842  * binary can be an absolute/relative path or a filename; the latter is resolved to a
10843  * full binary path via bpf_program__attach_uprobe_opts.
10844  *
10845  * Specifying uprobe+ ensures we carry out strict matching; either "uprobe" must be
10846  * specified (and auto-attach is not possible) or the above format is specified for
10847  * auto-attach.
10848  */
10849 static int attach_uprobe(const struct bpf_program *prog, long cookie, struct bpf_link **link)
10850 {
10851 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts);
10852 	char *probe_type = NULL, *binary_path = NULL, *func_name = NULL;
10853 	int n, ret = -EINVAL;
10854 	long offset = 0;
10855 
10856 	*link = NULL;
10857 
10858 	n = sscanf(prog->sec_name, "%m[^/]/%m[^:]:%m[a-zA-Z0-9_.]+%li",
10859 		   &probe_type, &binary_path, &func_name, &offset);
10860 	switch (n) {
10861 	case 1:
10862 		/* handle SEC("u[ret]probe") - format is valid, but auto-attach is impossible. */
10863 		ret = 0;
10864 		break;
10865 	case 2:
10866 		pr_warn("prog '%s': section '%s' missing ':function[+offset]' specification\n",
10867 			prog->name, prog->sec_name);
10868 		break;
10869 	case 3:
10870 	case 4:
10871 		opts.retprobe = strcmp(probe_type, "uretprobe") == 0 ||
10872 				strcmp(probe_type, "uretprobe.s") == 0;
10873 		if (opts.retprobe && offset != 0) {
10874 			pr_warn("prog '%s': uretprobes do not support offset specification\n",
10875 				prog->name);
10876 			break;
10877 		}
10878 		opts.func_name = func_name;
10879 		*link = bpf_program__attach_uprobe_opts(prog, -1, binary_path, offset, &opts);
10880 		ret = libbpf_get_error(*link);
10881 		break;
10882 	default:
10883 		pr_warn("prog '%s': invalid format of section definition '%s'\n", prog->name,
10884 			prog->sec_name);
10885 		break;
10886 	}
10887 	free(probe_type);
10888 	free(binary_path);
10889 	free(func_name);
10890 
10891 	return ret;
10892 }
10893 
10894 struct bpf_link *bpf_program__attach_uprobe(const struct bpf_program *prog,
10895 					    bool retprobe, pid_t pid,
10896 					    const char *binary_path,
10897 					    size_t func_offset)
10898 {
10899 	DECLARE_LIBBPF_OPTS(bpf_uprobe_opts, opts, .retprobe = retprobe);
10900 
10901 	return bpf_program__attach_uprobe_opts(prog, pid, binary_path, func_offset, &opts);
10902 }
10903 
10904 struct bpf_link *bpf_program__attach_usdt(const struct bpf_program *prog,
10905 					  pid_t pid, const char *binary_path,
10906 					  const char *usdt_provider, const char *usdt_name,
10907 					  const struct bpf_usdt_opts *opts)
10908 {
10909 	char resolved_path[512];
10910 	struct bpf_object *obj = prog->obj;
10911 	struct bpf_link *link;
10912 	__u64 usdt_cookie;
10913 	int err;
10914 
10915 	if (!OPTS_VALID(opts, bpf_uprobe_opts))
10916 		return libbpf_err_ptr(-EINVAL);
10917 
10918 	if (bpf_program__fd(prog) < 0) {
10919 		pr_warn("prog '%s': can't attach BPF program w/o FD (did you load it?)\n",
10920 			prog->name);
10921 		return libbpf_err_ptr(-EINVAL);
10922 	}
10923 
10924 	if (!binary_path)
10925 		return libbpf_err_ptr(-EINVAL);
10926 
10927 	if (!strchr(binary_path, '/')) {
10928 		err = resolve_full_path(binary_path, resolved_path, sizeof(resolved_path));
10929 		if (err) {
10930 			pr_warn("prog '%s': failed to resolve full path for '%s': %d\n",
10931 				prog->name, binary_path, err);
10932 			return libbpf_err_ptr(err);
10933 		}
10934 		binary_path = resolved_path;
10935 	}
10936 
10937 	/* USDT manager is instantiated lazily on first USDT attach. It will
10938 	 * be destroyed together with BPF object in bpf_object__close().
10939 	 */
10940 	if (IS_ERR(obj->usdt_man))
10941 		return libbpf_ptr(obj->usdt_man);
10942 	if (!obj->usdt_man) {
10943 		obj->usdt_man = usdt_manager_new(obj);
10944 		if (IS_ERR(obj->usdt_man))
10945 			return libbpf_ptr(obj->usdt_man);
10946 	}
10947 
10948 	usdt_cookie = OPTS_GET(opts, usdt_cookie, 0);
10949 	link = usdt_manager_attach_usdt(obj->usdt_man, prog, pid, binary_path,
10950 				        usdt_provider, usdt_name, usdt_cookie);
10951 	err = libbpf_get_error(link);
10952 	if (err)
10953 		return libbpf_err_ptr(err);
10954 	return link;
10955 }
10956 
10957 static int attach_usdt(const struct bpf_program *prog, long cookie, struct bpf_link **link)
10958 {
10959 	char *path = NULL, *provider = NULL, *name = NULL;
10960 	const char *sec_name;
10961 	int n, err;
10962 
10963 	sec_name = bpf_program__section_name(prog);
10964 	if (strcmp(sec_name, "usdt") == 0) {
10965 		/* no auto-attach for just SEC("usdt") */
10966 		*link = NULL;
10967 		return 0;
10968 	}
10969 
10970 	n = sscanf(sec_name, "usdt/%m[^:]:%m[^:]:%m[^:]", &path, &provider, &name);
10971 	if (n != 3) {
10972 		pr_warn("invalid section '%s', expected SEC(\"usdt/<path>:<provider>:<name>\")\n",
10973 			sec_name);
10974 		err = -EINVAL;
10975 	} else {
10976 		*link = bpf_program__attach_usdt(prog, -1 /* any process */, path,
10977 						 provider, name, NULL);
10978 		err = libbpf_get_error(*link);
10979 	}
10980 	free(path);
10981 	free(provider);
10982 	free(name);
10983 	return err;
10984 }
10985 
10986 static int determine_tracepoint_id(const char *tp_category,
10987 				   const char *tp_name)
10988 {
10989 	char file[PATH_MAX];
10990 	int ret;
10991 
10992 	ret = snprintf(file, sizeof(file), "%s/events/%s/%s/id",
10993 		       tracefs_path(), tp_category, tp_name);
10994 	if (ret < 0)
10995 		return -errno;
10996 	if (ret >= sizeof(file)) {
10997 		pr_debug("tracepoint %s/%s path is too long\n",
10998 			 tp_category, tp_name);
10999 		return -E2BIG;
11000 	}
11001 	return parse_uint_from_file(file, "%d\n");
11002 }
11003 
11004 static int perf_event_open_tracepoint(const char *tp_category,
11005 				      const char *tp_name)
11006 {
11007 	const size_t attr_sz = sizeof(struct perf_event_attr);
11008 	struct perf_event_attr attr;
11009 	char errmsg[STRERR_BUFSIZE];
11010 	int tp_id, pfd, err;
11011 
11012 	tp_id = determine_tracepoint_id(tp_category, tp_name);
11013 	if (tp_id < 0) {
11014 		pr_warn("failed to determine tracepoint '%s/%s' perf event ID: %s\n",
11015 			tp_category, tp_name,
11016 			libbpf_strerror_r(tp_id, errmsg, sizeof(errmsg)));
11017 		return tp_id;
11018 	}
11019 
11020 	memset(&attr, 0, attr_sz);
11021 	attr.type = PERF_TYPE_TRACEPOINT;
11022 	attr.size = attr_sz;
11023 	attr.config = tp_id;
11024 
11025 	pfd = syscall(__NR_perf_event_open, &attr, -1 /* pid */, 0 /* cpu */,
11026 		      -1 /* group_fd */, PERF_FLAG_FD_CLOEXEC);
11027 	if (pfd < 0) {
11028 		err = -errno;
11029 		pr_warn("tracepoint '%s/%s' perf_event_open() failed: %s\n",
11030 			tp_category, tp_name,
11031 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11032 		return err;
11033 	}
11034 	return pfd;
11035 }
11036 
11037 struct bpf_link *bpf_program__attach_tracepoint_opts(const struct bpf_program *prog,
11038 						     const char *tp_category,
11039 						     const char *tp_name,
11040 						     const struct bpf_tracepoint_opts *opts)
11041 {
11042 	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
11043 	char errmsg[STRERR_BUFSIZE];
11044 	struct bpf_link *link;
11045 	int pfd, err;
11046 
11047 	if (!OPTS_VALID(opts, bpf_tracepoint_opts))
11048 		return libbpf_err_ptr(-EINVAL);
11049 
11050 	pe_opts.bpf_cookie = OPTS_GET(opts, bpf_cookie, 0);
11051 
11052 	pfd = perf_event_open_tracepoint(tp_category, tp_name);
11053 	if (pfd < 0) {
11054 		pr_warn("prog '%s': failed to create tracepoint '%s/%s' perf event: %s\n",
11055 			prog->name, tp_category, tp_name,
11056 			libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
11057 		return libbpf_err_ptr(pfd);
11058 	}
11059 	link = bpf_program__attach_perf_event_opts(prog, pfd, &pe_opts);
11060 	err = libbpf_get_error(link);
11061 	if (err) {
11062 		close(pfd);
11063 		pr_warn("prog '%s': failed to attach to tracepoint '%s/%s': %s\n",
11064 			prog->name, tp_category, tp_name,
11065 			libbpf_strerror_r(err, errmsg, sizeof(errmsg)));
11066 		return libbpf_err_ptr(err);
11067 	}
11068 	return link;
11069 }
11070 
11071 struct bpf_link *bpf_program__attach_tracepoint(const struct bpf_program *prog,
11072 						const char *tp_category,
11073 						const char *tp_name)
11074 {
11075 	return bpf_program__attach_tracepoint_opts(prog, tp_category, tp_name, NULL);
11076 }
11077 
11078 static int attach_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11079 {
11080 	char *sec_name, *tp_cat, *tp_name;
11081 
11082 	*link = NULL;
11083 
11084 	/* no auto-attach for SEC("tp") or SEC("tracepoint") */
11085 	if (strcmp(prog->sec_name, "tp") == 0 || strcmp(prog->sec_name, "tracepoint") == 0)
11086 		return 0;
11087 
11088 	sec_name = strdup(prog->sec_name);
11089 	if (!sec_name)
11090 		return -ENOMEM;
11091 
11092 	/* extract "tp/<category>/<name>" or "tracepoint/<category>/<name>" */
11093 	if (str_has_pfx(prog->sec_name, "tp/"))
11094 		tp_cat = sec_name + sizeof("tp/") - 1;
11095 	else
11096 		tp_cat = sec_name + sizeof("tracepoint/") - 1;
11097 	tp_name = strchr(tp_cat, '/');
11098 	if (!tp_name) {
11099 		free(sec_name);
11100 		return -EINVAL;
11101 	}
11102 	*tp_name = '\0';
11103 	tp_name++;
11104 
11105 	*link = bpf_program__attach_tracepoint(prog, tp_cat, tp_name);
11106 	free(sec_name);
11107 	return libbpf_get_error(*link);
11108 }
11109 
11110 struct bpf_link *bpf_program__attach_raw_tracepoint(const struct bpf_program *prog,
11111 						    const char *tp_name)
11112 {
11113 	char errmsg[STRERR_BUFSIZE];
11114 	struct bpf_link *link;
11115 	int prog_fd, pfd;
11116 
11117 	prog_fd = bpf_program__fd(prog);
11118 	if (prog_fd < 0) {
11119 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
11120 		return libbpf_err_ptr(-EINVAL);
11121 	}
11122 
11123 	link = calloc(1, sizeof(*link));
11124 	if (!link)
11125 		return libbpf_err_ptr(-ENOMEM);
11126 	link->detach = &bpf_link__detach_fd;
11127 
11128 	pfd = bpf_raw_tracepoint_open(tp_name, prog_fd);
11129 	if (pfd < 0) {
11130 		pfd = -errno;
11131 		free(link);
11132 		pr_warn("prog '%s': failed to attach to raw tracepoint '%s': %s\n",
11133 			prog->name, tp_name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
11134 		return libbpf_err_ptr(pfd);
11135 	}
11136 	link->fd = pfd;
11137 	return link;
11138 }
11139 
11140 static int attach_raw_tp(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11141 {
11142 	static const char *const prefixes[] = {
11143 		"raw_tp",
11144 		"raw_tracepoint",
11145 		"raw_tp.w",
11146 		"raw_tracepoint.w",
11147 	};
11148 	size_t i;
11149 	const char *tp_name = NULL;
11150 
11151 	*link = NULL;
11152 
11153 	for (i = 0; i < ARRAY_SIZE(prefixes); i++) {
11154 		size_t pfx_len;
11155 
11156 		if (!str_has_pfx(prog->sec_name, prefixes[i]))
11157 			continue;
11158 
11159 		pfx_len = strlen(prefixes[i]);
11160 		/* no auto-attach case of, e.g., SEC("raw_tp") */
11161 		if (prog->sec_name[pfx_len] == '\0')
11162 			return 0;
11163 
11164 		if (prog->sec_name[pfx_len] != '/')
11165 			continue;
11166 
11167 		tp_name = prog->sec_name + pfx_len + 1;
11168 		break;
11169 	}
11170 
11171 	if (!tp_name) {
11172 		pr_warn("prog '%s': invalid section name '%s'\n",
11173 			prog->name, prog->sec_name);
11174 		return -EINVAL;
11175 	}
11176 
11177 	*link = bpf_program__attach_raw_tracepoint(prog, tp_name);
11178 	return libbpf_get_error(link);
11179 }
11180 
11181 /* Common logic for all BPF program types that attach to a btf_id */
11182 static struct bpf_link *bpf_program__attach_btf_id(const struct bpf_program *prog,
11183 						   const struct bpf_trace_opts *opts)
11184 {
11185 	LIBBPF_OPTS(bpf_link_create_opts, link_opts);
11186 	char errmsg[STRERR_BUFSIZE];
11187 	struct bpf_link *link;
11188 	int prog_fd, pfd;
11189 
11190 	if (!OPTS_VALID(opts, bpf_trace_opts))
11191 		return libbpf_err_ptr(-EINVAL);
11192 
11193 	prog_fd = bpf_program__fd(prog);
11194 	if (prog_fd < 0) {
11195 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
11196 		return libbpf_err_ptr(-EINVAL);
11197 	}
11198 
11199 	link = calloc(1, sizeof(*link));
11200 	if (!link)
11201 		return libbpf_err_ptr(-ENOMEM);
11202 	link->detach = &bpf_link__detach_fd;
11203 
11204 	/* libbpf is smart enough to redirect to BPF_RAW_TRACEPOINT_OPEN on old kernels */
11205 	link_opts.tracing.cookie = OPTS_GET(opts, cookie, 0);
11206 	pfd = bpf_link_create(prog_fd, 0, bpf_program__expected_attach_type(prog), &link_opts);
11207 	if (pfd < 0) {
11208 		pfd = -errno;
11209 		free(link);
11210 		pr_warn("prog '%s': failed to attach: %s\n",
11211 			prog->name, libbpf_strerror_r(pfd, errmsg, sizeof(errmsg)));
11212 		return libbpf_err_ptr(pfd);
11213 	}
11214 	link->fd = pfd;
11215 	return link;
11216 }
11217 
11218 struct bpf_link *bpf_program__attach_trace(const struct bpf_program *prog)
11219 {
11220 	return bpf_program__attach_btf_id(prog, NULL);
11221 }
11222 
11223 struct bpf_link *bpf_program__attach_trace_opts(const struct bpf_program *prog,
11224 						const struct bpf_trace_opts *opts)
11225 {
11226 	return bpf_program__attach_btf_id(prog, opts);
11227 }
11228 
11229 struct bpf_link *bpf_program__attach_lsm(const struct bpf_program *prog)
11230 {
11231 	return bpf_program__attach_btf_id(prog, NULL);
11232 }
11233 
11234 static int attach_trace(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11235 {
11236 	*link = bpf_program__attach_trace(prog);
11237 	return libbpf_get_error(*link);
11238 }
11239 
11240 static int attach_lsm(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11241 {
11242 	*link = bpf_program__attach_lsm(prog);
11243 	return libbpf_get_error(*link);
11244 }
11245 
11246 static struct bpf_link *
11247 bpf_program__attach_fd(const struct bpf_program *prog, int target_fd, int btf_id,
11248 		       const char *target_name)
11249 {
11250 	DECLARE_LIBBPF_OPTS(bpf_link_create_opts, opts,
11251 			    .target_btf_id = btf_id);
11252 	enum bpf_attach_type attach_type;
11253 	char errmsg[STRERR_BUFSIZE];
11254 	struct bpf_link *link;
11255 	int prog_fd, link_fd;
11256 
11257 	prog_fd = bpf_program__fd(prog);
11258 	if (prog_fd < 0) {
11259 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
11260 		return libbpf_err_ptr(-EINVAL);
11261 	}
11262 
11263 	link = calloc(1, sizeof(*link));
11264 	if (!link)
11265 		return libbpf_err_ptr(-ENOMEM);
11266 	link->detach = &bpf_link__detach_fd;
11267 
11268 	attach_type = bpf_program__expected_attach_type(prog);
11269 	link_fd = bpf_link_create(prog_fd, target_fd, attach_type, &opts);
11270 	if (link_fd < 0) {
11271 		link_fd = -errno;
11272 		free(link);
11273 		pr_warn("prog '%s': failed to attach to %s: %s\n",
11274 			prog->name, target_name,
11275 			libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
11276 		return libbpf_err_ptr(link_fd);
11277 	}
11278 	link->fd = link_fd;
11279 	return link;
11280 }
11281 
11282 struct bpf_link *
11283 bpf_program__attach_cgroup(const struct bpf_program *prog, int cgroup_fd)
11284 {
11285 	return bpf_program__attach_fd(prog, cgroup_fd, 0, "cgroup");
11286 }
11287 
11288 struct bpf_link *
11289 bpf_program__attach_netns(const struct bpf_program *prog, int netns_fd)
11290 {
11291 	return bpf_program__attach_fd(prog, netns_fd, 0, "netns");
11292 }
11293 
11294 struct bpf_link *bpf_program__attach_xdp(const struct bpf_program *prog, int ifindex)
11295 {
11296 	/* target_fd/target_ifindex use the same field in LINK_CREATE */
11297 	return bpf_program__attach_fd(prog, ifindex, 0, "xdp");
11298 }
11299 
11300 struct bpf_link *bpf_program__attach_freplace(const struct bpf_program *prog,
11301 					      int target_fd,
11302 					      const char *attach_func_name)
11303 {
11304 	int btf_id;
11305 
11306 	if (!!target_fd != !!attach_func_name) {
11307 		pr_warn("prog '%s': supply none or both of target_fd and attach_func_name\n",
11308 			prog->name);
11309 		return libbpf_err_ptr(-EINVAL);
11310 	}
11311 
11312 	if (prog->type != BPF_PROG_TYPE_EXT) {
11313 		pr_warn("prog '%s': only BPF_PROG_TYPE_EXT can attach as freplace",
11314 			prog->name);
11315 		return libbpf_err_ptr(-EINVAL);
11316 	}
11317 
11318 	if (target_fd) {
11319 		btf_id = libbpf_find_prog_btf_id(attach_func_name, target_fd);
11320 		if (btf_id < 0)
11321 			return libbpf_err_ptr(btf_id);
11322 
11323 		return bpf_program__attach_fd(prog, target_fd, btf_id, "freplace");
11324 	} else {
11325 		/* no target, so use raw_tracepoint_open for compatibility
11326 		 * with old kernels
11327 		 */
11328 		return bpf_program__attach_trace(prog);
11329 	}
11330 }
11331 
11332 struct bpf_link *
11333 bpf_program__attach_iter(const struct bpf_program *prog,
11334 			 const struct bpf_iter_attach_opts *opts)
11335 {
11336 	DECLARE_LIBBPF_OPTS(bpf_link_create_opts, link_create_opts);
11337 	char errmsg[STRERR_BUFSIZE];
11338 	struct bpf_link *link;
11339 	int prog_fd, link_fd;
11340 	__u32 target_fd = 0;
11341 
11342 	if (!OPTS_VALID(opts, bpf_iter_attach_opts))
11343 		return libbpf_err_ptr(-EINVAL);
11344 
11345 	link_create_opts.iter_info = OPTS_GET(opts, link_info, (void *)0);
11346 	link_create_opts.iter_info_len = OPTS_GET(opts, link_info_len, 0);
11347 
11348 	prog_fd = bpf_program__fd(prog);
11349 	if (prog_fd < 0) {
11350 		pr_warn("prog '%s': can't attach before loaded\n", prog->name);
11351 		return libbpf_err_ptr(-EINVAL);
11352 	}
11353 
11354 	link = calloc(1, sizeof(*link));
11355 	if (!link)
11356 		return libbpf_err_ptr(-ENOMEM);
11357 	link->detach = &bpf_link__detach_fd;
11358 
11359 	link_fd = bpf_link_create(prog_fd, target_fd, BPF_TRACE_ITER,
11360 				  &link_create_opts);
11361 	if (link_fd < 0) {
11362 		link_fd = -errno;
11363 		free(link);
11364 		pr_warn("prog '%s': failed to attach to iterator: %s\n",
11365 			prog->name, libbpf_strerror_r(link_fd, errmsg, sizeof(errmsg)));
11366 		return libbpf_err_ptr(link_fd);
11367 	}
11368 	link->fd = link_fd;
11369 	return link;
11370 }
11371 
11372 static int attach_iter(const struct bpf_program *prog, long cookie, struct bpf_link **link)
11373 {
11374 	*link = bpf_program__attach_iter(prog, NULL);
11375 	return libbpf_get_error(*link);
11376 }
11377 
11378 struct bpf_link *bpf_program__attach(const struct bpf_program *prog)
11379 {
11380 	struct bpf_link *link = NULL;
11381 	int err;
11382 
11383 	if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
11384 		return libbpf_err_ptr(-EOPNOTSUPP);
11385 
11386 	err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, &link);
11387 	if (err)
11388 		return libbpf_err_ptr(err);
11389 
11390 	/* When calling bpf_program__attach() explicitly, auto-attach support
11391 	 * is expected to work, so NULL returned link is considered an error.
11392 	 * This is different for skeleton's attach, see comment in
11393 	 * bpf_object__attach_skeleton().
11394 	 */
11395 	if (!link)
11396 		return libbpf_err_ptr(-EOPNOTSUPP);
11397 
11398 	return link;
11399 }
11400 
11401 static int bpf_link__detach_struct_ops(struct bpf_link *link)
11402 {
11403 	__u32 zero = 0;
11404 
11405 	if (bpf_map_delete_elem(link->fd, &zero))
11406 		return -errno;
11407 
11408 	return 0;
11409 }
11410 
11411 struct bpf_link *bpf_map__attach_struct_ops(const struct bpf_map *map)
11412 {
11413 	struct bpf_struct_ops *st_ops;
11414 	struct bpf_link *link;
11415 	__u32 i, zero = 0;
11416 	int err;
11417 
11418 	if (!bpf_map__is_struct_ops(map) || map->fd == -1)
11419 		return libbpf_err_ptr(-EINVAL);
11420 
11421 	link = calloc(1, sizeof(*link));
11422 	if (!link)
11423 		return libbpf_err_ptr(-EINVAL);
11424 
11425 	st_ops = map->st_ops;
11426 	for (i = 0; i < btf_vlen(st_ops->type); i++) {
11427 		struct bpf_program *prog = st_ops->progs[i];
11428 		void *kern_data;
11429 		int prog_fd;
11430 
11431 		if (!prog)
11432 			continue;
11433 
11434 		prog_fd = bpf_program__fd(prog);
11435 		kern_data = st_ops->kern_vdata + st_ops->kern_func_off[i];
11436 		*(unsigned long *)kern_data = prog_fd;
11437 	}
11438 
11439 	err = bpf_map_update_elem(map->fd, &zero, st_ops->kern_vdata, 0);
11440 	if (err) {
11441 		err = -errno;
11442 		free(link);
11443 		return libbpf_err_ptr(err);
11444 	}
11445 
11446 	link->detach = bpf_link__detach_struct_ops;
11447 	link->fd = map->fd;
11448 
11449 	return link;
11450 }
11451 
11452 typedef enum bpf_perf_event_ret (*bpf_perf_event_print_t)(struct perf_event_header *hdr,
11453 							  void *private_data);
11454 
11455 static enum bpf_perf_event_ret
11456 perf_event_read_simple(void *mmap_mem, size_t mmap_size, size_t page_size,
11457 		       void **copy_mem, size_t *copy_size,
11458 		       bpf_perf_event_print_t fn, void *private_data)
11459 {
11460 	struct perf_event_mmap_page *header = mmap_mem;
11461 	__u64 data_head = ring_buffer_read_head(header);
11462 	__u64 data_tail = header->data_tail;
11463 	void *base = ((__u8 *)header) + page_size;
11464 	int ret = LIBBPF_PERF_EVENT_CONT;
11465 	struct perf_event_header *ehdr;
11466 	size_t ehdr_size;
11467 
11468 	while (data_head != data_tail) {
11469 		ehdr = base + (data_tail & (mmap_size - 1));
11470 		ehdr_size = ehdr->size;
11471 
11472 		if (((void *)ehdr) + ehdr_size > base + mmap_size) {
11473 			void *copy_start = ehdr;
11474 			size_t len_first = base + mmap_size - copy_start;
11475 			size_t len_secnd = ehdr_size - len_first;
11476 
11477 			if (*copy_size < ehdr_size) {
11478 				free(*copy_mem);
11479 				*copy_mem = malloc(ehdr_size);
11480 				if (!*copy_mem) {
11481 					*copy_size = 0;
11482 					ret = LIBBPF_PERF_EVENT_ERROR;
11483 					break;
11484 				}
11485 				*copy_size = ehdr_size;
11486 			}
11487 
11488 			memcpy(*copy_mem, copy_start, len_first);
11489 			memcpy(*copy_mem + len_first, base, len_secnd);
11490 			ehdr = *copy_mem;
11491 		}
11492 
11493 		ret = fn(ehdr, private_data);
11494 		data_tail += ehdr_size;
11495 		if (ret != LIBBPF_PERF_EVENT_CONT)
11496 			break;
11497 	}
11498 
11499 	ring_buffer_write_tail(header, data_tail);
11500 	return libbpf_err(ret);
11501 }
11502 
11503 struct perf_buffer;
11504 
11505 struct perf_buffer_params {
11506 	struct perf_event_attr *attr;
11507 	/* if event_cb is specified, it takes precendence */
11508 	perf_buffer_event_fn event_cb;
11509 	/* sample_cb and lost_cb are higher-level common-case callbacks */
11510 	perf_buffer_sample_fn sample_cb;
11511 	perf_buffer_lost_fn lost_cb;
11512 	void *ctx;
11513 	int cpu_cnt;
11514 	int *cpus;
11515 	int *map_keys;
11516 };
11517 
11518 struct perf_cpu_buf {
11519 	struct perf_buffer *pb;
11520 	void *base; /* mmap()'ed memory */
11521 	void *buf; /* for reconstructing segmented data */
11522 	size_t buf_size;
11523 	int fd;
11524 	int cpu;
11525 	int map_key;
11526 };
11527 
11528 struct perf_buffer {
11529 	perf_buffer_event_fn event_cb;
11530 	perf_buffer_sample_fn sample_cb;
11531 	perf_buffer_lost_fn lost_cb;
11532 	void *ctx; /* passed into callbacks */
11533 
11534 	size_t page_size;
11535 	size_t mmap_size;
11536 	struct perf_cpu_buf **cpu_bufs;
11537 	struct epoll_event *events;
11538 	int cpu_cnt; /* number of allocated CPU buffers */
11539 	int epoll_fd; /* perf event FD */
11540 	int map_fd; /* BPF_MAP_TYPE_PERF_EVENT_ARRAY BPF map FD */
11541 };
11542 
11543 static void perf_buffer__free_cpu_buf(struct perf_buffer *pb,
11544 				      struct perf_cpu_buf *cpu_buf)
11545 {
11546 	if (!cpu_buf)
11547 		return;
11548 	if (cpu_buf->base &&
11549 	    munmap(cpu_buf->base, pb->mmap_size + pb->page_size))
11550 		pr_warn("failed to munmap cpu_buf #%d\n", cpu_buf->cpu);
11551 	if (cpu_buf->fd >= 0) {
11552 		ioctl(cpu_buf->fd, PERF_EVENT_IOC_DISABLE, 0);
11553 		close(cpu_buf->fd);
11554 	}
11555 	free(cpu_buf->buf);
11556 	free(cpu_buf);
11557 }
11558 
11559 void perf_buffer__free(struct perf_buffer *pb)
11560 {
11561 	int i;
11562 
11563 	if (IS_ERR_OR_NULL(pb))
11564 		return;
11565 	if (pb->cpu_bufs) {
11566 		for (i = 0; i < pb->cpu_cnt; i++) {
11567 			struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
11568 
11569 			if (!cpu_buf)
11570 				continue;
11571 
11572 			bpf_map_delete_elem(pb->map_fd, &cpu_buf->map_key);
11573 			perf_buffer__free_cpu_buf(pb, cpu_buf);
11574 		}
11575 		free(pb->cpu_bufs);
11576 	}
11577 	if (pb->epoll_fd >= 0)
11578 		close(pb->epoll_fd);
11579 	free(pb->events);
11580 	free(pb);
11581 }
11582 
11583 static struct perf_cpu_buf *
11584 perf_buffer__open_cpu_buf(struct perf_buffer *pb, struct perf_event_attr *attr,
11585 			  int cpu, int map_key)
11586 {
11587 	struct perf_cpu_buf *cpu_buf;
11588 	char msg[STRERR_BUFSIZE];
11589 	int err;
11590 
11591 	cpu_buf = calloc(1, sizeof(*cpu_buf));
11592 	if (!cpu_buf)
11593 		return ERR_PTR(-ENOMEM);
11594 
11595 	cpu_buf->pb = pb;
11596 	cpu_buf->cpu = cpu;
11597 	cpu_buf->map_key = map_key;
11598 
11599 	cpu_buf->fd = syscall(__NR_perf_event_open, attr, -1 /* pid */, cpu,
11600 			      -1, PERF_FLAG_FD_CLOEXEC);
11601 	if (cpu_buf->fd < 0) {
11602 		err = -errno;
11603 		pr_warn("failed to open perf buffer event on cpu #%d: %s\n",
11604 			cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
11605 		goto error;
11606 	}
11607 
11608 	cpu_buf->base = mmap(NULL, pb->mmap_size + pb->page_size,
11609 			     PROT_READ | PROT_WRITE, MAP_SHARED,
11610 			     cpu_buf->fd, 0);
11611 	if (cpu_buf->base == MAP_FAILED) {
11612 		cpu_buf->base = NULL;
11613 		err = -errno;
11614 		pr_warn("failed to mmap perf buffer on cpu #%d: %s\n",
11615 			cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
11616 		goto error;
11617 	}
11618 
11619 	if (ioctl(cpu_buf->fd, PERF_EVENT_IOC_ENABLE, 0) < 0) {
11620 		err = -errno;
11621 		pr_warn("failed to enable perf buffer event on cpu #%d: %s\n",
11622 			cpu, libbpf_strerror_r(err, msg, sizeof(msg)));
11623 		goto error;
11624 	}
11625 
11626 	return cpu_buf;
11627 
11628 error:
11629 	perf_buffer__free_cpu_buf(pb, cpu_buf);
11630 	return (struct perf_cpu_buf *)ERR_PTR(err);
11631 }
11632 
11633 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
11634 					      struct perf_buffer_params *p);
11635 
11636 struct perf_buffer *perf_buffer__new(int map_fd, size_t page_cnt,
11637 				     perf_buffer_sample_fn sample_cb,
11638 				     perf_buffer_lost_fn lost_cb,
11639 				     void *ctx,
11640 				     const struct perf_buffer_opts *opts)
11641 {
11642 	const size_t attr_sz = sizeof(struct perf_event_attr);
11643 	struct perf_buffer_params p = {};
11644 	struct perf_event_attr attr;
11645 
11646 	if (!OPTS_VALID(opts, perf_buffer_opts))
11647 		return libbpf_err_ptr(-EINVAL);
11648 
11649 	memset(&attr, 0, attr_sz);
11650 	attr.size = attr_sz;
11651 	attr.config = PERF_COUNT_SW_BPF_OUTPUT;
11652 	attr.type = PERF_TYPE_SOFTWARE;
11653 	attr.sample_type = PERF_SAMPLE_RAW;
11654 	attr.sample_period = 1;
11655 	attr.wakeup_events = 1;
11656 
11657 	p.attr = &attr;
11658 	p.sample_cb = sample_cb;
11659 	p.lost_cb = lost_cb;
11660 	p.ctx = ctx;
11661 
11662 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
11663 }
11664 
11665 struct perf_buffer *perf_buffer__new_raw(int map_fd, size_t page_cnt,
11666 					 struct perf_event_attr *attr,
11667 					 perf_buffer_event_fn event_cb, void *ctx,
11668 					 const struct perf_buffer_raw_opts *opts)
11669 {
11670 	struct perf_buffer_params p = {};
11671 
11672 	if (!attr)
11673 		return libbpf_err_ptr(-EINVAL);
11674 
11675 	if (!OPTS_VALID(opts, perf_buffer_raw_opts))
11676 		return libbpf_err_ptr(-EINVAL);
11677 
11678 	p.attr = attr;
11679 	p.event_cb = event_cb;
11680 	p.ctx = ctx;
11681 	p.cpu_cnt = OPTS_GET(opts, cpu_cnt, 0);
11682 	p.cpus = OPTS_GET(opts, cpus, NULL);
11683 	p.map_keys = OPTS_GET(opts, map_keys, NULL);
11684 
11685 	return libbpf_ptr(__perf_buffer__new(map_fd, page_cnt, &p));
11686 }
11687 
11688 static struct perf_buffer *__perf_buffer__new(int map_fd, size_t page_cnt,
11689 					      struct perf_buffer_params *p)
11690 {
11691 	const char *online_cpus_file = "/sys/devices/system/cpu/online";
11692 	struct bpf_map_info map;
11693 	char msg[STRERR_BUFSIZE];
11694 	struct perf_buffer *pb;
11695 	bool *online = NULL;
11696 	__u32 map_info_len;
11697 	int err, i, j, n;
11698 
11699 	if (page_cnt == 0 || (page_cnt & (page_cnt - 1))) {
11700 		pr_warn("page count should be power of two, but is %zu\n",
11701 			page_cnt);
11702 		return ERR_PTR(-EINVAL);
11703 	}
11704 
11705 	/* best-effort sanity checks */
11706 	memset(&map, 0, sizeof(map));
11707 	map_info_len = sizeof(map);
11708 	err = bpf_obj_get_info_by_fd(map_fd, &map, &map_info_len);
11709 	if (err) {
11710 		err = -errno;
11711 		/* if BPF_OBJ_GET_INFO_BY_FD is supported, will return
11712 		 * -EBADFD, -EFAULT, or -E2BIG on real error
11713 		 */
11714 		if (err != -EINVAL) {
11715 			pr_warn("failed to get map info for map FD %d: %s\n",
11716 				map_fd, libbpf_strerror_r(err, msg, sizeof(msg)));
11717 			return ERR_PTR(err);
11718 		}
11719 		pr_debug("failed to get map info for FD %d; API not supported? Ignoring...\n",
11720 			 map_fd);
11721 	} else {
11722 		if (map.type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) {
11723 			pr_warn("map '%s' should be BPF_MAP_TYPE_PERF_EVENT_ARRAY\n",
11724 				map.name);
11725 			return ERR_PTR(-EINVAL);
11726 		}
11727 	}
11728 
11729 	pb = calloc(1, sizeof(*pb));
11730 	if (!pb)
11731 		return ERR_PTR(-ENOMEM);
11732 
11733 	pb->event_cb = p->event_cb;
11734 	pb->sample_cb = p->sample_cb;
11735 	pb->lost_cb = p->lost_cb;
11736 	pb->ctx = p->ctx;
11737 
11738 	pb->page_size = getpagesize();
11739 	pb->mmap_size = pb->page_size * page_cnt;
11740 	pb->map_fd = map_fd;
11741 
11742 	pb->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
11743 	if (pb->epoll_fd < 0) {
11744 		err = -errno;
11745 		pr_warn("failed to create epoll instance: %s\n",
11746 			libbpf_strerror_r(err, msg, sizeof(msg)));
11747 		goto error;
11748 	}
11749 
11750 	if (p->cpu_cnt > 0) {
11751 		pb->cpu_cnt = p->cpu_cnt;
11752 	} else {
11753 		pb->cpu_cnt = libbpf_num_possible_cpus();
11754 		if (pb->cpu_cnt < 0) {
11755 			err = pb->cpu_cnt;
11756 			goto error;
11757 		}
11758 		if (map.max_entries && map.max_entries < pb->cpu_cnt)
11759 			pb->cpu_cnt = map.max_entries;
11760 	}
11761 
11762 	pb->events = calloc(pb->cpu_cnt, sizeof(*pb->events));
11763 	if (!pb->events) {
11764 		err = -ENOMEM;
11765 		pr_warn("failed to allocate events: out of memory\n");
11766 		goto error;
11767 	}
11768 	pb->cpu_bufs = calloc(pb->cpu_cnt, sizeof(*pb->cpu_bufs));
11769 	if (!pb->cpu_bufs) {
11770 		err = -ENOMEM;
11771 		pr_warn("failed to allocate buffers: out of memory\n");
11772 		goto error;
11773 	}
11774 
11775 	err = parse_cpu_mask_file(online_cpus_file, &online, &n);
11776 	if (err) {
11777 		pr_warn("failed to get online CPU mask: %d\n", err);
11778 		goto error;
11779 	}
11780 
11781 	for (i = 0, j = 0; i < pb->cpu_cnt; i++) {
11782 		struct perf_cpu_buf *cpu_buf;
11783 		int cpu, map_key;
11784 
11785 		cpu = p->cpu_cnt > 0 ? p->cpus[i] : i;
11786 		map_key = p->cpu_cnt > 0 ? p->map_keys[i] : i;
11787 
11788 		/* in case user didn't explicitly requested particular CPUs to
11789 		 * be attached to, skip offline/not present CPUs
11790 		 */
11791 		if (p->cpu_cnt <= 0 && (cpu >= n || !online[cpu]))
11792 			continue;
11793 
11794 		cpu_buf = perf_buffer__open_cpu_buf(pb, p->attr, cpu, map_key);
11795 		if (IS_ERR(cpu_buf)) {
11796 			err = PTR_ERR(cpu_buf);
11797 			goto error;
11798 		}
11799 
11800 		pb->cpu_bufs[j] = cpu_buf;
11801 
11802 		err = bpf_map_update_elem(pb->map_fd, &map_key,
11803 					  &cpu_buf->fd, 0);
11804 		if (err) {
11805 			err = -errno;
11806 			pr_warn("failed to set cpu #%d, key %d -> perf FD %d: %s\n",
11807 				cpu, map_key, cpu_buf->fd,
11808 				libbpf_strerror_r(err, msg, sizeof(msg)));
11809 			goto error;
11810 		}
11811 
11812 		pb->events[j].events = EPOLLIN;
11813 		pb->events[j].data.ptr = cpu_buf;
11814 		if (epoll_ctl(pb->epoll_fd, EPOLL_CTL_ADD, cpu_buf->fd,
11815 			      &pb->events[j]) < 0) {
11816 			err = -errno;
11817 			pr_warn("failed to epoll_ctl cpu #%d perf FD %d: %s\n",
11818 				cpu, cpu_buf->fd,
11819 				libbpf_strerror_r(err, msg, sizeof(msg)));
11820 			goto error;
11821 		}
11822 		j++;
11823 	}
11824 	pb->cpu_cnt = j;
11825 	free(online);
11826 
11827 	return pb;
11828 
11829 error:
11830 	free(online);
11831 	if (pb)
11832 		perf_buffer__free(pb);
11833 	return ERR_PTR(err);
11834 }
11835 
11836 struct perf_sample_raw {
11837 	struct perf_event_header header;
11838 	uint32_t size;
11839 	char data[];
11840 };
11841 
11842 struct perf_sample_lost {
11843 	struct perf_event_header header;
11844 	uint64_t id;
11845 	uint64_t lost;
11846 	uint64_t sample_id;
11847 };
11848 
11849 static enum bpf_perf_event_ret
11850 perf_buffer__process_record(struct perf_event_header *e, void *ctx)
11851 {
11852 	struct perf_cpu_buf *cpu_buf = ctx;
11853 	struct perf_buffer *pb = cpu_buf->pb;
11854 	void *data = e;
11855 
11856 	/* user wants full control over parsing perf event */
11857 	if (pb->event_cb)
11858 		return pb->event_cb(pb->ctx, cpu_buf->cpu, e);
11859 
11860 	switch (e->type) {
11861 	case PERF_RECORD_SAMPLE: {
11862 		struct perf_sample_raw *s = data;
11863 
11864 		if (pb->sample_cb)
11865 			pb->sample_cb(pb->ctx, cpu_buf->cpu, s->data, s->size);
11866 		break;
11867 	}
11868 	case PERF_RECORD_LOST: {
11869 		struct perf_sample_lost *s = data;
11870 
11871 		if (pb->lost_cb)
11872 			pb->lost_cb(pb->ctx, cpu_buf->cpu, s->lost);
11873 		break;
11874 	}
11875 	default:
11876 		pr_warn("unknown perf sample type %d\n", e->type);
11877 		return LIBBPF_PERF_EVENT_ERROR;
11878 	}
11879 	return LIBBPF_PERF_EVENT_CONT;
11880 }
11881 
11882 static int perf_buffer__process_records(struct perf_buffer *pb,
11883 					struct perf_cpu_buf *cpu_buf)
11884 {
11885 	enum bpf_perf_event_ret ret;
11886 
11887 	ret = perf_event_read_simple(cpu_buf->base, pb->mmap_size,
11888 				     pb->page_size, &cpu_buf->buf,
11889 				     &cpu_buf->buf_size,
11890 				     perf_buffer__process_record, cpu_buf);
11891 	if (ret != LIBBPF_PERF_EVENT_CONT)
11892 		return ret;
11893 	return 0;
11894 }
11895 
11896 int perf_buffer__epoll_fd(const struct perf_buffer *pb)
11897 {
11898 	return pb->epoll_fd;
11899 }
11900 
11901 int perf_buffer__poll(struct perf_buffer *pb, int timeout_ms)
11902 {
11903 	int i, cnt, err;
11904 
11905 	cnt = epoll_wait(pb->epoll_fd, pb->events, pb->cpu_cnt, timeout_ms);
11906 	if (cnt < 0)
11907 		return -errno;
11908 
11909 	for (i = 0; i < cnt; i++) {
11910 		struct perf_cpu_buf *cpu_buf = pb->events[i].data.ptr;
11911 
11912 		err = perf_buffer__process_records(pb, cpu_buf);
11913 		if (err) {
11914 			pr_warn("error while processing records: %d\n", err);
11915 			return libbpf_err(err);
11916 		}
11917 	}
11918 	return cnt;
11919 }
11920 
11921 /* Return number of PERF_EVENT_ARRAY map slots set up by this perf_buffer
11922  * manager.
11923  */
11924 size_t perf_buffer__buffer_cnt(const struct perf_buffer *pb)
11925 {
11926 	return pb->cpu_cnt;
11927 }
11928 
11929 /*
11930  * Return perf_event FD of a ring buffer in *buf_idx* slot of
11931  * PERF_EVENT_ARRAY BPF map. This FD can be polled for new data using
11932  * select()/poll()/epoll() Linux syscalls.
11933  */
11934 int perf_buffer__buffer_fd(const struct perf_buffer *pb, size_t buf_idx)
11935 {
11936 	struct perf_cpu_buf *cpu_buf;
11937 
11938 	if (buf_idx >= pb->cpu_cnt)
11939 		return libbpf_err(-EINVAL);
11940 
11941 	cpu_buf = pb->cpu_bufs[buf_idx];
11942 	if (!cpu_buf)
11943 		return libbpf_err(-ENOENT);
11944 
11945 	return cpu_buf->fd;
11946 }
11947 
11948 int perf_buffer__buffer(struct perf_buffer *pb, int buf_idx, void **buf, size_t *buf_size)
11949 {
11950 	struct perf_cpu_buf *cpu_buf;
11951 
11952 	if (buf_idx >= pb->cpu_cnt)
11953 		return libbpf_err(-EINVAL);
11954 
11955 	cpu_buf = pb->cpu_bufs[buf_idx];
11956 	if (!cpu_buf)
11957 		return libbpf_err(-ENOENT);
11958 
11959 	*buf = cpu_buf->base;
11960 	*buf_size = pb->mmap_size;
11961 	return 0;
11962 }
11963 
11964 /*
11965  * Consume data from perf ring buffer corresponding to slot *buf_idx* in
11966  * PERF_EVENT_ARRAY BPF map without waiting/polling. If there is no data to
11967  * consume, do nothing and return success.
11968  * Returns:
11969  *   - 0 on success;
11970  *   - <0 on failure.
11971  */
11972 int perf_buffer__consume_buffer(struct perf_buffer *pb, size_t buf_idx)
11973 {
11974 	struct perf_cpu_buf *cpu_buf;
11975 
11976 	if (buf_idx >= pb->cpu_cnt)
11977 		return libbpf_err(-EINVAL);
11978 
11979 	cpu_buf = pb->cpu_bufs[buf_idx];
11980 	if (!cpu_buf)
11981 		return libbpf_err(-ENOENT);
11982 
11983 	return perf_buffer__process_records(pb, cpu_buf);
11984 }
11985 
11986 int perf_buffer__consume(struct perf_buffer *pb)
11987 {
11988 	int i, err;
11989 
11990 	for (i = 0; i < pb->cpu_cnt; i++) {
11991 		struct perf_cpu_buf *cpu_buf = pb->cpu_bufs[i];
11992 
11993 		if (!cpu_buf)
11994 			continue;
11995 
11996 		err = perf_buffer__process_records(pb, cpu_buf);
11997 		if (err) {
11998 			pr_warn("perf_buffer: failed to process records in buffer #%d: %d\n", i, err);
11999 			return libbpf_err(err);
12000 		}
12001 	}
12002 	return 0;
12003 }
12004 
12005 int bpf_program__set_attach_target(struct bpf_program *prog,
12006 				   int attach_prog_fd,
12007 				   const char *attach_func_name)
12008 {
12009 	int btf_obj_fd = 0, btf_id = 0, err;
12010 
12011 	if (!prog || attach_prog_fd < 0)
12012 		return libbpf_err(-EINVAL);
12013 
12014 	if (prog->obj->loaded)
12015 		return libbpf_err(-EINVAL);
12016 
12017 	if (attach_prog_fd && !attach_func_name) {
12018 		/* remember attach_prog_fd and let bpf_program__load() find
12019 		 * BTF ID during the program load
12020 		 */
12021 		prog->attach_prog_fd = attach_prog_fd;
12022 		return 0;
12023 	}
12024 
12025 	if (attach_prog_fd) {
12026 		btf_id = libbpf_find_prog_btf_id(attach_func_name,
12027 						 attach_prog_fd);
12028 		if (btf_id < 0)
12029 			return libbpf_err(btf_id);
12030 	} else {
12031 		if (!attach_func_name)
12032 			return libbpf_err(-EINVAL);
12033 
12034 		/* load btf_vmlinux, if not yet */
12035 		err = bpf_object__load_vmlinux_btf(prog->obj, true);
12036 		if (err)
12037 			return libbpf_err(err);
12038 		err = find_kernel_btf_id(prog->obj, attach_func_name,
12039 					 prog->expected_attach_type,
12040 					 &btf_obj_fd, &btf_id);
12041 		if (err)
12042 			return libbpf_err(err);
12043 	}
12044 
12045 	prog->attach_btf_id = btf_id;
12046 	prog->attach_btf_obj_fd = btf_obj_fd;
12047 	prog->attach_prog_fd = attach_prog_fd;
12048 	return 0;
12049 }
12050 
12051 int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz)
12052 {
12053 	int err = 0, n, len, start, end = -1;
12054 	bool *tmp;
12055 
12056 	*mask = NULL;
12057 	*mask_sz = 0;
12058 
12059 	/* Each sub string separated by ',' has format \d+-\d+ or \d+ */
12060 	while (*s) {
12061 		if (*s == ',' || *s == '\n') {
12062 			s++;
12063 			continue;
12064 		}
12065 		n = sscanf(s, "%d%n-%d%n", &start, &len, &end, &len);
12066 		if (n <= 0 || n > 2) {
12067 			pr_warn("Failed to get CPU range %s: %d\n", s, n);
12068 			err = -EINVAL;
12069 			goto cleanup;
12070 		} else if (n == 1) {
12071 			end = start;
12072 		}
12073 		if (start < 0 || start > end) {
12074 			pr_warn("Invalid CPU range [%d,%d] in %s\n",
12075 				start, end, s);
12076 			err = -EINVAL;
12077 			goto cleanup;
12078 		}
12079 		tmp = realloc(*mask, end + 1);
12080 		if (!tmp) {
12081 			err = -ENOMEM;
12082 			goto cleanup;
12083 		}
12084 		*mask = tmp;
12085 		memset(tmp + *mask_sz, 0, start - *mask_sz);
12086 		memset(tmp + start, 1, end - start + 1);
12087 		*mask_sz = end + 1;
12088 		s += len;
12089 	}
12090 	if (!*mask_sz) {
12091 		pr_warn("Empty CPU range\n");
12092 		return -EINVAL;
12093 	}
12094 	return 0;
12095 cleanup:
12096 	free(*mask);
12097 	*mask = NULL;
12098 	return err;
12099 }
12100 
12101 int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz)
12102 {
12103 	int fd, err = 0, len;
12104 	char buf[128];
12105 
12106 	fd = open(fcpu, O_RDONLY | O_CLOEXEC);
12107 	if (fd < 0) {
12108 		err = -errno;
12109 		pr_warn("Failed to open cpu mask file %s: %d\n", fcpu, err);
12110 		return err;
12111 	}
12112 	len = read(fd, buf, sizeof(buf));
12113 	close(fd);
12114 	if (len <= 0) {
12115 		err = len ? -errno : -EINVAL;
12116 		pr_warn("Failed to read cpu mask from %s: %d\n", fcpu, err);
12117 		return err;
12118 	}
12119 	if (len >= sizeof(buf)) {
12120 		pr_warn("CPU mask is too big in file %s\n", fcpu);
12121 		return -E2BIG;
12122 	}
12123 	buf[len] = '\0';
12124 
12125 	return parse_cpu_mask_str(buf, mask, mask_sz);
12126 }
12127 
12128 int libbpf_num_possible_cpus(void)
12129 {
12130 	static const char *fcpu = "/sys/devices/system/cpu/possible";
12131 	static int cpus;
12132 	int err, n, i, tmp_cpus;
12133 	bool *mask;
12134 
12135 	tmp_cpus = READ_ONCE(cpus);
12136 	if (tmp_cpus > 0)
12137 		return tmp_cpus;
12138 
12139 	err = parse_cpu_mask_file(fcpu, &mask, &n);
12140 	if (err)
12141 		return libbpf_err(err);
12142 
12143 	tmp_cpus = 0;
12144 	for (i = 0; i < n; i++) {
12145 		if (mask[i])
12146 			tmp_cpus++;
12147 	}
12148 	free(mask);
12149 
12150 	WRITE_ONCE(cpus, tmp_cpus);
12151 	return tmp_cpus;
12152 }
12153 
12154 static int populate_skeleton_maps(const struct bpf_object *obj,
12155 				  struct bpf_map_skeleton *maps,
12156 				  size_t map_cnt)
12157 {
12158 	int i;
12159 
12160 	for (i = 0; i < map_cnt; i++) {
12161 		struct bpf_map **map = maps[i].map;
12162 		const char *name = maps[i].name;
12163 		void **mmaped = maps[i].mmaped;
12164 
12165 		*map = bpf_object__find_map_by_name(obj, name);
12166 		if (!*map) {
12167 			pr_warn("failed to find skeleton map '%s'\n", name);
12168 			return -ESRCH;
12169 		}
12170 
12171 		/* externs shouldn't be pre-setup from user code */
12172 		if (mmaped && (*map)->libbpf_type != LIBBPF_MAP_KCONFIG)
12173 			*mmaped = (*map)->mmaped;
12174 	}
12175 	return 0;
12176 }
12177 
12178 static int populate_skeleton_progs(const struct bpf_object *obj,
12179 				   struct bpf_prog_skeleton *progs,
12180 				   size_t prog_cnt)
12181 {
12182 	int i;
12183 
12184 	for (i = 0; i < prog_cnt; i++) {
12185 		struct bpf_program **prog = progs[i].prog;
12186 		const char *name = progs[i].name;
12187 
12188 		*prog = bpf_object__find_program_by_name(obj, name);
12189 		if (!*prog) {
12190 			pr_warn("failed to find skeleton program '%s'\n", name);
12191 			return -ESRCH;
12192 		}
12193 	}
12194 	return 0;
12195 }
12196 
12197 int bpf_object__open_skeleton(struct bpf_object_skeleton *s,
12198 			      const struct bpf_object_open_opts *opts)
12199 {
12200 	DECLARE_LIBBPF_OPTS(bpf_object_open_opts, skel_opts,
12201 		.object_name = s->name,
12202 	);
12203 	struct bpf_object *obj;
12204 	int err;
12205 
12206 	/* Attempt to preserve opts->object_name, unless overriden by user
12207 	 * explicitly. Overwriting object name for skeletons is discouraged,
12208 	 * as it breaks global data maps, because they contain object name
12209 	 * prefix as their own map name prefix. When skeleton is generated,
12210 	 * bpftool is making an assumption that this name will stay the same.
12211 	 */
12212 	if (opts) {
12213 		memcpy(&skel_opts, opts, sizeof(*opts));
12214 		if (!opts->object_name)
12215 			skel_opts.object_name = s->name;
12216 	}
12217 
12218 	obj = bpf_object__open_mem(s->data, s->data_sz, &skel_opts);
12219 	err = libbpf_get_error(obj);
12220 	if (err) {
12221 		pr_warn("failed to initialize skeleton BPF object '%s': %d\n",
12222 			s->name, err);
12223 		return libbpf_err(err);
12224 	}
12225 
12226 	*s->obj = obj;
12227 	err = populate_skeleton_maps(obj, s->maps, s->map_cnt);
12228 	if (err) {
12229 		pr_warn("failed to populate skeleton maps for '%s': %d\n", s->name, err);
12230 		return libbpf_err(err);
12231 	}
12232 
12233 	err = populate_skeleton_progs(obj, s->progs, s->prog_cnt);
12234 	if (err) {
12235 		pr_warn("failed to populate skeleton progs for '%s': %d\n", s->name, err);
12236 		return libbpf_err(err);
12237 	}
12238 
12239 	return 0;
12240 }
12241 
12242 int bpf_object__open_subskeleton(struct bpf_object_subskeleton *s)
12243 {
12244 	int err, len, var_idx, i;
12245 	const char *var_name;
12246 	const struct bpf_map *map;
12247 	struct btf *btf;
12248 	__u32 map_type_id;
12249 	const struct btf_type *map_type, *var_type;
12250 	const struct bpf_var_skeleton *var_skel;
12251 	struct btf_var_secinfo *var;
12252 
12253 	if (!s->obj)
12254 		return libbpf_err(-EINVAL);
12255 
12256 	btf = bpf_object__btf(s->obj);
12257 	if (!btf) {
12258 		pr_warn("subskeletons require BTF at runtime (object %s)\n",
12259 		        bpf_object__name(s->obj));
12260 		return libbpf_err(-errno);
12261 	}
12262 
12263 	err = populate_skeleton_maps(s->obj, s->maps, s->map_cnt);
12264 	if (err) {
12265 		pr_warn("failed to populate subskeleton maps: %d\n", err);
12266 		return libbpf_err(err);
12267 	}
12268 
12269 	err = populate_skeleton_progs(s->obj, s->progs, s->prog_cnt);
12270 	if (err) {
12271 		pr_warn("failed to populate subskeleton maps: %d\n", err);
12272 		return libbpf_err(err);
12273 	}
12274 
12275 	for (var_idx = 0; var_idx < s->var_cnt; var_idx++) {
12276 		var_skel = &s->vars[var_idx];
12277 		map = *var_skel->map;
12278 		map_type_id = bpf_map__btf_value_type_id(map);
12279 		map_type = btf__type_by_id(btf, map_type_id);
12280 
12281 		if (!btf_is_datasec(map_type)) {
12282 			pr_warn("type for map '%1$s' is not a datasec: %2$s",
12283 				bpf_map__name(map),
12284 				__btf_kind_str(btf_kind(map_type)));
12285 			return libbpf_err(-EINVAL);
12286 		}
12287 
12288 		len = btf_vlen(map_type);
12289 		var = btf_var_secinfos(map_type);
12290 		for (i = 0; i < len; i++, var++) {
12291 			var_type = btf__type_by_id(btf, var->type);
12292 			var_name = btf__name_by_offset(btf, var_type->name_off);
12293 			if (strcmp(var_name, var_skel->name) == 0) {
12294 				*var_skel->addr = map->mmaped + var->offset;
12295 				break;
12296 			}
12297 		}
12298 	}
12299 	return 0;
12300 }
12301 
12302 void bpf_object__destroy_subskeleton(struct bpf_object_subskeleton *s)
12303 {
12304 	if (!s)
12305 		return;
12306 	free(s->maps);
12307 	free(s->progs);
12308 	free(s->vars);
12309 	free(s);
12310 }
12311 
12312 int bpf_object__load_skeleton(struct bpf_object_skeleton *s)
12313 {
12314 	int i, err;
12315 
12316 	err = bpf_object__load(*s->obj);
12317 	if (err) {
12318 		pr_warn("failed to load BPF skeleton '%s': %d\n", s->name, err);
12319 		return libbpf_err(err);
12320 	}
12321 
12322 	for (i = 0; i < s->map_cnt; i++) {
12323 		struct bpf_map *map = *s->maps[i].map;
12324 		size_t mmap_sz = bpf_map_mmap_sz(map);
12325 		int prot, map_fd = bpf_map__fd(map);
12326 		void **mmaped = s->maps[i].mmaped;
12327 
12328 		if (!mmaped)
12329 			continue;
12330 
12331 		if (!(map->def.map_flags & BPF_F_MMAPABLE)) {
12332 			*mmaped = NULL;
12333 			continue;
12334 		}
12335 
12336 		if (map->def.map_flags & BPF_F_RDONLY_PROG)
12337 			prot = PROT_READ;
12338 		else
12339 			prot = PROT_READ | PROT_WRITE;
12340 
12341 		/* Remap anonymous mmap()-ed "map initialization image" as
12342 		 * a BPF map-backed mmap()-ed memory, but preserving the same
12343 		 * memory address. This will cause kernel to change process'
12344 		 * page table to point to a different piece of kernel memory,
12345 		 * but from userspace point of view memory address (and its
12346 		 * contents, being identical at this point) will stay the
12347 		 * same. This mapping will be released by bpf_object__close()
12348 		 * as per normal clean up procedure, so we don't need to worry
12349 		 * about it from skeleton's clean up perspective.
12350 		 */
12351 		*mmaped = mmap(map->mmaped, mmap_sz, prot,
12352 				MAP_SHARED | MAP_FIXED, map_fd, 0);
12353 		if (*mmaped == MAP_FAILED) {
12354 			err = -errno;
12355 			*mmaped = NULL;
12356 			pr_warn("failed to re-mmap() map '%s': %d\n",
12357 				 bpf_map__name(map), err);
12358 			return libbpf_err(err);
12359 		}
12360 	}
12361 
12362 	return 0;
12363 }
12364 
12365 int bpf_object__attach_skeleton(struct bpf_object_skeleton *s)
12366 {
12367 	int i, err;
12368 
12369 	for (i = 0; i < s->prog_cnt; i++) {
12370 		struct bpf_program *prog = *s->progs[i].prog;
12371 		struct bpf_link **link = s->progs[i].link;
12372 
12373 		if (!prog->autoload || !prog->autoattach)
12374 			continue;
12375 
12376 		/* auto-attaching not supported for this program */
12377 		if (!prog->sec_def || !prog->sec_def->prog_attach_fn)
12378 			continue;
12379 
12380 		/* if user already set the link manually, don't attempt auto-attach */
12381 		if (*link)
12382 			continue;
12383 
12384 		err = prog->sec_def->prog_attach_fn(prog, prog->sec_def->cookie, link);
12385 		if (err) {
12386 			pr_warn("prog '%s': failed to auto-attach: %d\n",
12387 				bpf_program__name(prog), err);
12388 			return libbpf_err(err);
12389 		}
12390 
12391 		/* It's possible that for some SEC() definitions auto-attach
12392 		 * is supported in some cases (e.g., if definition completely
12393 		 * specifies target information), but is not in other cases.
12394 		 * SEC("uprobe") is one such case. If user specified target
12395 		 * binary and function name, such BPF program can be
12396 		 * auto-attached. But if not, it shouldn't trigger skeleton's
12397 		 * attach to fail. It should just be skipped.
12398 		 * attach_fn signals such case with returning 0 (no error) and
12399 		 * setting link to NULL.
12400 		 */
12401 	}
12402 
12403 	return 0;
12404 }
12405 
12406 void bpf_object__detach_skeleton(struct bpf_object_skeleton *s)
12407 {
12408 	int i;
12409 
12410 	for (i = 0; i < s->prog_cnt; i++) {
12411 		struct bpf_link **link = s->progs[i].link;
12412 
12413 		bpf_link__destroy(*link);
12414 		*link = NULL;
12415 	}
12416 }
12417 
12418 void bpf_object__destroy_skeleton(struct bpf_object_skeleton *s)
12419 {
12420 	if (!s)
12421 		return;
12422 
12423 	if (s->progs)
12424 		bpf_object__detach_skeleton(s);
12425 	if (s->obj)
12426 		bpf_object__close(*s->obj);
12427 	free(s->maps);
12428 	free(s->progs);
12429 	free(s);
12430 }
12431